Skip to content

The open-source AI voice studio. Clone, dictate, create.

feat(engines): add OmniVoice TTS engine (600+ languages)

SKAL60721a959c21
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index e1bcd3e3..dee6b39a 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -85,6 +85,7 @@ jobs:
pip install -r backend/requirements.txt
pip install --no-deps chatterbox-tts
pip install --no-deps hume-tada
+ pip install --no-deps omnivoice
- name: Install MLX dependencies (Apple Silicon only)
if: matrix.backend == 'mlx'
@@ -290,6 +291,7 @@ jobs:
pip install -r backend/requirements.txt
pip install --no-deps chatterbox-tts
pip install --no-deps hume-tada
+ pip install --no-deps omnivoice
- name: Install PyTorch with CUDA 12.8
run: |
@@ -363,6 +365,7 @@ jobs:
pip install -r backend/requirements.txt
pip install --no-deps chatterbox-tts
pip install --no-deps hume-tada
+ pip install --no-deps omnivoice
- name: Build ROCm server binary (onedir)
shell: bash
diff --git a/Dockerfile b/Dockerfile
index 14d86b9b..1178d1c4 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -63,6 +63,7 @@ RUN if [ "$PYTORCH_VARIANT" = "rocm" ]; then \
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt
RUN pip install --no-cache-dir --prefix=/install --no-deps chatterbox-tts
RUN pip install --no-cache-dir --prefix=/install --no-deps hume-tada
+RUN pip install --no-cache-dir --prefix=/install --no-deps omnivoice
RUN pip install --no-cache-dir --prefix=/install \
git+https://github.com/QwenLM/Qwen3-TTS.git
diff --git a/app/src/components/Generation/EngineModelSelector.tsx b/app/src/components/Generation/EngineModelSelector.tsx
index d9856421..dbae2bcd 100644
--- a/app/src/components/Generation/EngineModelSelector.tsx
+++ b/app/src/components/Generation/EngineModelSelector.tsx
@@ -27,6 +27,7 @@ const ENGINE_OPTIONS = [
{ value: 'tada:1B', label: 'TADA 1B', engine: 'tada' },
{ value: 'tada:3B', label: 'TADA 3B Multilingual', engine: 'tada' },
{ value: 'kokoro', label: 'Kokoro 82M', engine: 'kokoro' },
+ { value: 'omnivoice', label: 'OmniVoice', engine: 'omnivoice' },
] as const;
const ENGINE_DESCRIPTIONS: Record<string, string> = {
@@ -37,13 +38,21 @@ const ENGINE_DESCRIPTIONS: Record<string, string> = {
chatterbox_turbo: 'English, [laugh] [cough] tags',
tada: 'HumeAI, 700s+ coherent audio',
kokoro: '82M params, CPU realtime, 8 langs',
+ omnivoice: '600+ languages, voice design',
};
/** Engines that only support English and should force language to 'en' on select. */
const ENGLISH_ONLY_ENGINES = new Set(['luxtts', 'chatterbox_turbo']);
/** Engines that support cloned (reference audio) profiles. */
-const CLONING_ENGINES = new Set(['qwen', 'luxtts', 'chatterbox', 'chatterbox_turbo', 'tada']);
+const CLONING_ENGINES = new Set([
+ 'qwen',
+ 'luxtts',
+ 'chatterbox',
+ 'chatterbox_turbo',
+ 'tada',
+ 'omnivoice',
+]);
function getAvailableOptions(selectedProfile?: VoiceProfileResponse | null) {
if (!selectedProfile) return ENGINE_OPTIONS;
diff --git a/app/src/components/ServerSettings/ModelManagement.tsx b/app/src/components/ServerSettings/ModelManagement.tsx
index b06783f9..c4406701 100644
--- a/app/src/components/ServerSettings/ModelManagement.tsx
+++ b/app/src/components/ServerSettings/ModelManagement.tsx
@@ -69,6 +69,8 @@ const MODEL_DESCRIPTIONS: Record<string, string> = {
'HumeAI TADA 3B Multilingual — built on Llama 3.2 3B. Supports 10 languages with high-fidelity voice cloning via text-acoustic dual alignment.',
kokoro:
'Kokoro 82M by hexgrad. Tiny 82M-parameter TTS that runs at CPU realtime. Supports 8 languages with pre-built voice styles. Apache 2.0 licensed.',
+ omnivoice:
+ 'OmniVoice by k2-fsa. Zero-shot voice cloning across 600+ languages via a diffusion language model, plus attribute-based voice design (gender, age, pitch, accent). 24kHz output, RTF as low as 0.025. Apache 2.0 licensed.',
'qwen-custom-voice-1.7B':
'Qwen3-TTS CustomVoice 1.7B by Alibaba. 9 premium preset voices with instruct-based style control for tone, emotion, and prosody. Supports 10 languages.',
'qwen-custom-voice-0.6B':
@@ -414,7 +416,8 @@ export function ModelManagement() {
m.model_name.startsWith('luxtts') ||
m.model_name.startsWith('chatterbox') ||
m.model_name.startsWith('tada') ||
- m.model_name.startsWith('kokoro'),
+ m.model_name.startsWith('kokoro') ||
+ m.model_name.startsWith('omnivoice'),
) ?? [];
const whisperModels = modelStatus?.models.filter((m) => m.model_name.startsWith('whisper')) ?? [];
const llmModels = modelStatus?.models.filter((m) => m.model_name.startsWith('qwen3-')) ?? [];
diff --git a/app/src/lib/api/types.ts b/app/src/lib/api/types.ts
index 457cf711..c6d9a550 100644
--- a/app/src/lib/api/types.ts
+++ b/app/src/lib/api/types.ts
@@ -78,7 +78,8 @@ export interface GenerationRequest {
| 'chatterbox'
| 'chatterbox_turbo'
| 'tada'
- | 'kokoro';
+ | 'kokoro'
+ | 'omnivoice';
instruct?: string;
/** When true and the profile has a personality prompt, input text is rewritten in-character before TTS. */
personality?: boolean;
diff --git a/app/src/lib/constants/languages.ts b/app/src/lib/constants/languages.ts
index e28c519b..3c1420f6 100644
--- a/app/src/lib/constants/languages.ts
+++ b/app/src/lib/constants/languages.ts
@@ -70,6 +70,33 @@ export const ENGINE_LANGUAGES: Record<string, readonly LanguageCode[]> = {
tada: ['en', 'ar', 'zh', 'de', 'es', 'fr', 'it', 'ja', 'pl', 'pt'],
kokoro: ['en', 'es', 'fr', 'hi', 'it', 'pt', 'ja', 'zh'],
qwen_custom_voice: ['zh', 'en', 'ja', 'ko', 'de', 'fr', 'ru', 'pt', 'es', 'it'],
+ // OmniVoice covers 600+ languages. Listed here are the ones ALL_LANGUAGES
+ // already knows -- widening that list is a separate change.
+ omnivoice: [
+ 'ar',
+ 'da',
+ 'de',
+ 'el',
+ 'en',
+ 'es',
+ 'fi',
+ 'fr',
+ 'he',
+ 'hi',
+ 'it',
+ 'ja',
+ 'ko',
+ 'ms',
+ 'nl',
+ 'no',
+ 'pl',
+ 'pt',
+ 'ru',
+ 'sv',
+ 'sw',
+ 'tr',
+ 'zh',
+ ],
} as const;
/** Helper: get language options for a given engine. */
diff --git a/app/src/lib/hooks/useGenerationForm.ts b/app/src/lib/hooks/useGenerationForm.ts
index e90320e9..38118df9 100644
--- a/app/src/lib/hooks/useGenerationForm.ts
+++ b/app/src/lib/hooks/useGenerationForm.ts
@@ -27,6 +27,7 @@ const generationSchema = z.object({
'chatterbox_turbo',
'tada',
'kokoro',
+ 'omnivoice',
])
.optional(),
personality: z.boolean().optional(),
@@ -100,9 +101,11 @@ export function useGenerationForm(options: UseGenerationFormOptions = {}) {
: 'tada-1b'
: engine === 'kokoro'
? 'kokoro'
- : engine === 'qwen_custom_voice'
- ? `qwen-custom-voice-${data.modelSize}`
- : `qwen-tts-${data.modelSize}`;
+ : engine === 'omnivoice'
+ ? 'omnivoice'
+ : engine === 'qwen_custom_voice'
+ ? `qwen-custom-voice-${data.modelSize}`
+ : `qwen-tts-${data.modelSize}`;
const displayName =
engine === 'luxtts'
? 'LuxTTS'
@@ -116,13 +119,15 @@ export function useGenerationForm(options: UseGenerationFormOptions = {}) {
: 'TADA 1B'
: engine === 'kokoro'
? 'Kokoro 82M'
- : engine === 'qwen_custom_voice'
- ? data.modelSize === '1.7B'
- ? 'Qwen CustomVoice 1.7B'
- : 'Qwen CustomVoice 0.6B'
- : data.modelSize === '1.7B'
- ? 'Qwen TTS 1.7B'
- : 'Qwen TTS 0.6B';
+ : engine === 'omnivoice'
+ ? 'OmniVoice'
+ : engine === 'qwen_custom_voice'
+ ? data.modelSize === '1.7B'
+ ? 'Qwen CustomVoice 1.7B'
+ : 'Qwen CustomVoice 0.6B'
+ : data.modelSize === '1.7B'
+ ? 'Qwen TTS 1.7B'
+ : 'Qwen TTS 0.6B';
// Check if model needs downloading
try {
diff --git a/backend/backends/__init__.py b/backend/backends/__init__.py
index 4da1a439..27082723 100644
--- a/backend/backends/__init__.py
+++ b/backend/backends/__init__.py
@@ -224,6 +224,7 @@ TTS_ENGINES = {
"chatterbox_turbo": "Chatterbox Turbo",
"tada": "TADA",
"kokoro": "Kokoro",
+ "omnivoice": "OmniVoice",
}
LLM_ENGINES = {
@@ -396,6 +397,42 @@ def _get_non_qwen_tts_configs() -> list[ModelConfig]:
size_mb=350,
languages=["en", "es", "fr", "hi", "it", "pt", "ja", "zh"],
),
+ ModelConfig(
+ model_name="omnivoice",
+ display_name="OmniVoice (600+ Languages)",
+ engine="omnivoice",
+ hf_repo_id="k2-fsa/OmniVoice",
+ size_mb=3300,
+ supports_instruct=True,
+ # OmniVoice covers 600+ languages; these are the ones already in
+ # Voicebox's language enum. Widening that enum is a separate change
+ # that touches the API contract and the frontend.
+ languages=[
+ "zh",
+ "en",
+ "ja",
+ "ko",
+ "de",
+ "fr",
+ "ru",
+ "pt",
+ "es",
+ "it",
+ "he",
+ "ar",
+ "da",
+ "el",
+ "fi",
+ "hi",
+ "ms",
+ "nl",
+ "no",
+ "pl",
+ "sv",
+ "sw",
+ "tr",
+ ],
+ ),
]
@@ -754,6 +791,10 @@ def get_tts_backend_for_engine(engine: str) -> TTSBackend:
from .kokoro_backend import KokoroTTSBackend
backend = KokoroTTSBackend()
+ elif engine == "omnivoice":
+ from .omnivoice_backend import OmniVoiceBackend
+
+ backend = OmniVoiceBackend()
elif engine == "qwen_custom_voice":
from .qwen_custom_voice_backend import QwenCustomVoiceBackend
diff --git a/backend/backends/omnivoice_backend.py b/backend/backends/omnivoice_backend.py
new file mode 100644
index 00000000..b4904f0a
--- /dev/null
+++ b/backend/backends/omnivoice_backend.py
@@ -0,0 +1,329 @@
+"""
+OmniVoice backend implementation.
+
+Wraps k2-fsa/OmniVoice, a diffusion-language-model zero-shot TTS covering 600+
+languages. ~3.3 GB of weights, 24 kHz output, RTF down to 0.025 on CUDA.
+
+Two things set this engine apart from the rest of the roster:
+
+ - It needs ``transformers.HiggsAudioV2TokenizerModel`` as its audio codec,
+ which only exists in transformers >= 5.3 while Voicebox is pinned to
+ <= 4.57.6. ``backend/utils/transformers5_compat.py`` grafts a vendored
+ copy onto the transformers namespace; it must run before ``omnivoice`` is
+ imported.
+ - Its ``instruct`` parameter is a closed attribute vocabulary (gender, age,
+ pitch, whisper, English accent, Chinese dialect), not the free-form prose
+ Qwen CustomVoice accepts. Anything outside it raises upstream.
+
+Languages: the 22 codes Voicebox already knows that OmniVoice also covers,
+plus Arabic via the ISO 639-3 code ``arb``. OmniVoice supports far more, but
+exposing them means widening the language enum across the API and frontend.
+"""
+
+import asyncio
+import gc
+import logging
+import sys
+from typing import Any, Optional, Tuple
+
+import numpy as np
+
+from .base import (
+ combine_voice_prompts as _combine_voice_prompts,
+ empty_device_cache,
+ get_torch_device,
+ is_model_cached,
+ manual_seed,
+ model_load_progress,
+)
+from ..utils.cache import cache_voice_prompt, get_cache_key, get_cached_voice_prompt
+
+logger = logging.getLogger(__name__)
+
+OMNIVOICE_HF_REPO = "k2-fsa/OmniVoice"
+
+# OmniVoice speaks ISO 639-3. Most of Voicebox's two-letter codes are valid
+# 639-3 codes too and pass straight through; Arabic is the exception, because
+# OmniVoice enumerates the individual varieties rather than the "ar"
+# macrolanguage. "arb" is Modern Standard Arabic.
+LANGUAGE_CODE_OVERRIDES = {"ar": "arb"}
+
+# Output sample rate, from the audio tokenizer's feature extractor. Read off
+# the loaded model when available; this is the fallback.
+DEFAULT_SAMPLE_RATE = 24000
+
+# Diffusion steps. Upstream defaults to 32; 16 roughly halves latency at some
+# quality cost.
+NUM_DIFFUSION_STEPS = 32
+
+_VOICE_CLONE_PROMPT_FORMAT_VERSION = 1
+
+
+def _clear_codec_layer_cache() -> None:
+ """Release the Higgs codec's per-instance layer cache.
+
+ ``HiggsAudioV2TokenizerPreTrainedModel._get_conv1d_layers`` carries an
+ ``@lru_cache`` on an instance method. The cache key includes ``self``, and
+ the cache lives on the function object — which lives on the class — so the
+ first call pins the tokenizer instance for the lifetime of the process.
+ Encoding a voice prompt triggers exactly one call, after which unloading
+ the engine strands ~0.8 GB of codec weights on the device.
+
+ Upstream bug, vendored verbatim from transformers rather than patched, so
+ a re-sync does not silently drop the fix. Clearing here costs one recompute
+ on the next load.
+ """
+ module = sys.modules.get(
+ "backend.vendor.higgs_audio_v2_tokenizer.modeling_higgs_audio_v2_tokenizer"
+ )
+ if module is None:
+ return
+
+ cached_method = getattr(
+ getattr(module, "HiggsAudioV2TokenizerPreTrainedModel", None),
+ "_get_conv1d_layers",
+ None,
+ )
+ cache_clear = getattr(cached_method, "cache_clear", None)
+ if cache_clear is not None:
+ cache_clear()
+
+
+class OmniVoiceBackend:
+ """OmniVoice backend for zero-shot voice cloning and voice design."""
+
+ def __init__(self):
+ self.model = None
+ self.model_size = "default" # OmniVoice ships a single checkpoint
+ self._device = None
+ self._asr_loaded = False
+
+ def _get_device(self) -> str:
+ # MPS is allowed: from_pretrained keeps the audio tokenizer on CPU
+ # there by itself, because the codec exceeds the 65536 output-channel
+ # limit MPS imposes.
+ return get_torch_device(allow_mps=True, allow_xpu=True)
+
+ @property
+ def device(self) -> str:
+ if self._device is None:
+ self._device = self._get_device()
+ return self._device
+
+ def is_loaded(self) -> bool:
+ return self.model is not None
+
+ def _get_model_path(self, model_size: str) -> str:
+ return OMNIVOICE_HF_REPO
+
+ def _is_model_cached(self, model_size: str = "default") -> bool:
+ return is_model_cached(OMNIVOICE_HF_REPO)
+
+ async def load_model(self, model_size: str = "default") -> None:
+ if self.model is not None:
+ return
+
+ await asyncio.to_thread(self._load_model_sync)
+
+ def _load_model_sync(self) -> None:
+ model_name = "omnivoice"
+ is_cached = self._is_model_cached()
+
+ with model_load_progress(model_name, is_cached):
+ import torch
+
+ # Must precede the omnivoice import: omnivoice does
+ # `from transformers import HiggsAudioV2TokenizerModel` at module
+ # scope, and on transformers 4.57.x that name does not exist.
+ from ..utils.transformers5_compat import install as install_transformers5_compat
+
+ install_transformers5_compat()
+
+ from omnivoice import OmniVoice
+
+ device = self.device
+ # fp16 on accelerators, fp32 on CPU and MPS. MPS fp16 underflows
+ # in the diffusion loop; CPU fp16 is slower than fp32.
+ dtype = (
+ torch.float16
+ if device in ("cuda", "xpu")
+ else torch.float32
+ )
+
+ logger.info("Loading OmniVoice on %s (%s)...", device, dtype)
+
+ self.model = OmniVoice.from_pretrained(
+ OMNIVOICE_HF_REPO,
+ device_map=device,
+ dtype=dtype,
+ )
+
+ logger.info("OmniVoice loaded successfully")
+
+ def unload_model(self) -> None:
+ if self.model is not None:
+ device = self.device
+ del self.model
+ self.model = None
+ self._device = None
+ self._asr_loaded = False
+
+ _clear_codec_layer_cache()
+ gc.collect()
+ empty_device_cache(device)
+
+ logger.info("OmniVoice unloaded")
+
+ @property
+ def sample_rate(self) -> int:
+ return int(getattr(self.model, "sampling_rate", DEFAULT_SAMPLE_RATE))
+
+ def _ensure_asr(self) -> None:
+ """Load OmniVoice's Whisper for auto-transcribing a reference clip.
+
+ Only needed when a profile carries no reference text. The default is
+ openai/whisper-large-v3-turbo, the same repo behind Voicebox's own
+ "turbo" STT model, so it is often already in the HF cache.
+ """
+ if self._asr_loaded:
+ return
+ logger.info("Loading OmniVoice ASR for reference transcription...")
+ self.model.load_asr_model()
+ self._asr_loaded = True
+
+ async def create_voice_prompt(
+ self,
+ audio_path: str,
+ reference_text: str,
+ use_cache: bool = True,
+ ) -> Tuple[dict, bool]:
+ """Encode reference audio into a reusable voice clone prompt.
+
+ Returns the fields of OmniVoice's ``VoiceClonePrompt`` as a plain dict
+ rather than the dataclass itself: the on-disk cache reads back with
+ ``torch.load(weights_only=True)``, which refuses arbitrary classes.
+ The layout matches ``VoiceClonePrompt.save()`` exactly.
+ """
+ await self.load_model()
+
+ cache_key = (
+ ("omnivoice_" + get_cache_key(audio_path, reference_text)) if use_cache else None
+ )
+
+ if cache_key:
+ cached = get_cached_voice_prompt(cache_key)
+ if isinstance(cached, dict) and "ref_audio_tokens" in cached:
+ return cached, True
+
+ def _encode_sync() -> dict:
+ ref_text = reference_text or None
+ if ref_text is None:
+ self._ensure_asr()
+
+ prompt = self.model.create_voice_clone_prompt(
+ ref_audio=str(audio_path),
+ ref_text=ref_text,
+ )
+ return {
+ "format_version": _VOICE_CLONE_PROMPT_FORMAT_VERSION,
+ "ref_audio_tokens": prompt.ref_audio_tokens.detach().cpu(),
+ "ref_text": prompt.ref_text,
+ "ref_rms": float(prompt.ref_rms),
+ }
+
+ encoded = await asyncio.to_thread(_encode_sync)
+
+ if cache_key:
+ cache_voice_prompt(cache_key, encoded)
+
+ return encoded, False
+
+ async def combine_voice_prompts(self, audio_paths, reference_texts):
+ return await _combine_voice_prompts(
+ audio_paths, reference_texts, sample_rate=DEFAULT_SAMPLE_RATE
+ )
+
+ async def generate(
+ self,
+ text: str,
+ voice_prompt: dict,
+ language: str = "en",
+ seed: Optional[int] = None,
+ instruct: Optional[str] = None,
+ ) -> Tuple[np.ndarray, int]:
+ """
+ Generate audio from text using OmniVoice.
+
+ Args:
+ text: Text to synthesize.
+ voice_prompt: Dict produced by create_voice_prompt(). Empty or
+ missing tokens fall back to voice design / auto voice.
+ language: Voicebox two-letter code, translated to ISO 639-3.
+ seed: Random seed for reproducibility.
+ instruct: Voice design attributes, comma-separated — e.g.
+ "female, low pitch, british accent". This is a closed
+ vocabulary, not free-form prose.
+
+ Returns:
+ Tuple of (audio_array, sample_rate).
+
+ Raises:
+ ValueError: if instruct contains attributes OmniVoice does not
+ recognise. The upstream message names the offending items.
+ """
+ await self.load_model()
+
+ clone_prompt = self._rebuild_clone_prompt(voice_prompt)
+ resolved_language = LANGUAGE_CODE_OVERRIDES.get(language, language)
+
+ def _generate_sync() -> Tuple[np.ndarray, int]:
+ if seed is not None:
+ manual_seed(seed, self.device)
+
+ kwargs: dict[str, Any] = {
+ "text": text,
+ "language": resolved_language,
+ "num_step": NUM_DIFFUSION_STEPS,
+ }
+ if clone_prompt is not None:
+ kwargs["voice_clone_prompt"] = clone_prompt
+ if instruct:
+ kwargs["instruct"] = instruct
+
+ try:
+ audios = self.model.generate(**kwargs)
+ except ValueError as exc:
+ if instruct and "instruct" in str(exc).lower():
+ raise ValueError(
+ "OmniVoice voice design accepts a fixed set of "
+ "attributes (gender, age, pitch, whisper, English "
+ f"accent, Chinese dialect), not free text. {exc}"
+ ) from exc
+ raise
+
+ return audios[0], self.sample_rate
+
+ return await asyncio.to_thread(_generate_sync)
+
+ def _rebuild_clone_prompt(self, voice_prompt: dict):
+ """Turn a cached prompt dict back into OmniVoice's dataclass.
+
+ Returns None when the profile carries no cloned reference, which puts
+ generation into voice-design or auto-voice mode.
+ """
+ if not voice_prompt or "ref_audio_tokens" not in voice_prompt:
+ return None
+
+ from omnivoice import VoiceClonePrompt
+
+ version = voice_prompt.get("format_version")
+ if version != _VOICE_CLONE_PROMPT_FORMAT_VERSION:
+ raise ValueError(
+ f"Unsupported OmniVoice voice prompt format version: {version}"
+ )
+
+ return VoiceClonePrompt(
+ ref_audio_tokens=voice_prompt["ref_audio_tokens"],
+ ref_text=voice_prompt["ref_text"],
+ ref_rms=voice_prompt["ref_rms"],
+ )
diff --git a/backend/build_binary.py b/backend/build_binary.py
index 0a7cf879..88e3a93c 100644
--- a/backend/build_binary.py
+++ b/backend/build_binary.py
@@ -268,6 +268,45 @@ def build_server(cuda=False, rocm=False):
"torchaudio",
"--collect-submodules",
"tada",
+ # OmniVoice — diffusion LM TTS, 600+ languages.
+ "--hidden-import",
+ "backend.backends.omnivoice_backend",
+ # The Higgs Audio V2 codec is vendored from transformers 5.x (we are
+ # capped at 4.57.6). Both the shim and the vendored package are
+ # imported from inside a function, so name them explicitly.
+ "--hidden-import",
+ "backend.utils.transformers5_compat",
+ "--collect-submodules",
+ "backend.vendor",
+ "--hidden-import",
+ "omnivoice",
+ "--hidden-import",
+ "omnivoice.models.omnivoice",
+ "--hidden-import",
+ "omnivoice.utils.audio",
+ "--hidden-import",
+ "omnivoice.utils.text",
+ "--hidden-import",
+ "omnivoice.utils.voice_design",
+ "--hidden-import",
+ "omnivoice.utils.duration",
+ "--hidden-import",
+ "omnivoice.utils.lang_map",
+ # omnivoice/__init__.py calls importlib.metadata.version("omnivoice").
+ # It degrades to "0.0.0" without metadata, but ship it anyway.
+ "--copy-metadata",
+ "omnivoice",
+ # The vendored codec builds its two sub-models through
+ # AutoModel.from_config(), which transformers resolves at runtime —
+ # static analysis cannot see either of them.
+ "--hidden-import",
+ "transformers.models.dac",
+ "--hidden-import",
+ "transformers.models.hubert",
+ # Reference-audio preprocessing (silence trimming) in
+ # omnivoice.utils.audio.
+ "--hidden-import",
+ "pydub",
# Kokoro 82M — lightweight TTS engine using misaki G2P
# collect-all is required because transformers introspects .py source
# files at runtime (e.g. _can_set_attn_implementation opens the class
diff --git a/backend/models.py b/backend/models.py
index 94a9fd54..ed43bd15 100644
--- a/backend/models.py
+++ b/backend/models.py
@@ -85,7 +85,7 @@ class GenerationRequest(BaseModel):
seed: Optional[int] = Field(None, ge=0)
model_size: Optional[str] = Field(default="1.7B", pattern="^(1\\.7B|0\\.6B|1B|3B)$")
instruct: Optional[str] = Field(None, max_length=500)
- engine: Optional[str] = Field(default=None, pattern="^(qwen|qwen_custom_voice|luxtts|chatterbox|chatterbox_turbo|tada|kokoro)$")
+ engine: Optional[str] = Field(default=None, pattern="^(qwen|qwen_custom_voice|luxtts|chatterbox|chatterbox_turbo|tada|kokoro|omnivoice)$")
personality: bool = Field(
default=False,
description="When true and the profile has a personality prompt, the input text is rewritten in-character before TTS.",
@@ -317,7 +317,7 @@ class MCPClientBindingResponse(BaseModel):
profile_id: Optional[str] = None
default_engine: Optional[str] = Field(
None,
- pattern="^(qwen|qwen_custom_voice|luxtts|chatterbox|chatterbox_turbo|tada|kokoro)$",
+ pattern="^(qwen|qwen_custom_voice|luxtts|chatterbox|chatterbox_turbo|tada|kokoro|omnivoice)$",
)
default_personality: bool = False
last_seen_at: Optional[datetime] = None
@@ -336,7 +336,7 @@ class MCPClientBindingUpsert(BaseModel):
profile_id: Optional[str] = None
default_engine: Optional[str] = Field(
None,
- pattern="^(qwen|qwen_custom_voice|luxtts|chatterbox|chatterbox_turbo|tada|kokoro)$",
+ pattern="^(qwen|qwen_custom_voice|luxtts|chatterbox|chatterbox_turbo|tada|kokoro|omnivoice)$",
)
default_personality: bool = False
@@ -355,7 +355,7 @@ class SpeakRequest(BaseModel):
)
engine: Optional[str] = Field(
None,
- pattern="^(qwen|qwen_custom_voice|luxtts|chatterbox|chatterbox_turbo|tada|kokoro)$",
+ pattern="^(qwen|qwen_custom_voice|luxtts|chatterbox|chatterbox_turbo|tada|kokoro|omnivoice)$",
)
personality: Optional[bool] = Field(
None,
diff --git a/backend/requirements.txt b/backend/requirements.txt
index 92621822..fbbeb71e 100644
--- a/backend/requirements.txt
+++ b/backend/requirements.txt
@@ -40,6 +40,16 @@ pyloudnorm
# provides the only class TADA uses: Snake1d.)
torchaudio
+# OmniVoice sub-dependencies (omnivoice itself is installed --no-deps
+# in the setup script because it requires transformers>=5.3, while several
+# engine workarounds here depend on transformers 4.57.x internals. The one
+# class it needs from 5.x — HiggsAudioV2TokenizerModel — is vendored under
+# backend/vendor/. Same treatment mlx-lm / mlx-audio already get.
+# Its remaining runtime deps (torch, torchaudio, transformers, accelerate,
+# numpy, soundfile, librosa) are all listed elsewhere in this file; gradio,
+# tensorboardX and webdataset are demo/training-only and deliberately skipped.
+pydub
+
# Kokoro TTS (lightweight 82M-param engine)
kokoro>=0.9.4
misaki[en,ja,zh]>=0.9.4
diff --git a/backend/services/profiles.py b/backend/services/profiles.py
index 2fad873d..7f300ee3 100644
--- a/backend/services/profiles.py
+++ b/backend/services/profiles.py
@@ -32,7 +32,7 @@ from . import history
logger = logging.getLogger(__name__)
-CLONING_ENGINES = {"qwen", "luxtts", "chatterbox", "chatterbox_turbo", "tada"}
+CLONING_ENGINES = {"qwen", "luxtts", "chatterbox", "chatterbox_turbo", "tada", "omnivoice"}
def _profile_to_response(
diff --git a/backend/tests/test_omnivoice_compat.py b/backend/tests/test_omnivoice_compat.py
new file mode 100644
index 00000000..94d0f745
--- /dev/null
+++ b/backend/tests/test_omnivoice_compat.py
@@ -0,0 +1,265 @@
+"""
+Unit tests for the OmniVoice engine's transformers 5 -> 4.57.6 compatibility layer.
+
+OmniVoice is built against transformers >= 5.3; Voicebox is pinned to <= 4.57.6
+because several engine workarounds read 4.57.x internals. ``backend/vendor/``
+carries the one class that gap costs us (the Higgs Audio V2 codec) and
+``backend/utils/transformers5_compat.py`` grafts it on.
+
+None of this downloads a model or touches a GPU. The full round trip — load,
+clone, generate, unload — is covered by the manual E2E suite described in
+``backend/tests/E2E_MODEL_TEST_DESIGN.md``.
+
+NOTE: ``patch_extra_special_tokens`` mutates ``transformers.PreTrainedTokenizerBase``
+globally; run serially, not under ``pytest-xdist`` with per-worker isolation.
+"""
+
+import sys
+
+import pytest
+import torch
+from torch import nn
+from transformers.tokenization_utils_base import PreTrainedTokenizerBase
+
+import backend.utils.transformers5_compat as compat
+from backend.vendor import _compat
+
+
+# ── conv1d_output_length ──────────────────────────────────────────────
+# Absent from 4.57.6's audio_utils; the vendored codec computes encoder
+# frame counts with it.
+
+
+ "kwargs,length,expected",
+ [
+ ({"kernel_size": 1, "stride": 1}, 100, 100),
+ ({"kernel_size": 3, "stride": 1, "padding": 1}, 100, 100),
+ ({"kernel_size": 4, "stride": 2, "padding": 1}, 100, 50),
+ ({"kernel_size": 3, "stride": 1, "dilation": 2, "padding": 2}, 100, 100),
+ ],
+)
+def test_conv1d_output_length_matches_torch(kwargs, length, expected):
+ layer = nn.Conv1d(1, 1, **kwargs)
+ assert _compat.conv1d_output_length(layer, length) == expected
+ # Cross-check against what the layer actually produces.
+ actual = layer(torch.zeros(1, 1, length)).shape[-1]
+ assert _compat.conv1d_output_length(layer, length) == actual
+
+
+# ── initialization module ─────────────────────────────────────────────
+# 5.x-only. Only reached from _init_weights, i.e. for weights missing from
+# the checkpoint.
+
+
+def test_initialization_functions_mutate_in_place_and_return_tensor():
+ tensor = torch.empty(4, 4)
+ result = _compat.initialization.zeros_(tensor)
+ assert result is tensor
+ assert torch.all(result == 0)
+
+ assert torch.all(_compat.initialization.ones_(torch.empty(3)) == 1)
+ assert _compat.initialization.normal_(torch.empty(8), mean=0.0, std=0.02) is not None
+
+
+def test_initialization_copy_writes_through():
+ target = torch.zeros(2)
+ source = torch.tensor([1.0, 2.0])
+ assert torch.equal(_compat.initialization.copy_(target, source), source)
+
+
+# ── PreTrainedConfig dataclass adapter ────────────────────────────────
+# 5.x configs are dataclasses whose generated __init__ ends in __post_init__.
+# 4.57.6's PretrainedConfig never calls it, which leaves sub-configs as raw
+# dicts and blows up later in to_diff_dict().
+
+
+class _SampleConfig(_compat.PreTrainedConfig):
+ model_type = "sample_compat_config"
+
+ plain_field: int = 7
+ listy_field: list = None
+ nested: dict = None
+
+ def __post_init__(self, **kwargs):
+ if isinstance(self.nested, dict):
+ self.nested = dict(self.nested, promoted=True)
+ super().__post_init__(**kwargs)
+
+
+def test_annotated_defaults_are_applied():
+ config = _SampleConfig()
+ assert config.plain_field == 7
+ assert config.nested is None
+
+
+def test_kwargs_override_defaults():
+ config = _SampleConfig(plain_field=42)
+ assert config.plain_field == 42
+
+
+def test_post_init_runs():
+ config = _SampleConfig(nested={"a": 1})
+ assert config.nested == {"a": 1, "promoted": True}
+
+
+def test_mutable_defaults_are_not_shared_between_instances():
+ class _ListConfig(_compat.PreTrainedConfig):
+ model_type = "list_compat_config"
+ items: list = []
+
+ first, second = _ListConfig(), _ListConfig()
+ first.items.append("x")
+ assert second.items == []
+
+
+def test_leftover_kwargs_reach_pretrained_config():
+ config = _SampleConfig(plain_field=1, output_hidden_states=True)
+ assert config.output_hidden_states is True
+
+
+# ── auto_docstring / strict no-ops ────────────────────────────────────
+# Both raise on 4.57.6 for the vendored class: auto_docstring rejects names
+# outside its registry, strict requires a dataclass.
+
+
+def test_auto_docstring_returns_target_unchanged():
+ class Target:
+ pass
+
+ assert _compat.auto_docstring(Target) is Target
+ assert _compat.auto_docstring(custom_intro="x")(Target) is Target
+
+
+def test_strict_returns_target_unchanged():
+ class Target:
+ pass
+
+ assert _compat.strict(Target) is Target
+ assert _compat.strict()(Target) is Target
+
+
+# ── extra_special_tokens list form ────────────────────────────────────
+# OmniVoice's tokenizer_config.json writes a list (5.x form); 4.57.6 calls
+# .keys() on it.
+
+
+def restore_special_tokens_hook():
+ saved = PreTrainedTokenizerBase.__dict__.get("_set_model_specific_special_tokens")
+ yield
+ if saved is not None:
+ PreTrainedTokenizerBase._set_model_specific_special_tokens = saved
+
+
+def test_patch_coerces_list_to_mapping(restore_special_tokens_hook):
+ seen = {}
+
+ def fake(self, special_tokens):
+ seen.update(special_tokens)
+
+ PreTrainedTokenizerBase._set_model_specific_special_tokens = fake
+ assert compat.patch_extra_special_tokens() is True
+
+ PreTrainedTokenizerBase._set_model_specific_special_tokens(
+ object(), ["<|lang_start|>", "<|text_end|>"]
+ )
+ assert seen == {
+ "lang_start_token": "<|lang_start|>",
+ "text_end_token": "<|text_end|>",
+ }
+
+
+def test_patch_leaves_mapping_form_alone(restore_special_tokens_hook):
+ seen = {}
+
+ def fake(self, special_tokens):
+ seen.update(special_tokens)
+
+ PreTrainedTokenizerBase._set_model_specific_special_tokens = fake
+ compat.patch_extra_special_tokens()
+
+ PreTrainedTokenizerBase._set_model_specific_special_tokens(
+ object(), {"boundary_token": "<|b|>"}
+ )
+ assert seen == {"boundary_token": "<|b|>"}
+
+
+def test_patch_is_idempotent(restore_special_tokens_hook):
+ PreTrainedTokenizerBase._set_model_specific_special_tokens = lambda self, tokens: None
+ assert compat.patch_extra_special_tokens() is True
+ assert compat.patch_extra_special_tokens() is False
+
+
+ "token,expected",
+ [
+ ("<|denoise|>", "denoise_token"),
+ ("<|instruct_start|>", "instruct_start_token"),
+ ("[SEP]", "sep_token"),
+ ("<mask>", "mask_token"),
+ ("<|weird-one|>", "weird_one_token"),
+ ],
+)
+def test_attribute_name_derivation(token, expected):
+ assert compat._attribute_name(token) == expected
+
+
+# ── engine wiring ─────────────────────────────────────────────────────
+
+
+def test_omnivoice_is_registered():
+ from backend.backends import TTS_ENGINES, get_model_config
+
+ assert TTS_ENGINES["omnivoice"] == "OmniVoice"
+
+ config = get_model_config("omnivoice")
+ assert config is not None
+ assert config.engine == "omnivoice"
+ assert config.hf_repo_id == "k2-fsa/OmniVoice"
+ assert config.supports_instruct is True
+
+
+def test_omnivoice_accepts_cloned_profiles():
+ """Regression: the service-layer allow-list is separate from the frontend one."""
+ from backend.services.profiles import CLONING_ENGINES
+
+ assert "omnivoice" in CLONING_ENGINES
+
+
+def test_declared_languages_are_resolvable_by_omnivoice():
+ """Every advertised code must map to something OmniVoice actually knows.
+
+ OmniVoice speaks ISO 639-3. Most two-letter codes pass straight through,
+ but Arabic does not: it enumerates varieties instead of the macrolanguage.
+ """
+ # omnivoice imports HiggsAudioV2TokenizerModel at module scope, so the
+ # shim has to be in place before the import -- which is itself the point.
+ compat.install()
+ try:
+ from omnivoice.utils.lang_map import LANG_NAME_TO_ID
+ except ImportError as exc: # pragma: no cover - omnivoice not installed
+ pytest.skip(f"omnivoice unavailable: {exc}")
+
+ from backend.backends import get_model_config
+ from backend.backends.omnivoice_backend import LANGUAGE_CODE_OVERRIDES
+
+ known = set(LANG_NAME_TO_ID.values())
+ unresolved = [
+ code
+ for code in get_model_config("omnivoice").languages
+ if LANGUAGE_CODE_OVERRIDES.get(code, code) not in known
+ ]
+ assert unresolved == []
+
+
+def test_clear_codec_layer_cache_is_safe_when_codec_never_imported():
+ from backend.backends.omnivoice_backend import _clear_codec_layer_cache
+
+ name = "backend.vendor.higgs_audio_v2_tokenizer.modeling_higgs_audio_v2_tokenizer"
+ saved = sys.modules.pop(name, None)
+ try:
+ _clear_codec_layer_cache() # must not raise
+ finally:
+ if saved is not None:
+ sys.modules[name] = saved
diff --git a/backend/utils/transformers5_compat.py b/backend/utils/transformers5_compat.py
new file mode 100644
index 00000000..c59e4372
--- /dev/null
+++ b/backend/utils/transformers5_compat.py
@@ -0,0 +1,180 @@
+"""Let transformers-5-era model assets load on the transformers 4.57.6 we pin.
+
+Voicebox cannot move to transformers 5: the offline-mode fix in
+``backend/utils/hf_offline_patch.py`` and the frozen-build rewrite in
+``backend/pyi_rth_torch_compiler_disable.py`` both read 4.57.x internals, and
+seven shipping engines depend on them. OmniVoice, however, was authored against
+transformers 5.3+ and trips over two gaps:
+
+1. Its audio codec is ``transformers.HiggsAudioV2TokenizerModel``, a class that
+ does not exist before 5.3. The weights ship inside the OmniVoice repo, so
+ only the modelling code is missing -- we vendor it under
+ ``backend/vendor/higgs_audio_v2_tokenizer`` and graft it on.
+2. Its ``tokenizer_config.json`` writes ``extra_special_tokens`` as a list,
+ the 5.x form. 4.57.6 expects a mapping and raises ``AttributeError``.
+
+Both fixes are additive: they add a name that was absent, and accept an input
+shape that previously crashed. Neither changes behaviour for the other engines.
+
+Same spirit as ``backend/utils/dac_shim.py``, which fakes ``dac.nn.layers`` so
+TADA can skip the descript-audio-codec dependency tree. The direction differs:
+that one replaces a package we do not want, these back-port from a version we
+cannot upgrade to.
+
+``install()`` must run before ``omnivoice`` is imported. It is idempotent, and
+each half no-ops when the running transformers already handles the case.
+"""
+
+import logging
+import sys
+
+logger = logging.getLogger(__name__)
+
+_installed = False
+
+
+def install() -> None:
+ """Apply every transformers 5 -> 4.57.6 shim OmniVoice needs."""
+ global _installed
+
+ if _installed:
+ return
+
+ install_higgs_audio_tokenizer()
+ patch_extra_special_tokens()
+ _installed = True
+
+
+# ---------------------------------------------------------------------------
+# 1. HiggsAudioV2TokenizerModel
+# ---------------------------------------------------------------------------
+
+
+def install_higgs_audio_tokenizer() -> bool:
+ """Graft the vendored Higgs Audio V2 codec onto ``transformers``.
+
+ Returns:
+ True if the vendored copy is now in place, False if the running
+ transformers already ships the real one.
+ """
+ import transformers
+
+ if hasattr(transformers, "HiggsAudioV2TokenizerModel"):
+ logger.debug(
+ "transformers %s ships HiggsAudioV2TokenizerModel, skipping shim",
+ transformers.__version__,
+ )
+ return False
+
+ from ..vendor import higgs_audio_v2_tokenizer as vendored
+ from ..vendor.higgs_audio_v2_tokenizer import (
+ configuration_higgs_audio_v2_tokenizer as vendored_config,
+ )
+ from ..vendor.higgs_audio_v2_tokenizer import (
+ modeling_higgs_audio_v2_tokenizer as vendored_modeling,
+ )
+
+ # The first import of transformers.processing_utils -- which the line above
+ # triggers -- re-runs transformers/__init__.py and rebinds
+ # sys.modules["transformers"] to a fresh _LazyModule. Anything set on the
+ # old object is lost, so re-fetch here, after the vendored import.
+ transformers = sys.modules["transformers"]
+
+ # Register under the module path upstream uses, so anything resolving the
+ # class by qualified name (pickling, AutoModel, remote-code loaders) finds
+ # it where it expects to.
+ base = "transformers.models.higgs_audio_v2_tokenizer"
+ sys.modules.setdefault(base, vendored)
+ sys.modules.setdefault(f"{base}.configuration_higgs_audio_v2_tokenizer", vendored_config)
+ sys.modules.setdefault(f"{base}.modeling_higgs_audio_v2_tokenizer", vendored_modeling)
+ setattr(transformers.models, "higgs_audio_v2_tokenizer", vendored)
+
+ # transformers is a _LazyModule whose __getattr__ only fires when normal
+ # attribute lookup fails, so a plain setattr wins for
+ # `from transformers import HiggsAudioV2TokenizerModel`.
+ for name in vendored.__all__:
+ setattr(transformers, name, getattr(vendored, name))
+
+ _register_with_auto_classes(vendored)
+
+ logger.info(
+ "installed vendored HiggsAudioV2Tokenizer (transformers %s lacks it)",
+ transformers.__version__,
+ )
+ return True
+
+
+def _register_with_auto_classes(vendored) -> None:
+ """Wire the vendored config/model into AutoConfig and AutoModel.
+
+ Not needed for OmniVoice's own load path, which instantiates the concrete
+ class, but it keeps ``AutoModel.from_config`` working for anything that
+ reaches the codec generically. Registration raises if the model type is
+ already known, which is fine to ignore.
+ """
+ from transformers import AutoConfig, AutoModel
+
+ try:
+ AutoConfig.register("higgs_audio_v2_tokenizer", vendored.HiggsAudioV2TokenizerConfig)
+ AutoModel.register(
+ vendored.HiggsAudioV2TokenizerConfig, vendored.HiggsAudioV2TokenizerModel
+ )
+ except ValueError as exc:
+ logger.debug("auto-class registration skipped: %s", exc)
+
+
+# ---------------------------------------------------------------------------
+# 2. extra_special_tokens as a list
+# ---------------------------------------------------------------------------
+
+
+def patch_extra_special_tokens() -> bool:
+ """Accept the 5.x list form of ``extra_special_tokens``.
+
+ 4.57.6's ``_set_model_specific_special_tokens`` calls ``.keys()`` on its
+ argument, so a list from a 5.x-era tokenizer_config.json dies with
+ ``AttributeError: 'list' object has no attribute 'keys'``. 5.x accepts both
+ shapes: a list means "these are special, but under no named attribute",
+ which 4.57.6 has no way to express, so we derive a name per token.
+
+ The tokens themselves are already marked ``special: true`` inside
+ tokenizer.json, so segmentation is correct either way — this only restores
+ the attribute exposure and, more to the point, stops the crash.
+
+ Returns:
+ True if the wrapper was installed, False if it was already there or
+ the running transformers needs no help.
+ """
+ from transformers.tokenization_utils_base import PreTrainedTokenizerBase
+
+ original = getattr(PreTrainedTokenizerBase, "_set_model_specific_special_tokens", None)
+ if original is None:
+ logger.debug("transformers has no _set_model_specific_special_tokens, skipping patch")
+ return False
+
+ if getattr(original, "_voicebox_patched", False):
+ return False
+
+ def patched(self, special_tokens):
+ if isinstance(special_tokens, (list, tuple, set)):
+ special_tokens = {_attribute_name(token): token for token in special_tokens}
+ return original(self, special_tokens)
+
+ patched._voicebox_patched = True
+ PreTrainedTokenizerBase._set_model_specific_special_tokens = patched
+
+ logger.debug("installed extra_special_tokens list-form wrapper")
+ return True
+
+
+def _attribute_name(token: str) -> str:
+ """Derive an attribute name for an unnamed extra special token.
+
+ ``"<|lang_start|>"`` becomes ``"lang_start_token"``, matching the
+ ``*_token`` convention of the built-in SPECIAL_TOKENS_ATTRIBUTES.
+ """
+ stem = str(token).strip()
+ for delimiter in ("<|", "|>", "<", ">", "[", "]"):
+ stem = stem.replace(delimiter, "")
+ stem = "".join(char if char.isalnum() else "_" for char in stem).strip("_").lower()
+ return f"{stem or 'extra'}_token"
diff --git a/backend/vendor/__init__.py b/backend/vendor/__init__.py
new file mode 100644
index 00000000..285d910d
--- /dev/null
+++ b/backend/vendor/__init__.py
@@ -0,0 +1,6 @@
+"""Third-party source vendored into the Voicebox backend.
+
+Contents here are near-verbatim copies of upstream code with only their
+imports rewritten. Do not hand-edit -- each subpackage documents the script
+that regenerates it.
+"""
diff --git a/backend/vendor/_compat.py b/backend/vendor/_compat.py
new file mode 100644
index 00000000..366a677b
--- /dev/null
+++ b/backend/vendor/_compat.py
@@ -0,0 +1,170 @@
+"""Compatibility shims for code vendored from transformers 5.x.
+
+Voicebox pins ``transformers<=4.57.6``. The Higgs Audio V2 tokenizer vendored
+into this package was written against 5.x and reaches for three symbols that
+4.57.6 does not export. All three are thin and stable, so we reimplement them
+here rather than move the whole app to transformers 5 and break the seven
+engines whose workarounds depend on 4.57.x internals (see
+``backend/utils/hf_offline_patch.py`` and
+``backend/pyi_rth_torch_compiler_disable.py``).
+
+Everything else the vendored code imports (``PreTrainedAudioTokenizerBase``,
+``Unpack``, ``TransformersKwargs``, ``auto_docstring``, ``can_return_tuple``,
+``ModelOutput``, ``requires``, ``AutoModel``) already exists in 4.57.6.
+"""
+
+import copy
+import types
+
+import torch
+from torch import nn
+from transformers.configuration_utils import PretrainedConfig
+
+_NO_DEFAULT = object()
+
+
+def _annotated_defaults(cls) -> dict:
+ """Collect the dataclass-style field defaults a vendored config declares.
+
+ Walks the MRO up to (but not including) :class:`PreTrainedConfig`, so only
+ fields introduced by vendored classes are returned — never the hundred-odd
+ attributes 4.57.6's PretrainedConfig manages itself.
+ """
+ defaults: dict = {}
+ for klass in reversed(cls.__mro__):
+ if klass in (PreTrainedConfig, PretrainedConfig, object):
+ continue
+ for name in getattr(klass, "__annotations__", {}):
+ if name.startswith("_"):
+ continue
+ value = klass.__dict__.get(name, _NO_DEFAULT)
+ if value is not _NO_DEFAULT:
+ defaults[name] = value
+ return defaults
+
+
+class PreTrainedConfig(PretrainedConfig):
+ """4.57.6 stand-in for the transformers 5.x config base class.
+
+ 5.x turned configs into dataclasses: fields are class-level annotations
+ with defaults, and a generated ``__init__`` ends by calling
+ ``__post_init__``, where subclasses promote nested dicts into real config
+ objects. 4.57.6's ``PretrainedConfig`` is an ordinary class that never
+ calls ``__post_init__``, which leaves ``sub_configs`` as plain dicts and
+ blows up later in ``to_diff_dict()``.
+
+ This reproduces the part of the 5.x protocol the vendored code relies on:
+ apply annotated defaults, bind the incoming values, then hand control to
+ ``__post_init__`` — which forwards the leftovers to the 4.57.6
+ ``__init__`` through the base implementation below.
+
+ Not a general-purpose backport. It covers exactly what
+ ``HiggsAudioV2TokenizerConfig`` needs.
+ """
+
+ def __init__(self, **kwargs):
+ for name, default in _annotated_defaults(type(self)).items():
+ if name in kwargs:
+ setattr(self, name, kwargs.pop(name))
+ else:
+ setattr(self, name, copy.deepcopy(default))
+
+ self.__post_init__(**kwargs)
+
+ def __post_init__(self, **kwargs):
+ PretrainedConfig.__init__(self, **kwargs)
+
+
+def strict(cls=None, **kwargs):
+ """No-op stand-in for ``huggingface_hub.dataclasses.strict``.
+
+ The real decorator adds runtime type validation to dataclass fields, and
+ refuses to wrap anything that is not a dataclass. ``PreTrainedConfig`` is a
+ dataclass in transformers 5.x but a plain class in 4.57.6, so applying it
+ here raises at class-definition time. The vendored config declares its
+ fields through a normal ``__init__``, so the validation has nothing to
+ check and dropping it changes no behaviour we depend on.
+ """
+ if cls is None:
+ return lambda inner: inner
+ return cls
+
+
+def conv1d_output_length(module: nn.Conv1d, input_length: int) -> int:
+ """Output length of a 1D convolution.
+
+ Verbatim from ``transformers.audio_utils.conv1d_output_length`` (5.x),
+ which does not exist in 4.57.6.
+ """
+ return int(
+ (
+ input_length
+ + 2 * module.padding[0]
+ - module.dilation[0] * (module.kernel_size[0] - 1)
+ - 1
+ )
+ / module.stride[0]
+ + 1
+ )
+
+
+def auto_docstring(obj=None, **kwargs):
+ """No-op stand-in for ``transformers.utils.auto_docstring``.
+
+ 4.57.6's version only accepts classes whose name matches an entry in its
+ internal registry (``...Model``, ``...ForCausalLM``, and so on) and raises
+ on anything else; 5.x dropped that restriction. It composes docstrings and
+ nothing else, so returning the object untouched costs only documentation.
+ """
+ if obj is None:
+ return lambda inner: inner
+ return obj
+
+
+def _build_initialization_module() -> types.ModuleType:
+ """Stand in for ``transformers.initialization`` (5.x only).
+
+ Upstream that module is a set of thin wrappers over ``torch.nn.init`` that
+ return the tensor and honour a global skip-init flag. The vendored
+ tokenizer only touches it from ``_init_weights``, which runs solely for
+ weights absent from the checkpoint, so plain delegation is enough.
+ """
+ module = types.ModuleType("transformers.initialization")
+
+ for name in (
+ "uniform_",
+ "normal_",
+ "constant_",
+ "ones_",
+ "zeros_",
+ "eye_",
+ "dirac_",
+ "xavier_uniform_",
+ "xavier_normal_",
+ "kaiming_uniform_",
+ "kaiming_normal_",
+ "trunc_normal_",
+ "orthogonal_",
+ "sparse_",
+ ):
+ torch_fn = getattr(nn.init, name)
+
+ def _wrap(tensor, *args, _fn=torch_fn, **kwargs):
+ with torch.no_grad():
+ _fn(tensor, *args, **kwargs)
+ return tensor
+
+ setattr(module, name, _wrap)
+
+ def copy_(tensor: torch.Tensor, other: torch.Tensor) -> torch.Tensor:
+ with torch.no_grad():
+ tensor.copy_(other)
+ return tensor
+
+ module.copy_ = copy_
+ return module
+
+
+initialization = _build_initialization_module()
+
+__all__ = ["PreTrainedConfig", "conv1d_output_length", "initialization", "strict", "auto_docstring"]
diff --git a/backend/vendor/higgs_audio_v2_tokenizer/__init__.py b/backend/vendor/higgs_audio_v2_tokenizer/__init__.py
new file mode 100644
index 00000000..68fe919f
--- /dev/null
+++ b/backend/vendor/higgs_audio_v2_tokenizer/__init__.py
@@ -0,0 +1,25 @@
+"""Higgs Audio V2 neural audio codec, vendored from transformers 5.x.
+
+OmniVoice imports ``HiggsAudioV2TokenizerModel`` straight from the
+``transformers`` namespace, but the class only landed in transformers 5.3 and
+Voicebox is capped at 4.57.6. The weights ship inside the OmniVoice repo
+(``audio_tokenizer/model.safetensors``); only the modelling code is missing,
+so we vendor it.
+
+Regenerate with ``python scripts/sync-higgs-tokenizer.py``. Install into the
+``transformers`` namespace with
+``backend.utils.transformers5_compat.install()`` -- that must run
+before ``omnivoice`` is imported.
+"""
+
+from .configuration_higgs_audio_v2_tokenizer import HiggsAudioV2TokenizerConfig
+from .modeling_higgs_audio_v2_tokenizer import (
+ HiggsAudioV2TokenizerModel,
+ HiggsAudioV2TokenizerPreTrainedModel,
+)
+
+__all__ = [
+ "HiggsAudioV2TokenizerConfig",
+ "HiggsAudioV2TokenizerModel",
+ "HiggsAudioV2TokenizerPreTrainedModel",
+]
diff --git a/backend/vendor/higgs_audio_v2_tokenizer/configuration_higgs_audio_v2_tokenizer.py b/backend/vendor/higgs_audio_v2_tokenizer/configuration_higgs_audio_v2_tokenizer.py
new file mode 100644
index 00000000..298e2fee
--- /dev/null
+++ b/backend/vendor/higgs_audio_v2_tokenizer/configuration_higgs_audio_v2_tokenizer.py
@@ -0,0 +1,177 @@
+# Vendored from huggingface/transformers @ main
+# src/transformers/models/higgs_audio_v2_tokenizer/configuration_higgs_audio_v2_tokenizer.py
+# Apache License 2.0 - Copyright 2025 Boson AI and The HuggingFace Team.
+#
+# Do NOT edit by hand. Regenerate with: python scripts/sync-higgs-tokenizer.py
+# Only the imports are touched; the body is verbatim.
+
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/higgs_audio_v2_tokenizer/modular_higgs_audio_v2_tokenizer.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_higgs_audio_v2_tokenizer.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 Boson AI and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import math
+
+import numpy as np
+from .._compat import strict
+
+from .._compat import PreTrainedConfig
+from transformers.utils import auto_docstring
+from transformers.models.auto import CONFIG_MAPPING, AutoConfig
+
+# Override: 4.57.6's auto_docstring rejects classes absent from its registry.
+from .._compat import auto_docstring # noqa: F811
+
+
+@auto_docstring(checkpoint="bosonai/higgs-audio-v2-tokenizer")
+@strict
+class HiggsAudioV2TokenizerConfig(PreTrainedConfig):
+ r"""
+ target_bandwidths (`List[float]`, *optional*, defaults to `[0.5, 1, 1.5, 2]`):
+ The range of different bandwidths (in kbps) the model can encode audio with.
+ kernel_size (`int`, *optional*, defaults to 3):
+ Kernel size for the initial semantic convolution.
+ channel_ratios (`List[float]`, *optional*, defaults to `[1, 1]`):
+ Expansion factors for the number of output channels in each semantic block.
+ strides (`List[int]`, *optional*, defaults to `[1, 1]`):
+ Strides for each semantic encoder block.
+ block_dilations (`List[int]`, *optional*, defaults to `[1, 1]`):
+ Dilation factors for the residual units in semantic blocks.
+ unit_kernel_size (`int`, *optional*, defaults to 3):
+ Kernel size inside each ResidualUnit in semantic blocks.
+ acoustic_model_config (`Union[Dict, AutoConfig]`, *optional*):
+ An instance of the configuration for the acoustic (DAC) model.
+ semantic_model_config (`Union[Dict, AutoConfig]`, *optional*):
+ An instance of the configuration object for the semantic (HuBERT) model.
+ semantic_sample_rate (`int`, *optional*, defaults to 16000):
+ The sampling rate at which the semantic model expects audio input, in hertz (Hz).
+ downsample_factor (`int`, *optional*, defaults to 320):
+ Downsampling factor for the semantic features.
+
+ Example:
+
+ ```python
+ >>> from transformers import HiggsAudioV2TokenizerModel, HiggsAudioV2TokenizerConfig
+
+ >>> # Initializing configuration
+ >>> configuration = HiggsAudioV2TokenizerConfig()
+
+ >>> # Initializing a model (with random weights) from the configuration
+ >>> model = HiggsAudioV2TokenizerModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "higgs_audio_v2_tokenizer"
+
+ sub_configs = {
+ "acoustic_model_config": AutoConfig,
+ "semantic_model_config": AutoConfig,
+ }
+
+ _default_acoustic_model_config_kwargs = {
+ "encoder_hidden_size": 64,
+ # NOTE: original DAC uses [2, 4, 8, 8] `downsampling ratios`, namely reverse of `upsampling_ratios`
+ # (not sure if intentional by HiggsAudioV2Tokenizer but we keep it)
+ "downsampling_ratios": [8, 5, 4, 2],
+ "decoder_hidden_size": 1024,
+ "upsampling_ratios": [8, 5, 4, 2],
+ "hidden_size": 256,
+ }
+
+ _default_semantic_model_config_kwargs = {
+ "mask_time_prob": 0.0,
+ }
+
+ target_bandwidths: list[int | float] | tuple[int | float, ...] = (0.5, 1, 1.5, 2, 4)
+ sample_rate: int = 24000
+ kernel_size: int = 3
+ channel_ratios: list[int] | tuple[int, ...] = (1, 1)
+ strides: list[int] | tuple[int, ...] = (1, 1)
+ block_dilations: list[int] | tuple[int, ...] = (1, 1)
+ unit_kernel_size: int = 3
+ codebook_size: int = 1024
+ codebook_dim: int = 64
+ initializer_range: float = 0.02
+ acoustic_model_config: dict | PreTrainedConfig | None = None
+ semantic_model_config: dict | PreTrainedConfig | None = None
+ semantic_sample_rate: int = 16000
+ downsample_factor: int = 320
+
+ def __post_init__(self, **kwargs):
+ if self.acoustic_model_config is None:
+ self.acoustic_model_config = CONFIG_MAPPING["dac"](
+ encoder_hidden_size=64,
+ # NOTE: original DAC uses [2, 4, 8, 8] `downsampling ratios`, namely reverse of `upsampling_ratios`
+ # (not sure if intentional by HiggsAudioV2Tokenizer but we keep it)
+ downsampling_ratios=[8, 5, 4, 2],
+ decoder_hidden_size=1024,
+ upsampling_ratios=[8, 5, 4, 2],
+ hidden_size=256,
+ )
+ elif isinstance(self.acoustic_model_config, dict):
+ self.acoustic_model_config["model_type"] = self.acoustic_model_config.get("model_type", "dac")
+ self.acoustic_model_config = CONFIG_MAPPING[self.acoustic_model_config["model_type"]](
+ **{**self._default_acoustic_model_config_kwargs, **self.acoustic_model_config}
+ )
+
+ if self.semantic_model_config is None:
+ self.semantic_model_config = CONFIG_MAPPING["hubert"]()
+ elif isinstance(self.semantic_model_config, dict):
+ self.semantic_model_config["model_type"] = self.semantic_model_config.get("model_type", "hubert")
+ self.semantic_model_config = CONFIG_MAPPING[self.semantic_model_config["model_type"]](
+ **{**self._default_semantic_model_config_kwargs, **self.semantic_model_config}
+ )
+
+ if self.codebook_dim is None:
+ self.codebook_dim = self.acoustic_model_config.hidden_size + self.semantic_model_config.hidden_size
+
+ super().__post_init__(**kwargs)
+
+ @property
+ def frame_rate(self) -> int:
+ return math.ceil(self.sample_rate / self.hop_length)
+
+ @property
+ def semantic_hidden_size(self) -> int:
+ return self.semantic_model_config.hidden_size
+
+ @property
+ def hop_length(self) -> int:
+ return int(np.prod(self.acoustic_model_config.downsampling_ratios))
+
+ @property
+ def codebook_nbits(self) -> int:
+ return math.ceil(math.log2(self.codebook_size))
+
+ @property
+ def hidden_size(self) -> int:
+ return self.acoustic_model_config.hidden_size + self.semantic_model_config.hidden_size
+
+ @property
+ def num_quantizers(self) -> int:
+ return int(1000 * self.target_bandwidths[-1] // (self.frame_rate * self.codebook_nbits))
+
+ @property
+ def semantic_downsample_factor(self):
+ return int(self.hop_length / (self.sample_rate / self.semantic_sample_rate) / self.downsample_factor)
+
+
+__all__ = ["HiggsAudioV2TokenizerConfig"]
diff --git a/backend/vendor/higgs_audio_v2_tokenizer/modeling_higgs_audio_v2_tokenizer.py b/backend/vendor/higgs_audio_v2_tokenizer/modeling_higgs_audio_v2_tokenizer.py
new file mode 100644
index 00000000..6baebb9d
--- /dev/null
+++ b/backend/vendor/higgs_audio_v2_tokenizer/modeling_higgs_audio_v2_tokenizer.py
@@ -0,0 +1,657 @@
+# Vendored from huggingface/transformers @ main
+# src/transformers/models/higgs_audio_v2_tokenizer/modeling_higgs_audio_v2_tokenizer.py
+# Apache License 2.0 - Copyright 2025 Boson AI and The HuggingFace Team.
+#
+# Do NOT edit by hand. Regenerate with: python scripts/sync-higgs-tokenizer.py
+# Only the imports are touched; the body is verbatim.
+
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/higgs_audio_v2_tokenizer/modular_higgs_audio_v2_tokenizer.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_higgs_audio_v2_tokenizer.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2025 Boson AI and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import math
+from dataclasses import dataclass
+from functools import lru_cache
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import torchaudio
+
+from .._compat import initialization as init
+from .._compat import conv1d_output_length
+from transformers.modeling_utils import PreTrainedAudioTokenizerBase
+from transformers.processing_utils import Unpack
+from transformers.utils import ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple
+from transformers.utils.import_utils import requires
+from transformers.models.auto import AutoModel
+from .configuration_higgs_audio_v2_tokenizer import HiggsAudioV2TokenizerConfig
+
+# Override: 4.57.6's auto_docstring rejects classes absent from its registry.
+from .._compat import auto_docstring # noqa: F811
+
+
+@requires(backends=("torchaudio",))
+@auto_docstring
+class HiggsAudioV2TokenizerPreTrainedModel(PreTrainedAudioTokenizerBase):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config_class = HiggsAudioV2TokenizerConfig
+ base_model_prefix = "higgs_audio_v2_tokenizer"
+ main_input_name = "input_values"
+ input_modalities = "audio"
+ _no_split_modules = ["HiggsAudioV2TokenizerResidualVectorQuantization"]
+ _keys_to_ignore_on_load_unexpected = ["semantic_model.masked_spec_embed"]
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, nn.Linear):
+ init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+ elif isinstance(module, nn.Conv1d):
+ init.kaiming_normal_(module.weight)
+ if module.bias is not None:
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
+ init.uniform_(module.bias, a=-k, b=k)
+ elif module.__class__.__name__ == "Snake1d":
+ init.ones_(module.alpha)
+ elif isinstance(module, nn.ConvTranspose1d):
+ module.reset_parameters()
+ elif isinstance(module, nn.Embedding):
+ init.normal_(module.weight, mean=0.0, std=0.02)
+ elif isinstance(module, HiggsAudioV2TokenizerModel):
+ # The conv1d are not handled correctly, as `self.acoustic_encoder/decoder` are initialized from a PreTrainedModel,
+ # but then only the submodules are used (which are not PreTrainedModels...) -> here we reinit them as in DacModel
+ for submodule in module.acoustic_encoder.modules():
+ if isinstance(submodule, nn.Conv1d):
+ init.trunc_normal_(submodule.weight, std=0.02)
+ init.constant_(submodule.bias, 0)
+ for submodule in module.acoustic_decoder.modules():
+ if isinstance(submodule, nn.Conv1d):
+ init.trunc_normal_(submodule.weight, std=0.02)
+ init.constant_(submodule.bias, 0)
+ elif isinstance(module, HiggsAudioV2TokenizerEuclideanCodebook):
+ init.copy_(module.inited, torch.Tensor([True]))
+ init.zeros_(module.cluster_size)
+ init.zeros_(module.embed)
+ init.zeros_(module.embed_avg)
+
+ def apply_weight_norm(self):
+ """Apply weight norm in the acoustic encoder and decoder because the original checkpoint has weight norm applied."""
+ weight_norm = torch.nn.utils.parametrizations.weight_norm
+
+ weight_norm(self.acoustic_encoder.conv1)
+ weight_norm(self.acoustic_encoder.conv2)
+
+ for block in self.acoustic_encoder.block:
+ weight_norm(block.conv1)
+ for res_unit in (block.res_unit1, block.res_unit2, block.res_unit3):
+ weight_norm(res_unit.conv1)
+ weight_norm(res_unit.conv2)
+
+ weight_norm(self.acoustic_decoder.conv1, name="weight")
+ weight_norm(self.acoustic_decoder.conv2, name="weight")
+
+ for block in self.acoustic_decoder.block:
+ weight_norm(block.conv_t1, name="weight")
+ for res_unit in (block.res_unit1, block.res_unit2, block.res_unit3):
+ weight_norm(res_unit.conv1, name="weight")
+ weight_norm(res_unit.conv2, name="weight")
+
+ def remove_weight_norm(self):
+ """Remove the weight norm from the acoustic encoder and decoder."""
+ for module in (self.acoustic_encoder, self.acoustic_decoder):
+ for m in module.modules():
+ try:
+ torch.nn.utils.remove_weight_norm(m, name="weight")
+ except (ValueError, AttributeError):
+ pass
+ if hasattr(m, "parametrizations") and "weight" in m.parametrizations:
+ torch.nn.utils.parametrize.remove_parametrizations(m, "weight", leave_parametrized=True)
+
+ @lru_cache
+ def _get_conv1d_layers(self, module):
+ """
+ Recursively iterate to fetch all Conv1d layers.
+ """
+
+ def get_conv1d_layers_recursive(module: nn.Module):
+ params_list = []
+
+ if isinstance(module, nn.Conv1d):
+ params_list.append(module)
+
+ # Recursively check all child modules
+ for child in module.children():
+ params_list.extend(get_conv1d_layers_recursive(child))
+
+ return params_list
+
+ return tuple(get_conv1d_layers_recursive(module))
+
+ def _get_conv1d_output_lengths(self, input_length, module=None):
+ """
+ For a given module, compute the output length that would be obtained after all Conv1d layers.
+ """
+ if module is None:
+ module = self
+
+ conv1d_layers = self._get_conv1d_layers(module)
+
+ for layer in conv1d_layers:
+ input_length = conv1d_output_length(layer, input_length)
+
+ return input_length
+
+
+class HiggsAudioV2TokenizerEuclideanCodebook(nn.Module):
+ """Codebook with Euclidean distance."""
+
+ def __init__(self, config):
+ super().__init__()
+ embed = torch.zeros(config.codebook_size, config.codebook_dim)
+ self.codebook_size = config.codebook_size
+ self.inited = nn.Buffer(torch.Tensor([True]))
+ self.cluster_size = nn.Buffer(torch.zeros(config.codebook_size))
+ self.embed = nn.Buffer(embed)
+ self.embed_avg = nn.Buffer(embed.clone())
+
+ def quantize(self, hidden_states):
+ embed = self.embed.t()
+ scaled_states = hidden_states.pow(2).sum(1, keepdim=True)
+ dist = -(scaled_states - 2 * hidden_states @ embed + embed.pow(2).sum(0, keepdim=True))
+ embed_ind = dist.max(dim=-1).indices
+ return embed_ind
+
+ def encode(self, hidden_states):
+ shape = hidden_states.shape
+ hidden_states = hidden_states.reshape((-1, shape[-1]))
+ embed_ind = self.quantize(hidden_states)
+ embed_ind = embed_ind.view(*shape[:-1])
+ return embed_ind
+
+ def decode(self, embed_ind):
+ quantized = F.embedding(embed_ind.to(self.embed.device), self.embed)
+ return quantized
+
+
+class HiggsAudioV2TokenizerVectorQuantization(nn.Module):
+ def __init__(self, config: HiggsAudioV2TokenizerConfig):
+ super().__init__()
+ self.codebook = HiggsAudioV2TokenizerEuclideanCodebook(config)
+ self.project_in = nn.Linear(config.hidden_size, config.codebook_dim)
+ self.project_out = nn.Linear(config.codebook_dim, config.hidden_size)
+
+ def encode(self, hidden_states):
+ hidden_states = hidden_states.permute(0, 2, 1)
+ hidden_states = self.project_in(hidden_states)
+ embed_in = self.codebook.encode(hidden_states)
+ return embed_in
+
+ def decode(self, embed_ind):
+ quantize = self.codebook.decode(embed_ind)
+ quantize = self.project_out(quantize)
+ quantize = quantize.permute(0, 2, 1)
+ return quantize
+
+
+@dataclass
+class HiggsAudioV2TokenizerOutput(ModelOutput):
+ """
+ Args:
+ audio_codes (`torch.LongTensor` of shape `(batch_size, num_quantizers, codes_length)`, *optional*):
+ Discrete code indices computed using `model.encode`.
+ audio_values (`torch.FloatTensor` of shape `(batch_size, channels, num_samples)`, *optional*)
+ Decoded audio values obtained using the decoder part of HiggsAudioV2Tokenizer.
+ """
+
+ audio_codes: torch.LongTensor | None = None
+ audio_values: torch.FloatTensor | None = None
+
+
+@dataclass
+class HiggsAudioV2TokenizerEncoderOutput(ModelOutput):
+ """
+ Args:
+ audio_codes (`torch.LongTensor` of shape `(batch_size, num_quantizers, codes_length)`, *optional*):
+ Discrete code indices computed using `model.encode`.
+ """
+
+ audio_codes: torch.LongTensor | None = None
+
+
+@dataclass
+class HiggsAudioV2TokenizerDecoderOutput(ModelOutput):
+ """
+ Args:
+ audio_values (`torch.FloatTensor` of shape `(batch_size, channels, num_samples)`, *optional*):
+ Decoded audio values obtained using the decoder part of HiggsAudioV2Tokenizer.
+ """
+
+ audio_values: torch.FloatTensor | None = None
+
+
+class HiggsAudioV2TokenizerResidualUnit(nn.Module):
+ """Residual block for SemanticEncoder and SemanticDecoder used in HiggsAudioV2Tokenizer."""
+
+ def __init__(self, config: HiggsAudioV2TokenizerConfig, in_channels: int, out_channels: int, dilation: int):
+ super().__init__()
+ self.activation = nn.ELU()
+ padding = ((config.unit_kernel_size - 1) // 2) * dilation
+ self.conv1 = nn.Conv1d(
+ in_channels,
+ out_channels,
+ config.unit_kernel_size,
+ stride=1,
+ padding=padding,
+ dilation=dilation,
+ groups=1,
+ bias=False,
+ )
+ self.conv2 = nn.Conv1d(in_channels=out_channels, out_channels=out_channels, kernel_size=1, bias=False)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ output_tensor = self.activation(hidden_state)
+ output_tensor = self.conv1(output_tensor)
+ output_tensor = self.activation(output_tensor)
+ output_tensor = self.conv2(output_tensor)
+ return hidden_state + output_tensor
+
+
+class HiggsAudioV2TokenizerSemanticEncoderBlock(nn.Module):
+ def __init__(self, config: HiggsAudioV2TokenizerConfig, in_channels: int, out_channels: int, stride: int):
+ super().__init__()
+ self.res_units = nn.ModuleList(
+ [
+ HiggsAudioV2TokenizerResidualUnit(config, in_channels, in_channels, dilation)
+ for dilation in config.block_dilations
+ ]
+ )
+
+ # special case: stride=1, do not use kernel=2
+ kernel = 3 if stride == 1 else (2 * stride)
+ padding = (kernel - 1) // 2
+ self.conv = nn.Conv1d(in_channels, out_channels, kernel_size=kernel, stride=stride, padding=padding, bias=True)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ for unit in self.res_units:
+ hidden_state = unit(hidden_state)
+ hidden_state = self.conv(hidden_state)
+ return hidden_state
+
+
+class SemanticEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ if len(config.strides) != len(config.channel_ratios):
+ raise ValueError("Number of strides must match the number of channel_ratios.")
+ self.conv = nn.Conv1d(
+ config.semantic_hidden_size,
+ config.semantic_hidden_size,
+ config.kernel_size,
+ 1,
+ config.kernel_size // 2,
+ bias=False,
+ )
+
+ in_channels = config.semantic_hidden_size
+ conv_blocks = []
+ for i, stride in enumerate(config.strides):
+ out_channels = int(config.semantic_hidden_size * config.channel_ratios[i])
+ conv_blocks += [HiggsAudioV2TokenizerSemanticEncoderBlock(config, in_channels, out_channels, stride)]
+ in_channels = out_channels
+
+ self.conv_blocks = nn.ModuleList(conv_blocks)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ hidden_state = self.conv(hidden_state)
+ for block in self.conv_blocks:
+ hidden_state = block(hidden_state)
+ return hidden_state
+
+
+class SemanticDecoderBlock(nn.Module):
+ def __init__(self, config: HiggsAudioV2TokenizerConfig, in_channels: int, out_channels: int, stride: int):
+ super().__init__()
+ if stride == 1:
+ self.conv = nn.Conv1d(
+ in_channels,
+ out_channels,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ bias=True,
+ )
+ else:
+ kernel_size = 2 * stride
+ padding = (stride + 1) // 2
+ output_padding = 1 if stride % 2 == 1 else 0
+ self.conv = nn.ConvTranspose1d(
+ in_channels, out_channels, kernel_size, stride, padding, output_padding, bias=False
+ )
+
+ self.res_units = nn.ModuleList(
+ [
+ HiggsAudioV2TokenizerResidualUnit(config, out_channels, out_channels, dilation)
+ for dilation in config.block_dilations
+ ]
+ )
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ hidden_state = self.conv(hidden_state)
+ for unit in self.res_units:
+ hidden_state = unit(hidden_state)
+ return hidden_state
+
+
+class SemanticDecoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.conv1 = nn.Conv1d(
+ in_channels=config.semantic_hidden_size,
+ out_channels=int(config.semantic_hidden_size * config.channel_ratios[0]),
+ kernel_size=config.kernel_size,
+ stride=1,
+ padding=config.kernel_size // 2,
+ bias=False,
+ )
+ conv_blocks = []
+ for i, stride in enumerate(config.strides):
+ in_channels = int(config.semantic_hidden_size * config.channel_ratios[i])
+
+ if i < (len(config.channel_ratios) - 1):
+ out_channels = int(config.semantic_hidden_size * config.channel_ratios[i + 1])
+ else:
+ out_channels = config.semantic_hidden_size
+
+ conv_blocks += [SemanticDecoderBlock(config, in_channels, out_channels, stride)]
+
+ self.conv_blocks = nn.ModuleList(conv_blocks)
+ self.conv2 = nn.Conv1d(
+ config.semantic_hidden_size,
+ config.semantic_hidden_size,
+ config.kernel_size,
+ stride=1,
+ padding=config.kernel_size // 2,
+ bias=False,
+ )
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ hidden_state = self.conv1(hidden_state)
+ for block in self.conv_blocks:
+ hidden_state = block(hidden_state)
+ hidden_state = self.conv2(hidden_state)
+ return hidden_state
+
+
+class HiggsAudioV2TokenizerResidualVectorQuantization(nn.Module):
+ """
+ Residual vector quantization implementation. Follows Algorithm 1 in https://huggingface.co/papers/2107.03312
+ """
+
+ def __init__(self, config: HiggsAudioV2TokenizerConfig):
+ super().__init__()
+ self.quantizers = nn.ModuleList(
+ [HiggsAudioV2TokenizerVectorQuantization(config) for _ in range(config.num_quantizers)]
+ )
+ self.frame_rate = config.frame_rate
+ self.codebook_size = config.codebook_size
+ self.num_quantizers = config.num_quantizers
+
+ def get_bandwidth_per_quantizer(self):
+ """Return bandwidth per quantizer."""
+ return math.log2(self.codebook_size) * self.frame_rate / 1000
+
+ def get_num_quantizers_for_bandwidth(self, bandwidth=None) -> int:
+ """Return num_quantizers based on specified target bandwidth."""
+ bw_per_q = self.get_bandwidth_per_quantizer()
+ num_quantizers = self.num_quantizers
+ if bandwidth is not None and bandwidth > 0.0:
+ num_quantizers = int(max(1, math.floor(bandwidth / bw_per_q)))
+ return num_quantizers
+
+ def encode(self, embeddings: torch.Tensor, bandwidth=None) -> torch.Tensor:
+ """
+ Encode the input tensor into discrete indices using RVQ, with the number of quantizers selected based on the given bandwidth.
+ Each quantizer /codebook residually quantizes the input and returns the nearest indices in terms of Euclidean distance.
+ """
+ num_quantizers = self.get_num_quantizers_for_bandwidth(bandwidth)
+ residual = embeddings
+ all_indices = []
+ for quantizer in self.quantizers[:num_quantizers]:
+ indices = quantizer.encode(residual)
+ quantized = quantizer.decode(indices)
+ residual = residual - quantized
+ all_indices.append(indices)
+ out_indices = torch.stack(all_indices)
+ return out_indices
+
+ def decode(self, codes: torch.Tensor) -> torch.Tensor:
+ """Decode the given codes to their quantized representation."""
+ quantized_out = torch.full((), 0.0, device=codes.device)
+ for i, indices in enumerate(codes):
+ quantizer = self.quantizers[i]
+ quantized = quantizer.decode(indices)
+ quantized_out = quantized_out + quantized.to(codes.device)
+ return quantized_out
+
+
+@requires(backends=("torchaudio",))
+@auto_docstring(custom_intro="""The HiggsAudioV2Tokenizer neural audio codec model.""")
+class HiggsAudioV2TokenizerModel(HiggsAudioV2TokenizerPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.config = config
+ self.pad = config.hop_length // 2
+ acoustic_model = AutoModel.from_config(config.acoustic_model_config)
+ self.acoustic_encoder = acoustic_model.encoder
+ self.acoustic_decoder = acoustic_model.decoder
+ self._adjust_dac_decoder(self.acoustic_decoder)
+ self.encoder_semantic = SemanticEncoder(config)
+ self.decoder_semantic = SemanticDecoder(config)
+ self.semantic_model = AutoModel.from_config(config.semantic_model_config).eval()
+ self.fc = nn.Linear(config.hidden_size, config.hidden_size)
+ self.fc1 = nn.Linear(config.hidden_size, config.semantic_model_config.hidden_size)
+ self.fc2 = nn.Linear(config.hidden_size, config.acoustic_model_config.hidden_size)
+ self.quantizer = HiggsAudioV2TokenizerResidualVectorQuantization(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @staticmethod
+ def _adjust_dac_decoder(decoder: nn.Module):
+ r"""
+ DAC implemented in HiggsAudioV2Tokenizer is slightly different from the HF version.
+ DAC in HiggsAudioV2Tokenizer adjusts the output padding in every ConvTranspose1d in the decoder and removes
+ the final `nn.Tanh` activation function.
+ """
+ for module in decoder.modules():
+ if isinstance(module, nn.ConvTranspose1d):
+ stride = module.stride[0] if isinstance(module.stride, tuple) else module.stride
+ module.output_padding = (stride % 2,)
+ if hasattr(decoder, "tanh") and isinstance(decoder.tanh, nn.Tanh):
+ decoder.tanh = nn.Identity()
+
+ def _extract_semantic_features(self, input_values: torch.FloatTensor) -> torch.FloatTensor:
+ if self.config.sample_rate != self.config.semantic_sample_rate:
+ input_values = torchaudio.functional.resample(
+ input_values, self.config.sample_rate, self.config.semantic_sample_rate
+ )
+
+ input_values = input_values[:, 0, :]
+ # TODO: there is a diff here with original codebase https://github.com/boson-ai/higgs-audio/blob/f644b62b855ba2b938896436221e01efadcc76ca/boson_multimodal/audio_processing/higgs_audio_v2_tokenizer.py#L173-L174
+ # input_values = F.pad(input_values, (self.pad, self.pad))
+ input_values = F.pad(input_values, (160, 160))
+ with torch.no_grad():
+ outputs = self.semantic_model(input_values, output_hidden_states=True)
+ hidden_states = outputs.hidden_states
+
+ stacked = torch.stack([h.to(input_values.device) for h in hidden_states], dim=1)
+ semantic_features = stacked.mean(dim=1)
+
+ if self.config.semantic_downsample_factor > 1:
+ semantic_features = semantic_features[:, :: self.config.semantic_downsample_factor, :]
+
+ return semantic_features
+
+ @auto_docstring
+ def encode(
+ self,
+ input_values: torch.Tensor,
+ bandwidth: float | None = None,
+ return_dict: bool | None = None,
+ ) -> torch.Tensor | HiggsAudioV2TokenizerEncoderOutput:
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, channels, num_samples)`):
+ Float values of the input audio waveform.
+ bandwidth (`float`, *optional*):
+ The target bandwidth in (kbps) supports only values in `config.target_bandwidths`.
+ Defaults to the highest available bandwidth `4.0` kbps.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`].
+
+ Returns:
+ `torch.LongTensor` of shape `(batch_size, num_quantizers, codes_length)` containing the discrete encoded audio codes.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ channels = input_values.shape[1]
+ if channels != 1:
+ raise ValueError(f"Audio must be mono, but got {channels}")
+
+ if bandwidth is None:
+ bandwidth = self.config.target_bandwidths[-1]
+ elif bandwidth not in self.config.target_bandwidths:
+ raise ValueError(
+ f"This model doesn't support the bandwidth {bandwidth}. Select one of {self.config.target_bandwidths}."
+ )
+
+ e_semantic_input = self._extract_semantic_features(input_values).detach()
+ e_semantic = self.encoder_semantic(e_semantic_input.transpose(1, 2))
+
+ # original codebase infer to get the output length, but we can directly infer it
+ # from the model and know whether we should pad
+ if self._get_conv1d_output_lengths(input_values.shape[2], self.acoustic_encoder) != e_semantic.shape[2]:
+ e_acoustic = self.acoustic_encoder(F.pad(input_values, (self.pad, self.pad)))
+ else:
+ e_acoustic = self.acoustic_encoder(input_values)
+
+ embeddings = torch.cat([e_acoustic.to(e_semantic.device), e_semantic], dim=1)
+ embeddings = self.fc(embeddings.transpose(1, 2)).transpose(1, 2)
+ audio_codes = self.quantizer.encode(embeddings, bandwidth)
+ audio_codes = audio_codes.transpose(0, 1)
+
+ if not return_dict:
+ return audio_codes
+
+ return HiggsAudioV2TokenizerEncoderOutput(audio_codes)
+
+ @auto_docstring
+ def decode(
+ self,
+ audio_codes: torch.Tensor,
+ return_dict: bool | None = None,
+ ) -> torch.Tensor | HiggsAudioV2TokenizerDecoderOutput:
+ r"""
+ audio_codes (`torch.LongTensor` of shape `(batch_size, num_quantizers, codes_length)`):
+ Discrete code indices computed using `model.encode`.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`]
+
+ Returns:
+ Decoded audio values of shape `(batch_size, channels, num_samples)` obtained using the decoder part of
+ HiggsAudioV2Tokenizer.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ audio_codes = audio_codes.transpose(0, 1)
+ quantized = self.quantizer.decode(audio_codes)
+ quantized_acoustic = self.fc2(quantized.transpose(1, 2)).transpose(1, 2)
+ audio_values = self.acoustic_decoder(quantized_acoustic)
+
+ if not return_dict:
+ return audio_values
+
+ return HiggsAudioV2TokenizerDecoderOutput(audio_values)
+
+ @auto_docstring
+ @can_return_tuple
+ def forward(
+ self,
+ input_values: torch.Tensor,
+ audio_codes: torch.Tensor | None = None,
+ bandwidth: float | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor] | HiggsAudioV2TokenizerOutput:
+ r"""
+ input_values (`torch.FloatTensor` of shape `(batch_size, channels, num_samples)`):
+ The raw float values of the input audio waveform.
+ audio_codes (`torch.LongTensor` of shape `(batch_size, num_quantizers, codes_length)`:
+ Discrete code indices computed using `model.encode`.
+ bandwidth (`float`, *optional*):
+ Target bandwidth in kbps. Must be one of `config.target_bandwidths`. Defaults to the highest available bandwidth.
+ bandwidth (`float`, *optional*):
+ Target bandwidth in kbps. Must be one of `config.target_bandwidths`. Defaults to the highest available bandwidth.
+
+ Returns:
+ `HiggsAudioV2TokenizerOutput` or tuple `(audio_codes, audio_values)`:
+ - `audio_codes` of shape `(batch_size, num_quantizers, codes_length)`: the quantized discrete codes.
+ - `audio_values` of shape `(batch_size, channels, num_samples)`: the reconstructed audio waveform given the codes.
+
+ Example:
+
+ ```python
+ >>> from datasets import load_dataset
+ >>> from transformers import AutoFeatureExtractor, HiggsAudioV2TokenizerModel
+
+ >>> model_id = "hf-audio/higgs_audio_v2_tokenizer-hubert-librispeech"
+ >>> model = HiggsAudioV2TokenizerModel.from_pretrained(model_id)
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained(model_id)
+
+ >>> dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
+ >>> dataset = dataset.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate))
+ >>> audio_sample = dataset[0]['audio']['array']
+
+ >>> inputs = feature_extractor(raw_audio=audio_sample, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+ >>> audio_codes = outputs.audio_codes
+ >>> audio_values = outputs.audio_values
+ ```
+ """
+ length = input_values.shape[-1]
+
+ if audio_codes is None:
+ audio_codes = self.encode(input_values, bandwidth, return_dict=False)
+
+ audio_values = self.decode(audio_codes, return_dict=True)[0][..., :length]
+
+ return HiggsAudioV2TokenizerOutput(audio_codes=audio_codes, audio_values=audio_values)
+
+
+__all__ = ["HiggsAudioV2TokenizerPreTrainedModel", "HiggsAudioV2TokenizerModel"]
diff --git a/justfile b/justfile
index 6c87aa84..25e22745 100644
--- a/justfile
+++ b/justfile
@@ -122,6 +122,9 @@ setup-python:
"{{ python }}" -m pip install --no-deps chatterbox-tts
# HumeAI TADA pins torch>=2.7,<2.8 which conflicts with our torch>=2.1
"{{ python }}" -m pip install --no-deps hume-tada
+ # OmniVoice requires transformers>=5.3; we vendor the one class it
+ # needs from 5.x (see backend/vendor/higgs_audio_v2_tokenizer).
+ "{{ python }}" -m pip install --no-deps omnivoice
# Apple Silicon: install MLX backend
if [ "$(uname -m)" = "arm64" ] && [ "$(uname)" = "Darwin" ]; then
echo "Detected Apple Silicon — installing MLX dependencies..."
@@ -207,6 +210,7 @@ setup-python:
Invoke-Pip install -r {{ backend_dir }}/requirements.txt; \
Invoke-Pip install --no-deps chatterbox-tts; \
Invoke-Pip install --no-deps hume-tada; \
+ Invoke-Pip install --no-deps omnivoice; \
Invoke-Pip install git+https://github.com/QwenLM/Qwen3-TTS.git; \
Invoke-Pip install pyinstaller ruff pytest pytest-asyncio -q; \
Write-Host "Python environment ready."
diff --git a/scripts/sync-higgs-tokenizer.py b/scripts/sync-higgs-tokenizer.py
new file mode 100644
index 00000000..8e6eefb8
--- /dev/null
+++ b/scripts/sync-higgs-tokenizer.py
@@ -0,0 +1,126 @@
+#!/usr/bin/env python3
+"""Vendor the Higgs Audio V2 tokenizer from transformers into backend/vendor/.
+
+OmniVoice needs ``transformers.HiggsAudioV2TokenizerModel``, which only exists
+in transformers >= 5.3. Voicebox is pinned to <= 4.57.6 because several engine
+workarounds depend on 4.57.x internals (see ``backend/utils/hf_offline_patch.py``
+and ``backend/pyi_rth_torch_compiler_disable.py``).
+
+Rather than move the whole app to transformers 5, we vendor the two files that
+define the tokenizer and rewrite their imports. Only a handful of symbols differ
+between the two versions; ``backend/vendor/_compat.py`` supplies them. This
+mirrors the ``--no-deps`` treatment already applied to mlx-lm / mlx-audio in the
+justfile, which declare transformers >= 5 for the same reason.
+
+Re-run to re-sync against a newer upstream revision:
+
+ python scripts/sync-higgs-tokenizer.py [--ref main]
+"""
+
+import argparse
+import re
+import urllib.request
+from pathlib import Path
+
+UPSTREAM = (
+ "https://raw.githubusercontent.com/huggingface/transformers/{ref}"
+ "/src/transformers/models/higgs_audio_v2_tokenizer/{name}.py"
+)
+FILES = ["configuration_higgs_audio_v2_tokenizer", "modeling_higgs_audio_v2_tokenizer"]
+DEST = Path(__file__).resolve().parent.parent / "backend" / "vendor" / "higgs_audio_v2_tokenizer"
+
+# Relative imports rewritten to absolute. Anything resolving to a symbol that
+# 4.57.6 does not have points at _compat instead of transformers.
+REWRITES = [
+ (r"^from \.\.\. import initialization as init$", "from .._compat import initialization as init"),
+ (r"^from \.\.\.audio_utils import conv1d_output_length$", "from .._compat import conv1d_output_length"),
+ (r"^from \.\.\.configuration_utils import PreTrainedConfig$", "from .._compat import PreTrainedConfig"),
+ (r"^from huggingface_hub\.dataclasses import strict$", "from .._compat import strict"),
+ (r"^from \.\.\.modeling_utils import ", "from transformers.modeling_utils import "),
+ (r"^from \.\.\.processing_utils import ", "from transformers.processing_utils import "),
+ (r"^from \.\.\.utils\.import_utils import ", "from transformers.utils.import_utils import "),
+ (r"^from \.\.\.utils import ", "from transformers.utils import "),
+ (r"^from \.\.auto import ", "from transformers.models.auto import "),
+]
+
+# Symbols that exist in both versions but behave differently, so a targeted
+# rewrite of the import line would break whenever upstream reorders it. Rebind
+# them after the import block instead: the later binding wins.
+OVERRIDES = [
+ (
+ "auto_docstring",
+ "4.57.6's auto_docstring rejects classes absent from its registry",
+ ),
+]
+
+HEADER = (
+ "# Vendored from huggingface/transformers @ {ref}\n"
+ "# src/transformers/models/higgs_audio_v2_tokenizer/{name}.py\n"
+ "# Apache License 2.0 - Copyright 2025 Boson AI and The HuggingFace Team.\n"
+ "#\n"
+ "# Do NOT edit by hand. Regenerate with: python scripts/sync-higgs-tokenizer.py\n"
+ "# Only the imports are touched; the body is verbatim.\n\n"
+)
+
+
+def rewrite_imports(source: str) -> tuple[list[str], int]:
+ lines, applied = [], 0
+ for line in source.splitlines():
+ for pattern, replacement in REWRITES:
+ new = re.sub(pattern, replacement, line)
+ if new != line:
+ line, applied = new, applied + 1
+ break
+ lines.append(line)
+ return lines, applied
+
+
+def append_overrides(lines: list[str]) -> list[str]:
+ """Rebind divergent symbols right after the module's import block."""
+ last_import = max(
+ (i for i, line in enumerate(lines) if re.match(r"^(from|import)\s", line)),
+ default=None,
+ )
+ if last_import is None:
+ return lines
+
+ block = [""]
+ for symbol, reason in OVERRIDES:
+ if not any(re.search(rf"\b{symbol}\b", line) for line in lines[: last_import + 1]):
+ continue
+ block.append(f"# Override: {reason}.")
+ block.append(f"from .._compat import {symbol} # noqa: F811")
+
+ if len(block) == 1:
+ return lines
+ return lines[: last_import + 1] + block + lines[last_import + 1 :]
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--ref", default="main", help="transformers git ref to vendor from")
+ args = parser.parse_args()
+
+ DEST.mkdir(parents=True, exist_ok=True)
+ for name in FILES:
+ url = UPSTREAM.format(ref=args.ref, name=name)
+ with urllib.request.urlopen(url) as response:
+ source = response.read().decode("utf-8")
+
+ lines, applied = rewrite_imports(source)
+ lines = append_overrides(lines)
+ body = "\n".join(lines) + "\n"
+ (DEST / f"{name}.py").write_text(HEADER.format(ref=args.ref, name=name) + body)
+ print(f"{name}.py: {len(lines)} lines, {applied} imports rewritten")
+
+ # A surviving relative import would resolve against our vendor package
+ # instead of transformers and break in a confusing way. Fail loudly.
+ for name in FILES:
+ for lineno, line in enumerate((DEST / f"{name}.py").read_text().splitlines(), 1):
+ if re.match(r"^from \.\.\.|^from \.\.[a-z]", line) and "_compat" not in line:
+ raise SystemExit(f"unrewritten relative import at {name}.py:{lineno}: {line}")
+ print("no unrewritten relative imports")
+
+
+if __name__ == "__main__":
+ main()