(ctx, vocab_parallel_logits, target)
| 26 | |
| 27 | @staticmethod |
| 28 | def forward(ctx, vocab_parallel_logits, target): |
| 29 | |
| 30 | # Copy so the input remains unchanged. |
| 31 | logits = vocab_parallel_logits.clone() |
| 32 | # Maximum value along vocab dimension across all GPUs. |
| 33 | logits_max = torch.max(logits, dim=-1)[0] |
| 34 | torch.distributed.all_reduce(logits_max, |
| 35 | op=torch.distributed.ReduceOp.MAX, |
| 36 | group=get_model_parallel_group()) |
| 37 | # Subtract the maximum value. |
| 38 | logits.sub_(logits_max.unsqueeze(dim=-1)) |
| 39 | # Sum of exponential of logits along vocab dimension across all GPUs. |
| 40 | exp_logits = logits.exp() |
| 41 | sum_exp_logits = exp_logits.sum(dim=-1) |
| 42 | torch.distributed.all_reduce(sum_exp_logits, |
| 43 | op=torch.distributed.ReduceOp.SUM, |
| 44 | group=get_model_parallel_group()) |
| 45 | |
| 46 | # Get the partition's vocab indecies |
| 47 | get_vocab_range = VocabUtility.vocab_range_from_per_partition_vocab_size |
| 48 | partition_vocab_size = vocab_parallel_logits.size()[-1] |
| 49 | rank = get_model_parallel_rank() |
| 50 | world_size = get_model_parallel_world_size() |
| 51 | vocab_start_index, vocab_end_index = get_vocab_range( |
| 52 | partition_vocab_size, rank, world_size) |
| 53 | |
| 54 | # Create a mask of valid vocab ids (1 means it needs to be masked). |
| 55 | target_mask = (target < vocab_start_index) | (target >= vocab_end_index) |
| 56 | masked_target = target.clone() - vocab_start_index |
| 57 | masked_target[target_mask] = 0 |
| 58 | |
| 59 | # Get predicted-logits = logits[target]. |
| 60 | # For Simplicity, we convert logits to a 2-D tensor with size |
| 61 | # [*, partition-vocab-size] and target to a 1-D tensor of size [*]. |
| 62 | logits_2d = logits.view(-1, partition_vocab_size) |
| 63 | masked_target_1d = masked_target.view(-1) |
| 64 | arange_1d = torch.arange(start=0, end=logits_2d.size()[0], |
| 65 | device=logits_2d.device) |
| 66 | predicted_logits_1d = logits_2d[arange_1d, masked_target_1d] |
| 67 | predicted_logits = predicted_logits_1d.view_as(target) |
| 68 | predicted_logits[target_mask] = 0.0 |
| 69 | # All reduce is needed to get the chunks from other GPUs. |
| 70 | torch.distributed.all_reduce(predicted_logits, |
| 71 | op=torch.distributed.ReduceOp.SUM, |
| 72 | group=get_model_parallel_group()) |
| 73 | |
| 74 | # Loss = log(sum(exp(logits))) - predicted-logit. |
| 75 | loss = torch.log(sum_exp_logits) - predicted_logits |
| 76 | |
| 77 | # Store softmax, target-mask and masked-target for backward pass. |
| 78 | exp_logits.div_(sum_exp_logits.unsqueeze(dim=-1)) |
| 79 | ctx.save_for_backward(exp_logits, target_mask, masked_target_1d) |
| 80 | |
| 81 | return loss |
| 82 | |
| 83 | @staticmethod |
| 84 | def backward(ctx, grad_output): |
nothing calls this directly
no test coverage detected