ruvllm 2.2.0

LLM serving runtime with Ruvector integration - Paged attention, KV cache, and SONA learning
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
//
// Normalization Kernels - Metal Compute Shader
// Optimized for Apple Silicon M4 Pro with SIMD reductions
//
// Includes:
// - RMSNorm (Root Mean Square Layer Normalization)
// - LayerNorm (Layer Normalization)
// - Fused normalization + residual operations
//
// Optimizations:
// - SIMD reduction (simd_sum) for parallel sum computation
// - Vectorized memory access (float4)
// - Fused operations to reduce memory bandwidth
// - 16-byte aligned threadgroup memory
//

#include <metal_stdlib>
using namespace metal;

// Constants
constant uint SIMD_SIZE = 32;
constant uint MAX_THREADS = 1024;

// Normalization parameters structure (matches Rust NormParams)
struct NormParams {
    uint hidden_size;       // Hidden dimension
    float eps;              // Epsilon for numerical stability
    uint elements_per_thread;  // Elements per thread for distribution
    uint _padding;          // Alignment padding
};

// =============================================================================
// High-Performance RMSNorm with SIMD reduction
// RMSNorm: x * weight / sqrt(mean(x^2) + eps)
// Used in LLaMA, Mistral, and other modern LLMs
// =============================================================================
kernel void rms_norm_v2(
    device float* x [[buffer(0)]],
    device const float* weight [[buffer(1)]],
    constant NormParams& params [[buffer(2)]],
    uint2 gid [[thread_position_in_grid]],
    uint tid [[thread_position_in_threadgroup]],
    uint simd_lane [[thread_index_in_simdgroup]],
    uint simd_group [[simdgroup_index_in_threadgroup]],
    uint threads_per_group [[threads_per_threadgroup]]
) {
    uint batch_idx = gid.y;
    uint hidden_size = params.hidden_size;
    float eps = params.eps;

    uint offset = batch_idx * hidden_size;

    // Shared memory for warp-level reduction results
    threadgroup float warp_sums[32] __attribute__((aligned(16)));

    // Step 1: Compute sum of squares with vectorized loads and SIMD reduction
    float local_sum = 0.0f;

    // Process 4 elements at a time using float4
    const uint vec_size = hidden_size / 4;
    const device float4* x_vec = reinterpret_cast<const device float4*>(x + offset);

    for (uint i = tid; i < vec_size; i += threads_per_group) {
        float4 val = x_vec[i];
        local_sum += val.x * val.x + val.y * val.y + val.z * val.z + val.w * val.w;
    }

    // Handle remainder
    for (uint i = vec_size * 4 + tid; i < hidden_size; i += threads_per_group) {
        float val = x[offset + i];
        local_sum += val * val;
    }

    // SIMD reduction within warp
    local_sum = simd_sum(local_sum);

    // Store warp results
    if (simd_lane == 0) {
        warp_sums[simd_group] = local_sum;
    }

    threadgroup_barrier(mem_flags::mem_threadgroup);

    // Final reduction across warps (first warp only)
    float total_sum = 0.0f;
    if (simd_group == 0) {
        uint num_warps = (threads_per_group + SIMD_SIZE - 1) / SIMD_SIZE;
        if (simd_lane < num_warps) {
            total_sum = warp_sums[simd_lane];
        }
        total_sum = simd_sum(total_sum);

        if (simd_lane == 0) {
            warp_sums[0] = total_sum;
        }
    }

    threadgroup_barrier(mem_flags::mem_threadgroup);

    // Compute inverse RMS
    float inv_rms = rsqrt(warp_sums[0] / float(hidden_size) + eps);

    // Step 2: Normalize and apply weight with vectorized stores
    device float4* out_vec = reinterpret_cast<device float4*>(x + offset);
    const device float4* w_vec = reinterpret_cast<const device float4*>(weight);

    for (uint i = tid; i < vec_size; i += threads_per_group) {
        float4 val = x_vec[i];
        float4 w = w_vec[i];
        out_vec[i] = val * inv_rms * w;
    }

    // Handle remainder
    for (uint i = vec_size * 4 + tid; i < hidden_size; i += threads_per_group) {
        x[offset + i] = x[offset + i] * inv_rms * weight[i];
    }
}

