File size: 35,120 Bytes
45b5d4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
# Copyright 2026 LightSpeed (Author: Tianchi Liu), Alibaba Inc, TICTAP-11 and b-re-w. 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.
r"""
EmoTra-TTS training on CosyVoice2-0.5B: Stage I (the speech token language model) and Stage II (the emotion injection
of the flow matching model). Port of the upstream recipes `run_EmoTra_sft_LLM.sh`, `run_EmoTra_sft_Flow_Lynorm_fixs.sh`,
their `conf/*.yaml` and `tools/precompute_llm_tokens_sft_LLM.py` (github.com/Liu-Tianchi/EmoTra-TTS, commit `23fe9e4`).

Run it from a copy of this repository (`python train.py ...`); it imports the modeling and processing files next to it.

Commands:

- `stage1`: starts from the `FunAudioLLM/CosyVoice2-0.5B` backbone ([`load_cosyvoice2_backbone`]) with freshly
  initialized EmoTra-TTS modules and trains the whole language model (`llm.*`). Adam, learning rate $10^{-5}$,
  constant, no weight decay, gradient clipping 5, gradient accumulation 2, 8 epochs.
- `precompute`: decodes the Stage II speech token inputs with a Stage I checkpoint: for every record with at least
  100 ground truth speech tokens, between 0.5 and 1.5 times that many tokens; records whose decode is shorter than
  100 tokens are dropped, the rest are cut or padded with their last token to the ground truth count.
- `stage2`: copies `llm.vad_projection` and `llm.hidden_reconstructor` of a Stage I checkpoint into the flow
  matching model and trains `flow.vad_downsample` and `flow.emo_layer_norm` only. Adam, learning rate
  $5\times10^{-5}$, constant, eps $10^{-8}$, L2 weight decay $10^{-6}$, gradient clipping 1, gradient accumulation 2,
  4 epochs. Half of the batches run in streaming mode.

Both stages keep the model in BF16, run BF16 autocast, and step FP32 master copies of the trainable parameters
([`FP32MasterAdam`]). A checkpoint holds `trainable.safetensors` (the trainable parameters only), `config.json` and
the trainer state.

Data. The released model was trained on `RetentionLabs/emotra-ash-transition-50k`, synthetic emotion transitions of
the EmoVoice-DB speaker `ash` built as upstream's `step0` to `step2` scripts build them. Its preparation (transition
synthesis, VAD filtering, w2v2 hidden states, speech tokens, mel features) is not part of this file. `--records`
is a file `torch.load` reads into `{"train": [...], "held_out": [...]}`, each a list of dicts:

| Field | Stage | Shape and content |
|---|---|---|
| `key` | both | `str`, unique per record |
| `input_ids` | I, precompute | `list[int]`, text ids of the processor's tokenizer (`add_special_tokens=False`), at most 200 |
| `speech_tokens` | I, precompute | `list[int]`, CosyVoice2 speech tokens of the target audio (25 Hz), at least one |
| `vad_start`, `vad_end` | both | `list[float]` of 3, `[arousal, valence, dominance]` in $[0, 1]$ of utterances A and B |
| `hidden_states_start`, `hidden_states_end` | I | `torch.Tensor` of shape `(1024,)`, pooled hidden state of the audEERING w2v2 VAD regressor on A and B |
| `speech_feat` | II | `torch.Tensor` of shape `(num_frames, 80)`, the 24 kHz log mel of the target audio ([`EmoTraTTSProcessor.speech_features`]), 50 frames per second |

Stage II also reads `--llm-tokens`, the output of `precompute` (`{"train": {key: tokens}, "held_out": {...}}`), and
uses the processor's fixed speaker embedding (`speaker_embedding.safetensors`, a CAM++ embedding of one neutral
recording of the speaker).
"""

import argparse
import importlib
import os
import random
import re
import sys
import types
from collections import defaultdict
from collections.abc import Callable, Iterable, Mapping, Sequence
from pathlib import Path
from typing import Any

import torch
from safetensors.torch import load_file, save_file
from torch import nn
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import Dataset
from transformers import Trainer, TrainingArguments
from transformers.trainer import TRAINING_ARGS_NAME


