Skip to content

Let Gemma 4 31B train when it is split across GPUs - #12233

Merged
danielhanchen merged 3 commits into
unslothai:mainfrom
NilayYadav:getting-error-indices-should-either
Sep 29, 2026
Merged

danielhanchen merged 3 commits into
unslothai:mainfrom
NilayYadav:getting-error-indices-should-either

Conversation

@NilayYadav

@NilayYadav NilayYadav commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

Training Gemma 4 31B stopped before the first step with "indices should be either on cpu or on the same device as the indexed tensor (cuda:0)" whenever the model was split over two or more GPUs. Studio does that split by itself when one card is too small for the run, for example on 16 GB cards. On a single GPU the same run trained fine.

The 31B builds an image attention mask from a token type tensor that lands on the first GPU, while the text embeddings it is compared against sit on the last one. This moves that tensor next to the embeddings, only for Gemma 4 models spread over several GPUs. Single GPU runs and other models are unchanged.

PR #12095 turns off padding-free batching instead, but the same error still happens with it.

Fixes #11952

Testing

  • 2x L4, transformers 5.5.0, Studio with unsloth/gemma-4-31B-it QLoRA (Studio split it over both cards by itself): main fails at step 0 with indices should be either on cpu or on the same device as the indexed tensor (cuda:0); this PR trains 5/5 steps. The library API with device_map="unsloth_balanced" gives the same result, and the losses (3.811, 3.340, 2.380, 2.305, 2.635) track a single-GPU run (3.794, 3.426, 2.382, 2.383, 2.599).
  • tests/test_gemma4_split_vision_mask.py needs two GPUs, so hosted CI skips it. On 2 GPUs with transformers 5.5.0 it fails on main and passes here. transformers 5.9 and newer move the token types themselves, so there the hook is a harmless no-op.
  • Single GPU: the hook is not registered, and loss and peak memory are unchanged.
  • Not fixed here: Gemma 4 E4B split over two GPUs still fails on both main and this PR, in the per-layer-input path. That needs its own fix.

NilayYadav

This comment was marked as outdated.

NilayYadav

This comment was marked as outdated.

@danielhanchen

Copy link
Copy Markdown
Member

Review record for #12233, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#212.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1: reviewed mirror 574f7a09e (this PR's 809a8fc5a)

chatgpt-codex-connector[bot] on unsloth/models/vision.py (on the mirror)

@@ -415,6 +415,28 @@ def _align_root_hook_with_input_embeddings(model):
     return target
 
 
+def _move_gemma4_token_types_to_input_embeddings(model):
+    inner = getattr(model, "model", None)
+    device_map = getattr(model, "hf_device_map", None)
+    if (
+        getattr(getattr(inner, "config", None), "model_type", None) != "gemma4"
+        or not device_map
+        or len(set(device_map.values())) < 2
+    ):
+        return
+    target = inner.get_input_embeddings().weight.device
+    if target.type in ("cpu", "meta"):
+        return
+
+    # transformers 5.5-5.8 build Gemma 4's vision mask groups on mm_token_type_ids' device (the root hook's) but index them from the embedding's; 5.9 moves them itself.
+    def to_input_embeddings(module, args, kwargs):
+        if kwargs.get("mm_token_type_ids") is not None:
+            kwargs["mm_token_type_ids"] = kwargs["mm_token_type_ids"].to(target)

P1 Badge Keep token types with caller-provided embeddings

When a split Gemma 4 is called with inputs_embeds (for example, during soft-prompt training), the embedding module is bypassed, so Accelerate leaves those embeddings on the root/first-layer device. This hook nevertheless moves mm_token_type_ids to the embedding weight's device; with the added test's placement that means embeddings on cuda:0 and token types on cuda:1. Transformers 5.5–5.8 then constructs vision_group_ids on cuda:1 but indexes it using mask indices derived on inputs_embeds.device, recreating the cross-device indexing failure this change is intended to fix. Use the supplied inputs_embeds.device when present, or only apply this move to the input_ids path.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Not a regression. With caller-provided inputs_embeds on a split Gemma 4, transformers 5.5.0 get_placeholder_mask compares them against embed_tokens(...) output from the embedding's card before mm_token_type_ids is read, so that path fails with a device mismatch on main and on this PR alike (measured on 2x L4).

Round 2: reviewed mirror 574f7a09e7 (this PR's 809a8fc5a)

chatgpt-codex-connector[bot] (on the mirror)

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

Reviewed commit: 574f7a09e7

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror 574f7a09e7 (this PR's 809a8fc5a).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

# Conflicts:
#	unsloth/models/vision.py
@danielhanchen
danielhanchen merged commit 7089071 into unslothai:main Sep 29, 2026
19 of 26 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

2 participants