File size: 201,081 Bytes
3a77415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
#!/usr/bin/env python3
"""Regenerate every headline number of the final bench as LaTeX macros (CPU only, no model run, no GPU).

Writes ../latex/numbers_final.tex (one \\newcommand per number) and
../latex/sections/A_subjects_table.tex (per-subject table). Re-runnable: the teacher and the same-engine baselines
are picked up automatically as soon as their logs are complete.

Sources (raw logs only; TABELLA.md is never read):
  - launch engine (motore-lancio-1107, commit 4ed3ec488), Corsair, Vulkan:
      /mnt/models/banco_completo/esiti_finale_1107/<XS|S|M|maestro|NAIVE_TQ1_0|IQ2_XXS|IQ1_M>/
      full MMLU: <model>/mmlu_blocchi/mmlu_<block>.log (MCLP rows), suite: <model>/<task>.log, lm-eval samples
  - teacher fallback (earlier build of the same fork): /mnt/models/banco_completo/esiti/maestro/
      -> every macro derived from it is flagged (\\teXXXsame = 0) and the tables print a cross-build mark
  - CUDA (RTX 4060 Laptop 8 GB): stato/aragorn_mmlu*, stato/cudavec_b, RIVALI_ARAGORN_1103, Q2_K block logs
  - speed: velocita.txt of the final bench, rows ROCM-MMQ / AB-RILASCIO / ARAGORN-MTP of stato/cicli.tsv
  - release files: /mnt/usb-ssd/lancio_1109/Thor-T-35B-A3B-{S,M}.gguf, /mnt/usb-ssd/lancio_1103/Thor-T-35B-A3B-XS.gguf
      (sha256 of the whole file; for S and M also a per-tensor comparison with the benchmarked file)

Statistics as in the paper: exact two-sided McNemar on discordant pairs; paired bootstrap of the student/teacher
ratio (10,000 resamples of the questions, seeds 20261102 + k, same indices for every model); cluster bootstrap over
the 57 subjects. Generative tasks: no McNemar on single runs (serving is not deterministic, see run-to-run pairs).

Usage:  OMP_NUM_THREADS=1 nice -n 19 python3 genera_numeri.py [--no-hash] [--check]
  --no-hash  skip sha256/per-tensor hashing and reuse the cache (.sha256_cache.json)
"""
from __future__ import annotations

import argparse
import glob
import hashlib
import json
import math
import os
import re
import time
import sys
from pathlib import Path

for _v in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"):
    os.environ.setdefault(_v, "1")
import numpy as np  # noqa: E402

# ---- data roots: override with environment variables to run on another machine or on the published bundle
BENCH = os.environ.get("THOR_BENCH_ROOT", "/mnt/models/banco_completo")    # per-question logs of the benches
GGUF = os.environ.get("THOR_GGUF_ROOT", "/mnt/models/gguf")                 # model files and development logs
FORGE = os.environ.get("THOR_FORGE_ROOT", "/home/angelo/tony-forgia")       # run register, bench files, CUDA logs
RELDIR = os.environ.get("THOR_RELEASE_ROOT", "/mnt/usb-ssd")                # released GGUF files
BUILD = os.environ.get("THOR_BUILD_ROOT", "/mnt/models/build")              # engine checkout (gguf-py only)
HFCACHE = os.environ.get("HF_HOME_CACHE", "/home/angelo/.cache/huggingface")  # cais/mmlu parquet

HERE = Path(__file__).resolve().parent
LATEX = Path(os.environ.get("THOR_LATEX_DIR", str(HERE.parent / "latex")))
OUT_TEX = LATEX / "numbers_final.tex"
OUT_SUBJ = LATEX / "sections" / "A_subjects_table.tex"
OUT_SUBJ_TEXT = LATEX / "sections" / "A_subjects_text.tex"
CACHE = HERE / ".sha256_cache.json"
# file facts (sizes, sha256, tensor identity, engine commit): written by a full run, read by --bundle runs, so that the
# script runs on the published measurement bundle without any model file
MANIFEST = Path(os.environ.get("THOR_FILE_MANIFEST", str(HERE / "manifest_file.json")))
FILE_SIZES: dict[str, int] = {}
# Winogrande items scored through the engine's wrong-first-logits branch (winogrande_ramo.py); excluded in the
# sensitivity analysis
_WR = Path(__file__).resolve().parent / "winogrande_ramo.json"
try:
    _wr = json.loads(_WR.read_text()) if _WR.exists() else None
    WINO_KEEP = None if _wr is None else np.array([i not in set(_wr["wrong_branch"]) for i in range(_wr["n_items"])])
    WINO_BAD = None if _wr is None else len(_wr["wrong_branch"])
except (ValueError, KeyError):
    WINO_KEEP, WINO_BAD = None, None
TCAND_SCORES: list = []
TE_PROV: dict[str, int] = {}     # task label -> 1 if the teacher reference is on the launch engine
TE_DRIFT: list[tuple] = []       # (task label, new - old points, changed answers, n) for tasks re-run on the launch engine
TASK_LABEL = {"hs": "HellaSwag", "wino": "Winogrande", "arcc": "ARC-Challenge", "arce": "ARC-Easy", "piqa": "PIQA",
              "boolq": "BoolQ", "obqa": "OpenBookQA", "tqa": "TruthfulQA", "mmlupro": "MMLU-Pro"}
SIZED_PATHS: set[str] = set()
PARTS: dict[str, dict] = {}

FIN = Path((BENCH + "/esiti_finale_1107"))
OLD = Path((BENCH + "/esiti"))
STATO = Path((FORGE + "/stato"))
CICLI = STATO / "cicli.tsv"
# the bundle ships only the register rows the script reads, with their line numbers (cicli_extract.tsv)
CICLI_EXTRACT = Path(os.environ.get("THOR_CICLI_EXTRACT", str(HERE / "cicli_extract.tsv")))
REGISTER_MARKERS = ("\tCARDAN-CONGIUNTO A-POST: passo", "\tCARDAN-CONGIUNTO B-POST: passo",
                    "\tARAGORN anteprima MMLU completo A e B:", "\tROCM-MMQ verifiche:", "\tAB-RILASCIO ", "\tARAGORN-MTP ", "\tA MMLU completo Kaggle CUDA ",
                    "\tMMLU-M-Q8 M motore nuovo", "\tCARDAN-KD PIENO-FED MMLU-2000 int8 80.30", "\tTHOR-T BERSAGLIO RAGGIUNTO",
                    "\tLANCIO3: A nuovo SALTATO",
                    "\tBANCO-COMPLETO: A mmlu_full", "\tM-COMPLETO-ARAGORN M MMLU completo su CUDA:",
                    "\tDecisione Angelo: base/maestro restano Ornith")


def register_rows() -> list[str]:
    """rows of the run register that the script reads; from cicli.tsv when present, else from the shipped extract"""
    if CICLI.exists():
        return [r for r in CICLI.read_bytes().decode("utf-8", "replace").split("\n")
                if any(m in r for m in REGISTER_MARKERS)]
    if CICLI_EXTRACT.exists():
        return [ln.split("\t", 1)[1] for ln in CICLI_EXTRACT.read_text(errors="replace").splitlines() if "\t" in ln]
    return []


def write_register_extract(path: Path) -> int:
    rows = CICLI.read_bytes().decode("utf-8", "replace").split("\n")   # stray CRs would shift line numbers
    cited = {int(ln.split("\t")[1]) for ln in (HERE / "storia_arresto_M.tsv").read_text().splitlines()[1:] if ln.strip()}
    cited |= {int(ln.split("\t")[2]) for ln in (HERE / "ricetta_SM.tsv").read_text().splitlines()[1:] if ln.strip()}
    cited |= {int(ln.split("\t")[0]) for ln in (HERE / "costo_SM.tsv").read_text().splitlines()[1:] if ln.strip()}
    cited |= {int(ln.split("\t")[1]) for ln in (HERE / "sizing_points.tsv").read_text().splitlines()[1:] if ln.strip()}
    cited |= {1276, 1241, 1245, 5048, 5060, 5061, 5063}
    for ln in (HERE / "radice_costo.tsv").read_text().splitlines()[1:]:
        if ln.strip():
            cited |= {int(ln.split("\t")[1]), int(ln.split("\t")[2])}
    if (HERE / "SM_CONSTRUCTION_FILES.tsv").exists():   # register rows of the shipped construction files of S and M
        for ln in (HERE / "SM_CONSTRUCTION_FILES.tsv").read_text(errors="replace").splitlines()[1:]:
            f_ = ln.split("\t")
            if len(f_) >= 4:
                cited |= {int(x) for x in re.findall(r"c(\d+)", f_[3])}
    # rows cited by the paper outside M's history (root lineage and cost, allocator facts, gate decisions; W5 round 17)
    if (HERE / "righe_citate.tsv").exists():
        cited |= {int(ln.split("\t")[0]) for ln in (HERE / "righe_citate.tsv").read_text().splitlines()[1:] if ln.strip()}
    keep = [f"{i + 1}\t{r}" for i, r in enumerate(rows)
            if any(m in r for m in REGISTER_MARKERS) or (i + 1) in cited or re.search(r"80,05|bersaglio|M-COMPLETO", r)]
    path.write_text("\n".join(keep) + "\n")
    return len(keep)
RIV = Path((GGUF + "/tony-tern/RIVALI_ARAGORN_1103"))
Q2K_CUDA = Path((GGUF + "/tony-tern/mmlu_logprob/aragorn/completo"))
MC = Path((FORGE + "/mc_v2"))
PARQUET = (HFCACHE + "/hub/datasets--cais--mmlu/snapshots/"
           "c30699e8356da336a370243923dbaf21066bb9fe/all/test-00000-of-00001.parquet")
GGUF_PY = (BUILD + "/thor-pub-q8/gguf-py")

BLOCKS = ["00000", "02000", "04000", "06000", "08000", "10000", "12000", "14000"]
NFULL, NDEV = 14042, 2000
SEED, NBOOT = 20261102, 10_000
PARAMS = 35_505_251_456  # exact parameter count of the teacher (llama-bench rounds it to 35.51 B)
GIB = 2 ** 30

RELEASE = {  # name: (released file, benchmarked file, base checkpoint, last recipe step)
    "XS": ((RELDIR + "/lancio_1103/Thor-T-35B-A3B-XS.gguf"), (RELDIR + "/lancio_1103/Thor-T-35B-A3B-XS.gguf"),
           "single plane (C)", "POST step 50 on T400; trained MTP head"),
    "S": ((RELDIR + "/lancio_1109/Thor-T-35B-A3B-S.gguf"),
          (GGUF + "/tony-tern/MTP_1101/prova_S/S-packed-testaXS.gguf"),
          "multi-plane B", "POST step 100 on B; MTP head of XS"),
    "M": ((RELDIR + "/lancio_1109/Thor-T-35B-A3B-M.gguf"),
          (GGUF + "/tony-tern/MTP_1101/prova_M_testaXS_1106/Thor-T-M-packed-testaXS.gguf"),
          "multi-plane A", "POST step 50 on A; MTP head of XS"),
}
TEACHER_BYTES_FILE = (GGUF + "/tony-tern/teacher-q8/Ornith-1.5-35B-A3B-Q8_0.gguf")
Q2K_FILE = (GGUF + "/thor-rivale/Ornith-1.5-35B-A3B-Q2_K.gguf")
Q4KM_FILE = (GGUF + "/thor-rivale/Ornith-1.5-35B-A3B-Q4_K_M.gguf")

# same-engine baselines (launch engine), with the cross-build CUDA value used until they land
BASELINES = {  # dir: (macro prefix, label, gguf, CUDA fallback dir in RIVALI_ARAGORN_1103 or None, fallback value)
    "NAIVE_TQ1_0": ("bnaive", "naive TQ1\\_0", (GGUF + "/tony-tern/BASELINE_1109/Ornith-1.5-35B-A3B-naive-TQ1_0.gguf"),
                    "Ornith-1.5-35B-A3B-TQ1_0-ingenuo", None),
    "IQ1_M": ("biqonem", "IQ1\\_M", (GGUF + "/tony-tern/RIVALI/dell/Ornith-1.5-35B-A3B-IQ1_M.gguf"),
              "Ornith-1.5-35B-A3B-IQ1_M", None),
    "MILLIE_ING": ("bmillie", "naive, Millie format", os.environ.get(
        "THOR_MILLIE_GGUF", str(Path(GGUF).parent / "deposito_spostato" / "millie" / "ornith57"
                                / "Ornith-1.5-35B-A3B-formatoMillie-rif.gguf")),
        None, None),
    "IQ2_XXS": ("biqtwo", "IQ2\\_XXS", (GGUF + "/thor-rivale/Ornith-1.5-35B-A3B-IQ2_XXS.gguf"),
                None, 71.53),  # earlier CUDA build (Kaggle T4), raw log not paired; value from the run register
}

MACROS: list[tuple[str, str, str]] = []  # (name, value, comment)
WARN: list[str] = []


# ------------------------------------------------------------------------------------------------ formatting
def mac(name: str, value, comment: str = "") -> None:
    if not re.fullmatch(r"[A-Za-z]+", name):
        raise SystemExit(f"bad macro name {name}")
    MACROS.append((name, str(value), comment))


def f2(x: float) -> str:
    return f"{x:.2f}"


def ints(n: int) -> str:
    return f"{n:,}"


def tex_p(p: float) -> str:
    if p < 1e-10:
        return r"\ensuremath{p < 10^{-10}}"
    if p >= 0.001:
        s = f"{p:.2g}" if p < 0.1 else f"{p:.2f}"
        return rf"\ensuremath{{p = {s}}}"
    m, e = f"{p:.1e}".split("e")
    return rf"\ensuremath{{p = {m}\cdot10^{{{int(e)}}}}}"


def p_exact(b: int, c: int) -> float:
    n = b + c
    if n == 0:
        return 1.0
    k = min(b, c)
    # log-space sum, exact enough for n up to a few thousand
    lt = [math.lgamma(n + 1) - math.lgamma(i + 1) - math.lgamma(n - i + 1) - n * math.log(2) for i in range(k + 1)]
    mx = max(lt)
    return min(1.0, 2 * math.exp(mx) * sum(math.exp(t - mx) for t in lt))


# ------------------------------------------------------------------------------------------------ log readers
def after_cutoff(path) -> bool:
    """one cutoff T0 for the whole chain (THOR_LOG_CUTOFF, epoch seconds; round 24): a log modified after T0 is treated
    as not yet written, in the full run and in the bundle list alike (elenca_bundle.py uses the same rule). A bundle copy
    (THOR_BUNDLE_DIR) holds only files listed before T0, so the rule is not applied there (copy times are new)."""
    c = os.environ.get("THOR_LOG_CUTOFF")
    if not c or os.environ.get("THOR_BUNDLE_DIR"):
        return False
    try:
        return os.path.getmtime(path) > float(c)
    except OSError:
        return False


def read_mclp(path: Path) -> dict | None:
    """MCLP rows: idx gold chosen k lp*k cnt*k. Returns arrays sorted by idx, or None if missing."""
    if not path.exists() or after_cutoff(path):
        return None
    segs: list[dict] = [{}]  # a concatenated log restarts the index at 0 for every block
    fins = []
    for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
        line = line.rstrip("\r")
        if line.startswith("MCLP\t"):
            c = line.split("\t")
            k = int(c[4])
            i = int(c[1])
            if i in segs[-1]:
                segs.append({})
            segs[-1][i] = (int(c[2]), int(c[3]), [float(x) for x in c[5:5 + k]], [int(x) for x in c[5 + k:5 + 2 * k]])
        elif "Final result:" in line:
            fins.append(float(re.search(r"Final result: ([0-9.]+)", line).group(1)))
    if not segs[0]:
        return None
    rows_l = []
    for sg in segs:
        if sorted(sg) != list(range(len(sg))):
            raise SystemExit(f"non-consecutive MCLP indices in {path}")
        rows_l += [sg[i] for i in range(len(sg))]
    fin = fins[-1] if len(segs) == 1 and fins else (100.0 if len(segs) > 1 else None)
    gold = np.array([r[0] for r in rows_l])
    ch = np.array([r[1] for r in rows_l])
    lp4 = np.array([r[2] for r in rows_l]) if all(len(r[2]) == 4 for r in rows_l) else None
    # summed recount = logged mean x token count, exactly as the scorer's outputs give it. A choice whose continuation
    # is empty after the shared prefix is removed (count 0) gets sum 0, which is the correct summed log-probability of
    # an empty suffix; its logged per-token mean comes from an out-of-range read in the scorer and is not valid. Those
    # items are counted (zero_tok) and listed (zero_idx) so the per-token metric can be reported without them.
    summ = np.array([int(np.argmax(np.array(r[2]) * np.array(r[3]))) for r in rows_l])
    zero_idx = [i for i, r in enumerate(rows_l) if min(r[3]) == 0]
    zero_tok = len(zero_idx)
    if len(segs) > 1:
        d = {"gold": gold, "ok": (gold == ch).astype(np.int8), "ok_sum": (gold == summ).astype(np.int8),
             "choice": ch, "choice_sum": summ, "final": fin, "path": str(path), "zero_tok": zero_tok,
             "zero_idx": zero_idx, "lp": lp4}
        return d
    d = {"gold": gold, "ok": (gold == ch).astype(np.int8), "ok_sum": (gold == summ).astype(np.int8),
         "choice": ch, "choice_sum": summ, "final": fin, "path": str(path), "zero_tok": zero_tok,
             "zero_idx": zero_idx, "lp": lp4}
    if fin is not None and abs(100 * d["ok"].mean() - fin) > 0.006:
        raise SystemExit(f"Final result mismatch in {path}: {fin} vs {100 * d['ok'].mean():.4f}")
    return d


def concat(parts: list[dict]) -> dict:
    out = {k: np.concatenate([p[k] for p in parts]) for k in ("gold", "ok", "ok_sum", "choice", "choice_sum")} | {
        "path": ";".join(p["path"] for p in parts)}
    if all(p.get("lp") is not None for p in parts):
        out["lp"] = np.concatenate([p["lp"] for p in parts])
    return out


def read_blocks(paths: list[Path]) -> dict | None:
    parts = []
    for p in paths:
        d = read_mclp(p)
        # a block is complete when it has its "Final result" line, or (older logs without it) all its questions
        if d is None or (d["final"] is None and len(d["gold"]) not in (NDEV, NFULL - 7 * NDEV)):
            return None
        parts.append(d)
    full = concat(parts)
    return full if len(full["gold"]) == NFULL else None


def read_hellaswag(path: Path) -> dict | None:
    if not path.exists() or after_cutoff(path):
        return None
    v, prev = [], 0
    for r in path.read_text(errors="replace").splitlines():
        m = re.match(r"^(\d+)\s+([0-9.]+)%", r)
        if m:
            i, acc = int(m.group(1)), float(m.group(2))
            g = round(acc * i / 100)
            v.append(g - prev)
            prev = g
    return {"ok": np.array(v, dtype=np.int8), "path": str(path)} if len(v) == 10042 else None


def read_winogrande(path: Path) -> dict | None:
    if not path.exists() or after_cutoff(path):
        return None
    v = []
    for r in path.read_text(errors="replace").splitlines():
        f = r.split()
        if len(f) == 6 and f[0].isdigit():
            v.append(int(f[4] == f[5]))
    return {"ok": np.array(v, dtype=np.int8), "path": str(path)} if len(v) == 1267 else None


def latest_samples(d: Path, task: str) -> Path | None:
    fs = sorted(glob.glob(str(d / task / "*" / f"samples_{task}_*.jsonl")))
    return Path(fs[-1]) if fs else None


def read_gen(d: Path, task: str) -> dict | None:
    f = latest_samples(d, task)
    if f is None or after_cutoff(f):
        return None
    rows = [json.loads(x) for x in open(f)]
    out: dict = {"path": str(f)}
    by: dict[str, list] = {}
    for r in rows:
        by.setdefault(r.get("filter", "none"), []).append(r)
    for filt, rs in by.items():
        rs.sort(key=lambda r: r["doc_id"])
        empty = sum(1 for r in rs if not (r["resps"][0][0] or "").strip())
        out["n"] = len(rs)
        out["empty"] = empty
        for metric in ("exact_match", "math_verify", "prompt_level_strict_acc", "inst_level_strict_acc",
                       "prompt_level_loose_acc", "inst_level_loose_acc"):
            if metric in rs[0]:
                vals = []
                for r in rs:
                    x = r[metric]
                    if isinstance(x, list):
                        vals.append(np.mean(x) if metric.startswith("inst") else float(all(x)))
                    else:
                        vals.append(float(x))
                key = f"{filt}:{metric}"
                if metric.startswith("inst"):  # instruction level: pooled over instructions
                    num = sum(sum(r[metric]) if isinstance(r[metric], list) else r[metric] for r in rs)
                    den = sum(len(r[metric]) if isinstance(r[metric], list) else 1 for r in rs)
                    out[key] = 100 * num / den
                else:
                    out[key] = np.array(vals, dtype=np.int8)
    res_f = sorted(glob.glob(str(d / task / "*" / "results_*.json")))
    if res_f:
        out["results"] = json.load(open(res_f[-1]))
    return out


# ------------------------------------------------------------------------------------------------ statistics
def mcnemar(base: np.ndarray, cand: np.ndarray) -> tuple[int, int, float]:
    """wins of cand (cand right, base wrong), losses, exact p"""
    w = int(((cand == 1) & (base == 0)).sum())
    l_ = int(((cand == 0) & (base == 1)).sum())
    return w, l_, p_exact(w, l_)


def boot_ratio(t: np.ndarray, s: np.ndarray, seed: int) -> tuple[float, float]:
    rng = np.random.default_rng(seed)
    n = len(t)
    r = np.empty(NBOOT)
    for k in range(0, NBOOT, 500):
        idx = rng.integers(0, n, size=(min(500, NBOOT - k), n))
        r[k:k + idx.shape[0]] = 100 * s[idx].sum(1) / t[idx].sum(1)
    return float(np.percentile(r, 2.5)), float(np.percentile(r, 97.5))


def boot_diff(t: np.ndarray, s: np.ndarray, seed: int) -> tuple[float, float]:
    rng = np.random.default_rng(seed)
    n = len(t)
    r = np.empty(NBOOT)
    for k in range(0, NBOOT, 500):
        idx = rng.integers(0, n, size=(min(500, NBOOT - k), n))
        r[k:k + idx.shape[0]] = 100 * (s[idx].sum(1) - t[idx].sum(1)) / n
    return float(np.percentile(r, 2.5)), float(np.percentile(r, 97.5))


def cluster_boot(t: np.ndarray, s: np.ndarray, subj: np.ndarray, seed: int) -> tuple[float, float]:
    names = np.unique(subj)
    ts = np.array([t[subj == x].sum() for x in names])
    ss = np.array([s[subj == x].sum() for x in names])
    rng = np.random.default_rng(seed)
    idx = rng.integers(0, len(names), size=(NBOOT, len(names)))
    r = 100 * ss[idx].sum(1) / ts[idx].sum(1)
    return float(np.percentile(r, 2.5)), float(np.percentile(r, 97.5))


def cluster_boot_diff(t: np.ndarray, s: np.ndarray, subj: np.ndarray, seed: int) -> tuple[float, float]:
    """difference model - teacher in points, subjects resampled with replacement (G14_R2 m2)"""
    names = np.unique(subj)
    ts = np.array([t[subj == x].sum() for x in names])
    ss = np.array([s[subj == x].sum() for x in names])
    ns = np.array([(subj == x).sum() for x in names])
    rng = np.random.default_rng(seed)
    idx = rng.integers(0, len(names), size=(NBOOT, len(names)))
    d = 100 * (ss[idx].sum(1) - ts[idx].sum(1)) / ns[idx].sum(1)
    return float(np.percentile(d, 2.5)), float(np.percentile(d, 97.5))


def write_if_changed(path: Path, text: str) -> None:
    """write only when the content differs: shipped paper sources are pinned in SHA256SUMS, and an identical rewrite
    would make them look newer than the sums (G20_R4: paper sources hashed at freeze)"""
    if path.exists() and path.read_text() == text:
        return
    path.write_text(text)


def holm(ps: list[float]) -> list[float]:
    order = sorted(range(len(ps)), key=lambda i: ps[i])
    out = [0.0] * len(ps)
    run = 0.0
    for rank, i in enumerate(order):
        run = max(run, min(1.0, (len(ps) - rank) * ps[i]))
        out[i] = run
    return out


# ------------------------------------------------------------------------------------------------ hashing
def load_cache() -> dict:
    return json.loads(CACHE.read_text()) if CACHE.exists() else {}


def file_key(p: str) -> str:
    st = os.stat(p)
    return f"{p}|{st.st_size}|{int(st.st_mtime)}"


def _sidecar(p: str, ext: str) -> str | None:
    """value recorded next to a removed model file: <dir>/<stem>.<ext> or the only *.<ext> in that folder whose
    content names the file (sha256 lists), else None"""
    d, name = os.path.dirname(p), os.path.basename(p)
    stem = name[:-5] if name.endswith(".gguf") else name
    cands = [os.path.join(d, stem + "." + ext)] + sorted(glob.glob(os.path.join(d, f"*.{ext}")))
    for c in cands:
        if os.path.exists(c):
            txt = open(c, errors="replace").read().strip()
            if c.endswith(stem + "." + ext) or name in txt or len(cands) == 2:
                return txt
    return None


def file_size(p: str) -> int | None:
    """size of a model file; when the file was removed after measurement: its .bytes sidecar, then the manifest"""
    SIZED_PATHS.add(p)
    if os.path.exists(p):
        return os.path.getsize(p)
    side = _sidecar(p, "bytes")
    if side:
        return int(re.sub(r"[^0-9]", "", side.split()[0]))
    if MANIFEST.exists():
        # keys are the paths of the measuring machine; map its model root onto the configured one (bundle runs)
        root_m, root_here = "/mnt/models", str(Path(GGUF).parent)
        for k, v in json.loads(MANIFEST.read_text()).get("paths", {}).items():
            if k == p or (k.startswith(root_m + "/") and root_here + k[len(root_m):] == p):
                return v
    return None


def sha256_file(p: str, cache: dict, allow: bool) -> str | None:
    if not os.path.exists(p):
        side = _sidecar(p, "sha256")
        return side.split()[0] if side else None
    k = "sha|" + file_key(p)
    if k in cache:
        return cache[k]
    if not allow:
        return None
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for blk in iter(lambda: f.read(1 << 22), b""):
            h.update(blk)
    cache[k] = h.hexdigest()
    return cache[k]


def tensor_hashes(p: str, cache: dict, allow: bool) -> dict | None:
    k = "tens|" + file_key(p)
    if k in cache:
        return cache[k]
    if not allow:
        return None
    sys.path.insert(0, GGUF_PY)
    import gguf  # noqa: PLC0415
    r = gguf.GGUFReader(p)
    out = {}
    for t in r.tensors:
        out[t.name] = hashlib.sha256(bytes(np.ascontiguousarray(t.data).view(np.uint8))).hexdigest()
    cache[k] = out
    return out


