Diff Coverage

Diff: origin/master...HEAD, staged and unstaged changes

Source File Diff Coverage (%) Missing Lines
hyper_parallel/components/functional/gated_residual.py 0.0% 17-19,21-22,25,33,35-40,43,45-46,49,58-66,69,78-87,90,100-112,115,117-129,136,146-148,151-157,166-168,170-176,179,209-212,214-215,218-228,232,235
hyper_parallel/components/modules/common/gated_residual.py 0.0% 28,30-32,34-35,37-41,44,46,49,51-53,56,58-60,63,66-71,73,75,77-78,81-82,85,88,91,106-109,111-123,125-136,138-139,141,143,154-157,160-161,164-165,168-170,172-174,176,178-192,194-196,199-202,206-209,211,215-216,219-220,230-234,237,246-254,259-260,271-272,282,293,304
hyper_parallel/components/functional/gated_residual.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# limitations under the License.
# ============================================================================
"""Gated Residual formulas with eager and optional CANN implementations."""

import importlib
from collections.abc import Callable
from math import isfinite

import torch
import torch.nn.functional as F


_BACKEND_ALIASES = {
    "eager": "eager",
    "torch": "eager",
    "ascendc": "ascendc",
    "cann": "ascendc",
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
    "cann": "ascendc",
}


def _validate_input_layout(x: torch.Tensor, channels: int) -> None:
    """Validate the input layout needed by the Python dispatcher."""
    if x.ndim < 1:
        raise ValueError("Gated Residual input must have at least one dimension")
    if isinstance(channels, bool) or not isinstance(channels, int) or channels <= 0:
        raise ValueError("Gated Residual channels must be a positive integer")
    if x.shape[-1] % channels:
        raise ValueError("Gated Residual input width must be divisible by channels")


def _validate_eps(eps: float) -> None:
    """Validate epsilon for the eager and empty-input paths."""
    if isinstance(eps, bool) or not isinstance(eps, (int, float)) or not isfinite(eps) or eps <= 0:
        raise ValueError("Gated Residual eps must be finite and positive")


def _validate_projection_shapes(
    x: torch.Tensor,
    w_down: torch.Tensor,
    w_up: torch.Tensor,
    w_gate: torch.Tensor | None,
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
    gamma: torch.Tensor | None,
    channels: int,
) -> None:
    """Validate projection and optional parameter shapes."""
    hidden_size = x.shape[-1]
    if w_down.ndim != 2 or w_down.shape[1] != hidden_size:
        raise ValueError("Gated Residual w_down must have shape [rank, input_width]")
    if w_up.ndim != 2 or tuple(w_up.shape) != (hidden_size, w_down.shape[0]):
        raise ValueError("Gated Residual w_up must have shape [input_width, rank]")
    if w_gate is not None and (w_gate.ndim != 2 or tuple(w_gate.shape) != (channels, hidden_size)):
        raise ValueError("Gated Residual w_gate must have shape [channels, input_width]")
    if gamma is not None and (gamma.ndim != 1 or gamma.shape[0] != hidden_size):
        raise ValueError("Gated Residual gamma must have shape [input_width]")


def _empty_result(
    x: torch.Tensor,
    w_down: torch.Tensor,
    w_up: torch.Tensor,
    w_gate: torch.Tensor | None,
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
    gamma: torch.Tensor | None,
    channels: int,
) -> tuple[torch.Tensor, torch.Tensor | None]:
    """Return shape-correct empty results while retaining all gradient edges."""
    hidden_size = x.shape[-1] // channels
    zero = x.reshape(-1)[:0].sum()
    for tensor in (w_down, w_up, w_gate, gamma):
        if tensor is not None:
            zero = zero + tensor.reshape(-1)[:0].sum().to(dtype=zero.dtype)
    mixed = x[..., :hidden_size].to(dtype=x.dtype) + zero.to(dtype=x.dtype)
    if w_gate is None:
        return mixed, None
    injection = x[..., :channels].to(dtype=x.dtype) + zero.to(dtype=x.dtype)
    return mixed, injection


