Diff Coverage

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

Source File Diff Coverage (%) Missing Lines
hyper_parallel/codegen/inline/component_source.py 100%  
hyper_parallel/codegen/inline/recognition.py 100%  
hyper_parallel/codegen/model_build_overlay.py 50.0% 42-43
hyper_parallel/components/modules/common/causal_lm_head.py 77.3% 44,46-50,53,62,80,84
hyper_parallel/components/modules/common/rms_norm.py 83.3% 65,220,224
hyper_parallel/components/modules/common/rotary_embedding.py 71.3% 31-47,71,93,104,108,110,123,139,147,152,155,157,159,182,191,199,201,244,260
hyper_parallel/components/modules/common/situ_mlp.py 79.3% 37,62,68,76,95,98,101,103,105,114,119,122,129-134
hyper_parallel/components/modules/engram/engram.py 96.7% 68,122
hyper_parallel/components/modules/engram/engram_family.py 100%  
hyper_parallel/components/modules/engram/host_checkpoint.py 82.9% 73,88,103,111-113,123,125,128,135,140,143,177,189-190,193,204,214-215,224,246-247,251-252,258,265,272,274,281,287,299,311,338,346,364,366,368-370,373,382,384,387
hyper_parallel/components/modules/engram/host_optimizer.py 92.4% 40,53,90,98,127
hyper_parallel/components/modules/engram/host_source.py 91.5% 50,58,61,77,81,84,87,107,114,120,202
hyper_parallel/components/modules/engram/host_state.py 79.8% 90,94-95,135,138,176,188,224-227,243-246,248-249,255-256,261-264,266,285-286,288,300,320,322-326,329-331,339,343,348,351,374
hyper_parallel/components/modules/engram/parallel_engram.py 96.7% 514
hyper_parallel/components/modules/mhc/_utils.py 94.4% 108
hyper_parallel/components/modules/mhc/mhc_family.py 100%  
hyper_parallel/components/modules/mhc/pipelined_mhc.py 58.3% 33-34,38,57,66,69,209-219,223-224,226,228-231,233,239-244,254-255,257,259
hyper_parallel/components/modules/mlp/swiglu_mlp.py 78.6% 45,48,65,67,95-96,114,135,138,150,152,154,156,158,160,162,164,166,228,251,253,255,268,317,338,346-348,350-354,372,391,398,400-403,409,411,414-415,417-420,426,430,437-438,478-479
hyper_parallel/components/modules/moe/grouped_experts/grouped_experts.py 100%  
hyper_parallel/components/modules/moe/shared_expert.py 100%  
hyper_parallel/components/modules/swiglu_mlp_family.py 100%  
hyper_parallel/high_availability/validation.py 100%  
hyper_parallel/codegen/model_build_overlay.py
38
39
40
41
42
43
44
45
46
47
def _prepare_model_source_compat(adapter: Any) -> None:
    """Run an optional model-owned compatibility hook before construction."""
    prepare_source = getattr(adapter, "source_import", None) if adapter is not None else None
    if prepare_source is not None:
        prepare_source()
        return
    loader = getattr(adapter, "codegen", None) if adapter is not None else None
    provider = loader() if loader is not None else None
    prepare = getattr(provider, "prepare_model_import", None)
    if prepare is not None:
hyper_parallel/components/modules/common/causal_lm_head.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    ) -> None:
        """Construct a bias-free head or adopt an existing compatible projection."""
        del module_fqn, context
        if (config is None) == (module is None):
            raise ValueError("provide exactly one of config or module")
        if module is None:
            for name in ("hidden_size", "vocab_size"):
                value = getattr(config, name, None)
                if isinstance(value, bool) or not isinstance(value, int) or value < 1:
                    raise ValueError(f"{name} must be a positive integer")
            super().__init__(config.hidden_size, config.vocab_size, bias=False)
        else:
            if not isinstance(module, nn.Linear) or module.bias is not None:
                raise ValueError("CausalLMHead requires a bias-free Linear source")
            nn.Module.__init__(self)
            self.in_features, self.out_features = module.in_features, module.out_features
            self.register_parameter("weight", module.weight)
            self.register_parameter("bias", None)
58
59
60
61
62
63
64
65
66
            self.training = module.training

    def make_transforms(self) -> list:
        """Projection names and shapes are unchanged."""
        return []

    def forward(
        self,
        input: torch.Tensor,
76
77
78
79
80
81
82
83
84
85
86
87
        locally sharded sequence. Chunked mode never creates full-sequence logits.
        """
        if targets is None:
            if loss_mask is not None:
                raise ValueError("loss_mask requires aligned targets")
            return F.linear(input, self.weight)  # pylint: disable=not-callable
        if loss_mask is not None:
            if loss_mask.shape != targets.shape:
                raise ValueError("loss_mask and targets must have identical shapes")
            targets = targets.masked_fill(~loss_mask.bool(), ignore_index)
        loss = chunked_cross_entropy(input, targets, self.weight, chunk_size=chunk_size, ignore_index=ignore_index)
        return ChunkedCausalLMOutput(loss_sum=loss, valid_token_count=(targets != ignore_index).sum())
hyper_parallel/components/modules/common/rms_norm.py
61
62
63
64
65
66
67
68
69
    @property

    def variance_epsilon(self) -> float:
        """Expose the source normalization epsilon to fused residual computations."""
        return self.eps

    def _set_policy(self, source: Any, cast_order: str | None, fp32_weight: bool | None) -> None:
        """Resolve source rounding order and FP32 scale ownership."""
        if cast_order is None:
216
217
218
219
220
221
222
223
224
225
226
227
228
    def _adopt_source(self, module: torch.nn.Module) -> None:
        """Validate offset ownership and convert only an explicitly declared direct scale."""
        weight = getattr(module, "weight", None)
        if not isinstance(weight, torch.nn.Parameter) or weight.ndim != 1:
            raise TypeError("offset source must expose a one-dimensional Parameter weight")
        self.eps = module.eps
        _validate_rms_settings(weight.numel(), self.eps)
        if self.fp32_weight and weight.dtype != torch.float32:
            raise ValueError("fp32_weight source must already own an FP32 offset")
        if self.source_representation == "scale":
            if isinstance(module, OffsetRMSNormModule) or _hf_scale_kind(module) == "offset":
                raise ValueError("offset source must not be declared as a direct scale")
            weight = torch.nn.Parameter(weight.detach() - 1.0, requires_grad=weight.requires_grad)
hyper_parallel/components/modules/common/rotary_embedding.py
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


def _yarn_frequencies(parameters: dict, dim: int, base: float, factor: float) -> torch.Tensor:
    """Build the static interpolation/extrapolation blend from its declared rotation range."""
    original = parameters.get("original_max_position_embeddings")
    if isinstance(original, bool) or not isinstance(original, int) or original < 1:
        raise ValueError("YaRN requires positive original_max_position_embeddings")
    fast, slow = parameters.get("beta_fast") or 32, parameters.get("beta_slow") or 1
    if fast <= 0 or slow <= 0 or base <= 1:
        raise ValueError("YaRN requires positive beta values and rope base greater than one")
    low = dim * log(original / (fast * 2 * pi)) / (2 * log(base))
    high = dim * log(original / (slow * 2 * pi)) / (2 * log(base))
    if parameters.get("truncate", True):
        low, high = floor(low), ceil(high)
    low, high = max(low, 0), min(high, dim - 1)
    if low == high:
        high += 0.001
    ramp = ((torch.arange(dim // 2, dtype=torch.float32, device="cpu") - low) / (high - low)).clamp(0, 1)
    extrapolation = 1 - ramp
    periods = base ** (torch.arange(0, dim, 2, dtype=torch.float32, device="cpu") / dim)
    return (1.0 / (factor * periods)) * (1 - extrapolation) + (1.0 / periods) * extrapolation


class RotaryEmbeddingModule(nn.Module):
    """Return split-half cos/sin; standard, linear and dynamic NTK have distinct validated semantics.
67
68
69
70
71
72
73
74
75
                              if output_format is None else output_format)
        if self.output_format not in ("cos_sin", "complex"):
            raise ValueError("Rotary output_format must be cos_sin or complex")
        if mrope_interleaved is not None and not isinstance(mrope_interleaved, bool):
            raise TypeError("mrope_interleaved must be bool or None")
        if module is not None:
            self._initialize_source(module, mrope_interleaved=mrope_interleaved)
        else:
            self.dim = config.dim
