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
fix(ltx2): answer both transformers warnings on the Gemma-4 tokenizer load
Lincoln Stein259e02cd8eae
diff --git a/invokeai/backend/model_manager/load/model_loaders/ltx2.py b/invokeai/backend/model_manager/load/model_loaders/ltx2.pyindex cb380ca898..4765d7e256 100644--- a/invokeai/backend/model_manager/load/model_loaders/ltx2.py+++ b/invokeai/backend/model_manager/load/model_loaders/ltx2.py@@ -22,7 +22,10 @@ reserves what a cast will produce *before* widening a tensor."""import json-from collections.abc import Callable+import logging+import threading+from collections.abc import Callable, Iterator+from contextlib import contextmanagerfrom pathlib import Pathfrom typing import Any, Optional@@ -80,6 +83,48 @@ _ENCODER_SUPPORTED_NOTE = ()_COMPONENT_SUPPORTED_NOTE = "LTX-2 component files (VAEs, vocoder, connectors, upsamplers) must be unquantized."+# ``AutoTokenizer`` sniffs the folder's ``config.json`` before it reads ``tokenizer_config.json``.+# The release declares ``gemma4_unified_text``, which this transformers version does not register,+# so ``AutoConfig`` raises and the fallback builds the base ``PreTrainedConfig``, whose+# ``model_type`` is "" -- reported at warning level as "You are using a model of type+# `gemma4_unified_text` to instantiate a model of type ``". That sniffed config is then discarded:+# the tokenizer class comes from ``tokenizer_config.json``, which names ``GemmaTokenizer``.+#+# The marker names the released type because the same line reports every unregistered one, with the+# declared type interpolated: the probe in ``configs/gemma4_encoder.py`` also matches a folder on+# ``architectures`` alone, so a repack declaring something else must keep the one message that names+# what it declares. The filter sits on the emitting logger so it runs in ``Logger.handle``, before+# the record reaches transformers' own handler (transformers attaches one to its root logger and,+# outside CI, does not propagate to InvokeAI's), and is scoped to the loading thread because+# verbosity is process-global and loads run alongside generation and the image index worker.+_CONFIG_LOGGER_NAME = "transformers.configuration_utils"+_RELEASE_MODEL_TYPE = "gemma4_unified_text"+_UNREGISTERED_MODEL_TYPE_MARKER = f"model of type `{_RELEASE_MODEL_TYPE}` to instantiate"++_tokenizer_load = threading.local()+++class _UnregisteredModelTypeFilter(logging.Filter):+ def filter(self, record: logging.LogRecord) -> bool:+ if not getattr(_tokenizer_load, "active", False):+ return True+ return _UNREGISTERED_MODEL_TYPE_MARKER not in record.getMessage()+++logging.getLogger(_CONFIG_LOGGER_NAME).addFilter(_UnregisteredModelTypeFilter())+++@contextmanager+def _quiet_unregistered_model_type() -> Iterator[None]:+ """Drop the config-sniff mismatch warning for a tokenizer load made on this thread."""+ previously_active = getattr(_tokenizer_load, "active", False)+ _tokenizer_load.active = True+ try:+ yield+ finally:+ _tokenizer_load.active = previously_active++_ROLE_LABELS = {layout.ROLE_VIDEO_VAE: "video VAE",layout.ROLE_AUDIO_VAE: "audio VAE",@@ -458,7 +503,15 @@ class LTX2Gemma4EncoderModel(ModelLoader):case SubModelType.Tokenizer:from transformers import AutoTokenizer- return AutoTokenizer.from_pretrained(root, local_files_only=True)+ # ``fix_mistral_regex=False``: transformers' Mistral-regex heuristic short-circuits on+ # the sibling ``config.json``'s ``transformers_version``, which the release does not+ # carry, so it advises the fix for this folder whatever the model is. Taking the advice+ # prepends the Tekken split regex to Gemma's pre-tokenizer and shatters words+ # ("inconsistent" becomes "in" + "consistent"), which would mis-tokenize every prompt.+ # Passing it explicitly keeps the released pre-tokenizer -- what the reference+ # pipelines encode with -- and states the decision instead of repeating the advice.+ with _quiet_unregistered_model_type():+ return AutoTokenizer.from_pretrained(root, local_files_only=True, fix_mistral_regex=False)case SubModelType.TextEncoder:return self._load_text_encoder(root / config.weight_file, root / "config.json")case _:diff --git a/tests/backend/ltx2/test_ltx2_real_files.py b/tests/backend/ltx2/test_ltx2_real_files.pyindex 9c143c4a88..1c137da82a 100644--- a/tests/backend/ltx2/test_ltx2_real_files.py+++ b/tests/backend/ltx2/test_ltx2_real_files.py@@ -140,6 +140,28 @@ def test_the_gemma4_tower_runs_and_yields_all_forty_nine_hidden_states() -> Noneassert not torch.allclose(out.hidden_states[-1].float(), out.hidden_states[0].float(), atol=1.0)+ SNAPSHOT is None or not (SNAPSHOT / "gemma4-12b-ltx-v1" / "tokenizer.json").exists(),+ reason="the Gemma-4 tokenizer is not in the Hugging Face cache",+)+def test_the_released_tokenizer_keeps_the_words_the_mistral_fix_would_shatter() -> None:+ """transformers advises the Mistral regex fix for this folder. Taking it prepends the Tekken+ split regex to Gemma's pre-tokenizer, which fragments words this vocabulary has whole -- every+ prompt would then encode differently from what the reference pipelines feed the tower. The+ synthetic folder in the loader suite pins the warnings; this pins the tokenization itself."""+ root = SNAPSHOT / "gemma4-12b-ltx-v1"+ config = Gemma4Encoder_Gemma4Encoder_LTX2_Config.model_construct(+ path=str(root), subfolder="", weight_file="gemma4-12b-ltx-v1_bf16.safetensors"+ )+ tokenizer = _loader(LTX2Gemma4EncoderModel)._load_model(config, SubModelType.Tokenizer)++ tokens = tokenizer.convert_ids_to_tokens(+ tokenizer("worst quality, inconsistent motion, blurry, jittery, distorted").input_ids+ )+ # Exactly the words the Mistral split shatters ("in"+"consistent", "bl"+"urry", "dist"+"orted").+ assert {"\u2581inconsistent", "\u2581blurry", "\u2581distorted"} <= set(tokens)++@requires_weightsdef test_the_mirror_s_nvfp4_transformer_is_refused_for_naming_no_layer() -> None:"""WanGP's nvfp4 repack carries no marker and no header entry for its 1176 packed layers, so thediff --git a/tests/backend/model_manager/load/test_ltx2_loader.py b/tests/backend/model_manager/load/test_ltx2_loader.pyindex da06d8456d..2ad939ebf0 100644--- a/tests/backend/model_manager/load/test_ltx2_loader.py+++ b/tests/backend/model_manager/load/test_ltx2_loader.py@@ -9,6 +9,7 @@ and ``dtypes_at_make_room`` (the working dict's dtypes when room was first made)"""import json+import loggingfrom pathlib import Pathfrom types import SimpleNamespace@@ -488,6 +489,101 @@ def test_the_tokenizer_comes_from_the_same_folder(monkeypatch, tmp_path) -> Noneassert calls == [tmp_path / "gemma4-12b-ltx-v1"]+def unregistered_tokenizer_folder(tmp_path: Path) -> Path:+ """A folder that trips both of the heuristics the released Gemma-4 encoder trips.++ Real transformers, no weights: an unregistered ``model_type`` so ``AutoConfig`` falls back to the+ base config, no ``transformers_version`` so the Mistral-regex heuristic cannot short-circuit, and+ a vocabulary over 100k with a pre-tokenizer, which is what gates that heuristic at all. Written+ here rather than mocked so the warnings are the ones transformers actually emits: a reworded+ message or a renamed kwarg has to fail a test instead of silently returning the noise.+ """+ from tokenizers import Tokenizer, models, pre_tokenizers++ root = tmp_path / "gemma4-12b-ltx-v1"+ root.mkdir()+ tokenizer = Tokenizer(models.WordLevel(vocab={f"t{i}": i for i in range(100_002)}, unk_token="t0"))+ tokenizer.pre_tokenizer = pre_tokenizers.Whitespace()+ tokenizer.save(str(root / "tokenizer.json"))+ (root / "tokenizer_config.json").write_text(+ json.dumps({"tokenizer_class": "PreTrainedTokenizerFast", "unk_token": "t0"})+ )+ (root / "config.json").write_text(+ json.dumps({"model_type": "gemma4_unified_text", "architectures": ["Gemma4UnifiedForCausalLM"]})+ )+ return root+++def transformers_warnings():+ """Every warning transformers emits, with its verbosity pinned so the capture cannot go empty."""+ import transformers++ logger = logging.getLogger("transformers")+ captured: list[str] = []++ class Capture(logging.Handler):+ def emit(self, record: logging.LogRecord) -> None:+ if record.levelno >= logging.WARNING:+ captured.append(record.getMessage())++ handler = Capture()+ previous = transformers.utils.logging.get_verbosity()+ transformers.utils.logging.set_verbosity_warning()+ logger.addHandler(handler)+ try:+ yield captured+ finally:+ logger.removeHandler(handler)+ transformers.utils.logging.set_verbosity(previous)+++def test_the_release_s_two_tokenizer_warnings_are_both_answered(unregistered_tokenizer_folder, transformers_warnings):+ """One is noise about a config that is discarded; the other is advice that would mis-tokenize+ every prompt if taken. Loading the same folder directly is the baseline: both fire there, so an+ empty capture after the loader means they were answered, not that they never happen."""+ from transformers import AutoTokenizer++ direct = AutoTokenizer.from_pretrained(unregistered_tokenizer_folder, local_files_only=True)+ baseline = list(transformers_warnings)+ assert sum("to instantiate a model of type" in message for message in baseline) == 1+ assert sum("fix_mistral_regex=True" in message for message in baseline) == 1++ transformers_warnings.clear()+ loader = object.__new__(LTX2Gemma4EncoderModel)+ config = Gemma4Encoder_Gemma4Encoder_LTX2_Config.model_construct(+ path=str(unregistered_tokenizer_folder.parent), subfolder="gemma4-12b-ltx-v1", weight_file="te.safetensors"+ )+ tokenizer = loader._load_model(config, SubModelType.Tokenizer)++ assert transformers_warnings == []+ # Declining the advice is not the same as taking it: the pre-tokenizer is the released one.+ assert str(tokenizer._tokenizer.pre_tokenizer) == str(direct._tokenizer.pre_tokenizer)+++def test_a_mismatch_naming_another_model_type_survives_the_tokenizer_load(+ unregistered_tokenizer_folder, transformers_warnings+):+ """The probe matches a folder on its ``architectures`` alone, so a repack can declare anything.+ The message naming what it declares is the only signal at load time that it is not the release,+ and dropping the whole family of mismatch messages would eat it."""+ logger = logging.getLogger(ltx2._CONFIG_LOGGER_NAME)+ other = "You are using a model of type `mystery_arch_v9` to instantiate a model of type ``."++ with ltx2._quiet_unregistered_model_type():+ logger.warning(other)+ assert transformers_warnings == [other]++ transformers_warnings.clear()+ from transformers import AutoTokenizer++ AutoTokenizer.from_pretrained(unregistered_tokenizer_folder, local_files_only=True)+ assert any("to instantiate a model of type" in message for message in transformers_warnings), (+ "the release's own mismatch reaches the log outside a tokenizer load"+ )++def test_the_encoder_sizes_its_weight_file_one_directory_down(tmp_path) -> None:nested = tmp_path / "gemma4-12b-ltx-v1"nested.mkdir()