Skip to content

Switch between training and inference mode in one tree walk - #13374

Merged
danielhanchen merged 11 commits into
mainfrom
speed-up-mode-switch
Oct 12, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
speed-up-mode-switch

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 12, 2026 •

Copy link
Copy Markdown
Member

for_inference() and for_training() run on every GRPO step (generation, then the loss), and each walked the whole module tree four times:

  1. model.train() / model.eval()
  2. a model.modules() scan to set the gradient_checkpointing flags
  3. another inside arm_gradient_checkpointing, every call, even once armed
  4. a model.parameters() scan to drop stale _fast_lora casts

On a Qwen3-0.6B LoRA (2389 modules) one inference to training round trip took about 39 ms, almost all of it Python walking modules.

Changes

  • New switch_training_mode(model, training) in _utils.py does all four in one pass and returns the modules that carry a gradient_checkpointing flag. for_inference, for_training, resolve_training_gradient_checkpointing and arm_gradient_checkpointing (in both FastBaseModel and FastLlamaModel) reuse that list.
  • The training flag is written to __dict__ directly for classes that keep nn.Module.__setattr__ (it only routes Parameters, Modules and buffers, so a bool ends up there anyway); classes with their own __setattr__ get a normal assignment.
  • training is written flat only where nn.Module.train would do nothing else. A module whose train() differs (class or instance override, such as the frozen-norm partial get_peft_model installs on BatchNorm / InstanceNorm; PreTrainedModel with use_kernels on; its own children() / named_children()) gets its own train(mode) for its subtree, in nn.Module.train's preorder, once per path for shared modules and once per parent for aliased children. A root that differs, or overrides eval(), gets model.train() / model.eval().
  • for_training still sets the mode after the .model chain bookkeeping (defer=True), so a custom train() keeps the final say.
  • Any class with its own modules() / named_modules() / parameters() / named_parameters() / _named_members() sends the checkpointing and _fast_lora scans back to model.modules() / model.parameters(); so does a successful first arming, since the model's enabler can flag new layers.
  • hasattr(module, "gradient_checkpointing") is answered from the class, __dict__ and the parameter / buffer / module dicts for plain modules, and by real hasattr for classes with their own __getattr__ (PEFT wrappers delegate it), so the set of modules is the same as before.
  • Non-nn.Module models keep the old calls.

Evidence

Same state: after a fixed sequence of 10 switches (for_training, seeded _fast_lora, for_inference, for_training(False), for_training(True), model.eval(), ...) every module's training, gradient_checkpointing (value and whether the instance owns it), checkpoint function, _flag_for_generation, remaining _fast_lora casts, requires_grad and config use_cache are identical to main on 8 models: tiny Qwen3, Qwen3-0.6B (FastLanguageModel and FastModel), tiny Gemma3 (vision), tiny Qwen3-MoE, tiny Qwen3.5 (hybrid), tiny gpt-oss, tiny Qwen3 full finetune, plus tiny Gemma3 and tiny Qwen3 with a frozen BatchNorm (the per-instance train() partial path).

Speed, one for_inference() + for_training() round trip:

Model Modules main (ms) this PR (ms)
Qwen3-0.6B LoRA, FastLanguageModel 2389 41.44 10.46 4.0x
Qwen3-0.6B LoRA, FastModel 2389 33.95 10.09 3.4x
tiny Gemma3 (vision) 338 4.82 1.82 2.6x
tiny Qwen3.5 (hybrid) 302 3.49 1.16 3.0x
tiny gpt-oss 151 2.94 0.75 3.9x
tiny Qwen3-MoE 157 2.51 0.96 2.6x
tiny Qwen3 179 2.45 1.01 2.4x
tiny Qwen3 full finetune 37 0.57 0.24 2.4x

Sequential ABBA on Qwen3-0.6B, fresh process per arm, 4 runs each: main median 38.9 ms (35.5 to 88.5), this PR 10.2 ms (9.0 to 11.5): 3.8x, at least 3.1x worst case against best case. The host was oversubscribed (load average ~680 on 192 cores), so treat the absolute numbers as noisy and the ratios as the result.