def _gated_residual_eager(
    x: torch.Tensor,
    w_down: torch.Tensor,
    w_up: torch.Tensor,
    w_gate: torch.Tensor | None,
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
    channels: int,
    eps: float,
) -> tuple[torch.Tensor, torch.Tensor | None]:
    """Evaluate the Gated Residual formula with Torch operators."""
    hidden_size = x.shape[-1] // channels
    values = x.float().unflatten(-1, (channels, hidden_size))
    normalized = values * torch.rsqrt(values.square().mean(dim=-1, keepdim=True) + eps)
    if gamma is not None:
        normalized = normalized * (1.0 + gamma.float().unflatten(-1, (channels, hidden_size)))
    flattened = normalized.flatten(-2)
    lowrank = F.silu(F.linear(flattened, w_down.float()) / channels)
    gate = torch.sigmoid(F.linear(lowrank, w_up.float()))
    mixed = (gate.unflatten(-1, (channels, hidden_size)) * normalized).mean(dim=-2).to(dtype=x.dtype)
    if w_gate is None:
        return mixed, None
    injection = (2.0 * torch.sigmoid(F.linear(flattened, w_gate.float()) / channels)).to(dtype=x.dtype)
    return mixed, injection


def _load_text_gated_residual() -> Callable:
    """Load the optional differentiable ops-transformer Python entry point."""
    errors = []
    for package_name in ("cann_ops_transformer", "cann_ops_transformer_custom"):
        try:
            module = importlib.import_module(f"{package_name}.ops.mhc.text_gated_residual")
        except (ImportError, OSError) as error:
            errors.append(f"{package_name}.ops.mhc.text_gated_residual: {error}")
            continue
        operator = getattr(module, "text_gated_residual", None)
        if callable(operator):
            return operator
        errors.append(f"{module.__name__}: text_gated_residual is not exported")
    detail = "; ".join(errors)
    raise ImportError(
        "Gated Residual backend='ascendc' requires the ops-transformer differentiable "
        "text_gated_residual Python wrapper and matching native forward/backward kernels. Install the matching "
        f"standalone package. Import details: {detail}"
    )
132
133
134
135
136
137
138
139
140
        f"standalone package. Import details: {detail}"
    )


def _gated_residual_fused(
    x: torch.Tensor,
    w_down: torch.Tensor,
    w_up: torch.Tensor,
    w_gate: torch.Tensor | None,
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
    channels: int,
    eps: float,
) -> tuple[torch.Tensor, torch.Tensor | None]:
    """Invoke the differentiable ops-transformer TextGatedResidual API."""
    operator = _load_text_gated_residual()
    output_shape = tuple(x.shape[:-1])
    hidden_size = x.shape[-1] // channels
    # The native API takes [B, S, D]. Flatten arbitrary leading token axes while
    # preserving differentiable reshape edges back to the model's layout.
    native_x = x.reshape(1, -1, x.shape[-1]).contiguous()
    native_dtype = native_x.dtype
    native_down = w_down.to(dtype=native_dtype).contiguous()
    native_up = w_up.to(dtype=native_dtype).contiguous()
    native_gate = None if w_gate is None else w_gate.to(dtype=native_dtype).contiguous()
    native_gamma = None if gamma is None else gamma.float().contiguous()
    result = operator(
        native_x,
        native_down,
        native_up,
        w_gate=native_gate,
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
        channels=channels,
        gamma=native_gamma,
        eps=eps,
    )
    if w_gate is None:
        mixed = result
        injection = None
    else:
        if not isinstance(result, tuple) or len(result) != 2:
            raise RuntimeError("TextGatedResidual must return (mixed, inject) when w_gate is provided")
        mixed, injection = result
    mixed = mixed.reshape(output_shape + (hidden_size,))
    if injection is not None:
        injection = injection.reshape(output_shape + (channels,))
    return mixed, injection


