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 24.2% 123,125-131,134,157,159-164,167,169-170,173,191-192,198,200,202-203,223,232-234,238,243-246,251-255,267-270,284-290,294-300,304,308,310-311,318-320,324,345-351,355-360,364,367,369-374,379,386,398-400,412-416,424,435,448,453-459,462,471-472,476,481-485,488,496-503,511-515,520,523-524,529,532-533,539-540,544-546,551-552,556-559,567-571,576-577,584-585,596-598,607-608,610,614-616,618,655-656,661-662,667,672-673,676-678,682,687,689-691,700-702,712-716,721-727,732-736,745-747,750-751,760-762,767-769,774,782-797,802-804,809,817-820,837-838,844-845,860-866,871,879-882,897-900,915-917,922-924,932,941-942,947,951,956,960,964-967,969-971,977-980,986-995,997,1011,1025-1028,1032-1033,1036-1040
hyper_parallel/tools/model_integration/case_matrix.py 9.1% 61,67-68,76-83,97-98,175-177,179-180,191,321
hyper_parallel/tools/model_integration/cli.py 5.3% 572-587,590-596,601-602,630-637,641-643
hyper_parallel/trainer/base.py 0.0% 605
hyper_parallel/trainer/config/parallelism.py 27.5% 73-74,76-88,91-94,101-106,111-117,120,140-145,151,164-165,168-173,176-178,182-184,186,188-189,191-195,197-204,207,211,216-218,223-227,236-240,244,249,262-270,289,293,300,305,325,329-333,337-338,342-345,349-351,357,364-367,388,392,399,403-405,410,417-418,427,431,451-452,456-462,465-468,473-475,482-487
hyper_parallel/trainer/config/resolver.py 0.0% 450,516
hyper_parallel/trainer/config/trainer.py 33.3% 90,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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138


def _is_repeated_block_container(container: nn.Module, children: list[tuple[str, nn.Module]]) -> bool:
    """Return whether one child module structurally represents repeated blocks."""
    if isinstance(container, nn.Sequential):
        # Sequential stems and heads may contain unrelated operations rather than repeated blocks.
        block_types = set()
        for _, child in children:
            wrapped_module = _get_checkpoint_wrapped_module(child)
            block_types.add(type(child if wrapped_module is None else wrapped_module))
        return len(block_types) == 1
    if isinstance(container, (nn.ModuleList, nn.ModuleDict)):
        return bool(children)
    # Ordinary modules may contain same-type stages with different roles, such as an aligner's projections.
    # Repeated blocks must use an explicit collection container so they do not enter layer numbering by accident.
    return False


