File size: 11,650 Bytes
b4ca4a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
"""Decoder capacity/routing variants for strict local-wrist Stereo-ACT.

Both variants retain frozen DINOv3 + DeFM and the 30x40 RGB->depth
cross_relbias front end from StereoACT.  They use only current local wrist
RGB-D tokens and local qpos; no task/agent ID, language, peer, or global view.
"""
from __future__ import annotations
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from train_stereo_act import StereoACT


class _Expert(nn.Module):
    def __init__(self, d_model, ffn_dim, dropout):
        super().__init__()
        self.net = nn.Sequential(nn.Linear(d_model, ffn_dim), nn.GELU(), nn.Dropout(dropout),
                                 nn.Linear(ffn_dim, d_model), nn.Dropout(dropout))
    def forward(self, x): return self.net(x)


class Top2SparseMoE(nn.Module):
    """Four FFN experts; each local decoder token selects exactly top-2."""
    def __init__(self, d_model, ffn_dim, experts=4, dropout=.1):
        super().__init__(); self.experts_n = experts
        self.router = nn.Linear(d_model, experts, bias=False)
        self.experts = nn.ModuleList([_Expert(d_model, ffn_dim, dropout) for _ in range(experts)])

    def forward(self, x):
        shape, flat = x.shape, x.reshape(-1, x.shape[-1])
        logits = self.router(flat)
        top_logits, top_ids = logits.topk(2, dim=-1)
        gates = top_logits.softmax(-1)
        out = torch.zeros_like(flat)
        for expert_id, expert in enumerate(self.experts):
            chosen = (top_ids == expert_id).nonzero(as_tuple=False)
            if chosen.numel() == 0: continue
            token_ids, slots = chosen[:, 0], chosen[:, 1]
            y = expert(flat.index_select(0, token_ids))
            out.index_add_(0, token_ids, y * gates[token_ids, slots].unsqueeze(-1))
        # Switch-style differentiable importance/load balancing; its minimum is one.
        importance = logits.softmax(-1).mean(0)
        load = torch.bincount(top_ids.reshape(-1), minlength=self.experts_n).to(flat.dtype) / (2.0 * flat.shape[0])
        aux = self.experts_n * (importance * load).sum()
        return out.reshape(shape), aux


class MoEDecoderLayer(nn.Module):
    def __init__(self, d_model, heads=8, ffn_dim=None, dropout=.1, experts=4):
        super().__init__(); ffn_dim = ffn_dim or 4*d_model
        self.self_attn = nn.MultiheadAttention(d_model, heads, dropout=dropout, batch_first=True)
        self.cross_attn = nn.MultiheadAttention(d_model, heads, dropout=dropout, batch_first=True)
        self.norm1, self.norm2, self.norm3 = nn.LayerNorm(d_model), nn.LayerNorm(d_model), nn.LayerNorm(d_model)
        self.drop1, self.drop2 = nn.Dropout(dropout), nn.Dropout(dropout)
        self.moe = Top2SparseMoE(d_model, ffn_dim, experts=experts, dropout=dropout)

    def forward(self, x, memory):
        x = x + self.drop1(self.self_attn(self.norm1(x), self.norm1(x), self.norm1(x), need_weights=False)[0])
        x = x + self.drop2(self.cross_attn(self.norm2(x), memory, memory, need_weights=False)[0])
        ff, aux = self.moe(self.norm3(x)); return x + ff, aux


class MoEDecoder(nn.Module):
    def __init__(self, d_model, layers=7, experts=4, dropout=.1):
        super().__init__(); self.layers = nn.ModuleList([MoEDecoderLayer(d_model, dropout=dropout, experts=experts) for _ in range(layers)])
    def forward(self, x, memory):
        aux = x.new_zeros(())
        for layer in self.layers:
            x, value = layer(x, memory); aux = aux + value
        return x, aux / len(self.layers)


