Repository navigation
Make RMSNorm, RoPE and the input-embedding hook traceable by torch.compile - #12171
Conversation
…mpile Under torch.compile both now go through torch.library.triton_op ops (same Triton kernels, fresh outputs, register_autograd) instead of a compiler.disable graph break. The eager autograd Functions are unchanged; torch without triton_op and non-CUDA devices keep the old graph break.
Compiled (fullgraph=True) vs eager forward and backward as bytes for RMSNorm (Llama and Gemma, fp16 / bf16 / fp32, strided input) and RoPE (positions and rope indices, GQA, Q / K laid out as in the attention forward), 0 graph breaks, the eager path still being the autograd Functions, and a LoRA Llama whose decoder layers compile with fullgraph=True inside Unsloth checkpointing.
The head-group count used divmod, which a SymInt rejects under torch.compile(dynamic=True). The eager Fast_RoPE_Embedding backward rotated its gradient in place through a stride 0 view when it arrived expanded (e.g. from Q.sum()), giving wrong dQ / dK; it is made contiguous first (a no-op for the dense gradients attention produces). Tests for both, the compiled route rotates copies only, formatting.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
enable_input_require_grads makes the frozen embedding output require grad with output.requires_grad_(True), which torch.compile cannot trace. While compiling, the hook now returns x + -0.0 through a small autograd Function whose anchor requires grad: the same values (signed zeros included) and the same requires_grad, with no graph break. Eager keeps the in-place flag. Both the transformers 5 hook loop and the older single-embedding variant are patched. The forward passes read config.use_return_dict, deprecated in transformers 5 behind a logger.warning_once that breaks fullgraph compiles; config_return_dict reads return_dict (and keeps the torchscript tuple rule of transformers 4). With both, the causal LM forward (embedding, decoder stack, loss) of a LoRA Llama without gradient checkpointing compiles with fullgraph=True.
Inductor's FX graph cache keys a torch.library.triton_op call without the Triton source behind it, so with a warm cache an edited kernel is served as the previous kernel's compiled code. Unsloth turns the FX graph cache on, so an upgrade could keep running an older kernel under torch.compile. Add a hash of each kernel file to torch.compiler.config.cache_key_tag.
…ch 2.11 With RMSNorm and RoPE traceable, a whole causal LM compile on torch 2.7 traces more of the fast_lora autograd Functions, and Inductor before 2.11 miscompiles their backward (18 of 28 LoRA gradients differed from eager on a tiny Llama, 4 of 28 already on main). Same guard as the NF4 kernels PR, so the two merge cleanly in either order. The decoder and causal LM tests now compare every LoRA gradient with eager on every torch version.
|
@codex security review |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
Wrap both replacements with functools.wraps so inspect.getsource still returns transformers' implementation. On transformers 4.57.6 the single-embedding variant is now patched too, and unsloth-zoo's upstream drift check (test_upstream_source_patterns) read the replacement instead and failed.
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
On a T4 (sm75) Dynamo cannot trace the bf16 Triton launch inside the ops: it falls into triton's JIT run (a graph break) and, with dynamic shapes, raised InternalTorchDynamoError. Unsloth runs fp16 there, but a bf16 input now keeps the previous compiler.disable path. The bf16 byte checks skip where bf16 is not native, and a new test pins the routing.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a8ee054ad1
ℹ️ 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".
| # Dynamo cannot trace a bf16 Triton kernel on GPUs without native bf16 (pre-Ampere, e.g. T4), | ||
| # where Unsloth runs fp16 anyway; bf16 there keeps the graph break. | ||
| try: | ||
| return bool(torch.version.hip) or torch.cuda.is_bf16_supported(including_emulation = False) |
There was a problem hiding this comment.
Gate BF16 tracing on the tensor's CUDA device
On heterogeneous CUDA systems, this process-wide value reflects only the current device at import time, while fast_rms_layernorm and fast_rope_embedding later use it for tensors on any CUDA device. If import occurs with an Ampere GPU current but a compiled/model-parallel segment runs on a pre-Ampere GPU such as a T4, BF16 enters the traceable Triton path that the preceding comment says cannot be traced there, causing compilation to fail instead of using the intended graph-break fallback; the reverse device order also unnecessarily disables tracing on capable GPUs. Cache capability per device or check the input tensor's device before selecting the traced path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in d2f7150: bf16 tracing now needs native bf16 on every visible GPU, so a mixed machine keeps bf16 on the untraced path everywhere. Added a test with a faked sm80 + sm75 pair.
The flag read only the current device at import, so on a mixed machine a layer placed on a pre-Ampere GPU could still take the traced bf16 path.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
With two GPUs visible Unsloth may place the tiny model on cuda:1 (Kaggle 2x T4), and the compiled decoder layers differ from eager by one bf16 rounding step of the largest gradient on an RTX PRO 6000.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Resolve the conflict with unslothai#12171 in Fast_RoPE_Embedding.backward: keep main's _rope_rows launch and give it the private contiguous clone of dY.
…mpile (unslothai#12171) * Make fast_rms_layernorm and fast_rope_embedding traceable by torch.compile Under torch.compile both now go through torch.library.triton_op ops (same Triton kernels, fresh outputs, register_autograd) instead of a compiler.disable graph break. The eager autograd Functions are unchanged; torch without triton_op and non-CUDA devices keep the old graph break. * Tests: fast_rms_layernorm and fast_rope_embedding under torch.compile Compiled (fullgraph=True) vs eager forward and backward as bytes for RMSNorm (Llama and Gemma, fp16 / bf16 / fp32, strided input) and RoPE (positions and rope indices, GQA, Q / K laid out as in the attention forward), 0 graph breaks, the eager path still being the autograd Functions, and a LoRA Llama whose decoder layers compile with fullgraph=True inside Unsloth checkpointing. * RoPE: SymInt-safe group count, contiguous eager backward gradient The head-group count used divmod, which a SymInt rejects under torch.compile(dynamic=True). The eager Fast_RoPE_Embedding backward rotated its gradient in place through a stride 0 view when it arrived expanded (e.g. from Q.sum()), giving wrong dQ / dK; it is made contiguous first (a no-op for the dense gradients attention produces). Tests for both, the compiled route rotates copies only, formatting. * Remove the input-embedding hook and return_dict graph breaks enable_input_require_grads makes the frozen embedding output require grad with output.requires_grad_(True), which torch.compile cannot trace. While compiling, the hook now returns x + -0.0 through a small autograd Function whose anchor requires grad: the same values (signed zeros included) and the same requires_grad, with no graph break. Eager keeps the in-place flag. Both the transformers 5 hook loop and the older single-embedding variant are patched. The forward passes read config.use_return_dict, deprecated in transformers 5 behind a logger.warning_once that breaks fullgraph compiles; config_return_dict reads return_dict (and keeps the torchscript tuple rule of transformers 4). With both, the causal LM forward (embedding, decoder stack, loss) of a LoRA Llama without gradient checkpointing compiles with fullgraph=True. * RMSNorm, RoPE: key the torch.compile cache on the kernel source Inductor's FX graph cache keys a torch.library.triton_op call without the Triton source behind it, so with a warm cache an edited kernel is served as the previous kernel's compiled code. Unsloth turns the FX graph cache on, so an upgrade could keep running an older kernel under torch.compile. Add a hash of each kernel file to torch.compiler.config.cache_key_tag. * fast_lora: keep the LoRA Functions opaque to torch.compile before torch 2.11 With RMSNorm and RoPE traceable, a whole causal LM compile on torch 2.7 traces more of the fast_lora autograd Functions, and Inductor before 2.11 miscompiles their backward (18 of 28 LoRA gradients differed from eager on a tiny Llama, 4 of 28 already on main). Same guard as the NF4 kernels PR, so the two merge cleanly in either order. The decoder and causal LM tests now compare every LoRA gradient with eager on every torch version. * Shorten comments * Trim comments * enable_input_require_grads patch: keep transformers' source visible Wrap both replacements with functools.wraps so inspect.getsource still returns transformers' implementation. On transformers 4.57.6 the single-embedding variant is now patched too, and unsloth-zoo's upstream drift check (test_upstream_source_patterns) read the replacement instead and failed. * RMSNorm, RoPE: keep bf16 untraced on GPUs without native bf16 On a T4 (sm75) Dynamo cannot trace the bf16 Triton launch inside the ops: it falls into triton's JIT run (a graph break) and, with dynamic shapes, raised InternalTorchDynamoError. Unsloth runs fp16 there, but a bf16 input now keeps the previous compiler.disable path. The bf16 byte checks skip where bf16 is not native, and a new test pins the routing. * RMSNorm, RoPE: require native bf16 on every visible GPU to trace bf16 The flag read only the current device at import, so on a mixed machine a layer placed on a pre-Ampere GPU could still take the traced bf16 path. * Trim comments * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Compile tests: inputs on the model's device, two bf16 steps of tolerance With two GPUs visible Unsloth may place the tiny model on cuda:1 (Kaggle 2x T4), and the compiled decoder layers differ from eager by one bf16 rounding step of the largest gradient on an RTX PRO 6000. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Summary
fast_rms_layernormandfast_rope_embeddingwere both@torch.compiler.disable("does not torch.compile properly; reason unknown"), so every Llama style decoder layer had graph breaks around its two RMSNorms and its RoPE, andfullgraph=Trueon a decoder layer failed.The reason is in-place writes that a traced graph may not make:
This PR keeps the Triton kernels and adds a traced route next to the eager one:
Fast_RMS_LayernormandFast_RoPE_Embedding(_QK)run as before, including the in-place reuse and the multi-GPU stream sync; outputs and gradients are byte-identical to main.torch.compileon CUDA withtorch.library.triton_op/wrap_triton(torch 2.6+):unsloth::rms_layernorm,unsloth::rms_layernorm_backward,unsloth::rope_embeddingandunsloth::rope_embedding_qkops withregister_autograd. They launch the same kernels with the same launch settings, but on fresh buffers (a copy of dY, a clone of Q / K), so nothing the graph owns is mutated. No device guard or stream sync inside the graph.compiler.disablebehaviour (a graph break), so the Intel Arc DG2 RMSNorm workaround infalcon_h1.pyis unaffected.torch.compiler.config.cache_key_tag: Inductor's FX graph cache keys atriton_opcall without the Triton source behind it, so a warm cache would otherwise keep serving an older kernel after an upgrade.Two more graph breaks are removed:
enable_input_require_gradsmakes the frozen embedding output require grad withoutput.requires_grad_(True), which Dynamo cannot trace. While compiling, the hook now returnsx + -0.0through a small autograd Function whose anchor requires grad: the same values (signed zeros included) and the samerequires_grad, without a break. Eager keeps the in-place flag. Both the transformers 5 hook loop and the older single-embedding variant are patched, throughfunctools.wrapssoinspect.getsourcestill shows transformers' implementation (unsloth-zoo's upstream drift checks read it).config.use_return_dict, which transformers 5 deprecated behind alogger.warning_once; that breaksfullgraph=Truecompiles.config_return_dictreadsreturn_dictinstead (keeping the torchscript tuple rule of transformers 4).With these, the causal LM forward of a LoRA Llama without gradient checkpointing (embedding, decoder stack and loss) compiles with
fullgraph=Trueon torch 2.11+ (on 2.10 one break is left inside the unsloth_zoo fused loss, oninspect.signature).Two fixes found while testing:
divmod, which a SymInt rejects undertorch.compile(dynamic=True).Fast_RoPE_Embeddingbackward rotated an expanded (stride 0) gradient in place through its view, giving wrong dQ / dK for losses likeQ.sum(). It now makes the gradient contiguous first, which is a no-op for the dense gradients attention produces.Tests
New
tests/test_rms_rope_compile.py:fullgraph=True) vs eager forward and backward, compared as bytes: RMSNorm (Llama and Gemma, fp16 / bf16 / fp32, 2D, 3D and strided input) and RoPE (positions and TRL style int32 rope indices, GQA and single KV head, Q / K laid out as inLlamaAttention_fast_forward).dynamic=Trueover several lengths, expanded gradients eager and compiled.requires_grad_()or logging breaks (fullgraph=Truefrom torch 2.11).fullgraph=True; loss and every LoRA gradient match eager on every torch version.The 2.7.1 failure (
test_omni_auto_class_resolution.py::test_a_getter_that_cannot_take_zero_arguments_is_skipped) fails the same way on main with transformers 4.57.6.On main, 31 of the compile tests fail with
Skip calling torch.compiler.disable()d function; thedynamic=True, expanded gradient, embedding hook and causal LM tests each fail with their fix reverted (the return_dict one on transformers 5).LoRA gradients before torch 2.11
Inductor before torch 2.11 miscompiles the traced backward of the
fast_loraautograd Functions: a whole-model compile of a tiny LoRA Llama on torch 2.7.1 already gave 4 of 28 LoRA gradients different from eager on main, and 18 of 28 once the norm and rotary breaks were gone, because more of those Functions got traced.fast_loranow keeps them opaque totorch.compilebefore torch 2.11 (the same guard as #12113, byte-identical, so the two merge cleanly in either order): 0 of 28 differ on torch 2.6, 2.7 and 2.10, and the decoder and causal LM tests compare every LoRA gradient with eager on every version.torch 2.6.0 (Triton 3.2, transformers 4.57.6, TRL 0.22.2, PEFT 0.18.0, Colab L4):
tests/test_rms_rope_compile.py44 passed.On torch 2.11 the causal LM test needs unsloth-zoo#1482 (already merged): without it the traced fused loss returns zero LoRA gradients.
Whole-model compile on dedicated GPUs
Colab, torch 2.11, Llama 3.2 1B / 3.1 8B bnb-4bit QLoRA, no gradient checkpointing, median ms per step over two runs (grad norm checked non-zero on every step):
Eager step time is unchanged (within 0.3%). The first compiled step takes longer with both PRs (the graph is larger).
Graph breaks and speed (local B200)
Local B200, torch 2.13, QLoRA r=16 on all linear layers, batch 2. Base is #12113 merged with main (so the NF4 dequant no longer breaks graphs), head is the same plus this PR. Speed is each arm against its own eager run in the same round, over two rounds with the arm order swapped; the host was shared and heavily loaded, so absolute step times moved by up to 40% between rounds and only the ratios are reported.
torch.compileper decoder layer, Unsloth checkpointingWith the per decoder layer compile, 8B stayed within noise of eager (the matmuls dominate). The two breaks left in the whole stack case in these runs were the embedding hook's
requires_grad_(), removed by the last commit. Losses of the compiled runs match eager within 1.2e-4 relative.Eager training is unchanged by construction (same kernels, byte-identical outputs and gradients;
fast_rms_layernormno longer goes through acompiler.disablewrapper,fast_rope_embeddinggains one Python call). The eager SFT A/B on the loaded host could not resolve step time differences below about 15%; training losses were identical until the host's usual run to run nondeterminism set in, and peak memory was 1697 MiB on both.Not covered
device.typeiscuda) and Intel XPU hardware were not run.PeftModel_fast_forwardstays@torch._disable_dynamo(lifting it would make any compiled region that calls the model, such as compiled trainer helpers, trace the whole model; the only other break behind it in these runs is gradient checkpointing), and Unsloth gradient checkpointing goes throughtorch.utils.checkpoint, which Dynamo does not trace.