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"""Source ownership and invocation metadata shared by linear-attention families."""
16from __future__ import annotations
17
18from copy import deepcopy
19from dataclasses import replace
20from typing import Any
21
22import torch
23from torch import nn
24
25from hyper_parallel.components.modules.attention.linear_attention_utils.sequence_layout import (
26 resolve_packed_sequence,
27)
28from hyper_parallel.core.dtensor.dtensor import DTensor
29
30
31def adopt_source_parameters(target: nn.Module, source: nn.Module, names: tuple[str, ...]) -> None:
32 """Retain source registration order, aliases, frozen weights and checkpoint keys.
33
34 Args:
35 target: Concrete family member, never a wrapper owning the source module.
36 source: Supported source layer or local family being promoted to CP.
37 names: Algorithm-owned top-level parameter and submodule names.
38 """
39 unknown = {name.split('.')[0] for name, _ in source.named_parameters()} - set(names)
40 if unknown:
41 raise ValueError(f"Unsupported linear-attention parameter owners: {sorted(unknown)}")
42 # Raw registries preserve aliases, None slots and buffer persistence that
43 # named_parameters()/named_buffers() cannot expose together.
44 for name, parameter in source._parameters.items(): # pylint: disable=protected-access
45 if name in names:
46 target.register_parameter(name, parameter)
47 for name, child in source._modules.items(): # pylint: disable=protected-access
48 # Parameterless source helpers also belong to the registered-module contract.
49 # Unknown parameter owners were rejected above, so preserving them is safe.
50 target.add_module(name, child)
51 for name, buffer in source._buffers.items(): # pylint: disable=protected-access
52 persistent = name not in source._non_persistent_buffers_set # pylint: disable=protected-access
53 target.register_buffer(name, buffer, persistent=persistent)
54 # Do not call train() recursively: source children may intentionally differ.
55 target.training = source.training
56
57
58def prepare_linear_attention_input(hidden_states: torch.Tensor, options: dict[str, Any],
59 cp_rank: int = 0, cp_size: int = 1) -> tuple:
60 """Resolve per-call metadata without storing the active batch on a module.
61
62 Args:
63 hidden_states: Local [B,T,C] or flattened [T,C] activations.
64 options: Explicit document offsets or an existing PackedSequenceInfo.
65 cp_rank: Logical sequence rank, independent of global rank numbering.
66 cp_size: Number of equal contiguous token shards.
67 """
68 if isinstance(hidden_states, DTensor):
69 hidden_states = hidden_states.to_local()
70 is_flat_input = hidden_states.ndim == 2
71 if is_flat_input:
72 hidden_states = hidden_states.unsqueeze(0)
73 if hidden_states.ndim != 3:
74 raise ValueError("Linear attention expects [B,T,C] or [T,C] inputs")
75 info = resolve_packed_sequence(options, hidden_states.shape[1], cp_rank=cp_rank, cp_size=cp_size)
76 if info is not None and hidden_states.shape[0] != 1:
77 raise ValueError("Packed linear attention requires batch dimension one")
78 return hidden_states, info, is_flat_input
79
80
81def copy_unbound_linear_attention(module: nn.Module, memo: dict) -> nn.Module:
82 """Copy weights before binding, retaining immutable family request metadata.
83
84 Args:
85 module: Local or not-yet-bound CP family member.
86 memo: Python deepcopy alias map.
87
88 Returns:
89 An independent parameter copy with the same logical family request.
90 """
91 if getattr(module, "cp_context", None) is not None or getattr(module, "_hp_parallel_binding", None) is not None:
92 raise RuntimeError("Copy linear-attention weights before binding communication resources")
93 result = type(module).__new__(type(module))
94 memo[id(module)] = result
95 state = dict(module.__dict__)
96 info = state.pop("_hp_family_build_info", None)
97 result.__dict__.update(deepcopy(state, memo))
98 if info is not None:
99 if info.layout is not None:
100 raise RuntimeError("Copy linear-attention weights before applying a distributed layout")
101 # Requests/selection contain only immutable execution options. Configuration
102 # snapshots are independent so changing a copied config cannot affect promotion.
103 # This copy retains the same private record owned by module_family.
104 result._hp_family_build_info = replace( # pylint: disable=protected-access
105 info, config_snapshot=deepcopy(info.config_snapshot, memo))
106 return result
107
108
109def validate_backend_options(options: Any) -> str:
110 """Validate the local algorithm independently of the CP topology.
111
112 Args:
113 options: Explicit backend options or invocation document metadata.
114 """
115 backend = options.get("backend", "eager")
116 if backend not in ("eager", "triton", "ascendc"):
117 raise ValueError("backend must be eager, triton or ascendc")
118 conv = options.get("conv_backend")
119 if conv is not None and conv not in ("eager", "triton", "ascendc"):
120 raise ValueError("conv_backend must be eager, triton or ascendc")
121 chunk = options.get("chunk_size", 64)
122 if (not isinstance(chunk, int) or isinstance(chunk, bool)) or chunk < 1 or (backend != "eager" and chunk != 64):
123 raise ValueError("chunk_size must be positive; fused backends require 64")
124 if options.get("input_layout", "BSH") not in ("BSH", "TH"):
125 raise ValueError("input_layout must be BSH or TH; TH declares flat packed token axis 0")
126 return backend