hf2q 0.1.3

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
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
#!/usr/bin/env python3
"""
ADR-015 iter9/iter11 aggregator: kernel attribution from xctrace MST traces
for hf2q vs llama-cli on the Q4_0-dominated dwq46 apex workload.

Why this exists (vs aggregate_decode_mst.py):
  iter8c-prep's aggregator emits per-dispatch DURATION distributions
  (count, sum, p50/p95) keyed only by sub_id/channel/slot. There is no
  kernel-name attribution. iter9 spec S3 requires kernel-name attribution
  to identify the iter10 attack target.

Schema status (iter11 re-discovery, 2026-04-28, mlx-native@a7d2b95 post-iter9b):
  Available schemas in MST trace:
    - metal-application-encoders-list  (per-encoder: cmd-buf, encoder, duration)
    - metal-application-event-interval (DEBUG GROUPS — STILL empty; mlx-native does
                                        not pushDebugGroup. iter11b candidate enabler.)
    - metal-driver-intervals           (Command Buffer / Command Encoder labels — generic)
    - metal-object-label               (CoreAnimation surfaces, AGXHeaps — no shader fn names)
    - metal-shader-profiler-shader-list (compiled-shader REGISTRY — NOW POPULATED post-iter9b
                                         with kernel_mul_mv_q4_0_f32 / kernel_mul_mv_id_q4_0_f32
                                         / kernel_mul_mm_q6_K_tensor_f32 / kernel_mul_mm_id_*
                                         labels and PC ranges. iter11 surfaces this; iter9 audit
                                         claim "shader-list empty" was stale w.r.t. iter9b.)
    - metal-shader-profiler-intervals  (Shader Timeline samples — STILL EMPTY without the
                                        GUI-only "Shader Timeline" checkbox in the template's
                                        Metal Application instrument settings. iter11 verified
                                        4 incantations cannot toggle this from CLI:
                                          (a) default `Metal System Trace`
                                          (b) MST + --instrument "Metal GPU Counters"
                                              + --instrument "Metal Performance Overview"
                                              + --instrument "Advanced Graphics Statistics"
                                          (c) MST + (b) + --instrument "Metal Application"
                                              + --instrument "GPU"
                                          (d) `Game Performance` template (sibling GPU.instrdst)
                                        All produce shader-list rows but ZERO Shader Timeline
                                        sample rows. .tracetemplate is NSKeyedArchiver bplist
                                        and the Shader Timeline toggle does not surface as a
                                        plain XML key — surgical patching from CLI is not
                                        feasible without a GUI Instruments.app pass.)
    - gpu-shader-profiler-interval     (Shader Timeline by-PC intervals — empty, same reason)
    - gpu-shader-profiler-sample       (Shader Timeline PC samples — empty, same reason)
    - metal-gpu-execution-points       (per-dispatch start/end pairs by gpu-submission-id)

  Conclusion (iter11 update of iter9 conclusion): mlx-native@a7d2b95 EXPOSES kernel labels
  via metal-shader-profiler-shader-list (PSO-id → label registry). However, the JOIN from
  per-dispatch GPU times (metal-gpu-execution-points) → PSO-id → label is BROKEN: nothing in
  the per-dispatch tables carries pso-id, and Shader Timeline (which records per-PC samples
  joinable to shader-list pc-ranges) cannot be enabled from xctrace CLI. PER-KERNEL-NAME
  µs/token ATTRIBUTION VIA xctrace MST IS THEREFORE STILL NOT POSSIBLE without one of:
    (1) iter11b enabler in mlx-native: pushDebugGroup(label) + popDebugGroup() around each
        kernel dispatch in src/encoder.rs; populates metal-application-event-interval with
        per-dispatch labeled intervals joinable to GPU duration. (recommended)
    (2) iter11c enabler in mlx-native: MTLCounterSampleBuffer programmatic sampling with
        per-dispatch begin/end stage-boundary GPU counter reads. M5 Max supports stage-
        boundary sampling per `project_m5max_no_dispatch_boundary_sampling`.
    (3) GUI Instruments.app run with Shader Timeline checkbox manually enabled, exporting
        the trace and re-running this aggregator with --enable-shader-timeline.
  The closest CLI-only signal remains the per-encoder duration in metal-application-encoders-list
  cross-joined with metal-gpu-execution-points by command-buffer-id, then BUCKETED by
  dispatch duration histogram — Q4_0 mat-vec dispatches sit in a known time band
  (~5–60 µs per dispatch on the dwq46 apex workload at decode), distinct from flash-attention
  (~50–500 µs) or RMS-norm (~1–10 µs). This is what we report as the "best-available"
  attribution alongside the kernel-label registry surfaced from shader-list.

Output (/tmp/adr015-iter9/aggregate-q4_0.txt):
  Per-binary, per-trial, the dispatch-duration histogram with bucketed
  attribution against a structural reference (counts per token from the
  Qwen3.5-MoE forward graph: 32 layers × 8 used_experts × 3 mat-vec per
  expert + 32 attn × 4 RMS + 32 flash-attn + …). Side-by-side hf2q vs
  llama for the highest-mass buckets, with Δµs/token and Δ% columns.

  Structural counts per token (n_used_experts=8, n_layers=32):
    Q4_0 mat-vec (mul_mv_id_q4_0_f32):
      gate/up: 32 layers × 8 experts × 2 = 512 dispatches/tok
      down:    32 layers × 8 experts × 1 = 256 dispatches/tok
      total:   768 Q4_0-id dispatches/tok
    Q4_0 mat-vec (mul_mv_q4_0_f32, dense Q/K/V/O proj):
      qkv_o:   32 layers × 4 = 128 dispatches/tok (if not fused)

Methodology AC2 compliance:
  Per spec AC2 ("NO double-counted overlapping inclusive frames"), we use
  metal-gpu-execution-points (point-events at GPU start/end) as the
  CANONICAL frame. metal-driver-intervals is INCLUSIVE of GPU work and
  is NOT summed. metal-application-encoders-list is reported separately
  (encoder-side wall-clock, not GPU time).

Usage:
  scripts/aggregate-q4_0-mst.py \
    --hf2q-trace /tmp/adr015-iter9/hf2q-trial-1.trace \
    --hf2q-trace /tmp/adr015-iter9/hf2q-trial-2.trace \
    ... \
    --llama-trace /tmp/adr015-iter9/llama-trial-1.trace \
    ... \
    --n-tokens 64 \
    --output /tmp/adr015-iter9/aggregate-q4_0.txt

Falls back gracefully if either side has fewer trials (median over what's
available). If --hf2q-trace is provided but --llama-trace is empty, prints
hf2q-only partial attribution (this is the iter9 claude-side mid-iteration
case, before codex completes llama capture).
"""

import argparse
import os
import statistics
import subprocess
import sys
import xml.etree.ElementTree as ET
from collections import defaultdict
from typing import Dict, List, Optional, Tuple


XCTRACE = "/Applications/Xcode.app/Contents/Developer/usr/bin/xctrace"


# --------------------------------------------------------------------- #
# Schema discovery                                                      #
# --------------------------------------------------------------------- #

def export_table(trace_path: str, schema: str) -> str:
    """Run `xctrace export --xpath ...` and return the XML stdout."""
    if not os.path.isdir(trace_path):
        raise FileNotFoundError(f"trace bundle not found: {trace_path}")
    xpath = f'/trace-toc/run/data/table[@schema="{schema}"]'
    proc = subprocess.run(
        [XCTRACE, "export", "--input", trace_path, "--xpath", xpath],
        check=True,
        capture_output=True,
        text=True,
    )
    return proc.stdout


def export_toc(trace_path: str) -> str:
    proc = subprocess.run(
        [XCTRACE, "export", "--input", trace_path, "--toc"],
        check=True,
        capture_output=True,
        text=True,
    )
    return proc.stdout


# --------------------------------------------------------------------- #
# id/ref dictionary — same scheme used by aggregate_decode_mst.py       #
# --------------------------------------------------------------------- #

def resolve(elem: ET.Element, table: dict) -> str:
    rid = elem.get("id")
    ref = elem.get("ref")
    if rid is not None:
        val = elem.get("fmt") or (elem.text or "")
        table[rid] = val
        return val
    if ref is not None:
        return table.get(ref, "")
    return elem.get("fmt") or (elem.text or "")


def text_int(elem: ET.Element, table: dict) -> Optional[int]:
    """Return the integer value of an XML cell, resolving id/ref."""
    rid = elem.get("id")
    ref = elem.get("ref")
    if rid is not None:
        # Definition: prefer text content (raw integer), fall back to fmt.
        t = (elem.text or "").strip()
        try:
            v = int(t) if t else int(elem.get("fmt") or "0")
            table[rid] = v
            return v
        except ValueError:
            return None
    if ref is not None:
        return table.get(ref)
    t = (elem.text or "").strip()
    try:
        return int(t) if t else int(elem.get("fmt") or "0")
    except ValueError:
        return None