89
90
91
92
93
94
95
96
            elif self.rope_type == "yarn":
                parameters = getattr(config, "rope_parameters", None)
                if not parameters:
                    raise ValueError("YaRN direct construction requires explicit rope_parameters")
                frequency = _yarn_frequencies(parameters, self.dim, self.base, self.factor)
            register_rebuildable_buffer(self, "inv_freq", value=frequency, persistent=False)
            self.inv_freq = self.inv_freq.to(target)
        self._validate()
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
        source_config = getattr(module, "config", None)
        params = getattr(source_config, "rope_parameters", None) or getattr(source_config, "rope_scaling", {}) or {}
        self.rope_type = getattr(module, "rope_type", params.get("rope_type", "default"))
        if self.rope_type not in ("default", "linear", "yarn"):
            raise ValueError("source conversion supports static default/linear/YaRN RoPE; "
                             "dynamic cache needs explicit config")
        frequency = getattr(module, "inv_freq", None)
        if not isinstance(frequency, torch.Tensor) or frequency.ndim != 1:
            raise ValueError("source requires a one-dimensional inv_freq buffer")
        if any(True for _ in module.parameters()):
            raise ValueError("parameterized rotary sources require a separate state contract")
        self.dim = 2 * frequency.numel()
        self.base = float(params.get("rope_theta", getattr(source_config, "rope_theta", 10000.0)))
        self.factor = float(params.get("factor", 1.0))
        self.max_position_embeddings = int(getattr(source_config, "max_position_embeddings", 2048))
119
120
121
122
123
124
125
126
127
        self.inv_freq = frequency
        original = getattr(module, "original_inv_freq", None)
        if isinstance(original, torch.Tensor):
            if original.shape != frequency.shape:
                raise ValueError("original rotary frequency shape must match inv_freq")
            value = rebuilt.clone() if original.is_meta else original.detach().cpu()
            register_rebuildable_buffer(self, "original_inv_freq", value=value, persistent=False)
            self.original_inv_freq = original
        self.train(module.training)
135
136
137
138
139
140
141
142
143
            mrope_interleaved = source_interleaved
        if self.mrope_section and mrope_interleaved is None:
            raise ValueError("multi-axis source requires an explicit mrope_interleaved contract")
        if mrope_interleaved is not None and not isinstance(mrope_interleaved, bool):
            raise TypeError("mrope_interleaved must be bool or None")
        self.mrope_interleaved = False if mrope_interleaved is None else mrope_interleaved

    def _rebuild_source_frequency(self, module: nn.Module, source_config: Any, params: dict,
                                  frequency: torch.Tensor) -> torch.Tensor:
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
                                  frequency: torch.Tensor) -> torch.Tensor:
        """Reconstruct only meta frequencies with the audited source arithmetic order."""
        if frequency.is_meta:
            if isinstance(module, RotaryEmbeddingModule):
                rebuilt = self.base ** (-torch.arange(0, self.dim, 2, device="cpu").float() / self.dim)
            elif callable(getattr(module, "compute_default_rope_parameters", None)):
                with torch.device("cpu"):
                    rebuilt, _ = module.compute_default_rope_parameters(source_config, device="cpu")
                if rebuilt.is_meta or rebuilt.shape != frequency.shape:
                    raise ValueError("source static rotary builder must produce the declared CPU frequency shape")
                rebuilt = rebuilt.detach().cpu()
            else:
                raise ValueError("meta rotary source must declare a supported frequency construction contract")
            if self.rope_type == "linear":
                rebuilt = rebuilt / self.factor
            elif self.rope_type == "yarn":
                rebuilt = _yarn_frequencies(params, self.dim, self.base, self.factor)
        else:
            rebuilt = frequency.detach().cpu()
        return rebuilt
178
179
180
181
182
183
184
185
186
        """Validate supported frequency and position layouts before execution."""
        if isinstance(self.dim, bool) or not isinstance(self.dim, int) or self.dim < 2 or self.dim % 2:
            raise ValueError("rotary dim must be a positive even integer")
        if self.rope_type not in ("default", "linear", "dynamic", "yarn"):
            raise ValueError("supported rope_type values are default, linear, dynamic and yarn")
        for name in ("base", "factor", "attention_factor"):
            value = getattr(self, name)
            if isinstance(value, bool) or not isinstance(value, (float, int)) or not isfinite(value) or value <= 0:
                raise ValueError(f"{name} must be finite and positive")
187
188
189
190
191
192
193
194
195
        if (isinstance(self.max_position_embeddings, bool)
                or not isinstance(self.max_position_embeddings, int) or self.max_position_embeddings < 1):
            raise ValueError("max_position_embeddings must be positive")
        if self.output_format not in ("cos_sin", "complex"):
            raise ValueError("Rotary output_format must be cos_sin or complex")
        self._validate_position_layout()

    def _validate_position_layout(self) -> None:
        """Validate dynamic NTK extent constraints and multi-axis section coverage."""
195
196
197
198
199
200
201
202
203
204
205
        """Validate dynamic NTK extent constraints and multi-axis section coverage."""
        if self.rope_type == "dynamic" and (self.dim <= 2 or self.factor < 1):
            raise ValueError("dynamic NTK requires dim > 2 and factor >= 1")
        if not isinstance(self.mrope_interleaved, bool):
            raise ValueError("mrope_interleaved must be boolean")
        if self.mrope_interleaved and len(self.mrope_section) != 3:
            raise ValueError("interleaved multimodal RoPE requires three axis sections")
        if self.mrope_section and (
                any(isinstance(x, bool) or not isinstance(x, int) or x < 1 for x in self.mrope_section)
                or sum(self.mrope_section) != self.dim // 2):
            raise ValueError("mrope_section must partition the half-dimension into positive axis sections")
240
241
242
243
244
245
246
247
248
            ) ** (self.dim / (self.dim - 2))
            frequency = adjusted ** (-torch.arange(0, self.dim, 2, device=x.device).float() / self.dim)
        # Explicit elementwise FP32 multiplication is unaffected by GEMM autocast.
        if self.mrope_interleaved and position_ids.ndim == 2:
            position_ids = position_ids.unsqueeze(0).expand(3, -1, -1)
        angles = position_ids.float().unsqueeze(-1) * frequency
        if position_ids.ndim == 3 and self.mrope_section:
            angles = self._merge_position_axes(angles)
        elif position_ids.ndim != 2 or self.mrope_section:
256
257
258
259
260
261
262
263
264

    def _merge_position_axes(self, angles: torch.Tensor) -> torch.Tensor:
        """Select source-declared axis sections before duplicating rotary channels."""
        if angles.shape[0] != len(self.mrope_section):
            raise ValueError("position axes must match mrope_section")
        if self.mrope_interleaved:
            merged = angles[0].clone()
            for axis in (1, 2):
                indices = slice(axis, self.mrope_section[axis] * 3, 3)
hyper_parallel/components/modules/common/situ_mlp.py
33
34
35
36
37
38
39
40
41
    def __init__(self, beta: float = 1.0, linear_beta: float | None = None) -> None:
        """Declare gate and optional up-projection saturation scales."""
        super().__init__()
        if beta <= 0 or (linear_beta is not None and linear_beta <= 0):
            raise ValueError("SiTU saturation scales must be positive")
        self.beta, self.linear_beta = beta, linear_beta

    def forward(self, packed: torch.Tensor) -> torch.Tensor:
        """Preserve the source activation's slicing and FP32 evaluation boundaries."""
58
59
60
61
62
63
64
65
66
        """Construct directly or adopt the exact source parameter identities without packing weights."""
        super().__init__()
        del module_fqn, context
        if (config is None) == (module is None):
            raise ValueError("provide exactly one of config or module")
        if module is not None:
            config = module.config
            state_layout = "w1_w3_w2" if all(hasattr(module, name) for name in ("w1", "w3", "w2")) else "gate_up_down"
        self.config = config
64
65
66
67
68
69
70
71
72
            config = module.config
            state_layout = "w1_w3_w2" if all(hasattr(module, name) for name in ("w1", "w3", "w2")) else "gate_up_down"
        self.config = config
        if state_layout not in ("gate_up_down", "w1_w3_w2"):
            raise ValueError("SiTU MLP supports gate_up_down or w1_w3_w2 source state")
        self.state_layout = state_layout
        self.projection_names = (
            ("gate_proj", "up_proj", "down_proj") if state_layout == "gate_up_down" else ("w1", "w3", "w2")
        )
