mlx_test.go 27.1 KB
Newer Older
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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
//go:build mlx

package mlx

import (
	"fmt"
	"testing"
)

// TestBasicCleanup verifies non-kept arrays are freed and kept arrays survive.
func TestBasicCleanup(t *testing.T) {
	weight := NewArrayFloat32([]float32{1, 2, 3, 4}, []int32{2, 2})
	Keep(weight)
	weight.Eval()

	intermediate := NewArrayFloat32([]float32{1, 1}, []int32{1, 2})
	result := Matmul(intermediate, weight)
	Keep(result)

	// Before eval: intermediate should be valid
	if !intermediate.Valid() {
		t.Fatal("intermediate should be valid before Eval")
	}

	Eval(result)

	// After eval: intermediate should be freed
	if intermediate.Valid() {
		t.Fatal("intermediate should be freed after Eval")
	}

	// Result should have correct values
	data := result.Data()
	if data[0] != 4 || data[1] != 6 {
		t.Errorf("expected [4, 6], got %v", data)
	}

	// Weight should survive
	if !weight.Valid() {
		t.Error("weight was freed")
	}
}

// TestKeptSurvives verifies kept arrays are not freed.
func TestKeptSurvives(t *testing.T) {
	a := NewArrayFloat32([]float32{1, 2}, []int32{2})
	b := NewArrayFloat32([]float32{3, 4}, []int32{2})
	result := Add(a, b)
	Keep(result)

	Eval(result)

	if !result.Valid() {
		t.Error("kept result was freed")
	}

	data := result.Data()
	if data[0] != 4 || data[1] != 6 {
		t.Errorf("expected [4, 6], got %v", data)
	}
}

// TestEvalAutoKeeps verifies Eval automatically keeps its outputs.
func TestEvalAutoKeeps(t *testing.T) {
	a := NewArrayFloat32([]float32{1, 2}, []int32{2})
	b := NewArrayFloat32([]float32{3, 4}, []int32{2})
	result := Add(a, b)

	// Don't call Keep(result) - Eval should auto-keep it
	Eval(result)

	// Result should survive (auto-kept by Eval)
	if !result.Valid() {
		t.Error("Eval output was freed - should be auto-kept")
	}

	// Inputs should be freed (not kept)
	if a.Valid() {
		t.Error("input 'a' should be freed")
	}
	if b.Valid() {
		t.Error("input 'b' should be freed")
	}

	// Verify data is correct
	data := result.Data()
	if data[0] != 4 || data[1] != 6 {
		t.Errorf("expected [4, 6], got %v", data)
	}
}

// TestWeightsSurvive verifies kept arrays survive multiple Eval cycles.
func TestWeightsSurvive(t *testing.T) {
	weight := NewArrayFloat32([]float32{1, 2, 3, 4}, []int32{2, 2})
	Keep(weight)
	weight.Eval()

	for i := 0; i < 5; i++ {
		x := NewArrayFloat32([]float32{1, 1}, []int32{1, 2})
		result := Matmul(x, weight)
		Keep(result)
		Eval(result)
	}

	if !weight.Valid() {
		t.Error("weight was freed after multiple iterations")
	}
}

// TestAsyncEvalCleanup verifies AsyncEval cleans up and dispatches.
func TestAsyncEvalCleanup(t *testing.T) {
	weight := NewArrayFloat32([]float32{1, 0, 0, 1}, []int32{2, 2}) // Identity matrix
	Keep(weight)
	weight.Eval()

	// First async step
	x1 := NewArrayFloat32([]float32{1, 2}, []int32{1, 2})
	result1 := Matmul(x1, weight)
	Keep(result1)
	AsyncEval(result1)

	// Second async step
	x2 := NewArrayFloat32([]float32{3, 4}, []int32{1, 2})
	result2 := Matmul(x2, weight)
	Keep(result2)
	AsyncEval(result2)

	// Sync and verify results
	result1.Eval()
	d1 := result1.Data()
	if d1[0] != 1 || d1[1] != 2 {
		t.Errorf("result1: expected [1, 2], got %v", d1)
	}

	result2.Eval()
	d2 := result2.Data()
	if d2[0] != 3 || d2[1] != 4 {
		t.Errorf("result2: expected [3, 4], got %v", d2)
	}

	if !weight.Valid() {
		t.Error("weight was freed during async")
	}
}

