csms6s.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. import time
  2. import torch
  3. import warnings
  4. WITH_SELECTIVESCAN_OFLEX = True
  5. WITH_SELECTIVESCAN_CORE = False
  6. WITH_SELECTIVESCAN_MAMBA = True
  7. try:
  8. import selective_scan_cuda_oflex
  9. except ImportError:
  10. WITH_SELECTIVESCAN_OFLEX = False
  11. warnings.warn("selective_scan_cuda_oflex is unavailable; SS2D will use a slower backend.", stacklevel=2)
  12. try:
  13. import selective_scan_cuda_core
  14. except ImportError:
  15. WITH_SELECTIVESCAN_CORE = False
  16. try:
  17. import selective_scan_cuda
  18. except ImportError:
  19. WITH_SELECTIVESCAN_MAMBA = False
  20. def selective_scan_torch(
  21. u: torch.Tensor, # (B, K * C, L)
  22. delta: torch.Tensor, # (B, K * C, L)
  23. A: torch.Tensor, # (K * C, N)
  24. B: torch.Tensor, # (B, K, N, L)
  25. C: torch.Tensor, # (B, K, N, L)
  26. D: torch.Tensor = None, # (K * C)
  27. delta_bias: torch.Tensor = None, # (K * C)
  28. delta_softplus=True,
  29. oflex=True,
  30. *args,
  31. **kwargs
  32. ):
  33. dtype_in = u.dtype
  34. Batch, K, N, L = B.shape
  35. KCdim = u.shape[1]
  36. Cdim = int(KCdim / K)
  37. assert u.shape == (Batch, KCdim, L)
  38. assert delta.shape == (Batch, KCdim, L)
  39. assert A.shape == (KCdim, N)
  40. assert C.shape == B.shape
  41. if delta_bias is not None:
  42. delta = delta + delta_bias[..., None]
  43. if delta_softplus:
  44. delta = torch.nn.functional.softplus(delta)
  45. u, delta, A, B, C = u.float(), delta.float(), A.float(), B.float(), C.float()
  46. B = B.view(Batch, K, 1, N, L).repeat(1, 1, Cdim, 1, 1).view(Batch, KCdim, N, L)
  47. C = C.view(Batch, K, 1, N, L).repeat(1, 1, Cdim, 1, 1).view(Batch, KCdim, N, L)
  48. deltaA = torch.exp(torch.einsum('bdl,dn->bdln', delta, A))
  49. deltaB_u = torch.einsum('bdl,bdnl,bdl->bdln', delta, B, u)
  50. if True:
  51. x = A.new_zeros((Batch, KCdim, N))
  52. ys = []
  53. for i in range(L):
  54. x = deltaA[:, :, i, :] * x + deltaB_u[:, :, i, :]
  55. y = torch.einsum('bdn,bdn->bd', x, C[:, :, :, i])
  56. ys.append(y)
  57. y = torch.stack(ys, dim=2) # (B, C, L)
  58. out = y if D is None else y + u * D.unsqueeze(-1)
  59. return out if oflex else out.to(dtype=dtype_in)
  60. class SelectiveScanCuda(torch.autograd.Function):
  61. @staticmethod
  62. @torch.amp.custom_fwd(device_type="cuda")
  63. def forward(ctx, u, delta, A, B, C, D=None, delta_bias=None, delta_softplus=False, oflex=True, backend=None):
  64. ctx.delta_softplus = delta_softplus
  65. backend = "oflex" if WITH_SELECTIVESCAN_OFLEX and (backend is None) else backend
  66. backend = "core" if WITH_SELECTIVESCAN_CORE and (backend is None) else backend
  67. backend = "mamba" if WITH_SELECTIVESCAN_MAMBA and (backend is None) else backend
  68. ctx.backend = backend
  69. if backend == "oflex":
  70. out, x, *rest = selective_scan_cuda_oflex.fwd(u, delta, A, B, C, D, delta_bias, delta_softplus, 1, oflex)
  71. elif backend == "core":
  72. out, x, *rest = selective_scan_cuda_core.fwd(u, delta, A, B, C, D, delta_bias, delta_softplus, 1)
  73. elif backend == "mamba":
  74. out, x, *rest = selective_scan_cuda.fwd(u, delta, A, B, C, D, None, delta_bias, delta_softplus)
  75. ctx.save_for_backward(u, delta, A, B, C, D, delta_bias, x)
  76. return out
  77. @staticmethod
  78. @torch.amp.custom_bwd(device_type="cuda")
  79. def backward(ctx, dout, *args):
  80. u, delta, A, B, C, D, delta_bias, x = ctx.saved_tensors
  81. backend = ctx.backend
  82. if dout.stride(-1) != 1:
  83. dout = dout.contiguous()
  84. if backend == "oflex":
  85. du, ddelta, dA, dB, dC, dD, ddelta_bias, *rest = selective_scan_cuda_oflex.bwd(
  86. u, delta, A, B, C, D, delta_bias, dout, x, ctx.delta_softplus, 1
  87. )
  88. elif backend == "core":
  89. du, ddelta, dA, dB, dC, dD, ddelta_bias, *rest = selective_scan_cuda_core.bwd(
  90. u, delta, A, B, C, D, delta_bias, dout, x, ctx.delta_softplus, 1
  91. )
  92. elif backend == "mamba":
  93. du, ddelta, dA, dB, dC, dD, ddelta_bias, *rest = selective_scan_cuda.bwd(
  94. u, delta, A, B, C, D, None, delta_bias, dout, x, None, None, ctx.delta_softplus,
  95. False
  96. )
  97. return du, ddelta, dA, dB, dC, dD, ddelta_bias, None, None, None
  98. def selective_scan_fn(
  99. u: torch.Tensor, # (B, K * C, L)
  100. delta: torch.Tensor, # (B, K * C, L)
  101. A: torch.Tensor, # (K * C, N)
  102. B: torch.Tensor, # (B, K, N, L)
  103. C: torch.Tensor, # (B, K, N, L)
  104. D: torch.Tensor = None, # (K * C)
  105. delta_bias: torch.Tensor = None, # (K * C)
  106. delta_softplus=True,
  107. oflex=True,
  108. backend=None,
  109. ):
  110. WITH_CUDA = (WITH_SELECTIVESCAN_OFLEX or WITH_SELECTIVESCAN_CORE or WITH_SELECTIVESCAN_MAMBA)
  111. fn = selective_scan_torch if backend == "torch" or (not WITH_CUDA) else SelectiveScanCuda.apply
  112. return fn(u, delta, A, B, C, D, delta_bias, delta_softplus, oflex, backend)
  113. # fvcore flops =======================================
  114. def print_jit_input_names(inputs):
  115. print("input params: ", end=" ", flush=True)
  116. try:
  117. for i in range(10):
  118. print(inputs[i].debugName(), end=" ", flush=True)
  119. except Exception as e:
  120. pass
  121. print("", flush=True)
  122. def flops_selective_scan_fn(B=1, L=256, D=768, N=16, with_D=True, with_Z=False, with_complex=False):
  123. """
  124. u: r(B D L)
  125. delta: r(B D L)
  126. A: r(D N)
  127. B: r(B N L)
  128. C: r(B N L)
  129. D: r(D)
  130. z: r(B D L)
  131. delta_bias: r(D), fp32
  132. ignores:
  133. [.float(), +, .softplus, .shape, new_zeros, repeat, stack, to(dtype), silu]
  134. """
  135. assert not with_complex
  136. # https://github.com/state-spaces/mamba/issues/110
  137. flops = 9 * B * L * D * N
  138. if with_D:
  139. flops += B * D * L
  140. if with_Z:
  141. flops += B * D * L
  142. return flops
  143. # this is only for selective_scan_ref...
  144. def flops_selective_scan_ref(B=1, L=256, D=768, N=16, with_D=True, with_Z=False, with_Group=True, with_complex=False):
  145. """
  146. u: r(B D L)
  147. delta: r(B D L)
  148. A: r(D N)
  149. B: r(B N L)
  150. C: r(B N L)
  151. D: r(D)
  152. z: r(B D L)
  153. delta_bias: r(D), fp32
  154. ignores:
  155. [.float(), +, .softplus, .shape, new_zeros, repeat, stack, to(dtype), silu]
  156. """
  157. import numpy as np
  158. # fvcore.nn.jit_handles
  159. def get_flops_einsum(input_shapes, equation):
  160. np_arrs = [np.zeros(s) for s in input_shapes]
  161. optim = np.einsum_path(equation, *np_arrs, optimize="optimal")[1]
  162. for line in optim.split("\n"):
  163. if "optimized flop" in line.lower():
  164. # divided by 2 because we count MAC (multiply-add counted as one flop)
  165. flop = float(np.floor(float(line.split(":")[-1]) / 2))
  166. return flop
  167. assert not with_complex
  168. flops = 0 # below code flops = 0
  169. flops += get_flops_einsum([[B, D, L], [D, N]], "bdl,dn->bdln")
  170. if with_Group:
  171. flops += get_flops_einsum([[B, D, L], [B, N, L], [B, D, L]], "bdl,bnl,bdl->bdln")
  172. else:
  173. flops += get_flops_einsum([[B, D, L], [B, D, N, L], [B, D, L]], "bdl,bdnl,bdl->bdln")
  174. in_for_flops = B * D * N
  175. if with_Group:
  176. in_for_flops += get_flops_einsum([[B, D, N], [B, D, N]], "bdn,bdn->bd")
  177. else:
  178. in_for_flops += get_flops_einsum([[B, D, N], [B, N]], "bdn,bn->bd")
  179. flops += L * in_for_flops
  180. if with_D:
  181. flops += B * D * L
  182. if with_Z:
  183. flops += B * D * L
  184. return flops
  185. def selective_scan_flop_jit(inputs, outputs, backend="prefixsum", verbose=True):
  186. if verbose:
  187. print_jit_input_names(inputs)
  188. flops_fn = flops_selective_scan_ref if backend == "naive" else flops_selective_scan_fn
  189. B, D, L = inputs[0].type().sizes()
  190. N = inputs[2].type().sizes()[1]
  191. flops = flops_fn(B=B, L=L, D=D, N=N, with_D=True, with_Z=False)
  192. return flops
  193. if __name__ == "__main__":
  194. def params(B, K, C, N, L, device = torch.device("cuda"), itype = torch.float):
  195. As = (-0.5 * torch.rand(K * C, N, device=device, dtype=torch.float32)).requires_grad_()
  196. Bs = torch.randn((B, K, N, L), device=device, dtype=itype).requires_grad_()
  197. Cs = torch.randn((B, K, N, L), device=device, dtype=itype).requires_grad_()
  198. Ds = torch.randn((K * C), device=device, dtype=torch.float32).requires_grad_()
  199. u = torch.randn((B, K * C, L), device=device, dtype=itype).requires_grad_()
  200. delta = (0.5 * torch.rand((B, K * C, L), device=device, dtype=itype)).requires_grad_()
  201. delta_bias = (0.5 * torch.rand((K * C), device=device, dtype=torch.float32)).requires_grad_()
  202. return u, delta, As, Bs, Cs, Ds, delta_bias
  203. def bench(func, xs, Warmup=30, NTimes=20):
  204. import time
  205. torch.cuda.synchronize()
  206. for r in range(Warmup):
  207. for x in xs:
  208. func(x)
  209. torch.cuda.synchronize()
  210. tim0 = time.time()
  211. for r in range(NTimes):
  212. for x in xs:
  213. func(x)
  214. torch.cuda.synchronize()
  215. return (time.time() - tim0) / NTimes
  216. def check():
  217. u, delta, As, Bs, Cs, Ds, delta_bias = params(1, 4, 16, 8, 512, itype=torch.float16)
  218. u1, delta1, As1, Bs1, Cs1, Ds1, delta_bias1 = [x.clone().detach().requires_grad_() for x in [u, delta, As, Bs, Cs, Ds, delta_bias]]
  219. # out_ref = selective_scan_fn(u, delta, As, Bs, Cs, Ds, delta_bias, True, backend="torch")
  220. out = selective_scan_fn(u1, delta1, As1, Bs1, Cs1, Ds1, delta_bias1, True, backend="oflex")
  221. out_ref = selective_scan_fn(u, delta, As, Bs, Cs, Ds, delta_bias, True, backend="mamba")
  222. print((out_ref - out).abs().max())
  223. out.sum().backward()
  224. out_ref.sum().backward()
  225. for x, y in zip([u, As, Bs, Cs, Ds, delta, delta_bias], [u1, As1, Bs1, Cs1, Ds1, delta1, delta_bias1]):
  226. print((x.grad - y.grad).abs().max())
  227. u, delta, As, Bs, Cs, Ds, delta_bias = params(128, 4, 96, 8, 56 * 56)
  228. print(bench(lambda x: selective_scan_fn(x[0], x[1], x[2], x[3], x[4], x[5], x[6], True, backend="oflex"), [(u, delta, As, Bs, Cs, Ds, delta_bias),]))
  229. print(bench(lambda x: selective_scan_fn(x[0], x[1], x[2], x[3], x[4], x[5], x[6], True, backend="mamba"), [(u, delta, As, Bs, Cs, Ds, delta_bias),]))
  230. print(bench(lambda x: selective_scan_fn(x[0], x[1], x[2], x[3], x[4], x[5], x[6], True, backend="torch"), [(u, delta, As, Bs, Cs, Ds, delta_bias),]))
  231. check()