# --------------------------------------------------------------------- #
# Schema 1: metal-gpu-execution-points (per-dispatch GPU start/end)     #
# Schema columns (verified from existing aggregate_decode_mst.py):      #
#   0: start-time (ns)                                                   #
#   1: metal-command-buffer-id (channel-id)                              #
#   2: uint32 (function: 1=start, 2=end)                                 #
#   3: uint32 (slot-id)                                                  #
#   4: metal-command-buffer-id (gpu-submission-id)                       #
#   5: uint64 (accelerator-id)                                           #
#   6: string (note) — optional sentinel                                 #
# --------------------------------------------------------------------- #

def parse_gpu_execution_points(xml_text: str) -> List[dict]:
    root = ET.fromstring(xml_text)
    rows = []
    table = {}
    for row in root.iter("row"):
        children = list(row)
        if len(children) < 5:
            continue

        t_str = resolve(children[0], table)
        # Prefer raw int text over fmt
        t_text = (children[0].text or "").strip()
        try:
            t_ns = int(t_text) if t_text else int(t_str)
        except ValueError:
            try:
                t_ns = int(t_str)
            except ValueError:
                continue

        chan = resolve(children[1], table)
        try:
            fn = int(resolve(children[2], table))
        except ValueError:
            continue
        slot = resolve(children[3], table)
        sub  = resolve(children[4], table)

        rows.append(
            dict(t_ns=t_ns, channel=chan, fn=fn, slot=slot, sub_id=sub)
        )
    return rows


def pair_dispatches(rows: List[dict]) -> Tuple[List[dict], int, int]:
    """Pair fn=1 (start) with fn=2 (end) by sub_id."""
    starts = {}
    paired = []
    unpaired_ends = 0
    for r in rows:
        key = r["sub_id"]
        if r["fn"] == 1:
            starts[key] = r
        elif r["fn"] == 2:
            s = starts.pop(key, None)
            if s is None:
                unpaired_ends += 1
                continue
            paired.append(dict(
                sub_id=key,
                channel=s["channel"],
                start_ns=s["t_ns"],
                end_ns=r["t_ns"],
                duration_ns=r["t_ns"] - s["t_ns"],
            ))
    return paired, unpaired_ends, len(starts)


# --------------------------------------------------------------------- #
# Schema 2: metal-application-encoders-list                             #
#   0: start-time                                                        #
#   1: duration                                                          #
#   2: thread                                                            #
#   3: process                                                           #
#   4: gpu (metal-device-name)                                           #
#   5: frame-number                                                      #
#   6: cmdbuffer-label                                                   #
#   7: cmdbuffer-label-indexed                                           #
#   8: encoder-label                                                     #
#   9: encoder-label-indexed                                             #
#  10: event-type                                                        #
#  11: cmdbuffer-id                                                      #
#  12: encoder-id                                                        #
# --------------------------------------------------------------------- #

def parse_encoders_list(xml_text: str) -> List[dict]:
    root = ET.fromstring(xml_text)
    rows = []
    table = {}
    for row in root.iter("row"):
        children = list(row)
        if len(children) < 13:
            continue

        # start-time (ns)
        t_text = (children[0].text or "").strip()
        try:
            t_ns = int(t_text)
        except ValueError:
            try:
                t_ns = int(resolve(children[0], table))
            except ValueError:
                continue

        # duration (ns)
        d_text = (children[1].text or "").strip()
        try:
            dur_ns = int(d_text) if d_text else int(resolve(children[1], table))
        except ValueError:
            continue

        encoder_label = resolve(children[8], table)
        cmdbuffer_label = resolve(children[6], table)
        event_type = resolve(children[10], table)

        rows.append(dict(
            start_ns=t_ns,
            duration_ns=dur_ns,
            encoder_label=encoder_label,
            cmdbuffer_label=cmdbuffer_label,
            event_type=event_type,
        ))
    return rows


# --------------------------------------------------------------------- #
# Schema 3: metal-shader-profiler-shader-list (iter9b kernel registry)  #
# Schema columns (verified from probe2 trace 2026-04-28T22:00Z, MST     #
# template, mlx-native@a7d2b95):                                        #
#   0: timestamp (ns)                                                    #
#   1: name           (metal-object-label)  e.g. "kernel_mul_mv_q4_0_f32 (35)"
#   2: label          (metal-object-label)  function label, often empty
#   3: pso-name       (metal-object-label)  e.g. "kernel_mul_mv_q4_0_f32"
#   4: id             (uint64)              cache_id from KernelRegistry
#   5: pc-start       (uint64)              GPU instruction-pointer start
#   6: pc-end         (uint64)              GPU instruction-pointer end
#   7: shader-type    (string)              "Compute" | "Vertex" | "Fragment"
#   8: process        (process)             e.g. "hf2q (93824)"
#   9: gpu            (metal-device-name)   "M5 Max"                     #
# --------------------------------------------------------------------- #

def parse_shader_list(xml_text: str, target_process_prefix: str) -> List[dict]:
    """Extract the kernel-label registry for a target process.

    Filter on process prefix (e.g. 'hf2q' / 'llama-cli') so we drop UI shaders
    from com.apple.WebKit.GPU and other system processes that share the trace.
    """
    root = ET.fromstring(xml_text)
    rows = []
    table = {}
    for row in root.iter("row"):
        children = list(row)
        if len(children) < 10:
            continue

        # name (col 1) — the kernel label with optional cache-id suffix " (N)"
        name = resolve(children[1], table)
        # pso-name (col 3) — the bare kernel label
        pso_name = resolve(children[3], table)
        cache_id = resolve(children[4], table)
        pc_start = resolve(children[5], table)
        pc_end = resolve(children[6], table)
        shader_type = resolve(children[7], table)
        proc = resolve(children[8], table)

        if not proc.startswith(target_process_prefix):
            continue
        if not name:
            continue

        rows.append(dict(
            name=name,
            pso_name=pso_name,
            cache_id=cache_id,
            pc_start=pc_start,
            pc_end=pc_end,
            shader_type=shader_type,
            process=proc,
        ))
    return rows


def kernel_family(label: str) -> str:
    """Group a labeled kernel into a coarse family for reporting.

    The labels come from mlx-native's KernelRegistry get_pipeline naming
    convention (iter9b). Strip optional cache-id suffix " (N)" and trailing
    function-constant key " | 0:b1 | 3:i32".
    """
    base = label.split("|", 1)[0].split(" (", 1)[0].strip()
    if not base.startswith("kernel_"):
        return base or "(unknown)"
    body = base[len("kernel_"):]
    # Common family prefixes — match longest first.
    families = [
        ("mul_mm_id_map0",        "moe_map0"),
        ("mul_mm_id_q4_0_tensor", "moe_q4_0_mm"),
        ("mul_mm_id_q5_K_tensor", "moe_q5_K_mm"),
        ("mul_mm_id_q6_K_tensor", "moe_q6_K_mm"),
        ("mul_mm_id",             "moe_mm"),
        ("mul_mv_id_q4_0",        "moe_q4_0_mv"),
        ("mul_mv_id_q5_K",        "moe_q5_K_mv"),
        ("mul_mv_id_q6_K",        "moe_q6_K_mv"),
        ("mul_mv_id_q8_0",        "moe_q8_0_mv"),
        ("mul_mv_id",             "moe_mv"),
        ("mul_mm_q4_0_tensor",    "dense_q4_0_mm"),
        ("mul_mm_q5_K_tensor",    "dense_q5_K_mm"),
        ("mul_mm_q6_K_tensor",    "dense_q6_K_mm"),
        ("mul_mm_q8_0_tensor",    "dense_q8_0_mm"),
        ("mul_mm",                "dense_mm"),
        ("mul_mv_q4_0",           "dense_q4_0_mv"),
        ("mul_mv_q5_K",           "dense_q5_K_mv"),
        ("mul_mv_q6_K",           "dense_q6_K_mv"),
        ("mul_mv_q8_0",           "dense_q8_0_mv"),
        ("mul_mv",                "dense_mv"),
        ("flash_attn",            "flash_attn"),
        ("rms_norm",              "rms_norm"),
        ("rope",                  "rope"),
        ("silu",                  "silu"),
        ("swiglu",                "swiglu"),
        ("kv_cache_copy",         "kv_cache"),
        ("argmax",                "argmax"),
        ("permute",               "permute"),
        ("cast",                  "cast"),
        ("residual_add",          "residual_add"),
        ("fused_norm",            "fused_norm"),
    ]
    for prefix, fam in families:
        if body.startswith(prefix):
            return fam
    return "other_" + body.split("_", 1)[0]


def shader_list_summary(rows: List[dict]) -> dict:
    """Group registered shaders by family and dedupe by pso_name."""
    by_family = defaultdict(set)
    for r in rows:
        fam = kernel_family(r["name"])
        # Dedupe by pso-name (which is the bare label without cache-id suffix);
        # function-constant variants share pso-name in iter9b.
        by_family[fam].add(r.get("pso_name", "") or r["name"])
    out = {}
    for fam, names in by_family.items():
        out[fam] = sorted(n for n in names if n)
    return out