// TestMultiOutput verifies multiple kept arrays survive.
func TestMultiOutput(t *testing.T) {
	a := NewArrayFloat32([]float32{1, 2, 3, 4}, []int32{2, 2})
	sum := Add(a, a)
	prod := Mul(a, a)
	Keep(sum, prod)

	Eval(sum, prod)

	// Both kept arrays should be valid
	if !sum.Valid() || !prod.Valid() {
		t.Error("kept arrays should survive cleanup")
	}

	// Verify values
	sumData := sum.Data()
	prodData := prod.Data()
	if sumData[0] != 2 || prodData[0] != 1 {
		t.Errorf("unexpected results: sum=%v prod=%v", sumData, prodData)
	}
}

// TestChaining verifies output from one step can be used in next.
func TestChaining(t *testing.T) {
	weight := NewArrayFloat32([]float32{1, 0, 0, 1}, []int32{2, 2})
	Keep(weight)
	weight.Eval()

	// First step
	x := NewArrayFloat32([]float32{1, 2}, []int32{1, 2})
	out1 := Matmul(x, weight)
	Keep(out1)
	AsyncEval(out1)

	// Second step uses output of first
	out2 := Add(out1, out1)
	Keep(out2)
	Eval(out2)

	// out1 should survive (was kept)
	if !out1.Valid() {
		t.Error("out1 was freed but used by second step")
	}

	// Final result should be correct
	data := out2.Data()
	if data[0] != 2 || data[1] != 4 {
		t.Errorf("expected [2, 4], got %v", data)
	}
}

// TestGenerationLoop simulates the LLM generation pattern with cache.
func TestGenerationLoop(t *testing.T) {
	weight := NewArrayFloat32([]float32{1, 0, 0, 1}, []int32{2, 2})
	Keep(weight)
	weight.Eval()

	// Simulate cache - starts as zeros
	cache := NewArrayFloat32([]float32{0, 0}, []int32{1, 2})
	Keep(cache)
	cache.Eval()

	var lastToken *Array

	// Simulate 5 generation steps
	for step := 0; step < 5; step++ {
		oldCache := cache

		// Simulate forward pass
		input := NewArrayFloat32([]float32{float32(step + 1), float32(step + 2)}, []int32{1, 2})
		output := Matmul(input, weight)

		// Simulate cache update
		newCache := Add(output, cache)

		// Mark what survives
		Keep(output, newCache)

		if step < 4 {
			AsyncEval(output, newCache)
		} else {
			Eval(output, newCache)
		}

		// Free old cache, update references
		oldCache.Free()
		lastToken = output
		cache = newCache
	}

	// Token output should be valid
	if !lastToken.Valid() {
		t.Error("token output was freed")
	}

	// Cache should be valid
	if !cache.Valid() {
		t.Error("cache was freed")
	}

	// Weight should survive all iterations
	if !weight.Valid() {
		t.Error("weight was freed")
	}
}

// BenchmarkCleanupOnly isolates cleanup cost without MLX ops.
func BenchmarkCleanupOnly(b *testing.B) {
	// Pre-create weight
	weight := NewArrayFloat32([]float32{1, 0, 0, 1}, []int32{2, 2})
	Keep(weight)
	weight.Eval()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		// Create 100 arrays - minimal ops
		arrays := make([]*Array, 100)
		for j := range arrays {
			arrays[j] = NewArrayFloat32([]float32{1, 2}, []int32{1, 2})
		}
		Keep(arrays[0])
		Eval() // Just cleanup
	}
}

// BenchmarkNewArrayOnly measures array creation overhead.
func BenchmarkNewArrayOnly(b *testing.B) {
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		_ = NewArrayFloat32([]float32{1, 2, 3, 4}, []int32{2, 2})
	}
}

// BenchmarkCGOCallOverhead measures raw CGO call cost.
func BenchmarkCGOCallOverhead(b *testing.B) {
	arr := NewArrayFloat32([]float32{1, 2, 3, 4}, []int32{2, 2})
	Keep(arr)
	arr.Eval()
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		_ = arr.Ndim() // Simple CGO call
	}
}

// BenchmarkCleanup_50 measures cleanup with 50 arrays.
func BenchmarkCleanup_50(b *testing.B) {
	benchCleanup(b, 50)
}

// BenchmarkCleanup_500 measures cleanup with 500 arrays (LLM scale).
func BenchmarkCleanup_500(b *testing.B) {
	benchCleanup(b, 500)
}

