| """ |
| VibeVoice LLM Surgery Module |
| ============================ |
| |
| Replace VibeVoice's Qwen2.5-1.5B decoder with Qwen3.5-4B-Base, while preserving |
| prior knowledge in the diffusion head and speech connectors via width expansion. |
| |
| Architecture changes (from -> to): |
| - LLM Decoder: Qwen2.5-1.5B -> Qwen3.5-4B-Base (text part) |
| * hidden_size: 1536 -> 2560 |
| * num_hidden_layers: 28 -> 32 |
| * vocab_size: 151936 -> 248320 |
| * attention: pure GQA -> hybrid Gated-DeltaNet + GQA (3:1) |
| - Acoustic connector output dim: 1536 -> 2560 (zero-pad expansion) |
| - Semantic connector output dim: 1536 -> 2560 (zero-pad expansion) |
| - Diffusion head hidden_size: 1536 -> 2560 (zero-pad expansion, |
| cond_proj re-initialized) |
| - Acoustic/Semantic Tokenizers: UNCHANGED (independent of LLM dim) |
| |
| Knowledge preservation strategy |
| ------------------------------- |
| For each Linear layer expanded from (in_old, out_old) to (in_new, out_new): |
| - top-left (in_old, out_old) block: copy old weights verbatim |
| - new output rows (out_old:out_new): zero-initialised -> these dims contribute |
| nothing to downstream computation |
| - new input columns (in_old:in_new): zero-initialised -> old behaviour on the |
| preserved dims is identical |
| For RMSNorm: |
| - first dim_old entries: copy old weight |
| - new entries: filled with 1.0 (identity contribution) |
| |
| The cond_proj layer of the diffusion head is RE-INITIALISED because its input |
| space (the LLM hidden states) is fundamentally different between Qwen2.5 and |
| Qwen3.5 (hybrid linear/full attention). Width-expanding it would not preserve |
| meaningful knowledge because the *meaning* of each hidden dimension has changed. |
| The other diffusion-head layers operate on the head's own hidden space, which is |
| preserved by the width expansion. |
| |
| After surgery the model is functional but its outputs will be degraded until a |
| short fine-tuning phase adapts the preserved weights to the new LLM's |
| representation space. |
| |
| Hardware target: 2x T4 (16 GB VRAM each) + 30 GB system RAM (Kaggle). |
| The surgery itself runs in CPU RAM (no GPU needed for tensor manipulations). |
| Verification / generation runs on a single T4 in bfloat16. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import gc |
| import json |
| import math |
| import os |
| import shutil |
| import sys |
| import warnings |
| from dataclasses import dataclass |
| from pathlib import Path |
| from typing import Any, Dict, List, Optional, Tuple, Union |
|
|
| import torch |
| import torch.nn as nn |
| import torch.nn.functional as F |
|
|
|
|
| |
| |
| |
|
|
| |
| OLD_LLM_HIDDEN_SIZE = 1536 |
| OLD_LLM_LAYERS = 28 |
| OLD_LLM_VOCAB = 151936 |
| OLD_LLM_INTERMEDIATE = 8960 |
| OLD_LLM_HEADS = 12 |
| OLD_LLM_KV_HEADS = 2 |
|
|
| |
| NEW_LLM_HIDDEN_SIZE = 2560 |
| NEW_LLM_LAYERS = 32 |
| NEW_LLM_VOCAB = 248320 |
| NEW_LLM_INTERMEDIATE = 9216 |
| NEW_LLM_HEADS = 16 |
| NEW_LLM_KV_HEADS = 4 |
| NEW_LLM_REPO = "Qwen/Qwen3.5-4B-Base" |
|
|
| |
| DIFFUSION_HEAD_LAYERS = 4 |
| DIFFUSION_HEAD_FFN_RATIO = 3.0 |
| DIFFUSION_HEAD_LATENT_SIZE = 64 |
| DIFFUSION_HEAD_RMS_EPS = 1e-5 |
|
|
| |
| ACOUSTIC_VAE_DIM = 64 |
| SEMANTIC_VAE_DIM = 128 |
|
|
|
|
| @dataclass |
| class SurgeryReport: |
| """Tracks everything that happened during surgery for logging/auditing.""" |
| old_llm_hidden: int |
| new_llm_hidden: int |
| old_vocab: int |
| new_vocab: int |
| expanded_modules: List[str] |
| reinitialized_modules: List[str] |
| preserved_modules: List[str] |
| total_params_before: int |
| total_params_after: int |
| output_dir: str |
|
|
| def summary(self) -> str: |
| delta = self.total_params_after - self.total_params_before |
| pct = 100.0 * delta / max(self.total_params_before, 1) |
| lines = [ |
| "=" * 70, |
| "VibeVoice Surgery Report", |
| "=" * 70, |
| f" LLM hidden size: {self.old_llm_hidden} -> {self.new_llm_hidden}", |
| f" Vocab size: {self.old_vocab} -> {self.new_vocab}", |
| f" Params before: {self.total_params_before:,}", |
| f" Params after: {self.total_params_after:,}", |
| f" Delta: {delta:+,} ({pct:+.2f}%)", |
| "", |
| f" Expanded (zero-pad): {len(self.expanded_modules)} modules", |
| f" Re-initialised: {len(self.reinitialized_modules)} modules", |
| f" Preserved unchanged: {len(self.preserved_modules)} modules", |
| "", |
| f" Output directory: {self.output_dir}", |
| "=" * 70, |
| ] |
| return "\n".join(lines) |
|
|
|
|
| |
| |
| |
|
|
| def setup_vibevoice_imports(vibevoice_repo_dir: Union[str, Path]) -> None: |
| """ |
| Add the VibeVoice repo root to sys.path and import its modelling modules |
| so that AutoModel picks up the VibeVoice registrations. |
| |
| `vibevoice_repo_dir` can be EITHER: |
| - The directory that *contains* the `vibevoice/` Python package. |
| Example: `/kaggle/working/VibeVoice/` (where `vibevoice/` lives inside) |
| - The `vibevoice/` package directory itself. |
| Example: `/kaggle/working/VibeVoice/vibevoice/` |
| - The `src/` directory of a finetuning fork (containing `vibevoice/`). |
| - The repo root of a finetuning fork (containing `src/vibevoice/`). |
| |
| The function auto-detects which case it is by checking for the existence |
| of the `modular/` subdirectory (which is the key marker of the vibevoice |
| package) containing `configuration_vibevoice.py`. |
| |
| IMPORTANT: The official Microsoft VibeVoice `__init__.py` imports streaming |
| classes (`VibeVoiceStreamingForConditionalGenerationInference`, etc.) that |
| may not exist in all forks and that trigger `AutoModel.register()` calls |
| which collide with transformers 5.x's builtin VibeVoice classes. To avoid |
| this, we ALWAYS replace `vibevoice/__init__.py` with a minimal stub |
| before importing the package. The original file is backed up as |
| `__init__.py.original` so it can be restored later if needed. |
| """ |
| p = Path(vibevoice_repo_dir).resolve() |
|
|
| def _looks_like_vibevoice_pkg(d: Path) -> bool: |
| """A directory looks like the vibevoice package if it has a |
| `modular/` subdirectory containing `configuration_vibevoice.py`.""" |
| return (d / "modular" / "configuration_vibevoice.py").exists() |
|
|
| def _find_vibevoice_pkg(start: Path) -> Path: |
| """Walk up to 3 levels looking for the vibevoice package directory.""" |
| candidates = [ |
| start, |
| start / "vibevoice", |
| start / "src" / "vibevoice", |
| start.parent, |
| start.parent / "vibevoice", |
| start.parent / "src" / "vibevoice", |
| start.parent.parent, |
| start.parent.parent / "vibevoice", |
| start.parent.parent / "src" / "vibevoice", |
| ] |
| for c in candidates: |
| if _looks_like_vibevoice_pkg(c): |
| return c |
| return None |
|
|
| |
| vv_pkg_dir = _find_vibevoice_pkg(p) |
| if vv_pkg_dir is None: |
| raise ImportError( |
| f"Cannot find the 'vibevoice' package near {vibevoice_repo_dir}.\n" |
| f"Looked for a directory containing 'modular/configuration_vibevoice.py' " |
| f"in the following candidates:\n" |
| f" - {p}\n" |
| f" - {p}/vibevoice/\n" |
| f" - {p}/src/vibevoice/\n" |
| f" - {p.parent}\n" |
| f" - {p.parent}/vibevoice/\n" |
| f" - {p.parent}/src/vibevoice/\n" |
| f" - {p.parent.parent}\n" |
| f" - {p.parent.parent}/vibevoice/\n" |
| f" - {p.parent.parent}/src/vibevoice/\n" |
| f"\nPlease pass the path to the directory that contains the " |
| f"'vibevoice/' folder (the repo root), OR the path to the " |
| f"'vibevoice/' folder itself." |
| ) |
|
|
| repo_root = vv_pkg_dir.parent |
| if str(repo_root) not in sys.path: |
| sys.path.insert(0, str(repo_root)) |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| init_file = vv_pkg_dir / "__init__.py" |
| backup_file = vv_pkg_dir / "__init__.py.original" |
| stub_content = ( |
| "# Auto-generated stub by surgery.py\n" |
| "# The original VibeVoice __init__.py imports streaming classes that\n" |
| "# (a) may not exist in all forks and (b) trigger AutoModel.register()\n" |
| "# calls that collide with transformers 5.x's builtin VibeVoice classes.\n" |
| "# Surgery.py imports the needed modules explicitly, so this stub can\n" |
| "# be empty. The original file is backed up as __init__.py.original.\n" |
| ) |
| if init_file.exists(): |
| original_content = init_file.read_text() |
| |
| if not backup_file.exists(): |
| backup_file.write_text(original_content) |
| |
| if original_content != stub_content: |
| print(f"[setup] Replacing {init_file} with minimal stub " |
| f"(original backed up at {backup_file})") |
| init_file.write_text(stub_content) |
| else: |
| print(f"[setup] Creating minimal {init_file}") |
| init_file.write_text(stub_content) |
|
|
| |
| modular_init = vv_pkg_dir / "modular" / "__init__.py" |
| modular_backup = vv_pkg_dir / "modular" / "__init__.py.original" |
| if modular_init.exists(): |
| modular_content = modular_init.read_text() |
| |
| if "streaming" in modular_content.lower(): |
| if not modular_backup.exists(): |
| modular_backup.write_text(modular_content) |
| print(f"[setup] Replacing {modular_init} with empty stub " |
| f"(original backed up at {modular_backup})") |
| modular_init.write_text( |
| "# Auto-generated stub by surgery.py\n" |
| "# The original modular/__init__.py imported streaming classes\n" |
| "# that may not exist in all forks. Surgery.py imports the\n" |
| "# needed modules explicitly.\n" |
| ) |
| else: |
| |
| modular_init.write_text( |
| "# Auto-generated stub by surgery.py\n" |
| ) |
|
|
| |
| processor_init = vv_pkg_dir / "processor" / "__init__.py" |
| if processor_init.exists(): |
| processor_content = processor_init.read_text() |
| if "streaming" in processor_content.lower() or "VibeVoiceStreamingProcessor" in processor_content: |
| processor_backup = vv_pkg_dir / "processor" / "__init__.py.original" |
| if not processor_backup.exists(): |
| processor_backup.write_text(processor_content) |
| print(f"[setup] Replacing {processor_init} with empty stub " |
| f"(original backed up at {processor_backup})") |
| processor_init.write_text( |
| "# Auto-generated stub by surgery.py\n" |
| ) |
| else: |
| processor_init.write_text("# Auto-generated stub by surgery.py\n") |
|
|
| |
| |
| |
| |
| _patch_auto_register_tolerant() |
|
|
| |
| |
| _patch_transformers_5x_compat() |
|
|
| |
| |
| |
| |
| _override_builtin_vibevoice_classes() |
|
|
| |
| |
| try: |
| import vibevoice |
| except ImportError as e: |
| raise ImportError( |
| f"Cannot import the 'vibevoice' package even after adding " |
| f"{repo_root} to sys.path and stubbing __init__.py. " |
| f"Original error: {e}" |
| ) |
|
|
| |
| |
| from vibevoice.modular import configuration_vibevoice |
| from vibevoice.modular import modeling_vibevoice |
| from vibevoice.modular import modular_vibevoice_tokenizer |
| from vibevoice.modular import modular_vibevoice_diffusion_head |
| from vibevoice.modular import modular_vibevoice_text_tokenizer |
|
|
| |
| |
| |
| _override_builtin_vibevoice_classes() |
|
|
| |
| |
| _patch_vibevoice_config_for_qwen35() |
|
|
| print(f"[setup] VibeVoice modules loaded from {repo_root}") |
|
|
|
|
| _AUTO_PATCHED = False |
|
|
|
|
| def _patch_auto_register_tolerant() -> None: |
| """Make AutoModel.register / AutoModelForCausalLM.register idempotent.""" |
| global _AUTO_PATCHED |
| if _AUTO_PATCHED: |
| return |
| from transformers.models.auto.auto_factory import _LazyAutoMapping |
|
|
| original_register = _LazyAutoMapping.register |
|
|
| def tolerant_register(self, config_class, model_class, exist_ok=True): |
| try: |
| return original_register(self, config_class, model_class, exist_ok=exist_ok) |
| except ValueError: |
| |
| return None |
|
|
| _LazyAutoMapping.register = tolerant_register |
| _AUTO_PATCHED = True |
| print("[setup] Patched AutoModel.register to be idempotent") |
|
|
|
|
| _COMPAT_PATCHED = False |
|
|
|
|
| def _patch_transformers_5x_compat() -> None: |
| """ |
| Apply compatibility shims for transformers 5.x breaking changes that |
| VibeVoice's source code does not yet handle: |
| |
| 1. `transformers.models.qwen2.tokenization_qwen2_fast` was removed in |
| transformers 5.x (Qwen2TokenizerFast now lives in tokenization_qwen2). |
| We inject a synthetic module that re-exports the merged class so the |
| VibeVoice `from ... import Qwen2TokenizerFast` keeps working. |
| |
| Idempotent. |
| """ |
| global _COMPAT_PATCHED |
| if _COMPAT_PATCHED: |
| return |
|
|
| import types |
| import transformers.models.qwen2 as qwen2_pkg |
| from transformers.models.qwen2 import tokenization_qwen2 |
|
|
| |
| |
| fast_mod = types.ModuleType("transformers.models.qwen2.tokenization_qwen2_fast") |
| |
| |
| fast_mod.Qwen2TokenizerFast = ( |
| getattr(tokenization_qwen2, "Qwen2TokenizerFast", None) |
| or tokenization_qwen2.Qwen2Tokenizer |
| ) |
| fast_mod.Qwen2Tokenizer = tokenization_qwen2.Qwen2Tokenizer |
| sys.modules["transformers.models.qwen2.tokenization_qwen2_fast"] = fast_mod |
| |
| qwen2_pkg.tokenization_qwen2_fast = fast_mod |
|
|
| _COMPAT_PATCHED = True |
| print("[setup] Patched transformers 5.x qwen2 tokenizer compat") |
|
|
|
|
| _OVERRIDE_PATCHED = False |
|
|
|
|
| def _override_builtin_vibevoice_classes() -> None: |
| """ |
| Force AutoModel.from_config (and AutoModelForCausalLM.from_pretrained) to |
| use the user's local VibeVoice classes instead of the (incompatible) |
| builtin ones shipped with transformers 5.x. |
| |
| transformers >= 5.x ships its own `VibeVoiceAcousticTokenizerConfig` / |
| `VibeVoiceAcousticTokenizerModel` etc., but with a DIFFERENT API than the |
| user's local code (e.g. `encoder_config` vs `encoder_n_filters`). If we |
| let AutoModel pick the builtin class, loading the user's checkpoint fails |
| with attribute errors. |
| |
| Implementation: we monkey-patch AutoModel.from_config to check whether the |
| passed config is one of the user's VibeVoice config classes. If yes, we |
| instantiate the user's model class directly. Otherwise, we delegate to |
| the original AutoModel.from_config (so non-VibeVoice models are |
| unaffected). AutoModelForCausalLM.from_pretrained is similarly patched |
| to route VibeVoice checkpoints to the user's |
| VibeVoiceForConditionalGeneration class. |
| |
| Idempotent. |
| """ |
| global _OVERRIDE_PATCHED |
|
|
| try: |
| from vibevoice.modular.configuration_vibevoice import ( |
| VibeVoiceConfig, |
| VibeVoiceAcousticTokenizerConfig, |
| VibeVoiceSemanticTokenizerConfig, |
| VibeVoiceDiffusionHeadConfig, |
| ) |
| except ImportError: |
| |
| return |
|
|
| if _OVERRIDE_PATCHED: |
| return |
|
|
| from transformers.models.auto import AutoModel, AutoModelForCausalLM |
|
|
| |
| |
| _USER_MODEL_CLASSES: Dict[type, type] = {} |
|
|
| def _ensure_user_classes_loaded() -> None: |
| if _USER_MODEL_CLASSES: |
| return |
| from vibevoice.modular.modular_vibevoice_tokenizer import ( |
| VibeVoiceAcousticTokenizerModel, |
| VibeVoiceSemanticTokenizerModel, |
| ) |
| from vibevoice.modular.modular_vibevoice_diffusion_head import ( |
| VibeVoiceDiffusionHead, |
| ) |
| from vibevoice.modular.modeling_vibevoice import ( |
| VibeVoiceModel, |
| VibeVoiceForConditionalGeneration, |
| ) |
| _USER_MODEL_CLASSES.update({ |
| VibeVoiceAcousticTokenizerConfig: VibeVoiceAcousticTokenizerModel, |
| VibeVoiceSemanticTokenizerConfig: VibeVoiceSemanticTokenizerModel, |
| VibeVoiceDiffusionHeadConfig: VibeVoiceDiffusionHead, |
| VibeVoiceConfig: VibeVoiceModel, |
| }) |
| |
| _USER_MODEL_CLASSES["__causal_lm__"] = VibeVoiceForConditionalGeneration |
|
|
| |
| _orig_automodel_from_config = AutoModel.from_config |
|
|
| def _patched_from_config(config, *args, **kwargs): |
| _ensure_user_classes_loaded() |
| |
| for user_cfg_cls, user_mdl_cls in _USER_MODEL_CLASSES.items(): |
| if not isinstance(user_cfg_cls, type): |
| continue |
| if isinstance(config, user_cfg_cls): |
| return user_mdl_cls._from_config(config, *args, **kwargs) |
| |
| |
| |
| cfg_cls_name = type(config).__name__ |
| name_to_model = { |
| "VibeVoiceAcousticTokenizerConfig": _USER_MODEL_CLASSES[VibeVoiceAcousticTokenizerConfig], |
| "VibeVoiceSemanticTokenizerConfig": _USER_MODEL_CLASSES[VibeVoiceSemanticTokenizerConfig], |
| "VibeVoiceDiffusionHeadConfig": _USER_MODEL_CLASSES[VibeVoiceDiffusionHeadConfig], |
| "VibeVoiceConfig": _USER_MODEL_CLASSES[VibeVoiceConfig], |
| } |
| if cfg_cls_name in name_to_model: |
| user_mdl_cls = name_to_model[cfg_cls_name] |
| return user_mdl_cls._from_config(config, *args, **kwargs) |
| return _orig_automodel_from_config(config, *args, **kwargs) |
|
|
| AutoModel.from_config = staticmethod(_patched_from_config) |
|
|
| |
| _orig_causallm_from_pretrained = AutoModelForCausalLM.from_pretrained |
|
|
| def _patched_causallm_from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs): |
| _ensure_user_classes_loaded() |
| |
| from transformers import AutoConfig |
| try: |
| cfg = AutoConfig.from_pretrained(pretrained_model_name_or_path, **{ |
| k: v for k, v in kwargs.items() |
| if k in ("cache_dir", "trust_remote_code", "revision", "use_auth_token") |
| }) |
| except Exception: |
| cfg = None |
| |
| is_vibevoice = False |
| if cfg is not None: |
| if isinstance(cfg, VibeVoiceConfig): |
| is_vibevoice = True |
| elif type(cfg).__name__ in ( |
| "VibeVoiceConfig", "VibeVoiceForConditionalGeneration", |
| ): |
| is_vibevoice = True |
| elif getattr(cfg, "model_type", "") in ("vibevoice", "vibepod"): |
| is_vibevoice = True |
| if is_vibevoice: |
| user_cls = _USER_MODEL_CLASSES.get("__causal_lm__") |
| if user_cls is not None: |
| return user_cls.from_pretrained(pretrained_model_name_or_path, *args, **kwargs) |
| |
| if hasattr(_orig_causallm_from_pretrained, "__func__"): |
| return _orig_causallm_from_pretrained.__func__(cls, pretrained_model_name_or_path, *args, **kwargs) |
| return _orig_causallm_from_pretrained(pretrained_model_name_or_path, *args, **kwargs) |
|
|
| AutoModelForCausalLM.from_pretrained = classmethod(_patched_causallm_from_pretrained) |
|
|
| |
| from transformers import AutoConfig |
| _orig_autoconfig_from_pretrained = AutoConfig.from_pretrained |
|
|
| def _patched_autoconfig_from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs): |
| cfg = _orig_autoconfig_from_pretrained.__func__(cls, pretrained_model_name_or_path, *args, **kwargs) \ |
| if hasattr(_orig_autoconfig_from_pretrained, "__func__") \ |
| else _orig_autoconfig_from_pretrained(pretrained_model_name_or_path, *args, **kwargs) |
| |
| |
| cfg_type_name = type(cfg).__name__ |
| builtin_vibevoice_names = { |
| "VibeVoiceAcousticTokenizerConfig", |
| "VibeVoiceSemanticTokenizerConfig", |
| "VibeVoiceDiffusionHeadConfig", |
| "VibeVoiceConfig", |
| } |
| if cfg_type_name in builtin_vibevoice_names: |
| |
| user_cfg_cls = { |
| "VibeVoiceAcousticTokenizerConfig": VibeVoiceAcousticTokenizerConfig, |
| "VibeVoiceSemanticTokenizerConfig": VibeVoiceSemanticTokenizerConfig, |
| "VibeVoiceDiffusionHeadConfig": VibeVoiceDiffusionHeadConfig, |
| "VibeVoiceConfig": VibeVoiceConfig, |
| }[cfg_type_name] |
| |
| try: |
| cfg_dict = cfg.to_dict() |
| |
| for k in ("model_type", "transformers_version"): |
| cfg_dict.pop(k, None) |
| |
| |
| |
| return user_cfg_cls(**cfg_dict) |
| except Exception as e: |
| print(f"[setup] WARN: could not rebuild config as user's class: {e}") |
| return cfg |
| return cfg |
|
|
| AutoConfig.from_pretrained = classmethod(_patched_autoconfig_from_pretrained) |
|
|
| |
| |
| |
| |
| try: |
| from vibevoice.modular.modeling_vibevoice import ( |
| VibeVoiceForConditionalGeneration as _VVCFG, |
| ) |
| |
| |
| _VVCFG._tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} |
|
|
| |
| |
| |
| |
| |
| |
| _orig_tie_weights_cfg = _VVCFG.tie_weights |
|
|
| def _patched_tie_weights_cfg(self, *args, **kwargs): |
| |
| kwargs.pop("recompute_mapping", None) |
| kwargs.pop("missing_keys", None) |
| return _orig_tie_weights_cfg(self, *args, **kwargs) |
|
|
| _VVCFG.tie_weights = _patched_tie_weights_cfg |
| print("[setup] Patched VibeVoiceForConditionalGeneration.tie_weights for transformers 5.x") |
|
|
| |
| |
| |
| |
| try: |
| from vibevoice.modular.modeling_vibevoice_inference import ( |
| VibeVoiceForConditionalGenerationInference as _VVInfCFG, |
| ) |
| _VVInfCFG._tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} |
|
|
| _orig_tie_weights_inf = _VVInfCFG.tie_weights |
|
|
| def _patched_tie_weights_inf(self, *args, **kwargs): |
| kwargs.pop("recompute_mapping", None) |
| kwargs.pop("missing_keys", None) |
| return _orig_tie_weights_inf(self, *args, **kwargs) |
|
|
| _VVInfCFG.tie_weights = _patched_tie_weights_inf |
| print("[setup] Patched VibeVoiceForConditionalGenerationInference.tie_weights for transformers 5.x") |
| except ImportError: |
| |
| pass |
|
|
| except ImportError as e: |
| print(f"[setup] WARN: could not patch _tied_weights_keys: {e}") |
|
|
| |
| |
| |
| |
| |
| |
| |
| try: |
| from vibevoice.schedule.dpm_solver import DPMSolverMultistepScheduler as _DPM |
| _orig_dpm_init = _DPM.__init__ |
|
|
| def _patched_dpm_init(self, *args, **kwargs): |
| |
| |
| with torch.device("cpu"): |
| return _orig_dpm_init(self, *args, **kwargs) |
|
|
| _DPM.__init__ = _patched_dpm_init |
| print("[setup] Patched DPMSolverMultistepScheduler.__init__ for meta device") |
| except ImportError as e: |
| print(f"[setup] WARN: could not patch DPMSolverMultistepScheduler: {e}") |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| try: |
| from transformers.generation.utils import GenerationMixin |
| _orig_prepare_gen_config = GenerationMixin._prepare_generation_config |
|
|
| def _patched_prepare_generation_config(self, generation_config, *args, **kwargs): |
| |
| |
| |
| return _orig_prepare_gen_config(self, generation_config, **kwargs) |
|
|
| GenerationMixin._prepare_generation_config = _patched_prepare_generation_config |
| print("[setup] Patched GenerationMixin._prepare_generation_config for transformers 5.x") |
| except (ImportError, AttributeError) as e: |
| print(f"[setup] WARN: could not patch _prepare_generation_config: {e}") |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| try: |
| _orig_prepare_cache = GenerationMixin._prepare_cache_for_generation |
|
|
| def _patched_prepare_cache_for_generation(self, generation_config, model_kwargs, *args, **kwargs): |
| |
| |
| |
| |
| |
| if len(args) > 3: |
| |
| args = args[:3] |
| result = _orig_prepare_cache(self, generation_config, model_kwargs, *args, **kwargs) |
|
|
| |
| |
| |
| |
| |
| |
| cache_name = "past_key_values" |
| pkv = model_kwargs.get(cache_name) |
| if pkv is not None and hasattr(pkv, "layers") and len(pkv.layers) > 0: |
| |
| dec_cfg = getattr(self.config, "decoder_config", None) |
| if dec_cfg is not None: |
| dec_layer_types = getattr(dec_cfg, "layer_types", None) |
| if dec_layer_types and any( |
| lt == "linear_attention" for lt in dec_layer_types |
| ): |
| |
| |
| from transformers.cache_utils import ( |
| LinearAttentionCacheLayerMixin as _LAC, |
| ) |
| has_linear = any( |
| isinstance(l, _LAC) for l in pkv.layers |
| ) |
| if not has_linear: |
| |
| |
| from transformers import DynamicCache as _DC |
| new_cache = _DC(config=dec_cfg) |
| model_kwargs[cache_name] = new_cache |
|
|
| return result |
|
|
| GenerationMixin._prepare_cache_for_generation = _patched_prepare_cache_for_generation |
| print("[setup] Patched GenerationMixin._prepare_cache_for_generation for transformers 5.x") |
| except (ImportError, AttributeError) as e: |
| print(f"[setup] WARN: could not patch _prepare_cache_for_generation: {e}") |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| try: |
| from vibevoice.modular.modeling_vibevoice import VibeVoicePreTrainedModel |
| _orig_vv_init_weights = VibeVoicePreTrainedModel._init_weights |
|
|
| |
| |
| |
| import threading |
| _init_state = threading.local() |
| _init_state.in_post_load_init = False |
|
|
| def _patched_vv_init_weights(self, module): |
| |
| from vibevoice.modular.modular_vibevoice_diffusion_head import VibeVoiceDiffusionHead |
| if isinstance(module, VibeVoiceDiffusionHead): |
| module.initialize_weights() |
| return |
| |
| |
| |
| if getattr(_init_state, "in_post_load_init", False): |
| |
| has_loaded_param = any( |
| getattr(p, "_is_hf_initialized", False) |
| for p in module.parameters(recurse=False) |
| ) |
| if has_loaded_param: |
| return |
| |
| _orig_vv_init_weights(self, module) |
|
|
| VibeVoicePreTrainedModel._init_weights = _patched_vv_init_weights |
|
|
| |
| _orig_vv_initialize_weights = VibeVoicePreTrainedModel.initialize_weights |
|
|
| def _patched_vv_initialize_weights(self): |
| _init_state.in_post_load_init = True |
| try: |
| return _orig_vv_initialize_weights(self) |
| finally: |
| _init_state.in_post_load_init = False |
|
|
| VibeVoicePreTrainedModel.initialize_weights = _patched_vv_initialize_weights |
| print("[setup] Patched VibeVoicePreTrainedModel._init_weights to preserve loaded weights") |
| except ImportError as e: |
| print(f"[setup] WARN: could not patch VibeVoicePreTrainedModel._init_weights: {e}") |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| try: |
| from vibevoice.modular.modular_vibevoice_tokenizer import VibeVoiceTokenizerEncoderOutput |
| if not hasattr(VibeVoiceTokenizerEncoderOutput, "__getitem__"): |
| def _encoder_output_getitem(self, index): |
| """Make the dataclass subscriptable like the old tuple-based API. |
| [0] -> self (the EncoderOutput object, which has .sample()) |
| [1] -> self.std |
| Any integer index returns self so that [0][0] chaining works. |
| """ |
| if index == 0: |
| return self |
| |
| elif index == 1: |
| return self.std |
| else: |
| return self |
| VibeVoiceTokenizerEncoderOutput.__getitem__ = _encoder_output_getitem |
| print("[setup] Patched VibeVoiceTokenizerEncoderOutput.__getitem__ " |
| "for tuple-like access (returns self for [0])") |
| except ImportError as e: |
| print(f"[setup] WARN: could not patch VibeVoiceTokenizerEncoderOutput: {e}") |
|
|
| _OVERRIDE_PATCHED = True |
| print("[setup] Overrode builtin VibeVoice classes with user's local ones") |
|
|
|
|
| _PATCHED = False |
|
|
|
|
| def _patch_vibevoice_config_for_qwen35() -> None: |
| """ |
| Monkey-patch VibeVoiceConfig so that its __init__ accepts any model_type |
| for the decoder_config (not just 'qwen2'). Without this patch, loading |
| a surgically-modified VibeVoice (which has a qwen3_5_text decoder) would |
| raise: "Unsupported decoder model type: qwen3_5_text". |
| |
| The patch is idempotent (safe to call multiple times). |
| """ |
| global _PATCHED |
| if _PATCHED: |
| return |
|
|
| from vibevoice.modular.configuration_vibevoice import VibeVoiceConfig |
| from transformers.models.qwen2.configuration_qwen2 import Qwen2Config |
| from transformers import AutoConfig |
|
|
| def patched_init(self, acoustic_tokenizer_config=None, semantic_tokenizer_config=None, |
| decoder_config=None, diffusion_head_config=None, **kwargs): |
| """ |
| Replacement for VibeVoiceConfig.__init__ that accepts ANY decoder |
| model_type (not just 'qwen2'). The original code only supports qwen2. |
| """ |
| |
| kwargs.setdefault("_attn_implementation_autoset", False) |
|
|
| |
| from vibevoice.modular.configuration_vibevoice import ( |
| VibeVoiceAcousticTokenizerConfig, |
| VibeVoiceSemanticTokenizerConfig, |
| VibeVoiceDiffusionHeadConfig, |
| ) |
| if acoustic_tokenizer_config is None: |
| self.acoustic_tokenizer_config = VibeVoiceAcousticTokenizerConfig() |
| elif isinstance(acoustic_tokenizer_config, dict): |
| d = dict(acoustic_tokenizer_config) |
| d["model_type"] = "vibevoice_acoustic_tokenizer" |
| self.acoustic_tokenizer_config = VibeVoiceAcousticTokenizerConfig(**d) |
| else: |
| self.acoustic_tokenizer_config = acoustic_tokenizer_config |
|
|
| |
| if semantic_tokenizer_config is None: |
| self.semantic_tokenizer_config = VibeVoiceSemanticTokenizerConfig() |
| elif isinstance(semantic_tokenizer_config, dict): |
| d = dict(semantic_tokenizer_config) |
| d["model_type"] = "vibevoice_semantic_tokenizer" |
| self.semantic_tokenizer_config = VibeVoiceSemanticTokenizerConfig(**d) |
| else: |
| self.semantic_tokenizer_config = semantic_tokenizer_config |
|
|
| |
| if decoder_config is None: |
| self.decoder_config = Qwen2Config() |
| elif isinstance(decoder_config, dict): |
| mt = decoder_config.get("model_type", "") |
| if mt == "qwen2": |
| self.decoder_config = Qwen2Config(**decoder_config) |
| elif mt: |
| |
| d = dict(decoder_config) |
| d.pop("model_type", None) |
| try: |
| self.decoder_config = AutoConfig.for_model(model_type=mt, **d) |
| except Exception as e: |
| print(f"[patch] Could not build config for model_type='{mt}': {e}") |
| raise |
| else: |
| |
| self.decoder_config = Qwen2Config(**decoder_config) |
| else: |
| |
| self.decoder_config = decoder_config |
|
|
| |
| if diffusion_head_config is None: |
| self.diffusion_head_config = VibeVoiceDiffusionHeadConfig() |
| elif isinstance(diffusion_head_config, dict): |
| d = dict(diffusion_head_config) |
| d["model_type"] = "vibevoice_diffusion_head" |
| self.diffusion_head_config = VibeVoiceDiffusionHeadConfig(**d) |
| else: |
| self.diffusion_head_config = diffusion_head_config |
|
|
| |
| self.acoustic_vae_dim = getattr(self.acoustic_tokenizer_config, 'vae_dim', 64) |
| self.semantic_vae_dim = getattr(self.semantic_tokenizer_config, 'vae_dim', 128) |
|
|
| |
| |
| super(VibeVoiceConfig, self).__init__(**kwargs) |
|
|
| |
| |
| |
| |
| |
| |
| dec = self.decoder_config |
| for attr in ("num_hidden_layers", "hidden_size", "num_attention_heads", |
| "num_key_value_heads", "head_dim", "intermediate_size", |
| "vocab_size", "max_position_embeddings", "rms_norm_eps", |
| "tie_word_embeddings", "layer_types"): |
| if hasattr(dec, attr) and not hasattr(self, attr): |
| try: |
| setattr(self, attr, getattr(dec, attr)) |
| except Exception: |
| pass |
|
|
| VibeVoiceConfig.__init__ = patched_init |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| def patched_get_text_config(self, decoder=None, encoder=None): |
| """ |
| Return the decoder's text config when decoder=True. |
| For VibeVoice, the decoder config is self.decoder_config. |
| """ |
| if decoder is True: |
| |
| if hasattr(self, "decoder_config") and self.decoder_config is not None: |
| return self.decoder_config |
| |
| |
| return _orig_get_text_config(self, decoder=decoder, encoder=encoder) |
|
|
| _orig_get_text_config = VibeVoiceConfig.get_text_config |
| VibeVoiceConfig.get_text_config = patched_get_text_config |
|
|
| _PATCHED = True |
| print("[setup] Patched VibeVoiceConfig to support qwen3_5_text decoder") |
|
|
| |
| |
| |
| try: |
| from vibevoice.modular.configuration_vibevoice_streaming import ( |
| VibeVoiceStreamingConfig as _VVStreamingConfig, |
| ) |
| _orig_streaming_init = _VVStreamingConfig.__init__ |
|
|
| def _patched_streaming_init(self, *args, **kwargs): |
| from transformers import AutoConfig |
| |
| if "decoder_config" in kwargs and isinstance(kwargs["decoder_config"], dict): |
| dc = kwargs["decoder_config"] |
| mt = dc.get("model_type", "") |
| if mt and mt != "qwen2": |
| try: |
| dc_clean = dict(dc) |
| dc_clean.pop("model_type", None) |
| kwargs["decoder_config"] = AutoConfig.for_model( |
| model_type=mt, **dc_clean |
| ) |
| except Exception as e: |
| print(f"[patch] Streaming config: AutoConfig.for_model " |
| f"failed for '{mt}': {e}") |
|
|
| |
| from vibevoice.modular import configuration_vibevoice_streaming as _vv_str_mod |
| from transformers.models.qwen2.configuration_qwen2 import Qwen2Config |
| _orig_qwen2cls = getattr(_vv_str_mod, "Qwen2Config", Qwen2Config) |
| dec_cfg = kwargs.get("decoder_config", None) |
| if dec_cfg is not None and not isinstance(dec_cfg, dict): |
| _vv_str_mod.Qwen2Config = (Qwen2Config, type(dec_cfg)) |
| try: |
| _orig_streaming_init(self, *args, **kwargs) |
| finally: |
| _vv_str_mod.Qwen2Config = _orig_qwen2cls |
|
|
| |
| if not hasattr(self, "decoder_config") or self.decoder_config is None: |
| dec_cfg = kwargs.get("decoder_config", None) |
| if dec_cfg is not None: |
| self.decoder_config = dec_cfg |
| else: |
| self.decoder_config = Qwen2Config() |
|
|
| _VVStreamingConfig.__init__ = _patched_streaming_init |
| print("[setup] Patched VibeVoiceStreamingConfig to support qwen3_5_text decoder") |
| except ImportError: |
| |
| pass |
|
|
|
|
| |
| |
| |
|
|
| @torch.no_grad() |
| def expand_linear_zero_pad( |
| old_layer: nn.Linear, |
| new_in_features: int, |
| new_out_features: int, |
| bias: Optional[bool] = None, |
| init_new_input: str = "zero", |
| ) -> nn.Linear: |
| """ |
| Build a new nn.Linear(new_in, new_out) whose top-left |
| (old_in, old_out) block equals the old layer's weights, and whose |
| new rows / columns are zero- (or optionally small-random-) initialised. |
| |
| Args: |
| old_layer: source nn.Linear; must have weight shape (old_out, old_in). |
| new_in_features: expanded input dim (>= old_in). |
| new_out_features: expanded output dim (>= old_out). |
| bias: whether the new layer should have a bias. |
| If None (default), the bias flag is INHERITED from old_layer: |
| if old_layer.bias is not None, the new layer also has a bias, |
| and the old bias values are copied (with zero-padding for the |
| new output positions). This preserves the original biases for |
| the preserved output dims and zero-inits the new dims. |
| If True/False, that value is used explicitly. |
| init_new_input: "zero" -> new input columns are zero |
| "small" -> new input columns are N(0, 1/sqrt(new_in)) |
| |
| Returns: |
| A new nn.Linear with the expanded weights loaded. |
| |
| NOTE: The previous default was `bias=False`, which silently dropped the |
| biases of the speech-connector fc1/fc2 and the diffusion-head FFN layers. |
| This caused the LOAD REPORT to flag `fc1.bias` / `fc2.bias` as MISSING |
| after surgery, and the biases were then re-initialised by `_init_weights`, |
| losing the pretrained bias values for the preserved output dims. |
| """ |
| old_out, old_in = old_layer.weight.shape |
| if new_in_features < old_in or new_out_features < old_out: |
| raise ValueError( |
| f"Cannot shrink layer: old=({old_in},{old_out}) " |
| f"new=({new_in_features},{new_out_features})" |
| ) |
|
|
| |
| |
| |
| |
| if bias is None: |
| bias = old_layer.bias is not None |
|
|
| |
| new_layer = nn.Linear( |
| new_in_features, |
| new_out_features, |
| bias=bias, |
| device=old_layer.weight.device, |
| dtype=old_layer.weight.dtype, |
| ) |
|
|
| |
| new_layer.weight.data.zero_() |
|
|
| |
| new_layer.weight.data[:old_out, :old_in].copy_(old_layer.weight.data) |
|
|
| |
| |
| |
| if init_new_input == "small" and new_in_features > old_in: |
| std = 1.0 / math.sqrt(new_in_features) |
| new_layer.weight.data[:old_out, old_in:].normal_(mean=0.0, std=std) |
|
|
| |
| |
| |
| |
| if bias: |
| |
| |
| |
| new_layer.bias.data.zero_() |
| if old_layer.bias is not None: |
| new_layer.bias.data[:old_out].copy_(old_layer.bias.data) |
|
|
| return new_layer |
|
|
|
|
| @torch.no_grad() |
| def expand_rmsnorm( |
| old_norm: nn.Module, |
| new_dim: int, |
| eps: Optional[float] = None, |
| ) -> nn.Module: |
| """ |
| Expand an RMSNorm-like module from old_dim to new_dim. |
| |
| The new weights are: [old_weights (copied), 1.0, 1.0, ...] |
| (1.0 because that is the identity contribution for the new dims). |
| |
| Works with both LlamaRMSNorm (transformers) and the custom RMSNorm |
| defined in modular_vibevoice_diffusion_head.py. |
| """ |
| |
| if not hasattr(old_norm, "weight"): |
| raise ValueError(f"Module {type(old_norm)} has no 'weight' attribute.") |
| old_dim = old_norm.weight.shape[0] |
| if new_dim < old_dim: |
| raise ValueError(f"Cannot shrink RMSNorm: {old_dim} -> {new_dim}") |
|
|
| |
| if eps is None: |
| eps = getattr(old_norm, "eps", 1e-6) |
|
|
| |
| norm_cls = type(old_norm) |
| try: |
| new_norm = norm_cls(new_dim, eps=eps) |
| except TypeError: |
| |
| new_norm = norm_cls(new_dim, eps=eps, elementwise_affine=True) |
|
|
| |
| new_norm = new_norm.to(device=old_norm.weight.device, dtype=old_norm.weight.dtype) |
|
|
| |
| new_norm.weight.data.fill_(1.0) |
| |
| new_norm.weight.data[:old_dim].copy_(old_norm.weight.data) |
|
|
| return new_norm |
|
|
|
|
| @torch.no_grad() |
| def reinit_linear_like_old( |
| layer: nn.Linear, |
| std: float = 0.02, |
| ) -> None: |
| """ |
| Re-initialise a Linear layer in place using the same scheme as |
| VibeVoicePreTrainedModel._init_weights (normal_ with std=0.02). |
| """ |
| layer.weight.data.normal_(mean=0.0, std=std) |
| if layer.bias is not None: |
| layer.bias.data.zero_() |
|
|
|
|
| |
| |
| |
|
|
| @torch.no_grad() |
| def expand_speech_connector( |
| old_connector: nn.Module, |
| new_output_dim: int, |
| name: str = "speech_connector", |
| ) -> nn.Module: |
| """ |
| Expand a SpeechConnector(input_dim, output_dim) from old_output_dim to |
| new_output_dim. The connector structure is: |
| fc1: Linear(input_dim, output_dim) |
| norm: LlamaRMSNorm(output_dim, eps=1e-6) |
| fc2: Linear(output_dim, output_dim) |
| |
| Strategy: |
| - fc1: Linear(in_vae, 1536) -> Linear(in_vae, 2560) |
| * input dim unchanged, output dim zero-padded |
| - norm: RMSNorm(1536) -> RMSNorm(2560) (copy old, 1.0 for new) |
| - fc2: Linear(1536, 1536) -> Linear(2560, 2560) |
| * both dims expanded; top-left block copied, rest zero |
| """ |
| |
| from vibevoice.modular.modeling_vibevoice import SpeechConnector |
|
|
| old_output_dim = old_connector.fc1.out_features |
| input_dim = old_connector.fc1.in_features |
|
|
| if new_output_dim <= old_output_dim: |
| raise ValueError( |
| f"Cannot shrink connector: {old_output_dim} -> {new_output_dim}" |
| ) |
|
|
| print(f" [{name}] fc1: Linear({input_dim},{old_output_dim}) " |
| f"-> Linear({input_dim},{new_output_dim}) (zero-pad output)") |
| print(f" [{name}] norm: RMSNorm({old_output_dim}) " |
| f"-> RMSNorm({new_output_dim}) (copy + 1.0 for new)") |
| print(f" [{name}] fc2: Linear({old_output_dim},{old_output_dim}) " |
| f"-> Linear({new_output_dim},{new_output_dim}) (zero-pad in+out)") |
|
|
| |
| new_connector = SpeechConnector(input_dim, new_output_dim) |
| new_connector = new_connector.to( |
| device=old_connector.fc1.weight.device, |
| dtype=old_connector.fc1.weight.dtype, |
| ) |
|
|
| |
| new_connector.fc1 = expand_linear_zero_pad( |
| old_connector.fc1, new_in_features=input_dim, new_out_features=new_output_dim |
| ) |
|
|
| |
| new_connector.norm = expand_rmsnorm(old_connector.norm, new_output_dim, eps=1e-6) |
|
|
| |
| new_connector.fc2 = expand_linear_zero_pad( |
| old_connector.fc2, |
| new_in_features=new_output_dim, |
| new_out_features=new_output_dim, |
| ) |
|
|
| return new_connector |
|
|
|
|
| @torch.no_grad() |
| def expand_timestep_embedder( |
| old_emb: nn.Module, |
| new_hidden: int, |
| ) -> nn.Module: |
| """ |
| Expand a TimestepEmbedder(hidden_size) from old_hidden to new_hidden. |
| Structure: |
| mlp[0]: Linear(freq_emb=256, hidden) -- zero-pad output |
| mlp[1]: SiLU activation (no params) |
| mlp[2]: Linear(hidden, hidden) -- zero-pad in+out |
| """ |
| from vibevoice.modular.modular_vibevoice_diffusion_head import TimestepEmbedder |
|
|
| old_hidden = old_emb.mlp[0].out_features |
| freq_emb = old_emb.mlp[0].in_features |
|
|
| print(f" [t_embedder] mlp[0]: Linear({freq_emb},{old_hidden}) " |
| f"-> Linear({freq_emb},{new_hidden}) (zero-pad output)") |
| print(f" [t_embedder] mlp[2]: Linear({old_hidden},{old_hidden}) " |
| f"-> Linear({new_hidden},{new_hidden}) (zero-pad in+out)") |
|
|
| new_emb = TimestepEmbedder(new_hidden) |
| new_emb = new_emb.to( |
| device=old_emb.mlp[0].weight.device, |
| dtype=old_emb.mlp[0].weight.dtype, |
| ) |
|
|
| new_emb.mlp[0] = expand_linear_zero_pad( |
| old_emb.mlp[0], new_in_features=freq_emb, new_out_features=new_hidden |
| ) |
| new_emb.mlp[2] = expand_linear_zero_pad( |
| old_emb.mlp[2], new_in_features=new_hidden, new_out_features=new_hidden |
| ) |
| |
| return new_emb |
|
|
|
|
| @torch.no_grad() |
| def expand_head_layer( |
| old_layer: nn.Module, |
| new_embed_dim: int, |
| new_ffn_dim: int, |
| new_cond_dim: int, |
| norm_eps: float, |
| ) -> nn.Module: |
| """ |
| Expand a HeadLayer(embed_dim, ffn_dim, cond_dim) to the new dims. |
| Structure: |
| ffn.gate_proj: Linear(embed, ffn) -- zero-pad in+out |
| ffn.up_proj: Linear(embed, ffn) -- zero-pad in+out |
| ffn.down_proj: Linear(ffn, embed) -- zero-pad in+out |
| norm: RMSNorm(embed) -- copy + 1.0 for new |
| adaLN_modulation[1]: Linear(cond, 3*embed) -- zero-pad in+out |
| """ |
| from vibevoice.modular.modular_vibevoice_diffusion_head import HeadLayer |
|
|
| |
| new_layer = HeadLayer( |
| embed_dim=new_embed_dim, |
| ffn_dim=new_ffn_dim, |
| cond_dim=new_cond_dim, |
| norm_eps=norm_eps, |
| ) |
| new_layer = new_layer.to( |
| device=old_layer.ffn.gate_proj.weight.device, |
| dtype=old_layer.ffn.gate_proj.weight.dtype, |
| ) |
|
|
| |
| new_layer.ffn.gate_proj = expand_linear_zero_pad( |
| old_layer.ffn.gate_proj, |
| new_in_features=new_embed_dim, |
| new_out_features=new_ffn_dim, |
| ) |
| new_layer.ffn.up_proj = expand_linear_zero_pad( |
| old_layer.ffn.up_proj, |
| new_in_features=new_embed_dim, |
| new_out_features=new_ffn_dim, |
| ) |
| new_layer.ffn.down_proj = expand_linear_zero_pad( |
| old_layer.ffn.down_proj, |
| new_in_features=new_ffn_dim, |
| new_out_features=new_embed_dim, |
| ) |
|
|
| |
| new_layer.norm = expand_rmsnorm(old_layer.norm, new_embed_dim, eps=norm_eps) |
|
|
| |
| new_layer.adaLN_modulation[1] = expand_linear_zero_pad( |
| old_layer.adaLN_modulation[1], |
| new_in_features=new_cond_dim, |
| new_out_features=3 * new_embed_dim, |
| ) |
|
|
| return new_layer |
|
|
|
|
| @torch.no_grad() |
| def expand_final_layer( |
| old_final: nn.Module, |
| new_hidden: int, |
| new_cond: int, |
| output_size: int, |
| norm_eps: float, |
| ) -> nn.Module: |
| """ |
| Expand FinalLayer(hidden, output, cond) to the new hidden/cond dims. |
| Structure: |
| norm_final: RMSNorm(hidden) (no affine) |
| linear: Linear(hidden, output_size) -- zero-pad input |
| adaLN_modulation[1]: Linear(cond, 2*hidden) -- zero-pad in+out |
| `output_size` (latent_size) is UNCHANGED. |
| """ |
| from vibevoice.modular.modular_vibevoice_diffusion_head import FinalLayer |
|
|
| new_final = FinalLayer( |
| hidden_size=new_hidden, |
| output_size=output_size, |
| cond_size=new_cond, |
| norm_eps=norm_eps, |
| ) |
| new_final = new_final.to( |
| device=old_final.linear.weight.device, |
| dtype=old_final.linear.weight.dtype, |
| ) |
|
|
| |
| |
| |
|
|
| |
| |
| new_final.linear = expand_linear_zero_pad( |
| old_final.linear, |
| new_in_features=new_hidden, |
| new_out_features=output_size, |
| ) |
|
|
| |
| new_final.adaLN_modulation[1] = expand_linear_zero_pad( |
| old_final.adaLN_modulation[1], |
| new_in_features=new_cond, |
| new_out_features=2 * new_hidden, |
| ) |
|
|
| return new_final |
|
|
|
|
| @torch.no_grad() |
| def expand_diffusion_head( |
| old_head: nn.Module, |
| new_hidden_size: int, |
| reinit_cond_proj: bool = True, |
| ) -> nn.Module: |
| """ |
| Expand a VibeVoiceDiffusionHead from old hidden_size to new_hidden_size. |
| The latent_size is UNCHANGED (still 64). |
| |
| Components: |
| noisy_images_proj: Linear(latent=64, hidden) -- zero-pad output |
| cond_proj: Linear(hidden, cond=hidden) -- RE-INITIALISE |
| t_embedder: TimestepEmbedder(cond=hidden) -- zero-pad |
| layers (4x HeadLayer): -- zero-pad |
| final_layer: FinalLayer(hidden, latent, cond) -- zero-pad |
| """ |
| from vibevoice.modular.modular_vibevoice_diffusion_head import ( |
| VibeVoiceDiffusionHead, |
| ) |
| from vibevoice.modular.configuration_vibevoice import ( |
| VibeVoiceDiffusionHeadConfig, |
| ) |
|
|
| old_hidden = old_head.config.hidden_size |
| latent_size = old_head.config.latent_size |
| head_layers = old_head.config.head_layers |
| head_ffn_ratio = old_head.config.head_ffn_ratio |
| rms_eps = old_head.config.rms_norm_eps |
|
|
| old_ffn_dim = int(old_hidden * head_ffn_ratio) |
| new_ffn_dim = int(new_hidden_size * head_ffn_ratio) |
|
|
| print(f" [diffusion_head] hidden_size: {old_hidden} -> {new_hidden_size}") |
| print(f" [diffusion_head] ffn_dim: {old_ffn_dim} -> {new_ffn_dim}") |
| print(f" [diffusion_head] latent_size: {latent_size} (unchanged)") |
| print(f" [diffusion_head] cond_proj reinit: {reinit_cond_proj}") |
|
|
| |
| new_cfg = VibeVoiceDiffusionHeadConfig( |
| hidden_size=new_hidden_size, |
| head_layers=head_layers, |
| head_ffn_ratio=head_ffn_ratio, |
| rms_norm_eps=rms_eps, |
| latent_size=latent_size, |
| speech_vae_dim=old_head.config.speech_vae_dim, |
| prediction_type=old_head.config.prediction_type, |
| diffusion_type=old_head.config.diffusion_type, |
| ddpm_num_steps=old_head.config.ddpm_num_steps, |
| ddpm_num_inference_steps=old_head.config.ddpm_num_inference_steps, |
| ddpm_beta_schedule=old_head.config.ddpm_beta_schedule, |
| ddpm_batch_mul=old_head.config.ddpm_batch_mul, |
| ) |
|
|
| |
| new_head = VibeVoiceDiffusionHead(new_cfg) |
| new_head = new_head.to( |
| device=old_head.noisy_images_proj.weight.device, |
| dtype=old_head.noisy_images_proj.weight.dtype, |
| ) |
|
|
| |
| new_head.noisy_images_proj = expand_linear_zero_pad( |
| old_head.noisy_images_proj, |
| new_in_features=latent_size, |
| new_out_features=new_hidden_size, |
| ) |
|
|
| |
| |
| if reinit_cond_proj: |
| print(f" [diffusion_head] cond_proj RE-INITIALISED (LLM hidden space changed)") |
| reinit_linear_like_old(new_head.cond_proj, std=0.02) |
| else: |
| new_head.cond_proj = expand_linear_zero_pad( |
| old_head.cond_proj, |
| new_in_features=new_hidden_size, |
| new_out_features=new_hidden_size, |
| ) |
|
|
| |
| new_head.t_embedder = expand_timestep_embedder(old_head.t_embedder, new_hidden_size) |
|
|
| |
| print(f" [diffusion_head] expanding {head_layers} HeadLayer modules...") |
| new_layers = nn.ModuleList() |
| for i, old_l in enumerate(old_head.layers): |
| new_l = expand_head_layer( |
| old_l, |
| new_embed_dim=new_hidden_size, |
| new_ffn_dim=new_ffn_dim, |
| new_cond_dim=new_hidden_size, |
| norm_eps=rms_eps, |
| ) |
| new_layers.append(new_l) |
| new_head.layers = new_layers |
|
|
| |
| new_head.final_layer = expand_final_layer( |
| old_head.final_layer, |
| new_hidden=new_hidden_size, |
| new_cond=new_hidden_size, |
| output_size=latent_size, |
| norm_eps=rms_eps, |
| ) |
|
|
| return new_head |
|
|
|
|
| |
| |
| |
|
|
| def load_qwen35_text_model( |
| repo: str = NEW_LLM_REPO, |
| torch_dtype: torch.dtype = torch.bfloat16, |
| cache_dir: Optional[str] = None, |
| low_cpu_mem_usage: bool = True, |
| ) -> Tuple[nn.Module, Any]: |
| """ |
| Load just the text decoder of Qwen3.5-4B-Base. |
| |
| The HF repo `Qwen/Qwen3.5-4B-Base` is multimodal |
| (`Qwen3_5ForConditionalGeneration`); we want the inner text model |
| (`Qwen3_5TextModel`, model_type='qwen3_5_text') WITHOUT the lm_head, so |
| that it can serve as `self.language_model` inside VibeVoiceModel (which |
| has its own `lm_head`). |
| |
| Returns (text_model, text_config). |
| """ |
| from transformers import AutoConfig, AutoModel |
| from transformers.models.auto import CONFIG_MAPPING |
|
|
| print(f"[qwen3.5] Loading full config from {repo}") |
| full_config = AutoConfig.from_pretrained(repo, cache_dir=cache_dir, trust_remote_code=True) |
|
|
| |
| if hasattr(full_config, "text_config"): |
| text_config_dict = full_config.text_config.to_dict() |
| else: |
| text_config_dict = full_config.to_dict() |
|
|
| print(f"[qwen3.5] Text model_type: {text_config_dict.get('model_type')}") |
| print(f"[qwen3.5] Text hidden_size: {text_config_dict.get('hidden_size')}") |
| print(f"[qwen3.5] Text num_hidden_layers: {text_config_dict.get('num_hidden_layers')}") |
| print(f"[qwen3.5] Text vocab_size: {text_config_dict.get('vocab_size')}") |
|
|
| |
| text_model_type = text_config_dict.get("model_type", "qwen3_5_text") |
|
|
| text_model = None |
| load_error = None |
|
|
| |
| try: |
| from transformers.models.auto import MODEL_MAPPING |
| |
| |
| text_config = full_config.text_config if hasattr(full_config, "text_config") else full_config |
| |
| text_model = AutoModel.from_pretrained( |
| repo, |
| config=text_config, |
| torch_dtype=torch_dtype, |
| cache_dir=cache_dir, |
| low_cpu_mem_usage=low_cpu_mem_usage, |
| trust_remote_code=True, |
| ) |
| print(f"[qwen3.5] Loaded via AutoModel.from_pretrained") |
| except Exception as e: |
| load_error = e |
| print(f"[qwen3.5] AutoModel failed: {e}") |
|
|
| |
| |
| if text_model is None: |
| try: |
| from transformers import AutoModelForCausalLM |
| print(f"[qwen3.5] Falling back to AutoModelForCausalLM...") |
| full_model = AutoModelForCausalLM.from_pretrained( |
| repo, |
| torch_dtype=torch_dtype, |
| cache_dir=cache_dir, |
| low_cpu_mem_usage=low_cpu_mem_usage, |
| trust_remote_code=True, |
| ) |
| |
| if hasattr(full_model, "model") and not hasattr(full_model, "text_model"): |
| text_model = full_model.model |
| |
| full_model.lm_head = None |
| elif hasattr(full_model, "text_model"): |
| text_model = full_model.text_model |
| else: |
| |
| text_model = full_model |
| print(f"[qwen3.5] Loaded via AutoModelForCausalLM, " |
| f"text_model class = {type(text_model).__name__}") |
| del full_model |
| gc.collect() |
| except Exception as e: |
| raise RuntimeError( |
| f"Could not load Qwen3.5-4B-Base text model. " |
| f"AutoModel error: {load_error}; AutoModelForCausalLM error: {e}" |
| ) |
|
|
| |
| if hasattr(text_model, "text_model"): |
| text_model = text_model.text_model |
|
|
| text_config = ( |
| full_config.text_config if hasattr(full_config, "text_config") else full_config |
| ) |
| return text_model, text_config |
|
|
|
|
| @torch.no_grad() |
| def replace_llm_in_vibevoice( |
| vibevoice_model: nn.Module, |
| new_text_model: nn.Module, |
| new_text_config: Any, |
| ) -> nn.Module: |
| """ |
| Replace `vibevoice_model.model.language_model` with `new_text_model` and |
| resize `vibevoice_model.lm_head` to the new vocab/hidden sizes. |
| |
| The old LLM and old lm_head are dropped (returned to caller for memory |
| management). |
| """ |
| |
| old_llm = vibevoice_model.model.language_model |
| old_lm_head = vibevoice_model.lm_head |
|
|
| |
| target_dtype = next(vibevoice_model.parameters()).dtype |
| target_device = next(vibevoice_model.parameters()).device |
| new_text_model = new_text_model.to(device=target_device, dtype=target_dtype) |
|
|
| |
| vibevoice_model.model.language_model = new_text_model |
|
|
| |
| new_hidden = new_text_config.hidden_size |
| new_vocab = new_text_config.vocab_size |
| print(f"[replace_llm] New lm_head: Linear({new_hidden}, {new_vocab}, bias=False)") |
| new_lm_head = nn.Linear(new_hidden, new_vocab, bias=False).to( |
| device=target_device, dtype=target_dtype |
| ) |
|
|
| |
| tie = getattr(vibevoice_model.config.decoder_config, "tie_word_embeddings", True) |
| if tie: |
| |
| if hasattr(new_text_model, "embed_tokens"): |
| embed = new_text_model.embed_tokens |
| else: |
| |
| embed = None |
| for n, m in new_text_model.named_modules(): |
| if "embed_tokens" in n: |
| embed = m |
| break |
| if embed is None: |
| raise RuntimeError("Could not find embed_tokens in the new text model.") |
| new_lm_head.weight = embed.weight |
| print(f"[replace_llm] Tied lm_head.weight to embed_tokens.weight") |
| else: |
| |
| |
| warnings.warn("tie_word_embeddings=False but no pretrained lm_head passed; " |
| "lm_head will be randomly initialised.") |
|
|
| vibevoice_model.lm_head = new_lm_head |
| vibevoice_model.vocab_size = new_vocab |
|
|
| return vibevoice_model |
|
|
|
|
| |
| |
| |
|
|
| def build_new_vibevoice_config( |
| old_config: Any, |
| new_text_config: Any, |
| ) -> Any: |
| """ |
| Build a new VibeVoiceConfig where: |
| - decoder_config is replaced with the Qwen3.5 text config |
| - diffusion_head_config.hidden_size is bumped to new_text_config.hidden_size |
| - acoustic_tokenizer_config / semantic_tokenizer_config are UNCHANGED |
| - vocab_size is updated to the new vocab |
| - tie_word_embeddings matches the new LLM's setting |
| """ |
| from vibevoice.modular.configuration_vibevoice import ( |
| VibeVoiceConfig, |
| VibeVoiceDiffusionHeadConfig, |
| ) |
|
|
| new_hidden = new_text_config.hidden_size |
| new_vocab = new_text_config.vocab_size |
|
|
| |
| |
| |
| text_cfg_dict = new_text_config.to_dict() if hasattr(new_text_config, "to_dict") else dict(new_text_config) |
|
|
| |
| old_diff_cfg = old_config.diffusion_head_config |
| new_diff_cfg = VibeVoiceDiffusionHeadConfig( |
| hidden_size=new_hidden, |
| head_layers=old_diff_cfg.head_layers, |
| head_ffn_ratio=old_diff_cfg.head_ffn_ratio, |
| rms_norm_eps=old_diff_cfg.rms_norm_eps, |
| latent_size=old_diff_cfg.latent_size, |
| speech_vae_dim=old_diff_cfg.speech_vae_dim, |
| prediction_type=old_diff_cfg.prediction_type, |
| diffusion_type=old_diff_cfg.diffusion_type, |
| ddpm_num_steps=old_diff_cfg.ddpm_num_steps, |
| ddpm_num_inference_steps=old_diff_cfg.ddpm_num_inference_steps, |
| ddpm_beta_schedule=old_diff_cfg.ddpm_beta_schedule, |
| ddpm_batch_mul=old_diff_cfg.ddpm_batch_mul, |
| ) |
|
|
| |
| |
| |
| new_config = VibeVoiceConfig( |
| acoustic_tokenizer_config=old_config.acoustic_tokenizer_config.to_dict() |
| if hasattr(old_config.acoustic_tokenizer_config, "to_dict") |
| else dict(old_config.acoustic_tokenizer_config), |
| semantic_tokenizer_config=old_config.semantic_tokenizer_config.to_dict() |
| if hasattr(old_config.semantic_tokenizer_config, "to_dict") |
| else dict(old_config.semantic_tokenizer_config), |
| decoder_config=None, |
| diffusion_head_config=new_diff_cfg.to_dict() |
| if hasattr(new_diff_cfg, "to_dict") |
| else dict(new_diff_cfg.__dict__), |
| ) |
|
|
| |
| |
| |
| new_config.decoder_config = new_text_config |
|
|
| |
| new_config.vocab_size = new_vocab |
| new_config.tie_word_embeddings = bool( |
| getattr(new_text_config, "tie_word_embeddings", True) |
| ) |
| new_config.acoustic_vae_dim = getattr(old_config, "acoustic_vae_dim", ACOUSTIC_VAE_DIM) |
| new_config.semantic_vae_dim = getattr(old_config, "semantic_vae_dim", SEMANTIC_VAE_DIM) |
| new_config.torch_dtype = "bfloat16" |
| new_config._attn_implementation_autoset = False |
|
|
| return new_config |
|
|
|
|
| |
| |
| |
|
|
| def perform_surgery( |
| old_checkpoint_path: Union[str, Path], |
| vibevoice_repo_dir: Union[str, Path], |
| output_dir: Union[str, Path], |
| new_llm_repo: str = NEW_LLM_REPO, |
| torch_dtype: torch.dtype = torch.bfloat16, |
| reinit_cond_proj: bool = True, |
| hf_cache_dir: Optional[str] = None, |
| skip_llm_download: bool = False, |
| fake_new_llm: bool = False, |
| ) -> SurgeryReport: |
| """ |
| End-to-end surgery: load old VibeVoice, swap LLM, expand connectors and |
| diffusion head, save the result. |
| |
| Args: |
| old_checkpoint_path: path to the original VibeVoice HF directory |
| (containing config.json + *.safetensors). |
| vibevoice_repo_dir: path to the directory *containing* the |
| `vibevoice/` Python package (so we can import it). |
| output_dir: where to save the surgically-modified model. |
| new_llm_repo: HF repo id for the new LLM. Defaults to Qwen3.5-4B-Base. |
| torch_dtype: dtype to use throughout. bf16 by default (T4-friendly). |
| reinit_cond_proj: whether to re-initialise the diffusion head's |
| cond_proj (recommended when swapping LLMs across families). |
| hf_cache_dir: optional HF cache dir for model downloads. |
| skip_llm_download: if True, do not download Qwen3.5 (used for tests |
| that only verify the surgery primitives). |
| fake_new_llm: if True, build a randomly-initialised text model with |
| the right shape (used for tests that don't need the real LLM). |
| |
| Returns: |
| SurgeryReport with details about what was done. |
| """ |
| output_dir = Path(output_dir) |
| output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| |
| print("\n[1/8] Setting up VibeVoice imports...") |
| setup_vibevoice_imports(vibevoice_repo_dir) |
|
|
| from vibevoice.modular.configuration_vibevoice import VibeVoiceConfig |
| from vibevoice.modular.modeling_vibevoice import VibeVoiceForConditionalGeneration |
|
|
| |
| print(f"\n[2/8] Loading original VibeVoice from {old_checkpoint_path}...") |
| |
| |
| |
| old_model = VibeVoiceForConditionalGeneration.from_pretrained( |
| old_checkpoint_path, |
| dtype=torch_dtype, |
| low_cpu_mem_usage=False, |
| ) |
| old_model.eval() |
| old_config = old_model.config |
| old_total_params = sum(p.numel() for p in old_model.parameters()) |
| print(f" Old model loaded. Total params: {old_total_params:,}") |
| print(f" Old LLM hidden: {old_config.decoder_config.hidden_size}") |
| print(f" Old vocab: {old_config.decoder_config.vocab_size}") |
|
|
| |
| if skip_llm_download: |
| print("\n[3/8] Skipping Qwen3.5 download (skip_llm_download=True).") |
| new_text_model = None |
| |
| from transformers.models.qwen3_5 import Qwen3_5TextConfig |
| new_text_config = Qwen3_5TextConfig( |
| hidden_size=NEW_LLM_HIDDEN_SIZE, |
| num_hidden_layers=NEW_LLM_LAYERS, |
| vocab_size=NEW_LLM_VOCAB, |
| intermediate_size=NEW_LLM_INTERMEDIATE, |
| num_attention_heads=NEW_LLM_HEADS, |
| num_key_value_heads=NEW_LLM_KV_HEADS, |
| tie_word_embeddings=True, |
| ) |
| elif fake_new_llm: |
| print("\n[3/8] Building a FAKE Qwen3.5 text model (for testing only).") |
| from transformers.models.qwen3_5 import Qwen3_5TextConfig, Qwen3_5TextModel |
| new_text_config = Qwen3_5TextConfig( |
| hidden_size=NEW_LLM_HIDDEN_SIZE, |
| num_hidden_layers=NEW_LLM_LAYERS, |
| vocab_size=NEW_LLM_VOCAB, |
| intermediate_size=NEW_LLM_INTERMEDIATE, |
| num_attention_heads=NEW_LLM_HEADS, |
| num_key_value_heads=NEW_LLM_KV_HEADS, |
| tie_word_embeddings=True, |
| ) |
| new_text_model = Qwen3_5TextModel(new_text_config).to(torch_dtype) |
| else: |
| print(f"\n[3/8] Loading Qwen3.5-4B-Base text model from {new_llm_repo}...") |
| new_text_model, new_text_config = load_qwen35_text_model( |
| repo=new_llm_repo, |
| torch_dtype=torch_dtype, |
| cache_dir=hf_cache_dir, |
| low_cpu_mem_usage=True, |
| ) |
| print(f" New LLM hidden: {new_text_config.hidden_size}") |
| print(f" New LLM layers: {new_text_config.num_hidden_layers}") |
| print(f" New vocab: {new_text_config.vocab_size}") |
|
|
| |
| print("\n[4/8] Building new VibeVoiceConfig...") |
| new_config = build_new_vibevoice_config(old_config, new_text_config) |
|
|
| |
| |
| |
| print("\n[5/8] Building new VibeVoice skeleton with new config...") |
| |
| prev_default = torch.get_default_dtype() |
| torch.set_default_dtype(torch_dtype) |
| new_model = VibeVoiceForConditionalGeneration(new_config) |
| torch.set_default_dtype(prev_default) |
| new_model.eval() |
|
|
| |
| print("\n[6/8] Transplanting weights...") |
|
|
| expanded_modules: List[str] = [] |
| reinit_modules: List[str] = [] |
| preserved_modules: List[str] = [] |
|
|
| |
| print(" -> Acoustic tokenizer (UNCHANGED)") |
| new_model.model.acoustic_tokenizer.load_state_dict( |
| old_model.model.acoustic_tokenizer.state_dict(), strict=True |
| ) |
| preserved_modules.append("model.acoustic_tokenizer") |
|
|
| |
| print(" -> Semantic tokenizer (UNCHANGED)") |
| new_model.model.semantic_tokenizer.load_state_dict( |
| old_model.model.semantic_tokenizer.state_dict(), strict=True |
| ) |
| preserved_modules.append("model.semantic_tokenizer") |
|
|
| |
| print(" -> Acoustic connector (width-expand)") |
| new_model.model.acoustic_connector = expand_speech_connector( |
| old_model.model.acoustic_connector, |
| new_output_dim=new_text_config.hidden_size, |
| name="acoustic_connector", |
| ).to(dtype=torch_dtype) |
| expanded_modules.append("model.acoustic_connector") |
|
|
| |
| print(" -> Semantic connector (width-expand)") |
| new_model.model.semantic_connector = expand_speech_connector( |
| old_model.model.semantic_connector, |
| new_output_dim=new_text_config.hidden_size, |
| name="semantic_connector", |
| ).to(dtype=torch_dtype) |
| expanded_modules.append("model.semantic_connector") |
|
|
| |
| new_model.model.speech_scaling_factor.data.copy_( |
| old_model.model.speech_scaling_factor.data |
| ) |
| new_model.model.speech_bias_factor.data.copy_( |
| old_model.model.speech_bias_factor.data |
| ) |
|
|
| |
| print(" -> Diffusion head (width-expand)") |
| new_model.model.prediction_head = expand_diffusion_head( |
| old_model.model.prediction_head, |
| new_hidden_size=new_text_config.hidden_size, |
| reinit_cond_proj=reinit_cond_proj, |
| ).to(dtype=torch_dtype) |
| expanded_modules.append("model.prediction_head") |
| if reinit_cond_proj: |
| reinit_modules.append("model.prediction_head.cond_proj") |
|
|
| |
| print(" -> Language model (REPLACE with Qwen3.5)") |
| if new_text_model is None and not skip_llm_download: |
| raise RuntimeError("new_text_model is None but skip_llm_download=False") |
| if new_text_model is not None: |
| new_model = replace_llm_in_vibevoice( |
| new_model, new_text_model, new_text_config |
| ) |
| reinit_modules.append("model.language_model (replaced)") |
|
|
| |
| preserved_modules.append("lm_head (tied with embed_tokens)") |
|
|
| |
| del old_model |
| gc.collect() |
|
|
| new_total_params = sum(p.numel() for p in new_model.parameters()) |
| print(f"\n New total params: {new_total_params:,}") |
|
|
| |
| print(f"\n[7/8] Saving surgically modified model to {output_dir}...") |
| new_model.save_pretrained( |
| output_dir, |
| max_shard_size="2GB", |
| safe_serialization=True, |
| ) |
| new_config.save_pretrained(output_dir) |
|
|
| |
| print("\n[8/8] Building surgery report...") |
| report = SurgeryReport( |
| old_llm_hidden=old_config.decoder_config.hidden_size, |
| new_llm_hidden=new_text_config.hidden_size, |
| old_vocab=old_config.decoder_config.vocab_size, |
| new_vocab=new_text_config.vocab_size, |
| expanded_modules=expanded_modules, |
| reinitialized_modules=reinit_modules, |
| preserved_modules=preserved_modules, |
| total_params_before=old_total_params, |
| total_params_after=new_total_params, |
| output_dir=str(output_dir), |
| ) |
| print(report.summary()) |
|
|
| report_path = output_dir / "surgery_report.json" |
| with open(report_path, "w") as f: |
| json.dump({ |
| "old_llm_hidden": report.old_llm_hidden, |
| "new_llm_hidden": report.new_llm_hidden, |
| "old_vocab": report.old_vocab, |
| "new_vocab": report.new_vocab, |
| "expanded_modules": report.expanded_modules, |
| "reinitialized_modules": report.reinitialized_modules, |
| "preserved_modules": report.preserved_modules, |
| "total_params_before": report.total_params_before, |
| "total_params_after": report.total_params_after, |
| "output_dir": report.output_dir, |
| }, f, indent=2) |
| print(f" Report saved to {report_path}") |
|
|
| return report |
|
|
|
|
| |
| |
| |
|
|
| def verify_surgery( |
| model_dir: Union[str, Path], |
| vibevoice_repo_dir: Union[str, Path], |
| torch_dtype: torch.dtype = torch.bfloat16, |
| device: str = "cuda" if torch.cuda.is_available() else "cpu", |
| ) -> Dict[str, Any]: |
| """ |
| Load the surgically-modified model and run a tiny forward pass to verify |
| there are no shape errors. Returns a dict with key diagnostics. |
| """ |
| print(f"\n[verify] Loading surgically modified model from {model_dir}...") |
| setup_vibevoice_imports(vibevoice_repo_dir) |
|
|
| from vibevoice.modular.modeling_vibevoice import VibeVoiceForConditionalGeneration |
|
|
| model = VibeVoiceForConditionalGeneration.from_pretrained( |
| model_dir, |
| dtype=torch_dtype, |
| low_cpu_mem_usage=False, |
| ) |
| model.to(device) |
| model.eval() |
|
|
| print(f" Model device: {next(model.parameters()).device}") |
| print(f" Model dtype: {next(model.parameters()).dtype}") |
| print(f" Vocab size: {model.config.decoder_config.vocab_size}") |
| print(f" Hidden size: {model.config.decoder_config.hidden_size}") |
| print(f" Diffusion hidden: {model.config.diffusion_head_config.hidden_size}") |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| print(" Running a tiny forward pass (with dummy speech tensors)...") |
| batch = 1 |
| seq_len = 8 |
| input_ids = torch.randint( |
| 0, model.config.decoder_config.vocab_size, (batch, seq_len), |
| device=device |
| ) |
| attention_mask = torch.ones_like(input_ids) |
| sem_vae_dim = model.config.semantic_vae_dim |
| speech_semantic_tensors = torch.zeros(batch, seq_len, sem_vae_dim, |
| device=device, dtype=torch_dtype) |
| speech_tensors = torch.zeros(batch, 3200, device=device, dtype=torch_dtype) |
|
|
| |
| |
| |
| n_frames = None |
| encode_dtype_candidates: List[torch.dtype] = [] |
| if hasattr(model, "dtype") and model.dtype is not None: |
| encode_dtype_candidates.append(model.dtype) |
| try: |
| tok_dtype = next(model.model.acoustic_tokenizer.parameters()).dtype |
| if tok_dtype not in encode_dtype_candidates: |
| encode_dtype_candidates.append(tok_dtype) |
| except StopIteration: |
| pass |
| for fallback_dtype in (torch.bfloat16, torch.float32): |
| if fallback_dtype not in encode_dtype_candidates: |
| encode_dtype_candidates.append(fallback_dtype) |
|
|
| for try_dtype in encode_dtype_candidates: |
| try: |
| with torch.no_grad(): |
| enc_in = speech_tensors.unsqueeze(1).to(dtype=try_dtype) |
| enc_out = model.model.acoustic_tokenizer.encode(enc_in) |
| n_frames = enc_out.mean.shape[1] |
| print(f" Acoustic tokenizer produced {n_frames} frames from " |
| f"{speech_tensors.shape[-1]} samples (dtype={try_dtype})") |
| break |
| except Exception as e: |
| print(f" Pre-compute with dtype={try_dtype} failed: " |
| f"{type(e).__name__}: {e}") |
|
|
| full_forward_ok = False |
| if n_frames is not None and n_frames > 0: |
| |
| |
| |
| |
| |
| n_to_set = min(n_frames, seq_len - 1) |
| if n_to_set > 0: |
| speech_masks = torch.zeros(batch, n_frames, |
| dtype=torch.bool, device=device) |
| speech_masks[:, :n_to_set] = True |
| acoustic_input_mask = torch.zeros_like(input_ids, dtype=torch.bool) |
| acoustic_input_mask[0, 1:1 + n_to_set] = True |
| acoustic_loss_mask = torch.zeros_like(input_ids, dtype=torch.bool) |
| speeches_loss_input = torch.zeros_like(input_ids, dtype=torch.bool) |
|
|
| try: |
| with torch.no_grad(): |
| out = model( |
| input_ids=input_ids, |
| attention_mask=attention_mask, |
| speech_tensors=speech_tensors, |
| speech_masks=speech_masks, |
| speech_semantic_tensors=speech_semantic_tensors, |
| acoustic_input_mask=acoustic_input_mask, |
| acoustic_loss_mask=acoustic_loss_mask, |
| speeches_loss_input=speeches_loss_input, |
| return_dict=True, |
| use_cache=False, |
| ) |
| logits = out.logits |
| assert logits.shape == (batch, seq_len, model.config.decoder_config.vocab_size), ( |
| f"Logits shape mismatch: {logits.shape}" |
| ) |
| print(f" Full forward pass OK. Logits shape: {tuple(logits.shape)}") |
| full_forward_ok = True |
| except Exception as e: |
| print(f" Full forward pass failed (expected for dummy inputs): " |
| f"{type(e).__name__}: {e}") |
| print(f" Falling back to inner model forward pass (no speech processing)...") |
| else: |
| print(f" n_frames={n_frames} but seq_len={seq_len} too small; " |
| f"skipping full forward pass.") |
| else: |
| print(f" Could not pre-compute n_frames; skipping full forward pass.") |
|
|
| if not full_forward_ok: |
| |
| with torch.no_grad(): |
| inner_out = model.model( |
| input_ids=input_ids, |
| attention_mask=attention_mask, |
| return_dict=True, |
| use_cache=False, |
| ) |
| hidden_states = inner_out.last_hidden_state |
| assert hidden_states.shape == (batch, seq_len, model.config.decoder_config.hidden_size), ( |
| f"Hidden states shape mismatch: {hidden_states.shape}" |
| ) |
| |
| logits = model.lm_head(hidden_states) |
| assert logits.shape == (batch, seq_len, model.config.decoder_config.vocab_size), ( |
| f"Logits shape mismatch: {logits.shape}" |
| ) |
| print(f" Inner model forward OK. Logits shape: {tuple(logits.shape)}") |
|
|
| |
| print(" Running diffusion head smoke test...") |
| latent_size = model.config.diffusion_head_config.latent_size |
| new_hidden = model.config.diffusion_head_config.hidden_size |
| noisy = torch.randn(2, latent_size, device=device, dtype=torch_dtype) |
| t = torch.tensor([10, 500], device=device, dtype=torch_dtype) |
| cond = torch.randn(2, new_hidden, device=device, dtype=torch_dtype) |
| with torch.no_grad(): |
| pred = model.model.prediction_head(noisy, t, cond) |
| assert pred.shape == (2, latent_size), f"Diffusion head shape mismatch: {pred.shape}" |
| print(f" Diffusion head output shape: {tuple(pred.shape)} OK") |
|
|
| |
| print(" Running connector smoke test...") |
| acoustic_in = torch.randn(3, ACOUSTIC_VAE_DIM, device=device, dtype=torch_dtype) |
| acoustic_out = model.model.acoustic_connector(acoustic_in) |
| assert acoustic_out.shape == (3, new_hidden), acoustic_out.shape |
| print(f" Acoustic connector: {ACOUSTIC_VAE_DIM} -> {tuple(acoustic_out.shape)[-1]} OK") |
|
|
| semantic_in = torch.randn(3, SEMANTIC_VAE_DIM, device=device, dtype=torch_dtype) |
| semantic_out = model.model.semantic_connector(semantic_in) |
| assert semantic_out.shape == (3, new_hidden), semantic_out.shape |
| print(f" Semantic connector: {SEMANTIC_VAE_DIM} -> {tuple(semantic_out.shape)[-1]} OK") |
|
|
| |
| print(" Verifying zero-padding of expanded layers...") |
| fc1_w = model.model.acoustic_connector.fc1.weight.data |
| old_hidden = OLD_LLM_HIDDEN_SIZE |
| new_rows = fc1_w[old_hidden:, :] |
| max_abs_new = new_rows.abs().max().item() |
| print(f" Acoustic connector fc1 new-output max |w|: {max_abs_new:.2e} " |
| f"({'OK' if max_abs_new < 1e-8 else 'NOT ZERO'})") |
|
|
| return { |
| "logits_shape": list(logits.shape), |
| "diffusion_output_shape": list(pred.shape), |
| "acoustic_connector_out_shape": list(acoustic_out.shape), |
| "semantic_connector_out_shape": list(semantic_out.shape), |
| "acoustic_fc1_new_rows_max_abs": max_abs_new, |
| "vocab_size": model.config.decoder_config.vocab_size, |
| "hidden_size": model.config.decoder_config.hidden_size, |
| "diffusion_hidden_size": new_hidden, |
| } |
|
|
|
|
| |
| |
| |
|
|
| def extract_audio_array( |
| outputs: Any, |
| ) -> Tuple[Optional["np.ndarray"], Optional[int]]: |
| """ |
| Extract the first valid audio waveform from a VibeVoice generation output |
| as a contiguous, 1-D float32 numpy array suitable for `soundfile.write`. |
| |
| VibeVoice's `generate()` returns a `VibeVoiceGenerationOutput` whose |
| `speech_outputs` field is a `List[Optional[Tensor]]` (see |
| modeling_vibevoice_inference.py:679-693). An entry is: |
| * None -> when that sample never emitted a `speech_diffusion_id` token, |
| so no audio chunks were collected for it. This is the normal |
| case for an un-fine-tuned model that collapses to EOS. |
| * Tensor -> the concatenated 1-D / 2-D waveform for that sample. |
| |
| This helper scans the list and returns the first non-None entry, converted |
| to float32. Returns (None, None) when no sample produced audio. |
| |
| Robustness notes: |
| * Skips None and empty entries (a `[None]` list is truthy, so the naive |
| `if outputs.speech_outputs:` check is NOT enough -- that was the root |
| cause of the original soundfile "dtype object" crash). |
| * Handles torch tensors (CPU or CUDA, any float dtype incl. bfloat16). |
| bfloat16 has no numpy equivalent, so we upcast to float32 first. |
| * Handles raw numpy arrays and python lists/tuples of numbers too. |
| * Flattens to 1-D (soundfile writes mono waveforms). |
| * NaN/Inf are replaced with 0 so a single bad sample can't abort the write. |
| """ |
| import numpy as np |
|
|
| speech_outputs = getattr(outputs, "speech_outputs", None) |
| if not speech_outputs: |
| return None, None |
|
|
| |
| |
| if not hasattr(outputs, "speech_outputs"): |
| candidates = [outputs] |
| else: |
| candidates = speech_outputs |
|
|
| for idx, wav in enumerate(candidates): |
| arr = None |
| if isinstance(wav, torch.Tensor): |
| |
| wav = wav.detach() |
| if wav.dtype != torch.float32 and wav.dtype != torch.float64: |
| wav = wav.float() |
| |
| arr = wav.cpu().numpy() |
| elif isinstance(wav, np.ndarray): |
| |
| if wav.dtype == object: |
| continue |
| if wav.dtype != np.float32 and wav.dtype != np.float64: |
| arr = wav.astype(np.float32) |
| else: |
| arr = wav |
| elif isinstance(wav, (list, tuple)): |
| try: |
| arr = np.asarray(wav, dtype=np.float32) |
| except (ValueError, TypeError): |
| continue |
| else: |
| |
| continue |
|
|
| |
| if arr is None or arr.size == 0: |
| continue |
|
|
| |
| arr = np.ascontiguousarray(arr.reshape(-1), dtype=np.float32) |
| if not np.all(np.isfinite(arr)): |
| arr = np.nan_to_num(arr, nan=0.0, posinf=0.0, neginf=0.0) |
|
|
| return arr, idx |
|
|
| return None, None |
|
|
|
|
| def test_audio_generation( |
| model_dir: Union[str, Path], |
| vibevoice_repo_dir: Union[str, Path], |
| text: str = "Hello, this is a test of the surgically modified VibeVoice model.", |
| output_wav_path: Union[str, Path] = "/home/z/my-project/download/test_audio.wav", |
| torch_dtype: torch.dtype = torch.bfloat16, |
| device: str = "cuda" if torch.cuda.is_available() else "cpu", |
| max_new_tokens: int = 200, |
| ) -> Dict[str, Any]: |
| """ |
| Load the inference variant of the surgically modified model and try to |
| generate audio from text. Because the surgically-modified model has not |
| yet been fine-tuned on speech data, the audio will be garbled -- this is |
| purely a smoke test that the generation pipeline runs end-to-end. |
| |
| The function tries multiple import strategies because different VibeVoice |
| repo forks ship different inference modules: |
| 1. modeling_vibevoice_inference.VibeVoiceForConditionalGenerationInference |
| (older forks / the user's original zip) |
| 2. modeling_vibevoice_streaming_inference.VibeVoiceStreamingForConditionalGenerationInference |
| (official Microsoft VibeVoice repo) |
| 3. Fallback: modeling_vibevoice.VibeVoiceForConditionalGeneration |
| (base model, no generate() — just a forward-pass smoke test) |
| """ |
| print(f"\n[gen] Loading inference model from {model_dir}...") |
| setup_vibevoice_imports(vibevoice_repo_dir) |
|
|
| |
| inference_cls = None |
| inference_type = None |
|
|
| |
| try: |
| from vibevoice.modular.modeling_vibevoice_inference import ( |
| VibeVoiceForConditionalGenerationInference, |
| ) |
| inference_cls = VibeVoiceForConditionalGenerationInference |
| inference_type = "non_streaming" |
| print(f" [import] Using VibeVoiceForConditionalGenerationInference " |
| f"from modeling_vibevoice_inference") |
| except ImportError as e1: |
| print(f" [import] modeling_vibevoice_inference not available: {e1}") |
|
|
| |
| if inference_cls is None: |
| try: |
| from vibevoice.modular.modeling_vibevoice_streaming_inference import ( |
| VibeVoiceStreamingForConditionalGenerationInference, |
| ) |
| inference_cls = VibeVoiceStreamingForConditionalGenerationInference |
| inference_type = "streaming" |
| print(f" [import] Using VibeVoiceStreamingForConditionalGenerationInference " |
| f"from modeling_vibevoice_streaming_inference") |
| except ImportError as e2: |
| print(f" [import] modeling_vibevoice_streaming_inference not available: {e2}") |
|
|
| |
| if inference_cls is None: |
| print(f" [import] No inference class found. Falling back to base model.") |
| from vibevoice.modular.modeling_vibevoice import ( |
| VibeVoiceForConditionalGeneration, |
| ) |
| inference_cls = VibeVoiceForConditionalGeneration |
| inference_type = "base_only" |
|
|
| |
| try: |
| model = inference_cls.from_pretrained( |
| model_dir, |
| dtype=torch_dtype, |
| low_cpu_mem_usage=False, |
| ) |
| model.to(device) |
| model.eval() |
| print(f" Model loaded ({inference_type} variant).") |
| print(f" Model device: {next(model.parameters()).device}") |
| except Exception as e: |
| print(f" Model loading failed: {type(e).__name__}: {e}") |
| import traceback |
| traceback.print_exc() |
| return {"status": "error", "error": f"Model loading failed: {type(e).__name__}: {e}"} |
|
|
| |
| print(" Loading tokenizer from Qwen3.5-4B-Base...") |
| try: |
| from vibevoice.modular.modular_vibevoice_text_tokenizer import ( |
| VibeVoiceTextTokenizerFast, |
| ) |
| tokenizer = VibeVoiceTextTokenizerFast.from_pretrained(NEW_LLM_REPO) |
| print(f" Tokenizer vocab size: {tokenizer.vocab_size}") |
| except Exception as e: |
| print(f" Tokenizer loading failed: {type(e).__name__}: {e}") |
| import traceback |
| traceback.print_exc() |
| return {"status": "error", "error": f"Tokenizer loading failed: {type(e).__name__}: {e}"} |
|
|
| |
| system_prompt = ( |
| " Transform the text provided by various speakers into speech output, " |
| "utilizing the distinct voice of each respective speaker.\n" |
| ) |
| full_text = system_prompt + text |
| inputs = tokenizer(full_text, return_tensors="pt") |
| input_ids = inputs["input_ids"].to(device) |
|
|
| |
| print(" Building fake reference audio (3 s of silence)...") |
| ref_audio = torch.zeros(1, 24000 * 3, device=device, dtype=torch.float32) |
| speech_tensors = ref_audio |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| print(" Encoding ref audio to determine n_frames...") |
| encode_dtype_candidates: List[torch.dtype] = [] |
| |
| if hasattr(model, "dtype") and model.dtype is not None: |
| encode_dtype_candidates.append(model.dtype) |
| |
| try: |
| tok_dtype = next(model.model.acoustic_tokenizer.parameters()).dtype |
| if tok_dtype not in encode_dtype_candidates: |
| encode_dtype_candidates.append(tok_dtype) |
| except StopIteration: |
| pass |
| |
| try: |
| conn_dtype = next(model.model.acoustic_connector.parameters()).dtype |
| if conn_dtype not in encode_dtype_candidates: |
| encode_dtype_candidates.append(conn_dtype) |
| except StopIteration: |
| pass |
| |
| for fallback_dtype in (torch.bfloat16, torch.float32): |
| if fallback_dtype not in encode_dtype_candidates: |
| encode_dtype_candidates.append(fallback_dtype) |
|
|
| print(f" Will try encode dtypes: " |
| f"{[str(d) for d in encode_dtype_candidates]}") |
|
|
| n_frames = None |
| last_err: Optional[Exception] = None |
| for try_dtype in encode_dtype_candidates: |
| try: |
| with torch.no_grad(): |
| |
| enc_input = speech_tensors.unsqueeze(1).to(dtype=try_dtype) |
| enc_out = model.model.acoustic_tokenizer.encode(enc_input) |
| |
| |
| n_frames = enc_out.mean.shape[1] |
| print(f" Acoustic tokenizer produced {n_frames} frames from " |
| f"{speech_tensors.shape[-1]} samples (dtype={try_dtype})") |
| last_err = None |
| break |
| except Exception as e: |
| last_err = e |
| print(f" Pre-compute with dtype={try_dtype} failed: " |
| f"{type(e).__name__}: {e}") |
|
|
| |
| |
| |
| |
| |
| if n_frames is None or n_frames <= 0: |
| msg = ( |
| f"Could not pre-compute n_frames after trying dtypes " |
| f"{[str(d) for d in encode_dtype_candidates]}. " |
| f"Last error: " |
| f"{type(last_err).__name__ if last_err else 'Unknown'}: {last_err}" |
| ) |
| print(f" ERROR: {msg}") |
| print(f" Aborting generation (the (1,1) fallback mask would cause " |
| f"an IndexError in _process_speech_inputs).") |
| return { |
| "status": "error", |
| "error": msg, |
| "inference_type": inference_type, |
| } |
|
|
| |
| |
| speech_input_mask = torch.zeros_like(input_ids, dtype=torch.bool) |
| n_to_set = min(n_frames, input_ids.shape[1] - 1) |
| if n_to_set <= 0: |
| msg = ( |
| f"Cannot fit any speech frames into the input sequence " |
| f"(n_frames={n_frames}, seq_len={input_ids.shape[1]}). " |
| f"Need seq_len >= 2." |
| ) |
| print(f" ERROR: {msg}") |
| return { |
| "status": "error", |
| "error": msg, |
| "inference_type": inference_type, |
| } |
| speech_input_mask[0, 1:1 + n_to_set] = True |
| print(f" speech_input_mask: {n_to_set} True positions " |
| f"(capped at seq_len-1={input_ids.shape[1]-1})") |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| speech_masks = torch.zeros(1, n_frames, dtype=torch.bool, device=device) |
| speech_masks[0, :n_to_set] = True |
| print(f" speech_masks: {n_to_set} True out of {n_frames} frames") |
| print(f" speech_masks shape: {tuple(speech_masks.shape)} " |
| f"(2D: batch x n_frames)") |
|
|
| print(f" Input ids shape: {tuple(input_ids.shape)}") |
|
|
| |
| if inference_type == "base_only": |
| print(f" Running forward-pass smoke test (base model has no generate())...") |
| try: |
| with torch.no_grad(): |
| out = model( |
| input_ids=input_ids, |
| attention_mask=torch.ones_like(input_ids), |
| speech_tensors=speech_tensors, |
| speech_masks=speech_masks, |
| speech_semantic_tensors=torch.zeros( |
| 1, input_ids.shape[1], SEMANTIC_VAE_DIM, |
| device=device, dtype=torch_dtype, |
| ), |
| acoustic_input_mask=speech_input_mask, |
| acoustic_loss_mask=torch.zeros_like(input_ids, dtype=torch.bool), |
| speeches_loss_input=torch.zeros_like(input_ids, dtype=torch.bool), |
| return_dict=True, |
| use_cache=False, |
| ) |
| print(f" Forward pass OK. Logits shape: {tuple(out.logits.shape)}") |
| return { |
| "status": "forward_only", |
| "logits_shape": list(out.logits.shape), |
| "note": "Base model has no generate() method; ran forward-pass only.", |
| } |
| except Exception as e: |
| print(f" Forward pass failed: {type(e).__name__}: {e}") |
| import traceback |
| traceback.print_exc() |
| return {"status": "error", "error": f"Forward pass failed: {type(e).__name__}: {e}"} |
|
|
| |
| print(f" Generating (max_new_tokens={max_new_tokens}, {inference_type} mode)...") |
|
|
| try: |
| with torch.no_grad(): |
| |
| |
| |
| |
| gen_kwargs = dict( |
| input_ids=input_ids, |
| attention_mask=torch.ones_like(input_ids), |
| speech_tensors=speech_tensors, |
| speech_masks=speech_masks, |
| speech_input_mask=speech_input_mask, |
| max_new_tokens=max_new_tokens, |
| do_sample=False, |
| return_speech=True, |
| tokenizer=tokenizer, |
| ) |
| outputs = model.generate(**gen_kwargs) |
| print(f" Generation finished.") |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| wav, audio_idx = extract_audio_array(outputs) |
| if wav is None: |
| print(" No speech outputs were generated (expected for an " |
| "un-fine-tuned model).") |
| return { |
| "status": "no_audio", |
| "sequence_len": int(outputs.sequences.shape[-1]) |
| if hasattr(outputs, "sequences") else 0, |
| "inference_type": inference_type, |
| } |
|
|
| |
| |
| import soundfile as sf |
| out_path = Path(output_wav_path) |
| out_path.parent.mkdir(parents=True, exist_ok=True) |
| sf.write(str(out_path), wav, 24000) |
| print(f" Audio written to {out_path} ({len(wav)} samples, " |
| f"from batch index {audio_idx})") |
| return { |
| "status": "ok", |
| "wav_path": str(out_path), |
| "num_samples": int(len(wav)), |
| "sequence_len": int(outputs.sequences.shape[-1]) |
| if hasattr(outputs, "sequences") else 0, |
| "inference_type": inference_type, |
| } |
| except Exception as e: |
| print(f" Generation failed: {type(e).__name__}: {e}") |
| import traceback |
| traceback.print_exc() |
| return {"status": "error", "error": f"{type(e).__name__}: {e}", "inference_type": inference_type} |
|
|
|
|
| |
| |
| |
|
|
| if __name__ == "__main__": |
| import argparse |
|
|
| p = argparse.ArgumentParser(description="VibeVoice LLM Surgery CLI") |
| sub = p.add_subparsers(dest="cmd", required=True) |
|
|
| sp = sub.add_parser("surgery", help="Run the full surgery") |
| sp.add_argument("--old-checkpoint", required=True, |
| help="Path to the original VibeVoice HF checkpoint directory") |
| sp.add_argument("--vibevoice-repo", required=True, |
| help="Path to the directory containing the vibevoice/ Python package") |
| sp.add_argument("--output-dir", required=True, |
| help="Where to save the surgically modified model") |
| sp.add_argument("--new-llm-repo", default=NEW_LLM_REPO) |
| sp.add_argument("--hf-cache-dir", default=None) |
| sp.add_argument("--keep-cond-proj", action="store_true", |
| help="Do NOT re-init the diffusion head's cond_proj (default: re-init)") |
| sp.add_argument("--fake-new-llm", action="store_true", |
| help="Use a randomly-initialised fake Qwen3.5 (for tests)") |
|
|
| vp = sub.add_parser("verify", help="Verify a surgically modified model") |
| vp.add_argument("--model-dir", required=True) |
| vp.add_argument("--vibevoice-repo", required=True) |
|
|
| gp = sub.add_parser("generate", help="Test audio generation") |
| gp.add_argument("--model-dir", required=True) |
| gp.add_argument("--vibevoice-repo", required=True) |
| gp.add_argument("--text", default="Hello, this is a test.") |
| gp.add_argument("--output-wav", default="/home/z/my-project/download/test_audio.wav") |
|
|
| args = p.parse_args() |
|
|
| if args.cmd == "surgery": |
| perform_surgery( |
| old_checkpoint_path=args.old_checkpoint, |
| vibevoice_repo_dir=args.vibevoice_repo, |
| output_dir=args.output_dir, |
| new_llm_repo=args.new_llm_repo, |
| hf_cache_dir=args.hf_cache_dir, |
| reinit_cond_proj=not args.keep_cond_proj, |
| fake_new_llm=args.fake_new_llm, |
| ) |
| elif args.cmd == "verify": |
| verify_surgery( |
| model_dir=args.model_dir, |
| vibevoice_repo_dir=args.vibevoice_repo, |
| ) |
| elif args.cmd == "generate": |
| test_audio_generation( |
| model_dir=args.model_dir, |
| vibevoice_repo_dir=args.vibevoice_repo, |
| text=args.text, |
| output_wav_path=args.output_wav, |
| ) |
|
|