# ------------------------------------------------------------------------------------------------ sections
def mmlu_section(subj: np.ndarray, cache: dict) -> dict:
    full: dict[str, dict] = {}
    for m in ("XS", "S", "M"):
        d = read_blocks([FIN / m / "mmlu_blocchi" / f"mmlu_{b}.log" for b in BLOCKS])
        if d is None:
            raise SystemExit(f"full MMLU of {m} incomplete on the launch engine")
        full[m] = d
    t_new = read_blocks([FIN / "maestro" / "mmlu_blocchi" / f"mmlu_{b}.log" for b in BLOCKS])
    if t_new is not None:
        teacher, same = t_new, 1
    else:
        teacher, same = read_mclp(OLD / "maestro" / "mmlu_full.log"), 0
        WARN.append("teacher full MMLU NOT on the launch engine yet: using esiti/maestro/mmlu_full.log (cross-build)")
    mac("teMMLUsame", same, "1 = teacher full MMLU measured on the launch engine")
    mac("teMMLUmark", "" if same else r"$^{\ddagger}$", "cross-build mark for teacher-relative numbers")
    mac("teMMLUsrc", "the launch engine" if same else "an earlier build of the same fork (cross-build)")
    t_old = read_mclp(OLD / "maestro" / "mmlu_full.log")
    if same and t_old is not None and np.array_equal(t_old["gold"], teacher["gold"]):
        # the teacher's own drift between the earlier build and the launch engine (G14_R5 S2)
        mac("teMMLUold", f2(100 * t_old["ok"].mean()), "teacher full MMLU, earlier build (same Q8_0 file)")
        mac("teMMLUdriftChoice", ints(int((t_old["choice"] != teacher["choice"]).sum())), "answers changed, of 14,042")
        w_, l_, pv_ = mcnemar(t_old["ok"], teacher["ok"])
        mac("teMMLUdriftWL", f"{w_}/{l_}", "right only on the launch engine / only on the earlier build")
        mac("teMMLUdriftP", tex_p(pv_))
        mac("teMMLUdriftPts", f"{100 * (teacher['ok'].mean() - t_old['ok'].mean()):+.2f}".replace("-", "$-$"))
        mac("teMMLUdevDrift", f2(100 * (teacher["ok"][:NDEV].mean() - t_old["ok"][:NDEV].mean())),
            "teacher drift on MMLU-2000, points")
        mac("mdMMLUretOld", f2(100 * full["M"]["ok"].mean() / t_old["ok"].mean()), "M against the earlier-build teacher")
        mac("mTargetPctOld", f2(100 * 80.05 / (100 * t_old["ok"].mean())), "the 80.05 target as % of the earlier-build teacher")
    for m, d in full.items():
        if not np.array_equal(d["gold"], teacher["gold"]):
            raise SystemExit(f"gold of {m} != gold of teacher")
    tab_gold = None
    try:
        import pyarrow.parquet as pq  # noqa: PLC0415
        tab_gold = np.array(pq.read_table(PARQUET, columns=["answer"]).column("answer").to_pylist())
    except Exception as e:  # noqa: BLE001
        WARN.append(f"cais/mmlu parquet not readable ({e}): gold check against the public split skipped")
    if tab_gold is not None and not np.array_equal(tab_gold, teacher["gold"]):
        raise SystemExit("gold of the logs != cais/mmlu test answers")
    t = teacher["ok"]
    tn = int(t.sum())
    mac("teMMLU", f2(100 * tn / NFULL), "teacher full MMLU")
    mac("teMMLUn", ints(tn))
    mac("teMMLUdev", f2(100 * t[:NDEV].mean()))
    mac("teMMLUheld", f2(100 * t[NDEV:].mean()))
    pre = {"XS": "xs", "S": "sm", "M": "md"}
    for k, (m, d) in enumerate(full.items()):
        p = pre[m]
        s = d["ok"]
        sn = int(s.sum())
        mac(f"{p}MMLU", f2(100 * sn / NFULL), f"{m} full MMLU, launch engine")
        mac(f"{p}MMLUn", ints(sn))
        mac(f"{p}MMLUret", f2(100 * sn / tn), "TEACHER-PCT")
        lo, hi = boot_ratio(t, s, SEED + 1 + 10 * k)
        mac(f"{p}MMLUretLo", f2(lo), "TEACHER-PCT")
        mac(f"{p}MMLUretHi", f2(hi), "TEACHER-PCT")
        clo, chi = cluster_boot(t, s, subj, SEED + 5 + 10 * k)
        mac(f"{p}MMLUretClLo", f"{clo:.2f}", "TEACHER-PCT cluster bootstrap over subjects (two decimals: edge)")
        mac(f"{p}MMLUretClHi", f"{chi:.2f}", "TEACHER-PCT")
        mac(f"{p}MMLUdiff", f"{100 * (sn - tn) / NFULL:+.2f}".replace("-", "$-$"))
        dlo, dhi = boot_diff(t, s, SEED + 6 + 10 * k)
        mac(f"{p}MMLUdiffLo", f"{dlo:+.2f}".replace("-", "$-$"))
        mac(f"{p}MMLUdiffHi", f"{dhi:+.2f}".replace("-", "$-$"))
        cd_lo, cd_hi = cluster_boot_diff(t, s, subj, SEED + 8 + 10 * k)
        mac(f"{p}MMLUdiffClLo", f"{cd_lo:+.2f}".replace("-", "$-$"), "difference, cluster bootstrap over subjects")
        mac(f"{p}MMLUdiffClHi", f"{cd_hi:+.2f}".replace("-", "$-$"))
        w, l_, pv = mcnemar(t, s)
        mac(f"{p}MMLUvsTe", f"{w}/{l_}", "wins/losses vs teacher")
        mac(f"{p}MMLUvsTeP", tex_p(pv))
        sh = s[NDEV:]
        mac(f"{p}MMLUheld", f2(100 * sh.mean()))
        mac(f"{p}MMLUheldRet", f2(100 * sh.sum() / t[NDEV:].sum()), "TEACHER-PCT")
        lo, hi = boot_ratio(t[NDEV:], sh, SEED + 2 + 10 * k)
        mac(f"{p}MMLUheldRetLo", f2(lo), "TEACHER-PCT")
        mac(f"{p}MMLUheldRetHi", f2(hi), "TEACHER-PCT")
        clo, chi = cluster_boot(t[NDEV:], sh, subj[NDEV:], SEED + 7 + 10 * k)
        if k == 0:
            mac("heldSubj", len(set(subj[NDEV:])), "subjects present in the 12,042 questions outside MMLU-2000")
        mac(f"{p}MMLUheldRetClLo", f"{clo:.2f}", "TEACHER-PCT cluster bootstrap over subjects, held-out 12,042")
        mac(f"{p}MMLUheldRetClHi", f"{chi:.2f}", "TEACHER-PCT")
        mac(f"{p}MMLUdev", f2(100 * s[:NDEV].mean()))
        mac(f"{p}MMLUdevRet", f2(100 * s[:NDEV].sum() / t[:NDEV].sum()), "TEACHER-PCT")
        rets = []
        for bi, b in enumerate(BLOCKS[:-1]):
            sl = slice(int(b), int(b) + 2000)
            rets.append(100 * s[sl].sum() / t[sl].sum())
            letter = "ABCDEFG"[bi]
            mac(f"{p}Blk{letter}", f2(100 * s[sl].mean()))
            mac(f"{p}Blk{letter}ret", f2(rets[-1]), "TEACHER-PCT")
        sl = slice(int(BLOCKS[-1]), NFULL)
        mac(f"{p}BlkH", f2(100 * s[sl].mean()), "last 42 questions")
        mac(f"{p}BlkHret", f2(100 * s[sl].sum() / t[sl].sum()), "TEACHER-PCT")
        mac(f"{p}BlkRetMin", f"{min(rets):.1f}", "TEACHER-PCT")
        mac(f"{p}BlkRetMax", f"{max(rets):.1f}", "TEACHER-PCT")
        mac(f"{p}MMLUac", f"{100 * (100 * sn / NFULL - 25) / (100 * tn / NFULL - 25):.1f}", "TEACHER-PCT above chance")
        # moral scenarios letter distribution (questions 8513-9407 of the test split)
        ms = subj == "moral_scenarios"
        mac(f"{p}MoralB", f"{100 * (d['choice'][ms] == 1).mean():.1f}")
        mac(f"{p}MoralOk", f"{100 * s[ms].mean():.1f}")
    for k, t_ in enumerate(BLOCKS[:-1]):
        sl = slice(int(t_), int(t_) + 2000)
        mac(f"teBlk{'ABCDEFG'[k]}", f2(100 * t[sl].mean()))
    mac("teBlkH", f2(100 * t[int(BLOCKS[-1]):].mean()), "last 42 questions")
    mac("blkHn", NFULL - int(BLOCKS[-1]))
    mac("teMoralB", f"{100 * (teacher['choice'][subj == 'moral_scenarios'] == 1).mean():.1f}")
    mac("teMoralOk", f"{100 * t[subj == 'moral_scenarios'].mean():.1f}")
    # paired model-vs-model, same engine
    for a, b, nm in (("XS", "S", "SvsXS"), ("S", "M", "MvsS"), ("XS", "M", "MvsXS")):
        w, l_, pv = mcnemar(full[a]["ok"], full[b]["ok"])
        mac(f"md{nm}" if nm.startswith("M") else f"sm{nm}", f"{w}/{l_}")
        mac((f"md{nm}" if nm.startswith("M") else f"sm{nm}") + "P", tex_p(pv))
        mac((f"md{nm}" if nm.startswith("M") else f"sm{nm}") + "Diff",
            f"{100 * (full[b]['ok'].sum() - full[a]['ok'].sum()) / NFULL:+.2f}")
    # engine drift: XS (launch, int8 off) vs C (earlier build, int8 on), same trunk tensors
    oldc = read_blocks([OLD / "C" / f"mmlu_full_{b}.log" for b in BLOCKS])
    if oldc is not None and np.array_equal(oldc["gold"], teacher["gold"]):
        w, l_, pv = mcnemar(oldc["ok"], full["XS"]["ok"])
        mac("xsOldEngine", f2(100 * oldc["ok"].mean()), "same trunk, earlier build, int8 on")
        mac("xsOldEngineWL", f"{w}/{l_}")
        mac("xsOldEngineP", tex_p(pv))
        mac("xsOldEngineSame", ints(int((oldc["choice"] == full["XS"]["choice"]).sum())))
    return {"teacher": teacher, "full": full, "same": same}


def baselines_section(mm: dict) -> None:
    t = mm["teacher"]["ok"]
    xs = mm["full"]["XS"]["ok"]
    for dname, (p, label, gg, cuda_dir, fallback) in BASELINES.items():
        d = read_blocks([FIN / dname / "mmlu_blocchi" / f"mmlu_{b}.log" for b in BLOCKS])
        same = d is not None
        src = None
        if not same and cuda_dir:
            d = read_blocks([RIV / cuda_dir / f"mmlu_{b}.log" for b in BLOCKS])
            src = "CUDA"
        mac(f"{p}Same", int(same), "BASELINE-SAME-ENGINE 1 = launch engine")
        mark = "" if same else (r"$^{c}$" if (src or fallback is not None) else "")
        mac(f"{p}Mark", mark, "BASELINE-SAME-ENGINE")
        sz = file_size(gg) or FILE_SIZES.get(dname)
        if sz is not None:
            FILE_SIZES[dname] = sz
            mac(f"{p}Bytes", ints(sz))
            mac(f"{p}GiB", f2(sz / GIB))
            mac(f"{p}Bpw", f"{8 * sz / PARAMS:.3f}")
        if d is not None:
            acc = 100 * d["ok"].mean()
            mac(f"{p}MMLU", f2(acc), "BASELINE-SAME-ENGINE" if same else "BASELINE-SAME-ENGINE cross-build CUDA")
            mac(f"{p}Ret", f2(100 * d["ok"].sum() / t.sum()), "TEACHER-PCT BASELINE-SAME-ENGINE")
            if same or True:
                w, l_, pv = mcnemar(d["ok"], xs)
                mac(f"{p}XSwl", f"{w}/{l_}", "XS wins/losses vs baseline; cross-build unless Same = 1")
                mac(f"{p}XSp", tex_p(pv))
                if same and p == "biqtwo":
                    sm_ = mm["full"]["S"]["ok"]
                    w2, l2, p2 = mcnemar(d["ok"], sm_)
                    mac("smVsIqtwoLE", f"{w2:,}/{l2:,}", "S wins/losses vs IQ2_XXS, launch engine")
                    mac("smVsIqtwoLEP", tex_p(p2))
                    mac("smVsIqtwoLEDiff", f"{100 * (sm_.sum() - d['ok'].sum()) / NFULL:+.2f}".replace("-", "$-$"))
                if same and p == "biqonem":
                    w2, l2, p2 = mcnemar(d["ok"], mm["full"]["S"]["ok"])
                    mac("smVsIqonemLE", f"{w2:,}/{l2:,}", "S wins/losses vs IQ1_M, launch engine")
                    mac("smVsIqonemLEP", tex_p(p2))
                if p == "biqtwo" and same:
                    lo, hi = boot_diff(d["ok"], xs, SEED + 50)
                    mac("biqtwoXSdiff", f"{100 * (xs.sum() - d['ok'].sum()) / NFULL:+.2f}".replace("-", "$-$"),
                        "XS minus IQ2_XXS, full MMLU, launch engine")
                    mac("biqtwoXSdiffLo", f"{lo:+.2f}".replace("-", "$-$"))
                    mac("biqtwoXSdiffHi", f"{hi:+.2f}".replace("-", "$-$"))
                    clo_, chi_ = cluster_boot_diff(d["ok"], xs, SUBJ_ALL, SEED + 52)
                    mac("biqtwoXSdiffClLo", f"{clo_:+.2f}".replace("-", "$-$"), "XS minus IQ2_XXS, by-subject bootstrap")
                    mac("biqtwoXSdiffClHi", f"{chi_:+.2f}".replace("-", "$-$"))
                    sm = mm["full"]["S"]["ok"]
                    w2, l2, p2 = mcnemar(d["ok"], sm)
                    lo2, hi2 = boot_diff(d["ok"], sm, SEED + 51)
                    mac("sIqDiff", f"{100 * (sm.sum() - d['ok'].sum()) / NFULL:+.2f}".replace("-", "$-$"),
                        "S minus IQ2_XXS, full MMLU, launch engine")
                    mac("sIqGap", f"{abs(100 * (sm.sum() - d['ok'].sum()) / NFULL):.2f}")
                    mac("sIqLo", f"{lo2:+.2f}".replace("-", "$-$"))
                    mac("sIqHi", f"{hi2:+.2f}".replace("-", "$-$"))
                    mac("sIqWL", f"{w2:,}/{l2:,}", "S wins/losses against IQ2_XXS")
                    mac("sIqP", tex_p(p2))
        elif fallback is not None:
            mac(f"{p}MMLU", f2(fallback), "BASELINE-SAME-ENGINE fallback: earlier CUDA build, value from run register")
            mac(f"{p}Ret", f2(100 * fallback / (100 * t.mean())), "TEACHER-PCT BASELINE-SAME-ENGINE")
            mac(f"{p}XSwl", "---")
            mac(f"{p}XSp", "---")
        # no log anywhere yet: MMLU/Ret/XSwl/XSp stay UNDEFINED, so the text can switch on \ifdefined\<p>MMLU
        if not same:
            WARN.append(f"baseline {dname}: same-engine run not complete, using "
                        f"{src or ('register value' if fallback is not None else 'nothing (macros undefined)')}")


def cuda_section(mm: dict) -> None:
    """CUDA, RTX 4060 Laptop 8 GB: MMLU-2000 paired with the Corsair, and full-test rival comparisons."""
    pre = {"XS": "xs", "S": "sm", "M": "md"}
    agree, gaps = [], []
    for m, f in (("M", STATO / "aragorn_mmlu" / "M.log"), ("S", STATO / "aragorn_mmlu" / "S.log"),
                 ("XS", STATO / "aragorn_mmlu_xs" / "XS.log")):
        d = read_mclp(f)
        if d is None:
            continue
        home = mm["full"][m]
        if not np.array_equal(d["gold"], home["gold"][:NDEV]):
            raise SystemExit(f"gold of CUDA {m} != home")
        w, l_, pv = mcnemar(home["ok"][:NDEV], d["ok"])
        p = pre[m]
        mac(f"{p}CudaDev", f2(100 * d["ok"].mean()), "CUDA RTX 4060, release HEAD, MMLU-2000")
        mac(f"{p}CudaWL", f"{w}/{l_}")
        mac(f"{p}CudaP", tex_p(pv))
        mac(f"{p}CudaSame", f"{100 * (d['choice'] == home['choice'][:NDEV]).mean():.1f}")
        agree.append(100 * (d["choice"] == home["choice"][:NDEV]).mean())
        gaps.append(abs(100 * (d["ok"].mean() - home["ok"][:NDEV].mean())))
    if agree:
        mac("cvAgreeLo", f"{min(agree):.1f}", "CUDA vs Vulkan, same file, MMLU-2000: per-question agreement range")
        mac("cvAgreeHi", f"{max(agree):.1f}")
        mac("cvGapMax", f2(max(gaps)), "largest CUDA-Vulkan score difference, same file, MMLU-2000")
        mac("cvChangeLo", f"{100 - max(agree):.1f}", "percentage of answers that change between CUDA and Vulkan")
        mac("cvChangeHi", f"{100 - min(agree):.1f}")
    # full test on CUDA (Aragorn, 3 Nov, pub/pr4-cuda): released trunks with the previous MTP head, and rivals
    rv = {}
    for key, dd in (("M", "Thor-T-M-finale-packed-1103"), ("S", "Thor-T-S-finale-packed-1103"),
                    ("Q4", "Ornith-1.5-35B-A3B-Q4_K_M"), ("IQ1M", "Ornith-1.5-35B-A3B-IQ1_M"),
                    ("MIXB", "Ornith-1.5-35B-A3B-IQ2XXS_mixB"), ("NAIVE", "Ornith-1.5-35B-A3B-TQ1_0-ingenuo")):
        d = read_blocks([RIV / dd / f"mmlu_{b}.log" for b in BLOCKS])
        if d is not None:
            rv[key] = d
    q2 = read_blocks([Q2K_CUDA / f"MMLUC-Q2K-{b}.log" for b in BLOCKS])
    if q2 is not None:
        rv["Q2"] = q2
        last = read_mclp(Q2K_CUDA / f"MMLUC-Q2K-{BLOCKS[-1]}.log")
        if last is not None and "CORSAIR" in (Q2K_CUDA / f"MMLUC-Q2K-{BLOCKS[-1]}.log").read_text(errors="replace"):
            mac("bqtwoApuN", len(last["gold"]), "last Q2_K block scored on the APU with Vulkan (log comment)")
    names = {"M": "mdCudaFull", "S": "smCudaFull", "Q4": "bqfourCuda", "IQ1M": "biqonemCuda", "MIXB": "bmixCuda",
             "NAIVE": "bnaiveCuda", "Q2": "bqtwoCuda"}
    t = mm["teacher"]["ok"]
    for k, d in rv.items():
        mac(names[k], f2(100 * d["ok"].mean()), "CUDA full test")
        mac(names[k] + "Ret", f2(100 * d["ok"].sum() / t.sum()), "TEACHER-PCT cross-build")
    for a, b, nm in (("Q4", "M", "mdVsQfour"), ("Q2", "M", "mdVsQtwo"), ("MIXB", "S", "smVsMix"),
                     ("IQ1M", "S", "smVsIqonem")):
        if a in rv and b in rv:
            w, l_, pv = mcnemar(rv[a]["ok"], rv[b]["ok"])
            mac(nm, f"{w}/{l_}", "CUDA full test")
            mac(nm + "P", tex_p(pv))
            mac(nm + "Diff", f"{100 * (rv[b]['ok'].sum() - rv[a]['ok'].sum()) / NFULL:+.2f}".replace("-", "$-$"))
            lo, hi = boot_diff(rv[a]["ok"], rv[b]["ok"], SEED + 40)
            mac(nm + "Lo", f"{lo:+.2f}".replace("-", "$-$"))
            mac(nm + "Hi", f"{hi:+.2f}".replace("-", "$-$"))


def suite_section(mm: dict) -> None:
    tasks_mc = {"arc_challenge": ("arcc", 25.0), "arc_easy": ("arce", 25.0), "boolq": ("boolq", 50.0),
                "piqa_full": ("piqa", 50.0), "openbookqa": ("obqa", 25.0), "truthfulqa_mc1": ("tqa", None),
                "mmlu_pro_mc": ("mmlupro", None)}
    pre = {"XS": "xs", "S": "sm", "M": "md"}

    exp_n = {"arc_challenge": 1172, "arc_easy": 2376, "boolq": 3270, "piqa_full": 1838, "openbookqa": 500,
             "truthfulqa_mc1": 817, "mmlu_pro_mc": 12032}

    def teacher_of(task: str, reader):
        new = reader(FIN / "maestro" / f"{task}.log")
        if new is not None and (task not in exp_n or len(new["ok"]) == exp_n[task]):
            return new, 1
        return reader(OLD / "maestro" / f"{task}.log"), 0

    todo = [(t, n, c, read_mclp) for t, (n, c) in tasks_mc.items()] + [
        ("hellaswag", "hs", 25.0, read_hellaswag), ("winogrande", "wino", 50.0, read_winogrande)]
    for task, nm, chance, reader in todo:
        tch, same = teacher_of(task, reader)
        mac(f"te{nm.capitalize()}same", same, f"teacher {task} on the launch engine")
        lab = TASK_LABEL.get(nm, nm)
        TE_PROV[lab] = same
        if same and tch is not None:
            old = reader(OLD / "maestro" / f"{task}.log")
            if old is not None and len(old["ok"]) == len(tch["ok"]):
                key = "choice" if "choice" in old and "choice" in tch else "ok"
                TE_DRIFT.append((lab, 100 * (tch["ok"].mean() - old["ok"].mean()),
                                 int((old[key] != tch[key]).sum()), len(tch["ok"]), key))
                if nm == "wino" and WINO_KEEP is not None and len(WINO_KEEP) == len(tch["ok"]):
                    kp = WINO_KEEP
                    mac("teDriftWinoX", f"{100 * (tch['ok'][kp].mean() - old['ok'][kp].mean()):+.2f}".replace("-", "$-$"),
                        "teacher Winogrande drift on the items outside the wrong-logits branch")
                    mac("teDriftWinoXChanged", ints(int((old[key][kp] != tch[key][kp]).sum())))
        if nm.capitalize() == "Hs":
            mac("teHellaSame", same, "alias of teHssame (teacher HellaSwag on the launch engine)")
        mac(f"te{nm.capitalize()}mark", "" if same else r"$^{\ddagger}$")
        if tch is None:
            WARN.append(f"no teacher log for {task}")
            continue
        if not same:
            WARN.append(f"teacher {task}: cross-build (esiti/maestro)")
        tacc = 100 * tch["ok"].mean()
        mac(f"te{nm.capitalize()}", f2(tacc))
        if "ok_sum" in tch:
            mac(f"te{nm.capitalize()}Sum", f2(100 * tch["ok_sum"].mean()))
        for k, m in enumerate(("XS", "S", "M")):
            d = reader(FIN / m / f"{task}.log")
            if d is None:
                continue
            p = pre[m]
            nmc = nm.capitalize()
            s = d["ok"]
            mac(f"{p}{nmc}", f2(100 * s.mean()))
            if len(s) != len(tch["ok"]):
                continue
            if "gold" in d and "gold" in tch and not np.array_equal(d["gold"], tch["gold"]):
                raise SystemExit(f"gold mismatch {m} {task}")
            mac(f"{p}{nmc}Ret", f2(100 * s.sum() / tch["ok"].sum()), "TEACHER-PCT")
            lo, hi = boot_ratio(tch["ok"], s, SEED + 20 + k)
            mac(f"{p}{nmc}RetLo", f"{lo:.1f}", "TEACHER-PCT")
            mac(f"{p}{nmc}RetHi", f"{hi:.1f}", "TEACHER-PCT")
            w, l_, pv = mcnemar(tch["ok"], s)
            mac(f"{p}{nmc}WL", f"{w}/{l_}")
            mac(f"{p}{nmc}P", tex_p(pv))
            if nm == "wino" and WINO_KEEP is not None and len(WINO_KEEP) == len(s):
                kp = WINO_KEEP
                mac(f"{p}WinoX", f2(100 * s[kp].mean()), "Winogrande without the items of the wrong-logits branch")
                mac(f"{p}WinoXRet", f2(100 * s[kp].sum() / tch["ok"][kp].sum()), "TEACHER-PCT")
                w2, l2, p2 = mcnemar(tch["ok"][kp], s[kp])
                mac(f"{p}WinoXWL", f"{w2}/{l2}")
                mac(f"{p}WinoXP", tex_p(p2))
                if k == 0:
                    mac("teWinoX", f2(100 * tch["ok"][kp].mean()))
            if chance is not None:
                mac(f"{p}{nmc}Ac", f"{100 * (100 * s.mean() - chance) / (tacc - chance):.1f}", "TEACHER-PCT")
            if "ok_sum" in d:
                ss = d["ok_sum"]
                mac(f"{p}{nmc}Sum", f2(100 * ss.mean()))
                mac(f"{p}{nmc}SumRet", f2(100 * ss.sum() / tch["ok_sum"].sum()), "TEACHER-PCT")
                w, l_, pv = mcnemar(tch["ok_sum"], ss)
                mac(f"{p}{nmc}SumWL", f"{w}/{l_}")
                mac(f"{p}{nmc}SumP", tex_p(pv))
                if chance is not None and "ok_sum" in tch:
                    tsum = 100 * tch["ok_sum"].mean()
                    mac(f"{p}{nmc}SumAc", f"{100 * (100 * ss.mean() - chance) / (tsum - chance):.1f}",
                        "TEACHER-PCT above chance, summed scoring (comparable to acc)")
                mac(f"{p}{nmc}Flip", ints(int((d["choice"] != d["choice_sum"]).sum())))
                mac(f"{p}{nmc}ZeroTok", d.get("zero_tok", 0), "items with an empty continuation (invalid per-token mean)")
                if d.get("zero_idx"):
                    keep = np.ones(len(s), bool)
                    keep[d["zero_idx"]] = False
                    mac(f"{p}{nmc}Excl", f2(100 * s[keep].mean()), "per-token accuracy without those items")
                    mac(f"{p}{nmc}ExclRet", f2(100 * s[keep].sum() / tch["ok"][keep].sum()), "TEACHER-PCT")
                    if p == "xs":
                        mac(f"{nmc.lower()}ExclN", ints(int(keep.sum())))
                        mac(f"te{nmc}Excl", f2(100 * tch["ok"][keep].mean()))
        if "zero_tok" in tch:
            mac(f"te{nm.capitalize()}ZeroTok", tch["zero_tok"])
        if "choice" in tch:
            mac(f"te{nm.capitalize()}Flip", ints(int((tch["choice"] != tch["choice_sum"]).sum())))
    # MMLU-Pro chance: 1/k mean over questions (up to 10 options)
    pro = read_mclp(FIN / "XS" / "mmlu_pro_mc.log")
    if pro is not None:
        ks = []
        for line in Path(FIN / "XS" / "mmlu_pro_mc.log").read_text(errors="replace").splitlines():
            if line.startswith("MCLP\t"):
                ks.append(int(line.split("\t")[4]))
        ch = 100 * float(np.mean([1 / k for k in ks]))
        mac("mmluproChance", f2(ch))
        tch, _ = teacher_of("mmlu_pro_mc", read_mclp)
        if tch is not None:
            ta = 100 * tch["ok"].mean()
            for m in ("XS", "S", "M"):
                d = read_mclp(FIN / m / "mmlu_pro_mc.log")
                if d is not None:
                    mac(f"{pre[m]}MmluproAc", f"{100 * (100 * d['ok'].mean() - ch) / (ta - ch):.1f}", "TEACHER-PCT")
    # engine drift of the teacher itself (same file, two builds)
    for task, nm in (("arc_easy", "Arce"), ("piqa_full", "Piqa")):
        a, b = read_mclp(OLD / "maestro" / f"{task}.log"), read_mclp(FIN / "maestro" / f"{task}.log")
        if a is not None and b is not None and len(a["gold"]) == len(b["gold"]):
            mac(f"teDrift{nm}Old", f2(100 * a["ok"].mean()))
            mac(f"teDrift{nm}New", f2(100 * b["ok"].mean()))
            mac(f"teDrift{nm}Changed", ints(int((a["choice"] != b["choice"]).sum())))
            mac(f"teDrift{nm}N", ints(len(a["gold"])))
            mac(f"teDrift{nm}Delta", f2(abs(100 * (b["ok"].mean() - a["ok"].mean()))), "teacher score drift, points")


N_DOCS = {"gsm8k": 1319, "ifeval": 541, "minerva_math500": 500}


def server_requests(log: Path, split_task: str = "") -> list[tuple[int, int]] | None:
    """(prompt tokens, generated tokens) per request of a llama-server log, paired by task id. If the log holds more
    requests than the task has documents (another job shared the port), keep the requests of this task: the n with the
    shortest prompts when the task's prompts are the short ones (IFEval, MATH-500), else the n longest; a warning says so."""
    if not log.exists():
        return None
    pr, gen = {}, {}
    for line in log.read_text(errors="replace").splitlines():
        m = re.search(r"task (\d+) \|\s+(prompt eval|eval) time =\s*[0-9.]+ ms /\s*(\d+) tokens", line)
        if m:
            (pr if m.group(2) == "prompt eval" else gen)[int(m.group(1))] = int(m.group(3))
    reqs = [(pr[k], gen[k]) for k in sorted(gen) if k in pr]
    task = log.stem.replace("server_", "")
    if split_task:
        # the GSM8K server of the teacher's launch-engine run also served IFEval, strictly after it: the first 1,319
        # requests by task id are GSM8K, the next 541 IFEval (prompt lengths confirm the boundary)
        ng, ni = N_DOCS["gsm8k"], N_DOCS["ifeval"]
        if len(reqs) != ng + ni:
            return None
        a_, b_ = reqs[:ng], reqs[ng:]
        if not np.median([x[0] for x in a_]) > 5 * np.median([x[0] for x in b_]):
            return None
        return a_ if split_task == "gsm8k" else b_
    n = N_DOCS.get(task)
    if n and len(reqs) > n:
        WARN.append(f"{log}: {len(reqs)} requests for {n} documents, another job shared the server; filtered by prompt length")
        reqs = sorted(reqs)[:n] if task in ("ifeval", "minerva_math500") else sorted(reqs)[-n:]
    return reqs


def cap_hits(log: Path, cap: int = 2048, split_task: str = "") -> int | None:
    """requests whose generation reached the token cap"""
    r = server_requests(log, split_task)
    return None if r is None else sum(1 for _, g in r if g >= cap)


def median_tokens(log: Path, split_task: str = "") -> str:
    """median generated tokens per request"""
    r = server_requests(log, split_task)
    return f"{int(np.median([g for _, g in r]))}" if r else "---"