// BenchmarkCleanup_1000 measures cleanup with 1000 arrays.
func BenchmarkCleanup_1000(b *testing.B) {
	benchCleanup(b, 1000)
}

func benchCleanup(b *testing.B, numArrays int) {
	weight := NewArrayFloat32([]float32{1, 0, 0, 1}, []int32{2, 2})
	Keep(weight)
	weight.Eval()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		x := NewArrayFloat32([]float32{1, 2}, []int32{1, 2})
		for j := 0; j < numArrays; j++ {
			x = Add(x, x)
		}
		result := Matmul(x, weight)
		Keep(result)
		Eval(result)
	}
}

// BenchmarkGenerationLoop_10 simulates 10 token generation steps.
func BenchmarkGenerationLoop_10(b *testing.B) {
	benchGenerationLoop(b, 10)
}

// BenchmarkGenerationLoop_100 simulates 100 token generation steps.
func BenchmarkGenerationLoop_100(b *testing.B) {
	benchGenerationLoop(b, 100)
}

func benchGenerationLoop(b *testing.B, steps int) {
	weight := NewArrayFloat32([]float32{1, 0, 0, 1}, []int32{2, 2})
	Keep(weight)
	weight.Eval()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		cache := NewArrayFloat32([]float32{0, 0}, []int32{1, 2})
		Keep(cache)
		cache.Eval()

		for step := 0; step < steps; step++ {
			oldCache := cache
			input := NewArrayFloat32([]float32{1, 2}, []int32{1, 2})
			output := Matmul(input, weight)
			newCache := Add(output, cache)
			Keep(output, newCache)

			if step < steps-1 {
				AsyncEval(output, newCache)
			} else {
				Eval(output, newCache)
			}
			oldCache.Free()
			cache = newCache
		}
	}
}

// BenchmarkLLMForward simulates a realistic LLM forward pass with ~500 ops.
func BenchmarkLLMForward(b *testing.B) {
	// Simulate weights for 32 layers
	numLayers := 32
	weights := make([]*Array, numLayers*4) // q, k, v, o per layer
	for i := range weights {
		weights[i] = NewArrayFloat32([]float32{1, 0, 0, 1}, []int32{2, 2})
	}
	Keep(weights...)
	Eval(weights...)

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		x := NewArrayFloat32([]float32{1, 2}, []int32{1, 2})

		// Simulate 32 transformer layers
		for layer := 0; layer < numLayers; layer++ {
			// Attention block (simplified)
			q := Matmul(x, weights[layer*4])
			k := Matmul(x, weights[layer*4+1])
			v := Matmul(x, weights[layer*4+2])
			attn := Matmul(Softmax(Matmul(q, Transpose(k, 1, 0)), -1), v)
			attnOut := Matmul(attn, weights[layer*4+3])

			// Residual + layernorm (simplified)
			x = Add(x, attnOut)
			x = RMSNormNoWeight(x, 1e-5)

			// FFN (simplified as single matmul)
			ffn := Matmul(x, weights[layer*4])
			ffn = SiLU(ffn)
			x = Add(x, ffn)
		}
		Keep(x)
		Eval(x)
	}
}

// ============ Compile Tests ============

// gelu implements GELU activation: x * 0.5 * (1 + erf(x / sqrt(2)))
func gelu(x *Array) *Array {
	sqrt2 := NewScalarArray(1.4142135623730951)
	half := NewScalarArray(0.5)
	one := NewScalarArray(1.0)
	scaled := Div(x, sqrt2)
	erfd := Erf(scaled)
	return Mul(Mul(x, half), Add(one, erfd))
}

// TestCompileBasic verifies compiled function produces correct output.
func TestCompileBasic(t *testing.T) {
	x := NewArrayFloat32([]float32{-1, 0, 1, 2}, []int32{4})
	Keep(x)
	x.Eval()

	// Uncompiled
	expected := gelu(x)
	Keep(expected)
	Eval(expected)

	// Compiled
	compiled := Compile(func(inputs []*Array) []*Array {
		return []*Array{gelu(inputs[0])}
	})
	defer compiled.Free()

	result := compiled.Call(x)[0]
	Keep(result)
	Eval(result)

	// Compare with tolerance
	expData := expected.Data()
	resData := result.Data()
	for i := range expData {
		diff := expData[i] - resData[i]
		if diff < 0 {
			diff = -diff
		}
		if diff > 1e-5 {
			t.Errorf("mismatch at %d: expected %f, got %f (diff=%e)", i, expData[i], resData[i], diff)
		}
	}
}

