Skip to content

fix: torch.compile support for TransformerBridge, including hooked runs - #2070

Open
adityasingh-ops wants to merge 6 commits into
TransformerLensOrg:devfrom
adityasingh-ops:feat/compile-hooks
Open

adityasingh-ops wants to merge 6 commits into
TransformerLensOrg:devfrom
adityasingh-ops:feat/compile-hooks

Conversation

@adityasingh-ops

Copy link
Copy Markdown

Description

Follow-up to #2032: makes TransformerBridge compile cleanly with torch.compile, including the hooked path that ARENA cares about (run_with_cache / run_with_hooks).

The first commit is @davidquarel's compile work from his fork (davidquarel#7), rebased onto current dev with him as author. (The PR of David's merged on Nov 27 was #2060, the shortformer change, so the compile commit wasn't on dev yet.) The only conflict was in block.py, where #2002 added a per-target scale for the scaled contribution hooks; I kept his bound-method hook and pass the per-target scale through. The rest is on top of that:

  • Backward hooks added after compiling never fired. HookPoint.forward now also guards on len(self.bwd_hooks), next to the fwd_hooks line.
  • threading.Lock break on the first compiled call of a model booted by name. Booting by name sets output_attentions, so transformers installs its output-capturing hooks on the first forward under a lock that dynamo can't enter. A model passed through hf_model= doesn't set it, which is why the existing tests didn't see this. The bridge now calls maybe_install_capturing_hooks at boot (it exists since transformers 5.9, our minimum).
  • run_with_cache broke the graph at every attention layer. AttentionAutoConversion records revert state keyed by id(tensor), and dynamo can't trace id() on a tensor created inside the graph. It now skips recording that state while compiling. Nothing on the hook path reads it (BaseTensorConversion.revert returns its input unchanged).
  • BlockBridge / EmbeddingBridge read Signature.parameters on every forward. That is a mappingproxy, and dynamo graph-breaks on it once run_with_cache has written to its cache dict. The parameter names and the **kwargs flag are now cached next to the signature, filled in set_original_component so the first compiled forward doesn't build them.
  • Graph-break tests compare against the same model unbridged instead of asserting 0, so a break that a transformers release adds to the HF model itself can't fail our CI.

Results

GPT-2, bridge.original_model.compile() (inductor), Apple M1 with 8 GB, MPS, batch 8 × 128:

eager compiled speedup
forward 312 ms 203 ms 1.54×
run_with_cache (12 hook_resid_post) 312 ms 231 ms 1.35×
run_with_cache (every hook) 352 ms 404 ms 0.87× (0.48× before)
run_with_hooks (12 hooks) 326 ms 253 ms 1.29×

Graph breaks during run_with_cache (every hook) on a compiled GPT-2: 55 → 0. With 12 forward hooks attached there are 0 breaks.

Caching every hook point is still not faster on MPS even with a single graph. My guess is that it is dominated by writing out every intermediate activation, but I haven't confirmed that, and I'd expect CUDA numbers to look different.

Numerics: compiled outputs match eager exactly (0.0) with backend="eager" on CPU and MPS, hooks included. With inductor, hooked GPT-2 logits (max |logit| ≈ 290) differ by up to 3.8e-2 in float32 and 3.0e-11 in float64, with 100% top-1 agreement, so I read the difference as inductor's fused-kernel rounding rather than hooks behaving differently.

Not covered here

  • Low memory: compiling Qwen2-0.5B with inductor on the 8 GB M1 didn't finish within 3 hours (it looks like it was swapping), so I only have numbers for GPT-2 on MPS.
  • Qwen2/Llama-style models still graph-break when hooks are attached to NormalizationBridge hook points. _run_intermediate_hook uses torch.allclose to detect in-place writes, which is data-dependent. Happy to look at that separately if you have a preferred approach.
  • AttentionAutoConversion._conversion_state grows by about two entries per forward and is never cleared (about 100 entries after 50 run_with_cache calls). I left that alone here to keep this to compile, but can send a small follow-up.

Type of change

  • Bug fix (non-breaking change which fixes an issue)

Checklist:

  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • I have not rewritten tests relating to key interfaces which would affect backward compatibility

tests/unit -m "not slow": 8934 passed, 58 skipped, 3 xfailed. make format and uv run mypy . are clean. Each new test fails without its fix: 1 break vs 0 for the lock, 0 backward-hook calls, and the end-to-end run_with_cache test (run in a fresh interpreter, since jaxtyping's runtime checks under pytest add breaks of their own) fails if either the conversion or the parameter-read fix is reverted.

davidquarel and others added 6 commits November 29, 2026 23:37
Wire block capture hooks at setup (as bound methods), avoid untraceable
lookups in GeneralizedComponent/MLPBridge/MoE router, replace the T5 Q/K
per-call hooks with a capture slot, and have HookPoint guard on its hook
list so hooks added after compiling take effect.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…call stays one graph

Booting by name sets output_attentions, so transformers installs its output-capturing
hooks on the first forward under a threading.Lock, which torch.compile can't trace.

The graph-break tests now compare against the same model unbridged instead of
asserting zero, so a break added to the HF model itself can't fail our CI.
…mpile

AttentionAutoConversion recorded revert state keyed by id(tensor) at every
hook_pattern / hook_attn_scores call. torch.compile can't trace id() on a tensor
created inside the graph, so caching attention patterns split the compiled model
at every attention layer. The state is now skipped while compiling.
BlockBridge and EmbeddingBridge read Signature.parameters on every forward.
That is a mappingproxy, and torch.compile graph-breaks on it once run_with_cache
has written to its cache dict. The parameter names and the **kwargs flag are now
cached with the signature, filled when the original component is set.

Adds tests for both fixes; run_with_cache on a compiled GPT-2 now has 0 graph
breaks (55 before).

@jlarson4 jlarson4 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for putting this together @adityasingh-ops! Just a couple comments on some additional elements that may need to be taken into account. Let me know if you have any questions

hidden_states = self.hook_in(hidden_states)
in_module = getattr(self, "in", None) or getattr(self, "input", None)
# _modules lookup: dynamo's guard codegen chokes on getattr(self, "in").
in_module: Any = self._modules.get("in") or self._modules.get("input")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GatedMLPBridge's processed-weights forward still reads this submodule with getattr(self, "in", None) (gated_mlp.py:118). A Llama, Mistral or Gemma bridge in default compatibility mode therefore raises InternalTorchDynamoError on its first compiled call, where dev runs it. Can you carry the fix over and add a compatibility-mode case to the compile tests?

# torch.compile: building it there graph-breaks.
if callable(getattr(original_component, "forward", None)):
try:
self._original_forward_params()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reading the signature for every component here leaves each bridge holding its wrapped forward. Where that forward is a local closure, as on Falcon-Mamba's mixer, the bridge can no longer be pickled, which works on dev. Could this be limited to the bridges that read the cached parameters?

@jlarson4 jlarson4 linked an issue Nov 30, 2026 that may be closed by this pull request

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Question] Desire for support for SPDA attention + compilation?

3 participants