multimodalart HF Staff commited on
Commit
384d7a7
·
verified ·
1 Parent(s): 6b35c50

Add pure-PyTorch mamba_ssm stand-in so the StreamMind gate loads

Browse files
app.py CHANGED
@@ -24,8 +24,6 @@ os.makedirs(os.environ["ONLINE_CODEC_CACHE_DIR"], exist_ok=True)
24
  os.makedirs(os.environ["STREAMMIND_CLIP_CACHE"], exist_ok=True)
25
 
26
  import importlib
27
- import math
28
- import shutil
29
  import subprocess
30
  import time
31
  import traceback
@@ -35,15 +33,9 @@ from pathlib import Path
35
 
36
  import spaces # noqa: F401 (must precede torch)
37
  import torch
38
- import torch.nn as nn
39
- import torch.nn.functional as F
40
  import gradio as gr
41
- import numpy as np
42
  from PIL import Image
43
- from huggingface_hub import hf_hub_download
44
- from safetensors.torch import load_file
45
- from transformers import AutoModelForCausalLM, AutoProcessor, Qwen3Config
46
- from transformers.models.qwen3 import Qwen3ForCausalLM
47
 
48
  MODEL_ID = "microsoft/Mage-VL"
49
 
@@ -80,225 +72,24 @@ ProcessorCls = type(processor)
80
  print(f"[init] model loaded, remote package = {_REMOTE_PKG}", flush=True)
81
 
82
 