// =============================================================================
// Original RMSNorm (kept for compatibility)
// =============================================================================
kernel void rms_norm(
    device float* x [[buffer(0)]],
    device const float* weight [[buffer(1)]],
    constant NormParams& params [[buffer(2)]],
    uint2 gid [[thread_position_in_grid]],
    uint tid [[thread_position_in_threadgroup]],
    uint threads_per_group [[threads_per_threadgroup]]
) {
    uint batch_idx = gid.y;
    uint hidden_size = params.hidden_size;
    float eps = params.eps;
    uint offset = batch_idx * hidden_size;

    threadgroup float shared_sum[MAX_THREADS];

    float local_sum = 0.0f;
    for (uint i = tid; i < hidden_size; i += threads_per_group) {
        float val = x[offset + i];
        local_sum = fma(val, val, local_sum);
    }

    // SIMD reduction first
    local_sum = simd_sum(local_sum);
    shared_sum[tid / SIMD_SIZE] = local_sum;

    threadgroup_barrier(mem_flags::mem_threadgroup);

    // Reduce across warps
    if (tid < threads_per_group / SIMD_SIZE) {
        local_sum = shared_sum[tid];
    } else {
        local_sum = 0.0f;
    }
    local_sum = simd_sum(local_sum);

    float inv_rms = rsqrt(local_sum / float(hidden_size) + eps);

    threadgroup_barrier(mem_flags::mem_threadgroup);

    for (uint i = tid; i < hidden_size; i += threads_per_group) {
        x[offset + i] = x[offset + i] * inv_rms * weight[i];
    }
}

// =============================================================================
// LayerNorm with SIMD reduction
// LayerNorm: (x - mean) / sqrt(var + eps) * weight + bias
// =============================================================================
kernel void layer_norm_v2(
    device float* x [[buffer(0)]],
    device const float* weight [[buffer(1)]],
    device const float* bias [[buffer(2)]],
    constant NormParams& params [[buffer(3)]],
    uint2 gid [[thread_position_in_grid]],
    uint tid [[thread_position_in_threadgroup]],
    uint simd_lane [[thread_index_in_simdgroup]],
    uint simd_group [[simdgroup_index_in_threadgroup]],
    uint threads_per_group [[threads_per_threadgroup]]
) {
    uint batch_idx = gid.y;
    uint hidden_size = params.hidden_size;
    float eps = params.eps;
    uint offset = batch_idx * hidden_size;

    threadgroup float warp_sum[32] __attribute__((aligned(16)));
    threadgroup float warp_sum_sq[32] __attribute__((aligned(16)));

    // Compute sum and sum of squares with vectorization
    float local_sum = 0.0f;
    float local_sum_sq = 0.0f;

    const uint vec_size = hidden_size / 4;
    const device float4* x_vec = reinterpret_cast<const device float4*>(x + offset);

    for (uint i = tid; i < vec_size; i += threads_per_group) {
        float4 val = x_vec[i];
        local_sum += val.x + val.y + val.z + val.w;
        local_sum_sq += val.x * val.x + val.y * val.y + val.z * val.z + val.w * val.w;
    }

    for (uint i = vec_size * 4 + tid; i < hidden_size; i += threads_per_group) {
        float val = x[offset + i];
        local_sum += val;
        local_sum_sq = fma(val, val, local_sum_sq);
    }

    // SIMD reduction
    local_sum = simd_sum(local_sum);
    local_sum_sq = simd_sum(local_sum_sq);

    if (simd_lane == 0) {
        warp_sum[simd_group] = local_sum;
        warp_sum_sq[simd_group] = local_sum_sq;
    }

    threadgroup_barrier(mem_flags::mem_threadgroup);

    // Final reduction
    float total_sum = 0.0f;
    float total_sum_sq = 0.0f;
    if (simd_group == 0) {
        uint num_warps = (threads_per_group + SIMD_SIZE - 1) / SIMD_SIZE;
        if (simd_lane < num_warps) {
            total_sum = warp_sum[simd_lane];
            total_sum_sq = warp_sum_sq[simd_lane];
        }
        total_sum = simd_sum(total_sum);
        total_sum_sq = simd_sum(total_sum_sq);

        if (simd_lane == 0) {
            warp_sum[0] = total_sum;
            warp_sum_sq[0] = total_sum_sq;
        }
    }

    threadgroup_barrier(mem_flags::mem_threadgroup);

    float mean = warp_sum[0] / float(hidden_size);
    float var = warp_sum_sq[0] / float(hidden_size) - mean * mean;
    float inv_std = rsqrt(var + eps);

    // Normalize with vectorization
    device float4* out_vec = reinterpret_cast<device float4*>(x + offset);
    const device float4* w_vec = reinterpret_cast<const device float4*>(weight);
    const device float4* b_vec = bias ? reinterpret_cast<const device float4*>(bias) : nullptr;

    for (uint i = tid; i < vec_size; i += threads_per_group) {
        float4 val = x_vec[i];
        float4 normalized = (val - mean) * inv_std;
        float4 w = w_vec[i];
        float4 b = b_vec ? b_vec[i] : float4(0.0f);
        out_vec[i] = fma(normalized, w, b);
    }

    for (uint i = vec_size * 4 + tid; i < hidden_size; i += threads_per_group) {
        float normalized = (x[offset + i] - mean) * inv_std;
        float bias_val = bias ? bias[i] : 0.0f;
        x[offset + i] = fma(normalized, weight[i], bias_val);
    }
}