# --------------------------------------------------------------------- #
# iter12: Per-encoder attribution                                       #
# --------------------------------------------------------------------- #
#
# Why this exists:
#   iter11 produced hf2q per-layer comparison via debug-group bucketing
#   on metal-application-encoders-list, but llama side was unattributed
#   (1 trace only, plus llama.cpp does not pushDebugGroup so no per-layer
#   debug-group labels are available). iter12 adds a CLI-only per-encoder
#   attribution path that works for BOTH binaries:
#
#     1. Read metal-application-encoders-list rows.
#     2. Filter to event-type="Encoding" and process matching the binary.
#     3. Bucket by (cmdbuffer-label, encoder-label) — both are short generic
#        names like "Command Buffer 0" / "Compute Command 0" / "Blit Command 0"
#        because neither llama.cpp nor mlx-native sets MTLCommandBuffer.label
#        / MTLComputeCommandEncoder.label or pushes debug groups.
#     4. The encoders-list duration is the encoder LIFETIME (host-side
#        encoding wall-clock), NOT GPU execution time. For GPU time, JOIN
#        encoders-list rows to metal-gpu-execution-points by encoder-id,
#        which exposes per-encoder GPU durations after we re-pair fn=1/2.
#     5. Sum per-bucket GPU µs/token; report side-by-side hf2q vs llama
#        with Δµs/tok and Δ%.
#
# Granularity caveat: "encoder bucket" here is COARSER than per-kernel-name
# attribution. On a typical decode token both hf2q and llama emit a single
# Compute encoder containing many dispatches, so per-encoder attribution
# nets out to roughly per-CB attribution. This is still useful for iter12
# because it answers the question "is the gap in compute encoders or in
# blit/setup encoders?" — which is a structurally different question from
# the per-dispatch (per-kernel) bucketing that BUCKETS handles upstream.
# --------------------------------------------------------------------- #


def parse_encoders_list_with_ids(xml_text: str, target_process_prefix: str = "") -> List[dict]:
    """Like parse_encoders_list but also captures cmdbuffer-id + encoder-id.

    Filters by process when target_process_prefix is non-empty so that
    parallel-process compositor frames (cmux/Safari/etc. that share the
    Metal trace) don't pollute the per-binary count.

    The xctrace XML uses NESTED id/ref dictionaries: e.g. col 2 (thread)
    contains a nested <process id=5 fmt="llama-bench (8455)">, and col 3
    (process) is just <process ref=5/>.  resolve() only handles direct
    id/ref so we need a pre-pass that walks all sub-elements of each row
    to register their fmt values into the id table.

    Schema columns (verified 2026-04-28 against iter11 llama trace):
      0: start-time (ns)
      1: duration (ns)
      2: thread (nested <tid> + <process id=N fmt="...">)
      3: process (ref to nested process id from col 2)
      4: gpu (metal-device-name)
      5: frame-number
      6: cmdbuffer-label
      7: cmdbuffer-label-indexed
      8: encoder-label
      9: encoder-label-indexed
     10: event-type
     11: cmdbuffer-id
     12: encoder-id
    """
    root = ET.fromstring(xml_text)
    rows = []
    table: Dict[str, str] = {}

    def _register_subtree(elem):
        """Walk elem and all descendants; populate id->fmt table."""
        rid = elem.get("id")
        if rid is not None:
            fmt = elem.get("fmt")
            if fmt is not None:
                table[rid] = fmt
            else:
                t = (elem.text or "").strip()
                if t:
                    table[rid] = t
        for child in elem:
            _register_subtree(child)

    # iter16 fix: duration (and start-time) cells store raw nanoseconds in
    # `<duration ... text>NNN</duration>` when the cell has an `id=`, but
    # ref'd cells (`<duration ref="58"/>`) drop the raw text and only carry
    # `fmt="9.62 µs"` via the dictionary. We need a numeric-text store keyed
    # by id, populated alongside `_register_subtree`'s fmt store. Without
    # this, ~70% of rows on traces with deduplicated durations fail to parse
    # and silently drop out of the per-CB aggregation (verified iter16 against
    # /tmp/adr015-iter16/traces/hf2q-trial-2.trace: 1899/2786 rows failed
    # with the original logic, recovering only 887 of 2786 encoders).
    text_table: Dict[str, int] = {}

    def _register_text(elem):
        rid = elem.get("id")
        if rid is not None:
            t = (elem.text or "").strip()
            if t:
                try:
                    text_table[rid] = int(t)
                except ValueError:
                    pass
        for child in elem:
            _register_text(child)

    _register_text(root)

    for row in root.iter("row"):
        # Pre-pass: register all id/fmt pairs for this row's subtree.
        _register_subtree(row)

        children = list(row)
        if len(children) < 13:
            continue

        t_text = (children[0].text or "").strip()
        try:
            if t_text:
                t_ns = int(t_text)
            else:
                ref = children[0].get("ref")
                if ref is not None and ref in text_table:
                    t_ns = text_table[ref]
                else:
                    t_ns = int(resolve(children[0], table))
        except ValueError:
            continue

        d_text = (children[1].text or "").strip()
        try:
            if d_text:
                dur_ns = int(d_text)
            else:
                ref = children[1].get("ref")
                if ref is not None and ref in text_table:
                    dur_ns = text_table[ref]
                else:
                    dur_ns = int(resolve(children[1], table))
        except ValueError:
            continue

        # Resolve process via the registered table (col 3 is a ref to a
        # nested id under col 2's thread element).
        proc_elem = children[3]
        proc_str = resolve(proc_elem, table) or ""
        # If still empty, pull directly from ref->table.
        if not proc_str:
            ref = proc_elem.get("ref")
            if ref is not None:
                proc_str = table.get(ref, "") or ""

        encoder_label = resolve(children[8], table)
        cmdbuffer_label = resolve(children[6], table)
        event_type = resolve(children[10], table)

        cmdbuf_id = None
        enc_id = None
        if len(children) > 11:
            cmdbuf_id = resolve(children[11], table)
        if len(children) > 12:
            enc_id = resolve(children[12], table)

        if target_process_prefix and not proc_str.startswith(target_process_prefix):
            continue

        rows.append(dict(
            start_ns=t_ns,
            duration_ns=dur_ns,
            encoder_label=encoder_label,
            cmdbuffer_label=cmdbuffer_label,
            event_type=event_type,
            cmdbuffer_id=cmdbuf_id,
            encoder_id=enc_id,
            process=proc_str,
        ))
    return rows


def encoder_family(enc_label: str) -> str:
    """Coarsen encoder label to a stable family for cross-trial comparison."""
    if not enc_label:
        return "(unknown)"
    if enc_label.startswith("Compute Command"):
        return "compute"
    if enc_label.startswith("Blit Command"):
        return "blit"
    if enc_label.startswith("Render Command"):
        return "render"
    if enc_label.startswith("Acceleration"):
        return "accel"
    return enc_label.split(" ")[0].lower() or "(unknown)"


def parse_submission_to_encoder_map(xml_text: str, target_process_prefix: str = "") -> Dict[str, str]:
    """Build sub_id -> encoder_id map from metal-gpu-submission-to-command-buffer-id.

    Schema columns (verified 2026-04-28 against iter11 llama trace):
      0: timestamp
      1: cmdbuffer-id
      2: gpu-submission-id  ← matches metal-gpu-execution-points.sub_id
      3: segment-id
      4: segmentlist-id
      5: encoder-id         ← matches metal-application-encoders-list.encoder_id
      6: accelerator-id
      ...
     12: process            ← filter target

    Filtered to the target binary's process so cmux/Safari compositor frames
    don't pollute the per-binary join.
    """
    root = ET.fromstring(xml_text)
    out: Dict[str, str] = {}
    table: Dict[str, str] = {}

    def _register_subtree(elem):
        rid = elem.get("id")
        if rid is not None:
            fmt = elem.get("fmt")
            if fmt is not None:
                table[rid] = fmt
            else:
                t = (elem.text or "").strip()
                if t:
                    table[rid] = t
        for child in elem:
            _register_subtree(child)

    for row in root.iter("row"):
        _register_subtree(row)
        children = list(row)
        if len(children) < 13:
            continue
        sub_id = resolve(children[2], table) or ""
        enc_id = resolve(children[5], table) or ""
        proc_elem = children[12]
        proc_str = resolve(proc_elem, table) or ""
        if not proc_str:
            ref = proc_elem.get("ref")
            if ref is not None:
                proc_str = table.get(ref, "") or ""
        if target_process_prefix and not proc_str.startswith(target_process_prefix):
            continue
        if sub_id and enc_id:
            out[sub_id] = enc_id
    return out


