Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / losses / model_output.py: 75%
16 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
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"""Loss module that reads the loss produced by a model."""
17__all__ = ["ModelOutputLoss"]
19from typing import Any, Dict, Optional, Union
21# AutoModels loss components implement the Transformers/PyTorch Trainer API.
22import torch
24from hyper_parallel.data.constants import IGNORE_INDEX
27class ModelOutputLoss(torch.nn.Module):
28 """Return the loss field from a Transformers-style model output."""
30 def forward( # pylint: disable=unused-argument
31 self,
32 *,
33 model_output: Any,
34 labels: Optional[torch.Tensor],
35 valid_token_count: Optional[torch.Tensor] = None,
36 ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
37 """Read the model-computed loss.
39 Args:
40 model_output: Model output exposing a ``loss`` attribute.
41 labels: Unshifted labels used by legacy callers that do not supply
42 an aligned token count.
43 valid_token_count: Trainer count after target alignment and masking.
44 When omitted, preserve the legacy unshifted-label convention.
46 Returns:
47 The loss tensor or named loss mapping from ``model_output.loss``.
48 """
49 local_loss = model_output.loss
50 if not isinstance(local_loss, torch.Tensor):
51 return local_loss
53 # Packed inputs may already be shifted: dropping their first target
54 # again can erase the only supervised token on a CP shard. Trainer owns
55 # target alignment, so use its count whenever it is available.
56 if valid_token_count is not None:
57 has_valid_labels = valid_token_count > 0
58 elif labels is not None:
59 has_valid_labels = labels[..., 1:].ne(IGNORE_INDEX).any()
60 else:
61 return local_loss
62 local_loss = torch.where(has_valid_labels, local_loss, torch.zeros_like(local_loss))
64 return local_loss