Diff Coverage

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

Source File Diff Coverage (%) Missing Lines
hyper_parallel/auto_parallel/_layer_census.py 100%  
hyper_parallel/distributed/activation_checkpoint.py 79.6% 154,226,237,245-246,282,289-292,296,312,337-343,347-352,356,359,361-366,371,378,427,451,454,463-464,468,477,489-495,507,516,525,532,536-538,667,688,699,712,734,761,769,783-785,845-847,863-865,882,887-889,954,991
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.3% 74,112,115,117,141,186,237,405,452,459
hyper_parallel/trainer/config/resolver.py 100%  
hyper_parallel/trainer/config/trainer.py 66.7% 95
hyper_parallel/distributed/activation_checkpoint.py
150
151
152
153
154
155
156
157
158

    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():
222
223
224
225
226
227
228
229
230
) -> 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
233
234
235
236
237
238
239
240
241
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]:
241
242
243
244
245
246
247
248
249
250
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(
278
279
280
281
282
283
284
285
286
    parent = layer
    parts = module_path.split(".")
    for part_index, part in enumerate(parts):
        if isinstance(current, ActivationWrapper):
            raise ValueError(
                f"{config_path}: layer {layer_index}, module {module_path!r} crosses "
                f"an existing activation wrapper at {block_info.fqn}"
            )
        parent = current
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
            )
        parent = current
        child = current._modules.get(part)  # pylint: disable=protected-access
        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(
                f"{config_path}: layer {layer_index}, module {module_path!r} does not exist "
                f"at {full_fqn}"
            )
        current = child
308
309
310
311
312
313
314
315
316
        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(
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
    module_path: str,
    config_path: str,
) -> _ResolvedModelTarget:
    """Resolve one exact model-root-relative module outside transformer layers."""
    current = model
    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
        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(
                f"{config_path}: model module {module_path!r} does not exist at {prefix}"
            )
        current = child

    target_module_ids = {id(module) for module in current.modules()}
    for layer_index, block_info in enumerate(blocks):
        layer = _current_block(block_info)
        layer_module_ids = {id(module) for module in layer.modules()}
        if id(current) in layer_module_ids or id(layer) in target_module_ids:
            raise ValueError(
                f"{config_path}: model module {module_path!r} must be outside transformer "
                f"layers, but overlaps layer {layer_index} ({block_info.fqn})"
            )

    _raise_incompatible_wrapper(
        current,
        config_path=config_path,
        layer_index=None,
        module_path=module_path,
374
375
376
377
378
379
380
381
382
        layer_index=None,
        module_path=module_path,
        module_fqn=module_path,
    )
    return _ResolvedModelTarget(
        config_path=config_path,
        module_path=module_path,
        module_fqn=module_path,
        parent=parent,
423
424
425
426
427
428
429
430
431
    *,
    config_path: str,
) -> tuple[_ResolvedModelTarget, ...]:
    """Resolve every normalized model-root-relative module target."""
    return tuple(
        _resolve_model_target(
            model,
            blocks,
            module_path=module.module_path,
447
448
449
450
451
452
453
454
455
456
457
458
        by_layer.setdefault(target.layer_index, []).append(target)
    for layer_index, layer_targets in by_layer.items():
        for index, target in enumerate(layer_targets):
            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})"
                    )
459
460
461
462
463
464
465
466
467
468
469
470
471
472


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})"


def _validate_target_aliases(targets: tuple[Any, ...]) -> None:
    """Reject one module object selected through multiple layer/path identities."""
473
474
475
476
477
478
479
480
    by_identity: dict[int, Any] = {}
    for target in targets:
        previous = by_identity.get(id(target.module))
        if previous is not None:
            raise ValueError(
                f"{_target_description(target)} aliases {_target_description(previous)}"
            )
        by_identity[id(target.module)] = target
485
486
487
488
489
490
491
492
493
494
495
496
497
498
    all_targets: tuple[Any, ...],
) -> None:
    """Reject model targets nested with any other activation target."""
    for target in model_targets:
        target_descendants = {id(module) for module in target.module.modules()}
        for other in all_targets:
            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)}"
                )
503
504
505
506
507
508
509
510
    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"
            )
512
513
514
515
516
517
518
519
520
    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}"
        )
521
522
523
524
525
526
527
528
529
    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}"
        )
528
529
530
531
532
533
534
535
536
537
538
539
540
541
            f"layer {layer_index}, module {module_path!r}"
        )

    if plan.mode == "hybrid":
        selective_layers = {
            target.layer_index
            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}"
            )
663
664
665
666
667
668
669
670
671
) -> tuple[_ResolvedTarget, ...]:
    """Resolve model-level selective targets when a selective config is active."""
    if selective_config is None:
        return ()
    return _resolve_model_targets(
        model,
        blocks,
        getattr(selective_config, "recompute_modules", ()),
        config_path="activation_checkpoint.selective.recompute",
684
685
686
687
688
689
690
691
692
            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)
