Skip to content

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.

Add seeded Text LLM sampling (#9451)

Jonathand9399b5b97d6
diff --git a/docs/src/content/docs/features/prompt-tools.md b/docs/src/content/docs/features/prompt-tools.md
index 45bfd96170..18882487d0 100644
--- a/docs/src/content/docs/features/prompt-tools.md
+++ b/docs/src/content/docs/features/prompt-tools.md
@@ -2,7 +2,7 @@
title: LLM Prompt Tools
sidebar:
order: 3
-lastUpdated: 2026-05-23
+lastUpdated: 2026-08-09
---
InvokeAI includes two built-in tools that use local language models to help you write better prompts. Both tools appear as small buttons in the top-right corner of the positive prompt area and are only visible when you have a compatible model installed.
@@ -52,4 +52,10 @@ Both tools overwrite your current prompt. You can undo this change:
## Workflow Node
-A **Text LLM** node is also available in the workflow editor for use in automated pipelines. It accepts a prompt string and model selection as inputs and outputs the expanded text as a string.
+The workflow editor provides **Text LLM** and **Text LLM (with System Prompt Preset)** nodes for automated pipelines. Both accept a prompt, model, maximum token count, and seed, then output generated text as a string. The preset variant reads its system prompt from the System Prompts library.
+
+Using the same seed reproduces sampling when the model, prompt, settings, hardware, and software versions remain the same. Results may differ across devices or software versions. The prompt area's **Expand Prompt** tool chooses a fresh seed for each request so repeated expansions can vary.
+
+API callers can pass an optional seed to **Expand Prompt**; the response returns the effective seed for replay.
+
+When a saved `1.0.0` Text LLM workflow is migrated, its new seed defaults to `0`, so repeated runs become deterministic. Connect a random integer node to **seed** if the workflow should vary between runs.
diff --git a/invokeai/app/api/routers/utilities.py b/invokeai/app/api/routers/utilities.py
index 023f653df6..0ede5441c4 100644
--- a/invokeai/app/api/routers/utilities.py
+++ b/invokeai/app/api/routers/utilities.py
@@ -20,6 +20,7 @@ from invokeai.app.services.events.events_base import EventServiceBase
from invokeai.app.services.image_files.image_files_common import ImageFileNotFoundException
from invokeai.app.services.model_records.model_records_base import UnknownModelException
from invokeai.app.util.dynamicprompts import find_missing_wildcards
+from invokeai.app.util.misc import SEED_MAX, get_random_seed
from invokeai.backend.llava_onevision_pipeline import LlavaOnevisionPipeline
from invokeai.backend.model_manager.taxonomy import ModelType
from invokeai.backend.text_llm_pipeline import DEFAULT_SYSTEM_PROMPT, ProgressCallback, TextLLMPipeline
@@ -88,6 +89,7 @@ class ExpandPromptRequest(BaseModel):
model_key: str
max_tokens: int = Field(default=300, ge=1, le=2048)
system_prompt: str | None = None
+ seed: int | None = Field(default=None, ge=0, le=SEED_MAX, description="Seed for reproducible text generation")
task_id: str | None = Field(
default=None, description="Client-supplied task ID used to correlate socket progress events to this request"
)
@@ -95,6 +97,7 @@ class ExpandPromptRequest(BaseModel):
class ExpandPromptResponse(BaseModel):
expanded_prompt: str
+ seed: int
error: str | None = None
@@ -136,9 +139,10 @@ def _run_expand_prompt(
model_key: str,
max_tokens: int,
system_prompt: str | None,
+ seed: int | None,
task_id: str | None,
user_id: str,
-) -> str:
+) -> tuple[str, int]:
"""Run text LLM inference synchronously (called from thread)."""
model_manager = ApiDependencies.invoker.services.model_manager
events = ApiDependencies.invoker.services.events
@@ -162,16 +166,18 @@ def _run_expand_prompt(
progress_callback = _make_progress_callback(events, task_id, user_id)
+ effective_seed = seed if seed is not None else get_random_seed()
output = pipeline.run(
prompt=prompt,
system_prompt=system_prompt or DEFAULT_SYSTEM_PROMPT,
max_new_tokens=max_tokens,
+ seed=effective_seed,
device=model_device,
dtype=TorchDevice.choose_torch_dtype(),
progress_callback=progress_callback,
)
- return output
+ return output, effective_seed
@utilities_router.post(
@@ -185,18 +191,19 @@ async def expand_prompt(current_user: CurrentUserOrDefault, body: ExpandPromptRe
"""Expand a brief prompt into a detailed image generation prompt using a text LLM."""
events = ApiDependencies.invoker.services.events
try:
- expanded = await asyncio.to_thread(
+ expanded, seed = await asyncio.to_thread(
_run_expand_prompt,
body.prompt,
body.model_key,
body.max_tokens,
body.system_prompt,
+ body.seed,
body.task_id,
current_user.user_id,
)
if body.task_id is not None:
events.emit_llm_task_complete(task_id=body.task_id, user_id=current_user.user_id)
- return ExpandPromptResponse(expanded_prompt=expanded)
+ return ExpandPromptResponse(expanded_prompt=expanded, seed=seed)
except UnknownModelException:
if body.task_id is not None:
events.emit_llm_task_error(task_id=body.task_id, user_id=current_user.user_id, error="Model not found")
diff --git a/invokeai/app/invocations/text_llm.py b/invokeai/app/invocations/text_llm.py
index 8308675cc0..036591bdd1 100644
--- a/invokeai/app/invocations/text_llm.py
+++ b/invokeai/app/invocations/text_llm.py
@@ -10,6 +10,7 @@ from invokeai.app.services.system_prompt_records.system_prompt_records_common im
SystemPromptNotFoundError,
SystemPromptRecordDTO,
)
+from invokeai.app.util.misc import SEED_MAX
from invokeai.backend.model_manager.taxonomy import ModelType
from invokeai.backend.text_llm_pipeline import DEFAULT_SYSTEM_PROMPT, TextLLMPipeline
from invokeai.backend.util.devices import TorchDevice
@@ -21,6 +22,7 @@ def _run_text_llm(
prompt: str,
system_prompt: str,
max_tokens: int,
+ seed: int,
) -> str:
"""Shared LLM invocation body used by every text-LLM node in this module."""
model_config = context.models.get_config(text_llm_model)
@@ -35,6 +37,7 @@ def _run_text_llm(
prompt=prompt,
system_prompt=system_prompt,
max_new_tokens=max_tokens,
+ seed=seed,
device=model_device,
dtype=TorchDevice.choose_torch_dtype(),
)
@@ -45,7 +48,7 @@ def _run_text_llm(
title="Text LLM",
tags=["llm", "text", "prompt"],
category="llm",
- version="1.0.0",
+ version="1.1.0",
classification=Classification.Beta,
)
class TextLLMInvocation(BaseInvocation):
@@ -72,6 +75,7 @@ class TextLLMInvocation(BaseInvocation):
le=2048,
description="Maximum number of tokens to generate.",
)
+ seed: int = InputField(default=0, ge=0, le=SEED_MAX, description=FieldDescriptions.seed)
@torch.no_grad()
def invoke(self, context: InvocationContext) -> StringOutput:
@@ -81,6 +85,7 @@ class TextLLMInvocation(BaseInvocation):
prompt=self.prompt,
system_prompt=self.system_prompt,
max_tokens=self.max_tokens,
+ seed=self.seed,
)
return StringOutput(value=output)
@@ -90,7 +95,7 @@ class TextLLMInvocation(BaseInvocation):
title="Text LLM (with System Prompt Preset)",
tags=["llm", "text", "prompt", "preset", "template"],
category="llm",
- version="1.0.0",
+ version="1.1.0",
classification=Classification.Beta,
)
class TextLLMWithPresetInvocation(BaseInvocation):
@@ -125,6 +130,7 @@ class TextLLMWithPresetInvocation(BaseInvocation):
le=2048,
description="Maximum number of tokens to generate.",
)
+ seed: int = InputField(default=0, ge=0, le=SEED_MAX, description=FieldDescriptions.seed)
def _resolve_system_prompt(self, context: InvocationContext) -> SystemPromptRecordDTO:
"""Resolve the referenced preset, enforcing the same access rules as the REST API.
@@ -169,5 +175,6 @@ class TextLLMWithPresetInvocation(BaseInvocation):
prompt=self.prompt,
system_prompt=record.content,
max_tokens=self.max_tokens,
+ seed=self.seed,
)
return StringOutput(value=output)
diff --git a/invokeai/backend/text_llm_pipeline.py b/invokeai/backend/text_llm_pipeline.py
index 740313385a..651be6c858 100644
--- a/invokeai/backend/text_llm_pipeline.py
+++ b/invokeai/backend/text_llm_pipeline.py
@@ -5,6 +5,7 @@ from typing import Callable
import torch
from transformers import PreTrainedModel, PreTrainedTokenizerBase, TextIteratorStreamer
+from transformers.generation.logits_process import LogitsProcessor
DEFAULT_SYSTEM_PROMPT = (
"You are an expert prompt writer for AI image generation. "
@@ -29,6 +30,102 @@ STREAM_TIMEOUT = 120.0
PROGRESS_EMIT_INTERVAL = 0.1
+_seeded_multinomial_state = threading.local()
+
+
+def _get_original_multinomial(multinomial):
+ """Unwrap a prior InvokeAI patch so module reloads do not stack wrappers."""
+ return getattr(multinomial, "_invokeai_original_multinomial", multinomial)
+
+
+_original_torch_multinomial = _get_original_multinomial(torch.multinomial)
+_original_tensor_multinomial = _get_original_multinomial(torch.Tensor.multinomial)
+
+
+class _SeededMultinomialMode:
+ """Use an invocation-local generator for multinomial sampling in this thread."""
+
+ def __init__(self, seed: int):
+ self._seed = seed
+ self._generators: dict[torch.device, torch.Generator] = {}
+ self._previous: "_SeededMultinomialMode | None" = None
+
+ def __enter__(self) -> "_SeededMultinomialMode":
+ self._previous = getattr(_seeded_multinomial_state, "active", None)
+ _seeded_multinomial_state.active = self
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback) -> None:
+ if self._previous is None:
+ del _seeded_multinomial_state.active
+ else:
+ _seeded_multinomial_state.active = self._previous
+
+ def _get_generator(self, device: torch.device) -> torch.Generator:
+ generator_device = torch.device("cpu") if device.type == "mps" else device
+ if generator_device not in self._generators:
+ self._generators[generator_device] = torch.Generator(device=generator_device).manual_seed(self._seed)
+ return self._generators[generator_device]
+
+
+def _sample_with_seed(input: torch.Tensor, args: tuple, kwargs: dict, original_multinomial) -> torch.Tensor:
+ mode: _SeededMultinomialMode | None = getattr(_seeded_multinomial_state, "active", None)
+ one_shot = False
+ if mode is None:
+ mode = getattr(_seeded_multinomial_state, "next_mode", None)
+ one_shot = mode is not None
+
+ try:
+ if mode is None or (kwargs.get("generator") is not None and not one_shot):
+ return original_multinomial(input, *args, **kwargs)
+
+ kwargs = dict(kwargs)
+ kwargs["generator"] = mode._get_generator(input.device)
+ if input.device.type != "mps":
+ return original_multinomial(input, *args, **kwargs)
+
+ # MPS has no usable device generator. Sampling on CPU keeps the invocation-local seed,
+ # then returns the selected token to the model device. Generation already synchronizes
+ # on each sampled token, so this is a correctness fallback rather than a fast path.
+ output = original_multinomial(input.cpu(), *args, **kwargs)
+ return output.to(input.device)
+ finally:
+ if one_shot:
+ _seeded_multinomial_state.__dict__.pop("next_mode", None)
+
+
+def _seeded_torch_multinomial(input: torch.Tensor, *args, **kwargs) -> torch.Tensor:
+ return _sample_with_seed(input, args, kwargs, _original_torch_multinomial)
+
+
+def _seeded_tensor_multinomial(input: torch.Tensor, *args, **kwargs) -> torch.Tensor:
+ return _sample_with_seed(input, args, kwargs, _original_tensor_multinomial)
+
+
+_seeded_torch_multinomial._invokeai_original_multinomial = _original_torch_multinomial
+_seeded_tensor_multinomial._invokeai_original_multinomial = _original_tensor_multinomial
+
+
+class _SeededMultinomialProcessor(LogitsProcessor):
+ """Arm seeded sampling for the multinomial call immediately after logits processing."""
+
+ def __init__(self, mode: _SeededMultinomialMode):
+ self._mode = mode
+
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
+ _seeded_multinomial_state.next_mode = self._mode
+ return scores
+
+
+# Transformers calls torch.multinomial directly today, while Tensor.multinomial is a supported
+# equivalent used by other callers. Install wrappers once so ordinary calls pay only a small
+# thread-local check; model forward operators are untouched.
+if torch.multinomial is not _seeded_torch_multinomial:
+ torch.multinomial = _seeded_torch_multinomial
+if torch.Tensor.multinomial is not _seeded_tensor_multinomial:
+ torch.Tensor.multinomial = _seeded_tensor_multinomial
+
+
class TextLLMPipeline:
"""A wrapper for a causal language model + tokenizer for text generation."""
@@ -41,6 +138,7 @@ class TextLLMPipeline:
prompt: str,
system_prompt: str = DEFAULT_SYSTEM_PROMPT,
max_new_tokens: int = 300,
+ seed: int = 0,
device: torch.device = torch.device("cpu"),
dtype: torch.dtype = torch.float16,
progress_callback: ProgressCallback | None = None,
@@ -83,6 +181,9 @@ class TextLLMPipeline:
temperature=0.7,
top_p=0.9,
streamer=streamer,
+ # Arm the generator only for Transformers' sampling call. Wrapping all of
+ # generate() in TorchFunctionMode intercepts every model-forward operator.
+ logits_processor=[_SeededMultinomialProcessor(_SeededMultinomialMode(seed))],
)
# model.generate blocks until done; run it in a thread so we can consume the
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index 5b633d1b1f..108308b33e 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -26473,6 +26473,20 @@
],
"title": "System Prompt"
},
+ "seed": {
+ "anyOf": [
+ {
+ "type": "integer",
+ "maximum": 4294967295.0,
+ "minimum": 0.0
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Seed",
+ "description": "Seed for reproducible text generation"
+ },
"task_id": {
"anyOf": [
{
@@ -26496,6 +26510,10 @@
"type": "string",
"title": "Expanded Prompt"
},
+ "seed": {
+ "type": "integer",
+ "title": "Seed"
+ },
"error": {
"anyOf": [
{
@@ -26509,7 +26527,7 @@
}
},
"type": "object",
- "required": ["expanded_prompt"],
+ "required": ["expanded_prompt", "seed"],
"title": "ExpandPromptResponse"
},
"ExposedField": {
@@ -84069,6 +84087,18 @@
"title": "Max Tokens",
"type": "integer"
},
+ "seed": {
+ "default": 0,
+ "description": "Seed for random number generation",
+ "field_kind": "input",
+ "input": "any",
+ "maximum": 4294967295,
+ "minimum": 0,
+ "orig_default": 0,
+ "orig_required": false,
+ "title": "Seed",
+ "type": "integer"
+ },
"type": {
"const": "text_llm",
"default": "text_llm",
@@ -84081,7 +84111,7 @@
"tags": ["llm", "text", "prompt"],
"title": "Text LLM",
"type": "object",
- "version": "1.0.0",
+ "version": "1.1.0",
"output": {
"$ref": "#/components/schemas/StringOutput"
}
@@ -84172,6 +84202,18 @@
"title": "Max Tokens",
"type": "integer"
},
+ "seed": {
+ "default": 0,
+ "description": "Seed for random number generation",
+ "field_kind": "input",
+ "input": "any",
+ "maximum": 4294967295,
+ "minimum": 0,
+ "orig_default": 0,
+ "orig_required": false,
+ "title": "Seed",
+ "type": "integer"
+ },
"type": {
"const": "text_llm_with_preset",
"default": "text_llm_with_preset",
@@ -84184,7 +84226,7 @@
"tags": ["llm", "text", "prompt", "preset", "template"],
"title": "Text LLM (with System Prompt Preset)",
"type": "object",
- "version": "1.0.0",
+ "version": "1.1.0",
"output": {
"$ref": "#/components/schemas/StringOutput"
}
diff --git a/invokeai/frontend/web/src/features/nodes/util/node/nodeUpdate.test.ts b/invokeai/frontend/web/src/features/nodes/util/node/nodeUpdate.test.ts
index 07d826c078..826e7b5d1e 100644
--- a/invokeai/frontend/web/src/features/nodes/util/node/nodeUpdate.test.ts
+++ b/invokeai/frontend/web/src/features/nodes/util/node/nodeUpdate.test.ts
@@ -91,7 +91,110 @@ const currentImageCollectionTemplate = {
},
} satisfies InvocationTemplate;
+const textLLMInputs = {
+ prompt: {
+ name: 'prompt',
+ title: 'Prompt',
+ required: false,
+ description: 'Input text prompt.',
+ fieldKind: 'input',
+ input: 'any',
+ ui_hidden: false,
+ type: { name: 'StringField', cardinality: 'SINGLE', batch: false },
+ default: '',
+ },
+ system_prompt: {
+ name: 'system_prompt',
+ title: 'System Prompt',
+ required: false,
+ description: 'System prompt that guides the model behavior.',
+ fieldKind: 'input',
+ input: 'any',
+ ui_hidden: false,
+ type: { name: 'StringField', cardinality: 'SINGLE', batch: false },
+ default: '',
+ },
+ text_llm_model: {
+ name: 'text_llm_model',
+ title: 'Text LLM Model',
+ required: true,
+ description: 'The text language model to use for text generation.',
+ fieldKind: 'input',
+ input: 'any',
+ ui_hidden: false,
+ type: { name: 'ModelIdentifierField', cardinality: 'SINGLE', batch: false },
+ default: undefined,
+ },
+ max_tokens: {
+ name: 'max_tokens',
+ title: 'Max Tokens',
+ required: false,
+ description: 'Maximum number of tokens to generate.',
+ fieldKind: 'input',
+ input: 'any',
+ ui_hidden: false,
+ type: { name: 'IntegerField', cardinality: 'SINGLE', batch: false },
+ default: 300,
+ },
+} satisfies InvocationTemplate['inputs'];
+
+const textLLMOutput = {
+ value: {
+ fieldKind: 'output',
+ name: 'value',
+ title: 'Value',
+ description: 'Generated text',
+ type: { name: 'StringField', cardinality: 'SINGLE', batch: false },
+ ui_hidden: false,
+ },
+} satisfies InvocationTemplate['outputs'];
+
+const oldTextLLMTemplate = {
+ title: 'Text LLM',
+ type: 'text_llm',
+ version: '1.0.0',
+ tags: ['llm', 'text'],
+ description: 'Run a text language model.',
+ outputType: 'string_output',
+ inputs: textLLMInputs,
+ outputs: textLLMOutput,
+ useCache: true,
+ nodePack: 'invokeai',
+ classification: 'beta',
+ category: 'llm',
+} satisfies InvocationTemplate;
+
+const currentTextLLMTemplate = {
+ ...oldTextLLMTemplate,
+ version: '1.1.0',
+ inputs: {
+ ...textLLMInputs,
+ seed: {
+ name: 'seed',
+ title: 'Seed',
+ required: false,
+ description: 'Seed for random number generation.',
+ fieldKind: 'input',
+ input: 'any',
+ ui_hidden: false,
+ type: { name: 'IntegerField', cardinality: 'SINGLE', batch: false },
+ default: 0,
+ },
+ },
+} satisfies InvocationTemplate;
+
describe('updateNode', () => {
+ it('adds the seeded default when updating a stored text_llm node', () => {
+ const node = buildInvocationNode({ x: 0, y: 0 }, oldTextLLMTemplate);
+ node.data.inputs.prompt!.value = 'a cat';
+
+ const updated = updateNode(node, currentTextLLMTemplate, { connectedInputNames: new Set() });
+
+ expect(updated.data.version).toBe('1.1.0');
+ expect(updated.data.inputs.prompt?.value).toBe('a cat');
+ expect(updated.data.inputs.seed?.value).toBe(0);
+ });
+
it('moves old image_collection direct collection values to the new images field', () => {
const node = buildInvocationNode({ x: 0, y: 0 }, oldImageCollectionTemplate);
const images = [{ image_name: 'first' }, { image_name: 'second' }];
diff --git a/invokeai/frontend/web/src/services/api/endpoints/utilities.ts b/invokeai/frontend/web/src/services/api/endpoints/utilities.ts
index 239cf568dd..2c81720576 100644
--- a/invokeai/frontend/web/src/services/api/endpoints/utilities.ts
+++ b/invokeai/frontend/web/src/services/api/endpoints/utilities.ts
@@ -17,11 +17,13 @@ type ExpandPromptRequest = {
model_key: string;
max_tokens?: number;
system_prompt?: string | null;
+ seed?: number | null;
task_id?: string | null;
};
type ExpandPromptResponse = {
expanded_prompt: string;
+ seed: number;
error?: string | null;
};
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index 2cfd6b40c5..4cf2aeb20e 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -10401,6 +10401,11 @@ export type components = {
max_tokens?: number;
/** System Prompt */
system_prompt?: string | null;
+ /**
+ * Seed
+ * @description Seed for reproducible text generation
+ */
+ seed?: number | null;
/**
* Task Id
* @description Client-supplied task ID used to correlate socket progress events to this request
@@ -10411,6 +10416,8 @@ export type components = {
ExpandPromptResponse: {
/** Expanded Prompt */
expanded_prompt: string;
+ /** Seed */
+ seed: number;
/** Error */
error?: string | null;
};
@@ -36686,6 +36693,12 @@ export type components = {
* @default 300
*/
max_tokens?: number;
+ /**
+ * Seed
+ * @description Seed for random number generation
+ * @default 0
+ */
+ seed?: number;
/**
* type
* @default text_llm
@@ -36747,6 +36760,12 @@ export type components = {
* @default 300
*/
max_tokens?: number;
+ /**
+ * Seed
+ * @description Seed for random number generation
+ * @default 0
+ */
+ seed?: number;
/**
* type
* @default text_llm_with_preset
diff --git a/tests/app/invocations/test_text_llm_with_preset.py b/tests/app/invocations/test_text_llm_with_preset.py
index e891beee83..c0f3b64528 100644
--- a/tests/app/invocations/test_text_llm_with_preset.py
+++ b/tests/app/invocations/test_text_llm_with_preset.py
@@ -13,7 +13,7 @@ import pytest
from invokeai.app.invocations.fields import SystemPromptField
from invokeai.app.invocations.model import ModelIdentifierField
-from invokeai.app.invocations.text_llm import TextLLMWithPresetInvocation
+from invokeai.app.invocations.text_llm import TextLLMInvocation, TextLLMWithPresetInvocation
from invokeai.app.services.system_prompt_records.system_prompt_records_common import (
SystemPromptNotFoundError,
)
@@ -26,9 +26,30 @@ def _make_invocation(prompt_id: str = "test-id") -> TextLLMWithPresetInvocation:
system_prompt=SystemPromptField(system_prompt_id=prompt_id),
text_llm_model=ModelIdentifierField(key="dummy", hash="x", name="dummy", base="any", type="text_llm"),
max_tokens=50,
+ seed=123,
)
+def test_plain_text_llm_node_passes_seed_to_llm() -> None:
+ inv = TextLLMInvocation(
+ id="test-node",
+ prompt="a cat",
+ system_prompt="system instruction",
+ text_llm_model=ModelIdentifierField(key="dummy", hash="x", name="dummy", base="any", type="text_llm"),
+ max_tokens=50,
+ seed=321,
+ )
+
+ with patch("invokeai.app.invocations.text_llm._run_text_llm", return_value="expanded") as mock_run:
+ result = inv.invoke(MagicMock())
+
+ assert result.value == "expanded"
+ assert mock_run.call_args.kwargs["prompt"] == "a cat"
+ assert mock_run.call_args.kwargs["system_prompt"] == "system instruction"
+ assert mock_run.call_args.kwargs["max_tokens"] == 50
+ assert mock_run.call_args.kwargs["seed"] == 321
+
+
def _make_context(
prompt_record_content: str | None,
*,
@@ -70,6 +91,7 @@ def test_preset_node_loads_content_from_db_and_passes_to_llm() -> None:
assert kwargs["system_prompt"] == "custom system instruction"
assert kwargs["prompt"] == "a cat"
assert kwargs["max_tokens"] == 50
+ assert kwargs["seed"] == 123
assert result.value == "expanded"
diff --git a/tests/backend/text_llm/test_text_llm_api_models.py b/tests/backend/text_llm/test_text_llm_api_models.py
index 99c1884acf..8b15c582fc 100644
--- a/tests/backend/text_llm/test_text_llm_api_models.py
+++ b/tests/backend/text_llm/test_text_llm_api_models.py
@@ -1,9 +1,19 @@
"""Tests for TextLLM API request/response models and validation."""
+from unittest.mock import MagicMock, patch
+
import pytest
+import torch
from pydantic import ValidationError
-from invokeai.app.api.routers.utilities import ExpandPromptRequest, ExpandPromptResponse, ImageToPromptRequest
+from invokeai.app.api.dependencies import ApiDependencies
+from invokeai.app.api.routers.utilities import (
+ ExpandPromptRequest,
+ ExpandPromptResponse,
+ ImageToPromptRequest,
+ _run_expand_prompt,
+)
+from invokeai.backend.model_manager.taxonomy import ModelType
class TestExpandPromptRequest:
@@ -11,6 +21,7 @@ class TestExpandPromptRequest:
req = ExpandPromptRequest(prompt="a cat", model_key="abc-123")
assert req.max_tokens == 300
assert req.system_prompt is None
+ assert req.seed is None
def test_max_tokens_upper_bound(self):
"""max_tokens should be capped at 2048."""
@@ -32,6 +43,11 @@ class TestExpandPromptRequest:
req = ExpandPromptRequest(prompt="a cat", model_key="abc-123", system_prompt="Be brief.")
assert req.system_prompt == "Be brief."
+ def test_seed_range(self):
+ assert ExpandPromptRequest(prompt="a cat", model_key="abc-123", seed=42).seed == 42
+ with pytest.raises(ValidationError):
+ ExpandPromptRequest(prompt="a cat", model_key="abc-123", seed=-1)
+
class TestImageToPromptRequest:
def test_defaults(self):
@@ -45,10 +61,37 @@ class TestImageToPromptRequest:
class TestExpandPromptResponse:
def test_success_response(self):
- resp = ExpandPromptResponse(expanded_prompt="A detailed scene")
+ resp = ExpandPromptResponse(expanded_prompt="A detailed scene", seed=42)
assert resp.expanded_prompt == "A detailed scene"
+ assert resp.seed == 42
assert resp.error is None
def test_error_response(self):
- resp = ExpandPromptResponse(expanded_prompt="", error="Model failed")
+ resp = ExpandPromptResponse(expanded_prompt="", seed=42, error="Model failed")
assert resp.error == "Model failed"
+
+
+def test_expand_prompt_uses_fresh_seed() -> None:
+ model_config = MagicMock(type=ModelType.TextLLM, path="model")
+ model = MagicMock()
+ model.parameters.side_effect = lambda: iter([torch.nn.Parameter(torch.zeros(1))])
+ loaded_model = MagicMock()
+ loaded_model.model_on_device.return_value.__enter__.return_value = (None, model)
+ services = MagicMock()
+ services.model_manager.store.get_model.return_value = model_config
+ services.model_manager.load.load_model.return_value = loaded_model
+
+ with (
+ patch.object(ApiDependencies, "invoker", MagicMock(services=services), create=True),
+ patch("invokeai.app.api.routers.utilities._resolve_model_path", return_value="model"),
+ patch("invokeai.app.api.routers.utilities.AutoTokenizer.from_pretrained"),
+ patch("invokeai.app.api.routers.utilities.get_random_seed", return_value=123),
+ patch("invokeai.app.api.routers.utilities.TextLLMPipeline") as pipeline_class,
+ ):
+ pipeline_class.return_value.run.return_value = "expanded"
+ assert _run_expand_prompt("cat", "model", 10, None, None, None, "user") == ("expanded", 123)
+ assert pipeline_class.return_value.run.call_args.kwargs["seed"] == 123
+
+ pipeline_class.return_value.run.reset_mock()
+ assert _run_expand_prompt("cat", "model", 10, None, 456, None, "user") == ("expanded", 456)
+ assert pipeline_class.return_value.run.call_args.kwargs["seed"] == 456
diff --git a/tests/backend/text_llm/test_text_llm_pipeline.py b/tests/backend/text_llm/test_text_llm_pipeline.py
index 08a3bcf57c..97919f0789 100644
--- a/tests/backend/text_llm/test_text_llm_pipeline.py
+++ b/tests/backend/text_llm/test_text_llm_pipeline.py
@@ -1,11 +1,16 @@
"""Tests for the TextLLMPipeline class."""
+import importlib
+import queue
import threading
from unittest.mock import MagicMock, patch
+import pytest
import torch
+from transformers import LlamaConfig, LlamaForCausalLM
-from invokeai.backend.text_llm_pipeline import DEFAULT_SYSTEM_PROMPT, TextLLMPipeline
+from invokeai.backend import text_llm_pipeline
+from invokeai.backend.text_llm_pipeline import DEFAULT_SYSTEM_PROMPT, TextLLMPipeline, _SeededMultinomialMode
def _make_mock_tokenizer(has_chat_template: bool = True) -> MagicMock:
@@ -42,6 +47,61 @@ class FakeStreamer:
return iter(self._chunks)
+class _TokenStreamer:
+ """Minimal streamer that exposes model-generated token ids as text chunks."""
+
+ def __init__(self, *args, **kwargs):
+ self._queue: queue.Queue[str | None] = queue.Queue()
+ self._skip_prompt = True
+
+ def put(self, value: torch.Tensor) -> None:
+ if self._skip_prompt:
+ self._skip_prompt = False
+ return
+ tokens = value.detach().cpu().reshape(-1).tolist()
+ self._queue.put(" ".join(str(token) for token in tokens) + " ")
+
+ def end(self) -> None:
+ self._queue.put(None)
+
+ def __iter__(self):
+ while (chunk := self._queue.get()) is not None:
+ yield chunk
+
+
+class _TokenBatch(dict):
+ def to(self, device: torch.device):
+ return _TokenBatch({key: value.to(device) for key, value in self.items()})
+
+
+class _TinyTokenizer:
+ chat_template = None
+
+ def __call__(self, prompt: str, return_tensors: str) -> _TokenBatch:
+ return _TokenBatch(input_ids=torch.tensor([[1, 2]], dtype=torch.long))
+
+ def encode(self, text: str, add_special_tokens: bool = False) -> list[str]:
+ return text.split()
+
+
+def _make_tiny_model() -> LlamaForCausalLM:
+ torch.manual_seed(123)
+ model = LlamaForCausalLM(
+ LlamaConfig(
+ vocab_size=32,
+ hidden_size=16,
+ intermediate_size=32,
+ num_hidden_layers=1,
+ num_attention_heads=2,
+ num_key_value_heads=2,
+ max_position_embeddings=64,
+ pad_token_id=0,
+ eos_token_id=None,
+ )
+ )
+ return model.eval()
+
+
def _patch_streamer(chunks: list[str] | None = None):
"""Patch TextIteratorStreamer in the pipeline module to return a FakeStreamer."""
chunks = chunks if chunks is not None else ["A detailed ", "landscape ", "with mountains"]
@@ -115,6 +175,239 @@ def test_pipeline_passes_generation_params():
assert "streamer" in generate_kwargs
+def test_seeded_multinomial_is_repeatable_despite_concurrent_global_rng_use():
+ """Unrelated RNG use must not alter sampling for a controlled seed."""
+ probabilities = torch.ones(100)
+ global_rng_state = torch.random.get_rng_state()
+
+ with _SeededMultinomialMode(seed=42):
+ expected = torch.multinomial(probabilities, num_samples=10, replacement=True)
+
+ assert torch.equal(torch.random.get_rng_state(), global_rng_state)
+
+ interference_done = threading.Event()
+
+ def _interfere() -> None:
+ torch.multinomial(probabilities, num_samples=10, replacement=True)
+ interference_done.set()
+
+ with _SeededMultinomialMode(seed=42):
+ thread = threading.Thread(target=_interfere)
+ thread.start()
+ assert interference_done.wait(timeout=1)
+ actual = torch.multinomial(probabilities, num_samples=10, replacement=True)
+ thread.join()
+
+ assert torch.equal(actual, expected)
+
+
+def test_seeded_multinomial_generator_advances_and_covers_tensor_method():
+ """A seeded context must advance one generator for both multinomial call forms."""
+ probabilities = torch.ones(100)
+
+ with _SeededMultinomialMode(seed=42):
+ first = torch.multinomial(probabilities, num_samples=100, replacement=True)
+ second = probabilities.multinomial(num_samples=100, replacement=True)
+ with _SeededMultinomialMode(seed=42):
+ method_repeat = probabilities.multinomial(num_samples=100, replacement=True)
+
+ assert not torch.equal(first, second)
+ assert torch.equal(first, method_repeat)
+
+
+def test_seeded_processor_consumes_seed_before_explicit_generator():
+ """A sampling call with an explicit generator still consumes the armed seed once."""
+ probabilities = torch.ones(100)
+ mode = text_llm_pipeline._SeededMultinomialMode(seed=42)
+ processor = text_llm_pipeline._SeededMultinomialProcessor(mode)
+ processor(torch.zeros((1, 1), dtype=torch.long), torch.zeros((1, 100)))
+
+ actual = torch.multinomial(
+ probabilities,
+ num_samples=100,
+ replacement=True,
+ generator=torch.Generator().manual_seed(1234),
+ )
+ with text_llm_pipeline._SeededMultinomialMode(seed=42):
+ expected = torch.multinomial(probabilities, num_samples=100, replacement=True)
+
+ assert torch.equal(actual, expected)
+ assert not hasattr(text_llm_pipeline._seeded_multinomial_state, "next_mode")
+
+
+def test_seeded_multinomial_patch_is_idempotent_on_reload():
+ """Reloading the module must not stack wrappers around torch.multinomial."""
+ original = text_llm_pipeline._original_torch_multinomial
+ importlib.reload(text_llm_pipeline)
+
+ assert text_llm_pipeline._original_torch_multinomial is original
+ with text_llm_pipeline._SeededMultinomialMode(seed=42):
+ samples = torch.multinomial(torch.ones(8), num_samples=4, replacement=True)
+ assert samples.shape == (4,)
+
+
+def test_pipeline_seeds_real_causal_lm_generation_end_to_end():
+ """The seed must cover the worker's real generate call, not only direct sampler tests."""
+ model = _make_tiny_model()
+ tokenizer = _TinyTokenizer()
+ pipeline = TextLLMPipeline(model, tokenizer)
+
+ with patch(
+ "invokeai.backend.text_llm_pipeline.TextIteratorStreamer",
+ _TokenStreamer,
+ ):
+ torch.manual_seed(1)
+ first = pipeline.run("test", max_new_tokens=12, seed=42, device=torch.device("cpu"), dtype=torch.float32)
+ torch.rand(100)
+ second = pipeline.run("test", max_new_tokens=12, seed=42, device=torch.device("cpu"), dtype=torch.float32)
+ third = pipeline.run("test", max_new_tokens=12, seed=43, device=torch.device("cpu"), dtype=torch.float32)
+
+ assert first == second
+ assert third != first
+ assert len(set(first.split())) > 1
+
+
+def test_pipeline_seeded_generations_are_isolated_when_concurrent():
+ """Concurrent production runs must match isolated runs for each seed."""
+ model = _make_tiny_model()
+ tokenizer = _TinyTokenizer()
+
+ def _run(seed: int) -> str:
+ return TextLLMPipeline(model, tokenizer).run(
+ "test", max_new_tokens=8, seed=seed, device=torch.device("cpu"), dtype=torch.float32
+ )
+
+ seeds = (42, 1234)
+ with patch("invokeai.backend.text_llm_pipeline.TextIteratorStreamer", _TokenStreamer):
+ expected = {seed: _run(seed) for seed in seeds}
+ barrier = threading.Barrier(len(seeds))
+ actual: dict[int, str] = {}
+ errors: list[BaseException] = []
+
+ def _run_concurrently(seed: int) -> None:
+ try:
+ barrier.wait(timeout=5)
+ actual[seed] = _run(seed)
+ except BaseException as e: # noqa: BLE001 - surface worker failures below
+ errors.append(e)
+
+ threads = [threading.Thread(target=_run_concurrently, args=(seed,), daemon=True) for seed in seeds]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join(timeout=10)
+
+ assert not errors
+ assert all(not thread.is_alive() for thread in threads)
+ assert actual == expected
+
+
[email protected](not torch.backends.mps.is_available(), reason="MPS is unavailable")
+def test_seeded_multinomial_is_repeatable_on_mps():
+ """MPS uses the CPU generator fallback and returns samples on the MPS device."""
+ try:
+ torch.mps.empty_cache()
+ probabilities = torch.ones(16, device="mps")
+ with _SeededMultinomialMode(seed=42):
+ first = torch.multinomial(probabilities, num_samples=4, replacement=True)
+ with _SeededMultinomialMode(seed=42):
+ second = probabilities.multinomial(num_samples=4, replacement=True)
+ except RuntimeError as e:
+ if "mps backend out of memory" in str(e).lower():
+ pytest.skip("MPS does not have enough memory for this test")
+ raise
+ finally:
+ torch.mps.empty_cache()
+
+ assert first.device.type == "mps"
+ assert torch.equal(first.cpu(), second.cpu())
+
+
[email protected](not torch.backends.mps.is_available(), reason="MPS is unavailable")
+def test_pipeline_seeds_real_causal_lm_generation_on_mps():
+ """The production pipeline must use the CPU generator fallback on MPS."""
+ model = None
+ pipeline = None
+ try:
+ torch.mps.empty_cache()
+ model = _make_tiny_model().to("mps")
+ pipeline = TextLLMPipeline(model, _TinyTokenizer())
+ with patch("invokeai.backend.text_llm_pipeline.TextIteratorStreamer", _TokenStreamer):
+ first = pipeline.run("test", max_new_tokens=4, seed=42, device=torch.device("mps"), dtype=torch.float32)
+ second = pipeline.run("test", max_new_tokens=4, seed=42, device=torch.device("mps"), dtype=torch.float32)
+ except RuntimeError as e:
+ if "mps backend out of memory" in str(e).lower():
+ pytest.skip("MPS does not have enough memory for this test")
+ raise
+ finally:
+ del pipeline
+ del model
+ torch.mps.empty_cache()
+
+ assert first == second
+
+
+def test_seeded_multinomial_contexts_are_isolated_when_interleaved_on_cpu():
+ """Concurrent seeded contexts must retain independent RNG sequences."""
+ probabilities = torch.arange(1, 101, dtype=torch.float32)
+ seeds = (42, 1234)
+ draw_count = 100
+
+ expected: dict[int, list[int]] = {}
+ for seed in seeds:
+ with _SeededMultinomialMode(seed=seed):
+ expected[seed] = [torch.multinomial(probabilities, num_samples=1).item() for _ in range(draw_count)]
+
+ barrier = threading.Barrier(len(seeds))
+ actual: dict[int, list[int]] = {}
+
+ def _sample(seed: int) -> None:
+ samples: list[int] = []
+ with _SeededMultinomialMode(seed=seed):
+ for _ in range(draw_count):
+ barrier.wait(timeout=5)
+ samples.append(torch.multinomial(probabilities, num_samples=1).item())
+ actual[seed] = samples
+
+ threads = [threading.Thread(target=_sample, args=(seed,), daemon=True) for seed in seeds]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join(timeout=5)
+
+ assert all(not thread.is_alive() for thread in threads)
+ assert actual == expected
+
+
+def test_stalled_generation_does_not_block_later_generation(monkeypatch: pytest.MonkeyPatch):
+ """A timed-out worker must not own shared state needed by later runs."""
+ monkeypatch.setattr(text_llm_pipeline, "STREAM_TIMEOUT", 0.05)
+ stalled_model = MagicMock()
+ release_stalled_model = threading.Event()
+ stalled_model.generate.side_effect = lambda **kwargs: release_stalled_model.wait()
+
+ with pytest.raises(RuntimeError, match="Text generation stalled"):
+ TextLLMPipeline(stalled_model, _make_mock_tokenizer()).run("test", device=torch.device("cpu"))
+
+ healthy_model = MagicMock()
+
+ def _generate(**kwargs):
+ streamer = kwargs["streamer"]
+ streamer.put(torch.tensor([[1, 2, 3, 4, 5]]))
+ streamer.put(torch.tensor([6]))
+ streamer.end()
+
+ healthy_model.generate.side_effect = _generate
+ healthy_tokenizer = _make_mock_tokenizer()
+ healthy_tokenizer.decode.return_value = "ok"
+ try:
+ TextLLMPipeline(healthy_model, healthy_tokenizer).run("test", device=torch.device("cpu"))
+ finally:
+ release_stalled_model.set()
+
+ healthy_model.generate.assert_called_once()
+
+
def test_pipeline_returns_joined_streamed_chunks():
"""Pipeline should return the concatenated, stripped streamer output."""
tokenizer = _make_mock_tokenizer(has_chat_template=True)