-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfull_graph_harness.py
More file actions
1831 lines (1617 loc) · 64.3 KB
/
Copy pathfull_graph_harness.py
File metadata and controls
1831 lines (1617 loc) · 64.3 KB
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
"""Helpers for executing saved full_graph_*.py artifacts.
The saved full graphs are print_readable-style Python modules. They contain a
torch.nn.Module subclass with tensor metadata in forward annotations, but no
canonical make_inputs() helper. This module reconstructs runnable inputs from
those annotations so the benchmark runner can time the whole graph directly.
"""
from __future__ import annotations
import math
import re
from dataclasses import dataclass
import json
from pathlib import Path
from typing import Any
@dataclass(frozen=True)
class FullGraphDefinition:
path: Path
graph_cls: type
input_specs: list[dict[str, Any]]
tensor_attrs: dict[str, dict[str, Any]]
forward_takes_no_inputs: bool
metadata: dict[str, Any]
_DTYPE_SHORT_NAMES = {
"f32": "float32",
"f16": "float16",
"bf16": "bfloat16",
"i64": "int64",
"i32": "int32",
"i16": "int16",
"i8": "int8",
"u8": "uint8",
"u16": "uint16",
"u32": "uint32",
"u64": "uint64",
"b8": "bool",
"f64": "float64",
"c64": "complex64",
"c128": "complex128",
"f8e4m3fn": "float8_e4m3fn",
"f8e5m2": "float8_e5m2",
}
def _torch_dtype(dtype_name: str):
import torch
return getattr(torch, dtype_name, torch.float32)
def _dtype_name(dtype: Any) -> str:
text = str(dtype)
return text.removeprefix("torch.")
def _default_generator_for_dtype(
dtype_name: str,
shape: tuple[int, ...] | list[int] = (),
) -> dict[str, Any]:
if dtype_name == "bool":
return {"kind": "randint", "low": 0, "high": 2}
if dtype_name.startswith("int") or dtype_name.startswith("uint"):
high = max([int(dim) for dim in shape], default=100)
return {"kind": "index", "low": 0, "high": max(high, 1)}
return {"kind": "randn"}
def _is_integer_or_bool_dtype_name(dtype_name: str) -> bool:
return (
dtype_name == "bool"
or dtype_name.startswith("int")
or dtype_name.startswith("uint")
)
def _default_generator_for_attr_dtype(dtype_name: str) -> dict[str, Any]:
# Annotation-only tensor constants have no payload. Zero is safer than
# random bounded indices for constants that feed indexing/scatter paths.
if _is_integer_or_bool_dtype_name(dtype_name):
return {"kind": "constant", "value": 0}
return {"kind": "randn"}
def _concrete_int(value: Any, *, default: int = 32) -> int:
try:
if hasattr(value, "node") and hasattr(value.node, "hint"):
return int(value.node.hint)
return int(value)
except Exception:
return default
def placeholder_info_from_gm(gm: Any) -> dict[str, dict]:
"""Build the placeholder_info shape/dtype map used for input generators."""
import torch
placeholder_info = {}
for node in gm.graph.nodes:
if node.op != "placeholder":
continue
val = (node.meta or {}).get("val")
if torch.is_tensor(val):
placeholder_info[node.name] = {
"shape": [_concrete_int(s) for s in val.shape],
"stride": [_concrete_int(s) for s in val.stride()]
if not val.is_contiguous()
else [],
"dtype": str(val.dtype),
"device": str(val.device),
}
elif isinstance(val, (torch.SymInt, torch.SymFloat)):
placeholder_info[node.name] = {
"shape": [],
"stride": [],
"dtype": "symint",
"device": "cpu",
"hint": _concrete_int(val),
}
return placeholder_info
def infer_index_bounds_from_gm(
gm: Any,
placeholder_info: dict[str, dict],
constants_out: dict[str, int] | None = None,
) -> dict[str, int]:
"""Infer valid index bounds for integer placeholders by inspecting consumers.
`constants_out` (optional dict, filled in place) receives placeholders
whose only safe generation is a CONSTANT value rather than a range —
e.g. maxpool offset tensors, where the window-center offset is the one
value in-bounds for every window under padding (random offsets put edge
windows out of range -> device-side assert in the consuming scatter).
"""
import torch
index_consumers = {
torch.ops.aten.scatter.src: (0, 1),
torch.ops.aten.scatter.value: (0, 1),
torch.ops.aten.scatter_add.default: (0, 1),
torch.ops.aten.gather.default: (0, 1),
torch.ops.aten.index_select.default: (0, 1),
torch.ops.aten.embedding.default: (0, None),
}
passthrough_ops = {
torch.ops.aten.clone.default,
torch.ops.aten.reshape.default,
torch.ops.aten.view.default,
torch.ops.aten.expand.default,
torch.ops.aten.slice.Tensor,
torch.ops.aten.unsqueeze.default,
torch.ops.aten.squeeze.default,
torch.ops.aten.squeeze.dim,
torch.ops.aten.select.int,
torch.ops.aten.permute.default,
torch.ops.aten.contiguous.default,
torch.ops.aten.t.default,
torch.ops.aten.transpose.int,
torch.ops.aten.where.self,
}
bounds = {}
constants = constants_out if constants_out is not None else {}
ph_nodes = {n.name: n for n in gm.graph.nodes if n.op == "placeholder"}
def _node_shape(n):
if not hasattr(n, "meta"):
return None
val = n.meta.get("val")
if isinstance(val, torch.Tensor):
return list(val.shape)
if n.op == "call_function" and n.target in {
torch.ops.aten.empty.memory_format,
torch.ops.aten.full.default,
}:
if n.args:
shape_arg = n.args[0]
if isinstance(shape_arg, (list, tuple)):
return list(shape_arg)
# Canonical (lifted) graphs replace the literal shape list with
# a _shape_param_N placeholder NODE whose meta['val'] holds the
# concrete list (capture_hook.lift_shape_params). Resolve it —
# otherwise index_put(full(_shape_param), [None,None,i,j], ..)
# loses its target shape and the index args fall through to the
# degenerate [0,1) default (the sum_sum_sum pytorch_unet class:
# arg3/arg6 should be [0,320), arg4/arg5 [0,479), not [0,1)).
if hasattr(shape_arg, "meta"):
mv = shape_arg.meta.get("val")
if isinstance(mv, (list, tuple)):
return list(mv)
return None
for name, node in ph_nodes.items():
info = placeholder_info.get(name, {})
dtype = info.get("dtype", "")
is_float = "float" in dtype or "bfloat" in dtype
if "int" not in dtype and not is_float:
continue
if "int8" in dtype:
# Maxpool OFFSET tensors (offset-within-window). Random offsets
# are NOT uniformly valid: offsets_to_indices converts them to
# flat indices relative to each window's position, and under
# padding the edge windows go negative / past the dim for most
# values (offset 0 at a padded edge -> index -113) — the
# consuming scatter_add then device-side-asserts and poisons
# the CUDA context (the wave-1 torchbench train assert class).
# The WINDOW-CENTER offset is in-bounds for every window
# (measured: 3x3 pad1 on 112x112 -> [0, 12430] vs dim 12544),
# so emit it via constants_out as a constant-value generator.
for user in node.users:
if user.op != "call_function":
continue
target_name = str(user.target)
if "max_pool_offsets_to_indices" not in target_name:
continue
kernel_size = user.args[1] if len(user.args) >= 2 else None
# In canonical (lifted) graphs the kernel size is a
# _shape_param placeholder NODE whose meta["val"] holds the
# list — resolve it (vgg16: literal-only check fell through
# to the 3x3 default const 4 on a 2x2 kernel -> offset 4
# invalid -> scatter assert).
if (kernel_size is not None
and not isinstance(kernel_size, (list, tuple))
and hasattr(kernel_size, "meta")):
mv = kernel_size.meta.get("val")
if isinstance(mv, (list, tuple)):
kernel_size = mv
if isinstance(kernel_size, (list, tuple)) and kernel_size:
if len(kernel_size) >= 2:
kh, kw = int(kernel_size[0]), int(kernel_size[1])
center = (kh // 2) * kw + (kw // 2)
else:
center = int(kernel_size[0]) // 2
constants[name] = center
break
if name not in constants:
# Offset 0 (first element of the window) is valid for any
# kernel WITHOUT padding; under padding only interior
# offsets are — but an unknown kernel size gives no better
# choice, and 0 is right far more often than a 3x3 center.
constants[name] = 0
continue
def _find_bound(start_node, max_hops=8):
# Collect EVERY bound the value reaches and return the MIN: a
# value consumed by several index ops must satisfy all of them
# (Electra: ids flow through gather into the 2-row token-type
# embedding — first-found returned the 512 gather bound and the
# 2-row table asserted OOB, poisoning the CUDA context).
#
# The walk follows VALUE flow through int arithmetic too, and
# INVERTS each transform when a consumption bound is found
# (Longformer: position ids = (ids * mask + 1) indexes a
# 4098-row table — the leaf bound is isqrt(4097), not 4098):
# add/sub const c -> bound - |c|
# mul const c>0 -> bound // c
# mul TENSOR -> isqrt(bound) (both operands generated
# by us; each < sqrt(B) keeps product < B)
# add TENSOR -> bound // 2 (same reasoning)
# convert/clone/.. -> unchanged
import math as _math
found: list[int] = []
def _invert(bound: int, chain) -> int:
b = bound
for kind, arg in reversed(chain):
if kind == "addc":
b = b - abs(int(arg))
elif kind == "mulc":
c = abs(int(arg))
b = b // c if c > 1 else b
elif kind == "mult":
b = int(_math.isqrt(max(b - 1, 1)))
elif kind == "addt":
b = b // 2
b = max(b, 1)
return b
_INT_ARITH = {
torch.ops.aten.add.Tensor: "add",
torch.ops.aten.sub.Tensor: "add", # same inversion class
torch.ops.aten.mul.Tensor: "mul",
}
_VALUE_PRESERVING = {
torch.ops.prims.convert_element_type.default,
}
frontier = [(start_node, ())]
for _hop in range(max_hops):
next_frontier = []
for n, chain in frontier:
for user in n.users:
if user.op != "call_function":
continue
target = user.target
if target == torch.ops.aten.embedding.default:
# only when n is the INDICES arg (args[1])
if len(user.args) > 1 and user.args[1] is n:
weight_arg = user.args[0] if user.args else None
if weight_arg and hasattr(weight_arg, "meta"):
val = weight_arg.meta.get("val")
if isinstance(val, torch.Tensor) and len(val.shape) > 0:
found.append(_invert(int(val.shape[0]), chain))
continue
if (target in (torch.ops.aten.index.Tensor,
torch.ops.aten.index_put.default,
torch.ops.aten.index_put_.default)
and len(user.args) >= 2):
# indices list position maps to DIM, INCLUDING
# None slots (index_put([None, None, i, j]):
# i indexes dim 2, j dim 3 — Yitu: bounding j
# by shape[0]=32 against dim3 size 1 asserted).
# index_put_ (in-place) shares the schema; both
# take (self, indices_list, values, ...).
target_shape = _node_shape(user.args[0])
indices = user.args[1]
if target_shape and isinstance(indices, (list, tuple)):
for dim, index_node in enumerate(indices):
if index_node is n and dim < len(target_shape):
found.append(_invert(int(target_shape[dim]), chain))
if target == torch.ops.aten.gather.default:
if user.args and user.args[0] is n:
# n is gather's DATA source: values flow on.
next_frontier.append((user, chain))
continue
if target in index_consumers:
target_arg_idx, dim_arg_idx = index_consumers[target]
if len(user.args) > target_arg_idx:
target_node = user.args[target_arg_idx]
target_shape = _node_shape(target_node)
if target_shape and target_node is not n:
if dim_arg_idx is not None and len(user.args) > dim_arg_idx:
dim = user.args[dim_arg_idx]
if isinstance(dim, int) and dim < len(target_shape):
found.append(_invert(int(target_shape[dim]), chain))
else:
found.append(_invert(int(target_shape[0]), chain))
if target in passthrough_ops or target in _VALUE_PRESERVING:
next_frontier.append((user, chain))
elif target in _INT_ARITH:
kind = _INT_ARITH[target]
other = None
for a in user.args[:2]:
if a is not n:
other = a
if isinstance(other, (int, float)):
next_frontier.append(
(user, chain + ((kind + "c", other),)))
else:
next_frontier.append(
(user, chain + ((kind + "t", None),)))
frontier = next_frontier
if not frontier:
break
if found:
return min(found)
return None
bound = _find_bound(node)
if bound is not None:
if is_float:
# FLOAT placeholder whose VALUES flow (via convert chains)
# into index consumption — OPT: position ids derive from a
# float attention mask, (mask - 1).to(int64) + 2 indexes a
# 2050-row table. randn would go negative/OOB; generate
# bounded non-negative values instead.
info.setdefault("gen", {"kind": "index", "low": 0,
"high": bound})
bounds[name] = bound
return bounds
def infer_permutation_indices_from_gm(
gm: Any,
placeholder_info: dict[str, dict],
) -> dict[str, int]:
"""Find integer placeholders that must be valid permutations."""
import torch
permutation_sizes = {}
ph_nodes = {n.name: n for n in gm.graph.nodes if n.op == "placeholder"}
def _shape_from_alloc(n):
if n.op != "call_function":
return None
if n.target not in {
torch.ops.aten.empty.memory_format,
torch.ops.aten.full.default,
}:
return None
if not n.args:
return None
shape_arg = n.args[0]
# Canonical graphs lift alloc shapes to _shape_param placeholder
# NODES — resolve via meta['val'] (gpt-oss MoE: empty(_shape_param)
# blinded the permutation detection; the scatter ordering indices
# then generated as random Index -> duplicate positions -> assert).
if not isinstance(shape_arg, (list, tuple)) and hasattr(shape_arg, "meta"):
mv = shape_arg.meta.get("val")
if isinstance(mv, (list, tuple)):
shape_arg = mv
if not isinstance(shape_arg, (list, tuple)):
return None
return list(shape_arg)
iota_passthrough_ops = {
torch.ops.aten.reshape.default,
torch.ops.aten.view.default,
torch.ops.aten.expand.default,
torch.ops.aten.unsqueeze.default,
torch.ops.aten.squeeze.default,
torch.ops.aten.squeeze.dim,
}
def _iota_size(n, max_hops=4):
if n.op != "call_function":
return None
if n.target != torch.ops.prims.iota.default:
if max_hops > 0 and n.target in iota_passthrough_ops and n.args:
return _iota_size(n.args[0], max_hops - 1)
return None
if not n.args:
return None
length = n.args[0]
# lifted/symbolic length: resolve via meta['val'] or SymInt hint
if not isinstance(length, int) and hasattr(length, "meta"):
mv = length.meta.get("val")
if isinstance(mv, int):
length = mv
elif hasattr(mv, "node") and hasattr(mv.node, "hint"):
length = int(mv.node.hint)
if isinstance(length, int):
return length
return None
for name, node in ph_nodes.items():
info = placeholder_info.get(name, {})
dtype = info.get("dtype", "")
if "int" not in dtype:
continue
for user in node.users:
if user.op != "call_function" or user.target != torch.ops.aten.index_put.default:
continue
if len(user.args) < 3:
continue
indices = user.args[1]
if not isinstance(indices, (list, tuple)) or node not in indices:
continue
target_shape = _shape_from_alloc(user.args[0])
iota_size = _iota_size(user.args[2])
if target_shape and iota_size and target_shape[0] == iota_size:
permutation_sizes[name] = iota_size
for user in node.users:
if user.op != "call_function" or user.target != torch.ops.aten.scatter.src:
continue
if len(user.args) < 4 or user.args[2] is not node:
continue
target_shape = _shape_from_alloc(user.args[0])
iota_size = _iota_size(user.args[3])
dim = user.args[1]
if target_shape and iota_size and isinstance(dim, int):
if dim < 0:
dim += len(target_shape)
if 0 <= dim < len(target_shape) and target_shape[dim] == iota_size:
permutation_sizes[name] = iota_size
return permutation_sizes
def _tensor_spec_from_value(
name: str,
value: Any,
*,
gen_override: dict[str, Any] | None = None,
include_exact: bool = False,
) -> dict[str, Any]:
dtype_name = _dtype_name(value.dtype)
shape = [_concrete_int(dim) for dim in value.shape]
generator = gen_override or _default_generator_for_dtype(dtype_name, shape)
spec = {
"kind": "tensor",
"name": name,
"shape": shape,
"dtype": dtype_name,
"stride": [_concrete_int(dim) for dim in value.stride()],
"device": "cuda" if str(value.device).startswith("cuda") else str(value.device),
"storage_offset": _concrete_int(value.storage_offset(), default=0),
"generator": generator,
}
if generator.get("kind") in {"index", "permutation"}:
spec["gen"] = generator
spec["constraint_source"] = "graph_inference" if gen_override else "dtype_shape_default"
exact = _exact_tensor_payload(value) if include_exact else None
if exact is not None:
spec.update(exact)
else:
spec["exact"] = False
if include_exact and _is_integer_or_bool_dtype_name(dtype_name):
spec["requires_exact"] = True
return spec
def _is_fake_or_meta_tensor(value: Any) -> bool:
if getattr(value, "is_meta", False):
return True
try:
from torch._subclasses.fake_tensor import FakeTensor
if isinstance(value, FakeTensor):
return True
except Exception:
pass
return "fake_tensor" in type(value).__module__
def _exact_tensor_payload(value: Any, *, max_numel: int = 4096) -> dict[str, Any] | None:
if _is_fake_or_meta_tensor(value):
return None
dtype_name = _dtype_name(value.dtype)
if value.numel() > max_numel:
return None
if not (
dtype_name == "bool"
or dtype_name.startswith("int")
or dtype_name.startswith("uint")
or value.numel() <= 16
):
return None
try:
detached = value.detach().cpu().contiguous()
except Exception:
return None
return {
"exact": True,
"data": detached.reshape(-1).tolist(),
}
def _scalar_spec_from_value(name: str, value: Any) -> dict[str, Any]:
import torch
if isinstance(value, (torch.SymInt, torch.SymFloat)):
return {"kind": "symint", "name": name, "value": _concrete_int(value)}
if isinstance(value, (int, float, bool)):
return {"kind": "scalar", "name": name, "value": value}
return {"kind": "scalar", "name": name, "value": 1}
def graph_constraints_from_gm(
gm: Any,
*,
index_bounds: dict[str, int] | None = None,
permutation_indices: dict[str, int] | None = None,
observed_stats: dict[str, dict] | None = None,
) -> dict[str, Any]:
"""Extract replay constraints from an FX GraphModule.
The exporter writes this next to full_graph_*.py so newly added model
graphs do not depend solely on parsing print_readable annotations.
Bound hierarchy (settled 2026-06-10):
1. graph_inference: known consumer patterns (embedding, gather, scatter)
2. observed: fallback from real execution stats (high = observed.max + 1)
3. default_unobserved: ONLY when observation was impossible (should not
occur for new captures)
"""
import torch
index_bounds = index_bounds or {}
permutation_indices = permutation_indices or {}
observed_stats = observed_stats or {}
inputs = []
outputs = []
tensor_attrs = {}
for node in gm.graph.nodes:
value = (node.meta or {}).get("val")
if node.op == "placeholder":
if torch.is_tensor(value):
gen_override = None
constraint_source = None
if node.name in permutation_indices:
gen_override = {
"kind": "permutation",
"size": int(permutation_indices[node.name]),
}
constraint_source = "graph_inference"
elif node.name in index_bounds:
gen_override = {
"kind": "index",
"low": 0,
"high": int(index_bounds[node.name]),
}
constraint_source = "graph_inference"
elif node.name in observed_stats:
# Observed-value fallback: use observed max + 1 as bound
obs = observed_stats[node.name]
dtype_name = _dtype_name(value.dtype)
if _is_integer_or_bool_dtype_name(dtype_name):
gen_override = {
"kind": "index",
"low": 0,
"high": int(obs["max"]) + 1,
}
constraint_source = "observed"
else:
# No inference bound and no observation
dtype_name = _dtype_name(value.dtype)
if _is_integer_or_bool_dtype_name(dtype_name):
constraint_source = "default_unobserved"
spec = _tensor_spec_from_value(
node.name,
value,
gen_override=gen_override,
)
# Override constraint_source with the hierarchy decision
if constraint_source is not None:
spec["constraint_source"] = constraint_source
# Attach observed stats alongside (regardless of which source won)
if node.name in observed_stats:
spec["observed"] = observed_stats[node.name]
# Note potential permutation: n_unique == numel on 1-D int tensor
obs = observed_stats[node.name]
shape = spec.get("shape", [])
if (
len(shape) == 1
and shape[0] > 0
and obs.get("n_unique") == shape[0]
and _is_integer_or_bool_dtype_name(spec.get("dtype", ""))
and spec.get("dtype", "") != "bool"
):
spec["maybe_permutation"] = True
inputs.append(spec)
else:
inputs.append(_scalar_spec_from_value(node.name, value))
elif node.op == "get_attr":
attr_value = _fetch_attr(gm, node.target)
if torch.is_tensor(attr_value):
tensor_attrs[str(node.target)] = _tensor_spec_from_value(
str(node.target),
attr_value,
include_exact=True,
)
elif node.op == "output":
for idx, leaf in enumerate(_iter_tree_leaves(node.args)):
if isinstance(leaf, torch.fx.Node):
leaf_value = (leaf.meta or {}).get("val")
if torch.is_tensor(leaf_value):
outputs.append(_tensor_spec_from_value(f"output_{idx}", leaf_value))
elif leaf_value is not None:
outputs.append(_scalar_spec_from_value(f"output_{idx}", leaf_value))
payload = {
"schema_version": 1,
"inputs": inputs,
"outputs": outputs,
"tensor_attrs": tensor_attrs,
}
storage_groups = _placeholder_storage_groups(gm)
if storage_groups:
# Inputs that are VIEWS OF ONE STORAGE (packed-qkv saved views in
# backward graphs etc). Regenerating them as independent storages
# changes footprint/locality and is wrong under mutation — replay
# must allocate one buffer per group and as_strided each member.
# Detectable ONLY at capture (live fake vals share a storage; any
# later retrace re-fabricates inputs and the identity is gone).
payload["storage_groups"] = storage_groups
return payload
def _placeholder_storage_groups(gm: Any) -> list[list[str]]:
"""Group placeholder names whose meta vals share one untyped storage."""
import torch
groups: dict[int, list[str]] = {}
for node in gm.graph.nodes:
if node.op != "placeholder":
continue
val = (node.meta or {}).get("val")
if not torch.is_tensor(val):
continue
try:
key = id(val.untyped_storage())
except Exception:
continue
groups.setdefault(key, []).append(node.name)
return [names for names in groups.values() if len(names) > 1]
def _fetch_attr(module: Any, target: Any) -> Any:
value = module
for atom in str(target).split("."):
value = getattr(value, atom)
return value
def _iter_tree_leaves(value: Any):
if isinstance(value, dict):
for item in value.values():
yield from _iter_tree_leaves(item)
elif isinstance(value, (list, tuple)):
for item in value:
yield from _iter_tree_leaves(item)
else:
yield value
def write_full_graph_metadata(
graph_path: str | Path,
gm: Any,
*,
extra: dict[str, Any] | None = None,
index_bounds: dict[str, int] | None = None,
permutation_indices: dict[str, int] | None = None,
observed_stats: dict[str, dict] | None = None,
) -> Path:
graph_path = Path(graph_path)
payload = graph_constraints_from_gm(
gm,
index_bounds=index_bounds,
permutation_indices=permutation_indices,
observed_stats=observed_stats,
)
payload["graph"] = graph_path.name
if extra:
payload.update(extra)
# Serialize inputs/outputs/tensor_attrs in the compact shared encoding
# (input_codec) — schema_version 2. The verbose dict-per-tensor form
# remains the in-memory representation; loaders inflate on read.
from input_codec import compact_from_spec
payload["schema_version"] = 2
for key in ("inputs", "outputs"):
if payload.get(key):
payload[key] = [compact_from_spec(s, include_name=True)
for s in payload[key]]
if payload.get("tensor_attrs"):
payload["tensor_attrs"] = {
name: compact_from_spec(s)
for name, s in payload["tensor_attrs"].items()
}
meta_path = graph_path.with_suffix(".meta.json")
meta_path.write_text(_dumps_compact_entries(payload) + "\n")
return meta_path
class _OneLine:
"""Marker: serialize this value on a single line inside indented JSON."""
def __init__(self, value):
self.value = value
def dumps_with_onelines(obj) -> str:
"""json.dumps(indent=2), but any _OneLine-wrapped value is emitted on a
single line (a compact input entry exploded across 12 indented lines
would re-create the verbosity the compact encoding exists to remove)."""
placeholders: list[str] = []
class _Enc(json.JSONEncoder):
def default(self, o):
if isinstance(o, _OneLine):
placeholders.append(
json.dumps(o.value, separators=(",", ":")))
return f"@@ONELINE{len(placeholders) - 1}@@"
return super().default(o)
text = json.dumps(obj, indent=2, cls=_Enc)
for i, body in enumerate(placeholders):
text = text.replace(f'"@@ONELINE{i}@@"', body)
return text
def _dumps_compact_entries(payload: dict) -> str:
"""Sidecar serializer: inputs/outputs/tensor_attrs entries one-lined."""
marked = dict(payload)
for key in ("inputs", "outputs"):
if marked.get(key):
marked[key] = [_OneLine(e) for e in marked[key]]
if marked.get("tensor_attrs"):
marked["tensor_attrs"] = {
k: _OneLine(v) for k, v in marked["tensor_attrs"].items()
}
return dumps_with_onelines(marked)
def _split_signature_args(sig: str) -> list[str]:
args = []
start = 0
in_quote = False
quote = ""
for i, ch in enumerate(sig):
if ch in {"'", '"'}:
if in_quote and ch == quote:
in_quote = False
quote = ""
elif not in_quote:
in_quote = True
quote = ch
elif ch == "," and not in_quote:
part = sig[start:i].strip()
if part:
args.append(part)
start = i + 1
part = sig[start:].strip()
if part:
args.append(part)
return args
def _parse_intish(value: str, *, default: int = 32) -> int:
value = value.strip()
try:
return int(value)
except ValueError:
pass
sym_match = re.fullmatch(r"Sym\(([^)]*)\)", value)
if sym_match:
return _parse_intish(sym_match.group(1), default=default)
if re.fullmatch(r"[A-Za-z_]\w*", value):
return default
match = re.search(r"-?\d+", value)
if match:
return int(match.group(0))
return default
def _symbolic_dims(shape_str: str) -> list[dict[str, Any]]:
symbols = []
for idx, dim in enumerate(shape_str.split(",")):
dim = dim.strip()
if not dim:
continue
try:
int(dim)
except ValueError:
symbols.append({"dim": idx, "symbol": dim, "default": _parse_intish(dim)})
return symbols
def _symbolic_stride_dims(stride_str: str | None) -> list[dict[str, Any]]:
if stride_str is None:
return []
symbolic = []
for idx, dim in enumerate(stride_str.split(",")):
dim = dim.strip()
if not dim:
continue
try:
int(dim)
except ValueError:
symbolic.append({"dim": idx, "expr": dim})
return symbolic
def _parse_shape(shape_str: str) -> tuple[int, ...]:
dims = []
for dim in shape_str.split(","):
dim = dim.strip()
if dim:
dims.append(_parse_intish(dim))
return tuple(dims)
def _parse_stride(stride_str: str | None) -> tuple[int, ...] | None:
if stride_str is None:
return None
dims = []
for dim in stride_str.split(","):
dim = dim.strip()
if dim:
dims.append(_parse_intish(dim))
return tuple(dims)
def _parse_device(device_str: str | None) -> str | None:
if not device_str:
return None
device_str = device_str.strip()
if not device_str:
return None
if device_str.startswith("cuda"):
return "cuda"
if device_str.startswith("cpu"):
return "cpu"
return None
def _forward_signature(content: str) -> str | None:
match = re.search(r"def forward\(self,?\s*(.*?)\):", content, re.DOTALL)
return match.group(1) if match else None
def forward_takes_no_inputs(content: str) -> bool:
sig = _forward_signature(content)
return sig is not None and not sig.strip()
def parse_full_graph_inputs(content: str) -> list[dict[str, Any]]:
"""Parse forward annotations into input specs.
Examples handled:
x: "f32[2, 3][3, 1]cuda:0"
s0: "Sym(s0)"
unannotated scalar parameters
"""
sig = _forward_signature(content)
if sig is None or not sig.strip():
return []
specs = []
for arg in _split_signature_args(sig):
name_match = re.match(r"(\w+)", arg)
name = name_match.group(1) if name_match else f"arg{len(specs)}"
annotation_match = re.match(r'\w+\s*:\s*"([^"]*)"', arg)
if annotation_match is None:
specs.append({"kind": "scalar", "name": name, "value": 1})
continue
annotation = annotation_match.group(1)
if annotation.startswith("Sym("):
specs.append({
"kind": "symint",
"name": name,
"value": _parse_intish(annotation),
"symbolic_expr": annotation.removeprefix("Sym(").removesuffix(")"),
})
continue
tensor_match = re.match(
r"(\w+)\[([^\]]*)\](?:\[([^\]]*)\])?(.*)",
annotation,
)
if tensor_match is None:
specs.append({"kind": "scalar", "name": name, "value": 1})
continue
dtype_token, shape_str, stride_str, device_str = tensor_match.groups()
dtype_name = _DTYPE_SHORT_NAMES.get(dtype_token, "float32")
shape = _parse_shape(shape_str)
generator = _default_generator_for_dtype(dtype_name, shape)
spec = {
"kind": "tensor",
"name": name,
"shape": shape,
"dtype": dtype_name,
"stride": _parse_stride(stride_str),
"device": _parse_device(device_str),
# print_readable annotations don't carry storage_offset: None =
# unknown (validator skips), never a false claim of 0 — packed
# qkv views (offset 192/384/...) are real and sidecar-recorded.
"storage_offset": None,
"generator": generator,
}
if generator.get("kind") == "index":
spec["gen"] = generator
spec["constraint_source"] = "annotation_default"
symbolic_dims = _symbolic_dims(shape_str)
if symbolic_dims:
spec["symbolic_dims"] = symbolic_dims
symbolic_stride_dims = _symbolic_stride_dims(stride_str)
if symbolic_stride_dims:
spec["symbolic_stride_dims"] = symbolic_stride_dims
specs.append({
**spec,
})
return specs
def parse_full_graph_tensor_attrs(content: str) -> dict[str, dict[str, Any]]:
"""Find saved self._frozen_param* and self._tensor_constant* references."""
attrs: dict[str, dict[str, Any]] = {}
pattern = re.compile(
r'\w+:\s*"(\w+)\[([^\]]*)\](?:\[([^\]]*)\])?([^"]*)"\s*=\s*'
r"self\.(_(?:frozen_param|tensor_constant)\w*)"
)
for line in content.splitlines():
match = pattern.search(line)
if not match:
continue
dtype_token, shape_str, stride_str, device_str, attr_name = match.groups()
dtype_name = _DTYPE_SHORT_NAMES.get(dtype_token, "float32")
shape = _parse_shape(shape_str)
generator = _default_generator_for_attr_dtype(dtype_name)
attrs[attr_name] = {