eniairaph07's picture
Add validated Transformers runtime and concise generation example
7218492 verified
Raw History Blame Contribute Delete
13.7 kB
"""Fresh inference graph for the released current-recipe tensor namespace."""
import hashlib,json
from pathlib import Path
import torch
from torch import nn
from torch.nn import functional as F
from .linear_engine import LinearEngine
from . import operators as ops
from .mamba_scan import prepare_scan,scan
from .runtime import release_precision
ASSETS=Path(__file__).with_name('assets')
REPO='4E-AI/Fidel2.0-1B'
REVISION='e69e77199309ae5190aff36da58ead52fdfddc88'
def asset(name):return json.loads((ASSETS/name).read_text())
class FidelCore(nn.Module):
"""All released tensors, explicit current forward, no legacy backend."""
def __init__(self):
super().__init__()
self.release_config=asset('model_config.json')
inventory=asset('released_tensor_schema.json')
manifest=asset('weights_manifest.json')['tensors']
self.functional_seeds=inventory['functional_seeds']
self.linear_seeds=self.release_config['numerical_recipe']['linear_seeds']
if set(inventory['schema'])!=set(manifest):raise ValueError('Tensor schema differs from release manifest')
for name,spec in inventory['schema'].items():
if spec['shape']!=manifest[name]['shape']:raise ValueError('Tensor shape differs from release')
path,leaf=name.rsplit('.',1)
node=self
for part in path.split('.'):
if part not in node._modules:node.add_module(part,nn.Module())
node=node._modules[part]
value=torch.empty(spec['shape'],dtype=getattr(torch,manifest[name]['dtype']))
if spec['buffer']:node.register_buffer(leaf,value)
else:node.register_parameter(leaf,nn.Parameter(value,requires_grad=False))
object.__setattr__(self,'engine',LinearEngine())
self.eval()
def tensor(self,name):
node=self
parts=name.split('.')
for part in parts[:-1]:node=node._modules[part]
return getattr(node,parts[-1])
def linear(self,x,name,*,seed=None,bridge=False,transpose=False):
w=self.tensor(name)
if transpose:w=w.T
if seed is None:seed=self.functional_seeds[name]
return self.engine(x,w,name=name+('/T' if transpose else ''),seed=seed,bridge=bridge)
def module_linear(self,x,name):
return self.linear(x,name+'.weight',seed=self.linear_seeds.get(name,0))
def norm(self,x,name):return ops.rmsnorm(x,self.tensor(name+'.weight'))
def mamba(self,u,index,trace=None,projected=None):
prefix=f'model.layers.{index}.mixer.mamba'
live=u.shape[1]
padded=F.pad(u,(0,0,0,(-live)%16))
packed=self.module_linear(padded,prefix+'.in_proj') if projected is None else projected
if trace is not None:trace['projected']=packed
z,v,b,c,dd_dt,dd_a,trap,angles=torch.split(packed,[3072,3072,256,256,48,48,48,16],-1)
size=packed.shape[1]
z=z.reshape(1,size,48,64);v=v.reshape_as(z)
b=b.reshape(1,size,4,1,64);c=c.reshape_as(b)
a=dd_a.float()
a=-(a.clamp_min(0)+torch.reciprocal(1-a.clamp_max(0)))
a=a.clamp_max(-1e-4)
dt=F.softplus(dd_dt+self.tensor(prefix+'.dt_bias'))
adt=(a*dt).transpose(1,2)
dt=dt.transpose(1,2)
angles=angles.unsqueeze(-2).expand(-1,-1,48,-1).float()
b=ops.bc_norm(b,self.tensor(prefix+'.B_norm.weight'))
c=ops.bc_norm(c,self.tensor(prefix+'.C_norm.weight'))
prepared=prepare_scan(adt,dt,angles)
active_cache=getattr(self,'_active_cache',None)
execute_scan=scan if active_cache is None or active_cache.mode!='chunk_state' else active_cache.scan_for(index,live)
result=execute_scan(c,b,v,q_bias=self.tensor(prefix+'.C_bias'),k_bias=self.tensor(prefix+'.B_bias'),
mimo_v=self.tensor(prefix+'.mimo_x'),mimo_o=self.tensor(prefix+'.mimo_o'),
mimo_z=self.tensor(prefix+'.mimo_z'),z=z,d=self.tensor(prefix+'.D'),
dt=dt,trap=trap.transpose(1,2),prepared=prepared)
value=result.output.reshape(1,size,3072)
output=self.module_linear(value,prefix+'.out_proj')[:,:live]
if trace is not None:
trace.update(b=b,c=c,dt=dt,adt=adt,raw_angles=angles,scan=value,projected_output=output,
angle_state=prepared['angle_state'],state=result.state,last_key=result.last_key)
return output
def mamba_block(self,x,index,trace=None):
backend=torch.backends.cuda.matmul
previous=backend.allow_bf16_reduced_precision_reduction
try:
if x.is_cuda:backend.allow_bf16_reduced_precision_reduction=False
u=self.norm(x,f'model.layers.{index}.mixer.norm')
if trace is not None:trace['normalized']=u
output=x+self.mamba(u.to(torch.bfloat16),index,trace).to(x.dtype)
if trace is not None:trace['output']=output
return output
finally:
if x.is_cuda:backend.allow_bf16_reduced_precision_reduction=previous
def delta(self,x,prefix):
return self.linear(self.linear(x,prefix+'.down'),prefix+'.up')
def attention_block(self,x,index=7,cache=None):
prefix=f'model.layers.{index}.mixer'
u=self.norm(x,prefix+'.norm')
q=self.linear(u,prefix+'.q_proj.weight')+self.delta(u,f'updates.q_{index}')
k=self.linear(u,prefix+'.k_proj.weight')
v=self.linear(u,prefix+'.v_proj.weight')+self.delta(u,f'updates.v_{index}')
q=q.reshape(1,-1,16,96);k=k.reshape(1,-1,4,96);v=v.reshape_as(k)
q,k=ops.rotary(q,k)
q=q.transpose(1,2);k=k.repeat_interleave(4,2).transpose(1,2);v=v.repeat_interleave(4,2).transpose(1,2)
active_cache=getattr(self,'_active_cache',None)
if active_cache is not None:
out=active_cache.attend(q,k,v).transpose(1,2).reshape_as(x)
return x+self.linear(out,prefix+'.o_proj.weight')
rows=[]
# This is the released InternalChat attention path, which uses an
# explicit causal row loop rather than its mixer's standalone SDPA.
for pos in range(x.shape[1]):
rows.append(ops.causal_attention_row(q[:,:,pos:pos+1],k[:,:,:pos+1],v[:,:,:pos+1])[2])
out=torch.cat(rows,2).transpose(1,2).reshape_as(x)
return x+self.linear(out,prefix+'.o_proj.weight')
def moe(self,x,index,trace=None):
prefix=f'model.layers.{index}.moe'
u=self.norm(x,prefix+'.norm')
logits=self.module_linear(u,prefix+'.router').to(torch.float16)
latent=self.linear(u,prefix+'.w_down.weight',seed=0,bridge=True).to(u.dtype).clamp(-1e4,1e4)
masked=ops.route_top2(logits,self.tensor(prefix+'.noise_weight'))
tokens,probs,counts=ops.expert_dispatch(masked)
dispatched=latent[tokens.long()]
outputs=[]
for expert in range(16):
if int(counts[expert])==0:
outputs.append(torch.zeros_like(dispatched[expert],dtype=torch.bfloat16));continue
rows=dispatched[expert].float()
def expert_linear(value,name,seed):
return self.engine(value,self.tensor(prefix+'.'+name)[expert].T.float(),
name=f'{prefix}.{name}/{expert}',seed=seed+expert,bridge=True)
h1=expert_linear(rows,'w_fc1',1000);hg=expert_linear(rows,'w_gate',2000)
hidden=ops.swiglu(torch.stack((h1,hg),-1).flatten(-2).to(torch.bfloat16))
outputs.append(expert_linear(hidden.float(),'w_fc2',3000).to(torch.bfloat16))
expert_sum=ops.recombine(torch.stack(outputs),tokens,probs,x.shape[0]).to(latent.dtype)
packed=self.linear(u.float(),prefix+'.shared_fc1_gate',seed=4000).to(torch.bfloat16)
shared_hidden=ops.swiglu(packed)
shared=self.linear(shared_hidden.float(),prefix+'.shared_fc2',seed=5000).to(x.dtype)
out=self.linear(expert_sum.to(x.dtype),prefix+'.w_up.weight',seed=0,bridge=True)+shared
out=out.nan_to_num(nan=0.,posinf=1e4,neginf=-1e4)
if trace is not None:trace.update(normalized=u,router_logits=logits,latent=latent,masked=masked,
expert_sum=expert_sum,shared=shared,output=x+out)
return x+out
def adapter(self,x,index):
prefix=f'model.layer_adapters.{index}'
def branch(name):
hidden=self.linear(x.float(),prefix+'.'+name+'.down')
return self.linear(F.silu(hidden),prefix+'.'+name+'.up').to(x.dtype)
return branch('base')+branch('delta')
def block(self,x,index,trace=None):
base=self.attention_block(x,index) if index==7 else self.mamba_block(x,index,trace)
value=self.moe(base.reshape(-1,1536),index).reshape_as(base)
value=value+self.adapter(x,index)
if index in (7,8):value=value+self.delta(x,f'updates.block_{index}')
return value
def hidden(self,ids,trace=None):
x=F.embedding(ids,self.tensor('model.embed.weight'))
for index in range(9):
x=self.block(x,index)
if trace is not None:trace[f'block{index}']=x.detach().clone()
return self.norm(x,'model.norm_f')
def cross(self,x,prompt,prefix):
query=self.linear(x.float(),prefix+'.q_proj')
keys=self.linear(prompt.float(),prefix+'.k_proj')
values=self.linear(prompt.float(),prefix+'.v_proj')
rank=query.shape[-1];rows=query.reshape(-1,rank);outputs=[]
for start in range(0,len(rows),128):
block=rows[start:start+128]
padded=F.pad(block,(0,0,0,128-len(block)))
context=ops.prompt_cross_products(padded,keys,values)[2]
outputs.append(context[:len(block)])
context=torch.cat(outputs).reshape_as(query)
return x+self.linear(F.silu(context),prefix+'.out_proj').to(x.dtype)
@release_precision()
def logits(self,ids,prompt_length,trace=None):
if self.training or torch.is_grad_enabled():raise RuntimeError('Use torch.inference_mode() with this inference graph')
if ids.ndim!=2 or ids.shape[0]!=1 or not 1<=prompt_length<=ids.shape[1]<=8192:
raise ValueError('One nonempty request within the released context is required')
hidden=self.hidden(ids,trace)
value=hidden[0,prompt_length-1:]
prompt=F.embedding(ids[0,:prompt_length],self.tensor('model.embed.weight'))
for name in ('prompt_cross_conditioner','contextual_prompt_v7','contextual_prompt_v8','contextual_prompt_v9'):
value=self.cross(value,prompt,'model.'+name)
residual=self.module_linear(value,'output.0').tanh()
value=value+self.module_linear(residual,'output.2')
value=self.cross(value,prompt,'chat_prompt')
base=self.module_linear(value,'model.lm_head.base').float()
update=self.linear(self.linear(value.float(),'model.lm_head.lora_a'),'model.lm_head.lora_b')
result=base+update
if trace is not None:trace.update(normalized_hidden=hidden,conditioned=value,logits=result)
return result.float()
def load_core(folder,device='cuda',verify=True):
from safetensors.torch import load_file
folder=Path(folder);manifest=asset('weights_manifest.json')
weights=folder/'model.safetensors';whole_file_verified=False
if weights.exists():
files=[weights]
if verify and weights.stat().st_size==manifest['weight_file']['bytes']:
digest=hashlib.sha256()
with weights.open('rb') as stream:
for chunk in iter(lambda:stream.read(8*1024*1024),b''):digest.update(chunk)
whole_file_verified=digest.hexdigest()==manifest['weight_file']['sha256']
else:
index=json.loads((folder/'model.safetensors.index.json').read_text())
names=sorted(set(index['weight_map'].values()))
if not names or any(not isinstance(name,str) or Path(name).name!=name or '/' in name or chr(92) in name for name in names):
raise ValueError('Invalid safetensors shard names')
if set(index['weight_map'])!=set(manifest['tensors']):raise ValueError('Shard index differs from the release tensor namespace')
files=[folder/name for name in names]
state={}
for file in files:
values=load_file(str(file),device='cpu')
if state.keys()&values.keys():raise ValueError('Duplicate tensor across shards')
state.update(values)
if set(state)!=set(manifest['tensors']):raise ValueError('Stored tensor namespace differs from the release')
for name,value in state.items():
expected=manifest['tensors'][name]
if str(value.dtype).split('.')[-1]!=expected['dtype'] or list(value.shape)!=expected['shape']:
raise ValueError('Stored tensor shape or dtype differs')
if verify and not whole_file_verified:
raw=value.contiguous().reshape(-1).view(torch.uint8).numpy()
if hashlib.sha256(raw).hexdigest()!=expected['sha256']:
raise ValueError('Stored tensor bytes differ: '+name)
with torch.device('meta'):model=FidelCore()
model.load_state_dict(state,strict=True,assign=True)
del state
model.to(device);model.eval()
model._weight_receipt={'strict':True,'tensor_count':359,'shards':len(files),
'whole_original_file_verified':whole_file_verified,
'all_original_tensor_bytes_verified':bool(verify)}
return model