neura-program 0.4.0

Graph lowering, wave scheduling and device tape encoding
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
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
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
use neura_abi::{Element, Kind, Placement, StepRecord, Store, TaskRecord, ValueRecord, WORD_BYTES};
use neura_graph::{Graph, Init, Shape};
use neura_op as op;
use neura_profile::{Budget, Profile};

const DEVICE: Budget = Budget::of(1024, 48 << 10);

fn narrow() -> Profile {
    Profile::derive(Budget::BASELINE)[0]
}

fn wide() -> Profile {
    *Profile::derive(Budget::BASELINE).last().expect("a profile")
}

fn every_profile() -> Vec<Profile> {
    Profile::derive(DEVICE)
}
use neura_program::{Encoding, Layout};
use std::mem::size_of;

const ALIGNMENT: u64 = 256;
const PLACEMENT: Placement = Placement::new(1 << 16, 1 << 18);

fn encoding(graph: &Graph) -> Encoding {
    encoding_with(graph, narrow())
}

fn encoding_with(graph: &Graph, profile: Profile) -> Encoding {
    Encoding::of(graph, ALIGNMENT, profile)
}

fn records<T: bytemuck::AnyBitPattern>(bytes: &[u8], width: usize) -> Vec<T> {
    bytes
        .chunks_exact(width)
        .map(bytemuck::pod_read_unaligned)
        .collect()
}

fn tape(encoding: &Encoding) -> Vec<TaskRecord> {
    records(encoding.tasks(), size_of::<TaskRecord>())
}

fn steps(encoding: &Encoding) -> Vec<StepRecord> {
    records(encoding.steps(), size_of::<StepRecord>())
}

fn kinds(encoding: &Encoding) -> Vec<Kind> {
    tape(encoding)
        .iter()
        .map(|task| Kind::of(task.kind))
        .collect()
}

fn segment_of(encoding: &Encoding, task: usize) -> usize {
    encoding
        .segments()
        .partition_point(|segment| segment.first as usize <= task)
        - 1
}

fn follows(encoding: &Encoding, before: usize, after: usize) -> bool {
    let segment = segment_of(encoding, before);
    let dispatch_before = dispatch_of(encoding, before);
    let dispatch_after = dispatch_of(encoding, after);
    dispatch_before < dispatch_after
        || (segment == segment_of(encoding, after)
            && before as u32 - encoding.segments()[segment].first
                < after as u32 - encoding.segments()[segment].first)
}

fn dispatch_of(encoding: &Encoding, task: usize) -> u32 {
    let mut at = 0usize;
    for (dispatch, record) in encoding.dispatches().iter().enumerate() {
        let count = encoding.segments()
            [record.first_segment as usize..(record.first_segment + record.segments) as usize]
            .iter()
            .map(|segment| segment.count as usize)
            .sum::<usize>();
        if task < at + count {
            return dispatch as u32;
        }
        at += count;
    }
    panic!("every task belongs to a dispatch")
}

fn writers(encoding: &Encoding, value: u32) -> Vec<usize> {
    tape(encoding)
        .iter()
        .enumerate()
        .filter(|(_, task)| task.out == value)
        .map(|(index, _)| index)
        .collect()
}

fn readers(encoding: &Encoding, value: u32) -> Vec<usize> {
    let tape = tape(encoding);
    let steps = steps(encoding);
    tape.iter()
        .enumerate()
        .filter(|(_, task)| {
            task.a == value
                || task.b == value
                || task.c == value
                || task.origin == value
                || (task.chain..task.chain + task.steps)
                    .any(|step| steps[step as usize].operand == value)
        })
        .map(|(index, _)| index)
        .collect()
}

fn refuses(action: impl FnOnce()) -> bool {
    std::panic::catch_unwind(std::panic::AssertUnwindSafe(action)).is_err()
}

#[test]
fn a_chain_of_rectifiers_fuses_into_one_task() {
    let graph = Graph::new();
    let mut value = graph.parameter(Shape::vector(4), Init::Zero, Element::Single);
    for _ in 0..4 {
        value = graph.relu(value);
    }
    assert_eq!(graph.task_count(), 4);
    let encoding = encoding(&graph);
    assert_eq!(encoding.task_count(), 1);
    assert_eq!(encoding.dispatch_count(), 1);
    assert_eq!(encoding.step_count(), 3);
    assert_eq!(value.shape().elements(), 4);
}

#[test]
fn a_dense_layer_fuses_its_epilogue_into_the_product() {
    let graph = Graph::new();
    let weight = graph.parameter(Shape::matrix(4, 8), Init::Zero, Element::Single);
    let bias = graph.parameter(Shape::vector(8), Init::Zero, Element::Single);
    let data = graph.input(Shape::matrix(3, 4), Element::Single);
    let activated = graph.relu(graph.add(graph.matmul(data, weight), bias));
    let encoding = encoding(&graph);
    assert_eq!(encoding.task_count(), 1);
    assert_eq!(encoding.dispatch_count(), 1);
    assert_eq!(kinds(&encoding), vec![Kind::Matmul]);
    let tape = tape(&encoding);
    assert_eq!(
        tape[0].steps, 2,
        "the bias and the rectifier ride the product"
    );
    let steps = steps(&encoding);
    assert_eq!(steps[tape[0].chain as usize].op, op::ADD);
    assert_eq!(steps[tape[0].chain as usize].operand, bias.id());
    assert_eq!(steps[tape[0].chain as usize + 1].op, op::RELU);
    assert_eq!(steps[tape[0].chain as usize + 1].operand, u32::MAX);
    assert_eq!(tape[0].out, activated.id());
}

#[test]
fn a_value_two_tasks_read_stays_on_the_tape() {
    let graph = Graph::new();
    let data = graph.parameter(Shape::vector(8), Init::Zero, Element::Single);
    let squared = graph.mul(data, data);
    let encoding = encoding(&graph);
    assert_eq!(encoding.task_count(), 1);
    assert_eq!(kinds(&encoding), vec![Kind::Binary]);
    assert_eq!(readers(&encoding, data.id()), vec![0]);
    assert_eq!(tape(&encoding)[0].out, squared.id());
}

#[test]
fn a_value_two_tasks_read_keeps_its_storage_from_the_output_of_either() {
    let graph = Graph::new();
    let left = graph.parameter(Shape::vector(64), Init::Zero, Element::Single);
    let right = graph.parameter(Shape::vector(64), Init::Zero, Element::Single);
    let product = graph.mul(left, right);
    let negated = graph.neg(product);
    let squared = graph.mul(product, product);
    let encoding = encoding(&graph);
    let reader = writers(&encoding, negated.id())[0];
    let taker = writers(&encoding, squared.id())[0];
    assert_eq!(
        dispatch_of(&encoding, reader),
        dispatch_of(&encoding, taker),
        "both readers of a value share a dispatch",
    );
    assert_ne!(
        encoding.span(product, PLACEMENT).offset,
        encoding.span(squared, PLACEMENT).offset,
        "the storage of a value a second task reads in the same dispatch was handed to its reader",
    );
}

#[test]
fn a_value_one_task_reads_hands_its_storage_to_that_task() {
    let graph = Graph::new();
    let data = graph.parameter(Shape::vector(64), Init::Zero, Element::Single);
    let scaled = graph.mul(data, graph.fill(Shape::vector(64), 2.0));
    let squared = graph.mul(scaled, scaled);
    let encoding = encoding(&graph);
    assert_eq!(
        encoding.span(scaled, PLACEMENT).offset,
        encoding.span(squared, PLACEMENT).offset,
        "the only reader of a value takes the storage it consumed",
    );
}