def _get_checkpoint_wrapped_module(module: nn.Module) -> Optional[nn.Module]:
    """Return a directly wrapped module for discovery de-duplication."""
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
    path is used.
    """
    block_infos = []
    discovered_block_ids = set()
    visited_module_ids = set()

    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():
            container_fqn = f"{owner_fqn}.{container_name}" if owner_fqn else container_name
            children = list(container.named_children())
            if not is_checkpoint_owner or not _is_repeated_block_container(container, children):
                _visit(container_fqn, container)
                continue

            visited_module_ids.add(id(container))
            for block_name, block in children:
                if id(block) in discovered_block_ids:
                    continue
                discovered_block_ids.add(id(block))
187
188
189
190
191
192
193
194
195
196
                        container_fqn=container_fqn,
                    )
                )

    _visit("", model)
    return block_infos, discovered_block_ids


def _find_transformer_layer_container_infos(model: nn.Module) -> list[_LayerContainerInfo]:
    """Group discovered blocks by repeated-block container."""
194
195
196
197
198
199
200
201
202
203
204
205
206
207

def _find_transformer_layer_container_infos(model: nn.Module) -> list[_LayerContainerInfo]:
    """Group discovered blocks by repeated-block container."""
    block_infos, _ = _find_transformer_block_modules(model)
    blocks_by_container: dict[int, list[_TransformerBlockInfo]] = {}
    for block_info in block_infos:
        blocks_by_container.setdefault(id(block_info.parent), []).append(block_info)

    containers = []
    seen_container_ids = set()
    for block_info in block_infos:
        container_id = id(block_info.parent)
        if container_id in seen_container_ids:
            continue
219
220
221
222
223
224
225
226
227
def _flatten_layer_container_infos(
    containers: list[_LayerContainerInfo],
) -> list[_TransformerBlockInfo]:
    """Flatten container metadata into stable global layer numbering."""
    return [block for container in containers for block in container.blocks]


def _resolve_activation_checkpoint_containers(
    model: nn.Module,
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
    *,
    required: bool = True,
) -> 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


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]:
    """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(
    module: nn.Module,
263
264
265
266
267
268
269
270
271
272
273
    module_path: str,
    module_fqn: str,
) -> None:
    """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"
            )
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
    module_path: str,
    config_path: str,
) -> _ResolvedTarget:
    """Resolve one exact relative module path inside a transformer layer."""
    layer = _current_block(block_info)
    current = layer
    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
        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

    module_fqn = f"{block_info.fqn}.{module_path}"
    _raise_incompatible_wrapper(
        current,
        config_path=config_path,
        layer_index=layer_index,
        module_path=module_path,
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
        layer_index=layer_index,
        module_path=module_path,
        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(
        config_path=config_path,
        layer_index=layer_index,
        layer_fqn=block_info.fqn,
        module_path=module_path,
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
376
377
378
379
380
381
382
383
    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,
382
383
384
385
386
387
388
389
390
        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,
394
395
396
397
398
399
400
401
402
403


def _validate_layer_index(layer_index: int, layer_count: int, *, config_path: str) -> None:
    """Validate one normalized layer index against discovered model layers."""
    if layer_index < 0 or layer_index >= layer_count:
        maximum = layer_count - 1
        raise ValueError(
            f"{config_path}: layer {layer_index} is outside the discovered range 0-{maximum}"
        )

408
409
410
411
412
413
414
415
416
417
418
419
420
    *,
    config_path: str,
) -> tuple[_ResolvedTarget, ...]:
    """Resolve every normalized region spec without modifying the model."""
    targets = []
    for region in regions:
        for layer_index in region.layers:
            _validate_layer_index(layer_index, len(blocks), config_path=config_path)
            targets.append(
                _resolve_module_target(
                    blocks[layer_index],
                    layer_index=layer_index,
                    module_path=region.module_path,
420
421
422
423
424
425
426
427
428
                    module_path=region.module_path,
                    config_path=f"{config_path}.{region.module_path}",
                )
            )
    return tuple(targets)


def _resolve_model_targets(
    model: nn.Module,
431
432
433
434
435
436
437
438
439
    *,
    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,
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466


def _target_key(target: _ResolvedTarget) -> tuple[int, str]:
    """Return one layer/path conflict key."""
    return target.layer_index, target.module_path


def _validate_nested_targets(targets: tuple[_ResolvedTarget, ...], *, config_path: str) -> None:
    """Reject ancestor/descendant target pairs within one layer."""
    by_layer: dict[int, list[_ResolvedTarget]] = {}
    for target in targets:
        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})"
                    )
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492


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."""
    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


def _validate_model_target_nesting(
    model_targets: tuple[_ResolvedModelTarget, ...],
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
    model_targets: tuple[_ResolvedModelTarget, ...],
    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)}"
                )
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537


def _validate_resolved_conflicts(plan: _ActivationPlan) -> None:
    """Validate model-level conflicts across all resolved active targets."""
    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"
            )

    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}"
        )
    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}"
        )
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
            "activation_checkpoint.selective recompute/swap conflict on "
            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}"
            )

    _validate_nested_targets(full_targets, config_path="activation_checkpoint.full.exclude_region")
    _validate_nested_targets(
        plan.selective_recompute_targets + plan.selective_swap_targets,
        config_path="activation_checkpoint.selective",
    )
    layer_targets = full_targets + plan.selective_recompute_targets + plan.selective_swap_targets
    all_targets = layer_targets + plan.selective_recompute_model_targets
    _validate_target_aliases(all_targets)
    _validate_model_target_nesting(plan.selective_recompute_model_targets, all_targets)


def _resolve_full_layers(
    blocks: list[_TransformerBlockInfo],
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
    blocks: list[_TransformerBlockInfo],
    full_config: Any,
) -> tuple[tuple[int, _TransformerBlockInfo], ...]:
    """Resolve selected full layers and reject existing wrappers."""
    if full_config is None:
        return ()
    full_layers = []
    for layer_index in full_config.recompute_layers:
        _validate_layer_index(
            layer_index,
            len(blocks),
            config_path="activation_checkpoint.full.recompute_layer",
        )
        block = blocks[layer_index]
        _raise_incompatible_wrapper(
            _current_block(block),
            config_path="activation_checkpoint.full.recompute_layer",
            layer_index=layer_index,
            module_path="<layer>",
580
581
582
583
584
585
586
587
588
589
            layer_index=layer_index,
            module_path="<layer>",
            module_fqn=block.fqn,
        )
        full_layers.append((layer_index, block))
    return tuple(full_layers)


