Python
added gguf support, models manager plugin, ltx2 contol video+audio mode
DeepBeepMeep38ef34078013
diff --git a/README.md b/README.mdindex affe740..2669388 100644--- a/README.md+++ b/README.md@@ -5,16 +5,19 @@<b>WanGP by DeepBeepMeep : The best Open Source Video Generative Models Accessible to the GPU Poor</b></p>-WanGP supports the Wan (and derived models), Hunyuan Video and LTV Video models with:+WanGP supports the Wan (and derived models), Hunyuan Video, Flux, Qwen, Z-Image, LongCat, Kandinsky and LTX Video models with:- Low VRAM requirements (as low as 6 GB of VRAM is sufficient for certain models)- Support for old Nvidia GPUs (RTX 10XX, 20xx, ...)- Support for AMD GPUs Radeon RX 76XX, 77XX, 78XX & 79XX, instructions in the Installation Section Below.- Very Fast on the latest GPUs- Easy to use Full Web based interface+- Support for many checkpoint Quantized formats: int8, fp8, gguf, NV FP4, Nunchaku- Auto download of the required model adapted to your specific architecture-- Tools integrated to facilitate Video Generation : Mask Editor, Prompt Enhancer, Temporal and Spatial Generation, MMAudio, Video Browser, Pose / Depth / Flow extractor+- Tools integrated to facilitate Video Generation : Mask Editor, Prompt Enhancer, Temporal and Spatial Generation, MMAudio, Video Browser, Pose / Depth / Flow extractor, Motion Designer+- Plenty of ready to use Plug Ins: Gallery Browser, Upscaler, Models/Checkpoints Manager, CivitAI browser and downloader, ...- Loras Support to customize each model- Queuing system : make your shopping list of videos to generate and come back later+- Headless mode: launch the generation of multiple image / videos using a command line**Discord Server to get Help from Other Users and show your Best Videos:** https://discord.gg/g7efUW9jGV@@ -23,6 +26,22 @@ WanGP supports the Wan (and derived models), Hunyuan Video and LTV Video models## 🔥 Latest Updates :+### January 17th 2026: WanGP v10.40, The Cost Saver+*GPUs are expensive, RAM is expensive, SSD are expensive, sadly we live now in a GPU & RAM poor.*++WanGP comes again to the rescue:++- **GGUF support**: as some of you know, I am not a big fan of this format because when used with image / video generative models we don't get any speed boost (matrices multiplications are still done at 16 bits), VRAM savings are small and quality is worse than with int8/fp8. Still gguf has one advantage: it consumes less RAM and hardware space. So enjoy gguf support. I have added ready to use *Kijai gguf finetunes* for *LTX 2*.++- **Models Manager PlugIn**: use this *Plugin* to identify how much space is taken by each *model* / *finetune* and delete the ones you no longer use. Try to avoid deleting shared files otherwise they will be downloaded again.++- **LTX 2 Dual Video & Audio Control**: you no longer need to extract the audio track of a *Control Video* if you want to use it as well to drive the video generation. New mode will allow you to use both motion and audio from Video Control.++- **LTX 2 - Custom VAE URL**: some users have asked if they could use the old *Distiller VAE* instead of the new one. To do that, create a *finetune* def based on an existing model definition and save it in the *finetunes/* folder with this entry (check the *docs/FINETUNES.md* doc):+```+ "VAE_URLs": ["https://huggingface.co/DeepBeepMeep/LTX-2/resolve/main/ltx-2-19b_vae_old.safetensors"]+```+### January 15th 2026: WanGP v10.30, The Need for Speed ...- **LTX Distilled VAE Upgrade**: *Kijai* has observed that the Distilled VAE produces images that were less sharp that the VAE of the Non Distilled model. I have used this as an opportunity to repackage all the LTX 2 checkpoints and reduce their overal HD footprint since they all share around 5GB.diff --git a/defaults/ltx2_distilled_gguf_q4_k_m.json b/defaults/ltx2_distilled_gguf_q4_k_m.jsonnew file mode 100644index 0000000..3f6b86f--- /dev/null+++ b/defaults/ltx2_distilled_gguf_q4_k_m.json@@ -0,0 +1,16 @@+{+ "model": {+ "name": "LTX-2 Distilled GGUF Q4_K_M 19B ",+ "architecture": "ltx2_19B",+ "description": "LTX-2 distilled GGUF Q4_K_M checkpoint for llama.cpp-backed quantization.",+ "URLs": [+ "https://huggingface.co/Kijai/LTXV2_comfy/resolve/main/diffusion_models/ltx-2-19b-distilled_Q4_K_M.gguf"+ ],+ "preload_URLs": "ltx2_19B",+ "ltx2_pipeline": "distilled"+ },+ "prompt": "A warm sunny backyard. The camera starts in a tight cinematic close-up of a woman and a man in their 30s, facing each other with serious expressions. The woman, emotional and dramatic, says softly, \"That's it... Dad's lost it. And we've lost Dad.\"The man exhales, slightly annoyed: \"Stop being so dramatic, Jess.\"A beat. He glances aside, then mutters defensively, \"He's just having fun.\"The camera slowly pans right, revealing the grandfather in the garden wearing enormous butterfly wings, waving his arms in the air like he's trying to take off.He shouts, \"Wheeeew!\" as he flaps his wings with full commitment.The woman covers her face, on the verge of tears. The tone is deadpan, absurd, and quietly tragic.",+ "num_inference_steps": 8,+ "video_length": 241,+ "guidance_scale": 4.0+}diff --git a/defaults/ltx2_distilled_gguf_q6_k.json b/defaults/ltx2_distilled_gguf_q6_k.jsonnew file mode 100644index 0000000..55c24d2--- /dev/null+++ b/defaults/ltx2_distilled_gguf_q6_k.json@@ -0,0 +1,16 @@+{+ "model": {+ "name": "LTX-2 Distilled GGUF Q6_K 19B ",+ "architecture": "ltx2_19B",+ "description": "LTX-2 distilled GGUF Q6_K checkpoint for llama.cpp-backed quantization.",+ "URLs": [+ "https://huggingface.co/Kijai/LTXV2_comfy/resolve/main/diffusion_models/ltx-2-19b-distilled_Q6_K.gguf"+ ],+ "preload_URLs": "ltx2_19B",+ "ltx2_pipeline": "distilled"+ },+ "prompt": "A warm sunny backyard. The camera starts in a tight cinematic close-up of a woman and a man in their 30s, facing each other with serious expressions. The woman, emotional and dramatic, says softly, \"That's it... Dad's lost it. And we've lost Dad.\"The man exhales, slightly annoyed: \"Stop being so dramatic, Jess.\"A beat. He glances aside, then mutters defensively, \"He's just having fun.\"The camera slowly pans right, revealing the grandfather in the garden wearing enormous butterfly wings, waving his arms in the air like he's trying to take off.He shouts, \"Wheeeew!\" as he flaps his wings with full commitment.The woman covers her face, on the verge of tears. The tone is deadpan, absurd, and quietly tragic.",+ "num_inference_steps": 8,+ "video_length": 241,+ "guidance_scale": 4.0+}diff --git a/defaults/ltx2_distilled_gguf_q8_0.json b/defaults/ltx2_distilled_gguf_q8_0.jsonnew file mode 100644index 0000000..708c67e--- /dev/null+++ b/defaults/ltx2_distilled_gguf_q8_0.json@@ -0,0 +1,16 @@+{+ "model": {+ "name": "LTX-2 Distilled GGUF Q8_0 19B ",+ "architecture": "ltx2_19B",+ "description": "LTX-2 distilled GGUF Q8_0 checkpoint for llama.cpp-backed quantization.",+ "URLs": [+ "https://huggingface.co/Kijai/LTXV2_comfy/resolve/main/diffusion_models/ltx-2-19b-distilled_Q8_0.gguf"+ ],+ "preload_URLs": "ltx2_19B",+ "ltx2_pipeline": "distilled"+ },+ "prompt": "A warm sunny backyard. The camera starts in a tight cinematic close-up of a woman and a man in their 30s, facing each other with serious expressions. The woman, emotional and dramatic, says softly, \"That's it... Dad's lost it. And we've lost Dad.\"The man exhales, slightly annoyed: \"Stop being so dramatic, Jess.\"A beat. He glances aside, then mutters defensively, \"He's just having fun.\"The camera slowly pans right, revealing the grandfather in the garden wearing enormous butterfly wings, waving his arms in the air like he's trying to take off.He shouts, \"Wheeeew!\" as he flaps his wings with full commitment.The woman covers her face, on the verge of tears. The tone is deadpan, absurd, and quietly tragic.",+ "num_inference_steps": 8,+ "video_length": 241,+ "guidance_scale": 4.0+}diff --git a/docs/FINETUNES.md b/docs/FINETUNES.mdindex 106bbea..a48960e 100644--- a/docs/FINETUNES.md+++ b/docs/FINETUNES.md@@ -57,6 +57,7 @@ For instance if one adds a module *vace_14B* on top of a model with architecture- *URLs*: URLs of all the finetune versions (quantized / non quantized). WanGP will pick the version that is the closest to the user preferences. You will need to follow a naming convention to help WanGP identify the content of each version (see next section). WanGP supports 8 bits quantized model that have been quantized using **quanto** and Scaled FP8 models. WanGP offers a command switch to build easily such a quantized model (see below). *URLs* can contain also paths to local file to allow testing.- *URLs2*: URLs of all the finetune versions (quantized / non quantized) of the weights used for the second phase of a model. For instance with Wan 2.2, the first phase contains the High Noise model weights and the second phase contains the Low Noise model weights. This feature can be used with other models than Wan 2.2 to combine different model weights during the same video generation.- *text_encoder_URLs* : URLs of the text_encoder versions (quantized or not), if specified will override the default text encoder+- *VAE_URLs* : URL of a VAE (in a list), if specified will override the default VAE (supported so far only with Wan & LTX2 models)- *modules*: this a list of modules to be combined with the models referenced by the URLs. A module is a model extension that is merged with a model to expand its capabilities. Supported models so far are : *vace_14B* and *multitalk*. For instance the full Vace model is the fusion of a Wan text 2 video and the Vace module.- *preload_URLs* : URLs of files to download no matter what (used to load quantization maps for instance)- *loras* : URLs of Loras that will applied before any other Lora specified by the user. These loras will be quite often Loras accelerators. For instance if you specify here the FusioniX Lora you will be able to reduce the number of generation steps to 10diff --git a/docs/LORAS.md b/docs/LORAS.mdindex 96bac0c..c028b56 100644--- a/docs/LORAS.md+++ b/docs/LORAS.md@@ -85,6 +85,8 @@ For dynamic effects over generation steps, use comma-separated values:With models like Wan 2.2 that uses internally two diffusion models (*High noise* / *Low Noise*) you can specify which Loras you want to be applied for a specific phase by separating each phase with a ";".+Like LTX 2 models have two passes the ";" can be used to specify the multiplier for each pass.+For instance, if you want to disable a lora for phase *High Noise* and enables it only for phase *Low Noise*:```0;1diff --git a/models/chatterbox/chatterbox_handler.py b/models/chatterbox/chatterbox_handler.pyindex ecb51d1..821b21e 100644--- a/models/chatterbox/chatterbox_handler.py+++ b/models/chatterbox/chatterbox_handler.py@@ -88,7 +88,7 @@ class family_handler:return extra_model_def@staticmethod- def query_model_files(computeList, base_model_type, model_filename, text_encoder_quantization, model_def=None):+ def query_model_files(computeList, base_model_type, model_def=None):mandatory_files = ["ve.safetensors","t3_mtl23ls_v2.safetensors",diff --git a/models/flux/flux_handler.py b/models/flux/flux_handler.pyindex 603727e..c883838 100644--- a/models/flux/flux_handler.py+++ b/models/flux/flux_handler.py@@ -1,22 +1,12 @@import osimport torchfrom PIL import Image-from shared.utils import files_locator as fl+from shared.utils.hf import build_hf_urldef test_flux2(base_model_type):return base_model_type in ["flux2_dev", "pi_flux2"]-def get_flux_text_encoder_filename(text_encoder_quantization, base_model_type):- if test_flux2( base_model_type):- text_encoder_filename = "mistral3small/mistral3_small_bf16.safetensors"- else:- text_encoder_filename = "T5_xxl_1.1/T5_xxl_1.1_enc_bf16.safetensors"- if text_encoder_quantization =="int8":- text_encoder_filename = text_encoder_filename.replace("bf16", "quanto_bf16_int8")- return fl.locate_file(text_encoder_filename, True)--class family_handler():@staticmethoddef query_supported_types():@@ -70,6 +60,20 @@ class family_handler():"no_negative_prompt" : flux2 or not (flux_chroma or flux_chroma_radiance),"flux-model": flux_model,}+ if flux2:+ text_encoder_folder = "mistral3small"+ extra_model_def["text_encoder_URLs"] = [+ build_hf_url("DeepBeepMeep/Flux2", text_encoder_folder, "mistral3_small_bf16.safetensors"),+ build_hf_url("DeepBeepMeep/Flux2", text_encoder_folder, "mistral3_small_quanto_bf16_int8.safetensors"),+ ]+ extra_model_def["text_encoder_folder"] = text_encoder_folder+ else:+ text_encoder_folder = "T5_xxl_1.1"+ extra_model_def["text_encoder_URLs"] = [+ build_hf_url("DeepBeepMeep/LTX_Video", text_encoder_folder, "T5_xxl_1.1_enc_bf16.safetensors"),+ build_hf_url("DeepBeepMeep/LTX_Video", text_encoder_folder, "T5_xxl_1.1_enc_quanto_bf16_int8.safetensors"),+ ]+ extra_model_def["text_encoder_folder"] = text_encoder_folderextra_model_def["profiles_dir"] = [] if (flux_schnell or flux2) else ["flux"]if flux_chroma or flux_chroma_radiance:extra_model_def["guidance_max_phases"] = 1@@ -207,15 +211,14 @@ class family_handler():return args.lora_dir_flux@staticmethod- def query_model_files(computeList, base_model_type, model_filename, text_encoder_quantization, model_def=None):- text_encoder_filename = get_flux_text_encoder_filename(text_encoder_quantization, base_model_type)+ def query_model_files(computeList, base_model_type, model_def=None):if test_flux2(base_model_type):ret = [{"repoId": "DeepBeepMeep/Flux2","sourceFolderList": ["mistral3small", ""],"fileList": [- [ "tokenizer.json", "tokenizer_config.json", "special_tokens_map.json", "processor_config.json", "config.json", "preprocessor_config.json", "chat_template.jinja", ] + computeList(text_encoder_filename),+ [ "tokenizer.json", "tokenizer_config.json", "special_tokens_map.json", "processor_config.json", "config.json", "preprocessor_config.json", "chat_template.jinja", ],[ "flux2_vae.safetensors", ],],}@@ -227,7 +230,7 @@ class family_handler():{"repoId" : "DeepBeepMeep/LTX_Video","sourceFolderList" : ["T5_xxl_1.1"],- "fileList" : [ ["added_tokens.json", "special_tokens_map.json", "spiece.model", "tokenizer_config.json"] + computeList(text_encoder_filename) ]+ "fileList" : [ ["added_tokens.json", "special_tokens_map.json", "spiece.model", "tokenizer_config.json"] ]},{"repoId" : "DeepBeepMeep/HunyuanVideo",@@ -271,7 +274,7 @@ class family_handler():model_type = model_type,model_def = model_def,base_model_type=base_model_type,- text_encoder_filename= get_flux_text_encoder_filename(text_encoder_quantization, base_model_type) if text_encoder_filename is None else text_encoder_filename,+ text_encoder_filename= text_encoder_filename,quantizeTransformer = quantizeTransformer,dtype = dtype,VAE_dtype = VAE_dtype,diff --git a/models/hyvideo/hunyuan.py b/models/hyvideo/hunyuan.pyindex 185de68..07a71aa 100644--- a/models/hyvideo/hunyuan.py+++ b/models/hyvideo/hunyuan.py@@ -404,11 +404,20 @@ class Inference(object):prompt_template_video = PROMPT_TEMPLATE[prompt_template_video] if prompt_template_video is not None else None+ text_encoder_folder = model_def.get("text_encoder_folder")+ if text_encoder_folder:+ tokenizer_path = fl.locate_folder(text_encoder_folder)+ elif text_encoder_filepath:+ tokenizer_path = os.path.dirname(text_encoder_filepath)+ else:+ tokenizer_path = None+text_encoder = text_encoder_cls(text_encoder_type=text_encoder,max_length=max_length,text_encoder_precision="fp16",tokenizer_type=tokenizer,+ tokenizer_path=tokenizer_path,i2v_mode=i2v_mode,prompt_template=prompt_template,prompt_template_video=prompt_template_video,diff --git a/models/hyvideo/hunyuan_handler.py b/models/hyvideo/hunyuan_handler.pyindex 681c77f..9939ce5 100644--- a/models/hyvideo/hunyuan_handler.py+++ b/models/hyvideo/hunyuan_handler.py@@ -1,23 +1,10 @@import osimport torch-from shared.utils import files_locator as fl+from shared.utils.hf import build_hf_urldef test_hunyuan_1_5(base_model_type):return base_model_type in ["hunyuan_1_5_t2v", "hunyuan_1_5_i2v", "hunyuan_1_5_upsampler"]-def get_hunyuan_text_encoder_filename(base_model_type, text_encoder_quantization):- if test_hunyuan_1_5(base_model_type):- text_encoder_filename = "Qwen2.5-VL-7B-Instruct/Qwen2.5-VL-7B-Instruct_bf16.safetensors"- if text_encoder_quantization =="int8":- text_encoder_filename = text_encoder_filename.replace("bf16", "quanto_bf16_int8")- else:- if text_encoder_quantization =="int8":- text_encoder_filename = "llava-llama-3-8b/llava-llama-3-8b-v1_1_vlm_quanto_int8.safetensors"- else:- text_encoder_filename = "llava-llama-3-8b/llava-llama-3-8b-v1_1_vlm_fp16.safetensors"-- return fl.locate_file(text_encoder_filename, True)-class family_handler():@staticmethod@@ -51,6 +38,21 @@ class family_handler():def query_model_def(base_model_type, model_def):extra_model_def = {}+ if test_hunyuan_1_5(base_model_type):+ text_encoder_folder = "Qwen2.5-VL-7B-Instruct"+ extra_model_def["text_encoder_URLs"] = [+ build_hf_url("DeepBeepMeep/Qwen_image", text_encoder_folder, "Qwen2.5-VL-7B-Instruct_bf16.safetensors"),+ build_hf_url("DeepBeepMeep/Qwen_image", text_encoder_folder, "Qwen2.5-VL-7B-Instruct_quanto_bf16_int8.safetensors"),+ ]+ extra_model_def["text_encoder_folder"] = text_encoder_folder+ else:+ text_encoder_folder = "llava-llama-3-8b"+ extra_model_def["text_encoder_URLs"] = [+ build_hf_url("DeepBeepMeep/HunyuanVideo", text_encoder_folder, "llava-llama-3-8b-v1_1_vlm_fp16.safetensors"),+ build_hf_url("DeepBeepMeep/HunyuanVideo", text_encoder_folder, "llava-llama-3-8b-v1_1_vlm_quanto_int8.safetensors"),+ ]+ extra_model_def["text_encoder_folder"] = text_encoder_folder+if base_model_type in ["hunyuan_avatar", "hunyuan_custom_audio"]:fps = 25elif base_model_type in ["hunyuan", "hunyuan_i2v", "hunyuan_custom_edit", "hunyuan_custom"] or test_hunyuan_1_5(base_model_type):@@ -201,14 +203,12 @@ class family_handler():return latent_rgb_factors, latent_rgb_factors_bias@staticmethod- def query_model_files(computeList, base_model_type, model_filename, text_encoder_quantization, model_def=None):- text_encoder_filename = get_hunyuan_text_encoder_filename(base_model_type,text_encoder_quantization)-+ def query_model_files(computeList, base_model_type, model_def=None):if test_hunyuan_1_5(base_model_type):download_def = [{"repoId" : "DeepBeepMeep/Qwen_image","sourceFolderList" : ["", "Qwen2.5-VL-7B-Instruct"],- "fileList" : [ ["qwen_vae.safetensors", "qwen_vae_config.json"], ["merges.txt", "tokenizer_config.json", "config.json", "vocab.json", "video_preprocessor_config.json", "preprocessor_config.json", "chat_template.json"] + computeList(text_encoder_filename) ]+ "fileList" : [ ["qwen_vae.safetensors", "qwen_vae_config.json"], ["merges.txt", "tokenizer_config.json", "config.json", "vocab.json", "video_preprocessor_config.json", "preprocessor_config.json", "chat_template.json"] ]},{"repoId" : "DeepBeepMeep/HunyuanVideo1.5",@@ -216,7 +216,7 @@ class family_handler():"fileList" :[ ["color_idx.json", "multilingual_10-lang_idx.json"] ,[ "config.json", "model.safetensors", "byt5_model.safetensors"], # "byt5_model.pt", "pytorch_model.bin"],[ "model.safetensors", "config.json", "preprocessor_config.json"],- [ "hunyuan_video_1_5_VAE_fp32.safetensors", "hunyuan_video_1_5_VAE.json"] + computeList(model_filename) ,+ [ "hunyuan_video_1_5_VAE_fp32.safetensors", "hunyuan_video_1_5_VAE.json"] ,]} ]@@ -224,11 +224,11 @@ class family_handler():download_def= {"repoId" : "DeepBeepMeep/HunyuanVideo","sourceFolderList" : [ "llava-llama-3-8b", "clip_vit_large_patch14", "whisper-tiny" , "det_align", "" ],- "fileList" :[ ["config.json", "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json", "preprocessor_config.json"] + computeList(text_encoder_filename) ,+ "fileList" :[ ["config.json", "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json", "preprocessor_config.json"],["config.json", "merges.txt", "model.safetensors", "preprocessor_config.json", "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json", "vocab.json"],["config.json", "model.safetensors", "preprocessor_config.json", "special_tokens_map.json", "tokenizer_config.json"],["detface.pt"],- [ "hunyuan_video_720_quanto_int8_map.json", "hunyuan_video_custom_VAE_fp32.safetensors", "hunyuan_video_custom_VAE_config.json", "hunyuan_video_VAE_fp32.safetensors", "hunyuan_video_VAE_config.json" , "hunyuan_video_720_quanto_int8_map.json" ] + computeList(model_filename)+ [ "hunyuan_video_720_quanto_int8_map.json", "hunyuan_video_custom_VAE_fp32.safetensors", "hunyuan_video_custom_VAE_config.json", "hunyuan_video_VAE_fp32.safetensors", "hunyuan_video_VAE_config.json" , "hunyuan_video_720_quanto_int8_map.json" ]]}return download_def@@ -243,7 +243,7 @@ class family_handler():model_type = model_type,base_model_type = base_model_type,model_def = model_def,- text_encoder_filepath = get_hunyuan_text_encoder_filename(base_model_type, text_encoder_quantization) if text_encoder_filename is None else text_encoder_filename,+ text_encoder_filepath = text_encoder_filename,dtype = dtype,quantizeTransformer = quantizeTransformer,VAE_dtype = VAE_dtype,diff --git a/models/kandinsky5/kandinsky_handler.py b/models/kandinsky5/kandinsky_handler.pyindex d08b0f0..360c52a 100644--- a/models/kandinsky5/kandinsky_handler.py+++ b/models/kandinsky5/kandinsky_handler.py@@ -1,14 +1,7 @@import osimport torchfrom omegaconf import OmegaConf-from shared.utils import files_locator as fl---def get_kandinsky_text_encoder_filename(text_encoder_quantization):- text_encoder_filename = "Qwen2.5-VL-7B-Instruct/Qwen2.5-VL-7B-Instruct_bf16.safetensors"- if text_encoder_quantization == "int8":- text_encoder_filename = text_encoder_filename.replace("bf16", "quanto_bf16_int8")- return fl.locate_file(text_encoder_filename, True)+from shared.utils.hf import build_hf_url_MAGCACHE_RATIOS_CACHE = {}@@ -196,6 +189,12 @@ class family_handler:"mag_cache": True,"profiles_dir": [profiles_dir],}+ text_encoder_folder = "Qwen2.5-VL-7B-Instruct"+ extra_model_def["text_encoder_URLs"] = [+ build_hf_url("DeepBeepMeep/Qwen_image", text_encoder_folder, "Qwen2.5-VL-7B-Instruct_bf16.safetensors"),+ build_hf_url("DeepBeepMeep/Qwen_image", text_encoder_folder, "Qwen2.5-VL-7B-Instruct_quanto_bf16_int8.safetensors"),+ ]+ extra_model_def["text_encoder_folder"] = text_encoder_folderif is_video:extra_model_def.update(@@ -222,8 +221,7 @@ class family_handler:return extra_model_def@staticmethod- def query_model_files(computeList, base_model_type, model_filename, text_encoder_quantization, model_def=None):- text_encoder_filename = get_kandinsky_text_encoder_filename(text_encoder_quantization)+ def query_model_files(computeList, base_model_type, model_def=None):return [{"repoId": "DeepBeepMeep/Qwen_image",@@ -238,8 +236,7 @@ class family_handler:"video_preprocessor_config.json","preprocessor_config.json","chat_template.json",- ]- + computeList(text_encoder_filename),+ ],],},{diff --git a/models/kandinsky5/kandinsky_main.py b/models/kandinsky5/kandinsky_main.pyindex fceadf0..19f3a3e 100644--- a/models/kandinsky5/kandinsky_main.py+++ b/models/kandinsky5/kandinsky_main.py@@ -44,9 +44,11 @@ def _get_config_path(base_model_type):return os.path.join("models", "kandinsky5", "configs", f"{base_model_type}.yaml")-def _select_qwen_checkpoint(path_hint=None):+def _select_qwen_checkpoint(path_hint=None, folder_hint=None):if path_hint is not None:return path_hint+ if folder_hint:+ return fl.locate_folder(folder_hint)candidates = [os.path.join("Qwen2.5-VL-7B-Instruct", "Qwen2.5-VL-7B-Instruct_bf16.safetensors"),os.path.join("Qwen2.5-VL-7B-Instruct", "Qwen2.5-VL-7B-Instruct_quanto_bf16_int8.safetensors"),@@ -121,7 +123,8 @@ class model_factory:model_filename = model_filename[0]conf.model.checkpoint_path = model_filename- qwen_path = _select_qwen_checkpoint(text_encoder_filename)+ text_encoder_folder = self.model_def.get("text_encoder_folder")+ qwen_path = _select_qwen_checkpoint(text_encoder_filename, text_encoder_folder)conf.model.text_embedder.qwen.checkpoint_path = qwen_pathconf.model.text_embedder.clip.checkpoint_path = fl.locate_folder("clip_vit_large_patch14")diff --git a/models/longcat/longcat_handler.py b/models/longcat/longcat_handler.pyindex 34fe081..11bcd52 100644--- a/models/longcat/longcat_handler.py+++ b/models/longcat/longcat_handler.py@@ -1,13 +1,6 @@import osimport torch-from shared.utils import files_locator as fl---def get_longcat_text_encoder_filename(text_encoder_quantization):- text_encoder_filename = "umt5-xxl/models_t5_umt5-xxl-enc-bf16.safetensors"- if text_encoder_quantization == "int8":- text_encoder_filename = text_encoder_filename.replace("bf16", "quanto_int8")- return fl.locate_file(text_encoder_filename, True)+from shared.utils.hf import build_hf_urlclass family_handler:@@ -64,6 +57,12 @@ class family_handler:("Distill", "distill"),],}+ text_encoder_folder = "umt5-xxl"+ extra_model_def["text_encoder_URLs"] = [+ build_hf_url("DeepBeepMeep/Wan2.1", text_encoder_folder, "models_t5_umt5-xxl-enc-bf16.safetensors"),+ build_hf_url("DeepBeepMeep/Wan2.1", text_encoder_folder, "models_t5_umt5-xxl-enc-quanto_int8.safetensors"),+ ]+ extra_model_def["text_encoder_folder"] = text_encoder_folderif base_model_type == "longcat_video":extra_model_def.update(@@ -104,15 +103,13 @@ class family_handler:return get_rgb_factors("wan")@staticmethod- def query_model_files(computeList, base_model_type, model_filename, text_encoder_quantization, model_def=None):- text_encoder_filename = get_longcat_text_encoder_filename(text_encoder_quantization)+ def query_model_files(computeList, base_model_type, model_def=None):download_def = [{"repoId": "DeepBeepMeep/Wan2.1","sourceFolderList": ["umt5-xxl", "chinese-wav2vec2-base"],"fileList": [- ["special_tokens_map.json", "spiece.model", "tokenizer.json", "tokenizer_config.json"]- + computeList(text_encoder_filename),+ ["special_tokens_map.json", "spiece.model", "tokenizer.json", "tokenizer_config.json"],["config.json","preprocessor_config.json",@@ -155,9 +152,7 @@ class family_handler:model_type=model_type,model_def=model_def,base_model_type=base_model_type,- text_encoder_filename=get_longcat_text_encoder_filename(text_encoder_quantization)- if text_encoder_filename is None- else text_encoder_filename,+ text_encoder_filename=text_encoder_filename,quantizeTransformer=quantizeTransformer,dtype=dtype,VAE_dtype=VAE_dtype,@@ -183,7 +178,7 @@ class family_handler:"num_inference_steps": 50,"audio_guidance_scale": 4.0,"sliding_window_overlap": 13,-+ "sliding_window_size": 93,})if base_model_type == "longcat_video":diff --git a/models/longcat/longcat_main.py b/models/longcat/longcat_main.pyindex c1f1240..d707f7f 100644--- a/models/longcat/longcat_main.py+++ b/models/longcat/longcat_main.py@@ -1,6 +1,7 @@import jsonimport mathimport gc+import osfrom typing import Optional, Listimport numpy as np@@ -80,12 +81,17 @@ class LongCatModel:text_encoder_path = text_encoder_filename or fl.locate_file("umt5-xxl/models_t5_umt5-xxl-enc-bf16.safetensors", True)+ text_encoder_folder = self.model_def.get("text_encoder_folder")+ if text_encoder_folder:+ tokenizer_path = fl.locate_folder(text_encoder_folder)+ else:+ tokenizer_path = os.path.dirname(text_encoder_path)self.text_encoder = T5EncoderModel(text_len=512,dtype=dtype,device=torch.device("cpu"),checkpoint_path=text_encoder_path,- tokenizer_path=fl.locate_folder("umt5-xxl"),+ tokenizer_path=tokenizer_path,shard_fn=None,)diff --git a/models/ltx2/ltx2.py b/models/ltx2/ltx2.pyindex 6d478ed..15a78ab 100644--- a/models/ltx2/ltx2.py+++ b/models/ltx2/ltx2.py@@ -46,6 +46,11 @@ LTX2_USE_FP32_ROPE_FREQS = True #Falsedef _normalize_config(config_value):if isinstance(config_value, dict):return config_value+ if isinstance(config_value, (bytes, bytearray, memoryview)):+ try:+ config_value = bytes(config_value).decode("utf-8")+ except Exception:+ return {}if isinstance(config_value, str):try:return json.loads(config_value)@@ -76,6 +81,20 @@ def _strip_model_prefix(key: str) -> str:def _apply_sd_ops(state_dict: dict, quantization_map: dict | None, sd_ops):+ if sd_ops is not None:+ has_match = False+ for key in state_dict.keys():+ key = _strip_model_prefix(key)+ if sd_ops.apply_to_key(key) is not None:+ has_match = True+ break+ if not has_match:+ new_sd = {_strip_model_prefix(k): v for k, v in state_dict.items()}+ new_qm = {}+ if quantization_map:+ new_qm = {_strip_model_prefix(k): v for k, v in quantization_map.items()}+ return new_sd, new_qm+new_sd = {}for key, value in state_dict.items():key = _strip_model_prefix(key)@@ -484,21 +503,14 @@ class LTX2:model.eval().requires_grad_(False)return model- # text_encoder = build_gemma_text_encoder(gemma_root, default_dtype=self.dtype)- # text_projection_path = _component_path("text_embedding_projection")- # text_projection_config = _component_config(text_projection_path)- # with init_empty_weights():- # text_embedding_projection = GemmaFeaturesExtractorProjLinear.from_config(text_projection_config)- # text_embedding_projection = _load_component( text_embedding_projection, text_projection_path, TEXT_EMBEDDING_PROJECTION_KEY_OPS )-transformer_sd_ops = LTXV_MODEL_COMFY_RENAMING_MAPwith init_empty_weights():velocity_model = LTXModelConfigurator.from_config(base_config)velocity_model = _load_component(velocity_model, transformer_path, transformer_sd_ops)transformer = X0Model(velocity_model)transformer.eval().requires_grad_(False)-- video_vae_path = _component_path("video_vae")+ VAE_URLs = self.model_def.get("VAE_URLs", None)+ video_vae_path = fl.locate_file(VAE_URLs[0]) if VAE_URLs is not None and len(VAE_URLs) else _component_path("video_vae")video_config = _component_config(video_vae_path)with init_empty_weights():video_encoder = VideoEncoderConfigurator.from_config(video_config)@@ -817,8 +829,9 @@ class LTX2:text_connectors = getattr(self, "_text_connectors", None)audio_conditionings = None- audio_guide = kwargs.get("audio_guide")- if audio_guide:+ input_waveform = kwargs.get("input_waveform")+ input_waveform_sample_rate = kwargs.get("input_waveform_sample_rate")+ if input_waveform is not None:audio_scale = kwargs.get("audio_scale")if audio_scale is None:audio_scale = 1.0@@ -826,9 +839,7 @@ class LTX2:if audio_strength > 0.0:if self._interrupt:return None- if not os.path.isfile(audio_guide):- raise FileNotFoundError(f"Audio guide '{audio_guide}' not found.")- waveform, waveform_sample_rate = torchaudio.load(audio_guide)+ waveform, waveform_sample_rate = torch.from_numpy(input_waveform), input_waveform_sample_rateif self._interrupt:return Noneif waveform.ndim == 1:diff --git a/models/ltx2/ltx2_handler.py b/models/ltx2/ltx2_handler.pyindex 64cec00..a70a885 100644--- a/models/ltx2/ltx2_handler.py+++ b/models/ltx2/ltx2_handler.py@@ -1,6 +1,7 @@import osimport torchfrom shared.utils import files_locator as fl+from shared.utils.hf import build_hf_url_GEMMA_FOLDER = "gemma-3-12b-it-qat-q4_0-unquantized"@@ -56,14 +57,6 @@ class family_handler:def query_family_infos():return {"ltx2": (40, "LTX-2")}- @staticmethod- def get_text_encoder_filename(text_encoder_quantization):- text_encoder_filename = f"{_GEMMA_FOLDER}/{_GEMMA_FILENAME}"- if text_encoder_quantization == "int8":- text_encoder_filename = f"{_GEMMA_FOLDER}/{_GEMMA_QUANTO_FILENAME}"- return fl.locate_file(text_encoder_filename, True)--@staticmethoddef query_model_def(base_model_type, model_def):pipeline_kind = model_def.get("ltx2_pipeline", "two_stage")@@ -72,7 +65,10 @@ class family_handler:extra_model_def = {"text_encoder_folder": _GEMMA_FOLDER,- "text_encoder_URLs": [_GEMMA_FILENAME, _GEMMA_QUANTO_FILENAME],+ "text_encoder_URLs": [+ build_hf_url("DeepBeepMeep/LTX-2", _GEMMA_FOLDER, _GEMMA_FILENAME),+ build_hf_url("DeepBeepMeep/LTX-2", _GEMMA_FOLDER, _GEMMA_QUANTO_FILENAME),+ ],"dtype": "bf16","fps": 24,"frames_minimum": 17,@@ -86,14 +82,16 @@ class family_handler:"audio_guide_label": "Audio Prompt (Soundtrack)","audio_scale_name": "Prompt Audio Strength","audio_prompt_type_sources": {- "selection": ["", "A"],+ "selection": ["", "A", "K"],"labels": {"": "Generate Video & Soundtrack based on Text Prompt","A": "Generate Video based on Soundtrack and Text Prompt",+ "K": "Generate Video based on Control Video + its Audio Track and Text Prompt",},"show_label": False,},"audio_guide_window_slicing": True,+ "output_audio_is_input_audio": True,"custom_denoising_strength": True,"profiles_dir": ["ltx2_19B"],}@@ -158,7 +156,7 @@ class family_handler:return 64@staticmethod- def query_model_files(computeList, base_model_type, model_filename, text_encoder_quantization, model_def=None):+ def query_model_files(computeList, base_model_type, model_def=None):gemma_files = ["added_tokens.json","chat_template.json",@@ -172,7 +170,7 @@ class family_handler:"tokenizer_config.json",]- file_list = [_SPATIAL_UPSCALER_FILENAME] + computeList(model_filename)+ file_list = [_SPATIAL_UPSCALER_FILENAME]for name in _get_multi_file_names(model_def).values():if name not in file_list:file_list.append(name)diff --git a/models/ltx2/ltx_core/model/transformer/transformer_args.py b/models/ltx2/ltx_core/model/transformer/transformer_args.pyindex 5a9f831..17e35d4 100644--- a/models/ltx2/ltx_core/model/transformer/transformer_args.py+++ b/models/ltx2/ltx_core/model/transformer/transformer_args.py@@ -1,4 +1,5 @@from dataclasses import dataclass, replace+import osimport torch@@ -170,22 +171,34 @@ class TransformerArgsPreprocessor:self,modality: Modality,) -> TransformerArgs:- x = self.patchify_proj(modality.latent)+ latent = modality.latent+ latent_dtype = latent.dtype+ weight = getattr(self.patchify_proj, "weight", None)+ weight_dtype = getattr(weight, "dtype", None)+ if weight_dtype is not None and latent_dtype != weight_dtype:+ latent = latent.to(weight_dtype)+ latent_dtype = latent.dtype+ if os.environ.get("WAN2GP_GGUF_TRACE_LATENT", "") in ("1", "true", "yes") and not hasattr(+ self, "_gguf_latent_logged"+ ):+ self._gguf_latent_logged = True+ print(f"[GGUF][patchify_proj] latent={latent_dtype} weight={weight_dtype}")+ x = self.patchify_proj(latent)timestep, embedded_timestep = self._prepare_timestep(modality.timesteps,x.shape[0],- modality.latent.dtype,+ latent_dtype,frame_indices=modality.frame_indices,)context, attention_mask = self._prepare_context(modality.context, x, modality.context_mask)- attention_mask = self._prepare_attention_mask(attention_mask, modality.latent.dtype)+ attention_mask = self._prepare_attention_mask(attention_mask, latent_dtype)pe = self._prepare_positional_embeddings(positions=modality.positions,inner_dim=self.inner_dim,max_pos=self.max_pos,use_middle_indices_grid=self.use_middle_indices_grid,num_attention_heads=self.num_attention_heads,- x_dtype=modality.latent.dtype,+ x_dtype=latent_dtype,frame_indices=modality.frame_indices,)return TransformerArgs(diff --git a/models/ltx2/ltx_core/tools.py b/models/ltx2/ltx_core/tools.pyindex c324161..6ac1757 100644--- a/models/ltx2/ltx_core/tools.py+++ b/models/ltx2/ltx_core/tools.py@@ -101,6 +101,8 @@ class VideoLatentTools(LatentTools):assert initial_latent.shape == self.target_shape.to_torch_shape(), (f"Latent shape {initial_latent.shape} does not match target shape {self.target_shape.to_torch_shape()}")+ if initial_latent.device != device or initial_latent.dtype != dtype:+ initial_latent = initial_latent.to(device=device, dtype=dtype)else:initial_latent = torch.zeros(*self.target_shape.to_torch_shape(),@@ -157,6 +159,8 @@ class AudioLatentTools(LatentTools):assert initial_latent.shape == self.target_shape.to_torch_shape(), (f"Latent shape {initial_latent.shape} does not match target shape {self.target_shape.to_torch_shape()}")+ if initial_latent.device != device or initial_latent.dtype != dtype:+ initial_latent = initial_latent.to(device=device, dtype=dtype)else:initial_latent = torch.zeros(*self.target_shape.to_torch_shape(),diff --git a/models/ltx_video/ltxv.py b/models/ltx_video/ltxv.pyindex 7959c67..8038987 100644--- a/models/ltx_video/ltxv.py+++ b/models/ltx_video/ltxv.py@@ -217,7 +217,12 @@ class LTXV:text_encoder = offload.fast_load_transformers_model(text_encoder_filepath)patchifier = SymmetricPatchifier(patch_size=1)- tokenizer = T5Tokenizer.from_pretrained(fl.locate_folder("T5_xxl_1.1"))+ text_encoder_folder = self.model_def.get("text_encoder_folder")+ if text_encoder_folder:+ tokenizer_path = fl.locate_folder(text_encoder_folder)+ else:+ tokenizer_path = os.path.dirname(text_encoder_filepath)+ tokenizer = T5Tokenizer.from_pretrained(tokenizer_path)enhance_prompt = Falseprompt_enhancer_image_caption_model = Nonediff --git a/models/ltx_video/ltxv_handler.py b/models/ltx_video/ltxv_handler.pyindex 033bf60..61eb61d 100644--- a/models/ltx_video/ltxv_handler.py+++ b/models/ltx_video/ltxv_handler.py@@ -1,13 +1,6 @@import osimport torch-from shared.utils import files_locator as fl---def get_ltxv_text_encoder_filename(text_encoder_quantization):- text_encoder_filename = "T5_xxl_1.1/T5_xxl_1.1_enc_bf16.safetensors"- if text_encoder_quantization =="int8":- text_encoder_filename = text_encoder_filename.replace("bf16", "quanto_bf16_int8")- return fl.locate_file(text_encoder_filename, True)+from shared.utils.hf import build_hf_urlclass family_handler():@staticmethod@@ -21,6 +14,12 @@ class family_handler():"no_negative_prompt" : True,})+ text_encoder_folder = "T5_xxl_1.1"+ extra_model_def["text_encoder_URLs"] = [+ build_hf_url("DeepBeepMeep/LTX_Video", text_encoder_folder, "T5_xxl_1.1_enc_bf16.safetensors"),+ build_hf_url("DeepBeepMeep/LTX_Video", text_encoder_folder, "T5_xxl_1.1_enc_quanto_bf16_int8.safetensors"),+ ]+ extra_model_def["text_encoder_folder"] = text_encoder_folderextra_model_def["fps"] = 30extra_model_def["frames_minimum"] = 17@@ -81,12 +80,11 @@ class family_handler():return 32@staticmethod- def query_model_files(computeList, base_model_type, model_filename, text_encoder_quantization, model_def=None):- text_encoder_filename = get_ltxv_text_encoder_filename(text_encoder_quantization)+ def query_model_files(computeList, base_model_type, model_def=None):return {"repoId" : "DeepBeepMeep/LTX_Video","sourceFolderList" : ["T5_xxl_1.1", "" ],- "fileList" : [ ["added_tokens.json", "special_tokens_map.json", "spiece.model", "tokenizer_config.json"] + computeList(text_encoder_filename), ["ltxv_0.9.7_VAE.safetensors", "ltxv_0.9.7_spatial_upscaler.safetensors", "ltxv_scheduler.json"] + computeList(model_filename) ]+ "fileList" : [ ["added_tokens.json", "special_tokens_map.json", "spiece.model", "tokenizer_config.json"], ["ltxv_0.9.7_VAE.safetensors", "ltxv_0.9.7_spatial_upscaler.safetensors", "ltxv_scheduler.json"] ]}@@ -96,7 +94,7 @@ class family_handler():ltxv_model = LTXV(model_filepath = model_filename,- text_encoder_filepath = get_ltxv_text_encoder_filename(text_encoder_quantization) if text_encoder_filename is None else text_encoder_filename,+ text_encoder_filepath = text_encoder_filename,model_type = model_type,base_model_type = base_model_type,model_def = model_def,diff --git a/models/qwen/qwen_handler.py b/models/qwen/qwen_handler.pyindex ee7499f..665d39c 100644--- a/models/qwen/qwen_handler.py+++ b/models/qwen/qwen_handler.py@@ -1,14 +1,7 @@import osimport torchimport gradio as gr-from shared.utils import files_locator as fl---def get_qwen_text_encoder_filename(text_encoder_quantization):- text_encoder_filename = "Qwen2.5-VL-7B-Instruct/Qwen2.5-VL-7B-Instruct_bf16.safetensors"- if text_encoder_quantization =="int8":- text_encoder_filename = text_encoder_filename.replace("bf16", "quanto_bf16_int8")- return fl.locate_file(text_encoder_filename, True)+from shared.utils.hf import build_hf_urlclass family_handler():@staticmethod@@ -22,6 +15,12 @@ class family_handler():"fit_into_canvas_image_refs": 0,"profiles_dir": ["qwen"],}+ text_encoder_folder = "Qwen2.5-VL-7B-Instruct"+ extra_model_def["text_encoder_URLs"] = [+ build_hf_url("DeepBeepMeep/Qwen_image", text_encoder_folder, "Qwen2.5-VL-7B-Instruct_bf16.safetensors"),+ build_hf_url("DeepBeepMeep/Qwen_image", text_encoder_folder, "Qwen2.5-VL-7B-Instruct_quanto_bf16_int8.safetensors"),+ ]+ extra_model_def["text_encoder_folder"] = text_encoder_folderextra_model_def["vae_upsampler"] = [1,2]@@ -112,15 +111,14 @@ class family_handler():return args.lora_dir_qwen@staticmethod- def query_model_files(computeList, base_model_type, model_filename, text_encoder_quantization, model_def=None):- text_encoder_filename = get_qwen_text_encoder_filename(text_encoder_quantization)+ def query_model_files(computeList, base_model_type, model_def=None):vae_files = ["qwen_vae.safetensors", "qwen_vae_config.json"]if base_model_type in ["qwen_image_layered_20B"]:vae_files.append("qwen_image_layered_vae_bf16.safetensors")download_def = [{"repoId" : "DeepBeepMeep/Qwen_image","sourceFolderList" : ["", "Qwen2.5-VL-7B-Instruct"],- "fileList" : [ vae_files, ["merges.txt", "tokenizer_config.json", "config.json", "vocab.json", "video_preprocessor_config.json", "preprocessor_config.json", "chat_template.json"] + computeList(text_encoder_filename) ]+ "fileList" : [ vae_files, ["merges.txt", "tokenizer_config.json", "config.json", "vocab.json", "video_preprocessor_config.json", "preprocessor_config.json", "chat_template.json"] ]}]download_def += [{@@ -141,7 +139,7 @@ class family_handler():model_type = model_type,model_def = model_def,base_model_type=base_model_type,- text_encoder_filename= get_qwen_text_encoder_filename(text_encoder_quantization) if text_encoder_filename is None else text_encoder_filename,+ text_encoder_filename=text_encoder_filename,quantizeTransformer = quantizeTransformer,dtype = dtype,VAE_dtype = VAE_dtype,diff --git a/models/qwen/qwen_main.py b/models/qwen/qwen_main.pyindex da6f8ae..c52a269 100644--- a/models/qwen/qwen_main.py+++ b/models/qwen/qwen_main.py@@ -63,9 +63,14 @@ class model_factory():transformer_filename = model_filename[0]processor = Nonetokenizer = None+ text_encoder_folder = model_def.get("text_encoder_folder")+ if text_encoder_folder:+ tokenizer_path = fl.locate_folder(text_encoder_folder)+ else:+ tokenizer_path = os.path.dirname(text_encoder_filename)if base_model_type in ["qwen_image_edit_20B", "qwen_image_edit_plus_20B", "qwen_image_edit_plus2_20B", "qwen_image_layered_20B"]:- processor = Qwen2VLProcessor.from_pretrained(fl.locate_folder("Qwen2.5-VL-7B-Instruct"))- tokenizer = AutoTokenizer.from_pretrained(fl.locate_folder("Qwen2.5-VL-7B-Instruct"))+ processor = Qwen2VLProcessor.from_pretrained(tokenizer_path)+ tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)self.base_model_type = base_model_typeif base_model_type == "qwen_image_layered_20B":diff --git a/models/wan/any2video.py b/models/wan/any2video.pyindex fc3e604..c116357 100644--- a/models/wan/any2video.py+++ b/models/wan/any2video.py@@ -99,12 +99,17 @@ class WanAny2V:self.model2 = Noneself.transformer_switch = model_def.get("URLs2", None) is not Noneself.is_mocha = model_def.get("mocha_mode", False)+ text_encoder_folder = model_def.get("text_encoder_folder")+ if text_encoder_folder:+ tokenizer_path = fl.locate_folder(text_encoder_folder)+ else:+ tokenizer_path = os.path.dirname(text_encoder_filename)self.text_encoder = T5EncoderModel(text_len=config.text_len,dtype=config.t5_dtype,device=torch.device('cpu'),checkpoint_path=text_encoder_filename,- tokenizer_path=fl.locate_folder(model_def.get("text_encoder_folder", os.path.dirname(text_encoder_filename))),+ tokenizer_path=tokenizer_path,shard_fn= None)if hasattr(config, "clip_checkpoint") and not model_def.get("i2v_2_2", False) or base_model_type in ["animate"]:self.clip = CLIPModel(@@ -122,7 +127,7 @@ class WanAny2V:if isinstance(vae_checkpoint, str):passelif isinstance(vae_checkpoint, list) and len(vae_checkpoint):- vae_checkpoint = vae_checkpoint[0]+ vae_checkpoint = fl.locate_file(vae_checkpoint[0])elif model_def.get("wan_5B_class", False):self.vae_stride = (4, 16, 16)vae_checkpoint = "Wan2.2_VAE.safetensors"diff --git a/models/wan/df_handler.py b/models/wan/df_handler.pyindex 22d06e9..7376c68 100644--- a/models/wan/df_handler.py+++ b/models/wan/df_handler.py@@ -1,4 +1,5 @@import torch+from shared.utils.hf import build_hf_urlclass family_handler():@@ -14,6 +15,12 @@ class family_handler():@staticmethoddef query_model_def(base_model_type, model_def):extra_model_def = {}+ text_encoder_folder = "umt5-xxl"+ extra_model_def["text_encoder_URLs"] = [+ build_hf_url("DeepBeepMeep/Wan2.1", text_encoder_folder, "models_t5_umt5-xxl-enc-bf16.safetensors"),+ build_hf_url("DeepBeepMeep/Wan2.1", text_encoder_folder, "models_t5_umt5-xxl-enc-quanto_int8.safetensors"),+ ]+ extra_model_def["text_encoder_folder"] = text_encoder_folderif base_model_type in ["sky_df_14B"]:fps = 24else:@@ -86,14 +93,13 @@ class family_handler():return latent_rgb_factors, latent_rgb_factors_bias@staticmethod- def query_model_files(computeList, base_model_type, model_filename, text_encoder_quantization, model_def=None):+ def query_model_files(computeList, base_model_type, model_def=None):from .wan_handler import family_handler- return family_handler.query_model_files(computeList, base_model_type, model_filename, text_encoder_quantization)+ return family_handler.query_model_files(computeList, base_model_type, model_def)@staticmethoddef load_model(model_filename, model_type, base_model_type, model_def, quantizeTransformer = False, text_encoder_quantization = None, dtype = torch.bfloat16, VAE_dtype = torch.float32, mixed_precision_transformer = False, save_quantized= False, submodel_no_list = None, text_encoder_filename = None):from .configs import WAN_CONFIGS- from .wan_handler import family_handlercfg = WAN_CONFIGS['t2v-14B']from . import DTT2Vwan_model = DTT2V(@@ -103,7 +109,7 @@ class family_handler():model_type = model_type,model_def = model_def,base_model_type=base_model_type,- text_encoder_filename= family_handler.get_text_encoder_filename(text_encoder_quantization) if text_encoder_filename is None else text_encoder_filename,+ text_encoder_filename= text_encoder_filename,quantizeTransformer = quantizeTransformer,dtype = dtype,VAE_dtype = VAE_dtype,diff --git a/models/wan/diffusion_forcing.py b/models/wan/diffusion_forcing.pyindex 3c33b4a..08dcf88 100644--- a/models/wan/diffusion_forcing.py+++ b/models/wan/diffusion_forcing.py@@ -47,12 +47,17 @@ class DTT2V:self.num_train_timesteps = config.num_train_timestepsself.param_dtype = config.param_dtypeself.text_len = config.text_len+ text_encoder_folder = (model_def or {}).get("text_encoder_folder")+ if text_encoder_folder:+ tokenizer_path = fl.locate_folder(text_encoder_folder)+ else:+ tokenizer_path = os.path.dirname(text_encoder_filename)self.text_encoder = T5EncoderModel(text_len=config.text_len,dtype=config.t5_dtype,device=torch.device('cpu'),checkpoint_path=text_encoder_filename,- tokenizer_path=fl.locate_folder(config.t5_tokenizer),+ tokenizer_path=tokenizer_path,shard_fn= None)self.model_def = model_defself.image_outputs = model_def.get("image_outputs", False)diff --git a/models/wan/ovi_fusion_engine.py b/models/wan/ovi_fusion_engine.pyindex 0c294cd..de06197 100644--- a/models/wan/ovi_fusion_engine.py+++ b/models/wan/ovi_fusion_engine.py@@ -96,12 +96,17 @@ class OviFusionEngine:vae_model_audio.requires_grad_(False).eval()self.audio_vae = vae_model_audio.bfloat16()# Load T5 text model+ text_encoder_folder = model_def.get("text_encoder_folder")+ if text_encoder_folder:+ tokenizer_path = fl.locate_folder(text_encoder_folder)+ else:+ tokenizer_path = os.path.dirname(text_encoder_filename)self.text_encoder = T5EncoderModel(text_len=512,dtype=torch.bfloat16,device=torch.device('cpu'),checkpoint_path=text_encoder_filename,- tokenizer_path=fl.locate_folder("umt5-xxl"),+ tokenizer_path=tokenizer_path,shard_fn= None)@@ -373,4 +378,4 @@ class OviFusionEngine:self.model.custom_compile(compile_kwargs)def get_trans_lora(self):- return self.model.video_model, None\ No newline at end of file+ return self.model.video_model, Nonediff --git a/models/wan/ovi_handler.py b/models/wan/ovi_handler.pyindex e769f6c..3a43d5e 100644--- a/models/wan/ovi_handler.py+++ b/models/wan/ovi_handler.py@@ -4,7 +4,7 @@ from typing import Any, Dict, Tupleimport torch-from shared.utils import files_locator as fl+from shared.utils.hf import build_hf_urlclass family_handler:@@ -30,17 +30,16 @@ class family_handler:return wan_family_handler.register_lora_cli_args(parser)- @staticmethod- def get_text_encoder_filename(text_encoder_quantization):- text_encoder_filename = "umt5-xxl/models_t5_umt5-xxl-enc-bf16.safetensors"- if text_encoder_quantization =="int8":- text_encoder_filename = text_encoder_filename.replace("bf16", "quanto_int8")- return fl.locate_file(text_encoder_filename, True)-@staticmethoddef query_model_def(base_model_type: str, model_def: Dict[str, Any]):+ text_encoder_folder = "umt5-xxl"cfg = {"wan_5B_class": True,+ "text_encoder_URLs": [+ build_hf_url("DeepBeepMeep/Wan2.1", text_encoder_folder, "models_t5_umt5-xxl-enc-bf16.safetensors"),+ build_hf_url("DeepBeepMeep/Wan2.1", text_encoder_folder, "models_t5_umt5-xxl-enc-quanto_int8.safetensors"),+ ],+ "text_encoder_folder": text_encoder_folder,"profiles_dir": ["wan_2_2_ovi"],"group": "wan2_2","fps": 24,@@ -68,10 +67,10 @@ class family_handler:return cfg@staticmethod- def query_model_files(computeList, base_model_type, model_filename, text_encoder_quantization, model_def=None):+ def query_model_files(computeList, base_model_type, model_def=None):from .wan_handler import family_handler- download_def = family_handler.query_model_files(computeList, "ti2v_2_2", model_filename, text_encoder_quantization)+ download_def = family_handler.query_model_files(computeList, "ti2v_2_2", model_def)if not isinstance(download_def, list):download_def = [download_def]download_def += [{@@ -112,7 +111,7 @@ class family_handler:checkpoint_dir=checkpoint_dir,model_def=model_def,model_filename = model_filename,- text_encoder_filename = family_handler.get_text_encoder_filename(text_encoder_quantization),+ text_encoder_filename = text_encoder_filename,dtype=dtype,)diff --git a/models/wan/wan_handler.py b/models/wan/wan_handler.pyindex be3bdc7..fe49c24 100644--- a/models/wan/wan_handler.py+++ b/models/wan/wan_handler.py@@ -6,7 +6,7 @@ import numpy as npimport gradio as grimport cv2from PIL import Image-from shared.utils import files_locator as fl+from shared.utils.hf import build_hf_urldef test_vace(base_model_type):return base_model_type in ["vace_14B", "vace_14B_2_2", "vace_1.3B", "vace_multitalk_14B", "vace_standin_14B", "vace_lynx_14B", "vace_ditto_14B"]@@ -182,21 +182,18 @@ class family_handler():coefficients= [-5784.54975374, 5449.50911966, -1811.16591783, 256.27178429, -13.02252404]skip_steps_cache.coefficients = coefficients- @staticmethod- def get_text_encoder_filename(text_encoder_quantization):- text_encoder_filename = "umt5-xxl/models_t5_umt5-xxl-enc-bf16.safetensors"- if text_encoder_quantization =="int8":- text_encoder_filename = text_encoder_filename.replace("bf16", "quanto_int8")- return fl.locate_file(text_encoder_filename, True)-@staticmethoddef query_model_def(base_model_type, model_def):extra_model_def = {}if "URLs2" in model_def:extra_model_def["no_steps_skipping"] = Trueextra_model_def["compile"] = ["transformer","transformer2"]- extra_model_def["text_encoder_URLs"] = ["models_t5_umt5-xxl-enc-bf16.safetensors", "models_t5_umt5-xxl-enc-quanto_int8.safetensors"]- extra_model_def["text_encoder_folder"] = "umt5-xxl"+ text_encoder_folder = "umt5-xxl"+ extra_model_def["text_encoder_URLs"] = [+ build_hf_url("DeepBeepMeep/Wan2.1", text_encoder_folder, "models_t5_umt5-xxl-enc-bf16.safetensors"),+ build_hf_url("DeepBeepMeep/Wan2.1", text_encoder_folder, "models_t5_umt5-xxl-enc-quanto_int8.safetensors"),+ ]+ extra_model_def["text_encoder_folder"] = text_encoder_folderextra_model_def["i2v_class"] = i2v = test_class_i2v(base_model_type)extra_model_def["t2v_class"] = t2v = test_class_t2v(base_model_type)extra_model_def["multitalk_class"] = multitalk = test_multitalk(base_model_type)@@ -676,17 +673,17 @@ class family_handler():return latent_rgb_factors, latent_rgb_factors_bias@staticmethod- def query_model_files(computeList, base_model_type, model_filename, text_encoder_quantization, model_def=None):- text_encoder_filename = family_handler.get_text_encoder_filename(text_encoder_quantization)-+ def query_model_files(computeList, base_model_type, model_def=None):if test_wan_5B(base_model_type):wan_files = []else:- wan_files = ["Wan2.1_VAE.safetensors", "fantasy_proj_model.safetensors", "Wan2.1_VAE_upscale2x_imageonly_real_v1.safetensors"]+ wan_files = ["Wan2.1_VAE.safetensors", "Wan2.1_VAE_upscale2x_imageonly_real_v1.safetensors"]+ if base_model_type in ["fantasy"]:+ wan_files.append("fantasy_proj_model.safetensors")download_def = [{"repoId" : "DeepBeepMeep/Wan2.1","sourceFolderList" : ["xlm-roberta-large", "umt5-xxl", "" ],- "fileList" : [ [ "models_clip_open-clip-xlm-roberta-large-vit-huge-14-bf16.safetensors", "sentencepiece.bpe.model", "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json"], ["special_tokens_map.json", "spiece.model", "tokenizer.json", "tokenizer_config.json"] + computeList(text_encoder_filename) , wan_files + computeList(model_filename) ]+ "fileList" : [ [ "models_clip_open-clip-xlm-roberta-large-vit-huge-14-bf16.safetensors", "sentencepiece.bpe.model", "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json"], ["special_tokens_map.json", "spiece.model", "tokenizer.json", "tokenizer_config.json"], wan_files ]}]if base_model_type == "scail":@@ -983,6 +980,11 @@ class family_handler():"sliding_window_size": 81,"sliding_window_overlap" : 4,})++ if test_wan_5B(base_model_type):+ ui_defaults.update({+ "sliding_window_size": 121,+ })if base_model_type in ["i2v_2_2"]:ui_defaults.update({"masking_strength": 0.1, "denoising_strength": 0.9})diff --git a/models/z_image/z_image_handler.py b/models/z_image/z_image_handler.pyindex 3c7e379..33132a5 100644--- a/models/z_image/z_image_handler.py+++ b/models/z_image/z_image_handler.py@@ -1,13 +1,6 @@import osimport torch-from shared.utils import files_locator as fl---def get_z_image_text_encoder_filename(text_encoder_quantization=None):- text_encoder_filename = "Qwen3/qwen3_bf16.safetensors"- if text_encoder_quantization =="int8":- text_encoder_filename = text_encoder_filename.replace("bf16", "quanto_bf16_int8")- return fl.locate_file(text_encoder_filename, True)+from shared.utils.hf import build_hf_urlclass family_handler:@@ -19,6 +12,12 @@ class family_handler:"fit_into_canvas_image_refs": 0,"profiles_dir": [],}+ text_encoder_folder = "Qwen3"+ extra_model_def["text_encoder_URLs"] = [+ build_hf_url("DeepBeepMeep/Z-Image", text_encoder_folder, "qwen3_bf16.safetensors"),+ build_hf_url("DeepBeepMeep/Z-Image", text_encoder_folder, "qwen3_quanto_bf16_int8.safetensors"),+ ]+ extra_model_def["text_encoder_folder"] = text_encoder_folderif base_model_type in ["z_image_control", "z_image_control2", "z_image_control2_1"]:extra_model_def["mask_preprocessing"] = {@@ -90,14 +89,13 @@ class family_handler:return args.lora_dir_z_image@staticmethod- def query_model_files(computeList, base_model_type, model_filename, text_encoder_quantization, model_def=None):- text_encoder_filename = get_z_image_text_encoder_filename(text_encoder_quantization)+ def query_model_files(computeList, base_model_type, model_def=None):download_def = [{"repoId": "DeepBeepMeep/Z-Image","sourceFolderList": ["Qwen3", ""],"fileList": [- ["tokenizer.json", "tokenizer_config.json", "vocab.json", "config.json", "merges.txt"]+ computeList(text_encoder_filename),+ ["tokenizer.json", "tokenizer_config.json", "vocab.json", "config.json", "merges.txt"],["ZImageTurbo_VAE_bf16_config.json", "ZImageTurbo_VAE_bf16.safetensors", "ZImageTurbo_scheduler_config.json"],],}@@ -122,10 +120,6 @@ class family_handler:):from .z_image_main import model_factory- text_encoder_filename = (- text_encoder_filename if text_encoder_filename is not None else get_z_image_text_encoder_filename(text_encoder_quantization)- )-# Detect if this is a control variant (v1 or v2)is_control = base_model_type in ["z_image_control", "z_image_control2", "z_image_control2_1"]diff --git a/models/z_image/z_image_main.py b/models/z_image/z_image_main.pyindex 9df1b65..42975bc 100644--- a/models/z_image/z_image_main.py+++ b/models/z_image/z_image_main.py@@ -111,9 +111,9 @@ class model_factory:default_transformer_config = os.path.join(os.path.dirname(os.path.abspath(__file__)), "configs", f"{base_model_type}.json")- def preprocess_sd(state_dict, verboseLevel=1):+ def preprocess_sd(state_dict):state_dict = conv_state_dict(state_dict)- return _split_nunchaku_fused(state_dict, verboseLevel=verboseLevel)+ return _split_nunchaku_fused(state_dict)model_class = ZImageTransformer2DModel@@ -160,7 +160,11 @@ class model_factory:text_encoder = offload.fast_load_transformers_model( text_encoder_filename, writable_tensors=True, modelClass=Qwen3ForCausalLM,)# Tokenizer- tokenizer_path = os.path.join(os.path.dirname(text_encoder_filename))+ text_encoder_folder = model_def.get("text_encoder_folder")+ if text_encoder_folder:+ tokenizer_path = fl.locate_folder(text_encoder_folder)+ else:+ tokenizer_path = os.path.dirname(text_encoder_filename)tokenizer = AutoTokenizer.from_pretrained(tokenizer_path, trust_remote_code=True)# VAEdiff --git a/plugins/wan2gp-models-manager/__init__.py b/plugins/wan2gp-models-manager/__init__.pynew file mode 100644index 0000000..8b13789--- /dev/null+++ b/plugins/wan2gp-models-manager/__init__.py@@ -0,0 +1 @@+diff --git a/plugins/wan2gp-models-manager/plugin.py b/plugins/wan2gp-models-manager/plugin.pynew file mode 100644index 0000000..0bc555b--- /dev/null+++ b/plugins/wan2gp-models-manager/plugin.py@@ -0,0 +1,2461 @@+import gradio as gr+import os+import json+import html+from collections import defaultdict+from shared.utils.plugins import WAN2GPPlugin+from shared.utils import files_locator as fl+from mmgp import quant_router+++class modelsManagerPlugin(WAN2GPPlugin):+ def __init__(self):+ super().__init__()+ self.name = "Models Manager"+ self.version = "1.0.0"+ self.description = "Inspect and manage installed model dependencies"+ self._node_map = {}+ self._tree_data = []+ self._model_files = {}+ self._model_primary = {}+ self._model_variants = {}+ self._variant_to_model = {}+ self._model_base_label = {}+ self._model_family_label = {}+ self._model_usage_ids = {}+ self._usage_files = {}+ self._file_usage = {}+ self._file_usage_models = {}+ self._file_info = {}+ self._basename_index = {}+ self._stats_total = 0+ self._stats_by_drive = []+ self._errors = []+ self._repo_root = os.path.abspath(os.getcwd())++ def setup_ui(self):+ self.request_global("get_model_def")+ self.request_global("get_model_name")+ self.request_global("get_model_family")+ self.request_global("get_parent_model_type")+ self.request_global("get_base_model_type")+ self.request_global("get_model_handler")+ self.request_global("get_model_recursive_prop")+ self.request_global("get_model_filename")+ self.request_global("get_local_model_filename")+ self.request_global("get_lora_dir")+ self.request_global("compact_name")+ self.request_global("create_models_hierarchy")+ self.request_global("families_infos")+ self.request_global("models_def")+ self.request_global("transformer_quantization")+ self.request_global("transformer_dtype_policy")+ self.request_global("text_encoder_quantization")+ self.request_global("displayed_model_types")+ self.request_global("transformer_types")++ self.add_custom_js(self._get_js())++ self.add_tab(+ tab_id="model_manager",+ label="Models Manager",+ component_constructor=self.create_model_ui,+ )++ def create_model_ui(self):+ with gr.Column():+ gr.Markdown("### Models Manager")+ gr.Markdown(+ "Sizes are unique GB recoverable on delete, plus shared GB used outside the branch."+ )+ with gr.Row():+ with gr.Column(scale=3, min_width=550):+ self.tree_html = gr.HTML()+ with gr.Column(scale=2, min_width=350, elem_classes="ckpt-right-column"):+ self.view_html = gr.HTML()++ self.refresh_button = gr.Button(+ "Refresh", variant="secondary", elem_id="ckpt_refresh_btn"+ )++ with gr.Column(visible=False):+ self.action_input = gr.Textbox(elem_id="model_action_input")++ self.refresh_button.click(+ fn=self._show_loading,+ inputs=[],+ outputs=[self.tree_html, self.view_html, self.refresh_button],+ show_progress="hidden",+ ).then(+ fn=self._build_tree,+ inputs=[],+ outputs=[self.tree_html, self.view_html, self.refresh_button],+ show_progress="full",+ )++ self.action_input.change(+ fn=self._handle_action,+ inputs=[self.action_input],+ outputs=[self.tree_html, self.view_html, self.refresh_button],+ show_progress="hidden",+ )++ self.on_tab_outputs = [self.tree_html, self.view_html, self.refresh_button]+ return self.tree_html++ def on_tab_select(self, state: dict):+ return self._show_loading()++ def _get_js(self):+ return """+ function modelRoot() {+ if (window.gradioApp) {+ return window.gradioApp();+ }+ const app = document.querySelector('gradio-app');+ return app ? (app.shadowRoot || app) : document;+ }++ window.updatemodelInput = function(elem_id, value) {+ const root = modelRoot();+ const input = root.querySelector(`#${elem_id} textarea, #${elem_id} input`);+ if (input) {+ input.value = value;+ input.dispatchEvent(new Event('input', { bubbles: true }));+ return true;+ }+ return false;+ };++ function ensuremodelModal() {+ let backdrop = document.getElementById('ckpt-delete-modal');+ if (backdrop) return backdrop;+ backdrop = document.createElement('div');+ backdrop.id = 'ckpt-delete-modal';+ backdrop.className = 'ckpt-modal-backdrop';+ backdrop.innerHTML = `+ <div class="ckpt-modal">+ <div class="ckpt-modal-title">Confirm Delete</div>+ <div class="ckpt-modal-body" id="ckpt-delete-modal-body"></div>+ <div class="ckpt-modal-actions">+ <button class="ckpt-modal-btn" id="ckpt-delete-cancel">Cancel</button>+ <button class="ckpt-modal-btn danger" id="ckpt-delete-unique">Delete Unique</button>+ <button class="ckpt-modal-btn danger" id="ckpt-delete-all">Delete Unique + Shared</button>+ </div>+ </div>+ `;+ document.body.appendChild(backdrop);+ const cancelBtn = backdrop.querySelector('#ckpt-delete-cancel');+ const uniqueBtn = backdrop.querySelector('#ckpt-delete-unique');+ const allBtn = backdrop.querySelector('#ckpt-delete-all');+ cancelBtn.addEventListener('click', () => {+ backdrop.style.display = 'none';+ backdrop.dataset.payloadUnique = '';+ backdrop.dataset.payloadAll = '';+ });+ uniqueBtn.addEventListener('click', () => {+ const payload = backdrop.dataset.payloadUnique || '';+ if (payload) {+ window.updatemodelInput("model_action_input", payload);+ }+ backdrop.style.display = 'none';+ backdrop.dataset.payloadUnique = '';+ backdrop.dataset.payloadAll = '';+ });+ allBtn.addEventListener('click', () => {+ const payload = backdrop.dataset.payloadAll || '';+ if (payload) {+ window.updatemodelInput("model_action_input", payload);+ }+ backdrop.style.display = 'none';+ backdrop.dataset.payloadUnique = '';+ backdrop.dataset.payloadAll = '';+ });+ backdrop.addEventListener('click', (evt) => {+ if (evt.target === backdrop) {+ backdrop.style.display = 'none';+ backdrop.dataset.payloadUnique = '';+ backdrop.dataset.payloadAll = '';+ }+ });+ return backdrop;+ }++ function showmodelModal(message, payloadUnique, payloadAll, uniqueSize, totalSize) {+ const backdrop = ensuremodelModal();+ const body = backdrop.querySelector('#ckpt-delete-modal-body');+ const uniqueBtn = backdrop.querySelector('#ckpt-delete-unique');+ const allBtn = backdrop.querySelector('#ckpt-delete-all');+ body.textContent = message;+ backdrop.dataset.payloadUnique = payloadUnique || '';+ backdrop.dataset.payloadAll = payloadAll || '';+ uniqueBtn.textContent = uniqueSize ? `Delete Unique (${uniqueSize})` : 'Delete Unique';+ allBtn.textContent = totalSize ? `Delete Unique + Shared (${totalSize})` : 'Delete Unique + Shared';+ backdrop.style.display = 'flex';+ }++ window.handlemodelAction = function(button, action) {+ if (!button) return;+ const nodeId = button.dataset.nodeId;+ const nodeLabel = button.dataset.nodeLabel || nodeId;+ const uniqueSize = button.dataset.uniqueSize || "0 B";+ const totalSize = button.dataset.totalSize || uniqueSize;+ if (!nodeId) return;+ if (action === "delete") {+ const payloadUnique = JSON.stringify({+ action: action,+ node_id: nodeId,+ delete_shared: false,+ ts: Date.now()+ });+ const payloadAll = JSON.stringify({+ action: action,+ node_id: nodeId,+ delete_shared: true,+ ts: Date.now()+ });+ showmodelModal(+ `Choose delete scope for "${nodeLabel}": unique only ${uniqueSize}, or unique + shared ${totalSize}.`,+ payloadUnique,+ payloadAll,+ uniqueSize,+ totalSize+ );+ return;+ }+ const payload = JSON.stringify({+ action: action,+ node_id: nodeId,+ ts: Date.now()+ });+ window.updatemodelInput("model_action_input", payload);+ };++ window.handlemodelRowClick = function(evt, row) {+ if (evt) evt.stopPropagation();+ if (!row) return;+ const nodeId = row.dataset.nodeId;+ if (!nodeId) return;+ const payload = JSON.stringify({+ action: "view",+ node_id: nodeId,+ ts: Date.now()+ });+ window.updatemodelInput("model_action_input", payload);+ };++ function ismodelTabActive() {+ const root = modelRoot();+ const tabs = root.querySelectorAll('button[role="tab"]');+ for (const tab of tabs) {+ if (tab.getAttribute('aria-selected') === 'true') {+ const label = (tab.textContent || '').trim();+ if (label === 'Models Manager') return true;+ }+ }+ return false;+ }++ function triggermodelRefresh() {+ const root = modelRoot();+ const btn = root.querySelector('#ckpt_refresh_btn button') || root.querySelector('#ckpt_refresh_btn');+ if (btn) btn.click();+ }++ function applymodelSticky() {+ const root = modelRoot();+ const sticky = root.querySelector('.ckpt-view-sticky');+ if (!sticky) return;+ sticky.style.position = 'sticky';+ sticky.style.top = '16px';+ sticky.style.alignSelf = 'flex-start';+ let parent = sticky.parentElement;+ let steps = 0;+ while (parent && steps < 6) {+ const style = window.getComputedStyle(parent);+ if (style.overflow && style.overflow !== 'visible') {+ parent.style.overflow = 'visible';+ }+ parent = parent.parentElement;+ steps += 1;+ }+ if (root && root.host && root.host.style) {+ const hostStyle = window.getComputedStyle(root.host);+ if (hostStyle.overflow && hostStyle.overflow !== 'visible') {+ root.host.style.overflow = 'visible';+ }+ }+ }++ let ckptFloating = {+ sticky: null,+ scrollEl: null,+ handler: null,+ resizeHandler: null,+ anchorTop: 0,+ topPadding: 16,+ };++ function findmodelScrollContainer(element) {+ let current = element;+ while (current) {+ const style = window.getComputedStyle(current);+ const overflowY = style.overflowY;+ if ((overflowY === 'auto' || overflowY === 'scroll') && current.scrollHeight > current.clientHeight + 1) {+ return current;+ }+ current = current.parentElement;+ }+ const root = modelRoot();+ const host = root && root.host ? root.host : null;+ current = host;+ while (current) {+ const style = window.getComputedStyle(current);+ const overflowY = style.overflowY;+ if ((overflowY === 'auto' || overflowY === 'scroll') && current.scrollHeight > current.clientHeight + 1) {+ return current;+ }+ current = current.parentElement;+ }+ return window;+ }++ function computemodelAnchorTop(sticky, scrollEl) {+ if (scrollEl === window) {+ return sticky.getBoundingClientRect().top + window.scrollY;+ }+ const rect = sticky.getBoundingClientRect();+ const containerRect = scrollEl.getBoundingClientRect();+ return rect.top - containerRect.top + scrollEl.scrollTop;+ }++ function clearmodelFloating(sticky) {+ if (!sticky) return;+ sticky.style.transform = '';+ sticky.style.willChange = '';+ }++ function updatemodelFloating() {+ const sticky = ckptFloating.sticky;+ if (!sticky) return;+ const scrollEl = ckptFloating.scrollEl || window;+ const scrollTop = scrollEl === window ? window.scrollY : scrollEl.scrollTop;+ let maxTranslate = Infinity;+ if (scrollEl === window) {+ const doc = document.documentElement;+ maxTranslate = Math.max(+ 0,+ (doc ? doc.scrollHeight : 0) - sticky.offsetHeight - ckptFloating.topPadding - ckptFloating.anchorTop+ );+ } else {+ maxTranslate = Math.max(+ 0,+ scrollEl.scrollHeight - sticky.offsetHeight - ckptFloating.topPadding - ckptFloating.anchorTop+ );+ }+ const offset = scrollTop + ckptFloating.topPadding - ckptFloating.anchorTop;+ const translate = Math.max(0, Math.min(offset, maxTranslate));+ if (translate > 0) {+ sticky.style.transform = `translateY(${translate}px)`;+ sticky.style.willChange = 'transform';+ } else {+ clearmodelFloating(sticky);+ }+ }++ function teardownmodelFloating() {+ if (ckptFloating.scrollEl && ckptFloating.handler) {+ if (ckptFloating.scrollEl === window) {+ window.removeEventListener('scroll', ckptFloating.handler);+ } else {+ ckptFloating.scrollEl.removeEventListener('scroll', ckptFloating.handler);+ }+ }+ if (ckptFloating.resizeHandler) {+ window.removeEventListener('resize', ckptFloating.resizeHandler);+ }+ clearmodelFloating(ckptFloating.sticky);+ if (ckptFloating.sticky) {+ ckptFloating.sticky.style.position = '';+ ckptFloating.sticky.style.top = '';+ }+ ckptFloating.sticky = null;+ ckptFloating.scrollEl = null;+ ckptFloating.handler = null;+ ckptFloating.resizeHandler = null;+ ckptFloating.anchorTop = 0;+ }++ function setupmodelFloating() {+ const root = modelRoot();+ const sticky = root.querySelector('.ckpt-view-sticky');+ if (!sticky) return;+ if (ckptFloating.sticky === sticky) {+ updatemodelFloating();+ return;+ }+ teardownmodelFloating();+ ckptFloating.sticky = sticky;+ sticky.style.position = 'relative';+ sticky.style.top = '0px';+ ckptFloating.scrollEl = findmodelScrollContainer(sticky);+ ckptFloating.anchorTop = computemodelAnchorTop(sticky, ckptFloating.scrollEl);+ ckptFloating.handler = () => updatemodelFloating();+ if (ckptFloating.scrollEl === window) {+ window.addEventListener('scroll', ckptFloating.handler, { passive: true });+ } else {+ ckptFloating.scrollEl.addEventListener('scroll', ckptFloating.handler, { passive: true });+ }+ ckptFloating.resizeHandler = () => {+ ckptFloating.anchorTop = computemodelAnchorTop(sticky, ckptFloating.scrollEl);+ updatemodelFloating();+ };+ window.addEventListener('resize', ckptFloating.resizeHandler);+ updatemodelFloating();+ }++ function observemodelView() {+ const root = modelRoot();+ const column = root.querySelector('.ckpt-right-column');+ if (!column || column.dataset.ckptObserved === '1') return;+ column.dataset.ckptObserved = '1';+ const observer = new MutationObserver(() => {+ applymodelSticky();+ setupmodelFloating();+ });+ observer.observe(column, { childList: true, subtree: true });+ }++ let ckptTabWasActive = false;+ let ckptRefreshBusy = false;+ let ckptRefreshStartedAt = 0;++ function waitForRefreshReady() {+ const root = modelRoot();+ const treeRoot = root.querySelector('#ckpt_tree_root');+ if (treeRoot && treeRoot.dataset.status === 'ready') {+ ckptRefreshBusy = false;+ applymodelSticky();+ setupmodelFloating();+ return;+ }+ if (ckptRefreshStartedAt && Date.now() - ckptRefreshStartedAt > 60000) {+ ckptRefreshBusy = false;+ applymodelSticky();+ setupmodelFloating();+ return;+ }+ setTimeout(waitForRefreshReady, 400);+ }++ function startmodelBuild() {+ if (ckptRefreshBusy) return;+ ckptRefreshBusy = true;+ ckptRefreshStartedAt = Date.now();+ triggermodelRefresh();+ setTimeout(waitForRefreshReady, 200);+ }++ function handleTabChange() {+ const active = ismodelTabActive();+ if (active && !ckptTabWasActive) {+ startmodelBuild();+ }+ if (active) {+ observemodelView();+ setTimeout(applymodelSticky, 200);+ setTimeout(setupmodelFloating, 260);+ }+ ckptTabWasActive = active;+ }++ function initmodelBridge() {+ const root = modelRoot();+ const tabs = root.querySelectorAll('button[role="tab"]');+ if (!tabs || tabs.length === 0) {+ setTimeout(initmodelBridge, 400);+ return;+ }+ const tabObserver = new MutationObserver(handleTabChange);+ tabObserver.observe(root, { attributes: true, subtree: true, attributeFilter: ['aria-selected', 'class'] });+ handleTabChange();+ }++ initmodelBridge();+ """++ def _show_loading(self):+ tree_loading = self._build_loading_html()+ view_hidden = gr.update(value="", visible=False)+ refresh_hidden = gr.update(visible=False)+ return tree_loading, view_hidden, refresh_hidden++ def _build_tree(self):+ self._build_cache()+ tree_html = self._build_tree_html()+ view_html = self._build_empty_view_html()+ view_visible = gr.update(value=view_html, visible=True)+ refresh_visible = gr.update(visible=True)+ return tree_html, view_visible, refresh_visible++ def _handle_action(self, payload: str):+ if not payload:+ return gr.update(), gr.update(), gr.update()+ try:+ data = json.loads(payload)+ except json.JSONDecodeError:+ return gr.update(), gr.update(), gr.update()++ action = data.get("action")+ node_id = data.get("node_id")+ if not action or not node_id:+ return gr.update(), gr.update(), gr.update()++ if not self._node_map:+ self._build_cache()++ if action == "view":+ view_html = self._build_view_html(node_id)+ return gr.update(), gr.update(value=view_html, visible=True), gr.update()++ if action == "delete":+ delete_shared = bool(data.get("delete_shared"))+ removed, missing, errors = self._delete_files_for_node(+ node_id, delete_shared=delete_shared+ )+ if errors:+ gr.Warning(f"Delete completed with errors: {len(errors)}")+ else:+ gr.Info(f"Deleted {len(removed)} files (missing: {len(missing)})")+ return self._build_tree()++ return gr.update(), gr.update(), gr.update()++ def _delete_files_for_node(self, node_id, delete_shared=False):+ node = self._node_map.get(node_id)+ if node is None:+ return [], [], []+ removed = []+ missing = []+ errors = []+ if delete_shared:+ target_files = node.get("files", set())+ else:+ target_files = node.get("unique_files", set())+ for path in sorted(target_files):+ if not os.path.isfile(path):+ missing.append(path)+ continue+ try:+ os.remove(path)+ removed.append(path)+ except OSError as exc:+ errors.append((path, str(exc)))+ return removed, missing, errors++ def _build_cache(self):+ self._node_map = {}+ self._tree_data = []+ self._model_files = {}+ self._model_primary = {}+ self._model_variants = {}+ self._variant_to_model = {}+ self._model_base_label = {}+ self._model_family_label = {}+ self._model_usage_ids = {}+ self._usage_files = {}+ self._file_usage = defaultdict(set)+ self._file_usage_models = defaultdict(set)+ self._file_info = {}+ self._basename_index = {}+ self._errors = []+ self._stats_total = 0+ self._stats_by_drive = []++ model_types = self._get_model_types()+ for model_type in model_types:+ try:+ variant_info = self._collect_model_variants(model_type)+ except Exception as exc:+ self._errors.append(f"{model_type}: {exc}")+ variant_info = {"variants": [], "primary_paths": [], "files": set()}+ variants = variant_info.get("variants", [])+ model_files = variant_info.get("files", set())+ self._model_variants[model_type] = variants+ self._model_primary[model_type] = variant_info.get("primary_paths", [])+ self._model_files[model_type] = model_files+ for path in model_files:+ self._file_usage_models[path].add(model_type)++ self._rebalance_other_shared_variants(model_types)++ self._usage_files = {}+ self._file_usage = defaultdict(set)+ self._variant_to_model = {}+ self._model_usage_ids = {}+ for model_type in model_types:+ usage_ids = set()+ for variant in self._model_variants.get(model_type, []):+ variant_id = variant["id"]+ usage_ids.add(variant_id)+ self._variant_to_model[variant_id] = model_type+ files = variant.get("files", set())+ self._usage_files[variant_id] = files+ for path in files:+ self._file_usage[path].add(variant_id)+ self._model_usage_ids[model_type] = usage_ids++ for path in self._file_usage_models.keys():+ try:+ exists = os.path.isfile(path)+ size = os.path.getsize(path) if exists else 0+ except OSError:+ exists = False+ size = 0+ self._file_info[path] = {"size": size, "exists": exists}++ self._compute_global_stats()+ self._build_tree_structure(model_types)++ def _compute_global_stats(self):+ total = 0+ by_drive = defaultdict(int)+ for path, info in self._file_info.items():+ size = info.get("size", 0)+ if size <= 0:+ continue+ total += size+ drive = self._get_drive_label(path)+ by_drive[drive] += size+ self._stats_total = total+ self._stats_by_drive = sorted(+ by_drive.items(), key=lambda item: (-item[1], item[0])+ )++ def _get_drive_label(self, path):+ drive, _ = os.path.splitdrive(path)+ if drive:+ return drive.rstrip(":").upper()+ if path.startswith("\\\\"):+ return "UNC"+ return "ROOT"++ def _get_model_types(self):+ types = []+ if isinstance(getattr(self, "models_def", None), dict) and self.models_def:+ types = sorted(self.models_def.keys())+ elif isinstance(self.transformer_types, list) and self.transformer_types:+ types = list(self.transformer_types)+ elif isinstance(self.displayed_model_types, list):+ types = list(self.displayed_model_types)+ seen = set()+ ordered = []+ for model_type in types:+ if model_type and model_type not in seen:+ ordered.append(model_type)+ seen.add(model_type)+ return ordered++ def _collect_model_variants(self, model_type):+ model_def = self.get_model_def(model_type)+ if model_def is None:+ return {"variants": [], "primary_paths": [], "files": set()}++ default_dtype_policy = self._resolve_default_dtype_policy(model_type, model_def)+ transformer_variants = self._collect_transformer_variants(+ model_type, model_def, default_dtype_policy+ )+ text_encoder_variants = self._collect_text_encoder_variants(+ model_type, model_def, default_dtype_policy+ )+ transformer_files = set()+ text_encoder_files = set()+ model_primary_paths = []+ for variant in transformer_variants:+ transformer_files.update(variant["files"])+ model_primary_paths.extend(variant.get("primary_paths", []))+ for variant in text_encoder_variants:+ text_encoder_files.update(variant["files"])+ model_primary_paths.extend(variant.get("primary_paths", []))+ model_primary_paths = self._dedupe_paths(model_primary_paths)++ other_files, shared_files = self._collect_other_files(+ model_type,+ model_def,+ transformer_files,+ text_encoder_files,+ )+ variants = list(transformer_variants) + list(text_encoder_variants)+ if other_files:+ other_id = self._make_variant_id(model_type, "other", "other")+ variants.append(+ {+ "id": other_id,+ "label": "Other",+ "type": "variant",+ "files": other_files,+ "primary_paths": [],+ }+ )+ if shared_files:+ shared_id = self._make_variant_id(model_type, "shared", "shared")+ variants.append(+ {+ "id": shared_id,+ "label": "Shared",+ "type": "variant",+ "files": shared_files,+ "primary_paths": [],+ }+ )++ model_files = set()+ for variant in variants:+ model_files.update(variant.get("files", set()))++ return {+ "variants": variants,+ "primary_paths": model_primary_paths,+ "files": model_files,+ }++ def _collect_transformer_variants(+ self, model_type, model_def, default_dtype_policy+ ):+ choice_lists, modules = self._collect_transformer_choice_lists(model_type, model_def)+ base_dtypes, token_dtypes, token_labels = self._collect_variant_candidates(+ choice_lists, default_dtype_policy+ )+ variants = []+ used_labels = set()++ base_default = self._format_dtype_label(default_dtype_policy)+ if base_dtypes:+ for dtype_policy in sorted(base_dtypes):+ label = self._format_variant_label("", dtype_policy, base_default)+ files, primary_paths = self._collect_transformer_files_for_variant(+ model_type, model_def, modules, "", dtype_policy+ )+ if not files:+ continue+ file_label = self._detect_quant_label_from_files(files)+ label = file_label or label+ variant_label = f"Transformer {label}"+ variant_id = self._make_variant_id(model_type, "transformer", label)+ variants.append(+ {+ "id": variant_id,+ "label": variant_label,+ "type": "variant",+ "files": files,+ "primary_paths": primary_paths,+ }+ )+ used_labels.add(variant_label)++ for token, dtypes in sorted(token_dtypes.items()):+ quant_param = self._quant_param_from_token(token)+ quant_label = token_labels.get(token) or self._format_quant_label(token)+ for dtype_policy in sorted(dtypes):+ label_suffix = ""+ if len(dtypes) > 1:+ label_suffix = f" {self._format_dtype_label(dtype_policy)}"+ label = f"{quant_label}{label_suffix}"+ files, primary_paths = self._collect_transformer_files_for_variant(+ model_type,+ model_def,+ modules,+ quant_param,+ dtype_policy,+ token_match=token,+ )+ if not files:+ continue+ file_label = self._detect_quant_label_from_files(files)+ quant_label = file_label or quant_label+ if not self._files_match_token(files, token):+ continue+ label = f"{quant_label}{label_suffix}" if quant_label else self._format_dtype_label(dtype_policy)+ variant_label = f"Transformer {label}"+ if variant_label in used_labels:+ continue+ variant_id = self._make_variant_id(model_type, "transformer", label)+ variants.append(+ {+ "id": variant_id,+ "label": variant_label,+ "type": "variant",+ "files": files,+ "primary_paths": primary_paths,+ }+ )+ used_labels.add(variant_label)++ return sorted(variants, key=lambda v: v["label"].lower())++ def _collect_transformer_choice_lists(self, model_type, model_def):+ choice_lists = []+ modules = self._expand_modules(model_type)++ urls = self.get_model_recursive_prop(model_type, "URLs", return_list=True)+ if urls:+ choice_lists.append(urls)+ if "URLs2" in model_def:+ urls2 = self.get_model_recursive_prop(model_type, "URLs2", return_list=True)+ if urls2:+ choice_lists.append(urls2)++ has_module_source = "module_source" in model_def+ has_module_source2 = "module_source2" in model_def+ for module in modules:+ if isinstance(module, dict):+ urls1 = module.get("URLs", [])+ urls2 = module.get("URLs2", [])+ if urls1 and not has_module_source:+ choice_lists.append(urls1)+ if urls2 and not has_module_source2:+ choice_lists.append(urls2)+ elif isinstance(module, list):+ if has_module_source:+ continue+ if module:+ choice_lists.append(module)+ else:+ if has_module_source:+ continue+ module_type = module+ sub_prop_name = "_list"+ if isinstance(module_type, str) and "#" in module_type:+ pos = module_type.rfind("#")+ sub_prop_name = module_type[pos + 1 :]+ module_type = module_type[:pos]+ try:+ mod_urls = self.get_model_recursive_prop(+ module_type, "modules", sub_prop_name=sub_prop_name, return_list=True+ )+ except Exception:+ mod_urls = []+ if isinstance(mod_urls, list) and mod_urls:+ if all(isinstance(item, list) for item in mod_urls):+ for entry in mod_urls:+ if entry:+ choice_lists.append(entry)+ else:+ choice_lists.append(mod_urls)+ return choice_lists, modules++ def _collect_transformer_files_for_variant(+ self,+ model_type,+ model_def,+ modules,+ quantization,+ dtype_policy,+ token_match=None,+ ):+ files = set()+ primary_paths = []++ model_filename = ""+ is_exotic = quantization not in ("", "int8", "fp8")+ if token_match and is_exotic:+ urls = self.get_model_recursive_prop(model_type, "URLs", return_list=True)+ model_filename = self._select_filename_by_token(urls, token_match)+ if not model_filename:+ model_filename = self.get_model_filename(+ model_type=model_type,+ quantization=quantization,+ dtype_policy=dtype_policy,+ )+ if model_filename:+ self._add_file(files, model_filename)+ primary_path = self._resolve_path(model_filename)+ if primary_path and primary_path in files:+ primary_paths.append(primary_path)++ if "URLs2" in model_def:+ model_filename2 = ""+ if token_match and is_exotic:+ urls2 = self.get_model_recursive_prop(+ model_type, "URLs2", return_list=True+ )+ model_filename2 = self._select_filename_by_token(urls2, token_match)+ if not model_filename2:+ model_filename2 = self.get_model_filename(+ model_type=model_type,+ quantization=quantization,+ dtype_policy=dtype_policy,+ submodel_no=2,+ )+ if model_filename2:+ self._add_file(files, model_filename2)+ primary_path2 = self._resolve_path(model_filename2)+ if primary_path2 and primary_path2 in files:+ primary_paths.append(primary_path2)++ has_module_source = "module_source" in model_def+ has_module_source2 = "module_source2" in model_def+ for module in modules:+ if isinstance(module, dict):+ urls1 = module.get("URLs", [])+ urls2 = module.get("URLs2", [])+ if urls1 and not has_module_source:+ filename = ""+ if token_match and is_exotic:+ filename = self._select_filename_by_token(urls1, token_match)+ if not filename:+ filename = self.get_model_filename(+ model_type=model_type,+ quantization=quantization,+ dtype_policy=dtype_policy,+ URLs=urls1,+ )+ if filename:+ self._add_file(files, filename)+ if urls2 and not has_module_source2:+ filename = ""+ if token_match and is_exotic:+ filename = self._select_filename_by_token(urls2, token_match)+ if not filename:+ filename = self.get_model_filename(+ model_type=model_type,+ quantization=quantization,+ dtype_policy=dtype_policy,+ URLs=urls2,+ )+ if filename:+ self._add_file(files, filename)+ elif isinstance(module, list):+ if has_module_source:+ continue+ filename = ""+ if token_match and is_exotic:+ filename = self._select_filename_by_token(module, token_match)+ if not filename:+ filename = self.get_model_filename(+ model_type=model_type,+ quantization=quantization,+ dtype_policy=dtype_policy,+ URLs=module,+ )+ if filename:+ self._add_file(files, filename)+ else:+ if has_module_source:+ continue+ if token_match and is_exotic:+ module_type = module+ sub_prop_name = "_list"+ if isinstance(module_type, str) and "#" in module_type:+ pos = module_type.rfind("#")+ sub_prop_name = module_type[pos + 1 :]+ module_type = module_type[:pos]+ try:+ mod_urls = self.get_model_recursive_prop(+ module_type,+ "modules",+ sub_prop_name=sub_prop_name,+ return_list=True,+ )+ except Exception:+ mod_urls = []+ filename = self._select_filename_by_token(mod_urls, token_match)+ else:+ filename = ""+ try:+ if not filename:+ filename = self.get_model_filename(+ model_type=model_type,+ quantization=quantization,+ dtype_policy=dtype_policy,+ module_type=module,+ )+ except Exception:+ filename = ""+ if filename:+ self._add_file(files, filename)++ return files, primary_paths++ def _collect_text_encoder_variants(+ self, model_type, model_def, default_dtype_policy+ ):+ variants = []+ text_encoder_urls = self.get_model_recursive_prop(+ model_type, "text_encoder_URLs", return_list=True+ )+ text_encoder_folder = model_def.get("text_encoder_folder", None)+ used_paths = set()+ used_labels = set()+ base_default = self._format_dtype_label(default_dtype_policy)+ if text_encoder_urls:+ base_dtypes, token_dtypes, token_labels = self._collect_variant_candidates(+ [text_encoder_urls], default_dtype_policy+ )+ if base_dtypes:+ for dtype_policy in sorted(base_dtypes):+ label = self._format_variant_label("", dtype_policy, base_default)+ filename = self.get_model_filename(+ model_type=model_type,+ quantization="",+ dtype_policy=dtype_policy,+ URLs=text_encoder_urls,+ )+ if not filename:+ continue+ files = set()+ self._add_file(+ files, filename, force_folder=text_encoder_folder+ )+ if not files:+ continue+ resolved_path = next(iter(files))+ if resolved_path in used_paths:+ continue+ used_paths.add(resolved_path)+ variant_label = f"Text Encoder {label}"+ if variant_label in used_labels:+ continue+ variant_id = self._make_variant_id(model_type, "text", label)+ variants.append(+ {+ "id": variant_id,+ "label": variant_label,+ "type": "variant",+ "files": files,+ "primary_paths": [resolved_path],+ }+ )+ used_labels.add(variant_label)++ for token, dtypes in sorted(token_dtypes.items()):+ quant_param = self._quant_param_from_token(token)+ quant_label = token_labels.get(token) or self._format_quant_label(token)+ for dtype_policy in sorted(dtypes):+ label_suffix = ""+ if len(dtypes) > 1:+ label_suffix = f" {self._format_dtype_label(dtype_policy)}"+ label = f"{quant_label}{label_suffix}"+ filename = ""+ if quant_param not in ("", "int8", "fp8"):+ filename = self._select_filename_by_token(text_encoder_urls, token)+ if not filename:+ filename = self.get_model_filename(+ model_type=model_type,+ quantization=quant_param,+ dtype_policy=dtype_policy,+ URLs=text_encoder_urls,+ )+ if not filename:+ continue+ files = set()+ self._add_file(+ files, filename, force_folder=text_encoder_folder+ )+ if not files:+ continue+ if not self._files_match_token(files, token):+ continue+ file_label = self._detect_quant_label_from_files(files)+ quant_label = file_label or quant_label+ resolved_path = next(iter(files))+ if resolved_path in used_paths:+ continue+ used_paths.add(resolved_path)+ label = f"{quant_label}{label_suffix}" if quant_label else self._format_dtype_label(dtype_policy)+ variant_label = f"Text Encoder {label}"+ if variant_label in used_labels:+ continue+ variant_id = self._make_variant_id(model_type, "text", label)+ variants.append(+ {+ "id": variant_id,+ "label": variant_label,+ "type": "variant",+ "files": files,+ "primary_paths": [resolved_path],+ }+ )+ used_labels.add(variant_label)+ else:+ handler = self.get_model_handler(model_type)+ get_name = getattr(handler, "get_text_encoder_filename", None)+ if get_name is not None:+ for quant_param in self._text_encoder_quant_candidates():+ try:+ filename = get_name(quant_param)+ except Exception:+ filename = None+ if not filename:+ continue+ files = set()+ self._add_file(+ files, filename, force_folder=text_encoder_folder+ )+ if not files:+ continue+ resolved_path = next(iter(files))+ if resolved_path in used_paths:+ continue+ used_paths.add(resolved_path)+ quant_label = self._detect_quant_label_from_files(files)+ label = quant_label or self._format_variant_label(+ "",+ self._detect_dtype_policy_from_name(os.path.basename(filename))+ or default_dtype_policy,+ base_default,+ )+ variant_label = f"Text Encoder {label}"+ if variant_label in used_labels:+ continue+ variant_id = self._make_variant_id(model_type, "text", label)+ variants.append(+ {+ "id": variant_id,+ "label": variant_label,+ "type": "variant",+ "files": files,+ "primary_paths": [resolved_path],+ }+ )+ used_labels.add(variant_label)++ return sorted(variants, key=lambda v: v["label"].lower())++ def _collect_other_files(+ self,+ model_type,+ model_def,+ transformer_files,+ text_encoder_files,+ ):+ other_files = set()+ shared_files = set()++ preload_urls = self.get_model_recursive_prop(+ model_type, "preload_URLs", return_list=True+ )+ for url in self._ensure_list(preload_urls):+ self._add_file(other_files, url)++ vae_urls = model_def.get("VAE_URLs", [])+ for url in self._ensure_list(vae_urls):+ self._add_file(shared_files, url)++ loras = self.get_model_recursive_prop(model_type, "loras", return_list=True)+ for url in self._ensure_list(loras):+ lora_dir = self._safe_get_lora_dir(model_type)+ if lora_dir:+ lora_path = os.path.join(lora_dir, os.path.basename(url))+ self._add_file(other_files, lora_path)++ handler_files = self._collect_handler_files(model_type, model_def)+ shared_files.update(handler_files)++ other_files.difference_update(transformer_files)+ other_files.difference_update(text_encoder_files)+ shared_files.difference_update(transformer_files)+ shared_files.difference_update(text_encoder_files)+ shared_files.difference_update(other_files)+ return other_files, shared_files++ def _resolve_default_dtype_policy(self, model_type, model_def):+ dtype = model_def.get("dtype")+ if isinstance(dtype, str) and dtype.lower() in ("fp16", "bf16"):+ return dtype.lower()+ policy = self.transformer_dtype_policy+ if isinstance(policy, str) and policy:+ return policy.lower()+ return "bf16"++ def _format_dtype_label(self, dtype_policy):+ return "FP16" if dtype_policy == "fp16" else "BF16"++ def _format_quant_label(self, token):+ if not token:+ return ""+ label = quant_router.get_quantization_label(token)+ if label:+ return label+ return str(token).replace("_", " ").upper()++ def _format_variant_label(self, token, dtype_policy, default_label):+ if token:+ return self._format_quant_label(token)+ if dtype_policy:+ return self._format_dtype_label(dtype_policy)+ return default_label++ def _detect_quant_info(self, name):+ if not name:+ return "", ""+ label = quant_router.detect_quantization_label_from_filename(name) or ""+ if label:+ return self._label_to_token(label), label+ kind = quant_router.detect_quantization_kind_for_file(name, verboseLevel=0)+ if kind and kind != "none":+ kind = str(kind).lower()+ return kind, kind.upper()+ lower = str(name).lower()+ aliases = self._get_quant_aliases()+ for token in aliases:+ if token in ("bf16", "fp16", "bfloat16", "float16"):+ continue+ if token and token in lower:+ return token, ""+ return "", ""++ def _label_to_token(self, label):+ if not label:+ return ""+ raw = str(label).strip()+ lower = raw.lower()+ if lower.startswith("gguf-"):+ return lower.split("-", 1)[1]+ if lower == "gguf":+ return "gguf"+ return lower++ def _detect_dtype_policy_from_name(self, name):+ if not name:+ return ""+ lower = str(name).lower()+ if "fp16" in lower or "float16" in lower:+ return "fp16"+ if "bf16" in lower or "bfloat16" in lower:+ return "bf16"+ return ""++ def _collect_variant_candidates(self, choice_lists, default_dtype_policy):+ base_dtypes = set()+ token_dtypes = defaultdict(set)+ token_labels = {}+ for choice_list in choice_lists:+ for entry in self._ensure_list(choice_list):+ if not entry:+ continue+ entry_str = str(entry)+ name = os.path.basename(entry_str)+ quant_source = self._resolve_path(entry_str) or entry_str+ token, label = self._detect_quant_info(quant_source)+ dtype_policy = self._detect_dtype_policy_from_name(name) or default_dtype_policy+ if token:+ token = str(token).lower()+ token_dtypes[token].add(dtype_policy)+ if label:+ token_labels.setdefault(token, label)+ else:+ base_dtypes.add(dtype_policy)+ if not base_dtypes and not token_dtypes:+ base_dtypes.add(default_dtype_policy)+ return base_dtypes, token_dtypes, token_labels++ def _quant_param_from_token(self, token):+ if not token:+ return ""+ lower = str(token).lower()+ if "int8" in lower:+ return "int8"+ if "fp8" in lower or "float8" in lower:+ return "fp8"+ return lower++ def _files_match_token(self, files, token):+ if not token:+ return True+ token = str(token).lower()+ for path in files:+ base = os.path.basename(path).lower()+ if token in base:+ return True+ label = quant_router.detect_quantization_label_from_filename(path)+ if label and self._label_to_token(label) == token:+ return True+ return False++ def _detect_quant_label_from_files(self, files):+ for path in files:+ label = quant_router.detect_quantization_label_from_filename(path)+ if label:+ return label+ return ""++ def _select_filename_by_token(self, urls, token):+ if not urls or not token:+ return ""+ token = str(token).lower()+ for entry in self._ensure_list(urls):+ if not entry:+ continue+ if isinstance(entry, list):+ for item in entry:+ if not item:+ continue+ base = os.path.basename(str(item)).lower()+ if token in base:+ return item+ label = quant_router.detect_quantization_label_from_filename(item)+ if label and self._label_to_token(label) == token:+ return item+ continue+ base = os.path.basename(str(entry)).lower()+ if token in base:+ return entry+ label = quant_router.detect_quantization_label_from_filename(entry)+ if label and self._label_to_token(label) == token:+ return entry+ return ""++ def _expand_modules(self, model_type):+ modules = self.get_model_recursive_prop(model_type, "modules", return_list=True)+ expanded_modules = []+ for module in modules:+ if isinstance(module, str):+ if "#" in module:+ expanded_modules.append(module)+ continue+ try:+ expanded = self.get_model_recursive_prop(+ module, "modules", sub_prop_name="_list", return_list=True+ )+ except Exception:+ expanded = []+ if expanded:+ expanded_modules.append(expanded)+ else:+ expanded_modules.append(module)+ else:+ expanded_modules.append(module)+ return expanded_modules++ def _make_variant_id(self, model_type, kind, label):+ slug = "".join(ch.lower() if ch.isalnum() else "_" for ch in label).strip("_")+ return f"variant::{model_type}::{kind}::{slug}"++ def _dedupe_paths(self, paths):+ seen = set()+ ordered = []+ for path in paths:+ if not path or path in seen:+ continue+ ordered.append(path)+ seen.add(path)+ return ordered++ def _get_quant_aliases(self):+ if not hasattr(self, "_quant_alias_cache"):+ aliases = set(quant_router.get_available_qtype_aliases() or [])+ aliases.update({"int8", "int8n", "fp8"})+ self._quant_alias_cache = sorted(+ {alias for alias in aliases if alias}, key=len, reverse=True+ )+ return self._quant_alias_cache++ def _text_encoder_quant_candidates(self):+ candidates = {""}+ aliases = self._get_quant_aliases()+ for token in aliases:+ if "int8" in token:+ candidates.add("int8")+ if "fp8" in token or "float8" in token:+ candidates.add("fp8")+ return sorted(candidates)++ def _collect_text_encoder_files(self, model_type, model_def):+ files = set()+ text_encoder_urls = self.get_model_recursive_prop(+ model_type, "text_encoder_URLs", return_list=True+ )+ text_encoder_folder = model_def.get("text_encoder_folder", None)+ text_encoder_filename = None+ if text_encoder_urls:+ text_encoder_filename = self.get_model_filename(+ model_type=model_type,+ quantization=self.text_encoder_quantization,+ dtype_policy=self.transformer_dtype_policy,+ URLs=text_encoder_urls,+ )+ else:+ handler = self.get_model_handler(model_type)+ get_name = getattr(handler, "get_text_encoder_filename", None)+ if get_name is not None:+ try:+ text_encoder_filename = get_name(self.text_encoder_quantization)+ except Exception:+ text_encoder_filename = None+ if text_encoder_filename:+ self._add_file(files, text_encoder_filename, force_folder=text_encoder_folder)+ return files++ def _collect_handler_files(self, model_type, model_def):+ handler = self.get_model_handler(model_type)+ query = getattr(handler, "query_model_files", None)+ if query is None:+ return set()+ base_model_type = self.get_base_model_type(model_type)+ try:+ download_defs = query(+ self._compute_list,+ base_model_type,+ model_def,+ )+ except Exception as exc:+ self._errors.append(f"{model_type}: {exc}")+ return set()++ if not download_defs:+ return set()+ if isinstance(download_defs, dict):+ download_defs = [download_defs]++ files = set()+ for download_def in download_defs:+ source_folders = download_def.get("sourceFolderList", [])+ file_lists = download_def.get("fileList", [])+ target_folders = download_def.get("targetFolderList")+ if target_folders is None:+ target_folders = [None] * len(source_folders)++ for source_folder, file_list, target_folder in zip(+ source_folders, file_lists, target_folders+ ):+ if target_folder == "":+ target_folder = None+ if source_folder is None:+ source_folder = ""++ if not file_list:+ continue++ for filename in file_list:+ if not filename:+ continue+ rel_path = self._combine_download_path(+ target_folder, source_folder, filename+ )+ files.add(self._resolve_download_relpath(rel_path))+ return {path for path in files if path and os.path.isfile(path)}++ def _build_tree_structure(self, model_types):+ families = defaultdict(list)+ for model_type in model_types:+ family = self.get_model_family(model_type, for_ui=True) or "unknown"+ families[family].append(model_type)++ family_order = sorted(+ families.keys(),+ key=lambda family: self.families_infos.get(family, (999, family))[0],+ )++ for family in family_order:+ family_label = self.families_infos.get(family, (999, family))[1]+ rows = []+ for model_type in families[family]:+ model_name = self.compact_name(+ family_label, self.get_model_name(model_type)+ )+ parent_id = self.get_parent_model_type(model_type)+ rows.append((model_name, model_type, parent_id))++ rows.sort(key=lambda row: row[0])+ parents_list, children_dict = self.create_models_hierarchy(rows)+ family_node_id = f"family::{family}"+ family_models = set(families[family])+ family_usage_ids = self._collect_usage_ids_for_models(family_models)+ family_files = self._collect_files_for_usage_ids(family_usage_ids)+ self._register_node(+ family_node_id,+ family_label,+ "family",+ family_models,+ family_files,+ path_label=family_label,+ )++ base_nodes = []+ for base_label, base_id in parents_list:+ child_entries = children_dict.get(base_id, [])+ child_nodes = []+ base_models = set()+ base_usage_ids = set()+ base_path = f"{family_label} / {base_label}"+ for child_label, child_model in child_entries:+ base_models.add(child_model)+ model_usage_ids = self._model_usage_ids.get(child_model, set())+ base_usage_ids.update(model_usage_ids)+ self._model_base_label[child_model] = base_label+ self._model_family_label[child_model] = family_label+ model_node_id = f"model::{child_model}"+ model_files = self._collect_files_for_usage_ids(model_usage_ids)+ primary_paths = self._model_primary.get(child_model, [])+ model_path = f"{base_path} / {child_label}"+ self._register_node(+ model_node_id,+ child_label,+ "model",+ {child_model},+ model_files,+ primary_paths=primary_paths,+ path_label=model_path,+ )+ variant_children = []+ for variant in self._model_variants.get(child_model, []):+ variant_id = variant["id"]+ variant_label = variant["label"]+ variant_path = f"{model_path} / {variant_label}"+ self._register_node(+ variant_id,+ variant_label,+ "variant",+ {child_model},+ variant.get("files", set()),+ primary_paths=variant.get("primary_paths", []),+ path_label=variant_path,+ )+ variant_children.append(+ {"id": variant_id, "label": variant_label, "type": "variant"}+ )+ child_nodes.append(+ {+ "id": model_node_id,+ "label": child_label,+ "type": "model",+ "children": variant_children,+ }+ )++ base_node_id = f"base::{family}::{base_id}"+ base_files = self._collect_files_for_usage_ids(base_usage_ids)+ self._register_node(+ base_node_id,+ base_label,+ "base",+ base_models,+ base_files,+ path_label=base_path,+ )+ base_nodes.append(+ {+ "id": base_node_id,+ "label": base_label,+ "type": "base",+ "children": child_nodes,+ }+ )++ self._tree_data.append(+ {+ "id": family_node_id,+ "label": family_label,+ "type": "family",+ "children": base_nodes,+ }+ )++ def _collect_usage_ids_for_models(self, model_set):+ usage_ids = set()+ for model_type in model_set:+ usage_ids.update(self._model_usage_ids.get(model_type, set()))+ return usage_ids++ def _collect_files_for_usage_ids(self, usage_ids):+ files = set()+ for usage_id in usage_ids:+ files.update(self._usage_files.get(usage_id, set()))+ return files++ def _register_node(+ self,+ node_id,+ label,+ node_type,+ model_set,+ files_set,+ primary_paths=None,+ path_label=None,+ ):+ unique_files, shared_files = self._split_files_by_shared(files_set, model_set)+ unique_size = self._sum_sizes(unique_files)+ shared_size = self._sum_sizes(shared_files)+ self._node_map[node_id] = {+ "id": node_id,+ "label": label,+ "type": node_type,+ "models": set(model_set),+ "files": set(files_set),+ "unique_files": unique_files,+ "shared_files": shared_files,+ "unique_size": unique_size,+ "shared_size": shared_size,+ "total_size": unique_size + shared_size,+ "primary_paths": primary_paths or [],+ "path_label": path_label or label,+ }++ def _sum_sizes(self, files_set):+ total = 0+ for path in files_set:+ total += self._file_info.get(path, {}).get("size", 0)+ return total++ def _split_files_by_shared(self, files_set, model_set):+ unique_files = set()+ shared_files = set()+ for path in files_set:+ used_by = self._file_usage_models.get(path, set())+ if used_by.issubset(model_set):+ unique_files.add(path)+ else:+ shared_files.add(path)+ return unique_files, shared_files++ def _rebalance_other_shared_variants(self, model_types):+ for model_type in model_types:+ variants = self._model_variants.get(model_type, [])+ if not variants:+ continue+ other_variant = None+ shared_variant = None+ for variant in variants:+ label = str(variant.get("label", "")).lower()+ if label == "other":+ other_variant = variant+ elif label == "shared":+ shared_variant = variant++ if not other_variant and not shared_variant:+ continue++ combined = set()+ if other_variant:+ combined.update(other_variant.get("files", set()))+ if shared_variant:+ combined.update(shared_variant.get("files", set()))++ new_variants = []+ for variant in variants:+ if variant is other_variant or variant is shared_variant:+ continue+ new_variants.append(variant)+ if not combined:+ self._model_variants[model_type] = new_variants+ continue++ model_set = {model_type}+ shared_files = {+ path+ for path in combined+ if not self._file_usage_models.get(path, set()).issubset(model_set)+ }+ other_files = combined - shared_files++ if other_files:+ if other_variant is None:+ other_variant = {+ "id": self._make_variant_id(model_type, "other", "other"),+ "label": "Other",+ "type": "variant",+ "files": other_files,+ "primary_paths": [],+ }+ else:+ other_variant["files"] = other_files+ new_variants.append(other_variant)++ if shared_files:+ if shared_variant is None:+ shared_variant = {+ "id": self._make_variant_id(model_type, "shared", "shared"),+ "label": "Shared",+ "type": "variant",+ "files": shared_files,+ "primary_paths": [],+ }+ else:+ shared_variant["files"] = shared_files+ new_variants.append(shared_variant)++ self._model_variants[model_type] = new_variants++ def _shared_base_labels(self, path, exclude_key=None):+ pairs = set()+ for model_type in self._file_usage_models.get(path, set()):+ base_label = self._model_base_label.get(model_type)+ family_label = self._model_family_label.get(model_type)+ if base_label and family_label:+ pairs.add((family_label, base_label))+ if exclude_key:+ pairs.discard(exclude_key)+ return [+ f"{family} {base}"+ for family, base in sorted(pairs, key=lambda item: (item[0].lower(), item[1].lower()))+ ]++ def _get_node_base_label(self, node_id, node_type):+ model_type = None+ if node_type == "base":+ family_label = None+ if node_id.startswith("base::"):+ parts = node_id.split("::", 2)+ if len(parts) >= 2:+ family_key = parts[1]+ family_label = self.families_infos.get(+ family_key, (999, family_key)+ )[1]+ info = self._node_map.get(node_id, {})+ base_label = info.get("label")+ if family_label and base_label:+ return (family_label, base_label)+ return None+ if node_type == "variant":+ model_type = self._variant_to_model.get(node_id)+ elif node_type == "model":+ if node_id.startswith("model::"):+ model_type = node_id.split("model::", 1)[1]+ if model_type:+ family_label = self._model_family_label.get(model_type)+ base_label = self._model_base_label.get(model_type)+ if family_label and base_label:+ return (family_label, base_label)+ return None++ def _build_tree_html(self):+ css = """+ <style>+ .ckpt-wrap { display: flex; flex-direction: column; gap: 12px; }+ .ckpt-panel { border: 1px solid var(--border-color-primary); border-radius: 14px; background: linear-gradient(135deg, rgba(255,255,255,0.02), rgba(0,0,0,0.02)); box-shadow: var(--shadow-drop-sm, 0 2px 8px rgba(0,0,0,0.08)); }+ .ckpt-panel-inner { padding: 10px; }+ .ckpt-tree { display: flex; flex-direction: column; gap: 8px; }+ .ckpt-node { border: 1px solid var(--border-color-primary); border-radius: 10px; background: var(--background-fill-secondary); box-shadow: inset 0 0 0 1px rgba(255,255,255,0.02); }+ .ckpt-node summary { list-style: none; cursor: pointer; padding: 8px 10px; }+ .ckpt-node summary::-webkit-details-marker { display: none; }+ .ckpt-row { display: flex; align-items: center; gap: 10px; border-radius: 8px; padding: 6px 6px; }+ .ckpt-row.clickable { cursor: pointer; transition: background 0.15s ease; }+ .ckpt-row.clickable:hover { background: rgba(127,127,127,0.08); }+ .ckpt-label { flex: 1; font-weight: 600; color: inherit; }+ .ckpt-sizes { display: flex; flex-direction: column; align-items: stretch; min-width: 128px; width: 128px; font-size: 0.85em; font-variant-numeric: tabular-nums; gap: 4px; }+ .ckpt-size-unique { color: inherit; }+ .ckpt-size-shared { color: inherit; }+ .ckpt-badge { padding: 3px 8px; border-radius: 999px; font-weight: 600; font-size: 0.82em; font-variant-numeric: tabular-nums; min-width: 84px; width: 100%; display: inline-flex; align-items: center; justify-content: center; }+ .ckpt-badge-unique { background: rgba(64, 120, 255, 0.18); color: #2f5bd4; border: 1px solid rgba(64, 120, 255, 0.4); }+ .ckpt-badge-shared { background: rgba(240, 200, 40, 0.25); color: #a66a00; border: 1px solid rgba(240, 200, 40, 0.5); }+ .ckpt-actions { display: flex; gap: 18px; }+ .ckpt-action-btn { padding: 3px 12px; height: 30px; border: 1px solid var(--border-color-primary); border-radius: 6px; cursor: pointer; font-size: 0.85em; display: inline-flex; align-items: center; justify-content: center; font-weight: 600; background: transparent; color: inherit; }+ .ckpt-action-btn:hover { box-shadow: var(--shadow-drop, 0 2px 6px rgba(0,0,0,0.12)); }+ .ckpt-view-btn { background: rgba(60, 120, 255, 0.9) !important; color: #ffffff !important; border-color: rgba(60, 120, 255, 0.95) !important; }+ .ckpt-view-btn:hover { background: rgba(60, 120, 255, 1) !important; }+ .ckpt-delete { background: rgba(220, 60, 60, 0.95) !important; color: #ffffff !important; border-color: rgba(220, 60, 60, 0.95) !important; }+ .ckpt-delete:hover { background: rgba(220, 60, 60, 1) !important; }+ .ckpt-children { padding: 6px 8px 10px 18px; display: flex; flex-direction: column; gap: 6px; }+ .ckpt-leaf { border: 1px solid var(--border-color-primary); border-radius: 8px; background: var(--background-fill-primary); padding: 6px 8px; }+ .ckpt-right-column { align-self: flex-start; position: relative; overflow: visible !important; }+ .ckpt-view-sticky { position: sticky; top: 16px; align-self: flex-start; }+ .ckpt-view { border: 1px solid var(--border-color-primary); border-radius: 12px; background: linear-gradient(135deg, rgba(255,255,255,0.02), rgba(0,0,0,0.02)); padding: 12px; max-height: none; overflow: visible; }+ .ckpt-view h4 { margin: 0 0 6px 0; }+ .ckpt-view-summary { font-size: 0.85em; color: inherit; margin-bottom: 8px; display: flex; flex-wrap: wrap; gap: 12px; }+ .ckpt-loading-message { font-size: 1.05em; font-weight: 600; color: inherit; padding: 16px 8px; }+ .ckpt-muted { opacity: 0.75; }+ .ckpt-stats { display: flex; flex-direction: column; gap: 6px; }+ .ckpt-stat-main { font-weight: 600; font-size: 0.95em; }+ .ckpt-drive-list { display: flex; flex-wrap: wrap; gap: 8px; }+ .ckpt-drive { padding: 4px 8px; border-radius: 999px; background: var(--background-fill-primary); border: 1px solid var(--border-color-primary); font-size: 0.82em; }+ .ckpt-file-tree { display: flex; flex-direction: column; gap: 6px; max-height: none; overflow: visible; }+ .ckpt-folder { border: 1px solid var(--border-color-primary); border-radius: 8px; background: var(--background-fill-primary); }+ .ckpt-folder.shared { border-color: rgba(240,200,40,0.45); }+ .ckpt-folder.shared > summary { background: rgba(240,200,40,0.12); }+ .ckpt-folder.unique { border-color: rgba(64, 120, 255, 0.35); }+ .ckpt-folder.unique > summary { background: rgba(64, 120, 255, 0.12); }+ .ckpt-folder summary { list-style: none; cursor: pointer; padding: 6px 8px; display: flex; align-items: center; gap: 8px; position: relative; }+ .ckpt-folder summary::-webkit-details-marker { display: none; }+ .ckpt-folder-name { flex: 1; font-weight: 600; }+ .ckpt-folder-size { font-size: 0.8em; color: inherit; opacity: 0.75; font-variant-numeric: tabular-nums; }+ .ckpt-folder-children { padding: 6px 8px 8px 18px; display: flex; flex-direction: column; gap: 4px; }+ .ckpt-file-row { display: flex; gap: 8px; align-items: center; font-size: 0.85em; padding: 2px 0; }+ .ckpt-file-row.shared { position: relative; }+ .ckpt-file-row.shared { color: #a66a00; background: rgba(240, 200, 40, 0.12); border-radius: 6px; padding: 2px 6px; }+ .ckpt-file-row.unique { background: rgba(64, 120, 255, 0.12); border-radius: 6px; padding: 2px 6px; }+ .ckpt-file-row.missing { opacity: 0.6; }+ .ckpt-file-name { flex: 1; word-break: break-all; }+ .ckpt-file-size { min-width: 70px; text-align: right; color: inherit; opacity: 0.75; font-variant-numeric: tabular-nums; }+ .ckpt-shared-tag { font-size: 0.72em; text-transform: uppercase; letter-spacing: 0.04em; border: 1px solid rgba(240,200,40,0.5); color: #a66a00; padding: 2px 6px; border-radius: 999px; background: rgba(240,200,40,0.12); }+ .ckpt-folder-tag { margin-left: 6px; }+ .ckpt-shared-tooltip { opacity: 0; visibility: hidden; pointer-events: none; position: absolute; top: 100%; left: 0; margin-top: 6px; padding: 6px 8px; background: var(--background-fill-primary); border: 1px solid var(--border-color-primary); border-radius: 8px; box-shadow: var(--shadow-drop, 0 2px 6px rgba(0,0,0,0.12)); font-size: 0.8em; z-index: 10; min-width: 160px; transform: translateY(4px); transition: opacity 0.15s ease, transform 0.15s ease; transition-delay: 0s; }+ .ckpt-shared-tooltip-title { font-weight: 600; margin-bottom: 4px; }+ .ckpt-file-row.shared:hover .ckpt-shared-tooltip { opacity: 1; visibility: visible; transform: translateY(0); transition-delay: 2s; }+ .ckpt-folder.shared summary:hover .ckpt-shared-tooltip { opacity: 1; visibility: visible; transform: translateY(0); transition-delay: 2s; }+ .ckpt-path { font-size: 0.82em; color: inherit; opacity: 0.8; margin-bottom: 6px; word-break: break-all; }+ .ckpt-primary { font-size: 0.82em; color: inherit; opacity: 0.8; margin-bottom: 8px; word-break: break-all; }+ .ckpt-errors { padding: 8px 10px; border: 1px solid rgba(220, 80, 80, 0.4); background: var(--background-fill-primary); border-radius: 8px; font-size: 0.85em; }+ .ckpt-modal-backdrop { position: fixed; inset: 0; background: rgba(0,0,0,0.45); display: none; align-items: center; justify-content: center; z-index: 9999; }+ .ckpt-modal { width: min(420px, 90vw); background: var(--background-fill-primary); border: 1px solid var(--border-color-primary); border-radius: 14px; padding: 18px; box-shadow: 0 12px 28px rgba(0,0,0,0.25); display: flex; flex-direction: column; gap: 12px; }+ .ckpt-modal-title { font-weight: 700; font-size: 1.05em; }+ .ckpt-modal-body { font-size: 0.95em; color: inherit; opacity: 0.8; }+ .ckpt-modal-actions { display: flex; gap: 12px; justify-content: flex-end; }+ .ckpt-modal-btn { padding: 8px 14px; border-radius: 8px; border: 1px solid var(--border-color-primary); background: var(--button-secondary-background-fill, #f0f0f0); cursor: pointer; font-weight: 600; }+ .ckpt-modal-btn.danger { background: rgba(220,80,80,0.15); border-color: rgba(220,80,80,0.5); color: #c62828; }+ </style>+ """++ tree_parts = [+ css,+ "<div id='ckpt_tree_root' data-status='ready' class='ckpt-wrap'>",+ ]+ if self._errors:+ errors_html = "<br>".join(html.escape(err) for err in self._errors[:10])+ tree_parts.append(f"<div class='ckpt-errors'>{errors_html}</div>")++ tree_parts.append("<div class='ckpt-panel'><div class='ckpt-panel-inner'>")+ tree_parts.append(self._build_stats_html())+ tree_parts.append("<div class='ckpt-tree'>")+ for family in self._tree_data:+ tree_parts.append(self._render_node(family, is_family=True))+ tree_parts.append("</div></div></div></div>")+ return "".join(tree_parts)++ def _build_stats_html(self):+ total_label = self._format_gb(self._stats_total)+ drive_html = ""+ if len(self._stats_by_drive) > 1:+ drive_items = []+ for drive, size in self._stats_by_drive:+ drive_items.append(+ f"<span class='ckpt-drive'>{html.escape(drive)}: {self._format_gb(size)}</span>"+ )+ drive_html = f"<div class='ckpt-drive-list'>{''.join(drive_items)}</div>"+ return (+ "<div class='ckpt-stats'>"+ f"<div class='ckpt-stat-main'>Total Used: {total_label}</div>"+ f"{drive_html}</div>"+ )++ def _render_node(self, node, is_family=False):+ node_id = node["id"]+ info = self._node_map.get(node_id, {})+ label = info.get("label", node.get("label", node_id))+ unique_size_value = info.get("unique_size", 0)+ shared_size_value = info.get("shared_size", 0)+ unique = self._format_gb(unique_size_value)+ shared = self._format_gb(shared_size_value)+ unique_label = self._format_size(unique_size_value)+ shared_label = self._format_size(shared_size_value)+ total_label = self._format_size(unique_size_value + shared_size_value)+ node_type = info.get("type", node.get("type", ""))++ children = node.get("children", [])+ click_view = node_type in ("model", "variant")+ row_html = self._render_row(+ label,+ node_id,+ unique,+ shared,+ unique_label,+ shared_label,+ total_label,+ node_type,+ click_view=click_view,+ )+ if children:+ child_html = "".join(self._render_node(child) for child in children)+ return (+ f"<details class='ckpt-node'><summary>{row_html}</summary>"+ f"<div class='ckpt-children'>{child_html}</div></details>"+ )+ return f"<div class='ckpt-leaf'>{row_html}</div>"++ def _render_row(+ self,+ label,+ node_id,+ unique,+ shared,+ unique_label,+ shared_label,+ total_label,+ node_type,+ click_view=False,+ ):+ label_display = html.escape(label)+ label_attr = html.escape(label, quote=True)+ node_id_attr = html.escape(node_id, quote=True)+ type_attr = html.escape(node_type, quote=True)+ row_class = "ckpt-row clickable" if click_view else "ckpt-row"+ row_onclick = (+ "onclick='handlemodelRowClick(event, this);'" if click_view else ""+ )+ unique_badge = f"<span class='ckpt-badge ckpt-badge-unique'>{unique}</span>"+ shared_badge = f"<span class='ckpt-badge ckpt-badge-shared'>{shared}</span>"+ return (+ f"<div class='{row_class}' data-node-id=\"{node_id_attr}\" data-node-label=\"{label_attr}\" data-node-type=\"{type_attr}\" {row_onclick}>"+ f"<div class='ckpt-label'>{label_display}</div>"+ "<div class='ckpt-sizes'>"+ f"<div class='ckpt-size-unique' title='Unique size'>{unique_badge}</div>"+ f"<div class='ckpt-size-shared' title='Shared size'>{shared_badge}</div>"+ "</div>"+ "<div class='ckpt-actions'>"+ f"<button class='ckpt-action-btn ckpt-view-btn' data-node-id=\"{node_id_attr}\" data-node-label=\"{label_attr}\" data-node-type=\"{type_attr}\" data-unique-size=\"{unique_label}\" data-shared-size=\"{shared_label}\" data-total-size=\"{total_label}\" onclick='event.stopPropagation(); handlemodelAction(this, \"view\");'>View</button>"+ f"<button class='ckpt-action-btn ckpt-delete' data-node-id=\"{node_id_attr}\" data-node-label=\"{label_attr}\" data-node-type=\"{type_attr}\" data-unique-size=\"{unique_label}\" data-shared-size=\"{shared_label}\" data-total-size=\"{total_label}\" onclick='event.stopPropagation(); handlemodelAction(this, \"delete\");'>Delete</button>"+ "</div>"+ "</div>"+ )++ def _build_empty_view_html(self):+ return (+ "<div class='ckpt-view-sticky'><div class='ckpt-view'>"+ "<h4>Files</h4>"+ "<div class='ckpt-view-summary'>Select a branch to view its files.</div>"+ "</div></div>"+ )++ def _build_loading_html(self):+ return (+ "<div id='ckpt_tree_root' data-status='loading' class='ckpt-wrap'>"+ "<div class='ckpt-panel'><div class='ckpt-panel-inner'>"+ "<div class='ckpt-loading-message'>Please wait while the models hierarchy is being built...</div>"+ "</div></div></div>"+ )++ def _build_view_html(self, node_id):+ node = self._node_map.get(node_id)+ if node is None:+ return self._build_empty_view_html()++ files = sorted(node["files"])+ node_type = node.get("type", "")+ current_base = self._get_node_base_label(node_id, node_type)+ shared_set = {+ path+ for path in files+ if not self._file_usage_models.get(path, set()).issubset(node["models"])+ }++ current_base_label = None+ if current_base:+ current_base_label = f"{current_base[0]} {current_base[1]}"+ shared_info = {}+ for path in shared_set:+ shared_labels = self._shared_base_labels(path, exclude_key=current_base)+ if not shared_labels and current_base_label:+ shared_labels = [f"Shared only within {current_base_label}"]+ shared_info[path] = shared_labels+ file_tree = self._build_file_tree(files, shared_set, shared_info)+ file_tree_html = self._render_file_tree(file_tree)++ unique = self._format_gb(node["unique_size"])+ shared = self._format_gb(node["shared_size"])+ label_text = node["label"]+ path_label = node.get("path_label") or label_text+ header = html.escape(path_label)+ unique_badge = f"<span class='ckpt-badge ckpt-badge-unique'>{unique}</span>"+ shared_badge = f"<span class='ckpt-badge ckpt-badge-shared'>{shared}</span>"+ shared_count = len(shared_set)+ unique_count = max(0, len(files) - shared_count)+ summary = (+ f"<span class='ckpt-muted'>{unique_count} files</span> | unique {unique_badge} "+ f"<span class='ckpt-muted'>{shared_count} files</span> | shared {shared_badge}"+ )+ primary_paths = node.get("primary_paths", [])+ primary_html = ""+ if primary_paths:+ label = "model path" if len(primary_paths) == 1 else "model paths"+ lines = "<br>".join(html.escape(path) for path in primary_paths)+ primary_html = f"<div class='ckpt-primary'><strong>{label}:</strong><br>{lines}</div>"+ return (+ "<div class='ckpt-view-sticky'><div class='ckpt-view'>"+ f"<h4><strong>{header}</strong></h4>"+ f"{primary_html}"+ f"<div class='ckpt-view-summary'>{summary}</div>"+ f"{file_tree_html}</div></div>"+ )++ def _build_file_tree(self, files, shared_set, shared_info=None):+ if shared_info is None:+ shared_info = {}+ root = {+ "children": {},+ "files": [],+ "size": 0,+ "all_shared": False,+ "all_unique": False,+ "has_files": False,+ "shared_with": set(),+ "shared_count": 0,+ "is_root": True,+ }+ for path in files:+ info = self._file_info.get(path, {})+ display = self._display_path(path)+ parts = self._split_display_path(display)+ name = parts[-1] if parts else display+ shared_with = shared_info.get(path, [])+ entry = {+ "path": path,+ "display": display,+ "name": name,+ "size": info.get("size", 0),+ "exists": info.get("exists", False),+ "shared": path in shared_set,+ "shared_with": shared_with,+ }++ node = root+ for part in parts[:-1]:+ node = node["children"].setdefault(+ part,+ {+ "children": {},+ "files": [],+ "size": 0,+ "all_shared": False,+ "all_unique": False,+ "has_files": False,+ "shared_with": set(),+ "shared_count": 0,+ "is_root": False,+ },+ )+ node["files"].append(entry)++ self._compute_folder_sizes(root)+ return root++ def _compute_folder_sizes(self, node):+ total = sum(entry["size"] for entry in node["files"])+ has_files = len(node["files"]) > 0+ all_shared = all(entry["shared"] for entry in node["files"]) if node["files"] else True+ all_unique = all(not entry["shared"] for entry in node["files"]) if node["files"] else True+ shared_with = set()+ shared_count = 0+ for entry in node["files"]:+ if entry.get("shared"):+ shared_with.update(entry.get("shared_with", []))+ for child in node["children"].values():+ (+ child_total,+ child_has_files,+ child_all_shared,+ child_shared_with,+ child_shared_count,+ child_all_unique,+ ) = self._compute_folder_sizes(child)+ total += child_total+ has_files = has_files or child_has_files+ all_shared = all_shared and child_all_shared+ all_unique = all_unique and child_all_unique+ shared_with.update(child_shared_with)+ shared_count += child_shared_count+ node["size"] = total+ node["has_files"] = has_files+ node["all_shared"] = has_files and all_shared+ node["all_unique"] = has_files and all_unique+ node["shared_with"] = shared_with+ if node["all_shared"] and not node.get("is_root"):+ shared_count += 1+ node["shared_count"] = shared_count+ return total, has_files, node["all_shared"], shared_with, shared_count, node["all_unique"]++ def _render_file_tree(self, node):+ open_shared_path = node.get("shared_count", 0) == 1+ parts = []+ for name in sorted(node["children"].keys(), key=lambda n: n.lower()):+ parts.append(+ self._render_folder(+ name,+ node["children"][name],+ level=0,+ open_shared_path=open_shared_path,+ )+ )++ for entry in sorted(node["files"], key=lambda e: e["name"].lower()):+ parts.append(self._render_file_entry(entry))++ return "<div class='ckpt-file-tree'>" + "".join(parts) + "</div>"++ def _render_folder(self, name, node, level, open_shared_path=False):+ name, node = self._collapse_single_child_folder(name, node)+ folder_name = html.escape(name)+ size_label = self._format_size(node.get("size", 0))+ shared_tag = ""+ shared_tooltip = ""+ folder_class = "ckpt-folder"+ if node.get("all_shared"):+ shared_tag = "<span class='ckpt-shared-tag ckpt-folder-tag'>Shared</span>"+ folder_class += " shared"+ shared_with = sorted(node.get("shared_with", []), key=lambda value: value.lower())+ if shared_with:+ lines = "".join(+ f"<div>{html.escape(label)}</div>" for label in shared_with+ )+ shared_tooltip = (+ "<div class='ckpt-shared-tooltip'>"+ "<div class='ckpt-shared-tooltip-title'>Shared with</div>"+ f"{lines}</div>"+ )+ elif node.get("all_unique"):+ folder_class += " unique"+ open_attr = ""+ if level < 1 or (open_shared_path and node.get("shared_count", 0) == 1):+ open_attr = " open"+ children_html = []+ for child_name in sorted(node["children"].keys(), key=lambda n: n.lower()):+ children_html.append(+ self._render_folder(+ child_name,+ node["children"][child_name],+ level + 1,+ open_shared_path=open_shared_path,+ )+ )+ for entry in sorted(node["files"], key=lambda e: e["name"].lower()):+ children_html.append(self._render_file_entry(entry))+ return (+ f"<details class='{folder_class}'{open_attr}>"+ "<summary>"+ f"<span class='ckpt-folder-name'>{folder_name}</span>"+ f"{shared_tag}"+ f"<span class='ckpt-folder-size'>{size_label}</span>"+ f"{shared_tooltip}"+ "</summary>"+ "<div class='ckpt-folder-children'>"+ + "".join(children_html)+ + "</div></details>"+ )++ def _collapse_single_child_folder(self, name, node):+ parts = [name]+ current = node+ while True:+ if current.get("files"):+ break+ children = current.get("children", {})+ if len(children) != 1:+ break+ child_name, child_node = next(iter(children.items()))+ parts.append(child_name)+ current = child_node+ return os.sep.join(parts), current++ def _render_file_entry(self, entry):+ classes = ["ckpt-file-row"]+ if entry.get("shared"):+ classes.append("shared")+ else:+ classes.append("unique")+ if not entry.get("exists"):+ classes.append("missing")+ class_attr = " ".join(classes)+ name = html.escape(entry.get("name", ""))+ size_label = self._format_size(entry.get("size", 0))+ display = html.escape(entry.get("display", ""))+ shared_tag = "<span class='ckpt-shared-tag'>Shared</span>" if entry.get("shared") else ""+ shared_tooltip = ""+ if entry.get("shared"):+ shared_with = entry.get("shared_with", [])+ if shared_with:+ lines = "".join(+ f"<div>{html.escape(label)}</div>" for label in shared_with+ )+ shared_tooltip = (+ "<div class='ckpt-shared-tooltip'>"+ "<div class='ckpt-shared-tooltip-title'>Shared with</div>"+ f"{lines}</div>"+ )+ return (+ f"<div class='{class_attr}' title='{display}'>"+ f"<span class='ckpt-file-name'>{name}</span>"+ f"{shared_tag}"+ f"<span class='ckpt-file-size'>{size_label}</span>"+ f"{shared_tooltip}"+ "</div>"+ )++ def _split_display_path(self, display_path):+ drive, rest = os.path.splitdrive(display_path)+ if drive:+ drive = drive.rstrip("\\/")+ rest = rest.replace("\\", "/")+ parts = [part for part in rest.split("/") if part]+ if drive:+ return [drive] + parts+ if display_path.startswith("\\\\"):+ return ["UNC"] + parts+ return parts++ def _add_file(self, files_set, value, force_folder=None):+ path = self._resolve_path(value, force_folder=force_folder)+ if path and os.path.isfile(path):+ files_set.add(path)++ def _download_root_name(self):+ root = fl.get_download_location()+ if not root or os.path.isabs(root):+ return ""+ norm = os.path.normpath(root)+ if not norm or norm == ".":+ return ""+ return norm.split(os.sep)[0]++ def _resolve_repo_relative_path(self, rel_path):+ if not rel_path:+ return None+ rel_path = str(rel_path)+ if rel_path.startswith("http"):+ return None+ root_name = self._download_root_name()+ if not root_name:+ return None+ rel_norm = os.path.normpath(rel_path)+ parts = rel_norm.split(os.sep)+ if parts and parts[0].lower() == root_name.lower():+ return self._normalize_path(os.path.join(self._repo_root, rel_norm))+ return None++ def _resolve_path(self, value, force_folder=None):+ if not value:+ return None+ if not isinstance(value, str):+ value = str(value)+ if os.path.isabs(value):+ abs_path = self._normalize_path(value)+ if os.path.isfile(abs_path):+ return abs_path+ basename = os.path.basename(abs_path)+ return abs_path+ repo_rel = self._resolve_repo_relative_path(value)+ if repo_rel:+ return repo_rel++ try:+ local_path = self.get_local_model_filename(value, extra_paths=force_folder)+ except Exception:+ local_path = None+ if local_path:+ return self._normalize_path(local_path)++ filename = os.path.basename(value) if value.startswith("http") else value+ if force_folder:+ expected = fl.get_download_location(filename, force_path=force_folder)+ else:+ expected = fl.get_download_location(filename)+ return self._normalize_path(expected)++ def _resolve_download_relpath(self, rel_path):+ if rel_path and os.path.isabs(rel_path):+ return self._normalize_path(rel_path)+ repo_rel = self._resolve_repo_relative_path(rel_path)+ if repo_rel:+ return repo_rel+ local = fl.locate_file(rel_path, error_if_none=False)+ if local:+ return self._normalize_path(local)+ return self._normalize_path(fl.get_download_location(rel_path))++ def _resolve_folder_path(self, source_folder, target_folder):+ parts = []+ if target_folder:+ parts.append(target_folder)+ if source_folder:+ parts.append(source_folder)+ rel_path = os.path.join(*parts) if parts else ""+ if rel_path and os.path.isabs(rel_path):+ return self._normalize_path(rel_path)+ repo_rel = self._resolve_repo_relative_path(rel_path)+ if repo_rel:+ return repo_rel+ if not rel_path:+ return self._normalize_path(fl.get_download_location())+ folder = fl.locate_folder(rel_path, error_if_none=False)+ if folder:+ return self._normalize_path(folder)+ return self._normalize_path(fl.get_download_location(rel_path))++ def _list_folder_files(self, folder_path):+ files = set()+ if not folder_path or not os.path.isdir(folder_path):+ return files+ for root, _, filenames in os.walk(folder_path):+ for name in filenames:+ files.add(self._normalize_path(os.path.join(root, name)))+ return files++ def _combine_download_path(self, target_folder, source_folder, filename):+ parts = []+ if target_folder:+ parts.append(target_folder)+ if source_folder:+ parts.append(source_folder)+ parts.append(filename)+ return os.path.join(*parts)++ def _compute_list(self, filename):+ if not filename:+ return []+ return [os.path.basename(str(filename))]++ def _ensure_list(self, value):+ if value is None:+ return []+ if isinstance(value, list):+ return value+ return [value]++ def _safe_get_lora_dir(self, model_type):+ try:+ return self.get_lora_dir(model_type)+ except Exception:+ return None++ def _normalize_path(self, path):+ return os.path.normcase(os.path.abspath(path))++ def _format_gb(self, size_bytes):+ size_gb = size_bytes / (1024 ** 3)+ return f"{size_gb:.2f} GB"++ def _format_size(self, size_bytes):+ if size_bytes >= 1024 ** 3:+ return f"{size_bytes / (1024 ** 3):.2f} GB"+ if size_bytes >= 1024 ** 2:+ return f"{size_bytes / (1024 ** 2):.1f} MB"+ if size_bytes >= 1024:+ return f"{size_bytes / 1024:.1f} KB"+ return f"{size_bytes} B"++ def _display_path(self, path):+ try:+ rel = os.path.relpath(path, self._repo_root)+ if not rel.startswith(".."):+ return rel+ except Exception:+ pass+ return path++ def _get_model_roots(self):+ roots = []+ for root in getattr(fl, "_models_paths", []) or []:+ if not root:+ continue+ if os.path.isabs(root):+ abs_root = root+ else:+ abs_root = os.path.join(self._repo_root, root)+ abs_root = self._normalize_path(abs_root)+ if abs_root not in roots:+ roots.append(abs_root)+ return roots++ def _build_basename_index(self, basenames, min_size=1):+ basenames = {name.lower() for name in basenames if name}+ if not basenames:+ return {}+ found = {}+ remaining = set(basenames)+ for root in self._get_model_roots():+ if not remaining:+ break+ if not os.path.isdir(root):+ continue+ for name in list(remaining):+ candidate = os.path.join(root, name)+ if os.path.isfile(candidate):+ try:+ if os.path.getsize(candidate) < min_size:+ continue+ except OSError:+ continue+ found[name] = self._normalize_path(candidate)+ remaining.discard(name)+ if not remaining:+ break+ if os.path.normcase(root) == os.path.normcase(self._repo_root):+ continue+ for dirpath, _, filenames in os.walk(root):+ for filename in filenames:+ key = filename.lower()+ if key in remaining:+ full_path = os.path.join(dirpath, filename)+ try:+ if os.path.getsize(full_path) < min_size:+ continue+ except OSError:+ continue+ found[key] = self._normalize_path(full_path)+ remaining.discard(key)+ if not remaining:+ break+ if not remaining:+ break+ return found++ def _find_in_model_roots(self, basename, min_size=1):+ if not basename:+ return None+ key = basename.lower()+ if key in self._basename_index:+ return self._basename_index.get(key)+ found = self._build_basename_index({basename}, min_size=min_size)+ if found:+ self._basename_index.update(found)+ return self._basename_index.get(key)+ self._basename_index[key] = None+ return None++ def _repair_missing_paths(self):+ missing = []+ for path in self._file_usage_models.keys():+ try:+ size = os.path.getsize(path) if os.path.isfile(path) else -1+ except OSError:+ size = -1+ if size <= 0:+ missing.append(path)+ if not missing:+ return+ basenames = {os.path.basename(path) for path in missing}+ found = self._build_basename_index(basenames, min_size=1)+ if not found:+ return+ for old_path in list(missing):+ key = os.path.basename(old_path).lower()+ new_path = found.get(key)+ if not new_path or new_path == old_path:+ continue+ self._swap_path(old_path, new_path)++ def _swap_path(self, old_path, new_path):+ usage_ids = self._file_usage.pop(old_path, set())+ if usage_ids:+ self._file_usage[new_path].update(usage_ids)+ for usage_id in usage_ids:+ files = self._usage_files.get(usage_id)+ if files is not None:+ files.discard(old_path)+ files.add(new_path)+ model_type = self._variant_to_model.get(usage_id)+ if model_type:+ for variant in self._model_variants.get(model_type, []):+ if variant.get("id") != usage_id:+ continue+ files_set = variant.get("files")+ if isinstance(files_set, set):+ files_set.discard(old_path)+ files_set.add(new_path)+ primary_paths = variant.get("primary_paths", [])+ variant["primary_paths"] = [+ new_path if path == old_path else path for path in primary_paths+ ]+ break++ model_types = self._file_usage_models.pop(old_path, set())+ if model_types:+ self._file_usage_models[new_path].update(model_types)+ for model_type in model_types:+ files = self._model_files.get(model_type)+ if files is not None:+ files.discard(old_path)+ files.add(new_path)+ primary_paths = self._model_primary.get(model_type)+ if primary_paths:+ self._model_primary[model_type] = [+ new_path if path == old_path else path for path in primary_paths+ ]diff --git a/requirements.txt b/requirements.txtindex 4918a5d..2d83938 100644--- a/requirements.txt+++ b/requirements.txt@@ -57,9 +57,10 @@ pydantic==2.10.6# Math & modelingtorchdiffeq>=0.2.5tensordict>=0.6.1-mmgp==3.6.15+mmgp==3.6.16peft==0.15.0matplotlib+gguf==0.17.1# Utilitiesftfydiff --git a/shared/qtypes/gguf.py b/shared/qtypes/gguf.pynew file mode 100644index 0000000..b374cac--- /dev/null+++ b/shared/qtypes/gguf.py@@ -0,0 +1,976 @@+import ast+import os+import re++import torch+from torch.utils import _pytree as pytree++from optimum.quanto import QModuleMixin+from optimum.quanto.tensor.qtensor import QTensor+from optimum.quanto.tensor.qtype import qtype as _quanto_qtype, qtypes as _quanto_qtypes+++HANDLER_NAME = "gguf"++try:+ import gguf+except Exception:+ gguf = None+++_GGUF_QTYPE_NAME = "gguf"+if _GGUF_QTYPE_NAME not in _quanto_qtypes:+ _quanto_qtypes[_GGUF_QTYPE_NAME] = _quanto_qtype(+ _GGUF_QTYPE_NAME,+ is_floating_point=False,+ bits=6,+ dtype=torch.uint8,+ qmin=-32.0,+ qmax=31.0,+ )+_GGUF_QTYPE = _quanto_qtypes[_GGUF_QTYPE_NAME]++_GGUF_DEFAULT_DTYPE = None+_GGUF_LABEL_CACHE = {}+++def _normalize_gguf_path(file_path):+ try:+ return os.path.normcase(os.path.abspath(file_path))+ except Exception:+ return str(file_path).lower()+++def normalize(file_path):+ return _normalize_gguf_path(file_path)+++def _set_default_dtype_from_loader(dtype):+ global _GGUF_DEFAULT_DTYPE+ if dtype is None:+ return+ _GGUF_DEFAULT_DTYPE = dtype+++def _resolve_default_dtype(dtype, fallback=None):+ if dtype is None:+ return _GGUF_DEFAULT_DTYPE or fallback+ if _GGUF_DEFAULT_DTYPE is not None and fallback is not None and dtype == fallback:+ return _GGUF_DEFAULT_DTYPE+ return dtype+def read_gguf_metadata(file_path):+ if gguf is None:+ raise RuntimeError("GGUF support requires the 'gguf' package.")+ reader = gguf.GGUFReader(file_path)+ metadata = {}+ field = reader.get_field("config")+ if field is not None:+ try:+ metadata["config"] = field.contents() if callable(getattr(field, "contents", None)) else field.contents+ except Exception:+ pass+ return metadata+++def _filter_state_dict_basic(state_dict, base_model_prefix, keep_prefix=False):+ new_state_dict = {}+ start = -1+ if keep_prefix:+ for k, v in state_dict.items():+ if k.startswith(base_model_prefix):+ new_state_dict[k] = v+ else:+ for k, v in state_dict.items():+ if k.startswith(base_model_prefix):+ new_start = len(base_model_prefix)+ else:+ pos = k.find("." + base_model_prefix)+ if pos < 0:+ continue+ new_start = pos + len(base_model_prefix) + 1+ if start != -1 and start != new_start:+ new_state_dict = state_dict+ break+ start = new_start+ new_state_dict[k[start:]] = v+ return new_state_dict+++def _gguf_get_orig_shape(reader, tensor_name):+ if gguf is None:+ raise RuntimeError("GGUF support requires the 'gguf' package.")+ field_key = f"comfy.gguf.orig_shape.{tensor_name}"+ field = reader.get_field(field_key)+ if field is None:+ return None+ if len(field.types) != 2 or field.types[0] != gguf.GGUFValueType.ARRAY or field.types[1] != gguf.GGUFValueType.INT32:+ raise TypeError(f"Bad GGUF shape metadata for {field_key}: {field.types}")+ return torch.Size(tuple(int(field.parts[part_idx][0]) for part_idx in field.data))+++def _gguf_resolve_prefix(tensor_names, prefixes):+ for prefix in prefixes:+ if any(name.startswith(prefix) for name in tensor_names):+ return prefix+ return None+++def load_gguf_state_dict(+ file_path,+ filters=None,+ keep_prefixes=False,+ writable_tensors=True,+ verboseLevel=1,+ default_dtype=None,+ pin_to_memory=False,+):+ if gguf is None:+ raise RuntimeError("GGUF support requires the 'gguf' package.")+ if pin_to_memory:+ raise Exception("Pinning to memory while loading GGUF files is not supported")++ import warnings++ def _cast_plain_tensor(torch_tensor, tensor_type):+ if tensor_type == gguf.GGMLQuantizationType.F16:+ if torch_tensor.dtype in (torch.uint8, torch.uint16):+ torch_tensor = torch_tensor.view(torch.float16)+ elif torch_tensor.dtype != torch.float16:+ torch_tensor = torch_tensor.to(torch.float16)+ elif tensor_type == gguf.GGMLQuantizationType.BF16:+ if torch_tensor.dtype in (torch.uint8, torch.uint16):+ torch_tensor = torch_tensor.view(torch.bfloat16)+ elif torch_tensor.dtype != torch.bfloat16:+ torch_tensor = torch_tensor.to(torch.bfloat16)+ elif tensor_type == gguf.GGMLQuantizationType.F32:+ if torch_tensor.dtype in (torch.uint8, torch.uint16, torch.uint32):+ torch_tensor = torch_tensor.view(torch.float32)+ elif torch_tensor.dtype != torch.float32:+ torch_tensor = torch_tensor.to(torch.float32)+ return torch_tensor++ def _tensor_type_from_dtype(dtype):+ if dtype == torch.float16:+ return gguf.GGMLQuantizationType.F16+ if dtype == torch.bfloat16:+ return gguf.GGMLQuantizationType.BF16+ if dtype == torch.float32:+ return gguf.GGMLQuantizationType.F32+ return None++ reader = gguf.GGUFReader(file_path)+ if verboseLevel >= 2:+ try:+ from mmgp import safetensors2+ safetensors2.verboseLevel = verboseLevel+ tracker = safetensors2.MmapTracker(file_path)+ tracker.register(reader.data, 0, 0, int(reader.data.nbytes))+ except Exception:+ tracker = None+ tensor_names = [tensor.name for tensor in reader.tensors]+ prefix = _gguf_resolve_prefix(tensor_names, ("model.diffusion_model.", "diffusion_model."))++ state_dict = {}+ qtype_counts = {}+ for tensor in reader.tensors:+ name = tensor.name+ if prefix and name.startswith(prefix):+ name = name[len(prefix):]++ with warnings.catch_warnings():+ warnings.filterwarnings("ignore", message="The given NumPy array is not writable")+ torch_tensor = torch.from_numpy(tensor.data)++ shape = _gguf_get_orig_shape(reader, tensor.name)+ if shape is None:+ shape = torch.Size(tuple(int(v) for v in reversed(tensor.shape)))+ if tensor.tensor_type in (+ gguf.GGMLQuantizationType.F32,+ gguf.GGMLQuantizationType.F16,+ gguf.GGMLQuantizationType.BF16,+ ):+ torch_tensor = _cast_plain_tensor(torch_tensor, tensor.tensor_type)+ torch_tensor = torch_tensor.view(*shape)+ wrapped = GGUFSourceTensor.wrap(torch_tensor, tensor_type=tensor.tensor_type, tensor_shape=shape)+ if name.endswith(".bias"):+ wrapped._gguf_bias_orig_dtype = wrapped.dtype+ wrapped._gguf_bias_orig_tensor_type = tensor.tensor_type+ state_dict[name] = wrapped+ type_name = getattr(tensor.tensor_type, "name", str(tensor.tensor_type))+ qtype_counts[type_name] = qtype_counts.get(type_name, 0) + 1++ if verboseLevel >= 2 and qtype_counts:+ print("GGUF qtypes: " + ", ".join(f"{k} ({v})" for k, v in qtype_counts.items()))++ if filters is not None:+ if not isinstance(filters, list):+ filters = [filters]+ new_sd = {}+ for one_filter in filters:+ new_sd.update(_filter_state_dict_basic(state_dict, one_filter, keep_prefixes))+ state_dict = new_sd++ if state_dict:+ for name, bias in list(state_dict.items()):+ if not name.endswith(".bias") or not torch.is_tensor(bias):+ continue+ weight_name = name[:-5] + "weight"+ weight = state_dict.get(weight_name)+ target_dtype = None+ weight_type = getattr(weight, "tensor_type", None) if torch.is_tensor(weight) else None+ if torch.is_tensor(weight) and weight_type is None:+ target_dtype = weight.dtype if weight.dtype.is_floating_point else default_dtype+ elif weight_type in (+ gguf.GGMLQuantizationType.F16,+ gguf.GGMLQuantizationType.BF16,+ gguf.GGMLQuantizationType.F32,+ ):+ target_dtype = weight.dtype+ else:+ target_dtype = default_dtype+ if target_dtype is None or bias.dtype == target_dtype:+ continue+ casted = bias.to(target_dtype)+ if isinstance(casted, GGUFSourceTensor):+ casted._gguf_bias_orig_dtype = getattr(bias, "_gguf_bias_orig_dtype", bias.dtype)+ casted._gguf_bias_orig_tensor_type = getattr(+ bias, "_gguf_bias_orig_tensor_type", getattr(bias, "tensor_type", None)+ )+ new_tensor_type = _tensor_type_from_dtype(target_dtype)+ if new_tensor_type is not None:+ casted.tensor_type = new_tensor_type+ casted.tensor_shape = getattr(bias, "tensor_shape", casted.shape)+ state_dict[name] = casted++ return state_dict, None, None+++def load_state_dict(*args, **kwargs):+ return load_gguf_state_dict(*args, **kwargs)+++class GGUFSourceTensor(torch.Tensor):+ @staticmethod+ def wrap(tensor, *, tensor_type, tensor_shape):+ wrapped = tensor.as_subclass(GGUFSourceTensor)+ wrapped.tensor_type = tensor_type+ wrapped.tensor_shape = tensor_shape+ return wrapped++ def to(self, *args, **kwargs):+ new = super().to(*args, **kwargs)+ new.tensor_type = getattr(self, "tensor_type", None)+ new.tensor_shape = getattr(self, "tensor_shape", new.shape)+ return new++ def clone(self, *args, **kwargs):+ cloned = super().clone(*args, **kwargs).as_subclass(GGUFSourceTensor)+ cloned.tensor_type = getattr(self, "tensor_type", None)+ cloned.tensor_shape = getattr(self, "tensor_shape", cloned.shape)+ return cloned++ def detach(self, *args, **kwargs):+ detached = super().detach(*args, **kwargs).as_subclass(GGUFSourceTensor)+ detached.tensor_type = getattr(self, "tensor_type", None)+ detached.tensor_shape = getattr(self, "tensor_shape", detached.shape)+ return detached++ def get_quantized_subtensors(self):+ return [("data", self)]++ def set_quantized_subtensors(self, sub_tensors):+ if isinstance(sub_tensors, dict):+ data = sub_tensors.get("data")+ else:+ data = dict(sub_tensors).get("data")+ if data is None or data is self:+ return+ torch.utils.swap_tensors(self, data)+++def _is_gguf_qtype(qtype_obj):+ if gguf is None:+ return False+ if qtype_obj is None:+ return False+ return qtype_obj not in (+ gguf.GGMLQuantizationType.F32,+ gguf.GGMLQuantizationType.F16,+ gguf.GGMLQuantizationType.BF16,+ )+++def _gguf_qtype_name(qtype_obj):+ if qtype_obj is None:+ return None+ return getattr(qtype_obj, "name", None) or str(qtype_obj)+++def _guess_variant_from_filename(filename):+ base = os.path.basename(str(filename))+ match = re.search(r"(?i)(?:^|[_-])(Q\d+_K|Q\d+_\d|Q\d+|IQ\d+_\w+)(?:$|[_.-])", base)+ if match:+ return match.group(1).upper()+ return None+++def detect_gguf_quantization_variant(file_path, verboseLevel=1):+ if gguf is None:+ return None+ try:+ reader = gguf.GGUFReader(file_path)+ except Exception:+ return None+ counts = {}+ for tensor in reader.tensors:+ qtype = getattr(tensor, "tensor_type", None)+ if qtype in (+ gguf.GGMLQuantizationType.F32,+ gguf.GGMLQuantizationType.F16,+ gguf.GGMLQuantizationType.BF16,+ ):+ continue+ name = _gguf_qtype_name(qtype)+ if not name:+ continue+ counts[name] = counts.get(name, 0) + 1+ if not counts:+ return None+ return max(counts, key=counts.get)+++def detect_quantization_kind_for_file(file_path, verboseLevel=1):+ if not file_path or str(file_path).lower().endswith(".gguf") is False:+ return None+ if gguf is None:+ return None+ return "gguf"+++def detect_quantization_label_from_filename(filename, verboseLevel=1):+ if not filename or str(filename).lower().endswith(".gguf") is False:+ return ""+ key = _normalize_gguf_path(filename)+ cached = _GGUF_LABEL_CACHE.get(key)+ if cached:+ return cached+ variant = _guess_variant_from_filename(filename)+ if not variant and os.path.isfile(filename):+ variant = detect_gguf_quantization_variant(filename, verboseLevel=verboseLevel)+ if variant:+ label = f"GGUF-{variant}"+ else:+ label = "GGUF"+ _GGUF_LABEL_CACHE[key] = label+ return label+++def _gguf_qfallback(callable, *args, **kwargs):+ args, kwargs = pytree.tree_map_only(GGUFWeightTensor, lambda x: x.dequantize(), (args, kwargs or {}))+ return callable(*args, **kwargs)+++def _reshape_scale(scale, weight):+ if scale.ndim == 0 or scale.numel() == 1:+ return scale+ if scale.ndim == 1 and scale.shape[0] == weight.shape[0]:+ return scale.view(weight.shape[0], *([1] * (weight.ndim - 1)))+ return scale+++def _gguf_dequantize_tensor(raw, qtype_obj, oshape, dtype=None):+ if gguf is None:+ raise RuntimeError("gguf package is required to dequantize GGUF weights.")+ if qtype_obj in (+ gguf.GGMLQuantizationType.F32,+ gguf.GGMLQuantizationType.F16,+ gguf.GGMLQuantizationType.BF16,+ ):+ out = raw.view(*oshape)+ return out.to(dtype) if dtype is not None else out+ if qtype_obj not in _DEQUANTIZE_FUNCTIONS:+ out = gguf.quants.dequantize(raw.cpu().numpy(), qtype_obj)+ out = torch.from_numpy(out)+ return out.to(dtype) if dtype is not None else out+ block_size, type_size = gguf.GGML_QUANT_SIZES[qtype_obj]+ dequantize_blocks = _DEQUANTIZE_FUNCTIONS[qtype_obj]+ rows = raw.reshape((-1, raw.shape[-1])).view(torch.uint8)+ n_blocks = rows.numel() // type_size+ blocks = rows.reshape((n_blocks, type_size))+ blocks = dequantize_blocks(blocks, block_size, type_size, dtype)+ return blocks.reshape(oshape)+++def _maybe_cast_bias(bias, target_dtype):+ if bias is None or not torch.is_tensor(bias) or target_dtype is None:+ return bias+ if bias.dtype == target_dtype:+ return bias+ if isinstance(bias, GGUFSourceTensor):+ tensor_type = getattr(bias, "tensor_type", None)+ tensor_shape = getattr(bias, "tensor_shape", bias.shape)+ if _is_gguf_qtype(tensor_type):+ return _gguf_dequantize_tensor(bias, tensor_type, tensor_shape, dtype=target_dtype)+ return bias.to(target_dtype)+++def _to_uint32(x):+ x = x.view(torch.uint8).to(torch.int32)+ return (x[:, 0] | x[:, 1] << 8 | x[:, 2] << 16 | x[:, 3] << 24).unsqueeze(1)+++def _to_uint16(x):+ x = x.view(torch.uint8).to(torch.int32)+ return (x[:, 0] | x[:, 1] << 8).unsqueeze(1)+++def _const_like(ref, values, dtype):+ device = ref.device if torch.is_tensor(ref) else None+ count = len(values)+ if count == 0:+ return torch.empty((0,), device=device, dtype=dtype)+ if count == 1:+ return torch.full((1,), values[0], device=device, dtype=dtype)+ step = values[1] - values[0]+ if all(values[idx] - values[idx - 1] == step for idx in range(1, count)):+ end = values[0] + step * count+ return torch.arange(values[0], end, step, device=device, dtype=dtype)+ raise ValueError("Unsupported constant pattern for GGUF dequantization.")+++def _split_block_dims(blocks, *args):+ n_max = blocks.shape[1]+ dims = list(args) + [n_max - sum(args)]+ return torch.split(blocks, dims, dim=1)+++def _dequantize_blocks_Q8_0(blocks, block_size, type_size, dtype=None):+ d, x = _split_block_dims(blocks, 2)+ d = d.view(torch.float16).to(dtype)+ x = x.view(torch.int8)+ return d * x+++def _dequantize_blocks_Q5_1(blocks, block_size, type_size, dtype=None):+ n_blocks = blocks.shape[0]+ d, m, qh, qs = _split_block_dims(blocks, 2, 2, 4)+ d = d.view(torch.float16).to(dtype)+ m = m.view(torch.float16).to(dtype)+ qh = _to_uint32(qh)+ qh = qh.reshape((n_blocks, 1)) >> torch.arange(32, device=d.device, dtype=torch.int32).reshape(1, 32)+ ql = qs.reshape((n_blocks, -1, 1, block_size // 2)) >> _const_like(d, [0, 4], torch.uint8).reshape(1, 1, 2, 1)+ qh = (qh & 1).to(torch.uint8)+ ql = (ql & 0x0F).reshape((n_blocks, -1))+ qs = ql | (qh << 4)+ return d * qs + m+++def _dequantize_blocks_Q5_0(blocks, block_size, type_size, dtype=None):+ n_blocks = blocks.shape[0]+ d, qh, qs = _split_block_dims(blocks, 2, 4)+ d = d.view(torch.float16).to(dtype)+ qh = _to_uint32(qh)+ qh = qh.reshape(n_blocks, 1) >> torch.arange(32, device=d.device, dtype=torch.int32).reshape(1, 32)+ ql = qs.reshape(n_blocks, -1, 1, block_size // 2) >> _const_like(d, [0, 4], torch.uint8).reshape(1, 1, 2, 1)+ qh = (qh & 1).to(torch.uint8)+ ql = (ql & 0x0F).reshape(n_blocks, -1)+ qs = (ql | (qh << 4)).to(torch.int8) - 16+ return d * qs+++def _dequantize_blocks_Q4_1(blocks, block_size, type_size, dtype=None):+ n_blocks = blocks.shape[0]+ d, m, qs = _split_block_dims(blocks, 2, 2)+ d = d.view(torch.float16).to(dtype)+ m = m.view(torch.float16).to(dtype)+ qs = qs.reshape((n_blocks, -1, 1, block_size // 2)) >> _const_like(d, [0, 4], torch.uint8).reshape(1, 1, 2, 1)+ qs = (qs & 0x0F).reshape((n_blocks, -1))+ return d * qs + m+++def _dequantize_blocks_Q4_0(blocks, block_size, type_size, dtype=None):+ n_blocks = blocks.shape[0]+ d, qs = _split_block_dims(blocks, 2)+ d = d.view(torch.float16).to(dtype)+ qs = qs.reshape((n_blocks, -1, 1, block_size // 2)) >> _const_like(d, [0, 4], torch.uint8).reshape(1, 1, 2, 1)+ qs = (qs & 0x0F).reshape((n_blocks, -1))+ qs = qs.to(torch.int8) - 8+ return d * qs+++QK_K = 256+K_SCALE_SIZE = 12+++def _get_scale_min(scales):+ n_blocks = scales.shape[0]+ scales = scales.view(torch.uint8)+ scales = scales.reshape((n_blocks, 3, 4))+ d, m, m_d = torch.split(scales, scales.shape[-2] // 3, dim=-2)+ sc = torch.cat([d & 0x3F, (m_d & 0x0F) | ((d >> 2) & 0x30)], dim=-1)+ mn = torch.cat([m & 0x3F, (m_d >> 4) | ((m >> 2) & 0x30)], dim=-1)+ return sc.reshape((n_blocks, 8)), mn.reshape((n_blocks, 8))+++def _dequantize_blocks_Q6_K(blocks, block_size, type_size, dtype=None):+ n_blocks = blocks.shape[0]+ ql, qh, scales, d = _split_block_dims(blocks, QK_K // 2, QK_K // 4, QK_K // 16)+ scales = scales.view(torch.int8).to(dtype)+ d = d.view(torch.float16).to(dtype)+ d = (d * scales).reshape((n_blocks, QK_K // 16, 1))+ ql = ql.reshape((n_blocks, -1, 1, 64)) >> _const_like(d, [0, 4], torch.uint8).reshape((1, 1, 2, 1))+ ql = (ql & 0x0F).reshape((n_blocks, -1, 32))+ qh = qh.reshape((n_blocks, -1, 1, 32)) >> _const_like(d, [0, 2, 4, 6], torch.uint8).reshape((1, 1, 4, 1))+ qh = (qh & 0x03).reshape((n_blocks, -1, 32))+ q = (ql | (qh << 4)).to(torch.int8) - 32+ q = q.reshape((n_blocks, QK_K // 16, -1))+ return (d * q).reshape((n_blocks, QK_K))+++def _dequantize_blocks_Q5_K(blocks, block_size, type_size, dtype=None):+ n_blocks = blocks.shape[0]+ d, dmin, scales, qh, qs = _split_block_dims(blocks, 2, 2, K_SCALE_SIZE, QK_K // 8)+ d = d.view(torch.float16).to(dtype)+ dmin = dmin.view(torch.float16).to(dtype)+ sc, m = _get_scale_min(scales)+ d = (d * sc).reshape((n_blocks, -1, 1))+ dm = (dmin * m).reshape((n_blocks, -1, 1))+ ql = qs.reshape((n_blocks, -1, 1, 32)) >> _const_like(d, [0, 4], torch.uint8).reshape((1, 1, 2, 1))+ qh = qh.reshape((n_blocks, -1, 1, 32)) >> _const_like(d, list(range(8)), torch.uint8).reshape((1, 1, 8, 1))+ ql = (ql & 0x0F).reshape((n_blocks, -1, 32))+ qh = (qh & 0x01).reshape((n_blocks, -1, 32))+ q = ql | (qh << 4)+ return (d * q - dm).reshape((n_blocks, QK_K))+++def _dequantize_blocks_Q4_K(blocks, block_size, type_size, dtype=None):+ n_blocks = blocks.shape[0]+ d, dmin, scales, qs = _split_block_dims(blocks, 2, 2, K_SCALE_SIZE)+ d = d.view(torch.float16).to(dtype)+ dmin = dmin.view(torch.float16).to(dtype)+ sc, m = _get_scale_min(scales)+ d = (d * sc).reshape((n_blocks, -1, 1))+ dm = (dmin * m).reshape((n_blocks, -1, 1))+ qs = qs.reshape((n_blocks, -1, 1, 32)) >> _const_like(d, [0, 4], torch.uint8).reshape((1, 1, 2, 1))+ qs = (qs & 0x0F).reshape((n_blocks, -1, 32))+ return (d * qs - dm).reshape((n_blocks, QK_K))+++def _dequantize_blocks_Q3_K(blocks, block_size, type_size, dtype=None):+ n_blocks = blocks.shape[0]+ hmask, qs, scales, d = _split_block_dims(blocks, QK_K // 8, QK_K // 4, 12)+ d = d.view(torch.float16).to(dtype)+ lscales, hscales = scales[:, :8], scales[:, 8:]+ lscales = lscales.reshape((n_blocks, 1, 8)) >> _const_like(d, [0, 4], torch.uint8).reshape((1, 2, 1))+ lscales = lscales.reshape((n_blocks, 16))+ hscales = hscales.reshape((n_blocks, 1, 4)) >> _const_like(d, [0, 2, 4, 6], torch.uint8).reshape((1, 4, 1))+ hscales = hscales.reshape((n_blocks, 16))+ scales = (lscales & 0x0F) | ((hscales & 0x03) << 4)+ scales = (scales.to(torch.int8) - 32)+ dl = (d * scales).reshape((n_blocks, 16, 1))+ ql = qs.reshape((n_blocks, -1, 1, 32)) >> _const_like(d, [0, 2, 4, 6], torch.uint8).reshape((1, 1, 4, 1))+ qh = hmask.reshape(n_blocks, -1, 1, 32) >> _const_like(d, list(range(8)), torch.uint8).reshape((1, 1, 8, 1))+ ql = ql.reshape((n_blocks, 16, QK_K // 16)) & 3+ qh = (qh.reshape((n_blocks, 16, QK_K // 16)) & 1) ^ 1+ q = (ql.to(torch.int8) - (qh << 2).to(torch.int8))+ return (dl * q).reshape((n_blocks, QK_K))+++def _dequantize_blocks_Q2_K(blocks, block_size, type_size, dtype=None):+ n_blocks = blocks.shape[0]+ scales, qs, d, dmin = _split_block_dims(blocks, QK_K // 16, QK_K // 4, 2)+ d = d.view(torch.float16).to(dtype)+ dmin = dmin.view(torch.float16).to(dtype)+ dl = (d * (scales & 0xF)).reshape((n_blocks, QK_K // 16, 1))+ ml = (dmin * (scales >> 4)).reshape((n_blocks, QK_K // 16, 1))+ shift = _const_like(d, [0, 2, 4, 6], torch.uint8).reshape((1, 1, 4, 1))+ qs = (qs.reshape((n_blocks, -1, 1, 32)) >> shift) & 3+ qs = qs.reshape((n_blocks, QK_K // 16, 16))+ qs = dl * qs - ml+ return qs.reshape((n_blocks, -1))+++if gguf is not None:+ _DEQUANTIZE_FUNCTIONS = {+ gguf.GGMLQuantizationType.Q8_0: _dequantize_blocks_Q8_0,+ gguf.GGMLQuantizationType.Q5_1: _dequantize_blocks_Q5_1,+ gguf.GGMLQuantizationType.Q5_0: _dequantize_blocks_Q5_0,+ gguf.GGMLQuantizationType.Q4_1: _dequantize_blocks_Q4_1,+ gguf.GGMLQuantizationType.Q4_0: _dequantize_blocks_Q4_0,+ gguf.GGMLQuantizationType.Q6_K: _dequantize_blocks_Q6_K,+ gguf.GGMLQuantizationType.Q5_K: _dequantize_blocks_Q5_K,+ gguf.GGMLQuantizationType.Q4_K: _dequantize_blocks_Q4_K,+ gguf.GGMLQuantizationType.Q3_K: _dequantize_blocks_Q3_K,+ gguf.GGMLQuantizationType.Q2_K: _dequantize_blocks_Q2_K,+ }+else:+ _DEQUANTIZE_FUNCTIONS = {}+++class GGUFWeightTensor(QTensor):+ @staticmethod+ def create(raw_tensor, size, stride, dtype, device=None, requires_grad=False, tensor_type=None, tensor_shape=None):+ if tensor_type is None:+ tensor_type = getattr(raw_tensor, "tensor_type", None)+ if tensor_shape is None:+ tensor_shape = getattr(raw_tensor, "tensor_shape", None) or size+ device = raw_tensor.device if device is None else device+ if raw_tensor.device != device:+ raw_tensor = raw_tensor.to(device)+ return GGUFWeightTensor(+ qtype=_GGUF_QTYPE,+ axis=0,+ size=size,+ stride=stride,+ raw=raw_tensor,+ tensor_type=tensor_type,+ tensor_shape=tensor_shape,+ dtype=dtype,+ requires_grad=requires_grad,+ )++ @staticmethod+ def __new__(cls, qtype, axis, size, stride, raw, tensor_type, tensor_shape, dtype, requires_grad=False):+ return torch.Tensor._make_wrapper_subclass(+ cls,+ size,+ strides=stride,+ dtype=dtype,+ device=raw.device,+ requires_grad=requires_grad,+ )++ def __init__(self, qtype, axis, size, stride, raw, tensor_type, tensor_shape, dtype, requires_grad=False):+ super().__init__(qtype, axis)+ self._data = raw+ self._tensor_type = tensor_type+ self._tensor_shape = torch.Size(tensor_shape)+ self._gguf_default_dtype = dtype++ def __repr__(self):+ cls_name = self.__class__.__name__+ try:+ shape = tuple(self.shape)+ except Exception:+ shape = "<?>"+ try:+ dtype = str(self.dtype).replace("torch.", "")+ except Exception:+ dtype = "<?>"+ try:+ device = str(self.device)+ except Exception:+ device = "<?>"+ qtype = getattr(self, "_qtype", None)+ qtype_name = getattr(qtype, "name", None) or str(qtype) if qtype is not None else "<?>"+ tensor_type = _gguf_qtype_name(getattr(self, "_tensor_type", None)) or "<?>"+ return (+ f"{cls_name}(shape={shape}, dtype={dtype}, device={device}, "+ f"qtype={qtype_name}, tensor_type={tensor_type})"+ )++ __str__ = __repr__++ def dequantize(self, dtype=None, device=None):+ if dtype is None:+ dtype = self.dtype+ if device is None:+ device = self.device+ raw = self._data if self._data.device == device else self._data.to(device)+ return _gguf_dequantize_tensor(raw, self._tensor_type, self._tensor_shape, dtype=dtype)++ def linear(self, input, bias=None):+ if torch.is_tensor(input):+ target_dtype = _resolve_default_dtype(self._gguf_default_dtype, fallback=input.dtype)+ target_device = input.device+ else:+ target_dtype = _resolve_default_dtype(self._gguf_default_dtype, fallback=self.dtype)+ target_device = self.device+ weight = self.dequantize(dtype=target_dtype, device=target_device)+ if torch.is_tensor(input) and input.dtype != weight.dtype:+ input = input.to(weight.dtype)+ bias = _maybe_cast_bias(bias, weight.dtype)+ return torch.nn.functional.linear(input, weight, bias)++ def get_quantized_subtensors(self):+ return [("data", self._data)]++ def set_quantized_subtensors(self, sub_tensors):+ if isinstance(sub_tensors, dict):+ sub_map = sub_tensors+ else:+ sub_map = {name: tensor for name, tensor in sub_tensors}+ data = sub_map.get("data", None)+ if data is not None:+ old_data = self._data+ if torch.is_tensor(old_data):+ try:+ torch.utils.swap_tensors(old_data, data)+ self._data = old_data+ except Exception:+ self._data = data+ else:+ self._data = data+ if hasattr(self, "_ggml_raw_cpu"):+ self._ggml_raw_cpu = None++ def __tensor_flatten__(self):+ inner_tensors = ["_data"]+ meta = {+ "qtype": self._qtype.name,+ "axis": str(self._axis),+ "size": str(list(self.size())),+ "stride": str(list(self.stride())),+ "dtype": str(self.dtype),+ "tensor_type": _gguf_qtype_name(self._tensor_type) or "",+ "tensor_shape": str(list(self._tensor_shape)),+ }+ return inner_tensors, meta++ @staticmethod+ def __tensor_unflatten__(inner_tensors, meta, outer_size, outer_stride):+ qtype = _quanto_qtypes[meta["qtype"]]+ axis = ast.literal_eval(meta["axis"])+ size = ast.literal_eval(meta["size"])+ stride = ast.literal_eval(meta["stride"])+ dtype_str = meta.get("dtype", "torch.float16")+ if dtype_str.startswith("torch."):+ dtype_name = dtype_str.split(".", 1)[1]+ dtype = getattr(torch, dtype_name, torch.float16)+ else:+ dtype = getattr(torch, dtype_str, torch.float16)+ tensor_shape = ast.literal_eval(meta.get("tensor_shape", str(list(size))))+ tensor_type = None+ if gguf is not None and meta.get("tensor_type"):+ tensor_type = getattr(gguf.GGMLQuantizationType, meta["tensor_type"], None)+ return GGUFWeightTensor(+ qtype=qtype,+ axis=axis,+ size=size,+ stride=stride,+ raw=inner_tensors["_data"],+ tensor_type=tensor_type,+ tensor_shape=tensor_shape,+ dtype=dtype,+ )++ @classmethod+ def __torch_function__(cls, func, types, args=(), kwargs=None):+ kwargs = kwargs or {}+ if func is torch.nn.functional.linear:+ input = args[0] if len(args) > 0 else kwargs.get("input", None)+ weight = args[1] if len(args) > 1 else kwargs.get("weight", None)+ bias = args[2] if len(args) > 2 else kwargs.get("bias", None)+ if isinstance(weight, GGUFWeightTensor):+ return weight.linear(input, bias=bias)+ with torch._C.DisableTorchFunctionSubclass():+ return func(*args, **kwargs)++ @classmethod+ def __torch_dispatch__(cls, op, types, args, kwargs=None):+ op = op.overloadpacket+ kwargs = kwargs or {}+ if op is torch.ops.aten.linear:+ input = args[0]+ weight = args[1]+ bias = args[2] if len(args) > 2 else None+ if isinstance(weight, GGUFWeightTensor):+ return weight.linear(input, bias=bias)+ if op is torch.ops.aten.detach:+ t = args[0]+ return GGUFWeightTensor.create(+ raw_tensor=op(t._data),+ size=t.size(),+ stride=t.stride(),+ dtype=t.dtype,+ device=t.device,+ requires_grad=t.requires_grad,+ tensor_type=getattr(t, "_tensor_type", None),+ tensor_shape=getattr(t, "_tensor_shape", None),+ )+ if op in (torch.ops.aten._to_copy, torch.ops.aten.to):+ t = args[0]+ dtype = kwargs.pop("dtype", t.dtype) if kwargs else t.dtype+ device = kwargs.pop("device", t.device) if kwargs else t.device+ if dtype != t.dtype:+ return t.dequantize(dtype=dtype, device=device)+ out_data = op(t._data, device=device, **(kwargs or {}))+ return GGUFWeightTensor.create(+ raw_tensor=out_data,+ size=t.size(),+ stride=t.stride(),+ dtype=t.dtype,+ device=device,+ requires_grad=t.requires_grad,+ tensor_type=getattr(t, "_tensor_type", None),+ tensor_shape=getattr(t, "_tensor_shape", None),+ )+ return _gguf_qfallback(op, *args, **(kwargs or {}))+++class QLinearGGUF(QModuleMixin, torch.nn.Linear):+ def __init__(+ self,+ in_features,+ out_features,+ bias=True,+ device=None,+ dtype=None,+ weights=None,+ activations=None,+ optimizer=None,+ quantize_input=True,+ ):+ super().__init__(+ in_features,+ out_features,+ bias=bias,+ device=device,+ dtype=dtype,+ weights=weights,+ activations=activations,+ optimizer=optimizer,+ quantize_input=quantize_input,+ )+ self._gguf_default_dtype = dtype++ @classmethod+ def qcreate(cls, module, weights, activations=None, optimizer=None, device=None):+ if torch.is_tensor(module.weight) and module.weight.dtype.is_floating_point:+ weight_dtype = module.weight.dtype+ elif torch.is_tensor(getattr(module, "bias", None)) and module.bias.dtype.is_floating_point:+ weight_dtype = module.bias.dtype+ else:+ weight_dtype = torch.float16+ return cls(+ module.in_features,+ module.out_features,+ module.bias is not None,+ device=device,+ dtype=weight_dtype,+ weights=weights,+ activations=activations,+ optimizer=optimizer,+ quantize_input=True,+ )++ def set_default_dtype(self, dtype):+ self._gguf_default_dtype = dtype++ @property+ def qweight(self):+ if self.weight_qtype == _GGUF_QTYPE:+ return self.weight+ return super().qweight++ def forward(self, input: torch.Tensor) -> torch.Tensor:+ qweight = self.qweight+ if isinstance(qweight, GGUFWeightTensor):+ return qweight.linear(input, bias=self.bias)+ return torch.nn.functional.linear(input, qweight, bias=self.bias)++ def _load_from_state_dict(+ self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs+ ):+ if self.weight_qtype != _GGUF_QTYPE:+ return super()._load_from_state_dict(+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs+ )++ weight_key = prefix + "weight"+ bias_key = prefix + "bias"+ input_scale_key = prefix + "input_scale"+ output_scale_key = prefix + "output_scale"++ weight_raw = state_dict.pop(weight_key, None)+ bias = state_dict.pop(bias_key, None)+ input_scale = state_dict.pop(input_scale_key, None)+ output_scale = state_dict.pop(output_scale_key, None)++ if weight_raw is None:+ missing_keys.append(weight_key)++ target_dtype = _resolve_default_dtype(self._gguf_default_dtype, fallback=self.weight.dtype)+ if weight_raw is not None:+ gguf_weight = GGUFWeightTensor.create(+ raw_tensor=weight_raw,+ size=self.weight.size(),+ stride=self.weight.stride(),+ dtype=target_dtype,+ device=weight_raw.device,+ requires_grad=False,+ )+ self.weight = torch.nn.Parameter(gguf_weight, requires_grad=False)++ if bias is not None:+ self.bias = torch.nn.Parameter(bias)++ if torch.is_tensor(weight_raw):+ scale_device = weight_raw.device+ elif torch.is_tensor(self.weight):+ scale_device = self.weight.device+ elif torch.is_tensor(bias):+ scale_device = bias.device+ else:+ scale_device = torch.device("cpu")++ if input_scale is not None:+ self.input_scale = input_scale.to(scale_device)+ else:+ if not hasattr(self, "input_scale") or self.input_scale.is_meta:+ scale_dtype = self.input_scale.dtype if hasattr(self, "input_scale") else torch.float32+ self.input_scale = torch.ones((), dtype=scale_dtype, device=scale_device)++ if output_scale is not None:+ self.output_scale = output_scale.to(scale_device)+ else:+ if not hasattr(self, "output_scale") or self.output_scale.is_meta:+ scale_dtype = self.output_scale.dtype if hasattr(self, "output_scale") else torch.float32+ self.output_scale = torch.ones((), dtype=scale_dtype, device=scale_device)++ return+++def _collect_gguf_specs(state_dict):+ specs = []+ for key, tensor in state_dict.items():+ if not key.endswith(".weight"):+ continue+ if not _is_gguf_qtype(getattr(tensor, "tensor_type", None)):+ continue+ specs.append({"name": key[:-7], "tensor": tensor})+ return specs+++def detect(state_dict, verboseLevel=1):+ if gguf is None:+ return {"matched": False, "kind": "none", "details": {"error": "gguf not installed"}}+ specs = _collect_gguf_specs(state_dict)+ if not specs:+ return {"matched": False, "kind": "none", "details": {}}+ names = [spec["name"] for spec in specs][:8]+ return {"matched": True, "kind": "gguf", "details": {"count": len(specs), "names": names}}+++def convert_to_quanto(state_dict, default_dtype, verboseLevel=1, detection=None):+ if gguf is None:+ return {"state_dict": state_dict, "quant_map": {}}+ if detection is not None and not detection.get("matched", False):+ return {"state_dict": state_dict, "quant_map": {}}+ specs = _collect_gguf_specs(state_dict)+ if not specs:+ return {"state_dict": state_dict, "quant_map": {}}+ _set_default_dtype_from_loader(default_dtype)+ quant_map = {spec["name"]: {"weights": _GGUF_QTYPE_NAME, "activations": "none"} for spec in specs}+ return {"state_dict": state_dict, "quant_map": quant_map}+++def apply_pre_quantization(model, state_dict, quantization_map, default_dtype=None, verboseLevel=1):+ if default_dtype is None or model is None or not quantization_map:+ return quantization_map or {}, []+ _set_default_dtype_from_loader(default_dtype)+ quantized = set(quantization_map.keys())+ for name, module in model.named_modules():+ if name in quantized and isinstance(module, torch.nn.Linear):+ module._router_default_dtype = default_dtype+ return quantization_map or {}, []diff --git a/shared/qtypes/nunchaku_fp4.py b/shared/qtypes/nunchaku_fp4.pyindex 36991d2..471b1bf 100644--- a/shared/qtypes/nunchaku_fp4.py+++ b/shared/qtypes/nunchaku_fp4.py@@ -13,6 +13,7 @@ from optimum.quanto.tensor.qtype import qtype as _quanto_qtype, qtypes as _quantHANDLER_NAME = "nunchaku_fp4"+HANDLER_PRIORITY = 2_NUNCHAKU_FP4_QTYPE_NAME = "nunchaku_fp4"if _NUNCHAKU_FP4_QTYPE_NAME not in _quanto_qtypes:diff --git a/shared/qtypes/nunchaku_int4.py b/shared/qtypes/nunchaku_int4.pyindex 0fb5f63..11327c6 100644--- a/shared/qtypes/nunchaku_int4.py+++ b/shared/qtypes/nunchaku_int4.py@@ -13,6 +13,7 @@ from optimum.quanto.tensor.qtype import qtype as _quanto_qtype, qtypes as _quantHANDLER_NAME = "nunchaku_int4"+HANDLER_PRIORITY = 2_NUNCHAKU_INT4_QTYPE_NAME = "nunchaku_int4"if _NUNCHAKU_INT4_QTYPE_NAME not in _quanto_qtypes:diff --git a/shared/qtypes/nvfp4.py b/shared/qtypes/nvfp4.pyindex 2f1a2af..5fdb7b1 100644--- a/shared/qtypes/nvfp4.py+++ b/shared/qtypes/nvfp4.py@@ -44,6 +44,7 @@ if _NVFP4_QTYPE_NAME not in _quanto_qtypes:qmax=6.0,)_NVFP4_QTYPE = _quanto_qtypes[_NVFP4_QTYPE_NAME]+HANDLER_PRIORITY = 1_NVFP4_LAYOUT_LEGACY = "legacy"_NVFP4_LAYOUT_TENSORCORE = "tensorcore"@@ -415,6 +416,21 @@ def _nvfp4_linear_cuda(input, weight, bias=None):return _nvfp4_linear_cuda_comfy(input, weight, bias=bias)+def _nvfp4_linear(input, weight, bias=None, op=None):+ if _nvfp4_can_use_kernel(input, weight):+ return _nvfp4_linear_cuda(input, weight, bias=bias)+ _nvfp4_note_fallback()+ dtype = input.dtype if torch.is_tensor(input) else weight.dtype+ device = input.device if torch.is_tensor(input) else weight.device+ w = weight.dequantize(dtype=dtype, device=device)+ if bias is not None and torch.is_tensor(bias) and bias.dtype != dtype:+ bias = bias.to(dtype)+ if op is not None:+ return op(input, w, bias)+ return torch.nn.functional.linear(input, w, bias)++def _is_float8_dtype(dtype):return "float8" in str(dtype).lower() or "f8" in str(dtype).lower()@@ -818,15 +834,7 @@ class NVFP4WeightTensor(QTensor):weight = args[1] if len(args) > 1 else kwargs.get("weight", None)bias = args[2] if len(args) > 2 else kwargs.get("bias", None)if isinstance(weight, NVFP4WeightTensor):- if _nvfp4_can_use_kernel(input, weight):- return _nvfp4_linear_cuda(input, weight, bias=bias)- _nvfp4_note_fallback()- dtype = input.dtype if torch.is_tensor(input) else weight.dtype- device = input.device if torch.is_tensor(input) else weight.device- w = weight.dequantize(dtype=dtype, device=device)- if bias is not None and torch.is_tensor(bias) and bias.dtype != dtype:- bias = bias.to(dtype)- return torch.nn.functional.linear(input, w, bias)+ return _nvfp4_linear(input, weight, bias=bias)with torch._C.DisableTorchFunctionSubclass():return func(*args, **kwargs)@@ -838,15 +846,7 @@ class NVFP4WeightTensor(QTensor):weight = args[1]bias = args[2] if len(args) > 2 else Noneif isinstance(weight, NVFP4WeightTensor):- if _nvfp4_can_use_kernel(input, weight):- return _nvfp4_linear_cuda(input, weight, bias=bias)- _nvfp4_note_fallback()- dtype = input.dtype if torch.is_tensor(input) else weight.dtype- device = input.device if torch.is_tensor(input) else weight.device- w = weight.dequantize(dtype=dtype, device=device)- if bias is not None and torch.is_tensor(bias) and bias.dtype != dtype:- bias = bias.to(dtype)- return op(input, w, bias)+ return _nvfp4_linear(input, weight, bias=bias, op=op)if op is torch.ops.aten.detach:t = args[0]return NVFP4WeightTensor.create(diff --git a/shared/qtypes/scaled_fp8.py b/shared/qtypes/scaled_fp8.pyindex ef56d5a..6079e59 100644--- a/shared/qtypes/scaled_fp8.py+++ b/shared/qtypes/scaled_fp8.py@@ -10,6 +10,7 @@ from optimum.quanto.tensor.qtype import qtype as _quanto_qtype, qtypes as _quantHANDLER_NAME = "fp8"+HANDLER_PRIORITY = 10_SCALED_FP8_E4M3_QTYPE_NAME = "scaled_float8_e4m3fn"_SCALED_FP8_E5M2_QTYPE_NAME = "scaled_float8_e5m2"@@ -199,6 +200,26 @@ class ScaledFP8WeightTensor(QTensor):self._scaled_mm_static_ok = _scaled_mm_static_ok(self._data, self._scale)self._set_linear_impl()+ def __repr__(self):+ cls_name = self.__class__.__name__+ try:+ shape = tuple(self.shape)+ except Exception:+ shape = "<?>"+ try:+ dtype = str(self.dtype).replace("torch.", "")+ except Exception:+ dtype = "<?>"+ try:+ device = str(self.device)+ except Exception:+ device = "<?>"+ qtype = getattr(self, "_qtype", None)+ qtype_name = getattr(qtype, "name", None) or str(qtype) if qtype is not None else "<?>"+ return f"{cls_name}(shape={shape}, dtype={dtype}, device={device}, qtype={qtype_name})"++ __str__ = __repr__+def _set_linear_impl(self):if self._scaled_mm_static_ok and _scaled_mm_available(self._data.dtype):self._linear_impl = ScaledFP8WeightTensor._linear_scaleddiff --git a/shared/utils/files_locator.py b/shared/utils/files_locator.pyindex 407d428..8d4bec4 100644--- a/shared/utils/files_locator.py+++ b/shared/utils/files_locator.py@@ -42,6 +42,8 @@ def locate_folder(folder_name, error_if_none = True):def locate_file(file_name, create_path_if_none = False, error_if_none = True, extra_paths = None):+ if file_name.startswith("http"):+ file_name = os.path.basename(file_name)searched_locations = []if os.path.isabs(file_name):if os.path.isfile(file_name): return file_namediff --git a/wgp.py b/wgp.pyindex f41bb46..181a508 100644--- a/wgp.py+++ b/wgp.py@@ -84,8 +84,8 @@ AUTOSAVE_PATH = AUTOSAVE_FILENAMEAUTOSAVE_TEMPLATE_PATH = AUTOSAVE_FILENAMECONFIG_FILENAME = "wgp_config.json"PROMPT_VARS_MAX = 10-target_mmgp_version = "3.6.15"-WanGP_version = "10.30"+target_mmgp_version = "3.6.16"+WanGP_version = "10.40"settings_version = 2.43max_source_video_frames = 3000prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer = None, None, None, None@@ -111,10 +111,13 @@ _HANDLER_MODULES = ["shared.qtypes.nvfp4","shared.qtypes.nunchaku_int4","shared.qtypes.nunchaku_fp4",+ "shared.qtypes.gguf",]quant_router.unregister_handler(".fp8_quanto_bridge")for handler in _HANDLER_MODULES:quant_router.register_handler(handler)+from shared.qtypes import gguf as gguf_handler+offload.register_file_extension("gguf", gguf_handler)@@ -643,6 +646,10 @@ def validate_settings(state, model_type, single_prompt, inputs):if image_mode > 0:audio_prompt_type = ""+ if "K" in audio_prompt_type and "V" not in video_prompt_type:+ gr.Info("You must enable a Control Video to use the Control Video Audio Track as an audio prompt")+ return ret()+if "B" in audio_prompt_type or "X" in audio_prompt_type:from models.wan.multitalk.multitalk import parse_speakers_locationsspeakers_bboxes, error = parse_speakers_locations(speakers_locations)@@ -769,7 +776,8 @@ def validate_settings(state, model_type, single_prompt, inputs):if "G" in video_prompt_type or model_def.get("mask_strength_always_enabled", False):if "A" in video_prompt_type and "U" not in video_prompt_type and masking_strength < 1.:masking_duration = math.ceil(num_inference_steps * masking_strength)- gr.Info(f"With Masking Strength {masking_strength:.1f}, Masking will last {masking_duration}{' Step' if masking_duration==1 else ' Steps'}")+ if masking_strength:+ gr.Info(f"With Masking Strength {masking_strength:.1f}, Masking will last {masking_duration}{' Step' if masking_duration==1 else ' Steps'}")else:masking_strength = 1.0if len(keep_frames_video_guide) > 0 and model_type in ["ltxv_13B"]:@@ -2986,9 +2994,7 @@ def download_models(model_filename = None, model_type= None, file_type = 0, submany_module_source = ("module_source2" if submodel_no ==2 else "module_source") in model_defmodel_type_handler = model_types_handlers[base_model_type]- if any_source and file_type==0 or any_module_source and file_type==1:- model_filename = None- else:+ if not (any_source and file_type==0 or any_module_source and file_type==1):local_model_filename = get_local_model_filename(model_filename, extra_paths= force_path)if local_model_filename is None and len(model_filename) > 0:local_model_filename = fl.get_download_location(os.path.basename(model_filename), force_path= force_path)@@ -3002,7 +3008,6 @@ def download_models(model_filename = None, model_type= None, file_type = 0, submif os.path.isfile(local_model_filename): os.remove(local_model_filename)raise Exception(f"'{url}' is invalid for Model '{model_type}' : {str(e)}'")if file_type!=0: return- model_filename = Nonefor prop, recursive in zip(["preload_URLs", "VAE_URLs"], [True, False]):if recursive:@@ -3036,9 +3041,7 @@ def download_models(model_filename = None, model_type= None, file_type = 0, submraise Exception(f"Lora URL '{url}' is invalid: {str(e)}'")if file_type != 0: return- # model_filename should be None (deprecated) as query_model_files is no longer in charge of loading the transformer- # likewise text_encoder_quantization is wont be used by coder_quantization since the text_encoder is loaded by load_models- model_files = model_type_handler.query_model_files(computeList, base_model_type, model_filename, text_encoder_quantization, model_def)+ model_files = model_type_handler.query_model_files(computeList, base_model_type, model_def)if not isinstance(model_files, list): model_files = [model_files]for one_repo in model_files:process_files_def(**one_repo)@@ -3313,12 +3316,7 @@ def load_models(model_type, override_profile = -1, **model_kwargs):model_type_handler = model_types_handlers[base_model_type]text_encoder_URLs= get_model_recursive_prop(model_type, "text_encoder_URLs", return_list= True)- text_encoder_filename = None- if text_encoder_URLs is None or len(text_encoder_URLs) == 0:- if hasattr(model_type_handler, "get_text_encoder_filename"):- text_encoder_filename = model_type_handler.get_text_encoder_filename(text_encoder_quantization)-- else:+ if text_encoder_URLs is not None:text_encoder_filename = get_model_filename(model_type=model_type, quantization= text_encoder_quantization, dtype_policy = transformer_dtype_policy, URLs=text_encoder_URLs)if text_encoder_filename is not None:text_encoder_folder = model_def.get("text_encoder_folder", None)@@ -3894,7 +3892,7 @@ def select_video(state, current_gallery_tab, input_file_list, file_selected, audimage_outputs = configs.get("image_mode",0) > 0map_video_prompt = {"V" : "Control Image" if image_outputs else "Control Video", ("VA", "U") : "Mask Image" if image_outputs else "Mask Video", "I" : "Reference Images"}map_image_prompt = {"V" : "Source Video", "L" : "Last Video", "S" : "Start Image", "E" : "End Image"}- map_audio_prompt = {"A" : "Audio Source", "B" : "Audio Source #2"}+ map_audio_prompt = {"A" : "Audio Source", "B" : "Audio Source #2", "K": "Control Video Audio Track"}video_other_prompts = [ v for s,v in map_image_prompt.items() if all_letters(video_image_prompt_type,s)] \+ [ v for s,v in map_video_prompt.items() if check(video_video_prompt_type,s)] \+ [ v for s,v in map_audio_prompt.items() if all_letters(video_audio_prompt_type,s)]@@ -5012,18 +5010,11 @@ def truncate_audio(generated_audio, trim_video_frames_beginning, trim_video_framreturn generated_audio[start:end if end > 0 else None]def slice_audio_window(audio_path, start_frame, num_frames, fps, output_dir, suffix=""):- if audio_path is None or num_frames <= 0 or fps <= 0:- return audio_path- try:- import soundfile as sf- except Exception:- return audio_path+ import soundfile as sfimport numpy as npstart_sec = float(start_frame) / float(fps)duration_sec = float(num_frames) / float(fps)- if duration_sec <= 0:- return audio_pathwith sf.SoundFile(audio_path) as audio_file:sample_rate = audio_file.samplerate@@ -5035,8 +5026,6 @@ def slice_audio_window(audio_path, start_frame, num_frames, fps, output_dir, sufpad_start = -start_samplestart_sample = 0frames_to_read = int(round(duration_sec * sample_rate))- if pad_start == 0 and start_sample == 0 and frames_to_read >= total_frames:- return audio_pathif start_sample > total_frames:data = np.zeros((0, channels), dtype=np.float32)else:@@ -5049,11 +5038,33 @@ def slice_audio_window(audio_path, start_frame, num_frames, fps, output_dir, sufif data.shape[0] < target_frames:pad_end = target_frames - data.shape[0]data = np.concatenate([data, np.zeros((pad_end, channels), dtype=np.float32)], axis=0)+ if data.ndim == 2:+ data = data.T+ return data, sample_rate- output_dir = output_dir or os.path.dirname(audio_path) or "."- temp_path = get_available_filename(output_dir, audio_path, suffix=suffix, force_extension=".wav")- sf.write(temp_path, data, sample_rate)- return temp_path+def extract_audio_track_to_wav(video_path, output_dir, suffix=""):+ if not video_path:+ return None+ try:+ video_path = os.fspath(video_path)+ except TypeError:+ return None+ try:+ import ffmpeg+ except Exception:+ return None+ output_dir = output_dir or os.path.dirname(video_path) or "."+ output_path = get_available_filename(output_dir, video_path, suffix=suffix, force_extension=".wav")+ try:+ (+ ffmpeg.input(video_path)+ .output(output_path, **{"map": "0:a:0", "acodec": "pcm_s16le"})+ .overwrite_output()+ .run(quiet=True)+ )+ except Exception:+ return None+ return output_pathdef write_wav_file(file_path, audio_data, sampling_rate):@@ -5445,8 +5456,15 @@ def generate_video(video_source = max(mp4_files, key=os.path.getmtime) if mp4_files else Nonefps = 1 if is_image else get_computed_fps(force_fps, base_model_type , video_guide, video_source )control_audio_tracks = source_audio_tracks = source_audio_metadata = []- if "R" in audio_prompt_type and video_guide is not None and MMAudio_setting == 0 and not any_letters(audio_prompt_type, "ABX"):+ if any_letters(audio_prompt_type, "R") and video_guide is not None and MMAudio_setting == 0 and not any_letters(audio_prompt_type, "ABXK"):control_audio_tracks, _ = extract_audio_tracks(video_guide)+ if "K" in audio_prompt_type and video_guide is not None:+ try:+ audio_guide = extract_audio_track_to_wav(video_guide, save_path, suffix="_control_audio")+ temp_filenames_list.append(audio_guide)+ except:+ audio_guide = None+ audio_guide2 = Noneif video_source is not None:source_audio_tracks, source_audio_metadata = extract_audio_tracks(video_source)video_fps, _, _, video_frames_count = get_video_info(video_source)@@ -5515,7 +5533,6 @@ def generate_video(audio_scale = audio_scale if model_def.get("audio_scale_name") else Noneaudio_context_lens = Noneif audio_guide != None:- from models.wan.fantasytalking.infer import parse_audiofrom preprocessing.extract_vocals import get_vocalsimport librosaduration = librosa.get_duration(path=audio_guide)@@ -5550,11 +5567,11 @@ def generate_video(audio_guide = get_vocals(original_audio_guide, get_available_filename(save_path, audio_guide, "_clean", ".wav"))temp_filenames_list += [audio_guide]- if model_def.get("audio_scale_name", None) is None:- output_new_audio_filepath = original_audio_guide+ output_new_audio_filepath = original_audio_guidecurrent_video_length = min(int(fps * duration //latent_size) * latent_size + latent_size + 1, current_video_length)if fantasy:+ from models.wan.fantasytalking.infer import parse_audio# audio_proj_split_full, audio_context_lens_full = parse_audio(audio_guide, num_frames= max_source_video_frames, fps= fps, padded_frames_for_embeddings= (reuse_frames if reset_control_aligment else 0), device= processing_device )if audio_scale is None:audio_scale = 1.0@@ -5631,6 +5648,7 @@ def generate_video(gen["extra_windows"] = 0gen["total_windows"] = 1gen["window_no"] = 1+ input_waveform, input_waveform_sample_rate = None, 0num_frames_generated = 0 # num of new frames created (lower than the number of frames really processed due to overlaps and discards)requested_frames_to_generate = default_requested_frames_to_generate # num of num frames to create (if any source window this num includes also the overlapped source window frames)cached_video_guide_processed = cached_video_mask_processed = cached_video_guide_processed2 = cached_video_mask_processed2 = None@@ -5708,21 +5726,11 @@ def generate_video(aligned_guide_start_frame = guide_start_frame - alignment_shiftaligned_guide_end_frame = guide_end_frame - alignment_shiftaligned_window_start_frame = window_start_frame - alignment_shift- audio_guide_window = audio_guide- if sliding_window and audio_guide is not None and model_def.get("audio_guide_window_slicing", False):+ if audio_guide is not None and model_def.get("audio_guide_window_slicing", False):audio_start_frame = aligned_window_start_frameif reset_control_aligment:audio_start_frame += source_video_overlap_frames_count- audio_guide_window = slice_audio_window(- audio_guide,- audio_start_frame,- current_video_length,- fps,- save_path,- suffix=f"_win{window_no}",- )- if audio_guide_window != audio_guide:- temp_filenames_list.append(audio_guide_window)+ input_waveform, input_waveform_sample_rate = slice_audio_window( audio_guide, audio_start_frame, current_video_length, fps, save_path, suffix=f"_win{window_no}", )if fantasy and audio_guide is not None:audio_proj_split , audio_context_lens = parse_audio(audio_guide, start_frame = aligned_window_start_frame, num_frames= current_video_length, fps= fps, device= processing_device )if multitalk:@@ -6020,7 +6028,9 @@ def generate_video(cfg_zero_step = cfg_zero_step,alt_guide_scale= alt_guidance_scale,audio_cfg_scale= audio_guidance_scale,- audio_guide=audio_guide_window,+ input_waveform=input_waveform,+ input_waveform_sample_rate=input_waveform_sample_rate,+ audio_guide=audio_guide,audio_guide2=audio_guide2,audio_proj= audio_proj_split,audio_scale= audio_scale,@@ -6116,19 +6126,17 @@ def generate_video(overlapped_latents = samples.get("latent_slice", None)BGRA_frames = samples.get("BGRA_frames", None)generated_audio = samples.get("audio", generated_audio)- output_audio_sampling_rate = samples.get("audio_sampling_rate", audio_sampling_rate)+ if generated_audio is not None and model_def.get("output_audio_is_input_audio", False) and output_new_audio_filepath is not None:+ generated_audio = None+ else:+ output_new_audio_filepath = None+ output_audio_sampling_rate = samples.get("audio_sampling_rate", audio_sampling_rate)post_decode_pre_trim = samples.get("post_decode_pre_trim", 0)samples = samples.get("x", None)if samples is not None:samples = samples.to("cpu")- if (- output_new_audio_filepath is None- and generated_audio is None- and original_audio_guide is not None- and model_def.get("audio_guide_window_slicing", False)- ):- output_new_audio_filepath = original_audio_guide+clear_gen_cache()offloadobj.unload_all()gc.collect()@@ -6161,13 +6169,7 @@ def generate_video(sample = sample[: , :-discard_last_frames]guide_start_frame -= discard_last_framesif generated_audio is not None:- generated_audio = truncate_audio(- generated_audio,- 0,- discard_last_frames,- fps,- output_audio_sampling_rate,- )+ generated_audio = truncate_audio( generated_audio, 0, discard_last_frames, fps, output_audio_sampling_rate,)if reuse_frames == 0:pre_video_guide = sample[:,max_source_video_frames :].clone()@@ -6184,25 +6186,13 @@ def generate_video(sample = torch.cat([ prefix_video[:, :-source_video_overlap_frames_count], sample], dim = 1)guide_start_frame -= source_video_overlap_frames_countif generated_audio is not None:- generated_audio = truncate_audio(- generated_audio,- source_video_overlap_frames_count,- 0,- fps,- output_audio_sampling_rate,- )+ generated_audio = truncate_audio( generated_audio, source_video_overlap_frames_count, 0, fps, output_audio_sampling_rate,)elif sliding_window and window_no > 1 and reuse_frames > 0:# remove sliding window overlapped frames at the beginning of the generationsample = sample[: , reuse_frames:]guide_start_frame -= reuse_framesif generated_audio is not None:- generated_audio = truncate_audio(- generated_audio,- reuse_frames,- 0,- fps,- output_audio_sampling_rate,- )+ generated_audio = truncate_audio( generated_audio, reuse_frames, 0, fps, output_audio_sampling_rate,)num_frames_generated = guide_start_frame - (source_video_frames_count - source_video_overlap_frames_count)if generated_audio is not None:@@ -8238,9 +8228,9 @@ def refresh_remove_background_sound(state, audio_prompt_type, remove_background_def refresh_audio_prompt_type_sources(state, audio_prompt_type, audio_prompt_type_sources):- audio_prompt_type = del_in_sequence(audio_prompt_type, "XCPAB")+ audio_prompt_type = del_in_sequence(audio_prompt_type, "XCPABK")audio_prompt_type = add_to_sequence(audio_prompt_type, audio_prompt_type_sources)- return audio_prompt_type, gr.update(visible = "A" in audio_prompt_type), gr.update(visible = "B" in audio_prompt_type), gr.update(visible = ("B" in audio_prompt_type or "X" in audio_prompt_type)), gr.update(visible= any_letters(audio_prompt_type, "ABX")), gr.update(visible= any_letters(audio_prompt_type,"AB"))+ return audio_prompt_type, gr.update(visible = "A" in audio_prompt_type), gr.update(visible = "B" in audio_prompt_type), gr.update(visible = ("B" in audio_prompt_type or "X" in audio_prompt_type)), gr.update(visible= any_letters(audio_prompt_type, "ABXK")), gr.update(visible= any_letters(audio_prompt_type,"AB"))def refresh_image_prompt_type_radio(state, image_prompt_type, image_prompt_type_radio):image_prompt_type = del_in_sequence(image_prompt_type, "VLTS")@@ -9207,11 +9197,12 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non"XA": "Two speakers, Auto Separation of Speakers (will work only if Voices are distinct)","CAB": "Two speakers, Speakers Audio sources are assumed to be played in a Row","PAB": "Two speakers, Speakers Audio sources are assumed to be played in Parallel",+ "K": "Control Video Audio Track",}if not isinstance(audio_prompt_type_sources_def, dict):has_multi_letter = "B" in audio_prompt_type_value or "X" in audio_prompt_type_valueif not any_single_speaker and "A" in audio_prompt_type_value and not has_multi_letter:- audio_prompt_type_value = del_in_sequence(audio_prompt_type_value, "XCPAB")+ audio_prompt_type_value = del_in_sequence(audio_prompt_type_value, "XCPABK")if not any_multi_speakers:audio_prompt_type_value = del_in_sequence(audio_prompt_type_value, "XCPB")selection = [""]@@ -9229,11 +9220,11 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonaudio_prompt_type_sources_choices.append((label, choice))if len(audio_prompt_type_sources_choices) == 0:audio_prompt_type_sources_choices = [(audio_prompt_type_sources_labels_all[""], "")]- letters_filter = audio_prompt_type_sources_def.get("letters_filter", "XCPAB")+ letters_filter = audio_prompt_type_sources_def.get("letters_filter", "XCPABK")default_choice = audio_prompt_type_sources_def.get("default", "")audio_prompt_type_sources_value = filter_letters(audio_prompt_type_value, letters_filter, default_choice)audio_prompt_type_sources_value = get_default_value(audio_prompt_type_sources_choices, audio_prompt_type_sources_value, default_choice)- audio_prompt_type_value = del_in_sequence(audio_prompt_type_value, "XCPAB")+ audio_prompt_type_value = del_in_sequence(audio_prompt_type_value, "XCPABK")audio_prompt_type_value = add_to_sequence(audio_prompt_type_value, audio_prompt_type_sources_value)sources_visible = model_def.get("audio_prompt_choices") is not None and not image_outputs and audio_prompt_type_sources_def.get("visible", True)audio_prompt_type_sources = gr.Dropdown(@@ -9261,7 +9252,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Noncustom_guide = gr.File(value= None, type="filepath", label= "Custom Guide", height=41, visible= False )else:custom_guide = gr.File(value= ui_defaults.get("custom_guide", None), type="filepath", label= custom_guide_def.get("label","Custom Guide"), height=41, visible= True, file_types = custom_guide_def.get("file_types", ["*.*"]) )- remove_background_sound = gr.Checkbox(label= "Remove Background Music" if audio_only else "Video Motion ignores Background Music (to get a better LipSync)", value="V" in audio_prompt_type_value, visible = any_audio_prompt and any_letters(audio_prompt_type_value, "ABX") and not image_outputs)+ remove_background_sound = gr.Checkbox(label= "Remove Background Music" if audio_only else "Video Motion ignores Background Music (to get a better LipSync)", value="V" in audio_prompt_type_value, visible = any_audio_prompt and any_letters(audio_prompt_type_value, "ABXK") and not image_outputs)with gr.Row(visible = any_audio_prompt and ("B" in audio_prompt_type_value or "X" in audio_prompt_type_value) and not image_outputs ) as speakers_locations_row:speakers_locations = gr.Text( ui_get("speakers_locations"), label="Speakers Locations separated by a Space. Each Location = Left:Right or a BBox Left:Top:Right:Bottom", visible= True)