72
73
74
75
76
77
78
79
80
        )
        beta = getattr(config, "activation_situ_beta", None) or 1.0
        linear_beta = getattr(config, "activation_situ_linear_beta", None)
        if getattr(config, "hidden_act", None) != "situ":
            raise ValueError("SiTUMLP requires a SiTU source activation contract")
        if module is not None:
            self._adopt_source(module, beta, linear_beta)
        else:
            self.hidden_size, self.intermediate_size = config.hidden_size, config.intermediate_size
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
    def _adopt_source(self, module: nn.Module, beta: float, linear_beta: float | None) -> None:
        """Validate and retain separate SiTU matrices and the source activation contract."""
        expected = set(self.projection_names) | {"act_fn"}
        if set(dict(module.named_children())) != expected or list(module.named_parameters(recurse=False)):
            raise ValueError("Unsupported separate-matrix SiTU source structure")
        gate, up, down = (getattr(module, name) for name in self.projection_names)
        if not all(type(item) is nn.Linear for item in (gate, up, down)):  # pylint: disable=unidiomatic-typecheck
            raise ValueError("SiTU source projections must be plain Linear modules")
        if ((gate.in_features, gate.out_features, down.in_features, down.out_features)
                != (up.in_features, up.out_features, gate.out_features, gate.in_features)):
            raise ValueError("SiTU source projection dimensions do not compose")
        if len({(p.device, p.dtype) for item in (gate, up, down) for p in item.parameters()}) != 1:
            raise ValueError("SiTU source projections must share device and dtype")
        if module.act_fn.beta != beta or module.act_fn.linear_beta != linear_beta:
            raise ValueError("SiTU source activation and config disagree")
        self.hidden_size, self.intermediate_size = gate.in_features, gate.out_features
        for name, child in module.named_children():
            self.add_module(name, SiTUActivation(beta, linear_beta) if name == "act_fn" else child)
        self.get_submodule("act_fn").training = module.act_fn.training
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
        self.training = module.training

    def make_transforms(self) -> list:
        """Keep every independent source matrix and state key unchanged."""
        return []

    def forward(self, hidden_states: torch.Tensor | None = None, *, x: torch.Tensor | None = None) -> torch.Tensor:
        """Project gate/up separately, evaluate public SiTU and project back to hidden width."""
        if hidden_states is not None and x is not None:
            raise ValueError("Provide SiTU inputs through hidden_states or x, not both")
        hidden_states = hidden_states if x is None else x
        if hidden_states is None:
            raise ValueError("SiTU requires input activations")
        gate, up, down = (getattr(self, name) for name in self.projection_names)
        return down(self.act_fn(torch.cat((gate(hidden_states), up(hidden_states)), dim=-1)))

125
126
127
128
129
130
131
132
133
134
135
136
137
138


