Repository navigation
fix: torch.compile support for TransformerBridge, including hooked runs - #2070
adityasingh-ops wants to merge 6 commits into
Conversation
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).
…sent since transformers 5.9)
jlarson4
left a comment
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
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?
Description
Follow-up to #2032: makes
TransformerBridgecompile cleanly withtorch.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
devwith him as author. (The PR of David's merged on Nov 27 was #2060, the shortformer change, so the compile commit wasn't ondevyet.) The only conflict was inblock.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:HookPoint.forwardnow also guards onlen(self.bwd_hooks), next to thefwd_hooksline.threading.Lockbreak on the first compiled call of a model booted by name. Booting by name setsoutput_attentions, so transformers installs its output-capturing hooks on the first forward under a lock that dynamo can't enter. A model passed throughhf_model=doesn't set it, which is why the existing tests didn't see this. The bridge now callsmaybe_install_capturing_hooksat boot (it exists since transformers 5.9, our minimum).run_with_cachebroke the graph at every attention layer.AttentionAutoConversionrecords revert state keyed byid(tensor), and dynamo can't traceid()on a tensor created inside the graph. It now skips recording that state while compiling. Nothing on the hook path reads it (BaseTensorConversion.revertreturns its input unchanged).BlockBridge/EmbeddingBridgereadSignature.parameterson every forward. That is a mappingproxy, and dynamo graph-breaks on it oncerun_with_cachehas written to its cache dict. The parameter names and the**kwargsflag are now cached next to the signature, filled inset_original_componentso the first compiled forward doesn't build them.Results
GPT-2,
bridge.original_model.compile()(inductor), Apple M1 with 8 GB, MPS, batch 8 × 128:run_with_cache(12hook_resid_post)run_with_cache(every hook)run_with_hooks(12 hooks)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
NormalizationBridgehook points._run_intermediate_hookusestorch.allcloseto detect in-place writes, which is data-dependent. Happy to look at that separately if you have a preferred approach.AttentionAutoConversion._conversion_stategrows by about two entries per forward and is never cleared (about 100 entries after 50run_with_cachecalls). I left that alone here to keep this to compile, but can send a small follow-up.Type of change
Checklist:
tests/unit -m "not slow": 8934 passed, 58 skipped, 3 xfailed.make formatanduv 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-endrun_with_cachetest (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.