def _resolve_optional_regions(
    blocks: list[_TransformerBlockInfo],
592
593
594
595
596
597
598
599
600
601
602
    *,
    config_path: str,
) -> tuple[_ResolvedTarget, ...]:
    """Resolve one region collection from an optional active config."""
    if config is None:
        return ()
    return _resolve_regions(
        blocks,
        getattr(config, attribute),
        config_path=config_path,
    )
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622


def _resolve_activation_plan(model: nn.Module, config: Any) -> _ActivationPlan:
    """Resolve and validate all active targets before installing any wrapper."""
    mode = _require_active_mode(config)
    full_config, selective_config = _resolve_mode_configs(config, mode)

    containers = _resolve_activation_checkpoint_containers(
        model,
        required=_requires_layer_targets(full_config, selective_config),
    )
    blocks = _flatten_layer_container_infos(containers)
    for layer_index, block in enumerate(blocks):
        logger.info("Activation checkpoint layer index=%d fqn=%s", layer_index, block.fqn)

    plan = _ActivationPlan(
        mode=mode,
        full_layers=_resolve_full_layers(blocks, full_config),
        full_save_targets=_resolve_optional_regions(
            blocks,
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
        full_cpu_pool_mb=getattr(full_config, "cpu_pool_mb", None),
        selective_group_swap=bool(getattr(selective_config, "group_swap", False)),
        selective_cpu_pool_mb=getattr(selective_config, "cpu_pool_mb", None),
    )
    _validate_resolved_conflicts(plan)
    return plan


def _require_active_mode(config: Any) -> str:
    """Return the normalized mode, rejecting missing or inactive values."""
    mode = getattr(config, "mode", None)
    if mode not in _ACTIVE_MODES:
        raise ValueError(
            "activation_checkpoint runtime requires normalized mode full, selective, or hybrid; "
            f"got {mode!r}"
        )
    return mode


def _resolve_mode_configs(config: Any, mode: str) -> tuple[Any, Any]:
    """Select the full and selective sub-configs the active mode requires."""
    full_config = getattr(config, "full", None) if mode in ("full", "hybrid") else None
    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"
        )
    return full_config, selective_config


def _requires_layer_targets(full_config: Any, selective_config: Any) -> bool:
    """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(
    model: nn.Module,
696
697
698
699
700
701
702
703
704
705
706
    blocks: list[_TransformerBlockInfo],
    selective_config: Any,
) -> 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",
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740


def _snapshot_overlap_marks(model: nn.Module) -> tuple[tuple[object, bool, Any], ...]:
    """Capture wrapper overlap marks so a failed apply can restore them."""
    snapshots = []
    seen = set()
    for module in model.modules():
        candidates = [module]
        candidates.extend(
            value
            for value in vars(module).values()
            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)


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


def _replace_target(
    target: Any,
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
    wrapped: nn.Module,
    records: list[_ReplacementRecord],
) -> 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))


def _replace_layer(
    block_info: _TransformerBlockInfo,
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
    wrapped: nn.Module,
    records: list[_ReplacementRecord],
) -> None:
    """Install one full-layer wrapper and record its inverse."""
    current = _current_block(block_info)
    setattr(block_info.parent, block_info.child_name, wrapped)
    records.append(_ReplacementRecord(block_info.parent, block_info.child_name, current))


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."""
    return list(dict.fromkeys(modules))


def _wire_prefetch_chain(
    model: nn.Module,
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
    model: nn.Module,
    nodes: list[tuple[int, int, nn.Module, str]],
) -> list[nn.Module]:
    """Wire all active swap nodes through one ordered SwapManager flow."""
    nodes.sort(key=lambda item: (item[0], item[1]))
    swap_manager = SwapManager()
    wired_modules = []
    try:
        for current, next_node in zip(nodes, nodes[1:]):
            current_module, next_module = current[2], next_node[2]
            wired_modules.extend((current_module, next_module))
            swap_manager.set_forward_prefetch_layer(current_module, next_module)
            logger.info("Activation swap prefetch %s -> %s", current[3], next_node[3])
    except BaseException:
        _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:
    """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."""
    return sorted(targets, key=lambda item: (item.layer_index, item.module_order))


