Text-to-Speech
English
German
voice-acting
qwen3
moss-audio-tokenizer-v2
audio-generation
File size: 17,505 Bytes
88faa07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#!/usr/bin/env python3
"""Full-parameter S3 long-reference continuation, matched to the Rank-128 LoRA data.

All model weights remain FP32 masters; forward/loss use the original BF16
autocast path. The source worklist, UID order, prompt renderer, resolved text,
15-second reference packing and audio-token objective are unchanged.
"""
from __future__ import annotations

from contextlib import nullcontext
from datetime import timedelta
import json
import math
import os
from pathlib import Path
import signal
import sys
import time

import numpy as np
import pyarrow.parquet as pq
import torch
import torch.distributed as dist
from torch import nn
from torch.nn.parallel import DistributedDataParallel as DDP
from transformers import AutoTokenizer

HERE = Path(__file__).resolve().parent
HOME = HERE.parent
SC = Path('/e/scratch/reformo/schuhmann1_moss')
OLD = HOME / 'hvs_ref_only_r128_v1'
VENDOR = HOME / 'm2_600m_tts_training/vendor/m2_20k_score'
sys.path[:0] = [str(OLD), str(HOME), str(HOME / 'm2_dpo_smoke_v1'), str(VENDOR)]

import run_smoke as core
import state_io
from continuation_control import complete_checkpoint, latest_checkpoint, sha
from build_worklist import MAX_REF_FRAMES, PREFERRED_MIN_REF_FRAMES
from prompt_mix import AnnotationIndex, MODES, SOURCE_PROMPT_SANITIZER_VERSION
from qa_worklist import Reader
from rowgroup_plan import read_rank_rows, SAMPLER_VERSION
from script_only import RENDERER_VERSION
from text_resolution import apply_to_rows, load_resolution, RESOLUTION_MANIFEST
from train import packed, mean_validation

WORKLIST = SC / 'out/hvs_ref_only_r128_v1/worklist'
BASE = SC / 'out/m2_600m_ladder/caption_curriculum_v1/training/checkpoints/step-00032337'
SCHEMA = SC / 'out/m2_20k_score/score_schema.json'
ROOT = SC / 'out/hvs_ref_full_ft_v1'
SEED = 20261004
PEAK_BACKBONE = 8e-6
PEAK_TALKER = 1.6e-5
WARMUP_FRACTION = .05
FLOOR_RATIO = .10
SAVE_EVERY = 1000
STOP = False


class Step(nn.Module):
    """DDP boundary around exactly the original teacher-forced audio loss."""

    def __init__(self, base, config, device):
        super().__init__()
        self.base = base
        self.config = config
        self.device = device

    def forward(self, batch):
        logprob, _ = core.logprob(self.base, self.config, batch, self.device)
        return -logprob


def stop(_signal, _frame):
    global STOP
    STOP = True


def atomic_json(path: Path, value: dict) -> None:
    temporary = path.with_suffix(path.suffix + '.partial')
    temporary.write_text(json.dumps(value, ensure_ascii=False, allow_nan=False, indent=2) + '\n')
    os.replace(temporary, path)


def lr_factor(step: int, total: int) -> float:
    warmup = max(1, round(total * WARMUP_FRACTION))
    if step <= warmup:
        return step / warmup
    progress = min(1., (step - warmup) / max(1, total - warmup))
    return FLOOR_RATIO + (1 - FLOOR_RATIO) * .5 * (1 + math.cos(math.pi * progress))


def prepare_rows(rank, world, changes, annotations):
    assigned, loads = read_rank_rows(rank, world)
    assigned = apply_to_rows(assigned, changes)
    rows = [row for row in assigned if row['split'] == 'train']
    assert rows
    annotations.attach(rows)
    validation = []
    for shard in range(128):
        for row in pq.read_table(WORKLIST / f'part-{shard:03d}.parquet').to_pylist():
            if row['split'] == 'validation' and len(validation) < world * 16:
                validation.append(row)
        if len(validation) >= world * 16:
            break
    assert len(validation) == world * 16
    validation = apply_to_rows(validation, changes)
    annotations.attach(validation)
    for cohort in (rows, validation):
        for row in cohort:
            if row.get('_resolution_action') == 'burst_only':
                row['_prompt_mode'] = 'script_only'
            elif row.get('_resolution_action') == 'relabel' and row['_prompt_mode'] in (
                    'general_script', 'caption_bude'):
                row['_prompt_mode'] = 'script_only'
    return rows, validation, loads