# The model files use package relative imports, so the folder of this file is loaded as the package `emotra_tts`.
_package = types.ModuleType("emotra_tts")
_package.__path__ = [str(Path(__file__).resolve().parent)]
sys.modules.setdefault("emotra_tts", _package)
EmoTraTTSConfig = importlib.import_module("emotra_tts.configuration_emotra_tts").EmoTraTTSConfig
repetition_aware_sampling = importlib.import_module("emotra_tts.generation_emotra_tts").repetition_aware_sampling
EmoTraTTSForConditionalGeneration = importlib.import_module(
    "emotra_tts.modeling_emotra_tts"
).EmoTraTTSForConditionalGeneration


STAGE1_TRAINABLE = "llm."
"""Name prefix of the parameters Stage I trains: the whole language model, as upstream's `train.py --model llm`."""

MIN_LLM_TOKENS = 100
TRAINABLE_WEIGHTS_NAME = "trainable.safetensors"

# Key renaming from the released CosyVoice2 files (`llm.pt`, `flow.pt`, `hift.pt`) to this model, applied in order.
COSYVOICE2_RENAMES = [
    (r"^llm\.llm\.model\.model\.", "llm.model."),
    (r"\.up_embed\.out\.0\.", ".up_input_projection.proj."),
    (r"\.up_embed\.out\.1\.", ".up_input_projection.layer_norm."),
    (r"\.up_encoders\.(\d+)\.self_attn\.", r".up_layers.\1.self_attn."),
    (r"\.up_encoders\.(\d+)\.feed_forward\.", r".up_layers.\1.feed_forward."),
    (r"\.up_encoders\.(\d+)\.norm_mha\.", r".up_layers.\1.self_attn_layer_norm."),
    (r"\.up_encoders\.(\d+)\.norm_ff\.", r".up_layers.\1.final_layer_norm."),
    (r"\.embed\.out\.0\.", ".input_projection.proj."),
    (r"\.embed\.out\.1\.", ".input_projection.layer_norm."),
    (r"\.encoders\.(\d+)\.self_attn\.", r".layers.\1.self_attn."),
    (r"\.encoders\.(\d+)\.feed_forward\.", r".layers.\1.feed_forward."),
    (r"\.encoders\.(\d+)\.norm1\.", r".layers.\1.self_attn_layer_norm."),
    (r"\.encoders\.(\d+)\.norm2\.", r".layers.\1.final_layer_norm."),
    (r"\.encoders\.(\d+)\.norm_mha\.", r".layers.\1.self_attn_layer_norm."),
    (r"\.encoders\.(\d+)\.norm_ff\.", r".layers.\1.final_layer_norm."),
    (r"\.after_norm\.", ".layer_norm."),
    (r"\.weight_g$", ".parametrizations.weight.original0"),
    (r"\.weight_v$", ".parametrizations.weight.original1"),
]
EMOTRA_MODULES = (
    "llm.vad_projection.",
    "llm.hidden_reconstructor.",
    "flow.vad_projection.",
    "flow.vad_hidden_reconstructor.",
    "flow.vad_downsample.",
    "flow.emo_layer_norm.",
)


def load_cosyvoice2_backbone(model: nn.Module, repo_id: str = "FunAudioLLM/CosyVoice2-0.5B") -> None:
    r"""
    Loads the three released CosyVoice2 networks into an [`EmoTraTTSForConditionalGeneration`], leaving the EmoTra-TTS
    modules as initialized.

    Args:
        model (`nn.Module`):
            The model.
        repo_id (`str`, *optional*, defaults to `"FunAudioLLM/CosyVoice2-0.5B"`):
            Hub repository or local folder with `llm.pt`, `flow.pt` and `hift.pt`.

    Raises:
        `ValueError`: If a backbone parameter is missing or a released tensor has no place in the model.
    """
    from huggingface_hub import hf_hub_download

    state = {}
    for prefix in ("llm", "flow", "hift"):
        path = Path(repo_id) / f"{prefix}.pt"
        path = path if path.is_file() else hf_hub_download(repo_id, f"{prefix}.pt")
        for key, value in torch.load(path, map_location="cpu", weights_only=True).items():
            name = f"{prefix}.{key}"
            for pattern, replacement in COSYVOICE2_RENAMES:
                name = re.sub(pattern, replacement, name)
            state[name] = value
    ignored = re.compile(r"llm\.model\.rotary_emb\.inv_freq|llm\.model\.lm_head\.")
    state = {name: value for name, value in state.items() if not ignored.search(name)}
    missing, unexpected = model.load_state_dict(state, strict=False)
    missing = [name for name in missing if not name.startswith(EMOTRA_MODULES)]
    if missing or unexpected:
        raise ValueError(f"backbone mismatch: missing {missing}, unexpected {unexpected}")