def _install_full_save_wrappers(
    targets: Sequence[_ResolvedTarget],
813
814
815
816
817
818
819
820
821
822
823
824
    targets: Sequence[_ResolvedTarget],
    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,
833
834
835
836
837
838
839
840
841
842
    cpu_pool: Optional[PinnedMemoryPool],
    replacements: list[_ReplacementRecord],
) -> None:
    """Wrap full-mode swap targets in exclusion wrappers backed by the full pool."""
    for target in _sorted_targets(targets):
        wrapped = checkpoint_exclude_wrapper(
            target.module,
            swap=True,
            group_swap=group_swap,
            cpu_pool=cpu_pool,
840
841
842
843
844
845
846
847
848
849
            swap=True,
            group_swap=group_swap,
            cpu_pool=cpu_pool,
        )
        _replace_target(target, wrapped, replacements)
        logger.info(
            "Activation wrapper=CheckpointExcludeWrapper(swap) layer=%d layer_fqn=%s "
            "module=%s module_fqn=%s pool=full",
            target.layer_index,
            target.layer_fqn,
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
    full_layers: Sequence[tuple[int, _TransformerBlockInfo]],
    replacements: list[_ReplacementRecord],
) -> dict[int, nn.Module]:
    """Wrap full-mode transformer blocks, returning wrappers keyed by layer index."""
    full_wrappers: dict[int, nn.Module] = {}
    for layer_index, block_info in full_layers:
        current_layer = _current_block(block_info)
        wrapped = checkpoint_wrapper(current_layer)
        _replace_layer(block_info, wrapped, replacements)
        full_wrappers[layer_index] = wrapped
        logger.info(
            "Activation wrapper=CheckpointWrapper(full) layer=%d layer_fqn=%s",
            layer_index,
            block_info.fqn,
        )
    return full_wrappers


def _install_selective_recompute_wrappers(
    targets: Sequence[_ResolvedTarget],
875
876
877
878
879
880
881
882
883
884
885
886
    targets: Sequence[_ResolvedTarget],
    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,
893
894
895
896
897
898
899
900
901
902
903
904
    targets: Sequence[_ResolvedModelTarget],
    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,
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
    cpu_pool: Optional[PinnedMemoryPool],
    replacements: list[_ReplacementRecord],
) -> 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,
928
929
930
931
932
933
934
935
936
            target.layer_fqn,
            target.module_path,
            target.module_fqn,
        )
    return swap_wrappers


def _collect_prefetch_nodes(
    plan: _ActivationPlan,
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
    full_wrappers: dict[int, nn.Module],
    selective_swap_wrappers: Sequence[tuple[_ResolvedTarget, nn.Module]],
) -> list[tuple[int, int, nn.Module, str]]:
    """Collect every swap node in layer order for one prefetch chain."""
    full_swap_layers = {target.layer_index for target in plan.full_swap_targets}
    prefetch_nodes = [
        (layer_index, -1, full_wrappers[layer_index], block_info.fqn)
        for layer_index, block_info in plan.full_layers
        if layer_index in full_swap_layers
    ]
    prefetch_nodes.extend(
        (target.layer_index, target.module_order, wrapper, target.module_fqn)
        for target, wrapper in selective_swap_wrappers
    )
    return prefetch_nodes


def _apply_activation_plan(model: nn.Module, plan: _ActivationPlan) -> nn.Module:
    """Create resources, install wrappers, and register one prefetch chain."""
    full_pool = _create_cpu_pool(
        plan.full_cpu_pool_mb,
        has_targets=bool(plan.full_swap_targets),
    )
    selective_pool = _create_cpu_pool(
        plan.selective_cpu_pool_mb,
        has_targets=bool(plan.selective_swap_targets),
    )
    resources = _ActivationCheckpointRuntimeResources(full_pool, selective_pool)
    overlap_marks = _snapshot_overlap_marks(model)
    replacements: list[_ReplacementRecord] = []
    wired_modules: list[nn.Module] = []

    try:
        _install_full_save_wrappers(plan.full_save_targets, replacements)
        _install_full_swap_wrappers(
            plan.full_swap_targets,
            plan.full_group_swap,
            full_pool,
            replacements,
973
974
975
976
977
978
979
980
981
982
983
984
            plan.full_group_swap,
            full_pool,
            replacements,
        )
        full_wrappers = _install_full_layer_wrappers(plan.full_layers, replacements)
        _install_selective_recompute_wrappers(plan.selective_recompute_targets, replacements)
        _install_selective_model_wrappers(plan.selective_recompute_model_targets, replacements)
        selective_swap_wrappers = _install_selective_swap_wrappers(
            plan.selective_swap_targets,
            plan.selective_group_swap,
            selective_pool,
            replacements,
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
            plan.selective_group_swap,
            selective_pool,
            replacements,
        )
        prefetch_nodes = _collect_prefetch_nodes(plan, full_wrappers, selective_swap_wrappers)
        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

    logger.info(
        "Activation checkpoint mode=%s: full_layers=%s, full_save_regions=%d, "
        "full_swap_regions=%d, full_pool=%s; selective_recompute_regions=%d, "
        "selective_recompute_modules=%d, selective_swap_regions=%d, selective_pool=%s",
        plan.mode,
1007
1008
1009
1010
1011
1012
1013
1014
1015
        len(plan.selective_recompute_model_targets),
        len(plan.selective_swap_targets),
        _pool_description(plan.selective_cpu_pool_mb, selective_pool),
    )
    return model