#[test]
fn a_retained_value_is_never_folded_away() {
    let graph = Graph::new();
    let data = graph.parameter(Shape::vector(8), Init::Zero, Element::Single);
    let doubled = graph.mul(data, graph.fill(Shape::vector(8), 2.0));
    graph.retain(doubled);
    let activated = graph.relu(doubled);
    graph.retain(activated);
    let encoding = encoding(&graph);
    let reader = writers(&encoding, activated.id());
    assert_eq!(reader.len(), 1, "the rectifier keeps a task of its own");
    assert_eq!(kinds(&encoding)[reader[0]], Kind::Unary);
    assert!(
        readers(&encoding, doubled.id()).contains(&reader[0]),
        "the rectifier reads the value the graph retains",
    );
}

#[test]
fn a_consumer_closes_the_producers_it_reads_into_one_segment() {
    let graph = Graph::new();
    let left = graph.parameter(Shape::vector(64), Init::Zero, Element::Single);
    let right = graph.parameter(Shape::vector(64), Init::Zero, Element::Single);
    let sum = graph.add(left, right);
    let product = graph.mul(left, right);
    graph.retain(sum);
    graph.retain(product);
    let out = graph.add(sum, product);
    graph.retain(out);
    let encoding = encoding(&graph);
    assert_eq!(encoding.task_count(), 3);
    assert_eq!(
        encoding.dispatch_count(),
        1,
        "a wave the device cannot fill hands its work to the wave it reads",
    );
    assert_eq!(encoding.dispatches()[0].segments, 1);
    assert_eq!(encoding.segments().len(), 1);
    let sum_task = writers(&encoding, sum.id())[0];
    let product_task = writers(&encoding, product.id())[0];
    let consumer = writers(&encoding, out.id())[0];
    assert!(follows(&encoding, sum_task, consumer));
    assert!(follows(&encoding, product_task, consumer));
    assert_eq!(out.shape(), Shape::vector(64));
}

#[test]
fn a_chain_of_temporaries_holds_one_tensor() {
    let graph = Graph::new();
    let mut value = graph.parameter(Shape::vector(256), Init::Zero, Element::Single);
    for _ in 0..16 {
        value = graph.relu(value);
    }
    let encoding = encoding(&graph);
    assert_eq!(encoding.task_count(), 1);
    assert_eq!(
        encoding.arena_bytes(),
        256 * 4,
        "the arena holds only the value the fused chain produces",
    );
    assert_eq!(
        Layout::of(&graph, ALIGNMENT).weights().words(),
        256,
        "the parameter lives in the weight store, not in the arena",
    );
}

#[test]
fn a_plan_sizes_its_own_arena() {
    let small = Graph::new();
    let parameter = small.parameter(Shape::vector(256), Init::Zero, Element::Single);
    small.relu(parameter);
    let large = Graph::new();
    let parameter = large.parameter(Shape::vector(4096), Init::Zero, Element::Single);
    large.relu(parameter);
    let small = encoding(&small);
    let large = encoding(&large);
    assert_eq!(small.arena_bytes(), 256 * 4);
    assert_eq!(large.arena_bytes(), 4096 * 4);
    assert!(
        small.arena_bytes() < large.arena_bytes(),
        "a wider tensor asks for a wider arena",
    );
}

#[test]
fn a_matmul_needs_a_shared_depth() {
    let graph = Graph::new();
    let left = graph.parameter(Shape::matrix(2, 3), Init::Zero, Element::Single);
    let right = graph.parameter(Shape::matrix(2, 4), Init::Zero, Element::Single);
    assert!(
        refuses(|| {
            let _ = graph.matmul(left, right);
        }),
        "a matmul of a 2x3 by a 2x4 was accepted",
    );
}

#[test]
fn elementwise_operands_must_meet() {
    let graph = Graph::new();
    let left = graph.parameter(Shape::matrix(2, 3), Init::Zero, Element::Single);
    let right = graph.parameter(Shape::matrix(2, 4), Init::Zero, Element::Single);
    assert!(
        refuses(|| {
            let _ = graph.add(left, right);
        }),
        "an add of a 2x3 and a 2x4 was accepted",
    );
}

#[test]
fn a_product_takes_the_tile_that_stages_the_fewest_loads_for_its_shape() {
    let graph = Graph::new();
    let tall = graph.parameter(Shape::matrix(1024, 32), Init::Zero, Element::Single);
    let weight = graph.parameter(Shape::matrix(32, 64), Init::Zero, Element::Single);
    let blocked = graph.parameter(Shape::matrix(32, 48), Init::Zero, Element::Single);
    let balanced = graph.matmul(tall, weight);
    let ragged = graph.matmul(tall, blocked);
    graph.retain(balanced);
    graph.retain(ragged);
    let encoding = encoding_with(&graph, wide());
    let tiles = encoding.tiles();
    let tasks = tape(&encoding);
    let balanced_task = *tasks
        .iter()
        .find(|task| task.out == balanced.id())
        .expect("the 1024x64 product holds a task");
    let balanced_tile = tiles[balanced_task.geometry as usize];
    assert_eq!(
        (balanced_tile.rows(), balanced_tile.columns()),
        (64, 64),
        "a product whose shape divides takes the tile that multiplies the most elements per staged load",
    );
    assert_eq!(balanced_tile.registers(), 16);
    let ragged_task = *tasks
        .iter()
        .find(|task| task.out == ragged.id())
        .expect("the 1024x48 product holds a task");
    assert_eq!(
        tiles[ragged_task.geometry as usize], balanced_tile,
        "a product no tile divides is masked by the tile its shape pays the least for",
    );
    assert_eq!(
        encoding.tiles(),
        wide().tiles(),
        "a plan carries every tile of the profile it compiles for",
    );
    assert_eq!(
        encoding.matmul_geometries(),
        vec![(balanced_tile, 32)],
        "a tape reports the geometry of every task it hands the device",
    );
    assert_eq!(
        encoding.work(),
        32 * balanced_tile.tile_work(),
        "a plan accounts the tile work it dispatches",
    );
    assert_ne!(
        encoding_with(&graph, narrow()).tiles(),
        encoding_with(&graph, wide()).tiles(),
        "a profile decides which tiles a product is tiled with",
    );
    assert!(
        encoding_with(&graph, wide()).task_count() < encoding_with(&graph, narrow()).task_count(),
        "a wider tile hands the device fewer, larger tasks",
    );
}

#[test]
fn a_product_whose_output_is_narrow_splits_its_depth_across_tasks() {
    let graph = Graph::new();
    let narrow = graph.parameter(Shape::matrix(8, 4096), Init::Zero, Element::Single);
    let weight = graph.parameter(Shape::matrix(4096, 32), Init::Zero, Element::Single);
    let out = graph.matmul(narrow, weight);
    graph.retain(out);
    let encoding = encoding_with(&graph, wide());
    let tape = tape(&encoding);
    assert_eq!(out.shape(), Shape::matrix(8, 32));
    let products = tape
        .iter()
        .filter(|task| Kind::of(task.kind) == Kind::Matmul)
        .collect::<Vec<_>>();
    let folds = tape
        .iter()
        .filter(|task| Kind::of(task.kind) == Kind::MatmulFold)
        .collect::<Vec<_>>();
    assert_eq!(folds.len(), 1);
    let tile = encoding.tiles()[products[0].geometry as usize];
    let tiles =
        out.shape().rows().div_ceil(tile.rows()) * out.shape().columns().div_ceil(tile.columns());
    let splits = folds[0].splits;
    assert!(
        splits > 1,
        "a product of {tiles} tiles fills no device without splitting its depth",
    );
    assert_eq!(products.len() as u32, tiles * splits);
    let partials = folds[0].a;
    assert_eq!(
        folds[0].out,
        out.id(),
        "the fold writes the product its graph names"
    );
    assert_ne!(partials, out.id(), "the fold reads partials of its own");
    let mut filled = vec![0u32; splits as usize];
    for task in &products {
        assert_eq!(task.splits, splits);
        assert_eq!(task.out, partials);
        assert_eq!(task.count, 1);
        filled[task.slot as usize] += 1;
    }
    assert!(
        filled.iter().all(|count| *count == tiles),
        "every split fills every tile of the product",
    );
    assert_eq!(
        folds[0].count,
        out.shape().elements(),
        "the fold writes one element per task",
    );
    assert_eq!(
        dispatch_of(&encoding, tape.len() - 1),
        encoding.dispatch_count() - 1,
        "the fold reads every slot after the last slot is written",
    );
}

