/* xe2_elementwise.cpp -- elementwise ops, one work-item an element. * * add: y = a + b, b broadcast along rows when it holds one row (a bias add), and with `div`, * y = rd(rd(a + b) / div), rd being y's dtype: libref's elementwise2 (ref_elementwise.cpp). */ #include "xe2_common.h" #include "xe2_ops.h" namespace xe2 { int add(const RadArgs* a, RadStream s) { if (!rad_args_have(a, 3)) return refuse("add: missing operand"); const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[2]; const int64_t n = rad_args_geti_or(a, "n", rad_tensor_numel(Y)); const float div = (float)rad_args_getf_or(a, "div", 1.0); if (!(div != 0.0f) || !sycl::isfinite(div)) return RAD_E_INVAL; if (n <= 0) return RAD_E_SHAPE; Rows ya, aa, ba; if (int rc = rows_view(Y, n, &ya, "add y"); rc < 0) return rc; const int64_t rows = ya.rows; if (rows <= 0 || rad_tensor_numel(A) < rows * n) return RAD_E_SHAPE; const bool bcast = rad_tensor_numel(B) == n && rows > 1; if (!bcast && rad_tensor_numel(B) < rows * n) return RAD_E_SHAPE; if (int rc = rows_view(A, n, &aa, "add a"); rc < 0) return rc; if (int rc = rows_view(B, n, &ba, "add b"); rc < 0) return rc; if (bcast) ba.pitch = 0; sycl::queue* q = queue_of(s); if (!q) return RAD_E_DEVICE; const int64_t total = rows * n; const size_t wg = 256; const size_t groups = (size_t)((total + (int64_t)wg - 1) / (int64_t)wg); return submit([&] { syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) { const int64_t g = (int64_t)it.get_global_id(0); if (g >= total) return; const int64_t r = g / n, i = g % n; const float u = rad_load_f32(aa.base, aa.dtype, r * aa.pitch + i); const float v = rad_load_f32(ba.base, ba.dtype, r * ba.pitch + i); float x = u + v; if (div != 1.0f) x = round_dt(ya.dtype, x) / div; rad_store_f32(ya.base, ya.dtype, r * ya.pitch + i, x); }); }); } } // namespace xe2