amir0907 commited on
Commit
0aa2a79
·
verified ·
1 Parent(s): 9f5e1c8

Upload 46 files

Browse files
Files changed (46) hide show
  1. VibeVoice-tpu/diff_head_layers.txt +26 -0
  2. VibeVoice-tpu/pyproject.toml +35 -0
  3. VibeVoice-tpu/src/TPU_SETUP.md +310 -0
  4. VibeVoice-tpu/src/data_vibevoice.py +446 -0
  5. VibeVoice-tpu/src/finetune_surgery_colab.ipynb +1225 -0
  6. VibeVoice-tpu/src/finetune_surgery_t4.py +1214 -0
  7. VibeVoice-tpu/src/finetune_vibevoice_lora105.py +1066 -0
  8. VibeVoice-tpu/src/finetune_vibevoice_tpu.py +1638 -0
  9. VibeVoice-tpu/src/finetune_vibevoice_tpu_colab.ipynb +1172 -0
  10. VibeVoice-tpu/src/preprocess_vibevoice.py +192 -0
  11. VibeVoice-tpu/src/preprocess_vibevoice_tpu.py +697 -0
  12. VibeVoice-tpu/src/tpu_config.py +275 -0
  13. VibeVoice-tpu/src/vibevoice/.DS_Store +0 -0
  14. VibeVoice-tpu/src/vibevoice/configs/qwen2.5_1.5b_64k.json +112 -0
  15. VibeVoice-tpu/src/vibevoice/configs/qwen2.5_7b_32k.json +113 -0
  16. VibeVoice-tpu/src/vibevoice/modular/__init__.py +0 -0
  17. VibeVoice-tpu/src/vibevoice/modular/__pycache__/__init__.cpython-311.pyc +0 -0
  18. VibeVoice-tpu/src/vibevoice/modular/__pycache__/__init__.cpython-39.pyc +0 -0
  19. VibeVoice-tpu/src/vibevoice/modular/__pycache__/configuration_vibevoice.cpython-311.pyc +0 -0
  20. VibeVoice-tpu/src/vibevoice/modular/__pycache__/modeling_vibevoice.cpython-311.pyc +0 -0
  21. VibeVoice-tpu/src/vibevoice/modular/__pycache__/modeling_vibevoice.cpython-39.pyc +0 -0
  22. VibeVoice-tpu/src/vibevoice/modular/__pycache__/modular_vibevoice_diffusion_head.cpython-311.pyc +0 -0
  23. VibeVoice-tpu/src/vibevoice/modular/__pycache__/modular_vibevoice_text_tokenizer.cpython-311.pyc +0 -0
  24. VibeVoice-tpu/src/vibevoice/modular/__pycache__/modular_vibevoice_tokenizer.cpython-311.pyc +0 -0
  25. VibeVoice-tpu/src/vibevoice/modular/configuration_vibevoice.py +266 -0
  26. VibeVoice-tpu/src/vibevoice/modular/modeling_vibevoice.py +508 -0
  27. VibeVoice-tpu/src/vibevoice/modular/modeling_vibevoice_inference.py +729 -0
  28. VibeVoice-tpu/src/vibevoice/modular/modular_vibevoice_diffusion_head.py +287 -0
  29. VibeVoice-tpu/src/vibevoice/modular/modular_vibevoice_text_tokenizer.py +214 -0
  30. VibeVoice-tpu/src/vibevoice/modular/modular_vibevoice_tokenizer.py +1195 -0
  31. VibeVoice-tpu/src/vibevoice/modular/streamer.py +264 -0
  32. VibeVoice-tpu/src/vibevoice/processor/__init__.py +0 -0
  33. VibeVoice-tpu/src/vibevoice/processor/__pycache__/__init__.cpython-311.pyc +0 -0
  34. VibeVoice-tpu/src/vibevoice/processor/__pycache__/vibevoice_processor.cpython-311.pyc +0 -0
  35. VibeVoice-tpu/src/vibevoice/processor/__pycache__/vibevoice_tokenizer_processor.cpython-311.pyc +0 -0
  36. VibeVoice-tpu/src/vibevoice/processor/preprocessor_config.json +13 -0
  37. VibeVoice-tpu/src/vibevoice/processor/vibevoice_processor.py +677 -0
  38. VibeVoice-tpu/src/vibevoice/processor/vibevoice_tokenizer_processor.py +483 -0
  39. VibeVoice-tpu/src/vibevoice/schedule/__init__.py +0 -0
  40. VibeVoice-tpu/src/vibevoice/schedule/__pycache__/__init__.cpython-311.pyc +0 -0
  41. VibeVoice-tpu/src/vibevoice/schedule/__pycache__/dpm_solver.cpython-311.pyc +0 -0
  42. VibeVoice-tpu/src/vibevoice/schedule/dpm_solver.py +1065 -0
  43. VibeVoice-tpu/src/vibevoice/schedule/timestep_sampler.py +19 -0
  44. VibeVoice-tpu/src/vibevoice/scripts/convert_nnscaler_checkpoint_to_transformers.py +166 -0
  45. VibeVoice-tpu/src/vibevoice_surgery_colab.ipynb +2156 -0
  46. VibeVoice-tpu/src/vibevoice_surgery_colab.py +1631 -0
VibeVoice-tpu/diff_head_layers.txt ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [0] noisy_images_proj.weight (shape: (3584, 64), trainable: True)
2
+ [1] cond_proj.weight (shape: (3584, 3584), trainable: True)
3
+ [2] t_embedder.mlp.0.weight (shape: (3584, 256), trainable: True)
4
+ [3] t_embedder.mlp.2.weight (shape: (3584, 3584), trainable: True)
5
+ [4] layers.0.ffn.gate_proj.weight (shape: (10752, 3584), trainable: True)
6
+ [5] layers.0.ffn.up_proj.weight (shape: (10752, 3584), trainable: True)
7
+ [6] layers.0.ffn.down_proj.weight (shape: (3584, 10752), trainable: True)
8
+ [7] layers.0.norm.weight (shape: (3584,), trainable: True)
9
+ [8] layers.0.adaLN_modulation.1.weight (shape: (10752, 3584), trainable: True)
10
+ [9] layers.1.ffn.gate_proj.weight (shape: (10752, 3584), trainable: True)
11
+ [10] layers.1.ffn.up_proj.weight (shape: (10752, 3584), trainable: True)
12
+ [11] layers.1.ffn.down_proj.weight (shape: (3584, 10752), trainable: True)
13
+ [12] layers.1.norm.weight (shape: (3584,), trainable: True)
14
+ [13] layers.1.adaLN_modulation.1.weight (shape: (10752, 3584), trainable: True)
15
+ [14] layers.2.ffn.gate_proj.weight (shape: (10752, 3584), trainable: True)
16
+ [15] layers.2.ffn.up_proj.weight (shape: (10752, 3584), trainable: True)
17
+ [16] layers.2.ffn.down_proj.weight (shape: (3584, 10752), trainable: True)
18
+ [17] layers.2.norm.weight (shape: (3584,), trainable: True)
19
+ [18] layers.2.adaLN_modulation.1.weight (shape: (10752, 3584), trainable: True)
20
+ [19] layers.3.ffn.gate_proj.weight (shape: (10752, 3584), trainable: True)
21
+ [20] layers.3.ffn.up_proj.weight (shape: (10752, 3584), trainable: True)
22
+ [21] layers.3.ffn.down_proj.weight (shape: (3584, 10752), trainable: True)
23
+ [22] layers.3.norm.weight (shape: (3584,), trainable: True)
24
+ [23] layers.3.adaLN_modulation.1.weight (shape: (10752, 3584), trainable: True)
25
+ [24] final_layer.linear.weight (shape: (64, 3584), trainable: True)
26
+ [25] final_layer.adaLN_modulation.1.weight (shape: (7168, 3584), trainable: True)
VibeVoice-tpu/pyproject.toml ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "vibevoice-finetuning"
3
+ version = "0.1.0"
4
+ description = "Open Source finetuning code for VibeVoice"
5
+ readme = "README.md"
6
+ requires-python = ">=3.8"
7
+ license = {file = "LICENSE"}
8
+ authors = [
9
+ {name = "jpgallegoarvpb", email = "juanpablo.gallego@voicepowered.ai"}
10
+ ]
11
+ dependencies = [
12
+ "numpy~=1.26.0",
13
+ "resampy==0.4.3",
14
+ "librosa==0.11.0",
15
+ "s3tokenizer",
16
+ "torch",
17
+ "torchaudio",
18
+ "transformers",
19
+ "datasets>=2.18.0",
20
+ "diffusers==0.29.0",
21
+ "resemble-perth==1.0.1",
22
+ "omegaconf==2.3.0",
23
+ "conformer==0.3.2",
24
+ "safetensors==0.5.3",
25
+ "peft>=0.11.0",
26
+ "tensorboard>=2.12",
27
+ "wandb"
28
+ ]
29
+
30
+ [build-system]
31
+ requires = ["setuptools>=61.0"]
32
+ build-backend = "setuptools.build_meta"
33
+
34
+ [tool.setuptools.packages.find]
35
+ where = ["src"]
VibeVoice-tpu/src/TPU_SETUP.md ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # VibeVoice Fine-Tuning on TPU v5e-8 — Setup Guide
2
+
3
+ ## Overview
4
+
5
+ This guide explains how to set up and run VibeVoice fine-tuning on Google Cloud TPU v5e-8.
6
+ The training code uses PyTorch/XLA with bfloat16 precision and a custom training loop.
7
+
8
+ ## Prerequisites
9
+
10
+ - Google Cloud account with TPU v5e access
11
+ - A preprocessed dataset directory containing `.pt` files
12
+ - A VibeVoice model directory (optionally with surgery module)
13
+
14
+ ## 1. Create a TPU v5e-8 VM
15
+
16
+ ```bash
17
+ # Set your project
18
+ export PROJECT_ID=your-project-id
19
+ export ZONE=us-central1-b # TPU v5e available zones
20
+ export VM_NAME=vibevoice-tpu
21
+
22
+ # Create a Cloud TPU v5e-8 VM
23
+ gcloud compute tpus tpu-vm create $VM_NAME \
24
+ --zone=$ZONE \
25
+ --accelerator-type=v5e-8 \
26
+ --version=tpu-ubuntu2204-base \
27
+ --project=$PROJECT_ID
28
+ ```
29
+
30
+ ## 2. SSH into the TPU VM
31
+
32
+ ```bash
33
+ gcloud compute tpus tpu-vm ssh $VM_NAME --zone=$ZONE --project=$PROJECT_ID
34
+ ```
35
+
36
+ ## 3. Install Dependencies
37
+
38
+ ```bash
39
+ # Update system
40
+ sudo apt-get update && sudo apt-get upgrade -y
41
+
42
+ # Install Python 3.10+ if needed
43
+ sudo apt-get install -y python3.10 python3.10-venv python3-pip
44
+
45
+ # Create virtual environment
46
+ python3 -m venv ~/vibevoice-env
47
+ source ~/vibevoice-env/bin/activate
48
+
49
+ # Install PyTorch/XLA (CRITICAL: must match TPU version)
50
+ pip install torch~=2.5.0
51
+ pip install torch_xla[tpu]~=2.5.0 -f https://storage.googleapis.com/libtpu-releases/index.html
52
+
53
+ # Install transformers and PEFT
54
+ pip install transformers>=4.45.0
55
+ pip install peft>=0.7.0
56
+ pip install datasets
57
+ pip install accelerate
58
+ pip install sentencepiece
59
+ pip install protobuf
60
+
61
+ # Install additional dependencies
62
+ pip install numpy
63
+ pip install tqdm
64
+ pip install librosa # For audio loading (optional with preprocessed data)
65
+
66
+ # Verify TPU is available
67
+ python3 -c "
68
+ import torch_xla.core.xla_model as xm
69
+ device = xm.xla_device()
70
+ print(f'TPU device: {device}')
71
+ print(f'World size: {xm.xrt_world_size()}')
72
+ print('✅ TPU is available!')
73
+ "
74
+ ```
75
+
76
+ ## 4. Transfer Data and Model
77
+
78
+ ### Option A: GCS Bucket (Recommended)
79
+
80
+ ```bash
81
+ # Upload your model and data to GCS
82
+ gsutil -m cp -r /path/to/surgery_model gs://your-bucket/models/vibevoice_surgery/
83
+ gsutil -m cp -r /path/to/preprocessed_data gs://your-bucket/data/preprocessed/
84
+
85
+ # Data can be accessed directly from GCS in the training script
86
+ # or download to local disk first:
87
+ mkdir -p ~/data ~/models
88
+ gsutil -m cp -r gs://your-bucket/data/preprocessed/* ~/data/
89
+ gsutil -m cp -r gs://your-bucket/models/vibevoice_surgery/* ~/models/
90
+ ```
91
+
92
+ ### Option B: Direct Transfer
93
+
94
+ ```bash
95
+ # From your local machine, transfer files to the TPU VM
96
+ gcloud compute tpus tpu-vm scp \
97
+ /path/to/preprocessed_data $VM_NAME:~/data/ \
98
+ --zone=$ZONE --project=$PROJECT_ID --recurse
99
+
100
+ gcloud compute tpus tpu-vm scp \
101
+ /path/to/surgery_model $VM_NAME:~/models/vibevoice_surgery/ \
102
+ --zone=$ZONE --project=$PROJECT_ID --recurse
103
+ ```
104
+
105
+ ## 5. Transfer Training Code
106
+
107
+ ```bash
108
+ # Transfer the training scripts
109
+ gcloud compute tpus tpu-vm scp \
110
+ /path/to/VibeVoice/src/finetune_vibevoice_tpu.py $VM_NAME:~/finetune_vibevoice_tpu.py \
111
+ --zone=$ZONE --project=$PROJECT_ID
112
+
113
+ gcloud compute tpus tpu-vm scp \
114
+ /path/to/VibeVoice/src/tpu_config.py $VM_NAME:~/tpu_config.py \
115
+ --zone=$ZONE --project=$PROJECT_ID
116
+
117
+ # Transfer the vibevoice package
118
+ gcloud compute tpus tpu-vm scp \
119
+ /path/to/VibeVoice/src/vibevoice $VM_NAME:~/vibevoice/ \
120
+ --zone=$ZONE --project=$PROJECT_ID --recurse
121
+
122
+ # Transfer surgery colab (if using surgery model)
123
+ gcloud compute tpus tpu-vm scp \
124
+ /path/to/VibeVoice/src/vibevoice_surgery_colab.py $VM_NAME:~/vibevoice_surgery_colab.py \
125
+ --zone=$ZONE --project=$PROJECT_ID
126
+ ```
127
+
128
+ ## 6. Run Training
129
+
130
+ ### Basic Usage
131
+
132
+ ```bash
133
+ cd ~
134
+ source ~/vibevoice-env/bin/activate
135
+
136
+ python3 finetune_vibevoice_tpu.py \
137
+ --model_name_or_path ~/models/vibevoice_surgery \
138
+ --preprocessed_dir ~/data \
139
+ --output_dir ~/output_tpu \
140
+ --max_steps 5000 \
141
+ --learning_rate 2e-5 \
142
+ --gradient_accumulation_steps 8 \
143
+ --logging_steps 10 \
144
+ --save_steps 500
145
+ ```
146
+
147
+ ### Full Configuration
148
+
149
+ ```bash
150
+ python3 finetune_vibevoice_tpu.py \
151
+ --model_name_or_path ~/models/vibevoice_surgery \
152
+ --preprocessed_dir ~/data \
153
+ --output_dir ~/output_tpu \
154
+ --max_steps 5000 \
155
+ --num_train_epochs 3 \
156
+ --learning_rate 2e-5 \
157
+ --lr_scheduler_type cosine \
158
+ --warmup_steps 100 \
159
+ --per_device_train_batch_size 1 \
160
+ --gradient_accumulation_steps 8 \
161
+ --max_grad_norm 1.0 \
162
+ --gradient_checkpointing \
163
+ --ce_loss_weight 1.0 \
164
+ --diffusion_loss_weight 1.0 \
165
+ --ddpm_batch_mul 1 \
166
+ --lora_r 8 \
167
+ --lora_alpha 32 \
168
+ --lora_dropout 0.05 \
169
+ --lora_target_modules "q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj" \
170
+ --train_connectors \
171
+ --train_surgery_module \
172
+ --no_freeze_llm \
173
+ --freeze_diffusion_head \
174
+ --freeze_lm_head \
175
+ --ema_decay 0.999 \
176
+ --logging_steps 10 \
177
+ --eval_steps 500 \
178
+ --save_steps 500 \
179
+ --save_total_limit 3 \
180
+ --eval_split_size 0.05 \
181
+ --seed 42
182
+ ```
183
+
184
+ ### Resume from Checkpoint
185
+
186
+ ```bash
187
+ python3 finetune_vibevoice_tpu.py \
188
+ --model_name_or_path ~/models/vibevoice_surgery \
189
+ --preprocessed_dir ~/data \
190
+ --output_dir ~/output_tpu \
191
+ --resume_from_checkpoint ~/output_tpu/checkpoint-2000 \
192
+ --max_steps 5000
193
+ ```
194
+
195
+ ## 7. Monitor Training
196
+
197
+ ```bash
198
+ # View training logs in real-time
199
+ tail -f ~/output_tpu/training.log
200
+
201
+ # Check TPU utilization
202
+ pip install cloud-tpu-diagnostics
203
+ python3 -c "
204
+ import torch_xla.core.xla_model as xm
205
+ print(f'Device: {xm.xla_device()}')
206
+ print(f'Ordinal: {xm.get_ordinal()}')
207
+ print(f'World size: {xm.xrt_world_size()}')
208
+ "
209
+ ```
210
+
211
+ ## 8. Retrieve Results
212
+
213
+ ```bash
214
+ # Copy output back to local machine
215
+ gcloud compute tpus tpu-vm scp \
216
+ $VM_NAME:~/output_tpu/ /local/path/to/output/ \
217
+ --zone=$ZONE --project=$PROJECT_ID --recurse
218
+
219
+ # Or upload to GCS
220
+ gsutil -m cp -r ~/output_tpu gs://your-bucket/outputs/vibevoice_tpu/
221
+ ```
222
+
223
+ ## Key Differences from GPU Training
224
+
225
+ | Aspect | GPU (T4/A100) | TPU v5e-8 |
226
+ |--------|---------------|-----------|
227
+ | Framework | PyTorch + CUDA | PyTorch/XLA |
228
+ | Precision | fp16 / bf16 | bf16 (native) |
229
+ | Training Loop | HF Trainer | Custom loop |
230
+ | Data Loading | DataLoader | MpDeviceLoader |
231
+ | Sync | NCCL all-reduce | xm.optimizer_step() |
232
+ | Graph | Dynamic | XLA compiled (static) |
233
+ | Memory | 16-80 GB/chip | 16 GB/chip × 8 |
234
+ | Batch Sync | Automatic | xm.mark_step() |
235
+
236
+ ## Memory Budget (per TPU chip)
237
+
238
+ | Component | bf16 Size |
239
+ |-----------|-----------|
240
+ | LLM (Qwen3-4B) | ~8 GB |
241
+ | Diffusion Head | ~2 GB |
242
+ | Tokenizers | ~1 GB |
243
+ | LM Head | ~0.3 GB |
244
+ | **Model Total** | **~12 GB** |
245
+ | Gradients | ~0.5 GB |
246
+ | Optimizer | ~1 GB |
247
+ | Activations | ~2 GB |
248
+ | **Total** | **~15.5 GB** |
249
+ | **Available** | **16 GB** |
250
+
251
+ ## Troubleshooting
252
+
253
+ ### XLA Compilation Errors
254
+ ```bash
255
+ # Clear XLA cache
256
+ rm -rf /tmp/xla_cache
257
+
258
+ # Set environment variables
259
+ export XLA_USE_BF16=1
260
+ export PJRT_DEVICE=TPU
261
+ ```
262
+
263
+ ### Out of Memory
264
+ ```bash
265
+ # Reduce per-device batch size
266
+ --per_device_train_batch_size 1
267
+
268
+ # Increase gradient accumulation (keeps effective batch)
269
+ --gradient_accumulation_steps 16
270
+
271
+ # Enable gradient checkpointing
272
+ --gradient_checkpointing
273
+
274
+ # Freeze more components
275
+ --freeze_diffusion_head
276
+ --lora_wrap_diffusion_head
277
+ ```
278
+
279
+ ### Slow First Step
280
+ The first training step is always slow on TPU due to XLA compilation.
281
+ Subsequent steps will be significantly faster. This is normal behavior.
282
+
283
+ ### Process Hangs
284
+ ```bash
285
+ # Check TPU health
286
+ python3 -c "
287
+ import torch_xla.core.xla_model as xm
288
+ device = xm.xla_device()
289
+ t = xm.send_cpu_data_to_device([1,2,3], device)
290
+ print('TPU communication OK')
291
+ "
292
+ ```
293
+
294
+ ## Performance Tips
295
+
296
+ 1. **Prefetch Data**: Ensure data is on local SSD, not GCS streaming
297
+ 2. **Batch Size**: Use batch_size=1 per chip with gradient_accumulation=8
298
+ 3. **Gradient Checkpointing**: Always enable for 16GB chips
299
+ 4. **XLA Cache**: Set `XLA_PERSISTENT_CACHE_PATH` for faster compilation on restarts
300
+ 5. **Data Format**: Preprocessed `.pt` files are fastest (no CPU preprocessing)
301
+ 6. **EMA**: EMA runs on CPU to save TPU memory (small overhead per step)
302
+
303
+ ## Effective Batch Size Calculation
304
+
305
+ ```
306
+ effective_batch = per_device_batch × num_chips × gradient_accumulation
307
+ = 1 × 8 × 8 = 64
308
+ ```
309
+
310
+ Adjust `gradient_accumulation_steps` to reach your target batch size.
VibeVoice-tpu/src/data_vibevoice.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from dataclasses import dataclass
3
+ from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
4
+
5
+ import numpy as np
6
+ import torch
7
+ import warnings
8
+ import random
9
+
10
+ try:
11
+ import librosa # type: ignore
12
+ except Exception: # pragma: no cover
13
+ librosa = None # Fallback: user must install librosa when using local audio paths
14
+
15
+ try:
16
+ import resampy # type: ignore
17
+ except Exception: # pragma: no cover
18
+ resampy = None
19
+
20
+
21
+ def _resample_if_needed(wav: np.ndarray, orig_sr: int, target_sr: int) -> np.ndarray:
22
+ if orig_sr == target_sr:
23
+ return wav.astype(np.float32, copy=False)
24
+ if resampy is not None:
25
+ return resampy.resample(wav.astype(np.float32), orig_sr, target_sr)
26
+ if librosa is not None:
27
+ return librosa.resample(y=wav.astype(np.float32), orig_sr=orig_sr, target_sr=target_sr)
28
+ warnings.warn(
29
+ "No resampler available; treating audio as target_sr without resampling. Install resampy or librosa.",
30
+ RuntimeWarning,
31
+ )
32
+ return wav.astype(np.float32, copy=False)
33
+
34
+
35
+ # Lightweight HF-style dataset wrapper (optional). Trainer can also pass raw HF datasets directly.
36
+ class VibeVoiceDataset:
37
+ def __init__(
38
+ self,
39
+ dataset: Any,
40
+ text_column: str = "text",
41
+ audio_column: str = "audio",
42
+ voice_prompts_column: Optional[str] = "voice_prompts",
43
+ ) -> None:
44
+ self.dataset = dataset
45
+ self.text_column = text_column
46
+ self.audio_column = audio_column
47
+ self.voice_prompts_column = voice_prompts_column
48
+
49
+ def __len__(self) -> int:
50
+ return len(self.dataset)
51
+
52
+ def __getitem__(self, idx: int) -> Dict[str, Any]:
53
+ item = self.dataset[idx]
54
+ data: Dict[str, Any] = {}
55
+ data["text"] = item[self.text_column]
56
+ data["audio"] = item[self.audio_column]
57
+
58
+ user_provided_prompt = None
59
+ if self.voice_prompts_column and self.voice_prompts_column in item:
60
+ user_provided_prompt = item[self.voice_prompts_column]
61
+
62
+ if user_provided_prompt:
63
+ # A prompt was provided in the dataset, so we use it.
64
+ if not isinstance(user_provided_prompt, list):
65
+ data["voice_prompts"] = [user_provided_prompt]
66
+ else:
67
+ data["voice_prompts"] = user_provided_prompt
68
+ else:
69
+ # FALLBACK: No prompt provided, so we auto-generate one from the target audio.
70
+ try:
71
+ target_sr = 24000
72
+ wav_array = _load_audio_to_24k(item[self.audio_column], target_sr=target_sr)
73
+ audio_len_seconds = len(wav_array) / target_sr
74
+
75
+ min_len_sec = min(5.0, audio_len_seconds / 4.0)
76
+ max_len_sec = min(15.0, audio_len_seconds / 2.0)
77
+
78
+ if min_len_sec > max_len_sec:
79
+ min_len_sec = max_len_sec
80
+ max_len_sec = min(max_len_sec, audio_len_seconds)
81
+
82
+ if max_len_sec > 0.1:
83
+ prompt_len_sec = random.uniform(min_len_sec, max_len_sec)
84
+ prompt_len_samples = int(prompt_len_sec * target_sr)
85
+
86
+ max_start_sample = len(wav_array) - prompt_len_samples
87
+ start_sample = random.randint(0, max_start_sample)
88
+
89
+ prompt_crop = wav_array[start_sample : start_sample + prompt_len_samples]
90
+
91
+ data["voice_prompts"] = [prompt_crop]
92
+ else:
93
+ data["voice_prompts"] = None
94
+
95
+ except Exception as e:
96
+ warnings.warn(f"Could not create voice prompt for item {idx}: {e}")
97
+ data["voice_prompts"] = None
98
+ return data
99
+
100
+
101
+ def _apply_silence_with_crossfade(
102
+ wav: np.ndarray,
103
+ *,
104
+ sample_rate: int,
105
+ pre_silence_sec: float = 0.25,
106
+ pre_crossfade_sec: float = 0.25,
107
+ post_crossfade_sec: float = 0.25,
108
+ post_silence_sec: float = 0.75,
109
+ ) -> np.ndarray:
110
+ """Pad audio with leading/trailing silence and apply crossfades.
111
+
112
+ Structure: [pre_silence][pre_crossfade][audio_body][post_crossfade][post_silence]
113
+ Crossfades blend the audio with silence linearly to avoid hard edges.
114
+ """
115
+
116
+ wav = np.asarray(wav, dtype=np.float32).reshape(-1)
117
+
118
+ start_sil_samples = int(round(pre_silence_sec * sample_rate))
119
+ end_sil_samples = int(round(post_silence_sec * sample_rate))
120
+ pre_crossfade_samples = int(round(pre_crossfade_sec * sample_rate))
121
+ post_crossfade_samples = int(round(post_crossfade_sec * sample_rate))
122
+
123
+ total_len = wav.shape[0]
124
+ if total_len == 0:
125
+ pieces: List[np.ndarray] = []
126
+ if start_sil_samples > 0:
127
+ pieces.append(np.zeros(start_sil_samples, dtype=np.float32))
128
+ if end_sil_samples > 0:
129
+ pieces.append(np.zeros(end_sil_samples, dtype=np.float32))
130
+ return np.concatenate(pieces) if pieces else wav
131
+
132
+ start_len = min(pre_crossfade_samples, total_len)
133
+ remaining_after_start = max(total_len - start_len, 0)
134
+ end_len = min(post_crossfade_samples, remaining_after_start)
135
+ middle_end_idx = total_len - end_len
136
+
137
+ start_segment = wav[:start_len]
138
+ middle_segment = wav[start_len:middle_end_idx]
139
+ end_segment = wav[middle_end_idx:]
140
+
141
+ def _linear_fade(num_samples: int, start: float, end: float) -> np.ndarray:
142
+ if num_samples <= 0:
143
+ return np.zeros((0,), dtype=np.float32)
144
+ return np.linspace(start, end, num_samples, endpoint=True, dtype=np.float32)
145
+
146
+ start_crossfade = start_segment * _linear_fade(start_len, 0.0, 1.0)
147
+ end_crossfade = end_segment * _linear_fade(end_segment.shape[0], 1.0, 0.0)
148
+
149
+ pieces: List[np.ndarray] = []
150
+ if start_sil_samples > 0:
151
+ pieces.append(np.zeros(start_sil_samples, dtype=np.float32))
152
+ if start_crossfade.size > 0:
153
+ pieces.append(start_crossfade.astype(np.float32, copy=False))
154
+ if middle_segment.size > 0:
155
+ pieces.append(middle_segment.astype(np.float32, copy=False))
156
+ if end_crossfade.size > 0:
157
+ pieces.append(end_crossfade.astype(np.float32, copy=False))
158
+ if end_sil_samples > 0:
159
+ pieces.append(np.zeros(end_sil_samples, dtype=np.float32))
160
+
161
+ return np.concatenate(pieces)
162
+
163
+
164
+ def _load_audio_to_24k(
165
+ audio: Union[str, np.ndarray, torch.Tensor, Dict[str, Any]],
166
+ *,
167
+ target_sr: int = 24000,
168
+ augment_with_silence: bool = False,
169
+ ) -> np.ndarray:
170
+ if isinstance(audio, np.ndarray):
171
+ wav_out = audio.astype(np.float32)
172
+ elif isinstance(audio, torch.Tensor):
173
+ wav_out = audio.detach().cpu().float().numpy()
174
+ elif isinstance(audio, str):
175
+ if librosa is None:
176
+ raise RuntimeError("librosa is required to load audio file paths. Please pip install librosa.")
177
+ wav, sr = librosa.load(audio, sr=None, mono=True)
178
+ wav_out = _resample_if_needed(wav, int(sr), target_sr)
179
+ elif isinstance(audio, dict) and "array" in audio and "sampling_rate" in audio:
180
+ arr = np.asarray(audio["array"], dtype=np.float32)
181
+ sr = int(audio["sampling_rate"])
182
+ wav_out = _resample_if_needed(arr, sr, target_sr)
183
+ else:
184
+ raise ValueError(f"Unsupported audio type: {type(audio)}")
185
+
186
+ wav_out = np.asarray(wav_out, dtype=np.float32)
187
+
188
+ if augment_with_silence:
189
+ wav_out = _apply_silence_with_crossfade(wav_out, sample_rate=target_sr)
190
+
191
+ return wav_out
192
+
193
+
194
+ @dataclass
195
+ class VibeVoiceCollator:
196
+ processor: Any # VibeVoiceProcessor
197
+ max_length: Optional[int] = None
198
+ speech_compress_ratio: int = 3200
199
+ semantic_vae_dim: int = 128
200
+ compute_semantics: bool = False
201
+ debug_checks: bool = False
202
+
203
+ text_field: str = "text"
204
+ audio_field: str = "audio"
205
+ voice_prompts_field: str = "voice_prompts"
206
+ voice_prompt_drop_rate: float = 0.0
207
+
208
+ def __call__(self, features: Sequence[Dict[str, Any]]) -> Dict[str, Any]:
209
+ batch_size = len(features)
210
+
211
+ sample_input_ids: List[List[int]] = []
212
+ sample_attention_masks: List[List[int]] = []
213
+ sample_acoustic_input_masks: List[List[bool]] = []
214
+ sample_acoustic_loss_masks: List[List[bool]] = []
215
+
216
+ all_speech_waveforms: List[np.ndarray] = []
217
+ all_speech_latent_lengths: List[int] = []
218
+ per_segment_is_target: List[bool] = []
219
+
220
+ for ex in features:
221
+ text: str = ex.get(self.text_field, "")
222
+ voice_prompts: Optional[List[Union[str, np.ndarray, torch.Tensor]]] = ex.get(self.voice_prompts_field)
223
+ target_audio: Union[str, np.ndarray, torch.Tensor, Dict[str, Any]] = ex.get(self.audio_field)
224
+
225
+ # Clamp drop rate for safety
226
+ _drop_rate = self.voice_prompt_drop_rate
227
+ if _drop_rate < 0.0:
228
+ _drop_rate = 0.0
229
+ elif _drop_rate > 1.0:
230
+ _drop_rate = 1.0
231
+
232
+ proc = self.processor(
233
+ text=[text],
234
+ voice_samples=[voice_prompts] if voice_prompts is not None and random.random() >= _drop_rate else None,
235
+ padding=False,
236
+ truncation=False,
237
+ max_length=self.max_length,
238
+ return_tensors="pt",
239
+ )
240
+
241
+ ids = proc["input_ids"][0].tolist()
242
+ attn = proc.get("attention_mask", torch.ones_like(proc["input_ids"]))[0].tolist()
243
+ speech_input_mask = proc.get("speech_input_mask")
244
+ if speech_input_mask is None:
245
+ speech_input_mask = torch.zeros_like(proc["input_ids"], dtype=torch.bool)
246
+ speech_input_mask_list = speech_input_mask[0].tolist()
247
+
248
+ wav_target = _load_audio_to_24k(target_audio, target_sr=24000, augment_with_silence=True)
249
+ # Prefer exact frame count from acoustic tokenizer if available; fallback to compress ratio
250
+ target_latent_len = None
251
+ try:
252
+ acoustic_tok = getattr(self.processor, "acoustic_tokenizer", None)
253
+ if acoustic_tok is not None and hasattr(acoustic_tok, "encode"):
254
+ enc_out = acoustic_tok.encode(wav_target)
255
+ # Normalize various possible return formats to get time dimension
256
+ T = None
257
+ try:
258
+ # Direct array-like with shape (T, D) or (T,)
259
+ if hasattr(enc_out, "shape") and len(getattr(enc_out, "shape", [])) >= 1:
260
+ T = int(enc_out.shape[0])
261
+ else:
262
+ # Nested lists/tuples or ModelOutput-like
263
+ cand = enc_out
264
+ # Drill down a couple of levels safely
265
+ for _ in range(2):
266
+ if isinstance(cand, (list, tuple)) and len(cand) > 0:
267
+ cand = cand[0]
268
+ if hasattr(cand, "shape") and len(getattr(cand, "shape", [])) >= 1:
269
+ T = int(cand.shape[0])
270
+ except Exception:
271
+ T = None
272
+ if T is not None and T > 0:
273
+ target_latent_len = T
274
+ except Exception:
275
+ target_latent_len = None
276
+ if target_latent_len is None:
277
+ target_latent_len = max(1, int(math.ceil(len(wav_target) / float(self.speech_compress_ratio))))
278
+
279
+ speech_diff_id = self.processor.tokenizer.speech_diffusion_id
280
+ target_placeholders = [speech_diff_id] * target_latent_len
281
+
282
+ ids_extended = ids + target_placeholders
283
+ attn_extended = attn + [1] * target_latent_len
284
+
285
+ acoustic_input_mask = speech_input_mask_list + [True] * target_latent_len
286
+ acoustic_loss_mask = ([False] * len(speech_input_mask_list)) + [True] * target_latent_len
287
+
288
+ speech_end_id = self.processor.tokenizer.speech_end_id
289
+ ids_extended.append(speech_end_id)
290
+ attn_extended.append(1)
291
+ acoustic_input_mask.append(False)
292
+ acoustic_loss_mask.append(False)
293
+
294
+ # Ensure text decoding sees an explicit end-of-sequence token after speech output.
295
+ eos_token_id = getattr(self.processor.tokenizer, "eos_id", None)
296
+ if eos_token_id is None:
297
+ eos_token_id = getattr(self.processor.tokenizer, "eos_token_id", None)
298
+ if eos_token_id is not None and eos_token_id >= 0:
299
+ ids_extended.append(eos_token_id)
300
+ attn_extended.append(1)
301
+ acoustic_input_mask.append(False)
302
+ acoustic_loss_mask.append(False)
303
+
304
+ if self.max_length is not None and len(ids_extended) > self.max_length:
305
+ cut = len(ids_extended) - int(self.max_length)
306
+ leading_non_acoustic = 0
307
+ for v in acoustic_input_mask:
308
+ if v:
309
+ break
310
+ leading_non_acoustic += 1
311
+ if cut > leading_non_acoustic:
312
+ raise ValueError(
313
+ f"--max_length={self.max_length} would truncate into acoustic tokens. "
314
+ f"Needed cut={cut}, but only {leading_non_acoustic} leading non-acoustic tokens available. "
315
+ "Increase max_length or shorten text/voice-prompt preamble."
316
+ )
317
+ ids_extended = ids_extended[cut:]
318
+ attn_extended = attn_extended[cut:]
319
+ acoustic_input_mask = acoustic_input_mask[cut:]
320
+ acoustic_loss_mask = acoustic_loss_mask[cut:]
321
+
322
+ sample_input_ids.append(ids_extended)
323
+ sample_attention_masks.append(attn_extended)
324
+ sample_acoustic_input_masks.append(acoustic_input_mask)
325
+ sample_acoustic_loss_masks.append(acoustic_loss_mask)
326
+
327
+ voice_speeches = []
328
+ voice_latent_lengths = []
329
+ if proc.get("speech_tensors") is not None:
330
+ voice_np = proc["speech_tensors"].cpu().numpy()
331
+ voice_masks = proc["speech_masks"].cpu().numpy().astype(bool)
332
+ for seg_idx in range(voice_np.shape[0]):
333
+ voice_speeches.append(voice_np[seg_idx])
334
+ voice_latent_lengths.append(int(voice_masks[seg_idx].sum()))
335
+
336
+ all_speech_waveforms.extend(voice_speeches)
337
+ all_speech_latent_lengths.extend(voice_latent_lengths)
338
+ per_segment_is_target.extend([False] * len(voice_speeches))
339
+
340
+ all_speech_waveforms.append(wav_target)
341
+ all_speech_latent_lengths.append(target_latent_len)
342
+ per_segment_is_target.append(True)
343
+
344
+ max_seq_len = max(len(x) for x in sample_input_ids)
345
+ padded_input_ids = []
346
+ padded_attention_masks = []
347
+ padded_acoustic_input_masks = []
348
+ padded_acoustic_loss_masks = []
349
+ tok = self.processor.tokenizer
350
+ pad_token_id = getattr(tok, "pad_token_id", None)
351
+ if pad_token_id is None or pad_token_id < 0:
352
+ pad_token_id = getattr(tok, "eos_token_id", None)
353
+ if pad_token_id is None or pad_token_id < 0:
354
+ raise ValueError(
355
+ "Tokenizer has no pad_token_id or eos_token_id; please set one or pass a valid pad id."
356
+ )
357
+ for ids, attn, ain_mask, aloss_mask in zip(
358
+ sample_input_ids, sample_attention_masks, sample_acoustic_input_masks, sample_acoustic_loss_masks
359
+ ):
360
+ pad_len = max_seq_len - len(ids)
361
+ padded_input_ids.append(ids + [pad_token_id] * pad_len)
362
+ padded_attention_masks.append(attn + [0] * pad_len)
363
+ padded_acoustic_input_masks.append(ain_mask + [False] * pad_len)
364
+ padded_acoustic_loss_masks.append(aloss_mask + [False] * pad_len)
365
+
366
+ input_ids_tensor = torch.tensor(padded_input_ids, dtype=torch.long)
367
+ attention_mask_tensor = torch.tensor(padded_attention_masks, dtype=torch.long)
368
+ acoustic_input_mask_tensor = torch.tensor(padded_acoustic_input_masks, dtype=torch.bool)
369
+ acoustic_loss_mask_tensor = torch.tensor(padded_acoustic_loss_masks, dtype=torch.bool)
370
+
371
+ if all_speech_waveforms:
372
+ max_wave_len = max(w.shape[0] for w in all_speech_waveforms)
373
+ padded_speeches = np.zeros((len(all_speech_waveforms), max_wave_len), dtype=np.float32)
374
+ for i, w in enumerate(all_speech_waveforms):
375
+ L = w.shape[0]
376
+ padded_speeches[i, :L] = w
377
+
378
+ max_latent_len = max(all_speech_latent_lengths) if all_speech_latent_lengths else 1
379
+ speech_masks_np = np.zeros((len(all_speech_waveforms), max_latent_len), dtype=np.bool_)
380
+ for i, L_lat in enumerate(all_speech_latent_lengths):
381
+ speech_masks_np[i, :L_lat] = True
382
+
383
+ speech_tensors_tensor = torch.tensor(padded_speeches, dtype=torch.float32)
384
+ speech_masks_tensor = torch.tensor(speech_masks_np, dtype=torch.bool)
385
+
386
+ speeches_loss_input_np = np.zeros_like(speech_masks_np, dtype=np.bool_)
387
+ for i, is_target in enumerate(per_segment_is_target):
388
+ if is_target:
389
+ speeches_loss_input_np[i] = speech_masks_np[i]
390
+ speeches_loss_input_tensor = torch.tensor(speeches_loss_input_np, dtype=torch.bool)
391
+
392
+ # Semantic features
393
+ if self.compute_semantics and hasattr(self.processor, "semantic_tokenizer") and self.processor.semantic_tokenizer is not None:
394
+ sem_feats: List[np.ndarray] = []
395
+ for w in all_speech_waveforms:
396
+ try:
397
+ # Expect [T, D] where T ≈ ceil(len(w)/compress_ratio)
398
+ sem = self.processor.semantic_tokenizer.encode(w)
399
+ sem = np.asarray(sem, dtype=np.float32)
400
+ except Exception:
401
+ sem = np.zeros((0, self.semantic_vae_dim), dtype=np.float32)
402
+ if sem.ndim != 2:
403
+ raise RuntimeError(f"Semantic tokenizer returned unexpected shape {sem.shape}. Expect [T, D].")
404
+ L = sem.shape[0]
405
+ D = sem.shape[1]
406
+ if D != self.semantic_vae_dim:
407
+ if D < self.semantic_vae_dim:
408
+ pad_d = np.zeros((L, self.semantic_vae_dim - D), dtype=np.float32)
409
+ sem = np.concatenate([sem, pad_d], axis=1)
410
+ else:
411
+ sem = sem[:, : self.semantic_vae_dim]
412
+ if L < max_latent_len:
413
+ pad = np.zeros((max_latent_len - L, self.semantic_vae_dim), dtype=np.float32)
414
+ sem = np.concatenate([sem, pad], axis=0)
415
+ elif L > max_latent_len:
416
+ sem = sem[:max_latent_len]
417
+ sem_feats.append(sem.astype(np.float32))
418
+ speech_semantic_tensors = torch.tensor(np.stack(sem_feats, axis=0), dtype=torch.float32)
419
+ else:
420
+ # Semantic tokenizer unavailable while semantics are required for training.
421
+ # Raise to avoid silently degrading alignment with zeroed features.
422
+ raise RuntimeError(
423
+ "Semantic features are required but could not be computed. "
424
+ "Ensure processor.semantic_tokenizer is available or precompute and provide features."
425
+ )
426
+ else:
427
+ speech_tensors_tensor = None
428
+ speech_masks_tensor = None
429
+ speeches_loss_input_tensor = None
430
+ speech_semantic_tensors = None # No segments in batch
431
+
432
+ if self.debug_checks:
433
+ assert (input_ids_tensor >= 0).all(), "input_ids contains negative indices"
434
+ if speech_tensors_tensor is not None:
435
+ assert speech_tensors_tensor.dim() == 2, "Expected speech_tensors 2D [segments, samples]"
436
+
437
+ return {
438
+ "input_ids": input_ids_tensor,
439
+ "attention_mask": attention_mask_tensor,
440
+ "speech_tensors": speech_tensors_tensor,
441
+ "speech_masks": speech_masks_tensor,
442
+ "speech_semantic_tensors": speech_semantic_tensors,
443
+ "acoustic_input_mask": acoustic_input_mask_tensor,
444
+ "acoustic_loss_mask": acoustic_loss_mask_tensor,
445
+ "speeches_loss_input": speeches_loss_input_tensor,
446
+ }
VibeVoice-tpu/src/finetune_surgery_colab.ipynb ADDED
@@ -0,0 +1,1225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "gpuType": "T4"
8
+ },
9
+ "kernelspec": {
10
+ "name": "python3",
11
+ "display_name": "Python 3"
12
+ },
13
+ "language_info": {
14
+ "name": "python"
15
+ },
16
+ "accelerator": "GPU",
17
+ "gpuClass": "standard"
18
+ },
19
+ "cells": [
20
+ {
21
+ "cell_type": "markdown",
22
+ "metadata": {},
23
+ "source": [
24
+ "# 🎙️ VibeVoice Surgery — Fine-Tuning on 2× T4 GPUs\n",
25
+ "\n",
26
+ "## Overview\n",
27
+ "\n",
28
+ "This notebook fine-tunes the **VibeVoice surgery model** (Qwen3-4B backbone + Surgery Module) on Google Colab with **2× NVIDIA T4 GPUs**.\n",
29
+ "\n",
30
+ "### Model Architecture After Surgery\n",
31
+ "| Component | Dimensions | Notes |\n",
32
+ "|-----------|-----------|-------|\n",
33
+ "| Qwen3-4B LLM | 2560-dim, 36 layers | Language model backbone |\n",
34
+ "| Surgery Module | 2560 → 3584 | Bridging module for diffusion head |\n",
35
+ "| Diffusion Head | 3584-dim | DDPM-based speech generation |\n",
36
+ "| Acoustic Connector | 64 → 2560 | Acoustic latent → LLM space |\n",
37
+ "| Semantic Connector | 128 → 2560 | Semantic latent → LLM space |\n",
38
+ "\n",
39
+ "### Training Strategy (Phase-Based)\n",
40
+ "\n",
41
+ "**Phase 1** (this notebook): Due to limited VRAM on T4s:\n",
42
+ "- ❌ **FREEZE**: LLM (Qwen3-4B), Diffusion Head\n",
43
+ "- ✅ **TRAIN**: Surgery Module, Acoustic Connector, Semantic Connector\n",
44
+ "\n",
45
+ "**Phase 2** (optional, after Phase 1 convergence):\n",
46
+ "- ❌ **FREEZE**: LLM backbone (keep frozen)\n",
47
+ "- ✅ **TRAIN**: Surgery Module, Connectors, Diffusion Head (LoRA)\n",
48
+ "\n",
49
+ "---"
50
+ ]
51
+ },
52
+ {
53
+ "cell_type": "markdown",
54
+ "metadata": {},
55
+ "source": [
56
+ "## Cell 1: 🔧 Environment Setup & Dependencies"
57
+ ]
58
+ },
59
+ {
60
+ "cell_type": "code",
61
+ "metadata": {},
62
+ "source": [
63
+ "#@title 1.1 — Install Dependencies { display-mode: \"form\" }\n",
64
+ "import subprocess, sys\n",
65
+ "\n",
66
+ "def install(package):\n",
67
+ " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", package])\n",
68
+ "\n",
69
+ "# Core ML stack\n",
70
+ "install(\"torch>=2.1.0\")\n",
71
+ "install(\"transformers>=4.51.0\") # Qwen3Config support\n",
72
+ "install(\"peft>=0.11.0\") # LoRA\n",
73
+ "install(\"datasets>=2.19.0\")\n",
74
+ "install(\"accelerate>=0.30.0\")\n",
75
+ "install(\"safetensors>=0.4.0\")\n",
76
+ "\n",
77
+ "# Audio processing\n",
78
+ "install(\"librosa>=0.10.0\")\n",
79
+ "install(\"soundfile>=0.12.0\")\n",
80
+ "install(\"resampy>=0.4.0\")\n",
81
+ "\n",
82
+ "# Utilities\n",
83
+ "install(\"sentencepiece\")\n",
84
+ "install(\"protobuf\")\n",
85
+ "install(\"tensorboard\")\n",
86
+ "install(\"tqdm\")\n",
87
+ "\n",
88
+ "print(\"✅ All dependencies installed successfully!\")"
89
+ ],
90
+ "execution_count": null,
91
+ "outputs": []
92
+ },
93
+ {
94
+ "cell_type": "code",
95
+ "metadata": {},
96
+ "source": [
97
+ "#@title 1.2 — Verify GPU Setup { display-mode: \"form\" }\n",
98
+ "import torch\n",
99
+ "\n",
100
+ "print(\"=\" * 60)\n",
101
+ "print(\" GPU Configuration\")\n",
102
+ "print(\"=\" * 60)\n",
103
+ "print(f\" PyTorch version: {torch.__version__}\")\n",
104
+ "print(f\" CUDA available: {torch.cuda.is_available()}\")\n",
105
+ "print(f\" GPU count: {torch.cuda.device_count()}\")\n",
106
+ "for i in range(torch.cuda.device_count()):\n",
107
+ " props = torch.cuda.get_device_properties(i)\n",
108
+ " mem_gb = props.total_mem / (1024**3)\n",
109
+ " print(f\" GPU {i}: {props.name} | {mem_gb:.1f} GB VRAM | Compute {props.major}.{props.minor}\")\n",
110
+ "print(\"=\" * 60)\n",
111
+ "\n",
112
+ "assert torch.cuda.device_count() >= 1, \"❌ No GPU found! Go to Runtime > Change runtime type > T4 GPU\"\n",
113
+ "if torch.cuda.device_count() >= 2:\n",
114
+ " print(\"\\n✅ Dual GPU setup detected — DataParallel will be used.\")\n",
115
+ "else:\n",
116
+ " print(\"\\n⚠️ Single GPU detected — training will be slower but functional.\")"
117
+ ],
118
+ "execution_count": null,
119
+ "outputs": []
120
+ },
121
+ {
122
+ "cell_type": "markdown",
123
+ "metadata": {},
124
+ "source": [
125
+ "## Cell 2: 📁 Project Setup & Model Paths"
126
+ ]
127
+ },
128
+ {
129
+ "cell_type": "code",
130
+ "metadata": {},
131
+ "source": [
132
+ "#@title 2.1 — Configure Paths { display-mode: \"form\" }\n",
133
+ "import os\n",
134
+ "\n",
135
+ "# ══════════════════════════════════════════════════════════\n",
136
+ "# CONFIGURE THESE PATHS FOR YOUR SETUP\n",
137
+ "# ══════════════════════════════════════════════════════════\n",
138
+ "\n",
139
+ "# Path to the surgery model directory (output of vibevoice_surgery_colab.py)\n",
140
+ "# On Google Colab, upload to /content/drive/MyDrive/... or /content/...\n",
141
+ "SURGERY_MODEL_PATH = \"/content/vibevoice_qwen3_surgery\" #@param {type:\"string\"}\n",
142
+ "\n",
143
+ "# Path to your training JSONL file\n",
144
+ "# Format: {\"text\": \"...\", \"audio\": \"/path/to/audio.wav\"}\n",
145
+ "TRAIN_JSONL_PATH = \"/content/train.jsonl\" #@param {type:\"string\"}\n",
146
+ "\n",
147
+ "# Optional: Path to validation JSONL\n",
148
+ "VALIDATION_JSONL_PATH = \"\" #@param {type:\"string\"}\n",
149
+ "\n",
150
+ "# Path to the VibeVoice source code\n",
151
+ "# You need vibevoice/, vibevoice_surgery_colab.py, data_vibevoice.py\n",
152
+ "PROJECT_DIR = \"/content/VibeVoice\" #@param {type:\"string\"}\n",
153
+ "\n",
154
+ "# Output directory for trained artifacts\n",
155
+ "OUTPUT_DIR = \"/content/vibevoice_finetuned\" #@param {type:\"string\"}\n",
156
+ "\n",
157
+ "# ══════════════════════════════════════════════════════════\n",
158
+ "\n",
159
+ "# Validation\n",
160
+ "if not os.path.exists(SURGERY_MODEL_PATH):\n",
161
+ " print(f\"⚠️ Surgery model not found at: {SURGERY_MODEL_PATH}\")\n",
162
+ " print(f\" Please upload the surgery model or update the path.\")\n",
163
+ " print(f\" Expected files: config.json, model.safetensors, etc.\")\n",
164
+ "\n",
165
+ "if not os.path.exists(TRAIN_JSONL_PATH):\n",
166
+ " print(f\"⚠️ Training JSONL not found at: {TRAIN_JSONL_PATH}\")\n",
167
+ " print(f\" Please upload or update the path.\")\n",
168
+ "\n",
169
+ "print(f\"\\n📁 Configuration:\")\n",
170
+ "print(f\" Surgery Model: {SURGERY_MODEL_PATH}\")\n",
171
+ "print(f\" Train JSONL: {TRAIN_JSONL_PATH}\")\n",
172
+ "print(f\" Validation: {VALIDATION_JSONL_PATH or '(none)'}\")\n",
173
+ "print(f\" Project Dir: {PROJECT_DIR}\")\n",
174
+ "print(f\" Output Dir: {OUTPUT_DIR}\")"
175
+ ],
176
+ "execution_count": null,
177
+ "outputs": []
178
+ },
179
+ {
180
+ "cell_type": "code",
181
+ "metadata": {},
182
+ "source": [
183
+ "#@title 2.2 — Clone or Link Project { display-mode: \"form\" }\n",
184
+ "\n",
185
+ "import os, sys\n",
186
+ "\n",
187
+ "# Option A: If project is in a Git repo\n",
188
+ "GIT_REPO_URL = \"\" #@param {type:\"string\"}\n",
189
+ "\n",
190
+ "if GIT_REPO_URL and not os.path.exists(PROJECT_DIR):\n",
191
+ " !git clone {GIT_REPO_URL} {PROJECT_DIR}\n",
192
+ " print(f\"✅ Cloned project from {GIT_REPO_URL}\")\n",
193
+ "elif not os.path.exists(PROJECT_DIR):\n",
194
+ " os.makedirs(PROJECT_DIR, exist_ok=True)\n",
195
+ " print(f\"⚠️ Created empty project dir at {PROJECT_DIR}\")\n",
196
+ " print(f\" Please upload vibevoice/, vibevoice_surgery_colab.py, data_vibevoice.py, finetune_surgery_t4.py\")\n",
197
+ "else:\n",
198
+ " print(f\"✅ Project dir exists: {PROJECT_DIR}\")\n",
199
+ "\n",
200
+ "# Add to Python path\n",
201
+ "if PROJECT_DIR not in sys.path:\n",
202
+ " sys.path.insert(0, PROJECT_DIR)\n",
203
+ "\n",
204
+ "# Verify critical files\n",
205
+ "required_files = [\n",
206
+ " \"vibevoice/modular/modeling_vibevoice.py\",\n",
207
+ " \"vibevoice/modular/configuration_vibevoice.py\",\n",
208
+ " \"vibevoice_surgery_colab.py\",\n",
209
+ " \"data_vibevoice.py\",\n",
210
+ " \"finetune_surgery_t4.py\",\n",
211
+ "]\n",
212
+ "missing = [f for f in required_files if not os.path.exists(os.path.join(PROJECT_DIR, f))]\n",
213
+ "if missing:\n",
214
+ " print(f\"\\n❌ Missing required files:\")\n",
215
+ " for f in missing:\n",
216
+ " print(f\" - {f}\")\n",
217
+ "else:\n",
218
+ " print(f\"\\n✅ All required project files found!\")"
219
+ ],
220
+ "execution_count": null,
221
+ "outputs": []
222
+ },
223
+ {
224
+ "cell_type": "markdown",
225
+ "metadata": {},
226
+ "source": [
227
+ "## Cell 3: 📊 Dataset Preparation"
228
+ ]
229
+ },
230
+ {
231
+ "cell_type": "code",
232
+ "metadata": {},
233
+ "source": [
234
+ "#@title 3.1 — Preview / Prepare Training Data { display-mode: \"form\" }\n",
235
+ "\n",
236
+ "import json, os\n",
237
+ "\n",
238
+ "def preview_jsonl(path, n=5):\n",
239
+ " \"\"\"Preview the first N samples of a JSONL file.\"\"\"\n",
240
+ " if not os.path.exists(path):\n",
241
+ " print(f\"❌ File not found: {path}\")\n",
242
+ " return\n",
243
+ " \n",
244
+ " print(f\"📄 Previewing: {path}\")\n",
245
+ " print(f\" File size: {os.path.getsize(path) / 1024 / 1024:.2f} MB\")\n",
246
+ " \n",
247
+ " count = 0\n",
248
+ " with open(path, 'r', encoding='utf-8') as f:\n",
249
+ " for i, line in enumerate(f):\n",
250
+ " if not line.strip():\n",
251
+ " continue\n",
252
+ " try:\n",
253
+ " sample = json.loads(line)\n",
254
+ " count += 1\n",
255
+ " if i < n:\n",
256
+ " text = sample.get('text', 'N/A')[:100]\n",
257
+ " audio = sample.get('audio', 'N/A')\n",
258
+ " has_vp = 'voice_prompts' in sample\n",
259
+ " print(f\"\\n Sample {i}:\")\n",
260
+ " print(f\" Text: {text}...\" if len(text) > 100 else f\" Text: {text}\")\n",
261
+ " print(f\" Audio: {audio}\")\n",
262
+ " print(f\" Voice Prompts: {'Yes' if has_vp else 'No (auto-generated)'}\")\n",
263
+ " except json.JSONDecodeError:\n",
264
+ " print(f\" ⚠️ Line {i}: Invalid JSON\")\n",
265
+ " \n",
266
+ " print(f\"\\n Total samples: {count}\")\n",
267
+ "\n",
268
+ "preview_jsonl(TRAIN_JSONL_PATH)\n",
269
+ "if VALIDATION_JSONL_PATH:\n",
270
+ " preview_jsonl(VALIDATION_JSONL_PATH)"
271
+ ],
272
+ "execution_count": null,
273
+ "outputs": []
274
+ },
275
+ {
276
+ "cell_type": "markdown",
277
+ "metadata": {},
278
+ "source": [
279
+ "## Cell 4: 🧊 Configure Freezing Strategy\n",
280
+ "\n",
281
+ "This is the **most important cell**. You choose exactly which layers to freeze and which to train.\n",
282
+ "\n",
283
+ "### Layer Groups\n",
284
+ "\n",
285
+ "| Layer Group | Parameters (approx) | Memory Impact | Description |\n",
286
+ "|-------------|--------------------|--------------:|-------------|\n",
287
+ "| **LLM (Qwen3-4B)** | ~4B | ~8 GB fp16 | Language model backbone |\n",
288
+ "| **Diffusion Head** | ~107M | ~214 MB fp16 | DDPM denoiser |\n",
289
+ "| **Surgery Module** | ~26M | ~52 MB fp16 | 2560→3584 bridge |\n",
290
+ "| **Acoustic Connector** | ~0.1M | ~0.2 MB fp16 | 64→2560 projection |\n",
291
+ "| **Semantic Connector** | ~0.3M | ~0.6 MB fp16 | 128→2560 projection |\n",
292
+ "| **LM Head** | ~388M | ~776 MB fp16 | Tied to embeddings (frozen) |\n",
293
+ "\n",
294
+ "### Recommended Phase 1 Strategy (T4 VRAM constrained)\n",
295
+ "Freeze **LLM + Diffusion Head + LM Head**, train **Surgery Module + Connectors**"
296
+ ]
297
+ },
298
+ {
299
+ "cell_type": "code",
300
+ "metadata": {},
301
+ "source": [
302
+ "#@title 4.1 — Layer Freezing Configuration { display-mode: \"form\" }\n",
303
+ "\n",
304
+ "# ══════════════════════════════════════════════════════════\n",
305
+ "# FREEZING STRATEGY — Choose what to freeze/train\n",
306
+ "# ══════════════════════════════════════════════════════════\n",
307
+ "\n",
308
+ "FREEZE_LLM = True #@param {type:\"boolean\"}\n",
309
+ "FREEZE_DIFFUSION_HEAD = True #@param {type:\"boolean\"}\n",
310
+ "FREEZE_SURGERY_MODULE = False #@param {type:\"boolean\"}\n",
311
+ "FREEZE_CONNECTORS = False #@param {type:\"boolean\"}\n",
312
+ "FREEZE_LM_HEAD = True #@param {type:\"boolean\"}\n",
313
+ "FREEZE_ACOUSTIC_TOKENIZER = True #@param {type:\"boolean\"}\n",
314
+ "FREEZE_SEMANTIC_TOKENIZER = True #@param {type:\"boolean\"}\n",
315
+ "\n",
316
+ "# ── LoRA Settings ──\n",
317
+ "# Only used if LLM is NOT frozen\n",
318
+ "USE_LORA_ON_LLM = False #@param {type:\"boolean\"}\n",
319
+ "LORA_R = 8 #@param {type:\"integer\"}\n",
320
+ "LORA_ALPHA = 32 #@param {type:\"integer\"}\n",
321
+ "LORA_DROPOUT = 0.05 #@param {type:\"float\"}\n",
322
+ "\n",
323
+ "# If LLM is frozen, force-disable LoRA\n",
324
+ "if FREEZE_LLM:\n",
325
+ " USE_LORA_ON_LLM = False\n",
326
+ " LORA_TARGET_MODULES = \"none\"\n",
327
+ "else:\n",
328
+ " LORA_TARGET_MODULES = \"q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj\" if USE_LORA_ON_LLM else \"none\"\n",
329
+ "\n",
330
+ "# ── Diffusion Head LoRA (optional) ──\n",
331
+ "LORA_WRAP_DIFFUSION_HEAD = False #@param {type:\"boolean\"}\n",
332
+ "TRAIN_DIFFUSION_HEAD = False #@param {type:\"boolean\"}\n",
333
+ "\n",
334
+ "# ── Print Summary ──\n",
335
+ "print(\"=\" * 60)\n",
336
+ "print(\" Freezing Strategy\")\n",
337
+ "print(\"=\" * 60)\n",
338
+ "components = [\n",
339
+ " (\"LLM (Qwen3-4B)\", FREEZE_LLM, \"~4B params\"),\n",
340
+ " (\"Diffusion Head\", FREEZE_DIFFUSION_HEAD, \"~107M params\"),\n",
341
+ " (\"Surgery Module\", FREEZE_SURGERY_MODULE, \"~26M params\"),\n",
342
+ " (\"Acoustic Connector\", FREEZE_CONNECTORS, \"~0.1M params\"),\n",
343
+ " (\"Semantic Connector\", FREEZE_CONNECTORS, \"~0.3M params\"),\n",
344
+ " (\"LM Head\", FREEZE_LM_HEAD, \"~388M params\"),\n",
345
+ " (\"Acoustic Tokenizer\", FREEZE_ACOUSTIC_TOKENIZER, \"~30M params\"),\n",
346
+ " (\"Semantic Tokenizer\", FREEZE_SEMANTIC_TOKENIZER, \"~30M params\"),\n",
347
+ "]\n",
348
+ "\n",
349
+ "train_count = 0\n",
350
+ "for name, frozen, params in components:\n",
351
+ " status = \"❌ FREEZE\" if frozen else \"✅ TRAIN\"\n",
352
+ " print(f\" {name:<25s} {status:<12s} {params}\")\n",
353
+ " if not frozen:\n",
354
+ " train_count += 1\n",
355
+ "\n",
356
+ "print(f\"\\n LoRA on LLM: {'✅ Yes (r=' + str(LORA_R) + ')' if USE_LORA_ON_LLM else '❌ No'}\")\n",
357
+ "print(f\" LoRA on Diffusion Head: {'✅ Yes' if LORA_WRAP_DIFFUSION_HEAD else '❌ No'}\")\n",
358
+ "print(f\" Full Train Diffusion: {'✅ Yes' if TRAIN_DIFFUSION_HEAD else '❌ No'}\")\n",
359
+ "print(f\"\\n Components to train: {train_count}\")\n",
360
+ "print(\"=\" * 60)"
361
+ ],
362
+ "execution_count": null,
363
+ "outputs": []
364
+ },
365
+ {
366
+ "cell_type": "code",
367
+ "metadata": {},
368
+ "source": [
369
+ "#@title 4.2 — Advanced: Per-Layer Freezing in Diffusion Head { display-mode: \"form\" }\n",
370
+ "\n",
371
+ "# If you want to freeze specific parameter groups within the diffusion head\n",
372
+ "# (e.g., freeze lower layers, only train upper layers), you can specify\n",
373
+ "# parameter indices to freeze.\n",
374
+ "#\n",
375
+ "# Diffusion Head parameter groups:\n",
376
+ "# [0] noisy_images_proj.weight — input projection (64 → 3584)\n",
377
+ "# [1] cond_proj.weight — condition projection (3584 → 3584)\n",
378
+ "# [2] t_embedder.mlp.0.weight — timestep embedding (256 → 3584)\n",
379
+ "# [3] t_embedder.mlp.2.weight — timestep embedding (3584 → 3584)\n",
380
+ "# [4-N] layers.* — transformer layers (HeadLayer)\n",
381
+ "# [final] final_layer.* — final output layer\n",
382
+ "\n",
383
+ "LAYERS_TO_FREEZE_IN_HEAD = \"\" #@param {type:\"string\"}\n",
384
+ "# Example: \"0,1\" to freeze noisy_images_proj and cond_proj\n",
385
+ "# Leave empty to freeze/unfreeze the entire head as a unit\n",
386
+ "\n",
387
+ "if LAYERS_TO_FREEZE_IN_HEAD:\n",
388
+ " print(f\"Diffusion head params to freeze by index: {LAYERS_TO_FREEZE_IN_HEAD}\")\n",
389
+ "else:\n",
390
+ " print(\"No per-parameter freezing configured for diffusion head.\")"
391
+ ],
392
+ "execution_count": null,
393
+ "outputs": []
394
+ },
395
+ {
396
+ "cell_type": "markdown",
397
+ "metadata": {},
398
+ "source": [
399
+ "## Cell 5: 🚀 Training Configuration"
400
+ ]
401
+ },
402
+ {
403
+ "cell_type": "code",
404
+ "metadata": {},
405
+ "source": [
406
+ "#@title 5.1 — Hyperparameters { display-mode: \"form\" }\n",
407
+ "\n",
408
+ "# ══════════════════════════════════════════════════════════\n",
409
+ "# TRAINING HYPERPARAMETERS\n",
410
+ "# ══════════════════════════════════════════════════════════\n",
411
+ "\n",
412
+ "NUM_EPOCHS = 3 #@param {type:\"integer\"}\n",
413
+ "BATCH_SIZE_PER_GPU = 1 #@param {type:\"integer\"}\n",
414
+ "GRADIENT_ACCUMULATION_STEPS = 8 #@param {type:\"integer\"}\n",
415
+ "LEARNING_RATE = 2e-5 #@param {type:\"number\"}\n",
416
+ "WARMUP_RATIO = 0.05 #@param {type:\"number\"}\n",
417
+ "WEIGHT_DECAY = 0.01 #@param {type:\"number\"}\n",
418
+ "MAX_GRAD_NORM = 1.0 #@param {type:\"number\"}\n",
419
+ "MAX_LENGTH = 2048 #@param {type:\"integer\"}\n",
420
+ "\n",
421
+ "# Loss weights\n",
422
+ "CE_LOSS_WEIGHT = 1.0 #@param {type:\"number\"}\n",
423
+ "DIFFUSION_LOSS_WEIGHT = 1.0 #@param {type:\"number\"}\n",
424
+ "DDPM_BATCH_MUL = 4 #@param {type:\"integer\"}\n",
425
+ "\n",
426
+ "# Data\n",
427
+ "VOICE_PROMPT_DROP_RATE = 0.0 #@param {type:\"number\"}\n",
428
+ "EVAL_SPLIT_SIZE = 0.05 #@param {type:\"number\"}\n",
429
+ "\n",
430
+ "# Precision\n",
431
+ "USE_FP16 = True #@param {type:\"boolean\"}\n",
432
+ "USE_BF16 = False #@param {type:\"boolean\"}\n",
433
+ "\n",
434
+ "# Memory optimization\n",
435
+ "GRADIENT_CHECKPOINTING = True #@param {type:\"boolean\"}\n",
436
+ "\n",
437
+ "# Logging\n",
438
+ "LOGGING_STEPS = 10 #@param {type:\"integer\"}\n",
439
+ "SAVE_STEPS = 500 #@param {type:\"integer\"}\n",
440
+ "SAVE_TOTAL_LIMIT = 3 #@param {type:\"integer\"}\n",
441
+ "EVAL_STEPS = 500 #@param {type:\"integer\"}\n",
442
+ "\n",
443
+ "# Seed\n",
444
+ "SEED = 42 #@param {type:\"integer\"}\n",
445
+ "\n",
446
+ "# Compute effective batch size\n",
447
+ "num_gpus = max(1, __import__('torch').cuda.device_count())\n",
448
+ "effective_batch = BATCH_SIZE_PER_GPU * GRADIENT_ACCUMULATION_STEPS * num_gpus\n",
449
+ "print(f\"\\n📊 Training Configuration:\")\n",
450
+ "print(f\" Epochs: {NUM_EPOCHS}\")\n",
451
+ "print(f\" Batch/GPU: {BATCH_SIZE_PER_GPU}\")\n",
452
+ "print(f\" Grad Accum: {GRADIENT_ACCUMULATION_STEPS}\")\n",
453
+ "print(f\" GPUs: {num_gpus}\")\n",
454
+ "print(f\" Effective Batch: {effective_batch}\")\n",
455
+ "print(f\" Learning Rate: {LEARNING_RATE}\")\n",
456
+ "print(f\" Precision: {'fp16' if USE_FP16 else 'bf16' if USE_BF16 else 'fp32'}\")\n",
457
+ "print(f\" Grad Checkpoint: {GRADIENT_CHECKPOINTING}\")"
458
+ ],
459
+ "execution_count": null,
460
+ "outputs": []
461
+ },
462
+ {
463
+ "cell_type": "markdown",
464
+ "metadata": {},
465
+ "source": [
466
+ "## Cell 6: 🏋️ Launch Fine-Tuning"
467
+ ]
468
+ },
469
+ {
470
+ "cell_type": "code",
471
+ "metadata": {},
472
+ "source": [
473
+ "#@title 6.1 — Build & Run Training Command { display-mode: \"form\" }\n",
474
+ "\n",
475
+ "import os, sys\n",
476
+ "\n",
477
+ "# Change to project directory\n",
478
+ "os.chdir(PROJECT_DIR)\n",
479
+ "\n",
480
+ "# Build the training command\n",
481
+ "cmd = f\"\"\"\n",
482
+ "python finetune_surgery_t4.py \\\n",
483
+ " --model_name_or_path \"{SURGERY_MODEL_PATH}\" \\\n",
484
+ " --processor_name_or_path \"{SURGERY_MODEL_PATH}\" \\\n",
485
+ " --train_jsonl \"{TRAIN_JSONL_PATH}\" \\\n",
486
+ " {f'--validation_jsonl \"{VALIDATION_JSONL_PATH}\"' if VALIDATION_JSONL_PATH else ''} \\\n",
487
+ " --output_dir \"{OUTPUT_DIR}\" \\\n",
488
+ " --max_length {MAX_LENGTH} \\\n",
489
+ " --num_train_epochs {NUM_EPOCHS} \\\n",
490
+ " --per_device_train_batch_size {BATCH_SIZE_PER_GPU} \\\n",
491
+ " --gradient_accumulation_steps {GRADIENT_ACCUMULATION_STEPS} \\\n",
492
+ " --learning_rate {LEARNING_RATE} \\\n",
493
+ " --warmup_ratio {WARMUP_RATIO} \\\n",
494
+ " --weight_decay {WEIGHT_DECAY} \\\n",
495
+ " --max_grad_norm {MAX_GRAD_NORM} \\\n",
496
+ " --gradient_clipping \\\n",
497
+ " --ddpm_batch_mul {DDPM_BATCH_MUL} \\\n",
498
+ " --ce_loss_weight {CE_LOSS_WEIGHT} \\\n",
499
+ " --diffusion_loss_weight {DIFFUSION_LOSS_WEIGHT} \\\n",
500
+ " --voice_prompt_drop_rate {VOICE_PROMPT_DROP_RATE} \\\n",
501
+ " --eval_split_size {EVAL_SPLIT_SIZE} \\\n",
502
+ " --do_eval \\\n",
503
+ " --logging_steps {LOGGING_STEPS} \\\n",
504
+ " --save_steps {SAVE_STEPS} \\\n",
505
+ " --save_total_limit {SAVE_TOTAL_LIMIT} \\\n",
506
+ " --eval_steps {EVAL_STEPS} \\\n",
507
+ " --evaluation_strategy steps \\\n",
508
+ " --load_best_model_at_end \\\n",
509
+ " --metric_for_best_model eval_loss \\\n",
510
+ " --greater_is_better False \\\n",
511
+ " --save_strategy steps \\\n",
512
+ " --report_to tensorboard \\\n",
513
+ " --run_name vibevoice_surgery_finetune \\\n",
514
+ " --seed {SEED} \\\n",
515
+ " --dataloader_num_workers 2 \\\n",
516
+ " --ignore_verifications \\\n",
517
+ " --remove_unused_columns False \\\n",
518
+ " --dataloader_pin_memory True \\\n",
519
+ " --freeze_llm {str(FREEZE_LLM).lower()} \\\n",
520
+ " --freeze_diffusion_head {str(FREEZE_DIFFUSION_HEAD).lower()} \\\n",
521
+ " --freeze_surgery_module {str(FREEZE_SURGERY_MODULE).lower()} \\\n",
522
+ " --freeze_connectors {str(FREEZE_CONNECTORS).lower()} \\\n",
523
+ " --freeze_lm_head {str(FREEZE_LM_HEAD).lower()} \\\n",
524
+ " --freeze_acoustic_tokenizer {str(FREEZE_ACOUSTIC_TOKENIZER).lower()} \\\n",
525
+ " --freeze_semantic_tokenizer {str(FREEZE_SEMANTIC_TOKENIZER).lower()} \\\n",
526
+ " --lora_target_modules {LORA_TARGET_MODULES} \\\n",
527
+ " --lora_r {LORA_R} \\\n",
528
+ " --lora_alpha {LORA_ALPHA} \\\n",
529
+ " --lora_dropout {LORA_DROPOUT} \\\n",
530
+ " --lora_wrap_diffusion_head {str(LORA_WRAP_DIFFUSION_HEAD).lower()} \\\n",
531
+ " --train_diffusion_head {str(TRAIN_DIFFUSION_HEAD).lower()} \\\n",
532
+ " --train_connectors {str(not FREEZE_CONNECTORS).lower()} \\\n",
533
+ " --train_surgery_module {str(not FREEZE_SURGERY_MODULE).lower()} \\\n",
534
+ " {f'--layers_to_freeze \"{LAYERS_TO_FREEZE_IN_HEAD}\"' if LAYERS_TO_FREEZE_IN_HEAD else ''} \\\n",
535
+ " {'--fp16' if USE_FP16 else ''} \\\n",
536
+ " {'--bf16' if USE_BF16 else ''} \\\n",
537
+ " {'--gradient_checkpointing' if GRADIENT_CHECKPOINTING else ''}\n",
538
+ "\"\"\"\n",
539
+ "\n",
540
+ "# Clean up the command (remove extra spaces and empty lines)\n",
541
+ "import re\n",
542
+ "cmd = re.sub(r'\\\\\\n\\s*\\\\', r'\\\\', cmd) # Remove empty continuations\n",
543
+ "cmd = re.sub(r'\\s+\\\\\\n\\s*$', '', cmd) # Clean trailing backslash\n",
544
+ "cmd = cmd.strip()\n",
545
+ "\n",
546
+ "print(\"=\" * 60)\n",
547
+ "print(\" Training Command\")\n",
548
+ "print(\"=\" * 60)\n",
549
+ "print(cmd)\n",
550
+ "print(\"=\" * 60)\n",
551
+ "\n",
552
+ "# ── PRE-TRAINING CHECKS ──\n",
553
+ "print(\"\\n🔍 Pre-training checks:\")\n",
554
+ "\n",
555
+ "errors = []\n",
556
+ "warnings_list = []\n",
557
+ "\n",
558
+ "# Check surgery model exists\n",
559
+ "if not os.path.exists(SURGERY_MODEL_PATH):\n",
560
+ " errors.append(f\"Surgery model not found: {SURGERY_MODEL_PATH}\")\n",
561
+ "else:\n",
562
+ " config_path = os.path.join(SURGERY_MODEL_PATH, \"config.json\")\n",
563
+ " if os.path.exists(config_path):\n",
564
+ " print(f\" ✅ Surgery model config found\")\n",
565
+ " else:\n",
566
+ " errors.append(f\"config.json not found in {SURGERY_MODEL_PATH}\")\n",
567
+ "\n",
568
+ "# Check training data\n",
569
+ "if not os.path.exists(TRAIN_JSONL_PATH):\n",
570
+ " errors.append(f\"Training JSONL not found: {TRAIN_JSONL_PATH}\")\n",
571
+ "else:\n",
572
+ " with open(TRAIN_JSONL_PATH, 'r') as f:\n",
573
+ " lines = f.readlines()\n",
574
+ " print(f\" ✅ Training data: {len(lines)} samples\")\n",
575
+ "\n",
576
+ "# Check GPU memory\n",
577
+ "if torch.cuda.is_available():\n",
578
+ " for i in range(torch.cuda.device_count()):\n",
579
+ " mem = torch.cuda.get_device_properties(i).total_mem / 1024**3\n",
580
+ " print(f\" ✅ GPU {i}: {mem:.1f} GB\")\n",
581
+ "\n",
582
+ "if errors:\n",
583
+ " print(f\"\\n❌ ERRORS (fix before training):\")\n",
584
+ " for e in errors:\n",
585
+ " print(f\" - {e}\")\n",
586
+ " raise RuntimeError(\"Pre-training checks failed. See errors above.\")\n",
587
+ "\n",
588
+ "if warnings_list:\n",
589
+ " print(f\"\\n⚠️ Warnings:\")\n",
590
+ " for w in warnings_list:\n",
591
+ " print(f\" - {w}\")\n",
592
+ "\n",
593
+ "print(\"\\n✅ All checks passed! Starting training...\")\n",
594
+ "print(\"=\" * 60)"
595
+ ],
596
+ "execution_count": null,
597
+ "outputs": []
598
+ },
599
+ {
600
+ "cell_type": "code",
601
+ "metadata": {},
602
+ "source": [
603
+ "#@title 6.2 — Execute Training { display-mode: \"form\" }\n",
604
+ "\n",
605
+ "# Run the training command\n",
606
+ "import subprocess, os\n",
607
+ "\n",
608
+ "os.chdir(PROJECT_DIR)\n",
609
+ "\n",
610
+ "print(\"🚀 Starting fine-tuning...\")\n",
611
+ "print(\"=\" * 60)\n",
612
+ "print(\"\"\"\n",
613
+ "NOTE: This will run for the configured number of epochs.\n",
614
+ "Monitor the output for:\n",
615
+ " - ce_loss: Cross-entropy loss on text tokens\n",
616
+ " - diffusion_loss: MSE loss on speech generation\n",
617
+ " - learning_rate_real: Actual learning rate\n",
618
+ "\n",
619
+ "Expected behavior:\n",
620
+ " - Phase 1 (frozen LLM+head): losses should decrease steadily\n",
621
+ " - Trainable params should show nonzero gradients\n",
622
+ " - EMA callback will track prediction head params\n",
623
+ "\"\"\")\n",
624
+ "print(\"=\" * 60)\n",
625
+ "\n",
626
+ "# Execute\n",
627
+ "process = subprocess.Popen(\n",
628
+ " cmd,\n",
629
+ " shell=True,\n",
630
+ " stdout=subprocess.PIPE,\n",
631
+ " stderr=subprocess.STDOUT,\n",
632
+ " universal_newlines=True,\n",
633
+ " bufsize=1,\n",
634
+ ")\n",
635
+ "\n",
636
+ "# Stream output\n",
637
+ "for line in process.stdout:\n",
638
+ " print(line, end='')\n",
639
+ "\n",
640
+ "process.wait()\n",
641
+ "exit_code = process.returncode\n",
642
+ "\n",
643
+ "print(\"\\n\" + \"=\" * 60)\n",
644
+ "if exit_code == 0:\n",
645
+ " print(\"✅ Training completed successfully!\")\n",
646
+ "else:\n",
647
+ " print(f\"❌ Training failed with exit code: {exit_code}\")\n",
648
+ "print(\"=\" * 60)"
649
+ ],
650
+ "execution_count": null,
651
+ "outputs": []
652
+ },
653
+ {
654
+ "cell_type": "markdown",
655
+ "metadata": {},
656
+ "source": [
657
+ "## Cell 7: 📈 Monitor Training"
658
+ ]
659
+ },
660
+ {
661
+ "cell_type": "code",
662
+ "metadata": {},
663
+ "source": [
664
+ "#@title 7.1 — Launch TensorBoard { display-mode: \"form\" }\n",
665
+ "\n",
666
+ "%load_ext tensorboard\n",
667
+ "%tensorboard --logdir {OUTPUT_DIR}"
668
+ ],
669
+ "execution_count": null,
670
+ "outputs": []
671
+ },
672
+ {
673
+ "cell_type": "code",
674
+ "metadata": {},
675
+ "source": [
676
+ "#@title 7.2 — Check Saved Artifacts { display-mode: \"form\" }\n",
677
+ "\n",
678
+ "import os, glob\n",
679
+ "\n",
680
+ "print(\"=\" * 60)\n",
681
+ "print(\" Saved Artifacts\")\n",
682
+ "print(\"=\" * 60)\n",
683
+ "\n",
684
+ "lora_dir = os.path.join(OUTPUT_DIR, \"lora\")\n",
685
+ "if os.path.exists(lora_dir):\n",
686
+ " for root, dirs, files in os.walk(lora_dir):\n",
687
+ " level = root.replace(lora_dir, '').count(os.sep)\n",
688
+ " indent = ' ' * level\n",
689
+ " print(f'{indent}{os.path.basename(root)}/')\n",
690
+ " subindent = ' ' * (level + 1)\n",
691
+ " for file in sorted(files):\n",
692
+ " fpath = os.path.join(root, file)\n",
693
+ " size_mb = os.path.getsize(fpath) / 1024 / 1024\n",
694
+ " print(f'{subindent}{file} ({size_mb:.2f} MB)')\n",
695
+ "else:\n",
696
+ " print(f\" ⚠️ No lora/ directory found in {OUTPUT_DIR}\")\n",
697
+ "\n",
698
+ "# Check checkpoints\n",
699
+ "checkpoints = sorted(glob.glob(os.path.join(OUTPUT_DIR, \"checkpoint-*\")))\n",
700
+ "print(f\"\\n📦 Checkpoints: {len(checkpoints)}\")\n",
701
+ "for ckpt in checkpoints[-3:]: # Show last 3\n",
702
+ " print(f\" {os.path.basename(ckpt)}\")\n",
703
+ "\n",
704
+ "print(\"=\" * 60)"
705
+ ],
706
+ "execution_count": null,
707
+ "outputs": []
708
+ },
709
+ {
710
+ "cell_type": "markdown",
711
+ "metadata": {},
712
+ "source": [
713
+ "## Cell 8: 🔄 Phase 2 — Expand Training (Optional)\n",
714
+ "\n",
715
+ "After Phase 1 converges, you can expand training to include more layers."
716
+ ]
717
+ },
718
+ {
719
+ "cell_type": "code",
720
+ "metadata": {},
721
+ "source": [
722
+ "#@title 8.1 — Configure Phase 2 { display-mode: \"form\" }\n",
723
+ "\n",
724
+ "# ══════════════════════════════════════════════════════════\n",
725
+ "# PHASE 2: Expand training scope\n",
726
+ "# ══════════════════════════════════════════════════════════\n",
727
+ "\n",
728
+ "RUN_PHASE_2 = False #@param {type:\"boolean\"}\n",
729
+ "\n",
730
+ "# Phase 2 settings — keep LLM frozen, add Diffusion Head\n",
731
+ "P2_FREEZE_LLM = True\n",
732
+ "P2_FREEZE_DIFFUSION_HEAD = False # Unfreeze diffusion head!\n",
733
+ "P2_FREEZE_SURGERY_MODULE = False\n",
734
+ "P2_FREEZE_CONNECTORS = False\n",
735
+ "P2_LORA_WRAP_DIFFUSION_HEAD = True # Use LoRA on head to save VRAM\n",
736
+ "P2_LEARNING_RATE = 1e-5 # Lower LR for Phase 2\n",
737
+ "P2_NUM_EPOCHS = 2\n",
738
+ "\n",
739
+ "# Resume from Phase 1 checkpoint\n",
740
+ "P2_RESUME_FROM = os.path.join(OUTPUT_DIR, \"lora\") #@param {type:\"string\"}\n",
741
+ "\n",
742
+ "if RUN_PHASE_2:\n",
743
+ " print(\"📋 Phase 2 Configuration:\")\n",
744
+ " print(f\" LLM: {'FROZEN' if P2_FREEZE_LLM else 'TRAIN'}\")\n",
745
+ " print(f\" Diff. Head: {'FROZEN' if P2_FREEZE_DIFFUSION_HEAD else 'TRAIN'}\")\n",
746
+ " print(f\" Surgery Mod: {'FROZEN' if P2_FREEZE_SURGERY_MODULE else 'TRAIN'}\")\n",
747
+ " print(f\" Connectors: {'FROZEN' if P2_FREEZE_CONNECTORS else 'TRAIN'}\")\n",
748
+ " print(f\" Head LoRA: {'Yes' if P2_LORA_WRAP_DIFFUSION_HEAD else 'No'}\")\n",
749
+ " print(f\" LR: {P2_LEARNING_RATE}\")\n",
750
+ " print(f\" Resume from: {P2_RESUME_FROM}\")\n",
751
+ "else:\n",
752
+ " print(\"Phase 2 is disabled. Set RUN_PHASE_2=True to enable.\")"
753
+ ],
754
+ "execution_count": null,
755
+ "outputs": []
756
+ },
757
+ {
758
+ "cell_type": "code",
759
+ "metadata": {},
760
+ "source": [
761
+ "#@title 8.2 — Execute Phase 2 { display-mode: \"form\" }\n",
762
+ "\n",
763
+ "if RUN_PHASE_2:\n",
764
+ " P2_OUTPUT_DIR = OUTPUT_DIR + \"_phase2\"\n",
765
+ " \n",
766
+ " p2_cmd = f\"\"\"\n",
767
+ " python finetune_surgery_t4.py \\\n",
768
+ " --model_name_or_path \"{SURGERY_MODEL_PATH}\" \\\n",
769
+ " --processor_name_or_path \"{SURGERY_MODEL_PATH}\" \\\n",
770
+ " --train_jsonl \"{TRAIN_JSONL_PATH}\" \\\n",
771
+ " {f'--validation_jsonl \"{VALIDATION_JSONL_PATH}\"' if VALIDATION_JSONL_PATH else ''} \\\n",
772
+ " --output_dir \"{P2_OUTPUT_DIR}\" \\\n",
773
+ " --max_length {MAX_LENGTH} \\\n",
774
+ " --num_train_epochs {P2_NUM_EPOCHS} \\\n",
775
+ " --per_device_train_batch_size {BATCH_SIZE_PER_GPU} \\\n",
776
+ " --gradient_accumulation_steps {GRADIENT_ACCUMULATION_STEPS} \\\n",
777
+ " --learning_rate {P2_LEARNING_RATE} \\\n",
778
+ " --warmup_ratio {WARMUP_RATIO} \\\n",
779
+ " --weight_decay {WEIGHT_DECAY} \\\n",
780
+ " --max_grad_norm {MAX_GRAD_NORM} \\\n",
781
+ " --gradient_clipping \\\n",
782
+ " --ddpm_batch_mul {DDPM_BATCH_MUL} \\\n",
783
+ " --ce_loss_weight {CE_LOSS_WEIGHT} \\\n",
784
+ " --diffusion_loss_weight {DIFFUSION_LOSS_WEIGHT} \\\n",
785
+ " --voice_prompt_drop_rate {VOICE_PROMPT_DROP_RATE} \\\n",
786
+ " --eval_split_size {EVAL_SPLIT_SIZE} \\\n",
787
+ " --do_eval \\\n",
788
+ " --logging_steps {LOGGING_STEPS} \\\n",
789
+ " --save_steps {SAVE_STEPS} \\\n",
790
+ " --save_total_limit {SAVE_TOTAL_LIMIT} \\\n",
791
+ " --eval_steps {EVAL_STEPS} \\\n",
792
+ " --evaluation_strategy steps \\\n",
793
+ " --load_best_model_at_end \\\n",
794
+ " --metric_for_best_model eval_loss \\\n",
795
+ " --greater_is_better False \\\n",
796
+ " --save_strategy steps \\\n",
797
+ " --report_to tensorboard \\\n",
798
+ " --run_name vibevoice_surgery_phase2 \\\n",
799
+ " --seed {SEED} \\\n",
800
+ " --dataloader_num_workers 2 \\\n",
801
+ " --ignore_verifications \\\n",
802
+ " --remove_unused_columns False \\\n",
803
+ " --dataloader_pin_memory True \\\n",
804
+ " --freeze_llm {str(P2_FREEZE_LLM).lower()} \\\n",
805
+ " --freeze_diffusion_head {str(P2_FREEZE_DIFFUSION_HEAD).lower()} \\\n",
806
+ " --freeze_surgery_module {str(P2_FREEZE_SURGERY_MODULE).lower()} \\\n",
807
+ " --freeze_connectors {str(P2_FREEZE_CONNECTORS).lower()} \\\n",
808
+ " --freeze_lm_head True \\\n",
809
+ " --freeze_acoustic_tokenizer True \\\n",
810
+ " --freeze_semantic_tokenizer True \\\n",
811
+ " --lora_target_modules none \\\n",
812
+ " --lora_wrap_diffusion_head {str(P2_LORA_WRAP_DIFFUSION_HEAD).lower()} \\\n",
813
+ " --train_diffusion_head {str(not P2_FREEZE_DIFFUSION_HEAD).lower()} \\\n",
814
+ " --train_connectors {str(not P2_FREEZE_CONNECTORS).lower()} \\\n",
815
+ " --train_surgery_module {str(not P2_FREEZE_SURGERY_MODULE).lower()} \\\n",
816
+ " {'--fp16' if USE_FP16 else ''} \\\n",
817
+ " {'--bf16' if USE_BF16 else ''} \\\n",
818
+ " --gradient_checkpointing\n",
819
+ " \"\"\"\n",
820
+ " \n",
821
+ " print(\"🚀 Starting Phase 2 training...\")\n",
822
+ " os.chdir(PROJECT_DIR)\n",
823
+ " process = subprocess.Popen(p2_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, bufsize=1)\n",
824
+ " for line in process.stdout:\n",
825
+ " print(line, end='')\n",
826
+ " process.wait()\n",
827
+ " \n",
828
+ " if process.returncode == 0:\n",
829
+ " print(\"\\n✅ Phase 2 training completed!\")\n",
830
+ " else:\n",
831
+ " print(f\"\\n❌ Phase 2 failed with exit code: {process.returncode}\")\n",
832
+ "else:\n",
833
+ " print(\"Phase 2 skipped (RUN_PHASE_2=False).\")"
834
+ ],
835
+ "execution_count": null,
836
+ "outputs": []
837
+ },
838
+ {
839
+ "cell_type": "markdown",
840
+ "metadata": {},
841
+ "source": [
842
+ "## Cell 9: 💾 Export & Merge Trained Weights"
843
+ ]
844
+ },
845
+ {
846
+ "cell_type": "code",
847
+ "metadata": {},
848
+ "source": [
849
+ "#@title 9.1 — Merge LoRA Weights & Create Inference Model { display-mode: \"form\" }\n",
850
+ "\n",
851
+ "import os, sys, json, gc\n",
852
+ "import torch\n",
853
+ "\n",
854
+ "os.chdir(PROJECT_DIR)\n",
855
+ "sys.path.insert(0, PROJECT_DIR)\n",
856
+ "\n",
857
+ "MERGE_OUTPUT = os.path.join(OUTPUT_DIR, \"merged_inference\") #@param {type:\"string\"}\n",
858
+ "\n",
859
+ "print(\"=\" * 60)\n",
860
+ "print(\" Merging Trained Weights\")\n",
861
+ "print(\"=\" * 60)\n",
862
+ "\n",
863
+ "lora_dir = os.path.join(OUTPUT_DIR, \"lora\")\n",
864
+ "if not os.path.exists(lora_dir):\n",
865
+ " raise FileNotFoundError(f\"No trained artifacts found at {lora_dir}\")\n",
866
+ "\n",
867
+ "# Apply patches\n",
868
+ "from vibevoice_surgery_colab import (\n",
869
+ " _patch_vibevoice_config_for_qwen3,\n",
870
+ " Qwen3SurgeryModule,\n",
871
+ " load_surgery_model,\n",
872
+ " save_surgery_model,\n",
873
+ " QWEN3_HIDDEN_SIZE,\n",
874
+ " DIFFUSION_HIDDEN_SIZE,\n",
875
+ " SURGERY_LAYER_INDICES,\n",
876
+ ")\n",
877
+ "_patch_vibevoice_config_for_qwen3()\n",
878
+ "\n",
879
+ "# Load the base surgery model\n",
880
+ "print(\"\\n[1/5] Loading base surgery model...\")\n",
881
+ "model = load_surgery_model(SURGERY_MODEL_PATH, dtype=torch.float16, device_map=\"cpu\")\n",
882
+ "\n",
883
+ "# Load LLM LoRA weights\n",
884
+ "print(\"\\n[2/5] Loading LLM LoRA weights...\")\n",
885
+ "try:\n",
886
+ " from peft import load_peft_weights, set_peft_model_state_dict\n",
887
+ " adapters_weights = load_peft_weights(lora_dir)\n",
888
+ " set_peft_model_state_dict(model.model.language_model, adapters_weights)\n",
889
+ " # Merge LoRA into base weights\n",
890
+ " model.model.language_model = model.model.language_model.merge_and_unload()\n",
891
+ " print(\" ✅ LLM LoRA merged\")\n",
892
+ "except Exception as e:\n",
893
+ " print(f\" ℹ️ No LLM LoRA found (expected if LLM was frozen): {e}\")\n",
894
+ "\n",
895
+ "# Load Diffusion Head\n",
896
+ "print(\"\\n[3/5] Loading Diffusion Head weights...\")\n",
897
+ "ph_path = os.path.join(lora_dir, \"diffusion_head_full.bin\")\n",
898
+ "if os.path.exists(ph_path):\n",
899
+ " model.model.prediction_head.load_state_dict(\n",
900
+ " torch.load(ph_path, map_location=\"cpu\"), strict=False\n",
901
+ " )\n",
902
+ " print(\" ✅ Diffusion Head loaded\")\n",
903
+ "\n",
904
+ "# Load Connectors\n",
905
+ "print(\"\\n[4/5] Loading Connectors...\")\n",
906
+ "for conn_name in [\"acoustic_connector\", \"semantic_connector\"]:\n",
907
+ " conn_path = os.path.join(lora_dir, conn_name, \"pytorch_model.bin\")\n",
908
+ " conn = getattr(model.model, conn_name, None)\n",
909
+ " if os.path.exists(conn_path) and conn is not None:\n",
910
+ " conn.load_state_dict(torch.load(conn_path, map_location=\"cpu\"))\n",
911
+ " print(f\" ✅ {conn_name} loaded\")\n",
912
+ "\n",
913
+ "# Load Surgery Module\n",
914
+ "print(\"\\n[5/5] Loading Surgery Module...\")\n",
915
+ "sm_path = os.path.join(lora_dir, \"surgery_module\", \"pytorch_model.bin\")\n",
916
+ "if os.path.exists(sm_path) and hasattr(model.model, \"surgery_module\"):\n",
917
+ " model.model.surgery_module.load_state_dict(\n",
918
+ " torch.load(sm_path, map_location=\"cpu\")\n",
919
+ " )\n",
920
+ " print(\" ✅ Surgery Module loaded\")\n",
921
+ "\n",
922
+ "# Save merged model\n",
923
+ "print(f\"\\n💾 Saving merged model to {MERGE_OUTPUT}...\")\n",
924
+ "save_surgery_model(model, MERGE_OUTPUT)\n",
925
+ "print(f\"\\n✅ Merged inference model saved to: {MERGE_OUTPUT}\")\n",
926
+ "\n",
927
+ "# Cleanup\n",
928
+ "del model\n",
929
+ "gc.collect()\n",
930
+ "torch.cuda.empty_cache()"
931
+ ],
932
+ "execution_count": null,
933
+ "outputs": []
934
+ },
935
+ {
936
+ "cell_type": "markdown",
937
+ "metadata": {},
938
+ "source": [
939
+ "## Cell 10: 🎤 Quick Inference Test"
940
+ ]
941
+ },
942
+ {
943
+ "cell_type": "code",
944
+ "metadata": {},
945
+ "source": [
946
+ "#@title 10.1 — Load Merged Model for Inference { display-mode: \"form\" }\n",
947
+ "\n",
948
+ "import os, sys, gc, torch\n",
949
+ "\n",
950
+ "os.chdir(PROJECT_DIR)\n",
951
+ "sys.path.insert(0, PROJECT_DIR)\n",
952
+ "\n",
953
+ "from vibevoice_surgery_colab import (\n",
954
+ " _patch_vibevoice_config_for_qwen3,\n",
955
+ " load_surgery_model,\n",
956
+ ")\n",
957
+ "_patch_vibevoice_config_for_qwen3()\n",
958
+ "\n",
959
+ "MERGE_PATH = os.path.join(OUTPUT_DIR, \"merged_inference\")\n",
960
+ "\n",
961
+ "if not os.path.exists(MERGE_PATH):\n",
962
+ " print(f\"⚠️ Merged model not found at {MERGE_PATH}\")\n",
963
+ " print(f\" Using base surgery model instead.\")\n",
964
+ " MERGE_PATH = SURGERY_MODEL_PATH\n",
965
+ "\n",
966
+ "print(f\"Loading model from {MERGE_PATH}...\")\n",
967
+ "inference_model = load_surgery_model(\n",
968
+ " MERGE_PATH,\n",
969
+ " dtype=torch.float16,\n",
970
+ " device_map=\"auto\",\n",
971
+ ")\n",
972
+ "inference_model.eval()\n",
973
+ "print(\"✅ Model loaded for inference!\")"
974
+ ],
975
+ "execution_count": null,
976
+ "outputs": []
977
+ },
978
+ {
979
+ "cell_type": "code",
980
+ "metadata": {},
981
+ "source": [
982
+ "#@title 10.2 — Generate Speech { display-mode: \"form\" }\n",
983
+ "\n",
984
+ "import torch, soundfile as sf\n",
985
+ "from vibevoice.processor.vibevoice_processor import VibeVoiceProcessor\n",
986
+ "\n",
987
+ "TEXT_TO_SPEAK = \"Hello, this is a test of the fine-tuned voice model.\" #@param {type:\"string\"}\n",
988
+ "VOICE_PROMPT_PATH = \"\" #@param {type:\"string\"}\n",
989
+ "CFG_SCALE = 3.0 #@param {type:\"number\"}\n",
990
+ "OUTPUT_AUDIO_PATH = \"/content/generated_speech.wav\" #@param {type:\"string\"}\n",
991
+ "\n",
992
+ "# Load processor\n",
993
+ "processor = VibeVoiceProcessor.from_pretrained(MERGE_PATH)\n",
994
+ "\n",
995
+ "# Prepare inputs\n",
996
+ "if VOICE_PROMPT_PATH and os.path.exists(VOICE_PROMPT_PATH):\n",
997
+ " proc_out = processor(\n",
998
+ " text=[TEXT_TO_SPEAK],\n",
999
+ " voice_samples=[[VOICE_PROMPT_PATH]],\n",
1000
+ " return_tensors=\"pt\",\n",
1001
+ " )\n",
1002
+ "else:\n",
1003
+ " proc_out = processor(\n",
1004
+ " text=[TEXT_TO_SPEAK],\n",
1005
+ " return_tensors=\"pt\",\n",
1006
+ " )\n",
1007
+ "\n",
1008
+ "print(f\"Input tokens: {proc_out['input_ids'].shape}\")\n",
1009
+ "\n",
1010
+ "# Generate\n",
1011
+ "print(\"\\n🎤 Generating speech...\")\n",
1012
+ "with torch.no_grad():\n",
1013
+ " output = inference_model.generate(\n",
1014
+ " **{k: v.to(inference_model.device) if isinstance(v, torch.Tensor) else v \n",
1015
+ " for k, v in proc_out.items()},\n",
1016
+ " tokenizer=processor.tokenizer,\n",
1017
+ " cfg_scale=CFG_SCALE,\n",
1018
+ " max_new_tokens=2048,\n",
1019
+ " show_progress_bar=True,\n",
1020
+ " )\n",
1021
+ "\n",
1022
+ "# Save audio\n",
1023
+ "if output.speech_outputs and output.speech_outputs[0] is not None:\n",
1024
+ " audio = output.speech_outputs[0].cpu().float().numpy()\n",
1025
+ " sf.write(OUTPUT_AUDIO_PATH, audio, 24000)\n",
1026
+ " print(f\"\\n✅ Audio saved to: {OUTPUT_AUDIO_PATH}\")\n",
1027
+ " print(f\" Duration: {len(audio) / 24000:.2f} seconds\")\n",
1028
+ " print(f\" Shape: {audio.shape}\")\n",
1029
+ "else:\n",
1030
+ " print(\"❌ No audio generated. Check the input and model.\")"
1031
+ ],
1032
+ "execution_count": null,
1033
+ "outputs": []
1034
+ },
1035
+ {
1036
+ "cell_type": "code",
1037
+ "metadata": {},
1038
+ "source": [
1039
+ "#@title 10.3 — Play Generated Audio { display-mode: \"form\" }\n",
1040
+ "\n",
1041
+ "from IPython.display import Audio, display\n",
1042
+ "\n",
1043
+ "if os.path.exists(OUTPUT_AUDIO_PATH):\n",
1044
+ " display(Audio(OUTPUT_AUDIO_PATH))\n",
1045
+ "else:\n",
1046
+ " print(\"No audio file found. Run Cell 10.2 first.\")"
1047
+ ],
1048
+ "execution_count": null,
1049
+ "outputs": []
1050
+ },
1051
+ {
1052
+ "cell_type": "markdown",
1053
+ "metadata": {},
1054
+ "source": [
1055
+ "## Cell 11: 📦 Download & Cleanup"
1056
+ ]
1057
+ },
1058
+ {
1059
+ "cell_type": "code",
1060
+ "metadata": {},
1061
+ "source": [
1062
+ "#@title 11.1 — Package Results for Download { display-mode: \"form\" }\n",
1063
+ "\n",
1064
+ "import shutil, os\n",
1065
+ "\n",
1066
+ "ZIP_OUTPUT = \"/content/vibevoice_finetuned.zip\" #@param {type:\"string\"}\n",
1067
+ "\n",
1068
+ "# Package the trained artifacts\n",
1069
+ "lora_dir = os.path.join(OUTPUT_DIR, \"lora\")\n",
1070
+ "if os.path.exists(lora_dir):\n",
1071
+ " print(f\"📦 Packaging {lora_dir}...\")\n",
1072
+ " shutil.make_archive(\n",
1073
+ " ZIP_OUTPUT.replace('.zip', ''),\n",
1074
+ " 'zip',\n",
1075
+ " lora_dir,\n",
1076
+ " )\n",
1077
+ " size_mb = os.path.getsize(ZIP_OUTPUT) / 1024 / 1024\n",
1078
+ " print(f\"✅ Package created: {ZIP_OUTPUT} ({size_mb:.1f} MB)\")\n",
1079
+ " \n",
1080
+ " # In Colab, you can download with:\n",
1081
+ " try:\n",
1082
+ " from google.colab import files\n",
1083
+ " files.download(ZIP_OUTPUT)\n",
1084
+ " except ImportError:\n",
1085
+ " print(f\" (Not in Colab — download {ZIP_OUTPUT} manually)\")\n",
1086
+ "else:\n",
1087
+ " print(f\"❌ No trained artifacts found at {lora_dir}\")"
1088
+ ],
1089
+ "execution_count": null,
1090
+ "outputs": []
1091
+ },
1092
+ {
1093
+ "cell_type": "code",
1094
+ "metadata": {},
1095
+ "source": [
1096
+ "#@title 11.2 — Upload to Google Drive { display-mode: \"form\" }\n",
1097
+ "\n",
1098
+ "UPLOAD_TO_DRIVE = False #@param {type:\"boolean\"}\n",
1099
+ "DRIVE_PATH = \"/content/drive/MyDrive/vibevoice_finetuned\" #@param {type:\"string\"}\n",
1100
+ "\n",
1101
+ "if UPLOAD_TO_DRIVE:\n",
1102
+ " import shutil\n",
1103
+ " \n",
1104
+ " # Mount Drive\n",
1105
+ " try:\n",
1106
+ " from google.colab import drive\n",
1107
+ " drive.mount('/content/drive')\n",
1108
+ " except ImportError:\n",
1109
+ " print(\"❌ Not running in Google Colab.\")\n",
1110
+ " UPLOAD_TO_DRIVE = False\n",
1111
+ " \n",
1112
+ " if UPLOAD_TO_DRIVE:\n",
1113
+ " os.makedirs(DRIVE_PATH, exist_ok=True)\n",
1114
+ " lora_dir = os.path.join(OUTPUT_DIR, \"lora\")\n",
1115
+ " if os.path.exists(lora_dir):\n",
1116
+ " print(f\"📤 Copying to Google Drive: {DRIVE_PATH}\")\n",
1117
+ " shutil.copytree(lora_dir, os.path.join(DRIVE_PATH, \"lora\"), dirs_exist_ok=True)\n",
1118
+ " print(f\"✅ Uploaded to Google Drive!\")\n",
1119
+ " \n",
1120
+ " # Also copy merged model if exists\n",
1121
+ " merged = os.path.join(OUTPUT_DIR, \"merged_inference\")\n",
1122
+ " if os.path.exists(merged):\n",
1123
+ " shutil.copytree(merged, os.path.join(DRIVE_PATH, \"merged\"), dirs_exist_ok=True)\n",
1124
+ " print(f\"✅ Merged model uploaded too!\")\n",
1125
+ "else:\n",
1126
+ " print(\"Drive upload disabled.\")"
1127
+ ],
1128
+ "execution_count": null,
1129
+ "outputs": []
1130
+ },
1131
+ {
1132
+ "cell_type": "markdown",
1133
+ "metadata": {},
1134
+ "source": [
1135
+ "---\n",
1136
+ "\n",
1137
+ "## 📖 Quick Reference\n",
1138
+ "\n",
1139
+ "### CLI Usage (alternative to notebook)\n",
1140
+ "\n",
1141
+ "```bash\n",
1142
+ "# Phase 1: Train Surgery Module + Connectors (freeze LLM + Diffusion Head)\n",
1143
+ "python finetune_surgery_t4.py \\\n",
1144
+ " --model_name_or_path /path/to/surgery_model \\\n",
1145
+ " --train_jsonl /path/to/train.jsonl \\\n",
1146
+ " --output_dir /path/to/output \\\n",
1147
+ " --freeze_llm true \\\n",
1148
+ " --freeze_diffusion_head true \\\n",
1149
+ " --freeze_surgery_module false \\\n",
1150
+ " --freeze_connectors false \\\n",
1151
+ " --train_connectors true \\\n",
1152
+ " --train_surgery_module true \\\n",
1153
+ " --lora_target_modules none \\\n",
1154
+ " --fp16 \\\n",
1155
+ " --gradient_checkpointing \\\n",
1156
+ " --num_train_epochs 3 \\\n",
1157
+ " --learning_rate 2e-5\n",
1158
+ "\n",
1159
+ "# Phase 2: Add Diffusion Head training\n",
1160
+ "python finetune_surgery_t4.py \\\n",
1161
+ " --model_name_or_path /path/to/surgery_model \\\n",
1162
+ " --train_jsonl /path/to/train.jsonl \\\n",
1163
+ " --output_dir /path/to/output_phase2 \\\n",
1164
+ " --freeze_llm true \\\n",
1165
+ " --freeze_diffusion_head false \\\n",
1166
+ " --lora_wrap_diffusion_head true \\\n",
1167
+ " --train_connectors true \\\n",
1168
+ " --train_surgery_module true \\\n",
1169
+ " --lora_target_modules none \\\n",
1170
+ " --fp16 \\\n",
1171
+ " --gradient_checkpointing \\\n",
1172
+ " --num_train_epochs 2 \\\n",
1173
+ " --learning_rate 1e-5\n",
1174
+ "```\n",
1175
+ "\n",
1176
+ "### Layer Freezing Flags\n",
1177
+ "\n",
1178
+ "| Flag | Default | Description |\n",
1179
+ "|------|---------|-------------|\n",
1180
+ "| `--freeze_llm` | True | Freeze entire LLM backbone |\n",
1181
+ "| `--freeze_diffusion_head` | True | Freeze diffusion prediction head |\n",
1182
+ "| `--freeze_surgery_module` | False | Freeze the 2560→3584 bridge |\n",
1183
+ "| `--freeze_connectors` | False | Freeze acoustic/semantic connectors |\n",
1184
+ "| `--freeze_lm_head` | True | Freeze LM output head |\n",
1185
+ "| `--freeze_acoustic_tokenizer` | True | Freeze acoustic VAE |\n",
1186
+ "| `--freeze_semantic_tokenizer` | True | Freeze semantic VAE |\n",
1187
+ "| `--train_diffusion_head` | False | Full fine-tune diffusion head |\n",
1188
+ "| `--train_connectors` | True | Full fine-tune connectors |\n",
1189
+ "| `--train_surgery_module` | True | Full fine-tune surgery module |\n",
1190
+ "| `--lora_target_modules` | q,k,v,o,... | LLM LoRA targets (\"none\" to disable) |\n",
1191
+ "| `--lora_wrap_diffusion_head` | False | Apply LoRA to diffusion head |\n",
1192
+ "| `--layers_to_freeze` | None | Specific diffusion head param indices to freeze |\n",
1193
+ "\n",
1194
+ "### Saved Artifacts Structure\n",
1195
+ "\n",
1196
+ "```\n",
1197
+ "output_dir/\n",
1198
+ "├── lora/\n",
1199
+ "│ ├── adapter_config.json # LLM LoRA config\n",
1200
+ "│ ├── adapter_model.safetensors # LLM LoRA weights\n",
1201
+ "│ ├── diffusion_head/\n",
1202
+ "│ │ ├── adapter_config.json # Head LoRA config\n",
1203
+ "│ │ ├── adapter_model.safetensors\n",
1204
+ "│ │ └── diffusion_head_full.bin # Full head weights\n",
1205
+ "│ ├── acoustic_connector/\n",
1206
+ "│ │ └── pytorch_model.bin\n",
1207
+ "│ ├── semantic_connector/\n",
1208
+ "│ │ └── pytorch_model.bin\n",
1209
+ "│ └── surgery_module/\n",
1210
+ "│ └── pytorch_model.bin\n",
1211
+ "├── checkpoint-500/\n",
1212
+ "├── checkpoint-1000/\n",
1213
+ "└── merged_inference/ # (if Cell 9.1 ran)\n",
1214
+ " ├── config.json\n",
1215
+ " ├── model.safetensors\n",
1216
+ " └── preprocessor_config.json\n",
1217
+ "```\n",
1218
+ "\n",
1219
+ "---\n",
1220
+ "\n",
1221
+ "*Built with ❤️ for the VibeVoice project*"
1222
+ ]
1223
+ }
1224
+ ]
1225
+ }
VibeVoice-tpu/src/finetune_surgery_t4.py ADDED
@@ -0,0 +1,1214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ VibeVoice Surgery Fine-Tuning on 2× T4 GPUs
3
+ =============================================
4
+
5
+ Complete fine-tuning pipeline for the VibeVoice surgery model (Qwen3-4B backbone).
6
+ Designed for Kaggle / Google Colab with 2× NVIDIA T4 GPUs (16 GB VRAM each).
7
+
8
+ Supports:
9
+ - Configurable layer freezing (LLM, Diffusion Head, Surgery Module, Connectors)
10
+ - LoRA on LLM and/or Diffusion Head
11
+ - Phase-based training (Phase 1: freeze LLM+head, Phase 2: unfreeze)
12
+ - Multi-GPU via DataParallel / DDP
13
+ - fp16 mixed precision (T4 native)
14
+ - Gradient checkpointing for memory efficiency
15
+ - EMA on prediction head
16
+ - Checkpoint resume with custom weight loading
17
+ - Comprehensive diagnostics and logging
18
+ """
19
+
20
+ import os
21
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
22
+
23
+ import gc
24
+ import json
25
+ import copy
26
+ import logging
27
+ import random
28
+ from dataclasses import dataclass, field
29
+ from typing import Any, Dict, List, Optional, Tuple
30
+
31
+ import torch
32
+ import torch.nn as nn
33
+ import torch.nn.functional as F
34
+
35
+ from datasets import load_dataset, DatasetDict, VerificationMode
36
+ from transformers import (
37
+ HfArgumentParser,
38
+ Trainer,
39
+ set_seed,
40
+ TrainerCallback,
41
+ )
42
+ from transformers import TrainingArguments as HfTrainingArguments
43
+ from transformers.models.llama.modeling_llama import LlamaRMSNorm
44
+
45
+ from peft import LoraConfig, get_peft_model, TaskType
46
+
47
+ # VibeVoice imports
48
+ from vibevoice.modular.modeling_vibevoice import (
49
+ VibeVoiceModel,
50
+ VibeVoiceForConditionalGeneration,
51
+ SpeechConnector,
52
+ )
53
+ from vibevoice.modular.configuration_vibevoice import VibeVoiceConfig
54
+ from vibevoice.processor.vibevoice_processor import VibeVoiceProcessor
55
+
56
+ # Surgery imports — monkey-patch for Qwen3 support
57
+ try:
58
+ from vibevoice_surgery_colab import (
59
+ _patch_vibevoice_config_for_qwen3,
60
+ Qwen3SurgeryModule,
61
+ load_surgery_model,
62
+ QWEN3_HIDDEN_SIZE,
63
+ DIFFUSION_HIDDEN_SIZE,
64
+ SURGERY_LAYER_INDICES,
65
+ )
66
+ _patch_vibevoice_config_for_qwen3()
67
+ except ImportError:
68
+ raise ImportError(
69
+ "vibevoice_surgery_colab.py must be in the same directory. "
70
+ "This script depends on the surgery module definition and patch."
71
+ )
72
+
73
+ from data_vibevoice import VibeVoiceDataset, VibeVoiceCollator
74
+
75
+ logger = logging.getLogger(__name__)
76
+
77
+
78
+ # ============================================================================
79
+ # SECTION 1: Argument Dataclasses
80
+ # ============================================================================
81
+
82
+ @dataclass
83
+ class ModelArguments:
84
+ """Arguments for model loading and component configuration."""
85
+ model_name_or_path: Optional[str] = field(
86
+ default=None,
87
+ metadata={"help": "Path to the surgery model directory (saved by vibevoice_surgery_colab.py)"},
88
+ )
89
+ processor_name_or_path: Optional[str] = field(
90
+ default=None,
91
+ metadata={"help": "Path to processor dir. Defaults to model_name_or_path."},
92
+ )
93
+ cache_dir: Optional[str] = field(default=None)
94
+
95
+ # ── Freezing Strategy ──
96
+ freeze_llm: bool = field(
97
+ default=True,
98
+ metadata={"help": "Freeze the LLM (Qwen3) entirely. Set False for full fine-tune or LoRA."},
99
+ )
100
+ freeze_diffusion_head: bool = field(
101
+ default=True,
102
+ metadata={"help": "Freeze the Diffusion Head (prediction_head)."},
103
+ )
104
+ freeze_surgery_module: bool = field(
105
+ default=False,
106
+ metadata={"help": "Freeze the Surgery Module (2560→3584 bridge)."},
107
+ )
108
+ freeze_connectors: bool = field(
109
+ default=False,
110
+ metadata={"help": "Freeze acoustic and semantic connectors."},
111
+ )
112
+ freeze_acoustic_tokenizer: bool = field(default=True)
113
+ freeze_semantic_tokenizer: bool = field(default=True)
114
+ freeze_lm_head: bool = field(
115
+ default=True,
116
+ metadata={"help": "Freeze LM head. Should be True when LLM is frozen (tied weights)."},
117
+ )
118
+
119
+ # ── LoRA Configuration ──
120
+ lora_r: int = field(default=8)
121
+ lora_alpha: int = field(default=32)
122
+ lora_dropout: float = field(default=0.05)
123
+ lora_target_modules: str = field(
124
+ default="q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj",
125
+ metadata={"help": "Comma-separated LoRA target modules for LLM. Use 'none' to disable."},
126
+ )
127
+ lora_wrap_diffusion_head: bool = field(
128
+ default=False,
129
+ metadata={"help": "Apply LoRA to the Diffusion Head."},
130
+ )
131
+
132
+ # ── Fine-tune flags ──
133
+ train_diffusion_head: bool = field(
134
+ default=False,
135
+ metadata={"help": "Full fine-tune the Diffusion Head (overrides freeze_diffusion_head)."},
136
+ )
137
+ train_connectors: bool = field(
138
+ default=True,
139
+ metadata={"help": "Full fine-tune acoustic/semantic connectors."},
140
+ )
141
+ train_surgery_module: bool = field(
142
+ default=True,
143
+ metadata={"help": "Full fine-tune the Surgery Module."},
144
+ )
145
+
146
+ # ── Advanced ──
147
+ layers_to_freeze: Optional[str] = field(
148
+ default=None,
149
+ metadata={"help": "Comma-separated indices of diffusion head params to freeze (e.g., '0,1,5')."},
150
+ )
151
+
152
+
153
+ @dataclass
154
+ class DataArguments:
155
+ """Arguments for dataset loading and preprocessing."""
156
+ dataset_name: Optional[str] = field(default=None)
157
+ dataset_config_name: Optional[str] = field(default=None)
158
+ train_split_name: str = field(default="train")
159
+ eval_split_name: Optional[str] = field(default="validation")
160
+ text_column_name: str = field(default="text")
161
+ audio_column_name: str = field(default="audio")
162
+ voice_prompts_column_name: Optional[str] = field(default="voice_prompts")
163
+ eval_split_size: float = field(default=0.0)
164
+ ignore_verifications: bool = field(default=False)
165
+ max_length: Optional[int] = field(default=None)
166
+ train_jsonl: Optional[str] = field(default=None)
167
+ validation_jsonl: Optional[str] = field(default=None)
168
+ voice_prompt_drop_rate: float = field(default=0.0)
169
+
170
+
171
+ @dataclass
172
+ class CustomTrainingArguments(HfTrainingArguments):
173
+ """Extended training arguments for VibeVoice surgery fine-tuning."""
174
+ ddpm_batch_mul: int = field(default=1)
175
+ ce_loss_weight: float = field(default=1.0)
176
+ diffusion_loss_weight: float = field(default=1.0)
177
+ gradient_clipping: bool = field(
178
+ default=False,
179
+ metadata={"help": "Enable gradient clipping with max_grad_norm."},
180
+ )
181
+ debug_ce_details: bool = field(default=False)
182
+ debug_ce_topk: int = field(default=5)
183
+ debug_ce_max_examples: int = field(default=1)
184
+ debug_ce_every_n_steps: int = field(default=200)
185
+ debug_save: bool = field(default=False)
186
+
187
+
188
+ # ============================================================================
189
+ # SECTION 2: LoRA Configuration Builders
190
+ # ============================================================================
191
+
192
+ def build_lora_config(args: ModelArguments) -> LoraConfig:
193
+ """Build LoRA config for the LLM."""
194
+ target_modules = [s.strip() for s in args.lora_target_modules.split(",") if s.strip()]
195
+ return LoraConfig(
196
+ r=args.lora_r,
197
+ lora_alpha=args.lora_alpha,
198
+ lora_dropout=args.lora_dropout,
199
+ bias="none",
200
+ task_type=TaskType.CAUSAL_LM,
201
+ target_modules=target_modules,
202
+ )
203
+
204
+
205
+ def build_head_lora_config(args: ModelArguments) -> LoraConfig:
206
+ """Build LoRA config for the Diffusion Head."""
207
+ target_modules = [
208
+ "noisy_images_proj", "cond_proj",
209
+ "gate_proj", "up_proj", "down_proj", "linear",
210
+ ]
211
+ return LoraConfig(
212
+ r=args.lora_r,
213
+ lora_alpha=args.lora_alpha,
214
+ lora_dropout=args.lora_dropout,
215
+ bias="none",
216
+ task_type=TaskType.FEATURE_EXTRACTION,
217
+ target_modules=target_modules,
218
+ )
219
+
220
+
221
+ # ============================================================================
222
+ # SECTION 3: Helper Functions
223
+ # ============================================================================
224
+
225
+ def mask_for_ce(
226
+ labels: torch.Tensor,
227
+ attention_mask: torch.Tensor,
228
+ acoustic_input_mask: torch.Tensor,
229
+ pad_id: int = -100,
230
+ ) -> torch.Tensor:
231
+ """Build CE loss mask: only predict text tokens, not acoustic placeholders."""
232
+ shifted = labels[:, 1:].contiguous()
233
+ base_mask = (
234
+ attention_mask[:, 1:].contiguous().eq(1)
235
+ if (attention_mask is not None and attention_mask.numel() > 0)
236
+ else torch.ones_like(shifted, dtype=torch.bool)
237
+ )
238
+ label_is_acoustic = acoustic_input_mask[:, 1:].contiguous()
239
+ final_mask = base_mask & (~label_is_acoustic)
240
+ out = shifted.clone()
241
+ out[~final_mask] = pad_id
242
+ return out
243
+
244
+
245
+ def _patch_acoustic_encode_for_legacy_indexing(model_obj, logger_):
246
+ """Patch acoustic tokenizer encode to return [[...]] for legacy indexing."""
247
+ try:
248
+ acoustic = getattr(getattr(model_obj, "model", model_obj), "acoustic_tokenizer", None)
249
+ if acoustic is None or not hasattr(acoustic, "encode"):
250
+ logger_.warning("No acoustic_tokenizer.encode() found to patch.")
251
+ return
252
+ base_encode = acoustic.encode
253
+
254
+ def encode_wrapped(*args, **kwargs):
255
+ out = base_encode(*args, **kwargs)
256
+ try:
257
+ _ = out[0][0]
258
+ return out
259
+ except Exception:
260
+ pass
261
+ if isinstance(out, dict):
262
+ for k in ("frames", "codes", "tokens", "latents", "hidden_states"):
263
+ if k in out:
264
+ return [[out[k]]]
265
+ if len(out) > 0:
266
+ return [[next(iter(out.values()))]]
267
+ for attr in ("frames", "codes", "tokens", "latents", "hidden_states"):
268
+ if hasattr(out, attr):
269
+ return [[getattr(out, attr)]]
270
+ try:
271
+ if isinstance(out, torch.Tensor):
272
+ return [[out]]
273
+ except Exception:
274
+ pass
275
+ return [[out]]
276
+
277
+ acoustic.encode = encode_wrapped
278
+ logger_.info("Patched acoustic_tokenizer.encode() for legacy indexing.")
279
+ except Exception as e:
280
+ logger_.warning(f"Failed to patch acoustic_tokenizer.encode(): {e}")
281
+
282
+
283
+ def _force_output_hidden_states(model):
284
+ """Monkey-patch the base model to always output hidden_states."""
285
+ original_forward = model.model.forward
286
+ import functools
287
+
288
+ @functools.wraps(original_forward)
289
+ def patched_forward(self, **kwargs):
290
+ kwargs["output_hidden_states"] = True
291
+ return original_forward(**kwargs)
292
+
293
+ model.model.forward = patched_forward.__get__(model.model, type(model.model))
294
+ logger.info("Patched VibeVoiceModel.forward to force output_hidden_states=True")
295
+
296
+
297
+ def print_model_summary(model, logger_):
298
+ """Print a comprehensive summary of trainable vs frozen parameters."""
299
+ components = {
300
+ "LLM (language_model)": getattr(model.model, "language_model", None),
301
+ "LM Head": getattr(model, "lm_head", None),
302
+ "Diffusion Head (prediction_head)": getattr(model.model, "prediction_head", None),
303
+ "Surgery Module": getattr(model.model, "surgery_module", None),
304
+ "Acoustic Connector": getattr(model.model, "acoustic_connector", None),
305
+ "Semantic Connector": getattr(model.model, "semantic_connector", None),
306
+ "Acoustic Tokenizer": getattr(model.model, "acoustic_tokenizer", None),
307
+ "Semantic Tokenizer": getattr(model.model, "semantic_tokenizer", None),
308
+ }
309
+
310
+ total_all = 0
311
+ total_train = 0
312
+ logger_.info("=" * 70)
313
+ logger_.info(" MODEL PARAMETER SUMMARY")
314
+ logger_.info("=" * 70)
315
+
316
+ for name, mod in components.items():
317
+ if mod is None:
318
+ logger_.info(f" {name:<40s} NOT FOUND")
319
+ continue
320
+ n_all = sum(p.numel() for p in mod.parameters())
321
+ n_train = sum(p.numel() for p in mod.parameters() if p.requires_grad)
322
+ pct = (100.0 * n_train / n_all) if n_all > 0 else 0.0
323
+ status = "TRAINABLE" if n_train > 0 else "FROZEN"
324
+ if n_train > 0 and n_train < n_all:
325
+ status = f"PARTIAL ({pct:.1f}%)"
326
+ logger_.info(f" {name:<40s} {n_all:>14,} total | {n_train:>14,} train | {status}")
327
+ total_all += n_all
328
+ total_train += n_train
329
+
330
+ logger_.info("-" * 70)
331
+ logger_.info(f" {'TOTAL':<40s} {total_all:>14,} total | {total_train:>14,} train")
332
+ logger_.info(f" Trainable percentage: {100.0 * total_train / max(total_all, 1):.2f}%")
333
+ logger_.info("=" * 70)
334
+
335
+
336
+ # ============================================================================
337
+ # SECTION 4: EMA Callback
338
+ # ============================================================================
339
+
340
+ class EmaCallback(TrainerCallback):
341
+ """Exponential Moving Average for the prediction head."""
342
+
343
+ def __init__(self, attr_path="model.prediction_head", decay=0.999, device="cuda"):
344
+ self.attr_path = attr_path
345
+ self.decay = float(decay)
346
+ self.device = torch.device(device)
347
+ self.shadow = None
348
+ self._orig = None
349
+
350
+ def _get_module(self, model):
351
+ mod = model
352
+ for name in self.attr_path.split('.'):
353
+ mod = getattr(mod, name)
354
+ return mod
355
+
356
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
357
+ head = self._get_module(model)
358
+ self.shadow = {
359
+ k: p.detach().to(self.device).clone()
360
+ for k, p in head.state_dict().items()
361
+ }
362
+
363
+ def on_step_end(self, args, state, control, model=None, **kwargs):
364
+ if self.shadow is None:
365
+ return
366
+ head = self._get_module(model)
367
+ with torch.no_grad():
368
+ for k, v in head.state_dict().items():
369
+ self.shadow[k].mul_(self.decay).add_(
370
+ v.detach().to(self.device), alpha=(1.0 - self.decay)
371
+ )
372
+
373
+ def _swap_in_ema(self, model):
374
+ head = self._get_module(model)
375
+ self._orig = copy.deepcopy(head.state_dict())
376
+ head.load_state_dict(self.shadow, strict=False)
377
+
378
+ def _swap_back(self, model):
379
+ if self._orig is None:
380
+ return
381
+ head = self._get_module(model)
382
+ head.load_state_dict(self._orig, strict=False)
383
+ self._orig = None
384
+
385
+ def on_evaluate(self, args, state, control, model=None, **kwargs):
386
+ self._swap_in_ema(model)
387
+
388
+ def on_evaluate_end(self, args, state, control, model=None, **kwargs):
389
+ self._swap_back(model)
390
+
391
+ def on_save(self, args, state, control, model=None, **kwargs):
392
+ self._swap_in_ema(model)
393
+
394
+ def on_save_end(self, args, state, control, model=None, **kwargs):
395
+ self._swap_back(model)
396
+
397
+ def on_train_end(self, args, state, control, model=None, **kwargs):
398
+ self._swap_in_ema(model)
399
+
400
+
401
+ # ============================================================================
402
+ # SECTION 5: LoRA Debug Callback
403
+ # ============================================================================
404
+
405
+ class LoRADebugCallback(TrainerCallback):
406
+ """Monitor LoRA parameter changes during training."""
407
+
408
+ def __init__(self, log_every_n_steps: int = 50):
409
+ self.log_every_n_steps = max(1, int(log_every_n_steps))
410
+ self.prev_param_norms: Dict[str, float] = {}
411
+ self.lora_param_names: List[str] = []
412
+
413
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
414
+ try:
415
+ if model is None:
416
+ return
417
+ named = dict(model.named_parameters())
418
+ self.lora_param_names = [
419
+ n for n in named if ("lora_A" in n or "lora_B" in n)
420
+ ]
421
+ for n in self.lora_param_names:
422
+ self.prev_param_norms[n] = float(named[n].data.norm().item())
423
+ total = len(self.lora_param_names)
424
+ req_grad = sum(1 for n in self.lora_param_names if named[n].requires_grad)
425
+ logger.info(f"LoRA debug: {total} LoRA params, {req_grad} trainable.")
426
+ except Exception as e:
427
+ logger.warning(f"LoRA debug init failed: {e}")
428
+
429
+ def on_step_end(self, args, state, control, model=None, **kwargs):
430
+ try:
431
+ if model is None or not self.lora_param_names:
432
+ return
433
+ step = int(getattr(state, "global_step", 0) or 0)
434
+ if step % self.log_every_n_steps != 0 and step != 1:
435
+ return
436
+ named = dict(model.named_parameters())
437
+ changed = 0
438
+ for n in self.lora_param_names:
439
+ p = named.get(n)
440
+ if p is None:
441
+ continue
442
+ prev = self.prev_param_norms.get(n, 0.0)
443
+ curr = float(p.data.norm().item())
444
+ if abs(curr - prev) > 1e-12:
445
+ changed += 1
446
+ self.prev_param_norms[n] = curr
447
+ logger.info(f"LoRA debug step {step}: {changed}/{len(self.lora_param_names)} params changed.")
448
+ except Exception as e:
449
+ logger.warning(f"LoRA debug step failed: {e}")
450
+
451
+
452
+ # ============================================================================
453
+ # SECTION 6: Custom Trainer with Surgery-aware Forward
454
+ # ============================================================================
455
+
456
+ class VibeVoiceSurgeryTrainer(Trainer):
457
+ """
458
+ Custom Trainer for VibeVoice Surgery model.
459
+
460
+ Key modification: When a surgery_module exists, condition features for
461
+ the diffusion head are projected through the Surgery Module (2560→3584)
462
+ before being fed to prediction_head.
463
+
464
+ Also handles:
465
+ - Dual loss (CE + Diffusion)
466
+ - Semantic tensor dtype alignment
467
+ - Diagnostics logging
468
+ """
469
+
470
+ def compute_loss(
471
+ self,
472
+ model: VibeVoiceForConditionalGeneration,
473
+ inputs: Dict[str, Any],
474
+ return_outputs=False,
475
+ num_items_in_batch: Optional[int] = None,
476
+ ):
477
+ labels = inputs.get("input_ids")
478
+ attention_mask = inputs.get("attention_mask")
479
+ acoustic_input_mask = inputs.get("acoustic_input_mask")
480
+
481
+ # Align semantic tensor dtype
482
+ sem = inputs.get("speech_semantic_tensors", None)
483
+ try:
484
+ target_dtype = next(model.model.semantic_connector.parameters()).dtype
485
+ except Exception:
486
+ target_dtype = model.get_input_embeddings().weight.dtype
487
+
488
+ if sem is None:
489
+ sm = inputs.get("speech_masks")
490
+ if sm is not None:
491
+ sem_dim = getattr(model.config, "semantic_vae_dim", 128)
492
+ inputs["speech_semantic_tensors"] = torch.zeros(
493
+ sm.size(0), sm.size(1), sem_dim,
494
+ dtype=target_dtype, device=sm.device,
495
+ )
496
+ elif isinstance(sem, torch.Tensor):
497
+ inputs["speech_semantic_tensors"] = sem.to(dtype=target_dtype)
498
+
499
+ # ── Forward through model ──
500
+ outputs = model(
501
+ input_ids=inputs.get("input_ids"),
502
+ attention_mask=attention_mask,
503
+ speech_tensors=inputs.get("speech_tensors"),
504
+ speech_masks=inputs.get("speech_masks"),
505
+ speech_semantic_tensors=inputs.get("speech_semantic_tensors"),
506
+ acoustic_input_mask=acoustic_input_mask,
507
+ acoustic_loss_mask=inputs.get("acoustic_loss_mask"),
508
+ speeches_loss_input=inputs.get("speeches_loss_input"),
509
+ ddpm_batch_mul=getattr(self.args, "ddpm_batch_mul", 1),
510
+ output_hidden_states=True, # Required for surgery module
511
+ )
512
+
513
+ # ── CE Loss ──
514
+ logits = outputs.logits
515
+ ce_labels = mask_for_ce(labels, attention_mask, acoustic_input_mask, pad_id=-100)
516
+ shift_logits = logits[:, :-1, :].contiguous()
517
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
518
+ ce_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), ce_labels.view(-1))
519
+
520
+ # ── Diffusion Loss (Surgery-aware) ──
521
+ # The model's forward() computes diffusion_loss internally.
522
+ # For surgery models, we need to recompute with Surgery Module applied.
523
+ has_surgery = hasattr(model.model, "surgery_module")
524
+
525
+ if has_surgery and hasattr(outputs, "hidden_states") and outputs.hidden_states is not None:
526
+ # Recompute diffusion loss with surgery-projected conditions
527
+ diffusion_loss = self._compute_surgery_diffusion_loss(
528
+ model, inputs, outputs, acoustic_input_mask
529
+ )
530
+ else:
531
+ diffusion_loss = (
532
+ outputs.diffusion_loss
533
+ if outputs.diffusion_loss is not None
534
+ else torch.tensor(0.0, device=ce_loss.device)
535
+ )
536
+
537
+ # ── Combined Loss ──
538
+ total = (
539
+ getattr(self.args, "ce_loss_weight", 1.0) * ce_loss
540
+ + getattr(self.args, "diffusion_loss_weight", 1.0) * diffusion_loss
541
+ )
542
+
543
+ # ── Logging ──
544
+ try:
545
+ prefix = "train" if model.training else "eval"
546
+ self.log({
547
+ f"{prefix}/ce_loss": ce_loss.detach().item(),
548
+ f"{prefix}/diffusion_loss": (
549
+ diffusion_loss.detach().item()
550
+ if isinstance(diffusion_loss, torch.Tensor)
551
+ else float(diffusion_loss)
552
+ ),
553
+ })
554
+ if hasattr(self, "optimizer") and self.optimizer is not None:
555
+ if len(self.optimizer.param_groups) > 0:
556
+ lr_val = self.optimizer.param_groups[0].get("lr")
557
+ if lr_val is not None:
558
+ self.log({"train/learning_rate_real": float(lr_val)})
559
+ except Exception:
560
+ pass
561
+
562
+ return (total, outputs) if return_outputs else total
563
+
564
+ def _compute_surgery_diffusion_loss(
565
+ self,
566
+ model,
567
+ inputs,
568
+ outputs,
569
+ acoustic_input_mask,
570
+ ):
571
+ """
572
+ Compute diffusion loss using Surgery Module to project hidden states
573
+ from Qwen3 hidden_size (2560) to diffusion head hidden_size (3584).
574
+ """
575
+ speech_tensors = inputs.get("speech_tensors")
576
+ speech_masks = inputs.get("speech_masks")
577
+ acoustic_loss_mask = inputs.get("acoustic_loss_mask")
578
+ speeches_loss_input = inputs.get("speeches_loss_input")
579
+ ddpm_batch_mul = getattr(self.args, "ddpm_batch_mul", 1)
580
+
581
+ if speech_tensors is None or acoustic_loss_mask is None:
582
+ return sum(p.sum() for p in model.model.prediction_head.parameters()) * 0.0
583
+
584
+ if acoustic_loss_mask.sum().item() == 0:
585
+ return sum(p.sum() for p in model.model.prediction_head.parameters()) * 0.0
586
+
587
+ hidden_states = outputs.last_hidden_state
588
+
589
+ # Get ground truth acoustic features (64-dim latents)
590
+ x = model.get_input_embeddings()(inputs["input_ids"])
591
+ with torch.no_grad():
592
+ speech_all_features, _ = model.forward_speech_features(
593
+ speech_tensors=speech_tensors.type_as(x),
594
+ speech_masks=speech_masks,
595
+ return_unmask=True,
596
+ )
597
+ speech_features = speech_all_features[speeches_loss_input & speech_masks]
598
+
599
+ # Build condition from hidden states + Surgery Module
600
+ cond_mask = torch.zeros_like(acoustic_loss_mask, dtype=torch.bool)
601
+ cond_mask[:, :-1] = acoustic_loss_mask[:, 1:]
602
+ cond_mask[:, 0] = False
603
+ condition_features = hidden_states[cond_mask]
604
+
605
+ # Apply Surgery Module: 2560 → 3584
606
+ condition_features = model.model.surgery_module(condition_features)
607
+
608
+ speech_len, latent_size = speech_features.shape
609
+ noise = torch.randn(
610
+ (speech_len * ddpm_batch_mul, latent_size),
611
+ device=hidden_states.device,
612
+ dtype=hidden_states.dtype,
613
+ )
614
+ timesteps = torch.multinomial(
615
+ torch.ones(model.config.diffusion_head_config.ddpm_num_steps),
616
+ speech_len * ddpm_batch_mul,
617
+ replacement=True,
618
+ ).to(hidden_states.device)
619
+
620
+ speech_features_rep = speech_features.repeat_interleave(ddpm_batch_mul, dim=0)
621
+ condition_features_rep = condition_features.repeat_interleave(ddpm_batch_mul, dim=0)
622
+
623
+ noisy_speech = model.model.noise_scheduler.add_noise(speech_features_rep, noise, timesteps)
624
+ model_output = model.model.prediction_head(noisy_speech, timesteps.type_as(x), condition_features_rep)
625
+
626
+ prediction_type = model.config.diffusion_head_config.prediction_type
627
+ if prediction_type == "epsilon":
628
+ target = noise
629
+ elif prediction_type == "v_prediction":
630
+ target = model.model.noise_scheduler.get_velocity(speech_features_rep, noise, timesteps)
631
+ else:
632
+ raise NotImplementedError(f"Prediction type {prediction_type} not implemented")
633
+
634
+ loss = F.mse_loss(model_output.float(), target.float(), reduction="sum")
635
+ if latent_size > 0 and ddpm_batch_mul > 0:
636
+ loss = loss / latent_size / ddpm_batch_mul / max(speech_len, 1)
637
+ return loss
638
+
639
+ def _save(self, output_dir: Optional[str] = None, state_dict=None):
640
+ """Save LoRA adapters, connectors, surgery module, and diffusion head."""
641
+ try:
642
+ target_dir = output_dir or self.args.output_dir
643
+ lora_out = os.path.join(target_dir, "lora")
644
+ os.makedirs(lora_out, exist_ok=True)
645
+
646
+ # LLM LoRA adapters
647
+ lm = getattr(self.model.model, "language_model", None)
648
+ if hasattr(lm, "save_pretrained"):
649
+ lm.save_pretrained(lora_out)
650
+
651
+ # Diffusion Head LoRA adapters
652
+ ph = getattr(self.model.model, "prediction_head", None)
653
+ if hasattr(ph, "save_pretrained"):
654
+ ph_dir = os.path.join(lora_out, "diffusion_head")
655
+ os.makedirs(ph_dir, exist_ok=True)
656
+ ph.save_pretrained(ph_dir)
657
+
658
+ # Full diffusion head state_dict
659
+ if ph is not None and hasattr(ph, "state_dict"):
660
+ sd = ph.state_dict()
661
+ torch.save(sd, os.path.join(lora_out, "diffusion_head_full.bin"))
662
+
663
+ # Acoustic Connector
664
+ ac = getattr(self.model.model, "acoustic_connector", None)
665
+ if ac is not None:
666
+ ac_dir = os.path.join(lora_out, "acoustic_connector")
667
+ os.makedirs(ac_dir, exist_ok=True)
668
+ torch.save(ac.state_dict(), os.path.join(ac_dir, "pytorch_model.bin"))
669
+
670
+ # Semantic Connector
671
+ se = getattr(self.model.model, "semantic_connector", None)
672
+ if se is not None:
673
+ se_dir = os.path.join(lora_out, "semantic_connector")
674
+ os.makedirs(se_dir, exist_ok=True)
675
+ torch.save(se.state_dict(), os.path.join(se_dir, "pytorch_model.bin"))
676
+
677
+ # Surgery Module
678
+ sm = getattr(self.model.model, "surgery_module", None)
679
+ if sm is not None:
680
+ sm_dir = os.path.join(lora_out, "surgery_module")
681
+ os.makedirs(sm_dir, exist_ok=True)
682
+ torch.save(sm.state_dict(), os.path.join(sm_dir, "pytorch_model.bin"))
683
+ logger.info(f"Saved Surgery Module to {sm_dir}")
684
+
685
+ except Exception as e:
686
+ logger.warning(f"Failed to save custom assets: {e}")
687
+
688
+
689
+ # ============================================================================
690
+ # SECTION 7: Main Function
691
+ # ============================================================================
692
+
693
+ def main() -> None:
694
+ parser = HfArgumentParser((ModelArguments, DataArguments, CustomTrainingArguments))
695
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
696
+
697
+ logging.basicConfig(
698
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
699
+ datefmt="%m/%d/%Y %H:%M:%S",
700
+ level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN,
701
+ )
702
+ logger.info("Training parameters: %s", training_args)
703
+ set_seed(training_args.seed)
704
+
705
+ # ── Gradient Clipping ──
706
+ if not getattr(training_args, "gradient_clipping", False):
707
+ training_args.max_grad_norm = 0.0
708
+ logger.info("Gradient clipping disabled. Use --gradient_clipping to enable.")
709
+ else:
710
+ if not training_args.max_grad_norm or training_args.max_grad_norm <= 0:
711
+ training_args.max_grad_norm = 1.0
712
+ logger.info(f"Gradient clipping: max_grad_norm={training_args.max_grad_norm}")
713
+
714
+ # ── Load Processor ──
715
+ processor_path = model_args.processor_name_or_path or model_args.model_name_or_path
716
+ if processor_path is None:
717
+ raise ValueError("--model_name_or_path must be provided")
718
+ processor = VibeVoiceProcessor.from_pretrained(processor_path)
719
+
720
+ tok = processor.tokenizer
721
+ for required in ["speech_start_id", "speech_diffusion_id", "speech_end_id"]:
722
+ if not hasattr(tok, required) or getattr(tok, required) is None:
723
+ raise RuntimeError(f"Tokenizer missing required special id: {required}")
724
+
725
+ # ── Load Surgery Model ──
726
+ if model_args.model_name_or_path is None:
727
+ raise ValueError("--model_name_or_path is required")
728
+
729
+ dtype = torch.float32
730
+ if training_args.bf16:
731
+ dtype = torch.bfloat16
732
+ elif getattr(training_args, "fp16", False):
733
+ dtype = torch.float16
734
+
735
+ logger.info(f"Loading surgery model from {model_args.model_name_or_path}...")
736
+ logger.info(f" Dtype: {dtype}")
737
+
738
+ # Load using the surgery model loader (handles device_map, surgery module, patches)
739
+ surgery_model = load_surgery_model(
740
+ model_args.model_name_or_path,
741
+ dtype=dtype,
742
+ device_map="cpu", # Load on CPU first for weight manipulation
743
+ )
744
+
745
+ _patch_acoustic_encode_for_legacy_indexing(surgery_model, logger)
746
+ processor.semantic_tokenizer = getattr(surgery_model.model, "semantic_tokenizer", None)
747
+
748
+ # ── Verify Surgery Module ──
749
+ has_surgery = hasattr(surgery_model.model, "surgery_module")
750
+ if has_surgery:
751
+ sm = surgery_model.model.surgery_module
752
+ logger.info(f"Surgery Module found: {sm.extra_repr()}")
753
+ else:
754
+ logger.warning("No Surgery Module found! This may be an unsurgeried model.")
755
+
756
+ # ── Verify Dimensions ──
757
+ lm_hidden = surgery_model.config.decoder_config.hidden_size
758
+ dh_hidden = surgery_model.config.diffusion_head_config.hidden_size
759
+ logger.info(f" LLM hidden_size: {lm_hidden}")
760
+ logger.info(f" Diffusion head hidden_size: {dh_hidden}")
761
+ if has_surgery:
762
+ logger.info(f" Surgery Module: {lm_hidden} → {dh_hidden}")
763
+
764
+ # ── Tie LM Head ──
765
+ try:
766
+ emb = surgery_model.get_input_embeddings()
767
+ head = surgery_model.get_output_embeddings()
768
+ if hasattr(emb, "weight") and hasattr(head, "weight"):
769
+ if emb.weight.shape == head.weight.shape and emb.weight.data_ptr() != head.weight.data_ptr():
770
+ with torch.no_grad():
771
+ head.weight = emb.weight
772
+ logger.info("Force-tied LM head to embed_tokens.")
773
+ except Exception as e:
774
+ logger.warning(f"Force-tie LM head failed: {e}")
775
+
776
+ # ── Disable Cache ──
777
+ if hasattr(surgery_model.config, "use_cache") and training_args.do_train:
778
+ surgery_model.config.use_cache = False
779
+
780
+ # ── Force output_hidden_states ──
781
+ _force_output_hidden_states(surgery_model)
782
+
783
+ # ======================================================================
784
+ # FREEZING STRATEGY
785
+ # ======================================================================
786
+ logger.info("\n" + "=" * 70)
787
+ logger.info(" CONFIGURING LAYER FREEZING")
788
+ logger.info("=" * 70)
789
+
790
+ # Step 1: Freeze ALL parameters
791
+ for _, p in surgery_model.named_parameters():
792
+ p.requires_grad = False
793
+ logger.info(" [1] All parameters frozen.")
794
+
795
+ # Step 2: Freeze tokenizers (always)
796
+ if model_args.freeze_acoustic_tokenizer and hasattr(surgery_model.model, "acoustic_tokenizer"):
797
+ for p in surgery_model.model.acoustic_tokenizer.parameters():
798
+ p.requires_grad = False
799
+ logger.info(" [2] Acoustic tokenizer: FROZEN")
800
+
801
+ if model_args.freeze_semantic_tokenizer and hasattr(surgery_model.model, "semantic_tokenizer"):
802
+ for p in surgery_model.model.semantic_tokenizer.parameters():
803
+ p.requires_grad = False
804
+ logger.info(" [2] Semantic tokenizer: FROZEN")
805
+
806
+ # Step 3: LoRA wrap LLM
807
+ tm_lower = [s.strip().lower() for s in model_args.lora_target_modules.split(",") if s.strip()]
808
+ skip_lm_lora = (len(tm_lower) == 0) or all(
809
+ t in ("none", "off", "disable", "disabled") for t in tm_lower
810
+ )
811
+
812
+ if not skip_lm_lora and not model_args.freeze_llm:
813
+ lora_cfg = build_lora_config(model_args)
814
+ surgery_model.model.language_model = get_peft_model(
815
+ surgery_model.model.language_model, lora_cfg
816
+ )
817
+ logger.info(f" [3] LLM wrapped with LoRA (r={model_args.lora_r}, alpha={model_args.lora_alpha})")
818
+ elif model_args.freeze_llm:
819
+ logger.info(" [3] LLM: FROZEN (no LoRA)")
820
+ else:
821
+ logger.info(" [3] LLM LoRA: SKIPPED (target_modules=none)")
822
+
823
+ # Step 4: Re-enable trainable params
824
+ if not skip_lm_lora and not model_args.freeze_llm:
825
+ for n, p in surgery_model.model.language_model.named_parameters():
826
+ if "lora_A" in n or "lora_B" in n:
827
+ p.requires_grad = True
828
+ logger.info(" [4] LLM LoRA params: ENABLED")
829
+
830
+ # Step 5: Diffusion Head
831
+ if model_args.train_diffusion_head:
832
+ for p in surgery_model.model.prediction_head.parameters():
833
+ p.requires_grad = True
834
+ logger.info(" [5] Diffusion Head: FULL TRAIN")
835
+ elif model_args.lora_wrap_diffusion_head:
836
+ # LoRA wrap diffusion head
837
+ class _HeadShim(nn.Module):
838
+ def __init__(self, base):
839
+ super().__init__()
840
+ self.base = base
841
+
842
+ def forward(self, *args, **kwargs):
843
+ if len(args) >= 3:
844
+ noisy_images, timesteps, condition = args[:3]
845
+ else:
846
+ noisy_images = kwargs.get("noisy_images")
847
+ timesteps = kwargs.get("timesteps")
848
+ condition = kwargs.get("condition")
849
+ return self.base(noisy_images, timesteps, condition)
850
+
851
+ try:
852
+ shim = _HeadShim(surgery_model.model.prediction_head)
853
+ surgery_model.model.prediction_head = get_peft_model(shim, build_head_lora_config(model_args))
854
+ for n, p in surgery_model.model.prediction_head.named_parameters():
855
+ if "lora_A" in n or "lora_B" in n:
856
+ p.requires_grad = True
857
+ logger.info(" [5] Diffusion Head: LoRA WRAPPED")
858
+ except Exception as e:
859
+ logger.warning(f" [5] Diffusion Head LoRA failed: {e}")
860
+ elif model_args.freeze_diffusion_head:
861
+ logger.info(" [5] Diffusion Head: FROZEN")
862
+ else:
863
+ for p in surgery_model.model.prediction_head.parameters():
864
+ p.requires_grad = True
865
+ logger.info(" [5] Diffusion Head: FULL TRAIN (default unfrozen)")
866
+
867
+ # Step 6: Specific diffusion head layer freezing
868
+ if model_args.layers_to_freeze and hasattr(surgery_model.model, "prediction_head"):
869
+ head_params = list(surgery_model.model.prediction_head.named_parameters())
870
+ try:
871
+ indices = {int(x.strip()) for x in model_args.layers_to_freeze.split(",") if x.strip()}
872
+ frozen = 0
873
+ for i, (name, param) in enumerate(head_params):
874
+ if i in indices:
875
+ param.requires_grad = False
876
+ frozen += 1
877
+ logger.info(f" Froze diffusion head param [{i}]: {name}")
878
+ logger.info(f" [6] Froze {frozen} diffusion head params by index.")
879
+ except Exception as e:
880
+ logger.error(f" [6] layers_to_freeze parse error: {e}")
881
+
882
+ # Step 7: Surgery Module
883
+ if hasattr(surgery_model.model, "surgery_module"):
884
+ if model_args.freeze_surgery_module:
885
+ for p in surgery_model.model.surgery_module.parameters():
886
+ p.requires_grad = False
887
+ logger.info(" [7] Surgery Module: FROZEN")
888
+ else:
889
+ for p in surgery_model.model.surgery_module.parameters():
890
+ p.requires_grad = True
891
+ logger.info(" [7] Surgery Module: TRAINABLE")
892
+
893
+ # Step 8: Connectors
894
+ if model_args.train_connectors:
895
+ if hasattr(surgery_model.model, "acoustic_connector"):
896
+ for p in surgery_model.model.acoustic_connector.parameters():
897
+ p.requires_grad = True
898
+ if hasattr(surgery_model.model, "semantic_connector"):
899
+ for p in surgery_model.model.semantic_connector.parameters():
900
+ p.requires_grad = True
901
+ logger.info(" [8] Connectors: TRAINABLE")
902
+ elif model_args.freeze_connectors:
903
+ logger.info(" [8] Connectors: FROZEN")
904
+ else:
905
+ # Default: train connectors
906
+ if hasattr(surgery_model.model, "acoustic_connector"):
907
+ for p in surgery_model.model.acoustic_connector.parameters():
908
+ p.requires_grad = True
909
+ if hasattr(surgery_model.model, "semantic_connector"):
910
+ for p in surgery_model.model.semantic_connector.parameters():
911
+ p.requires_grad = True
912
+ logger.info(" [8] Connectors: TRAINABLE (default)")
913
+
914
+ # Step 9: Freeze embedding + LM head
915
+ try:
916
+ emb = surgery_model.get_input_embeddings()
917
+ if hasattr(emb, "weight"):
918
+ emb.weight.requires_grad_(False)
919
+ head = surgery_model.get_output_embeddings()
920
+ if head is not None and hasattr(head, "weight"):
921
+ if model_args.freeze_lm_head:
922
+ head.weight.requires_grad_(False)
923
+ logger.info(" [9] LM Head: FROZEN")
924
+ else:
925
+ logger.info(" [9] LM Head: TRAINABLE (weight-tied with embeddings)")
926
+ except Exception as e:
927
+ logger.warning(f" [9] Embedding/head freeze failed: {e}")
928
+
929
+ # ── Print Summary ──
930
+ print_model_summary(surgery_model, logger)
931
+
932
+ # ── Move to GPU ──
933
+ if torch.cuda.device_count() > 1:
934
+ logger.info(f"Using {torch.cuda.device_count()} GPUs with DataParallel")
935
+ surgery_model = nn.DataParallel(surgery_model)
936
+ else:
937
+ device = torch.device("cuda:0")
938
+ surgery_model = surgery_model.to(device)
939
+ logger.info(f"Using single GPU: {device}")
940
+
941
+ # ======================================================================
942
+ # DATASETS
943
+ # ======================================================================
944
+
945
+ # Preprocessed data support
946
+ class PreprocessedBatchDataset:
947
+ def __init__(self, preprocessed_file: str):
948
+ self.data = torch.load(preprocessed_file, map_location="cpu")
949
+ logger.info(f"Loaded {len(self.data)} preprocessed batches from {preprocessed_file}")
950
+
951
+ def __len__(self):
952
+ return len(self.data)
953
+
954
+ def __getitem__(self, idx):
955
+ return self.data[idx]
956
+
957
+ class PreprocessedBatchSubset:
958
+ def __init__(self, dataset, indices):
959
+ self.dataset = dataset
960
+ self.indices = indices
961
+
962
+ def __len__(self):
963
+ return len(self.indices)
964
+
965
+ def __getitem__(self, idx):
966
+ return self.dataset[self.indices[idx]]
967
+
968
+ class PreprocessedBatchCollator:
969
+ def __call__(self, batch):
970
+ if not batch:
971
+ return {}
972
+ result = {}
973
+ for key in batch[0].keys():
974
+ tensors = [b[key] for b in batch if b[key] is not None]
975
+ if tensors and isinstance(tensors[0], torch.Tensor):
976
+ result[key] = torch.cat(tensors, dim=0)
977
+ else:
978
+ result[key] = tensors[0] if tensors else None
979
+ return result
980
+
981
+ preprocessed_dir = os.path.join(training_args.output_dir, "preprocessed")
982
+ preprocessed_file = os.path.join(preprocessed_dir, "preprocessed_batches.pt")
983
+
984
+ if os.path.exists(preprocessed_file):
985
+ logger.info(f"Loading preprocessed data from {preprocessed_file}")
986
+ preprocessed_data = PreprocessedBatchDataset(preprocessed_file)
987
+ train_dataset = preprocessed_data
988
+ eval_dataset = None
989
+
990
+ if training_args.do_eval and data_args.eval_split_size and data_args.eval_split_size > 0 and len(preprocessed_data) > 1:
991
+ num_eval = max(1, int(len(preprocessed_data) * data_args.eval_split_size))
992
+ num_train = len(preprocessed_data) - num_eval
993
+ indices = list(range(len(preprocessed_data)))
994
+ random.Random(training_args.seed).shuffle(indices)
995
+ train_dataset = PreprocessedBatchSubset(preprocessed_data, indices[:num_train])
996
+ eval_dataset = PreprocessedBatchSubset(preprocessed_data, indices[num_train:])
997
+ else:
998
+ logger.info("Preprocessed data not found, loading from raw JSONL/HF datasets")
999
+ verification_mode = VerificationMode.NO_CHECKS if data_args.ignore_verifications else VerificationMode.BASIC_CHECKS
1000
+ if data_args.train_jsonl is not None:
1001
+ data_files = {"train": data_args.train_jsonl}
1002
+ if data_args.validation_jsonl is not None:
1003
+ data_files["validation"] = data_args.validation_jsonl
1004
+ raw = load_dataset("json", data_files=data_files, verification_mode=verification_mode, cache_dir=model_args.cache_dir)
1005
+ else:
1006
+ if data_args.dataset_name is None:
1007
+ raise ValueError("Provide --dataset_name or --train_jsonl")
1008
+ raw = load_dataset(
1009
+ data_args.dataset_name,
1010
+ data_args.dataset_config_name,
1011
+ verification_mode=verification_mode,
1012
+ cache_dir=model_args.cache_dir,
1013
+ )
1014
+ train_ds = raw[data_args.train_split_name]
1015
+ eval_ds = None
1016
+ if training_args.do_eval:
1017
+ if data_args.eval_split_name and data_args.eval_split_name in raw:
1018
+ eval_ds = raw[data_args.eval_split_name]
1019
+ elif data_args.eval_split_size and data_args.eval_split_size > 0 and len(train_ds) > 1:
1020
+ split = train_ds.train_test_split(test_size=data_args.eval_split_size, seed=training_args.seed)
1021
+ train_ds, eval_ds = split["train"], split["test"]
1022
+
1023
+ train_dataset = VibeVoiceDataset(
1024
+ train_ds,
1025
+ text_column=data_args.text_column_name,
1026
+ audio_column=data_args.audio_column_name,
1027
+ voice_prompts_column=data_args.voice_prompts_column_name,
1028
+ )
1029
+ eval_dataset = None
1030
+ if eval_ds is not None:
1031
+ eval_dataset = VibeVoiceDataset(
1032
+ eval_ds,
1033
+ text_column=data_args.text_column_name,
1034
+ audio_column=data_args.audio_column_name,
1035
+ voice_prompts_column=data_args.voice_prompts_column_name,
1036
+ )
1037
+
1038
+ # ── Collator ──
1039
+ speech_compress_ratio = getattr(processor, "speech_tok_compress_ratio", 3200)
1040
+ semantic_dim = getattr(surgery_model.config if not isinstance(surgery_model, nn.DataParallel) else surgery_model.module.config, "semantic_vae_dim", 128)
1041
+ compute_semantics = hasattr(processor, "semantic_tokenizer") and processor.semantic_tokenizer is not None
1042
+
1043
+ if os.path.exists(preprocessed_file):
1044
+ data_collator = PreprocessedBatchCollator()
1045
+ else:
1046
+ data_collator = VibeVoiceCollator(
1047
+ processor=processor,
1048
+ max_length=data_args.max_length,
1049
+ speech_compress_ratio=speech_compress_ratio,
1050
+ semantic_vae_dim=semantic_dim,
1051
+ compute_semantics=compute_semantics,
1052
+ debug_checks=False,
1053
+ voice_prompt_drop_rate=data_args.voice_prompt_drop_rate,
1054
+ )
1055
+
1056
+ # ======================================================================
1057
+ # CAST TRAINABLE PARAMS TO FP32 (prevents GradScaler issues with fp16)
1058
+ # ======================================================================
1059
+ if getattr(training_args, "fp16", False) or getattr(training_args, "bf16", False):
1060
+ logger.info("Casting trainable parameters to float32 for GradScaler compatibility.")
1061
+ model_ref = surgery_model.module if isinstance(surgery_model, nn.DataParallel) else surgery_model
1062
+ for name, param in model_ref.named_parameters():
1063
+ if param.requires_grad:
1064
+ param.data = param.data.to(torch.float32)
1065
+
1066
+ # ======================================================================
1067
+ # BUILD TRAINER
1068
+ # ======================================================================
1069
+ ema_cb = EmaCallback(attr_path="model.prediction_head", decay=0.999, device="cuda")
1070
+
1071
+ trainer = VibeVoiceSurgeryTrainer(
1072
+ model=surgery_model,
1073
+ args=training_args,
1074
+ train_dataset=train_dataset,
1075
+ eval_dataset=eval_dataset,
1076
+ data_collator=data_collator,
1077
+ callbacks=[
1078
+ ema_cb,
1079
+ LoRADebugCallback(
1080
+ log_every_n_steps=int(getattr(training_args, "logging_steps", 50) or 50)
1081
+ ),
1082
+ ],
1083
+ )
1084
+
1085
+ # ── Debug Save ──
1086
+ if getattr(training_args, "debug_save", False):
1087
+ try:
1088
+ debug_dir = os.path.join(training_args.output_dir, "debug_initial")
1089
+ lora_out = os.path.join(debug_dir, "lora")
1090
+ os.makedirs(lora_out, exist_ok=True)
1091
+ logger.info(f"[debug_save] Saving initial components to {debug_dir}")
1092
+ model_ref = surgery_model.module if isinstance(surgery_model, nn.DataParallel) else surgery_model
1093
+ lm = getattr(model_ref.model, "language_model", None)
1094
+ if hasattr(lm, "save_pretrained"):
1095
+ lm.save_pretrained(lora_out)
1096
+ ph = getattr(model_ref.model, "prediction_head", None)
1097
+ if ph is not None and hasattr(ph, "state_dict"):
1098
+ torch.save(ph.state_dict(), os.path.join(lora_out, "diffusion_head_full.bin"))
1099
+ except Exception as e:
1100
+ logger.warning(f"[debug_save] Failed: {e}")
1101
+
1102
+ # ── Gradient Checkpointing ──
1103
+ if getattr(training_args, "gradient_checkpointing", False):
1104
+ try:
1105
+ model_ref = surgery_model.module if isinstance(surgery_model, nn.DataParallel) else surgery_model
1106
+ model_ref.gradient_checkpointing_enable()
1107
+ logger.info("Gradient checkpointing enabled.")
1108
+ except Exception:
1109
+ logger.warning("Failed to enable gradient checkpointing.")
1110
+
1111
+ # ======================================================================
1112
+ # RESUME FROM CHECKPOINT
1113
+ # ======================================================================
1114
+ if training_args.do_train and training_args.resume_from_checkpoint:
1115
+ checkpoint_path = None
1116
+ if isinstance(training_args.resume_from_checkpoint, bool) and training_args.resume_from_checkpoint:
1117
+ from transformers.trainer_utils import get_last_checkpoint
1118
+ checkpoint_path = get_last_checkpoint(training_args.output_dir)
1119
+ else:
1120
+ checkpoint_path = training_args.resume_from_checkpoint
1121
+
1122
+ if checkpoint_path and os.path.exists(checkpoint_path):
1123
+ lora_dir = os.path.join(checkpoint_path, "lora")
1124
+ if os.path.exists(lora_dir):
1125
+ logger.info(f"Resuming custom weights from {lora_dir}")
1126
+ model_ref = surgery_model.module if isinstance(surgery_model, nn.DataParallel) else surgery_model
1127
+
1128
+ # Load LLM LoRA
1129
+ lm = getattr(model_ref.model, "language_model", None)
1130
+ if hasattr(lm, "save_pretrained"):
1131
+ try:
1132
+ from peft import load_peft_weights, set_peft_model_state_dict
1133
+ adapters_weights = load_peft_weights(lora_dir)
1134
+ set_peft_model_state_dict(model_ref.model.language_model, adapters_weights)
1135
+ logger.info("Loaded LLM LoRA weights.")
1136
+ except Exception as e:
1137
+ logger.warning(f"Could not load LLM LoRA: {e}")
1138
+
1139
+ # Load Diffusion Head
1140
+ ph_path = os.path.join(lora_dir, "diffusion_head_full.bin")
1141
+ if os.path.exists(ph_path) and hasattr(model_ref.model, "prediction_head"):
1142
+ try:
1143
+ model_ref.model.prediction_head.load_state_dict(
1144
+ torch.load(ph_path, map_location="cpu"), strict=False
1145
+ )
1146
+ logger.info("Loaded Diffusion Head weights.")
1147
+ except Exception as e:
1148
+ logger.warning(f"Failed to load Diffusion Head: {e}")
1149
+
1150
+ # Load Connectors
1151
+ for conn_name in ["acoustic_connector", "semantic_connector"]:
1152
+ conn_path = os.path.join(lora_dir, conn_name, "pytorch_model.bin")
1153
+ conn = getattr(model_ref.model, conn_name, None)
1154
+ if os.path.exists(conn_path) and conn is not None:
1155
+ try:
1156
+ conn.load_state_dict(torch.load(conn_path, map_location="cpu"))
1157
+ logger.info(f"Loaded {conn_name}.")
1158
+ except Exception as e:
1159
+ logger.warning(f"Failed to load {conn_name}: {e}")
1160
+
1161
+ # Load Surgery Module
1162
+ sm_path = os.path.join(lora_dir, "surgery_module", "pytorch_model.bin")
1163
+ sm = getattr(model_ref.model, "surgery_module", None)
1164
+ if os.path.exists(sm_path) and sm is not None:
1165
+ try:
1166
+ sm.load_state_dict(torch.load(sm_path, map_location="cpu"))
1167
+ logger.info("Loaded Surgery Module weights.")
1168
+ except Exception as e:
1169
+ logger.warning(f"Failed to load Surgery Module: {e}")
1170
+
1171
+ # ======================================================================
1172
+ # TRAIN
1173
+ # ======================================================================
1174
+ if training_args.do_train:
1175
+ trainer.train(resume_from_checkpoint=False)
1176
+
1177
+ # ── Save Final ──
1178
+ lora_out = os.path.join(training_args.output_dir, "lora")
1179
+ os.makedirs(lora_out, exist_ok=True)
1180
+ model_ref = surgery_model.module if isinstance(surgery_model, nn.DataParallel) else surgery_model
1181
+
1182
+ lm = getattr(model_ref.model, "language_model", None)
1183
+ if hasattr(lm, "save_pretrained"):
1184
+ lm.save_pretrained(lora_out)
1185
+
1186
+ ph = getattr(model_ref.model, "prediction_head", None)
1187
+ if hasattr(ph, "save_pretrained"):
1188
+ ph_dir = os.path.join(lora_out, "diffusion_head")
1189
+ os.makedirs(ph_dir, exist_ok=True)
1190
+ ph.save_pretrained(ph_dir)
1191
+ if ph is not None and hasattr(ph, "state_dict"):
1192
+ torch.save(ph.state_dict(), os.path.join(lora_out, "diffusion_head_full.bin"))
1193
+
1194
+ for conn_name in ["acoustic_connector", "semantic_connector"]:
1195
+ conn = getattr(model_ref.model, conn_name, None)
1196
+ if conn is not None:
1197
+ conn_dir = os.path.join(lora_out, conn_name)
1198
+ os.makedirs(conn_dir, exist_ok=True)
1199
+ torch.save(conn.state_dict(), os.path.join(conn_dir, "pytorch_model.bin"))
1200
+
1201
+ sm = getattr(model_ref.model, "surgery_module", None)
1202
+ if sm is not None:
1203
+ sm_dir = os.path.join(lora_out, "surgery_module")
1204
+ os.makedirs(sm_dir, exist_ok=True)
1205
+ torch.save(sm.state_dict(), os.path.join(sm_dir, "pytorch_model.bin"))
1206
+
1207
+ logger.info(f"All trained components saved to {lora_out}")
1208
+
1209
+ if training_args.do_eval and eval_dataset is not None:
1210
+ trainer.evaluate()
1211
+
1212
+
1213
+ if __name__ == "__main__":
1214
+ main()
VibeVoice-tpu/src/finetune_vibevoice_lora105.py ADDED
@@ -0,0 +1,1066 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # train_vibevoice_lora.py
2
+ import os
3
+ os.environ["CUDA_VISIBLE_DEVICES"] = "0"
4
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
5
+
6
+ import logging
7
+ import os
8
+ from dataclasses import dataclass, field
9
+ from typing import Any, Dict, List, Optional, Tuple
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.nn.functional as F
14
+ from datasets import load_dataset, DatasetDict, VerificationMode
15
+
16
+ from transformers import (
17
+ HfArgumentParser,
18
+ Trainer,
19
+ set_seed,
20
+ TrainerCallback,
21
+ )
22
+ from transformers import TrainingArguments as HfTrainingArguments
23
+
24
+ from peft import LoraConfig, get_peft_model, TaskType
25
+
26
+ from vibevoice.modular.modeling_vibevoice import VibeVoiceForConditionalGeneration
27
+ from vibevoice.modular.configuration_vibevoice import VibeVoiceConfig
28
+ from vibevoice.processor.vibevoice_processor import VibeVoiceProcessor
29
+
30
+ # Monkey-patch VibeVoiceConfig for Qwen3 support (must run before model loading)
31
+ try:
32
+ from vibevoice_surgery_colab import _patch_vibevoice_config_for_qwen3
33
+ _patch_vibevoice_config_for_qwen3()
34
+ except Exception:
35
+ # Surgery script may not be available; native Qwen3 support in configuration_vibevoice.py
36
+ pass
37
+
38
+ from data_vibevoice import VibeVoiceDataset, VibeVoiceCollator
39
+
40
+ logger = logging.getLogger(__name__)
41
+
42
+ # ================== SAMPLE CALLBACK UTILS ==================
43
+
44
+ import copy
45
+ import torch
46
+ from transformers import TrainerCallback
47
+
48
+ class EmaCallback(TrainerCallback):
49
+ def __init__(self, attr_path="model.prediction_head", decay=0.999, device="cuda"):
50
+ """
51
+ attr_path: where the head lives under self.model (Trainer wraps your VibeVoiceForConditionalGeneration)
52
+ decay: EMA decay (0.999 ~ stable, 0.9999 ~ very smooth, slower to adapt)
53
+ """
54
+ self.attr_path = attr_path
55
+ self.decay = float(decay)
56
+ self.device = torch.device(device)
57
+ self.shadow = None
58
+ self._orig = None # store non-EMA weights when we swap
59
+
60
+ def _get_module(self, model):
61
+ # Resolve dotted path like "model.prediction_head"
62
+ mod = model
63
+ for name in self.attr_path.split('.'):
64
+ mod = getattr(mod, name)
65
+ return mod
66
+
67
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
68
+ head = self._get_module(model)
69
+ self.shadow = {k: p.detach().to(self.device).clone()
70
+ for k, p in head.state_dict().items()}
71
+
72
+ def on_step_end(self, args, state, control, model=None, **kwargs):
73
+ if self.shadow is None: return
74
+ head = self._get_module(model)
75
+ with torch.no_grad():
76
+ for k, v in head.state_dict().items():
77
+ self.shadow[k].mul_(self.decay).add_(v.detach().to(self.device), alpha=(1.0 - self.decay))
78
+
79
+ # ---- Swap helpers ----
80
+ def _swap_in_ema(self, model):
81
+ head = self._get_module(model)
82
+ self._orig = copy.deepcopy(head.state_dict())
83
+ head.load_state_dict(self.shadow, strict=False)
84
+
85
+ def _swap_back(self, model):
86
+ if self._orig is None: return
87
+ head = self._get_module(model)
88
+ head.load_state_dict(self._orig, strict=False)
89
+ self._orig = None
90
+
91
+ def on_evaluate(self, args, state, control, model=None, **kwargs):
92
+ # use EMA during eval
93
+ self._swap_in_ema(model)
94
+
95
+ def on_evaluate_end(self, args, state, control, model=None, **kwargs):
96
+ self._swap_back(model)
97
+
98
+ def on_save(self, args, state, control, model=None, **kwargs):
99
+ # temporarily swap to EMA, let Trainer save, then swap back
100
+ self._swap_in_ema(model)
101
+
102
+ def on_save_end(self, args, state, control, model=None, **kwargs):
103
+ self._swap_back(model)
104
+
105
+ def on_train_end(self, args, state, control, model=None, **kwargs):
106
+ # final checkpoint: persist EMA
107
+ self._swap_in_ema(model)
108
+
109
+
110
+ @dataclass
111
+ class ModelArguments:
112
+ model_name_or_path: Optional[str] = field(
113
+ default=None, metadata={"help": "Path to VibeVoice base model with config.json"}
114
+ )
115
+ processor_name_or_path: Optional[str] = field(
116
+ default=None, metadata={"help": "Path to processor dir (preprocessor_config.json). Defaults to model path."}
117
+ )
118
+ cache_dir: Optional[str] = field(default=None)
119
+ freeze_acoustic_tokenizer: bool = field(default=True)
120
+ freeze_semantic_tokenizer: bool = field(default=True)
121
+ lora_r: int = field(default=8)
122
+ lora_alpha: int = field(default=32)
123
+ lora_dropout: float = field(default=0.05)
124
+ lora_target_modules: str = field(
125
+ default="q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj",
126
+ metadata={"help": "Comma-separated list of target module names in the LLM blocks"},
127
+ )
128
+ lora_wrap_diffusion_head: bool = field(default=False, metadata={"help": "Wrap diffusion head with PEFT LoRA"})
129
+ train_diffusion_head: bool = field(default=False, metadata={"help": "Train diffusion prediction head (full fine-tune)"})
130
+ train_connectors: bool = field(default=False, metadata={"help": "Train acoustic/semantic connectors (full fine-tune)"})
131
+ train_surgery_module: bool = field(default=False, metadata={"help": "Train surgery module (full fine-tune, NOT LoRA). For surgery models only."})
132
+ layers_to_freeze: Optional[str] = field(
133
+ default=None,
134
+ metadata={"help": "Comma-separated indices of diffusion head layers to freeze (e.g., '0,1,5,7,8')."}
135
+ )
136
+
137
+ @dataclass
138
+ class DataArguments:
139
+ dataset_name: Optional[str] = field(default=None, metadata={"help": "HF dataset name or 'json' with --train_jsonl for local files"})
140
+ dataset_config_name: Optional[str] = field(default=None)
141
+ train_split_name: str = field(default="train")
142
+ eval_split_name: Optional[str] = field(default="validation")
143
+ text_column_name: str = field(default="text")
144
+ audio_column_name: str = field(default="audio")
145
+ voice_prompts_column_name: Optional[str] = field(default="voice_prompts")
146
+ eval_split_size: float = field(default=0.0)
147
+ ignore_verifications: bool = field(default=False)
148
+ max_length: Optional[int] = field(default=None)
149
+ train_jsonl: Optional[str] = field(default=None, metadata={"help": "Path to local train JSONL with {text, audio, [voice_prompts]}"})
150
+ validation_jsonl: Optional[str] = field(default=None, metadata={"help": "Optional path to local validation JSONL"})
151
+ voice_prompt_drop_rate: float = field(
152
+ default=0.0,
153
+ metadata={"help": "Probability to drop conditioning voice prompt during training (0.0 keep always, 1.0 drop always)."},
154
+ )
155
+
156
+ @dataclass
157
+ class CustomTrainingArguments(HfTrainingArguments):
158
+ ddpm_batch_mul: int = field(default=1)
159
+ ce_loss_weight: float = field(default=1.0)
160
+ diffusion_loss_weight: float = field(default=1.0)
161
+ debug_ce_details: bool = field(default=False)
162
+ debug_ce_topk: int = field(default=5)
163
+ debug_ce_max_examples: int = field(default=1)
164
+ debug_ce_every_n_steps: int = field(default=200)
165
+ gradient_clipping: bool = field(
166
+ default=False,
167
+ metadata={"help": "Enable gradient clipping using max_grad_norm (set via --max_grad_norm, default 1.0). When False, disables clipping by forcing max_grad_norm=0.0."},
168
+ )
169
+ debug_save: bool = field(
170
+ default=False,
171
+ metadata={"help": "If set, saves model components BEFORE training starts, into output_dir/debug_initial."},
172
+ )
173
+
174
+ def build_lora_config(args: ModelArguments) -> LoraConfig:
175
+ target_modules = [s.strip() for s in args.lora_target_modules.split(",") if s.strip()]
176
+ return LoraConfig(
177
+ r=args.lora_r,
178
+ lora_alpha=args.lora_alpha,
179
+ lora_dropout=args.lora_dropout,
180
+ bias="none",
181
+ task_type=TaskType.CAUSAL_LM,
182
+ target_modules=target_modules,
183
+ )
184
+
185
+ def build_head_lora_config(args: ModelArguments) -> LoraConfig:
186
+ target_modules = ["noisy_images_proj","cond_proj","gate_proj","up_proj","down_proj","linear"]
187
+ return LoraConfig(
188
+ r=args.lora_r,
189
+ lora_alpha=args.lora_alpha,
190
+ lora_dropout=args.lora_dropout,
191
+ bias="none",
192
+ task_type=TaskType.FEATURE_EXTRACTION,
193
+ target_modules=target_modules,
194
+ )
195
+
196
+ def mask_for_ce(labels: torch.Tensor, attention_mask: torch.Tensor, acoustic_input_mask: torch.Tensor, pad_id: int = -100) -> torch.Tensor:
197
+ shifted = labels[:, 1:].contiguous()
198
+ base_mask = attention_mask[:, 1:].contiguous().eq(1) if (attention_mask is not None and attention_mask.numel() > 0) else torch.ones_like(shifted, dtype=torch.bool)
199
+ label_is_acoustic = acoustic_input_mask[:, 1:].contiguous()
200
+ final_mask = base_mask & (~label_is_acoustic)
201
+ out = shifted.clone()
202
+ out[~final_mask] = pad_id
203
+ return out
204
+
205
+ def _patch_acoustic_encode_for_legacy_indexing(model_obj, logger_):
206
+ try:
207
+ acoustic = getattr(getattr(model_obj, "model", model_obj), "acoustic_tokenizer", None)
208
+ if acoustic is None or not hasattr(acoustic, "encode"):
209
+ logger_.warning("No acoustic_tokenizer.encode() found to patch.")
210
+ return
211
+ base_encode = acoustic.encode
212
+ def encode_wrapped(*args, **kwargs):
213
+ out = base_encode(*args, **kwargs)
214
+ try:
215
+ _ = out[0][0]
216
+ return out
217
+ except Exception:
218
+ pass
219
+ if isinstance(out, dict):
220
+ for k in ("frames", "codes", "tokens", "latents", "hidden_states"):
221
+ if k in out:
222
+ return [[out[k]]]
223
+ if len(out) > 0:
224
+ return [[next(iter(out.values()))]]
225
+ for attr in ("frames", "codes", "tokens", "latents", "hidden_states"):
226
+ if hasattr(out, attr):
227
+ return [[getattr(out, attr)]]
228
+ try:
229
+ if isinstance(out, torch.Tensor):
230
+ return [[out]]
231
+ except Exception:
232
+ pass
233
+ return [[out]]
234
+ acoustic.encode = encode_wrapped
235
+ logger_.info("Patched acoustic_tokenizer.encode() to return [[...]] for legacy indexing.")
236
+ except Exception as e:
237
+ logger_.warning(f"Failed to patch acoustic_tokenizer.encode(): {e}")
238
+
239
+ def main() -> None:
240
+ parser = HfArgumentParser((ModelArguments, DataArguments, CustomTrainingArguments))
241
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
242
+
243
+ logging.basicConfig(
244
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
245
+ datefmt="%m/%d/%Y %H:%M:%S",
246
+ level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN,
247
+ )
248
+ logger.info("Training/evaluation parameters %s", training_args)
249
+ set_seed(training_args.seed)
250
+
251
+ # Configure gradient clipping
252
+ if not getattr(training_args, "gradient_clipping", False):
253
+ if hasattr(training_args, "max_grad_norm"):
254
+ training_args.max_grad_norm = 0.0
255
+ logger.info("Gradient clipping disabled (set max_grad_norm=0.0). Use --gradient_clipping to enable.")
256
+ else:
257
+ if (not hasattr(training_args, "max_grad_norm")) or training_args.max_grad_norm is None or training_args.max_grad_norm <= 0:
258
+ training_args.max_grad_norm = 1.0
259
+ logger.info(f"Gradient clipping enabled: max_grad_norm={training_args.max_grad_norm}")
260
+
261
+ # Load processor
262
+ processor_path = model_args.processor_name_or_path or model_args.model_name_or_path
263
+ if processor_path is None:
264
+ raise ValueError("--model_name_or_path (or --processor_name_or_path) must be provided")
265
+ processor: VibeVoiceProcessor = VibeVoiceProcessor.from_pretrained(processor_path)
266
+
267
+ # Required special tokens
268
+ tok = processor.tokenizer
269
+ for required in ["speech_start_id", "speech_diffusion_id", "speech_end_id"]:
270
+ if not hasattr(tok, required) or getattr(tok, required) is None:
271
+ raise RuntimeError(f"Tokenizer missing required special id: {required}")
272
+
273
+ # Load model
274
+ if model_args.model_name_or_path is None:
275
+ raise ValueError("--model_name_or_path is required to load VibeVoice base model")
276
+ dtype = torch.float32
277
+ if training_args.bf16:
278
+ dtype = torch.bfloat16
279
+ elif getattr(training_args, "fp16", False):
280
+ dtype = torch.float16
281
+ model = VibeVoiceForConditionalGeneration.from_pretrained(
282
+ model_args.model_name_or_path,
283
+ torch_dtype=dtype, device_map={"": 0},
284
+ )
285
+ _patch_acoustic_encode_for_legacy_indexing(model, logger)
286
+ processor.semantic_tokenizer = getattr(model.model, "semantic_tokenizer", None)
287
+
288
+ # Diagnostics: LM head tie
289
+ try:
290
+ in_emb_mod = model.get_input_embeddings()
291
+ out_emb_mod = model.get_output_embeddings()
292
+ in_w = getattr(in_emb_mod, "weight", None)
293
+ out_w = getattr(out_emb_mod, "weight", None)
294
+ shared_ptr = bool(in_w is not None and out_w is not None and in_w.data_ptr() == out_w.data_ptr())
295
+ values_equal = False
296
+ if in_w is not None and out_w is not None and in_w.shape == out_w.shape:
297
+ try:
298
+ values_equal = bool(torch.allclose(in_w, out_w))
299
+ except Exception:
300
+ values_equal = False
301
+ try:
302
+ tie_cfg = getattr(getattr(model.config, "decoder_config", model.config), "tie_word_embeddings", None)
303
+ except Exception:
304
+ tie_cfg = getattr(model.config, "tie_word_embeddings", None)
305
+ logger.info(f"LM head diagnostics -> shared_params={shared_ptr}, values_equal={values_equal}, tie_word_embeddings={tie_cfg}")
306
+ if out_w is not None:
307
+ logger.info(f"LM head requires_grad before freeze: {bool(out_w.requires_grad)}")
308
+ except Exception as e:
309
+ logger.warning(f"LM head tie diagnostics failed: {e}")
310
+
311
+ # Hard-tie LM head
312
+ try:
313
+ emb_module = model.get_input_embeddings()
314
+ head_module = model.get_output_embeddings()
315
+ if hasattr(emb_module, "weight") and hasattr(head_module, "weight"):
316
+ if emb_module.weight.shape == head_module.weight.shape and emb_module.weight.data_ptr() != head_module.weight.data_ptr():
317
+ with torch.no_grad():
318
+ head_module.weight = emb_module.weight
319
+ logger.info("Force-tied LM head weight to input embeddings (pointer share).")
320
+ except Exception as e:
321
+ logger.warning(f"Force-tie of LM head failed: {e}")
322
+
323
+ # Validate special IDs (info logs only)
324
+ try:
325
+ special_names = ["speech_start_id", "speech_diffusion_id", "speech_end_id"]
326
+ try:
327
+ vocab_size = int(getattr(model.config.decoder_config, "vocab_size", 0))
328
+ except Exception:
329
+ vocab_size = 0
330
+ in_emb_mod = model.get_input_embeddings()
331
+ out_emb_mod = model.get_output_embeddings()
332
+ in_w = getattr(in_emb_mod, "weight", None)
333
+ out_w = getattr(out_emb_mod, "weight", None)
334
+ for name in special_names:
335
+ val = getattr(tok, name, None)
336
+ exists = (val is not None)
337
+ in_range = (exists and isinstance(val, int) and 0 <= val < vocab_size)
338
+ equal_row = None
339
+ if in_range and in_w is not None and out_w is not None and in_w.shape == out_w.shape and in_w.size(0) > val:
340
+ try:
341
+ equal_row = bool(torch.allclose(in_w[val], out_w[val]))
342
+ except Exception:
343
+ equal_row = False
344
+ decoded_str = None
345
+ if exists and isinstance(val, int):
346
+ try:
347
+ decoded_str = tok.decode([val])
348
+ except Exception:
349
+ try:
350
+ decoded_str = tok.convert_ids_to_tokens(val)
351
+ except Exception:
352
+ decoded_str = "<decode_failed>"
353
+ logger.info(f"Special token check -> {name}={val}, decoded='{decoded_str}', exists={exists}, in_vocab_range={in_range}, emb_vs_head_row_equal={equal_row}")
354
+ except Exception as e:
355
+ logger.warning(f"Special token ID/row validation failed: {e}")
356
+
357
+ # Quick tokenizer diagnostics (optional)
358
+ try:
359
+ logger.info("=== TOKENIZER DIAGNOSTICS ===")
360
+ logger.info(f"Tokenizer class: {type(tok).__name__}")
361
+ logger.info(f"Tokenizer vocab_size: {tok.vocab_size}")
362
+ # tiny CE smoke test
363
+ with torch.no_grad():
364
+ simple_text = "The cat sat on the mat."
365
+ simple_ids = torch.tensor([tok.encode(simple_text, add_special_tokens=True)], device=model.device)
366
+ simple_mask = torch.ones_like(simple_ids)
367
+ x = model.get_input_embeddings()(simple_ids)
368
+ outputs = model.model(inputs_embeds=x, attention_mask=simple_mask, return_dict=True)
369
+ logits = model.lm_head(outputs.last_hidden_state)
370
+ shift_logits = logits[:, :-1, :].contiguous()
371
+ shift_labels = simple_ids[:, 1:].contiguous()
372
+ ce_loss = F.cross_entropy(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1), reduction='mean')
373
+ logger.info(f"Simple text CE loss: {ce_loss.item():.4f}")
374
+ except Exception as e:
375
+ logger.warning(f"Tokenizer diagnostics failed: {e}")
376
+
377
+ # Disable cache during training
378
+ if hasattr(model.config, "use_cache") and training_args.do_train:
379
+ model.config.use_cache = False
380
+
381
+ # Freeze tokenizers
382
+ if model_args.freeze_acoustic_tokenizer and hasattr(model.model, "acoustic_tokenizer"):
383
+ for p in model.model.acoustic_tokenizer.parameters():
384
+ p.requires_grad = False
385
+ if model_args.freeze_semantic_tokenizer and hasattr(model.model, "semantic_tokenizer"):
386
+ for p in model.model.semantic_tokenizer.parameters():
387
+ p.requires_grad = False
388
+
389
+ # LoRA wrap LLM (optional)
390
+ lora_cfg = build_lora_config(model_args)
391
+ tm_lower = [s.strip().lower() for s in model_args.lora_target_modules.split(",") if s.strip()]
392
+ skip_lm_lora = (len(tm_lower) == 0) or all(t in ("none", "off", "disable", "disabled") for t in tm_lower)
393
+ if not skip_lm_lora:
394
+ model.model.language_model = get_peft_model(model.model.language_model, lora_cfg)
395
+ else:
396
+ logger.info("Skipping LLM LoRA wrapping (lora_target_modules indicates none).")
397
+
398
+ try:
399
+ model.tie_weights()
400
+ except Exception:
401
+ pass
402
+
403
+ # Freeze all then enable trainable subsets
404
+ for _, p in model.named_parameters():
405
+ p.requires_grad = False
406
+
407
+ try:
408
+ for n, p in model.model.language_model.named_parameters():
409
+ if "lora_A" in n or "lora_B" in n:
410
+ p.requires_grad = True
411
+ except Exception:
412
+ logger.warning("Could not re-enable LoRA params on language_model.")
413
+
414
+ # Diffusion head LoRA wrapping (optional)
415
+ if getattr(model_args, "lora_wrap_diffusion_head", False) and hasattr(model.model, "prediction_head"):
416
+ class _HeadForwardShim(nn.Module):
417
+ def __init__(self, base: nn.Module): super().__init__(); self.base = base
418
+ def forward(self, *args, **kwargs):
419
+ if len(args) >= 3:
420
+ noisy_images, timesteps, condition = args[:3]
421
+ else:
422
+ noisy_images = kwargs.get("noisy_images")
423
+ timesteps = kwargs.get("timesteps")
424
+ condition = kwargs.get("condition")
425
+ return self.base(noisy_images, timesteps, condition)
426
+ try:
427
+ shim = _HeadForwardShim(model.model.prediction_head)
428
+ model.model.prediction_head = get_peft_model(shim, build_head_lora_config(model_args))
429
+ for n, p in model.model.prediction_head.named_parameters():
430
+ if "lora_A" in n or "lora_B" in n:
431
+ p.requires_grad = True
432
+ except Exception as e:
433
+ logger.warning(f"Could not LoRA-wrap diffusion head: {e}")
434
+
435
+ # Train full diffusion head (optional)
436
+ if getattr(model_args, "train_diffusion_head", False) and hasattr(model.model, "prediction_head"):
437
+ for p in model.model.prediction_head.parameters():
438
+ p.requires_grad = True
439
+
440
+ # Freeze diffusion head layers (optional)
441
+ if model_args.layers_to_freeze is not None and hasattr(model.model, "prediction_head"):
442
+ head_params = list(model.model.prediction_head.named_parameters())
443
+ try:
444
+ indices_to_freeze = {int(x.strip()) for x in model_args.layers_to_freeze.split(',') if x.strip()}
445
+ frozen_count = 0
446
+ for i, (name, param) in enumerate(head_params):
447
+ if i in indices_to_freeze:
448
+ param.requires_grad = False
449
+ frozen_count += 1
450
+ logger.info(f"Froze layer [{i}]: {name}")
451
+ logger.info(f"Successfully froze {frozen_count} parameter groups in the diffusion head.")
452
+ except Exception as e:
453
+ logger.error(f"Could not parse --layers_to_freeze: {e}")
454
+ raise
455
+
456
+ # Connectors
457
+ if getattr(model_args, "train_connectors", False):
458
+ if hasattr(model.model, "acoustic_connector"):
459
+ for p in model.model.acoustic_connector.parameters():
460
+ p.requires_grad = True
461
+ if hasattr(model.model, "semantic_connector"):
462
+ for p in model.model.semantic_connector.parameters():
463
+ p.requires_grad = True
464
+ else:
465
+ if hasattr(model.model, "acoustic_connector"):
466
+ for p in model.model.acoustic_connector.parameters():
467
+ p.requires_grad = False
468
+ if hasattr(model.model, "semantic_connector"):
469
+ for p in model.model.semantic_connector.parameters():
470
+ p.requires_grad = False
471
+
472
+ # Surgery Module — full fine-tune (NOT LoRA)
473
+ # This is for models that underwent surgery (Qwen3 replacement).
474
+ # The surgery module bridges Qwen3 hidden_size (2560) to diffusion head (3584).
475
+ if getattr(model_args, "train_surgery_module", False) and hasattr(model.model, "surgery_module"):
476
+ for p in model.model.surgery_module.parameters():
477
+ p.requires_grad = True
478
+ logger.info("Surgery Module enabled for full fine-tuning (all parameters trainable).")
479
+ elif hasattr(model.model, "surgery_module"):
480
+ # Keep surgery module frozen unless explicitly requested
481
+ for p in model.model.surgery_module.parameters():
482
+ p.requires_grad = False
483
+
484
+ # Freeze embedding + head
485
+ try:
486
+ emb = model.get_input_embeddings()
487
+ if hasattr(emb, "weight"):
488
+ emb.weight.requires_grad_(False)
489
+ head = model.get_output_embeddings()
490
+ if head is not None and hasattr(head, "weight"):
491
+ head.weight.requires_grad_(False)
492
+ except Exception:
493
+ pass
494
+
495
+ # Diagnostics
496
+ def _sum_params(named_iter):
497
+ return sum(p.numel() for _, p in named_iter if p.requires_grad)
498
+ try:
499
+ lm_lora = _sum_params(model.model.language_model.named_parameters()) if hasattr(model.model, "language_model") else 0
500
+ pred_head_train = _sum_params(model.model.prediction_head.named_parameters()) if hasattr(model.model, "prediction_head") else 0
501
+ ac_conn_train = _sum_params(model.model.acoustic_connector.named_parameters()) if hasattr(model.model, "acoustic_connector") else 0
502
+ se_conn_train = _sum_params(model.model.semantic_connector.named_parameters()) if hasattr(model.model, "semantic_connector") else 0
503
+ surgery_train = _sum_params(model.model.surgery_module.named_parameters()) if hasattr(model.model, "surgery_module") else 0
504
+ total_trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
505
+ logger.info(f"Trainable by block -> LLM-LoRA: {lm_lora:,} | diff_head: {pred_head_train:,} | ac_conn: {ac_conn_train:,} | se_conn: {se_conn_train:,} | surgery: {surgery_train:,}")
506
+ logger.info("TOTAL trainable: %s", f"{total_trainable:,}")
507
+ except Exception:
508
+ pass
509
+
510
+ # Preprocessed data classes
511
+ class PreprocessedBatchDataset:
512
+ def __init__(self, preprocessed_file: str):
513
+ self.data = torch.load(preprocessed_file, map_location='cpu')
514
+ logger.info(f"Loaded {len(self.data)} preprocessed batches from {preprocessed_file}")
515
+
516
+ def __len__(self):
517
+ return len(self.data)
518
+
519
+ def __getitem__(self, idx):
520
+ batch = self.data[idx]
521
+ result = {}
522
+ for k, v in batch.items():
523
+ if isinstance(v, torch.Tensor):
524
+ result[k] = v
525
+ else:
526
+ result[k] = v
527
+ return result
528
+
529
+ class PreprocessedBatchSubset:
530
+ def __init__(self, dataset: 'PreprocessedBatchDataset', indices: List[int]):
531
+ self.dataset = dataset
532
+ self.indices = indices
533
+
534
+ def __len__(self):
535
+ return len(self.indices)
536
+
537
+ def __getitem__(self, idx):
538
+ actual_idx = self.indices[idx]
539
+ return self.dataset[actual_idx]
540
+
541
+ class PreprocessedBatchCollator:
542
+ def __call__(self, batch: List[Dict[str, torch.Tensor]]) -> Dict[str, torch.Tensor]:
543
+ if not batch:
544
+ return {}
545
+ result = {}
546
+ for key in batch[0].keys():
547
+ tensors = [b[key] for b in batch if b[key] is not None]
548
+ if tensors and isinstance(tensors[0], torch.Tensor):
549
+ result[key] = torch.cat(tensors, dim=0)
550
+ else:
551
+ result[key] = tensors[0] if tensors else None
552
+ return result
553
+
554
+ # Datasets
555
+ preprocessed_dir = os.path.join(training_args.output_dir, "preprocessed")
556
+ preprocessed_file = os.path.join(preprocessed_dir, "preprocessed_batches.pt")
557
+
558
+ if os.path.exists(preprocessed_file):
559
+ logger.info(f"Loading preprocessed data from {preprocessed_file}")
560
+ preprocessed_data = PreprocessedBatchDataset(preprocessed_file)
561
+
562
+ train_dataset = preprocessed_data
563
+ eval_dataset = None
564
+
565
+ if training_args.do_eval and data_args.eval_split_size and data_args.eval_split_size > 0 and len(preprocessed_data) > 1:
566
+ num_eval = max(1, int(len(preprocessed_data) * data_args.eval_split_size))
567
+ num_train = len(preprocessed_data) - num_eval
568
+ indices = list(range(len(preprocessed_data)))
569
+ import random
570
+ random.Random(training_args.seed).shuffle(indices)
571
+ train_indices = indices[:num_train]
572
+ eval_indices = indices[num_train:]
573
+ train_dataset = PreprocessedBatchSubset(preprocessed_data, train_indices)
574
+ eval_dataset = PreprocessedBatchSubset(preprocessed_data, eval_indices)
575
+ else:
576
+ logger.info(f"Preprocessed data not found at {preprocessed_file}, loading from raw JSONL/HF datasets")
577
+ verification_mode = VerificationMode.NO_CHECKS if data_args.ignore_verifications else VerificationMode.BASIC_CHECKS
578
+ if data_args.train_jsonl is not None:
579
+ data_files: Dict[str, str] = {"train": data_args.train_jsonl}
580
+ if data_args.validation_jsonl is not None:
581
+ data_files["validation"] = data_args.validation_jsonl
582
+ raw = load_dataset("json", data_files=data_files, verification_mode=verification_mode, cache_dir=model_args.cache_dir)
583
+ else:
584
+ if data_args.dataset_name is None:
585
+ raise ValueError("Provide --dataset_name (HF datasets) or use --train_jsonl/--validation_jsonl for local files.")
586
+ raw = load_dataset(
587
+ data_args.dataset_name,
588
+ data_args.dataset_config_name,
589
+ verification_mode=verification_mode,
590
+ cache_dir=model_args.cache_dir,
591
+ )
592
+ train_ds = raw[data_args.train_split_name]
593
+ eval_ds = None
594
+ if training_args.do_eval:
595
+ if data_args.eval_split_name and data_args.eval_split_name in raw:
596
+ eval_ds = raw[data_args.eval_split_name]
597
+ elif data_args.eval_split_size and data_args.eval_split_size > 0 and len(train_ds) > 1:
598
+ split = train_ds.train_test_split(test_size=data_args.eval_split_size, seed=training_args.seed)
599
+ train_ds, eval_ds = split["train"], split["test"]
600
+
601
+ train_dataset = VibeVoiceDataset(
602
+ train_ds,
603
+ text_column=data_args.text_column_name,
604
+ audio_column=data_args.audio_column_name,
605
+ voice_prompts_column=data_args.voice_prompts_column_name,
606
+ )
607
+ eval_dataset = None
608
+ if eval_ds is not None:
609
+ eval_dataset = VibeVoiceDataset(
610
+ eval_ds,
611
+ text_column=data_args.text_column_name,
612
+ audio_column=data_args.audio_column_name,
613
+ voice_prompts_column=data_args.voice_prompts_column_name,
614
+ )
615
+
616
+ # Ratios/dims from processor+model
617
+ speech_compress_ratio = getattr(processor, "speech_tok_compress_ratio", 3200)
618
+ semantic_dim = getattr(model.config, "semantic_vae_dim", None)
619
+ if semantic_dim is None:
620
+ try:
621
+ semantic_dim = int(getattr(model.config.semantic_tokenizer_config, "vae_dim", 128))
622
+ except Exception:
623
+ semantic_dim = 128
624
+
625
+ compute_semantics_flag = hasattr(processor, "semantic_tokenizer") and processor.semantic_tokenizer is not None
626
+
627
+ if os.path.exists(preprocessed_file):
628
+ data_collator = PreprocessedBatchCollator()
629
+ else:
630
+ data_collator = VibeVoiceCollator(
631
+ processor=processor,
632
+ max_length=data_args.max_length,
633
+ speech_compress_ratio=speech_compress_ratio,
634
+ semantic_vae_dim=semantic_dim,
635
+ compute_semantics=compute_semantics_flag,
636
+ debug_checks=False,
637
+ voice_prompt_drop_rate=data_args.voice_prompt_drop_rate,
638
+ )
639
+
640
+ class LoRADebugCallback(TrainerCallback):
641
+ def __init__(self, log_every_n_steps: int = 50):
642
+ self.log_every_n_steps = max(1, int(log_every_n_steps))
643
+ self.prev_param_norms: Dict[str, float] = {}
644
+ self.lora_param_names: List[str] = []
645
+
646
+ def on_train_begin(self, args, state, control, model=None, **kwargs):
647
+ try:
648
+ if model is None:
649
+ return
650
+ named: Dict[str, torch.nn.Parameter] = dict(model.named_parameters())
651
+ self.lora_param_names = [n for n in named.keys() if ("lora_A" in n or "lora_B" in n)]
652
+ for n in self.lora_param_names:
653
+ p = named[n]
654
+ self.prev_param_norms[n] = float(p.data.norm().item())
655
+ total = len(self.lora_param_names)
656
+ req_grad = sum(1 for n in self.lora_param_names if named[n].requires_grad)
657
+ num_A = sum(1 for n in self.lora_param_names if "lora_A" in n)
658
+ num_B = sum(1 for n in self.lora_param_names if "lora_B" in n)
659
+ zero_B = sum(1 for n in self.lora_param_names if ("lora_B" in n and float(named[n].data.norm().item()) == 0.0))
660
+ logger.info(f"LoRA debug: found {total} LoRA params (A={num_A}, B={num_B}); trainable={req_grad}. Initial lora_B_zero={zero_B}.")
661
+ if total == 0:
662
+ logger.warning("LoRA debug: No LoRA parameters found. Check lora_target_modules.")
663
+ if req_grad != total:
664
+ logger.warning("LoRA debug: Some LoRA params are frozen. They should be trainable.")
665
+ except Exception as e:
666
+ logger.warning(f"LoRA debug (on_train_begin) failed: {e}")
667
+
668
+ def on_step_end(self, args, state, control, model=None, **kwargs):
669
+ try:
670
+ if model is None or len(self.lora_param_names) == 0:
671
+ return
672
+ step = int(getattr(state, "global_step", 0) or 0)
673
+ if step % self.log_every_n_steps != 0 and step != 1:
674
+ return
675
+ named: Dict[str, torch.nn.Parameter] = dict(model.named_parameters())
676
+ changed_A = 0
677
+ changed_B = 0
678
+ zero_B = 0
679
+ eps = 1e-12
680
+ for n in self.lora_param_names:
681
+ p = named.get(n, None)
682
+ if p is None:
683
+ continue
684
+ prev = self.prev_param_norms.get(n, 0.0)
685
+ curr = float(p.data.norm().item())
686
+ if "lora_A" in n and abs(curr - prev) > eps:
687
+ changed_A += 1
688
+ if "lora_B" in n:
689
+ if abs(curr - prev) > eps:
690
+ changed_B += 1
691
+ if curr == 0.0:
692
+ zero_B += 1
693
+ self.prev_param_norms[n] = curr
694
+ total_A = sum(1 for n in self.lora_param_names if "lora_A" in n)
695
+ total_B = sum(1 for n in self.lora_param_names if "lora_B" in n)
696
+ logger.info(f"LoRA debug step {step}: changed A {changed_A}/{total_A}, changed B {changed_B}/{total_B}, lora_B_zero_now={zero_B}.")
697
+ except Exception as e:
698
+ logger.warning(f"LoRA debug (on_step_end) failed: {e}")
699
+
700
+ class VibeVoiceTrainer(Trainer):
701
+ def compute_loss(self, model: VibeVoiceForConditionalGeneration, inputs: Dict[str, Any], return_outputs=False, num_items_in_batch: Optional[int] = None):
702
+ labels = inputs.get("input_ids")
703
+ attention_mask = inputs.get("attention_mask")
704
+ acoustic_input_mask = inputs.get("acoustic_input_mask")
705
+
706
+ # Ensure semantic tensors exist and have correct dtype/device
707
+ sem = inputs.get("speech_semantic_tensors", None)
708
+ try:
709
+ target_dtype = next(model.model.semantic_connector.parameters()).dtype
710
+ except Exception:
711
+ target_dtype = model.get_input_embeddings().weight.dtype
712
+
713
+ if sem is None:
714
+ sm = inputs.get("speech_masks")
715
+ if sm is not None:
716
+ zeros = torch.zeros(
717
+ sm.size(0), sm.size(1),
718
+ getattr(model.config, "semantic_vae_dim", 128),
719
+ dtype=target_dtype,
720
+ device=sm.device,
721
+ )
722
+ inputs["speech_semantic_tensors"] = zeros
723
+ else:
724
+ if isinstance(sem, torch.Tensor):
725
+ inputs["speech_semantic_tensors"] = sem.to(dtype=target_dtype)
726
+
727
+ outputs = model(
728
+ input_ids=inputs.get("input_ids"),
729
+ attention_mask=attention_mask,
730
+ speech_tensors=inputs.get("speech_tensors"),
731
+ speech_masks=inputs.get("speech_masks"),
732
+ speech_semantic_tensors=inputs.get("speech_semantic_tensors"),
733
+ acoustic_input_mask=acoustic_input_mask,
734
+ acoustic_loss_mask=inputs.get("acoustic_loss_mask"),
735
+ speeches_loss_input=inputs.get("speeches_loss_input"),
736
+ ddpm_batch_mul=training_args.ddpm_batch_mul,
737
+ )
738
+
739
+ # Invariants: token/latent selection equality across views (warn, don't assert)
740
+ try:
741
+ al_mask = inputs.get("acoustic_loss_mask")
742
+ sp_masks = inputs.get("speech_masks")
743
+ sp_loss_sel = inputs.get("speeches_loss_input")
744
+ num_tok_total = int(acoustic_input_mask.sum().item()) if acoustic_input_mask is not None else 0
745
+ num_tok_loss = int(al_mask.sum().item()) if al_mask is not None else 0
746
+ num_lat_total = int(sp_masks.sum().item()) if sp_masks is not None else 0
747
+ num_lat_loss = int(((sp_loss_sel & sp_masks).sum().item())) if (sp_loss_sel is not None and sp_masks is not None) else 0
748
+ self.log({
749
+ "debug/num_tok_total": float(num_tok_total),
750
+ "debug/num_tok_loss": float(num_tok_loss),
751
+ "debug/num_lat_total": float(num_lat_total),
752
+ "debug/num_lat_loss": float(num_lat_loss),
753
+ })
754
+ if sp_loss_sel is not None and sp_masks is not None and al_mask is not None:
755
+ if num_tok_loss != num_lat_loss:
756
+ logger.warning(f"Loss selection mismatch: acoustic_loss_mask={num_tok_loss} vs speeches_loss_input={num_lat_loss}")
757
+ except Exception:
758
+ pass
759
+
760
+ # CE Loss
761
+ logits = outputs.logits
762
+ ce_labels = mask_for_ce(labels, attention_mask, acoustic_input_mask, pad_id=-100)
763
+ shift_logits = logits[:, :-1, :].contiguous()
764
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
765
+ ce_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), ce_labels.view(-1))
766
+
767
+ # Optional CE diagnostics
768
+ try:
769
+ self._debug_ce(shift_logits, ce_labels, attention_mask, acoustic_input_mask)
770
+ except Exception as e:
771
+ logger.warning(f"Failed invoking CE debug: {e}")
772
+
773
+ # Diffusion loss
774
+ diffusion_loss = outputs.diffusion_loss if outputs.diffusion_loss is not None else torch.tensor(0.0, device=ce_loss.device)
775
+ total = training_args.ce_loss_weight * ce_loss + training_args.diffusion_loss_weight * diffusion_loss
776
+
777
+ # Logs
778
+ try:
779
+ prefix = "train" if model.training else "eval"
780
+ self.log({
781
+ f"{prefix}/ce_loss": ce_loss.detach().item(),
782
+ f"{prefix}/diffusion_loss": diffusion_loss.detach().item() if isinstance(diffusion_loss, torch.Tensor) else float(diffusion_loss),
783
+ })
784
+ if hasattr(self, "optimizer") and self.optimizer is not None and len(self.optimizer.param_groups) > 0:
785
+ lr_val = self.optimizer.param_groups[0].get("lr", None)
786
+ if lr_val is not None:
787
+ self.log({"train/learning_rate_real": float(lr_val)})
788
+ except Exception:
789
+ pass
790
+
791
+ return (total, outputs) if return_outputs else total
792
+
793
+ def _debug_ce(self, shift_logits: torch.Tensor, ce_labels: torch.Tensor, attention_mask: Optional[torch.Tensor], acoustic_input_mask: Optional[torch.Tensor]):
794
+ try:
795
+ if not getattr(training_args, "debug_ce_details", False):
796
+ return
797
+ step = int(getattr(self.state, "global_step", 0) or 0)
798
+ every_n = max(1, int(getattr(training_args, "debug_ce_every_n_steps", 200) or 200))
799
+ if not (step <= 1 or (step % every_n == 0)):
800
+ return
801
+
802
+ with torch.no_grad():
803
+ vocab = shift_logits.size(-1)
804
+ per_token_loss = F.cross_entropy(
805
+ shift_logits.view(-1, vocab),
806
+ ce_labels.view(-1),
807
+ reduction="none",
808
+ ignore_index=-100,
809
+ ).view_as(ce_labels)
810
+
811
+ valid_mask = ce_labels.ne(-100)
812
+ num_valid = int(valid_mask.sum().item())
813
+ avg_loss = float((per_token_loss[valid_mask].mean().item())) if num_valid > 0 else float("nan")
814
+
815
+ per_ex_avgs = []
816
+ max_examples = max(1, int(getattr(training_args, "debug_ce_max_examples", 1) or 1))
817
+ B = ce_labels.size(0)
818
+ for b in range(min(B, max_examples)):
819
+ vb = valid_mask[b]
820
+ if int(vb.sum().item()) > 0:
821
+ per_ex_avgs.append(float(per_token_loss[b][vb].mean().item()))
822
+ else:
823
+ per_ex_avgs.append(float("nan"))
824
+ logger.info(f"CE debug: tokens_in_loss={num_valid}, avg_loss={avg_loss:.4f}, per_example_avgs={[round(x,4) if x==x else None for x in per_ex_avgs]}")
825
+ except Exception as e:
826
+ logger.warning(f"CE detailed debug failed: {e}")
827
+
828
+ # --------- CRITICAL SAVE OVERRIDES: also dump FULL head/connectors for inference ---------
829
+
830
+
831
+ def _save(self, output_dir: Optional[str] = None, state_dict=None) -> None:
832
+ try:
833
+ target_dir = output_dir or self.args.output_dir
834
+ lora_out = os.path.join(target_dir, "lora")
835
+ os.makedirs(lora_out, exist_ok=True)
836
+
837
+ # --- LLM PEFT adapters (if LoRA-wrapped) ---
838
+ language_model = getattr(self.model.model, "language_model", None)
839
+ if hasattr(language_model, "save_pretrained"):
840
+ language_model.save_pretrained(lora_out)
841
+
842
+ # --- Diffusion head PEFT adapters (if LoRA-wrapped) ---
843
+ pred_head = getattr(self.model.model, "prediction_head", None)
844
+ if hasattr(pred_head, "save_pretrained"):
845
+ ph_dir = os.path.join(lora_out, "diffusion_head")
846
+ os.makedirs(ph_dir, exist_ok=True)
847
+ pred_head.save_pretrained(ph_dir)
848
+
849
+ # --- ALWAYS save FULL diffusion head state_dict for fallback ---
850
+ if pred_head is not None and hasattr(pred_head, "state_dict"):
851
+ sd = pred_head.state_dict()
852
+ torch.save(sd, os.path.join(lora_out, "diffusion_head_full.bin"))
853
+ ph_dir = os.path.join(lora_out, "diffusion_head")
854
+ os.makedirs(ph_dir, exist_ok=True)
855
+ torch.save(sd, os.path.join(ph_dir, "diffusion_head_full.bin"))
856
+
857
+ # --- Connectors (plain state_dicts) ---
858
+ ac = getattr(self.model.model, "acoustic_connector", None)
859
+ if ac is not None:
860
+ ac_dir = os.path.join(lora_out, "acoustic_connector")
861
+ os.makedirs(ac_dir, exist_ok=True)
862
+ torch.save(ac.state_dict(), os.path.join(ac_dir, "pytorch_model.bin"))
863
+
864
+ se = getattr(self.model.model, "semantic_connector", None)
865
+ if se is not None:
866
+ se_dir = os.path.join(lora_out, "semantic_connector")
867
+ os.makedirs(se_dir, exist_ok=True)
868
+ torch.save(se.state_dict(), os.path.join(se_dir, "pytorch_model.bin"))
869
+
870
+ except Exception as e:
871
+ logger.warning(f"Failed to save LoRA assets: {e}")
872
+
873
+
874
+ # ------------- Build the Trainer -------------
875
+
876
+ # Resolve which adapters to apply in samples
877
+
878
+ ema_cb = EmaCallback(attr_path="model.prediction_head", decay=0.999, device="cuda")
879
+
880
+ # --- CRITICAL FIX: CAST TRAINABLE PARAMS TO FP32 ---
881
+ # This prevents 'ValueError: Attempting to unscale FP16 gradients'
882
+ if getattr(training_args, 'fp16', False) or getattr(training_args, 'bf16', False):
883
+ print('>>> INFO: Enforcing float32 for trainable parameters (LoRA/Head) to fix GradScaler.')
884
+ for name, param in model.named_parameters():
885
+ if param.requires_grad:
886
+ param.data = param.data.to(torch.float32)
887
+ # ---------------------------------------------------
888
+
889
+ trainer = VibeVoiceTrainer(
890
+ model=model,
891
+ args=training_args,
892
+ train_dataset=train_dataset,
893
+ eval_dataset=eval_dataset,
894
+ data_collator=data_collator,
895
+ callbacks=[ema_cb, LoRADebugCallback(log_every_n_steps=(int(getattr(training_args, "logging_steps", 50) or 50)))],
896
+ )
897
+
898
+ # Optional debug pre-training save
899
+ if getattr(training_args, "debug_save", False):
900
+ try:
901
+ debug_dir = os.path.join(training_args.output_dir, "debug_initial")
902
+ lora_out = os.path.join(debug_dir, "lora")
903
+ os.makedirs(lora_out, exist_ok=True)
904
+ logger.info(f"[debug_save] Saving initial (pre-training) model components to: {debug_dir}")
905
+ # language model adapters / base
906
+ try:
907
+ if hasattr(model.model.language_model, "save_pretrained"):
908
+ model.model.language_model.save_pretrained(lora_out)
909
+ except Exception as e_lm:
910
+ logger.warning(f"[debug_save] Failed to save language_model: {e_lm}")
911
+ # diffusion head
912
+ try:
913
+ if hasattr(model.model, "prediction_head") and hasattr(model.model.prediction_head, "save_pretrained"):
914
+ model.model.prediction_head.save_pretrained(os.path.join(lora_out, "diffusion_head"))
915
+ except Exception as e_head:
916
+ logger.warning(f"[debug_save] Failed to save prediction_head: {e_head}")
917
+ # NEW: full diffusion head state_dict as fallback
918
+ try:
919
+ ph = getattr(model.model, "prediction_head", None)
920
+ if ph is not None and hasattr(ph, "state_dict"):
921
+ sd = ph.state_dict()
922
+ torch.save(sd, os.path.join(lora_out, "diffusion_head_full.bin"))
923
+ os.makedirs(os.path.join(lora_out, "diffusion_head"), exist_ok=True)
924
+ torch.save(sd, os.path.join(lora_out, "diffusion_head", "diffusion_head_full.bin"))
925
+ except Exception as e:
926
+ logger.warning(f"[debug_save] Failed to save FULL diffusion head: {e}")
927
+ # connectors
928
+ try:
929
+ ac_conn = getattr(model.model, "acoustic_connector", None)
930
+ if ac_conn is not None:
931
+ ac_dir = os.path.join(lora_out, "acoustic_connector")
932
+ os.makedirs(ac_dir, exist_ok=True)
933
+ torch.save(ac_conn.state_dict(), os.path.join(ac_dir, "pytorch_model.bin"))
934
+ except Exception as e_ac:
935
+ logger.warning(f"[debug_save] Failed to save acoustic_connector: {e_ac}")
936
+ try:
937
+ se_conn = getattr(model.model, "semantic_connector", None)
938
+ if se_conn is not None:
939
+ se_dir = os.path.join(lora_out, "semantic_connector")
940
+ os.makedirs(se_dir, exist_ok=True)
941
+ torch.save(se_conn.state_dict(), os.path.join(se_dir, "pytorch_model.bin"))
942
+ except Exception as e_se:
943
+ logger.warning(f"[debug_save] Failed to save semantic_connector: {e_se}")
944
+ except Exception as e:
945
+ logger.warning(f"[debug_save] Unexpected failure saving initial components: {e}")
946
+
947
+ if getattr(training_args, "gradient_checkpointing", False):
948
+ try:
949
+ model.gradient_checkpointing_enable()
950
+ except Exception:
951
+ logger.warning("Failed to enable gradient checkpointing on the model.")
952
+
953
+ # =========================================================================
954
+ # Load Custom Weights from Checkpoint before resuming training
955
+ # =========================================================================
956
+ if training_args.do_train and training_args.resume_from_checkpoint:
957
+ checkpoint_path = None
958
+ if isinstance(training_args.resume_from_checkpoint, bool) and training_args.resume_from_checkpoint:
959
+ from transformers.trainer_utils import get_last_checkpoint
960
+ checkpoint_path = get_last_checkpoint(training_args.output_dir)
961
+ else:
962
+ checkpoint_path = training_args.resume_from_checkpoint
963
+
964
+ if checkpoint_path is not None and os.path.exists(checkpoint_path):
965
+ lora_dir = os.path.join(checkpoint_path, "lora")
966
+ if os.path.exists(lora_dir):
967
+ logger.info(f"*** Resuming custom weights (LoRA, Connectors, Head) from {lora_dir} ***")
968
+
969
+ # 1. Load LLM LoRA
970
+ if hasattr(model.model, "language_model"):
971
+ try:
972
+ from peft import load_peft_weights, set_peft_model_state_dict
973
+ adapters_weights = load_peft_weights(lora_dir)
974
+ set_peft_model_state_dict(model.model.language_model, adapters_weights)
975
+ logger.info("Successfully loaded LLM LoRA weights.")
976
+ except Exception as e:
977
+ logger.warning(f"Could not load LLM LoRA weights: {e}")
978
+
979
+ # 2. Load Diffusion Head
980
+ ph_full_path = os.path.join(lora_dir, "diffusion_head_full.bin")
981
+ if os.path.exists(ph_full_path) and hasattr(model.model, "prediction_head"):
982
+ try:
983
+ model.model.prediction_head.load_state_dict(torch.load(ph_full_path, map_location="cpu"), strict=False)
984
+ logger.info("Successfully loaded Diffusion Head weights.")
985
+ except Exception as e:
986
+ logger.warning(f"Failed to load Diffusion Head weights: {e}")
987
+
988
+ # 3. Load Acoustic Connector
989
+ ac_path = os.path.join(lora_dir, "acoustic_connector", "pytorch_model.bin")
990
+ if os.path.exists(ac_path) and hasattr(model.model, "acoustic_connector"):
991
+ try:
992
+ model.model.acoustic_connector.load_state_dict(torch.load(ac_path, map_location="cpu"))
993
+ logger.info("Successfully loaded Acoustic Connector weights.")
994
+ except Exception as e:
995
+ logger.warning(f"Failed to load Acoustic Connector weights: {e}")
996
+
997
+ # 4. Load Semantic Connector
998
+ se_path = os.path.join(lora_dir, "semantic_connector", "pytorch_model.bin")
999
+ if os.path.exists(se_path) and hasattr(model.model, "semantic_connector"):
1000
+ try:
1001
+ model.model.semantic_connector.load_state_dict(torch.load(se_path, map_location="cpu"))
1002
+ logger.info("Successfully loaded Semantic Connector weights.")
1003
+ except Exception as e:
1004
+ logger.warning(f"Failed to load Semantic Connector weights: {e}")
1005
+ else:
1006
+ logger.warning(f"No custom 'lora' directory found inside checkpoint: {checkpoint_path}")
1007
+ # =========================================================================
1008
+
1009
+ if training_args.do_train:
1010
+ # ----- THE FIX: SET resume_from_checkpoint=False HERE -----
1011
+ # The weights are ALREADY loaded via the custom block above.
1012
+ # Setting this to False forces Trainer to start counting steps/epochs from 0
1013
+ # for your new dataset, preventing it from immediately exiting.
1014
+ trainer.train(resume_from_checkpoint=False)
1015
+
1016
+ lora_out = os.path.join(training_args.output_dir, "lora")
1017
+ os.makedirs(lora_out, exist_ok=True)
1018
+
1019
+ # LLM PEFT (if any)
1020
+ lm = getattr(model.model, "language_model", None)
1021
+ if hasattr(lm, "save_pretrained"):
1022
+ lm.save_pretrained(lora_out)
1023
+
1024
+ # Diffusion head PEFT (if any)
1025
+ ph = getattr(model.model, "prediction_head", None)
1026
+ if hasattr(ph, "save_pretrained"):
1027
+ ph_dir = os.path.join(lora_out, "diffusion_head")
1028
+ os.makedirs(ph_dir, exist_ok=True)
1029
+ ph.save_pretrained(ph_dir)
1030
+
1031
+ # ALWAYS: full diffusion head state_dict fallback
1032
+ try:
1033
+ if ph is not None and hasattr(ph, "state_dict"):
1034
+ sd = ph.state_dict()
1035
+ torch.save(sd, os.path.join(lora_out, "diffusion_head_full.bin"))
1036
+ ph_dir = os.path.join(lora_out, "diffusion_head")
1037
+ os.makedirs(ph_dir, exist_ok=True)
1038
+ torch.save(sd, os.path.join(ph_dir, "diffusion_head_full.bin"))
1039
+ except Exception as e:
1040
+ logger.warning(f"Failed to save FULL diffusion head at end: {e}")
1041
+
1042
+ # Connectors (if trained)
1043
+ try:
1044
+ ac = getattr(model.model, "acoustic_connector", None)
1045
+ if ac is not None:
1046
+ ac_dir = os.path.join(lora_out, "acoustic_connector")
1047
+ os.makedirs(ac_dir, exist_ok=True)
1048
+ torch.save(ac.state_dict(), os.path.join(ac_dir, "pytorch_model.bin"))
1049
+ except Exception as e:
1050
+ logger.warning(f"Failed to save acoustic_connector: {e}")
1051
+
1052
+ try:
1053
+ se = getattr(model.model, "semantic_connector", None)
1054
+ if se is not None:
1055
+ se_dir = os.path.join(lora_out, "semantic_connector")
1056
+ os.makedirs(se_dir, exist_ok=True)
1057
+ torch.save(se.state_dict(), os.path.join(se_dir, "pytorch_model.bin"))
1058
+ except Exception as e:
1059
+ logger.warning(f"Failed to save semantic_connector: {e}")
1060
+
1061
+ if training_args.do_eval and eval_dataset is not None:
1062
+ trainer.evaluate()
1063
+
1064
+
1065
+ if __name__ == "__main__":
1066
+ main()
VibeVoice-tpu/src/finetune_vibevoice_tpu.py ADDED
@@ -0,0 +1,1638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ VibeVoice Fine-Tuning on TPU v5e-8
3
+ ====================================
4
+
5
+ Complete fine-tuning pipeline for VibeVoice (with surgery module support)
6
+ on Google Cloud TPU v5e-8 (8 chips × 16 GB HBM = 128 GB total).
7
+
8
+ Key changes from GPU (T4/A100) version:
9
+ - PyTorch/XLA instead of CUDA
10
+ - bfloat16 precision (native on TPU v5e)
11
+ - Custom training loop (HF Trainer lacks native TPU/XLA support)
12
+ - XLA graph compilation with explicit mark_step() synchronization
13
+ - MpDeviceLoader for distributed data loading across 8 TPU chips
14
+ - Gradient accumulation with proper XLA all-reduce
15
+
16
+ Data:
17
+ - Expects preprocessed .pt files in an input folder
18
+ - Each .pt file contains a list of preprocessed batch dicts
19
+ - Dicts have keys: input_ids, attention_mask, speech_tensors, speech_masks,
20
+ speech_semantic_tensors, acoustic_input_mask, acoustic_loss_mask, speeches_loss_input
21
+
22
+ Usage:
23
+ python finetune_vibevoice_tpu.py \
24
+ --model_name_or_path /path/to/surgery_model \
25
+ --preprocessed_dir /path/to/preprocessed_data \
26
+ --output_dir /path/to/output \
27
+ --max_steps 5000 \
28
+ --learning_rate 2e-5 \
29
+ --gradient_accumulation_steps 8
30
+ """
31
+
32
+ import os
33
+ import sys
34
+ import gc
35
+ import copy
36
+ import math
37
+ import time
38
+ import random
39
+ import logging
40
+ import functools
41
+ from dataclasses import dataclass, field
42
+ from typing import Any, Dict, List, Optional, Tuple
43
+
44
+ # ============================================================================
45
+ # TPU Environment Setup (must be before torch import)
46
+ # ============================================================================
47
+ from tpu_config import setup_tpu_env, TPU_CONFIG, TPU_TRAINING_CONFIG, XLA_CONFIG
48
+ setup_tpu_env()
49
+
50
+ import torch
51
+ import torch.nn as nn
52
+ import torch.nn.functional as F
53
+
54
+ # PyTorch/XLA imports
55
+ import torch_xla
56
+ import torch_xla.core.xla_model as xm
57
+ import torch_xla.core.xla_env_registry as xenv
58
+ import torch_xla.distributed.xla_multiprocessing as xmp
59
+ import torch_xla.distributed.parallel_loader as pl
60
+ from torch_xla.amp import autocast
61
+
62
+ # Transformers & PEFT
63
+ from transformers import (
64
+ AutoModel,
65
+ AutoModelForCausalLM,
66
+ set_seed,
67
+ )
68
+ from transformers.models.llama.modeling_llama import LlamaRMSNorm
69
+ from peft import LoraConfig, get_peft_model, TaskType
70
+
71
+ # VibeVoice imports
72
+ from vibevoice.modular.modeling_vibevoice import (
73
+ VibeVoiceModel,
74
+ VibeVoiceForConditionalGeneration,
75
+ SpeechConnector,
76
+ )
77
+ from vibevoice.modular.configuration_vibevoice import VibeVoiceConfig
78
+ from vibevoice.processor.vibevoice_processor import VibeVoiceProcessor
79
+
80
+ # Surgery imports — monkey-patch for Qwen3 support
81
+ try:
82
+ from vibevoice_surgery_colab import (
83
+ _patch_vibevoice_config_for_qwen3,
84
+ Qwen3SurgeryModule,
85
+ load_surgery_model,
86
+ QWEN3_HIDDEN_SIZE,
87
+ DIFFUSION_HIDDEN_SIZE,
88
+ SURGERY_LAYER_INDICES,
89
+ )
90
+ _patch_vibevoice_config_for_qwen3()
91
+ except ImportError:
92
+ try:
93
+ from vibevoice_surgery_colab import _patch_vibevoice_config_for_qwen3
94
+ _patch_vibevoice_config_for_qwen3()
95
+ HAS_SURGERY = False
96
+ except Exception:
97
+ HAS_SURGERY = False
98
+
99
+ logger = logging.getLogger(__name__)
100
+
101
+
102
+ # ============================================================================
103
+ # SECTION 1: Argument Dataclasses
104
+ # ============================================================================
105
+
106
+ @dataclass
107
+ class TPUModelArguments:
108
+ """Arguments for model loading on TPU."""
109
+ model_name_or_path: str = field(
110
+ metadata={"help": "Path to the VibeVoice/surgery model directory"}
111
+ )
112
+ processor_name_or_path: Optional[str] = field(
113
+ default=None,
114
+ metadata={"help": "Path to processor dir. Defaults to model_name_or_path."},
115
+ )
116
+
117
+ # Freezing strategy
118
+ freeze_llm: bool = field(default=False)
119
+ freeze_diffusion_head: bool = field(default=True)
120
+ freeze_surgery_module: bool = field(default=False)
121
+ freeze_connectors: bool = field(default=False)
122
+ freeze_acoustic_tokenizer: bool = field(default=True)
123
+ freeze_semantic_tokenizer: bool = field(default=True)
124
+ freeze_lm_head: bool = field(default=True)
125
+
126
+ # LoRA
127
+ lora_r: int = field(default=8)
128
+ lora_alpha: int = field(default=32)
129
+ lora_dropout: float = field(default=0.05)
130
+ lora_target_modules: str = field(
131
+ default="q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj",
132
+ )
133
+ lora_wrap_diffusion_head: bool = field(default=False)
134
+
135
+ # Fine-tune flags
136
+ train_diffusion_head: bool = field(default=False)
137
+ train_connectors: bool = field(default=True)
138
+ train_surgery_module: bool = field(default=True)
139
+
140
+ # Advanced
141
+ layers_to_freeze: Optional[str] = field(default=None)
142
+
143
+
144
+ @dataclass
145
+ class TPUDataArguments:
146
+ """Arguments for data loading."""
147
+ preprocessed_dir: str = field(
148
+ metadata={"help": "Directory containing preprocessed .pt files"}
149
+ )
150
+ eval_split_size: float = field(default=0.05)
151
+ seed: int = field(default=42)
152
+
153
+
154
+ @dataclass
155
+ class TPUTrainingArguments:
156
+ """Arguments for TPU training."""
157
+ output_dir: str = field(default="./output_tpu")
158
+
159
+ # Batch & accumulation
160
+ per_device_train_batch_size: int = field(default=1)
161
+ gradient_accumulation_steps: int = field(default=8)
162
+
163
+ # Learning rate
164
+ learning_rate: float = field(default=2e-5)
165
+ lr_scheduler_type: str = field(default="cosine")
166
+ warmup_ratio: float = field(default=0.1)
167
+ warmup_steps: int = field(default=100)
168
+
169
+ # Loss weights
170
+ ce_loss_weight: float = field(default=1.0)
171
+ diffusion_loss_weight: float = field(default=1.0)
172
+ ddpm_batch_mul: int = field(default=1)
173
+
174
+ # Gradient clipping
175
+ max_grad_norm: float = field(default=1.0)
176
+
177
+ # Training duration
178
+ max_steps: int = field(default=5000)
179
+ num_train_epochs: int = field(default=3)
180
+
181
+ # Logging & saving
182
+ logging_steps: int = field(default=10)
183
+ save_steps: int = field(default=500)
184
+ eval_steps: int = field(default=500)
185
+ save_total_limit: int = field(default=3)
186
+
187
+ # Gradient checkpointing
188
+ gradient_checkpointing: bool = field(default=True)
189
+
190
+ # EMA
191
+ ema_decay: float = field(default=0.999)
192
+
193
+ # Random seed
194
+ seed: int = field(default=42)
195
+
196
+ # Resume
197
+ resume_from_checkpoint: Optional[str] = field(default=None)
198
+
199
+
200
+ # ============================================================================
201
+ # SECTION 2: Helper Functions
202
+ # ============================================================================
203
+
204
+ def mask_for_ce(
205
+ labels: torch.Tensor,
206
+ attention_mask: torch.Tensor,
207
+ acoustic_input_mask: torch.Tensor,
208
+ pad_id: int = -100,
209
+ ) -> torch.Tensor:
210
+ """Build CE loss mask: only predict text tokens, not acoustic placeholders."""
211
+ shifted = labels[:, 1:].contiguous()
212
+ base_mask = (
213
+ attention_mask[:, 1:].contiguous().eq(1)
214
+ if (attention_mask is not None and attention_mask.numel() > 0)
215
+ else torch.ones_like(shifted, dtype=torch.bool)
216
+ )
217
+ label_is_acoustic = acoustic_input_mask[:, 1:].contiguous()
218
+ final_mask = base_mask & (~label_is_acoustic)
219
+ out = shifted.clone()
220
+ out[~final_mask] = pad_id
221
+ return out
222
+
223
+
224
+ def _patch_acoustic_encode_for_legacy_indexing(model_obj, logger_):
225
+ """Patch acoustic tokenizer encode to return [[...]] for legacy indexing."""
226
+ try:
227
+ acoustic = getattr(getattr(model_obj, "model", model_obj), "acoustic_tokenizer", None)
228
+ if acoustic is None or not hasattr(acoustic, "encode"):
229
+ logger_.warning("No acoustic_tokenizer.encode() found to patch.")
230
+ return
231
+ base_encode = acoustic.encode
232
+
233
+ def encode_wrapped(*args, **kwargs):
234
+ out = base_encode(*args, **kwargs)
235
+ try:
236
+ _ = out[0][0]
237
+ return out
238
+ except Exception:
239
+ pass
240
+ if isinstance(out, dict):
241
+ for k in ("frames", "codes", "tokens", "latents", "hidden_states"):
242
+ if k in out:
243
+ return [[out[k]]]
244
+ if len(out) > 0:
245
+ return [[next(iter(out.values()))]]
246
+ for attr in ("frames", "codes", "tokens", "latents", "hidden_states"):
247
+ if hasattr(out, attr):
248
+ return [[getattr(out, attr)]]
249
+ try:
250
+ if isinstance(out, torch.Tensor):
251
+ return [[out]]
252
+ except Exception:
253
+ pass
254
+ return [[out]]
255
+
256
+ acoustic.encode = encode_wrapped
257
+ logger_.info("Patched acoustic_tokenizer.encode() for legacy indexing.")
258
+ except Exception as e:
259
+ logger_.warning(f"Failed to patch acoustic_tokenizer.encode(): {e}")
260
+
261
+
262
+ def _force_output_hidden_states(model):
263
+ """Monkey-patch the base model to always output hidden_states."""
264
+ original_forward = model.model.forward
265
+
266
+ @functools.wraps(original_forward)
267
+ def patched_forward(self, **kwargs):
268
+ kwargs["output_hidden_states"] = True
269
+ return original_forward(**kwargs)
270
+
271
+ model.model.forward = patched_forward.__get__(model.model, type(model.model))
272
+ logger.info("Patched VibeVoiceModel.forward to force output_hidden_states=True")
273
+
274
+
275
+ def print_model_summary(model, logger_):
276
+ """Print a comprehensive summary of trainable vs frozen parameters."""
277
+ components = {
278
+ "LLM (language_model)": getattr(model.model, "language_model", None),
279
+ "LM Head": getattr(model, "lm_head", None),
280
+ "Diffusion Head (prediction_head)": getattr(model.model, "prediction_head", None),
281
+ "Surgery Module": getattr(model.model, "surgery_module", None),
282
+ "Acoustic Connector": getattr(model.model, "acoustic_connector", None),
283
+ "Semantic Connector": getattr(model.model, "semantic_connector", None),
284
+ "Acoustic Tokenizer": getattr(model.model, "acoustic_tokenizer", None),
285
+ "Semantic Tokenizer": getattr(model.model, "semantic_tokenizer", None),
286
+ }
287
+
288
+ total_all = 0
289
+ total_train = 0
290
+ logger_.info("=" * 70)
291
+ logger_.info(" MODEL PARAMETER SUMMARY")
292
+ logger_.info("=" * 70)
293
+
294
+ for name, mod in components.items():
295
+ if mod is None:
296
+ logger_.info(f" {name:<40s} NOT FOUND")
297
+ continue
298
+ n_all = sum(p.numel() for p in mod.parameters())
299
+ n_train = sum(p.numel() for p in mod.parameters() if p.requires_grad)
300
+ pct = (100.0 * n_train / n_all) if n_all > 0 else 0.0
301
+ status = "TRAINABLE" if n_train > 0 else "FROZEN"
302
+ if n_train > 0 and n_train < n_all:
303
+ status = f"PARTIAL ({pct:.1f}%)"
304
+ logger_.info(f" {name:<40s} {n_all:>14,} total | {n_train:>14,} train | {status}")
305
+ total_all += n_all
306
+ total_train += n_train
307
+
308
+ logger_.info("-" * 70)
309
+ logger_.info(f" {'TOTAL':<40s} {total_all:>14,} total | {total_train:>14,} train")
310
+ logger_.info(f" Trainable percentage: {100.0 * total_train / max(total_all, 1):.2f}%")
311
+ logger_.info("=" * 70)
312
+
313
+
314
+ # ============================================================================
315
+ # SECTION 3: LoRA Configuration
316
+ # ============================================================================
317
+
318
+ def build_lora_config(args: TPUModelArguments) -> LoraConfig:
319
+ """Build LoRA config for the LLM."""
320
+ target_modules = [s.strip() for s in args.lora_target_modules.split(",") if s.strip()]
321
+ return LoraConfig(
322
+ r=args.lora_r,
323
+ lora_alpha=args.lora_alpha,
324
+ lora_dropout=args.lora_dropout,
325
+ bias="none",
326
+ task_type=TaskType.CAUSAL_LM,
327
+ target_modules=target_modules,
328
+ )
329
+
330
+
331
+ def build_head_lora_config(args: TPUModelArguments) -> LoraConfig:
332
+ """Build LoRA config for the Diffusion Head."""
333
+ target_modules = [
334
+ "noisy_images_proj", "cond_proj",
335
+ "gate_proj", "up_proj", "down_proj", "linear",
336
+ ]
337
+ return LoraConfig(
338
+ r=args.lora_r,
339
+ lora_alpha=args.lora_alpha,
340
+ lora_dropout=args.lora_dropout,
341
+ bias="none",
342
+ task_type=TaskType.FEATURE_EXTRACTION,
343
+ target_modules=target_modules,
344
+ )
345
+
346
+
347
+ # ============================================================================
348
+ # SECTION 4: Preprocessed Data Loading for TPU
349
+ # ============================================================================
350
+
351
+ class TPUPreprocessedDataset(torch.utils.data.Dataset):
352
+ """
353
+ Dataset that loads preprocessed .pt files from a directory.
354
+
355
+ Each .pt file contains a list of batch dicts with tensors.
356
+ This class flattens all files into a single indexed dataset,
357
+ keeping tensors on CPU and letting the XLA data loader handle
358
+ device transfer.
359
+ """
360
+
361
+ def __init__(self, preprocessed_dir: str, logger_: logging.Logger):
362
+ super().__init__()
363
+ self.items: List[Dict[str, torch.Tensor]] = []
364
+
365
+ # Find all .pt files in the directory
366
+ pt_files = sorted([
367
+ os.path.join(preprocessed_dir, f)
368
+ for f in os.listdir(preprocessed_dir)
369
+ if f.endswith(".pt")
370
+ ])
371
+
372
+ if not pt_files:
373
+ raise FileNotFoundError(
374
+ f"No .pt files found in {preprocessed_dir}. "
375
+ "Please provide a directory with preprocessed .pt files."
376
+ )
377
+
378
+ logger_.info(f"Loading {len(pt_files)} preprocessed .pt files from {preprocessed_dir}")
379
+
380
+ for pt_file in pt_files:
381
+ try:
382
+ data = torch.load(pt_file, map_location="cpu")
383
+ if isinstance(data, list):
384
+ # List of batch dicts
385
+ for batch in data:
386
+ if isinstance(batch, dict):
387
+ self.items.append(batch)
388
+ logger_.info(f" Loaded {len(data)} batches from {os.path.basename(pt_file)}")
389
+ elif isinstance(data, dict):
390
+ # Single batch dict
391
+ self.items.append(data)
392
+ logger_.info(f" Loaded 1 batch from {os.path.basename(pt_file)}")
393
+ else:
394
+ logger_.warning(f" Skipping {os.path.basename(pt_file)}: unexpected format {type(data)}")
395
+ except Exception as e:
396
+ logger_.warning(f" Failed to load {os.path.basename(pt_file)}: {e}")
397
+
398
+ if not self.items:
399
+ raise ValueError(
400
+ f"No valid batch data found in .pt files in {preprocessed_dir}"
401
+ )
402
+
403
+ logger_.info(f"Total preprocessed samples: {len(self.items)}")
404
+
405
+ def __len__(self) -> int:
406
+ return len(self.items)
407
+
408
+ def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
409
+ item = self.items[idx]
410
+ result = {}
411
+ for k, v in item.items():
412
+ if isinstance(v, torch.Tensor):
413
+ result[k] = v.detach().clone()
414
+ elif v is None:
415
+ result[k] = None
416
+ else:
417
+ result[k] = v
418
+ return result
419
+
420
+
421
+ class TPUBatchCollator:
422
+ """
423
+ Collator that concatenates pre-batched tensors along dim=0.
424
+ Used with preprocessed data where each item is already a batch.
425
+ """
426
+
427
+ def __call__(self, batch: List[Dict[str, Any]]) -> Dict[str, Any]:
428
+ if not batch:
429
+ return {}
430
+
431
+ result = {}
432
+ keys = batch[0].keys()
433
+
434
+ for key in keys:
435
+ tensors = []
436
+ for b in batch:
437
+ v = b.get(key)
438
+ if v is not None and isinstance(v, torch.Tensor):
439
+ tensors.append(v)
440
+
441
+ if tensors:
442
+ # Check if we can concatenate (same ndim)
443
+ ndim = tensors[0].dim()
444
+ if all(t.dim() == ndim for t in tensors):
445
+ result[key] = torch.cat(tensors, dim=0)
446
+ else:
447
+ result[key] = tensors[0]
448
+ else:
449
+ # Use the first non-None value
450
+ for b in batch:
451
+ v = b.get(key)
452
+ if v is not None:
453
+ result[key] = v
454
+ break
455
+
456
+ return result
457
+
458
+
459
+ # ============================================================================
460
+ # SECTION 5: EMA (Exponential Moving Average)
461
+ # ============================================================================
462
+
463
+ class EMAModel:
464
+ """
465
+ EMA for the prediction head.
466
+ Maintains a shadow copy of parameters with exponential decay.
467
+ Compatible with TPU/XLA (uses CPU copies for shadow params).
468
+ """
469
+
470
+ def __init__(self, model: nn.Module, attr_path: str = "model.prediction_head", decay: float = 0.999):
471
+ self.attr_path = attr_path
472
+ self.decay = decay
473
+ self.shadow: Dict[str, torch.Tensor] = {}
474
+ self._orig: Optional[Dict[str, torch.Tensor]] = None
475
+
476
+ def _get_module(self, model: nn.Module) -> nn.Module:
477
+ mod = model
478
+ for name in self.attr_path.split('.'):
479
+ mod = getattr(mod, name)
480
+ return mod
481
+
482
+ def initialize(self, model: nn.Module):
483
+ """Initialize shadow parameters from model."""
484
+ head = self._get_module(model)
485
+ self.shadow = {
486
+ k: p.detach().cpu().float().clone()
487
+ for k, p in head.state_dict().items()
488
+ }
489
+ xm.master_print(f"EMA initialized with {len(self.shadow)} parameters")
490
+
491
+ def update(self, model: nn.Module):
492
+ """Update shadow parameters with current model parameters."""
493
+ if not self.shadow:
494
+ return
495
+ head = self._get_module(model)
496
+ with torch.no_grad():
497
+ for k, v in head.state_dict().items():
498
+ if k in self.shadow:
499
+ # Move to CPU for shadow update
500
+ v_cpu = v.detach().cpu().float()
501
+ self.shadow[k].mul_(self.decay).add_(v_cpu, alpha=(1.0 - self.decay))
502
+
503
+ def apply_shadow(self, model: nn.Module) -> Dict[str, Any]:
504
+ """Swap in EMA parameters. Returns original state for restore."""
505
+ head = self._get_module(model)
506
+ self._orig = {k: v.clone() for k, v in head.state_dict().items()}
507
+ # Load shadow (CPU) to model device
508
+ device = next(head.parameters()).device
509
+ ema_state = {k: v.to(device) for k, v in self.shadow.items()}
510
+ head.load_state_dict(ema_state, strict=False)
511
+ return self._orig
512
+
513
+ def restore(self, model: nn.Module):
514
+ """Restore original parameters (swap back from EMA)."""
515
+ if self._orig is None:
516
+ return
517
+ head = self._get_module(model)
518
+ head.load_state_dict(self._orig, strict=False)
519
+ self._orig = None
520
+
521
+
522
+ # ============================================================================
523
+ # SECTION 6: Model Setup for TPU
524
+ # ============================================================================
525
+
526
+ def setup_model_for_tpu(
527
+ model_args: TPUModelArguments,
528
+ device: torch.device,
529
+ ) -> Tuple[VibeVoiceForConditionalGeneration, VibeVoiceProcessor]:
530
+ """
531
+ Load and configure VibeVoice model for TPU training.
532
+
533
+ Returns:
534
+ (model, processor) tuple, both on the specified XLA device.
535
+ """
536
+ xm.master_print("=" * 70)
537
+ xm.master_print(" LOADING MODEL FOR TPU v5e-8 TRAINING")
538
+ xm.master_print("=" * 70)
539
+
540
+ # ── Load Processor ──
541
+ processor_path = model_args.processor_name_or_path or model_args.model_name_or_path
542
+ processor = VibeVoiceProcessor.from_pretrained(processor_path)
543
+
544
+ tok = processor.tokenizer
545
+ for required in ["speech_start_id", "speech_diffusion_id", "speech_end_id"]:
546
+ if not hasattr(tok, required) or getattr(tok, required) is None:
547
+ raise RuntimeError(f"Tokenizer missing required special id: {required}")
548
+
549
+ # ── Load Model ──
550
+ # Load in bf16 for TPU v5e compatibility
551
+ dtype = torch.bfloat16
552
+ xm.master_print(f" Loading model in {dtype} precision...")
553
+
554
+ # Check if this is a surgery model (has Qwen3SurgeryModule)
555
+ try:
556
+ from vibevoice_surgery_colab import load_surgery_model
557
+ model = load_surgery_model(
558
+ model_args.model_name_or_path,
559
+ dtype=dtype,
560
+ device_map="cpu",
561
+ )
562
+ xm.master_print(" Loaded as surgery model")
563
+ except (ImportError, Exception):
564
+ model = VibeVoiceForConditionalGeneration.from_pretrained(
565
+ model_args.model_name_or_path,
566
+ torch_dtype=dtype,
567
+ device_map="cpu",
568
+ )
569
+ xm.master_print(" Loaded as standard VibeVoice model")
570
+
571
+ _patch_acoustic_encode_for_legacy_indexing(model, logger)
572
+ processor.semantic_tokenizer = getattr(model.model, "semantic_tokenizer", None)
573
+
574
+ # ── Verify Surgery Module ──
575
+ has_surgery = hasattr(model.model, "surgery_module")
576
+ if has_surgery:
577
+ sm = model.model.surgery_module
578
+ xm.master_print(f" Surgery Module: {sm.extra_repr()}")
579
+ else:
580
+ xm.master_print(" No Surgery Module (standard model)")
581
+
582
+ # ── Force output_hidden_states ──
583
+ _force_output_hidden_states(model)
584
+
585
+ # ── Disable Cache ──
586
+ if hasattr(model.config, "use_cache"):
587
+ model.config.use_cache = False
588
+
589
+ # ── Tie LM Head ──
590
+ try:
591
+ emb = model.get_input_embeddings()
592
+ head = model.get_output_embeddings()
593
+ if hasattr(emb, "weight") and hasattr(head, "weight"):
594
+ if emb.weight.shape == head.weight.shape and emb.weight.data_ptr() != head.weight.data_ptr():
595
+ with torch.no_grad():
596
+ head.weight = emb.weight
597
+ xm.master_print(" Force-tied LM head to embed_tokens")
598
+ except Exception as e:
599
+ logger.warning(f"Force-tie LM head failed: {e}")
600
+
601
+ # ======================================================================
602
+ # FREEZING STRATEGY
603
+ # ======================================================================
604
+ xm.master_print("\n CONFIGURING LAYER FREEZING")
605
+
606
+ # Step 1: Freeze ALL
607
+ for _, p in model.named_parameters():
608
+ p.requires_grad = False
609
+
610
+ # Step 2: Tokenizers (always frozen)
611
+ if model_args.freeze_acoustic_tokenizer and hasattr(model.model, "acoustic_tokenizer"):
612
+ for p in model.model.acoustic_tokenizer.parameters():
613
+ p.requires_grad = False
614
+
615
+ if model_args.freeze_semantic_tokenizer and hasattr(model.model, "semantic_tokenizer"):
616
+ for p in model.model.semantic_tokenizer.parameters():
617
+ p.requires_grad = False
618
+
619
+ # Step 3: LoRA wrap LLM
620
+ tm_lower = [s.strip().lower() for s in model_args.lora_target_modules.split(",") if s.strip()]
621
+ skip_lm_lora = (len(tm_lower) == 0) or all(
622
+ t in ("none", "off", "disable", "disabled") for t in tm_lower
623
+ )
624
+
625
+ if not skip_lm_lora and not model_args.freeze_llm:
626
+ lora_cfg = build_lora_config(model_args)
627
+ model.model.language_model = get_peft_model(
628
+ model.model.language_model, lora_cfg
629
+ )
630
+ xm.master_print(f" LLM wrapped with LoRA (r={model_args.lora_r}, alpha={model_args.lora_alpha})")
631
+ elif model_args.freeze_llm:
632
+ xm.master_print(" LLM: FROZEN (no LoRA)")
633
+ else:
634
+ xm.master_print(" LLM LoRA: SKIPPED (target_modules=none)")
635
+
636
+ # Step 4: Re-enable LoRA params
637
+ if not skip_lm_lora and not model_args.freeze_llm:
638
+ for n, p in model.model.language_model.named_parameters():
639
+ if "lora_A" in n or "lora_B" in n:
640
+ p.requires_grad = True
641
+
642
+ # Step 5: Diffusion Head
643
+ if model_args.train_diffusion_head:
644
+ for p in model.model.prediction_head.parameters():
645
+ p.requires_grad = True
646
+ xm.master_print(" Diffusion Head: FULL TRAIN")
647
+ elif model_args.lora_wrap_diffusion_head:
648
+ class _HeadShim(nn.Module):
649
+ def __init__(self, base):
650
+ super().__init__()
651
+ self.base = base
652
+
653
+ def forward(self, *args, **kwargs):
654
+ if len(args) >= 3:
655
+ noisy_images, timesteps, condition = args[:3]
656
+ else:
657
+ noisy_images = kwargs.get("noisy_images")
658
+ timesteps = kwargs.get("timesteps")
659
+ condition = kwargs.get("condition")
660
+ return self.base(noisy_images, timesteps, condition)
661
+
662
+ try:
663
+ shim = _HeadShim(model.model.prediction_head)
664
+ model.model.prediction_head = get_peft_model(shim, build_head_lora_config(model_args))
665
+ for n, p in model.model.prediction_head.named_parameters():
666
+ if "lora_A" in n or "lora_B" in n:
667
+ p.requires_grad = True
668
+ xm.master_print(" Diffusion Head: LoRA WRAPPED")
669
+ except Exception as e:
670
+ logger.warning(f"Diffusion Head LoRA failed: {e}")
671
+ elif model_args.freeze_diffusion_head:
672
+ xm.master_print(" Diffusion Head: FROZEN")
673
+
674
+ # Step 6: Specific diffusion head layer freezing
675
+ if model_args.layers_to_freeze and hasattr(model.model, "prediction_head"):
676
+ head_params = list(model.model.prediction_head.named_parameters())
677
+ try:
678
+ indices = {int(x.strip()) for x in model_args.layers_to_freeze.split(",") if x.strip()}
679
+ for i, (name, param) in enumerate(head_params):
680
+ if i in indices:
681
+ param.requires_grad = False
682
+ xm.master_print(f" Froze diffusion head param [{i}]: {name}")
683
+ except Exception as e:
684
+ logger.error(f"layers_to_freeze parse error: {e}")
685
+
686
+ # Step 7: Surgery Module
687
+ if hasattr(model.model, "surgery_module"):
688
+ if model_args.freeze_surgery_module:
689
+ for p in model.model.surgery_module.parameters():
690
+ p.requires_grad = False
691
+ xm.master_print(" Surgery Module: FROZEN")
692
+ else:
693
+ for p in model.model.surgery_module.parameters():
694
+ p.requires_grad = True
695
+ xm.master_print(" Surgery Module: TRAINABLE")
696
+
697
+ # Step 8: Connectors
698
+ if model_args.train_connectors:
699
+ if hasattr(model.model, "acoustic_connector"):
700
+ for p in model.model.acoustic_connector.parameters():
701
+ p.requires_grad = True
702
+ if hasattr(model.model, "semantic_connector"):
703
+ for p in model.model.semantic_connector.parameters():
704
+ p.requires_grad = True
705
+ xm.master_print(" Connectors: TRAINABLE")
706
+ elif model_args.freeze_connectors:
707
+ xm.master_print(" Connectors: FROZEN")
708
+
709
+ # Step 9: Freeze embedding + LM head
710
+ try:
711
+ emb = model.get_input_embeddings()
712
+ if hasattr(emb, "weight"):
713
+ emb.weight.requires_grad_(False)
714
+ head = model.get_output_embeddings()
715
+ if head is not None and hasattr(head, "weight"):
716
+ if model_args.freeze_lm_head:
717
+ head.weight.requires_grad_(False)
718
+ xm.master_print(" LM Head: FROZEN")
719
+ except Exception as e:
720
+ logger.warning(f"Embedding/head freeze failed: {e}")
721
+
722
+ # ── Print Summary ──
723
+ print_model_summary(model, logger)
724
+
725
+ # ── Move to TPU device ──
726
+ xm.master_print(f"\n Moving model to XLA device: {device}")
727
+ model = model.to(device)
728
+ xm.master_print(" Model loaded on TPU successfully!")
729
+
730
+ return model, processor
731
+
732
+
733
+ # ============================================================================
734
+ # SECTION 7: Training Loop for TPU
735
+ # ============================================================================
736
+
737
+ class TPUScheduler:
738
+ """Learning rate scheduler compatible with TPU/XLA."""
739
+
740
+ def __init__(
741
+ self,
742
+ optimizer: torch.optim.Optimizer,
743
+ scheduler_type: str = "cosine",
744
+ num_warmup_steps: int = 100,
745
+ num_training_steps: int = 5000,
746
+ warmup_ratio: float = 0.1,
747
+ ):
748
+ self.optimizer = optimizer
749
+ self.scheduler_type = scheduler_type
750
+ self.num_warmup_steps = num_warmup_steps
751
+ self.num_training_steps = num_training_steps
752
+
753
+ if num_warmup_steps == 0 and warmup_ratio > 0:
754
+ self.num_warmup_steps = int(num_training_steps * warmup_ratio)
755
+
756
+ self.base_lrs = [group["lr"] for group in optimizer.param_groups]
757
+ self.current_step = 0
758
+
759
+ def get_lr_scale(self, step: int) -> float:
760
+ if step < self.num_warmup_steps:
761
+ return float(step) / float(max(1, self.num_warmup_steps))
762
+
763
+ if self.scheduler_type == "cosine":
764
+ progress = float(step - self.num_warmup_steps) / float(
765
+ max(1, self.num_training_steps - self.num_warmup_steps)
766
+ )
767
+ return max(0.0, 0.5 * (1.0 + math.cos(math.pi * progress)))
768
+ elif self.scheduler_type == "linear":
769
+ progress = float(step - self.num_warmup_steps) / float(
770
+ max(1, self.num_training_steps - self.num_warmup_steps)
771
+ )
772
+ return max(0.0, 1.0 - progress)
773
+ else:
774
+ return 1.0
775
+
776
+ def step(self):
777
+ self.current_step += 1
778
+ lr_scale = self.get_lr_scale(self.current_step)
779
+ for base_lr, group in zip(self.base_lrs, self.optimizer.param_groups):
780
+ group["lr"] = base_lr * lr_scale
781
+
782
+ def get_last_lr(self) -> float:
783
+ return self.optimizer.param_groups[0]["lr"]
784
+
785
+
786
+ def compute_loss(
787
+ model: VibeVoiceForConditionalGeneration,
788
+ inputs: Dict[str, torch.Tensor],
789
+ ce_loss_weight: float = 1.0,
790
+ diffusion_loss_weight: float = 1.0,
791
+ ddpm_batch_mul: int = 1,
792
+ ) -> Tuple[torch.Tensor, Dict[str, float]]:
793
+ """
794
+ Compute the combined CE + Diffusion loss for VibeVoice.
795
+
796
+ Returns:
797
+ (total_loss, metrics_dict)
798
+ """
799
+ labels = inputs.get("input_ids")
800
+ attention_mask = inputs.get("attention_mask")
801
+ acoustic_input_mask = inputs.get("acoustic_input_mask")
802
+
803
+ # Align semantic tensor dtype
804
+ sem = inputs.get("speech_semantic_tensors", None)
805
+ try:
806
+ target_dtype = next(model.model.semantic_connector.parameters()).dtype
807
+ except Exception:
808
+ target_dtype = model.get_input_embeddings().weight.dtype
809
+
810
+ if sem is None:
811
+ sm = inputs.get("speech_masks")
812
+ if sm is not None:
813
+ sem_dim = getattr(model.config, "semantic_vae_dim", 128)
814
+ inputs["speech_semantic_tensors"] = torch.zeros(
815
+ sm.size(0), sm.size(1), sem_dim,
816
+ dtype=target_dtype, device=sm.device,
817
+ )
818
+ elif isinstance(sem, torch.Tensor):
819
+ inputs["speech_semantic_tensors"] = sem.to(dtype=target_dtype)
820
+
821
+ # ── Forward ──
822
+ outputs = model(
823
+ input_ids=inputs.get("input_ids"),
824
+ attention_mask=attention_mask,
825
+ speech_tensors=inputs.get("speech_tensors"),
826
+ speech_masks=inputs.get("speech_masks"),
827
+ speech_semantic_tensors=inputs.get("speech_semantic_tensors"),
828
+ acoustic_input_mask=acoustic_input_mask,
829
+ acoustic_loss_mask=inputs.get("acoustic_loss_mask"),
830
+ speeches_loss_input=inputs.get("speeches_loss_input"),
831
+ ddpm_batch_mul=ddpm_batch_mul,
832
+ output_hidden_states=True,
833
+ )
834
+
835
+ # ── CE Loss ──
836
+ logits = outputs.logits
837
+ ce_labels = mask_for_ce(labels, attention_mask, acoustic_input_mask, pad_id=-100)
838
+ shift_logits = logits[:, :-1, :].contiguous()
839
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
840
+ ce_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), ce_labels.view(-1))
841
+
842
+ # ── Diffusion Loss ──
843
+ has_surgery = hasattr(model.model, "surgery_module")
844
+
845
+ if has_surgery and hasattr(outputs, "hidden_states") and outputs.hidden_states is not None:
846
+ diffusion_loss = _compute_surgery_diffusion_loss(
847
+ model, inputs, outputs, acoustic_input_mask, ddpm_batch_mul
848
+ )
849
+ else:
850
+ diffusion_loss = (
851
+ outputs.diffusion_loss
852
+ if outputs.diffusion_loss is not None
853
+ else torch.tensor(0.0, device=ce_loss.device, dtype=ce_loss.dtype)
854
+ )
855
+
856
+ # ── Combined Loss ──
857
+ total = ce_loss_weight * ce_loss + diffusion_loss_weight * diffusion_loss
858
+
859
+ metrics = {
860
+ "ce_loss": ce_loss.detach().item(),
861
+ "diffusion_loss": diffusion_loss.detach().item() if isinstance(diffusion_loss, torch.Tensor) else float(diffusion_loss),
862
+ "total_loss": total.detach().item(),
863
+ }
864
+
865
+ return total, metrics
866
+
867
+
868
+ def _compute_surgery_diffusion_loss(
869
+ model: VibeVoiceForConditionalGeneration,
870
+ inputs: Dict[str, torch.Tensor],
871
+ outputs: Any,
872
+ acoustic_input_mask: torch.Tensor,
873
+ ddpm_batch_mul: int = 1,
874
+ ) -> torch.Tensor:
875
+ """Compute diffusion loss using Surgery Module to project hidden states."""
876
+ speech_tensors = inputs.get("speech_tensors")
877
+ speech_masks = inputs.get("speech_masks")
878
+ acoustic_loss_mask = inputs.get("acoustic_loss_mask")
879
+ speeches_loss_input = inputs.get("speeches_loss_input")
880
+
881
+ if speech_tensors is None or acoustic_loss_mask is None:
882
+ return sum(p.sum() for p in model.model.prediction_head.parameters()) * 0.0
883
+
884
+ if acoustic_loss_mask.sum().item() == 0:
885
+ return sum(p.sum() for p in model.model.prediction_head.parameters()) * 0.0
886
+
887
+ hidden_states = outputs.last_hidden_state
888
+
889
+ # Get ground truth acoustic features
890
+ x = model.get_input_embeddings()(inputs["input_ids"])
891
+ with torch.no_grad():
892
+ speech_all_features, _ = model.forward_speech_features(
893
+ speech_tensors=speech_tensors.type_as(x),
894
+ speech_masks=speech_masks,
895
+ return_unmask=True,
896
+ )
897
+ speech_features = speech_all_features[speeches_loss_input & speech_masks]
898
+
899
+ # Build condition from hidden states + Surgery Module
900
+ cond_mask = torch.zeros_like(acoustic_loss_mask, dtype=torch.bool)
901
+ cond_mask[:, :-1] = acoustic_loss_mask[:, 1:]
902
+ cond_mask[:, 0] = False
903
+ condition_features = hidden_states[cond_mask]
904
+
905
+ # Apply Surgery Module: 2560 → 3584
906
+ condition_features = model.model.surgery_module(condition_features)
907
+
908
+ speech_len, latent_size = speech_features.shape
909
+ noise = torch.randn(
910
+ (speech_len * ddpm_batch_mul, latent_size),
911
+ device=hidden_states.device,
912
+ dtype=hidden_states.dtype,
913
+ )
914
+ timesteps = torch.multinomial(
915
+ torch.ones(model.config.diffusion_head_config.ddpm_num_steps),
916
+ speech_len * ddpm_batch_mul,
917
+ replacement=True,
918
+ ).to(hidden_states.device)
919
+
920
+ speech_features_rep = speech_features.repeat_interleave(ddpm_batch_mul, dim=0)
921
+ condition_features_rep = condition_features.repeat_interleave(ddpm_batch_mul, dim=0)
922
+
923
+ noisy_speech = model.model.noise_scheduler.add_noise(speech_features_rep, noise, timesteps)
924
+ model_output = model.model.prediction_head(noisy_speech, timesteps.type_as(x), condition_features_rep)
925
+
926
+ prediction_type = model.config.diffusion_head_config.prediction_type
927
+ if prediction_type == "epsilon":
928
+ target = noise
929
+ elif prediction_type == "v_prediction":
930
+ target = model.model.noise_scheduler.get_velocity(speech_features_rep, noise, timesteps)
931
+ else:
932
+ raise NotImplementedError(f"Prediction type {prediction_type} not implemented")
933
+
934
+ loss = F.mse_loss(model_output.float(), target.float(), reduction="sum")
935
+ if latent_size > 0 and ddpm_batch_mul > 0:
936
+ loss = loss / latent_size / ddpm_batch_mul / max(speech_len, 1)
937
+ return loss
938
+
939
+
940
+ # ============================================================================
941
+ # SECTION 8: Checkpoint Save/Load
942
+ # ============================================================================
943
+
944
+ def save_checkpoint(
945
+ model: VibeVoiceForConditionalGeneration,
946
+ optimizer: torch.optim.Optimizer,
947
+ scheduler: TPUScheduler,
948
+ ema: EMAModel,
949
+ global_step: int,
950
+ output_dir: str,
951
+ save_total_limit: int = 3,
952
+ ):
953
+ """Save training checkpoint compatible with GPU inference."""
954
+ ckpt_dir = os.path.join(output_dir, f"checkpoint-{global_step}")
955
+ lora_out = os.path.join(ckpt_dir, "lora")
956
+ os.makedirs(lora_out, exist_ok=True)
957
+
958
+ xm.master_print(f"\n Saving checkpoint at step {global_step} to {ckpt_dir}")
959
+
960
+ # Ensure we're saving the EMA version
961
+ ema.apply_shadow(model)
962
+
963
+ # ── LLM LoRA adapters ──
964
+ lm = getattr(model.model, "language_model", None)
965
+ if hasattr(lm, "save_pretrained"):
966
+ lm.save_pretrained(lora_out)
967
+
968
+ # ── Diffusion Head ──
969
+ ph = getattr(model.model, "prediction_head", None)
970
+ if ph is not None and hasattr(ph, "state_dict"):
971
+ sd = ph.state_dict()
972
+ # Save to CPU for cross-device compatibility
973
+ sd_cpu = {k: v.cpu() for k, v in sd.items()}
974
+ torch.save(sd_cpu, os.path.join(lora_out, "diffusion_head_full.bin"))
975
+
976
+ if hasattr(ph, "save_pretrained"):
977
+ ph_dir = os.path.join(lora_out, "diffusion_head")
978
+ os.makedirs(ph_dir, exist_ok=True)
979
+ ph.save_pretrained(ph_dir)
980
+ torch.save(sd_cpu, os.path.join(ph_dir, "diffusion_head_full.bin"))
981
+
982
+ # ── Connectors ──
983
+ for conn_name in ["acoustic_connector", "semantic_connector"]:
984
+ conn = getattr(model.model, conn_name, None)
985
+ if conn is not None:
986
+ conn_dir = os.path.join(lora_out, conn_name)
987
+ os.makedirs(conn_dir, exist_ok=True)
988
+ sd = {k: v.cpu() for k, v in conn.state_dict().items()}
989
+ torch.save(sd, os.path.join(conn_dir, "pytorch_model.bin"))
990
+
991
+ # ── Surgery Module ──
992
+ sm = getattr(model.model, "surgery_module", None)
993
+ if sm is not None:
994
+ sm_dir = os.path.join(lora_out, "surgery_module")
995
+ os.makedirs(sm_dir, exist_ok=True)
996
+ sd = {k: v.cpu() for k, v in sm.state_dict().items()}
997
+ torch.save(sd, os.path.join(sm_dir, "pytorch_model.bin"))
998
+
999
+ # ── Training state ──
1000
+ training_state = {
1001
+ "global_step": global_step,
1002
+ "optimizer_state": {
1003
+ "param_groups": optimizer.param_groups,
1004
+ },
1005
+ "scheduler_step": scheduler.current_step,
1006
+ "ema_decay": ema.decay,
1007
+ }
1008
+ # Move optimizer states to CPU for saving
1009
+ optimizer_state_dict = {}
1010
+ for k, v in optimizer.state_dict().items():
1011
+ if isinstance(v, dict):
1012
+ cpu_v = {}
1013
+ for kk, vv in v.items():
1014
+ if isinstance(vv, torch.Tensor):
1015
+ cpu_v[kk] = vv.cpu()
1016
+ else:
1017
+ cpu_v[kk] = vv
1018
+ optimizer_state_dict[k] = cpu_v
1019
+ elif isinstance(v, torch.Tensor):
1020
+ optimizer_state_dict[k] = v.cpu()
1021
+ else:
1022
+ optimizer_state_dict[k] = v
1023
+ training_state["optimizer_state_dict"] = optimizer_state_dict
1024
+
1025
+ torch.save(training_state, os.path.join(ckpt_dir, "training_state.pt"))
1026
+
1027
+ # Restore original parameters
1028
+ ema.restore(model)
1029
+
1030
+ xm.master_print(f" Checkpoint saved: {ckpt_dir}")
1031
+
1032
+ # ── Cleanup old checkpoints ──
1033
+ _cleanup_old_checkpoints(output_dir, save_total_limit, global_step)
1034
+
1035
+
1036
+ def _cleanup_old_checkpoints(output_dir: str, save_total_limit: int, current_step: int):
1037
+ """Remove old checkpoints keeping only the most recent ones."""
1038
+ if save_total_limit <= 0:
1039
+ return
1040
+
1041
+ checkpoint_dirs = []
1042
+ for d in os.listdir(output_dir):
1043
+ if d.startswith("checkpoint-"):
1044
+ try:
1045
+ step = int(d.split("-")[1])
1046
+ checkpoint_dirs.append((step, os.path.join(output_dir, d)))
1047
+ except (ValueError, IndexError):
1048
+ pass
1049
+
1050
+ checkpoint_dirs.sort(key=lambda x: x[0])
1051
+
1052
+ while len(checkpoint_dirs) > save_total_limit:
1053
+ step, path = checkpoint_dirs.pop(0)
1054
+ if step != current_step:
1055
+ import shutil
1056
+ shutil.rmtree(path, ignore_errors=True)
1057
+ xm.master_print(f" Removed old checkpoint: {path}")
1058
+
1059
+
1060
+ def load_checkpoint(
1061
+ checkpoint_path: str,
1062
+ model: VibeVoiceForConditionalGeneration,
1063
+ optimizer: torch.optim.Optimizer,
1064
+ scheduler: TPUScheduler,
1065
+ ) -> int:
1066
+ """Load training checkpoint and return the global step."""
1067
+ xm.master_print(f"\n Resuming from checkpoint: {checkpoint_path}")
1068
+
1069
+ lora_dir = os.path.join(checkpoint_path, "lora")
1070
+ if not os.path.exists(lora_dir):
1071
+ xm.master_print(f" No 'lora' directory found in {checkpoint_path}")
1072
+ return 0
1073
+
1074
+ # ── Load LLM LoRA ──
1075
+ lm = getattr(model.model, "language_model", None)
1076
+ if hasattr(lm, "save_pretrained"):
1077
+ try:
1078
+ from peft import load_peft_weights, set_peft_model_state_dict
1079
+ adapters_weights = load_peft_weights(lora_dir)
1080
+ set_peft_model_state_dict(model.model.language_model, adapters_weights)
1081
+ xm.master_print(" Loaded LLM LoRA weights")
1082
+ except Exception as e:
1083
+ logger.warning(f"Could not load LLM LoRA: {e}")
1084
+
1085
+ # ── Load Diffusion Head ──
1086
+ ph_path = os.path.join(lora_dir, "diffusion_head_full.bin")
1087
+ if os.path.exists(ph_path) and hasattr(model.model, "prediction_head"):
1088
+ try:
1089
+ model.model.prediction_head.load_state_dict(
1090
+ torch.load(ph_path, map_location="cpu"), strict=False
1091
+ )
1092
+ xm.master_print(" Loaded Diffusion Head weights")
1093
+ except Exception as e:
1094
+ logger.warning(f"Failed to load Diffusion Head: {e}")
1095
+
1096
+ # ── Load Connectors ──
1097
+ for conn_name in ["acoustic_connector", "semantic_connector"]:
1098
+ conn_path = os.path.join(lora_dir, conn_name, "pytorch_model.bin")
1099
+ conn = getattr(model.model, conn_name, None)
1100
+ if os.path.exists(conn_path) and conn is not None:
1101
+ try:
1102
+ conn.load_state_dict(torch.load(conn_path, map_location="cpu"))
1103
+ xm.master_print(f" Loaded {conn_name}")
1104
+ except Exception as e:
1105
+ logger.warning(f"Failed to load {conn_name}: {e}")
1106
+
1107
+ # ── Load Surgery Module ──
1108
+ sm_path = os.path.join(lora_dir, "surgery_module", "pytorch_model.bin")
1109
+ sm = getattr(model.model, "surgery_module", None)
1110
+ if os.path.exists(sm_path) and sm is not None:
1111
+ try:
1112
+ sm.load_state_dict(torch.load(sm_path, map_location="cpu"))
1113
+ xm.master_print(" Loaded Surgery Module weights")
1114
+ except Exception as e:
1115
+ logger.warning(f"Failed to load Surgery Module: {e}")
1116
+
1117
+ # ── Load Training State ──
1118
+ state_path = os.path.join(checkpoint_path, "training_state.pt")
1119
+ global_step = 0
1120
+ if os.path.exists(state_path):
1121
+ try:
1122
+ training_state = torch.load(state_path, map_location="cpu")
1123
+ global_step = training_state.get("global_step", 0)
1124
+ scheduler.current_step = training_state.get("scheduler_step", 0)
1125
+ xm.master_print(f" Resumed at global_step={global_step}")
1126
+ except Exception as e:
1127
+ logger.warning(f"Failed to load training state: {e}")
1128
+
1129
+ return global_step
1130
+
1131
+
1132
+ # ============================================================================
1133
+ # SECTION 9: Main Training Function (per-TPU process)
1134
+ # ============================================================================
1135
+
1136
+ def train_fn(rank: int, model_args: TPUModelArguments, data_args: TPUDataArguments,
1137
+ training_args: TPUTrainingArguments):
1138
+ """
1139
+ Main training function executed on each TPU chip.
1140
+
1141
+ Args:
1142
+ rank: TPU chip index (0-7)
1143
+ model_args: Model configuration
1144
+ data_args: Data configuration
1145
+ training_args: Training configuration
1146
+ """
1147
+ # ── Setup ──
1148
+ device = xm.xla_device()
1149
+ xm.master_print(f"\n{'='*70}")
1150
+ xm.master_print(f" TPU v5e-8 Fine-Tuning | Process {rank} | Device: {device}")
1151
+ xm.master_print(f"{'='*70}")
1152
+
1153
+ set_seed(training_args.seed + rank)
1154
+
1155
+ # ── Load Model ──
1156
+ model, processor = setup_model_for_tpu(model_args, device)
1157
+
1158
+ # ── Load Preprocessed Data ──
1159
+ xm.master_print(f"\n Loading preprocessed data from {data_args.preprocessed_dir}")
1160
+ full_dataset = TPUPreprocessedDataset(data_args.preprocessed_dir, logger)
1161
+
1162
+ # ── Train/Eval Split ──
1163
+ eval_dataset = None
1164
+ if data_args.eval_split_size > 0 and len(full_dataset) > 1:
1165
+ num_eval = max(1, int(len(full_dataset) * data_args.eval_split_size))
1166
+ num_train = len(full_dataset) - num_eval
1167
+ indices = list(range(len(full_dataset)))
1168
+ random.Random(training_args.seed).shuffle(indices)
1169
+
1170
+ train_dataset = torch.utils.data.Subset(full_dataset, indices[:num_train])
1171
+ eval_dataset = torch.utils.data.Subset(full_dataset, indices[num_train:])
1172
+ xm.master_print(f" Train samples: {len(train_dataset)}, Eval samples: {len(eval_dataset)}")
1173
+ else:
1174
+ train_dataset = full_dataset
1175
+ xm.master_print(f" Train samples: {len(train_dataset)}")
1176
+
1177
+ # ── Data Loaders ──
1178
+ train_sampler = torch.utils.data.distributed.DistributedSampler(
1179
+ train_dataset,
1180
+ num_replicas=xm.xrt_world_size(),
1181
+ rank=xm.get_ordinal(),
1182
+ shuffle=True,
1183
+ seed=training_args.seed,
1184
+ )
1185
+
1186
+ train_loader = torch.utils.data.DataLoader(
1187
+ train_dataset,
1188
+ batch_size=training_args.per_device_train_batch_size,
1189
+ sampler=train_sampler,
1190
+ collate_fn=TPUBatchCollator(),
1191
+ num_workers=0, # Use 0 for TPU (data on CPU, transferred via XLA)
1192
+ pin_memory=False,
1193
+ drop_last=True,
1194
+ )
1195
+
1196
+ # Wrap with MpDeviceLoader for TPU
1197
+ train_device_loader = pl.MpDeviceLoader(train_loader, device)
1198
+
1199
+ eval_device_loader = None
1200
+ if eval_dataset is not None:
1201
+ eval_sampler = torch.utils.data.distributed.DistributedSampler(
1202
+ eval_dataset,
1203
+ num_replicas=xm.xrt_world_size(),
1204
+ rank=xm.get_ordinal(),
1205
+ shuffle=False,
1206
+ )
1207
+ eval_loader = torch.utils.data.DataLoader(
1208
+ eval_dataset,
1209
+ batch_size=training_args.per_device_train_batch_size,
1210
+ sampler=eval_sampler,
1211
+ collate_fn=TPUBatchCollator(),
1212
+ num_workers=0,
1213
+ pin_memory=False,
1214
+ drop_last=False,
1215
+ )
1216
+ eval_device_loader = pl.MpDeviceLoader(eval_loader, device)
1217
+
1218
+ # ── Optimizer ──
1219
+ trainable_params = [p for p in model.parameters() if p.requires_grad]
1220
+ xm.master_print(f"\n Trainable parameters: {sum(p.numel() for p in trainable_params):,}")
1221
+
1222
+ optimizer = torch.optim.AdamW(
1223
+ trainable_params,
1224
+ lr=training_args.learning_rate,
1225
+ betas=(0.9, 0.999),
1226
+ eps=1e-8,
1227
+ weight_decay=0.01,
1228
+ )
1229
+
1230
+ # ── Scheduler ──
1231
+ scheduler = TPUScheduler(
1232
+ optimizer,
1233
+ scheduler_type=training_args.lr_scheduler_type,
1234
+ num_warmup_steps=training_args.warmup_steps,
1235
+ num_training_steps=training_args.max_steps,
1236
+ warmup_ratio=training_args.warmup_ratio,
1237
+ )
1238
+
1239
+ # ── EMA ──
1240
+ ema = EMAModel(
1241
+ model,
1242
+ attr_path="model.prediction_head",
1243
+ decay=training_args.ema_decay,
1244
+ )
1245
+ ema.initialize(model)
1246
+
1247
+ # ── Gradient Checkpointing ──
1248
+ if training_args.gradient_checkpointing:
1249
+ try:
1250
+ model.gradient_checkpointing_enable()
1251
+ xm.master_print(" Gradient checkpointing enabled")
1252
+ except Exception as e:
1253
+ logger.warning(f"Failed to enable gradient checkpointing: {e}")
1254
+
1255
+ # ── Resume from Checkpoint ──
1256
+ global_step = 0
1257
+ if training_args.resume_from_checkpoint and os.path.exists(training_args.resume_from_checkpoint):
1258
+ global_step = load_checkpoint(
1259
+ training_args.resume_from_checkpoint, model, optimizer, scheduler
1260
+ )
1261
+ # Move model back to device after loading CPU weights
1262
+ model = model.to(device)
1263
+
1264
+ # ── Training Loop ──
1265
+ xm.master_print(f"\n{'='*70}")
1266
+ xm.master_print(f" STARTING TRAINING")
1267
+ xm.master_print(f" Max steps: {training_args.max_steps}")
1268
+ xm.master_print(f" Gradient accumulation: {training_args.gradient_accumulation_steps}")
1269
+ xm.master_print(f" Effective batch size: {training_args.per_device_train_batch_size} × {xm.xrt_world_size()} × {training_args.gradient_accumulation_steps}")
1270
+ xm.master_print(f"{'='*70}\n")
1271
+
1272
+ model.train()
1273
+ optimizer.zero_grad()
1274
+
1275
+ accum_steps = training_args.gradient_accumulation_steps
1276
+ log_steps = training_args.logging_steps
1277
+ save_steps = training_args.save_steps
1278
+ eval_steps = training_args.eval_steps
1279
+
1280
+ running_metrics: Dict[str, float] = {}
1281
+ step_loss = 0.0
1282
+ step_count = 0
1283
+ start_time = time.time()
1284
+ epoch = 0
1285
+
1286
+ while global_step < training_args.max_steps:
1287
+ epoch += 1
1288
+ train_sampler.set_epoch(epoch)
1289
+ xm.master_print(f"\n === Epoch {epoch} ===")
1290
+
1291
+ for batch_idx, batch in enumerate(train_device_loader):
1292
+ if global_step >= training_args.max_steps:
1293
+ break
1294
+
1295
+ # ── Forward + Backward ──
1296
+ with autocast(device=device, dtype=torch.bfloat16):
1297
+ loss, metrics = compute_loss(
1298
+ model, batch,
1299
+ ce_loss_weight=training_args.ce_loss_weight,
1300
+ diffusion_loss_weight=training_args.diffusion_loss_weight,
1301
+ ddpm_batch_mul=training_args.ddpm_batch_mul,
1302
+ )
1303
+ loss = loss / accum_steps
1304
+
1305
+ loss.backward()
1306
+
1307
+ # Accumulate metrics
1308
+ for k, v in metrics.items():
1309
+ running_metrics[k] = running_metrics.get(k, 0.0) + v
1310
+ step_loss += loss.item()
1311
+ step_count += 1
1312
+
1313
+ # ── Gradient Accumulation Sync ──
1314
+ if (batch_idx + 1) % accum_steps == 0:
1315
+ # Gradient clipping
1316
+ if training_args.max_grad_norm > 0:
1317
+ torch.nn.utils.clip_grad_norm_(
1318
+ trainable_params, training_args.max_grad_norm
1319
+ )
1320
+
1321
+ # Optimizer step (XLA synchronized)
1322
+ xm.optimizer_step(optimizer)
1323
+ optimizer.zero_grad()
1324
+
1325
+ # Scheduler step
1326
+ scheduler.step()
1327
+
1328
+ # EMA update
1329
+ ema.update(model)
1330
+
1331
+ global_step += 1
1332
+
1333
+ # ── Logging ──
1334
+ if global_step % log_steps == 0:
1335
+ elapsed = time.time() - start_time
1336
+ avg_loss = step_loss / max(step_count, 1)
1337
+ lr = scheduler.get_last_lr()
1338
+
1339
+ avg_metrics = {
1340
+ k: v / max(step_count, 1) for k, v in running_metrics.items()
1341
+ }
1342
+
1343
+ xm.master_print(
1344
+ f" Step {global_step}/{training_args.max_steps} | "
1345
+ f"Loss: {avg_loss:.4f} | "
1346
+ f"CE: {avg_metrics.get('ce_loss', 0):.4f} | "
1347
+ f"Diff: {avg_metrics.get('diffusion_loss', 0):.4f} | "
1348
+ f"LR: {lr:.2e} | "
1349
+ f"Time: {elapsed:.1f}s"
1350
+ )
1351
+
1352
+ running_metrics = {}
1353
+ step_loss = 0.0
1354
+ step_count = 0
1355
+ start_time = time.time()
1356
+
1357
+ # ── Evaluation ──
1358
+ if eval_device_loader is not None and global_step % eval_steps == 0:
1359
+ eval_loss = _evaluate(model, eval_device_loader, training_args, device)
1360
+ xm.master_print(f" [EVAL] Step {global_step} | Loss: {eval_loss:.4f}")
1361
+
1362
+ # ── Save Checkpoint ──
1363
+ if global_step % save_steps == 0:
1364
+ xm.rendezvous("save_checkpoint")
1365
+ save_checkpoint(
1366
+ model, optimizer, scheduler, ema,
1367
+ global_step, training_args.output_dir,
1368
+ training_args.save_total_limit,
1369
+ )
1370
+
1371
+ # Mark step for XLA compilation
1372
+ xm.mark_step()
1373
+
1374
+ # ── Final Save ──
1375
+ xm.rendezvous("final_save")
1376
+ save_checkpoint(
1377
+ model, optimizer, scheduler, ema,
1378
+ global_step, training_args.output_dir,
1379
+ training_args.save_total_limit,
1380
+ )
1381
+
1382
+ # Also save final model in a clean format
1383
+ _save_final_model(model, ema, training_args.output_dir)
1384
+
1385
+ xm.master_print(f"\n{'='*70}")
1386
+ xm.master_print(f" TRAINING COMPLETE!")
1387
+ xm.master_print(f" Total steps: {global_step}")
1388
+ xm.master_print(f" Model saved to: {training_args.output_dir}")
1389
+ xm.master_print(f"{'='*70}")
1390
+
1391
+
1392
+ def _evaluate(
1393
+ model: VibeVoiceForConditionalGeneration,
1394
+ eval_loader: pl.MpDeviceLoader,
1395
+ training_args: TPUTrainingArguments,
1396
+ device: torch.device,
1397
+ ) -> float:
1398
+ """Run evaluation and return average loss."""
1399
+ model.eval()
1400
+ total_loss = 0.0
1401
+ num_batches = 0
1402
+
1403
+ with torch.no_grad():
1404
+ for batch in eval_loader:
1405
+ with autocast(device=device, dtype=torch.bfloat16):
1406
+ loss, _ = compute_loss(
1407
+ model, batch,
1408
+ ce_loss_weight=training_args.ce_loss_weight,
1409
+ diffusion_loss_weight=training_args.diffusion_loss_weight,
1410
+ ddpm_batch_mul=training_args.ddpm_batch_mul,
1411
+ )
1412
+ total_loss += loss.item()
1413
+ num_batches += 1
1414
+ xm.mark_step()
1415
+
1416
+ if num_batches >= 50: # Limit eval batches
1417
+ break
1418
+
1419
+ model.train()
1420
+ avg_loss = total_loss / max(num_batches, 1)
1421
+
1422
+ # All-reduce eval loss across TPU chips
1423
+ loss_tensor = torch.tensor([avg_loss], device=device)
1424
+ xm.all_reduce("sum", [loss_tensor])
1425
+ avg_loss = loss_tensor.item() / xm.xrt_world_size()
1426
+
1427
+ return avg_loss
1428
+
1429
+
1430
+ def _save_final_model(
1431
+ model: VibeVoiceForConditionalGeneration,
1432
+ ema: EMAModel,
1433
+ output_dir: str,
1434
+ ):
1435
+ """Save the final trained model in a clean format."""
1436
+ final_dir = os.path.join(output_dir, "final_model")
1437
+ lora_out = os.path.join(final_dir, "lora")
1438
+ os.makedirs(lora_out, exist_ok=True)
1439
+
1440
+ xm.master_print(f"\n Saving final model to {final_dir}")
1441
+
1442
+ # Apply EMA for final save
1443
+ ema.apply_shadow(model)
1444
+
1445
+ # Save all components
1446
+ lm = getattr(model.model, "language_model", None)
1447
+ if hasattr(lm, "save_pretrained"):
1448
+ lm.save_pretrained(lora_out)
1449
+
1450
+ ph = getattr(model.model, "prediction_head", None)
1451
+ if ph is not None and hasattr(ph, "state_dict"):
1452
+ sd = {k: v.cpu() for k, v in ph.state_dict().items()}
1453
+ torch.save(sd, os.path.join(lora_out, "diffusion_head_full.bin"))
1454
+
1455
+ for conn_name in ["acoustic_connector", "semantic_connector"]:
1456
+ conn = getattr(model.model, conn_name, None)
1457
+ if conn is not None:
1458
+ conn_dir = os.path.join(lora_out, conn_name)
1459
+ os.makedirs(conn_dir, exist_ok=True)
1460
+ sd = {k: v.cpu() for k, v in conn.state_dict().items()}
1461
+ torch.save(sd, os.path.join(conn_dir, "pytorch_model.bin"))
1462
+
1463
+ sm = getattr(model.model, "surgery_module", None)
1464
+ if sm is not None:
1465
+ sm_dir = os.path.join(lora_out, "surgery_module")
1466
+ os.makedirs(sm_dir, exist_ok=True)
1467
+ sd = {k: v.cpu() for k, v in sm.state_dict().items()}
1468
+ torch.save(sd, os.path.join(sm_dir, "pytorch_model.bin"))
1469
+
1470
+ ema.restore(model)
1471
+ xm.master_print(f" Final model saved to {final_dir}")
1472
+
1473
+
1474
+ # ============================================================================
1475
+ # SECTION 10: Entry Point
1476
+ # ============================================================================
1477
+
1478
+ def main():
1479
+ """Parse arguments and launch TPU training."""
1480
+ import argparse
1481
+
1482
+ parser = argparse.ArgumentParser(
1483
+ description="VibeVoice Fine-Tuning on TPU v5e-8",
1484
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
1485
+ )
1486
+
1487
+ # Model arguments
1488
+ parser.add_argument("--model_name_or_path", type=str, required=True,
1489
+ help="Path to VibeVoice/surgery model directory")
1490
+ parser.add_argument("--processor_name_or_path", type=str, default=None,
1491
+ help="Path to processor directory")
1492
+
1493
+ # Freezing
1494
+ parser.add_argument("--freeze_llm", action="store_true", default=False)
1495
+ parser.add_argument("--no_freeze_llm", dest="freeze_llm", action="store_false")
1496
+ parser.add_argument("--freeze_diffusion_head", action="store_true", default=True)
1497
+ parser.add_argument("--no_freeze_diffusion_head", dest="freeze_diffusion_head", action="store_false")
1498
+ parser.add_argument("--freeze_surgery_module", action="store_true", default=False)
1499
+ parser.add_argument("--freeze_connectors", action="store_true", default=False)
1500
+ parser.add_argument("--train_diffusion_head", action="store_true", default=False)
1501
+ parser.add_argument("--train_connectors", action="store_true", default=True)
1502
+ parser.add_argument("--train_surgery_module", action="store_true", default=True)
1503
+ parser.add_argument("--lora_wrap_diffusion_head", action="store_true", default=False)
1504
+
1505
+ # LoRA
1506
+ parser.add_argument("--lora_r", type=int, default=8)
1507
+ parser.add_argument("--lora_alpha", type=int, default=32)
1508
+ parser.add_argument("--lora_dropout", type=float, default=0.05)
1509
+ parser.add_argument("--lora_target_modules", type=str,
1510
+ default="q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj")
1511
+ parser.add_argument("--layers_to_freeze", type=str, default=None)
1512
+
1513
+ # Data
1514
+ parser.add_argument("--preprocessed_dir", type=str, required=True,
1515
+ help="Directory containing preprocessed .pt files")
1516
+ parser.add_argument("--eval_split_size", type=float, default=0.05)
1517
+
1518
+ # Training
1519
+ parser.add_argument("--output_dir", type=str, default="./output_tpu")
1520
+ parser.add_argument("--max_steps", type=int, default=5000)
1521
+ parser.add_argument("--num_train_epochs", type=int, default=3)
1522
+ parser.add_argument("--learning_rate", type=float, default=2e-5)
1523
+ parser.add_argument("--lr_scheduler_type", type=str, default="cosine")
1524
+ parser.add_argument("--warmup_steps", type=int, default=100)
1525
+ parser.add_argument("--warmup_ratio", type=float, default=0.1)
1526
+ parser.add_argument("--per_device_train_batch_size", type=int, default=1)
1527
+ parser.add_argument("--gradient_accumulation_steps", type=int, default=8)
1528
+ parser.add_argument("--max_grad_norm", type=float, default=1.0)
1529
+ parser.add_argument("--gradient_checkpointing", action="store_true", default=True)
1530
+ parser.add_argument("--no_gradient_checkpointing", dest="gradient_checkpointing", action="store_false")
1531
+
1532
+ # Loss weights
1533
+ parser.add_argument("--ce_loss_weight", type=float, default=1.0)
1534
+ parser.add_argument("--diffusion_loss_weight", type=float, default=1.0)
1535
+ parser.add_argument("--ddpm_batch_mul", type=int, default=1)
1536
+
1537
+ # Logging & saving
1538
+ parser.add_argument("--logging_steps", type=int, default=10)
1539
+ parser.add_argument("--save_steps", type=int, default=500)
1540
+ parser.add_argument("--eval_steps", type=int, default=500)
1541
+ parser.add_argument("--save_total_limit", type=int, default=3)
1542
+
1543
+ # EMA
1544
+ parser.add_argument("--ema_decay", type=float, default=0.999)
1545
+
1546
+ # Resume
1547
+ parser.add_argument("--resume_from_checkpoint", type=str, default=None)
1548
+
1549
+ # Seed
1550
+ parser.add_argument("--seed", type=int, default=42)
1551
+
1552
+ args = parser.parse_args()
1553
+
1554
+ # Build argument dataclasses
1555
+ model_args = TPUModelArguments(
1556
+ model_name_or_path=args.model_name_or_path,
1557
+ processor_name_or_path=args.processor_name_or_path,
1558
+ freeze_llm=args.freeze_llm,
1559
+ freeze_diffusion_head=args.freeze_diffusion_head,
1560
+ freeze_surgery_module=args.freeze_surgery_module,
1561
+ freeze_connectors=args.freeze_connectors,
1562
+ freeze_acoustic_tokenizer=True,
1563
+ freeze_semantic_tokenizer=True,
1564
+ freeze_lm_head=True,
1565
+ lora_r=args.lora_r,
1566
+ lora_alpha=args.lora_alpha,
1567
+ lora_dropout=args.lora_dropout,
1568
+ lora_target_modules=args.lora_target_modules,
1569
+ lora_wrap_diffusion_head=args.lora_wrap_diffusion_head,
1570
+ train_diffusion_head=args.train_diffusion_head,
1571
+ train_connectors=args.train_connectors,
1572
+ train_surgery_module=args.train_surgery_module,
1573
+ layers_to_freeze=args.layers_to_freeze,
1574
+ )
1575
+
1576
+ data_args = TPUDataArguments(
1577
+ preprocessed_dir=args.preprocessed_dir,
1578
+ eval_split_size=args.eval_split_size,
1579
+ seed=args.seed,
1580
+ )
1581
+
1582
+ training_args = TPUTrainingArguments(
1583
+ output_dir=args.output_dir,
1584
+ per_device_train_batch_size=args.per_device_train_batch_size,
1585
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
1586
+ learning_rate=args.learning_rate,
1587
+ lr_scheduler_type=args.lr_scheduler_type,
1588
+ warmup_ratio=args.warmup_ratio,
1589
+ warmup_steps=args.warmup_steps,
1590
+ ce_loss_weight=args.ce_loss_weight,
1591
+ diffusion_loss_weight=args.diffusion_loss_weight,
1592
+ ddpm_batch_mul=args.ddpm_batch_mul,
1593
+ max_grad_norm=args.max_grad_norm,
1594
+ max_steps=args.max_steps,
1595
+ num_train_epochs=args.num_train_epochs,
1596
+ logging_steps=args.logging_steps,
1597
+ save_steps=args.save_steps,
1598
+ eval_steps=args.eval_steps,
1599
+ save_total_limit=args.save_total_limit,
1600
+ gradient_checkpointing=args.gradient_checkpointing,
1601
+ ema_decay=args.ema_decay,
1602
+ seed=args.seed,
1603
+ resume_from_checkpoint=args.resume_from_checkpoint,
1604
+ )
1605
+
1606
+ # ── Print Configuration ──
1607
+ xm.master_print(f"\n{'='*70}")
1608
+ xm.master_print(f" VibeVoice TPU v5e-8 Fine-Tuning Configuration")
1609
+ xm.master_print(f"{'='*70}")
1610
+ xm.master_print(f" Model: {model_args.model_name_or_path}")
1611
+ xm.master_print(f" Data: {data_args.preprocessed_dir}")
1612
+ xm.master_print(f" Output: {training_args.output_dir}")
1613
+ xm.master_print(f" Precision: bfloat16 (TPU native)")
1614
+ xm.master_print(f" Max steps: {training_args.max_steps}")
1615
+ xm.master_print(f" Batch size: {training_args.per_device_train_batch_size}")
1616
+ xm.master_print(f" Grad accum: {training_args.gradient_accumulation_steps}")
1617
+ xm.master_print(f" LR: {training_args.learning_rate}")
1618
+ xm.master_print(f" LoRA r: {model_args.lora_r}")
1619
+ xm.master_print(f" Grad checkpoint: {training_args.gradient_checkpointing}")
1620
+ xm.master_print(f" Surgery module: {'TRAINABLE' if model_args.train_surgery_module else 'FROZEN'}")
1621
+ xm.master_print(f" Connectors: {'TRAINABLE' if model_args.train_connectors else 'FROZEN'}")
1622
+ xm.master_print(f"{'='*70}\n")
1623
+
1624
+ # ── Create output directory ──
1625
+ os.makedirs(training_args.output_dir, exist_ok=True)
1626
+
1627
+ # ── Launch training ──
1628
+ # Use xmp.spawn for multi-process TPU training
1629
+ xmp.spawn(
1630
+ train_fn,
1631
+ args=(model_args, data_args, training_args),
1632
+ nprocs=TPU_CONFIG["num_chips"],
1633
+ start_method="fork",
1634
+ )
1635
+
1636
+
1637
+ if __name__ == "__main__":
1638
+ main()
VibeVoice-tpu/src/finetune_vibevoice_tpu_colab.ipynb ADDED
@@ -0,0 +1,1172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "gpuType": "TPU"
8
+ },
9
+ "kernelspec": {
10
+ "name": "python3",
11
+ "display_name": "Python 3"
12
+ },
13
+ "language_info": {
14
+ "name": "python"
15
+ },
16
+ "accelerator": "TPU"
17
+ },
18
+ "cells": [
19
+ {
20
+ "cell_type": "markdown",
21
+ "metadata": {},
22
+ "source": [
23
+ "# 🎙️ VibeVoice Fine-Tuning on TPU (Google Colab)\n",
24
+ "\n",
25
+ "## Overview\n",
26
+ "\n",
27
+ "This notebook fine-tunes the **VibeVoice surgery model** (Qwen3-4B backbone + Surgery Module) on **Google Colab TPU** using PyTorch/XLA.\n",
28
+ "\n",
29
+ "### Key Differences from GPU Training\n",
30
+ "| Aspect | GPU (T4) | TPU |\n",
31
+ "|--------|----------|-----|\n",
32
+ "| Framework | PyTorch + CUDA | PyTorch/XLA |\n",
33
+ "| Precision | fp16 | bfloat16 (native) |\n",
34
+ "| Training Loop | HF Trainer | Custom XLA loop |\n",
35
+ "| Data Loading | DataLoader | MpDeviceLoader |\n",
36
+ "| 8 Cores | N/A | 8 TPU cores (data parallel) |\n",
37
+ "| Memory | 15 GB (T4) | 8 GB HBM per core × 8 = 64 GB total |\n",
38
+ "\n",
39
+ "### Model Architecture After Surgery\n",
40
+ "| Component | Dimensions | Notes |\n",
41
+ "|-----------|-----------|-------|\n",
42
+ "| Qwen3-4B LLM | 2560-dim, 36 layers | Language model backbone |\n",
43
+ "| Surgery Module | 2560 → 3584 | Bridging module for diffusion head |\n",
44
+ "| Diffusion Head | 3584-dim | DDPM-based speech generation |\n",
45
+ "| Acoustic Connector | 64 → 2560 | Acoustic latent → LLM space |\n",
46
+ "| Semantic Connector | 128 → 2560 | Semantic latent → LLM space |\n",
47
+ "\n",
48
+ "### Data Format\n",
49
+ "This notebook expects **preprocessed `.pt` files** in a directory.\n",
50
+ "Each `.pt` file contains a list of batch dicts with tensors:\n",
51
+ "- `input_ids`, `attention_mask`, `speech_tensors`, `speech_masks`\n",
52
+ "- `speech_semantic_tensors`, `acoustic_input_mask`, `acoustic_loss_mask`, `speeches_loss_input`\n",
53
+ "\n",
54
+ "---"
55
+ ]
56
+ },
57
+ {
58
+ "cell_type": "markdown",
59
+ "metadata": {},
60
+ "source": [
61
+ "## Cell 1: 🔧 Environment Setup & Dependencies"
62
+ ]
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "#@title 1.1 — Install PyTorch/XLA and Dependencies { display-mode: \"form\" }\n",
69
+ "import subprocess, sys, os\n",
70
+ "\n",
71
+ "def install(package):\n",
72
+ " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", package])\n",
73
+ "\n",
74
+ "# Install PyTorch/XLA (CRITICAL for TPU support)\n",
75
+ "# Match version to your Colab TPU runtime\n",
76
+ "!pip install torch~=2.5.0\n",
77
+ "!pip install torch_xla[tpu]~=2.5.0 -f https://storage.googleapis.com/libtpu-releases/index.html\n",
78
+ "\n",
79
+ "# Core ML stack\n",
80
+ "install(\"transformers>=4.45.0\")\n",
81
+ "install(\"peft>=0.7.0\")\n",
82
+ "install(\"datasets>=2.19.0\")\n",
83
+ "install(\"safetensors>=0.4.0\")\n",
84
+ "\n",
85
+ "# Audio processing (optional — only needed for raw audio)\n",
86
+ "# install(\"librosa>=0.10.0\")\n",
87
+ "# install(\"soundfile>=0.12.0\")\n",
88
+ "\n",
89
+ "# Utilities\n",
90
+ "install(\"sentencepiece\")\n",
91
+ "install(\"protobuf\")\n",
92
+ "install(\"tqdm\")\n",
93
+ "install(\"numpy\")\n",
94
+ "\n",
95
+ "print(\"✅ All dependencies installed successfully!\")"
96
+ ],
97
+ "execution_count": null,
98
+ "outputs": []
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "metadata": {},
103
+ "source": [
104
+ "#@title 1.2 — Verify TPU Setup { display-mode: \"form\" }\n",
105
+ "\n",
106
+ "import os\n",
107
+ "\n",
108
+ "# Set TPU environment variables BEFORE importing torch_xla\n",
109
+ "os.environ[\"XLA_USE_BF16\"] = \"1\"\n",
110
+ "os.environ[\"XLA_DOWNCAST_BF16\"] = \"1\"\n",
111
+ "os.environ[\"PJRT_DEVICE\"] = \"TPU\"\n",
112
+ "os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n",
113
+ "\n",
114
+ "import torch\n",
115
+ "import torch_xla\n",
116
+ "import torch_xla.core.xla_model as xm\n",
117
+ "import torch_xla.distributed.xla_multiprocessing as xmp\n",
118
+ "\n",
119
+ "# Verify TPU\n",
120
+ "print(\"=\" * 60)\n",
121
+ "print(\" TPU Configuration\")\n",
122
+ "print(\"=\" * 60)\n",
123
+ "print(f\" PyTorch version: {torch.__version__}\")\n",
124
+ "print(f\" PyTorch/XLA version: {torch_xla.__version__}\")\n",
125
+ "\n",
126
+ "try:\n",
127
+ " device = xm.xla_device()\n",
128
+ " print(f\" XLA device: {device}\")\n",
129
+ " print(f\" World size: {xm.xrt_world_size()}\")\n",
130
+ " \n",
131
+ " # Quick computation test\n",
132
+ " t = torch.randn(2, 2).to(device)\n",
133
+ " result = t @ t.T\n",
134
+ " xm.mark_step()\n",
135
+ " print(f\" TPU compute test: ✅ PASSED\")\n",
136
+ " print(f\" TPU dtype: bfloat16 (native)\")\n",
137
+ " print(\"=\" * 60)\n",
138
+ " print(\"\\n✅ TPU is ready for training!\")\n",
139
+ "except Exception as e:\n",
140
+ " print(f\"\\n❌ TPU initialization failed: {e}\")\n",
141
+ " print(\"Please go to Runtime > Change runtime type > TPU\")\n",
142
+ " raise"
143
+ ],
144
+ "execution_count": null,
145
+ "outputs": []
146
+ },
147
+ {
148
+ "cell_type": "markdown",
149
+ "metadata": {},
150
+ "source": [
151
+ "## Cell 2: 📁 Project Setup & Paths"
152
+ ]
153
+ },
154
+ {
155
+ "cell_type": "code",
156
+ "metadata": {},
157
+ "source": [
158
+ "#@title 2.1 — Configure Paths { display-mode: \"form\" }\n",
159
+ "import os\n",
160
+ "\n",
161
+ "# ══════════════════════════════════════════════════════════\n",
162
+ "# CONFIGURE THESE PATHS FOR YOUR SETUP\n",
163
+ "# ══════════════════════════════════════════════════════════\n",
164
+ "\n",
165
+ "# Path to the surgery model directory\n",
166
+ "SURGERY_MODEL_PATH = \"/content/vibevoice_qwen3_surgery\" #@param {type:\"string\"}\n",
167
+ "\n",
168
+ "# Path to the directory containing preprocessed .pt files\n",
169
+ "# Each .pt file should contain a list of batch dicts\n",
170
+ "PREPROCESSED_DATA_DIR = \"/content/preprocessed_data\" #@param {type:\"string\"}\n",
171
+ "\n",
172
+ "# Path to the VibeVoice source code\n",
173
+ "# You need: vibevoice/, vibevoice_surgery_colab.py, tpu_config.py, finetune_vibevoice_tpu.py\n",
174
+ "PROJECT_DIR = \"/content/VibeVoice/src\" #@param {type:\"string\"}\n",
175
+ "\n",
176
+ "# Output directory for trained artifacts\n",
177
+ "OUTPUT_DIR = \"/content/vibevoice_tpu_finetuned\" #@param {type:\"string\"}\n",
178
+ "\n",
179
+ "# ══════════════════════════════════════════════════════════\n",
180
+ "\n",
181
+ "# Validation\n",
182
+ "if not os.path.exists(SURGERY_MODEL_PATH):\n",
183
+ " print(f\"⚠️ Surgery model not found at: {SURGERY_MODEL_PATH}\")\n",
184
+ " print(f\" Please upload the surgery model or update the path.\")\n",
185
+ "\n",
186
+ "if not os.path.exists(PREPROCESSED_DATA_DIR):\n",
187
+ " print(f\"⚠️ Preprocessed data not found at: {PREPROCESSED_DATA_DIR}\")\n",
188
+ " print(f\" Please upload .pt files to this directory.\")\n",
189
+ "else:\n",
190
+ " pt_files = [f for f in os.listdir(PREPROCESSED_DATA_DIR) if f.endswith('.pt')]\n",
191
+ " print(f\" Found {len(pt_files)} .pt files in {PREPROCESSED_DATA_DIR}\")\n",
192
+ "\n",
193
+ "print(f\"\\n📁 Configuration:\")\n",
194
+ "print(f\" Surgery Model: {SURGERY_MODEL_PATH}\")\n",
195
+ "print(f\" Preprocessed Data: {PREPROCESSED_DATA_DIR}\")\n",
196
+ "print(f\" Project Dir: {PROJECT_DIR}\")\n",
197
+ "print(f\" Output Dir: {OUTPUT_DIR}\")"
198
+ ],
199
+ "execution_count": null,
200
+ "outputs": []
201
+ },
202
+ {
203
+ "cell_type": "code",
204
+ "metadata": {},
205
+ "source": [
206
+ "#@title 2.2 — Clone or Link Project { display-mode: \"form\" }\n",
207
+ "\n",
208
+ "import os, sys\n",
209
+ "\n",
210
+ "# Option A: If project is in a Git repo\n",
211
+ "GIT_REPO_URL = \"\" #@param {type:\"string\"}\n",
212
+ "\n",
213
+ "if GIT_REPO_URL and not os.path.exists(PROJECT_DIR):\n",
214
+ " !git clone {GIT_REPO_URL} {PROJECT_DIR}\n",
215
+ " print(f\"✅ Cloned project from {GIT_REPO_URL}\")\n",
216
+ "elif not os.path.exists(PROJECT_DIR):\n",
217
+ " os.makedirs(PROJECT_DIR, exist_ok=True)\n",
218
+ " print(f\"⚠️ Created empty project dir at {PROJECT_DIR}\")\n",
219
+ " print(f\" Please upload vibevoice/, vibevoice_surgery_colab.py, tpu_config.py, finetune_vibevoice_tpu.py\")\n",
220
+ "else:\n",
221
+ " print(f\"✅ Project dir exists: {PROJECT_DIR}\")\n",
222
+ "\n",
223
+ "# Add to Python path\n",
224
+ "if PROJECT_DIR not in sys.path:\n",
225
+ " sys.path.insert(0, PROJECT_DIR)\n",
226
+ "\n",
227
+ "# Verify critical files\n",
228
+ "required_files = [\n",
229
+ " \"vibevoice/modular/modeling_vibevoice.py\",\n",
230
+ " \"vibevoice/modular/configuration_vibevoice.py\",\n",
231
+ " \"vibevoice_surgery_colab.py\",\n",
232
+ " \"tpu_config.py\",\n",
233
+ " \"finetune_vibevoice_tpu.py\",\n",
234
+ "]\n",
235
+ "missing = [f for f in required_files if not os.path.exists(os.path.join(PROJECT_DIR, f))]\n",
236
+ "if missing:\n",
237
+ " print(f\"\\n❌ Missing required files:\")\n",
238
+ " for f in missing:\n",
239
+ " print(f\" - {f}\")\n",
240
+ "else:\n",
241
+ " print(f\"\\n✅ All required project files found!\")"
242
+ ],
243
+ "execution_count": null,
244
+ "outputs": []
245
+ },
246
+ {
247
+ "cell_type": "markdown",
248
+ "metadata": {},
249
+ "source": [
250
+ "## Cell 3: 📊 Preprocessed Data Validation"
251
+ ]
252
+ },
253
+ {
254
+ "cell_type": "code",
255
+ "metadata": {},
256
+ "source": [
257
+ "#@title 3.1 — Validate Preprocessed Data { display-mode: \"form\" }\n",
258
+ "\n",
259
+ "import os, torch\n",
260
+ "\n",
261
+ "def validate_preprocessed_data(data_dir, n_preview=3):\n",
262
+ " \"\"\"Validate and preview preprocessed .pt files.\"\"\"\n",
263
+ " print(f\"\\n{'='*60}\")\n",
264
+ " print(f\" Preprocessed Data Validation\")\n",
265
+ " print(f\"{'='*60}\")\n",
266
+ " \n",
267
+ " pt_files = sorted([f for f in os.listdir(data_dir) if f.endswith('.pt')])\n",
268
+ " \n",
269
+ " if not pt_files:\n",
270
+ " print(f\" ❌ No .pt files found in {data_dir}\")\n",
271
+ " return\n",
272
+ " \n",
273
+ " print(f\" 📁 Directory: {data_dir}\")\n",
274
+ " print(f\" 📄 Files: {len(pt_files)}\")\n",
275
+ " \n",
276
+ " total_samples = 0\n",
277
+ " expected_keys = {\n",
278
+ " 'input_ids', 'attention_mask', 'speech_tensors', \n",
279
+ " 'speech_masks', 'speech_semantic_tensors',\n",
280
+ " 'acoustic_input_mask', 'acoustic_loss_mask', 'speeches_loss_input'\n",
281
+ " }\n",
282
+ " \n",
283
+ " for i, fname in enumerate(pt_files):\n",
284
+ " fpath = os.path.join(data_dir, fname)\n",
285
+ " fsize_mb = os.path.getsize(fpath) / (1024 * 1024)\n",
286
+ " \n",
287
+ " try:\n",
288
+ " data = torch.load(fpath, map_location='cpu')\n",
289
+ " \n",
290
+ " if isinstance(data, list):\n",
291
+ " num_samples = len(data)\n",
292
+ " total_samples += num_samples\n",
293
+ " \n",
294
+ " # Validate first sample\n",
295
+ " if data and isinstance(data[0], dict):\n",
296
+ " keys = set(data[0].keys())\n",
297
+ " missing_keys = expected_keys - keys\n",
298
+ " extra_keys = keys - expected_keys\n",
299
+ " \n",
300
+ " status = \"✅\" if not missing_keys else \"⚠️\"\n",
301
+ " print(f\"\\n {status} {fname} ({fsize_mb:.1f} MB): {num_samples} samples\")\n",
302
+ " print(f\" Keys: {sorted(keys)}\")\n",
303
+ " \n",
304
+ " if missing_keys:\n",
305
+ " print(f\" ⚠️ Missing keys: {missing_keys}\")\n",
306
+ " \n",
307
+ " # Preview tensor shapes\n",
308
+ " if i < n_preview:\n",
309
+ " sample = data[0]\n",
310
+ " for k, v in sample.items():\n",
311
+ " if isinstance(v, torch.Tensor):\n",
312
+ " print(f\" {k}: shape={v.shape}, dtype={v.dtype}\")\n",
313
+ " elif isinstance(data, dict):\n",
314
+ " total_samples += 1\n",
315
+ " print(f\"\\n ✅ {fname} ({fsize_mb:.1f} MB): 1 sample (single dict)\")\n",
316
+ " \n",
317
+ " except Exception as e:\n",
318
+ " print(f\"\\n ❌ {fname}: Failed to load — {e}\")\n",
319
+ " \n",
320
+ " print(f\"\\n {'='*60}\")\n",
321
+ " print(f\" Total samples: {total_samples}\")\n",
322
+ " print(f\" {'='*60}\")\n",
323
+ " \n",
324
+ " return total_samples\n",
325
+ "\n",
326
+ "total_samples = validate_preprocessed_data(PREPROCESSED_DATA_DIR)"
327
+ ],
328
+ "execution_count": null,
329
+ "outputs": []
330
+ },
331
+ {
332
+ "cell_type": "markdown",
333
+ "metadata": {},
334
+ "source": [
335
+ "## Cell 4: 🧊 Configure Freezing Strategy\n",
336
+ "\n",
337
+ "### Layer Groups\n",
338
+ "\n",
339
+ "| Layer Group | Parameters (approx) | Memory Impact | Description |\n",
340
+ "|-------------|--------------------|--------------:|-------------|\n",
341
+ "| **LLM (Qwen3-4B)** | ~4B | ~8 GB bf16 | Language model backbone |\n",
342
+ "| **Diffusion Head** | ~107M | ~214 MB bf16 | DDPM denoiser |\n",
343
+ "| **Surgery Module** | ~26M | ~52 MB bf16 | 2560→3584 bridge |\n",
344
+ "| **Acoustic Connector** | ~0.1M | ~0.2 MB bf16 | 64→2560 projection |\n",
345
+ "| **Semantic Connector** | ~0.3M | ~0.6 MB bf16 | 128→2560 projection |\n",
346
+ "| **LM Head** | ~388M | ~776 MB bf16 | Tied to embeddings (frozen) |\n",
347
+ "\n",
348
+ "### TPU Memory Budget (per core)\n",
349
+ "~12 GB model + ~3.5 GB training overhead = ~15.5 GB out of 8 GB per core\n",
350
+ "\n",
351
+ "**Note**: With 8 TPU cores, each core processes a separate batch. Total HBM = 64 GB.\n",
352
+ "The model is **replicated** across all 8 cores (data parallelism)."
353
+ ]
354
+ },
355
+ {
356
+ "cell_type": "code",
357
+ "metadata": {},
358
+ "source": [
359
+ "#@title 4.1 — Layer Freezing Configuration { display-mode: \"form\" }\n",
360
+ "\n",
361
+ "# ══════════════════════════════════════════════════════════\n",
362
+ "# FREEZING STRATEGY — Choose what to freeze/train\n",
363
+ "# ══════════════════════════════════════════════════════════\n",
364
+ "\n",
365
+ "# For TPU with 8GB per core, default strategy:\n",
366
+ "# Freeze LLM (use LoRA), freeze diffusion head, train surgery+connectors\n",
367
+ "\n",
368
+ "FREEZE_LLM = False #@param {type:\"boolean\"} # False = use LoRA on LLM\n",
369
+ "FREEZE_DIFFUSION_HEAD = True #@param {type:\"boolean\"}\n",
370
+ "FREEZE_SURGERY_MODULE = False #@param {type:\"boolean\"}\n",
371
+ "FREEZE_CONNECTORS = False #@param {type:\"boolean\"}\n",
372
+ "FREEZE_LM_HEAD = True #@param {type:\"boolean\"}\n",
373
+ "\n",
374
+ "# ── LoRA Settings ──\n",
375
+ "USE_LORA_ON_LLM = True #@param {type:\"boolean\"}\n",
376
+ "LORA_R = 8 #@param {type:\"integer\"}\n",
377
+ "LORA_ALPHA = 32 #@param {type:\"integer\"}\n",
378
+ "LORA_DROPOUT = 0.05 #@param {type:\"float\"}\n",
379
+ "\n",
380
+ "# Configure target modules\n",
381
+ "if FREEZE_LLM:\n",
382
+ " USE_LORA_ON_LLM = False\n",
383
+ " LORA_TARGET_MODULES = \"none\"\n",
384
+ "else:\n",
385
+ " LORA_TARGET_MODULES = \"q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj\" if USE_LORA_ON_LLM else \"none\"\n",
386
+ "\n",
387
+ "# ── Diffusion Head options ──\n",
388
+ "LORA_WRAP_DIFFUSION_HEAD = False #@param {type:\"boolean\"}\n",
389
+ "TRAIN_DIFFUSION_HEAD = False #@param {type:\"boolean\"}\n",
390
+ "\n",
391
+ "# ── Print Summary ──\n",
392
+ "print(\"=\" * 60)\n",
393
+ "print(\" Freezing Strategy\")\n",
394
+ "print(\"=\" * 60)\n",
395
+ "components = [\n",
396
+ " (\"LLM (Qwen3-4B)\", FREEZE_LLM, \"~4B params | ~8 GB\"),\n",
397
+ " (\"Diffusion Head\", FREEZE_DIFFUSION_HEAD, \"~107M params | ~214 MB\"),\n",
398
+ " (\"Surgery Module\", FREEZE_SURGERY_MODULE, \"~26M params | ~52 MB\"),\n",
399
+ " (\"Acoustic Connector\", FREEZE_CONNECTORS, \"~0.1M params | ~0.2 MB\"),\n",
400
+ " (\"Semantic Connector\", FREEZE_CONNECTORS, \"~0.3M params | ~0.6 MB\"),\n",
401
+ " (\"LM Head\", FREEZE_LM_HEAD, \"~388M params | ~776 MB\"),\n",
402
+ "]\n",
403
+ "\n",
404
+ "train_count = 0\n",
405
+ "for name, frozen, params in components:\n",
406
+ " status = \"❌ FREEZE\" if frozen else \"✅ TRAIN\"\n",
407
+ " print(f\" {name:<25s} {status:<12s} {params}\")\n",
408
+ " if not frozen:\n",
409
+ " train_count += 1\n",
410
+ "\n",
411
+ "print(f\"\\n LoRA on LLM: {'✅ Yes (r=' + str(LORA_R) + ')' if USE_LORA_ON_LLM else '❌ No'}\")\n",
412
+ "print(f\" LoRA on Diffusion Head: {'✅ Yes' if LORA_WRAP_DIFFUSION_HEAD else '❌ No'}\")\n",
413
+ "print(f\" Full Train Diffusion: {'✅ Yes' if TRAIN_DIFFUSION_HEAD else '❌ No'}\")\n",
414
+ "print(f\"\\n Components to train: {train_count}\")\n",
415
+ "print(\"=\" * 60)"
416
+ ],
417
+ "execution_count": null,
418
+ "outputs": []
419
+ },
420
+ {
421
+ "cell_type": "markdown",
422
+ "metadata": {},
423
+ "source": [
424
+ "## Cell 5: 🚀 Training Configuration"
425
+ ]
426
+ },
427
+ {
428
+ "cell_type": "code",
429
+ "metadata": {},
430
+ "source": [
431
+ "#@title 5.1 — Hyperparameters { display-mode: \"form\" }\n",
432
+ "\n",
433
+ "# ══════════════════════════════════════════════════════════\n",
434
+ "# TRAINING HYPERPARAMETERS FOR TPU\n",
435
+ "# ══════════════════════════════════════════════════════════\n",
436
+ "\n",
437
+ "MAX_STEPS = 5000 #@param {type:\"integer\"}\n",
438
+ "NUM_EPOCHS = 3 #@param {type:\"integer\"}\n",
439
+ "BATCH_SIZE_PER_CORE = 1 #@param {type:\"integer\"}\n",
440
+ "GRADIENT_ACCUMULATION_STEPS = 8 #@param {type:\"integer\"}\n",
441
+ "LEARNING_RATE = 2e-5 #@param {type:\"number\"}\n",
442
+ "LR_SCHEDULER = \"cosine\" #@param [\"cosine\", \"linear\", \"constant\"]\n",
443
+ "WARMUP_STEPS = 100 #@param {type:\"integer\"}\n",
444
+ "WARMUP_RATIO = 0.1 #@param {type:\"number\"}\n",
445
+ "WEIGHT_DECAY = 0.01 #@param {type:\"number\"}\n",
446
+ "MAX_GRAD_NORM = 1.0 #@param {type:\"number\"}\n",
447
+ "\n",
448
+ "# Loss weights\n",
449
+ "CE_LOSS_WEIGHT = 1.0 #@param {type:\"number\"}\n",
450
+ "DIFFUSION_LOSS_WEIGHT = 1.0 #@param {type:\"number\"}\n",
451
+ "DDPM_BATCH_MUL = 1 #@param {type:\"integer\"}\n",
452
+ "\n",
453
+ "# EMA\n",
454
+ "EMA_DECAY = 0.999 #@param {type:\"number\"}\n",
455
+ "\n",
456
+ "# Data\n",
457
+ "EVAL_SPLIT_SIZE = 0.05 #@param {type:\"number\"}\n",
458
+ "\n",
459
+ "# Memory optimization\n",
460
+ "GRADIENT_CHECKPOINTING = True #@param {type:\"boolean\"}\n",
461
+ "\n",
462
+ "# Logging\n",
463
+ "LOGGING_STEPS = 10 #@param {type:\"integer\"}\n",
464
+ "SAVE_STEPS = 500 #@param {type:\"integer\"}\n",
465
+ "SAVE_TOTAL_LIMIT = 3 #@param {type:\"integer\"}\n",
466
+ "EVAL_STEPS = 500 #@param {type:\"integer\"}\n",
467
+ "\n",
468
+ "# Seed\n",
469
+ "SEED = 42 #@param {type:\"integer\"}\n",
470
+ "\n",
471
+ "# Compute effective batch size\n",
472
+ "# On Colab TPU v2, there are 8 cores\n",
473
+ "NUM_TPU_CORES = 8\n",
474
+ "effective_batch = BATCH_SIZE_PER_CORE * GRADIENT_ACCUMULATION_STEPS * NUM_TPU_CORES\n",
475
+ "print(f\"\\n📊 TPU Training Configuration:\")\n",
476
+ "print(f\" Max Steps: {MAX_STEPS}\")\n",
477
+ "print(f\" Epochs: {NUM_EPOCHS}\")\n",
478
+ "print(f\" Batch/Core: {BATCH_SIZE_PER_CORE}\")\n",
479
+ "print(f\" Grad Accum: {GRADIENT_ACCUMULATION_STEPS}\")\n",
480
+ "print(f\" TPU Cores: {NUM_TPU_CORES}\")\n",
481
+ "print(f\" Effective Batch: {effective_batch}\")\n",
482
+ "print(f\" Learning Rate: {LEARNING_RATE}\")\n",
483
+ "print(f\" LR Scheduler: {LR_SCHEDULER}\")\n",
484
+ "print(f\" Precision: bfloat16 (TPU native)\")\n",
485
+ "print(f\" Grad Checkpoint: {GRADIENT_CHECKPOINTING}\")\n",
486
+ "print(f\" EMA Decay: {EMA_DECAY}\")"
487
+ ],
488
+ "execution_count": null,
489
+ "outputs": []
490
+ },
491
+ {
492
+ "cell_type": "markdown",
493
+ "metadata": {},
494
+ "source": [
495
+ "## Cell 6: 🏋️ Launch Fine-Tuning"
496
+ ]
497
+ },
498
+ {
499
+ "cell_type": "code",
500
+ "metadata": {},
501
+ "source": [
502
+ "#@title 6.1 — Pre-Training Checks { display-mode: \"form\" }\n",
503
+ "\n",
504
+ "import os, sys, torch\n",
505
+ "\n",
506
+ "print(\"🔍 Pre-training checks:\")\n",
507
+ "\n",
508
+ "errors = []\n",
509
+ "\n",
510
+ "# Check surgery model\n",
511
+ "if not os.path.exists(SURGERY_MODEL_PATH):\n",
512
+ " errors.append(f\"Surgery model not found: {SURGERY_MODEL_PATH}\")\n",
513
+ "else:\n",
514
+ " config_path = os.path.join(SURGERY_MODEL_PATH, \"config.json\")\n",
515
+ " if os.path.exists(config_path):\n",
516
+ " print(f\" ✅ Surgery model config found\")\n",
517
+ " else:\n",
518
+ " errors.append(f\"config.json not found in {SURGERY_MODEL_PATH}\")\n",
519
+ "\n",
520
+ "# Check preprocessed data\n",
521
+ "if not os.path.exists(PREPROCESSED_DATA_DIR):\n",
522
+ " errors.append(f\"Preprocessed data dir not found: {PREPROCESSED_DATA_DIR}\")\n",
523
+ "else:\n",
524
+ " pt_files = [f for f in os.listdir(PREPROCESSED_DATA_DIR) if f.endswith('.pt')]\n",
525
+ " if not pt_files:\n",
526
+ " errors.append(f\"No .pt files found in {PREPROCESSED_DATA_DIR}\")\n",
527
+ " else:\n",
528
+ " print(f\" ✅ Found {len(pt_files)} preprocessed .pt files\")\n",
529
+ "\n",
530
+ "# Check TPU\n",
531
+ "try:\n",
532
+ " import torch_xla.core.xla_model as xm\n",
533
+ " device = xm.xla_device()\n",
534
+ " print(f\" ✅ TPU device: {device}\")\n",
535
+ " print(f\" ✅ TPU cores: {xm.xrt_world_size()}\")\n",
536
+ "except Exception as e:\n",
537
+ " errors.append(f\"TPU not available: {e}\")\n",
538
+ "\n",
539
+ "# Check project files\n",
540
+ "required_files = [\n",
541
+ " \"tpu_config.py\",\n",
542
+ " \"finetune_vibevoice_tpu.py\",\n",
543
+ " \"vibevoice/modular/modeling_vibevoice.py\",\n",
544
+ " \"vibevoice_surgery_colab.py\",\n",
545
+ "]\n",
546
+ "for f in required_files:\n",
547
+ " fpath = os.path.join(PROJECT_DIR, f)\n",
548
+ " if os.path.exists(fpath):\n",
549
+ " print(f\" ✅ {f}\")\n",
550
+ " else:\n",
551
+ " errors.append(f\"Missing: {f}\")\n",
552
+ "\n",
553
+ "if errors:\n",
554
+ " print(f\"\\n❌ ERRORS (fix before training):\")\n",
555
+ " for e in errors:\n",
556
+ " print(f\" - {e}\")\n",
557
+ " raise RuntimeError(\"Pre-training checks failed. See errors above.\")\n",
558
+ "\n",
559
+ "print(\"\\n✅ All checks passed! Ready to start training.\")"
560
+ ],
561
+ "execution_count": null,
562
+ "outputs": []
563
+ },
564
+ {
565
+ "cell_type": "code",
566
+ "metadata": {},
567
+ "source": [
568
+ "#@title 6.2 — Execute TPU Fine-Tuning { display-mode: \"form\" }\n",
569
+ "\n",
570
+ "import os, sys, subprocess\n",
571
+ "\n",
572
+ "# Change to project directory\n",
573
+ "os.chdir(PROJECT_DIR)\n",
574
+ "\n",
575
+ "# Build the training command\n",
576
+ "cmd = f\"\"\"\n",
577
+ "python finetune_vibevoice_tpu.py \\\n",
578
+ " --model_name_or_path \"{SURGERY_MODEL_PATH}\" \\\n",
579
+ " --preprocessed_dir \"{PREPROCESSED_DATA_DIR}\" \\\n",
580
+ " --output_dir \"{OUTPUT_DIR}\" \\\n",
581
+ " --max_steps {MAX_STEPS} \\\n",
582
+ " --num_train_epochs {NUM_EPOCHS} \\\n",
583
+ " --per_device_train_batch_size {BATCH_SIZE_PER_CORE} \\\n",
584
+ " --gradient_accumulation_steps {GRADIENT_ACCUMULATION_STEPS} \\\n",
585
+ " --learning_rate {LEARNING_RATE} \\\n",
586
+ " --lr_scheduler_type {LR_SCHEDULER} \\\n",
587
+ " --warmup_steps {WARMUP_STEPS} \\\n",
588
+ " --warmup_ratio {WARMUP_RATIO} \\\n",
589
+ " --max_grad_norm {MAX_GRAD_NORM} \\\n",
590
+ " --ce_loss_weight {CE_LOSS_WEIGHT} \\\n",
591
+ " --diffusion_loss_weight {DIFFUSION_LOSS_WEIGHT} \\\n",
592
+ " --ddpm_batch_mul {DDPM_BATCH_MUL} \\\n",
593
+ " --ema_decay {EMA_DECAY} \\\n",
594
+ " --eval_split_size {EVAL_SPLIT_SIZE} \\\n",
595
+ " --logging_steps {LOGGING_STEPS} \\\n",
596
+ " --save_steps {SAVE_STEPS} \\\n",
597
+ " --save_total_limit {SAVE_TOTAL_LIMIT} \\\n",
598
+ " --eval_steps {EVAL_STEPS} \\\n",
599
+ " --lora_r {LORA_R} \\\n",
600
+ " --lora_alpha {LORA_ALPHA} \\\n",
601
+ " --lora_dropout {LORA_DROPOUT} \\\n",
602
+ " --lora_target_modules {LORA_TARGET_MODULES} \\\n",
603
+ " --lora_wrap_diffusion_head {str(LORA_WRAP_DIFFUSION_HEAD).lower()} \\\n",
604
+ " --train_diffusion_head {str(TRAIN_DIFFUSION_HEAD).lower()} \\\n",
605
+ " --train_connectors {str(not FREEZE_CONNECTORS).lower()} \\\n",
606
+ " --train_surgery_module {str(not FREEZE_SURGERY_MODULE).lower()} \\\n",
607
+ " {'--freeze_llm' if FREEZE_LLM else '--no_freeze_llm'} \\\n",
608
+ " {'--freeze_diffusion_head' if FREEZE_DIFFUSION_HEAD else '--no_freeze_diffusion_head'} \\\n",
609
+ " {'--freeze_surgery_module' if FREEZE_SURGERY_MODULE else ''} \\\n",
610
+ " {'--freeze_connectors' if FREEZE_CONNECTORS else ''} \\\n",
611
+ " {'--gradient_checkpointing' if GRADIENT_CHECKPOINTING else '--no_gradient_checkpointing'} \\\n",
612
+ " --seed {SEED}\n",
613
+ "\"\"\"\n",
614
+ "\n",
615
+ "# Clean up\n",
616
+ "import re\n",
617
+ "cmd = re.sub(r'\\s+\\\\\\n\\s+', ' ', cmd)\n",
618
+ "cmd = cmd.strip()\n",
619
+ "\n",
620
+ "print(\"=\" * 60)\n",
621
+ "print(\" Training Command\")\n",
622
+ "print(\"=\" * 60)\n",
623
+ "print(cmd)\n",
624
+ "print(\"=\" * 60)\n",
625
+ "\n",
626
+ "print(\"\\n🚀 Starting TPU fine-tuning...\")\n",
627
+ "print(\"\"\"\n",
628
+ "NOTE: The first training step will be SLOW due to XLA compilation.\n",
629
+ "This is normal — subsequent steps will be much faster.\n",
630
+ "\n",
631
+ "Monitor the output for:\n",
632
+ " - ce_loss: Cross-entropy loss on text tokens\n",
633
+ " - diffusion_loss: MSE loss on speech generation\n",
634
+ " - total_loss: Combined loss\n",
635
+ " - LR: Learning rate schedule\n",
636
+ "\"\"\")\n",
637
+ "print(\"=\" * 60)\n",
638
+ "\n",
639
+ "# Execute\n",
640
+ "process = subprocess.Popen(\n",
641
+ " cmd,\n",
642
+ " shell=True,\n",
643
+ " stdout=subprocess.PIPE,\n",
644
+ " stderr=subprocess.STDOUT,\n",
645
+ " universal_newlines=True,\n",
646
+ " bufsize=1,\n",
647
+ ")\n",
648
+ "\n",
649
+ "# Stream output\n",
650
+ "for line in process.stdout:\n",
651
+ " print(line, end='')\n",
652
+ "\n",
653
+ "process.wait()\n",
654
+ "exit_code = process.returncode\n",
655
+ "\n",
656
+ "print(\"\\n\" + \"=\" * 60)\n",
657
+ "if exit_code == 0:\n",
658
+ " print(\"✅ TPU Fine-Tuning completed successfully!\")\n",
659
+ "else:\n",
660
+ " print(f\"❌ Training failed with exit code: {exit_code}\")\n",
661
+ "print(\"=\" * 60)"
662
+ ],
663
+ "execution_count": null,
664
+ "outputs": []
665
+ },
666
+ {
667
+ "cell_type": "markdown",
668
+ "metadata": {},
669
+ "source": [
670
+ "## Cell 7: 📈 Monitor Training & Check Results"
671
+ ]
672
+ },
673
+ {
674
+ "cell_type": "code",
675
+ "metadata": {},
676
+ "source": [
677
+ "#@title 7.1 — Check Training Progress { display-mode: \"form\" }\n",
678
+ "\n",
679
+ "import os, glob, torch\n",
680
+ "\n",
681
+ "print(\"=\" * 60)\n",
682
+ "print(\" Training Progress\")\n",
683
+ "print(\"=\" * 60)\n",
684
+ "\n",
685
+ "# Check checkpoints\n",
686
+ "checkpoints = sorted(glob.glob(os.path.join(OUTPUT_DIR, \"checkpoint-*\")), \n",
687
+ " key=lambda x: int(x.split('-')[-1]))\n",
688
+ "print(f\"\\n📦 Checkpoints saved: {len(checkpoints)}\")\n",
689
+ "for ckpt in checkpoints[-5:]:\n",
690
+ " step = ckpt.split('-')[-1]\n",
691
+ " lora_dir = os.path.join(ckpt, \"lora\")\n",
692
+ " has_lora = os.path.exists(lora_dir)\n",
693
+ " print(f\" checkpoint-{step} | LoRA: {'✅' if has_lora else '❌'}\")\n",
694
+ "\n",
695
+ "# Check final model\n",
696
+ "final_dir = os.path.join(OUTPUT_DIR, \"final_model\")\n",
697
+ "if os.path.exists(final_dir):\n",
698
+ " print(f\"\\n✅ Final model saved at: {final_dir}\")\n",
699
+ "else:\n",
700
+ " print(f\"\\n⚠️ Final model not yet saved.\")\n",
701
+ "\n",
702
+ "# Show disk usage\n",
703
+ "total_size = 0\n",
704
+ "for root, dirs, files in os.walk(OUTPUT_DIR):\n",
705
+ " for f in files:\n",
706
+ " total_size += os.path.getsize(os.path.join(root, f))\n",
707
+ "print(f\"\\n💾 Total output size: {total_size / 1024 / 1024:.1f} MB\")\n",
708
+ "print(\"=\" * 60)"
709
+ ],
710
+ "execution_count": null,
711
+ "outputs": []
712
+ },
713
+ {
714
+ "cell_type": "code",
715
+ "metadata": {},
716
+ "source": [
717
+ "#@title 7.2 — Inspect Latest Saved Artifacts { display-mode: \"form\" }\n",
718
+ "\n",
719
+ "import os, glob\n",
720
+ "\n",
721
+ "# Find latest checkpoint or final model\n",
722
+ "checkpoints = sorted(glob.glob(os.path.join(OUTPUT_DIR, \"checkpoint-*\")),\n",
723
+ " key=lambda x: int(x.split('-')[-1]))\n",
724
+ "\n",
725
+ "latest_dir = checkpoints[-1] if checkpoints else OUTPUT_DIR\n",
726
+ "lora_dir = os.path.join(latest_dir, \"lora\")\n",
727
+ "\n",
728
+ "if not os.path.exists(lora_dir):\n",
729
+ " # Try final model\n",
730
+ " lora_dir = os.path.join(OUTPUT_DIR, \"final_model\", \"lora\")\n",
731
+ " if not os.path.exists(lora_dir):\n",
732
+ " print(f\"⚠️ No saved artifacts found.\")\n",
733
+ " lora_dir = None\n",
734
+ "\n",
735
+ "if lora_dir and os.path.exists(lora_dir):\n",
736
+ " print(\"=\" * 60)\n",
737
+ " print(f\" Saved Artifacts: {lora_dir}\")\n",
738
+ " print(\"=\" * 60)\n",
739
+ " \n",
740
+ " for root, dirs, files in os.walk(lora_dir):\n",
741
+ " level = root.replace(lora_dir, '').count(os.sep)\n",
742
+ " indent = ' ' * level\n",
743
+ " print(f'{indent}{os.path.basename(root)}/')\n",
744
+ " subindent = ' ' * (level + 1)\n",
745
+ " for file in sorted(files):\n",
746
+ " fpath = os.path.join(root, file)\n",
747
+ " size_mb = os.path.getsize(fpath) / 1024 / 1024\n",
748
+ " print(f'{subindent}{file} ({size_mb:.2f} MB)')\n",
749
+ " \n",
750
+ " print(\"=\" * 60)"
751
+ ],
752
+ "execution_count": null,
753
+ "outputs": []
754
+ },
755
+ {
756
+ "cell_type": "markdown",
757
+ "metadata": {},
758
+ "source": [
759
+ "## Cell 8: 🔄 Phase 2 — Expand Training (Optional)\n",
760
+ "\n",
761
+ "After Phase 1 converges, you can expand training to include the diffusion head."
762
+ ]
763
+ },
764
+ {
765
+ "cell_type": "code",
766
+ "metadata": {},
767
+ "source": [
768
+ "#@title 8.1 — Configure Phase 2 { display-mode: \"form\" }\n",
769
+ "\n",
770
+ "# ════════════════════��═════════════════════════════════════\n",
771
+ "# PHASE 2: Expand training scope\n",
772
+ "# ══════════════════════════════════════════════════════════\n",
773
+ "\n",
774
+ "RUN_PHASE_2 = False #@param {type:\"boolean\"}\n",
775
+ "\n",
776
+ "# Phase 2 settings — keep LLM frozen with LoRA, unfreeze diffusion head with LoRA\n",
777
+ "P2_FREEZE_LLM = False\n",
778
+ "P2_FREEZE_DIFFUSION_HEAD = False # Unfreeze diffusion head!\n",
779
+ "P2_FREEZE_SURGERY_MODULE = False\n",
780
+ "P2_FREEZE_CONNECTORS = False\n",
781
+ "P2_LORA_WRAP_DIFFUSION_HEAD = True # Use LoRA on head to save memory\n",
782
+ "P2_LEARNING_RATE = 1e-5 # Lower LR for Phase 2\n",
783
+ "P2_MAX_STEPS = 3000\n",
784
+ "\n",
785
+ "# Resume from Phase 1 checkpoint\n",
786
+ "P2_RESUME_FROM = os.path.join(OUTPUT_DIR, \"final_model\") #@param {type:\"string\"}\n",
787
+ "P2_OUTPUT_DIR = OUTPUT_DIR + \"_phase2\"\n",
788
+ "\n",
789
+ "if RUN_PHASE_2:\n",
790
+ " print(\"📋 Phase 2 Configuration:\")\n",
791
+ " print(f\" LLM: {'FROZEN' if P2_FREEZE_LLM else 'LoRA TRAIN'}\")\n",
792
+ " print(f\" Diff. Head: {'FROZEN' if P2_FREEZE_DIFFUSION_HEAD else 'LoRA TRAIN'}\")\n",
793
+ " print(f\" Surgery Mod: {'FROZEN' if P2_FREEZE_SURGERY_MODULE else 'TRAIN'}\")\n",
794
+ " print(f\" Connectors: {'FROZEN' if P2_FREEZE_CONNECTORS else 'TRAIN'}\")\n",
795
+ " print(f\" Head LoRA: {'Yes' if P2_LORA_WRAP_DIFFUSION_HEAD else 'No'}\")\n",
796
+ " print(f\" LR: {P2_LEARNING_RATE}\")\n",
797
+ " print(f\" Resume from: {P2_RESUME_FROM}\")\n",
798
+ "else:\n",
799
+ " print(\"Phase 2 is disabled. Set RUN_PHASE_2=True to enable.\")"
800
+ ],
801
+ "execution_count": null,
802
+ "outputs": []
803
+ },
804
+ {
805
+ "cell_type": "code",
806
+ "metadata": {},
807
+ "source": [
808
+ "#@title 8.2 — Execute Phase 2 { display-mode: \"form\" }\n",
809
+ "\n",
810
+ "if RUN_PHASE_2:\n",
811
+ " os.chdir(PROJECT_DIR)\n",
812
+ " \n",
813
+ " p2_cmd = f\"\"\"\n",
814
+ " python finetune_vibevoice_tpu.py \\\n",
815
+ " --model_name_or_path \"{SURGERY_MODEL_PATH}\" \\\n",
816
+ " --preprocessed_dir \"{PREPROCESSED_DATA_DIR}\" \\\n",
817
+ " --output_dir \"{P2_OUTPUT_DIR}\" \\\n",
818
+ " --resume_from_checkpoint \"{P2_RESUME_FROM}\" \\\n",
819
+ " --max_steps {P2_MAX_STEPS} \\\n",
820
+ " --num_train_epochs 2 \\\n",
821
+ " --per_device_train_batch_size {BATCH_SIZE_PER_CORE} \\\n",
822
+ " --gradient_accumulation_steps {GRADIENT_ACCUMULATION_STEPS} \\\n",
823
+ " --learning_rate {P2_LEARNING_RATE} \\\n",
824
+ " --lr_scheduler_type cosine \\\n",
825
+ " --warmup_steps {WARMUP_STEPS} \\\n",
826
+ " --max_grad_norm {MAX_GRAD_NORM} \\\n",
827
+ " --ce_loss_weight {CE_LOSS_WEIGHT} \\\n",
828
+ " --diffusion_loss_weight {DIFFUSION_LOSS_WEIGHT} \\\n",
829
+ " --ddpm_batch_mul {DDPM_BATCH_MUL} \\\n",
830
+ " --ema_decay {EMA_DECAY} \\\n",
831
+ " --eval_split_size {EVAL_SPLIT_SIZE} \\\n",
832
+ " --logging_steps {LOGGING_STEPS} \\\n",
833
+ " --save_steps {SAVE_STEPS} \\\n",
834
+ " --save_total_limit {SAVE_TOTAL_LIMIT} \\\n",
835
+ " --eval_steps {EVAL_STEPS} \\\n",
836
+ " --lora_r {LORA_R} \\\n",
837
+ " --lora_alpha {LORA_ALPHA} \\\n",
838
+ " --lora_target_modules q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj \\\n",
839
+ " --lora_wrap_diffusion_head {str(P2_LORA_WRAP_DIFFUSION_HEAD).lower()} \\\n",
840
+ " --train_diffusion_head {str(not P2_FREEZE_DIFFUSION_HEAD).lower()} \\\n",
841
+ " --train_connectors {str(not P2_FREEZE_CONNECTORS).lower()} \\\n",
842
+ " --train_surgery_module {str(not P2_FREEZE_SURGERY_MODULE).lower()} \\\n",
843
+ " {'--no_freeze_llm' if not P2_FREEZE_LLM else '--freeze_llm'} \\\n",
844
+ " {'--no_freeze_diffusion_head' if not P2_FREEZE_DIFFUSION_HEAD else '--freeze_diffusion_head'} \\\n",
845
+ " --gradient_checkpointing \\\n",
846
+ " --seed {SEED}\n",
847
+ " \"\"\"\n",
848
+ " \n",
849
+ " import re\n",
850
+ " p2_cmd = re.sub(r'\\s+\\\\\\n\\s+', ' ', p2_cmd).strip()\n",
851
+ " \n",
852
+ " print(\"🚀 Starting Phase 2 training on TPU...\")\n",
853
+ " \n",
854
+ " process = subprocess.Popen(p2_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, bufsize=1)\n",
855
+ " for line in process.stdout:\n",
856
+ " print(line, end='')\n",
857
+ " process.wait()\n",
858
+ " \n",
859
+ " if process.returncode == 0:\n",
860
+ " print(\"\\n✅ Phase 2 training completed!\")\n",
861
+ " else:\n",
862
+ " print(f\"\\n❌ Phase 2 failed with exit code: {process.returncode}\")\n",
863
+ "else:\n",
864
+ " print(\"Phase 2 skipped (RUN_PHASE_2=False).\")"
865
+ ],
866
+ "execution_count": null,
867
+ "outputs": []
868
+ },
869
+ {
870
+ "cell_type": "markdown",
871
+ "metadata": {},
872
+ "source": [
873
+ "## Cell 9: 💾 Export & Merge Trained Weights"
874
+ ]
875
+ },
876
+ {
877
+ "cell_type": "code",
878
+ "metadata": {},
879
+ "source": [
880
+ "#@title 9.1 — Merge LoRA Weights & Create Inference Model { display-mode: \"form\" }\n",
881
+ "\n",
882
+ "import os, sys, gc, torch\n",
883
+ "\n",
884
+ "os.chdir(PROJECT_DIR)\n",
885
+ "sys.path.insert(0, PROJECT_DIR)\n",
886
+ "\n",
887
+ "MERGE_OUTPUT = os.path.join(OUTPUT_DIR, \"merged_inference\") #@param {type:\"string\"}\n",
888
+ "\n",
889
+ "print(\"=\" * 60)\n",
890
+ "print(\" Merging Trained Weights (TPU → CPU for inference)\")\n",
891
+ "print(\"=\" * 60)\n",
892
+ "\n",
893
+ "# Find the checkpoint with trained weights\n",
894
+ "# Try final_model first, then latest checkpoint\n",
895
+ "lora_dir = os.path.join(OUTPUT_DIR, \"final_model\", \"lora\")\n",
896
+ "if not os.path.exists(lora_dir):\n",
897
+ " checkpoints = sorted(glob.glob(os.path.join(OUTPUT_DIR, \"checkpoint-*\")),\n",
898
+ " key=lambda x: int(x.split('-')[-1]))\n",
899
+ " if checkpoints:\n",
900
+ " lora_dir = os.path.join(checkpoints[-1], \"lora\")\n",
901
+ "\n",
902
+ "if not os.path.exists(lora_dir):\n",
903
+ " raise FileNotFoundError(f\"No trained artifacts found in {OUTPUT_DIR}\")\n",
904
+ "\n",
905
+ "print(f\"\\nUsing trained weights from: {lora_dir}\")\n",
906
+ "\n",
907
+ "# Apply patches\n",
908
+ "from vibevoice_surgery_colab import (\n",
909
+ " _patch_vibevoice_config_for_qwen3,\n",
910
+ " Qwen3SurgeryModule,\n",
911
+ " load_surgery_model,\n",
912
+ " save_surgery_model,\n",
913
+ " QWEN3_HIDDEN_SIZE,\n",
914
+ " DIFFUSION_HIDDEN_SIZE,\n",
915
+ " SURGERY_LAYER_INDICES,\n",
916
+ ")\n",
917
+ "_patch_vibevoice_config_for_qwen3()\n",
918
+ "\n",
919
+ "# Load the base surgery model\n",
920
+ "print(\"\\n[1/5] Loading base surgery model...\")\n",
921
+ "model = load_surgery_model(SURGERY_MODEL_PATH, dtype=torch.float32, device_map=\"cpu\")\n",
922
+ "\n",
923
+ "# Load LLM LoRA weights\n",
924
+ "print(\"\\n[2/5] Loading LLM LoRA weights...\")\n",
925
+ "try:\n",
926
+ " from peft import load_peft_weights, set_peft_model_state_dict\n",
927
+ " adapters_weights = load_peft_weights(lora_dir)\n",
928
+ " set_peft_model_state_dict(model.model.language_model, adapters_weights)\n",
929
+ " model.model.language_model = model.model.language_model.merge_and_unload()\n",
930
+ " print(\" ✅ LLM LoRA merged\")\n",
931
+ "except Exception as e:\n",
932
+ " print(f\" ℹ️ No LLM LoRA found: {e}\")\n",
933
+ "\n",
934
+ "# Load Diffusion Head\n",
935
+ "print(\"\\n[3/5] Loading Diffusion Head weights...\")\n",
936
+ "ph_path = os.path.join(lora_dir, \"diffusion_head_full.bin\")\n",
937
+ "if os.path.exists(ph_path):\n",
938
+ " model.model.prediction_head.load_state_dict(\n",
939
+ " torch.load(ph_path, map_location=\"cpu\"), strict=False\n",
940
+ " )\n",
941
+ " print(\" ✅ Diffusion Head loaded\")\n",
942
+ "\n",
943
+ "# Load Connectors\n",
944
+ "print(\"\\n[4/5] Loading Connectors...\")\n",
945
+ "for conn_name in [\"acoustic_connector\", \"semantic_connector\"]:\n",
946
+ " conn_path = os.path.join(lora_dir, conn_name, \"pytorch_model.bin\")\n",
947
+ " conn = getattr(model.model, conn_name, None)\n",
948
+ " if os.path.exists(conn_path) and conn is not None:\n",
949
+ " conn.load_state_dict(torch.load(conn_path, map_location=\"cpu\"))\n",
950
+ " print(f\" ✅ {conn_name} loaded\")\n",
951
+ "\n",
952
+ "# Load Surgery Module\n",
953
+ "print(\"\\n[5/5] Loading Surgery Module...\")\n",
954
+ "sm_path = os.path.join(lora_dir, \"surgery_module\", \"pytorch_model.bin\")\n",
955
+ "if os.path.exists(sm_path) and hasattr(model.model, \"surgery_module\"):\n",
956
+ " model.model.surgery_module.load_state_dict(\n",
957
+ " torch.load(sm_path, map_location=\"cpu\")\n",
958
+ " )\n",
959
+ " print(\" ✅ Surgery Module loaded\")\n",
960
+ "\n",
961
+ "# Save merged model\n",
962
+ "print(f\"\\n💾 Saving merged model to {MERGE_OUTPUT}...\")\n",
963
+ "save_surgery_model(model, MERGE_OUTPUT)\n",
964
+ "print(f\"\\n✅ Merged inference model saved to: {MERGE_OUTPUT}\")\n",
965
+ "\n",
966
+ "# Cleanup\n",
967
+ "del model\n",
968
+ "gc.collect()"
969
+ ],
970
+ "execution_count": null,
971
+ "outputs": []
972
+ },
973
+ {
974
+ "cell_type": "markdown",
975
+ "metadata": {},
976
+ "source": [
977
+ "## Cell 10: 🎤 Quick Inference Test"
978
+ ]
979
+ },
980
+ {
981
+ "cell_type": "code",
982
+ "metadata": {},
983
+ "source": [
984
+ "#@title 10.1 — Load Merged Model for Inference { display-mode: \"form\" }\n",
985
+ "\n",
986
+ "import os, sys, gc, torch\n",
987
+ "\n",
988
+ "os.chdir(PROJECT_DIR)\n",
989
+ "sys.path.insert(0, PROJECT_DIR)\n",
990
+ "\n",
991
+ "from vibevoice_surgery_colab import (\n",
992
+ " _patch_vibevoice_config_for_qwen3,\n",
993
+ " load_surgery_model,\n",
994
+ ")\n",
995
+ "_patch_vibevoice_config_for_qwen3()\n",
996
+ "\n",
997
+ "MERGE_PATH = os.path.join(OUTPUT_DIR, \"merged_inference\")\n",
998
+ "\n",
999
+ "if not os.path.exists(MERGE_PATH):\n",
1000
+ " print(f\"⚠️ Merged model not found at {MERGE_PATH}\")\n",
1001
+ " print(f\" Using base surgery model instead.\")\n",
1002
+ " MERGE_PATH = SURGERY_MODEL_PATH\n",
1003
+ "\n",
1004
+ "print(f\"Loading model from {MERGE_PATH}...\")\n",
1005
+ "# For inference, use CPU or GPU (not TPU — inference is better on GPU)\n",
1006
+ "inference_device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
1007
+ "print(f\"Inference device: {inference_device}\")\n",
1008
+ "\n",
1009
+ "inference_model = load_surgery_model(\n",
1010
+ " MERGE_PATH,\n",
1011
+ " dtype=torch.float16 if inference_device == \"cuda\" else torch.float32,\n",
1012
+ " device_map=\"auto\" if inference_device == \"cuda\" else \"cpu\",\n",
1013
+ ")\n",
1014
+ "inference_model.eval()\n",
1015
+ "print(\"✅ Model loaded for inference!\")"
1016
+ ],
1017
+ "execution_count": null,
1018
+ "outputs": []
1019
+ },
1020
+ {
1021
+ "cell_type": "code",
1022
+ "metadata": {},
1023
+ "source": [
1024
+ "#@title 10.2 — Generate Speech { display-mode: \"form\" }\n",
1025
+ "\n",
1026
+ "import torch\n",
1027
+ "\n",
1028
+ "TEXT_TO_SPEAK = \"Hello, this is a test of the fine-tuned voice model.\" #@param {type:\"string\"}\n",
1029
+ "VOICE_PROMPT_PATH = \"\" #@param {type:\"string\"}\n",
1030
+ "CFG_SCALE = 3.0 #@param {type:\"number\"}\n",
1031
+ "OUTPUT_AUDIO_PATH = \"/content/generated_speech.wav\" #@param {type:\"string\"}\n",
1032
+ "\n",
1033
+ "from vibevoice.processor.vibevoice_processor import VibeVoiceProcessor\n",
1034
+ "\n",
1035
+ "# Load processor\n",
1036
+ "processor = VibeVoiceProcessor.from_pretrained(MERGE_PATH)\n",
1037
+ "\n",
1038
+ "# Prepare inputs\n",
1039
+ "if VOICE_PROMPT_PATH and os.path.exists(VOICE_PROMPT_PATH):\n",
1040
+ " proc_out = processor(\n",
1041
+ " text=[TEXT_TO_SPEAK],\n",
1042
+ " voice_samples=[[VOICE_PROMPT_PATH]],\n",
1043
+ " return_tensors=\"pt\",\n",
1044
+ " )\n",
1045
+ "else:\n",
1046
+ " proc_out = processor(\n",
1047
+ " text=[TEXT_TO_SPEAK],\n",
1048
+ " return_tensors=\"pt\",\n",
1049
+ " )\n",
1050
+ "\n",
1051
+ "input_ids = proc_out[\"input_ids\"]\n",
1052
+ "attention_mask = proc_out.get(\"attention_mask\", torch.ones_like(input_ids))\n",
1053
+ "\n",
1054
+ "# Move to device\n",
1055
+ "device = next(inference_model.parameters()).device\n",
1056
+ "input_ids = input_ids.to(device)\n",
1057
+ "attention_mask = attention_mask.to(device)\n",
1058
+ "\n",
1059
+ "speech_tensors = proc_out.get(\"speech_tensors\")\n",
1060
+ "speech_masks = proc_out.get(\"speech_masks\")\n",
1061
+ "speech_input_mask = proc_out.get(\"speech_input_mask\")\n",
1062
+ "\n",
1063
+ "if speech_tensors is not None:\n",
1064
+ " speech_tensors = speech_tensors.to(device)\n",
1065
+ "if speech_masks is not None:\n",
1066
+ " speech_masks = speech_masks.to(device)\n",
1067
+ "if speech_input_mask is not None:\n",
1068
+ " speech_input_mask = speech_input_mask.to(device)\n",
1069
+ "\n",
1070
+ "print(f\"Generating speech for: {TEXT_TO_SPEAK[:80]}...\")\n",
1071
+ "print(f\"Input shape: {input_ids.shape}\")\n",
1072
+ "\n",
1073
+ "# Generate\n",
1074
+ "with torch.no_grad():\n",
1075
+ " output = inference_model.generate(\n",
1076
+ " input_ids=input_ids,\n",
1077
+ " attention_mask=attention_mask,\n",
1078
+ " speech_tensors=speech_tensors,\n",
1079
+ " speech_masks=speech_masks,\n",
1080
+ " speech_input_mask=speech_input_mask,\n",
1081
+ " max_new_tokens=2048,\n",
1082
+ " cfg_scale=CFG_SCALE,\n",
1083
+ " return_speech=True,\n",
1084
+ " )\n",
1085
+ "\n",
1086
+ "# Extract audio\n",
1087
+ "if hasattr(output, 'speech_outputs') and output.speech_outputs:\n",
1088
+ " import soundfile as sf\n",
1089
+ " audio = output.speech_outputs[0]\n",
1090
+ " if isinstance(audio, torch.Tensor):\n",
1091
+ " audio = audio.cpu().numpy()\n",
1092
+ " sf.write(OUTPUT_AUDIO_PATH, audio, 24000)\n",
1093
+ " print(f\"\\n✅ Audio saved to {OUTPUT_AUDIO_PATH}\")\n",
1094
+ " \n",
1095
+ " # Play in Colab\n",
1096
+ " from IPython.display import Audio, display\n",
1097
+ " display(Audio(OUTPUT_AUDIO_PATH))\n",
1098
+ "else:\n",
1099
+ " print(\"⚠️ No speech output generated.\")\n",
1100
+ " print(\"Output type:\", type(output))\n",
1101
+ " if hasattr(output, 'sequences'):\n",
1102
+ " print(f\"Generated sequence shape: {output.sequences.shape}\")"
1103
+ ],
1104
+ "execution_count": null,
1105
+ "outputs": []
1106
+ },
1107
+ {
1108
+ "cell_type": "markdown",
1109
+ "metadata": {},
1110
+ "source": [
1111
+ "## Cell 11: 📦 Download Results"
1112
+ ]
1113
+ },
1114
+ {
1115
+ "cell_type": "code",
1116
+ "metadata": {},
1117
+ "source": [
1118
+ "#@title 11.1 — Zip and Download Trained Artifacts { display-mode: \"form\" }\n",
1119
+ "\n",
1120
+ "import os, shutil\n",
1121
+ "\n",
1122
+ "ZIP_NAME = \"vibevoice_tpu_finetuned.zip\" #@param {type:\"string\"}\n",
1123
+ "\n",
1124
+ "zip_path = f\"/content/{ZIP_NAME}\"\n",
1125
+ "\n",
1126
+ "# Create zip\n",
1127
+ "print(f\"📦 Creating zip archive: {ZIP_NAME}...\")\n",
1128
+ "shutil.make_archive(\n",
1129
+ " zip_path.replace('.zip', ''),\n",
1130
+ " 'zip',\n",
1131
+ " os.path.dirname(OUTPUT_DIR),\n",
1132
+ " os.path.basename(OUTPUT_DIR)\n",
1133
+ ")\n",
1134
+ "\n",
1135
+ "size_mb = os.path.getsize(zip_path) / (1024 * 1024)\n",
1136
+ "print(f\"✅ Archive created: {zip_path} ({size_mb:.1f} MB)\")\n",
1137
+ "\n",
1138
+ "# Download\n",
1139
+ "from google.colab import files\n",
1140
+ "print(f\"\\n📥 Downloading {ZIP_NAME}...\")\n",
1141
+ "files.download(zip_path)"
1142
+ ],
1143
+ "execution_count": null,
1144
+ "outputs": []
1145
+ },
1146
+ {
1147
+ "cell_type": "code",
1148
+ "metadata": {},
1149
+ "source": [
1150
+ "#@title 11.2 — Upload to Google Drive { display-mode: \"form\" }\n",
1151
+ "\n",
1152
+ "UPLOAD_TO_DRIVE = False #@param {type:\"boolean\"}\n",
1153
+ "DRIVE_PATH = \"/content/drive/MyDrive/vibevoice_tpu_finetuned\" #@param {type:\"string\"}\n",
1154
+ "\n",
1155
+ "if UPLOAD_TO_DRIVE:\n",
1156
+ " from google.colab import drive\n",
1157
+ " drive.mount('/content/drive')\n",
1158
+ " \n",
1159
+ " import shutil\n",
1160
+ " print(f\"📤 Copying to Google Drive: {DRIVE_PATH}...\")\n",
1161
+ " if os.path.exists(DRIVE_PATH):\n",
1162
+ " shutil.rmtree(DRIVE_PATH)\n",
1163
+ " shutil.copytree(OUTPUT_DIR, DRIVE_PATH)\n",
1164
+ " print(f\"✅ Copied to {DRIVE_PATH}\")\n",
1165
+ "else:\n",
1166
+ " print(\"Drive upload skipped. Set UPLOAD_TO_DRIVE=True to enable.\")"
1167
+ ],
1168
+ "execution_count": null,
1169
+ "outputs": []
1170
+ }
1171
+ ]
1172
+ }
VibeVoice-tpu/src/preprocess_vibevoice.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ VibeVoice Dataset Preprocessing Script
3
+
4
+ این اسکریپت تمام داده‌ها را روی GPU پردازش کرده و نتایج را در یک فایل .pt ذخیره می‌کند.
5
+ در حین آموزش، داده‌های پردازش شده از حافظه یا دیسک بارگذاری می‌شوند.
6
+
7
+ استفاده:
8
+ python preprocess_vibevoice.py \\
9
+ --processor_name_or_path vibevoice/processor \\
10
+ --train_jsonl final.jsonl \\
11
+ --output_dir preprocessed_data \\
12
+ --per_device_batch_size 4 \\
13
+ --device cuda:0 \\
14
+ --max_length 800
15
+
16
+ این تمام داده‌ها را از .jsonl می‌خواند، بر روی GPU پردازش می‌کند و خروجی را
17
+ به صورت مجموعه‌ای از فایل‌های PyTorch ذخیره می‌کند.
18
+ """
19
+
20
+ import logging
21
+ import json
22
+ import os
23
+ import torch
24
+ import numpy as np
25
+ from pathlib import Path
26
+ from dataclasses import dataclass
27
+ from typing import Optional, Dict, Any, List
28
+ from tqdm import tqdm
29
+
30
+ from transformers import HfArgumentParser
31
+ from vibevoice.processor.vibevoice_processor import VibeVoiceProcessor
32
+ from data_vibevoice import _load_audio_to_24k, VibeVoiceCollator
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+
37
+ @dataclass
38
+ class PreprocessArguments:
39
+ """Arguments for preprocessing"""
40
+ processor_name_or_path: Optional[str] = None
41
+ train_jsonl: Optional[str] = None
42
+ output_dir: str = "preprocessed_data"
43
+ per_device_batch_size: int = 4
44
+ device: str = "cuda:0"
45
+ max_length: Optional[int] = None
46
+ text_column_name: str = "text"
47
+ audio_column_name: str = "audio"
48
+ voice_prompts_column_name: str = "voice_prompts"
49
+ save_raw_audio: bool = False # اگر True باشد، صوت خام را نیز ذخیره کند
50
+ debug: bool = False
51
+
52
+
53
+ class RawDatasetLoader:
54
+ """سادگی‌تر نسخه‌ای از VibeVoiceDataset برای پردازش خام"""
55
+ def __init__(self, jsonl_path: str, text_column: str = "text",
56
+ audio_column: str = "audio", voice_prompts_column: str = "voice_prompts"):
57
+ self.jsonl_path = jsonl_path
58
+ self.text_column = text_column
59
+ self.audio_column = audio_column
60
+ self.voice_prompts_column = voice_prompts_column
61
+ self.data = []
62
+ self._load()
63
+
64
+ def _load(self):
65
+ with open(self.jsonl_path, 'r', encoding='utf-8') as f:
66
+ for line in f:
67
+ if line.strip():
68
+ self.data.append(json.loads(line))
69
+
70
+ def __len__(self):
71
+ return len(self.data)
72
+
73
+ def __getitem__(self, idx):
74
+ return self.data[idx]
75
+
76
+
77
+ def preprocess_dataset(args: PreprocessArguments) -> None:
78
+ """
79
+ داده‌ها را پردازش کنید و در فایل‌های PyTorch ذخیره کنید
80
+ """
81
+ logging.basicConfig(
82
+ format="%(asctime)s - %(levelname)s - %(message)s",
83
+ level=logging.INFO
84
+ )
85
+
86
+ # بارگذاری پردازشگر
87
+ logger.info(f"Loading processor from {args.processor_name_or_path}")
88
+ processor = VibeVoiceProcessor.from_pretrained(args.processor_name_or_path)
89
+
90
+ # بررسی semantic_tokenizer
91
+ has_semantic_tokenizer = hasattr(processor, "semantic_tokenizer") and processor.semantic_tokenizer is not None
92
+ logger.info(f"Semantic tokenizer available: {has_semantic_tokenizer}")
93
+
94
+ if not has_semantic_tokenizer:
95
+ logger.warning("Semantic tokenizer not found in processor!")
96
+ logger.warning("This is OK for preprocessing - will use zero features as placeholders")
97
+
98
+ # بارگذاری داده‌های خام
99
+ logger.info(f"Loading dataset from {args.train_jsonl}")
100
+ dataset = RawDatasetLoader(
101
+ args.train_jsonl,
102
+ text_column=args.text_column_name,
103
+ audio_column=args.audio_column_name,
104
+ voice_prompts_column=args.voice_prompts_column_name
105
+ )
106
+ logger.info(f"Dataset size: {len(dataset)}")
107
+
108
+ # آماده‌سازی دایرکتوری خروجی
109
+ output_dir = Path(args.output_dir)
110
+ output_dir.mkdir(parents=True, exist_ok=True)
111
+
112
+ preprocessed_data_dir = output_dir / "preprocessed"
113
+ preprocessed_data_dir.mkdir(parents=True, exist_ok=True)
114
+
115
+ # دستور‌العمل collator
116
+ collator = VibeVoiceCollator(
117
+ processor=processor,
118
+ max_length=args.max_length,
119
+ speech_compress_ratio=getattr(processor, "speech_tok_compress_ratio", 3200),
120
+ semantic_vae_dim=128, # پیش‌فرض
121
+ compute_semantics=has_semantic_tokenizer, # فقط اگر موجود باشد
122
+ voice_prompt_drop_rate=0.0 # بدون حذف اثناء پردازش
123
+ )
124
+
125
+ # پردازش در دسته‌های batch
126
+ all_samples = []
127
+ batch = []
128
+ device = torch.device(args.device)
129
+
130
+ logger.info(f"Processing on device: {device}")
131
+ logger.info(f"Computing semantics: {has_semantic_tokenizer}")
132
+ logger.info(f"Max length: {args.max_length}")
133
+
134
+ for idx in tqdm(range(len(dataset)), desc="Loading samples"):
135
+ item = dataset[idx]
136
+ batch.append(item)
137
+
138
+ if len(batch) == args.per_device_batch_size or idx == len(dataset) - 1:
139
+ if len(batch) == 0:
140
+ continue
141
+ try:
142
+ # پردازش دسته
143
+ processed = collator(batch)
144
+
145
+ # منتقل کردن به CPU برای ذخیره
146
+ processed_cpu = {}
147
+ for k, v in processed.items():
148
+ if isinstance(v, torch.Tensor):
149
+ processed_cpu[k] = v.cpu()
150
+ else:
151
+ processed_cpu[k] = v
152
+
153
+ all_samples.append(processed_cpu)
154
+ batch = []
155
+
156
+ except Exception as e:
157
+ logger.error(f"Error processing batch starting at index {idx - len(batch) + 1}: {e}")
158
+ import traceback
159
+ logger.error(traceback.format_exc())
160
+ batch = []
161
+ continue
162
+
163
+ # ذخیره داده‌های پردازش‌شده
164
+ logger.info(f"Saving {len(all_samples)} batches...")
165
+
166
+ # ذخیره به صورت یک فایل واحد یا چندین فایل
167
+ output_file = preprocessed_data_dir / "preprocessed_batches.pt"
168
+ torch.save(all_samples, output_file)
169
+ logger.info(f"Saved preprocessed data to {output_file}")
170
+
171
+ # ذخیره metadata
172
+ metadata = {
173
+ "num_batches": len(all_samples),
174
+ "per_device_batch_size": args.per_device_batch_size,
175
+ "max_length": args.max_length,
176
+ "text_column": args.text_column_name,
177
+ "audio_column": args.audio_column_name,
178
+ "voice_prompts_column": args.voice_prompts_column_name,
179
+ }
180
+
181
+ metadata_file = output_dir / "metadata.json"
182
+ with open(metadata_file, 'w') as f:
183
+ json.dump(metadata, f, indent=2)
184
+ logger.info(f"Saved metadata to {metadata_file}")
185
+
186
+ logger.info("Preprocessing complete!")
187
+
188
+
189
+ if __name__ == "__main__":
190
+ parser = HfArgumentParser(PreprocessArguments)
191
+ args = parser.parse_args_into_dataclasses()[0]
192
+ preprocess_dataset(args)
VibeVoice-tpu/src/preprocess_vibevoice_tpu.py ADDED
@@ -0,0 +1,697 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ VibeVoice Dataset Preprocessing on TPU v5e
3
+ ============================================
4
+
5
+ این اسکریپت تمام داده‌ها را روی TPU پردازش کرده و نتایج را در فایل‌های .pt ذخیره می‌کند.
6
+ از قدرت TPU برای اجرای مدل‌های Acoustic Tokenizer و Semantic Tokenizer استفاده می‌کند.
7
+
8
+ مزیت نسبت به preprocess_vibevoice.py (CPU/GPU):
9
+ - اجرای tokenizer‌های عصبی روی TPU (200+ TFLOPS bf16)
10
+ - تبدیل dtype به bfloat16 هنگام پردازش (بهینه برای TPU v5e)
11
+ - پردازش موازی تنسورها روی TPU
12
+ - بدون نیاز به GPU — فقط TPU لازم است
13
+
14
+ استفاده:
15
+ python preprocess_vibevoice_tpu.py \\
16
+ --model_name_or_path /path/to/surgery_model \\
17
+ --train_jsonl /path/to/data.jsonl \\
18
+ --output_dir /path/to/preprocessed_output \\
19
+ --preprocess_batch_size 8 \\
20
+ --max_length 800 \\
21
+ --num_workers 0
22
+
23
+ خروجی:
24
+ output_dir/
25
+ preprocessed_batches_0000.pt
26
+ preprocessed_batches_0001.pt
27
+ ...
28
+ metadata.json
29
+ """
30
+
31
+ import os
32
+ import gc
33
+ import sys
34
+ import json
35
+ import math
36
+ import time
37
+ import logging
38
+ import functools
39
+ from pathlib import Path
40
+ from dataclasses import dataclass, field
41
+ from typing import Optional, Dict, Any, List, Tuple
42
+
43
+ # ============================================================================
44
+ # TPU Environment Setup (must be before torch import)
45
+ # ============================================================================
46
+ from tpu_config import setup_tpu_env, TPU_CONFIG
47
+ setup_tpu_env()
48
+
49
+ import numpy as np
50
+ import torch
51
+ import torch.nn as nn
52
+
53
+ # PyTorch/XLA imports
54
+ import torch_xla
55
+ import torch_xla.core.xla_model as xm
56
+ import torch_xla.distributed.xla_multiprocessing as xmp
57
+
58
+ # VibeVoice imports
59
+ from vibevoice.modular.modeling_vibevoice import (
60
+ VibeVoiceForConditionalGeneration,
61
+ )
62
+ from vibevoice.processor.vibevoice_processor import VibeVoiceProcessor
63
+ from data_vibevoice import _load_audio_to_24k, VibeVoiceCollator
64
+
65
+ logger = logging.getLogger(__name__)
66
+
67
+
68
+ # ============================================================================
69
+ # SECTION 1: Arguments
70
+ # ============================================================================
71
+
72
+ @dataclass
73
+ class TPUPreprocessArgs:
74
+ """Arguments for TPU preprocessing."""
75
+ # Model (needed for acoustic/semantic tokenizers)
76
+ model_name_or_path: str = field(
77
+ metadata={"help": "Path to surgery model (used for tokenizers)"}
78
+ )
79
+ processor_name_or_path: Optional[str] = field(
80
+ default=None,
81
+ metadata={"help": "Path to processor. Defaults to model_name_or_path."},
82
+ )
83
+
84
+ # Data input
85
+ train_jsonl: str = field(
86
+ metadata={"help": "Path to JSONL training data file"}
87
+ )
88
+
89
+ # Output
90
+ output_dir: str = field(
91
+ default="./preprocessed_tpu",
92
+ metadata={"help": "Directory to save preprocessed .pt files"},
93
+ )
94
+
95
+ # Preprocessing options
96
+ preprocess_batch_size: int = field(
97
+ default=8,
98
+ metadata={"help": "Number of samples per preprocessing batch"},
99
+ )
100
+ max_length: Optional[int] = field(
101
+ default=None,
102
+ metadata={"help": "Max sequence length. None = no limit."},
103
+ )
104
+ text_column_name: str = field(default="text")
105
+ audio_column_name: str = field(default="audio")
106
+ voice_prompts_column_name: str = field(default="voice_prompts")
107
+ speech_compress_ratio: int = field(default=3200)
108
+ semantic_vae_dim: int = field(default=128)
109
+ voice_prompt_drop_rate: float = field(default=0.0)
110
+
111
+ # Performance
112
+ save_every_n_batches: int = field(
113
+ default=100,
114
+ metadata={"help": "Save chunks every N batches to manage memory"},
115
+ )
116
+
117
+
118
+ # ============================================================================
119
+ # SECTION 2: Raw Data Loader
120
+ # ============================================================================
121
+
122
+ class RawDatasetLoader:
123
+ """Simple loader for JSONL datasets."""
124
+ def __init__(self, jsonl_path: str, text_column: str = "text",
125
+ audio_column: str = "audio", voice_prompts_column: str = "voice_prompts"):
126
+ self.jsonl_path = jsonl_path
127
+ self.text_column = text_column
128
+ self.audio_column = audio_column
129
+ self.voice_prompts_column = voice_prompts_column
130
+ self.data = []
131
+ self._load()
132
+
133
+ def _load(self):
134
+ with open(self.jsonl_path, 'r', encoding='utf-8') as f:
135
+ for line in f:
136
+ if line.strip():
137
+ self.data.append(json.loads(line))
138
+
139
+ def __len__(self):
140
+ return len(self.data)
141
+
142
+ def __getitem__(self, idx):
143
+ return self.data[idx]
144
+
145
+
146
+ # ============================================================================
147
+ # SECTION 3: TPU Model & Tokenizer Loading
148
+ # ============================================================================
149
+
150
+ def _patch_acoustic_encode_for_legacy_indexing(model_obj, logger_):
151
+ """Patch acoustic tokenizer encode to return [[...]] for legacy indexing."""
152
+ try:
153
+ acoustic = getattr(getattr(model_obj, "model", model_obj), "acoustic_tokenizer", None)
154
+ if acoustic is None or not hasattr(acoustic, "encode"):
155
+ logger_.warning("No acoustic_tokenizer.encode() found to patch.")
156
+ return
157
+ base_encode = acoustic.encode
158
+
159
+ def encode_wrapped(*args, **kwargs):
160
+ out = base_encode(*args, **kwargs)
161
+ try:
162
+ _ = out[0][0]
163
+ return out
164
+ except Exception:
165
+ pass
166
+ if isinstance(out, dict):
167
+ for k in ("frames", "codes", "tokens", "latents", "hidden_states"):
168
+ if k in out:
169
+ return [[out[k]]]
170
+ if len(out) > 0:
171
+ return [[next(iter(out.values()))]]
172
+ for attr in ("frames", "codes", "tokens", "latents", "hidden_states"):
173
+ if hasattr(out, attr):
174
+ return [[getattr(out, attr)]]
175
+ try:
176
+ if isinstance(out, torch.Tensor):
177
+ return [[out]]
178
+ except Exception:
179
+ pass
180
+ return [[out]]
181
+
182
+ acoustic.encode = encode_wrapped
183
+ logger_.info("Patched acoustic_tokenizer.encode() for legacy indexing.")
184
+ except Exception as e:
185
+ logger_.warning(f"Failed to patch acoustic_tokenizer.encode(): {e}")
186
+
187
+
188
+ def load_model_on_tpu(model_path: str, device: torch.device, dtype=torch.bfloat16):
189
+ """
190
+ Load model on TPU — only used for accessing tokenizers.
191
+ The LLM and other components are frozen/not used for preprocessing.
192
+ """
193
+ xm.master_print(f" Loading model from {model_path}...")
194
+
195
+ # Try surgery model first
196
+ try:
197
+ from vibevoice_surgery_colab import _patch_vibevoice_config_for_qwen3, load_surgery_model
198
+ _patch_vibevoice_config_for_qwen3()
199
+ model = load_surgery_model(model_path, dtype=dtype, device_map="cpu")
200
+ xm.master_print(" Loaded as surgery model")
201
+ except (ImportError, Exception):
202
+ model = VibeVoiceForConditionalGeneration.from_pretrained(
203
+ model_path, torch_dtype=dtype, device_map="cpu"
204
+ )
205
+ xm.master_print(" Loaded as standard VibeVoice model")
206
+
207
+ _patch_acoustic_encode_for_legacy_indexing(model, logger)
208
+
209
+ # Move to TPU
210
+ xm.master_print(f" Moving model to TPU device: {device}")
211
+ model = model.to(device)
212
+ xm.master_print(" Model loaded on TPU!")
213
+
214
+ return model
215
+
216
+
217
+ # ============================================================================
218
+ # SECTION 4: TPU-Accelerated Preprocessing Engine
219
+ # ============================================================================
220
+
221
+ class TPUPreprocessor:
222
+ """
223
+ Preprocesses raw VibeVoice data using TPU for compute-intensive operations.
224
+
225
+ Pipeline:
226
+ 1. CPU: Load JSONL → read audio files → resample to 24kHz
227
+ 2. CPU: Text tokenization via processor
228
+ 3. TPU: Acoustic tokenizer encoding (neural network on TPU)
229
+ 4. TPU: Semantic tokenizer encoding (neural network on TPU)
230
+ 5. TPU: Tensor padding, stacking, dtype conversion to bfloat16
231
+ 6. CPU: Save as .pt files
232
+ """
233
+
234
+ def __init__(
235
+ self,
236
+ model: VibeVoiceForConditionalGeneration,
237
+ processor: VibeVoiceProcessor,
238
+ device: torch.device,
239
+ args: TPUPreprocessArgs,
240
+ ):
241
+ self.model = model
242
+ self.processor = processor
243
+ self.device = device
244
+ self.args = args
245
+
246
+ # Verify tokenizers
247
+ self.acoustic_tokenizer = getattr(model.model, "acoustic_tokenizer", None)
248
+ self.semantic_tokenizer = getattr(model.model, "semantic_tokenizer", None)
249
+
250
+ # Also check processor for semantic tokenizer
251
+ proc_sem = getattr(processor, "semantic_tokenizer", None)
252
+ if self.semantic_tokenizer is None and proc_sem is not None:
253
+ self.semantic_tokenizer = proc_sem
254
+
255
+ xm.master_print(f" Acoustic tokenizer: {'✓' if self.acoustic_tokenizer is not None else '✗'}")
256
+ xm.master_print(f" Semantic tokenizer: {'✓' if self.semantic_tokenizer is not None else '✗'}")
257
+
258
+ # Build collator for text/audio processing
259
+ self.collator = VibeVoiceCollator(
260
+ processor=processor,
261
+ max_length=args.max_length,
262
+ speech_compress_ratio=args.speech_compress_ratio,
263
+ semantic_vae_dim=args.semantic_vae_dim,
264
+ compute_semantics=True,
265
+ voice_prompt_drop_rate=args.voice_prompt_drop_rate,
266
+ )
267
+
268
+ def preprocess_all(self) -> int:
269
+ """
270
+ Preprocess all data from JSONL and save as .pt files.
271
+
272
+ Returns:
273
+ Total number of batch files saved.
274
+ """
275
+ args = self.args
276
+
277
+ # ── Load raw data ──
278
+ xm.master_print(f"\n{'='*70}")
279
+ xm.master_print(f" TPU v5e DATA PREPROCESSING")
280
+ xm.master_print(f"{'='*70}")
281
+ xm.master_print(f" Input: {args.train_jsonl}")
282
+ xm.master_print(f" Output: {args.output_dir}")
283
+
284
+ raw_dataset = RawDatasetLoader(
285
+ args.train_jsonl,
286
+ text_column=args.text_column_name,
287
+ audio_column=args.audio_column_name,
288
+ voice_prompts_column=args.voice_prompts_column_name,
289
+ )
290
+ total_samples = len(raw_dataset)
291
+ xm.master_print(f" Total samples: {total_samples}")
292
+
293
+ # ── Prepare output directory ──
294
+ output_dir = Path(args.output_dir)
295
+ output_dir.mkdir(parents=True, exist_ok=True)
296
+
297
+ # ── Process in batches ──
298
+ batch_size = args.preprocess_batch_size
299
+ num_batches = math.ceil(total_samples / batch_size)
300
+ save_every = args.save_every_n_batches
301
+
302
+ xm.master_print(f" Batch size: {batch_size}")
303
+ xm.master_print(f" Total batches: {num_batches}")
304
+ xm.master_print(f" Save every: {save_every} batches")
305
+ xm.master_print(f"{'='*70}\n")
306
+
307
+ t_start = time.time()
308
+ chunk_idx = 0
309
+ chunk_buffer: List[Dict[str, torch.Tensor]] = []
310
+ total_saved = 0
311
+ samples_processed = 0
312
+
313
+ # Set model to eval mode (no gradients needed for preprocessing)
314
+ self.model.eval()
315
+
316
+ for batch_idx in range(num_batches):
317
+ start_idx = batch_idx * batch_size
318
+ end_idx = min(start_idx + batch_size, total_samples)
319
+ raw_batch = [raw_dataset[i] for i in range(start_idx, end_idx)]
320
+
321
+ try:
322
+ processed = self._preprocess_single_batch(raw_batch)
323
+
324
+ if processed is not None:
325
+ # Move to CPU for storage
326
+ processed_cpu = {}
327
+ for k, v in processed.items():
328
+ if isinstance(v, torch.Tensor):
329
+ processed_cpu[k] = v.detach().cpu()
330
+ else:
331
+ processed_cpu[k] = v
332
+
333
+ chunk_buffer.append(processed_cpu)
334
+ samples_processed += end_idx - start_idx
335
+
336
+ # Periodic XLA mark_step
337
+ xm.mark_step()
338
+
339
+ except Exception as e:
340
+ logger.error(f"Error in batch {batch_idx} (samples {start_idx}-{end_idx}): {e}")
341
+ import traceback
342
+ logger.error(traceback.format_exc())
343
+ xm.mark_step() # Clear XLA state after error
344
+ continue
345
+
346
+ # Save chunk when buffer is full or at the end
347
+ if len(chunk_buffer) >= save_every or batch_idx == num_batches - 1:
348
+ if chunk_buffer:
349
+ chunk_path = output_dir / f"preprocessed_batches_{chunk_idx:04d}.pt"
350
+ torch.save(chunk_buffer, str(chunk_path))
351
+ total_saved += len(chunk_buffer)
352
+ xm.master_print(
353
+ f" [{batch_idx+1}/{num_batches}] Saved chunk {chunk_idx} "
354
+ f"({len(chunk_buffer)} batches) → {chunk_path.name} | "
355
+ f"Samples: {samples_processed}/{total_samples}"
356
+ )
357
+ chunk_buffer = []
358
+ chunk_idx += 1
359
+ gc.collect()
360
+
361
+ # Progress
362
+ if (batch_idx + 1) % max(1, num_batches // 10) == 0:
363
+ elapsed = time.time() - t_start
364
+ speed = samples_processed / max(elapsed, 0.001)
365
+ eta = (total_samples - samples_processed) / max(speed, 0.001)
366
+ xm.master_print(
367
+ f" Progress: {samples_processed}/{total_samples} samples | "
368
+ f"{speed:.1f} samples/s | ETA: {eta:.0f}s"
369
+ )
370
+
371
+ # ── Save metadata ──
372
+ t_total = time.time() - t_start
373
+ metadata = {
374
+ "total_batches": total_saved,
375
+ "total_samples": total_samples,
376
+ "num_chunk_files": chunk_idx,
377
+ "preprocess_batch_size": batch_size,
378
+ "max_length": args.max_length,
379
+ "speech_compress_ratio": args.speech_compress_ratio,
380
+ "semantic_vae_dim": args.semantic_vae_dim,
381
+ "processing_time_seconds": t_total,
382
+ "device": "tpu_v5e",
383
+ "dtype": "bfloat16",
384
+ }
385
+ metadata_path = output_dir / "metadata.json"
386
+ with open(metadata_path, 'w') as f:
387
+ json.dump(metadata, f, indent=2)
388
+
389
+ xm.master_print(f"\n{'='*70}")
390
+ xm.master_print(f" PREPROCESSING COMPLETE!")
391
+ xm.master_print(f" Total batches saved: {total_saved}")
392
+ xm.master_print(f" Chunk files: {chunk_idx}")
393
+ xm.master_print(f" Total time: {t_total:.1f}s")
394
+ if t_total > 0:
395
+ xm.master_print(f" Average speed: {total_samples/t_total:.1f} samples/s")
396
+ xm.master_print(f" Output directory: {args.output_dir}")
397
+ xm.master_print(f"{'='*70}\n")
398
+
399
+ return chunk_idx
400
+
401
+ @torch.no_grad()
402
+ def _preprocess_single_batch(self, raw_batch: List[Dict[str, Any]]) -> Optional[Dict[str, torch.Tensor]]:
403
+ """
404
+ Process a single batch of raw data.
405
+
406
+ Steps:
407
+ 1. CPU: Collator does text tokenization + audio loading + padding
408
+ 2. TPU: Move tensors to TPU, convert to bfloat16
409
+ 3. TPU: Re-encode semantics on TPU if needed
410
+ """
411
+ args = self.args
412
+
413
+ # ── Step 1: CPU preprocessing via collator ──
414
+ # VibeVoiceCollator handles:
415
+ # - Text tokenization via processor
416
+ # - Audio loading & resampling to 24kHz
417
+ # - Voice prompt processing
418
+ # - Building input_ids, attention_mask, masks
419
+ # - Acoustic/semantic feature extraction
420
+ processed = self.collator(raw_batch)
421
+
422
+ if not processed:
423
+ return None
424
+
425
+ # ── Step 2: Move all tensors to TPU and convert to bfloat16 ──
426
+ result = {}
427
+ for k, v in processed.items():
428
+ if isinstance(v, torch.Tensor):
429
+ v_tpu = v.to(self.device)
430
+ # Convert float tensors to bfloat16 for TPU v5e
431
+ if v_tpu.is_floating_point():
432
+ v_tpu = v_tpu.to(dtype=torch.bfloat16)
433
+ result[k] = v_tpu
434
+ else:
435
+ result[k] = v
436
+
437
+ # ── Step 3: Re-encode semantic features on TPU if placeholder ──
438
+ if ("speech_semantic_tensors" in result
439
+ and "speech_tensors" in result
440
+ and result["speech_semantic_tensors"] is not None):
441
+
442
+ sem = result["speech_semantic_tensors"]
443
+ if torch.all(sem == 0) and self.semantic_tokenizer is not None:
444
+ try:
445
+ result["speech_semantic_tensors"] = self._encode_semantics_on_tpu(
446
+ result["speech_tensors"],
447
+ result.get("speech_masks"),
448
+ )
449
+ except Exception as e:
450
+ logger.debug(f"TPU semantic encoding failed, keeping zeros: {e}")
451
+
452
+ # ── Step 4: Re-encode acoustic features on TPU if needed ──
453
+ # Acoustic features are encoded via forward_speech_features in the collator
454
+ # but the collator uses CPU. If acoustic_tokenizer is on TPU, we can
455
+ # benefit from TPU speed for the acoustic encoding too.
456
+ if (self.acoustic_tokenizer is not None
457
+ and "speech_tensors" in result
458
+ and result["speech_tensors"] is not None):
459
+
460
+ # The speech_tensors are raw waveforms — acoustic encoding is done
461
+ # during training via model.forward_speech_features(). For preprocessing,
462
+ # we ensure the raw waveforms are properly formatted on TPU.
463
+ pass # Acoustic encoding happens during forward pass, waveforms are stored as-is
464
+
465
+ # ── Step 5: Convert non-float tensors back to CPU-compatible types ──
466
+ # Ensure integer/bool tensors stay as their original types
467
+ for k in result:
468
+ if isinstance(result[k], torch.Tensor):
469
+ if result[k].dtype == torch.bfloat16:
470
+ pass # Keep bfloat16 — finetune script will handle dtype
471
+ elif result[k].dtype in (torch.int64, torch.int32, torch.int16):
472
+ pass # Keep integer types
473
+ elif result[k].dtype == torch.bool:
474
+ pass # Keep bool
475
+
476
+ return result
477
+
478
+ def _encode_semantics_on_tpu(
479
+ self,
480
+ speech_tensors: torch.Tensor,
481
+ speech_masks: Optional[torch.Tensor],
482
+ ) -> torch.Tensor:
483
+ """
484
+ Encode semantic features using the semantic tokenizer on TPU.
485
+
486
+ This is the main TPU-accelerated operation — semantic encoding is a
487
+ neural network forward pass that benefits greatly from TPU compute.
488
+ """
489
+ device = speech_tensors.device
490
+ batch_size = speech_tensors.shape[0]
491
+ max_latent_len = speech_masks.shape[1] if speech_masks is not None else 1
492
+ sem_dim = self.args.semantic_vae_dim
493
+
494
+ semantic_features = []
495
+
496
+ for i in range(batch_size):
497
+ wav = speech_tensors[i]
498
+
499
+ # Determine actual latent length from mask
500
+ if speech_masks is not None:
501
+ mask = speech_masks[i]
502
+ if mask.dim() >= 1 and mask.any():
503
+ latent_len = min(int(mask.sum().item()), max_latent_len)
504
+ else:
505
+ latent_len = max_latent_len
506
+ else:
507
+ latent_len = max_latent_len
508
+
509
+ try:
510
+ sem_out = self.semantic_tokenizer.encode(
511
+ wav.unsqueeze(0) if wav.dim() == 1 else wav
512
+ )
513
+
514
+ # Handle various output formats
515
+ if isinstance(sem_out, torch.Tensor):
516
+ sem_feat = sem_out.float()
517
+ elif isinstance(sem_out, dict):
518
+ for key in ('features', 'mean', 'hidden_states', 'tokens'):
519
+ if key in sem_out:
520
+ sem_feat = sem_out[key].float()
521
+ break
522
+ else:
523
+ sem_feat = torch.zeros(latent_len, sem_dim, device=device)
524
+ elif hasattr(sem_out, 'mean'):
525
+ sem_feat = sem_out.mean.float()
526
+ else:
527
+ sem_feat = torch.zeros(latent_len, sem_dim, device=device)
528
+
529
+ # Ensure shape [T, D]
530
+ if sem_feat.dim() == 3:
531
+ sem_feat = sem_feat.squeeze(0)
532
+ if sem_feat.dim() == 1:
533
+ sem_feat = sem_feat.unsqueeze(0)
534
+
535
+ # Pad/trim to match latent_len
536
+ T = sem_feat.shape[0]
537
+ if T < latent_len:
538
+ pad = torch.zeros(
539
+ latent_len - T, sem_feat.shape[1],
540
+ device=device, dtype=sem_feat.dtype
541
+ )
542
+ sem_feat = torch.cat([sem_feat, pad], dim=0)
543
+ elif T > latent_len:
544
+ sem_feat = sem_feat[:latent_len]
545
+
546
+ # Ensure correct feature dimension
547
+ if sem_feat.shape[1] != sem_dim:
548
+ if sem_feat.shape[1] < sem_dim:
549
+ pad_d = torch.zeros(
550
+ sem_feat.shape[0], sem_dim - sem_feat.shape[1],
551
+ device=device, dtype=sem_feat.dtype
552
+ )
553
+ sem_feat = torch.cat([sem_feat, pad_d], dim=1)
554
+ else:
555
+ sem_feat = sem_feat[:, :sem_dim]
556
+
557
+ semantic_features.append(sem_feat.to(dtype=torch.bfloat16))
558
+
559
+ except Exception as e:
560
+ logger.debug(f"Semantic encode failed for sample {i}: {e}")
561
+ semantic_features.append(
562
+ torch.zeros(latent_len, sem_dim, device=device, dtype=torch.bfloat16)
563
+ )
564
+
565
+ # Stack [B, T, D]
566
+ if semantic_features:
567
+ return torch.stack(semantic_features, dim=0)
568
+ else:
569
+ return torch.zeros(
570
+ batch_size, max_latent_len, sem_dim,
571
+ device=device, dtype=torch.bfloat16
572
+ )
573
+
574
+
575
+ # ============================================================================
576
+ # SECTION 5: Single-process TPU preprocessing (for Colab / single host)
577
+ # ============================================================================
578
+
579
+ def preprocess_single_process(rank: int, args: TPUPreprocessArgs):
580
+ """
581
+ Run preprocessing on a single TPU chip.
582
+ Uses only rank 0 to avoid data duplication.
583
+ """
584
+ device = xm.xla_device()
585
+
586
+ if not xm.is_master_ordinal():
587
+ return # Only master process does preprocessing
588
+
589
+ xm.master_print(f"\n{'='*70}")
590
+ xm.master_print(f" TPU v5e Data Preprocessing | Device: {device}")
591
+ xm.master_print(f"{'='*70}")
592
+
593
+ # ── Load Processor ──
594
+ processor_path = args.processor_name_or_path or args.model_name_or_path
595
+ xm.master_print(f" Loading processor from {processor_path}")
596
+ processor = VibeVoiceProcessor.from_pretrained(processor_path)
597
+
598
+ # ── Load Model on TPU ──
599
+ model = load_model_on_tpu(args.model_name_or_path, device)
600
+
601
+ # ── Set processor's semantic tokenizer from model ──
602
+ proc_sem = getattr(model.model, "semantic_tokenizer", None)
603
+ if proc_sem is not None:
604
+ processor.semantic_tokenizer = proc_sem
605
+
606
+ # ── Run Preprocessing ──
607
+ preprocessor = TPUPreprocessor(model, processor, device, args)
608
+ num_files = preprocessor.preprocess_all()
609
+
610
+ xm.master_print(f" Done! {num_files} chunk files saved to {args.output_dir}")
611
+
612
+
613
+ # ============================================================================
614
+ # SECTION 6: Entry Point
615
+ # ============================================================================
616
+
617
+ def main():
618
+ import argparse
619
+
620
+ parser = argparse.ArgumentParser(
621
+ description="VibeVoice TPU Data Preprocessing — preprocess on TPU, save as .pt",
622
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
623
+ )
624
+
625
+ # Model
626
+ parser.add_argument("--model_name_or_path", type=str, required=True,
627
+ help="Path to surgery/VibeVoice model (for tokenizers)")
628
+ parser.add_argument("--processor_name_or_path", type=str, default=None,
629
+ help="Path to processor directory")
630
+
631
+ # Data
632
+ parser.add_argument("--train_jsonl", type=str, required=True,
633
+ help="Path to JSONL training data")
634
+ parser.add_argument("--output_dir", type=str, default="./preprocessed_tpu",
635
+ help="Output directory for .pt files")
636
+
637
+ # Preprocessing
638
+ parser.add_argument("--preprocess_batch_size", type=int, default=8,
639
+ help="Samples per preprocessing batch")
640
+ parser.add_argument("--max_length", type=int, default=None,
641
+ help="Max sequence length")
642
+ parser.add_argument("--text_column_name", type=str, default="text")
643
+ parser.add_argument("--audio_column_name", type=str, default="audio")
644
+ parser.add_argument("--voice_prompts_column_name", type=str, default="voice_prompts")
645
+ parser.add_argument("--speech_compress_ratio", type=int, default=3200)
646
+ parser.add_argument("--semantic_vae_dim", type=int, default=128)
647
+ parser.add_argument("--voice_prompt_drop_rate", type=float, default=0.0)
648
+
649
+ # Performance
650
+ parser.add_argument("--save_every_n_batches", type=int, default=100,
651
+ help="Save .pt chunk files every N batches")
652
+
653
+ args = parser.parse_args()
654
+
655
+ # Build args dataclass
656
+ preprocess_args = TPUPreprocessArgs(
657
+ model_name_or_path=args.model_name_or_path,
658
+ processor_name_or_path=args.processor_name_or_path,
659
+ train_jsonl=args.train_jsonl,
660
+ output_dir=args.output_dir,
661
+ preprocess_batch_size=args.preprocess_batch_size,
662
+ max_length=args.max_length,
663
+ text_column_name=args.text_column_name,
664
+ audio_column_name=args.audio_column_name,
665
+ voice_prompts_column_name=args.voice_prompts_column_name,
666
+ speech_compress_ratio=args.speech_compress_ratio,
667
+ semantic_vae_dim=args.semantic_vae_dim,
668
+ voice_prompt_drop_rate=args.voice_prompt_drop_rate,
669
+ save_every_n_batches=args.save_every_n_batches,
670
+ )
671
+
672
+ # ── Print config ──
673
+ print(f"\n{'='*70}")
674
+ print(f" VibeVoice TPU Data Preprocessing")
675
+ print(f"{'='*70}")
676
+ print(f" Model: {args.model_name_or_path}")
677
+ print(f" JSONL: {args.train_jsonl}")
678
+ print(f" Output: {args.output_dir}")
679
+ print(f" Batch: {args.preprocess_batch_size}")
680
+ print(f" Max len: {args.max_length}")
681
+ print(f" Sem dim: {args.semantic_vae_dim}")
682
+ print(f" Save every: {args.save_every_n_batches} batches")
683
+ print(f"{'='*70}\n")
684
+
685
+ # ── Launch on TPU ──
686
+ # Use only 1 process (rank 0) since preprocessing is sequential
687
+ # but benefits from TPU compute power for tokenizers
688
+ xmp.spawn(
689
+ preprocess_single_process,
690
+ args=(preprocess_args,),
691
+ nprocs=1, # Single TPU chip for preprocessing
692
+ start_method="fork",
693
+ )
694
+
695
+
696
+ if __name__ == "__main__":
697
+ main()
VibeVoice-tpu/src/tpu_config.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ TPU v5e-8 Configuration for VibeVoice Fine-Tuning
3
+ ===================================================
4
+
5
+ TPU v5e specifications:
6
+ - 8 chips per host (1 TPU v5e-8 pod slice)
7
+ - 16 GB HBM per chip = 128 GB total HBM
8
+ - bfloat16 native support (preferred over fp16)
9
+ - 200+ TFLOPS bf16 per chip
10
+
11
+ Key differences from GPU training:
12
+ - Use PyTorch/XLA instead of CUDA
13
+ - bfloat16 instead of fp16
14
+ - XLA graph compilation (static graphs)
15
+ - xm.mark_step() for explicit synchronization
16
+ - MpDeviceLoader for distributed data loading
17
+ """
18
+
19
+ import os
20
+
21
+
22
+ # ============================================================================
23
+ # TPU Environment Setup
24
+ # ============================================================================
25
+
26
+ def setup_tpu_env():
27
+ """Configure environment variables for optimal TPU v5e performance."""
28
+ # XLA configuration
29
+ os.environ.setdefault("XLA_USE_BF16", "1")
30
+ os.environ.setdefault("XLA_DOWNCAST_BF16", "1")
31
+
32
+ # PJRT runtime (modern TPU runtime)
33
+ os.environ.setdefault("PJRT_DEVICE", "TPU")
34
+
35
+ # Performance tuning
36
+ os.environ.setdefault("XLA_SYNC_WAIT", "1")
37
+ os.environ.setdefault("XLA_PERSISTENT_CACHE_PATH", "/tmp/xla_cache")
38
+
39
+ # Disable unnecessary features
40
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
41
+
42
+ # XLA compilation flags for performance
43
+ os.environ.setdefault("XLA_FLAGS",
44
+ "--xla_gpu_cuda_data_dir=/dev/null " # Not needed for TPU
45
+ "--xla_force_host_platform_device_count=8" # 8 TPU chips
46
+ )
47
+
48
+
49
+ # ============================================================================
50
+ # TPU Device Configuration
51
+ # ============================================================================
52
+
53
+ TPU_CONFIG = {
54
+ # Number of TPU chips (v5e-8 = 8 chips)
55
+ "num_chips": 8,
56
+
57
+ # HBM per chip
58
+ "hbm_per_chip_gb": 16,
59
+
60
+ # Total available HBM
61
+ "total_hbm_gb": 128,
62
+
63
+ # Data parallelism (use all 8 chips for data parallel)
64
+ "data_parallel_size": 8,
65
+
66
+ # Model parallelism (1 = no model parallelism)
67
+ "model_parallel_size": 1,
68
+
69
+ # Preferred dtype for TPU v5e
70
+ "dtype": "bfloat16",
71
+ }
72
+
73
+
74
+ # ============================================================================
75
+ # Training Configuration for TPU v5e-8
76
+ # ============================================================================
77
+
78
+ TPU_TRAINING_CONFIG = {
79
+ # ---- Batch Size & Accumulation ----
80
+ # Per-chip batch size (limited by 16GB HBM per chip)
81
+ # For VibeVoice-7B surgery model: batch_size=1 is safe with gradient checkpointing
82
+ "per_device_train_batch_size": 1,
83
+
84
+ # Gradient accumulation steps (effective batch = 1 * 8 * 8 = 64)
85
+ "gradient_accumulation_steps": 8,
86
+
87
+ # Total effective batch size
88
+ # = per_device_batch * num_chips * grad_accum = 1 * 8 * 8 = 64
89
+ "effective_batch_size": 64,
90
+
91
+ # ---- Learning Rate ----
92
+ "learning_rate": 2e-5,
93
+ "lr_scheduler_type": "cosine",
94
+ "warmup_ratio": 0.1,
95
+ "warmup_steps": 100,
96
+
97
+ # ---- Precision ----
98
+ # bfloat16 is native on TPU v5e (NOT fp16)
99
+ "bf16": True,
100
+ "fp16": False,
101
+
102
+ # ---- Memory Optimization ----
103
+ "gradient_checkpointing": True,
104
+ "ddpm_batch_mul": 1,
105
+
106
+ # ---- Loss Weights ----
107
+ "ce_loss_weight": 1.0,
108
+ "diffusion_loss_weight": 1.0,
109
+
110
+ # ---- Gradient Clipping ----
111
+ "max_grad_norm": 1.0,
112
+
113
+ # ---- Training Duration ----
114
+ "max_steps": 5000,
115
+ "num_train_epochs": 3,
116
+ "max_epochs": 3,
117
+
118
+ # ---- Logging & Saving ----
119
+ "logging_steps": 10,
120
+ "eval_steps": 500,
121
+ "save_steps": 500,
122
+ "save_total_limit": 3,
123
+
124
+ # ---- Data Loading ----
125
+ "dataloader_num_workers": 4,
126
+ "prefetch_factor": 4,
127
+
128
+ # ---- Evaluation ----
129
+ "eval_split_size": 0.05,
130
+ "do_eval": True,
131
+
132
+ # ---- Random Seed ----
133
+ "seed": 42,
134
+ }
135
+
136
+
137
+ # ============================================================================
138
+ # LoRA Configuration for TPU
139
+ # ============================================================================
140
+
141
+ TPU_LORA_CONFIG = {
142
+ "lora_r": 8,
143
+ "lora_alpha": 32,
144
+ "lora_dropout": 0.05,
145
+ "lora_target_modules": "q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj",
146
+ }
147
+
148
+
149
+ # ============================================================================
150
+ # Component Freezing Configuration
151
+ # ============================================================================
152
+
153
+ FREEZE_CONFIG = {
154
+ "freeze_llm": False, # LoRA wraps LLM, so it's partially trainable
155
+ "freeze_diffusion_head": True,
156
+ "freeze_surgery_module": False, # Train surgery module
157
+ "freeze_connectors": False, # Train connectors
158
+ "freeze_acoustic_tokenizer": True,
159
+ "freeze_semantic_tokenizer": True,
160
+ "freeze_lm_head": True,
161
+
162
+ # Fine-tune flags
163
+ "train_diffusion_head": False,
164
+ "train_connectors": True,
165
+ "train_surgery_module": True,
166
+
167
+ # Optional: wrap diffusion head with LoRA
168
+ "lora_wrap_diffusion_head": False,
169
+ }
170
+
171
+
172
+ # ============================================================================
173
+ # XLA Compilation & Performance Settings
174
+ # ============================================================================
175
+
176
+ XLA_CONFIG = {
177
+ # Number of batches to prefetch (larger = better throughput, more memory)
178
+ "prefetch_factor": 4,
179
+
180
+ # Enable XLA compilation caching (faster restarts)
181
+ "enable_compilation_cache": True,
182
+
183
+ # Mark step frequency (sync XLA graph every N batches)
184
+ # Should match gradient_accumulation_steps
185
+ "mark_step_frequency": 1,
186
+
187
+ # XLA auto-jit compilation
188
+ "auto_jit": True,
189
+ }
190
+
191
+
192
+ # ============================================================================
193
+ # Checkpoint Configuration
194
+ # ============================================================================
195
+
196
+ CHECKPOINT_CONFIG = {
197
+ # Save format compatible with GPU inference
198
+ "save_format": "pytorch",
199
+
200
+ # Components to save
201
+ "save_lora_adapters": True,
202
+ "save_diffusion_head": True,
203
+ "save_connectors": True,
204
+ "save_surgery_module": True,
205
+
206
+ # Checkpoint directory structure
207
+ # output_dir/
208
+ # checkpoint-{step}/
209
+ # lora/ # LLM LoRA adapters
210
+ # lora/diffusion_head/ # Diffusion head LoRA or full weights
211
+ # lora/diffusion_head_full.bin
212
+ # lora/acoustic_connector/
213
+ # lora/semantic_connector/
214
+ # lora/surgery_module/
215
+ # training_state.pt # Optimizer/scheduler state
216
+ }
217
+
218
+
219
+ # ============================================================================
220
+ # Memory Estimation
221
+ # ============================================================================
222
+
223
+ def estimate_memory_usage():
224
+ """
225
+ Rough memory estimation for TPU v5e-8.
226
+
227
+ Model components (approximate, bf16):
228
+ - LLM (Qwen3-4B): ~8 GB
229
+ - Diffusion Head: ~2 GB
230
+ - Acoustic Tokenizer: ~0.5 GB
231
+ - Semantic Tokenizer: ~0.5 GB
232
+ - Connectors: ~0.02 GB
233
+ - Surgery Module: ~0.04 GB
234
+ - LM Head: ~0.3 GB
235
+ Total model: ~12 GB per chip (fits in 16 GB HBM)
236
+
237
+ Training overhead:
238
+ - Gradients (trainable params): ~0.5 GB
239
+ - Optimizer states (AdamW): ~1 GB
240
+ - Activations (with gradient checkpointing): ~2 GB
241
+ Total overhead: ~3.5 GB
242
+
243
+ Total: ~15.5 GB per chip (tight but fits in 16 GB)
244
+ """
245
+
246
+ estimates = {
247
+ "model_bf16_gb": 12.0,
248
+ "gradients_gb": 0.5,
249
+ "optimizer_gb": 1.0,
250
+ "activations_gb": 2.0,
251
+ "total_gb": 15.5,
252
+ "available_gb": 16.0,
253
+ "headroom_gb": 0.5,
254
+ }
255
+
256
+ print("=" * 50)
257
+ print(" MEMORY ESTIMATION (per TPU chip, bf16)")
258
+ print("=" * 50)
259
+ for key, val in estimates.items():
260
+ print(f" {key:<25s}: {val:>6.1f} GB")
261
+ print("=" * 50)
262
+
263
+ if estimates["total_gb"] > estimates["available_gb"]:
264
+ print(" ⚠️ WARNING: Estimated usage exceeds available memory!")
265
+ print(" Consider: reduce batch size, increase grad accumulation,")
266
+ print(" or freeze more components.")
267
+ else:
268
+ print(" ✅ Model fits within TPU v5e HBM budget.")
269
+
270
+ return estimates
271
+
272
+
273
+ if __name__ == "__main__":
274
+ setup_tpu_env()
275
+ estimate_memory_usage()
VibeVoice-tpu/src/vibevoice/.DS_Store ADDED
Binary file (6.15 kB). View file
 
VibeVoice-tpu/src/vibevoice/configs/qwen2.5_1.5b_64k.json ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_attn_implementation_autoset": true,
3
+ "acoustic_vae_dim": 64,
4
+ "acoustic_tokenizer_config": {
5
+ "causal": true,
6
+ "channels": 1,
7
+ "conv_bias": true,
8
+ "conv_norm": "none",
9
+ "corpus_normalize": 0.0,
10
+ "decoder_depths": null,
11
+ "decoder_n_filters": 32,
12
+ "decoder_ratios": [
13
+ 8,
14
+ 5,
15
+ 5,
16
+ 4,
17
+ 2,
18
+ 2
19
+ ],
20
+ "disable_last_norm": true,
21
+ "encoder_depths": "3-3-3-3-3-3-8",
22
+ "encoder_n_filters": 32,
23
+ "encoder_ratios": [
24
+ 8,
25
+ 5,
26
+ 5,
27
+ 4,
28
+ 2,
29
+ 2
30
+ ],
31
+ "fix_std": 0.5,
32
+ "layer_scale_init_value": 1e-06,
33
+ "layernorm": "RMSNorm",
34
+ "layernorm_elementwise_affine": true,
35
+ "layernorm_eps": 1e-05,
36
+ "mixer_layer": "depthwise_conv",
37
+ "model_type": "vibepod_acoustic_tokenizer",
38
+ "pad_mode": "constant",
39
+ "std_dist_type": "gaussian",
40
+ "vae_dim": 64,
41
+ "weight_init_value": 0.01
42
+ },
43
+ "decoder_config": {
44
+ "attention_dropout": 0.0,
45
+ "hidden_act": "silu",
46
+ "hidden_size": 1536,
47
+ "initializer_range": 0.02,
48
+ "intermediate_size": 8960,
49
+ "max_position_embeddings": 65536,
50
+ "max_window_layers": 28,
51
+ "model_type": "qwen2",
52
+ "num_attention_heads": 12,
53
+ "num_hidden_layers": 28,
54
+ "num_key_value_heads": 2,
55
+ "rms_norm_eps": 1e-06,
56
+ "rope_scaling": null,
57
+ "rope_theta": 1000000.0,
58
+ "sliding_window": null,
59
+ "tie_word_embeddings": true,
60
+ "torch_dtype": "bfloat16",
61
+ "use_cache": true,
62
+ "use_sliding_window": false,
63
+ "vocab_size": 151936
64
+ },
65
+ "diffusion_head_config": {
66
+ "ddpm_batch_mul": 4,
67
+ "ddpm_beta_schedule": "cosine",
68
+ "ddpm_num_inference_steps": 20,
69
+ "ddpm_num_steps": 1000,
70
+ "diffusion_type": "ddpm",
71
+ "head_ffn_ratio": 3.0,
72
+ "head_layers": 4,
73
+ "hidden_size": 1536,
74
+ "latent_size": 64,
75
+ "model_type": "vibepod_diffusion_head",
76
+ "prediction_type": "v_prediction",
77
+ "rms_norm_eps": 1e-05,
78
+ "speech_vae_dim": 64
79
+ },
80
+ "model_type": "vibepod",
81
+ "semantic_tokenizer_config": {
82
+ "causal": true,
83
+ "channels": 1,
84
+ "conv_bias": true,
85
+ "conv_norm": "none",
86
+ "corpus_normalize": 0.0,
87
+ "disable_last_norm": true,
88
+ "encoder_depths": "3-3-3-3-3-3-8",
89
+ "encoder_n_filters": 32,
90
+ "encoder_ratios": [
91
+ 8,
92
+ 5,
93
+ 5,
94
+ 4,
95
+ 2,
96
+ 2
97
+ ],
98
+ "fix_std": 0,
99
+ "layer_scale_init_value": 1e-06,
100
+ "layernorm": "RMSNorm",
101
+ "layernorm_elementwise_affine": true,
102
+ "layernorm_eps": 1e-05,
103
+ "mixer_layer": "depthwise_conv",
104
+ "model_type": "vibepod_semantic_tokenizer",
105
+ "pad_mode": "constant",
106
+ "std_dist_type": "none",
107
+ "vae_dim": 128,
108
+ "weight_init_value": 0.01
109
+ },
110
+ "semantic_vae_dim": 128,
111
+ "torch_dtype": "bfloat16"
112
+ }
VibeVoice-tpu/src/vibevoice/configs/qwen2.5_7b_32k.json ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_attn_implementation_autoset": true,
3
+ "acoustic_vae_dim": 64,
4
+ "acoustic_tokenizer_config": {
5
+ "causal": true,
6
+ "channels": 1,
7
+ "conv_bias": true,
8
+ "conv_norm": "none",
9
+ "corpus_normalize": 0.0,
10
+ "decoder_depths": null,
11
+ "decoder_n_filters": 32,
12
+ "decoder_ratios": [
13
+ 8,
14
+ 5,
15
+ 5,
16
+ 4,
17
+ 2,
18
+ 2
19
+ ],
20
+ "disable_last_norm": true,
21
+ "encoder_depths": "3-3-3-3-3-3-8",
22
+ "encoder_n_filters": 32,
23
+ "encoder_ratios": [
24
+ 8,
25
+ 5,
26
+ 5,
27
+ 4,
28
+ 2,
29
+ 2
30
+ ],
31
+ "fix_std": 0.5,
32
+ "layer_scale_init_value": 1e-06,
33
+ "layernorm": "RMSNorm",
34
+ "layernorm_elementwise_affine": true,
35
+ "layernorm_eps": 1e-05,
36
+ "mixer_layer": "depthwise_conv",
37
+ "model_type": "vibepod_acoustic_tokenizer",
38
+ "pad_mode": "constant",
39
+ "std_dist_type": "gaussian",
40
+ "vae_dim": 64,
41
+ "weight_init_value": 0.01
42
+ },
43
+ "decoder_config": {
44
+ "attention_dropout": 0.0,
45
+ "hidden_act": "silu",
46
+ "hidden_size": 3584,
47
+ "initializer_range": 0.02,
48
+ "intermediate_size": 18944,
49
+ "max_position_embeddings": 32768,
50
+ "max_window_layers": 28,
51
+ "model_type": "qwen2",
52
+ "num_attention_heads": 28,
53
+ "num_hidden_layers": 28,
54
+ "num_key_value_heads": 4,
55
+ "rms_norm_eps": 1e-06,
56
+ "rope_theta": 1000000.0,
57
+ "sliding_window": null,
58
+ "tie_word_embeddings": false,
59
+ "torch_dtype": "bfloat16",
60
+ "transformers_version": "4.40.1",
61
+ "use_cache": true,
62
+ "use_mrope": false,
63
+ "use_sliding_window": false,
64
+ "vocab_size": 152064
65
+ },
66
+ "diffusion_head_config": {
67
+ "ddpm_batch_mul": 4,
68
+ "ddpm_beta_schedule": "cosine",
69
+ "ddpm_num_inference_steps": 20,
70
+ "ddpm_num_steps": 1000,
71
+ "diffusion_type": "ddpm",
72
+ "head_ffn_ratio": 3.0,
73
+ "head_layers": 4,
74
+ "hidden_size": 3584,
75
+ "latent_size": 64,
76
+ "model_type": "vibepod_diffusion_head",
77
+ "prediction_type": "v_prediction",
78
+ "rms_norm_eps": 1e-05,
79
+ "speech_vae_dim": 64
80
+ },
81
+ "model_type": "vibepod",
82
+ "semantic_tokenizer_config": {
83
+ "causal": true,
84
+ "channels": 1,
85
+ "conv_bias": true,
86
+ "conv_norm": "none",
87
+ "corpus_normalize": 0.0,
88
+ "disable_last_norm": true,
89
+ "encoder_depths": "3-3-3-3-3-3-8",
90
+ "encoder_n_filters": 32,
91
+ "encoder_ratios": [
92
+ 8,
93
+ 5,
94
+ 5,
95
+ 4,
96
+ 2,
97
+ 2
98
+ ],
99
+ "fix_std": 0,
100
+ "layer_scale_init_value": 1e-06,
101
+ "layernorm": "RMSNorm",
102
+ "layernorm_elementwise_affine": true,
103
+ "layernorm_eps": 1e-05,
104
+ "mixer_layer": "depthwise_conv",
105
+ "model_type": "vibepod_semantic_tokenizer",
106
+ "pad_mode": "constant",
107
+ "std_dist_type": "none",
108
+ "vae_dim": 128,
109
+ "weight_init_value": 0.01
110
+ },
111
+ "semantic_vae_dim": 128,
112
+ "torch_dtype": "bfloat16"
113
+ }
VibeVoice-tpu/src/vibevoice/modular/__init__.py ADDED
File without changes
VibeVoice-tpu/src/vibevoice/modular/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (175 Bytes). View file
 
VibeVoice-tpu/src/vibevoice/modular/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (153 Bytes). View file
 
VibeVoice-tpu/src/vibevoice/modular/__pycache__/configuration_vibevoice.cpython-311.pyc ADDED
Binary file (9.25 kB). View file
 
VibeVoice-tpu/src/vibevoice/modular/__pycache__/modeling_vibevoice.cpython-311.pyc ADDED
Binary file (29.3 kB). View file
 
VibeVoice-tpu/src/vibevoice/modular/__pycache__/modeling_vibevoice.cpython-39.pyc ADDED
Binary file (14.7 kB). View file
 
VibeVoice-tpu/src/vibevoice/modular/__pycache__/modular_vibevoice_diffusion_head.cpython-311.pyc ADDED
Binary file (15.8 kB). View file
 
VibeVoice-tpu/src/vibevoice/modular/__pycache__/modular_vibevoice_text_tokenizer.cpython-311.pyc ADDED
Binary file (8.29 kB). View file
 
VibeVoice-tpu/src/vibevoice/modular/__pycache__/modular_vibevoice_tokenizer.cpython-311.pyc ADDED
Binary file (65.4 kB). View file
 
VibeVoice-tpu/src/vibevoice/modular/configuration_vibevoice.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ VibeVoice_AcousticTokenizer model configuration"""
2
+
3
+ from typing import Dict, List, Optional, Tuple
4
+
5
+ from transformers.configuration_utils import PretrainedConfig
6
+ from transformers.utils import logging
7
+
8
+ from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
9
+
10
+ # Try to import Qwen3Config (available in transformers >= 4.51.0)
11
+ try:
12
+ from transformers import Qwen3Config
13
+ except ImportError:
14
+ Qwen3Config = None
15
+
16
+ logger = logging.get_logger(__name__)
17
+
18
+
19
+ class VibeVoiceAcousticTokenizerConfig(PretrainedConfig):
20
+ model_type = "vibevoice_acoustic_tokenizer"
21
+
22
+ def __init__(
23
+ self,
24
+ channels: int = 1,
25
+ corpus_normalize: float = 0.0,
26
+ causal: bool = True,
27
+ vae_dim: int = 64,
28
+ fix_std: float = 0.5,
29
+ std_dist_type: str = 'gaussian',
30
+ # common
31
+ mixer_layer: str = 'depthwise_conv',
32
+ conv_norm: str = 'none',
33
+ pad_mode: str = 'constant',
34
+ disable_last_norm: bool = True,
35
+ layernorm: str = 'RMSNorm',
36
+ layernorm_eps: float = 1e-5,
37
+ layernorm_elementwise_affine: bool = True,
38
+ conv_bias: bool = True,
39
+ layer_scale_init_value: float = 1e-6,
40
+ weight_init_value: float = 1e-2,
41
+ # encoder specific
42
+ encoder_n_filters: int = 32,
43
+ encoder_ratios: Optional[List[int]] = [8,5,5,4,2,2],
44
+ encoder_depths: str = "3-3-3-3-3-3-8",
45
+ # decoder specific
46
+ decoder_n_filters: int = 32,
47
+ decoder_ratios: Optional[List[int]] = None, # if None, same as encoder
48
+ decoder_depths: Optional[str] = None,
49
+ **kwargs
50
+ ):
51
+ super().__init__(**kwargs)
52
+ self.channels = channels
53
+ self.corpus_normalize = corpus_normalize
54
+ self.causal = causal
55
+ self.vae_dim = vae_dim
56
+ self.fix_std = fix_std
57
+ self.std_dist_type = std_dist_type
58
+
59
+ # common parameters
60
+ self.conv_norm = conv_norm
61
+ self.pad_mode = pad_mode
62
+ self.layernorm_eps = layernorm_eps
63
+ self.disable_last_norm = disable_last_norm
64
+ self.layernorm = layernorm
65
+ self.layernorm_elementwise_affine = layernorm_elementwise_affine
66
+ self.conv_bias = conv_bias
67
+ self.layer_scale_init_value = layer_scale_init_value
68
+ self.weight_init_value = weight_init_value
69
+ self.mixer_layer = mixer_layer
70
+
71
+ # encoder specific parameters
72
+ self.encoder_n_filters = encoder_n_filters
73
+ self.encoder_ratios = encoder_ratios
74
+ self.encoder_depths = encoder_depths
75
+
76
+ # decoder specific parameters
77
+ self.decoder_ratios = decoder_ratios if decoder_ratios is not None else encoder_ratios
78
+ self.decoder_n_filters = decoder_n_filters
79
+ self.decoder_depths = decoder_depths
80
+
81
+
82
+ class VibeVoiceSemanticTokenizerConfig(PretrainedConfig):
83
+ model_type = "vibevoice_semantic_tokenizer"
84
+
85
+ def __init__(
86
+ self,
87
+ channels: int = 1,
88
+ corpus_normalize: float = 0.0,
89
+ causal: bool = True,
90
+ vae_dim: int = 64,
91
+ fix_std: float = 0,
92
+ std_dist_type: str = 'none',
93
+ # common
94
+ mixer_layer: str = 'depthwise_conv',
95
+ conv_norm: str = 'none',
96
+ pad_mode: str = 'constant',
97
+ disable_last_norm: bool = True,
98
+ layernorm: str = 'RMSNorm',
99
+ layernorm_eps: float = 1e-5,
100
+ layernorm_elementwise_affine: bool = True,
101
+ conv_bias: bool = True,
102
+ layer_scale_init_value: float = 1e-6,
103
+ weight_init_value: float = 1e-2,
104
+ # encoder specific
105
+ encoder_n_filters: int = 32,
106
+ encoder_ratios: Optional[List[int]] = [8,5,5,4,2,2],
107
+ encoder_depths: str = "3-3-3-3-3-3-8",
108
+ **kwargs
109
+ ):
110
+ super().__init__(**kwargs)
111
+ self.channels = channels
112
+ self.corpus_normalize = corpus_normalize
113
+ self.causal = causal
114
+ self.vae_dim = vae_dim
115
+ self.fix_std = fix_std
116
+ self.std_dist_type = std_dist_type
117
+
118
+ # common parameters
119
+ self.conv_norm = conv_norm
120
+ self.pad_mode = pad_mode
121
+ self.layernorm_eps = layernorm_eps
122
+ self.disable_last_norm = disable_last_norm
123
+ self.layernorm = layernorm
124
+ self.layernorm_elementwise_affine = layernorm_elementwise_affine
125
+ self.conv_bias = conv_bias
126
+ self.layer_scale_init_value = layer_scale_init_value
127
+ self.weight_init_value = weight_init_value
128
+ self.mixer_layer = mixer_layer
129
+
130
+ # encoder specific parameters
131
+ self.encoder_n_filters = encoder_n_filters
132
+ self.encoder_ratios = encoder_ratios
133
+ self.encoder_depths = encoder_depths
134
+
135
+
136
+ class VibeVoiceDiffusionHeadConfig(PretrainedConfig):
137
+ model_type = "vibevoice_diffusion_head"
138
+
139
+ def __init__(
140
+ self,
141
+ hidden_size=768,
142
+ head_layers=4,
143
+ head_ffn_ratio=3.0,
144
+ rms_norm_eps=1e-5,
145
+ latent_size=64,
146
+ speech_vae_dim=None,
147
+ prediction_type="v_prediction",
148
+ diffusion_type="ddpm",
149
+ ddpm_num_steps=1000,
150
+ ddpm_num_inference_steps=20,
151
+ ddpm_beta_schedule="cosine",
152
+ ddpm_batch_mul=4,
153
+ **kwargs
154
+ ):
155
+ self.hidden_size = hidden_size
156
+ self.head_layers = head_layers
157
+ self.head_ffn_ratio = head_ffn_ratio
158
+ self.rms_norm_eps = rms_norm_eps
159
+ self.latent_size = latent_size
160
+ self.speech_vae_dim = speech_vae_dim
161
+ self.prediction_type = prediction_type
162
+ self.diffusion_type = diffusion_type
163
+ self.ddpm_num_steps = ddpm_num_steps
164
+ self.ddpm_num_inference_steps = ddpm_num_inference_steps
165
+ self.ddpm_beta_schedule = ddpm_beta_schedule
166
+ self.ddpm_batch_mul = ddpm_batch_mul
167
+
168
+ super().__init__(**kwargs)
169
+
170
+ class VibeVoiceConfig(PretrainedConfig):
171
+ model_type = "vibevoice"
172
+ is_composition = True
173
+ sub_configs = {
174
+ "acoustic_tokenizer_config": VibeVoiceAcousticTokenizerConfig,
175
+ "semantic_tokenizer_config": VibeVoiceSemanticTokenizerConfig,
176
+ "decoder_config": Qwen2Config,
177
+ "diffusion_head_config": VibeVoiceDiffusionHeadConfig,
178
+ }
179
+ # keys_to_ignore_at_inference = ["past_key_values"]
180
+ # Default tensor parallel plan for base model `Qwen2`
181
+ base_model_tp_plan = {
182
+ "layers.*.self_attn.q_proj": "colwise",
183
+ "layers.*.self_attn.k_proj": "colwise",
184
+ "layers.*.self_attn.v_proj": "colwise",
185
+ "layers.*.self_attn.o_proj": "rowwise",
186
+ "layers.*.mlp.gate_proj": "colwise",
187
+ "layers.*.mlp.up_proj": "colwise",
188
+ "layers.*.mlp.down_proj": "rowwise",
189
+ }
190
+
191
+ def __init__(
192
+ self,
193
+ acoustic_tokenizer_config=None,
194
+ semantic_tokenizer_config=None,
195
+ decoder_config=None,
196
+ diffusion_head_config=None,
197
+ **kwargs
198
+ ):
199
+
200
+ # kwargs["_attn_implementation"] = "flash_attention_2"
201
+ kwargs["_attn_implementation_autoset"] = False
202
+
203
+ if acoustic_tokenizer_config is None:
204
+ self.acoustic_tokenizer_config = self.sub_configs["acoustic_tokenizer_config"]()
205
+ elif isinstance(acoustic_tokenizer_config, dict):
206
+ acoustic_tokenizer_config["model_type"] = "vibevoice_acoustic_tokenizer"
207
+ self.acoustic_tokenizer_config = self.sub_configs["acoustic_tokenizer_config"](**acoustic_tokenizer_config)
208
+ elif isinstance(acoustic_tokenizer_config, VibeVoiceAcousticTokenizerConfig):
209
+ # If an instance of the config class is provided
210
+ self.acoustic_tokenizer_config = acoustic_tokenizer_config
211
+
212
+ if semantic_tokenizer_config is None:
213
+ self.semantic_tokenizer_config = self.sub_configs["semantic_tokenizer_config"]()
214
+ elif isinstance(semantic_tokenizer_config, dict):
215
+ semantic_tokenizer_config["model_type"] = "vibevoice_semantic_tokenizer"
216
+ self.semantic_tokenizer_config = self.sub_configs["semantic_tokenizer_config"](**semantic_tokenizer_config)
217
+ elif isinstance(semantic_tokenizer_config, VibeVoiceSemanticTokenizerConfig):
218
+ # If an instance of the config class is provided
219
+ self.semantic_tokenizer_config = semantic_tokenizer_config
220
+
221
+ if decoder_config is None:
222
+ self.decoder_config = self.sub_configs["decoder_config"]()
223
+ elif isinstance(decoder_config, dict):
224
+ model_type = decoder_config.get("model_type", "")
225
+ if model_type == "qwen2":
226
+ self.decoder_config = Qwen2Config(**decoder_config)
227
+ elif model_type == "qwen3" and Qwen3Config is not None:
228
+ self.decoder_config = Qwen3Config(**decoder_config)
229
+ else:
230
+ # Fallback: try Qwen2Config for unknown types (backward compat)
231
+ try:
232
+ self.decoder_config = Qwen2Config(**decoder_config)
233
+ except Exception:
234
+ raise ValueError(
235
+ f"Unsupported decoder model type: '{model_type}'. "
236
+ f"Supported: 'qwen2', 'qwen3'"
237
+ )
238
+ elif isinstance(decoder_config, Qwen2Config):
239
+ self.decoder_config = decoder_config
240
+ elif Qwen3Config is not None and isinstance(decoder_config, Qwen3Config):
241
+ self.decoder_config = decoder_config
242
+ elif isinstance(decoder_config, PretrainedConfig):
243
+ # Accept any PretrainedConfig subclass (future-proof)
244
+ self.decoder_config = decoder_config
245
+
246
+ if diffusion_head_config is None:
247
+ self.diffusion_head_config = self.sub_configs["diffusion_head_config"]()
248
+ elif isinstance(diffusion_head_config, dict):
249
+ diffusion_head_config["model_type"] = "vibevoice_diffusion_head"
250
+ self.diffusion_head_config = self.sub_configs["diffusion_head_config"](**diffusion_head_config)
251
+ elif isinstance(diffusion_head_config, VibeVoiceDiffusionHeadConfig):
252
+ # If an instance of the config class is provided
253
+ self.diffusion_head_config = diffusion_head_config
254
+
255
+ # other parameters
256
+ self.acoustic_vae_dim = getattr(self.acoustic_tokenizer_config, 'vae_dim', 64)
257
+ self.semantic_vae_dim = getattr(self.semantic_tokenizer_config, 'vae_dim', 128)
258
+
259
+ super().__init__(**kwargs)
260
+
261
+ __all__ = [
262
+ "VibeVoiceAcousticTokenizerConfig",
263
+ "VibeVoiceSemanticTokenizerConfig",
264
+ "VibeVoiceDiffusionHeadConfig",
265
+ "VibeVoiceConfig"
266
+ ]
VibeVoice-tpu/src/vibevoice/modular/modeling_vibevoice.py ADDED
@@ -0,0 +1,508 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Dict, List, Optional, Tuple, Union, Callable
3
+ from tqdm import tqdm
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ import torch.distributed as dist
8
+
9
+ from transformers.models.auto import AutoModel, AutoModelForCausalLM
10
+
11
+ from transformers.activations import ACT2FN
12
+ from transformers.modeling_outputs import CausalLMOutput, BaseModelOutputWithPast, ModelOutput
13
+ from transformers.models.llama.modeling_llama import LlamaRMSNorm
14
+ from transformers import modeling_utils
15
+ from transformers.modeling_utils import PreTrainedModel
16
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
17
+ from transformers.utils import logging
18
+
19
+
20
+ from .modular_vibevoice_tokenizer import VibeVoiceTokenizerStreamingCache, VibeVoiceAcousticTokenizerModel, VibeVoiceSemanticTokenizerModel
21
+ from .modular_vibevoice_diffusion_head import VibeVoiceDiffusionHead
22
+ from vibevoice.schedule.dpm_solver import DPMSolverMultistepScheduler
23
+
24
+ from .configuration_vibevoice import VibeVoiceConfig
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+ if not hasattr(modeling_utils, "ALL_PARALLEL_STYLES") or modeling_utils.ALL_PARALLEL_STYLES is None:
30
+ modeling_utils.ALL_PARALLEL_STYLES = ["tp", "none", "colwise", "rowwise"]
31
+
32
+ @dataclass
33
+ class VibeVoiceCausalLMOutputWithPast(ModelOutput):
34
+ loss: Optional[torch.FloatTensor] = None
35
+ diffusion_loss: Optional[torch.FloatTensor] = None
36
+ speech_token_num: Optional[int] = None
37
+ logits: torch.FloatTensor = None
38
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
39
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
40
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
41
+
42
+
43
+ @dataclass
44
+ class VibeVoiceGenerationOutput(ModelOutput):
45
+ """
46
+ Output type for VibeVoice generation.
47
+
48
+ Args:
49
+ sequences (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
50
+ The generated sequences.
51
+ speech_outputs (`List[torch.FloatTensor]`, *optional*):
52
+ List of generated speech waveforms or latents for each speech segment.
53
+ """
54
+ sequences: torch.LongTensor = None
55
+ speech_outputs: Optional[List[torch.FloatTensor]] = None
56
+
57
+
58
+ class SpeechConnector(nn.Module):
59
+ def __init__(self, input_dim, output_dim):
60
+ super().__init__()
61
+ self.fc1 = nn.Linear(input_dim, output_dim)
62
+ self.norm = LlamaRMSNorm(output_dim, eps=1e-6)
63
+ self.fc2 = nn.Linear(output_dim, output_dim)
64
+
65
+ def forward(self, features, **kwargs):
66
+ x = self.fc1(features)
67
+ x = self.norm(x)
68
+ x = self.fc2(x)
69
+ return x
70
+
71
+
72
+ # @auto_docstring
73
+ class VibeVoicePreTrainedModel(PreTrainedModel):
74
+ config_class = VibeVoiceConfig
75
+ base_model_prefix = "model"
76
+ supports_gradient_checkpointing = True
77
+ _skip_keys_device_placement = "past_key_values"
78
+ _supports_cache_class = True
79
+ _supports_flash_attn_2 = True
80
+ _supports_sdpa = True
81
+ _supports_quantized_cache = True
82
+ _supports_static_cache = True
83
+ _supports_attention_backend = True
84
+
85
+ def _init_weights(self, module):
86
+ if isinstance(module, VibeVoiceDiffusionHead):
87
+ module.initialize_weights()
88
+ return
89
+
90
+ # Use the language model's initializer_range if available
91
+ if hasattr(self.config, 'language_model_config') and hasattr(self.config.language_model_config, 'initializer_range'):
92
+ std = self.config.language_model_config.initializer_range
93
+ elif hasattr(self.config, 'decoder_config') and hasattr(self.config.decoder_config, 'initializer_range'):
94
+ std = self.config.decoder_config.initializer_range
95
+ else:
96
+ std = 0.02 # Default value
97
+
98
+ if isinstance(module, nn.Linear):
99
+ module.weight.data.normal_(mean=0.0, std=std)
100
+ if module.bias is not None:
101
+ module.bias.data.zero_()
102
+ elif isinstance(module, nn.LayerNorm):
103
+ module.weight.data.fill_(1.0)
104
+ module.bias.data.zero_()
105
+
106
+ # @auto_docstring
107
+ class VibeVoiceModel(VibeVoicePreTrainedModel):
108
+ def __init__(self, config):
109
+ super().__init__(config)
110
+
111
+ if hasattr(config, 'torch_dtype') and config.torch_dtype is not None:
112
+ if isinstance(config.torch_dtype, str):
113
+ dtype = getattr(torch, config.torch_dtype)
114
+ else:
115
+ dtype = config.torch_dtype
116
+ else:
117
+ dtype = torch.float32
118
+
119
+ # Initialize Qwen2 model for language modeling
120
+ lm_config = config.decoder_config
121
+ self.language_model = AutoModel.from_config(lm_config)
122
+
123
+ # Initialize speech components if needed
124
+ self.acoustic_tokenizer = AutoModel.from_config(config.acoustic_tokenizer_config).to(dtype)
125
+ self.semantic_tokenizer = AutoModel.from_config(config.semantic_tokenizer_config).to(dtype)
126
+
127
+ self.acoustic_connector = SpeechConnector(config.acoustic_vae_dim, lm_config.hidden_size).to(dtype)
128
+ self.semantic_connector = SpeechConnector(config.semantic_vae_dim, lm_config.hidden_size).to(dtype)
129
+
130
+ # Register scaling factors as buffers - use 1D tensors for FSDP compatibility
131
+ self.register_buffer('speech_scaling_factor', torch.tensor(float('nan')))
132
+ self.register_buffer('speech_bias_factor', torch.tensor(float('nan')))
133
+
134
+ # Initialize prediction head for speech generation
135
+ self.prediction_head = AutoModel.from_config(config.diffusion_head_config).to(dtype)
136
+
137
+ # Initialize noise scheduler
138
+ self.noise_scheduler = DPMSolverMultistepScheduler(
139
+ num_train_timesteps=config.diffusion_head_config.ddpm_num_steps,
140
+ beta_schedule=config.diffusion_head_config.ddpm_beta_schedule,
141
+ prediction_type=config.diffusion_head_config.prediction_type
142
+ )
143
+
144
+ def get_input_embeddings(self):
145
+ if hasattr(self.language_model, 'embed_tokens'):
146
+ # If the language model has an embed_tokens attribute, return it
147
+ return self.language_model.embed_tokens
148
+
149
+ for name, attr in self.language_model.fullmap.items(): # parallel by nnscaler, the name is changed
150
+ if attr.orig_name == 'embed_tokens.weight':
151
+ return getattr(self.language_model, name)
152
+ assert False, 'should not arrive here'
153
+
154
+ def set_input_embeddings(self, value):
155
+ self.language_model.embed_tokens = value
156
+
157
+ def set_speech_tokenizers(self, acoustic_tokenizer=None, semantic_tokenizer=None):
158
+ """Set the speech tokenizers used for encoding and decoding speech."""
159
+ self.acoustic_tokenizer = acoustic_tokenizer
160
+ self.semantic_tokenizer = semantic_tokenizer
161
+
162
+ # Reset the encoder to evaluation mode
163
+ if self.acoustic_tokenizer is not None:
164
+ self.acoustic_tokenizer.eval()
165
+
166
+ if self.semantic_tokenizer is not None:
167
+ self.semantic_tokenizer.eval()
168
+
169
+ def forward(
170
+ self,
171
+ input_ids: torch.LongTensor = None,
172
+ attention_mask: Optional[torch.Tensor] = None,
173
+ position_ids: Optional[torch.LongTensor] = None,
174
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
175
+ inputs_embeds: Optional[torch.FloatTensor] = None,
176
+ use_cache: Optional[bool] = None,
177
+ output_attentions: Optional[bool] = None,
178
+ output_hidden_states: Optional[bool] = None,
179
+ return_dict: Optional[bool] = None,
180
+ cache_position: Optional[torch.LongTensor] = None,
181
+ **kwargs,
182
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
183
+
184
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
185
+
186
+ # Forward through language model
187
+ outputs = self.language_model(
188
+ input_ids=input_ids,
189
+ attention_mask=attention_mask,
190
+ position_ids=position_ids,
191
+ past_key_values=past_key_values,
192
+ inputs_embeds=inputs_embeds,
193
+ use_cache=use_cache,
194
+ output_attentions=output_attentions,
195
+ output_hidden_states=output_hidden_states,
196
+ return_dict=return_dict,
197
+ cache_position=cache_position,
198
+ **kwargs,
199
+ )
200
+
201
+ if not return_dict:
202
+ return outputs
203
+
204
+ return BaseModelOutputWithPast(
205
+ last_hidden_state=outputs.last_hidden_state,
206
+ past_key_values=outputs.past_key_values,
207
+ hidden_states=outputs.hidden_states,
208
+ attentions=outputs.attentions,
209
+ )
210
+
211
+
212
+ class VibeVoiceForConditionalGeneration(VibeVoicePreTrainedModel):
213
+ _tied_weights_keys = ["lm_head.weight"]
214
+ _tp_plan = {"lm_head": "colwise_rep"}
215
+
216
+ def __init__(self, config):
217
+ super().__init__(config)
218
+ self.model = VibeVoiceModel(config)
219
+ self.vocab_size = config.decoder_config.vocab_size
220
+ self.lm_head = nn.Linear(config.decoder_config.hidden_size, self.vocab_size, bias=False)
221
+
222
+ self.post_init()
223
+
224
+ def get_input_embeddings(self):
225
+ return self.model.get_input_embeddings()
226
+
227
+ def set_input_embeddings(self, value):
228
+ self.model.set_input_embeddings(value)
229
+
230
+ def get_output_embeddings(self):
231
+ return self.lm_head
232
+
233
+ def set_decoder(self, decoder):
234
+ self.model.language_model = decoder
235
+
236
+ def get_decoder(self):
237
+ return self.model.language_model
238
+
239
+ def tie_weights(self):
240
+ """
241
+ Tie the weights between the input embeddings and the output embeddings.
242
+ """
243
+ if getattr(self.config.decoder_config, 'tie_word_embeddings', False):
244
+ # The standard PreTrainedModel method will handle the tying.
245
+ # It typically does a simple parameter object assignment, which is
246
+ # CORRECT to do BEFORE FSDP wraps the model.
247
+ output_embeddings = self.get_output_embeddings()
248
+ input_embeddings = self.get_input_embeddings()
249
+ if hasattr(input_embeddings, 'weight'):
250
+ output_embeddings.weight = input_embeddings.weight
251
+ else:
252
+ # maybe returned input_embeddings a tensor directly
253
+ output_embeddings.weight = input_embeddings
254
+
255
+ if getattr(output_embeddings, "bias", None) is not None:
256
+ output_embeddings.bias.data = nn.functional.pad(
257
+ output_embeddings.bias.data,
258
+ (0, output_embeddings.weight.shape[0] - output_embeddings.bias.shape[0]),
259
+ "constant",
260
+ 0,
261
+ )
262
+ print("✅ Tied input and output embeddings using standard assignment.")
263
+ else:
264
+ print("ℹ️ tie_word_embeddings is False, not tying weights.")
265
+
266
+ # Also, ensure set_output_embeddings is safe, though your implementation looks okay.
267
+ # The key is to avoid calling it after accelerator.prepare().
268
+ def set_output_embeddings(self, new_embeddings):
269
+ # Your current implementation using data.copy_ is good practice,
270
+ # but the best way is to not call this after prepare().
271
+ self.lm_head = new_embeddings
272
+
273
+ def forward_speech_features(
274
+ self,
275
+ speech_tensors=None,
276
+ speech_masks=None,
277
+ speech_type="audio",
278
+ return_unmask=False
279
+ ):
280
+ if speech_tensors is None:
281
+ # Use config to get vae_dim instead of non-existent self.args
282
+ vae_dim = self.config.acoustic_tokenizer_config.vae_dim
283
+ audio_features = torch.zeros(1, 1, vae_dim).to(self.get_input_embeddings().weight)
284
+ connect_features = self.model.acoustic_connector(audio_features)
285
+ return audio_features, connect_features
286
+ else:
287
+ with torch.no_grad():
288
+ if speech_type == "audio":
289
+ with torch.no_grad():
290
+ frames = self.model.acoustic_tokenizer.encode(speech_tensors.unsqueeze(1))[0][0]
291
+ audio_tokens = frames.sample(self.model.acoustic_tokenizer.std_dist_type)[0]
292
+
293
+ elif speech_type == "vae":
294
+ # Use config to get vae_dim instead of non-existent self.args
295
+ vae_dim = self.config.acoustic_tokenizer_config.vae_dim
296
+ speech_mode = speech_tensors.reshape(speech_tensors.size(0), -1, vae_dim)
297
+
298
+ # gaussian sample from the speech_mode
299
+ batch_size = speech_mode.size(0)
300
+ value = self.model.acoustic_tokenizer.fix_std / 0.8
301
+ std = torch.randn(batch_size, dtype=speech_mode.dtype, device=speech_mode.device) * value
302
+ std = std.view(-1, *[1] * (speech_mode.dim() - 1))
303
+ audio_tokens = speech_mode + std * torch.randn(speech_mode.shape).to(speech_mode)
304
+ else:
305
+ raise NotImplementedError(f"Speech type {speech_type} not implemented")
306
+
307
+ if torch.isnan(self.model.speech_scaling_factor) or torch.isnan(self.model.speech_bias_factor):
308
+ scaling_factor = 1. / audio_tokens[speech_masks].flatten().std()
309
+ bias_factor = -audio_tokens[speech_masks].flatten().mean()
310
+
311
+ # Only use distributed operations if the process group is initialized
312
+ if dist.is_available() and dist.is_initialized():
313
+ dist.all_reduce(scaling_factor, op=dist.ReduceOp.SUM)
314
+ dist.all_reduce(bias_factor, op=dist.ReduceOp.SUM)
315
+ world_size = dist.get_world_size()
316
+ self.model.speech_scaling_factor.copy_(scaling_factor / world_size)
317
+ self.model.speech_bias_factor.copy_(bias_factor / world_size)
318
+ print(f"Speech scaling factor (distributed): {self.model.speech_scaling_factor}, bias factor: {self.model.speech_bias_factor}", flush=True)
319
+ else:
320
+ # Single process case
321
+ self.model.speech_scaling_factor.copy_(scaling_factor)
322
+ self.model.speech_bias_factor.copy_(bias_factor)
323
+ print(f"Speech scaling factor (single process): {self.model.speech_scaling_factor}, bias factor: {self.model.speech_bias_factor}", flush=True)
324
+
325
+ audio_features = (audio_tokens + self.model.speech_bias_factor) * self.model.speech_scaling_factor
326
+
327
+ connect_features = self.model.acoustic_connector(audio_features)
328
+ if return_unmask:
329
+ return audio_features, connect_features
330
+ return audio_features[speech_masks], connect_features[speech_masks]
331
+
332
+ def forward(
333
+ self,
334
+ input_ids: torch.LongTensor = None,
335
+ attention_mask: Optional[torch.Tensor] = None,
336
+ position_ids: Optional[torch.LongTensor] = None,
337
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
338
+ inputs_embeds: Optional[torch.FloatTensor] = None,
339
+ labels: Optional[torch.LongTensor] = None,
340
+ use_cache: Optional[bool] = False,
341
+ output_attentions: Optional[bool] = None,
342
+ output_hidden_states: Optional[bool] = None,
343
+ return_dict: Optional[bool] = None,
344
+ cache_position: Optional[torch.LongTensor] = None,
345
+ # New arguments for speech processing and loss calculation
346
+ speech_tensors: Optional[torch.FloatTensor] = None,
347
+ speech_masks: Optional[torch.BoolTensor] = None,
348
+ speeches_loss_input: Optional[torch.FloatTensor] = None,
349
+ speech_semantic_tensors: Optional[torch.FloatTensor] = None,
350
+ acoustic_input_mask: Optional[torch.BoolTensor] = None,
351
+ acoustic_loss_mask: Optional[torch.BoolTensor] = None,
352
+ ddpm_batch_mul: int = 1,
353
+ **kwargs: Optional[Dict[str, Union[torch.Tensor, str]]],
354
+ ) -> Union[Tuple, VibeVoiceCausalLMOutputWithPast]:
355
+
356
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
357
+
358
+ x = self.get_input_embeddings()(input_ids)
359
+
360
+ semantic_speech_all_connect_features = self.model.semantic_connector(speech_semantic_tensors)
361
+ if speeches_loss_input is not None:
362
+ # only part audio need diffuse
363
+ speech_all_features, speech_all_connect_features = self.forward_speech_features(
364
+ speech_tensors=speech_tensors.type_as(x) if speech_tensors is not None else None,
365
+ speech_masks=speech_masks,
366
+ speech_type=kwargs.get("speech_type", "audio"),
367
+ return_unmask=True
368
+ )
369
+ if speech_tensors is not None:
370
+ if semantic_speech_all_connect_features is not None:
371
+ x[acoustic_input_mask] = speech_all_connect_features[speech_masks] + semantic_speech_all_connect_features[speech_masks]
372
+ else:
373
+ x[acoustic_input_mask] = speech_all_connect_features[speech_masks]
374
+ speech_features = speech_all_features[speeches_loss_input & speech_masks] # only part audio need diffuse
375
+ speech_connect_features = speech_all_connect_features[speeches_loss_input & speech_masks]
376
+ # Forward-time consistency check: selected latent count should match number of acoustic placeholders
377
+ try:
378
+ if acoustic_input_mask is not None:
379
+ assert speech_connect_features.shape[0] == int(acoustic_input_mask.sum().item()), (
380
+ f"Mismatch between selected speech connectors ({speech_connect_features.shape[0]}) and acoustic_input_mask sum ({int(acoustic_input_mask.sum().item())})"
381
+ )
382
+ except Exception:
383
+ pass
384
+ else:
385
+ speech_features, speech_connect_features = self.forward_speech_features(
386
+ speech_tensors=speech_tensors.type_as(x) if speech_tensors is not None else None,
387
+ speech_masks=speech_masks,
388
+ speech_type=kwargs.get("speech_type", "audio"),
389
+ )
390
+ if speech_tensors is not None:
391
+ x[acoustic_input_mask] = speech_connect_features
392
+
393
+ outputs = self.model(
394
+ input_ids=None,
395
+ attention_mask=attention_mask,
396
+ position_ids=position_ids,
397
+ past_key_values=past_key_values,
398
+ inputs_embeds=x,
399
+ use_cache=use_cache,
400
+ output_attentions=output_attentions,
401
+ output_hidden_states=False,
402
+ return_dict=return_dict,
403
+ cache_position=cache_position,
404
+ )
405
+
406
+ hidden_states = outputs.last_hidden_state
407
+ logits = self.lm_head(hidden_states)
408
+ # logits = logits.float()
409
+
410
+ loss = None
411
+ if labels is not None:
412
+ # The custom CE loss with masking is calculated in the training script.
413
+ # We leave the standard loss calculation here as None.
414
+ pass
415
+
416
+ # --- Diffusion Loss Calculation ---
417
+ diffusion_loss = None
418
+ # This block is executed only if we are in a context that involves speech.
419
+ if speech_tensors is not None and acoustic_loss_mask.sum().item() > 0:
420
+ # Build conditioning mask from positions whose NEXT token is a speech latent (shift left by 1)
421
+ cond_mask = torch.zeros_like(acoustic_loss_mask, dtype=torch.bool)
422
+ cond_mask[:, :-1] = acoustic_loss_mask[:, 1:]
423
+ cond_mask[:, 0] = False
424
+ condition_features = hidden_states[cond_mask]
425
+
426
+ speech_len, latent_size = speech_features.shape
427
+ # Sanity check: ensure 1:1 alignment between selected conditions and latents
428
+ try:
429
+ assert condition_features.shape[0] == speech_len, (
430
+ f"Mismatch: condition_features={condition_features.shape[0]} vs speech_features={speech_len}"
431
+ )
432
+ except Exception:
433
+ pass
434
+
435
+ noise = torch.randn(
436
+ (speech_len * ddpm_batch_mul, latent_size),
437
+ device=hidden_states.device,
438
+ dtype=hidden_states.dtype
439
+ )
440
+
441
+ timesteps = torch.multinomial(
442
+ torch.ones(self.config.diffusion_head_config.ddpm_num_steps),
443
+ speech_len * ddpm_batch_mul,
444
+ replacement=True,
445
+ ).to(hidden_states.device)
446
+
447
+ speech_features_repeated = speech_features.repeat_interleave(ddpm_batch_mul, dim=0)
448
+ condition_features_repeated = condition_features.repeat_interleave(ddpm_batch_mul, dim=0)
449
+
450
+ noisy_speech_features = self.model.noise_scheduler.add_noise(
451
+ speech_features_repeated, noise, timesteps
452
+ )
453
+
454
+ model_output = self.model.prediction_head(
455
+ noisy_speech_features,
456
+ timesteps.type_as(x),
457
+ condition_features_repeated
458
+ )
459
+
460
+ prediction_type = self.config.diffusion_head_config.prediction_type
461
+ if prediction_type == "epsilon":
462
+ target_for_loss = noise
463
+ elif prediction_type == "v_prediction":
464
+ target_for_loss = self.model.noise_scheduler.get_velocity(
465
+ speech_features_repeated, noise, timesteps
466
+ )
467
+ else:
468
+ raise NotImplementedError(f"Prediction type {prediction_type} not implemented")
469
+
470
+ diffusion_loss = F.mse_loss(model_output.float(), target_for_loss.float(), reduction='sum')
471
+ if latent_size > 0 and ddpm_batch_mul > 0:
472
+ # Normalize by latent dim, number of sampled diffusion steps per latent, and number of speech tokens
473
+ diffusion_loss = diffusion_loss / latent_size / ddpm_batch_mul / max(speech_len, 1)
474
+ else:
475
+ diffusion_loss = torch.tensor(0.0, device=diffusion_loss.device)
476
+
477
+ else:
478
+ # Dummy loss for DDP to work when there are no speech samples in a batch,
479
+ # but we are in a speech context.
480
+ diffusion_loss = sum(p.sum() for p in self.model.prediction_head.parameters()) * 0.0
481
+ diffusion_loss += sum(p.sum() for p in self.model.acoustic_connector.parameters()) * 0.0
482
+ diffusion_loss += sum(p.sum() for p in self.model.semantic_connector.parameters()) * 0.0
483
+ # --- End Diffusion Loss Calculation ---
484
+
485
+ if not return_dict:
486
+ output = (logits, speech_len) + outputs.to_tuple()[1:]
487
+ return (loss, diffusion_loss) + output
488
+
489
+ return VibeVoiceCausalLMOutputWithPast(
490
+ loss=loss,
491
+ diffusion_loss=diffusion_loss,
492
+ speech_token_num=speech_len if speech_tensors is not None else 0,
493
+ logits=logits,
494
+ past_key_values=outputs.past_key_values,
495
+ hidden_states=outputs.hidden_states,
496
+ attentions=outputs.attentions,
497
+ )
498
+
499
+ AutoModel.register(VibeVoiceConfig, VibeVoiceModel)
500
+ AutoModelForCausalLM.register(VibeVoiceConfig, VibeVoiceForConditionalGeneration)
501
+
502
+ __all__ = [
503
+ "VibeVoiceModel",
504
+ "VibeVoicePreTrainedModel",
505
+ "VibeVoiceForConditionalGeneration",
506
+ "VibeVoiceCausalLMOutputWithPast",
507
+ "VibeVoiceGenerationOutput",
508
+ ]
VibeVoice-tpu/src/vibevoice/modular/modeling_vibevoice_inference.py ADDED
@@ -0,0 +1,729 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Dict, List, Optional, Tuple, Union, Callable
3
+ from tqdm import tqdm
4
+ import torch
5
+ import torch.nn as nn
6
+
7
+ from transformers.models.auto import AutoModel, AutoModelForCausalLM
8
+
9
+ from transformers.generation import GenerationMixin, GenerationConfig, LogitsProcessor, LogitsProcessorList, StoppingCriteriaList
10
+ from transformers.modeling_outputs import BaseModelOutputWithPast, ModelOutput
11
+ from transformers import modeling_utils
12
+ from transformers.modeling_utils import PreTrainedModel
13
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
14
+ from transformers.utils import logging
15
+
16
+
17
+ # from .modular_vibevoice_tokenizer import VibeVoiceTokenizerStreamingCache, VibeVoiceAcousticTokenizerModel, VibeVoiceSemanticTokenizerModel
18
+ from .modular_vibevoice_tokenizer import VibeVoiceTokenizerStreamingCache, VibeVoiceTokenizerEncoderOutput
19
+ from .modular_vibevoice_diffusion_head import VibeVoiceDiffusionHead
20
+ from vibevoice.schedule.dpm_solver import DPMSolverMultistepScheduler
21
+
22
+ from .configuration_vibevoice import VibeVoiceConfig
23
+
24
+ from .modular_vibevoice_text_tokenizer import VibeVoiceTextTokenizer, VibeVoiceTextTokenizerFast
25
+
26
+ from .modeling_vibevoice import VibeVoiceModel, VibeVoicePreTrainedModel
27
+ from .streamer import AudioStreamer, AsyncAudioStreamer
28
+
29
+ # DynamicCache compatibility shim (transformers >= 4.43)
30
+ try:
31
+ from transformers.cache_utils import DynamicCache
32
+ _HAS_DYNAMIC_CACHE = True
33
+ except ImportError:
34
+ _HAS_DYNAMIC_CACHE = False
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+ if not hasattr(modeling_utils, "ALL_PARALLEL_STYLES") or modeling_utils.ALL_PARALLEL_STYLES is None:
39
+ modeling_utils.ALL_PARALLEL_STYLES = ["tp", "none", "colwise", "rowwise"]
40
+
41
+ @dataclass
42
+ class VibeVoiceCausalLMOutputWithPast(BaseModelOutputWithPast):
43
+ logits: Optional[torch.FloatTensor] = None
44
+
45
+ @dataclass
46
+ class VibeVoiceGenerationOutput(ModelOutput):
47
+ """
48
+ Output type for VibeVoice generation.
49
+
50
+ Args:
51
+ sequences (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
52
+ The generated sequences.
53
+ speech_outputs (`List[torch.FloatTensor]`, *optional*):
54
+ List of generated speech waveforms or latents for each speech segment.
55
+ """
56
+ sequences: torch.LongTensor = None
57
+ speech_outputs: Optional[List[torch.FloatTensor]] = None
58
+ reach_max_step_sample: Optional[torch.BoolTensor] = None
59
+
60
+ class VibeVoiceTokenConstraintProcessor(LogitsProcessor):
61
+ """Constrains token generation to only valid tokens during speech generation."""
62
+
63
+ def __init__(self, valid_token_ids: List[int], device: torch.device = None):
64
+ self.valid_token_ids = torch.tensor(valid_token_ids, dtype=torch.long, device=device)
65
+
66
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
67
+ # Create a mask for valid tokens
68
+ mask = torch.full_like(scores, float('-inf'))
69
+ mask[:, self.valid_token_ids] = 0
70
+
71
+ # Apply mask to scores
72
+ scores = scores + mask
73
+ return scores
74
+
75
+ class VibeVoiceForConditionalGenerationInference(VibeVoicePreTrainedModel, GenerationMixin):
76
+ _tied_weights_keys = ["lm_head.weight"]
77
+ _tp_plan = {"lm_head": "colwise_rep"}
78
+
79
+ def __init__(self, config):
80
+ super().__init__(config)
81
+
82
+ # Initialize the base model
83
+ self.model = VibeVoiceModel(config)
84
+
85
+ # LM head for text generation
86
+ self.lm_head = nn.Linear(config.decoder_config.hidden_size, config.decoder_config.vocab_size, bias=False)
87
+
88
+ # inference configuration
89
+ self.ddpm_inference_steps = config.diffusion_head_config.ddpm_num_inference_steps
90
+
91
+ # Initialize weights and apply final processing
92
+ self.post_init()
93
+
94
+ @property
95
+ def noise_scheduler(self):
96
+ return self.model.noise_scheduler
97
+
98
+ @property
99
+ def prediction_head(self):
100
+ return self.model.prediction_head
101
+
102
+ @property
103
+ def speech_scaling_factor(self):
104
+ return self.model.speech_scaling_factor
105
+
106
+ @property
107
+ def speech_bias_factor(self):
108
+ return self.model.speech_bias_factor
109
+
110
+ @property
111
+ def acoustic_tokenizer(self):
112
+ return self.model.acoustic_tokenizer
113
+
114
+ @property
115
+ def semantic_tokenizer(self):
116
+ return self.model.semantic_tokenizer
117
+
118
+ @property
119
+ def acoustic_connector(self):
120
+ return self.model.acoustic_connector
121
+
122
+ @property
123
+ def semantic_connector(self):
124
+ return self.model.semantic_connector
125
+
126
+ def tie_weights(self):
127
+ """
128
+ Tie the weights between the input embeddings and the output embeddings.
129
+ """
130
+ # Tie lm_head.weight to language_model.embed_tokens.weight
131
+ if not getattr(self.config, 'tie_word_embeddings', False):
132
+ return
133
+
134
+ if hasattr(self, 'lm_head') and hasattr(self.model.language_model, 'embed_tokens'):
135
+ self.lm_head.weight = self.model.language_model.embed_tokens.weight
136
+
137
+ def get_input_embeddings(self):
138
+ return self.model.get_input_embeddings()
139
+
140
+ def set_input_embeddings(self, value):
141
+ self.model.set_input_embeddings(value)
142
+
143
+ def get_output_embeddings(self):
144
+ return self.lm_head
145
+
146
+ def set_output_embeddings(self, new_embeddings):
147
+ self.lm_head = new_embeddings
148
+
149
+ def set_speech_tokenizers(self, acoustic_tokenizer=None, semantic_tokenizer=None):
150
+ """Set the speech tokenizers used for encoding and decoding speech."""
151
+ self.model.set_speech_tokenizers(acoustic_tokenizer, semantic_tokenizer)
152
+
153
+ def set_ddpm_inference_steps(self, num_steps=None):
154
+ self.ddpm_inference_steps = num_steps or self.config.diffusion_head_config.ddpm_num_inference_steps
155
+
156
+ def _process_speech_inputs(self, speech_tensors, speech_masks, speech_type="audio"):
157
+ """Process speech inputs through tokenizers and connectors."""
158
+ with torch.no_grad():
159
+ if speech_type == "audio":
160
+ # Encode audio to acoustic latents
161
+ encoder_output = self.model.acoustic_tokenizer.encode(speech_tensors.unsqueeze(1))
162
+ acoustic_latents = encoder_output.sample(dist_type=self.model.acoustic_tokenizer.std_dist_type)[0]
163
+
164
+ # Apply scaling and bias
165
+ acoustic_features = (acoustic_latents + self.model.speech_bias_factor.to(acoustic_latents.device)) * self.model.speech_scaling_factor.to(acoustic_latents.device)
166
+
167
+ # Connect to language model space
168
+ acoustic_connected = self.model.acoustic_connector(acoustic_features)[speech_masks.cpu()]
169
+
170
+ return acoustic_features, acoustic_connected
171
+ elif speech_type == "pt":
172
+ encoder_output = VibeVoiceTokenizerEncoderOutput(mean=speech_tensors, std=self.acoustic_tokenizer.config.fix_std)
173
+ acoustic_latents = encoder_output.sample(dist_type=self.model.acoustic_tokenizer.std_dist_type)[0]
174
+
175
+ # Apply scaling and bias
176
+ acoustic_features = (acoustic_latents + self.model.speech_bias_factor.to(acoustic_latents.device)) * self.model.speech_scaling_factor.to(acoustic_latents.device)
177
+
178
+ # Connect to language model space
179
+ acoustic_connected = self.model.acoustic_connector(acoustic_features)[speech_masks.cpu()]
180
+
181
+ return acoustic_features, acoustic_connected
182
+ else:
183
+ raise NotImplementedError(f"Speech type {speech_type} not implemented")
184
+
185
+ # @can_return_tuple
186
+ def forward(
187
+ self,
188
+ input_ids: torch.LongTensor = None,
189
+ attention_mask: Optional[torch.Tensor] = None,
190
+ position_ids: Optional[torch.LongTensor] = None,
191
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
192
+ inputs_embeds: Optional[torch.FloatTensor] = None,
193
+ labels: Optional[torch.LongTensor] = None,
194
+ use_cache: Optional[bool] = None,
195
+ output_attentions: Optional[bool] = None,
196
+ output_hidden_states: Optional[bool] = None,
197
+ return_dict: Optional[bool] = None,
198
+ cache_position: Optional[torch.LongTensor] = None,
199
+ speech_tensors: Optional[torch.FloatTensor] = None,
200
+ speech_masks: Optional[torch.BoolTensor] = None,
201
+ speech_input_mask: Optional[torch.BoolTensor] = None,
202
+ logits_to_keep: Union[int, slice] = 0,
203
+ **kwargs,
204
+ ) -> Union[Tuple, VibeVoiceCausalLMOutputWithPast]:
205
+ """
206
+ Args:
207
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
208
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
209
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
210
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
211
+ speech_tensors (`torch.FloatTensor`, *optional*):
212
+ Input speech waveforms for voice cloning or speech understanding.
213
+ speech_masks (`torch.BoolTensor`, *optional*):
214
+ Masks indicating valid speech frames.
215
+ speech_input_mask (`torch.BoolTensor`, *optional*):
216
+ Positions in the input sequence where speech embeddings should be inserted.
217
+
218
+ Returns:
219
+ `VibeVoiceCausalLMOutputWithPast` or tuple
220
+ """
221
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
222
+
223
+ # Get embeddings
224
+ if inputs_embeds is None:
225
+ inputs_embeds = self.model.get_input_embeddings()(input_ids)
226
+
227
+ # Process speech inputs if provided
228
+ if speech_tensors is not None and speech_masks is not None:
229
+ acoustic_features, speech_embeds = self._process_speech_inputs(speech_tensors.to(self.dtype), speech_masks)
230
+ if speech_input_mask is not None:
231
+ inputs_embeds[speech_input_mask] = speech_embeds
232
+
233
+ outputs = self.model(
234
+ inputs_embeds=inputs_embeds,
235
+ attention_mask=attention_mask,
236
+ position_ids=position_ids,
237
+ past_key_values=past_key_values,
238
+ use_cache=use_cache,
239
+ output_attentions=output_attentions,
240
+ output_hidden_states=output_hidden_states,
241
+ return_dict=return_dict,
242
+ cache_position=cache_position,
243
+ **kwargs,
244
+ )
245
+
246
+ hidden_states = outputs[0] if not return_dict else outputs.last_hidden_state
247
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
248
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
249
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
250
+
251
+ if labels is not None:
252
+ raise NotImplementedError("Loss computation is not implemented in this version.")
253
+
254
+ return VibeVoiceCausalLMOutputWithPast(
255
+ logits=logits,
256
+ past_key_values=outputs.past_key_values,
257
+ last_hidden_state=hidden_states,
258
+ attentions=outputs.attentions,
259
+ )
260
+
261
+ def _build_generate_config_model_kwargs(self, generation_config, inputs, tokenizer, return_processors=False, **kwargs):
262
+ if generation_config is None:
263
+ generation_config = GenerationConfig(
264
+ bos_token_id=tokenizer.bos_token_id,
265
+ eos_token_id=tokenizer.eos_token_id,
266
+ pad_token_id = tokenizer.pad_token_id
267
+ )
268
+ else:
269
+ generation_config = GenerationConfig(
270
+ **generation_config,
271
+ bos_token_id=tokenizer.bos_token_id,
272
+ eos_token_id=tokenizer.eos_token_id,
273
+ pad_token_id = tokenizer.pad_token_id
274
+ )
275
+
276
+ generation_config, model_kwargs = self._prepare_generation_config(
277
+ generation_config,
278
+ True,
279
+ speech_start_id=tokenizer.speech_start_id,
280
+ speech_end_id=tokenizer.speech_end_id,
281
+ speech_diffusion_id=tokenizer.speech_diffusion_id,
282
+ **kwargs
283
+ )
284
+ generation_config.speech_start_id = tokenizer.speech_start_id
285
+ generation_config.speech_end_id = tokenizer.speech_end_id
286
+ generation_config.speech_diffusion_id = tokenizer.speech_diffusion_id
287
+
288
+ inputs_tensor, model_input_name, model_kwargs = self._prepare_model_inputs(inputs, generation_config.bos_token_id, model_kwargs)
289
+ batch_size = inputs_tensor.shape[0]
290
+ device = self.device
291
+
292
+ self._prepare_special_tokens(generation_config, True, device=device)
293
+ generation_config.use_cache = True
294
+ model_kwargs["use_cache"] = generation_config.use_cache
295
+ input_ids = inputs_tensor.to(self.device)
296
+
297
+ input_ids_length = input_ids.shape[1]
298
+ has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
299
+ has_default_min_length = kwargs.get("min_length") is None and generation_config.min_length is not None
300
+ generation_config = self._prepare_generated_length(
301
+ generation_config=generation_config,
302
+ has_default_max_length=has_default_max_length,
303
+ has_default_min_length=has_default_min_length,
304
+ model_input_name=model_input_name,
305
+ inputs_tensor=inputs_tensor,
306
+ input_ids_length=input_ids_length,
307
+ )
308
+
309
+ max_cache_length = generation_config.max_length - 1
310
+ self._prepare_cache_for_generation(generation_config, model_kwargs, None, batch_size, max_cache_length, device)
311
+ model_kwargs['cache_position'] = torch.arange(input_ids_length, device=device, dtype=torch.long)
312
+ for k, v in model_kwargs.items():
313
+ if isinstance(v, torch.Tensor):
314
+ model_kwargs[k] = v.to(device=device)
315
+
316
+ if return_processors:
317
+ logits_processor = self._get_logits_processor(
318
+ generation_config=generation_config,
319
+ input_ids_seq_length=input_ids_length,
320
+ encoder_input_ids=inputs_tensor,
321
+ prefix_allowed_tokens_fn=None,
322
+ logits_processor=LogitsProcessorList(),
323
+ device=inputs_tensor.device,
324
+ model_kwargs=model_kwargs,
325
+ )
326
+
327
+ stopping_criteria = self._get_stopping_criteria(generation_config=generation_config, stopping_criteria=StoppingCriteriaList())
328
+
329
+ return generation_config, model_kwargs, input_ids, logits_processor, stopping_criteria
330
+ else:
331
+ return generation_config, model_kwargs, input_ids
332
+
333
+ @torch.no_grad()
334
+ def generate(
335
+ self,
336
+ inputs: Optional[torch.Tensor] = None,
337
+ generation_config: Optional[GenerationConfig] = None,
338
+ logits_processor: Optional[LogitsProcessorList] = None,
339
+ stopping_criteria: Optional[StoppingCriteriaList] = None,
340
+ prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
341
+ synced_gpus: Optional[bool] = None,
342
+ assistant_model: Optional["PreTrainedModel"] = None,
343
+ audio_streamer: Optional[Union[AudioStreamer, AsyncAudioStreamer]] = None,
344
+ negative_prompt_ids: Optional[torch.Tensor] = None,
345
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
346
+ speech_tensors: Optional[torch.FloatTensor] = None,
347
+ speech_masks: Optional[torch.BoolTensor] = None,
348
+ speech_input_mask: Optional[torch.BoolTensor] = None,
349
+ return_speech: bool = True,
350
+ cfg_scale: float = 1.0,
351
+ stop_check_fn: Optional[Callable[[], bool]] = None,
352
+ **kwargs,
353
+ ) -> Union[torch.LongTensor, VibeVoiceGenerationOutput]:
354
+ """
355
+ Generates sequences of token ids and optionally speech outputs.
356
+
357
+ Args:
358
+ All standard generation arguments from GenerationMixin
359
+ negative_prompt_ids: Negative prompt for CFG in speech generation
360
+ negative_prompt_attention_mask: Attention mask for negative prompt
361
+ speech_tensors: Input speech for voice cloning
362
+ speech_masks: Masks for speech tensors
363
+ speech_input_mask: Positions to insert speech embeddings
364
+ return_speech: Whether to decode and return speech outputs
365
+ cfg_scale: CFG scale for speech generation
366
+ stop_check_fn: Optional callable that returns True if generation should stop
367
+
368
+ Returns:
369
+ Generated token sequences and optionally speech outputs
370
+ """
371
+ # 1. Handle `generation_config` and kwargs that might update it, and validate the `.generate()` call
372
+ tokenizer = kwargs.pop("tokenizer", None) # Pull this out first, we only use it for stopping criteria
373
+ parsed_scripts = kwargs.pop("parsed_scripts", None)
374
+ all_speakers_list = kwargs.pop("all_speakers_list", None)
375
+ max_length_times = kwargs.pop("max_length_times", 2)
376
+
377
+ if kwargs.get('max_new_tokens', None) is None:
378
+ kwargs['max_new_tokens'] = self.config.decoder_config.max_position_embeddings - kwargs['input_ids'].shape[-1]
379
+
380
+ generation_config, model_kwargs, input_ids, logits_processor, stopping_criteria = self._build_generate_config_model_kwargs(
381
+ generation_config, inputs, tokenizer, return_processors=True, **kwargs
382
+ )
383
+
384
+ negative_kwargs = {
385
+ 'input_ids': torch.full((kwargs['input_ids'].shape[0], 1), tokenizer.speech_start_id, dtype=torch.long, device=kwargs['input_ids'].device),
386
+ 'attention_mask': torch.ones((kwargs['input_ids'].shape[0], 1), dtype=torch.long, device=kwargs['input_ids'].device),
387
+ 'max_new_tokens': kwargs.get('max_new_tokens', 100)
388
+ }
389
+ negative_generation_config, negative_model_kwargs, negative_input_ids = self._build_generate_config_model_kwargs(
390
+ None, None, tokenizer, return_processors=False, **negative_kwargs
391
+ )
392
+
393
+ acoustic_cache = VibeVoiceTokenizerStreamingCache()
394
+ semantic_cache = VibeVoiceTokenizerStreamingCache()
395
+
396
+ # Device resolution for multi-GPU compatibility
397
+ # acoustic_tokenizer and semantic_tokenizer may live on different GPUs
398
+ acoustic_device = next(self.model.acoustic_tokenizer.parameters()).device
399
+ semantic_device = next(self.model.semantic_tokenizer.parameters()).device
400
+ acoustic_connect_device = next(self.model.acoustic_connector.parameters()).device
401
+ semantic_connect_device = next(self.model.semantic_connector.parameters()).device
402
+
403
+ batch_size = input_ids.shape[0]
404
+ device = input_ids.device
405
+ finished_tags = torch.zeros(batch_size, dtype=torch.bool, device=device)
406
+ correct_cnt = torch.zeros(batch_size, dtype=torch.long, device=device)
407
+ is_prefill = True
408
+ inputs_embeds = None
409
+ verbose = kwargs.get("verbose", False)
410
+
411
+ # Initialize audio chunks storage for each sample
412
+ audio_chunks = [[] for _ in range(batch_size)]
413
+
414
+ initial_length = input_ids.shape[-1]
415
+ initial_length_per_sample = model_kwargs['attention_mask'].sum(dim=-1)
416
+
417
+ # Define all valid tokens that can be generated
418
+ valid_tokens = [
419
+ generation_config.speech_start_id,
420
+ generation_config.speech_end_id,
421
+ generation_config.speech_diffusion_id,
422
+ generation_config.eos_token_id
423
+ ]
424
+ # Add bos_token_id if it exists
425
+ if hasattr(generation_config, 'bos_token_id') and generation_config.bos_token_id is not None:
426
+ valid_tokens.append(generation_config.bos_token_id)
427
+
428
+ # Add custom processor to constrain token generation
429
+ token_constraint_processor = VibeVoiceTokenConstraintProcessor(valid_tokens, device=device)
430
+ if logits_processor is None:
431
+ logits_processor = LogitsProcessorList()
432
+ logits_processor.append(token_constraint_processor)
433
+
434
+ max_steps = min(generation_config.max_length - initial_length, int(max_length_times * initial_length))
435
+ max_step_per_sample = torch.minimum(generation_config.max_length - initial_length_per_sample, (max_length_times * initial_length_per_sample).long())
436
+ reach_max_step_sample = torch.zeros(batch_size, dtype=torch.bool, device=device)
437
+
438
+ # Create progress iterator if verbose
439
+ if kwargs.get("show_progress_bar", True):
440
+ progress_bar = tqdm(range(max_steps), desc="Generating", leave=False)
441
+ else:
442
+ progress_bar = range(max_steps)
443
+
444
+ for step in progress_bar:
445
+ # Check for external stop signal
446
+ if stop_check_fn is not None and stop_check_fn():
447
+ if verbose:
448
+ print(f"Generation stopped externally at step {step + 1}")
449
+ # End the audio streamer if it exists
450
+ if audio_streamer is not None:
451
+ audio_streamer.end()
452
+ break
453
+
454
+ # Check if audio_streamer has been ended (stopped externally)
455
+ if audio_streamer is not None and hasattr(audio_streamer, 'finished_flags'):
456
+ if any(audio_streamer.finished_flags):
457
+ if verbose:
458
+ print(f"Audio generation stopped externally at step {step + 1}")
459
+ break
460
+
461
+ if finished_tags.all():
462
+ if hasattr(progress_bar, 'set_description'):
463
+ progress_bar.set_description("Generation complete")
464
+ break
465
+
466
+ if input_ids.shape[-1] >= generation_config.max_length:
467
+ print(f"Reached maximum generation length {generation_config.max_length}, stopped it.")
468
+ reached_samples = torch.arange(batch_size, device=device)[~finished_tags]
469
+ if reached_samples.numel() > 0:
470
+ reach_max_step_sample[reached_samples] = True
471
+ break
472
+
473
+ # Update progress bar description with active samples
474
+ if hasattr(progress_bar, 'set_description'):
475
+ active_samples = (~finished_tags).sum().item()
476
+ progress_bar.set_description(f"Generating (active: {active_samples}/{batch_size})")
477
+
478
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
479
+ if is_prefill:
480
+ # we process the speech inputs only during the first generation step
481
+ prefill_inputs = {
482
+ "speech_tensors": speech_tensors.to(device=device),
483
+ "speech_masks": speech_masks.to(device),
484
+ "speech_input_mask": speech_input_mask.to(device),
485
+ }
486
+ is_prefill = False
487
+ else:
488
+ _ = model_inputs.pop('inputs_embeds', None)
489
+ prefill_inputs = {'inputs_embeds': inputs_embeds}
490
+
491
+ # Forward pass through the model
492
+ outputs = self(
493
+ **model_inputs, **prefill_inputs, logits_to_keep=1, return_dict=True, output_attentions=False, output_hidden_states=False,
494
+ )
495
+ model_kwargs = self._update_model_kwargs_for_generation(
496
+ outputs, model_kwargs, is_encoder_decoder=False,
497
+ )
498
+
499
+ # Get logits and apply logits processor
500
+ next_token_logits = outputs.logits[:, -1, :].to(copy=True, dtype=torch.float32, device=input_ids.device)
501
+ # next_token_logits = outputs.logits[:, -1, :].to(copy=True, device=input_ids.device)
502
+ next_token_scores = logits_processor(input_ids, next_token_logits)
503
+
504
+ # token selection
505
+ if generation_config.do_sample:
506
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
507
+ # TODO (joao): this OP throws "skipping cudagraphs due to ['incompatible ops']", find solution
508
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
509
+ else:
510
+ next_tokens = torch.argmax(next_token_scores, dim=-1)
511
+
512
+ next_tokens[finished_tags] = generation_config.eos_token_id
513
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
514
+
515
+ if not kwargs.get('refresh_negative', True):
516
+ negative_model_inputs = self.prepare_inputs_for_generation(negative_input_ids, **negative_model_kwargs)
517
+ # Forward negative pass through the model
518
+ if negative_model_inputs['inputs_embeds'] is None and inputs_embeds is not None:
519
+ negative_model_inputs['inputs_embeds'] = inputs_embeds
520
+ negative_model_inputs['input_ids'] = None
521
+
522
+ negative_outputs = self(
523
+ **negative_model_inputs, logits_to_keep=0, return_dict=True, output_attentions=False, output_hidden_states=False,
524
+ )
525
+ negative_model_kwargs = self._update_model_kwargs_for_generation(
526
+ negative_outputs, negative_model_kwargs, is_encoder_decoder=False,
527
+ )
528
+ negative_input_ids = torch.cat([negative_input_ids, next_tokens[:, None]], dim=-1)
529
+
530
+ # reached end of generation
531
+ if (next_tokens == generation_config.eos_token_id).any():
532
+ eos_indices = (next_tokens == generation_config.eos_token_id).nonzero(as_tuple=False).squeeze(1)
533
+ # Only print for samples that are newly finished (not already marked as finished)
534
+ new_eos_indices = eos_indices[~finished_tags[eos_indices]]
535
+ if new_eos_indices.numel() > 0:
536
+ finished_tags[new_eos_indices] = True
537
+ if verbose:
538
+ print(f"Samples {new_eos_indices.tolist()} reached EOS token at step {step + 1}.", flush=True)
539
+ if audio_streamer is not None:
540
+ audio_streamer.end(new_eos_indices)
541
+
542
+ # Check if any sample reached its maximum generation length
543
+ max_length_reached = step >= max_step_per_sample
544
+ new_max_length_indices = torch.nonzero(max_length_reached & ~finished_tags, as_tuple=False).squeeze(1)
545
+ if new_max_length_indices.numel() > 0:
546
+ finished_tags[new_max_length_indices] = True
547
+ reach_max_step_sample[new_max_length_indices] = True
548
+ if verbose:
549
+ print(f"Samples {new_max_length_indices.tolist()} reached max generation length at step {step + 1}.", flush=True)
550
+ if audio_streamer is not None:
551
+ audio_streamer.end(new_max_length_indices)
552
+
553
+ # speech_end
554
+ diffusion_end_indices = (next_tokens == generation_config.speech_end_id).nonzero(as_tuple=False).squeeze(1)
555
+ if diffusion_end_indices.numel() > 0:
556
+ # Clear tokenizer caches for samples that reached speech end
557
+ acoustic_cache.set_to_zero(diffusion_end_indices)
558
+ semantic_cache.set_to_zero(diffusion_end_indices)
559
+
560
+ # speech_begin
561
+ diffusion_start_indices = torch.arange(batch_size, device=device)[~finished_tags & (next_tokens == generation_config.speech_start_id)]
562
+ if diffusion_start_indices.numel() > 0 and kwargs.get('refresh_negative', True):
563
+ # update attention mask
564
+ for i, sample_idx in enumerate(diffusion_start_indices.tolist()):
565
+ negative_model_kwargs['attention_mask'][sample_idx, :] = 0
566
+ negative_model_kwargs['attention_mask'][sample_idx, -1] = 1
567
+ # update past key values
568
+ for layer_idx, (k_cache, v_cache) in enumerate(zip(negative_model_kwargs['past_key_values'].key_cache,
569
+ negative_model_kwargs['past_key_values'].value_cache)):
570
+ # Process each non-diffusion sample
571
+ for sample_idx in diffusion_start_indices.tolist():
572
+ # Shift cache for this sample
573
+ k_cache[sample_idx, :, -1, :] = k_cache[sample_idx, :, 0, :].clone()
574
+ v_cache[sample_idx, :, -1, :] = v_cache[sample_idx, :, 0, :].clone()
575
+ # update negative_input_ids
576
+ for sample_idx in diffusion_start_indices.tolist():
577
+ negative_input_ids[sample_idx, -1] = generation_config.speech_start_id
578
+
579
+ # Prepare inputs_embeds for next iteration
580
+ # Initialize with default embeddings for all tokens
581
+ next_inputs_embeds = self.model.get_input_embeddings()(next_tokens).unsqueeze(1) # [batch_size, 1, hidden_size]
582
+
583
+ # forward diffusion
584
+ # Diffusion indices are those that are not finished and not special tokens
585
+ diffusion_indices = torch.arange(batch_size, device=device)[~finished_tags & (next_tokens == generation_config.speech_diffusion_id)]
586
+
587
+ if diffusion_indices.numel() > 0:
588
+ if kwargs.get('refresh_negative', True):
589
+ negative_model_inputs = self.prepare_inputs_for_generation(negative_input_ids, **negative_model_kwargs)
590
+ # Forward negative pass through the model
591
+ if negative_model_inputs['inputs_embeds'] is None and inputs_embeds is not None:
592
+ negative_model_inputs['inputs_embeds'] = inputs_embeds
593
+ negative_model_inputs['input_ids'] = None
594
+
595
+ negative_outputs = self(
596
+ **negative_model_inputs, logits_to_keep=0, return_dict=True, output_attentions=False, output_hidden_states=False,
597
+ )
598
+ negative_model_kwargs = self._update_model_kwargs_for_generation(
599
+ negative_outputs, negative_model_kwargs, is_encoder_decoder=False,
600
+ )
601
+ negative_input_ids = torch.cat([negative_input_ids, next_tokens[:, None]], dim=-1)
602
+ # correct the non-diffusion indices
603
+ # we forward all samples' negative outputs even if
604
+ # they are not in diffusion mode to keep the cache consistent
605
+ # So we need to correct the kv cache of non-diffusion samples
606
+ non_diffusion_mask = ~finished_tags & (next_tokens != generation_config.speech_diffusion_id)
607
+ if non_diffusion_mask.any():
608
+ non_diffusion_indices = torch.arange(batch_size, device=device)[non_diffusion_mask]
609
+ start_indices = correct_cnt[non_diffusion_indices]
610
+
611
+ # 1. Update attention_mask - need to handle each sample separately
612
+ seq_len = negative_model_kwargs['attention_mask'].shape[1]
613
+ for i, (sample_idx, start_idx) in enumerate(zip(non_diffusion_indices.tolist(), start_indices.tolist())):
614
+ # Shift the attention mask for this sample
615
+ if start_idx + 1 < seq_len - 1:
616
+ negative_model_kwargs['attention_mask'][sample_idx, start_idx+1:] = \
617
+ negative_model_kwargs['attention_mask'][sample_idx, start_idx:-1].clone()
618
+ negative_model_kwargs['attention_mask'][sample_idx, start_idx] = 0
619
+
620
+ # 2. Update past_key_values
621
+ for layer_idx, (k_cache, v_cache) in enumerate(zip(negative_model_kwargs['past_key_values'].key_cache,
622
+ negative_model_kwargs['past_key_values'].value_cache)):
623
+ # Process each non-diffusion sample
624
+ for sample_idx, start_idx in zip(non_diffusion_indices.tolist(), start_indices.tolist()):
625
+ if start_idx + 1 < k_cache.shape[2] - 1:
626
+ # Shift cache for this sample
627
+ k_cache[sample_idx, :, start_idx+1:, :] = k_cache[sample_idx, :, start_idx:-1, :].clone()
628
+ v_cache[sample_idx, :, start_idx+1:, :] = v_cache[sample_idx, :, start_idx:-1, :].clone()
629
+
630
+ # 3. Update negative_input_ids
631
+ for sample_idx, start_idx in zip(non_diffusion_indices.tolist(), start_indices.tolist()):
632
+ if start_idx + 1 < negative_input_ids.shape[1] - 1:
633
+ negative_input_ids[sample_idx, start_idx+1:] = \
634
+ negative_input_ids[sample_idx, start_idx:-1].clone()
635
+
636
+ correct_cnt[non_diffusion_indices] += 1
637
+
638
+ positive_condition = outputs.last_hidden_state[diffusion_indices, -1, :]
639
+ negative_condition = negative_outputs.last_hidden_state[diffusion_indices, -1, :]
640
+
641
+ speech_latent = self.sample_speech_tokens(
642
+ positive_condition,
643
+ negative_condition,
644
+ cfg_scale=cfg_scale,
645
+ ).unsqueeze(1)
646
+
647
+ # Decode acoustic latent to audio using acoustic streaming cache
648
+ scaled_latent = speech_latent / self.model.speech_scaling_factor.to(speech_latent.device) - self.model.speech_bias_factor.to(speech_latent.device)
649
+ audio_chunk = self.model.acoustic_tokenizer.decode(
650
+ scaled_latent.to(self.model.acoustic_tokenizer.device),
651
+ cache=acoustic_cache, # Use acoustic-specific cache
652
+ sample_indices=diffusion_indices.to(self.model.acoustic_tokenizer.device),
653
+ use_cache=True,
654
+ debug=False
655
+ )
656
+
657
+ # Store audio chunks for each sample
658
+ for i, sample_idx in enumerate(diffusion_indices):
659
+ idx = sample_idx.item()
660
+ # Only append audio chunk if the sample is not finished
661
+ if not finished_tags[idx]:
662
+ audio_chunks[idx].append(audio_chunk[i])
663
+
664
+ # Add streaming support here
665
+ if audio_streamer is not None:
666
+ # Stream the audio chunks immediately
667
+ audio_streamer.put(audio_chunk, diffusion_indices)
668
+
669
+ # Encode audio to semantic features using semantic streaming cache
670
+ semantic_features = self.model.semantic_tokenizer.encode(
671
+ audio_chunk,
672
+ cache=semantic_cache, # Use semantic-specific cache
673
+ sample_indices=diffusion_indices,
674
+ use_cache=True,
675
+ debug=False
676
+ ).mean # semantic tokenizer has no VAE.
677
+
678
+ # Combine acoustic and semantic features for next input
679
+ acoustic_embed = self.model.acoustic_connector(speech_latent)
680
+ semantic_embed = self.model.semantic_connector(semantic_features)
681
+ diffusion_embeds = acoustic_embed + semantic_embed
682
+
683
+ # Update embeddings for diffusion indices
684
+ next_inputs_embeds[diffusion_indices] = diffusion_embeds
685
+
686
+ # Set inputs_embeds for next iteration
687
+ inputs_embeds = next_inputs_embeds
688
+
689
+ if audio_streamer is not None:
690
+ audio_streamer.end()
691
+
692
+ # Concatenate audio chunks for each sample
693
+ final_audio_outputs = []
694
+ for sample_chunks in audio_chunks:
695
+ if sample_chunks:
696
+ # Concatenate all chunks along the time dimension (assumed to be the last dimension)
697
+ concatenated_audio = torch.cat(sample_chunks, dim=-1)
698
+ final_audio_outputs.append(concatenated_audio)
699
+ else:
700
+ # If no audio was generated for this sample, append None
701
+ final_audio_outputs.append(None)
702
+
703
+ return VibeVoiceGenerationOutput(
704
+ sequences=input_ids,
705
+ speech_outputs=final_audio_outputs if return_speech else None,
706
+ reach_max_step_sample=reach_max_step_sample,
707
+ )
708
+
709
+ @torch.no_grad()
710
+ def sample_speech_tokens(self, condition, neg_condition, cfg_scale=3.0):
711
+ self.model.noise_scheduler.set_timesteps(self.ddpm_inference_steps)
712
+ condition = torch.cat([condition, neg_condition], dim=0).to(self.model.prediction_head.device)
713
+ speech = torch.randn(condition.shape[0], self.config.acoustic_vae_dim).to(condition)
714
+ for t in self.model.noise_scheduler.timesteps:
715
+ half = speech[: len(speech) // 2]
716
+ combined = torch.cat([half, half], dim=0)
717
+ eps = self.model.prediction_head(combined, t.repeat(combined.shape[0]).to(combined), condition=condition)
718
+ cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)
719
+ half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps)
720
+ eps = torch.cat([half_eps, half_eps], dim=0)
721
+ speech = self.model.noise_scheduler.step(eps, t, speech).prev_sample
722
+ return speech[: len(speech) // 2]
723
+
724
+
725
+ AutoModelForCausalLM.register(VibeVoiceConfig, VibeVoiceForConditionalGenerationInference)
726
+
727
+ __all__ = [
728
+ "VibeVoiceForConditionalGenerationInference",
729
+ ]
VibeVoice-tpu/src/vibevoice/modular/modular_vibevoice_diffusion_head.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Optional, Tuple, Union
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+
8
+ from transformers.models.auto import AutoModel
9
+ from transformers.modeling_utils import PreTrainedModel
10
+ # from transformers.modeling_layers import GradientCheckpointingLayer
11
+ from transformers.activations import ACT2FN
12
+ from transformers.utils import logging
13
+
14
+ from .configuration_vibevoice import VibeVoiceDiffusionHeadConfig
15
+
16
+
17
+ logger = logging.get_logger(__name__)
18
+
19
+
20
+ class RMSNorm(nn.Module):
21
+ def __init__(self, dim: int, eps: float = 1e-6, elementwise_affine=True, memory_efficient=False):
22
+ super().__init__()
23
+ self.dim = dim
24
+ self.eps = eps
25
+ self.elementwise_affine = elementwise_affine
26
+ if self.elementwise_affine:
27
+ self.weight = nn.Parameter(torch.ones(dim))
28
+ else:
29
+ self.register_parameter('weight', None)
30
+
31
+ def _norm(self, x):
32
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
33
+
34
+ def forward(self, x):
35
+ output = self._norm(x.float()).type_as(x)
36
+ if self.weight is not None:
37
+ output = output * self.weight
38
+ return output
39
+
40
+ def extra_repr(self) -> str:
41
+ return f'dim={self.dim}, eps={self.eps}, elementwise_affine={self.elementwise_affine}'
42
+
43
+ def modulate(x, shift, scale):
44
+ """Apply modulation to input tensor."""
45
+ return x * (1 + scale) + shift
46
+
47
+
48
+ class TimestepEmbedder(nn.Module):
49
+ """
50
+ Embeds scalar timesteps into vector representations.
51
+
52
+ Args:
53
+ hidden_size (`int`): Size of the output embedding
54
+ frequency_embedding_size (`int`, optional): Size of the intermediate frequency embedding
55
+ """
56
+ def __init__(self, hidden_size, frequency_embedding_size=256):
57
+ super().__init__()
58
+ self.mlp = nn.Sequential(
59
+ nn.Linear(frequency_embedding_size, hidden_size, bias=False),
60
+ # nn.SiLU(),
61
+ ACT2FN['silu'],
62
+ nn.Linear(hidden_size, hidden_size, bias=False),
63
+ )
64
+ self.frequency_embedding_size = frequency_embedding_size
65
+
66
+ @staticmethod
67
+ def timestep_embedding(t, dim, max_period=10000):
68
+ """
69
+ Create sinusoidal timestep embeddings.
70
+
71
+ Args:
72
+ t (`torch.Tensor`): A 1-D Tensor of N indices, one per batch element.
73
+ These may be fractional.
74
+ dim (`int`): The dimension of the output.
75
+ max_period (`int`, optional): Controls the minimum frequency of the embeddings.
76
+
77
+ Returns:
78
+ `torch.Tensor`: An [N, D] Tensor of positional embeddings.
79
+ """
80
+ half = dim // 2
81
+ freqs = torch.exp(
82
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
83
+ ).to(t.device)
84
+ args = t[:, None].float() * freqs[None]
85
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
86
+ if dim % 2:
87
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
88
+ return embedding.to(t.dtype)
89
+
90
+ def forward(self, t):
91
+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
92
+ t_emb = self.mlp(t_freq)
93
+ return t_emb
94
+
95
+
96
+ class FeedForwardNetwork(nn.Module):
97
+ """
98
+ Standard feed-forward network with SwiGLU activation.
99
+
100
+ Args:
101
+ embed_dim (`int`): Input dimension
102
+ ffn_dim (`int`): Hidden dimension
103
+ """
104
+ def __init__(
105
+ self,
106
+ embed_dim,
107
+ ffn_dim,
108
+ ):
109
+ super().__init__()
110
+ self.embed_dim = embed_dim
111
+ self.gate_proj = nn.Linear(self.embed_dim, ffn_dim, bias=False)
112
+ self.up_proj = nn.Linear(self.embed_dim, ffn_dim, bias=False)
113
+ self.down_proj = nn.Linear(ffn_dim, self.embed_dim, bias=False)
114
+ self.act_fn = ACT2FN['silu'] # Using SiLU as the activation function
115
+
116
+ def forward(self, x):
117
+ gate = self.gate_proj(x)
118
+ up = self.up_proj(x)
119
+
120
+ # SwiGLU activation
121
+ # gate = F.silu(gate)
122
+ gate = self.act_fn(gate)
123
+ return self.down_proj(gate * up)
124
+
125
+
126
+ class HeadLayer(nn.Module):
127
+ """
128
+ A layer in the diffusion head.
129
+
130
+ Args:
131
+ embed_dim (`int`): Input dimension
132
+ ffn_dim (`int`): Hidden dimension
133
+ cond_dim (`int`): Condition embedding dimension
134
+ norm_eps (`float`, optional): Epsilon for normalization
135
+ """
136
+ def __init__(
137
+ self,
138
+ embed_dim,
139
+ ffn_dim,
140
+ cond_dim,
141
+ norm_eps=1e-5,
142
+ ):
143
+ super().__init__()
144
+ self.embed_dim = embed_dim
145
+ self.cond_dim = cond_dim
146
+ self.ffn_dim = ffn_dim
147
+ self.ffn = FeedForwardNetwork(
148
+ self.embed_dim,
149
+ self.ffn_dim,
150
+ )
151
+ self.norm = RMSNorm(self.embed_dim, eps=norm_eps)
152
+ self.adaLN_modulation = nn.Sequential(
153
+ # nn.SiLU(),
154
+ ACT2FN['silu'],
155
+ nn.Linear(cond_dim, 3 * self.embed_dim, bias=False)
156
+ )
157
+
158
+ def forward(self, x, c):
159
+ shift_ffn, scale_ffn, gate_ffn = self.adaLN_modulation(c).chunk(3, dim=-1)
160
+ x = x + gate_ffn * self.ffn(modulate(self.norm(x), shift_ffn, scale_ffn))
161
+ return x
162
+
163
+
164
+ class FinalLayer(nn.Module):
165
+ """
166
+ Final layer in the diffusion head.
167
+
168
+ Args:
169
+ hidden_size (`int`): Input dimension
170
+ output_size (`int`): Output dimension
171
+ cond_size (`int`): Condition embedding dimension
172
+ norm_eps (`float`, optional): Epsilon for normalization
173
+ """
174
+ def __init__(self, hidden_size, output_size, cond_size, norm_eps=1e-5):
175
+ super().__init__()
176
+ self.norm_final = RMSNorm(hidden_size, eps=norm_eps, elementwise_affine=False)
177
+ self.linear = nn.Linear(hidden_size, output_size, bias=False)
178
+ self.adaLN_modulation = nn.Sequential(
179
+ # nn.SiLU(),
180
+ ACT2FN['silu'],
181
+ nn.Linear(cond_size, 2 * hidden_size, bias=False)
182
+ )
183
+
184
+ def forward(self, x, c):
185
+ shift, scale = self.adaLN_modulation(c).chunk(2, dim=-1)
186
+ x = modulate(self.norm_final(x), shift, scale)
187
+ x = self.linear(x)
188
+ return x
189
+
190
+
191
+ class VibeVoiceDiffusionHead(PreTrainedModel):
192
+ """
193
+ Diffusion head model for vibevoice.
194
+
195
+ Args:
196
+ config (`VibeVoiceDiffusionHeadConfig`): Model configuration
197
+ latent_size (`int`, optional): Size of the latent space. If not provided, uses `config.latent_size`.
198
+ """
199
+ config_class = VibeVoiceDiffusionHeadConfig
200
+ supports_gradient_checkpointing = True
201
+ _supports_flash_attn_2 = True
202
+ _supports_sdpa = True
203
+
204
+ def __init__(
205
+ self,
206
+ config,
207
+ ):
208
+ super().__init__(config)
209
+ self.config = config
210
+ self.cond_dim = config.hidden_size
211
+ latent_size = config.latent_size
212
+
213
+ self.noisy_images_proj = nn.Linear(latent_size, config.hidden_size, bias=False)
214
+ self.cond_proj = nn.Linear(config.hidden_size, self.cond_dim, bias=False)
215
+ self.t_embedder = TimestepEmbedder(self.cond_dim)
216
+
217
+ ffn_dim = int(config.hidden_size * config.head_ffn_ratio)
218
+
219
+ # Create the intermediate layers
220
+ self.layers = nn.ModuleList([
221
+ HeadLayer(
222
+ embed_dim=config.hidden_size,
223
+ ffn_dim=ffn_dim,
224
+ cond_dim=self.cond_dim,
225
+ norm_eps=config.rms_norm_eps
226
+ )
227
+ for _ in range(config.head_layers)
228
+ ])
229
+
230
+ # Final layer for output
231
+ self.final_layer = FinalLayer(
232
+ hidden_size=config.hidden_size,
233
+ output_size=latent_size,
234
+ cond_size=self.cond_dim,
235
+ norm_eps=config.rms_norm_eps
236
+ )
237
+
238
+ self.initialize_weights()
239
+
240
+ def initialize_weights(self):
241
+ """Initialize the weights of the model."""
242
+ # Initialize timestep embedder
243
+ nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)
244
+ nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)
245
+
246
+ # Zero-out adaLN modulation layers
247
+ for layer in self.layers:
248
+ nn.init.constant_(layer.adaLN_modulation[-1].weight, 0)
249
+
250
+ # Zero-out output layers
251
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)
252
+ nn.init.constant_(self.final_layer.linear.weight, 0)
253
+
254
+ def forward(
255
+ self,
256
+ noisy_images,
257
+ timesteps,
258
+ condition,
259
+ ):
260
+ """
261
+ Forward pass of the prediction head.
262
+
263
+ Args:
264
+ noisy_images (`torch.Tensor`): Noisy images/latents to denoise
265
+ timesteps (`torch.Tensor`): Timesteps for diffusion
266
+ condition (`torch.Tensor`): Conditioning information
267
+
268
+ Returns:
269
+ `torch.Tensor`: The predicted noise/velocity
270
+ """
271
+ x = self.noisy_images_proj(noisy_images)
272
+ t = self.t_embedder(timesteps)
273
+ condition = self.cond_proj(condition)
274
+ c = condition + t
275
+
276
+ for layer in self.layers:
277
+ x = layer(x, c)
278
+
279
+ x = self.final_layer(x, c)
280
+ return x
281
+
282
+
283
+ AutoModel.register(VibeVoiceDiffusionHeadConfig, VibeVoiceDiffusionHead)
284
+
285
+ __all__ = [
286
+ "VibeVoiceDiffusionHead",
287
+ ]
VibeVoice-tpu/src/vibevoice/modular/modular_vibevoice_text_tokenizer.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tokenization classes for vibevoice."""
2
+
3
+ from typing import List, Optional, Union
4
+
5
+ from transformers.utils import logging
6
+ from transformers.models.qwen2.tokenization_qwen2 import Qwen2Tokenizer
7
+ from transformers.models.qwen2.tokenization_qwen2_fast import Qwen2TokenizerFast
8
+
9
+ logger = logging.get_logger(__name__)
10
+
11
+
12
+ class VibeVoiceTextTokenizer(Qwen2Tokenizer):
13
+ """
14
+ Construct a VibeVoice tokenizer. Based on the Qwen2 tokenizer with additional special tokens for speech.
15
+
16
+ Args:
17
+ vocab_file (`str`):
18
+ Path to the vocabulary file.
19
+ merges_file (`str`):
20
+ Path to the merges file.
21
+ errors (`str`, *optional*, defaults to `"replace"`):
22
+ Paradigm to follow when decoding bytes to UTF-8.
23
+ unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
24
+ The unknown token.
25
+ bos_token (`str`, *optional*):
26
+ The beginning of sequence token. Not used for vibevoice.
27
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
28
+ The end of sequence token.
29
+ pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
30
+ The token used for padding.
31
+ add_special_tokens (`bool`, *optional*, defaults to `True`):
32
+ Whether or not to add special tokens when encoding.
33
+ """
34
+
35
+ model_input_names = ["input_ids", "attention_mask"]
36
+
37
+ def __init__(
38
+ self,
39
+ vocab_file,
40
+ merges_file,
41
+ errors="replace",
42
+ unk_token="<|endoftext|>",
43
+ bos_token=None,
44
+ eos_token="<|endoftext|>",
45
+ pad_token="<|endoftext|>",
46
+ add_prefix_space=False,
47
+ add_special_tokens=True,
48
+ **kwargs,
49
+ ):
50
+ super().__init__(
51
+ vocab_file=vocab_file,
52
+ merges_file=merges_file,
53
+ errors=errors,
54
+ unk_token=unk_token,
55
+ bos_token=bos_token,
56
+ eos_token=eos_token,
57
+ pad_token=pad_token,
58
+ add_prefix_space=add_prefix_space,
59
+ add_special_tokens=add_special_tokens,
60
+ **kwargs,
61
+ )
62
+
63
+ # Add VibeVoice-specific special tokens
64
+ self._add_vibevoice_special_tokens()
65
+
66
+ def _add_vibevoice_special_tokens(self):
67
+ """Add VibeVoice-specific special tokens."""
68
+ special_tokens = {
69
+ "additional_special_tokens": [
70
+ "<|vision_start|>", # Speech start (reusing vision tokens)
71
+ "<|vision_end|>", # Speech end
72
+ "<|vision_pad|>", # Speech diffusion pad
73
+ ]
74
+ }
75
+ num_added = self.add_special_tokens(special_tokens)
76
+
77
+ # Cache special token IDs
78
+ self._speech_start_id = self.convert_tokens_to_ids("<|vision_start|>")
79
+ self._speech_end_id = self.convert_tokens_to_ids("<|vision_end|>")
80
+ self._speech_diffusion_id = self.convert_tokens_to_ids("<|vision_pad|>")
81
+
82
+ self._eos_id = self.convert_tokens_to_ids('<|endoftext|>')
83
+
84
+ return num_added
85
+
86
+ @property
87
+ def eos_id(self) -> int:
88
+ """Id of the end of sequence token."""
89
+ return self._eos_id
90
+
91
+ @property
92
+ def speech_start_id(self) -> int:
93
+ """Id of the speech start token."""
94
+ return self._speech_start_id
95
+
96
+ @property
97
+ def speech_end_id(self) -> int:
98
+ """Id of the speech end token."""
99
+ return self._speech_end_id
100
+
101
+ @property
102
+ def speech_diffusion_id(self) -> int:
103
+ """Id of the speech diffusion token."""
104
+ return self._speech_diffusion_id
105
+
106
+ @property
107
+ def pad_id(self) -> int:
108
+ """Id used for padding (returns -100 for loss masking)."""
109
+ return -100
110
+
111
+
112
+ class VibeVoiceTextTokenizerFast(Qwen2TokenizerFast):
113
+ """
114
+ Construct a "fast" VibeVoice tokenizer (backed by HuggingFace's *tokenizers* library).
115
+ Based on the Qwen2 tokenizer with additional special tokens for speech.
116
+
117
+ Args:
118
+ vocab_file (`str`, *optional*):
119
+ Path to the vocabulary file.
120
+ merges_file (`str`, *optional*):
121
+ Path to the merges file.
122
+ tokenizer_file (`str`, *optional*):
123
+ Path to [tokenizers](https://github.com/huggingface/tokenizers) file.
124
+ unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
125
+ The unknown token.
126
+ bos_token (`str`, *optional*):
127
+ The beginning of sequence token. Not used for vibevoice.
128
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
129
+ The end of sequence token.
130
+ pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
131
+ The token used for padding.
132
+ """
133
+
134
+ model_input_names = ["input_ids", "attention_mask"]
135
+
136
+ def __init__(
137
+ self,
138
+ vocab_file=None,
139
+ merges_file=None,
140
+ tokenizer_file=None,
141
+ unk_token="<|endoftext|>",
142
+ bos_token=None,
143
+ eos_token="<|endoftext|>",
144
+ pad_token="<|endoftext|>",
145
+ add_prefix_space=False,
146
+ **kwargs,
147
+ ):
148
+ super().__init__(
149
+ vocab_file=vocab_file,
150
+ merges_file=merges_file,
151
+ tokenizer_file=tokenizer_file,
152
+ unk_token=unk_token,
153
+ bos_token=bos_token,
154
+ eos_token=eos_token,
155
+ pad_token=pad_token,
156
+ add_prefix_space=add_prefix_space,
157
+ **kwargs,
158
+ )
159
+
160
+ # Add VibeVoice-specific special tokens
161
+ self._add_vibevoice_special_tokens()
162
+
163
+ def _add_vibevoice_special_tokens(self):
164
+ """Add VibeVoice-specific special tokens."""
165
+ special_tokens = {
166
+ "additional_special_tokens": [
167
+ "<|vision_start|>", # Speech start (reusing vision tokens)
168
+ "<|vision_end|>", # Speech end
169
+ "<|vision_pad|>", # Speech diffusion pad
170
+ ]
171
+ }
172
+ num_added = self.add_special_tokens(special_tokens)
173
+
174
+ # Cache special token IDs
175
+ self._speech_start_id = self.convert_tokens_to_ids("<|vision_start|>")
176
+ self._speech_end_id = self.convert_tokens_to_ids("<|vision_end|>")
177
+ self._speech_diffusion_id = self.convert_tokens_to_ids("<|vision_pad|>")
178
+
179
+ # self._eos_id = self.convert_tokens_to_ids('<|endoftext|>')
180
+ self._eos_id = self.eos_token_id # qwen2 / qwen3
181
+ self._pad_id = self.convert_tokens_to_ids('<|image_pad|>')
182
+
183
+ return num_added
184
+
185
+ @property
186
+ def eos_id(self) -> int:
187
+ """Id of the end of sequence token."""
188
+ return self._eos_id
189
+
190
+ @property
191
+ def speech_start_id(self) -> int:
192
+ """Id of the speech start token."""
193
+ return self._speech_start_id
194
+
195
+ @property
196
+ def speech_end_id(self) -> int:
197
+ """Id of the speech end token."""
198
+ return self._speech_end_id
199
+
200
+ @property
201
+ def speech_diffusion_id(self) -> int:
202
+ """Id of the speech diffusion token."""
203
+ return self._speech_diffusion_id
204
+
205
+ @property
206
+ def pad_id(self) -> int:
207
+ """Id used for padding (returns -100 for loss masking)."""
208
+ return self._pad_id
209
+
210
+
211
+ __all__ = [
212
+ "VibeVoiceTextTokenizer",
213
+ "VibeVoiceTextTokenizerFast",
214
+ ]
VibeVoice-tpu/src/vibevoice/modular/modular_vibevoice_tokenizer.py ADDED
@@ -0,0 +1,1195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import typing as tp
3
+ from functools import partial
4
+ from dataclasses import dataclass, field
5
+ from typing import Dict, List, Optional, Tuple, Union
6
+ import copy
7
+
8
+ import numpy as np
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+
13
+ from transformers.models.auto import AutoModel
14
+
15
+ from transformers.configuration_utils import PretrainedConfig
16
+ from transformers.utils import logging
17
+ from transformers.modeling_utils import PreTrainedModel
18
+ from transformers.activations import ACT2FN
19
+
20
+ from .configuration_vibevoice import VibeVoiceAcousticTokenizerConfig, VibeVoiceSemanticTokenizerConfig
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+ import os
25
+ # Try to import APEX FusedRMSNorm
26
+ try:
27
+ from apex.normalization.fused_layer_norm import fused_rms_norm_affine
28
+ APEX_AVAILABLE = True
29
+ logger.info("APEX FusedRMSNorm is available and will be used for optimization")
30
+ if int(os.getenv("OPTIMIZE_FOR_SPEED", "0")) == 0:
31
+ APEX_AVAILABLE = False
32
+ logger.warning("APEX FusedRMSNorm is disabled by environment variable OPTIMIZE_FOR_SPEED=0")
33
+ except ImportError:
34
+ APEX_AVAILABLE = False
35
+ logger.warning("APEX FusedRMSNorm not available, using native implementation")
36
+ # APEX_AVAILABLE=False
37
+
38
+ # Normalization modules
39
+ class ConvLayerNorm(nn.LayerNorm):
40
+ """
41
+ Convolution-friendly LayerNorm that moves channels to last dimensions
42
+ before running the normalization and moves them back to original position right after.
43
+ """
44
+ def __init__(self, normalized_shape: tp.Union[int, tp.List[int], torch.Size], **kwargs):
45
+ super().__init__(normalized_shape, **kwargs)
46
+
47
+ def forward(self, x):
48
+ x = x.transpose(1, 2) # b ... t -> b t ...
49
+ x = nn.functional.layer_norm(x.float(), self.normalized_shape, self.weight.float(), self.bias.float(), self.eps).type_as(x)
50
+ x = x.transpose(1, 2) # b t ... -> b ... t
51
+ return x
52
+
53
+ class RMSNorm(nn.Module):
54
+ def __init__(self, dim: int, eps: float = 1e-5, elementwise_affine=True, weight_shape=None):
55
+ super().__init__()
56
+ self.dim = dim
57
+ self.eps = eps
58
+ self.elementwise_affine = elementwise_affine
59
+ if self.elementwise_affine:
60
+ weight_shape = (dim,) if weight_shape is None else weight_shape
61
+ self.weight = nn.Parameter(torch.ones(weight_shape))
62
+ else:
63
+ self.register_parameter('weight', None)
64
+
65
+ def _norm(self, x):
66
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
67
+
68
+ def forward(self, x):
69
+ output = self._norm(x.float()).type_as(x)
70
+ if self.weight is not None:
71
+ output = output * self.weight
72
+ return output
73
+
74
+ def extra_repr(self) -> str:
75
+ return f'dim={self.dim}, eps={self.eps}, elementwise_affine={self.elementwise_affine}'
76
+
77
+ class ConvRMSNorm(RMSNorm):
78
+ def __init__(self, dim: int, eps: float = 1e-5, elementwise_affine=True, weight_shape=None):
79
+ super().__init__(dim, eps, elementwise_affine, weight_shape)
80
+
81
+ def forward(self, x):
82
+ x = x.transpose(1, 2) # b ... t -> b t ...
83
+ if (not APEX_AVAILABLE) or (not self.elementwise_affine):
84
+ # Fallback to native implementation
85
+ output = self._norm(x.float()).type_as(x)
86
+ if self.weight is not None:
87
+ output = output * self.weight
88
+ else:
89
+ output = fused_rms_norm_affine(x, self.weight, self.weight.shape, self.eps)
90
+ output = output.transpose(1, 2) # b t ... -> b ... t
91
+ return output
92
+
93
+ # Convolutional layers and utilities
94
+ CONV_NORMALIZATIONS = frozenset(['none', 'weight_norm', 'spectral_norm',
95
+ 'time_layer_norm', 'layer_norm', 'time_group_norm'])
96
+
97
+
98
+ def apply_parametrization_norm(module: nn.Module, norm: str = 'none') -> nn.Module:
99
+ assert norm in CONV_NORMALIZATIONS
100
+ if norm == 'weight_norm':
101
+ return nn.utils.weight_norm(module)
102
+ elif norm == 'spectral_norm':
103
+ return nn.utils.spectral_norm(module)
104
+ else:
105
+ # We already check was in CONV_NORMALIZATION, so any other choice
106
+ # doesn't need reparametrization.
107
+ return module
108
+
109
+
110
+ def get_norm_module(module: nn.Module, causal: bool = False, norm: str = 'none', **norm_kwargs) -> nn.Module:
111
+ """Return the proper normalization module. If causal is True, this will ensure the returned
112
+ module is causal, or return an error if the normalization doesn't support causal evaluation.
113
+ """
114
+ assert norm in CONV_NORMALIZATIONS
115
+ if norm == 'layer_norm':
116
+ assert isinstance(module, nn.modules.conv._ConvNd)
117
+ return ConvLayerNorm(module.out_channels, **norm_kwargs)
118
+ elif norm == 'time_group_norm':
119
+ if causal:
120
+ raise ValueError("GroupNorm doesn't support causal evaluation.")
121
+ assert isinstance(module, nn.modules.conv._ConvNd)
122
+ return nn.GroupNorm(1, module.out_channels, **norm_kwargs)
123
+ else:
124
+ return nn.Identity()
125
+
126
+
127
+ def get_extra_padding_for_conv1d(x: torch.Tensor, kernel_size: int, stride: int,
128
+ padding_total: int = 0) -> int:
129
+ """Calculate extra padding needed for convolution to have the same output length"""
130
+ length = x.shape[-1]
131
+ n_frames = (length - kernel_size + padding_total) / stride + 1
132
+ ideal_length = (math.ceil(n_frames) - 1) * stride + (kernel_size - padding_total)
133
+ return ideal_length - length
134
+
135
+
136
+ def pad1d(x: torch.Tensor, paddings: tp.Tuple[int, int], mode: str = 'zero', value: float = 0.):
137
+ """Pad 1D input with handling for small inputs in reflect mode"""
138
+ length = x.shape[-1]
139
+ padding_left, padding_right = paddings
140
+ assert padding_left >= 0 and padding_right >= 0, (padding_left, padding_right)
141
+ if mode == 'reflect':
142
+ max_pad = max(padding_left, padding_right)
143
+ extra_pad = 0
144
+ if length <= max_pad:
145
+ extra_pad = max_pad - length + 1
146
+ x = F.pad(x, (0, extra_pad))
147
+ padded = F.pad(x, paddings, mode, value)
148
+ end = padded.shape[-1] - extra_pad
149
+ return padded[..., :end]
150
+ else:
151
+ return F.pad(x, paddings, mode, value)
152
+
153
+
154
+ def unpad1d(x: torch.Tensor, paddings: tp.Tuple[int, int]):
155
+ """Remove padding from x, handling properly zero padding. Only for 1d!"""
156
+ padding_left, padding_right = paddings
157
+ assert padding_left >= 0 and padding_right >= 0, (padding_left, padding_right)
158
+ assert (padding_left + padding_right) <= x.shape[-1]
159
+ end = x.shape[-1] - padding_right
160
+ return x[..., padding_left: end]
161
+
162
+
163
+ class NormConv1d(nn.Module):
164
+ """Wrapper around Conv1d and normalization applied to this conv"""
165
+ def __init__(self, *args, causal: bool = False, norm: str = 'none',
166
+ norm_kwargs: tp.Dict[str, tp.Any] = {}, **kwargs):
167
+ super().__init__()
168
+ self.conv = apply_parametrization_norm(nn.Conv1d(*args, **kwargs), norm)
169
+ self.norm = get_norm_module(self.conv, causal, norm, **norm_kwargs)
170
+ self.norm_type = norm
171
+
172
+ def forward(self, x):
173
+ x = self.conv(x)
174
+ x = self.norm(x)
175
+ return x
176
+
177
+
178
+ class NormConvTranspose1d(nn.Module):
179
+ """Wrapper around ConvTranspose1d and normalization applied to this conv"""
180
+ def __init__(self, *args, causal: bool = False, norm: str = 'none',
181
+ norm_kwargs: tp.Dict[str, tp.Any] = {}, **kwargs):
182
+ super().__init__()
183
+ self.convtr = apply_parametrization_norm(nn.ConvTranspose1d(*args, **kwargs), norm)
184
+ self.norm = get_norm_module(self.convtr, causal, norm, **norm_kwargs)
185
+ self.norm_type = norm
186
+
187
+ def forward(self, x):
188
+ x = self.convtr(x)
189
+ x = self.norm(x)
190
+ return x
191
+
192
+
193
+ class VibeVoiceTokenizerStreamingCache:
194
+ """Cache for streaming convolution, similar to KV cache in attention"""
195
+ def __init__(self):
196
+ self.cache = {} # Dict mapping (layer_id, sample_idx) to state tensor
197
+
198
+ def get(self, layer_id: str, sample_indices: torch.Tensor) -> Optional[torch.Tensor]:
199
+ """Get cached states for given layer and sample indices"""
200
+ states = []
201
+ max_length = 0
202
+
203
+ # First pass: collect states and find max length
204
+ for idx in sample_indices.tolist():
205
+ key = (layer_id, idx)
206
+ if key not in self.cache:
207
+ return None # If any sample is missing, return None
208
+ state = self.cache[key]
209
+ states.append(state)
210
+ max_length = max(max_length, state.shape[-1])
211
+
212
+ # Second pass: pad states to max length if needed
213
+ if len(states) > 0 and states[0].dim() >= 2:
214
+ padded_states = []
215
+ for state in states:
216
+ if state.shape[-1] < max_length:
217
+ # Pad on the time dimension (last dimension)
218
+ pad_size = max_length - state.shape[-1]
219
+ # Pad with zeros on the LEFT to align the most recent samples
220
+ padded_state = F.pad(state, (pad_size, 0), mode='constant', value=0)
221
+ padded_states.append(padded_state)
222
+ else:
223
+ padded_states.append(state)
224
+ return torch.stack(padded_states, dim=0)
225
+ else:
226
+ return torch.stack(states, dim=0)
227
+
228
+ def set(self, layer_id: str, sample_indices: torch.Tensor, states: torch.Tensor):
229
+ """Set cached states for given layer and sample indices"""
230
+ for i, idx in enumerate(sample_indices.tolist()):
231
+ key = (layer_id, idx)
232
+ self.cache[key] = states[i].detach()
233
+
234
+ def set_to_zero(self, sample_indices: torch.Tensor):
235
+ """Set all cached states to zero for given sample indices"""
236
+ for key in list(self.cache.keys()):
237
+ layer_id, sample_idx = key
238
+ if sample_idx in sample_indices.tolist():
239
+ # Create zero tensor with same shape and dtype as cached tensor
240
+ cached_tensor = self.cache[key]
241
+ self.cache[key] = torch.zeros_like(cached_tensor)
242
+
243
+ def clear(self, layer_id: Optional[str] = None, sample_indices: Optional[torch.Tensor] = None):
244
+ """Clear cache for specific layer/samples or everything"""
245
+ if layer_id is None and sample_indices is None:
246
+ self.cache.clear()
247
+ elif layer_id is not None and sample_indices is None:
248
+ # Clear all samples for a specific layer
249
+ keys_to_remove = [k for k in self.cache.keys() if k[0] == layer_id]
250
+ for k in keys_to_remove:
251
+ del self.cache[k]
252
+ elif layer_id is not None and sample_indices is not None:
253
+ # Clear specific samples for a specific layer
254
+ for idx in sample_indices.tolist():
255
+ key = (layer_id, idx)
256
+ self.cache.pop(key, None)
257
+
258
+ class SConv1d(nn.Module):
259
+ """Conv1d with built-in handling of asymmetric or causal padding and normalization."""
260
+ def __init__(self, in_channels: int, out_channels: int,
261
+ kernel_size: int, stride: int = 1, dilation: int = 1,
262
+ groups: int = 1, bias: bool = True, causal: bool = False,
263
+ norm: str = 'none', norm_kwargs: tp.Dict[str, tp.Any] = {},
264
+ pad_mode: str = 'reflect'):
265
+ super().__init__()
266
+ self.conv = NormConv1d(in_channels, out_channels, kernel_size, stride,
267
+ dilation=dilation, groups=groups, bias=bias, causal=causal,
268
+ norm=norm, norm_kwargs=norm_kwargs)
269
+ self.causal = causal
270
+ self.pad_mode = pad_mode
271
+
272
+ # Store configuration
273
+ self.kernel_size = kernel_size
274
+ self.dilation = dilation
275
+ self.stride = stride
276
+ self.in_channels = in_channels
277
+ self.out_channels = out_channels
278
+
279
+ # For causal convolution, we need to maintain kernel_size - 1 samples as context
280
+ # need to check use which context_size is more suitable
281
+ # self.context_size = (kernel_size - 1) * dilation
282
+ self.context_size = (kernel_size - 1) * dilation - (stride - 1)
283
+
284
+ # For non-streaming mode, calculate padding
285
+ self.padding_total = (kernel_size - 1) * dilation - (stride - 1)
286
+
287
+ # Create a unique layer ID for cache management
288
+ self._layer_id = None
289
+
290
+ @property
291
+ def layer_id(self):
292
+ if self._layer_id is None:
293
+ self._layer_id = f"sconv1d_{id(self)}"
294
+ return self._layer_id
295
+
296
+ def forward(self, x: torch.Tensor,
297
+ cache: Optional[VibeVoiceTokenizerStreamingCache] = None,
298
+ sample_indices: Optional[torch.Tensor] = None,
299
+ use_cache: bool = False,
300
+ debug: bool = False) -> torch.Tensor:
301
+ """
302
+ Forward pass with optional streaming support via cache.
303
+
304
+ Args:
305
+ x: Input tensor [batch_size, channels, time]
306
+ cache: VibeVoiceTokenizerStreamingCache object for maintaining states
307
+ sample_indices: Indices identifying each sample for cache management
308
+ use_cache: Whether to use cached states for streaming
309
+ debug: Whether to print debug information
310
+
311
+ Returns:
312
+ Output tensor
313
+ """
314
+ B, C, T = x.shape
315
+
316
+ # Non-streaming mode
317
+ if not use_cache or cache is None:
318
+ return self._forward_non_streaming(x, debug=debug)
319
+
320
+ # Streaming mode
321
+ assert self.causal, "Streaming mode is only supported for causal convolutions"
322
+ assert sample_indices is not None, "sample_indices must be provided for streaming mode"
323
+ assert len(sample_indices) == B, "sample_indices must match batch size"
324
+
325
+ return self._forward_streaming(x, cache, sample_indices, debug)
326
+
327
+ def _forward_streaming(self, x: torch.Tensor,
328
+ cache: VibeVoiceTokenizerStreamingCache,
329
+ sample_indices: torch.Tensor,
330
+ debug: bool = False) -> torch.Tensor:
331
+ """Streaming forward pass with cache operations kept separate from compiled code"""
332
+ B, C, T = x.shape
333
+
334
+ # Cache operations (not compiled)
335
+ cached_states = cache.get(self.layer_id, sample_indices)
336
+
337
+ if cached_states is None:
338
+ # First chunk - initialize with zeros for context
339
+ if self.context_size > 0:
340
+ cached_states = torch.zeros(B, C, self.context_size, device=x.device, dtype=x.dtype)
341
+ if debug:
342
+ print(f"[DEBUG] Initialized cache with shape: {cached_states.shape}, context_size={self.context_size}")
343
+ else:
344
+ cached_states = torch.zeros(B, C, 0, device=x.device, dtype=x.dtype)
345
+ if debug:
346
+ print(f"[DEBUG] No context needed (kernel_size=stride)")
347
+
348
+ # Concatenate cached states with input
349
+ if cached_states.shape[2] > 0:
350
+ input_with_context = torch.cat([cached_states, x], dim=2)
351
+ else:
352
+ input_with_context = x
353
+
354
+ if debug:
355
+ print(f"[DEBUG] Input shape: {x.shape}, Cache shape: {cached_states.shape}, Combined: {input_with_context.shape}")
356
+
357
+ # Apply convolution directly - no extra padding in streaming mode
358
+ # The conv layer will handle its own padding internally
359
+ output = self.conv(input_with_context)
360
+
361
+ if debug:
362
+ print(f"[DEBUG] Output shape: {output.shape}")
363
+
364
+ # Update cache for next chunk
365
+ if self.context_size > 0:
366
+ # Calculate how many samples to keep
367
+ total_input_length = input_with_context.shape[2]
368
+
369
+ # Keep the last context_size samples
370
+ if total_input_length >= self.context_size:
371
+ new_cache_start = total_input_length - self.context_size
372
+ new_cache = input_with_context[:, :, new_cache_start:]
373
+ else:
374
+ # If we have less than context_size samples, keep everything
375
+ new_cache = input_with_context
376
+
377
+ if debug:
378
+ print(f"[DEBUG] New cache shape: {new_cache.shape}")
379
+
380
+ cache.set(self.layer_id, sample_indices, new_cache)
381
+
382
+ return output
383
+
384
+ def _forward_non_streaming(self, x: torch.Tensor, debug: bool = False) -> torch.Tensor:
385
+ """Standard forward pass without streaming"""
386
+ B, C, T = x.shape
387
+ kernel_size = self.kernel_size
388
+ stride = self.stride
389
+ dilation = self.dilation
390
+ padding_total = self.padding_total
391
+
392
+ # Compute extra padding for stride alignment
393
+ extra_padding = get_extra_padding_for_conv1d(x, kernel_size, stride, padding_total)
394
+
395
+ if debug:
396
+ print(f"[DEBUG NON-STREAMING] Input shape: {x.shape}, padding_total={padding_total}, extra_padding={extra_padding}")
397
+
398
+ if self.causal:
399
+ # Left padding for causal
400
+ if self.pad_mode == 'constant':
401
+ x = pad1d(x, (padding_total, extra_padding), mode=self.pad_mode, value=0)
402
+ else:
403
+ x = pad1d(x, (padding_total, extra_padding), mode=self.pad_mode)
404
+ else:
405
+ # Symmetric padding for non-causal
406
+ padding_right = padding_total // 2
407
+ padding_left = padding_total - padding_right
408
+ x = pad1d(x, (padding_left, padding_right + extra_padding), mode=self.pad_mode)
409
+
410
+ if debug:
411
+ print(f"[DEBUG NON-STREAMING] After padding: {x.shape}")
412
+
413
+ output = self.conv(x)
414
+
415
+ if debug:
416
+ print(f"[DEBUG NON-STREAMING] Output shape: {output.shape}")
417
+
418
+ return output
419
+
420
+
421
+ class SConvTranspose1d(nn.Module):
422
+ """ConvTranspose1d with built-in handling of asymmetric or causal padding and normalization."""
423
+ def __init__(self, in_channels: int, out_channels: int,
424
+ kernel_size: int, stride: int = 1, causal: bool = False,
425
+ norm: str = 'none', trim_right_ratio: float = 1.,
426
+ norm_kwargs: tp.Dict[str, tp.Any] = {}, bias: bool = True):
427
+ super().__init__()
428
+ self.convtr = NormConvTranspose1d(in_channels, out_channels, kernel_size, stride,
429
+ causal=causal, norm=norm, norm_kwargs=norm_kwargs, bias=bias)
430
+ self.causal = causal
431
+ self.trim_right_ratio = trim_right_ratio
432
+ assert self.causal or self.trim_right_ratio == 1., \
433
+ "`trim_right_ratio` != 1.0 only makes sense for causal convolutions"
434
+ assert self.trim_right_ratio >= 0. and self.trim_right_ratio <= 1.
435
+
436
+ # Store configuration
437
+ self.kernel_size = kernel_size
438
+ self.stride = stride
439
+ self.in_channels = in_channels
440
+ self.out_channels = out_channels
441
+
442
+ # For transposed convolution, padding calculation is different
443
+ self.padding_total = kernel_size - stride
444
+
445
+ # For streaming, we need to keep track of input history
446
+ # Transposed conv needs to see multiple input samples to produce correct output
447
+ self.context_size = kernel_size - 1
448
+
449
+ # Create a unique layer ID for cache management
450
+ self._layer_id = None
451
+
452
+ @property
453
+ def layer_id(self):
454
+ if self._layer_id is None:
455
+ self._layer_id = f"sconvtr1d_{id(self)}"
456
+ return self._layer_id
457
+
458
+ def forward(self, x: torch.Tensor,
459
+ cache: Optional[VibeVoiceTokenizerStreamingCache] = None,
460
+ sample_indices: Optional[torch.Tensor] = None,
461
+ use_cache: bool = False,
462
+ debug: bool = False) -> torch.Tensor:
463
+ """
464
+ Forward pass with optional streaming support via cache.
465
+ """
466
+ B, C, T = x.shape
467
+
468
+ # Non-streaming mode
469
+ if not use_cache or cache is None:
470
+ return self._forward_non_streaming(x, debug=debug)
471
+
472
+ # Streaming mode
473
+ assert sample_indices is not None, "sample_indices must be provided for streaming mode"
474
+ assert len(sample_indices) == B, "sample_indices must match batch size"
475
+
476
+ return self._forward_streaming(x, cache, sample_indices, debug)
477
+
478
+ def _forward_streaming(self, x: torch.Tensor,
479
+ cache: VibeVoiceTokenizerStreamingCache,
480
+ sample_indices: torch.Tensor,
481
+ debug: bool = False) -> torch.Tensor:
482
+ """Streaming forward pass with cache operations kept separate from compiled code"""
483
+ B, C, T = x.shape
484
+
485
+ # Cache operations (not compiled)
486
+ cached_input = cache.get(self.layer_id, sample_indices)
487
+
488
+ if cached_input is None:
489
+ # First chunk - no history yet
490
+ cached_input = torch.zeros(B, C, 0, device=x.device, dtype=x.dtype)
491
+ if debug:
492
+ print(f"[DEBUG] Initialized empty cache for transposed conv")
493
+
494
+ # Concatenate cached input with new input
495
+ full_input = torch.cat([cached_input, x], dim=2)
496
+
497
+ if debug:
498
+ print(f"[DEBUG] Input shape: {x.shape}, Cache shape: {cached_input.shape}, Combined: {full_input.shape}")
499
+
500
+ # First chunk or debug mode - use uncompiled version
501
+ full_output = self.convtr(full_input)
502
+
503
+ if debug:
504
+ print(f"[DEBUG] Full transposed conv output shape: {full_output.shape}")
505
+
506
+ # Calculate padding to remove
507
+ if self.causal:
508
+ padding_right = math.ceil(self.padding_total * self.trim_right_ratio)
509
+ padding_left = self.padding_total - padding_right
510
+ else:
511
+ padding_right = self.padding_total // 2
512
+ padding_left = self.padding_total - padding_right
513
+
514
+ # Remove padding
515
+ if padding_left + padding_right > 0:
516
+ full_output = unpad1d(full_output, (padding_left, padding_right))
517
+
518
+ if debug:
519
+ print(f"[DEBUG] After unpadding: {full_output.shape}")
520
+
521
+ # Determine which part of the output corresponds to the new input
522
+ if cached_input.shape[2] == 0:
523
+ # First chunk - return all output
524
+ output = full_output
525
+ else:
526
+ # Subsequent chunks - return only the new output
527
+ expected_new_output = T * self.stride
528
+
529
+ # Take the last expected_new_output samples
530
+ if full_output.shape[2] >= expected_new_output:
531
+ output = full_output[:, :, -expected_new_output:]
532
+ else:
533
+ output = full_output
534
+
535
+ if debug:
536
+ print(f"[DEBUG] Final streaming output shape: {output.shape}")
537
+
538
+ # Update cache
539
+ if full_input.shape[2] > self.context_size:
540
+ new_cache = full_input[:, :, -self.context_size:]
541
+ else:
542
+ new_cache = full_input
543
+
544
+ if debug:
545
+ print(f"[DEBUG] New cache shape: {new_cache.shape}")
546
+
547
+ cache.set(self.layer_id, sample_indices, new_cache)
548
+
549
+ return output
550
+
551
+ def _forward_non_streaming(self, x: torch.Tensor, debug: bool = False) -> torch.Tensor:
552
+ """Standard forward pass without streaming"""
553
+ if debug:
554
+ print(f"[DEBUG NON-STREAMING] Input shape: {x.shape}")
555
+
556
+ # Apply transposed convolution
557
+ y = self.convtr(x)
558
+
559
+ if debug:
560
+ print(f"[DEBUG NON-STREAMING] After transposed conv: {y.shape}")
561
+
562
+ # Calculate and remove padding
563
+ if self.causal:
564
+ padding_right = math.ceil(self.padding_total * self.trim_right_ratio)
565
+ padding_left = self.padding_total - padding_right
566
+ else:
567
+ padding_right = self.padding_total // 2
568
+ padding_left = self.padding_total - padding_right
569
+
570
+ if padding_left + padding_right > 0:
571
+ y = unpad1d(y, (padding_left, padding_right))
572
+
573
+ if debug:
574
+ print(f"[DEBUG NON-STREAMING] Final output shape: {y.shape}")
575
+
576
+ return y
577
+
578
+ # FFN
579
+ class FFN(nn.Module):
580
+ def __init__(
581
+ self,
582
+ embed_dim,
583
+ ffn_dim,
584
+ bias=False,
585
+ ):
586
+ super().__init__()
587
+ self.embed_dim = embed_dim
588
+ self.linear1 = nn.Linear(self.embed_dim, ffn_dim, bias=bias)
589
+ self.gelu = ACT2FN["gelu"]
590
+ self.linear2 = nn.Linear(ffn_dim, self.embed_dim, bias=bias)
591
+
592
+ def forward(self, x):
593
+ x = self.linear1(x)
594
+ x = self.gelu(x)
595
+ x = self.linear2(x)
596
+ return x
597
+
598
+
599
+ class Convlayer(nn.Module):
600
+ def __init__(
601
+ self,
602
+ in_channels,
603
+ out_channels,
604
+ kernel_size,
605
+ stride=1,
606
+ dilation=1,
607
+ groups=1,
608
+ bias=True,
609
+ pad_mode='zeros',
610
+ norm='weight_norm',
611
+ causal=True,
612
+ ):
613
+ super().__init__()
614
+ self.conv = SConv1d(in_channels, out_channels, kernel_size, stride=stride, dilation=dilation,
615
+ groups=groups, bias=bias, pad_mode=pad_mode, norm=norm, causal=causal)
616
+
617
+ def forward(self, x):
618
+ return self.conv(x)
619
+
620
+ class Block1D(nn.Module):
621
+ def __init__(self, dim, kernel_size=7, drop_path=0., mixer_layer='conv',
622
+ layer_scale_init_value=1e-6, **kwargs):
623
+ super().__init__()
624
+
625
+ if kwargs.get('layernorm', 'LN') == 'LN':
626
+ self.norm = ConvLayerNorm(dim, eps=kwargs.get('eps', 1e-6))
627
+ self.ffn_norm = ConvLayerNorm(dim, eps=kwargs.get('eps', 1e-6))
628
+ elif kwargs.get('layernorm', 'RMSNorm') == 'RMSNorm':
629
+ self.norm = ConvRMSNorm(dim, eps=kwargs.get('eps', 1e-6))
630
+ self.ffn_norm = ConvRMSNorm(dim, eps=kwargs.get('eps', 1e-6))
631
+
632
+ if mixer_layer == 'conv':
633
+ self.mixer = Convlayer(dim, dim, groups=kwargs.get('groups', 1),
634
+ kernel_size=kernel_size,
635
+ pad_mode=kwargs.get('pad_mode', 'reflect'),
636
+ norm=kwargs.get('norm', 'none'),
637
+ causal=kwargs.get('causal', True),
638
+ bias=kwargs.get('bias', True),
639
+ )
640
+ elif mixer_layer == 'depthwise_conv':
641
+ self.mixer = Convlayer(dim, dim, groups=dim,
642
+ kernel_size=kernel_size,
643
+ pad_mode=kwargs.get('pad_mode', 'reflect'),
644
+ norm=kwargs.get('norm', 'none'),
645
+ causal=kwargs.get('causal', True),
646
+ bias=kwargs.get('bias', True),
647
+ )
648
+ else:
649
+ raise ValueError(f"Unsupported mixer layer: {mixer_layer}")
650
+
651
+ self.ffn = FFN(
652
+ dim,
653
+ kwargs.get('ffn_expansion', 4) * dim,
654
+ bias=kwargs.get('bias', False),
655
+ )
656
+ self.drop_path = nn.Identity() if drop_path <= 0. else nn.modules.DropPath(drop_path)
657
+
658
+ if layer_scale_init_value > 0:
659
+ self.gamma = nn.Parameter(layer_scale_init_value * torch.ones((dim)), requires_grad=True)
660
+ self.ffn_gamma = nn.Parameter(layer_scale_init_value * torch.ones((dim)), requires_grad=True)
661
+ else:
662
+ self.gamma = None
663
+ self.ffn_gamma = None
664
+
665
+ def forward(self, x):
666
+ # mixer
667
+ residual = x
668
+ x = self.norm(x)
669
+ x = self.mixer(x)
670
+ if self.gamma is not None:
671
+ x = x * self.gamma.unsqueeze(-1)
672
+ x = residual + self.drop_path(x)
673
+
674
+ # ffn
675
+ residual = x
676
+ x = self.ffn_norm(x)
677
+ x = x.permute(0, 2, 1)
678
+ x = self.ffn(x)
679
+ x = x.permute(0, 2, 1)
680
+ if self.ffn_gamma is not None:
681
+ x = x * self.ffn_gamma.unsqueeze(-1)
682
+ x = residual + self.drop_path(x)
683
+
684
+ return x
685
+
686
+
687
+ class TokenizerEncoder(nn.Module):
688
+ """
689
+ Encoder component for the VibeVoice tokenizer that converts audio to latent representations.
690
+
691
+ Args:
692
+ config: Configuration object with model parameters
693
+ """
694
+ def __init__(self, config):
695
+ super().__init__()
696
+
697
+ # Extract parameters from config
698
+ self.channels = config.channels
699
+ self.dimension = config.dimension
700
+ self.n_filters = config.n_filters
701
+ self.ratios = list(reversed(config.ratios))
702
+ self.depths = config.depths
703
+ self.n_residual_layers = getattr(config, "n_residual_layers", 1)
704
+ self.hop_length = np.prod(self.ratios)
705
+ self.causal = config.causal
706
+
707
+ # Additional config parameters with defaults
708
+ kernel_size = getattr(config, "kernel_size", 7)
709
+ last_kernel_size = getattr(config, "last_kernel_size", 7)
710
+ norm = getattr(config, "norm", "none")
711
+ norm_params = getattr(config, "norm_params", {})
712
+ pad_mode = getattr(config, "pad_mode", "reflect")
713
+ bias = getattr(config, "bias", True)
714
+ layernorm = getattr(config, "layernorm", "LN")
715
+ layernorm_eps = getattr(config, "layernorm_eps", 1e-6)
716
+ layernorm_elementwise_affine = getattr(config, "layernorm_elementwise_affine", True)
717
+ drop_path_rate = getattr(config, "drop_path_rate", 0.0)
718
+ mixer_layer = getattr(config, "mixer_layer", "conv")
719
+ layer_scale_init_value = getattr(config, "layer_scale_init_value", 0)
720
+ disable_last_norm = getattr(config, "disable_last_norm", False)
721
+
722
+ # determine the norm type based on layernorm
723
+ if layernorm == 'LN':
724
+ norm_type = ConvLayerNorm
725
+ elif layernorm == 'RMSNorm':
726
+ norm_type = partial(ConvRMSNorm, elementwise_affine=layernorm_elementwise_affine)
727
+ else:
728
+ raise ValueError(f"Unsupported norm type: {layernorm}")
729
+
730
+ # stem and intermediate downsampling conv layers
731
+ stem = nn.Sequential(
732
+ SConv1d(self.channels, self.n_filters, kernel_size, norm=norm, norm_kwargs=norm_params, causal=self.causal, pad_mode=pad_mode, bias=bias),
733
+ )
734
+
735
+ self.downsample_layers = nn.ModuleList()
736
+ self.downsample_layers.append(stem)
737
+ for i in range(len(self.ratios)):
738
+ in_ch = self.n_filters * (2 ** i)
739
+ out_ch = self.n_filters * (2 ** (i + 1))
740
+ downsample_layer = nn.Sequential(
741
+ SConv1d(in_ch, out_ch, kernel_size=self.ratios[i] * 2, stride=self.ratios[i], causal=self.causal, pad_mode=pad_mode, norm=norm, bias=bias)
742
+ )
743
+ self.downsample_layers.append(downsample_layer)
744
+
745
+ # configure the transformer blocks
746
+ layer_type = partial(
747
+ Block1D,
748
+ mixer_layer=mixer_layer,
749
+ layernorm=layernorm,
750
+ eps=layernorm_eps,
751
+ causal=self.causal,
752
+ pad_mode=pad_mode,
753
+ norm=norm,
754
+ bias=bias,
755
+ layer_scale_init_value=layer_scale_init_value,
756
+ )
757
+
758
+ self.stages = nn.ModuleList()
759
+ dp_rates = list(np.linspace(0, drop_path_rate, sum(self.depths)).tolist())
760
+ cur = 0
761
+
762
+ for i in range(len(self.depths)):
763
+ in_ch = self.n_filters * (2 ** i)
764
+ stage = nn.Sequential(
765
+ *[layer_type(dim=in_ch, drop_path=dp_rates[cur + j]) for j in range(self.depths[i])]
766
+ )
767
+ self.stages.append(stage)
768
+ cur += self.depths[i]
769
+
770
+ if not disable_last_norm:
771
+ self.norm = norm_type(in_ch, eps=layernorm_eps)
772
+ else:
773
+ self.norm = nn.Identity()
774
+ self.head = SConv1d(in_ch, self.dimension, kernel_size=last_kernel_size, causal=self.causal, pad_mode=pad_mode, norm=norm, bias=bias)
775
+
776
+ def forward_features(self, x, cache=None, sample_indices=None, use_cache=False, debug=False):
777
+ for i in range(len(self.depths)):
778
+ # Apply downsampling
779
+ for layer in self.downsample_layers[i]:
780
+ if isinstance(layer, SConv1d):
781
+ x = layer(x, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
782
+ else:
783
+ x = layer(x)
784
+
785
+ # Apply stage (Block1D contains Convlayer which contains SConv1d)
786
+ for block in self.stages[i]:
787
+ if hasattr(block, 'mixer') and hasattr(block.mixer, 'conv') and isinstance(block.mixer.conv, SConv1d):
788
+ # Block1D forward with cache support
789
+ residual = x
790
+ x = block.norm(x)
791
+ x = block.mixer.conv(x, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
792
+ if block.gamma is not None:
793
+ x = x * block.gamma.unsqueeze(-1)
794
+ x = residual + x
795
+
796
+ # FFN part
797
+ residual = x
798
+ x = block.ffn_norm(x)
799
+ x = x.permute(0, 2, 1)
800
+ x = block.ffn(x)
801
+ x = x.permute(0, 2, 1)
802
+ if block.ffn_gamma is not None:
803
+ x = x * block.ffn_gamma.unsqueeze(-1)
804
+ x = residual + x
805
+ else:
806
+ x = block(x)
807
+
808
+ return self.norm(x)
809
+
810
+ def forward(self, x, cache=None, sample_indices=None, use_cache=False, debug=False):
811
+ x = self.forward_features(x, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
812
+ x = self.head(x, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
813
+ return x
814
+
815
+
816
+ class TokenizerDecoder(nn.Module):
817
+ """
818
+ Decoder component for the VibeVoice tokenizer that converts latent representations back to audio.
819
+
820
+ Args:
821
+ config: Configuration object with model parameters
822
+ """
823
+ def __init__(self, config):
824
+ super().__init__()
825
+
826
+ # Extract parameters from config
827
+ self.dimension = config.dimension
828
+ self.channels = config.channels
829
+ self.n_filters = config.n_filters
830
+ self.ratios = config.ratios
831
+
832
+ # IMPORTANT CHANGE: Don't reverse depths again since they're already reversed in VibeVoiceAcousticTokenizerModel
833
+ self.depths = config.depths # Changed from list(reversed(config.depths))
834
+
835
+ self.n_residual_layers = getattr(config, "n_residual_layers", 1)
836
+ self.hop_length = np.prod(self.ratios)
837
+ self.causal = config.causal
838
+
839
+ # Additional config parameters with defaults
840
+ kernel_size = getattr(config, "kernel_size", 7)
841
+ last_kernel_size = getattr(config, "last_kernel_size", 7)
842
+ norm = getattr(config, "norm", "none")
843
+ norm_params = getattr(config, "norm_params", {})
844
+ pad_mode = getattr(config, "pad_mode", "reflect")
845
+ bias = getattr(config, "bias", True)
846
+ layernorm = getattr(config, "layernorm", "LN")
847
+ layernorm_eps = getattr(config, "layernorm_eps", 1e-6)
848
+ trim_right_ratio = getattr(config, "trim_right_ratio", 1.0)
849
+ layernorm_elementwise_affine = getattr(config, "layernorm_elementwise_affine", True)
850
+ drop_path_rate = getattr(config, "drop_path_rate", 0.0)
851
+ mixer_layer = getattr(config, "mixer_layer", "conv")
852
+ layer_scale_init_value = getattr(config, "layer_scale_init_value", 0)
853
+ disable_last_norm = getattr(config, "disable_last_norm", False)
854
+
855
+ # determine the norm type based on layernorm
856
+ if layernorm == 'LN':
857
+ norm_type = ConvLayerNorm
858
+ elif layernorm == 'RMSNorm':
859
+ norm_type = partial(ConvRMSNorm, elementwise_affine=layernorm_elementwise_affine)
860
+ else:
861
+ raise ValueError(f"Unsupported norm type: {layernorm}")
862
+
863
+ # stem and upsampling layers
864
+ stem = nn.Sequential(
865
+ SConv1d(self.dimension, self.n_filters * 2 ** (len(self.depths) - 1), kernel_size, norm=norm,
866
+ norm_kwargs=norm_params, causal=self.causal, pad_mode=pad_mode, bias=bias),
867
+ )
868
+
869
+ self.upsample_layers = nn.ModuleList()
870
+ self.upsample_layers.append(stem)
871
+ for i in range(len(self.ratios)):
872
+ in_ch = self.n_filters * (2 ** (len(self.depths) - 1 - i))
873
+ out_ch = self.n_filters * (2 ** (len(self.depths) - 1 - i - 1))
874
+ upsample_layer = nn.Sequential(
875
+ SConvTranspose1d(in_ch, out_ch,
876
+ kernel_size=self.ratios[i] * 2, stride=self.ratios[i],
877
+ norm=norm, norm_kwargs=norm_params, bias=bias,
878
+ causal=self.causal, trim_right_ratio=trim_right_ratio),
879
+ )
880
+ self.upsample_layers.append(upsample_layer)
881
+
882
+ # configure transformer blocks
883
+ layer_type = partial(
884
+ Block1D,
885
+ mixer_layer=mixer_layer,
886
+ layernorm=layernorm,
887
+ eps=layernorm_eps,
888
+ causal=self.causal,
889
+ pad_mode=pad_mode,
890
+ norm=norm,
891
+ bias=bias,
892
+ layer_scale_init_value=layer_scale_init_value,
893
+ )
894
+
895
+ self.stages = nn.ModuleList()
896
+ dp_rates = list(np.linspace(0, drop_path_rate, sum(self.depths)).tolist())
897
+ cur = 0
898
+
899
+ # Create stages in the same order as the original model
900
+ for i in range(len(self.depths)):
901
+ in_ch = self.n_filters * (2 ** (len(self.depths) - 1 - i))
902
+ stage = nn.Sequential(
903
+ *[layer_type(dim=in_ch, drop_path=dp_rates[cur + j]) for j in range(self.depths[i])]
904
+ )
905
+ self.stages.append(stage)
906
+ cur += self.depths[i]
907
+
908
+ if not disable_last_norm:
909
+ self.norm = norm_type(in_ch, eps=layernorm_eps)
910
+ else:
911
+ self.norm = nn.Identity()
912
+ self.head = SConv1d(in_ch, self.channels, kernel_size=last_kernel_size, causal=self.causal, pad_mode=pad_mode, norm=norm, bias=bias)
913
+
914
+ def forward_features(self, x, cache=None, sample_indices=None, use_cache=False, debug=False):
915
+ for i in range(len(self.depths)):
916
+ # Apply upsampling
917
+ for layer in self.upsample_layers[i]:
918
+ if isinstance(layer, (SConv1d, SConvTranspose1d)):
919
+ x = layer(x, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
920
+ else:
921
+ x = layer(x)
922
+
923
+ # Apply stage (Block1D contains Convlayer which contains SConv1d)
924
+ for block in self.stages[i]:
925
+ if hasattr(block, 'mixer') and hasattr(block.mixer, 'conv') and isinstance(block.mixer.conv, SConv1d):
926
+ # Block1D forward with cache support
927
+ residual = x
928
+ x = block.norm(x)
929
+ x = block.mixer.conv(x, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
930
+ if block.gamma is not None:
931
+ x = x * block.gamma.unsqueeze(-1)
932
+ x = residual + x
933
+
934
+ # FFN part
935
+ residual = x
936
+ x = block.ffn_norm(x)
937
+ x = x.permute(0, 2, 1)
938
+ x = block.ffn(x)
939
+ x = x.permute(0, 2, 1)
940
+ if block.ffn_gamma is not None:
941
+ x = x * block.ffn_gamma.unsqueeze(-1)
942
+ x = residual + x
943
+ else:
944
+ x = block(x)
945
+
946
+ return self.norm(x)
947
+
948
+ def forward(self, x, cache=None, sample_indices=None, use_cache=False, debug=False):
949
+ x = self.forward_features(x, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
950
+ x = self.head(x, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
951
+ return x
952
+
953
+
954
+ @dataclass
955
+ class VibeVoiceTokenizerEncoderOutput:
956
+ """
957
+ Output of VibeVoice tokenizer encoder, representing a Gaussian distribution with fixed variance.
958
+
959
+ Args:
960
+ mean (`torch.FloatTensor`): The mean parameters of the distribution.
961
+ std (`float` or `torch.FloatTensor`): Fixed standard deviation value.
962
+ """
963
+ mean: torch.Tensor
964
+ std: Optional[Union[float, torch.Tensor]] = None
965
+
966
+ def sample(self, dist_type='fix'):
967
+ """
968
+ Sample from the distribution.
969
+
970
+ Args:
971
+ dist_type (`str`): Sampling method, either 'fix' or 'gaussian'.
972
+
973
+ Returns:
974
+ `torch.FloatTensor`: Sampled values.
975
+ `torch.FloatTensor` (optional): Standard deviation used (only when dist_type='gaussian').
976
+ """
977
+ if dist_type == 'fix':
978
+ x = self.mean + self.std * torch.randn_like(self.mean)
979
+ return x, self.std
980
+ elif dist_type == 'gaussian':
981
+ batch_size = self.mean.size(0)
982
+ value = self.std / 0.8
983
+ std = torch.randn(batch_size, device=self.mean.device, dtype=self.mean.dtype) * value
984
+
985
+ while std.dim() < self.mean.dim():
986
+ std = std.unsqueeze(-1)
987
+
988
+ x = self.mean + std * torch.randn_like(self.mean)
989
+ return x, std
990
+ else:
991
+ return self.mean, self.std
992
+
993
+ def kl(self):
994
+ """Compute KL divergence between this distribution and a standard normal."""
995
+ target = torch.zeros_like(self.mean)
996
+ return F.mse_loss(self.mean, target, reduction='none')
997
+
998
+ def mode(self):
999
+ """Return the distribution mode (which is the mean for Gaussian)."""
1000
+ return self.mean
1001
+
1002
+ class VibeVoiceAcousticTokenizerModel(PreTrainedModel):
1003
+ """VibeVoice speech tokenizer model combining encoder and decoder for acoustic tokens"""
1004
+
1005
+ config_class = VibeVoiceAcousticTokenizerConfig
1006
+ base_model_prefix = "vibevoice_acoustic_tokenizer"
1007
+ _supports_flash_attn_2 = True
1008
+ _supports_sdpa = True
1009
+ _no_split_modules = ["TokenizerEncoder", "TokenizerDecoder"]
1010
+
1011
+ def __init__(self, config):
1012
+ super().__init__(config)
1013
+
1014
+ self.register_buffer('fix_std', torch.tensor(config.fix_std), persistent=False)
1015
+ self.std_dist_type = getattr(config, "std_dist_type", "fix")
1016
+
1017
+ # Parse encoder depths
1018
+ if isinstance(config.encoder_depths, str):
1019
+ encoder_depths = [int(d) for d in config.encoder_depths.split('-')]
1020
+ else:
1021
+ encoder_depths = config.encoder_depths
1022
+
1023
+ # Parse decoder depths if provided
1024
+ if config.decoder_depths is not None and isinstance(config.decoder_depths, str):
1025
+ decoder_depths = [int(d) for d in config.decoder_depths.split('-')]
1026
+ else:
1027
+ # Default: use reversed encoder depths if decoder_depths is None
1028
+ decoder_depths = list(reversed(encoder_depths))
1029
+
1030
+ # Create encoder config
1031
+ encoder_config = copy.deepcopy(config)
1032
+ encoder_config.dimension = config.vae_dim
1033
+ encoder_config.n_filters = config.encoder_n_filters
1034
+ encoder_config.ratios = config.encoder_ratios
1035
+ encoder_config.depths = encoder_depths
1036
+ encoder_config.norm = config.conv_norm
1037
+ encoder_config.pad_mode = config.pad_mode
1038
+ encoder_config.bias = config.conv_bias
1039
+ encoder_config.layernorm_eps = config.layernorm_eps
1040
+ encoder_config.layernorm_elementwise_affine = config.layernorm_elementwise_affine
1041
+ encoder_config.mixer_layer = config.mixer_layer
1042
+ encoder_config.layer_scale_init_value = config.layer_scale_init_value
1043
+ encoder_config.disable_last_norm = config.disable_last_norm
1044
+
1045
+ # Create decoder config
1046
+ decoder_config = copy.deepcopy(config)
1047
+ decoder_config.dimension = config.vae_dim
1048
+ decoder_config.n_filters = config.decoder_n_filters
1049
+ decoder_config.ratios = config.decoder_ratios
1050
+ decoder_config.depths = decoder_depths
1051
+ decoder_config.norm = config.conv_norm
1052
+ decoder_config.pad_mode = config.pad_mode
1053
+ decoder_config.bias = config.conv_bias
1054
+ decoder_config.layernorm_eps = config.layernorm_eps
1055
+ decoder_config.layernorm_elementwise_affine = config.layernorm_elementwise_affine
1056
+ decoder_config.mixer_layer = config.mixer_layer
1057
+ decoder_config.layer_scale_init_value = config.layer_scale_init_value
1058
+ decoder_config.disable_last_norm = config.disable_last_norm
1059
+
1060
+ # Initialize encoder and decoder
1061
+ self.encoder = TokenizerEncoder(encoder_config)
1062
+ self.decoder = TokenizerDecoder(decoder_config)
1063
+
1064
+ # Initialize weights
1065
+ self.apply(self._init_weights)
1066
+
1067
+ def _init_weights(self, module):
1068
+ """Initialize weights for the model"""
1069
+ if isinstance(module, nn.Linear):
1070
+ nn.init.normal_(module.weight, std=self.config.weight_init_value)
1071
+ if module.bias is not None:
1072
+ nn.init.zeros_(module.bias)
1073
+ elif isinstance(module, nn.LayerNorm):
1074
+ nn.init.ones_(module.weight)
1075
+ nn.init.zeros_(module.bias)
1076
+ elif isinstance(module, nn.Conv1d):
1077
+ nn.init.normal_(module.weight, std=self.config.weight_init_value)
1078
+ if module.bias is not None:
1079
+ nn.init.zeros_(module.bias)
1080
+
1081
+ @torch.no_grad()
1082
+ def encode(self, audio, cache=None, sample_indices=None, use_cache=False, debug=False):
1083
+ """Convert audio to latent representations"""
1084
+ latents = self.encoder(audio, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
1085
+ return VibeVoiceTokenizerEncoderOutput(mean=latents.permute(0, 2, 1), std=self.fix_std)
1086
+
1087
+ @torch.no_grad()
1088
+ def sampling(self, encoder_output, dist_type=None):
1089
+ """Sample from the encoder output distribution"""
1090
+ dist_type = dist_type or self.std_dist_type
1091
+
1092
+ if dist_type == 'fix':
1093
+ return encoder_output.sample(dist_type='fix')
1094
+ elif dist_type == 'gaussian':
1095
+ return encoder_output.sample(dist_type='gaussian')
1096
+ else:
1097
+ raise ValueError(f"Unsupported dist_type: {dist_type}, expected 'fix' or 'gaussian'")
1098
+
1099
+ @torch.no_grad()
1100
+ def decode(self, latents, cache=None, sample_indices=None, use_cache=False, debug=False):
1101
+ """Convert latent representations back to audio"""
1102
+ if latents.shape[1] == self.config.vae_dim:
1103
+ pass
1104
+ else:
1105
+ latents = latents.permute(0, 2, 1)
1106
+
1107
+ audio = self.decoder(latents, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
1108
+ return audio
1109
+
1110
+ def forward(self, audio, cache=None, sample_indices=None, use_cache=False, debug=False):
1111
+ """Full forward pass: encode audio to latents, then decode back to audio"""
1112
+ encoder_output = self.encode(audio, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
1113
+ sampled_latents, _ = self.sampling(encoder_output)
1114
+ reconstructed = self.decode(sampled_latents, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
1115
+ return reconstructed, sampled_latents
1116
+
1117
+
1118
+ class VibeVoiceSemanticTokenizerModel(PreTrainedModel):
1119
+ """VibeVoice speech tokenizer model with only encoder for semantic tokens"""
1120
+
1121
+ config_class = VibeVoiceSemanticTokenizerConfig
1122
+ base_model_prefix = "vibevoice_semantic_tokenizer"
1123
+ _supports_flash_attn_2 = True
1124
+ _supports_sdpa = True
1125
+ _no_split_modules = ["TokenizerEncoder"]
1126
+
1127
+ def __init__(self, config):
1128
+ super().__init__(config)
1129
+
1130
+ # Parse encoder depths
1131
+ if isinstance(config.encoder_depths, str):
1132
+ encoder_depths = [int(d) for d in config.encoder_depths.split('-')]
1133
+ else:
1134
+ encoder_depths = config.encoder_depths
1135
+
1136
+ # Create encoder config
1137
+ encoder_config = copy.deepcopy(config)
1138
+ encoder_config.dimension = config.vae_dim
1139
+ encoder_config.n_filters = config.encoder_n_filters
1140
+ encoder_config.ratios = config.encoder_ratios
1141
+ encoder_config.depths = encoder_depths
1142
+ encoder_config.norm = config.conv_norm
1143
+ encoder_config.pad_mode = config.pad_mode
1144
+ encoder_config.bias = config.conv_bias
1145
+ encoder_config.layernorm_eps = config.layernorm_eps
1146
+ encoder_config.layernorm_elementwise_affine = config.layernorm_elementwise_affine
1147
+ encoder_config.mixer_layer = config.mixer_layer
1148
+ encoder_config.layer_scale_init_value = config.layer_scale_init_value
1149
+ encoder_config.disable_last_norm = config.disable_last_norm
1150
+
1151
+ # Initialize encoder and decoder
1152
+ self.encoder = TokenizerEncoder(encoder_config)
1153
+
1154
+ # Initialize weights
1155
+ self.apply(self._init_weights)
1156
+
1157
+ def _init_weights(self, module):
1158
+ """Initialize weights for the model"""
1159
+ if isinstance(module, nn.Linear):
1160
+ nn.init.normal_(module.weight, std=self.config.weight_init_value)
1161
+ if module.bias is not None:
1162
+ nn.init.zeros_(module.bias)
1163
+ elif isinstance(module, nn.LayerNorm):
1164
+ nn.init.ones_(module.weight)
1165
+ nn.init.zeros_(module.bias)
1166
+ elif isinstance(module, nn.Conv1d):
1167
+ nn.init.normal_(module.weight, std=self.config.weight_init_value)
1168
+ if module.bias is not None:
1169
+ nn.init.zeros_(module.bias)
1170
+
1171
+ @torch.no_grad()
1172
+ def encode(self, audio, cache=None, sample_indices=None, use_cache=False, debug=False):
1173
+ """Convert audio to latent representations"""
1174
+ latents = self.encoder(audio, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
1175
+ return VibeVoiceTokenizerEncoderOutput(mean=latents.permute(0, 2, 1))
1176
+
1177
+ @torch.no_grad()
1178
+ def sampling(self, encoder_output, dist_type=None):
1179
+ """Sample from the encoder output distribution"""
1180
+ return encoder_output.sample(dist_type='none')
1181
+
1182
+ def forward(self, audio, cache=None, sample_indices=None, use_cache=False, debug=False):
1183
+ """Full forward pass: encode audio to latents, then decode back to audio"""
1184
+ encoder_output = self.encode(audio, cache=cache, sample_indices=sample_indices, use_cache=use_cache, debug=debug)
1185
+ sampled_latents, _ = self.sampling(encoder_output, dist_type='none')
1186
+ return None, sampled_latents
1187
+
1188
+ AutoModel.register(VibeVoiceAcousticTokenizerConfig, VibeVoiceAcousticTokenizerModel, exist_ok=True)
1189
+ AutoModel.register(VibeVoiceSemanticTokenizerConfig, VibeVoiceSemanticTokenizerModel, exist_ok=True)
1190
+
1191
+ __all__ = [
1192
+ "VibeVoiceTokenizerStreamingCache",
1193
+ "VibeVoiceAcousticTokenizerModel",
1194
+ "VibeVoiceSemanticTokenizerModel",
1195
+ ]
VibeVoice-tpu/src/vibevoice/modular/streamer.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import torch
4
+
5
+ import asyncio
6
+ from queue import Queue
7
+ from typing import TYPE_CHECKING, Optional
8
+
9
+
10
+ from transformers.generation import BaseStreamer
11
+
12
+
13
+ class AudioStreamer(BaseStreamer):
14
+ """
15
+ Audio streamer that stores audio chunks in queues for each sample in the batch.
16
+ This allows streaming audio generation for multiple samples simultaneously.
17
+
18
+ Parameters:
19
+ batch_size (`int`):
20
+ The batch size for generation
21
+ stop_signal (`any`, *optional*):
22
+ The signal to put in the queue when generation ends. Defaults to None.
23
+ timeout (`float`, *optional*):
24
+ The timeout for the audio queue. If `None`, the queue will block indefinitely.
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ batch_size: int,
30
+ stop_signal: Optional[any] = None,
31
+ timeout: Optional[float] = None,
32
+ ):
33
+ self.batch_size = batch_size
34
+ self.stop_signal = stop_signal
35
+ self.timeout = timeout
36
+
37
+ # Create a queue for each sample in the batch
38
+ self.audio_queues = [Queue() for _ in range(batch_size)]
39
+ self.finished_flags = [False for _ in range(batch_size)]
40
+ self.sample_indices_map = {} # Maps from sample index to queue index
41
+
42
+ def put(self, audio_chunks: torch.Tensor, sample_indices: torch.Tensor):
43
+ """
44
+ Receives audio chunks and puts them in the appropriate queues.
45
+
46
+ Args:
47
+ audio_chunks: Tensor of shape (num_samples, ...) containing audio chunks
48
+ sample_indices: Tensor indicating which samples these chunks belong to
49
+ """
50
+ for i, sample_idx in enumerate(sample_indices):
51
+ idx = sample_idx.item()
52
+ if idx < self.batch_size and not self.finished_flags[idx]:
53
+ # Convert to numpy or keep as tensor based on preference
54
+ audio_chunk = audio_chunks[i].detach().cpu()
55
+ self.audio_queues[idx].put(audio_chunk, timeout=self.timeout)
56
+
57
+ def end(self, sample_indices: Optional[torch.Tensor] = None):
58
+ """
59
+ Signals the end of generation for specified samples or all samples.
60
+
61
+ Args:
62
+ sample_indices: Optional tensor of sample indices to end. If None, ends all.
63
+ """
64
+ if sample_indices is None:
65
+ # End all samples
66
+ for idx in range(self.batch_size):
67
+ if not self.finished_flags[idx]:
68
+ self.audio_queues[idx].put(self.stop_signal, timeout=self.timeout)
69
+ self.finished_flags[idx] = True
70
+ else:
71
+ # End specific samples
72
+ for sample_idx in sample_indices:
73
+ idx = sample_idx.item() if torch.is_tensor(sample_idx) else sample_idx
74
+ if idx < self.batch_size and not self.finished_flags[idx]:
75
+ self.audio_queues[idx].put(self.stop_signal, timeout=self.timeout)
76
+ self.finished_flags[idx] = True
77
+
78
+ def __iter__(self):
79
+ """Returns an iterator over the batch of audio streams."""
80
+ return AudioBatchIterator(self)
81
+
82
+ def get_stream(self, sample_idx: int):
83
+ """Get the audio stream for a specific sample."""
84
+ if sample_idx >= self.batch_size:
85
+ raise ValueError(f"Sample index {sample_idx} exceeds batch size {self.batch_size}")
86
+ return AudioSampleIterator(self, sample_idx)
87
+
88
+
89
+ class AudioSampleIterator:
90
+ """Iterator for a single audio stream from the batch."""
91
+
92
+ def __init__(self, streamer: AudioStreamer, sample_idx: int):
93
+ self.streamer = streamer
94
+ self.sample_idx = sample_idx
95
+
96
+ def __iter__(self):
97
+ return self
98
+
99
+ def __next__(self):
100
+ value = self.streamer.audio_queues[self.sample_idx].get(timeout=self.streamer.timeout)
101
+ if value == self.streamer.stop_signal:
102
+ raise StopIteration()
103
+ return value
104
+
105
+
106
+ class AudioBatchIterator:
107
+ """Iterator that yields audio chunks for all samples in the batch."""
108
+
109
+ def __init__(self, streamer: AudioStreamer):
110
+ self.streamer = streamer
111
+ self.active_samples = set(range(streamer.batch_size))
112
+
113
+ def __iter__(self):
114
+ return self
115
+
116
+ def __next__(self):
117
+ if not self.active_samples:
118
+ raise StopIteration()
119
+
120
+ batch_chunks = {}
121
+ samples_to_remove = set()
122
+
123
+ # Try to get chunks from all active samples
124
+ for idx in self.active_samples:
125
+ try:
126
+ value = self.streamer.audio_queues[idx].get(block=False)
127
+ if value == self.streamer.stop_signal:
128
+ samples_to_remove.add(idx)
129
+ else:
130
+ batch_chunks[idx] = value
131
+ except:
132
+ # Queue is empty for this sample, skip it this iteration
133
+ pass
134
+
135
+ # Remove finished samples
136
+ self.active_samples -= samples_to_remove
137
+
138
+ if batch_chunks:
139
+ return batch_chunks
140
+ elif self.active_samples:
141
+ # If no chunks were ready but we still have active samples,
142
+ # wait a bit and try again
143
+ import time
144
+ time.sleep(0.01)
145
+ return self.__next__()
146
+ else:
147
+ raise StopIteration()
148
+
149
+
150
+ class AsyncAudioStreamer(AudioStreamer):
151
+ """
152
+ Async version of AudioStreamer for use in async contexts.
153
+ """
154
+
155
+ def __init__(
156
+ self,
157
+ batch_size: int,
158
+ stop_signal: Optional[any] = None,
159
+ timeout: Optional[float] = None,
160
+ ):
161
+ super().__init__(batch_size, stop_signal, timeout)
162
+ # Replace regular queues with async queues
163
+ self.audio_queues = [asyncio.Queue() for _ in range(batch_size)]
164
+ self.loop = asyncio.get_running_loop()
165
+
166
+ def put(self, audio_chunks: torch.Tensor, sample_indices: torch.Tensor):
167
+ """Put audio chunks in the appropriate async queues."""
168
+ for i, sample_idx in enumerate(sample_indices):
169
+ idx = sample_idx.item()
170
+ if idx < self.batch_size and not self.finished_flags[idx]:
171
+ audio_chunk = audio_chunks[i].detach().cpu()
172
+ self.loop.call_soon_threadsafe(
173
+ self.audio_queues[idx].put_nowait, audio_chunk
174
+ )
175
+
176
+ def end(self, sample_indices: Optional[torch.Tensor] = None):
177
+ """Signal the end of generation for specified samples."""
178
+ if sample_indices is None:
179
+ indices_to_end = range(self.batch_size)
180
+ else:
181
+ indices_to_end = [s.item() if torch.is_tensor(s) else s for s in sample_indices]
182
+
183
+ for idx in indices_to_end:
184
+ if idx < self.batch_size and not self.finished_flags[idx]:
185
+ self.loop.call_soon_threadsafe(
186
+ self.audio_queues[idx].put_nowait, self.stop_signal
187
+ )
188
+ self.finished_flags[idx] = True
189
+
190
+ async def get_stream(self, sample_idx: int):
191
+ """Get async iterator for a specific sample's audio stream."""
192
+ if sample_idx >= self.batch_size:
193
+ raise ValueError(f"Sample index {sample_idx} exceeds batch size {self.batch_size}")
194
+
195
+ while True:
196
+ value = await self.audio_queues[sample_idx].get()
197
+ if value == self.stop_signal:
198
+ break
199
+ yield value
200
+
201
+ def __aiter__(self):
202
+ """Returns an async iterator over all audio streams."""
203
+ return AsyncAudioBatchIterator(self)
204
+
205
+
206
+ class AsyncAudioBatchIterator:
207
+ """Async iterator for batch audio streaming."""
208
+
209
+ def __init__(self, streamer: AsyncAudioStreamer):
210
+ self.streamer = streamer
211
+ self.active_samples = set(range(streamer.batch_size))
212
+
213
+ def __aiter__(self):
214
+ return self
215
+
216
+ async def __anext__(self):
217
+ if not self.active_samples:
218
+ raise StopAsyncIteration()
219
+
220
+ batch_chunks = {}
221
+ samples_to_remove = set()
222
+
223
+ # Create tasks for all active samples
224
+ tasks = {
225
+ idx: asyncio.create_task(self._get_chunk(idx))
226
+ for idx in self.active_samples
227
+ }
228
+
229
+ # Wait for at least one chunk to be ready
230
+ done, pending = await asyncio.wait(
231
+ tasks.values(),
232
+ return_when=asyncio.FIRST_COMPLETED,
233
+ timeout=self.streamer.timeout
234
+ )
235
+
236
+ # Cancel pending tasks
237
+ for task in pending:
238
+ task.cancel()
239
+
240
+ # Process completed tasks
241
+ for idx, task in tasks.items():
242
+ if task in done:
243
+ try:
244
+ value = await task
245
+ if value == self.streamer.stop_signal:
246
+ samples_to_remove.add(idx)
247
+ else:
248
+ batch_chunks[idx] = value
249
+ except asyncio.CancelledError:
250
+ pass
251
+
252
+ self.active_samples -= samples_to_remove
253
+
254
+ if batch_chunks:
255
+ return batch_chunks
256
+ elif self.active_samples:
257
+ # Try again if we still have active samples
258
+ return await self.__anext__()
259
+ else:
260
+ raise StopAsyncIteration()
261
+
262
+ async def _get_chunk(self, idx):
263
+ """Helper to get a chunk from a specific queue."""
264
+ return await self.streamer.audio_queues[idx].get()
VibeVoice-tpu/src/vibevoice/processor/__init__.py ADDED
File without changes
VibeVoice-tpu/src/vibevoice/processor/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (177 Bytes). View file
 
VibeVoice-tpu/src/vibevoice/processor/__pycache__/vibevoice_processor.cpython-311.pyc ADDED
Binary file (33.3 kB). View file
 
VibeVoice-tpu/src/vibevoice/processor/__pycache__/vibevoice_tokenizer_processor.cpython-311.pyc ADDED
Binary file (21.5 kB). View file
 
VibeVoice-tpu/src/vibevoice/processor/preprocessor_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "processor_class": "VibeVoiceProcessor",
3
+ "speech_tok_compress_ratio": 3200,
4
+ "db_normalize": true,
5
+ "audio_processor": {
6
+ "feature_extractor_type": "VibeVoiceTokenizerProcessor",
7
+ "sampling_rate": 24000,
8
+ "normalize_audio": true,
9
+ "target_dB_FS": -25,
10
+ "eps": 1e-06
11
+ },
12
+ "language_model_pretrained_name": "Qwen/Qwen2.5-7B"
13
+ }
VibeVoice-tpu/src/vibevoice/processor/vibevoice_processor.py ADDED
@@ -0,0 +1,677 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import warnings
3
+ from typing import List, Optional, Union, Dict, Any, Tuple
4
+ import os
5
+ import re
6
+
7
+ import numpy as np
8
+ import torch
9
+
10
+ from transformers.tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
11
+ from transformers.utils import TensorType, logging
12
+ from .vibevoice_tokenizer_processor import AudioNormalizer
13
+
14
+ logger = logging.get_logger(__name__)
15
+
16
+
17
+ class VibeVoiceProcessor:
18
+ r"""
19
+ Constructs a VibeVoice processor which wraps a VibeVoice tokenizer and audio processor into a single processor.
20
+
21
+ [`VibeVoiceProcessor`] offers all the functionalities of [`VibeVoiceTokenizer`] and [`VibeVoiceTokenizerProcessor`].
22
+ See the [`~VibeVoiceProcessor.__call__`] and [`~VibeVoiceProcessor.decode`] for more information.
23
+
24
+ Args:
25
+ tokenizer (`VibeVoiceTextTokenizer` or `VibeVoiceTextTokenizerFast`):
26
+ The tokenizer for text processing.
27
+ audio_processor (`VibeVoiceTokenizerProcessor`):
28
+ The audio processor for speech processing.
29
+ speech_tok_compress_ratio (`int`, *optional*, defaults to 3200):
30
+ The compression ratio for speech tokenization.
31
+ db_normalize (`bool`, *optional*, defaults to True):
32
+ Whether to apply decibel normalization to audio inputs.
33
+ """
34
+
35
+ def __init__(self, tokenizer=None, audio_processor=None, speech_tok_compress_ratio=3200, db_normalize=True, **kwargs):
36
+ self.tokenizer = tokenizer
37
+ self.audio_processor = audio_processor
38
+ self.speech_tok_compress_ratio = speech_tok_compress_ratio
39
+ self.db_normalize = db_normalize
40
+ self.audio_normalizer = AudioNormalizer() if db_normalize else None
41
+ self.system_prompt = " Transform the text provided by various speakers into speech output, utilizing the distinct voice of each respective speaker.\n"
42
+
43
+ @classmethod
44
+ def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
45
+ """
46
+ Instantiate a VibeVoiceProcessor from a pretrained VibeVoice processor.
47
+
48
+ Args:
49
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
50
+ This can be either:
51
+ - a string, the *model id* of a pretrained model
52
+ - a path to a *directory* containing processor config
53
+
54
+ Returns:
55
+ [`VibeVoiceProcessor`]: The processor object instantiated from pretrained model.
56
+ """
57
+ import os
58
+ import json
59
+ from .vibevoice_tokenizer_processor import VibeVoiceTokenizerProcessor
60
+ from vibevoice.modular.modular_vibevoice_text_tokenizer import (
61
+ VibeVoiceTextTokenizer,
62
+ VibeVoiceTextTokenizerFast
63
+ )
64
+
65
+ # Load processor configuration
66
+ config_path = os.path.join(pretrained_model_name_or_path, "preprocessor_config.json")
67
+ if os.path.exists(config_path):
68
+ with open(config_path, 'r') as f:
69
+ config = json.load(f)
70
+ else:
71
+ logger.warning(f"No preprocessor_config.json found at {pretrained_model_name_or_path}, using defaults")
72
+ config = {
73
+ "speech_tok_compress_ratio": 3200,
74
+ "db_normalize": True,
75
+ }
76
+
77
+ # Extract main processor parameters
78
+ speech_tok_compress_ratio = config.get("speech_tok_compress_ratio", 3200)
79
+ db_normalize = config.get("db_normalize", True)
80
+
81
+ # Load tokenizer - try from model path first, then fallback to Qwen
82
+ language_model_pretrained_name = config.get("language_model_pretrained_name", None) or kwargs.pop("language_model_pretrained_name", "Qwen/Qwen2.5-1.5B")
83
+ logger.info(f"Loading tokenizer from {language_model_pretrained_name}")
84
+ if 'qwen' in language_model_pretrained_name.lower():
85
+ tokenizer = VibeVoiceTextTokenizerFast.from_pretrained(
86
+ language_model_pretrained_name,
87
+ **kwargs
88
+ )
89
+ else:
90
+ raise ValueError(f"Unsupported tokenizer type for {language_model_pretrained_name}. Supported types: Qwen, Llama, Gemma.")
91
+
92
+ # Load audio processor
93
+ if "audio_processor" in config:
94
+ # Create audio processor from config
95
+ audio_config = config["audio_processor"]
96
+ audio_processor = VibeVoiceTokenizerProcessor(
97
+ sampling_rate=audio_config.get("sampling_rate", 24000),
98
+ normalize_audio=audio_config.get("normalize_audio", True),
99
+ target_dB_FS=audio_config.get("target_dB_FS", -25),
100
+ eps=audio_config.get("eps", 1e-6),
101
+ )
102
+ else:
103
+ # Create default audio processor
104
+ audio_processor = VibeVoiceTokenizerProcessor()
105
+
106
+ # Create and return the processor
107
+ return cls(
108
+ tokenizer=tokenizer,
109
+ audio_processor=audio_processor,
110
+ speech_tok_compress_ratio=speech_tok_compress_ratio,
111
+ db_normalize=db_normalize,
112
+ )
113
+
114
+ def save_pretrained(self, save_directory: Union[str, os.PathLike], **kwargs):
115
+ """
116
+ Save a processor to a directory, so that it can be re-loaded using the
117
+ [`~VibeVoiceProcessor.from_pretrained`] class method.
118
+
119
+ Args:
120
+ save_directory (`str` or `os.PathLike`):
121
+ Directory where the processor will be saved.
122
+ """
123
+ import os
124
+ import json
125
+
126
+ os.makedirs(save_directory, exist_ok=True)
127
+
128
+ # Save processor configuration
129
+ processor_config = {
130
+ "processor_class": "VibeVoiceProcessor",
131
+ "speech_tok_compress_ratio": self.speech_tok_compress_ratio,
132
+ "db_normalize": self.db_normalize,
133
+ "audio_processor": {
134
+ "feature_extractor_type": "VibeVoiceTokenizerProcessor",
135
+ "sampling_rate": getattr(self.audio_processor, 'sampling_rate', 24000),
136
+ "normalize_audio": getattr(self.audio_processor, 'normalize_audio', True),
137
+ "target_dB_FS": getattr(self.audio_processor, 'target_dB_FS', -25),
138
+ "eps": getattr(self.audio_processor, 'eps', 1e-6),
139
+ }
140
+ }
141
+
142
+ config_path = os.path.join(save_directory, "preprocessor_config.json")
143
+ with open(config_path, 'w') as f:
144
+ json.dump(processor_config, f, indent=2)
145
+
146
+ logger.info(f"Processor configuration saved in {config_path}")
147
+
148
+ def __call__(
149
+ self,
150
+ text: Optional[Union[str, List[str], TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None,
151
+ voice_samples: Optional[Union[List[Union[str, np.ndarray]], List[List[Union[str, np.ndarray]]]]] = None,
152
+ padding: Union[bool, str, PaddingStrategy] = True,
153
+ truncation: Union[bool, str, TruncationStrategy] = False,
154
+ max_length: Optional[int] = None,
155
+ return_tensors: Optional[Union[str, TensorType]] = None,
156
+ return_attention_mask: bool = True,
157
+ **kwargs,
158
+ ) -> BatchEncoding:
159
+ """
160
+ Main method to process one or more podcast scripts with optional voice samples.
161
+
162
+ Args:
163
+ text (`str`, `List[str]`):
164
+ The input text(s) to process. Can be:
165
+ - A single script string
166
+ - A list of script strings for batch processing
167
+ - A path to a .json or .txt file
168
+ - A list of paths
169
+ voice_samples (`List[Union[str, np.ndarray]]`, `List[List[Union[str, np.ndarray]]]`, *optional*):
170
+ Voice samples for each script. Can be:
171
+ - A list of samples for a single script
172
+ - A list of lists for batch processing
173
+ padding (`bool`, `str` or `PaddingStrategy`, defaults to `True`):
174
+ Whether to pad sequences to the same length
175
+ truncation (`bool`, `str` or `TruncationStrategy`, defaults to `False`):
176
+ Whether to truncate sequences
177
+ max_length (`int`, *optional*):
178
+ Maximum length of the returned sequences
179
+ return_tensors (`str` or `TensorType`, *optional*):
180
+ If set, will return tensors of a particular framework
181
+ return_attention_mask (`bool`, defaults to `True`):
182
+ Whether to return the attention mask
183
+
184
+ Returns:
185
+ `BatchEncoding`: A BatchEncoding with the following fields:
186
+ - **input_ids** -- List of token id sequences or tensor
187
+ - **attention_mask** -- List of attention masks or tensor
188
+ - **speech_tensors** -- Padded speech inputs (if voice_samples provided)
189
+ - **speech_masks** -- Speech masks (if voice_samples provided)
190
+ - **speech_input_mask** -- Boolean masks indicating speech token positions
191
+ """
192
+ # Handle single vs batch input
193
+ if isinstance(text, str) or (isinstance(text, list) and len(text) > 0 and not isinstance(text[0], str)):
194
+ # Single input
195
+ texts = [text]
196
+ is_batched = False
197
+ else:
198
+ # Batch input
199
+ texts = text
200
+ is_batched = True
201
+
202
+ # Handle voice samples
203
+ if voice_samples is not None:
204
+ if not is_batched or (isinstance(voice_samples[0], (str, np.ndarray))):
205
+ # Single set of voice samples
206
+ voice_samples_list = [voice_samples]
207
+ else:
208
+ # Batch of voice samples
209
+ voice_samples_list = voice_samples
210
+ else:
211
+ voice_samples_list = [None] * len(texts)
212
+
213
+ # Process each input
214
+ all_encodings = []
215
+ for text_input, voice_input in zip(texts, voice_samples_list):
216
+ encoding = self._process_single(text_input, voice_input)
217
+ all_encodings.append(encoding)
218
+
219
+ # Combine batch
220
+ batch_encoding = self._batch_encode(
221
+ all_encodings,
222
+ padding=padding,
223
+ truncation=truncation,
224
+ max_length=max_length,
225
+ return_tensors=return_tensors,
226
+ return_attention_mask=return_attention_mask,
227
+ )
228
+
229
+ return batch_encoding
230
+
231
+ def _process_single(
232
+ self,
233
+ text: Union[str, TextInput],
234
+ voice_samples: Optional[List[Union[str, np.ndarray]]] = None,
235
+ ) -> Dict[str, Any]:
236
+ """Process a single podcast script."""
237
+ # Determine if text is a file path or direct script
238
+ script = None
239
+ if isinstance(text, str):
240
+ # Check if it's a file path
241
+ if text.endswith('.json') and os.path.exists(text):
242
+ script = self._convert_json_to_script(text)
243
+ elif text.endswith('.txt') and os.path.exists(text):
244
+ script = self._convert_text_to_script(text)
245
+ else:
246
+ # Assume it's the script content directly
247
+ script = text
248
+
249
+ if script is None:
250
+ raise ValueError(f"Could not process input text: {text}")
251
+
252
+ # Parse the script
253
+ parsed_lines = self._parse_script(script)
254
+ all_speakers = list(set(speaker_id for speaker_id, _ in parsed_lines))
255
+
256
+ # Create system prompt
257
+ # system_tokens = self.tokenizer.encode(self.system_prompt, add_special_tokens=False)
258
+ system_tokens = self.tokenizer.encode(self.system_prompt)
259
+
260
+ # Process voice samples if provided
261
+ if voice_samples:
262
+ voice_tokens, voice_speech_inputs, voice_speech_masks = self._create_voice_prompt(voice_samples[:len(all_speakers)])
263
+ else:
264
+ voice_tokens, voice_speech_inputs, voice_speech_masks = [], [], []
265
+
266
+ # Build full token sequence
267
+ full_tokens = system_tokens + voice_tokens
268
+ speech_input_mask = [False] * len(system_tokens) + voice_speech_masks
269
+
270
+ # Add text input section
271
+ full_tokens += self.tokenizer.encode(' Text input:\n', add_special_tokens=False)
272
+ speech_input_mask += [False] * len(self.tokenizer.encode(' Text input:\n', add_special_tokens=False))
273
+
274
+ for speaker_id, speaker_text in parsed_lines:
275
+ speaker_text_tokens = self.tokenizer.encode(f" Speaker {speaker_id}:{speaker_text}\n", add_special_tokens=False)
276
+ full_tokens += speaker_text_tokens
277
+ speech_input_mask += [False] * len(speaker_text_tokens)
278
+
279
+ # Add speech output section
280
+ full_tokens += self.tokenizer.encode(' Speech output:\n', add_special_tokens=False) + [self.tokenizer.speech_start_id]
281
+ speech_input_mask += [False] * (len(self.tokenizer.encode(' Speech output:\n', add_special_tokens=False)) + 1)
282
+
283
+ return {
284
+ "input_ids": full_tokens,
285
+ "speech_inputs": voice_speech_inputs if voice_speech_inputs else None,
286
+ "speech_input_mask": speech_input_mask,
287
+ "parsed_script": parsed_lines,
288
+ "all_speakers": all_speakers,
289
+ }
290
+
291
+ def _batch_encode(
292
+ self,
293
+ encodings: List[Dict[str, Any]],
294
+ padding: Union[bool, str, PaddingStrategy] = True,
295
+ truncation: Union[bool, str, TruncationStrategy] = False,
296
+ max_length: Optional[int] = None,
297
+ return_tensors: Optional[Union[str, TensorType]] = None,
298
+ return_attention_mask: bool = True,
299
+ ) -> BatchEncoding:
300
+ """Combine multiple encodings into a batch with padding."""
301
+ # Extract input_ids and create attention_mask
302
+ input_ids_list = [enc["input_ids"] for enc in encodings]
303
+ speech_input_masks_list = [enc["speech_input_mask"] for enc in encodings]
304
+
305
+ # Determine padding strategy
306
+ if isinstance(padding, bool):
307
+ padding_strategy = PaddingStrategy.LONGEST if padding else PaddingStrategy.DO_NOT_PAD
308
+ elif isinstance(padding, str):
309
+ padding_strategy = PaddingStrategy(padding)
310
+ else:
311
+ padding_strategy = padding
312
+
313
+ # Apply padding to input_ids
314
+ if padding_strategy != PaddingStrategy.DO_NOT_PAD:
315
+ if padding_strategy == PaddingStrategy.LONGEST:
316
+ max_len = max(len(ids) for ids in input_ids_list)
317
+ elif padding_strategy == PaddingStrategy.MAX_LENGTH and max_length is not None:
318
+ max_len = max_length
319
+ else:
320
+ max_len = max(len(ids) for ids in input_ids_list)
321
+
322
+ # Pad sequences
323
+ padded_input_ids = []
324
+ attention_masks = []
325
+ padded_speech_input_masks = []
326
+
327
+ for input_ids, speech_mask in zip(input_ids_list, speech_input_masks_list):
328
+ # Truncate if needed
329
+ if truncation and len(input_ids) > max_len:
330
+ input_ids = input_ids[:max_len]
331
+ speech_mask = speech_mask[:max_len]
332
+
333
+ # Pad
334
+ padding_length = max_len - len(input_ids)
335
+ # padded_ids = [self.tokenizer.pad_token_id] * padding_length + input_ids
336
+ padded_ids = [self.tokenizer.pad_id] * padding_length + input_ids
337
+ attention_mask = [0] * padding_length + [1] * len(input_ids)
338
+ padded_speech_mask = [False] * padding_length + speech_mask
339
+
340
+ padded_input_ids.append(padded_ids)
341
+ attention_masks.append(attention_mask)
342
+ padded_speech_input_masks.append(padded_speech_mask)
343
+
344
+ input_ids_list = padded_input_ids
345
+ speech_input_masks_list = padded_speech_input_masks
346
+ else:
347
+ # No padding, just create attention masks
348
+ attention_masks = [[1] * len(ids) for ids in input_ids_list] if return_attention_mask else None
349
+
350
+ # Process speech inputs
351
+ all_speech_inputs = []
352
+ has_speech = False
353
+ for enc in encodings:
354
+ if enc["speech_inputs"] is not None:
355
+ all_speech_inputs.extend(enc["speech_inputs"])
356
+ has_speech = True
357
+
358
+ # Prepare batch encoding
359
+ batch_encoding = BatchEncoding()
360
+
361
+ # Handle tensor conversion
362
+ if return_tensors is not None:
363
+ batch_encoding["input_ids"] = torch.tensor(input_ids_list, dtype=torch.long)
364
+ if return_attention_mask and attention_masks is not None:
365
+ batch_encoding["attention_mask"] = torch.tensor(attention_masks, dtype=torch.long)
366
+ batch_encoding["speech_input_mask"] = torch.tensor(speech_input_masks_list, dtype=torch.bool)
367
+ else:
368
+ batch_encoding["input_ids"] = input_ids_list
369
+ if return_attention_mask and attention_masks is not None:
370
+ batch_encoding["attention_mask"] = attention_masks
371
+ batch_encoding["speech_input_mask"] = speech_input_masks_list
372
+
373
+ # Process speech tensors if present
374
+ if has_speech:
375
+ speech_dict = self.prepare_speech_inputs(
376
+ all_speech_inputs,
377
+ return_tensors=return_tensors,
378
+ )
379
+ batch_encoding["speech_tensors"] = speech_dict["padded_speeches"]
380
+ batch_encoding["speech_masks"] = speech_dict["speech_masks"]
381
+ else:
382
+ batch_encoding["speech_tensors"] = None
383
+ batch_encoding["speech_masks"] = None
384
+
385
+ # Add metadata
386
+ batch_encoding["parsed_scripts"] = [enc["parsed_script"] for enc in encodings]
387
+ batch_encoding["all_speakers_list"] = [enc["all_speakers"] for enc in encodings]
388
+
389
+ return batch_encoding
390
+
391
+ def _create_voice_prompt(
392
+ self,
393
+ speaker_samples: List[Union[str, np.ndarray]]
394
+ ) -> Tuple[List[int], List[np.ndarray], List[bool]]:
395
+ """
396
+ Create voice prompt tokens and process audio samples.
397
+
398
+ Returns:
399
+ tuple: (voice_tokens, voice_speech_inputs, voice_speech_masks)
400
+ """
401
+ vae_token_id = self.tokenizer.speech_diffusion_id
402
+
403
+ voice_full_tokens = self.tokenizer.encode(' Voice input:\n', add_special_tokens=False)
404
+ voice_speech_inputs = []
405
+ voice_speech_masks = [False] * len(voice_full_tokens)
406
+
407
+ for speaker_id, speaker_audio in enumerate(speaker_samples):
408
+ prefix_tokens = self.tokenizer.encode(f" Speaker {speaker_id}:", add_special_tokens=False)
409
+
410
+ # Process audio
411
+ if isinstance(speaker_audio, str):
412
+ # Load audio from file
413
+ wav = self.audio_processor._load_audio_from_path(speaker_audio)
414
+ else:
415
+ wav = np.array(speaker_audio, dtype=np.float32)
416
+
417
+ # Apply normalization if needed
418
+ if self.db_normalize and self.audio_normalizer:
419
+ wav = self.audio_normalizer(wav)
420
+
421
+ # Calculate token length based on compression ratio
422
+ # if speaker_audio.endswith('.pt') or speaker_audio.endswith('.npy'):
423
+ # vae_tok_len = wav.shape[0]
424
+ # else:
425
+ vae_tok_len = math.ceil(wav.shape[0] / self.speech_tok_compress_ratio)
426
+
427
+ # Build tokens and masks
428
+ speaker_tokens = (prefix_tokens +
429
+ [self.tokenizer.speech_start_id] +
430
+ [vae_token_id] * vae_tok_len +
431
+ [self.tokenizer.speech_end_id] +
432
+ self.tokenizer.encode('\n', add_special_tokens=False))
433
+
434
+ vae_input_mask = ([False] * len(prefix_tokens) +
435
+ [False] +
436
+ [True] * vae_tok_len +
437
+ [False] +
438
+ [False])
439
+
440
+ voice_full_tokens.extend(speaker_tokens)
441
+ voice_speech_masks.extend(vae_input_mask)
442
+ voice_speech_inputs.append(wav)
443
+
444
+ return voice_full_tokens, voice_speech_inputs, voice_speech_masks
445
+
446
+ def prepare_speech_inputs(
447
+ self,
448
+ speech_inputs: List[np.ndarray],
449
+ return_tensors: Optional[Union[str, TensorType]] = None,
450
+ device: Optional[Union[str, torch.device]] = None,
451
+ dtype: Optional[torch.dtype] = None,
452
+ ) -> Dict[str, Any]:
453
+ """
454
+ Prepare speech inputs for model consumption.
455
+
456
+ Args:
457
+ speech_inputs: List of speech arrays
458
+ return_tensors: Output tensor type
459
+ device: Device to place tensors on
460
+ dtype: Data type for tensors
461
+
462
+ Returns:
463
+ Dictionary with padded_speeches and speech_masks
464
+ """
465
+ if not speech_inputs:
466
+ return {"padded_speeches": None, "speech_masks": None}
467
+
468
+ # Calculate sequence lengths
469
+ vae_tok_seqlens = [math.ceil(s.shape[0] / self.speech_tok_compress_ratio) for s in speech_inputs]
470
+ # vae_tok_seqlens = [math.ceil(s.shape[0] / self.speech_tok_compress_ratio) if s.ndim == 1 else s.shape[0] for s in speech_inputs]
471
+ max_speech_length = max(s.shape[0] for s in speech_inputs)
472
+
473
+ # Pad speeches
474
+ if speech_inputs[0].ndim == 1:
475
+ padded_speeches = np.full((len(speech_inputs), max_speech_length), fill_value=0, dtype=np.float32)
476
+ else:
477
+ padded_speeches = np.full((len(speech_inputs), max_speech_length, speech_inputs[0].shape[-1]), fill_value=0, dtype=np.float32)
478
+ speech_masks = np.zeros((len(speech_inputs), max(vae_tok_seqlens)), dtype=np.bool_)
479
+
480
+ for i, (speech, vae_tok_length) in enumerate(zip(speech_inputs, vae_tok_seqlens)):
481
+ padded_speeches[i, :len(speech)] = speech
482
+ speech_masks[i, :vae_tok_length] = True
483
+
484
+ result = {
485
+ "padded_speeches": padded_speeches,
486
+ "speech_masks": speech_masks,
487
+ }
488
+
489
+ # Convert to tensors if requested
490
+ if return_tensors == "pt":
491
+ result["padded_speeches"] = torch.tensor(padded_speeches, device=device, dtype=dtype or torch.float32)
492
+ result["speech_masks"] = torch.tensor(speech_masks, device=device, dtype=torch.bool)
493
+
494
+ return result
495
+
496
+ def _convert_json_to_script(self, json_file: str) -> str:
497
+ """
498
+ Convert JSON format to script format.
499
+ Expected JSON format:
500
+ [
501
+ {"speaker": "1", "text": "Hello everyone..."},
502
+ {"speaker": "2", "text": "Great to be here..."}
503
+ ]
504
+ """
505
+ import json
506
+
507
+ with open(json_file, 'r', encoding='utf-8') as f:
508
+ data = json.load(f)
509
+
510
+ if not isinstance(data, list):
511
+ raise ValueError("JSON file must contain a list of speaker entries")
512
+
513
+ script_lines = []
514
+ for item in data:
515
+ if not isinstance(item, dict):
516
+ logger.warning(f"Skipping non-dict entry: {item}")
517
+ continue
518
+
519
+ speaker = item.get('speaker')
520
+ text = item.get('text')
521
+
522
+ if speaker is None or text is None:
523
+ logger.warning(f"Skipping entry missing speaker or text: {item}")
524
+ continue
525
+
526
+ # Ensure speaker ID is valid
527
+ try:
528
+ speaker_id = int(speaker)
529
+ except (ValueError, TypeError):
530
+ logger.warning(f"Invalid speaker ID: {speaker}, skipping entry")
531
+ continue
532
+
533
+ # Clean up text
534
+ text = text.strip()
535
+ if text:
536
+ script_lines.append(f"Speaker {speaker_id}: {text}")
537
+
538
+ if not script_lines:
539
+ raise ValueError("No valid entries found in JSON file")
540
+
541
+ return "\n".join(script_lines)
542
+
543
+ def _convert_text_to_script(self, text_file: str) -> str:
544
+ """
545
+ Convert text file to script format.
546
+ Handles multiple formats:
547
+ 1. Already formatted as "Speaker X: text"
548
+ 2. Plain text (assigns to Speaker 1)
549
+
550
+ Handles edge cases like multiple colons in a line.
551
+ """
552
+ with open(text_file, 'r', encoding='utf-8') as f:
553
+ lines = f.readlines()
554
+
555
+ script_lines = []
556
+ current_speaker = 1
557
+
558
+ for line in lines:
559
+ line = line.strip()
560
+ if not line:
561
+ continue
562
+
563
+ # Try to parse as "Speaker X: text" format
564
+ # Use regex to be more robust
565
+ speaker_match = re.match(r'^Speaker\s+(\d+)\s*:\s*(.*)$', line, re.IGNORECASE)
566
+
567
+ if speaker_match:
568
+ speaker_id = int(speaker_match.group(1))
569
+ text = speaker_match.group(2).strip()
570
+ if text:
571
+ script_lines.append(f"Speaker {speaker_id}: {text}")
572
+ else:
573
+ # Treat as plain text - assign to current speaker
574
+ script_lines.append(f"Speaker {current_speaker}: {line}")
575
+
576
+ if not script_lines:
577
+ raise ValueError("No valid content found in text file")
578
+
579
+ return "\n".join(script_lines)
580
+
581
+ def _parse_script(self, script: str) -> List[Tuple[int, str]]:
582
+ """Parse script into list of (speaker_id, text) tuples."""
583
+ lines = script.strip().split("\n")
584
+ parsed_lines = []
585
+ speaker_ids = []
586
+
587
+ # First pass: parse all lines and collect speaker IDs
588
+ for line in lines:
589
+ if not line.strip():
590
+ continue
591
+
592
+ # Use regex to handle edge cases like multiple colons
593
+ match = re.match(r'^Speaker\s+(\d+)\s*:\s*(.*)$', line.strip(), re.IGNORECASE)
594
+
595
+ if match:
596
+ speaker_id = int(match.group(1))
597
+ text = ' ' + match.group(2).strip()
598
+ parsed_lines.append((speaker_id, text))
599
+ speaker_ids.append(speaker_id)
600
+ else:
601
+ logger.warning(f"Could not parse line: '{line}'")
602
+
603
+ if not parsed_lines:
604
+ raise ValueError("No valid speaker lines found in script")
605
+
606
+ # Check if we need to normalize speaker IDs (only if all are > 0)
607
+ min_speaker_id = min(speaker_ids)
608
+ if min_speaker_id > 0:
609
+ # Normalize to start from 0
610
+ normalized_lines = []
611
+ for speaker_id, text in parsed_lines:
612
+ normalized_lines.append((speaker_id - 1, text))
613
+ return normalized_lines
614
+ else:
615
+ # Keep original IDs
616
+ return parsed_lines
617
+
618
+ def _merge_inputs(self, text_inputs: BatchEncoding, audio_inputs: Dict) -> BatchEncoding:
619
+ """Merge text and audio inputs into a single BatchEncoding."""
620
+ # Start with text inputs
621
+ merged = BatchEncoding(text_inputs)
622
+
623
+ # Add audio-specific fields
624
+ if "audio" in audio_inputs:
625
+ merged["speech_inputs"] = audio_inputs["audio"]
626
+ if "streaming" in audio_inputs:
627
+ merged["streaming"] = audio_inputs["streaming"]
628
+
629
+ return merged
630
+
631
+ def batch_decode(self, *args, **kwargs):
632
+ """
633
+ This method forwards all its arguments to VibeVoiceTextTokenizer's [`~PreTrainedTokenizer.batch_decode`].
634
+ Please refer to the docstring of this method for more information.
635
+ """
636
+ return self.tokenizer.batch_decode(*args, **kwargs)
637
+
638
+ def decode(self, *args, **kwargs):
639
+ """
640
+ This method forwards all its arguments to VibeVoiceTextTokenizer's [`~PreTrainedTokenizer.decode`].
641
+ Please refer to the docstring of this method for more information.
642
+ """
643
+ return self.tokenizer.decode(*args, **kwargs)
644
+
645
+ @property
646
+ def model_input_names(self):
647
+ """
648
+ Return the list of inputs accepted by the model.
649
+ """
650
+ tokenizer_input_names = self.tokenizer.model_input_names
651
+ audio_processor_input_names = self.audio_processor.model_input_names
652
+ return list(dict.fromkeys(tokenizer_input_names + audio_processor_input_names + ["speech_inputs", "speech_input_mask"]))
653
+
654
+ def save_audio(self,
655
+ audio: Union[torch.Tensor, np.ndarray, List[Union[torch.Tensor, np.ndarray]]],
656
+ output_path: str = "output.wav",
657
+ sampling_rate: Optional[int] = None,
658
+ normalize: bool = False,
659
+ batch_prefix: str = "audio_",
660
+ ) -> str:
661
+ """
662
+ Save audio data to a file.
663
+ Args:
664
+ audio (Union[torch.Tensor, np.ndarray, List[Union[torch.Tensor, np.ndarray]]]):
665
+ The audio data to save. Can be a single tensor/array or a list of them.
666
+ output_path (str, optional): Path to save the audio file. Defaults to "output.wav".
667
+ sampling_rate (int, optional): Sampling rate for the audio. If None, uses the processor's default.
668
+ normalize (bool, optional): Whether to normalize the audio before saving. Defaults to False.
669
+ batch_prefix (str, optional): Prefix for batch audio files. Defaults to "audio_".
670
+ Returns:
671
+ str: The path to the saved audio file.
672
+ """
673
+ return self.audio_processor.save_audio(audio, output_path=output_path, sampling_rate=sampling_rate, normalize=normalize, batch_prefix=batch_prefix)
674
+
675
+ __all__ = [
676
+ "VibeVoiceProcessor",
677
+ ]
VibeVoice-tpu/src/vibevoice/processor/vibevoice_tokenizer_processor.py ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Processor class for VibeVoice models.
3
+ """
4
+
5
+ import os
6
+ import json
7
+ import warnings
8
+ from typing import List, Optional, Union, Dict, Any
9
+
10
+ import numpy as np
11
+ import torch
12
+
13
+ from transformers.feature_extraction_utils import FeatureExtractionMixin
14
+ from transformers.utils import logging
15
+
16
+ logger = logging.get_logger(__name__)
17
+
18
+
19
+ class AudioNormalizer:
20
+ """
21
+ Audio normalization class for VibeVoice tokenizer.
22
+
23
+ This class provides audio normalization to ensure consistent input levels
24
+ for the VibeVoice tokenizer while maintaining audio quality.
25
+ """
26
+
27
+ def __init__(self, target_dB_FS: float = -25, eps: float = 1e-6):
28
+ """
29
+ Initialize the audio normalizer.
30
+
31
+ Args:
32
+ target_dB_FS (float): Target dB FS level for the audio. Default: -25
33
+ eps (float): Small value to avoid division by zero. Default: 1e-6
34
+ """
35
+ self.target_dB_FS = target_dB_FS
36
+ self.eps = eps
37
+
38
+ def tailor_dB_FS(self, audio: np.ndarray) -> tuple:
39
+ """
40
+ Adjust the audio to the target dB FS level.
41
+
42
+ Args:
43
+ audio (np.ndarray): Input audio signal
44
+
45
+ Returns:
46
+ tuple: (normalized_audio, rms, scalar)
47
+ """
48
+ rms = np.sqrt(np.mean(audio**2))
49
+ scalar = 10 ** (self.target_dB_FS / 20) / (rms + self.eps)
50
+ normalized_audio = audio * scalar
51
+ return normalized_audio, rms, scalar
52
+
53
+ def avoid_clipping(self, audio: np.ndarray, scalar: Optional[float] = None) -> tuple:
54
+ """
55
+ Avoid clipping by scaling down if necessary.
56
+
57
+ Args:
58
+ audio (np.ndarray): Input audio signal
59
+ scalar (float, optional): Explicit scaling factor
60
+
61
+ Returns:
62
+ tuple: (normalized_audio, scalar)
63
+ """
64
+ if scalar is None:
65
+ max_val = np.max(np.abs(audio))
66
+ if max_val > 1.0:
67
+ scalar = max_val + self.eps
68
+ else:
69
+ scalar = 1.0
70
+
71
+ return audio / scalar, scalar
72
+
73
+ def __call__(self, audio: np.ndarray) -> np.ndarray:
74
+ """
75
+ Normalize the audio by adjusting to target dB FS and avoiding clipping.
76
+
77
+ Args:
78
+ audio (np.ndarray): Input audio signal
79
+
80
+ Returns:
81
+ np.ndarray: Normalized audio signal
82
+ """
83
+ # First adjust to target dB FS
84
+ audio, _, _ = self.tailor_dB_FS(audio)
85
+ # Then avoid clipping
86
+ audio, _ = self.avoid_clipping(audio)
87
+ return audio
88
+
89
+
90
+ # Change from ProcessorMixin to FeatureExtractionMixin which is designed for single components
91
+ class VibeVoiceTokenizerProcessor(FeatureExtractionMixin):
92
+ """
93
+ Processor for VibeVoice acoustic tokenizer models.
94
+
95
+ This processor handles audio preprocessing for VibeVoice models, including:
96
+ - Audio format conversion (stereo to mono)
97
+ - Optional audio normalization
98
+ - Streaming support for infinite-length audio
99
+
100
+ Args:
101
+ sampling_rate (int, optional): Expected sampling rate. Defaults to 24000.
102
+ normalize_audio (bool, optional): Whether to normalize audio. Defaults to True.
103
+ target_dB_FS (float, optional): Target dB FS for normalization. Defaults to -25.
104
+ eps (float, optional): Small value for numerical stability. Defaults to 1e-6.
105
+ """
106
+ model_input_names = ["input_features"]
107
+
108
+ def __init__(
109
+ self,
110
+ sampling_rate: int = 24000,
111
+ normalize_audio: bool = True,
112
+ target_dB_FS: float = -25,
113
+ eps: float = 1e-6,
114
+ **kwargs,
115
+ ):
116
+ super().__init__(**kwargs)
117
+
118
+ self.sampling_rate = sampling_rate
119
+ self.normalize_audio = normalize_audio
120
+
121
+ # Initialize audio normalizer if needed
122
+ if self.normalize_audio:
123
+ self.normalizer = AudioNormalizer(target_dB_FS=target_dB_FS, eps=eps)
124
+ else:
125
+ self.normalizer = None
126
+
127
+ # Save config
128
+ self.feature_extractor_dict = {
129
+ "sampling_rate": sampling_rate,
130
+ "normalize_audio": normalize_audio,
131
+ "target_dB_FS": target_dB_FS,
132
+ "eps": eps,
133
+ }
134
+
135
+ def _ensure_mono(self, audio: np.ndarray) -> np.ndarray:
136
+ """
137
+ Convert stereo audio to mono if needed.
138
+
139
+ Args:
140
+ audio (np.ndarray): Input audio array
141
+
142
+ Returns:
143
+ np.ndarray: Mono audio array
144
+ """
145
+ if len(audio.shape) == 1:
146
+ return audio
147
+ elif len(audio.shape) == 2:
148
+ if audio.shape[0] == 2: # (2, time)
149
+ return np.mean(audio, axis=0)
150
+ elif audio.shape[1] == 2: # (time, 2)
151
+ return np.mean(audio, axis=1)
152
+ else:
153
+ # If one dimension is 1, squeeze it
154
+ if audio.shape[0] == 1:
155
+ return audio.squeeze(0)
156
+ elif audio.shape[1] == 1:
157
+ return audio.squeeze(1)
158
+ else:
159
+ raise ValueError(f"Unexpected audio shape: {audio.shape}")
160
+ else:
161
+ raise ValueError(f"Audio should be 1D or 2D, got shape: {audio.shape}")
162
+
163
+ def _process_single_audio(self, audio: Union[np.ndarray, List[float]]) -> np.ndarray:
164
+ """
165
+ Process a single audio array.
166
+
167
+ Args:
168
+ audio: Single audio input
169
+
170
+ Returns:
171
+ np.ndarray: Processed audio
172
+ """
173
+ # Convert to numpy array
174
+ if not isinstance(audio, np.ndarray):
175
+ audio = np.array(audio, dtype=np.float32)
176
+ else:
177
+ audio = audio.astype(np.float32)
178
+
179
+ # Ensure mono
180
+ audio = self._ensure_mono(audio)
181
+
182
+ # Normalize if requested
183
+ if self.normalize_audio and self.normalizer is not None:
184
+ audio = self.normalizer(audio)
185
+
186
+ return audio
187
+
188
+ def __call__(
189
+ self,
190
+ audio: Union[str, np.ndarray, List[float], List[np.ndarray], List[List[float]], List[str]] = None,
191
+ sampling_rate: Optional[int] = None,
192
+ return_tensors: Optional[str] = None,
193
+ **kwargs,
194
+ ):
195
+ """
196
+ Process audio for VibeVoice models.
197
+
198
+ Args:
199
+ audio: Audio input(s) to process. Can be:
200
+ - str: Path to audio file
201
+ - np.ndarray: Audio array
202
+ - List[float]: Audio as list of floats
203
+ - List[np.ndarray]: Batch of audio arrays
204
+ - List[str]: Batch of audio file paths
205
+ sampling_rate (int, optional): Sampling rate of the input audio
206
+ return_tensors (str, optional): Return format ('pt' for PyTorch, 'np' for NumPy)
207
+
208
+ Returns:
209
+ dict: Processed audio inputs with keys:
210
+ - input_features: Audio tensor(s) ready for the model
211
+ """
212
+ if audio is None:
213
+ raise ValueError("Audio input is required")
214
+
215
+ # Validate sampling rate
216
+ if sampling_rate is not None and sampling_rate != self.sampling_rate:
217
+ logger.warning(
218
+ f"Input sampling rate ({sampling_rate}) differs from expected "
219
+ f"sampling rate ({self.sampling_rate}). Please resample your audio."
220
+ )
221
+
222
+ # Handle different input types
223
+ if isinstance(audio, str):
224
+ # Single audio file path
225
+ audio = self._load_audio_from_path(audio)
226
+ is_batched = False
227
+ elif isinstance(audio, list):
228
+ if len(audio) == 0:
229
+ raise ValueError("Empty audio list provided")
230
+
231
+ # Check if it's a list of file paths
232
+ if all(isinstance(item, str) for item in audio):
233
+ # Batch of audio file paths
234
+ audio = [self._load_audio_from_path(path) for path in audio]
235
+ is_batched = True
236
+ else:
237
+ # Check if it's batched audio arrays
238
+ is_batched = isinstance(audio[0], (np.ndarray, list))
239
+ else:
240
+ # Single audio array or list
241
+ is_batched = False
242
+
243
+ # Process audio
244
+ if is_batched:
245
+ processed_audio = [self._process_single_audio(a) for a in audio]
246
+ else:
247
+ processed_audio = [self._process_single_audio(audio)]
248
+
249
+ # Convert to tensors if requested
250
+ if return_tensors == "pt":
251
+ if len(processed_audio) == 1:
252
+ # Create a proper batch dimension (B, T)
253
+ input_features = torch.from_numpy(processed_audio[0]).unsqueeze(0).unsqueeze(1)
254
+ else:
255
+ # For batched input with different lengths, create a batch properly
256
+ input_features = torch.stack([torch.from_numpy(a) for a in processed_audio]).unsqueeze(1)
257
+ elif return_tensors == "np":
258
+ if len(processed_audio) == 1:
259
+ input_features = processed_audio[0][np.newaxis, np.newaxis, :]
260
+ else:
261
+ input_features = np.stack(processed_audio)[:, np.newaxis, :]
262
+ else:
263
+ input_features = processed_audio[0] if len(processed_audio) == 1 else processed_audio
264
+
265
+ outputs = {
266
+ "audio": input_features, # Use "audio" instead of "input_features"
267
+ }
268
+
269
+ return outputs
270
+
271
+ def _load_audio_from_path(self, audio_path: str) -> np.ndarray:
272
+ """
273
+ Load audio from file path.
274
+
275
+ Args:
276
+ audio_path (str): Path to audio file
277
+
278
+ Returns:
279
+ np.ndarray: Loaded audio array
280
+ """
281
+ # Get file extension to determine loading method
282
+ file_ext = os.path.splitext(audio_path)[1].lower()
283
+
284
+ if file_ext in ['.wav', '.mp3', '.flac', '.m4a', '.ogg']:
285
+ # Audio file - use librosa
286
+ import librosa
287
+ audio_array, sr = librosa.load(
288
+ audio_path,
289
+ sr=self.sampling_rate,
290
+ mono=True
291
+ )
292
+ return audio_array
293
+ elif file_ext == '.pt':
294
+ # PyTorch tensor file
295
+ audio_tensor = torch.load(audio_path, map_location='cpu').squeeze()
296
+ if isinstance(audio_tensor, torch.Tensor):
297
+ audio_array = audio_tensor.numpy()
298
+ else:
299
+ audio_array = np.array(audio_tensor)
300
+ return audio_array.astype(np.float32)
301
+ elif file_ext == '.npy':
302
+ # NumPy file
303
+ audio_array = np.load(audio_path)
304
+ return audio_array.astype(np.float32)
305
+ else:
306
+ raise ValueError(
307
+ f"Unsupported file format: {file_ext}. "
308
+ f"Supported formats: .wav, .mp3, .flac, .m4a, .ogg, .pt, .npy, .npz"
309
+ )
310
+
311
+ def preprocess_audio(
312
+ self,
313
+ audio_path_or_array: Union[str, np.ndarray],
314
+ normalize: Optional[bool] = None,
315
+ ) -> np.ndarray:
316
+ """
317
+ Convenience method to preprocess audio from file path or array.
318
+ This method is kept for backward compatibility but __call__ is recommended.
319
+
320
+ Args:
321
+ audio_path_or_array: Path to audio file or numpy array
322
+ normalize: Whether to normalize (overrides default setting)
323
+
324
+ Returns:
325
+ np.ndarray: Preprocessed audio array
326
+ """
327
+ if isinstance(audio_path_or_array, str):
328
+ audio_array = self._load_audio_from_path(audio_path_or_array)
329
+ else:
330
+ audio_array = np.array(audio_path_or_array, dtype=np.float32)
331
+
332
+ # Override normalization setting if specified
333
+ original_normalize = self.normalize_audio
334
+ if normalize is not None:
335
+ self.normalize_audio = normalize
336
+
337
+ try:
338
+ processed = self._process_single_audio(audio_array)
339
+ finally:
340
+ # Restore original setting
341
+ self.normalize_audio = original_normalize
342
+
343
+ return processed
344
+
345
+ # Override to_dict method for configuration saving
346
+ def to_dict(self) -> Dict[str, Any]:
347
+ """
348
+ Convert the object to a dict containing all attributes needed for serialization.
349
+ """
350
+ return self.feature_extractor_dict
351
+
352
+ def save_audio(
353
+ self,
354
+ audio: Union[torch.Tensor, np.ndarray, List[Union[torch.Tensor, np.ndarray]]],
355
+ output_path: str = "output.wav",
356
+ sampling_rate: Optional[int] = None,
357
+ normalize: bool = False,
358
+ batch_prefix: str = "audio_",
359
+ ):
360
+ """
361
+ Save audio data to WAV file(s).
362
+
363
+ Args:
364
+ audio: Audio data to save. Can be:
365
+ - torch.Tensor: PyTorch tensor with shape (B, C, T) or (B, T) or (T)
366
+ - np.ndarray: NumPy array with shape (B, C, T) or (B, T) or (T)
367
+ - List of tensors or arrays
368
+ output_path: Path where to save the audio. If saving multiple files,
369
+ this is treated as a directory and individual files will be saved inside.
370
+ sampling_rate: Sampling rate for the saved audio. Defaults to the processor's rate.
371
+ normalize: Whether to normalize audio before saving.
372
+ batch_prefix: Prefix for batch files when saving multiple audios.
373
+
374
+ Returns:
375
+ List[str]: Paths to the saved audio files.
376
+ """
377
+ if sampling_rate is None:
378
+ sampling_rate = self.sampling_rate
379
+
380
+ try:
381
+ import soundfile as sf
382
+ except ImportError:
383
+ raise ImportError(
384
+ "soundfile is required to save audio files. "
385
+ "Install it with: pip install soundfile"
386
+ )
387
+
388
+ # Ensure audio is in the right format
389
+ if isinstance(audio, torch.Tensor):
390
+ # Convert PyTorch tensor to numpy
391
+ audio_np = audio.float().detach().cpu().numpy()
392
+ elif isinstance(audio, np.ndarray):
393
+ audio_np = audio
394
+ elif isinstance(audio, list):
395
+ # Handle list of tensors or arrays
396
+ if all(isinstance(a, torch.Tensor) for a in audio):
397
+ audio_np = [a.float().detach().cpu().numpy() for a in audio]
398
+ else:
399
+ audio_np = audio
400
+ else:
401
+ raise ValueError(f"Unsupported audio type: {type(audio)}")
402
+
403
+ saved_paths = []
404
+
405
+ # Handle based on shape or type
406
+ if isinstance(audio_np, list):
407
+ # Multiple separate audios to save
408
+ output_dir = output_path
409
+
410
+ # Ensure output directory exists
411
+ os.makedirs(output_dir, exist_ok=True)
412
+
413
+ # Save each audio
414
+ for i, audio_item in enumerate(audio_np):
415
+ audio_item = self._prepare_audio_for_save(audio_item, normalize)
416
+ file_path = os.path.join(output_dir, f"{batch_prefix}{i}.wav")
417
+ sf.write(file_path, audio_item, sampling_rate)
418
+ saved_paths.append(file_path)
419
+
420
+ else:
421
+ # Handle different dimensions
422
+ if len(audio_np.shape) >= 3: # (B, C, T) or similar
423
+ # Get batch size
424
+ batch_size = audio_np.shape[0]
425
+
426
+ if batch_size > 1:
427
+ # Multiple audios in a batch
428
+ output_dir = output_path
429
+
430
+ # Ensure output directory exists
431
+ os.makedirs(output_dir, exist_ok=True)
432
+
433
+ # Save each audio in the batch
434
+ for i in range(batch_size):
435
+ # Extract single audio and remove channel dim if present
436
+ single_audio = audio_np[i]
437
+ if len(single_audio.shape) > 1:
438
+ if single_audio.shape[0] == 1: # (1, T)
439
+ single_audio = single_audio.squeeze(0)
440
+
441
+ single_audio = self._prepare_audio_for_save(single_audio, normalize)
442
+ file_path = os.path.join(output_dir, f"{batch_prefix}{i}.wav")
443
+ sf.write(file_path, single_audio, sampling_rate)
444
+ saved_paths.append(file_path)
445
+ else:
446
+ # Single audio with batch and channel dims
447
+ audio_item = audio_np.squeeze() # Remove batch and channel dimensions
448
+ audio_item = self._prepare_audio_for_save(audio_item, normalize)
449
+ sf.write(output_path, audio_item, sampling_rate)
450
+ saved_paths.append(output_path)
451
+ else:
452
+ # Single audio without batch dimension
453
+ audio_item = self._prepare_audio_for_save(audio_np, normalize)
454
+ sf.write(output_path, audio_item, sampling_rate)
455
+ saved_paths.append(output_path)
456
+
457
+ return saved_paths
458
+
459
+ def _prepare_audio_for_save(self, audio: np.ndarray, normalize: bool) -> np.ndarray:
460
+ """
461
+ Prepare audio for saving by ensuring it's the right shape and optionally normalizing.
462
+
463
+ Args:
464
+ audio: Audio data as numpy array
465
+ normalize: Whether to normalize audio
466
+
467
+ Returns:
468
+ np.ndarray: Processed audio ready for saving
469
+ """
470
+ # Ensure right dimensionality
471
+ if len(audio.shape) > 1 and audio.shape[0] == 1: # (1, T)
472
+ audio = audio.squeeze(0)
473
+
474
+ # Normalize if requested
475
+ if normalize:
476
+ max_val = np.abs(audio).max()
477
+ if max_val > 0:
478
+ audio = audio / max_val
479
+
480
+ return audio
481
+
482
+
483
+ __all__ = ["VibeVoiceTokenizerProcessor", "AudioNormalizer"]
VibeVoice-tpu/src/vibevoice/schedule/__init__.py ADDED
File without changes
VibeVoice-tpu/src/vibevoice/schedule/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (176 Bytes). View file
 
VibeVoice-tpu/src/vibevoice/schedule/__pycache__/dpm_solver.cpython-311.pyc ADDED
Binary file (55.5 kB). View file
 
VibeVoice-tpu/src/vibevoice/schedule/dpm_solver.py ADDED
@@ -0,0 +1,1065 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 TSAIL Team and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # DISCLAIMER: This file is strongly influenced by https://github.com/LuChengTHU/dpm-solver
16
+
17
+ import math
18
+ from typing import List, Optional, Tuple, Union
19
+
20
+ import numpy as np
21
+ import torch
22
+
23
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
24
+ from diffusers.utils import deprecate
25
+ from diffusers.utils.torch_utils import randn_tensor
26
+ from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput
27
+
28
+ def betas_for_alpha_bar(
29
+ num_diffusion_timesteps,
30
+ max_beta=0.999,
31
+ alpha_transform_type="cosine",
32
+ ):
33
+ """
34
+ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
35
+ (1-beta) over time from t = [0,1].
36
+
37
+ Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
38
+ to that part of the diffusion process.
39
+
40
+
41
+ Args:
42
+ num_diffusion_timesteps (`int`): the number of betas to produce.
43
+ max_beta (`float`): the maximum beta to use; use values lower than 1 to
44
+ prevent singularities.
45
+ alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
46
+ Choose from `cosine` or `exp`
47
+
48
+ Returns:
49
+ betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
50
+ """
51
+ if alpha_transform_type == "cosine":
52
+
53
+ def alpha_bar_fn(t):
54
+ return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2
55
+ # return math.cos(t * math.pi / 2 * 0.95) ** 2
56
+
57
+ elif alpha_transform_type == "exp":
58
+
59
+ def alpha_bar_fn(t):
60
+ return math.exp(t * -12.0)
61
+
62
+ elif alpha_transform_type == "cauchy":
63
+ # µ + γ tan (π (0.5 - x)) γ = 1, µ = 3
64
+ # alpha^2 = 1-1/(exp(λ)+1)
65
+ def alpha_bar_fn(t, gamma=1, mu=3):
66
+ snr = mu + gamma * math.tan(math.pi * (0.5 - t) * 0.9)
67
+ return 1 - 1 / (math.exp(snr) + 1.1)
68
+
69
+ elif alpha_transform_type == "laplace":
70
+ # µ − bsgn(0.5 − t) log(1 − 2|t − 0.5|) µ = 0, b = 1
71
+ def alpha_bar_fn(t, mu=0, b=1):
72
+ snr = mu - b * math.copysign(1, 0.5 - t) * math.log(1 - 2 * abs(t - 0.5) * 0.98)
73
+ return 1 - 1 / (math.exp(snr) + 1.02)
74
+
75
+ else:
76
+ raise ValueError(f"Unsupported alpha_transform_type: {alpha_transform_type}")
77
+
78
+ betas = []
79
+ for i in range(num_diffusion_timesteps):
80
+ t1 = i / num_diffusion_timesteps
81
+ t2 = (i + 1) / num_diffusion_timesteps
82
+ betas.append(min(1 - alpha_bar_fn(t2) / alpha_bar_fn(t1), max_beta))
83
+ return torch.tensor(betas, dtype=torch.float32)
84
+
85
+
86
+ # Copied from diffusers.schedulers.scheduling_ddim.rescale_zero_terminal_snr
87
+ def rescale_zero_terminal_snr(betas):
88
+ """
89
+ Rescales betas to have zero terminal SNR Based on https://arxiv.org/pdf/2305.08891.pdf (Algorithm 1)
90
+
91
+
92
+ Args:
93
+ betas (`torch.Tensor`):
94
+ the betas that the scheduler is being initialized with.
95
+
96
+ Returns:
97
+ `torch.Tensor`: rescaled betas with zero terminal SNR
98
+ """
99
+ # Convert betas to alphas_bar_sqrt
100
+ alphas = 1.0 - betas
101
+ alphas_cumprod = torch.cumprod(alphas, dim=0)
102
+ alphas_bar_sqrt = alphas_cumprod.sqrt()
103
+
104
+ # Store old values.
105
+ alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone()
106
+ alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone()
107
+
108
+ # Shift so the last timestep is zero.
109
+ alphas_bar_sqrt -= alphas_bar_sqrt_T
110
+
111
+ # Scale so the first timestep is back to the old value.
112
+ alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T)
113
+
114
+ # Convert alphas_bar_sqrt to betas
115
+ alphas_bar = alphas_bar_sqrt**2 # Revert sqrt
116
+ alphas = alphas_bar[1:] / alphas_bar[:-1] # Revert cumprod
117
+ alphas = torch.cat([alphas_bar[0:1], alphas])
118
+ betas = 1 - alphas
119
+
120
+ return betas
121
+
122
+ class DPMSolverMultistepScheduler(SchedulerMixin, ConfigMixin):
123
+ """
124
+ `DPMSolverMultistepScheduler` is a fast dedicated high-order solver for diffusion ODEs.
125
+
126
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
127
+ methods the library implements for all schedulers such as loading and saving.
128
+
129
+ Args:
130
+ num_train_timesteps (`int`, defaults to 1000):
131
+ The number of diffusion steps to train the model.
132
+ beta_start (`float`, defaults to 0.0001):
133
+ The starting `beta` value of inference.
134
+ beta_end (`float`, defaults to 0.02):
135
+ The final `beta` value.
136
+ beta_schedule (`str`, defaults to `"linear"`):
137
+ The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
138
+ `linear`, `scaled_linear`, or `squaredcos_cap_v2`.
139
+ trained_betas (`np.ndarray`, *optional*):
140
+ Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
141
+ solver_order (`int`, defaults to 2):
142
+ The DPMSolver order which can be `1` or `2` or `3`. It is recommended to use `solver_order=2` for guided
143
+ sampling, and `solver_order=3` for unconditional sampling.
144
+ prediction_type (`str`, defaults to `epsilon`, *optional*):
145
+ Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
146
+ `sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
147
+ Video](https://imagen.research.google/video/paper.pdf) paper).
148
+ thresholding (`bool`, defaults to `False`):
149
+ Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such
150
+ as Stable Diffusion.
151
+ dynamic_thresholding_ratio (`float`, defaults to 0.995):
152
+ The ratio for the dynamic thresholding method. Valid only when `thresholding=True`.
153
+ sample_max_value (`float`, defaults to 1.0):
154
+ The threshold value for dynamic thresholding. Valid only when `thresholding=True` and
155
+ `algorithm_type="dpmsolver++"`.
156
+ algorithm_type (`str`, defaults to `dpmsolver++`):
157
+ Algorithm type for the solver; can be `dpmsolver`, `dpmsolver++`, `sde-dpmsolver` or `sde-dpmsolver++`. The
158
+ `dpmsolver` type implements the algorithms in the [DPMSolver](https://huggingface.co/papers/2206.00927)
159
+ paper, and the `dpmsolver++` type implements the algorithms in the
160
+ [DPMSolver++](https://huggingface.co/papers/2211.01095) paper. It is recommended to use `dpmsolver++` or
161
+ `sde-dpmsolver++` with `solver_order=2` for guided sampling like in Stable Diffusion.
162
+ solver_type (`str`, defaults to `midpoint`):
163
+ Solver type for the second-order solver; can be `midpoint` or `heun`. The solver type slightly affects the
164
+ sample quality, especially for a small number of steps. It is recommended to use `midpoint` solvers.
165
+ lower_order_final (`bool`, defaults to `True`):
166
+ Whether to use lower-order solvers in the final steps. Only valid for < 15 inference steps. This can
167
+ stabilize the sampling of DPMSolver for steps < 15, especially for steps <= 10.
168
+ euler_at_final (`bool`, defaults to `False`):
169
+ Whether to use Euler's method in the final step. It is a trade-off between numerical stability and detail
170
+ richness. This can stabilize the sampling of the SDE variant of DPMSolver for small number of inference
171
+ steps, but sometimes may result in blurring.
172
+ use_karras_sigmas (`bool`, *optional*, defaults to `False`):
173
+ Whether to use Karras sigmas for step sizes in the noise schedule during the sampling process. If `True`,
174
+ the sigmas are determined according to a sequence of noise levels {σi}.
175
+ use_lu_lambdas (`bool`, *optional*, defaults to `False`):
176
+ Whether to use the uniform-logSNR for step sizes proposed by Lu's DPM-Solver in the noise schedule during
177
+ the sampling process. If `True`, the sigmas and time steps are determined according to a sequence of
178
+ `lambda(t)`.
179
+ final_sigmas_type (`str`, defaults to `"zero"`):
180
+ The final `sigma` value for the noise schedule during the sampling process. If `"sigma_min"`, the final
181
+ sigma is the same as the last sigma in the training schedule. If `zero`, the final sigma is set to 0.
182
+ lambda_min_clipped (`float`, defaults to `-inf`):
183
+ Clipping threshold for the minimum value of `lambda(t)` for numerical stability. This is critical for the
184
+ cosine (`squaredcos_cap_v2`) noise schedule.
185
+ variance_type (`str`, *optional*):
186
+ Set to "learned" or "learned_range" for diffusion models that predict variance. If set, the model's output
187
+ contains the predicted Gaussian variance.
188
+ timestep_spacing (`str`, defaults to `"linspace"`):
189
+ The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
190
+ Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
191
+ steps_offset (`int`, defaults to 0):
192
+ An offset added to the inference steps, as required by some model families.
193
+ rescale_betas_zero_snr (`bool`, defaults to `False`):
194
+ Whether to rescale the betas to have zero terminal SNR. This enables the model to generate very bright and
195
+ dark samples instead of limiting it to samples with medium brightness. Loosely related to
196
+ [`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506).
197
+ """
198
+
199
+ _compatibles = [e.name for e in KarrasDiffusionSchedulers]
200
+ order = 1
201
+
202
+ @register_to_config
203
+ def __init__(
204
+ self,
205
+ num_train_timesteps: int = 1000,
206
+ beta_start: float = 0.0001,
207
+ beta_end: float = 0.02,
208
+ beta_schedule: str = "linear",
209
+ trained_betas: Optional[Union[np.ndarray, List[float]]] = None,
210
+ solver_order: int = 2,
211
+ prediction_type: str = "epsilon",
212
+ thresholding: bool = False,
213
+ dynamic_thresholding_ratio: float = 0.995,
214
+ sample_max_value: float = 1.0,
215
+ algorithm_type: str = "dpmsolver++",
216
+ solver_type: str = "midpoint",
217
+ lower_order_final: bool = True,
218
+ euler_at_final: bool = False,
219
+ use_karras_sigmas: Optional[bool] = False,
220
+ use_lu_lambdas: Optional[bool] = False,
221
+ final_sigmas_type: Optional[str] = "zero", # "zero", "sigma_min"
222
+ lambda_min_clipped: float = -float("inf"),
223
+ variance_type: Optional[str] = None,
224
+ timestep_spacing: str = "linspace",
225
+ steps_offset: int = 0,
226
+ rescale_betas_zero_snr: bool = False,
227
+ ):
228
+ if algorithm_type in ["dpmsolver", "sde-dpmsolver"]:
229
+ deprecation_message = f"algorithm_type {algorithm_type} is deprecated and will be removed in a future version. Choose from `dpmsolver++` or `sde-dpmsolver++` instead"
230
+ deprecate("algorithm_types dpmsolver and sde-dpmsolver", "1.0.0", deprecation_message)
231
+
232
+ if trained_betas is not None:
233
+ self.betas = torch.tensor(trained_betas, dtype=torch.float32)
234
+ elif beta_schedule == "linear":
235
+ self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)
236
+ elif beta_schedule == "scaled_linear":
237
+ # this schedule is very specific to the latent diffusion model.
238
+ self.betas = torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2
239
+ elif beta_schedule == "squaredcos_cap_v2" or beta_schedule == "cosine":
240
+ # Glide cosine schedule
241
+ self.betas = betas_for_alpha_bar(num_train_timesteps, alpha_transform_type="cosine")
242
+ elif beta_schedule == "cauchy":
243
+ self.betas = betas_for_alpha_bar(num_train_timesteps, alpha_transform_type="cauchy")
244
+ elif beta_schedule == "laplace":
245
+ self.betas = betas_for_alpha_bar(num_train_timesteps, alpha_transform_type="laplace")
246
+ else:
247
+ raise NotImplementedError(f"{beta_schedule} is not implemented for {self.__class__}")
248
+
249
+ if rescale_betas_zero_snr:
250
+ self.betas = rescale_zero_terminal_snr(self.betas)
251
+
252
+ self.alphas = 1.0 - self.betas
253
+ self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
254
+
255
+ if rescale_betas_zero_snr:
256
+ # Close to 0 without being 0 so first sigma is not inf
257
+ # FP16 smallest positive subnormal works well here
258
+ self.alphas_cumprod[-1] = 2**-24
259
+
260
+ # Currently we only support VP-type noise schedule
261
+ self.alpha_t = torch.sqrt(self.alphas_cumprod)
262
+ self.sigma_t = torch.sqrt(1 - self.alphas_cumprod)
263
+ self.lambda_t = torch.log(self.alpha_t) - torch.log(self.sigma_t)
264
+ self.sigmas = ((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5
265
+
266
+ # standard deviation of the initial noise distribution
267
+ self.init_noise_sigma = 1.0
268
+
269
+ # settings for DPM-Solver
270
+ if algorithm_type not in ["dpmsolver", "dpmsolver++", "sde-dpmsolver", "sde-dpmsolver++"]:
271
+ if algorithm_type == "deis":
272
+ self.register_to_config(algorithm_type="dpmsolver++")
273
+ else:
274
+ raise NotImplementedError(f"{algorithm_type} is not implemented for {self.__class__}")
275
+
276
+ if solver_type not in ["midpoint", "heun"]:
277
+ if solver_type in ["logrho", "bh1", "bh2"]:
278
+ self.register_to_config(solver_type="midpoint")
279
+ else:
280
+ raise NotImplementedError(f"{solver_type} is not implemented for {self.__class__}")
281
+
282
+ if algorithm_type not in ["dpmsolver++", "sde-dpmsolver++"] and final_sigmas_type == "zero":
283
+ raise ValueError(
284
+ f"`final_sigmas_type` {final_sigmas_type} is not supported for `algorithm_type` {algorithm_type}. Please choose `sigma_min` instead."
285
+ )
286
+
287
+ # setable values
288
+ self.num_inference_steps = None
289
+ timesteps = np.linspace(0, num_train_timesteps - 1, num_train_timesteps, dtype=np.float32)[::-1].copy()
290
+ self.timesteps = torch.from_numpy(timesteps)
291
+ self.model_outputs = [None] * solver_order
292
+ self.lower_order_nums = 0
293
+ self._step_index = None
294
+ self._begin_index = None
295
+ self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication
296
+
297
+ @property
298
+ def step_index(self):
299
+ """
300
+ The index counter for current timestep. It will increase 1 after each scheduler step.
301
+ """
302
+ return self._step_index
303
+
304
+ @property
305
+ def begin_index(self):
306
+ """
307
+ The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
308
+ """
309
+ return self._begin_index
310
+
311
+ def set_begin_index(self, begin_index: int = 0):
312
+ """
313
+ Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
314
+
315
+ Args:
316
+ begin_index (`int`):
317
+ The begin index for the scheduler.
318
+ """
319
+ self._begin_index = begin_index
320
+
321
+ def set_timesteps(
322
+ self,
323
+ num_inference_steps: int = None,
324
+ device: Union[str, torch.device] = None,
325
+ timesteps: Optional[List[int]] = None,
326
+ ):
327
+ """
328
+ Sets the discrete timesteps used for the diffusion chain (to be run before inference).
329
+
330
+ Args:
331
+ num_inference_steps (`int`):
332
+ The number of diffusion steps used when generating samples with a pre-trained model.
333
+ device (`str` or `torch.device`, *optional*):
334
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
335
+ timesteps (`List[int]`, *optional*):
336
+ Custom timesteps used to support arbitrary timesteps schedule. If `None`, timesteps will be generated
337
+ based on the `timestep_spacing` attribute. If `timesteps` is passed, `num_inference_steps` and `sigmas`
338
+ must be `None`, and `timestep_spacing` attribute will be ignored.
339
+ """
340
+ if num_inference_steps is None and timesteps is None:
341
+ raise ValueError("Must pass exactly one of `num_inference_steps` or `timesteps`.")
342
+ if num_inference_steps is not None and timesteps is not None:
343
+ raise ValueError("Can only pass one of `num_inference_steps` or `custom_timesteps`.")
344
+ if timesteps is not None and self.config.use_karras_sigmas:
345
+ raise ValueError("Cannot use `timesteps` with `config.use_karras_sigmas = True`")
346
+ if timesteps is not None and self.config.use_lu_lambdas:
347
+ raise ValueError("Cannot use `timesteps` with `config.use_lu_lambdas = True`")
348
+
349
+ if timesteps is not None:
350
+ timesteps = np.array(timesteps).astype(np.int64)
351
+ else:
352
+ # Clipping the minimum of all lambda(t) for numerical stability.
353
+ # This is critical for cosine (squaredcos_cap_v2) noise schedule.
354
+ clipped_idx = torch.searchsorted(torch.flip(self.lambda_t, [0]), self.config.lambda_min_clipped)
355
+ last_timestep = ((self.config.num_train_timesteps - clipped_idx).numpy()).item()
356
+
357
+ # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
358
+ if self.config.timestep_spacing == "linspace":
359
+ timesteps = (
360
+ np.linspace(0, last_timestep - 1, num_inference_steps + 1)
361
+ .round()[::-1][:-1]
362
+ .copy()
363
+ .astype(np.int64)
364
+ )
365
+ elif self.config.timestep_spacing == "leading":
366
+ step_ratio = last_timestep // (num_inference_steps + 1)
367
+ # creates integer timesteps by multiplying by ratio
368
+ # casting to int to avoid issues when num_inference_step is power of 3
369
+ timesteps = (
370
+ (np.arange(0, num_inference_steps + 1) * step_ratio).round()[::-1][:-1].copy().astype(np.int64)
371
+ )
372
+ timesteps += self.config.steps_offset
373
+ elif self.config.timestep_spacing == "trailing":
374
+ step_ratio = self.config.num_train_timesteps / num_inference_steps
375
+ # creates integer timesteps by multiplying by ratio
376
+ # casting to int to avoid issues when num_inference_step is power of 3
377
+ timesteps = np.arange(last_timestep, 0, -step_ratio).round().copy().astype(np.int64)
378
+ timesteps -= 1
379
+ else:
380
+ raise ValueError(
381
+ f"{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'."
382
+ )
383
+
384
+ sigmas = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)
385
+ log_sigmas = np.log(sigmas)
386
+
387
+ if self.config.use_karras_sigmas:
388
+ sigmas = np.flip(sigmas).copy()
389
+ sigmas = self._convert_to_karras(in_sigmas=sigmas, num_inference_steps=num_inference_steps)
390
+ timesteps = np.array([self._sigma_to_t(sigma, log_sigmas) for sigma in sigmas]).round()
391
+ elif self.config.use_lu_lambdas:
392
+ lambdas = np.flip(log_sigmas.copy())
393
+ lambdas = self._convert_to_lu(in_lambdas=lambdas, num_inference_steps=num_inference_steps)
394
+ sigmas = np.exp(lambdas)
395
+ timesteps = np.array([self._sigma_to_t(sigma, log_sigmas) for sigma in sigmas]).round()
396
+ else:
397
+ sigmas = np.interp(timesteps, np.arange(0, len(sigmas)), sigmas)
398
+
399
+ if self.config.final_sigmas_type == "sigma_min":
400
+ sigma_last = ((1 - self.alphas_cumprod[0]) / self.alphas_cumprod[0]) ** 0.5
401
+ elif self.config.final_sigmas_type == "zero":
402
+ sigma_last = 0
403
+ else:
404
+ raise ValueError(
405
+ f"`final_sigmas_type` must be one of 'zero', or 'sigma_min', but got {self.config.final_sigmas_type}"
406
+ )
407
+
408
+ sigmas = np.concatenate([sigmas, [sigma_last]]).astype(np.float32)
409
+
410
+ self.sigmas = torch.from_numpy(sigmas)
411
+ self.timesteps = torch.from_numpy(timesteps).to(device=device, dtype=torch.int64)
412
+
413
+ self.num_inference_steps = len(timesteps)
414
+
415
+ self.model_outputs = [
416
+ None,
417
+ ] * self.config.solver_order
418
+ self.lower_order_nums = 0
419
+
420
+ # add an index counter for schedulers that allow duplicated timesteps
421
+ self._step_index = None
422
+ self._begin_index = None
423
+ self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication
424
+
425
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample
426
+ def _threshold_sample(self, sample: torch.Tensor) -> torch.Tensor:
427
+ """
428
+ "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
429
+ prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
430
+ s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
431
+ pixels from saturation at each step. We find that dynamic thresholding results in significantly better
432
+ photorealism as well as better image-text alignment, especially when using very large guidance weights."
433
+
434
+ https://arxiv.org/abs/2205.11487
435
+ """
436
+ dtype = sample.dtype
437
+ batch_size, channels, *remaining_dims = sample.shape
438
+
439
+ if dtype not in (torch.float32, torch.float64):
440
+ sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half
441
+
442
+ # Flatten sample for doing quantile calculation along each image
443
+ sample = sample.reshape(batch_size, channels * np.prod(remaining_dims))
444
+
445
+ abs_sample = sample.abs() # "a certain percentile absolute pixel value"
446
+
447
+ s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
448
+ s = torch.clamp(
449
+ s, min=1, max=self.config.sample_max_value
450
+ ) # When clamped to min=1, equivalent to standard clipping to [-1, 1]
451
+ s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0
452
+ sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s"
453
+
454
+ sample = sample.reshape(batch_size, channels, *remaining_dims)
455
+ sample = sample.to(dtype)
456
+
457
+ return sample
458
+
459
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._sigma_to_t
460
+ def _sigma_to_t(self, sigma, log_sigmas):
461
+ # get log sigma
462
+ log_sigma = np.log(np.maximum(sigma, 1e-10))
463
+
464
+ # get distribution
465
+ dists = log_sigma - log_sigmas[:, np.newaxis]
466
+
467
+ # get sigmas range
468
+ low_idx = np.cumsum((dists >= 0), axis=0).argmax(axis=0).clip(max=log_sigmas.shape[0] - 2)
469
+ high_idx = low_idx + 1
470
+
471
+ low = log_sigmas[low_idx]
472
+ high = log_sigmas[high_idx]
473
+
474
+ # interpolate sigmas
475
+ w = (low - log_sigma) / (low - high)
476
+ w = np.clip(w, 0, 1)
477
+
478
+ # transform interpolation to time range
479
+ t = (1 - w) * low_idx + w * high_idx
480
+ t = t.reshape(sigma.shape)
481
+ return t
482
+
483
+ def _sigma_to_alpha_sigma_t(self, sigma):
484
+ alpha_t = 1 / ((sigma**2 + 1) ** 0.5)
485
+ sigma_t = sigma * alpha_t
486
+
487
+ return alpha_t, sigma_t
488
+
489
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._convert_to_karras
490
+ def _convert_to_karras(self, in_sigmas: torch.Tensor, num_inference_steps) -> torch.Tensor:
491
+ """Constructs the noise schedule of Karras et al. (2022)."""
492
+
493
+ # Hack to make sure that other schedulers which copy this function don't break
494
+ # TODO: Add this logic to the other schedulers
495
+ if hasattr(self.config, "sigma_min"):
496
+ sigma_min = self.config.sigma_min
497
+ else:
498
+ sigma_min = None
499
+
500
+ if hasattr(self.config, "sigma_max"):
501
+ sigma_max = self.config.sigma_max
502
+ else:
503
+ sigma_max = None
504
+
505
+ sigma_min = sigma_min if sigma_min is not None else in_sigmas[-1].item()
506
+ sigma_max = sigma_max if sigma_max is not None else in_sigmas[0].item()
507
+
508
+ rho = 7.0 # 7.0 is the value used in the paper
509
+ ramp = np.linspace(0, 1, num_inference_steps)
510
+ min_inv_rho = sigma_min ** (1 / rho)
511
+ max_inv_rho = sigma_max ** (1 / rho)
512
+ sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
513
+ return sigmas
514
+
515
+ def _convert_to_lu(self, in_lambdas: torch.Tensor, num_inference_steps) -> torch.Tensor:
516
+ """Constructs the noise schedule of Lu et al. (2022)."""
517
+
518
+ lambda_min: float = in_lambdas[-1].item()
519
+ lambda_max: float = in_lambdas[0].item()
520
+
521
+ rho = 1.0 # 1.0 is the value used in the paper
522
+ ramp = np.linspace(0, 1, num_inference_steps)
523
+ min_inv_rho = lambda_min ** (1 / rho)
524
+ max_inv_rho = lambda_max ** (1 / rho)
525
+ lambdas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
526
+ return lambdas
527
+
528
+ def convert_model_output(
529
+ self,
530
+ model_output: torch.Tensor,
531
+ *args,
532
+ sample: torch.Tensor = None,
533
+ **kwargs,
534
+ ) -> torch.Tensor:
535
+ """
536
+ Convert the model output to the corresponding type the DPMSolver/DPMSolver++ algorithm needs. DPM-Solver is
537
+ designed to discretize an integral of the noise prediction model, and DPM-Solver++ is designed to discretize an
538
+ integral of the data prediction model.
539
+
540
+ <Tip>
541
+
542
+ The algorithm and model type are decoupled. You can use either DPMSolver or DPMSolver++ for both noise
543
+ prediction and data prediction models.
544
+
545
+ </Tip>
546
+
547
+ Args:
548
+ model_output (`torch.Tensor`):
549
+ The direct output from the learned diffusion model.
550
+ sample (`torch.Tensor`):
551
+ A current instance of a sample created by the diffusion process.
552
+
553
+ Returns:
554
+ `torch.Tensor`:
555
+ The converted model output.
556
+ """
557
+ timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None)
558
+ if sample is None:
559
+ if len(args) > 1:
560
+ sample = args[1]
561
+ else:
562
+ raise ValueError("missing `sample` as a required keyward argument")
563
+ if timestep is not None:
564
+ deprecate(
565
+ "timesteps",
566
+ "1.0.0",
567
+ "Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
568
+ )
569
+
570
+ # DPM-Solver++ needs to solve an integral of the data prediction model.
571
+ if self.config.algorithm_type in ["dpmsolver++", "sde-dpmsolver++"]:
572
+ if self.config.prediction_type == "epsilon":
573
+ # DPM-Solver and DPM-Solver++ only need the "mean" output.
574
+ if self.config.variance_type in ["learned", "learned_range"]:
575
+ model_output = model_output[:, :3]
576
+ sigma = self.sigmas[self.step_index]
577
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
578
+ x0_pred = (sample - sigma_t * model_output) / alpha_t
579
+ elif self.config.prediction_type == "sample":
580
+ x0_pred = model_output
581
+ elif self.config.prediction_type == "v_prediction":
582
+ sigma = self.sigmas[self.step_index]
583
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
584
+ x0_pred = alpha_t * sample - sigma_t * model_output
585
+ else:
586
+ raise ValueError(
587
+ f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"
588
+ " `v_prediction` for the DPMSolverMultistepScheduler."
589
+ )
590
+
591
+ if self.config.thresholding:
592
+ x0_pred = self._threshold_sample(x0_pred)
593
+
594
+ return x0_pred
595
+
596
+ # DPM-Solver needs to solve an integral of the noise prediction model.
597
+ elif self.config.algorithm_type in ["dpmsolver", "sde-dpmsolver"]:
598
+ if self.config.prediction_type == "epsilon":
599
+ # DPM-Solver and DPM-Solver++ only need the "mean" output.
600
+ if self.config.variance_type in ["learned", "learned_range"]:
601
+ epsilon = model_output[:, :3]
602
+ else:
603
+ epsilon = model_output
604
+ elif self.config.prediction_type == "sample":
605
+ sigma = self.sigmas[self.step_index]
606
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
607
+ epsilon = (sample - alpha_t * model_output) / sigma_t
608
+ elif self.config.prediction_type == "v_prediction":
609
+ sigma = self.sigmas[self.step_index]
610
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
611
+ epsilon = alpha_t * model_output + sigma_t * sample
612
+ else:
613
+ raise ValueError(
614
+ f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"
615
+ " `v_prediction` for the DPMSolverMultistepScheduler."
616
+ )
617
+
618
+ if self.config.thresholding:
619
+ sigma = self.sigmas[self.step_index]
620
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
621
+ x0_pred = (sample - sigma_t * epsilon) / alpha_t
622
+ x0_pred = self._threshold_sample(x0_pred)
623
+ epsilon = (sample - alpha_t * x0_pred) / sigma_t
624
+
625
+ return epsilon
626
+
627
+ def dpm_solver_first_order_update(
628
+ self,
629
+ model_output: torch.Tensor,
630
+ *args,
631
+ sample: torch.Tensor = None,
632
+ noise: Optional[torch.Tensor] = None,
633
+ **kwargs,
634
+ ) -> torch.Tensor:
635
+ """
636
+ One step for the first-order DPMSolver (equivalent to DDIM).
637
+
638
+ Args:
639
+ model_output (`torch.Tensor`):
640
+ The direct output from the learned diffusion model.
641
+ sample (`torch.Tensor`):
642
+ A current instance of a sample created by the diffusion process.
643
+
644
+ Returns:
645
+ `torch.Tensor`:
646
+ The sample tensor at the previous timestep.
647
+ """
648
+ timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None)
649
+ prev_timestep = args[1] if len(args) > 1 else kwargs.pop("prev_timestep", None)
650
+ if sample is None:
651
+ if len(args) > 2:
652
+ sample = args[2]
653
+ else:
654
+ raise ValueError(" missing `sample` as a required keyward argument")
655
+ if timestep is not None:
656
+ deprecate(
657
+ "timesteps",
658
+ "1.0.0",
659
+ "Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
660
+ )
661
+
662
+ if prev_timestep is not None:
663
+ deprecate(
664
+ "prev_timestep",
665
+ "1.0.0",
666
+ "Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
667
+ )
668
+
669
+ sigma_t, sigma_s = self.sigmas[self.step_index + 1], self.sigmas[self.step_index]
670
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
671
+ alpha_s, sigma_s = self._sigma_to_alpha_sigma_t(sigma_s)
672
+ lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
673
+ lambda_s = torch.log(alpha_s) - torch.log(sigma_s)
674
+
675
+ h = lambda_t - lambda_s
676
+ if self.config.algorithm_type == "dpmsolver++":
677
+ x_t = (sigma_t / sigma_s) * sample - (alpha_t * (torch.exp(-h) - 1.0)) * model_output
678
+ elif self.config.algorithm_type == "dpmsolver":
679
+ x_t = (alpha_t / alpha_s) * sample - (sigma_t * (torch.exp(h) - 1.0)) * model_output
680
+ elif self.config.algorithm_type == "sde-dpmsolver++":
681
+ assert noise is not None
682
+ x_t = (
683
+ (sigma_t / sigma_s * torch.exp(-h)) * sample
684
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * model_output
685
+ + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
686
+ )
687
+ elif self.config.algorithm_type == "sde-dpmsolver":
688
+ assert noise is not None
689
+ x_t = (
690
+ (alpha_t / alpha_s) * sample
691
+ - 2.0 * (sigma_t * (torch.exp(h) - 1.0)) * model_output
692
+ + sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise
693
+ )
694
+ return x_t
695
+
696
+ def multistep_dpm_solver_second_order_update(
697
+ self,
698
+ model_output_list: List[torch.Tensor],
699
+ *args,
700
+ sample: torch.Tensor = None,
701
+ noise: Optional[torch.Tensor] = None,
702
+ **kwargs,
703
+ ) -> torch.Tensor:
704
+ """
705
+ One step for the second-order multistep DPMSolver.
706
+
707
+ Args:
708
+ model_output_list (`List[torch.Tensor]`):
709
+ The direct outputs from learned diffusion model at current and latter timesteps.
710
+ sample (`torch.Tensor`):
711
+ A current instance of a sample created by the diffusion process.
712
+
713
+ Returns:
714
+ `torch.Tensor`:
715
+ The sample tensor at the previous timestep.
716
+ """
717
+ timestep_list = args[0] if len(args) > 0 else kwargs.pop("timestep_list", None)
718
+ prev_timestep = args[1] if len(args) > 1 else kwargs.pop("prev_timestep", None)
719
+ if sample is None:
720
+ if len(args) > 2:
721
+ sample = args[2]
722
+ else:
723
+ raise ValueError(" missing `sample` as a required keyward argument")
724
+ if timestep_list is not None:
725
+ deprecate(
726
+ "timestep_list",
727
+ "1.0.0",
728
+ "Passing `timestep_list` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
729
+ )
730
+
731
+ if prev_timestep is not None:
732
+ deprecate(
733
+ "prev_timestep",
734
+ "1.0.0",
735
+ "Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
736
+ )
737
+
738
+ sigma_t, sigma_s0, sigma_s1 = (
739
+ self.sigmas[self.step_index + 1],
740
+ self.sigmas[self.step_index],
741
+ self.sigmas[self.step_index - 1],
742
+ )
743
+
744
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
745
+ alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
746
+ alpha_s1, sigma_s1 = self._sigma_to_alpha_sigma_t(sigma_s1)
747
+
748
+ lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
749
+ lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
750
+ lambda_s1 = torch.log(alpha_s1) - torch.log(sigma_s1)
751
+
752
+ m0, m1 = model_output_list[-1], model_output_list[-2]
753
+
754
+ h, h_0 = lambda_t - lambda_s0, lambda_s0 - lambda_s1
755
+ r0 = h_0 / h
756
+ D0, D1 = m0, (1.0 / r0) * (m0 - m1)
757
+ if self.config.algorithm_type == "dpmsolver++":
758
+ # See https://arxiv.org/abs/2211.01095 for detailed derivations
759
+ if self.config.solver_type == "midpoint":
760
+ x_t = (
761
+ (sigma_t / sigma_s0) * sample
762
+ - (alpha_t * (torch.exp(-h) - 1.0)) * D0
763
+ - 0.5 * (alpha_t * (torch.exp(-h) - 1.0)) * D1
764
+ )
765
+ elif self.config.solver_type == "heun":
766
+ x_t = (
767
+ (sigma_t / sigma_s0) * sample
768
+ - (alpha_t * (torch.exp(-h) - 1.0)) * D0
769
+ + (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1
770
+ )
771
+ elif self.config.algorithm_type == "dpmsolver":
772
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
773
+ if self.config.solver_type == "midpoint":
774
+ x_t = (
775
+ (alpha_t / alpha_s0) * sample
776
+ - (sigma_t * (torch.exp(h) - 1.0)) * D0
777
+ - 0.5 * (sigma_t * (torch.exp(h) - 1.0)) * D1
778
+ )
779
+ elif self.config.solver_type == "heun":
780
+ x_t = (
781
+ (alpha_t / alpha_s0) * sample
782
+ - (sigma_t * (torch.exp(h) - 1.0)) * D0
783
+ - (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1
784
+ )
785
+ elif self.config.algorithm_type == "sde-dpmsolver++":
786
+ assert noise is not None
787
+ if self.config.solver_type == "midpoint":
788
+ x_t = (
789
+ (sigma_t / sigma_s0 * torch.exp(-h)) * sample
790
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * D0
791
+ + 0.5 * (alpha_t * (1 - torch.exp(-2.0 * h))) * D1
792
+ + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
793
+ )
794
+ elif self.config.solver_type == "heun":
795
+ x_t = (
796
+ (sigma_t / sigma_s0 * torch.exp(-h)) * sample
797
+ + (alpha_t * (1 - torch.exp(-2.0 * h))) * D0
798
+ + (alpha_t * ((1.0 - torch.exp(-2.0 * h)) / (-2.0 * h) + 1.0)) * D1
799
+ + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise
800
+ )
801
+ elif self.config.algorithm_type == "sde-dpmsolver":
802
+ assert noise is not None
803
+ if self.config.solver_type == "midpoint":
804
+ x_t = (
805
+ (alpha_t / alpha_s0) * sample
806
+ - 2.0 * (sigma_t * (torch.exp(h) - 1.0)) * D0
807
+ - (sigma_t * (torch.exp(h) - 1.0)) * D1
808
+ + sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise
809
+ )
810
+ elif self.config.solver_type == "heun":
811
+ x_t = (
812
+ (alpha_t / alpha_s0) * sample
813
+ - 2.0 * (sigma_t * (torch.exp(h) - 1.0)) * D0
814
+ - 2.0 * (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1
815
+ + sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise
816
+ )
817
+ return x_t
818
+
819
+ def multistep_dpm_solver_third_order_update(
820
+ self,
821
+ model_output_list: List[torch.Tensor],
822
+ *args,
823
+ sample: torch.Tensor = None,
824
+ **kwargs,
825
+ ) -> torch.Tensor:
826
+ """
827
+ One step for the third-order multistep DPMSolver.
828
+
829
+ Args:
830
+ model_output_list (`List[torch.Tensor]`):
831
+ The direct outputs from learned diffusion model at current and latter timesteps.
832
+ sample (`torch.Tensor`):
833
+ A current instance of a sample created by diffusion process.
834
+
835
+ Returns:
836
+ `torch.Tensor`:
837
+ The sample tensor at the previous timestep.
838
+ """
839
+
840
+ timestep_list = args[0] if len(args) > 0 else kwargs.pop("timestep_list", None)
841
+ prev_timestep = args[1] if len(args) > 1 else kwargs.pop("prev_timestep", None)
842
+ if sample is None:
843
+ if len(args) > 2:
844
+ sample = args[2]
845
+ else:
846
+ raise ValueError(" missing`sample` as a required keyward argument")
847
+ if timestep_list is not None:
848
+ deprecate(
849
+ "timestep_list",
850
+ "1.0.0",
851
+ "Passing `timestep_list` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
852
+ )
853
+
854
+ if prev_timestep is not None:
855
+ deprecate(
856
+ "prev_timestep",
857
+ "1.0.0",
858
+ "Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
859
+ )
860
+
861
+ sigma_t, sigma_s0, sigma_s1, sigma_s2 = (
862
+ self.sigmas[self.step_index + 1],
863
+ self.sigmas[self.step_index],
864
+ self.sigmas[self.step_index - 1],
865
+ self.sigmas[self.step_index - 2],
866
+ )
867
+
868
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
869
+ alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
870
+ alpha_s1, sigma_s1 = self._sigma_to_alpha_sigma_t(sigma_s1)
871
+ alpha_s2, sigma_s2 = self._sigma_to_alpha_sigma_t(sigma_s2)
872
+
873
+ lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
874
+ lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
875
+ lambda_s1 = torch.log(alpha_s1) - torch.log(sigma_s1)
876
+ lambda_s2 = torch.log(alpha_s2) - torch.log(sigma_s2)
877
+
878
+ m0, m1, m2 = model_output_list[-1], model_output_list[-2], model_output_list[-3]
879
+
880
+ h, h_0, h_1 = lambda_t - lambda_s0, lambda_s0 - lambda_s1, lambda_s1 - lambda_s2
881
+ r0, r1 = h_0 / h, h_1 / h
882
+ D0 = m0
883
+ D1_0, D1_1 = (1.0 / r0) * (m0 - m1), (1.0 / r1) * (m1 - m2)
884
+ D1 = D1_0 + (r0 / (r0 + r1)) * (D1_0 - D1_1)
885
+ D2 = (1.0 / (r0 + r1)) * (D1_0 - D1_1)
886
+ if self.config.algorithm_type == "dpmsolver++":
887
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
888
+ x_t = (
889
+ (sigma_t / sigma_s0) * sample
890
+ - (alpha_t * (torch.exp(-h) - 1.0)) * D0
891
+ + (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1
892
+ - (alpha_t * ((torch.exp(-h) - 1.0 + h) / h**2 - 0.5)) * D2
893
+ )
894
+ elif self.config.algorithm_type == "dpmsolver":
895
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
896
+ x_t = (
897
+ (alpha_t / alpha_s0) * sample
898
+ - (sigma_t * (torch.exp(h) - 1.0)) * D0
899
+ - (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1
900
+ - (sigma_t * ((torch.exp(h) - 1.0 - h) / h**2 - 0.5)) * D2
901
+ )
902
+ return x_t
903
+
904
+ def index_for_timestep(self, timestep, schedule_timesteps=None):
905
+ if schedule_timesteps is None:
906
+ schedule_timesteps = self.timesteps
907
+
908
+ index_candidates = (schedule_timesteps == timestep).nonzero()
909
+
910
+ if len(index_candidates) == 0:
911
+ step_index = len(self.timesteps) - 1
912
+ # The sigma index that is taken for the **very** first `step`
913
+ # is always the second index (or the last index if there is only 1)
914
+ # This way we can ensure we don't accidentally skip a sigma in
915
+ # case we start in the middle of the denoising schedule (e.g. for image-to-image)
916
+ elif len(index_candidates) > 1:
917
+ step_index = index_candidates[1].item()
918
+ else:
919
+ step_index = index_candidates[0].item()
920
+
921
+ return step_index
922
+
923
+ def _init_step_index(self, timestep):
924
+ """
925
+ Initialize the step_index counter for the scheduler.
926
+ """
927
+
928
+ if self.begin_index is None:
929
+ if isinstance(timestep, torch.Tensor):
930
+ timestep = timestep.to(self.timesteps.device)
931
+ self._step_index = self.index_for_timestep(timestep)
932
+ else:
933
+ self._step_index = self._begin_index
934
+
935
+ def step(
936
+ self,
937
+ model_output: torch.Tensor,
938
+ timestep: int,
939
+ sample: torch.Tensor,
940
+ generator=None,
941
+ variance_noise: Optional[torch.Tensor] = None,
942
+ return_dict: bool = True,
943
+ ) -> Union[SchedulerOutput, Tuple]:
944
+ """
945
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the sample with
946
+ the multistep DPMSolver.
947
+
948
+ Args:
949
+ model_output (`torch.Tensor`):
950
+ The direct output from learned diffusion model.
951
+ timestep (`int`):
952
+ The current discrete timestep in the diffusion chain.
953
+ sample (`torch.Tensor`):
954
+ A current instance of a sample created by the diffusion process.
955
+ generator (`torch.Generator`, *optional*):
956
+ A random number generator.
957
+ variance_noise (`torch.Tensor`):
958
+ Alternative to generating noise with `generator` by directly providing the noise for the variance
959
+ itself. Useful for methods such as [`LEdits++`].
960
+ return_dict (`bool`):
961
+ Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`.
962
+
963
+ Returns:
964
+ [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`:
965
+ If return_dict is `True`, [`~schedulers.scheduling_utils.SchedulerOutput`] is returned, otherwise a
966
+ tuple is returned where the first element is the sample tensor.
967
+
968
+ """
969
+ if self.num_inference_steps is None:
970
+ raise ValueError(
971
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
972
+ )
973
+
974
+ if self.step_index is None:
975
+ self._init_step_index(timestep)
976
+
977
+ # Improve numerical stability for small number of steps
978
+ lower_order_final = (self.step_index == len(self.timesteps) - 1) and (
979
+ self.config.euler_at_final
980
+ or (self.config.lower_order_final and len(self.timesteps) < 15)
981
+ or self.config.final_sigmas_type == "zero"
982
+ )
983
+ lower_order_second = (
984
+ (self.step_index == len(self.timesteps) - 2) and self.config.lower_order_final and len(self.timesteps) < 15
985
+ )
986
+
987
+ model_output = self.convert_model_output(model_output, sample=sample)
988
+ for i in range(self.config.solver_order - 1):
989
+ self.model_outputs[i] = self.model_outputs[i + 1]
990
+ self.model_outputs[-1] = model_output
991
+
992
+ # Upcast to avoid precision issues when computing prev_sample
993
+ sample = sample.to(torch.float32)
994
+ if self.config.algorithm_type in ["sde-dpmsolver", "sde-dpmsolver++"] and variance_noise is None:
995
+ noise = randn_tensor(
996
+ model_output.shape, generator=generator, device=model_output.device, dtype=torch.float32
997
+ )
998
+ elif self.config.algorithm_type in ["sde-dpmsolver", "sde-dpmsolver++"]:
999
+ noise = variance_noise.to(device=model_output.device, dtype=torch.float32)
1000
+ else:
1001
+ noise = None
1002
+
1003
+ if self.config.solver_order == 1 or self.lower_order_nums < 1 or lower_order_final:
1004
+ prev_sample = self.dpm_solver_first_order_update(model_output, sample=sample, noise=noise)
1005
+ elif self.config.solver_order == 2 or self.lower_order_nums < 2 or lower_order_second:
1006
+ prev_sample = self.multistep_dpm_solver_second_order_update(self.model_outputs, sample=sample, noise=noise)
1007
+ else:
1008
+ prev_sample = self.multistep_dpm_solver_third_order_update(self.model_outputs, sample=sample)
1009
+
1010
+ if self.lower_order_nums < self.config.solver_order:
1011
+ self.lower_order_nums += 1
1012
+
1013
+ # Cast sample back to expected dtype
1014
+ prev_sample = prev_sample.to(model_output.dtype)
1015
+
1016
+ # upon completion increase step index by one
1017
+ self._step_index += 1
1018
+
1019
+ if not return_dict:
1020
+ return (prev_sample,)
1021
+
1022
+ return SchedulerOutput(prev_sample=prev_sample)
1023
+
1024
+ def add_noise(
1025
+ self,
1026
+ original_samples: torch.Tensor,
1027
+ noise: torch.Tensor,
1028
+ timesteps: torch.IntTensor,
1029
+ ) -> torch.Tensor:
1030
+ # Make sure sigmas and timesteps have the same device and dtype as original_samples
1031
+ # alpha_t = self.alpha_t.to(device=original_samples.device, dtype=original_samples.dtype)
1032
+ # sigma_t = self.sigma_t.to(device=original_samples.device, dtype=original_samples.dtype)
1033
+ alpha_t = self.alpha_t.to(original_samples.device).to(original_samples.dtype)
1034
+ sigma_t = self.sigma_t.to(original_samples.device).to(original_samples.dtype)
1035
+ timesteps = timesteps.to(original_samples.device)
1036
+ alpha_t = alpha_t[timesteps].flatten()
1037
+ while len(alpha_t.shape) < len(original_samples.shape):
1038
+ alpha_t = alpha_t.unsqueeze(-1)
1039
+
1040
+ sigma_t = sigma_t[timesteps].flatten()
1041
+ while len(sigma_t.shape) < len(original_samples.shape):
1042
+ sigma_t = sigma_t.unsqueeze(-1)
1043
+ noisy_samples = alpha_t * original_samples + sigma_t * noise
1044
+ return noisy_samples
1045
+
1046
+ def get_velocity(self, original_samples: torch.Tensor, noise: torch.Tensor, timesteps: torch.IntTensor) -> torch.Tensor:
1047
+ # alpha_t = self.alpha_t.to(device=original_samples.device, dtype=original_samples.dtype)
1048
+ # sigma_t = self.sigma_t.to(device=original_samples.device, dtype=original_samples.dtype)
1049
+ alpha_t = self.alpha_t.to(original_samples.device).to(original_samples.dtype)
1050
+ sigma_t = self.sigma_t.to(original_samples.device).to(original_samples.dtype)
1051
+
1052
+ timesteps = timesteps.to(original_samples.device)
1053
+ alpha_t = alpha_t[timesteps].flatten()
1054
+ while len(alpha_t.shape) < len(original_samples.shape):
1055
+ alpha_t = alpha_t.unsqueeze(-1)
1056
+
1057
+ sigma_t = sigma_t[timesteps].flatten()
1058
+ while len(sigma_t.shape) < len(original_samples.shape):
1059
+ sigma_t = sigma_t.unsqueeze(-1)
1060
+
1061
+ velocity = alpha_t * noise - sigma_t * original_samples
1062
+ return velocity
1063
+
1064
+ def __len__(self):
1065
+ return self.config.num_train_timesteps
VibeVoice-tpu/src/vibevoice/schedule/timestep_sampler.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+
4
+
5
+ class UniformSampler:
6
+ def __init__(self, timesteps = 1000):
7
+ self.timesteps = timesteps
8
+ def sample(self, batch_size, device):
9
+ return torch.randint(0, self.timesteps, (batch_size,), device=device)
10
+
11
+ class LogitNormalSampler:
12
+ def __init__(self, timesteps = 1000, m = 0, s = 1):
13
+ self.timesteps = timesteps
14
+ timesteps = torch.linspace(0, 1, timesteps)
15
+ logit = torch.log(timesteps / (1 - timesteps))
16
+ self.prob = torch.exp(-0.5 * (logit - m) ** 2 / s ** 2) / (s * math.sqrt(2 * math.pi))
17
+ def sample(self, batch_size, device):
18
+ return torch.multinomial(self.prob, batch_size, replacement=True).to(device)
19
+
VibeVoice-tpu/src/vibevoice/scripts/convert_nnscaler_checkpoint_to_transformers.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+
4
+ import argparse
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import re
9
+ import torch
10
+ from typing import Dict, List, Tuple
11
+
12
+ from vibevoice.modular.configuration_vibevoice import (
13
+ VibeVoiceConfig
14
+ )
15
+ from vibevoice.modular.modeling_vibevoice import VibeVoiceForConditionalGeneration
16
+ from transformers.utils import logging
17
+
18
+ logger = logging.get_logger(__name__)
19
+
20
+ def convert_vibevoice_nnscaler_checkpoint_to_hf(
21
+ checkpoint_path: str,
22
+ pytorch_dump_folder_path: str,
23
+ config_path: str = None,
24
+ ):
25
+ """
26
+ Convert a nnscaler VibeVoice checkpoint to HuggingFace format.
27
+ Supports both regular checkpoints and tensor parallel checkpoints.
28
+ """
29
+
30
+ # Load regular checkpoint
31
+ logger.info(f"Loading regular checkpoint from {checkpoint_path}")
32
+ checkpoint = torch.load(checkpoint_path, map_location="cpu") # ['model', 'optimizer', 'lr_scheduler', 'train_status', 'train_args', 'rng_states', 'nnscaler', 'dataloader']
33
+
34
+ # config = checkpoint['train_args']
35
+ init_config_name = checkpoint['train_args']['vars']['model_args']['config_path']['relative_path']
36
+ pretrained_name = checkpoint['train_args']['vars']['data_args']['tokenizer_path']
37
+
38
+ init_config_path = Path(__file__).parent.parent / 'configs' / init_config_name.split('/')[-1]
39
+ if init_config_path.exists():
40
+ logger.info(f"Loading initial config from {init_config_path}")
41
+ with open(init_config_path, 'r') as f:
42
+ init_config = json.load(f)
43
+ else:
44
+ raise FileNotFoundError(f"Initial config file {init_config_path} not found. Please provide a valid path.")
45
+
46
+ tie_word_embeddings = init_config['decoder_config'].get('tie_word_embeddings', True)
47
+ logger.info(f"Tie word embeddings: {tie_word_embeddings}")
48
+
49
+ init_config['decoder_config']['use_cache'] = True
50
+ config = VibeVoiceConfig(**init_config, tie_word_embeddings=tie_word_embeddings)
51
+
52
+ # # Extract the model state dict
53
+ model_state_dict = {k.replace('model.model.', 'model.'): v for k, v in checkpoint["model"].items() if k.startswith('model.model.')}
54
+ if not tie_word_embeddings and 'model.lm_head.weight' in checkpoint["model"].keys():
55
+ # If not tying weights, we need to add the lm_head weight separately
56
+ model_state_dict['lm_head.weight'] = checkpoint["model"]['model.lm_head.weight']
57
+
58
+ # Override with provided config if available
59
+ if config_path:
60
+ logger.info(f"Loading config from {config_path}")
61
+ with open(config_path, 'r') as f:
62
+ config_dict = json.load(f)
63
+ config = VibeVoiceConfig.from_dict(config_dict)
64
+
65
+ # Set the default dtype to bfloat16 before creating the model
66
+ original_dtype = torch.get_default_dtype()
67
+ torch.set_default_dtype(torch.bfloat16)
68
+
69
+ # Create the HuggingFace model
70
+ logger.info("Creating HuggingFace VibeVoiceForConditionalGeneration model")
71
+ model = VibeVoiceForConditionalGeneration(config)
72
+
73
+ # Restore original dtype
74
+ torch.set_default_dtype(original_dtype)
75
+
76
+ # Load the state dict
77
+ logger.info("Loading weights into model")
78
+ missing_keys, unexpected_keys = model.load_state_dict(model_state_dict, strict=False)
79
+
80
+ if missing_keys:
81
+ logger.warning(f"Missing keys: {missing_keys}")
82
+ if unexpected_keys:
83
+ logger.warning(f"Unexpected keys: {unexpected_keys}")
84
+
85
+ # Create output directory
86
+ os.makedirs(pytorch_dump_folder_path, exist_ok=True)
87
+
88
+ # Save the model and config
89
+ logger.info(f"Saving model to {pytorch_dump_folder_path}")
90
+
91
+ # Save config
92
+ config.save_pretrained(pytorch_dump_folder_path)
93
+
94
+ # Save VibeVoiceProcessor configuration
95
+ logger.info("Saving VibeVoiceProcessor configuration")
96
+ processor_config = {
97
+ "processor_class": "VibeVoiceProcessor",
98
+ "speech_tok_compress_ratio": 3200,
99
+ "db_normalize": True,
100
+ # Audio processor configuration
101
+ "audio_processor": {
102
+ "feature_extractor_type": "VibeVoiceTokenizerProcessor",
103
+ "sampling_rate": 24000,
104
+ "normalize_audio": True,
105
+ "target_dB_FS": -25,
106
+ "eps": 1e-6,
107
+ },
108
+ "language_model_pretrained_name": pretrained_name,
109
+ }
110
+
111
+ processor_config_path = os.path.join(pytorch_dump_folder_path, "preprocessor_config.json")
112
+ with open(processor_config_path, 'w') as f:
113
+ json.dump(processor_config, f, indent=2)
114
+ logger.info(f"Saved processor config to {processor_config_path}")
115
+
116
+ # Save model with sharding
117
+ # save_pretrained handles tied weights automatically
118
+ logger.info("Saving model weights with sharding...")
119
+ model.save_pretrained(
120
+ pytorch_dump_folder_path,
121
+ max_shard_size="2GB", # Set maximum size for each shard
122
+ safe_serialization=True # Ensure saving in .safetensors format
123
+ )
124
+ logger.info(f"Model weights saved to {pytorch_dump_folder_path}")
125
+
126
+ logger.info("Conversion complete!")
127
+
128
+ # Verify the saved model can be loaded
129
+ logger.info("Verifying saved model...")
130
+ loaded_model = VibeVoiceForConditionalGeneration.from_pretrained(pytorch_dump_folder_path)
131
+ logger.info("Model successfully loaded from saved checkpoint!")
132
+
133
+ def main():
134
+ parser = argparse.ArgumentParser()
135
+ parser.add_argument(
136
+ "--nnscaler_checkpoint_path",
137
+ type=str,
138
+ required=True,
139
+ help="Path to the fairseq checkpoint (.pt file). For tensor parallel checkpoints, "
140
+ "provide any one of the part files (e.g., checkpoint_1_5000-model_part-0.pt), "
141
+ "and the script will automatically detect and merge all parts.",
142
+ )
143
+ parser.add_argument(
144
+ "--pytorch_dump_folder_path",
145
+ type=str,
146
+ required=True,
147
+ help="Path to the output PyTorch model directory",
148
+ )
149
+ parser.add_argument(
150
+ "--config_path",
151
+ type=str,
152
+ default=None,
153
+ help="Optional path to a config JSON file to override extracted config",
154
+ )
155
+
156
+ args = parser.parse_args()
157
+
158
+ convert_vibevoice_nnscaler_checkpoint_to_hf(
159
+ args.nnscaler_checkpoint_path,
160
+ args.pytorch_dump_folder_path,
161
+ args.config_path,
162
+ )
163
+
164
+
165
+ if __name__ == "__main__":
166
+ main()
VibeVoice-tpu/src/vibevoice_surgery_colab.ipynb ADDED
@@ -0,0 +1,2156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "gpuType": "T4"
8
+ },
9
+ "kernelspec": {
10
+ "name": "python3",
11
+ "display_name": "Python 3"
12
+ },
13
+ "language_info": {
14
+ "name": "python"
15
+ },
16
+ "accelerator": "GPU",
17
+ "gpuClass": "standard"
18
+ },
19
+ "cells": [
20
+ {
21
+ "cell_type": "markdown",
22
+ "metadata": {},
23
+ "source": [
24
+ "# 🔬 VibeVoice Surgery — Colab Notebook\n",
25
+ "## Replacing Qwen2.5-7B with Qwen3-4B + Surgery Module\n",
26
+ "\n",
27
+ "This notebook performs **model surgery** on `VibeVoice-7B`, replacing the Qwen2.5-7B\n",
28
+ "language model with Qwen3-4B and adding a **Surgery Module** to bridge the hidden\n",
29
+ "dimension gap (2560 → 3584) for the Diffusion Head.\n",
30
+ "\n",
31
+ "### Architecture Overview\n",
32
+ "\n",
33
+ "```\n",
34
+ "Audio → AcousticTokenizer (64-dim) → AcousticConnector → (2560-dim)\n",
35
+ "Audio → SemanticTokenizer (128-dim) → SemanticConnector → (2560-dim)\n",
36
+ "Combined → Qwen3-4B → hidden_states[37 × 2560-dim]\n",
37
+ " → SurgeryModule → (3584-dim) → DiffusionHead → Speech\n",
38
+ " → LMHead → Text Tokens\n",
39
+ "```\n",
40
+ "\n",
41
+ "### Surgery Module Pipeline\n",
42
+ "1. **Hierarchical Feature Extraction** — extract hidden states from 4 intermediate Qwen3 layers\n",
43
+ "2. **Learnable Weighted Sum** — softmax-weighted average\n",
44
+ "3. **RMSNorm** — numerical stabilisation\n",
45
+ "4. **SwiGLU** — non-linear translation between vector spaces\n",
46
+ "5. **Linear Projection** — upscale 2560 → 3584\n",
47
+ "\n",
48
+ "### Requirements\n",
49
+ "- GPU with ≥16 GB VRAM (T4, A100, etc.)\n",
50
+ "- ~30 GB system RAM for surgery phase\n",
51
+ "- `transformers >= 4.51.0` (for Qwen3 support)"
52
+ ]
53
+ },
54
+ {
55
+ "cell_type": "markdown",
56
+ "metadata": {},
57
+ "source": [
58
+ "---\n",
59
+ "## 1. Install Dependencies"
60
+ ]
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "execution_count": null,
65
+ "metadata": {},
66
+ "outputs": [],
67
+ "source": [
68
+ "# Install/upgrade dependencies\n",
69
+ "!pip install -q \"transformers>=4.51.0\" accelerate torch torchvision\n",
70
+ "!pip install -q peft tqdm safetensors\n",
71
+ "\n",
72
+ "# Verify GPU availability\n",
73
+ "import torch\n",
74
+ "print(f\"CUDA available: {torch.cuda.is_available()}\")\n",
75
+ "print(f\"GPU count: {torch.cuda.device_count()}\")\n",
76
+ "for i in range(torch.cuda.device_count()):\n",
77
+ " print(f\" GPU {i}: {torch.cuda.get_device_name(i)} — {torch.cuda.get_device_properties(i).total_mem / 1e9:.1f} GB\")"
78
+ ]
79
+ },
80
+ {
81
+ "cell_type": "markdown",
82
+ "metadata": {},
83
+ "source": [
84
+ "---\n",
85
+ "## 2. Clone VibeVoice Repository"
86
+ ]
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "execution_count": null,
91
+ "metadata": {},
92
+ "outputs": [],
93
+ "source": [
94
+ "import os\n",
95
+ "import sys\n",
96
+ "\n",
97
+ "# Clone the VibeVoice repository if not already present\n",
98
+ "REPO_URL = \"https://github.com/microsoft/VibeVoice.git\" # Adjust URL as needed\n",
99
+ "REPO_DIR = \"/content/VibeVoice\"\n",
100
+ "\n",
101
+ "if not os.path.exists(REPO_DIR):\n",
102
+ " !git clone $REPO_URL $REPO_DIR\n",
103
+ "else:\n",
104
+ " print(f\"Repository already exists at {REPO_DIR}\")\n",
105
+ "\n",
106
+ "# Add src to path\n",
107
+ "SRC_DIR = os.path.join(REPO_DIR, \"src\")\n",
108
+ "if SRC_DIR not in sys.path:\n",
109
+ " sys.path.insert(0, SRC_DIR)\n",
110
+ "\n",
111
+ "os.chdir(SRC_DIR)\n",
112
+ "print(f\"Working directory: {os.getcwd()}\")"
113
+ ]
114
+ },
115
+ {
116
+ "cell_type": "markdown",
117
+ "metadata": {},
118
+ "source": [
119
+ "---\n",
120
+ "## 3. Global Configuration"
121
+ ]
122
+ },
123
+ {
124
+ "cell_type": "code",
125
+ "execution_count": null,
126
+ "metadata": {},
127
+ "outputs": [],
128
+ "source": [
129
+ "import torch\n",
130
+ "import torch.nn as nn\n",
131
+ "import torch.nn.functional as F\n",
132
+ "\n",
133
+ "# ── Precision ──\n",
134
+ "# T4 GPUs (Turing architecture) do NOT support bfloat16 efficiently.\n",
135
+ "# Use float16 for T4. For A100/H100, you can use bfloat16.\n",
136
+ "DTYPE = torch.float16\n",
137
+ "\n",
138
+ "# ── Qwen3-4B dimensions ──\n",
139
+ "QWEN3_HIDDEN_SIZE = 2560\n",
140
+ "QWEN3_NUM_LAYERS = 36\n",
141
+ "QWEN3_VOCAB_SIZE = 151936\n",
142
+ "QWEN3_MODEL_ID = \"Qwen/Qwen3-4B-Instruct-2507\"\n",
143
+ "\n",
144
+ "# ── VibeVoice Diffusion Head dimensions (unchanged) ──\n",
145
+ "DIFFUSION_HIDDEN_SIZE = 3584\n",
146
+ "\n",
147
+ "# ── Surgery: which intermediate layers of Qwen3 to extract (0-indexed) ──\n",
148
+ "# Layers 24, 28, 32, 34 out of 36 total\n",
149
+ "SURGERY_LAYER_INDICES = [24, 28, 32, 34]\n",
150
+ "\n",
151
+ "# ── Attention implementation ──\n",
152
+ "# T4 GPUs (Turing architecture) do NOT support flash_attention_2.\n",
153
+ "# Always use \"sdpa\" for T4 / Turing compatibility.\n",
154
+ "ATTN_IMPL = \"sdpa\"\n",
155
+ "\n",
156
+ "# ── Model paths ──\n",
157
+ "VIBEVOICE_MODEL_ID = \"vibevoice/VibeVoice-7B\"\n",
158
+ "OUTPUT_DIR = \"/content/vibevoice_qwen3_surgery\"\n",
159
+ "\n",
160
+ "print(f\"╔══════════════════════════════════════════════════════════════╗\")\n",
161
+ "print(f\"║ VibeVoice Surgery — Configuration ║\")\n",
162
+ "print(f\"╠══════════════════════════════════════════════════════════════╣\")\n",
163
+ "print(f\"║ Dtype: {str(DTYPE):<42}║\")\n",
164
+ "print(f\"║ Attention: {ATTN_IMPL:<42}║\")\n",
165
+ "print(f\"║ Qwen3 hidden: {QWEN3_HIDDEN_SIZE:<42}║\")\n",
166
+ "print(f\"║ Qwen3 layers: {QWEN3_NUM_LAYERS:<42}║\")\n",
167
+ "print(f\"║ Diffusion hidden: {DIFFUSION_HIDDEN_SIZE:<42}║\")\n",
168
+ "print(f\"║ Surgery layers: {str(SURGERY_LAYER_INDICES):<42}║\")\n",
169
+ "print(f\"╚══════════════════════════════════════════════════════════════╝\")"
170
+ ]
171
+ },
172
+ {
173
+ "cell_type": "markdown",
174
+ "metadata": {},
175
+ "source": [
176
+ "---\n",
177
+ "## 4. Monkey-patch VibeVoiceConfig for Qwen3 Support\n",
178
+ "\n",
179
+ "The original `VibeVoiceConfig` only accepts `decoder_config` with `model_type=\"qwen2\"`.\n",
180
+ "This patch adds support for `model_type=\"qwen3\"`."
181
+ ]
182
+ },
183
+ {
184
+ "cell_type": "code",
185
+ "execution_count": null,
186
+ "metadata": {},
187
+ "outputs": [],
188
+ "source": [
189
+ "import types\n",
190
+ "import functools\n",
191
+ "import warnings\n",
192
+ "from typing import Optional, Tuple, Union, List, Dict, Any\n",
193
+ "\n",
194
+ "from transformers import (\n",
195
+ " AutoModel,\n",
196
+ " AutoModelForCausalLM,\n",
197
+ " AutoConfig,\n",
198
+ " AutoTokenizer,\n",
199
+ ")\n",
200
+ "from transformers.modeling_outputs import BaseModelOutputWithPast, ModelOutput\n",
201
+ "from transformers.models.llama.modeling_llama import LlamaRMSNorm\n",
202
+ "from transformers.utils import logging\n",
203
+ "\n",
204
+ "# Import VibeVoice components\n",
205
+ "from vibevoice.modular.configuration_vibevoice import (\n",
206
+ " VibeVoiceConfig,\n",
207
+ " VibeVoiceDiffusionHeadConfig,\n",
208
+ ")\n",
209
+ "from vibevoice.modular.modeling_vibevoice import (\n",
210
+ " VibeVoiceModel,\n",
211
+ " VibeVoiceForConditionalGeneration,\n",
212
+ " SpeechConnector,\n",
213
+ ")\n",
214
+ "from vibevoice.modular.modeling_vibevoice_inference import (\n",
215
+ " VibeVoiceForConditionalGenerationInference,\n",
216
+ " VibeVoiceCausalLMOutputWithPast,\n",
217
+ " VibeVoiceGenerationOutput,\n",
218
+ " VibeVoiceTokenConstraintProcessor,\n",
219
+ ")\n",
220
+ "from vibevoice.modular.modular_vibevoice_tokenizer import VibeVoiceTokenizerStreamingCache\n",
221
+ "\n",
222
+ "logger = logging.get_logger(__name__)\n",
223
+ "print(\"✅ VibeVoice modules imported successfully\")"
224
+ ]
225
+ },
226
+ {
227
+ "cell_type": "code",
228
+ "execution_count": null,
229
+ "metadata": {},
230
+ "outputs": [],
231
+ "source": [
232
+ "def _patch_vibevoice_config_for_qwen3():\n",
233
+ " \"\"\"\n",
234
+ " Monkey-patch VibeVoiceConfig.__init__ to accept Qwen3Config as decoder_config.\n",
235
+ " \n",
236
+ " The original VibeVoiceConfig only accepts decoder_config with model_type=\"qwen2\".\n",
237
+ " This patch adds support for model_type=\"qwen3\" by importing Qwen3Config and\n",
238
+ " handling it alongside Qwen2Config.\n",
239
+ " \"\"\"\n",
240
+ " try:\n",
241
+ " from transformers import Qwen3Config\n",
242
+ " except ImportError:\n",
243
+ " raise ImportError(\n",
244
+ " \"Qwen3Config not found. Please upgrade transformers: \"\n",
245
+ " \"pip install 'transformers>=4.51.0'\"\n",
246
+ " )\n",
247
+ " \n",
248
+ " from transformers.models.qwen2.configuration_qwen2 import Qwen2Config\n",
249
+ " from transformers.configuration_utils import PretrainedConfig\n",
250
+ " \n",
251
+ " _orig_init = VibeVoiceConfig.__init__\n",
252
+ " \n",
253
+ " def _new_init(\n",
254
+ " self,\n",
255
+ " acoustic_tokenizer_config=None,\n",
256
+ " semantic_tokenizer_config=None,\n",
257
+ " decoder_config=None,\n",
258
+ " diffusion_head_config=None,\n",
259
+ " **kwargs\n",
260
+ " ):\n",
261
+ " kwargs[\"_attn_implementation_autoset\"] = False\n",
262
+ " \n",
263
+ " # ── acoustic_tokenizer_config ──\n",
264
+ " if acoustic_tokenizer_config is None:\n",
265
+ " self.acoustic_tokenizer_config = self.sub_configs[\"acoustic_tokenizer_config\"]()\n",
266
+ " elif isinstance(acoustic_tokenizer_config, dict):\n",
267
+ " acoustic_tokenizer_config[\"model_type\"] = \"vibevoice_acoustic_tokenizer\"\n",
268
+ " self.acoustic_tokenizer_config = self.sub_configs[\"acoustic_tokenizer_config\"](\n",
269
+ " **acoustic_tokenizer_config\n",
270
+ " )\n",
271
+ " else:\n",
272
+ " self.acoustic_tokenizer_config = acoustic_tokenizer_config\n",
273
+ " \n",
274
+ " # ── semantic_tokenizer_config ──\n",
275
+ " if semantic_tokenizer_config is None:\n",
276
+ " self.semantic_tokenizer_config = self.sub_configs[\"semantic_tokenizer_config\"]()\n",
277
+ " elif isinstance(semantic_tokenizer_config, dict):\n",
278
+ " semantic_tokenizer_config[\"model_type\"] = \"vibevoice_semantic_tokenizer\"\n",
279
+ " self.semantic_tokenizer_config = self.sub_configs[\"semantic_tokenizer_config\"](\n",
280
+ " **semantic_tokenizer_config\n",
281
+ " )\n",
282
+ " else:\n",
283
+ " self.semantic_tokenizer_config = semantic_tokenizer_config\n",
284
+ " \n",
285
+ " # ── decoder_config (NOW SUPPORTS QWEN3!) ──\n",
286
+ " if decoder_config is None:\n",
287
+ " self.decoder_config = self.sub_configs[\"decoder_config\"]()\n",
288
+ " elif isinstance(decoder_config, dict):\n",
289
+ " model_type = decoder_config.get(\"model_type\", \"\")\n",
290
+ " if model_type == \"qwen2\":\n",
291
+ " self.decoder_config = Qwen2Config(**decoder_config)\n",
292
+ " elif model_type == \"qwen3\":\n",
293
+ " self.decoder_config = Qwen3Config(**decoder_config)\n",
294
+ " else:\n",
295
+ " try:\n",
296
+ " self.decoder_config = Qwen2Config(**decoder_config)\n",
297
+ " except Exception:\n",
298
+ " raise ValueError(\n",
299
+ " f\"Unsupported decoder model type: {model_type}. \"\n",
300
+ " f\"Supported: 'qwen2', 'qwen3'\"\n",
301
+ " )\n",
302
+ " elif isinstance(decoder_config, (Qwen2Config, Qwen3Config)):\n",
303
+ " self.decoder_config = decoder_config\n",
304
+ " elif isinstance(decoder_config, PretrainedConfig):\n",
305
+ " self.decoder_config = decoder_config\n",
306
+ " else:\n",
307
+ " raise ValueError(f\"Invalid decoder_config type: {type(decoder_config)}\")\n",
308
+ " \n",
309
+ " # ── diffusion_head_config ──\n",
310
+ " if diffusion_head_config is None:\n",
311
+ " self.diffusion_head_config = self.sub_configs[\"diffusion_head_config\"]()\n",
312
+ " elif isinstance(diffusion_head_config, dict):\n",
313
+ " diffusion_head_config[\"model_type\"] = \"vibevoice_diffusion_head\"\n",
314
+ " self.diffusion_head_config = self.sub_configs[\"diffusion_head_config\"](\n",
315
+ " **diffusion_head_config\n",
316
+ " )\n",
317
+ " else:\n",
318
+ " self.diffusion_head_config = diffusion_head_config\n",
319
+ " \n",
320
+ " # Derived dimensions\n",
321
+ " self.acoustic_vae_dim = getattr(self.acoustic_tokenizer_config, \"vae_dim\", 64)\n",
322
+ " self.semantic_vae_dim = getattr(self.semantic_tokenizer_config, \"vae_dim\", 128)\n",
323
+ " \n",
324
+ " PretrainedConfig.__init__(self, **kwargs)\n",
325
+ " \n",
326
+ " VibeVoiceConfig.__init__ = _new_init\n",
327
+ " print(\"✅ VibeVoiceConfig patched to accept Qwen3Config\")\n",
328
+ "\n",
329
+ "\n",
330
+ "# Apply the patch immediately\n",
331
+ "_patch_vibevoice_config_for_qwen3()"
332
+ ]
333
+ },
334
+ {
335
+ "cell_type": "markdown",
336
+ "metadata": {},
337
+ "source": [
338
+ "---\n",
339
+ "## 5. Surgery Module Definition\n",
340
+ "\n",
341
+ "The `Qwen3SurgeryModule` bridges Qwen3-4B (2560-dim) to the VibeVoice Diffusion Head (3584-dim).\n",
342
+ "\n",
343
+ "### Pipeline:\n",
344
+ "1. **Hierarchical Feature Extraction** — extract hidden states from 4 intermediate Qwen3 layers (rich prosody / emotion / phonetic info)\n",
345
+ "2. **Learnable Weighted Sum** — softmax-weighted average (memory-efficient)\n",
346
+ "3. **RMSNorm** — numerical stabilisation across layer magnitudes\n",
347
+ "4. **SwiGLU** — non-linear translation between vector spaces\n",
348
+ "5. **Linear Projection** — upscale 2560 → 3584 for the Diffusion Head\n",
349
+ "\n",
350
+ "### Initialization Strategy:\n",
351
+ "- **Zero-init output projection** → safe start for fine-tuning (model behaves like original at start)\n",
352
+ "- **Zero-init layer weights** → uniform weighting after softmax\n",
353
+ "- **Normal init SwiGLU** → standard initialization for non-linear layers"
354
+ ]
355
+ },
356
+ {
357
+ "cell_type": "code",
358
+ "execution_count": null,
359
+ "metadata": {},
360
+ "outputs": [],
361
+ "source": [
362
+ "class Qwen3SurgeryModule(nn.Module):\n",
363
+ " \"\"\"\n",
364
+ " Bridges Qwen3-4B (2560-dim) to VibeVoice Diffusion Head (3584-dim).\n",
365
+ "\n",
366
+ " Pipeline:\n",
367
+ " 1. Hierarchical Feature Extraction — extract hidden states from 4\n",
368
+ " intermediate Qwen3 layers (rich prosody / emotion / phonetic info)\n",
369
+ " 2. Learnable Weighted Sum — softmax-weighted average (memory-efficient)\n",
370
+ " 3. RMSNorm — numerical stabilisation across layer magnitudes\n",
371
+ " 4. SwiGLU — non-linear translation between vector spaces\n",
372
+ " 5. Linear Projection — upscale 2560 → 3584 for the Diffusion Head\n",
373
+ "\n",
374
+ " Args:\n",
375
+ " input_dim: Qwen3 hidden size (2560)\n",
376
+ " output_dim: Diffusion Head hidden size (3584)\n",
377
+ " layer_indices: 0-indexed transformer layer indices to extract\n",
378
+ " rms_norm_eps: Epsilon for RMSNorm\n",
379
+ " \"\"\"\n",
380
+ "\n",
381
+ " def __init__(\n",
382
+ " self,\n",
383
+ " input_dim: int = 2560,\n",
384
+ " output_dim: int = 3584,\n",
385
+ " layer_indices: Optional[List[int]] = None,\n",
386
+ " rms_norm_eps: float = 1e-6,\n",
387
+ " ):\n",
388
+ " super().__init__()\n",
389
+ " if layer_indices is None:\n",
390
+ " layer_indices = [24, 28, 32, 34]\n",
391
+ "\n",
392
+ " self.input_dim = input_dim\n",
393
+ " self.output_dim = output_dim\n",
394
+ " self.layer_indices = layer_indices\n",
395
+ " self.num_layers = len(layer_indices)\n",
396
+ "\n",
397
+ " # Step 2: Learnable Weighted Sum\n",
398
+ " self.layer_weights = nn.Parameter(torch.zeros(self.num_layers))\n",
399
+ "\n",
400
+ " # Step 3: RMSNorm\n",
401
+ " self.norm = LlamaRMSNorm(input_dim, eps=rms_norm_eps)\n",
402
+ "\n",
403
+ " # Step 4: SwiGLU\n",
404
+ " self.swiglu_gate = nn.Linear(input_dim, input_dim, bias=False)\n",
405
+ " self.swiglu_up = nn.Linear(input_dim, input_dim, bias=False)\n",
406
+ "\n",
407
+ " # Step 5: Linear Projection\n",
408
+ " self.output_proj = nn.Linear(input_dim, output_dim, bias=False)\n",
409
+ "\n",
410
+ " self._initialize_weights()\n",
411
+ "\n",
412
+ " def _initialize_weights(self):\n",
413
+ " nn.init.normal_(self.swiglu_gate.weight, std=0.02)\n",
414
+ " nn.init.normal_(self.swiglu_up.weight, std=0.02)\n",
415
+ " # Zero-init output → safe start for fine-tuning\n",
416
+ " nn.init.zeros_(self.output_proj.weight)\n",
417
+ " nn.init.zeros_(self.layer_weights)\n",
418
+ "\n",
419
+ " def forward(self, all_hidden_states: Tuple[torch.Tensor, ...]) -> torch.Tensor:\n",
420
+ " \"\"\"\n",
421
+ " Args:\n",
422
+ " all_hidden_states: Tuple of (num_layers+1) tensors [B, Seq, input_dim].\n",
423
+ " Index 0 = embedding, index i+1 = transformer layer i.\n",
424
+ "\n",
425
+ " Returns:\n",
426
+ " Transformed features [B, Seq, output_dim]\n",
427
+ " \"\"\"\n",
428
+ " # Step 1: Extract selected layers\n",
429
+ " selected = [all_hidden_states[i + 1] for i in self.layer_indices]\n",
430
+ "\n",
431
+ " # Step 2: Weighted sum\n",
432
+ " weights = F.softmax(self.layer_weights, dim=0)\n",
433
+ " merged = torch.zeros_like(selected[0])\n",
434
+ " for w, h in zip(weights, selected):\n",
435
+ " merged = merged + w * h\n",
436
+ "\n",
437
+ " # Step 3: Normalise\n",
438
+ " merged = self.norm(merged)\n",
439
+ "\n",
440
+ " # Step 4: SwiGLU\n",
441
+ " gate = F.silu(self.swiglu_gate(merged))\n",
442
+ " up = self.swiglu_up(merged)\n",
443
+ " hidden = gate * up\n",
444
+ "\n",
445
+ " # Step 5: Project\n",
446
+ " return self.output_proj(hidden)\n",
447
+ "\n",
448
+ " def extra_repr(self) -> str:\n",
449
+ " return (\n",
450
+ " f\"input_dim={self.input_dim}, output_dim={self.output_dim}, \"\n",
451
+ " f\"layers={self.layer_indices}\"\n",
452
+ " )\n",
453
+ "\n",
454
+ "\n",
455
+ "print(\"✅ Surgery Module class defined\")"
456
+ ]
457
+ },
458
+ {
459
+ "cell_type": "markdown",
460
+ "metadata": {},
461
+ "source": [
462
+ "---\n",
463
+ "## 6. Surgery Functions\n",
464
+ "\n",
465
+ "Core functions that perform the actual model surgery:\n",
466
+ "- `create_qwen3_config_for_surgery()` — creates Qwen3Config with correct parameters\n",
467
+ "- `perform_surgery()` — the main surgery function that replaces LM, connectors, and adds surgery module\n",
468
+ "- `_patch_base_model_forward()` — forces `output_hidden_states=True`\n",
469
+ "- `_patch_inference_forward()` — includes hidden_states in forward output\n",
470
+ "- `_patch_generate_method()` — integrates surgery module into generation loop"
471
+ ]
472
+ },
473
+ {
474
+ "cell_type": "code",
475
+ "execution_count": null,
476
+ "metadata": {},
477
+ "outputs": [],
478
+ "source": [
479
+ "def create_qwen3_config_for_surgery():\n",
480
+ " \"\"\"Create a Qwen3Config with the correct parameters for surgery.\"\"\"\n",
481
+ " from transformers import Qwen3Config\n",
482
+ " \n",
483
+ " return Qwen3Config(\n",
484
+ " hidden_size=QWEN3_HIDDEN_SIZE,\n",
485
+ " num_hidden_layers=QWEN3_NUM_LAYERS,\n",
486
+ " num_attention_heads=32,\n",
487
+ " num_key_value_heads=8,\n",
488
+ " intermediate_size=9728,\n",
489
+ " hidden_act=\"silu\",\n",
490
+ " max_position_embeddings=262144,\n",
491
+ " max_window_layers=36,\n",
492
+ " rms_norm_eps=1e-6,\n",
493
+ " vocab_size=QWEN3_VOCAB_SIZE,\n",
494
+ " tie_word_embeddings=True,\n",
495
+ " rope_theta=5000000,\n",
496
+ " head_dim=128,\n",
497
+ " torch_dtype=\"float16\",\n",
498
+ " _attn_implementation=ATTN_IMPL,\n",
499
+ " )\n",
500
+ "\n",
501
+ "\n",
502
+ "print(\"✅ Qwen3 config factory defined\")"
503
+ ]
504
+ },
505
+ {
506
+ "cell_type": "code",
507
+ "execution_count": null,
508
+ "metadata": {},
509
+ "outputs": [],
510
+ "source": [
511
+ "def _update_config_for_qwen3(model):\n",
512
+ " \"\"\"Update the model's config to reflect Qwen3 decoder dimensions.\"\"\"\n",
513
+ " qwen3_config = create_qwen3_config_for_surgery()\n",
514
+ " model.config.decoder_config = qwen3_config\n",
515
+ " model.config.tie_word_embeddings = True\n",
516
+ "\n",
517
+ "\n",
518
+ "def _patch_base_model_forward(model: VibeVoiceModel):\n",
519
+ " \"\"\"\n",
520
+ " Patch VibeVoiceModel.forward to always return hidden_states.\n",
521
+ " The Surgery Module needs access to intermediate layer hidden states.\n",
522
+ " \"\"\"\n",
523
+ " original_forward = model.forward\n",
524
+ "\n",
525
+ " @functools.wraps(original_forward)\n",
526
+ " def patched_forward(\n",
527
+ " self,\n",
528
+ " input_ids=None,\n",
529
+ " attention_mask=None,\n",
530
+ " position_ids=None,\n",
531
+ " past_key_values=None,\n",
532
+ " inputs_embeds=None,\n",
533
+ " use_cache=None,\n",
534
+ " output_attentions=None,\n",
535
+ " output_hidden_states=None, # Will be forced True\n",
536
+ " return_dict=None,\n",
537
+ " cache_position=None,\n",
538
+ " **kwargs,\n",
539
+ " ):\n",
540
+ " return original_forward(\n",
541
+ " input_ids=input_ids,\n",
542
+ " attention_mask=attention_mask,\n",
543
+ " position_ids=position_ids,\n",
544
+ " past_key_values=past_key_values,\n",
545
+ " inputs_embeds=inputs_embeds,\n",
546
+ " use_cache=use_cache,\n",
547
+ " output_attentions=output_attentions,\n",
548
+ " output_hidden_states=True, # Always True for Surgery Module\n",
549
+ " return_dict=return_dict,\n",
550
+ " cache_position=cache_position,\n",
551
+ " **kwargs,\n",
552
+ " )\n",
553
+ "\n",
554
+ " model.forward = types.MethodType(patched_forward, model)\n",
555
+ " print(\" ✓ Base model forward patched (output_hidden_states=True)\")\n",
556
+ "\n",
557
+ "\n",
558
+ "print(\"✅ Config and base forward patch functions defined\")"
559
+ ]
560
+ },
561
+ {
562
+ "cell_type": "code",
563
+ "execution_count": null,
564
+ "metadata": {},
565
+ "outputs": [],
566
+ "source": [
567
+ "def _patch_inference_forward(model: VibeVoiceForConditionalGenerationInference):\n",
568
+ " \"\"\"\n",
569
+ " Patch the inference forward to:\n",
570
+ " 1. Force output_hidden_states=True\n",
571
+ " 2. Include hidden_states in the return value (needed by surgery module)\n",
572
+ " \"\"\"\n",
573
+ " original_forward = model.__class__.forward\n",
574
+ "\n",
575
+ " def patched_forward(\n",
576
+ " self,\n",
577
+ " input_ids=None,\n",
578
+ " attention_mask=None,\n",
579
+ " position_ids=None,\n",
580
+ " past_key_values=None,\n",
581
+ " inputs_embeds=None,\n",
582
+ " labels=None,\n",
583
+ " use_cache=None,\n",
584
+ " output_attentions=None,\n",
585
+ " output_hidden_states=None,\n",
586
+ " return_dict=None,\n",
587
+ " cache_position=None,\n",
588
+ " speech_tensors=None,\n",
589
+ " speech_masks=None,\n",
590
+ " speech_input_mask=None,\n",
591
+ " logits_to_keep=0,\n",
592
+ " **kwargs,\n",
593
+ " ):\n",
594
+ " return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n",
595
+ "\n",
596
+ " # Get embeddings\n",
597
+ " if inputs_embeds is None:\n",
598
+ " inputs_embeds = self.model.get_input_embeddings()(input_ids)\n",
599
+ "\n",
600
+ " # Process speech inputs\n",
601
+ " if speech_tensors is not None and speech_masks is not None:\n",
602
+ " acoustic_features, speech_embeds = self._process_speech_inputs(\n",
603
+ " speech_tensors.to(self.dtype), speech_masks\n",
604
+ " )\n",
605
+ " if speech_input_mask is not None:\n",
606
+ " inputs_embeds[speech_input_mask] = speech_embeds\n",
607
+ "\n",
608
+ " # Always output hidden states for Surgery Module\n",
609
+ " outputs = self.model(\n",
610
+ " inputs_embeds=inputs_embeds,\n",
611
+ " attention_mask=attention_mask,\n",
612
+ " position_ids=position_ids,\n",
613
+ " past_key_values=past_key_values,\n",
614
+ " use_cache=use_cache,\n",
615
+ " output_attentions=output_attentions,\n",
616
+ " output_hidden_states=True, # Always True!\n",
617
+ " return_dict=return_dict,\n",
618
+ " cache_position=cache_position,\n",
619
+ " **kwargs,\n",
620
+ " )\n",
621
+ "\n",
622
+ " hidden_states = outputs[0] if not return_dict else outputs.last_hidden_state\n",
623
+ " slice_indices = (\n",
624
+ " slice(-logits_to_keep, None)\n",
625
+ " if isinstance(logits_to_keep, int)\n",
626
+ " else logits_to_keep\n",
627
+ " )\n",
628
+ " logits = self.lm_head(hidden_states[:, slice_indices, :])\n",
629
+ "\n",
630
+ " if labels is not None:\n",
631
+ " raise NotImplementedError(\"Loss computation not implemented in surgery version.\")\n",
632
+ "\n",
633
+ " # KEY CHANGE: Include hidden_states in the output\n",
634
+ " return VibeVoiceCausalLMOutputWithPast(\n",
635
+ " logits=logits,\n",
636
+ " past_key_values=outputs.past_key_values,\n",
637
+ " last_hidden_state=hidden_states,\n",
638
+ " hidden_states=outputs.hidden_states, # ← All layer hidden states\n",
639
+ " attentions=outputs.attentions,\n",
640
+ " )\n",
641
+ "\n",
642
+ " model.forward = types.MethodType(patched_forward, model)\n",
643
+ " print(\" ✓ Inference forward patched (includes hidden_states)\")\n",
644
+ "\n",
645
+ "\n",
646
+ "print(\"✅ Inference forward patch function defined\")"
647
+ ]
648
+ },
649
+ {
650
+ "cell_type": "code",
651
+ "execution_count": null,
652
+ "metadata": {},
653
+ "outputs": [],
654
+ "source": [
655
+ "import copy\n",
656
+ "from tqdm import tqdm\n",
657
+ "from transformers.generation import GenerationConfig, LogitsProcessorList, StoppingCriteriaList\n",
658
+ "\n",
659
+ "\n",
660
+ "def _patch_generate_method(model: VibeVoiceForConditionalGenerationInference):\n",
661
+ " \"\"\"\n",
662
+ " Patch generate to use the Surgery Module for conditioning.\n",
663
+ " \n",
664
+ " Key changes vs. original generate:\n",
665
+ " 1. Forward calls use output_hidden_states=True\n",
666
+ " 2. Conditioning uses Surgery Module instead of last_hidden_state\n",
667
+ " 3. Device-aware surgery module calls for multi-GPU\n",
668
+ " \"\"\"\n",
669
+ "\n",
670
+ " def patched_generate(\n",
671
+ " self,\n",
672
+ " inputs=None,\n",
673
+ " generation_config=None,\n",
674
+ " logits_processor=None,\n",
675
+ " stopping_criteria=None,\n",
676
+ " prefix_allowed_tokens_fn=None,\n",
677
+ " synced_gpus=None,\n",
678
+ " assistant_model=None,\n",
679
+ " audio_streamer=None,\n",
680
+ " negative_prompt_ids=None,\n",
681
+ " negative_prompt_attention_mask=None,\n",
682
+ " speech_tensors=None,\n",
683
+ " speech_masks=None,\n",
684
+ " speech_input_mask=None,\n",
685
+ " return_speech=True,\n",
686
+ " cfg_scale=1.0,\n",
687
+ " stop_check_fn=None,\n",
688
+ " **kwargs,\n",
689
+ " ):\n",
690
+ " \"\"\"Modified generate that uses Surgery Module for conditioning.\"\"\"\n",
691
+ " # ── Setup ──\n",
692
+ " tokenizer = kwargs.pop(\"tokenizer\", None)\n",
693
+ " parsed_scripts = kwargs.pop(\"parsed_scripts\", None)\n",
694
+ " all_speakers_list = kwargs.pop(\"all_speakers_list\", None)\n",
695
+ " max_length_times = kwargs.pop(\"max_length_times\", 2)\n",
696
+ "\n",
697
+ " if kwargs.get(\"max_new_tokens\", None) is None:\n",
698
+ " kwargs[\"max_new_tokens\"] = (\n",
699
+ " self.config.decoder_config.max_position_embeddings\n",
700
+ " - kwargs[\"input_ids\"].shape[-1]\n",
701
+ " )\n",
702
+ "\n",
703
+ " (\n",
704
+ " generation_config, model_kwargs, input_ids,\n",
705
+ " logits_processor, stopping_criteria,\n",
706
+ " ) = self._build_generate_config_model_kwargs(\n",
707
+ " generation_config, inputs, tokenizer,\n",
708
+ " return_processors=True, **kwargs,\n",
709
+ " )\n",
710
+ "\n",
711
+ " negative_kwargs = {\n",
712
+ " \"input_ids\": torch.full(\n",
713
+ " (kwargs[\"input_ids\"].shape[0], 1),\n",
714
+ " tokenizer.speech_start_id,\n",
715
+ " dtype=torch.long, device=kwargs[\"input_ids\"].device,\n",
716
+ " ),\n",
717
+ " \"attention_mask\": torch.ones(\n",
718
+ " (kwargs[\"input_ids\"].shape[0], 1),\n",
719
+ " dtype=torch.long, device=kwargs[\"input_ids\"].device,\n",
720
+ " ),\n",
721
+ " \"max_new_tokens\": kwargs.get(\"max_new_tokens\", 100),\n",
722
+ " }\n",
723
+ " negative_generation_config, negative_model_kwargs, negative_input_ids = (\n",
724
+ " self._build_generate_config_model_kwargs(\n",
725
+ " None, None, tokenizer,\n",
726
+ " return_processors=False, **negative_kwargs,\n",
727
+ " )\n",
728
+ " )\n",
729
+ "\n",
730
+ " acoustic_cache = VibeVoiceTokenizerStreamingCache()\n",
731
+ " semantic_cache = VibeVoiceTokenizerStreamingCache()\n",
732
+ "\n",
733
+ " batch_size = input_ids.shape[0]\n",
734
+ " device = input_ids.device\n",
735
+ " finished_tags = torch.zeros(batch_size, dtype=torch.bool, device=device)\n",
736
+ " correct_cnt = torch.zeros(batch_size, dtype=torch.long, device=device)\n",
737
+ " is_prefill = True\n",
738
+ " inputs_embeds = None\n",
739
+ " verbose = kwargs.get(\"verbose\", False)\n",
740
+ "\n",
741
+ " audio_chunks = [[] for _ in range(batch_size)]\n",
742
+ "\n",
743
+ " initial_length = input_ids.shape[-1]\n",
744
+ " initial_length_per_sample = model_kwargs[\"attention_mask\"].sum(dim=-1)\n",
745
+ "\n",
746
+ " valid_tokens = [\n",
747
+ " generation_config.speech_start_id,\n",
748
+ " generation_config.speech_end_id,\n",
749
+ " generation_config.speech_diffusion_id,\n",
750
+ " generation_config.eos_token_id,\n",
751
+ " ]\n",
752
+ " if hasattr(generation_config, \"bos_token_id\") and generation_config.bos_token_id is not None:\n",
753
+ " valid_tokens.append(generation_config.bos_token_id)\n",
754
+ "\n",
755
+ " token_constraint_processor = VibeVoiceTokenConstraintProcessor(valid_tokens, device=device)\n",
756
+ " if logits_processor is None:\n",
757
+ " logits_processor = LogitsProcessorList()\n",
758
+ " logits_processor.append(token_constraint_processor)\n",
759
+ "\n",
760
+ " max_steps = min(\n",
761
+ " generation_config.max_length - initial_length,\n",
762
+ " int(max_length_times * initial_length),\n",
763
+ " )\n",
764
+ " max_step_per_sample = torch.minimum(\n",
765
+ " generation_config.max_length - initial_length_per_sample,\n",
766
+ " (max_length_times * initial_length_per_sample).long(),\n",
767
+ " )\n",
768
+ " reach_max_step_sample = torch.zeros(batch_size, dtype=torch.bool, device=device)\n",
769
+ "\n",
770
+ " progress_bar = (\n",
771
+ " tqdm(range(max_steps), desc=\"Generating\", leave=False)\n",
772
+ " if kwargs.get(\"show_progress_bar\", True)\n",
773
+ " else range(max_steps)\n",
774
+ " )\n",
775
+ "\n",
776
+ " # Device resolution for multi-GPU compatibility\n",
777
+ " acoustic_device = next(self.model.acoustic_tokenizer.parameters()).device\n",
778
+ " semantic_device = next(self.model.semantic_tokenizer.parameters()).device\n",
779
+ " acoustic_connect_device = next(self.model.acoustic_connector.parameters()).device\n",
780
+ " semantic_connect_device = next(self.model.semantic_connector.parameters()).device\n",
781
+ "\n",
782
+ " # Helper: run surgery module with correct device placement\n",
783
+ " def _run_surgery(hidden_states_tuple):\n",
784
+ " \"\"\"Run surgery module on last token only, handling multi-GPU placement.\"\"\"\n",
785
+ " surgery_mod = self.model.surgery_module\n",
786
+ " surgery_device = next(surgery_mod.parameters()).device\n",
787
+ " # Slice to last token only — avoids O(N²) on full sequence\n",
788
+ " selected = tuple(h[:, -1:, :] for h in hidden_states_tuple)\n",
789
+ " if selected[0].device != surgery_device:\n",
790
+ " selected = tuple(h.to(surgery_device) for h in selected)\n",
791
+ " return surgery_mod(selected)\n",
792
+ "\n",
793
+ " # ── Generation Loop ──\n",
794
+ " for step in progress_bar:\n",
795
+ " if stop_check_fn is not None and stop_check_fn():\n",
796
+ " if verbose:\n",
797
+ " print(f\"Generation stopped externally at step {step + 1}\")\n",
798
+ " if audio_streamer is not None:\n",
799
+ " audio_streamer.end()\n",
800
+ " break\n",
801
+ "\n",
802
+ " if audio_streamer is not None and hasattr(audio_streamer, \"finished_flags\"):\n",
803
+ " if any(audio_streamer.finished_flags):\n",
804
+ " if verbose:\n",
805
+ " print(f\"Audio generation stopped externally at step {step + 1}\")\n",
806
+ " break\n",
807
+ "\n",
808
+ " if finished_tags.all():\n",
809
+ " if hasattr(progress_bar, \"set_description\"):\n",
810
+ " progress_bar.set_description(\"Generation complete\")\n",
811
+ " break\n",
812
+ "\n",
813
+ " if input_ids.shape[-1] >= generation_config.max_length:\n",
814
+ " print(f\"Reached max generation length {generation_config.max_length}\")\n",
815
+ " reached = torch.arange(batch_size, device=device)[~finished_tags]\n",
816
+ " if reached.numel() > 0:\n",
817
+ " reach_max_step_sample[reached] = True\n",
818
+ " break\n",
819
+ "\n",
820
+ " if hasattr(progress_bar, \"set_description\"):\n",
821
+ " active = (~finished_tags).sum().item()\n",
822
+ " progress_bar.set_description(f\"Generating (active: {active}/{batch_size})\")\n",
823
+ "\n",
824
+ " model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)\n",
825
+ " if is_prefill:\n",
826
+ " prefill_inputs = {\n",
827
+ " \"speech_tensors\": speech_tensors.to(device=device),\n",
828
+ " \"speech_masks\": speech_masks.to(device),\n",
829
+ " \"speech_input_mask\": speech_input_mask.to(device),\n",
830
+ " }\n",
831
+ " is_prefill = False\n",
832
+ " else:\n",
833
+ " _ = model_inputs.pop(\"inputs_embeds\", None)\n",
834
+ " prefill_inputs = {\"inputs_embeds\": inputs_embeds}\n",
835
+ "\n",
836
+ " # Forward\n",
837
+ " outputs = self(\n",
838
+ " **model_inputs, **prefill_inputs,\n",
839
+ " logits_to_keep=1, return_dict=True,\n",
840
+ " output_attentions=False, output_hidden_states=True,\n",
841
+ " )\n",
842
+ " model_kwargs = self._update_model_kwargs_for_generation(\n",
843
+ " outputs, model_kwargs, is_encoder_decoder=False,\n",
844
+ " )\n",
845
+ "\n",
846
+ " next_token_logits = outputs.logits[:, -1, :].to(\n",
847
+ " copy=True, dtype=torch.float32, device=input_ids.device,\n",
848
+ " )\n",
849
+ " next_token_scores = logits_processor(input_ids, next_token_logits)\n",
850
+ "\n",
851
+ " if generation_config.do_sample:\n",
852
+ " probs = nn.functional.softmax(next_token_scores, dim=-1)\n",
853
+ " next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)\n",
854
+ " else:\n",
855
+ " next_tokens = torch.argmax(next_token_scores, dim=-1)\n",
856
+ "\n",
857
+ " next_tokens[finished_tags] = generation_config.eos_token_id\n",
858
+ " input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)\n",
859
+ "\n",
860
+ " # Negative prompt update (non-refresh mode)\n",
861
+ " if not kwargs.get(\"refresh_negative\", True):\n",
862
+ " negative_model_inputs = self.prepare_inputs_for_generation(\n",
863
+ " negative_input_ids, **negative_model_kwargs\n",
864
+ " )\n",
865
+ " if negative_model_inputs[\"inputs_embeds\"] is None and inputs_embeds is not None:\n",
866
+ " negative_model_inputs[\"inputs_embeds\"] = inputs_embeds\n",
867
+ " negative_model_inputs[\"input_ids\"] = None\n",
868
+ "\n",
869
+ " negative_outputs = self(\n",
870
+ " **negative_model_inputs,\n",
871
+ " logits_to_keep=0, return_dict=True,\n",
872
+ " output_attentions=False, output_hidden_states=True,\n",
873
+ " )\n",
874
+ " negative_model_kwargs = self._update_model_kwargs_for_generation(\n",
875
+ " negative_outputs, negative_model_kwargs, is_encoder_decoder=False,\n",
876
+ " )\n",
877
+ " negative_input_ids = torch.cat(\n",
878
+ " [negative_input_ids, next_tokens[:, None]], dim=-1\n",
879
+ " )\n",
880
+ "\n",
881
+ " # EOS handling\n",
882
+ " if (next_tokens == generation_config.eos_token_id).any():\n",
883
+ " eos_indices = (\n",
884
+ " (next_tokens == generation_config.eos_token_id)\n",
885
+ " .nonzero(as_tuple=False).squeeze(1)\n",
886
+ " )\n",
887
+ " new_eos = eos_indices[~finished_tags[eos_indices]]\n",
888
+ " if new_eos.numel() > 0:\n",
889
+ " finished_tags[new_eos] = True\n",
890
+ " if verbose:\n",
891
+ " print(f\"Samples {new_eos.tolist()} reached EOS at step {step+1}.\", flush=True)\n",
892
+ " if audio_streamer is not None:\n",
893
+ " audio_streamer.end(new_eos)\n",
894
+ "\n",
895
+ " # Max length handling\n",
896
+ " max_reached = step >= max_step_per_sample\n",
897
+ " new_max = torch.nonzero(max_reached & ~finished_tags, as_tuple=False).squeeze(1)\n",
898
+ " if new_max.numel() > 0:\n",
899
+ " finished_tags[new_max] = True\n",
900
+ " reach_max_step_sample[new_max] = True\n",
901
+ " if verbose:\n",
902
+ " print(f\"Samples {new_max.tolist()} reached max length at step {step+1}.\", flush=True)\n",
903
+ " if audio_streamer is not None:\n",
904
+ " audio_streamer.end(new_max)\n",
905
+ "\n",
906
+ " # speech_end\n",
907
+ " diffusion_end = (\n",
908
+ " (next_tokens == generation_config.speech_end_id)\n",
909
+ " .nonzero(as_tuple=False).squeeze(1)\n",
910
+ " )\n",
911
+ " if diffusion_end.numel() > 0:\n",
912
+ " acoustic_cache.set_to_zero(diffusion_end)\n",
913
+ " semantic_cache.set_to_zero(diffusion_end)\n",
914
+ "\n",
915
+ " # speech_begin — update negative prompt cache\n",
916
+ " diffusion_start = torch.arange(batch_size, device=device)[\n",
917
+ " ~finished_tags & (next_tokens == generation_config.speech_start_id)\n",
918
+ " ]\n",
919
+ " if diffusion_start.numel() > 0 and kwargs.get(\"refresh_negative\", True):\n",
920
+ " for idx in diffusion_start.tolist():\n",
921
+ " negative_model_kwargs[\"attention_mask\"][idx, :] = 0\n",
922
+ " negative_model_kwargs[\"attention_mask\"][idx, -1] = 1\n",
923
+ " for k_cache, v_cache in zip(\n",
924
+ " negative_model_kwargs[\"past_key_values\"].key_cache,\n",
925
+ " negative_model_kwargs[\"past_key_values\"].value_cache,\n",
926
+ " ):\n",
927
+ " for idx in diffusion_start.tolist():\n",
928
+ " k_cache[idx, :, -1, :] = k_cache[idx, :, 0, :].clone()\n",
929
+ " v_cache[idx, :, -1, :] = v_cache[idx, :, 0, :].clone()\n",
930
+ " for idx in diffusion_start.tolist():\n",
931
+ " negative_input_ids[idx, -1] = generation_config.speech_start_id\n",
932
+ "\n",
933
+ " # Prepare next embeddings\n",
934
+ " next_inputs_embeds = self.model.get_input_embeddings()(next_tokens).unsqueeze(1)\n",
935
+ "\n",
936
+ " # ── Diffusion forward ──\n",
937
+ " diffusion_indices = torch.arange(batch_size, device=device)[\n",
938
+ " ~finished_tags & (next_tokens == generation_config.speech_diffusion_id)\n",
939
+ " ]\n",
940
+ "\n",
941
+ " if diffusion_indices.numel() > 0:\n",
942
+ " # Negative pass for diffusion\n",
943
+ " if kwargs.get(\"refresh_negative\", True):\n",
944
+ " negative_model_inputs = self.prepare_inputs_for_generation(\n",
945
+ " negative_input_ids, **negative_model_kwargs\n",
946
+ " )\n",
947
+ " if negative_model_inputs[\"inputs_embeds\"] is None and inputs_embeds is not None:\n",
948
+ " negative_model_inputs[\"inputs_embeds\"] = inputs_embeds\n",
949
+ " negative_model_inputs[\"input_ids\"] = None\n",
950
+ "\n",
951
+ " negative_outputs = self(\n",
952
+ " **negative_model_inputs,\n",
953
+ " logits_to_keep=0, return_dict=True,\n",
954
+ " output_attentions=False, output_hidden_states=True,\n",
955
+ " )\n",
956
+ " negative_model_kwargs = self._update_model_kwargs_for_generation(\n",
957
+ " negative_outputs, negative_model_kwargs, is_encoder_decoder=False,\n",
958
+ " )\n",
959
+ " negative_input_ids = torch.cat(\n",
960
+ " [negative_input_ids, next_tokens[:, None]], dim=-1\n",
961
+ " )\n",
962
+ "\n",
963
+ " # Correct non-diffusion samples' KV cache\n",
964
+ " non_diff_mask = ~finished_tags & (next_tokens != generation_config.speech_diffusion_id)\n",
965
+ " if non_diff_mask.any():\n",
966
+ " non_diff_idx = torch.arange(batch_size, device=device)[non_diff_mask]\n",
967
+ " starts = correct_cnt[non_diff_idx]\n",
968
+ "\n",
969
+ " seq_len = negative_model_kwargs[\"attention_mask\"].shape[1]\n",
970
+ " for i, (s_idx, s_start) in enumerate(\n",
971
+ " zip(non_diff_idx.tolist(), starts.tolist())\n",
972
+ " ):\n",
973
+ " if s_start + 1 < seq_len - 1:\n",
974
+ " negative_model_kwargs[\"attention_mask\"][s_idx, s_start+1:] = \\\n",
975
+ " negative_model_kwargs[\"attention_mask\"][s_idx, s_start:-1].clone()\n",
976
+ " negative_model_kwargs[\"attention_mask\"][s_idx, s_start] = 0\n",
977
+ "\n",
978
+ " for k_cache, v_cache in zip(\n",
979
+ " negative_model_kwargs[\"past_key_values\"].key_cache,\n",
980
+ " negative_model_kwargs[\"past_key_values\"].value_cache,\n",
981
+ " ):\n",
982
+ " for s_idx, s_start in zip(non_diff_idx.tolist(), starts.tolist()):\n",
983
+ " if s_start + 1 < k_cache.shape[2] - 1:\n",
984
+ " k_cache[s_idx, :, s_start+1:, :] = \\\n",
985
+ " k_cache[s_idx, :, s_start:-1, :].clone()\n",
986
+ " v_cache[s_idx, :, s_start+1:, :] = \\\n",
987
+ " v_cache[s_idx, :, s_start:-1, :].clone()\n",
988
+ "\n",
989
+ " for s_idx, s_start in zip(non_diff_idx.tolist(), starts.tolist()):\n",
990
+ " if s_start + 1 < negative_input_ids.shape[1] - 1:\n",
991
+ " negative_input_ids[s_idx, s_start+1:] = \\\n",
992
+ " negative_input_ids[s_idx, s_start:-1].clone()\n",
993
+ "\n",
994
+ " correct_cnt[non_diff_idx] += 1\n",
995
+ "\n",
996
+ " # ── SURGERY: Use Surgery Module for conditioning ──\n",
997
+ " surgery_out = _run_surgery(outputs.hidden_states) # [B, 1, 3584]\n",
998
+ " positive_condition = surgery_out[:, -1, :][diffusion_indices]\n",
999
+ "\n",
1000
+ " neg_surgery_out = _run_surgery(negative_outputs.hidden_states)\n",
1001
+ " negative_condition = neg_surgery_out[:, -1, :][diffusion_indices]\n",
1002
+ "\n",
1003
+ " speech_latent = self.sample_speech_tokens(\n",
1004
+ " positive_condition,\n",
1005
+ " negative_condition,\n",
1006
+ " cfg_scale=cfg_scale,\n",
1007
+ " ).unsqueeze(1)\n",
1008
+ "\n",
1009
+ " # Decode acoustic latent to audio\n",
1010
+ " scaled_latent = (\n",
1011
+ " speech_latent\n",
1012
+ " / self.model.speech_scaling_factor.to(speech_latent.device)\n",
1013
+ " - self.model.speech_bias_factor.to(speech_latent.device)\n",
1014
+ " )\n",
1015
+ " audio_chunk = self.model.acoustic_tokenizer.decode(\n",
1016
+ " scaled_latent.to(self.model.acoustic_tokenizer.device),\n",
1017
+ " cache=acoustic_cache,\n",
1018
+ " sample_indices=diffusion_indices.to(self.model.acoustic_tokenizer.device),\n",
1019
+ " use_cache=True,\n",
1020
+ " debug=False,\n",
1021
+ " )\n",
1022
+ "\n",
1023
+ " for i, s_idx in enumerate(diffusion_indices):\n",
1024
+ " idx = s_idx.item()\n",
1025
+ " if not finished_tags[idx]:\n",
1026
+ " audio_chunks[idx].append(audio_chunk[i])\n",
1027
+ "\n",
1028
+ " if audio_streamer is not None:\n",
1029
+ " audio_streamer.put(audio_chunk, diffusion_indices)\n",
1030
+ "\n",
1031
+ " semantic_features = self.model.semantic_tokenizer.encode(\n",
1032
+ " audio_chunk,\n",
1033
+ " cache=semantic_cache,\n",
1034
+ " sample_indices=diffusion_indices,\n",
1035
+ " use_cache=True,\n",
1036
+ " debug=False,\n",
1037
+ " ).mean\n",
1038
+ "\n",
1039
+ " acoustic_embed = self.model.acoustic_connector(\n",
1040
+ " speech_latent.to(acoustic_connect_device)\n",
1041
+ " ).to(device)\n",
1042
+ " semantic_embed = self.model.semantic_connector(\n",
1043
+ " semantic_features.to(semantic_connect_device)\n",
1044
+ " ).to(device)\n",
1045
+ " diffusion_embeds = acoustic_embed + semantic_embed\n",
1046
+ "\n",
1047
+ " next_inputs_embeds[diffusion_indices] = diffusion_embeds\n",
1048
+ "\n",
1049
+ " inputs_embeds = next_inputs_embeds\n",
1050
+ "\n",
1051
+ " if audio_streamer is not None:\n",
1052
+ " audio_streamer.end()\n",
1053
+ "\n",
1054
+ " # Concatenate audio chunks\n",
1055
+ " final_audio_outputs = []\n",
1056
+ " for sample_chunks in audio_chunks:\n",
1057
+ " if sample_chunks:\n",
1058
+ " final_audio_outputs.append(torch.cat(sample_chunks, dim=-1))\n",
1059
+ " else:\n",
1060
+ " final_audio_outputs.append(None)\n",
1061
+ "\n",
1062
+ " return VibeVoiceGenerationOutput(\n",
1063
+ " sequences=input_ids,\n",
1064
+ " speech_outputs=final_audio_outputs if return_speech else None,\n",
1065
+ " reach_max_step_sample=reach_max_step_sample,\n",
1066
+ " )\n",
1067
+ "\n",
1068
+ " model.generate = types.MethodType(patched_generate, model)\n",
1069
+ " print(\" ✓ Generate method patched (Surgery Module integrated)\")\n",
1070
+ "\n",
1071
+ "\n",
1072
+ "print(\"✅ Generate patch function defined\")"
1073
+ ]
1074
+ },
1075
+ {
1076
+ "cell_type": "markdown",
1077
+ "metadata": {},
1078
+ "source": [
1079
+ "---\n",
1080
+ "## 7. Main Surgery Function\n",
1081
+ "\n",
1082
+ "The `perform_surgery()` function executes the complete model surgery on CPU:\n",
1083
+ "1. Replace Qwen2.5-7B language model with Qwen3-4B\n",
1084
+ "2. Replace acoustic & semantic connectors for new hidden size\n",
1085
+ "3. Replace lm_head for new vocab size\n",
1086
+ "4. Add Surgery Module\n",
1087
+ "5. Patch forward methods\n",
1088
+ "6. Update config"
1089
+ ]
1090
+ },
1091
+ {
1092
+ "cell_type": "code",
1093
+ "execution_count": null,
1094
+ "metadata": {},
1095
+ "outputs": [],
1096
+ "source": [
1097
+ "def perform_surgery(\n",
1098
+ " vibevoice_model: VibeVoiceForConditionalGenerationInference,\n",
1099
+ " qwen3_model,\n",
1100
+ " surgery_layer_indices: Optional[List[int]] = None,\n",
1101
+ " dtype: torch.dtype = DTYPE,\n",
1102
+ ") -> VibeVoiceForConditionalGenerationInference:\n",
1103
+ " \"\"\"\n",
1104
+ " Perform the complete model surgery on CPU:\n",
1105
+ " 1. Replace Qwen2.5-7B language model with Qwen3-4B\n",
1106
+ " 2. Replace acoustic & semantic connectors for new hidden size\n",
1107
+ " 3. Replace lm_head for new vocab size\n",
1108
+ " 4. Add Surgery Module\n",
1109
+ " 5. Patch forward methods\n",
1110
+ " 6. Update config\n",
1111
+ " \"\"\"\n",
1112
+ " if surgery_layer_indices is None:\n",
1113
+ " surgery_layer_indices = SURGERY_LAYER_INDICES\n",
1114
+ "\n",
1115
+ " print(\"\\n\" + \"=\" * 64)\n",
1116
+ " print(\" PERFORMING MODEL SURGERY (on CPU)\")\n",
1117
+ " print(\"=\" * 64)\n",
1118
+ "\n",
1119
+ " # ── Step 1: Replace Language Model ──\n",
1120
+ " print(\"\\n[1/6] Replacing language model: Qwen2.5-7B → Qwen3-4B...\")\n",
1121
+ " qwen3_base = qwen3_model.model # Qwen3Model (without lm_head)\n",
1122
+ "\n",
1123
+ " old_lm = vibevoice_model.model.language_model\n",
1124
+ " del old_lm\n",
1125
+ " vibevoice_model.model.language_model = qwen3_base\n",
1126
+ " print(f\" ✓ Language model replaced ({QWEN3_HIDDEN_SIZE}-dim, {QWEN3_NUM_LAYERS} layers)\")\n",
1127
+ "\n",
1128
+ " # ── Step 2: Replace Acoustic Connector ──\n",
1129
+ " print(\"\\n[2/6] Replacing acoustic connector...\")\n",
1130
+ " old_acoustic = vibevoice_model.model.acoustic_connector\n",
1131
+ " del old_acoustic\n",
1132
+ " vibevoice_model.model.acoustic_connector = SpeechConnector(\n",
1133
+ " input_dim=vibevoice_model.config.acoustic_vae_dim, # 64\n",
1134
+ " output_dim=QWEN3_HIDDEN_SIZE, # 2560\n",
1135
+ " ).to(dtype=dtype)\n",
1136
+ " print(f\" ✓ Acoustic connector: 64 → {QWEN3_HIDDEN_SIZE}\")\n",
1137
+ "\n",
1138
+ " # ── Step 3: Replace Semantic Connector ──\n",
1139
+ " print(\"\\n[3/6] Replacing semantic connector...\")\n",
1140
+ " old_semantic = vibevoice_model.model.semantic_connector\n",
1141
+ " del old_semantic\n",
1142
+ " vibevoice_model.model.semantic_connector = SpeechConnector(\n",
1143
+ " input_dim=vibevoice_model.config.semantic_vae_dim, # 128\n",
1144
+ " output_dim=QWEN3_HIDDEN_SIZE, # 2560\n",
1145
+ " ).to(dtype=dtype)\n",
1146
+ " print(f\" ✓ Semantic connector: 128 → {QWEN3_HIDDEN_SIZE}\")\n",
1147
+ "\n",
1148
+ " # ── Step 4: Replace LM Head ──\n",
1149
+ " print(\"\\n[4/6] Replacing LM head...\")\n",
1150
+ " old_head = vibevoice_model.lm_head\n",
1151
+ " del old_head\n",
1152
+ " vibevoice_model.lm_head = nn.Linear(\n",
1153
+ " QWEN3_HIDDEN_SIZE, QWEN3_VOCAB_SIZE, bias=False\n",
1154
+ " ).to(dtype=dtype)\n",
1155
+ "\n",
1156
+ " # Tie weights (Qwen3 uses tie_word_embeddings=True)\n",
1157
+ " if hasattr(vibevoice_model.model.language_model, \"embed_tokens\"):\n",
1158
+ " vibevoice_model.lm_head.weight = vibevoice_model.model.language_model.embed_tokens.weight\n",
1159
+ " print(\" ✓ LM head weights tied to embed_tokens\")\n",
1160
+ " print(f\" ✓ LM head: {QWEN3_HIDDEN_SIZE} → {QWEN3_VOCAB_SIZE}\")\n",
1161
+ "\n",
1162
+ " # ── Step 5: Add Surgery Module ──\n",
1163
+ " print(\"\\n[5/6] Adding Surgery Module...\")\n",
1164
+ " surgery_module = Qwen3SurgeryModule(\n",
1165
+ " input_dim=QWEN3_HIDDEN_SIZE,\n",
1166
+ " output_dim=DIFFUSION_HIDDEN_SIZE,\n",
1167
+ " layer_indices=surgery_layer_indices,\n",
1168
+ " rms_norm_eps=1e-6,\n",
1169
+ " ).to(dtype=dtype)\n",
1170
+ " vibevoice_model.model.surgery_module = surgery_module\n",
1171
+ "\n",
1172
+ " surgery_params = sum(p.numel() for p in surgery_module.parameters())\n",
1173
+ " print(f\" ✓ Surgery Module: {surgery_params:,} parameters\")\n",
1174
+ " print(f\" ✓ Pipeline: layers{surgery_layer_indices} → WeightedSum → \"\n",
1175
+ " f\"RMSNorm → SwiGLU → Linear({QWEN3_HIDDEN_SIZE}→{DIFFUSION_HIDDEN_SIZE})\")\n",
1176
+ "\n",
1177
+ " # ── Step 6: Patch Forward Methods ──\n",
1178
+ " print(\"\\n[6/6] Patching forward & generate methods...\")\n",
1179
+ " _patch_base_model_forward(vibevoice_model.model)\n",
1180
+ " _patch_inference_forward(vibevoice_model)\n",
1181
+ " _patch_generate_method(vibevoice_model)\n",
1182
+ "\n",
1183
+ " # ── Update Config ──\n",
1184
+ " print(\"\\n[Extra] Updating model config...\")\n",
1185
+ " _update_config_for_qwen3(vibevoice_model)\n",
1186
+ "\n",
1187
+ " # ── Verify Diffusion Head untouched ──\n",
1188
+ " print(\"\\n[Verify] Diffusion Head (should be unchanged):\")\n",
1189
+ " dh = vibevoice_model.model.prediction_head\n",
1190
+ " print(f\" cond_proj: {dh.cond_proj.weight.shape}\")\n",
1191
+ " print(f\" noisy_images_proj: {dh.noisy_images_proj.weight.shape}\")\n",
1192
+ " print(f\" hidden_size: {dh.config.hidden_size}\")\n",
1193
+ "\n",
1194
+ " print(\"\\n\" + \"=\" * 64)\n",
1195
+ " print(\" SURGERY COMPLETE!\")\n",
1196
+ " print(\"=\" * 64)\n",
1197
+ "\n",
1198
+ " return vibevoice_model\n",
1199
+ "\n",
1200
+ "\n",
1201
+ "print(\"✅ Main surgery function defined\")"
1202
+ ]
1203
+ },
1204
+ {
1205
+ "cell_type": "markdown",
1206
+ "metadata": {},
1207
+ "source": [
1208
+ "---\n",
1209
+ "## 8. Custom Model Class for Save/Load\n",
1210
+ "\n",
1211
+ "Extended VibeVoice inference model that includes the Surgery Module in its `__init__`,\n",
1212
+ "so `from_pretrained` can load surgery weights correctly."
1213
+ ]
1214
+ },
1215
+ {
1216
+ "cell_type": "code",
1217
+ "execution_count": null,
1218
+ "metadata": {},
1219
+ "outputs": [],
1220
+ "source": [
1221
+ "import gc\n",
1222
+ "import json\n",
1223
+ "\n",
1224
+ "\n",
1225
+ "class VibeVoiceSurgeryModel(VibeVoiceForConditionalGenerationInference):\n",
1226
+ " \"\"\"\n",
1227
+ " Extended VibeVoice inference model that includes the Surgery Module\n",
1228
+ " in its __init__, so from_pretrained can load surgery weights correctly.\n",
1229
+ " \"\"\"\n",
1230
+ " \n",
1231
+ " def __init__(self, config):\n",
1232
+ " super().__init__(config)\n",
1233
+ " # Add surgery module if config includes it\n",
1234
+ " if hasattr(config, \"surgery_module_config\"):\n",
1235
+ " sc = config.surgery_module_config\n",
1236
+ " self.model.surgery_module = Qwen3SurgeryModule(\n",
1237
+ " input_dim=sc.get(\"input_dim\", QWEN3_HIDDEN_SIZE),\n",
1238
+ " output_dim=sc.get(\"output_dim\", DIFFUSION_HIDDEN_SIZE),\n",
1239
+ " layer_indices=sc.get(\"layer_indices\", SURGERY_LAYER_INDICES),\n",
1240
+ " rms_norm_eps=sc.get(\"rms_norm_eps\", 1e-6),\n",
1241
+ " )\n",
1242
+ "\n",
1243
+ "\n",
1244
+ "# Register with AutoModel so from_pretrained works\n",
1245
+ "AutoModelForCausalLM.register(VibeVoiceConfig, VibeVoiceSurgeryModel)\n",
1246
+ "\n",
1247
+ "print(\"✅ VibeVoiceSurgeryModel class defined and registered\")"
1248
+ ]
1249
+ },
1250
+ {
1251
+ "cell_type": "markdown",
1252
+ "metadata": {},
1253
+ "source": [
1254
+ "---\n",
1255
+ "## 9. Save & Load Functions"
1256
+ ]
1257
+ },
1258
+ {
1259
+ "cell_type": "code",
1260
+ "execution_count": null,
1261
+ "metadata": {},
1262
+ "outputs": [],
1263
+ "source": [
1264
+ "def save_surgery_model(model, output_dir: str):\n",
1265
+ " \"\"\"\n",
1266
+ " Save the surgery model in a format that can be reloaded correctly.\n",
1267
+ " \n",
1268
+ " Key: We save decoder_config with model_type=\"qwen3\" and Qwen3 parameters.\n",
1269
+ " The monkey-patched VibeVoiceConfig handles qwen3 on reload.\n",
1270
+ " \"\"\"\n",
1271
+ " os.makedirs(output_dir, exist_ok=True)\n",
1272
+ " print(f\" Saving model weights...\")\n",
1273
+ " model.save_pretrained(output_dir, safe_serialization=True)\n",
1274
+ " print(f\" ✓ Model weights saved\")\n",
1275
+ "\n",
1276
+ " # Save config with surgery_module_config\n",
1277
+ " print(f\" Saving config...\")\n",
1278
+ " config_dict = model.config.to_dict()\n",
1279
+ " \n",
1280
+ " # Save decoder config as qwen3\n",
1281
+ " qwen3_cfg = create_qwen3_config_for_surgery()\n",
1282
+ " config_dict[\"decoder_config\"] = qwen3_cfg.to_dict()\n",
1283
+ " config_dict[\"decoder_config\"][\"model_type\"] = \"qwen3\"\n",
1284
+ "\n",
1285
+ " # Add surgery module config\n",
1286
+ " config_dict[\"surgery_module_config\"] = {\n",
1287
+ " \"input_dim\": QWEN3_HIDDEN_SIZE,\n",
1288
+ " \"output_dim\": DIFFUSION_HIDDEN_SIZE,\n",
1289
+ " \"layer_indices\": SURGERY_LAYER_INDICES,\n",
1290
+ " \"rms_norm_eps\": 1e-6,\n",
1291
+ " }\n",
1292
+ "\n",
1293
+ " config_path = os.path.join(output_dir, \"config.json\")\n",
1294
+ " with open(config_path, \"w\") as f:\n",
1295
+ " json.dump(config_dict, f, indent=2, default=str)\n",
1296
+ " print(f\" ✓ Config saved\")\n",
1297
+ "\n",
1298
+ " # Save surgery config separately\n",
1299
+ " surgery_config_path = os.path.join(output_dir, \"surgery_module_config.json\")\n",
1300
+ " with open(surgery_config_path, \"w\") as f:\n",
1301
+ " json.dump(config_dict[\"surgery_module_config\"], f, indent=2)\n",
1302
+ " print(f\" ✓ Surgery module config saved\")\n",
1303
+ "\n",
1304
+ " # Print file sizes\n",
1305
+ " print(f\"\\n Saved files:\")\n",
1306
+ " total_size = 0\n",
1307
+ " for f_name in sorted(os.listdir(output_dir)):\n",
1308
+ " f_path = os.path.join(output_dir, f_name)\n",
1309
+ " if os.path.isfile(f_path):\n",
1310
+ " size_mb = os.path.getsize(f_path) / 1e6\n",
1311
+ " total_size += size_mb\n",
1312
+ " print(f\" {f_name}: {size_mb:.1f} MB\")\n",
1313
+ " print(f\" Total: {total_size:.1f} MB ({total_size/1024:.2f} GB)\")\n",
1314
+ " print(f\" ✓ Saved to {output_dir}\")\n",
1315
+ "\n",
1316
+ "\n",
1317
+ "def load_surgery_model(\n",
1318
+ " model_path: str,\n",
1319
+ " dtype: torch.dtype = DTYPE,\n",
1320
+ " device_map: str = \"auto\",\n",
1321
+ "):\n",
1322
+ " \"\"\"\n",
1323
+ " Load a previously saved surgery model.\n",
1324
+ " \n",
1325
+ " Uses VibeVoiceSurgeryModel (custom class) so that from_pretrained\n",
1326
+ " creates the surgery_module before loading weights.\n",
1327
+ " \n",
1328
+ " Also applies the runtime forward/generate patches.\n",
1329
+ " \n",
1330
+ " Fix: When device_map=\"auto\", the auto-generated device map misses\n",
1331
+ " registered buffers (speech_scaling_factor, speech_bias_factor) that\n",
1332
+ " live directly on VibeVoiceModel. We manually add those entries.\n",
1333
+ " \"\"\"\n",
1334
+ " print(f\"\\n Loading surgery model from {model_path}...\")\n",
1335
+ " \n",
1336
+ " # Ensure config patch is applied\n",
1337
+ " _patch_vibevoice_config_for_qwen3()\n",
1338
+ "\n",
1339
+ " # Load config to get surgery_module_config\n",
1340
+ " config_path = os.path.join(model_path, \"config.json\")\n",
1341
+ " with open(config_path, \"r\") as f:\n",
1342
+ " config_dict = json.load(f)\n",
1343
+ "\n",
1344
+ " # Create config using our patched VibeVoiceConfig\n",
1345
+ " config = VibeVoiceConfig(**config_dict)\n",
1346
+ "\n",
1347
+ " # ── Fix device_map for registered buffers ──\n",
1348
+ " if device_map == \"auto\":\n",
1349
+ " from accelerate import infer_auto_device_map, get_max_memory\n",
1350
+ "\n",
1351
+ " print(\" Computing device map for multi-GPU placement...\")\n",
1352
+ " max_memory = get_max_memory()\n",
1353
+ "\n",
1354
+ " # Build a meta-device model to infer the device map structure\n",
1355
+ " with torch.device(\"meta\"):\n",
1356
+ " meta_model = VibeVoiceSurgeryModel(config)\n",
1357
+ "\n",
1358
+ " no_split = [\n",
1359
+ " \"VibeVoiceDiffusionHead\",\n",
1360
+ " \"VibeVoiceAcousticTokenizerModel\",\n",
1361
+ " \"VibeVoiceSemanticTokenizerModel\",\n",
1362
+ " \"Qwen3SurgeryModule\",\n",
1363
+ " ]\n",
1364
+ "\n",
1365
+ " device_map_dict = infer_auto_device_map(\n",
1366
+ " meta_model,\n",
1367
+ " max_memory=max_memory,\n",
1368
+ " no_split_module_classes=no_split,\n",
1369
+ " )\n",
1370
+ "\n",
1371
+ " # Determine which device to place the buffers on\n",
1372
+ " buffer_device = device_map_dict.get(\n",
1373
+ " \"model.language_model\",\n",
1374
+ " device_map_dict.get(\"model\", \"cuda:0\"),\n",
1375
+ " )\n",
1376
+ "\n",
1377
+ " # Add entries for registered buffers that are direct children of model\n",
1378
+ " for key in [\"model.speech_scaling_factor\", \"model.speech_bias_factor\"]:\n",
1379
+ " if key not in device_map_dict:\n",
1380
+ " device_map_dict[key] = buffer_device\n",
1381
+ " print(f\" Added device map entry: {key} → {buffer_device}\")\n",
1382
+ "\n",
1383
+ " del meta_model\n",
1384
+ " gc.collect()\n",
1385
+ " torch.cuda.empty_cache()\n",
1386
+ "\n",
1387
+ " device_map = device_map_dict\n",
1388
+ "\n",
1389
+ " # Load using our custom class that includes surgery_module in __init__\n",
1390
+ " model = VibeVoiceSurgeryModel.from_pretrained(\n",
1391
+ " model_path,\n",
1392
+ " config=config,\n",
1393
+ " torch_dtype=dtype,\n",
1394
+ " device_map=device_map,\n",
1395
+ " trust_remote_code=True,\n",
1396
+ " )\n",
1397
+ "\n",
1398
+ " # Verify surgery module\n",
1399
+ " if not hasattr(model.model, \"surgery_module\"):\n",
1400
+ " print(\" ⚠ Surgery Module not found after loading, adding manually...\")\n",
1401
+ " sc = config.surgery_module_config\n",
1402
+ " model.model.surgery_module = Qwen3SurgeryModule(**sc).to(dtype=dtype)\n",
1403
+ " # Try to load surgery weights\n",
1404
+ " from safetensors.torch import load_file as safetensors_load\n",
1405
+ " safetensors_path = os.path.join(model_path, \"model.safetensors\")\n",
1406
+ " bin_path = os.path.join(model_path, \"pytorch_model.bin\")\n",
1407
+ " weights_path = safetensors_path if os.path.exists(safetensors_path) else bin_path\n",
1408
+ " if os.path.exists(weights_path):\n",
1409
+ " if weights_path.endswith(\".safetensors\"):\n",
1410
+ " all_weights = safetensors_load(weights_path)\n",
1411
+ " else:\n",
1412
+ " all_weights = torch.load(weights_path, map_location=\"cpu\")\n",
1413
+ " surgery_state = {\n",
1414
+ " k.replace(\"model.surgery_module.\", \"\"): v\n",
1415
+ " for k, v in all_weights.items()\n",
1416
+ " if k.startswith(\"model.surgery_module.\")\n",
1417
+ " }\n",
1418
+ " if surgery_state:\n",
1419
+ " model.model.surgery_module.load_state_dict(surgery_state, strict=False)\n",
1420
+ " print(\" ✓ Surgery Module weights loaded\")\n",
1421
+ "\n",
1422
+ " # Apply runtime patches (not saved with the model)\n",
1423
+ " _patch_base_model_forward(model.model)\n",
1424
+ " _patch_inference_forward(model)\n",
1425
+ " _patch_generate_method(model)\n",
1426
+ "\n",
1427
+ " # Tie weights\n",
1428
+ " try:\n",
1429
+ " model.tie_weights()\n",
1430
+ " except Exception:\n",
1431
+ " pass\n",
1432
+ "\n",
1433
+ " print(f\" ✓ Surgery model loaded successfully\")\n",
1434
+ " return model\n",
1435
+ "\n",
1436
+ "\n",
1437
+ "print(\"✅ Save/Load functions defined\")"
1438
+ ]
1439
+ },
1440
+ {
1441
+ "cell_type": "markdown",
1442
+ "metadata": {},
1443
+ "source": [
1444
+ "---\n",
1445
+ "## 10. Memory Estimation"
1446
+ ]
1447
+ },
1448
+ {
1449
+ "cell_type": "code",
1450
+ "execution_count": null,
1451
+ "metadata": {},
1452
+ "outputs": [],
1453
+ "source": [
1454
+ "def estimate_memory():\n",
1455
+ " \"\"\"Print memory estimates for the surgery process.\"\"\"\n",
1456
+ " qwen3_gb = QWEN3_NUM_LAYERS * 0.22 # rough estimate ~8GB\n",
1457
+ " vibevoice_total_gb = 14.0 # ~7B params in fp16\n",
1458
+ " vibevoice_excl_lm_gb = 3.0 # diffusion head + tokenizers + connectors\n",
1459
+ " surgery_gb = 0.05 # ~25M params\n",
1460
+ " \n",
1461
+ " final_model_gb = qwen3_gb + vibevoice_excl_lm_gb + surgery_gb\n",
1462
+ " during_surgery_gb = vibevoice_total_gb + qwen3_gb\n",
1463
+ " \n",
1464
+ " print(f\"\\n📊 Memory Estimates (float16):\")\n",
1465
+ " print(f\" VibeVoice 7B (CPU RAM): ~{vibevoice_total_gb:.1f} GB\")\n",
1466
+ " print(f\" Qwen3-4B (CPU RAM): ~{qwen3_gb:.1f} GB\")\n",
1467
+ " print(f\" During surgery (CPU RAM): ~{during_surgery_gb:.1f} GB\")\n",
1468
+ " print(f\" Final model (VRAM): ~{final_model_gb:.1f} GB\")\n",
1469
+ " print(f\" Colab CPU RAM available: ~12-25 GB\")\n",
1470
+ " print(f\" Colab GPU VRAM (T4): 15 GB\")\n",
1471
+ " print(f\" ℹ ️ If RAM is tight, load models sequentially (delete before loading next)\")\n",
1472
+ "\n",
1473
+ "\n",
1474
+ "estimate_memory()"
1475
+ ]
1476
+ },
1477
+ {
1478
+ "cell_type": "markdown",
1479
+ "metadata": {},
1480
+ "source": [
1481
+ "---\n",
1482
+ "## 11. Verification Tests"
1483
+ ]
1484
+ },
1485
+ {
1486
+ "cell_type": "code",
1487
+ "execution_count": null,
1488
+ "metadata": {},
1489
+ "outputs": [],
1490
+ "source": [
1491
+ "def verify_surgery(model):\n",
1492
+ " \"\"\"Run verification tests on the modified model.\"\"\"\n",
1493
+ " print(\"\\n\" + \"─\" * 64)\n",
1494
+ " print(\" VERIFICATION TESTS\")\n",
1495
+ " print(\"─\" * 64)\n",
1496
+ "\n",
1497
+ " all_passed = True\n",
1498
+ "\n",
1499
+ " # Test 1: Surgery Module exists\n",
1500
+ " print(\"\\n[Test 1] Surgery Module exists...\")\n",
1501
+ " try:\n",
1502
+ " assert hasattr(model.model, \"surgery_module\")\n",
1503
+ " sm = model.model.surgery_module\n",
1504
+ " assert sm.input_dim == QWEN3_HIDDEN_SIZE\n",
1505
+ " assert sm.output_dim == DIFFUSION_HIDDEN_SIZE\n",
1506
+ " assert sm.layer_indices == SURGERY_LAYER_INDICES\n",
1507
+ " print(\" ✓ PASSED\")\n",
1508
+ " except Exception as e:\n",
1509
+ " print(f\" ✗ FAILED: {e}\")\n",
1510
+ " all_passed = False\n",
1511
+ "\n",
1512
+ " # Test 2: Language model is Qwen3\n",
1513
+ " print(\"\\n[Test 2] Language model is Qwen3...\")\n",
1514
+ " try:\n",
1515
+ " lm = model.model.language_model\n",
1516
+ " assert lm.config.hidden_size == QWEN3_HIDDEN_SIZE\n",
1517
+ " assert lm.config.num_hidden_layers == QWEN3_NUM_LAYERS\n",
1518
+ " print(f\" ✓ PASSED (hidden={QWEN3_HIDDEN_SIZE}, layers={QWEN3_NUM_LAYERS})\")\n",
1519
+ " except Exception as e:\n",
1520
+ " print(f\" ✗ FAILED: {e}\")\n",
1521
+ " all_passed = False\n",
1522
+ "\n",
1523
+ " # Test 3: Connectors\n",
1524
+ " print(\"\\n[Test 3] Connector dimensions...\")\n",
1525
+ " try:\n",
1526
+ " ac = model.model.acoustic_connector\n",
1527
+ " sc = model.model.semantic_connector\n",
1528
+ " assert ac.fc1.out_features == QWEN3_HIDDEN_SIZE\n",
1529
+ " assert sc.fc1.out_features == QWEN3_HIDDEN_SIZE\n",
1530
+ " print(\" ✓ PASSED\")\n",
1531
+ " except Exception as e:\n",
1532
+ " print(f\" ✗ FAILED: {e}\")\n",
1533
+ " all_passed = False\n",
1534
+ "\n",
1535
+ " # Test 4: LM Head\n",
1536
+ " print(\"\\n[Test 4] LM Head dimensions...\")\n",
1537
+ " try:\n",
1538
+ " assert model.lm_head.in_features == QWEN3_HIDDEN_SIZE\n",
1539
+ " assert model.lm_head.out_features == QWEN3_VOCAB_SIZE\n",
1540
+ " print(\" ✓ PASSED\")\n",
1541
+ " except Exception as e:\n",
1542
+ " print(f\" ✗ FAILED: {e}\")\n",
1543
+ " all_passed = False\n",
1544
+ "\n",
1545
+ " # Test 5: Diffusion Head unchanged\n",
1546
+ " print(\"\\n[Test 5] Diffusion Head (should be 3584)...\")\n",
1547
+ " try:\n",
1548
+ " dh = model.model.prediction_head\n",
1549
+ " assert dh.config.hidden_size == DIFFUSION_HIDDEN_SIZE\n",
1550
+ " assert dh.cond_proj.weight.shape[0] == DIFFUSION_HIDDEN_SIZE\n",
1551
+ " assert dh.cond_proj.weight.shape[1] == DIFFUSION_HIDDEN_SIZE\n",
1552
+ " print(\" ✓ PASSED\")\n",
1553
+ " except Exception as e:\n",
1554
+ " print(f\" ✗ FAILED: {e}\")\n",
1555
+ " all_passed = False\n",
1556
+ "\n",
1557
+ " # Test 6: Surgery Module forward pass\n",
1558
+ " print(\"\\n[Test 6] Surgery Module forward pass...\")\n",
1559
+ " try:\n",
1560
+ " sm = model.model.surgery_module\n",
1561
+ " device = next(sm.parameters()).device\n",
1562
+ " dtype = next(sm.parameters()).dtype\n",
1563
+ " with torch.no_grad():\n",
1564
+ " dummy_hs = tuple(\n",
1565
+ " torch.randn(1, 10, QWEN3_HIDDEN_SIZE, dtype=dtype, device=device)\n",
1566
+ " for _ in range(QWEN3_NUM_LAYERS + 1)\n",
1567
+ " )\n",
1568
+ " output = sm(dummy_hs)\n",
1569
+ " assert output.shape == (1, 10, DIFFUSION_HIDDEN_SIZE)\n",
1570
+ " assert not torch.isnan(output).any()\n",
1571
+ " assert not torch.isinf(output).any()\n",
1572
+ " print(f\" ✓ PASSED [1, 10, {QWEN3_HIDDEN_SIZE}] → [1, 10, {DIFFUSION_HIDDEN_SIZE}]\")\n",
1573
+ " except Exception as e:\n",
1574
+ " print(f\" ✗ FAILED: {e}\")\n",
1575
+ " all_passed = False\n",
1576
+ "\n",
1577
+ " # Test 7: Layer weights uniform\n",
1578
+ " print(\"\\n[Test 7] Initial layer weights (uniform)...\")\n",
1579
+ " try:\n",
1580
+ " weights = F.softmax(sm.layer_weights, dim=0)\n",
1581
+ " expected = torch.full_like(weights, 1.0 / sm.num_layers)\n",
1582
+ " assert torch.allclose(weights, expected, atol=1e-6)\n",
1583
+ " print(f\" ✓ PASSED ({weights.tolist()})\")\n",
1584
+ " except Exception as e:\n",
1585
+ " print(f\" ✗ FAILED: {e}\")\n",
1586
+ " all_passed = False\n",
1587
+ "\n",
1588
+ " # Test 8: Output projection zero-init\n",
1589
+ " print(\"\\n[Test 8] Output projection zero-init...\")\n",
1590
+ " try:\n",
1591
+ " assert torch.all(sm.output_proj.weight == 0)\n",
1592
+ " print(\" ✓ PASSED\")\n",
1593
+ " except Exception as e:\n",
1594
+ " print(f\" ✗ FAILED: {e}\")\n",
1595
+ " all_passed = False\n",
1596
+ "\n",
1597
+ " print(\"\\n\" + \"─\" * 64)\n",
1598
+ " if all_passed:\n",
1599
+ " print(\" ✅ ALL TESTS PASSED!\")\n",
1600
+ " else:\n",
1601
+ " print(\" ⚠️ SOME TESTS FAILED — check above\")\n",
1602
+ " print(\"─\" * 64)\n",
1603
+ "\n",
1604
+ " return all_passed\n",
1605
+ "\n",
1606
+ "\n",
1607
+ "def print_surgery_summary(model):\n",
1608
+ " \"\"\"Print a comprehensive summary of the surgery model.\"\"\"\n",
1609
+ " print(\"\\n\" + \"═\" * 64)\n",
1610
+ " print(\" SURGERY SUMMARY\")\n",
1611
+ " print(\"═\" * 64)\n",
1612
+ "\n",
1613
+ " lm = model.model.language_model\n",
1614
+ " lm_params = sum(p.numel() for p in lm.parameters())\n",
1615
+ " print(f\"\\n┌─ Language Model (Qwen3-4B)\")\n",
1616
+ " print(f\"│ Type: {lm.__class__.__name__}\")\n",
1617
+ " print(f\"│ Parameters: {lm_params:,}\")\n",
1618
+ " print(f\"│ Hidden: {model.config.decoder_config.hidden_size}\")\n",
1619
+ " print(f\"│ Layers: {model.config.decoder_config.num_hidden_layers}\")\n",
1620
+ "\n",
1621
+ " sm = model.model.surgery_module\n",
1622
+ " sm_params = sum(p.numel() for p in sm.parameters())\n",
1623
+ " print(f\"├─ Surgery Module\")\n",
1624
+ " print(f\"│ Parameters: {sm_params:,}\")\n",
1625
+ " print(f\"│ {sm.extra_repr()}\")\n",
1626
+ "\n",
1627
+ " ac_params = sum(p.numel() for p in model.model.acoustic_connector.parameters())\n",
1628
+ " sc_params = sum(p.numel() for p in model.model.semantic_connector.parameters())\n",
1629
+ " print(f\"├─ Acoustic Connector: {ac_params:,} params\")\n",
1630
+ " print(f\"├─ Semantic Connector: {sc_params:,} params\")\n",
1631
+ "\n",
1632
+ " lmh_params = sum(p.numel() for p in model.lm_head.parameters())\n",
1633
+ " print(f\"├─ LM Head: {lmh_params:,} params\")\n",
1634
+ "\n",
1635
+ " dh = model.model.prediction_head\n",
1636
+ " dh_params = sum(p.numel() for p in dh.parameters())\n",
1637
+ " print(f\"├─ Diffusion Head (unchanged): {dh_params:,} params\")\n",
1638
+ "\n",
1639
+ " at_params = sum(p.numel() for p in model.model.acoustic_tokenizer.parameters())\n",
1640
+ " st_params = sum(p.numel() for p in model.model.semantic_tokenizer.parameters())\n",
1641
+ " print(f\"├─ Acoustic Tokenizer (unchanged): {at_params:,} params\")\n",
1642
+ " print(f\"└─ Semantic Tokenizer (unchanged): {st_params:,} params\")\n",
1643
+ "\n",
1644
+ " total_params = sum(p.numel() for p in model.parameters())\n",
1645
+ " print(f\"\\n Total: {total_params:,} params (~{total_params * 2 / 1e9:.2f} GB in fp16)\")\n",
1646
+ "\n",
1647
+ " print(f\"\\n Data Flow:\")\n",
1648
+ " print(f\" Audio → AcousticTokenizer → (64-dim) → AcousticConnector → ({QWEN3_HIDDEN_SIZE}-dim)\")\n",
1649
+ " print(f\" Audio → SemanticTokenizer → (128-dim) → SemanticConnector → ({QWEN3_HIDDEN_SIZE}-dim)\")\n",
1650
+ " print(f\" Combined → Qwen3-4B → hidden_states[37 × {QWEN3_HIDDEN_SIZE}-dim]\")\n",
1651
+ " print(f\" → SurgeryModule → ({DIFFUSION_HIDDEN_SIZE}-dim) → DiffusionHead → Speech\")\n",
1652
+ " print(f\" → LMHead → Text Tokens\")\n",
1653
+ " print(\"═\" * 64)\n",
1654
+ "\n",
1655
+ "\n",
1656
+ "print(\"✅ Verification and summary functions defined\")"
1657
+ ]
1658
+ },
1659
+ {
1660
+ "cell_type": "markdown",
1661
+ "metadata": {},
1662
+ "source": [
1663
+ "---\n",
1664
+ "## 12. Main Surgery Pipeline\n",
1665
+ "\n",
1666
+ "Execute the complete surgery:\n",
1667
+ "1. Load VibeVoice 7B on CPU\n",
1668
+ "2. Load Qwen3-4B on CPU\n",
1669
+ "3. Perform surgery on CPU\n",
1670
+ "4. Save modified model\n",
1671
+ "5. Reload with device_map across GPU(s)"
1672
+ ]
1673
+ },
1674
+ {
1675
+ "cell_type": "code",
1676
+ "execution_count": null,
1677
+ "metadata": {},
1678
+ "outputs": [],
1679
+ "source": [
1680
+ "def run_surgery():\n",
1681
+ " \"\"\"\n",
1682
+ " Execute the complete surgery pipeline:\n",
1683
+ " 1. Load VibeVoice 7B on CPU\n",
1684
+ " 2. Load Qwen3-4B on CPU\n",
1685
+ " 3. Perform surgery on CPU\n",
1686
+ " 4. Save modified model\n",
1687
+ " 5. Reload with device_map across GPU(s)\n",
1688
+ " \"\"\"\n",
1689
+ " print(\"\\n\" + \"█\" * 64)\n",
1690
+ " print(\" VIBEVOICE MODEL SURGERY\")\n",
1691
+ " print(\" Qwen2.5-7B → Qwen3-4B + Surgery Module\")\n",
1692
+ " print(\"█\" * 64)\n",
1693
+ "\n",
1694
+ " estimate_memory()\n",
1695
+ "\n",
1696
+ " # ── Step 1: Load VibeVoice 7B on CPU ──\n",
1697
+ " print(\"\\n[Step 1/5] Loading VibeVoice 7B on CPU...\")\n",
1698
+ " gc.collect()\n",
1699
+ " torch.cuda.empty_cache()\n",
1700
+ "\n",
1701
+ " try:\n",
1702
+ " vibevoice_model = VibeVoiceForConditionalGenerationInference.from_pretrained(\n",
1703
+ " VIBEVOICE_MODEL_ID,\n",
1704
+ " torch_dtype=DTYPE,\n",
1705
+ " device_map=\"cpu\",\n",
1706
+ " trust_remote_code=True,\n",
1707
+ " )\n",
1708
+ " print(f\" ✓ VibeVoice 7B loaded on CPU\")\n",
1709
+ " except Exception as e:\n",
1710
+ " print(f\" ✗ Failed: {e}\")\n",
1711
+ " raise\n",
1712
+ "\n",
1713
+ " print(f\" Original decoder: {vibevoice_model.config.decoder_config.hidden_size}-dim, \"\n",
1714
+ " f\"{vibevoice_model.config.decoder_config.num_hidden_layers} layers, \"\n",
1715
+ " f\"vocab={vibevoice_model.config.decoder_config.vocab_size}\")\n",
1716
+ "\n",
1717
+ " # ── Step 2: Load Qwen3-4B on CPU ──\n",
1718
+ " print(f\"\\n[Step 2/5] Loading {QWEN3_MODEL_ID} on CPU...\")\n",
1719
+ " gc.collect()\n",
1720
+ " torch.cuda.empty_cache()\n",
1721
+ "\n",
1722
+ " try:\n",
1723
+ " qwen3_model = AutoModelForCausalLM.from_pretrained(\n",
1724
+ " QWEN3_MODEL_ID,\n",
1725
+ " torch_dtype=DTYPE,\n",
1726
+ " device_map=\"cpu\",\n",
1727
+ " trust_remote_code=True,\n",
1728
+ " )\n",
1729
+ " print(f\" ✓ Qwen3-4B loaded on CPU\")\n",
1730
+ " except Exception as e:\n",
1731
+ " print(f\" ✗ Failed: {e}\")\n",
1732
+ " print(f\" ℹ ️ Ensure transformers>=4.51.0: pip install 'transformers>=4.51.0'\")\n",
1733
+ " raise\n",
1734
+ "\n",
1735
+ " # Verify dimensions\n",
1736
+ " assert qwen3_model.config.hidden_size == QWEN3_HIDDEN_SIZE\n",
1737
+ " assert qwen3_model.config.num_hidden_layers == QWEN3_NUM_LAYERS\n",
1738
+ " assert qwen3_model.config.vocab_size == QWEN3_VOCAB_SIZE\n",
1739
+ " print(f\" Qwen3: {QWEN3_HIDDEN_SIZE}-dim, {QWEN3_NUM_LAYERS} layers, vocab={QWEN3_VOCAB_SIZE}\")\n",
1740
+ "\n",
1741
+ " # ── Step 3: Perform Surgery on CPU ──\n",
1742
+ " print(f\"\\n[Step 3/5] Performing surgery on CPU...\")\n",
1743
+ " modified_model = perform_surgery(\n",
1744
+ " vibevoice_model=vibevoice_model,\n",
1745
+ " qwen3_model=qwen3_model,\n",
1746
+ " surgery_layer_indices=SURGERY_LAYER_INDICES,\n",
1747
+ " dtype=DTYPE,\n",
1748
+ " )\n",
1749
+ "\n",
1750
+ " # Free Qwen3 model\n",
1751
+ " del qwen3_model\n",
1752
+ " gc.collect()\n",
1753
+ " torch.cuda.empty_cache()\n",
1754
+ "\n",
1755
+ " # ── Step 4: Save Surgery Model ──\n",
1756
+ " print(f\"\\n[Step 4/5] Saving surgery model to {OUTPUT_DIR}...\")\n",
1757
+ " save_surgery_model(modified_model, OUTPUT_DIR)\n",
1758
+ "\n",
1759
+ " # Free CPU model\n",
1760
+ " del modified_model\n",
1761
+ " gc.collect()\n",
1762
+ " torch.cuda.empty_cache()\n",
1763
+ "\n",
1764
+ " # ── Step 5: Reload with device_map ──\n",
1765
+ " print(f\"\\n[Step 5/5] Loading with device_map across GPU(s)...\")\n",
1766
+ " final_model = load_surgery_model(\n",
1767
+ " OUTPUT_DIR,\n",
1768
+ " dtype=DTYPE,\n",
1769
+ " device_map=\"auto\",\n",
1770
+ " )\n",
1771
+ "\n",
1772
+ " # Print summary\n",
1773
+ " print_surgery_summary(final_model)\n",
1774
+ "\n",
1775
+ " return final_model\n",
1776
+ "\n",
1777
+ "\n",
1778
+ "print(\"✅ Main surgery pipeline defined\")"
1779
+ ]
1780
+ },
1781
+ {
1782
+ "cell_type": "markdown",
1783
+ "metadata": {},
1784
+ "source": [
1785
+ "---\n",
1786
+ "## 13. 🚀 Run the Surgery!\n",
1787
+ "\n",
1788
+ "**⚠️ Important Notes Before Running:**\n",
1789
+ "1. This will download ~22 GB of model weights (VibeVoice 7B + Qwen3-4B)\n",
1790
+ "2. The surgery is performed on CPU to avoid GPU OOM\n",
1791
+ "3. The final model is saved and reloaded with `device_map=\"auto\"`\n",
1792
+ "4. Make sure you have enough disk space (~25 GB) and RAM (~25 GB)"
1793
+ ]
1794
+ },
1795
+ {
1796
+ "cell_type": "code",
1797
+ "execution_count": null,
1798
+ "metadata": {},
1799
+ "outputs": [],
1800
+ "source": [
1801
+ "# ╔═══════════════════════════════════════════════════════════════╗\n",
1802
+ "# ║ RUN THE SURGERY — Execute this cell! ║\n",
1803
+ "# ╚═══════════════════════════════════════════════════════════════╝\n",
1804
+ "\n",
1805
+ "surgery_model = run_surgery()"
1806
+ ]
1807
+ },
1808
+ {
1809
+ "cell_type": "markdown",
1810
+ "metadata": {},
1811
+ "source": [
1812
+ "---\n",
1813
+ "## 14. Verify the Surgery"
1814
+ ]
1815
+ },
1816
+ {
1817
+ "cell_type": "code",
1818
+ "execution_count": null,
1819
+ "metadata": {},
1820
+ "outputs": [],
1821
+ "source": [
1822
+ "# Run verification tests\n",
1823
+ "all_tests_passed = verify_surgery(surgery_model)\n",
1824
+ "print(f\"\\nVerification result: {'✅ ALL PASSED' if all_tests_passed else '❌ SOME FAILED'}\")"
1825
+ ]
1826
+ },
1827
+ {
1828
+ "cell_type": "markdown",
1829
+ "metadata": {},
1830
+ "source": [
1831
+ "---\n",
1832
+ "## 15. Tokenizer Setup (Required for Inference)\n",
1833
+ "\n",
1834
+ "Qwen3 has a different vocabulary than Qwen2.5:\n",
1835
+ "- Qwen2.5 vocab_size: 152064\n",
1836
+ "- Qwen3 vocab_size: 151936\n",
1837
+ "\n",
1838
+ "You must use the Qwen3 tokenizer and add the special speech tokens."
1839
+ ]
1840
+ },
1841
+ {
1842
+ "cell_type": "code",
1843
+ "execution_count": null,
1844
+ "metadata": {},
1845
+ "outputs": [],
1846
+ "source": [
1847
+ "# Load Qwen3 tokenizer\n",
1848
+ "from transformers import AutoTokenizer\n",
1849
+ "\n",
1850
+ "qwen3_tokenizer = AutoTokenizer.from_pretrained(QWEN3_MODEL_ID, trust_remote_code=True)\n",
1851
+ "print(f\"Qwen3 tokenizer loaded: vocab_size={qwen3_tokenizer.vocab_size}\")\n",
1852
+ "\n",
1853
+ "# Load original VibeVoice tokenizer to get special token IDs\n",
1854
+ "from vibevoice.processor.vibevoice_processor import VibeVoiceProcessor\n",
1855
+ "orig_processor = VibeVoiceProcessor.from_pretrained(VIBEVOICE_MODEL_ID)\n",
1856
+ "orig_tokenizer = orig_processor.tokenizer\n",
1857
+ "\n",
1858
+ "# Get special token values from original tokenizer\n",
1859
+ "special_tokens = {\n",
1860
+ " \"speech_start\": getattr(orig_tokenizer, \"speech_start_id\", None),\n",
1861
+ " \"speech_end\": getattr(orig_tokenizer, \"speech_end_id\", None),\n",
1862
+ " \"speech_diffusion\": getattr(orig_tokenizer, \"speech_diffusion_id\", None),\n",
1863
+ "}\n",
1864
+ "print(f\"\\nOriginal special tokens: {special_tokens}\")\n",
1865
+ "print(f\"Original speech_start decoded: '{orig_tokenizer.decode([special_tokens['speech_start']])}'\")\n",
1866
+ "print(f\"Original speech_end decoded: '{orig_tokenizer.decode([special_tokens['speech_end']])}'\")\n",
1867
+ "print(f\"Original speech_diffusion decoded: '{orig_tokenizer.decode([special_tokens['speech_diffusion']])}'\")\n",
1868
+ "\n",
1869
+ "# Add special tokens to Qwen3 tokenizer\n",
1870
+ "num_added = qwen3_tokenizer.add_special_tokens({\n",
1871
+ " \"additional_special_tokens\": [\n",
1872
+ " orig_tokenizer.decode([special_tokens[\"speech_start\"]]),\n",
1873
+ " orig_tokenizer.decode([special_tokens[\"speech_end\"]]),\n",
1874
+ " orig_tokenizer.decode([special_tokens[\"speech_diffusion\"]]),\n",
1875
+ " ]\n",
1876
+ "})\n",
1877
+ "print(f\"\\nAdded {num_added} special tokens to Qwen3 tokenizer\")\n",
1878
+ "\n",
1879
+ "# Get new IDs\n",
1880
+ "qwen3_tokenizer.speech_start_id = qwen3_tokenizer.convert_tokens_to_ids(\n",
1881
+ " orig_tokenizer.decode([special_tokens[\"speech_start\"]])\n",
1882
+ ")\n",
1883
+ "qwen3_tokenizer.speech_end_id = qwen3_tokenizer.convert_tokens_to_ids(\n",
1884
+ " orig_tokenizer.decode([special_tokens[\"speech_end\"]])\n",
1885
+ ")\n",
1886
+ "qwen3_tokenizer.speech_diffusion_id = qwen3_tokenizer.convert_tokens_to_ids(\n",
1887
+ " orig_tokenizer.decode([special_tokens[\"speech_diffusion\"]])\n",
1888
+ ")\n",
1889
+ "\n",
1890
+ "print(f\"\\nNew special token IDs:\")\n",
1891
+ "print(f\" speech_start_id: {qwen3_tokenizer.speech_start_id}\")\n",
1892
+ "print(f\" speech_end_id: {qwen3_tokenizer.speech_end_id}\")\n",
1893
+ "print(f\" speech_diffusion_id: {qwen3_tokenizer.speech_diffusion_id}\")\n",
1894
+ "\n",
1895
+ "# Resize model embeddings if needed\n",
1896
+ "new_vocab_size = len(qwen3_tokenizer)\n",
1897
+ "print(f\"\\nNew vocab size: {new_vocab_size}\")\n",
1898
+ "\n",
1899
+ "if new_vocab_size != surgery_model.config.decoder_config.vocab_size:\n",
1900
+ " print(f\"Resizing embeddings: {surgery_model.config.decoder_config.vocab_size} → {new_vocab_size}\")\n",
1901
+ " surgery_model.model.language_model.resize_token_embeddings(new_vocab_size)\n",
1902
+ " surgery_model.config.decoder_config.vocab_size = new_vocab_size\n",
1903
+ " # Re-tie weights\n",
1904
+ " surgery_model.lm_head.weight = surgery_model.model.language_model.embed_tokens.weight\n",
1905
+ " print(\" ✓ Embeddings resized and weights re-tied\")\n",
1906
+ "\n",
1907
+ "print(\"\\n✅ Tokenizer setup complete\")"
1908
+ ]
1909
+ },
1910
+ {
1911
+ "cell_type": "markdown",
1912
+ "metadata": {},
1913
+ "source": [
1914
+ "---\n",
1915
+ "## 16. Inference Demo\n",
1916
+ "\n",
1917
+ "Test the surgery model with a simple text-to-speech generation.\n",
1918
+ "\n",
1919
+ "**Note:** The surgery model is in its initial state (zero-init output projection),\n",
1920
+ "so the generated speech quality will be random noise. You need to **fine-tune** the\n",
1921
+ "surgery module + connectors for meaningful output."
1922
+ ]
1923
+ },
1924
+ {
1925
+ "cell_type": "code",
1926
+ "execution_count": null,
1927
+ "metadata": {},
1928
+ "outputs": [],
1929
+ "source": [
1930
+ "# Test inference (expect random noise since model is not fine-tuned yet)\n",
1931
+ "import numpy as np\n",
1932
+ "\n",
1933
+ "print(\"Testing inference (random output expected — fine-tune for real speech)...\\n\")\n",
1934
+ "\n",
1935
+ "# Prepare input\n",
1936
+ "text = \"Hello, this is a test of the surgery model.\"\n",
1937
+ "\n",
1938
+ "# Use the processor to format the input\n",
1939
+ "processor = VibeVoiceProcessor.from_pretrained(VIBEVOICE_MODEL_ID)\n",
1940
+ "# Update processor's tokenizer\n",
1941
+ "processor.tokenizer = qwen3_tokenizer\n",
1942
+ "\n",
1943
+ "# Format input with speech markers\n",
1944
+ "formatted_text = f\"<|speech_start|>{text}<|speech_diffusion|>\"\n",
1945
+ "input_ids = qwen3_tokenizer.encode(formatted_text, return_tensors=\"pt\")\n",
1946
+ "\n",
1947
+ "# Create speech masks (dummy for testing)\n",
1948
+ "speech_tensors = torch.zeros(1, 1, 64, dtype=DTYPE, device=surgery_model.device)\n",
1949
+ "speech_masks = torch.ones(1, 1, dtype=torch.bool)\n",
1950
+ "speech_input_mask = torch.zeros_like(input_ids, dtype=torch.bool)\n",
1951
+ "\n",
1952
+ "print(f\"Input text: {text}\")\n",
1953
+ "print(f\"Formatted: {formatted_text}\")\n",
1954
+ "print(f\"Input IDs shape: {input_ids.shape}\")\n",
1955
+ "print(f\"\\nGenerating...\")\n",
1956
+ "\n",
1957
+ "try:\n",
1958
+ " with torch.no_grad():\n",
1959
+ " output = surgery_model.generate(\n",
1960
+ " input_ids=input_ids.to(surgery_model.device),\n",
1961
+ " tokenizer=qwen3_tokenizer,\n",
1962
+ " speech_tensors=speech_tensors,\n",
1963
+ " speech_masks=speech_masks,\n",
1964
+ " speech_input_mask=speech_input_mask,\n",
1965
+ " max_new_tokens=50,\n",
1966
+ " do_sample=False,\n",
1967
+ " return_speech=True,\n",
1968
+ " show_progress_bar=True,\n",
1969
+ " )\n",
1970
+ " \n",
1971
+ " print(f\"\\n✅ Inference completed!\")\n",
1972
+ " print(f\"Generated sequence length: {output.sequences.shape[-1]}\")\n",
1973
+ " if output.speech_outputs and output.speech_outputs[0] is not None:\n",
1974
+ " print(f\"Speech output shape: {output.speech_outputs[0].shape}\")\n",
1975
+ " # Save as audio file\n",
1976
+ " import scipy.io.wavfile as wavfile\n",
1977
+ " audio = output.speech_outputs[0].cpu().numpy().squeeze()\n",
1978
+ " wavfile.write(\"/content/surgery_test_output.wav\", 24000, audio)\n",
1979
+ " print(f\"Audio saved to /content/surgery_test_output.wav\")\n",
1980
+ " else:\n",
1981
+ " print(\"No speech output (expected for un-fine-tuned model)\")\n",
1982
+ "except Exception as e:\n",
1983
+ " print(f\"Inference error (expected for un-fine-tuned model): {e}\")\n",
1984
+ " print(\"This is normal — the surgery module needs fine-tuning before generating real speech.\")"
1985
+ ]
1986
+ },
1987
+ {
1988
+ "cell_type": "markdown",
1989
+ "metadata": {},
1990
+ "source": [
1991
+ "---\n",
1992
+ "## 17. LoRA Fine-Tuning Setup (Optional)\n",
1993
+ "\n",
1994
+ "Setup LoRA for parameter-efficient fine-tuning of the surgery model."
1995
+ ]
1996
+ },
1997
+ {
1998
+ "cell_type": "code",
1999
+ "execution_count": null,
2000
+ "metadata": {},
2001
+ "outputs": [],
2002
+ "source": [
2003
+ "def setup_lora_training(\n",
2004
+ " model,\n",
2005
+ " lora_r: int = 16,\n",
2006
+ " lora_alpha: int = 32,\n",
2007
+ " lora_dropout: float = 0.05,\n",
2008
+ " target_modules: Optional[List[str]] = None,\n",
2009
+ "):\n",
2010
+ " \"\"\"\n",
2011
+ " Setup LoRA for parameter-efficient fine-tuning of the surgery model.\n",
2012
+ " \"\"\"\n",
2013
+ " try:\n",
2014
+ " from peft import LoraConfig, get_peft_model, TaskType\n",
2015
+ " except ImportError:\n",
2016
+ " raise ImportError(\"pip install peft\")\n",
2017
+ "\n",
2018
+ " if target_modules is None:\n",
2019
+ " target_modules = [\n",
2020
+ " \"surgery_module.swiglu_gate\",\n",
2021
+ " \"surgery_module.swiglu_up\",\n",
2022
+ " \"surgery_module.output_proj\",\n",
2023
+ " \"acoustic_connector.fc1\",\n",
2024
+ " \"acoustic_connector.fc2\",\n",
2025
+ " \"semantic_connector.fc1\",\n",
2026
+ " \"semantic_connector.fc2\",\n",
2027
+ " ]\n",
2028
+ "\n",
2029
+ " lora_config = LoraConfig(\n",
2030
+ " r=lora_r,\n",
2031
+ " lora_alpha=lora_alpha,\n",
2032
+ " lora_dropout=lora_dropout,\n",
2033
+ " target_modules=target_modules,\n",
2034
+ " bias=\"none\",\n",
2035
+ " task_type=TaskType.CAUSAL_LM,\n",
2036
+ " )\n",
2037
+ "\n",
2038
+ " peft_model = get_peft_model(model, lora_config)\n",
2039
+ "\n",
2040
+ " trainable = sum(p.numel() for p in peft_model.parameters() if p.requires_grad)\n",
2041
+ " total = sum(p.numel() for p in peft_model.parameters())\n",
2042
+ " print(f\"\\n LoRA Applied:\")\n",
2043
+ " print(f\" Trainable: {trainable:,} ({100 * trainable / total:.2f}%)\")\n",
2044
+ " print(f\" Total: {total:,}\")\n",
2045
+ "\n",
2046
+ " return peft_model\n",
2047
+ "\n",
2048
+ "\n",
2049
+ "# Uncomment to apply LoRA:\n",
2050
+ "# lora_model = setup_lora_training(surgery_model)"
2051
+ ]
2052
+ },
2053
+ {
2054
+ "cell_type": "markdown",
2055
+ "metadata": {},
2056
+ "source": [
2057
+ "---\n",
2058
+ "## 18. Push to HuggingFace Hub (Optional)"
2059
+ ]
2060
+ },
2061
+ {
2062
+ "cell_type": "code",
2063
+ "execution_count": null,
2064
+ "metadata": {},
2065
+ "outputs": [],
2066
+ "source": [
2067
+ "# Uncomment and set your HF token to push the model\n",
2068
+ "# from huggingface_hub import login\n",
2069
+ "# login(token=\"YOUR_HF_TOKEN\")\n",
2070
+ "#\n",
2071
+ "# HF_REPO = \"your-username/vibevoice-qwen3-surgery\"\n",
2072
+ "# surgery_model.push_to_hub(HF_REPO)\n",
2073
+ "# qwen3_tokenizer.push_to_hub(HF_REPO)\n",
2074
+ "# print(f\"Model pushed to https://huggingface.co/{HF_REPO}\")"
2075
+ ]
2076
+ },
2077
+ {
2078
+ "cell_type": "markdown",
2079
+ "metadata": {},
2080
+ "source": [
2081
+ "---\n",
2082
+ "## 19. Load from Saved Checkpoint (Future Use)\n",
2083
+ "\n",
2084
+ "To reload the surgery model later without re-running the surgery:"
2085
+ ]
2086
+ },
2087
+ {
2088
+ "cell_type": "code",
2089
+ "execution_count": null,
2090
+ "metadata": {},
2091
+ "outputs": [],
2092
+ "source": [
2093
+ "# Uncomment to load from saved checkpoint:\n",
2094
+ "# _patch_vibevoice_config_for_qwen3()\n",
2095
+ "# loaded_model = load_surgery_model(\n",
2096
+ "# OUTPUT_DIR,\n",
2097
+ "# dtype=DTYPE,\n",
2098
+ "# device_map=\"auto\",\n",
2099
+ "# )\n",
2100
+ "# verify_surgery(loaded_model)"
2101
+ ]
2102
+ },
2103
+ {
2104
+ "cell_type": "markdown",
2105
+ "metadata": {},
2106
+ "source": [
2107
+ "---\n",
2108
+ "## 20. Compatibility Notes\n",
2109
+ "\n",
2110
+ "### ✅ Compatible (no changes needed):\n",
2111
+ "- `VibeVoiceModel` — forward patched to force `output_hidden_states=True`\n",
2112
+ "- `SpeechConnector` — replaced with correct dimensions (64/128 → 2560)\n",
2113
+ "- `VibeVoiceDiffusionHead` — UNCHANGED (still expects 3584-dim conditioning)\n",
2114
+ "- `VibeVoiceAcousticTokenizerModel` — UNCHANGED\n",
2115
+ "- `VibeVoiceSemanticTokenizerModel` — UNCHANGED\n",
2116
+ "- `VibeVoiceTokenizerStreamingCache` — UNCHANGED\n",
2117
+ "- `AudioStreamer` / `AsyncAudioStreamer` — UNCHANGED\n",
2118
+ "- `DPMSolverMultistepScheduler` — UNCHANGED\n",
2119
+ "- `sample_speech_tokens()` — UNCHANGED (receives 3584-dim from surgery)\n",
2120
+ "\n",
2121
+ "### ⚠️ Requires Attention:\n",
2122
+ "1. **TOKENIZER**: Qwen3 has `vocab_size=151936` (vs Qwen2's 152064). You MUST swap the text tokenizer to `Qwen3Tokenizer`.\n",
2123
+ "\n",
2124
+ "2. **SPECIAL TOKENS**: `speech_start_id`, `speech_end_id`, `speech_diffusion_id` must be added to the Qwen3 tokenizer.\n",
2125
+ "\n",
2126
+ "3. **TRAINING**: Use `finetune_vibevoice_lora105.py` with `--train_surgery_module=True` for fine-tuning.\n",
2127
+ "\n",
2128
+ "4. **CONFIG LOADING**: Call `_patch_vibevoice_config_for_qwen3()` before loading the saved model.\n",
2129
+ "\n",
2130
+ "5. **WEIGHT TYING**: Qwen3 uses `tie_word_embeddings=True`. After surgery, `lm_head.weight` IS `embed_tokens.weight`.\n",
2131
+ "\n",
2132
+ "6. **GENERATE**: Each `generate()` call is independent. The surgery module is called fresh for each diffusion step.\n",
2133
+ "\n",
2134
+ "7. **MULTI-GPU**: The patched generate method handles device placement for multi-GPU setups."
2135
+ ]
2136
+ },
2137
+ {
2138
+ "cell_type": "code",
2139
+ "execution_count": null,
2140
+ "metadata": {},
2141
+ "outputs": [],
2142
+ "source": [
2143
+ "print(\"\\n\" + \"█\" * 64)\n",
2144
+ "print(\" SURGERY NOTEBOOK COMPLETE!\")\n",
2145
+ "print(f\" Model saved to: {OUTPUT_DIR}\")\n",
2146
+ "print(\"\")\n",
2147
+ "print(\" Next Steps:\")\n",
2148
+ "print(\" 1. Fine-tune the Surgery Module + connectors\")\n",
2149
+ "print(\" 2. Use setup_lora_training() for LoRA fine-tuning\")\n",
2150
+ "print(\" 3. Use load_surgery_model() to reload later\")\n",
2151
+ "print(\" 4. Use finetune_vibevoice_lora105.py with --train_surgery_module=True\")\n",
2152
+ "print(\"█\" * 64)"
2153
+ ]
2154
+ }
2155
+ ]
2156
+ }
VibeVoice-tpu/src/vibevoice_surgery_colab.py ADDED
@@ -0,0 +1,1631 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ VibeVoice Surgery for Kaggle Dual T4 GPUs
3
+ ==========================================
4
+
5
+ This script performs model surgery on VibeVoice-7B, replacing the Qwen2.5-7B
6
+ language model with Qwen3-4B and adding a Surgery Module to bridge the hidden
7
+ dimension gap (2560 → 3584) for the Diffusion Head.
8
+
9
+ Designed for Kaggle environment:
10
+ - 2× T4 GPUs (16 GB VRAM each, 32 GB total)
11
+ - ~30 GB system RAM (CPU)
12
+ - float16 precision (T4 native — bfloat16 is NOT efficient on Turing arch.)
13
+
14
+ Memory strategy:
15
+ 1. Load both models on CPU RAM (~22 GB in fp16)
16
+ 2. Perform surgery on CPU
17
+ 3. Save the modified model
18
+ 4. Reload with device_map="auto" across both T4 GPUs
19
+
20
+ Compatibility fixes vs. the original surgery script:
21
+ - Monkey-patches VibeVoiceConfig to accept Qwen3Config
22
+ - Saves config in a reload-safe format (Qwen3 params under qwen2 model_type)
23
+ - Adds hidden_states to inference forward output (needed by surgery module)
24
+ - Uses float16 for T4 compatibility
25
+ - Handles device placement for multi-GPU surgery module calls
26
+ - Properly ties LM head weights for Qwen3
27
+ """
28
+
29
+ import os
30
+ import sys
31
+ import gc
32
+ import json
33
+ import copy
34
+ import types
35
+ import warnings
36
+ import functools
37
+ from typing import Optional, Tuple, Union, List, Dict, Any
38
+ from dataclasses import dataclass
39
+
40
+ import torch
41
+ import torch.nn as nn
42
+ import torch.nn.functional as F
43
+
44
+ from transformers import (
45
+ AutoModel,
46
+ AutoModelForCausalLM,
47
+ AutoConfig,
48
+ AutoTokenizer,
49
+ )
50
+ from transformers.modeling_outputs import BaseModelOutputWithPast, ModelOutput
51
+ from transformers.models.llama.modeling_llama import LlamaRMSNorm
52
+ from transformers.utils import logging
53
+
54
+ # ── Import VibeVoice components ──
55
+ from vibevoice.modular.configuration_vibevoice import (
56
+ VibeVoiceConfig,
57
+ VibeVoiceDiffusionHeadConfig,
58
+ )
59
+ from vibevoice.modular.modeling_vibevoice import (
60
+ VibeVoiceModel,
61
+ VibeVoiceForConditionalGeneration,
62
+ SpeechConnector,
63
+ )
64
+ from vibevoice.modular.modeling_vibevoice_inference import (
65
+ VibeVoiceForConditionalGenerationInference,
66
+ VibeVoiceCausalLMOutputWithPast,
67
+ VibeVoiceGenerationOutput,
68
+ VibeVoiceTokenConstraintProcessor,
69
+ )
70
+ from vibevoice.modular.modular_vibevoice_tokenizer import VibeVoiceTokenizerStreamingCache
71
+
72
+ logger = logging.get_logger(__name__)
73
+
74
+ # ============================================================================
75
+ # SECTION 1: Global Configuration
76
+ # ============================================================================
77
+
78
+ DTYPE = torch.float16 # T4 native precision (NOT bfloat16)
79
+
80
+ # Qwen3-4B dimensions
81
+ QWEN3_HIDDEN_SIZE = 2560
82
+ QWEN3_NUM_LAYERS = 36
83
+ QWEN3_VOCAB_SIZE = 151936
84
+ QWEN3_MODEL_ID = "Qwen/Qwen3-4B-Instruct-2507"
85
+
86
+ # VibeVoice Diffusion Head dimensions (unchanged)
87
+ DIFFUSION_HIDDEN_SIZE = 3584
88
+
89
+ # Surgery: which intermediate layers of Qwen3 to extract (0-indexed)
90
+ # Layers 24, 28, 32, 34 out of 36 total
91
+ SURGERY_LAYER_INDICES = [24, 28, 32, 34]
92
+
93
+ # Attention implementation
94
+ # IMPORTANT: T4 GPUs (Turing architecture) do NOT support flash_attention_2.
95
+ # Always use "sdpa" for T4 / Turing compatibility.
96
+ ATTN_IMPL = "sdpa"
97
+
98
+ # Model paths — adjust for your setup
99
+ VIBEVOICE_MODEL_ID = "vibevoice/VibeVoice-7B"
100
+ OUTPUT_DIR = "/kaggle/working/vibevoice_qwen3_surgery"
101
+
102
+ print(f"╔══════════════════════════════════════════════════════════════╗")
103
+ print(f"║ VibeVoice Surgery — Kaggle Dual T4 Configuration ║")
104
+ print(f"╠══════════════════════════════════════════════════════════════╣")
105
+ print(f"║ Dtype: {str(DTYPE):<42}║")
106
+ print(f"║ Attention: {ATTN_IMPL:<42}║")
107
+ print(f"║ Qwen3 hidden: {QWEN3_HIDDEN_SIZE:<42}║")
108
+ print(f"║ Qwen3 layers: {QWEN3_NUM_LAYERS:<42}║")
109
+ print(f"║ Diffusion hidden: {DIFFUSION_HIDDEN_SIZE:<42}║")
110
+ print(f"║ Surgery layers: {str(SURGERY_LAYER_INDICES):<42}║")
111
+ print(f"╚══════════════════════════════════════════════════════════════╝")
112
+
113
+
114
+ # ============================================================================
115
+ # SECTION 2: Monkey-patch VibeVoiceConfig to Accept Qwen3
116
+ # ============================================================================
117
+
118
+ def _patch_vibevoice_config_for_qwen3():
119
+ """
120
+ Monkey-patch VibeVoiceConfig.__init__ to accept Qwen3Config as decoder_config.
121
+
122
+ The original VibeVoiceConfig only accepts decoder_config with model_type="qwen2".
123
+ This patch adds support for model_type="qwen3" by importing Qwen3Config and
124
+ handling it alongside Qwen2Config.
125
+ """
126
+ try:
127
+ from transformers import Qwen3Config
128
+ except ImportError:
129
+ raise ImportError(
130
+ "Qwen3Config not found. Please upgrade transformers: "
131
+ "pip install 'transformers>=4.51.0'"
132
+ )
133
+
134
+ from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
135
+ from transformers.configuration_utils import PretrainedConfig
136
+
137
+ # Store original __init__ for reference
138
+ _orig_init = VibeVoiceConfig.__init__
139
+
140
+ def _new_init(
141
+ self,
142
+ acoustic_tokenizer_config=None,
143
+ semantic_tokenizer_config=None,
144
+ decoder_config=None,
145
+ diffusion_head_config=None,
146
+ **kwargs
147
+ ):
148
+ kwargs["_attn_implementation_autoset"] = False
149
+
150
+ # ── acoustic_tokenizer_config ──
151
+ if acoustic_tokenizer_config is None:
152
+ self.acoustic_tokenizer_config = self.sub_configs["acoustic_tokenizer_config"]()
153
+ elif isinstance(acoustic_tokenizer_config, dict):
154
+ acoustic_tokenizer_config["model_type"] = "vibevoice_acoustic_tokenizer"
155
+ self.acoustic_tokenizer_config = self.sub_configs["acoustic_tokenizer_config"](
156
+ **acoustic_tokenizer_config
157
+ )
158
+ else:
159
+ self.acoustic_tokenizer_config = acoustic_tokenizer_config
160
+
161
+ # ── semantic_tokenizer_config ──
162
+ if semantic_tokenizer_config is None:
163
+ self.semantic_tokenizer_config = self.sub_configs["semantic_tokenizer_config"]()
164
+ elif isinstance(semantic_tokenizer_config, dict):
165
+ semantic_tokenizer_config["model_type"] = "vibevoice_semantic_tokenizer"
166
+ self.semantic_tokenizer_config = self.sub_configs["semantic_tokenizer_config"](
167
+ **semantic_tokenizer_config
168
+ )
169
+ else:
170
+ self.semantic_tokenizer_config = semantic_tokenizer_config
171
+
172
+ # ── decoder_config (NOW SUPPORTS QWEN3!) ──
173
+ if decoder_config is None:
174
+ self.decoder_config = self.sub_configs["decoder_config"]()
175
+ elif isinstance(decoder_config, dict):
176
+ model_type = decoder_config.get("model_type", "")
177
+ if model_type == "qwen2":
178
+ self.decoder_config = Qwen2Config(**decoder_config)
179
+ elif model_type == "qwen3":
180
+ self.decoder_config = Qwen3Config(**decoder_config)
181
+ else:
182
+ # Try Qwen2Config as fallback (for "vibepod" etc.)
183
+ try:
184
+ self.decoder_config = Qwen2Config(**decoder_config)
185
+ except Exception:
186
+ raise ValueError(
187
+ f"Unsupported decoder model type: {model_type}. "
188
+ f"Supported: 'qwen2', 'qwen3'"
189
+ )
190
+ elif isinstance(decoder_config, (Qwen2Config, Qwen3Config)):
191
+ self.decoder_config = decoder_config
192
+ elif isinstance(decoder_config, PretrainedConfig):
193
+ # Accept any PretrainedConfig (e.g., Qwen3Config instance)
194
+ self.decoder_config = decoder_config
195
+ else:
196
+ raise ValueError(f"Invalid decoder_config type: {type(decoder_config)}")
197
+
198
+ # ── diffusion_head_config ──
199
+ if diffusion_head_config is None:
200
+ self.diffusion_head_config = self.sub_configs["diffusion_head_config"]()
201
+ elif isinstance(diffusion_head_config, dict):
202
+ diffusion_head_config["model_type"] = "vibevoice_diffusion_head"
203
+ self.diffusion_head_config = self.sub_configs["diffusion_head_config"](
204
+ **diffusion_head_config
205
+ )
206
+ else:
207
+ self.diffusion_head_config = diffusion_head_config
208
+
209
+ # Derived dimensions
210
+ self.acoustic_vae_dim = getattr(self.acoustic_tokenizer_config, "vae_dim", 64)
211
+ self.semantic_vae_dim = getattr(self.semantic_tokenizer_config, "vae_dim", 128)
212
+
213
+ PretrainedConfig.__init__(self, **kwargs)
214
+
215
+ VibeVoiceConfig.__init__ = _new_init
216
+ print("✅ VibeVoiceConfig patched to accept Qwen3Config")
217
+
218
+
219
+ # Apply the patch immediately
220
+ _patch_vibevoice_config_for_qwen3()
221
+
222
+
223
+ # ============================================================================
224
+ # SECTION 3: Surgery Module Definition
225
+ # ============================================================================
226
+
227
+ class Qwen3SurgeryModule(nn.Module):
228
+ """
229
+ Bridges Qwen3-4B (2560-dim) to VibeVoice Diffusion Head (3584-dim).
230
+
231
+ Pipeline:
232
+ 1. Hierarchical Feature Extraction — extract hidden states from 4
233
+ intermediate Qwen3 layers (rich prosody / emotion / phonetic info)
234
+ 2. Learnable Weighted Sum — softmax-weighted average (memory-efficient)
235
+ 3. RMSNorm — numerical stabilisation across layer magnitudes
236
+ 4. SwiGLU — non-linear translation between vector spaces
237
+ 5. Linear Projection — upscale 2560 → 3584 for the Diffusion Head
238
+
239
+ Args:
240
+ input_dim: Qwen3 hidden size (2560)
241
+ output_dim: Diffusion Head hidden size (3584)
242
+ layer_indices: 0-indexed transformer layer indices to extract
243
+ rms_norm_eps: Epsilon for RMSNorm
244
+ """
245
+
246
+ def __init__(
247
+ self,
248
+ input_dim: int = 2560,
249
+ output_dim: int = 3584,
250
+ layer_indices: Optional[List[int]] = None,
251
+ rms_norm_eps: float = 1e-6,
252
+ ):
253
+ super().__init__()
254
+ if layer_indices is None:
255
+ layer_indices = [24, 28, 32, 34]
256
+
257
+ self.input_dim = input_dim
258
+ self.output_dim = output_dim
259
+ self.layer_indices = layer_indices
260
+ self.num_layers = len(layer_indices)
261
+
262
+ # Step 2: Learnable Weighted Sum
263
+ self.layer_weights = nn.Parameter(torch.zeros(self.num_layers))
264
+
265
+ # Step 3: RMSNorm
266
+ self.norm = LlamaRMSNorm(input_dim, eps=rms_norm_eps)
267
+
268
+ # Step 4: SwiGLU
269
+ self.swiglu_gate = nn.Linear(input_dim, input_dim, bias=False)
270
+ self.swiglu_up = nn.Linear(input_dim, input_dim, bias=False)
271
+
272
+ # Step 5: Linear Projection
273
+ self.output_proj = nn.Linear(input_dim, output_dim, bias=False)
274
+
275
+ self._initialize_weights()
276
+
277
+ def _initialize_weights(self):
278
+ nn.init.normal_(self.swiglu_gate.weight, std=0.02)
279
+ nn.init.normal_(self.swiglu_up.weight, std=0.02)
280
+ # Zero-init output → safe start for fine-tuning
281
+ nn.init.zeros_(self.output_proj.weight)
282
+ nn.init.zeros_(self.layer_weights)
283
+
284
+ def forward(self, all_hidden_states: Tuple[torch.Tensor, ...]) -> torch.Tensor:
285
+ """
286
+ Args:
287
+ all_hidden_states: Tuple of (num_layers+1) tensors [B, Seq, input_dim].
288
+ Index 0 = embedding, index i+1 = transformer layer i.
289
+
290
+ Returns:
291
+ Transformed features [B, Seq, output_dim]
292
+ """
293
+ # Step 1: Extract selected layers
294
+ selected = [all_hidden_states[i + 1] for i in self.layer_indices]
295
+
296
+ # Step 2: Weighted sum
297
+ weights = F.softmax(self.layer_weights, dim=0)
298
+ merged = torch.zeros_like(selected[0])
299
+ for w, h in zip(weights, selected):
300
+ merged = merged + w * h
301
+
302
+ # Step 3: Normalise
303
+ merged = self.norm(merged)
304
+
305
+ # Step 4: SwiGLU
306
+ gate = F.silu(self.swiglu_gate(merged))
307
+ up = self.swiglu_up(merged)
308
+ hidden = gate * up
309
+
310
+ # Step 5: Project
311
+ return self.output_proj(hidden)
312
+
313
+ def extra_repr(self) -> str:
314
+ return (
315
+ f"input_dim={self.input_dim}, output_dim={self.output_dim}, "
316
+ f"layers={self.layer_indices}"
317
+ )
318
+
319
+
320
+ print("✅ Surgery Module class defined")
321
+
322
+
323
+ # ============================================================================
324
+ # SECTION 4: Surgery Functions
325
+ # ============================================================================
326
+
327
+ def create_qwen3_config_for_surgery() -> "Qwen3Config":
328
+ """Create a Qwen3Config with the correct parameters for surgery."""
329
+ from transformers import Qwen3Config
330
+
331
+ return Qwen3Config(
332
+ hidden_size=QWEN3_HIDDEN_SIZE,
333
+ num_hidden_layers=QWEN3_NUM_LAYERS,
334
+ num_attention_heads=32,
335
+ num_key_value_heads=8,
336
+ intermediate_size=9728,
337
+ hidden_act="silu",
338
+ max_position_embeddings=262144,
339
+ max_window_layers=36,
340
+ rms_norm_eps=1e-6,
341
+ vocab_size=QWEN3_VOCAB_SIZE,
342
+ tie_word_embeddings=True,
343
+ rope_theta=5000000,
344
+ head_dim=128,
345
+ torch_dtype="float16",
346
+ _attn_implementation=ATTN_IMPL,
347
+ )
348
+
349
+
350
+ def perform_surgery(
351
+ vibevoice_model: VibeVoiceForConditionalGenerationInference,
352
+ qwen3_model,
353
+ surgery_layer_indices: Optional[List[int]] = None,
354
+ dtype: torch.dtype = DTYPE,
355
+ ) -> VibeVoiceForConditionalGenerationInference:
356
+ """
357
+ Perform the complete model surgery on CPU:
358
+ 1. Replace Qwen2.5-7B language model with Qwen3-4B
359
+ 2. Replace acoustic & semantic connectors for new hidden size
360
+ 3. Replace lm_head for new vocab size
361
+ 4. Add Surgery Module
362
+ 5. Patch forward methods
363
+ 6. Update config
364
+
365
+ Args:
366
+ vibevoice_model: Original VibeVoice 7B model (loaded on CPU)
367
+ qwen3_model: Loaded Qwen3-4B model (loaded on CPU)
368
+ surgery_layer_indices: Which Qwen3 layers to extract
369
+ dtype: Target dtype (float16 for T4)
370
+
371
+ Returns:
372
+ Modified VibeVoice model with surgery applied
373
+ """
374
+ if surgery_layer_indices is None:
375
+ surgery_layer_indices = SURGERY_LAYER_INDICES
376
+
377
+ print("\n" + "=" * 64)
378
+ print(" PERFORMING MODEL SURGERY (on CPU)")
379
+ print("=" * 64)
380
+
381
+ # ── Step 1: Replace Language Model ──
382
+ print("\n[1/6] Replacing language model: Qwen2.5-7B → Qwen3-4B...")
383
+ qwen3_base = qwen3_model.model # Qwen3Model (without lm_head)
384
+
385
+ old_lm = vibevoice_model.model.language_model
386
+ del old_lm
387
+ vibevoice_model.model.language_model = qwen3_base
388
+ print(f" ✓ Language model replaced ({QWEN3_HIDDEN_SIZE}-dim, {QWEN3_NUM_LAYERS} layers)")
389
+
390
+ # ── Step 2: Replace Acoustic Connector ──
391
+ print("\n[2/6] Replacing acoustic connector...")
392
+ old_acoustic = vibevoice_model.model.acoustic_connector
393
+ del old_acoustic
394
+ vibevoice_model.model.acoustic_connector = SpeechConnector(
395
+ input_dim=vibevoice_model.config.acoustic_vae_dim, # 64
396
+ output_dim=QWEN3_HIDDEN_SIZE, # 2560
397
+ ).to(dtype=dtype)
398
+ print(f" ✓ Acoustic connector: 64 → {QWEN3_HIDDEN_SIZE}")
399
+
400
+ # ── Step 3: Replace Semantic Connector ──
401
+ print("\n[3/6] Replacing semantic connector...")
402
+ old_semantic = vibevoice_model.model.semantic_connector
403
+ del old_semantic
404
+ vibevoice_model.model.semantic_connector = SpeechConnector(
405
+ input_dim=vibevoice_model.config.semantic_vae_dim, # 128
406
+ output_dim=QWEN3_HIDDEN_SIZE, # 2560
407
+ ).to(dtype=dtype)
408
+ print(f" ✓ Semantic connector: 128 → {QWEN3_HIDDEN_SIZE}")
409
+
410
+ # ── Step 4: Replace LM Head ──
411
+ print("\n[4/6] Replacing LM head...")
412
+ old_head = vibevoice_model.lm_head
413
+ del old_head
414
+ vibevoice_model.lm_head = nn.Linear(
415
+ QWEN3_HIDDEN_SIZE, QWEN3_VOCAB_SIZE, bias=False
416
+ ).to(dtype=dtype)
417
+
418
+ # Tie weights (Qwen3 uses tie_word_embeddings=True)
419
+ if hasattr(vibevoice_model.model.language_model, "embed_tokens"):
420
+ vibevoice_model.lm_head.weight = vibevoice_model.model.language_model.embed_tokens.weight
421
+ print(" ✓ LM head weights tied to embed_tokens")
422
+ print(f" ✓ LM head: {QWEN3_HIDDEN_SIZE} → {QWEN3_VOCAB_SIZE}")
423
+
424
+ # ── Step 5: Add Surgery Module ──
425
+ print("\n[5/6] Adding Surgery Module...")
426
+ surgery_module = Qwen3SurgeryModule(
427
+ input_dim=QWEN3_HIDDEN_SIZE,
428
+ output_dim=DIFFUSION_HIDDEN_SIZE,
429
+ layer_indices=surgery_layer_indices,
430
+ rms_norm_eps=1e-6,
431
+ ).to(dtype=dtype)
432
+ vibevoice_model.model.surgery_module = surgery_module
433
+
434
+ surgery_params = sum(p.numel() for p in surgery_module.parameters())
435
+ print(f" ✓ Surgery Module: {surgery_params:,} parameters")
436
+ print(f" ✓ Pipeline: layers{surgery_layer_indices} → WeightedSum → "
437
+ f"RMSNorm → SwiGLU → Linear({QWEN3_HIDDEN_SIZE}→{DIFFUSION_HIDDEN_SIZE})")
438
+
439
+ # ── Step 6: Patch Forward Methods ──
440
+ print("\n[6/6] Patching forward & generate methods...")
441
+ _patch_base_model_forward(vibevoice_model.model)
442
+ _patch_inference_forward(vibevoice_model)
443
+ _patch_generate_method(vibevoice_model)
444
+
445
+ # ── Update Config ──
446
+ print("\n[Extra] Updating model config...")
447
+ _update_config_for_qwen3(vibevoice_model)
448
+
449
+ # ── Verify Diffusion Head untouched ──
450
+ print("\n[Verify] Diffusion Head (should be unchanged):")
451
+ dh = vibevoice_model.model.prediction_head
452
+ print(f" cond_proj: {dh.cond_proj.weight.shape}")
453
+ print(f" noisy_images_proj: {dh.noisy_images_proj.weight.shape}")
454
+ print(f" hidden_size: {dh.config.hidden_size}")
455
+
456
+ print("\n" + "=" * 64)
457
+ print(" SURGERY COMPLETE!")
458
+ print("=" * 64)
459
+
460
+ return vibevoice_model
461
+
462
+
463
+ def _update_config_for_qwen3(model):
464
+ """Update the model's config to reflect Qwen3 decoder dimensions."""
465
+ qwen3_config = create_qwen3_config_for_surgery()
466
+ model.config.decoder_config = qwen3_config
467
+
468
+ # Also set tie_word_embeddings at the top level for the inference class's tie_weights
469
+ model.config.tie_word_embeddings = True
470
+
471
+
472
+ def _patch_base_model_forward(model: VibeVoiceModel):
473
+ """
474
+ Patch VibeVoiceModel.forward to always return hidden_states.
475
+ The Surgery Module needs access to intermediate layer hidden states.
476
+ """
477
+ original_forward = model.forward
478
+
479
+ @functools.wraps(original_forward)
480
+ def patched_forward(
481
+ self,
482
+ input_ids=None,
483
+ attention_mask=None,
484
+ position_ids=None,
485
+ past_key_values=None,
486
+ inputs_embeds=None,
487
+ use_cache=None,
488
+ output_attentions=None,
489
+ output_hidden_states=None, # Will be forced True
490
+ return_dict=None,
491
+ cache_position=None,
492
+ **kwargs,
493
+ ):
494
+ return original_forward(
495
+ input_ids=input_ids,
496
+ attention_mask=attention_mask,
497
+ position_ids=position_ids,
498
+ past_key_values=past_key_values,
499
+ inputs_embeds=inputs_embeds,
500
+ use_cache=use_cache,
501
+ output_attentions=output_attentions,
502
+ output_hidden_states=True, # Always True for Surgery Module
503
+ return_dict=return_dict,
504
+ cache_position=cache_position,
505
+ **kwargs,
506
+ )
507
+
508
+ model.forward = types.MethodType(patched_forward, model)
509
+ print(" ✓ Base model forward patched (output_hidden_states=True)")
510
+
511
+
512
+ def _patch_inference_forward(model: VibeVoiceForConditionalGenerationInference):
513
+ """
514
+ Patch the inference forward to:
515
+ 1. Force output_hidden_states=True
516
+ 2. Include hidden_states in the return value (needed by surgery module)
517
+ """
518
+ original_forward = model.__class__.forward
519
+
520
+ def patched_forward(
521
+ self,
522
+ input_ids=None,
523
+ attention_mask=None,
524
+ position_ids=None,
525
+ past_key_values=None,
526
+ inputs_embeds=None,
527
+ labels=None,
528
+ use_cache=None,
529
+ output_attentions=None,
530
+ output_hidden_states=None,
531
+ return_dict=None,
532
+ cache_position=None,
533
+ speech_tensors=None,
534
+ speech_masks=None,
535
+ speech_input_mask=None,
536
+ logits_to_keep=0,
537
+ **kwargs,
538
+ ):
539
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
540
+
541
+ # Get embeddings
542
+ if inputs_embeds is None:
543
+ inputs_embeds = self.model.get_input_embeddings()(input_ids)
544
+
545
+ # Process speech inputs
546
+ if speech_tensors is not None and speech_masks is not None:
547
+ acoustic_features, speech_embeds = self._process_speech_inputs(
548
+ speech_tensors.to(self.dtype), speech_masks
549
+ )
550
+ if speech_input_mask is not None:
551
+ inputs_embeds[speech_input_mask] = speech_embeds
552
+
553
+ # Always output hidden states for Surgery Module
554
+ outputs = self.model(
555
+ inputs_embeds=inputs_embeds,
556
+ attention_mask=attention_mask,
557
+ position_ids=position_ids,
558
+ past_key_values=past_key_values,
559
+ use_cache=use_cache,
560
+ output_attentions=output_attentions,
561
+ output_hidden_states=True, # Always True!
562
+ return_dict=return_dict,
563
+ cache_position=cache_position,
564
+ **kwargs,
565
+ )
566
+
567
+ hidden_states = outputs[0] if not return_dict else outputs.last_hidden_state
568
+ slice_indices = (
569
+ slice(-logits_to_keep, None)
570
+ if isinstance(logits_to_keep, int)
571
+ else logits_to_keep
572
+ )
573
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
574
+
575
+ if labels is not None:
576
+ raise NotImplementedError("Loss computation not implemented in surgery version.")
577
+
578
+ # KEY CHANGE: Include hidden_states in the output
579
+ return VibeVoiceCausalLMOutputWithPast(
580
+ logits=logits,
581
+ past_key_values=outputs.past_key_values,
582
+ last_hidden_state=hidden_states,
583
+ hidden_states=outputs.hidden_states, # ← All layer hidden states
584
+ attentions=outputs.attentions,
585
+ )
586
+
587
+ model.forward = types.MethodType(patched_forward, model)
588
+ print(" ✓ Inference forward patched (includes hidden_states)")
589
+
590
+
591
+ def _patch_generate_method(model: VibeVoiceForConditionalGenerationInference):
592
+ """
593
+ Patch generate to use the Surgery Module for conditioning.
594
+
595
+ Key changes vs. original generate:
596
+ 1. Forward calls use output_hidden_states=True
597
+ 2. Conditioning uses Surgery Module instead of last_hidden_state
598
+ 3. Device-aware surgery module calls for multi-GPU
599
+ """
600
+ from tqdm import tqdm
601
+ from transformers.generation import GenerationConfig, LogitsProcessorList, StoppingCriteriaList
602
+
603
+ def patched_generate(
604
+ self,
605
+ inputs=None,
606
+ generation_config=None,
607
+ logits_processor=None,
608
+ stopping_criteria=None,
609
+ prefix_allowed_tokens_fn=None,
610
+ synced_gpus=None,
611
+ assistant_model=None,
612
+ audio_streamer=None,
613
+ negative_prompt_ids=None,
614
+ negative_prompt_attention_mask=None,
615
+ speech_tensors=None,
616
+ speech_masks=None,
617
+ speech_input_mask=None,
618
+ return_speech=True,
619
+ cfg_scale=1.0,
620
+ stop_check_fn=None,
621
+ **kwargs,
622
+ ):
623
+ """Modified generate that uses Surgery Module for conditioning."""
624
+ # ── Setup ──
625
+ tokenizer = kwargs.pop("tokenizer", None)
626
+ parsed_scripts = kwargs.pop("parsed_scripts", None)
627
+ all_speakers_list = kwargs.pop("all_speakers_list", None)
628
+ max_length_times = kwargs.pop("max_length_times", 2)
629
+
630
+ if kwargs.get("max_new_tokens", None) is None:
631
+ kwargs["max_new_tokens"] = (
632
+ self.config.decoder_config.max_position_embeddings
633
+ - kwargs["input_ids"].shape[-1]
634
+ )
635
+
636
+ (
637
+ generation_config, model_kwargs, input_ids,
638
+ logits_processor, stopping_criteria,
639
+ ) = self._build_generate_config_model_kwargs(
640
+ generation_config, inputs, tokenizer,
641
+ return_processors=True, **kwargs,
642
+ )
643
+
644
+ negative_kwargs = {
645
+ "input_ids": torch.full(
646
+ (kwargs["input_ids"].shape[0], 1),
647
+ tokenizer.speech_start_id,
648
+ dtype=torch.long, device=kwargs["input_ids"].device,
649
+ ),
650
+ "attention_mask": torch.ones(
651
+ (kwargs["input_ids"].shape[0], 1),
652
+ dtype=torch.long, device=kwargs["input_ids"].device,
653
+ ),
654
+ "max_new_tokens": kwargs.get("max_new_tokens", 100),
655
+ }
656
+ negative_generation_config, negative_model_kwargs, negative_input_ids = (
657
+ self._build_generate_config_model_kwargs(
658
+ None, None, tokenizer,
659
+ return_processors=False, **negative_kwargs,
660
+ )
661
+ )
662
+
663
+ acoustic_cache = VibeVoiceTokenizerStreamingCache()
664
+ semantic_cache = VibeVoiceTokenizerStreamingCache()
665
+
666
+ batch_size = input_ids.shape[0]
667
+ device = input_ids.device
668
+ finished_tags = torch.zeros(batch_size, dtype=torch.bool, device=device)
669
+ correct_cnt = torch.zeros(batch_size, dtype=torch.long, device=device)
670
+ is_prefill = True
671
+ inputs_embeds = None
672
+ verbose = kwargs.get("verbose", False)
673
+
674
+ audio_chunks = [[] for _ in range(batch_size)]
675
+
676
+ initial_length = input_ids.shape[-1]
677
+ initial_length_per_sample = model_kwargs["attention_mask"].sum(dim=-1)
678
+
679
+ valid_tokens = [
680
+ generation_config.speech_start_id,
681
+ generation_config.speech_end_id,
682
+ generation_config.speech_diffusion_id,
683
+ generation_config.eos_token_id,
684
+ ]
685
+ if hasattr(generation_config, "bos_token_id") and generation_config.bos_token_id is not None:
686
+ valid_tokens.append(generation_config.bos_token_id)
687
+
688
+ token_constraint_processor = VibeVoiceTokenConstraintProcessor(valid_tokens, device=device)
689
+ if logits_processor is None:
690
+ logits_processor = LogitsProcessorList()
691
+ logits_processor.append(token_constraint_processor)
692
+
693
+ max_steps = min(
694
+ generation_config.max_length - initial_length,
695
+ int(max_length_times * initial_length),
696
+ )
697
+ max_step_per_sample = torch.minimum(
698
+ generation_config.max_length - initial_length_per_sample,
699
+ (max_length_times * initial_length_per_sample).long(),
700
+ )
701
+ reach_max_step_sample = torch.zeros(batch_size, dtype=torch.bool, device=device)
702
+
703
+ progress_bar = (
704
+ tqdm(range(max_steps), desc="Generating", leave=False)
705
+ if kwargs.get("show_progress_bar", True)
706
+ else range(max_steps)
707
+ )
708
+
709
+ # Device resolution for multi-GPU compatibility
710
+ # acoustic_tokenizer and semantic_tokenizer may live on different GPUs
711
+ acoustic_device = next(self.model.acoustic_tokenizer.parameters()).device
712
+ semantic_device = next(self.model.semantic_tokenizer.parameters()).device
713
+ acoustic_connect_device = next(self.model.acoustic_connector.parameters()).device
714
+ semantic_connect_device = next(self.model.semantic_connector.parameters()).device
715
+
716
+ # Helper: run surgery module with correct device placement
717
+ # Optimization: only pass last token since we only need surgery_out[:, -1, :]
718
+ def _run_surgery(hidden_states_tuple):
719
+ """Run surgery module on last token only, handling multi-GPU placement."""
720
+ surgery_mod = self.model.surgery_module
721
+ surgery_device = next(surgery_mod.parameters()).device
722
+ # Slice to last token only — avoids O(N²) on full sequence
723
+ # Each hidden_state is [B, Seq, D], we take [:, -1:, :] → [B, 1, D]
724
+ selected = tuple(h[:, -1:, :] for h in hidden_states_tuple)
725
+ if selected[0].device != surgery_device:
726
+ selected = tuple(h.to(surgery_device) for h in selected)
727
+ return surgery_mod(selected)
728
+
729
+ # ── Generation Loop ──
730
+ for step in progress_bar:
731
+ if stop_check_fn is not None and stop_check_fn():
732
+ if verbose:
733
+ print(f"Generation stopped externally at step {step + 1}")
734
+ if audio_streamer is not None:
735
+ audio_streamer.end()
736
+ break
737
+
738
+ if audio_streamer is not None and hasattr(audio_streamer, "finished_flags"):
739
+ if any(audio_streamer.finished_flags):
740
+ if verbose:
741
+ print(f"Audio generation stopped externally at step {step + 1}")
742
+ break
743
+
744
+ if finished_tags.all():
745
+ if hasattr(progress_bar, "set_description"):
746
+ progress_bar.set_description("Generation complete")
747
+ break
748
+
749
+ if input_ids.shape[-1] >= generation_config.max_length:
750
+ print(f"Reached max generation length {generation_config.max_length}")
751
+ reached = torch.arange(batch_size, device=device)[~finished_tags]
752
+ if reached.numel() > 0:
753
+ reach_max_step_sample[reached] = True
754
+ break
755
+
756
+ if hasattr(progress_bar, "set_description"):
757
+ active = (~finished_tags).sum().item()
758
+ progress_bar.set_description(f"Generating (active: {active}/{batch_size})")
759
+
760
+ model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
761
+ if is_prefill:
762
+ prefill_inputs = {
763
+ "speech_tensors": speech_tensors.to(device=device),
764
+ "speech_masks": speech_masks.to(device),
765
+ "speech_input_mask": speech_input_mask.to(device),
766
+ }
767
+ is_prefill = False
768
+ else:
769
+ _ = model_inputs.pop("inputs_embeds", None)
770
+ prefill_inputs = {"inputs_embeds": inputs_embeds}
771
+
772
+ # Forward (output_hidden_states=True is handled by patched forward)
773
+ outputs = self(
774
+ **model_inputs, **prefill_inputs,
775
+ logits_to_keep=1, return_dict=True,
776
+ output_attentions=False, output_hidden_states=True,
777
+ )
778
+ model_kwargs = self._update_model_kwargs_for_generation(
779
+ outputs, model_kwargs, is_encoder_decoder=False,
780
+ )
781
+
782
+ next_token_logits = outputs.logits[:, -1, :].to(
783
+ copy=True, dtype=torch.float32, device=input_ids.device,
784
+ )
785
+ next_token_scores = logits_processor(input_ids, next_token_logits)
786
+
787
+ if generation_config.do_sample:
788
+ probs = nn.functional.softmax(next_token_scores, dim=-1)
789
+ next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
790
+ else:
791
+ next_tokens = torch.argmax(next_token_scores, dim=-1)
792
+
793
+ next_tokens[finished_tags] = generation_config.eos_token_id
794
+ input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
795
+
796
+ # Negative prompt update (non-refresh mode)
797
+ if not kwargs.get("refresh_negative", True):
798
+ negative_model_inputs = self.prepare_inputs_for_generation(
799
+ negative_input_ids, **negative_model_kwargs
800
+ )
801
+ if negative_model_inputs["inputs_embeds"] is None and inputs_embeds is not None:
802
+ negative_model_inputs["inputs_embeds"] = inputs_embeds
803
+ negative_model_inputs["input_ids"] = None
804
+
805
+ negative_outputs = self(
806
+ **negative_model_inputs,
807
+ logits_to_keep=0, return_dict=True,
808
+ output_attentions=False, output_hidden_states=True,
809
+ )
810
+ negative_model_kwargs = self._update_model_kwargs_for_generation(
811
+ negative_outputs, negative_model_kwargs, is_encoder_decoder=False,
812
+ )
813
+ negative_input_ids = torch.cat(
814
+ [negative_input_ids, next_tokens[:, None]], dim=-1
815
+ )
816
+
817
+ # EOS handling
818
+ if (next_tokens == generation_config.eos_token_id).any():
819
+ eos_indices = (
820
+ (next_tokens == generation_config.eos_token_id)
821
+ .nonzero(as_tuple=False).squeeze(1)
822
+ )
823
+ new_eos = eos_indices[~finished_tags[eos_indices]]
824
+ if new_eos.numel() > 0:
825
+ finished_tags[new_eos] = True
826
+ if verbose:
827
+ print(f"Samples {new_eos.tolist()} reached EOS at step {step+1}.", flush=True)
828
+ if audio_streamer is not None:
829
+ audio_streamer.end(new_eos)
830
+
831
+ # Max length handling
832
+ max_reached = step >= max_step_per_sample
833
+ new_max = torch.nonzero(max_reached & ~finished_tags, as_tuple=False).squeeze(1)
834
+ if new_max.numel() > 0:
835
+ finished_tags[new_max] = True
836
+ reach_max_step_sample[new_max] = True
837
+ if verbose:
838
+ print(f"Samples {new_max.tolist()} reached max length at step {step+1}.", flush=True)
839
+ if audio_streamer is not None:
840
+ audio_streamer.end(new_max)
841
+
842
+ # speech_end
843
+ diffusion_end = (
844
+ (next_tokens == generation_config.speech_end_id)
845
+ .nonzero(as_tuple=False).squeeze(1)
846
+ )
847
+ if diffusion_end.numel() > 0:
848
+ acoustic_cache.set_to_zero(diffusion_end)
849
+ semantic_cache.set_to_zero(diffusion_end)
850
+
851
+ # speech_begin — update negative prompt cache
852
+ diffusion_start = torch.arange(batch_size, device=device)[
853
+ ~finished_tags & (next_tokens == generation_config.speech_start_id)
854
+ ]
855
+ if diffusion_start.numel() > 0 and kwargs.get("refresh_negative", True):
856
+ for idx in diffusion_start.tolist():
857
+ negative_model_kwargs["attention_mask"][idx, :] = 0
858
+ negative_model_kwargs["attention_mask"][idx, -1] = 1
859
+ for k_cache, v_cache in zip(
860
+ negative_model_kwargs["past_key_values"].key_cache,
861
+ negative_model_kwargs["past_key_values"].value_cache,
862
+ ):
863
+ for idx in diffusion_start.tolist():
864
+ k_cache[idx, :, -1, :] = k_cache[idx, :, 0, :].clone()
865
+ v_cache[idx, :, -1, :] = v_cache[idx, :, 0, :].clone()
866
+ for idx in diffusion_start.tolist():
867
+ negative_input_ids[idx, -1] = generation_config.speech_start_id
868
+
869
+ # Prepare next embeddings
870
+ next_inputs_embeds = self.model.get_input_embeddings()(next_tokens).unsqueeze(1)
871
+
872
+ # ── Diffusion forward ──
873
+ diffusion_indices = torch.arange(batch_size, device=device)[
874
+ ~finished_tags & (next_tokens == generation_config.speech_diffusion_id)
875
+ ]
876
+
877
+ if diffusion_indices.numel() > 0:
878
+ # Negative pass for diffusion
879
+ if kwargs.get("refresh_negative", True):
880
+ negative_model_inputs = self.prepare_inputs_for_generation(
881
+ negative_input_ids, **negative_model_kwargs
882
+ )
883
+ if negative_model_inputs["inputs_embeds"] is None and inputs_embeds is not None:
884
+ negative_model_inputs["inputs_embeds"] = inputs_embeds
885
+ negative_model_inputs["input_ids"] = None
886
+
887
+ negative_outputs = self(
888
+ **negative_model_inputs,
889
+ logits_to_keep=0, return_dict=True,
890
+ output_attentions=False, output_hidden_states=True,
891
+ )
892
+ negative_model_kwargs = self._update_model_kwargs_for_generation(
893
+ negative_outputs, negative_model_kwargs, is_encoder_decoder=False,
894
+ )
895
+ negative_input_ids = torch.cat(
896
+ [negative_input_ids, next_tokens[:, None]], dim=-1
897
+ )
898
+
899
+ # Correct non-diffusion samples' KV cache
900
+ non_diff_mask = ~finished_tags & (next_tokens != generation_config.speech_diffusion_id)
901
+ if non_diff_mask.any():
902
+ non_diff_idx = torch.arange(batch_size, device=device)[non_diff_mask]
903
+ starts = correct_cnt[non_diff_idx]
904
+
905
+ seq_len = negative_model_kwargs["attention_mask"].shape[1]
906
+ for i, (s_idx, s_start) in enumerate(
907
+ zip(non_diff_idx.tolist(), starts.tolist())
908
+ ):
909
+ if s_start + 1 < seq_len - 1:
910
+ negative_model_kwargs["attention_mask"][s_idx, s_start+1:] = \
911
+ negative_model_kwargs["attention_mask"][s_idx, s_start:-1].clone()
912
+ negative_model_kwargs["attention_mask"][s_idx, s_start] = 0
913
+
914
+ for k_cache, v_cache in zip(
915
+ negative_model_kwargs["past_key_values"].key_cache,
916
+ negative_model_kwargs["past_key_values"].value_cache,
917
+ ):
918
+ for s_idx, s_start in zip(non_diff_idx.tolist(), starts.tolist()):
919
+ if s_start + 1 < k_cache.shape[2] - 1:
920
+ k_cache[s_idx, :, s_start+1:, :] = \
921
+ k_cache[s_idx, :, s_start:-1, :].clone()
922
+ v_cache[s_idx, :, s_start+1:, :] = \
923
+ v_cache[s_idx, :, s_start:-1, :].clone()
924
+
925
+ for s_idx, s_start in zip(non_diff_idx.tolist(), starts.tolist()):
926
+ if s_start + 1 < negative_input_ids.shape[1] - 1:
927
+ negative_input_ids[s_idx, s_start+1:] = \
928
+ negative_input_ids[s_idx, s_start:-1].clone()
929
+
930
+ correct_cnt[non_diff_idx] += 1
931
+
932
+ # ── SURGERY: Use Surgery Module for conditioning ──
933
+ # Original code used: outputs.last_hidden_state[:, -1, :]
934
+ # Now we transform ALL hidden states through the Surgery Module
935
+ surgery_out = _run_surgery(outputs.hidden_states) # [B, Seq, 3584]
936
+ positive_condition = surgery_out[:, -1, :][diffusion_indices]
937
+
938
+ neg_surgery_out = _run_surgery(negative_outputs.hidden_states)
939
+ negative_condition = neg_surgery_out[:, -1, :][diffusion_indices]
940
+
941
+ speech_latent = self.sample_speech_tokens(
942
+ positive_condition,
943
+ negative_condition,
944
+ cfg_scale=cfg_scale,
945
+ ).unsqueeze(1)
946
+
947
+ # Decode acoustic latent to audio
948
+ scaled_latent = (
949
+ speech_latent
950
+ / self.model.speech_scaling_factor.to(speech_latent.device)
951
+ - self.model.speech_bias_factor.to(speech_latent.device)
952
+ )
953
+ audio_chunk = self.model.acoustic_tokenizer.decode(
954
+ scaled_latent.to(self.model.acoustic_tokenizer.device),
955
+ cache=acoustic_cache,
956
+ sample_indices=diffusion_indices.to(self.model.acoustic_tokenizer.device),
957
+ use_cache=True,
958
+ debug=False,
959
+ )
960
+
961
+ for i, s_idx in enumerate(diffusion_indices):
962
+ idx = s_idx.item()
963
+ if not finished_tags[idx]:
964
+ audio_chunks[idx].append(audio_chunk[i])
965
+
966
+ if audio_streamer is not None:
967
+ audio_streamer.put(audio_chunk, diffusion_indices)
968
+
969
+ semantic_features = self.model.semantic_tokenizer.encode(
970
+ audio_chunk,
971
+ cache=semantic_cache,
972
+ sample_indices=diffusion_indices,
973
+ use_cache=True,
974
+ debug=False,
975
+ ).mean
976
+
977
+ acoustic_embed = self.model.acoustic_connector(
978
+ speech_latent.to(acoustic_connect_device)
979
+ ).to(device)
980
+ semantic_embed = self.model.semantic_connector(
981
+ semantic_features.to(semantic_connect_device)
982
+ ).to(device)
983
+ diffusion_embeds = acoustic_embed + semantic_embed
984
+
985
+ next_inputs_embeds[diffusion_indices] = diffusion_embeds
986
+
987
+ inputs_embeds = next_inputs_embeds
988
+
989
+ if audio_streamer is not None:
990
+ audio_streamer.end()
991
+
992
+ # Concatenate audio chunks
993
+ final_audio_outputs = []
994
+ for sample_chunks in audio_chunks:
995
+ if sample_chunks:
996
+ final_audio_outputs.append(torch.cat(sample_chunks, dim=-1))
997
+ else:
998
+ final_audio_outputs.append(None)
999
+
1000
+ return VibeVoiceGenerationOutput(
1001
+ sequences=input_ids,
1002
+ speech_outputs=final_audio_outputs if return_speech else None,
1003
+ reach_max_step_sample=reach_max_step_sample,
1004
+ )
1005
+
1006
+ model.generate = types.MethodType(patched_generate, model)
1007
+ print(" ✓ Generate method patched (Surgery Module integrated)")
1008
+
1009
+
1010
+ # ============================================================================
1011
+ # SECTION 5: Custom Model Class for Save/Load
1012
+ # ============================================================================
1013
+
1014
+ class VibeVoiceSurgeryModel(VibeVoiceForConditionalGenerationInference):
1015
+ """
1016
+ Extended VibeVoice inference model that includes the Surgery Module
1017
+ in its __init__, so from_pretrained can load surgery weights correctly.
1018
+ """
1019
+
1020
+ def __init__(self, config):
1021
+ super().__init__(config)
1022
+ # Add surgery module if config includes it
1023
+ if hasattr(config, "surgery_module_config"):
1024
+ sc = config.surgery_module_config
1025
+ self.model.surgery_module = Qwen3SurgeryModule(
1026
+ input_dim=sc.get("input_dim", QWEN3_HIDDEN_SIZE),
1027
+ output_dim=sc.get("output_dim", DIFFUSION_HIDDEN_SIZE),
1028
+ layer_indices=sc.get("layer_indices", SURGERY_LAYER_INDICES),
1029
+ rms_norm_eps=sc.get("rms_norm_eps", 1e-6),
1030
+ )
1031
+
1032
+
1033
+ # Register with AutoModel so from_pretrained works
1034
+ AutoModelForCausalLM.register(VibeVoiceConfig, VibeVoiceSurgeryModel)
1035
+
1036
+
1037
+ # ============================================================================
1038
+ # SECTION 6: Memory Estimation
1039
+ # ============================================================================
1040
+
1041
+ def estimate_memory():
1042
+ """Print memory estimates for the surgery process."""
1043
+ bytes_per_param = 2 # float16
1044
+
1045
+ qwen3_gb = QWEN3_NUM_LAYERS * 0.22 # rough estimate ~8GB
1046
+ vibevoice_total_gb = 14.0 # ~7B params in fp16
1047
+ vibevoice_excl_lm_gb = 3.0 # diffusion head + tokenizers + connectors
1048
+ surgery_gb = 0.05 # ~25M params
1049
+
1050
+ final_model_gb = qwen3_gb + vibevoice_excl_lm_gb + surgery_gb
1051
+ during_surgery_gb = vibevoice_total_gb + qwen3_gb
1052
+
1053
+ print(f"\n📊 Memory Estimates (float16):")
1054
+ print(f" VibeVoice 7B (CPU RAM): ~{vibevoice_total_gb:.1f} GB")
1055
+ print(f" Qwen3-4B (CPU RAM): ~{qwen3_gb:.1f} GB")
1056
+ print(f" During surgery (CPU RAM): ~{during_surgery_gb:.1f} GB")
1057
+ print(f" Final model (VRAM): ~{final_model_gb:.1f} GB")
1058
+ print(f" Kaggle CPU RAM available: ~30 GB")
1059
+ print(f" Kaggle GPU VRAM (2×T4): 32 GB total")
1060
+ print(f" ✅ Fits comfortably!")
1061
+
1062
+
1063
+ # ============================================================================
1064
+ # SECTION 7: Main Surgery Pipeline
1065
+ # ============================================================================
1066
+
1067
+ def run_surgery():
1068
+ """
1069
+ Execute the complete surgery pipeline:
1070
+ 1. Load VibeVoice 7B on CPU
1071
+ 2. Load Qwen3-4B on CPU
1072
+ 3. Perform surgery on CPU
1073
+ 4. Save modified model
1074
+ 5. Reload with device_map across 2 T4 GPUs
1075
+ """
1076
+ print("\n" + "█" * 64)
1077
+ print(" VIBEVOICE MODEL SURGERY")
1078
+ print(" Qwen2.5-7B → Qwen3-4B + Surgery Module")
1079
+ print(" Target: Kaggle Dual T4 GPUs")
1080
+ print("█" * 64)
1081
+
1082
+ estimate_memory()
1083
+
1084
+ # ── Step 1: Load VibeVoice 7B on CPU ──
1085
+ print("\n[Step 1/5] Loading VibeVoice 7B on CPU...")
1086
+ gc.collect()
1087
+ torch.cuda.empty_cache()
1088
+
1089
+ try:
1090
+ vibevoice_model = VibeVoiceForConditionalGenerationInference.from_pretrained(
1091
+ VIBEVOICE_MODEL_ID,
1092
+ torch_dtype=DTYPE,
1093
+ device_map="cpu",
1094
+ trust_remote_code=True,
1095
+ )
1096
+ print(f" ✓ VibeVoice 7B loaded on CPU")
1097
+ except Exception as e:
1098
+ print(f" ✗ Failed: {e}")
1099
+ raise
1100
+
1101
+ print(f" Original decoder: {vibevoice_model.config.decoder_config.hidden_size}-dim, "
1102
+ f"{vibevoice_model.config.decoder_config.num_hidden_layers} layers, "
1103
+ f"vocab={vibevoice_model.config.decoder_config.vocab_size}")
1104
+
1105
+ # ── Step 2: Load Qwen3-4B on CPU ──
1106
+ print(f"\n[Step 2/5] Loading {QWEN3_MODEL_ID} on CPU...")
1107
+ gc.collect()
1108
+ torch.cuda.empty_cache()
1109
+
1110
+ try:
1111
+ qwen3_model = AutoModelForCausalLM.from_pretrained(
1112
+ QWEN3_MODEL_ID,
1113
+ torch_dtype=DTYPE,
1114
+ device_map="cpu",
1115
+ trust_remote_code=True,
1116
+ )
1117
+ print(f" ✓ Qwen3-4B loaded on CPU")
1118
+ except Exception as e:
1119
+ print(f" ✗ Failed: {e}")
1120
+ print(f" ℹ Ensure transformers>=4.51.0: pip install 'transformers>=4.51.0'")
1121
+ raise
1122
+
1123
+ # Verify dimensions
1124
+ assert qwen3_model.config.hidden_size == QWEN3_HIDDEN_SIZE
1125
+ assert qwen3_model.config.num_hidden_layers == QWEN3_NUM_LAYERS
1126
+ assert qwen3_model.config.vocab_size == QWEN3_VOCAB_SIZE
1127
+ print(f" Qwen3: {QWEN3_HIDDEN_SIZE}-dim, {QWEN3_NUM_LAYERS} layers, vocab={QWEN3_VOCAB_SIZE}")
1128
+
1129
+ # ── Step 3: Perform Surgery on CPU ──
1130
+ print(f"\n[Step 3/5] Performing surgery on CPU...")
1131
+ modified_model = perform_surgery(
1132
+ vibevoice_model=vibevoice_model,
1133
+ qwen3_model=qwen3_model,
1134
+ surgery_layer_indices=SURGERY_LAYER_INDICES,
1135
+ dtype=DTYPE,
1136
+ )
1137
+
1138
+ # Free Qwen3 model (its weights are now in the modified model)
1139
+ del qwen3_model
1140
+ gc.collect()
1141
+ torch.cuda.empty_cache()
1142
+
1143
+ # ── Step 4: Save Surgery Model ──
1144
+ print(f"\n[Step 4/5] Saving surgery model to {OUTPUT_DIR}...")
1145
+ save_surgery_model(modified_model, OUTPUT_DIR)
1146
+
1147
+ # Free CPU model
1148
+ del modified_model
1149
+ gc.collect()
1150
+ torch.cuda.empty_cache()
1151
+
1152
+ # ── Step 5: Reload with device_map across 2 T4s ──
1153
+ print(f"\n[Step 5/5] Loading with device_map across 2 T4 GPUs...")
1154
+ final_model = load_surgery_model(
1155
+ OUTPUT_DIR,
1156
+ dtype=DTYPE,
1157
+ device_map="auto",
1158
+ )
1159
+
1160
+ # Print summary
1161
+ print_surgery_summary(final_model)
1162
+
1163
+ return final_model
1164
+
1165
+
1166
+ # ============================================================================
1167
+ # SECTION 8: Save & Load Functions
1168
+ # ============================================================================
1169
+
1170
+ def save_surgery_model(model, output_dir: str):
1171
+ """
1172
+ Save the surgery model in a format that can be reloaded correctly.
1173
+
1174
+ Key: We save decoder_config with model_type="qwen2" but Qwen3 parameters.
1175
+ This avoids the VibeVoiceConfig validation issue on reload.
1176
+ The monkey-patch we applied handles qwen3, but for saved configs we use
1177
+ a compatible format.
1178
+ """
1179
+ os.makedirs(output_dir, exist_ok=True)
1180
+ print(f" Saving model weights...")
1181
+ model.save_pretrained(output_dir, safe_serialization=True)
1182
+ print(f" ✓ Model weights saved")
1183
+
1184
+ # Save config with surgery_module_config
1185
+ print(f" Saving config...")
1186
+ config_dict = model.config.to_dict()
1187
+
1188
+ # Save decoder config as qwen3 (our patched VibeVoiceConfig handles it)
1189
+ qwen3_cfg = create_qwen3_config_for_surgery()
1190
+ config_dict["decoder_config"] = qwen3_cfg.to_dict()
1191
+ config_dict["decoder_config"]["model_type"] = "qwen3"
1192
+
1193
+ # Add surgery module config
1194
+ config_dict["surgery_module_config"] = {
1195
+ "input_dim": QWEN3_HIDDEN_SIZE,
1196
+ "output_dim": DIFFUSION_HIDDEN_SIZE,
1197
+ "layer_indices": SURGERY_LAYER_INDICES,
1198
+ "rms_norm_eps": 1e-6,
1199
+ }
1200
+
1201
+ config_path = os.path.join(output_dir, "config.json")
1202
+ with open(config_path, "w") as f:
1203
+ json.dump(config_dict, f, indent=2, default=str)
1204
+ print(f" ✓ Config saved")
1205
+
1206
+ # Save surgery config separately
1207
+ surgery_config_path = os.path.join(output_dir, "surgery_module_config.json")
1208
+ with open(surgery_config_path, "w") as f:
1209
+ json.dump(config_dict["surgery_module_config"], f, indent=2)
1210
+ print(f" ✓ Surgery module config saved")
1211
+
1212
+ # Print file sizes
1213
+ print(f"\n Saved files:")
1214
+ total_size = 0
1215
+ for f_name in sorted(os.listdir(output_dir)):
1216
+ f_path = os.path.join(output_dir, f_name)
1217
+ if os.path.isfile(f_path):
1218
+ size_mb = os.path.getsize(f_path) / 1e6
1219
+ total_size += size_mb
1220
+ print(f" {f_name}: {size_mb:.1f} MB")
1221
+ print(f" Total: {total_size:.1f} MB ({total_size/1024:.2f} GB)")
1222
+ print(f" ✓ Saved to {output_dir}")
1223
+
1224
+
1225
+ def load_surgery_model(
1226
+ model_path: str,
1227
+ dtype: torch.dtype = DTYPE,
1228
+ device_map: str = "auto",
1229
+ ):
1230
+ """
1231
+ Load a previously saved surgery model.
1232
+
1233
+ Uses VibeVoiceSurgeryModel (custom class) so that from_pretrained
1234
+ creates the surgery_module before loading weights.
1235
+
1236
+ Also applies the runtime forward/generate patches.
1237
+
1238
+ Fix: When device_map="auto", the auto-generated device map misses
1239
+ registered buffers (speech_scaling_factor, speech_bias_factor) that
1240
+ live directly on VibeVoiceModel. We manually add those entries.
1241
+ """
1242
+ print(f"\n Loading surgery model from {model_path}...")
1243
+
1244
+ # Ensure config patch is applied (in case this is called standalone)
1245
+ _patch_vibevoice_config_for_qwen3()
1246
+
1247
+ # Load config to get surgery_module_config
1248
+ config_path = os.path.join(model_path, "config.json")
1249
+ with open(config_path, "r") as f:
1250
+ config_dict = json.load(f)
1251
+
1252
+ # Create config using our patched VibeVoiceConfig
1253
+ config = VibeVoiceConfig(**config_dict)
1254
+
1255
+ # ── Fix device_map for registered buffers ──
1256
+ if device_map == "auto":
1257
+ from accelerate import infer_auto_device_map, get_max_memory
1258
+
1259
+ print(" Computing device map for multi-GPU placement...")
1260
+ max_memory = get_max_memory()
1261
+
1262
+ # Build a meta-device model to infer the device map structure
1263
+ with torch.device("meta"):
1264
+ meta_model = VibeVoiceSurgeryModel(config)
1265
+
1266
+ no_split = [
1267
+ "VibeVoiceDiffusionHead",
1268
+ "VibeVoiceAcousticTokenizerModel",
1269
+ "VibeVoiceSemanticTokenizerModel",
1270
+ "Qwen3SurgeryModule",
1271
+ ]
1272
+
1273
+ device_map_dict = infer_auto_device_map(
1274
+ meta_model,
1275
+ max_memory=max_memory,
1276
+ no_split_module_classes=no_split,
1277
+ )
1278
+
1279
+ # Determine which device to place the buffers on
1280
+ buffer_device = device_map_dict.get(
1281
+ "model.language_model",
1282
+ device_map_dict.get("model", "cuda:0"),
1283
+ )
1284
+
1285
+ # Add entries for registered buffers that are direct children of model
1286
+ for key in ["model.speech_scaling_factor", "model.speech_bias_factor"]:
1287
+ if key not in device_map_dict:
1288
+ device_map_dict[key] = buffer_device
1289
+ print(f" Added device map entry: {key} → {buffer_device}")
1290
+
1291
+ del meta_model
1292
+ gc.collect()
1293
+ torch.cuda.empty_cache()
1294
+
1295
+ device_map = device_map_dict
1296
+
1297
+ # Load using our custom class that includes surgery_module in __init__
1298
+ model = VibeVoiceSurgeryModel.from_pretrained(
1299
+ model_path,
1300
+ config=config,
1301
+ torch_dtype=dtype,
1302
+ device_map=device_map,
1303
+ trust_remote_code=True,
1304
+ )
1305
+
1306
+ # Verify surgery module
1307
+ if not hasattr(model.model, "surgery_module"):
1308
+ print(" ⚠ Surgery Module not found after loading, adding manually...")
1309
+ sc = config.surgery_module_config
1310
+ model.model.surgery_module = Qwen3SurgeryModule(**sc).to(dtype=dtype)
1311
+ # Try to load surgery weights from the saved state dict
1312
+ surgery_state = {
1313
+ k.replace("model.surgery_module.", ""): v
1314
+ for k, v in torch.load(
1315
+ os.path.join(model_path, "model.safetensors")
1316
+ if os.path.exists(os.path.join(model_path, "model.safetensors"))
1317
+ else os.path.join(model_path, "pytorch_model.bin"),
1318
+ map_location="cpu",
1319
+ ).items()
1320
+ if k.startswith("model.surgery_module.")
1321
+ }
1322
+ if surgery_state:
1323
+ model.model.surgery_module.load_state_dict(surgery_state, strict=False)
1324
+ print(" ✓ Surgery Module weights loaded")
1325
+
1326
+ # Apply runtime patches (not saved with the model)
1327
+ _patch_base_model_forward(model.model)
1328
+ _patch_inference_forward(model)
1329
+ _patch_generate_method(model)
1330
+
1331
+ # Tie weights
1332
+ try:
1333
+ model.tie_weights()
1334
+ except Exception:
1335
+ pass
1336
+
1337
+ print(f" ✓ Surgery model loaded successfully")
1338
+ return model
1339
+
1340
+
1341
+ # ============================================================================
1342
+ # SECTION 9: Verification
1343
+ # ============================================================================
1344
+
1345
+ def verify_surgery(model):
1346
+ """Run verification tests on the modified model."""
1347
+ print("\n" + "─" * 64)
1348
+ print(" VERIFICATION TESTS")
1349
+ print("─" * 64)
1350
+
1351
+ all_passed = True
1352
+
1353
+ # Test 1: Surgery Module exists
1354
+ print("\n[Test 1] Surgery Module exists...")
1355
+ try:
1356
+ assert hasattr(model.model, "surgery_module")
1357
+ sm = model.model.surgery_module
1358
+ assert sm.input_dim == QWEN3_HIDDEN_SIZE
1359
+ assert sm.output_dim == DIFFUSION_HIDDEN_SIZE
1360
+ assert sm.layer_indices == SURGERY_LAYER_INDICES
1361
+ print(" ✓ PASSED")
1362
+ except Exception as e:
1363
+ print(f" ✗ FAILED: {e}")
1364
+ all_passed = False
1365
+
1366
+ # Test 2: Language model is Qwen3
1367
+ print("\n[Test 2] Language model is Qwen3...")
1368
+ try:
1369
+ lm = model.model.language_model
1370
+ assert lm.config.hidden_size == QWEN3_HIDDEN_SIZE
1371
+ assert lm.config.num_hidden_layers == QWEN3_NUM_LAYERS
1372
+ print(f" ✓ PASSED (hidden={QWEN3_HIDDEN_SIZE}, layers={QWEN3_NUM_LAYERS})")
1373
+ except Exception as e:
1374
+ print(f" ✗ FAILED: {e}")
1375
+ all_passed = False
1376
+
1377
+ # Test 3: Connectors
1378
+ print("\n[Test 3] Connector dimensions...")
1379
+ try:
1380
+ ac = model.model.acoustic_connector
1381
+ sc = model.model.semantic_connector
1382
+ assert ac.fc1.out_features == QWEN3_HIDDEN_SIZE
1383
+ assert sc.fc1.out_features == QWEN3_HIDDEN_SIZE
1384
+ print(" ✓ PASSED")
1385
+ except Exception as e:
1386
+ print(f" ✗ FAILED: {e}")
1387
+ all_passed = False
1388
+
1389
+ # Test 4: LM Head
1390
+ print("\n[Test 4] LM Head dimensions...")
1391
+ try:
1392
+ assert model.lm_head.in_features == QWEN3_HIDDEN_SIZE
1393
+ assert model.lm_head.out_features == QWEN3_VOCAB_SIZE
1394
+ print(" ✓ PASSED")
1395
+ except Exception as e:
1396
+ print(f" ✗ FAILED: {e}")
1397
+ all_passed = False
1398
+
1399
+ # Test 5: Diffusion Head unchanged
1400
+ print("\n[Test 5] Diffusion Head (should be 3584)...")
1401
+ try:
1402
+ dh = model.model.prediction_head
1403
+ assert dh.config.hidden_size == DIFFUSION_HIDDEN_SIZE
1404
+ assert dh.cond_proj.weight.shape[0] == DIFFUSION_HIDDEN_SIZE
1405
+ assert dh.cond_proj.weight.shape[1] == DIFFUSION_HIDDEN_SIZE
1406
+ print(" ✓ PASSED")
1407
+ except Exception as e:
1408
+ print(f" ✗ FAILED: {e}")
1409
+ all_passed = False
1410
+
1411
+ # Test 6: Surgery Module forward pass
1412
+ print("\n[Test 6] Surgery Module forward pass...")
1413
+ try:
1414
+ sm = model.model.surgery_module
1415
+ device = next(sm.parameters()).device
1416
+ dtype = next(sm.parameters()).dtype
1417
+ with torch.no_grad():
1418
+ dummy_hs = tuple(
1419
+ torch.randn(1, 10, QWEN3_HIDDEN_SIZE, dtype=dtype, device=device)
1420
+ for _ in range(QWEN3_NUM_LAYERS + 1)
1421
+ )
1422
+ output = sm(dummy_hs)
1423
+ assert output.shape == (1, 10, DIFFUSION_HIDDEN_SIZE)
1424
+ assert not torch.isnan(output).any()
1425
+ assert not torch.isinf(output).any()
1426
+ print(f" ✓ PASSED [1, 10, {QWEN3_HIDDEN_SIZE}] → [1, 10, {DIFFUSION_HIDDEN_SIZE}]")
1427
+ except Exception as e:
1428
+ print(f" ✗ FAILED: {e}")
1429
+ all_passed = False
1430
+
1431
+ # Test 7: Layer weights uniform
1432
+ print("\n[Test 7] Initial layer weights (uniform)...")
1433
+ try:
1434
+ weights = F.softmax(sm.layer_weights, dim=0)
1435
+ expected = torch.full_like(weights, 1.0 / sm.num_layers)
1436
+ assert torch.allclose(weights, expected, atol=1e-6)
1437
+ print(f" ✓ PASSED ({weights.tolist()})")
1438
+ except Exception as e:
1439
+ print(f" ✗ FAILED: {e}")
1440
+ all_passed = False
1441
+
1442
+ # Test 8: Output projection zero-init
1443
+ print("\n[Test 8] Output projection zero-init...")
1444
+ try:
1445
+ assert torch.all(sm.output_proj.weight == 0)
1446
+ print(" ✓ PASSED")
1447
+ except Exception as e:
1448
+ print(f" ✗ FAILED: {e}")
1449
+ all_passed = False
1450
+
1451
+ print("\n" + "─" * 64)
1452
+ if all_passed:
1453
+ print(" ✅ ALL TESTS PASSED!")
1454
+ else:
1455
+ print(" ⚠️ SOME TESTS FAILED — check above")
1456
+ print("─" * 64)
1457
+
1458
+ return all_passed
1459
+
1460
+
1461
+ def print_surgery_summary(model):
1462
+ """Print a comprehensive summary of the surgery model."""
1463
+ print("\n" + "═" * 64)
1464
+ print(" SURGERY SUMMARY")
1465
+ print("═" * 64)
1466
+
1467
+ lm = model.model.language_model
1468
+ lm_params = sum(p.numel() for p in lm.parameters())
1469
+ print(f"\n┌─ Language Model (Qwen3-4B)")
1470
+ print(f"│ Type: {lm.__class__.__name__}")
1471
+ print(f"│ Parameters: {lm_params:,}")
1472
+ print(f"│ Hidden: {model.config.decoder_config.hidden_size}")
1473
+ print(f"│ Layers: {model.config.decoder_config.num_hidden_layers}")
1474
+
1475
+ sm = model.model.surgery_module
1476
+ sm_params = sum(p.numel() for p in sm.parameters())
1477
+ print(f"├─ Surgery Module")
1478
+ print(f"│ Parameters: {sm_params:,}")
1479
+ print(f"│ {sm.extra_repr()}")
1480
+
1481
+ ac_params = sum(p.numel() for p in model.model.acoustic_connector.parameters())
1482
+ sc_params = sum(p.numel() for p in model.model.semantic_connector.parameters())
1483
+ print(f"├─ Acoustic Connector: {ac_params:,} params")
1484
+ print(f"├─ Semantic Connector: {sc_params:,} params")
1485
+
1486
+ lmh_params = sum(p.numel() for p in model.lm_head.parameters())
1487
+ print(f"├─ LM Head: {lmh_params:,} params")
1488
+
1489
+ dh = model.model.prediction_head
1490
+ dh_params = sum(p.numel() for p in dh.parameters())
1491
+ print(f"├─ Diffusion Head (unchanged): {dh_params:,} params")
1492
+
1493
+ at_params = sum(p.numel() for p in model.model.acoustic_tokenizer.parameters())
1494
+ st_params = sum(p.numel() for p in model.model.semantic_tokenizer.parameters())
1495
+ print(f"├─ Acoustic Tokenizer (unchanged): {at_params:,} params")
1496
+ print(f"└─ Semantic Tokenizer (unchanged): {st_params:,} params")
1497
+
1498
+ total_params = sum(p.numel() for p in model.parameters())
1499
+ print(f"\n Total: {total_params:,} params (~{total_params * 2 / 1e9:.2f} GB in fp16)")
1500
+
1501
+ print(f"\n Data Flow:")
1502
+ print(f" Audio → AcousticTokenizer → (64-dim) → AcousticConnector → ({QWEN3_HIDDEN_SIZE}-dim)")
1503
+ print(f" Audio → SemanticTokenizer → (128-dim) → SemanticConnector → ({QWEN3_HIDDEN_SIZE}-dim)")
1504
+ print(f" Combined → Qwen3-4B → hidden_states[37 × {QWEN3_HIDDEN_SIZE}-dim]")
1505
+ print(f" → SurgeryModule → ({DIFFUSION_HIDDEN_SIZE}-dim) → DiffusionHead → Speech")
1506
+ print(f" → LMHead → Text Tokens")
1507
+ print("═" * 64)
1508
+
1509
+
1510
+ # ============================================================================
1511
+ # SECTION 10: LoRA Fine-Tuning Setup (Optional)
1512
+ # ============================================================================
1513
+
1514
+ def setup_lora_training(
1515
+ model,
1516
+ lora_r: int = 16,
1517
+ lora_alpha: int = 32,
1518
+ lora_dropout: float = 0.05,
1519
+ target_modules: Optional[List[str]] = None,
1520
+ ):
1521
+ """
1522
+ Setup LoRA for parameter-efficient fine-tuning of the surgery model.
1523
+ """
1524
+ try:
1525
+ from peft import LoraConfig, get_peft_model, TaskType
1526
+ except ImportError:
1527
+ raise ImportError("pip install peft")
1528
+
1529
+ if target_modules is None:
1530
+ target_modules = [
1531
+ "surgery_module.swiglu_gate",
1532
+ "surgery_module.swiglu_up",
1533
+ "surgery_module.output_proj",
1534
+ "acoustic_connector.fc1",
1535
+ "acoustic_connector.fc2",
1536
+ "semantic_connector.fc1",
1537
+ "semantic_connector.fc2",
1538
+ ]
1539
+
1540
+ lora_config = LoraConfig(
1541
+ r=lora_r,
1542
+ lora_alpha=lora_alpha,
1543
+ lora_dropout=lora_dropout,
1544
+ target_modules=target_modules,
1545
+ bias="none",
1546
+ task_type=TaskType.CAUSAL_LM,
1547
+ )
1548
+
1549
+ peft_model = get_peft_model(model, lora_config)
1550
+
1551
+ trainable = sum(p.numel() for p in peft_model.parameters() if p.requires_grad)
1552
+ total = sum(p.numel() for p in peft_model.parameters())
1553
+ print(f"\n LoRA Applied:")
1554
+ print(f" Trainable: {trainable:,} ({100 * trainable / total:.2f}%)")
1555
+ print(f" Total: {total:,}")
1556
+
1557
+ return peft_model
1558
+
1559
+
1560
+ # ============================================================================
1561
+ # SECTION 11: Main Entry Point
1562
+ # ============================================================================
1563
+
1564
+ if __name__ == "__main__":
1565
+ modified_model = run_surgery()
1566
+ verify_surgery(modified_model)
1567
+
1568
+ print("\n" + "█" * 64)
1569
+ print(" SURGERY COMPLETE!")
1570
+ print(f" Model distributed across 2 T4 GPUs")
1571
+ print("")
1572
+ print(" Next Steps:")
1573
+ print(" 1. Swap tokenizer to Qwen3Tokenizer (different vocab)")
1574
+ print(" 2. Fine-tune the Surgery Module + connectors")
1575
+ print(" 3. Use setup_lora_training() for LoRA fine-tuning")
1576
+ print(" 4. Use load_surgery_model() to reload later")
1577
+ print("█" * 64)
1578
+
1579
+
1580
+ # ============================================================================
1581
+ # SECTION 12: Compatibility Notes
1582
+ # ============================================================================
1583
+ """
1584
+ COMPATIBILITY ANALYSIS — Surgery vs. VibeVoice Components
1585
+ ==========================================================
1586
+
1587
+ ✅ COMPATIBLE (no changes needed):
1588
+ • VibeVoiceModel — forward patched to force output_hidden_states=True
1589
+ • SpeechConnector — replaced with correct dimensions (64/128 → 2560)
1590
+ • VibeVoiceDiffusionHead — UNCHANGED (still expects 3584-dim conditioning)
1591
+ • VibeVoiceAcousticTokenizerModel — UNCHANGED
1592
+ • VibeVoiceSemanticTokenizerModel — UNCHANGED
1593
+ • VibeVoiceTokenizerStreamingCache — UNCHANGED
1594
+ • AudioStreamer / AsyncAudioStreamer — UNCHANGED
1595
+ • DPMSolverMultistepScheduler — UNCHANGED
1596
+ • sample_speech_tokens() — UNCHANGED (receives 3584-dim from surgery)
1597
+
1598
+ ⚠️ REQUIRES ATTENTION:
1599
+ 1. TOKENIZER: Qwen3 has vocab_size=151936 (vs Qwen2's 152064).
1600
+ You MUST swap the text tokenizer to Qwen3Tokenizer:
1601
+ from transformers import AutoTokenizer
1602
+ tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-4B-Instruct-2507")
1603
+ The VibeVoiceProcessor wraps this tokenizer, so you need to update
1604
+ the processor's tokenizer as well.
1605
+
1606
+ 2. SPECIAL TOKENS: speech_start_id, speech_end_id, speech_diffusion_id
1607
+ must be added to the Qwen3 tokenizer before use. These are NOT in
1608
+ Qwen3's default vocab. You need to add them and resize the embedding.
1609
+
1610
+ 3. TRAINING SCRIPT: The existing finetune_vibevoice_lora105.py uses
1611
+ VibeVoiceForConditionalGeneration (training class), not the inference
1612
+ class. The training class's forward() has a different signature
1613
+ (includes diffusion loss computation). To fine-tune the surgery model,
1614
+ you need to adapt the training script.
1615
+
1616
+ 4. CONFIG LOADING: The saved config uses model_type="qwen3" for
1617
+ decoder_config. The monkey-patched VibeVoiceConfig handles this,
1618
+ but you MUST call _patch_vibevoice_config_for_qwen3() before loading.
1619
+
1620
+ 5. WEIGHT TYING: Qwen3 uses tie_word_embeddings=True. After surgery,
1621
+ lm_head.weight IS embed_tokens.weight (pointer sharing). If you
1622
+ load weights separately, ensure tying is re-established.
1623
+
1624
+ 6. GENERATE METHOD: The patched generate stores no persistent state
1625
+ between calls. Each generate() call is independent. The surgery
1626
+ module is called fresh for each diffusion step.
1627
+
1628
+ 7. MULTI-GENERATE TOKEN CONSTRAINTS: The generate method constrains
1629
+ output to valid tokens (speech_start, speech_end, speech_diffusion,
1630
+ eos, bos). These IDs must match the Qwen3 tokenizer's vocabulary.
1631
+ """