jisue's picture
Experiment backup 2026-11-10T01:58:18.622752+00:00
0f5d220 verified
Raw History Blame Contribute Delete
13.6 kB
"""Explicit no-register adapter. OpenPI/HF-derived block algebra: Apache-2.0.
The original model is loaded before constructing this wrapper. No monkeypatch,
hooks, cache mutation, module-global state, or optimizer. All fast state is passed.
"""
import torch
from torch import nn
from transformers.models.gemma import modeling_gemma as mg
from transformers.masking_utils import create_causal_mask
from openpi.models_pytorch.pi0_pytorch import make_att_2d_masks
from .core import TTTLayer, TTTConfig
class ExpertTTT(nn.Module):
def __init__(self, model, indices):
super().__init__()
self.model=model
self.gate_zero=False
depth=len(model.paligemma_with_expert.gemma_expert.model.layers)
assert all(0<=i<depth for i in indices)
width=model.paligemma_with_expert.gemma_expert.config.hidden_size
self.ttt=nn.ModuleDict({str(i):TTTLayer(TTTConfig(dim=width,memory_dim=32,hidden_dim=64)).to(next(model.action_in_proj.parameters()).device) for i in indices})
self.eval()
def initial_state(self,batch=1):
return {k:m.initial_state(batch) for k,m in self.ttt.items()}
def insert(self,idx,x,incoming,candidate,enabled,differentiable,trace,taps):
key=str(idx)
if taps is not None:
taps.setdefault('layer_hidden', {})[key]=x.detach().cpu()
if not enabled or key not in self.ttt:return x
layer=self.ttt[key]
inner_trace={} if taps is not None else None
y,new=layer.step(x.float(),incoming[key],differentiable=differentiable,inner_trace=inner_trace)
if taps is not None:taps['inner_trace']=inner_trace
candidate[key]=new
# Core includes exactly one residual. Cast the complete sum back once.
result=(x.float() + 0.0*(y-x.float())).to(x.dtype) if self.gate_zero else y.to(x.dtype)
if trace is not None:
with torch.no_grad():
memory=layer.out(layer.fast(layer.q(x.float()),new.weights))
delta=torch.tanh(layer.alpha)*memory
trace.append({'layer':idx,'shape':list(x.shape),'input_dtype':str(x.dtype),
'gate_zero_override':self.gate_zero,
'memory_rms':float(memory.double().square().mean().sqrt()),
'gated_residual_rms':float(delta.double().square().mean().sqrt()),
'cast_output_max_difference':float((result.float()-x.float()).abs().max()),
'updates':new.updates.tolist()})
if taps is not None:
taps[key]={'input':x,'output':result,'candidate':new}
return result
def cached(self,suffix,mask,positions,cache,cond,incoming,*,enabled=True,differentiable=False,trace=None,taps=None):
expert=self.model.paligemma_with_expert.gemma_expert.model
candidate=dict(incoming) if enabled else incoming
cp=torch.arange(cache.get_seq_length(),cache.get_seq_length()+suffix.shape[1],device=suffix.device)
causal=create_causal_mask(config=expert.config,input_embeds=suffix,attention_mask=mask,
cache_position=cp,past_key_values=cache,position_ids=positions)
hidden=suffix.to(expert.layers[0].self_attn.q_proj.weight.dtype)
rope=expert.rotary_emb(hidden,positions)
for idx,layer in enumerate(expert.layers):
residual=hidden
hidden,gate=layer.input_layernorm(hidden,cond)
if taps is not None and idx==0:
shape=(*hidden.shape[:-1],-1,layer.self_attn.head_dim)
q=layer.self_attn.q_proj(hidden).view(shape).transpose(1,2)
k=layer.self_attn.k_proj(hidden).view(shape).transpose(1,2)
v=layer.self_attn.v_proj(hidden).view(shape).transpose(1,2)
q,k=mg.apply_rotary_pos_emb(q,k,*rope)
k=torch.cat([cache[idx][0],k],2);v=torch.cat([cache[idx][1],v],2)
taps['attention0']={n:z.detach().cpu() for n,z in {'q':q,'k':k,'v':v,'mask':causal}.items()}
hidden,_=layer.self_attn(hidden_states=hidden,attention_mask=causal,position_ids=positions,
past_key_value=cache,output_attentions=False,use_cache=False,
cache_position=cp,position_embeddings=rope)
if taps is not None and idx==17:
taps['attention_branch']=(hidden if gate is None else hidden*gate).detach().cpu()
taps['pre_attention_residual']=residual.detach().cpu()
if getattr(self,'ttt_insertion_point','after_attention_residual')=='before_attention_residual':
hidden=self.insert(idx,hidden,incoming,candidate,enabled,differentiable,trace,taps)
hidden=mg._gated_residual(residual,hidden,gate)
if getattr(self,'ttt_insertion_point','after_attention_residual')=='after_attention_residual':
hidden=self.insert(idx,hidden,incoming,candidate,enabled,differentiable,trace,taps)
residual=hidden
hidden,gate=layer.post_attention_layernorm(hidden,cond)
hidden=layer.mlp(hidden)
hidden=mg._gated_residual(residual,hidden,gate)
hidden,_=expert.norm(hidden,cond)
return hidden,candidate
def joint(self,prefix,suffix,mask,positions,cond,incoming,*,enabled=True,differentiable=False,trace=None,taps=None):
candidate=dict(incoming) if enabled else incoming
inputs=[prefix,suffix]
conditions=[None,cond]
for idx in range(len(self.model.paligemma_with_expert.gemma_expert.model.layers)):
inputs=self.joint_layer(idx,inputs,mask,positions,conditions,incoming,candidate,enabled,differentiable,trace,taps)
hidden,_=self.model.paligemma_with_expert.gemma_expert.model.norm(inputs[1],cond)
return hidden,candidate
def velocity(self,prepared,noisy,time,incoming,*,path='cached',enabled=True,differentiable=False,trace=None,taps=None):
p,pm,pa,state,cache=prepared
s,sm,sa,cond=self.model.embed_suffix(state,noisy,time)
if path=='joint':
pad=torch.cat([pm,sm],1);att=torch.cat([pa,sa],1)
mask=self.model._prepare_attention_masks_4d(make_att_2d_masks(pad,att))
pos=pad.cumsum(1)-1
s=s.to(p.dtype)
out,candidate=self.joint(p,s,mask,pos,cond,incoming,enabled=enabled,differentiable=differentiable,trace=trace,taps=taps)
else:
mask=torch.cat([pm[:,None,:].expand(-1,sm.shape[1],-1),make_att_2d_masks(sm,sa)],2)
mask=self.model._prepare_attention_masks_4d(mask)
pos=pm.sum(-1)[:,None]+sm.cumsum(1)-1
out,candidate=self.cached(s,mask,pos,cache,cond,incoming,enabled=enabled,differentiable=differentiable,trace=trace,taps=taps)
return self.model.action_out_proj(out[:,-self.model.config.action_horizon:].float()),candidate
@torch.no_grad()
def rollout_observation(self,prepared,noise,incoming,observation_index,*,enabled=True,num_steps=10):
# Hypothesis for this integration: every solver call reads the SAME incoming
# state; only the final candidate is committed, once per observation.
snapshots={k:tuple(w.clone() for w in s.weights) for k,s in incoming.items()}
x=noise;dt=torch.tensor(-1/num_steps,device=x.device);time=torch.tensor(1.,device=x.device)
calls=[];iteration=0;candidate=incoming
while time>=-dt/2:
trace=[]
v,candidate=self.velocity(prepared,x,time.expand(x.shape[0]),incoming,enabled=enabled,trace=trace)
if not bool(torch.isfinite(v).all()) or not all(bool(torch.isfinite(w).all()) for st in candidate.values() for w in st.weights):
raise FloatingPointError(f'Nonfinite observation={observation_index}, denoising_iteration={iteration}')
for k,s in incoming.items():
for a,b in zip(s.weights,snapshots[k]):assert torch.equal(a,b),'incoming mutated'
calls.append({'observation_index':observation_index,'denoising_iteration':iteration,'time':float(time),
'incoming_updates':{k:s.updates.tolist() for k,s in incoming.items()},'layers':trace})
x=x+dt*v;time+=dt;iteration+=1
committed={k:s.detach() for k,s in candidate.items()} if enabled else incoming
assert all(w.grad_fn is None and not w.requires_grad for s in committed.values() for w in s.weights)
return x,committed,{'observation_index':observation_index,'denoising_calls':iteration,
'commits':1 if enabled else 0,'calls':calls}
def joint_layer(self, layer_idx, inputs_embeds, attention_mask, position_ids, adarms_cond, incoming, candidate, enabled, differentiable, trace, taps):
models = [self.model.paligemma_with_expert.paligemma.language_model, self.model.paligemma_with_expert.gemma_expert.model]
query_states = []
key_states = []
value_states = []
gates = []
for i, hidden_states in enumerate(inputs_embeds):
layer = models[i].layers[layer_idx]
hidden_states, gate = layer.input_layernorm(hidden_states, cond=adarms_cond[i]) # noqa: PLW2901
gates.append(gate)
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, layer.self_attn.head_dim)
query_state = layer.self_attn.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
key_state = layer.self_attn.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
value_state = layer.self_attn.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
query_states.append(query_state)
key_states.append(key_state)
value_states.append(value_state)
# Concatenate and process attention
query_states = torch.cat(query_states, dim=2)
key_states = torch.cat(key_states, dim=2)
value_states = torch.cat(value_states, dim=2)
dummy_tensor = torch.zeros(
query_states.shape[0],
query_states.shape[2],
query_states.shape[-1],
device=query_states.device,
dtype=query_states.dtype,
)
cos, sin = self.model.paligemma_with_expert.paligemma.model.language_model.rotary_emb(dummy_tensor, position_ids)
query_states, key_states = mg.apply_rotary_pos_emb(
query_states, key_states, cos, sin, unsqueeze_dim=1
)
batch_size = query_states.shape[0]
scaling = self.model.paligemma_with_expert.paligemma.language_model.layers[layer_idx].self_attn.scaling
if taps is not None:
plen=inputs_embeds[0].shape[1]
taps.setdefault('joint_prefix_kv', {})[str(layer_idx)]=(key_states[:,:,:plen].detach().cpu(),value_states[:,:,:plen].detach().cpu())
if layer_idx==0:
taps['attention0']={n:z.detach().cpu() for n,z in {'q':query_states,'k':key_states,'v':value_states,'mask':attention_mask}.items()}
# Attention computation
att_output, _ = mg.eager_attention_forward(
self.model.paligemma_with_expert.paligemma.language_model.layers[layer_idx].self_attn,
query_states,
key_states,
value_states,
attention_mask,
scaling,
)
# Get head_dim from the current layer, not from the model
head_dim = self.model.paligemma_with_expert.paligemma.language_model.layers[layer_idx].self_attn.head_dim
att_output = att_output.reshape(batch_size, -1, 1 * 8 * head_dim)
# Process layer outputs
outputs_embeds = []
start_pos = 0
for i, hidden_states in enumerate(inputs_embeds):
layer = models[i].layers[layer_idx]
end_pos = start_pos + hidden_states.shape[1]
if att_output.dtype != layer.self_attn.o_proj.weight.dtype:
att_output = att_output.to(layer.self_attn.o_proj.weight.dtype)
out_emb = layer.self_attn.o_proj(att_output[:, start_pos:end_pos])
if taps is not None and i==1 and layer_idx==17:
taps['attention_branch']=(out_emb if gates[i] is None else out_emb*gates[i]).detach().cpu()
taps['pre_attention_residual']=hidden_states.detach().cpu()
# The comparison profile matches OpenTau's attention-branch insertion.
if i==1 and getattr(self,'ttt_insertion_point','after_attention_residual')=='before_attention_residual':
out_emb=self.insert(layer_idx,out_emb,incoming,candidate,enabled,differentiable,trace,taps)
# first residual
out_emb = mg._gated_residual(hidden_states, out_emb, gates[i]) # noqa: SLF001
if i == 1 and getattr(self,'ttt_insertion_point','after_attention_residual')=='after_attention_residual':
out_emb = self.insert(layer_idx, out_emb, incoming, candidate, enabled, differentiable, trace, taps)
after_first_residual = out_emb.clone()
out_emb, gate = layer.post_attention_layernorm(out_emb, cond=adarms_cond[i])
# Convert to bfloat16 if the next layer (mlp) uses bfloat16
if layer.mlp.up_proj.weight.dtype == torch.bfloat16:
out_emb = out_emb.to(dtype=torch.bfloat16)
out_emb = layer.mlp(out_emb)
# second residual
out_emb = mg._gated_residual(after_first_residual, out_emb, gate) # noqa: SLF001
outputs_embeds.append(out_emb)
start_pos = end_pos
return outputs_embeds