Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / ops / impl / mome.py: 61%
33 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"""Masked causal depthwise convolution and residual for MOME."""
17from __future__ import annotations
19from typing import Protocol
21import torch
22from torch.nn import functional as F
24from .._dependency import require_package, require_symbol
25from ..registry import OpRegistry
26from ..spec import OpSpec
29class MomeFn(Protocol):
30 """Add causal depthwise-convolution outputs at masked positions."""
32 def __call__(
33 self, x: torch.Tensor, mask: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor | None = None,
34 ) -> torch.Tensor:
35 """Apply [C, 1, K] weights to [B, T, C] states and gate the residual update with a [B, T] mask."""
38MOME = OpSpec[MomeFn](config_key="mome")
41def native_mome(
42 x: torch.Tensor, mask: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor | None = None,
43) -> torch.Tensor:
44 """Use a depthwise Torch convolution and mask its outputs."""
45 padding = weight.shape[-1] - 1
46 padded = F.pad(x.transpose(1, 2), (padding, 0))
47 mixed = torch.conv1d(padded, weight, bias, groups=x.shape[-1]).transpose(1, 2)
48 return x + mixed * mask.unsqueeze(-1).to(mixed.dtype)
51def _load_omni() -> MomeFn:
52 """Load the optional Omni masked convolution and residual adapter."""
53 require_package("omni_training_custom_ops")
54 require_symbol(torch.ops.custom, "npu_aggregate_hidden")
55 require_symbol(torch.ops.custom, "npu_aggregate_hidden_grad")
56 # The autograd bridge imports the optional Omni extension.
57 from hyper_parallel.components.functional.aggregate_hidden import ( # pylint: disable=import-outside-toplevel
58 aggregate_hidden,
59 )
61 def run(
62 x: torch.Tensor, mask: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor | None = None,
63 ) -> torch.Tensor:
64 """Apply the fused causal update and the reference output mask."""
65 padding = weight.shape[-1] - 1
66 padded = F.pad(x, (0, 0, padding, 0))
67 # The reference convolves all input positions and masks the final update.
68 kernel_mask = F.pad(torch.ones_like(mask), (padding, 0), value=False)
69 mixed = aggregate_hidden(
70 padded.transpose(0, 1).contiguous(), weight.squeeze(1).transpose(0, 1), kernel_mask,
71 )[padding:].transpose(0, 1).contiguous()
72 if bias is not None:
73 mixed = mixed + bias.to(mixed.dtype)
74 return x + mixed * mask.unsqueeze(-1).to(mixed.dtype)
76 return run
79def register_mome(registry: OpRegistry) -> None:
80 """Register the Torch reference and the Ascend Omni implementation."""
81 registry.register_family("mome", specs=(MOME,))
82 registry.register_impl(MOME, name="native", devices=("cpu", "cuda", "npu"), load=lambda: native_mome)
83 registry.register_impl(MOME, name="omni", devices=("npu",), load=_load_omni)