Diff Coverage

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

Source File Diff Coverage (%) Missing Lines
hyper_parallel/components/modules/attention/compressed_sparse_attention2/cp_compressed_sparse_attention2.py 0.0% 168,174,180
hyper_parallel/components/modules/attention/compressed_sparse_attention2/indexer.py 0.0% 650
hyper_parallel/distributed/activation_checkpoint.py 93.8% 162,234,245,253-254,270,300,320,350-351,360,462,472,503,515,524,533,546,677,690,723,734,747,991,1028
hyper_parallel/tools/model_integration/case_matrix.py 81.8% 77,82-83,177
hyper_parallel/tools/model_integration/cli.py 84.2% 573,579,583,586-587,596
hyper_parallel/trainer/base.py 100%  
hyper_parallel/trainer/config/parallelism.py 95.7% 74,112,115,117,141,186,237,405,452
hyper_parallel/trainer/config/resolver.py 100%  
hyper_parallel/trainer/config/trainer.py 66.7% 95
hyper_parallel/components/modules/attention/compressed_sparse_attention2/cp_compressed_sparse_attention2.py
164
165
166
167
168
169
170
171
172
            raise NotImplementedError("Indexer overlap requires ordinary causal selection and TP=1")
        cos, sin = compress_position_embeddings
        weights = self.weights_proj(hidden_states.detach())
        weights = weights * (self.head_dim**-0.5 * self.global_num_heads**-0.5)
        wave = self._launch_selection(query_residual, weights, (cos, sin), document_lengths)
        prepared_key = self.prepare_key(latent, cos, sin, index_key, block_plan, key_position_embeddings)
        if prepare_attention is not None:
            prepare_attention()
        prepared = self._prepare_dispatched(wave)
170
171
172
173
174
175
176
177
178
        if prepare_attention is not None:
            prepare_attention()
        prepared = self._prepare_dispatched(wave)
        key = self.exchange_key(prepared_key)
        select = self._select_dispatched
        result = select(prepared, key)
        del prepared
        query = self._project_index_query(query_residual, cos, sin)
        if weights.shape[-1] != query.shape[2]:
176
177
178
179
180
181
182
183
184
        del prepared
        query = self._project_index_query(query_residual, cos, sin)
        if weights.shape[-1] != query.shape[2]:
            raise ValueError("Indexer query and merge weights must have matching head counts")
        return CSA2IndexerOutput(self._finish_selection(result), key, None, query, weights)

    @torch.no_grad()
    def _launch_selection(self, qr: torch.Tensor, weights: torch.Tensor, embeddings: tuple, lengths: tuple) -> Any:
        """Use the existing task planner and dtype-preserving input transport."""
hyper_parallel/components/modules/attention/compressed_sparse_attention2/indexer.py
646
647
648
649
650
651
652
653
654
        if weights.shape[-1] != query.shape[2]:
            raise ValueError("Indexer query and merge weights must have matching head counts")
        weights = weights * (self.head_dim**-0.5 * self.global_num_heads**-0.5)
        key = self.exchange_key(prepared_key)
        selected, candidates = self._select_tokens(
            query, key, weights, candidate_blocks, query_offset, reduce_sum,
            minimum_key_indices, query_segments, causal_upper,
        )
        return CSA2IndexerOutput(selected, key, candidates, query, weights)
hyper_parallel/distributed/activation_checkpoint.py
158
159
160
161
162
163
164
165
166

    def _visit(owner_fqn: str, owner: nn.Module) -> None:
        owner_id = id(owner)
        if owner_id in visited_module_ids or owner_id in discovered_block_ids:
            return
        visited_module_ids.add(owner_id)
        is_checkpoint_owner = hasattr(owner, "gradient_checkpointing")

        for container_name, container in owner.named_children():
230
231
232
233
234
235
236
237
238
) -> list[_LayerContainerInfo]:
    """Discover repeated transformer containers and optionally require one."""
    containers = _find_transformer_layer_container_infos(model)
    if required and not containers:
        raise ValueError(
            f"{type(model).__name__} has no module with a 'gradient_checkpointing' "
            "attribute and a non-empty repeated block container"
        )
    return containers
