markat-compiler 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. markat/__init__.py +123 -0
  2. markat/backends/__init__.py +8 -0
  3. markat/backends/profiles.py +350 -0
  4. markat/benchmark/__init__.py +21 -0
  5. markat/benchmark/runner.py +266 -0
  6. markat/calibration/__init__.py +8 -0
  7. markat/calibration/profiler.py +317 -0
  8. markat/cli.py +524 -0
  9. markat/config.py +194 -0
  10. markat/cost_model.py +461 -0
  11. markat/diagnostics/__init__.py +10 -0
  12. markat/diagnostics/bisect.py +242 -0
  13. markat/diagnostics/provenance.py +312 -0
  14. markat/egraph/__init__.py +17 -0
  15. markat/egraph/core.py +301 -0
  16. markat/egraph/pass_runner.py +788 -0
  17. markat/egraph/rules.py +634 -0
  18. markat/exporter/__init__.py +18 -0
  19. markat/exporter/dtype_gating.py +106 -0
  20. markat/exporter/onnx_export.py +992 -0
  21. markat/frontend/__init__.py +18 -0
  22. markat/frontend/ingest.py +325 -0
  23. markat/frontend/metadata.py +802 -0
  24. markat/frontend/safetensors_store.py +473 -0
  25. markat/ir/__init__.py +26 -0
  26. markat/ir/canonicalize.py +976 -0
  27. markat/ir/ops_registry.py +541 -0
  28. markat/ir/regions.py +475 -0
  29. markat/ir/weight_store.py +136 -0
  30. markat/passes/__init__.py +16 -0
  31. markat/passes/folding.py +735 -0
  32. markat/passes/fusion.py +219 -0
  33. markat/passes/identities.py +319 -0
  34. markat/quantization/__init__.py +36 -0
  35. markat/quantization/ops.py +931 -0
  36. markat/quantization/planner.py +433 -0
  37. markat/quantization/smoothing.py +292 -0
  38. markat/report.py +159 -0
  39. markat/robotics/__init__.py +18 -0
  40. markat/robotics/loop_hoister.py +428 -0
  41. markat/robotics/multistream.py +482 -0
  42. markat/simplifier.py +372 -0
  43. markat/structure/__init__.py +24 -0
  44. markat/structure/mask_analyzer.py +222 -0
  45. markat/structure/ops.py +408 -0
  46. markat/structure/specializer.py +618 -0
  47. markat_compiler-0.3.0.dist-info/METADATA +447 -0
  48. markat_compiler-0.3.0.dist-info/RECORD +53 -0
  49. markat_compiler-0.3.0.dist-info/WHEEL +5 -0
  50. markat_compiler-0.3.0.dist-info/entry_points.txt +2 -0
  51. markat_compiler-0.3.0.dist-info/licenses/LICENSE +201 -0
  52. markat_compiler-0.3.0.dist-info/licenses/NOTICE +4 -0
  53. markat_compiler-0.3.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,266 @@
