Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
Disable thinking in LLMs so prompt expansion will work properly with thinking models (#9380)
Shane Killian3b913d130394
diff --git a/docs/src/content/docs/features/prompt-tools.md b/docs/src/content/docs/features/prompt-tools.mdindex 18882487d0..c0b4fc00d8 100644--- a/docs/src/content/docs/features/prompt-tools.md+++ b/docs/src/content/docs/features/prompt-tools.md@@ -29,6 +29,10 @@ Takes your short prompt and expands it into a detailed, vivid description suitabInstall by pasting the HuggingFace ID into the Model Manager. The model is automatically detected as a **Text LLM** type.+### Reasoning ("thinking") models++Reasoning models such as Qwen3 or the DeepSeek-R1 distills normally write out a chain of thought before their answer. Prompt expansion returns the generated text as-is, so that reasoning would end up in your prompt. InvokeAI therefore renders the chat template with thinking disabled, which makes these models answer directly. Models whose chat template does not support the switch are unaffected, and models that always reason (with no way to turn it off) are not suitable for prompt expansion.+## Image to PromptUpload an image and generate a descriptive prompt from it using a vision-language model.diff --git a/invokeai/backend/text_llm_pipeline.py b/invokeai/backend/text_llm_pipeline.pyindex 651be6c858..608d566b88 100644--- a/invokeai/backend/text_llm_pipeline.py+++ b/invokeai/backend/text_llm_pipeline.py@@ -144,14 +144,21 @@ class TextLLMPipeline:progress_callback: ProgressCallback | None = None,) -> str:# Build messages for chat template if supported, otherwise use raw prompt.- if hasattr(self._tokenizer, "apply_chat_template") and self._tokenizer.chat_template is not None:+ used_chat_template = (+ hasattr(self._tokenizer, "apply_chat_template") and self._tokenizer.chat_template is not None+ )+ if used_chat_template:messages = []if system_prompt:messages.append({"role": "system", "content": system_prompt})messages.append({"role": "user", "content": prompt})try:+ # enable_thinking=False makes reasoning models (Qwen3, DeepSeek-R1 distills and+ # other templates that honour the flag) emit an empty thinking block instead of a+ # chain of thought, so prompt expansion returns the prompt rather than the model's+ # reasoning. Templates that do not know the flag ignore it.formatted_prompt: str = self._tokenizer.apply_chat_template(- messages, tokenize=False, add_generation_prompt=True+ messages, tokenize=False, add_generation_prompt=True, enable_thinking=False)except Exception as e: # noqa: BLE001 - jinja2 TemplateError is not importable here# Some chat templates (notably Gemma) reject a dedicated "system" role. Fold the@@ -159,7 +166,7 @@ class TextLLMPipeline:if system_prompt and "system role" in str(e).lower():merged = [{"role": "user", "content": f"{system_prompt}\n\n{prompt}"}]formatted_prompt = self._tokenizer.apply_chat_template(- merged, tokenize=False, add_generation_prompt=True+ merged, tokenize=False, add_generation_prompt=True, enable_thinking=False)else:raise@@ -169,7 +176,12 @@ class TextLLMPipeline:else:formatted_prompt = prompt- inputs = self._tokenizer(formatted_prompt, return_tensors="pt").to(device=device)+ # A rendered chat template already carries the model's control tokens, so adding special+ # tokens again duplicates BOS for the families that use one (Gemma, Llama). The raw+ # fallback prompt above has no control tokens and still needs them.+ inputs = self._tokenizer(formatted_prompt, return_tensors="pt", add_special_tokens=not used_chat_template).to(+ device=device+ )streamer = TextIteratorStreamer(self._tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=STREAM_TIMEOUTdiff --git a/tests/backend/text_llm/test_text_llm_pipeline.py b/tests/backend/text_llm/test_text_llm_pipeline.pyindex 97919f0789..f88d842150 100644--- a/tests/backend/text_llm/test_text_llm_pipeline.py+++ b/tests/backend/text_llm/test_text_llm_pipeline.py@@ -77,7 +77,7 @@ class _TokenBatch(dict):class _TinyTokenizer:chat_template = None- def __call__(self, prompt: str, return_tensors: str) -> _TokenBatch:+ def __call__(self, prompt: str, return_tensors: str, add_special_tokens: bool = True) -> _TokenBatch:return _TokenBatch(input_ids=torch.tensor([[1, 2]], dtype=torch.long))def encode(self, text: str, add_special_tokens: bool = False) -> list[str]:diff --git a/tests/backend/text_llm/test_text_llm_thinking.py b/tests/backend/text_llm/test_text_llm_thinking.pynew file mode 100644index 0000000000..0b0d50db48--- /dev/null+++ b/tests/backend/text_llm/test_text_llm_thinking.py@@ -0,0 +1,135 @@+"""Regression tests for reasoning ("thinking") models in TextLLMPipeline.++Reasoning models such as Qwen3 emit a chain of thought before their answer unless the chat+template is rendered with ``enable_thinking=False``. Prompt expansion returns the raw generated+text, so without the flag the user gets the model's reasoning instead of a prompt.++These tests are hermetic: the bundled Qwen3 tokenizer ships the real Qwen3 chat template, so no+network access, model weights or GPU are required.+"""++from unittest.mock import MagicMock, patch++import torch+from transformers import PreTrainedTokenizerBase++from invokeai.backend.qwen3.qwen3_tokenizer import load_bundled_qwen3_tokenizer+from invokeai.backend.text_llm_pipeline import TextLLMPipeline++# What the Qwen3 template appends after the generation prompt when thinking is disabled: an+# already-closed, empty thinking block, so the model starts on the answer.+EMPTY_THINKING_BLOCK = "<think>\n\n</think>\n\n"+++class _FakeStreamer:+ """Stand-in for TextIteratorStreamer — yields a fixed sequence of text chunks."""++ def __init__(self, *args, **kwargs):+ pass++ def __iter__(self):+ return iter(["expanded ", "prompt"])+++def _patch_streamer():+ return patch("invokeai.backend.text_llm_pipeline.TextIteratorStreamer", _FakeStreamer)+++class _RecordingTokenizer:+ """Delegates to a real tokenizer while recording what the pipeline sends it."""++ def __init__(self, tokenizer: PreTrainedTokenizerBase):+ self._tokenizer = tokenizer+ self.formatted_prompts: list[str] = []+ self.tokenize_kwargs: list[dict] = []++ def __getattr__(self, name: str):+ return getattr(self._tokenizer, name)++ def __call__(self, text: str, **kwargs):+ self.formatted_prompts.append(text)+ self.tokenize_kwargs.append(kwargs)+ return self._tokenizer(text, **kwargs)+++class _FakeEncoding(dict):+ def to(self, *args, **kwargs):+ return self+++def _make_system_role_rejecting_tokenizer() -> MagicMock:+ """A Gemma-style tokenizer whose template rejects a dedicated system role."""+ tokenizer = MagicMock()+ tokenizer.chat_template = "<<template>>"++ def apply_chat_template(messages, **kwargs):+ if any(m["role"] == "system" for m in messages):+ raise ValueError("System role not supported")+ return "FORMATTED_PROMPT"++ tokenizer.apply_chat_template.side_effect = apply_chat_template+ tokenizer.return_value = _FakeEncoding(+ input_ids=torch.tensor([[1, 2, 3]]), attention_mask=torch.tensor([[1, 1, 1]])+ )+ return tokenizer+++def test_thinking_is_disabled_for_a_real_reasoning_chat_template() -> None:+ """The rendered prompt must pre-close the thinking block so generation starts on the answer."""+ tokenizer = _RecordingTokenizer(load_bundled_qwen3_tokenizer())+ pipeline = TextLLMPipeline(MagicMock(), tokenizer)++ with _patch_streamer():+ pipeline.run(prompt="a cat", system_prompt="be helpful", max_new_tokens=8)++ assert len(tokenizer.formatted_prompts) == 1+ formatted_prompt = tokenizer.formatted_prompts[0]+ assert "be helpful" in formatted_prompt+ assert "a cat" in formatted_prompt+ assert formatted_prompt.endswith(EMPTY_THINKING_BLOCK)+++def test_the_thinking_assertion_is_not_vacuous() -> None:+ """Without the flag the same template leaves the thinking block open — this is the bug."""+ tokenizer = load_bundled_qwen3_tokenizer()++ formatted_prompt = tokenizer.apply_chat_template(+ [{"role": "user", "content": "a cat"}], tokenize=False, add_generation_prompt=True+ )++ assert not formatted_prompt.endswith(EMPTY_THINKING_BLOCK)+++def test_thinking_is_disabled_on_the_system_role_retry() -> None:+ """The Gemma fallback re-renders the template and must keep thinking disabled."""+ tokenizer = _make_system_role_rejecting_tokenizer()+ pipeline = TextLLMPipeline(MagicMock(), tokenizer)++ with _patch_streamer():+ pipeline.run(prompt="a cat", system_prompt="be helpful", max_new_tokens=8)++ assert tokenizer.apply_chat_template.call_count == 2+ assert all(call.kwargs["enable_thinking"] is False for call in tokenizer.apply_chat_template.call_args_list)+++def test_rendered_chat_template_is_tokenized_without_extra_special_tokens() -> None:+ """The template already emits its control tokens; re-adding them duplicates BOS."""+ tokenizer = _RecordingTokenizer(load_bundled_qwen3_tokenizer())+ pipeline = TextLLMPipeline(MagicMock(), tokenizer)++ with _patch_streamer():+ pipeline.run(prompt="a cat", max_new_tokens=8)++ assert tokenizer.tokenize_kwargs[0]["add_special_tokens"] is False+++def test_raw_fallback_prompt_is_tokenized_with_special_tokens() -> None:+ """Without a chat template the prompt carries no control tokens, so it still needs them."""+ tokenizer = _RecordingTokenizer(load_bundled_qwen3_tokenizer())+ tokenizer.chat_template = None+ pipeline = TextLLMPipeline(MagicMock(), tokenizer)++ with _patch_streamer():+ pipeline.run(prompt="a cat", max_new_tokens=8)++ assert tokenizer.tokenize_kwargs[0]["add_special_tokens"] is True