def _apply_activation_checkpointing(
    model: nn.Module,
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
    ``None`` and ``mode=off`` are no-ops. Active modes are incompatible with
    compile and must use the replacement schema object; legacy string modes
    and selection/swap-input arguments are intentionally unsupported.
    """
    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:
        raise ValueError(
            "activation_checkpoint modes full, selective, and hybrid are not supported with torch.compile"
        )
    plan = _resolve_activation_plan(model, activation_checkpoint)
    disable_native_checkpointing = getattr(model, "gradient_checkpointing_disable", None)
    if callable(disable_native_checkpointing):
        disable_native_checkpointing()
    return _apply_activation_plan(model, plan)


__all__ = [
    "_apply_activation_checkpointing",
hyper_parallel/tools/model_integration/case_matrix.py
57
58
59
60
61
62
63
64
65


def _case_name(topology: Mapping[str, Any], prefix: str = "") -> str:
    """Build a stable case name from the topology fields present."""
    ordered = (*_PARALLEL_TOPOLOGY_FIELDS, "recompute_layer")
    pieces = []
    for name in ordered:
        if name not in topology:
            continue
63
64
65
66
67
68
69
70
71
    for name in ordered:
        if name not in topology:
            continue
        value = topology[name]
        if name == "recompute_layer":
            value = "off" if not value else "layers" + "-".join(str(index) for index in value)
        pieces.append(f"{name}{value}")
    name = "_".join(str(piece).replace("/", "-") for piece in pieces)
    return f"{prefix}_{name}" if prefix else name
72
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."""
 93
 94
 95
 96
 97
 98
 99
100
101
102
        supported = ", ".join(_TOPOLOGY_DEFAULTS)
        raise ValueError(
            f"{path} contains unsupported fields {unsupported}; supported fields: {supported}"
        )
    if "recompute_layer" in resolved:
        resolved["recompute_layer"] = _validate_recompute_layers(
            resolved["recompute_layer"],
            f"{path}.recompute_layer",
        )
    return resolved
171
172
173
174
175
176
177
178
179
180
181
182
183
184
        baseline: Mapping[str, Any],
        seen: set[str],
) -> 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,
            f"matrix.recompute_layers[{index}]",
        )
        topology = dict(baseline)
187
188
189
190
191
192
193
194
195
                matrix.get("recompute_topology") or {},
                "matrix.recompute_topology",
            )
        )
        topology["recompute_layer"] = recompute_layers
        key = json.dumps(topology, sort_keys=True)
        if key in seen:
            continue
        seen.add(key)
317
318
319
320
321
322
323
324
325
    cases = [ValidationCase("baseline", baseline, compare_to="baseline")]
    seen = {json.dumps(baseline, sort_keys=True)}
    cases.extend(_axis_cases(matrix, baseline, seen))
    cases.extend(_combined_cases(matrix, baseline, seen))
    if matrix.get("recompute_layers"):
        cases.extend(_recompute_cases(matrix, baseline, seen))
    ep1_case = _ep1_fallback_case(cases, baseline)
    if ep1_case is not None:
        cases.insert(1, ep1_case)
hyper_parallel/tools/model_integration/cli.py
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
    raw_exclude_region: Any,
    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 {}
        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:
                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
        result[section] = targets
    return result