class StereoFFNMoE(StereoACT):
    """Stereo front end + top-2 four-expert FFN replacement in every decoder block."""
    def __init__(self, *args, experts=4, **kwargs):
        super().__init__(*args, **kwargs)
        self.experts_n = experts
        self.decoder = MoEDecoder(self.query.shape[-1], layers=len(self.decoder.layers), experts=experts)

    def forward(self, image, depth_mm, qpos, actions=None):
        x = self._rgbd_tokens(image, depth_mm); state = self.state(qpos).unsqueeze(1)
        if actions is not None:
            h = self.posterior(self.action(actions) + self.pos)
            mu, logvar = self.latent(h.mean(1)).chunk(2, -1); z = mu + torch.randn_like(mu) * torch.exp(.5 * logvar)
        else:
            mu = logvar = None; z = torch.zeros((image.shape[0], self.z_proj.in_features), device=image.device)
        memory = torch.cat((state, self.z_proj(z).unsqueeze(1), x), dim=1)
        decoded, aux = self.decoder(self.query.expand(image.shape[0], -1, -1), memory)
        return self.out(decoded), mu, logvar, aux


class RoleCrossAdapter(nn.Module):
    """Small role-specific cross-attention from one action query to current observation tokens."""
    def __init__(self, d_model, rank=32):
        super().__init__()
        self.q = nn.Linear(d_model, rank, bias=False); self.k = nn.Linear(d_model, rank, bias=False)
        self.v = nn.Linear(d_model, rank, bias=False); self.out = nn.Linear(rank, d_model, bias=False)
        self.rank = rank
    def forward(self, query, observation):
        scores = torch.matmul(self.q(query), self.k(observation).transpose(-1, -2)) / math.sqrt(self.rank)
        return self.out(torch.matmul(scores.softmax(-1), self.v(observation)))


class ARCADecoderLayer(nn.Module):
    def __init__(self, d_model, roles=4, rank=32, heads=8, dropout=.1):
        super().__init__(); ffn = 4*d_model
        self.self_attn = nn.MultiheadAttention(d_model, heads, dropout=dropout, batch_first=True)
        self.cross_attn = nn.MultiheadAttention(d_model, heads, dropout=dropout, batch_first=True)
        self.norm1, self.norm2, self.norm3 = nn.LayerNorm(d_model), nn.LayerNorm(d_model), nn.LayerNorm(d_model)
        self.drop1, self.drop2 = nn.Dropout(dropout), nn.Dropout(dropout)
        self.ff = _Expert(d_model, ffn, dropout)
        self.adapters = nn.ModuleList([RoleCrossAdapter(d_model, rank) for _ in range(roles)])

    def forward(self, x, memory, observation, gates):
        x = x + self.drop1(self.self_attn(self.norm1(x), self.norm1(x), self.norm1(x), need_weights=False)[0])
        h = self.norm2(x)
        base = self.cross_attn(h, memory, memory, need_weights=False)[0]
        role = torch.zeros_like(base)
        for role_id, adapter in enumerate(self.adapters):
            role = role + gates[..., role_id:role_id+1] * adapter(h, observation)
        x = x + self.drop2(base + role)
        return x + self.ff(self.norm3(x))


class ARCADecoder(nn.Module):
    def __init__(self, d_model, layers=7, roles=4, rank=32, dropout=.1):
        super().__init__(); self.layers = nn.ModuleList([ARCADecoderLayer(d_model, roles, rank, dropout=dropout) for _ in range(layers)])
    def forward(self, x, memory, observation, gates):
        for layer in self.layers: x = layer(x, memory, observation, gates)
        return x


