Repository navigation
Read the logit transforms from one place instead of four - #8997
danielhanchen merged 7 commits into
Conversation
The GRPO path and the causal LM forward each re-derived which field carries the model's logit scale: cohere multiplies by logit_scale, granite divides by logits_scaling, falcon_h1 multiplies by lm_head_multiplier. unsloth_zoo's device map planner now derives the same three values to size the head's card, so both read them from detect_logit_transforms and a new architecture is taught once rather than twice. Verified equivalent on cohere, granite (explicit and default logits_scaling), falcon_h1, llama and gemma2: identical softcapping and scaling in every case. Guarded so an older unsloth_zoo without the helper keeps the previous inline derivation. ImportError is the right scope here: it means the symbol is missing from an older zoo, and a broader catch would hide a genuinely broken install that the unguarded unsloth_zoo imports above would have failed on anyway.
inspect.getsource inlines the patched function bodies but not this file's imports, so detect_logit_transforms was never bound in the generated UnslothGRPOTrainer module and every GRPO run raised NameError on the first old_per_token_logps computation. Add the guarded import to RL_PRE_ITEMS alongside the other constants the inlined functions reference. Also read the transforms from the same place in grpo_trainer_compute_loss. The old and reference logps come from _get_per_token_logps_and_entropies and the gradient logps from here, so reading them two different ways makes the importance ratio compare two different policies. On Falcon-H1, whose lm_head_multiplier only the helper knows about, the ratio lands on the epsilon clip for every token.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5ecd1d8929
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if detect_logit_transforms is not None: | ||
| _transforms = detect_logit_transforms(self.config) | ||
| logit_softcapping = _transforms["logit_softcapping"] |
There was a problem hiding this comment.
Apply detected transforms before the fused loss returns
When labels are provided and UNSLOTH_RETURN_LOGITS is not enabled, the fused-loss path returns at line 1526 before this detection runs. That path still reads only the top-level softcap and special-cases exactly model_type == "falcon_h1", so nested transforms and variants recognized by detect_logit_transforms train with unscaled or uncapped logits even though inference uses the detected transforms. Move detection ahead of the fused branch and pass the same values into that loss path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reachable, so I am leaving it. The divergence is real in the abstract, but no family that can get to CausalLM_fast_forward can observe it.
loader.py assigns dispatch_model for exactly llama, mistral, gemma, gemma2, qwen2, qwen3 and qwen3_moe. FastFalconH1Model, FastCohereModel and FastGraniteModel are imported but their assignments are commented out (loader.py:914, 924, 927), so their pre_patch/post_patch never runs and CausalLM_fast_forward is never installed on those classes. That is also why the model_type == "falcon_h1" special-case at line 1488 is dead code today rather than evidence the path is live.
Comparing the fused-branch read against the helper for every family that does reach it:
| family | fused-path cap | helper (cap, scale) |
|---|---|---|
| llama | 0 | (0.0, 0.0) |
| mistral | 0 | (0.0, 0.0) |
| gemma | 0 | (0.0, 0.0) |
| gemma2 | 30.0 | (30.0, 0.0) |
| qwen2 | 0 | (0.0, 0.0) |
| qwen3 | 0 | (0.0, 0.0) |
| qwen3_moe | 0 | (0.0, 0.0) |
Zero divergences. None of these carry logit_scale, logits_scaling or lm_head_multiplier, none has a nested text config carrying one, and gemma2 keeps its soft cap on the top-level config where both readers already agree. glm4_moe, which also imports CausalLM_fast_forward, carries none of the five fields either.
So moving detection above the fused branch would be a pure no-op refactor of a hot path. I would rather leave the asymmetry visible than churn it with no behaviour change to justify it. If a granite, cohere or falcon_h1 dispatcher is re-enabled this becomes live and should be converted in the same change that re-enables it.
detect_logit_transforms only does getattr(x, "config", x), and a DDP or Accelerate wrapper never forwards .config, so passing the bare model made it read the wrapper and report no transforms at all. That is the same trap _unsloth_get_model_config was added to close in #5955, except silent this time: multi-GPU GRPO on Gemma 2 quietly lost its 30.0 softcapping, and Cohere and Granite lost their scaling, in both the reference and the gradient path. The existing guard test only grepped for the old string, which survives in the fallback branch, so it kept passing. Give it a behavioural case instead.
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
|
Note on the two sites this PR does not convert, since the original description got one of them wrong. The description claimed `llama.py:1438` and `mistral.py:335` read the attention cap. They do not. Both read `final_logit_softcapping`, the output-head cap, so they are genuine duplicates of the derivation this PR collapses, not a different concern. The actual attention-cap sites are `attn_logit_softcapping` in `kernels/flex_attention.py` and `models/gemma2.py`, and those are unrelated. I still left both alone, on reachability rather than on relevance:
The third duplicate, `rl_replacements.py:2737`, was a different story and is fixed in ddd4d5d's parent: that one is reachable and was actively wrong, since the old and reference logps came from the converted site while the gradient logps came from the unconverted one. |
The behavioural case asserted that the helper reports nothing for a bare DDP wrapper. That was true of the helper as it stood, but unsloth-zoo#1067 now unwraps .module and ._orig_mod itself, so the assertion would fail the moment that lands. Neither behaviour is wrong and this test has no business deciding which one the zoo picks. Assert the invariant that holds either way instead: the config the call sites resolve is the one the transforms come back from. Verified passing against both the current released helper and the #1067 version.
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
The loss recomputes log-probs from hidden states, so it has to reproduce what each family's forward does to its logits. A wrong factor there does not raise, it just shifts every log-prob and the importance ratio built from them. unsloth-zoo owns the field names; this owns the expected values, so a change in the helper's coverage arrives as a diff to read rather than a quiet numerics shift. Covers the four stable families plus the three the helper has just rebucketed, each recording what the path used to apply.
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
8fc26f0
into
glimmer-loader-quant-metadata-and-device-map
…-GPU device map (#8968) * Keep the real quantization skip list on save, and add an opt-in multi-GPU device map * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Resolve device_map = "unsloth" on the diffusion path, pin the vision planner revision Two leaks in the opt-in device map. FastModel dispatches diffusion models before FastBaseModel runs, so "unsloth" reached transformers unresolved, which turns an unknown device_map string into torch.device("unsloth") and raises. FastDiffusionModel now resolves it at the leaf, the same place llama.py and vision.py do, and _dispatch_diffusion forwards device_map_planner_kwargs, which is a named parameter and so never appeared in **kwargs. vision.py planned against the default branch while the load used _revision. A plan sized from a different revision either under-budgets or names modules the checkpoint does not have, and accelerate raises on the missing devices rather than warning. tests/test_unsloth_device_map_leaks.py pins that every leaf loader resolves before it loads and that each planner call gets the same ref as the weights. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Plan the device map for the quantization the load will really apply loader.py clears load_in_4bit and load_in_8bit whenever the caller passes a quantization_config, since transformers refuses both at once. The leaf loaders were handing those cleared flags to the planner, so a full-precision checkpoint about to be quantized got sized at bf16. The planner refuses to spill a bitsandbytes model to CPU and raises DeviceMapInfeasible rather than falling back, so a 70B QLoRA that fits on two cards failed outright. The skip list has to travel with them. On-the-fly quantization always keeps SKIP_QUANTIZATION_MODULES in compute dtype and transformers reads that as modules_to_not_convert, so planning lm_head and a whole vision_tower at 4bit understates the head device by GiBs. That is the one number the head-aware plan exists to get right. A pre-quantized checkpoint is unaffected: its own config.json carries the list. planner_quantization_kwargs in loader_utils.py builds the right inputs for both leaves. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Size the device map for the dtype and quant config the load will really use from_pretrained's dtype overrides whatever config.json declares, but the planner only ever saw the config, so any load that changed dtype was sized wrong by a factor of two. A float32 load of a bfloat16 checkpoint got an accepted map that OOMs while materializing, and the default bfloat16 load of a float32 checkpoint raised DeviceMapInfeasible on a load that fits. All three leaves now pass the dtype the load is given. In vision.py that means resolving the forced-float32 case before the plan rather than at the load, so both use one value. diffusion.py was still handing the planner the bare flags. Its BitsAndBytesConfig skips lm_head, embed_tokens, experts, self_conditioning and router, and transformers turns that into modules_to_not_convert, so every skipped module was budgeted at 4 bits while it materializes in compute dtype. For a MoE checkpoint the experts are most of the weights. The config is now built before the plan and the load reuses that same object. Passing the real config rather than a generic skip list matters for the 8bit branch, which deliberately has no skip list; injecting one there would over-size and could refuse a load that fits. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Do not plan a device map when the load builds a different model than the repo config The planner only receives model_name and rebuilds the repo's own config, so any load that overrides that config gets a map for a module tree it will not have. text_only is the reachable case. It swaps in the text sub-config and loads the decoder alone, so the plan describes the whole VLM and names model.language_model.layers.N while the load creates model.layers.N. On a Gemma 3 4B that is 444 of 445 weights arriving with no device, and transformers raises "doesn't have any device set" mid-load. Transformers 4.57 no longer pre-flights the map through accelerate's check_device_map, so there is no friendly error first. num_labels is the same failure from the other side: the load builds a sequence classification head whose score replaces the lm_head the plan named, and accelerate refuses the map for giving score.weight no device. Both now decline planning and fall back to sequential, matching how the resolver already handles vLLM, full finetuning and distributed launches. Passing the effective config to the planner is not an option: plan_device_map_for_pretrained takes only a repo name and builds the config itself. The class comparison is on model classes rather than auto classes, since AutoModelForVision2Seq and AutoModelForImageTextToText are distinct objects that resolve to the same VLM. It fails open: an unknown class vetoes nothing. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Decline planning on the optimized path too when num_labels loads a task head Last commit vetoed a class-divergent plan in vision.py, but loader.py only delegates to FastModel for 8bit, full finetuning and QAT. A num_labels load of a llama, mistral, gemma, gemma2, qwen2 or qwen3 repo stays on the optimized path, where the planner sized the repo's causal LM and the load then built AutoModelForSequenceClassification. That model has a score head and no lm_head, so accelerate's dispatch_model refuses the map with "does not give any device for the following parameters: score.weight". The veto does not fail open here, unlike the vision path. A num_labels load is a classification load by construction and the planner's own class resolution can never produce a sequence classification class, so an unknown class still declines. * Decline the unsloth device map in FastSentenceTransformer FastSentenceTransformer takes its own device_map and forwards it to FastModel, which resolves the sentinel on its own copy. But it also derives the SentenceTransformer device from the unresolved variable in three places, and those only normalize a dict, "auto" and "sequential", so "unsloth" reached SentenceTransformer(device = ...) and its self.to() raised: Expected one of cpu, cuda, ... device type at start of device string: unsloth. Adding the sentinel to those three lists would be worse than the crash. SentenceTransformer moves the assembled model onto one device, so a planned split map would be silently pulled back onto card 0. Declining once at the top matches how the resolver already handles vLLM, full finetuning and distributed launches. test_unsloth_device_map_leaks.py named this invariant already but only covered llama, vision and diffusion. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Make the SentenceTransformer decline survive UNSLOTH_AUTO_DEVICE_MAP The decline added in the previous commit read the raw argument, but FastModel runs requested_device_map unconditionally, and that upgrades exactly the "sequential" the SentenceTransformer path hands it. So with UNSLOTH_AUTO_DEVICE_MAP=1 the model was still planned across cards while st_device below read "sequential", and encode() then pulled the split model onto one card. That is the silent consolidation the previous commit set out to avoid, and it happened even when the caller explicitly asked for the sentinel and was explicitly declined. The decline now resolves the env var too, and the switch is pinned off for the load and restored in the same finally that already restores UNSLOTH_WARN_UNINITIALIZED. Only the training path was affected; the for_inference branch returns before this and never re-enters FastModel. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Tighten comments and docstrings in the device map planning path Shorten the explanatory comments added by this PR without dropping the reasons they record, and correct planner_model_class's docstring: it answers for the config it is given, which on both call sites is the user's config when one was supplied, while the planner rebuilds the repo config from model_name. * Set the auto-map pin inside the try that restores it The pin was assigned before the try block, but the distilbert and mpnet patch helpers run in between and can raise. That would leave UNSLOTH_AUTO_DEVICE_MAP=0 in the process environment with nothing to restore it, silently disabling the opt-in for every later load rather than just this one. * Read the logit transforms from one place instead of four (#8997) * Read the logit transforms from one place instead of four The GRPO path and the causal LM forward each re-derived which field carries the model's logit scale: cohere multiplies by logit_scale, granite divides by logits_scaling, falcon_h1 multiplies by lm_head_multiplier. unsloth_zoo's device map planner now derives the same three values to size the head's card, so both read them from detect_logit_transforms and a new architecture is taught once rather than twice. Verified equivalent on cohere, granite (explicit and default logits_scaling), falcon_h1, llama and gemma2: identical softcapping and scaling in every case. Guarded so an older unsloth_zoo without the helper keeps the previous inline derivation. ImportError is the right scope here: it means the symbol is missing from an older zoo, and a broader catch would hide a genuinely broken install that the unguarded unsloth_zoo imports above would have failed on anyway. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Give the generated GRPO module the transform helper it calls inspect.getsource inlines the patched function bodies but not this file's imports, so detect_logit_transforms was never bound in the generated UnslothGRPOTrainer module and every GRPO run raised NameError on the first old_per_token_logps computation. Add the guarded import to RL_PRE_ITEMS alongside the other constants the inlined functions reference. Also read the transforms from the same place in grpo_trainer_compute_loss. The old and reference logps come from _get_per_token_logps_and_entropies and the gradient logps from here, so reading them two different ways makes the importance ratio compare two different policies. On Falcon-H1, whose lm_head_multiplier only the helper knows about, the ratio lands on the epsilon clip for every token. * Hand the transform helper the unwrapped config, not the model detect_logit_transforms only does getattr(x, "config", x), and a DDP or Accelerate wrapper never forwards .config, so passing the bare model made it read the wrapper and report no transforms at all. That is the same trap _unsloth_get_model_config was added to close in #5955, except silent this time: multi-GPU GRPO on Gemma 2 quietly lost its 30.0 softcapping, and Cohere and Granite lost their scaling, in both the reference and the gradient path. The existing guard test only grepped for the old string, which survives in the fallback branch, so it kept passing. Give it a behavioural case instead. * Stop the DDP transform test from pinning the zoo's internals The behavioural case asserted that the helper reports nothing for a bare DDP wrapper. That was true of the helper as it stood, but unsloth-zoo#1067 now unwraps .module and ._orig_mod itself, so the assertion would fail the moment that lands. Neither behaviour is wrong and this test has no business deciding which one the zoo picks. Assert the invariant that holds either way instead: the config the call sites resolve is the one the transforms come back from. Verified passing against both the current released helper and the #1067 version. * Pin the per-family logit transforms the GRPO path applies The loss recomputes log-probs from hidden states, so it has to reproduce what each family's forward does to its logits. A wrong factor there does not raise, it just shifts every log-prob and the importance ratio built from them. unsloth-zoo owns the field names; this owns the expected values, so a change in the helper's coverage arrives as a diff to read rather than a quiet numerics shift. Covers the four stable families plus the three the helper has just rebucketed, each recording what the path used to apply. * Tighten the comments on the logit transform path --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Do not let a card that cannot report its memory fail the load resolve_unsloth_device_map read free memory outside the try that guards the plan, so a device that refuses to initialise took the whole load down instead of falling back to the placement the caller would have had anyway. mem_get_info opens a context on every visible card, and an ECC-fenced GPU, a MIG parent handle or one held in Exclusive_Process mode raises there. device_count() is wrapped for the same reason, one call earlier. planner_quantization_kwargs imported the shared skip list unguarded, and the leaf loaders build these arguments on every quantized load whether or not anything will be planned, so on an unsloth_zoo below our pin that import was a 4bit load turning into an ImportError. It now degrades to no skip list, which is only reached where the planner itself is going to decline. tests/test_unsloth_device_map_platform_matrix.py states the three properties that make the opt-in safe as the whole product rather than one path each: 4 hosts x 5 accelerators x 4 GPU counts x 14 placements returned untouched, the sentinel never escaping to transformers under any combination of launcher and flags, and the planner running exactly where a plan can apply. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Pin Studio's placement against the loader opt-in Studio never passes the planning sentinel, but an operator can set UNSLOTH_AUTO_DEVICE_MAP=1 process-wide, and Studio's "sequential" is not a default it forgot to change: get_device_map() returns it to mean one device. Two facts keep that safe, and neither was written down anywhere. Its multi-GPU answer is "balanced", which the opt-in does not touch, and its single-GPU answer is only reached inside a worker that already narrowed the visible devices to the selection, so the planner counts one GPU and declines. Asserted over the 7 hardware profiles already in this file (NVIDIA, ROCm, XPU, Apple with and without MLX, arm64 Linux, CPU) x 5 GPU selections x the opt-in unset, 0 and 1: whatever Studio decided is what the loader hands transformers. In this file rather than a new one because it runs in the isolated pytest invocation -- the spoofs here mutate hardware.py module globals. * Take three review findings on the opt-in device map max_memory is a named parameter of the planner, so a caller who put their own in device_map_planner_kwargs -- reserving room for another workload -- made the call raise TypeError: got multiple values for keyword argument 'max_memory'. The handler around it turned that into a silent "sequential", losing both the cap they asked for and the plan. Theirs is now taken per device and kept under what is actually free, read with accelerate's own parser so "10GiB" means here what it means at the load. A caller can reserve memory we cannot measure; they cannot conjure memory the card has not got, and planning above free is how a plan OOMs on dispatch. UNSLOTH_AUTO_DEVICE_MAP upgraded every "sequential", including one the caller typed out, because the default and an explicit request are the same string. The default now carries that distinction in its type: a str subclass that equals, formats, hashes and serialises as "sequential", so transformers and inspect.signature see exactly what they saw before, while the env var can tell which one nobody chose. A caller who names accelerate's greedy sequential fill keeps it. That also retires the process-wide pin in sentence_transformer.py. It existed only because the nested FastModel load could re-upgrade the "sequential" the decline had just produced; handing that call a plain str settles it locally. os.environ is shared, so the pin was visible to unrelated loads on other threads, and two overlapping sentence loads could restore it out of order. A legacy diffusion_gemma checkpoint loads only because _load_diffusion_config catches AutoConfig's unknown-model error and rewrites the type in memory. The planner takes a name, not a config, so it rebuilt the original and hit the same error, reported as a generic planning failure on a route this branch had just added support for. It now declines with that reason named. tests/test_unsloth_device_map_review_fixes.py covers all four; 14 of its 15 fail on the code as reviewed. The three ast harnesses learn the marker, and the two assertions that encoded "any sequential upgrades" now state the corrected rule. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Read the max_memory cap without needing accelerate importable The cross-platform run caught this: _as_bytes parsed the caller's budget through accelerate.utils.modeling.convert_file_size_to_int inside a try/except, so on a machine without accelerate installed every budget read as unparseable and the cap was dropped in silence, leaving the measured free memory in its place. That is the same silent loss the max_memory fix exists to close, and it runs while placement is still being decided, before anything has established that accelerate is present. Reproduce accelerate's spelling rules locally instead, and keep the copy in step with the original with a parametrized agreement test that skips where accelerate is not installed. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Honour the caller's device set, explicit ST maps, and the prequantized skip list Three from review: max_memory now replaces the measured budget rather than overlaying onto it. The keys of a mapping the caller wrote are the devices they will let the load use -- accelerate's _init_infer_auto_device_map takes devices = list(max_memory.keys()) and get_max_memory never widens a supplied mapping -- so {0: ..., 1: ...} on a four-GPU host was leaving the planner free to place weights on the two cards they had reserved for another workload. Devices we cannot measure (cpu, disk) survive. FastSentenceTransformer stripped the default's marker with str(), which also turned an explicit dict placement into the text "{'': 0, 'model': 1}". unmarked_device_map touches the marker and nothing else. llama.py declines to plan a prequantized bitsandbytes checkpoint of a mamba hybrid whose bundled skip list lacks the exclusions the load adds. merge_quantization_configs overlays loading attributes for GPTQ/AWQ/AutoRound/FbgemmFp8/CompressedTensors/Mxfp4 and never for bitsandbytes, so such a checkpoint is always sized by the list in its own config.json and no argument here can correct it; the mamba stacks are GiBs of error. The other unbundled entries reachable on this loader are MoE routers, which top out near 70 MiB on Qwen3-235B-A22B, inside the planner's 256 MiB safety margin. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Tighten the comments added by this PR Comment and docstring text only, AST-verified against HEAD. Also drops a stale copy of the max_memory rationale in loader_utils that the earlier fix left behind above its replacement. * Probe only the GPUs the caller left in max_memory mem_get_info was called for every visible device before the caller's device set was applied, so a card withheld for another workload got a CUDA context initialised on it anyway, and a withheld card that refuses (Exclusive_Process, ECC, MIG parent) dropped the whole plan to sequential over a device this load was never going to touch -- sequential being the placement that then OOMs. The device set is now read before probing. A set with fewer than two GPUs is not a multi-GPU plan, so it returns sequential without asking the planner or touching a card. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Tighten the probe-ordering comment Comment text only, AST-verified. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Several places in unsloth derive the same three values off the model config: the soft cap, and the two logit scales (multiply or divide, depending on the family). Each derivation knows about a different subset of the architectures:
rl_replacements.py:1721readsfinal_logit_softcapping,logit_scaleandlogits_scaling, but misses Falcon-H1'slm_head_multiplierand does not look atconfig.text_config.llama.py:1525special-casesgraniteandfalcon_h1bymodel_typestring, so a variant with a differentmodel_typebut the same field silently gets nothing.rl_replacements.py:2737derives the same values a third time, for the gradient path.unslothai/unsloth-zoo#1067addsdetect_logit_transforms, which the device map planner now uses to size the head's headroom. Since the planner and the loss must agree on which transforms are applied (the planner reserves for exactly the temporaries the loss allocates), they should be reading the same function rather than each deriving its own answer.What changed
rl_replacements.pyandllama.pycalldetect_logit_transformsbehind a guarded import:Every existing derivation is kept intact on the
Nonebranch, so an olderunsloth_zoobehaves exactly as it does today. Nothing here requires the zoo PR to have landed.llama.pydivides where the zoo helper reports a divide, sogranite's1 / logits_scalingis preserved without themodel_typecheck.Both GRPO sites pass
model_config, not the baremodel. The helper only doesgetattr(x, "config", x), and a DDP or Accelerate wrapper does not forward.config, so handing it the model would make it read the wrapper and report no transforms at all. That is the same trap_unsloth_get_model_configwas added to close in #5955.The generated GRPO trainer gets its own copy of the guarded import via
RL_PRE_ITEMS["grpo_trainer"].inspect.getsourceinlines the patched function bodies but not this file's imports, so without it the name is referenced inUnslothGRPOTrainer.pyand bound nowhere.This is currently a no-op for every user
Worth being explicit about, because it bounds the risk: no released
unsloth_zoothrough 2026.8.12 containsdetect_logit_transforms, andpyproject.tomlpinsunsloth_zoo>=2026.8.11. So on every install that exists today the guarded import fails and the fallback branch runs, which is the pre-PR code verbatim. Nothing changes for anyone untilunsloth-zoo#1067ships. Both directions of the version skew are safe: new unsloth with old zoo takes the fallback, and old unsloth with new zoo is unaffected because the zoo addition is purely additive.Verification
Equivalence-tested the collapsed
llama.pybranch against the old one across gemma2, gemma3, cohere, granite, falcon_h1 and llama configs: 0 mismatches. The new path additionally picks up Falcon-H1 through the config rather than themodel_typestring, and picks up nestedtext_configmodels the old path missed.Regenerated
unsloth_compiled_cache/UnslothGRPOTrainer.pyoff this branch and confirmed the guarded import lands at module level ahead of both call sites and resolves in the generated module's globals.get_text_config()is the only transformers API the new path leans on. Its signature is identical at 4.57.6, 5.0.0 and 5.15.0, and the only body difference between them sits inside a branch a no-arg call never reaches. It raisesValueErrorwhen several sub-config names are present, which the helper catches and degrades to "no transforms", i.e. the pre-PR answer. The changed lines contain no torch, vllm or CUDA API, no filesystem path and no shell, so there is no OS-specific or browser-facing surface here.Unrelated test noise
A full-suite run on this branch shows a cluster of 5 errors at the 18% mark, all of
tests/saving/test_gguf_export_and_inference.py. These are pre-existing and not from this PR:RuntimeError: Triton Error [CUDA]: no kernel image is available for execution on the device, raised from two module-scoped fixtures that train a tiny LoRA on GPU. It is GPU/Triton contention inside the long shared-GPU suite, not a logits or config problem.mainbefore this branch existed has the byte-identical progress line (..........EEEEE......... [ 18%]) and the same five node ids.Re-verified against the current unsloth-zoo#1067 helper
The zoo helper changed after this branch was written (
f78ed1f): it now unwraps.module/._orig_moditself, excludesaya_visionandcohere2_vision(whosetext_config.logit_scaleis never applied by their own head), and additionally detects xLSTM'soutput_logit_soft_capand T5Gemma's cap onconfig.decoder. Re-ran the per-family diff against that revision: still 0 divergences for every family that reachesCausalLM_fast_forward(llama, mistral, gemma, gemma2, qwen2, qwen3, qwen3_moe, glm4_moe).The call sites keep resolving the config themselves rather than leaning on the helper's new unwrapping. It is a no-op when the helper also unwraps, and it is still required on the fallback branch and against any already-released zoo, so the GRPO path stays correct on every version rather than only the newest.
The xLSTM and T5Gemma additions do change what the GRPO path sees for those two families, from "no cap" to the cap their forward actually applies. That is the intended direction: the recomputed log-probs have to mirror the model's own forward, and previously they did not.
Deliberate behaviour change: three families in the GRPO path
unsloth-zoo#1067now covers three families the old derivation got wrong. Because these call sites apply the transform rather than merely size for it, that is a numerics change and not just better coverage, so it is spelled out here with the exact factors.The
llama.pypath is unaffected: 0 divergences for every family that reachesCausalLM_fast_forward. Only the GRPO log-prob path changes, and only for these three.logits_scalingwas read as a divisor and is a multiplier (modeling_hyperclovax.py: "MuP: multiply logits by logits_scaling (cf. GraniteForCausalLM which divides)"). The path previously appliedlogits / sand now applieslogits * s, so for a config withlogits_scaling = sthe factor moves bys**2. Thats**2is the size of the bug being corrected, not of a regression being introduced.text_config.output_multiplier, about0.196on the released config. Its soft cap of20.0was already applied by both the old and new code.logits_scalingscales hidden states before the head, so applying it to logits was wrong.Order of operations was checked rather than assumed. The loss applies multiply, then divide, then soft cap.
modeling_muse_glimmer.py:1257doeslogits * output_multiplierand then the tanh cap, i.e.T * tanh(logits * mult / T), which is the same order. Granite and Cohere are unchanged.tests/python/test_grpo_logit_transform_families.pypins the expected triple per family, recording for these three what the path used to apply, so any further movement in the helper's coverage shows up as a failing assertion instead of a silent shift.Who this actually affects. Muse Glimmer GRPO users on transformers 5.15 will see log-probs change by the
0.196factor, which brings Unsloth into agreement with what transformers actually computes; hyperclovax users on 5.9+ get thes**2correction described above. This is reachable, not theoretical.muse_glimmeris absent from transformers atv5.5.0andv5.9.0(HTTP 404 for itsmodeling_*.py) and present atv5.15.0, and nothing stops a user from being on 5.15: thetransformers<=5.5.0bound appears in only 2 of the 173 extras, the core[project].dependenciestable does not constrain transformers at all, and there is no runtime ceiling check. The Glimmer GRPO notebook installs transformers 5.15 outright. So the affected user is a first-party, shipped one, and for them this is a fix rather than a hazard.Why it is not gated off anyway. Filtering at the call site would mean reintroducing a per-family allow-list, which is the construct this PR removes, and would recreate the same failure mode one level down: the next family added to the helper would be silently ignored by the loss. It would also put the loss and the planner back into disagreement about which transforms exist, which is the invariant this PR is for. Correcting a multiplier that was previously dropped, or applied in the wrong direction, is the right outcome for the users who reach it.
Base
Opened against
glimmer-loader-quant-metadata-and-device-map(#8968, converged and unmerged), which already touches thedevice_map_planner_kwargsplumbing in these files. Retarget tomainonce that merges.