// =============================================================================
// Original LayerNorm (kept for compatibility)
// =============================================================================
kernel void layer_norm(
    device float* x [[buffer(0)]],
    device const float* weight [[buffer(1)]],
    device const float* bias [[buffer(2)]],
    constant NormParams& params [[buffer(3)]],
    uint2 gid [[thread_position_in_grid]],
    uint tid [[thread_position_in_threadgroup]],
    uint threads_per_group [[threads_per_threadgroup]]
) {
    uint batch_idx = gid.y;
    uint hidden_size = params.hidden_size;
    float eps = params.eps;
    uint offset = batch_idx * hidden_size;

    threadgroup float shared_sum[MAX_THREADS];
    threadgroup float shared_sum_sq[MAX_THREADS];

    float local_sum = 0.0f;
    float local_sum_sq = 0.0f;

    for (uint i = tid; i < hidden_size; i += threads_per_group) {
        float val = x[offset + i];
        local_sum += val;
        local_sum_sq = fma(val, val, local_sum_sq);
    }

    // SIMD reduction
    local_sum = simd_sum(local_sum);
    local_sum_sq = simd_sum(local_sum_sq);

    shared_sum[tid / SIMD_SIZE] = local_sum;
    shared_sum_sq[tid / SIMD_SIZE] = local_sum_sq;

    threadgroup_barrier(mem_flags::mem_threadgroup);

    if (tid < threads_per_group / SIMD_SIZE) {
        local_sum = shared_sum[tid];
        local_sum_sq = shared_sum_sq[tid];
    } else {
        local_sum = 0.0f;
        local_sum_sq = 0.0f;
    }
    local_sum = simd_sum(local_sum);
    local_sum_sq = simd_sum(local_sum_sq);

    float mean = local_sum / float(hidden_size);
    float var = local_sum_sq / float(hidden_size) - mean * mean;
    float inv_std = rsqrt(var + eps);

    threadgroup_barrier(mem_flags::mem_threadgroup);

    for (uint i = tid; i < hidden_size; i += threads_per_group) {
        float normalized = (x[offset + i] - mean) * inv_std;
        float bias_val = bias ? bias[i] : 0.0f;
        x[offset + i] = fma(normalized, weight[i], bias_val);
    }
}

// =============================================================================
// Fused RMSNorm + Residual Addition
// Computes: residual = x + residual; output = RMSNorm(residual) * weight
// Single pass through memory for better bandwidth utilization
// =============================================================================
kernel void rms_norm_residual_v2(
    device float* x [[buffer(0)]],
    device float* residual [[buffer(1)]],
    device const float* weight [[buffer(2)]],
    constant NormParams& params [[buffer(3)]],
    uint2 gid [[thread_position_in_grid]],
    uint tid [[thread_position_in_threadgroup]],
    uint simd_lane [[thread_index_in_simdgroup]],
    uint simd_group [[simdgroup_index_in_threadgroup]],
    uint threads_per_group [[threads_per_threadgroup]]
) {
    uint batch_idx = gid.y;
    uint hidden_size = params.hidden_size;
    float eps = params.eps;
    uint offset = batch_idx * hidden_size;

    threadgroup float warp_sums[32] __attribute__((aligned(16)));
    threadgroup float temp_data[MAX_THREADS] __attribute__((aligned(16)));

    // Step 1: Add residual and compute sum of squares in one pass
    float local_sum = 0.0f;

    const uint vec_size = hidden_size / 4;
    device float4* x_vec = reinterpret_cast<device float4*>(x + offset);
    device float4* res_vec = reinterpret_cast<device float4*>(residual + offset);

    for (uint i = tid; i < vec_size; i += threads_per_group) {
        float4 x_val = x_vec[i];
        float4 r_val = res_vec[i];
        float4 sum_val = x_val + r_val;

        // Store sum back to residual
        res_vec[i] = sum_val;

        // Accumulate sum of squares
        local_sum += sum_val.x * sum_val.x + sum_val.y * sum_val.y +
                     sum_val.z * sum_val.z + sum_val.w * sum_val.w;
    }

    for (uint i = vec_size * 4 + tid; i < hidden_size; i += threads_per_group) {
        float sum_val = x[offset + i] + residual[offset + i];
        residual[offset + i] = sum_val;
        local_sum = fma(sum_val, sum_val, local_sum);
    }

    // SIMD reduction
    local_sum = simd_sum(local_sum);

    if (simd_lane == 0) {
        warp_sums[simd_group] = local_sum;
    }

    threadgroup_barrier(mem_flags::mem_threadgroup);

    // Final reduction
    if (simd_group == 0) {
        uint num_warps = (threads_per_group + SIMD_SIZE - 1) / SIMD_SIZE;
        if (simd_lane < num_warps) {
            local_sum = warp_sums[simd_lane];
        } else {
            local_sum = 0.0f;
        }
        local_sum = simd_sum(local_sum);

        if (simd_lane == 0) {
            warp_sums[0] = local_sum;
        }
    }

    threadgroup_barrier(mem_flags::mem_threadgroup);

    float inv_rms = rsqrt(warp_sums[0] / float(hidden_size) + eps);

    // Step 2: Normalize from residual and write to x
    const device float4* w_vec = reinterpret_cast<const device float4*>(weight);

    for (uint i = tid; i < vec_size; i += threads_per_group) {
        float4 val = res_vec[i];
        float4 w = w_vec[i];
        x_vec[i] = val * inv_rms * w;
    }

    for (uint i = vec_size * 4 + tid; i < hidden_size; i += threads_per_group) {
        x[offset + i] = residual[offset + i] * inv_rms * weight[i];
    }
}