Training: jobs/ab.py base vs head, NO_REGRESSION (per-step loss within tolerance, all base checks hold) on grpo tiny (10 steps), grpo gpt_oss_tiny, sft tiny (10 steps), vision_sft tiny and dpo tiny (3 runs; one step-time WARN on a shared GPU did not repeat).

Tests: tests/test_switch_training_mode.py checks the result against model.train() / eval() on real nn.Module trees: shared and aliased submodules, empty slots, a PEFT-style delegating wrapper, custom train() / eval() / __setattr__ / __getattribute__ / child traversal / enumeration, an instance train() partial, a real PreTrainedModel with and without use_kernels, and a drift guard on PreTrainedModel.train. It passes under transformers 4.57.6, 5.5.0 and 5.17.0. tests/test_for_training_generation_flag.py adds the ordering and arming cases for both for_training sites and still runs without torch. The related existing test files pass the same on main and here.

for_inference / for_training run on every GRPO step and each walked the whole
module tree four times: model.train() / eval(), a modules() scan for the
gradient_checkpointing flags, another inside arm_gradient_checkpointing, and a
parameters() scan for stale _fast_lora casts. On a Qwen3-0.6B LoRA (2389 modules)
one inference -> training round trip took 33-41 ms.

switch_training_mode does all of it in one pass and writes the training flag the
way nn.Module.__setattr__ would, falling back to the real model.train(mode) when a
class's train()/eval() does more than nn.Module's (PreTrainedModel with use_kernels
on, any custom override). The per-module state after every switch is identical to
before on 8 models (dense, MoE, hybrid, vision, gpt-oss, full finetune).
@danielhanchen danielhanchen self-assigned this Oct 12, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 12, 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 ⚠️ Failed 2026-10-12T07:42:26.432940Z 7550568 New commits
ℹ️ 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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…an set the flag

get_peft_model gives frozen running-stat norms a per-instance train() that keeps
them in eval (_unsloth_freeze_norm_running_stats); the flat write skipped it and
put them back in training on every for_training. A module whose train() differs
from nn.Module's (instance or class override, PreTrainedModel with kernels on, its
own child traversal) now gets its own train(mode) for its subtree, a root with its
own eval() gets model.eval(), and a data-descriptor training flag goes through
normal assignment.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: fa7c4d0bda

ℹ️ 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/_utils.py Outdated
for param in module._parameters.values():
if param is not None and "_fast_lora" in param.__dict__:
del param._fast_lora
stack.extend((child, covered) for child in module._modules.values())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Use custom child traversal for ancillary mode state

When a module overrides children() or named_children() to expose a dynamic child absent from _modules, the delegated train(mode) reaches that child, but this raw _modules walk neither returns its gradient_checkpointing flag nor clears _fast_lora; the old modules() and parameters() scans did both. Conversely, registered children intentionally hidden by the override are now processed. The fresh evidence beyond the earlier traversal fix is that delegation repairs mode recursion only, while the ancillary checkpoint/cache scan still follows the raw registry.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The old scans did not use children() either: Module.modules() is named_modules(), which iterates self._modules.items() directly, and parameters() goes through _named_members -> named_modules. So the raw _modules walk visits exactly the modules the removed modules() / parameters() scans did; only the train() recursion follows children(), and that part already delegates.

for_training wrote m.training = True along the .model chain and then called
model.train(), so a custom train() had the final say. switch_training_mode(...,
defer=True) collects first and applies the mode at the same point.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Mode writes and delegated train() calls now run in the order the recursive call
would run them, and a shared module reached through a plain parent is switched even
when another path to it runs through a custom train() that does not recurse. A
class with its own __getattribute__ is asked hasattr() like one with __getattr__.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

A child registered under two names in one parent is switched once, as
named_children() yields it. When a class overrides modules() / named_modules()
/ parameters() / named_parameters() / _named_members(), the checkpointing and
_fast_lora scans use model.modules() / model.parameters() as before.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 1fcb301c7e