def encoder_gpu_summary(
    encoders: List[dict],
    paired_dispatches: List[dict],
    sub_to_enc: Dict[str, str],
) -> Dict[str, dict]:
    """Bucket encoders by family and accumulate GPU duration via dispatch joins.

    JOIN PATH (verified 2026-04-28 against iter11 llama trial-1):
        1. metal-gpu-execution-points fn=1/2 paired by sub_id
                → paired dispatches with `sub_id`
        2. metal-gpu-submission-to-command-buffer-id maps sub_id → encoder_id
                → produces per-dispatch encoder attribution
        3. metal-application-encoders-list maps encoder_id → label
                → groups into family (compute / blit / render / accel)

    Without the submission-to-cb-id intermediary, sub_id and encoder_id
    live in DIFFERENT id namespaces (sub_id is 32-bit GPU submission counter,
    encoder_id is 40-bit MTLObject id) — the iter12 fix is to wire that
    table in.

    Returns: { family -> { count_encoders, gpu_sum_ns, host_sum_ns,
                           count_dispatches_in_encoder_family } }
    """
    enc_by_id: Dict[str, str] = {}
    enc_count_by_family: Dict[str, int] = defaultdict(int)
    enc_host_sum_by_family: Dict[str, int] = defaultdict(int)
    seen_ids = set()
    for e in encoders:
        eid = e.get("encoder_id")
        if not eid or eid in seen_ids:
            continue
        seen_ids.add(eid)
        fam = encoder_family(e.get("encoder_label", ""))
        enc_by_id[eid] = fam
        enc_count_by_family[fam] += 1
        enc_host_sum_by_family[fam] += e.get("duration_ns", 0)

    enc_gpu_sum_by_family: Dict[str, int] = defaultdict(int)
    enc_disp_count_by_family: Dict[str, int] = defaultdict(int)
    matched = 0
    unmatched = 0
    unmapped = 0
    for p in paired_dispatches:
        sid = p.get("sub_id")
        eid = sub_to_enc.get(sid)
        if eid is None:
            unmapped += 1
            continue
        fam = enc_by_id.get(eid)
        if fam is None:
            unmatched += 1
            continue
        matched += 1
        enc_gpu_sum_by_family[fam] += p.get("duration_ns", 0)
        enc_disp_count_by_family[fam] += 1

    out: Dict[str, dict] = {}
    families = set(enc_by_id.values())
    families.update(enc_gpu_sum_by_family.keys())
    for fam in sorted(families):
        out[fam] = dict(
            count_encoders=enc_count_by_family.get(fam, 0),
            count_dispatches_in_encoder_family=enc_disp_count_by_family.get(fam, 0),
            host_sum_ns=enc_host_sum_by_family.get(fam, 0),
            gpu_sum_ns=enc_gpu_sum_by_family.get(fam, 0),
        )
    out["_meta"] = dict(
        matched_dispatches=matched,
        unmatched_dispatches=unmatched,  # mapped to enc_id but family unknown (rare)
        unmapped_dispatches=unmapped,    # sub_id not in submission-map (cross-process)
        total_encoders=len(seen_ids),
    )
    return out


def median_encoder_summaries(per_trial: List[Dict[str, dict]], n_tokens_list: List[int]) -> Dict[str, dict]:
    """Median across trials for each encoder family."""
    if not per_trial:
        return {}
    families = set()
    for s in per_trial:
        families.update(k for k in s.keys() if not k.startswith("_"))
    out: Dict[str, dict] = {}
    for fam in sorted(families):
        gpu_us_per_tok = []
        host_us_per_tok = []
        n_enc_per_tok = []
        for s, n_tok in zip(per_trial, n_tokens_list):
            n_tok = max(n_tok, 1)
            b = s.get(fam) or {}
            gpu_us_per_tok.append(b.get("gpu_sum_ns", 0) / 1000.0 / n_tok)
            host_us_per_tok.append(b.get("host_sum_ns", 0) / 1000.0 / n_tok)
            n_enc_per_tok.append(b.get("count_encoders", 0) / n_tok)
        out[fam] = dict(
            median_gpu_us_per_token=statistics.median(gpu_us_per_tok),
            median_host_us_per_token=statistics.median(host_us_per_tok),
            median_encoders_per_token=statistics.median(n_enc_per_tok),
            gpu_us_per_token_per_trial=gpu_us_per_tok,
        )
    return out


# --------------------------------------------------------------------- #
# iter16: Per-CB-label attribution (semantic phase names)               #
# --------------------------------------------------------------------- #
#
# Why this exists (vs iter12 per-encoder family bucketing):
#   iter12 per-encoder attribution coarsens to {compute, blit, render, accel}
#   because neither hf2q nor llama set MTLCommandBuffer.label or
#   MTLComputeCommandEncoder.label. iter15 §E discovered the missing wire-up;
#   iter16 lands `cmd_buf.set_label(label)` + active-encoder set_label inside
#   `mlx_native::CommandEncoder::commit_*labeled`, which propagates the
#   semantic phase string (e.g. "layer.attn_moe_ffn",
#   "output_head.fused_norm_lm_argmax", "layer.delta_net.ops1-9") to xctrace's
#   `metal-application-encoders-list.cmdbuffer-label` column.
#
# Aggregation:
#   1. Reuse iter12's parse_encoders_list_with_ids + parse_submission_to_encoder_map
#      pipeline.
#   2. Group by `cmdbuffer_label` (semantic phase name) instead of
#      encoder_family.
#   3. Sum per-CB GPU duration via the same join (sub_id -> encoder_id ->
#      cmdbuffer_label).
#   4. Report side-by-side hf2q vs llama (both should now carry semantic
#      labels for hf2q; llama still emits generic "Command Buffer N" because
#      llama.cpp does not setLabel — that's a comparable-axis issue but the
#      hf2q-side breakdown is the actionable signal for iter17 hypothesis
#      ranking).
#
# Phase-name normalization: strip per-layer indices when present so layer 0
# through layer 39 collapse into a single "layer.attn_moe_ffn" row instead of
# 40 separate rows. The current hf2q labels happen to be layer-index-free
# already (fixed phase names emitted from the inner loop), but
# `gpu_ffn::proj()` and others use `format!("{label_prefix}.gate_up")` which
# may inherit a per-layer prefix in the future — preempt that.
# --------------------------------------------------------------------- #


def normalize_phase_label(label: str) -> str:
    """Collapse per-layer index suffixes / prefixes into a single phase name.

    Examples:
      "layer.42.attn_moe_ffn"   -> "layer.attn_moe_ffn"
      "layer.attn_moe_ffn.42"   -> "layer.attn_moe_ffn"
      "layer.attn_moe_ffn"      -> "layer.attn_moe_ffn"
      "Command Buffer 0"        -> "Command Buffer 0"   (unchanged generic)
      "[0] Command Buffer 0"    -> "Command Buffer 0"   (strip index prefix)
    """
    if not label:
        return "(unknown)"
    # Strip metal-rs-style indexed prefix "[N] " that appears in
    # cmdbuffer-label-indexed but is sometimes echoed into cmdbuffer-label.
    if label.startswith("[") and "] " in label:
        label = label.split("] ", 1)[1]
    # Drop per-layer numeric segments (forward and reverse).
    parts = label.split(".")
    parts = [p for p in parts if not p.isdigit()]
    return ".".join(parts) if parts else label


def cb_label_gpu_summary(
    encoders: List[dict],
    paired_dispatches: List[dict],
    sub_to_enc: Dict[str, str],
) -> Dict[str, dict]:
    """Bucket dispatches by the cmdbuffer-label of their owning encoder.

    JOIN PATH (iter16, building on iter12):
        1. metal-gpu-execution-points fn=1/2 paired by sub_id
                -> per-dispatch (sub_id, duration_ns)
        2. metal-gpu-submission-to-command-buffer-id maps sub_id -> encoder_id
        3. metal-application-encoders-list maps encoder_id -> cmdbuffer_label
        4. normalize_phase_label collapses per-layer indices.

    Returns: {phase_label -> {count_cbs, count_dispatches, gpu_sum_ns,
                               host_sum_ns}}
    """
    enc_to_phase: Dict[str, str] = {}
    enc_to_host_ns: Dict[str, int] = {}
    seen_enc = set()
    cb_count_by_phase: Dict[str, int] = defaultdict(int)
    enc_host_sum_by_phase: Dict[str, int] = defaultdict(int)

    for e in encoders:
        eid = e.get("encoder_id")
        if not eid or eid in seen_enc:
            continue
        seen_enc.add(eid)
        phase = normalize_phase_label(e.get("cmdbuffer_label", "") or "")
        enc_to_phase[eid] = phase
        enc_to_host_ns[eid] = e.get("duration_ns", 0)
        cb_count_by_phase[phase] += 1
        enc_host_sum_by_phase[phase] += e.get("duration_ns", 0)

    enc_gpu_sum_by_phase: Dict[str, int] = defaultdict(int)
    enc_disp_count_by_phase: Dict[str, int] = defaultdict(int)
    matched = 0
    unmapped = 0
    unmatched_phase = 0
    for p in paired_dispatches:
        sid = p.get("sub_id")
        eid = sub_to_enc.get(sid)
        if eid is None:
            unmapped += 1
            continue
        phase = enc_to_phase.get(eid)
        if phase is None:
            unmatched_phase += 1
            continue
        matched += 1
        enc_gpu_sum_by_phase[phase] += p.get("duration_ns", 0)
        enc_disp_count_by_phase[phase] += 1

    out: Dict[str, dict] = {}
    phases = set(enc_to_phase.values())
    phases.update(enc_gpu_sum_by_phase.keys())
    for phase in sorted(phases):
        out[phase] = dict(
            count_cbs=cb_count_by_phase.get(phase, 0),
            count_dispatches=enc_disp_count_by_phase.get(phase, 0),
            host_sum_ns=enc_host_sum_by_phase.get(phase, 0),
            gpu_sum_ns=enc_gpu_sum_by_phase.get(phase, 0),
        )
    out["_meta"] = dict(
        matched_dispatches=matched,
        unmapped_dispatches=unmapped,
        unmatched_phase_dispatches=unmatched_phase,
        total_encoders=len(seen_enc),
        labelled_encoders=sum(
            1 for p in enc_to_phase.values()
            if p and not p.startswith("Command Buffer")
            and not p.startswith("Compute Command")
        ),
    )
    return out


