Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
fix(chat_templates): remove CUDA hardcoded device from stopping criteria (#10684)
li-lizhe0f461886a69c
diff --git a/tests/test_stopping_criteria_device.py b/tests/test_stopping_criteria_device.pynew file mode 100644index 00000000000..26ce603af7f--- /dev/null+++ b/tests/test_stopping_criteria_device.py@@ -0,0 +1,64 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+"""create_stopping_criteria must not assume CUDA.++Before the fix these failed with a cuda/cpu device mismatch, and at construction on a+non-CUDA build.+"""++import types++import pytest+import torch++from unsloth.chat_templates import create_stopping_criteria+++class _FakeTokenizer:+ """Just enough surface for create_stopping_criteria; no network, no files."""++ def __init__(self, eos_token_id = 2):+ self.eos_token_id = eos_token_id++ def __call__(+ self,+ texts,+ add_special_tokens = False,+ return_tensors = "pt",+ ):+ # "\n" + stop_word -> [newline, stop, stop]; the caller drops the newline.+ return types.SimpleNamespace(input_ids = torch.tensor([[13, 100, 101]]))+++def test_eos_criteria_builds_and_runs_on_cpu():+ criteria = create_stopping_criteria(_FakeTokenizer(eos_token_id = 2))++ assert criteria[0].stop_token.device.type == "cpu"+ assert criteria[0](torch.tensor([9, 9, 2]), None) is True+ assert criteria[0](torch.tensor([9, 9, 3]), None) is False+++def test_multi_token_criteria_builds_and_runs_on_cpu():+ criteria = create_stopping_criteria(_FakeTokenizer(), stop_word = "<|stop|>")++ assert criteria[0].length == 2+ assert criteria[0].single_match is False+ assert criteria[0].stop_token.device.type == "cpu"+ assert criteria[0](torch.tensor([7, 100, 101]), None) is True+ assert criteria[0](torch.tensor([100, 101, 7]), None) is False++[email protected](not torch.cuda.is_available(), reason = "needs an accelerator")+def test_stop_token_follows_the_input_device():+ criteria = create_stopping_criteria(_FakeTokenizer(eos_token_id = 2))++ assert criteria[0](torch.tensor([9, 9, 2], device = "cuda"), None) is True+ assert criteria[0].stop_token.device.type == "cuda"+ pointer = criteria[0].stop_token.data_ptr()++ # cached, so generation does not pay a host-to-device copy per token+ assert criteria[0](torch.tensor([9, 9, 2], device = "cuda"), None) is True+ assert criteria[0].stop_token.data_ptr() == pointer++ assert criteria[0](torch.tensor([9, 9, 2]), None) is True+ assert criteria[0].stop_token.device.type == "cpu"diff --git a/unsloth/chat_templates.py b/unsloth/chat_templates.pyindex 5e63c504d9e..dc8f21d9963 100644--- a/unsloth/chat_templates.py+++ b/unsloth/chat_templates.py@@ -2872,19 +2872,21 @@ def create_stopping_criteria(tokenizer, stop_word = "eos_token"):class StoppingCriteriaSub(StoppingCriteria):__slots__ = "stop_token", "single_match", "length",- def __init__(self, stops = "eos_token", device = "cuda", encounters = 1):+ def __init__(self, stops = "eos_token", encounters = 1):super().__init__()if stops == "eos_token":- self.stop_token = torch.tensor(tokenizer.eos_token_id, device = "cuda")+ self.stop_token = torch.tensor(tokenizer.eos_token_id)self.length = 1else:self.stop_token = tokenizer(["\n" + stops], add_special_tokens = False, return_tensors = "pt")- self.stop_token = self.stop_token.input_ids.ravel()[1:].to("cuda")+ self.stop_token = self.stop_token.input_ids.ravel()[1:]self.length = self.stop_token.shape[0]self.single_match = self.length == 1def __call__(self, input_ids: LongTensor, scores: FloatTensor) -> bool:input_ids = input_ids.ravel()+ if self.stop_token.device != input_ids.device:+ self.stop_token = self.stop_token.to(input_ids.device)last_token = input_ids[-1]if self.single_match and (last_token == self.stop_token): return True