#[test]
fn a_fold_leaves_the_wave_that_already_fills_the_device() {
    let graph = Graph::new();
    let narrow = graph.parameter(Shape::matrix(8, 4096), Init::Zero, Element::Single);
    let weight = graph.parameter(Shape::matrix(4096, 32), Init::Zero, Element::Single);
    let out = graph.matmul(narrow, weight);
    graph.retain(out);
    let encoding = encoding_with(&graph, wide());
    let tape = tape(&encoding);
    let fold = tape
        .iter()
        .position(|task| Kind::of(task.kind) == Kind::MatmulFold)
        .expect("a product that splits its depth carries a fold");
    assert_ne!(
        dispatch_of(&encoding, fold),
        dispatch_of(&encoding, 0),
        "a fold never lengthens the wave its own partials already fill",
    );
}

#[test]
fn a_split_product_hands_its_epilogue_to_the_fold() {
    let graph = Graph::new();
    let weight = graph.parameter(Shape::matrix(4096, 32), Init::Zero, Element::Single);
    let bias = graph.parameter(Shape::vector(32), Init::Zero, Element::Single);
    let data = graph.input(Shape::matrix(8, 4096), Element::Single);
    let out = graph.relu(graph.add(graph.matmul(data, weight), bias));
    graph.retain(out);
    let encoding = encoding_with(&graph, wide());
    let tape = tape(&encoding);
    let folds = tape
        .iter()
        .filter(|task| Kind::of(task.kind) == Kind::MatmulFold)
        .collect::<Vec<_>>();
    assert_eq!(folds.len(), 1);
    assert_eq!(folds[0].out, out.id());
    assert_eq!(
        folds[0].steps, 2,
        "the bias and the rectifier ride the fold"
    );
    let steps = steps(&encoding);
    assert_eq!(steps[folds[0].chain as usize].op, op::ADD);
    assert_eq!(steps[folds[0].chain as usize].operand, bias.id());
    assert_eq!(steps[folds[0].chain as usize + 1].op, op::RELU);
    for task in tape
        .iter()
        .filter(|task| Kind::of(task.kind) == Kind::Matmul)
    {
        assert_eq!(
            task.steps, 0,
            "a product that splits its depth applies no epilogue of its own",
        );
    }
}

#[test]
fn a_wide_op_hands_the_device_a_bounded_number_of_tasks() {
    for (elements, tasks) in [(32u32, 1u32), (4096, 2), (65536, 32), (1 << 20, 512)] {
        let graph = Graph::new();
        let data = graph.input(Shape::vector(elements), Element::Single);
        graph.relu(data);
        let encoding = encoding(&graph);
        assert_eq!(
            encoding.task_count(),
            tasks,
            "a rectifier over {elements} elements hands the device {tasks} tasks",
        );
    }
}

#[test]
fn every_profile_plans_the_same_values() {
    for profile in every_profile() {
        let graph = Graph::new();
        let weight = graph.parameter(Shape::matrix(4, 8), Init::Zero, Element::Single);
        let bias = graph.parameter(Shape::vector(8), Init::Zero, Element::Single);
        let data = graph.input(Shape::matrix(2, 4), Element::Single);
        let out = graph.relu(graph.add(graph.matmul(data, weight), bias));
        let encoding = encoding_with(&graph, profile);
        assert_eq!(
            encoding.value_count() as usize,
            graph.value_count(),
            "{profile:?} publishes values a graph without a reduction holds",
        );
        assert_eq!(encoding.span(out, PLACEMENT).elements, 16);
    }
}

#[test]
fn a_backward_pass_reaches_every_parameter() {
    let graph = Graph::new();
    let weight = graph.parameter(Shape::matrix(4, 8), Init::Zero, Element::Single);
    let bias = graph.parameter(Shape::vector(8), Init::Zero, Element::Single);
    let input = graph.input(Shape::matrix(16, 4), Element::Single);
    let dense = graph.matmul(input, weight);
    let shifted = graph.add(dense, bias);
    let activated = graph.relu(shifted);
    let loss = graph.sum(activated);
    let grads = graph.backward(loss);
    assert_eq!(grads.of(weight).shape(), Shape::matrix(4, 8));
    assert_eq!(grads.of(bias).shape(), Shape::vector(8));

    let kinds = kinds(&encoding(&graph));
    assert!(
        kinds.contains(&Kind::Matmul),
        "the weight gradient is a matmul"
    );
    assert!(
        kinds.contains(&Kind::Partial),
        "the rectifier contributes a mask"
    );
    assert!(
        kinds.contains(&Kind::SumChunk),
        "the loss reduces through partial sums"
    );
    assert!(
        kinds.contains(&Kind::Broadcast),
        "the loss gradient spreads the scalar over the tensor"
    );
    assert_eq!(
        kinds.iter().filter(|kind| **kind == Kind::SumAxis).count(),
        1,
        "the bias gradient folds the rows it was spread over",
    );
}

#[test]
fn a_broadcast_product_folds_its_gradient_back_to_the_shape_of_its_operand() {
    let graph = Graph::new();
    let left = graph.parameter(Shape::of([4, 1, 3, 2]), Init::Zero, Element::Single);
    let right = graph.parameter(Shape::of([1, 5, 2, 3]), Init::Zero, Element::Single);
    let product = graph.matmul(left, right);
    assert_eq!(product.shape(), Shape::of([4, 5, 3, 3]));
    let grads = graph.backward(graph.sum(product));
    assert_eq!(
        grads.of(left).shape(),
        left.shape(),
        "a gradient of a broadcast operand carries the shape of that operand",
    );
    assert_eq!(grads.of(right).shape(), right.shape());
    assert_eq!(
        kinds(&encoding(&graph))
            .iter()
            .filter(|kind| **kind == Kind::SumAxis)
            .count(),
        2,
        "one fold returns each operand to the rows its product spread",
    );
}

#[test]
fn a_reduction_folds_through_as_many_levels_as_it_takes() {
    let graph = Graph::new();
    let wide = graph.parameter(Shape::vector(1 << 21), Init::Zero, Element::Single);
    let loss = graph.sum(wide);
    let encoding = encoding(&graph);
    let reductions = kinds(&encoding)
        .iter()
        .filter(|kind| **kind == Kind::SumChunk)
        .count();
    assert_eq!(
        reductions, 257,
        "a sum folds a chunk of 8192 elements at a time until one scalar stands",
    );
    assert_eq!(
        encoding.dispatch_count(),
        2,
        "every level of the fold is a dispatch"
    );
    assert_eq!(loss.shape(), Shape::scalar());
    assert!(
        encoding.value_count() as usize > graph.value_count(),
        "a folded reduction publishes its partial sums",
    );
}