def _trainer_launch_argv(
    manifest: ValidationManifest,
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
        "--module",
        module,
        str(config),
    ]
    activation_checkpoint = {"mode": "off"}
    if topology.get("recompute_layer"):
        full_config: dict[str, Any] = {"recompute_layer": topology["recompute_layer"]}
        recipe = yaml.safe_load(config.read_text(encoding="utf-8")) or {}
        recipe_activation = recipe.get("activation_checkpoint") or {}
        recipe_full = recipe_activation.get("full") or {}
        if "exclude_region" in recipe_full:
            exclude_region = _active_full_exclude_region(
                recipe_full["exclude_region"],
                topology["recompute_layer"],
            )
            if exclude_region:
                full_config["exclude_region"] = exclude_region
        activation_checkpoint = {"mode": "full", "full": full_config}
    controlled_overrides = {
        "training.train_iters": _phase_train_iters(phase, steps, split_step),
        # Split-run preparation stops early but must retain the full-run LR
        # curve so its checkpoint is numerically comparable with the baseline.
hyper_parallel/trainer/base.py
601
602
603
604
605
606
607
608
609
        """Build the optional joint-graph compiler for this trainer runtime."""
        if not self.config.compile.selects_graph_compiler():
            return
        # Keep eager trainers independent of the graph compiler and its pass import tree.
        from hyper_parallel.compile.compiler import GraphCompiler  # pylint: disable=C0415

        self.graph_compiler = GraphCompiler(
            model=self.model,
            train_fn=self._graph_train_fn,
hyper_parallel/trainer/config/parallelism.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98


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:
        if isinstance(item, bool):
            raise ValueError(f"{path} must not contain boolean layer values")
        if isinstance(item, int):
            if item < 0:
                raise ValueError(f"{path} must not contain negative layer index {item}")
            expanded = (item,)
        elif isinstance(item, str):
            match = _LAYER_RANGE_PATTERN.fullmatch(item)
            if match is None:
                raise ValueError(
                    f"{path} contains invalid layer range {item!r}; expected forms such as '0-3'"
                )
            start, end = (int(group) for group in match.groups())
            if start > end:
                raise ValueError(f"{path} contains reversed layer range {item!r}")
            expanded = tuple(range(start, end + 1))
        else:
            raise ValueError(
                f"{path} must contain only non-negative integers or closed ranges, "
                f"got {type(item).__name__}"
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
                f"{path} must contain only non-negative integers or closed ranges, "
                f"got {type(item).__name__}"
            )

        for layer_index in expanded:
            if layer_index in seen:
                raise ValueError(f"{path} contains duplicate layer index {layer_index}")
            seen.add(layer_index)
            layers.append(layer_index)
    return tuple(sorted(layers))


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


@dataclass(frozen=True)
class ModuleRegionSpec:
136
137
138
139
140
141
142
143
144
145
146
147
148
149


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(
            ModuleRegionSpec(
                module_path=module_path,
                layers=_normalize_layer_set(raw_layers, path=f"{path}.{module_path}"),
            )
147
148
149
150
151
152
153
154
155
                module_path=module_path,
                layers=_normalize_layer_set(raw_layers, path=f"{path}.{module_path}"),
            )
        )
    return tuple(regions)


def _normalize_recompute_targets(
    value: object,
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
    tuple[ModuleRegionSpec, ...],
    tuple[ModelModuleSpec, ...],
]:
    """Normalize selective recompute layer regions and model-level modules."""
    if isinstance(value, Mapping):
        targets: list[Union[ModuleRegionSpec, ModelModuleSpec]] = list(
            _normalize_region_mapping(value, path=path)
        )
    elif isinstance(value, (list, tuple)):
        targets = []
        for index, item in enumerate(value):
            item_path = f"{path}[{index}]"
            if isinstance(item, str):
                targets.append(
                    ModelModuleSpec(_validate_module_path(item, path=item_path))
                )
                continue
            if not isinstance(item, Mapping):
                raise ValueError(
                    f"{item_path} must be a model module path string or a single-entry "
                    "mapping from a layer-relative module path to a layer set"
                )
            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))

    region_paths = set()
    for region in regions:
        if region.module_path in region_paths:
            raise ValueError(f"{path} contains duplicate layer-relative module path {region.module_path!r}")
        region_paths.add(region.module_path)

    module_paths = set()
    for module in modules:
        if module.module_path in module_paths:
            raise ValueError(f"{path} contains duplicate model module path {module.module_path!r}")
        module_paths.add(module.module_path)
    for index, module in enumerate(modules):
        for other in modules[index + 1:]:
            if module.module_path.startswith(f"{other.module_path}.") or other.module_path.startswith(
                f"{module.module_path}."
            ):
                raise ValueError(
                    f"{path} has nested model targets {module.module_path!r} and "
                    f"{other.module_path!r}"
                )
    return tuple(targets), regions, modules


def _normalize_group_swap(value: object, *, path: str) -> bool:
    """Normalize one optional group-swap flag."""
    if not isinstance(value, bool):
        raise ValueError(f"{path} must be a bool")
    return value


