-
Notifications
You must be signed in to change notification settings - Fork 769
/
Copy pathenqueue.cpp
2001 lines (1747 loc) · 74.9 KB
/
enqueue.cpp
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
//===--------- enqueue.cpp - CUDA Adapter ---------------------------------===//
//
// Copyright (C) 2023 Intel Corporation
//
// Part of the Unified-Runtime Project, under the Apache License v2.0 with LLVM
// Exceptions. See LICENSE.TXT
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "enqueue.hpp"
#include "common.hpp"
#include "context.hpp"
#include "event.hpp"
#include "kernel.hpp"
#include "memory.hpp"
#include "queue.hpp"
#include <cmath>
#include <cuda.h>
#include <ur/ur.hpp>
ur_result_t enqueueEventsWait(ur_queue_handle_t CommandQueue, CUstream Stream,
uint32_t NumEventsInWaitList,
const ur_event_handle_t *EventWaitList) {
UR_ASSERT(EventWaitList, UR_RESULT_SUCCESS);
try {
ScopedContext Active(CommandQueue->getDevice());
auto Result = forLatestEvents(
EventWaitList, NumEventsInWaitList,
[Stream](ur_event_handle_t Event) -> ur_result_t {
if (Event->getStream() == Stream) {
return UR_RESULT_SUCCESS;
} else {
UR_CHECK_ERROR(cuStreamWaitEvent(Stream, Event->get(), 0));
return UR_RESULT_SUCCESS;
}
});
return Result;
} catch (ur_result_t Err) {
return Err;
} catch (...) {
return UR_RESULT_ERROR_UNKNOWN;
}
}
ur_result_t setCuMemAdvise(CUdeviceptr DevPtr, size_t Size,
ur_usm_advice_flags_t URAdviceFlags,
CUdevice Device) {
std::unordered_map<ur_usm_advice_flags_t, CUmem_advise>
URToCUMemAdviseDeviceFlagsMap = {
{UR_USM_ADVICE_FLAG_SET_READ_MOSTLY, CU_MEM_ADVISE_SET_READ_MOSTLY},
{UR_USM_ADVICE_FLAG_CLEAR_READ_MOSTLY,
CU_MEM_ADVISE_UNSET_READ_MOSTLY},
{UR_USM_ADVICE_FLAG_SET_PREFERRED_LOCATION,
CU_MEM_ADVISE_SET_PREFERRED_LOCATION},
{UR_USM_ADVICE_FLAG_CLEAR_PREFERRED_LOCATION,
CU_MEM_ADVISE_UNSET_PREFERRED_LOCATION},
{UR_USM_ADVICE_FLAG_SET_ACCESSED_BY_DEVICE,
CU_MEM_ADVISE_SET_ACCESSED_BY},
{UR_USM_ADVICE_FLAG_CLEAR_ACCESSED_BY_DEVICE,
CU_MEM_ADVISE_UNSET_ACCESSED_BY},
};
for (auto &FlagPair : URToCUMemAdviseDeviceFlagsMap) {
if (URAdviceFlags & FlagPair.first) {
UR_CHECK_ERROR(cuMemAdvise(DevPtr, Size, FlagPair.second, Device));
}
}
std::unordered_map<ur_usm_advice_flags_t, CUmem_advise>
URToCUMemAdviseHostFlagsMap = {
{UR_USM_ADVICE_FLAG_SET_PREFERRED_LOCATION_HOST,
CU_MEM_ADVISE_SET_PREFERRED_LOCATION},
{UR_USM_ADVICE_FLAG_CLEAR_PREFERRED_LOCATION_HOST,
CU_MEM_ADVISE_UNSET_PREFERRED_LOCATION},
{UR_USM_ADVICE_FLAG_SET_ACCESSED_BY_HOST,
CU_MEM_ADVISE_SET_ACCESSED_BY},
{UR_USM_ADVICE_FLAG_CLEAR_ACCESSED_BY_HOST,
CU_MEM_ADVISE_UNSET_ACCESSED_BY},
};
for (auto &FlagPair : URToCUMemAdviseHostFlagsMap) {
if (URAdviceFlags & FlagPair.first) {
UR_CHECK_ERROR(cuMemAdvise(DevPtr, Size, FlagPair.second, CU_DEVICE_CPU));
}
}
std::array<ur_usm_advice_flags_t, 6> UnmappedMemAdviceFlags = {
UR_USM_ADVICE_FLAG_SET_NON_ATOMIC_MOSTLY,
UR_USM_ADVICE_FLAG_CLEAR_NON_ATOMIC_MOSTLY,
UR_USM_ADVICE_FLAG_BIAS_CACHED,
UR_USM_ADVICE_FLAG_BIAS_UNCACHED,
UR_USM_ADVICE_FLAG_SET_NON_COHERENT_MEMORY,
UR_USM_ADVICE_FLAG_CLEAR_NON_COHERENT_MEMORY};
for (auto &UnmappedFlag : UnmappedMemAdviceFlags) {
if (URAdviceFlags & UnmappedFlag) {
UR_LOG(WARN, "Memory advice ignored because the CUDA backend does not "
"support some of the specified flags.");
return UR_RESULT_SUCCESS;
}
}
return UR_RESULT_SUCCESS;
}
// Determine local work sizes that result in uniform work groups.
// The default threadsPerBlock only require handling the first work_dim
// dimension.
void guessLocalWorkSize(ur_device_handle_t Device, size_t *ThreadsPerBlock,
const size_t *GlobalWorkSize, const uint32_t WorkDim,
ur_kernel_handle_t Kernel) {
assert(ThreadsPerBlock != nullptr);
assert(GlobalWorkSize != nullptr);
assert(Kernel != nullptr);
// The below assumes a three dimensional range but this is not guaranteed by
// UR.
size_t GlobalSizeNormalized[3] = {1, 1, 1};
for (uint32_t i = 0; i < WorkDim; i++) {
GlobalSizeNormalized[i] = GlobalWorkSize[i];
}
size_t MaxBlockDim[3];
MaxBlockDim[0] = Device->getMaxWorkItemSizes(0);
MaxBlockDim[1] = Device->getMaxWorkItemSizes(1);
MaxBlockDim[2] = Device->getMaxWorkItemSizes(2);
int MinGrid, MaxBlockSize;
UR_CHECK_ERROR(cuOccupancyMaxPotentialBlockSize(
&MinGrid, &MaxBlockSize, Kernel->get(), NULL, Kernel->getLocalSize(),
MaxBlockDim[0]));
roundToHighestFactorOfGlobalSizeIn3d(ThreadsPerBlock, GlobalSizeNormalized,
MaxBlockDim, MaxBlockSize);
}
// Helper to verify out-of-registers case (exceeded block max registers).
// If the kernel requires a number of registers for the entire thread
// block exceeds the hardware limitations, then the cuLaunchKernel call
// will fail to launch with CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES error.
bool hasExceededMaxRegistersPerBlock(ur_device_handle_t Device,
ur_kernel_handle_t Kernel,
size_t BlockSize) {
return BlockSize * Kernel->getRegsPerThread() > Device->getMaxRegsPerBlock();
}
// Helper to compute kernel parameters from workload
// dimensions.
// @param [in] Context handler to the target Context
// @param [in] Device handler to the target Device
// @param [in] WorkDim workload dimension
// @param [in] GlobalWorkOffset pointer workload global offsets
// @param [in] LocalWorkOffset pointer workload local offsets
// @param [inout] Kernel handler to the kernel
// @param [inout] CuFunc handler to the cuda function attached to the kernel
// @param [out] ThreadsPerBlock Number of threads per block we should run
// @param [out] BlocksPerGrid Number of blocks per grid we should run
ur_result_t
setKernelParams([[maybe_unused]] const ur_context_handle_t Context,
const ur_device_handle_t Device, const uint32_t WorkDim,
const size_t *GlobalWorkOffset, const size_t *GlobalWorkSize,
const size_t *LocalWorkSize, ur_kernel_handle_t &Kernel,
CUfunction &CuFunc, size_t (&ThreadsPerBlock)[3],
size_t (&BlocksPerGrid)[3]) {
ur_result_t Result = UR_RESULT_SUCCESS;
size_t MaxWorkGroupSize = 0u;
bool ProvidedLocalWorkGroupSize = LocalWorkSize != nullptr;
uint32_t LocalSize = Kernel->getLocalSize();
try {
// Set the active context here as guessLocalWorkSize needs an active context
ScopedContext Active(Device);
{
size_t *MaxThreadsPerBlock = Kernel->MaxThreadsPerBlock;
size_t *ReqdThreadsPerBlock = Kernel->ReqdThreadsPerBlock;
MaxWorkGroupSize = Device->getMaxWorkGroupSize();
if (ProvidedLocalWorkGroupSize) {
auto IsValid = [&](int Dim) {
if (ReqdThreadsPerBlock[Dim] != 0 &&
LocalWorkSize[Dim] != ReqdThreadsPerBlock[Dim])
return UR_RESULT_ERROR_INVALID_WORK_GROUP_SIZE;
if (MaxThreadsPerBlock[Dim] != 0 &&
LocalWorkSize[Dim] > MaxThreadsPerBlock[Dim])
return UR_RESULT_ERROR_INVALID_WORK_GROUP_SIZE;
if (LocalWorkSize[Dim] > Device->getMaxWorkItemSizes(Dim))
return UR_RESULT_ERROR_INVALID_WORK_GROUP_SIZE;
// Checks that local work sizes are a divisor of the global work sizes
// which includes that the local work sizes are neither larger than
// the global work sizes and not 0.
if (0u == LocalWorkSize[Dim])
return UR_RESULT_ERROR_INVALID_WORK_GROUP_SIZE;
if (0u != (GlobalWorkSize[Dim] % LocalWorkSize[Dim]))
return UR_RESULT_ERROR_INVALID_WORK_GROUP_SIZE;
ThreadsPerBlock[Dim] = LocalWorkSize[Dim];
return UR_RESULT_SUCCESS;
};
size_t KernelLocalWorkGroupSize = 1;
for (size_t Dim = 0; Dim < WorkDim; Dim++) {
auto Err = IsValid(Dim);
if (Err != UR_RESULT_SUCCESS)
return Err;
// If no error then compute the total local work size as a product of
// all dims.
KernelLocalWorkGroupSize *= LocalWorkSize[Dim];
}
if (size_t MaxLinearThreadsPerBlock = Kernel->MaxLinearThreadsPerBlock;
MaxLinearThreadsPerBlock &&
MaxLinearThreadsPerBlock < KernelLocalWorkGroupSize) {
return UR_RESULT_ERROR_INVALID_WORK_GROUP_SIZE;
}
if (hasExceededMaxRegistersPerBlock(Device, Kernel,
KernelLocalWorkGroupSize)) {
return UR_RESULT_ERROR_OUT_OF_RESOURCES;
}
} else {
guessLocalWorkSize(Device, ThreadsPerBlock, GlobalWorkSize, WorkDim,
Kernel);
}
}
if (MaxWorkGroupSize <
ThreadsPerBlock[0] * ThreadsPerBlock[1] * ThreadsPerBlock[2]) {
return UR_RESULT_ERROR_INVALID_WORK_GROUP_SIZE;
}
for (size_t i = 0; i < WorkDim; i++) {
BlocksPerGrid[i] =
(GlobalWorkSize[i] + ThreadsPerBlock[i] - 1) / ThreadsPerBlock[i];
}
// Set the implicit global offset parameter if kernel has offset variant
if (Kernel->get_with_offset_parameter()) {
std::uint32_t CudaImplicitOffset[3] = {0, 0, 0};
if (GlobalWorkOffset) {
for (size_t i = 0; i < WorkDim; i++) {
CudaImplicitOffset[i] =
static_cast<std::uint32_t>(GlobalWorkOffset[i]);
if (GlobalWorkOffset[i] != 0) {
CuFunc = Kernel->get_with_offset_parameter();
}
}
}
Kernel->setImplicitOffsetArg(sizeof(CudaImplicitOffset),
CudaImplicitOffset);
}
if (LocalSize > static_cast<uint32_t>(Device->getMaxCapacityLocalMem())) {
setErrorMessage("Excessive allocation of local memory on the device",
UR_RESULT_ERROR_ADAPTER_SPECIFIC);
return UR_RESULT_ERROR_ADAPTER_SPECIFIC;
}
if (Device->maxLocalMemSizeChosen()) {
// Set up local memory requirements for kernel.
if (Device->getMaxChosenLocalMem() < 0) {
bool EnvVarHasURPrefix =
std::getenv("UR_CUDA_MAX_LOCAL_MEM_SIZE") != nullptr;
setErrorMessage(EnvVarHasURPrefix ? "Invalid value specified for "
"UR_CUDA_MAX_LOCAL_MEM_SIZE"
: "Invalid value specified for "
"SYCL_PI_CUDA_MAX_LOCAL_MEM_SIZE",
UR_RESULT_ERROR_ADAPTER_SPECIFIC);
return UR_RESULT_ERROR_ADAPTER_SPECIFIC;
}
if (LocalSize > static_cast<uint32_t>(Device->getMaxChosenLocalMem())) {
bool EnvVarHasURPrefix =
std::getenv("UR_CUDA_MAX_LOCAL_MEM_SIZE") != nullptr;
setErrorMessage(
EnvVarHasURPrefix
? "Local memory for kernel exceeds the amount requested using "
"UR_CUDA_MAX_LOCAL_MEM_SIZE. Try increasing the value of "
"UR_CUDA_MAX_LOCAL_MEM_SIZE."
: "Local memory for kernel exceeds the amount requested using "
"SYCL_PI_CUDA_MAX_LOCAL_MEM_SIZE. Try increasing the the "
"value of SYCL_PI_CUDA_MAX_LOCAL_MEM_SIZE.",
UR_RESULT_ERROR_ADAPTER_SPECIFIC);
return UR_RESULT_ERROR_ADAPTER_SPECIFIC;
}
UR_CHECK_ERROR(cuFuncSetAttribute(
CuFunc, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES,
Device->getMaxChosenLocalMem()));
} else if (LocalSize > 48 * 1024) {
// CUDA requires explicit carveout of dynamic shared memory size if larger
// than 48 kB, otherwise cuLaunchKernel fails.
UR_CHECK_ERROR(cuFuncSetAttribute(
CuFunc, CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, LocalSize));
}
} catch (ur_result_t Err) {
Result = Err;
}
return Result;
}
/// Enqueues a wait on the given CUstream for all specified events (See
/// \ref enqueueEventWaitWithBarrier.) If the events list is empty, the enqueued
/// wait will wait on all previous events in the queue.
///
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueEventsWaitWithBarrier(
ur_queue_handle_t hQueue, uint32_t numEventsInWaitList,
const ur_event_handle_t *phEventWaitList, ur_event_handle_t *phEvent) {
// This function makes one stream work on the previous work (or work
// represented by input events) and then all future work waits on that stream.
try {
ScopedContext Active(hQueue->getDevice());
uint32_t StreamToken;
ur_stream_guard Guard;
CUstream CuStream = hQueue->getNextComputeStream(
numEventsInWaitList, phEventWaitList, Guard, &StreamToken);
{
std::lock_guard<std::mutex> GuardBarrier(hQueue->BarrierMutex);
if (hQueue->BarrierEvent == nullptr) {
UR_CHECK_ERROR(
cuEventCreate(&hQueue->BarrierEvent, CU_EVENT_DISABLE_TIMING));
}
if (numEventsInWaitList == 0) { // wait on all work
if (hQueue->BarrierTmpEvent == nullptr) {
UR_CHECK_ERROR(
cuEventCreate(&hQueue->BarrierTmpEvent, CU_EVENT_DISABLE_TIMING));
}
hQueue->syncStreams(
[CuStream, TmpEvent = hQueue->BarrierTmpEvent](CUstream s) {
if (CuStream != s) {
// record a new CUDA event on every stream and make one stream
// wait for these events
UR_CHECK_ERROR(cuEventRecord(TmpEvent, s));
UR_CHECK_ERROR(cuStreamWaitEvent(CuStream, TmpEvent, 0));
}
});
} else { // wait just on given events
forLatestEvents(phEventWaitList, numEventsInWaitList,
[CuStream](ur_event_handle_t Event) -> ur_result_t {
if (Event->getQueue()->hasBeenSynchronized(
Event->getComputeStreamToken())) {
return UR_RESULT_SUCCESS;
} else {
UR_CHECK_ERROR(
cuStreamWaitEvent(CuStream, Event->get(), 0));
return UR_RESULT_SUCCESS;
}
});
}
UR_CHECK_ERROR(cuEventRecord(hQueue->BarrierEvent, CuStream));
for (unsigned int i = 0; i < hQueue->ComputeAppliedBarrier.size(); i++) {
hQueue->ComputeAppliedBarrier[i] = false;
}
for (unsigned int i = 0; i < hQueue->TransferAppliedBarrier.size(); i++) {
hQueue->TransferAppliedBarrier[i] = false;
}
}
if (phEvent) {
*phEvent = ur_event_handle_t_::makeNative(
UR_COMMAND_EVENTS_WAIT_WITH_BARRIER, hQueue, CuStream, StreamToken);
UR_CHECK_ERROR((*phEvent)->start());
UR_CHECK_ERROR((*phEvent)->record());
}
return UR_RESULT_SUCCESS;
} catch (ur_result_t Err) {
return Err;
} catch (...) {
return UR_RESULT_ERROR_UNKNOWN;
}
}
UR_APIEXPORT ur_result_t urEnqueueEventsWaitWithBarrierExt(
ur_queue_handle_t hQueue, const ur_exp_enqueue_ext_properties_t *,
uint32_t numEventsInWaitList, const ur_event_handle_t *phEventWaitList,
ur_event_handle_t *phEvent) {
return urEnqueueEventsWaitWithBarrier(hQueue, numEventsInWaitList,
phEventWaitList, phEvent);
}
/// Enqueues a wait on the given CUstream for all events.
/// See \ref enqueueEventWait
/// TODO: Add support for multiple streams once the Event class is properly
/// refactored.
///
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueEventsWait(
ur_queue_handle_t hQueue, uint32_t numEventsInWaitList,
const ur_event_handle_t *phEventWaitList, ur_event_handle_t *phEvent) {
return urEnqueueEventsWaitWithBarrier(hQueue, numEventsInWaitList,
phEventWaitList, phEvent);
}
static ur_result_t
enqueueKernelLaunch(ur_queue_handle_t hQueue, ur_kernel_handle_t hKernel,
uint32_t workDim, const size_t *pGlobalWorkOffset,
const size_t *pGlobalWorkSize, const size_t *pLocalWorkSize,
uint32_t numEventsInWaitList,
const ur_event_handle_t *phEventWaitList,
ur_event_handle_t *phEvent, size_t WorkGroupMemory) {
// Preconditions
UR_ASSERT(hQueue->getDevice() == hKernel->getProgram()->getDevice(),
UR_RESULT_ERROR_INVALID_KERNEL);
UR_ASSERT(workDim > 0, UR_RESULT_ERROR_INVALID_WORK_DIMENSION);
UR_ASSERT(workDim < 4, UR_RESULT_ERROR_INVALID_WORK_DIMENSION);
// Early exit for zero size kernel
if (*pGlobalWorkSize == 0) {
return urEnqueueEventsWaitWithBarrier(hQueue, numEventsInWaitList,
phEventWaitList, phEvent);
}
// Set the number of threads per block to the number of threads per warp
// by default unless user has provided a better number
size_t ThreadsPerBlock[3] = {32u, 1u, 1u};
size_t BlocksPerGrid[3] = {1u, 1u, 1u};
// Set work group memory so we can compute the whole memory requirement
if (WorkGroupMemory)
hKernel->setWorkGroupMemory(WorkGroupMemory);
uint32_t LocalSize = hKernel->getLocalSize();
CUfunction CuFunc = hKernel->get();
// This might return UR_RESULT_ERROR_ADAPTER_SPECIFIC, which cannot be handled
// using the standard UR_CHECK_ERROR
if (ur_result_t Ret =
setKernelParams(hQueue->getContext(), hQueue->Device, workDim,
pGlobalWorkOffset, pGlobalWorkSize, pLocalWorkSize,
hKernel, CuFunc, ThreadsPerBlock, BlocksPerGrid);
Ret != UR_RESULT_SUCCESS)
return Ret;
try {
std::unique_ptr<ur_event_handle_t_> RetImplEvent{nullptr};
ScopedContext Active(hQueue->getDevice());
uint32_t StreamToken;
ur_stream_guard Guard;
CUstream CuStream = hQueue->getNextComputeStream(
numEventsInWaitList, phEventWaitList, Guard, &StreamToken);
UR_CHECK_ERROR(enqueueEventsWait(hQueue, CuStream, numEventsInWaitList,
phEventWaitList));
// For memory migration across devices in the same context
if (hQueue->getContext()->Devices.size() > 1) {
for (auto &MemArg : hKernel->Args.MemObjArgs) {
enqueueMigrateMemoryToDeviceIfNeeded(MemArg.Mem, hQueue->getDevice(),
CuStream);
if (MemArg.AccessFlags &
(UR_MEM_FLAG_READ_WRITE | UR_MEM_FLAG_WRITE_ONLY)) {
MemArg.Mem->setLastQueueWritingToMemObj(hQueue);
}
}
}
if (phEvent) {
RetImplEvent =
std::unique_ptr<ur_event_handle_t_>(ur_event_handle_t_::makeNative(
UR_COMMAND_KERNEL_LAUNCH, hQueue, CuStream, StreamToken));
UR_CHECK_ERROR(RetImplEvent->start());
}
auto &ArgPointers = hKernel->getArgPointers();
UR_CHECK_ERROR(cuLaunchKernel(
CuFunc, BlocksPerGrid[0], BlocksPerGrid[1], BlocksPerGrid[2],
ThreadsPerBlock[0], ThreadsPerBlock[1], ThreadsPerBlock[2], LocalSize,
CuStream, const_cast<void **>(ArgPointers.data()), nullptr));
if (phEvent) {
UR_CHECK_ERROR(RetImplEvent->record());
*phEvent = RetImplEvent.release();
}
} catch (ur_result_t Err) {
return Err;
}
return UR_RESULT_SUCCESS;
}
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueKernelLaunch(
ur_queue_handle_t hQueue, ur_kernel_handle_t hKernel, uint32_t workDim,
const size_t *pGlobalWorkOffset, const size_t *pGlobalWorkSize,
const size_t *pLocalWorkSize, uint32_t numEventsInWaitList,
const ur_event_handle_t *phEventWaitList, ur_event_handle_t *phEvent) {
return enqueueKernelLaunch(hQueue, hKernel, workDim, pGlobalWorkOffset,
pGlobalWorkSize, pLocalWorkSize,
numEventsInWaitList, phEventWaitList, phEvent,
/*WorkGroupMemory=*/0);
}
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueCooperativeKernelLaunchExp(
ur_queue_handle_t hQueue, ur_kernel_handle_t hKernel, uint32_t workDim,
const size_t *pGlobalWorkOffset, const size_t *pGlobalWorkSize,
const size_t *pLocalWorkSize, uint32_t numEventsInWaitList,
const ur_event_handle_t *phEventWaitList, ur_event_handle_t *phEvent) {
if (pGlobalWorkOffset == nullptr || *pGlobalWorkOffset == 0) {
ur_exp_launch_property_t coop_prop;
coop_prop.id = UR_EXP_LAUNCH_PROPERTY_ID_COOPERATIVE;
coop_prop.value.cooperative = 1;
return urEnqueueKernelLaunchCustomExp(
hQueue, hKernel, workDim, pGlobalWorkOffset, pGlobalWorkSize,
pLocalWorkSize, 1, &coop_prop, numEventsInWaitList, phEventWaitList,
phEvent);
}
return urEnqueueKernelLaunch(hQueue, hKernel, workDim, pGlobalWorkOffset,
pGlobalWorkSize, pLocalWorkSize,
numEventsInWaitList, phEventWaitList, phEvent);
}
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueKernelLaunchCustomExp(
ur_queue_handle_t hQueue, ur_kernel_handle_t hKernel, uint32_t workDim,
const size_t *pGlobalWorkOffset, const size_t *pGlobalWorkSize,
const size_t *pLocalWorkSize, uint32_t numPropsInLaunchPropList,
const ur_exp_launch_property_t *launchPropList,
uint32_t numEventsInWaitList, const ur_event_handle_t *phEventWaitList,
ur_event_handle_t *phEvent) {
size_t WorkGroupMemory = [&]() -> size_t {
const ur_exp_launch_property_t *WorkGroupMemoryProp = std::find_if(
launchPropList, launchPropList + numPropsInLaunchPropList,
[](const ur_exp_launch_property_t &Prop) {
return Prop.id == UR_EXP_LAUNCH_PROPERTY_ID_WORK_GROUP_MEMORY;
});
if (WorkGroupMemoryProp != launchPropList + numPropsInLaunchPropList)
return WorkGroupMemoryProp->value.workgroup_mem_size;
return 0;
}();
if (numPropsInLaunchPropList == 0 ||
(WorkGroupMemory && numPropsInLaunchPropList == 1)) {
return enqueueKernelLaunch(hQueue, hKernel, workDim, pGlobalWorkOffset,
pGlobalWorkSize, pLocalWorkSize,
numEventsInWaitList, phEventWaitList, phEvent,
WorkGroupMemory);
}
#if CUDA_VERSION >= 11080
// Preconditions
UR_ASSERT(hQueue->getDevice() == hKernel->getProgram()->getDevice(),
UR_RESULT_ERROR_INVALID_KERNEL);
UR_ASSERT(workDim > 0, UR_RESULT_ERROR_INVALID_WORK_DIMENSION);
UR_ASSERT(workDim < 4, UR_RESULT_ERROR_INVALID_WORK_DIMENSION);
if (launchPropList == NULL) {
return UR_RESULT_ERROR_INVALID_NULL_POINTER;
}
std::vector<CUlaunchAttribute> launch_attribute;
launch_attribute.reserve(numPropsInLaunchPropList);
// Early exit for zero size kernel
if (*pGlobalWorkSize == 0) {
return urEnqueueEventsWaitWithBarrier(hQueue, numEventsInWaitList,
phEventWaitList, phEvent);
}
// Set the number of threads per block to the number of threads per warp
// by default unless user has provided a better number
size_t ThreadsPerBlock[3] = {32u, 1u, 1u};
size_t BlocksPerGrid[3] = {1u, 1u, 1u};
// Set work group memory so we can compute the whole memory requirement
if (WorkGroupMemory)
hKernel->setWorkGroupMemory(WorkGroupMemory);
uint32_t LocalSize = hKernel->getLocalSize();
CUfunction CuFunc = hKernel->get();
for (uint32_t i = 0; i < numPropsInLaunchPropList; i++) {
switch (launchPropList[i].id) {
case UR_EXP_LAUNCH_PROPERTY_ID_IGNORE: {
auto &attr = launch_attribute.emplace_back();
attr.id = CU_LAUNCH_ATTRIBUTE_IGNORE;
break;
}
case UR_EXP_LAUNCH_PROPERTY_ID_CLUSTER_DIMENSION: {
auto &attr = launch_attribute.emplace_back();
attr.id = CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION;
// Note that cuda orders from right to left wrt SYCL dimensional order.
if (workDim == 3) {
attr.value.clusterDim.x = launchPropList[i].value.clusterDim[2];
attr.value.clusterDim.y = launchPropList[i].value.clusterDim[1];
attr.value.clusterDim.z = launchPropList[i].value.clusterDim[0];
} else if (workDim == 2) {
attr.value.clusterDim.x = launchPropList[i].value.clusterDim[1];
attr.value.clusterDim.y = launchPropList[i].value.clusterDim[0];
attr.value.clusterDim.z = launchPropList[i].value.clusterDim[2];
} else {
attr.value.clusterDim.x = launchPropList[i].value.clusterDim[0];
attr.value.clusterDim.y = launchPropList[i].value.clusterDim[1];
attr.value.clusterDim.z = launchPropList[i].value.clusterDim[2];
}
UR_CHECK_ERROR(cuFuncSetAttribute(
CuFunc, CU_FUNC_ATTRIBUTE_NON_PORTABLE_CLUSTER_SIZE_ALLOWED, 1));
break;
}
case UR_EXP_LAUNCH_PROPERTY_ID_COOPERATIVE: {
auto &attr = launch_attribute.emplace_back();
attr.id = CU_LAUNCH_ATTRIBUTE_COOPERATIVE;
attr.value.cooperative = launchPropList[i].value.cooperative;
break;
}
case UR_EXP_LAUNCH_PROPERTY_ID_WORK_GROUP_MEMORY: {
break;
}
default: {
return UR_RESULT_ERROR_INVALID_ENUMERATION;
}
}
}
// This might return UR_RESULT_ERROR_ADAPTER_SPECIFIC, which cannot be handled
// using the standard UR_CHECK_ERROR
if (ur_result_t Ret =
setKernelParams(hQueue->getContext(), hQueue->Device, workDim,
pGlobalWorkOffset, pGlobalWorkSize, pLocalWorkSize,
hKernel, CuFunc, ThreadsPerBlock, BlocksPerGrid);
Ret != UR_RESULT_SUCCESS)
return Ret;
try {
std::unique_ptr<ur_event_handle_t_> RetImplEvent{nullptr};
ScopedContext Active(hQueue->getDevice());
uint32_t StreamToken;
ur_stream_guard Guard;
CUstream CuStream = hQueue->getNextComputeStream(
numEventsInWaitList, phEventWaitList, Guard, &StreamToken);
UR_CHECK_ERROR(enqueueEventsWait(hQueue, CuStream, numEventsInWaitList,
phEventWaitList));
// For memory migration across devices in the same context
if (hQueue->getContext()->Devices.size() > 1) {
for (auto &MemArg : hKernel->Args.MemObjArgs) {
enqueueMigrateMemoryToDeviceIfNeeded(MemArg.Mem, hQueue->getDevice(),
CuStream);
if (MemArg.AccessFlags &
(UR_MEM_FLAG_READ_WRITE | UR_MEM_FLAG_WRITE_ONLY)) {
MemArg.Mem->setLastQueueWritingToMemObj(hQueue);
}
}
}
if (phEvent) {
RetImplEvent =
std::unique_ptr<ur_event_handle_t_>(ur_event_handle_t_::makeNative(
UR_COMMAND_KERNEL_LAUNCH, hQueue, CuStream, StreamToken));
UR_CHECK_ERROR(RetImplEvent->start());
}
auto &ArgPointers = hKernel->getArgPointers();
CUlaunchConfig launch_config;
launch_config.gridDimX = BlocksPerGrid[0];
launch_config.gridDimY = BlocksPerGrid[1];
launch_config.gridDimZ = BlocksPerGrid[2];
launch_config.blockDimX = ThreadsPerBlock[0];
launch_config.blockDimY = ThreadsPerBlock[1];
launch_config.blockDimZ = ThreadsPerBlock[2];
launch_config.sharedMemBytes = LocalSize;
launch_config.hStream = CuStream;
launch_config.attrs = &launch_attribute[0];
launch_config.numAttrs = launch_attribute.size();
UR_CHECK_ERROR(cuLaunchKernelEx(&launch_config, CuFunc,
const_cast<void **>(ArgPointers.data()),
nullptr));
if (phEvent) {
UR_CHECK_ERROR(RetImplEvent->record());
*phEvent = RetImplEvent.release();
}
} catch (ur_result_t Err) {
return Err;
}
return UR_RESULT_SUCCESS;
#else
[[maybe_unused]] auto _ = launchPropList;
setErrorMessage("This feature requires cuda 11.8 or later.",
UR_RESULT_ERROR_ADAPTER_SPECIFIC);
return UR_RESULT_ERROR_ADAPTER_SPECIFIC;
#endif // CUDA_VERSION >= 11080
}
/// Set parameters for general 3D memory copy.
/// If the source and/or destination is on the device, SrcPtr and/or DstPtr
/// must be a pointer to a CUdeviceptr
void setCopyRectParams(ur_rect_region_t region, const void *SrcPtr,
const CUmemorytype_enum SrcType,
ur_rect_offset_t src_offset, size_t src_row_pitch,
size_t src_slice_pitch, void *DstPtr,
const CUmemorytype_enum DstType,
ur_rect_offset_t dst_offset, size_t dst_row_pitch,
size_t dst_slice_pitch, CUDA_MEMCPY3D ¶ms) {
src_row_pitch =
(!src_row_pitch) ? region.width + src_offset.x : src_row_pitch;
src_slice_pitch = (!src_slice_pitch)
? ((region.height + src_offset.y) * src_row_pitch)
: src_slice_pitch;
dst_row_pitch =
(!dst_row_pitch) ? region.width + dst_offset.x : dst_row_pitch;
dst_slice_pitch = (!dst_slice_pitch)
? ((region.height + dst_offset.y) * dst_row_pitch)
: dst_slice_pitch;
params.WidthInBytes = region.width;
params.Height = region.height;
params.Depth = region.depth;
params.srcMemoryType = SrcType;
params.srcDevice = SrcType == CU_MEMORYTYPE_DEVICE
? *static_cast<const CUdeviceptr *>(SrcPtr)
: 0;
params.srcHost = SrcType == CU_MEMORYTYPE_HOST ? SrcPtr : nullptr;
params.srcXInBytes = src_offset.x;
params.srcY = src_offset.y;
params.srcZ = src_offset.z;
params.srcPitch = src_row_pitch;
params.srcHeight = src_slice_pitch / src_row_pitch;
params.dstMemoryType = DstType;
params.dstDevice =
DstType == CU_MEMORYTYPE_DEVICE ? *static_cast<CUdeviceptr *>(DstPtr) : 0;
params.dstHost = DstType == CU_MEMORYTYPE_HOST ? DstPtr : nullptr;
params.dstXInBytes = dst_offset.x;
params.dstY = dst_offset.y;
params.dstZ = dst_offset.z;
params.dstPitch = dst_row_pitch;
params.dstHeight = dst_slice_pitch / dst_row_pitch;
}
/// General 3D memory copy operation.
/// This function requires the corresponding CUDA context to be at the top of
/// the context stack
/// If the source and/or destination is on the device, SrcPtr and/or DstPtr
/// must be a pointer to a CUdeviceptr
static ur_result_t commonEnqueueMemBufferCopyRect(
CUstream cu_stream, ur_rect_region_t region, const void *SrcPtr,
const CUmemorytype_enum SrcType, ur_rect_offset_t src_offset,
size_t src_row_pitch, size_t src_slice_pitch, void *DstPtr,
const CUmemorytype_enum DstType, ur_rect_offset_t dst_offset,
size_t dst_row_pitch, size_t dst_slice_pitch) {
UR_ASSERT(SrcType == CU_MEMORYTYPE_DEVICE || SrcType == CU_MEMORYTYPE_HOST,
UR_RESULT_ERROR_INVALID_MEM_OBJECT);
UR_ASSERT(DstType == CU_MEMORYTYPE_DEVICE || DstType == CU_MEMORYTYPE_HOST,
UR_RESULT_ERROR_INVALID_MEM_OBJECT);
CUDA_MEMCPY3D params = {};
setCopyRectParams(region, SrcPtr, SrcType, src_offset, src_row_pitch,
src_slice_pitch, DstPtr, DstType, dst_offset, dst_row_pitch,
dst_slice_pitch, params);
UR_CHECK_ERROR(cuMemcpy3DAsync(¶ms, cu_stream));
return UR_RESULT_SUCCESS;
}
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueMemBufferReadRect(
ur_queue_handle_t hQueue, ur_mem_handle_t hBuffer, bool blockingRead,
ur_rect_offset_t bufferOrigin, ur_rect_offset_t hostOrigin,
ur_rect_region_t region, size_t bufferRowPitch, size_t bufferSlicePitch,
size_t hostRowPitch, size_t hostSlicePitch, void *pDst,
uint32_t numEventsInWaitList, const ur_event_handle_t *phEventWaitList,
ur_event_handle_t *phEvent) {
std::unique_ptr<ur_event_handle_t_> RetImplEvent{nullptr};
try {
// Note that this entry point may be called on a queue that may not be the
// last queue to write to the MemBuffer, meaning we must perform the copy
// from a different device
if (hBuffer->LastQueueWritingToMemObj &&
hBuffer->LastQueueWritingToMemObj->getDevice() != hQueue->getDevice()) {
hQueue = hBuffer->LastQueueWritingToMemObj;
}
auto Device = hQueue->getDevice();
ScopedContext Active(Device);
CUstream Stream = hQueue->getNextTransferStream();
UR_CHECK_ERROR(enqueueEventsWait(hQueue, Stream, numEventsInWaitList,
phEventWaitList));
if (phEvent) {
RetImplEvent =
std::unique_ptr<ur_event_handle_t_>(ur_event_handle_t_::makeNative(
UR_COMMAND_MEM_BUFFER_READ_RECT, hQueue, Stream));
UR_CHECK_ERROR(RetImplEvent->start());
}
auto DevPtr = std::get<BufferMem>(hBuffer->Mem).getPtr(Device);
UR_CHECK_ERROR(commonEnqueueMemBufferCopyRect(
Stream, region, &DevPtr, CU_MEMORYTYPE_DEVICE, bufferOrigin,
bufferRowPitch, bufferSlicePitch, pDst, CU_MEMORYTYPE_HOST, hostOrigin,
hostRowPitch, hostSlicePitch));
if (phEvent) {
UR_CHECK_ERROR(RetImplEvent->record());
}
if (blockingRead) {
UR_CHECK_ERROR(cuStreamSynchronize(Stream));
}
if (phEvent) {
*phEvent = RetImplEvent.release();
}
} catch (ur_result_t Err) {
return Err;
}
return UR_RESULT_SUCCESS;
}
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueMemBufferWriteRect(
ur_queue_handle_t hQueue, ur_mem_handle_t hBuffer, bool blockingWrite,
ur_rect_offset_t bufferOrigin, ur_rect_offset_t hostOrigin,
ur_rect_region_t region, size_t bufferRowPitch, size_t bufferSlicePitch,
size_t hostRowPitch, size_t hostSlicePitch, void *pSrc,
uint32_t numEventsInWaitList, const ur_event_handle_t *phEventWaitList,
ur_event_handle_t *phEvent) {
CUdeviceptr DevPtr =
std::get<BufferMem>(hBuffer->Mem).getPtr(hQueue->getDevice());
std::unique_ptr<ur_event_handle_t_> RetImplEvent{nullptr};
hBuffer->setLastQueueWritingToMemObj(hQueue);
try {
ScopedContext Active(hQueue->getDevice());
CUstream cuStream = hQueue->getNextTransferStream();
UR_CHECK_ERROR(enqueueEventsWait(hQueue, cuStream, numEventsInWaitList,
phEventWaitList));
if (phEvent) {
RetImplEvent =
std::unique_ptr<ur_event_handle_t_>(ur_event_handle_t_::makeNative(
UR_COMMAND_MEM_BUFFER_WRITE_RECT, hQueue, cuStream));
UR_CHECK_ERROR(RetImplEvent->start());
}
UR_CHECK_ERROR(commonEnqueueMemBufferCopyRect(
cuStream, region, pSrc, CU_MEMORYTYPE_HOST, hostOrigin, hostRowPitch,
hostSlicePitch, &DevPtr, CU_MEMORYTYPE_DEVICE, bufferOrigin,
bufferRowPitch, bufferSlicePitch));
if (phEvent) {
UR_CHECK_ERROR(RetImplEvent->record());
}
if (blockingWrite) {
UR_CHECK_ERROR(cuStreamSynchronize(cuStream));
}
if (phEvent) {
*phEvent = RetImplEvent.release();
}
} catch (ur_result_t Err) {
return Err;
}
return UR_RESULT_SUCCESS;
}
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueMemBufferCopy(
ur_queue_handle_t hQueue, ur_mem_handle_t hBufferSrc,
ur_mem_handle_t hBufferDst, size_t srcOffset, size_t dstOffset, size_t size,
uint32_t numEventsInWaitList, const ur_event_handle_t *phEventWaitList,
ur_event_handle_t *phEvent) {
UR_ASSERT(size + dstOffset <= std::get<BufferMem>(hBufferDst->Mem).getSize(),
UR_RESULT_ERROR_INVALID_SIZE);
UR_ASSERT(size + srcOffset <= std::get<BufferMem>(hBufferSrc->Mem).getSize(),
UR_RESULT_ERROR_INVALID_SIZE);
std::unique_ptr<ur_event_handle_t_> RetImplEvent{nullptr};
try {
ScopedContext Active(hQueue->getDevice());
ur_result_t Result = UR_RESULT_SUCCESS;
auto Stream = hQueue->getNextTransferStream();
Result =
enqueueEventsWait(hQueue, Stream, numEventsInWaitList, phEventWaitList);
if (phEvent) {
RetImplEvent =
std::unique_ptr<ur_event_handle_t_>(ur_event_handle_t_::makeNative(
UR_COMMAND_MEM_BUFFER_COPY, hQueue, Stream));
UR_CHECK_ERROR(RetImplEvent->start());
}
auto Src = std::get<BufferMem>(hBufferSrc->Mem)
.getPtrWithOffset(hQueue->getDevice(), srcOffset);
auto Dst = std::get<BufferMem>(hBufferDst->Mem)
.getPtrWithOffset(hQueue->getDevice(), dstOffset);
UR_CHECK_ERROR(cuMemcpyDtoDAsync(Dst, Src, size, Stream));
if (phEvent) {
UR_CHECK_ERROR(RetImplEvent->record());
*phEvent = RetImplEvent.release();
}
return Result;
} catch (ur_result_t Err) {
return Err;
} catch (...) {
return UR_RESULT_ERROR_UNKNOWN;
}
}
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueMemBufferCopyRect(
ur_queue_handle_t hQueue, ur_mem_handle_t hBufferSrc,
ur_mem_handle_t hBufferDst, ur_rect_offset_t srcOrigin,
ur_rect_offset_t dstOrigin, ur_rect_region_t region, size_t srcRowPitch,
size_t srcSlicePitch, size_t dstRowPitch, size_t dstSlicePitch,
uint32_t numEventsInWaitList, const ur_event_handle_t *phEventWaitList,
ur_event_handle_t *phEvent) {
ur_result_t Result = UR_RESULT_SUCCESS;
CUdeviceptr SrcPtr =
std::get<BufferMem>(hBufferSrc->Mem).getPtr(hQueue->getDevice());
CUdeviceptr DstPtr =
std::get<BufferMem>(hBufferDst->Mem).getPtr(hQueue->getDevice());
std::unique_ptr<ur_event_handle_t_> RetImplEvent{nullptr};
try {
ScopedContext Active(hQueue->getDevice());
CUstream CuStream = hQueue->getNextTransferStream();
Result = enqueueEventsWait(hQueue, CuStream, numEventsInWaitList,
phEventWaitList);
if (phEvent) {
RetImplEvent =
std::unique_ptr<ur_event_handle_t_>(ur_event_handle_t_::makeNative(
UR_COMMAND_MEM_BUFFER_COPY_RECT, hQueue, CuStream));
UR_CHECK_ERROR(RetImplEvent->start());
}
Result = commonEnqueueMemBufferCopyRect(
CuStream, region, &SrcPtr, CU_MEMORYTYPE_DEVICE, srcOrigin, srcRowPitch,
srcSlicePitch, &DstPtr, CU_MEMORYTYPE_DEVICE, dstOrigin, dstRowPitch,
dstSlicePitch);
if (phEvent) {
UR_CHECK_ERROR(RetImplEvent->record());
*phEvent = RetImplEvent.release();
}
} catch (ur_result_t err) {
Result = err;
}
return Result;
}
// CUDA has no memset functions that allow setting values more than 4 bytes. UR
// API lets you pass an arbitrary "pattern" to the buffer fill, which can be
// more than 4 bytes. We must break up the pattern into 1, 2 or 4-byte values
// and set the buffer using multiple strided calls.
ur_result_t commonMemSetLargePattern(CUstream Stream, uint32_t PatternSize,
size_t Size, const void *pPattern,
CUdeviceptr Ptr) {
// Find the largest supported word size into which the pattern can be divided
auto BackendWordSize = PatternSize % 4u == 0u ? 4u
: PatternSize % 2u == 0u ? 2u
: 1u;
// Calculate the number of words in the pattern, the stride, and the number of
// times the pattern needs to be applied
auto NumberOfSteps = PatternSize / BackendWordSize;
auto Pitch = NumberOfSteps * BackendWordSize;
auto Height = Size / PatternSize;
// Same implementation works for any pattern word type (uint8_t, uint16_t,
// uint32_t)
auto memsetImpl = [BackendWordSize, NumberOfSteps, Pitch, Height, Size, Ptr,
&Stream](const auto *pPatternWords,
auto &&continuousMemset, auto &&stridedMemset) {
// If the pattern is 1 word or the first word is repeated throughout, a fast
// continuous fill can be used without the need for slower strided fills
bool UseOnlyFirstValue{true};
for (auto Step{1u}; (Step < NumberOfSteps) && UseOnlyFirstValue; ++Step) {
if (*(pPatternWords + Step) != *pPatternWords) {
UseOnlyFirstValue = false;
}
}
auto OptimizedNumberOfSteps{UseOnlyFirstValue ? 1u : NumberOfSteps};
// Fill the pattern in steps of BackendWordSize bytes. Use a continuous
// fill in the first step because it's faster than a strided fill. Then,
// overwrite the other values in subsequent steps.
for (auto Step{0u}; Step < OptimizedNumberOfSteps; ++Step) {
if (Step == 0) {
UR_CHECK_ERROR(continuousMemset(Ptr, *(pPatternWords),
Size / BackendWordSize, Stream));
} else {
UR_CHECK_ERROR(stridedMemset(Ptr + Step * BackendWordSize, Pitch,
*(pPatternWords + Step), 1u, Height,