def median_cb_label_summaries(
    per_trial: List[Dict[str, dict]], n_tokens_list: List[int]
) -> Dict[str, dict]:
    """Median across trials for each phase label."""
    if not per_trial:
        return {}
    phases = set()
    for s in per_trial:
        phases.update(k for k in s.keys() if not k.startswith("_"))
    out: Dict[str, dict] = {}
    for phase in sorted(phases):
        gpu_us_per_tok = []
        host_us_per_tok = []
        cbs_per_tok = []
        disps_per_tok = []
        for s, n_tok in zip(per_trial, n_tokens_list):
            n_tok = max(n_tok, 1)
            b = s.get(phase) or {}
            gpu_us_per_tok.append(b.get("gpu_sum_ns", 0) / 1000.0 / n_tok)
            host_us_per_tok.append(b.get("host_sum_ns", 0) / 1000.0 / n_tok)
            cbs_per_tok.append(b.get("count_cbs", 0) / n_tok)
            disps_per_tok.append(b.get("count_dispatches", 0) / n_tok)
        out[phase] = dict(
            median_gpu_us_per_token=statistics.median(gpu_us_per_tok),
            median_host_us_per_token=statistics.median(host_us_per_tok),
            median_cbs_per_token=statistics.median(cbs_per_tok),
            median_dispatches_per_token=statistics.median(disps_per_tok),
            mean_us_per_cb=(
                statistics.mean(gpu_us_per_tok) / max(statistics.mean(cbs_per_tok), 1e-9)
                if cbs_per_tok and any(c > 0 for c in cbs_per_tok)
                else 0.0
            ),
            gpu_us_per_token_per_trial=gpu_us_per_tok,
        )
    return out


# --------------------------------------------------------------------- #
# Bucketing by dispatch duration                                        #
# --------------------------------------------------------------------- #

# Empirical buckets for the dwq46 decode workload (verified against
# qwen35/forward_gpu.rs structural counts). Boundaries chosen so that
# each bucket cleanly maps to a kernel class:
#   [0,    2_000)   ns   small ops: rms_norm, scalar mul, reshape, etc.
#   [2_000, 8_000)  ns   medium: small mat-vecs (Q/K/V dense if not fused),
#                        rope, soft-cap
#   [8_000, 32_000) ns   Q4_0 mat-vec MoE expert dispatches (heart of gap)
#   [32_000, 80_000) ns  flash_attn, mul_mm_id pooled
#   [80_000, +∞)    ns   prefill mul_mm_id, lm_head, large blits
BUCKETS = [
    ("xs_<2us",     0,         2_000),
    ("sm_2_8us",    2_000,     8_000),
    ("md_8_32us",   8_000,     32_000),
    ("lg_32_80us",  32_000,    80_000),
    ("xl_>=80us",   80_000,    None),
]


def bucket_of(dur_ns: int) -> str:
    for name, lo, hi in BUCKETS:
        if dur_ns >= lo and (hi is None or dur_ns < hi):
            return name
    return "unknown"


def bucket_summary(paired: List[dict]) -> Dict[str, dict]:
    """Compute per-bucket count + sum + p50 + p95."""
    by_bucket = defaultdict(list)
    for p in paired:
        by_bucket[bucket_of(p["duration_ns"])].append(p["duration_ns"])

    out = {}
    for name, _, _ in BUCKETS:
        durs = by_bucket.get(name, [])
        out[name] = dict(
            count=len(durs),
            sum_ns=sum(durs),
            p50_ns=int(statistics.median(durs)) if durs else 0,
            p95_ns=int(durs[int(0.95 * (len(durs) - 1))]) if len(durs) >= 2 else (durs[0] if durs else 0),
            mean_ns=int(sum(durs) / len(durs)) if durs else 0,
        )
    out["_total"] = dict(
        count=len(paired),
        sum_ns=sum(p["duration_ns"] for p in paired),
    )
    return out


# --------------------------------------------------------------------- #
# Per-trace summary                                                     #
# --------------------------------------------------------------------- #

def summarize_trace(trace_path: str, n_tokens: int, target_process_prefix: str = "") -> dict:
    """Return per-trace bucketed dispatch summary plus iter11 shader registry.

    target_process_prefix filters the iter11 shader-list registry to the
    binary under test (e.g. "hf2q" / "llama-cli") so UI shaders from the
    system browser/window-server don't pollute the report.
    """
    xml = export_table(trace_path, "metal-gpu-execution-points")
    rows = parse_gpu_execution_points(xml)
    paired, unpaired_ends, leftover = pair_dispatches(rows)

    enc_xml = export_table(trace_path, "metal-application-encoders-list")
    encoders = parse_encoders_list(enc_xml)

    # iter12: per-encoder attribution.  Reparse encoders with process
    # filter + encoder/cmdbuffer ids so we can join to per-dispatch GPU
    # times by sub_id.  Filter to the binary's process so cmux/Safari
    # compositor frames don't pollute counts.
    encoders_filtered = parse_encoders_list_with_ids(
        enc_xml, target_process_prefix=target_process_prefix or ""
    )
    # iter12: load submission-to-cb-id table for sub_id -> encoder_id join.
    sub_to_enc: Dict[str, str] = {}
    try:
        map_xml = export_table(trace_path, "metal-gpu-submission-to-command-buffer-id")
        sub_to_enc = parse_submission_to_encoder_map(
            map_xml, target_process_prefix=target_process_prefix or ""
        )
    except Exception:
        pass
    encoder_gpu = encoder_gpu_summary(encoders_filtered, paired, sub_to_enc)

    # iter16: per-CB-label (semantic phase) attribution. Same join as
    # iter12 but groups by cmdbuffer-label instead of encoder-family.
    cb_label_gpu = cb_label_gpu_summary(encoders_filtered, paired, sub_to_enc)

    # iter11: surface the now-populated shader-list registry. Returns {} on
    # any error (e.g. older traces) so iter9 archived bundles still work.
    shader_registry: Dict[str, List[str]] = {}
    shader_count = 0
    try:
        sl_xml = export_table(trace_path, "metal-shader-profiler-shader-list")
        sl_rows = parse_shader_list(sl_xml, target_process_prefix or "")
        shader_count = len(sl_rows)
        shader_registry = shader_list_summary(sl_rows)
    except Exception:
        pass

    # iter11: probe Shader Timeline samples — expected to be empty until
    # iter11b enabler lands or GUI Instruments.app is used.
    shader_timeline_rows = 0
    try:
        st_xml = export_table(trace_path, "metal-shader-profiler-intervals")
        # Cheap row count without full parse.
        shader_timeline_rows = st_xml.count("<row")
    except Exception:
        pass

    buckets = bucket_summary(paired)
    total_gpu_ns = buckets["_total"]["sum_ns"]
    total_dispatches = buckets["_total"]["count"]

    return dict(
        path=trace_path,
        rows=len(rows),
        paired=len(paired),
        unpaired_ends=unpaired_ends,
        leftover_starts=leftover,
        encoders=len(encoders),
        encoder_total_ns=sum(e["duration_ns"] for e in encoders),
        n_tokens=n_tokens,
        buckets=buckets,
        # Per-token attribution
        dispatches_per_token=total_dispatches / max(n_tokens, 1),
        gpu_us_per_token=total_gpu_ns / 1000.0 / max(n_tokens, 1),
        # iter11 additions
        shader_registry=shader_registry,
        shader_count=shader_count,
        shader_timeline_rows=shader_timeline_rows,
        # iter12 additions: per-encoder bucket attribution
        encoder_filtered_count=len(encoders_filtered),
        encoder_gpu=encoder_gpu,
        # iter16 addition: per-CB-label semantic-phase attribution
        cb_label_gpu=cb_label_gpu,
    )


