AgentNewTwo commited on
Commit
a55ce2f
·
1 Parent(s): 7858cc2

Restore Mage-VL mamba import compatibility

Browse files
README.md CHANGED
@@ -64,4 +64,6 @@ to reconstruct only the events supported by the recording, and links each claim
64
  - VibeASR.cpp pinned at `70b3ebb8ad75b5f37aee948df34f15cc84951d05`
65
 
66
  Mage-VL loading and codec preprocessing are derived from Microsoft's Apache-2.0 reference Space. ReplayForge's
67
- workflow, evidence model, privacy controls, report generator, and interface are original project work.
 
 
 
64
  - VibeASR.cpp pinned at `70b3ebb8ad75b5f37aee948df34f15cc84951d05`
65
 
66
  Mage-VL loading and codec preprocessing are derived from Microsoft's Apache-2.0 reference Space. ReplayForge's
67
+ pure-PyTorch `mamba_ssm` compatibility shim is also retained because Transformers validates Mage-VL's optional
68
+ StreamMind import even though ReplayForge does not load that gate. ReplayForge's workflow, evidence model, privacy
69
+ controls, report generator, and interface are original project work.
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