原始模型:# Copyright (c) 2023, Tri Dao, Albert Gu. import math from typing import Optional…
- User
原始模型:# Copyright (c) 2023, Tri Dao, Albert Gu.
import math from typing import Optional
import torch import torch.nn as nn import torch.nn.functional as F from torch import Tensor
from einops import rearrange, repeat
try: from causal_conv1d import causal_conv1d_fn, causal_conv1d_update except ImportError: causal_conv1d_fn, causal_conv1d_update = None
try: from mamba_ssm.ops.selective_scan_interface import selective_scan_fn, mamba_inner_fn, bimamba_inner_fn, mamba_inner_fn_no_out_proj except ImportError: selective_scan_fn, mamba_inner_fn, bimamba_inner_fn, mamba_inner_fn_no_out_proj = None, None, None, None, None
try: from mamba_ssm.ops.triton.selective_state_update import selective_state_update except ImportError: selective_state_update = None
try: from mamba_ssm.ops.triton.layernorm import RMSNorm, layer_norm_fn, rms_norm_fn except ImportError: RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None
d_state又称N,是隐状态的维度。d_model代表数据在经过SSM块之前和之后的数据维度,是输入x的维度
class Mamba(nn.Module): def init( self, d_model, d_state=16, d_conv=4, expand=2, dt_rank="auto", dt_min=0.001, dt_max=0.1, dt_init="random", dt_scale=1.0, dt_init_floor=1e-4, conv_bias=True, bias=False, use_fast_path=True, # Fused kernel options layer_idx=None, device=None, dtype=None, bimamba_type="none", if_devide_out=False, init_layer_scale=None, ): factory_kwargs = {"device": device, "dtype": dtype} super().init() self.d_model = d_model self.d_state = d_state self.d_conv = d_conv self.expand = expand self.d_inner = int(self.expand * self.d_model) self.dt_rank = math.ceil(self.d_model / 16) if dt_rank == "auto" else dt_rank self.use_fast_path = use_fast_path self.layer_idx = layer_idx self.bimamba_type = bimamba_type self.if_devide_out = if_devide_out
self.init_layer_scale = init_layer_scale if init_layer_scale is not None: self.gamma = nn.Parameter(init_layer_scale * torch.ones((d_model)), requires_grad=True) self.in_proj = nn.Linear(self.d_model, self.d_inner * 2, bias=bias, **factory_kwargs) self.conv1d = nn.Conv1d( in_channels=self.d_inner, out_channels=self.d_inner, bias=conv_bias, kernel_size=d_conv, groups=self.d_inner, padding=d_conv - 1, **factory_kwargs, ) self.activation = "silu" self.act = nn.SiLU() self.x_proj = nn.Linear( self.d_inner, self.dt_rank + self.d_state * 2, bias=False, **factory_kwargs ) self.dt_proj = nn.Linear(self.dt_rank, self.d_inner, bias=True, **factory_kwargs) # Initialize special dt projection to preserve variance at initialization dt_init_std = self.dt_rank**-0.5 * dt_scale if dt_init == "constant": nn.init.constant_(self.dt_proj.weight, dt_init_std) elif dt_init == "random": nn.init.uniform_(self.dt_proj.weight, -dt_init_std, dt_init_std) else: raise NotImplementedError # Initialize dt bias so that F.softplus(dt_bias) is between dt_min and dt_max dt = torch.exp( torch.rand(self.d_inner, **factory_kwargs) * (math.log(dt_max) - math.log(dt_min)) + math.log(dt_min) ).clamp(min=dt_init_floor) # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759 inv_dt = dt + torch.log(-torch.expm1(-dt)) with torch.no_grad(): self.dt_proj.bias.copy_(inv_dt) # Our initialization would set all Linear.bias to zero, need to mark this one as _no_reinit self.dt_proj.bias._no_reinit = True # S4D real initialization A = repeat( torch.arange(1, self.d_state + 1, dtype=torch.float32, device=device), "n -> d n", d=self.d_inner, ).contiguous() A_log = torch.log(A) # Keep A_log in fp32 self.A_log = nn.Parameter(A_log) self.A_log._no_weight_decay = True # D "skip" parameter self.D = nn.Parameter(torch.ones(self.d_inner, device=device)) # Keep in fp32 self.D._no_weight_decay = True # bidirectional if bimamba_type == "v1": A_b = repeat( torch.arange(1, self.d_state + 1, dtype=torch.float32, device=device), "n -> d n", d=self.d_inner, ).contiguous() A_b_log = torch.log(A_b) # Keep A_b_log in fp32 self.A_b_log = nn.Parameter(A_b_log) self.A_b_log._no_weight_decay = True elif bimamba_type == "v2": A_b = repeat( torch.arange(1, self.d_state + 1, dtype=torch.float32, device=device), "n -> d n", d=self.d_inner, ).contiguous() A_b_log = torch.log(A_b) # Keep A_b_log in fp32 self.A_b_log = nn.Parameter(A_b_log) self.A_b_log._no_weight_decay = True self.conv1d_b = nn.Conv1d( in_channels=self.d_inner, out_channels=self.d_inner, bias=conv_bias, kernel_size=d_conv, groups=self.d_inner, padding=d_conv - 1, **factory_kwargs, ) self.x_proj_b = nn.Linear( self.d_inner, self.dt_rank + self.d_state * 2, bias=False, **factory_kwargs ) self.dt_proj_b = nn.Linear(self.dt_rank, self.d_inner, bias=True, **factory_kwargs) self.D_b = nn.Parameter(torch.ones(self.d_inner, device=device)) # Keep in fp32 self.D_b._no_weight_decay = True self.out_proj = nn.Linear(self.d_inner, self.d_model, bias=bias, **factory_kwargs) def forward(self, hidden_states, inference_params=None): """ hidden_states: (B, L, D) Returns: same shape as hidden_states """ batch, seqlen, dim = hidden_states.shape conv_state, ssm_state = None, None if inference_params is not None: conv_state, ssm_state = self._get_states_from_cache(inference_params, batch) if inference_params.seqlen_offset > 0: # The states are updated inplace out, _, _ = self.step(hidden_states, conv_state, ssm_state) return out # We do matmul and transpose BLH -> HBL at the same time xz = rearrange( self.in_proj.weight @ rearrange(hidden_states, "b l d -> d (b l)"), "d (b l) -> b d l", l=seqlen, ) if self.in_proj.bias is not None: xz = xz + rearrange(self.in_proj.bias.to(dtype=xz.dtype), "d -> d 1") A = -torch.exp(self.A_log.float()) # (d_inner, d_state) # In the backward pass we write dx and dz next to each other to avoid torch.cat if self.use_fast_path and inference_params is None: # Doesn't support outputting the states if self.bimamba_type == "v1": A_b = -torch.exp(self.A_b_log.float()) out = bimamba_inner_fn( xz, self.conv1d.weight, self.conv1d.bias, self.x_proj.weight, self.dt_proj.weight, self.out_proj.weight, self.out_proj.bias, A, A_b, None, # input-dependent B None, # input-dependent C self.D.float(), delta_bias=self.dt_proj.bias.float(), delta_softplus=True, ) elif self.bimamba_type == "v2": A_b = -torch.exp(self.A_b_log.float()) out = mamba_inner_fn_no_out_proj( xz, self.conv1d.weight, self.conv1d.bias, self.x_proj.weight, self.dt_proj.weight, A, None, # input-dependent B None, # input-dependent C self.D.float(), delta_bias=self.dt_proj.bias.float(), delta_softplus=True, ) out_b = mamba_inner_fn_no_out_proj( xz.flip([-1]), self.conv1d_b.weight, self.conv1d_b.bias, self.x_proj_b.weight, self.dt_proj_b.weight, A_b, None, None, self.D_b.float(), delta_bias=self.dt_proj_b.bias.float(), delta_softplus=True, ) # F.linear(rearrange(out_z, "b d l -> b l d"), out_proj_weight, out_proj_bias) if not self.if_devide_out: out = F.linear(rearrange(out + out_b.flip([-1]), "b d l -> b l d"), self.out_proj.weight, self.out_proj.bias) else: out = F.linear(rearrange(out + out_b.flip([-1]), "b d l -> b l d") / 2, self.out_proj.weight, self.out_proj.bias) else: out = mamba_inner_fn( xz, self.conv1d.weight, self.conv1d.bias, self.x_proj.weight, self.dt_proj.weight, self.out_proj.weight, self.out_proj.bias, A, None, # input-dependent B None, # input-dependent C self.D.float(), delta_bias=self.dt_proj.bias.float(), delta_softplus=True, ) else: x, z = xz.chunk(2, dim=1) # Compute short convolution if conv_state is not None: # If we just take x[:, :, -self.d_conv :], it will error if seqlen < self.d_conv # Instead F.pad will pad with zeros if seqlen < self.d_conv, and truncate otherwise. conv_state.copy_(F.pad(x, (self.d_conv - x.shape[-1], 0))) # Update state (B D W) if causal_conv1d_fn is None: x = self.act(self.conv1d(x)[..., :seqlen]) else: assert self.activation in ["silu", "swish"] x = causal_conv1d_fn( x=x, weight=rearrange(self.conv1d.weight, "d 1 w -> d w"), bias=self.conv1d.bias, activation=self.activation, ) # We're careful here about the layout, to avoid extra transposes. # We want dt to have d as the slowest moving dimension # and L as the fastest moving dimension, since those are what the ssm_scan kernel expects. x_dbl = self.x_proj(rearrange(x, "b d l -> (b l) d")) # (bl d) dt, B, C = torch.split(x_dbl, [self.dt_rank, self.d_state, self.d_state], dim=-1) dt = self.dt_proj.weight @ dt.t() dt = rearrange(dt, "d (b l) -> b d l", l=seqlen) B = rearrange(B, "(b l) dstate -> b dstate l", l=seqlen).contiguous() C = rearrange(C, "(b l) dstate -> b dstate l", l=seqlen).contiguous() assert self.activation in ["silu", "swish"] y = selective_scan_fn( x, dt, A, B, C, self.D.float(), z=z, delta_bias=self.dt_proj.bias.float(), delta_softplus=True, return_last_state=ssm_state is not None, ) if ssm_state is not None: y, last_state = y ssm_state.copy_(last_state) y = rearrange(y, "b d l -> b l d") out = self.out_proj(y) if self.init_layer_scale is not None: out = out * self.gamma return out def step(self, hidden_states, conv_state, ssm_state): dtype = hidden_states.dtype assert hidden_states.shape[1] == 1, "Only support decoding with 1 token at a time for now" xz = self.in_proj(hidden_states.squeeze(1)) # (B 2D) x, z = xz.chunk(2, dim=-1) # (B D) # Conv step if causal_conv1d_update is None: conv_state.copy_(torch.roll(conv_state, shifts=-1, dims=-1)) # Update state (B D W) conv_state[:, :, -1] = x x = torch.sum(conv_state * rearrange(self.conv1d.weight, "d 1 w -> d w"), dim=-1) # (B D) if self.conv1d.bias is not None: x = x + self.conv1d.bias x = self.act(x).to(dtype=dtype) else: x = causal_conv1d_update( x, conv_state, rearrange(self.conv1d.weight, "d 1 w -> d w"), self.conv1d.bias, self.activation, ) x_db = self.x_proj(x) # (B dt_rank+2*d_state) dt, B, C = torch.split(x_db, [self.dt_rank, self.d_state, self.d_state], dim=-1) # Don't add dt_bias here dt = F.linear(dt, self.dt_proj.weight) # (B d_inner) A = -torch.exp(self.A_log.float()) # (d_inner, d_state) # SSM step if selective_state_update is None: # Discretize A and B dt = F.softplus(dt + self.dt_proj.bias.to(dtype=dt.dtype)) dA = torch.exp(torch.einsum("bd,dn->bdn", dt, A)) dB = torch.einsum("bd,bn->bdn", dt, B) ssm_state.copy_(ssm_state * dA + rearrange(x, "b d -> b d 1") * dB) y = torch.einsum("bdn,bn->bd", ssm_state.to(dtype), C) y = y + self.D.to(dtype) * x y = y * self.act(z) # (B D) else: y = selective_state_update( ssm_state, x, dt, A, B, C, self.D, z=z, dt_bias=self.dt_proj.bias, dt_softplus=True ) out = self.out_proj(y) return out.unsqueeze(1), conv_state, ssm_state def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs): device = self.out_proj.weight.device conv_dtype = self.conv1d.weight.dtype if dtype is None else dtype conv_state = torch.zeros( batch_size, self.d_model * self.expand, self.d_conv, device=device, dtype=conv_dtype ) ssm_dtype = self.dt_proj.weight.dtype if dtype is None else dtype # ssm_dtype = torch.float32 ssm_state = torch.zeros( batch_size, self.d_model * self.expand, self.d_state, device=device, dtype=ssm_dtype ) return conv_state, ssm_state def _get_states_from_cache(self, inference_params, batch_size, initialize_states=False): assert self.layer_idx is not None if self.layer_idx not in inference_params.key_value_memory_dict: batch_shape = (batch_size,) conv_state = torch.zeros( batch_size, self.d_model * self.expand, self.d_conv, device=self.conv1d.weight.device, dtype=self.conv1d.weight.dtype, ) ssm_state = torch.zeros( batch_size, self.d_model * self.expand, self.d_state, device=self.dt_proj.weight.device, dtype=self.dt_proj.weight.dtype, # dtype=torch.float32, ) inference_params.key_value_memory_dict[self.layer_idx] = (conv_state, ssm_state) else: conv_state, ssm_state = inference_params.key_value_memory_dict[self.layer_idx] # TODO: What if batch size changes between generation, and we reuse the same states? if initialize_states: conv_state.zero_() ssm_state.zero_() return conv_state, ssm_state - Assistant
在您提供的两段代码之间,主要的区别在于卷积层的实现方式。让我们仔细看看这些区别:
-
增加的卷积层:
-
在第二段代码中,增加了一个新的卷积层
conv1d_stride2和conv1d_b_S2,与原始的conv1d和conv1d_b(仅在bimamba_type="v2"时使用)相比,这些新增加的卷积层具有设置步长 (stride) 为 2:self.conv1d_stride2 = nn.Conv1d( in_channels=self.d_inner, out_channels=self.d_inner, bias=conv_bias, kernel_size=d_conv, groups=self.d_inner, padding=d_conv - 1, stride=2, # 设置步长为2 **factory_kwargs, ) -
对于双向 Mamba(
bimamba_type="v2"),添加了一个同样设置stride=2的conv1d_b_S2:self.conv1d_b_S2 = nn.Conv1d( in_channels=self.d_inner, out_channels=self.d_inner, bias=conv_bias, kernel_size=d_conv, groups=self.d_inner, padding=d_conv - 1, stride=2, # 设置步长为2 **factory_kwargs, )
-
-
- User
原始的Conv1d是如何集成在mamba块中的?
- Assistant
在原始的
Mamba类中,Conv1d层被集成在前向传播过程中,并可能在推理时单步执行。下面是对如何集成Conv1d层的解释:前向传播 (
forward) 方法中的集成-
输入投影:
- 最初,输入数据被
self.in_proj层投影,形成一个新的张量xz。
xz = rearrange( self.in_proj.weight @ rearrange(hidden_states, "b l d -> d (b l)"), "d (b l) -> b d l", l=seqlen, ) - 最初,输入数据被
-
卷积操作:
- 预处理
xz后,xz被拆分为x和z,其中x被传递给self.conv1d。
x, z = xz.chunk(2, dim=1) x = self.act(self.conv1d(x)[..., :seqlen]) - 预处理
-
:
-
- User
那么现在在卷积后再增加一个步长为2的卷积操作,串联在原本的卷积调用后面。
- Assistant
要在卷积操作中添加一个步长为2的卷积,并将其与原始卷积串联,可以在
Mamba类的前向传播和单步执行过程中对卷积步骤进行修改。以下是如何实现这一目标的示例:修改
forward方法在
forward方法中,将新的步长为2的卷积conv1d_stride2添加到现有卷积之后:def forward(self, hidden_states, inference_params=None): ... x, z = xz.chunk(2, dim=1) # 分离 x 和 z # 现有卷积操作 if conv_state is not None: conv_state.copy_(F.pad(x, (self.d_conv - x.shape[-1], 0))) if causal_conv1d_fn is None: x = self.act(self.conv1d(x)[..., :seqlen]) else: assert self.activation in ["silu", "swish"] x = causal_conv1d_fn( x=x, weight=rearrange(self.conv1d.weight, "d 1 w -> d w"), bias=self.conv1d.bias, activation=self.activation, ) # 新增步长为2的卷积操作 x = self.act(self.conv1d_stride2(x)) ... - User
那么如果是并联呢?
- Assistant
如果要在卷积操作中将一个步长为2的卷积与原始卷积并联,而非串联,那就需要对两者的输出结果在某个地方进行合并,以确保后续网络层可以处理。这里有一个简单的方法是在
forward和step方法中实现并联结构:并联结构
- User
- Assistant
将步长为2的卷积操作集成到
Mamba类中的方法如您所示,能捕获更大感受野的局部特征。然而,新的卷积操作是否合逻辑地集成到原有结构中,取决于几个重要方面:-
卷积输出的形状:
- 由于步长为2,
conv1d_stride2的输出长度会少一半,因此在后续需要确保形状或梯度运算的兼容性。由于代码中使用的插值 (F.interpolate) 恢复到原长,通过线性插值将宽度恢复,确保与之前的卷积输出相加是一个合适的操作。
- 由于步长为2,
-
特征融合:
- 在
forward和step方法中,两个卷积(常规和步长为2)后的输出需要合并。当前方法通过相加操作来融合两个特征图:x = x + F.interpolate(x_stride2, scale_factor=2, mode='linear') - 该方法在理论上是可行的,但不同应用场景下,可能需要更多的实验来调优插值模式和融合策略。
- 在
-
数值稳定性与信息保留:
- 使用插值在一定程度上会引入信息损失和数值误差。选择适合的插值方式(线性插值已是很常用的一种)并确保在模型中这种误差不影响最终性能。
-
上下文合理性:
- 检查步长为2卷积是否引入在合适的上下文之中。例如:模型预期能够合理利用两种不同尺寸特征时(分别对短期/长期特征的感知)。
-
可训练性与效率:
- 确保这种组合在训练效率和收敛性上表现良好。有时复杂结构可能需要更细致的初始化或正则化来确保性能。
在整体结构中,新添加的并联步长卷积逻辑上是合理的,但需要通过实验来验证在特定任务上的有效性和改善效果。试验不同组合策略(如融合方法、插值模式)可能有助于找到最优解。
-
- User
如果我们要检查新增之后的维度,应该在哪里进行print?
- Assistant
为了检查新增的步长为2的卷积操作对数据张量维度的影响,您可以在代码的关键步骤中使用
print语句来输出张量的形状。这可以帮助验证卷积和其他操作产生预期的形状变化。建议在以下几个位置添加print语句。在
forward方法中-
在卷积之后: 添加
print语句以查看经过原始卷积和步长为2的卷积后的形状。# 原始卷积输出形状 x = self.act(self.conv1d(x)[..., :seqlen]) print("Shape after conv1d:", x.shape) # 步长为2的卷积输出形状 x_stride2 = self.act(self.conv1d_stride2(x)[..., :seqlen // 2]) print("Shape after conv1d_stride2:", x_stride2.shape) # 合并后的形状 x = x + F.interpolate(x_stride2, scale_factor=2, mode='linear') print("Shape after combining:", x.shape) -
在举例输出之前: 检查其他关键点的形状变化,尤其是在后续需要使用该张量输出到其他模块时。
在
step方法中-
在每个步骤内的更新: 您也可以在
step中的相同位置添加相关输出,以在单步预测过程中跟踪形状。# 原始卷积输出形状 x = causal_conv1d_update(...) print("Shape after conv1d in step:", x.shape) # 步长为2的卷积输出形状 x_stride2 = self.act(self.conv1d_stride2(x.unsqueeze(-1)).squeeze(-1)) print("Shape after conv1d_stride2 in step:", x_stride2.shape) # 合并后的形状 x = x + F.interpolate(x_stride2, scale_factor=2, mode='linear') print("Shape after combining in step:", x.shape)
-