695
696
697
698
699
700
701
702
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")

708
709
710
711
712
713
714
715
716
) -> 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))
730
731
732
733
734
735
736
737
738
def _create_cpu_pool(cpu_pool_mb: Optional[int], *, has_targets: bool) -> Optional[PinnedMemoryPool]:
    """Create one runtime pool only for an active swap target domain."""
    if not has_targets or cpu_pool_mb is None:
        return None
    return PinnedMemoryPool(max_host_bytes=cpu_pool_mb * _MIB)


def _dedupe_modules(modules: list[nn.Module]) -> list[nn.Module]:
    """De-duplicate modules while preserving forward order."""
757
758
759
760
761
762
763
764
765
        _teardown_wired_swap_layers(_dedupe_modules(wired_modules))
        raise
    wired_modules = _dedupe_modules(wired_modules)
    if wired_modules:
        weakref.finalize(model, _teardown_wired_swap_layers, tuple(wired_modules))
    return wired_modules


def _pool_description(cpu_pool_mb: Optional[int], pool: Optional[PinnedMemoryPool]) -> str:
765
766
767
768
769
770
771
772
773
def _pool_description(cpu_pool_mb: Optional[int], pool: Optional[PinnedMemoryPool]) -> str:
    """Format one pool for the activation summary log."""
    if pool is None or cpu_pool_mb is None:
        return "none"
    return f"{cpu_pool_mb} MiB ({pool.max_host_bytes} bytes)"


def _sorted_targets(targets: Sequence[_ResolvedTarget]) -> list[_ResolvedTarget]:
    """Order replacement targets by layer index, then model registration order."""
779
780
781
782
783
784
785
786
787
788
789
    replacements: list[_ReplacementRecord],
) -> None:
    """Wrap full-mode save targets in memory-saving-only wrappers."""
    for target in _sorted_targets(targets):
        wrapped = checkpoint_exclude_wrapper(target.module, swap=False)
        _replace_target(target, wrapped, replacements)
        logger.info(
            "Activation wrapper=CheckpointExcludeWrapper(save) layer=%d layer_fqn=%s "
            "module=%s module_fqn=%s pool=none",
            target.layer_index,
            target.layer_fqn,
841
842
843
844
845
846
847
848
849
850
851
    replacements: list[_ReplacementRecord],
) -> None:
    """Wrap selective-mode layer-relative recompute targets."""
    for target in _sorted_targets(targets):
        wrapped = checkpoint_wrapper(target.module)
        _replace_target(target, wrapped, replacements)
        logger.info(
            "Activation wrapper=CheckpointWrapper(selective) layer=%d layer_fqn=%s "
            "module=%s module_fqn=%s",
            target.layer_index,
            target.layer_fqn,
859
860
861
862
863
864
865
866
867
868
869
    replacements: list[_ReplacementRecord],
) -> None:
    """Wrap selective-mode model-root-relative recompute targets."""
    for target in targets:
        wrapped = checkpoint_wrapper(target.module)
        _replace_target(target, wrapped, replacements)
        logger.info(
            "Activation wrapper=CheckpointWrapper(selective) scope=model "
            "module=%s module_fqn=%s",
            target.module_path,
            target.module_fqn,
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
) -> list[tuple[_ResolvedTarget, nn.Module]]:
    """Wrap selective-mode swap targets, returning the installed wrapper pairs."""
    swap_wrappers: list[tuple[_ResolvedTarget, nn.Module]] = []
    for target in _sorted_targets(targets):
        wrapped = swap_wrapper(
            target.module,
            group_swap=group_swap,
            cpu_pool=cpu_pool,
        )
        _replace_target(target, wrapped, replacements)
        swap_wrappers.append((target, wrapped))
        logger.info(
            "Activation wrapper=SwapWrapper layer=%d layer_fqn=%s module=%s "
            "module_fqn=%s pool=selective",
            target.layer_index,
            target.layer_fqn,
950
951
952
953
954
955
956
957
958
        prefetch_nodes = _collect_prefetch_nodes(plan, full_wrappers, selective_swap_wrappers)
        wired_modules = _wire_prefetch_chain(model, prefetch_nodes)
    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
987
988
989
990
991
992
993
994
995
    """
    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"
        )
    _require_active_mode(activation_checkpoint)
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") and self.full is not None:
455
456
457
458
459
460
461
462
463
            )
        if self.mode in ("full", "hybrid") and self.full is not None:
            self.full.validate_active()
        if self.mode == "hybrid" and self.full is None:
            raise ValueError("activation_checkpoint.mode=hybrid requires activation_checkpoint.full")
        if self.mode in ("selective", "hybrid"):
            if self.selective is None:
                raise ValueError(
                    f"activation_checkpoint.mode={self.mode} requires activation_checkpoint.selective"
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 (