Check the index error: [code]
- User
Check the index error:
codedef backward(ctx, grad_output): """Manually calculate the gradient in a memory-efficient way Ref: https://indii.org/blog/gradients-of-softmax-and-logsumexp/ """ x, weight, labels = ctx.saved_tensors sp = ctx.sp device = x.device dtype = x.dtype bsz, seqlen, hidden = x.size() vocab, hidden = weight.size() micro_seqlen = seqlen // sp print(f"bsz, seqlen, hidden: {bsz, seqlen, hidden}") d_weight = torch.zeros_like(weight, device=weight.device) d_x = [] for i in range(sp): # shard data along sequence dimension, reduce peak memory x_ = x[:, micro_seqlen * i: micro_seqlen * (i + 1)] p = F.softmax( torch.einsum("blh, vh -> blv", x_, weight), dim=-1 ) # memory efficient in-place backprop # loss -> d_logits d_logits = -p.view(-1) # [b * l * v] labels_ = labels[:, micro_seqlen * i: micro_seqlen * (i + 1)].view(-1) # [b * l] index = torch.arange(bsz * micro_seqlen, device=device) * vocab + labels_ print(f"bsz: {bsz}, micro_seqlen: {micro_seqlen}, dtype: {dtype}, device: {device}") source = torch.tensor([1] * bsz * micro_seqlen, dtype=dtype, device=device) print(f"device: {device} pass source, round: {i}") d_logits.index_add_(0, index, source) d_logits = -d_logits.view(bsz, micro_seqlen, vocab) / (bsz * seqlen) # d_logits -> d_x and d_weight d_x.append(torch.einsum("blv, vh -> blh", d_logits, weight)) d_weight += torch.einsum("blv, blh -> vh", d_logits, x_) d_weight = grad_output * d_weight d_x = grad_output * torch.concat(d_x, 1) return d_x, d_weight, None, None - Assistant