Repository navigation
Switch between training and inference mode in one tree walk - #13374
Conversation
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).
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 security review |
…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.
|
@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: 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".
| 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()) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
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__.
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.
|
@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: 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".
| train, plain_eval, gc, plain_setattr, walk = _mode_switch_class_info(type(module)) | ||
| plain_walk = plain_walk and walk |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@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: 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".
| if defer: | ||
| return checkpointing, apply | ||
| apply() | ||
| return checkpointing |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| if training: | ||
| for param in module._parameters.values(): | ||
| if param is not None and "_fast_lora" in param.__dict__: | ||
| del param._fast_lora |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
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.
…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.
for_inference()andfor_training()run on every GRPO step (generation, then the loss), and each walked the whole module tree four times:model.train()/model.eval()model.modules()scan to set thegradient_checkpointingflagsarm_gradient_checkpointing, every call, even once armedmodel.parameters()scan to drop stale_fast_loracastsOn 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
switch_training_mode(model, training)in_utils.pydoes all four in one pass and returns the modules that carry agradient_checkpointingflag.for_inference,for_training,resolve_training_gradient_checkpointingandarm_gradient_checkpointing(in bothFastBaseModelandFastLlamaModel) reuse that list.trainingflag is written to__dict__directly for classes that keepnn.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.trainingis written flat only wherenn.Module.trainwould do nothing else. A module whosetrain()differs (class or instance override, such as the frozen-norm partialget_peft_modelinstalls on BatchNorm / InstanceNorm;PreTrainedModelwithuse_kernelson; its ownchildren()/named_children()) gets its owntrain(mode)for its subtree, innn.Module.train's preorder, once per path for shared modules and once per parent for aliased children. A root that differs, or overrideseval(), getsmodel.train()/model.eval().for_trainingstill sets the mode after the.modelchain bookkeeping (defer=True), so a customtrain()keeps the final say.modules()/named_modules()/parameters()/named_parameters()/_named_members()sends the checkpointing and_fast_lorascans back tomodel.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 realhasattrfor classes with their own__getattr__(PEFT wrappers delegate it), so the set of modules is the same as before.nn.Modulemodels 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'straining,gradient_checkpointing(value and whether the instance owns it), checkpoint function,_flag_for_generation, remaining_fast_loracasts,requires_gradand configuse_cacheare identical tomainon 8 models: tiny Qwen3, Qwen3-0.6B (FastLanguageModelandFastModel), 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-instancetrain()partial path).Speed, one
for_inference()+for_training()round trip:FastLanguageModelFastModelSequential 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.pybase 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.pychecks the result againstmodel.train()/eval()on realnn.Moduletrees: shared and aliased submodules, empty slots, a PEFT-style delegating wrapper, customtrain()/eval()/__setattr__/__getattribute__/ child traversal / enumeration, an instancetrain()partial, a realPreTrainedModelwith and withoutuse_kernels, and a drift guard onPreTrainedModel.train. It passes under transformers 4.57.6, 5.5.0 and 5.17.0.tests/test_for_training_generation_flag.pyadds the ordering and arming cases for bothfor_trainingsites and still runs without torch. The related existing test files pass the same onmainand here.