def generative_section() -> None:
    pre = {"XS": "xs", "S": "sm", "M": "md"}
    tg_new = read_gen(FIN / "maestro", "gsm8k")
    tg = tg_new or read_gen(OLD / "maestro", "gsm8k")
    mac("teGsmSame", int(tg_new is not None), "1 = teacher GSM8K in the launch protocol (reasoning on)")
    TE_PROV["GSM8K"] = int(tg_new is not None)
    mac("teGsmMark", "" if tg_new is not None else r"$^{\S}$")
    if tg_new is None:
        WARN.append("teacher GSM8K/IFEval: earlier build; reasoning on (median generated tokens, see teGsmTok)")
    if tg is not None:
        mac("teGsmStrict", f2(100 * tg["strict-match:exact_match"].mean()))
        mac("teGsmFlex", f2(100 * tg["flexible-extract:exact_match"].mean()))
        mac("teGsmEmpty", tg["empty"])
    ti_new = read_gen(FIN / "maestro", "ifeval")
    ti = ti_new or read_gen(OLD / "maestro", "ifeval")
    mac("teIfevalSame", int(ti_new is not None))
    TE_PROV["IFEval"] = int(ti_new is not None)
    mac("teIfevalMark", "" if ti_new is not None else r"$^{\S}$")
    if ti is not None:
        mac("teIfeval", f2(100 * ti["none:prompt_level_strict_acc"].mean()))
        mac("teIfevalEmpty", ti["empty"])
    tm = read_gen(FIN / "maestro", "minerva_math500")
    TE_PROV["MATH-500"] = int(tm is not None)
    if tm is not None:
        mac("teMath", f2(100 * tm["none:math_verify"].mean()))
        mac("teMathEm", f2(100 * tm["none:exact_match"].mean()))
        mac("teMathEmpty", tm["empty"])
    for m in ("XS", "S", "M"):
        p = pre[m]
        g = read_gen(FIN / m, "gsm8k")
        if g is not None:
            st, fl = g["strict-match:exact_match"], g["flexible-extract:exact_match"]
            mac(f"{p}GsmStrict", f2(100 * st.mean()))
            mac(f"{p}GsmFlex", f2(100 * fl.mean()))
            mac(f"{p}GsmEmpty", g["empty"])
            mac(f"{p}GsmN", g["n"])
            if tg is not None:
                mac(f"{p}GsmStrictRet", f2(100 * st.sum() / tg["strict-match:exact_match"].sum()), "TEACHER-PCT")
                mac(f"{p}GsmFlexRet", f2(100 * fl.sum() / tg["flexible-extract:exact_match"].sum()), "TEACHER-PCT")
            res = g.get("results", {})
            if m == "XS" and res:
                mac("lmevalVersion", res.get("lm_eval_version", "?"))
                mac("transformersVersion", res.get("transformers_version", "?"))
                mac("lmevalFewshot", res.get("n-shot", {}).get("gsm8k", "?"))
                mac("lmevalMultiturn", "true" if res.get("fewshot_as_multiturn") else "false")
                cfg = res.get("config", {})
                mac("lmevalMaxGen", ints(cfg.get("gen_kwargs", {}).get("max_gen_toks", 0)))
                mac("lmevalConcurrent", cfg.get("model_args", {}).get("num_concurrent", "?"))
        i = read_gen(FIN / m, "ifeval")
        if i is not None:
            mac(f"{p}Ifeval", f2(100 * i["none:prompt_level_strict_acc"].mean()))
            mac(f"{p}IfevalLoose", f2(100 * i["none:prompt_level_loose_acc"].mean()))
            mac(f"{p}IfevalInst", f2(i["none:inst_level_strict_acc"]))
            mac(f"{p}IfevalEmpty", i["empty"])
            mac(f"{p}IfevalEmptyPct", f"{100 * i['empty'] / i['n']:.0f}")
        mt = read_gen(FIN / m, "minerva_math500")
        if mt is not None:
            mac(f"{p}Math", f2(100 * mt["none:math_verify"].mean()))
            mac(f"{p}MathEm", f2(100 * mt["none:exact_match"].mean()))
            mac(f"{p}MathEmpty", mt["empty"])
            mac(f"{p}MathEmptyPct", f"{100 * mt['empty'] / mt['n']:.0f}")
            if tm is not None:
                mac(f"{p}MathRet", f2(100 * mt["none:math_verify"].sum() / tm["none:math_verify"].sum()), "TEACHER-PCT")
    # run-to-run variability of served generation (same tensors, same engine, identical protocol)
    pairs = (("Rep", FIN / "S", FIN / "Svecchia", "gsm8k"),  # S released trunk vs same trunk, previous MTP head
             ("RepM", OLD / "A", OLD.parent / "esiti_rip_1108" / "Arip", "gsm8k"))  # A-POST T50 twice, earlier build
    for nm, a, b, task in pairs:
        ga, gb = read_gen(a, task), read_gen(b, task)
        if ga is None or gb is None:
            continue
        sa, sb = ga["strict-match:exact_match"], gb["strict-match:exact_match"]
        w, l_, pv = mcnemar(sa, sb)
        mac(f"gsm{nm}A", f2(100 * sa.mean()))
        mac(f"gsm{nm}B", f2(100 * sb.mean()))
        mac(f"gsm{nm}WL", f"{w}/{l_}")
        mac(f"gsm{nm}P", tex_p(pv))
        mac(f"gsm{nm}AFlex", f2(100 * ga["flexible-extract:exact_match"].mean()))
        mac(f"gsm{nm}BFlex", f2(100 * gb["flexible-extract:exact_match"].mean()))
    # the six GSM8K test runs of the same M file before the configuration was frozen (disclosed in the protocol)
    rip, sic = OLD.parent / "esiti_rip_1108", OLD.parent / "esiti_sicuro_1108"
    runs = (("One", FIN / "M" / "con_reasoning_preserve"), ("Two", sic / "M"), ("Three", sic / "Mvecchio"),
            ("Four", FIN / "M" / "senza_ragionamento"), ("Five", rip / "Mpub"), ("Six", rip / "Mthink"))
    runs = runs + (("Seven", OLD / "A"), ("Eight", rip / "Arip"))  # A after its last step, unpacked, earlier build
    for nm, d in runs:
        g = read_gen(d, "gsm8k")
        if g is None:
            continue
        mac(f"mrun{nm}Strict", f2(100 * g["strict-match:exact_match"].mean()), str(d))
        mac(f"mrun{nm}Flex", f2(100 * g["flexible-extract:exact_match"].mean()))
        mac(f"mrun{nm}Tok", median_tokens(d / "server_gsm8k.log"))
    # two different quantities: EMPTY = final answer empty after the reasoning is removed (from the samples);
    # CAP = requests whose generation reached the 2,048-token cap (from the server log)
    te_shared = FIN / "maestro" / "server_gsm8k.log"
    te_split = server_requests(te_shared, "gsm8k") is not None
    mac("teSplitDone", int(te_split), "1 = teacher GSM8K/IFEval counts from the shared launch-engine server log, split")
    for pm, d in (("xs", FIN / "XS"), ("sm", FIN / "S"), ("md", FIN / "M"), ("te", FIN / "maestro")):
        for task, nm, n in (("gsm8k", "Gsm", 1319), ("ifeval", "Ifeval", 541), ("minerva_math500", "Math", 500)):
            if pm == "te" and task != "minerva_math500":
                c = cap_hits(te_shared, split_task=task) if te_split else cap_hits(OLD / "maestro" / f"server_{task}.log")
            else:
                c = cap_hits(d / f"server_{task}.log")
            if c is None:
                continue
            mac(f"{pm}{nm}Cap", c, f"cap hits ({task})")
            mac(f"{pm}{nm}CapPct", f"{100 * c / n:.1f}")
    # median generated tokens per request: settles the reasoning mode of each run
    for task, nm in (("gsm8k", "teGsmTok"), ("ifeval", "teIfevalTok")):
        mac(nm, median_tokens(te_shared, task) if te_split else median_tokens(OLD / "maestro" / f"server_{task}.log"),
            "median generated tokens per request" + (", launch engine (shared log split)" if te_split else ", earlier build"))
    for nm, d, task in (("xsGsmTok", FIN / "XS", "gsm8k"), ("smGsmTok", FIN / "S", "gsm8k"),
                        ("mdGsmTok", FIN / "M", "gsm8k"), ("mdIfevalTok", FIN / "M", "ifeval"),
                        ("mdGsmOffTok", FIN / "M" / "senza_ragionamento", "gsm8k")):
        mac(nm, median_tokens(d / f"server_{task}.log"), "median generated tokens per request")
    if ti is not None:
        for m in ("XS", "S", "M"):
            i = read_gen(FIN / m, "ifeval")
            if i is not None:
                mac(f"{ {'XS': 'xs', 'S': 'sm', 'M': 'md'}[m] }IfevalRet".replace(" ", ""),
                    f2(100 * i["none:prompt_level_strict_acc"].sum() / ti["none:prompt_level_strict_acc"].sum()),
                    "TEACHER-PCT")
    # reasoning mode effect on the same M file
    off = read_gen(FIN / "M" / "senza_ragionamento", "gsm8k")
    on = read_gen(FIN / "M", "gsm8k")
    if off is not None and on is not None:
        w, l_, pv = mcnemar(off["strict-match:exact_match"], on["strict-match:exact_match"])
        mac("mdGsmOff", f2(100 * off["strict-match:exact_match"].mean()), "M, reasoning off, same engine")
        mac("mdGsmOffWL", f"{w}/{l_}")
        mac("mdGsmOffP", tex_p(pv))


def dev_curves() -> None:
    """POST step counts of S and M: MMLU-2000 curves (earlier build), every measured step, Holm over the family."""
    T = Path((GGUF + "/tony-tern"))
    for pre, base, steps, fmt in (("bpost", T / "B_POST_1101/base/mmlu_B_base.log", (50, 100, 150, 200, 250),
                                   "B_POST_1101/tappa_{0}/mmlu_BPOST{0}.log"),
                                  ("apost", T / "A_POST_1101/base/mmlu_A_base.log", (50, 100, 150),
                                   "A_POST_1101/tappa_{0}/mmlu_APOST{0}.log")):
        b = read_mclp(base)
        if b is None:
            continue
        mac(f"{pre}Base", f2(100 * b["ok"].mean()))
        rows = []
        for st in steps:
            d = read_mclp(T / fmt.format(st))
            if d is None or not np.array_equal(d["gold"], b["gold"]):
                continue
            w, l_, pv = mcnemar(b["ok"], d["ok"])
            rows.append((st, 100 * d["ok"].mean(), w, l_, pv))
        hp = holm([r[4] for r in rows])
        # selection inflation of the released step (best of the measured checkpoints), same model as for T400 (G18_R2 S2)
        oks = [read_mclp(T / fmt.format(st))["ok"] for st, *_ in rows]
        if len(oks) >= 2:
            dd = sorted(int((a_ != b_).sum()) for i_, a_ in enumerate(oks) for b_ in oks[i_ + 1:])
            sd_ = 100 * math.sqrt(float(np.median(dd))) / (math.sqrt(2) * NDEV)
            up_, lo_ = _inflation([r[1] for r in rows], sd_)
            mac(f"{pre}Infl", f"{up_:.1f}", "inflation of the best checkpoint if all true scores are equal, points")
            mac(f"{pre}InflLo", f"{lo_:.1f}", "with the true-score spread estimated from the observed scores")
            mac(f"{pre}DiscMed", f"{float(np.median(dd)):.0f}", "median discordant questions between its checkpoints")
        names = "ABCDE"
        mac(f"{pre}N", len(rows))
        for k, ((st, acc, w, l_, pv), h) in enumerate(zip(rows, hp)):
            mac(f"{pre}{names[k]}", f2(acc), f"step {st}")
            mac(f"{pre}{names[k]}WL", f"{w}/{l_}")
            mac(f"{pre}{names[k]}P", tex_p(pv))
            mac(f"{pre}{names[k]}Holm", tex_p(h))


RIVAL_DIRS = {"Q2_K": "rqtwo", "IQ2_XXS": "riqtwo", "Q4_K_M": "rqfour", "IQ1_M": "riqonem", "NAIVE_TQ1_0": "rnaive",
              "MILLIE_ING": "rmillie", "RADICE": "rroot"}
RIVAL_TASKS = {"hellaswag": "Hs", "winogrande": "Wino", "arc_challenge": "Arcc", "arc_easy": "Arce", "piqa_full": "Piqa",
               "boolq": "Boolq", "openbookqa": "Obqa", "truthfulqa_mc1": "Tqa", "mmlu_pro_mc": "Mmlupro"}


QUEUED_SUITE = {"Q2_K", "IQ2_XXS", "Q4_K_M", "MILLIE_ING", "RADICE"}       # likelihood suite queued on the launch engine
QUEUED_GSM = {"Q2_K", "IQ2_XXS", "IQ1_M", "MILLIE_ING", "RADICE"}          # GSM8K queued on the launch engine


def rivals_suite() -> None:
    """Standard quantizations on the likelihood tasks, launch engine; cells read 'run pending' until the logs land."""
    readers = {"hellaswag": read_hellaswag, "winogrande": read_winogrande}
    mac("runPending", r"\textit{pending}", "cell of a rival run queued, not yet complete")
    mac("notMeasured", r"n.m.", "cell of a run that is not planned")
    for dname, p in RIVAL_DIRS.items():
        done = 0
        for task, nm in RIVAL_TASKS.items():
            lp_ = FIN / dname / f"{task}.log"
            # a log written in the last THOR_PENDING_RECENT_S seconds is still pending for the bundle list
            # (elenca_bundle.py): the full run treats it the same way, so both runs see the same files
            recent_ = after_cutoff(lp_) or (not os.environ.get("THOR_LOG_CUTOFF") and not BUNDLE_MODE and lp_.exists()
                       and time.time() - lp_.stat().st_mtime < int(os.environ.get("THOR_PENDING_RECENT_S", "1800")))
            d = None if recent_ else readers.get(task, read_mclp)(lp_)
            ok = d is not None and (task in readers or len(d["ok"]) > 0)
            if ok and task not in readers:
                exp = {"arc_challenge": 1172, "arc_easy": 2376, "piqa_full": 1838, "boolq": 3270, "openbookqa": 500,
                       "truthfulqa_mc1": 817, "mmlu_pro_mc": 12032}[task]
                ok = len(d["ok"]) == exp
            if ok:
                done += 1
                mac(f"{p}{nm}", f2(100 * d["ok"].mean()), f"launch engine {dname} {task}")
                if "ok_sum" in d:
                    mac(f"{p}{nm}Sum", f2(100 * d["ok_sum"].mean()))
            else:
                cell = r"\runPending" if dname in QUEUED_SUITE else r"\notMeasured"
                mac(f"{p}{nm}", cell, f"PENDING-RUN {dname} {task}" if dname in QUEUED_SUITE else "not measured")
                if task not in readers:
                    mac(f"{p}{nm}Sum", cell)
        mac(f"{p}Done", done, f"tasks complete for {dname} (of {len(RIVAL_TASKS)})")
        g = read_gen(FIN / dname, "gsm8k")
        if g is not None and g.get("n") == 1319:
            mac(f"{p}GsmStrict", f2(100 * g["strict-match:exact_match"].mean()))
            mac(f"{p}GsmFlex", f2(100 * g["flexible-extract:exact_match"].mean()))
            mac(f"{p}GsmEmpty", g["empty"])
        else:
            for k in ("GsmStrict", "GsmFlex", "GsmEmpty"):
                mac(f"{p}{k}", r"\runPending" if dname in QUEUED_GSM else r"\notMeasured",
                    f"PENDING-RUN {dname} gsm8k" if dname in QUEUED_GSM else "not measured")
        if done < len(RIVAL_TASKS) and dname in QUEUED_SUITE:
            WARN.append(f"rival {dname}: {done}/{len(RIVAL_TASKS)} likelihood tasks on the launch engine")


def hf_etag(meta_dir: str, name: str) -> tuple[str, str] | None:
    """(revision, LFS sha256) recorded by huggingface_hub when the file was downloaded"""
    f = Path(meta_dir) / ".cache" / "huggingface" / "download" / f"{name}.metadata"
    if not f.exists():
        return None
    rev, etag = f.read_text().split()[:2]
    return rev, etag


def inputs_section(cache: dict, allow: bool) -> None:
    """Teacher, root and baselines: provenance and sha256 (computed, compared with the hub's LFS hash when known)."""
    src = GGUF + "/thor-src/Ornith-1.5-35B-A3B-bf16"
    for k, shard in (("One", "00001"), ("Two", "00002")):
        e = hf_etag(GGUF + "/thor-src", f"Ornith-1.5-35B-A3B-bf16/Ornith-1.5-35B-A3B-bf16-{shard}-of-00002.gguf")
        if e:
            mac("bfRev", e[0][:8]) if k == "One" else None
            mac(f"bfShard{k}Sha", e[1], "LFS sha256 of the bf16 shard (bartowski repo)")
    te = TEACHER_BYTES_FILE
    sha = sha256_file(te, cache, allow) or "unknown"
    decl = Path(te + ".sha256")
    if decl.exists() and sha != "unknown" and decl.read_text().split()[0] != sha:
        raise SystemExit("teacher sha256 differs from its .sha256 file")
    mac("teSha", sha, "teacher Q8_0, quantized by us from the bf16 shards")
    root = GGUF + "/tony-tern/R2B3m/Thor-T-R2B3m.gguf"
    if os.path.exists(root):
        rs = sha256_file(root, cache, allow) or "unknown"
        if rs not in ("unknown", "56cb5bcdd9813a1015a7cad5364b5a80226f990fb8bd561b7cae4727d70efc43"):
            raise SystemExit("root sha256 differs from the recipe")
        mac("rootSha", rs)
        mac("rootBytes", ints(file_size(root)))
        mac("rootGiB", f2(file_size(root) / GIB))
        mac("rootBpw", f"{8 * file_size(root) / PARAMS:.3f}")
    for p, name, d in (("bqtwo", "Ornith-1.5-35B-A3B-Q2_K.gguf", GGUF + "/thor-rivale"),
                       ("bqfour", "Ornith-1.5-35B-A3B-Q4_K_M.gguf", GGUF + "/thor-rivale"),
                       ("biqtwo", "Ornith-1.5-35B-A3B-IQ2_XXS.gguf", GGUF + "/thor-rivale"),
                       ("bimat", "Ornith-1.5-35B-A3B-imatrix.gguf", GGUF + "/thor-rivale"),
                       ("biqonem", "Ornith-1.5-35B-A3B-IQ1_M.gguf", GGUF + "/tony-tern/RIVALI/dell"),
                       ("bmix", "Ornith-1.5-35B-A3B-IQ2XXS_mixB.gguf", GGUF + "/tony-tern/RIVALI/dell")):
        f = f"{d}/{name}"
        if not os.path.exists(f):
            continue
        sh = sha256_file(f, cache, allow) or "unknown"
        e = hf_etag(d, name)
        if e and sh != "unknown" and e[1] != sh:
            raise SystemExit(f"{name}: local sha256 != hub LFS sha256")
        mac(f"{p}Sha", sh, "downloaded (hub LFS sha256 matches)" if e else "built by us")
        mac(f"{p}ShaShort", sh[:12])
        if e:
            mac(f"{p}Rev", e[0][:8])
        if p == "bmix":
            mac("bmixBytes", ints(file_size(f)))
            mac("bmixGiB", f2(file_size(f) / GIB))
            mac("bmixBpw", f"{8 * file_size(f) / PARAMS:.3f}")


def root_section(mm: dict) -> None:
    """the frozen root R2B3m on the full test (engine thor-c0t, an earlier build: cross-build against XS).
    \\rootMMLU and its companions stay UNDEFINED until the launch-bench run lands; \\rootCuda is the earlier run."""
    mac("rootMark", "", "the packed root runs on the launch engine")
    mac("rootCuda", "74.69", "full test, earlier build on another machine, 1 Oct (run register row 591, raw log not in "
        "the bundle)")
    v = FIN / "RADICE" / "velocita.txt"
    if v.exists():
        b = _bench_md(v)
        r = b.get(None) or (b[min(b)] if b else {})
        if "tg128" in r:
            mac("rootVkTg", f2(r["tg128"][0]), "packed root, launch engine")
        if "pp512" in r:
            mac("rootVkPp", f2(r["pp512"][0]))
    if not any(n == "rootVkTg" for n, _, _ in MACROS):
        mac("rootVkTg", r"\textit{running}", "PENDING-RUN")
        mac("rootVkPp", r"\textit{running}", "PENDING-RUN")
    d = read_blocks([FIN / "RADICE" / "mmlu_blocchi" / f"mmlu_{b}.log" for b in BLOCKS])
    if d is None or not np.array_equal(d["gold"], mm["teacher"]["gold"]):
        # until then: the root's earlier CUDA logs of the 12,042 questions outside MMLU-2000 (cross-engine)
        parts = [read_mclp(Q2K_CUDA / f"MMLUC-R2B3m-{b}.log") for b in BLOCKS[1:]]
        if all(p_ is not None and len(p_["gold"]) in (NDEV, NFULL - 7 * NDEV) for p_ in parts):
            ch = concat(parts)
            if np.array_equal(ch["gold"], mm["teacher"]["gold"][NDEV:]):
                xs_h = mm["full"]["XS"]["ok"][NDEV:]
                w, l_, pv = mcnemar(ch["ok"], xs_h)
                mac("rootXSheldDiff", f"{100 * (xs_h.sum() - ch['ok'].sum()) / len(xs_h):+.2f}".replace("-", "$-$"),
                    "XS (launch engine) minus root (earlier CUDA logs), 12,042 questions: cross-engine")
                mac("rootXSheldWL", f"{w:,}/{l_:,}")
                mac("rootXSheldP", tex_p(pv))
                mac("rootXSheldGap", f"{abs(100 * (xs_h.sum() - ch['ok'].sum()) / len(xs_h)):.2f}")
                mac("rootHeld", f2(100 * ch["ok"].mean()), "root, 12,042 questions, earlier CUDA logs")
                mac("rootXSheldCross", 1)
        mac("rootDone", 0, "PENDING-RUN packed root on the launch engine")
        for k in ("MMLU", "Ret", "XSwl", "XSp"):
            mac(f"root{k}", r"\textit{running}", "PENDING-RUN")
        WARN.append("root full MMLU not complete (esiti_finale_1107/RADICE/mmlu_blocchi)")
        return
    mac("rootDone", 1, "packed root, full MMLU on the launch engine")
    xs_h, r_h = mm["full"]["XS"]["ok"][NDEV:], d["ok"][NDEV:]
    w, l_, pv = mcnemar(r_h, xs_h)
    mac("rootXSheldDiff", f"{100 * (xs_h.sum() - r_h.sum()) / len(xs_h):+.2f}".replace("-", "$-$"),
        "XS minus root, 12,042 questions outside MMLU-2000, same engine")
    mac("rootXSheldWL", f"{w:,}/{l_:,}")
    mac("rootXSheldP", tex_p(pv))
    mac("rootXSheldCross", 0)
    mac("rootXSheldGap", f"{abs(100 * (xs_h.sum() - r_h.sum()) / len(xs_h)):.2f}")
    mac("rootHeld", f2(100 * r_h.mean()), "packed root, 12,042 questions, launch engine")
    mac("rootMMLU", f2(100 * d["ok"].mean()), "packed root, full MMLU, launch engine")
    mac("rootRet", f2(100 * d["ok"].sum() / mm["teacher"]["ok"].sum()), "TEACHER-PCT")
    w, l_, pv = mcnemar(d["ok"], mm["full"]["XS"]["ok"])
    mac("rootXSdiff", f"{100 * (mm['full']['XS']['ok'].sum() - d['ok'].sum()) / NFULL:+.2f}".replace("-", "$-$"),
        "XS minus packed root, full MMLU, same engine")
    mac("rootXSwl", f"{w}/{l_}", "XS wins/losses against the root, same engine")
    mac("rootXSp", tex_p(pv))
    mac("rootDev", f2(100 * d["ok"][:NDEV].mean()), "packed root, MMLU-2000, launch engine")
    xs_d, r_d = mm["full"]["XS"]["ok"][:NDEV], d["ok"][:NDEV]
    w, l_, pv = mcnemar(r_d, xs_d)
    mac("rootXSdevDiff", f"{100 * (xs_d.sum() - r_d.sum()) / NDEV:+.2f}".replace("-", "$-$"),
        "XS minus root on MMLU-2000 (the subset XS was selected on), same engine")
    mac("rootXSdevWL", f"{w}/{l_}")
    mac("rootXSdevP", tex_p(pv))
    # is the dev-vs-outside difference of the XS-root gap itself significant? discordant counts, Fisher exact
    from scipy.stats import fisher_exact  # noqa: PLC0415
    wh, lh, _ = mcnemar(d["ok"][NDEV:], mm["full"]["XS"]["ok"][NDEV:])
    mac("rootXSdevVsHeldP", tex_p(float(fisher_exact([[w, l_], [wh, lh]])[1])),
        "Fisher exact: XS-root discordance on MMLU-2000 vs on the other 12,042 (subject mix differs)")


def ctrl_post(mm: dict) -> None:
    """control for B1: C0B + only the POST step of C (50 steps, no checkpoint selection), run on thor-c0t, the engine of
    C, and compared with C on that engine (esiti/C). Macros stay undefined until the eight blocks are complete."""
    d0 = Path(os.environ.get("THOR_CTRL_POST_DIR", GGUF + "/tony-tern/CONTROLLO_SOLO_POST_C0B_1109/completo"))
    # MMLU-2000 of the control (step 50, no checkpoint selection) against C0B on the same engine (thor-c0t) and
    # against C (G19_R5 S3); register row 2026-11-10T07:59 CONTROLLO-SOLO-POST
    dc = d0.parent
    x_ = read_mclp(dc / "tappa_50" / "mmlu_C0BPOST50.log")
    z_ = read_mclp(dc / "c0b_completo" / "mmlu_00000.log")
    c_ = read_mclp(Path(DEV_CHAIN["C"][0]))
    okd = all(v is not None and len(v["gold"]) == NDEV for v in (x_, z_, c_)) and \
        np.array_equal(x_["gold"], z_["gold"]) and np.array_equal(x_["gold"], c_["gold"])
    mac("ctrlPostDevDone", int(okd), "1 = MMLU-2000 of the control C0B + only C's last step is complete")
    if okd:
        mac("ctrlPostDevMMLU", f2(100 * x_["ok"].mean()), "control, MMLU-2000, step 50 (no selection)")
        mac("ctrlPostDevBase", f2(100 * z_["ok"].mean()), "C0B on the same engine, MMLU-2000")
        w, l_, pv = mcnemar(z_["ok"], x_["ok"])
        mac("ctrlPostDevWL", f"{w}/{l_}", "control wins/losses against C0B")
        mac("ctrlPostDevP", tex_p(pv))
        mac("ctrlPostDevGain", f"{100 * (x_['ok'].mean() - z_['ok'].mean()):+.2f}", "control minus C0B, points")
        w, l_, pv = mcnemar(x_["ok"], c_["ok"])
        mac("ctrlPostDevVsCWL", f"{w}/{l_}", "C wins/losses against the control")
        mac("ctrlPostDevVsCP", tex_p(pv))
    parts = []
    for b in BLOCKS:
        cand = sorted(d0.glob(f"**/*mmlu*{b}*.log")) if d0.exists() else []
        parts.append(cand[0] if cand else d0 / f"mmlu_{b}.log")
    full = read_blocks(parts)
    c = read_blocks([OLD / "C" / f"mmlu_full_{b}.log" for b in BLOCKS])
    if full is not None and c is not None and np.array_equal(full["gold"], c["gold"]):
        w, l_, pv = mcnemar(full["ok"], c["ok"])
        mac("ctrlPostMMLU", f2(100 * full["ok"].mean()), "C0B + POST only, full test, thor-c0t")
        mac("ctrlPostC", f2(100 * c["ok"].mean()), "C on thor-c0t, full test")
        mac("ctrlPostVsCwl", f"{w}/{l_}", "C wins/losses against the control, same engine")
        mac("ctrlPostVsCp", tex_p(pv))
        mac("ctrlPostDev", f2(100 * full["ok"][:NDEV].mean()))
        mac("ctrlPostDone", 1, "1 = full test of the control complete (elenca_bundle ships its logs)")
    else:
        mac("ctrlPostDone", 0, "1 = full test of the control complete")
        WARN.append(f"control C0B + POST only not complete ({d0})")


OC = GGUF + "/tony-tern/OBIETTIVO_C"
DEV_CHAIN = {  # macro key: (MMLU-2000 log, previous key); development history, earlier builds
    "Root": (GGUF + "/tony-tern/G64/grezzi/mmlu_R2B3m.log", None),
    "Czb": (OC + "/TRIO/mmlu_C0B.log", "Root"),
    "Cc": (GGUF + "/tony-tern/E2E_C2/mmlu_C-bil1jarq.log", "Czb"),
    "Ptwo": (OC + "/PTQ2/mmlu_C-p_bil1jarqdrq.log", "Cc"),
    "Stwo": (OC + "/S23_SEQUENZIALE_CORRETTO_1014/misure/mmlu_C-S23-s2.log", "Ptwo"),
    "Sfourb": (OC + "/OBQ_FIBRATO_S4_1014/mmlu_info_OBQ.log", "Stwo"),
    "Jt": (OC + "/CARDAN_CONGIUNTO_1018/tappa_550/mmlu_CONGIUNTO.log", "Sfourb"),
    "Sseven": (OC + "/S7_CONGIUNTO_T550_1020/Thor-T-C-S7-T550-g10.mmlu.log", "Jt"),
    "Tfour": (OC + "/CARDAN_CONGIUNTO_S7T550_1020/tappa_400/mmlu_CONGIUNTO.log", "Sseven"),
    "C": (OC + "/CARDAN_T400POST_1027/tappa_50/mmlu_T400POST50.log", "Tfour"),
    "Ssix": (OC + "/DENSI_CARDAN_OBQ_1016/mmlu_DC.log", "Sfourb"),
    "Nthree": (OC + "/S5_CARDAN_DC600_1017/kd/mmlu_CARDAN.log", "Ssix"),
    "Dtwo": (OC + "/DENSI2_SU_N3_1017/mmlu_DC.log", "Nthree"),
}
RIPRO = OC + "/RIPRO_ORIGINAL_1029/t400line"
DEV_REPRO = {  # key: (original log, reproduced log)
    "J": (DEV_CHAIN["Jt"][0], RIPRO + "/CARDAN_CONGIUNTO_T550/tappa_550/mmlu_CONGIUNTO.log"),
    "S": (DEV_CHAIN["Sseven"][0], RIPRO + "/S7_CONGIUNTO_T550/Thor-T-C-S7-T550-ORIGINAL-g10.mmlu.log"),
    "T": (DEV_CHAIN["Tfour"][0], RIPRO + "/CARDAN_CONGIUNTO_S7T550/tappa_400/mmlu_CONGIUNTO.log"),
    "C": (DEV_CHAIN["C"][0], RIPRO + "/CARDAN_T400POST/tappa_50/mmlu_T400POST50.log"),
}