def main() -> None:
    smoke = os.environ.get('HVS_FULL_FT_SMOKE') == '1'
    rank, world, local = (int(os.environ[key]) for key in
                          ('SLURM_PROCID', 'SLURM_NTASKS', 'SLURM_LOCALID'))
    assert world == (4 if smoke else 32)
    visible = torch.cuda.device_count()
    assert visible in (1, 4), visible
    device_index = 0 if visible == 1 else local
    device = torch.device('cuda', device_index)
    torch.cuda.set_device(device)
    torch.set_num_threads(4)
    dist.init_process_group('nccl', init_method='env://', rank=rank, world_size=world,
                            timeout=timedelta(minutes=30), device_id=device)
    signal.signal(signal.SIGUSR1, stop)
    signal.signal(signal.SIGTERM, stop)
    started = time.monotonic()

    manifest_path = WORKLIST / 'MANIFEST.json'
    manifest = json.loads(manifest_path.read_text())
    assert manifest['status'] == 'COMPLETE' and manifest['eligible_unique_targets'] == 3_707_948
    assert manifest['reference_max_frames'] == MAX_REF_FRAMES == 187
    assert manifest['reference_preferred_min_frames'] == PREFERRED_MIN_REF_FRAMES == 63
    assert manifest['prompt_mix_version'] == 'hvs-ref15-mix-v1'
    resolution, changes = load_resolution()
    assert resolution['status'] == 'PASS'
    qa = json.loads((WORKLIST.parent / 'QA_SAMPLES.json').read_text())
    assert qa['status'] == 'PASS' and qa['sampled_rows'] == 64
    assert set(qa['prompt_mode_rows']) == set(MODES)
    annotations = AnnotationIndex()
    rows, validation, loads = prepare_rows(rank, world, changes, annotations)
    effective = torch.tensor([sum(row['_prompt_mode'] == mode for row in rows)
                              for mode in MODES], dtype=torch.int64, device=device)
    dist.all_reduce(effective)
    prompt_counts = {mode: int(effective[i].item()) for i, mode in enumerate(MODES)}
    assert sum(prompt_counts.values()) <= resolution['accepted_rows']
    accum = 2 if smoke else 4
    local_steps = torch.tensor([math.ceil(len(rows) / accum)], dtype=torch.int64, device=device)
    dist.all_reduce(local_steps, op=dist.ReduceOp.MAX)
    total = 2 if smoke else int(local_steps.item())
    assert len(rows) >= accum * total if smoke else total > 1000
    if not smoke:
        assert total == 26774, total
    order = np.random.default_rng(SEED + rank).permutation(len(rows))
    torch.manual_seed(SEED)
    torch.cuda.manual_seed_all(SEED)

    schema = json.loads(SCHEMA.read_text())
    model, config = core.build_fresh(schema, log=lambda _: None)
    state = torch.load(BASE / 'model_bf16.pt', map_location='cpu', weights_only=True)
    model.load_state_dict(state, strict=True)
    model.tie_weights()
    del state
    # FP32 master parameters are necessary at these small continuation LRs:
    # tiny updates to BF16 parameter tensors can round away completely.
    model = model.to(device=device, dtype=torch.float32).eval()
    assert all(model.audio_lm_heads[i].weight.data_ptr() ==
               model.audio_embeddings[i].weight.data_ptr() for i in range(12))
    # The inherited score conditioner is unused by this audio-caption loss;
    # retain its original frozen state. Every *active* semantic and Talker
    # parameter is fully fine-tuned, without a LoRA or adapter.
    for name, parameter in model.named_parameters():
        parameter.requires_grad_(not name.startswith('score_conditioner.'))
    groups = {'backbone': [], 'talker': []}
    for name, parameter in model.named_parameters():
        if not parameter.requires_grad:
            continue
        key = 'backbone' if name.startswith(('transformer.', 'text_lm_head.')) else 'talker'
        groups[key].append(parameter)
    assert all(groups.values())
    optimizer = torch.optim.AdamW([
        {'name': 'backbone', 'params': groups['backbone'], 'lr': PEAK_BACKBONE},
        {'name': 'talker', 'params': groups['talker'], 'lr': PEAK_TALKER},
    ], betas=(.9, .95), eps=1e-8, weight_decay=.01, foreach=False)
    wrapper = DDP(Step(model, config, device).eval(), device_ids=[device_index],
                  broadcast_buffers=False, find_unused_parameters=True,
                  gradient_as_bucket_view=True)
    _, _, Processor = core.moss_small.export_classes()
    processor = Processor(tokenizer=AutoTokenizer.from_pretrained(
        core.moss_small.SFT3, trust_remote_code=True, local_files_only=True),
        audio_tokenizer=None, model_config=config)
    packer = core.ScorePacker(processor, config, schema)
    reader = Reader()
    run = ROOT / ('smoke_4gpu' if smoke else 'training')
    run.mkdir(parents=True, exist_ok=True)
    contract = {
        'kind': 'hvs-long-ref-full-ft-v1', 'world': world, 'seed': SEED,
        'base_checkpoint': str(BASE), 'manifest_sha256': sha(manifest_path),
        'resolution_sha256': sha(RESOLUTION_MANIFEST), 'schema_sha256': sha(SCHEMA),
        'source_prompt_sanitizer_version': SOURCE_PROMPT_SANITIZER_VERSION,
        'script_renderer_version': RENDERER_VERSION, 'sampler_version': SAMPLER_VERSION,
        'lr_backbone_peak': PEAK_BACKBONE, 'lr_talker_peak': PEAK_TALKER,
        'objective': 'same_audio_logprob_as_reference_lora',
        'prompt_counts': prompt_counts, 'total_steps': total,
    }
    chosen = [None]
    scheduler = NoOpScheduler()
    if rank == 0:
        try:
            directory = latest_checkpoint(run / 'checkpoints', contract, world)
            if directory is not None:
                complete_checkpoint(directory, contract, world, content=True)
            chosen[0] = {'path': str(directory) if directory else None}
        except Exception as error:
            chosen[0] = {'error': repr(error)}
    dist.broadcast_object_list(chosen, src=0)
    assert 'error' not in chosen[0], chosen[0]
    completed = 0
    if chosen[0]['path']:
        completed = state_io.load(chosen[0]['path'], wrapper, optimizer, scheduler, contract)
    # state_io expects an ordinary scheduler object. The schedule is instead
    # a deterministic pure function of the committed global step, so give it
    # a no-op state carrier to preserve its atomic checkpoint/restore path.
    if rank == 0:
        print(json.dumps({'kind': 'start', 'smoke': smoke, 'world': world,
                          'steps': total, 'resumed_step': completed,
                          'trainable_parameters': sum(p.numel() for p in model.parameters() if p.requires_grad),
                          'frozen_unused_parameters': sum(p.numel() for p in model.parameters() if not p.requires_grad),
                          'backbone_parameters': sum(p.numel() for p in groups['backbone']),
                          'talker_parameters': sum(p.numel() for p in groups['talker']),
                          'effective_batch': world * accum,
                          'prompt_counts': prompt_counts,
                          'reference_max_seconds': MAX_REF_FRAMES * .08,
                          'rowgroup_load_min': min(loads), 'rowgroup_load_max': max(loads)}), flush=True)
    metrics = run / 'metrics.jsonl'
    if completed == 0:
        value, n = mean_validation(model, config, reader, packer, annotations,
                                   validation, device, rank, world)
        if rank == 0:
            with metrics.open('a') as output:
                output.write(json.dumps({'kind': 'validation', 'step': 0,
                                         'nll_per_frame': value, 'rows': n}) + '\n')
    last = completed
    for step in range(completed + 1, total + 1):
        last = step
        optimizer.zero_grad(set_to_none=True)
        local_count = max(0, min(accum, len(rows) - (step - 1) * accum))
        global_count = torch.tensor([local_count], dtype=torch.int64, device=device)
        dist.all_reduce(global_count)
        assert global_count.item() > 0
        local_modes = [0] * len(MODES)
        ref_frames = long_refs = short_refs = 0
        local_loss = 0.
        for micro in range(accum):
            position = (step - 1) * accum + micro
            active = position < len(rows)
            row = rows[int(order[position])] if active else rows[0]
            batch, facts = packed(row, reader, packer, annotations)
            if active:
                local_modes[MODES.index(facts['prompt_mode'])] += 1
                ref_frames += facts['reference_frames']
                long_refs += int(facts['reference_frames'] > 37)
                short_refs += int(facts['reference_frames'] < PREFERRED_MIN_REF_FRAMES)
            context = wrapper.no_sync() if micro + 1 < accum else nullcontext()
            with context:
                raw_loss = wrapper(batch)
                assert torch.isfinite(raw_loss)
                (raw_loss * (world / int(global_count.item()) if active else 0.)).backward()
            if active:
                local_loss += float(raw_loss.detach())
        grad_norm = torch.nn.utils.clip_grad_norm_(wrapper.parameters(), 1.)
        assert torch.isfinite(grad_norm) and float(grad_norm) > 0
        update_canary = None
        if smoke and step == 1:
            representatives = []
            for group_name in ('backbone', 'talker'):
                chosen_parameter = next((parameter for parameter in groups[group_name]
                                         if parameter.grad is not None and
                                         bool(parameter.grad.detach().abs().max() > 0)), None)
                assert chosen_parameter is not None, f'No {group_name} gradient'
                representatives.append((group_name, chosen_parameter,
                                        chosen_parameter.detach().clone()))
            update_canary = representatives
        multiplier = lr_factor(step, total)
        optimizer.param_groups[0]['lr'] = PEAK_BACKBONE * multiplier
        optimizer.param_groups[1]['lr'] = PEAK_TALKER * multiplier
        optimizer.step()
        if update_canary is not None:
            weight_changes = {name: float((parameter.detach() - before).abs().sum())
                              for name, parameter, before in update_canary}
            assert weight_changes['backbone'] > 0 and weight_changes['talker'] > 0, weight_changes
            if rank == 0:
                print(json.dumps({'kind': 'full_ft_update_canary', 'step': step,
                                  'backbone_l1_change': weight_changes['backbone'],
                                  'talker_l1_change': weight_changes['talker']}), flush=True)
        summary = torch.tensor([ref_frames, long_refs, short_refs, *local_modes],
                               dtype=torch.int64, device=device)
        dist.all_reduce(summary)
        if rank == 0 and (smoke or step % 50 == 0):
            event = {'kind': 'train', 'step': step, 'total': total,
                     'loss_local': local_loss / max(1, local_count),
                     'examples_global': int(global_count.item()),
                     'grad_norm': float(grad_norm),
                     'lr_backbone': optimizer.param_groups[0]['lr'],
                     'lr_talker': optimizer.param_groups[1]['lr'],
                     'reference_mean_seconds': float(summary[0]) * .08 / int(global_count.item()),
                     'reference_longer_than_2_96s': int(summary[1]),
                     'reference_under_preferred_5s': int(summary[2]),
                     'prompt_mode_counts': {mode: int(summary[i+3]) for i, mode in enumerate(MODES)},
                     'elapsed_s': time.monotonic() - started,
                     'peak_allocated_gib': torch.cuda.max_memory_allocated(device) / 2**30}
            with metrics.open('a') as output:
                output.write(json.dumps(event) + '\n')
            print(json.dumps(event), flush=True)
        value = None
        if smoke or step % 500 == 0 or step == total:
            value, n = mean_validation(model, config, reader, packer, annotations,
                                       validation, device, rank, world)
            if rank == 0:
                with metrics.open('a') as output:
                    output.write(json.dumps({'kind': 'validation', 'step': step,
                                             'nll_per_frame': value, 'rows': n}) + '\n')
        flag = torch.tensor([int(STOP or time.monotonic() - started > 10.5 * 3600)], device=device)
        dist.all_reduce(flag, op=dist.ReduceOp.MAX)
        if (smoke and step == total) or (not smoke and step % SAVE_EVERY == 0) or step == total or flag.item():
            directory = state_io.save(run / 'checkpoints', wrapper, optimizer,
                                      scheduler, step, contract,
                                      export=(step == total or (not smoke and step % 5000 == 0)))
            if rank == 0:
                print(json.dumps({'kind': 'checkpoint', 'step': step,
                                  'directory': str(directory), 'validation_nll_per_frame': value}), flush=True)
        if flag.item():
            break
    if rank == 0 and last == total:
        atomic_json(run / 'DONE.json', {'status': 'COMPLETE', 'step': total,
                    'manifest_sha256': contract['manifest_sha256'],
                    'resolution_sha256': contract['resolution_sha256'],
                    'base_checkpoint': str(BASE), 'time': time.time()})
    dist.barrier()
    dist.destroy_process_group()


class NoOpScheduler:
    def state_dict(self):
        return {}

    def load_state_dict(self, state):
        assert state == {}


if __name__ == '__main__':
    main()