|
| 1 | +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import torch |
| 16 | +import torch.distributed as dist |
| 17 | +import torch.nn as nn |
| 18 | +import torch.nn.functional as F |
| 19 | +from torch.distributed.tensor import DTensor, Shard |
| 20 | + |
| 21 | + |
| 22 | +def _infer_tp_group_from_dtensor(tensor: "torch.Tensor"): |
| 23 | + """Return device_mesh process group if tensor is a DTensor sharded on vocab (logits last dim, lm_head dim 0).""" |
| 24 | + if not isinstance(tensor, DTensor): |
| 25 | + return None |
| 26 | + # Vocab sharding: Shard on last dim (logits) or Shard(0) (weight matrix) |
| 27 | + has_shard = any(isinstance(p, Shard) for p in tensor.placements) |
| 28 | + if not has_shard: |
| 29 | + return None |
| 30 | + return tensor.device_mesh.get_group() |
| 31 | + |
| 32 | + |
| 33 | +def _kl_forward_tp( |
| 34 | + t_logits: torch.Tensor, |
| 35 | + s_logits: torch.Tensor, |
| 36 | + tp_group, |
| 37 | +) -> torch.Tensor: |
| 38 | + """ |
| 39 | + Compute KL (negative cross entropy sum(P*log Q)) with tensor parallelism. |
| 40 | + Returns per-token negative cross entropy (sum over vocab). |
| 41 | + """ |
| 42 | + teacher_max = t_logits.max(dim=-1, keepdim=True).values |
| 43 | + dist.all_reduce(teacher_max, op=dist.ReduceOp.MAX, group=tp_group) |
| 44 | + output_teacher = t_logits - teacher_max |
| 45 | + |
| 46 | + denom_teacher = torch.exp(output_teacher).sum(dim=-1, keepdim=True) |
| 47 | + dist.all_reduce(denom_teacher, op=dist.ReduceOp.SUM, group=tp_group) |
| 48 | + teacher_prob = torch.exp(output_teacher - torch.log(denom_teacher.clamp(min=1e-12))) |
| 49 | + |
| 50 | + student_max = s_logits.max(dim=-1, keepdim=True).values |
| 51 | + dist.all_reduce(student_max, op=dist.ReduceOp.MAX, group=tp_group) |
| 52 | + output_student = s_logits - student_max.detach() |
| 53 | + |
| 54 | + denom_student = torch.exp(output_student).sum(dim=-1, keepdim=True) |
| 55 | + dist.all_reduce(denom_student, op=dist.ReduceOp.SUM, group=tp_group) |
| 56 | + student_log_prob = output_student - torch.log(denom_student.clamp(min=1e-12)) |
| 57 | + |
| 58 | + term = teacher_prob * student_log_prob |
| 59 | + inf_mask = torch.isinf(s_logits) |
| 60 | + term = torch.masked_fill(term, inf_mask, 0.0) |
| 61 | + ce_local = term.sum(dim=-1) |
| 62 | + dist.all_reduce(ce_local, op=dist.ReduceOp.SUM, group=tp_group) |
| 63 | + return ce_local.view(-1) |
| 64 | + |
| 65 | + |
| 66 | +class KDLoss(nn.Module): |
| 67 | + """TP-aware KD on precomputed logits.""" |
| 68 | + |
| 69 | + def __init__( |
| 70 | + self, |
| 71 | + ignore_index: int = -100, |
| 72 | + temperature: float = 1.0, |
| 73 | + fp32_upcast: bool = True, |
| 74 | + tp_group=None, |
| 75 | + **kwargs, |
| 76 | + ): |
| 77 | + super().__init__() |
| 78 | + self.ignore_index = ignore_index |
| 79 | + self.temperature = temperature |
| 80 | + self.fp32_upcast = fp32_upcast |
| 81 | + self.tp_group = tp_group |
| 82 | + |
| 83 | + def forward( |
| 84 | + self, |
| 85 | + student_logits: torch.Tensor, |
| 86 | + teacher_logits: torch.Tensor, |
| 87 | + labels: torch.Tensor, |
| 88 | + num_batch_labels: int | None = None, |
| 89 | + ) -> torch.Tensor: |
| 90 | + valid_mask = (labels != self.ignore_index).view(-1) |
| 91 | + if valid_mask.sum() == 0: |
| 92 | + return student_logits.new_tensor(0.0) |
| 93 | + |
| 94 | + if student_logits.ndim > 2: |
| 95 | + student_logits = student_logits.view(-1, student_logits.shape[-1]) |
| 96 | + if teacher_logits.ndim > 2: |
| 97 | + teacher_logits = teacher_logits.view(-1, teacher_logits.shape[-1]) |
| 98 | + if labels.ndim > 1: |
| 99 | + labels = labels.view(-1) |
| 100 | + |
| 101 | + tp_group = self.tp_group |
| 102 | + if isinstance(student_logits, DTensor) and tp_group is None: |
| 103 | + tp_group = _infer_tp_group_from_dtensor(student_logits) |
| 104 | + |
| 105 | + if tp_group is not None: |
| 106 | + if isinstance(student_logits, DTensor): |
| 107 | + student_logits = student_logits.to_local() |
| 108 | + if isinstance(teacher_logits, DTensor): |
| 109 | + teacher_logits = teacher_logits.to_local() |
| 110 | + else: |
| 111 | + if isinstance(student_logits, DTensor): |
| 112 | + student_logits = student_logits.full_tensor() |
| 113 | + if isinstance(teacher_logits, DTensor): |
| 114 | + teacher_logits = teacher_logits.full_tensor() |
| 115 | + |
| 116 | + t_logits = teacher_logits[valid_mask] |
| 117 | + s_logits = student_logits[valid_mask] |
| 118 | + |
| 119 | + if self.fp32_upcast: |
| 120 | + t_logits = t_logits.float() |
| 121 | + s_logits = s_logits.float() |
| 122 | + if self.temperature != 1.0: |
| 123 | + t_logits = t_logits.mul(1.0 / self.temperature) |
| 124 | + s_logits = s_logits.mul(1.0 / self.temperature) |
| 125 | + |
| 126 | + if tp_group is not None: |
| 127 | + kl_per_token = _kl_forward_tp(t_logits, s_logits, tp_group) |
| 128 | + else: |
| 129 | + teacher_prob = F.softmax(t_logits, dim=-1, dtype=torch.float32) |
| 130 | + student_logprob = F.log_softmax(s_logits, dim=-1, dtype=torch.float32) |
| 131 | + inf_mask = torch.isinf(s_logits) |
| 132 | + kl_per_token = ( |
| 133 | + torch.masked_fill(teacher_prob * student_logprob, inf_mask, 0.0).sum(-1).view(-1) |
| 134 | + ) |
| 135 | + |
| 136 | + if self.temperature != 1.0: |
| 137 | + kl_per_token = kl_per_token * (self.temperature**2) |
| 138 | + |
| 139 | + if num_batch_labels is not None: |
| 140 | + return -torch.sum(kl_per_token) / num_batch_labels |
| 141 | + return -torch.mean(kl_per_token) |
0 commit comments