BNarayanaReddy commited on
Commit
df98707
·
verified ·
1 Parent(s): 6a8b759

Telugu ISO single-speaker fine-tune (run LoRA)

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ language: [te, en]
4
+ pipeline_tag: text-to-speech
5
+ tags: [text-to-speech, telugu, higgs-audio, voice-avatar, code-switch]
6
+ base_model: bosonai/higgs-audio-v3-tts-4b
7
+ ---
8
+
9
+ # Higgs Audio v3 — Telugu single-speaker voice (ISO-romanized fine-tune)
10
+
11
+ Expressive single-speaker **Telugu** (code-switch) TTS, fine-tuned from Higgs
12
+ Audio v3 (4B). Generates this speaker's voice **from text with no reference clip**.
13
+
14
+ **Frontend matters:** Telugu text must be ISO-15919 romanized with the *same*
15
+ `frontend.py` used in training (Telugu tokenizes to byte-fragments otherwise).
16
+ `generate_speech` handles the rest.
17
+
18
+ ```python
19
+ import torch, torchaudio
20
+ from transformers import AutoModelForCausalLM, AutoTokenizer
21
+ from frontend import romanize # shipped in this repo
22
+
23
+ repo = "BNarayanaReddy/higgs-telugu-e4-lora"
24
+ tok = AutoTokenizer.from_pretrained(repo)
25
+ model = AutoModelForCausalLM.from_pretrained(repo, trust_remote_code=True,
26
+ dtype=torch.bfloat16).to("cuda").eval()
27
+
28
+ text = "హలో, ఈ రోజు ఎలా ఉన్నారు?"
29
+ wav = model.generate_speech(romanize(text, "iso"), tok, temperature=0.7, top_p=0.95)
30
+ torchaudio.save("out.wav", wav.unsqueeze(0), model.config.sample_rate)
31
+ ```
32
+
33
+ Run #1 of an ISO-romanized single-speaker adaptation. Research use.
chat_template.jinja ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0]['role'] == 'system' %}
4
+ {{- messages[0]['content'] }}
5
+ {%- else %}
6
+ {{- 'You are a helpful assistant.' }}
7
+ {%- endif %}
8
+ {{- "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
9
+ {%- for tool in tools %}
10
+ {{- "\n" }}
11
+ {{- tool | tojson }}
12
+ {%- endfor %}
13
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
14
+ {%- else %}
15
+ {%- if messages[0]['role'] == 'system' %}
16
+ {{- '<|im_start|>system\n' + messages[0]['content'] + '<|im_end|>\n' }}
17
+ {%- else %}
18
+ {{- '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }}
19
+ {%- endif %}
20
+ {%- endif %}
21
+ {%- for message in messages %}
22
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) %}
23
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }}
24
+ {%- elif message.role == "assistant" %}
25
+ {{- '<|im_start|>' + message.role }}
26
+ {%- if message.content %}
27
+ {{- '\n' + message.content }}
28
+ {%- endif %}
29
+ {%- for tool_call in message.tool_calls %}
30
+ {%- if tool_call.function is defined %}
31
+ {%- set tool_call = tool_call.function %}
32
+ {%- endif %}
33
+ {{- '\n<tool_call>\n{"name": "' }}
34
+ {{- tool_call.name }}
35
+ {{- '", "arguments": ' }}
36
+ {{- tool_call.arguments | tojson }}
37
+ {{- '}\n</tool_call>' }}
38
+ {%- endfor %}
39
+ {{- '<|im_end|>\n' }}
40
+ {%- elif message.role == "tool" %}
41
+ {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") %}
42
+ {{- '<|im_start|>user' }}
43
+ {%- endif %}
44
+ {{- '\n<tool_response>\n' }}
45
+ {{- message.content }}
46
+ {{- '\n</tool_response>' }}
47
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
48
+ {{- '<|im_end|>\n' }}
49
+ {%- endif %}
50
+ {%- endif %}
51
+ {%- endfor %}
52
+ {%- if add_generation_prompt %}
53
+ {{- '<|im_start|>assistant\n' }}
54
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "HiggsMultimodalQwen3ForConditionalGeneration"
4
+ ],
5
+ "audio_encoder_config": {
6
+ "encoder_type": "discrete",
7
+ "mel_per_sample": 8,
8
+ "model_type": "higgs_audio_encoder",
9
+ "num_codebooks": 8,
10
+ "out_dim": 2560,
11
+ "tie_word_embeddings": true,
12
+ "use_delay_pattern": true,
13
+ "vocab_size": 1026
14
+ },
15
+ "audio_token_id": -100,
16
+ "audio_tokenizer_id": "bosonai/higgs-audio-v2-tokenizer",
17
+ "auto_map": {
18
+ "AutoConfig": "configuration_higgs_multimodal_qwen3.HiggsMultimodalQwen3Config",
19
+ "AutoModel": "modeling_higgs_multimodal_qwen3.HiggsMultimodalQwen3ForConditionalGeneration",
20
+ "AutoModelForCausalLM": "modeling_higgs_multimodal_qwen3.HiggsMultimodalQwen3ForConditionalGeneration"
21
+ },
22
+ "dtype": "bfloat16",
23
+ "ignore_index": -100,
24
+ "mel_per_sample": 8,
25
+ "model_type": "higgs_multimodal_qwen3",
26
+ "sample_rate": 24000,
27
+ "text_config": {
28
+ "architectures": [
29
+ "Qwen3ForCausalLM"
30
+ ],
31
+ "attention_bias": false,
32
+ "attention_dropout": 0.0,
33
+ "bos_token_id": 151643,
34
+ "dtype": "bfloat16",
35
+ "eos_token_id": 151643,
36
+ "head_dim": 128,
37
+ "hidden_act": "silu",
38
+ "hidden_size": 2560,
39
+ "initializer_range": 0.02,
40
+ "intermediate_size": 9728,
41
+ "layer_types": [
42
+ "full_attention",
43
+ "full_attention",
44
+ "full_attention",
45
+ "full_attention",
46
+ "full_attention",
47
+ "full_attention",
48
+ "full_attention",
49
+ "full_attention",
50
+ "full_attention",
51
+ "full_attention",
52
+ "full_attention",
53
+ "full_attention",
54
+ "full_attention",
55
+ "full_attention",
56
+ "full_attention",
57
+ "full_attention",
58
+ "full_attention",
59
+ "full_attention",
60
+ "full_attention",
61
+ "full_attention",
62
+ "full_attention",
63
+ "full_attention",
64
+ "full_attention",
65
+ "full_attention",
66
+ "full_attention",
67
+ "full_attention",
68
+ "full_attention",
69
+ "full_attention",
70
+ "full_attention",
71
+ "full_attention",
72
+ "full_attention",
73
+ "full_attention",
74
+ "full_attention",
75
+ "full_attention",
76
+ "full_attention",
77
+ "full_attention"
78
+ ],
79
+ "max_position_embeddings": 32768,
80
+ "max_window_layers": 36,
81
+ "model_type": "qwen3",
82
+ "num_attention_heads": 32,
83
+ "num_hidden_layers": 36,
84
+ "num_key_value_heads": 8,
85
+ "pad_token_id": null,
86
+ "rms_norm_eps": 1e-06,
87
+ "rope_parameters": {
88
+ "rope_theta": 1000000,
89
+ "rope_type": "default"
90
+ },
91
+ "sliding_window": null,
92
+ "tie_word_embeddings": true,
93
+ "use_cache": true,
94
+ "use_sliding_window": false,
95
+ "vocab_size": 151936
96
+ },
97
+ "transformers_version": "5.16.1",
98
+ "use_cache": false
99
+ }
configuration_higgs_multimodal_qwen3.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ """Config for HiggsMultimodalQwen3 — the Higgs Audio v3 TTS model.
3
+
4
+ A standard Qwen3 text backbone plus a fused multi-codebook audio embedding /
5
+ head. Audio is encoded/decoded by the separately-loaded
6
+ ``bosonai/higgs-audio-v2-tokenizer`` (``higgs_audio_v2_tokenizer``), which is
7
+ native to transformers >= 5.5.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Any
13
+
14
+ from transformers import CONFIG_MAPPING, PretrainedConfig
15
+
16
+ # Higgs Qwen3 sub-configs ship ``rope_theta=null``; transformers' default of
17
+ # 10000 is wrong for Qwen3 (trained at 1e6). Patch before instantiation.
18
+ _QWEN3_ROPE_THETA = 1_000_000
19
+
20
+
21
+ def _build_text_config(raw: Any) -> PretrainedConfig:
22
+ """Realise a text-backbone sub-config into a concrete ``PretrainedConfig``."""
23
+ if isinstance(raw, PretrainedConfig):
24
+ return raw
25
+ cfg = dict(raw or {})
26
+ model_type = cfg.get("model_type", "qwen3")
27
+ if model_type == "qwen3":
28
+ rope = cfg.get("rope_parameters") or {}
29
+ if cfg.get("rope_theta") is None and rope.get("rope_theta") is None:
30
+ cfg["rope_theta"] = _QWEN3_ROPE_THETA
31
+ cfg_cls = CONFIG_MAPPING[model_type]
32
+ return cfg_cls(**cfg)
33
+
34
+
35
+ _DEFAULT_AUDIO_ENCODER_CONFIG: dict[str, Any] = {
36
+ "encoder_type": "discrete",
37
+ "num_codebooks": 8,
38
+ "vocab_size": 1026,
39
+ "out_dim": 2560,
40
+ "tie_word_embeddings": True,
41
+ "use_delay_pattern": True,
42
+ "model_type": "higgs_audio_encoder",
43
+ }
44
+
45
+
46
+ class HiggsMultimodalQwen3Config(PretrainedConfig):
47
+ """Config for ``HiggsMultimodalQwen3ForConditionalGeneration``.
48
+
49
+ Args:
50
+ audio_encoder_config: discrete-codec descriptor. ``num_codebooks`` /
51
+ ``vocab_size`` (incl. BOC/EOC specials) / ``out_dim`` /
52
+ ``tie_word_embeddings`` drive the fused embedding + head.
53
+ text_config: Qwen3 backbone config, eagerly realised so
54
+ ``config.text_config.num_attention_heads`` works directly.
55
+ audio_token_id: placeholder id (``-100``) marking reference-audio slots
56
+ in ``input_ids`` that the fused audio embedding fills.
57
+ audio_tokenizer_id: repo id of the codec used to encode reference audio
58
+ and decode generated codes back to a waveform.
59
+ sample_rate: codec sample rate, Hz.
60
+ """
61
+
62
+ model_type = "higgs_multimodal_qwen3"
63
+ is_composition = True
64
+
65
+ def __init__(
66
+ self,
67
+ audio_encoder_config: dict[str, Any] | None = None,
68
+ text_config: dict[str, Any] | PretrainedConfig | None = None,
69
+ audio_token_id: int = -100,
70
+ mel_per_sample: int = 8,
71
+ audio_tokenizer_id: str = "bosonai/higgs-audio-v2-tokenizer",
72
+ sample_rate: int = 24_000,
73
+ **kwargs,
74
+ ):
75
+ self.audio_token_id = audio_token_id
76
+ self.mel_per_sample = mel_per_sample
77
+ self.audio_tokenizer_id = audio_tokenizer_id
78
+ self.sample_rate = sample_rate
79
+ self.audio_encoder_config = audio_encoder_config or dict(
80
+ _DEFAULT_AUDIO_ENCODER_CONFIG
81
+ )
82
+ self.text_config = _build_text_config(text_config)
83
+ super().__init__(**kwargs)
84
+
85
+ def get_text_config(self, decoder: bool = False) -> PretrainedConfig:
86
+ del decoder
87
+ return self.text_config
88
+
89
+
90
+ __all__ = ["HiggsMultimodalQwen3Config"]
frontend.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frozen Telugu text frontend — the ONE romanizer used at train AND serve.
2
+
3
+ Never reimplement this on one side. A one-token drift between training and
4
+ inference silently destroys quality. Run #1 uses scheme="iso".
5
+
6
+ iso ISO-15919, diacritics kept (halō, mīru viṁṭunnāru) — phonemically faithful.
7
+ ascii ISO-15919 diacritics stripped — ablation only (bakes in English accent).
8
+ native passthrough (byte-soup baseline) — ablation only.
9
+
10
+ Only Telugu Unicode runs are transliterated; English/code-switch spans, digits
11
+ and punctuation pass through untouched.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ import unicodedata
17
+
18
+ from indic_transliteration import sanscript
19
+
20
+ _TELUGU_RUN = re.compile(r"[ఀ-౿]+")
21
+
22
+
23
+ def _iso_run(m: "re.Match") -> str:
24
+ return sanscript.transliterate(m.group(0), sanscript.TELUGU, sanscript.ISO)
25
+
26
+
27
+ def romanize(text: str, scheme: str = "iso") -> str:
28
+ if scheme == "native":
29
+ return text
30
+ iso = _TELUGU_RUN.sub(_iso_run, text)
31
+ if scheme == "iso":
32
+ return iso
33
+ if scheme == "ascii":
34
+ d = unicodedata.normalize("NFKD", iso)
35
+ return "".join(c for c in d if not unicodedata.combining(c))
36
+ raise ValueError(f"unknown scheme: {scheme!r}")
37
+
38
+
39
+ if __name__ == "__main__":
40
+ for s in ["హలో my dear Telugu people, మీరు వింటున్నారు.", "పవనితో కబుర్లు."]:
41
+ print("NATIVE:", s)
42
+ print(" ISO :", romanize(s, "iso"))
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2b6fbb37661844298934269a3b27e35c715fd75c8aee54c09cf84bc8d0692a70
3
+ size 8087006776
modeling_higgs_multimodal_qwen3.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ """HiggsMultimodalQwen3 — Higgs Audio v3 TTS, ported to plain transformers.
3
+
4
+ Architecture:
5
+ * a standard Qwen3 backbone (``Qwen3Model``) for the autoregressive LM;
6
+ * one fused multi-codebook embedding ``[N*V, D]`` whose per-codebook lookups
7
+ are summed — it both embeds reference-audio codes into the prompt and
8
+ re-embeds each generated row during decoding;
9
+ * a tied fused head ``[L, D] -> [L, N, V]`` producing per-codebook logits.
10
+
11
+ Audio I/O (waveform <-> discrete codes) is handled by the transformers-native
12
+ ``HiggsAudioV2TokenizerModel`` (``bosonai/higgs-audio-v2-tokenizer``), loaded
13
+ lazily on first use.
14
+
15
+ Generation follows Higgs' delay pattern: codebook ``c`` is shifted by ``c``
16
+ steps, padded with BOC (1024) before and EOC (1025) after its data span. A
17
+ small per-request state machine drives the delay ramp-up, EOC detection and
18
+ wind-down; the produced rows are de-delayed and decoded to a 24 kHz waveform.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from dataclasses import dataclass
24
+ from typing import Any
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ from torch import nn
29
+ from transformers import AutoModel, PreTrainedModel
30
+ from transformers.models.qwen3.modeling_qwen3 import Qwen3Model
31
+
32
+ from .configuration_higgs_multimodal_qwen3 import HiggsMultimodalQwen3Config
33
+
34
+ # Codec-vocab specials, inside the per-codebook [0, V) space (NOT the text vocab).
35
+ BOC_ID = 1024
36
+ EOC_ID = 1025
37
+ # Placeholder id marking reference-audio slots in ``input_ids``.
38
+ AUDIO_PLACEHOLDER_ID = -100
39
+
40
+ _REQUIRED_SPECIALS = ("<|tts|>", "<|ref_audio|>", "<|text|>", "<|audio|>")
41
+
42
+
43
+ # --------------------------------------------------------------------------- #
44
+ # Delay pattern
45
+ # --------------------------------------------------------------------------- #
46
+ def apply_delay_pattern(codes_TN: torch.Tensor) -> torch.Tensor:
47
+ """``[T, N]`` raw codes -> ``[T + N - 1, N]`` delayed, BOC/EOC padded."""
48
+ T, N = codes_TN.shape
49
+ out = torch.full(
50
+ (T + N - 1, N), EOC_ID, device=codes_TN.device, dtype=codes_TN.dtype
51
+ )
52
+ t_idx = torch.arange(T + N - 1, device=codes_TN.device)
53
+ for c in range(N):
54
+ out[t_idx < c, c] = BOC_ID
55
+ out[c : c + T, c] = codes_TN[:, c]
56
+ return out
57
+
58
+
59
+ def reverse_delay_pattern(delayed_LN: torch.Tensor) -> torch.Tensor:
60
+ """``[L, N]`` delayed (L >= N) -> ``[L - (N - 1), N]`` raw codes."""
61
+ L, N = delayed_LN.shape
62
+ T = L - (N - 1)
63
+ if T <= 0:
64
+ raise ValueError(f"delayed rows L={L} < num_codebooks N={N}")
65
+ out = torch.empty((T, N), device=delayed_LN.device, dtype=delayed_LN.dtype)
66
+ for c in range(N):
67
+ out[:, c] = delayed_LN[c : c + T, c]
68
+ return out
69
+
70
+
71
+ # --------------------------------------------------------------------------- #
72
+ # Fused multi-codebook modules
73
+ # --------------------------------------------------------------------------- #
74
+ class HiggsFusedMultiTextEmbedding(nn.Module):
75
+ """Fused multi-codebook embedding: one ``[N*V, D]`` weight + offset lookup.
76
+
77
+ ``codes_LN[..., N]`` -> ``[..., D]`` summed across the codebook axis.
78
+ """
79
+
80
+ def __init__(self, num_codebooks: int, vocab_size: int, hidden_size: int):
81
+ super().__init__()
82
+ self.weight = nn.Parameter(torch.empty(num_codebooks * vocab_size, hidden_size))
83
+ self.num_codebooks = num_codebooks
84
+ self.vocab_size = vocab_size
85
+
86
+ def forward(self, codes_LN: torch.Tensor) -> torch.Tensor:
87
+ offsets = (
88
+ torch.arange(self.num_codebooks, device=codes_LN.device, dtype=codes_LN.dtype)
89
+ * self.vocab_size
90
+ )
91
+ return F.embedding(codes_LN + offsets, self.weight).sum(dim=-2)
92
+
93
+
94
+ class HiggsFusedMultiTextHead(nn.Module):
95
+ """Fused multi-codebook head: ``[L, D]`` -> ``[L, N, V]`` via one linear."""
96
+
97
+ def __init__(self, num_codebooks: int, vocab_size: int, hidden_size: int):
98
+ super().__init__()
99
+ self.weight = nn.Parameter(torch.empty(num_codebooks * vocab_size, hidden_size))
100
+ self.num_codebooks = num_codebooks
101
+ self.vocab_size = vocab_size
102
+
103
+ def forward(self, hidden_LD: torch.Tensor) -> torch.Tensor:
104
+ logits = F.linear(hidden_LD, self.weight)
105
+ return logits.reshape(hidden_LD.shape[0], self.num_codebooks, self.vocab_size)
106
+
107
+
108
+ # --------------------------------------------------------------------------- #
109
+ # Per-request delay/EOC sampler state machine (reference oracle, pure torch)
110
+ # --------------------------------------------------------------------------- #
111
+ @dataclass
112
+ class _SamplerState:
113
+ num_codebooks: int
114
+ delay_count: int = 0
115
+ eoc_countdown: int | None = None
116
+ generation_done: bool = False
117
+ last_codes: torch.Tensor | None = None
118
+
119
+
120
+ def _sample(logits_NV: torch.Tensor, temperature: float, top_p: float | None,
121
+ top_k: int | None) -> torch.Tensor:
122
+ if temperature <= 1e-5:
123
+ return logits_NV.argmax(dim=-1)
124
+ logits = logits_NV / temperature
125
+ if top_k is not None and top_k > 0:
126
+ k = min(top_k, logits.size(-1))
127
+ kth = logits.topk(k, dim=-1).values[:, -1:]
128
+ logits = torch.where(logits < kth, float("-inf"), logits)
129
+ if top_p is not None and top_p < 1.0:
130
+ sorted_logits, sorted_idx = torch.sort(logits, descending=True, dim=-1)
131
+ cum = sorted_logits.softmax(dim=-1).cumsum(dim=-1)
132
+ remove = cum > top_p
133
+ remove[..., 1:] = remove[..., :-1].clone()
134
+ remove[..., 0] = False
135
+ scatter = torch.zeros_like(remove)
136
+ scatter.scatter_(-1, sorted_idx, remove)
137
+ logits = torch.where(scatter, float("-inf"), logits)
138
+ return logits.softmax(dim=-1).multinomial(num_samples=1).squeeze(-1)
139
+
140
+
141
+ def _sampler_step(logits_NV: torch.Tensor, state: _SamplerState, *,
142
+ temperature: float, top_p: float | None,
143
+ top_k: int | None) -> torch.Tensor:
144
+ """One AR step of the multi-codebook delay sampler. Mutates ``state``."""
145
+ N = state.num_codebooks
146
+ codes_N = _sample(logits_NV, temperature, top_p, top_k).to(torch.long)
147
+
148
+ if state.delay_count < N:
149
+ next_cb = state.delay_count + 1
150
+ if next_cb < N:
151
+ codes_N[next_cb:] = BOC_ID
152
+ state.delay_count += 1
153
+ elif state.eoc_countdown is not None:
154
+ state.eoc_countdown -= 1
155
+ if state.eoc_countdown <= 0:
156
+ state.generation_done = True
157
+ elif int(codes_N[0].item()) == EOC_ID:
158
+ if N <= 2:
159
+ state.generation_done = True
160
+ else:
161
+ state.eoc_countdown = N - 2
162
+
163
+ if not state.generation_done:
164
+ state.last_codes = codes_N.clone()
165
+ return codes_N
166
+
167
+
168
+ class HiggsMultimodalQwen3PreTrainedModel(PreTrainedModel):
169
+ config_class = HiggsMultimodalQwen3Config
170
+ base_model_prefix = "model"
171
+ _supports_cache_class = True
172
+ _supports_sdpa = True
173
+
174
+
175
+ class HiggsMultimodalQwen3ForConditionalGeneration(HiggsMultimodalQwen3PreTrainedModel):
176
+ """Higgs Audio v3 TTS model.
177
+
178
+ Loadable via ``AutoModelForCausalLM.from_pretrained(..., trust_remote_code=True)``.
179
+ Use :meth:`generate_speech` for end-to-end text -> waveform synthesis.
180
+ """
181
+
182
+ # Higgs ckpt names -> this module's parameter tree. transformers 5.x applies
183
+ # this via the ``key_mapping`` weight-conversion path (see ``from_pretrained``).
184
+ _HIGGS_KEY_MAPPING = {
185
+ r"tied\.embedding\.text_embedding\.": "model.embed_tokens.",
186
+ r"tied\.embedding\.modality_embeddings\.0\.embedding\.": "audio_embedding.",
187
+ r"body\.": "model.",
188
+ }
189
+ # Codec weights (bundled in the ckpt) and the tied text head are not part of
190
+ # the AR graph; the codec is loaded separately from ``audio_tokenizer_id``.
191
+ _keys_to_ignore_on_load_unexpected = [
192
+ r"tied\.embedding\.modality_embeddings\.0\.model\.",
193
+ r"tied\.head\.",
194
+ ]
195
+ _tied_weights_keys = ["audio_head.weight"]
196
+
197
+ @classmethod
198
+ def from_pretrained(cls, *args, **kwargs):
199
+ kwargs.setdefault("key_mapping", dict(cls._HIGGS_KEY_MAPPING))
200
+ return super().from_pretrained(*args, **kwargs)
201
+
202
+ def __init__(self, config: HiggsMultimodalQwen3Config):
203
+ super().__init__(config)
204
+ text_config = config.get_text_config()
205
+ self.model = Qwen3Model(text_config)
206
+
207
+ enc = config.audio_encoder_config or {}
208
+ self.num_codebooks = int(enc["num_codebooks"])
209
+ self.codebook_vocab_size = int(enc["vocab_size"])
210
+ hidden = int(enc.get("out_dim", text_config.hidden_size))
211
+ self._tie_audio_head = bool(enc.get("tie_word_embeddings", True))
212
+
213
+ self.audio_embedding = HiggsFusedMultiTextEmbedding(
214
+ self.num_codebooks, self.codebook_vocab_size, hidden
215
+ )
216
+ self.audio_head = HiggsFusedMultiTextHead(
217
+ self.num_codebooks, self.codebook_vocab_size, hidden
218
+ )
219
+ self._audio_codec = None # lazily loaded
220
+ self.post_init()
221
+
222
+ def tie_weights(self, *args, **kwargs):
223
+ super().tie_weights(*args, **kwargs)
224
+ if self._tie_audio_head:
225
+ self.audio_head.weight = self.audio_embedding.weight
226
+
227
+ def get_input_embeddings(self):
228
+ return self.model.embed_tokens
229
+
230
+ def set_input_embeddings(self, value):
231
+ self.model.embed_tokens = value
232
+
233
+ # ----- audio codec (lazy) --------------------------------------------- #
234
+ def get_audio_codec(self):
235
+ """Load + cache the ``higgs_audio_v2_tokenizer`` codec (fp32, eval)."""
236
+ if self._audio_codec is None:
237
+ codec = AutoModel.from_pretrained(
238
+ self.config.audio_tokenizer_id, dtype=torch.float32,
239
+ trust_remote_code=True,
240
+ )
241
+ codec = codec.to(self.device).eval()
242
+ for p in codec.parameters():
243
+ p.requires_grad_(False)
244
+ self._audio_codec = codec
245
+ return self._audio_codec
246
+
247
+ @torch.no_grad()
248
+ def _encode_reference(self, waveform: torch.Tensor, sample_rate: int) -> torch.Tensor:
249
+ """Reference waveform -> ``[T, N]`` int64 codes (on model device)."""
250
+ import torchaudio
251
+
252
+ codec = self.get_audio_codec()
253
+ wav = waveform.float()
254
+ while wav.ndim < 3:
255
+ wav = wav.unsqueeze(0)
256
+ if sample_rate != self.config.sample_rate:
257
+ wav = torchaudio.functional.resample(wav, sample_rate, self.config.sample_rate)
258
+ if wav.shape[-1] < self.config.sample_rate:
259
+ wav = F.pad(wav, (0, self.config.sample_rate - wav.shape[-1]))
260
+ wav = wav.to(self.device, dtype=torch.float32)
261
+ codes_BNT = codec.encode(wav).audio_codes
262
+ return codes_BNT.squeeze(0).transpose(0, 1).to(torch.long)
263
+
264
+ @torch.no_grad()
265
+ def _decode_codes(self, codes_TN: torch.Tensor) -> torch.Tensor:
266
+ """``[T, N]`` raw codes -> mono waveform ``[L]`` (CPU float32)."""
267
+ codec = self.get_audio_codec()
268
+ codec_vocab = self.codebook_vocab_size - 2 # drop BOC/EOC
269
+ codes_TN = torch.where(codes_TN >= codec_vocab, torch.zeros_like(codes_TN), codes_TN)
270
+ codes_BNT = codes_TN.transpose(0, 1).unsqueeze(0).to(self.device, torch.long)
271
+ audio = codec.decode(codes_BNT).audio_values
272
+ return audio.squeeze(0).squeeze(0).detach().cpu().float()
273
+
274
+ # ----- prompt assembly ------------------------------------------------ #
275
+ @staticmethod
276
+ def _special_ids(tokenizer) -> dict[str, int | None]:
277
+ vocab = dict(tokenizer.get_added_vocab())
278
+ missing = [t for t in _REQUIRED_SPECIALS if t not in vocab]
279
+ if missing:
280
+ raise ValueError(f"Tokenizer is missing Higgs TTS specials: {missing}")
281
+ ids = {t: vocab[t] for t in _REQUIRED_SPECIALS}
282
+ ids["<|ref_text|>"] = vocab.get("<|ref_text|>")
283
+ return ids
284
+
285
+ def _build_prompt_ids(self, tokenizer, text: str, *, num_ref_tokens: int,
286
+ reference_text: str | None) -> list[int]:
287
+ sp = self._special_ids(tokenizer)
288
+ ids: list[int] = [sp["<|tts|>"]]
289
+ if reference_text and num_ref_tokens > 0 and sp["<|ref_text|>"] is not None:
290
+ ids.append(sp["<|ref_text|>"])
291
+ ids.extend(tokenizer.encode(reference_text, add_special_tokens=False))
292
+ if num_ref_tokens > 0:
293
+ ids.append(sp["<|ref_audio|>"])
294
+ ids.extend([AUDIO_PLACEHOLDER_ID] * num_ref_tokens)
295
+ ids.append(sp["<|text|>"])
296
+ ids.extend(tokenizer.encode(text, add_special_tokens=False))
297
+ ids.append(sp["<|audio|>"])
298
+ return ids
299
+
300
+ def _prefill_embeds(self, prompt_ids: list[int],
301
+ delayed_ref: torch.Tensor | None) -> torch.Tensor:
302
+ """Embed the prompt; overlay fused audio embedding at ``-100`` slots."""
303
+ ids = torch.tensor(prompt_ids, dtype=torch.long, device=self.device)
304
+ mask = ids == AUDIO_PLACEHOLDER_ID
305
+ safe = torch.where(mask, torch.zeros_like(ids), ids)
306
+ embeds = self.model.embed_tokens(safe)
307
+ if delayed_ref is not None and mask.any():
308
+ n = int(mask.sum().item())
309
+ audio = self.audio_embedding(delayed_ref[:n].to(self.device))
310
+ embeds[mask] = audio.to(embeds.dtype)
311
+ return embeds.unsqueeze(0) # [1, S, D]
312
+
313
+ # ----- generation ----------------------------------------------------- #
314
+ @torch.no_grad()
315
+ def generate_speech(
316
+ self,
317
+ text: str,
318
+ tokenizer,
319
+ *,
320
+ reference_audio: torch.Tensor | None = None,
321
+ reference_sample_rate: int | None = None,
322
+ reference_codes: torch.Tensor | None = None,
323
+ reference_text: str | None = None,
324
+ max_new_tokens: int = 2048,
325
+ temperature: float = 1.0,
326
+ top_p: float | None = None,
327
+ top_k: int | None = None,
328
+ ) -> torch.Tensor:
329
+ """Synthesize ``text`` into a mono 24 kHz waveform (CPU float32 ``[L]``).
330
+
331
+ Voice cloning: pass ``reference_audio`` (``[L]`` / ``[C, L]`` tensor with
332
+ ``reference_sample_rate``) or pre-encoded ``reference_codes`` (``[T, N]``).
333
+ ``reference_text`` (the transcript of the reference) improves cloning.
334
+ """
335
+ N = self.num_codebooks
336
+
337
+ delayed_ref = None
338
+ if reference_codes is not None:
339
+ delayed_ref = apply_delay_pattern(reference_codes.to(torch.long))
340
+ elif reference_audio is not None:
341
+ sr = reference_sample_rate or self.config.sample_rate
342
+ codes_TN = self._encode_reference(reference_audio, sr)
343
+ delayed_ref = apply_delay_pattern(codes_TN.cpu())
344
+
345
+ prompt_ids = self._build_prompt_ids(
346
+ tokenizer, text,
347
+ num_ref_tokens=0 if delayed_ref is None else delayed_ref.shape[0],
348
+ reference_text=reference_text,
349
+ )
350
+
351
+ inputs_embeds = self._prefill_embeds(prompt_ids, delayed_ref)
352
+ out = self.model(inputs_embeds=inputs_embeds, use_cache=True)
353
+ past = out.past_key_values
354
+ hidden_last = out.last_hidden_state[:, -1, :]
355
+ position = inputs_embeds.shape[1]
356
+
357
+ state = _SamplerState(num_codebooks=N)
358
+ rows: list[torch.Tensor] = []
359
+ for _ in range(max_new_tokens):
360
+ logits_NV = self.audio_head(hidden_last).to(torch.float32)[0] # [N, V]
361
+ codes_N = _sampler_step(
362
+ logits_NV, state,
363
+ temperature=temperature, top_p=top_p, top_k=top_k,
364
+ )
365
+ if state.generation_done:
366
+ break
367
+ rows.append(codes_N.cpu())
368
+
369
+ step_embed = self.audio_embedding(codes_N.unsqueeze(0)).unsqueeze(1)
370
+ cache_pos = torch.tensor([position], device=self.device)
371
+ out = self.model(
372
+ inputs_embeds=step_embed.to(inputs_embeds.dtype),
373
+ past_key_values=past,
374
+ use_cache=True,
375
+ cache_position=cache_pos,
376
+ )
377
+ past = out.past_key_values
378
+ hidden_last = out.last_hidden_state[:, -1, :]
379
+ position += 1
380
+
381
+ if len(rows) < N:
382
+ return torch.zeros(0, dtype=torch.float32)
383
+ delayed_LN = torch.stack(rows, dim=0)
384
+ codes_TN = reverse_delay_pattern(delayed_LN)
385
+ return self._decode_codes(codes_TN)
386
+
387
+
388
+ __all__ = [
389
+ "HiggsMultimodalQwen3ForConditionalGeneration",
390
+ "HiggsMultimodalQwen3PreTrainedModel",
391
+ ]
speaker_embedding.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e54562976d9f6334e391072d6289e2fcf685e8bfbe0f162091884f5bfc1ba2bb
3
+ size 11951
tags_spec.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"speakers": ["pavani"], "serve_tags": ["<|prosody:expressive_high|>"]}
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eb883de2de5adc5113f1f02b54830a0ea7cd6ef191cde65c41aceb3737d4d1c1
3
+ size 11433924
tokenizer_config.json ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": null,
5
+ "clean_up_tokenization_spaces": false,
6
+ "eos_token": "<|endoftext|>",
7
+ "errors": "replace",
8
+ "extra_special_tokens": [
9
+ "<|asr|>",
10
+ "<|streaming_asr|>",
11
+ "<|tts|>",
12
+ "<|streaming_tts|>",
13
+ "<|audio_cont_txt|>",
14
+ "<|audio|>",
15
+ "<|audio_end|>",
16
+ "<|text|>",
17
+ "<|text_end|>",
18
+ "<|eoc|>",
19
+ "<|user|>",
20
+ "<|assistant|>",
21
+ "<|system|>",
22
+ "<|await_audio|>",
23
+ "<|ref_audio|>",
24
+ "<|ref_text|>",
25
+ "<|emotion:elation|>",
26
+ "<|emotion:amusement|>",
27
+ "<|emotion:enthusiasm|>",
28
+ "<|emotion:determination|>",
29
+ "<|emotion:pride|>",
30
+ "<|emotion:contentment|>",
31
+ "<|emotion:affection|>",
32
+ "<|emotion:relief|>",
33
+ "<|emotion:contemplation|>",
34
+ "<|emotion:confusion|>",
35
+ "<|emotion:surprise|>",
36
+ "<|emotion:awe|>",
37
+ "<|emotion:longing|>",
38
+ "<|emotion:arousal|>",
39
+ "<|emotion:anger|>",
40
+ "<|emotion:fear|>",
41
+ "<|emotion:disgust|>",
42
+ "<|emotion:bitterness|>",
43
+ "<|emotion:sadness|>",
44
+ "<|emotion:shame|>",
45
+ "<|emotion:helplessness|>",
46
+ "<|env:music|>",
47
+ "<|env:noise|>",
48
+ "<|style:singing|>",
49
+ "<|style:shouting|>",
50
+ "<|style:whispering|>",
51
+ "<|sfx:cough|>",
52
+ "<|sfx:laughter|>",
53
+ "<|sfx:crying|>",
54
+ "<|sfx:screaming|>",
55
+ "<|sfx:burping|>",
56
+ "<|sfx:humming|>",
57
+ "<|sfx:sigh|>",
58
+ "<|sfx:sniff|>",
59
+ "<|sfx:sneeze|>",
60
+ "<|prosody:speed_very_slow|>",
61
+ "<|prosody:speed_slow|>",
62
+ "<|prosody:speed_fast|>",
63
+ "<|prosody:speed_very_fast|>",
64
+ "<|prosody:pitch_low|>",
65
+ "<|prosody:pitch_high|>",
66
+ "<|prosody:pause|>",
67
+ "<|prosody:long_pause|>",
68
+ "<|chatml|>",
69
+ "<|prosody:expressive_high|>",
70
+ "<|prosody:expressive_low|>"
71
+ ],
72
+ "is_local": false,
73
+ "local_files_only": false,
74
+ "model_max_length": 131072,
75
+ "pad_token": "<|endoftext|>",
76
+ "split_special_tokens": false,
77
+ "tokenizer_class": "Qwen2Tokenizer",
78
+ "unk_token": null
79
+ }