"""Batch independent questions within a request, retaining the official runner.""" import contextlib,hashlib from pathlib import Path from aran_engine import AranEngine,answer from decision_index.engines import validate class AranBatchEngine(AranEngine): latency='Serial request wall time, including rendering and tokenization; independent questions inside each request are batched. CUDA synchronized by the official runner.' def __init__(self,max_batch=512,token_budget=65536,**options): super().__init__(**options) self.max_batch=int(max_batch);self.token_budget=int(token_budget) self.provenance.update(question_batch_cap=self.max_batch,padded_token_budget=self.token_budget, question_seed_policy='independent generator reset to seed for every question', base_adapter_sha256=self.provenance['adapter_sha256'], adapter_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest()) def _infer(self,entries): torch=self.torch ids,attention,positions,valid,_=self.inference.collate(entries,self.tokenizer.pad_token_id,marker_slots=4,device=self.model.device) precision=torch.autocast('cuda',dtype=torch.bfloat16) if self.model.device.type=='cuda' else contextlib.nullcontext() with precision: flow=self.model.flow start,markers,sequence=flow.encode(ids,attention,positions,return_context=True) # Batch composition must not change a question's Gaussian source. noise=torch.cat([flow.initial_state(start[i:i+1],generator=torch.Generator(device=start.device).manual_seed(self.seed)) for i in range(len(entries))]) logits,_=flow.categorical_rollout(noise,start,markers,valid,sequence,self.steps) return [logits[i,:len(entry[1])].float().softmax(-1).tolist() for i,entry in enumerate(entries)] def __call__(self,state,questions): result=self.infer_requests([dict(state=state,questions=questions)])[0] if isinstance(result,Exception):raise result return result,None def infer_requests(self,requests): from decision_index.engines import Unsupported packed=[];metadata=[];results=[None]*len(requests);answers=[{} for _ in requests] for request_index,payload in enumerate(requests): try:entries,meta=self._pack(payload['state'],payload['questions']) except Unsupported as error: results[request_index]=error continue packed.extend(entries);metadata.extend((request_index,*item) for item in meta) order=sorted(range(len(packed)),key=lambda i:(len(packed[i][1]),len(packed[i][0]))) cursor=0 with self.torch.inference_mode(): while cursorself.token_budget or option_width*(len(indices)+1)>8192):break indices.append(index);longest=proposed try:probabilities=self._infer([packed[i] for i in indices]) except self.torch.OutOfMemoryError: self.torch.cuda.empty_cache() if len(indices)==1:raise self.max_batch=max(1,len(indices)//2) continue for index,probs in zip(indices,probabilities): request_index,name,kind,keys=metadata[index];answers[request_index][name]=answer(kind,keys,probs) cursor+=len(indices) for i,payload in enumerate(requests): if results[i] is not None:continue response=dict(model=self.name,answers={name:answers[i][name] for name in payload['questions']}) validate(payload['questions'],response);results[i]=response return results