Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / functional / mhc_post.py: 90%
48 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"""Manifold hyper-connection post-processing functions."""
17import importlib
18from typing import Any, Tuple
19import warnings
21import torch
23from hyper_parallel.tools.logging import get_logger
25logger = get_logger()
28class _CannMhcPost(torch.autograd.Function):
29 """Autograd bridge routing CANN mhc_post through the PyTorch dispatcher."""
31 @staticmethod
32 def forward(
33 ctx: Any,
34 x: torch.Tensor,
35 h_res: torch.Tensor,
36 h_out: torch.Tensor,
37 h_post: torch.Tensor,
38 ) -> torch.Tensor:
39 """Invoke the registered CANN mhc_post dispatcher op."""
40 # Keep the optional CANN extension out of CPU/non-CANN imports.
41 importlib.import_module("cann_ops_transformer.ops.mhc_post")
43 ctx.save_for_backward(x, h_res, h_out, h_post)
44 return torch.ops.cann_ops_transformer.mhc_post(x, h_res, h_out, h_post)
46 @staticmethod
47 def backward(
48 ctx: Any,
49 grad_output: torch.Tensor,
50 ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
51 """Invoke the registered CANN mhc_post_backward dispatcher op."""
52 # Keep the optional CANN extension out of CPU/non-CANN imports.
53 importlib.import_module("cann_ops_transformer.ops.mhc_post_backward")
55 x, h_res, h_out, h_post = ctx.saved_tensors
56 grad_x, grad_h_res, grad_h_out, grad_h_post = torch.ops.cann_ops_transformer.mhc_post_backward(
57 grad_output, x, h_res, h_out, h_post
58 )
59 return grad_x, grad_h_res, grad_h_out, grad_h_post
62class _MhcPost(torch.autograd.Function):
63 """Autograd bridge for the legacy omni NPU MHC post operator."""
65 @staticmethod
66 def forward(
67 ctx: Any,
68 x: torch.Tensor,
69 h_res: torch.Tensor,
70 h_out: torch.Tensor,
71 h_post: torch.Tensor,
72 ) -> torch.Tensor:
73 """Run the legacy omni NPU MHC post forward operator."""
74 # The package is optional and is needed only for the legacy omni backend.
75 # pylint: disable=import-outside-toplevel
76 try:
77 import omni_training_custom_ops # noqa: F401 # pylint: disable=unused-import
78 except ImportError as error:
79 raise ImportError("MHC backend='omni' requires omni_training_custom_ops") from error
80 # pylint: enable=import-outside-toplevel
81 ctx.save_for_backward(x, h_res, h_out, h_post)
82 return torch.ops.custom.npu_ai_infra_manifold_constrained_hyper_connection_post(
83 x,
84 h_res,
85 h_out,
86 h_post,
87 )
89 @staticmethod
90 def backward(
91 ctx: Any,
92 grad_output: torch.Tensor,
93 ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
94 """Run the legacy omni NPU MHC post backward operator."""
95 x, h_res, h_out, h_post = ctx.saved_tensors
96 grad_x, grad_h_res, grad_h_out, grad_h_post = torch.ops.custom.npu_ai_infra_mhc_post_grad(
97 grad_output.contiguous(),
98 x,
99 h_res,
100 h_out,
101 h_post,
102 )
103 return grad_x, grad_h_res, grad_h_out, grad_h_post
106def mhc_post(
107 x: torch.Tensor,
108 residual: torch.Tensor,
109 h_post: torch.Tensor,
110 h_res: torch.Tensor,
111 num_stream: int,
112 *,
113 backend: str = "cann",
114) -> torch.Tensor:
115 """Combine transformed and residual streams after an MHC-wrapped block.
117 Args:
118 x: Output of the wrapped block.
119 residual: Flattened residual streams.
120 h_post: Per-stream output mixing coefficients.
121 h_res: Residual stream mixing matrix.
122 num_stream: Number of residual streams.
123 backend: ``"cann"`` (default) calls the differentiable CANN
124 ops-transformer ``mhc_post`` operator and requires fp16/bf16
125 ``x``/``residual`` with fp32 ``h_post``/``h_res``. Graph capture
126 requires a CANN wrapper that uses the PyTorch dispatcher. CPU and
127 FP32 NPU inputs use the tensor formula. The legacy ``"omni"``
128 backend is deprecated.
130 Returns:
131 Flattened mixed residual streams.
132 """
133 if backend not in ("cann", "omni"):
134 raise ValueError(f"backend must be 'cann' or 'omni', got {backend!r}")
135 x_shape = x.size()
136 residual = residual.reshape(x_shape[0], x_shape[1], num_stream, -1)
137 is_npu = x.device.type == "npu"
138 if is_npu and x.dtype == torch.float32:
139 warnings.warn(
140 "Fused mHC post does not support FP32 NPU inputs; using the PyTorch tensor formula.",
141 RuntimeWarning,
142 stacklevel=1,
143 )
144 elif is_npu:
145 # Load only the selected optional backend so either can be used independently.
146 # pylint: disable=import-outside-toplevel
147 if backend == "cann":
148 # CANN argument order: residual streams, residual matrix, block
149 # output, post coefficients.
150 return _CannMhcPost.apply(residual, h_res, x, h_post).flatten(2)
151 logger.warning(
152 "mhc_post backend='omni' is deprecated and will be removed in a future release; "
153 "use backend='cann'."
154 )
155 return _MhcPost.apply(residual, h_res, x, h_post).flatten(2)
156 # pylint: enable=import-outside-toplevel
157 output = h_post.unsqueeze(-1) * x.unsqueeze(-2)
158 output = output + torch.sum(
159 h_res.unsqueeze(-1) * residual.unsqueeze(-2), dim=2
160 )
161 return output.flatten(2).to(x.dtype)