-
Notifications
You must be signed in to change notification settings - Fork 442
Expand file tree
/
Copy pathAMReX_GpuDevice.cpp
More file actions
1412 lines (1219 loc) · 45.8 KB
/
AMReX_GpuDevice.cpp
File metadata and controls
1412 lines (1219 loc) · 45.8 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
#include <AMReX_Arena.H>
#include <AMReX_GpuDevice.H>
#include <AMReX_GpuLaunch.H>
#include <AMReX_Machine.H>
#include <AMReX_ParallelDescriptor.H>
#include <AMReX_ParmParse.H>
#include <AMReX_Print.H>
#ifdef AMREX_USE_HYPRE
# include <_hypre_utilities.h>
#endif
#include <iostream>
#include <map>
#include <algorithm>
#include <string>
#include <unordered_set>
#include <exception>
#if defined(AMREX_USE_CUDA)
#include <cuda_profiler_api.h>
#if defined(AMREX_PROFILING) || defined (AMREX_TINY_PROFILING)
#if __has_include(<nvtx3/nvtx3.hpp>)
# include <nvtx3/nvtx3.hpp>
#elif __has_include(<nvtx3/nvToolsExt.h>)
# include <nvtx3/nvToolsExt.h>
#else
# include <nvToolsExt.h>
#endif
#endif
#endif
#if defined(AMREX_USE_HIP)
#include <hip/hip_runtime.h>
#if defined(AMREX_USE_ROCTX)
#include <rocprofiler-sdk-roctx/roctx.h>
#endif
#endif
#ifdef AMREX_USE_ACC
#include <openacc.h>
extern "C" {
void amrex_initialize_acc (int);
void amrex_finalize_acc ();
void amrex_set_acc_stream (int);
}
#endif
#ifdef AMREX_USE_SYCL
namespace {
auto amrex_sycl_error_handler = [] (sycl::exception_list exceptions) {
for (std::exception_ptr const& e : exceptions) {
try {
std::rethrow_exception(e);
} catch (sycl::exception const& ex) {
amrex::Abort(std::string("Async SYCL exception: ")+ex.what()+"!!!!!");
}
}
};
}
#endif
#if defined(AMREX_USE_HIP) && defined(HIP_VERSION_MAJOR) && (HIP_VERSION_MAJOR <= 6)
namespace {
__host__ __device__ void amrex_check_wavefront_size () {
#ifdef __HIP_DEVICE_COMPILE__
// * https://github.com/AMReX-Codes/amrex/issues/3792
// __AMDGCN_WAVEFRONT_SIZE is valid in device code only.
// Thus we have to check it this way.
// * https://github.com/AMReX-Codes/amrex/issues/4270
// __AMDGCN_WAVEFRONT_SIZE will be deprecated.
#ifdef __AMDGCN_WAVEFRONT_SIZE
static_assert(__AMDGCN_WAVEFRONT_SIZE == AMREX_AMDGCN_WAVEFRONT_SIZE,
"Please let the amrex team know if you encounter this");
#endif
#endif
}
}
#endif
namespace amrex::Gpu {
int Device::device_id = 0;
int Device::num_devices_used = 0;
int Device::num_device_partners = 1;
int Device::verbose = 0;
#ifdef AMREX_USE_GPU
int Device::max_gpu_streams = 4;
#else
int Device::max_gpu_streams = 1;
#endif
#ifdef AMREX_USE_GPU
dim3 Device::numThreadsMin = dim3(1, 1, 1);
dim3 Device::numThreadsOverride = dim3(0, 0, 0);
dim3 Device::numBlocksOverride = dim3(0, 0, 0);
unsigned int Device::max_blocks_per_launch = 2560;
Vector<StreamManager> Device::gpu_stream_pool;
Vector<int> Device::gpu_stream_index;
gpuDeviceProp_t Device::device_prop;
int Device::memory_pools_supported = 0;
#ifdef AMREX_USE_GPU
Vector<Device::ExternalStream> Device::external_stream_stack;
#endif
constexpr int Device::warp_size;
#ifdef AMREX_USE_SYCL
std::unique_ptr<sycl::context> Device::sycl_context;
std::unique_ptr<sycl::device> Device::sycl_device;
#endif
namespace {
#if defined(__CUDACC__)
AMREX_GPU_GLOBAL void emptyKernel() {}
#endif
void InitializeGraph(int graph_size)
{
amrex::ignore_unused(graph_size);
#if defined(__CUDACC__) && defined(AMREX_USE_CUDA)
BL_PROFILE("InitGraph");
int streams = Gpu::Device::numGpuStreams();
cudaGraphExec_t graphExec{};
for (int n=0; n<(graph_size); ++n)
{
Gpu::Device::startGraphRecording((n == 0), NULL, NULL, 0);
// ..................
Gpu::Device::setStreamIndex(n%streams);
emptyKernel<<<1, 1, 0, Gpu::gpuStream()>>>();
// ..................
graphExec = Gpu::Device::stopGraphRecording((n == (graph_size-1)));
}
AMREX_CUDA_SAFE_CALL(cudaGraphExecDestroy(graphExec));
#endif
}
}
[[nodiscard]] gpuStream_t&
StreamManager::getStream () {
return m_stream;
}
gpuStream_t const&
StreamManager::getStream () const {
return m_stream;
}
void
StreamManager::sync () {
decltype(m_free_wait_list) new_empty_wait_list{};
{
// lock mutex before accessing and modifying member variables
std::lock_guard<std::mutex> lock(m_mutex);
m_free_wait_list.swap(new_empty_wait_list);
}
// unlock mutex before stream sync and memory free
// to avoid deadlocks from the CArena mutex
// actual stream sync
#ifdef AMREX_USE_SYCL
try {
m_stream.queue->wait_and_throw();
} catch (sycl::exception const& ex) {
for (auto [arena, mem] : new_empty_wait_list) {
arena->free(mem);
}
new_empty_wait_list.clear();
amrex::Abort(std::string("streamSynchronize: ")+ex.what()+"!!!!!");
}
#else
AMREX_HIP_OR_CUDA( AMREX_HIP_SAFE_CALL(hipStreamSynchronize(m_stream));,
AMREX_CUDA_SAFE_CALL(cudaStreamSynchronize(m_stream)); )
#endif
// synconizing the stream may have taken a long time and
// there may be new kernels launched already, so we free memory
// according to the state from before the stream was synced
for (auto [arena, mem] : new_empty_wait_list) {
arena->free(mem);
}
}
void
StreamManager::free_async (Arena* arena, void* mem) {
if (arena->isDeviceAccessible()) {
std::size_t free_wait_list_size = 0;
{
// lock mutex before accessing and modifying member variables
std::lock_guard<std::mutex> lock(m_mutex);
m_free_wait_list.emplace_back(arena, mem);
free_wait_list_size = m_free_wait_list.size();
}
// Limit the number of memory allocations in m_free_wait_list
// in case the stream is never synchronized
if (free_wait_list_size > 100) {
sync();
}
} else {
arena->free(mem);
}
}
std::size_t
StreamManager::wait_list_size () {
// lock mutex before accessing member variables
std::lock_guard<std::mutex> lock(m_mutex);
return m_free_wait_list.size();
}
#endif
void
Device::Initialize (bool minimal, int a_device_id)
{
amrex::ignore_unused(minimal, a_device_id);
#ifdef AMREX_USE_GPU
#if defined(AMREX_USE_CUDA) && (defined(AMREX_PROFILING) || defined(AMREX_TINY_PROFILING))
// Wrap cuda init to identify it appropriately in nvvp.
// Note: first substantial cuda call may cause a lengthy
// cuda API and cuda driver API initialization that will
// be captured by the profiler. It a necessary, system
// dependent step that is unavoidable.
nvtxRangePush("initialize_device");
#endif
ParmParse ppamrex("amrex");
ppamrex.queryAdd("max_gpu_streams", max_gpu_streams);
max_gpu_streams = std::min(max_gpu_streams, AMREX_GPU_MAX_STREAMS);
max_gpu_streams = std::max(max_gpu_streams, 1);
ParmParse pp("device");
if (! pp.query("verbose", "v", verbose)) {
pp.add("verbose", verbose);
}
if (amrex::Verbose()) {
AMREX_HIP_OR_CUDA_OR_SYCL
( amrex::Print() << "Initializing HIP...\n";,
amrex::Print() << "Initializing CUDA...\n";,
amrex::Print() << "Initializing SYCL...\n"; )
}
// Count the number of GPU devices.
int gpu_device_count = 0;
#ifdef AMREX_USE_SYCL
{
sycl::platform platform(sycl::gpu_selector_v);
auto const& gpu_devices = platform.get_devices();
gpu_device_count = gpu_devices.size();
if (gpu_device_count <= 0) {
amrex::Abort("No GPU device found");
}
}
#else
AMREX_HIP_OR_CUDA(AMREX_HIP_SAFE_CALL (hipGetDeviceCount(&gpu_device_count));,
AMREX_CUDA_SAFE_CALL(cudaGetDeviceCount(&gpu_device_count)); );
if (gpu_device_count <= 0) {
amrex::Abort("No GPU device found");
}
#endif
// Now, assign ranks to GPUs. If we only have one GPU,
// or only one MPI rank, this is easy. Otherwise, we
// need to do a little more work.
int n_local_procs = 1;
amrex::ignore_unused(n_local_procs);
if (minimal) {
device_id = 0;
AMREX_HIP_OR_CUDA(AMREX_HIP_SAFE_CALL (hipGetDevice(&device_id));,
AMREX_CUDA_SAFE_CALL(cudaGetDevice(&device_id)); );
} else if (a_device_id >= 0) {
device_id = a_device_id;
} else if (ParallelDescriptor::NProcs() == 1) {
device_id = 0;
}
else if (gpu_device_count == 1) {
device_id = 0;
}
else {
if (ParallelDescriptor::NProcsPerNode() == gpu_device_count) {
device_id = ParallelDescriptor::MyRankInNode();
} else if (ParallelDescriptor::NProcsPerProcessor() == gpu_device_count) {
device_id = ParallelDescriptor::MyRankInProcessor();
} else {
device_id = ParallelDescriptor::MyProc() % gpu_device_count;
}
}
if (gpu_device_count > 1 && ! minimal && a_device_id < 0) {
if (Machine::name() == "nersc.perlmutter") {
// The CPU/GPU mapping on perlmutter has the reverse order.
device_id = gpu_device_count - device_id - 1;
if (amrex::Verbose()) {
amrex::Print() << "Multiple GPUs are visible to each MPI rank. Fixing GPU assignment for Perlmutter according to heuristics.\n";
}
} else if (Machine::name() == "olcf.frontier") {
// The CPU/GPU mapping on fronter is documented at
// https://docs.olcf.ornl.gov/systems/frontier_user_guide.html
if (gpu_device_count == 8) {
constexpr std::array<int,8> gpu_order = {4,5,2,3,6,7,0,1};
device_id = gpu_order[device_id];
if (amrex::Verbose()) {
amrex::Print() << "Multiple GPUs are visible to each MPI rank. Fixing GPU assignment for Frontier according to heuristics.\n";
}
}
} else {
if (amrex::Verbose() && ParallelDescriptor::IOProcessor()) {
amrex::Warning("Multiple GPUs are visible to each MPI rank. This is usually not an issue. But this may lead to incorrect or suboptimal rank-to-GPU mapping.");
}
}
}
#if !defined(AMREX_USE_SYCL)
if ( ! minimal) {
AMREX_HIP_OR_CUDA(AMREX_HIP_SAFE_CALL (hipSetDevice(device_id));,
AMREX_CUDA_SAFE_CALL(cudaSetDevice(device_id)); );
}
#endif
#ifdef AMREX_USE_ACC
amrex_initialize_acc(device_id);
#endif
initialize_gpu(minimal);
num_devices_used = ParallelDescriptor::NProcs();
#ifdef AMREX_USE_MPI
if (ParallelDescriptor::NProcs() > 1 && ! minimal) {
#if defined(HIP_VERSION_MAJOR) && defined(HIP_VERSION_MINOR) && ((HIP_VERSION_MAJOR < 5) || ((HIP_VERSION_MAJOR == 5) && (HIP_VERSION_MINOR < 2)))
// hip < 5.2: uuid not supported
num_device_partners = 1;
#elif defined(AMREX_USE_CUDA) || defined(AMREX_USE_HIP)
constexpr int len = 16;
static_assert(std::is_same<decltype(AMREX_HIP_OR_CUDA(hipUUID,cudaUUID_t)::bytes),
char[len]>());
std::vector<char> buf(ParallelDescriptor::NProcs()*len);
char* pbuf = buf.data();
#ifdef AMREX_USE_CUDA
auto const& uuid = device_prop.uuid;
#else
hipUUID uuid;
AMREX_HIP_SAFE_CALL(hipDeviceGetUuid(&uuid, device_id));
#endif
char const* sbuf = uuid.bytes;
MPI_Allgather(sbuf, len, MPI_CHAR, pbuf, len, MPI_CHAR,
ParallelDescriptor::Communicator());
std::map<std::string,int> uuid_counts;
std::string my_uuid;
for (int i = 0; i < ParallelDescriptor::NProcs(); ++i) {
std::string iuuid(pbuf+i*len, len);
if (i == ParallelDescriptor::MyProc()) {
my_uuid = iuuid;
}
++uuid_counts[iuuid];
}
num_devices_used = uuid_counts.size();
num_device_partners = uuid_counts[my_uuid];
#elif defined(AMREX_USE_SYCL)
auto const& d = *sycl_device;
if (d.has(sycl::aspect::ext_intel_device_info_uuid)) {
auto uuid = d.get_info<sycl::ext::intel::info::device::uuid>();
using id_t = decltype(uuid); // std::array<unsigned char,16>
using char_t = id_t::value_type; // unsigned char
int len = std::tuple_size<id_t>::value;
std::vector<char_t> buf(ParallelDescriptor::NProcs()*len);
char_t* pbuf = buf.data();
MPI_Allgather(uuid.data(), len,
ParallelDescriptor::Mpi_typemap<char_t>::type(),
pbuf, len,
ParallelDescriptor::Mpi_typemap<char_t>::type(),
ParallelDescriptor::Communicator());
using str_t = std::basic_string<char_t>;
std::map<str_t,int> uuid_counts;
str_t my_uuid;
for (int i = 0; i < ParallelDescriptor::NProcs(); ++i) {
str_t iuuid(pbuf+i*len, len);
if (i == ParallelDescriptor::MyProc()) {
my_uuid = iuuid;
}
++uuid_counts[iuuid];
}
num_devices_used = uuid_counts.size();
num_device_partners = uuid_counts[my_uuid];
#if 0
for (int i = 0; i < ParallelDescriptor::NProcs(); ++i) {
if (i == ParallelDescriptor::MyProc()) {
std::cout << "Proc. " << i << ": |";
for (auto x : uuid) {
std::cout << std::hex << static_cast<unsigned int>(x) << "|";
}
std::cout << '\n';;
}
ParallelDescriptor::Barrier();
}
#endif
}
#endif
AMREX_ALWAYS_ASSERT(num_device_partners > 0);
}
#endif /* AMREX_USE_MPI */
if (amrex::Verbose() && ! minimal) {
#if defined(AMREX_USE_CUDA)
amrex::Print() << "CUDA"
#elif defined(AMREX_USE_HIP)
amrex::Print() << "HIP"
#elif defined(AMREX_USE_SYCL)
amrex::Print() << "SYCL"
#endif
<< " initialized with " << num_devices_used
<< ((num_devices_used == 1) ? " device.\n"
: " devices.\n");
if (num_devices_used < ParallelDescriptor::NProcs() && ParallelDescriptor::IOProcessor()) {
amrex::Warning("There are more MPI processes than the number of unique GPU devices. This is not necessarily a problem.\n"
"For example this could happen when a device such as MI300A is partitioned into multiple subdevices.");
}
}
#if defined(AMREX_USE_CUDA) && (defined(AMREX_PROFILING) || defined(AMREX_TINY_PROFILING))
nvtxRangePop();
#endif
#if defined(AMREX_USE_HIP) && defined(HIP_VERSION_MAJOR) && (HIP_VERSION_MAJOR <= 6)
if (num_devices_used < 0) {
// This test is always false, but it makes the compiler no longer
// complain about unused function, amrex_check_wavefront_size.
amrex::single_task(amrex_check_wavefront_size);
}
#endif
Device::profilerStart();
#endif /* AMREX_USE_GPU */
}
void
Device::Finalize ()
{
#ifdef AMREX_USE_GPU
streamSynchronizeAll();
Device::profilerStop();
#ifdef AMREX_USE_SYCL
for (auto& s : gpu_stream_pool) {
delete s.getStream().queue;
s.getStream().queue = nullptr;
}
sycl_context.reset();
sycl_device.reset();
#else
for (int i = 0; i < max_gpu_streams; ++i)
{
AMREX_HIP_OR_CUDA( AMREX_HIP_SAFE_CALL( hipStreamDestroy(gpu_stream_pool[i].getStream()));,
AMREX_CUDA_SAFE_CALL(cudaStreamDestroy(gpu_stream_pool[i].getStream())); );
}
#endif
gpu_stream_index.clear();
#ifdef AMREX_USE_ACC
amrex_finalize_acc();
#endif
#endif
}
void
Device::initialize_gpu (bool minimal)
{
amrex::ignore_unused(minimal);
#ifdef AMREX_USE_GPU
if (gpu_stream_pool.size() != max_gpu_streams) {
// no copy/move constructor for std::mutex
gpu_stream_pool = Vector<StreamManager>(max_gpu_streams);
}
#ifdef AMREX_USE_HIP
AMREX_HIP_SAFE_CALL(hipGetDeviceProperties(&device_prop, device_id));
AMREX_ALWAYS_ASSERT_WITH_MESSAGE(warp_size == device_prop.warpSize, "Incorrect warp size");
// check compute capability
// AMD devices do not support shared cache banking.
for (int i = 0; i < max_gpu_streams; ++i) {
AMREX_HIP_SAFE_CALL(hipStreamCreate(&gpu_stream_pool[i].getStream()));
}
#ifdef AMREX_GPU_STREAM_ALLOC_SUPPORT
AMREX_HIP_SAFE_CALL(hipDeviceGetAttribute(&memory_pools_supported, hipDeviceAttributeMemoryPoolsSupported, device_id));
#endif
#elif defined(AMREX_USE_CUDA)
AMREX_CUDA_SAFE_CALL(cudaGetDeviceProperties(&device_prop, device_id));
AMREX_ALWAYS_ASSERT_WITH_MESSAGE(device_prop.major >= 4 || (device_prop.major == 3 && device_prop.minor >= 5),
"Compute capability must be >= 3.5");
#ifdef AMREX_GPU_STREAM_ALLOC_SUPPORT
cudaDeviceGetAttribute(&memory_pools_supported, cudaDevAttrMemoryPoolsSupported, device_id);
#endif
#if (__CUDACC_VER_MAJOR__ < 12) || ((__CUDACC_VER_MAJOR__ == 12) && (__CUDACC_VER_MINOR__ < 4))
if ( ! minimal ) {
if (sizeof(Real) == 8) {
AMREX_CUDA_SAFE_CALL(cudaDeviceSetSharedMemConfig(cudaSharedMemBankSizeEightByte));
} else if (sizeof(Real) == 4) {
AMREX_CUDA_SAFE_CALL(cudaDeviceSetSharedMemConfig(cudaSharedMemBankSizeFourByte));
}
}
#endif
for (int i = 0; i < max_gpu_streams; ++i) {
AMREX_CUDA_SAFE_CALL(cudaStreamCreate(&gpu_stream_pool[i].getStream()));
#ifdef AMREX_USE_ACC
acc_set_cuda_stream(i, gpu_stream_pool[i].getStream());
#endif
}
AMREX_ALWAYS_ASSERT_WITH_MESSAGE(warp_size == device_prop.warpSize, "Incorrect warp size");
#elif defined(AMREX_USE_SYCL)
{ // create device, context and queues
sycl::platform platform(sycl::gpu_selector_v);
auto const& gpu_devices = platform.get_devices();
sycl_device = std::make_unique<sycl::device>(gpu_devices[device_id]);
sycl_context = std::make_unique<sycl::context>(*sycl_device, amrex_sycl_error_handler);
for (int i = 0; i < max_gpu_streams; ++i) {
gpu_stream_pool[i].getStream().queue = new sycl::queue(*sycl_context, *sycl_device,
sycl::property_list{sycl::property::queue::in_order{}});
}
}
{ // device property
auto const& d = *sycl_device;
device_prop.name = d.get_info<sycl::info::device::name>();
device_prop.vendor = d.get_info<sycl::info::device::vendor>();
device_prop.totalGlobalMem = d.get_info<sycl::info::device::global_mem_size>();
device_prop.sharedMemPerBlock = d.get_info<sycl::info::device::local_mem_size>();
device_prop.multiProcessorCount = d.get_info<sycl::info::device::max_compute_units>();
device_prop.maxThreadsPerMultiProcessor = -1; // xxxxx SYCL todo: d.get_info<sycl::info::device::max_work_items_per_compute_unit>(); // unknown
device_prop.maxThreadsPerBlock = d.get_info<sycl::info::device::max_work_group_size>();
auto mtd = d.get_info<sycl::info::device::max_work_item_sizes<3>>();
device_prop.maxThreadsDim[0] = mtd[0];
device_prop.maxThreadsDim[1] = mtd[1];
device_prop.maxThreadsDim[2] = mtd[2];
device_prop.maxGridSize[0] = -1; // xxxxx SYCL todo: unknown
device_prop.maxGridSize[1] = -1; // unknown
device_prop.maxGridSize[2] = -1; // unknown
device_prop.warpSize = warp_size;
auto sgss = d.get_info<sycl::info::device::sub_group_sizes>();
device_prop.maxMemAllocSize = d.get_info<sycl::info::device::max_mem_alloc_size>();
device_prop.managedMemory = d.has(sycl::aspect::usm_host_allocations);
device_prop.concurrentManagedAccess = d.has(sycl::aspect::usm_shared_allocations);
device_prop.maxParameterSize = d.get_info<sycl::info::device::max_parameter_size>();
if (verbose)
{
amrex::Print() << "Device Properties:\n"
<< " name: " << device_prop.name << "\n"
<< " vendor: " << device_prop.vendor << "\n"
<< " totalGlobalMem: " << device_prop.totalGlobalMem << "\n"
<< " sharedMemPerBlock: " << device_prop.sharedMemPerBlock << "\n"
<< " multiProcessorCount: " << device_prop.multiProcessorCount << "\n"
<< " maxThreadsPerBlock: " << device_prop.maxThreadsPerBlock << "\n"
<< " maxThreadsDim: (" << device_prop.maxThreadsDim[0] << ", " << device_prop.maxThreadsDim[1] << ", " << device_prop.maxThreadsDim[2] << ")\n"
<< " warpSize:";
for (auto s : sgss) {
amrex::Print() << " " << s;
}
amrex::Print() << " (" << warp_size << " is used)\n"
<< " maxMemAllocSize: " << device_prop.maxMemAllocSize << "\n"
<< " managedMemory: " << (device_prop.managedMemory ? "Yes" : "No") << "\n"
<< " concurrentManagedAccess: " << (device_prop.concurrentManagedAccess ? "Yes" : "No") << "\n"
<< " maxParameterSize: " << device_prop.maxParameterSize << "\n"
<< '\n';
#if defined(__INTEL_LLVM_COMPILER)
if (d.has(sycl::aspect::ext_intel_gpu_eu_simd_width)) {
auto r = d.get_info<sycl::ext::intel::info::device::gpu_eu_simd_width>();
amrex::Print() << " Intel GPU Execution Unit SIMD Width: " << r << "\n";
}
if (d.has(sycl::aspect::ext_intel_gpu_eu_count)) {
auto r = d.get_info<sycl::ext::intel::info::device::gpu_eu_count>();
amrex::Print() << " Intel GPU Execution Unit Count: " << r << "\n";
}
if (d.has(sycl::aspect::ext_intel_gpu_slices)) {
auto r = d.get_info<sycl::ext::intel::info::device::gpu_slices>();
amrex::Print() << " Intel GPU Number of Slices: " << r << "\n";
}
if (d.has(sycl::aspect::ext_intel_gpu_subslices_per_slice)) {
auto r = d.get_info<sycl::ext::intel::info::device::gpu_subslices_per_slice>();
amrex::Print() << " Intel GPU Number of Subslices per Slice: " << r << "\n";
}
if (d.has(sycl::aspect::ext_intel_gpu_eu_count_per_subslice)) {
auto r = d.get_info<sycl::ext::intel::info::device::gpu_eu_count_per_subslice>();
amrex::Print() << " Intel GPU Number of EUs per Subslice: " << r << "\n";
}
if (d.has(sycl::aspect::ext_intel_gpu_hw_threads_per_eu)) {
auto r = d.get_info<sycl::ext::intel::info::device::gpu_hw_threads_per_eu>();
amrex::Print() << " Intel GPU Number of hardware threads per EU: " << r << "\n";
}
if (d.has(sycl::aspect::ext_intel_max_mem_bandwidth)) {
auto r = d.get_info<sycl::ext::intel::info::device::max_mem_bandwidth>();
amrex::Print() << " Intel GPU Maximum Memory Bandwidth (B/s): " << r << "\n";
}
#endif
}
auto found = std::ranges::find(sgss, static_cast<decltype(sgss)::value_type>(warp_size));
if (found == sgss.end()) { amrex::Abort("Incorrect subgroup size"); }
}
#endif
gpu_stream_index.resize(OpenMP::get_max_threads(), 0);
ParmParse pp("device");
int nx = 0;
int ny = 0;
int nz = 0;
pp.query("numThreads.x", nx);
pp.query("numThreads.y", ny);
pp.query("numThreads.z", nz);
numThreadsOverride.x = (int) nx;
numThreadsOverride.y = (int) ny;
numThreadsOverride.z = (int) nz;
nx = 0;
ny = 0;
nz = 0;
pp.query("numBlocks.x", nx);
pp.query("numBlocks.y", ny);
pp.query("numBlocks.z", nz);
numBlocksOverride.x = (int) nx;
numBlocksOverride.y = (int) ny;
numBlocksOverride.z = (int) nz;
// Graph initialization
int graph_init = 0;
int graph_size = 10000;
pp.query("graph_init", graph_init);
pp.query("graph_init_nodes", graph_size);
if (graph_init)
{
GraphSafeGuard gsg(true);
InitializeGraph(graph_size);
}
#ifdef AMREX_USE_SYCL
// max_blocks_per_launch = 100000; // xxxxx SYCL todo
#else
max_blocks_per_launch = 4 * numMultiProcessors() * maxThreadsPerMultiProcessor() / AMREX_GPU_MAX_THREADS;
#endif
#endif
}
int
Device::deviceId () noexcept
{
return device_id;
}
int
Device::numDevicesUsed () noexcept
{
return num_devices_used;
}
int Device::numDevicePartners () noexcept
{
return num_device_partners;
}
#ifdef AMREX_USE_GPU
int
Device::streamIndex (gpuStream_t s) noexcept
{
for (auto const& ext : external_stream_stack) {
AMREX_ASSERT(ext.manager != nullptr);
if (ext.manager->getStream() == s) {
return 0;
}
}
const int N = gpu_stream_pool.size();
for (int i = 0; i < N ; ++i) {
if (gpu_stream_pool[i].getStream() == s) {
return i;
}
}
return N;
}
#endif
void
Device::setStreamIndex (int idx) noexcept
{
amrex::ignore_unused(idx);
#ifdef AMREX_USE_GPU
gpu_stream_index[OpenMP::get_thread_num()] = idx % max_gpu_streams;
#ifdef AMREX_USE_ACC
amrex_set_acc_stream(idx % max_gpu_streams);
#endif
#endif
}
#ifdef AMREX_USE_GPU
gpuStream_t
Device::resetStream () noexcept
{
gpuStream_t r = gpuStream();
gpu_stream_index[OpenMP::get_thread_num()] = 0;
return r;
}
gpuStream_t
Device::setStream (gpuStream_t s) noexcept
{
int const tid = OpenMP::get_thread_num();
gpuStream_t r = gpuStream();
for (auto it = external_stream_stack.rbegin(); it != external_stream_stack.rend(); ++it) {
AMREX_ASSERT(it->manager != nullptr);
if (it->manager->getStream() == s) {
setStreamIndex(it->saved_stream_index);
return r;
}
}
int const idx = streamIndex(s);
if (idx == static_cast<int>(gpu_stream_pool.size())) {
amrex::Abort("Gpu::Device::setStream: stream is not managed by AMReX.");
}
gpu_stream_index[tid] = idx;
return r;
}
void
Device::setExternalStream (gpuStream_t s)
{
AMREX_ALWAYS_ASSERT_WITH_MESSAGE(!OpenMP::in_parallel(),
"Gpu::setExternalGpuStream is not supported inside OpenMP parallel regions.");
#if defined(AMREX_USE_CUDA)
# if defined(CUDART_VERSION) && (CUDART_VERSION >= 12080)
int stream_device = -1;
AMREX_CUDA_SAFE_CALL(cudaStreamGetDevice(s, &stream_device));
AMREX_ALWAYS_ASSERT_WITH_MESSAGE(stream_device == Device::deviceId(),
"Gpu::setExternalGpuStream: external CUDA stream must belong to the active device.");
# else
amrex::ignore_unused(s); // cudaStreamGetDevice arrived in CUDA 12.8.
# endif
#elif defined(AMREX_USE_HIP)
# if defined(HIP_VERSION_MAJOR) && defined(HIP_VERSION_MINOR) && \
((HIP_VERSION_MAJOR > 5) || (HIP_VERSION_MAJOR == 5 && HIP_VERSION_MINOR >= 6))
hipDevice_t stream_device = -1;
AMREX_HIP_SAFE_CALL(hipStreamGetDevice(s, &stream_device));
AMREX_ALWAYS_ASSERT_WITH_MESSAGE(stream_device == Device::deviceId(),
"Gpu::setExternalGpuStream: external HIP stream must belong to the active device.");
# else
amrex::ignore_unused(s); // hipStreamGetDevice landed in ROCm 5.6.
# endif
#endif
#ifdef AMREX_USE_SYCL
AMREX_ALWAYS_ASSERT_WITH_MESSAGE(s.queue != nullptr,
"Gpu::setExternalGpuStream: null SYCL queue is not supported.");
AMREX_ALWAYS_ASSERT_WITH_MESSAGE(s.queue->get_context() == Device::syclContext(),
"Gpu::setExternalGpuStream: external SYCL queue must use AMReX's SYCL context.");
AMREX_ALWAYS_ASSERT_WITH_MESSAGE(s.queue->get_device() == Device::syclDevice(),
"Gpu::setExternalGpuStream: external SYCL queue must use AMReX's SYCL device.");
AMREX_ALWAYS_ASSERT_WITH_MESSAGE(s.queue->has_property<sycl::property::queue::in_order>(),
"Gpu::setExternalGpuStream: external SYCL queue must be in-order.");
#endif
// External stream overrides intentionally do not try to synchronize
// OpenACC stream state. AMReX does not support mixing OpenACC work into
// these regions.
external_stream_stack.emplace_back(
ExternalStream{std::make_unique<StreamManager>(),
gpu_stream_index[OpenMP::get_thread_num()]});
external_stream_stack.back().manager->getStream() = s;
}
void
Device::resetExternalStream (ExternalStreamSync sync_stream) noexcept
{
AMREX_ALWAYS_ASSERT_WITH_MESSAGE(!OpenMP::in_parallel(),
"Gpu::resetExternalGpuStream is not supported inside OpenMP parallel regions.");
if (external_stream_stack.empty()) { return; }
auto& external_stream = external_stream_stack.back();
if (external_stream.manager) {
// ExternalStreamSync::No hands synchronization responsibility back to
// the caller. Once the stream is popped, AMReX no longer tracks it in
// global stream synchronization helpers, and it is the caller's
// responsibility to synchronize the external stream when needed.
if (sync_stream == ExternalStreamSync::Yes || external_stream.manager->wait_list_size() > 0) {
external_stream.manager->sync();
}
}
int const saved_stream_index = external_stream.saved_stream_index;
external_stream_stack.pop_back();
setStreamIndex(saved_stream_index);
}
bool
Device::usingExternalStream () noexcept
{
return !external_stream_stack.empty();
}
#endif
void
Device::synchronize ()
{
#ifdef AMREX_USE_GPU
AMREX_HIP_OR_CUDA( AMREX_HIP_SAFE_CALL(hipDeviceSynchronize());,
AMREX_CUDA_SAFE_CALL(cudaDeviceSynchronize()); )
// After the device-wide sync completes, synchronizing all AMReX-managed
// streams is cheap and drains deferred frees queued on their managers.
streamSynchronizeAll();
#endif
}
void
Device::streamSynchronize () noexcept
{
#ifdef AMREX_USE_GPU
if (!external_stream_stack.empty()) {
AMREX_ASSERT(external_stream_stack.back().manager != nullptr);
external_stream_stack.back().manager->sync();
} else {
int tid = OpenMP::get_thread_num();
gpu_stream_pool[gpu_stream_index[tid]].sync();
}
#endif
}
#ifdef AMREX_USE_GPU
void
Device::streamSynchronize (gpuStream_t s) noexcept
{
bool found_external = false;
for (auto& ext : external_stream_stack) {
AMREX_ASSERT(ext.manager != nullptr);
if (ext.manager->getStream() == s) {
ext.manager->sync();
found_external = true;
}
}
if (found_external) {
return;
}
for (auto& mgr : gpu_stream_pool) {
if (mgr.getStream() == s) {
mgr.sync();
return;
}
}
#if defined(AMREX_USE_SYCL)
if (s.queue != nullptr) {
try {
s.queue->wait_and_throw();
} catch (sycl::exception const& ex) {
amrex::Abort(std::string("streamSynchronize(stream): ")+ex.what()+"!!!!!");
}
} else {
amrex::Abort("streamSynchronize(stream): unknown SYCL stream.");
}
#else
AMREX_HIP_OR_CUDA(
AMREX_HIP_SAFE_CALL(hipStreamSynchronize(s));,
AMREX_CUDA_SAFE_CALL(cudaStreamSynchronize(s)); )
#endif
}
#endif
void
Device::streamSynchronizeActive () noexcept
{
#ifdef AMREX_USE_GPU
if (Gpu::inSingleStreamRegion()) {
Gpu::streamSynchronize();
} else {
Gpu::streamSynchronizeAll();
}
#endif
}
void
Device::streamSynchronizeAll () noexcept
{
#ifdef AMREX_USE_GPU
for (auto& ext : external_stream_stack) {
if (ext.manager) {
ext.manager->sync();
}
}
for (auto& s : gpu_stream_pool) {
s.sync();
}
#endif
}
void
Device::freeAsync (Arena* arena, void* mem) noexcept
{
#ifdef AMREX_USE_GPU
if (!external_stream_stack.empty()) {
AMREX_ASSERT(external_stream_stack.back().manager != nullptr);
external_stream_stack.back().manager->free_async(arena, mem);
} else {
int tid = OpenMP::get_thread_num();
gpu_stream_pool[gpu_stream_index[tid]].free_async(arena, mem);
}
#else
arena->free(mem);
#endif
}
#ifdef AMREX_USE_GPU
void
Device::streamOrderedFreeAsync (Arena* arena, void* mem, gpuStream_t stream) noexcept
{
for (auto it = external_stream_stack.rbegin(); it != external_stream_stack.rend(); ++it) {
AMREX_ASSERT(it->manager != nullptr);
if (it->manager->getStream() == stream) {
it->manager->free_async(arena, mem);
return;
}
}
for (auto& mgr : gpu_stream_pool) {
if (mgr.getStream() == stream) {
mgr.free_async(arena, mem);
return;
}
}
amrex::Abort("Gpu::Device::streamOrderedFreeAsync: stream is not managed by AMReX. "
"If this is an external stream, it must still be active when stream-ordered "
"memory is freed.");
}
#endif
bool
Device::clearFreeAsyncBuffer () noexcept
{
#ifdef AMREX_USE_GPU
bool freed_memory = false;
for (auto& s : gpu_stream_pool) {
if (s.wait_list_size() > 0) {
s.sync();
freed_memory = true;
}
}
for (auto& ext : external_stream_stack) {
AMREX_ASSERT(ext.manager != nullptr);
if (ext.manager->wait_list_size() > 0) {
ext.manager->sync();
freed_memory = true;
}
}
return freed_memory;
#else
return false;
#endif
}
#if defined(__CUDACC__) && defined(AMREX_USE_CUDA)