ℹ️ 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/_utils.py
Comment on lines +8833 to +8834
train, plain_eval, gc, plain_setattr, walk = _mode_switch_class_info(type(module))
plain_walk = plain_walk and walk

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Honor per-instance child traversal overrides

When children or named_children is patched on an individual module instance, this class-only lookup still classifies its traversal as standard. nn.Module.train() resolves those methods through the instance, but the optimized path instead walks raw _modules, so children intentionally hidden or exposed by the override enter the wrong mode. Fresh evidence after the earlier traversal fix is that only an instance-level train override is checked below; instance-level traversal overrides still need to force delegation.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not changing this: children / named_children patched onto a single module instance is not a pattern any transformers, PEFT or Unsloth model uses, and covering every instance-level dunder would grow the guard without a reachable case. Class-level traversal overrides already delegate.

The enabler runs once, when a model was loaded without checkpointing, and a remote
one can flag layers the walk did not see. main's final modules() scan caught them;
rescan in that one case so they get the requested mode.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 7da57de05b

ℹ️ 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/_utils.py
Comment on lines +8889 to +8892
if defer:
return checkpointing, apply
apply()
return checkpointing

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Refresh checkpoint modules after delegated mode changes

When a custom train() adds or removes a registered child or creates a gradient_checkpointing attribute during the mode transition, apply() performs that mutation only after checkpointing was collected, but the caller receives the stale pre-transition list. The old final model.modules() scan occurred after model.train(), so, for example, for_training(..., use_gradient_checkpointing=False) previously disabled a flag created by the custom method whereas it now leaves that module enabled. Rescan after delegated mode calls, at least on the custom path, before returning the list.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not changing this: no supported model's train() adds children or gradient_checkpointing attributes while switching mode (the only per-instance train() Unsloth installs, the frozen-norm partial, does not), and rescanning after every delegated call would put the full modules() scan back on every switch for BatchNorm models, which is what this PR removes.

Comment thread unsloth/models/_utils.py
Comment on lines +8857 to +8860
if training:
for param in module._parameters.values():
if param is not None and "_fast_lora" in param.__dict__:
del param._fast_lora

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve caches excluded by custom parameter enumeration

When the root model overrides parameters() or related enumeration to omit some registered parameters, this raw walk deletes _fast_lora from those omitted parameters before plain_walk triggers the compatibility fallback below. The previous for param in model.parameters() scan respected that filtering, and the later fallback cannot restore an already-deleted cache; models that deliberately hide frozen or offloaded parameters therefore lose and rebuild their inference casts on every training transition. Defer the destructive deletion until enumeration compatibility is known, or collect candidates first and use only the custom enumeration when required.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not changing this: _fast_lora is only a dtype-cast copy that fast_linear_forward rebuilds from the live weight on next use, so dropping it for a parameter a custom parameters() hides cannot change any output; at worst one cast is redone. No supported model hides registered parameters from parameters() either.

transformers <= 5.5 re-kernelizes with kernelize() (on every train() while
use_kernels is set), later ones with set_use_kernels(True) on a mode change.
Compare against model.eval() on the installed version instead of a fixed count,
and allow kernelize in the drift guard.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

The original generation-flag tests use plain fakes; give the lifted code a stub
torch when it is not installed so they take the non-Module path as before. The
torch-based tests still skip there.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@danielhanchen
danielhanchen merged commit 0edcd85 into main Oct 12, 2026
@danielhanchen
danielhanchen deleted the speed-up-mode-switch branch October 12, 2026 10:34
danielhanchen added a commit that referenced this pull request Oct 12, 2026
…3445)

test_return_logits_survives_for_training lifts for_training into a stub namespace that predates #13374's switch_training_mode, so the missing name came back as None. Stub it and the three-argument resolve, and make that namespace raise NameError on any unstubbed name.
test_windows_torch_flavor_invariant: count #13396's causal-conv1d + mamba-ssm slot in the torch totals and its call in step 13.
test_token_count_prompt_parity: stub #13372's browser agent store with its defaults; the count and the request both call browserAgentToolsForTurn.
test_diffusion_mlx_engine_router (from #13379): read install_python_stack.py as UTF-8 for test_source_read_encoding.
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