Skip to content
Python

added flux nag

DeepBeepMeepdb57670553c9
diff --git a/README.md b/README.md
index c22c658..1197d30 100644
--- a/README.md
+++ b/README.md
@@ -5,7 +5,7 @@
<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, Flux, Qwen, Z-Image, LongCat, Kandinsky and LTX Video models with:
+WanGP supports the Wan (and derived models) but also Hunyuan Video, Flux, Qwen, Z-Image, LongCat, Kandinsky, LTX 1 & 2, Qwen3 TTS, Chatterbox, HearMula, ... 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.
@@ -17,9 +17,9 @@ WanGP supports the Wan (and derived models), Hunyuan Video, Flux, Qwen, Z-Image,
- 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
+- Headless mode: launch the generation of multiple image / videos / audio files using a command line
-**Discord Server to get Help from Other Users and show your Best Videos:** https://discord.gg/g7efUW9jGV
+**Discord Server to get Help from the WanGP Community and show your Best Gens:** https://discord.gg/g7efUW9jGV
**Follow DeepBeepMeep on Twitter/X to get the Latest News**: https://x.com/deepbeepmeep
diff --git a/defaults/flux2_dev.json b/defaults/flux2_dev.json
index b3976f5..a3b1b1e 100644
--- a/defaults/flux2_dev.json
+++ b/defaults/flux2_dev.json
@@ -6,9 +6,7 @@
"URLs": [
"https://huggingface.co/DeepBeepMeep/Flux2/resolve/main/flux2-dev.safetensors",
"https://huggingface.co/DeepBeepMeep/Flux2/resolve/main/flux2-dev_quanto_bf16_int8.safetensors"
- ],
- "image_outputs": true,
- "no_negative_prompt": true
+ ]
},
"prompt": "draw a hat on top of a hat inside a hat",
"resolution": "1024x1024",
diff --git a/defaults/flux2_klein_4b.json b/defaults/flux2_klein_4b.json
index fb78f1c..55d38aa 100644
--- a/defaults/flux2_klein_4b.json
+++ b/defaults/flux2_klein_4b.json
@@ -6,9 +6,7 @@
"URLs": [
"https://huggingface.co/DeepBeepMeep/Flux2/resolve/main/flux-2-klein-4b.safetensors",
"https://huggingface.co/DeepBeepMeep/Flux2/resolve/main/flux-2-klein-4b_quanto_bf16_int8.safetensors"
- ],
- "image_outputs": true,
- "no_negative_prompt": true
+ ]
},
"prompt": "a cozy reading nook with warm sunlight, soft textiles, and a cup of tea on a wooden side table",
"resolution": "1024x1024",
diff --git a/defaults/flux2_klein_9b.json b/defaults/flux2_klein_9b.json
index 877f2f8..4295d95 100644
--- a/defaults/flux2_klein_9b.json
+++ b/defaults/flux2_klein_9b.json
@@ -6,9 +6,7 @@
"URLs": [
"https://huggingface.co/DeepBeepMeep/Flux2/resolve/main/flux-2-klein-9b.safetensors",
"https://huggingface.co/DeepBeepMeep/Flux2/resolve/main/flux-2-klein-9b_quanto_bf16_int8.safetensors"
- ],
- "image_outputs": true,
- "no_negative_prompt": true
+ ]
},
"prompt": "a glass greenhouse filled with lush tropical plants, misty air, and dappled light",
"resolution": "1024x1024",
diff --git a/defaults/qwen3_tts_customvoice.json b/defaults/qwen3_tts_customvoice.json
index c161528..e9d73dc 100644
--- a/defaults/qwen3_tts_customvoice.json
+++ b/defaults/qwen3_tts_customvoice.json
@@ -1,8 +1,8 @@
{
"model": {
- "name": "TTS Qwen3 CustomVoice(12Hz) 1.7B",
+ "name": "TTS Qwen3 Custom Voice (12Hz) 1.7B",
"architecture": "qwen3_tts_customvoice",
- "description": "Qwen3 CustomVoice with fixed speaker presets and optional instruction control.",
+ "description": "Qwen3 Custom Voice with fixed speaker presets and optional instruction control.",
"URLs": [
"https://huggingface.co/DeepBeepMeep/TTS/resolve/main/qwen3_tts_12hz_1b7_customvoice_bf16.safetensors"
]
diff --git a/defaults/qwen3_tts_voicedesign.json b/defaults/qwen3_tts_voicedesign.json
index 45f6ef3..851485f 100644
--- a/defaults/qwen3_tts_voicedesign.json
+++ b/defaults/qwen3_tts_voicedesign.json
@@ -1,8 +1,8 @@
{
"model": {
- "name": "TTS Qwen3 VoiceDesign (12Hz) 1.7B",
+ "name": "TTS Qwen3 Voice Design (12Hz) 1.7B",
"architecture": "qwen3_tts_voicedesign",
- "description": "Qwen3 VoiceDesign with natural language voice instructions.",
+ "description": "Qwen3 Voice Design with natural language voice instructions.",
"URLs": [
"https://huggingface.co/DeepBeepMeep/TTS/resolve/main/qwen3_tts_12hz_1b7_voicedesign_bf16.safetensors"
]
diff --git a/models/TTS/__init__.py b/models/TTS/__init__.py
index 11fb3fe..64141c8 100644
--- a/models/TTS/__init__.py
+++ b/models/TTS/__init__.py
@@ -1 +1 @@
-from .tts_handler import family_handler
+from . import chatterbox_handler, heartmula_handler, qwen3_handler, yue_handler
diff --git a/models/TTS/qwen3/defs.py b/models/TTS/qwen3/defs.py
deleted file mode 100644
index 6f36459..0000000
--- a/models/TTS/qwen3/defs.py
+++ /dev/null
@@ -1,277 +0,0 @@
-from __future__ import annotations
-
-import json
-from pathlib import Path
-from typing import Optional
-
-
-QWEN3_TTS_VARIANTS = {
- "qwen3_tts_customvoice": {
- "repo": "Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice",
- "config_file": "qwen3_tts_customvoice.json",
- },
- "qwen3_tts_voicedesign": {
- "repo": "Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign",
- "config_file": "qwen3_tts_voicedesign.json",
- },
- "qwen3_tts_base": {
- "repo": "Qwen/Qwen3-TTS-12Hz-1.7B-Base",
- "config_file": "qwen3_tts_base.json",
- },
-}
-
-QWEN3_TTS_GENERATION_CONFIG = "qwen3_tts_generation_config.json"
-_QWEN3_CONFIG_DIR = Path(__file__).resolve().parent / "configs"
-
-QWEN3_TTS_TEXT_TOKENIZER_DIR = "qwen3_tts_text_tokenizer"
-QWEN3_TTS_SPEECH_TOKENIZER_DIR = "qwen3_tts_tokenizer_12hz"
-QWEN3_TTS_SPEECH_TOKENIZER_WEIGHTS = "qwen3_tts_tokenizer_12hz.safetensors"
-QWEN3_TTS_REPO = "DeepBeepMeep/TTS"
-QWEN3_TTS_TEXT_TOKENIZER_FILES = [
- "merges.txt",
- "vocab.json",
- "tokenizer_config.json",
- "preprocessor_config.json",
-]
-QWEN3_TTS_SPEECH_TOKENIZER_FILES = [
- "config.json",
- "configuration.json",
- "preprocessor_config.json",
- QWEN3_TTS_SPEECH_TOKENIZER_WEIGHTS,
-]
-
-QWEN3_TTS_LANG_FALLBACK = [
- "auto",
- "chinese",
- "english",
- "japanese",
- "korean",
- "german",
- "french",
- "russian",
- "portuguese",
- "spanish",
- "italian",
-]
-QWEN3_TTS_SPEAKER_FALLBACK = [
- "serena",
- "vivian",
- "uncle_fu",
- "ryan",
- "aiden",
- "ono_anna",
- "sohee",
- "eric",
- "dylan",
-]
-QWEN3_TTS_SPEAKER_META = {
- "vivian": {
- "style": "Bright, slightly edgy young female voice",
- "language": "Chinese",
- },
- "serena": {
- "style": "Warm, gentle young female voice",
- "language": "Chinese",
- },
- "uncle_fu": {
- "style": "Seasoned male voice with a low, mellow timbre",
- "language": "Chinese",
- },
- "dylan": {
- "style": "Youthful Beijing male voice with a clear, natural timbre",
- "language": "Chinese (Beijing Dialect)",
- },
- "eric": {
- "style": "Lively Chengdu male voice with a slightly husky brightness",
- "language": "Chinese (Sichuan Dialect)",
- },
- "ryan": {
- "style": "Dynamic male voice with strong rhythmic drive",
- "language": "English",
- },
- "aiden": {
- "style": "Sunny American male voice with a clear midrange",
- "language": "English",
- },
- "ono_anna": {
- "style": "Playful Japanese female voice with a light, nimble timbre",
- "language": "Japanese",
- },
- "sohee": {
- "style": "Warm Korean female voice with rich emotion",
- "language": "Korean",
- },
-}
-TTS_MONOLOGUE_PROMPT = (
- "You are a speechwriting assistant. Generate a single-speaker monologue "
- "for a text-to-speech model based on the user prompt. Output only the "
- "monologue text. Do not include explanations, bullet lists, or stage "
- "directions. Keep a consistent tone and point of view. Use natural, "
- "spoken sentences with clear punctuation for pauses. Aim for a short "
- "monologue (4-8 sentences) unless the prompt asks for a different length.\n\n"
- "Example:\n"
- "I never thought a small town would teach me so much about patience. "
- "Every morning the same faces pass the bakery window, and I know their "
- "stories without a word. The bell over the door rings, the coffee steams, "
- "and time slows down just enough to breathe. Some days I miss the noise of "
- "the city, but most days I am grateful for the quiet. It lets me hear "
- "myself think, and that has become its own kind of music."
-)
-QWEN3_TTS_DURATION_SLIDER = {
- "label": "Max duration (seconds)",
- "min": 1,
- "max": 240,
- "increment": 1,
- "default": 20,
-}
-
-
-def _format_qwen3_label(value: str) -> str:
- return value.replace("_", " ").title()
-
-def _format_qwen3_speaker_label(name: str) -> str:
- label = _format_qwen3_label(name)
- meta = QWEN3_TTS_SPEAKER_META.get(name.lower())
- if not meta:
- return label
- parts = []
- style = meta.get("style", "")
- language = meta.get("language", "")
- if style:
- parts.append(style)
- if language:
- parts.append(language)
- if not parts:
- return label
- return f"{label} ({'; '.join(parts)})"
-
-
-def get_qwen3_config_path(base_model_type: str) -> Optional[str]:
- variant = QWEN3_TTS_VARIANTS.get(base_model_type)
- if variant is None:
- return None
- config_path = _QWEN3_CONFIG_DIR / variant["config_file"]
- return str(config_path) if config_path.is_file() else None
-
-
-def get_qwen3_generation_config_path() -> Optional[str]:
- config_path = _QWEN3_CONFIG_DIR / QWEN3_TTS_GENERATION_CONFIG
- return str(config_path) if config_path.is_file() else None
-
-
-def load_qwen3_config(base_model_type: str) -> Optional[dict]:
- config_path = get_qwen3_config_path(base_model_type)
- if not config_path:
- return None
- with open(config_path, "r", encoding="utf-8") as handle:
- return json.load(handle)
-
-
-def get_qwen3_languages(base_model_type: str) -> list[str]:
- config = load_qwen3_config(base_model_type)
- if config is None:
- return list(QWEN3_TTS_LANG_FALLBACK)
- lang_map = config.get("talker_config", {}).get("codec_language_id", {})
- languages = [name for name in lang_map.keys() if "dialect" not in name.lower()]
- languages = ["auto"] + sorted({name.lower() for name in languages})
- return languages
-
-
-def get_qwen3_speakers(base_model_type: str) -> list[str]:
- config = load_qwen3_config(base_model_type)
- if config is None:
- return list(QWEN3_TTS_SPEAKER_FALLBACK)
- speakers = list(config.get("talker_config", {}).get("spk_id", {}).keys())
- speakers = sorted({name.lower() for name in speakers})
- return speakers or list(QWEN3_TTS_SPEAKER_FALLBACK)
-
-
-def get_qwen3_language_choices(base_model_type: str) -> list[tuple[str, str]]:
- return [(_format_qwen3_label(lang), lang) for lang in get_qwen3_languages(base_model_type)]
-
-
-def get_qwen3_speaker_choices(base_model_type: str) -> list[tuple[str, str]]:
- return [(_format_qwen3_speaker_label(name), name) for name in get_qwen3_speakers(base_model_type)]
-
-
-def get_qwen3_model_def(base_model_type: str) -> dict:
- common = {
- "audio_only": True,
- "image_outputs": False,
- "sliding_window": False,
- "guidance_max_phases": 0,
- "no_negative_prompt": True,
- "image_prompt_types_allowed": "",
- "supports_early_stop": True,
- "profiles_dir": [base_model_type],
- "duration_slider": dict(QWEN3_TTS_DURATION_SLIDER),
- "top_k_slider": True,
- "text_prompt_enhancer_instructions": TTS_MONOLOGUE_PROMPT,
- "compile": False,
- }
- if base_model_type == "qwen3_tts_customvoice":
- speakers = get_qwen3_speakers(base_model_type)
- default_speaker = speakers[0] if speakers else ""
- return {
- **common,
- "model_modes": {
- "choices": get_qwen3_speaker_choices(base_model_type),
- "default": default_speaker,
- "label": "Speaker",
- },
- "alt_prompt": {
- "label": "Instruction (optional)",
- "placeholder": "calm, friendly, slightly husky",
- "lines": 2,
- },
- }
- if base_model_type == "qwen3_tts_voicedesign":
- return {
- **common,
- "model_modes": {
- "choices": get_qwen3_language_choices(base_model_type),
- "default": "auto",
- "label": "Language",
- },
- "alt_prompt": {
- "label": "Voice instruction",
- "placeholder": "young female, warm tone, clear articulation",
- "lines": 2,
- },
- }
- if base_model_type == "qwen3_tts_base":
- return {
- **common,
- "model_modes": {
- "choices": get_qwen3_language_choices(base_model_type),
- "default": "auto",
- "label": "Language",
- },
- "alt_prompt": {
- "label": "Reference transcript (optional)",
- "placeholder": "Okay. Yeah. I respect you, but you blew it.",
- "lines": 3,
- },
- "any_audio_prompt": True,
- "audio_guide_label": "Reference voice",
- }
- return common
-
-
-def get_qwen3_duration_default() -> int:
- return int(QWEN3_TTS_DURATION_SLIDER.get("default", 20))
-
-
-def get_qwen3_download_def(base_model_type: str) -> list[dict]:
- return [
- {
- "repoId": QWEN3_TTS_REPO,
- "sourceFolderList": [QWEN3_TTS_TEXT_TOKENIZER_DIR],
- "fileList": [QWEN3_TTS_TEXT_TOKENIZER_FILES],
- },
- {
- "repoId": QWEN3_TTS_REPO,
- "sourceFolderList": [QWEN3_TTS_SPEECH_TOKENIZER_DIR],
- "fileList": [QWEN3_TTS_SPEECH_TOKENIZER_FILES],
- },
- ]
diff --git a/models/TTS/qwen3/pipeline.py b/models/TTS/qwen3/pipeline.py
index 2eac6ac..a5e6803 100644
--- a/models/TTS/qwen3/pipeline.py
+++ b/models/TTS/qwen3/pipeline.py
@@ -18,7 +18,7 @@ from transformers.generation import StoppingCriteria, StoppingCriteriaList
from mmgp import offload
from shared.utils import files_locator as fl
-from . import defs as qwen3_defs
+from .. import qwen3_handler as qwen3_defs
from .core.models.configuration_qwen3_tts import Qwen3TTSConfig
from .core.models.modeling_qwen3_tts import Qwen3TTSForConditionalGeneration
from .core.models.processing_qwen3_tts import Qwen3TTSProcessor
diff --git a/models/TTS/tts_handler.py b/models/TTS/tts_handler.py
deleted file mode 100644
index b21f387..0000000
--- a/models/TTS/tts_handler.py
+++ /dev/null
@@ -1,687 +0,0 @@
-import os
-
-import gradio as gr
-import torch
-
-from shared.utils import files_locator as fl
-from .qwen3 import defs as qwen3_defs
-
-
-_FALLBACK_SUPPORTED_LANGUAGES = {
- "ar": "Arabic",
- "da": "Danish",
- "de": "German",
- "el": "Greek",
- "en": "English",
- "es": "Spanish",
- "fi": "Finnish",
- "fr": "French",
- "he": "Hebrew",
- "hi": "Hindi",
- "it": "Italian",
- "ja": "Japanese",
- "ko": "Korean",
- "ms": "Malay",
- "nl": "Dutch",
- "no": "Norwegian",
- "pl": "Polish",
- "pt": "Portuguese",
- "ru": "Russian",
- "sv": "Swedish",
- "sw": "Swahili",
- "tr": "Turkish",
- "zh": "Chinese",
-}
-
-
-def _get_supported_languages() -> dict:
- try:
- from .chatterbox.mtl_tts import SUPPORTED_LANGUAGES
- except Exception:
- return _FALLBACK_SUPPORTED_LANGUAGES
- return SUPPORTED_LANGUAGES
-
-
-def _get_language_choices() -> list[tuple[str, str]]:
- languages = _get_supported_languages()
- return [
- (f"{name} ({code})", code)
- for code, name in sorted(languages.items(), key=lambda item: item[1])
- ]
-
-HEARTMULA_VERSION = "3B"
-
-YUE_STAGE1_COT_REPO = "m-a-p/YuE-s1-7B-anneal-en-cot"
-YUE_STAGE1_ICL_REPO = "m-a-p/YuE-s1-7B-anneal-en-icl"
-YUE_STAGE2_REPO = "m-a-p/YuE-s2-1B-general"
-YUE_STAGE1_FILES = [
- "config.json",
-]
-YUE_STAGE2_FILES = [
- "config.json",
-]
-
-
-def _get_heartmula_local_config_path() -> str:
- return os.path.join(
- os.path.dirname(__file__),
- "HeartMula",
- "config",
- f"heartmula_{HEARTMULA_VERSION}.json",
- )
-
-
-def _get_chatterbox_model_def():
- return {
- "audio_only": True,
- "image_outputs": False,
- "sliding_window": False,
- "guidance_max_phases": 0,
- "no_negative_prompt": True,
- "image_prompt_types_allowed": "",
- "profiles_dir": ["chatterbox"],
- "audio_guide_label": "Voice to Replicate",
- "model_modes": {
- "choices": _get_language_choices(),
- "default": "en",
- "label": "Language",
- },
- "any_audio_prompt": True,
- "chatterbox_controls": True,
- "text_prompt_enhancer_instructions": qwen3_defs.TTS_MONOLOGUE_PROMPT,
- }
-
-
-def _get_heartmula_model_def():
- return {
- "audio_only": True,
- "image_outputs": False,
- "sliding_window": False,
- "guidance_max_phases": 1,
- "no_negative_prompt": True,
- "image_prompt_types_allowed": "",
- "supports_early_stop": True,
- "profiles_dir": ["heartmula_oss_3b"],
- "alt_prompt": {
- "label": "Keywords / Tags",
- "placeholder": "piano,happy,wedding",
- "lines": 2,
- },
- "text_prompt_enhancer_instructions": (
- "You are a lyric-writing assistant. Generate a clean song lyric prompt "
- "for a text-to-song model. Output only the lyric text with optional "
- "section headers in square brackets (e.g., [Verse], [Chorus], [Bridge], "
- "[Intro], [Outro]). Do not include explanations, bullet lists, or tags. "
- "Keep a consistent theme, POV, and rhyme or rhythm where natural. Use "
- "short lines that are easy to sing.\n\n"
- "Example:\n"
- "[Verse]\n"
- "Morning light through the window pane\n"
- "I hum a tune to chase the rain\n"
- "Steady steps on a quiet street\n"
- "Heart and rhythm, gentle beat\n"
- ),
- "duration_slider": {
- "label": "Duration of the Song (in seconds)",
- "min": 30,
- "max": 240,
- "increment": 0.1,
- "default": 120,
- },
- "top_k_slider": True,
- "heartmula_cfg_scale": 1.5,
- "heartmula_topk": 50,
- "heartmula_max_audio_length_ms": 120000,
- "heartmula_codec_guidance_scale": 1.25,
- "heartmula_codec_steps": 10,
- "heartmula_codec_version": "",
- "compile": False, #["transformer", "transformer2"]
- }
-
-
-def _get_yue_model_def(model_def):
- use_audio_prompt = bool(model_def.get("yue_audio_prompt", False))
- yue_def = {
- "audio_only": True,
- "image_outputs": False,
- "sliding_window": False,
- "guidance_max_phases": 0,
- "no_negative_prompt": True,
- "image_prompt_types_allowed": "",
- "profiles_dir": ["yue"],
- "alt_prompt": {
- "label": "Genres / Tags",
- "placeholder": "pop, dreamy, warm vocal, female, nostalgic",
- "lines": 2,
- },
- "yue_max_new_tokens": 3000,
- "yue_run_n_segments": 2,
- "yue_stage2_batch_size": 4,
- "yue_segment_duration": 6,
- "yue_prompt_start_time": 0.0,
- "yue_prompt_end_time": 30.0,
- }
- if use_audio_prompt:
- yue_def.update(
- {
- "any_audio_prompt": True,
- "audio_prompt_choices": True,
- "audio_guide_label": "Vocal prompt",
- "audio_guide2_label": "Instrumental prompt",
- "audio_prompt_type_sources": {
- "selection": ["", "A", "AB"],
- "labels": {
- "": "Lyrics only",
- "A": "Mixed audio prompt",
- "AB": "Vocal + Instrumental prompts",
- },
- "letters_filter": "AB",
- "default": "",
- },
- }
- )
- return yue_def
-
-
-def _get_chatterbox_download_def():
- mandatory_files = [
- "ve.safetensors",
- "t3_mtl23ls_v2.safetensors",
- "s3gen.pt",
- "grapheme_mtl_merged_expanded_v1.json",
- "conds.pt",
- "Cangjie5_TC.json",
- ]
- return {
- "repoId": "ResembleAI/chatterbox",
- "sourceFolderList": [""],
- "targetFolderList": ["chatterbox"],
- "fileList": [mandatory_files],
- }
-
-
-def _get_heartmula_download_def(model_def):
- codec_version = (model_def or {}).get("heartmula_codec_version", "")
- codec_suffix = f"_{codec_version}" if codec_version else ""
- repo_id = "DeepBeepMeep/TTS"
- gen_files = [
- "gen_config.json",
- "tokenizer.json",
- f"codec_config{codec_suffix}.json",
- f"HeartMula_codec{codec_suffix}.safetensors",
- ]
- return [
- {
- "repoId": repo_id,
- "sourceFolderList": ["HeartMula"],
- "fileList": [gen_files],
- },
- ]
-
-
-def _get_yue_download_def(model_def):
- use_audio_prompt = bool(model_def.get("yue_audio_prompt", False))
- stage1_repo = YUE_STAGE1_ICL_REPO if use_audio_prompt else YUE_STAGE1_COT_REPO
- stage1_folder = os.path.basename(stage1_repo)
- stage2_folder = os.path.basename(YUE_STAGE2_REPO)
- xcodec_root = "xcodec_mini_infer"
- xcodec_source_folders = [
- "final_ckpt",
- "decoders",
- "models",
- "modules",
- "quantization",
- "RepCodec",
- "descriptaudiocodec",
- "vocos",
- "semantic_ckpts/hf_1_325000",
- ]
- xcodec_files = [
- ["config.yaml", "ckpt_00360000.pth"],
- ["config.yaml", "decoder_131000.pth", "decoder_151000.pth"],
- [],
- [],
- [],
- [],
- [],
- [],
- [],
- ]
- return [
- {
- "repoId": stage1_repo,
- "sourceFolderList": [""],
- "targetFolderList": [stage1_folder],
- "fileList": [YUE_STAGE1_FILES],
- },
- {
- "repoId": YUE_STAGE2_REPO,
- "sourceFolderList": [""],
- "targetFolderList": [stage2_folder],
- "fileList": [YUE_STAGE2_FILES],
- },
- {
- "repoId": stage1_repo,
- "sourceFolderList": [""],
- "targetFolderList": ["mm_tokenizer_v0.2_hf"],
- "fileList": [["tokenizer.model"]],
- },
- {
- "repoId": "m-a-p/xcodec_mini_infer",
- "sourceFolderList": [""],
- "targetFolderList": [xcodec_root],
- "fileList": [["vocoder.py", "post_process_audio.py"]],
- },
- {
- "repoId": "m-a-p/xcodec_mini_infer",
- "sourceFolderList": xcodec_source_folders,
- "targetFolderList": [xcodec_root] * len(xcodec_source_folders),
- "fileList": xcodec_files,
- },
- ]
-
-
-class family_handler:
- @staticmethod
- def query_supported_types():
- return [
- "chatterbox",
- "heartmula_oss_3b",
- "yue",
- *list(qwen3_defs.QWEN3_TTS_VARIANTS),
- ]
-
- @staticmethod
- def query_family_maps():
- return {}, {}
-
- @staticmethod
- def query_model_family():
- return "tts"
-
- @staticmethod
- def query_family_infos():
- return {"tts": (200, "TTS")}
-
- @staticmethod
- def register_lora_cli_args(parser, lora_root):
- parser.add_argument(
- "--lora-dir-tts",
- type=str,
- default=None,
- help=f"Path to a directory that contains TTS settings (default: {os.path.join(lora_root, 'tts')})",
- )
-
- @staticmethod
- def get_lora_dir(base_model_type, args, lora_root):
- return getattr(args, "lora_dir_tts", None) or os.path.join(lora_root, "tts")
-
- @staticmethod
- def query_model_def(base_model_type, model_def):
- if base_model_type == "heartmula_oss_3b":
- return _get_heartmula_model_def()
- if base_model_type == "yue":
- return _get_yue_model_def(model_def)
- if base_model_type in qwen3_defs.QWEN3_TTS_VARIANTS:
- return qwen3_defs.get_qwen3_model_def(base_model_type)
- return _get_chatterbox_model_def()
-
- @staticmethod
- def query_model_files(computeList, base_model_type, model_def=None):
- if base_model_type == "heartmula_oss_3b":
- return _get_heartmula_download_def(model_def or {})
- if base_model_type == "yue":
- return _get_yue_download_def(model_def or {})
- if base_model_type in qwen3_defs.QWEN3_TTS_VARIANTS:
- return qwen3_defs.get_qwen3_download_def(base_model_type)
- return _get_chatterbox_download_def()
-
- @staticmethod
- def load_model(
- model_filename,
- model_type,
- base_model_type,
- model_def,
- quantizeTransformer=False,
- text_encoder_quantization=None,
- dtype=None,
- VAE_dtype=None,
- mixed_precision_transformer=False,
- save_quantized=False,
- submodel_no_list=None,
- text_encoder_filename=None,
- profile = 0,
- **kwargs,
- ):
- ckpt_root = fl.get_download_location()
- if base_model_type == "heartmula_oss_3b":
- from .HeartMula.pipeline import HeartMuLaPipeline
-
- weights_candidate = None
- if isinstance(model_filename, (list, tuple)):
- if len(model_filename) > 0:
- weights_candidate = model_filename[0]
- else:
- weights_candidate = model_filename
- heartmula_weights_path = None
- if weights_candidate:
- heartmula_weights_path = fl.locate_file(
- weights_candidate, error_if_none=False
- )
- if heartmula_weights_path is None:
- heartmula_weights_path = weights_candidate
- pipeline = HeartMuLaPipeline(
- ckpt_root=ckpt_root,
- device=torch.device("cpu"),
- version=HEARTMULA_VERSION,
- VAE_dtype = VAE_dtype,
- heartmula_weights_path=heartmula_weights_path,
- cfg_scale=model_def.get("heartmula_cfg_scale", 1.5),
- topk=model_def.get("heartmula_topk", 50),
- max_audio_length_ms=model_def.get("heartmula_max_audio_length_ms", 120000),
- codec_steps=model_def.get("heartmula_codec_steps", 10),
- codec_guidance_scale=model_def.get(
- "heartmula_codec_guidance_scale", 1.25
- ),
- codec_version=model_def.get("heartmula_codec_version", ""),
- )
-
- pipeline.mula.decoder[0].layers._compile_me = False
- pipeline.mula.backbone.layers._compile_me = False
- pipe = {"transformer": pipeline.mula, "transformer2": pipeline.mula.decoder[0], "codec": pipeline.codec}
- pipe = { "pipe": pipe, "coTenantsMap" : {
- "transformer": ["transformer2"],
- "transformer2": ["transformer"],
- }
- }
-
- if int(profile) in (2,4,5):
- pipe["budgets"] = { "transformer2" : 200}
-
- return pipeline, pipe
-
- if base_model_type == "yue":
- from .yue.pipeline import YuePipeline
-
- if isinstance(model_filename, list):
- stage1_weights = model_filename[0] if len(model_filename) > 0 else ""
- stage2_weights = model_filename[1] if len(model_filename) > 1 else ""
- else:
- stage1_weights = model_filename or ""
- stage2_weights = ""
-
- pipeline = YuePipeline(
- stage1_weights_path=stage1_weights,
- stage2_weights_path=stage2_weights,
- use_audio_prompt=bool(model_def.get("yue_audio_prompt", False)),
- max_new_tokens=model_def.get("yue_max_new_tokens", 200),
- run_n_segments=model_def.get("yue_run_n_segments", 1),
- stage2_batch_size=model_def.get("yue_stage2_batch_size", 10),
- segment_duration=model_def.get("yue_segment_duration", 6),
- prompt_start_time=model_def.get("yue_prompt_start_time", 0.0),
- prompt_end_time=model_def.get("yue_prompt_end_time", 30.0),
- )
-
- pipe = {
- "transformer": pipeline.model_stage1,
- "transformer2": pipeline.model_stage2,
- "codec_model": pipeline.codec_model,
- "vocoder_vocal": pipeline.vocoder_vocal,
- "vocoder_inst": pipeline.vocoder_inst,
- }
- return pipeline, pipe
-
- if base_model_type in qwen3_defs.QWEN3_TTS_VARIANTS:
- from .qwen3.pipeline import Qwen3TTSPipeline
-
- weights_candidate = None
- if isinstance(model_filename, (list, tuple)):
- if len(model_filename) > 0:
- weights_candidate = model_filename[0]
- else:
- weights_candidate = model_filename
- weights_path = None
- if weights_candidate:
- weights_path = fl.locate_file(weights_candidate, error_if_none=False)
- if weights_path is None:
- weights_path = weights_candidate
-
- pipeline = Qwen3TTSPipeline(
- model_weights_path=weights_path,
- base_model_type=base_model_type,
- ckpt_root=ckpt_root,
- device=torch.device("cpu"),
- )
-
- pipe = {"transformer": pipeline.model}
- if getattr(pipeline, "speech_tokenizer", None) is not None:
- pipe["speech_tokenizer"] = pipeline.speech_tokenizer.model
- return pipeline, pipe
-
- from .chatterbox.pipeline import ChatterboxPipeline
-
- pipeline = ChatterboxPipeline(ckpt_root=ckpt_root, device="cpu")
- pipe = {
- "ve": pipeline.model.ve,
- "s3gen": pipeline.model.s3gen,
- "t3": pipeline.model.t3,
- "conds": pipeline.model.conds,
- }
- return pipeline, pipe
-
- @staticmethod
- def fix_settings(base_model_type, settings_version, model_def, ui_defaults):
- if "alt_prompt" not in ui_defaults:
- ui_defaults["alt_prompt"] = ""
-
- if base_model_type == "heartmula_oss_3b":
- defaults = {
- "audio_prompt_type": "",
- }
- elif base_model_type == "yue":
- defaults = {
- "audio_prompt_type": "",
- }
- elif base_model_type == "qwen3_tts_customvoice":
- speakers = qwen3_defs.get_qwen3_speakers(base_model_type)
- defaults = {
- "audio_prompt_type": "",
- "model_mode": speakers[0] if speakers else "",
- }
- elif base_model_type == "qwen3_tts_voicedesign":
- defaults = {
- "audio_prompt_type": "",
- "model_mode": "auto",
- }
- elif base_model_type == "qwen3_tts_base":
- defaults = {
- "audio_prompt_type": "A",
- "model_mode": "auto",
- }
- else:
- defaults = {
- "audio_prompt_type": "A",
- "model_mode": "en",
- }
- for key, value in defaults.items():
- ui_defaults.setdefault(key, value)
- if settings_version < 2.44:
- if base_model_type == "heartmula_oss_3b":
- ui_defaults["guidance_scale"] = model_def.get("heartmula_cfg_scale", 1.5)
- ui_defaults["top_k"] = model_def.get("heartmula_topk", 50)
- elif base_model_type in qwen3_defs.QWEN3_TTS_VARIANTS:
- if model_def.get("top_k_slider", False):
- ui_defaults["top_k"] = 50
- elif base_model_type != "yue":
- ui_defaults["guidance_scale"] = 1.0
-
- @staticmethod
- def update_default_settings(base_model_type, model_def, ui_defaults):
- if base_model_type == "heartmula_oss_3b":
- duration_def = model_def.get("duration_slider", {})
- ui_defaults.update(
- {
- "audio_prompt_type": "",
- "alt_prompt": "piano,happy,wedding",
- "repeat_generation": 1,
- "duration_seconds": duration_def.get("default", 120),
- "video_length": 0,
- "num_inference_steps": 0,
- "negative_prompt": "",
- "temperature": 1.0,
- "guidance_scale": model_def.get("heartmula_cfg_scale", 1.5),
- "top_k": model_def.get("heartmula_topk", 50),
- "multi_prompts_gen_type": 2
- }
- )
- return
- if base_model_type == "yue":
- ui_defaults.update(
- {
- "audio_prompt_type": "",
- "alt_prompt": "pop, dreamy, warm vocal, female, nostalgic",
- "repeat_generation": 1,
- "video_length": 0,
- "num_inference_steps": 0,
- "negative_prompt": "",
- "temperature": 1.0,
- "multi_prompts_gen_type": 2,
- }
- )
- return
-
- if base_model_type == "qwen3_tts_customvoice":
- speakers = qwen3_defs.get_qwen3_speakers(base_model_type)
- default_speaker = speakers[0] if speakers else ""
- ui_defaults.update(
- {
- "audio_prompt_type": "",
- "model_mode": default_speaker,
- "alt_prompt": "",
- "duration_seconds": qwen3_defs.get_qwen3_duration_default(),
- "repeat_generation": 1,
- "video_length": 0,
- "num_inference_steps": 0,
- "negative_prompt": "",
- "temperature": 0.9,
- "top_k": 50,
- "multi_prompts_gen_type": 2,
- }
- )
- return
-
- if base_model_type == "qwen3_tts_voicedesign":
- ui_defaults.update(
- {
- "audio_prompt_type": "",
- "model_mode": "auto",
- "alt_prompt": "young female, warm tone, clear articulation",
- "duration_seconds": qwen3_defs.get_qwen3_duration_default(),
- "repeat_generation": 1,
- "video_length": 0,
- "num_inference_steps": 0,
- "negative_prompt": "",
- "temperature": 0.9,
- "top_k": 50,
- "multi_prompts_gen_type": 2,
- }
- )
- return
-
- if base_model_type == "qwen3_tts_base":
- ui_defaults.update(
- {
- "audio_prompt_type": "A",
- "model_mode": "auto",
- "alt_prompt": "",
- "duration_seconds": qwen3_defs.get_qwen3_duration_default(),
- "repeat_generation": 1,
- "video_length": 0,
- "num_inference_steps": 0,
- "negative_prompt": "",
- "temperature": 0.9,
- "top_k": 50,
- "multi_prompts_gen_type": 2,
- }
- )
- return
-
- ui_defaults.update(
- {
- "audio_prompt_type": "A",
- "model_mode": "en",
- "repeat_generation": 1,
- "video_length": 0,
- "num_inference_steps": 0,
- "negative_prompt": "",
- "exaggeration": 0.5,
- "temperature": 0.8,
- "pace": 0.5,
- "guidance_scale": 1.0,
- "multi_prompts_gen_type": 2,
- }
- )
-
- @staticmethod
- def validate_generative_prompt(base_model_type, model_def, inputs, one_prompt):
- if base_model_type == "heartmula_oss_3b":
- alt_prompt = inputs.get("alt_prompt", "")
- if alt_prompt is None or len(str(alt_prompt).strip()) == 0:
- return "Keywords prompt cannot be empty for HeartMuLa."
- if inputs.get("audio_guide") is not None or inputs.get("audio_guide2") is not None:
- return "HeartMuLa does not support reference audio yet."
- return None
- if base_model_type == "yue":
- if one_prompt is None or len(str(one_prompt).strip()) == 0:
- return "Lyrics prompt cannot be empty for Yue."
- alt_prompt = inputs.get("alt_prompt", "")
- if alt_prompt is None or len(str(alt_prompt).strip()) == 0:
- return "Genres prompt cannot be empty for Yue."
- audio_prompt_type = inputs.get("audio_prompt_type", "") or ""
- if model_def.get("yue_audio_prompt", False):
- if "A" in audio_prompt_type:
- if inputs.get("audio_guide") is None:
- return "You must provide a vocal or mixed audio prompt for Yue ICL."
- if "B" in audio_prompt_type and inputs.get("audio_guide2") is None:
- return "You must provide an instrumental prompt for Yue ICL."
- start_time = float(inputs.get("yue_prompt_start_time", model_def.get("yue_prompt_start_time", 0.0)))
- end_time = float(inputs.get("yue_prompt_end_time", model_def.get("yue_prompt_end_time", 30.0)))
- if start_time >= end_time:
- return "Audio prompt start time must be less than end time."
- if end_time - start_time > 30:
- return "Audio prompt duration should not exceed 30 seconds."
- elif inputs.get("audio_guide") is not None or inputs.get("audio_guide2") is not None:
- return "Select an audio prompt type for Yue ICL or clear audio prompts."
- else:
- if inputs.get("audio_guide") is not None or inputs.get("audio_guide2") is not None:
- return "Yue base model does not support audio prompts. Please use Yue ICL."
- return None
-
- if base_model_type == "qwen3_tts_customvoice":
- if one_prompt is None or len(str(one_prompt).strip()) == 0:
- return "Prompt text cannot be empty for Qwen3 CustomVoice."
- speaker = inputs.get("model_mode", "")
- if not speaker:
- return "Please select a speaker for Qwen3 CustomVoice."
- speakers = qwen3_defs.get_qwen3_speakers(base_model_type)
- if speaker.lower() not in speakers:
- return f"Unsupported speaker '{speaker}'."
- return None
-
- if base_model_type == "qwen3_tts_voicedesign":
- if one_prompt is None or len(str(one_prompt).strip()) == 0:
- return "Prompt text cannot be empty for Qwen3 VoiceDesign."
- return None
-
- if base_model_type == "qwen3_tts_base":
- if one_prompt is None or len(str(one_prompt).strip()) == 0:
- return "Prompt text cannot be empty for Qwen3 Base voice clone."
- if inputs.get("audio_guide") is None:
- return "Qwen3 Base requires a reference audio clip."
- return None
-
- if len(one_prompt) > 300:
- gr.Info(
- "It is recommended to use a prompt that has less than 300 characters,"
- " otherwise you may get unexpected results."
- )
diff --git a/models/flux/flux_handler.py b/models/flux/flux_handler.py
index 2ed270e..faae5cc 100644
--- a/models/flux/flux_handler.py
+++ b/models/flux/flux_handler.py
@@ -81,10 +81,25 @@ class family_handler():
extra_model_def = {
"image_outputs" : True,
- "no_negative_prompt" : flux2 or not (flux_chroma or flux_chroma_radiance),
+ "no_negative_prompt" : flux_chroma or flux_chroma_radiance,
"flux-model": flux_model,
"flux2": flux2,
}
+ nag_supported = base_model_type in [
+ "flux_schnell",
+ "flux_dev_kontext",
+ "flux_dev_umo",
+ "flux_dev_uso",
+ "flux_dev_kontext_dreamomni2",
+ "pi_flux2",
+ "flux2_dev",
+ "flux",
+ "flux2_klein_4b",
+ "flux2_klein_9b",
+ ]
+ if nag_supported:
+ extra_model_def["NAG"] = True
+ extra_model_def["no_negative_prompt"] = False
supports_inpaint = flux_kontext or flux_schnell or flux_dev or flux2
if supports_inpaint:
extra_model_def["inpaint_support"] = True
diff --git a/models/flux/flux_main.py b/models/flux/flux_main.py
index cf338a0..62ba93e 100644
--- a/models/flux/flux_main.py
+++ b/models/flux/flux_main.py
@@ -282,6 +282,27 @@ class model_factory:
guide_scale = 1.0
if self.guidance_max_phases < 1: guide_scale = 1
if n_prompt is None or len(n_prompt) == 0: n_prompt = "low quality, ugly, unfinished, out of focus, deformed, disfigure, blurry, smudged, restricted palette, flat colors"
+ nag_scale = bbargs.get("NAG_scale", 1.0)
+ nag_tau = bbargs.get("NAG_tau", 3.5)
+ nag_alpha = bbargs.get("NAG_alpha", 0.5)
+ NAG = None
+ if nag_scale > 1 and guide_scale <= 1:
+ NAG = {"scale": nag_scale, "tau": nag_tau, "alpha": nag_alpha, "prefix_len": 0}
+ def _align_seq_len(tensor, target_len):
+ if tensor is None:
+ return tensor
+ seq_dim = 0 if tensor.dim() == 2 else 1
+ cur_len = tensor.shape[seq_dim]
+ if cur_len == target_len:
+ return tensor
+ if cur_len < target_len:
+ pad_len = target_len - cur_len
+ if seq_dim == 0:
+ pad = tensor[-1:].repeat(pad_len, 1)
+ return torch.cat([tensor, pad], dim=0)
+ pad = tensor[:, -1:, :].repeat(1, pad_len, 1)
+ return torch.cat([tensor, pad], dim=1)
+ return tensor.narrow(seq_dim, 0, target_len)
flux_dev_uso = self.name in ['flux-dev-uso']
flux_dev_umo = self.name in ['flux-dev-umo']
radiance = self.name in ['flux-chroma-radiance']
@@ -297,6 +318,23 @@ class model_factory:
img, img_ids = batched_prc_img(randn)
encode_fn = lambda prompts: list(zip(*batched_prc_txt(self.mistral(prompts).to(torch.bfloat16))))
txt_embeds, txt_ids = self.text_encoder_cache.encode(encode_fn, [input_prompt], device=self.device)[0]
+ if NAG is not None:
+ neg_embeds, neg_ids = self.text_encoder_cache.encode(encode_fn, [n_prompt], device=self.device)[0]
+ if txt_embeds.dim() == 2:
+ txt_embeds = txt_embeds.unsqueeze(0)
+ txt_ids = txt_ids.unsqueeze(0)
+ if neg_embeds.dim() == 2:
+ neg_embeds = neg_embeds.unsqueeze(0)
+ neg_ids = neg_ids.unsqueeze(0)
+ pos_len = txt_embeds.shape[1]
+ neg_embeds = _align_seq_len(neg_embeds, pos_len)
+ neg_ids = _align_seq_len(neg_ids, pos_len)
+ txt_embeds = torch.cat([txt_embeds, neg_embeds], dim=1)
+ txt_ids = torch.cat([txt_ids, neg_ids], dim=1)
+ NAG["cap_embed_len"] = pos_len
+ if txt_embeds.dim() == 2:
+ txt_embeds = txt_embeds.unsqueeze(0)
+ txt_ids = txt_ids.unsqueeze(0)
txt_embeds, txt_ids = txt_embeds.expand(batch_size, -1, -1), txt_ids.expand(batch_size, -1, -1)
vec = torch.zeros(batch_size, 1, device=device, dtype=self.dtype)
inp = { "img": img, "img_ids": img_ids, "txt": txt_embeds.to(device), "txt_ids": txt_ids.to(device), "vec": vec }
@@ -409,7 +447,20 @@ class model_factory:
if txt.shape[0] == 1 and prompt_bs > 1:
txt = txt.repeat(prompt_bs, 1, 1)
vec = vec.repeat(prompt_bs, 1)
- txt_ids = torch.zeros(prompt_bs, txt.shape[1], 3, device=device)
+ if NAG is not None:
+ pos_len = txt.shape[1]
+ neg_list = [n_prompt] if isinstance(n_prompt, str) else n_prompt
+ neg_bs = len(neg_list) if batch_size == 1 and not isinstance(n_prompt, str) else batch_size
+ neg_contexts = self.text_encoder_cache.encode(encode_fn, neg_list, device=device)
+ neg_txt = torch.cat([ctx["txt"] for ctx in neg_contexts], dim=0)
+ if neg_txt.shape[0] == 1 and neg_bs > 1:
+ neg_txt = neg_txt.repeat(neg_bs, 1, 1)
+ neg_txt = _align_seq_len(neg_txt, pos_len)
+ if neg_txt.shape[0] == 1 and txt.shape[0] > 1:
+ neg_txt = neg_txt.repeat(txt.shape[0], 1, 1)
+ txt = torch.cat([txt, neg_txt], dim=1)
+ NAG["cap_embed_len"] = pos_len
+ txt_ids = torch.zeros(txt.shape[0], txt.shape[1], 3, device=device)
inp.update({"txt": txt.to(device), "txt_ids": txt_ids.to(device), "vec": vec.to(device)})
if guide_scale != 1:
neg_list = [n_prompt] if isinstance(n_prompt, str) else n_prompt
@@ -433,6 +484,8 @@ class model_factory:
siglip_embedding_ids = torch.zeros( siglip_embedding.shape[0], siglip_embedding.shape[1], 3 ).to(device)
inp["siglip_embedding"] = siglip_embedding
inp["siglip_embedding_ids"] = siglip_embedding_ids
+ if NAG is not None:
+ NAG["prefix_len"] = siglip_embedding.shape[1]
if radiance:
def unpack_latent(x):
@@ -460,6 +513,7 @@ class model_factory:
height=height,
width=width,
vae_scale_factor=8,
+ NAG=NAG,
)
if x==None: return None
# decode latents to pixel space
diff --git a/models/flux/math.py b/models/flux/math.py
index a249f19..0e1cdb2 100644
--- a/models/flux/math.py
+++ b/models/flux/math.py
@@ -4,18 +4,81 @@ from torch import Tensor
from shared.attention import pay_attention
-def attention(qkv_list, pe: Tensor) -> Tensor:
+def attention(qkv_list, pe: Tensor, *, txt_len: int | None = None, NAG: dict | None = None) -> Tensor:
q, k, v = qkv_list
qkv_list.clear()
- q_list = [q]
+ q_list = [q]
q = None
q = apply_rope_(q_list, pe)
- k_list = [k]
+ k_list = [k]
k = None
k = apply_rope_(k_list, pe)
- qkv_list = [q.transpose(1,2), k.transpose(1,2) ,v.transpose(1,2)]
- del q,k, v
- x = pay_attention(qkv_list).transpose(1,2)
+
+ if NAG is not None and txt_len is not None:
+ cap_len = int(NAG.get("cap_embed_len", 0) or 0)
+ prefix_len = int(NAG.get("prefix_len", 0) or 0)
+ total_len = q.shape[2]
+ img_start = txt_len
+ packed_len = txt_len - prefix_len
+ if cap_len > 0 and packed_len == (cap_len * 2) and img_start <= total_len:
+ pos_start = prefix_len
+ pos_end = pos_start + cap_len
+ neg_start = pos_end
+ neg_end = neg_start + cap_len
+ if neg_end <= txt_len:
+ # Build pos/neg sequences that share prefix + image tokens.
+ q_neg = torch.cat( (q[:, :, :prefix_len], q[:, :, neg_start:neg_end], q[:, :, img_start:]), dim=2, )
+ k_neg = torch.cat( (k[:, :, :prefix_len], k[:, :, neg_start:neg_end], k[:, :, img_start:]), dim=2, )
+ v_neg = torch.cat( (v[:, :, :prefix_len], v[:, :, neg_start:neg_end], v[:, :, img_start:]), dim=2, )
+
+ q_pos = torch.cat((q[:, :, :pos_end], q[:, :, img_start:]), dim=2)
+ k_pos = torch.cat((k[:, :, :pos_end], k[:, :, img_start:]), dim=2)
+ v_pos = torch.cat((v[:, :, :pos_end], v[:, :, img_start:]), dim=2)
+ del q, k, v
+
+ qkv_pos = [q_pos.transpose(1, 2), k_pos.transpose(1, 2), v_pos.transpose(1, 2)]
+ q_pos = k_pos = v_pos = None
+ x_pos = pay_attention(qkv_pos)
+ x_pos = x_pos.flatten(2, 3)
+
+ qkv_neg = [q_neg.transpose(1, 2), k_neg.transpose(1, 2), v_neg.transpose(1, 2)]
+ q_neg = k_neg = v_neg = None
+ x_neg = pay_attention(qkv_neg)
+ x_neg = x_neg.flatten(2, 3)
+
+ neg_slice_end = prefix_len + cap_len
+ neg_out = x_neg[:, prefix_len:neg_slice_end].clone()
+ nag_scale = NAG["scale"]
+ nag_alpha = NAG["alpha"]
+ nag_tau = NAG["tau"]
+ dtype = x_pos.dtype
+
+ x_guidance = x_neg
+ x_guidance.mul_(1 - nag_scale)
+ x_guidance.add_(x_pos, alpha=nag_scale)
+ norm_positive = torch.norm(x_pos, p=1, dim=-1, keepdim=True)
+ norm_guidance = torch.norm(x_guidance, p=1, dim=-1, keepdim=True)
+ scale = norm_guidance / norm_positive
+ torch.nan_to_num(scale, nan=10.0, posinf=10.0, neginf=10.0, out=scale)
+ factor = (1 / (norm_guidance + 1e-7) * norm_positive * nag_tau).to(x_guidance.dtype)
+ x_guidance = torch.where(scale > nag_tau, x_guidance * factor, x_guidance).to(dtype)
+ del norm_positive, norm_guidance, scale, factor
+
+ x_guidance.mul_(nag_alpha)
+ x_guidance.add_(x_pos, alpha=(1 - nag_alpha))
+ x_pos = None
+
+ prefix_pos_guidance = x_guidance[:, :pos_end]
+ img_guidance = x_guidance[:, pos_end:]
+ x_guidance = None
+
+ out = torch.cat([prefix_pos_guidance, neg_out, img_guidance], dim=1)
+ prefix_pos_guidance = neg_out = img_guidance = None
+ return out
+
+ qkv_list = [q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)]
+ del q, k, v
+ x = pay_attention(qkv_list).transpose(1, 2)
# x = torch.nn.functional.scaled_dot_product_attention(q, k, v)
x = rearrange(x, "B H L D -> B L (H D)")
diff --git a/models/flux/model.py b/models/flux/model.py
index 3157bf0..74a4f79 100644
--- a/models/flux/model.py
+++ b/models/flux/model.py
@@ -377,6 +377,7 @@ class Flux(nn.Module):
pipeline =None,
siglip_embedding = None,
siglip_embedding_ids = None,
+ NAG: dict | None = None,
) -> Tensor:
sz = len(txt_list)
@@ -430,6 +431,7 @@ class Flux(nn.Module):
txt_ids_list = [torch.cat((siglip_embedding_ids, txt_id) , dim=1) for txt_id in txt_ids_list]
pe_list = [self.pe_embedder(torch.cat((txt_ids, img_ids), dim=1)) for txt_ids in txt_ids_list]
+ txt_len = txt_list[0].shape[1] if len(txt_list) > 0 else 0
if self.is_flux2:
double_vec_list = [ ( self.double_stream_modulation_img(base_vec_list[i]), self.double_stream_modulation_txt(base_vec_list[i]), ) for i in range(sz) ]
@@ -444,7 +446,7 @@ class Flux(nn.Module):
if pipeline._interrupt:
return [None] * sz
for img, txt, pe, vec in zip(img_list, txt_list, pe_list, vec_list):
- img[...], txt[...] = block(img=img, txt=txt, vec=vec, pe=pe)
+ img[...], txt[...] = block(img=img, txt=txt, vec=vec, pe=pe, NAG=NAG)
img = txt = pe = vec= None
img_list = [torch.cat((txt, img), 1) for txt, img in zip(txt_list, img_list)]
@@ -463,7 +465,7 @@ class Flux(nn.Module):
if pipeline._interrupt:
return [None] * sz
for img, pe, vec in zip(img_list, pe_list, vec_list):
- img[...]= block(x=img, vec=vec, pe=pe)
+ img[...]= block(x=img, vec=vec, pe=pe, txt_len=txt_len, NAG=NAG)
img = pe = vec = None
img_list = [img[:, txt.shape[1] : txt.shape[1] + img_len, ...] for img, txt in zip(img_list, txt_list)]
diff --git a/models/flux/modules/layers.py b/models/flux/modules/layers.py
index c9f8a69..6884c1f 100644
--- a/models/flux/modules/layers.py
+++ b/models/flux/modules/layers.py
@@ -245,7 +245,7 @@ class DoubleStreamBlock(nn.Module):
nn.Linear(mlp_hidden_dim, hidden_size, bias=mlp_bias),
)
- def forward(self, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor) -> tuple[Tensor, Tensor]:
+ def forward(self, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor, *, NAG: dict | None = None) -> tuple[Tensor, Tensor]:
if self.shared_modulation:
(img_mod1, img_mod2), (txt_mod1, txt_mod2) = vec
else:
@@ -265,7 +265,7 @@ class DoubleStreamBlock(nn.Module):
img_q= self.img_attn.norm(img_q, None, img_v)
- img_k = self.img_attn.norm(None, img_k, img_v)
+ img_k= self.img_attn.norm(None, img_k, img_v)
# prepare txt for attention
txt_modulated = self.txt_norm1(txt)
@@ -292,7 +292,7 @@ class DoubleStreamBlock(nn.Module):
qkv_list = [q, k, v]
del q, k, v
- attn = attention(qkv_list, pe=pe)
+ attn = attention(qkv_list, pe=pe, txt_len=txt.shape[1], NAG=NAG)
txt_attn, img_attn = attn[:, : txt.shape[1]], attn[:, txt.shape[1] :]
@@ -358,7 +358,7 @@ class SingleStreamBlock(nn.Module):
else:
self.modulation = None
- def forward(self, x: Tensor, vec: Tensor, pe: Tensor) -> Tensor:
+ def forward(self, x: Tensor, vec: Tensor, pe: Tensor, *, txt_len: int | None = None, NAG: dict | None = None) -> Tensor:
if self.shared_modulation:
mod = vec
elif self.modulation is not None:
@@ -384,7 +384,7 @@ class SingleStreamBlock(nn.Module):
# compute attention
qkv_list = [q, k, v]
del q, k, v
- attn = attention(qkv_list, pe=pe)
+ attn = attention(qkv_list, pe=pe, txt_len=txt_len, NAG=NAG)
# compute activation in mlp stream, cat again and run second linear layer
x_mod_shape = x_mod.shape
diff --git a/models/flux/sampling.py b/models/flux/sampling.py
index 56bf328..0d7fc75 100644
--- a/models/flux/sampling.py
+++ b/models/flux/sampling.py
@@ -532,6 +532,7 @@ def denoise(
img_cond_seq_ids: Tensor | None = None,
siglip_embedding = None,
siglip_embedding_ids = None,
+ NAG: dict | None = None,
callback=None,
pipeline=None,
loras_slists=None,
@@ -560,6 +561,8 @@ def denoise(
"siglip_embedding": siglip_embedding,
"siglip_embedding_ids": siglip_embedding_ids,
}
+ if NAG is not None:
+ kwargs["NAG"] = NAG
if callback != None:
callback(-1, None, True)
diff --git a/wgp.py b/wgp.py
index 568bf1f..263414b 100644
--- a/wgp.py
+++ b/wgp.py
@@ -1699,7 +1699,7 @@ def update_generation_status(html_content):
if(html_content):
return gr.update(value=html_content)
-family_handlers = ["models.wan.wan_handler", "models.wan.ovi_handler", "models.wan.df_handler", "models.hyvideo.hunyuan_handler", "models.ltx_video.ltxv_handler", "models.ltx2.ltx2_handler", "models.longcat.longcat_handler", "models.flux.flux_handler", "models.qwen.qwen_handler", "models.kandinsky5.kandinsky_handler", "models.z_image.z_image_handler", "models.TTS.tts_handler"]
+family_handlers = ["models.wan.wan_handler", "models.wan.ovi_handler", "models.wan.df_handler", "models.hyvideo.hunyuan_handler", "models.ltx_video.ltxv_handler", "models.ltx2.ltx2_handler", "models.longcat.longcat_handler", "models.flux.flux_handler", "models.qwen.qwen_handler", "models.kandinsky5.kandinsky_handler", "models.z_image.z_image_handler", "models.TTS.chatterbox_handler", "models.TTS.qwen3_handler", "models.TTS.yue_handler", "models.TTS.heartmula_handler"]
DEFAULT_LORA_ROOT = "loras"
def register_family_lora_args(parser, lora_root):