Skip to content

Fix GRPO logit scaling when model is wrapped by DDP - #5955

Merged
oobabooga merged 9 commits into
unslothai:mainfrom
ftrajkov-amd:fix/grpo-ddp-model-config-access
Jul 2, 2026
Merged

oobabooga merged 9 commits into
unslothai:mainfrom
ftrajkov-amd:fix/grpo-ddp-model-config-access

Conversation

@ftrajkov-amd

Copy link
Copy Markdown
Contributor

Summary

Distributed GRPO training fails when Accelerate/DDP wraps the policy model: rl_replacements.py reads model.config directly, but the wrapper exposes config on model.module.config instead.

This PR adds _unsloth_get_model_config() and routes GRPO logit softcapping / scaling lookups through the unwrapped config. Also guards _unsloth_get_final_logit_softcapping(None).

Fixes #3571 (related: #3914). Follow-up to the approach started in #3809.

Changes

  • unsloth/models/rl_replacements.py
    • New helper: _unsloth_get_model_config(model) — resolves model.config, falling back to model.module.config
    • Use _cfg in _get_per_token_logps_and_entropies and GRPO compute_loss logit-scaling block
    • Inject helper into compiled GRPO trainer via RL_PRE_ITEMS
  • tests/python/test_grpo_ddp_model_config.py — static source guard

Minimal repro / test (torchrun + GRPO)

Before this fix, 2-GPU DDP GRPO can fail on the first training step with:

AttributeError: 'DistributedDataParallel' object has no attribute 'config'

After this fix, the same run should pass step 0.

1. Save as grpo_ddp_smoke.py

import unsloth  # noqa: F401 — must import before TRL
from datasets import Dataset
from unsloth import FastLanguageModel, PatchFastRL
from trl import GRPOConfig, GRPOTrainer

PatchFastRL("GRPO")

MODEL = "unsloth/Qwen3-0.6B"  # small model for a quick smoke test

model, tokenizer = FastLanguageModel.from_pretrained(
    MODEL,
    max_seq_length=2048,
    load_in_4bit=True,
)
model = FastLanguageModel.get_peft_model(model, r=8, lora_alpha=16)


def reward_func(completions, **kwargs):
    return [1.0 if completion.strip() else 0.0 for completion in completions]


train_dataset = Dataset.from_dict(
    {"prompt": ["Explain why the sky is blue in one sentence."] * 8}
)

training_args = GRPOConfig(
    output_dir="grpo_ddp_smoke",
    per_device_train_batch_size=1,
    gradient_accumulation_steps=1,
    num_generations=4,
    max_prompt_length=256,
    max_completion_length=128,
    max_steps=2,
    logging_steps=1,
    report_to="none",
)

trainer = GRPOTrainer(
    model=model,
    processing_class=tokenizer,
    reward_funcs=[reward_func],
    args=training_args,
    train_dataset=train_dataset,
)
trainer.train()

2. Run with torchrun (2 GPUs)

pip install unsloth trl datasets

# editable install if testing this PR branch:
# pip install -e .

torchrun --nproc_per_node=2 grpo_ddp_smoke.py

Notes:

  • num_generations must divide the global batch size (nproc_per_node × per_device_train_batch_size × gradient_accumulation_steps). With 2 GPUs and batch size 1, num_generations=4 works.
  • Delete unsloth_compiled_cache/ when switching Unsloth versions so GRPO patches recompile.
  • For VLM GRPO (the original Multi-GPU Support for GRPO Training with Vision-Language Models (VLM) #3571 report), the same DDP config unwrap applies once the trainer reaches the logit-scaling path in compute_loss.

Test plan

Distributed GRPO fails with AttributeError because rl_replacements reads model.config directly while Accelerate/DDP exposes config on model.module. Add _unsloth_get_model_config() and route softcapping/scaling lookups through it.

Fixes unslothai#3571

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a helper function _unsloth_get_model_config to retrieve the model configuration while correctly unwrapping DDP/Accelerate wrappers. It updates logit-scaling helpers to use this function instead of directly accessing model.config, handles potential None configurations, and adds a test suite to verify these changes. I have no feedback to provide as there are no review comments.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@Datta0 Datta0 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hey @ftrajkov-amd thnks for the contribution. Added a couple of minor comments.
Can you please share any runs (wandb or anything) to validate that this works?

Comment thread unsloth/models/rl_replacements.py Outdated
temperature = self.temperature
logit_softcapping = _unsloth_get_final_logit_softcapping(model.config)
logit_scale_multiply = getattr(model.config, "logit_scale", 0)
_cfg = _unsloth_get_model_config(model)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

NIT: please do this within the get_softcapping function?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Is this approach suitable? d73c7b6

Comment thread unsloth/models/rl_replacements.py Outdated
logit_scale_multiply = getattr(model.config, "logit_scale", 0)
_cfg = _unsloth_get_model_config(model)
logit_softcapping = _unsloth_get_final_logit_softcapping(_cfg)
logit_scale_multiply = (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

NIT: please Undo the styling changes

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Do you mean about automatic commits that stylize the code into multiple lines ?

ftrajkov-amd and others added 2 commits June 3, 2026 17:42
Updated the logit scaling functions to directly utilize the model instead of an intermediate configuration object. This change improves the clarity of the code and ensures consistent access to model attributes. Adjusted related tests to reflect these changes.

Fixes unslothai#3571

Co-authored-by: Cursor <[email protected]>

@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: 3d8fa21073

ℹ️ 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".

@ftrajkov-amd
ftrajkov-amd requested a review from Datta0 June 9, 2026 11:28
@danielhanchen danielhanchen self-assigned this Jun 11, 2026
@ftrajkov-amd

Copy link
Copy Markdown
Contributor Author

@danielhanchen Can you take a look and provide the feedback?

@oobabooga

Copy link
Copy Markdown
Member

Reproduced this on a real 2-GPU box (RTX 6000 Ada and a 3090). On current main the 2-GPU DDP GRPO run dies at step 0 with exactly 'DistributedDataParallel' object has no attribute 'config', the #3571 error. With your fix the identical run completes both steps on both ranks, and a single-GPU run still passes with no regression. That confirms your diagnosis: DDP hides the config behind model.module, and routing the logit-scaling reads through the unwrap helper closes it. Fork CI is green: oobabooga#20.

Also addressed @Datta0's styling nit: hoisted a model_config local into both GRPO blocks so the logits_scaling line stays on one line (it was over the 100-char limit, so pre-commit had wrapped it) and dropped the duplicated unwrap calls. Your helper is unchanged, and softcapping still takes the model and unwraps internally. Updated the static-source test to match.

Thanks @ftrajkov-amd. Merging.

@oobabooga
oobabooga merged commit c5adb69 into unslothai:main Jul 2, 2026
1 check passed
danielhanchen added a commit that referenced this pull request Aug 16, 2026
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.
danielhanchen added a commit that referenced this pull request Aug 16, 2026
* 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>
danielhanchen added a commit that referenced this pull request Aug 25, 2026
…-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>
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.

Multi-GPU Support for GRPO Training with Vision-Language Models (VLM)

4 participants