// =============================================================================
// Original Fused RMSNorm + Residual (kept for compatibility)
// =============================================================================
kernel void rms_norm_residual(
    device float* x [[buffer(0)]],
    device float* residual [[buffer(1)]],
    device const float* weight [[buffer(2)]],
    constant NormParams& params [[buffer(3)]],
    uint2 gid [[thread_position_in_grid]],
    uint tid [[thread_position_in_threadgroup]],
    uint threads_per_group [[threads_per_threadgroup]]
) {
    uint batch_idx = gid.y;
    uint hidden_size = params.hidden_size;
    float eps = params.eps;
    uint offset = batch_idx * hidden_size;

    threadgroup float shared_sum[MAX_THREADS];

    float local_sum = 0.0f;
    for (uint i = tid; i < hidden_size; i += threads_per_group) {
        float val = x[offset + i] + residual[offset + i];
        residual[offset + i] = val;
        local_sum = fma(val, val, local_sum);
    }

    local_sum = simd_sum(local_sum);
    shared_sum[tid / SIMD_SIZE] = local_sum;

    threadgroup_barrier(mem_flags::mem_threadgroup);

    if (tid < threads_per_group / SIMD_SIZE) {
        local_sum = shared_sum[tid];
    } else {
        local_sum = 0.0f;
    }
    local_sum = simd_sum(local_sum);

    float inv_rms = rsqrt(local_sum / float(hidden_size) + eps);

    threadgroup_barrier(mem_flags::mem_threadgroup);

    for (uint i = tid; i < hidden_size; i += threads_per_group) {
        x[offset + i] = residual[offset + i] * inv_rms * weight[i];
    }
}

// =============================================================================
// FP16 RMSNorm with SIMD reduction
// =============================================================================
kernel void rms_norm_f16_v2(
    device half* x [[buffer(0)]],
    device const half* weight [[buffer(1)]],
    constant NormParams& params [[buffer(2)]],
    uint2 gid [[thread_position_in_grid]],
    uint tid [[thread_position_in_threadgroup]],
    uint simd_lane [[thread_index_in_simdgroup]],
    uint simd_group [[simdgroup_index_in_threadgroup]],
    uint threads_per_group [[threads_per_threadgroup]]
) {
    uint batch_idx = gid.y;
    uint hidden_size = params.hidden_size;
    float eps = params.eps;
    uint offset = batch_idx * hidden_size;

    threadgroup float warp_sums[32] __attribute__((aligned(16)));

    // Compute sum of squares (use FP32 for accuracy)
    float local_sum = 0.0f;

    const uint vec_size = hidden_size / 4;
    const device half4* x_vec = reinterpret_cast<const device half4*>(x + offset);

    for (uint i = tid; i < vec_size; i += threads_per_group) {
        float4 val = float4(x_vec[i]);
        local_sum += val.x * val.x + val.y * val.y + val.z * val.z + val.w * val.w;
    }

    for (uint i = vec_size * 4 + tid; i < hidden_size; i += threads_per_group) {
        float val = float(x[offset + i]);
        local_sum = fma(val, val, local_sum);
    }

    // SIMD reduction
    local_sum = simd_sum(local_sum);

    if (simd_lane == 0) {
        warp_sums[simd_group] = local_sum;
    }

    threadgroup_barrier(mem_flags::mem_threadgroup);

    if (simd_group == 0) {
        uint num_warps = (threads_per_group + SIMD_SIZE - 1) / SIMD_SIZE;
        if (simd_lane < num_warps) {
            local_sum = warp_sums[simd_lane];
        } else {
            local_sum = 0.0f;
        }
        local_sum = simd_sum(local_sum);

        if (simd_lane == 0) {
            warp_sums[0] = local_sum;
        }
    }

    threadgroup_barrier(mem_flags::mem_threadgroup);

    half inv_rms = half(rsqrt(warp_sums[0] / float(hidden_size) + eps));

    // Normalize with vectorization
    device half4* out_vec = reinterpret_cast<device half4*>(x + offset);
    const device half4* w_vec = reinterpret_cast<const device half4*>(weight);

    for (uint i = tid; i < vec_size; i += threads_per_group) {
        half4 val = x_vec[i];
        half4 w = w_vec[i];
        out_vec[i] = val * inv_rms * w;
    }

    for (uint i = vec_size * 4 + tid; i < hidden_size; i += threads_per_group) {
        x[offset + i] = x[offset + i] * inv_rms * weight[i];
    }
}