def median_summaries(summaries: List[dict]) -> dict:
    """Combine N per-trial summaries into a single median view."""
    if not summaries:
        return {}
    # iter11: union the shader-registry across trials (set by family,
    # alphabetical for reporting).
    registry_union: Dict[str, set] = defaultdict(set)
    for s in summaries:
        for fam, names in (s.get("shader_registry") or {}).items():
            registry_union[fam].update(names)
    registry_out = {fam: sorted(names) for fam, names in registry_union.items()}

    shader_timeline_rows_max = max(
        (s.get("shader_timeline_rows", 0) for s in summaries), default=0
    )

    # iter12: median encoder attribution across trials
    encoder_gpu_per_trial = [s.get("encoder_gpu", {}) for s in summaries]
    n_tokens_per_trial = [s["n_tokens"] for s in summaries]
    encoder_gpu_med = median_encoder_summaries(encoder_gpu_per_trial, n_tokens_per_trial)

    # iter16: median per-CB-label attribution across trials
    cb_label_gpu_per_trial = [s.get("cb_label_gpu", {}) for s in summaries]
    cb_label_gpu_med = median_cb_label_summaries(cb_label_gpu_per_trial, n_tokens_per_trial)

    out = {
        "n_trials": len(summaries),
        "n_tokens_per_trial": n_tokens_per_trial,
        "paired_per_trial": [s["paired"] for s in summaries],
        "gpu_us_per_token_per_trial": [s["gpu_us_per_token"] for s in summaries],
        "median_dispatches_per_token": statistics.median(
            [s["dispatches_per_token"] for s in summaries]
        ),
        "median_gpu_us_per_token": statistics.median(
            [s["gpu_us_per_token"] for s in summaries]
        ),
        "buckets": {},
        # iter11 additions
        "shader_registry": registry_out,
        "shader_timeline_rows": shader_timeline_rows_max,
        # iter12 additions
        "encoder_gpu": encoder_gpu_med,
        "encoder_gpu_per_trial": encoder_gpu_per_trial,
        # iter16 additions
        "cb_label_gpu": cb_label_gpu_med,
        "cb_label_gpu_per_trial": cb_label_gpu_per_trial,
    }
    for name, _, _ in BUCKETS:
        counts_per_tok = []
        sums_per_tok_us = []
        p50_us = []
        for s in summaries:
            n_tok = max(s["n_tokens"], 1)
            b = s["buckets"].get(name, {})
            counts_per_tok.append(b.get("count", 0) / n_tok)
            sums_per_tok_us.append(b.get("sum_ns", 0) / 1000.0 / n_tok)
            p50_us.append(b.get("p50_ns", 0) / 1000.0)
        out["buckets"][name] = dict(
            median_dispatches_per_token=statistics.median(counts_per_tok),
            median_us_per_token=statistics.median(sums_per_tok_us),
            median_p50_us_per_dispatch=statistics.median(p50_us),
        )
    return out


# --------------------------------------------------------------------- #
# Side-by-side report                                                   #
# --------------------------------------------------------------------- #

def fmt_int(v) -> str:
    if isinstance(v, float):
        if v >= 100:
            return f"{v:>10.1f}"
        return f"{v:>10.3f}"
    return f"{v:>10}"