83
- # ----------------------------------------------------- pure-torch StreamMind gate
84
- # The released gate module imports `mamba_ssm.models.mixer_seq_simple.create_block`,
85
- # whose CUDA kernels (selective_scan_cuda / causal_conv1d) have no wheel for the
86
- # ZeroGPU Blackwell (sm_120) / torch-2.11 cell and cannot be compiled inside a
87
- # Space build. The block below is a faithful pure-PyTorch port of Mamba-1
88
- # (`mamba_ssm.modules.mamba_simple.Mamba` + `mamba_ssm.modules.block.Block`,
89
- # fused_add_norm=False, rms_norm=False, d_intermediate=0) using the upstream
90
- # `selective_scan_ref` reference recurrence, with identical parameter names so the
91
- # released `streammind_gate.safetensors` loads with strict=True.
92
-
93
-
94
- def _selective_scan_ref(u, delta, A, B, C, D=None, z=None, delta_bias=None,
95
- delta_softplus=False):
96
- """u,delta,z: (b, d, l) · A: (d, n) · B,C: (b, n, l) · D: (d,)"""
97
- dtype_in = u.dtype
98
- u = u.float()
99
- delta = delta.float()
100
- if delta_bias is not None:
101
- delta = delta + delta_bias[..., None].float()
102
- if delta_softplus:
103
- delta = F.softplus(delta)
104
- batch, dim, dstate = u.shape[0], A.shape[0], A.shape[1]
105
- B = B.float()
106
- C = C.float()
107
- x = A.new_zeros((batch, dim, dstate))
108
- deltaA = torch.exp(torch.einsum("bdl,dn->bdln", delta, A))
109
- deltaB_u = torch.einsum("bdl,bnl,bdl->bdln", delta, B, u)
110
- ys = []
111
- for i in range(u.shape[2]):
112
- x = deltaA[:, :, i] * x + deltaB_u[:, :, i]
113
- ys.append(torch.einsum("bdn,bn->bd", x, C[:, :, i]))
114
- y = torch.stack(ys, dim=2)
115
- out = y if D is None else y + u * D.unsqueeze(-1)
116
- if z is not None:
117
- out = out * F.silu(z)
118
- return out.to(dtype=dtype_in)
119
-
120
-
121
- class _Mamba(nn.Module):
122
- def __init__(self, d_model, d_state=16, d_conv=4, expand=2):
123
- super().__init__()
124
- self.d_model = d_model
125
- self.d_state = d_state
126
- self.d_conv = d_conv
127
- self.d_inner = int(expand * d_model)
128
- self.dt_rank = math.ceil(d_model / 16)
129
- self.in_proj = nn.Linear(d_model, self.d_inner * 2, bias=False)
130
- self.conv1d = nn.Conv1d(self.d_inner, self.d_inner, bias=True,
131
- kernel_size=d_conv, groups=self.d_inner,
132
- padding=d_conv - 1)
133
- self.act = nn.SiLU()
134
- self.x_proj = nn.Linear(self.d_inner, self.dt_rank + 2 * self.d_state, bias=False)
135
- self.dt_proj = nn.Linear(self.dt_rank, self.d_inner, bias=True)
136
- self.A_log = nn.Parameter(torch.zeros(self.d_inner, self.d_state))
137
- self.D = nn.Parameter(torch.ones(self.d_inner))
138
- self.out_proj = nn.Linear(self.d_inner, d_model, bias=False)
139
-
140
- def forward(self, hidden_states, inference_params=None, **kwargs):
141
- b, l, _ = hidden_states.shape
142
- xz = self.in_proj(hidden_states).transpose(1, 2) # (b, 2*d_inner, l)
143
- A = -torch.exp(self.A_log.float()) # (d_inner, d_state)
144
- x, z = xz.chunk(2, dim=1)
145
- x = self.act(self.conv1d(x)[..., :l])
146
- x_dbl = self.x_proj(x.transpose(1, 2).reshape(b * l, self.d_inner))
147
- dt, B, C = torch.split(x_dbl, [self.dt_rank, self.d_state, self.d_state], dim=-1)
148
- dt = (self.dt_proj.weight @ dt.t()).view(self.d_inner, b, l).permute(1, 0, 2)
149
- B = B.view(b, l, self.d_state).transpose(1, 2).contiguous()
150
- C = C.view(b, l, self.d_state).transpose(1, 2).contiguous()
151
- y = _selective_scan_ref(
152
- x, dt, A, B, C, self.D.float(), z=z,
153
- delta_bias=self.dt_proj.bias.float(), delta_softplus=True,
154
- )
155
- return self.out_proj(y.transpose(1, 2))
156
-
157
-
158
- class _Block(nn.Module):
159
- def __init__(self, dim):
160
- super().__init__()
161
- self.norm = nn.LayerNorm(dim)
162
- self.mixer = _Mamba(dim)
163
-
164
- def forward(self, hidden_states, residual=None, inference_params=None):
165
- residual = (hidden_states + residual) if residual is not None else hidden_states
166
- hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
167
- hidden_states = self.mixer(hidden_states, inference_params=inference_params)
168
- return hidden_states, residual
169
-
170
-
171
- # The remaining gate modules below are verbatim ports of the released
172
- # `streammind_gate.py` (PreNet / PostNet / VideoMamba / Qwen3ForCausalLMCls /
173
- # ClsNet / StreamMindGate); only `create_block` is swapped for `_Block` above.
174
- # The released module cannot simply be imported because line 6 of it is a
175
- # module-level `from mamba_ssm... import create_block`.
176
-
177
-
178
- class _PreNet(nn.Module):
179
- def __init__(self, d_code, d_model):
180
- super().__init__()
181
- self.fc3 = nn.Linear(d_code, d_model)
182
-
183
- def forward(self, x):
184
- return F.leaky_relu(self.fc3(x))
185
-
186
-
187
- class _PostNet(nn.Module):
188
- def __init__(self, d_model, n_class):
189
- super().__init__()
190
- self.fc3 = nn.Linear(d_model, n_class)
191
-
192
- def forward(self, x):
193
- return self.fc3(F.leaky_relu(x))
194
-
195
-
196
- class _VideoMamba(nn.Module):
197
- def __init__(self, d_model, n_ssm=1):
198
- super().__init__()
199
- self.ssms = nn.ModuleList([_Block(d_model) for _ in range(n_ssm)])
200
- self.norm_fn = nn.LayerNorm(d_model)
201
-
202
- def forward(self, embeds, inference_params=None):
203
- hidden_states, residual = embeds, None
204
- for ssm in self.ssms:
205
- hidden_states, residual = ssm(
206
- hidden_states, residual, inference_params=inference_params
207
- )
208
- residual = hidden_states + residual if residual is not None else hidden_states
209
- return self.norm_fn(residual.to(dtype=self.norm_fn.weight.dtype))
210
-
211
-
212
- class _Qwen3ForCausalLMCls(Qwen3ForCausalLM):
213
- def forward(self, inputs_embeds=None, labels=None, attention_mask=None, **kwargs):
214
- outputs = self.model(inputs_embeds=inputs_embeds, attention_mask=attention_mask)
215
- logits = self.lm_head(outputs.last_hidden_state).float()
216
- return {"loss": None, "logits": logits}
217
-
218
-
219
- class _ClsNet(nn.Module):
220
- def __init__(self, hidden_size=2560, num_layers=4):
221
- super().__init__()
222
- config = Qwen3Config(
223
- vocab_size=2,
224
- hidden_size=hidden_size,
225
- num_hidden_layers=num_layers,
226
- num_attention_heads=32,
227
- num_key_value_heads=8,
228
- intermediate_size=12288,
229
- head_dim=128,
230
- max_position_embeddings=8192,
231
- rms_norm_eps=1e-6,
232
- tie_word_embeddings=False,
233
- attention_bias=False,
234
- )
235
- self.cls_model = _Qwen3ForCausalLMCls(config)
236
-
237
- def forward(self, x, labels=None, attention_mask=None):
238
- return self.cls_model(inputs_embeds=x, labels=labels, attention_mask=attention_mask)
239
-
240
-
241
- class StreamMindGate(nn.Module):
242
- def __init__(self, hidden_size=2560):
243
- super().__init__()
244
- self.pre_net = _PreNet(hidden_size, hidden_size)
245
- self.mamba_model = _VideoMamba(hidden_size)
246
- self.post_net = _PostNet(hidden_size, hidden_size)
247
- self.cls_net = _ClsNet(hidden_size=hidden_size, num_layers=4)
248
-
249
- def perception_tokens(self, vision_tokens):
250
- """[B,T,P,D] visual patches -> one EPFE token per time step."""
251
- x = vision_tokens.mean(dim=2)
252
- batch, time_, dim = x.shape
253
- x = self.pre_net(x.reshape(batch * time_, dim)).reshape(batch, time_, dim)
254
- x = self.mamba_model(x)
255
- x = self.post_net(x.reshape(batch * time_, dim)).reshape(batch, time_, dim)
256
- return x
257
-
258
- def forward(self, vision_tokens, response_positions=None):
259
- """Return [B,T,2] silence/speak logits for every EPFE time step."""
260
- tokens = self.perception_tokens(vision_tokens)
261
- batch, time_, dim = tokens.shape
262
- target_ids = torch.zeros(batch, time_, dtype=torch.long, device=tokens.device)
263
- if response_positions is not None:
264
- target_ids[:, torch.as_tensor(response_positions, device=tokens.device) - 1] = 1
265
- targets = self.cls_net.cls_model.model.embed_tokens(
266
- target_ids.reshape(batch * time_)
267
- )
268
- pair = torch.stack((tokens.reshape(batch * time_, dim), targets), dim=1)
269
- rotary = self.cls_net.cls_model.model.rotary_emb
270
- saved_inv_freq = rotary.inv_freq
271
- try:
272
- # Match the training checkpoint, where the full model (including
273
- # non-persistent Qwen3 RoPE buffers) was cast to BF16.
274
- rotary.inv_freq = rotary.inv_freq.to(pair.dtype)
275
- output = self.cls_net(
276
- pair,
277
- attention_mask=torch.ones(pair.shape[:2], device=pair.device),
278
- )
279
- finally:
280
- rotary.inv_freq = saved_inv_freq
281
- return output["logits"][:, 0].reshape(batch, time_, 2)
282
-
283
-
284
- def _build_gate():
285
- """StreamMindGate with the pure-torch Mamba block, released weights."""
286
- gate = StreamMindGate(model.config.text_config.hidden_size)
287
- state = load_file(hf_hub_download(MODEL_ID, "streammind_gate.safetensors"))
288
- gate.load_state_dict(state, strict=True)
289
- return gate.to("cuda", dtype=torch.bfloat16).eval()
290
-
291
 
