"""Pinned Hub data -> verified caches -> independent Stage A ASR/TTS training. The pilot profile uses already encoded training data. The full profile encodes the official alignment splits once and reuses verified preparation manifests. Natural interaction data is not mislabeled as a causal duplex training cache. """ from __future__ import annotations import argparse from dataclasses import replace from fnmatch import fnmatch import hashlib import json import os from pathlib import Path import re import runpy import shutil import subprocess import sys import tarfile from .config import Config from .data import AlignmentDataset, load_jsonl, write_jsonl def digest(path): value = hashlib.sha256() with Path(path).open('rb') as handle: for block in iter(lambda: handle.read(4 * 1024**2), b''): value.update(block) return value.hexdigest() def save_json(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + '.tmp') temporary.write_text(json.dumps(value, indent=2, sort_keys=True) + '\n', encoding='utf-8') temporary.replace(path) def patterns(profile): common = ['README.md', 'LICENSE', 'MANIFEST.json', 'codec-pilot/*.toml', 'reports/codec-pilot.json'] return common + (['codec-pilot/**'] if profile == 'pilot' else ['alignment/**', 'reports/alignment.json', 'tools/materialize_alignment.py']) def verify_snapshot(root, profile): root = Path(root).resolve() manifest = json.loads((root / 'MANIFEST.json').read_text(encoding='utf-8')) if manifest.get('status') != 'validated' or manifest.get('release') != 'nano-duplex-data-v1': raise ValueError('Expected a validated nano-duplex data release') expected = [item for item in manifest['files'] if any(fnmatch(item['path'], pattern) for pattern in patterns(profile))] if not expected: raise ValueError('Release has no files for this profile') for item in expected: path = (root / item['path']).resolve() if not path.is_relative_to(root) or path.is_symlink(): raise ValueError('Snapshot path escapes its dataset root') if not path.is_file() or path.stat().st_size != item['bytes'] or digest(path) != item['sha256']: raise ValueError(f'Snapshot file failed verification: {item["path"]}') return {'manifest_sha256': digest(root / 'MANIFEST.json'), 'verified_files': len(expected)} def snapshot(args): lock_path = args.work_dir / 'dataset-lock.json' old = json.loads(lock_path.read_text()) if lock_path.exists() else None if old and old['repo'] != args.repo: raise ValueError('This work directory is bound to another repository') if old and args.revision and old['revision'] != args.revision: raise ValueError('Use a new work directory when changing the dataset revision') revision = args.revision or (old['revision'] if old else None) if not args.offline and args.phase in {'download', 'all'}: from huggingface_hub import HfApi, snapshot_download revision = revision or HfApi().dataset_info(args.repo).sha snapshot_download(args.repo, repo_type='dataset', revision=revision, local_dir=args.snapshot_dir, allow_patterns=patterns(args.profile), max_workers=8) checked = verify_snapshot(args.snapshot_dir, args.profile) revision = revision or ('local:' + checked['manifest_sha256']) if old and old['manifest_sha256'] != checked['manifest_sha256']: raise ValueError('Dataset contents changed inside an existing work directory') lock = {'repo': args.repo, 'revision': revision, **checked} save_json(lock_path, lock) return lock def dataset_path(args, task, split='train'): folder = args.work_dir / 'codec-pilot' if args.profile == 'pilot' else args.work_dir / 'prepared' return folder / f'{task}-{split}.jsonl' def configurations(args): result = {} for task in ('asr', 'tts'): base = Config.load(args.snapshot_dir / 'codec-pilot' / f'{task}.toml') config = replace(base, dataset=str(dataset_path(args, task)), output_dir=str(args.run_dir / task), device=args.device, batch_size=args.batch_size, steps=args.steps, save_every=min(base.save_every, args.steps)).validate() path = args.work_dir / 'configs' / f'{task}.toml' path.parent.mkdir(parents=True, exist_ok=True) path.write_text(''.join(f'{key} = {json.dumps(value, ensure_ascii=True, allow_nan=False)}\n' for key, value in config.to_dict().items() if value is not None), encoding='utf-8') result[task] = config return result def train_command(args, task): prefix = [sys.executable] if args.nproc > 1: prefix += ['-m', 'torch.distributed.run', '--standalone', f'--nproc_per_node={args.nproc}'] command = prefix + ['-m', 'nano_duplex.train', '--config', str(args.work_dir / 'configs' / f'{task}.toml')] checkpoint = args.run_dir / task / 'latest.pt' if args.resume and checkpoint.is_file(): command += ['--resume', str(checkpoint)] return command def cache_present(path, config, task): data = AlignmentDataset(path, config, f'alignment_{task}') for row in data.manifest_rows: if not (Path(path).parent / row['cache']['path']).is_file(): raise FileNotFoundError('A prepared tensor cache is missing') return len(data) def expand_pilot(snapshot_dir, destination): """Expand only indexed regular tensor files, checking each digest before promotion.""" source, destination = Path(snapshot_dir) / 'codec-pilot', Path(destination).resolve() index = json.loads((source / 'cache-index.json').read_text(encoding='utf-8')) expected = {item['path']: item for item in index['files']} if len(expected) != len(index['files']): raise ValueError('Duplicate archive index paths') destination.mkdir(parents=True, exist_ok=True) seen = set() with tarfile.open(source / 'tensors.tar', 'r') as archive: for member in archive: item = expected.get(member.name) if (not member.isfile() or item is None or member.name in seen or member.size != item['bytes'] or not re.fullmatch(r'cache/[0-9a-f]{64}\.pt', member.name)): raise ValueError('Unexpected tensor archive member') seen.add(member.name) candidate = destination / member.name path = candidate.resolve() if not path.is_relative_to(destination) or candidate.is_symlink(): raise ValueError('Tensor archive path escapes its output') if path.is_file() and digest(path) == item['sha256']: continue path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix('.pt.tmp') with archive.extractfile(member) as reader, temporary.open('wb') as target: shutil.copyfileobj(reader, target, 1024**2) if temporary.stat().st_size != item['bytes'] or digest(temporary) != item['sha256']: raise ValueError('Expanded tensor checksum mismatch') temporary.replace(path) if seen != set(expected): raise ValueError('Tensor archive is missing indexed files') for task in ('asr', 'tts'): shutil.copyfile(source / f'{task}-train.jsonl', destination / f'{task}-train.jsonl') return len(expected) def prepare(args, configs, lock): if args.profile == 'pilot': expand_pilot(args.snapshot_dir, args.work_dir / 'codec-pilot') return {task: cache_present(dataset_path(args, task), configs[task], task) for task in configs} state_path = args.work_dir / 'preparation.json' binding = {'manifest_sha256': lock['manifest_sha256'], 'codec': {key: getattr(configs['asr'], key) for key in ('mimi_repo', 'mimi_revision', 'sample_rate', 'tick_ms', 'audio_dim', 'codebooks', 'codebook_size')}} state = json.loads(state_path.read_text()) if state_path.exists() else {**binding, 'completed': {}} if any(state.get(key) != value for key, value in binding.items()): raise ValueError('Cached preparation belongs to a different dataset or codec; use a new work directory') save_json(state_path, state) # This is the release's own materializer, checked against the pinned manifest above. export = runpy.run_path(str(args.snapshot_dir / 'tools/materialize_alignment.py'))['materialize'] for split in ('train', 'validation', 'test'): paths = {task: dataset_path(args, task, split) for task in configs} if split in state['completed']: for task, path in paths.items(): if digest(path) != state['completed'][split][task]: raise ValueError('A prepared manifest changed; refusing to silently reuse it') cache_present(path, configs[task], task) print(json.dumps({'preparation': split, 'status': 'reused'}), flush=True) continue raw = args.work_dir / 'raw' / f'{split}.jsonl' if not raw.exists(): export(args.snapshot_dir, raw.parent, split) for row in load_jsonl(raw): if digest(raw.parent / row['audio']) != row['source_sha256']: raise ValueError('A materialized source WAV changed before encoding') command = [sys.executable, '-m', 'nano_duplex.data', 'prepare-pair', '--config', str(args.work_dir / 'configs/asr.toml'), '--tts-config', str(args.work_dir / 'configs/tts.toml'), '--manifest', str(raw), '--asr-output', str(paths['asr']), '--tts-output', str(paths['tts'])] subprocess.run(command, check=True) for path in paths.values(): rows = load_jsonl(path) for row in rows: row['audio'] = Path(os.path.relpath((raw.parent / row['audio']).resolve(), path.parent)).as_posix() write_jsonl(path, rows) state['completed'][split] = {task: digest(path) for task, path in paths.items()} save_json(state_path, state) return {task: cache_present(dataset_path(args, task), configs[task], task) for task in configs} def options(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--repo', default='JonesLin/nano-duplex-data-v1') parser.add_argument('--revision', help='Exact dataset commit; otherwise resolve once and lock it locally') parser.add_argument('--profile', choices=['pilot', 'full'], default='pilot') parser.add_argument('--phase', choices=['download', 'prepare', 'train', 'evaluate', 'all'], default='all') parser.add_argument('--snapshot-dir', type=Path, default=Path('data/hf-server/snapshot')) parser.add_argument('--work-dir', type=Path, default=Path('data/hf-server/work')) parser.add_argument('--run-dir', type=Path) parser.add_argument('--nproc', type=int, default=1) parser.add_argument('--steps', type=int, default=400) parser.add_argument('--batch-size', type=int, default=8) parser.add_argument('--device', default='cuda') parser.add_argument('--resume', action='store_true') parser.add_argument('--offline', action='store_true', help='Use and verify an existing local snapshot') parser.add_argument('--dry-run', action='store_true', help='Print the workflow without network access or file changes') args = parser.parse_args(argv) if args.revision and not re.fullmatch('[0-9a-f]{40}', args.revision): parser.error('--revision must be a full 40-character commit SHA') if min(args.nproc, args.steps, args.batch_size) <= 0: parser.error('GPU processes, steps and batch size must be positive') if args.profile == 'pilot' and args.phase == 'evaluate': parser.error('The codec pilot is training-only; use the full profile for held-out evaluation') args.run_dir = args.run_dir or Path(f'runs/hf-stage-a-{args.profile}') for name in ('snapshot_dir', 'work_dir', 'run_dir'): setattr(args, name, getattr(args, name).resolve()) return args def main(argv=None): args = options(argv) if args.dry_run: print(json.dumps({'profile': args.profile, 'phase': args.phase, 'repo': args.repo, 'revision': args.revision or 'resolve once and lock', 'download_patterns': patterns(args.profile), 'prepare': 'reuse included Mimi tensors' if args.profile == 'pilot' else 'export verified WAV/JSONL; encode train/validation/test once; reuse on later runs', 'training_commands': {task: train_command(args, task) for task in ('asr', 'tts')}, 'scope': 'independent Stage A alignment; no duplex-policy training'}, indent=2)) return 0 if args.phase in {'train', 'all'}: found_checkpoint = False for task in ('asr', 'tts'): exists = (args.run_dir / task / 'latest.pt').exists() found_checkpoint |= exists if exists and not args.resume: raise FileExistsError('Existing checkpoints require --resume or a new --run-dir') if args.resume and not found_checkpoint: raise FileNotFoundError('--resume requires at least one existing task checkpoint') lock = snapshot(args) configs = configurations(args) status = {'status': 'running', 'profile': args.profile, 'phase': args.phase, 'dataset': lock, 'completed': []} status_path = args.work_dir / 'pipeline-status.json' save_json(status_path, status) try: if args.phase in {'prepare', 'all'}: status['cache_rows'] = prepare(args, configs, lock) status['completed'].append('prepare') save_json(status_path, status) if args.phase in {'train', 'all'}: for task in configs: cache_present(dataset_path(args, task), configs[task], task) subprocess.run(train_command(args, task), check=True) status['completed'].append(f'train_{task}') save_json(status_path, status) if args.phase == 'evaluate' or (args.phase == 'all' and args.profile == 'full'): for task in configs: subprocess.run([sys.executable, '-m', 'nano_duplex.alignment_eval', '--checkpoint', str(args.run_dir / task / 'latest.pt'), '--manifest', str(dataset_path(args, task, 'validation')), '--train-manifest', str(dataset_path(args, task)), '--split', 'heldout', '--device', args.device, '--max-samples', '8', '--max-new-tokens', '96', '--output-dir', str(args.run_dir / 'evaluation' / task)], check=True) status['completed'].append(f'evaluate_{task}') status['status'] = 'completed' except Exception as exc: status.update(status='failed', error=f'{type(exc).__name__}: {exc}') raise finally: save_json(status_path, status) print(json.dumps(status), flush=True) return 0 if __name__ == '__main__': raise SystemExit(main())