char-fork/llama.cpp

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

David Friehscuda: fix warnings for unused variable/function (#26688)5b87ed30f

char/aliceai-t5-moe
29.2 KiB697 linesraw
1#include "quantize.cuh"
2#include <cstdint>
3
4#if defined(BLACKWELL_MMA_AVAILABLE)
5// this maps to 256-bit loads in PTX on supported devices,
6// and otherwise falls back to 2 128-bit loads
7struct __builtin_align__(32) float8 {
8    float x; float y; float z; float w;
9    float p; float q; float r; float s;
10};
11
12#if CUDART_VERSION >= 12080
13static __device__ __forceinline__ float nvfp4_native_scale_error(
14        const float vals[QK_NVFP4_SUB], const float inv_col_scale, const float inv_scale, const float scale) {
15    const float scale_dequant = 2.0f * scale;
16    float err = 0.0f;
17
18#pragma unroll
19    for (int k = 0; k < QK_NVFP4_SUB; k += 4) {
20        const float v0 = vals[k + 0] * inv_col_scale;
21        const float v1 = vals[k + 1] * inv_col_scale;
22        const float v2 = vals[k + 2] * inv_col_scale;
23        const float v3 = vals[k + 3] * inv_col_scale;
24
25        const __nv_fp4x4_e2m1 q(make_float4(v0 * inv_scale, v1 * inv_scale, v2 * inv_scale, v3 * inv_scale));
26        const __nv_fp4x4_storage_t q_storage = q.__x;
27        const __nv_fp4x2_storage_t q_lo = static_cast<__nv_fp4x2_storage_t>(q_storage);
28        const __nv_fp4x2_storage_t q_hi = static_cast<__nv_fp4x2_storage_t>(q_storage >> 8U);
29
30        const __half2_raw hraw2_lo = __nv_cvt_fp4x2_to_halfraw2(q_lo, __NV_E2M1);
31        const __half2_raw hraw2_hi = __nv_cvt_fp4x2_to_halfraw2(q_hi, __NV_E2M1);
32        const __half2 h2_lo = static_cast<__half2>(hraw2_lo);
33        const __half2 h2_hi = static_cast<__half2>(hraw2_hi);
34        const float2 dq_lo = __half22float2(h2_lo);
35        const float2 dq_hi = __half22float2(h2_hi);
36
37        const float err0 = fabsf(v0) - fabsf(dq_lo.x) * scale_dequant;
38        const float err1 = fabsf(v1) - fabsf(dq_lo.y) * scale_dequant;
39        const float err2 = fabsf(v2) - fabsf(dq_hi.x) * scale_dequant;
40        const float err3 = fabsf(v3) - fabsf(dq_hi.y) * scale_dequant;
41
42        err = fmaf(err0, err0, err);
43        err = fmaf(err1, err1, err);
44        err = fmaf(err2, err2, err);
45        err = fmaf(err3, err3, err);
46    }
47
48    return err;
49}
50#endif // CUDART_VERSION >= 12080
51#endif // defined(BLACKWELL_MMA_AVAILABLE)
52
53__launch_bounds__(CUDA_QUANTIZE_BLOCK_SIZE, 1)
54static __global__ void quantize_q8_1(
55        const float * x_ptr, void * vy_ptr,
56        const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
57        const int64_t ne0, const uint32_t ne1, const uint3 ne2) {
58    ggml_cuda_pdl_lc();
59    const float * GGML_CUDA_RESTRICT x  = x_ptr;
60    void        * GGML_CUDA_RESTRICT vy = vy_ptr;
61    const int64_t i0 = (int64_t)blockDim.x*blockIdx.x + threadIdx.x;
62
63    if (i0 >= ne0) {
64        return;
65    }
66
67    const int64_t i3 = fastdiv(blockIdx.z, ne2);
68    const int64_t i2 = blockIdx.z - i3*ne2.z;
69    const int64_t i1 = blockIdx.y;
70
71    const int64_t & i00 = i0;
72    const int64_t & i01 = i1;
73    const int64_t & i02 = i2;
74    const int64_t & i03 = i3;
75
76    const int64_t i_cont = ((i3*ne2.z + i2) * ne1 + i1) * ne0 + i0;
77
78    block_q8_1 * y = (block_q8_1 *) vy;
79
80    const int64_t ib  = i_cont / QK8_1; // block index
81    const int64_t iqs = i_cont % QK8_1; // quant index
82
83    ggml_cuda_pdl_sync();
84    const float xi = i0 < ne00 ? x[i03*s03 + i02*s02 + i01*s01 + i00] : 0.0f;
85    float amax = fabsf(xi);
86    float sum = xi;
87
88    amax = warp_reduce_max<QK8_1>(amax);
89    sum  = warp_reduce_sum<QK8_1>(sum);
90
91    const float  d = amax / 127.0f;
92    const int8_t q = amax == 0.0f ? 0 : roundf(xi / d);
93
94    y[ib].qs[iqs] = q;
95
96    if (iqs > 0) {
97        return;
98    }
99
100    y[ib].ds = make_half2(d, sum);
101}
102
103__device__ __forceinline__ uint8_t compute_e8m0_scale(float amax) {
104    if (!(amax > 0.0f)) {
105        return 0;
106    }
107
108    // FP4 E2M1: max exponent (unbiased) is 2.
109    constexpr int FP4_E2M1_EMAX = 2;
110
111    const float e = log2f(amax);
112
113    // "even" -> round-to-nearest integer, ties-to-even
114    const int e_int = __float2int_rn(e);
115
116    const int shared_exp = e_int - FP4_E2M1_EMAX;
117
118    int biased = shared_exp + 127;
119
120    biased = max(biased, 0);
121    biased = min(biased, 254);
122
123    return static_cast<uint8_t>(biased);
124}
125
126// scatter: grid over tokens, quantize once, write to all the token's compact rows
127template <bool scatter, bool use_aligned_float8>
128static __global__ void quantize_mmq_nvfp4(
129        const float * __restrict__ x, const int32_t * __restrict__ ids, void * __restrict__ vy, float * __restrict__ scale,
130        const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
131        const int64_t ne0, const int64_t ne1, const int64_t ne2, const int n_expert_used) {
132#if defined(BLACKWELL_MMA_AVAILABLE)
133
134    const int64_t blocks_per_col = (ne0 + QK_FP4_MMQ - 1) / QK_FP4_MMQ;
135
136    int64_t base_idx;
137    if constexpr (scatter) {
138        base_idx = (int64_t) blockIdx.x * s02; // one physical row per token
139    } else {
140        const int64_t i2  = blockIdx.y % ne2;
141        const int64_t i3  = blockIdx.y / ne2;
142        const int64_t i01 = ids ? ids[blockIdx.x] : blockIdx.x;
143        base_idx = i3 * s03 + i2 * s02 + i01 * s01;
144    }
145    const float * __restrict__  x_row = x + base_idx;
146
147    float amax = 0.0f;
148    if constexpr (use_aligned_float8) {
149        for (int64_t i0 = 8 * threadIdx.x; i0 < ne00; i0 += 8 * blockDim.x) {
150            const float * x_base = x_row + i0;
151            const float8 v = reinterpret_cast<const float8 *>(x_base)[0];
152            amax = fmaxf(amax, fabsf(v.x));
153            amax = fmaxf(amax, fabsf(v.y));
154            amax = fmaxf(amax, fabsf(v.z));
155            amax = fmaxf(amax, fabsf(v.w));
156            amax = fmaxf(amax, fabsf(v.p));
157            amax = fmaxf(amax, fabsf(v.q));
158            amax = fmaxf(amax, fabsf(v.r));
159            amax = fmaxf(amax, fabsf(v.s));
160        }
161    } else {
162        for (int64_t i0 = threadIdx.x; i0 < ne00; i0 += blockDim.x) {
163            amax = fmaxf(amax, fabsf(x_row[i0]));
164        }
165    }
166
167    amax = warp_reduce_max<WARP_SIZE>(amax);
168
169    __shared__ float warp_amax[CUDA_QUANTIZE_BLOCK_SIZE_MMQ / WARP_SIZE];
170    const int lane = threadIdx.x % WARP_SIZE;
171    const int warp = threadIdx.x / WARP_SIZE;
172
173    if (lane == 0) {
174        warp_amax[warp] = amax;
175    }
176    __syncthreads();
177
178    if (warp == 0) {
179        amax = threadIdx.x < int(CUDA_QUANTIZE_BLOCK_SIZE_MMQ / WARP_SIZE) ? warp_amax[lane] : 0.0f;
180        amax = warp_reduce_max<WARP_SIZE>(amax);
181        if (lane == 0) {
182            warp_amax[0] = amax / (6.0f * 448.0f);
183            if constexpr (scatter) {
184#pragma unroll
185                for (int slot = 0; slot < n_expert_used; ++slot) {
186                    const int64_t i = ids[(int64_t) blockIdx.x * n_expert_used + slot];
187                    scale[i] = warp_amax[0];
188                }
189            } else {
190                scale[blockIdx.y * ne1 + blockIdx.x] = warp_amax[0];
191            }
192        }
193    }
194    __syncthreads();
195
196    block_fp4_mmq * y = (block_fp4_mmq *) vy;
197    const int64_t n_subblocks = (ne0 + QK_NVFP4_SUB - 1) / QK_NVFP4_SUB;
198
199    for (int64_t isb = threadIdx.x; isb < n_subblocks; isb += blockDim.x) {
200        const int64_t i0_base = isb * QK_NVFP4_SUB;
201        const int64_t k_block = i0_base / QK_FP4_MMQ;
202        const int sub = (i0_base % QK_FP4_MMQ) / QK_NVFP4_SUB;
203
204        const float row_scale = warp_amax[0];
205        const float inv_col_scale = row_scale > 0.0f ? 1.0f / row_scale : 0.0f;
206
207        float vals[QK_NVFP4_SUB];
208        if constexpr (use_aligned_float8) {
209            const float * x_base = x_row + i0_base;
210            const float8 v0 = i0_base +  7 < ne00 ? reinterpret_cast<const float8 *>(x_base)[0]     : float8{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
211            const float8 v1 = i0_base + 15 < ne00 ? reinterpret_cast<const float8 *>(x_base + 8)[0] : float8{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
212            vals[0] = v0.x; vals[1] = v0.y; vals[2] = v0.z; vals[3] = v0.w;
213            vals[4] = v0.p; vals[5] = v0.q; vals[6] = v0.r; vals[7] = v0.s;
214            vals[8] = v1.x; vals[9] = v1.y; vals[10] = v1.z; vals[11] = v1.w;
215            vals[12] = v1.p; vals[13] = v1.q; vals[14] = v1.r; vals[15] = v1.s;
216        } else {
217#pragma unroll
218            for (int k = 0; k < QK_NVFP4_SUB; ++k) {
219                const int64_t i00 = i0_base + k;
220                vals[k] = i00 < ne00 ? x_row[i00] : 0.0f;
221            }
222        }
223
224        uint32_t q0 = 0;
225        uint32_t q1 = 0;
226
227        float amax_sub = 0.0f;
228#pragma unroll
229        for (int k = 0; k < QK_NVFP4_SUB; ++k) {
230            amax_sub = fmaxf(amax_sub, fabsf(vals[k] * inv_col_scale));
231        }
232
233        static constexpr int test_offsets[5] = { 0, -1, 1, -2, 2 };
234        const int first_fp8_code = (int) ggml_cuda_fp32_to_ue4m3(amax_sub / 6.0f);
235
236        uint8_t fp8_code = (uint8_t) first_fp8_code;
237        float subblock_scale = ggml_cuda_ue4m3_to_fp32(fp8_code);
238        float inv_scale_err = subblock_scale > 0.0f ? 0.5f / subblock_scale : 0.0f;
239#if CUDART_VERSION >= 12080
240        float best_err = nvfp4_native_scale_error(vals, inv_col_scale, inv_scale_err, subblock_scale);
241#else
242        float best_err = 0.0f;
243#pragma unroll
244        for (int k = 0; k < QK_NVFP4_SUB; ++k) {
245            const float v = vals[k] * inv_col_scale;
246            const uint8_t q = ggml_cuda_float_to_fp4_e2m1(v, inv_scale_err);
247            const float err_diff = fabsf(v) - fabsf(kvalues_fp4[q & 0x7]) * subblock_scale;
248            best_err = fmaf(err_diff, err_diff, best_err);
249        }
250#endif // CUDART_VERSION >= 12080
251
252#pragma unroll
253        for (int i = 1; i < 5; ++i) {
254            const int test_code = first_fp8_code + test_offsets[i];
255            if (test_code < 0 || test_code > 0x7e) {
256                continue;
257            }
258
259            const float test_scale = ggml_cuda_ue4m3_to_fp32((uint8_t) test_code);
260            const float test_inv_scale = test_scale > 0.0f ? 0.5f / test_scale : 0.0f;
261#if CUDART_VERSION >= 12080
262            const float cur_err = nvfp4_native_scale_error(vals, inv_col_scale, test_inv_scale, test_scale);
263#else
264            float cur_err = 0.0f;
265#pragma unroll
266            for (int k = 0; k < QK_NVFP4_SUB; ++k) {
267                const float v = vals[k] * inv_col_scale;
268                const uint8_t q = ggml_cuda_float_to_fp4_e2m1(v, test_inv_scale);
269                const float err_diff = fabsf(v) - fabsf(kvalues_fp4[q & 0x7]) * test_scale;
270                cur_err = fmaf(err_diff, err_diff, cur_err);
271            }
272#endif // CUDART_VERSION >= 12080
273
274            if (cur_err < best_err) {
275                best_err = cur_err;
276                fp8_code = (uint8_t) test_code;
277                subblock_scale = test_scale;
278            }
279        }
280#if CUDART_VERSION >= 12080
281        const float inv_scale = subblock_scale > 0.0f ? 0.5f / subblock_scale : 0.0f;
282        const float s = inv_col_scale * inv_scale;
283
284        __nv_fp4x4_e2m1 q0_lo(make_float4(vals[0] * s, vals[8]  * s, vals[1] * s, vals[9]  * s));
285        __nv_fp4x4_e2m1 q0_hi(make_float4(vals[2] * s, vals[10] * s, vals[3] * s, vals[11] * s));
286        __nv_fp4x4_e2m1 q1_lo(make_float4(vals[4] * s, vals[12] * s, vals[5] * s, vals[13] * s));
287        __nv_fp4x4_e2m1 q1_hi(make_float4(vals[6] * s, vals[14] * s, vals[7] * s, vals[15] * s));
288
289        const char2 q0_lo_c = *reinterpret_cast<char2 *>(&q0_lo);
290        const char2 q0_hi_c = *reinterpret_cast<char2 *>(&q0_hi);
291        const char2 q1_lo_c = *reinterpret_cast<char2 *>(&q1_lo);
292        const char2 q1_hi_c = *reinterpret_cast<char2 *>(&q1_hi);
293
294        q0 = uint32_t(uint8_t(q0_lo_c.x)) | (uint32_t(uint8_t(q0_lo_c.y)) <<  8) |
295            (uint32_t(uint8_t(q0_hi_c.x)) << 16) | (uint32_t(uint8_t(q0_hi_c.y)) << 24);
296        q1 = uint32_t(uint8_t(q1_lo_c.x)) | (uint32_t(uint8_t(q1_lo_c.y)) <<  8) |
297            (uint32_t(uint8_t(q1_hi_c.x)) << 16) | (uint32_t(uint8_t(q1_hi_c.y)) << 24);
298#else
299        const float inv_scale = subblock_scale > 0.0f ? 0.5f / subblock_scale : 0.0f;
300#pragma unroll
301        for (int k = 0; k < QK_NVFP4_SUB / 4; ++k) {
302            q0 |= uint32_t(ggml_cuda_float_to_fp4_e2m1(vals[k + 0] * inv_col_scale, inv_scale)) << (8 * k);
303            q0 |= uint32_t(ggml_cuda_float_to_fp4_e2m1(vals[k + 8] * inv_col_scale, inv_scale)) << (8 * k + 4);
304            q1 |= uint32_t(ggml_cuda_float_to_fp4_e2m1(vals[k + 4] * inv_col_scale, inv_scale)) << (8 * k);
305            q1 |= uint32_t(ggml_cuda_float_to_fp4_e2m1(vals[k + 12] * inv_col_scale, inv_scale)) << (8 * k + 4);
306        }
307#endif // CUDART_VERSION >= 12080
308
309        if constexpr (scatter) {
310#pragma unroll
311            for (int slot = 0; slot < n_expert_used; ++slot) {
312                const int64_t i = ids[(int64_t) blockIdx.x * n_expert_used + slot];
313                block_fp4_mmq * yb = y + (k_block * ne1 + i);
314                uint32_t * yqs = reinterpret_cast<uint32_t *>(yb->qs);
315                yqs[2 * sub + 0] = q0;
316                yqs[2 * sub + 1] = q1;
317                reinterpret_cast<uint8_t *>(yb->d4)[sub] = fp8_code;
318            }
319        } else {
320            block_fp4_mmq * yb = y + (blockIdx.y * ((int64_t) blocks_per_col * ne1) + k_block * ne1 + blockIdx.x);
321            uint32_t * yqs = reinterpret_cast<uint32_t *>(yb->qs);
322            yqs[2 * sub + 0] = q0;
323            yqs[2 * sub + 1] = q1;
324            reinterpret_cast<uint8_t *>(yb->d4)[sub] = fp8_code;
325        }
326    }
327#else
328    GGML_UNUSED_VARS(x, ids, vy, scale, ne00, s01, s02, s03, ne0, ne1, ne2, n_expert_used);
329    NO_DEVICE_CODE; // This is for Blackwell NVFP4 activations only.
330#endif // defined(BLACKWELL_MMA_AVAILABLE)
331
332}
333
334// quantize values in the format mxfp4 is stored which is interleaved nibbles
335// i.e. a block a0-a31 is represented as a0a16,a1a17 ...a15a31
336// scatter: grid over tokens, quantize once, write to all the token's compact rows
337template <bool scatter>
338static __global__ void quantize_mmq_mxfp4(const float * __restrict__ x,
339                                          const int32_t * __restrict__ ids,
340                                          void * __restrict__ vy,
341                                          const int64_t ne00,
342                                          const int64_t s01,
343                                          const int64_t s02,
344                                          const int64_t s03,
345                                          const int64_t ne0,
346                                          const int     ne1,
347                                          const int     ne2,
348                                          const int     n_expert_used) {
349    constexpr int vals_per_scale = 32;
350    constexpr int vals_per_warp  = 2 * vals_per_scale;  // Each warp processes 2 blocks of 32 = 64 values
351
352    const int warp_id = threadIdx.y;
353    const int lane_id_32 = threadIdx.x;
354
355    const int nwarps = blockDim.y;
356
357    const int64_t warp_start_offset = (blockIdx.y * nwarps + warp_id) * vals_per_warp;
358
359    if (warp_start_offset >= ne0) {
360        return;
361    }
362
363    const int64_t block_fp4_mmq_size = QK_FP4_MMQ;
364    const int64_t k_block            = warp_start_offset / block_fp4_mmq_size;
365    const int64_t quad_idx_in_block  = (warp_start_offset % block_fp4_mmq_size) / vals_per_warp;
366
367    const int group_id = lane_id_32 / 4;
368    const int lane_in_group = lane_id_32 % 4;
369    const int base = group_id * 2;
370
371    ggml_cuda_pdl_sync();
372    int64_t base_pos;
373    if constexpr (scatter) {
374        base_pos = (int64_t) blockIdx.x * s02; // one physical row per token
375    } else {
376        const int64_t i2  = blockIdx.z % ne2;
377        const int64_t i3  = blockIdx.z / ne2;
378        const int64_t i01 = ids ? ids[blockIdx.x] : blockIdx.x;
379        base_pos = i3 * s03 + i2 * s02 + i01 * s01;
380    }
381
382    uint8_t scales[2];
383    char2   packed[2];
384
385#pragma unroll
386    for (int b = 0; b < 2; ++b) {
387        const int64_t i0 = warp_start_offset + b * vals_per_scale + lane_id_32;
388        const float xi = (i0 < ne00) ? x[base_pos + i0] : 0.0f;
389
390        float amax = fabsf(xi);
391#pragma unroll
392        for (int mask = 16; mask > 0; mask >>= 1) {
393            amax = fmaxf(amax, __shfl_xor_sync(0xFFFFFFFF, amax, mask, WARP_SIZE));
394        }
395
396        const uint8_t e = compute_e8m0_scale(amax);
397        scales[b] = e;
398        const float inv_s = (amax == 0.0f) ? 0.0f : __frcp_rn(ggml_cuda_e8m0_to_fp32(e));
399
400#if CUDART_VERSION >= 12080
401        const float scaled_val = xi * inv_s;
402
403        const float val0 = __shfl_sync(0xFFFFFFFF, scaled_val, base, WARP_SIZE);
404        const float val1 = __shfl_sync(0xFFFFFFFF, scaled_val, base + 16, WARP_SIZE);
405        const float val2 = __shfl_sync(0xFFFFFFFF, scaled_val, base + 1, WARP_SIZE);
406        const float val3 = __shfl_sync(0xFFFFFFFF, scaled_val, base + 17, WARP_SIZE);
407
408        __nv_fp4x4_e2m1 fp4_packed(make_float4(val0, val1, val2, val3));
409        packed[b] = *(char2 *) &fp4_packed;
410#else
411        // Fallback: manual FP4 conversion using LUT
412        const uint8_t q_val = ggml_cuda_float_to_fp4_e2m1(xi, inv_s);
413
414        const uint8_t q_lo_0 = __shfl_sync(0xFFFFFFFF, q_val, base,      WARP_SIZE);
415        const uint8_t q_lo_1 = __shfl_sync(0xFFFFFFFF, q_val, base + 1,  WARP_SIZE);
416        const uint8_t q_hi_0 = __shfl_sync(0xFFFFFFFF, q_val, base + 16, WARP_SIZE);
417        const uint8_t q_hi_1 = __shfl_sync(0xFFFFFFFF, q_val, base + 17, WARP_SIZE);
418
419        char2 q;
420        q.x = (q_hi_0 << 4) | q_lo_0;
421        q.y = (q_hi_1 << 4) | q_lo_1;
422        packed[b] = q;
423#endif // CUDART_VERSION >= 12080
424    }
425
426    block_fp4_mmq * y = (block_fp4_mmq *) vy;
427    if constexpr (scatter) {
428#pragma unroll
429        for (int slot = 0; slot < n_expert_used; ++slot) {
430            const int64_t i = ids[(int64_t) blockIdx.x * n_expert_used + slot];
431            block_fp4_mmq * yb = y + (k_block * ne1 + i);
432            char2 * yqs2 = (char2 *) yb->qs;
433            if (lane_in_group == 0) {
434                yqs2[quad_idx_in_block * 16 + 0 * 8 + group_id] = packed[0];
435                yqs2[quad_idx_in_block * 16 + 1 * 8 + group_id] = packed[1];
436            }
437            if (lane_id_32 == 0) {
438                yb->d4[quad_idx_in_block] = (scales[1] << 8) | scales[0];
439            }
440        }
441    } else {
442        const int64_t ib0 = blockIdx.z * ((int64_t) ne1 * (ne0 / block_fp4_mmq_size));
443        block_fp4_mmq * yb = y + (ib0 + k_block * ne1 + blockIdx.x);
444        char2 * yqs2 = (char2 *) yb->qs;
445        if (lane_in_group == 0) {
446            yqs2[quad_idx_in_block * 16 + 0 * 8 + group_id] = packed[0];
447            yqs2[quad_idx_in_block * 16 + 1 * 8 + group_id] = packed[1];
448        }
449        if (lane_id_32 == 0) {
450            yb->d4[quad_idx_in_block] = (scales[1] << 8) | scales[0];
451        }
452    }
453    GGML_UNUSED(n_expert_used);
454}
455
456// scatter: grid over tokens, quantize once, write to all the token's compact rows
457template <mmq_q8_1_ds_layout ds_layout, bool scatter>
458static __global__ void quantize_mmq_q8_1(
459        const float * __restrict__ x, const int32_t * __restrict__ ids, void * __restrict__ vy,
460        const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
461        const int64_t ne0, const int ne1, const int ne2, const int n_expert_used) {
462
463    constexpr int vals_per_scale = ds_layout == MMQ_Q8_1_DS_LAYOUT_D2S6 ? 64 : 32;
464    constexpr int vals_per_sum   = ds_layout == MMQ_Q8_1_DS_LAYOUT_D2S6 ? 16 : 32;
465
466    const int64_t i0 = ((int64_t)blockDim.x*blockIdx.y + threadIdx.x)*4;
467
468    if (i0 >= ne0) {
469        return;
470    }
471
472    const int64_t i00 = i0;
473    ggml_cuda_pdl_sync();
474
475    int64_t base_idx;
476    if constexpr (scatter) {
477        base_idx = (int64_t) blockIdx.x * s02; // one physical row per token
478    } else {
479        const int64_t i2  = blockIdx.z % ne2;
480        const int64_t i3  = blockIdx.z / ne2;
481        const int64_t i01 = ids ? ids[blockIdx.x] : blockIdx.x;
482        base_idx = i3*s03 + i2*s02 + i01*s01;
483    }
484
485    const float4 * x4 = (const float4 *) x;
486    block_q8_1_mmq * y = (block_q8_1_mmq *) vy;
487
488    const int64_t k_block = i0 / QK8_1_MMQ; // column block in the channel
489    const int64_t iqs     = i0 % QK8_1_MMQ; // quant index in block
490
491    // Load 4 floats per thread and calculate max. abs. value between them:
492    const float4 xi = i0 < ne00 ? x4[(base_idx + i00)/4] : make_float4(0.0f, 0.0f, 0.0f, 0.0f);
493    float amax = fabsf(xi.x);
494    amax = fmaxf(amax, fabsf(xi.y));
495    amax = fmaxf(amax, fabsf(xi.z));
496    amax = fmaxf(amax, fabsf(xi.w));
497
498    // Exchange max. abs. value between vals_per_scale/4 threads.
499#pragma unroll
500    for (int offset = vals_per_scale/8; offset > 0; offset >>= 1) {
501        amax = fmaxf(amax, __shfl_xor_sync(0xFFFFFFFF, amax, offset, WARP_SIZE));
502    }
503
504    float sum;
505    if (ds_layout != MMQ_Q8_1_DS_LAYOUT_D4) {
506        sum = xi.x + xi.y + xi.z + xi.w;
507
508        // Calculate sums across vals_per_sum/4 threads.
509#pragma unroll
510        for (int offset = vals_per_sum/8; offset > 0; offset >>= 1) {
511            sum += __shfl_xor_sync(0xFFFFFFFF, sum, offset, WARP_SIZE);
512        }
513    }
514
515    const float d_inv = 127.0f / amax;
516    char4 q;
517    q.x = roundf(xi.x*d_inv);
518    q.y = roundf(xi.y*d_inv);
519    q.z = roundf(xi.z*d_inv);
520    q.w = roundf(xi.w*d_inv);
521    const float d = 1.0f / d_inv;
522
523    // write the block once (normal) or to each of the token's compact rows (scatter)
524    const int nwrite = scatter ? n_expert_used : 1;
525#pragma unroll
526    for (int slot = 0; slot < nwrite; ++slot) {
527        int64_t ib;
528        if constexpr (scatter) {
529            const int64_t i = ids[(int64_t) blockIdx.x * n_expert_used + slot];
530            ib = k_block*ne1 + i;
531        } else {
532            const int64_t ib0 = blockIdx.z*((int64_t)gridDim.x*gridDim.y*blockDim.x/QK8_1); // first block of channel
533            ib = ib0 + k_block*ne1 + blockIdx.x;
534        }
535
536        // Write back 4 int8 values as a single 32 bit value for better memory bandwidth:
537        char4 * yqs4 = (char4 *) y[ib].qs;
538        yqs4[iqs/4] = q;
539
540        if (ds_layout == MMQ_Q8_1_DS_LAYOUT_D2S6) {
541            if (iqs % 16 == 0 && iqs < 96) {
542                y[ib].d2s6[2 + iqs/16] = sum;
543                if (iqs % 64 == 0) {
544                    y[ib].d2s6[iqs/64] = d;
545                }
546            }
547        } else if (iqs % 32 == 0) {
548            if (ds_layout == MMQ_Q8_1_DS_LAYOUT_DS4) {
549                y[ib].ds4[iqs/32] = make_half2(d, sum);
550            } else {
551                y[ib].d4[iqs/32]  = d;
552            }
553        }
554    }
555    GGML_UNUSED(n_expert_used);
556}
557
558void quantize_row_q8_1_cuda(
559        const float * x, const int32_t * ids, void * vy, const ggml_type type_src0,
560        const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
561        const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
562    GGML_ASSERT(!ids);
563    GGML_ASSERT(ne0 % QK8_1 == 0);
564
565    const uint3 ne2_fastdiv = init_fastdiv_values(ne2);
566
567    const int64_t block_num_x = (ne0 + CUDA_QUANTIZE_BLOCK_SIZE - 1) / CUDA_QUANTIZE_BLOCK_SIZE;
568    const dim3 num_blocks(block_num_x, ne1, ne2*ne3);
569    const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE, 1, 1);
570    const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(num_blocks, block_size, 0, stream);
571    ggml_cuda_kernel_launch(quantize_q8_1, launch_params, x, vy, ne00, s01, s02, s03, ne0, ne1, ne2_fastdiv);
572    GGML_UNUSED(type_src0);
573}
574
575void quantize_mmq_q8_1_cuda(
576        const float * x, const int32_t * ids, void * vy, const ggml_type type_src0,
577        const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
578        const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
579    GGML_ASSERT(ne00 % 4 == 0);
580    GGML_ASSERT(ne0 % QK8_1_MMQ == 0);
581
582    // ne1 tends to assume the highest values, therefore use it as the "x" dimension of the CUDA grid:
583    const int64_t block_num_y = (ne0 + 4*CUDA_QUANTIZE_BLOCK_SIZE_MMQ - 1) / (4*CUDA_QUANTIZE_BLOCK_SIZE_MMQ);
584    const dim3 num_blocks(ne1, block_num_y, ne2*ne3);
585    const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1);
586    switch (mmq_get_q8_1_ds_layout(type_src0)) {
587        case MMQ_Q8_1_DS_LAYOUT_D4:
588            quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_D4, false>
589                <<<num_blocks, block_size, 0, stream>>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
590            break;
591        case MMQ_Q8_1_DS_LAYOUT_DS4:
592            quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_DS4, false>
593                <<<num_blocks, block_size, 0, stream>>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
594            break;
595        case MMQ_Q8_1_DS_LAYOUT_D2S6:
596            quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_D2S6, false>
597                <<<num_blocks, block_size, 0, stream>>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
598            break;
599        default:
600            GGML_ABORT("fatal error");
601            break;
602    }
603}
604
605// scatter=true reuses the quant kernel: grid over tokens, ids = inverse map (token slot -> compact row)
606void quantize_scatter_mmq_q8_1_cuda(
607        const float * x, const int32_t * ids_src1_inv, void * vy, const ggml_type type_src0,
608        const int64_t ne00, const int64_t stride_token, const int64_t ne0,
609        const int64_t n_tokens, const int64_t nrows_dst, const int n_expert_used, cudaStream_t stream) {
610    GGML_ASSERT(ne00 % 4 == 0);
611    GGML_ASSERT(ne0 % QK8_1_MMQ == 0);
612
613    const int64_t block_num_y = (ne0 + 4*CUDA_QUANTIZE_BLOCK_SIZE_MMQ - 1) / (4*CUDA_QUANTIZE_BLOCK_SIZE_MMQ);
614    const dim3 num_blocks(n_tokens, block_num_y, 1);
615    const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1);
616    switch (mmq_get_q8_1_ds_layout(type_src0)) {
617        case MMQ_Q8_1_DS_LAYOUT_D4:
618            quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_D4, true><<<num_blocks, block_size, 0, stream>>>(
619                x, ids_src1_inv, vy, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/(int) nrows_dst, /*ne2=*/1, n_expert_used);
620            break;
621        case MMQ_Q8_1_DS_LAYOUT_DS4:
622            quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_DS4, true><<<num_blocks, block_size, 0, stream>>>(
623                x, ids_src1_inv, vy, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/(int) nrows_dst, /*ne2=*/1, n_expert_used);
624            break;
625        case MMQ_Q8_1_DS_LAYOUT_D2S6:
626            quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_D2S6, true><<<num_blocks, block_size, 0, stream>>>(
627                x, ids_src1_inv, vy, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/(int) nrows_dst, /*ne2=*/1, n_expert_used);
628            break;
629        default:
630            GGML_ABORT("fatal error");
631            break;
632    }
633}
634
635// scatter=true reuses the quant kernels: grid over tokens, ids = inverse map (token slot -> compact row)
636void quantize_scatter_mmq_fp4_cuda(
637        const float * x, const int32_t * ids_src1_inv, void * vy, float * scale, const ggml_type type_src0, const bool use_aligned_float8,
638        const int64_t ne00, const int64_t stride_token, const int64_t ne0,
639        const int64_t n_tokens, const int64_t nrows_dst, const int n_expert_used, cudaStream_t stream) {
640    GGML_ASSERT(ne0 > 0);
641    if (type_src0 == GGML_TYPE_NVFP4) {
642        GGML_ASSERT(scale);
643        GGML_ASSERT(ne00 % QK_NVFP4 == 0);
644        const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1);
645        const dim3 num_blocks(n_tokens, 1, 1);
646        if (use_aligned_float8) {
647            quantize_mmq_nvfp4<true, true><<<num_blocks, block_size, 0, stream>>>(
648                x, ids_src1_inv, vy, scale, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/nrows_dst, /*ne2=*/1, n_expert_used);
649        } else {
650            quantize_mmq_nvfp4<true, false><<<num_blocks, block_size, 0, stream>>>(
651                x, ids_src1_inv, vy, scale, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/nrows_dst, /*ne2=*/1, n_expert_used);
652        }
653    } else {
654        GGML_ASSERT(type_src0 == GGML_TYPE_MXFP4);
655        constexpr int nwarps = 8;
656        constexpr int vals_per_block = nwarps * 2 * QK_MXFP4;
657        const int64_t block_num_y = (ne0 + vals_per_block - 1) / vals_per_block;
658        const dim3 block_size(WARP_SIZE, nwarps, 1);
659        const dim3 num_blocks(n_tokens, block_num_y, 1);
660        quantize_mmq_mxfp4<true><<<num_blocks, block_size, 0, stream>>>(
661            x, ids_src1_inv, vy, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/(int) nrows_dst, /*ne2=*/1, n_expert_used);
662    }
663}
664
665void quantize_mmq_fp4_cuda(
666        const float * x, const int32_t * ids, void * vy, float * scale, const ggml_type type_src0, const bool use_aligned_float8,
667        const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
668        const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
669    GGML_ASSERT(type_src0 == GGML_TYPE_MXFP4 || type_src0 == GGML_TYPE_NVFP4);
670    GGML_ASSERT(ne0 > 0);
671
672    if (type_src0 == GGML_TYPE_NVFP4) {
673        GGML_ASSERT(scale);
674        GGML_ASSERT(ne00 % QK_NVFP4 == 0);
675        const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1);
676        const dim3 num_blocks(ne1, ne2 * ne3, 1);
677        if (use_aligned_float8) {
678            quantize_mmq_nvfp4<false, true><<<num_blocks, block_size, 0, stream>>>(
679                x, ids, vy, scale, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
680        } else {
681            quantize_mmq_nvfp4<false, false><<<num_blocks, block_size, 0, stream>>>(
682                x, ids, vy, scale, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
683        }
684    } else {
685        GGML_ASSERT(ne0 % (2 * QK_MXFP4) == 0);
686
687        constexpr int nwarps = 8;
688        constexpr int vals_per_warp  = 2 * QK_MXFP4;
689        constexpr int vals_per_block = nwarps * vals_per_warp;
690
691        const int64_t block_num_y = (ne0 + vals_per_block - 1) / vals_per_block;
692        const dim3    num_blocks(ne1, block_num_y, ne2 * ne3);
693        const dim3    block_size(WARP_SIZE, nwarps, 1);
694
695        quantize_mmq_mxfp4<false><<<num_blocks, block_size, 0, stream>>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
696    }
697}