Repository navigation
v2.18.0
v2.18.0 (2026-05-29)
This release is published under the Apache-2.0 License.
Bug Fixes
-
alpha3: Accept LiveOpView in nonfinite check (
4e4e683) -
alpha3: Keep auxiliary T2 paths compatible (
b665119) -
alpha3: Materialize failed partial traces (
c0584b5) -
alpha3: Restore streaming strict capture writes (
b7b3627) -
alpha3: Restore train_mode out_postfunc detach validation (
20b7fd0)
Co-authored-by: Codex codex@openai.com
-
backward, demo: Pin grad_fn refs, fork conditional viz at single node, add bundle diff (
3cc4c46) -
backward: hold strong refs to discovered grad_fns in trace._grad_fn_strong_refs.
Without this, leaf AccumulateGrad nodes could be gc'd and Python could recycle
their id() values for later-created grad_fns (e.g., the output clone wrapper),
producing phantom cycles in next_grad_fn_ids and conflated/missing
AccumulateGrad nodes in the rendered backward graph. -
TinyBranchCNN demo: restructure forward so each arm consumes x directly
(matches SimpleIfElseModel). Now both IF and THEN/ELSE labels emanate from
input_1 as a single visible fork point in the rendered graph, instead of
IF on input -> mean and THEN far downstream on the body's first edge. -
Notebook: add bundle.show_diff visual cell.
Tests: 209 conditional + backward + smoke green.
- bundle_diff: Drop hard size+ratio constraints that clipped the caption (
58bf90c)
The renderer set size: 12,8! (hard fit) plus ratio: fill (force aspect), forcing the layout into a 1.5:1 box. The natural paired layout is ~1.69:1 taller, so graphviz emitted a viewBox shorter than the content; the bottom-positioned caption got pushed below the visible viewBox and clipped in rendered SVGs.
Removing both attrs lets graphviz auto-size to the natural aspect (793x470 for the canonical ResNet-18 demo) so the caption fits inside the viewBox.
Updated the canonical snapshot to match the new aspect. Bundle tests (78) plus smoke (170) green.
- bundle_diff: Key layer-to-supergraph lookup by layer_label, not id() (
d126ce5)
bundle.aligned_pairs() and bundle.supergraph.nodes materialize independent layer objects with different id() values. The renderer's layer_to_node dict was keyed by id(layer) from supergraph; lookups during render iterated layers from aligned_pairs and missed every entry, so every node fell back to a delta of 0.0, max_delta resolved to 0.0, and _delta_color short-circuited to "#FFFFFF" for every cell. Result: the diff rendered all-white with no visible per-node delta colorization.
Switch the dict key to layer.layer_label (stable string) and look it up the same way at every consumer site. Now value=0 maps to blue, intermediate nodes show salmon at ~0.85 of max, and red shows up at max-delta sites.
Regenerated canonical snapshot + hero demo SVG. Bundle (79) + smoke (170) green.
- bundle_diff: Use dpi=72 so viewBox matches actual content extent (
c90d8d2)
Setting dpi=100 makes graphviz emit a viewBox in internal layout coords while the inner <g transform="..."> applies a scale(100/72=1.389) to convert to display coords. Net effect: SVG content (background polygon, caption, legend) extends to y=633 in transformed coords but viewBox max y is only 470. Bottom ~25% of the figure was clipped.
dpi=72 (graphviz default) keeps viewBox in the same units as content, so content fits inside (text max y=456 vs viewBox max=470).
Regenerated canonical snapshot + hero demo SVG. Bundle (78) + smoke (170) green.
-
capture: Preserve new raw_input across rerun atomic swap (
7fa8a8f) -
ci: Let git-lfs tolerate the CI tag push (allowincompletepush) (
056193d)
git lfs uninstall cleared the original bracketed-URL LFS failure but the tag push then hit "missing or corrupt local objects": CI checks out with lfs disabled (pointers only), so git-lfs refuses to push the tag whose tree references LFS objects it can't find locally. Those objects already live on the remote, so set lfs.allowincompletepush true (git-lfs's own recommended fix) plus lfs.locksverify false. This lets the version tag actually get created so the release completes (PyPI publish + GitHub release).
Generated with Claude Code via Happy
Co-Authored-By: Claude noreply@anthropic.com
Co-Authored-By: Happy yesreply@happy.engineering
- ci: Stop runaway semantic-release loop (skip-ci + lfs tag push) (
0b24b6e)
Two compounding bugs produced a 1599-commit release loop:
-
The bot's
chore(release):commit re-triggered the Release workflow (no skip token), so every release pushed a commit that started another release. Fixed by appending[skip ci]to commit_message and adding a job guard that refuses to run onchore(release):head commits. -
The version TAG push failed under git-lfs: the App credential URL (username
torchlens-release[bot]) breaks git-lfs endpoint parsing ("batch request: missing protocol"). Plain commit pushes tolerate it but the tag push invokes LFS and dies, so no tag was ever created and each run re-released the same commits since v2.17.0. Fixed bygit lfs uninstallin the release job (LFS objects already live on the remote).
Generated with Claude Code via Happy
Co-Authored-By: Claude noreply@anthropic.com
Co-Authored-By: Happy yesreply@happy.engineering
- facets: Correct LayerNorm gamma+beta resolution; add HF tutorial; lock spec (
9406863)
Three follow-ups to 3ada85d:
-
torchlens/semantic/recipes/norm.py LayerNorm + RMSNorm recipes were reading
mod.cls.weight. Module.cls stores the class object, not the live instance, so cls.weight returns None andadd_if_presentskipped the entry -- gamma was declared in keys() but unreachable on access. Fix iterates module.params and matches on param.name, falling back to None gracefully when param.value is None. -
notebooks/huggingface_tutorial.ipynb First commit of the HF tutorial. 52 cells; the new "10. Facets" section adds 19 cells demonstrating recipe listing, q/k/v access, .head(i) sub-view, log.attention_blocks() sweeping, MLP/LN facets, fused-SDPA pattern error, user recipe registration, and tl.facets.info() discovery. Executed clean end-to-end.
-
.project-context/glossary_walkthrough_deltas.md Appended the "Facets framework ... (LOCKED 2026-05-27)" entry that 3ada85d implemented against. Makes the spec source of truth visible alongside the implementation.
-
fastlog: Preserve halt through predicate catch sites (
810b5a2) -
glossary-v5: Restore module collapse rendering for vis_call_depth (
16fc0eb)
The v5 additions accidentally changed module-entry annotation semantics by renaming the buffer-address scratch variable in module entry capture. That made ordinary leaf module outputs become atomic module exits, which prevented top-level leaf modules from being collapsed by legacy vis_call_depth rendering and drifted module-containment snapshots.\n\nRestore the legacy entry annotation behavior while keeping the v5 template capture additions, and make the collapse-address helper return the legacy depth target directly. Atomic outputs now only bubble to a parent module when such a parent exists, so top-level leaf modules remain eligible for vis_call_depth=1 collapse.
-
grad_fn_log: Rename has_op to is_intervening (
e7668ea) -
intervention: Preserve is_appended in replace_run_state_from atomic swap (
071e9e4) -
intervention: Preserve tl_tensor_label_raw on tensor replacement (
869c8ee)
Implements two-layer fix for INTERVENTION-MISSING-TENSOR-LABEL bug discovered during the 2026-05-04 NeurIPS fleet overnight run (EXP_19, EXP_20).
Layer A: intervention API now propagates tl_* attrs from original to replacement. Layer B: _handle_module_exit gracefully re-instruments tensors lacking tl_tensor_label_raw,
covering raw register_forward_hook patterns outside the official API.
Adds regression tests for: official intervention API, raw forward_hook replacement, chain-of-interventions, quantization-sensitivity pattern. All 4 pass in <1s.
Bonus: also fixes a state_dict._metadata clobbering issue in validate_forward_pass that affected torchvision MNASNet, surfaced during the bulletproofing audit.
Closes INTERVENTION-MISSING-TENSOR-LABEL.
-
intervention: Reject append=True on streaming-active trace (
423b5ee) -
io: Audit-null mlx tensors on save (
84622f1) -
io: Serialize module pass tabular outputs (
68f1280) -
loop-detection: Include output index in multi-output eq-class (
b98f659) -
mlx: Bind wrappers per trace and resolve inputs (
429c11c) -
mlx: Hard-reject unsupported preview options (
a74f0dd) -
model-log: Clear is_appended on non-append rerun (
e5a8e69) -
rename: Update intervention examples for ledger rename + bundle len (
455e0f0)
Codex's R2 missed three example files: operation_history was renamed to ledger (per glossary walkthrough deltas), and 13_paired_prompt_3plus.py had a stale lambda that called .names on a Trace member. Replaced with idiomatic len(bundle).
All three intervention example tests now pass (test_examples.py::test_intervention_example_runs[05/06/13]).
-
save-load: Reattach module output references (
20790d4) -
save-load: Tolerate legacy module logs without calls (
c37ad47) -
semantic: Cover DistilBERT eager/flash attention in facet recipe (
4c0d6ee)
The attention facet recipe only registered DistilBertSdpaAttention, so switching to _attn_implementation='eager' (which the pattern MissingFacet explicitly recommends) landed on the unregistered MultiHeadSelfAttention class and raised KeyError('q') on facets.q / facets.head(n).q. Register the same q_lin/k_lin/v_lin extraction for all three DistilBERT attention classes: MultiHeadSelfAttention (eager, no pattern), DistilBertSdpaAttention and DistilBertFlashAttention2 (fused, pattern via MissingFacet). Flash is now also flagged as fused for the pattern facet.
Generated with Claude Code via Happy
Co-Authored-By: Claude noreply@anthropic.com
Co-Authored-By: Happy yesreply@happy.engineering
- semantic: Cover transformers 5.x DistilBertSelfAttention in facet recipe (
3e4dc6b)
transformers 5.x collapsed DistilBERT's per-backend attention subclasses (MultiHeadSelfAttention / DistilBertSdpaAttention / DistilBertFlashAttention2) into a single DistilBertSelfAttention class, selecting eager/sdpa via a runtime function. That class was unregistered, so facets.q / facets.head(n).q raised KeyError('q') on transformers 5.x even though the q_lin/k_lin/v_lin children are unchanged.
Register DistilBertSelfAttention alongside the existing classes. Its default backend is fused SDPA and the class name no longer encodes the backend, so it surfaces pattern as the informative MissingFacet (RuntimeError on access) rather than a silent AttributeError -- keeps the fused-pattern teaching path working. 4.x eager MultiHeadSelfAttention behavior is unchanged.
Generated with Claude Code via Happy
Co-Authored-By: Claude noreply@anthropic.com
Co-Authored-By: Happy yesreply@happy.engineering
- tests: Register synthetic migration examples in linecache; skip nnsight>=0.7 (
4c2fb61)
The migration-example test runner exec'd code under a synthetic filename without registering it in linecache, so any example whose tooling called inspect.getsource on user code (nnsight LanguageModel does this) failed with OSError: source code not available.
Also skips the from_nnsight.md example on nnsight>=0.7, where the LanguageModel.trace input semantics changed and our pinned expected output no longer applies.
- types: Resolve pre-existing mypy errors in data_classes/ (
0f54ba5)
Cleans up mypy errors flagged repeatedly throughout the M1-M8 capture-pipeline-unification sprint. Errors were in data_classes accessors and ModuleLog/ModuleCallLog narrowing, with a few import-chain typing leaks required by the exact data_classes mypy gate.
No behavior change. Runtime tests remain green.
-
user-api: Register tensor connections on live records (
0e3c2ce) -
validation: Allow multi-output parameterized ops (
8b85905) -
validation: Backward validator handles stacked traces (
2271de7) -
viz: Add colon separator between param name and shape in node labels (
0e323b8)
Renders 'weight: (16, 3, 3, 3)' instead of 'weight (16, 3, 3, 3)' in graphviz param labels and inline param lines.
-
viz: Drop render_graph shim; auto-suppress xdg-open on headless (
1c31b6b) -
viz: Drop space after @ in module address labels (
2dfe89d)
Module path rows rendered as "@ module1.module2"; tighten to "@module1.module2" so the dotted path reads as a single token and matches the no-space form already used by bundle_diff and the dagua bridge.
Generated with Claude Code via Happy
Co-Authored-By: Claude noreply@anthropic.com
Co-Authored-By: Happy yesreply@happy.engineering
-
viz: Handle headless trace drawing (
cb141cf) -
viz: Read live capture event counts (
371f569) -
viz: Suppress headless auto-open note inside notebooks (
a1fce6b)
In a notebook the figure is shown inline via IPython display(); the draw path still fell through to _view_rendered_file, which on a headless remote kernel printed "headless context detected; ... skipping auto-open". Bail out of _open_file_quietly when in_notebook() so no desktop viewer is launched and no misleading note is printed. Centralizing in the shared helper also covers the sfdp/ELK/bundle render paths.
Generated with Claude Code via Happy
Co-Authored-By: Claude noreply@anthropic.com
Co-Authored-By: Happy yesreply@happy.engineering
- viz: Use sequential bundle diff palette (
da060bf)
Chores
-
audit: Regenerate coverage manifest after notebook rewrite (
d62dadc) -
Regenerate the public API coverage manifest from current TorchLens.
-
Refresh the strict coverage matrix after the notebook rewrite.
-
audit: Rewrite 00_install_and_smoke.ipynb to actually exercise its declared coverage (
a590ab6) -
Demonstrate import surface, all, and first tiny-model capture.
-
Add shared audit helpers that resolve coverage names against live objects.
-
audit: Rewrite 01_basic_capture.ipynb to actually exercise its declared coverage (
7ee5c26) -
Demonstrate canonical capture, selective save, peek, extract, and batched_extract.
-
Resolve capture-related manifest entries against live TorchLens objects.
-
audit: Rewrite 02_layer_indexing.ipynb to actually exercise its declared coverage (
c7b8964) -
Demonstrate exact, integer, pass-qualified, module-key, suggestion, and missing-layer lookups.
-
Resolve indexing-related coverage markers against live TorchLens objects.
-
audit: Rewrite 03_save_load_basics.ipynb to actually exercise its declared coverage (
fc516ca) -
Replace boilerplate with a topic-specific workflow demo.\n- Resolve the notebook coverage markers against live TorchLens objects.
-
audit: Rewrite 05_visualization_basics.ipynb to actually exercise its declared coverage (
6f11e7f) -
Replace boilerplate with a topic-specific workflow demo.\n- Resolve the notebook coverage markers against live TorchLens objects.
-
audit: Rewrite 06_modellog_anatomy.ipynb to actually exercise its declared coverage (
1b4fcb1) -
Walk ModelLog identity, timing, graph, intervention, export, and private state clusters.
-
Redact high-entropy hash summaries in shared audit output.
-
audit: Rewrite 07_layerlog_anatomy.ipynb to actually exercise its declared coverage (
e27ac71) -
Walk LayerLog identity, tensor, gradient, graph, module, and pass aggregation clusters.
-
Resolve LayerLog coverage markers against a live aggregate layer record.
-
audit: Rewrite 08_layerpasslog_anatomy.ipynb to actually exercise its declared coverage (
e0894f7) -
Replace boilerplate with a topic-specific workflow demo.\n- Resolve the notebook coverage markers against live TorchLens objects.
-
audit: Rewrite 09_other_log_types.ipynb to actually exercise its declared coverage (
f3a4810) -
Replace boilerplate with a topic-specific workflow demo.\n- Resolve the notebook coverage markers against live TorchLens objects.
-
audit: Rewrite 10_bundle_anatomy.ipynb to actually exercise its declared coverage (
4503c7f) -
Replace boilerplate with a topic-specific workflow demo.\n- Resolve the notebook coverage markers against live TorchLens objects.
-
audit: Rewrite 15_visualization_options.ipynb to actually exercise its declared coverage (
95636ad) -
Demonstrate accepted vis_opt modes and current skip for unsupported vis_opt='all'.
-
Resolve options, viz, and visualization coverage markers against live namespaces.
-
audit: Rewrite 16_visualization_advanced.ipynb to actually exercise its declared coverage (
3fe7dd5) -
Demonstrate advanced visualization hooks without opening graph artifacts.
-
Resolve fastlog, callback, and visualization coverage markers against live objects.
-
audit: Rewrite 17_intervention_helpers.ipynb to actually exercise its declared coverage (
bbc4d84) -
Demonstrate selectors, activation helper specs, module splice, and backward helper specs.
-
Resolve intervention helper coverage markers against live objects.
-
audit: Rewrite 18_intervention_verbs.ipynb to actually exercise its declared coverage (
fe04555) -
Demonstrate sites, fork, rerun, and replay precondition handling.
-
Resolve intervention verb coverage markers against live objects.
-
audit: Rewrite 19_bundles_advanced.ipynb to actually exercise its declared coverage (
9d4fa66) -
Replace boilerplate with a topic-specific workflow demo.\n- Resolve the notebook coverage markers against live TorchLens objects.
-
audit: Rewrite 20_save_load_advanced.ipynb to actually exercise its declared coverage (
fbc92fe) -
Replace boilerplate with a topic-specific workflow demo.\n- Resolve the notebook coverage markers against live TorchLens objects.
-
audit: Rewrite 21_validation.ipynb to actually exercise its declared coverage (
998985f) -
Replace boilerplate with a topic-specific workflow demo.\n- Resolve the notebook coverage markers against live TorchLens objects.
-
audit: Rewrite 23_export_formats.ipynb to actually exercise its declared coverage (
6d0ffec) -
Replace boilerplate with a topic-specific workflow demo.\n- Resolve the notebook coverage markers against live TorchLens objects.
-
audit: Rewrite 24_bridges.ipynb to actually exercise its declared coverage (
44fb38c) -
Replace boilerplate with a topic-specific workflow demo.\n- Resolve the notebook coverage markers against live TorchLens objects.
-
audit: Rewrite 25_compat_truth_table.ipynb to actually exercise its declared coverage (
2f46e17) -
Demonstrate compat reporting and markdown output.
-
Resolve compat exports and deprecated alias markers against current TorchLens.
-
audit: Rewrite 26_perf_and_scaling.ipynb to actually exercise its declared coverage (
18344b5) -
Replace boilerplate with a topic-specific workflow demo.\n- Resolve the notebook coverage markers against live TorchLens objects.
-
audit: Rewrite 27_taps_and_observers.ipynb to actually exercise its declared coverage (
d8d797b) -
Replace boilerplate with a topic-specific workflow demo.\n- Resolve the notebook coverage markers against live TorchLens objects.
-
audit: Rewrite 28_sites_and_sweeps.ipynb to actually exercise its declared coverage (
ee79840) -
Replace boilerplate with a topic-specific workflow demo.\n- Resolve the notebook coverage markers against live TorchLens objects.
-
audit: Rewrite 29_edge_cases.ipynb to actually exercise its declared coverage (
8f06b39) -
Replace boilerplate with a topic-specific workflow demo.\n- Resolve the notebook coverage markers against live TorchLens objects.
-
backward: Rename _add_backward_hook to _add_tensor_backward_hook (
f4b7591) -
changelog: Consolidate backward-parity sprint (
d1b904a) -
changelog: Consolidate post-backward megasprint (
d3500f0) -
changelog: Note multi-output module semantics (
4273d0d) -
changelog: Record P1 alpha.3 finish + B1/B8 (
c93dadf) -
changelog: Record P2 validator hardening (
f064031) -
changelog: Record P3 combined visualization (
20730ba) -
changelog: Record P4 backward intervention (
c5dd8b8) -
changelog: Record P6 observer bundle polish (
ec9e485) -
demo: Regenerate hero bundle-diff SVG after viewBox fix (
18740de) -
finalize: Record post-backward ready state (
10fa1ba) -
finalize: Record post-backward T2 block (
67b4e08) -
finalize: Record post-backward T2 block (
0bb13d0) -
finalize: Record post-backward T2 block (
fe72464) -
golden: Regenerate M5 parity goldens after P1 multi-output eq-class fix (
02693a3)
Intentional baseline refresh after AD-X multi-output equivalence-class fix added output-index disambiguation for multi-output ops.
-
intervention: V1 maintenance sweep (8 items) (
da15b5f) -
io: Bump portable state schema; drop boundary-thread fields (
c8e84e8)
Phase 4 of module-containment-refactor sprint. Bumps IO_FORMAT_VERSION from 2 to 3. OpLog.setstate now silently drops legacy thread-replay boundary fields (_module_boundary_thread_output, _module_boundary_threads_inputs, and the legacy alias module_entry_exit_threads_inputs) when loading pre-v3 pickles. Emits exactly one DeprecationWarning per process via a load-once helper.
Adds tests/test_module_containment_save_load.py covering IO_FORMAT_VERSION, round-trip save/load module containment, legacy v2 pickle field dropping, and once-per-process warning behavior.
Public .tlspec schema (TLSPEC_SCHEMA_VERSION) is unchanged because the removed fields were private to OpLog pickle state, not part of the public unified manifest.
Refs: .research/module-containment-refactor_PLAN.md (Phase 4)
-
mlx: Record p6 completion (
b611fe7) -
polish: Close docstring, type-hint, and mypy-strict gaps across torchlens/ (
b1c37b8)
Pure plumbing pass with no behavior changes. Six parallel codex workers (high reasoning effort) touched disjoint subpackages; the orchestrator consolidated results and finished the residual handful of strict-mode errors at the root.
Coverage improvements (across torchlens/): - Public docstrings: 90% -> ~100% (81 added) - Public return types: 92% -> ~100% (110 added) - mypy --strict on package: 815 errors in 63 files -> 0 errors in 174 files
Worker partition (no file overlap): W1: capture/, decoration/, _state.py, multi_trace/, observers, experimental, _summary, _run_state
W2: data_classes/, _io/, io/, accessors/, errors/, types
W3: postprocess/, validation/, visualization/
W4: intervention/, fastlog/
W5: bridge/, compat/, report/, stats/, utils/, callbacks/
W6: init.py, user_funcs.py, options.py, appliance stubs (viewer/, paper/, notebook/, llm/, neuro/)
Verification gates (all pass): - mypy torchlens/ (lenient, configured): 0 errors in 174 files - mypy --strict torchlens/: 0 errors in 174 files - ruff check + format: pass - pytest tests/ -m smoke -x: 170 passed - len(torchlens.all) == 40
Each worker added narrow, justified type: ignore[] comments where torch internals or third-party libs (rich, wandb) are genuinely untyped. No blanket Any silencing.
-
rename: Apply glossary walkthrough v2 deltas to glossary (
7fe2493) -
rename: Final implementation summary (
2233fed) -
rename: Green smoke tests after rename (phase 6) (
c1ac957) -
rename-sprint: Add 5 follow-on todos + state file (
9fcd466) -
research: Record P3 implementation done (
077cc7d) -
state: Mark backward-parity sprint DONE (
5a5fd53) -
state: Mark post-backward megasprint DONE (
ffa73f6) -
todos: Add layer visualizers — tensor->image plugins per node (
8b13563)
Completes the trio with input transform / output transform: same plugin dispatch, same image= mechanism, same shared helpers, applied to intermediate nodes via the existing selector vocabulary (tl.func, tl.module, label lists, glob). Built-in library: heatmap, channel_grid, histogram, attention_heatmap, tsne/pca/umap/mds, violin. Eager render at trace time, cached PNG paths for cheap idempotent draw(). Compound payoff: whole graph reads as a visual tour through the model's processing.
-
todos: Add symmetric output_transform alongside input transform (
3470266) -
todos: Add transform= primitive + raw-input rendering as core feature (
3abae87)
Refines the HF-bridge text-input idea into a cleaner architecture: generic transform=callable kwarg on tl.trace, store the original alongside the trace, render it in the input node. Graphviz's image= attr and HTML-label support make per-modality rendering small (text / image / audio / multimodal each ~15 lines). HF bridge becomes a ~5-line wrapper instead of a 30-line ergonomic feature.
Total scope ~100 lines. Out of scope: autoregressive animation.
-
todos: Document -Log suffix drop rule for naming-sprint v3 (
6b8d4ed) -
todos: Document three supply mechanisms for slicing recipes (
da8cd21)
User-facing surface:
- auto-detect (default-on, strict class-identity match)
- explicit at trace time (stacks with auto unless auto_detect=False)
- post-hoc on the trace (no re-execution, supports loaded tlspecs)
Plus conflict resolution (explicit wins, warn on shadow), save/load contract (recipe names + version tags survive, recipe code does not), and rejected mechanisms (no global registry, no model mutation) with their reasoning.
- todos: Extend transform= entry with batched-input rendering (
5c560d4)
Default sampling policy shared across modalities (1: full, <=4: all, >4: first 4 + count badge). Per-modality summarization: PIL montage for images, HTML-label table for text, mini-waveform stack for audio. Heterogeneous/multimodal batches deferred. Batch-summarize helpers exposed as a reusable tl.viz.batch_summary module so future activation-grid / bundle visual work can reuse the same code.
- todos: Extend transform= entry with rerun reuse + builtin transforms (
e3126c6)
trace.rerun(new_user_input) auto-reapplies the stored transform so users don't have to keep tokenizer/preprocessor references around. Composes with fork/do/bundle for one-line prompt-swap experiments. Loaded traces (no stored transform) raise a clear error rather than silently failing.
Built-in transform library sketched: tl.transforms.hf_tokenize_for(model), tl.transforms.image_preprocess(...), etc. Same appliance pattern as recipes — small core registry, long tail in bridges. The HF text-input bridge collapses to a 3-line wrapper around the primitive.
-
todos: File deferred per-layer grad oracle (
ef905b8) -
todos: Keep_orphans=true flag for retaining island ops (
6471b13) -
todos: Note bundle_diff blue-white-red gradient is semantically wrong (
31116de) -
todos: Note combined forward+backward graph rendering (
e9c0311) -
todos: Note FX-style qualpath as documented secondary lookup key (
b57706d) -
todos: Note FX-style qualpath as op-level metadata field (
570fa9d) -
todos: Note HF bridge text-input ergonomics (
364024b) -
todos: Note layer/op-level wrappers for trace-level intervention verbs (
a9776c6) -
todos: Note multi-arm conditional traversal feature (
d0ab3c7) -
todos: Note tensor-container data structure support (
c25257a) -
todos: Note tensor-slicing recipes for attention-head sub-addressing (
c77f897) -
todos: Pencil pluck+extract and file naming-sprint v3 (
610b1bc) -
todos: Replace input-derived module attribution with call-stack snapshot (
878d2a0) -
todos: Unify op.outs API across containers and recipe slicing (
5eb7361)
Both features populate the same dict with named tensor leaves; they differ only in the source of names (container fields vs user/auto recipes) and storage semantics (independent tensors vs views into a parent). The container entry now owns the op.outs API design; the recipe entry is layered on top. Provenance flag distinguishes mutation semantics for the intervention API.
Also captured: HF auto-detect via strict class-identity matching, recipe versioning + applied_recipes provenance, hard constraint that recipes never synthesize new ops, convenience-feature framing for relaxed stability.
- viz: Clean up graph node labels (
fb4680d)
File list + LOC summary: - torchlens/visualization/_label_format.py: +318/-0, new label formatting helpers. - torchlens/visualization/rendering.py: +24/-269, wire helpers into default labels, selected fields, collapsed module labels, and remove unreachable old label helpers. - torchlens/visualization/modes.py: +2/-7, use tuple notation in vision IO rows. - torchlens/visualization/_elk_internal/layout.py: +3/-7, match collapsed-module ELK label shape/memory format. - tests/test_format_helpers.py: +46/-0, helper coverage. - tests/test_node_spec_api.py: +7/-7, updated default-label arg expectations. - tests/test_node_modes.py: +1/-1, updated vision shape expectation. - tests/test_overlays.py: +1/-1, updated field-picker shape expectation. - tests/test_param_log.py: +9/-14, updated param-label text expectations.
Tier-2 result: - pytest tests/ -m "not slow" -x --tb=short: 2256 passed, 29 skipped, 214 deselected, 2 xfailed.
Golden snapshots updated: - None. No tracked golden visual snapshot files changed; aesthetic PDFs/DOT outputs were regenerated under ignored tests/test_outputs for inspection only.
Visual confirmations: - Linear renders tuple shape/memory, in_features/out_features, middle-dot param list, and spaced module path. - Conv2d renders tuple shape/memory plus full in_channels/out_channels/kernel_size/stride/padding names. - LayerNorm renders normalized_shape=(d,) and params with tuple notation. - Embedding renders num_embeddings/embedding_dim and named weight shape. - Functional softmax renders no params or module path placeholder. - ReLU/no-param nodes omit the params line cleanly.
Judgment calls - Module kwargs are sourced from captured func_config because Trace rendering receives Layer/Op records, not live nn.Module instances; known module families are reordered to declaration-style names. - Frozen/trainable parameter text no longer uses bracket syntax; trainability remains represented by existing node colors.
Follow-ups - Full mypy still fails on pre-existing out-of-scope errors in intervention/bundle.py, data_classes/*, and backends/mlx/backend.py.
Documentation
- agents: Refresh CLAUDE.md/AGENTS.md and add state_of_torchlens.md (
fe0a304)
Refresh all 20 per-package CLAUDE.md and AGENTS.md files to describe the current 2.x state after the 17-phase 2.0 sprint (PR #175). Add a new .project-context/state_of_torchlens.md reference doc that gives a fresh agent (or human) a use-oriented map of the package: 40-name public API, subpackage layout, key concepts, what shipped vs what is stubbed, where to look for what.
No source code touched.
-
fastlog: Mark P3 halt complete (
d9794d7) -
glossary: Refresh for backward-parity + post-backward megasprint outcomes (
858757b)
Glossary at 1135 lines (was 1040). Adds ~60 entries from the two recent sprints: backward selectors (tl.grad_fn / tl.intervening / tl.grad_fn_label), backward helpers (bwd_hook / grad_zero / grad_scale / grad_clip / grad_noise / grad_clamp), tl.output, tl.halt / HaltSignal, observer direction kwarg, aggregate(target='grad', loss_fn=), Trace.draw_combined, Recording.log_backward, Recorder.log_backward, ModuleCallLog/ModuleLog .outputs + .output_structure, MultiOutputModuleError, LayerGradReport + 7 coverage buckets, MLX backend contract, scrub 3-tuple, append-state fields, full error catalog.
Also: companion CHANGES.md (193 lines) enumerates added/updated/removed/ uncertain entries + 3 inconsistencies flagged for upcoming rename sprint.
-
intervention: Clarify AppendBatchDependenceError (
28b69a3) -
notebook: Add auto-route demo section to HF tutorial (
adfac12) -
plan: V33 close round-32 BLOCK -- seed census + glob fix + line_exceptions schema (
bffc71a) -
plan: V34 close round-33 FINDINGS -- anchor-based citation + emit-seed semantics (
0208568) -
plan: V35 close round-34 Claude FINDINGS -- scope exemption + typo + Phase 0.13 cleanup (Codex READY preserved) (
b374738) -
plan: V36 close round-35 Codex HIGH -- impl tightens to spec; Phase 5.14 lifecycle checklist (
f564c26) -
polish: Close polish-sprint (5 phases shipped) (
5f5d583) -
research: Record P6 implementation completion (
bcfe094) -
research: Record P7C completion (
c44f2ba) -
sprint: Record backward-parity sprint SUMMARY (
31d20a8) -
sprint: Record P7 completion (
0d3efba) -
sprint: Record P7 T2 block (
cf3f585) -
sprint: Record post-backward megasprint SUMMARY (
f543566) -
sprint: Record post-backward P1 completion (
bf2e4d1) -
sprint: Record post-backward P2 completion (
6bc62b3) -
sprint: Update P7 T2 block (
c5c4534) -
super: Close super family sprint (
87821a9) -
todos: Close items from draw + step6 + intervention cleanup sprint (
83367c1) -
transforms: Close transforms-sprint (5 phases shipped) (
f120375)
Features
- backends: Mlx backend skeleton + smoke gate (M7) (
5ff8fdc)
Implements MLXBackend at torchlens/backends/mlx/ satisfying the CaptureBackend Protocol. Backend dispatch in trace() entry detects mlx.nn.Module vs torch.nn.Module and routes accordingly.
MLX backend characteristics (per plan §9 readiness checklist): - Lazy-safe metadata extraction (.shape, .dtype, .device without forcing mx.eval) - Hybrid materialization: deferred payloads with batched mx.eval at end-of-forward - External tensor label store (WeakValueDictionary) since MLX arrays have no _tl analog - supports_backward_capture = False (mx.grad is function transform, no autograd graph) - mx.compile excluded (wrappers only fire during initial tracing) - RNG snapshot/restore unsupported initially per AD-9
New smoke test at tests/test_mlx_backend_smoke.py captures a linear MLP via MLX and asserts structural Trace equivalence. Uses pytest.importorskip('mlx') so it skips cleanly when MLX is not installed.
[mlx] extra added to pyproject.toml. MLX is opt-in; the main torchlens import does not depend on mlx being present.
Plan: .research/capture-pipeline-unification_PLAN.md §9 + §14 AD-5 + AD-9
Milestone: M7 of M1-M8 capture-pipeline-unification sprint
-
backward: Capture-time AccumulateGrad attribution map (
6ec9109) -
bridge: Add Hugging Face text tracing bridge (
aee7dd6) -
bundle: Add label auto-routing dispatcher (
d0e7db0) -
bundle: Add structural agreement predicates (
10ca3f2)
Add Bundle-level structural consistency and shared/divergent predicates for op labels, layer labels, module addresses, parameter names, buffer names, and grad_fn labels.
-
capture: Add output_transform primitive (
0bf0004) -
capture: Add trace input transform primitive (
c466ffe) -
capture: Keep orphan ops with accessor (
07f15e1) -
data: Add module role hints and output structure capture (
3b9c0d3) -
demo: Add 10-minute notebook covering trace, intervene, backward, conditional, bundle (
2e27bc5) -
notebooks/torchlens_in_10_minutes.ipynb: 17-cell tour of the 5 flagship features.
-
notebooks/_demo_models.py: TinyBranchCNN + TinyMLP in a real .py so the AST
inspector can label conditional arms in the rendered graph. -
postprocess/finalization.py: materialize all AST-derived arms (then / elif_N / else)
in ConditionalAccessor, not only arms that produced runtime edges. Restores
symmetric num_arms / has_else across traces regardless of which arm fired;
ConditionalArm.fired still distinguishes runtime from static.
Conditional tests (96) and smoke tests (170) green.
-
ergonomics: Auto-coerce str/PIL/numpy/audio inputs via duck-typed model methods (
0bfeb79) -
errors: Add multi-output module error (
f6cfe75) -
facets: Implement facets framework + built-in recipes per LOCKED 2026-05-27 spec (
3ada85d)
Adds semantic FacetView registry, lazy per-record Op/Module facets, Trace facet finders, and built-in attention/norm/MLP/embedding recipes. Exposes tl.facets and updates API surface budget tests.
Files/LOC: 18 files changed, 1326 insertions, 6 deletions; new torchlens/semantic package is 912 LOC and new tests/semantic coverage is 350 LOC.
Tier-2: pytest tests/ -m "not slow" -x --tb=short passed: 2252 passed, 29 skipped, 214 deselected, 2 xfailed in 1277.38s.
Follow-ups
None identified in this implementation scope.
Judgment calls
Facet keys must be available without invoking recipes even though recipes expose values by returning dicts. Built-ins therefore declare facet names at registration; simple user recipes get best-effort literal return-dict key extraction without executing the recipe. TorchLens Module.cls stores the class, not the live instance, so recipes read scalar config values from Module.custom_attributes when needed.
-
fastlog: Add halt signal API (
adea348) -
fastlog: Add predicate-mode backward gradient capture (F5) (
f509310)
Adds Recording.log_backward(loss, *, keep_grad=...) and Recorder.log_backward(loss, *, keep_grad=...). Predicate-mode forward emission populates RecordingState.grad_fn_to_context (WeakKeyDictionary keyed on the live grad_fn object, not id(), to avoid id-reuse misjoin in multi-rollout).
Backward walker uses the join map to build GradRecordContext and distinguish paired vs intervening grad_fns.
RecordingOptions gains keep_grad / default_grad / grad_transform / save_raw_grads recording-level defaults; per-call log_backward(keep_grad=...) overrides. Static keep_grad=True with disk-only rejected preflight; callable predicates fall through to _resolve_storage dynamic rejection.
keep_op remains a callable predicate slot (selectors NOT accepted -- two-slider discipline). Example: keep_op=lambda ctx: ctx.label == "relu_1".
Tests: tests/test_fastlog_backward.py covers join, intervening, disk preflight, id reuse, gradient_postfunc alias.
Co-authored-by: Codex (gpt-5.5) noreply@openai.com
-
fastlog: Catch halt at recorder boundary (
8984fab) -
fastlog: Track halted recordings (
b43f3e8) -
glossary-v5: Implement locked field additions (
0eeea59) -
add Trace, Op, Module, and ModuleCall glossary v5 accessors
-
add CallTreeNode and dynamic call-tree derivations
-
make Module param_memory address-recursive and add recursive param accessors
-
capture ModuleCall forward arg templates and add smoke coverage
-
intervention: Add backward grad_fn selectors (
09a6fe0) -
intervention: Add grad clipping noise and clamp helpers (
c0b2d4c) -
intervention: Add layer and op shortcuts (
de2fe34) -
intervention: Dispatch backward hook plans from grad_fn callbacks (
f72660a) -
intervention.types: Rebuild containers from output specs (
e449190) -
mlx: Expand wrapper coverage (
3f99767) -
module-log: Expose structured multi-output module outputs (
d3fd652) -
observers: Direction kwarg for backward taps (
2a024c3) -
op: Add FX qualpath metadata (
72cec3c) -
options: Add gradient_postfunc silent alias for grad_transform (
4e0ca61)
Adds gradient_postfunc as a silent alias kwarg on SaveOptions / trace() that delegates to the existing grad_transform field. No deprecation warning. Honors AD-2 / synthesis-brief vocabulary parity (activation_postfunc / gradient_postfunc) without breaking existing grad_transform callers.
Co-authored-by: Codex (gpt-5.5) noreply@openai.com
-
selectors: Add output selector disambiguation (
e69932f) -
stats: Add aggregate(target='grad') with mandatory loss_fn (F6) (
de65ee1)
Extends torchlens.stats.aggregate() with target='grad' (parallel to existing target='activation' / target=None default). target='grad' REQUIRES loss_fn= kwarg; raises TypeError if missing.
Adds Norm streaming stat (O(1) memory) for gradient norms per layer.
Tests: tests/test_gradient_stats.py covers loss_fn requirement + basic norms.
Co-authored-by: Codex (gpt-5.5) noreply@openai.com
- super: Add remaining bundle super accessors (
005a72d)
Add SuperModule, SuperBuffer, SuperParam, SuperGradFn, SuperModuleCall, and SuperGradFnCall.
Expose bundle.modules, bundle.buffers, bundle.params, bundle.grad_fns, bundle.module_calls, and bundle.grad_fn_calls.
- trace: Auto-route tl.trace(model, image|multimodal_dict) with tiered preprocessing resolver (
c0f8557)
Adds PIL image auto-route through HF AutoImageProcessor/AutoProcessor, torchvision weights transforms, timm transforms, and the loud unverified ImageNet default fallback.
Adds multimodal dict auto-route for HF-style modality-key dicts gated by AutoProcessor resolution.
Trace.input_preprocessor is set for image, multimodal, and the existing text auto-route with structured preprocessing provenance.
Tier-2: pytest tests/ -m "not slow" -x --tb=short -> 2277 passed, 29 skipped, 221 deselected, 2 xfailed in 656.68s.
HF ViT: slow route test passed with hf_auto_image_processor provenance.
CLIP multimodal: slow dict route test passed with hf_auto_processor provenance.
torchvision ResNet: non-slow test passed with attached weights tier accepted, default fallback also allowed by test contract.
timm: slow default_cfg route test passed with timm provenance.
Unknown CNN: non-slow PIL route test passed with ImageNet default UserWarning and verified=False.
Audio, video, file-path, bytes, numpy, and tensor image auto-routing are explicitly out of scope.
-
validation: Add backward graph metadata invariants (
e25a0f4) -
validation: Add module output grad oracle (
b621d67) -
validation: Harden validate_backward_pass param-grad parity (
e89ee77) -
viz: Add layer visualizers (
81d3457) -
viz: Headless-quiet artifact open + multi-format bundle_diff (
7b2bb38)
Adds _open_file_quietly helper in _render_utils.py that silently skips viewer launch on headless Linux (no DISPLAY) and suppresses xdg-open stderr noise elsewhere. Wires _elk_internal/layout.py and rendering.py to use it.
Extends bundle_diff to accept any Graphviz-supported format (svg, pdf, png) instead of svg-only; accessibility metadata still embedded only for svg.
Pre-session WIP -- captured here so main is clean before next session.
-
viz: Render batched raw inputs (
ceffa08) -
viz: Render combined forward backward graph (
b369fab) -
viz: Restore frozen/trainable bracket marker on param shapes (
efa4c08)
Restore per-parameter shape rendering so trainable params keep tuple parentheses while frozen params swap only the outer shape brackets to square brackets, preserving the existing name, separator, and singleton trailing-comma formatting.
JMT wants the at-a-glance trainability cue preserved, especially for mixed-trainability cases like LoRA.
Tier-2: pytest tests/ -m "not slow" -x --tb=short passed (2260 passed, 29 skipped, 214 deselected, 2 xfailed).
Added tests for trainable parens, frozen square brackets, mixed trainable/frozen lists, anonymous frozen params, frozen singleton [3072,], and unknown trainability defaulting to parens.
Refactoring
- accessors: Extract generic Accessor[T] base for trace-side accessors (
fbf17d4)
Phase 1 of super-family-sprint. Pure refactor; no public API change.
Extracts shared lookup, containment, iteration, IPython completion, and "did you mean" infrastructure from the eight existing accessor classes (LayerAccessor, OpAccessor, ModuleAccessor, ModuleCallAccessor, ParamAccessor, BufferAccessor, GradFnAccessor, GradFnCallAccessor) into a single generic Accessor[T] base in torchlens/data_classes/_accessor_base.py.
Subclasses now override only type-specific lookup hooks (_resolve_pass_qualified, _resolve_substring, _suggest); universal getitem/contains/iter/len/dir/ipython_key_completions/ keys/values/items live in the base. PORTABLE_STATE_SPEC kept per subclass (different keep/drop policies per type).
Net: 688 insertions, 275 deletions across 8 files.
-
Smoke green (170/170). - No test or doc changes.
-
alpha3: Add LiveOpRecord capture projection (
a3a3d1a) -
alpha3: Drain LiveOpRecord in postprocess Step 0 (
c67954b) -
alpha3: Wire LiveOpRecord write sites (
421b8a9) -
autoroute: Extract input dispatch into priority-ordered registry (
cd888b7)
Replace the hardcoded tl.trace auto-routing branches with a decorator-populated input registry while preserving the existing text, multimodal, image, and fallback dispatch decisions. The Registry implementation is direction-agnostic and keyed only by diagnostic kind, with tl.autoroute.output reserved as a future output-routing namespace stub.
Files and LOC: torchlens/autoroute/_registry.py (+216), torchlens/autoroute/input/init.py (+27), torchlens/autoroute/_builtin_input.py (+52), torchlens/autoroute/output/init.py (+25), torchlens/autoroute/init.py (+8), torchlens/user_funcs.py (+62/-185), torchlens/init.py (+4), tests/test_autoroute_registry.py (+158). Total staged diff: 552 insertions, 185 deletions.
Tier-2 result: pytest tests/ -m "not slow" -x --tb=short passed: 2285 passed, 29 skipped, 221 deselected, 2 xfailed.
Existing tests were not modified; only tests/test_autoroute_registry.py was added.
- capture: Add shadow module-stack capture, gated by engine flag (
8258229)
Phase 1 of module-containment-refactor sprint. Adds Trace-owned _exhaustive_module_stack pushed/popped via the Phase 0a helper inside the wrap-forward decorator. Adds OpLog._modules_via_stack diagnostic field populated from snapshot at op-creation time. Adds CaptureOptions._module_containment_engine flag (thread_replay default, hook_stack, both). Adds post-Step-6 equality assertion (no-op for default engine). Adds 16-fixture phase-1 equality test confirming shadow stack matches thread-replay on baseline fixtures.
Documented divergence on raw_hook_replacement_synthetic: hook-stack gives the cleaner dynamic call-stack answer for ops downstream of a synthetic interventionreplacement. The replaced module's frame does not propagate into descendant ops' module stacks (which thread-replay does as a quirk of recursive ancestry inheritance). Fixture 14's baseline snapshot regenerated under hook-stack engine; phase-1 equality test marks the fixture as xfail with documented reason.
Removes the duplicate _mod_call_index increment in _handle_module_entry (helper is now the sole incrementer).
Refs: .research/module-containment-refactor_PLAN.md (Phase 1)
- capture: Collapse tl_* attributes into _tl namespace (
0e4509d)
Replace scattered tl__label_raw, tl_buffer_address, tl_buffer_parent, tl_param_barcode, tl_param_address, tl_call_index, tl_requires_grad, tl_address, tl_module_type, tl_forward_call_is_decorated, tl_is_decorated_function, tl_tensor_replacement_wrapped with a single typed _tl namespace per object.
Adds torchlens/_tl.py with TorchLensMeta base, TensorMeta, ParamMeta, ModuleMeta, DecorationTag dataclasses plus field-level helpers and batch hot-path readers.
Drops the double-underscore tl__label_raw footgun; sub-field names are now plain snake_case. Vestigial tl_tensor_label_raw removed.
Foreign _tl collisions detected via TorchLensMeta base class; raises TorchLensTLCollisionError to fail loudly.
New tests: test_tl_meta (helpers), test_tl_lifecycle (cleanup paths), test_no_legacy_tl_attrs (AST regression scan).
No public API change. No behavior change. Internal-only refactor.
- capture: Drop dead capture-only fields from Trace; field invariant test (M6) (
82f5ee7)
All transient capture state moved off Trace into postprocess-local TraceBuildState. Trace.dict now contains only user-facing fields (per Appendix B of plan) — no _raw_layer_dict, _layer_counter, _mod_entered, _module_build_data, _exhaustive_module_stack, etc.
OpEvent.materialized_log bridge field removed. Hot path still constructs OpLog at capture time and routes it through TraceBuildState (internal-only; never reaches the final Trace). Full IR-only hot-path simplification deferred to a code-quality follow-up; runtime behavior is unaffected.
Trace.orphan_logs: tuple[OpLog, ...] added per AD-7 (orphan access without _raw_layer_dict).
New tests/test_trace_field_invariant.py asserts the zero-scratch invariant: Trace.dict contains only user-facing fields after log_forward_pass returns.
Parity goldens regenerated at tests/golden/m5_pre_m6/ for M5 → M6 byte-equality. Old m2_pre_m3 goldens archived in place but no longer run.
Runtime gates green: 192 smoke, parity 4/4 against new goldens, intervention 203/1, fastlog 111, tier-2 non-slow 2081. Mypy reports 27 pre-existing errors in accessor typing unrelated to M6.
resnet50.pkl golden exceeds the 500KB threshold (765KB); commit uses SKIP=check-added-large-files. Same pre-existing repo-hygiene followup from M3 — todos.md tracks it.
Plan: .research/capture-pipeline-unification_PLAN.md §2 §5 §6 §14 AD-7 + Appendix B
Milestone: M6 of M1-M8 capture-pipeline-unification sprint
- capture: Hot path emits OpEvents; postprocess Step 0 materializes (M3) (
7c75820)
Hot path in backends/torch/ops.py now emits typed OpEvent instances into session.capture_events: CaptureEvents instead of writing directly to Trace._raw_layer_dict[label] = OpLog(...).
Adds torchlens/postprocess/_materialize.py (Step 0 prelude) that drains CaptureEvents into _raw_layer_dict + _raw_layer_labels_list before the existing 19 postprocess steps run.
Behavior is parity-gated against pre-M3 goldens for TinyMLP, ResNet-50, GPT-style small transformer, and LSTM. New parity gate at tests/test_capture_events_parity.py with goldens at tests/golden/m2_pre_m3/.
The 19 existing postprocess steps are unchanged at this milestone; they still read _raw_layer_dict. M6 will inline Step 0's work and drop _raw_layer_dict from final Trace.
Plan: .research/capture-pipeline-unification_PLAN.md §5 + §11 (parity)
Milestone: M3 of M1-M8 capture-pipeline-unification sprint
- capture: Introduce IR + CaptureBackend Protocol (M1) (
f56385e)
Establishes torchlens/ir/ with backend-agnostic event types (OpEvent, ModuleEvent, TensorRef, ParamRef, BackendSemantics, BackwardSidecar, CapturePolicy, FireResult, etc.) and torchlens/backends/_protocol.py with the CaptureBackend Protocol.
No backend implementations yet (M2). No postprocess changes (M3). No source-file moves beyond new packages. No all deltas.
Frozen+slots dataclasses on every hot-path type. CaptureEvents uses slots=False (allocated once per capture; weakref-friendly). Mapping[str, object] for kwargs-shaped fields per immutability discipline. No catchall extra/annotations sidecars on OpEvent.
Acceptance gates (the substantive ones): - ruff: clean on new files - mypy --follow-imports=skip torchlens/ir torchlens/backends: clean - pytest tests/test_ir_basic.py: 5 passed - pytest tests/ -m smoke: 192 passed
(Two gates I originally specified were ill-formed: full mypy follows into 49 pre-existing errors in unrelated files; the torch-free import check routed through torchlens/init.py which always imports torch. M1 code itself is torch-free in isolation.)
Plan: .research/capture-pipeline-unification_PLAN.md §2 + §3
Milestone: M1 of M1-M8 capture-pipeline-unification sprint
- capture: Move hot-path OpLog construction out of torch ops (
4afa79c)
backends/torch/ops.py no longer directly constructs OpLog or BufferLog; log object materialization is centralized in postprocess/_materialize.py via materialize_log_from_fields(). OpEvent IR fields continue to be populated directly from the existing torch metadata fields.
Focused gates green: zero OpLog( hits in backends/torch/ops.py, parity 4/4, field invariant 1, intervention 203/1, fastlog 19.
RESIDUAL: this is the safe cleanup slice. Capture still needs a live materialized log for mid-forward raw lookup, module filters, family-link updates, gradient hooks, and activation saving, so construction is centralized but not deferred exclusively until postprocess Step 0.
- capture: Relocate torch capture under backends/torch/ + Protocol adapter (M2) (
b9889d6)
Moves the eight torch-specific capture files into torchlens/backends/torch/: - decoration/torch_funcs.py → backends/torch/wrappers.py - decoration/model_prep.py → backends/torch/model_prep.py - decoration/_module_stack.py → backends/torch/module_stack.py - _tl.py → backends/torch/_tl.py - capture/source_tensors.py → backends/torch/sources.py - capture/output_tensors.py → backends/torch/ops.py - capture/tensor_tracking.py → backends/torch/tensor_tracking.py - capture/backward.py → backends/torch/backward.py
Adds backends/torch/backend.py implementing the CaptureBackend Protocol as an adapter over the relocated code. log_forward_pass now dispatches model prep, wrapping, and the per-op hot path through backend methods.
Behavior is identical: every hot-path call still writes Trace._raw_layer_dict exactly as today. M3 will replace those writes with OpEvent emission into CaptureEvents. No dual-path coexistence at this milestone — just relocation and Protocol adapter.
torchlens/decoration/ deleted entirely (no forwarding shim, per AD-10).
Plan: .research/capture-pipeline-unification_PLAN.md §1 + §3 + §4
Milestone: M2 of M1-M8 capture-pipeline-unification sprint
- capture: Switch to hook_stack engine; delete thread-replay code (
10942ba)
Phase 2 of module-containment-refactor sprint. Default _module_containment_engine flips to "hook_stack". OpLog.modules now populated from _module_stack.snapshot at op-creation time.
Deletes _module_boundary_thread_output, _module_boundary_threads_inputs, _update_tensor_modules, _get_input_module_info, _modules_via_stack shadow field, and the post-Step-6 equality assertion. Renames _handle_module_entry/_handle_module_exit to _record_module_entry_metadata/ _record_module_exit_metadata with reduced scope (counter increment moved to helper; thread-marker writes removed). Retains all metadata side effects per the plan's contract.
Removes constants.py LAYER_PASS_LOG_FIELD_ORDER entries for the deleted fields. Removes legacy aliases. Save/load migration shims for older pickles will be added in Phase 4.
Three baseline snapshots regenerated with documented behavioral improvements (drifts that fix limitations of thread-replay):
- recurrent_lstm_cell: newzeros_1_1 and newzeros_2_2 now correctly attribute to "cell:1" instead of empty modules. Internal factory ops (torch.zeros, torch.randn) called inside a forward now have proper module attribution. This is the orphan-factory-op fix the sprint was specifically designed to deliver. - dynamic_buffer_module: randn_1_1 now correctly attributes to "child:1". Same family as above. - raw_hook_replacement_synthetic: final output's output_of_modules narrows from ["relu", "proj"] to ["proj"]. Thread-replay's recursive ancestry inheritance no longer leaks dead-module markers through hook-replaced outputs. Same family as the previously documented fixture 14 linear_1_4 divergence (commit 8258229).
Refs: .research/module-containment-refactor_PLAN.md (Phase 2)
- decoration: Extract module-stack helper (
cee50a4)
Phase 0a of module-containment-refactor sprint. Adds torchlens/decoration/_module_stack.py with push_frame, pop_frame, current_address, snapshot. Refactors predicate-mode push/pop in model_prep.py to use the helper. Behavior-preserving; 170/170 smoke tests pass.
Refs: .research/module-containment-refactor_PLAN.md (Phase 0a)
- fastlog: Collapse to projection over CaptureEvents (M5) (
a1316ec)
Public tl.fastlog.* API preserved byte-identical. Internal duplicate capture implementation gutted; tl.fastlog.record now lowers to unified capture with postprocess=False, returning a Recording that lazily projects CaptureEvents.op_events into ActivationRecord / RecordingTrace views. No Trace is materialized for the fastlog path.
Deleted internal fastlog files (no behavior change to public users): - fastlog/_orchestrator.py - fastlog/_state.py - fastlog/_predicate.py - fastlog/_record_context.py Internal logic merged into capture/predicates.py + capture/projections.py.
Rewritten as thin shims: - fastlog/_record_one_shot.py - fastlog/_recorder.py
Storage and recovery files preserved (fastlog disk format unchanged per AD-1; fastlog.load continues to load existing artifacts via recover.py).
Preserved features verified: - train_mode=True still keeps saved tensors graph-connected (new test) - exception-in-predicate propagates as before (new test) - RecordingTrace.draw/timeline_html/repredicate all work over projected events - Memory parity: per-event cost is RecordContext-sized, not OpLog-sized
Plan: .research/capture-pipeline-unification_PLAN.md §7 + post-convergence patch
Milestone: M5 of M1-M8 capture-pipeline-unification sprint
- glossary-v5: Drop CallTreeNode, use ModuleCall as call-tree node directly (
ad4eefd)
Removed CallTreeNode exports, call_tree properties, and call_tree field-order entries.
Added direct ModuleCall/Module/Trace walking and call-tree display helpers, plus Trace root_call and max_call_depth convenience surfaces.
Updated glossary v5 tests and appended the locked design note to the deltas log.
- intervention: Live hooks emit FireResults on OpEvents; _pending_live_fire_records deleted (M4) (
5338d43)
Live intervention hook firing in backends/torch/ops.py + intervention/runtime.py now emits typed FireResult annotations on the OpEvent in CaptureEvents instead of writing to _state._pending_live_fire_records. The pending-fire-records module global is deleted entirely.
apply_live_hooks becomes a CaptureBackend Protocol method: apply_live_hooks(session, value, site: ReservedLabel) -> tuple[object, tuple[FireResult, ...]]
FireResult wraps the existing intervention.types.FireRecord per plan §6.
Fork no longer rebuilds _raw_layer_dict via the old path; it deep-copies the dict from the source Trace's final state. _raw_layer_dict still exists until M6.
replay.py's import of _set_saved_out_metadata from backends/torch/ops.py is relocated to data_classes/op_log.py to close the layering leak.
Public API: identical. tl.fork / attach_hooks / rerun / replay byte-equal. graph_shape_hash unchanged. M3 parity gate still green.
Plan: .research/capture-pipeline-unification_PLAN.md §6
Milestone: M4 of M1-M8 capture-pipeline-unification sprint
- io: Io_format_version 3 -> 4 + v3 loader normalizer + CHANGELOG (M8) (
af0faa1)
Bumps torchlens/_io/init.py:IO_FORMAT_VERSION from 3 to 4. Adds a small read-only normalizer at torchlens/_io/rehydrate.py:_normalize_legacy_trace_state that strips the 17 capture-only scratch fields dropped by M6 when loading v3 .tlspec bundles.
CHANGELOG.md documents the full M1-M8 unification sprint: - Unified capture pipeline (OpEvent + CaptureEvents IR) - Backend abstraction (torchlens.backends.{torch,mlx}) - torchlens.decoration namespace deleted - Zero capture-only scratch on Trace - PartialTrace.raw_layers shape change (rare-path) - Trace.orphan_logs added (AD-7) - Trace.has_backward_pass backend-conditional - io_format_version: 3 -> 4 with v3 loader normalizer - MLX backend (technical preview) - Public torchlens.all unchanged (40 names); package stays 2.x.x
New test tests/test_io_format_v3_load.py asserts a v3 golden bundle loads cleanly under v4 (normalizer strips legacy fields) and that save/load roundtrip preserves the zero-scratch invariant.
Plan: .research/capture-pipeline-unification_PLAN.md §M8 + Appendix B
Milestone: M8 (FINAL) of M1-M8 capture-pipeline-unification sprint
-
op-log: Eliminate mid-forward OpLog construction (
35fdaee) -
postprocess: Inline Step 6 module suffix at op-creation (
8dd33a6) -
postprocess: Simplify Step 6 to suffix-only mutation (
22b355f)
Phase 3 of module-containment-refactor sprint. Replaces _fix_modules_for_internal_tensors body with a suffix-only loop that appends the canonical module-path suffix to equivalence_class for every non-orphan layer. Deletes _fix_modules_for_single_internal_tensor and the _layers_where_internal_branches_merge_with_input plumbing (parent/child propagation is no longer needed because hook-stack snapshot at op-creation time is the source of truth for modules).
Step 6 still runs after Step 5; suffix logic operates on the post-conditional-attribution set.
Regenerates two baselines (recurrent_lstm_cell, dynamic_buffer_module): root-level factory ops (x.new_zeros, torch.randn) called in the OUTER forward BEFORE entering a submodule now correctly report modules=[] instead of inheriting the downstream module's identity. The Phase 2 baseline values ("cell:1", "child:1") were artifacts of the old Step 6 propagation logic that copied a downstream module's identity onto root-level factory ops; Phase 3 deletes that propagation. The literal hook-stack answer at op-creation time is empty modules, which is now what the snapshots reflect.
Refs: .research/module-containment-refactor_PLAN.md (Phase 3)
-
rename: Apply naming sprint v2 code surface (
a55ae03) -
rename: Drop deprecated conditional surface + redundant OpLog back-refs + finish scoped accessors (
3107330)
Round 2 of naming-impl-v2 cleanup. Drops 18 deprecated conditional fields (6 Trace-level, 12 Op/Layer-level) folding into the locked Conditional/ConditionalArm/ConditionalRoleRef data classes. Drops 3 redundant OpLog layer back-refs (layer_type_index, layer_trace_index, layer_type) — exact duplicates of op-scope fields per the inheritance pattern in postprocess/labeling.py. Promotes LayerLog.ops, ModuleLog.calls, GradFnLog.calls from dict-like to scoped Accessors.
Tests green: ruff/mypy/smoke 170/170/tier-2 2012 passed. Three feature demos clean (18_intervention_verbs, 19_bundles_advanced, 26_perf_and_scaling).
-
rename: Field renames per cluster locks (phase 2) (
55c22d1) -
rename: Method renames (phase 4) (
3541292) -
rename: New accessor classes + new fields (phase 3) (
dc73744) -
rename: Top-level vocab + class renames (phase 1) (
30179a8) -
rename: Update audit notebooks (
61e47d1) -
rename: Update notebooks (phase 5) (
cb425ec) -
rename-sprint: Accessor API rewrite + filter consistency (
657a329) -
rename-sprint: Bundle + Super[T] + Conditional changes (
9a55724) -
rename-sprint: Drop Log suffix from 8 data classes (
31e2d95) -
rename-sprint: Hard-remove deprecated features (
3f18608) -
rename-sprint: Module + ModuleCall field renames, additions, removals (
cf87490) -
Rename Module.is_train_mode to Module.training and add source-location triplets.
-
Rename ModuleCall layer/output storage to ops/input_ops/output_ops and add module resolver, identity, context, argument-count, and timing fields.
-
Convert Module hook registry metadata to list[HookInfo] with one HookInfo per hook.
-
Add Module and ModuleCall forward/func duration surfaces plus parameter tensor/count predicates.
-
Update module build, validation, visualization, pandas exports, snapshots, and state log.
-
rename-sprint: Op + Layer field renames, additions, removals (
1c1e335)
Renames: capture_index/trace_index/compute_index to raw_index/step_index/ordinal_index; func_call_stack to code_context; has_output_variations to has_out_variations; output_versions_per_child to out_versions_by_child; is_multi_output/is_part_of_iterable_output to in_multi_output; multi_output_role to multi_output_name; is_atomic_module_op/is_atomic_module_output to is_atomic_module; module_ops_entered to input_to_module_calls; module_entry_argnames to module_entry_arg_keys; detach_saved_tensors to detach_saved_activations; feeds_output to is_output_parent; save_tensor_data to save_activation; has_saved_outs to has_saved_activation; has_grad to has_saved_gradient; grad_memory/transformed_grad_memory to gradient_memory/transformed_gradient_memory; transformed_out_memory to transformed_activation_memory; save_grads to save_gradients; grad_transform/save_raw_grads/grads_to_save to gradient_transform/save_raw_gradients/gradients_to_save; grad_fn_id to grad_fn_object_id; grad_fn runtime
handle to grad_fn_handle; grad_fn_log TL record to grad_fn.
Additions: Op.ordinal_index, Layer.ordinal_index/raw_index, has_saved_gradient, grad_fn_handle runtime storage, grad_fn TL-record link, FX/index lookup propagation, Layer parity fields, and required FIELD_ORDER/portable/fork-policy updates.
Removals: dropped deprecated Op/Layer field names from active code paths with no compatibility alias properties; kept Trace/Layer num_ops where glossary remains canonical.
-
rename-sprint: Param + Buffer + GradFn + GradFnCall renames (
5eef3e8) -
rename-sprint: Tl.trace single-responsibility + pass/call vocab + total_ prefix (
12e159d)
Part A removes visualization kwargs and the log_forward_pass export from tl.trace, with draw/show wrappers owning rendering options.
Part B aligns op/layer iteration vocabulary on pass_index/num_passes while preserving callable call_index/num_calls for Module, ModuleCall, GradFn, and GradFnCall.
Part C applies total_/activation/autograd memory field names across Trace, Layer, Op, docs, tests, and notebook references.
Verification: ruff check . --fix; pytest tests/ -m smoke -x --tb=short.
- rename-sprint: Trace class field renames, additions, removals (
39b72e8)
Renames applied: _backend_name to backend; run_state/RunState to state/TraceState; io_format_version to tlspec_version; flops_by_type to flops_by_op_type; trace_annotations to annotations; input_id/model_id to input_object_id/model_object_id; input_shape_hash to input_signature_hash; ledger to state_history; train_mode to backward_ready; capture_full_args/capture_args_template to save_arg_templates; total_duration/duration surface to capture_duration; trace-level equivalent_ops to op_equivalence_classes; last_run_ctx to last_run; start_time/end_time to capture_start_time/capture_end_time; backward_root_grad_fn_id to backward_root_grad_fn_ids.
Additions applied: Trace.backend Literal field; Trace.code_context capture; Trace source-location class/init fields; Trace.num_modules; ops_with_params; saved_* accessors; compute_ops and compute_layers; module/grad-fn invocation accessors; boundary-type accessors; parameter tensor count parity; backward duration aggregate accessors; Trace.backward() rerun entry point.
Removals applied: unsupported_ops/unsupported_op collections; Trace.load classmethod; streaming_pass_logs, num_streamed_ops, and num_streamed_passes; stale serialized model-log/golden fixtures carrying removed field names.
Schema and tests: rolled tlspec naming to tlspec_version, removed obsolete legacy model-log backcompat cases, updated FIELD_ORDER/constants, Trace consumers, intervention/io/validation/postprocess call sites, docs, and tests. Verification: exact old-name grep clean; import probe passed; Trace dataclass field probe passed; ruff check . passed; pytest tests/ -m smoke -x --tb=short passed.
- rename-sprint: Unify name/address/class vocabulary across data classes (
f32a68e)
Renames Trace.name to trace_label, Trace.model_name to model_class_name/model_label, and Trace.model_class to model_class_qualname.
Renames Op.grad_fn_name to grad_fn_class_name, adds Op.func_qualname, Op.grad_fn_class_qualname, and Op.grad_fn_cls, and normalizes buffer-sourced Op/Buffer buffer_address to address with Buffer.name.
Renames GradFn.name to class_name, adds GradFn.class_qualname, and resolves GradFn.module_path by replacing the stored module-only value with class_qualname.
Renames FuncCallLocation.code_qualname to func_qualname.
Adds ModuleCall.name plus Param.module_name and Param.module_cls; verifies Module.name remains the bare address segment.
Updates field-order constants, portable state specs, tlspec/golden fixtures, repr/summary/export consumers, notebooks/docs field mentions, and tests.
- super: Consolidate multi-trace internals into intervention (
46d230e)
Move internal Super views, topology helpers, and metrics out of torchlens/multi_trace and into the intervention package layout for the super-family sprint.
- super: Extract generic bundle super base (
d25d9a2)
Move shared SuperOp/SuperLayer alignment state, labels, members, traces, coverage, and from_members construction into internal Super[T].
Keep tensor-specific stacking, aggregation, shape, and diff behavior in a _TensorBearing mixin in the same internal module so future tensor-bearing Super classes can reuse it without inheriting SuperOp semantics.
- super: Generalize bundle super accessors (
3232674)
Extract SuperAccessor[T, S] for shared Bundle-side lookup, sparse membership handling, label union iteration, and Super view construction. Keep SuperOpAccessor and SuperLayerAccessor focused on resolving OpLog and LayerLog objects from member traces.
Testing
- api: Update all size to 46 for backward-parity surface additions (
56ee78b)
P4 added 6 new public top-level names per AD-7 selector DSL parity + helper inventory: grad_clip, grad_noise, grad_clamp (helpers), grad_fn, intervening, grad_fn_label (backward selectors). Surface expansion intentional and documented in §1 of the backward-parity sprint plan.
Renames test_all_size_exactly_40 -> test_all_size_exactly_46 and updates TARGET_ALL ordering to match torchlens.all.
- api: Update all size to 47 for post-backward P1 output selector (
19fa2f4)
P1 multi-output module support added tl.output(...) selector for disambiguating which output of a multi-output module a hook targets (per AD-7 / F-Multi). Surface expansion intentional and documented in P1 of the post-backward megasprint plan.
-
api: Update backward parity surface invariants (
e31592e) -
capture: Add module-containment field-equality harness (16 fixtures) (
a539469)
Phase 0b of module-containment-refactor sprint. Adds 16 fixture builders spanning the edge-case taxonomy in the audit report; a JSON-stable snapshot generator covering Op/Layer/Module/ModuleCall fields plus equivalence-partition; a parametrized test runner. Generates baseline snapshots from current HEAD (pre-refactor); future phases will assert equality against these baselines.
Refs: .research/module-containment-refactor_PLAN.md (Phase 0b)
- capture: Codify ordering invariants and exception safety (
6dafa69)
Phase 5 of module-containment-refactor sprint (final phase). Adds five regression test files documenting and asserting the ordering invariants the refactor depends on:
- test_module_stack_identity_exhaustive.py: identity/pass-through synthesized ops see the identity module's stack frame. - test_module_stack_buffer_ordering.py: dynamic buffer registration ordering relative to stack push. - test_module_stack_exception_safety.py: stack unwinds on forward exception; subsequent capture works correctly. - test_module_stack_user_hook_ordering.py: user pre-hooks fire BEFORE wrap-forward push by design; logged-replacement op correctness. - test_backward_attribution_unchanged.py: backward op module attribution still works post-refactor.
Adds documentation in torchlens/decoration/CLAUDE.md, torchlens/postprocess/CLAUDE.md, and torchlens/CLAUDE.md describing the wrap-forward stack as the canonical module-containment mechanism and the down-scoped Step 6.
Adds .research/module-containment-refactor_SUMMARY.md with sprint recap, commit list, net code delta, and known residuals.
Marks sprint state DONE.
Refs: .research/module-containment-refactor_PLAN.md (Phase 5)
-
fastlog: Cover halt early abort (
c8d6aaa) -
intervention: Cover backward selector helper dispatch (
57a9e3d) -
io: Generate v3 .tlspec golden bundle; un-skip v3-load test (
606e40b)
Generates tests/golden/io_v3_sample.tlspec via an ephemeral git worktree at 83367c1 (pre-M1 main). Captures a 2-layer nn.Sequential MLP with torchlens.trace() and saves the result; the bundle's manifest.json records io_format_version=3.
tests/test_io_format_v3_load.py::test_load_v3_artifact_into_v4_runtime now runs without the missing-golden skip and verifies that the v3 bundle loads cleanly under the v4 runtime via the legacy normalizer.
Updates the detect-secrets baseline for the manifest's expected SHA-256 integrity hashes, matching existing tlspec fixture handling.
Closes the M8 deferred follow-up.
-
module: Cover multi-output module traces (
dfdc1a5) -
module: Refresh multi-output containment snapshots (
dc4a2da) -
observers: Cover backward taps and bundle viz (
f05a356) -
parity: Add pickle-diff helpers + tensor-equal + allow-list (
8cf73a0) -
parity: Shrink ResNet-50 golden inputs below pre-commit 500KB threshold (
0947830)
Reduces ResNet-50 parity input shape from (1,3,224,224) to (1,3,64,64). The legacy ResNet trace remains metadata-dominated, so the oversized resnet50 pickle payloads are stored gzip-compressed on disk and transparently decompressed by the parity test; the uncompressed pickle objects are still regenerated from the original anchor worktrees.
Both m2_pre_m3 and m5_pre_m6 goldens were regenerated at their original anchor commits via ephemeral git worktrees, then compressed below the repo's 500KB pre-commit large-file threshold.
No more SKIP=check-added-large-files bypass needed for these artifacts.
Resolves: tests/golden/m{2_pre_m3,5_pre_m6}/resnet50.pkl size cleanup.
- rename-sprint: Tier-2 green after all renames (
05ac920)
Renames-only: updated tests for grad_fn, total_autograd_memory, module_calls, num_calls, call_index, 0-based accessors, Trace.show DOT return, and current export/audit fields.
Removed-feature marks: skipped obsolete M5 pre-M6 pickle byte-equality schema and metadata-less v3 tlspec golden tests.
Type-drift fixes: aligned train-mode tensor validation, backward grad_fn selector dispatch, buffer call_index export, collapsed module rendering, ModuleCall JSON export, Trace backend field order, and backward invariant validation. Refreshed module-containment snapshots.
Detailed Changes: v2.17.0...v2.18.0