Text Classification
Transformers
Safetensors
English
aran_decision_flow
feature-extraction
custom_code
decision-model
flow-matching
multiple-choice
zero-shot-classification
Instructions to use TheHuggerFacer/Aran-1 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use TheHuggerFacer/Aran-1 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="TheHuggerFacer/Aran-1", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("TheHuggerFacer/Aran-1", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
File size: 4,032 Bytes
fa8c939 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | """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 cursor<len(order):
indices=[];longest=0
for index in order[cursor:cursor+self.max_batch]:
proposed=max(longest,len(packed[index][0]))
option_width=max(len(packed[i][1]) for i in indices+[index])
if indices and (proposed*(len(indices)+1)>self.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
|