voice / surgery.py
amir0907's picture
Upload surgery.py
5ee862b verified
Raw
History Blame Contribute Delete
122 kB
"""
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
# ============================================================================
# Section 1: Configuration constants & dataclasses
# ============================================================================
# --- Old LLM (Qwen2.5-1.5B) specs (from configs/qwen2.5_1.5b_64k.json) ---
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 (Qwen3.5-4B-Base text part) specs (from HF config.json) ---
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 defaults (from configs/qwen2.5_1.5b_64k.json) ---
DIFFUSION_HEAD_LAYERS = 4
DIFFUSION_HEAD_FFN_RATIO = 3.0
DIFFUSION_HEAD_LATENT_SIZE = 64
DIFFUSION_HEAD_RMS_EPS = 1e-5
# --- Acoustic / Semantic tokenizer VAE dims (UNCHANGED through surgery) ---
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)
# ============================================================================
# Section 2: Path setup & VibeVoice module loader
# ============================================================================
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, # path IS the package
start / "vibevoice", # path contains vibevoice/
start / "src" / "vibevoice", # finetuning fork: path/src/vibevoice
start.parent, # parent might be the package
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
# Auto-detect: find the vibevoice package directory
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))
# === IMPORTANT: Replace vibevoice/__init__.py with a minimal stub ===
# The official Microsoft VibeVoice __init__.py imports streaming classes
# that:
# (a) may not exist in all forks (e.g. the finetuning fork doesn't have them)
# (b) trigger AutoModel.register() calls that collide with transformers 5.x's
# builtin VibeVoice classes, raising:
# ValueError: 'VibeVoiceAcousticTokenizerConfig' is already used by a
# Transformers model.
# We avoid both issues by replacing __init__.py with an empty stub BEFORE
# importing the package. The original file is backed up.
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()
# Only back up if we haven't already
if not backup_file.exists():
backup_file.write_text(original_content)
# Check if the current content is already our stub
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)
# Also replace vibevoice/modular/__init__.py if it imports streaming classes
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 it imports streaming classes, replace with empty stub
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:
# Create empty __init__.py
modular_init.write_text(
"# Auto-generated stub by surgery.py\n"
)
# Same for processor/__init__.py if needed
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")
# Pre-patch AutoModel.register / AutoModelForCausalLM.register to be
# tolerant of re-registration (newer transformers raises if a config is
# already registered; VibeVoice's modular files don't pass exist_ok=True).
# This MUST happen before importing vibevoice's modular modules.
_patch_auto_register_tolerant()
# Patch transformers 5.x breaking changes that VibeVoice's source code
# does not yet handle.
_patch_transformers_5x_compat()
# IMPORTANT: transformers >= 5.x ships its own (incompatible) VibeVoice
# implementation. We MUST force AutoModel / AutoConfig to use the user's
# local VibeVoice classes instead of the builtin ones, otherwise loading
# the user's checkpoint fails with attribute errors.
_override_builtin_vibevoice_classes()
# Sanity-check that the package is importable (with the stub __init__.py,
# this should NOT trigger streaming imports)
try:
import vibevoice # noqa: F401
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}"
)
# Importing these modules triggers the AutoModel.register() calls inside
# them, so that VibeVoiceConfig becomes a known config class.
from vibevoice.modular import configuration_vibevoice # noqa: F401
from vibevoice.modular import modeling_vibevoice # noqa: F401
from vibevoice.modular import modular_vibevoice_tokenizer # noqa: F401
from vibevoice.modular import modular_vibevoice_diffusion_head # noqa: F401
from vibevoice.modular import modular_vibevoice_text_tokenizer # noqa: F401
# Re-override AFTER the user's modular files are imported, because their
# register() calls (which we made idempotent above) won't replace the
# builtin mappings.
_override_builtin_vibevoice_classes()
# IMPORTANT: Patch VibeVoiceConfig so it accepts qwen3_5_text as a decoder
# type (the upstream code only accepts qwen2).
_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:
# Already registered -- skip silently.
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
# 1. Inject a synthetic `tokenization_qwen2_fast` module that re-exports
# the (merged) Qwen2TokenizerFast from tokenization_qwen2.
fast_mod = types.ModuleType("transformers.models.qwen2.tokenization_qwen2_fast")
# The merged class might be called Qwen2Tokenizer (the only one that exists
# in 5.x) — alias it as Qwen2TokenizerFast for backward compatibility.
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
# Also expose as attribute of the parent package
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:
# Not imported yet -- can't override. Will be retried after import.
return
if _OVERRIDE_PATCHED:
return
from transformers.models.auto import AutoModel, AutoModelForCausalLM
# Mapping from the user's config class -> user's model class
# (filled in lazily because some model files may not be importable yet)
_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,
})
# Cache the CausalLM class too
_USER_MODEL_CLASSES["__causal_lm__"] = VibeVoiceForConditionalGeneration
# --- Patch AutoModel.from_config ---
_orig_automodel_from_config = AutoModel.from_config
def _patched_from_config(config, *args, **kwargs):
_ensure_user_classes_loaded()
# Check by identity (config is an INSTANCE of one of the user's classes)
for user_cfg_cls, user_mdl_cls in _USER_MODEL_CLASSES.items():
if not isinstance(user_cfg_cls, type):
continue # skip non-type keys like "__causal_lm__"
if isinstance(config, user_cfg_cls):
return user_mdl_cls._from_config(config, *args, **kwargs)
# Fallback: also check by class name (in case the config is a
# transformers-builtin VibeVoice config that we want to redirect
# to the user's class). Built lazily from _USER_MODEL_CLASSES.
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)
# --- Patch AutoModelForCausalLM.from_pretrained ---
_orig_causallm_from_pretrained = AutoModelForCausalLM.from_pretrained
def _patched_causallm_from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
_ensure_user_classes_loaded()
# Inspect the config to decide whether to route to the user's class
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
# Check if the loaded config is (or should be) a VibeVoice config
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)
# Call the original classmethod with cls as the first arg
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)
# --- Also patch AutoConfig.from_pretrained to redirect VibeVoice configs ---
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)
# If the config is a transformers-builtin VibeVoice config (because
# the model_type matched the builtin), rebuild it as the user's config.
cfg_type_name = type(cfg).__name__
builtin_vibevoice_names = {
"VibeVoiceAcousticTokenizerConfig",
"VibeVoiceSemanticTokenizerConfig",
"VibeVoiceDiffusionHeadConfig",
"VibeVoiceConfig",
}
if cfg_type_name in builtin_vibevoice_names:
# Get the user's config class
user_cfg_cls = {
"VibeVoiceAcousticTokenizerConfig": VibeVoiceAcousticTokenizerConfig,
"VibeVoiceSemanticTokenizerConfig": VibeVoiceSemanticTokenizerConfig,
"VibeVoiceDiffusionHeadConfig": VibeVoiceDiffusionHeadConfig,
"VibeVoiceConfig": VibeVoiceConfig,
}[cfg_type_name]
# Build a new config of the user's class from the dict
try:
cfg_dict = cfg.to_dict()
# Remove keys that may confuse the user's __init__
for k in ("model_type", "transformers_version"):
cfg_dict.pop(k, None)
# The user's VibeVoiceConfig __init__ takes specific kwargs;
# if it raises, we just return the original (builtin) config
# and let downstream handle it.
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)
# --- Patch _tied_weights_keys format for transformers 5.x ---
# In transformers 5.x, _tied_weights_keys is a DICT (target -> source),
# but the user's VibeVoice code declares it as a LIST ["lm_head.weight"].
# This causes a crash in get_expanded_tied_weights_keys.
try:
from vibevoice.modular.modeling_vibevoice import (
VibeVoiceForConditionalGeneration as _VVCFG,
)
# Convert list to dict {target: source} where source is the input
# embeddings key.
_VVCFG._tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
# --- Patch tie_weights signature for transformers 5.x ---
# In transformers 5.x, PreTrainedModel.init_weights calls
# self.tie_weights(recompute_mapping=False), and _finalize_model_loading
# calls self.tie_weights(missing_keys=..., recompute_mapping=False).
# The user's VibeVoiceForConditionalGeneration.tie_weights() doesn't
# accept these kwargs. Wrap it to accept and ignore the extras.
_orig_tie_weights_cfg = _VVCFG.tie_weights
def _patched_tie_weights_cfg(self, *args, **kwargs):
# Accept and ignore transformers 5.x 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")
# Also patch the inference variant if it's importable.
# IMPORTANT: VibeVoiceForConditionalGenerationInference has its OWN
# tie_weights method (it doesn't inherit from VibeVoiceForConditionalGeneration),
# so we must patch it separately.
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:
# modeling_vibevoice_inference.py not present in this fork
pass
except ImportError as e:
print(f"[setup] WARN: could not patch _tied_weights_keys: {e}")
# --- Patch DPMSolverMultistepScheduler for transformers 5.x ---
# In transformers 5.x, from_pretrained may run model __init__ under a
# `torch.device("meta")` context manager, which makes all tensor creation
# happen on the meta device. The DPMSolverMultistepScheduler in VibeVoice's
# schedule/dpm_solver.py does `self.sigmas = self.sigmas.to("cpu")`, which
# fails because meta tensors cannot be copied out.
# Fix: wrap the scheduler's __init__ to escape the meta device context.
try:
from vibevoice.schedule.dpm_solver import DPMSolverMultistepScheduler as _DPM
_orig_dpm_init = _DPM.__init__
def _patched_dpm_init(self, *args, **kwargs):
# Temporarily exit any meta device context by using torch.device("cpu")
# as the active device during init.
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}")
# --- Patch GenerationMixin._prepare_generation_config for transformers 5.x ---
# VibeVoice's inference code calls:
# self._prepare_generation_config(generation_config, True, speech_start_id=..., ...)
# In transformers 4.x, the signature was:
# _prepare_generation_config(self, generation_config, copy=True, **kwargs)
# In transformers 5.x, the `copy` parameter was removed:
# _prepare_generation_config(self, generation_config, **kwargs)
# This causes: TypeError: takes 2 positional arguments but 3 were given
# Fix: wrap the method to accept and ignore the extra positional `copy` arg.
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):
# In transformers 5.x, there's no `copy` positional arg.
# VibeVoice passes `True` as the second positional arg (the old `copy`).
# We just ignore it — the new transformers always copies internally.
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}")
# --- Patch GenerationMixin._prepare_cache_for_generation for transformers 5.x ---
# VibeVoice's inference code calls (6 positional args after self):
# self._prepare_cache_for_generation(generation_config, model_kwargs, None, batch_size, max_cache_length, device)
# In transformers 5.x, the signature is (5 positional args after self, no `device`):
# _prepare_cache_for_generation(self, generation_config, model_kwargs, generation_mode, batch_size, max_cache_length) -> bool
# The `device` arg was removed in 5.x. We patch the method to accept and
# ignore the extra `device` arg, and return True (the new return value).
#
# CRITICAL FIX for Qwen3.5 hybrid attention:
# We also ensure the DynamicCache is created with the REAL decoder config
# (not the VibeVoiceConfig wrapper). This is needed because Qwen3.5 uses
# hybrid attention (LinearAttention + FullAttention), and the DynamicCache
# must know the `layer_types` to create the correct mix of cache layers.
# Without this, all cache layers are created as DynamicLayer (full_attention),
# and `has_previous_state()` raises:
# ValueError: `has_previous_state` can only be called on LinearAttention
# layers, and the current Cache seem to only contain Attention layers.
try:
_orig_prepare_cache = GenerationMixin._prepare_cache_for_generation
def _patched_prepare_cache_for_generation(self, generation_config, model_kwargs, *args, **kwargs):
# VibeVoice passes (generation_config, model_kwargs, None, batch_size, max_cache_length, device)
# New API expects (generation_config, model_kwargs, generation_mode, batch_size, max_cache_length)
# args = (None, batch_size, max_cache_length, device) from VibeVoice
# We need to pass only the first 3 of args (None, batch_size, max_cache_length)
# and drop the `device`.
if len(args) > 3:
# VibeVoice style: drop the extra `device` arg
args = args[:3]
result = _orig_prepare_cache(self, generation_config, model_kwargs, *args, **kwargs)
# --- Belt-and-suspenders fix for Qwen3.5 hybrid attention cache ---
# After the original method creates the cache, verify it has the
# correct layer types. If the cache was created with the wrong
# config (e.g., VibeVoiceConfig instead of decoder_config), and
# the decoder uses hybrid attention (layer_types includes
# "linear_attention"), recreate the cache with the correct config.
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:
# Check if the decoder has hybrid attention
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
):
# The decoder uses hybrid attention. Check if the cache
# has any LinearAttention layers.
from transformers.cache_utils import (
LinearAttentionCacheLayerMixin as _LAC,
)
has_linear = any(
isinstance(l, _LAC) for l in pkv.layers
)
if not has_linear:
# The cache was created without LinearAttention
# layers. Recreate it with the real decoder config.
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}")
# --- Patch _init_weights to be a no-op for non-diffusion-head modules
# when called from `initialize_weights` (post-state_dict-load).
# In transformers 5.x, `from_pretrained` calls `initialize_weights` which
# applies `_initialize_weights` to every module. For non-remote-code models
# (our case), the `_is_hf_initialized` flag is NOT checked at the module
# level, so `_init_weights` is called on every module, re-randomizing the
# loaded weights! The intended mechanism is that `init.guard_torch_init_functions`
# intercepts torch's init functions and checks the param-level flag, but
# VibeVoice's `_init_weights` uses `module.weight.data.normal_(...)` which
# may not be intercepted. To be safe, we make `_init_weights` a no-op for
# Linear/Embedding/LayerNorm modules after the model is constructed.
try:
from vibevoice.modular.modeling_vibevoice import VibeVoicePreTrainedModel
_orig_vv_init_weights = VibeVoicePreTrainedModel._init_weights
# We use a thread-local flag to indicate whether we're in the
# post-load init phase. The flag is set by a wrapper around
# `initialize_weights` and unset after.
import threading
_init_state = threading.local()
_init_state.in_post_load_init = False
def _patched_vv_init_weights(self, module):
# Always allow VibeVoiceDiffusionHead initialization
from vibevoice.modular.modular_vibevoice_diffusion_head import VibeVoiceDiffusionHead
if isinstance(module, VibeVoiceDiffusionHead):
module.initialize_weights()
return
# During post-load init, skip re-initialization for modules that
# already have their params loaded (i.e. have _is_hf_initialized
# on at least one param).
if getattr(_init_state, "in_post_load_init", False):
# Check if any param of this module has _is_hf_initialized
has_loaded_param = any(
getattr(p, "_is_hf_initialized", False)
for p in module.parameters(recurse=False)
)
if has_loaded_param:
return # skip re-init
# Otherwise, call the original init
_orig_vv_init_weights(self, module)
VibeVoicePreTrainedModel._init_weights = _patched_vv_init_weights
# Wrap `initialize_weights` to set the post-load flag
_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}")
# --- Patch VibeVoiceTokenizerEncoderOutput to be subscriptable ---
# The VibeVoice source code in modeling_vibevoice.py:291 does:
# frames = self.model.acoustic_tokenizer.encode(speech_tensors.unsqueeze(1))[0][0]
# audio_tokens = frames.sample(self.model.acoustic_tokenizer.std_dist_type)[0]
# This assumes encode() returns a nested tuple where [0][0] extracts the
# EncoderOutput object. However, the current VibeVoice source defines
# encode() to return a VibeVoiceTokenizerEncoderOutput dataclass directly
# (with .mean, .std, and .sample() attributes), which is NOT subscriptable.
# This is an internal VibeVoice bug — the caller and callee were updated at
# different times and are now incompatible.
#
# Fix: add __getitem__ to VibeVoiceTokenizerEncoderOutput so that [0] and
# [0][0] both return self (the EncoderOutput object). This way:
# encode(...)[0] -> self (the EncoderOutput)
# encode(...)[0][0] -> self[0] -> self (the EncoderOutput)
# frames.sample(...) -> calls .sample() on the EncoderOutput ✓
# This preserves the caller's intent without modifying VibeVoice's source.
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 # Return self so [0][0] still gives self,
# and frames.sample() works on the EncoderOutput
elif index == 1:
return self.std
else:
return self # Be lenient: return self for any index
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["_attn_implementation_autoset"] = False -- preserve caller intent
kwargs.setdefault("_attn_implementation_autoset", False)
# --- acoustic_tokenizer_config ---
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
# --- semantic_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
# --- decoder_config (THE KEY CHANGE: support any model_type) ---
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:
# Any other model_type: use AutoConfig to build the right class
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:
# No model_type -- assume qwen2 (backwards compat)
self.decoder_config = Qwen2Config(**decoder_config)
else:
# Already a config object
self.decoder_config = decoder_config
# --- diffusion_head_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
# Other parameters
self.acoustic_vae_dim = getattr(self.acoustic_tokenizer_config, 'vae_dim', 64)
self.semantic_vae_dim = getattr(self.semantic_tokenizer_config, 'vae_dim', 128)
# Call PreTrainedConfig.__init__ to handle remaining kwargs
# (vocab_size, tie_word_embeddings, torch_dtype, etc.)
super(VibeVoiceConfig, self).__init__(**kwargs)
# --- Expose decoder_config attributes at the top level for transformers 5.x ---
# transformers 5.x's cache utilities (DynamicCache, etc.) access
# `config.num_hidden_layers`, `config.hidden_size`, etc. directly on the
# top-level config. VibeVoiceConfig is a composite config that stores
# these in `self.decoder_config`, so we need to expose them as
# pass-through properties.
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 # some attributes may be read-only
VibeVoiceConfig.__init__ = patched_init
# --- Override get_text_config to return decoder_config for decoder=True ---
# This is CRITICAL for Qwen3.5 hybrid attention models.
#
# transformers 5.x's DynamicCache.__init__ does:
# decoder_config = config.get_text_config(decoder=True)
# layer_types = getattr(decoder_config, "layer_types", None)
#
# The default get_text_config(decoder=True) looks for attributes named
# "decoder", "generator", or "text_config". VibeVoiceConfig stores its
# decoder config as "decoder_config" (not "decoder"), so the default
# implementation returns `self` (the VibeVoiceConfig) instead of the
# real Qwen3.5 text config.
#
# While the patched __init__ above DOES propagate `layer_types` to the
# top level, this propagation can be fragile:
# - It depends on `setattr` succeeding (some attributes may be read-only)
# - It depends on `from_pretrained` calling the patched __init__
# - Different transformers versions may handle config loading differently
#
# By overriding get_text_config, we ensure DynamicCache ALWAYS gets the
# real Qwen3.5 text config (with layer_types properly set), eliminating
# the "has_previous_state can only be called on LinearAttention layers"
# error that occurs when the cache is created without LinearAttention
# layers.
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:
# Return the real decoder config (Qwen3.5 text config)
if hasattr(self, "decoder_config") and self.decoder_config is not None:
return self.decoder_config
# For other cases (encoder=True, or both unset), fall back to the
# original implementation
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")
# --- Also patch VibeVoiceStreamingConfig (if it exists) ---
# The Microsoft VibeVoice repo has a VibeVoiceStreamingConfig that has the
# same "Unsupported decoder model type" issue. We patch it the same way.
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
# Pre-convert decoder_config dict -> config object
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}")
# Temporarily make the isinstance check accept our config class
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 decoder_config is still a dict, forcibly set it
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:
# The streaming config doesn't exist in this fork — skip
pass
# ============================================================================
# Section 3: Low-level weight expansion utilities
# ============================================================================
@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})"
)
# Inherit bias flag from old_layer if not explicitly specified.
# This fixes the bug where expand_speech_connector / expand_head_layer /
# expand_final_layer / expand_timestep_embedder previously built new
# Linear layers with bias=False even when the original had bias=True.
if bias is None:
bias = old_layer.bias is not None
# Build new layer in the same dtype/device as the old one
new_layer = nn.Linear(
new_in_features,
new_out_features,
bias=bias,
device=old_layer.weight.device,
dtype=old_layer.weight.dtype,
)
# Zero everything first (this covers new rows AND new columns AND any bias)
new_layer.weight.data.zero_()
# Copy the old (old_out, old_in) block into the top-left
new_layer.weight.data[:old_out, :old_in].copy_(old_layer.weight.data)
# Optionally fill the new input columns with small random values so that
# the new dims can start learning immediately (does NOT change behaviour
# on the preserved dims because the new OUTPUT rows are still zero).
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)
# Copy bias if it exists in both. The new bias positions (old_out:new_out)
# remain zero, consistent with the zero-pad strategy: the new output dims
# contribute nothing to downstream computation until fine-tuning moves them
# away from zero.
if bias:
# Always zero the new bias first (nn.Linear's default init leaves it
# non-zero). If we have an old bias, copy its values into the top-left
# block; otherwise leave the whole bias zero (zero-pad strategy).
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.
"""
# Detect old dim
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}")
# Find eps
if eps is None:
eps = getattr(old_norm, "eps", 1e-6)
# Build a new module of the same type
norm_cls = type(old_norm)
try:
new_norm = norm_cls(new_dim, eps=eps)
except TypeError:
# Some custom RMSNorm variants have extra kwargs
new_norm = norm_cls(new_dim, eps=eps, elementwise_affine=True)
# Move to same device/dtype as old
new_norm = new_norm.to(device=old_norm.weight.device, dtype=old_norm.weight.dtype)
# Initialize all weights to 1.0
new_norm.weight.data.fill_(1.0)
# Copy old weights into the first old_dim entries
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_()
# ============================================================================
# Section 4: Surgery primitives for the speech connectors and diffusion head
# ============================================================================
@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
"""
# Re-import locally so callers don't have to depend on VibeVoice at import time
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)")
# Build new connector (random init, we'll overwrite below)
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,
)
# fc1: input dim unchanged, output dim expanded -> zero-pad output rows
new_connector.fc1 = expand_linear_zero_pad(
old_connector.fc1, new_in_features=input_dim, new_out_features=new_output_dim
)
# norm: expand RMSNorm
new_connector.norm = expand_rmsnorm(old_connector.norm, new_output_dim, eps=1e-6)
# fc2: both dims expanded
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 # 256
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
)
# mlp[1] (SiLU) has no params
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
# Build new layer (random init, we'll overwrite)
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,
)
# FFN: gate_proj, up_proj, down_proj
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,
)
# Norm
new_layer.norm = expand_rmsnorm(old_layer.norm, new_embed_dim, eps=norm_eps)
# adaLN_modulation = Sequential(SiLU, Linear(cond, 3*embed))
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,
)
# norm_final: RMSNorm without affine -- just rebuild (no weights to copy)
# The custom RMSNorm class supports elementwise_affine=False -> weight is None
# No action needed; the constructor already handled it.
# linear: Linear(old_hidden, output) -> Linear(new_hidden, output)
# Output dim unchanged, input dim expanded -> zero-pad input columns
new_final.linear = expand_linear_zero_pad(
old_final.linear,
new_in_features=new_hidden,
new_out_features=output_size,
)
# adaLN_modulation[1]: Linear(cond, 2*hidden) -> Linear(new_cond, 2*new_hidden)
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}")
# Build new config
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,
)
# Build new diffusion head (random init, we'll overwrite below)
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,
)
# noisy_images_proj: Linear(latent, old_hidden) -> Linear(latent, new_hidden)
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,
)
# cond_proj: Linear(old_hidden, old_hidden) -> Linear(new_hidden, new_hidden)
# Re-initialise: the LLM hidden state space has changed fundamentally.
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,
)
# t_embedder
new_head.t_embedder = expand_timestep_embedder(old_head.t_embedder, new_hidden_size)
# layers (ModuleList)
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, # cond_dim == hidden_size in this model
norm_eps=rms_eps,
)
new_layers.append(new_l)
new_head.layers = new_layers
# final_layer
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
# ============================================================================
# Section 5: LLM replacement (the core of the surgery)
# ============================================================================
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)
# Extract text_config (multimodal repo) or use full config (text-only repo)
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')}")
# Try to instantiate the text model class directly.
text_model_type = text_config_dict.get("model_type", "qwen3_5_text")
text_model = None
load_error = None
# Strategy 1: try AutoModel with the text config registered as a known type
try:
from transformers.models.auto import MODEL_MAPPING
# Build a standalone text config of the right class
# The text_config is already a config instance in newer transformers
text_config = full_config.text_config if hasattr(full_config, "text_config") else full_config
# AutoModel should pick up Qwen3_5TextModel
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}")
# Strategy 2: load Qwen3_5ForCausalLM (or Qwen3_5ForConditionalGeneration)
# and extract the inner text model
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,
)
# The CausalLM typically has .model (the base text model)
if hasattr(full_model, "model") and not hasattr(full_model, "text_model"):
text_model = full_model.model
# Detach so that disposing of full_model doesn't free the weights
full_model.lm_head = None
elif hasattr(full_model, "text_model"):
text_model = full_model.text_model
else:
# Last resort: take everything except lm_head
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 text_model still wraps a vision component, strip it
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).
"""
# Detach old LLM
old_llm = vibevoice_model.model.language_model
old_lm_head = vibevoice_model.lm_head
# Move new text model to the same device/dtype as the rest of the model
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)
# Wire it in
vibevoice_model.model.language_model = new_text_model
# Rebuild lm_head
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
)
# Re-tie weights if config says so
tie = getattr(vibevoice_model.config.decoder_config, "tie_word_embeddings", True)
if tie:
# Get the input embeddings of the new text model
if hasattr(new_text_model, "embed_tokens"):
embed = new_text_model.embed_tokens
else:
# Walk attributes to find embeddings
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:
# Keep the pretrained lm_head weights from Qwen3.5 if available
# (We'd need to pass them in; for now leave default-init.)
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
# ============================================================================
# Section 6: Config update
# ============================================================================
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
# Convert the Qwen3.5 text config to a plain dict so VibeVoiceConfig can
# re-instantiate it via its sub_configs logic. VibeVoiceConfig currently
# only knows about Qwen2Config as a decoder type, so we have to extend it.
text_cfg_dict = new_text_config.to_dict() if hasattr(new_text_config, "to_dict") else dict(new_text_config)
# Build new diffusion head 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,
)
# Build the new VibeVoiceConfig.
# We bypass the __init__ sub_config dispatch (which is hardcoded to Qwen2Config)
# by constructing a minimal VibeVoiceConfig and assigning the configs manually.
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, # we set it manually below
diffusion_head_config=new_diff_cfg.to_dict()
if hasattr(new_diff_cfg, "to_dict")
else dict(new_diff_cfg.__dict__),
)
# Replace decoder_config with the actual Qwen3.5 text config object.
# VibeVoiceModel.__init__ uses AutoModel.from_config(lm_config), which
# works with any registered config class as long as it knows the model_type.
new_config.decoder_config = new_text_config
# Top-level fields
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
# ============================================================================
# Section 7: Main surgery orchestrator
# ============================================================================
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)
# 1. Setup imports
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
# 2. Load original VibeVoice
print(f"\n[2/8] Loading original VibeVoice from {old_checkpoint_path}...")
# NOTE: low_cpu_mem_usage=False is required because the DPMSolverMultistepScheduler
# inside VibeVoiceModel.__init__ does .to("cpu") on its sigmas, which fails
# under the init_empty_weights context manager that low_cpu_mem_usage=True uses.
old_model = VibeVoiceForConditionalGeneration.from_pretrained(
old_checkpoint_path,
dtype=torch_dtype, # transformers 5.x uses 'dtype' (was '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}")
# 3. Load Qwen3.5-4B-Base text model
if skip_llm_download:
print("\n[3/8] Skipping Qwen3.5 download (skip_llm_download=True).")
new_text_model = None
# Build a minimal text config matching Qwen3.5-4B
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}")
# 4. Build the new VibeVoiceConfig
print("\n[4/8] Building new VibeVoiceConfig...")
new_config = build_new_vibevoice_config(old_config, new_text_config)
# 5. Build a new VibeVoiceForConditionalGeneration with the new config,
# but WITHOUT re-initialising everything. We'll transplant the old
# weights module-by-module.
print("\n[5/8] Building new VibeVoice skeleton with new config...")
# Save current default dtype, set to torch_dtype for the constructor
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()
# 6. Transplant weights
print("\n[6/8] Transplanting weights...")
expanded_modules: List[str] = []
reinit_modules: List[str] = []
preserved_modules: List[str] = []
# 6a. Acoustic tokenizer - copy unchanged
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")
# 6b. Semantic tokenizer - copy unchanged
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")
# 6c. Acoustic connector - width-expand
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")
# 6d. Semantic connector - width-expand
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")
# 6e. speech_scaling_factor / speech_bias_factor buffers - copy as-is
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
)
# 6f. Diffusion head (prediction_head) - width-expand
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")
# 6g. LLM - replace
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)")
# 6h. lm_head - either tied or rebuilt (replace_llm_in_vibevoice handled it)
preserved_modules.append("lm_head (tied with embed_tokens)")
# Free memory
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:,}")
# 7. Save the model
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)
# 8. Build & save report
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
# ============================================================================
# Section 8: Verification helpers
# ============================================================================
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, # transformers 5.x
low_cpu_mem_usage=False, # see perform_surgery for the reason
)
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}")
# Forward pass with a tiny fake input.
# VibeVoice's forward ALWAYS calls self.model.semantic_connector(...)
# and self.forward_speech_features(...), so we MUST provide dummy speech
# tensors even for a smoke test. See modeling_vibevoice.py:360.
#
# The speech path requires carefully matched shapes:
# - speech_tensors: (batch, n_audio_samples) -- raw audio waveform
# - speech_masks: (batch, n_frames) -- 2D bool mask, n_frames
# equals what the acoustic tokenizer produces from
# n_audio_samples
# - acoustic_input_mask: (batch, seq_len) -- n_frames True positions
# (so inputs_embeds[mask] matches speech_embeds shape)
# If any of these mismatch, the forward fails with a shape error. We
# pre-compute n_frames by running the acoustic tokenizer once on the
# dummy audio, then build all masks consistently. If pre-compute fails
# (e.g. dtype mismatch), we fall back to testing the inner model only.
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)
# Pre-compute n_frames via the acoustic tokenizer.
# `forward()` converts speech_tensors to `self.dtype` before encoding,
# so we use model.dtype here (the same strategy as test_audio_generation).
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:
# Build correctly-shaped speech_masks and acoustic_input_mask.
# - speech_masks: 2D (batch, n_frames), all True (select all frames)
# - acoustic_input_mask: 2D (batch, seq_len), with n_frames True
# positions (capped at seq_len-1 to leave room for at least one
# non-speech token)
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:
# Fallback: test the inner VibeVoiceModel directly (no speech processing)
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}"
)
# Compute logits via lm_head
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)}")
# Sanity check: diffusion head can be called directly
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")
# Sanity check: connectors produce new-hidden-size output
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")
# Sanity check: zero-padded dims of expanded layers are actually zero
print(" Verifying zero-padding of expanded layers...")
fc1_w = model.model.acoustic_connector.fc1.weight.data # (new_hidden, in_vae)
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,
}
# ============================================================================
# Section 9: Audio generation test
# ============================================================================
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
# Accept a bare tensor/array/list as well (defensive: some callers pass the
# raw waveform instead of the full ModelOutput).
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):
# bfloat16 has no numpy dtype -> upcast to float32 before .numpy()
wav = wav.detach()
if wav.dtype != torch.float32 and wav.dtype != torch.float64:
wav = wav.float()
# .cpu() in case it's on CUDA
arr = wav.cpu().numpy()
elif isinstance(wav, np.ndarray):
# Could be object dtype if someone did np.asarray(None); reject.
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:
# None, or any other non-array object -> skip
continue
# Reject 0-d / empty arrays.
if arr is None or arr.size == 0:
continue
# Flatten to 1-D mono waveform, make contiguous, sanitise non-finite.
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)
# --- Try to find a usable inference class ---
inference_cls = None
inference_type = None
# Strategy 1: modeling_vibevoice_inference (older forks)
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}")
# Strategy 2: modeling_vibevoice_streaming_inference (Microsoft repo)
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}")
# Strategy 3: Fall back to the base model (no generate(), just forward)
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"
# --- Load the model ---
try:
model = inference_cls.from_pretrained(
model_dir,
dtype=torch_dtype, # transformers 5.x
low_cpu_mem_usage=False, # see perform_surgery for the reason
)
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}"}
# --- Load tokenizer ---
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}"}
# --- Build inputs ---
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)
# Build a fake audio prompt (3 seconds of silence at 24kHz)
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
# --- Step 1: Encode ref audio to determine n_frames ---
# n_frames = number of frames the acoustic tokenizer produces from the
# audio. This is needed to build both speech_masks and speech_input_mask
# with the correct shapes.
#
# CRITICAL: `forward()` in modeling_vibevoice_inference.py:222 converts
# `speech_tensors` to `self.dtype` (the model's overall dtype) before
# calling `_process_speech_inputs`. We MUST match that exact dtype here,
# because the acoustic_tokenizer's Conv1d weights/biases are in
# `model.dtype`. Using a different dtype (e.g. float32) triggers
# `RuntimeError: Input type (float) and bias type (c10::BFloat16) should
# be the same`.
#
# We try multiple dtype candidates because `low_cpu_mem_usage=False`
# loading can leave some submodules in a mixed-dtype state, and
# `next(acoustic_tokenizer.parameters()).dtype` is not guaranteed to
# match the dtype that the rest of the model expects.
print(" Encoding ref audio to determine n_frames...")
encode_dtype_candidates: List[torch.dtype] = []
# Primary: model.dtype (what forward() actually uses)
if hasattr(model, "dtype") and model.dtype is not None:
encode_dtype_candidates.append(model.dtype)
# Secondary: dtype of the first acoustic_tokenizer parameter
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
# Tertiary: dtype of the connector (downstream consumer)
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
# Final fallbacks
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():
# acoustic_tokenizer.encode expects (batch, channels, samples)
enc_input = speech_tensors.unsqueeze(1).to(dtype=try_dtype)
enc_out = model.model.acoustic_tokenizer.encode(enc_input)
# enc_out is a VibeVoiceTokenizerEncoderOutput (after our patch)
# enc_out.mean has shape (batch, n_frames, vae_dim)
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}")
# --- Fail-fast: do NOT fall back to a (1,1) speech_masks. ---
# The previous (1,1) fallback caused IndexError at inference line 161
# because the actual `acoustic_connected` had shape (1, N, hidden) while
# the mask selected only 1 frame. We MUST know the real n_frames to
# build correctly-shaped speech_masks and speech_input_mask.
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,
}
# --- Step 2: Build speech_input_mask (shape: batch x seq_len) ---
# Number of True values MUST equal n_frames (or be capped at seq_len-1).
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})")
# --- Step 3: Build speech_masks (shape: batch x n_frames) ---
# In VibeVoice's _process_speech_inputs (line 161):
# acoustic_connected = self.model.acoustic_connector(acoustic_features)[speech_masks.cpu()]
# - acoustic_connected has shape (batch, n_frames, hidden_size)
# - speech_masks is 2D (batch, n_frames) to select frames
# - tensor_3d[mask_2d] returns (n_true, hidden_size)
# - The result is assigned to inputs_embeds[speech_input_mask] which also
# has shape (n_true, hidden_size).
#
# CRITICAL: The number of True values in speech_masks MUST equal the
# number of True values in speech_input_mask, because both produce
# tensors of shape (n_true, hidden_size) that get assigned to each other.
# So if we cap speech_input_mask at n_to_set, we must also cap speech_masks
# to select only n_to_set frames.
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 we only have the base model (no generate()), do a forward-pass test ---
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}"}
# --- Full generation (for non-streaming and streaming inference classes) ---
print(f" Generating (max_new_tokens={max_new_tokens}, {inference_type} mode)...")
try:
with torch.no_grad():
# The generate() signature differs between streaming and non-streaming.
# Both accept input_ids, attention_mask, speech_tensors, speech_masks,
# speech_input_mask, max_new_tokens, tokenizer. We pass them as kwargs
# and let the model handle the rest.
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.")
# Extract the first valid audio waveform from the generation output.
# `speech_outputs` is a List[Optional[Tensor]]: each entry is a 1-D/2-D
# waveform tensor for one batch sample, or None when that sample never
# emitted a speech_diffusion_id token (very common for an un-fine-tuned
# model that collapses to EOS early). A previous version of this code
# only checked whether the LIST was truthy (`[None]` is truthy!), then
# blindly did `np.asarray(None)` which yields a dtype='object' array
# that soundfile rejects with:
# ValueError: dtype must be one of ['float32','float64','int16',
# 'int32'] and not 'object'
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,
}
# Write to WAV. wav is guaranteed float32 here (see extract_audio_array),
# which is one of soundfile's supported dtypes.
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}
# ============================================================================
# Section 10: CLI entry point
# ============================================================================
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,
)