1
+ # Copyright 2026 Athrva Pandhare
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Measured ONNX Runtime latency harness for Markat artifacts.
5
+
6
+ The harness measures execution; it never derives a number from the cost model.
7
+ An artifact (or an in-memory ``ModelProto``) is loaded by ONNX Runtime on the
8
+ requested providers, warmed up for ``warmup`` runs, then each of ``iters``
9
+ ``session.run`` calls is timed individually with :func:`time.perf_counter`.
10
+ The reported percentiles are computed from those measured samples only.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import dataclass
16
+ from datetime import datetime, timezone
17
+ import gc
18
+ import os
19
+ from pathlib import Path
20
+ import platform
21
+ import time
22
+ from typing import Any, Sequence
23
+
24
+ import numpy as np
25
+ import onnx
26
+ import onnxruntime as ort
27
+ import torch
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class BenchmarkResult:
32
+ """One measured benchmark run.
33
+
34
+ ``device_meta`` is best-effort environment metadata, not a hardware
35
+ specification: ``platform``/``machine``/``processor`` come from the
36
+ standard library (``processor`` may be empty on some Linux systems),
37
+ ``cpu_capability`` from ``torch.backends.cpu``, and the remaining entries
38
+ from the running interpreter. All values are strings so the record stays
39
+ JSON-friendly.
40
+ """
41
+
42
+ provider: str
43
+ device_meta: dict[str, str]
44
+ warmup_iters: int
45
+ timed_iters: int
46
+ latency_ms_p50: float
47
+ latency_ms_p95: float
48
+ latency_ms_p99: float
49
+ latency_ms_mean: float
50
+ fusion_audit: dict[str, int] | None
51
+ artifact_bytes: int
52
+ timestamp: str
53
+ markat_version: str
54
+ torch_version: str
55
+ ort_version: str
56
+
57
+
58
+ def _markat_version() -> str:
59
+ # Imported lazily: ``markat/__init__`` imports this module, so the version
60
+ # attribute is not bound yet while the benchmark module is being loaded.
61
+ import markat
62
+
63
+ return markat.__version__
64
+
65
+
66
+ def _device_metadata() -> dict[str, str]:
67
+ """Best-effort, platform-dependent CPU/runtime metadata."""
68
+ return {
69
+ "platform": platform.platform(),
70
+ "system": platform.system(),
71
+ "machine": platform.machine(),
72
+ "processor": platform.processor()
73
+ or os.environ.get("PROCESSOR_IDENTIFIER", "")
74
+ or platform.machine(),
75
+ "cpu_capability": torch.backends.cpu.get_cpu_capability(),
76
+ "torch_threads": str(torch.get_num_threads()),
77
+ "python": platform.python_version(),
78
+ }
79
+
80
+
81
+ def _to_numpy(value: Any) -> Any:
82
+ if isinstance(value, torch.Tensor):
83
+ return value.detach().cpu().numpy()
84
+ return value
85
+
86
+
87
+ def _build_feeds(
88
+ session: ort.InferenceSession, example_inputs: Any
89
+ ) -> dict[str, Any]:
90
+ """Map caller inputs onto the session's input names in declaration order."""
91
+ if isinstance(example_inputs, dict):
92
+ return {name: _to_numpy(value) for name, value in example_inputs.items()}
93
+ if isinstance(example_inputs, (torch.Tensor, np.ndarray)):
94
+ values: tuple[Any, ...] = (example_inputs,)
95
+ else:
96
+ values = tuple(example_inputs)
97
+ inputs = session.get_inputs()
98
+ if len(values) != len(inputs):
99
+ raise ValueError(
100
+ f"benchmark received {len(values)} example input(s) for a session "
101
+ f"with {len(inputs)} input(s)"
102
+ )
103
+ return {
104
+ meta.name: _to_numpy(value) for meta, value in zip(inputs, values)
105
+ }
106
+
107
+
108
+ def _has_external_data(proto: onnx.ModelProto) -> bool:
109
+ return any(
110
+ tensor.data_location == onnx.TensorProto.EXTERNAL
111
+ for tensor in proto.graph.initializer
112
+ )
113
+
114
+
115
+ def _session_source(artifact: Any) -> bytes | str:
116
+ """Return the source handed to ``onnxruntime.InferenceSession``."""
117
+ if isinstance(artifact, onnx.ModelProto):
118
+ if _has_external_data(artifact):
119
+ raise ValueError(
120
+ "this ModelProto stores weights in external data; pass the "
121
+ "artifact path instead so ONNX Runtime can resolve the sidecar"
122
+ )
123
+ return artifact.SerializeToString()
124
+ path = Path(artifact)
125
+ if not path.exists():
126
+ raise FileNotFoundError(f"ONNX artifact not found: {path}")
127
+ return str(path)
128
+
129
+
130
+ def _artifact_bytes(artifact: Any, session_source: bytes | str) -> int:
131
+ if isinstance(artifact, onnx.ModelProto):
132
+ assert isinstance(session_source, bytes)
133
+ return len(session_source)
134
+ path = Path(artifact)
135
+ total = path.stat().st_size
136
+ sidecar = path.with_name(f"{path.name}.data")
137
+ if sidecar.exists():
138
+ total += sidecar.stat().st_size
139
+ return total
140
+
141
+
142
+ def _latency_summary(latencies_ms: Sequence[float]) -> tuple[float, float, float, float]:
143
+ samples = np.asarray(latencies_ms, dtype=np.float64)
144
+ p50, p95, p99 = (float(value) for value in np.percentile(samples, (50, 95, 99)))
145
+ return p50, p95, p99, float(samples.mean())
146
+
147
+
148
+ def benchmark_onnx_artifact(
149
+ artifact_or_proto: Any,
150
+ example_inputs: Any,
151
+ *,
152
+ providers: Sequence[str] = ("CPUExecutionProvider",),
153
+ warmup: int = 10,
154
+ iters: int = 50,
155
+ session_options: ort.SessionOptions | None = None,
156
+ fusion_audit: dict[str, int] | None = None,
157
+ ) -> BenchmarkResult:
158
+ """Measure ``session.run`` latency for an ONNX artifact on this machine.
159
+
160
+ Parameters
161
+ ----------
162
+ artifact_or_proto:
163
+ Path to a ``.onnx`` artifact (preferred: a path lets ONNX Runtime
164
+ resolve an external ``.onnx.data`` sidecar naturally) or an in-memory
165
+ ``onnx.ModelProto`` whose weights are inline.
166
+ example_inputs:
167
+ A single tensor/array, a tuple/list of inputs in the session's input
168
+ order, or a dict keyed by input name. Torch tensors are moved to CPU
169
+ NumPy; other values are passed through unchanged.
170
+ providers, session_options:
171
+ Forwarded to ``onnxruntime.InferenceSession``. The first entry becomes
172
+ the reported ``provider``.
173
+ warmup, iters:
174
+ Warmup runs (excluded from the samples), then individually timed
175
+ ``session.run`` calls. ``warmup >= 0`` and ``iters >= 1``.
176
+ fusion_audit:
177
+ Optional fusion audit copied from the export report so the measurement
178
+ record can carry the provider-optimized op counts.
179
+
180
+ The percentile fields are computed from the timed samples with linear
181
+ interpolation; ``p50 <= p95 <= p99`` holds by construction. Two runs of the
182
+ same artifact differ only in timings and the timestamp.
183
+ """
184
+ if warmup < 0:
185
+ raise ValueError(f"warmup must be non-negative, got {warmup}")
186
+ if iters < 1:
187
+ raise ValueError(f"iters must be at least 1, got {iters}")
188
+ if not providers:
189
+ raise ValueError("at least one execution provider is required")
190
+
191
+ session_source = _session_source(artifact_or_proto)
192
+ session = ort.InferenceSession(
193
+ session_source,
194
+ sess_options=session_options,
195
+ providers=list(providers),
196
+ )
197
+ feeds = _build_feeds(session, example_inputs)
198
+
199
+ for _ in range(warmup):
200
+ session.run(None, feeds)
201
+
202
+ # A collection triggered by the append/allocate between two timed calls
203
+ # would be charged to the sample. Disabling the collector for the timed loop
204
+ # keeps the measured interval to the ``session.run`` call itself; the
205
+ # previous collector state is restored even if a run raises.
206
+ gc_was_enabled = gc.isenabled()
207
+ gc.disable()
208
+ latencies_ms: list[float] = []
209
+ try:
210
+ for _ in range(iters):
211
+ start = time.perf_counter()
212
+ session.run(None, feeds)
213
+ latencies_ms.append((time.perf_counter() - start) * 1000.0)
214
+ finally:
215
+ if gc_was_enabled:
216
+ gc.enable()
217
+
218
+ p50, p95, p99, mean = _latency_summary(latencies_ms)
219
+ return BenchmarkResult(
220
+ provider=str(session.get_providers()[0]),
221
+ device_meta=_device_metadata(),
222
+ warmup_iters=warmup,
223
+ timed_iters=iters,
224
+ latency_ms_p50=p50,
225
+ latency_ms_p95=p95,
226
+ latency_ms_p99=p99,
227
+ latency_ms_mean=mean,
228
+ fusion_audit=dict(fusion_audit) if fusion_audit is not None else None,
229
+ artifact_bytes=_artifact_bytes(artifact_or_proto, session_source),
230
+ timestamp=datetime.now(timezone.utc).isoformat(),
231
+ markat_version=_markat_version(),
232
+ torch_version=torch.__version__,
233
+ ort_version=ort.__version__,
234
+ )
235
+
236
+
237
+ def benchmark_simplified(
238
+ graph: torch.nn.Module,
239
+ example_inputs: Any,
240
+ *,
241
+ providers: Sequence[str] = ("CPUExecutionProvider",),
242
+ warmup: int = 10,
243
+ iters: int = 50,
244
+ session_options: ort.SessionOptions | None = None,
245
+ ) -> BenchmarkResult:
246
+ """Export ``graph`` with :func:`markat.export_onnx` defaults, then measure it.
247
+
248
+ This convenience helper deliberately uses the default export settings
249
+ (generic ORT CPU target, no external data, no dynamic-shape overrides, ORT
250
+ verification on) so it cannot silently diverge from what the caller asked
251
+ for. When a specific target, dynamic axes, or an on-disk external-data
252
+ artifact is required, export explicitly and pass the artifact path to
253
+ :func:`benchmark_onnx_artifact` instead.
254
+ """
255
+ from markat.exporter.onnx_export import export_onnx
256
+
257
+ proto, report = export_onnx(graph, example_inputs)
258
+ return benchmark_onnx_artifact(
259
+ proto,
260
+ example_inputs,
261
+ providers=providers,
262
+ warmup=warmup,
263
+ iters=iters,
264
+ session_options=session_options,
265
+ fusion_audit=report.fusion_audit or None,
266
+ )
@@ -0,0 +1,8 @@
1
+ # Copyright 2026 Athrva Pandhare
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Runtime calibration profiling for attention structure and activation quantization sensitivity."""
5
+
6
+ from markat.calibration.profiler import CalibrationProfile, CalibrationProfiler
7
+
8
+ __all__ = ["CalibrationProfile", "CalibrationProfiler"]
@@ -0,0 +1,317 @@
1
+ # Copyright 2026 Athrva Pandhare
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Forward-hook and FX-interpreter profiler collecting masks, Linear/Conv2d activations, and task-weighted sensitivities."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass, field
9
+ from typing import Any
10
+
11
+ import torch
12
+ import torch.fx as fx
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+
16
+
17
+ @dataclass
18
+ class LayerActivationStats:
19
+ """Subsampled input/output activations and downstream sensitivity weight for a Linear or Conv2d layer."""
20
+
21
+ sample_inputs: torch.Tensor
22
+ output_energy: float
23
+ amplification_factor: float = 1.0
24
+ max_abs_activation: float = 0.0
25
+ percentile_999_abs: float = 0.0
26
+ min_activation: float = 0.0
27
+ max_activation: float = 0.0
28
+ outlier_ratio: float = 0.0
29
+ # Observed output activations. ``out_sample_inputs`` holds the bounded
30
+ # output sample tensor; the scalar fields record the same summary
31
+ # statistics as the inputs so a static output Q/DQ grid can be calibrated
32
+ # without clipping amplified layers. All default to "absent" so hand-built
33
+ # stats objects keep the legacy mirror-of-input behaviour.
34
+ out_sample_inputs: torch.Tensor | None = None
35
+ out_max_abs_activation: float = 0.0
36
+ out_min_activation: float = 0.0
37
+ out_max_activation: float = 0.0
38
+ out_percentile_999_abs: float = 0.0
39
+
40
+
41
+ @dataclass
42
+ class CalibrationProfile:
43
+ """Aggregated runtime observations across calibration inputs."""
44
+
45
+ invariant_masks: dict[str, torch.Tensor] = field(default_factory=dict)
46
+ layer_stats: dict[str, LayerActivationStats] = field(default_factory=dict)
47
+ reference_outputs: list[torch.Tensor] = field(default_factory=list)
48
+ mean_output_energy: float = 1.0
49
+
50
+
51
+ class _MaskObservingInterpreter(fx.Interpreter):
52
+ """FX Interpreter that records `attn_mask` tensors passed to MHA / SDPA / baddbmm nodes."""
53
+
54
+ def __init__(self, gm: fx.GraphModule) -> None:
55
+ super().__init__(gm)
56
+ self.seen_masks: dict[str, list[torch.Tensor]] = {}
57
+
58
+ def run_node(self, n: fx.Node) -> Any:
59
+ args, kwargs = self.fetch_args_kwargs_from_env(n)
60
+ if n.op == "call_module":
61
+ submod = self.fetch_attr(str(n.target))
62
+ if isinstance(submod, nn.MultiheadAttention):
63
+ mask = args[5] if len(args) >= 6 else kwargs.get("attn_mask")
64
+ if isinstance(mask, torch.Tensor):
65
+ self.seen_masks.setdefault(n.name, []).append(mask.detach().cpu().clone())
66
+ elif n.op == "call_function" and n.target is F.scaled_dot_product_attention:
67
+ mask = args[3] if len(args) >= 4 else kwargs.get("attn_mask")
68
+ if isinstance(mask, torch.Tensor):
69
+ self.seen_masks.setdefault(n.name, []).append(mask.detach().cpu().clone())
70
+ elif n.op == "call_function" and "baddbmm" in getattr(n.target, "__name__", str(n.target)):
71
+ if len(args) >= 3 and isinstance(args[0], torch.Tensor):
72
+ self.seen_masks.setdefault(n.name, []).append(args[0].detach().cpu().clone())
73
+ return super().run_node(n)
74
+
75
+
76
+ def _extract_primary_tensor(out: Any) -> torch.Tensor | None:
77
+ if isinstance(out, torch.Tensor):
78
+ return out
79
+ if isinstance(out, (tuple, list)):
80
+ for item in out:
81
+ t = _extract_primary_tensor(item)
82
+ if t is not None:
83
+ return t
84
+ if isinstance(out, dict):
85
+ for item in out.values():
86
+ t = _extract_primary_tensor(item)
87
+ if t is not None:
88
+ return t
89
+ return None
90
+
91
+
92
+ def _sample_activation_stats(
93
+ chunks: list[torch.Tensor],
94
+ ) -> tuple[torch.Tensor | None, float, float, float, float]:
95
+ """Concatenate captured samples and summarize their activation range.
96
+
97
+ Returns ``(sample, max_abs, percentile_999_abs, min, max)``. An empty list
98
+ yields ``(None, 0.0, 0.0, 0.0, 0.0)`` so a missing capture leaves the
99
+ "no statistics" sentinel that callers fall back on.
100
+ """
101
+ if not chunks:
102
+ return None, 0.0, 0.0, 0.0, 0.0
103
+ sample = torch.cat(chunks, dim=0)
104
+ xf = sample.float()
105
+ abs_x = xf.abs()
106
+ max_abs = float(abs_x.max().item()) if abs_x.numel() > 0 else 0.0
107
+ p999 = (
108
+ float(torch.quantile(abs_x.reshape(-1)[:65536], 0.9995).item())
109
+ if abs_x.numel() > 0
110
+ else max_abs
111
+ )
112
+ min_v = float(xf.min().item()) if xf.numel() > 0 else 0.0
113
+ max_v = float(xf.max().item()) if xf.numel() > 0 else 0.0
114
+ return sample, max_abs, p999, min_v, max_v
115
+
116
+
117
+ class CalibrationProfiler:
118
+ """Collects runtime mask invariants and per-layer Linear/Conv2d activation sensitivity data."""
119
+
120
+ def __init__(self, max_tokens_per_layer: int = 512, max_conv_samples: int = 16) -> None:
121
+ self.max_tokens_per_layer = max_tokens_per_layer
122
+ self.max_conv_samples = max_conv_samples
123
+
124
+ def collect_masks(
125
+ self, gm: fx.GraphModule, batches: list[tuple[Any, ...]]
126
+ ) -> dict[str, torch.Tensor]:
127
+ """Run batches through an FX interpreter to detect invariant runtime attention masks."""
128
+ if not batches:
129
+ return {}
130
+ interp = _MaskObservingInterpreter(gm)
131
+ with torch.no_grad():
132
+ for batch in batches[:4]:
133
+ try:
134
+ interp.run(*batch)
135
+ except Exception:
136
+ return {}
137
+
138
+ invariant: dict[str, torch.Tensor] = {}
139
+ for node_name, masks in interp.seen_masks.items():
140
+ if not masks:
141
+ continue
142
+ first = masks[0]
143
+ if all(
144
+ m.shape == first.shape
145
+ and m.dtype == first.dtype
146
+ and torch.equal(torch.isnan(m), torch.isnan(first))
147
+ and torch.equal(
148
+ torch.nan_to_num(m, nan=0.0, neginf=-1e9, posinf=1e9),
149
+ torch.nan_to_num(first, nan=0.0, neginf=-1e9, posinf=1e9),
150
+ )
151
+ for m in masks[1:]
152
+ ):
153
+ invariant[node_name] = first
154
+ return invariant
155
+
156
+ def collect_layer_activations_and_sensitivity(
157
+ self,
158
+ gm: fx.GraphModule,
159
+ batches: list[tuple[Any, ...]],
160
+ output_channel_weights: list[float] | None = None,
161
+ ) -> CalibrationProfile:
162
+ """Capture sample activations for `nn.Linear` and `nn.Conv2d` submodules and estimate sensitivities."""
163
+ profile = CalibrationProfile()
164
+ if not batches:
165
+ return profile
166
+
167
+ captured_inputs: dict[str, list[torch.Tensor]] = {}
168
+ captured_outputs: dict[str, list[torch.Tensor]] = {}
169
+ captured_out_energy: dict[str, list[float]] = {}
170
+ hooks: list[Any] = []
171
+
172
+ target_modules: dict[str, nn.Module] = {
173
+ name: mod
174
+ for name, mod in gm.named_modules()
175
+ if type(mod) in (nn.Linear, nn.Conv2d)
176
+ }
177
+
178
+ def _make_hook(lname: str, is_conv: bool):
179
+ def _hook(mod: nn.Module, inp: tuple[Any, ...], out: Any) -> None:
180
+ if not inp or not isinstance(inp[0], torch.Tensor):
181
+ return
182
+ x = inp[0].detach()
183
+ curr = captured_inputs.setdefault(lname, [])
184
+ already = sum(t.shape[0] for t in curr)
185
+ if is_conv:
186
+ if already < self.max_conv_samples:
187
+ take = min(x.shape[0], self.max_conv_samples - already)
188
+ curr.append(x[:take].cpu())
189
+ else:
190
+ flat_x = x.reshape(-1, x.shape[-1])
191
+ if already < self.max_tokens_per_layer:
192
+ take = min(flat_x.shape[0], self.max_tokens_per_layer - already)
193
+ curr.append(flat_x[:take].cpu())
194
+
195
+ if isinstance(out, torch.Tensor):
196
+ e = float(out.detach().float().pow(2).mean().item())
197
+ captured_out_energy.setdefault(lname, []).append(e)
198
+
199
+ # Bound the observed output samples exactly like the inputs
200
+ # so the output activation grid is calibrated on the same
201
+ # representative subset at no extra memory cost.
202
+ y = out.detach()
203
+ curr_out = captured_outputs.setdefault(lname, [])
204
+ already_out = sum(t.shape[0] for t in curr_out)
205
+ if is_conv:
206
+ if already_out < self.max_conv_samples:
207
+ take = min(y.shape[0], self.max_conv_samples - already_out)
208
+ curr_out.append(y[:take].cpu())
209
+ else:
210
+ flat_y = y.reshape(-1, y.shape[-1])
211
+ if already_out < self.max_tokens_per_layer:
212
+ take = min(flat_y.shape[0], self.max_tokens_per_layer - already_out)
213
+ curr_out.append(flat_y[:take].cpu())
214
+
215
+ return _hook
216
+
217
+ for name, mod in target_modules.items():
218
+ hooks.append(mod.register_forward_hook(_make_hook(name, isinstance(mod, nn.Conv2d))))
219
+
220
+ ref_outputs: list[torch.Tensor] = []
221
+ out_energies: list[float] = []
222
+ try:
223
+ with torch.no_grad():
224
+ for batch in batches:
225
+ raw_out = gm(*batch)
226
+ t_out = _extract_primary_tensor(raw_out)
227
+ if t_out is not None:
228
+ ref_outputs.append(t_out.detach().clone())
229
+ out_energies.append(float(t_out.detach().float().pow(2).sum().item()))
230
+ finally:
231
+ for h in hooks:
232
+ h.remove()
233
+
234
+ profile.reference_outputs = ref_outputs
235
+ profile.mean_output_energy = sum(out_energies) / max(len(out_energies), 1)
236
+
237
+ first_batch = batches[0]
238
+ base_out = ref_outputs[0].float() if ref_outputs else None
239
+ chan_w_tensor: torch.Tensor | None = None
240
+ if base_out is not None and output_channel_weights is not None:
241
+ if len(output_channel_weights) == base_out.shape[-1]:
242
+ chan_w_tensor = torch.tensor(
243
+ output_channel_weights, dtype=torch.float32, device=base_out.device
244
+ )
245
+
246
+ for name, mod in target_modules.items():
247
+ chunks = captured_inputs.get(name, [])
248
+ if not chunks:
249
+ continue
250
+ sample_x, max_abs, p999, min_v, max_v = _sample_activation_stats(chunks)
251
+ assert sample_x is not None
252
+ xf = sample_x.float()
253
+ med_abs = float(xf.abs().median().item()) if xf.numel() > 0 else 1.0
254
+
255
+ out_sample, out_max_abs, out_p999, out_min_v, out_max_v = _sample_activation_stats(
256
+ captured_outputs.get(name, [])
257
+ )
258
+
259
+ # Channel-wise outlier ratio for Linear [N, C], or overall max/median for Conv2d
260
+ if isinstance(mod, nn.Linear) and xf.ndim == 2 and xf.shape[1] > 1:
261
+ ch_max = xf.abs().amax(dim=0)
262
+ outlier_ratio = float(ch_max.max().item()) / max(float(ch_max.median().item()), 1e-6)
263
+ else:
264
+ outlier_ratio = max_abs / max(med_abs, 1e-6)
265
+
266
+ layer_e = sum(captured_out_energy.get(name, [1.0])) / max(
267
+ len(captured_out_energy.get(name, [1.0])), 1
268
+ )
269
+
270
+ amp = 1.0
271
+ if base_out is not None:
272
+ noise_norm_sq = 0.0
273
+
274
+ def _perturb_hook(_m: nn.Module, _i: Any, o: torch.Tensor) -> torch.Tensor:
275
+ nonlocal noise_norm_sq
276
+ eps_scale = max(float(o.detach().float().std().item()) * 1e-3, 1e-4)
277
+ gen = torch.Generator(device="cpu").manual_seed(1337)
278
+ delta = (
279
+ torch.randn(o.shape, generator=gen, dtype=torch.float32).to(o.device)
280
+ * eps_scale
281
+ )
282
+ noise_norm_sq = float(delta.pow(2).sum().item())
283
+ return o + delta.to(o.dtype)
284
+
285
+ ph = mod.register_forward_hook(_perturb_hook)
286
+ try:
287
+ with torch.no_grad():
288
+ pert_raw = gm(*first_batch)
289
+ pert_t = _extract_primary_tensor(pert_raw)
290
+ if pert_t is not None and noise_norm_sq > 0:
291
+ diff = pert_t.float() - base_out
292
+ if chan_w_tensor is not None:
293
+ diff = diff * chan_w_tensor
294
+ out_diff_sq = float(diff.pow(2).sum().item())
295
+ amp = (out_diff_sq / noise_norm_sq) ** 0.5
296
+ except Exception:
297
+ amp = 1.0
298
+ finally:
299
+ ph.remove()
300
+
301
+ profile.layer_stats[name] = LayerActivationStats(
302
+ sample_inputs=sample_x,
303
+ output_energy=layer_e,
304
+ amplification_factor=max(amp, 1e-6),
305
+ max_abs_activation=max_abs,
306
+ percentile_999_abs=p999,
307
+ min_activation=min_v,
308
+ max_activation=max_v,
309
+ outlier_ratio=outlier_ratio,
310
+ out_sample_inputs=out_sample,
311
+ out_max_abs_activation=out_max_abs,
312
+ out_min_activation=out_min_v,
313
+ out_max_activation=out_max_v,
314
+ out_percentile_999_abs=out_p999,
315
+ )
316
+
317
+ return profile