ssd_combined.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. # Copyright (c) 2024, Tri Dao, Albert Gu.
  2. """We want triton==2.1.0 or 2.2.0 for this
  3. """
  4. from typing import Optional
  5. import math
  6. from packaging import version
  7. import torch
  8. import torch.nn.functional as F
  9. from torch import Tensor
  10. from mamba_ssm.utils.torch import custom_bwd, custom_fwd
  11. import triton
  12. import triton.language as tl
  13. from einops import rearrange, repeat
  14. try:
  15. from causal_conv1d import causal_conv1d_fn
  16. import causal_conv1d_cuda
  17. except ImportError:
  18. causal_conv1d_fn, causal_conv1d_cuda = None, None
  19. from mamba_ssm.ops.triton.ssd_bmm import _bmm_chunk_fwd, _bmm_chunk_bwd
  20. from mamba_ssm.ops.triton.ssd_chunk_state import _chunk_cumsum_fwd, _chunk_cumsum_bwd
  21. from mamba_ssm.ops.triton.ssd_chunk_state import _chunk_state_fwd, _chunk_state_bwd_db
  22. from mamba_ssm.ops.triton.ssd_chunk_state import _chunk_state_bwd_ddAcs_stable
  23. from mamba_ssm.ops.triton.ssd_chunk_state import chunk_state, chunk_state_ref
  24. from mamba_ssm.ops.triton.ssd_chunk_state import chunk_state_varlen
  25. from mamba_ssm.ops.triton.ssd_state_passing import _state_passing_fwd, _state_passing_bwd
  26. from mamba_ssm.ops.triton.ssd_state_passing import state_passing, state_passing_ref
  27. from mamba_ssm.ops.triton.ssd_chunk_scan import _chunk_scan_fwd, _chunk_scan_bwd_dz, _chunk_scan_bwd_dstates
  28. from mamba_ssm.ops.triton.ssd_chunk_scan import _chunk_scan_bwd_dC, _chunk_scan_bwd_dcb
  29. from mamba_ssm.ops.triton.ssd_chunk_scan import _chunk_scan_bwd_ddAcs_stable
  30. from mamba_ssm.ops.triton.ssd_chunk_scan import chunk_scan, chunk_scan_ref
  31. from mamba_ssm.ops.triton.ssd_chunk_scan import _chunk_scan_bwd_ddAcs_prev
  32. from mamba_ssm.ops.triton.layernorm_gated import rmsnorm_fn, _layer_norm_fwd, _layer_norm_bwd
  33. from mamba_ssm.ops.triton.k_activations import _swiglu_fwd, _swiglu_bwd
  34. TRITON_22 = version.parse(triton.__version__) >= version.parse('2.2.0')
  35. def init_to_zero(names):
  36. return lambda nargs: [nargs[name].zero_() for name in names if nargs[name] is not None]
  37. @triton.autotune(
  38. configs=[
  39. triton.Config({'BLOCK_SIZE_M': 128, 'BLOCK_SIZE_N': 256, 'BLOCK_SIZE_K': 64}, num_stages=3, num_warps=8, pre_hook=init_to_zero(["ddt_ptr"])),
  40. triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_N': 256, 'BLOCK_SIZE_K': 32}, num_stages=4, num_warps=4, pre_hook=init_to_zero(["ddt_ptr"])),
  41. triton.Config({'BLOCK_SIZE_M': 128, 'BLOCK_SIZE_N': 128, 'BLOCK_SIZE_K': 32}, num_stages=4, num_warps=4, pre_hook=init_to_zero(["ddt_ptr"])),
  42. triton.Config({'BLOCK_SIZE_M': 128, 'BLOCK_SIZE_N': 64, 'BLOCK_SIZE_K': 32}, num_stages=4, num_warps=4, pre_hook=init_to_zero(["ddt_ptr"])),
  43. triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_N': 128, 'BLOCK_SIZE_K': 32}, num_stages=4, num_warps=4, pre_hook=init_to_zero(["ddt_ptr"])),
  44. triton.Config({'BLOCK_SIZE_M': 128, 'BLOCK_SIZE_N': 32, 'BLOCK_SIZE_K': 32}, num_stages=4, num_warps=4, pre_hook=init_to_zero(["ddt_ptr"])),
  45. triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_N': 32, 'BLOCK_SIZE_K': 32}, num_stages=5, num_warps=4, pre_hook=init_to_zero(["ddt_ptr"])),
  46. triton.Config({'BLOCK_SIZE_M': 32, 'BLOCK_SIZE_N': 64, 'BLOCK_SIZE_K': 32}, num_stages=5, num_warps=4, pre_hook=init_to_zero(["ddt_ptr"])),
  47. triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_N': 64, 'BLOCK_SIZE_K': 32}, num_stages=4, num_warps=4, pre_hook=init_to_zero(["ddt_ptr"])),
  48. ],
  49. key=['chunk_size', 'hdim', 'dstate'],
  50. )
  51. @triton.jit
  52. def _chunk_scan_chunk_state_bwd_dx_kernel(
  53. # Pointers to matrices
  54. x_ptr, cb_ptr, dout_ptr, dt_ptr, dA_cumsum_ptr, seq_idx_ptr, D_ptr,
  55. b_ptr, dstates_ptr,
  56. dx_ptr, ddt_ptr, dD_ptr,
  57. # Matrix dimensions
  58. chunk_size, hdim, dstate,
  59. batch, seqlen, nheads_ngroups_ratio,
  60. # Strides
  61. stride_x_batch, stride_x_seqlen, stride_x_head, stride_x_hdim,
  62. stride_cb_batch, stride_cb_chunk, stride_cb_head, stride_cb_csize_m, stride_cb_csize_k,
  63. stride_dout_batch, stride_dout_seqlen, stride_dout_head, stride_dout_hdim,
  64. stride_dt_batch, stride_dt_chunk, stride_dt_head, stride_dt_csize,
  65. stride_dA_cs_batch, stride_dA_cs_chunk, stride_dA_cs_head, stride_dA_cs_csize,
  66. stride_seq_idx_batch, stride_seq_idx_seqlen,
  67. stride_D_head,
  68. stride_b_batch, stride_b_seqlen, stride_b_head, stride_b_dstate,
  69. stride_dstates_batch, stride_dstates_chunk, stride_dstates_head, stride_dstates_hdim, stride_dstates_dstate,
  70. stride_dx_batch, stride_dx_seqlen, stride_dx_head, stride_dx_hdim,
  71. stride_ddt_batch, stride_ddt_chunk, stride_ddt_head, stride_ddt_csize,
  72. stride_dD_batch, stride_dD_chunk, stride_dD_head, stride_dD_csize, stride_dD_hdim,
  73. # Meta-parameters
  74. HAS_D: tl.constexpr,
  75. D_HAS_HDIM: tl.constexpr,
  76. HAS_SEQ_IDX: tl.constexpr,
  77. BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr,
  78. BLOCK_SIZE_DSTATE: tl.constexpr,
  79. IS_TRITON_22: tl.constexpr,
  80. ):
  81. pid_bc = tl.program_id(axis=1)
  82. pid_c = pid_bc // batch
  83. pid_b = pid_bc - pid_c * batch
  84. pid_h = tl.program_id(axis=2)
  85. num_pid_n = tl.cdiv(hdim, BLOCK_SIZE_N)
  86. pid_m = tl.program_id(axis=0) // num_pid_n
  87. pid_n = tl.program_id(axis=0) % num_pid_n
  88. x_ptr += pid_b * stride_x_batch + pid_c * chunk_size * stride_x_seqlen + pid_h * stride_x_head
  89. cb_ptr += pid_b * stride_cb_batch + pid_c * stride_cb_chunk + (pid_h // nheads_ngroups_ratio) * stride_cb_head
  90. dout_ptr += pid_b * stride_dout_batch + pid_c * chunk_size * stride_dout_seqlen + pid_h * stride_dout_head
  91. dt_ptr += pid_b * stride_dt_batch + pid_c * stride_dt_chunk + pid_h * stride_dt_head
  92. ddt_ptr += pid_b * stride_ddt_batch + pid_c * stride_ddt_chunk + pid_h * stride_ddt_head
  93. dA_cumsum_ptr += pid_b * stride_dA_cs_batch + pid_c * stride_dA_cs_chunk + pid_h * stride_dA_cs_head
  94. b_ptr += pid_b * stride_b_batch + pid_c * chunk_size * stride_b_seqlen + (pid_h // nheads_ngroups_ratio) * stride_b_head
  95. dstates_ptr += pid_b * stride_dstates_batch + pid_c * stride_dstates_chunk + pid_h * stride_dstates_head
  96. if HAS_SEQ_IDX:
  97. seq_idx_ptr += pid_b * stride_seq_idx_batch + pid_c * chunk_size * stride_seq_idx_seqlen
  98. offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
  99. offs_n = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
  100. chunk_size_limit = min(chunk_size, seqlen - pid_c * chunk_size)
  101. acc = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
  102. dA_cs_m = tl.load(dA_cumsum_ptr + offs_m * stride_dA_cs_csize, mask=offs_m < chunk_size_limit, other=0.0).to(tl.float32)
  103. dA_cs_last = tl.load(dA_cumsum_ptr + (chunk_size - 1) * stride_dA_cs_csize).to(tl.float32)
  104. if not HAS_SEQ_IDX:
  105. scale = tl.exp(dA_cs_last - dA_cs_m)
  106. else:
  107. seq_idx_m = tl.load(seq_idx_ptr + offs_m * stride_seq_idx_seqlen, mask=offs_m < chunk_size_limit, other=-1)
  108. seq_idx_last = tl.load(seq_idx_ptr + (chunk_size_limit - 1) * stride_seq_idx_seqlen)
  109. scale = tl.where(seq_idx_m == seq_idx_last, tl.exp(dA_cs_last - dA_cs_m), 0.0)
  110. # Might be faster to just do 1 iteration with larger BLOCK_SIZE_K, up to block size 128
  111. # However, we're getting error with the Triton compiler 2.1.0 for that code path:
  112. # Unexpected mma -> mma layout conversion
  113. # Triton 2.2.0 fixes this
  114. offs_dstate = tl.arange(0, BLOCK_SIZE_DSTATE if IS_TRITON_22 and BLOCK_SIZE_DSTATE <= 128 else BLOCK_SIZE_K)
  115. b_ptrs = b_ptr + (offs_m[:, None] * stride_b_seqlen + offs_dstate[None, :] * stride_b_dstate)
  116. dstates_ptrs = dstates_ptr + (offs_n[None, :] * stride_dstates_hdim + offs_dstate[:, None] * stride_dstates_dstate)
  117. if IS_TRITON_22 and BLOCK_SIZE_DSTATE <= 128:
  118. b = tl.load(b_ptrs, mask=(offs_m[:, None] < chunk_size_limit) & (offs_dstate[None, :] < dstate), other=0.0)
  119. dstates = tl.load(dstates_ptrs, mask=(offs_dstate[:, None] < dstate) & (offs_n[None, :] < hdim), other=0.0)
  120. dstates = dstates.to(b_ptr.dtype.element_ty)
  121. acc = tl.dot(b, dstates) * scale[:, None]
  122. else:
  123. for k in range(0, dstate, BLOCK_SIZE_K):
  124. b = tl.load(b_ptrs, mask=(offs_m[:, None] < chunk_size_limit) & (offs_dstate[None, :] < dstate - k), other=0.0)
  125. dstates = tl.load(dstates_ptrs, mask=(offs_dstate[:, None] < dstate - k) & (offs_n[None, :] < hdim), other=0.0)
  126. dstates = dstates.to(b_ptr.dtype.element_ty)
  127. acc += tl.dot(b, dstates)
  128. b_ptrs += BLOCK_SIZE_K * stride_b_dstate
  129. dstates_ptrs += BLOCK_SIZE_K * stride_dstates_dstate
  130. acc *= scale[:, None]
  131. # x_ptrs = x_ptr + (offs_m[:, None] * stride_x_seqlen + offs_n[None, :] * stride_x_hdim)
  132. # x = tl.load(x_ptrs, mask=(offs_m[:, None] < chunk_size_limit) & (offs_n[None, :] < hdim), other=0.0).to(tl.float32)
  133. # dt_ptrs = dt_ptr + offs_m * stride_dt_csize
  134. # dt_m = tl.load(dt_ptrs, mask=offs_m < chunk_size_limit, other=0.0).to(tl.float32)
  135. # ddt = tl.sum(acc * x, axis=1) * dt_m
  136. # ddt_ptrs = ddt_ptr + offs_m * stride_ddt_csize
  137. # tl.atomic_add(ddt_ptrs, ddt, mask=offs_m < chunk_size)
  138. offs_k = tl.arange(0, BLOCK_SIZE_K)
  139. cb_ptrs = cb_ptr + (offs_m[:, None] * stride_cb_csize_m + offs_k[None, :] * stride_cb_csize_k)
  140. dout_ptrs = dout_ptr + (offs_k[:, None] * stride_dout_seqlen + offs_n[None, :] * stride_dout_hdim)
  141. dA_cumsum_ptrs = dA_cumsum_ptr + offs_k * stride_dA_cs_csize
  142. K_MAX = chunk_size_limit
  143. K_MIN = pid_m * BLOCK_SIZE_M
  144. cb_ptrs += K_MIN * stride_cb_csize_k
  145. dout_ptrs += K_MIN * stride_dout_seqlen
  146. dA_cumsum_ptrs += K_MIN * stride_dA_cs_csize
  147. for k in range(K_MIN, K_MAX, BLOCK_SIZE_K):
  148. k = tl.multiple_of(k, BLOCK_SIZE_K)
  149. # For some reason setting mask to (offs_m[:, None] < chunk_size_limit) is much slower
  150. cb = tl.load(cb_ptrs, mask=(offs_m[:, None] < chunk_size) & (offs_k[None, :] < K_MAX - k), other=0.0)
  151. dout = tl.load(dout_ptrs, mask=(offs_k[:, None] < K_MAX - k) & (offs_n[None, :] < hdim), other=0.0)
  152. dA_cs_k = tl.load(dA_cumsum_ptrs, mask=offs_k < K_MAX - k, other=0.0).to(tl.float32)
  153. cb *= tl.exp(dA_cs_k[None, :] - dA_cs_m[:, None])
  154. # If we don't have the (k + offs_k[None, :] < K_MAX) mask, for indices outside this range,
  155. # we might have dA_cs_m = 0.0 and dA_cs_k very negative, and tl.exp will return inf.
  156. # Multiplying with cb, which is 0.0 outside the range, will make the result NaN.
  157. # This will cause NaN in acc, and hence NaN in dx and ddt.
  158. mask = (k + offs_k[None, :] >= offs_m[:, None]) & (k + offs_k[None, :] < K_MAX)
  159. cb = tl.where(mask, cb, 0.0)
  160. cb = cb.to(dout_ptr.dtype.element_ty)
  161. acc += tl.dot(cb, dout)
  162. cb_ptrs += BLOCK_SIZE_K * stride_cb_csize_k
  163. dout_ptrs += BLOCK_SIZE_K * stride_dout_seqlen
  164. dA_cumsum_ptrs += BLOCK_SIZE_K * stride_dA_cs_csize
  165. offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
  166. offs_n = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
  167. dt_ptrs = dt_ptr + offs_m * stride_dt_csize
  168. dt_m = tl.load(dt_ptrs, mask=offs_m < chunk_size_limit, other=0.0).to(tl.float32)
  169. dx = acc * dt_m[:, None]
  170. dx_ptr += pid_b * stride_dx_batch + pid_c * chunk_size * stride_dx_seqlen + pid_h * stride_dx_head
  171. dx_ptrs = dx_ptr + (offs_m[:, None] * stride_dx_seqlen + offs_n[None, :] * stride_dx_hdim)
  172. if HAS_D:
  173. dout_res_ptrs = dout_ptr + (offs_m[:, None] * stride_dout_seqlen + offs_n[None, :] * stride_dout_hdim)
  174. dout_res = tl.load(dout_res_ptrs, mask=(offs_m[:, None] < chunk_size_limit) & (offs_n[None, :] < hdim), other=0.0).to(tl.float32)
  175. if D_HAS_HDIM:
  176. D = tl.load(D_ptr + pid_h * stride_D_head + offs_n, mask=offs_n < hdim, other=0.0).to(tl.float32)
  177. else:
  178. D = tl.load(D_ptr + pid_h * stride_D_head).to(tl.float32)
  179. dx += dout_res * D
  180. tl.store(dx_ptrs, dx, mask=(offs_m[:, None] < chunk_size_limit) & (offs_n[None, :] < hdim))
  181. x_ptrs = x_ptr + (offs_m[:, None] * stride_x_seqlen + offs_n[None, :] * stride_x_hdim)
  182. x = tl.load(x_ptrs, mask=(offs_m[:, None] < chunk_size_limit) & (offs_n[None, :] < hdim), other=0.0).to(tl.float32)
  183. if HAS_D:
  184. dD_ptr += pid_b * stride_dD_batch + pid_c * stride_dD_chunk + pid_h * stride_dD_head + pid_m * stride_dD_csize
  185. if D_HAS_HDIM:
  186. dD_ptrs = dD_ptr + offs_n * stride_dD_hdim
  187. dD = tl.sum(dout_res * x, axis=0)
  188. tl.store(dD_ptrs, dD, mask=offs_n < hdim)
  189. else:
  190. dD = tl.sum(dout_res * x)
  191. tl.store(dD_ptr, dD)
  192. ddt = tl.sum(acc * x, axis=1)
  193. ddt_ptrs = ddt_ptr + offs_m * stride_ddt_csize
  194. tl.atomic_add(ddt_ptrs, ddt, mask=offs_m < chunk_size)
  195. def _chunk_scan_chunk_state_bwd_dx(x, dt, dA_cumsum, B, CB, dout, dstates, D=None, seq_idx=None, dx=None):
  196. batch, seqlen, nheads, headdim = x.shape
  197. _, _, nchunks, chunk_size = dt.shape
  198. _, _, ngroups, dstate = B.shape
  199. assert nheads % ngroups == 0
  200. assert B.shape == (batch, seqlen, ngroups, dstate)
  201. assert CB.shape == (batch, nchunks, ngroups, chunk_size, chunk_size)
  202. assert dt.shape == (batch, nheads, nchunks, chunk_size)
  203. assert dA_cumsum.shape == dt.shape
  204. assert dout.shape == x.shape
  205. assert dstates.shape == (batch, nchunks, nheads, headdim, dstate)
  206. if seq_idx is not None:
  207. assert seq_idx.shape == (batch, seqlen)
  208. if D is not None:
  209. assert D.shape == (nheads, headdim) or D.shape == (nheads,)
  210. assert D.stride(-1) == 1
  211. BLOCK_SIZE_min = 32
  212. dD = torch.empty(triton.cdiv(chunk_size, BLOCK_SIZE_min), batch, nchunks, nheads,
  213. headdim if D.dim() == 2 else 1, device=D.device, dtype=torch.float32)
  214. else:
  215. dD = None
  216. dD_strides = ((dD.stride(0), dD.stride(1), dD.stride(2), dD.stride(3), dD.stride(4))
  217. if D is not None else (0, 0, 0, 0, 0))
  218. if dx is None:
  219. dx = torch.empty_like(x)
  220. else:
  221. assert dx.shape == x.shape
  222. ddt = torch.empty(batch, nheads, nchunks, chunk_size, device=dout.device, dtype=torch.float32)
  223. grid_dx = lambda META: (triton.cdiv(chunk_size, META['BLOCK_SIZE_M']) * triton.cdiv(headdim, META['BLOCK_SIZE_N']),
  224. batch * nchunks, nheads)
  225. with torch.cuda.device(x.device.index):
  226. _chunk_scan_chunk_state_bwd_dx_kernel[grid_dx](
  227. x, CB, dout, dt, dA_cumsum, seq_idx, D, B, dstates, dx, ddt, dD,
  228. chunk_size, headdim, dstate,
  229. batch, seqlen, nheads // ngroups,
  230. x.stride(0), x.stride(1), x.stride(2), x.stride(3),
  231. CB.stride(0), CB.stride(1), CB.stride(2), CB.stride(-1), CB.stride(-2),
  232. dout.stride(0), dout.stride(1), dout.stride(2), dout.stride(3),
  233. dt.stride(0), dt.stride(2), dt.stride(1), dt.stride(3),
  234. dA_cumsum.stride(0), dA_cumsum.stride(2), dA_cumsum.stride(1), dA_cumsum.stride(3),
  235. *((seq_idx.stride(0), seq_idx.stride(1)) if seq_idx is not None else (0, 0)),
  236. D.stride(0) if D is not None else 0,
  237. B.stride(0), B.stride(1), B.stride(2), B.stride(3),
  238. dstates.stride(0), dstates.stride(1), dstates.stride(2), dstates.stride(3), dstates.stride(4),
  239. dx.stride(0), dx.stride(1), dx.stride(2), dx.stride(3),
  240. ddt.stride(0), ddt.stride(2), ddt.stride(1), ddt.stride(3),
  241. dD_strides[1], dD_strides[2], dD_strides[3], dD_strides[0], dD_strides[4],
  242. D is not None,
  243. D.dim() == 2 if D is not None else True,
  244. HAS_SEQ_IDX=seq_idx is not None,
  245. BLOCK_SIZE_DSTATE=max(triton.next_power_of_2(dstate), 16),
  246. IS_TRITON_22=TRITON_22
  247. )
  248. if D is not None:
  249. BLOCK_SIZE_actual = _chunk_scan_chunk_state_bwd_dx_kernel.best_config.kwargs["BLOCK_SIZE_M"]
  250. n_valid_blocks = (chunk_size + BLOCK_SIZE_actual - 1) // BLOCK_SIZE_actual
  251. dD = dD[:n_valid_blocks].sum(dim=(0, 1, 2)).to(dtype=D.dtype)
  252. if D.dim() == 1:
  253. dD = rearrange(dD, "h 1 -> h")
  254. return dx, ddt.to(dtype=dt.dtype), dD
  255. def _mamba_chunk_scan_combined_fwd(x, dt, A, B, C, chunk_size, D=None, z=None, dt_bias=None, initial_states=None, seq_idx=None, cu_seqlens=None, dt_softplus=False, dt_limit=(0.0, float("inf"))):
  256. batch, seqlen, nheads, headdim = x.shape
  257. _, _, ngroups, dstate = B.shape
  258. assert nheads % ngroups == 0
  259. assert B.shape == (batch, seqlen, ngroups, dstate)
  260. assert x.shape == (batch, seqlen, nheads, headdim)
  261. assert dt.shape == (batch, seqlen, nheads)
  262. assert A.shape == (nheads,)
  263. assert C.shape == B.shape
  264. if z is not None:
  265. assert z.shape == x.shape
  266. if D is not None:
  267. assert D.shape == (nheads, headdim) or D.shape == (nheads,)
  268. if seq_idx is not None:
  269. assert seq_idx.shape == (batch, seqlen)
  270. if B.stride(-1) != 1:
  271. B = B.contiguous()
  272. if C.stride(-1) != 1:
  273. C = C.contiguous()
  274. if x.stride(-1) != 1 and x.stride(1) != 1: # Either M or K dimension should be contiguous
  275. x = x.contiguous()
  276. if z is not None and z.stride(-1) != 1 and z.stride(1) != 1: # Either M or K dimension should be contiguous
  277. z = z.contiguous()
  278. if D is not None and D.stride(-1) != 1:
  279. D = D.contiguous()
  280. if initial_states is not None:
  281. assert initial_states.shape == (batch, nheads, headdim, dstate)
  282. # # (batch, nchunks, chunk_size, chunk_size) or (batch, nchunks, nheads, chunk_size, chunk_size)
  283. # dA_cumsum_tmp0, dt_tmp0 = _chunk_cumsum_fwd(dt[:, :147], A, chunk_size, dt_bias=dt_bias, dt_softplus=dt_softplus)
  284. # dA_cumsum_tmp1, dt_tmp1 = _chunk_cumsum_fwd(dt[:, 147:], A, chunk_size, dt_bias=dt_bias, dt_softplus=dt_softplus)
  285. # dA_cumsum_tmp2, dt_tmp2 = _chunk_cumsum_fwd(dt[:, 147:256], A, chunk_size, dt_bias=dt_bias, dt_softplus=dt_softplus)
  286. dA_cumsum, dt = _chunk_cumsum_fwd(dt, A, chunk_size, dt_bias=dt_bias, dt_softplus=dt_softplus, dt_limit=dt_limit)
  287. states = _chunk_state_fwd(B, x, dt, dA_cumsum, seq_idx=seq_idx, states_in_fp32=True)
  288. # states_tmp0 = _chunk_state_fwd(B[:, :147], x[:, :147], dt_tmp0, dA_cumsum_tmp0, states_in_fp32=True)
  289. # states_tmp1 = _chunk_state_fwd(B[:, 147:], x[:, 147:], dt_tmp1, dA_cumsum_tmp1, states_in_fp32=True)
  290. # states_tmp2 = _chunk_state_fwd(B[:, 147:256], x[:, 147:256], dt_tmp2, dA_cumsum_tmp2, states_in_fp32=True)
  291. states, final_states = _state_passing_fwd(rearrange(states, "... p n -> ... (p n)"), dA_cumsum[:, :, :, -1],
  292. initial_states=rearrange(initial_states, "... p n -> ... (p n)") if initial_states is not None else None,
  293. seq_idx=seq_idx, chunk_size=chunk_size, out_dtype=C.dtype)
  294. states, final_states = [rearrange(t, "... (p n) -> ... p n", n=dstate) for t in [states, final_states]]
  295. # states_tmp0 = rearrange(_state_passing_fwd(rearrange(states_tmp0, "... p n -> ... (p n)"), dA_cumsum_tmp0[:, :, :, -1], chunk_size=chunk_size), "... (p n) -> ... p n", n=dstate)
  296. # states_tmp1 = rearrange(_state_passing_fwd(rearrange(states_tmp1, "... p n -> ... (p n)"), dA_cumsum_tmp1[:, :, :, -1], chunk_size=chunk_size), "... (p n) -> ... p n", n=dstate)
  297. CB = _bmm_chunk_fwd(C, B, chunk_size, seq_idx=seq_idx, output_dtype=torch.float32)
  298. out, out_x = _chunk_scan_fwd(CB, x, dt, dA_cumsum, C, states, D=D, z=z, seq_idx=seq_idx)
  299. if cu_seqlens is None:
  300. return out, out_x, dt, dA_cumsum, states, final_states
  301. else:
  302. assert batch == 1, "passing cu_seqlens to get the varlen states is only supported if batch dimension is 1"
  303. varlen_states = chunk_state_varlen(B.squeeze(0), x.squeeze(0), dt.squeeze(0), dA_cumsum.squeeze(0),
  304. cu_seqlens, states.squeeze(0))
  305. return out, out_x, dt, dA_cumsum, states, final_states, varlen_states
  306. def _mamba_chunk_scan_combined_bwd(dout, x, dt, A, B, C, out, chunk_size, D=None, z=None,
  307. dt_bias=None, initial_states=None, dfinal_states=None, seq_idx=None, dt_softplus=False,
  308. dt_limit=(0.0, float("inf")),
  309. dx=None, ddt=None, dB=None, dC=None, dz=None, recompute_output=False):
  310. if dout.stride(-1) != 1:
  311. dout = dout.contiguous()
  312. batch, seqlen, nheads, headdim = x.shape
  313. nchunks = math.ceil(seqlen / chunk_size)
  314. _, _, ngroups, dstate = B.shape
  315. assert dout.shape == (batch, seqlen, nheads, headdim)
  316. assert dt.shape == (batch, seqlen, nheads)
  317. assert A.shape == (nheads,)
  318. assert nheads % ngroups == 0
  319. assert B.shape == (batch, seqlen, ngroups, dstate)
  320. assert C.shape == B.shape
  321. assert out.shape == x.shape
  322. if initial_states is not None:
  323. assert initial_states.shape == (batch, nheads, headdim, dstate)
  324. if seq_idx is not None:
  325. assert seq_idx.shape == (batch, seqlen)
  326. if dx is not None:
  327. assert dx.shape == x.shape
  328. if dB is not None:
  329. assert dB.shape == B.shape
  330. dB_given = dB
  331. else:
  332. dB_given = torch.empty_like(B)
  333. if dC is not None:
  334. assert dC.shape == C.shape
  335. dC_given = dC
  336. else:
  337. dC_given = torch.empty_like(C)
  338. if dz is not None:
  339. assert z is not None
  340. assert dz.shape == z.shape
  341. if ddt is not None:
  342. assert ddt.shape == dt.shape
  343. ddt_given = ddt
  344. else:
  345. ddt_given = torch.empty_like(dt)
  346. # TD: For some reason Triton (2.1.0 and 2.2.0) errors with
  347. # "[CUDA]: invalid device context" (e.g. during varlne test), and cloning makes it work. Idk why.
  348. dt_in = dt.clone()
  349. dA_cumsum, dt = _chunk_cumsum_fwd(dt_in, A, chunk_size, dt_bias=dt_bias, dt_softplus=dt_softplus,
  350. dt_limit=dt_limit)
  351. CB = _bmm_chunk_fwd(C, B, chunk_size, seq_idx=seq_idx, output_dtype=torch.float32)
  352. states = _chunk_state_fwd(B, x, dt, dA_cumsum, seq_idx=seq_idx, states_in_fp32=True)
  353. states, _ = _state_passing_fwd(rearrange(states, "... p n -> ... (p n)"), dA_cumsum[:, :, :, -1],
  354. initial_states=rearrange(initial_states, "... p n -> ... (p n)") if initial_states is not None else None,
  355. seq_idx=seq_idx, chunk_size=chunk_size)
  356. states = rearrange(states, "... (p n) -> ... p n", n=dstate)
  357. if z is not None:
  358. dz, dout, dD, *rest = _chunk_scan_bwd_dz(x, z, out, dout, chunk_size=chunk_size, has_ddAcs=False, D=D, dz=dz, recompute_output=recompute_output)
  359. outz = rest[0] if recompute_output else out
  360. else:
  361. dz = None
  362. outz = out
  363. dstates = _chunk_scan_bwd_dstates(C, dA_cumsum, dout, seq_idx=seq_idx, dtype=states.dtype)
  364. # dstates has length nchunks, containing the gradient to initial states at index 0 and
  365. # gradient to the states of chunk (nchunks - 2) at index (nchunks - 1)
  366. # Do computation in fp32 but convert dstates and states to fp16/bf16 since dstates and states
  367. # will be used in matmul in the next kernels.
  368. dstates, ddA_chunk_cumsum, dinitial_states, states = _state_passing_bwd(
  369. rearrange(states, "... p n -> ... (p n)"),
  370. dA_cumsum[:, :, :, -1],
  371. rearrange(dstates, "... p n -> ... (p n)"),
  372. dfinal_states=rearrange(dfinal_states, "... p n -> ... (p n)") if dfinal_states is not None else None,
  373. seq_idx=seq_idx,
  374. has_initial_states=initial_states is not None,
  375. dstates_dtype=x.dtype,
  376. states_dtype=x.dtype,
  377. chunk_size=chunk_size,
  378. )
  379. # dstates has length nchunks, containing the gradient to states of chunk 0 at index 0 and
  380. # gradient to the final states at index (nchunks - 1)
  381. # states has length nchunks, containing the initial states at index 0 and the state for chunk (nchunks - 2) at index (nchunks - 1)
  382. # The final states is not stored.
  383. states = rearrange(states, "... (p n) -> ... p n", n=dstate)
  384. dstates = rearrange(dstates, "... (p n) -> ... p n", n=dstate)
  385. dinitial_states = rearrange(dinitial_states, "... (p n) -> ... p n", n=dstate) if dinitial_states is not None else None
  386. dx, ddt, dD_from_x = _chunk_scan_chunk_state_bwd_dx(x, dt, dA_cumsum, B, CB, dout, dstates, D=D, seq_idx=seq_idx, dx=dx)
  387. # dB = _chunk_state_bwd_db(x, dt, dA_cumsum, dstates, seq_idx=seq_idx, ngroups=ngroups)
  388. dB, ddA_next = _chunk_state_bwd_db(x, dt, dA_cumsum, dstates, seq_idx=seq_idx, B=B, ngroups=ngroups)
  389. # dC = _chunk_scan_bwd_dC(states[:, :-1].to(x.dtype), dA_cumsum, dout, seq_idx=seq_idx, ngroups=ngroups)
  390. dC, ddA_cumsum_prev = _chunk_scan_bwd_dC(states.to(x.dtype), dA_cumsum, dout, seq_idx=seq_idx, C=C, ngroups=ngroups)
  391. # Computing ddA with the dcb kernel is much slower, so we're not using it for now
  392. dCB = _chunk_scan_bwd_dcb(x, dt, dA_cumsum, dout, seq_idx=seq_idx, ngroups=ngroups)
  393. # dCB, ddA_tmp = _chunk_scan_bwd_dcb(x, dt, dA_cumsum, dout, seq_idx=seq_idx, CB=CB, ngroups=ngroups)
  394. dCB = dCB.to(CB.dtype)
  395. _bmm_chunk_bwd(C, dCB, residual=dB, out=dB_given)
  396. _bmm_chunk_bwd(B, rearrange(dCB, "... l s -> ... s l"), residual=dC, out=dC_given)
  397. # If we have z, then dout_x is recomputed in fp32 so dD = (dout_x * x).sum() is more accurate
  398. # than dD_from_x = (dout_x * x).sum() where dout_x is in fp16/bf16
  399. if z is None:
  400. dD = dD_from_x
  401. # Formula for ddA_cumsum, assuming out is the output of the forward pass before adding x * D.
  402. # ddA_cumsum = torch.einsum("bclhp,bclhp->bhcl", out.float(), dout.float()) - ddt * dt
  403. # However, this is numerically unstable: when we do the reverse cumsum on ddA_cumsum, there might
  404. # be a lot of underflow.
  405. # This is already done as part of bwd_dC kernel
  406. # ddA_cumsum_prev = _chunk_scan_bwd_ddAcs_prev(states[:, :-1], C, dout, dA_cumsum, seq_idx=seq_idx)
  407. ddA_cumsum_prev[..., -1] += ddA_chunk_cumsum
  408. ddA_prev = ddA_cumsum_prev.flip([-1]).cumsum(dim=-1).flip([-1])
  409. # This is already done as part of bwd_dB kernel
  410. # ddA_next = _chunk_state_bwd_ddAcs_stable(B, x, dt, dA_cumsum, dstates, seq_idx=seq_idx)
  411. # We don't need to pass in seq_idx because CB also zeros out entries where seq_idx[i] != seq_idx[j]
  412. ddA = _chunk_scan_bwd_ddAcs_stable(x, dt, dA_cumsum, dout, CB)
  413. ddA += ddA_next + ddA_prev
  414. ddt_given, dA, ddt_bias = _chunk_cumsum_bwd(ddA, ddt, dt_in, A, dt_bias=dt_bias, dt_softplus=dt_softplus, dt_limit=dt_limit, ddt=ddt_given)
  415. # These 2 lines are just to test ddt and dA being computed by old code
  416. # _, dA = selective_scan_bwd(dout, x, dt, A, B, C, D=D.float(), z=z)
  417. # ddt_given.copy_(ddt)
  418. return_vals = (dx, ddt_given, dA, dB_given, dC_given, dD, dz, ddt_bias, dinitial_states)
  419. return return_vals if not recompute_output else (*return_vals, outz)
  420. def selective_scan_bwd(dout, x, dt, A, B, C, D=None, z=None):
  421. """
  422. Argument:
  423. dout: (batch, seqlen, nheads, headdim)
  424. x: (batch, seqlen, nheads, headdim)
  425. dt: (batch, nheads, nchunks, chunk_size) or (batch, nheads, headdim, nchunks, chunk_size)
  426. A: (nheads) or (dim, dstate)
  427. B: (batch, seqlen, ngroups, dstate)
  428. C: (batch, seqlen, ngroups, dstate)
  429. D: (nheads, headdim) or (nheads,)
  430. z: (batch, seqlen, nheads, headdim)
  431. Return:
  432. out: (batch, seqlen, nheads, headdim)
  433. """
  434. import selective_scan
  435. batch, seqlen, nheads, headdim = x.shape
  436. chunk_size = dt.shape[-1]
  437. _, _, ngroups, dstate = B.shape
  438. assert nheads % ngroups == 0
  439. x = rearrange(x, "b l h p -> b (h p) l")
  440. squeeze_dt = dt.dim() == 4
  441. if dt.dim() == 4:
  442. dt = repeat(dt, "b h c l -> b h p c l", p=headdim)
  443. dt = rearrange(dt, "b h p c l -> b (h p) (c l)", p=headdim)
  444. squeeze_A = A.dim() == 1
  445. if A.dim() == 1:
  446. A = repeat(A, "h -> (h p) n", p=headdim, n=dstate).to(dtype=torch.float32)
  447. else:
  448. A = A.to(dtype=torch.float32)
  449. B = rearrange(B, "b l g n -> b g n l")
  450. C = rearrange(C, "b l g n -> b g n l")
  451. if D is not None:
  452. if D.dim() == 2:
  453. D = rearrange(D, "h p -> (h p)")
  454. else:
  455. D = repeat(D, "h -> (h p)", p=headdim)
  456. if z is not None:
  457. z = rearrange(z, "b l h p -> b (h p) l")
  458. if x.stride(-1) != 1:
  459. x = x.contiguous()
  460. if dt.stride(-1) != 1:
  461. dt = dt.contiguous()
  462. if D is not None:
  463. D = D.contiguous()
  464. if B.stride(-1) != 1:
  465. B = B.contiguous()
  466. if C.stride(-1) != 1:
  467. C = C.contiguous()
  468. if z is not None and z.stride(-1) != 1:
  469. z = z.contiguous()
  470. _, intermediate, *rest = selective_scan.fwd(x, dt.to(dtype=x.dtype), A, B, C, D, z, None, False)
  471. if z is not None:
  472. out = rest[0]
  473. else:
  474. out = None
  475. dout = rearrange(dout, "b l h p -> b (h p) l")
  476. if dout.stride(-1) != 1:
  477. dout = dout.contiguous()
  478. # The kernel supports passing in a pre-allocated dz (e.g., in case we want to fuse the
  479. # backward of selective_scan with the backward of chunk).
  480. # Here we just pass in None and dz will be allocated in the C++ code.
  481. _, ddt, dA, *rest = selective_scan.bwd(
  482. x, dt.to(dtype=x.dtype), A, B, C, D, z, None, dout, intermediate, out, None, False,
  483. False # option to recompute out_z, not used here
  484. )
  485. ddt = rearrange(ddt, "b (h p) (c l) -> b h p c l", p=headdim, l=chunk_size)
  486. if squeeze_dt:
  487. ddt = ddt.float().sum(dim=2)
  488. if squeeze_A:
  489. dA = rearrange(dA, "(h p) n -> h p n", p=headdim).sum(dim=(1, 2))
  490. return ddt, dA
  491. class MambaChunkScanCombinedFn(torch.autograd.Function):
  492. @staticmethod
  493. def forward(ctx, x, dt, A, B, C, chunk_size, D=None, z=None, dt_bias=None, initial_states=None, seq_idx=None, cu_seqlens=None, dt_softplus=False, dt_limit=(0.0, float("inf")), return_final_states=False, return_varlen_states=False):
  494. ctx.dt_dtype = dt.dtype
  495. if not return_varlen_states:
  496. cu_seqlens = None
  497. else:
  498. assert cu_seqlens is not None, "cu_seqlens must be provided if return_varlen_states is True"
  499. out, out_x, dt_out, dA_cumsum, states, final_states, *rest = _mamba_chunk_scan_combined_fwd(x, dt, A, B, C, chunk_size, D=D, z=z, dt_bias=dt_bias, initial_states=initial_states, seq_idx=seq_idx, cu_seqlens=cu_seqlens, dt_softplus=dt_softplus, dt_limit=dt_limit)
  500. ctx.save_for_backward(out if z is None else out_x, x, dt, dA_cumsum, A, B, C, D, z, dt_bias, initial_states, seq_idx)
  501. ctx.dt_softplus = dt_softplus
  502. ctx.chunk_size = chunk_size
  503. ctx.dt_limit = dt_limit
  504. ctx.return_final_states = return_final_states
  505. ctx.return_varlen_states = return_varlen_states
  506. if not return_varlen_states:
  507. return out if not return_final_states else (out, final_states)
  508. else:
  509. varlen_states = rest[0]
  510. return (out, varlen_states) if not return_final_states else (out, final_states, varlen_states)
  511. @staticmethod
  512. def backward(ctx, dout, *args):
  513. out, x, dt, dA_cumsum, A, B, C, D, z, dt_bias, initial_states, seq_idx = ctx.saved_tensors
  514. assert not ctx.return_varlen_states, "return_varlen_states is not supported in backward"
  515. dfinal_states = args[0] if ctx.return_final_states else None
  516. dx, ddt, dA, dB, dC, dD, dz, ddt_bias, dinitial_states = _mamba_chunk_scan_combined_bwd(dout, x, dt, A, B, C, out, ctx.chunk_size, D=D, z=z, dt_bias=dt_bias, initial_states=initial_states, dfinal_states=dfinal_states, seq_idx=seq_idx, dt_softplus=ctx.dt_softplus, dt_limit=ctx.dt_limit)
  517. return dx, ddt, dA, dB, dC, None, dD, dz, ddt_bias, dinitial_states, None, None, None, None, None, None
  518. def mamba_chunk_scan_combined(x, dt, A, B, C, chunk_size, D=None, z=None, dt_bias=None, initial_states=None, seq_idx=None, cu_seqlens=None, dt_softplus=False, dt_limit=(0.0, float("inf")), return_final_states=False, return_varlen_states=False):
  519. """
  520. Argument:
  521. x: (batch, seqlen, nheads, headdim)
  522. dt: (batch, seqlen, nheads)
  523. A: (nheads)
  524. B: (batch, seqlen, ngroups, dstate)
  525. C: (batch, seqlen, ngroups, dstate)
  526. chunk_size: int
  527. D: (nheads, headdim) or (nheads,)
  528. z: (batch, seqlen, nheads, headdim)
  529. dt_bias: (nheads,)
  530. initial_states: (batch, nheads, headdim, dstate)
  531. seq_idx: (batch, seqlen)
  532. cu_seqlens: (num_sequences + 1) or None, only used if return_varlen_states is True
  533. dt_softplus: Whether to apply softplus to dt
  534. Return:
  535. out: (batch, seqlen, nheads, headdim)
  536. """
  537. return MambaChunkScanCombinedFn.apply(x, dt, A, B, C, chunk_size, D, z, dt_bias, initial_states, seq_idx, cu_seqlens, dt_softplus, dt_limit, return_final_states, return_varlen_states)
  538. def mamba_chunk_scan(x, dt, A, B, C, chunk_size, D=None, z=None, dt_bias=None, dt_softplus=False):
  539. """
  540. Argument:
  541. x: (batch, seqlen, nheads, headdim)
  542. dt: (batch, seqlen, nheads)
  543. A: (nheads)
  544. B: (batch, seqlen, ngroups, dstate)
  545. C: (batch, seqlen, ngroups, dstate)
  546. D: (nheads, headdim) or (nheads,)
  547. z: (batch, seqlen, nheads, headdim)
  548. dt_bias: (nheads,)
  549. Return:
  550. out: (batch, seqlen, nheads, headdim)
  551. """
  552. batch, seqlen, nheads, headdim = x.shape
  553. dstate = B.shape[-1]
  554. if seqlen % chunk_size != 0:
  555. dt = F.pad(dt, (0, 0, 0, chunk_size - seqlen % chunk_size))
  556. dt = rearrange(dt, "b (c l) h -> b h c l", l=chunk_size)
  557. dt = dt.float() # We want high precision for this before cumsum
  558. if dt_bias is not None:
  559. dt = dt + rearrange(dt_bias, "h -> h 1 1")
  560. if dt_softplus:
  561. dt = F.softplus(dt)
  562. dA = dt * rearrange(A, "h -> h 1 1")
  563. dA = dt * rearrange(A, "h -> h 1 1")
  564. dA_cumsum = torch.cumsum(dA, dim=-1)
  565. # 1. Compute the state for each chunk
  566. states = chunk_state(B, x, dt, dA_cumsum, states_in_fp32=True)
  567. # 2. Pass the state to all the chunks by weighted cumsum.
  568. states = rearrange(state_passing(rearrange(states, "... p n -> ... (p n)"), dA_cumsum[:, :, :, -1])[0],
  569. "... (p n) -> ... p n", n=dstate)
  570. # 3. Compute the output for each chunk
  571. out = chunk_scan(B, C, x, dt, dA_cumsum, states, D=D, z=z)
  572. return out
  573. def ssd_chunk_scan_combined_ref(x, dt, A, B, C, chunk_size, D=None, z=None, dt_bias=None, dt_softplus=False):
  574. """
  575. Argument:
  576. x: (batch, seqlen, nheads, headdim)
  577. dt: (batch, seqlen, nheads)
  578. A: (nheads)
  579. B: (batch, seqlen, ngroups, dstate)
  580. C: (batch, seqlen, ngroups, dstate)
  581. D: (nheads, headdim) or (nheads,)
  582. z: (batch, seqlen, nheads, headdim)
  583. dt_bias: (nheads,)
  584. Return:
  585. out: (batch, seqlen, nheads, headdim)
  586. """
  587. batch, seqlen, nheads, headdim = x.shape
  588. dstate = B.shape[-1]
  589. if seqlen % chunk_size != 0:
  590. dt = F.pad(dt, (0, 0, 0, chunk_size - seqlen % chunk_size))
  591. dt = rearrange(dt, "b (c l) h -> b h c l", l=chunk_size)
  592. dt = dt.float() # We want high precision for this before cumsum
  593. if dt_bias is not None:
  594. dt = dt + rearrange(dt_bias, "h -> h 1 1")
  595. if dt_softplus:
  596. dt = F.softplus(dt)
  597. dA = dt * rearrange(A, "h -> h 1 1")
  598. dA_cumsum = torch.cumsum(dA, dim=-1)
  599. # 1. Compute the state for each chunk
  600. states = chunk_state_ref(B, x, dt, dA_cumsum)
  601. states_dtype = states.dtype
  602. if states.dtype not in [torch.float32, torch.float64]:
  603. states = states.to(torch.float32)
  604. # 2. Pass the state to all the chunks by weighted cumsum.
  605. # state_passing_ref is much less numerically stable
  606. states = rearrange(state_passing_ref(rearrange(states, "... p n -> ... (p n)"), dA_cumsum[:, :, :, -1])[0],
  607. "... (p n) -> ... p n", n=dstate)
  608. states = states.to(states_dtype)
  609. # 3. Compute the output for each chunk
  610. out = chunk_scan_ref(B, C, x, dt, dA_cumsum, states, D=D, z=z)
  611. return out
  612. def ssd_selective_scan(x, dt, A, B, C, D=None, z=None, dt_bias=None, dt_softplus=False, dt_limit=(0.0, float("inf"))):
  613. """
  614. Argument:
  615. x: (batch, seqlen, nheads, headdim)
  616. dt: (batch, seqlen, nheads) or (batch, seqlen, nheads, headdim)
  617. A: (nheads) or (dim, dstate)
  618. B: (batch, seqlen, ngroups, dstate)
  619. C: (batch, seqlen, ngroups, dstate)
  620. D: (nheads, headdim) or (nheads,)
  621. z: (batch, seqlen, nheads, headdim)
  622. dt_bias: (nheads,) or (nheads, headdim)
  623. Return:
  624. out: (batch, seqlen, nheads, headdim)
  625. """
  626. from mamba_ssm.ops.selective_scan_interface import selective_scan_fn
  627. batch, seqlen, nheads, headdim = x.shape
  628. _, _, ngroups, dstate = B.shape
  629. x = rearrange(x, "b l h p -> b (h p) l")
  630. if dt.dim() == 3:
  631. dt = repeat(dt, "b l h -> b l h p", p=headdim)
  632. dt = rearrange(dt, "b l h p -> b (h p) l")
  633. if A.dim() == 1:
  634. A = repeat(A, "h -> (h p) n", p=headdim, n=dstate).to(dtype=torch.float32)
  635. else:
  636. A = A.to(dtype=torch.float32)
  637. B = rearrange(B, "b l g n -> b g n l")
  638. C = rearrange(C, "b l g n -> b g n l")
  639. if D is not None:
  640. if D.dim() == 2:
  641. D = rearrange(D, "h p -> (h p)")
  642. else:
  643. D = repeat(D, "h -> (h p)", p=headdim)
  644. if z is not None:
  645. z = rearrange(z, "b l h p -> b (h p) l")
  646. if dt_bias is not None:
  647. if dt_bias.dim() == 1:
  648. dt_bias = repeat(dt_bias, "h -> h p", p=headdim)
  649. dt_bias = rearrange(dt_bias, "h p -> (h p)")
  650. if dt_limit != (0.0, float("inf")):
  651. if dt_bias is not None:
  652. dt = dt + rearrange(dt_bias, "d -> d 1")
  653. if dt_softplus:
  654. dt = F.softplus(dt)
  655. dt = dt.clamp(min=dt_limit[0], max=dt_limit[1]).to(x.dtype)
  656. dt_bias = None
  657. dt_softplus = None
  658. out = selective_scan_fn(x, dt, A, B, C, D=D, z=z, delta_bias=dt_bias, delta_softplus=dt_softplus)
  659. return rearrange(out, "b (h p) l -> b l h p", p=headdim)
  660. def mamba_conv1d_scan_ref(xBC, conv1d_weight, conv1d_bias, dt, A, chunk_size, D=None, z=None,
  661. dt_bias=None, dt_softplus=False, dt_limit=(0.0, float("inf")),
  662. activation="silu", headdim=None, ngroups=1):
  663. """
  664. Argument:
  665. xBC: (batch, seqlen, dim + 2 * ngroups * dstate) where dim == nheads * headdim
  666. conv1d_weight: (dim + 2 * ngroups * dstate, width)
  667. conv1d_bias: (dim + 2 * ngroups * dstate,)
  668. dt: (batch, seqlen, nheads) or (batch, seqlen, nheads, headdim)
  669. A: (nheads)
  670. D: (nheads, headdim) or (nheads,)
  671. z: (batch, seqlen, dim)
  672. dt_bias: (nheads) or (nheads, headdim)
  673. headdim: if D is 1D and z is None, headdim must be passed in
  674. Return:
  675. out: (batch, seqlen, dim)
  676. """
  677. batch, seqlen, nheads = dt.shape[:3]
  678. assert nheads % ngroups == 0
  679. if z is not None:
  680. dim = z.shape[-1]
  681. assert dim % nheads == 0
  682. headdim = dim // nheads
  683. else:
  684. if D.dim() == 1:
  685. assert headdim is not None
  686. else:
  687. headdim = D.shape[1]
  688. dim = nheads * headdim
  689. xBC = rearrange(causal_conv1d_fn(rearrange(xBC, "b s d -> b d s"), conv1d_weight, conv1d_bias, activation=activation),
  690. "b d s -> b s d")
  691. dstate = (xBC.shape[-1] - dim) // ngroups // 2
  692. x, B, C = torch.split(xBC, [dim, ngroups * dstate, ngroups * dstate], dim=-1)
  693. x = rearrange(x, "b l (h p) -> b l h p", h=nheads)
  694. B = rearrange(B, "b l (g n) -> b l g n", g=ngroups)
  695. C = rearrange(C, "b l (g n) -> b l g n", g=ngroups)
  696. z = rearrange(z, "b l (h p) -> b l h p", h=nheads) if z is not None else None
  697. out = ssd_selective_scan(x, dt.to(x.dtype), A, B, C, D=D.float(), z=z, dt_bias=dt_bias, dt_softplus=dt_softplus, dt_limit=dt_limit)
  698. return rearrange(out, "b s h p -> b s (h p)")
  699. class MambaSplitConv1dScanCombinedFn(torch.autograd.Function):
  700. @staticmethod
  701. @custom_fwd
  702. def forward(ctx, zxbcdt, conv1d_weight, conv1d_bias, dt_bias, A, D, chunk_size, initial_states=None, seq_idx=None, dt_limit=(0.0, float("inf")), return_final_states=False, activation="silu",
  703. rmsnorm_weight=None, rmsnorm_eps=1e-6, outproj_weight=None, outproj_bias=None, headdim=None,
  704. ngroups=1, norm_before_gate=True):
  705. assert activation in [None, "silu", "swish"]
  706. if D.dim() == 1:
  707. assert headdim is not None
  708. nheads, = D.shape
  709. else:
  710. nheads, headdim = D.shape
  711. batch, seqlen, _ = zxbcdt.shape
  712. dim = nheads * headdim
  713. assert nheads % ngroups == 0
  714. dstate = (conv1d_weight.shape[0] - dim) // ngroups // 2
  715. d_nonssm = (zxbcdt.shape[-1] - 2 * dim - 2 * ngroups * dstate - nheads) // 2
  716. assert d_nonssm >= 0
  717. assert zxbcdt.shape == (batch, seqlen, 2 * d_nonssm + 2 * dim + 2 * ngroups * dstate + nheads)
  718. assert dt_bias.shape == (nheads,)
  719. assert A.shape == (nheads,)
  720. zx0, z, xBC, dt = torch.split(zxbcdt, [2 * d_nonssm, dim, dim + ngroups * dstate * 2, nheads], dim=-1)
  721. seq_idx = seq_idx.contiguous() if seq_idx is not None else None
  722. xBC_conv = rearrange(
  723. causal_conv1d_cuda.causal_conv1d_fwd(rearrange(xBC, "b s d -> b d s"),
  724. conv1d_weight, conv1d_bias, seq_idx, None, None, activation in ["silu", "swish"]),
  725. "b d s -> b s d"
  726. )
  727. x, B, C = torch.split(xBC_conv, [dim, ngroups * dstate, ngroups * dstate], dim=-1)
  728. x = rearrange(x, "b l (h p) -> b l h p", h=nheads)
  729. B = rearrange(B, "b l (g n) -> b l g n", g=ngroups)
  730. C = rearrange(C, "b l (g n) -> b l g n", g=ngroups)
  731. z = rearrange(z, "b l (h p) -> b l h p", h=nheads) if z is not None else None
  732. if rmsnorm_weight is None:
  733. out, out_x, dt_out, dA_cumsum, states, final_states = _mamba_chunk_scan_combined_fwd(x, dt, A, B, C, chunk_size=chunk_size, D=D, z=z, dt_bias=dt_bias, initial_states=initial_states, seq_idx=seq_idx, dt_softplus=True, dt_limit=dt_limit)
  734. out = rearrange(out, "b s h p -> b s (h p)")
  735. rstd = None
  736. if d_nonssm > 0:
  737. out = torch.cat([_swiglu_fwd(zx0), out], dim=-1)
  738. else:
  739. out_x, _, dt_out, dA_cumsum, states, final_states = _mamba_chunk_scan_combined_fwd(x, dt, A, B, C, chunk_size=chunk_size, D=D, z=None, dt_bias=dt_bias, initial_states=initial_states, seq_idx=seq_idx, dt_softplus=True, dt_limit=dt_limit)
  740. # reshape input data into 2D tensor
  741. x_rms = rearrange(out_x, "b s h p -> (b s) (h p)")
  742. z_rms = rearrange(z, "b s h p -> (b s) (h p)")
  743. rmsnorm_weight = rmsnorm_weight.contiguous()
  744. if d_nonssm == 0:
  745. out = None
  746. else:
  747. out01 = torch.empty((batch, seqlen, d_nonssm + dim), dtype=x_rms.dtype, device=x_rms.device)
  748. out = rearrange(out01[..., d_nonssm:], "b s d -> (b s) d")
  749. _swiglu_fwd(zx0, out=out01[..., :d_nonssm])
  750. out, _, rstd = _layer_norm_fwd(x_rms, rmsnorm_weight, None, rmsnorm_eps, z_rms, out=out,
  751. group_size=dim // ngroups,
  752. norm_before_gate=norm_before_gate, is_rms_norm=True)
  753. if d_nonssm == 0:
  754. out = rearrange(out, "(b s) d -> b s d", b=batch)
  755. else:
  756. out = out01
  757. ctx.outproj_weight_dtype = outproj_weight.dtype if outproj_weight is not None else None
  758. if outproj_weight is not None:
  759. if torch.is_autocast_enabled():
  760. dtype = torch.get_autocast_gpu_dtype()
  761. out, outproj_weight = out.to(dtype), outproj_weight.to(dtype)
  762. outproj_bias = outproj_bias.to(dtype) if outproj_bias is not None else None
  763. out = F.linear(out, outproj_weight, outproj_bias)
  764. else:
  765. assert outproj_bias is None
  766. ctx.save_for_backward(zxbcdt, conv1d_weight, conv1d_bias,
  767. out_x, A, D, dt_bias, initial_states, seq_idx, rmsnorm_weight, rstd, outproj_weight, outproj_bias)
  768. ctx.dt_limit = dt_limit
  769. ctx.return_final_states = return_final_states
  770. ctx.activation = activation
  771. ctx.rmsnorm_eps = rmsnorm_eps
  772. ctx.norm_before_gate = norm_before_gate
  773. ctx.chunk_size = chunk_size
  774. ctx.headdim = headdim
  775. ctx.ngroups = ngroups
  776. return out if not return_final_states else (out, final_states)
  777. @staticmethod
  778. @custom_bwd
  779. def backward(ctx, dout, *args):
  780. zxbcdt, conv1d_weight, conv1d_bias, out, A, D, dt_bias, initial_states, seq_idx, rmsnorm_weight, rstd, outproj_weight, outproj_bias = ctx.saved_tensors
  781. dfinal_states = args[0] if ctx.return_final_states else None
  782. headdim = ctx.headdim
  783. nheads = D.shape[0]
  784. dim = nheads * headdim
  785. assert nheads % ctx.ngroups == 0
  786. dstate = (conv1d_weight.shape[0] - dim) // ctx.ngroups // 2
  787. d_nonssm = (zxbcdt.shape[-1] - 2 * dim - 2 * ctx.ngroups * dstate - nheads) // 2
  788. assert d_nonssm >= 0
  789. recompute_output = outproj_weight is not None
  790. if recompute_output:
  791. out_recompute = torch.empty(*out.shape[:2], d_nonssm + dim, device=out.device, dtype=out.dtype)
  792. out0_recompute, out1_recompute = out_recompute.split([d_nonssm, dim], dim=-1)
  793. zx0, z, xBC, dt = torch.split(zxbcdt, [2 * d_nonssm, dim, dim + 2 * ctx.ngroups * dstate, nheads], dim=-1)
  794. # Recompute x, B, C
  795. xBC_conv = rearrange(
  796. causal_conv1d_cuda.causal_conv1d_fwd(rearrange(xBC, "b s d -> b d s"),
  797. conv1d_weight, conv1d_bias, seq_idx, None, None, ctx.activation in ["silu", "swish"]),
  798. "b d s -> b s d"
  799. )
  800. x, B, C = torch.split(xBC_conv, [dim, ctx.ngroups * dstate, ctx.ngroups * dstate], dim=-1)
  801. x = rearrange(x, "b l (h p) -> b l h p", h=nheads)
  802. B = rearrange(B, "b l (g n) -> b l g n", g=ctx.ngroups)
  803. C = rearrange(C, "b l (g n) -> b l g n", g=ctx.ngroups)
  804. dzxbcdt = torch.empty_like(zxbcdt)
  805. dzx0, dz, dxBC_given, ddt_given = torch.split(dzxbcdt, [2 * d_nonssm, dim, dim + 2 * ctx.ngroups * dstate, nheads], dim=-1)
  806. dxBC = torch.empty_like(xBC)
  807. dx, dB, dC = torch.split(dxBC, [dim, ctx.ngroups * dstate, ctx.ngroups * dstate], dim=-1)
  808. z = rearrange(z, "b l (h p) -> b l h p", h=nheads)
  809. dx = rearrange(dx, "b l (h p) -> b l h p", h=nheads)
  810. dB = rearrange(dB, "b l (g n) -> b l g n", g=ctx.ngroups)
  811. dC = rearrange(dC, "b l (g n) -> b l g n", g=ctx.ngroups)
  812. if outproj_weight is not None:
  813. dout_og = dout
  814. dout = F.linear(dout, outproj_weight.t())
  815. if d_nonssm > 0:
  816. dout0, dout = dout.split([d_nonssm, dim], dim=-1)
  817. _swiglu_bwd(zx0, dout0, dxy=dzx0, recompute_output=True, out=out0_recompute)
  818. dout = rearrange(dout, "b s (h p) -> b s h p", p=headdim)
  819. if rmsnorm_weight is None:
  820. dz = rearrange(dz, "b l (h p) -> b l h p", h=nheads)
  821. dx, ddt, dA, dB, dC, dD, dz, ddt_bias, dinitial_states, *rest = _mamba_chunk_scan_combined_bwd(
  822. dout, x, dt, A, B, C, out, ctx.chunk_size, D=D, z=z, dt_bias=dt_bias, initial_states=initial_states, dfinal_states=dfinal_states, seq_idx=seq_idx, dt_softplus=True, dt_limit=ctx.dt_limit, dx=dx, ddt=ddt_given, dB=dB, dC=dC, dz=dz, recompute_output=recompute_output
  823. )
  824. out_for_linear = rearrange(rest[0], "b s h p -> b s (h p)") if recompute_output else None
  825. drmsnorm_weight = None
  826. else:
  827. batch = dout.shape[0]
  828. dy_rms = rearrange(dout, "b s h p -> (b s) (h p)")
  829. dz = rearrange(dz, "b l d -> (b l) d")
  830. x_rms = rearrange(out, "b s h p -> (b s) (h p)")
  831. z_rms = rearrange(z, "b s h p -> (b s) (h p)")
  832. out1_recompute = rearrange(out1_recompute, "b s d -> (b s) d") if recompute_output else None
  833. dout, drmsnorm_weight, _, dz, *rest = _layer_norm_bwd(dy_rms, x_rms, rmsnorm_weight, None, ctx.rmsnorm_eps, None, rstd, z_rms, group_size=dim//ctx.ngroups, norm_before_gate=ctx.norm_before_gate, is_rms_norm=True, recompute_output=recompute_output, dz=dz, out=out1_recompute if recompute_output else None)
  834. out_for_linear = out_recompute if recompute_output else None
  835. dout = rearrange(dout, "(b s) (h p) -> b s h p", b=batch, p=headdim)
  836. dx, ddt, dA, dB, dC, dD, _, ddt_bias, dinitial_states = _mamba_chunk_scan_combined_bwd(
  837. dout, x, dt, A, B, C, out, ctx.chunk_size, D=D, z=None, dt_bias=dt_bias, initial_states=initial_states, dfinal_states=dfinal_states, seq_idx=seq_idx, dt_softplus=True, dt_limit=ctx.dt_limit, dx=dx, ddt=ddt_given, dB=dB, dC=dC
  838. )
  839. if outproj_weight is not None:
  840. doutproj_weight = torch.einsum("bso,bsd->od", dout_og, out_for_linear)
  841. doutproj_bias = dout_og.sum(dim=(0, 1)) if outproj_bias is not None else None
  842. else:
  843. doutproj_weight, doutproj_bias = None, None
  844. dxBC_given = rearrange(dxBC_given, "b s d -> b d s")
  845. dxBC_given, dweight, dbias, *_ = causal_conv1d_cuda.causal_conv1d_bwd(
  846. rearrange(xBC, "b s d -> b d s"), conv1d_weight, conv1d_bias,
  847. rearrange(dxBC, "b s d -> b d s"), seq_idx, None, None, dxBC_given, False, ctx.activation in ["silu", "swish"]
  848. )
  849. dxBC_given = rearrange(dxBC_given, "b d s -> b s d")
  850. return dzxbcdt, dweight, dbias, ddt_bias, dA, dD, None, dinitial_states, None, None, None, None, drmsnorm_weight, None, doutproj_weight, doutproj_bias, None, None, None
  851. def mamba_split_conv1d_scan_combined(zxbcdt, conv1d_weight, conv1d_bias, dt_bias, A, D, chunk_size, initial_states=None, seq_idx=None, dt_limit=(0.0, float("inf")), return_final_states=False, activation="silu", rmsnorm_weight=None, rmsnorm_eps=1e-6, outproj_weight=None, outproj_bias=None, headdim=None, ngroups=1, norm_before_gate=True):
  852. """
  853. Argument:
  854. zxbcdt: (batch, seqlen, 2 * dim + 2 * ngroups * dstate + nheads) where dim == nheads * headdim
  855. conv1d_weight: (dim + 2 * ngroups * dstate, width)
  856. conv1d_bias: (dim + 2 * ngroups * dstate,)
  857. dt_bias: (nheads,)
  858. A: (nheads)
  859. D: (nheads, headdim) or (nheads,)
  860. initial_states: (batch, nheads, headdim, dstate)
  861. seq_idx: (batch, seqlen), int32
  862. rmsnorm_weight: (dim,)
  863. outproj_weight: (out_dim, dim)
  864. outproj_bias: (out_dim,)
  865. headdim: if D is 1D, headdim must be passed in
  866. norm_before_gate: if True, we do RMSNorm(x) * F.silu(z). If False, we do RMSNorm(x * F.silu(z))
  867. Return:
  868. out: (batch, seqlen, dim)
  869. """
  870. return MambaSplitConv1dScanCombinedFn.apply(zxbcdt, conv1d_weight, conv1d_bias, dt_bias, A, D, chunk_size, initial_states, seq_idx, dt_limit, return_final_states, activation, rmsnorm_weight, rmsnorm_eps, outproj_weight, outproj_bias, headdim, ngroups, norm_before_gate)
  871. def mamba_split_conv1d_scan_ref(zxbcdt, conv1d_weight, conv1d_bias, dt_bias, A, D, chunk_size, dt_limit=(0.0, float("inf")), activation="silu", rmsnorm_weight=None, rmsnorm_eps=1e-6, outproj_weight=None, outproj_bias=None, headdim=None, ngroups=1, norm_before_gate=True):
  872. """
  873. Argument:
  874. zxbcdt: (batch, seqlen, 2 * dim + 2 * ngroups * dstate + nheads) where dim == nheads * headdim
  875. conv1d_weight: (dim + 2 * ngroups * dstate, width)
  876. conv1d_bias: (dim + 2 * ngroups * dstate,)
  877. dt_bias: (nheads,)
  878. A: (nheads)
  879. D: (nheads, headdim) or (nheads,)
  880. rmsnorm_weight: (dim,)
  881. outproj_weight: (out_dim, dim)
  882. outproj_bias: (out_dim,)
  883. headdim: if D is 1D, headdim must be passed in
  884. norm_before_gate: if True, we do RMSNorm(x) * F.silu(z). If False, we do RMSNorm(x * F.silu(z))
  885. Return:
  886. out: (batch, seqlen, dim)
  887. """
  888. if D.dim() == 1:
  889. assert headdim is not None
  890. nheads, = D.shape
  891. else:
  892. nheads, headdim = D.shape
  893. assert nheads % ngroups == 0
  894. batch, seqlen, _ = zxbcdt.shape
  895. dim = nheads * headdim
  896. dstate = (zxbcdt.shape[-1] - 2 * dim - nheads) // ngroups // 2
  897. assert zxbcdt.shape == (batch, seqlen, 2 * dim + 2 * ngroups * dstate + nheads)
  898. assert dt_bias.shape == (nheads,)
  899. assert A.shape == (nheads,)
  900. if rmsnorm_weight is not None:
  901. assert rmsnorm_weight.shape == (dim,)
  902. z, xBC, dt = torch.split(zxbcdt, [dim, dim + 2 * ngroups * dstate, nheads], dim=-1)
  903. xBC = rearrange(causal_conv1d_fn(rearrange(xBC, "b s d -> b d s"), conv1d_weight, conv1d_bias, activation=activation),
  904. "b d s -> b s d")
  905. x, B, C = torch.split(xBC, [dim, ngroups * dstate, ngroups * dstate], dim=-1)
  906. x = rearrange(x, "b l (h p) -> b l h p", h=nheads)
  907. B = rearrange(B, "b l (g n) -> b l g n", g=ngroups)
  908. C = rearrange(C, "b l (g n) -> b l g n", g=ngroups)
  909. z = rearrange(z, "b l (h p) -> b l h p", h=nheads)
  910. out = ssd_selective_scan(x, dt.to(x.dtype), A, B, C, D=D.float(),
  911. z=z if rmsnorm_weight is None else None, dt_bias=dt_bias, dt_softplus=True, dt_limit=dt_limit)
  912. out = rearrange(out, "b s h p -> b s (h p)")
  913. if rmsnorm_weight is not None:
  914. out = rmsnorm_fn(out, rmsnorm_weight, None, z=rearrange(z, "b l h p -> b l (h p)"), eps=rmsnorm_eps,
  915. norm_before_gate=norm_before_gate)
  916. if outproj_weight is not None:
  917. out = F.linear(out, outproj_weight, outproj_bias)
  918. return out