241
242
243
244
245
246
247
248
249
def _current_block(block_info: _TransformerBlockInfo) -> nn.Module:
    """Return the current registered block and reject structure drift."""
    block = block_info.parent._modules.get(block_info.child_name)  # pylint: disable=protected-access
    if not isinstance(block, nn.Module):
        raise ValueError(f"discovered layer {block_info.fqn} is no longer an nn.Module")
    return block


def _module_registration_order(layer: nn.Module) -> dict[str, int]:
249
250
251
252
253
254
255
256
257
258
def _module_registration_order(layer: nn.Module) -> dict[str, int]:
    """Return stable registered-module order within one layer."""
    try:
        iterator = layer.named_modules(remove_duplicate=False)
    except TypeError:
        iterator = layer.named_modules()
    return {module_path: index for index, (module_path, _) in enumerate(iterator)}


def _raise_incompatible_wrapper(
266
267
268
269
270
271
272
273
    """Reject existing or partially removed activation wrappers."""
    target_location = f"layer {layer_index}" if layer_index is not None else "model target"
    for descendant in module.modules():
        if isinstance(descendant, ActivationWrapper) or getattr(descendant, "_is_wrapped", False):
            raise ValueError(
                f"{config_path}: {target_location}, module {module_path!r} ({module_fqn}) "
                "is already covered by an incompatible activation wrapper"
            )
296
297
298
299
300
301
302
303
304
        if not isinstance(child, nn.Module):
            prefix = ".".join(parts[:part_index + 1])
            full_fqn = f"{block_info.fqn}.{prefix}"
            if hasattr(current, part):
                raise ValueError(
                    f"{config_path}: layer {layer_index}, module {module_path!r} resolves "
                    f"{full_fqn} to non-nn.Module {type(getattr(current, part)).__name__}"
                )
            raise ValueError(
316
317
318
319
320
321
322
323
324
        module_fqn=module_fqn,
    )
    module_order = _module_registration_order(layer).get(module_path)
    if module_order is None:
        raise ValueError(
            f"{config_path}: layer {layer_index}, module {module_path!r} ({module_fqn}) "
            "has no stable registered forward order"
        )
    return _ResolvedTarget(
346
347
348
349
350
351
352
353
354
355
    parent = model
    parts = module_path.split(".")
    for part_index, part in enumerate(parts):
        if isinstance(current, ActivationWrapper):
            prefix = ".".join(parts[:part_index]) or "<model>"
            raise ValueError(
                f"{config_path}: model module {module_path!r} crosses an existing "
                f"activation wrapper at {prefix}"
            )
        parent = current
356
357
358
359
360
361
362
363
364
        child = current._modules.get(part)  # pylint: disable=protected-access
        prefix = ".".join(parts[:part_index + 1])
        if not isinstance(child, nn.Module):
            if hasattr(current, part):
                raise ValueError(
                    f"{config_path}: model module {module_path!r} resolves {prefix} "
                    f"to non-nn.Module {type(getattr(current, part)).__name__}"
                )
            raise ValueError(
458
459
460
461
462
463
464
465
466
            for other in layer_targets[index + 1:]:
                if target.module_path.startswith(f"{other.module_path}.") or other.module_path.startswith(
                    f"{target.module_path}."
                ):
                    raise ValueError(
                        f"{config_path}: layer {layer_index} has nested activation targets "
                        f"{target.module_path!r} ({target.module_fqn}) and "
                        f"{other.module_path!r} ({other.module_fqn})"
                    )
468
469
470
471
472
473
474
475
476

def _target_description(target: Any) -> str:
    """Format one resolved target without inventing a model-level layer index."""
    if isinstance(target, _ResolvedTarget):
        return (
            f"{target.config_path}: layer {target.layer_index}, module "
            f"{target.module_path!r} ({target.module_fqn})"
        )
    return f"{target.config_path}: model module {target.module_path!r} ({target.module_fqn})"
499
500
501
502
503
504
505
506
            if other is target or other.module is target.module:
                continue
            other_descendants = {id(module) for module in other.module.modules()}
            if id(other.module) in target_descendants or id(target.module) in other_descendants:
                raise ValueError(
                    "activation_checkpoint.selective has nested activation targets: "
                    f"{_target_description(target)} and {_target_description(other)}"
                )
511
512
513
514
515
516
517
518
    full_layer_indices = {layer_index for layer_index, _ in plan.full_layers}
    full_targets = plan.full_save_targets + plan.full_swap_targets
    for target in full_targets:
        if target.layer_index not in full_layer_indices:
            raise ValueError(
                f"{target.config_path}: layer {target.layer_index}, module {target.module_path!r} "
                "is outside activation_checkpoint.full.recompute_layer"
            )
520
521
522
523
524
525
526
527
528
    full_conflicts = {_target_key(target) for target in plan.full_save_targets} & {
        _target_key(target) for target in plan.full_swap_targets
    }
    if full_conflicts:
        layer_index, module_path = sorted(full_conflicts)[0]
        raise ValueError(
            "activation_checkpoint.full exclude save/swap conflict on "
            f"layer {layer_index}, module {module_path!r}"
        )
529
530
531
532
533
534
535
536
537
    selective_conflicts = {
        _target_key(target) for target in plan.selective_recompute_targets
    } & {_target_key(target) for target in plan.selective_swap_targets}
    if selective_conflicts:
        layer_index, module_path = sorted(selective_conflicts)[0]
        raise ValueError(
            "activation_checkpoint.selective recompute/swap conflict on "
            f"layer {layer_index}, module {module_path!r}"
        )
542
543
544
545
546
547
548
549
            for target in plan.selective_recompute_targets + plan.selective_swap_targets
        }
        overlap = sorted(full_layer_indices & selective_layers)
        if overlap:
            raise ValueError(
                "activation_checkpoint.mode=hybrid requires disjoint full and selective layers; "
                f"overlap={overlap}"
            )
673
674
675
676
677
678
679
680
681
    selective_config = (
        getattr(config, "selective", None) if mode in ("selective", "hybrid") else None
    )
    if mode in ("full", "hybrid") and full_config is None:
        raise ValueError(f"activation_checkpoint.mode={mode} requires activation_checkpoint.full")
    if mode in ("selective", "hybrid") and selective_config is None:
        raise ValueError(
            f"activation_checkpoint.mode={mode} requires activation_checkpoint.selective"
        )
686
687
688
689
690
691
692
693
694
    """Return whether any active target needs transformer-block discovery."""
    if full_config is not None:
        return True
    if selective_config is None:
        return False
    return bool(selective_config.recompute_regions or selective_config.swap_regions)


def _resolve_optional_model_targets(
719
720
721
722
723
724
725
726
727
            if callable(value) and not isinstance(value, nn.Module) and hasattr(value, "__dict__")
        )
        for candidate in candidates:
            if id(candidate) in seen:
                continue
            seen.add(id(candidate))
            exists = hasattr(candidate, "_is_wrapped")
            snapshots.append((candidate, exists, getattr(candidate, "_is_wrapped", None)))
    return tuple(snapshots)
730
731
732
733
734
735
736
737
def _restore_overlap_marks(snapshots: tuple[tuple[object, bool, Any], ...]) -> None:
    """Restore overlap marks captured before wrapper construction."""
    for candidate, existed, value in snapshots:
        if existed:
            setattr(candidate, "_is_wrapped", value)
        elif hasattr(candidate, "_is_wrapped"):
            delattr(candidate, "_is_wrapped")

743
744
745
746
747
748
749
750
751
) -> None:
    """Install one already-constructed wrapper and record its inverse."""
    current = target.parent._modules.get(target.child_name)  # pylint: disable=protected-access
    if current is not target.module:
        raise RuntimeError(
            f"{target.config_path}: target {target.module_fqn} changed during activation wrapper apply"
        )
    setattr(target.parent, target.child_name, wrapped)
    records.append(_ReplacementRecord(target.parent, target.child_name, target.module))
987
988
989
990
991
992
993
994
995
        wired_modules = _wire_prefetch_chain(model, prefetch_nodes)
        model._hp_activation_checkpoint_resources = resources  # pylint: disable=protected-access
    except BaseException:
        if wired_modules:
            _teardown_wired_swap_layers(wired_modules)
        for record in reversed(replacements):
            setattr(record.parent, record.child_name, record.original)
        _restore_overlap_marks(overlap_marks)
        raise
1024
1025
1026
1027
1028
1029
1030
1031
1032
    """
    if activation_checkpoint is None or getattr(activation_checkpoint, "mode", None) == "off":
        return model
    if isinstance(activation_checkpoint, str):
        raise ValueError(
            "legacy activation_checkpoint string modes are unsupported; pass the normalized "
            "activation_checkpoint configuration object"
        )
    if enable_compile:
hyper_parallel/tools/model_integration/case_matrix.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87

def _validate_recompute_layers(value: Any, path: str) -> list[int | str]:
    """Validate one explicit full-checkpoint layer set."""
    if not isinstance(value, list):
        raise ValueError(f"{path} must be a list of layer numbers or ranges")
    if not value:
        return []
    try:
        return list(FullCheckpointConfig(recompute_layer=value).recompute_layers)
    except ValueError as error:
        raise ValueError(str(error).replace("activation_checkpoint.full.recompute_layer", path)) from error


def _validate_topology(topology: Mapping[str, Any], path: str) -> dict[str, Any]:
    """Reject fields that the standard Trainer launcher cannot consume."""
173
174
175
176
177
178
179
180
181
) -> list[ValidationCase]:
    """Generate one case per requested full-checkpoint layer set."""
    requested_layer_sets = matrix.get("recompute_layers") or ()
    if not isinstance(requested_layer_sets, (list, tuple)):
        raise ValueError("matrix.recompute_layers must be a list")
    cases = []
    for index, requested_layers in enumerate(requested_layer_sets):
        recompute_layers = _validate_recompute_layers(
            requested_layers,
hyper_parallel/tools/model_integration/cli.py
569
570
571
572
573
574
575
576
577
    recompute_layers: list[int],
) -> dict[str, Any]:
    """Restrict recipe-owned exclusions to layers active in one matrix case."""
    if not isinstance(raw_exclude_region, Mapping):
        raise ManifestError("activation_checkpoint.full.exclude_region must be a mapping")
    active_layers = set(recompute_layers)
    result: dict[str, Any] = {}
    for section in ("save", "swap"):
        raw_targets = raw_exclude_region.get(section) or {}
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
    result: dict[str, Any] = {}
    for section in ("save", "swap"):
        raw_targets = raw_exclude_region.get(section) or {}
        if not isinstance(raw_targets, Mapping):
            raise ManifestError(f"activation_checkpoint.full.exclude_region.{section} must be a mapping")
        targets = {}
        for module_path, raw_layers in raw_targets.items():
            if section == "swap" and module_path in ("group_swap", "cpu_pool"):
                continue
            try:
                normalized = FullCheckpointConfig(recompute_layer=raw_layers).recompute_layers
            except ValueError as error:
                raise ManifestError(
                    f"invalid activation_checkpoint.full.exclude_region.{section}.{module_path}: {error}"
                ) from error
            selected = [layer for layer in normalized if layer in active_layers]
            if selected:
592
593
594
595
596
597
598
599
600
                targets[module_path] = selected
        if not targets:
            continue
        if section == "swap":
            targets = {
                key: raw_targets[key]
                for key in ("group_swap", "cpu_pool")
                if key in raw_targets
            } | targets
hyper_parallel/trainer/config/parallelism.py
70
71
72
73
74
75
76
77
78

def _normalize_layer_set(value: object, *, path: str) -> tuple[int, ...]:
    """Normalize one YAML layer set into an ordered, duplicate-free tuple."""
    if not isinstance(value, (list, tuple)) or not value:
        raise ValueError(f"{path} must be a non-empty list of layer numbers or ranges")

    layers = []
    seen = set()
    for item in value:
108
109
110
111
112
113
114
115
116
117
118
119
120

def _validate_module_path(module_path: object, *, path: str) -> str:
    """Validate one exact layer-relative module path."""
    if not isinstance(module_path, str) or not module_path.strip():
        raise ValueError(f"{path} module paths must be non-empty strings")
    normalized = module_path.strip()
    if normalized != module_path or any(not part for part in normalized.split(".")):
        raise ValueError(f"{path}.{module_path} is not a valid dotted module path")
    if any(character in normalized for character in "*?[]"):
        raise ValueError(
            f"{path}.{module_path} must be an exact module path; glob and index syntax are unsupported"
        )
    return normalized
137
138
139
140
141
142
143
144
145

def _normalize_region_mapping(value: object, *, path: str) -> tuple[ModuleRegionSpec, ...]:
    """Normalize an exact module-path mapping into immutable region specs."""
    if not isinstance(value, Mapping):
        raise ValueError(f"{path} must be a mapping from module paths to layer sets")
    regions = []
    for raw_module_path, raw_layers in value.items():
        module_path = _validate_module_path(raw_module_path, path=path)
        regions.append(
182
183
184
185
186
187
188
189
            if len(item) != 1:
                raise ValueError(f"{item_path} must contain exactly one layer-relative module target")
            targets.extend(_normalize_region_mapping(item, path=item_path))
    else:
        raise ValueError(f"{path} must be a mapping or list of recompute targets")

    regions = tuple(target for target in targets if isinstance(target, ModuleRegionSpec))
    modules = tuple(target for target in targets if isinstance(target, ModelModuleSpec))
233
234
235
236
237
238
239
240
241
    path: str,
) -> tuple[tuple[ModuleRegionSpec, ...], bool, Optional[int]]:
    """Split swap common options from exact module-path targets."""
    if not isinstance(value, Mapping):
        raise ValueError(f"{path} must be a mapping")
    group_swap = _normalize_group_swap(value.get("group_swap", True), path=f"{path}.group_swap")
    cpu_pool_mb = _normalize_cpu_pool(value.get("cpu_pool"), path=f"{path}.cpu_pool")
    regions = _normalize_region_mapping(
        {key: item for key, item in value.items() if key not in _SWAP_OPTION_KEYS},
401
402
403
404
405
406
407
408
409
                "activation_checkpoint.selective requires at least one recompute or swap module target"
            )
        conflicts = _region_layer_pairs(self.recompute_regions) & _region_layer_pairs(self.swap_regions)
        if conflicts:
            layer_index, module_path = sorted(conflicts)[0]
            raise ValueError(
                "activation_checkpoint.selective.recompute and activation_checkpoint.selective.swap "
                f"conflict on layer {layer_index}, module {module_path!r}"
            )
448
449
450
451
452
453
454
455
456

    def __post_init__(self) -> None:
        """Validate mode-specific requirements and configuration conflicts."""
        if self.mode not in ("off", "full", "selective", "hybrid"):
            raise ValueError(
                "activation_checkpoint.mode must be off, full, selective, or hybrid; "
                f"got {self.mode!r}"
            )
        if self.mode in ("full", "hybrid"):
hyper_parallel/trainer/config/trainer.py
91
92
93
94
95
96
97
98
99
            self.compile.enabled
            and self.activation_checkpoint is not None
            and self.activation_checkpoint.mode != "off"
        ):
            raise ValueError(
                "compile.enabled=true is not supported with activation_checkpoint.mode="
                f"{self.activation_checkpoint.mode}"
            )
        if (