def write_report(out_path: str, hf2q: dict, llama: dict, hf2q_trials: List[dict], llama_trials: List[dict]):
    lines = []
    lines.append("=" * 110)
    lines.append("ADR-015 iter9/iter11 — Q4_0 dispatch attribution (xctrace MST)")
    lines.append("=" * 110)
    lines.append("")
    lines.append("Methodology:")
    lines.append("  - canonical frame: metal-gpu-execution-points fn=1/2 paired by sub_id (per AC2)")
    lines.append("  - encoders sidecar: metal-application-encoders-list (informational; not summed)")
    lines.append("  - iter11 status: kernel REGISTRY surfaced via metal-shader-profiler-shader-list")
    lines.append("    (now populated post-iter9b labels at mlx-native@a7d2b95).  Per-dispatch")
    lines.append("    PSO→duration JOIN STILL BLOCKED: no per-dispatch table carries pso-id, and")
    lines.append("    Shader Timeline (the metal-shader-profiler-intervals row source) cannot be")
    lines.append("    enabled from xctrace CLI.  iter11 verified 4 incantations:")
    lines.append("      (a) default `Metal System Trace`")
    lines.append("      (b) MST + --instrument 'Metal GPU Counters' / 'Metal Performance Overview'")
    lines.append("              + --instrument 'Advanced Graphics Statistics'")
    lines.append("      (c) MST + (b) + --instrument 'Metal Application' + --instrument 'GPU'")
    lines.append("      (d) `Game Performance` template")
    lines.append("    All produce the kernel-name registry but ZERO Shader Timeline samples.")
    lines.append("    Recommended pivot: iter11b enabler = mlx-native pushDebugGroup(label) +")
    lines.append("    popDebugGroup() around each kernel dispatch in src/encoder.rs.")
    lines.append("  - bucketing strategy (best-available CLI signal): per-dispatch duration")
    lines.append("    histogram into 5 bands, where each band cleanly maps to a kernel class on")
    lines.append("    the dwq46 decode workload:")
    lines.append("      xs_<2us     : rms_norm, scalar mul, reshape")
    lines.append("      sm_2_8us    : rope, soft-cap, small mat-vec")
    lines.append("      md_8_32us   : Q4_0 MoE mat-vec_id (gate/up/down), dense Q4_0 mat-vec")
    lines.append("      lg_32_80us  : flash_attn, pooled mul_mm_id")
    lines.append("      xl_>=80us   : prefill mul_mm_id, lm_head, large blits")
    lines.append("")
    lines.append("Inputs:")
    lines.append(f"  hf2q  trials: {len(hf2q_trials)}")
    for s in hf2q_trials:
        lines.append(f"    - {os.path.basename(s['path'])}: paired={s['paired']:>6d} dispatches "
                     f"({s['dispatches_per_token']:.1f}/tok), gpu={s['gpu_us_per_token']:.1f} µs/tok")
    lines.append(f"  llama trials: {len(llama_trials)}")
    for s in llama_trials:
        lines.append(f"    - {os.path.basename(s['path'])}: paired={s['paired']:>6d} dispatches "
                     f"({s['dispatches_per_token']:.1f}/tok), gpu={s['gpu_us_per_token']:.1f} µs/tok")
    lines.append("")

    if hf2q and llama:
        lines.append("=" * 110)
        lines.append("Side-by-side bucketed attribution (medians across trials)")
        lines.append("=" * 110)
        header = (f"{'BUCKET':<14s}  "
                  f"{'hf2q disp/tok':>14s}  {'hf2q µs/disp':>14s}  {'hf2q µs/tok':>14s}  "
                  f"{'llama disp/tok':>15s}  {'llama µs/disp':>15s}  {'llama µs/tok':>14s}  "
                  f"{'Δµs/tok':>10s}  {'Δ%':>8s}")
        lines.append(header)
        lines.append("-" * len(header))
        for name, _, _ in BUCKETS:
            hb = hf2q["buckets"][name]
            lb = llama["buckets"][name]
            d_us = hb["median_us_per_token"] - lb["median_us_per_token"]
            d_pct = (d_us / lb["median_us_per_token"] * 100) if lb["median_us_per_token"] > 0 else 0.0
            lines.append(
                f"{name:<14s}  "
                f"{hb['median_dispatches_per_token']:>14.1f}  "
                f"{hb['median_p50_us_per_dispatch']:>14.2f}  "
                f"{hb['median_us_per_token']:>14.1f}  "
                f"{lb['median_dispatches_per_token']:>15.1f}  "
                f"{lb['median_p50_us_per_dispatch']:>15.2f}  "
                f"{lb['median_us_per_token']:>14.1f}  "
                f"{d_us:>+10.1f}  "
                f"{d_pct:>+7.1f}%"
            )
        lines.append("-" * len(header))
        lines.append(
            f"{'TOTAL':<14s}  "
            f"{hf2q['median_dispatches_per_token']:>14.1f}  "
            f"{'-':>14s}  "
            f"{hf2q['median_gpu_us_per_token']:>14.1f}  "
            f"{llama['median_dispatches_per_token']:>15.1f}  "
            f"{'-':>15s}  "
            f"{llama['median_gpu_us_per_token']:>14.1f}  "
            f"{(hf2q['median_gpu_us_per_token'] - llama['median_gpu_us_per_token']):>+10.1f}  "
            f"{((hf2q['median_gpu_us_per_token'] - llama['median_gpu_us_per_token']) / llama['median_gpu_us_per_token'] * 100):>+7.1f}%"
        )
        lines.append("")
        lines.append("Q4_0-attributable summary (md_8_32us bucket — Q4_0 MoE mat-vec_id territory):")
        hb = hf2q["buckets"]["md_8_32us"]
        lb = llama["buckets"]["md_8_32us"]
        lines.append(f"  hf2q : {hb['median_dispatches_per_token']:.1f} disp/tok × {hb['median_p50_us_per_dispatch']:.2f} µs/disp = {hb['median_us_per_token']:.1f} µs/tok")
        lines.append(f"  llama: {lb['median_dispatches_per_token']:.1f} disp/tok × {lb['median_p50_us_per_dispatch']:.2f} µs/disp = {lb['median_us_per_token']:.1f} µs/tok")
        d_us = hb["median_us_per_token"] - lb["median_us_per_token"]
        d_pct_of_total = d_us / max(llama["median_gpu_us_per_token"], 1) * 100
        lines.append(f"  delta: {d_us:+.1f} µs/tok ({d_pct_of_total:+.2f}% of llama wall)")
        lines.append("")
        lines.append("Iter10 attack target (largest positive Δµs/tok bucket):")
        target = max(BUCKETS, key=lambda b: hf2q["buckets"][b[0]]["median_us_per_token"] - llama["buckets"][b[0]]["median_us_per_token"])
        tname = target[0]
        d_us = hf2q["buckets"][tname]["median_us_per_token"] - llama["buckets"][tname]["median_us_per_token"]
        lines.append(f"  bucket: {tname}")
        lines.append(f"  Δµs/tok: {d_us:+.1f}")
        lines.append(f"  Likely kernel class: {bucket_kernel_hint(tname)}")
        lines.append("")
    elif hf2q:
        lines.append("=" * 110)
        lines.append("hf2q-only partial attribution (llama traces not yet available)")
        lines.append("=" * 110)
        header = f"{'BUCKET':<14s}  {'disp/tok':>10s}  {'µs/disp p50':>14s}  {'µs/tok':>10s}"
        lines.append(header)
        lines.append("-" * len(header))
        for name, _, _ in BUCKETS:
            hb = hf2q["buckets"][name]
            lines.append(
                f"{name:<14s}  "
                f"{hb['median_dispatches_per_token']:>10.1f}  "
                f"{hb['median_p50_us_per_dispatch']:>14.2f}  "
                f"{hb['median_us_per_token']:>10.1f}"
            )
        lines.append(
            f"{'TOTAL':<14s}  "
            f"{hf2q['median_dispatches_per_token']:>10.1f}  "
            f"{'-':>14s}  "
            f"{hf2q['median_gpu_us_per_token']:>10.1f}"
        )
        lines.append("")
    else:
        lines.append("(no traces summarised)")

    # iter12: per-encoder attribution side-by-side.  This is iter12's primary
    # deliverable — fills the missing "what does llama spend µs on per encoder
    # bucket?" half of iter11's per-layer comparison.
    if hf2q and llama and (hf2q.get("encoder_gpu") or llama.get("encoder_gpu")):
        lines.append("")
        lines.append("=" * 110)
        lines.append("iter12 — Per-encoder GPU-time attribution (xctrace MST CLI-only)")
        lines.append("=" * 110)
        lines.append("Methodology: encoders bucketed by family (compute / blit / render / accel),")
        lines.append("  filtered to target binary's process.  GPU time = sum of paired dispatch")
        lines.append("  durations joined to the encoder by THREADING the join through the")
        lines.append("  metal-gpu-submission-to-command-buffer-id table (sub_id -> encoder_id),")
        lines.append("  because sub_id and encoder_id live in different id namespaces (sub_id is")
        lines.append("  a 32-bit GPU submission counter; encoder_id is a 40-bit MTLObject id).")
        lines.append("  Host time = encoder lifetime from metal-application-encoders-list")
        lines.append("  (encoding wall-clock, not GPU wall-clock — kept for reference).")
        lines.append("")
        lines.append("Granularity caveat: both llama.cpp and mlx-native emit only generic encoder")
        lines.append("  labels ('Compute Command N' / 'Blit Command N') — neither pushes debug")
        lines.append("  groups nor sets MTLObject labels.  Per-encoder attribution is therefore")
        lines.append("  COARSER than per-kernel; on a typical decode token both binaries emit a")
        lines.append("  single Compute encoder containing many dispatches, so per-encoder GPU sum")
        lines.append("  is roughly per-CB GPU sum.")
        lines.append("")
        header = (f"{'family':<10s}  "
                  f"{'hf2q enc/tok':>13s}  {'hf2q gpu_µs/tok':>15s}  "
                  f"{'llama enc/tok':>14s}  {'llama gpu_µs/tok':>16s}  "
                  f"{'Δgpu_µs/tok':>12s}  {'Δ%':>8s}")
        lines.append(header)
        lines.append("-" * len(header))
        all_families = sorted(
            set((hf2q.get("encoder_gpu") or {}).keys())
            | set((llama.get("encoder_gpu") or {}).keys())
        )
        # Sort by Δgpu_µs/tok desc so the largest gap is on top
        rows_sorted = []
        for fam in all_families:
            hb = (hf2q.get("encoder_gpu") or {}).get(fam) or {}
            lb = (llama.get("encoder_gpu") or {}).get(fam) or {}
            h_gpu = hb.get("median_gpu_us_per_token", 0.0)
            l_gpu = lb.get("median_gpu_us_per_token", 0.0)
            d_us = h_gpu - l_gpu
            d_pct = (d_us / l_gpu * 100) if l_gpu > 0 else 0.0
            rows_sorted.append((fam, hb, lb, d_us, d_pct))
        rows_sorted.sort(key=lambda r: -r[3])
        for fam, hb, lb, d_us, d_pct in rows_sorted:
            lines.append(
                f"{fam:<10s}  "
                f"{hb.get('median_encoders_per_token', 0):>13.2f}  "
                f"{hb.get('median_gpu_us_per_token', 0):>15.1f}  "
                f"{lb.get('median_encoders_per_token', 0):>14.2f}  "
                f"{lb.get('median_gpu_us_per_token', 0):>16.1f}  "
                f"{d_us:>+12.1f}  "
                f"{d_pct:>+7.1f}%"
            )
        # Totals across families
        h_total = sum(b.get("median_gpu_us_per_token", 0)
                      for b in (hf2q.get("encoder_gpu") or {}).values())
        l_total = sum(b.get("median_gpu_us_per_token", 0)
                      for b in (llama.get("encoder_gpu") or {}).values())
        lines.append("-" * len(header))
        lines.append(
            f"{'TOTAL':<10s}  "
            f"{'-':>13s}  "
            f"{h_total:>15.1f}  "
            f"{'-':>14s}  "
            f"{l_total:>16.1f}  "
            f"{(h_total - l_total):>+12.1f}  "
            f"{((h_total - l_total) / l_total * 100 if l_total else 0):>+7.1f}%"
        )
        lines.append("")
        lines.append("Per-trial encoder gpu µs/tok (compute family only) for stat visibility:")
        for fam in ["compute", "blit"]:
            for trace_label, side in [("hf2q ", hf2q), ("llama", llama)]:
                if not side:
                    continue
                rows_pt = side.get("encoder_gpu_per_trial") or []
                vals = []
                for s, n_tok in zip(rows_pt, side.get("n_tokens_per_trial") or []):
                    if not s:
                        continue
                    b = s.get(fam) or {}
                    vals.append(b.get("gpu_sum_ns", 0) / 1000.0 / max(n_tok, 1))
                if vals:
                    lines.append(f"  {trace_label} {fam:<7s}: "
                                 f"{', '.join(f'{x:.1f}' for x in vals)}")
        lines.append("")

    # iter16: per-CB-label semantic-phase attribution side-by-side.
    if hf2q and (hf2q.get("cb_label_gpu") or (llama or {}).get("cb_label_gpu")):
        lines.append("")
        lines.append("=" * 110)
        lines.append("iter16 — Per-CB semantic-phase attribution (xctrace MST CLI-only)")
        lines.append("=" * 110)
        lines.append("Methodology: hf2q's `mlx_native::CommandEncoder::commit_*labeled(label)`")
        lines.append("  now propagates the semantic phase string to MTLCommandBuffer.label and")
        lines.append("  the active MTLComputeCommandEncoder.label, populating xctrace's")
        lines.append("  `metal-application-encoders-list.cmdbuffer-label` column. Phases")
        lines.append("  are joined to per-dispatch GPU duration via")
        lines.append("  metal-gpu-submission-to-command-buffer-id (sub_id -> encoder_id) ->")
        lines.append("  metal-application-encoders-list (encoder_id -> cmdbuffer_label).")
        lines.append("")
        lines.append("Comparable-axis caveat: llama.cpp does NOT setLabel on its CBs (verified")
        lines.append("  iter15 Phase 0; iter16 §A.2 Phase 0 probe re-confirmed). llama rows here")
        lines.append("  bucket under generic 'Command Buffer N' phase names — so this table")
        lines.append("  shows hf2q's INTERNAL distribution across phases (the actionable signal")
        lines.append("  for ranking iter17 hypotheses) and llama's TOTAL as a single anchor.")
        lines.append("")
        # hf2q labelled-encoder coverage (sanity probe).
        try:
            sample_per_trial = hf2q.get("cb_label_gpu_per_trial") or []
            if sample_per_trial:
                meta = sample_per_trial[0].get("_meta", {})
                lines.append(
                    f"hf2q label coverage (trial 0): {meta.get('labelled_encoders', 0)}"
                    f" / {meta.get('total_encoders', 0)} encoders carry a semantic label"
                )
                lines.append("")
        except Exception:
            pass
        header = (f"{'phase':<48s}  "
                  f"{'hf2q cbs/tok':>13s}  {'hf2q disp/tok':>14s}  {'hf2q gpu_µs/tok':>15s}  "
                  f"{'llama cbs/tok':>14s}  {'llama gpu_µs/tok':>16s}  "
                  f"{'Δgpu_µs/tok':>12s}")
        lines.append(header)
        lines.append("-" * len(header))
        all_phases = sorted(
            set((hf2q.get("cb_label_gpu") or {}).keys())
            | set((llama or {}).get("cb_label_gpu", {}).keys() if llama else [])
        )
        rows_sorted = []
        for phase in all_phases:
            hb = (hf2q.get("cb_label_gpu") or {}).get(phase) or {}
            lb = ((llama or {}).get("cb_label_gpu") or {}).get(phase) or {}
            h_gpu = hb.get("median_gpu_us_per_token", 0.0)
            l_gpu = lb.get("median_gpu_us_per_token", 0.0)
            d_us = h_gpu - l_gpu
            rows_sorted.append((phase, hb, lb, d_us))
        rows_sorted.sort(key=lambda r: -r[1].get("median_gpu_us_per_token", 0.0))
        for phase, hb, lb, d_us in rows_sorted:
            lines.append(
                f"{phase[:48]:<48s}  "
                f"{hb.get('median_cbs_per_token', 0):>13.2f}  "
                f"{hb.get('median_dispatches_per_token', 0):>14.2f}  "
                f"{hb.get('median_gpu_us_per_token', 0):>15.1f}  "
                f"{lb.get('median_cbs_per_token', 0):>14.2f}  "
                f"{lb.get('median_gpu_us_per_token', 0):>16.1f}  "
                f"{d_us:>+12.1f}"
            )
        h_total = sum(b.get("median_gpu_us_per_token", 0)
                      for b in (hf2q.get("cb_label_gpu") or {}).values())
        l_total = sum(b.get("median_gpu_us_per_token", 0)
                      for b in ((llama or {}).get("cb_label_gpu") or {}).values())
        lines.append("-" * len(header))
        lines.append(
            f"{'TOTAL':<48s}  "
            f"{'-':>13s}  "
            f"{'-':>14s}  "
            f"{h_total:>15.1f}  "
            f"{'-':>14s}  "
            f"{l_total:>16.1f}  "
            f"{(h_total - l_total):>+12.1f}"
        )
        lines.append("")
        # Top-3 hf2q phases by GPU µs/tok — iter17 candidate ranking.
        labelled_rows = [
            r for r in rows_sorted
            if r[0] and not r[0].startswith("Command Buffer")
            and not r[0].startswith("Compute Command")
            and r[0] != "(unknown)"
        ]
        if labelled_rows:
            lines.append("iter17 candidate ranking — top-3 hf2q phases by gpu_µs/token:")
            for phase, hb, _lb, _d in labelled_rows[:3]:
                cbs = hb.get("median_cbs_per_token", 0.0)
                disp = hb.get("median_dispatches_per_token", 0.0)
                gpu = hb.get("median_gpu_us_per_token", 0.0)
                mean_per_cb = hb.get("mean_us_per_cb", 0.0)
                lines.append(
                    f"  {phase}: {cbs:.2f} cbs/tok × ~{mean_per_cb:.1f} µs/cb"
                    f" = {gpu:.1f} gpu_µs/tok ({disp:.1f} dispatches/tok)"
                )
            lines.append("")

    # iter11: surface the kernel registry per binary so reviewers can confirm
    # iter9b labels propagated end-to-end through xctrace.
    lines.append("")
    lines.append("=" * 110)
    lines.append("iter11 — Kernel registry (metal-shader-profiler-shader-list, post-iter9b labels)")
    lines.append("=" * 110)
    if hf2q and hf2q.get("shader_registry"):
        lines.append("")
        lines.append("hf2q registry (PSO labels by family, deduped):")
        for fam in sorted(hf2q["shader_registry"].keys()):
            names = hf2q["shader_registry"][fam]
            lines.append(f"  {fam:>20s}  ({len(names):>2d}): {', '.join(names[:5])}"
                         f"{'' if len(names) > 5 else ''}")
        lines.append(f"  Shader Timeline samples (metal-shader-profiler-intervals): "
                     f"{hf2q.get('shader_timeline_rows', 0)} rows "
                     f"({'EMPTY (CLI cannot toggle)' if hf2q.get('shader_timeline_rows', 0) == 0 else 'populated'})")
    if llama and llama.get("shader_registry"):
        lines.append("")
        lines.append("llama-cli registry (PSO labels by family, deduped):")
        for fam in sorted(llama["shader_registry"].keys()):
            names = llama["shader_registry"][fam]
            lines.append(f"  {fam:>20s}  ({len(names):>2d}): {', '.join(names[:5])}"
                         f"{'' if len(names) > 5 else ''}")
        lines.append(f"  Shader Timeline samples: "
                     f"{llama.get('shader_timeline_rows', 0)} rows")
    lines.append("")
    lines.append("Verdict: kernel-NAME attribution per dispatch is BLOCKED on Shader Timeline")
    lines.append("toggle which xctrace CLI cannot enable. iter11b enabler (mlx-native")
    lines.append("pushDebugGroup) is the recommended unblock; expected to populate")
    lines.append("metal-application-event-interval with per-dispatch labeled intervals")
    lines.append("joinable to GPU duration via canonical fn=1/2 sub_id pairs.")
    lines.append("")

    # iter11: per-trial gpu_us_per_token for statistical visibility.
    if hf2q and hf2q.get("gpu_us_per_token_per_trial"):
        lines.append(f"hf2q  per-trial gpu µs/tok: "
                     f"{', '.join(f'{x:.1f}' for x in hf2q['gpu_us_per_token_per_trial'])}")
    if llama and llama.get("gpu_us_per_token_per_trial"):
        lines.append(f"llama per-trial gpu µs/tok: "
                     f"{', '.join(f'{x:.1f}' for x in llama['gpu_us_per_token_per_trial'])}")
    lines.append("")

    text = "\n".join(lines) + "\n"
    with open(out_path, "w") as f:
        f.write(text)
    sys.stdout.write(text)


