Skip to content
Python

added custom text encoder support for ltx2 + auto recovery for failed lora pinning

DeepBeepMeepf1c17f2a439d
diff --git a/README.md b/README.md
index 86d8a62..d4c18fe 100644
--- a/README.md
+++ b/README.md
@@ -37,7 +37,7 @@ WanGP supports the Wan (and derived models), Hunyuan Video and LTV Video models
## 🔥 Latest Updates :
-### January 11th 2026: WanGP v10.20, When there is no VRAM left there is still some VRAM left ...
+### January 12th 2026: WanGP v10.22, When there is no VRAM left there is still some VRAM left ...
- **LTX 2 - SUPER VRAM OPTIMIZATIONS**
@@ -57,11 +57,16 @@ After much suffering I have managed to reduce by at least 1/3 the VRAM requireme
Use a *Control Video* to transfer *Pose*, *Depth*, *Canny Edges*. I have added some extra tweaks: with WanGP you can restrict the transfer to a *masked area*, define a *denoising strength* (how much the control video is going to be followed) and a *masking strength* (how much unmasked area is impacted)
-- **Start Image Strength**: if you set values lower than 1 you may to reduce the static image effect, you get sometime with LTX2 i2v
+- **Start Image Strength**: This new slider will appear below a *Start Image* or Source *Video*. If you set it to values lower than 1 you may to reduce the static image effect, you get sometime with LTX2 i2v
-- **Max Loras Pinned Slider**: Some users (with usually PC with less than 64 GB of RAM) have reported Out Of Memory although the model seemed to load just fine when starting a gen with Loras. This is sometime related to WanGP attempting (and failing due to unsufficient reserved RAM) to pin the Loras to Reserved Memory for faster gen. I have added a Slider at the bottom of the *Configuration* / *Performance* tab that you can use to prevent WanGP from Pinning Loras (to do so set it to 0). This may solve the oom crashes with *LTX2 Default (non distilled)*
+- **Custom Gemma Text Encoder for LTX 2**: As a practical case, the *Heretic* text encoder is now supported by WanGP. Check the *finetune* doc, but in short create a *finetune* that has a *text_encoder_URLS* key that contains a list of one or more file paths or URLs.
-*update 10.21*: added slider Loras Max Pinning slider
+- **Experimental Auto Recovery Failed Lora Pin**: Some users (with usually PC with less than 64 GB of RAM) have reported Out Of Memory although a model seemed to load just fine when starting a gen with Loras. This is sometime related to WanGP attempting (and failing due to unsufficient reserved RAM) to pin the Loras to Reserved Memory for faster gen. I have experimented a recovery mode that should release sufficient ressources to continue the Video Gen. This may solve the oom crashes with *LTX2 Default (non distilled)*
+
+- **Max Loras Pinned Slider**: If the Auto Recovery Mode is still not sufficient, I have added a Slider at the bottom of the *Configuration* / *Performance* tab that you can use to prevent WanGP from Pinning Loras (to do so set it to 0). As if there is no loading attempt there wont be any crash...
+
+*update 10.21*: added slider Loras Max Pinning slider\
+*update 10.22*: added support for custom Ltx2 Text Encoder + Auto Recovery mode if Lora Pinning failed
### January 9st 2026: WanGP v10.11, Spoiled again
diff --git a/models/ltx2/ltx2_handler.py b/models/ltx2/ltx2_handler.py
index bd09438..1ed3ed3 100644
--- a/models/ltx2/ltx2_handler.py
+++ b/models/ltx2/ltx2_handler.py
@@ -234,6 +234,7 @@ class family_handler:
"sliding_window_overlap": 17,
"denoising_strength": 1.0,
"masking_strength": 0,
+ "audio_prompt_type": "",
}
)
ui_defaults.setdefault("audio_scale", 1.0)
diff --git a/models/ltx2/ltx_core/loader/single_gpu_model_builder.py b/models/ltx2/ltx_core/loader/single_gpu_model_builder.py
index 6cbde6d..40cc5bf 100644
--- a/models/ltx2/ltx_core/loader/single_gpu_model_builder.py
+++ b/models/ltx2/ltx_core/loader/single_gpu_model_builder.py
@@ -143,7 +143,7 @@ class SingleGPUModelBuilder(Generic[ModelType], ModelBuilderProtocol[ModelType],
default_dtype=dtype or torch.bfloat16,
ignore_missing_keys=self.ignore_missing_keys,
)
- return self._return_model(meta_model, device)
+ return self._return_model(meta_model, device)
model_paths = self.model_path if isinstance(self.model_path, tuple) else [self.model_path]
model_state_dict = self.load_sd(model_paths, sd_ops=self.model_sd_ops, registry=self.registry, device=device)
@@ -152,25 +152,22 @@ class SingleGPUModelBuilder(Generic[ModelType], ModelBuilderProtocol[ModelType],
quantization_map = {}
post_load_hooks = []
- try:
- from mmgp import offload as mmgp_offload
- from mmgp.quant_router import apply_pre_quantization, detect_and_convert
-
- conv_result = detect_and_convert(sd, default_dtype=dtype or torch.bfloat16, verboseLevel=0)
- sd = conv_result.get("state_dict", sd)
- quantization_map = conv_result.get("quant_map", {}) or {}
+ from mmgp import offload as mmgp_offload
+ from mmgp.quant_router import apply_pre_quantization, detect_and_convert
+
+ conv_result = detect_and_convert(sd, default_dtype=dtype or torch.bfloat16, verboseLevel=0)
+ sd = conv_result.get("state_dict", sd)
+ quantization_map = conv_result.get("quant_map", {}) or {}
+ if quantization_map:
+ quantization_map, post_load_hooks = apply_pre_quantization(
+ meta_model,
+ sd,
+ quantization_map,
+ default_dtype=dtype,
+ verboseLevel=0,
+ )
if quantization_map:
- quantization_map, post_load_hooks = apply_pre_quantization(
- meta_model,
- sd,
- quantization_map,
- default_dtype=dtype,
- verboseLevel=0,
- )
- if quantization_map:
- mmgp_offload._requantize(meta_model, sd, quantization_map, default_dtype=dtype)
- except Exception as exc:
- logger.warning("Quantization handler skipped: %s", exc)
+ mmgp_offload._requantize(meta_model, sd, quantization_map, default_dtype=dtype)
if dtype is not None and not quantization_map:
sd = {key: value.to(dtype=dtype) for key, value in sd.items()}
diff --git a/models/ltx2/ltx_core/text_encoders/gemma/encoders/base_encoder.py b/models/ltx2/ltx_core/text_encoders/gemma/encoders/base_encoder.py
index 1e157b6..e2028c9 100644
--- a/models/ltx2/ltx_core/text_encoders/gemma/encoders/base_encoder.py
+++ b/models/ltx2/ltx_core/text_encoders/gemma/encoders/base_encoder.py
@@ -12,7 +12,7 @@ from ..embeddings_connector import Embeddings1DConnector
from ..feature_extractor import GemmaFeaturesExtractorProjLinear
from ..tokenizer import LTXVGemmaTokenizer
from shared.utils import files_locator as fl
-from .....ltx2_handler import _GEMMA_FOLDER
+from .....ltx2_handler import _GEMMA_FOLDER, get_text_encoder_name
import os
@@ -319,15 +319,54 @@ def _find_merged_gemma_file(gemma_root: str) -> str | None:
def module_ops_from_gemma_root(gemma_root: str) -> tuple[ModuleOps, ...]:
gemma_path = gemma_root
gemma_root = os.path.dirname(gemma_root)
- tokenizer_path = fl.locate_file(_GEMMA_FOLDER, "tokenizer.model")
+ tokenizer_path = fl.locate_folder(os.path.join(_GEMMA_FOLDER)) #, "tokenizer.model"
def load_gemma(module: GemmaTextEncoderModelBase) -> GemmaTextEncoderModelBase:
- config_path = fl.locate_file(_GEMMA_FOLDER, "config.json")
+ def preprocess_sd(sd):
+ if len(sd) == 0:
+ return sd
+ first = next(iter(sd))
+ if any(first.startswith(prefix) for prefix in ["model.embed", "embed.layers"]):
+ sd.pop('spiece_model', None)
+ new_sd = {}
+ for k,v in sd.items():
+ if "model." in k:
+ k = k.replace("model.", "model.language_model.")
+ else:
+ k = "model." + k
+ new_sd[k] = v
+ sd = new_sd
+ submodels_prefixes = {"model.language_model": 0,"model.vision_tower": 0, "model.multi_modal_projector":0}
+ for k,v in sd.items():
+ pop = False
+ for prefix in submodels_prefixes:
+ if k.startswith(prefix):
+ pop =True
+ break
+ if pop:
+ del submodels_prefixes[prefix]
+ if len(submodels_prefixes)==0:
+ break
+
+ if len(submodels_prefixes):
+ original_text_encoder = fl.locate_file( os.path.join(_GEMMA_FOLDER, get_text_encoder_name("int8")), error_if_none=False)
+ if original_text_encoder is None :
+ original_text_encoder = fl.locate_file(os.path.join(_GEMMA_FOLDER, get_text_encoder_name("bf16")), error_if_none=True)
+ from mmgp.offload import load_sd
+ ori_sd, ori_qm, ori_twm = load_sd(original_text_encoder, list(submodels_prefixes.keys()), keep_prefixes= True, writable_tensors=False)
+ if ori_twm is None:
+ ori_twm = {'model.language_model.embed_tokens.weight': ['lm_head.weight']}
+ sd.update(ori_sd)
+ return sd, ori_qm, ori_twm
+ return sd
+
+ config_path = fl.locate_file(os.path.join(_GEMMA_FOLDER, "config.json"))
module.model = offload.fast_load_transformers_model(
gemma_path,
modelClass=Gemma3ForConditionalGeneration,
defaultConfigPath=config_path,
writable_tensors=False,
+ preprocess_sd = preprocess_sd,
)
module._gemma_root = module._gemma_root or gemma_root
return module
diff --git a/requirements.txt b/requirements.txt
index 4fa9024..8bc32a4 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -57,7 +57,7 @@ pydantic==2.10.6
# Math & modeling
torchdiffeq>=0.2.5
tensordict>=0.6.1
-mmgp==3.6.12
+mmgp==3.6.13
peft==0.15.0
matplotlib
diff --git a/wgp.py b/wgp.py
index 122bf22..60fc76b 100644
--- a/wgp.py
+++ b/wgp.py
@@ -84,8 +84,8 @@ AUTOSAVE_PATH = AUTOSAVE_FILENAME
AUTOSAVE_TEMPLATE_PATH = AUTOSAVE_FILENAME
CONFIG_FILENAME = "wgp_config.json"
PROMPT_VARS_MAX = 10
-target_mmgp_version = "3.6.12"
-WanGP_version = "10.21"
+target_mmgp_version = "3.6.13"
+WanGP_version = "10.22"
settings_version = 2.43
max_source_video_frames = 3000
prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer = None, None, None, None
@@ -136,35 +136,7 @@ def clear_gen_cache():
if "_cache" in offload.shared_state:
del offload.shared_state["_cache"]
-def _flush_torch_memory():
- gc.collect()
- if torch.cuda.is_available():
- try:
- torch.cuda.synchronize()
- except torch.cuda.CudaError:
- pass
- for idx in range(torch.cuda.device_count()):
- with torch.cuda.device(idx):
- torch.cuda.empty_cache()
- torch.cuda.ipc_collect()
- torch.cuda.reset_peak_memory_stats()
- try:
- torch._C._host_emptyCache()
- except AttributeError:
- pass
- if os.name == "nt":
- try:
- import ctypes, ctypes.wintypes as wintypes, os as _os
- PROCESS_SET_QUOTA = 0x0100
- PROCESS_QUERY_INFORMATION = 0x0400
- kernel32 = ctypes.windll.kernel32
- psapi = ctypes.windll.psapi
- handle = kernel32.OpenProcess(PROCESS_SET_QUOTA | PROCESS_QUERY_INFORMATION, False, _os.getpid())
- if handle:
- psapi.EmptyWorkingSet(handle)
- kernel32.CloseHandle(handle)
- except Exception:
- pass
+
def release_model():
global wan_model, offloadobj, reload_needed
@@ -175,12 +147,7 @@ def release_model():
if offloadobj is not None:
offloadobj.release()
offloadobj = None
- _flush_torch_memory()
- from accelerate import init_empty_weights
- with init_empty_weights():
- for _ in range(3):
- dummy_tensor = torch.nn.Embedding(256384, 1024)
- dummy_tensor = None
+ offload.flush_torch_caches()
reload_needed = True
def get_unique_id():
global unique_id
@@ -2885,28 +2852,6 @@ def save_quantized_model(model, model_type, model_filename, dtype, config_file,
writer.write(json.dumps(saved_finetune_def, indent=4))
print(f"The '{finetune_file}' definition file has been automatically updated with the local path to the new quantized model.")
-def save_gemma_text_encoder_files(wan_model, output_dir = "c:\\temp", send_cmd = None):
- text_encoder = getattr(wan_model, "text_encoder", None)
- if text_encoder is None:
- return
- gemma_root = getattr(text_encoder, "_gemma_root", None)
- gemma_model = getattr(text_encoder, "model", None)
- if gemma_root is None or gemma_model is None:
- return
-
- os.makedirs(output_dir, exist_ok=True)
- base_name = os.path.basename(os.path.normpath(gemma_root))
- merged_path = os.path.join(output_dir, f"{base_name}.safetensors")
- quant_path = os.path.join(output_dir, f"{base_name}_quanto_bf16_int8.safetensors")
- config_path = os.path.join(gemma_root, "config.json")
- if not os.path.isfile(config_path):
- config_path = None
-
- if send_cmd is not None:
- send_cmd("info", f"Saving Gemma weights to '{merged_path}' and quantized to '{quant_path}'.")
-
- offload.save_model(gemma_model, merged_path, config_file_path=config_path)
- offload.save_model(gemma_model, quant_path, config_file_path=config_path, do_quantize=True)
def get_loras_preprocessor(transformer, model_type):
preprocessor = getattr(transformer, "preprocess_loras", None)
@@ -5330,7 +5275,12 @@ def generate_video(
send_cmd("status", "Model loaded")
reload_needed= False
if args.test:
- save_gemma_text_encoder_files(wan_model, send_cmd=send_cmd)
+ skip_gemma_save = os.environ.get("WAN2GP_SKIP_GEMMA_SAVE", "").strip().lower() in (
+ "1",
+ "true",
+ "yes",
+ "on",
+ )
send_cmd("info", "Test mode: model loaded, skipping generation.")
return
overridden_attention = get_overridden_attention(model_type)
@@ -9219,10 +9169,10 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
)
any_audio_prompt = model_def.get("any_audio_prompt", False)
- audio_prompt_type_value = ui_get("audio_prompt_type", "A" if any_audio_prompt else "")
+ audio_prompt_type_sources_def = model_def.get("audio_prompt_type_sources", None)
+ audio_prompt_type_value = ui_get("audio_prompt_type", "A" if any_audio_prompt and audio_prompt_type_sources_def is None else "")
any_multi_speakers = False
if any_audio_prompt:
- audio_prompt_type_sources_def = model_def.get("audio_prompt_type_sources", None)
any_single_speaker = not model_def.get("multi_speakers_only", False)
any_multi_speakers = not model_def.get("one_speaker_only", False) and not audio_only
audio_prompt_type_sources_labels_all = {