def dev_chain() -> None:
    """chain of C and its internal re-run on MMLU-2000 (earlier builds), from the raw MCLP logs. C and its reproduction
    were first scored on a shuffled copy and remapped; when the stored-order re-scores land
    (esiti_finale_1107/C_ordine_memorizzato/mmlu_{C,CRIPRO}.log) they replace them and \\cOrderStored becomes 1."""
    so = FIN / "C_ordine_memorizzato"
    c_s, r_s = read_mclp(so / "mmlu_C.log"), read_mclp(so / "mmlu_CRIPRO.log")
    stored = c_s is not None and r_s is not None and len(c_s["gold"]) == NDEV and len(r_s["gold"]) == NDEV
    if stored:
        DEV_CHAIN["C"] = (str(so / "mmlu_C.log"), "Tfour")
        DEV_REPRO["C"] = (str(so / "mmlu_C.log"), str(so / "mmlu_CRIPRO.log"))
    mac("cOrderStored", int(stored), "1 = C and reproduced C re-scored in stored order")
    logs = {k: read_mclp(Path(v[0])) for k, v in DEV_CHAIN.items()}
    for k, (_, prev) in DEV_CHAIN.items():
        d = logs[k]
        if d is None:
            WARN.append(f"chain log missing: {k}")
            continue
        mac(f"chain{k}", f2(100 * d["ok"].mean()), "MMLU-2000, development history")
        if prev and logs.get(prev) is not None:
            w, l_, pv = mcnemar(logs[prev]["ok"], d["ok"])
            mac(f"chain{k}WL", f"{w}/{l_}")
            mac(f"chain{k}P", tex_p(pv))
    if logs.get("C") is not None and logs.get("Czb") is not None:
        w, l_, pv = mcnemar(logs["Czb"]["ok"], logs["C"]["ok"])
        mac("chainCvsCzbWL", f"{w}/{l_}")
        mac("chainCvsCzbP", tex_p(pv))
    for k, (a, b) in DEV_REPRO.items():
        x, y = read_mclp(Path(a)), read_mclp(Path(b))
        if x is None or y is None:
            WARN.append(f"repro log missing: {k}")
            continue
        w, l_, pv = mcnemar(x["ok"], y["ok"])
        mac(f"rep{k}Orig", f2(100 * x["ok"].mean()))
        mac(f"rep{k}Repro", f2(100 * y["ok"].mean()))
        mac(f"rep{k}WL", f"{w}/{l_}", "reproduced wins/losses against the original")
        mac(f"rep{k}P", tex_p(pv))
        mac(f"rep{k}Same", ints(int((x["choice"] == y["choice"]).sum())))
    for k in ("T", "C"):
        x, y = read_mclp(Path(DEV_REPRO[k][0])), read_mclp(Path(DEV_REPRO[k][1]))
        if x is not None and y is not None:
            w, l_ = mcnemar(x["ok"], y["ok"])[:2]
            n = len(x["ok"])
            dlt = 100 * (w - l_) / n  # reproduced minus original (mcnemar counts wins of the second)
            se = 100 * math.sqrt(w + l_ - (w - l_) ** 2 / n) / n
            mac(f"rep{k}WaldLo", f"{dlt - 1.96 * se:+.2f}".replace("-", "$-$"), "Wald 95 % CI, reproduced minus original")
            mac(f"rep{k}WaldHi", f"{dlt + 1.96 * se:+.2f}".replace("-", "$-$"))
    t, c = read_mclp(Path(DEV_REPRO["T"][1])), read_mclp(Path(DEV_REPRO["C"][1]))
    if t is not None and c is not None:
        w, l_, pv = mcnemar(t["ok"], c["ok"])
        mac("repPostWL", f"{w}/{l_}", "reproduced C against reproduced T400")
        mac("repPostP", tex_p(pv))


def _prior_offsets(lp: np.ndarray, target: np.ndarray, iters: int = 500) -> np.ndarray:
    """three free offsets (b[0] = 0) that move the model's mean letter distribution onto the target, no labels used"""
    b = np.zeros(4)
    for _ in range(iters):
        z = lp + b
        q = np.exp(z - z.max(1, keepdims=True))
        q /= q.sum(1, keepdims=True)
        m = q.mean(0)
        b += np.log(target / m)
        b -= b[0]
    return b


def _oracle_offsets(lp: np.ndarray, gold: np.ndarray, starts: list, rounds: int = 6) -> np.ndarray:
    """three offsets (b[0] = 0) fitted to the gold labels of the same test questions, maximizing accuracy in sample: an
    in-sample fitted shift, found by coordinate search on a 0.005 grid over [-6, 6] (not exhaustive, not a bound)."""
    grid = np.arange(-6.0, 6.0 + 1e-9, 0.005)
    best_b, best = None, -1
    for b0 in starts:
        b = np.array(b0, dtype=float)
        b -= b[0]
        for _ in range(rounds):
            for j in (1, 2, 3):
                z = lp + b
                other = np.delete(z, j, axis=1)
                mo = other.max(1)
                arg_o = np.delete(np.arange(4), j)[other.argmax(1)]
                # option j wins iff lp_j + v > mo (ties go to the lower index, as argmax does)
                win = (lp[:, j][:, None] + grid[None, :]) > mo[:, None]
                acc = np.where(win, (gold == j)[:, None], (arg_o == gold)[:, None]).sum(0)
                b[j] = grid[int(acc.argmax())]
        a = int((np.argmax(lp + b, 1) == gold).sum())
        if a > best:
            best, best_b = a, b.copy()
    return best_b


def prior_control(subj: np.ndarray, mm: dict) -> None:
    """CPU control for the letter-prior reading of the last step: apply the label-free three-offset correction of
    tab:prior to T400's full-test log-probabilities (earlier build) and count what it recovers of C's gain."""
    cert = OC + "/CERT_MMLU_COMPLETO"
    t400 = read_blocks([Path(DEV_CHAIN["Tfour"][0])] + [Path(f"{cert}/mmlu_T400_{b}.log") for b in BLOCKS[1:]])
    cfull = read_blocks([Path(DEV_CHAIN["C"][0])] + [Path(f"{cert}/mmlu_T400POST-T50_{b}.log") for b in BLOCKS[1:]])
    te = mm["teacher"]
    if t400 is None or cfull is None or t400.get("lp") is None or te.get("lp") is None:
        WARN.append("prior control: logs or per-option log-probabilities missing")
        return
    def mean_dist(lp):
        q = np.exp(lp - lp.max(1, keepdims=True))
        return (q / q.sum(1, keepdims=True)).mean(0)
    b = _prior_offsets(t400["lp"], mean_dist(te["lp"]))
    corr = (np.argmax(t400["lp"] + b, 1) == t400["gold"]).astype(np.int8)
    base, post = t400["ok"], cfull["ok"]
    mac("priorTfour", f2(100 * base.mean()), "T400 full test, earlier build")
    mac("priorTfourCorr", f2(100 * corr.mean()), "T400 + label-free three-offset prior correction")
    mac("priorC", f2(100 * post.mean()), "C full test, earlier build")
    gain = int(post.sum() - base.sum())
    rec = int(corr.sum() - base.sum())
    mac("priorGainNet", ints(gain), "net questions gained by the last step")
    w0, l0, p0 = mcnemar(base, post)
    mac("priorGainWL", f"{w0}/{l0}", "C against T400, full test, earlier build")
    mac("priorGainP", tex_p(p0))
    hh = slice(NDEV, None)
    w0, l0, p0 = mcnemar(base[hh], post[hh])
    mac("priorHeldWL", f"{w0}/{l0}", "C against T400, held-out 12,042")
    mac("priorHeldP", tex_p(p0))
    mac("priorRecNet", ints(rec), "net questions recovered by the prior correction")
    w, l_, pv = mcnemar(corr, post)
    mac("priorCvsCorrWL", f"{w}/{l_}", "C against corrected T400")
    mac("priorCvsCorrP", tex_p(pv))
    ms = subj == "moral_scenarios"
    mac("priorMoralTfour", f"{100 * base[ms].mean():.1f}")
    mac("priorMoralCorr", f"{100 * corr[ms].mean():.1f}")
    mac("priorMoralC", f"{100 * post[ms].mean():.1f}")
    nm = ~ms
    mac("priorNoMoralGain", ints(int(post[nm].sum() - base[nm].sum())))
    mac("priorNoMoralRec", ints(int(corr[nm].sum() - base[nm].sum())))
    # in-sample fitted shifts: offsets fitted to the gold labels of the same questions. Every fit (T400 and C) starts
    # from the same set: zero, the teacher-matched offsets of T400 and the teacher-matched offsets of C (G10_R6 S1)
    starts = [np.zeros(4), b]
    if cfull.get("lp") is not None:
        starts.append(_prior_offsets(cfull["lp"], mean_dist(te["lp"])))
    bo = _oracle_offsets(t400["lp"], t400["gold"], starts)
    oc = (np.argmax(t400["lp"] + bo, 1) == t400["gold"]).astype(np.int8)
    mac("priorOracleTfour", f2(100 * oc.mean()), "T400 + oracle three-offset shift fitted on its own gold (in-sample)")
    mac("priorOracleRecNet", ints(int(oc.sum() - base.sum())), "net questions recovered by the oracle shift")
    mac("priorOracleNoMoralRec", f"{int(oc[nm].sum() - base[nm].sum()):+d}".replace("-", "$-$"))
    mac("priorOracleMoralRec", f"{int(oc[ms].sum() - base[ms].sum()):+d}".replace("-", "$-$"))
    w, l_, pv = mcnemar(oc, post)
    mac("priorCvsOracleWL", f"{w}/{l_}", "C against oracle-corrected T400")
    mac("priorCvsOracleP", tex_p(pv))
    h = slice(NDEV, None)
    bh = _oracle_offsets(t400["lp"][h], t400["gold"][h], starts)
    oh = (np.argmax(t400["lp"][h] + bh, 1) == t400["gold"][h]).astype(np.int8)
    mac("priorOracleHeldRec", ints(int(oh.sum() - base[h].sum())), "oracle fitted on the 12,042 held-out questions")
    mac("priorHeldGain", ints(int(post[h].sum() - base[h].sum())))
    mac("priorOracleHeldPct", f"{100 * (oh.sum() - base[h].sum()) / (post[h].sum() - base[h].sum()):.0f}",
        "held-out fit, % of the held-out gain")
    mac("priorMoralNet", ints(int(post[ms].sum() - base[ms].sum())), "net questions of the last step in moral scenarios")
    nmh = nm[NDEV:]
    mac("priorOracleHeldNoMoralRec", f"{int(oh[nmh].sum() - base[h][nmh].sum()):+d}".replace("-", "$-$"),
        "held-out fit, net outside moral scenarios")
    # fit restricted to the questions outside moral scenarios (full test), and the same fit on C as a noise floor
    bn = _oracle_offsets(t400["lp"][nm], t400["gold"][nm], starts)
    on = (np.argmax(t400["lp"][nm] + bn, 1) == t400["gold"][nm])
    mac("priorNoMoralFitRec", f"{int(on.sum() - base[nm].sum()):+d}".replace("-", "$-$"),
        "T400, shift fitted on the non-moral questions only, in sample")
    if cfull.get("lp") is not None:
        bc = _oracle_offsets(cfull["lp"][nm], cfull["gold"][nm], starts)
        oc_ = (np.argmax(cfull["lp"][nm] + bc, 1) == cfull["gold"][nm])
        mac("priorNoMoralFitFloor", f"{int(oc_.sum() - post[nm].sum()):+d}".replace("-", "$-$"),
            "same fit, same starts, on C (outside moral scenarios), in sample")
        # symmetric control (G10_R2 m3): C with its own fitted shift (full test) against the shifted T400
        bcf = _oracle_offsets(cfull["lp"], cfull["gold"], starts)
        ocf = (np.argmax(cfull["lp"] + bcf, 1) == cfull["gold"]).astype(np.int8)
        mac("priorCshift", f2(100 * ocf.mean()), "C with its own in-sample fitted shift, full test")
        w, l_, pv = mcnemar(oc, ocf)
        mac("priorCshiftVsTWL", f"{w}/{l_}", "shifted C against shifted T400")
        mac("priorCshiftVsTP", tex_p(pv))


def fold_holm() -> None:
    """Holm over the seven folded-against-host comparisons of tab:fold-acc (T300 included). A and the iterated fold have
    no log in our tree: their counts (44/26, 17/32) come from the run register and enter by their exact p."""
    lg = {k: read_mclp(Path(DEV_CHAIN[k][0])) for k in ("Sfourb", "Ssix", "Nthree", "Dtwo", "Sseven", "Tfour")}
    t300 = read_mclp(Path(OC + "/CARDAN_CONGIUNTO_S7T550_1020/tappa_300/mmlu_CONGIUNTO.log"))
    if any(v is None for v in lg.values()) or t300 is None:
        WARN.append("fold Holm: a log is missing")
        return
    fam = {"A": (44, 26), "Ssix": mcnemar(lg["Sfourb"]["ok"], lg["Ssix"]["ok"])[:2],
           "Nthree": mcnemar(lg["Ssix"]["ok"], lg["Nthree"]["ok"])[:2],
           "Dtwo": mcnemar(lg["Nthree"]["ok"], lg["Dtwo"]["ok"])[:2],
           "Tthree": mcnemar(lg["Sseven"]["ok"], t300["ok"])[:2],
           "Tfour": mcnemar(lg["Sseven"]["ok"], lg["Tfour"]["ok"])[:2], "Iter": (17, 32)}
    ps = {k: p_exact(w, l_) for k, (w, l_) in fam.items()}
    w, l_ = fam["Tthree"]
    mac("foldTthreeWL", f"{w}/{l_}", "T300 folded against its host S7")
    mac("foldTthreeP", tex_p(ps["Tthree"]))
    for k, h in zip(ps, holm(list(ps.values()))):
        mac(f"foldHolm{k}", tex_p(h), "Holm over the seven fold comparisons")


def fucina_flag() -> None:
    # REPLAY_STATUS lives at the dataset root (next to SHA256SUMS); in our tree, next to this script
    root = HERE.parent if (HERE.parent / "SHA256SUMS").exists() else HERE
    f = Path(os.environ.get("THOR_REPLAY_STATUS", str(root / "REPLAY_STATUS")))
    ok_line = None
    if f.exists():
        for ln in f.read_text(errors="replace").splitlines():
            m_ = re.fullmatch(r"REPLAY VERIFIED (\d{4}-\d{2}-\d{2}(?:T[0-9:]+)?) ([0-9a-f]{7,40})", ln.strip())
            if m_:
                ok_line = m_
    sp = HERE / "fucina_split.tsv"
    pub = ""
    if sp.exists():
        pub = dict(ln.split("\t", 1) for ln in sp.read_text().splitlines() if "\t" in ln).get("public", "")
    if ok_line and pub and not pub.startswith(ok_line.group(2)[:7]):
        WARN.append(f"REPLAY_STATUS names commit {ok_line.group(2)[:9]}, not the cited forge commit {pub[:7]}: ignored")
        ok_line = None
    if ok_line:
        mac("fucinaReplayVerified", "1", f"{f.name}: REPLAY VERIFIED {ok_line.group(1)} {ok_line.group(2)}")
        mac("fucinaReplayDate", ok_line.group(1))
        mac("fucinaReplayCommit", ok_line.group(2)[:9])
    else:
        mac("fucinaReplayVerified", "0", "REPLAY_STATUS absent or without the exact line REPLAY VERIFIED <date> <commit>")


def bytes_by_part(cache: dict) -> None:
    """bytes of each released file by part, from the GGUF headers: embedding+head, MTP block, experts, other ternary
    (dense) tensors, F32 tensors"""
    sys.path.insert(0, GGUF_PY)
    import gguf  # noqa: PLC0415
    files = {"xs": RELEASE["XS"][0], "sm": RELEASE["S"][0], "md": RELEASE["M"][0],
             "root": GGUF + "/tony-tern/R2B3m/Thor-T-R2B3m-packed.gguf"}
    for p, f in files.items():
        if not os.path.exists(f):
            continue
        k = "parts|" + file_key(f)
        if k not in cache:
            r = gguf.GGUFReader(f)
            n_layers = max(int(t.name.split(".")[1]) for t in r.tensors if t.name.startswith("blk."))
            part = {"emb": 0, "mtp": 0, "exp": 0, "dense": 0, "flt": 0}
            for t in r.tensors:
                nb = int(t.n_bytes)
                if t.name.startswith(("token_embd", "output.")) or t.name == "output.weight":
                    part["emb"] += nb
                elif t.name.startswith(f"blk.{n_layers}."):
                    part["mtp"] += nb
                elif t.tensor_type.name in ("F32", "F16", "BF16"):
                    part["flt"] += nb
                elif "_exps" in t.name:
                    part["exp"] += nb
                else:
                    part["dense"] += nb
            cache[k] = part
        part = cache[k]
        tot = sum(part.values())
        for q, v in part.items():
            mac(f"{p}Part{q.capitalize()}", f2(v / GIB), f"GiB of {q}")
        mac(f"{p}PartEmbPct", f"{100 * part['emb'] / tot:.1f}", "share of embedding+head in the tensor bytes")
        mac(f"{p}PartTot", f2(tot / GIB))
        PARTS[p] = part
    if "xs" in PARTS and "sm" in PARTS:
        for q, nm in (("emb", "Emb"), ("dense", "Dense"), ("exp", "Exp"), ("mtp", "Mtp"), ("flt", "Flt")):
            dlt = PARTS["sm"][q] - PARTS["xs"][q]
            mac(f"smMinusXs{nm}", f"{dlt / 1e6:+.0f}".replace("-", "$-$"), "MB, S minus XS")
    if os.path.exists(files["root"]):
        sha = sha256_file(files["root"], cache, True)
        mac("rootPackedSha", sha, "released root, packed into the release types")
        mac("rootPackedBytes", ints(file_size(files["root"])))
        mac("rootPackedGiB", f2(file_size(files["root"]) / GIB))
        mac("rootPackedBpw", f"{8 * file_size(files['root']) / PARAMS:.3f}")


def np_control() -> None:
    """ARC-Challenge at the bench's own settings (-c 1024 -ub 512), -np 5 against -np 16, for XS and M (launch engine);
    files controllo_np/{XS,M}_arc_np{5,16}.log (the -np 1 runs stopped at the first five-option question). Each model's macros appear when both of its logs are complete."""
    d = FIN / "controllo_np"
    done = 0
    for m, p in (("XS", "Xs"), ("M", "Md")):
        a, b = read_mclp(d / f"{m}_arc_np5.log"), read_mclp(d / f"{m}_arc_np16.log")
        if a is None or b is None or len(a["gold"]) != len(b["gold"]) or a["final"] is None or b["final"] is None:
            continue
        w, l_, pv = mcnemar(b["ok"], a["ok"])
        mac(f"npCtl{p}N", ints(len(a["gold"])))
        mac(f"npCtl{p}Changed", ints(int((a["choice"] != b["choice"]).sum())))
        mac(f"npCtl{p}WL", f"{w}/{l_}", "-np 5 wins/losses against -np 16")
        mac(f"npCtl{p}P", tex_p(pv))
        mac(f"npCtl{p}AccFour", f2(100 * a["ok"].mean()), "-np 5")
        mac(f"npCtl{p}AccSixteen", f2(100 * b["ok"].mean()))
        done += 1
    mac("npCtlDone", int(done == 2), "CONTROL-NP: both XS and M complete")
    # partial first control (-np 1 requested, raised to 4 by the scorer; stopped at the first five-option question)
    for m, p in (("XS", "Xs"), ("M", "Md")):
        a_, b_ = read_mclp(d / f"{m}_arc_np1.log"), read_mclp(d / f"{m}_arc_np16.log")
        if a_ is None or b_ is None:
            continue
        n_ = len(a_["choice"])
        if len(b_["choice"]) < n_:      # the -np 16 log is still being written: the comparison is not ready
            continue
        ch = int((a_["choice"] != b_["choice"][:n_]).sum())
        if p == "Xs":
            mac("npPartN", ints(n_), "items scored by the partial -np 1 (raised to 4) control")
        mac(f"npPart{p}Changed", ch)
        mac(f"npPart{p}Pct", f"{100 * ch / n_:.1f}")
    mac("npDone", int(done == 2), "alias for W1 (07_limitations)")
    for m, p in (("XS", "Xs"), ("M", "Md")):
        if any(n == f"npCtl{p}AccFour" for n, _, _ in MACROS):
            v = {n: x for n, x, _ in MACROS}
            mac(f"np{m}diff", f"{float(v[f'npCtl{p}AccFour']) - float(v[f'npCtl{p}AccSixteen']):+.2f}".replace("-", "$-$"),
                "minimum batch (4) minus -np 16, ARC-C")
        else:
            mac(f"np{m}diff", r"\textit{running}", "PENDING-RUN")
    if done < 2:
        WARN.append("-np control not complete (esiti_finale_1107/controllo_np/{XS,M}_arc_np{5,16}.log)")


SPEED_KEYS = (("IQ2XXS_mixB", "mix"), ("IQ2XXS", "mix"), ("IQ2_XXS", "iqtwo"), ("IQ1_M", "iqonem"), ("Q2_K", "qtwo"),
              ("Q4_K_M", "qfour"), ("maestro", "te"), ("XS", "xs"), ("C", "xs"), ("S", "sm"), ("B", "sm"), ("M", "md"),
              ("A", "md"))


def _speed_key(name: str) -> str | None:
    for k, v in SPEED_KEYS:
        if name == k or name.startswith(k + "_") or name.endswith("-" + k):
            return v
    return None


def _bench_md(path: Path) -> dict:
    """llama-bench markdown: {ncmoe or None: {'pp512': (v, sd), 'tg128': (v, sd)}}"""
    out: dict = {}
    for line in path.read_text(errors="replace").splitlines():
        c = [x.strip() for x in line.split("|")]
        if len(c) > 4 and c[-3] in ("pp512", "tg128"):
            nc = int(c[-4]) if c[-4].isdigit() and "ncmoe" not in c[-4] and len(c) > 9 else None
            v = c[-2].split(" ± ")
            out.setdefault(nc, {})[c[-3]] = (float(v[0]), float(v[1]) if len(v) > 1 else 0.0)
    return out


def speed_sessions() -> None:
    """One-session Vulkan speeds of all files (7 Nov, build 5d2e382a9, an ancestor of the launch engine), the same-session
    re-run on the launch engine (tonight) and the RTX 4060 rivals; raw llama-bench outputs, first of two rounds."""
    # esiti_finale_1107/velocita_rivali (10 Nov 04:19) is NOT used: another job shared the GPU (Q4_K_M 39.23 tokens/s
    # against 70.28-70.93 in clean sessions; AUDIT_TAGLI notes). A clean same-session re-run will use another directory.
    for tag, d in (("vsev", Path(FORGE + "/velocita_1101/paper_finale_1107/grezzi")),
                   ("vnew", FIN / "velocita_rivali_pulite")):
        n = 0
        files = sorted(d.glob("bench_*_g1.txt")) if d.exists() else []
        for f in files:
            m = re.match(r"bench_(.+)_(base|int8)_g1\.txt", f.name)
            if not m or not (key := _speed_key(m.group(1))):
                continue
            b = _bench_md(f)
            if not b:
                continue
            r = b[min(b, key=lambda x: -1 if x is None else x)]
            mode = "I" if m.group(2) == "int8" else "B"
            for t, nm in (("tg128", "Tg"), ("pp512", "Pp")):
                if t in r:
                    mac(f"{tag}{key}{mode}{nm}", f2(r[t][0]), f"{d.name} {f.name}")
            n += 1
        mac(f"{tag}Done", int(n > 0), f"files parsed: {n}")
        if tag == "vnew" and n == 0:
            WARN.append("same-session rival speeds on the launch engine not yet present (esiti_finale_1107/velocita_rivali)")
    d = STATO / "aragorn_rivali"
    n = 0
    for f in sorted(d.glob("*")) if d.exists() else []:
        if f.suffix not in (".log", ".txt") or not (key := _speed_key(f.stem.replace("b_", "", 1))):
            continue
        b = {k: v for k, v in _bench_md(f).items() if k is not None}
        if not b:
            continue
        nc = min(b)
        mac(f"cr{key}Nc", nc, f"RTX 4060 rivals {f.name}")
        for t, nm in (("tg128", "Tg"), ("pp512", "Pp")):
            if t in b[nc]:
                mac(f"cr{key}{nm}", f2(b[nc][t][0]))
        n += 1
    mac("crDone", int(n > 0))
    # one session, one binary (pub/cuda-vec 49fa8a71e), RTX 4060 laptop, -p 512 -n 128 -r 3, -ncmoe 14..30
    d = STATO / "aragorn_stessa_sessione_1110"
    keys = {"Thor-T-35B-A3B-XS": "xs", "Thor-T-S-packed-testaXS": "sm", "Thor-T-M-packed-testaXS": "md",
            "Ornith-1.5-35B-A3B-IQ2_XXS": "iqtwo", "Ornith-1.5-35B-A3B-Q2_K": "qtwo"}
    EQ = 22
    n = 0
    for stem, key in keys.items():
        f = d / f"{stem}.log"
        b = {k: v for k, v in _bench_md(f).items() if k is not None and "tg128" in v} if f.exists() else {}
        if not b:
            continue
        nc = max(b, key=lambda k: b[k]["tg128"][0])
        mac(f"cs{key}Nc", nc, f"same-session CUDA {f.name}: -ncmoe of the best tg128")
        mac(f"cs{key}Tg", f2(b[nc]["tg128"][0]))
        mac(f"cs{key}Pp", f2(b[nc]["pp512"][0]) if "pp512" in b[nc] else "---")
        if EQ in b:
            mac(f"cs{key}TgEq", f2(b[EQ]["tg128"][0]), f"tg128 at -ncmoe {EQ}")
            mac(f"cs{key}PpEq", f2(b[EQ]["pp512"][0]) if "pp512" in b[EQ] else "---")
        n += 1
    gl = d / "git.log"
    mac("csCommit", gl.read_text(errors="replace").split()[0][:9] if gl.exists() else "---")
    mac("csEqNc", EQ)
    mac("csDone", int(n == len(keys)), f"same-session CUDA files parsed: {n}")


def speed_section() -> None:
    def bench(path: Path) -> dict:
        out = {}
        if not path.exists():
            return out
        for line in path.read_text(errors="replace").splitlines():
            m = re.search(r"\|\s*(pp512|tg128)\s*\|\s*([0-9.]+) ± ([0-9.]+)", line)
            if m:
                out[m.group(1)] = (float(m.group(2)), float(m.group(3)))
        return out

    pre = {"XS": "xs", "S": "sm", "M": "md"}
    for m in ("XS", "S", "M"):
        b = bench(FIN / m / "velocita.txt")
        for k, nm in (("tg128", "Tg"), ("pp512", "Pp")):
            if k in b:
                mac(f"{pre[m]}Vk{nm}", f2(b[k][0]), "launch engine, final bench session")
                mac(f"{pre[m]}Vk{nm}Sd", f2(b[k][1]))
    b = bench(OLD / "maestro" / "velocita.txt")
    for k, nm in (("tg128", "Tg"), ("pp512", "Pp")):
        if k in b:
            mac(f"teVk{nm}", f2(b[k][0]), "teacher, idle session 2 Nov, commit 05589d4 (cross-build)")
            mac(f"teVk{nm}Sd", f2(b[k][1]))
    rows = register_rows()
    rocm = [r for r in rows if "\tROCM-MMQ verifiche:" in r]
    if rocm:
        r = rocm[-1]
        key = {"Thor-T-35B-A3B": "xs", "S-packed-testa": "sm", "Thor-T-M-packe": "md", "Ornith-1.5-35B": "bqfour"}
        for seg in r.split("|"):
            seg = seg.strip()
            mv = re.match(r"VK (\S+): pp512 ([0-9.]+) ± ([0-9.]+) ; tg128 ([0-9.]+) ± ([0-9.]+)", seg)
            if mv and mv.group(1) in key:
                p = key[mv.group(1)]
                mac(f"{p}SesVkPp", f2(float(mv.group(2))), "one session, launch engine, int8 flag on, -r 2")
                mac(f"{p}SesVkTg", f2(float(mv.group(4))))
            mr = re.match(r"(\S+): == thor-aragorn2 .*== thor-cudammq pp512 ([0-9.]+) ± ([0-9.]+) ; tg128 ([0-9.]+) ± ([0-9.]+)",
                          seg)
            if mr and mr.group(1) in key:
                p = key[mr.group(1)]
                mac(f"{p}RocmPp", f2(float(mr.group(2))), "ROCm/HIP, pub/cuda-mmq (ancestor of the release)")
                mac(f"{p}RocmTg", f2(float(mr.group(4))))
    ab = [r for r in rows if "\tAB-RILASCIO " in r]
    if ab:
        ms = re.findall(r"(motore-lancio-1107|build-vk): pp512 ([0-9.]+) ± [0-9.]+ ; tg128 ([0-9.]+)", ab[-1])
        if len(ms) >= 2:
            mac("mdAbLaunchTg", f2(float(ms[0][2])), "M Vulkan, launch engine vs release branch, same session")
            mac("mdAbLaunchPp", f2(float(ms[0][1])))
            mac("mdAbRelTg", f2(float(ms[1][2])))
            mac("mdAbRelPp", f2(float(ms[1][1])))
    # CUDA RTX 4060 Laptop 8 GB, release HEAD (pub/cuda-vec 49fa8a71e): llama-bench md tables
    cb = STATO / "cudavec_b"
    for f, p in (("b_XS_new.log", "xs"), ("b_S_new.log", "sm"), ("b_M_new.log", "md"), ("b_Q4.log", "bqfour")):
        path = cb / f
        if not path.exists():
            continue
        first = {}
        for line in path.read_text(errors="replace").splitlines():
            c = [x.strip() for x in line.split("|")]
            if len(c) > 8 and c[-3] in ("pp512", "tg128") and c[-4].isdigit():
                nc = int(c[-4])
                first.setdefault(nc, {})[c[-3]] = c[-2].split(" ± ")
        if first:
            nc = min(first)
            mac(f"{p}CuNcmoe", nc, "smallest -ncmoe measured (fits 8 GB)")
            for k, nm in (("tg128", "Tg"), ("pp512", "Pp")):
                if k in first[nc]:
                    mac(f"{p}Cu{nm}", f2(float(first[nc][k][0])))
                    mac(f"{p}Cu{nm}Sd", f2(float(first[nc][k][1])))
    for f, p in (("b_M41_new.log", "md"), ("b_Q4_41.log", "bqfour")):
        path = cb / f
        if path.exists():
            m = re.search(r"tg128\s*\|\s*([0-9.]+) ± ([0-9.]+)", path.read_text(errors="replace"))
            if m:
                mac(f"{p}CuCpuTg", f2(float(m.group(1))), "all expert layers in host RAM (-ncmoe 41)")
                mac(f"{p}CuCpuTgSd", f2(float(m.group(2))))
    mtp = [r for r in rows if "\tARAGORN-MTP " in r]
    if mtp:
        for name, p in (("Thor-T-35B-A3B-XS", "xs"), ("Thor-T-S-packed-testaXS", "sm"), ("Thor-T-M-packed-testaXS", "md")):
            mn = re.search(re.escape(name) + r" none ([0-9.]+)", mtp[-1])
            m1 = re.search(re.escape(name) + r" mtp1 ([0-9.]+) / ([0-9.]+)", mtp[-1])
            if mn and m1:
                mac(f"{p}MtpNone", f2(float(mn.group(1))), "CUDA RTX 4060, 7 Nov build, 5 prompts x 256 tokens")
                mac(f"{p}MtpOne", f2(float(m1.group(1))))
                mac(f"{p}MtpAcc", f"{float(m1.group(2)):.1f}")
                mac(f"{p}MtpGain", f"{100 * (float(m1.group(1)) / float(mn.group(1)) - 1):.0f}")


