Text-to-Speech
English
German
voice-acting
qwen3
moss-audio-tokenizer-v2
audio-generation
ChristophSchuhmann's picture
Add S3 Ref15 Full FT as reference-conditioned default
88faa07 verified
Raw History Blame Contribute Delete
9.41 kB
#!/usr/bin/env python3
"""Build a packed, unique-audio S3/tier7 reference-only LoRA worklist.
The old S3 caption curriculum has many presentations per target. Family 0
identifies one presentation per physical target. We use that base-index set,
then join *all* validated reference-eligible UIDs against the frozen reference
assets, not merely the historical 50% reference draw. Four CPU processes each
write 32 Parquet containers; no per-sample files or decoded audio are written.
"""
from __future__ import annotations
from collections import Counter
import hashlib
import json
import math
import os
from pathlib import Path
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
SC = Path('/e/scratch/reformo/schuhmann1_moss')
CURRICULUM = SC / 'out/m2_600m_ladder/caption_curriculum_v1'
LOGICAL = CURRICULUM / 'manifests/S3/manifest.json'
OUT = SC / 'out/hvs_ref_only_r128_v1/worklist'
SHARDS = 128
WORLD = 4
EXPECTED_UNIQUE = 7_216_621
EXPECTED_ELIGIBLE = 3_707_948
MISSING = np.iinfo(np.uint32).max
# MOSS v2 has 80 ms frames. A future reference-conditioned run should allow
# 15-20 s, not inherit the historical 37-frame (2.96 s) crop. Prefer >=5 s
# where a verified same-speaker alternative exists; retain shorter frozen
# references here only to honor the requested all-eligible-S3 coverage and
# report them explicitly. 187 frames = 14.96 s; 188 would exceed 15 s.
MAX_REF_FRAMES = 187
PREFERRED_MIN_REF_FRAMES = 63
def reference_bin(frames):
if frames < 50:
return 'under_4s'
if frames < PREFERRED_MIN_REF_FRAMES:
return '4_to_under_5s'
if frames < 125:
return '5_to_under_10s'
if frames < 188:
return '10_to_under_15s'
return '15s_or_longer'
def sha(path):
h = hashlib.sha256()
with Path(path).open('rb') as stream:
for block in iter(lambda: stream.read(8 << 20), b''):
h.update(block)
return h.hexdigest()
def read_row(fd, offsets, index):
a, b = int(offsets[index]), int(offsets[index + 1])
return json.loads(os.pread(fd, b - a, a))
def uid_validation(uid):
return int.from_bytes(hashlib.blake2b(uid.encode(), digest_size=8).digest(), 'big') % 200 == 0
def main():
rank = int(os.environ['SLURM_PROCID'])
assert int(os.environ['SLURM_NTASKS']) == WORLD and 0 <= rank < WORLD
logical = json.loads(LOGICAL.read_text())
assert logical['status'] == 'complete' and logical['stage'] == 'S3'
assert logical['unique_audio_occurrences'] == EXPECTED_UNIQUE
assert int(logical['family_reference_eligible_counts']['0']) == EXPECTED_ELIGIBLE
base_manifest = Path(logical['base_manifest'])
base_spec = json.loads(base_manifest.read_text())
assert base_spec['status'] == 'complete' and base_spec['ladder_stage'] == 'tier7'
asset_manifest = Path(logical['assets_manifest'])
assets = json.loads(asset_manifest.read_text())
assert assets['status'] == 'complete' and assets['references']['rows'] > EXPECTED_ELIGIBLE
descriptors = np.load(LOGICAL.parent / logical['descriptors'], mmap_mode='r', allow_pickle=False)
assert len(descriptors) == logical['presentations']
base_ids = np.sort(np.asarray(descriptors['base'][descriptors['family'] == 0], dtype=np.uint32))
assert len(base_ids) == EXPECTED_UNIQUE and len(np.unique(base_ids)) == EXPECTED_UNIQUE
base_root = base_manifest.parent
base_offsets = np.load(base_root / base_spec['offsets'], mmap_mode='r', allow_pickle=False)
assert len(base_offsets) == base_spec['presentations'] + 1
base_fd = os.open(base_root / base_spec['records'], os.O_RDONLY)
asset_root = asset_manifest.parent
refs = assets['references']
ref_keys = np.load(asset_root / refs['keys'], mmap_mode='r', allow_pickle=False)
ref_values = np.load(asset_root / refs['values'], mmap_mode='r', allow_pickle=False)
ref_offsets = np.load(asset_root / refs['offsets'], mmap_mode='r', allow_pickle=False)
ref_fd = os.open(asset_root / refs['records'], os.O_RDONLY)
assert len(ref_keys) == len(ref_values) == refs['rows']
assert len(ref_offsets) == len(ref_keys) + 1
assert ref_keys.dtype == np.dtype('S128')
OUT.mkdir(parents=True, exist_ok=True)
width = math.ceil(base_spec['presentations'] / SHARDS)
try:
for shard in range(rank, SHARDS, WORLD):
output = OUT / f'part-{shard:03d}.parquet'
proof = OUT / f'part-{shard:03d}.PASS.json'
if output.exists() and proof.exists():
prior = json.loads(proof.read_text())
assert prior['status'] == 'PASS' and prior['shard'] == shard
assert prior['output_sha256'] == sha(output)
print(json.dumps({'shard': shard, 'status': 'ALREADY_COMMITTED'}), flush=True)
continue
assert not output.exists() and not proof.exists(), f'incomplete shard {shard}'
first, last = shard * width, min((shard + 1) * width, base_spec['presentations'])
a, b = np.searchsorted(base_ids, [first, last])
selected = base_ids[a:b]
targets = [read_row(base_fd, base_offsets, int(index)) for index in selected]
queries = np.asarray([row['uid'].encode() for row in targets], dtype='S128')
positions = np.searchsorted(ref_keys, queries)
valid = positions < len(ref_keys)
valid[valid] = ref_keys[positions[valid]] == queries[valid]
output_rows = []
sources, source_hours = Counter(), Counter()
ref_bins, short_sources = Counter(), Counter()
for index in np.flatnonzero(valid):
target = targets[int(index)]
uid = target['uid']
assert len(uid.encode()) <= 128
reference = read_row(ref_fd, ref_offsets, int(ref_values[int(positions[index])]))
assert reference['uid'] == uid and reference['reference_uid'] != uid
locator = dict(reference['locator'])
original_crop = int(locator['crop_frames'])
full_frames = int(locator['full_frames'])
assert 0 < original_crop <= 37 <= full_frames
# The original codec shard retains all frames. Only the old
# locator's crop field imposed the 2.96-second ceiling.
used_frames = min(full_frames, MAX_REF_FRAMES)
locator['crop_start_frame'] = 0
locator['crop_frames'] = used_frames
assert target['record_locator'] and target['target_locator']
duration = float(target['dur_s'])
assert math.isfinite(duration) and duration > 0
output_rows.append({
'uid': uid, 'base_index': int(selected[index]), 'source': target['source'],
'duration_s': duration, 'record_locator': target['record_locator'],
'target_locator': target['target_locator'],
'reference_uid': reference['reference_uid'],
'reference_locator': locator,
'reference_full_frames': full_frames,
'reference_used_frames': used_frames,
'reference_under_preferred_5s': used_frames < PREFERRED_MIN_REF_FRAMES,
'split': 'validation' if uid_validation(uid) else 'train',
})
sources[target['source']] += 1
source_hours[target['source']] += duration / 3600
ref_bins[reference_bin(full_frames)] += 1
if used_frames < PREFERRED_MIN_REF_FRAMES:
short_sources[target['source']] += 1
temporary = output.with_suffix('.parquet.partial')
# Some contiguous base-index ranges have no eligible reference.
# A zero-row Parquet shard is valid and keeps the 128-shard index
# deterministic; it must not abort a 3.7M-row job after hours.
table = (pa.Table.from_pylist(output_rows) if output_rows else
pa.table({'uid': pa.array([], type=pa.string())}))
pq.write_table(table, temporary,
compression='zstd', row_group_size=4096)
os.replace(temporary, output)
result = {'status': 'PASS', 'shard': shard,
'unique_s3_targets_examined': len(targets),
'reference_eligible_rows': len(output_rows),
'reference_eligible_hours': sum(source_hours.values()),
'source_rows': dict(sources), 'source_hours': dict(source_hours),
'reference_full_duration_bins': dict(ref_bins),
'reference_under_preferred_5s_by_source': dict(short_sources),
'reference_max_frames': MAX_REF_FRAMES,
'reference_preferred_min_frames': PREFERRED_MIN_REF_FRAMES,
'validation_rows': sum(row['split'] == 'validation' for row in output_rows),
'output_sha256': sha(output), 'per_sample_files_created': 0}
proof_tmp = proof.with_suffix('.json.partial')
proof_tmp.write_text(json.dumps(result, indent=2) + '\n')
os.replace(proof_tmp, proof)
print(json.dumps(result), flush=True)
finally:
os.close(base_fd)
os.close(ref_fd)
if __name__ == '__main__':
main()