def _normalize_cpu_pool(value: object, *, path: str) -> Optional[int]:
    """Normalize one optional pinned-memory-pool capacity in MiB."""
    if value is None:
        return None
    if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
        raise ValueError(f"{path} must be a positive integer MiB value or null")
    return value


def _split_swap_mapping(
    value: object,
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
    *,
    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},
        path=path,
    )
    return regions, group_swap, cpu_pool_mb


def _region_layer_pairs(regions: tuple[ModuleRegionSpec, ...]) -> set[tuple[int, str]]:
    """Expand region specs into layer/path conflict keys."""
    return {
        (layer_index, region.module_path)
        for region in regions
        for layer_index in region.layers
    }
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
    *,
    path: str,
) -> None:
    """Reject ancestor/descendant activation targets within one layer."""
    by_layer: dict[int, list[str]] = {}
    for region in regions:
        for layer_index in region.layers:
            by_layer.setdefault(layer_index, []).append(region.module_path)
    for layer_index, module_paths in by_layer.items():
        for index, module_path in enumerate(module_paths):
            for other_path in module_paths[index + 1:]:
                if module_path.startswith(f"{other_path}.") or other_path.startswith(f"{module_path}."):
                    raise ValueError(
                        f"{path} has nested targets on layer {layer_index}: "
                        f"{module_path!r} and {other_path!r}"
                    )
285
286
287
288
289
290
291
292
293
294
295
296
    cpu_pool_mb: Optional[int] = field(init=False)

    def __post_init__(self) -> None:
        """Normalize save and swap mappings."""
        self.save_regions = _normalize_region_mapping(
            self.save,
            path="activation_checkpoint.full.exclude_region.save",
        )
        self.swap_regions, self.group_swap, self.cpu_pool_mb = _split_swap_mapping(
            self.swap,
            path="activation_checkpoint.full.exclude_region.swap",
        )
296
297
298
299
300
301
302
303
304
305
306
307
308
        )

    def to_dict(self) -> dict[str, Any]:
        """Serialize the normalized exclusion configuration."""
        swap = {
            "group_swap": self.group_swap,
            "cpu_pool": self.cpu_pool_mb,
            **{region.module_path: list(region.layers) for region in self.swap_regions},
        }
        return {
            "save": {region.module_path: list(region.layers) for region in self.save_regions},
            "swap": swap,
        }
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
    cpu_pool_mb: Optional[int] = field(init=False)

    def __post_init__(self) -> None:
        """Normalize full-layer coverage and exclusion settings."""
        self.recompute_layers = _normalize_layer_set(
            self.recompute_layer,
            path="activation_checkpoint.full.recompute_layer",
        )
        exclude_region = self.exclude_region or FullExcludeRegionConfig()
        self.save_regions = exclude_region.save_regions
        self.swap_regions = exclude_region.swap_regions
        self.group_swap = exclude_region.group_swap
        self.cpu_pool_mb = exclude_region.cpu_pool_mb

    def validate_active(self) -> None:
        """Validate conflicts that matter when full mode is active."""
        recompute_layers = set(self.recompute_layers)
        for config_path, regions in (
            ("activation_checkpoint.full.exclude_region.save", self.save_regions),
            ("activation_checkpoint.full.exclude_region.swap", self.swap_regions),
        ):
            for region in regions:
                outside = sorted(set(region.layers) - recompute_layers)
                if outside:
                    raise ValueError(
                        f"{config_path}.{region.module_path} selects layer(s) {outside} outside "
                        "activation_checkpoint.full.recompute_layer"
                    )
        conflicts = _region_layer_pairs(self.save_regions) & _region_layer_pairs(self.swap_regions)
        if conflicts:
            layer_index, module_path = sorted(conflicts)[0]
            raise ValueError(
                "activation_checkpoint.full.exclude_region.save and "
                "activation_checkpoint.full.exclude_region.swap conflict on "
                f"layer {layer_index}, module {module_path!r}"
353
354
355
356
357
358
359
360
                "activation_checkpoint.full.exclude_region.save and "
                "activation_checkpoint.full.exclude_region.swap conflict on "
                f"layer {layer_index}, module {module_path!r}"
            )
        _validate_nested_regions(
            self.save_regions + self.swap_regions,
            path="activation_checkpoint.full.exclude_region",
        )
