Skip to content

[Bug] RuntimeError: expected self and mask to be on the same device, but got mask on cuda:0 and self on cuda:1 #4041

Closed

Description

@nole69
  1. Did you update? pip install --upgrade unsloth unsloth_zoo yes

  2. Colab or Kaggle or local / cloud local local

  3. Number GPUs used, use nvidia-smi 2 GPUs (NVIDIA RTX PRO 6000 Blackwell Max-Q Workstation Edition)

  4. Which notebook? Please link! gpt_oss_20b

  5. Which Unsloth version, TRL version, transformers version, PyTorch version?
    unsloth==2026.2.1
    transformers==4.57.6
    trl==0.24.0
    torch==2.10.0
    unsloth_zoo==2026.2.1

  6. Which trainer? SFTTrainer, GRPOTrainer etc SFTTrainer

from unsloth import FastLanguageModel
import torch
max_seq_length = 1024*32

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name = "unsloth/gpt-oss-120b-unsloth-bnb-4bit",
    dtype = dtype, # None for auto detection
    max_seq_length = max_seq_length, # Choose any for long context!
    load_in_4bit = True,  # 4 bit quantization to reduce memory
    full_finetuning = False, # [NEW!] We have full finetuning now!
    device_map = "balanced",
)

model = FastLanguageModel.get_peft_model(
    model,
    r = 16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
    target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
                      "gate_proj", "up_proj", "down_proj",],
    lora_alpha = 32,
    lora_dropout = 0, # Supports any, but = 0 is optimized
    bias = "none",    # Supports any, but = "none" is optimized
    # [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes!
    use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context
    random_state = 3407,
    use_rslora = False,  # We support rank stabilized LoRA
    loftq_config = None, # And LoftQ
)

from jinja2 import Template
from unsloth.chat_templates import get_chat_template, standardize_sharegpt

def formatting_prompts_func(examples):
    convos = examples["messages"]
    texts = [tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = False) for convo in convos]
    return { "text" : texts, }

new_train_dataset = standardize_sharegpt(my_train_dataset)
new_train_dataset = new_train_dataset.map(formatting_prompts_func, batched = True,)

new_val_dataset = standardize_sharegpt(my_val_dataset)
new_val_dataset = new_val_dataset.map(formatting_prompts_func, batched = True,)

from trl import SFTTrainer, SFTConfig
trainer = SFTTrainer(
    model = model,
    tokenizer = tokenizer,
    train_dataset = train_dataset,
    eval_dataset = val_dataset, # Can set up evaluation!
    args = SFTConfig(
        dataset_text_field = "text",
        per_device_train_batch_size = 1,
        per_device_eval_batch_size = 1,
        gradient_accumulation_steps = 16, # Use GA to mimic batch size!
        warmup_steps = 40,
        # num_train_epochs = 1, # Set this for 1 full training run.
        max_steps = 1500,
        #max_steps = 1,
        #max_length = max_seq_length,
        learning_rate = 5e-5, # Reduce to 2e-5 for long training runs
        fp16 = not torch.cuda.is_bf16_supported(),
        bf16 = torch.cuda.is_bf16_supported(),
        logging_steps = 25,
        optim = "adamw_8bit",
        weight_decay = 0.01,
        lr_scheduler_type = "linear",
        seed = 2678,
        output_dir = "/path/to/model_checkpoints",
        save_strategy = "steps",
        eval_strategy = "steps",
        eval_steps=25,
        save_steps=25,
        do_eval=True
    ),
)

from unsloth.chat_templates import train_on_responses_only

gpt_oss_kwargs = dict(instruction_part = "<|start|>user<|message|>", response_part = "<|start|>assistant<|message|>")

trainer = train_on_responses_only(
    trainer,
    **gpt_oss_kwargs,
)

trainer_stats = trainer.train()

The traceback

