mixer_seq_simple.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. """Pure-PyTorch `create_block` — Mamba-1 mixer + residual block, no CUDA kernels.
  2. “Pure-PyTorch `create_block` — Mamba-1 混合器 + 残余块,没有 CUDA 内核。
  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. Parameter names/shapes match upstream exactly, so the released
  9. `streammind_gate.safetensors` loads with strict=True:
  10. mixer.in_proj.weight (2*d_inner, d_model)
  11. mixer.conv1d.{weight,bias} (d_inner, 1, d_conv) / (d_inner,)
  12. mixer.x_proj.weight (dt_rank + 2*d_state, d_inner)
  13. mixer.dt_proj.{weight,bias} (d_inner, dt_rank) / (d_inner,)
  14. mixer.A_log (d_inner, d_state)
  15. mixer.D (d_inner,)
  16. mixer.out_proj.weight (d_model, d_inner)
  17. norm.{weight,bias} (d_model,)
  18. """
  19. import math
  20. import torch
  21. import torch.nn as nn
  22. import torch.nn.functional as F
  23. def selective_scan_ref(u, delta, A, B, C, D=None, z=None, delta_bias=None,
  24. delta_softplus=False, return_last_state=False):
  25. """Upstream reference implementation (single-group, non-complex path).
  26. u, delta, z: (b, d, l) · A: (d, n) · B, C: (b, n, l) · D: (d,)
  27. """
  28. dtype_in = u.dtype
  29. u = u.float()
  30. delta = delta.float()
  31. if delta_bias is not None:
  32. delta = delta + delta_bias[..., None].float()
  33. if delta_softplus:
  34. delta = F.softplus(delta)
  35. batch, dim = u.shape[0], A.shape[0]
  36. dstate = A.shape[1]
  37. B = B.float()
  38. C = C.float()
  39. x = A.new_zeros((batch, dim, dstate))
  40. deltaA = torch.exp(torch.einsum("bdl,dn->bdln", delta, A))
  41. deltaB_u = torch.einsum("bdl,bnl,bdl->bdln", delta, B, u)
  42. ys = []
  43. last_state = None
  44. for i in range(u.shape[2]):
  45. x = deltaA[:, :, i] * x + deltaB_u[:, :, i]
  46. ys.append(torch.einsum("bdn,bn->bd", x, C[:, :, i]))
  47. if i == u.shape[2] - 1:
  48. last_state = x
  49. y = torch.stack(ys, dim=2)
  50. out = y if D is None else y + u * D.unsqueeze(-1)
  51. if z is not None:
  52. out = out * F.silu(z)
  53. out = out.to(dtype=dtype_in)
  54. return (out, last_state) if return_last_state else out
  55. class Mamba(nn.Module):
  56. def __init__(self, d_model, d_state=16, d_conv=4, expand=2, dt_rank="auto",
  57. conv_bias=True, bias=False, layer_idx=None, **kwargs):
  58. super().__init__()
  59. self.d_model = d_model
  60. self.d_state = d_state
  61. self.d_conv = d_conv
  62. self.expand = expand
  63. self.d_inner = int(expand * d_model)
  64. self.dt_rank = math.ceil(d_model / 16) if dt_rank == "auto" else dt_rank
  65. self.layer_idx = layer_idx
  66. self.in_proj = nn.Linear(self.d_model, self.d_inner * 2, bias=bias)
  67. self.conv1d = nn.Conv1d(
  68. in_channels=self.d_inner, out_channels=self.d_inner, bias=conv_bias,
  69. kernel_size=d_conv, groups=self.d_inner, padding=d_conv - 1,
  70. )
  71. self.activation = "silu"
  72. self.act = nn.SiLU()
  73. self.x_proj = nn.Linear(self.d_inner, self.dt_rank + self.d_state * 2, bias=False)
  74. self.dt_proj = nn.Linear(self.dt_rank, self.d_inner, bias=True)
  75. self.A_log = nn.Parameter(torch.zeros(self.d_inner, self.d_state))
  76. self.D = nn.Parameter(torch.ones(self.d_inner))
  77. self.out_proj = nn.Linear(self.d_inner, self.d_model, bias=bias)
  78. def forward(self, hidden_states, inference_params=None, **kwargs):
  79. batch, seqlen, _ = hidden_states.shape
  80. xz = self.in_proj(hidden_states).transpose(1, 2) # (b, 2*d_inner, l)
  81. A = -torch.exp(self.A_log.float()) # (d_inner, d_state)
  82. x, z = xz.chunk(2, dim=1)
  83. x = self.act(self.conv1d(x)[..., :seqlen])
  84. x_dbl = self.x_proj(x.transpose(1, 2).reshape(batch * seqlen, self.d_inner))
  85. dt, B, C = torch.split(
  86. x_dbl, [self.dt_rank, self.d_state, self.d_state], dim=-1
  87. )
  88. dt = (self.dt_proj.weight @ dt.t()).view(self.d_inner, batch, seqlen)
  89. dt = dt.permute(1, 0, 2).contiguous() # (b, d_inner, l)
  90. B = B.view(batch, seqlen, self.d_state).transpose(1, 2).contiguous()
  91. C = C.view(batch, seqlen, self.d_state).transpose(1, 2).contiguous()
  92. y = selective_scan_ref(
  93. x, dt, A, B, C, self.D.float(), z=z,
  94. delta_bias=self.dt_proj.bias.float(), delta_softplus=True,
  95. )
  96. return self.out_proj(y.transpose(1, 2))
  97. class Block(nn.Module):
  98. """`mamba_ssm.modules.block.Block` with fused_add_norm=False, mlp=Identity."""
  99. def __init__(self, dim, mixer_cls, norm_cls=nn.LayerNorm, mlp_cls=nn.Identity,
  100. fused_add_norm=False, residual_in_fp32=False):
  101. super().__init__()
  102. self.residual_in_fp32 = residual_in_fp32
  103. self.fused_add_norm = fused_add_norm
  104. self.norm = norm_cls(dim)
  105. self.mixer = mixer_cls(dim)
  106. if mlp_cls is not nn.Identity:
  107. self.norm2 = norm_cls(dim)
  108. self.mlp = mlp_cls(dim)
  109. else:
  110. self.mlp = None
  111. def forward(self, hidden_states, residual=None, inference_params=None, **kwargs):
  112. residual = (hidden_states + residual) if residual is not None else hidden_states
  113. hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype))
  114. if self.residual_in_fp32:
  115. residual = residual.to(torch.float32)
  116. hidden_states = self.mixer(hidden_states, inference_params=inference_params)
  117. if self.mlp is not None:
  118. residual = hidden_states + residual
  119. hidden_states = self.norm2(residual.to(dtype=self.norm2.weight.dtype))
  120. hidden_states = self.mlp(hidden_states)
  121. return hidden_states, residual
  122. def create_block(d_model, d_intermediate=0, ssm_cfg=None, attn_layer_idx=None,
  123. attn_cfg=None, norm_epsilon=1e-5, rms_norm=False,
  124. residual_in_fp32=False, fused_add_norm=False, layer_idx=None,
  125. device=None, dtype=None, **kwargs):
  126. if d_intermediate:
  127. raise NotImplementedError(
  128. "This pure-PyTorch mamba_ssm stand-in only supports d_intermediate=0 "
  129. "(the configuration used by Mage-VL's StreamMind gate)."
  130. )
  131. if attn_layer_idx and layer_idx in attn_layer_idx:
  132. raise NotImplementedError(
  133. "Attention blocks are not supported by this mamba_ssm stand-in."
  134. )
  135. if rms_norm:
  136. raise NotImplementedError(
  137. "rms_norm=True is not supported by this mamba_ssm stand-in."
  138. )
  139. factory_kwargs = {"device": device, "dtype": dtype}
  140. ssm_cfg = dict(ssm_cfg or {})
  141. ssm_cfg.pop("layer", None)
  142. def mixer_cls(dim):
  143. return Mamba(dim, layer_idx=layer_idx, **ssm_cfg)
  144. def norm_cls(dim):
  145. return nn.LayerNorm(dim, eps=norm_epsilon)
  146. block = Block(
  147. d_model, mixer_cls, norm_cls=norm_cls, mlp_cls=nn.Identity,
  148. fused_add_norm=fused_add_norm, residual_in_fp32=residual_in_fp32,
  149. )
  150. block.layer_idx = layer_idx
  151. if factory_kwargs["device"] is not None or factory_kwargs["dtype"] is not None:
  152. block = block.to(**{k: v for k, v in factory_kwargs.items() if v is not None})
  153. return block