// TestCompileMultipleInputs verifies compiled function with multiple inputs.
func TestCompileMultipleInputs(t *testing.T) {
	a := NewArrayFloat32([]float32{1, 2, 3, 4}, []int32{4})
	b := NewArrayFloat32([]float32{5, 6, 7, 8}, []int32{4})
	Keep(a, b)
	Eval(a, b)

	compiled := Compile(func(inputs []*Array) []*Array {
		sum := Add(inputs[0], inputs[1])
		prod := Mul(inputs[0], inputs[1])
		return []*Array{sum, prod}
	})
	defer compiled.Free()

	outputs := compiled.Call(a, b)
	Keep(outputs...)
	Eval(outputs...)

	sumData := outputs[0].Data()
	prodData := outputs[1].Data()
	if sumData[0] != 6 || prodData[0] != 5 {
		t.Errorf("unexpected: sum[0]=%f, prod[0]=%f", sumData[0], prodData[0])
	}
}

// TestCompileReuse verifies compiled function can be called multiple times.
func TestCompileReuse(t *testing.T) {
	compiled := Compile(func(inputs []*Array) []*Array {
		return []*Array{Add(inputs[0], inputs[0])}
	})
	defer compiled.Free()

	for i := 0; i < 5; i++ {
		x := NewArrayFloat32([]float32{float32(i)}, []int32{1})
		Keep(x)
		x.Eval()
		result := compiled.Call(x)[0]
		Keep(result)
		Eval(result)
		data := result.Data()
		expected := float32(i * 2)
		if data[0] != expected {
			t.Errorf("iteration %d: expected %f, got %f", i, expected, data[0])
		}
	}
}

// BenchmarkGELUUncompiled benchmarks uncompiled GELU.
func BenchmarkGELUUncompiled(b *testing.B) {
	x := RandomNormal([]int32{1000, 1024}, 42)
	Keep(x)
	x.Eval()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		y := x
		for j := 0; j < 10; j++ {
			y = gelu(y)
		}
		Keep(y)
		Eval(y)
	}
}

// BenchmarkGELUCompiled benchmarks compiled GELU.
func BenchmarkGELUCompiled(b *testing.B) {
	x := RandomNormal([]int32{1000, 1024}, 42)
	Keep(x)
	x.Eval()

	compiled := Compile(func(inputs []*Array) []*Array {
		y := inputs[0]
		for j := 0; j < 10; j++ {
			y = gelu(y)
		}
		return []*Array{y}
	})
	defer compiled.Free()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		result := compiled.Call(x)
		Keep(result[0])
		Eval(result[0])
	}
}

// TestCompileNoMemoryLeak verifies compiled functions don't leak memory.
func TestCompileNoMemoryLeak(t *testing.T) {
	x := RandomNormal([]int32{100, 100}, 42)
	Keep(x)
	x.Eval()

	compiled := Compile(func(inputs []*Array) []*Array {
		y := inputs[0]
		for j := 0; j < 5; j++ {
			y = gelu(y)
		}
		return []*Array{y}
	})
	defer compiled.Free()

	// Warmup to establish baseline
	for i := 0; i < 10; i++ {
		result := compiled.Call(x)
		Keep(result[0])
		Eval(result[0])
		result[0].Free()
	}

	MetalResetPeakMemory()
	initialMem := MetalGetActiveMemory()

	for i := 0; i < 100; i++ {
		result := compiled.Call(x)
		Keep(result[0])
		Eval(result[0])
		result[0].Free()
	}

	Eval() // Final cleanup

	finalMem := MetalGetActiveMemory()
	peakMem := MetalGetPeakMemory()

	// Memory should not grow significantly (allow 10MB slack for caching)
	growth := int64(finalMem) - int64(initialMem)
	if growth > 10*1024*1024 {
		t.Errorf("memory grew by %d bytes over 100 iterations", growth)
	}
	t.Logf("memory: initial=%dMB, final=%dMB, peak=%dMB, growth=%dKB",
		initialMem/(1<<20), finalMem/(1<<20), peakMem/(1<<20), growth/1024)
}