MTP_RUNS = Path(FORGE + "/velocita_1101")
MTP_REG = "mtp_integra_1955"   # the run of register row 2026-11-07T20:03 (MTP-INTEGRA), build 4ed3ec488 (launch engine)


def mtp_launch_section() -> None:
    """MTP speed on the launch engine (Vulkan, APU), 7 Nov: five repetitions of curva_mtp.sh (5 prompts x 256 tokens,
    temp 0, ctx 4096, one request) with the int8 flag on (q1) and off (q0); the registered run is the last one. Each
    file is reported at its release setting (XS off, S and M on); the build is the launch engine (integra_1950 logs)."""
    prod = Path(GGUF) / "tony-tern" / "MTP_1101" / "prova_M_testaXS_1106" / "curva_mtp.sh"   # bundle-relative (POD_g20 S1)
    if prod.exists():
        prod.read_text()   # read so that the producer ships with the logs
    bl = (MTP_RUNS / "integra_1950" / "bench_XS_q0.txt")
    if not bl.exists() or "build: 4ed3ec488" not in bl.read_text(errors="replace"):
        WARN.append("MTP launch-engine run: build of integra_1950 is not 4ed3ec488")
        return

    def raw_rate(d: Path, m_: str, spec: str) -> float | None:
        """mean of the unrounded decode rates of the five completions (risp_<m>_<spec>_<i>.json; POD_g20 N2)"""
        v = []
        for f in sorted(d.glob(f"risp_{m_}_{spec}_*.json")):
            try:
                v.append(float(json.loads(f.read_text())["timings"]["predicted_per_second"]))
            except (ValueError, KeyError, TypeError):
                return None
        return sum(v) / len(v) if len(v) == 5 else None

    def table(d: Path) -> dict:
        t = {}
        r = d / "RISULTATI.md"
        if not r.exists():
            return t
        txt = r.read_text(errors="replace")
        for ln in txt.splitlines():
            c = [x.strip() for x in ln.strip().strip("|").split("|")]
            if len(c) == 6 and c[0] in ("M", "S", "XS") and c[1] in ("none", "mtp1", "mtp2"):
                t[(c[0], c[1])] = (float(c[2]), c[5])
        m = re.search(r"identico a spec none \(greedy\): (\d+)/(\d+)", txt)
        if m:
            t["same"] = (int(m.group(1)), int(m.group(2)))
        return t

    runs = sorted(d for d in MTP_RUNS.glob("mtp_integra_*") if d.is_dir())
    for d in runs:
        for q in ("q0", "q1"):
            lg = MTP_RUNS / f"{d.name}.{q}.log"
            if lg.exists():
                lg.read_text(errors="replace")
    setting = {"XS": "q0", "S": "q1", "M": "q1"}
    pre = {"XS": "xs", "S": "sm", "M": "md"}
    reg = {q: table(MTP_RUNS / MTP_REG / q) for q in ("q0", "q1")}
    if not all(reg.values()):
        WARN.append("MTP launch-engine run: registered tables missing")
        return
    mac("mtpLEEarlierN", len(runs) - 1, "earlier builds measured the same way on 7 Nov (not repetitions)")
    mac("mtpRepDone", 0, "1 = five-run repetition on the launch-engine build measured (queued)")
    for m_, q in setting.items():
        p = pre[m_]
        t = reg[q]
        none, one, two = t[(m_, "none")][0], t[(m_, "mtp1")][0], t[(m_, "mtp2")][0]
        mac(f"{p}MtpLENone", f2(none), f"tokens/s, launch engine Vulkan, {q} (release int8 setting), no draft")
        mac(f"{p}MtpLEOne", f2(one), "one MTP draft token")
        mac(f"{p}MtpLETwo", f2(two), "two MTP draft tokens")
        mac(f"{p}MtpLEAccOne", t[(m_, "mtp1")][1], "draft acceptance %, one draft token")
        mac(f"{p}MtpLEAccTwo", t[(m_, "mtp2")][1])
        r0, r1 = raw_rate(MTP_RUNS / MTP_REG / q, m_, "none"), raw_rate(MTP_RUNS / MTP_REG / q, m_, "mtp1")
        g_ = 100 * (r1 / r0 - 1) if r0 and r1 else 100 * (one / none - 1)
        mac(f"{p}MtpLEGain", f"{g_:.1f}", "decode speed-up with one draft token, %, from the unrounded rates")
        gains = []
        for d in runs:
            if d.name == MTP_REG:
                continue          # the other runs were made on four earlier builds (integra_1658/1729/1830/1905)
            tt = table(d / q)
            r0, r1 = raw_rate(d / q, m_, "none"), raw_rate(d / q, m_, "mtp1")
            if r0 and r1:
                gains.append(100 * (r1 / r0 - 1))
            elif (m_, "none") in tt and (m_, "mtp1") in tt:
                gains.append(100 * (tt[(m_, "mtp1")][0] / tt[(m_, "none")][0] - 1))
        mac(f"{p}MtpLEGainLo", f"{min(gains):.1f}", "range of the speed-up on four earlier builds (7 Nov)")
        mac(f"{p}MtpLEGainHi", f"{max(gains):.1f}")
    t1 = reg["q1"]
    mac("xsMtpLEqOneGain", f"{100 * (t1[('XS', 'mtp1')][0] / t1[('XS', 'none')][0] - 1):.1f}",
        "XS with the int8 flag on (not its release setting)")
    for q in ("q0", "q1"):
        if "same" in reg[q]:
            a_, b_ = reg[q]["same"]
            a_, b_ = a_ - b_ // 3, b_ - b_ // 3      # drop the "none" runs, identical to themselves by construction
            mac(f"mtpLESame{'Off' if q == 'q0' else 'On'}", f"{a_}/{b_}",
                "greedy completions identical with and without one/two draft tokens (int8 flag off/on)")


def sizing_section() -> None:
    """size -> retention: allocations of the same root measured on MMLU-2000 in early October (sizing_points.tsv); each
    row's bytes and score must appear in its register row; the teacher (82.00, row 1276) and the root (74.6, rows
    1241/1245) were read on the same binary"""
    if CICLI.exists():
        reg = {i + 1: r_ for i, r_ in enumerate(CICLI.read_bytes().decode("utf-8", "replace").split("\n"))}
    else:
        reg = {int(ln.split("\t", 1)[0]): ln.split("\t", 1)[1] for ln in
               CICLI_EXTRACT.read_text(errors="replace").splitlines() if "\t" in ln}
    te_row, root_rows = 1276, (1241, 1245)
    if "82,00" not in reg.get(te_row, "") or not all("74.6" in reg.get(r, "") for r in root_rows):
        WARN.append("sizing: teacher/root MMLU-2000 not found in the register rows")
        return
    te = 82.00
    mac("szTeDev", f2(te), "teacher MMLU-2000 on the binary of the sizing points (register row 1276)")
    mac("szRootRet", f"{100 * 74.6 / te:.1f}", "root, MMLU-2000 as % of the teacher, same binary")
    for ln in (HERE / "sizing_points.tsv").read_text().splitlines()[1:]:
        lab, row, by, sc, _ = ln.split("\t")
        t = reg.get(int(row), "")
        if by not in t or sc not in t:
            raise SystemExit(f"sizing_points.tsv: {lab} not confirmed by register row {row}")
        mac(f"sz{lab}GiB", f2(int(by) / GIB), f"register row {row}")
        mac(f"sz{lab}Ret", f"{100 * float(sc) / te:.1f}", "MMLU-2000 as % of the teacher, same binary")
        mac(f"sz{lab}Score", f"{float(sc):.2f}")


def root_mtp_section() -> None:
    """our ternary MTP head (XS's block 40) grafted onto the root (register 2026-11-10T09:57, row 5048), measured on the
    RTX 4060 with our CUDA build in one session with XS (stato/radice_mtp_1110/aragorn/RISULTATI.md, row 5060); the
    trunk logits are unchanged (KLD control on the launch engine, row 5061)"""
    r = STATO / "radice_mtp_1110" / "aragorn" / "RISULTATI.md"
    rows = {i + 1: x for i, x in enumerate(CICLI.read_bytes().decode("utf-8", "replace").split("\n"))} if CICLI.exists() else {}
    t = r.read_text(errors="replace") if r.exists() else ""
    tab = {}
    for ln in t.splitlines():
        c = [x.strip() for x in ln.strip().strip("|").split("|")]
        if len(c) == 6 and c[1] in ("none", "mtp1", "mtp2"):
            tab[(c[0], c[1])] = (float(c[2]), c[5])
    m = re.search(r"identico a spec none \(greedy\): (\d+)/(\d+)", t)
    reg_ok = (not rows) or ("8851425088 B, sha 25fb7303782afcb5" in rows.get(5048, "") and "stessa top 100,00" in rows.get(5061, ""))
    ok = all((k, sp) in tab for k in ("radice_testaXS", "XS") for sp in ("none", "mtp1", "mtp2")) and m and reg_ok
    mac("rootMtpDone", int(bool(ok)), "1 = our ternary MTP head grafted onto the root and its acceptance measured")
    if not ok:
        WARN.append("root + our MTP head: measurement not found")
        return
    for k, p in (("radice_testaXS", "rootMtp"), ("XS", "xsMtpCuSes")):
        n0, n1, n2 = tab[(k, "none")][0], tab[(k, "mtp1")][0], tab[(k, "mtp2")][0]
        mac(f"{p}None", f2(n0), "tokens/s, RTX 4060, our CUDA build, -ncmoe 14, same session (10 Nov)")
        mac(f"{p}One", f2(n1))
        mac(f"{p}Two", f2(n2))
        mac(f"{p}AccOne", tab[(k, "mtp1")][1])
        mac(f"{p}AccTwo", tab[(k, "mtp2")][1])
        mac(f"{p}Gain", f"{100 * (n1 / n0 - 1):.1f}")
    mac("rootMtpSame", f"{m.group(1)}/{m.group(2)}", "drafted greedy completions identical to no-draft")
    mac("rootGraftBytes", "8,851,425,088", "root with our MTP head (register row 5048)")
    mac("rootGraftSha", "25fb7303", "sha256 prefix, register row 5048")


def ptq_mtp_section() -> None:
    """our ternary MTP head inside XS-PTQ1_0 (MTP tensors rotated and listed, eh_proj ternary), run on PrismML's fork with
    a two-commit local patch (3763b87, 8f2b52c; not pushed), RTX 4060, same session as XS on our CUDA build
    (stato/mtp_ptq1_fase_a/RISULTATI.md; register row 5063)"""
    d = STATO / "mtp_ptq1_fase_a"
    t = (d / "RISULTATI.md").read_text(errors="replace") if (d / "RISULTATI.md").exists() else ""
    (d / "commit_fork.txt").read_text(errors="replace") if (d / "commit_fork.txt").exists() else ""
    tab = {}
    for ln in t.splitlines():
        c = [x.strip() for x in ln.strip().strip("|").split("|")]
        if len(c) == 6 and c[1] in ("none", "mtp1", "mtp2"):
            tab[(c[0], c[1])] = (float(c[2]), c[5])
    m = re.search(r"identico a spec none \(greedy\): (\d+)/(\d+)", t)
    rows = {i + 1: x for i, x in enumerate(CICLI.read_bytes().decode("utf-8", "replace").split("\n"))} if CICLI.exists() else {}
    reg_ok = (not rows) or ("7f45ac12" in rows.get(5063, "") and "8.650.567.136" in rows.get(5063, ""))
    ok = all((k, sp) in tab for k in ("PTQ1_0_fork", "XS_nostro") for sp in ("none", "mtp1", "mtp2")) and m and reg_ok
    mac("ptqMtpDone", int(bool(ok)), "1 = our MTP head measured inside XS-PTQ1_0 on PrismML's fork (local patch)")
    if not ok:
        return
    for k, p in (("PTQ1_0_fork", "ptqMtp"), ("XS_nostro", "xsMtpPtqSes")):
        n0, n1, n2 = tab[(k, "none")][0], tab[(k, "mtp1")][0], tab[(k, "mtp2")][0]
        mac(f"{p}None", f2(n0), "tokens/s, RTX 4060, -ncmoe 14, same session (10 Nov)")
        mac(f"{p}One", f2(n1))
        mac(f"{p}Two", f2(n2))
        mac(f"{p}AccOne", tab[(k, "mtp1")][1])
        mac(f"{p}AccTwo", tab[(k, "mtp2")][1])
        mac(f"{p}Ratio", f"{n1 / n0:.2f}")
    mac("ptqMtpSame", f"{m.group(1)}/{m.group(2)}")
    mac("ptqMtpBytes", "8,650,567,136", "XS-PTQ1_0 with the MTP tensors listed (register row 5063)")
    mac("ptqMtpSha", "7f45ac12")


def derived_claims() -> None:
    """counts and ratios stated in the abstract and conclusion, from macros already emitted (AUDIT_TAGLI restores)"""
    v = {n: val for n, val, _ in MACROS}

    def pnum(t: str) -> float:
        t = t.replace("\\ensuremath{", "")
        t = t[:-1] if t.endswith("}") else t
        if "<" in t:
            return 0.0
        m = re.search(r"=\s*([0-9.]+)(?:\\cdot10\^\{(-?\d+)\})?", t)
        return float(m.group(1)) * (10 ** int(m.group(2)) if m.group(2) else 1) if m else 1.0
    # M against Q2_K on the likelihood tasks that have landed for Q2_K (unpaired, indicative; tab:rivals-suite)
    suite = (("Hs", "HellaSwag"), ("Wino", "Winogrande"), ("Arcc", "ARC-Challenge"), ("Arce", "ARC-easy"),
             ("Piqa", "PIQA"), ("Boolq", "BoolQ"), ("Obqa", "OpenBookQA"), ("Tqa", "TruthfulQA-MC1"),
             ("Mmlupro", "MMLU-Pro"))
    num = lambda x: re.fullmatch(r"[0-9.]+", str(x or "")) is not None
    landed = [(k, nm) for k, nm in suite if num(v.get(f"rqtwo{k}")) and num(v.get(f"md{k}"))]
    above = [nm for k, nm in landed if float(v[f"md{k}"]) > float(v[f"rqtwo{k}"])]
    notab = [f"{nm} ({v['md' + k]} against {v['rqtwo' + k]})" for k, nm in landed if nm not in above]
    mac("qtwoSuiteN", len(landed), "Q2_K likelihood tasks landed on the launch engine (of 9)")
    mac("mdOverQtwoSuiteK", len(above), "of which M scores higher (unpaired, indicative)")
    mac("mdOverQtwoSuiteExc", "; ".join(notab) if notab else "none")
    tasks = (("Hs", "HellaSwag"), ("Wino", "Winogrande"), ("Arcc", "ARC-Challenge"), ("Arce", "ARC-easy"),
             ("Boolq", "BoolQ"), ("Piqa", "PIQA"), ("Obqa", "OpenBookQA"), ("Tqa", "TruthfulQA-MC1"),
             ("Mmlupro", "MMLU-Pro"))
    have = [(k, nm) for k, nm in tasks if f"md{k}P" in v and f"md{k}Ret" in v]
    below = [nm for k, nm in have if pnum(v[f"md{k}P"]) < 0.05 and float(v[f"md{k}Ret"]) < 100]
    mac("mdLikN", len(have), "likelihood tasks with a paired test of M against the teacher (per-token scoring)")
    mac("mdLikBelowN", len(below), "of which M is significantly below the teacher (p < 0.05, nominal)")
    mac("mdLikBelowNames", ", ".join(below) if below else "none")
    if "xsVkTg" in v and "teVkTg" in v:
        mac("xsOverTeTg", f"{float(v['xsVkTg']) / float(v['teVkTg']):.2f}",
            "XS decode speed over the Q8_0 teacher's (launch engine vs the teacher's earlier idle session)")
    if "vsevxsBTg" in v and "vsevteBTg" in v:
        mac("xsOverTeSame", f"{float(v['vsevxsBTg']) / float(v['vsevteBTg']):.2f}",
            "XS over the teacher, decode, same session and binary (7 Nov)")
    if "xsSesVkTg" in v and "teVkTg" in v:
        mac("xsSesOverTeTg", f"{float(v['xsSesVkTg']) / float(v['teVkTg']):.2f}")


def release_section(cache: dict, allow: bool) -> None:
    q2 = file_size(Q2K_FILE) or 13085779616
    q4 = file_size(Q4KM_FILE) or 21864081056
    te = file_size(TEACHER_BYTES_FILE)
    mac("teBytes", ints(te))
    mac("teGiB", f2(te / GIB))
    mac("bqtwoBytes", ints(q2))
    mac("bqtwoGiB", f2(q2 / GIB))
    mac("bqfourBytes", ints(q4))
    mac("bqfourGiB", f2(q4 / GIB))
    pre = {"XS": "xs", "S": "sm", "M": "md"}
    for m, (rel, bench_f, base, step) in RELEASE.items():
        p = pre[m]
        sz = file_size(rel)
        mac(f"{p}Bytes", ints(sz), f"released file {rel}")
        mac(f"{p}GiB", f2(sz / GIB))
        mac(f"{p}Bpw", f"{8 * sz / PARAMS:.3f}")
        mac(f"{p}File", Path(rel).name.replace("_", r"\_"))
        sha = sha256_file(rel, cache, allow)
        if sha is None:
            WARN.append(f"sha256 of {rel} not cached and --no-hash given")
            sha = "unknown"
        mac(f"{p}Sha", sha)
        mac(f"{p}ShaShort", sha[:16])
        declared = None
        for sf in (Path(rel).with_suffix(".gguf.sha256"), Path(rel).parent / "SHA256SUMS"):
            if sf.exists():
                for line in sf.read_text().splitlines():
                    tok = line.split()
                    if tok and (len(tok) == 1 or tok[-1].endswith(Path(rel).name)):
                        declared = tok[0]
        if declared and sha != "unknown" and declared != sha:
            raise SystemExit(f"sha256 of {rel} != declared {declared}")
        bsz = file_size(bench_f)
        if bsz is not None:
            mac(f"{p}BenchBytes", ints(bsz), "benchmarked file")
            mac(f"{p}BenchDelta", ints(bsz - sz))
        if rel != bench_f and bsz is not None:
            a, b = tensor_hashes(rel, cache, allow), tensor_hashes(bench_f, cache, allow)
            if a is not None and b is not None:
                same = sum(1 for k, v in a.items() if b.get(k) == v)
                mac(f"{p}TensSame", ints(same), "tensors byte-identical between released and benchmarked file")
                mac(f"{p}TensRel", ints(len(a)))
                mac(f"{p}TensBench", ints(len(b)))
                extra = sorted(set(b) - set(a))
                mac(f"{p}TensDropped", ints(len(extra)))
                if extra:
                    WARN.append(f"{m}: tensors only in the benchmarked file: {extra[:5]}...")
        elif rel == bench_f:
            mac(f"{p}TensSame", "all")
    # XS against the checkpoint C of the paper (earlier header, untrained MTP block)
    c_file = (GGUF + "/tony-tern/OBIETTIVO_C/RECORD_C/Thor-T-C-T400POST-T50.gguf")
    if os.path.exists(c_file):
        a, b = tensor_hashes(RELEASE["XS"][0], cache, allow), tensor_hashes(c_file, cache, allow)
        if a is not None and b is not None:
            diff = sorted(k for k in set(a) | set(b) if a.get(k) != b.get(k))
            mac("xsVsCsame", ints(sum(1 for k, v in a.items() if b.get(k) == v)), "tensors of XS identical to C")
            mac("xsVsCdiff", ints(len(diff)))
            mac("xsVsCdiffOnlyMtp", int(all(k.startswith("blk.40.") for k in diff)), "1 = differences only in block 40")
            if not all(k.startswith("blk.40.") for k in diff):
                WARN.append(f"XS differs from C outside block 40: {[k for k in diff if not k.startswith('blk.40.')][:6]}")
    md = file_size(RELEASE["M"][0])
    mac("mdOverQtwo", ints(md - q2), "bytes of M above Q2_K")
    mac("mdOverQtwoPct", f"{100 * (md - q2) / q2:.3f}")
    mac("mdVsQfourPct", f"{100 * md / q4:.1f}", "M bytes as % of Q4_K_M")
    xs, s = file_size(RELEASE["XS"][0]), file_size(RELEASE["S"][0])
    mac("smOverXsPct", f"{100 * (s - xs) / xs:.1f}")
    mac("smOverXsGiB", f2((s - xs) / GIB))
    sh = {}
    for b in BLOCKS:
        f = MC / f"mmlu_{b}.bin"
        if f.exists():
            sh[b] = sha256_file(str(f), cache, True)
    if "00000" in sh:
        mac("benchDevSha", sh["00000"])
        mac("benchDevShaShort", sh["00000"][:16] + r"\ldots", "short form for running text")


def subjects_table(mm: dict, subj: np.ndarray) -> None:
    import pyarrow.parquet as pq  # noqa: PLC0415,F401
    t = mm["teacher"]["ok"]
    xs, s, m = (mm["full"][k]["ok"] for k in ("XS", "S", "M"))
    names = sorted(np.unique(subj))
    rows = []
    for nm in names:
        k = subj == nm
        w, l_, pv = mcnemar(t[k], xs[k])
        ws, ls, ps = mcnemar(t[k], s[k])
        wm, lm, pm = mcnemar(t[k], m[k])
        rows.append({"s": nm, "n": int(k.sum()), "t": 100 * t[k].mean(), "xs": 100 * xs[k].mean(),
                     "sm": 100 * s[k].mean(), "md": 100 * m[k].mean(), "w": w, "l": l_, "p": pv,
                     "ws": ws, "ls": ls, "ps": ps, "wm": wm, "lm": lm, "pm": pm})
    for key, hk in (("p", "ph"), ("ps", "phs"), ("pm", "phm")):
        for r, a in zip(rows, holm([r[key] for r in rows])):
            r[hk] = a
    worst = {r["s"] for r in sorted(rows, key=lambda r: r["xs"] - r["t"])[:5]}
    below = sum(r["xs"] < r["t"] for r in rows)
    sig = sum(r["ph"] < 0.05 for r in rows)
    sig_above = sum(r["ph"] < 0.05 and r["xs"] > r["t"] for r in rows)
    mac("subjBelow", below)
    mac("subjSigHolm", sig)
    mac("subjSigHolmAbove", sig_above)
    mac("subjMdSigRaw", sum(r["pm"] < 0.05 for r in rows))
    write_subjects_text(rows, worst)

    def tp(p: float) -> str:
        if p < 1e-10:
            return r"$<10^{-10}$"
        if p >= 0.001:
            return f"{p:.2g}" if p < 0.1 else f"{p:.2f}"
        mm_, e = f"{p:.1e}".split("e")
        return f"${mm_}\\cdot10^{{{int(e)}}}$"
    def line(r):
        name = r["s"].replace("_", r"\_")
        if r["s"] in worst:
            name = r"\textbf{" + name + "}"
        d = r["xs"] - r["t"]
        ds = f"$+{d:.2f}$" if d >= 0 else f"$-{-d:.2f}$"
        st = lambda ph: "$^{*}$" if ph < 0.05 else ""
        return (f"{name} & {r['n']} & {r['t']:.2f} & {r['xs']:.2f} & {ds} & {r['w']}/{r['l']} & "
                f"{tp(r['p'])}{st(r['ph'])} & {r['sm']:.2f} & {r['ws']}/{r['ls']}{st(r['phs'])} & "
                f"{r['md']:.2f} & {r['wm']}/{r['lm']}{st(r['phm'])}\\\\")
    head = [r"\centering\scriptsize", r"\setlength{\tabcolsep}{2pt}", r"\begin{tabular}{@{}lrrrrrrrrrr@{}}", r"\toprule",
            r"subject & $n$ & teacher\teMMLUmark & XS & XS$-$teacher & XS w/l & $p$ & S & S w/l & M & M w/l\\", r"\midrule"]
    half = (len(rows) + 1) // 2
    L = ["% GENERATED by ../../revisione_1109/genera_numeri.py -- do not edit by hand.",
         r"\begin{table}[p]", *head, *[line(r) for r in rows[:half]], r"\bottomrule", r"\end{tabular}",
         r"\caption{Full MMLU test by subject, first half (alphabetical); continued in \cref{tab:subjects}.}",
         r"\label{tab:subjects-a}", r"\end{table}",
         r"\begin{table}[p]", *head, *[line(r) for r in rows[half:]], r"\bottomrule", r"\end{tabular}",
          r"\caption{Full MMLU test by subject (\texttt{cais/mmlu} test split, 14,042 questions), zero-shot, second half "
          r"(first half in \cref{tab:subjects-a}). XS, S and M on "
          r"the launch engine; the teacher on \teMMLUsrc. XS w/l: questions answered correctly by XS only / by the "
          r"teacher only (S w/l, M w/l likewise); $p$: exact McNemar (\cref{sec:mcnemar}); $^{*}$: significant after "
          rf"Holm correction over the 57 subjects, separately for each model. XS is below the teacher on \subjBelow{{}} of 57 subjects; \subjSigHolm{{}} differences survive "
          r"the Holm correction. In bold the five subjects where XS loses most. Generated by "
          r"\texttt{genera\_numeri.py} from the per-question logs.}",
          r"\label{tab:subjects}", r"\end{table}"]
    OUT_SUBJ.parent.mkdir(parents=True, exist_ok=True)
    write_if_changed(OUT_SUBJ, "\n".join(L) + "\n")


def write_subjects_text(rows: list, worst: set) -> None:
    """the Appendix I paragraph, generated from the same per-subject tests as the table (G14 S1/S3)"""
    def nm(x):
        return x.replace("_", " ")
    def sg(d):
        return f"$+{d:.2f}$" if d >= 0 else f"$-{-d:.2f}$"
    out = []
    for lab, key, w_, l_, p_, ph in (("XS", "xs", "w", "l", "p", "ph"), ("S", "sm", "ws", "ls", "ps", "phs"),
                                     ("M", "md", "wm", "lm", "pm", "phm")):
        below = sum(r[key] < r["t"] for r in rows)
        eq = sum(abs(r[key] - r["t"]) < 1e-9 for r in rows)
        above = sum(r[key] > r["t"] for r in rows)
        raw = sum(r[p_] < 0.05 for r in rows)
        surv = sorted([r for r in rows if r[ph] < 0.05], key=lambda r: r[key] - r["t"])
        sv = "; ".join(f"{nm(r['s'])} {sg(r[key] - r['t'])} ({r[w_]}/{r[l_]}, Holm {tex_p(r[ph])})" for r in surv)
        txt = (f"{lab} is below the teacher on {below} subjects, equal on {eq} and above on {above}; {raw} raw "
               f"differences have $p < 0.05$ and {len(surv)} survive the Holm correction over the 57 subjects")
        txt += (f" ({sv})." if surv else ".")
        best = max(rows, key=lambda r: r[key] - r["t"])
        if best[key] > best["t"]:
            txt += (f" Its largest gain over the teacher, {nm(best['s'])} {sg(best[key] - best['t'])} "
                    f"({best[w_]}/{best[l_]}, nominal {tex_p(best[p_])}, Holm {tex_p(best[ph])}), "
                    + ("survives the correction." if best[ph] < 0.05 else "does not survive the correction."))
        out.append(txt)
    w5 = sorted([r for r in rows if r["s"] in worst], key=lambda r: r["xs"] - r["t"])
    rets = [100 * r["xs"] / r["t"] for r in rows if r["t"] > 0]
    out.insert(1, "The five subjects where XS loses most are " + ", ".join(
        f"{nm(r['s'])} ({sg(r['xs'] - r['t'])}, {r['w']}/{r['l']})" for r in w5)
        + f"; per-subject retention of XS ranges from {min(rets):.1f}\\,\\% to {max(rets):.1f}\\,\\%.")
    OUT_SUBJ_TEXT.parent.mkdir(parents=True, exist_ok=True)
    write_if_changed(OUT_SUBJ_TEXT, "% GENERATED by ../../revisione_1109/genera_numeri.py -- do not edit by hand.\n"
                             + "\n".join(out) + "\n")


