forked from NVIDIA/TensorRT-LLM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssm.py
354 lines (317 loc) · 13.6 KB
/
ssm.py
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# SPDX-FileCopyrightText: Copyright (c) 2022-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import math
from typing import Optional
from .._common import default_net
from ..functional import (ACT2FN, Tensor, concat, conv2d, gather, mamba_conv1d,
permute, selective_scan, shape, split, view)
from ..module import Module
from ..parameter import Parameter
from .linear import ColumnLinear, Linear, RowLinear
from .normalization import RmsNorm
class MambaConv1d(Module):
def __init__(self,
d_inner,
d_conv=4,
pre_stride=0,
post_stride=0,
dtype=None,
apply_silu=True):
super().__init__()
self.d_inner = d_inner
self.d_conv = d_conv
self.pre_stride = pre_stride
self.post_stride = post_stride
self.dtype = dtype
self.weight = Parameter(shape=(self.d_inner, 1, self.d_conv, 1),
dtype=dtype)
self.bias = Parameter(shape=(self.d_inner, ), dtype=dtype)
self.apply_silu = apply_silu
def forward(self,
x: Tensor,
conv_state: Tensor,
host_request_types: Tensor,
last_token_ids: Tensor,
host_context_lengths: Optional[Tensor] = None,
slot_mapping: Optional[Tensor] = None,
conv_indices: Optional[Tensor] = None):
'''
Parameters:
x: [B, L, D] or [T, D]
conv_state: [B, W, D] or [1] of type int64 for paged state
host_request_types: [B]
last_token_ids: [B]
host_context_lengths: [B]
slot_mapping: [B]
conv_indices: [B]
'''
if default_net().plugin_config.mamba_conv1d_plugin:
transposed_weight = permute(
view(self.weight.value, shape=[self.d_inner, 1, self.d_conv]),
(1, 2, 0))
x_conv, conv_state = mamba_conv1d(
x, conv_state, transposed_weight, self.bias.value,
host_request_types, last_token_ids, self.d_inner, self.d_conv,
self.dtype, self.pre_stride, self.post_stride,
host_context_lengths, slot_mapping, self.apply_silu)
else:
assert not default_net().plugin_config.paged_state
assert len(
x.shape
) == 3, "remove_input_padding is not supported by OOTB for Mamba."
if self.pre_stride > 0:
_, x = split(x,
[self.pre_stride, self.d_inner + self.post_stride],
dim=-1)
if self.post_stride > 0:
x, _ = split(x, [self.d_inner, self.post_stride], dim=-1)
x = x.permute([0, 2, 1])
# In context phase, conv_state is a zero tensor, and it is used for padding
# In generation phase, conv_state is a tensor of the past x
x_pad = concat([conv_state, x], dim=2)
# Update conv_state
conv_state = gather(x_pad, 2, conv_indices)
# Convolution
x_pad = x_pad.view(
concat([shape(x_pad, 0),
shape(x_pad, 1),
shape(x_pad, 2), 1]))
x_conv = conv2d(x_pad,
self.weight.value,
self.bias.value,
groups=self.d_inner)
if self.apply_silu:
x_conv = ACT2FN['silu'](x_conv)
x_conv = x_conv.view(
concat([shape(x_conv, 0),
shape(x_conv, 1),
shape(x_conv, 2)]))
# Get dt, B and C
x_conv = x_conv.permute([0, 2, 1])
return x_conv, conv_state
class Mamba(Module):
def __init__(self,
d_model,
d_inner,
d_state=16,
d_conv=4,
dt_rank="auto",
bias=False,
dtype=None):
super().__init__()
self.d_model = d_model
self.d_state = d_state
self.d_conv = d_conv
self.d_inner = d_inner
self.dt_rank = math.ceil(self.d_model /
16) if dt_rank == "auto" else dt_rank
self.dtype = dtype
self.A = Parameter(shape=(self.d_state, self.d_inner), dtype="float32")
self.D = Parameter(shape=(self.d_inner, ), dtype="float32")
self.dt_bias = Parameter(shape=(self.d_inner, ), dtype="float32")
self.in_proj_x = Linear(self.d_model,
self.d_inner,
bias=bias,
dtype=dtype,
gather_output=False)
self.in_proj_z = Linear(self.d_model,
self.d_inner,
bias=bias,
dtype=dtype,
gather_output=False)
self.conv1d = MambaConv1d(self.d_inner, self.d_conv, dtype=self.dtype)
self.x_proj = Linear(self.d_inner,
self.dt_rank + self.d_state * 2,
bias=False,
dtype=dtype,
gather_output=False)
self.dt_proj = Linear(self.dt_rank,
self.d_inner,
bias=False,
dtype=dtype,
gather_output=False,
pad_lda=self.d_state * 2)
self.out_proj = Linear(self.d_inner,
self.d_model,
bias=bias,
dtype=dtype,
gather_output=False)
def forward(self,
hidden_states: Tensor,
conv_state: Tensor,
ssm_state: Tensor,
host_request_types: Tensor,
last_token_ids: Tensor,
host_context_lengths: Optional[Tensor] = None,
slot_mapping: Optional[Tensor] = None,
conv_indices: Optional[Tensor] = None):
'''
Parameters:
hidden_states: [B, L, D] or [T, D]
conv_state: [B, W, D] or [1] of type int64 for paged state
ssm_state: [B, N, D] or [1] of type int64 for paged state
host_request_types: [B]
last_token_ids: [B]
host_context_lengths: [B]
slot_mapping: [B]
conv_indices: [B]
'''
# in_proj
x = self.in_proj_x(hidden_states)
z = self.in_proj_z(hidden_states)
x_conv, conv_state = self.conv1d(x, conv_state, host_request_types,
last_token_ids, host_context_lengths,
slot_mapping, conv_indices)
# Get dt, B and C
x_dbl = self.x_proj(x_conv)
if default_net().plugin_config.gemm_plugin:
dt = self.dt_proj(x_dbl)
else:
dt, _ = split(x_dbl, [self.dt_rank, self.d_state * 2], dim=-1)
dt = self.dt_proj(dt)
# selective scan
y, ssm_state = selective_scan(x_conv,
ssm_state,
dt,
self.dt_bias.value,
self.A.value,
x_dbl,
self.D.value,
host_request_types,
last_token_ids,
self.d_inner,
self.d_state,
self.dt_rank,
delta_softplus=True,
dtype=self.dtype,
z=z,
host_context_lengths=host_context_lengths,
slot_mapping=slot_mapping)
# out_proj
out = self.out_proj(y)
return out, conv_state, ssm_state
class Mamba2(Module):
def __init__(self,
d_model,
d_inner,
d_state=16,
d_conv=4,
headdim=64,
ngroups=1,
chunk_size=256,
bias=False,
rmsnorm=True,
dtype=None,
tp_group=None,
tp_size=1):
super().__init__()
self.d_model = d_model
self.d_state = d_state
self.d_conv = d_conv
assert d_inner % tp_size == 0
self.d_inner = d_inner // tp_size
self.headdim = headdim
assert ngroups % tp_size == 0
self.ngroups = ngroups // tp_size
self.chunk_size = chunk_size
self.rmsnorm = rmsnorm
self.dtype = dtype
assert d_inner % headdim == 0
nheads = d_inner // headdim
assert nheads % tp_size == 0
self.nheads = nheads // tp_size
self.A = Parameter(shape=(self.nheads, ), dtype="float32")
self.D = Parameter(shape=(self.nheads, ), dtype="float32")
self.dt_bias = Parameter(shape=(self.nheads, ), dtype="float32")
d_in_proj = 2 * d_inner + 2 * ngroups * d_state + nheads
self.in_proj = ColumnLinear(d_model,
d_in_proj,
bias=bias,
dtype=dtype,
tp_group=tp_group,
tp_size=tp_size,
gather_output=False)
self.conv_dim = (d_inner + 2 * ngroups * d_state) // tp_size
self.conv1d = MambaConv1d(self.conv_dim,
self.d_conv,
pre_stride=self.d_inner,
post_stride=self.nheads,
dtype=self.dtype)
if rmsnorm:
self.norm = RmsNorm(normalized_shape=self.d_inner,
num_groups=self.ngroups,
eps=1e-5,
dtype=dtype)
self.out_proj = RowLinear(d_inner,
d_model,
bias=bias,
dtype=dtype,
tp_group=tp_group,
tp_size=tp_size)
def forward(self,
hidden_states: Tensor,
conv_state: Tensor,
ssm_state: Tensor,
host_request_types: Tensor,
last_token_ids: Tensor,
host_context_lengths: Optional[Tensor] = None,
slot_mapping: Optional[Tensor] = None,
conv_indices: Optional[Tensor] = None):
'''
Parameters:
hidden_states: [B, L, D] or [T, D]
conv_state: [B, W, D_conv] or [1] of type int64 for paged state
ssm_state: [B, H, N, D] or [1] of type int64 for paged state
host_request_types: [B]
last_token_ids: [B]
host_context_lengths: [B]
slot_mapping: [B]
conv_indices: [B]
'''
# in_proj
zxbcdt = self.in_proj(hidden_states)
# conv1d
xbc_conv, conv_state = self.conv1d(zxbcdt, conv_state,
host_request_types, last_token_ids,
host_context_lengths, slot_mapping,
conv_indices)
# mamba scan
y, ssm_state = selective_scan(xbc_conv,
ssm_state,
zxbcdt,
self.dt_bias.value,
self.A.value,
xbc_conv,
self.D.value,
host_request_types,
last_token_ids,
self.d_inner,
self.d_state,
dt_rank=0,
delta_softplus=True,
dtype=self.dtype,
z=zxbcdt,
host_context_lengths=host_context_lengths,
slot_mapping=slot_mapping,
nheads=self.nheads,
ngroups=self.ngroups,
chunk_size=self.chunk_size,
mamba_version='Mamba2')
# norm
if self.rmsnorm:
y = self.norm(y)
# out_proj
out = self.out_proj(y)
return out, conv_state, ssm_state