// =============================================================================
// Original FP16 RMSNorm (kept for compatibility)
// =============================================================================
kernel void rms_norm_f16(
    device half* x [[buffer(0)]],
    device const half* weight [[buffer(1)]],
    constant NormParams& params [[buffer(2)]],
    uint2 gid [[thread_position_in_grid]],
    uint tid [[thread_position_in_threadgroup]],
    uint threads_per_group [[threads_per_threadgroup]]
) {
    uint batch_idx = gid.y;
    uint hidden_size = params.hidden_size;
    half eps = half(params.eps);
    uint offset = batch_idx * hidden_size;

    threadgroup float shared_sum[MAX_THREADS];

    float local_sum = 0.0f;
    for (uint i = tid; i < hidden_size; i += threads_per_group) {
        float val = float(x[offset + i]);
        local_sum = fma(val, val, local_sum);
    }

    local_sum = simd_sum(local_sum);
    shared_sum[tid / SIMD_SIZE] = local_sum;

    threadgroup_barrier(mem_flags::mem_threadgroup);

    if (tid < threads_per_group / SIMD_SIZE) {
        local_sum = shared_sum[tid];
    } else {
        local_sum = 0.0f;
    }
    local_sum = simd_sum(local_sum);

    half inv_rms = half(rsqrt(local_sum / float(hidden_size) + float(eps)));

    threadgroup_barrier(mem_flags::mem_threadgroup);

    for (uint i = tid; i < hidden_size; i += threads_per_group) {
        x[offset + i] = x[offset + i] * inv_rms * weight[i];
    }
}

// =============================================================================
// Group RMSNorm with SIMD reduction
// =============================================================================
kernel void group_rms_norm(
    device float* x [[buffer(0)]],
    device const float* weight [[buffer(1)]],
    constant uint& num_groups [[buffer(2)]],
    constant uint& channels_per_group [[buffer(3)]],
    constant float& eps [[buffer(4)]],
    uint3 gid [[thread_position_in_grid]],
    uint tid [[thread_position_in_threadgroup]],
    uint simd_lane [[thread_index_in_simdgroup]],
    uint simd_group [[simdgroup_index_in_threadgroup]],
    uint threads_per_group [[threads_per_threadgroup]]
) {
    uint batch_idx = gid.z;
    uint group_idx = gid.y;
    uint channels = num_groups * channels_per_group;
    uint group_offset = group_idx * channels_per_group;

    threadgroup float warp_sums[32] __attribute__((aligned(16)));

    float local_sum = 0.0f;
    for (uint c = tid; c < channels_per_group; c += threads_per_group) {
        uint idx = batch_idx * channels + group_offset + c;
        float val = x[idx];
        local_sum = fma(val, val, local_sum);
    }

    local_sum = simd_sum(local_sum);

    if (simd_lane == 0) {
        warp_sums[simd_group] = local_sum;
    }

    threadgroup_barrier(mem_flags::mem_threadgroup);

    if (simd_group == 0) {
        uint num_warps = (threads_per_group + SIMD_SIZE - 1) / SIMD_SIZE;
        if (simd_lane < num_warps) {
            local_sum = warp_sums[simd_lane];
        } else {
            local_sum = 0.0f;
        }
        local_sum = simd_sum(local_sum);

        if (simd_lane == 0) {
            warp_sums[0] = local_sum;
        }
    }

    threadgroup_barrier(mem_flags::mem_threadgroup);

    float inv_rms = rsqrt(warp_sums[0] / float(channels_per_group) + eps);

    for (uint c = tid; c < channels_per_group; c += threads_per_group) {
        uint idx = batch_idx * channels + group_offset + c;
        x[idx] = x[idx] * inv_rms * weight[group_offset + c];
    }
}

// =============================================================================
// Fused LayerNorm + Linear projection (common in transformers)
// output = Linear(LayerNorm(x)) = W @ LayerNorm(x) + b
// =============================================================================
// Maximum supported hidden_size for layer_norm_linear_fused kernel
// Metal threadgroup memory is limited and we use static arrays for performance
constant uint MAX_HIDDEN_SIZE_FUSED = 1024;