// TestCompileWithRandomState verifies compiled function can capture and update random state.
func TestCompileWithRandomState(t *testing.T) {
	// Simulate logits for sampling
	logits := NewArrayFloat32([]float32{0.1, 0.2, 0.3, 0.4}, []int32{1, 4})
	Keep(logits)
	logits.Eval()

	// Initial random key
	key := RandomKey(42)
	Keep(key)

	// Compile a sampling function that splits the key
	compiled := Compile(func(inputs []*Array) []*Array {
		logits := inputs[0]
		keyIn := inputs[1]

		// Split key: one for sampling, one for next iteration
		key1, key2 := RandomSplit(keyIn)

		// Sample from logits
		sample := RandomCategoricalWithKey(logits, key2, -1, 1)

		return []*Array{sample, key1}
	})
	defer compiled.Free()

	// Run multiple sampling steps
	samples := make([]int32, 10)
	for i := 0; i < 10; i++ {
		outputs := compiled.Call(logits, key)
		Keep(outputs...)
		Eval(outputs...)
		samples[i] = outputs[0].ItemInt32()
		key.Free()
		key = outputs[1]
	}

	// Verify we got valid samples (0-3)
	for i, s := range samples {
		if s < 0 || s > 3 {
			t.Errorf("sample %d out of range: %d", i, s)
		}
	}
	t.Logf("samples: %v", samples)

	// Verify samples aren't all the same (randomness works)
	allSame := true
	for i := 1; i < len(samples); i++ {
		if samples[i] != samples[0] {
			allSame = false
			break
		}
	}
	if allSame {
		t.Error("all samples are the same - random state may not be updating")
	}
}

// swiGLU implements the GPT-OSS custom SwiGLU activation.
func swiGLU(gate, up *Array, alpha, limit float32) *Array {
	gateClipped := ClipScalar(gate, 0, limit, false, true)
	upClipped := ClipScalar(up, -limit, limit, true, true)
	gluScaled := MulScalar(gateClipped, alpha)
	sig := Sigmoid(gluScaled)
	outGlu := Mul(gateClipped, sig)
	return Mul(outGlu, AddScalar(upClipped, 1.0))
}

// TestCompileSwiGLU verifies compiled SwiGLU produces correct output.
func TestCompileSwiGLU(t *testing.T) {
	gate := NewArrayFloat32([]float32{-1, 0, 1, 2, 5, 10}, []int32{6})
	up := NewArrayFloat32([]float32{-5, -1, 0, 1, 5, 10}, []int32{6})
	Keep(gate, up)
	Eval(gate, up)

	const alpha float32 = 1.702
	const limit float32 = 7.0

	// Uncompiled
	expected := swiGLU(gate, up, alpha, limit)
	Keep(expected)
	Eval(expected)

	// Compiled
	compiled := Compile(func(inputs []*Array) []*Array {
		return []*Array{swiGLU(inputs[0], inputs[1], alpha, limit)}
	})
	defer compiled.Free()

	result := compiled.Call(gate, up)[0]
	Keep(result)
	Eval(result)

	// Compare
	expData := expected.Data()
	resData := result.Data()
	for i := range expData {
		diff := expData[i] - resData[i]
		if diff < 0 {
			diff = -diff
		}
		if diff > 1e-5 {
			t.Errorf("mismatch at %d: expected %f, got %f", i, expData[i], resData[i])
		}
	}
	t.Logf("SwiGLU results: %v", resData)
}

// BenchmarkSwiGLUUncompiled benchmarks uncompiled SwiGLU.
func BenchmarkSwiGLUUncompiled(b *testing.B) {
	gate := RandomNormal([]int32{1, 2880}, 42)
	up := RandomNormal([]int32{1, 2880}, 43)
	Keep(gate, up)
	Eval(gate, up)

	const alpha float32 = 1.702
	const limit float32 = 7.0

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		result := swiGLU(gate, up, alpha, limit)
		Keep(result)
		Eval(result)
	}
}

// BenchmarkSwiGLUCompiled benchmarks compiled SwiGLU.
func BenchmarkSwiGLUCompiled(b *testing.B) {
	gate := RandomNormal([]int32{1, 2880}, 42)
	up := RandomNormal([]int32{1, 2880}, 43)
	Keep(gate, up)
	Eval(gate, up)

	const alpha float32 = 1.702
	const limit float32 = 7.0

	compiled := Compile(func(inputs []*Array) []*Array {
		return []*Array{swiGLU(inputs[0], inputs[1], alpha, limit)}
	})
	defer compiled.Free()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		result := compiled.Call(gate, up)
		Keep(result[0])
		Eval(result[0])
	}
}