def gated_residual(
    x: torch.Tensor,
    w_down: torch.Tensor,
    w_up: torch.Tensor,
    w_gate: torch.Tensor | None = None,
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
    Raises:
        ImportError: The selected native backend is unavailable or lacks its training API.
        ValueError: The backend or input layout is invalid.
    """
    try:
        resolved_backend = _BACKEND_ALIASES[backend]
    except (KeyError, TypeError) as error:
        raise ValueError("Gated Residual backend must be eager or ascendc") from error

    _validate_input_layout(x, channels)
    if x.numel() == 0 or any(size == 0 for size in x.shape[:-1]):
        # The native kernel is skipped for empty inputs, so validate the complete
        # eager contract here rather than relying on CANN's operator checks.
        _validate_eps(eps)
        _validate_projection_shapes(x, w_down, w_up, w_gate, gamma, channels)
        return _empty_result(x, w_down, w_up, w_gate, gamma, channels)
    if resolved_backend == "eager":
        _validate_eps(eps)
        _validate_projection_shapes(x, w_down, w_up, w_gate, gamma, channels)
        return _gated_residual_eager(x, w_down, w_up, w_gate, gamma, channels, eps)
    if x.device.type != "npu":
        raise ValueError("Gated Residual backend='ascendc' requires NPU tensors")
    if x.dtype not in (torch.float16, torch.bfloat16):
        raise ValueError("Gated Residual backend='ascendc' supports float16 or bfloat16 inputs")
    # For nonempty AscendC calls, CANN validates projection shapes, optional
    # inputs, dtypes and epsilon. Keep only the checks needed before Python
    # reshaping and backend dispatch above.
    return _gated_residual_fused(x, w_down, w_up, w_gate, gamma, channels, eps)


__all__ = ["gated_residual"]
hyper_parallel/components/modules/common/gated_residual.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
injection weights, matching the reference model's responsibility boundary.
``combine`` exposes that same residual update as an optional convenience API.
"""

from __future__ import annotations

from collections.abc import Mapping
from math import isfinite
from typing import Any

import torch
from torch import nn

from hyper_parallel.components.functional.gated_residual import gated_residual
from hyper_parallel.components.modules.module_family import ModuleFamily, build_family, register_module_family
from hyper_parallel.core.dtensor.placement_types import Replicate, Shard
from hyper_parallel.distributed.recipe_spec import ModuleShardingSpec
from hyper_parallel.models.replacement import module_replacement


def _config_value(config: Any, name: str, default: Any = None) -> Any:
    """Read one optional field from a model configuration."""
    return getattr(config, name, default) if config is not None else default


def _positive_int(value: Any, name: str) -> int:
    """Validate a positive integer configuration field."""
    if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
        raise ValueError(f"GatedResidual {name} must be a positive integer")
    return value


def _positive_float(value: Any, name: str) -> float:
    """Validate a finite positive floating-point configuration field."""
    if isinstance(value, bool) or not isinstance(value, (int, float)) or not isfinite(value) or value <= 0:
        raise ValueError(f"GatedResidual {name} must be finite and positive")
    return float(value)


class _GroupedOffsetRMSNorm(nn.Module):
    """Zero-centered RMSNorm applied independently to each residual stream."""

    def __init__(self, hidden_size: int, group_size: int, eps: float) -> None:
        super().__init__()
        if hidden_size % group_size:
            raise ValueError("GatedResidual hidden_size must be divisible by group_size")
        self.eps = eps
        self.group_size = group_size
        # Initialize gamma to zero and apply it as (1 + gamma).
        self.weight = nn.Parameter(torch.zeros(hidden_size))

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        """Normalize each ``group_size`` slice in FP32 and restore input dtype."""
        input_dtype = hidden_states.dtype
        values = hidden_states.float().unflatten(
            -1, (hidden_states.shape[-1] // self.group_size, self.group_size)
        )
        normalized = values * torch.rsqrt(values.square().mean(dim=-1, keepdim=True) + self.eps)
        scaled = normalized * (
            1.0 + self.weight.float().unflatten(-1, (self.weight.numel() // self.group_size, self.group_size))
        )
        return scaled.flatten(-2).to(input_dtype)


class GatedResidualModule(nn.Module):
    """Configurable Gated Residual module family member."""

    def __init__(
        self,
        *,
        config: Any = None,
        module: nn.Module | None = None,
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
        ``use_combine`` is inferred from a source module's
        ``block_inject_weight``.  For direct construction it defaults to true;
        the final model mixer can pass ``use_combine=False``.
        """
        super().__init__()
        del module_fqn, context
        if (config is None) == (module is None):
            raise ValueError("provide exactly one of config or module")

        source_config = config if config is not None else getattr(module, "config", None)
        self.config = source_config
        configured_backend = _config_value(source_config, "gated_residual_backend")
        if configured_backend is None:
            configured_backend = _config_value(source_config, "gated_res_backend")
        if configured_backend is None:
            configured_backend = _config_value(module, "backend", "eager")
        if configured_backend not in ("eager", "torch", "ascendc", "cann"):
            raise ValueError("GatedResidual backend must be eager or ascendc")
        self.backend = "eager" if configured_backend in ("eager", "torch") else "ascendc"
        if module is not None:
            self._adopt_source(module, use_combine)
            return

        self.hidden_size = _positive_int(_config_value(config, "hidden_size"), "hidden_size")
        self.hc_count = _positive_int(_config_value(config, "hc_count", 4), "hc_count")
        self.hc_lowrank = _positive_int(_config_value(config, "hc_lowrank", 320), "hc_lowrank")
        eps = _positive_float(_config_value(config, "rms_norm_eps", 1e-6), "rms_norm_eps")
        self.use_combine = True if use_combine is None else use_combine
        if not isinstance(self.use_combine, bool):
            raise TypeError("GatedResidual use_combine must be bool")
        self.hc_norm = _GroupedOffsetRMSNorm(self.hyper_hidden_size, self.hidden_size, eps)
        self.input_mix_weight_down = nn.Linear(self.hyper_hidden_size, self.hc_lowrank, bias=False)
        self.input_mix_weight_up = nn.Linear(self.hc_lowrank, self.hyper_hidden_size, bias=False)
        if self.use_combine:
            self.block_inject_weight = nn.Linear(self.hyper_hidden_size, self.hc_count, bias=False)

    @property
    def hyper_hidden_size(self) -> int:
        """Return the flattened residual-stream width."""
        return self.hc_count * self.hidden_size

    def combine(
        self,
        block_output: torch.Tensor,
        hyper_input: torch.Tensor,
        injection_weights: torch.Tensor,
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224

        The method is an optional convenience for model code. Callers may
        instead apply this equation themselves, as the reference decoder does.
        """
        if not self.use_combine:
            raise RuntimeError("GatedResidual combine is unavailable when use_combine=False")
        if block_output.shape[-1] != self.hidden_size:
            raise ValueError(
                f"Expected block output width {self.hidden_size}, got {block_output.shape[-1]}"
            )
        if hyper_input.shape[-1] != self.hyper_hidden_size:
            raise ValueError(
                f"Expected {self.hyper_hidden_size} hyper-connection features, got {hyper_input.shape[-1]}"
            )
        if injection_weights.shape[-1] != self.hc_count:
            raise ValueError(
                f"Expected {self.hc_count} injection weights, got {injection_weights.shape[-1]}"
            )
        leading_shape = block_output.shape[:-1]
        if hyper_input.shape[:-1] != leading_shape or injection_weights.shape[:-1] != leading_shape:
            raise ValueError("GatedResidual block output, hyper input, and injection weights must align")

        streams = hyper_input.unflatten(-1, (self.hc_count, self.hidden_size))
        injected = block_output.unsqueeze(-2) * injection_weights.unsqueeze(-1)
        return (streams + injected).flatten(-2)

    def _adopt_source(self, module: nn.Module, use_combine: bool | None) -> None:
        """Retain source children and parameter identities during replacement."""
        required = ("hc_norm", "input_mix_weight_down", "input_mix_weight_up")
        if any(not hasattr(module, name) for name in required):
            raise TypeError("GatedResidual source must expose hc_norm and input-mix projections")
        self.hc_norm = module.hc_norm
        self.input_mix_weight_down = module.input_mix_weight_down
        self.input_mix_weight_up = module.input_mix_weight_up
        source_inject = getattr(module, "block_inject_weight", None)
        inferred = source_inject is not None
        self.use_combine = inferred if use_combine is None else use_combine
        if not isinstance(self.use_combine, bool):
            raise TypeError("GatedResidual use_combine must be bool")
        if self.use_combine:
            if source_inject is None:
                raise ValueError("GatedResidual source has no block_inject_weight")
            self.block_inject_weight = source_inject

        self.hc_count = _positive_int(getattr(module, "hc_count", None), "hc_count")
        self.hidden_size = _positive_int(getattr(module, "hidden_size", None), "hidden_size")
        self.hc_lowrank = _positive_int(
            getattr(module.input_mix_weight_down, "out_features", None), "hc_lowrank"
        )
        expected = self.hyper_hidden_size
        if module.input_mix_weight_down.in_features != expected:
            raise ValueError("GatedResidual source down projection has incompatible input width")
        if (
            module.input_mix_weight_up.in_features != self.hc_lowrank
            or module.input_mix_weight_up.out_features != expected
        ):
            raise ValueError("GatedResidual source up projection has incompatible shape")
        if self.use_combine and module.block_inject_weight.out_features != self.hc_count:
            raise ValueError("GatedResidual source injection projection has incompatible shape")
        self.train(module.training)

    def forward(
        self, hyper_input: torch.Tensor,
    ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
        """Run the source-compatible mixer contract using the selected backend."""
        if hyper_input.shape[-1] != self.hyper_hidden_size:
            raise ValueError(
                f"Expected {self.hyper_hidden_size} hyper-connection features, got {hyper_input.shape[-1]}"
            )
        weight_gate = self.block_inject_weight.weight if self.use_combine else None
        mixed, injection = gated_residual(
            hyper_input,
            self.input_mix_weight_down.weight,
            self.input_mix_weight_up.weight,
            weight_gate,
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
            gamma=self.hc_norm.weight,
            eps=self.hc_norm.eps,
            backend=self.backend,
        )
        if not self.use_combine:
            return mixed
        if injection is None:
            raise RuntimeError("GatedResidual combine requires injection weights")
        return mixed, hyper_input, injection


def gated_residual_sharding(*, module: nn.Module, module_fqn: str, member: Any, context: Any) -> ModuleShardingSpec:
    """Declare explicit replicated parameter and sequence-token layouts.

    The eager family currently keeps all projections replicated under TP.  This
    is intentional: splitting the down projection requires an all-reduce between
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
    the down and up projections, which is not implicit in a module boundary.
    The declaration therefore preserves correctness while leaving a future
    collective-aware TP member free to introduce the Transformers rowwise plan.
    """
    del module_fqn, member
    replicated = {axis: Replicate() for axis in context.mesh_dim_names if axis in context.axis_sizes}
    tokens = dict(replicated)
    if context.axis_sizes.get("cp", 1) > 1:
        tokens["cp"] = Shard(1)
    if context.axis_sizes.get("tp", 1) > 1 and context.sequence_parallel:
        tokens["tp"] = Shard(1)
    params = {name: dict(replicated) for name, _ in module.named_parameters()}
    outputs = (
        ("mixed_input", "hyper_input", "injection_weights")
        if getattr(module, "use_combine", False)
        else ("output",)
    )
    output_layout = {name: dict(tokens) for name in outputs}
    return ModuleShardingSpec(
        params=params,
        in_src={"hyper_input": dict(tokens)},
        in_dst={"hyper_input": dict(tokens)},
        out_src=output_layout,
267
268
269
270
271
272
273
274
275
276
        is_boundary=True,
    )


@module_replacement
def GatedResidual(  # pylint: disable=invalid-name
    *,
    config: Any = None,
    module: nn.Module | None = None,
    module_fqn: str = "",
278
279
280
281
282
283
284
285
286
    mesh: Any = None,
    use_combine: bool | None = None,
) -> nn.Module:
    """Build the config-selected Gated Residual family member from config or source."""
    return build_family(
        GatedResidual,
        config=config,
        module=module,
        module_fqn=module_fqn,
289
290
291
292
293
294
295
296
297
        use_combine=use_combine,
    )


register_module_family(
    ModuleFamily(
        name="gated_residual",
        baseline=GatedResidual,
        variants={"local": "hyper_parallel.components.modules.common.gated_residual.GatedResidualModule"},
300
301
302
303
304
    )
)


__all__ = ["GatedResidual", "GatedResidualModule", "gated_residual_sharding"]