"""Load a pinned Elephant runtime and score ordered decision slots.""" from functools import partial import hashlib import importlib import os def setup(): import torch import torch.distributed as dist rank = int(os.environ.get('RANK', '0')) world = int(os.environ.get('WORLD_SIZE', '1')) if world > 1: devices = os.environ.get('CUDA_VISIBLE_DEVICES') if devices is None: devices = ','.join(str(index) for index in range(torch.cuda.device_count())) os.environ['CUDA_VISIBLE_DEVICES'] = devices.split(',')[int(os.environ['LOCAL_RANK'])] dist.init_process_group('nccl', device_id=torch.device('cuda:0')) elif not torch.cuda.is_available(): raise RuntimeError('Elephant NF4/BF16 inference and training require CUDA.') return rank, world def load(dataset, stage, base_dir, image_root, adapter, **kwargs): runtime = importlib.import_module(f'judge.stage{stage}_runtime') from qev.prompt import PromptStyle, render_question runtime.common.render_question = partial(render_question, style=PromptStyle(show_names=stage == 1 or dataset == 'dubai')) bundle, _ = runtime.load_model(base_dir, image_root, adapter=adapter, **kwargs) return runtime, bundle def score(runtime, bundle, questions, rank=0, world=1): import torch.distributed as dist questions = list(questions) local = [row for row in questions if int(hashlib.sha256(row['name'].encode()).hexdigest(), 16) % world == rank] bundle.model.eval() results = {} for offset in range(0, len(local), 4): chunk = local[offset:offset + 4] for row, scores in zip(chunk, runtime.predict(bundle, chunk), strict=True): results[row['name']] = [[index, scores[label]] for label, index in row['native_candidate_indices'].items()] if world > 1: shards = [None] * world dist.all_gather_object(shards, results) results = {key: value for shard in shards for key, value in shard.items()} if len(results) != len(questions): raise ValueError('Missing or duplicate question scores') return results