char-fork/llama.cpp

git clone https://git.t4t.associates/char-fork/llama.cpp

Jassieluosycl : clamp softmax input to avoid underflow (#24941)e7e3f3509

char/aliceai-t5-moe
14.6 KiB425 linesraw
1#include "softmax.hpp"
2#include <cstdint>
3#include <utility>
4#include <cmath>
5
6
7template <typename T> static __dpct_inline__ float t2f32(T val) {
8    return (float) val;
9}
10
11template <> float __dpct_inline__ t2f32<sycl::half>(sycl::half val) {
12  return sycl::vec<sycl::half, 1>(val)
13      .convert<float, sycl::rounding_mode::automatic>()[0];
14}
15
16struct soft_max_params {
17
18    int64_t nheads;
19    uint32_t n_head_log2;
20    int64_t ncols;
21    int64_t nrows_x;
22    int64_t nrows_y;
23    int64_t ne00;
24    int64_t ne01;
25    int64_t ne02;
26    int64_t ne03;
27    int64_t nb11;
28    int64_t nb12;
29    int64_t nb13;
30
31    int64_t ne12;
32    int64_t ne13;
33    float scale;
34    float max_bias;
35    float m0;
36    float m1;
37};
38
39// When ncols_template == 0 the bounds for the loops in this function are not known and can't be unrolled.
40// As we want to keep pragma unroll for all other cases we suppress the clang transformation warning here.
41#ifdef __clang__
42#pragma clang diagnostic push
43#pragma clang diagnostic ignored "-Wpass-failed"
44#endif // __clang__
45template <bool use_shared, int ncols_template, int block_size_template, typename T>
46static void soft_max_f32(const float *         x,
47                         const T *             mask,
48                         const float *         sinks,
49                         float *               dst,
50                         const soft_max_params p,
51                         uint8_t *             dpct_local) {
52    auto      item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
53    const int ncols    = ncols_template == 0 ? p.ncols : ncols_template;
54    const int block_size = block_size_template == 0
55                               ? item_ct1.get_local_range(2)
56                               : block_size_template;
57    const int nthreads = block_size;
58    const int nwarps = nthreads / WARP_SIZE;
59    const size_t nreduce = nwarps / WARP_SIZE;
60
61    const int tid = item_ct1.get_local_id(2);
62
63    const int64_t i03 = item_ct1.get_group(0);
64    const int64_t i02 = item_ct1.get_group(1);
65    const int64_t i01 = item_ct1.get_group(2);
66
67    //TODO: noncontigous inputs/outputs
68    const int rowx = item_ct1.get_group(2) +
69                     item_ct1.get_group(1) * item_ct1.get_group_range(2) +
70                     item_ct1.get_group(0) * item_ct1.get_group_range(2) *
71                         item_ct1.get_group_range(1);
72
73    const int64_t i11 = i01;
74    const int64_t i12 = i02 % p.ne12;
75    const int64_t i13 = i03 % p.ne13;
76
77    x    += int64_t(rowx)*ncols;
78    mask += (i11*p.nb11 + i12*p.nb12 + i13*p.nb13) / sizeof(T) * (mask != nullptr);
79    dst  += int64_t(rowx)*ncols;
80
81    const int warp_id = item_ct1.get_local_id(2) / WARP_SIZE;
82    const int lane_id = item_ct1.get_local_id(2) % WARP_SIZE;
83
84    const float slope = get_alibi_slope(p.max_bias, i02, p.n_head_log2, p.m0, p.m1);
85
86    float * buf_iw = (float *) dpct_local;
87
88    // shared memory buffer to cache values between iterations:
89    float *vals = use_shared ? buf_iw + sycl::max(nwarps, WARP_SIZE) : dst;
90    float max_val = sinks ? sinks[i02] : -INFINITY;
91#pragma unroll
92    for (int col0 = 0; col0 < ncols; col0 += block_size) {
93        const int col = col0 + tid;
94
95        if (ncols_template == 0 && col >= ncols) {
96            break;
97        }
98
99        const float val = x[col]*p.scale + (mask ? slope*t2f32(mask[col]) : 0.0f);
100
101        vals[col] = val;
102        max_val   = sycl::max(max_val, val);
103    }
104    // find the max value in the block
105    max_val = warp_reduce_max<WARP_SIZE>(max_val);
106
107    if (block_size > WARP_SIZE) {
108        if (lane_id == 0) {
109            buf_iw[warp_id] = max_val;
110        }
111        item_ct1.barrier();
112
113        max_val = -INFINITY;
114        for (int i = lane_id; i < nwarps; i += WARP_SIZE) {
115            max_val = sycl::max(max_val, buf_iw[i]);
116        }
117        max_val = warp_reduce_max<WARP_SIZE>(max_val);
118    }
119    float tmp = 0.0f; // partial sum
120
121#pragma unroll
122    for (int col0 = 0; col0 < ncols; col0 += block_size) {
123        const int col = col0 + tid;
124
125        if (ncols_template == 0 && col >= ncols) {
126            break;
127        }
128
129        const float val = sycl::native::exp(sycl::max(vals[col] - max_val, -80.0f));
130        tmp += val;
131        vals[col] = val;
132    }
133    // find the sum of exps in the block
134    tmp = warp_reduce_sum<WARP_SIZE>(tmp);
135    if (block_size > WARP_SIZE) {
136        item_ct1.barrier();
137        if (warp_id == 0) {
138            buf_iw[lane_id] = 0.0f;
139            for (size_t i = 1; i < nreduce; i += 1) {
140                buf_iw[lane_id + i * WARP_SIZE] = 0.f;
141            }
142        }
143        item_ct1.barrier();
144
145        if (lane_id == 0) {
146            buf_iw[warp_id] = tmp;
147        }
148        item_ct1.barrier();
149
150        tmp = buf_iw[lane_id];
151        for (size_t i = 1; i < nreduce; i += 1) {
152            tmp += buf_iw[lane_id + i * WARP_SIZE];
153        }
154        tmp = warp_reduce_sum<WARP_SIZE>(tmp);
155    }
156    if (sinks) {
157        tmp += sycl::native::exp(sycl::max(sinks[i02] - max_val, -80.0f));
158    }
159    const float inv_sum = 1.0f / tmp;
160
161#pragma unroll
162    for (int col0 = 0; col0 < ncols; col0 += block_size) {
163        const int col = col0 + tid;
164
165        if (ncols_template == 0 && col >= ncols) {
166            return;
167        }
168
169        dst[col] = vals[col] * inv_sum;
170    }
171}
172#ifdef __clang__
173#pragma clang diagnostic pop
174#endif // __clang__
175
176static void soft_max_back_f32(const float *grad, const float *dstf, float *dst,
177                              const int ncols, const float scale) {
178    auto      item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
179    const int tid      = item_ct1.get_local_id(2);
180    const int rowx     = item_ct1.get_group(2);
181
182    grad += int64_t(rowx)*ncols;
183    dstf += int64_t(rowx)*ncols;
184    dst  += int64_t(rowx)*ncols;
185
186    float dgf_dot = 0.0f; // dot product of dst from forward pass and gradients
187
188    for (int col = tid; col < ncols; col += WARP_SIZE) {
189        dgf_dot += dstf[col]*grad[col];
190    }
191
192    dgf_dot = warp_reduce_sum<WARP_SIZE>(dgf_dot);
193
194    for (int col = tid; col < ncols; col += WARP_SIZE) {
195        dst[col] = scale * (grad[col] - dgf_dot) * dstf[col];
196    }
197}
198
199template <int... Ns, typename T>
200static void launch_soft_max_kernels(const float *           x,
201                                    const T *               mask,
202                                    const float *           sinks,
203                                    float *                 dst,
204                                    const soft_max_params & p,
205                                    dpct::queue_ptr         stream,
206                                    dpct::dim3              block_dims,
207                                    dpct::dim3              block_nums,
208                                    size_t                  nbytes_shared)
209{
210    auto launch_kernel = [=](auto I) -> bool {
211        constexpr int ncols = decltype(I)::value;
212        constexpr int block = (ncols > 1024 ? 1024 : ncols);
213        if (p.ncols == ncols) {
214            stream->submit([&](sycl::handler &cgh) {
215                sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
216                    sycl::range<1>(nbytes_shared), cgh);
217
218                cgh.parallel_for(
219                    sycl::nd_range<3>(block_nums * block_dims, block_dims),
220                    [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(
221                        WARP_SIZE)]] {
222                        soft_max_f32<true, ncols, block>(
223                            x, mask, sinks, dst, p,
224                            dpct_local_acc_ct1
225                                .get_multi_ptr<sycl::access::decorated::no>()
226                                .get());
227                        GGML_UNUSED(item_ct1);
228                    });
229            });
230            return true;
231        }
232        return false;
233    };
234
235    // unary fold over launch_kernel
236    if ((launch_kernel(std::integral_constant<int, Ns>{}) || ...)) {
237        return;
238    }
239
240    stream->submit([&](sycl::handler &cgh) {
241        sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
242            sycl::range<1>(nbytes_shared), cgh);
243
244        cgh.parallel_for(
245            sycl::nd_range<3>(block_nums * block_dims, block_dims),
246            [=](sycl::nd_item<3> item_ct1)
247                [[sycl::reqd_sub_group_size(WARP_SIZE)]] {
248                    soft_max_f32<true, 0, 0>(
249                        x, mask, sinks, dst, p,
250                        dpct_local_acc_ct1
251                            .get_multi_ptr<sycl::access::decorated::no>()
252                            .get());
253                    GGML_UNUSED(item_ct1);
254                });
255    });
256}
257
258template <typename T>
259static void soft_max_f32_sycl(const float *x, const T *mask,
260                              const float *sinks, float *dst,
261                              const soft_max_params &params,
262                              dpct::queue_ptr stream, int device) {
263    int nth = WARP_SIZE;
264    int max_block_size = ggml_sycl_info().max_work_group_sizes[device];
265    const int64_t ncols_x = params.ncols;
266
267    while (nth < ncols_x && nth < max_block_size) nth *= 2;
268    if (nth>max_block_size) nth = max_block_size;
269
270    const dpct::dim3 block_dims(nth, 1, 1);
271    const dpct::dim3 block_nums(params.ne01, params.ne02, params.ne03);
272    const size_t nbytes_shared =
273        (GGML_PAD(ncols_x, WARP_SIZE) + WARP_SIZE) * sizeof(float);
274
275    const int id       = get_current_device_id();
276    const size_t smpbo = ggml_sycl_info().devices[id].smpbo;
277
278    if (nbytes_shared <= smpbo && ncols_x <= max_block_size) {
279        launch_soft_max_kernels<32, 64, 128, 256, 512, 1024, 2048, 4096>(
280            x, mask, sinks, dst, params, stream, block_dims, block_nums,
281            nbytes_shared);
282    } else {
283        const size_t nbytes_shared_low = WARP_SIZE * sizeof(float);
284
285        stream->submit([&](sycl::handler &cgh) {
286            sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
287                sycl::range<1>(nbytes_shared_low), cgh);
288
289            cgh.parallel_for(
290                sycl::nd_range<3>(block_nums * block_dims, block_dims),
291                [=](sycl::nd_item<3> item_ct1)
292                    [[sycl::reqd_sub_group_size(WARP_SIZE)]] {
293                    soft_max_f32<false, 0, 0>(
294                        x, mask, sinks, dst, params,
295                        dpct_local_acc_ct1
296                            .get_multi_ptr<sycl::access::decorated::no>()
297                            .get());
298                    GGML_UNUSED(item_ct1);
299                });
300        });
301    }
302}
303
304static void soft_max_back_f32_sycl(const float *   grad,
305                                   const float *   dstf,
306                                   float *         dst,
307                                   const int       ncols,
308                                   const int       nrows,
309                                   const float     scale,
310                                   dpct::queue_ptr stream) {
311    const dpct::dim3 block_dims(WARP_SIZE, 1, 1);
312    const dpct::dim3 block_nums(nrows, 1, 1);
313
314    stream->parallel_for(sycl::nd_range<3>(block_nums * block_dims, block_dims),
315                         [=](sycl::nd_item<3> item_ct1) {
316                             soft_max_back_f32(grad, dstf, dst, ncols, scale);
317                             GGML_UNUSED(item_ct1);
318                         });
319}
320
321void ggml_sycl_op_soft_max(ggml_backend_sycl_context & ctx, ggml_tensor * dst) {
322    scope_op_debug_print scope_dbg_print(__func__, dst, /*num_src=*/2);
323
324    const ggml_tensor * src0 = dst->src[0];
325    const ggml_tensor * src1 = dst->src[1];
326    const ggml_tensor * src2 = dst->src[2];
327
328    const float * src0_d = (const float *) src0->data;
329    const void  * src1_d = src1 ? (const void *) src1->data : nullptr;
330    const void  * src2_d = src2 ? (const void *) src2->data : nullptr;
331    float       *  dst_d = (float *) dst->data;
332
333    dpct::queue_ptr stream = ctx.stream();
334
335    GGML_ASSERT(src0->type == GGML_TYPE_F32);
336    GGML_ASSERT( dst->type == GGML_TYPE_F32);
337
338    // src1 contains mask and it is optional
339    GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_F32);
340
341    const int64_t nrows_x = ggml_nrows(src0);
342    const int64_t nrows_y = src0->ne[1];
343
344    const int64_t ne00 = src0->ne[0];
345
346    float scale    = 1.0f;
347    float max_bias = 0.0f;
348
349    memcpy(&scale,    (const float *) dst->op_params + 0, sizeof(float));
350    memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
351
352    const bool use_f16 = (src1 && src1->type == GGML_TYPE_F16);
353
354    const int64_t nb11 = src1 ? src1->nb[1] : 1;
355    const int64_t nb12 = src1 ? src1->nb[2] : 1;
356    const int64_t nb13 = src1 ? src1->nb[3] : 1;
357
358    const int64_t ne12 = src1 ? src1->ne[2] : 1;
359    const int64_t ne13 = src1 ? src1->ne[3] : 1;
360
361    const uint32_t n_head      = src0->ne[2];
362    const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head));
363
364    const float m0 = powf(2.0f, -(max_bias       ) / n_head_log2);
365    const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
366
367
368    soft_max_params params = {};
369    params.nheads = src0->ne[2];
370    params.n_head_log2 = n_head_log2;
371    params.ncols = ne00;
372    params.nrows_x = nrows_x;
373    params.nrows_y = nrows_y;
374    params.ne00 = src0->ne[0];
375    params.ne01 = src0->ne[1];
376    params.ne02 = src0->ne[2];
377    params.ne03 = src0->ne[3];
378    params.nb11 = nb11;
379    params.nb12 = nb12;
380    params.nb13 = nb13;
381    params.ne12 = ne12;
382    params.ne13 = ne13;
383    params.scale = scale;
384    params.max_bias = max_bias;
385    params.m0 = m0;
386    params.m1 = m1;
387
388    if (use_f16) {
389        soft_max_f32_sycl(src0_d, (const sycl::half *)src1_d,
390                          (const float *)src2_d, dst_d, params, stream,
391                          ctx.device);
392    } else {
393        soft_max_f32_sycl(src0_d, (const float *)src1_d, (const float *)src2_d,
394                          dst_d, params, stream, ctx.device);
395    }
396}
397
398void ggml_sycl_op_soft_max_back(ggml_backend_sycl_context & ctx, ggml_tensor * dst) {
399    scope_op_debug_print scope_dbg_print(__func__, dst, /*num_src=*/2);
400    const ggml_tensor * src0 = dst->src[0]; // grad
401    const ggml_tensor * src1 = dst->src[1]; // forward pass output
402
403    const float * src0_d = (const float *) src0->data;
404    const float * src1_d = (const float *) src1->data;
405    float       * dst_d  = (float       *) dst->data;
406
407    dpct::queue_ptr stream = ctx.stream();
408
409    GGML_ASSERT(src0->type == GGML_TYPE_F32);
410    GGML_ASSERT(src1->type == GGML_TYPE_F32);
411    GGML_ASSERT( dst->type == GGML_TYPE_F32);
412
413    const int64_t ncols = src0->ne[0];
414    const int64_t nrows = ggml_nrows(src0);
415
416    float scale    = 1.0f;
417    float max_bias = 0.0f;
418
419    memcpy(&scale,    (const float *) dst->op_params + 0, sizeof(float));
420    memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
421
422    GGML_ASSERT(max_bias == 0.0f);
423
424    soft_max_back_f32_sycl(src0_d, src1_d, dst_d, ncols, nrows, scale, stream);
425}