Spaces:
Running
Running
Download code/run_inference.py from laion/humaneness-ears-atlas: direct link, hf CLI and curl.
- Browser
- Download file 4.05 kB
-
https://huggingface.co/spaces/laion/humaneness-ears-atlas/resolve/main/code/run_inference.py
- Command line
-
hf download hf://spaces/laion/humaneness-ears-atlas/code/run_inference.py
-
curl -L -o run_inference.py https://huggingface.co/spaces/laion/humaneness-ears-atlas/resolve/main/code/run_inference.py
4.05 kB
| #!/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() | |