def q2k_launch(mm: dict) -> None:
    """Q2_K full MMLU on the launch engine (unit q2k-lancio-1109, mmlu_blocchi_q2k_1109.sh): \\qtwoDone = 1 when all
    blocks are complete; then M vs Q2_K is paired on one engine."""
    d = read_blocks([FIN / "Q2_K" / "mmlu_blocchi" / f"mmlu_{b}.log" for b in BLOCKS])
    ok = d is not None and np.array_equal(d["gold"], mm["teacher"]["gold"])
    mac("qtwoDone", int(ok), "1 = Q2_K full MMLU on the launch engine complete")
    if not ok:
        WARN.append("Q2_K launch-engine full MMLU not complete")
        return
    t, m = mm["teacher"]["ok"], mm["full"]["M"]["ok"]
    mac("bqtwoMMLU", f2(100 * d["ok"].mean()), "Q2_K full MMLU, launch engine")
    mac("bqtwoRet", f2(100 * d["ok"].sum() / t.sum()), "TEACHER-PCT")
    w, l_, pv = mcnemar(d["ok"], m)
    mac("mdVsQtwoLE", f"{w:,}/{l_:,}", "M wins/losses against Q2_K, launch engine")
    mac("mdVsQtwoLEP", tex_p(pv))
    mac("mdVsQtwoLEDiff", f"{100 * (m.sum() - d['ok'].sum()) / NFULL:+.2f}".replace("-", "$-$"))
    lo, hi = boot_diff(d["ok"], m, SEED + 61)
    mac("mdVsQtwoLELo", f"{lo:+.2f}".replace("-", "$-$"))
    mac("mdVsQtwoLEHi", f"{hi:+.2f}".replace("-", "$-$"))


def ptq_section(mm: dict) -> None:
    """PTQ1_0 end-to-end job (stato/ptq1_xs_1109.sh, unit ptq1-xs-1109): XS converted bit-exactly to upstream PTQ1_0,
    KLD against XS and MMLU-2000 on the upstream build (CPU), paired with XS on CPU and with XS on the launch engine.
    \\ptqDone = 1 only when the conversion is verified, the KLD is read and both MMLU-2000 logs are complete."""
    o = Path(os.environ.get("PTQ1_OUT", str(FIN / "PTQ1_0")))
    conv_ok = (o / "conv.log").exists() and any(
        ln.startswith("OK:") for ln in (o / "conv.log").read_text(errors="replace").splitlines())
    xs_c, pt_c = read_mclp(o / "mmlu2000_xs_cpu.log"), read_mclp(o / "mmlu2000_ptq1_cpu.log")
    mm_ok = all(d is not None and len(d["gold"]) == NDEV for d in (xs_c, pt_c))
    kl = (o / "kld_ptq1_vs_xs.log").read_text(errors="replace") if (o / "kld_ptq1_vs_xs.log").exists() else ""
    m_kld = re.search(r"Mean\s+KLD:\s*([-0-9.eE]+)\s*(?:±|\+/-)\s*([0-9.eE]+)", kl)
    m_top = re.search(r"Same top p:\s*([0-9.]+)\s*(?:±|\+/-)\s*([0-9.]+)", kl)
    # the job's logs are pending (not shipped) until the whole job is complete, so its numbers are emitted only then
    job_done = conv_ok and mm_ok and m_kld is not None
    if m_kld and job_done:
        mac("ptqKLD", f"{float(m_kld.group(1)):.6f}", "PTQ1_0 (upstream, CPU) vs XS (release branch, CPU), 4x512 wiki")
        mac("ptqKLDse", f"{float(m_kld.group(2)):.6f}")
    if m_top and job_done:
        mac("ptqTopP", f"{float(m_top.group(1)):.2f}", "same top token, %")
    if mm_ok:
        gold = mm["full"]["XS"]["gold"][:NDEV]
        if not (np.array_equal(xs_c["gold"], gold) and np.array_equal(pt_c["gold"], gold)):
            raise SystemExit("PTQ1_0 MMLU-2000 gold != XS gold")
        mac("ptqXsCpu", f2(100 * xs_c["ok"].mean()), "XS on CPU, release branch, MMLU-2000")
        mac("ptqMMLU", f2(100 * pt_c["ok"].mean()), "XS as PTQ1_0 on CPU, upstream master + #29676, MMLU-2000")
        w, l_, pv = mcnemar(xs_c["ok"], pt_c["ok"])
        mac("ptqVsCpuWL", f"{w}/{l_}", "PTQ1_0 wins/losses against XS, both CPU")
        mac("ptqVsCpuP", tex_p(pv))
        mac("ptqVsCpuSame", ints(int((xs_c["choice"] == pt_c["choice"]).sum())), "same chosen answer, of 2000")
        xv = mm["full"]["XS"]
        w, l_, pv = mcnemar(xv["ok"][:NDEV], pt_c["ok"])
        mac("ptqVsVkWL", f"{w}/{l_}", "PTQ1_0 (CPU) wins/losses against XS (launch engine): cross-engine")
        mac("ptqVsVkP", tex_p(pv))
        mac("ptqVsVkSame", ints(int((xv["choice"][:NDEV] == pt_c["choice"]).sum())))
    for nm, f in (("Xs", "bench_xs_cpu.txt"), ("Ptq", "bench_ptq1_cpu.txt")):
        if (o / f).exists():
            for line in (o / f).read_text(errors="replace").splitlines():
                c = [x.strip() for x in line.split("|")]
                if len(c) > 3 and c[-3] in ("pp512", "tg128"):
                    v = re.match(r"([0-9.]+)", c[-2])
                    if v:
                        mac(f"ptqBench{nm}{'Pp' if c[-3] == 'pp512' else 'Tg'}", f"{float(v.group(1)):.2f}",
                            "llama-bench CPU, tokens/s")
    done = conv_ok and mm_ok and m_kld is not None
    if not (m_kld and job_done):
        mac("ptqKLD", r"\textit{pending}", "placeholder until the ptq1-xs-1109 job lands")
    if not mm_ok:
        mac("ptqMMLU", r"\textit{pending}", "placeholder until the ptq1-xs-1109 job lands")
    mac("ptqDone", int(done), "1 = XS converted to PTQ1_0, KLD and MMLU-2000 on the upstream build complete")
    mac("ptqCpuDone", int(done), "1 = the upstream CPU run of XS as PTQ1_0 (KLD + MMLU-2000) is complete")
    # second run: PrismML's fork (prism 6447906) on CUDA, RTX 4060 laptop, -ngl 999 -ncmoe 14, paired with XS on the
    # CUDA build pub/cuda-vec (49fa8a71e) on the same machine; per-question logs copied from the laptop's result folder
    fd = Path(os.environ.get("PTQ1_FORK_CUDA", str(STATO / "ptq1_fork_cuda_1110")))
    fk, xc = read_mclp(fd / "m4.unix.log"), read_mclp(fd / "xs_cuda_mmlu.unix.log")
    # clean re-run (no parallel task on the laptop; register PTQ1-FORK-CUDA-MMLU-SOLO): it replaces the first log when its
    # per-question log is complete (G17_R4 S3: the switch is derived from the file, not typed)
    clean = read_mclp(fd / "mmlu_solo_1110" / "mmlu.unix.log") if (fd / "mmlu_solo_1110" / "mmlu.unix.log").exists() else None
    if clean is not None and len(clean["gold"]) != NDEV:
        clean = None
    if clean is not None:
        if fk is not None and len(fk["gold"]) == NDEV:
            mac("ptqForkSoloSame", ints(int((clean["choice"] == fk["choice"]).sum())),
                "same chosen answer, clean re-run against the first fork run, of 2000")
        fk = clean
    gold = mm["full"]["XS"]["gold"][:NDEV]
    fork_ok = all(d is not None and len(d["gold"]) == NDEV for d in (fk, xc))
    if fork_ok and not (np.array_equal(fk["gold"], gold) and np.array_equal(xc["gold"], gold)):
        raise SystemExit("PTQ1_0 fork MMLU-2000 gold != XS gold")
    def kld_log(f: Path) -> dict | None:
        if not f.exists():
            return None
        t = f.read_text(errors="replace")
        g = lambda pat: (lambda m_: float(m_.group(1)) if m_ else None)(re.search(pat, t))
        r = dict(kld=g(r"Mean\s+KLD:\s*([0-9.eE-]+)"), top=g(r"Same top p:\s*([0-9.]+)"),
                 ppl=g(r"Mean PPL\(Q\)\s*:\s*([0-9.]+)"), pplx=g(r"Mean PPL\(base\)\s*:\s*([0-9.]+)"))
        return r if all(v is not None for v in r.values()) else None

    def bench1(f: Path) -> dict:
        b = _bench_md(f) if f.exists() else {}
        return next(iter(b.values()), {}) if b else {}

    kc = kld_log(fd / "kld_ptq1_fork_vs_xs.log")
    bf, bx = bench1(fd / "bench_ptq1_fork.txt"), bench1(fd / "bench_xs_cudavec.txt")
    fork_ok = fork_ok and kc is not None and all("tg128" in b and "pp512" in b for b in (bf, bx))
    mac("ptqForkDone", int(fork_ok), "1 = XS as PTQ1_0 on PrismML's fork (CUDA, RTX 4060) is complete")
    mac("ptqForkClean", int(clean is not None), "1 = the clean re-run of the fork CUDA MMLU-2000 (no parallel task) is the log used")
    if fork_ok:
        mac("ptqForkMMLU", f2(100 * fk["ok"].mean()), "XS as PTQ1_0 on PrismML's fork, CUDA RTX 4060, MMLU-2000")
        mac("ptqForkXs", f2(100 * xc["ok"].mean()), "XS on pub/cuda-vec, same laptop, MMLU-2000")
        w, l_, pv = mcnemar(xc["ok"], fk["ok"])
        mac("ptqForkWL", f"{w}/{l_}", "PTQ1_0 on the fork against XS on pub/cuda-vec, same laptop")
        mac("ptqForkP", tex_p(pv))
        mac("ptqForkSame", ints(int((xc["choice"] == fk["choice"]).sum())))
        mac("ptqForkRet", f"{100 * fk['ok'].mean() / xc['ok'].mean():.1f}", "% of XS on the same laptop")
        mac("ptqForkKLD", f"{kc['kld']:.6f}", "fork vs XS (pub/cuda-vec), 4x512 wiki, kld_ptq1_fork_vs_xs.log")
        mac("ptqForkTopP", f"{kc['top']:.2f}")
        mac("ptqForkPPL", f"{kc['ppl']:.4f}")
        mac("ptqForkPPLxs", f"{kc['pplx']:.4f}")
        for nm, b in (("", bf), ("Xs", bx)):
            mac(f"ptqFork{nm}Pp", f2(b["pp512"][0]), "llama-bench -ncmoe 14, RTX 4060")
            mac(f"ptqFork{nm}PpSd", f2(b["pp512"][1]))
            mac(f"ptqFork{nm}Tg", f2(b["tg128"][0]))
    # third run: the fork on Vulkan (Radeon 8060S), against XS on the launch engine and our PTQ1_0 Vulkan port
    fv = Path(os.environ.get("PTQ1_FORK_VK", str(STATO / "ptq1_fork_vulkan_1110")))
    kv = kld_log(fv / "kld_prismfork_vk.log")
    bv = {k: bench1(fv / f"bench_{f}_vk.txt") for k, f in (("", "prismfork"), ("Port", "ourport"), ("Xs", "xs_launch"))}
    vk_ok = kv is not None and all("tg128" in b and "pp512" in b for b in bv.values())
    mac("ptqVkfDone", int(vk_ok), "1 = KLD and llama-bench of XS as PTQ1_0 on PrismML's fork, Vulkan, are complete")
    if vk_ok:
        mac("ptqVkfKLD", f"{kv['kld']:.6f}", "fork (Vulkan) vs XS (launch engine), 4x512 wiki")
        mac("ptqVkfTopP", f"{kv['top']:.2f}")
        mac("ptqVkfPPL", f"{kv['ppl']:.4f}")
        mac("ptqVkfPPLxs", f"{kv['pplx']:.4f}")
        for nm, b in bv.items():
            mac(f"ptqVkf{nm}Pp", f2(b["pp512"][0]), "llama-bench Vulkan, Radeon 8060S")
            mac(f"ptqVkf{nm}Tg", f2(b["tg128"][0]))
    if not done:
        WARN.append(f"PTQ1_0 job not complete (conv {conv_ok}, mmlu {mm_ok}, kld {m_kld is not None})")


RULE_PICKS: dict = {}


def recipe_sm_section() -> None:
    """register-only values of the construction of S and M (G17_R1 S2): ricetta_SM.tsv names, for every value, the
    register row and the literal text of that row that carries it; the script checks the text against the register
    (or its shipped extract) and fails on a mismatch"""
    tab = [ln.split("\t") for ln in (HERE / "ricetta_SM.tsv").read_text().splitlines()[1:] if ln.strip()]
    if CICLI.exists():
        raw = CICLI.read_bytes().decode("utf-8", "replace").split("\n")
        rows = {i + 1: r for i, r in enumerate(raw)}
    else:
        rows = {int(ln.split("\t", 1)[0]): ln.split("\t", 1)[1] for ln in
                CICLI_EXTRACT.read_text(errors="replace").splitlines() if "\t" in ln}
    for key, val, row, txt, what in tab:
        r = rows.get(int(row), "")
        if txt not in r:
            raise SystemExit(f"ricetta_SM.tsv: {key}: text {txt!r} not in register row {row}")
        mac(key, val, f"{what}; register row {row}")


def root_cost_section() -> None:
    """lower bound of the APU-GPU hours of the root's direct ancestry after the forge (radice_costo.tsv: stage times read
    from the register; every start row must exist and carry the stated date), G19_R1"""
    tab = [ln.split("\t") for ln in (HERE / "radice_costo.tsv").read_text().splitlines()[1:] if ln.strip()]
    if CICLI.exists():
        reg = {i + 1: r_ for i, r_ in enumerate(CICLI.read_bytes().decode("utf-8", "replace").split("\n"))}
    else:
        reg = {int(ln.split("\t", 1)[0]): ln.split("\t", 1)[1] for ln in
               CICLI_EXTRACT.read_text(errors="replace").splitlines() if "\t" in ln}
    for r in tab:
        for k in (int(r[1]), int(r[2])):
            if k not in reg:
                raise SystemExit(f"radice_costo.tsv: register row {k} missing")
        if not reg[int(r[1])].startswith(r[3]):
            raise SystemExit(f"radice_costo.tsv: row {r[1]} is not dated {r[3]}")
    gpu = sum(float(r[5]) for r in tab)
    mac("rootGpuHoursLB", f"{math.floor(gpu)}", "lower bound of APU-GPU hours, root ancestry after the forge (radice_costo.tsv)")
    # recorded compute of the construction of S and M before their final step (costo_SM.tsv, G20_R5): every row must
    # carry "in <minutes> min" in the register
    ct = [ln.split("\t") for ln in (HERE / "costo_SM.tsv").read_text().splitlines()[1:] if ln.strip()]
    for r in ct:
        if f"in {r[1]} min" not in reg.get(int(r[0]), ""):
            raise SystemExit(f"costo_SM.tsv: 'in {r[1]} min' not in register row {r[0]}")
    apu = sum(int(r[1]) for r in ct if r[2] == "APU GPU") / 60
    mac("smAllocApuH", f"{apu:.0f}", "recorded APU-GPU hours of the construction of S and M before the final step")
    mac("smAllocLaptopH", f"{sum(int(r[1]) for r in ct if r[2] == 'laptop GPU') / 60:.1f}", "laptop GPU hours, same")
    for hh in ("A", "B", "shared"):
        mac(f"smAlloc{hh.capitalize()}H", f"{sum(int(r[1]) for r in ct if r[3] == hh and r[2] == 'APU GPU') / 60:.1f}")
    # stratified second test sample: overlap with MMLU-2000 (G19_R2)
    f_ = Path(FORGE) / "mc_v2" / "mmlu2000_strat.indice.tsv"
    if f_.exists():
        idx = [int(ln.split("\t")[1]) for ln in f_.read_text().splitlines() if ln and not ln.startswith("#")]
        mac("stratN", ints(len(idx)), "questions of the stratified sample")
        mac("stratOverlap", ints(sum(1 for i in idx if i < NDEV)), "of them inside MMLU-2000")


def m_stop_readings() -> None:
    """M's development history from the curated table storia_arresto_M.tsv (G16_R1 B1): every row names the register
    row it comes from; the dates are checked against the register. The rule's picks of the last steps of S and M are
    still read from the register rows of the selection loss."""
    tab = [ln.split("\t") for ln in (HERE / "storia_arresto_M.tsv").read_text().splitlines()[1:] if ln.strip()]
    # dates AND scores are checked against the register, or against the shipped extract in bundle mode (G18_R4 m7)
    if CICLI.exists():
        reg = {i + 1: r_ for i, r_ in enumerate(CICLI.read_bytes().decode("utf-8", "replace").split("\n"))}
    else:
        reg = {int(ln.split("\t", 1)[0]): ln.split("\t", 1)[1] for ln in
               CICLI_EXTRACT.read_text(errors="replace").splitlines() if "\t" in ln}
    for r in tab:
        row = reg.get(int(r[1]))
        if row is None:
            raise SystemExit(f"storia_arresto_M.tsv: register row {r[1]} missing (register and extract)")
        if not row.startswith(r[0]):
            raise SystemExit(f"storia_arresto_M.tsv: row {r[1]} is not dated {r[0]} in the register")
        sc = r[5]
        if sc != "-" and sc not in row and sc.replace(".", ",") not in row:
            blk = [(float(x.replace(",", ".")), int(n_)) for n_, x in
                   re.findall(r"\bA \d{5} (\d+) Final result: ([0-9.,]+)", row)]
            tot = sum(n_ for _, n_ in blk)
            if not tot or f"{sum(x * n_ for x, n_ in blk) / tot:.2f}" != sc:
                raise SystemExit(f"storia_arresto_M.tsv: score {sc} not found in register row {r[1]}")
    mon = {"10": "Oct", "11": "Nov", "09": "Sep"}
    def day(t):
        return f"{int(t[8:10])} {mon.get(t[5:7], t[5:7])}"
    reads = [r for r in tab if r[5] != "-" and r[4] in ("14042", "12042")]
    mac("mStopN", len(reads), "full-test (or outside-12,042) readings of the weights of M's line, storia_arresto_M.tsv")
    mac("mStopList", "; ".join(f"{day(r[0])}: {r[5]} ({r[2]}, {r[3]}"
                               + (", 12,042 questions outside MMLU-2000" if r[4] == "12042" else "") + ")" for r in reads))
    find = lambda pat: next((r for r in tab if pat in r[6]), None)
    for key, pat in (("mTargetDate", "first stated"), ("mTargetConfirmDate", "confirmed"), ("mTargetRestateDate", "restated"),
                     ("mDevReachDate", "reached on the development subset"), ("mDeclareDate", "declared met"),
                     ("mReachFullDate", "M reaches the target")):
        r = find(pat)
        if r:
            mac(key, day(r[0]))
    r = find("could not finish before")
    if r:
        mac("mDeadlineDate", f"{day(r[0])}, 22:23", "decision not to run the alternative host A-NUOVO (deadline 7 Nov)")
    r = find("M fixed on MMLU-2000")
    if r:
        mac("mFixDate", day(r[0]), "M's line fixed (A-POST step 50 chosen), register row " + r[1])
        mac("mStopBeforeFixN", sum(1 for x in reads if x[0] < r[0]), "full-test readings of M's line before M was fixed")
        mac("mStopAfterFixN", sum(1 for x in reads if x[0] > r[0]), "full-test readings after M was fixed")
    mac("mTargetQtwo", "78.15", "Q2_K's MMLU-2000 score on which the target 80.05 = 78.15 + 2 sigma was defined")
    # the same 80.05 read against the full test (G18_R2 S1): as a share of the teacher and as a distance above Q2_K
    v_ = {n_: val for n_, val, _ in MACROS}
    try:
        te_, q2_ = float(v_["teMMLU"]), float(v_["bqtwoMMLU"])
        mac("mTargetRetFull", f"{100 * 80.05 / te_:.2f}", "TEACHER-PCT 80.05 as % of the teacher's full-test score")
        mac("mTargetOverQtwoFull", f"{80.05 - q2_:.2f}", "80.05 minus Q2_K's full-test score, points")
        se_ = 100 * math.sqrt(q2_ / 100 * (1 - q2_ / 100) / NFULL)
        mac("mTargetOverQtwoFullSe", f"{(80.05 - q2_) / se_:.0f}", "that distance in binomial SEs of a full-test score")
    except (KeyError, ValueError):
        WARN.append("mTargetRetFull: teacher or Q2_K full-test macro missing")
    rows = register_rows()
    for row in rows:
        c = row.split("\t")
        if len(c) < 3:
            continue
        mp = re.match(r"CARDAN-CONGIUNTO (A|B)-POST: passo (\d+) .*migliore \(([0-9.]+), (\d+)\)", c[2])
        if mp:
            key = "ruleApostStep" if mp.group(1) == "A" else "ruleBpostStep"
            RULE_PICKS.setdefault(key, []).append((c[0], int(mp.group(2)), int(mp.group(4))))
    for key, picks in RULE_PICKS.items():
        ends = [b for i, (_, st, b) in enumerate(picks) if i == len(picks) - 1 or picks[i + 1][1] <= st]
        mac(key, " and then ".join(str(x) for x in dict.fromkeys(ends)),
            "step picked by the registered rule (KL24 + paper loss) at the end of each run of the last step (register)")
        before = [b for t, _, b in picks if t < "2026-11-03"]
        if before and key == "ruleBpostStep":
            mac("ruleBpostStepFirst", before[-1], "the rule's pick when S was fixed (run to step 150, before the continuation)")


def microbatch_section() -> None:
    """micro-batch shares of likelihood scoring from microbatch_shares.json, written by microbatch_shares.py (scripts/ in the bundle, strumenti/ in our tree)
    (shipped): items with micro-batches of <= 8 tokens, and scored rows in <= 8-column head products"""
    f = HERE / "microbatch_shares.json"
    if not f.exists():
        WARN.append("microbatch_shares.json missing: run microbatch_shares.py")
        return
    d = json.loads(f.read_text())
    names = {"arc_easy": "Arce", "arc_challenge": "Arcc", "openbookqa": "Obqa", "boolq": "Boolq", "truthfulqa_mc1": "Tqa",
             "piqa_full": "Piqa", "mmlu_pro_mc": "Mmlupro", "mmlu_full": "Mmlu", "hellaswag": "Hs"}
    multi = ("arc_easy", "arc_challenge", "openbookqa", "truthfulqa_mc1", "piqa_full", "hellaswag")
    for k, nm in names.items():
        if k not in d:
            continue
        r = d[k]
        mac(f"mb{nm}Items", ints(r["items_body"]), f"{k}: items with a micro-batch of <= 8 tokens")
        mac(f"mb{nm}ItemsPct", f"{100 * r['items_body'] / r['items']:.1f}")
        mac(f"mb{nm}RowsPct", f"{100 * r['out_mv'] / max(1, r['out']):.1f}", f"{k}: scored rows in <= 8-column products")
    body = [100 * d[k]["items_body"] / d[k]["items"] for k in multi + ("boolq",) if k in d]
    rows = [100 * d[k]["out_mv"] / d[k]["out"] for k in multi if k in d]
    toks = [100 * d[k]["rel_small"] / d[k]["rel"] for k in multi + ("boolq",) if k in d]
    if body:
        mac("mbItemsLo", f"{min(body):.0f}", "range over BoolQ and the multi-token tasks")
        mac("mbItemsHi", f"{max(body):.0f}")
        mac("mbRowsLo", f"{min(rows):.0f}")
        mac("mbRowsHi", f"{max(rows):.0f}")
        mac("mbToksLo", f"{min(toks):.0f}")
        mac("mbToksHi", f"{max(toks):.0f}")


def c4_section() -> None:
    """top-1 agreement with the Q8_0 teacher on C4 validation text (llama-perplexity "Same top p", 20 chunks of 4,096
    tokens), RTX 4060 laptop, build of unrecorded commit (eng275), 30-31 Oct; logs stato/top1_c4_1031/<name>.out.
    These are the hosts before their last step (A, B, C's parent line), not the released files."""
    d = STATO / "top1_c4_1031"
    names = {"A_CARDAN_FED": "A", "B": "B", "C_T400POST": "C", "IQ2XXS_mixB": "Mix", "IQ2_XXS": "Iqtwo", "Q2_K": "Qtwo",
             "Q3_K_M": "Qthree", "Q4_K_M": "Qfour"}
    n = 0
    for f, nm in names.items():
        p_ = d / f"{f}.out"
        m_ = re.findall(r"Same top p:\s*([0-9.]+)", p_.read_text(errors="replace")) if p_.exists() else []
        if m_:
            mac(f"cfour{nm}", f2(float(m_[-1])), f"top-1 agreement with the teacher on C4, {f} (laptop CUDA, pre-release)")
            n += 1
    mac("cfourDone", int(n == len(names)))
    # the same-backend set (APU, Vulkan; G17_R1 m7): the teacher reference was computed there; A and B fail to load
    for f, nm in names.items():
        p_ = d / f"c_{f}.out"
        m_ = re.findall(r"Same top p:\s*([0-9.]+)", p_.read_text(errors="replace")) if p_.exists() else []
        mac(f"cfourVk{nm}", f2(float(m_[-1])) if m_ else r"\textit{n/a}",
            f"top-1 agreement on C4, {f}, APU Vulkan (same backend as the reference)" + ("" if m_ else ": failed to load"))


def c4_released_section() -> None:
    """top-1 agreement on C4 of the RELEASED files and of Q2_K / IQ2_XXS, one CUDA session on the RTX 4060 laptop
    (pub/cuda-vec, teacher reference basec4.kld of 31 Oct), stato/c4_rilasciati_1110/<file>.out (G18_R5 S2).
    S and M are the benchmarked copies, whose tensors are byte-identical to the released files."""
    d = STATO / "c4_rilasciati_1110"
    names = {"Thor-T-35B-A3B-XS": "Xs", "Thor-T-S-packed-testaXS": "Sm", "Thor-T-M-packed-testaXS": "Md",
             "Ornith-1.5-35B-A3B-Q2_K": "Qtwo", "Ornith-1.5-35B-A3B-IQ2_XXS": "Iqtwo"}
    n = 0
    for f, nm in names.items():
        p_ = d / f"{f}.out"
        t = p_.read_text(errors="replace") if p_.exists() else ""
        m_ = re.findall(r"Same top p:\s*([0-9.]+)", t)
        k_ = re.findall(r"Mean\s+KLD:\s*([0-9.eE-]+)", t)
        if m_:
            mac(f"cfourRel{nm}", f2(float(m_[-1])), f"top-1 agreement on C4, released {f} (laptop CUDA, one session)")
            n += 1
        else:
            mac(f"cfourRel{nm}", r"\textit{running}", "PENDING-RUN")
        if k_:
            mac(f"cfourRelKld{nm}", f"{float(k_[-1]):.4f}", f"mean KLD to the teacher on C4, {f}")
        r_ = re.findall(r"Mean PPL\(Q\)/PPL\(base\)\s*:\s*([0-9.]+)", t)
        if r_:
            mac(f"cfourRelPplR{nm}", f"{float(r_[-1]):.3f}", f"perplexity ratio to the teacher on C4, {f}")
    mac("cfourReleasedDone", int(n == len(names)), "1 = C4 agreement of the released XS, S, M and of Q2_K, IQ2_XXS measured")
    # the copies measured on the laptop (certutil there) against the originals on the main machine (sha256sum): all
    # five must match, or the run stops (round 19c)
    fa, fc = d / "sha256_aragorn.txt", d / "sha256_corsair.txt"
    if fa.exists() and fc.exists():
        ta = fa.read_text(errors="replace")
        lap = {}
        for m2 in re.finditer(r"SHA256 hash di .*?\\([^\\\r\n]+\.gguf):\s*([0-9a-f]{64})", ta):
            lap[m2.group(1)] = m2.group(2)
        main_ = set(re.findall(r"\b([0-9a-f]{64})\b", fc.read_text(errors="replace")))
        bad = [k for k, v in lap.items() if v not in main_]
        if len(lap) != len(names) or bad:
            raise SystemExit(f"C4 laptop copies: sha256 mismatch or missing ({bad or len(lap)})")
        mac("cfourShaOk", 1, "the five files measured on the laptop are byte-identical to those on the main machine")
        for f_, nm in names.items():
            if f_ + ".gguf" in lap:
                mac(f"cfourSha{nm}", lap[f_ + ".gguf"][:16], f"sha256 prefix of {f_}.gguf as measured on the laptop")
    else:
        mac("cfourShaOk", 0, "sha256 of the laptop copies not available")
    # paired chunk-level differences (G19_R2 S1): llama-perplexity prints cumulative means per chunk of equal size, so
    # chunk k's own value is k*cum_k - (k-1)*cum_{k-1}; t interval over the chunks
    def per_chunk_col(f_: str, col: int) -> list:
        """per-chunk values of column col (0 PPL, 1 ln ratio, 2 KL, 3 dp RMS, 4 same top p) from the cumulative table"""
        p_ = d / f"{f_}.out"
        if not p_.exists():
            return []
        cum = []
        for ln in p_.read_text(errors="replace").splitlines():
            if re.match(r"^\s+\d+\s", ln):
                v = re.findall(r"(-?[0-9.]+)\s*±", ln)
                if len(v) >= 5:
                    cum.append(float(v[col]))
        return [(k + 1) * c - k * (cum[k - 1] if k else 0.0) for k, c in enumerate(cum)]

    def per_chunk(f_: str) -> list:
        p_ = d / f"{f_}.out"
        if not p_.exists():
            return []
        cum = [float(m2.group(1)) for ln in p_.read_text(errors="replace").splitlines()
               if re.match(r"^\s+\d+\s", ln) for m2 in [re.search(r"([0-9.]+) ±\s+[0-9.]+ %\s*$", ln)] if m2]
        return [(k + 1) * c - k * (cum[k - 1] if k else 0.0) for k, c in enumerate(cum)]
    T975 = {9: 2.262, 14: 2.145, 19: 2.093, 24: 2.064, 29: 2.045}   # t quantiles (no SciPy dependency)
    for nm, a_, b_ in (("MdQtwo", "Thor-T-M-packed-testaXS", "Ornith-1.5-35B-A3B-Q2_K"),
                       ("SmIqtwo", "Thor-T-S-packed-testaXS", "Ornith-1.5-35B-A3B-IQ2_XXS")):
        x_, y_ = per_chunk(a_), per_chunk(b_)
        if len(x_) == len(y_) and len(x_) >= 3:
            dd_ = np.array(x_) - np.array(y_)
            m_, h_ = float(dd_.mean()), float(T975.get(len(dd_) - 1, 1.96) * dd_.std(ddof=1) / math.sqrt(len(dd_)))
            sg = lambda v: f"{v:+.2f}".replace("-", "$-$")
            mac(f"cfourDiff{nm}", sg(m_), "paired chunk-level difference of C4 top-1 agreement, points")
            mac(f"cfourDiff{nm}Lo", sg(m_ - h_), "95 % t interval over the chunks")
            mac(f"cfourDiff{nm}Hi", sg(m_ + h_))
            mac(f"cfourDiff{nm}Pos", int((dd_ > 0).sum()), "chunks in which ours agrees more")
            mac(f"cfourDiff{nm}N", len(dd_))
            for tag, col, fn in (("Kld", 2, lambda v: v), ("PplR", 1, lambda v: v)):   # PplR: ln PPL ratio
                xa, ya = [fn(v) for v in per_chunk_col(a_, col)], [fn(v) for v in per_chunk_col(b_, col)]
                if len(xa) == len(ya) == len(dd_):
                    e_ = np.array(xa) - np.array(ya)
                    me, he = float(e_.mean()), float(T975.get(len(e_) - 1, 1.96) * e_.std(ddof=1) / math.sqrt(len(e_)))
                    sg4 = lambda v: f"{v:+.4f}".replace("-", "$-$")
                    mac(f"cfourDiff{tag}{nm}", sg4(me), f"paired chunk-level difference of {tag} on C4 (ours minus standard)")
                    mac(f"cfourDiff{tag}{nm}Lo", sg4(me - he))
                    mac(f"cfourDiff{tag}{nm}Hi", sg4(me + he))
                    mac(f"cfourDiff{tag}{nm}Better", int((e_ < 0).sum()), "chunks in which ours is lower (better)")
    if n < len(names):
        WARN.append("C4 agreement of the released files: running (stato/c4_rilasciati_1110)")