// BenchmarkSwiGLU10xUncompiled benchmarks 10 chained SwiGLU ops uncompiled.
func BenchmarkSwiGLU10xUncompiled(b *testing.B) {
	x := RandomNormal([]int32{1, 2880}, 42)
	Keep(x)
	x.Eval()

	const alpha float32 = 1.702
	const limit float32 = 7.0

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		y := x
		for j := 0; j < 10; j++ {
			y = swiGLU(y, y, alpha, limit)
		}
		Keep(y)
		Eval(y)
	}
}

// BenchmarkSwiGLU10xCompiled benchmarks 10 chained SwiGLU ops compiled.
func BenchmarkSwiGLU10xCompiled(b *testing.B) {
	x := RandomNormal([]int32{1, 2880}, 42)
	Keep(x)
	x.Eval()

	const alpha float32 = 1.702
	const limit float32 = 7.0

	compiled := Compile(func(inputs []*Array) []*Array {
		y := inputs[0]
		for j := 0; j < 10; j++ {
			y = swiGLU(y, y, alpha, limit)
		}
		return []*Array{y}
	})
	defer compiled.Free()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		result := compiled.Call(x)
		Keep(result[0])
		Eval(result[0])
	}
}

// ============ Sampler Benchmarks ============

// sampleTopK implements top-k sampling
func sampleTopK(logits, key *Array, k int) (*Array, *Array) {
	neg := Neg(logits)
	indices := Argpartition(neg, k-1, -1)
	topK := Slice(indices, []int32{0}, []int32{int32(k)})
	values := TakeAlongAxis(logits, topK, -1)
	key1, key2 := RandomSplit(key)
	sampled := RandomCategoricalWithKey(values, key2, -1, 1)
	return Take(topK, sampled, -1), key1
}

// sampleTopP implements top-p (nucleus) sampling
func sampleTopP(logits, key *Array, p float32, vocabSize int32) (*Array, *Array) {
	sorted := Argsort(Neg(logits), -1)
	sortedLogits := TakeAlongAxis(logits, sorted, -1)
	probs := Softmax(sortedLogits, -1)
	cumProbs := Cumsum(probs, -1)
	mask := LessScalar(cumProbs, p)
	negInf := FullDtype(float32(-1e9), logits.Dtype(), vocabSize)
	masked := Where(mask, sortedLogits, negInf)
	key1, key2 := RandomSplit(key)
	sampled := RandomCategoricalWithKey(masked, key2, -1, 1)
	return Take(sorted, sampled, -1), key1
}

// BenchmarkSampleTopKUncompiled benchmarks uncompiled top-k sampling.
func BenchmarkSampleTopKUncompiled(b *testing.B) {
	vocabSize := int32(32000)
	logits := RandomNormal([]int32{vocabSize}, 42)
	key := RandomKey(42)
	Keep(logits, key)
	Eval(logits, key)

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		var token *Array
		token, key = sampleTopK(logits, key, 40)
		Keep(token, key)
		Eval(token)
	}
}

// BenchmarkSampleTopKCompiled benchmarks compiled top-k sampling.
func BenchmarkSampleTopKCompiled(b *testing.B) {
	vocabSize := int32(32000)
	logits := RandomNormal([]int32{vocabSize}, 42)
	key := RandomKey(42)
	Keep(logits, key)
	Eval(logits, key)

	compiled := Compile(func(inputs []*Array) []*Array {
		token, newKey := sampleTopK(inputs[0], inputs[1], 40)
		return []*Array{token, newKey}
	})
	defer compiled.Free()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		outputs := compiled.Call(logits, key)
		Keep(outputs...)
		Eval(outputs[0])
		key = outputs[1]
	}
}

// BenchmarkSampleTopPUncompiled benchmarks uncompiled top-p sampling.
func BenchmarkSampleTopPUncompiled(b *testing.B) {
	vocabSize := int32(32000)
	logits := RandomNormal([]int32{vocabSize}, 42)
	key := RandomKey(42)
	Keep(logits, key)
	Eval(logits, key)

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		var token *Array
		token, key = sampleTopP(logits, key, 0.9, vocabSize)
		Keep(token, key)
		Eval(token)
	}
}

