MCPcopy Create free account
hub / github.com/zai-org/CodeGeeX / forward

Method forward

codegeex/megatron/mpu/cross_entropy.py:27–89  ·  view source on GitHub ↗
(ctx, vocab_parallel_logits, target)

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls 5

sizeMethod · 0.80
logMethod · 0.80

Tested by

no test coverage detected