292
  GATE_ERROR = ""
293
  try:
294
  _t0 = time.perf_counter()
295
- model.model.streammind_gate = _build_gate()
296
  print(f"[gate] loaded in {time.perf_counter() - _t0:.1f}s", flush=True)
297
  except Exception as exc: # surfaced in the streaming tab, never kills the boot
298
  GATE_ERROR = f"{type(exc).__name__}: {exc}"
299
  print("[gate] FAILED:\n" + traceback.format_exc(), flush=True)
300
 
301
 
 
302
  # --------------------------------------------------------------------------- utils
303
 
304
 
 
24
  os.makedirs(os.environ["STREAMMIND_CLIP_CACHE"], exist_ok=True)
25
 
26
  import importlib
 
 
27
  import subprocess
28
  import time
29
  import traceback
 
33
 
34
  import spaces # noqa: F401 (must precede torch)
35
  import torch
 
 
36
  import gradio as gr
 
37
  from PIL import Image
38
+ from transformers import AutoModelForCausalLM, AutoProcessor
 
 
 
39
 
40
  MODEL_ID = "microsoft/Mage-VL"
41
 
 
72
  print(f"[init] model loaded, remote package = {_REMOTE_PKG}", flush=True)
73
 
74
 
75
+ # ----------------------------------------------------- StreamMind cognition gate
76
+ # `streammind_gate.py` in the model repo imports
77
+ # `mamba_ssm.models.mixer_seq_simple.create_block`; the real mamba-ssm ships CUDA
78
+ # extensions with no wheel for this runtime, so `./mamba_ssm/` in this Space is a
79
+ # pure-PyTorch stand-in with identical parameter names/shapes (see its docstring).
80
+ # With that in place the released gate code + checkpoint load unmodified.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
  GATE_ERROR = ""
