"""Portable14-layer typed-decision runtime. No project-local imports or text generation.""" import importlib.metadata import json import math import threading import types from pathlib import Path import torch from torch import nn from safetensors.torch import load_file from transformers import AutoModelForCausalLM, AutoTokenizer class Unsupported(ValueError): pass def text(value): return value if isinstance(value,str) else json.dumps(value,ensure_ascii=False,separators=(',',':')) class Pointer(nn.Module): def __init__(self,dim=1024,width=256): super().__init__();self.na=nn.LayerNorm(dim);self.nn_=nn.LayerNorm(dim) self.q=nn.Linear(dim,width);self.k=nn.Linear(dim,width);self.last=nn.Parameter(torch.zeros(1),requires_grad=False) def forward(self,answer,options): scores=(self.q(self.na(answer))*self.k(self.nn_(options))).sum(-1)/math.sqrt(self.q.out_features) scores=scores.clone();scores[-1]+=self.last[0] return scores class ResidualLoRA(nn.Module): """Keep the effective3-seed weight mean unmerged to preserve reference BF16 operations.""" def __init__(self,base,a,b,scale): super().__init__();self.base=base;self.scale=float(scale) self.register_buffer('A',a.to(base.weight.device));self.register_buffer('B',b.to(base.weight.device)) def forward(self,x): return self.base(x)+(x@self.A.to(x.dtype).t())@self.B.to(x.dtype).t()*self.scale def enable_stateonly(model): """State queries read prefix+all state; all other queries and GDN remain causal. Qwen attention projection/rotary/gating operations follow Transformers5.8.0 (Hugging Face, Apache-2.0); state-span overwrite is the trained s014 convention. """ from transformers.models.qwen3_5 import modeling_qwen3_5 as mq from transformers.integrations.sdpa_attention import sdpa_attention_forward for layer in model.model.layers: if layer.layer_type!='full_attention':continue attn=layer.self_attn def forward(self,hidden_states,position_embeddings,attention_mask,past_key_values=None,state_spans=None,**kwargs): if past_key_values is not None:raise Unsupported('State-only profile does not use prefix caches') if state_spans is None or len(state_spans)!=hidden_states.shape[0]:raise ValueError('Missing state spans') input_shape=hidden_states.shape[:-1];hidden_shape=(*input_shape,-1,self.head_dim) query,gate=torch.chunk(self.q_proj(hidden_states).view(*input_shape,-1,self.head_dim*2),2,dim=-1) gate=gate.reshape(*input_shape,-1) query=self.q_norm(query.view(hidden_shape)).transpose(1,2) key=self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1,2) value=self.v_proj(hidden_states).view(hidden_shape).transpose(1,2) query,key=mq.apply_rotary_pos_emb(query,key,*position_embeddings) dropout=0.0 if not self.training else self.attention_dropout causal,_=sdpa_attention_forward(self,query,key,value,attention_mask,dropout=dropout,scaling=self.scaling,**kwargs) pieces=[] for b,(start,end) in enumerate(state_spans): start,end=int(start),int(end) if not 0<=start<=end<=hidden_states.shape[1]:raise ValueError('Invalid state span') if end<=start:pieces.append(None);continue part,_=sdpa_attention_forward(self,query[b:b+1,:,start:end],key[b:b+1,:,:end],value[b:b+1,:,:end],None, dropout=dropout,scaling=self.scaling,is_causal=False) pieces.append(part[0]) output=torch.stack([causal[b] if pieces[b] is None else torch.cat([causal[b,:start],pieces[b].to(causal.dtype),causal[b,end:]],0) for b,(start,end) in enumerate(state_spans)],0) output=output.reshape(*input_shape,-1).contiguous()*torch.sigmoid(gate) return self.o_proj(output),None attn.forward=types.MethodType(forward,attn) class DecisionModel: def __init__(self,model,revision=None,device='cuda',mem_gb=None): if importlib.metadata.version('transformers')!='5.8.0': raise RuntimeError('This reference profile requires transformers==5.8.0; use operator/requirements.txt') if not torch.cuda.is_available():raise RuntimeError('The validated profile requires an NVIDIA CUDA GPU') for name in ['flash-linear-attention','fla-core']: if importlib.metadata.version(name)!='0.5.2':raise RuntimeError(f'Requires {name}==0.5.2') self.device=torch.device(device) if self.device.type!='cuda':raise RuntimeError('Only the validated CUDA profile is enabled') if self.device.index is None:self.device=torch.device('cuda',torch.cuda.current_device()) torch.set_num_threads(2);torch.backends.cuda.matmul.allow_tf32=False if mem_gb is not None:torch.cuda.set_per_process_memory_fraction(float(mem_gb)*2**30/torch.cuda.get_device_properties(self.device).total_memory,self.device) directory=Path(model) if not directory.is_dir(): from huggingface_hub import snapshot_download directory=Path(snapshot_download(model,revision=revision,allow_patterns=['*.json','*.safetensors','tokenizer*','chat_template.jinja'])) self.directory=directory self.spec=json.loads((directory/'operator_config.json').read_text()) self.model_id=self.spec['model_id'];self.depth=int(self.spec['layers']);self.attention=self.spec['attention'];self.lock=threading.Lock() if self.depth!=14 or self.attention not in ['causal','stateonly']:raise ValueError('Unrecognized checkpoint profile') # Match the measured profile even on hosts that have optional causal-conv installed. from transformers.models.qwen3_5 import modeling_qwen3_5 as mq if mq.FusedRMSNormGated is None or mq.chunk_gated_delta_rule is None:raise RuntimeError('FLA kernels unavailable; install pinned requirements') mq.causal_conv1d_fn=None;mq.causal_conv1d_update=None;mq.is_fast_path_available=False self.tok=AutoTokenizer.from_pretrained(directory,local_files_only=True,trust_remote_code=False) self.model=AutoModelForCausalLM.from_pretrained(directory,dtype=torch.bfloat16,attn_implementation='sdpa', local_files_only=True,trust_remote_code=False,device_map=None) self.model.model.layers=nn.ModuleList(list(self.model.model.layers)[:self.depth]) for config in [self.model.config,self.model.model.config]: config.num_hidden_layers=self.depth;config.layer_types=list(config.layer_types)[:self.depth];config.use_cache=False self.model.requires_grad_(False);self.model.to(self.device).eval() self.head=Pointer().to(self.device) self.head.load_state_dict(load_file(str(directory/self.spec['head']),device=str(self.device))) self.head.requires_grad_(False).eval() adapter_file=self.spec.get('adapter') if adapter_file: weights=load_file(str(directory/adapter_file),device='cpu');names=self.spec['adapter_modules'] expected={name+'.'+part for name in names for part in ['A','B']} if set(weights)!=expected:raise ValueError('Adapter tensor names do not match checkpoint profile') for name in names: layer,path=name.split('.',1);block=self.model.model.layers[int(layer)];parent,_,child=path.rpartition('.') owner=block.get_submodule(parent) if parent else block;base=getattr(owner,child) if not isinstance(base,nn.Linear):raise ValueError('Adapter base is not a linear projection') a,b=weights[name+'.A'],weights[name+'.B'] if a.shape[1]!=base.in_features or b.shape!=(base.out_features,a.shape[0]):raise ValueError('Adapter shape mismatch') setattr(owner,child,ResidualLoRA(base,a,b,self.spec['adapter_scale'])) if self.attention=='stateonly':enable_stateonly(self.model) # Same frozen CPU lookup as the reference evaluator, with unchanged BF16 values. embedding=self.model.model.get_input_embeddings();embedding.to('cpu') if self.model.config.tie_word_embeddings:self.model.lm_head.weight=embedding.weight native_forward=type(embedding).forward;target_device=self.device def lookup(module,ids):return native_forward(module,ids.to('cpu')).to(target_device) embedding.forward=types.MethodType(lookup,embedding) template=self.tok.apply_chat_template([{'role':'user','content':'__BODY__'}],tokenize=False,add_generation_prompt=True,enable_thinking=False) self.pre,self.post=template.split('__BODY__') self.max_tokens=int(self.model.config.max_position_embeddings) def render(self,state,question): kind=question.get('type');q=dict(question) if kind=='score': levels=q.get('criteria') if not isinstance(levels,list) or not levels:raise Unsupported('score.criteria must be a nonempty ordered list') q=dict(type='choice',instructions=q.get('instructions',''),criteria={str(i):v for i,v in enumerate(levels)}) if q.get('type')=='choice': criteria=q.get('criteria') if not isinstance(criteria,dict) or not criteria:raise Unsupported('choice.criteria must be a nonempty object') if not all(isinstance(k,str) for k in criteria):raise Unsupported('Option IDs must be strings') items=[(k,k if v is None else text(v)) for k,v in criteria.items()] elif q.get('type')=='noul': c=q.get('criteria') if isinstance(q.get('criteria'),dict) else {} items=[('true',text(c.get('true','True'))),('false',text(c.get('false','False')))] else:raise Unsupported('Supported question types: noul,choice,score') stxt=text(state) if state not in ('',None,{},[]) else '(empty)' body=['State:',stxt,'','Question:',text(q.get('instructions','')),'','Options:'] body += [f'[{i+1}] {key}: {desc}' for i,(key,desc) in enumerate(items)] body += ['','Select one option. Answer only with its bracketed numeric identifier.'] prompt=self.pre+'\n'.join(body)+self.post+'Best answer: [' encoded=self.tok(prompt,add_special_tokens=False,return_offsets_mapping=True);offsets=encoded['offset_mapping'] if len(encoded['input_ids'])>self.max_tokens:raise Unsupported('Context limit exceeded; inputs are never truncated') end=len(self.pre+'\n'.join(body[:body.index('Options:')+1]))+1;pos=[];j=0 for i,(key,desc) in enumerate(items): end+=len(f'[{i+1}] {key}: {desc}') while not offsets[j][0]<=endstart) last=max(i for i,(a,b) in enumerate(offsets) if aa) if offsets[first][0]question_start:raise ValueError('State/token boundary invariant failed') return dict(ids=encoded['input_ids'],positions=pos,keys=[k for k,_ in items],span=(first,last+1),kind=kind) @torch.inference_mode() def predict_one(self,state,question): record=self.render(state,question);ids=torch.tensor([record['ids']],device=self.device);kw={} if self.attention=='stateonly':kw['state_spans']=[record['span']] with torch.autocast('cuda',dtype=torch.bfloat16): h=self.model.model(input_ids=ids,attention_mask=torch.ones_like(ids),use_cache=False,**kw).last_hidden_state[0] z=self.head(h[-1].float(),h[torch.tensor(record['positions'],device=self.device)].float()) values=z.float().softmax(-1).cpu().tolist();p=dict(zip(record['keys'],values)) if any(not math.isfinite(v) or v<0 for v in values) or abs(sum(values)-1)>1e-4:raise RuntimeError('Invalid model probabilities') if record['kind']=='noul':answer={'type':'noul','noul':p['true']} elif record['kind']=='score':answer={'type':'score','score':sum(int(k)*v for k,v in p.items()),'probabilities':p} else:answer={'type':'choice','choice':max(p,key=p.get),'probabilities':p} return answer,len(record['ids']) def predict(self,state,questions): if not isinstance(questions,dict) or not questions:raise Unsupported('questions must be a nonempty object') if not all(isinstance(k,str) and isinstance(q,dict) for k,q in questions.items()):raise Unsupported('Invalid question entries') with self.lock: answers={};count=0 for key,q in questions.items(): answer,n=self.predict_one(state,q);answers[key]=answer;count+=n return {'model':self.model_id,'answers':answers,'usage':{'input_tokens':count,'output_tokens':0}}