class FP32MasterAdam(torch.optim.Adam):
    r"""
    Constructs Adam on FP32 master copies of BF16 model parameters. The model parameters keep BF16 for forward and
    backward; each step copies their gradients to the masters, updates the masters and writes them back, so updates
    below the BF16 resolution accumulate. `weight_decay` is the L2 term Adam adds to the gradient.

    Args:
        params (`Iterable[nn.Parameter]`):
            Model parameters in checkpoint order.
        lr (`float`, *optional*, defaults to 0.001):
            Learning rate.
        **kwargs:
            Additional arguments passed to `torch.optim.Adam`.
    """

    def __init__(self, params: Iterable[nn.Parameter], lr: float = 1e-3, **kwargs: Any):
        self._model_params = list(params)
        masters = [nn.Parameter(parameter.detach().float().clone()) for parameter in self._model_params]
        super().__init__(masters, lr=lr, **kwargs)

    def zero_grad(self, set_to_none: bool = True) -> None:
        super().zero_grad(set_to_none=set_to_none)
        for parameter in self._model_params:
            if parameter.grad is not None:
                if set_to_none:
                    parameter.grad = None
                else:
                    parameter.grad.detach_()
                    parameter.grad.zero_()

    @torch.no_grad()
    def step(self, closure: Callable[[], torch.Tensor] | None = None) -> None:
        if closure is not None:
            raise NotImplementedError("FP32 master optimizer does not support a closure; compute and clip model gradients first")
        masters = [parameter for group in self.param_groups for parameter in group["params"]]
        for parameter, master in zip(self._model_params, masters, strict=True):
            master.grad = None if parameter.grad is None else parameter.grad.detach().float()
        super().step()
        for parameter, master in zip(self._model_params, masters, strict=True):
            parameter.copy_(master)

    def state_dict(self) -> dict[str, Any]:
        state = super().state_dict()
        state["fp32_master_params"] = [
            parameter.detach().clone() for group in self.param_groups for parameter in group["params"]
        ]
        return state

    def load_state_dict(self, state_dict: dict[str, Any]) -> None:
        state_dict = dict(state_dict)
        masters = state_dict.pop("fp32_master_params", None)
        super().load_state_dict(state_dict)
        with torch.no_grad():
            targets = [parameter for group in self.param_groups for parameter in group["params"]]
            sources = masters if masters is not None else [parameter.float() for parameter in self._model_params]
            for target, source in zip(targets, sources, strict=True):
                target.copy_(source)


class EmoTraTrainer(Trainer):
    r"""
    [`~transformers.Trainer`] that steps [`FP32MasterAdam`] over the trainable parameters, in one group, and saves only
    the trainable parameters (`trainable.safetensors`) in a checkpoint.
    """

    def create_optimizer(self, model: nn.Module | None = None) -> torch.optim.Optimizer:
        if self.optimizer is None:
            model = self.model if model is None else model
            self.optimizer = FP32MasterAdam(
                [param for param in model.parameters() if param.requires_grad],
                lr=self.args.learning_rate,
                betas=(self.args.adam_beta1, self.args.adam_beta2),
                eps=self.args.adam_epsilon,
                weight_decay=self.args.weight_decay,
            )
        return self.optimizer

    def _save(self, output_dir: str | None = None, state_dict: dict | None = None) -> None:
        output_dir = output_dir if output_dir is not None else self.args.output_dir
        if not self.args.should_save:
            return
        os.makedirs(output_dir, exist_ok=True)
        model = self.accelerator.unwrap_model(self.model, keep_torch_compile=False)
        trainable = {
            name: param.detach().contiguous().cpu() for name, param in model.named_parameters() if param.requires_grad
        }
        save_file(trainable, os.path.join(output_dir, TRAINABLE_WEIGHTS_NAME), metadata={"format": "pt"})
        model.config.save_pretrained(output_dir)
        torch.save(self.args, os.path.join(output_dir, TRAINING_ARGS_NAME))

    def _load_from_checkpoint(self, resume_from_checkpoint: str, model: nn.Module | None = None) -> None:
        load_trainable_weights(self.model if model is None else model, resume_from_checkpoint)


