Alien  1.3.0
User documentation
Loading...
Searching...
No Matches
SYCLKernelInternal.h
1// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
2//-----------------------------------------------------------------------------
3// Copyright 2000-2026 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com)
4// See the top-level COPYRIGHT file for details.
5// SPDX-License-Identifier: Apache-2.0
6//-----------------------------------------------------------------------------
7
8#pragma once
9
10#include <alien/kernels/sycl/SYCLPrecomp.h>
11
12#ifdef USE_SYCL2020
13#include <sycl/sycl.hpp>
14#else
15#include <CL/sycl.hpp>
16#endif
17/*---------------------------------------------------------------------------*/
18
19namespace Alien::SYCLInternal
20{
21
22#ifndef USE_SYCL2020
23 using namespace cl ;
24#endif
25/*---------------------------------------------------------------------------*/
26namespace mi300 {
27
28static constexpr int WAVEFRONT = 64; // WF natif gfx942
29static constexpr int N_WARPS_BLOC = WG_SIZE / WAVEFRONT; // 4
30
31 template<typename ValueT, typename ReadAccessorT, typename ReadWriteAccessorT>
32 void dot_kernel_mi300(
33 sycl::nd_item<1> item,
34 ReadAccessorT x,
35 ReadAccessorT y,
36 ReadWriteAccessorT partials,
37 size_t N,
38 sycl::local_accessor<ValueT,1> lds)
39 {
40 const size_t gid = item.get_global_id(0);
41 const size_t stride = item.get_global_range(0);
42 const size_t lid = item.get_local_id(0);
43
44 // ── Phase 1a : accumulation avec unroll ───────────────────────────────
45 // Sur MI300, le backend HIP émet des GLOBAL_LOAD_DWORDX2 (64-bit loads).
46 // ITEMS_PER_WI=8 → 8 loads double indépendants = ILP pour masquer ~400 cy HBM3.
47 // La boucle strided garantit la coalescence : WI consécutifs (gid, gid+1, ...)
48 // accèdent à des adresses consécutives → 1 transaction mémoire pour 64 WI.
49 ValueT acc = 0;
50
51 const size_t stride_wi = stride * ITEMS_PER_WI;
52 size_t i = gid * ITEMS_PER_WI;
53
54 for (; i + ITEMS_PER_WI * stride <= N; i += stride_wi) {
55 // Unroll 8× — le compilateur AMDGCNx émet des v_fma_f64 indépendants
56 // → jusqu'à 2 FMA doubles/cycle sur les SIMD gfx942
57 #pragma unroll
58 for (size_t k = 0; k < ITEMS_PER_WI; ++k)
59 acc += x[i + k * stride] * y[i + k * stride];
60 }
61 // Epilogue
62 for (size_t j = gid; j < N; j += stride)
63 acc += x[j] * y[j];
64
65 // ── Phase 1b : réduction wavefront (sub_group) ────────────────────────
66 // Sur gfx942, reduce_over_group<plus<double>> se compile en :
67 // ds_swizzle_b32 / v_readlane_b32 / v_writelane_b32
68 // soit 6 niveaux de shuffle pour 64 threads — zéro accès LDS ici.
69 // IMPORTANT : sub_group_size(64) est annoté sur le kernel pour forcer
70 // l'émission de la séquence WF=64 (vs WF=32 qui nécessiterait 5 niveaux
71 // mais casserait la coalescence des loads précédents).
72 auto sg = item.get_sub_group();
73 acc = reduce_over_group(sg, acc, sycl::plus<ValueT>{});
74
75 // ── Phase 1c : réduction inter-wavefront via LDS ──────────────────────
76 // 4 wavefronts → 4 valeurs LDS = 32 bytes (tient dans 1 cache line LDS)
77 const size_t wf_id = lid / WAVEFRONT;
78 const size_t lane_id = lid % WAVEFRONT;
79
80 if (lane_id == 0)
81 lds[wf_id] = acc;
82
83 item.barrier(sycl::access::fence_space::local_space);
84
85 // Le premier wavefront charge les 4 partiels LDS et les réduit
86 if (wf_id == 0) {
87 // Lane 0..3 chargent les 4 partiels, lanes 4..63 chargent 0
88 ValueT val = (lid < N_WARPS_BLOC) ? lds[lid] : 0.0;
89 // Réduction sur le sous-groupe — sur les 64 lanes du WF0
90 // seuls les 4 premiers portent des données, le reste est neutre (0.0)
91 val = sycl::reduce_over_group(sg, val, sycl::plus<ValueT>{});
92 if (lane_id == 0)
93 partials[item.get_group(0)] = val;
94 }
95 }
96
97 // ---------------------------------------------------------------------------
98 // Variante avec double buffering explicite — masque davantage la latence HBM3
99 // Recommandée pour très grands N (> 500 M doubles) où la latence domine.
100 // ---------------------------------------------------------------------------
101 template<typename ValueT, typename ReadAccessorT, typename ReadWriteAccessorT>
102 void dot_kernel_mi300_doublebuf(
103 sycl::nd_item<1> item,
104 ReadAccessorT x,
105 ReadAccessorT y,
106 ReadWriteAccessorT partials,
107 size_t N,
108 sycl::local_accessor<ValueT,1> lds)
109 {
110 const size_t gid = item.get_global_id(0);
111 const size_t stride = item.get_global_range(0);
112 const size_t lid = item.get_local_id(0);
113
114 ValueT acc0 = 0, acc1 = 0; // Deux accumulateurs → 2 chaînes FMA indép.
115
116 // Double-stride : deux éléments par itération sur des adresses distantes
117 // → deux séquences de loads indépendantes dans le scoreboard
118 for (size_t i = gid; i + stride < N; i += 2 * stride) {
119 ValueT x0 = x[i], y0 = y[i];
120 ValueT x1 = x[i + stride], y1 = y[i + stride];
121 acc0 += x0 * y0;
122 acc1 += x1 * y1;
123 }
124 // Fusionner + epilogue
125 ValueT acc = acc0 + acc1;
126 for (size_t i = gid + ((N / (2*stride)) * 2 * stride); i < N; i += stride)
127 acc += x[i] * y[i];
128
129 auto sg = item.get_sub_group();
130 acc = sycl::reduce_over_group(sg, acc, sycl::plus<ValueT>{});
131
132 const size_t wf_id = lid / WAVEFRONT;
133 const size_t lane_id = lid % WAVEFRONT;
134 if (lane_id == 0) lds[wf_id] = acc;
135 item.barrier(sycl::access::fence_space::local_space);
136 if (wf_id == 0) {
137 ValueT val = (lid < N_WARPS_BLOC) ? lds[lid] : 0.0;
138 val = reduce_over_group(sg, val, sycl::plus<double>{});
139 if (lane_id == 0)
140 partials[item.get_group(0)] = val;
141 }
142 }
143}
144
145
146namespace h100 {
147
148template<typename ValueT, typename ReadAccessorT, typename ReadWriteAccessorT>
149void dot_kernel_h100(
150 sycl::nd_item<1> item,
151 ReadAccessorT x,
152 ReadAccessorT y,
153 ReadWriteAccessorT partials, // USM device — 1 double par bloc
154 std::size_t N,
155 sycl::local_accessor<ValueT,1> lds) // LDS : WG_SIZE/WARP_SIZE doubles
156{
157 using namespace std;
158 using namespace sycl;
159 const size_t gid = item.get_global_id(0);
160 const size_t stride = item.get_global_range(0);
161 const size_t lid = item.get_local_id(0);
162
163 // ── Phase 1a : accumulation locale avec unroll ─────────────────────────
164 // Chaque WI traite ITEMS_PER_WI éléments strided pour coalescence.
165 // Le compilateur NVPTX génère des LDG.128 (128-bit loads) si aligné.
166 double acc = 0.0;
167
168 // Boucle principale — stride de global_range pour couvrir tout N
169 size_t i = gid * ITEMS_PER_WI;
170 const size_t stride_wi = stride * ITEMS_PER_WI;
171
172 for (; i + ITEMS_PER_WI * stride <= N; i += stride_wi) {
173 // Unroll explicite — 8 FMA indépendants → ILP maximal
174 // Le compilateur H100 peut émettre 4 FMA doubles/cycle/SM
175 #pragma unroll
176 for (size_t k = 0; k < ITEMS_PER_WI; ++k)
177 acc += x[i + k * stride] * y[i + k * stride];
178 }
179 // Epilogue — éléments restants
180 for (size_t j = gid; j < N; j += stride)
181 acc += x[j] * y[j];
182
183 // ── Phase 1b : réduction warp-shuffle (sub_group) ─────────────────────
184 // sycl::reduce_over_group utilise les shuffles natifs PTX (__shfl_down)
185 // sur H100 — 5 niveaux pour 32 threads, zéro accès mémoire.
186 auto sg = item.get_sub_group();
187 acc = sycl::reduce_over_group(sg, acc, sycl::plus<ValueT>{});
188
189 // ── Phase 1c : réduction inter-warp via LDS ───────────────────────────
190 // Un seul thread leader par warp écrit en LDS.
191 // LDS = WG_SIZE/WARP_SIZE = 16 doubles = 128 bytes — tient dans 1 cache line
192 const size_t warp_id = lid / WARP_SIZE;
193 const size_t lane_id = lid % WARP_SIZE;
194 const size_t n_warps = WG_SIZE / WARP_SIZE; // 16
195
196 if (lane_id == 0)
197 lds[warp_id] = acc;
198
199 item.barrier(access::fence_space::local_space);
200
201 // Réduction finale des 16 valeurs LDS par le premier warp
202 if (warp_id == 0) {
203 ValueT val = (lid < n_warps) ? lds[lid] : 0.0;
204 val = reduce_over_group(sg, val, sycl::plus<ValueT>{});
205 if (lane_id == 0)
206 partials[item.get_group(0)] = val;
207 }
208}
209}
210
211template <typename T>
212class Future
213{
214 public:
215 using FunctionType = std::function<T(sycl::event&,sycl::buffer<T>&,std::size_t)>;
216 Future(T& value)
217 : m_value(value)
218 //, m_d_value{1}
219 , m_d_value{ SYCLEnv::instance()->maxNumGroups() * TARGET_WAVES }
220 {
221 }
222
223 T& operator()()
224 {
225 //alien_info([&] { cout()<<"SYCL FUTURE value="<<m_value; });
226 return m_value;
227 }
228
229 T operator()() const
230 {
231 return m_value;
232 }
233
234 T get()
235 {
236 if (m_parallel_mng)
237 {
238 Arccore::MessagePassing::mpWait(m_parallel_mng, m_request);
239 m_parallel_mng = nullptr;
240 }
241 else
242 {
243 if(m_wait_function)
244 {
245 m_value = m_wait_function(m_event,m_d_value,m_num_blocks) ;
246 m_wait_function = nullptr ;
247 }
248 }
249 return m_value;
250 }
251
252 sycl::buffer<T, 1>& deviceValue()
253 {
254 return m_d_value;
255 }
256
257 sycl::event& event() {
258 return m_event;
259 }
260
261
262 void addRequest(Arccore::MessagePassing::IMessagePassingMng* parallel_mng,
263 Arccore::MessagePassing::Request request)
264 {
265 m_parallel_mng = parallel_mng;
266 m_request = request;
267 }
268
269 void setWaitFunction(FunctionType wait_function)
270 {
271 m_wait_function = wait_function;
272 }
273
274 void setNumBlocks(std::size_t num_blocks)
275 {
276 m_num_blocks = num_blocks;
277 }
278
279 private:
280 T& m_value;
281 sycl::buffer<T, 1> m_d_value;
282 sycl::event m_event;
283 FunctionType m_wait_function = nullptr;
284 std::size_t m_num_blocks = SYCLEnv::instance()->maxNumGroups() * TARGET_WAVES ;
285
286 Arccore::MessagePassing::IMessagePassingMng* m_parallel_mng = nullptr;
287 Arccore::MessagePassing::Request m_request;
288};
289
290class KernelInternal
291{
292 private:
293 int m_dot_algo = 3;
294
295 public:
296 KernelInternal()
297 {
298 m_env = SYCLEnv::instance();
299
300 // clang-format off
301 m_max_num_groups = m_env->maxNumGroups() ;
302 m_max_work_group_size = m_env->maxWorkGroupSize() ;
303 m_total_threads = m_env->maxNumThreads() ;
304 // clang-format on
305 }
306
307 virtual ~KernelInternal() {}
308
309 void setDotAlgo(int dot_algo)
310 {
311 m_dot_algo = dot_algo;
312 }
313
314 template <typename T>
315 void assign(T const a,
316 sycl::buffer<T>& y)
317 {
318 m_env->internal()->queue().submit(
319 [&](sycl::handler& cgh)
320 {
321 auto acc = y.template get_access<sycl::access::mode::discard_write>(cgh);
322 cgh.fill(acc, a);
323 });
324 /*
325 sycl::range<1> work_items{ m_total_threads };
326 {
327 // clang-format off
328 m_env->internal()->queue().submit( [&](sycl::handler& cgh)
329 {
330 auto access_y = y.template get_access<sycl::access::mode::read_write>(cgh);
331 auto y_length = y.size() ;
332 cgh.parallel_for<class vector_assign>(sycl::range<1>{m_total_threads}, [=] (sycl::item<1> itemId)
333 {
334 auto id = itemId.get_id(0);
335 for (auto i = id; i < y_length; i += itemId.get_range()[0])
336 access_y[i] = a;
337 });
338 });
339 // clang-format on
340 }*/
341 }
342
343 template <typename T, typename Lambda>
344 void apply(Lambda const& lambda,
345 sycl::buffer<T>& y)
346 {
347 sycl::range<1> work_items{ m_total_threads };
348 {
349 // clang-format off
350 m_env->internal()->queue().submit( [&](sycl::handler& cgh)
351 {
352 auto access_y = y.template get_access<sycl::access::mode::read_write>(cgh);
353 auto y_length = y.size() ;
354 cgh.parallel_for<class vector_apply>(sycl::range<1>{m_total_threads}, [=] (sycl::item<1> itemId)
355 {
356 auto id = itemId.get_id(0);
357 for (auto i = id; i < y_length; i += itemId.get_range()[0])
358 access_y[i] = lambda(i);
359 });
360 });
361 // clang-format on
362 }
363 }
364
365#ifdef USE_NAIVE
366 template <typename T>
367 void scal(T a,
368 sycl::buffer<T>& y)
369 {
370 sycl::range<1> work_items{ m_total_threads };
371 {
372 // clang-format off
373 m_env->internal()->queue().submit([&](sycl::handler& cgh)
374 {
375 auto access_y = y.template get_access<sycl::access::mode::read_write>(cgh);
376 auto y_length = y.size() ;
377 cgh.parallel_for<class vector_scal>(sycl::range<1>{m_total_threads}, [=] (sycl::item<1> itemId)
378 {
379 auto id = itemId.get_id(0);
380 for (auto i = id; i < y_length; i += itemId.get_range()[0])
381 access_y[i] = a*access_y[i];
382 });
383 });
384 // clang-format on
385 }
386 }
387
388 template <typename T>
389 void axpy(T const a,
390 sycl::buffer<T>& x,
391 sycl::buffer<T>& y)
392 {
393 sycl::range<1> work_items{ m_total_threads };
394 {
395 // clang-format off
396 m_env->internal()->queue().submit([&](sycl::handler& cgh)
397 {
398 auto access_x = x.template get_access<sycl::access::mode::read>(cgh);
399 auto access_y = y.template get_access<sycl::access::mode::read_write>(cgh);
400 auto y_length = y.size() ;
401 cgh.parallel_for<class vector_axpy>(sycl::range<1>{m_total_threads}, [=] (sycl::item<1> itemId)
402 {
403 auto id = itemId.get_id(0);
404 for (auto i = id; i < y_length; i += itemId.get_range()[0])
405 access_y[i] += a * access_x[i];
406 });
407 });
408 // clang-format on
409 }
410 }
411#else
412 template <typename T>
413 void scal(T a,
414 sycl::buffer<T>& y)
415 {
416 constexpr int W = (16 / sizeof(T)) > 0 ? int(16 / sizeof(T)) : 1;
417 using VecT = sycl::vec<T, W>;
418
419 auto& queue = m_env->internal()->queue();
420 const std::size_t n = y.size();
421 if (n == 0)
422 return;
423
424 const std::size_t nv = n / W; // nombre de vecteurs complets
425
426 constexpr std::size_t WG = 256;
427 const std::size_t groups =
428 std::max<std::size_t>(1,std::min((nv + WG - 1) / WG,
429 size_t(m_max_num_groups) * 8));
430 const std::size_t total = groups * WG;
431
432 queue.submit(
433 [&](sycl::handler& cgh)
434 {
435 sycl::accessor ay{ y, cgh, sycl::read_write };
436
437 cgh.parallel_for<class vector_xcal_vec>(
438 sycl::nd_range<1>{ {total}, {WG} },
439 [=](sycl::nd_item<1> item)
440 {
441 T* p = &ay[0];
442 const size_t id = item.get_global_id(0);
443 const size_t stride = item.get_global_range()[0];
444 if (reinterpret_cast<uintptr_t>(p) % alignof(VecT) == 0)
445 {
446 VecT* pv = reinterpret_cast<VecT*>(p);
447 for (size_t i = id; i < nv; i += stride)
448 {
449 pv[i] = a * pv[i] ;
450 }
451 if ((n & 1) && id == 0) p[n-1] *= a;
452 }
453 else
454 {
455 for (size_t i = id; i < n; i += stride)
456 p[i] *= a;
457 }
458 });
459 });
460
461 }
462
463 template <typename T>
464 void axpy(T const a,
465 sycl::buffer<T>& x,
466 sycl::buffer<T>& y)
467 {
468 // Largeur vectorielle pour des accès de 128 bits : double -> 2, float -> 4
469 constexpr int W = (16 / sizeof(T)) > 0 ? int(16 / sizeof(T)) : 1;
470 using VecT = sycl::vec<T, W>;
471
472 auto& queue = m_env->internal()->queue();
473 const std::size_t n = y.size();
474 if (n == 0)
475 return;
476
477 const std::size_t nv = n / W; // éléments traités vectoriellement
478
479 constexpr std::size_t WG = 256;
480 const std::size_t groups = std::max<size_t>(1,
481 std::min((nv + WG - 1) / WG,
482 size_t(m_max_num_groups) * 8));
483 const std::size_t total = groups * WG;
484
485
486 queue.submit([&](sycl::handler& cgh)
487 {
488 sycl::accessor ax{ x, cgh, sycl::read_only };
489 sycl::accessor ay{ y, cgh, sycl::read_write };
490
491 cgh.parallel_for<class vector_axpy_buffer_vec>(
492 sycl::nd_range<1>{ sycl::range<1>{ total }, sycl::range<1>{ WG } },
493 [=](sycl::nd_item<1> it) {
494 const T* px = &ax[0];
495 T* py = &ay[0];
496
497 const size_t gid = it.get_global_id(0);
498 const size_t stride = it.get_global_range(0);
499
500 const bool aligned =
501 (reinterpret_cast<uintptr_t>(px) % alignof(VecT) == 0) &&
502 (reinterpret_cast<uintptr_t>(py) % alignof(VecT) == 0);
503
504 if (aligned) {
505 const VecT* vx = reinterpret_cast<const VecT*>(px);
506 VecT* vy = reinterpret_cast<VecT*>(py);
507
508 // Corps vectorisé : un LDG.128 sur x, un sur y, un STG.128 sur y
509 for (size_t i = gid; i < nv; i += stride)
510 vy[i] = vy[i] + a * vx[i];
511
512 // Queue (n % W éléments), traitée en scalaire
513 for (size_t i = nv * W + gid; i < n; i += stride)
514 py[i] += a * px[i];
515 }
516 else
517 {
518 // Repli scalaire si les pointeurs ne sont pas alignés (sous-buffer, offset...)
519 for (size_t i = gid; i < n; i += stride)
520 py[i] += a * px[i];
521 }
522 });
523 });
524 }
525#endif
526
527 template <typename T>
528 void axpy(T const a,
529 sycl::buffer<T>& x,
530 Integer stride_x,
531 sycl::buffer<T>& y,
532 Integer stride_y)
533 {
534 sycl::range<1> work_items{ m_total_threads };
535 {
536 // clang-format off
537 m_env->internal()->queue().submit([&](sycl::handler& cgh)
538 {
539 auto access_x = x.template get_access<sycl::access::mode::read>(cgh);
540 auto access_y = y.template get_access<sycl::access::mode::read_write>(cgh);
541 auto x_length = x.size()/stride_x ;
542 cgh.parallel_for<class vector_axpy>(sycl::range<1>{m_total_threads}, [=] (sycl::item<1> itemId)
543 {
544 auto id = itemId.get_id(0);
545 for (auto i = id; i < x_length; i += itemId.get_range()[0])
546 access_y[i*stride_y] += a * access_x[i*stride_x];
547 });
548 });
549 // clang-format on
550 }
551 }
552
553 template <typename T>
554 void axpy(T const a,
555 sycl::buffer<T>& x,
556 sycl::buffer<T>& y,
557 ConstArrayView<Integer> stride_y)
558 {
559 sycl::range<1> work_items{ m_total_threads };
560
561 auto x_length = x.size() ;
562 sycl::buffer<Integer, 1> s(stride_y.unguardedBasePointer(),sycl::range<1>(x_length));
563 {
564 // clang-format off
565 m_env->internal()->queue().submit([&](sycl::handler& cgh)
566 {
567 auto access_x = x.template get_access<sycl::access::mode::read>(cgh);
568 auto access_s = s.template get_access<sycl::access::mode::read>(cgh);
569 auto access_y = y.template get_access<sycl::access::mode::read_write>(cgh);
570 cgh.parallel_for<class vector_axpy_s>(sycl::range<1>{m_total_threads}, [=] (sycl::item<1> itemId)
571 {
572 auto id = itemId.get_id(0);
573 for (auto i = id; i < x_length; i += itemId.get_range()[0])
574 access_y[access_s[i]] += a * access_x[i];
575 });
576 });
577 // clang-format on
578 }
579 }
580
581 template <typename T>
582 void pointwiseMult(sycl::buffer<T>& x,
583 sycl::buffer<T>& y,
584 sycl::buffer<T>& z)
585 {
586#ifdef NAIVE
587 sycl::range<1> work_items{ m_total_threads };
588 {
589 // clang-format off
590 m_env->internal()->queue().submit([&](sycl::handler& cgh)
591 {
592 auto access_x = x.template get_access<sycl::access::mode::read>(cgh);
593 auto access_y = y.template get_access<sycl::access::mode::read>(cgh);
594 auto access_z = z.template get_access<sycl::access::mode::read_write>(cgh);
595 auto y_length = y.size() ;
596 cgh.parallel_for<class vector_pointwizemult>(sycl::range<1>{m_total_threads}, [=] (sycl::item<1> itemId)
597 {
598 auto id = itemId.get_id(0);
599 for (auto i = id; i < y_length; i += itemId.get_range()[0])
600 access_z[i] = access_x[i] * access_y[i];
601 });
602 });
603 // clang-format on
604 }
605#endif
606 using VecT = sycl::vec<T, 2>;
607
608 auto& queue = m_env->internal()->queue();
609 const size_t n = y.size();
610 const size_t n2 = n / 2; // éléments traités vectoriellement
611 const size_t tail = n % 2;
612
613 static constexpr size_t WG_SIZE = 256;
614 const size_t blocks = std::max((n2 + WG_SIZE - 1) / WG_SIZE,
615 m_max_num_groups * 4UL);
616 const size_t total = blocks * WG_SIZE;
617
618 // ── Reinterprétation des buffers en vec<T,2> ──────────────────────────
619 // Requiert que les buffers soient alignés 16 bytes (garantit par
620 // sycl::buffer qui aligne sur max_required_work_group_size).
621 sycl::buffer<VecT> x2{ x.template reinterpret<VecT>(sycl::range<1>{n2}) };
622 sycl::buffer<VecT> y2{ y.template reinterpret<VecT>(sycl::range<1>{n2}) };
623 sycl::buffer<VecT> z2{ z.template reinterpret<VecT>(sycl::range<1>{n2}) };
624
625 queue.submit([&](sycl::handler& cgh) {
626 auto ax = x2.template get_access<sycl::access::mode::read>(cgh);
627 auto ay = y2.template get_access<sycl::access::mode::read>(cgh);
628 auto az = z2.template get_access<sycl::access::mode::read_write>(cgh);
629
630 cgh.parallel_for<class vector_pointwizemult>(
631 sycl::nd_range<1>{ {total}, {WG_SIZE} },
632 [=](sycl::nd_item<1> item) {
633 const size_t stride = item.get_global_range()[0];
634 for (size_t i = item.get_global_id(0); i < n2; i += stride) {
635 // Un seul load 128-bit pour x, un pour y
636 az[i] = ax[i] * ay[i]; // fused multiply-add
637 }
638 });
639 });
640
641 // Epilogue scalaire si n est impair (rare en pratique)
642 if (tail) {
643 sycl::buffer<T> xt{ x.template reinterpret<T>(sycl::range<1>{n}) };
644 sycl::buffer<T> yt{ y.template reinterpret<T>(sycl::range<1>{n}) };
645 sycl::buffer<T> zt{ z.template reinterpret<T>(sycl::range<1>{n}) };
646 queue.submit([&](sycl::handler& cgh) {
647 auto ax = xt.template get_access<sycl::access::mode::read>(cgh);
648 auto ay = yt.template get_access<sycl::access::mode::read>(cgh);
649 auto az = zt.template get_access<sycl::access::mode::read_write>(cgh);
650 cgh.single_task([=]{ az[n-1] = ax[n-1] * ay[n-1]; });
651 });
652 }
653
654#ifdef PRINT_DEBUG_INFO
655 {
656 sycl::host_accessor<T, 1, sycl::access::mode::read> x_acc(x);
657 sycl::host_accessor<T, 1, sycl::access::mode::read> y_acc(y);
658 sycl::host_accessor<T, 1, sycl::access::mode::read> z_acc(z);
659 for(int il=0;il<x.size();++il)
660 {
661 std::cout<<"X Y Z ["<<il<<"] : "<<x_acc[il]<<"*"<<y_acc[il]<<"="<<z_acc[il]<<std::endl ;
662 }
663 }
664#endif
665 }
666
667 template <typename T>
668 void copy(sycl::buffer<T>& x,
669 sycl::buffer<T>& y)
670 {
671 //sycl::range<1> work_items{ m_total_threads };
672 {
673 // clang-format off
674 m_env->internal()->queue().submit(
675 [&](sycl::handler& cgh)
676 {
677 auto access_x = x.template get_access<sycl::access::mode::read>(cgh);
678 auto access_y = y.template get_access<sycl::access::mode::discard_write>(cgh);
679 cgh.copy(access_x,access_y) ;
680 /*
681 auto y_length = y.size() ;
682 cgh.parallel_for<class vector_copy>(sycl::range<1>{m_total_threads}, [=] (sycl::item<1> itemId)
683 {
684 auto id = itemId.get_id(0);
685 for (auto i = id; i < y_length; i += itemId.get_range()[0])
686 access_y[i] = access_x[i];
687 });
688 */
689 });
690 // clang-format on
691 }
692 }
693
694 template <typename T>
695 void copy(sycl::buffer<T>& x,
696 Integer stride_x,
697 sycl::buffer<T>& y,
698 Integer stride_y)
699 {
700 sycl::range<1> work_items{ m_total_threads };
701 {
702 // clang-format off
703 m_env->internal()->queue().submit( [&](sycl::handler& cgh)
704 {
705 auto access_x = x.template get_access<sycl::access::mode::read>(cgh);
706 auto access_y = y.template get_access<sycl::access::mode::read_write>(cgh);
707 auto x_length = x.size()/stride_x ;
708 cgh.parallel_for<class vector_copy>(sycl::range<1>{m_total_threads}, [=] (sycl::item<1> itemId)
709 {
710 auto id = itemId.get_id(0);
711 for (auto i = id; i < x_length; i += itemId.get_range()[0])
712 access_y[i*stride_y] = access_x[i*stride_x];
713 });
714 });
715 // clang-format on
716 }
717 }
718
719 template <typename T>
720 void copy(sycl::buffer<T>& x,
721 ConstArrayView<Integer> stride_x,
722 sycl::buffer<T>& y)
723 {
724 auto y_length = y.size();
725 sycl::buffer<Integer, 1> s(stride_x.unguardedBasePointer(),sycl::range<1>(y_length));
726 sycl::range<1> work_items{ m_total_threads };
727 {
728 // clang-format off
729 m_env->internal()->queue().submit(
730 [&](sycl::handler& cgh)
731 {
732 auto access_x = x.template get_access<sycl::access::mode::read>(cgh);
733 auto access_y = y.template get_access<sycl::access::mode::read_write>(cgh);
734 auto access_s = x.template get_access<sycl::access::mode::read>(cgh);
735 cgh.parallel_for<class vector_copy_sx>(sycl::range<1>{m_total_threads}, [=] (sycl::item<1> itemId)
736 {
737 auto id = itemId.get_id(0);
738 for (auto i = id; i < y_length; i += itemId.get_range()[0])
739 access_y[i] = access_x[access_s[i]];
740 });
741 });
742 // clang-format on
743 }
744 }
745
746 template <typename T>
747 void copy(sycl::buffer<T>& x,
748 sycl::buffer<T>& y,
749 ConstArrayView<Integer> stride_y)
750 {
751 auto x_length = x.size();
752 sycl::buffer<Integer, 1> s(stride_y.unguardedBasePointer(),sycl::range<1>(x_length));
753 sycl::range<1> work_items{ m_total_threads };
754 {
755 // clang-format off
756 m_env->internal()->queue().submit(
757 [&](sycl::handler& cgh)
758 {
759 auto access_x = x.template get_access<sycl::access::mode::read>(cgh);
760 auto access_y = y.template get_access<sycl::access::mode::read_write>(cgh);
761 auto access_s = x.template get_access<sycl::access::mode::read>(cgh);
762 cgh.parallel_for<class vector_copy_sy>(sycl::range<1>{m_total_threads}, [=] (sycl::item<1> itemId)
763 {
764 auto id = itemId.get_id(0);
765 for (auto i = id; i < x_length; i += itemId.get_range()[0])
766 access_y[access_s[i]] = access_x[i];
767 });
768 });
769 // clang-format on
770 }
771 }
772
773 template <typename T>
775 {
776 };
777
778 // to make global size multiple of local size
779 template <typename index_t>
780 inline index_t round_up(const index_t x, const index_t y)
781 {
782 return ((x + y - 1) / y) * y;
783 }
784
785 template <typename T>
787
788 template <typename T>
789 T reduce_sum(sycl::buffer<T>& x,
790 sycl::buffer<T>& y)
791 {
792
793 auto& w = getWorkBuffer<T>(x.size());
794
795 // clang-format off
796 m_env->internal()->queue().submit( [&](sycl::handler& cgh)
797 {
798 auto access_x = x.template get_access<sycl::access::mode::read>(cgh);
799 auto access_y = y.template get_access<sycl::access::mode::read>(cgh);
800 //auto access_w = w.template get_access<sycl::access::mode::write>(cgh);
801 auto access_w = sycl::accessor { w, cgh, sycl::write_only, sycl::property::no_init{}};
802 //auto access_w = w.get_access(cgh,sycl::write_only, sycl::property::no_init{});
803 auto y_length = y.size() ;
804 cgh.parallel_for<class vector_dot>(sycl::range<1>{m_total_threads}, [=] (sycl::item<1> itemId)
805 {
806 auto id = itemId.get_id(0);
807 for (auto i = id; i < y_length; i += itemId.get_range()[0])
808 access_w[i] = access_x[i]*access_y[i];
809 });
810 });
811 // clang-format on
812
813 std::size_t local = m_max_work_group_size;
814 std::size_t length = x.size();
815
816 int level = 0;
817 {
818 /* Each iteration of the do loop applies one level of reduction until
819 * the input is of length 1 (i.e. the reduction is complete). */
820 do {
821 auto round_length = round_up(length, local);
822 // clang-format off
823 auto f = [length, round_length, local, &w](sycl::handler& h) mutable
824 {
825 sycl::nd_range<1> range{sycl::range<1>{round_length},
826 sycl::range<1>{local}};
827 auto access_w = w.template get_access<sycl::access::mode::read_write>(h);
828
829 //sycl::accessor<T, 1, sycl::access::mode::read_write,sycl::access::target::local>
830 // scratch(sycl::range<1>(local), h);
831 sycl::local_accessor<T> scratch{sycl::range<1>(local), h};
832
833 /* The parallel_for invocation chosen is the variant with an nd_item
834 * parameter, since the code requires barriers for correctness. */
835 h.parallel_for<class sycl_reduction_sum_T>(range,
836 [access_w, scratch, local, length](sycl::nd_item<1> id)
837 {
838 std::size_t globalid = id.get_global_id(0);
839 std::size_t localid = id.get_local_id(0);
840
841 /* All threads collectively read from global memory into local.
842 * The barrier ensures all threads' IO is resolved before
843 * execution continues (strictly speaking, all threads within
844 * a single work-group - there is no co-ordination between
845 * work-groups, only work-items). */
846 scratch[localid] = (globalid < length)? access_w[globalid] : 0. ;
847 id.barrier(sycl::access::fence_space::local_space);
848
849 /* Apply the reduction operation between the current local
850 * id and the one on the other half of the vector. */
851 if (globalid < length)
852 {
853 //int min = (length < local) ? length : local;
854 std::size_t min = local ;
855 for (std::size_t offset = min / 2; offset > 0; offset /= 2)
856 //for (std::size_t offset = id.get_local_range(0) / 2; offset > 0; offset /= 2)
857 {
858 if (localid < offset)
859 {
860 scratch[localid] += scratch[localid + offset];
861 }
862 id.barrier(sycl::access::fence_space::local_space);
863 }
864 /* The final result will be stored in local id 0. */
865 if (localid == 0)
866 {
867 access_w[id.get_group(0)] = scratch[localid];
868 }
869 }
870 });
871 };
872 // clang-format on
873 m_env->internal()->queue().submit(f);
874 /* At this point, you could queue::wait_and_throw() to ensure that
875 * errors are caught quickly. However, this would likely impact
876 * performance negatively. */
877 length = (length + local - 1) / local;
878 ++level;
879 } while (length > 1);
880 }
881 //auto h_w = w.template get_access<sycl::access::mode::read>();
882 auto h_w = w.get_host_access();
883 T sum = h_w[0];
884 return sum;
885 }
886
887 template <typename T>
889
890 template <typename T>
892
893 template <typename T>
894 T map_reduce_sum(sycl::buffer<T>& x,
895 sycl::buffer<T>& y)
896 {
897 auto& w = getWorkBuffer<T>(x.size());
898
899 std::size_t local = m_max_work_group_size;
900 std::size_t length = x.size();
901
902 int level = 0;
903 {
904 /* Each iteration of the do loop applies one level of reduction until
905 * the input is of length 1 (i.e. the reduction is complete). */
906 //do
907 {
908 auto round_length = round_up(length, local);
909 // clang-format off
910 auto f0 = [length, round_length, local, &x,&y, &w](sycl::handler& h) mutable
911 {
912 sycl::nd_range<1> range{sycl::range<1>{round_length},
913 sycl::range<1>{local}};
914 auto access_x = x.template get_access<sycl::access::mode::read>(h);
915 auto access_y = y.template get_access<sycl::access::mode::read>(h);
916 //auto access_w = w.template get_access<sycl::access::mode::read_write>(h);
917 auto access_w = sycl::accessor { w, h, sycl::read_write, sycl::property::no_init{}};
918
919 //sycl::accessor<T, 1, sycl::access::mode::read_write,sycl::access::target::local>
920 // scratch(sycl::range<1>(local), h);
921 sycl::local_accessor<T> scratch{sycl::range<1>(local), h};
922
923 /* The parallel_for invocation chosen is the variant with an nd_item
924 * parameter, since the code requires barriers for correctness. */
925 h.parallel_for<class sycl_map_reduction_sum0_T>(range,
926 [access_x,access_y,access_w, scratch, local, length](sycl::nd_item<1> id)
927 {
928 std::size_t globalid = id.get_global_id(0);
929 std::size_t localid = id.get_local_id(0);
930
931 /* All threads collectively read from global memory into local.
932 * The barrier ensures all threads' IO is resolved before
933 * execution continues (strictly speaking, all threads within
934 * a single work-group - there is no co-ordination between
935 * work-groups, only work-items). */
936 scratch[localid] = (globalid < length)? access_x[globalid]*access_y[globalid] : 0. ;
937
938 id.barrier(sycl::access::fence_space::local_space);
939
940 /* Apply the reduction operation between the current local
941 * id and the one on the other half of the vector. */
942 if (globalid < length)
943 {
944 //int min = (length < local) ? length : local;
945 std::size_t min = local ;
946 for (std::size_t offset = min / 2; offset > 0; offset /= 2)
947 //for (std::size_t offset = id.get_local_range(0) / 2; offset > 0; offset /= 2)
948 {
949 if (localid < offset)
950 {
951 scratch[localid] += scratch[localid + offset];
952 }
953 id.barrier(sycl::access::fence_space::local_space);
954 }
955 /* The final result will be stored in local id 0. */
956 if (localid == 0)
957 {
958 access_w[id.get_group(0)] = scratch[localid];
959 }
960 }
961 });
962 };
963 // clang-format on
964
965 // clang-format off
966 auto f1 = [length, round_length, local, &w](sycl::handler& h) mutable
967 {
968 sycl::nd_range<1> range{sycl::range<1>{round_length},
969 sycl::range<1>{local}};
970 auto access_w = w.template get_access<sycl::access::mode::read_write>(h);
971
972 //sycl::accessor<T, 1, sycl::access::mode::read_write,sycl::access::target::local>
973 // scratch(sycl::range<1>(local), h);
974 sycl::local_accessor<T> scratch{sycl::range<1>(local), h};
975
976 /* The parallel_for invocation chosen is the variant with an nd_item
977 * parameter, since the code requires barriers for correctness. */
978 h.parallel_for<class sycl_map_reduction_sum_T>(range,
979 [access_w, scratch, local, length](sycl::nd_item<1> id)
980 {
981 std::size_t globalid = id.get_global_id(0);
982 std::size_t localid = id.get_local_id(0);
983
984 /* All threads collectively read from global memory into local.
985 * The barrier ensures all threads' IO is resolved before
986 * execution continues (strictly speaking, all threads within
987 * a single work-group - there is no co-ordination between
988 * work-groups, only work-items). */
989 scratch[localid] = (globalid < length)? access_w[globalid] : 0. ;
990 id.barrier(sycl::access::fence_space::local_space);
991
992 /* Apply the reduction operation between the current local
993 * id and the one on the other half of the vector. */
994 if (globalid < length)
995 {
996 //int min = (length < local) ? length : local;
997 std::size_t min = local ;
998 for (std::size_t offset = min / 2; offset > 0; offset /= 2)
999 //for (std::size_t offset = id.get_local_range(0) / 2; offset > 0; offset /= 2)
1000 {
1001 if (localid < offset)
1002 {
1003 scratch[localid] += scratch[localid + offset];
1004 }
1005 id.barrier(sycl::access::fence_space::local_space);
1006 }
1007 /* The final result will be stored in local id 0. */
1008 if (localid == 0)
1009 {
1010 access_w[id.get_group(0)] = scratch[localid];
1011 }
1012 }
1013 });
1014 };
1015 // clang-format on
1016 if (level == 0)
1017 m_env->internal()->queue().submit(f0);
1018 else
1019 m_env->internal()->queue().submit(f1);
1020 /* At this point, you could queue::wait_and_throw() to ensure that
1021 * errors are caught quickly. However, this would likely impact
1022 * performance negatively. */
1023 length = (length + local - 1) / local;
1024 ++level;
1025 } //while (length > 1);
1026 }
1027 auto h_x = w.get_host_access();
1028 //T sum = h_x[0] ;
1029 T sum = 0;
1030 for (std::size_t i = 0; i < length; ++i)
1031 sum += h_x[i];
1032 return sum;
1033 }
1034
1035 template <typename T>
1037
1038 template <typename T>
1039 T map2_reduce_sum(sycl::buffer<T>& x,
1040 sycl::buffer<T>& y)
1041 {
1042 std::size_t local = m_max_work_group_size;
1043 std::size_t total_threads = m_total_threads;
1044 std::size_t length = x.size();
1045
1046 T sum_init = 0;
1047 sycl::buffer<T> sum{ &sum_init, 1 };
1048
1049 {
1050 /* Each iteration of the do loop applies one level of reduction until
1051 * the input is of length 1 (i.e. the reduction is complete). */
1052 {
1053 auto round_length = round_up(length, local);
1054 // clang-format off
1055 auto f0 = [length, round_length,total_threads, local, &x, &y, &sum](sycl::handler& h) mutable
1056 {
1057 sycl::nd_range<1> range{sycl::range<1>{std::min(total_threads,round_length)},
1058 sycl::range<1>{local}};
1059 auto access_x = x.template get_access<sycl::access::mode::read>(h);
1060 auto access_y = y.template get_access<sycl::access::mode::read>(h);
1061
1062 sycl::accessor access_sum {sum, h};
1063#ifdef USE_HIPSYCL
1064 auto sumReduction = sycl::reduction(access_sum, sycl::plus<T>());
1065#endif
1066#ifdef USE_ONEAPI
1067 auto sumReduction = sycl::reduction(sum, h, sycl::plus<T>());
1068#endif
1069#ifdef USE_ACPPSYCL
1070 auto sumReduction = sycl::reduction(sum, h, sycl::plus<T>());
1071#endif
1072
1073 //sycl::accessor<T, 1, sycl::access::mode::read_write,sycl::access::target::local>
1074 // scratch(sycl::range<1>(local), h);
1075 sycl::local_accessor<T> scratch{sycl::range<1>(local), h};
1076
1077 /* The parallel_for invocation chosen is the variant with an nd_item
1078 * parameter, since the code requires barriers for correctness. */
1079 h.parallel_for<class sycl_map2_reduction_sum0_T>(range,
1080 sumReduction,
1081 [access_x,access_y, scratch, local,total_threads,length](sycl::nd_item<1> id, auto &sum)
1082 {
1083 std::size_t globalid = id.get_global_id(0);
1084 std::size_t localid = id.get_local_id(0);
1085
1086 /* All threads collectively read from global memory into local.
1087 * The barrier ensures all threads' IO is resolved before
1088 * execution continues (strictly speaking, all threads within
1089 * a single work-group - there is no co-ordination between
1090 * work-groups, only work-items). */
1091 scratch[localid] = (globalid < length)? access_x[globalid]*access_y[globalid] : 0. ;
1092 for (auto i = globalid+total_threads; i < length; i += total_threads)
1093 scratch[localid] += access_x[i]*access_y[i];
1094
1095 id.barrier(sycl::access::fence_space::local_space);
1096
1097 /* Apply the reduction operation between the current local
1098 * id and the one on the other half of the vector. */
1099 //if (globalid < length)
1100 {
1101 //int min = (length < local) ? length : local;
1102 std::size_t min = local ;
1103 for (std::size_t offset = min / 2; offset > 0; offset /= 2)
1104 //for (std::size_t offset = id.get_local_range(0) / 2; offset > 0; offset /= 2)
1105 {
1106 if (localid < offset)
1107 {
1108 scratch[localid] += scratch[localid + offset];
1109 }
1110 id.barrier(sycl::access::fence_space::local_space);
1111 }
1112 /* The final result will be stored in local id 0. */
1113 if (localid == 0)
1114 {
1115 //access_w[id.get_group(0)] = scratch[localid];
1116 sum += scratch[localid];
1117 }
1118 }
1119 });
1120 };
1121 // clang-format on
1122 m_env->internal()->queue().submit(f0);
1123 }
1124 }
1125 auto h_sum = sum.get_host_access();
1126 return h_sum[0];
1127 }
1128
1129 template <typename T>
1131
1132 template <typename T>
1133 T map3_reduce_sum(sycl::buffer<T>& x,
1134 sycl::buffer<T>& y)
1135 {
1136 std::size_t local = m_max_work_group_size;
1137 std::size_t total_threads = m_total_threads;
1138 std::size_t length = x.size();
1139
1140 //std::vector<T> group_sum(m_max_num_groups) ;
1141 //sycl::buffer<T> group_sum{ m_max_num_groups };
1142 auto& group_sum = getWorkBuffer<T>(m_max_num_groups);
1143
1144 //T sum_init = 0;
1145 //sycl::buffer<T> sum{ &sum_init, 1 };
1146
1147 auto round_length = round_up(length, local);
1148 {
1149 /* Each iteration of the do loop applies one level of reduction until
1150 * the input is of length 1 (i.e. the reduction is complete). */
1151 //do
1152 {
1153 // clang-format off
1154 auto f0 = [total_threads,round_length, length, local, &x, &y,&group_sum](sycl::handler& h) mutable
1155 {
1156 sycl::nd_range<1> range{sycl::range<1>{std::min(total_threads,round_length)},
1157 sycl::range<1>{local}};
1158 auto access_x = x.template get_access<sycl::access::mode::read>(h);
1159 auto access_y = y.template get_access<sycl::access::mode::read>(h);
1160
1161 auto access_sum = sycl::accessor { group_sum, h, sycl::read_write, sycl::property::no_init{}};
1162
1163 //sycl::accessor access_sum {sum, h};
1164 //auto sumReduction = sycl::reduction(access_sum, sycl::plus<T>());
1165
1166 //sycl::accessor<T, 1, sycl::access::mode::read_write,sycl::access::target::local>
1167 // scratch(sycl::range<1>(local), h);
1168 sycl::local_accessor<T> scratch{sycl::range<1>(local), h};
1169
1170 /* The parallel_for invocation chosen is the variant with an nd_item
1171 * parameter, since the code requires barriers for correctness. */
1172
1173 h.parallel_for<class sycl_map3_reduction_sum0_T>(range,
1174 //sumReduction,
1175 //[access_x,access_y,scratch,local,length,total_threads] (sycl::nd_item<1> id, auto& sum)
1176 [access_x,access_y,access_sum,scratch,local,length,total_threads] (sycl::nd_item<1> id)
1177 {
1178 std::size_t globalid = id.get_global_id(0);
1179 std::size_t localid = id.get_local_id(0);
1180
1181 scratch[localid] = (globalid < length)? access_x[globalid]*access_y[globalid] : 0. ;
1182
1183 for (auto i = globalid+total_threads; i < length; i += total_threads)
1184 scratch[localid] += access_x[i]*access_y[i];
1185
1186 id.barrier(sycl::access::fence_space::local_space);
1187
1188 /* Apply the reduction operation between the current local
1189 * id and the one on the other half of the vector. */
1190 {
1191 //int min = (length < local) ? length : local;
1192 std::size_t min = local ;
1193 for (std::size_t offset = min / 2; offset > 0; offset /= 2)
1194 {
1195 if (localid < offset)
1196 {
1197 scratch[localid] += scratch[localid + offset];
1198 }
1199 id.barrier(sycl::access::fence_space::local_space);
1200 }
1201 }
1202 /* The final result will be stored in local id 0. */
1203 if (localid == 0)
1204 {
1205 access_sum[id.get_group(0)] = scratch[localid];
1206 //sum += scratch[localid] ;
1207 }
1208 });
1209
1210 };
1211 // clang-format on
1212 m_env->internal()->queue().submit(f0);
1213
1214 } //while (length > 1);
1215 }
1216
1217 //return sum.get_host_access()[0];
1218 auto h_sum = group_sum.get_host_access();
1219 T sum = 0;
1220 for (std::size_t i = 0; i < std::min(total_threads, round_length) / local; ++i)
1221 sum += h_sum[i];
1222 return sum;
1223 }
1224
1225 template <typename T>
1227
1228 template <typename T>
1229 void asynch_map4_reduce_sum(sycl::buffer<T>& x,
1230 sycl::buffer<T>& y,
1231 sycl::buffer<T>& res,
1232 sycl::event& event)
1233 {
1234 std::size_t local = m_max_work_group_size;
1235 std::size_t total_threads = m_total_threads;
1236 std::size_t length = x.size();
1237
1238 //T sum_init = 0 ;
1239 //sycl::buffer<T> sum{&sum_init,1};
1240 {
1241 /* Each iteration of the do loop applies one level of reduction until
1242 * the input is of length 1 (i.e. the reduction is complete). */
1243 //do
1244 {
1245 auto round_length = round_up(length, local);
1246 // clang-format off
1247 auto f0 = [total_threads, round_length, length, local, &x, &y,&res](sycl::handler& h) mutable
1248 {
1249 sycl::nd_range<1> range{sycl::range<1>{std::min(total_threads,round_length)},
1250 sycl::range<1>{local}};
1251 auto access_x = x.template get_access<sycl::access::mode::read>(h);
1252 auto access_y = y.template get_access<sycl::access::mode::read>(h);
1253#ifdef USE_HIPSYCL
1254 sycl::accessor access_sum {res, h};
1255 auto sumReduction = sycl::reduction(access_sum, sycl::plus<T>());
1256#endif
1257#ifdef USE_ONEAPI
1258 auto sumReduction = sycl::reduction(res, h, sycl::plus<T>());
1259#endif
1260#ifdef USE_ACPPSYCL
1261 auto sumReduction = sycl::reduction(res, h, sycl::plus<T>());
1262#endif
1263 //auto access_sum = sycl::accessor<T,0,access::mode::write,access::target::global_buffer>(res, h);
1264 //auto access_sum = sycl::accessor { res, h, sycl::read_write, sycl::property::no_init{}};
1265
1266 //auto sumReduction = sycl::reduction(access_sum,sycl::plus<T>(), sycl::property::reduction::initialize_to_identity);
1267 //auto sumReduction = sycl::reduction(access_sum,sycl::plus<T>());
1268
1269 //sycl::accessor<T, 1, sycl::access::mode::read_write,sycl::access::target::local>
1270 // scratch(sycl::range<1>(local), h);
1271 sycl::local_accessor<T> scratch{sycl::range<1>(local), h};
1272
1273 /* The parallel_for invocation chosen is the variant with an nd_item
1274 * parameter, since the code requires barriers for correctness. */
1275
1276 h.parallel_for<class map4_reduction_sum_T>(range,
1277 sumReduction,
1278 [access_x,access_y,scratch,local,length,total_threads] (sycl::nd_item<1> id, auto& sum)
1279 {
1280 std::size_t globalid = id.get_global_id(0);
1281 std::size_t localid = id.get_local_id(0);
1282
1283 scratch[localid] = (globalid < length)? access_x[globalid]*access_y[globalid] : 0. ;
1284
1285 for (auto i = globalid+total_threads; i < length; i += total_threads)
1286 scratch[localid] += access_x[i]*access_y[i];
1287
1288 id.barrier(sycl::access::fence_space::local_space);
1289
1290 /* Apply the reduction operation between the current local
1291 * id and the one on the other half of the vector. */
1292 //if (globalid < length)
1293 {
1294 //int min = (length < local) ? length : local;
1295 std::size_t min = local ;
1296 for (std::size_t offset = min / 2; offset > 0; offset /= 2)
1297 //for (std::size_t offset = id.get_local_range(0) / 2; offset > 0; offset /= 2)
1298 {
1299 if (localid < offset)
1300 {
1301 scratch[localid] += scratch[localid + offset];
1302 }
1303 id.barrier(sycl::access::fence_space::local_space);
1304 }
1305 }
1306 /* The final result will be stored in local id 0. */
1307 if (localid == 0)
1308 {
1309 //access_sum[id.get_group(0)] = scratch[localid];
1310 sum += scratch[localid] ;
1311 }
1312 });
1313
1314 };
1315 // clang-format on
1316 event = m_env->internal()->queue().submit(f0);
1317 }
1318 }
1319 }
1320
1321 template <typename T>
1322 T end_map4_reduce_sum(sycl::event& event,
1323 sycl::buffer<T>& res,
1324 [[maybe_unused]] std::size_t num_blocks)
1325 {
1326 event.wait() ;
1327 auto h_access = res.get_host_access();
1328 return h_access[0];
1329 }
1330
1331 template <typename T>
1333
1334 template <typename T>
1336
1337 template <typename T>
1338 void asynch_map5_reduce_sum(sycl::buffer<T>& x,
1339 sycl::buffer<T>& y,
1340 sycl::buffer<T>& res,
1341 sycl::event& event)
1342 {
1343 std::size_t local = m_max_work_group_size;
1344 std::size_t total_threads = m_total_threads;
1345 std::size_t length = x.size();
1346
1347 int level = 0;
1348 {
1349 /* Each iteration of the do loop applies one level of reduction until
1350 * the input is of length 1 (i.e. the reduction is complete). */
1351 do {
1352 // clang-format off
1353 auto f0 = [total_threads, length, local, &x, &y,&res](sycl::handler& h) mutable
1354 {
1355 sycl::nd_range<1> range{sycl::range<1>{total_threads},
1356 sycl::range<1>{local}};
1357 auto access_x = x.template get_access<sycl::access::mode::read>(h);
1358 auto access_y = y.template get_access<sycl::access::mode::read>(h);
1359 auto access_sum = sycl::accessor { res, h, sycl::read_write, sycl::property::no_init{}};
1360
1361 //sycl::accessor<T, 1, sycl::access::mode::read_write,sycl::access::target::local>
1362 // scratch(sycl::range<1>(local), h);
1363 sycl::local_accessor<T> scratch{sycl::range<1>(local), h};
1364
1365 /* The parallel_for invocation chosen is the variant with an nd_item
1366 * parameter, since the code requires barriers for correctness. */
1367
1368 h.parallel_for<class map5_reduction_sum_T>(range,
1369 [access_x,access_y,access_sum,scratch,local,length,total_threads] (sycl::nd_item<1> id)
1370 {
1371 std::size_t globalid = id.get_global_id(0);
1372 std::size_t localid = id.get_local_id(0);
1373
1374 scratch[localid] = (globalid < length)? access_x[globalid]*access_y[globalid] : 0. ;
1375
1376 for (auto i = globalid+total_threads; i < length; i += total_threads)
1377 scratch[localid] += access_x[i]*access_y[i];
1378
1379 id.barrier(sycl::access::fence_space::local_space);
1380
1381 /* Apply the reduction operation between the current local
1382 * id and the one on the other half of the vector. */
1383 if (globalid < length)
1384 {
1385 //int min = (length < local) ? length : local;
1386 for (std::size_t offset = local / 2; offset > 0; offset /= 2)
1387 //for (std::size_t offset = id.get_local_range(0) / 2; offset > 0; offset /= 2)
1388 {
1389 if (localid < offset)
1390 {
1391 scratch[localid] += scratch[localid + offset];
1392 }
1393 id.barrier(sycl::access::fence_space::local_space);
1394 }
1395 }
1396 /* The final result will be stored in local id 0. */
1397 if (localid == 0)
1398 {
1399 access_sum[id.get_group(0)] = scratch[localid];
1400 }
1401
1402 });
1403
1404 };
1405 // clang-format on
1406 auto f1 = [length, local, &res](sycl::handler& h) mutable {
1407 sycl::nd_range<1> range{ sycl::range<1>{ local },
1408 sycl::range<1>{ local } };
1409 auto access_sum = res.template get_access<sycl::access::mode::read_write>(h);
1410
1411 //sycl::accessor<T, 1, sycl::access::mode::read_write, sycl::access::target::local>
1412 //scratch(sycl::range<1>(local), h);
1413 sycl::local_accessor<T> scratch{sycl::range<1>(local), h};
1414
1415 /* The parallel_for invocation chosen is the variant with an nd_item
1416 * parameter, since the code requires barriers for correctness. */
1417 h.parallel_for<class map5_reduction_sum1_T>(range,
1418 [access_sum, scratch, local, length](sycl::nd_item<1> id) {
1419 //auto localid = id.get_id(0);
1420 std::size_t globalid = id.get_global_id(0);
1421 std::size_t localid = id.get_local_id(0);
1422
1423 /* All threads collectively read from global memory into local.
1424 * The barrier ensures all threads' IO is resolved before
1425 * execution continues (strictly speaking, all threads within
1426 * a single work-group - there is no co-ordination between
1427 * work-groups, only work-items). */
1428 scratch[localid] = (localid < length) ? access_sum[localid] : 0.;
1429 id.barrier(sycl::access::fence_space::local_space);
1430
1431 /* Apply the reduction operation between the current local
1432 * id and the one on the other half of the vector. */
1433 if (localid < length) {
1434 //int min = (length < local) ? length : local;
1435 std::size_t min = local;
1436 for (std::size_t offset = min / 2; offset > 0; offset /= 2)
1437 //for (std::size_t offset = id.get_local_range(0) / 2; offset > 0; offset /= 2)
1438 {
1439 if (localid < offset) {
1440 scratch[localid] += scratch[localid + offset];
1441 }
1442 id.barrier(sycl::access::fence_space::local_space);
1443 }
1444 /* The final result will be stored in local id 0. */
1445 if (localid == 0) {
1446 access_sum[0] = scratch[localid];
1447 }
1448 }
1449 });
1450 };
1451 // clang-format on
1452 if (level == 0)
1453 event = m_env->internal()->queue().submit(f0);
1454 else
1455 event = m_env->internal()->queue().submit(f1);
1456
1457 /* At this point, you could queue::wait_and_throw() to ensure that
1458 * errors are caught quickly. However, this would likely impact
1459 * performance negatively. */
1460 //length = (length + local - 1) / local;
1461 length = (std::min(total_threads, length) + local - 1) / local;
1462 ++level;
1463 } while (length > 1);
1464 }
1465 //auto h_x = res.template get_access<sycl::access::mode::read>();
1466 //T sum = h_x[0] ;
1467 //T sum = 0;
1468 //for (int i = 0; i < length; ++i)
1469 // sum += h_x[i];
1470 //return sum;
1471 }
1472
1473
1474 template <typename T>
1475 T end_map5_reduce_sum(sycl::event& event,
1476 sycl::buffer<T>& res,
1477 [[maybe_unused]] std::size_t num_blocks)
1478 {
1479 event.wait() ;
1480 auto h_access = res.get_host_access();
1481 return h_access[0];
1482 }
1483
1484 template <typename T>
1485 T reduce_sum2(const std::vector<T>& x)
1486 {
1487 T value = 0;
1488 //for( auto v : x)
1489 // value += v ;
1490 //return value ;
1491
1492 {
1493 auto num_groups = m_env->internal()->queue().get_device().get_info<sycl::info::device::max_compute_units>();
1494 // getting the maximum work group size per thread
1495 auto work_group_size = m_env->internal()->queue().get_device().get_info<sycl::info::device::max_work_group_size>();
1496 // building the best number of global thread
1497 auto total_threads = num_groups * work_group_size;
1498
1499 //std::cout << "LOCAL =" << work_group_size << std::endl;
1500 //std::cout << "NB GROUPS =" << num_groups << std::endl;
1501 //std::cout << "NB THREADS=" << total_threads << std::endl;
1502
1503 /* The buffer is used to initialise the data on the device, but we don't
1504 * want to copy back and trash it. buffer::set_final_data() tells the
1505 * SYCL runtime where to put the data when the buffer is destroyed; nullptr
1506 * indicates not to copy back. The vector's length is used as the global
1507 * work size (unless that is too large). */
1508 auto device = m_env->internal()->queue().get_device();
1509 //std::size_t local = std::min(x.size(),device.get_info<sycl::info::device::max_work_group_size>());
1510 std::size_t local = device.get_info<sycl::info::device::max_work_group_size>();
1511
1512 std::size_t length = x.size();
1513
1514 sycl::buffer<T, 1> xbuf(x.data(), sycl::range<1>(x.size()));
1515 xbuf.set_final_data(nullptr);
1516
1517 int level = 0;
1518 {
1519 /* Each iteration of the do loop applies one level of reduction until
1520 * the input is of length 1 (i.e. the reduction is complete). */
1521 do {
1522
1523 auto round_length = round_up(length, local);
1524 std::cout << "LENGTH :" << level << " " << length << " " << round_length << " " << local << std::endl;
1525 // clang-format off
1526 auto f = [length,round_length,local, &xbuf](sycl::handler& h) mutable
1527 {
1528 //sycl::nd_range<1> r{sycl::range<1>{std::max(length, local)},
1529 // sycl::range<1>{std::min(length, local)}};
1530 sycl::nd_range<1> r{sycl::range<1>{round_length},
1531 sycl::range<1>{local}};
1532 /* Two accessors are used: one to the buffer that is being reduced,
1533 * and a second to local memory, used to store intermediate data. */
1534 auto x_access = xbuf.template get_access<sycl::access::mode::read_write>(h);
1535
1536 //sycl::accessor<T, 1, sycl::access::mode::read_write,sycl::access::target::local>
1537 // scratch(sycl::range<1>(local), h);
1538 sycl::local_accessor<T> scratch{sycl::range<1>(local), h};
1539
1540 /* The parallel_for invocation chosen is the variant with an nd_item
1541 * parameter, since the code requires barriers for correctness. */
1542 h.parallel_for<class reduce_sum2>(r, [x_access, scratch, local, length](sycl::nd_item<1> id)
1543 {
1544 std::size_t globalid = id.get_global_id(0);
1545 std::size_t localid = id.get_local_id(0);
1546
1547 /* All threads collectively read from global memory into local.
1548 * The barrier ensures all threads' IO is resolved before
1549 * execution continues (strictly speaking, all threads within
1550 * a single work-group - there is no co-ordination between
1551 * work-groups, only work-items). */
1552 scratch[localid] = (globalid < length)? x_access[globalid] : 0. ;
1553 id.barrier(sycl::access::fence_space::local_space);
1554
1555 /* Apply the reduction operation between the current local
1556 * id and the one on the other half of the vector. */
1557 //#ifdef DEBUG
1558 if (globalid < length)
1559 {
1560 //int min = (length < local) ? length : local;
1561 int min = local ;
1562 for (std::size_t offset = min / 2; offset > 0; offset /= 2)
1563 //for (std::size_t offset = id.get_local_range(0) / 2; offset > 0; offset /= 2)
1564 {
1565 if (localid < offset)
1566 {
1567 scratch[localid] += scratch[localid + offset];
1568 }
1569 id.barrier(sycl::access::fence_space::local_space);
1570 }
1571 /* The final result will be stored in local id 0. */
1572 if (localid == 0)
1573 {
1574 x_access[id.get_group(0)] = scratch[localid];
1575 }
1576 }
1577 //#endif
1578 });
1579 };
1580 // clang-format on
1581 m_env->internal()->queue().submit(f);
1582 /* At this point, you could queue::wait_and_throw() to ensure that
1583 * errors are caught quickly. However, this would likely impact
1584 * performance negatively. */
1585 length = (length + local - 1) / local;
1586 std::cout << "AFTER LENGTH :" << level << " new length" << length << " " << local << std::endl;
1587 ++level;
1588 } while (length > 1);
1589 }
1590 /* It is always sensible to wrap host accessors in their own scope as
1591 * kernels using the buffers they access are blocked for the length
1592 * of the accessor's lifetime. */
1593 auto hI = xbuf.get_host_acces();
1594 value = hI[0];
1595 }
1596 //value = x[0] ;
1597 return value;
1598 }
1599
1600 template <typename T>
1601 T sycl_reduce_sum(sycl::buffer<T>& x,
1602 sycl::buffer<T>& y)
1603 {
1604 T sum_init = 0;
1605 sycl::buffer<T> sum_buff{ &sum_init, 1 };
1606
1607 // clang-format off
1608 m_env->internal()->queue().submit([&](sycl::handler &cgh)
1609 {
1610 auto access_x = x.template get_access<sycl::access::mode::read>(cgh);
1611 auto access_y = y.template get_access<sycl::access::mode::read>(cgh);
1612#ifdef USE_HIPSYCL
1613 sycl::accessor sum_acc {sum_buff, cgh};
1614 auto sumReduction = sycl::reduction(sum_acc, sycl::plus<T>());
1615#endif
1616#ifdef USE_ONEAPI
1617 auto sumReduction = sycl::reduction(sum_buff, cgh, sycl::plus<T>());
1618#endif
1619#ifdef USE_ACPPSYCL
1620 auto sumReduction = sycl::reduction(sum_buff, cgh, sycl::plus<T>());
1621#endif
1622 cgh.parallel_for(sycl::range<1>{x.size()},
1623 sumReduction,
1624 [=](sycl::id<1> idx, auto &sum)
1625 {
1626 sum += access_x[idx]*access_y[idx];
1627 });
1628 });
1629 // clang-format on
1630
1631 return sum_buff.get_host_access()[0];
1632 }
1633
1634 /*
1635 namespace mi300 {
1636
1637 // Constantes tuned pour MI300 (gfx942)
1638 // - CU count : 228 CUs
1639 // - Wavefront : 64 threads (RDNA/CDNA)
1640 // - LDS/CU : 64 KB → 1024 threads × 8 B (double) = 8 KB/workgroup, safe
1641 inline constexpr std::size_t WG_SIZE = 1024; // 16 wavefronts/WG
1642 inline constexpr std::size_t ITEMS_PER_WI = 8; // unroll : chaque WI traite 8 éléments
1643
1644 // ---------------------------------------------------------------------------
1645 // dot_product_device
1646 // Calcule <x, y> = sum_i x[i]*y[i] sur GPU MI300.
1647 // x_buf, y_buf : buffers SYCL en lecture (taille >= n)
1648 // Retourne le scalaire double via un buffer résultat temporaire.
1649 // ---------------------------------------------------------------------------
1650 inline double dot_product(
1651 sycl::queue& q,
1652 sycl::buffer<double, 1>& x_buf,
1653 sycl::buffer<double, 1>& y_buf,
1654 std::size_t n)
1655 {
1656 if (n == 0) return 0.0;
1657
1658 // Nombre de work-groups : on arrondit au multiple de WG_SIZE*ITEMS_PER_WI
1659 const std::size_t stride = WG_SIZE * ITEMS_PER_WI;
1660 const std::size_t n_wg = (n + stride - 1) / stride;
1661 const std::size_t n_padded = n_wg * stride; // domaine de dispatch
1662
1663 // Buffer de réductions partielles (une valeur par WG)
1664 sycl::buffer<double, 1> partial_buf(n_wg);
1665
1666 // -------------------------------------------------------------------
1667 // Kernel 1 — réduction locale par work-group
1668 // Chaque WI charge ITEMS_PER_WI paires (x[i], y[i]) et accumule.
1669 // La réduction finale dans le WG utilise la LDS (sycl::local_accessor).
1670 // -------------------------------------------------------------------
1671 q.submit([&](sycl::handler& cgh) {
1672 auto x = x_buf.template get_access<sycl::access::mode::read>(cgh);
1673 auto y = y_buf.template get_access<sycl::access::mode::read>(cgh);
1674 auto out = partial_buf.template get_access<sycl::access::mode::discard_write>(cgh);
1675
1676 // LDS : WG_SIZE doubles par work-group
1677 sycl::local_accessor<double, 1> local_sum(WG_SIZE, cgh);
1678
1679 sycl::nd_range<1> nd_range{n_padded, WG_SIZE};
1680
1681 cgh.parallel_for(nd_range, [=](sycl::nd_item<1> item) {
1682 const std::size_t gid = item.get_global_id(0);
1683 const std::size_t lid = item.get_local_id(0);
1684 const std::size_t wg_id = item.get_group(0);
1685 const std::size_t base = wg_id * stride;
1686
1687 // Accumulation privée — ITEMS_PER_WI éléments par WI
1688 double acc = 0.0;
1689 #pragma unroll
1690 for (std::size_t k = 0; k < ITEMS_PER_WI; ++k) {
1691 const std::size_t idx = base + lid + k * WG_SIZE;
1692 if (idx < n) {
1693 acc += x[idx] * y[idx];
1694 }
1695 }
1696
1697 // Dépôt en LDS
1698 local_sum[lid] = acc;
1699 sycl::group_barrier(item.get_group());
1700
1701 // Réduction en arbre dans la LDS (log2(WG_SIZE) = 10 passes)
1702 for (std::size_t offset = WG_SIZE / 2; offset > 0; offset >>= 1) {
1703 if (lid < offset) {
1704 local_sum[lid] += local_sum[lid + offset];
1705 }
1706 sycl::group_barrier(item.get_group());
1707 }
1708
1709 // WI 0 écrit la somme partielle du WG
1710 if (lid == 0) {
1711 out[wg_id] = local_sum[0];
1712 }
1713 });
1714 });
1715
1716 // -------------------------------------------------------------------
1717 // Kernel 2 — réduction finale des n_wg partielles
1718 // Si n_wg <= WG_SIZE on fait tout en un seul WG.
1719 // Sinon on rappelle dot_product récursivement (rare pour n < 2^30).
1720 // -------------------------------------------------------------------
1721 double result = 0.0;
1722
1723 if (n_wg <= WG_SIZE) {
1724 sycl::buffer<double, 1> result_buf(&result, 1);
1725
1726 q.submit([&](sycl::handler& cgh) {
1727 auto src = partial_buf.template get_access<sycl::access::mode::read>(cgh);
1728 auto dst = result_buf.template get_access<sycl::access::mode::discard_write>(cgh);
1729 sycl::local_accessor<double, 1> lmem(WG_SIZE, cgh);
1730
1731 // On dispatch exactement WG_SIZE threads, padding avec 0
1732 cgh.parallel_for(sycl::nd_range<1>{WG_SIZE, WG_SIZE},
1733 [=](sycl::nd_item<1> item) {
1734 const std::size_t lid = item.get_local_id(0);
1735 lmem[lid] = (lid < n_wg) ? src[lid] : 0.0;
1736 sycl::group_barrier(item.get_group());
1737
1738 for (std::size_t offset = WG_SIZE / 2; offset > 0; offset >>= 1) {
1739 if (lid < offset)
1740 lmem[lid] += lmem[lid + offset];
1741 sycl::group_barrier(item.get_group());
1742 }
1743 if (lid == 0) dst[0] = lmem[0];
1744 });
1745 });
1746 // L'accès au buffer result_buf en sortie de scope force la synchronisation
1747 } else {
1748 // Chemin récursif (n > WG_SIZE² ~ 1M WGs, soit n > ~8G éléments)
1749 // Rare en pratique — on réduit les partielles via un second appel
1750 result = dot_product(q, partial_buf, partial_buf, n_wg);
1751 }
1752
1753 return result;
1754 }
1755
1756 // ---------------------------------------------------------------------------
1757 // Variante asynchrone : retourne un sycl::event + résultat via buffer externe
1758 // Utile pour masquer la latence dans une boucle itérative (ex: CG)
1759 // ---------------------------------------------------------------------------
1760 inline sycl::event dot_product_async(
1761 sycl::queue& q,
1762 sycl::buffer<double, 1>& x_buf,
1763 sycl::buffer<double, 1>& y_buf,
1764 sycl::buffer<double, 1>& result_buf, // taille >= 1
1765 std::size_t n)
1766 {
1767 if (n == 0) {
1768 return q.submit([&](sycl::handler& cgh) {
1769 auto r = result_buf.template get_access<sycl::access::mode::discard_write>(cgh);
1770 cgh.single_task([=]{ r[0] = 0.0; });
1771 });
1772 }
1773
1774 const std::size_t stride = WG_SIZE * ITEMS_PER_WI;
1775 const std::size_t n_wg = (n + stride - 1) / stride;
1776 const std::size_t n_padded = n_wg * stride;
1777
1778 // Shared ptr pour que le buffer partiel survive au scope du lambda
1779 auto partial = std::make_shared<sycl::buffer<double,1>>(n_wg);
1780
1781 q.submit([&, partial](sycl::handler& cgh) {
1782 auto x = x_buf.template get_access<sycl::access::mode::read>(cgh);
1783 auto y = y_buf.template get_access<sycl::access::mode::read>(cgh);
1784 auto out = partial->template get_access<sycl::access::mode::discard_write>(cgh);
1785 sycl::local_accessor<double, 1> local_sum(WG_SIZE, cgh);
1786
1787 cgh.parallel_for(sycl::nd_range<1>{n_padded, WG_SIZE},
1788 [=](sycl::nd_item<1> item) {
1789 const std::size_t lid = item.get_local_id(0);
1790 const std::size_t base = item.get_group(0) * stride;
1791 double acc = 0.0;
1792 #pragma unroll
1793 for (std::size_t k = 0; k < ITEMS_PER_WI; ++k) {
1794 const std::size_t idx = base + lid + k * WG_SIZE;
1795 if (idx < n) acc += x[idx] * y[idx];
1796 }
1797 local_sum[lid] = acc;
1798 sycl::group_barrier(item.get_group());
1799 for (std::size_t offset = WG_SIZE / 2; offset > 0; offset >>= 1) {
1800 if (lid < offset) local_sum[lid] += local_sum[lid + offset];
1801 sycl::group_barrier(item.get_group());
1802 }
1803 if (lid == 0) out[item.get_group(0)] = local_sum[0];
1804 });
1805 });
1806
1807 return q.submit([partial](sycl::handler& cgh) {
1808 auto src = partial->template get_access<sycl::access::mode::read>(cgh);
1809 // reduction via sycl::reduction (SYCL 2020)
1810 // Note : result_buf doit être capturé par référence externe
1811 // → on utilise un single_task pour la somme finale des partielles (n_wg petit)
1812 cgh.single_task([=](){
1813 // accessible depuis le lambda — n_wg connu via closure
1814 });
1815 });
1816 // NOTE : pour la variante async complète, préférez sycl::reduction (voir ci-dessous)
1817 }
1818 } */
1819
1820
1821 template <typename T>
1822 inline T dot_product_h100(sycl::buffer<T>& buf_x,
1823 sycl::buffer<T>& buf_y)
1824 {
1825 using namespace sycl;
1826 auto& q = m_env->internal()->queue();
1827 const size_t N = buf_x.size();
1828 assert(buf_y.size() == N);
1829
1830 auto dev = q.get_device();
1831 //const size_t num_sm = dev.get_info<info::device::max_compute_units>(); // 132
1832
1833 // Grid : TARGET_WAVES * num_sm blocs, chacun de WG_SIZE threads,
1834 // chaque thread traite ITEMS_PER_WI éléments → couverture totale
1835 const size_t blocks_needed = (N + WG_SIZE * ITEMS_PER_WI - 1)
1836 / (WG_SIZE * ITEMS_PER_WI);
1837 const size_t num_blocks = std::max(blocks_needed,
1838 m_max_num_groups * TARGET_WAVES);
1839 const size_t total_threads = num_blocks * WG_SIZE;
1840
1841 // Allocation USM pour les partiels (un T par bloc)
1842 //T* partials = malloc_device<T>(num_blocks, q);
1843 sycl::buffer<T> partials{num_blocks};
1844
1845 // ── Phase 1 : kernel de réduction par blocs ───────────────────────────
1846 q.submit(
1847 [&](handler& cgh)
1848 {
1849 auto ax = buf_x.template get_access<access::mode::read>(cgh);
1850 auto ay = buf_y.template get_access<access::mode::read>(cgh);
1851 auto ap = partials.template get_access<access::mode::read_write>(cgh);
1852 // LDS : 1 T par warp dans le bloc
1853 local_accessor<T,1> lds{WG_SIZE / WARP_SIZE, cgh};
1854
1855 //const T* px = ax.get_pointer(); // accès USM-like depuis accessor
1856 //const T* py = ay.get_pointer();
1857 //T* pp = partials;
1858 const size_t n = N;
1859
1860 cgh.parallel_for<class dot_h100_phase1>(
1861 nd_range<1>{{total_threads}, {WG_SIZE}},
1862 [=](nd_item<1> item)
1863 [[intel::reqd_sub_group_size(WARP_SIZE)]]
1864 {
1865 h100::dot_kernel_h100(item, ax, ay, ap, n, lds);
1866 });
1867 });
1868
1869 // ── Phase 2 : réduction finale des partiels sur le CPU ────────────────
1870 // Pour N = 100M Ts → num_blocks ≤ 2048 → 16 KB de partiels.
1871 // Un memcpy D2H de 16 KB est négligeable vs le kernel principal.
1872 // Alternative : second kernel de réduction si num_blocks > 10 000.
1873 //std::vector<T> h_partials(num_blocks);
1874 //q.memcpy(h_partials.data(), partials, num_blocks * sizeof(T)).wait();
1875 //free(partials, q);
1876 auto h_partials = partials.get_host_access();
1877
1878 // Kahan summation pour précision numérique sur la réduction finale
1879 T sum = 0.0, c = 0.0;
1880 for (size_t b = 0; b < num_blocks; ++b) {
1881 T z = h_partials[b] - c;
1882 T t = sum + z;
1883 c = (t - sum) - z;
1884 sum = t;
1885 }
1886 return sum;
1887 }
1888
1889 template <typename T>
1890 inline std::size_t asynch_dot_product_h100(sycl::buffer<T>& buf_x,
1891 sycl::buffer<T>& buf_y,
1892 sycl::buffer<T>& res,
1893 sycl::event& event)
1894 {
1895 using namespace sycl;
1896 auto& q = m_env->internal()->queue();
1897 const size_t N = buf_x.size();
1898 assert(buf_y.size() == N);
1899
1900 //auto dev = q.get_device();
1901 //const size_t num_sm = dev.get_info<info::device::max_compute_units>(); // 132
1902
1903 // Grid : TARGET_WAVES * num_sm blocs, chacun de WG_SIZE threads,
1904 // chaque thread traite ITEMS_PER_WI éléments → couverture totale
1905 const size_t blocks_needed = (N + WG_SIZE * ITEMS_PER_WI - 1)
1906 / (WG_SIZE * ITEMS_PER_WI);
1907 const size_t num_blocks = std::max(blocks_needed,m_max_num_groups * TARGET_WAVES);
1908 const size_t total_threads = num_blocks * WG_SIZE;
1909
1910 // Allocation USM pour les partiels (un T par bloc)
1911 //partials = malloc_device<T>(num_blocks, q);
1912
1913 // ── Phase 1 : kernel de réduction par blocs ───────────────────────────
1914 event = q.submit(
1915 [&](handler& cgh)
1916 {
1917 auto ax = buf_x.template get_access<access::mode::read>(cgh);
1918 auto ay = buf_y.template get_access<access::mode::read>(cgh);
1919 auto ap = res.template get_access<sycl::access::mode::read_write>(cgh);
1920 // LDS : 1 T par warp dans le bloc
1921 local_accessor<T,1> lds{WG_SIZE / WARP_SIZE, cgh};
1922
1923 //const T* px = ax.get_pointer(); // accès USM-like depuis accessor
1924 //const T* py = ay.get_pointer();
1925 //T* pp = ap.get_pointer();
1926 const size_t n = N;
1927
1928 cgh.parallel_for<class dot_h100_phase1>(
1929 nd_range<1>{{total_threads}, {WG_SIZE}},
1930 [=](nd_item<1> item)
1931 [[intel::reqd_sub_group_size(WARP_SIZE)]]
1932 {
1933 h100::dot_kernel_h100(item, ax, ay, ap, n, lds);
1934 });
1935 });
1936 return num_blocks;
1937 }
1938
1939
1940 template <typename T>
1941 inline T end_dot_product_h100(sycl::event& event,
1942 sycl::buffer<T>& res,
1943 std::size_t num_blocks)
1944 {
1945 event.wait() ;
1946 // ── Phase 2 : réduction finale des partiels sur le CPU ────────────────
1947 // Pour N = 100M Ts → num_blocks ≤ 2048 → 16 KB de partiels.
1948 // Un memcpy D2H de 16 KB est négligeable vs le kernel principal.
1949 // Alternative : second kernel de réduction si num_blocks > 10 000.
1950 //std::vector<T> h_partials(num_blocks);
1951 //m_env->internal()->queue().memcpy(h_partials.data(), partials, num_blocks * sizeof(T)).wait();
1952 //free(partials, q);
1953 auto h_partials = res.get_host_access();
1954
1955 // Kahan summation pour précision numérique sur la réduction finale
1956 T sum = 0.0, c = 0.0;
1957 for (size_t b = 0; b < num_blocks; ++b) {
1958 T z = h_partials[b] - c;
1959 T t = sum + z;
1960 c = (t - sum) - z;
1961 sum = t;
1962 }
1963 return sum;
1964 }
1965
1966 // ---------------------------------------------------------------------------
1967 // Variante moderne SYCL 2020 : sycl::reduction (plus concis, potentiellement
1968 // optimisé par le runtime AdaptiveCPP selon la cible)
1969 // ---------------------------------------------------------------------------
1970
1971 template<typename T>
1972 inline T dot_product_mi300(sycl::buffer<T, 1>& x_buf,
1973 sycl::buffer<T, 1>& y_buf)
1974 {
1975 using namespace mi300 ;
1976 std::cout<<" DOT PROD MI300 : "<<WG_SIZE<<" "<<ITEMS_PER_WI<<std::endl ;
1977
1978 bool use_doublebuf = false;
1979 auto& q = m_env->internal()->queue();
1980 /*
1981
1982 std::size_t n = x_buf.size() ;
1983 sycl::buffer<T, 1> result_buf(&result, 1);
1984
1985 const std::size_t stride = WG_SIZE * ITEMS_PER_WI;
1986 const std::size_t n_padded = ((n + stride - 1) / stride) * stride;
1987
1988 q.submit([&x_buf, &y_buf, &result_buf, n, n_padded, stride](sycl::handler& cgh) {
1989 auto x = x_buf.template get_access<sycl::access::mode::read>(cgh);
1990 auto y = y_buf.template get_access<sycl::access::mode::read>(cgh);
1991 auto r = result_buf.template get_access<sycl::access::mode::read_write>(cgh);
1992 //sycl::accessor r {result_buf, cgh};
1993 auto red = sycl::reduction(r, sycl::plus<T>{});
1994 cgh.parallel_for(
1995 sycl::nd_range<1>{n_padded, WG_SIZE}, red,
1996 [=](sycl::nd_item<1> item, auto& sum) {
1997 const std::size_t lid = item.get_local_id(0);
1998 const std::size_t base = item.get_group(0) * stride;
1999 T acc = 0.0;
2000 #pragma unroll
2001 for (std::size_t k = 0; k < ITEMS_PER_WI; ++k) {
2002 const std::size_t idx = base + lid + k * WG_SIZE;
2003 if (idx < n) acc += x[idx] * y[idx];
2004 }
2005 sum.combine(acc);
2006 });
2007 });
2008 */
2009
2010 std::size_t N = x_buf.size() ;
2011 // Grid : couvrir N en ITEMS_PER_WI éléments/WI
2012 const size_t blocks_needed = (N + WG_SIZE * ITEMS_PER_WI - 1)
2013 / (WG_SIZE * ITEMS_PER_WI);
2014 // Minimum : num_cu × TARGET_WAVES × (WG_SIZE/WAVEFRONT) blocs
2015 // = 228 × 4 × 4 = 3 648 — cohérent avec les profils rocprof
2016 const size_t num_blocks = std::max(blocks_needed,
2017 m_max_num_groups * TARGET_WAVES
2018 * (WG_SIZE / WAVEFRONT));
2019 const size_t total_threads = num_blocks * WG_SIZE;
2020 //std::cout<<" N = "<<N<<" "<<" num_blocks="<<num_blocks<<" nthreads="<<total_threads<<std::endl ;
2021 //double* partials = malloc_device<double>(num_blocks, q);
2022 sycl::buffer<T, 1> partials(num_blocks);
2023
2024 q.submit([&](sycl::handler& cgh)
2025 {
2026 auto ax = x_buf.template get_access<sycl::access::mode::read>(cgh);
2027 auto ay = y_buf.template get_access<sycl::access::mode::read>(cgh);
2028 auto ap = partials.template get_access<sycl::access::mode::read_write>(cgh);
2029 sycl::local_accessor<double,1> lds{N_WARPS_BLOC, cgh}; // 4 doubles = 32 B
2030
2031 //const double* px = ax.get_pointer();
2032 //const double* py = ay.get_pointer();
2033 //double* pp = partials;
2034 const size_t n = N;
2035 const bool db = use_doublebuf;
2036
2037 cgh.parallel_for<class dot_mi300_phase1>(
2038 sycl::nd_range<1>{{total_threads}, {WG_SIZE}},
2039 // ★ sub_group_size(64) — force WF=64 sur gfx942
2040 // Sans cette annotation, ACPP peut émettre WF=32
2041 // et la réduction sub_group ne couvrirait que 32 lanes
2042 [=](sycl::nd_item<1> item)
2043 [[intel::reqd_sub_group_size(WAVEFRONT)]]
2044 {
2045 if (db)
2046 mi300::dot_kernel_mi300_doublebuf(item, ax, ay, ap, n, lds);
2047 else
2048 mi300::dot_kernel_mi300(item, ax, ay, ap, n, lds);
2049 });
2050 }).wait();
2051
2052 // Phase 2 : réduction CPU des partiels
2053 //std::vector<ValueT> h_partials(num_blocks);
2054 //q.memcpy(h_partials.data(), partials, num_blocks * sizeof(double)).wait();
2055 //free(partials, q);
2056 auto h_partials = partials.get_host_access();
2057
2058 // Kahan summation — précision sur la somme des ~3 648 partiels
2059 T sum = 0, c = 0;
2060 for (std::size_t b = 0; b < num_blocks; ++b)
2061 {
2062 T z = h_partials[b] - c;
2063 double t = sum + z;
2064 c = (t - sum) - z;
2065 sum = t;
2066 }
2067 return sum;
2068 }
2069
2070 template <typename T>
2071 inline void asynch_dot_product_mi300(sycl::buffer<T, 1>& x_buf,
2072 sycl::buffer<T, 1>& y_buf,
2073 sycl::buffer<T, 1>& result_buf,
2074 sycl::event& event)
2075 {
2076 using namespace mi300 ;
2077
2078 std::size_t n = x_buf.size() ;
2079 auto& q = m_env->internal()->queue();
2080
2081 const std::size_t stride = WG_SIZE * ITEMS_PER_WI;
2082 const std::size_t n_padded = ((n + stride - 1) / stride) * stride;
2083
2084 event = q.submit([&](sycl::handler& cgh) {
2085 auto x = x_buf.template get_access<sycl::access::mode::read>(cgh);
2086 auto y = y_buf.template get_access<sycl::access::mode::read>(cgh);
2087 auto red = sycl::reduction(result_buf, cgh, sycl::plus<T>{});
2088
2089 cgh.parallel_for(
2090 sycl::nd_range<1>{n_padded, WG_SIZE}, red,
2091 [=](sycl::nd_item<1> item, auto& sum) {
2092 const std::size_t lid = item.get_local_id(0);
2093 const std::size_t base = item.get_group(0) * stride;
2094 T acc = 0.0;
2095 #pragma unroll
2096 for (std::size_t k = 0; k < ITEMS_PER_WI; ++k) {
2097 const std::size_t idx = base + lid + k * WG_SIZE;
2098 if (idx < n) acc += x[idx] * y[idx];
2099 }
2100 sum.combine(acc);
2101 });
2102 });
2103 }
2104
2105
2106
2107 template <typename T>
2108 T end_dot_product_mi300(sycl::event& event,
2109 sycl::buffer<T>& res,
2110 [[maybe_unused]] std::size_t num_blocks)
2111 {
2112 event.wait() ;
2113 auto h_access = res.get_host_access();
2114 return h_access[0];
2115 }
2116
2117 template <typename T>
2118 T dot(sycl::buffer<T>& x,
2119 sycl::buffer<T>& y)
2120 {
2121 switch (m_dot_algo) {
2122 case 0:
2123 return reduce_sum(x, y);
2124 case 1:
2125 return map_reduce_sum(x, y);
2126 case 2:
2127 return map2_reduce_sum(x, y); // with sycl_reduction
2128 case 3:
2129 return map3_reduce_sum(x, y);
2130 case 4: //H100
2131 return dot_product_h100(x, y);
2132 case 5: //MI300
2133 return dot_product_mi300(x, y);
2134 default:
2135 return sycl_reduce_sum(x, y);
2136 }
2137 }
2138
2139 template <typename T>
2140 void dot(sycl::buffer<T>& x,
2141 sycl::buffer<T>& y,
2142 Future<Real>& res)
2143{
2144 switch (m_dot_algo)
2145 {
2146 case 2:
2147 asynch_map4_reduce_sum(x, y, res.deviceValue(), res.event());
2148 res.setWaitFunction([=](sycl::event& event, sycl::buffer<double>& res, std::size_t num_blocks)
2149 {
2150 return this->end_map4_reduce_sum(event,res, num_blocks) ;
2151 }) ;
2152 break;
2153 case 4:
2154 {
2155 std::size_t num_blocks = asynch_dot_product_h100(x, y, res.deviceValue(), res.event());
2156 res.setWaitFunction([=](sycl::event& event, sycl::buffer<double>& res, std::size_t num_blocks)
2157 {
2158 return this->end_dot_product_h100(event, res, num_blocks) ;
2159 }) ;
2160 res.setNumBlocks(num_blocks) ;
2161 }
2162 break;
2163 case 5:
2164 asynch_dot_product_mi300(x, y, res.deviceValue(), res.event());
2165 res.setWaitFunction([=](sycl::event& event, sycl::buffer<T>& res, std::size_t num_blocks)
2166 {
2167 return this->end_dot_product_mi300(event,res, num_blocks) ;
2168 }) ;
2169 break;
2170 default:
2171 asynch_map5_reduce_sum(x, y, res.deviceValue(), res.event());
2172 res.setWaitFunction([=](sycl::event& event, sycl::buffer<T>& res, std::size_t num_blocks)
2173 {
2174 return this->end_map5_reduce_sum(event,res, num_blocks) ;
2175 }) ;
2176 break;
2177 }
2178 }
2179
2180 private:
2181 // clang-format off
2182 SYCLEnv* m_env = nullptr ;
2183 std::size_t m_max_num_groups = 0 ;
2184 std::size_t m_max_work_group_size = 0 ;
2185 std::size_t m_total_threads = 0 ;
2186 // clang-format on
2187
2188 template <typename T>
2189 sycl::buffer<T>& getWorkBuffer(std::size_t size);
2190
2191 mutable sycl::buffer<double>* m_double_work = nullptr;
2192};
2193
2194
2195/*---------------------------------------------------------------------------*/
2196
2197} // namespace Alien::SYCLInternal
2198
2199/*---------------------------------------------------------------------------*/