Aran-1 / aran_engine.py
TheHuggerFacer's picture
Add fixed-format, no-truncation Decision Index inference adapter
d8c7eff verified
Raw History Blame Contribute Delete
6.18 kB
"""Decision Index adapter for Aran-1. Inference only; never truncates a request."""
import contextlib
import hashlib
import importlib
import json
from pathlib import Path
from decision_index.engines import Engine, Unsupported, validate
MODEL='TheHuggerFacer/Aran-1'
REVISION='d89add9515635f88a9f741b88dcc63d717dec707'
def text(value):
return value if isinstance(value,str) else json.dumps(value,ensure_ascii=False,separators=(',',':'))
def request(state,question):
"""Map every typed question using one fixed rendering, independent of benchmark."""
kind=question['type'];criteria=question.get('criteria')
instructions=text(question.get('instructions',''))
if kind=='choice':
if not isinstance(criteria,dict) or not criteria:raise Unsupported('Choice questions require named options')
keys=list(criteria)
descriptions=[text(criteria[k]) if criteria[k] not in (None,'') else str(k) for k in keys]
choices=descriptions if len(set(descriptions))==len(keys) else list(map(str,keys))
instructions+='\n\nOptions:\n'+'\n'.join(f'{k}: {d}' for k,d in zip(keys,descriptions))
elif kind=='noul':
keys=['no','yes'];choices=keys.copy()
if criteria:
if not isinstance(criteria,dict):raise Unsupported('Noul criteria must be a mapping')
descriptions=[text(criteria.get(k,criteria.get(alias,k))) for k,alias in zip(keys,['false','true'])]
instructions+='\n\nCriteria:\n'+'\n'.join(f'{k}: {d}' for k,d in zip(keys,descriptions))
else:raise Unsupported('Unsupported question type '+str(kind))
if len(keys)>255:raise Unsupported('Declared maximum: 255 choices per question')
state=text(state)
row=dict(id='request',kind=kind,context='State:\n'+state+'\n\nQuestion:\n'+instructions,
choices=choices,probabilities=[0.]*len(keys))
return row,(state,instructions),keys
def answer(kind,keys,probabilities):
if kind=='noul':return dict(type='noul',noul=probabilities[1])
by_key=dict(zip(keys,probabilities))
return dict(type='choice',choice=max(by_key,key=by_key.get),probabilities=by_key)
class AranEngine(Engine):
name='aran1_step1'
latency='Serial request wall time, including rendering/tokenization, all supplied questions, encoding and flow; CUDA synchronized by the official runner.'
def __init__(self,model=MODEL,revision=REVISION,steps=1,seed=19031,device='cuda',**options):
super().__init__(model=model,revision=revision,steps=steps,seed=seed,device=device,**options)
import torch
from transformers import AutoModel,AutoTokenizer
if type(steps) is not int or steps<1:raise ValueError('steps must be a positive integer')
self.torch=torch;self.steps=steps;self.seed=seed
self.model=AutoModel.from_pretrained(model,revision=revision,trust_remote_code=True).to(device).eval().requires_grad_(False)
self.tokenizer=AutoTokenizer.from_pretrained(model,revision=revision,trust_remote_code=True)
self.tokenizer.flow_choice_marker_token_id=self.tokenizer.convert_tokens_to_ids('[OPT]')
package=self.model.__class__.__module__.rsplit('.',1)[0]
self.inference=importlib.import_module(package+'.inference')
self.name=f'aran1_step{steps}'
self.provenance=dict(model=model,revision=revision,parameters=sum(p.numel() for p in self.model.parameters()),
steps=steps,pruning=False,seed=seed,stored_dtype='float32',cuda_autocast='bfloat16',
max_packed_tokens=4096,question_placeholders_removed=4,max_choices=255,truncation=False,
adapter_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest())
def _pack(self,state,questions):
rows=[];sections=[];metadata=[]
for name,question in questions.items():
row,section,keys=request(state,question);rows.append(row);sections.append(section);metadata.append((name,question['type'],keys))
try:
packed=self.inference.tokenize_requests(rows,self.tokenizer,sections=sections,marker_slots=4,
question_context_first=True,clip_long_choices=False)
except ValueError as error:
if 'token budget' in str(error):raise Unsupported('Request exceeds the declared 4096 packed-token context limit') from error
raise
if any(entry[3] for entry in packed):raise Unsupported('Request exceeds the declared 4096 packed-token context limit; truncation disabled')
return packed,metadata
def __call__(self,state,questions):
torch=self.torch
if not questions:return {'model':self.name,'answers':{}},None
packed,metadata=self._pack(state,questions)
answers={}
# Keep independent questions serial: this is also the reproducible latency path.
with torch.inference_mode():
for entry,(name,kind,keys) in zip(packed,metadata):
ids,attention,positions,valid,_=self.inference.collate([entry],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:
logits=self.model(ids,attention,positions,choice_mask=valid,steps=self.steps,seed=self.seed).logits
probabilities=logits.float().softmax(-1)[0,:len(keys)].tolist()
answers[name]=answer(kind,keys,probabilities)
response=dict(model=self.name,answers=answers);validate(questions,response)
return response,None
def synchronize(self):
if self.model.device.type=='cuda':self.torch.cuda.synchronize(self.model.device)
def runtime(self):
import transformers
torch=self.torch
return dict(torch=torch.__version__,transformers=transformers.__version__,
device=str(self.model.device),gpu=torch.cuda.get_device_name(self.model.device) if self.model.device.type=='cuda' else None,
max_tokens=4096,max_options=255,truncation=False)
def close(self):
del self.model
if self.torch.cuda.is_available():self.torch.cuda.empty_cache()