def load_trainable_weights(model: nn.Module, checkpoint: str | os.PathLike) -> None:
    r"""
    Loads the trainable parameters a checkpoint holds into `model`.

    Args:
        model (`nn.Module`):
            The model, already frozen the way the run froze it.
        checkpoint (`str` or `os.PathLike`):
            The checkpoint directory.

    Raises:
        `ValueError`: If the checkpoint and the trainable parameters of `model` do not name the same tensors.
    """
    state = load_file(os.path.join(checkpoint, TRAINABLE_WEIGHTS_NAME))
    params = dict(model.named_parameters())
    expected = {name for name, param in params.items() if param.requires_grad}
    if set(state) != expected:
        missing, unexpected = sorted(expected - set(state)), sorted(set(state) - expected)
        raise ValueError(
            f"{checkpoint} does not match the trainable parameters: missing {missing}, unexpected {unexpected}"
        )
    with torch.no_grad():
        for name, tensor in state.items():
            params[name].copy_(tensor.to(device=params[name].device, dtype=params[name].dtype))


class EmoTraTransitionDataset(Dataset):
    r"""
    The training items of one stage. Stage I items hold the text ids, the speech tokens, the start and end VAD and the
    hidden states of A and B. Stage II items hold the speech tokens the Stage I model decoded (`llm_tokens`), the mel of
    the audio, the speaker embedding and the VAD. Tokens and mel are cut to a common length of `token_mel_ratio` frames
    per token, as upstream's `compute_fbank` cuts them.

    Args:
        records (`Sequence[Mapping[str, Any]]`):
            Records in the format of this file's docstring; Stage II records also hold `llm_tokens`.
        stage (`int`):
            1 or 2.
        speaker_embedding (`torch.Tensor`, *optional*):
            The neutral speaker embedding (192), needed for Stage II.
        token_mel_ratio (`int`, *optional*, defaults to 2):
            Mel frames per speech token.
    """

    def __init__(
        self,
        records: Sequence[Mapping[str, Any]],
        stage: int,
        speaker_embedding: torch.Tensor | None = None,
        token_mel_ratio: int = 2,
    ):
        if stage not in (1, 2):
            raise ValueError(f"stage must be 1 or 2, got {stage}")
        if stage == 2 and speaker_embedding is None:
            raise ValueError("Stage II needs the speaker embedding")
        self.records = list(records)
        self.stage = stage
        self.speaker_embedding = speaker_embedding
        self.token_mel_ratio = token_mel_ratio

    def __len__(self) -> int:
        return len(self.records)

    def __getitem__(self, index: int) -> dict[str, torch.Tensor]:
        record = self.records[index]
        item = {
            "vad_start": torch.tensor(record["vad_start"], dtype=torch.bfloat16),
            "vad_end": torch.tensor(record["vad_end"], dtype=torch.bfloat16),
        }
        if self.stage == 1:
            item["input_ids"] = torch.tensor(record["input_ids"], dtype=torch.long)
            item["speech_token_ids"] = torch.tensor(record["speech_tokens"], dtype=torch.long)
            item["hidden_states_start"] = torch.as_tensor(record["hidden_states_start"], dtype=torch.bfloat16)
            item["hidden_states_end"] = torch.as_tensor(record["hidden_states_end"], dtype=torch.bfloat16)
            return item
        feat = torch.as_tensor(record["speech_feat"])
        tokens = torch.tensor(record["llm_tokens"], dtype=torch.long)
        length = min(feat.shape[0] // self.token_mel_ratio, tokens.shape[0])
        item["speech_token_ids"] = tokens[:length]
        item["speech_feat"] = feat[: length * self.token_mel_ratio].to(torch.bfloat16)
        item["speaker_embedding"] = torch.as_tensor(self.speaker_embedding, dtype=torch.bfloat16).reshape(-1)
        return item


def collate_stage1(items: Sequence[Mapping[str, torch.Tensor]]) -> dict[str, torch.Tensor]:
    """
    Pads Stage I items into the keyword arguments of [`EmoTraTTSForConditionalGeneration.forward`].

    Args:
        items (`Sequence[Mapping[str, torch.Tensor]]`):
            Items of [`EmoTraTransitionDataset`] for Stage I.

    Returns:
        `dict[str, torch.Tensor]`: `input_ids`, `input_lengths`, `speech_token_ids`, `speech_token_lengths`,
        `vad_start`, `vad_end`, `hidden_states_start`, `hidden_states_end`.
    """
    return {
        "input_ids": pad_sequence([i["input_ids"] for i in items], batch_first=True),
        "input_lengths": torch.tensor([len(i["input_ids"]) for i in items], dtype=torch.int32),
        "speech_token_ids": pad_sequence([i["speech_token_ids"] for i in items], batch_first=True),
        "speech_token_lengths": torch.tensor([len(i["speech_token_ids"]) for i in items], dtype=torch.int32),
        "vad_start": torch.stack([i["vad_start"] for i in items]),
        "vad_end": torch.stack([i["vad_end"] for i in items]),
        "hidden_states_start": torch.stack([i["hidden_states_start"] for i in items]),
        "hidden_states_end": torch.stack([i["hidden_states_end"] for i in items]),
    }


def collate_stage2(items: Sequence[Mapping[str, torch.Tensor]], streaming_probability: float = 0.5) -> dict[str, Any]:
    """
    Pads Stage II items, and draws whether the batch runs in streaming mode with probability one half, as upstream
    draws it per batch.

    Args:
        items (`Sequence[Mapping[str, torch.Tensor]]`):
            Items of [`EmoTraTransitionDataset`] for Stage II.
        streaming_probability (`float`, *optional*, defaults to 0.5):
            Probability of streaming mode.

    Returns:
        `dict[str, Any]`: `speech_token_ids`, `speech_token_lengths`, `speech_feat`, `speech_feat_lengths`,
        `speaker_embedding`, `vad_start`, `vad_end` and `streaming`.
    """
    return {
        "speech_token_ids": pad_sequence([i["speech_token_ids"] for i in items], batch_first=True),
        "speech_token_lengths": torch.tensor([len(i["speech_token_ids"]) for i in items], dtype=torch.int32),
        "speech_feat": pad_sequence([i["speech_feat"] for i in items], batch_first=True),
        "speech_feat_lengths": torch.tensor([len(i["speech_feat"]) for i in items], dtype=torch.int32),
        "speaker_embedding": torch.stack([i["speaker_embedding"] for i in items]),
        "vad_start": torch.stack([i["vad_start"] for i in items]),
        "vad_end": torch.stack([i["vad_end"] for i in items]),
        "streaming": random.random() < streaming_probability,
    }


def prepare_stage1(model: nn.Module) -> list[str]:
    r"""
    Sets up Stage I as upstream does: the whole language model (`llm.*`, the Qwen2 decoder, the text and speech
    embeddings, the speech head and the two VAD modules) trains; the flow model and HiFT are frozen. The model is BF16.

    Args:
        model (`nn.Module`):
            An [`EmoTraTTSForConditionalGeneration`].

    Returns:
        `list[str]`: Names of the trainable parameters.
    """
    model.to(dtype=torch.bfloat16)
    for name, param in model.named_parameters():
        param.requires_grad_(name.startswith(STAGE1_TRAINABLE))
    return [name for name, param in model.named_parameters() if param.requires_grad]


def load_stage1_weights_for_flow(model: nn.Module, checkpoint: str | os.PathLike) -> list[str]:
    """
    Loads the `llm.vad_projection` and `llm.hidden_reconstructor` weights of a Stage I checkpoint, which
    [`prepare_stage2`] then copies into the flow model.

    Args:
        model (`nn.Module`):
            An [`EmoTraTTSForConditionalGeneration`].
        checkpoint (`str` or `os.PathLike`):
            The Stage I checkpoint directory.

    Returns:
        `list[str]`: The loaded parameter names.

    Raises:
        ValueError: If the checkpoint lacks a parameter of the two modules.
    """
    state = load_file(os.path.join(checkpoint, TRAINABLE_WEIGHTS_NAME))
    wanted = {
        name: param
        for name, param in model.named_parameters()
        if name.startswith(("llm.vad_projection.", "llm.hidden_reconstructor."))
    }
    missing = sorted(set(wanted) - set(state))
    if missing:
        raise ValueError(f"{checkpoint} lacks {missing}")
    with torch.no_grad():
        for name, param in wanted.items():
            param.copy_(state[name].to(param.device, param.dtype))
    return sorted(wanted)


def prepare_stage2(model: nn.Module) -> list[str]:
    """
    Sets up Stage II with [`EmoTraTTSForConditionalGeneration.prepare_flow_stage`]: the VAD modules copied into the
    flow model, everything frozen except `flow.vad_downsample` and `flow.emo_layer_norm`.

    Args:
        model (`nn.Module`):
            The model, with the Stage I VAD modules loaded.

    Returns:
        `list[str]`: Names of the trainable parameters.
    """
    model.to(dtype=torch.bfloat16)
    model.prepare_flow_stage()
    return [name for name, param in model.named_parameters() if param.requires_grad]


def load_for_generation(
    model: nn.Module, stage1_checkpoint: str | os.PathLike, stage2_checkpoint: str | os.PathLike
) -> nn.Module:
    r"""
    Assembles the generating model as upstream's inference does: the Stage I language model, with the flow model's VAD
    modules copied from it, and the Stage II flow emotion modules. This is how the weights of this repository were
    assembled from `stage1/` and `stage2/`.

    Args:
        model (`nn.Module`):
            An [`EmoTraTTSForConditionalGeneration`] holding the CosyVoice2 backbone.
        stage1_checkpoint (`str` or `os.PathLike`):
            The Stage I checkpoint directory.
        stage2_checkpoint (`str` or `os.PathLike`):
            The Stage II checkpoint directory.

    Returns:
        `nn.Module`: The model, frozen and in evaluation mode.
    """
    prepare_stage1(model)
    load_trainable_weights(model, stage1_checkpoint)
    prepare_stage2(model)
    load_trainable_weights(model, stage2_checkpoint)
    model.requires_grad_(False)
    return model.eval()


def decode_llm_tokens_batch(
    model: nn.Module,
    input_ids: torch.Tensor,
    vad_start: torch.Tensor,
    vad_end: torch.Tensor,
    min_lengths: Sequence[int],
    max_lengths: Sequence[int],
    top_p: float = 0.8,
    top_k: int = 25,
    window_size: int = 10,
    repetition_threshold: float = 0.1,
) -> list[list[int]]:
    r"""
    Decodes equal-length text prefixes as independent autoregressive token sequences.

    Args:
        model (`nn.Module`):
            The Stage I model.
        input_ids (`torch.Tensor` of shape `(batch_size, text_length)`):
            Equal-length text ids.
        vad_start (`torch.Tensor` of shape `(batch_size, 3)`):
            Start VAD.
        vad_end (`torch.Tensor` of shape `(batch_size, 3)`):
            End VAD.
        min_lengths (`Sequence[int]`):
            Fewest tokens per sequence.
        max_lengths (`Sequence[int]`):
            Most tokens per sequence.
        top_p (`float`, *optional*, defaults to 0.8):
            Nucleus probability.
        top_k (`int`, *optional*, defaults to 25):
            Candidates.
        window_size (`int`, *optional*, defaults to 10):
            Repetition window.
        repetition_threshold (`float`, *optional*, defaults to 0.1):
            Repetition limit.

    Returns:
        `list[list[int]]`: Decoded tokens in input order.
    """
    batch_size = input_ids.shape[0]
    llm = model.llm
    sos = llm.llm_embedding.weight[llm.sos_index].reshape(1, 1, -1).expand(batch_size, -1, -1)
    task_id = llm.llm_embedding.weight[llm.task_id_index].reshape(1, 1, -1).expand(batch_size, -1, -1)
    vad = llm.embed_vad(vad_start.to(sos.dtype), vad_end.to(sos.dtype)).to(sos.dtype)
    hidden_states = torch.concat([sos, vad, llm.embed_text(input_ids), task_id], dim=1)
    tokens = [[] for _ in range(batch_size)]
    active = list(range(batch_size))
    past_key_values = None
    while active:
        logits, past_key_values = llm(hidden_states, past_key_values=past_key_values, use_cache=True)
        next_active = []
        next_embeddings = []
        for active_index, original_index in enumerate(active):
            log_probs = logits[active_index, -1].float().log_softmax(dim=-1)
            if len(tokens[original_index]) < min_lengths[original_index]:
                log_probs[llm.eos_token_id] = -float("inf")
            token = repetition_aware_sampling(
                log_probs, tokens[original_index], top_p, top_k, window_size, repetition_threshold
            )
            if token not in llm.stop_token_ids:
                tokens[original_index].append(token)
            if token not in llm.stop_token_ids and len(tokens[original_index]) < max_lengths[original_index]:
                next_active.append(original_index)
                next_embeddings.append(llm.speech_embedding.weight[token])
        if not next_active:
            break
        indices = torch.tensor([active.index(index) for index in next_active], device=hidden_states.device)
        past_key_values.batch_select_indices(indices)
        active = next_active
        hidden_states = torch.stack(next_embeddings).unsqueeze(1)
    return tokens


def truncate_or_pad_tokens(generated: Sequence[int], length: int) -> list[int]:
    """
    Cuts decoded tokens to `length`, or pads them with their last token (0 when there is none).

    Args:
        generated (`Sequence[int]`):
            Decoded tokens.
        length (`int`):
            The ground truth token count.

    Returns:
        `list[int]`: Exactly `length` tokens.
    """
    generated = list(generated)
    if len(generated) >= length:
        return generated[:length]
    return generated + [generated[-1] if generated else 0] * (length - len(generated))


@torch.inference_mode()
def precompute_llm_tokens(
    model: nn.Module,
    records: Sequence[Mapping[str, Any]],
    min_token_len: int = MIN_LLM_TOKENS,
    decode_batch_size: int = 32,
) -> dict[str, list[int]]:
    r"""
    The Stage II inputs (`precompute_llm_tokens_sft_LLM.py`): for every record with at least `min_token_len` ground
    truth tokens, the Stage I model decodes between half and one and a half times that many tokens; records whose
    decode is shorter than `min_token_len` are dropped, the rest are cut or padded to the ground truth count.

    Args:
        model (`nn.Module`):
            The Stage I model, in evaluation mode.
        records (`Sequence[Mapping[str, Any]]`):
            Records with `key`, `input_ids`, `speech_tokens`, `vad_start` and `vad_end`.
        min_token_len (`int`, *optional*, defaults to 100):
            Fewest tokens kept (4 s at 25 Hz).
        decode_batch_size (`int`, *optional*, defaults to 32):
            Equal text-length records decoded per model call.

    Returns:
        `dict[str, list[int]]`: Tokens per kept record key.
    """
    device = next(model.parameters()).device
    buckets = defaultdict(list)
    for record in records:
        if len(record["speech_tokens"]) >= min_token_len:
            buckets[len(record["input_ids"])].append(record)
    result = {}
    for bucket in buckets.values():
        for start in range(0, len(bucket), decode_batch_size):
            batch = bucket[start : start + decode_batch_size]
            generated = decode_llm_tokens_batch(
                model,
                torch.tensor([record["input_ids"] for record in batch], device=device),
                torch.tensor([record["vad_start"] for record in batch], device=device),
                torch.tensor([record["vad_end"] for record in batch], device=device),
                [max(1, int(len(record["speech_tokens"]) * 0.5)) for record in batch],
                [int(len(record["speech_tokens"]) * 1.5) for record in batch],
            )
            for record, tokens in zip(batch, generated, strict=True):
                if len(tokens) >= min_token_len:
                    result[record["key"]] = truncate_or_pad_tokens(tokens, len(record["speech_tokens"]))
    return result


def stage_training_arguments(stage: int, output_dir: str, **overrides: Any) -> TrainingArguments:
    r"""
    The training arguments of a stage, with upstream's recipe: Stage I Adam at $10^{-5}$, constant, no weight decay,
    clipping 5, accumulation 2, 8 epochs; Stage II Adam at $5\times10^{-5}$, constant, eps $10^{-8}$, L2 weight decay
    $10^{-6}$, clipping 1, accumulation 2, 4 epochs. Both run BF16 autocast.

    Args:
        stage (`int`):
            1 or 2.
        output_dir (`str`):
            Run directory.
        **overrides:
            Fields of [`~transformers.TrainingArguments`] that replace the defaults.

    Returns:
        [`~transformers.TrainingArguments`]: The arguments.
    """
    common = dict(
        output_dir=output_dir,
        lr_scheduler_type="constant",
        gradient_accumulation_steps=2,
        eval_strategy="steps",
        save_strategy="steps",
        logging_steps=10,
        report_to="none",
        remove_unused_columns=False,
        dataloader_num_workers=0,
        seed=0,
        bf16=True,
    )
    if stage == 1:
        recipe = dict(
            learning_rate=1e-5, weight_decay=0.0, max_grad_norm=5.0, num_train_epochs=8, eval_steps=300,
            save_steps=300, label_names=["speech_token_ids"],
        )  # fmt: skip
    else:
        recipe = dict(
            learning_rate=5e-5, adam_epsilon=1e-8, weight_decay=1e-6, max_grad_norm=1.0, num_train_epochs=4,
            eval_steps=200, save_steps=200, label_names=["speech_feat"],
        )  # fmt: skip
    return TrainingArguments(**{**common, **recipe, **overrides})


def build_model(release: str, cosyvoice: str) -> nn.Module:
    """
    Builds an [`EmoTraTTSForConditionalGeneration`] with the configuration of this repository, the CosyVoice2 backbone
    and freshly initialized EmoTra-TTS modules, in BF16.

    Args:
        release (`str`):
            Folder or Hub id of this repository, for `config.json`.
        cosyvoice (`str`):
            Folder or Hub id of the released CosyVoice2 checkpoint.

    Returns:
        `nn.Module`: The model.
    """
    model = EmoTraTTSForConditionalGeneration(EmoTraTTSConfig.from_pretrained(release))
    load_cosyvoice2_backbone(model, cosyvoice)
    return model.to(torch.bfloat16)


def main(argv: Sequence[str] | None = None) -> None:
    """
    Command line entry point, see the module docstring.

    Args:
        argv (`Sequence[str]`, *optional*):
            Arguments, defaults to `sys.argv[1:]`.
    """
    parser = argparse.ArgumentParser(prog="python train.py")
    parser.add_argument("--records", required=True, help="torch file with {'train': [...], 'held_out': [...]}")
    parser.add_argument("--release", default=str(Path(__file__).resolve().parent), help="this repository")
    parser.add_argument("--cosyvoice", default="FunAudioLLM/CosyVoice2-0.5B")
    parser.add_argument("--device", default=None)
    commands = parser.add_subparsers(dest="command", required=True)
    for name in ("stage1", "stage2"):
        stage = commands.add_parser(name)
        stage.add_argument("--output-dir", required=True)
        stage.add_argument("--per-device-train-batch-size", type=int, default=16)
        stage.add_argument("--max-steps", type=int, default=-1)
        if name == "stage2":
            stage.add_argument("--stage1-checkpoint", required=True)
            stage.add_argument("--llm-tokens", required=True)
    precompute = commands.add_parser("precompute")
    precompute.add_argument("--stage1-checkpoint", required=True)
    precompute.add_argument("--output", required=True)
    precompute.add_argument("--min-token-len", type=int, default=MIN_LLM_TOKENS)
    precompute.add_argument("--decode-batch-size", type=int, default=32)
    args = parser.parse_args(argv)

    device = args.device or ("cuda" if torch.cuda.is_available() else "cpu")
    records = torch.load(args.records, weights_only=False)
    train_records, eval_records = records["train"], records["held_out"]
    model = build_model(args.release, args.cosyvoice)

    if args.command == "precompute":
        prepare_stage1(model)
        load_trainable_weights(model, args.stage1_checkpoint)
        model.to(device).eval()
        tokens = {
            split: precompute_llm_tokens(model, part, args.min_token_len, args.decode_batch_size)
            for split, part in (("train", train_records), ("held_out", eval_records))
        }
        torch.save(tokens, args.output)
        print(f"{len(tokens['train'])} train and {len(tokens['held_out'])} held-out records kept for Stage II")
        return

    if args.command == "stage1":
        prepare_stage1(model)
        train_set, eval_set = EmoTraTransitionDataset(train_records, 1), EmoTraTransitionDataset(eval_records, 1)
        collator = collate_stage1
    else:
        load_stage1_weights_for_flow(model, args.stage1_checkpoint)
        prepare_stage2(model)
        llm_tokens = torch.load(args.llm_tokens)
        from safetensors.torch import load_file as load_safetensors
        from transformers.utils.hub import cached_file

        speaker = load_safetensors(cached_file(args.release, "speaker_embedding.safetensors"))["speaker_embedding"]
        parts = []
        for split, part in (("train", train_records), ("held_out", eval_records)):
            kept = llm_tokens[split]
            parts.append([{**record, "llm_tokens": kept[record["key"]]} for record in part if record["key"] in kept])
        train_set = EmoTraTransitionDataset(parts[0], 2, speaker_embedding=speaker)
        eval_set = EmoTraTransitionDataset(parts[1], 2, speaker_embedding=speaker)
        collator = collate_stage2
    stage = 1 if args.command == "stage1" else 2
    training_args = stage_training_arguments(
        stage, args.output_dir, per_device_train_batch_size=args.per_device_train_batch_size, max_steps=args.max_steps
    )
    trainer = EmoTraTrainer(
        model=model, args=training_args, train_dataset=train_set, eval_dataset=eval_set, data_collator=collator
    )
    trainer.train(resume_from_checkpoint=any(Path(args.output_dir).glob("checkpoint-*")) or None)


if __name__ == "__main__":
    main()