83
  try:
84
  _t0 = time.perf_counter()
85
+ model.model._load_streammind_gate()
86
  print(f"[gate] loaded in {time.perf_counter() - _t0:.1f}s", flush=True)
87
  except Exception as exc: # surfaced in the streaming tab, never kills the boot
88
  GATE_ERROR = f"{type(exc).__name__}: {exc}"
89
  print("[gate] FAILED:\n" + traceback.format_exc(), flush=True)
90
 
91
 
92
+
93
  # --------------------------------------------------------------------------- utils
94
 
95
 
mamba_ssm/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pure-PyTorch stand-in for the parts of `mamba-ssm` that Mage-VL needs.
2
+
3
+ `microsoft/Mage-VL`'s remote code (`streammind_gate.py`) does
4
+
5
+ from mamba_ssm.models.mixer_seq_simple import create_block
6
+
7
+ at module level, and `transformers.dynamic_module_utils.check_imports` imports
8
+ every top-level dependency of every remote file before it will load the model —
9
+ so `mamba_ssm` must be importable even though only the StreamMind cognition gate
10
+ uses it.
11
+
12
+ The real `mamba-ssm` ships CUDA extensions (`selective_scan_cuda`,
13
+ `causal_conv1d_cuda`) with no wheel for the ZeroGPU Blackwell (sm_120) /
14
+ torch-2.11 / cp312 runtime, and compiling them from source is not viable inside
15
+ a Space build. This package therefore provides a faithful pure-PyTorch port of
16
+ Mamba-1 (`mamba_ssm.modules.mamba_simple.Mamba` + `mamba_ssm.modules.block.Block`
17
+ with the defaults `create_block` uses: rms_norm=False, fused_add_norm=False,
18
+ residual_in_fp32=False, d_intermediate=0) built on the upstream
19
+ `selective_scan_ref` reference recurrence, with identical parameter names and
20
+ shapes so `streammind_gate.safetensors` loads with `strict=True`.
21
+
22
+ The gate runs over a handful of EPFE tokens (one per codec canvas), so the slow
23
+ sequential scan costs milliseconds — the CUDA kernel buys nothing here.
24
+ """
25
+
26
+ __version__ = "2.2.6.mage-vl-pure-torch"
mamba_ssm/models/__init__.py ADDED
File without changes
mamba_ssm/models/mixer_seq_simple.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pure-PyTorch `create_block` — Mamba-1 mixer + residual block, no CUDA kernels.
2
+
3
+ Mirrors `mamba_ssm.modules.mamba_simple.Mamba` and `mamba_ssm.modules.block.Block`
4
+ for the argument set `create_block()` is called with by Mage-VL's StreamMind gate
5
+ (`create_block(d_model, d_intermediate=0, layer_idx=i)`), i.e. the upstream
6
+ defaults: ssm_cfg={} -> d_state=16, d_conv=4, expand=2, dt_rank=ceil(d_model/16),
7
+ rms_norm=False -> nn.LayerNorm, fused_add_norm=False, residual_in_fp32=False.
8
+
9
+ Parameter names/shapes match upstream exactly, so the released
10
+ `streammind_gate.safetensors` loads with strict=True:
11
+
12
+ mixer.in_proj.weight (2*d_inner, d_model)
13
+ mixer.conv1d.{weight,bias} (d_inner, 1, d_conv) / (d_inner,)
14
+ mixer.x_proj.weight (dt_rank + 2*d_state, d_inner)
15
+ mixer.dt_proj.{weight,bias} (d_inner, dt_rank) / (d_inner,)
16
+ mixer.A_log (d_inner, d_state)
17
+ mixer.D (d_inner,)
18
+ mixer.out_proj.weight (d_model, d_inner)
19
+ norm.{weight,bias} (d_model,)
20
+ """
21
+
22
+ import math
23
+
24
+ import torch
25
+ import torch.nn as nn
26
+ import torch.nn.functional as F
27
+
28
+
29
+ def selective_scan_ref(u, delta, A, B, C, D=None, z=None, delta_bias=None,
30
+ delta_softplus=False, return_last_state=False):
31
+ """Upstream reference implementation (single-group, non-complex path).
32
+
33
+ u, delta, z: (b, d, l) · A: (d, n) · B, C: (b, n, l) · D: (d,)
34
+ """
35
+ dtype_in = u.dtype
36
+ u = u.float()
37
+ delta = delta.float()
38
+ if delta_bias is not None:
39
+ delta = delta + delta_bias[..., None].float()
40
+ if delta_softplus:
41
+ delta = F.softplus(delta)
42
+ batch, dim = u.shape[0], A.shape[0]
43
+ dstate = A.shape[1]
44
+ B = B.float()
45
+ C = C.float()
46
+ x = A.new_zeros((batch, dim, dstate))
47
+ deltaA = torch.exp(torch.einsum("bdl,dn->bdln", delta, A))
48
+ deltaB_u = torch.einsum("bdl,bnl,bdl->bdln", delta, B, u)
49
+ ys = []
50
+ last_state = None
51
+ for i in range(u.shape[2]):
52
+ x = deltaA[:, :, i] * x + deltaB_u[:, :, i]
53
+ ys.append(torch.einsum("bdn,bn->bd", x, C[:, :, i]))
54
+ if i == u.shape[2] - 1:
55
+ last_state = x
56
+ y = torch.stack(ys, dim=2)
57
+ out = y if D is None else y + u * D.unsqueeze(-1)
58
+ if z is not None:
59
+ out = out * F.silu(z)
60
+ out = out.to(dtype=dtype_in)
61
+ return (out, last_state) if return_last_state else out
62
+
63
+
64
+ class Mamba(nn.Module):
65
+ def __init__(self, d_model, d_state=16, d_conv=4, expand=2, dt_rank="auto",
66
+ conv_bias=True, bias=False, layer_idx=None, **kwargs):
67
+ super().__init__()
68
+ self.d_model = d_model
69
+ self.d_state = d_state
70
+ self.d_conv = d_conv
71
+ self.expand = expand
72
+ self.d_inner = int(expand * d_model)
73
+ self.dt_rank = math.ceil(d_model / 16) if dt_rank == "auto" else dt_rank
74
+ self.layer_idx = layer_idx
75
+
76
+ self.in_proj = nn.Linear(self.d_model, self.d_inner * 2, bias=bias)
77
+ self.conv1d = nn.Conv1d(
78
+ in_channels=self.d_inner, out_channels=self.d_inner, bias=conv_bias,
79
+ kernel_size=d_conv, groups=self.d_inner, padding=d_conv - 1,
80
+ )
81
+ self.activation = "silu"
82
+ self.act = nn.SiLU()
83
+ self.x_proj = nn.Linear(self.d_inner, self.dt_rank + self.d_state * 2, bias=False)
84
+ self.dt_proj = nn.Linear(self.dt_rank, self.d_inner, bias=True)
85
+ self.A_log = nn.Parameter(torch.zeros(self.d_inner, self.d_state))
86
+ self.D = nn.Parameter(torch.ones(self.d_inner))
87
+ self.out_proj = nn.Linear(self.d_inner, self.d_model, bias=bias)
88
+
89
+ def forward(self, hidden_states, inference_params=None, **kwargs):
90
+ batch, seqlen, _ = hidden_states.shape
91
+ xz = self.in_proj(hidden_states).transpose(1, 2) # (b, 2*d_inner, l)
92
+ A = -torch.exp(self.A_log.float()) # (d_inner, d_state)
93
+ x, z = xz.chunk(2, dim=1)
94
+ x = self.act(self.conv1d(x)[..., :seqlen])
95
+ x_dbl = self.x_proj(x.transpose(1, 2).reshape(batch * seqlen, self.d_inner))
96
+ dt, B, C = torch.split(
97
+ x_dbl, [self.dt_rank, self.d_state, self.d_state], dim=-1
98
+ )
99
+ dt = (self.dt_proj.weight @ dt.t()).view(self.d_inner, batch, seqlen)
100
+ dt = dt.permute(1, 0, 2).contiguous() # (b, d_inner, l)
101
+ B = B.view(batch, seqlen, self.d_state).transpose(1, 2).contiguous()
102
+ C = C.view(batch, seqlen, self.d_state).transpose(1, 2).contiguous()
103
+ y = selective_scan_ref(
104
+ x, dt, A, B, C, self.D.float(), z=z,
105
+ delta_bias=self.dt_proj.bias.float(), delta_softplus=True,
106
+ )
107
+ return self.out_proj(y.transpose(1, 2))
108
+
109
+
110
+ class Block(nn.Module):
111
+ """`mamba_ssm.modules.block.Block` with fused_add_norm=False, mlp=Identity."""
112
+
113
+ def __init__(self, dim, mixer_cls, norm_cls=nn.LayerNorm, mlp_cls=nn.Identity,
114
+ fused_add_norm=False, residual_in_fp32=False):
115
+ super().__init__()
116
+ self.residual_in_fp32 = residual_in_fp32
117
+ self.fused_add_norm = fused_add_norm
118
+ self.norm = norm_cls(dim)
119
+ self.mixer = mixer_cls(dim)
120
+ if mlp_cls is not nn.Identity:
121
+ self.norm2 = norm_cls(dim)
122
+ self.mlp = mlp_cls(dim)
123
+ else:
124
+ self.mlp = None
125
+
126
+ def forward(self, hidden_states, residual=None, inference_params=None, **kwargs):
127
+ residual = (hidden_states + residual) if residual is not None else hidden_states
128
+ hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
129
+ if self.residual_in_fp32:
130
+ residual = residual.to(torch.float32)
131
+ hidden_states = self.mixer(hidden_states, inference_params=inference_params)
132
+ if self.mlp is not None:
133
+ residual = hidden_states + residual
134
+ hidden_states = self.norm2(residual.to(dtype=self.norm2.weight.dtype))
135
+ hidden_states = self.mlp(hidden_states)
136
+ return hidden_states, residual
137
+
138
+
139
+ def create_block(d_model, d_intermediate=0, ssm_cfg=None, attn_layer_idx=None,
140
+ attn_cfg=None, norm_epsilon=1e-5, rms_norm=False,
141
+ residual_in_fp32=False, fused_add_norm=False, layer_idx=None,
142
+ device=None, dtype=None, **kwargs):
143
+ if d_intermediate:
144
+ raise NotImplementedError(
145
+ "This pure-PyTorch mamba_ssm stand-in only supports d_intermediate=0 "
146
+ "(the configuration used by Mage-VL's StreamMind gate)."
147
+ )
148
+ if attn_layer_idx and layer_idx in attn_layer_idx:
149
+ raise NotImplementedError(
150
+ "Attention blocks are not supported by this mamba_ssm stand-in."
151
+ )
152
+ if rms_norm:
153
+ raise NotImplementedError(
154
+ "rms_norm=True is not supported by this mamba_ssm stand-in."
155
+ )
156
+ factory_kwargs = {"device": device, "dtype": dtype}
157
+ ssm_cfg = dict(ssm_cfg or {})
158
+ ssm_cfg.pop("layer", None)
159
+
160
+ def mixer_cls(dim):
161
+ return Mamba(dim, layer_idx=layer_idx, **ssm_cfg)
162
+
163
+ def norm_cls(dim):
164
+ return nn.LayerNorm(dim, eps=norm_epsilon)
165
+
166
+ block = Block(
167
+ d_model, mixer_cls, norm_cls=norm_cls, mlp_cls=nn.Identity,
168
+ fused_add_norm=fused_add_norm, residual_in_fp32=residual_in_fp32,
169
+ )
170
+ block.layer_idx = layer_idx
171
+ if factory_kwargs["device"] is not None or factory_kwargs["dtype"] is not None:
172
+ block = block.to(**{k: v for k, v in factory_kwargs.items() if v is not None})
173
+ return block