File size: 7,828 Bytes
6e802a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# config.py: Token vocabulary and constants: control, tag, plan and speech tokens, and the codec tier sizes read
# from MVC_NUM_SPEECH_TOKENS / MVC_NUM_CODEC_LEVELS / MVC_ENABLE_PLAN_TOKENS.

import os
from dataclasses import dataclass, field
from typing import List, Dict, Optional

BOS_TOKEN = "<BOS>"
EOS_TOKEN = "<EOS>"
PAD_TOKEN = "<PAD>"

USER_PROMPT_TOKEN = "[USER_PROMPT]"

THINK_START_TOKEN = "<THINK>"
THINK_END_TOKEN = "</THINK>"

AUDIO_START_TOKEN = "<AUDIO>"
AUDIO_END_TOKEN = "</AUDIO>"

SPEAKER_TOKEN = "[SPEAKER]"

EMOTION_TAGS = [
    "[EMO:neutral]",
    "[EMO:sarcastic]",
    "[EMO:angry]",
    "[EMO:sad]",
    "[EMO:joyful]",
    "[EMO:fearful]",
    "[EMO:ironic]",
    "[EMO:deadpan]",
]

PROSODY_TAGS = [
    "[PACE:slow]",
    "[PACE:normal]",
    "[PACE:fast]",
    "[PITCH:low]",
    "[PITCH:mid]",
    "[PITCH:high]",
    "[BREAK:short]",
    "[BREAK:long]",
]

_TRUE_STRINGS = {"1", "true", "yes", "on"}
_FALSE_STRINGS = {"0", "false", "no", "off"}


def _env_flag(name: str, default: str = "0") -> bool:
    raw = os.environ.get(name, default)
    value = str(raw).strip().lower()
    if value in _TRUE_STRINGS:
        return True
    if value in _FALSE_STRINGS:
        return False
    raise ValueError(
        f"{name}={raw!r} is not a recognised boolean. Use one of "
        f"{sorted(_TRUE_STRINGS)} or {sorted(_FALSE_STRINGS)}."
    )

ENABLE_PLAN_TOKENS: bool = _env_flag("MVC_ENABLE_PLAN_TOKENS", "0")

PLAN_START_TOKEN = "<PLAN>"
PLAN_END_TOKEN = "</PLAN>"

PLAN_WORD_SEP_TOKEN = "[PW]"

PITCH_BINS = 16
DURATION_BINS = 16
ENERGY_BINS = 8

PLAN_PITCH_PREFIX = "[P:"
PLAN_DURATION_PREFIX = "[D:"
PLAN_ENERGY_PREFIX = "[E:"
STYLE_TOKEN_PREFIX = "[STY:"
PLAN_TOKEN_SUFFIX = "]"

NUM_STYLE_TOKENS: int = int(os.environ.get("MVC_NUM_STYLE_TOKENS", "0"))
if NUM_STYLE_TOKENS < 0 or NUM_STYLE_TOKENS > 4096:
    raise ValueError(
        f"MVC_NUM_STYLE_TOKENS={NUM_STYLE_TOKENS} out of range [0, 4096] — this is a "
        f"small pooled codebook (1-4 tokens per utterance, §3.3), not a codec."
    )
if NUM_STYLE_TOKENS > 0 and not ENABLE_PLAN_TOKENS:
    raise ValueError(
        f"MVC_NUM_STYLE_TOKENS={NUM_STYLE_TOKENS} requires MVC_ENABLE_PLAN_TOKENS=1 "
        f"(the style tokens are part of the P²-CoT plan block). Set both or neither."
    )


def get_plan_pitch_tokens() -> List[str]:
    return [f"{PLAN_PITCH_PREFIX}{i}{PLAN_TOKEN_SUFFIX}" for i in range(PITCH_BINS)]


def get_plan_duration_tokens() -> List[str]:
    return [f"{PLAN_DURATION_PREFIX}{i}{PLAN_TOKEN_SUFFIX}" for i in range(DURATION_BINS)]


def get_plan_energy_tokens() -> List[str]:
    return [f"{PLAN_ENERGY_PREFIX}{i}{PLAN_TOKEN_SUFFIX}" for i in range(ENERGY_BINS)]


def get_style_tokens() -> List[str]:
    return [f"{STYLE_TOKEN_PREFIX}{i}{PLAN_TOKEN_SUFFIX}" for i in range(NUM_STYLE_TOKENS)]


def get_plan_tokens() -> List[str]:
    return (
        [PLAN_START_TOKEN, PLAN_END_TOKEN, PLAN_WORD_SEP_TOKEN]
        + get_plan_pitch_tokens()
        + get_plan_duration_tokens()
        + get_plan_energy_tokens()
        + get_style_tokens()
    )

NUM_SPEECH_TOKENS = int(os.environ.get("MVC_NUM_SPEECH_TOKENS", "65536"))
CODEBOOK_SIZE = NUM_SPEECH_TOKENS
SPEECH_TOKEN_PREFIX = "[SPEECH_"
SPEECH_TOKEN_SUFFIX = "]"


def get_speech_tokens() -> List[str]:
    return [f"{SPEECH_TOKEN_PREFIX}{i}{SPEECH_TOKEN_SUFFIX}" for i in range(CODEBOOK_SIZE)]