def situ_sharding(*, module: nn.Module, module_fqn: str, member: Any, context: Any) -> ModuleShardingSpec:
    """Own every source matrix while keeping the currently local computation explicit."""
    del module_fqn, member
    placements = {axis: Replicate() for axis in context.mesh_dim_names if axis in context.axis_sizes}
    tokens = dict(placements)
    if context.axis_sizes["cp"] > 1:
        tokens["cp"] = Shard(1)
    return ModuleShardingSpec(
        params={name: dict(placements) for name, _ in module.named_parameters()},
        in_src={"hidden_states": dict(tokens)},
        in_dst={"hidden_states": dict(tokens)},
        out_src={"output": dict(tokens)},
hyper_parallel/components/modules/engram/engram.py
64
65
66
67
68
69
70
71
72

    def adopt(cls, source: nn.Embedding) -> "_LocalRowEmbedding":
        """Preserve the source Parameter identity without initializing or copying weights."""
        if source.padding_idx is not None or source.max_norm is not None or source.scale_grad_by_freq or source.sparse:
            raise ValueError("Engram requires an unpadded dense embedding without in-place row normalization")
        if isinstance(source, cls):
            return source
        result = cls(source.num_embeddings, source.embedding_dim, _weight=source.weight,
                     _freeze=not source.weight.requires_grad)
118
119
120
121
122
123
124
125
126
        self.train(module.training)

    def parallel_module_spec(self) -> ParallelModuleSpec:
        """Borrow existing job groups; Engram owns its sparse row transport and hash halo."""
        return ParallelModuleSpec(
            "engram.rows",
            "mesh",
            {"forward": ("hidden_states", "input_ids", "segment_starts", "token_mask")},
            validate=validate_engram_layout,
hyper_parallel/components/modules/engram/host_checkpoint.py
69
70
71
72
73
74
75
76
77
def _sparse_moment_snapshot(state, table) -> dict[str, Any]:
    """Read moments for saving without creating optimizer state."""
    sparse = state.sparse_optimizer
    if sparse is None:
        raise RuntimeError("Host table has no SparseAdam optimizer")
    moments = sparse.state.get(table.weight, {})
    exp_avg = moments.get("exp_avg")
    exp_avg_sq = moments.get("exp_avg_sq")
    return {
84
85
86
87
88
89
90
91
92
def _initialize_sparse_moments(state, table) -> dict[str, Any]:
    """Create owner-local moments only for restore or explicit reset."""
    sparse = state.sparse_optimizer
    if sparse is None:
        raise RuntimeError("Host table has no SparseAdam optimizer")
    moments = sparse.state[table.weight]
    moments.setdefault("step", 0)
    if "exp_avg" not in moments:
        moments["exp_avg"] = torch.zeros_like(table.weight)
 99
100
101
102
103
104
105
106
    digest = hashlib.sha256()
    digest.update(str(int(moments["step"])).encode())
    for tensor in (table.weight, moments["exp_avg"], moments["exp_avg_sq"]):
        if tensor.device.type != "cpu" or tensor.dtype != torch.float32:
            raise ValueError("Host sidecar tensors must be CPU FP32")
        digest.update(memoryview(tensor.detach().contiguous().numpy()).cast("B"))
    return digest.hexdigest()

107
108
109
110
111
112
113
114
115
116
117

def _all_rank_objects(value):
    if not dist.is_initialized():
        return [value]
    gathered = [None] * dist.get_world_size()
    dist.all_gather_object(gathered, value)
    return gathered


def _validate_files(records: list[dict[str, Any]]) -> list[dict[str, Any]]:
    """Check owner replicas agree and keep one writer record per owner."""
119
120
121
122
123
124
125
126
127
128
129
130
131
132
    for record in records:
        key = (record["stage"], record["fqn"], record["ep_rank"])
        previous = by_owner.setdefault(key, record)
        if previous["fingerprint"] != record["fingerprint"]:
            raise ValueError(f"Host owner replicas disagree: {key}")
        if previous["start"] != record["start"] or previous["rows"] != record["rows"]:
            raise ValueError(f"Host owner replica interval mismatch: {key}")
        if record.get("file"):
            if previous.get("file") and previous is not record:
                raise ValueError(f"Host owner has multiple sidecar writers: {key}")
            by_owner[key] = record
    files = sorted(by_owner.values(), key=lambda entry: (entry["stage"], entry["fqn"], entry["start"]))
    by_layer = {}
    for entry in files:
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
    by_layer = {}
    for entry in files:
        by_layer.setdefault((entry["stage"], entry["fqn"]), []).append(entry)
        if not entry.get("file"):
            raise ValueError("Host owner has no sidecar file")
    for (stage, fqn), entries in by_layer.items():
        cursor = 0
        for entry in entries:
            if entry["start"] != cursor:
                raise ValueError(f"Host row coverage gap or overlap: {stage}:{fqn}")
            cursor += entry["rows"]
        if cursor != entries[0]["physical_rows"]:
            raise ValueError(f"Host row coverage incomplete: {stage}:{fqn}")
    return files


def _write_owner_record(state: Any, root: Path, stage: int,
173
174
175
176
177
178
179
180
181
def _consistent_sparse_hparams(gathered: list[dict[str, Any]]) -> dict[str, Any]:
    """Choose nonempty optimizer settings and verify all Host stages agree."""
    settings = [entry["sparse_hparams"] for entry in gathered if entry["sparse_hparams"]]
    if settings and any(item != settings[0] for item in settings):
        raise ValueError("Host sparse optimizer settings differ between ranks")
    return settings[0] if settings else {}


def _publish_schema(root: Path, schema: dict[str, Any]) -> None:
185
186
187
188
189
190
191
192
193
194
195
196
197
        if not dist.is_initialized() or dist.get_rank() == 0:
            temporary = root / f".schema.{os.getpid()}.tmp"
            temporary.write_text(json.dumps(schema, sort_keys=True), encoding="utf-8")
            os.replace(temporary, root / "schema.json")
    except (OSError, TypeError, ValueError) as exc:
        schema_error = str(exc)
    errors = [message for message in _all_rank_objects(schema_error) if message]
    if errors:
        raise RuntimeError(f"Host sidecar schema write failed: {errors[0]}")


def before_checkpoint_save(state: Any, runtime: CheckpointRuntime) -> None:
    """Write one file per owner, validate all replicas, then publish schema.
200
201
202
203
204
205
206
207
208
        state: Trainer or external model state.
        runtime: Checkpoint runtime and topology context.
    """
    if not runtime.include_optimizer or not runtime.include_train_state:
        raise ValueError("Host checkpoint requires optimizer and train state")
    root = Path(runtime.step_dir) / _DIR
    root.mkdir(parents=True, exist_ok=True)
    mesh = runtime.mesh_context
    stage = int(getattr(mesh, "pp_rank", 0))
210
211
212
213
214
215
216
217
218
219
    error = None
    try:
        for fqn, table in state.tables.items():
            records.append(_write_owner_record(state, root, stage, fqn, table))
    except (OSError, RuntimeError, ValueError) as exc:
        error = str(exc)
    hparams = state.sparse_optimizer.param_groups[0].copy() if state.sparse_optimizer else {}
    hparams.pop("params", None)
    gathered = _all_rank_objects({
        "records": records, "error": error, "sparse_hparams": hparams,
220
221
222
223
224
225
226
227
228
        "optimizer_keys": sorted(runtime.persisted_optimizer_keys),
    })
    errors = [entry["error"] for entry in gathered if entry["error"]]
    if errors:
        raise RuntimeError(f"Host sidecar save failed: {errors[0]}")
    files = _validate_files([record for entry in gathered for record in entry["records"]])
    hparams = _consistent_sparse_hparams(gathered)
    optimizer_keys_by_rank = [entry["optimizer_keys"] for entry in gathered]
    schema = {
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
def _validate_dense_metadata(step_dir: str, expected: list[str]) -> None:
    """Require DCP optimizer leaves to equal the sidecar's exact manifest."""
    if not expected:
        return
    metadata = FileSystemReader(step_dir).read_metadata()
    persisted = {
        key.removeprefix("optimizer.") for key in metadata.state_dict_metadata
        if key.startswith("optimizer.")
    }
    if persisted != set(expected):
        raise ValueError("Dense optimizer DCP metadata differs from Host sidecar manifest")


def _validate_sparse_optimizer_hparams(state: Any, schema: dict[str, Any]) -> None:
    """Require the same SparseAdam settings apart from the scheduled LR."""
254
255
256
257
258
259
260
261
262

def _validate_sparse_optimizer_hparams(state: Any, schema: dict[str, Any]) -> None:
    """Require the same SparseAdam settings apart from the scheduled LR."""
    if state.sparse_optimizer is None:
        return
    current = state.sparse_optimizer.param_groups[0].copy()
    current.pop("params", None)
    current.pop("lr", None)
    saved = schema["sparse_hparams"].copy()
261
262
263
264
265
266
267
268
269
    current.pop("lr", None)
    saved = schema["sparse_hparams"].copy()
    saved.pop("lr", None)
    if json.loads(json.dumps(current, sort_keys=True)) != saved:
        raise ValueError("Host SparseAdam hyperparameters differ from checkpoint")


def _validate_load_schema(state: Any, runtime: CheckpointRuntime,
                          root: Path, schema: dict[str, Any]) -> None:
268
269
270
271
272
273
274
275
276
277
278
def _validate_load_schema(state: Any, runtime: CheckpointRuntime,
                          root: Path, schema: dict[str, Any]) -> None:
    """Validate topology, dense metadata, owner checksums and local intervals."""
    if schema["format_version"] != _VERSION or schema["assets_digest"] != _asset_digest(state):
        raise ValueError("Host sidecar version or asset digest mismatch")
    if schema["topology"] != _topology(runtime.mesh_context):
        raise ValueError("Host sidecar topology mismatch")
    _validate_sparse_optimizer_hparams(state, schema)
    files = _validate_files(schema["files"])
    _validate_dense_metadata(runtime.step_dir, schema["dense_optimizer_keys"])
    for entry in files:
277
278
279
280
281
282
283
284
285
    _validate_dense_metadata(runtime.step_dir, schema["dense_optimizer_keys"])
    for entry in files:
        path = root / entry["file"]
        if _sha_file(path) != entry["sha256"]:
            raise ValueError(f"Host sidecar checksum mismatch: {path}")
    for fqn, table in state.tables.items():
        matches = [entry for entry in files if entry["fqn"] == fqn
                   and entry["stage"] == getattr(runtime.mesh_context, "pp_rank", 0)
                   and entry["ep_rank"] == table.ep_rank]
283
284
285
286
287
288
289
290
291
        matches = [entry for entry in files if entry["fqn"] == fqn
                   and entry["stage"] == getattr(runtime.mesh_context, "pp_rank", 0)
                   and entry["ep_rank"] == table.ep_rank]
        if len(matches) != 1 or matches[0]["start"] != table.global_row_start:
            raise ValueError(f"Host sidecar owner interval mismatch: {fqn}")


def _local_optimizer_keys(schema: dict[str, Any], rank: int,
                          world_size: int) -> frozenset[str]:
295
296
297
298
299
300
301
302
303
        raise ValueError("Host sidecar dense optimizer rank manifest mismatch")
    for keys in by_rank:
        if (not isinstance(keys, list) or any(not isinstance(key, str) for key in keys)
                or len(keys) != len(set(keys))):
            raise ValueError("Host sidecar dense optimizer rank keys are invalid")
    return frozenset(by_rank[rank])


def before_checkpoint_load(state: Any, runtime: CheckpointRuntime) -> HostSidecarLoadPlan:
307
308
309
310
311
312
313
314
315
        state: Trainer or external model state.
        runtime: Checkpoint runtime and topology context.
    """
    if runtime.include_optimizer != runtime.include_train_state:
        raise ValueError("Host checkpoint restore requires both optimizer and train state or neither")
    root = Path(runtime.step_dir) / _DIR
    error = None
    schema = None
    local_keys = frozenset()
334
335
336
337
338
339
340
341
342
                 and item["stage"] == getattr(runtime.mesh_context, "pp_rank", 0)
                 and item["ep_rank"] == table.ep_rank)
    payload = torch.load(root / entry["file"], map_location="cpu", weights_only=True)
    if tuple(payload["weight"].shape) != tuple(table.weight.shape):
        raise ValueError(f"Host sidecar row shape mismatch: {fqn}")
    with torch.no_grad():
        table.weight.copy_(payload["weight"])
    if runtime.include_optimizer:
        moments = _initialize_sparse_moments(state, table)
342
343
344
345
346
347
348
349
        moments = _initialize_sparse_moments(state, table)
        moments["step"] = int(payload["step"])
        for name in ("exp_avg", "exp_avg_sq"):
            if tuple(payload[name].shape) != tuple(table.weight.shape):
                raise ValueError(f"Host sidecar moment shape mismatch: {fqn}:{name}")
            moments[name].copy_(payload[name])
    table.clear_step()

360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
    root = Path(runtime.step_dir) / _DIR
    plan_error = None
    try:
        if not isinstance(load_plan, HostSidecarLoadPlan):
            raise TypeError("Host sidecar load plan has an invalid type")
        if load_plan.step_dir != runtime.step_dir:
            raise ValueError("Host sidecar load plan belongs to a different checkpoint")
        if not isinstance(load_plan.schema, dict):
            raise TypeError("Host sidecar load plan schema has an invalid type")
    except (TypeError, ValueError) as exc:
        plan_error = str(exc)
    errors = [message for message in _all_rank_objects(plan_error) if message]
    if errors:
        raise RuntimeError(f"Host sidecar load failed: {errors[0]}")

    error = None
    try:
        schema = load_plan.schema
378
379
380
381
382
383
384
385
386
387
388
389
390
391
        if runtime.include_optimizer and state.sparse_optimizer is not None:
            state.sparse_optimizer.param_groups[0]["lr"] = schema["current_lr"]
        for fqn, table in state.tables.items():
            _restore_owner_payload(state, runtime, root, schema, fqn, table)
    except (EOFError, OSError, KeyError, RuntimeError, StopIteration,
            TypeError, ValueError, pickle.UnpicklingError) as exc:
        error = str(exc)
    errors = [message for message in _all_rank_objects(error) if message]
    if errors:
        raise RuntimeError(f"Host sidecar load failed: {errors[0]}")


def after_weights_only_load(state: Any) -> None:
    """Discard sparse optimizer moments without modifying restored weights.
hyper_parallel/components/modules/engram/host_optimizer.py
36
37
38
39
40
41
42
43
44
        self.state = "ACCUMULATING"
        self.optimizers_dict = dict(dense.optimizers_dict)
        if sparse is not None:
            if "engram_sparse" in self.optimizers_dict:
                raise ValueError("Dense optimizer already uses engram_sparse name")
            self.optimizers_dict["engram_sparse"] = sparse
        self.chained_optimizers = list(self.optimizers_dict.values())
        self.param_groups = [group for optimizer in self.chained_optimizers
                             for group in optimizer.param_groups]
49
50
51
52
53
54
55
56
57
        Args:
            closure: Optional optimizer closure.
        """
        if self.state != "PREPARED":
            raise RuntimeError("Host sparse optimizer step requires PREPARED gradients")
        for table in self.tables.values():
            table.install_grad()
        result = self.dense.step(closure=closure)
        sparse_seconds = 0.0
86
87
88
89
90
91
92
93
        self.state = "ACCUMULATING"

    def state_dict(self) -> dict[str, Any]:
        """Return only dense optimizer state for regular DCP."""
        return self.dense.state_dict()

    def load_state_dict(self, state_dict: dict[str, Any]) -> None:
        """Load only dense optimizer state; the sparse sidecar restores the rest.
 94
 95
 96
 97
 98
 99
100
101

        Args:
            state_dict: State dictionary to read or write.
        """
        self.dense.load_state_dict(state_dict)

    def drop_unpersisted_dense_state(self, persisted_keys: frozenset[str]) -> None:
        """Discard lazy moments absent from the saved dense optimizer state.
123
124
125
126
127
                optimizer.state.pop(optimizer_param, None)

    def optimizer_for_dcp(self) -> Any:
        """Return the dense wrapper for lazy optimizer-state materialization."""
        return self.dense
hyper_parallel/components/modules/engram/host_source.py
46
47
48
49
50
51
52
53
54
    if not path.is_file():
        return root, {}
    payload = json.loads(path.read_text(encoding="utf-8"))
    if payload.get("format_version") != 1 or not isinstance(payload.get("tables"), dict):
        raise ValueError("Invalid Engram Host row manifest")
    return root, payload["tables"]


def _read_manifest_rows(root: Path, source_key: str, spec: dict[str, Any],
54
55
56
57
58
59
60
61
62
63
64
65
def _read_manifest_rows(root: Path, source_key: str, spec: dict[str, Any],
                        table: HostEngramTable) -> torch.Tensor:
    """Validate complete physical row coverage and read only this owner."""
    if spec.get("shape") != [table.physical_rows, table.width]:
        raise ValueError(f"Host Engram manifest shape mismatch: {source_key}")
    fragments = spec.get("fragments")
    if not isinstance(fragments, list) or not fragments:
        raise ValueError(f"Host Engram manifest has no row fragments: {source_key}")
    rows = torch.empty((table.rows_per_owner, table.width), dtype=torch.float32)
    owner_start = table.global_row_start
    owner_end = owner_start + table.rows_per_owner
    cursor = 0
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
        if left >= right:
            continue
        path = (root / fragment["file"]).resolve()
        if not path.is_relative_to(root.resolve()) or path.suffix != ".safetensors":
            raise ValueError(f"Host Engram manifest has invalid fragment path: {source_key}")
        with safe_open(str(path), framework="pt", device="cpu") as source:
            tensor_slice = source.get_slice(fragment["key"])
            if tuple(tensor_slice.get_shape()) != (length, table.width):
                raise ValueError(f"Host Engram manifest fragment shape mismatch: {source_key}")
            part = tensor_slice[left - start:right - start]
        if part.dtype != torch.float32:
            raise ValueError(f"Host Engram manifest fragment dtype mismatch: {source_key}")
        rows[left - owner_start:right - owner_start] = part
    if cursor != table.physical_rows:
        raise ValueError(f"Host Engram manifest row coverage incomplete: {source_key}")
    return rows


def _host_source_keys(model: nn.Module, checkpoint_index: Any,
103
104
105
106
107
108
109
110
111
            source_key, renamings, converters, getattr(model, "base_model_prefix", None),
            meta_state_dict=all_targets,
        )
        if target not in targets and source_key in targets:
            target, source_pattern = rename_source_key(
                source_key, [], [], getattr(model, "base_model_prefix", None),
                meta_state_dict=all_targets,
            )
        if target not in targets:
110
111
112
113
114
115
116
117
118
            )
        if target not in targets:
            continue
        if source_pattern is not None:
            raise ValueError(f"Host Engram source conversion cannot be sliced: {source_key}")
        if target in found:
            raise ValueError(f"Multiple Host Engram source keys map to {target}")
        found[target] = source_key
    missing = targets - found.keys()
116
117
118
119
120
121
122
123
124
            raise ValueError(f"Multiple Host Engram source keys map to {target}")
        found[target] = source_key
    missing = targets - found.keys()
    if missing:
        raise KeyError(f"Missing Host Engram source key for {sorted(missing)}")
    return found


def _seed_owner_rows(fqn: str, table: HostEngramTable) -> torch.Tensor:
198
199
200
201
202
203
204
205
                        lambda start, count, tensor_slice=tensor_slice: tensor_slice[start:start + count],
                    )
            source_keys.add(source_key)
        if rows.dtype != torch.float32 or tuple(rows.shape) != tuple(table.weight.shape):
            raise ValueError(f"Host Engram source dtype or local shape mismatch: {target}")
        torch.utils.swap_tensors(table.weight, nn.Parameter(rows.contiguous()))
        table.weight._is_hf_initialized = True  # pylint: disable=W0212
    return frozenset(source_keys)
hyper_parallel/components/modules/engram/host_state.py
86
87
88
89
90
91
92
93
94
95
96
97
98
            table = self.tables[fqn.removesuffix(".weight")]
            if (named.get(fqn) is not parameter or parameter.device.type != "cpu"
                    or parameter.dtype != torch.float32
                    or tuple(parameter.shape) != (table.rows_per_owner, table.width)):
                raise RuntimeError(f"Host Engram parameter identity or device changed: {fqn}")

    def weight_digests(self) -> dict[str, str]:
        """Fingerprint owner-local row bytes around ordinary model initialization."""
        self.check_identities()
        return {
            fqn: hashlib.sha256(memoryview(parameter.detach().contiguous().numpy()).cast("B")).hexdigest()
            for fqn, parameter in self.parameters.items()
        }
131
132
133
134
135
136
137
138
139
140
141
142
    def recovery_replica_ranks(self, rank: int) -> set[int]:
        """Derive same-owner replicas from the mesh used to synchronize sparse gradients."""
        mesh = self.mesh_context
        if mesh is None or mesh.device_mesh is None:
            return {rank}
        moe = mesh.fsdp_moe_mesh
        if moe is None:
            return set(mesh.device_mesh.rank_list)
        ranks = tuple(moe.rank_list)
        own = np.unravel_index(ranks.index(rank), moe.mesh_shape)
        return {
            peer for peer, coordinate in zip(ranks, np.ndindex(moe.mesh_shape))
172
173
174
175
176
177
178
179
180
        ).get_optimizer()
        dense_ids = {id(param) for group in dense_raw.param_groups for param in group["params"]}
        all_ids = {id(param) for param in self.model.parameters() if param.requires_grad}
        if dense_ids & host_ids or dense_ids | host_ids != all_ids:
            raise ValueError("Dense and Host optimizers do not partition trainable parameters")
        dense = wrap_dense(dense_raw)
        hparams = getattr(getattr(self.model, "config", None), "engram_sparse_adam_config", None)
        if hparams is None:
            hparams = {"lr": 1.0e-3}
184
185
186
187
188
189
190
191
        return self.optimizer

    def optimizer_for_dcp(self) -> Any:
        """Return the dense optimizer that owns the DCP state."""
        return self.optimizer.optimizer_for_dcp()

    def before_checkpoint_save(self, runtime: CheckpointRuntime) -> None:
        """Write and verify CPU owner sidecars before dense DCP save.
220
221
222
223
224
225
226
227
228
229
230
231
        """Count each owner's synchronized row gradient on one edp replica."""
        mesh = self.mesh_context
        if mesh is None or mesh.device_mesh is None or not dist.is_initialized():
            return True
        moe = mesh.fsdp_moe_mesh
        if moe is None:
            return dist.get_rank() == min(mesh.device_mesh.rank_list)
        return all(moe.get_local_rank(name) == 0 for name in
                   ("edp_shard", "edp_replicate") if name in (moe.mesh_dim_names or ()))

    def _prepare_sparse_rows(self, gradient_divisor: float = 1.0) -> None:
        """Coalesce and synchronize each table before the shared failure gate."""
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
                started = time.perf_counter()
                local = table.coalesce_pending()
                table.coalesce_seconds += time.perf_counter() - started
                local_bad = False
            except (ValueError, IndexError) as exc:
                logger.error("Host sparse local row validation failed: %s", exc)
                local = None
                local_bad = True
            if stage_check(local_bad, mesh):
                failed = True
                break
            synced = sparse_sum_same_ep(local, mesh, table.width)
            synced_nnz = synced._nnz()  # pylint: disable=protected-access
            table.max_synced_nnz = max(table.max_synced_nnz, synced_nnz)
            if stage_check(synced_nnz > table.max_sparse_rows_per_step or
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
            synced_nnz = synced._nnz()  # pylint: disable=protected-access
            table.max_synced_nnz = max(table.max_synced_nnz, synced_nnz)
            if stage_check(synced_nnz > table.max_sparse_rows_per_step or
                           not bool(torch.isfinite(synced.values()).all()), mesh):
                failed = True
                break
            table.pending = torch.sparse_coo_tensor(
                synced.indices(), synced.values() / (denominator * gradient_divisor), synced.shape,
            ).coalesce()
        if mesh is not None and mesh.pp_size > 1:
            device_type = mesh.device_mesh.device_type
            failure_flag = torch.tensor(int(failed), device=torch.device(device_type))
            dist.all_reduce(failure_flag, op=dist.ReduceOp.MAX)
            failed = bool(failure_flag.item())
        if failed:
            raise RuntimeError("Host sparse gradient validation failed")

    def _combined_gradient_norm(self) -> tuple[torch.Tensor, list[torch.Tensor]]:
        """Count each dense shard and synchronized sparse owner exactly once."""
        mesh = self.mesh_context
281
282
283
284
285
286
287
288
289
290
291
292
                sparse_sq.add_(table.pending.values().square().sum().to(dense_sq.device))
        stage_reduce_scalar(sparse_sq, mesh)
        global_sq = dense_sq + sparse_sq
        if mesh is not None and mesh.pp_size > 1:
            dist.all_reduce(global_sq, op=dist.ReduceOp.SUM)
            global_sq.div_(mesh.dp_size * mesh.cp_size * mesh.tp_size)
        if not bool(torch.isfinite(global_sq)):
            raise RuntimeError("Non-finite combined Engram gradient norm")
        return global_sq.sqrt(), dense_refs

    def prepare_optimizer_step(self, *, max_norm: float, gradient_divisor: float = 1.0) -> GradientPreparation:
        """Normalize owned sparse gradients, then clip jointly with dense gradients.
296
297
298
299
300
301
302
303
304
            gradient_divisor: Step divisor for sparse gradients only; Trainer has
                already normalized dense gradients. Defaults to no normalization.
        """
        if self.optimizer is None or self.optimizer.state != "ACCUMULATING":
            raise RuntimeError("Host gradient preparation requires ACCUMULATING state")
        self._prepare_sparse_rows(gradient_divisor)
        norm, dense_refs = self._combined_gradient_norm()
        coefficient = (torch.clamp(max_norm / (norm + 1.0e-6), max=1.0)
                       if max_norm > 0 else torch.ones_like(norm))
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
def _validate_host_source_layout(target: str, layout: Any, ep_size: int) -> None:
    """Require the planner's sole EP row shard and reject any second shard."""
    if ep_size == 1:
        if layout is not None and any(isinstance(place, Shard) for place in layout[0]):
            raise ValueError(f"EP1 Host Engram cannot be sharded: {target}")
        return
    if layout is None:
        raise ValueError(f"Missing EP source layout for {target}")
    placements, source_mesh = layout
    dim_names = source_mesh.mesh_dim_names or ()
    if len(placements) != len(dim_names) or sum(
            name == "ep" and isinstance(place, Shard) and place.dim == 0
            for name, place in zip(dim_names, placements)) != 1:
        raise ValueError(f"Host Engram requires exactly one EP Shard(0): {target}")
    if any(isinstance(place, Shard) and name != "ep" for name, place in zip(dim_names, placements)):
        raise ValueError(f"Host Engram has an unexpected second shard: {target}")


def _validate_host_model_mode(model: nn.Module, tables: Mapping[str, HostEngramTable],
                              context: ExternalBuildContext) -> bool:
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
                              context: ExternalBuildContext) -> bool:
    """Reject mixed device/Host replacements and unsupported build settings."""
    backend = getattr(getattr(model, "config", None), "engram_storage_backend", "device")
    if backend not in ("device", "host"):
        raise ValueError("engram_storage_backend must be 'device' or 'host'")
    if not tables and backend != "host":
        return False
    if backend != "host":
        raise ValueError("HostEngramModule requires engram_storage_backend='host'")
    from hyper_parallel.components.modules.engram import EngramModule  # pylint: disable=C0415
    if any(isinstance(module, EngramModule)
           and not isinstance(module.embed, HostEngramTable)
           for module in model.modules()):
        raise ValueError("Host Engram configuration still contains a device replacement")
    if (context.validate_placement or context.init_device is None
            or context.model_init_dtype not in (torch.float32, torch.bfloat16)):
        raise ValueError("Host Engram requires meta production build with model_init_dtype=float32 or bfloat16")
    return True


def build_engram_external_state(model: nn.Module,
370
371
372
373
374
375
376
377
378
    ep_size = mesh.ep_size if mesh is not None else 1
    ep_rank = mesh.ep_rank if mesh is not None else 0
    ep_mesh = mesh.fsdp_moe_mesh["ep"] if ep_size > 1 else None
    if ep_mesh is not None:
        ep_rank = ep_mesh.get_local_rank()
    for fqn, table in tables.items():
        target = f"{fqn}.weight"
        layout = (context.source_shard_info or {}).get(target)
        _validate_host_source_layout(target, layout, ep_size)
hyper_parallel/components/modules/engram/parallel_engram.py
510
511
512
513
514
515
516
517
518
                mask.to(torch.bool).unsqueeze(-1).unsqueeze(-1),
                fused, hidden_states,
            )
        if ep_size > 1:
            return module.parallel_forward(
                hidden_states, input_ids, segment_starts, token_mask,
                ep_group=ep_group, ep_rank=ep_rank, ep_size=ep_size,
                cp_group=cp_group, cp_rank=cp_rank, cp_size=cp_size,
                tp_rank=tp_rank, tp_size=tp_size,
hyper_parallel/components/modules/mhc/_utils.py
104
105
106
107
108
109
110
def _validate_pipelined(*, config: Any, module: nn.Module | None, context: Any, member: Any) -> None:
    """Reject fused execution without the matching shifted boundary protocol."""
    del config, module, context
    if member.selectors["use_fused_ops"] and not member.selectors["shifted"]:
        raise ValueError("Native pipelined mHC requires shifted=True")
    if member.selectors["use_fused_ops"] and any(member.axis_sizes[axis] > 1 for axis in ("tp", "cp")):
        raise NotImplementedError("Native shifted mHC requires TP=CP=1 until its advance boundary is qualified")
hyper_parallel/components/modules/mhc/pipelined_mhc.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class _UnweightedRMSNorm(nn.Module):
    """Normalize coefficient predictors without introducing an extra learned scale."""

    def __init__(self, eps: float) -> None:
        super().__init__()
        self.eps = eps

    def forward(self, values: torch.Tensor) -> torch.Tensor:
        """Preserve the source FP32 variance and input-dtype reciprocal scaling order."""
        return values * torch.rsqrt(values.float().square().mean(-1, keepdim=True) + self.eps).to(values.dtype)


class PipelinedMhcModule(nn.Module):
    """Coefficient module for cross-sublayer pipelined mHC."""
53
54
55
56
57
58
59
60
61
        """Reuse the source module's ``fn/base/scale`` parameter layout."""
        super().__init__()
        del module_fqn, context
        if isinstance(token_tile, bool) or not isinstance(token_tile, int) or token_tile < 1:
            raise ValueError("token_tile must be a positive integer")
        self.token_tile = token_tile
        if (module is None) == (config is None):
            raise ValueError("provide exactly one of config or module")
        source = config if config is not None else module
62
63
64
65
66
67
68
69
70
71
72
73
        self.init_scale = getattr(source, "init_scale", 0.01 if config is not None else 1.0)
        self.init_method_std = getattr(source, "init_method_std", 0.02)
        if (isinstance(self.init_scale, bool) or not isinstance(self.init_scale, (int, float))
                or not isfinite(self.init_scale)):
            raise ValueError("init_scale must be finite")
        if (isinstance(self.init_method_std, bool) or not isinstance(self.init_method_std, (int, float))
                or not isfinite(self.init_method_std) or self.init_method_std <= 0):
            raise ValueError("init_method_std must be positive and finite")
        if config is not None:
            self._init_from_config(config)
        else:
            self._adopt_source(module)
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
236
237
    def __init__(self, *, config: Any = None, module: nn.Module | None = None,
                 module_fqn: str = "", context: Mapping[str, Any] | None = None,
                 token_tile: int = 32) -> None:
        """Retain the ordinary coefficient state keys for the shifted training protocol."""
        super().__init__(config=config, module=module, module_fqn=module_fqn, context=context, token_tile=token_tile)
        if tuple(self.input_norm.parameters()):
            raise ValueError("Shifted pipelined mHC requires unweighted coefficient normalization")
        if self.hc_mult != 4 or self.hc_sinkhorn_iters != 20:
            raise ValueError("Shifted pipelined mHC requires four streams and twenty Sinkhorn iterations")
        if isinstance(token_tile, bool) or not isinstance(token_tile, int) or token_tile < 1:
            raise ValueError("token_tile must be a positive integer")
        self.token_tile = token_tile
        self.norm_eps = getattr(self.input_norm, "eps", getattr(self.input_norm, "variance_epsilon", None))
        if self.norm_eps is None:
            raise ValueError("Shifted pipelined mHC requires the source normalization epsilon")

    def _apply(self, fn: Any, recurse: bool = True) -> nn.Module:
        """Keep coefficient, normalization and gradient storage in FP32 during dtype conversion."""
        protected = {id(parameter) for parameter in self.parameters()}
        protected.update(id(parameter.grad) for parameter in self.parameters() if parameter.grad is not None)

        def preserve(tensor: torch.Tensor) -> torch.Tensor:
            """Keep protected coefficients in FP32 without a lower-precision round trip."""
            converted = fn(tensor)
            if id(tensor) not in protected or converted.dtype == torch.float32:
                return converted
            return converted.float() if tensor.is_meta else tensor.to(device=converted.device, dtype=torch.float32)

        return super()._apply(preserve, recurse=recurse)

    def advance(self, previous_output: torch.Tensor, residual: torch.Tensor,
                previous_pre_mix: torch.Tensor, previous_post_mix: torch.Tensor,
                previous_residual_mix: torch.Tensor, norm_weight: torch.Tensor) -> tuple[torch.Tensor, ...]:
235
236
237
238
239
240
241
242
243
244
245
246
247
248
    def advance(self, previous_output: torch.Tensor, residual: torch.Tensor,
                previous_pre_mix: torch.Tensor, previous_post_mix: torch.Tensor,
                previous_residual_mix: torch.Tensor, norm_weight: torch.Tensor) -> tuple[torch.Tensor, ...]:
        """Evaluate the source shifted boundary with ordinary differentiable Torch operations."""
        updated = pipelined_mhc_post(previous_output, residual, previous_post_mix, previous_residual_mix)
        pre, post, mixing = self(updated)
        collapsed = (previous_pre_mix.unsqueeze(-1) * updated.float()).sum(dim=2)
        reciprocal_std = torch.rsqrt(collapsed.square().mean(dim=-1, keepdim=True) + self.norm_eps)
        block_input = (collapsed * reciprocal_std).to(residual.dtype) * norm_weight
        return updated, pre, post, mixing, block_input


class NativeShiftedPipelinedMhcModule(ShiftedPipelinedMhcModule):
    """Use the native multicore kernel with the same coefficient and external-normalization ownership."""
250
251
252
253
254
255
256
257
258
259
260
261
262
    def advance(self, previous_output: torch.Tensor, residual: torch.Tensor,
                previous_pre_mix: torch.Tensor, previous_post_mix: torch.Tensor,
                previous_residual_mix: torch.Tensor, norm_weight: torch.Tensor) -> tuple[torch.Tensor, ...]:
        """Execute the explicitly selected NPU kernel without changing state keys or silently falling back."""
        if residual.device.type != "npu":
            raise ValueError("Native shifted pipelined mHC requires NPU tensors")
        # The multicore dependency is optional until its execution member is called.
        from hyper_multicore.modules.mega_mhc.function import hyper_mega_mhc  # pylint: disable=import-outside-toplevel

        return hyper_mega_mhc(previous_output, residual, previous_pre_mix, previous_post_mix,
                              previous_residual_mix, self.fn.float(), self.scale.float(), self.base.float(),
                              norm_weight, hc_eps=self.hc_eps, norm_eps=self.norm_eps,
                              num_iters=self.hc_sinkhorn_iters, token_tile=self.token_tile)
hyper_parallel/components/modules/mlp/swiglu_mlp.py
41
42
43
44
45
46
47
48
49
50
51
52
        value = getattr(config, name)
        if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
            raise ValueError(f"{name} must be a positive integer")
    if not isinstance(config.bias, bool):
        raise TypeError("bias must be bool")
    limit = getattr(config, "swiglu_limit", 0.0)
    if isinstance(limit, bool) or not isinstance(limit, (int, float)) or not isfinite(limit):
        raise ValueError("swiglu_limit must be finite; nonpositive values disable clamping")


def swiglu_activation(gate: torch.Tensor, up: torch.Tensor, *, limit: float = 0.0,
                       activation_dtype: str = "input") -> torch.Tensor:
61
62
63
64
65
66
67
68
69
70
71
        limit: Positive clamp bound; nonpositive values disable clamping.
        activation_dtype: Compute in the input dtype or float32.
    """
    if activation_dtype not in ("input", "float32"):
        raise ValueError("activation_dtype must be input or float32")
    if isinstance(limit, bool) or not isinstance(limit, (int, float)) or not isfinite(limit):
        raise ValueError("SwiGLU limit must be finite")
    if activation_dtype == "float32":
        gate, up = gate.float(), up.float()
    if limit > 0:
        gate, up = gate.clamp(max=limit), up.clamp(-limit, limit)
91
92
93
94
95
96
97
98
99
    """
    activation_dtype = _resolve_activation_dtype(activation_dtype, limit)
    if x.device.type == "npu" and limit <= 0 and activation_dtype == "input":
        # Optional NPU operators are required only by NPU execution.
        from hyper_parallel.components.functional import swiglu  # pylint: disable=C0415
        return swiglu(x)
    gate, up = x.chunk(2, dim=-1)
    return swiglu_activation(gate, up, limit=limit, activation_dtype=activation_dtype).to(x.dtype)

110
111
112
113
114
115
116
117
118
    if limit is None:
        limit = source.limit if hf_clamped_source else getattr(
            source, "swiglu_limit", 0.0 if hf_source else getattr(config, "swiglu_limit", 0.0))
    if isinstance(limit, bool) or not isinstance(limit, (int, float)) or not isfinite(limit):
        raise ValueError("swiglu_limit must be finite")
    if literal_source_limit and limit <= 0:
        raise ValueError("HF DeepseekV4 literal nonpositive clamp is not a disabled-clamp source contract")
    if activation_dtype is None:
        activation_dtype = getattr(source, "activation_dtype",
131
132
133
134
135
136
137
138
139
140
141
        """Validate and return the source Gate, Up, and Down projections."""
        required = ("gate_proj", "up_proj", "down_proj")
        missing = [name for name in required if not hasattr(module, name)]
        if missing:
            raise TypeError(f"SwiGLUMLPModule source module is missing: {missing}")
        projections = (module.gate_proj, module.up_proj, module.down_proj)
        if not all(isinstance(projection, nn.Linear) for projection in projections):
            raise TypeError("SwiGLUMLPModule requires Gate, Up, and Down projections to be nn.Linear")
        return projections

    @staticmethod
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
        down_proj: nn.Linear,
    ) -> None:
        """Validate source projection shapes, placement, and training policy."""
        if gate_proj.in_features != up_proj.in_features:
            raise ValueError("Gate and Up projections must have the same input size")
        if gate_proj.out_features != up_proj.out_features:
            raise ValueError("Gate and Up projections must have the same output size")
        if down_proj.in_features != gate_proj.out_features:
            raise ValueError("Down projection input size must equal the SwiGLU intermediate size")
        if down_proj.out_features != gate_proj.in_features:
            raise ValueError("Down projection output size must equal the MLP hidden size")
        if gate_proj.weight.device != up_proj.weight.device or gate_proj.weight.dtype != up_proj.weight.dtype:
            raise ValueError("Gate and Up projection weights must share device and dtype")
        if gate_proj.weight.device != down_proj.weight.device or gate_proj.weight.dtype != down_proj.weight.dtype:
            raise ValueError("Gate, Up, and Down projection weights must share device and dtype")
        if gate_proj.weight.requires_grad != up_proj.weight.requires_grad:
            raise ValueError("Gate and Up projection weights must share a training policy")
        if (gate_proj.bias is None) != (up_proj.bias is None):
            raise ValueError("Gate and Up projections must use the same bias policy")
        if gate_proj.bias is not None and gate_proj.bias.requires_grad != up_proj.bias.requires_grad:
            raise ValueError("Gate and Up projection biases must share a training policy")

    def _initialize_fc1(self, gate_proj: nn.Linear, up_proj: nn.Linear) -> None:
        """Create the packed Gate/Up projection with source parameter values."""
        pack = ConcatenateWithSections((self.intermediate_size, self.intermediate_size))
224
225
226
227
228
229
230
231
232
        """
        super().__init__()
        del module_fqn, context
        if (config is None) == (module is None):
            raise ValueError("provide exactly one of config or module")
        source = config if config is not None else module
        self.swiglu_limit, self.activation_dtype = _activation_settings(
            source, limit=swiglu_limit, activation_dtype=activation_dtype)
        if config is not None:
247
248
249
250
251
252
253
254
255
256
257
258
259
        if all(isinstance(getattr(module, name, None), nn.Linear) for name in ("w1", "w2")):
            source_config = getattr(module, "config", None)
            if (not hasattr(module, "swiglu_limit")
                    and getattr(source_config, "hidden_act", None) not in ("silu", "swiglu")):
                raise TypeError("packed w1/w2 source must explicitly declare SwiGLU activation semantics")
            if module.w1.out_features != 2 * module.w2.in_features or module.w2.out_features != module.w1.in_features:
                raise ValueError("packed SwiGLU source must contain [gate, up] rows followed by a down projection")
            if module.w1.weight.device != module.w2.weight.device or module.w1.weight.dtype != module.w2.weight.dtype:
                raise ValueError("packed SwiGLU projections must share device and dtype")
            self.config = getattr(module, "config", None)
            self.hidden_size, self.intermediate_size = module.w1.in_features, module.w2.in_features
            self.linear_fc1, self.linear_fc2 = module.w1, module.w2
            self._packed_source = True
264
265
266
267
268
269
270
271

        config = getattr(module, "config", None)
        hidden_act = getattr(config, "hidden_act", getattr(config, "hidden_activation", None))
        if hidden_act is not None and hidden_act not in ("silu", "swiglu"):
            raise ValueError(f"SwiGLUMLPModule requires a SiLU activation, but got {hidden_act}")
        self.config = config
        self.hidden_size = gate_proj.in_features
        self.intermediate_size = gate_proj.out_features
313
314
315
316
317
318
319
320
321
            x: Token activations, exclusive with hidden_states.
            hidden_states: Equivalent keyword spelling for token activations.
        """
        if (x is None) == (hidden_states is None):
            raise ValueError("provide exactly one of x or hidden_states")
        x = hidden_states if x is None else x
        intermediate_parallel = self.linear_fc1(x)
        intermediate_parallel = local_swiglu(intermediate_parallel, limit=self.swiglu_limit,
                                             activation_dtype=self.activation_dtype)
334
335
336
337
338
339
340
341
342
                 activation_dtype: str | None = None, swiglu_limit: float | None = None) -> None:
        """Construct vision projections or retain a declared packed source unchanged."""
        super().__init__()
        if (config is None) == (module is None):
            raise ValueError("provide exactly one of config or module")
        self.swiglu_limit, self.activation_dtype = _activation_settings(
            config if config is not None else module, limit=swiglu_limit, activation_dtype=activation_dtype)
        if config is not None:
            _validate_mlp_config(config)
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
            _validate_mlp_config(config)
            self.w1 = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=config.bias)
            self.w2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=config.bias)
        else:
            if not all(isinstance(getattr(module, name, None), nn.Linear) for name in ("w1", "w2")):
                raise TypeError("w1_w2 source requires two Linear projections")
            if (module.w1.out_features != 2 * module.w2.in_features
                    or module.w1.in_features != module.w2.out_features):
                raise ValueError("w1_w2 source must contain gate/up rows and a compatible down projection")
            if module.w1.weight.dtype != module.w2.weight.dtype or module.w1.weight.device != module.w2.weight.device:
                raise ValueError("w1/w2 must share dtype and device")
            self.w1, self.w2 = module.w1, module.w2
            self.train(module.training)

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        """Apply the shared SwiGLU math without changing source checkpoint names.
368
369
370
371
372
373
374
375
376
        self.w2.reset_parameters()

    def make_transforms(self) -> list[WeightRenaming | WeightConverter]:
        """Packed source and target share the same logical state names."""
        return []


class SeparateSwiGLUMLPModule(nn.Module):
    """SwiGLU retaining separate logical matrices and source parameter identities.
387
388
389
390
391
392
393
394
395
        """Build from complete config or validated separate source projections."""
        super().__init__()
        del module_fqn, context
        if (module is None) == (config is None):
            raise ValueError("provide exactly one of config or module")
        source = module if module is not None else config
        self.swiglu_limit, self.activation_dtype = _activation_settings(
            source, limit=swiglu_limit, activation_dtype=activation_dtype)
        self.config = config if module is None else getattr(module, "config", None)
394
395
396
397
398
399
400
401
402
403
404
405
406
407
            source, limit=swiglu_limit, activation_dtype=activation_dtype)
        self.config = config if module is None else getattr(module, "config", None)
        activation = getattr(self.config, "hidden_act", getattr(self.config, "hidden_activation", None))
        if activation is not None and activation not in ("silu", "swiglu"):
            raise ValueError(f"SwiGLU requires a SiLU activation, but got {activation}")
        if module is None:
            _validate_mlp_config(config)
            self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.bias)
            self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.bias)
            self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=config.bias)
        else:
            gate, up, down = SwiGLUMLPModule._source_projections(module)
            # Independent projection freezing is valid without a packed Parameter.
            if ((gate.in_features, gate.out_features, down.in_features, down.out_features)
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
            gate, up, down = SwiGLUMLPModule._source_projections(module)
            # Independent projection freezing is valid without a packed Parameter.
            if ((gate.in_features, gate.out_features, down.in_features, down.out_features)
                    != (up.in_features, up.out_features, gate.out_features, gate.in_features)):
                raise ValueError("SwiGLU projection shapes must describe one hidden/intermediate pair")
            if len({(item.weight.device, item.weight.dtype) for item in (gate, up, down)}) != 1:
                raise ValueError("SwiGLU projections must share device and dtype")
            self.gate_proj, self.up_proj, self.down_proj = gate, up, down
            if isinstance(getattr(module, "act_fn", None), nn.Module):
                activation_type = type(module.act_fn)
                hf_silu = (activation_type.__module__ == "transformers.activations"
                           and activation_type.__name__ == "SiLUActivation")
                if not isinstance(module.act_fn, nn.SiLU) and not hf_silu:
                    raise ValueError("Registered SwiGLU activation must be a supported SiLU module")
                self.act_fn = nn.SiLU()
                self.act_fn.training = module.act_fn.training
            self.training = module.training

    def forward(self, hidden_states: torch.Tensor | None = None, *, x: torch.Tensor | None = None) -> torch.Tensor:
        """Evaluate SwiGLU; ``x`` preserves HF MLP keyword calls."""
422
423
424
425
426
427
428
429
430
431
432
433

    def forward(self, hidden_states: torch.Tensor | None = None, *, x: torch.Tensor | None = None) -> torch.Tensor:
        """Evaluate SwiGLU; ``x`` preserves HF MLP keyword calls."""
        if (hidden_states is None) == (x is None):
            raise ValueError("provide exactly one of hidden_states or x")
        hidden_states = x if hidden_states is None else hidden_states
        gate, up = self.gate_proj(hidden_states), self.up_proj(hidden_states)
        if hasattr(self, "act_fn") and self.swiglu_limit <= 0 and self.activation_dtype == "input":
            hidden = self.act_fn(gate) * up
        else:
            hidden = swiglu_activation(gate, up, limit=self.swiglu_limit, activation_dtype=self.activation_dtype)
        return self.down_proj(hidden.to(hidden_states.dtype))
433
434
435
436
437
438
439
440
441
442
        return self.down_proj(hidden.to(hidden_states.dtype))

    def reset_parameters(self) -> None:
        """Initialize the three projections after meta materialization."""
        for projection in (self.gate_proj, self.up_proj, self.down_proj):
            projection.reset_parameters()

    def make_transforms(self) -> list[WeightRenaming | WeightConverter]:
        """Source checkpoint names and shapes already match this member."""
        return []
474
475
476
477
478
479

def parameter_sharding_rules() -> list[tuple[str, Any]]:
    """Declare packed projection roles next to the family owning those names."""
    # The planner imports family discovery; resolve its role type after discovery completes.
    from hyper_parallel.distributed.tensor_parallel.param_role import ParamRole  # pylint: disable=C0415
    return [("linear_fc1.weight", ParamRole.FUSED_GATE_UP), ("linear_fc2.weight", ParamRole.ROWWISE)]