def host_a_section(mm: dict) -> None:
    """full MMLU of M's host A on the launch engine (int8 1), paired with M (G18_R2 S2): esiti_finale_1107/OSPITE_A"""
    a_ = read_blocks([FIN / "OSPITE_A" / "mmlu_blocchi" / f"mmlu_{b}.log" for b in BLOCKS])
    m_ = mm["full"].get("M")
    ok = a_ is not None and m_ is not None and np.array_equal(a_["gold"], m_["gold"])
    mac("hostAFullDone", int(ok), "1 = full MMLU of M's host A on the launch engine, paired with M")
    if ok:
        mac("hostAFull", f2(100 * a_["ok"].mean()), "M's host A, full MMLU, launch engine, int8 1")
        w, l_, pv = mcnemar(a_["ok"], m_["ok"])
        mac("hostAvsMWL", f"{w}/{l_}", "M wins/losses against its host A, full MMLU, same engine")
        mac("hostAvsMP", tex_p(pv))
        mac("hostAvsMDiff", f"{100 * (m_['ok'].mean() - a_['ok'].mean()):+.2f}".replace("-", "$-$"), "M minus A, points")
    else:
        mac("hostAFull", r"\textit{running}", "PENDING-RUN")
        WARN.append("full MMLU of M's host A on the launch engine: running (esiti_finale_1107/OSPITE_A)")


def strat_outside_section() -> None:
    """second test sample (stratified, 2,000 questions) restricted to the questions outside MMLU-2000, each last-step
    checkpoint of A and B against its host, Holm over the three checkpoints of each host (G20_R2)"""
    idx_f = Path(FORGE) / "mc_v2" / "mmlu2000_strat.indice.tsv"
    sd = Path(BENCH) / "strat"
    if not idx_f.exists() or not sd.exists():
        return
    full_idx = np.array([int(ln.split("\t")[1]) for ln in idx_f.read_text().splitlines() if ln and not ln.startswith("#")])
    keep = full_idx >= NDEV
    mac("stratOutN", ints(int(keep.sum())), "stratified questions outside MMLU-2000")
    for host, pre in (("A", "stratA"), ("B", "stratB")):
        base = read_mclp(sd / f"{host}-base.log")
        rows = []
        for st in (50, 100, 150):
            x = read_mclp(sd / f"{host}-POST-T{st}.log")
            if base is None or x is None or len(x["gold"]) != len(keep):
                continue
            w, l_, pv = mcnemar(base["ok"][keep], x["ok"][keep])
            rows.append((st, w, l_, pv))
        hp = holm([r[3] for r in rows])
        wn = {50: "Fifty", 100: "Hundred", 150: "OneFifty"}
        for k, ((st, w, l_, pv), h) in enumerate(zip(rows, hp)):
            st = wn[st]
            mac(f"{pre}Out{st}WL", f"{w}/{l_}", f"{host}-POST step {st} against {host}, stratified, outside MMLU-2000")
            mac(f"{pre}Out{st}P", tex_p(pv))
            mac(f"{pre}Out{st}Holm", tex_p(h))


def q4km_launch_section(mm: dict) -> None:
    """Q4_K_M full MMLU on the launch engine, paired with M (queued, G20_R2): esiti_finale_1107/Q4_K_M/mmlu_blocchi"""
    q = read_blocks([FIN / "Q4_K_M" / "mmlu_blocchi" / f"mmlu_{b}.log" for b in BLOCKS])
    m_ = mm["full"].get("M")
    ok = q is not None and m_ is not None and np.array_equal(q["gold"], m_["gold"])
    mac("qfourLEDone", int(ok), "1 = Q4_K_M full MMLU on the launch engine, paired with M")
    if ok:
        mac("qfourLE", f2(100 * q["ok"].mean()), "Q4_K_M, full MMLU, launch engine")
        w, l_, pv = mcnemar(q["ok"], m_["ok"])
        mac("mdVsQfourLEWL", f"{w}/{l_}", "M wins/losses against Q4_K_M, same engine")
        mac("mdVsQfourLEP", tex_p(pv))
        mac("mdVsQfourLEDiff", f"{100 * (m_['ok'].mean() - q['ok'].mean()):+.2f}".replace("-", "$-$"))
        lo, hi = boot_diff(q["ok"], m_["ok"], SEED + 41)
        mac("mdVsQfourLELo", f"{lo:+.2f}".replace("-", "$-$"), "bootstrap 95 % CI of M minus Q4_K_M, same engine")
        mac("mdVsQfourLEHi", f"{hi:+.2f}".replace("-", "$-$"))
        clo_, chi_ = cluster_boot_diff(q["ok"], m_["ok"], SUBJ_ALL, SEED + 42)
        mac("mdVsQfourLEClLo", f"{clo_:+.2f}".replace("-", "$-$"), "M minus Q4_K_M, same engine, by-subject bootstrap")
        mac("mdVsQfourLEClHi", f"{chi_:+.2f}".replace("-", "$-$"))
        ten = int(str(dict((n, v) for n, v, _ in MACROS)["teMMLUn"]).replace(",", ""))
        mac("qfourLERet", f2(100 * int(q["ok"].sum()) / ten), "Q4_K_M as % of the teacher, launch engine (counts)")
    else:
        WARN.append("Q4_K_M full MMLU on the launch engine: queued (esiti_finale_1107/Q4_K_M)")


def q2zero_section() -> None:
    """XS stored as upstream Q2_0 with the Hadamard metadata (stock llama.cpp route, G15_R3 S1). The measurement
    (bit-exact check, KLD, paired MMLU-2000, speed, file size) is not yet parsed: the switch stays 0 until its raw files
    in stato/q2_0_upstream_1110/ are wired here."""
    d = STATO / "q2_0_upstream_1110"
    conv = (d / "conv.log").read_text(errors="replace") if (d / "conv.log").exists() else ""
    m_ = re.search(r"OK: (\d+) weights repacked TQ1_0R_1024 -> Q2_0, every block bit-identical", conv)
    mac("qtwoZeroConvDone", int(bool(m_)), "1 = XS converted to upstream Q2_0, every block bit-identical in d*q")
    if m_:
        mac("qtwoZeroWeights", f"{int(m_.group(1)) / 1e9:.1f}", "G weights repacked")
        info = dict(ln.split("\t", 1) for ln in (d / "file.tsv").read_text().splitlines() if "\t" in ln) \
            if (d / "file.tsv").exists() else {}
        if "bytes" in info:
            b = int(info["bytes"])
            mac("qtwoZeroBytes", ints(b), "file size of XS as Q2_0")
            mac("qtwoZeroGiB", f2(b / GIB))
            mac("qtwoZeroSha", info.get("sha256", "")[:8])
    mac("qtwoZeroDone", 0, "1 = KLD, MMLU-2000 and speed of XS as Q2_0 on stock upstream measured on Vulkan (APU)")
    # CUDA run (W5): stock upstream master 9d340ec (only a print patch for the MCLP lines), RTX 4060 laptop,
    # -ngl 999 -ncmoe 14; paired with XS on our CUDA build pub/cuda-vec (49fa8a71e) on the same laptop, whose MMLU-2000
    # log is the one of the PrismML-fork comparison (same file, same machine). Register 2026-11-10T06:07/06:09.
    # stock upstream 9d340ec with VULKAN on the RTX 4060 (second vendor), same laptop, paired with XS on our CUDA build
    dv = d / "vulkan_rtx"
    qv = read_mclp(dv / "mmlu2000_q2_0_upstream_vk_rtx.log") if (dv / "mmlu2000_q2_0_upstream_vk_rtx.log").exists() else None
    xv = read_mclp(STATO / "ptq1_fork_cuda_1110" / "xs_cuda_mmlu.unix.log")
    tv = (dv / "kld_q2_0_upstream_vk_rtx.log").read_text(errors="replace") if (dv / "kld_q2_0_upstream_vk_rtx.log").exists() else ""
    gv = lambda pat: (lambda m2: float(m2.group(1)) if m2 else None)(re.search(pat, tv))
    klv = dict(kld=gv(r"Mean\s+KLD:\s*([0-9.eE-]+)"), top=gv(r"Same top p:\s*([0-9.]+)"),
               ppl=gv(r"Mean PPL\(Q\)\s*:\s*([0-9.]+)"), pplx=gv(r"Mean PPL\(base\)\s*:\s*([0-9.]+)"))
    btx = (dv / "bench_q2_0_upstream_vk_rtx.txt").read_text(errors="replace") if (dv / "bench_q2_0_upstream_vk_rtx.txt").exists() else ""
    bvk = {k: re.search(k + r"\s*\|\s*([0-9.]+) ± ([0-9.]+)", btx) for k in ("pp512", "tg128")}
    okv = (qv is not None and xv is not None and len(qv["gold"]) == NDEV and len(xv["gold"]) == NDEV
           and np.array_equal(qv["gold"], xv["gold"]) and all(v is not None for v in klv.values())
           and all(bvk.values()) and "Vulkan0" in btx and "NVIDIA" in btx)
    mac("qtwoZeroVkRtxDone", int(okv), "1 = XS as Q2_0 measured on stock upstream VULKAN on the RTX 4060 (NVIDIA)")
    if okv:
        w, l_, pv = mcnemar(xv["ok"], qv["ok"])
        mac("qtwoZeroVkMMLU", f2(100 * qv["ok"].mean()), "XS as Q2_0, stock upstream 9d340ec, Vulkan on the RTX 4060, MMLU-2000")
        mac("qtwoZeroVkXs", f2(100 * xv["ok"].mean()), "XS on pub/cuda-vec, same laptop")
        mac("qtwoZeroVkWL", f"{w}/{l_}", "Q2_0 (upstream Vulkan) wins/losses against XS")
        mac("qtwoZeroVkP", tex_p(pv))
        mac("qtwoZeroVkKLD", f"{klv['kld']:.6f}", "Q2_0 (upstream Vulkan, RTX 4060) vs XS (pub/cuda-vec)")
        mac("qtwoZeroVkPPL", f"{klv['ppl']:.4f}")
        mac("qtwoZeroVkPPLxs", f"{klv['pplx']:.4f}")
        mac("qtwoZeroVkPp", f2(float(bvk["pp512"].group(1))), "llama-bench, -ncmoe 14")
        mac("qtwoZeroVkTg", f2(float(bvk["tg128"].group(1))))
    else:
        WARN.append("Q2_0 on stock upstream Vulkan (RTX 4060): not complete")
    dc = d / "cuda"
    q = read_mclp(dc / "mmlu.unix.log") if (dc / "mmlu.unix.log").exists() else None
    xc = read_mclp(STATO / "ptq1_fork_cuda_1110" / "xs_cuda_mmlu.unix.log")
    t = (dc / "kld_q2_0_upstream_cuda.log").read_text(errors="replace") if (dc / "kld_q2_0_upstream_cuda.log").exists() else ""
    g = lambda pat: (lambda m2: float(m2.group(1)) if m2 else None)(re.search(pat, t))
    kl = dict(kld=g(r"Mean\s+KLD:\s*([0-9.eE-]+)"), top=g(r"Same top p:\s*([0-9.]+)"),
              ppl=g(r"Mean PPL\(Q\)\s*:\s*([0-9.]+)"), pplx=g(r"Mean PPL\(base\)\s*:\s*([0-9.]+)"))
    bq = next(iter(_bench_md(dc / "bench_q2_0_upstream_cuda.txt").values()), {}) if (dc / "bench_q2_0_upstream_cuda.txt").exists() else {}
    bx = next(iter(_bench_md(dc / "bench_xs_cudavec.txt").values()), {}) if (dc / "bench_xs_cudavec.txt").exists() else {}
    ok = (q is not None and xc is not None and len(q["gold"]) == NDEV and len(xc["gold"]) == NDEV
          and all(v is not None for v in kl.values()) and all("tg128" in b and "pp512" in b for b in (bq, bx)))
    mac("qtwoZeroCudaDone", int(ok), "1 = XS as Q2_0 measured on stock upstream CUDA (RTX 4060): KLD, MMLU-2000, speed")
    if ok:
        if not np.array_equal(q["gold"], xc["gold"]):
            raise SystemExit("Q2_0 CUDA MMLU-2000 gold != XS CUDA gold")
        mac("qtwoZeroCuMMLU", f2(100 * q["ok"].mean()), "XS as Q2_0, stock upstream 9d340ec, CUDA RTX 4060, MMLU-2000")
        mac("qtwoZeroCuXs", f2(100 * xc["ok"].mean()), "XS on pub/cuda-vec (49fa8a71e), same laptop, MMLU-2000")
        w, l_, pv = mcnemar(xc["ok"], q["ok"])
        mac("qtwoZeroCuWL", f"{w}/{l_}", "Q2_0 (upstream) wins/losses against XS (pub/cuda-vec), same laptop")
        mac("qtwoZeroCuP", tex_p(pv))
        mac("qtwoZeroCuSame", ints(int((xc["choice"] == q["choice"]).sum())), "same chosen answer, of 2000")
        mac("qtwoZeroCuKLD", f"{kl['kld']:.6f}", "Q2_0 (upstream CUDA) vs XS (pub/cuda-vec), 4x512 wiki")
        mac("qtwoZeroCuTopP", f"{kl['top']:.2f}")
        mac("qtwoZeroCuPPL", f"{kl['ppl']:.4f}")
        mac("qtwoZeroCuPPLxs", f"{kl['pplx']:.4f}")
        for nm, b in (("", bq), ("Xs", bx)):
            mac(f"qtwoZeroCu{nm}Pp", f2(b["pp512"][0]), "llama-bench -ngl 999 -ncmoe 14, RTX 4060, same session")
            mac(f"qtwoZeroCu{nm}PpSd", f2(b["pp512"][1]))
            mac(f"qtwoZeroCu{nm}Tg", f2(b["tg128"][0]))
            mac(f"qtwoZeroCu{nm}TgSd", f2(b["tg128"][1]))
    # KL of M against M on the same laptop with only our own CUDA kernel variant changing (stato/cudavec_b: the file is
    # Thor-T-M-packed-testaXS.gguf at -ncmoe 26, 2 chunks; G18_R6 S1): NOT a floor for the XS/Q2_0 run (-ncmoe 14, 4
    # chunks), which has no matched floor yet (\xsFloorDone)
    fl = []
    for f_ in sorted((STATO / "cudavec_b").glob("kld_*_ub*.log")):
        t_ = f_.read_text(errors="replace")
        mk, mt = re.search(r"Mean\s+KLD:\s*([0-9.eE-]+)", t_), re.search(r"Same top p:\s*([0-9.]+)", t_)
        if mk and mt:
            fl.append((float(mk.group(1)), float(mt.group(1))))
    if fl:
        mac("kldFloorN", len(fl), "M-vs-M KL runs on the RTX 4060 (-ncmoe 26, 2 chunks), our kernel variants only")
        mac("kldFloorLo", f"{min(k for k, _ in fl):.4f}")
        mac("kldFloorHi", f"{max(k for k, _ in fl):.4f}")
        mac("kldFloorTopLo", f2(min(t for _, t in fl)))
        mac("kldFloorTopHi", f2(max(t for _, t in fl)))
    mac("xsFloorDone", 0, "1 = matched XS-vs-XS KL floor at the Q2_0 settings measured (-ncmoe 14, 4 chunks)")
    mac("xsFloorKld", r"\textit{pending}", "PENDING-RUN")
    # token budgets of the final steps and of the single-plane line (hand-entered from the training logs and the recipe,
    # app:method "Training budget", app:s-recipe; listed among the hand-entered numbers of the Reproducibility section)
    for n_, v_ in (("tokXs", "8.2"), ("tokSm", "2.05"), ("tokSmRel", "0.82"), ("tokMd", "1.36"), ("tokMdRel", "0.41")):
        mac(n_, v_, "M tokens, hand-entered (training logs, recipe)")
    mac("matchAllocDone", 0, "1 = matched simple-allocation control at M's bytes measured (paired full MMLU); in preparation")
    WARN.append("Q2_0 route of XS: KLD/MMLU-2000/speed on stock upstream Vulkan (APU) still pending")


def speed_drift() -> None:
    """how much faster the launch engine decodes than the 7 Nov binary (5d2e382a9), per file, from existing macros"""
    v = {n: val for n, val, _ in MACROS}
    pairs = [("xsSesVkTg", "vsevxsITg"), ("smSesVkTg", "vsevsmITg"), ("mdSesVkTg", "vsevmdITg")]
    try:
        r = [100 * (float(v[a]) / float(v[b]) - 1) for a, b in pairs]
        q = 100 * (float(v["bqfourSesVkTg"]) / float(v["vsevqfourBTg"]) - 1)
    except (KeyError, ValueError):
        WARN.append("speed drift: session macros missing")
        return
    mac("vsevTernLo", f"{min(r):.0f}", "launch engine vs 7 Nov binary, ternary decode, % faster (min)")
    mac("vsevTernHi", f"{max(r):.0f}")
    mac("vsevQfourChg", f"{q:.1f}", "same for Q4_K_M, %")
    try:
        mac("vsevXsFloatChg", f"{100 * (float(v['xsVkTg']) / float(v['vsevxsBTg']) - 1):.1f}",
            "XS float path: final-bench launch engine vs 7 Nov binary, %")
    except (KeyError, ValueError):
        pass


def derived_literals() -> None:
    """numbers the text used to type by hand, derived from macros already computed (G8_R1 m2/m6)"""
    v = {n: val for n, val, _ in MACROS}

    def num(k):
        return float(str(v[k]).replace(",", ""))
    try:
        mac("biqtwoOverSmGiB", f2(num("biqtwoGiB") - num("smGiB")), "IQ2_XXS minus S, GiB")
        mac("biqtwoOverXsGiB", f"{num('biqtwoGiB') - num('xsGiB'):.1f}", "IQ2_XXS minus XS, GiB")
        mac("priorGainPts", f2(100 * num("priorGainNet") / NFULL), "last step on T400, full test, points")
        if WINO_BAD is not None:
            mac("winoBadN", WINO_BAD, "Winogrande items scored through the engine's wrong-first-logits branch")
            mac("winoKeepN", ints(int(WINO_KEEP.sum())))
        prov = {"MMLU": int(v.get("teMMLUsame", "0") == "1"), **TE_PROV}
        def lst(xs):
            xs = list(xs)
            return "none" if not xs else xs[0] if len(xs) == 1 else ", ".join(xs[:-1]) + " and " + xs[-1]
        mac("teLaunchTasks", lst(k for k, x in prov.items() if x), "teacher references on the launch engine")
        mac("teEarlierTasks", lst(k for k, x in prov.items() if not x), "teacher references on an earlier build")
        mac("teEarlierN", sum(1 for x in prov.values() if not x), "number of teacher references on an earlier build")
        mac("teSuiteAnyEarlier", int(any(not v for k, v in TE_PROV.items() if k not in ("GSM8K", "IFEval", "MATH-500"))),
            "1 if some likelihood task still has an earlier-build teacher (the double-dagger footnote is needed)")
        if TE_DRIFT:
            lab, dlt, ch, n, key = max(TE_DRIFT, key=lambda r: abs(r[1]))
            mac("teDriftMaxTask", lab, "largest teacher drift between the earlier build and the launch engine")
            mac("teDriftMaxPts", f"{dlt:+.2f}".replace("-", "$-$"))
            mac("teDriftMaxChanged", ints(ch), "answers changed" if key == "choice" else "correctness changed")
            mac("teDriftMaxN", ints(n))
            md_gap = abs(float(v.get("mdMMLUdiff", "0").replace("$-$", "-")))
            if md_gap > 0:
                mac("teDriftRatio", f"{abs(dlt) / md_gap:.1f}", "largest teacher drift (another task) over |M - teacher| on MMLU")
            mac("teDriftList", "; ".join(f"{a} " + f"{b:+.2f}".replace("-", "$-$") +
                                        f" ({c:,}/{d:,} {'answers' if k_ == 'choice' else 'correctness'})"
                                        for a, b, c, d, k_ in sorted(TE_DRIFT, key=lambda r: -abs(r[1]))),
                "per-task teacher drift, points (changed/items)")
        q2 = v.get("qtwoDone") == "1"
        mac("bqtwoScore", v["bqtwoMMLU"] if q2 else v["bqtwoCuda"], "Q2_K full MMLU, best available engine")
        mac("bqtwoScoreRet", v["bqtwoRet"] if q2 else v["bqtwoCudaRet"], "TEACHER-PCT")
        mac("bqtwoWhere", "on the launch engine" if q2 else
            "on an earlier build on the RTX 4060 laptop, backend not recorded", "where the Q2_K score was measured")
        mac("outsideReadings", r"read \outsideReadN{} times by models of the single-plane line during development "
            r"(\cref{tab:outside-readings}): as finalists C, a weight average of last-step checkpoints and a "
            r"checkpoint of a run resumed after those two scores were known, and the other models for analysis only; "
            r"C was kept", "one wording for the readings of the 12,042 questions (G9_R5 S1, G10_R2)")
        mac("outsideShort", r"not held out: read several times during development, \cref{sec:selection}",
            "short reference to the readings of the 12,042 questions, defined once in the selection list")
        mac("rootMinusCDev", f2(num("chainRoot") - num("chainC")), "root minus C, MMLU-2000, earlier builds")
        mac("xsUnderRootPct", f"{100 * (num('rootPackedBytes') - num('xsBytes')) / num('rootPackedBytes'):.1f}",
            "XS bytes below the packed root, %")
        mac("smSvsXSDiffAbs", str(v["smSvsXSDiff"]).lstrip("+").replace("$-$", ""), "no-sign variant for prose")
        sl = [100 * (1 - num(b) / num(a)) for a, b in (("xsSesVkTg", "vsevxsITg"), ("smSesVkTg", "vsevsmITg"),
                                                      ("mdSesVkTg", "vsevmdITg"))]
        mac("vsevSlowLo", f"{min(sl):.0f}", "7 Nov binary slower than the launch engine, ternary decode, %")
        mac("vsevSlowHi", f"{max(sl):.0f}")
    except (KeyError, ValueError) as e:
        WARN.append(f"derived literals: {e}")


def verify_sums() -> None:
    """--bundle: check every file of SHA256SUMS against the bundle directory (THOR_BUNDLE_DIR), if one is given"""
    d = os.environ.get("THOR_BUNDLE_DIR")
    if not d:
        return
    f = Path(d) / "SHA256SUMS"
    if not f.exists():
        raise SystemExit("SHA256SUMS missing from the bundle")
    bad = []
    for ln in f.read_text().splitlines():
        if not ln.strip():
            continue
        h, rel = ln.split("  ", 1)
        p = Path(d) / rel
        if not p.exists():
            if rel not in os.environ.get("THOR_SUMS_ALLOW_MISSING", "").split(":"):
                bad.append(f"missing {rel}")
            continue
        hh = hashlib.sha256()
        with open(p, "rb") as fh:
            for blk in iter(lambda: fh.read(1 << 22), b""):
                hh.update(blk)
        if hh.hexdigest() != h:
            bad.append(f"sha256 {rel}")
    if bad:
        raise SystemExit(f"SHA256SUMS check failed: {bad[:10]} ({len(bad)} files)")
    print("SHA256SUMS: all files verified")


OUR_PREFIX = re.compile(r"^(?:xs|sm|md|te|b[a-z]+|r[a-z]+|prior|root|chain|rep|ctrl|npCtl|vsev|vnew|cv|ptq|qtwo|gsm|"
                        r"mrun|subj|held|outside|fucina|release|bf|bench|fold|gap|slope|lmeval|mmlupro|cOrder|cCand|"
                        r"blk|crSes)[A-Z]")
_NUMEXPR = re.compile(r"\\ifnum\\numexpr\s*\(?0?(?:\\ifcsname\s*)?\\?([A-Za-z]+)(?:\\endcsname\\[A-Za-z]+\\fi)?\)?\s*\*\s*"
                      r"\(?0?(?:\\ifcsname\s*)?\\?([A-Za-z]+)(?:\\endcsname\\[A-Za-z]+\\fi)?\)?\s*\\relax\s*=\s*(\d)")
_CMP = re.compile(r"\\ifnum\\([A-Za-z]+)\s*([<>])\s*(\d+)")
_TOK = re.compile(r"\\ifnum0\\ifcsname\s*([A-Za-z]+)\\endcsname\\[A-Za-z]+\\fi\s*=\s*(\d)|\\ifnum\\([A-Za-z]+)\s*=\s*(\d)"
                  r"|\\ifdefined\\([A-Za-z]+)|\\ifcsname\s*([A-Za-z]+)\\endcsname|\\if[a-z]*(?![A-Za-z])|\\else(?![A-Za-z])"
                  r"|\\fi(?![A-Za-z])|\\([A-Za-z]+)")


def live_uses(text: str, values: dict) -> set:
    """macro names used in the branches that LaTeX actually expands, given the emitted switch values"""
    used, stack = set(), []  # stack of (this branch live?, parent live)
    live = True
    for m in _TOK.finditer(text):
        g = m.groups()
        if g[0] or g[2]:
            name, want = (g[0], g[1]) if g[0] else (g[2], g[3])
            cond = values.get(name, "0") == want
            stack.append((live, cond))
            live = live and cond
        elif g[4] or g[5]:
            name = g[4] or g[5]
            stack.append((live, name in values))
            live = live and name in values
        elif m.group(0).startswith("\\if"):
            stack.append((live, None))  # other conditionals: both branches may run
        elif m.group(0) == "\\else":
            if stack:
                parent, cond = stack[-1]
                live = parent if cond is None else (parent and not cond)
        elif m.group(0) == "\\fi":
            if stack:
                live = stack.pop()[0]
        elif g[6] and live:
            used.add(g[6])
    return used


def provenance_lint() -> list:
    """hand-typed provenance that contradicts the generated switches (G12_R5 S2)"""
    paper = Path(os.environ.get("THOR_PAPER_DIR", str(HERE.parent / "latex")))
    if not (paper / "main.tex").exists():
        if os.environ.get("THOR_BUNDLE_DIR") or "--bundle" in sys.argv:
            raise SystemExit("paper/main.tex missing from the bundle: the macro guard cannot run (G20_R4 S1)")
        return []
    values = {n: v for n, v, _ in MACROS}
    same = {lab: v for lab, v in TE_PROV.items()}
    all_same = (values.get("teMMLUsame") == "1" and values.get("rootDone") == "1"
                and values.get("teEarlierTasks") == "none")
    out = []
    for f in [*paper.glob("*.tex"), *paper.glob("sections/*.tex")]:
        if f.name == "numbers_final.tex" or ".bak" in f.name or "PROPOSTA" in f.name or f.name.startswith("A_letture"):
            continue
        t = "\n".join(re.sub(r"(?<!\\)%.*", "", ln) for ln in f.read_text(errors="replace").splitlines())
        live = live_uses(t, values)
        if values.get("qtwoDone") == "1" and "bqtwoApuN" in live:
            out.append(f"{f.name}: \\bqtwoApuN in a live branch with qtwoDone=1")
        lt = live_text(t, values)
        for lab, v in same.items():
            if v and re.search(re.escape(lab) + r"[^.;]{0,40}(earlier build|now on the launch engine)", lt):
                out.append(f"{f.name}: hand-typed provenance for {lab}")
        # G14_R5 B1: once every teacher reference and the root are on the launch engine, no typeset sentence may
        # still speak of an earlier-build teacher, a cross-build or cross-machine pairing, or carry their marks
        if all_same:
            ltx = re.sub(r"\\([A-Za-z]+)(\{\})?", lambda m_: values.get(m_.group(1), m_.group(0)), lt)
            for sent in re.split(r"(?<=[.;])\s+", ltx):
                if re.search(r"drift|generated-token|history|development|same\s+(?:teacher\s+)?file", sent):
                    continue
                for pat in (r"for none", r"cross-build", r"cross-machine", r"\\ddagger", r"\^\{?\\S\}?", r"80\.33",
                            r"11,280", r"teacher[^.]{0,80}earlier build", r"earlier build[^.]{0,80}teacher"):
                    if re.search(pat, sent):
                        out.append(f"{f.name}: stale provenance /{pat}/: {sent.strip()[:110]}")
    return out


