Skip to content

Block compile: let an enclosing torch.compile own wrapped decoder layers - #14704

Merged
danielhanchen merged 6 commits into
mainfrom
dh/s3-block-compile-outer
Oct 22, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
dh/s3-block-compile-outer

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

When a user wraps the model or a training step in their own torch.compile, the per-layer block
compile wrapper (installed on the FastLanguageModel LoRA path since #14398) is inlined into the
outer trace. It then calls torch._dynamo.maybe_mark_dynamic, which dynamo forbids while tracing,
and its own compiled callable. fullgraph=True always fails with
"Attempt to trace forbidden callable maybe_mark_dynamic"; with suppress_errors the outer graph
falls back and splits (5 graphs instead of 1 on a tiny Llama).

Fix: if torch.compiler.is_compiling(), the wrapper runs the stock forward so the outer graph
owns the layer. Outside an enclosing compile nothing changes (same graphs, same recompile count,
same loss on a tiny Llama).

Tests:

  • New tests/test_block_compile.py::test_outer_compile_owns_the_block (fullgraph, default,
    suppress_errors): fails on main, passes here. Checks grads vs the stock forward, no nested
    compiled call, no graph breaks, one graph.
  • Block compile suites on CPU: 60 passed, 4 skipped (CUDA only) on torch 2.13.0 and 2.14.1.

Inside an outer trace the block wrapper called maybe_mark_dynamic (forbidden
while tracing) and its own compiled callable. It now runs the stock forward
there so the outer graph inlines the layer. The standalone path is unchanged.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-22T16:01:40.045491Z 7d71fcb Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 369c99b0d2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/models/_block_compile.py Outdated
Comment on lines +689 to +690
if torch.compiler.is_compiling():
return original(self, hidden_states, *args, **kwargs)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep decode-aware forwards enabled under the outer trace

When a wrapped layer contains a forward decorated with torch_compiler_disable_unless_decode—notably Qwen3 MoE's sparse-MoE forward—this early return bypasses run(), the only path that sets UNSLOTH_DECODE_COMPILE (inline_flag[0]) to true. The decorator therefore selects its torch.compiler.disable branch while the enclosing Dynamo trace is active, so fullgraph=True still fails and the default mode graph-breaks and executes the MoE portion eagerly instead of allowing the enclosing compile to own the layer. The compiling branch needs to preserve the equivalent inline behavior before calling original.

Useful? React with 👍 / 👎.

Comment thread unsloth/models/_block_compile.py Outdated
Comment on lines +689 to +690
if torch.compiler.is_compiling():
return original(self, hidden_states, *args, **kwargs)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Prepare GDN layers before handing them to the outer trace

When a Qwen3.5 linear-attention layer's first invocation is through the enclosing compile, this return prevents _prepare_gdn from ever running. Besides installing the checked opaque GDN op, that preparation calls _route_sm_count, which exists because FLA's Triton device-property lookup is untraceable on ROCm; consequently an outer fullgraph=True forward/backward still fails there (and the default mode graph-breaks), while _GDN_OP remains uninitialized until an unrelated standalone call occurs. The GDN preparation must happen eagerly before the enclosing trace is allowed to enter original.

Useful? React with 👍 / 👎.

Comment thread unsloth/models/_block_compile.py Outdated
Comment on lines +689 to +690
if torch.compiler.is_compiling():
return original(self, hidden_states, *args, **kwargs)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Honor selective expert dequantization under outer compile

When the first call is made through an enclosing compile with UNSLOTH_MOE_SELECTIVE_DEQUANT=1 or UNSLOTH_MOE_DEQUANT_CHUNK_EXPERTS set, this return skips _experts_outside. The selective planner explicitly returns None while compiling because it needs host-read routing counts, so the expert remains inside the outer graph and the implementation dequantizes the entire 4-bit expert stack instead of only the requested experts/chunks; on the large MoE models these settings target, that can eliminate the intended memory bound and cause an OOM. The explicit selective-dequant paths still need to be moved outside capture before entering original.

Useful? React with 👍 / 👎.

pre-commit-ci Bot and others added 3 commits October 22, 2026 15:11
The outer-trace path now runs what run() does except the nested compiled
call and dynamic marking: UNSLOTH_DECODE_COMPILE and the block mode are set
around the stock forward, so decode-aware forwards (Qwen3-MoE sparse block)
are traced instead of breaking. Setup that needs eager code (moving
selective / chunked 4-bit experts out of the graph, the GDN self-check and
sm-count routing) runs through a torch.compiler.disable'd helper on the
first trace only; dense layers never take it. Standalone path unchanged.
@danielhanchen

Copy link
Copy Markdown
Member Author

Updated after review (6679e44): under an enclosing compile the wrapper now does everything its normal path does except the nested compiled call, mark_dynamic and the eager mask scan:

  • sets the same inline decode state, so decode-aware forwards such as the Qwen3-MoE sparse block stay inside the outer graph (fullgraph: 1 graph, 0 breaks; before, Skip calling torch.compiler.disable()d function / 7 breaks);
  • runs the one-time eager setup (_experts_outside, _prepare_gdn incl. _route_sm_count) through a torch.compiler.disabled helper the first time it is pending, so GDN layers get their opaque op and selective / chunked 4-bit experts stay outside the graph (one break on that first call only);
  • keeps the existing checks (eval, cache, kill switch, fp32, ZeRO-3, packed, off mode) ahead of the outer-trace branch.

The standalone path is unchanged (same loss, 1 graph, same call counts on tiny Llama and Qwen3-MoE). Block compile tests: 64 passed, 4 skipped (CUDA / fla) on torch 2.13 and 2.14.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 7d71fcb995

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

@danielhanchen
danielhanchen merged commit 7e12c32 into main Oct 22, 2026
@danielhanchen
danielhanchen deleted the dh/s3-block-compile-outer branch October 22, 2026 18:40
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.

1 participant