Download recipe/kit-v3/alignment_head/benchmark_threads.py from gowombat/tiny-voca-da: direct link, hf CLI and curl.
- Browser
- Download file 6.25 kB
-
https://huggingface.co/gowombat/tiny-voca-da/resolve/main/recipe/kit-v3/alignment_head/benchmark_threads.py
- Command line
-
hf download hf://gowombat/tiny-voca-da/recipe/kit-v3/alignment_head/benchmark_threads.py
-
curl -L -o benchmark_threads.py https://huggingface.co/gowombat/tiny-voca-da/resolve/main/recipe/kit-v3/alignment_head/benchmark_threads.py
6.25 kB
| #!/usr/bin/env python3 | |
| """Measure a CPU cache run and compare exact hidden states with a fixed pilot.""" | |
| import argparse | |
| import json | |
| import os | |
| from pathlib import Path | |
| import resource | |
| import signal | |
| import subprocess | |
| import sys | |
| import time | |
| import torch | |
| from adapt_head import dump, rows, sha | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--manifest', type=Path, required=True) | |
| parser.add_argument('--config', type=Path, required=True) | |
| parser.add_argument('--reference-cache', type=Path, | |
| help='Optional fixed cache for an exact hidden-state comparison') | |
| parser.add_argument('--output', type=Path, required=True) | |
| parser.add_argument('--threads', type=int, required=True) | |
| parser.add_argument('--minimum-memory-gib', type=float, default=1.0, | |
| help='Interrupt only this newly launched process below this system MemAvailable') | |
| args = parser.parse_args() | |
| if args.threads < 1 or (args.output.exists() and any(args.output.iterdir())): | |
| raise ValueError('positive thread count and a new output directory are required') | |
| args.output.mkdir(parents=True, exist_ok=True) | |
| reference = None | |
| if args.reference_cache: | |
| reference_meta = json.loads((args.reference_cache / 'identity.json').read_text()) | |
| if not reference_meta.get('complete') or sha(args.reference_cache / 'index.jsonl') != reference_meta['index_sha256']: | |
| raise ValueError('reference cache is incomplete or changed') | |
| reference = {row['id']: row for row in rows(args.reference_cache / 'index.jsonl')} | |
| required_ids = {row['id'] for row in rows(args.manifest)} | |
| if not required_ids <= set(reference): | |
| raise ValueError('reference cache does not cover every requested pilot ID') | |
| reference = {sample_id: reference[sample_id] for sample_id in required_ids} | |
| command = [sys.executable, str(Path(__file__).with_name('adapt_head.py')), '--threads', str(args.threads), | |
| 'cache', '--manifest', str(args.manifest.resolve()), '--config', str(args.config.resolve()), | |
| '--output', str((args.output / 'cache').resolve())] | |
| environment = dict(os.environ, OMP_NUM_THREADS=str(args.threads), MKL_NUM_THREADS=str(args.threads)) | |
| dump(args.output / 'command.json', {'argv': command, 'manifest_sha256': sha(args.manifest), | |
| 'config_sha256': sha(args.config), 'reference_identity_sha256': sha(args.reference_cache / 'identity.json') if args.reference_cache else None, | |
| 'OMP_NUM_THREADS': str(args.threads), 'MKL_NUM_THREADS': str(args.threads), | |
| 'abort_below_mem_available_bytes': int(args.minimum_memory_gib * 1024**3)}) | |
| minimum, samples, aborted = None, 0, False | |
| started = time.monotonic() | |
| with (args.output / 'cache.log').open('w') as log: | |
| process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, env=environment) | |
| try: | |
| while process.poll() is None: | |
| available = int(next(line.split()[1] for line in Path('/proc/meminfo').read_text().splitlines() | |
| if line.startswith('MemAvailable:'))) * 1024 | |
| minimum = available if minimum is None else min(minimum, available) | |
| samples += 1 | |
| if available < args.minimum_memory_gib * 1024**3 and not aborted: | |
| aborted = True | |
| process.send_signal(signal.SIGINT) | |
| time.sleep(0.1) | |
| except KeyboardInterrupt: | |
| process.send_signal(signal.SIGINT) | |
| process.wait() | |
| raise | |
| measured = {'returncode': process.returncode, 'elapsed_seconds': time.monotonic() - started, | |
| 'peak_rss_kib': resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss, | |
| 'minimum_system_mem_available_bytes': minimum, 'memory_samples': samples, | |
| 'aborted_for_memory': aborted, 'threads': args.threads} | |
| if process.returncode == 0 and reference is not None: | |
| actual = {row['id']: row for row in rows(args.output / 'cache/index.jsonl')} | |
| if set(actual) != set(reference): | |
| raise ValueError('pilot ID membership differs from the reference') | |
| comparison = [] | |
| for sample_id, row in actual.items(): | |
| old = reference[sample_id] | |
| old_path = args.reference_cache / old['cache'] | |
| new_path = args.output / 'cache' / row['cache'] | |
| if sha(old_path) != old['cache_sha256'] or sha(new_path) != row['cache_sha256']: | |
| raise ValueError('pilot representation bytes changed') | |
| first = torch.load(old_path, map_location='cpu', weights_only=True) | |
| second = torch.load(new_path, map_location='cpu', weights_only=True) | |
| equal = torch.equal(first['hidden'], second['hidden']) | |
| comparison.append({'id': sample_id, 'hidden_bitwise_equal': equal, | |
| 'audio_sha_equal': row['audio_sha256'] == old['audio_sha256'], | |
| 'max_absolute_hidden_difference': 0.0 if equal else | |
| float((first['hidden'].float() - second['hidden'].float()).abs().max())}) | |
| measured['comparison_to_reference'] = comparison | |
| measured['all_hidden_states_bitwise_equal'] = all(row['hidden_bitwise_equal'] and row['audio_sha_equal'] | |
| for row in comparison) | |
| measured['actual_attention_implementation'] = json.loads((args.output / 'cache/identity.json').read_text())['runtime']['attention_implementation'] | |
| if process.returncode == 0: | |
| completed = json.loads((args.output / 'cache/identity.json').read_text()) | |
| measured['cache_complete'] = completed['complete'] | |
| measured['cache_utterances'] = completed['count'] | |
| measured['actual_attention_implementation'] = completed['runtime']['attention_implementation'] | |
| dump(args.output / 'resource.json', measured) | |
| print(json.dumps({k:v for k,v in measured.items() if k != 'comparison_to_reference'}, indent=2), flush=True) | |
| if process.returncode: | |
| raise SystemExit(process.returncode) | |
| if __name__ == '__main__': | |
| main() | |