// BenchmarkSampleTopPCompiled benchmarks compiled top-p sampling.
func BenchmarkSampleTopPCompiled(b *testing.B) {
	vocabSize := int32(32000)
	logits := RandomNormal([]int32{vocabSize}, 42)
	key := RandomKey(42)
	Keep(logits, key)
	Eval(logits, key)

	compiled := Compile(func(inputs []*Array) []*Array {
		token, newKey := sampleTopP(inputs[0], inputs[1], 0.9, vocabSize)
		return []*Array{token, newKey}
	})
	defer compiled.Free()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		outputs := compiled.Call(logits, key)
		Keep(outputs...)
		Eval(outputs[0])
		key = outputs[1]
	}
}

// TestCompiledSamplerMemoryStable verifies compiled samplers don't leak memory.
func TestCompiledSamplerMemoryStable(t *testing.T) {
	vocabSize := int32(32000)
	logits := RandomNormal([]int32{vocabSize}, 42)
	key := RandomKey(42)
	Keep(logits, key)
	Eval(logits, key)

	compiledTopK := Compile(func(inputs []*Array) []*Array {
		token, newKey := sampleTopK(inputs[0], inputs[1], 40)
		return []*Array{token, newKey}
	})
	defer compiledTopK.Free()

	compiledTopP := Compile(func(inputs []*Array) []*Array {
		token, newKey := sampleTopP(inputs[0], inputs[1], 0.9, vocabSize)
		return []*Array{token, newKey}
	})
	defer compiledTopP.Free()

	// Warmup
	for i := 0; i < 10; i++ {
		out := compiledTopK.Call(logits, key)
		Keep(out...)
		Eval(out[0])
		out[0].Free()
		key = out[1]
	}

	MetalResetPeakMemory()
	initialMem := MetalGetActiveMemory()

	// Run 500 iterations of each sampler
	for i := 0; i < 500; i++ {
		// TopK
		out := compiledTopK.Call(logits, key)
		Keep(out...)
		Eval(out[0])
		out[0].Free()
		key = out[1]

		// TopP
		out = compiledTopP.Call(logits, key)
		Keep(out...)
		Eval(out[0])
		out[0].Free()
		key = out[1]
	}

	Eval() // Final cleanup

	finalMem := MetalGetActiveMemory()
	peakMem := MetalGetPeakMemory()

	growth := int64(finalMem) - int64(initialMem)
	t.Logf("memory: initial=%dMB, final=%dMB, peak=%dMB, growth=%dKB",
		initialMem/(1<<20), finalMem/(1<<20), peakMem/(1<<20), growth/1024)

	// Memory should stay bounded (allow 20MB for caching overhead)
	if growth > 20*1024*1024 {
		t.Errorf("memory grew by %d bytes over 1000 sampler calls - possible leak!", growth)
	}
}

// BenchmarkSimpleOps measures simple ops with cleanup
func BenchmarkSimpleOps(b *testing.B) {
	weight := NewArrayFloat32([]float32{1, 0, 0, 1}, []int32{2, 2})
	Keep(weight)
	weight.Eval()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		x := NewArrayFloat32([]float32{1, 2}, []int32{1, 2})
		result := Matmul(x, weight)
		Keep(result)
		AsyncEval(result)
		result.Eval()
	}
}

// BenchmarkLayerLike measures layer-like ops (~15 ops)
func BenchmarkLayerLike(b *testing.B) {
	hidden := int32(256)
	w := Ones(hidden, hidden)
	Keep(w)
	w.Eval()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		x := Ones(1, hidden)
		// Simulate attention-like ops with proper shapes
		h := Matmul(x, w)                  // [1, 256] @ [256, 256] = [1, 256]
		h = Add(h, Matmul(h, w))           // residual
		h = Mul(h, Sigmoid(Matmul(h, w)))  // gating
		h = Matmul(h, w)                   // output projection
		h = Add(x, RMSNormNoWeight(h, 1e-5)) // residual + norm
		Keep(h)
		AsyncEval(h)
		Eval(h)
	}
}

// BenchmarkManyOps measures with increasing op counts
func BenchmarkManyOps(b *testing.B) {
	w := Ones(64, 64)
	Keep(w)
	w.Eval()

	for _, numOps := range []int{10, 50, 100, 500, 1000} {
		b.Run(fmt.Sprintf("ops_%d", numOps), func(b *testing.B) {
			for i := 0; i < b.N; i++ {
				x := Ones(1, 64)
				for j := 0; j < numOps; j++ {
					x = Add(x, Matmul(x, w))
				}
				Keep(x)
				AsyncEval(x)
				Eval(x)
			}
		})
	}
}