def live_text(text: str, values: dict) -> str:
    """the text LaTeX actually typesets given the emitted switches (dead branches removed)"""
    def num(name):
        try:
            return int(values.get(name, "0"))
        except ValueError:
            return 0
    # normalise product and comparison conditions to a synthetic \ifnum\X=1 the tokenizer understands
    synth = {}
    def sub_num(m_):
        k = "zzN" + "".join("abcdefghij"[int(c)] for c in str(len(synth)))
        synth[k] = "1" if num(m_.group(1)) * num(m_.group(2)) == int(m_.group(3)) else "0"
        return f"\\ifnum\\{k}=1"
    def sub_cmp(m_):
        k = "zzC" + "".join("abcdefghij"[int(c)] for c in str(len(synth)))
        a_, op, b_ = num(m_.group(1)), m_.group(2), int(m_.group(3))
        synth[k] = "1" if (a_ > b_ if op == ">" else a_ < b_) else "0"
        return f"\\ifnum\\{k}=1"
    text = _CMP.sub(sub_cmp, _NUMEXPR.sub(sub_num, text))
    values = {**values, **synth}
    out, stack, live, pos = [], [], True, 0
    for m in _TOK.finditer(text):
        if live:
            out.append(text[pos:m.start()])
        pos = m.end()
        g = m.groups()
        if g[0] or g[2]:
            name, want = (g[0], g[1]) if g[0] else (g[2], g[3])
            cond = values.get(name, "0") == want
            stack.append((live, cond))
            live = live and cond
        elif g[4] or g[5]:
            name = g[4] or g[5]
            stack.append((live, name in values))
            live = live and name in values
        elif m.group(0).startswith("\\if"):
            stack.append((live, None))
        elif m.group(0) == "\\else":
            if stack:
                parent, cond = stack[-1]
                live = parent if cond is None else (parent and not cond)
        elif m.group(0) == "\\fi":
            if stack:
                live = stack.pop()[0]
        elif live:
            out.append(m.group(0))
    if live:
        out.append(text[pos:])
    return "".join(out)


def check_paper_macros(emitted: set) -> set:
    """macros of our families used in live branches of the paper sources but not emitted"""
    paper = Path(os.environ.get("THOR_PAPER_DIR", str(HERE.parent / "latex")))
    if not (paper / "main.tex").exists():
        if os.environ.get("THOR_BUNDLE_DIR") or "--bundle" in sys.argv:
            raise SystemExit("paper/main.tex missing from the bundle: the macro guard cannot run (G20_R4 S1)")
        return set()
    values = {n: v for n, v, _ in MACROS}
    used, defined = set(), set()
    for f in [*paper.glob("*.tex"), *paper.glob("sections/*.tex")]:
        if f.name == "numbers_final.tex" or ".bak" in f.name or "PROPOSTA" in f.name:
            continue
        t = "\n".join(re.sub(r"(?<!\\)%.*", "", ln) for ln in f.read_text(errors="replace").splitlines())
        used |= live_uses(t, values)
        # switches tested in \ifnum conditions count as used too (G18_R4 m6): dropping one must fail the guard
        used |= set(re.findall(r"\\ifnum\\([A-Za-z]+)", t)) & set(values)
        used |= set(re.findall(r"\\ifcsname\s*([A-Za-z]+)\s*\\endcsname", t)) & set(values)   # G19_R4
        defined |= set(re.findall(r"\\(?:newcommand|renewcommand|def)\s*\{?\\([A-Za-z]+)", t))
    # every macro of the frozen paper's numbers file that a live branch uses must be emitted (G14_R4 S1), whatever
    # its prefix; plus the prefix families for macros never emitted before
    nf = paper / "numbers_final.tex"
    frozen = set(re.findall(r"^\\newcommand\{\\([A-Za-z]+)\}", nf.read_text(errors="replace"), re.M)) if nf.exists() else set()
    return {u for u in used if (OUR_PREFIX.match(u) or u in frozen) and u not in emitted and u not in defined}


def _inflation(scores: list, sd: float, n_sim: int = 200_000) -> tuple[float, float]:
    """expected (observed maximum - true score of the chosen one): all-equal truths, and truths ~ N(mean, tau^2) with
    tau^2 = max(0, var(observed) - sd^2)"""
    rng = np.random.default_rng(SEED)
    n = len(scores)
    noise = rng.standard_normal((n_sim, n)) * sd
    up = float(noise.max(1).mean())
    tau = math.sqrt(max(0.0, float(np.var(scores, ddof=1)) - sd ** 2))
    true = rng.standard_normal((n_sim, n)) * tau
    obs = true + noise
    k = obs.argmax(1)
    lo_ = float((obs[np.arange(n_sim), k] - true[np.arange(n_sim), k]).mean())
    return up, lo_


BUNDLE_MODE = False
DATES_FILE = HERE / "date_letture.json"   # shipped: dates of readings, recorded on the measuring machine (G14_R4 S1)
_DATES: dict | None = None
_REGFN = None
SUBJ_ALL = None


def reading_date(path: str) -> str:
    """date of a reading from the shipped manifest; file modification times are lost on download or copy, so they are
    read only on the measuring machine (full run) and recorded in the manifest, never in a bundle run"""
    global _DATES
    if _DATES is None:
        _DATES = json.loads(DATES_FILE.read_text()) if DATES_FILE.exists() else {}
    key = str(path).replace(GGUF, "{gguf}").replace(FORGE, "{forge}").replace(BENCH, "{bench}")
    if key in _DATES:
        return _DATES[key]
    if BUNDLE_MODE:
        raise SystemExit(f"reading date of {key} missing from {DATES_FILE.name}")
    # the date comes from the run register row that names the log (G20_R4 m5), the file time only when no row does;
    # the source of each date is recorded in date_letture_fonte.json
    global _REGFN
    if _REGFN is None:
        import runpy as _rp  # noqa: PLC0415
        _REGFN = _rp.run_path(str(HERE / "estrai_letture.py"), run_name="letture_lib")["reg_date"]
    d_, src_ = _REGFN(str(path), Path(path).stat().st_mtime)
    _DATES[key] = d_
    DATES_FILE.write_text(json.dumps(_DATES, indent=0, sort_keys=True))
    fs_ = HERE / "date_letture_fonte.json"
    src = json.loads(fs_.read_text()) if fs_.exists() else {}
    src[key] = src_
    fs_.write_text(json.dumps(src, indent=0, sort_keys=True))
    return _DATES[key]


def _chain_inflation(vk: list, sd_c: float, n_sim: int = 200_000) -> None:
    """two-stage selection on the same 2,000 questions (G13_R2 S1, G14_R2 S1): T400 chosen as the best of its run's
    readings, then C as the best of the candidates on its host. Additive structure: a candidate's score is T400's
    reading plus a candidate-specific term whose noise sd_c is measured RELATIVE TO T400 (discordance against T400), so
    C carries T400's selected error at full weight and adds the maximum over the candidates of that term. The two
    stages act on the same questions and add. (The correlation of per-question correctness is item difficulty, not
    shared noise, and is not used to discount.)"""
    t_scores = [float(v) for v in TCAND_SCORES]
    if len(t_scores) < 3:
        return
    t400 = read_mclp(Path(DEV_CHAIN["Tfour"][0]))
    c = read_mclp(Path(DEV_CHAIN["C"][0]))
    if t400 is None or c is None:
        return
    r = float(np.corrcoef(t400["ok"].astype(float), c["ok"].astype(float))[0, 1])
    sd_t = SD_T[0]
    c_scores = [float(x["score"]) for x in vk]
    on_t400 = np.array([1.0 if str(x.get("host", "T400")).startswith("T400") else 0.0 for x in vk])
    mac("cCandOnTfour", int(on_t400.sum()), "candidates on the T400 host (inherit T400's selection)")
    rng = np.random.default_rng(SEED + 7)
    res, parts = [], []
    for spread in (False, True):
        tau_t = math.sqrt(max(0.0, float(np.var(t_scores, ddof=1)) - sd_t ** 2)) if spread else 0.0
        tau_c = math.sqrt(max(0.0, float(np.var(c_scores, ddof=1)) - sd_c ** 2)) if spread else 0.0
        nt, nc = len(t_scores), len(c_scores)
        e_t = rng.standard_normal((n_sim, nt)) * sd_t
        tt = rng.standard_normal((n_sim, nt)) * tau_t
        k = (tt + e_t).argmax(1)
        e_sel = e_t[np.arange(n_sim), k]                       # stage 1: error carried by the chosen T400
        d = rng.standard_normal((n_sim, nc)) * sd_c            # stage 2: candidate noise relative to its host
        tc = rng.standard_normal((n_sim, nc)) * tau_c
        # candidates on the T400 host inherit T400's selected error; those on the S7+DOWNH host do not (G15_R5)
        carry = e_sel[:, None] * on_t400[None, :]
        obs = tc + d + carry
        j = obs.argmax(1)
        tot = (d + carry)[np.arange(n_sim), j]
        res.append(float(tot.mean()))
        parts.append((float(carry[np.arange(n_sim), j].mean()), float(d[np.arange(n_sim), j].mean())))
    mac("cChainInfl", f"{res[0]:.1f}", "C: two-stage (T400 then C) inflation, additive, all true scores equal, points")
    mac("cChainInflLo", f"{res[1]:.1f}", "C: two-stage inflation, true-score spread estimated per stage")
    mac("cChainStageOne", f"{parts[0][0]:.2f}", "stage 1 carried into the chosen candidate (T400's selected error), all equal")
    mac("cChainStageTwo", f"{parts[0][1]:.2f}", "stage 2 (C among the candidates, relative to T400), all equal")
    mac("cTfourCorr", f"{r:.2f}", "correlation of per-question correctness of C and T400 on MMLU-2000")
    mac("cTfourSame", f"{100 * float((t400['choice'] == c['choice']).mean()):.0f}", "% of answers C shares with T400")


SD_T = [0.40 / math.sqrt(2)]   # fallback; replaced from the T400-run discordances in readings_section (G17_R2 m9)


def readings_section() -> None:
    """macros from letture.json (estrai_letture.py): candidates of C and readings of the 12,042 questions"""
    f = HERE / "letture.json"
    if not f.exists():
        WARN.append("letture.json missing: run estrai_letture.py")
        return
    d = json.loads(f.read_text())
    words = {2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight"}
    n = sum(1 for c in d["candidates"] if c.get("engine", "Vulkan") == "Vulkan")
    mac("cCandN", n, "folded candidates of the single-plane line on the T400 or S7+DOWNH host, Vulkan, C the highest")
    mac("cCandAll", len(d["candidates"]), "the same with the CUDA readings")
    mac("cCandArms", words.get(len(d["arms"]), len(d["arms"])), "arms")
    mac("cCandHosts", words.get(len(d["hosts"]), len(d["hosts"])), "hosts")
    mac("cCandUnfolded", len(d["unfolded"]), "unfolded-adapter readings of the same arms")
    fp = d.get("fold_pairs", [])
    if fp:
        big = max(fp, key=lambda r: r["cost"])
        mac("foldPairN", len(fp), "folded/unfolded pairs of the same run and step in the logs")
        mac("foldCostMax", f"{big['cost']:.2f}", "largest measured cost of folding, points")
        mac("foldCostMaxRun", big["run"].replace("_", r"\_"))
        mac("foldCostMaxStep", big["step"])
        mac("foldCostMaxWL", big["wl"], "unfolded wins/losses against folded")
        mac("foldCostMaxP", tex_p(big["p"]))
        lo_ = min(fp, key=lambda r: r["cost"])
        mac("foldCostMin", f"{lo_['cost']:+.2f}".replace("-", "$-$"), "smallest measured cost of folding (negative: fold better)")
    c_line = [r for r in d["outside"] if r.get("development", r.get("c_line"))]
    mac("outsideReadN", len(c_line), "readings of the 12,042 questions by models of the line before C was chosen")
    mac("outsideReadLine", sum(1 for r in d["outside"] if r.get("c_line")), "by models of the line, any date")
    mac("outsideReadAll", len(d["outside"]), "readings of the 12,042 questions by any model")
    # inflation of the selected maximum under two models (G12_R2 S2): all true scores equal (upper) and true scores spread
    # as estimated from the observed ones (empirical Bayes: tau^2 = var(observed) - sigma^2), by simulation
    vk = [c for c in d["candidates"] if c.get("engine", "Vulkan") == "Vulkan"]
    disc = sorted(sum(int(x) for x in c["wl"].split("/")) for c in vk)
    sd = 100 * math.sqrt(float(np.median(disc))) / (math.sqrt(2) * NDEV)
    mac("cCandDiscLo", disc[0], "smallest discordant count against T400")
    mac("cCandDiscHi", disc[-1], "largest discordant count against T400")
    up, lo_ = _inflation([float(c["score"]) for c in vk], sd)
    mac("cCandInfl", f"{up:.1f}", "inflation of the best Vulkan candidate if all true scores are equal (upper), points")
    mac("cCandInflLo", f"{lo_:.1f}", "inflation with the true-score spread estimated from the observed scores, points")
    # T400: the MMLU-2000 readings of its run (steps and the weight average tappa_9xxx); the selection used those that
    # existed when T400 was chosen (before 23 Oct); steps 600/650 were measured later
    t_all, t_sel, t_ok = [], [], []
    import datetime as _dt
    for f_ in sorted(glob.glob(GGUF + "/tony-tern/OBIETTIVO_C/CARDAN_CONGIUNTO_S7T550_1020/tappa_*/mmlu_CONGIUNTO.log")):
        if not re.search(r"tappa_\d+/", f_):
            continue
        x = read_mclp(Path(f_))
        if x is None or len(x["gold"]) != NDEV:
            continue
        sc = 100 * x["ok"].mean()
        t_all.append(sc)
        if reading_date(f_) < "2026-10-23":
            t_sel.append(sc)
            t_ok.append(x["ok"])
    TCAND_SCORES[:] = t_sel
    # noise of one T400-run reading from the data (G17_R2 m9): median discordance over all pairs of the readings
    # available at the choice, sd of a paired difference = 100 sqrt(disc) / NDEV, of one reading that / sqrt(2)
    if len(t_ok) >= 2:
        dd = sorted(int((a_ != b_).sum()) for i_, a_ in enumerate(t_ok) for b_ in t_ok[i_ + 1:])
        SD_T[0] = 100 * math.sqrt(float(np.median(dd))) / (math.sqrt(2) * NDEV)
        mac("tCandDiscMed", f"{float(np.median(dd)):.0f}", "median discordant questions between readings of the T400 run")
        mac("tCandSd", f"{SD_T[0]:.2f}", "sd of one T400-run reading implied by that discordance, points")
    if len(t_sel) >= 3:
        up, lo_ = _inflation(t_sel, SD_T[0])
        mac("tCandN", len(t_sel), "MMLU-2000 readings of the T400 run available when T400 was chosen (incl. a weight average)")
        mac("tCandAll", len(t_all), "all MMLU-2000 readings of the T400 run (incl. steps measured later)")
        mac("tCandInfl", f"{up:.1f}", "T400: inflation if all true scores are equal")
        mac("tCandInflLo", f"{lo_:.1f}", "T400: inflation with the estimated true-score spread")
    _chain_inflation(vk, sd)


def contamination_section() -> None:
    """MMLU-Pro items overlapping the MMLU calibration questions (contaminazione_mmlupro.py)"""
    f = HERE / "contaminazione_mmlupro.json"
    if not f.exists():
        WARN.append("contaminazione_mmlupro.json missing")
        return
    d = json.loads(f.read_text())
    mac("proOverlapExact", d["exact"], "MMLU-Pro questions identical to a calibration question")
    mac("proOverlapLong", d["long"], "MMLU-Pro questions containing a long calibration passage")
    mac("proOverlapLongCal", ints(d["n_long_cal"]), "calibration questions of at least 200 characters")
    mac("proOverlapN", len(d["overlap_items"]), "MMLU-Pro items overlapping (union)")
    if "exact_generic" in d:
        mac("proClsExactGeneric", d["exact_generic"], "same-stem matches whose stem is generic (under 50 characters)")
    mac("proOverlapLongOnly", d.get("long_not_exact", d["long"]), "overlapping items sharing a passage, not the question")
    mac("proNearPrefix", d.get("near_prefix", 0), "further items sharing the first 60 characters (near duplicates)")
    if "near_prefix_new" in d:
        mac("proNearPrefixNew", d["near_prefix_new"], "of those, items in none of the three classes")
    for cls, nm in (("exact", "Exact"), ("passage", "Passage"), ("template", "Template")):
        if f"te_{cls}" in d:
            mac(f"proCls{nm}N", d[f"te_{cls}"].split("/")[1], f"MMLU-Pro items in overlap class {cls}")
            for who, k in (("te", "te"), ("xs", "XS"), ("sm", "S"), ("md", "M")):
                mac(f"{who}ProCls{nm}", d[f"{k}_{cls}"].split("/")[0], f"correct answers of {k} in class {cls}")
    for m, p_ in (("XS", "xs"), ("S", "sm"), ("M", "md")):
        if f"ret_{m}_clean" in d:
            mac(f"{p_}MmluproRetClean", f2(d[f"ret_{m}_clean"]), "TEACHER-PCT MMLU-Pro retention without overlapping items")
            mac(f"{p_}MmluproRetOverlap", f2(d[f"ret_{m}_overlap"]), "TEACHER-PCT on the overlapping items only")
            mac(f"{p_}MmluproOverlapWL", d[f"wl_{m}_overlap"], "wins/losses against the teacher on the overlapping items")
            mac(f"{p_}MmluproOverlapP", tex_p(d[f"p_{m}_overlap"]))


# ------------------------------------------------------------------------------------------------ main
def sums_stale() -> list[str]:
    """in our tree (not in a downloaded bundle): shipped files modified after SHA256SUMS was written (G17_R4 S4)"""
    sums, lst = HERE / "SHA256SUMS", HERE / "BENCH_FILES.tsv"
    # skipped in a downloaded bundle and while elenca_bundle.py lists the files (it writes SHA256SUMS right after)
    if os.environ.get("THOR_BUNDLE_DIR") or os.environ.get("THOR_NO_BUNDLE_LIST") or not (sums.exists() and lst.exists()):
        return []
    t0 = sums.stat().st_mtime
    out = []
    for ln in lst.read_text(errors="replace").splitlines()[1:]:
        f_ = ln.split("\t")
        if (len(f_) < 3 or not f_[1].startswith("/") or f_[1].endswith(".gguf")
                or f_[2].startswith(("pending", "not shipped", "-", "MISSING"))):
            continue
        p_ = Path(f_[1])
        if p_.is_file() and p_.stat().st_mtime > t0 + 1:
            out.append(f_[0])
    return out


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--no-hash", action="store_true")
    ap.add_argument("--bundle", action="store_true",
                    help="run on the measurement bundle: file facts from the manifest, no model file is read")
    a = ap.parse_args()
    if not a.bundle and not os.environ.get("THOR_NO_BUNDLE_LIST") and CICLI.exists():
        import subprocess  # noqa: PLC0415
        subprocess.run([sys.executable, str(HERE / "estrai_letture.py")], check=True)
    man = {}
    global BUNDLE_MODE
    BUNDLE_MODE = bool(a.bundle)
    if BUNDLE_MODE and os.environ.get("THOR_FORBID_PRIVATE"):
        # bundle self-test (elenca_bundle.py --test): any read of an author-machine root fails, as on an external
        # machine (POD_g20 S1)
        priv = tuple(x for x in os.environ["THOR_FORBID_PRIVATE"].split(":") if x)
        bdir = os.environ.get("THOR_BUNDLE_DIR", "/nonexistent")

        def _no_private(event, args):
            if event == "open" and args and isinstance(args[0], (str, bytes, os.PathLike)):
                p_ = os.path.abspath(os.fsdecode(args[0]))
                if p_.startswith(priv) and not p_.startswith(bdir):
                    raise FileNotFoundError(f"bundle mode reads a private path: {p_}")
        sys.addaudithook(_no_private)
    if a.bundle:
        verify_sums()          # before anything is computed or written
        man = json.loads(MANIFEST.read_text())
        FILE_SIZES.update({k: int(v) for k, v in man["sizes"].items()})
    cache = load_cache()
    import pyarrow.parquet as pq  # noqa: PLC0415
    subj = np.array(pq.read_table(PARQUET, columns=["subject"]).column("subject").to_pylist())
    globals()["SUBJ_ALL"] = subj
    mm = mmlu_section(subj, cache)
    baselines_section(mm)
    cuda_section(mm)
    ptq_section(mm)
    q2k_launch(mm)
    suite_section(mm)
    generative_section()
    dev_curves()
    rivals_suite()
    np_control()
    root_section(mm)
    ctrl_post(mm)
    dev_chain()
    fucina_flag()
    fold_holm()
    prior_control(subj, mm)
    speed_section()
    speed_sessions()
    speed_drift()
    q2zero_section()
    c4_section()
    c4_released_section()
    host_a_section(mm)
    q4km_launch_section(mm)
    mtp_launch_section()
    strat_outside_section()
    microbatch_section()
    m_stop_readings()
    root_cost_section()
    recipe_sm_section()
    readings_section()
    contamination_section()
    sizing_section()
    root_mtp_section()
    ptq_mtp_section()
    derived_claims()
    if a.bundle:
        # tensor identities are re-checked from the per-tensor sha256 lists shipped in the manifest
        tens = man.get("tensors", {})
        chk = {}
        for m, (rel_, meas) in (("sm", ("S_released", "S_measured")), ("md", ("M_released", "M_measured"))):
            if rel_ in tens and meas in tens:
                chk[f"{m}TensSame"] = ints(sum(1 for k, v in tens[rel_].items() if tens[meas].get(k) == v))
        if "XS" in tens and "C" in tens:
            chk["xsVsCsame"] = ints(sum(1 for k, v in tens["XS"].items() if tens["C"].get(k) == v))
        for n, v, c in man["macros"]:
            if n in chk and chk[n] != v:
                raise SystemExit(f"manifest tensor lists disagree with {n}: {chk[n]} vs {v}")
            mac(n, v, c + (" [rechecked from per-tensor sha256]" if n in chk else " [manifest]"))
    else:
        k0 = len(MACROS)
        release_section(cache, not a.no_hash)
        inputs_section(cache, not a.no_hash)
        bytes_by_part(cache)
        try:
            import subprocess  # noqa: PLC0415
            rc = subprocess.run(["git", "-C", BUILD + "/thor-pub-q8", "rev-parse", "--short=9", "thor-t-v1^{commit}"],
                                capture_output=True, text=True, timeout=30).stdout.strip()
        except Exception as e:  # noqa: BLE001
            rc = ""
            WARN.append(f"release commit not read: {e}")
        mac("releaseCommit", rc or "unknown", "commit of tag thor-t-v1 (git rev-parse)")
        try:
            fc = subprocess.run(["git", "-C", FORGE + "/fucina_en", "rev-parse", "--short=7", "thor-recipe-c-v1^{commit}"],
                                capture_output=True, text=True, timeout=30).stdout.strip()
        except Exception as e:  # noqa: BLE001
            fc = ""
            WARN.append(f"fucina tag not read: {e}")
        # the public forge repository is a git subtree split of fucina_en: cite the post-split commit (fucina_split.tsv),
        # after checking that it was computed from the commit the private tag points to now
        sp = HERE / "fucina_split.tsv"
        pub = ""
        if sp.exists():
            rec = dict(ln.split("\t", 1) for ln in sp.read_text().splitlines() if "\t" in ln)
            if fc and rec.get("private", "").startswith(fc):
                pub = rec.get("public", "")[:7]
            else:
                WARN.append("fucina_split.tsv is stale: the private tag moved; recompute the subtree split")
        mac("fucinaTagCommit", pub or fc or "unknown", "commit of tag thor-recipe-c-v1 in the public (subtree-split) forge")
        mac("fucinaTagPrivate", fc or "unknown", "same tag in the private history (comment only)")
        tens = {}
        c_file = GGUF + "/tony-tern/OBIETTIVO_C/RECORD_C/Thor-T-C-T400POST-T50.gguf"
        for lab, f in (("XS", RELEASE["XS"][0]), ("S_released", RELEASE["S"][0]), ("S_measured", RELEASE["S"][1]),
                       ("M_released", RELEASE["M"][0]), ("M_measured", RELEASE["M"][1]), ("C", c_file)):
            if os.path.exists(f):
                h = tensor_hashes(f, cache, not a.no_hash)
                if h:
                    tens[lab] = h
        paths = {f: os.path.getsize(f) for f in SIZED_PATHS if os.path.exists(f)}
        old = json.loads(MANIFEST.read_text()).get("paths", {}) if MANIFEST.exists() else {}
        pq_entry = {"path": "hf/" + PARQUET[len(HFCACHE.rstrip("/")) + 1:], "bytes": os.path.getsize(PARQUET),
                    "sha256": sha256_file(PARQUET, cache, True)} if os.path.exists(PARQUET) else {}
        MANIFEST.write_text(json.dumps({"sizes": FILE_SIZES, "macros": MACROS[k0:], "tensors": tens, "parquet": pq_entry,
                                        "paths": old | paths}, indent=1))
    subjects_table(mm, subj)
    # returns of extra bytes along the released family (full test, teacher-relative)
    v = {n: val for n, val, _ in MACROS}
    gib = {p: float(v[f"{p}GiB"]) for p in ("xs", "sm", "md")}
    ret = {p: float(v[f"{p}MMLUret"]) for p in ("xs", "sm", "md")}
    mac("slopeXsSm", f"{(ret['sm'] - ret['xs']) / (gib['sm'] - gib['xs']):.1f}", "TEACHER-PCT points of retention per GiB")
    mac("slopeSmMd", f"{(ret['md'] - ret['sm']) / (gib['md'] - gib['sm']):.2f}", "TEACHER-PCT")
    mac("gapXsSm", f"{ret['sm'] - ret['xs']:.2f}", "TEACHER-PCT")
    mac("gapSmMd", f"{ret['md'] - ret['sm']:.2f}", "TEACHER-PCT")
    mac("gibXsSm", f"{gib['sm'] - gib['xs']:.2f}")
    mac("gibSmMd", f"{gib['md'] - gib['sm']:.2f}")
    CACHE.write_text(json.dumps(cache, indent=0))
    derived_literals()
    names = [n for n, _, _ in MACROS]
    dup = {n for n in names if names.count(n) > 1}
    if dup:
        raise SystemExit(f"duplicate macros: {sorted(dup)}")
    head = ["% GENERATED by revisione_1109/genera_numeri.py -- do not edit by hand. Re-run the script instead.",
            "% Lines tagged TEACHER-PCT depend on the teacher reference; BASELINE-SAME-ENGINE on the baselines.",
            *[f"% WARNING: {w}" for w in dict.fromkeys(WARN)],
            r"\ifdefined\numbersfinalloaded\else", r"\def\numbersfinalloaded{}"]
    body = [f"\\newcommand{{\\{n}}}{{{v}}}" + (f"  % {c}" if c else "") for n, v, c in MACROS]
    if a.bundle:
        stale = sums_stale()
        if stale:
            raise SystemExit(f"SHA256SUMS is older than {len(stale)} shipped files (re-run --no-hash last): {stale[:5]}")
    txt_out = "\n".join(head + body + [r"\fi", ""])
    def _defs(t_: str) -> list:
        return [ln.split("  %")[0] for ln in t_.splitlines() if ln.startswith("\\newcommand")]
    old_ = OUT_TEX.read_text() if OUT_TEX.exists() else ""
    # an identical file keeps its time (G17_R4 S4); in --bundle mode a file with the same definitions is kept too
    # (only its comment header may differ), so that the hashed copy of the full run stays valid
    if not (old_ == txt_out or (a.bundle and _defs(old_) == _defs(txt_out))):
        OUT_TEX.write_text(txt_out)
    print(f"{len(MACROS)} macros -> {OUT_TEX}")
    for w in WARN:
        print("WARNING:", w)
    if a.bundle:
        # THOR_GUARD_DROP: self-test of the guard only (elenca_bundle.py --test); pretends one macro was not emitted
        undefined = check_paper_macros({n for n, _, _ in MACROS} - {os.environ.get("THOR_GUARD_DROP", "")})
        if undefined:
            raise SystemExit(f"macros used in the paper but not emitted: {sorted(undefined)}")
        lint = provenance_lint()
        if lint:
            raise SystemExit("provenance lint: " + "; ".join(lint[:10]))
    elif not os.environ.get("THOR_NO_BUNDLE_LIST"):
        # the bench file list is regenerated after every full run, so it never goes stale
        import subprocess  # noqa: PLC0415
        r = subprocess.run([sys.executable, str(HERE / "elenca_bundle.py")], env=dict(os.environ, THOR_NO_BUNDLE_LIST="1"))
        if r.returncode:
            raise SystemExit("elenca_bundle.py failed: BENCH_FILES.tsv is not up to date")


if __name__ == "__main__":
    main()