#[test]
fn a_parameter_updated_in_place_feeds_the_tasks_that_follow() {
    let graph = Graph::new();
    let weight = graph.parameter(Shape::vector(8), Init::Zero, Element::Single);
    let input = graph.input(Shape::vector(8), Element::Single);
    let loss = graph.sum(graph.mul(input, weight));
    let grads = graph.backward(loss);
    let scaled = graph.mul(grads.of(weight), graph.fill(Shape::scalar(), -0.1));
    graph.add_into(weight, scaled);
    let read_back = graph.relu(weight);
    graph.retain(read_back);
    let encoding = encoding(&graph);
    let update = writers(&encoding, weight.id());
    assert!(!update.is_empty(), "the update writes the parameter");
    let reader = writers(&encoding, read_back.id());
    assert_eq!(reader.len(), 1, "the reader holds a task of its own");
    assert!(
        update
            .iter()
            .all(|task| follows(&encoding, *task, reader[0])),
        "a reader observes the update it follows",
    );
}

#[test]
fn an_update_in_place_follows_every_reader_of_the_value_it_replaces() {
    let graph = Graph::new();
    let weight = graph.parameter(Shape::vector(8), Init::Zero, Element::Single);
    let input = graph.input(Shape::vector(8), Element::Single);
    let read = graph.mul(input, weight);
    graph.retain(read);
    let loss = graph.sum(read);
    let grads = graph.backward(loss);
    graph.add_into(weight, grads.of(weight));
    let read_back = graph.relu(weight);
    graph.retain(read_back);
    let encoding = encoding(&graph);
    let update = writers(&encoding, weight.id());
    assert_eq!(update.len(), 1, "the update writes the parameter once");
    let before = writers(&encoding, read.id())[0];
    let after = writers(&encoding, read_back.id())[0];
    assert!(
        follows(&encoding, before, update[0]),
        "an update in place follows every reader of the value it replaces",
    );
    assert!(
        follows(&encoding, update[0], after),
        "a reader that follows the update observes it",
    );
}

#[test]
fn a_graph_updated_in_place_is_refused_a_later_backward() {
    let graph = Graph::new();
    let weight = graph.parameter(Shape::vector(4), Init::Zero, Element::Single);
    let loss = graph.sum(graph.relu(weight));
    graph.add_into(weight, graph.fill(Shape::vector(4), 0.5));
    assert!(
        refuses(|| {
            let _ = graph.backward(loss);
        }),
        "a loss was differentiated after its parameter had been updated",
    );
}

#[test]
fn a_view_shares_the_storage_of_its_source() {
    let graph = Graph::new();
    let matrix = graph.parameter(Shape::matrix(8, 4), Init::Zero, Element::Single);
    let transposed = graph.permute(matrix, [0, 1, 3, 2]);
    assert_eq!(transposed.shape(), Shape::matrix(4, 8));
    let encoding = encoding(&graph);
    assert_eq!(encoding.span(matrix, PLACEMENT).elements, 32);
    assert!(
        refuses(|| {
            let _ = encoding.span(transposed, PLACEMENT);
        }),
        "a transposed view was handed its own storage",
    );
    assert!(!encoding.readable(transposed));
}

#[test]
fn a_view_that_its_storage_addresses_row_by_row_reads_back_as_that_storage() {
    let graph = Graph::new();
    let matrix = graph.input(Shape::matrix(8, 4), Element::Single);
    let flattened = graph.reshape(matrix, Shape::vector(32));
    let weight = graph.parameter(Shape::matrix(4, 2), Init::Zero, Element::Single);
    let squared = graph.reshape(weight, Shape::matrix(2, 4));
    let encoding = encoding(&graph);
    for (view, storage) in [(flattened, matrix), (squared, weight)] {
        assert_eq!(
            encoding.span(view, PLACEMENT),
            encoding.span(storage, PLACEMENT)
        );
        assert!(encoding.readable(view));
    }
}

#[test]
fn a_softmax_row_keeps_its_shape_and_gradient() {
    let graph = Graph::new();
    let logits = graph.parameter(
        Shape::matrix(16, 8),
        Init::Uniform {
            low: -1.0,
            high: 1.0,
        },
        Element::Single,
    );
    let probabilities = graph.softmax(logits);
    assert_eq!(probabilities.shape(), Shape::matrix(16, 8));
    let grads = graph.backward(graph.sum(probabilities));
    assert_eq!(grads.of(logits).shape(), Shape::matrix(16, 8));
}

#[test]
fn a_graph_is_differentiated_once() {
    let graph = Graph::new();
    let weight = graph.parameter(Shape::vector(4), Init::Zero, Element::Single);
    let loss = graph.sum(graph.relu(weight));
    graph.backward(loss);
    assert!(
        refuses(|| {
            let _ = graph.backward(loss);
        }),
        "a graph was differentiated twice",
    );
}

#[test]
fn a_loss_that_derives_from_no_parameter_is_refused() {
    let graph = Graph::new();
    let data = graph.input(Shape::vector(4), Element::Single);
    let loss = graph.sum(graph.relu(data));
    assert!(
        refuses(|| {
            let _ = graph.backward(loss);
        }),
        "a loss without parameters was differentiated",
    );
}

#[test]
fn a_plan_holds_every_value_and_the_seed_of_every_parameter() {
    let graph = Graph::new();
    let weight = graph.parameter(
        Shape::matrix(4, 4),
        Init::Uniform {
            low: -0.5,
            high: 0.5,
        },
        Element::Single,
    );
    let input = graph.input(Shape::matrix(2, 4), Element::Single);
    let out = graph.softmax(graph.matmul(input, weight));
    graph.backward(graph.sum(out));
    let encoding = encoding(&graph);
    assert!(encoding.value_count() as usize >= graph.value_count());
    assert!(encoding.arena_bytes() > 0);
    assert!(encoding.work() > 0);
    let layout = Layout::of(&graph, ALIGNMENT);
    let seed = layout
        .seeds()
        .iter()
        .find(|seed| {
            layout.weight_bytes(PLACEMENT, seed.address())
                == encoding.span(weight, PLACEMENT).offset
        })
        .expect("the weight carries its sampler");
    assert_eq!(seed.elements(), 16);
    assert_eq!(
        seed.init(),
        Init::Uniform {
            low: -0.5,
            high: 0.5
        }
    );
}

#[test]
fn a_non_scalar_loss_is_refused() {
    let graph = Graph::new();
    let weight = graph.parameter(Shape::vector(4), Init::Zero, Element::Single);
    assert!(
        refuses(|| {
            let _ = graph.backward(weight);
        }),
        "a vector was accepted as a loss",
    );
}

#[test]
fn every_tensor_a_plan_names_lies_inside_its_region() {
    for profile in every_profile() {
        let graph = Graph::new();
        let weight = graph.parameter(Shape::matrix(8, 4), Init::Zero, Element::Single);
        let data = graph.input(Shape::matrix(2, 8), Element::Single);
        let out = graph.softmax(graph.add(
            graph.matmul(data, weight),
            graph.fill(Shape::vector(4), 1.0),
        ));
        graph.retain(out);
        let grads = graph.backward(graph.sum(out));
        graph.retain(grads.of(weight));
        let encoding = encoding_with(&graph, profile);
        let layout = Layout::of(&graph, ALIGNMENT);
        for value in [weight, data, out, grads.of(weight)] {
            let span = encoding.span(value, PLACEMENT);
            let bytes = u64::from(span.elements) * WORD_BYTES;
            let (base, limit) = match span.store {
                Store::Tensors => (PLACEMENT.tensors() * WORD_BYTES, encoding.tensor_bytes()),
                Store::Weights => (PLACEMENT.weights() * WORD_BYTES, layout.weights().bytes()),
            };
            assert!(
                span.offset - base + bytes <= limit,
                "tensor {} of {} bytes at {} leaves the {} bytes of its {:?}",
                value.id(),
                bytes,
                span.offset - base,
                limit,
                span.store,
            );
            assert_eq!(
                (span.offset - base) % ALIGNMENT,
                0,
                "a tensor lies off the block grid"
            );
        }
    }
}