class StereoARCA(StereoACT):
    """Action-role conditioned observation cross-attention inside every decoder layer."""
    def __init__(self, *args, roles=4, role_rank=32, **kwargs):
        super().__init__(*args, **kwargs)
        d = self.query.shape[-1]; self.roles_n, self.role_rank = roles, role_rank
        self.decoder = ARCADecoder(d, layers=len(self.decoder.layers), roles=roles, rank=role_rank)
        self.route_state, self.route_observation = nn.Linear(d, d, bias=False), nn.Linear(d, d, bias=False)
        self.route_mlp = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, d), nn.GELU(), nn.Linear(d, d, bias=False))
        self.role_prototypes = nn.Parameter(torch.randn(roles, d) * .02)

    def _route(self, state, observation, batch):
        # This deliberately excludes ACT's posterior z: z is zero at deployment.
        q = self.query.expand(batch, -1, -1)
        context = self.route_state(state) + self.route_observation(observation.mean(1))
        features = self.route_mlp(q + context.unsqueeze(1))
        logits = torch.matmul(features, self.role_prototypes.t()) / math.sqrt(features.shape[-1])
        values, ids = logits.topk(2, dim=-1); gates = torch.zeros_like(logits).scatter_(-1, ids, values.softmax(-1).to(logits.dtype))
        importance = logits.softmax(-1).mean((0, 1))
        load = (gates.gt(0).to(logits.dtype).mean((0, 1)) / 2.0)
        aux = self.roles_n * (importance * load).sum()
        return gates, aux

    def forward(self, image, depth_mm, qpos, actions=None):
        x = self._rgbd_tokens(image, depth_mm); state_vec = self.state(qpos); state = state_vec.unsqueeze(1)
        gates, aux = self._route(state_vec, x, image.shape[0])
        if actions is not None:
            h = self.posterior(self.action(actions) + self.pos)
            mu, logvar = self.latent(h.mean(1)).chunk(2, -1); z = mu + torch.randn_like(mu) * torch.exp(.5 * logvar)
        else:
            mu = logvar = None; z = torch.zeros((image.shape[0], self.z_proj.in_features), device=image.device)
        memory = torch.cat((state, self.z_proj(z).unsqueeze(1), x), dim=1)
        decoded = self.decoder(self.query.expand(image.shape[0], -1, -1), memory, x, gates)
        return self.out(decoded), mu, logvar, aux


class StereoSyncARCA(StereoARCA):
    """Stereo-ARCA with a training-only synchronized action-stage teacher.

    At inference ``phase_target`` is never provided.  Each local policy predicts
    the phase from its own current wrist RGB-D tokens and qpos, then conditions
    action-query routing on that *predicted* soft phase.  The optional target is
    used only for the CE loss in the trainer.
    """
    def __init__(self, *args, phases=8, **kwargs):
        super().__init__(*args, **kwargs)
        d = self.query.shape[-1]
        self.phases_n = phases
        self.phase_head = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, d), nn.GELU(), nn.Linear(d, phases))
        self.phase_embed = nn.Parameter(torch.randn(phases, d) * .02)

    def _sync_route(self, state, observation, phase_probs, batch):
        q = self.query.expand(batch, -1, -1)
        context = self.route_state(state) + self.route_observation(observation.mean(1))
        phase_context = torch.matmul(phase_probs, self.phase_embed)
        features = self.route_mlp(q + (context + phase_context).unsqueeze(1))
        logits = torch.matmul(features, self.role_prototypes.t()) / math.sqrt(features.shape[-1])
        values, ids = logits.topk(2, dim=-1)
        gates = torch.zeros_like(logits).scatter_(-1, ids, values.softmax(-1).to(logits.dtype))
        importance = logits.softmax(-1).mean((0, 1))
        load = gates.gt(0).to(logits.dtype).mean((0, 1)) / 2.0
        aux = self.roles_n * (importance * load).sum()
        return gates, aux

    def forward(self, image, depth_mm, qpos, actions=None):
        x = self._rgbd_tokens(image, depth_mm)
        state_vec = self.state(qpos)
        local_context = self.route_state(state_vec) + self.route_observation(x.mean(1))
        phase_logits = self.phase_head(local_context)
        phase_probs = phase_logits.softmax(-1)
        gates, aux = self._sync_route(state_vec, x, phase_probs, image.shape[0])
        state = state_vec.unsqueeze(1)
        if actions is not None:
            h = self.posterior(self.action(actions) + self.pos)
            mu, logvar = self.latent(h.mean(1)).chunk(2, -1)
            z = mu + torch.randn_like(mu) * torch.exp(.5 * logvar)
        else:
            mu = logvar = None
            z = torch.zeros((image.shape[0], self.z_proj.in_features), device=image.device)
        memory = torch.cat((state, self.z_proj(z).unsqueeze(1), x), dim=1)
        decoded = self.decoder(self.query.expand(image.shape[0], -1, -1), memory, x, gates)
        return self.out(decoded), mu, logvar, aux, phase_logits, gates