Diff Coverage

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

Source File Diff Coverage (%) Missing Lines
hyper_parallel/components/functional/gated_residual.py 55.7% 36,38,40,46,60,62,64,66,85,117-129,146-148,151-157,166-168,170-176,225-228,232
hyper_parallel/components/modules/common/gated_residual.py 73.2% 52,59,69,77-78,81-82,85,109,119,131,155,157,161,165,170,180,188,190-192,201,206,208,216,233,246-254,259-260
hyper_parallel/components/functional/gated_residual.py
32
33
34
35
36
37
38
39
40
41
42
43
44

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."""
42
43
44
45
46
47
48
49
50

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,
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
) -> 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,
81
82
83
84
85
86
87
88
        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

113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133


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}"
    )
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
        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,
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
    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
48
49
50
51
52
53
54
55
56

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:
55
56
57
58
59
60
61
62
63

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):
65
66
67
68
69
70
71
72
73

    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))
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
        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."""
105
106
107
108
109
110
111
112
113
        """
        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")
115
116
117
118
119
120
121
122
123
            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
127
128
129
130
131
132
133
134
135
        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:
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
        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)
176
177
178
179
180
181
182
183
184
    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)
184
185
186
187
188
189
190
191
192
193
194
195
196
        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(
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
            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,
212
213
214
215
216
217
218
219
220
        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(
229
230
231
232
233
234
235
236
237
        )
        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:
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,