Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / mhc / mhc_post.py: 96%
23 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"""Parameter-free mHC post computation."""
16from __future__ import annotations
17from collections.abc import Mapping
18from typing import Any
19import torch
20from torch import nn
21from hyper_parallel.components.functional.mhc_post import mhc_post
22from ._utils import _num_stream, _validate_settings
25class MhcPostModule(nn.Module):
26 """Combine transformed and residual streams after an MHC-wrapped block."""
28 def __init__(
29 self,
30 *,
31 module: nn.Module | None = None,
32 module_fqn: str = "",
33 context: Mapping[str, Any] | None = None,
34 config: Any = None,
35 ) -> None:
36 """Build the high-performance MHC post module from an existing module.
38 Args:
39 module: Source MHC post module.
40 module_fqn: Fully qualified source-module name supplied by replacement.
41 context: Replacement context supplied by Trainer.
42 """
43 super().__init__()
44 del module_fqn, context
45 if (module is None) == (config is None):
46 raise ValueError("provide exactly one of config or module")
47 if config is not None:
48 _validate_settings(config.num_stream)
49 self.config = config
50 self.num_stream = config.num_stream
51 return
52 self.config = getattr(module, "config", None)
53 self.num_stream = _num_stream(module)
54 self.train(module.training)
56 def forward(
57 self,
58 x: torch.Tensor,
59 residual: torch.Tensor,
60 h_post: torch.Tensor,
61 h_res: torch.Tensor,
62 ) -> torch.Tensor:
63 """Mix the wrapped block output into the residual streams."""
64 return mhc_post(
65 x,
66 residual,
67 h_post,
68 h_res,
69 self.num_stream,
70 )