"""Heterogeneous LFM3 decoder stack with exact source-operation transport. Machine cells use the compiled circuit's original sparse ReLU/head operations. No SiLU approximation, normalization, widening or numerical conversion is added. Language cache indices remain those of the unmodified language layers. """ from collections import OrderedDict import inspect,weakref import torch from torch import nn from .computer.circuit import CompiledComputer,CircuitStage class MachineDecoderLayer(nn.Module): decoder_role='machine' def language_identity(self,hidden_states):return hidden_states class ComputerControlDecoderLayer(MachineDecoderLayer): decoder_role='computer_control' def __init__(self,computer): super().__init__();self.spec=computer.spec self.embedding=computer.embedding;self.output=computer.output;self.programs=computer.programs def forward(self,hidden_states=None,*,phase='language',args=(),kwargs=None): if phase=='language':return hidden_states port=self._port();kwargs=kwargs or {} if phase=='boot':return CompiledComputer.boot(port,*args,**kwargs) if phase=='embed':return CompiledComputer.embed(port,*args,**kwargs) raise ValueError('Unknown control phase: '+phase) class OrderedSparseDownProjection(nn.Module): """Exact w2 adapter: retain coefficient multiplication and scatter order.""" def __init__(self,data):super().__init__();self.data=data def forward(self,values,template): values=values*self.data.coefficient return torch.zeros_like(template).index_add_(1,self.data.output,values) class ExactGatedMLP(nn.Module): """LFM gated-MLP decomposition with exact ReLU/sparse projection adapters.""" def __init__(self,operation): super().__init__();self.w1=operation.b;self.w3=operation.a self.w2=OrderedSparseDownProjection(operation.data);self.activation=nn.ReLU() def forward(self,hidden_states,active): values=self.w3(hidden_states)*self.activation(self.w1(hidden_states)) return self.w2(values,hidden_states)*active[:,None] class ExactRecurrentAttention(nn.Module): """Exact memory attention adapter; persistent writes are source operations.""" def __init__(self,operation): super().__init__();self.spec=operation.spec;self.data=operation.data for name in operation.spec['maps']:self.add_module(name,getattr(operation,name)) def forward(self,x,state,active): d=self.data;memory,history=state;flat=torch.cat((x,history),dim=1) B,V=x.shape[0],d.khead.numel() q=self.q(flat).relu().reshape(B,-1,128)[:,d.khead] k=self.k(flat).relu().reshape(B,-1,128)[:,d.khead] v=self.v(flat).relu().reshape(B,V,128) z=self.z(flat).relu().reshape(B,V,128) a,beta=self.a(flat),self.b(flat)+d.bconst factor=torch.where(a==0,1.,torch.where(a==110,.5,0.)) updated=memory*factor[:,:,None,None];row=k.argmax(-1) write=(k.amax(-1)>0)&(beta==1) selector=torch.arange(128,device=x.device)[None,None,:]==row[:,:,None] updated=torch.where((write[:,:,None]&selector)[:,:,:,None],v[:,:,None,:],updated) memory.copy_(torch.where(active[:,None,None,None],updated,memory)) read=((q>0)[:,:,:,None]*memory).sum(2) reference=read[:,:,:2].square().sum(-1,keepdim=True) denominator=(reference/128.).sqrt() normalized=torch.where(reference>0,read/torch.where(denominator>0,denominator,1.),0.) delta=(normalized*z*d.oweight).reshape(B,-1) return torch.zeros_like(x).index_add_(1,d.output.flatten(),delta)*active[:,None] def commit_history(self,x,state,active): memory,history=state new_history=torch.cat((x,history[:,:2*x.shape[1]]),dim=1) history.copy_(torch.where(active[:,None],new_history,history)) class ComputerExecutionDecoderLayer(MachineDecoderLayer): decoder_role='computer_execution' def __init__(self,operations): super().__init__();self.stage_specs=[operation.spec for operation in operations];self.triton_widths={} self.operator_norm=nn.Identity();self.ffn_norm=nn.Identity();self.use_sandwich_norm=False head=next((op for op in operations if op.kind=='head'),None);ffn=next((op for op in operations if op.kind=='ffn'),None) self.self_attn=ExactRecurrentAttention(head) if head is not None else None self.feed_forward=ExactGatedMLP(ffn) if ffn is not None else None def forward(self,hidden_states,state=None,active=None,backend='torch',scratch=None,*,phase='language'): if active is None:return hidden_states if backend=='triton': for spec in self.stage_specs: view=StageAdapter(self,spec) if view.kind not in self.triton_widths:raise RuntimeError("Call circuit.prepare('triton') before CUDA capture.") view.widths=self.triton_widths[view.kind] hidden_states,_=CircuitStage.triton(view,hidden_states,state if view.kind=='head' else None,active,scratch) return hidden_states,state # Same operator/residual then gated-MLP/residual organization as LFM3. # Missing machine sublayers are pruned, not simulated with add-zero. if self.self_attn is not None: residual=hidden_states attention_output=self.self_attn(self.operator_norm(hidden_states),state,active) hidden_states=residual+attention_output self.self_attn.commit_history(residual,state,active) if self.feed_forward is not None: residual=hidden_states ffn_output=self.feed_forward(self.ffn_norm(hidden_states),active) hidden_states=residual+ffn_output return hidden_states,state class StageAdapter: """Parameter-free view for stable logical state names and program boot.""" def __init__(self,cell,spec):self.cell=cell;self.spec=spec;self.kind=spec['kind'];self.widths=None @property def data(self):return self.cell.feed_forward.w2.data if self.kind=='ffn' else self.cell.self_attn.data def __getattr__(self,name): if self.kind=='ffn' and name in ('a','b'):return getattr(self.cell.feed_forward,'w3' if name=='a' else 'w1') if self.kind=='head':return getattr(self.cell.self_attn,name) raise AttributeError(name) def logical_modules(self): for name in self.spec['maps']:yield name,getattr(self,name) yield 'data',self.data def prepare_triton(self): CircuitStage.prepare_triton(self);self.cell.triton_widths[self.kind]=self.widths class MemoryDecoderLayer(MachineDecoderLayer): decoder_role='memory' def __init__(self,ram,files):super().__init__();self.ram=ram;self.files=files def forward(self,hidden_states=None,*,phase='language',component='ram',method='forward',args=(),kwargs=None): if phase=='language':return hidden_states module=getattr(self,component) return module(*args,**(kwargs or {})) if method=='forward' else getattr(module,method)(*args,**(kwargs or {})) class ServiceDecoderLayer(MachineDecoderLayer): def __init__(self,module,role):super().__init__();self.payload=module;self.decoder_role=role def forward(self,hidden_states=None,*,phase='language',method='forward',args=(),kwargs=None): if phase=='language':return hidden_states return self.payload(*args,**(kwargs or {})) if method=='forward' else getattr(self.payload,method)(*args,**(kwargs or {})) class DecoderModelMixin: def forward(self,*args,execution_phase=None,**kwargs): if execution_phase is None or execution_phase=='language':return super().forward(*args,**kwargs) if args:raise ValueError('Machine execution uses explicit typed arguments') if execution_phase=='computer': state=kwargs.pop('computer_state') if kwargs:raise ValueError('Unexpected computer execution fields') # The original transition function calls the actual decoder cells # through the stage view. No separate computer module is retained. port=self._computer_port active=(state.current!=port.spec['halt'])&state.valid x=port.embed(state.current);scratch=torch.zeros_like(x) if port.backend=='triton' else None hi=0 for cell in self.layers[1:1+self.computer_block_count]: head=state.heads[hi] if cell.self_attn is not None else None x,_=cell(x,head,active,port.backend,scratch) hi+=cell.self_attn is not None out=port.output family=(x[:,out.family].round()*out.family_weight).sum(1).long() payload=(x[:,out.payload].round()*out.payload_weight).sum(1).long() f=family.clamp(0,port.embedding.start.numel()-1) valid=((family>=0)&(family=0)&(payload=p:return base+str(i-p)+'.'+tail if i==0:return 'computer.'+tail if 1<=i<=layout['computer_block_count']: kind='ffn' if tail.startswith('feed_forward.') else 'head' source=next(j for j,n in enumerate(layout['stage_to_decoder']) if n==i and layout['computer_stage_kinds'][j]==kind) if kind=='ffn': for before,after in [('feed_forward.w3.','a.'),('feed_forward.w1.','b.'),('feed_forward.w2.data.','data.')]: if tail.startswith(before):return 'computer.stages.'+str(source)+'.'+after+tail[len(before):] raise ValueError('Unmapped machine FFN tensor: '+key) assert tail.startswith('self_attn.');return 'computer.stages.'+str(source)+'.'+tail[len('self_attn.'):] for index,child,prefix in [(layout['memory_index'],'ram.','ram.'),(layout['memory_index'],'files.','files.'),(layout.get('bridge_index'),'payload.','ram_bridge.'),(layout['analytics_index'],'payload.','analytics.')]: if i==index and tail.startswith(child):return prefix+tail[len(child):] raise ValueError('Unmapped decoder tensor: '+key)