// BenchmarkLLMScale measures at LLM-realistic scale (~1348 arrays)
func BenchmarkLLMScale(b *testing.B) {
	// Simulate Qwen-like model: 24 layers, each with ~56 ops = 1344 arrays
	numLayers := 24
	opsPerLayer := 56

	// Create weights
	hidden := int32(64)
	weights := make([]*Array, numLayers*4)
	for i := range weights {
		weights[i] = Ones(hidden, hidden)
	}
	Keep(weights...)
	Eval(weights...)

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		x := Ones(1, hidden)

		for layer := 0; layer < numLayers; layer++ {
			for op := 0; op < opsPerLayer/4; op++ {
				x = Add(x, Matmul(x, weights[layer*4]))
				x = Mul(x, Sigmoid(x))
			}
		}
		Keep(x)
		AsyncEval(x)
		Eval(x)
	}
}

// BenchmarkArrayFreeLoop measures the cost of freeing N arrays
func BenchmarkArrayFreeLoop(b *testing.B) {
	for _, count := range []int{100, 500, 1000, 1500} {
		b.Run(fmt.Sprintf("arrays_%d", count), func(b *testing.B) {
			for i := 0; i < b.N; i++ {
				b.StopTimer()
				arrays := make([]*Array, count)
				for j := 0; j < count; j++ {
					arrays[j] = NewArrayFloat32([]float32{1, 2, 3, 4}, []int32{2, 2})
				}
				b.StartTimer()

				// Cleanup all arrays
				Eval()
			}
		})
	}
}

// BenchmarkCleanupIsolated measures just cleanup time
func BenchmarkCleanupIsolated(b *testing.B) {
	w := NewArrayFloat32([]float32{1}, []int32{1, 1})
	Keep(w)
	w.Eval()

	for _, count := range []int{100, 500, 1000, 1500} {
		b.Run(fmt.Sprintf("arrays_%d", count), func(b *testing.B) {
			b.ResetTimer()
			for i := 0; i < b.N; i++ {
				b.StopTimer()
				x := NewArrayFloat32([]float32{1}, []int32{1})
				for j := 0; j < count; j++ {
					x = Add(x, x)
				}
				Keep(x)
				b.StartTimer()
				Eval() // Just cleanup
			}
		})
	}
}

// TestMemoryStable verifies that cleanup doesn't cause unbounded memory growth.
func TestMemoryStable(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping memory test in short mode")
	}

	// Create realistic-sized arrays (like KV cache)
	batchSize := int32(1)
	numHeads := int32(8)
	seqLen := int32(256)
	headDim := int32(64)
	cacheShape := []int32{batchSize, numHeads, seqLen, headDim}
	cacheSize := batchSize * numHeads * seqLen * headDim * 4 // float32 = 4 bytes

	// Initial cache
	keys := Zeros(cacheShape, DtypeFloat32)
	values := Zeros(cacheShape, DtypeFloat32)
	Keep(keys, values)
	Eval(keys, values)

	// Warmup
	for i := 0; i < 5; i++ {
		oldKeys, oldValues := keys, values

		newKeys := Add(keys, keys)
		newValues := Add(values, values)
		Keep(newKeys, newValues)
		Eval(newKeys, newValues)

		oldKeys.Free()
		oldValues.Free()
		keys, values = newKeys, newValues
	}

	MetalResetPeakMemory()
	initialMem := MetalGetActiveMemory()

	// Run 100 steps
	for step := 0; step < 100; step++ {
		oldKeys, oldValues := keys, values

		newKeys := Add(keys, keys)
		newValues := Add(values, values)
		Keep(newKeys, newValues)
		Eval(newKeys, newValues)

		oldKeys.Free()
		oldValues.Free()
		keys, values = newKeys, newValues
	}

	Eval() // Final cleanup

	finalMem := MetalGetActiveMemory()
	peakMem := MetalGetPeakMemory()

	growth := int64(finalMem) - int64(initialMem)
	expectedMaxGrowth := int64(cacheSize * 4 * 10)

	t.Logf("cache size: %d bytes", cacheSize*2)
	t.Logf("memory: initial=%dMB, final=%dMB, peak=%dMB, growth=%dKB",
		initialMem/(1<<20), finalMem/(1<<20), peakMem/(1<<20), growth/1024)

	if growth > expectedMaxGrowth {
		t.Errorf("memory grew by %d bytes over 100 steps (expected max %d) - possible leak",
			growth, expectedMaxGrowth)
	}
}