Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / common / causal_lm_head.py: 77%
44 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"""Public vocabulary projection and pre-shifted chunked cross-entropy family."""
16from __future__ import annotations
18from typing import Any
20import torch
21from torch import nn
22from torch.nn import functional as F
24from hyper_parallel.components.losses.chunked_cross_entropy import ChunkedCausalLMOutput, chunked_cross_entropy
25from hyper_parallel.components.modules.module_family import ModuleFamily, build_family, register_module_family
26from hyper_parallel.models.replacement import module_replacement
29class CausalLMHeadModule(nn.Linear):
30 """Own the vocabulary weight while supporting logits and memory-bounded CE.
32 Inheriting Linear retains HF initialization and embedding tying semantics.
33 Source adoption allocates no replacement weight and changes no parameter key.
34 """
36 supports_chunked_cross_entropy = True
38 def __init__(
39 self, *, config: Any = None, module: nn.Module | None = None, module_fqn: str = "", context: Any = None
40 ) -> None:
41 """Construct a bias-free head or adopt an existing compatible projection."""
42 del module_fqn, context
43 if (config is None) == (module is None):
44 raise ValueError("provide exactly one of config or module")
45 if module is None:
46 for name in ("hidden_size", "vocab_size"):
47 value = getattr(config, name, None)
48 if isinstance(value, bool) or not isinstance(value, int) or value < 1:
49 raise ValueError(f"{name} must be a positive integer")
50 super().__init__(config.hidden_size, config.vocab_size, bias=False)
51 else:
52 if not isinstance(module, nn.Linear) or module.bias is not None:
53 raise ValueError("CausalLMHead requires a bias-free Linear source")
54 nn.Module.__init__(self)
55 self.in_features, self.out_features = module.in_features, module.out_features
56 self.register_parameter("weight", module.weight)
57 self.register_parameter("bias", None)
58 self.training = module.training
60 def make_transforms(self) -> list:
61 """Projection names and shapes are unchanged."""
62 return []
64 def forward(
65 self,
66 input: torch.Tensor,
67 *,
68 targets: torch.Tensor | None = None,
69 loss_mask: torch.Tensor | None = None,
70 chunk_size: int = 1024,
71 ignore_index: int = -100,
72 ) -> torch.Tensor | ChunkedCausalLMOutput:
73 """Project to logits or compute summed CE from already aligned targets.
75 Targets are pre-shifted by the data owner; this component never shifts a
76 locally sharded sequence. Chunked mode never creates full-sequence logits.
77 """
78 if targets is None:
79 if loss_mask is not None:
80 raise ValueError("loss_mask requires aligned targets")
81 return F.linear(input, self.weight) # pylint: disable=not-callable
82 if loss_mask is not None:
83 if loss_mask.shape != targets.shape:
84 raise ValueError("loss_mask and targets must have identical shapes")
85 targets = targets.masked_fill(~loss_mask.bool(), ignore_index)
86 loss = chunked_cross_entropy(input, targets, self.weight, chunk_size=chunk_size, ignore_index=ignore_index)
87 return ChunkedCausalLMOutput(loss_sum=loss, valid_token_count=(targets != ignore_index).sum())
90@module_replacement
91def CausalLMHead(
92 *,
93 config: Any = None,
94 module: nn.Module | None = None, # pylint: disable=invalid-name
95 module_fqn: str = "",
96 context: Any = None,
97 mesh: Any = None,
98) -> nn.Module:
99 """Construct the tracked vocabulary-projection and chunked-CE component."""
100 return build_family(CausalLMHead, config=config, module=module, module_fqn=module_fqn, context=context, mesh=mesh)
103register_module_family(
104 ModuleFamily(
105 name="causal_lm_head",
106 baseline=CausalLMHead,
107 variants={"local": "hyper_parallel.components.modules.common.causal_lm_head.CausalLMHeadModule"},
108 default_variant="local",
109 )
110)