def get_control_tokens() -> List[str]:
    tokens = [
        USER_PROMPT_TOKEN,
        THINK_START_TOKEN,
        THINK_END_TOKEN,
        AUDIO_START_TOKEN,
        AUDIO_END_TOKEN,
        SPEAKER_TOKEN,
    ] + EMOTION_TAGS + PROSODY_TAGS
    if ENABLE_PLAN_TOKENS:
        tokens = tokens + get_plan_tokens()
    return tokens


def get_all_special_tokens() -> List[str]:
    return get_control_tokens() + get_speech_tokens()


@dataclass
class TrainingStageConfig:
    name: str
    description: str

    backbone_lr: float
    new_params_lr: float

    freeze_backbone: bool = False
    use_lora: bool = False
    lora_rank: int = 64
    lora_target_modules: List[str] = field(default_factory=lambda: ["in_proj", "out_proj"])

    lambda_reasoning: float = 0.0
    lambda_speech: float = 1.0

    mask_prompt: bool = True
    mask_reasoning: bool = True
    include_reasoning_in_sequence: bool = False

    warmup_steps: int = 1000
    scheduler_type: str = "cosine"

    max_seq_length: int = 2048
    gradient_checkpointing: bool = False

    freeze_backbone_for_mtp: bool = False
    mtp_healing: bool = False

STAGE_1_CONFIG = TrainingStageConfig(
    name="codec_alignment",
    description="Stage 1: Teach backbone to predict speech tokens from text (no CoT).",
    backbone_lr=1e-4,
    new_params_lr=3e-4,
    freeze_backbone=False,
    use_lora=True,
    lora_rank=64,
    lambda_reasoning=0.0,
    lambda_speech=1.0,
    mask_prompt=True,
    mask_reasoning=True,
    include_reasoning_in_sequence=False,
    warmup_steps=2000,
    max_seq_length=2048,
)

STAGE_2_CONFIG = TrainingStageConfig(
    name="cot_pretraining",
    description="Stage 2: Teach model to generate reasoning before speech tokens.",
    backbone_lr=5e-5,
    new_params_lr=5e-5,
    freeze_backbone=False,
    use_lora=False,
    lambda_reasoning=0.3,
    lambda_speech=1.0,
    mask_prompt=True,
    mask_reasoning=False,
    include_reasoning_in_sequence=True,
    warmup_steps=3000,
    max_seq_length=4096,
)

STAGE_3_CONFIG = TrainingStageConfig(
    name="expressive_sft",
    description="Stage 3: Fine-tune on expressive/emotional data with CoT.",
    backbone_lr=1e-5,
    new_params_lr=1e-5,
    freeze_backbone=False,
    use_lora=False,
    lambda_reasoning=0.3,
    lambda_speech=1.0,
    mask_prompt=True,
    mask_reasoning=False,
    include_reasoning_in_sequence=True,
    warmup_steps=500,
    max_seq_length=4096,
)

STAGE_4_CONFIG = TrainingStageConfig(
    name="dpo",
    description="Stage 4: Direct Preference Optimization for prosody alignment.",
    backbone_lr=5e-6,
    new_params_lr=5e-6,
    freeze_backbone=False,
    use_lora=False,
    lambda_reasoning=0.0,
    lambda_speech=1.0,
    mask_prompt=True,
    mask_reasoning=True,
    include_reasoning_in_sequence=True,
    warmup_steps=200,
    max_seq_length=4096,
)

STAGE_5_CONFIG = TrainingStageConfig(
    name="mtp_healing",
    description=(
        "Stage 5: MTP Healing [11] — freeze backbone and fine-tune only "
        "CRH + speculative prediction heads on self-generated data using NLL loss. "
        "Restores MTP accuracy after DPO/RL stages which may degrade speculative "
        "decoding acceptance rates."
    ),
    backbone_lr=0.0,
    new_params_lr=1e-4,
    freeze_backbone=False,
    use_lora=False,
    lambda_reasoning=0.0,
    lambda_speech=1.0,
    mask_prompt=True,
    mask_reasoning=True,
    include_reasoning_in_sequence=True,
    warmup_steps=100,
    max_seq_length=4096,
    freeze_backbone_for_mtp=True,
    mtp_healing=True,
)

STAGE_CONFIGS = {
    1: STAGE_1_CONFIG,
    2: STAGE_2_CONFIG,
    3: STAGE_3_CONFIG,
    4: STAGE_4_CONFIG,
    5: STAGE_5_CONFIG,
}


def get_stage_config(stage: int) -> TrainingStageConfig:
    if stage not in STAGE_CONFIGS:
        raise ValueError(f"Invalid stage {stage}. Must be one of {list(STAGE_CONFIGS.keys())}")
    return STAGE_CONFIGS[stage]


@dataclass
class ModelConfig:
    model_name: str = "state-spaces/mamba2-1.3b"
    codebook_size: int = NUM_SPEECH_TOKENS
    num_crh_heads: int = 0
    crh_discount: float = 0.85
    crh_codebook_size: int = 2048
    num_spec_heads: int = 0
    spec_discount: float = 0.8
    shared_spec_weights: bool = True
    use_speaker_conditioning: bool = False
    speaker_embedding_dim: int = 256
    num_speakers: int = 1000
    num_mtp_heads: int = 0
    mtp_discount: float = 0.8
    dtype: str = "bfloat16"

DEFAULT_MODEL_CONFIG = ModelConfig()