#[test]
fn a_folded_operand_remembers_which_side_of_its_consumer_it_took() {
    let graph = Graph::new();
    let left = graph.parameter(Shape::vector(4), Init::Zero, Element::Single);
    let right = graph.parameter(Shape::vector(4), Init::Zero, Element::Single);
    let bias = graph.input(Shape::vector(4), Element::Single);
    let difference = graph.sub(bias, graph.mul(left, right));
    let quotient = graph.div(graph.mul(right, left), bias);
    graph.retain(difference);
    graph.retain(quotient);
    let encoding = encoding(&graph);
    assert_eq!(encoding.task_count(), 2);
    let tape = tape(&encoding);
    let steps = steps(&encoding);
    assert_eq!(tape[0].op, op::MUL);
    let folded_into_a_subtraction = steps[tape[0].chain as usize];
    assert_eq!(folded_into_a_subtraction.op, op::SUB);
    assert_eq!(folded_into_a_subtraction.operand, bias.id());
    assert_eq!(
        folded_into_a_subtraction.swapped, 1,
        "a product folded into a subtraction is its subtrahend",
    );
    assert_eq!(tape[1].op, op::MUL);
    let folded_into_a_quotient = steps[tape[1].chain as usize];
    assert_eq!(folded_into_a_quotient.op, op::DIV);
    assert_eq!(folded_into_a_quotient.operand, bias.id());
    assert_eq!(
        folded_into_a_quotient.swapped, 0,
        "a product folded into a quotient is its dividend",
    );
}

#[test]
fn a_partial_reads_back_the_result_its_formula_names() {
    let graph = Graph::new();
    let weight = graph.parameter(Shape::vector(4), Init::Zero, Element::Single);
    let scale = graph.parameter(Shape::vector(4), Init::Zero, Element::Single);
    let activated = graph.tanh(weight);
    let scaled = graph.mul(activated, scale);
    let loss = graph.sum(scaled);
    let gradients = graph.backward(loss);
    graph.retain(gradients.of(weight));
    let encoding = encoding(&graph);
    let tape = tape(&encoding);
    let tangent = tape
        .iter()
        .find(|task| task.op == op::TANH)
        .expect("the tangent keeps a task of its own while the product differentiates it");
    assert_eq!(tangent.out, activated.id());
    let partial = tape
        .iter()
        .find(|task| task.op == op::TANH && Kind::of(task.kind) == Kind::Partial)
        .expect("the tangent leaves a partial behind");
    assert_eq!(
        partial.a,
        activated.id(),
        "a tangent partial reads the value its own op produced, not the operand it was handed",
    );
    assert_eq!(partial.b, neura_abi::NO_VALUE);
    assert_eq!(partial.slot, 0);
    assert_eq!(partial.c, gradients.of(activated).id());
    assert_eq!(partial.out, gradients.of(weight).id());
}

#[test]
fn a_partial_reads_back_the_operands_its_formula_names() {
    let graph = Graph::new();
    let weight = graph.parameter(Shape::vector(4), Init::Zero, Element::Single);
    let other = graph.parameter(Shape::vector(4), Init::Zero, Element::Single);
    let magnitude = graph.abs(weight);
    let scaled = graph.mul(magnitude, other);
    let loss = graph.sum(scaled);
    let gradients = graph.backward(loss);
    graph.retain(gradients.of(weight));
    graph.retain(gradients.of(other));
    let encoding = encoding(&graph);
    let tape = tape(&encoding);
    let absolute = tape
        .iter()
        .find(|task| task.op == op::ABS && Kind::of(task.kind) == Kind::Partial)
        .expect("a magnitude sign reaches the operand it was taken from");
    assert_eq!(
        absolute.a,
        weight.id(),
        "a magnitude partial has to read the operand it differentiates",
    );
    assert_eq!(absolute.b, neura_abi::NO_VALUE);
    let products = tape
        .iter()
        .filter(|task| task.op == op::MUL && Kind::of(task.kind) == Kind::Partial)
        .collect::<Vec<_>>();
    assert_eq!(products.len(), 2, "each tracked factor carries a partial");
    for (slot, partial) in products.iter().enumerate() {
        assert_eq!(
            partial.a,
            neura_abi::NO_VALUE,
            "a product descends through the factor it did not differentiate",
        );
        assert_eq!(
            partial.b,
            if slot == 0 {
                other.id()
            } else {
                magnitude.id()
            },
        );
        assert_eq!(partial.slot, slot as u32);
    }
}

#[test]
fn a_write_takes_its_turn_after_every_write_it_follows() {
    let graph = Graph::new();
    let state = graph.resident(Shape::vector(4), Element::Single);
    let deep = {
        let mut value = graph.relu(graph.input(Shape::vector(4), Element::Single));
        for _ in 0..5 {
            value = graph.relu(value);
        }
        value
    };
    let shallow = graph.fill(Shape::vector(4), 7.0);
    graph.add_into(state, deep);
    graph.copy_into(state, shallow);
    let out = graph.relu(state);
    graph.retain(state);
    graph.retain(out);
    let encoding = encoding(&graph);
    let updates = writers(&encoding, state.id());
    assert_eq!(updates.len(), 2, "two tasks update the resident tensor");
    let reader = writers(&encoding, out.id())[0];
    assert!(
        follows(&encoding, updates[0], updates[1]),
        "the copy reaches the tensor the sum already updated",
    );
    assert!(
        updates
            .iter()
            .all(|update| follows(&encoding, *update, reader)),
        "the reader reaches the tensor after every update to it",
    );
}

#[test]
fn a_chain_of_single_task_levels_rides_one_segment() {
    let graph = Graph::new();
    let mut value = graph.input(Shape::vector(64), Element::Single);
    for _ in 1..8 {
        value = graph.relu(graph.mul(value, value));
    }
    let out = graph.relu(value);
    graph.retain(out);
    let encoding = encoding(&graph);
    assert_eq!(encoding.task_count(), 7);
    assert_eq!(
        encoding.dispatch_count(),
        1,
        "a chain of single task levels leaves one dispatch",
    );
    assert_eq!(
        encoding.dispatches()[0].segments,
        1,
        "one workgroup carries the whole chain",
    );
    assert_eq!(encoding.segments().len(), 1);
    for task in 0..encoding.task_count() as usize {
        assert_eq!(segment_of(&encoding, task), 0);
        assert_eq!(dispatch_of(&encoding, task), 0);
    }
}

#[test]
fn a_fold_reads_a_leaf_no_later_than_the_task_it_lands_behind() {
    let graph = Graph::new();
    let state = graph.resident(Shape::vector(4), Element::Single);
    let bias = graph.parameter(Shape::vector(4), Init::Zero, Element::Single);
    let read = graph.mul(state, bias);
    let patch = graph.fill(Shape::vector(4), 7.0);
    graph.copy_into(state, patch);
    let out = graph.relu(read);
    graph.retain(out);
    let encoding = encoding(&graph);
    let writer = writers(&encoding, out.id());
    assert_eq!(writer.len(), 1);
    assert_eq!(
        kinds(&encoding)[writer[0]],
        Kind::Unary,
        "the rectifier kept a task of its own behind the write of the leaf it reads",
    );
    assert!(readers(&encoding, read.id()).contains(&writer[0]));
}

