Skip to content

Run Unsloth's patched forwards only on Unsloth-loaded models - #15101

Merged
danielhanchen merged 2 commits into
mainfrom
dh/s5-plain-reload
Oct 24, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
dh/s5-plain-reload

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

After FastLanguageModel.from_pretrained loads a Llama-family checkpoint, a plain transformers model loaded in the same process fails on forward or generate. This happens when someone evaluates a saved model with stock transformers in the same notebook:

  • AttributeError: 'LlamaForCausalLM' object has no attribute 'max_seq_length' on generate (bf16 plain load)
  • RuntimeError: expected mat1 and mat2 to have the same dtype on forward (fp32 plain load)
  • NotImplementedError: No operator found for memory_efficient_attention_forward (small head dims)

FastLlamaModel.pre_patch (unsloth/models/llama.py) assigns the fast forwards to the transformers classes themselves (LlamaAttention, LlamaDecoderLayer, LlamaModel, LlamaForCausalLM.forward, prepare_inputs_for_generation, _reorder_cache). Every later instance of those classes, including ones built by plain transformers, therefore runs Unsloth's paths without the state they assume (max_seq_length, which is set only on models Unsloth loaded, plus the dtype and attention setup).

Change

  • After pre_patch, each patched method that has a recorded original is wrapped in a dispatcher. The originals come from the existing _unsloth_pre_patch_originals record. A module marked _unsloth_fast_path runs the Unsloth method. Any other instance gets the method the class held before the first patch, or the inherited one when the class did not define it. functools.wraps keeps the signature and qualname, so Trainer column filtering and the loss-utils lookups are unchanged. __init__ is not wrapped.
  • FastLlamaModel.from_pretrained marks every module of the model it loaded (before post_patch), and get_peft_model marks it again at the point where it already sets max_seq_length on every module.
  • Plain models still build Unsloth's rotary module, because the modeling module's LlamaRotaryEmbedding is replaced. That module now answers the stock rotary_emb(x, position_ids) call with per-position cos/sin in x.dtype. Unsloth's own code only reads the cache through get_cached, so its paths are unchanged.
  • No global unpatching. restore_transformers_family still restores the originals for FastModel.

Tests

  • tests/test_plain_transformers_after_fast_language_model.py
    • CPU: patched methods run only on marked instances, a second patch round does not double-wrap, the signature is preserved, an inherited original falls back to the base class, and restore_transformers_family still restores.
    • GPU: Unsloth load, then a plain AutoModelForCausalLM load in the same process. Forward and generate match a fresh-process plain run. A second FastLanguageModel load gives bitwise equal logits.
    • Before the fix both tests fail (the GPU one with the max_seq_length AttributeError). After the fix both pass.
  • Manual matrix on a B200, Unsloth load followed by a plain load, with a fresh-process plain run as reference:
model base head logits max abs diff vs fresh plain generate
zephyr-smol_llama-100m (fp32) dtype RuntimeError 1.8e-5 equal
zephyr-smol_llama-100m (bf16) max_seq_length AttributeError on generate 0.0 equal
tiny-random-LlamaForCausalLM (fp32) xformers NotImplementedError 0.0 equal
tiny-LlamaForCausalLM-3.2 (llama3 rope) xformers NotImplementedError 1.2e-8 equal
tiny-Qwen2ForCausalLM-2.5 xformers NotImplementedError 2.0e-8 equal

The non-zero fp32 diffs come from the RoPE table being built on another device, not from a different path.

  • Unsloth training is unchanged. For zephyr-smol_llama-100m with LoRA, 3 AdamW steps give losses and a LoRA parameter hash that are bitwise equal between base and head. They stay bitwise equal on head when a plain model is loaded and run between the Unsloth load and training. Unsloth generate and a second FastLanguageModel load also match.
  • Existing related tests on head: test_fast_language_model_after_fast_model, test_plain_load_after_unsloth_rope, test_ppo_trainer_patches, test_decode_gqa_in_place, test_fused_ce_logit_scale, test_longrope_short_long_boundary, test_mistral_sliding_window_mask, test_rope_cache_current_device, test_rms_rope_compile, utils/test_rope_scaling_drift, utils/test_packing all pass, except test_rms_rope_compile::test_tiny_llama_causal_lm_compiles_fullgraph. That one fails identically on main (an xformers LowerTriangularMask graph break under fullgraph). The trace on head passes through the new dispatcher without a break.

Not covered

  • Only transformers 5.x and torch from this environment, on one B200. The transformers 4.57 floor was not run.
  • The other families that share the dispatcher (Mistral, Gemma, Gemma2, Cohere, Granite, Qwen3, MoE, Falcon-H1) were not run end to end. Qwen2 was.
  • A model loaded with plain transformers and then passed to FastLanguageModel.get_peft_model is marked there and keeps the fast path, as today. Calling a fast forward on such a model before get_peft_model now takes the stock path.
  • Plain models loaded after Unsloth now run the stock (slower) forwards. Before this change they ran the fast ones, for example a TRL reward model loaded by name.

A plain transformers model loaded after FastLanguageModel in the same process
picked up the class-level fast forwards and failed in forward or generate
(missing max_seq_length, xformers dispatch, dtype mismatch). The patched methods
now dispatch on a per-module marker set at load and fall back to the method the
class held before the first patch; the Unsloth rotary module answers a stock
(x, position_ids) call with per-position cos/sin.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 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-24T08:12:30.035696Z 69728d1 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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 69728d1db7

ℹ️ 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
danielhanchen merged commit 8c69315 into main Oct 24, 2026
@danielhanchen
danielhanchen deleted the dh/s5-plain-reload branch October 24, 2026 13:34
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