kernel void layer_norm_linear_fused(
    device const float* x [[buffer(0)]],
    device const float* ln_weight [[buffer(1)]],
    device const float* ln_bias [[buffer(2)]],
    device const float* linear_weight [[buffer(3)]],  // [out_features, hidden_size]
    device const float* linear_bias [[buffer(4)]],    // [out_features]
    device float* output [[buffer(5)]],
    constant uint& hidden_size [[buffer(6)]],
    constant uint& out_features [[buffer(7)]],
    constant float& eps [[buffer(8)]],
    uint2 gid [[thread_position_in_grid]],
    uint tid [[thread_position_in_threadgroup]],
    uint simd_lane [[thread_index_in_simdgroup]],
    uint simd_group [[simdgroup_index_in_threadgroup]],
    uint threads_per_group [[threads_per_threadgroup]]
) {
    uint batch_idx = gid.y;
    uint out_idx = gid.x;

    if (out_idx >= out_features) return;

    // SECURITY FIX: Guard against buffer overflow in threadgroup memory
    // The normalized array is statically sized to MAX_HIDDEN_SIZE_FUSED (1024)
    // Models with larger hidden dimensions should use the non-fused kernel instead
    if (hidden_size > MAX_HIDDEN_SIZE_FUSED) return;

    uint x_offset = batch_idx * hidden_size;

    threadgroup float warp_sum[32];
    threadgroup float warp_sum_sq[32];
    threadgroup float normalized[MAX_HIDDEN_SIZE_FUSED];  // SECURITY: Using constant for clarity

    // Step 1: Compute mean and variance with SIMD reduction
    float local_sum = 0.0f;
    float local_sum_sq = 0.0f;

    for (uint i = tid; i < hidden_size; i += threads_per_group) {
        float val = x[x_offset + i];
        local_sum += val;
        local_sum_sq = fma(val, val, local_sum_sq);
    }

    local_sum = simd_sum(local_sum);
    local_sum_sq = simd_sum(local_sum_sq);

    if (simd_lane == 0) {
        warp_sum[simd_group] = local_sum;
        warp_sum_sq[simd_group] = local_sum_sq;
    }

    threadgroup_barrier(mem_flags::mem_threadgroup);

    if (simd_group == 0) {
        uint num_warps = (threads_per_group + SIMD_SIZE - 1) / SIMD_SIZE;
        if (simd_lane < num_warps) {
            local_sum = warp_sum[simd_lane];
            local_sum_sq = warp_sum_sq[simd_lane];
        } else {
            local_sum = 0.0f;
            local_sum_sq = 0.0f;
        }
        local_sum = simd_sum(local_sum);
        local_sum_sq = simd_sum(local_sum_sq);

        if (simd_lane == 0) {
            warp_sum[0] = local_sum;
            warp_sum_sq[0] = local_sum_sq;
        }
    }

    threadgroup_barrier(mem_flags::mem_threadgroup);

    float mean = warp_sum[0] / float(hidden_size);
    float var = warp_sum_sq[0] / float(hidden_size) - mean * mean;
    float inv_std = rsqrt(var + eps);

    // Step 2: Normalize and store in shared memory
    for (uint i = tid; i < hidden_size; i += threads_per_group) {
        float val = (x[x_offset + i] - mean) * inv_std;
        float bias_val = ln_bias ? ln_bias[i] : 0.0f;
        normalized[i] = fma(val, ln_weight[i], bias_val);
    }

    threadgroup_barrier(mem_flags::mem_threadgroup);

    // Step 3: Linear projection (dot product with weight row)
    float dot = 0.0f;
    for (uint i = tid; i < hidden_size; i += threads_per_group) {
        dot = fma(normalized[i], linear_weight[out_idx * hidden_size + i], dot);
    }

    dot = simd_sum(dot);

    if (simd_lane == 0) {
        warp_sum[simd_group] = dot;
    }

    threadgroup_barrier(mem_flags::mem_threadgroup);

    if (simd_group == 0 && simd_lane == 0) {
        float total = 0.0f;
        uint num_warps = (threads_per_group + SIMD_SIZE - 1) / SIMD_SIZE;
        for (uint w = 0; w < num_warps; w++) {
            total += warp_sum[w];
        }
        float bias = linear_bias ? linear_bias[out_idx] : 0.0f;
        output[batch_idx * out_features + out_idx] = total + bias;
    }
}