-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlean_trimming.h
More file actions
2150 lines (1566 loc) · 80.4 KB
/
lean_trimming.h
File metadata and controls
2150 lines (1566 loc) · 80.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Header guard
#ifndef LEAN_TRIMMING_H
#define LEAN_TRIMMING_H
// Header files
using namespace std;
// Configurable constants
// Lean trimming number of edges per step one work item
#define LEAN_TRIMMING_NUMBER_OF_EDGES_PER_STEP_ONE_WORK_ITEM min(static_cast<uint64_t>(64), NUMBER_OF_EDGES)
// Constants
// Lean trimming required RAM bytes
#define LEAN_TRIMMING_REQUIRED_RAM_BYTES (NUMBER_OF_EDGES / BITS_IN_A_BYTE * 3)
// Function prototypes
// Check if using an Apple device and not using OpenCL
#if defined __APPLE__ && !defined USE_OPENCL
// Create lean trimming context
static inline MTL::Device *createLeanTrimmingContext(const unsigned int deviceIndex) noexcept;
// Perform lean trimming loop
static inline bool performLeanTrimmingLoop(MTL::Device *device) noexcept;
// Otherwise
#else
// Create lean trimming context
static inline cl_context createLeanTrimmingContext(const cl_platform_id platforms[], const cl_uint numberOfPlatforms, const unsigned int deviceIndex) noexcept;
// Perform lean trimming loop
static inline bool performLeanTrimmingLoop(const cl_context context) noexcept;
#endif
// Supporting function implementation
// Check if using an Apple device and not using OpenCL
#if defined __APPLE__ && !defined USE_OPENCL
// Create lean trimming context
MTL::Device *createLeanTrimmingContext(const unsigned int deviceIndex) noexcept {
// Set index to zero
unsigned int index = 0;
// Check if getting all devices failed
unique_ptr<NS::Array, void(*)(NS::Array *)> devices(MTL::CopyAllDevices(), [](NS::Array *devices) noexcept {
// Free devices
devices->release();
});
if(!devices) {
// Set devices to include just the default device
devices = unique_ptr<NS::Array, void(*)(NS::Array *)>(NS::Array::alloc()->init((const NS::Object *[]){
// Default device
MTL::CreateSystemDefaultDevice()
}, 1), [](NS::Array *devices) noexcept {
// Free devices
devices->release();
});
}
// Check if getting devices was successful
if(devices) {
// Go through all devices
for(NS::UInteger i = 0; i < devices->count(); ++i) {
// Get device
MTL::Device *device = reinterpret_cast<MTL::Device *>(devices->object(i));
// Check if device supports the Metal version
if(device && device->supportsFamily(MTL::GPUFamilyMetal3)) {
// Check if device's name exists
const NS::String *name = device->name();
if(name) {
// Check if name's UTF-8 string exists
const char *utf8String = name->utf8String();
if(utf8String) {
// Check if device index isn't specified or index is for the specified device
if(deviceIndex == ALL_DEVICES || ++index == deviceIndex) {
// Check if device's memory size is large enough
if(device->recommendedMaxWorkingSetSize() >= LEAN_TRIMMING_REQUIRED_RAM_BYTES) {
// Check if device index is specified
if(deviceIndex != ALL_DEVICES) {
// Display message
cout << "Using the GPU for lean trimming." << endl;
}
// Otherwise
else {
// Display message
cout << "Using " << utf8String << " for lean trimming." << endl;
}
// Don't free device when devices is freed
device->retain();
// Return device
return device;
}
}
}
}
}
}
}
// Return nothing
return nullptr;
}
// Otherwise
#else
// Create lean trimming context
cl_context createLeanTrimmingContext(const cl_platform_id platforms[], const cl_uint numberOfPlatforms, const unsigned int deviceIndex) noexcept {
// Set index to zero
unsigned int index = 0;
// Go through all platforms
for(cl_uint i = 0; i < numberOfPlatforms; ++i) {
// Check if getting platform's number of devices was successful and devices exist
cl_uint numberOfDevices;
if(clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_GPU, 0, nullptr, &numberOfDevices) == CL_SUCCESS && numberOfDevices) {
// Check if getting platform's devices was successful
cl_device_id devices[numberOfDevices];
if(clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_GPU, numberOfDevices, devices, nullptr) == CL_SUCCESS) {
// Go through all of the platform's devices
for(cl_uint j = 0; j < numberOfDevices; ++j) {
// Check if getting device's availability and profile size was successful, device is available, and profile exists
cl_bool isAvailable;
size_t profileSize;
if(clGetDeviceInfo(devices[j], CL_DEVICE_AVAILABLE, sizeof(isAvailable), &isAvailable, nullptr) == CL_SUCCESS && clGetDeviceInfo(devices[j], CL_DEVICE_PROFILE, 0, nullptr, &profileSize) == CL_SUCCESS && isAvailable == CL_TRUE && profileSize) {
// Check if getting device's profile and OpenCL version size was successful, profile is full profile, and OpenCL version exists
char profile[profileSize];
size_t openClVersionSize;
if(clGetDeviceInfo(devices[j], CL_DEVICE_PROFILE, profileSize, profile, nullptr) == CL_SUCCESS && clGetDeviceInfo(devices[j], CL_DEVICE_OPENCL_C_VERSION, 0, nullptr, &openClVersionSize) == CL_SUCCESS && !strcmp(profile, "FULL_PROFILE") && openClVersionSize) {
// Check if getting device's OpenCL version, is little endian, and name size was successful, OpenCL version is compatible, device is little endian, and its name exists
char openClVersion[openClVersionSize];
cl_bool isLittleEndian;
size_t nameSize;
if(clGetDeviceInfo(devices[j], CL_DEVICE_OPENCL_C_VERSION, openClVersionSize, openClVersion, nullptr) == CL_SUCCESS && clGetDeviceInfo(devices[j], CL_DEVICE_ENDIAN_LITTLE, sizeof(isLittleEndian), &isLittleEndian, nullptr) == CL_SUCCESS && clGetDeviceInfo(devices[j], CL_DEVICE_NAME, 0, nullptr, &nameSize) == CL_SUCCESS && !strncmp(openClVersion, "OpenCL C ", sizeof("OpenCL C ") - sizeof('\0')) && strtod(&openClVersion[sizeof("OpenCL C ") - sizeof('\0')], nullptr) >= 1.2 && isLittleEndian == CL_TRUE && nameSize) {
// Check if getting device's name was successful
char name[nameSize];
if(clGetDeviceInfo(devices[j], CL_DEVICE_NAME, nameSize, name, nullptr) == CL_SUCCESS) {
// Check if device index isn't specified or index is for the specified device
if(deviceIndex == ALL_DEVICES || ++index == deviceIndex) {
// Check if getting device's memory size was successful and memory size is large enough
cl_ulong memorySize;
if(clGetDeviceInfo(devices[j], CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(memorySize), &memorySize, nullptr) == CL_SUCCESS && memorySize >= LEAN_TRIMMING_REQUIRED_RAM_BYTES) {
// Check if creating context for the device was successful
cl_context context = clCreateContext(unmove((const cl_context_properties[]){CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>(platforms[i]), 0}), 1, &devices[j], nullptr, nullptr, nullptr);
if(context) {
// Check if device index is specified
if(deviceIndex != ALL_DEVICES) {
// Display message
cout << "Using the GPU for lean trimming." << endl;
}
// Otherwise
else {
// Display message
cout << "Using " << name << " for lean trimming." << endl;
}
// Return context
return context;
}
}
}
}
}
}
}
}
}
}
}
// Return nothing
return nullptr;
}
#endif
// Check if using an Apple device and not using OpenCL
#if defined __APPLE__ && !defined USE_OPENCL
// Perform lean trimming loop
bool performLeanTrimmingLoop(MTL::Device *device) noexcept {
// Check if creating preprocessor macros failed
const unique_ptr<NS::Dictionary, void(*)(NS::Dictionary *)> preprocessorMacros(NS::Dictionary::alloc()->init((const NS::Object *[]){
// Edge bits value
MTLSTR(TO_STRING(EDGE_BITS)),
// Number of edges per step one work item value
unique_ptr<NS::Number, void(*)(NS::Number *)>(NS::Number::alloc()->init(LEAN_TRIMMING_NUMBER_OF_EDGES_PER_STEP_ONE_WORK_ITEM), [](NS::Number *numberOfEdgesPerStepOneWorkItemValue) noexcept {
// Free number of edges per step one work item value
numberOfEdgesPerStepOneWorkItemValue->release();
}).get(),
}, (const NS::Object *[]){
// Edge bits key
MTLSTR("EDGE_BITS"),
// Number of edges per step one work item key
MTLSTR("NUMBER_OF_EDGES_PER_STEP_ONE_WORK_ITEM")
}, 2), [](NS::Dictionary *preprocessorMacros) noexcept {
// Free preprocessor macros
preprocessorMacros->release();
});
if(!preprocessorMacros) {
// Display message
cout << "Creating preprocessor macros for the kernels failed." << endl;
// Return false
return false;
}
// Check if creating compile options for the kernels failed
const unique_ptr<MTL::CompileOptions, void(*)(MTL::CompileOptions *)> compileOptions(MTL::CompileOptions::alloc()->init(), [](MTL::CompileOptions *compileOptions) noexcept {
// Free compile options
compileOptions->release();
});
if(!compileOptions) {
// Display message
cout << "Creating compile options for the kernels failed." << endl;
// Return false
return false;
}
// Configure compiler options
compileOptions->setPreprocessorMacros(preprocessorMacros.get());
compileOptions->setLanguageVersion(METAL_TARGET_VERSION);
// Check if creating library for the device failed
const NS::String *source = (
#include "./lean_trimming.metal"
);
NS::Error *createLibraryError;
const unique_ptr<MTL::Library, void(*)(MTL::Library *)> library(device->newLibrary(source, compileOptions.get(), &createLibraryError), [](MTL::Library *library) noexcept {
// Free library
library->release();
});
if(!library) {
// Display message
cout << "Creating library for the GPU failed." << endl;
// Check if an error exists
if(createLibraryError) {
// Check if error's localized description exists
const NS::String *localizedDescription = createLibraryError->localizedDescription();
if(localizedDescription) {
// Check if localized description's UTF-8 string exists
const char *utf8String = localizedDescription->utf8String();
if(utf8String) {
// Display message
cout << utf8String << endl;
}
}
}
// Return false
return false;
}
// Check if getting kernels from the library failed
const unique_ptr<MTL::Function, void(*)(MTL::Function *)> stepOneKernel(library->newFunction(MTLSTR("trimEdgesStepOne")), [](MTL::Function *stepOneKernel) noexcept {
// Free step one kernel
stepOneKernel->release();
});
const unique_ptr<MTL::Function, void(*)(MTL::Function *)> stepTwoKernel(library->newFunction(MTLSTR("trimEdgesStepTwo")), [](MTL::Function *stepTwoKernel) noexcept {
// Free step two kernel
stepTwoKernel->release();
});
const unique_ptr<MTL::Function, void(*)(MTL::Function *)> stepThreeKernel(library->newFunction(MTLSTR("trimEdgesStepThree")), [](MTL::Function *stepThreeKernel) noexcept {
// Free step three kernel
stepThreeKernel->release();
});
const unique_ptr<MTL::Function, void(*)(MTL::Function *)> stepFourKernel(library->newFunction(MTLSTR("trimEdgesStepFour")), [](MTL::Function *stepFourKernel) noexcept {
// Free step four kernel
stepFourKernel->release();
});
const unique_ptr<MTL::Function, void(*)(MTL::Function *)> clearNodesBitmapKernel(library->newFunction(MTLSTR("clearNodesBitmap")), [](MTL::Function *clearNodesBitmapKernel) noexcept {
// Free clear nodes bitmap kernel
clearNodesBitmapKernel->release();
});
if(!stepOneKernel || !stepTwoKernel || !stepThreeKernel || !stepFourKernel || !clearNodesBitmapKernel) {
// Display message
cout << "Getting kernels from the library failed." << endl;
// Return false
return false;
}
// Check if creating pipelines for the device failed
NS::Error *createPipelineOneError;
unique_ptr<MTL::ComputePipelineState, void(*)(MTL::ComputePipelineState *)> stepOnePipeline(device->newComputePipelineState(stepOneKernel.get(), &createPipelineOneError), [](MTL::ComputePipelineState *stepOnePipeline) noexcept {
// Free step one pipeline
stepOnePipeline->release();
});
NS::Error *createPipelineTwoError;
unique_ptr<MTL::ComputePipelineState, void(*)(MTL::ComputePipelineState *)> stepTwoPipeline(device->newComputePipelineState(stepTwoKernel.get(), &createPipelineTwoError), [](MTL::ComputePipelineState *stepTwoPipeline) noexcept {
// Free step two pipeline
stepTwoPipeline->release();
});
NS::Error *createPipelineThreeError;
unique_ptr<MTL::ComputePipelineState, void(*)(MTL::ComputePipelineState *)> stepThreePipeline(device->newComputePipelineState(stepThreeKernel.get(), &createPipelineThreeError), [](MTL::ComputePipelineState *stepThreePipeline) noexcept {
// Free step three pipeline
stepThreePipeline->release();
});
NS::Error *createPipelineFourError;
unique_ptr<MTL::ComputePipelineState, void(*)(MTL::ComputePipelineState *)> stepFourPipeline(device->newComputePipelineState(stepFourKernel.get(), &createPipelineFourError), [](MTL::ComputePipelineState *stepFourPipeline) noexcept {
// Free step four pipeline
stepFourPipeline->release();
});
NS::Error *createPipelineClearNodesBitmapError;
unique_ptr<MTL::ComputePipelineState, void(*)(MTL::ComputePipelineState *)> clearNodesBitmapPipeline(device->newComputePipelineState(clearNodesBitmapKernel.get(), &createPipelineClearNodesBitmapError), [](MTL::ComputePipelineState *clearNodesBitmapPipeline) noexcept {
// Free clear nodes bitmap pipeline
clearNodesBitmapPipeline->release();
});
if(!stepOnePipeline || !stepTwoPipeline || !stepThreePipeline || !stepFourPipeline || !clearNodesBitmapPipeline) {
// Display message
cout << "Creating pipelines for the GPU failed." << endl;
// Check if creating pipeline one failed and an error exists
if(!stepOnePipeline && createPipelineOneError) {
// Check if error's localized description exists
const NS::String *localizedDescription = createPipelineOneError->localizedDescription();
if(localizedDescription) {
// Check if localized description's UTF-8 string exists
const char *utf8String = localizedDescription->utf8String();
if(utf8String) {
// Display message
cout << utf8String << endl;
}
}
}
// Check if creating pipeline two failed and an error exists
if(!stepTwoPipeline && createPipelineTwoError) {
// Check if error's localized description exists
const NS::String *localizedDescription = createPipelineTwoError->localizedDescription();
if(localizedDescription) {
// Check if localized description's UTF-8 string exists
const char *utf8String = localizedDescription->utf8String();
if(utf8String) {
// Display message
cout << utf8String << endl;
}
}
}
// Check if creating pipeline three failed and an error exists
if(!stepThreePipeline && createPipelineThreeError) {
// Check if error's localized description exists
const NS::String *localizedDescription = createPipelineThreeError->localizedDescription();
if(localizedDescription) {
// Check if localized description's UTF-8 string exists
const char *utf8String = localizedDescription->utf8String();
if(utf8String) {
// Display message
cout << utf8String << endl;
}
}
}
// Check if creating pipeline four failed and an error exists
if(!stepFourPipeline && createPipelineFourError) {
// Check if error's localized description exists
const NS::String *localizedDescription = createPipelineFourError->localizedDescription();
if(localizedDescription) {
// Check if localized description's UTF-8 string exists
const char *utf8String = localizedDescription->utf8String();
if(utf8String) {
// Display message
cout << utf8String << endl;
}
}
}
// Check if creating pipeline clear nodes bitmap failed and an error exists
if(!clearNodesBitmapPipeline && createPipelineClearNodesBitmapError) {
// Check if error's localized description exists
const NS::String *localizedDescription = createPipelineClearNodesBitmapError->localizedDescription();
if(localizedDescription) {
// Check if localized description's UTF-8 string exists
const char *utf8String = localizedDescription->utf8String();
if(utf8String) {
// Display message
cout << utf8String << endl;
}
}
}
// Return false
return false;
}
// Set total number of work items based on the kernels
const MTL::Size totalNumberOfWorkItems[] = {
// Trim edges step one kernel
{NUMBER_OF_EDGES / LEAN_TRIMMING_NUMBER_OF_EDGES_PER_STEP_ONE_WORK_ITEM, 1, 1},
// Trim edges step two kernel
{NUMBER_OF_EDGES / (sizeof(uint64_t) * BITS_IN_A_BYTE), 1, 1},
// Trim edges step three kernel
{NUMBER_OF_EDGES / (sizeof(uint64_t) * BITS_IN_A_BYTE), 1, 1},
// Trim edges step four kernel
{NUMBER_OF_EDGES / (sizeof(uint64_t) * BITS_IN_A_BYTE), 1, 1},
// Clear nodes bitmap kernel
{(NUMBER_OF_EDGES / BITS_IN_A_BYTE) / sizeof(uint64_t), 1, 1}
};
// Set work items per work group based on the total number of work items and max work group size
const MTL::Size workItemsPerWorkGroup[] = {
// Trim edges step one kernel
{min(bit_floor(device->maxThreadsPerThreadgroup().width), totalNumberOfWorkItems[0].width), 1, 1},
// Trim edges step two kernel
{min(bit_floor(device->maxThreadsPerThreadgroup().width), totalNumberOfWorkItems[1].width), 1, 1},
// Trim edges step three kernel
{min(bit_floor(device->maxThreadsPerThreadgroup().width), totalNumberOfWorkItems[2].width), 1, 1},
// Trim edges step four kernel
{min(bit_floor(device->maxThreadsPerThreadgroup().width), totalNumberOfWorkItems[3].width), 1, 1},
// Clear nodes bitmap kernel
{min(bit_floor(device->maxThreadsPerThreadgroup().width), totalNumberOfWorkItems[4].width), 1, 1}
};
// Check if creating pipeline descriptors failed
const unique_ptr<MTL::ComputePipelineDescriptor, void(*)(MTL::ComputePipelineDescriptor *)> stepOnePipelineDescriptor(MTL::ComputePipelineDescriptor::alloc()->init(), [](MTL::ComputePipelineDescriptor *stepOnePipelineDescriptor) noexcept {
// Free step one pipeline descriptor
stepOnePipelineDescriptor->release();
});
const unique_ptr<MTL::ComputePipelineDescriptor, void(*)(MTL::ComputePipelineDescriptor *)> stepTwoPipelineDescriptor(MTL::ComputePipelineDescriptor::alloc()->init(), [](MTL::ComputePipelineDescriptor *stepTwoPipelineDescriptor) noexcept {
// Free step two pipeline descriptor
stepTwoPipelineDescriptor->release();
});
const unique_ptr<MTL::ComputePipelineDescriptor, void(*)(MTL::ComputePipelineDescriptor *)> stepThreePipelineDescriptor(MTL::ComputePipelineDescriptor::alloc()->init(), [](MTL::ComputePipelineDescriptor *stepThreePipelineDescriptor) noexcept {
// Free step three pipeline descriptor
stepThreePipelineDescriptor->release();
});
const unique_ptr<MTL::ComputePipelineDescriptor, void(*)(MTL::ComputePipelineDescriptor *)> stepFourPipelineDescriptor(MTL::ComputePipelineDescriptor::alloc()->init(), [](MTL::ComputePipelineDescriptor *stepFourPipelineDescriptor) noexcept {
// Free step four pipeline descriptor
stepFourPipelineDescriptor->release();
});
const unique_ptr<MTL::ComputePipelineDescriptor, void(*)(MTL::ComputePipelineDescriptor *)> clearNodesBitmapPipelineDescriptor(MTL::ComputePipelineDescriptor::alloc()->init(), [](MTL::ComputePipelineDescriptor *clearNodesBitmapPipelineDescriptor) noexcept {
// Free clear nodes bitmap pipeline descriptor
clearNodesBitmapPipelineDescriptor->release();
});
if(!stepOnePipelineDescriptor || !stepTwoPipelineDescriptor || !stepThreePipelineDescriptor || !stepFourPipelineDescriptor || !clearNodesBitmapPipelineDescriptor) {
// Display message
cout << "Creating pipeline descriptors failed." << endl;
// Return false
return false;
}
// Configure pipeline descriptors
stepOnePipelineDescriptor->setComputeFunction(stepOneKernel.get());
stepOnePipelineDescriptor->setMaxTotalThreadsPerThreadgroup(workItemsPerWorkGroup[0].width);
stepOnePipelineDescriptor->setThreadGroupSizeIsMultipleOfThreadExecutionWidth(workItemsPerWorkGroup[0].width % stepOnePipeline->threadExecutionWidth() == 0);
stepTwoPipelineDescriptor->setComputeFunction(stepTwoKernel.get());
stepTwoPipelineDescriptor->setMaxTotalThreadsPerThreadgroup(workItemsPerWorkGroup[1].width);
stepTwoPipelineDescriptor->setThreadGroupSizeIsMultipleOfThreadExecutionWidth(workItemsPerWorkGroup[1].width % stepTwoPipeline->threadExecutionWidth() == 0);
stepThreePipelineDescriptor->setComputeFunction(stepThreeKernel.get());
stepThreePipelineDescriptor->setMaxTotalThreadsPerThreadgroup(workItemsPerWorkGroup[2].width);
stepThreePipelineDescriptor->setThreadGroupSizeIsMultipleOfThreadExecutionWidth(workItemsPerWorkGroup[2].width % stepThreePipeline->threadExecutionWidth() == 0);
stepFourPipelineDescriptor->setComputeFunction(stepFourKernel.get());
stepFourPipelineDescriptor->setMaxTotalThreadsPerThreadgroup(workItemsPerWorkGroup[3].width);
stepFourPipelineDescriptor->setThreadGroupSizeIsMultipleOfThreadExecutionWidth(workItemsPerWorkGroup[3].width % stepFourPipeline->threadExecutionWidth() == 0);
clearNodesBitmapPipelineDescriptor->setComputeFunction(clearNodesBitmapKernel.get());
clearNodesBitmapPipelineDescriptor->setMaxTotalThreadsPerThreadgroup(workItemsPerWorkGroup[4].width);
clearNodesBitmapPipelineDescriptor->setThreadGroupSizeIsMultipleOfThreadExecutionWidth(workItemsPerWorkGroup[4].width % clearNodesBitmapPipeline->threadExecutionWidth() == 0);
// Check if recreating pipelines for the device with hardcoded work items per work group failed
stepOnePipeline = unique_ptr<MTL::ComputePipelineState, void(*)(MTL::ComputePipelineState *)>(device->newComputePipelineState(stepOnePipelineDescriptor.get(), MTL::PipelineOptionNone, nullptr, &createPipelineOneError), [](MTL::ComputePipelineState *stepOnePipeline) noexcept {
// Free step one pipeline
stepOnePipeline->release();
});
stepTwoPipeline = unique_ptr<MTL::ComputePipelineState, void(*)(MTL::ComputePipelineState *)>(device->newComputePipelineState(stepTwoPipelineDescriptor.get(), MTL::PipelineOptionNone, nullptr, &createPipelineTwoError), [](MTL::ComputePipelineState *stepTwoPipeline) noexcept {
// Free step two pipeline
stepTwoPipeline->release();
});
stepThreePipeline = unique_ptr<MTL::ComputePipelineState, void(*)(MTL::ComputePipelineState *)>(device->newComputePipelineState(stepThreePipelineDescriptor.get(), MTL::PipelineOptionNone, nullptr, &createPipelineThreeError), [](MTL::ComputePipelineState *stepThreePipeline) noexcept {
// Free step three pipeline
stepThreePipeline->release();
});
stepFourPipeline = unique_ptr<MTL::ComputePipelineState, void(*)(MTL::ComputePipelineState *)>(device->newComputePipelineState(stepFourPipelineDescriptor.get(), MTL::PipelineOptionNone, nullptr, &createPipelineFourError), [](MTL::ComputePipelineState *stepFourPipeline) noexcept {
// Free step four pipeline
stepFourPipeline->release();
});
clearNodesBitmapPipeline = unique_ptr<MTL::ComputePipelineState, void(*)(MTL::ComputePipelineState *)>(device->newComputePipelineState(clearNodesBitmapPipelineDescriptor.get(), MTL::PipelineOptionNone, nullptr, &createPipelineClearNodesBitmapError), [](MTL::ComputePipelineState *clearNodesBitmapPipeline) noexcept {
// Free clear nodes bitmap pipeline
clearNodesBitmapPipeline->release();
});
if(!stepOnePipeline || !stepTwoPipeline || !stepThreePipeline || !stepFourPipeline || !clearNodesBitmapPipeline) {
// Display message
cout << "Creating pipelines for the GPU failed." << endl;
// Check if recreating pipeline one failed and an error exists
if(!stepOnePipeline && createPipelineOneError) {
// Check if error's localized description exists
const NS::String *localizedDescription = createPipelineOneError->localizedDescription();
if(localizedDescription) {
// Check if localized description's UTF-8 string exists
const char *utf8String = localizedDescription->utf8String();
if(utf8String) {
// Display message
cout << utf8String << endl;
}
}
}
// Check if recreating pipeline two failed and an error exists
if(!stepTwoPipeline && createPipelineTwoError) {
// Check if error's localized description exists
const NS::String *localizedDescription = createPipelineTwoError->localizedDescription();
if(localizedDescription) {
// Check if localized description's UTF-8 string exists
const char *utf8String = localizedDescription->utf8String();
if(utf8String) {
// Display message
cout << utf8String << endl;
}
}
}
// Check if recreating pipeline three failed and an error exists
if(!stepThreePipeline && createPipelineThreeError) {
// Check if error's localized description exists
const NS::String *localizedDescription = createPipelineThreeError->localizedDescription();
if(localizedDescription) {
// Check if localized description's UTF-8 string exists
const char *utf8String = localizedDescription->utf8String();
if(utf8String) {
// Display message
cout << utf8String << endl;
}
}
}
// Check if recreating pipeline four failed and an error exists
if(!stepFourPipeline && createPipelineFourError) {
// Check if error's localized description exists
const NS::String *localizedDescription = createPipelineFourError->localizedDescription();
if(localizedDescription) {
// Check if localized description's UTF-8 string exists
const char *utf8String = localizedDescription->utf8String();
if(utf8String) {
// Display message
cout << utf8String << endl;
}
}
}
// Check if recreating pipeline clear nodes bitmap failed and an error exists
if(!clearNodesBitmapPipeline && createPipelineClearNodesBitmapError) {
// Check if error's localized description exists
const NS::String *localizedDescription = createPipelineClearNodesBitmapError->localizedDescription();
if(localizedDescription) {
// Check if localized description's UTF-8 string exists
const char *utf8String = localizedDescription->utf8String();
if(utf8String) {
// Display message
cout << utf8String << endl;
}
}
}
// Return false
return false;
}
// Check if allocating memory on the device failed
const unique_ptr<MTL::Buffer, void(*)(MTL::Buffer *)> edgesBitmapOne(device->newBuffer(NUMBER_OF_EDGES / BITS_IN_A_BYTE, MTL::ResourceStorageModeShared | MTL::ResourceHazardTrackingModeUntracked), [](MTL::Buffer *edgesBitmapOne) noexcept {
// Free edges bitmap one
edgesBitmapOne->release();
});
const unique_ptr<MTL::Buffer, void(*)(MTL::Buffer *)> edgesBitmapTwo(device->newBuffer(NUMBER_OF_EDGES / BITS_IN_A_BYTE, MTL::ResourceStorageModeShared | MTL::ResourceHazardTrackingModeUntracked), [](MTL::Buffer *edgesBitmapTwo) noexcept {
// Free edges bitmap two
edgesBitmapTwo->release();
});
const unique_ptr<MTL::Buffer, void(*)(MTL::Buffer *)> nodesBitmap(device->newBuffer(NUMBER_OF_EDGES / BITS_IN_A_BYTE, MTL::ResourceStorageModePrivate | MTL::ResourceHazardTrackingModeUntracked), [](MTL::Buffer *nodesBitmap) noexcept {
// Free nodes bitmap
nodesBitmap->release();
});
if(!edgesBitmapOne || !edgesBitmapTwo || !nodesBitmap) {
// Display message
cout << "Allocating memory on the GPU failed." << endl;
// Return false
return false;
}
// Check if creating command queue for the device failed
const unique_ptr<MTL::CommandQueue, void(*)(MTL::CommandQueue *)> commandQueue(device->newCommandQueue(), [](MTL::CommandQueue *commandQueue) noexcept {
// Free command queue
commandQueue->release();
});
if(!commandQueue) {
// Display message
cout << "Creating command queue for the GPU failed." << endl;
// Return false
return false;
}
// Display message
cout << "Mining started" << endl << endl << "Mining info:" << endl << "\tMining rate:\t 0 graph(s)/second" << endl << "\tGraphs checked:\t 0" << endl;
// Check if not tuning
#ifndef TUNING
// Display message
cout << "\tSolutions found: 0" << endl;
#endif
// Display message
cout << "Pipeline stages:" << endl;
// Set previous graph processed time to now
previousGraphProcessedTime = chrono::high_resolution_clock::now();
// Set start time to now
chrono::high_resolution_clock::time_point startTime = previousGraphProcessedTime;
// Check if creating autorelease pool failed
unique_ptr<NS::AutoreleasePool, void(*)(NS::AutoreleasePool *)> autoreleasePool(NS::AutoreleasePool::alloc()->init(), [](NS::AutoreleasePool *autoreleasePool) noexcept {
// Free autorelease pool
autoreleasePool->release();
});
if(!autoreleasePool) {
// Display message
cout << "Creating autorelease pool failed." << endl;
// Return false
return false;
}
// Check if creating command queue's command buffer failed
MTL::CommandBuffer *commandBuffer = commandQueue->commandBuffer();
if(!commandBuffer) {
// Display message
cout << "Creating command queue's command buffer failed." << endl;
// Return false
return false;
}
// Check if creating command buffer's compute pass encoder failed
MTL::ComputeCommandEncoder *computePassEncoder = commandBuffer->computeCommandEncoder();
if(!computePassEncoder) {
// Display message
cout << "Creating command buffer's compute pass encoder failed." << endl;
// Return false
return false;
}
// Get SipHash keys from job's header and nonce
uint64_t __attribute__((vector_size(sizeof(uint64_t) * SIPHASH_KEYS_SIZE))) sipHashKeysOne;
uint64_t heightOne = jobHeight;
uint64_t idOne = jobId;
uint64_t nonceOne = jobNonce++;
blake2b(sipHashKeysOne, jobHeader, nonceOne);
// Set compute pass's nodes bitmap, SipHash keys, and edges bitmap arguments
computePassEncoder->setBuffer(nodesBitmap.get(), 0, 0);
computePassEncoder->setBytes(&sipHashKeysOne, sizeof(sipHashKeysOne), 1);
computePassEncoder->setBuffer(edgesBitmapOne.get(), 0, 2);
// Add clearing nodes bitmap to the compute pass
computePassEncoder->setComputePipelineState(clearNodesBitmapPipeline.get());
computePassEncoder->dispatchThreads(totalNumberOfWorkItems[4], workItemsPerWorkGroup[4]);
// Add running step one to the compute pass
computePassEncoder->setComputePipelineState(stepOnePipeline.get());
computePassEncoder->dispatchThreads(totalNumberOfWorkItems[0], workItemsPerWorkGroup[0]);
// Add running step two to the compute pass
computePassEncoder->setComputePipelineState(stepTwoPipeline.get());
computePassEncoder->dispatchThreads(totalNumberOfWorkItems[1], workItemsPerWorkGroup[1]);
// Go through all remaining trimming rounds
for(unsigned int i = 1; i < TRIMMING_ROUNDS; ++i) {
// Add clearing nodes bitmap to the compute pass
computePassEncoder->setComputePipelineState(clearNodesBitmapPipeline.get());
computePassEncoder->dispatchThreads(totalNumberOfWorkItems[4], workItemsPerWorkGroup[4]);
// Set compute pass's nodes in second partition argument
computePassEncoder->setBytes(&unmove(static_cast<uint8_t>(i % 2)), sizeof(uint8_t), 3);
// Add running step three to the compute pass
computePassEncoder->setComputePipelineState(stepThreePipeline.get());
computePassEncoder->dispatchThreads(totalNumberOfWorkItems[2], workItemsPerWorkGroup[2]);
// Add running step four to the compute pass
computePassEncoder->setComputePipelineState(stepFourPipeline.get());
computePassEncoder->dispatchThreads(totalNumberOfWorkItems[3], workItemsPerWorkGroup[3]);
}
// Finish adding commands to the compute pass
computePassEncoder->endEncoding();
// Set end time to now
chrono::high_resolution_clock::time_point endTime = chrono::high_resolution_clock::now();
// Run the compute pass
commandBuffer->commit();
// Wait until the compute pass has finished
commandBuffer->waitUntilCompleted();
// Check if closing
if(closing) {
// Return true
return true;
}
// Check if running compute pass failed
if(commandBuffer->error()) {
// Display message
cout << "Running compute pass failed." << endl;
// Return false
return false;
}
// Display message
cout << "\tTrimming time:\t " << (commandBuffer->GPUEndTime() - commandBuffer->kernelStartTime() + static_cast<chrono::duration<double>>(endTime - startTime).count()) << " second(s)" << endl;
// Set start time to now
startTime = chrono::high_resolution_clock::now();
// Free objects with autorelease memory
autoreleasePool.reset();
// Check if recreating autorelease pool failed
autoreleasePool = unique_ptr<NS::AutoreleasePool, void(*)(NS::AutoreleasePool *)>(NS::AutoreleasePool::alloc()->init(), [](NS::AutoreleasePool *autoreleasePool) noexcept {
// Free autorelease pool
autoreleasePool->release();
});
if(!autoreleasePool) {
// Display message
cout << "Creating autorelease pool failed." << endl;
// Return false
return false;
}
// Check if creating command queue's command buffer failed
commandBuffer = commandQueue->commandBuffer();
if(!commandBuffer) {
// Display message
cout << "Creating command queue's command buffer failed." << endl;
// Return false
return false;
}
// Check if creating command buffer's compute pass encoder failed
computePassEncoder = commandBuffer->computeCommandEncoder();
if(!computePassEncoder) {
// Display message
cout << "Creating command buffer's compute pass encoder failed." << endl;
// Return false
return false;
}
// Get SipHash keys from job's header and nonce
uint64_t __attribute__((vector_size(sizeof(uint64_t) * SIPHASH_KEYS_SIZE))) sipHashKeysTwo;
uint64_t heightTwo = jobHeight;
uint64_t idTwo = jobId;
uint64_t nonceTwo = jobNonce++;
blake2b(sipHashKeysTwo, jobHeader, nonceTwo);
// Set compute pass's nodes bitmap, SipHash keys, and edges bitmap arguments
computePassEncoder->setBuffer(nodesBitmap.get(), 0, 0);
computePassEncoder->setBytes(&sipHashKeysTwo, sizeof(sipHashKeysTwo), 1);
computePassEncoder->setBuffer(edgesBitmapTwo.get(), 0, 2);
// Add clearing nodes bitmap to the compute pass
computePassEncoder->setComputePipelineState(clearNodesBitmapPipeline.get());
computePassEncoder->dispatchThreads(totalNumberOfWorkItems[4], workItemsPerWorkGroup[4]);
// Add running step one to the compute pass
computePassEncoder->setComputePipelineState(stepOnePipeline.get());
computePassEncoder->dispatchThreads(totalNumberOfWorkItems[0], workItemsPerWorkGroup[0]);
// Add running step two to the compute pass
computePassEncoder->setComputePipelineState(stepTwoPipeline.get());
computePassEncoder->dispatchThreads(totalNumberOfWorkItems[1], workItemsPerWorkGroup[1]);
// Go through all remaining trimming rounds
for(unsigned int i = 1; i < TRIMMING_ROUNDS; ++i) {
// Add clearing nodes bitmap to the compute pass
computePassEncoder->setComputePipelineState(clearNodesBitmapPipeline.get());
computePassEncoder->dispatchThreads(totalNumberOfWorkItems[4], workItemsPerWorkGroup[4]);
// Set compute pass's nodes in second partition argument
computePassEncoder->setBytes(&unmove(static_cast<uint8_t>(i % 2)), sizeof(uint8_t), 3);
// Add running step three to the compute pass
computePassEncoder->setComputePipelineState(stepThreePipeline.get());
computePassEncoder->dispatchThreads(totalNumberOfWorkItems[2], workItemsPerWorkGroup[2]);
// Add running step four to the compute pass
computePassEncoder->setComputePipelineState(stepFourPipeline.get());
computePassEncoder->dispatchThreads(totalNumberOfWorkItems[3], workItemsPerWorkGroup[3]);
}
// Finish adding commands to the compute pass
computePassEncoder->endEncoding();
// Set end time to now
endTime = chrono::high_resolution_clock::now();
// Run the compute pass
commandBuffer->commit();
// Trimming finished
trimmingFinished(edgesBitmapOne->contents(), sipHashKeysOne, heightOne, idOne, nonceOne);
// Wait until the compute pass has finished
commandBuffer->waitUntilCompleted();
// While not closing
while(!closing) {
// Check if running compute pass failed
if(commandBuffer->error()) {
// Display message
cout << "Running compute pass failed." << endl;
// Return false
return false;
}
// Display message
cout << "\tTrimming time:\t " << (commandBuffer->GPUEndTime() - commandBuffer->kernelStartTime() + static_cast<chrono::duration<double>>(endTime - startTime).count()) << " second(s)" << endl;
// Set start time to now
startTime = chrono::high_resolution_clock::now();
// Free objects with autorelease memory
autoreleasePool.reset();
// Check if recreating autorelease pool failed
autoreleasePool = unique_ptr<NS::AutoreleasePool, void(*)(NS::AutoreleasePool *)>(NS::AutoreleasePool::alloc()->init(), [](NS::AutoreleasePool *autoreleasePool) noexcept {
// Free autorelease pool
autoreleasePool->release();
});
if(!autoreleasePool) {
// Display message
cout << "Creating autorelease pool failed." << endl;
// Return false
return false;
}
// Check if creating command queue's command buffer failed