360
361
362
363
364
365
366
367
368
369
370
371
        )

    def to_dict(self) -> dict[str, Any]:
        """Serialize the normalized full configuration."""
        result = {"recompute_layer": list(self.recompute_layers)}
        if self.exclude_region is not None:
            result["exclude_region"] = self.exclude_region.to_dict()
        return result


@dataclass
class SelectiveCheckpointConfig:
384
385
386
387
388
389
390
391
392
393
394
395
    cpu_pool_mb: Optional[int] = field(init=False)

    def __post_init__(self) -> None:
        """Normalize exact selective targets and swap options."""
        self.recompute_targets, self.recompute_regions, self.recompute_modules = _normalize_recompute_targets(
            self.recompute,
            path="activation_checkpoint.selective.recompute",
        )
        self.swap_regions, self.group_swap, self.cpu_pool_mb = _split_swap_mapping(
            self.swap,
            path="activation_checkpoint.selective.swap",
        )
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
        )

    def validate_active(self) -> None:
        """Validate active selective coverage and target conflicts."""
        if not self.recompute_regions and not self.recompute_modules and not self.swap_regions:
            raise ValueError(
                "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}"
            )
        _validate_nested_regions(
            self.recompute_regions + self.swap_regions,
            path="activation_checkpoint.selective",
        )
413
414
415
416
417
418
419
420
421
422
        )

    def to_dict(self) -> dict[str, Any]:
        """Serialize the normalized selective configuration."""
        if self.recompute_modules:
            recompute: Union[dict[str, Any], list[Union[str, dict[str, Any]]]] = [
                (
                    {target.module_path: list(target.layers)}
                    if isinstance(target, ModuleRegionSpec)
                    else target.module_path
423
424
425
426
427
428
429
430
431
432
433
434
435
                )
                for target in self.recompute_targets
            ]
        else:
            recompute = {
                region.module_path: list(region.layers)
                for region in self.recompute_regions
            }
        return {
            "recompute": recompute,
            "swap": {
                "group_swap": self.group_swap,
                "cpu_pool": self.cpu_pool_mb,
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
    selective: Optional[SelectiveCheckpointConfig] = None

    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"):
            if self.full is None:
                raise ValueError(f"activation_checkpoint.mode={self.mode} requires activation_checkpoint.full")
            self.full.validate_active()
        if self.mode in ("selective", "hybrid"):
            if self.selective is None:
                raise ValueError(
                    f"activation_checkpoint.mode={self.mode} requires activation_checkpoint.selective"
                )
            self.selective.validate_active()
        if self.mode == "hybrid":
            full_layers = set(self.full.recompute_layers)
            selective_layers = {
                layer_index
                for region in self.selective.recompute_regions + self.selective.swap_regions
                for layer_index in region.layers
            }
            overlap = sorted(full_layers & selective_layers)
            if overlap:
                raise ValueError(
                    "activation_checkpoint.mode=hybrid requires disjoint full and selective layers; "
                    f"overlap={overlap}"
                )
478
479
480
481
482
483
484
485
486
487
488
489
490
491
                )

    def to_dict(self) -> dict[str, Any]:
        """Serialize the normalized activation-checkpoint configuration."""
        result: dict[str, Any] = {"mode": self.mode}
        if self.full is not None:
            result["full"] = self.full.to_dict()
        if self.selective is not None:
            result["selective"] = self.selective.to_dict()
        return result


def _resolve_replace_implementation(value: Union[str, Target[Any]]) -> Target[Any]:
    """Resolve a replacement implementation without invoking its callable."""
hyper_parallel/trainer/config/resolver.py
446
447
448
449
450
451
452
453
454
        raise ConfigResolutionError(
            location, f"value of type {type(config).__name__} has no configurable fields"
        )

    config_fields = {field.name: field for field in fields(config) if field.init}
    name = parts[0]
    if name not in config_fields:
        target = getattr(config, "target", None)
        if isinstance(target, Target):
512
513
514
515
516
517
518
519
    """Resolve YAML fields and construct a configuration dataclass."""
    if not isinstance(node, Mapping):
        raise ConfigResolutionError(path, "configuration section must be a YAML mapping")

    config_fields = {field.name: field for field in fields(config_type) if field.init}
    unknown = sorted(set(node) - set(config_fields))
    if unknown:
        raise ConfigResolutionError(path, f"unknown configuration fields: {unknown}")
hyper_parallel/trainer/config/trainer.py
86
87
88
89
90
91
92
93
94
95
96
97
98
99
    peft: Optional[Any] = None

    def __post_init__(self) -> None:
        """Validate combinations that span multiple config sections."""
        if (
            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 (