File size: 4,047 Bytes
42ba33d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Four independent GPU workers: two Base and two Small, resumable by SHA."""
from __future__ import annotations

import hashlib
import json
import os
import sys
import tarfile
import tempfile
from collections import OrderedDict
from pathlib import Path

import torch

OUT = Path('/e/scratch/reformo/schuhmann1_moss/whisper_score_regression/'
           'gemini_audio_atlas_20261007')
RELEASE = Path('/e/scratch/reformo/schuhmann1_moss/whisper_score_regression/'
               'hf_gemini_release_20261007/model')
sys.path.insert(0, str(RELEASE))
from inference import Predictor  # noqa: E402


class Tars:
    def __init__(self, capacity=32):
        self.capacity = capacity
        self.files = OrderedDict()

    def payload(self, tar_path, member):
        path = str(tar_path)
        if path in self.files:
            tf = self.files.pop(path)
        else:
            tf = tarfile.open(path, 'r')
        self.files[path] = tf
        while len(self.files) > self.capacity:
            self.files.popitem(last=False)[1].close()
        return tf.extractfile(member).read()

    def close(self):
        for tf in self.files.values():
            tf.close()


def main():
    rank = int(os.environ['LOCAL_RANK'])
    world = int(os.environ['LOCAL_WORLD_SIZE'])
    if world != 4 or rank not in range(4):
        raise RuntimeError('Expected exactly four local GPU workers')
    torch.cuda.set_device(rank)
    size = 'base' if rank < 2 else 'small'
    shard = rank % 2
    rows = [json.loads(line) for line in (OUT / 'inference_manifest.jsonl').open()]
    rows = [row for i, row in enumerate(rows) if i % 2 == shard]
    rows.sort(key=lambda row: (row['audio_tar'], row['audio_member']))
    folder = OUT / 'predictions'
    folder.mkdir(exist_ok=True)
    final = folder / f'{size}-shard{shard}.jsonl'
    temp = folder / f'{size}-shard{shard}.jsonl.incomplete'
    if final.exists():
        saved = [json.loads(line)['sha256_mp3'] for line in final.open()]
        if len(saved) == len(rows) and set(saved) == {r['sha256_mp3'] for r in rows}:
            print('ALREADY_COMPLETE', size, shard, len(rows), flush=True)
            return
        raise RuntimeError(f'Final prediction file is incomplete: {final}')
    done = set()
    if temp.exists():
        for line in temp.open():
            try:
                done.add(json.loads(line)['sha256_mp3'])
            except json.JSONDecodeError:
                raise RuntimeError(f'Partial JSON line in {temp}; review before resume')
    predictor = Predictor(RELEASE, size, device=f'cuda:{rank}', threads=4)
    tars = Tars()
    with tempfile.TemporaryDirectory(prefix=f'gemini-atlas-{size}-{shard}-') as tmp, temp.open('a') as output:
        audio_path = Path(tmp) / 'clip.mp3'
        for i, row in enumerate(rows, 1):
            sha = row['sha256_mp3']
            if sha in done:
                continue
            audio = tars.payload(row['audio_tar'], row['audio_member'])
            if hashlib.sha256(audio).hexdigest() != sha:
                raise RuntimeError(f'Audio SHA mismatch: {sha}')
            audio_path.write_bytes(audio)
            prediction = predictor.predict(audio_path, include_frames=True)
            if len(prediction['scores_raw']) != 192:
                raise RuntimeError(f'{size}/{sha}: expected 192 scores')
            output.write(json.dumps({'sha256_mp3': sha, 'model': size,
                                     'prediction': prediction}, ensure_ascii=False,
                                    allow_nan=False) + '\n')
            done.add(sha)
            if i % 25 == 0:
                output.flush(); os.fsync(output.fileno())
                print('PROGRESS', size, shard, i, '/', len(rows), flush=True)
        output.flush(); os.fsync(output.fileno())
    tars.close()
    if len(done) != len(rows):
        raise RuntimeError(f'{size}/{shard}: only {len(done)} of {len(rows)}')
    temp.replace(final)
    print('COMPLETE', size, shard, len(rows), flush=True)


if __name__ == '__main__':
    main()