Traceback (most recent call last):
  File "/home/nolelin/train.py", line 166, in <module>
    trainer_stats = trainer.train()
                    ^^^^^^^^^^^^^^^
  File "/home/nolelin/unsloth_compiled_cache/UnslothSFTTrainer.py", line 66, in wrapper
    output = f(self, *args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/transformers/trainer.py", line 2325, in train
    return inner_training_loop(
           ^^^^^^^^^^^^^^^^^^^^
  File "<string>", line 328, in _fast_inner_training_loop
  File "/home/nolelin/unsloth_compiled_cache/UnslothSFTTrainer.py", line 1267, in training_step
    return super().training_step(*args, **kwargs)   
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^   
  File "<string>", line 40, in _unsloth_training_step
  File "/home/nolelin/unsloth_compiled_cache/UnslothSFTTrainer.py", line 1256, in compute_loss
    outputs = super().compute_loss(
              ^^^^^^^^^^^^^^^^^^^^^
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/unsloth/models/_utils.py", line 1830, in _unsloth_pre_compute_loss
    outputs = self._old_compute_loss(model, inputs, *args, **kwargs)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<string>", line 36, in compute_loss
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1776, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1787, in _call_impl
    return forward_call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/accelerate/utils/operations.py", line 819, in forward
    return model_forward(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/accelerate/utils/operations.py", line 807, in __call__
    return convert_to_fp32(self.model_forward(*args, **kwargs))
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/torch/amp/autocast_mode.py", line 44, in decorate_autocast
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/peft/peft_model.py", line 1923, in forward
    return self.base_model(
           ^^^^^^^^^^^^^^^^
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1776, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1787, in _call_impl
    return forward_call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/peft/tuners/tuners_utils.py", line 311, in forward
    return self.model.forward(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/accelerate/hooks.py", line 175, in new_forward
    output = module._old_forward(*args, **kwargs)   
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/unsloth_zoo/temporary_patches/gpt_oss.py", line 2820, in _patched_causal_lm_forward
    return _original_causal_lm_forward(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/unsloth_zoo/temporary_patches/gpt_oss.py", line 2820, in _patched_causal_lm_forward
    return _original_causal_lm_forward(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/transformers/utils/generic.py", line 918, in wrapper
    output = func(self, *args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/transformers/models/gpt_oss/modeling_gpt_oss.py", line 687, in forward
    loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/unsloth_zoo/loss_utils.py", line 126, in UnslothForCausalLMLoss
    loss = unsloth_fixed_cross_entropy(shift_logits, shift_labels, num_items_in_batch, ignore_index, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/unsloth_zoo/loss_utils.py", line 96, in unsloth_fixed_cross_entropy
    loss = _fast_cross_entropy_loss(
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/unsloth/kernels/cross_entropy_loss.py", line 440, in fast_cross_entropy_loss
    loss = Fast_CrossEntropyLoss.apply(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/torch/autograd/function.py", line 583, in apply
    return super().apply(*args, **kwargs)  # type: ignore[misc]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/nolelin/venv312_unsloth_2026_2_1/lib/python3.12/site-packages/unsloth/kernels/cross_entropy_loss.py", line 372, in forward
    losses.masked_fill_(labels == -100, 0)  # Don't forget to mask padding out!
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: expected self and mask to be on the same device, but got mask on cuda:0 and self on cuda:1

Activity

  1. nole69 commented on Feb 13, 2026

    @nole69
    ContributorAuthor

    I've also tried setting TOKENIZERS_PARALLELISM=false according to Klepackp in #3862 but that didn't resolve this error.

  2. ai-nikolai commented on Feb 13, 2026

    @ai-nikolai

    @nole69 could you clarify how you launched the script?

    Have a look at this documentation for multi-gpu launches:
    https://unsloth.ai/docs/basics/multi-gpu-training-with-unsloth

    Does it still fail for you after trying accelerate as described above?

  3. nole69 commented on Feb 14, 2026

    @nole69
    ContributorAuthor

    @ai-nikolai Yes I have tried running as part of local jupyter notebook and also as simply python train.py

    My code is based off of the documentation for multi-gpu, where I set device_map = "balanced". But I think accelerate is only used for DDP, is that correct? Would accelerate still be appropriate for device_map = "balanced"?

  4. devchilll commented on Feb 14, 2026

    @devchilll
    Contributor

    think I found the issue:
    When running SFT training on a multi-GPU setup with device_map="balanced", model layers get split across GPUs (e.g., cuda:0 and cuda:1). The custom Unsloth cross-entropy loss kernel in Fast_CrossEntropyLoss.forward creates the losses tensor on whichever device the logits are on (e.g., cuda:1 for the final layers), but the labels tensor remains on cuda:0 (the default device). This causes a RuntimeError at the masked_fill_ call because PyTorch requires both operands to be on the same device.

    Create a pull request to fix this - pending review

  5. devchilll commented on Feb 14, 2026

    @devchilll
    Contributor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions