MCPcopy Create free account
hub / github.com/MzeroMiko/mamba-mini / backward

Method backward

test_selective_scan_easy.py:184–377  ·  view source on GitHub ↗
(ctx, doys: torch.Tensor, *args)

Source from the content-addressed store, hash-verified

182 @staticmethod
183 @torch.cuda.amp.custom_bwd
184 def backward(ctx, doys: torch.Tensor, *args):
185 DEBUG = getattr(ctx, "DEBUG", False)
186 us, dts, As, Bs, Cs, Ds, delta_bias, ohs = ctx.saved_tensors
187
188 B, G, D, N, L = ctx.shape
189 chunksize = ctx.chunksize
190 delta_softplus = ctx.delta_softplus
191 doys = doys.view(B, G, D, L).permute(3, 0, 1, 2)
192
193 def rev_comsum(x):
194 cum_sum = torch.cumsum(x, dim=0)
195 return (x - cum_sum + cum_sum[-1:None])
196
197 if DEBUG:
198 dtype = torch.float32
199 us = us.requires_grad_()
200 dts = dts.requires_grad_()
201 As = As.requires_grad_()
202 Bs = Bs.requires_grad_()
203 Cs = Cs.requires_grad_()
204 Ds = Ds.requires_grad_() if Ds is not None else None
205 delta_bias = delta_bias.requires_grad_() if delta_bias is not None else None
206 ohs = ohs.requires_grad_()
207
208 # copy forward again
209 if DEBUG:
210 has_D = Ds is not None
211
212 tmp_fwd_dtBus = []
213 tmp_fwd_rAts = []
214 tmp_fwd_Ats = []
215 tmp_fwd_dtBus_div_rAts_cumsum = []
216 tmp_fwd_dtBus_div_rAts = []
217
218 chunks = list(range(0, L, chunksize))
219 oys = []
220 ohs = []
221 hprefix = us.new_zeros((B, G, D, N), dtype=torch.float)
222 for i in chunks:
223 ts = dts[i:i+chunksize].cumsum(dim=0)
224 Ats = torch.einsum("gdn,lbgd->lbgdn", As, ts).exp()
225 # scale = Ats[-1:].detach()
226 scale = 1
227 rAts = Ats / scale
228 duts = dts[i:i + chunksize] * us[i:i + chunksize]
229 dtBus = torch.einsum("lbgd,lbgn->lbgdn", duts, Bs[i:i + chunksize])
230 tmp_dtBus_div_rAts = (dtBus / rAts)
231 tmp_dtBus_div_rAts_cumsum = tmp_dtBus_div_rAts.cumsum(dim=0)
232 hs = rAts * tmp_dtBus_div_rAts_cumsum + Ats * hprefix.unsqueeze(0)
233 ys = torch.einsum("lbgn,lbgdn->lbgd", Cs[i:i + chunksize], hs)
234 oys.append(ys)
235 ohs.append(hs)
236 hprefix = hs[-1]
237
238 tmp_fwd_dtBus_div_rAts_cumsum.append(tmp_dtBus_div_rAts_cumsum)
239 tmp_fwd_dtBus_div_rAts.append(tmp_dtBus_div_rAts)
240 tmp_fwd_dtBus.append(dtBus)
241 tmp_fwd_rAts.append(rAts)

Callers 1

test_selective_scanFunction · 0.45

Calls

no outgoing calls

Tested by

no test coverage detected