Skip to content

[Bug] Sampling inside TrainingCallback gives ValueError: Invalid target device: None #3538

Closed

Description

@nielsrolf
  1. Did you update? pip install --upgrade unsloth unsloth_zoo - yes
  2. Colab or Kaggle or local / cloud - on a runpod GPU (it happens on every hardware I tried, including H100, H200, L40, A100)
  3. Number GPUs used, use nvidia-smi - 1
  4. Which notebook? Please link! - not a notebook, but here is the callback that used to work with previous unsloth versions, but stopped working: https://github.com/longtermrisk/openweights/blob/main/openweights/jobs/unsloth/sampling_callback.py
  5. Which Unsloth version, TRL version, transformers version, PyTorch version? - the latest unsloth Docker image (both latest and stable):
torch==2.8.0+cu128
transformers==4.56.2
trl==0.23.0
unsloth==2025.10.3
unsloth_zoo==2025.10.3
  1. Which trainer? SFTTrainer, GRPOTrainer etc - SFTTrainer

Traceback:

Traceback (most recent call last):
  File "/tmp/tmprkrgnt2r/training.py", line 179, in <module>
    main(sys.argv[1])
  File "/tmp/tmprkrgnt2r/training.py", line 175, in main
    train(training_config, skip_client_logging)
  File "/tmp/tmprkrgnt2r/training.py", line 93, in train
    trainer.train()
  File "/tmp/tmprkrgnt2r/unsloth_compiled_cache/UnslothSFTTrainer.py", line 53, in wrapper
    output = f(self, *args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/conda/lib/python3.11/site-packages/transformers/trainer.py", line 2328, in train
    return inner_training_loop(
           ^^^^^^^^^^^^^^^^^^^^
  File "<string>", line 231, in _fast_inner_training_loop
  File "/opt/conda/lib/python3.11/site-packages/transformers/trainer_callback.py", line 506, in on_train_begin
    return self.call_event("on_train_begin", args, state, control)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/conda/lib/python3.11/site-packages/transformers/trainer_callback.py", line 556, in call_event
    result = getattr(callback, event)(
             ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/tmp/tmprkrgnt2r/sampling_callback.py", line 130, in on_train_begin
    self.run(model=self.model, step=0)
  File "/tmp/tmprkrgnt2r/sampling_callback.py", line 143, in run
    completions = sample(
                  ^^^^^^^
  File "/tmp/tmprkrgnt2r/sampling_callback.py", line 80, in sample
    _sample(
  File "/tmp/tmprkrgnt2r/sampling_callback.py", line 56, in _sample
    output_sequences = model.generate(input_ids=input_ids, **gen_kwargs)
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/conda/lib/python3.11/site-packages/peft/peft_model.py", line 1973, in generate
    outputs = self.base_model.generate(*args, **kwargs)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/conda/lib/python3.11/site-packages/unsloth/models/llama.py", line 1764, in unsloth_fast_generate
    output = self._old_generate(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/conda/lib/python3.11/site-packages/torch/utils/_contextlib.py", line 120, in decorate_context
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/opt/conda/lib/python3.11/site-packages/transformers/generation/utils.py", line 2539, in generate
    result = self._sample(
             ^^^^^^^^^^^^^
  File "/opt/conda/lib/python3.11/site-packages/transformers/generation/utils.py", line 2870, in _sample
    outputs = model_forward(**model_inputs, return_dict=True)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/conda/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1773, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/conda/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1784, in _call_impl
    return forward_call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/conda/lib/python3.11/site-packages/unsloth/models/llama.py", line 1133, in _CausalLM_fast_forward
    outputs = fast_forward_inference(
              ^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/conda/lib/python3.11/site-packages/unsloth/models/llama.py", line 1055, in LlamaModel_fast_forward_inference_custom
    X, residual, position_ids = move_to_device(
                                ^^^^^^^^^^^^^^^
  File "/opt/conda/lib/python3.11/site-packages/unsloth/models/_utils.py", line 1025, in move_to_device
    raise ValueError(f"Invalid target device: {target_device}")
ValueError: Invalid target device: None

To reproduce: use the following callback inside of an SFTTrainer:

import json
import math
import os

import torch
import torch.nn.functional as F
from transformers import TrainerCallback
from unsloth import FastLanguageModel

def load_jsonl(file_id):
        with open(file_id, "r") as f:
            return [json.loads(line) for line in f.readlines() if line.strip()]

def _sample(
    model,
    tokenizer,
    conversations,
    top_p=1,
    max_tokens=600,
    temperature=0,
    stop=[],
    prefix="",
):
    is_training = model.training
    if is_training:
        FastLanguageModel.for_inference(model)
    texts = []
    for conversation in conversations:
        messages = conversation["messages"]
        pre = prefix
        if messages[-1]["role"] == "assistant":
            messages, pre = messages[:-1], messages[-1]["content"]
        text = tokenizer.apply_chat_template(
            messages, tokenize=False, add_generation_prompt=True
        )
        texts.append(text + pre)
    # Tokenize and pad the input texts
    inputs = tokenizer(
        texts,
        return_tensors="pt",
        padding=True,
        truncation=True,
        return_attention_mask=True,
    )
    input_ids = inputs.input_ids.to(model.device)
    attention_mask = inputs.attention_mask.to(model.device)
    gen_kwargs = {
        "max_new_tokens": max_tokens,
        "do_sample": temperature > 0,
        "top_p": top_p,
        "temperature": temperature if temperature > 0 else 1.0,
        "pad_token_id": tokenizer.pad_token_id,
        "attention_mask": attention_mask,
        "stop_strings": [tokenizer.eos_token],
        "tokenizer": tokenizer,
    }
    with torch.no_grad():
        output_sequences = model.generate(input_ids=input_ids, **gen_kwargs)
    decoded_outputs = tokenizer.batch_decode(
        output_sequences[:, input_ids.shape[1] :], skip_special_tokens=True
    )
    if is_training:
        FastLanguageModel.for_training(model)
    return [prefix + output for output in decoded_outputs]


def sample(
    model,
    tokenizer,
    conversations,
    batch_size,
    top_p=1,
    max_tokens=600,
    temperature=0,
    stop=[],
    prefix="",
):
    """Batched version of _sample"""
    completions = []
    for i in range(0, len(conversations), batch_size):
        completions.extend(
            _sample(
                model,
                tokenizer,
                conversations[i : i + batch_size],
                top_p,
                max_tokens,
                temperature,
                stop,
                prefix,
            )
        )
    return completions


class SamplingCallback(TrainerCallback):
    def __init__(
        self,
        dataset,
        tokenizer,
        eval_steps="log",
        batch_size=8,
        tag="samples",
        temperature=0,
        max_tokens=600,
    ):
        """
        A callback that samples from the model and logs the results.

        Args:
            dataset: List[Message] or str: file_id
            tokenizer: The tokenizer to use for encoding conversations
            eval_steps: Evaluate every `eval_steps` training steps
            output_dir: Directory where token-level logP data will be saved
            batch_size: Batch size to use during evaluation
            tag: Key to use when logging the loss metric
        """
        if isinstance(dataset, str):
            dataset = load_jsonl(dataset)
        self.dataset = dataset
        self.tokenizer = tokenizer
        self.eval_steps = eval_steps
        self.batch_size = batch_size
        self.tag = tag
        self.temperature = temperature
        self.max_tokens = max_tokens

    def on_init_end(self, args, state, control, **kwargs):
        self.model = kwargs["model"]

    def on_train_begin(self, args, state, control, **kwargs):
        self.run(model=self.model, step=0)

    def on_step_end(self, args, state, control, **kwargs):
        """Called at the end of each training step."""
        if state.global_step % self.eval_steps != 0:
            return
        self.run(kwargs["model"], state.global_step)

    def run(self, model, step):
        """Called at the end of each training step."""
        # Get the model from kwargs
        FastLanguageModel.for_inference(model)

        completions = sample(
            model,
            self.tokenizer,
            self.dataset,
            batch_size=self.batch_size,
            max_tokens=self.max_tokens,
            temperature=self.temperature,
        )

        results_file = f"samples_{self.tag}_{step}.jsonl"
        with open(results_file, "w") as f:
            for row, completion in zip(self.dataset, completions):
                row["completion"] = completion
                f.write(json.dumps(row) + "\n")

        # Log the test loss
        print(
            {
                "type": "samples",
                "step": step,
                "file": samples_file["id"],
                "tag": self.tag,
            }
        )

        # Return model to training mode
        FastLanguageModel.for_training(model)

Activity

  1. danielhanchen commented on Nov 1, 2025

    @danielhanchen
    Member

    @Datta0 I think this is interacting with the move_to_device function

  2. Datta0 commented on Nov 1, 2025

    @Datta0
    Contributor

    Strange, we do support int, str and torch.device
    Also there's a fallback here which defaults to 0
    The only way this can fail is some part of the code wrote wrong value to decoder_layer._per_layer_device_index
    So someone/some code explicitly wrote None to the attribute?

  3. nielsrolf commented on Jan 9, 2026

    @nielsrolf
    Author

    My fallback solution since this issue appeared has been to pin unsloth to an older version. I would like to eventually upgrade to a new version if this issue gets fixed, so I'd be curious if there are any updates?

  4. shubhamjain0594 commented on Feb 13, 2026

    @shubhamjain0594

    Having same issue here, checking if anyone found a solution.

    My setup is this:

    • Training a model with accelerate and SFTTrainer from trl. Using unsloth to load the model and the apply LoRA.
    • I have modified the evaluation loop of SFTTrainer so that instead of just evaluating loss, I generate on test examples then evaluate some metrics post generation. I am getting this error during generation.
  5. yenhao-huang commented on Aug 10, 2026

    @yenhao-huang

    I think the issue is that PyTorch allows:

    torch.device("cpu").index     # None
    torch.device("cpu", 0).index  # 0

    verify_and_set_device() stores device.index directly without handling None, which is later passed to move_to_device() and causes the error.

    Perhaps this:

    device_index = getattr(decoder_layer, "_per_layer_device_index", 0)

    could be changed to:

    device_index = getattr(decoder_layer, "_per_layer_device_index", None)
    if device_index is None:
        device_index = 0

    If needed, I can submit a fix.

  6. added 3 commits that reference this issue on Sep 15, 2026
    4a52c33
    bca18eb
    b2462ed
  7. added a commit that references this issue on Sep 17, 2026
    7236127
  8. added a commit that references this issue on Oct 13, 2026
    ce2c341
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