#[test]
fn a_fold_reaches_past_a_task_the_chain_does_not_read() {
    let graph = Graph::new();
    let left = graph.parameter(Shape::vector(8), Init::Zero, Element::Single);
    let right = graph.parameter(Shape::vector(8), Init::Zero, Element::Single);
    let product = graph.mul(left, right);
    let filler = graph.fill(Shape::vector(8), 1.0);
    let out = graph.add(product, filler);
    graph.retain(out);
    let encoding = encoding(&graph);
    assert_eq!(
        encoding.task_count(),
        2,
        "the product folded into the sum it feeds and left the filler on the tape",
    );
    assert_eq!(kinds(&encoding), vec![Kind::Fill, Kind::Binary]);
    let tape = tape(&encoding);
    assert_eq!(tape[1].out, out.id());
    assert_eq!(tape[1].steps, 1);
}

#[test]
fn a_reduction_opens_the_chain_it_would_have_materialized() {
    let graph = Graph::new();
    let data = graph.input(Shape::matrix(1, 8), Element::Single);
    let squared = graph.mul(data, data);
    let rows = graph.sum_rows(squared);
    graph.retain(rows);
    let encoding = encoding(&graph);
    assert_eq!(kinds(&encoding), vec![Kind::SumAxis]);
    let tape = tape(&encoding);
    assert_eq!(
        tape[0].prelude_steps, 1,
        "the fold of the reduction opens the product it would have read",
    );
    assert_eq!(tape[0].a, data.id(), "the reduction reads the operand");
    assert_eq!(tape[0].out, rows.id(), "the reduction writes its own row");
    assert_eq!(writers(&encoding, squared.id()), Vec::<usize>::new());
    let opened = steps(&encoding)[tape[0].prelude as usize];
    assert_eq!(opened.op, op::MUL);
    assert_eq!(opened.operand, data.id());
    assert_eq!(opened.swapped, 0);
}

#[test]
fn a_pinned_product_keeps_the_task_that_writes_it() {
    let graph = Graph::new();
    let data = graph.input(Shape::matrix(1, 8), Element::Single);
    let squared = graph.mul(data, data);
    graph.retain(squared);
    graph.retain(graph.sum_rows(squared));
    let encoding = encoding(&graph);
    assert_eq!(kinds(&encoding), vec![Kind::Binary, Kind::SumAxis]);
    assert!(
        tape(&encoding).iter().all(|task| task.prelude_steps == 0),
        "a reduction opens no tensor another task still reads",
    );
    assert_eq!(writers(&encoding, squared.id()).len(), 1);
}

#[test]
fn a_task_that_reads_its_source_more_than_once_keeps_it_materialized() {
    let graph = Graph::new();
    let data = graph.input(Shape::matrix(1, 8), Element::Single);
    let logits = graph.exp(data);
    graph.retain(graph.softmax(logits));
    let encoding = encoding(&graph);
    assert_eq!(kinds(&encoding), vec![Kind::Unary, Kind::Softmax]);
    assert!(
        tape(&encoding).iter().all(|task| task.prelude_steps == 0),
        "a row a task walks three times holds the task that wrote it",
    );
    assert_eq!(writers(&encoding, logits.id()).len(), 1);
}

#[test]
fn a_reduction_that_opens_a_chain_also_carries_its_epilogue() {
    let graph = Graph::new();
    let data = graph.input(Shape::matrix(1, 8), Element::Single);
    let squared = graph.mul(data, data);
    graph.retain(graph.relu(graph.sum_rows(squared)));
    let encoding = encoding(&graph);
    let tape = tape(&encoding);
    assert_eq!(encoding.task_count(), 1);
    assert_eq!(tape[0].prelude_steps, 1);
    assert_eq!(tape[0].steps, 1);
    let steps = steps(&encoding);
    assert_eq!(steps[tape[0].prelude as usize].op, op::MUL);
    assert_eq!(steps[tape[0].chain as usize].op, op::RELU);
    assert_ne!(
        tape[0].prelude, tape[0].chain,
        "the chain a task opens stands beside the chain it closes",
    );
}

#[test]
fn a_product_two_reductions_read_keeps_the_task_that_writes_it() {
    let graph = Graph::new();
    let data = graph.input(Shape::vector(8), Element::Single);
    let squared = graph.mul(data, data);
    graph.retain(graph.sum(squared));
    graph.retain(graph.sum_rows(squared));
    let encoding = encoding(&graph);
    assert_eq!(
        kinds(&encoding),
        vec![Kind::Binary, Kind::SumChunk, Kind::SumAxis],
    );
    assert!(
        tape(&encoding).iter().all(|task| task.prelude_steps == 0),
        "a reduction opens only a tensor no other task reads",
    );
}

#[test]
fn an_opened_reduction_hands_its_arena_back_to_the_product() {
    let graph = Graph::new();
    let data = graph.input(Shape::matrix(4, 256), Element::Single);
    graph.retain(graph.sum_rows(graph.mul(data, data)));
    let opened = encoding(&graph);
    let pinned = Graph::new();
    let data = pinned.input(Shape::matrix(4, 256), Element::Single);
    let squared = pinned.mul(data, data);
    pinned.retain(squared);
    pinned.retain(pinned.sum_rows(squared));
    assert_eq!(opened.task_count(), 4);
    assert!(
        opened.arena_bytes() < encoding(&pinned).arena_bytes(),
        "the product a reduction opens holds no tensor of its own",
    );
}

#[test]
fn a_fold_keeps_the_storage_a_view_reads_written() {
    let graph = Graph::new();
    let left = graph.parameter(Shape::matrix(2, 3), Init::Zero, Element::Single);
    let right = graph.parameter(Shape::matrix(2, 3), Init::Zero, Element::Single);
    let product = graph.mul(left, right);
    let doubled = graph.add(product, graph.fill(Shape::matrix(2, 3), 1.0));
    let rows = graph.sum_rows(graph.permute(product, [0, 1, 3, 2]));
    graph.retain(doubled);
    graph.retain(rows);
    let encoding = encoding(&graph);
    assert_eq!(
        writers(&encoding, product.id()).len(),
        1,
        "the product a view reads kept the task that writes it",
    );
    assert_eq!(encoding.task_count(), 3);
}

#[test]
fn an_update_in_place_reads_the_tensor_it_writes_through_its_own_layout() {
    let graph = Graph::new();
    let table = graph.resident(Shape::matrix(4, 4), Element::Single);
    let patch = graph.parameter(Shape::matrix(4, 4), Init::Zero, Element::Single);
    graph.add_into(table, patch);
    assert!(
        refuses(|| {
            graph.add_into(table, graph.permute(table, [0, 1, 3, 2]));
        }),
        "an update in place accepted a transposed view of the tensor it writes",
    );
    graph.add_into(
        table,
        graph.permute(graph.permute(table, [0, 1, 3, 2]), [0, 1, 3, 2]),
    );
}

#[test]
fn a_shape_the_device_cannot_address_is_refused_before_it_is_built() {
    let largest = Shape::of([46340, 46340]);
    assert_eq!(largest.elements(), 2_147_395_600);
    assert_eq!(largest.dims(), [1, 1, 46340, 46340]);
    assert_eq!(largest.rows(), 46340);
    assert_eq!(largest.strides(), [0, 0, 46340, 1]);
    assert!(refuses(|| {
        let _ = Shape::of([65536, 65536]);
    }));
    assert!(refuses(|| {
        let _ = Shape::of([4096, 1024, 1024]);
    }));
    assert!(refuses(|| {
        let _ = Shape::of([65536, 1, 1, 1]).combined(Shape::of([1, 1, 1, 65536]));
    }));
    assert!(refuses(|| {
        let _ = Shape::of([0]);
    }));
    assert!(refuses(|| {
        let _ = Shape::of([1, 1, 1, 1, 1]);
    }));
    assert_eq!(Shape::of([3, 4, 5]).reduced(2).elements(), 15);
}

#[test]
fn a_narrow_parameter_update_packs_the_image_the_chain_folded() {
    let graph = Graph::new();
    let weight = graph.parameter(Shape::vector(300), Init::Zero, Element::Half);
    graph.mul_into(weight, graph.fill(Shape::vector(300), 2.0));
    let encoding = encoding(&graph);
    let tape = tape(&encoding);
    let values = records::<ValueRecord>(encoding.values(), size_of::<ValueRecord>());
    assert_eq!(values[weight.id() as usize].element, Element::Half.code());
    assert_eq!(values[weight.id() as usize].store, Store::Weights.code());

    let convert = tape
        .iter()
        .find(|task| Kind::of(task.kind) == Kind::Convert)
        .expect("a half precision parameter packs the image its update computed");
    assert_eq!(convert.out, weight.id());
    assert_eq!(convert.first, 0);
    assert_eq!(convert.count, 150);
    assert_eq!(convert.prelude_steps, 0);
    let image = values[convert.a as usize];
    assert_eq!(image.element, Element::Single.code());
    assert_eq!(image.store, Store::Tensors.code());
    assert_eq!(image.dims, Shape::vector(300).dims());

    let writer = tape
        .iter()
        .find(|task| task.out == convert.a)
        .expect("the image holds the product the update computed");
    assert_eq!(Kind::of(writer.kind), Kind::Fill);
    assert_eq!(writer.steps, 1);
    let step = steps(&encoding)[writer.chain as usize];
    assert_eq!(step.op, op::MUL);
    assert_eq!(step.operand, weight.id());
    assert_eq!(step.swapped, 1);
    assert_eq!(
        tape.len(),
        2,
        "the fill and the convert that packs its product are the whole tape",
    );
}

#[test]
fn a_narrow_update_in_place_packs_the_word_it_reads() {
    let graph = Graph::new();
    let weight = graph.parameter(Shape::vector(300), Init::Zero, Element::Half);
    let factor = graph.input(Shape::vector(300), Element::Single);
    graph.mul_into(weight, factor);
    let encoding = encoding(&graph);
    let tape = tape(&encoding);
    assert_eq!(
        tape.len(),
        1,
        "an update in place of a narrow tensor reads and writes the very word its convert packs",
    );
    let convert = &tape[0];
    assert_eq!(Kind::of(convert.kind), Kind::Convert);
    assert_eq!(convert.a, weight.id());
    assert_eq!(convert.out, weight.id());
    assert_eq!(convert.first, 0);
    assert_eq!(convert.count, 150);
    assert_eq!(convert.steps, 1);
    let step = steps(&encoding)[convert.chain as usize];
    assert_eq!(step.op, op::MUL);
    assert_eq!(step.operand, factor.id());
    assert_eq!(step.swapped, 0);
}

#[test]
fn a_narrow_product_packs_the_image_it_computed() {
    let graph = Graph::new();
    let left = graph.parameter(Shape::matrix(4, 8), Init::Zero, Element::Half);
    let right = graph.parameter(Shape::matrix(8, 16), Init::Zero, Element::Half);
    let product = graph.matmul(left, right);
    assert_eq!(graph.element(product), Element::Half);
    let encoding = encoding(&graph);
    let tape = tape(&encoding);
    let values = records::<ValueRecord>(encoding.values(), size_of::<ValueRecord>());
    assert_eq!(
        values[product.id() as usize].element,
        Element::Half.code(),
        "a product of two narrow tensors keeps the numbers its operands carry",
    );
    let convert = tape
        .iter()
        .find(|task| Kind::of(task.kind) == Kind::Convert)
        .expect("a narrow product packs the image its tiles wrote");
    assert_eq!(convert.out, product.id());
    assert_eq!(convert.first, 0);
    assert_eq!(convert.count, 32);
    assert_eq!(convert.prelude_steps, 0);
    let image = values[convert.a as usize];
    assert_eq!(image.element, Element::Single.code());
    assert_eq!(image.dims, Shape::matrix(4, 16).dims());
    assert_eq!(
        Shape::of(values[product.id() as usize].dims).elements(),
        64,
        "the image holds one number per element of the product",
    );
    tape.iter()
        .find(|task| task.out == convert.a && Kind::of(task.kind) == Kind::Matmul)
        .expect("the image holds the product the tiles computed");
}

#[test]
fn a_quantized_parameter_packs_four_numbers_a_word_beside_its_quantum() {
    let graph = Graph::new();
    let weight = graph.quantized_parameter(Shape::vector(300), Init::Zero, 0.25);
    assert_eq!(graph.element(weight), Element::Int8);
    assert_eq!(graph.scale(weight), 0.25);
    let instead = Graph::new();
    instead.parameter(Shape::vector(300), Init::Zero, Element::Single);
    let single_precision = encoding(&instead);
    let encoding = encoding(&graph);
    let values = records::<ValueRecord>(encoding.values(), size_of::<ValueRecord>());
    let record = values[weight.id() as usize];
    assert_eq!(record.element, Element::Int8.code());
    assert_eq!(record.store, Store::Weights.code());
    assert_eq!(
        record.table,
        Element::Int8.payload_words(300) as u32,
        "the quantum a quantized tensor reconstructs by stands at the end of the words its numbers pack into",
    );
    assert_eq!(encoding.weights().words(), Element::Int8.storage_words(300));
    assert_eq!(single_precision.weights().words(), 300);
}

#[test]
fn a_quantized_image_packs_four_numbers_a_word() {
    let graph = Graph::new();
    let source = graph.parameter(Shape::vector(300), Init::Zero, Element::Single);
    let quantized = graph.quantize(source, 0.125);
    graph.retain(quantized);
    let instead = Graph::new();
    let source = instead.parameter(Shape::vector(300), Init::Zero, Element::Single);
    instead.retain(instead.cast(source, Element::Half));
    let half_precision = encoding(&instead);
    let encoding = encoding(&graph);
    let tape = tape(&encoding);
    let values = records::<ValueRecord>(encoding.values(), size_of::<ValueRecord>());
    let record = values[quantized.id() as usize];
    assert_eq!(record.element, Element::Int8.code());
    assert_eq!(record.table, Element::Int8.payload_words(300) as u32);
    assert_eq!(record.store, Store::Tensors.code());
    let convert = tape
        .iter()
        .find(|task| Kind::of(task.kind) == Kind::Convert)
        .expect("a quantized tensor packs the numbers its image computed");
    assert_eq!(convert.out, quantized.id());
    assert_eq!(convert.a, source.id());
    assert_eq!(convert.first, 0);
    assert_eq!(convert.count, 75);
    assert_eq!(steps(&encoding)[convert.chain as usize].op, op::IDENTITY);
    assert_eq!(
        encoding.arena_bytes(),
        Element::Int8.storage_words(300) * WORD_BYTES,
        "the arena holds a word of every four numbers a quantized tensor carries beside the quantum they share",
    );
    assert_eq!(
        half_precision.arena_bytes(),
        Element::Half.storage_words(300) * WORD_BYTES,
    );
}

#[test]
fn a_cast_declares_the_numbers_a_tensor_carries() {
    let graph = Graph::new();
    let wide = graph.input(Shape::vector(6), Element::Single);
    let narrow = graph.cast(wide, Element::Half);
    let folded = graph.sum(narrow);
    assert_eq!(graph.element(narrow), Element::Half);
    assert_eq!(
        graph.element(graph.cast(narrow, Element::Half)),
        Element::Half
    );
    assert_eq!(graph.element(graph.add(narrow, narrow)), Element::Half);
    assert_eq!(graph.element(graph.add(narrow, wide)), Element::Single);
    assert_eq!(graph.element(graph.relu(narrow)), Element::Half);
    assert_eq!(graph.element(folded), Element::Single);
    assert_eq!(
        graph.cast(narrow, Element::Half),
        narrow,
        "a cast that asks for the numbers a tensor already carries adds no task",
    );
    let encoding = encoding(&graph);
    let tape = tape(&encoding);
    let convert = tape
        .iter()
        .find(|task| Kind::of(task.kind) == Kind::Convert)
        .expect("a cast to half packs the numbers it narrows");
    assert_eq!(convert.out, narrow.id());
    assert_eq!(convert.a, wide.id());
    assert_eq!(convert.count, 3);
    assert_eq!(convert.steps, 1);
    assert_eq!(steps(&encoding)[convert.chain as usize].op, op::IDENTITY);
    let widened = tape
        .iter()
        .find(|task| task.out == folded.id())
        .expect("a sum reads the narrow tensor it folds");
    assert_eq!(Kind::of(widened.kind), Kind::SumChunk);
}

fn narrow_rows_through_an_image(kind: Kind) {
    let graph = Graph::new();
    let table = graph.parameter(Shape::matrix(4, 2), Init::Zero, Element::Half);
    let indices = graph.input(Shape::matrix(3, 1), Element::Single);
    let updates = graph.input(Shape::matrix(3, 2), Element::Single);
    match kind {
        Kind::Scatter => graph.scatter_into(table, indices, updates),
        Kind::ScatterWrite => graph.write_into(table, indices, updates),
        other => panic!("a {} task reaches no row of a table", other.name()),
    }
    let encoding = encoding(&graph);
    let tape = tape(&encoding);
    let values = records::<ValueRecord>(encoding.values(), size_of::<ValueRecord>());
    let convert = tape
        .iter()
        .find(|task| Kind::of(task.kind) == Kind::Convert)
        .expect("a half precision table packs the rows its task reached");
    assert_eq!(convert.out, table.id());
    assert_eq!(convert.count, 4);
    assert_eq!(values[convert.a as usize].store, Store::Tensors.code());

    let rows = tape
        .iter()
        .find(|task| Kind::of(task.kind) == kind)
        .expect("the task reaches the rows of the image");
    assert_eq!(rows.out, convert.a);
    let copy = tape
        .iter()
        .find(|task| task.out == convert.a && Kind::of(task.kind) == Kind::Unary)
        .expect("the image holds the table before the task reaches it");
    assert_eq!(copy.a, table.id());
    assert_eq!(copy.param, 0.0);
    assert_eq!(copy.op, op::IDENTITY);
}

#[test]
fn a_narrow_parameter_reaches_the_rows_it_names_through_an_image() {
    narrow_rows_through_an_image(Kind::Scatter);
    narrow_rows_through_an_image(Kind::ScatterWrite);
}

#[test]
fn a_cursor_stays_on_the_tape_the_block_it_starts_from_reads_it() {
    let graph = Graph::new();
    let queries = graph.parameter(Shape::of([1, 1, 4, 4]), Init::Zero, Element::Single);
    let keys = graph.parameter(Shape::of([1, 1, 4, 4]), Init::Zero, Element::Single);
    let cursor = graph.fill(Shape::scalar(), 2.0);
    let out = graph.attention(
        queries,
        keys,
        keys,
        neura_graph::AttentionOptions {
            scale: 0.5,
            causal: true,
            origin: Some(cursor),
        },
    );
    graph.retain(out);
    let encoding = encoding(&graph);
    let written = writers(&encoding, cursor.id());
    assert_eq!(
        written.len(),
        1,
        "a cursor is a tensor the task that walks a block reads, not a chain it folds away",
    );
    let attended = readers(&encoding, cursor.id());
    let attention = attended
        .iter()
        .copied()
        .find(|task| Kind::of(tape(&encoding)[*task].kind) == Kind::Attention)
        .expect("the attention reads the cursor it starts from");
    assert!(
        follows(&encoding, written[0], attention),
        "the task that writes the cursor runs before the block that starts from it",
    );
    assert_eq!(tape(&encoding)[attention].origin, cursor.id());
}

#[test]
fn a_cursor_holds_one_position_per_plane() {
    let graph = Graph::new();
    let queries = graph.parameter(Shape::of([2, 1, 4, 4]), Init::Zero, Element::Single);
    let keys = graph.parameter(Shape::of([2, 1, 4, 4]), Init::Zero, Element::Single);
    let positions = |dims: [u32; 4]| graph.fill(Shape::of(dims), 1.0);
    let options = |origin| neura_graph::AttentionOptions {
        scale: 0.5,
        causal: true,
        origin,
    };
    let _ = graph.attention(queries, keys, keys, options(None));
    let _ = graph.attention(queries, keys, keys, options(Some(positions([1, 1, 1, 1]))));
    let _ = graph.attention(queries, keys, keys, options(Some(positions([2, 1, 1, 1]))));
    assert!(refuses(|| {
        let _ = graph.attention(queries, keys, keys, options(Some(positions([3, 1, 1, 1]))));
    }));
    assert!(refuses(|| {
        let _ = graph.attention(queries, keys, keys, options(Some(positions([1, 1, 4, 1]))));
    }));
    assert!(refuses(|| {
        let brief = graph.parameter(Shape::of([2, 1, 2, 4]), Init::Zero, Element::Single);
        let _ = graph.attention(
            queries,
            brief,
            brief,
            options(Some(positions([1, 1, 1, 1]))),
        );
    }));
}

#[test]
fn a_block_quantized_weight_finds_its_quantum_beside_the_words_it_packs() {
    let graph = Graph::new();
    let weight = graph.block_quantized_parameter(Shape::vector(300), Init::Zero, Element::Int4);
    let encoding = encoding(&graph);
    let values = records::<ValueRecord>(encoding.values(), size_of::<ValueRecord>());
    let record = values[weight.id() as usize];
    assert_eq!(record.element, Element::Int4.code());
    assert_eq!(record.store, Store::Weights.code());
    assert_eq!(
        record.table,
        Element::Int4.payload_words(300) as u32,
        "the quantum of every block stands beside the words its numbers pack into",
    );
    assert_eq!(Element::Int4.quanta(300), 3);
    assert_eq!(encoding.weights().words(), Element::Int4.storage_words(300));
}

#[test]
fn a_tape_never_writes_a_block_quantized_tensor() {
    let graph = Graph::new();
    let weight = graph.block_quantized_parameter(Shape::vector(4), Init::Zero, Element::Int4);
    let data = graph.input(Shape::vector(4), Element::Single);
    graph.add_into(weight, data);
    assert!(
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| encoding(&graph))).is_err(),
        "a block quantized weight packs the quantum of every block out of the numbers it holds, and a tape carries none of them",
    );
}