def bucket_kernel_hint(name: str) -> str:
    return {
        "xs_<2us": "rms_norm / reshape / scalar",
        "sm_2_8us": "rope / soft-cap / small mat-vec",
        "md_8_32us": "Q4_0 MoE mat-vec_id (gate/up/down) — primary Q4_0 attack surface",
        "lg_32_80us": "flash_attn / pooled mul_mm_id",
        "xl_>=80us": "prefill mul_mm_id / lm_head / large blits",
    }.get(name, "unknown")


# --------------------------------------------------------------------- #
# Main                                                                  #
# --------------------------------------------------------------------- #

def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--hf2q-trace", action="append", default=[], help="hf2q .trace bundle (repeatable)")
    ap.add_argument("--llama-trace", action="append", default=[], help="llama .trace bundle (repeatable)")
    ap.add_argument("--n-tokens", type=int, default=64, help="decode tokens per trial (default 64)")
    ap.add_argument("--output", default="/tmp/adr015-iter9/aggregate-q4_0.txt")
    ap.add_argument("--toc-dump", default=None, help="if set, dump xctrace --toc to this path for one trace")
    args = ap.parse_args()

    if args.toc_dump and args.hf2q_trace:
        with open(args.toc_dump, "w") as f:
            f.write(export_toc(args.hf2q_trace[0]))
        print(f"toc dumped: {args.toc_dump}", file=sys.stderr)

    hf2q_trials = []
    for t in args.hf2q_trace:
        try:
            s = summarize_trace(t, args.n_tokens, target_process_prefix="hf2q")
            hf2q_trials.append(s)
            print(
                f"ok: hf2q {t}: {s['paired']} paired, "
                f"{s.get('shader_count', 0)} shaders, "
                f"{s.get('shader_timeline_rows', 0)} timeline samples",
                file=sys.stderr,
            )
        except Exception as e:
            print(f"WARN: hf2q {t}: {e}", file=sys.stderr)

    llama_trials = []
    for t in args.llama_trace:
        try:
            # llama-cli registers as either "llama-cli" or "llama-bench"
            s = summarize_trace(t, args.n_tokens, target_process_prefix="llama")
            llama_trials.append(s)
            print(
                f"ok: llama {t}: {s['paired']} paired, "
                f"{s.get('shader_count', 0)} shaders, "
                f"{s.get('shader_timeline_rows', 0)} timeline samples",
                file=sys.stderr,
            )
        except Exception as e:
            print(f"WARN: llama {t}: {e}", file=sys.stderr)

    hf2q_med = median_summaries(hf2q_trials)
    llama_med = median_summaries(llama_trials)

    os.makedirs(os.path.dirname(args.output), exist_ok=True)
    write_report(args.output, hf2q_med, llama_med, hf2q_trials, llama_trials)
    print(f"\nwrote: {args.output}", file=sys.stderr)


if __name__ == "__main__":
    main()