Diff Coverage

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

Source File Diff Coverage (%) Missing Lines
hyper_parallel/codegen/astkit/edits.py 0.0% 113-114
hyper_parallel/codegen/build.py 0.0% 61,63
hyper_parallel/codegen/emit/modeling.py 12.1% 359,493-495,497,513,516,539-545,584-589,593-601,604,609-610,616,618,623-630,636-660,757-759,899-908
hyper_parallel/codegen/emit/parallel.py 10.3% 90,113-114,127,540-551,553-554,559-568,570-572,612,690-692
hyper_parallel/codegen/emit/patches.py 100%  
hyper_parallel/codegen/emit/replacement.py 0.0% 69-70
hyper_parallel/codegen/emit/snapshot_patches.py 0.0% 174,181
hyper_parallel/codegen/inline/attention.py 12.5% 187-188,192,249-252
hyper_parallel/codegen/inline/component_source.py 13.9% 45-50,52-54,56,58,63-71,81-104,109,118-128,143-153,156-160,163-164,166-173,179-182,187-190,192,197,199-200,202,206,211-212,215,220-225,230-246,251-264,269-273,275-276
hyper_parallel/codegen/inline/declaration_edits.py 8.8% 36-37,39,48,61-75,80-90,101
hyper_parallel/codegen/inline/forward_edits.py 8.6% 45-47,62-77,111,113-114,116-125
hyper_parallel/codegen/inline/framework_spec.py 21.4% 455,458,467,486,489-491,517-530,532-536,545-550,556-564,569-570,573
hyper_parallel/codegen/inline/ir.py 100%  
hyper_parallel/codegen/inline/meta_plan.py 50.0% 29
hyper_parallel/codegen/inline/patch_engine.py 9.2% 51,194-196,203-217,222-231,236-238,240-241,243,245,337-341,343,359-383,388-396,401,406-410,413-416,421-427,431-432,437-438,442-445,447-448,459-460,481-487,489,491-496,498,503-505,507,512-515
hyper_parallel/codegen/inline/pipeline.py 11.6% 73-75,87,188-189,191-194,196-199,213-222,227-228,231-232,234-238,268-269,274,383-384
hyper_parallel/codegen/inline/recognition.py 12.5% 225-226,228,231-234,245,247,253,255,260,274-281,286-290,297,299-303,305-306,311-313,319,325-331,336-344,349-352,354-355,360-374,381-388,391-402,444,453-466,471,474-475,478,480-484,491-497,499,501-502,504,506-525,527-529,534,540-547,552-564,633-639,644,680-686,693-700,727,731-732,737,741-742
hyper_parallel/codegen/inline/replacement_pass.py 14.3% 67-68,73,78-81,98,134-141,147-148
hyper_parallel/codegen/inline/source_plan.py 100%  
hyper_parallel/codegen/inline/strategy_pass.py 12.5% 60-61,63-74,91,97-98,100,128-129,135
hyper_parallel/codegen/model_build_overlay.py 12.5% 154-157,167-169,174,178-179,339,349-350,352-354,378,380,382-383,390-395,397-398
hyper_parallel/codegen/plan/observation.py 12.5% 157-166,168-170,172
hyper_parallel/codegen/session.py 14.3% 48,111-121
hyper_parallel/codegen/astkit/edits.py
109
110
111
112
113
114
115
116
117
118
        for line in new_body.splitlines(keepends=True)
    ]
    replacement = "".join(body_lines)
    # Composed source can place the next class directly after the consumed newline.
    if not replacement.endswith("\n") and source_text[func.body_end:func.body_end + 1] not in ("", "\n", "\r"):
        replacement += "\n"
    return (TextEdit(func.body_start, func.body_end, replacement),)


def insert_after_imports(
hyper_parallel/codegen/build.py
57
58
59
60
61
62
63
64
65
66
67
    distributed_setup = create_offline_distributed_setup(config)
    normalize_distributed_setup_overrides(distributed_setup, config)

    session = CodegenBuildSession()
    with use_codegen_model_build_overlay(session, artifact_dir, defer_publish=True) as result, \
            use_codegen_planner_overlay():
        result.model = config.model.build(
            distributed_setup=distributed_setup,
            peft_config=config.peft,
            activation_checkpoint=config.activation_checkpoint.mode,
            activation_checkpoint_selection=config.activation_checkpoint.selection,
hyper_parallel/codegen/emit/modeling.py
355
356
357
358
359
360
361
362
363
            None if getattr(emission_meta, "nested_components", None) else source_path
        ),
    )
    text = _lower_forward_boundaries(text, emission_meta, module_name)
    text = collapse_unmodified_components(text)
    _verify_recorded_patch_materialization(
        text, emission_meta, patch_plan=patch_plan
    )
    return _banner(meta) + text
489
490
491
492
493
494
495
496
497
498
499
500
501
    missing = []
    for record in records:
        constructor = getattr(record, "factory", None) or record.replacement_type
        name = constructor.__name__
        if name not in bound_names:
            name = record.replacement_type.__name__
        calls = [node for node in ast.walk(tree)
                 if isinstance(node, ast.Call) and _call_name(node.func) == name]
        visible = name in bound_names and bool(calls) and _replacement_calls_cover_fqn(calls, record.module_fqn)
        if visible:
            _record_materialized(
                materialized,
                record.module_fqn,
509
510
511
512
513
514
515
516
517
518
519
520


def _replacement_calls_cover_fqn(calls: list[ast.Call], fqn: str) -> bool:
    """Require exact coverage when emitted constructors name their observed paths."""
    explicit = {keyword.value.value for call in calls for keyword in call.keywords
                if keyword.arg == "module_fqn" and isinstance(keyword.value, ast.Constant)
                and isinstance(keyword.value.value, str) and keyword.value.value}
    return not explicit or fqn in explicit


def _wrapper_identity(record: Any) -> tuple[Any, str, str]:
    """Return target type, host name, and target FQN for a wrapper record."""
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
def _wrapper_source_form(
    classes: dict[str, ast.ClassDef], host: ast.ClassDef, record: Any, replacements: Any
) -> str | None:
    """Return the concrete source form that materializes a wrapper."""
    definition = getattr(record, "observed_definition", None)
    if definition is not None:
        return _observed_method_form(host, definition, getattr(record, "target_type", None))
    source_form = _declared_wrapper_form(host, record)
    if source_form is None or source_form == "observed_native_methods":
        return source_form
    return _wrapper_class_form(classes, host, record, replacements)


def _wrapper_class_form(
    classes: dict[str, ast.ClassDef], host: ast.ClassDef, record: Any, replacements: Any
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
607
608
609
610
611
612
613
614


def _declared_wrapper_form(host: ast.ClassDef, record: Any) -> str | None:
    """Require computation from the selected wrapper, not an unrelated CP flag."""
    wrapper = getattr(record, "wrapper", None)
    if wrapper is None:
        return "structural"
    arguments = getattr(record, "factory_kwargs", {})
    try:
        spec = strategy_spec_for(
            projected_target_path(wrapper), inner_wrapper=True,
            construction_kwargs=tuple(f"{name}={value!r}" for name, value in sorted(arguments.items())),
        )
    except RuntimeError:
        return None
    if spec is None or spec.subclass_shell is None:
        return None
    if spec.definition is not None:
        return _observed_method_form(host, spec.definition, getattr(record, "target_type", None))
    expected = _wrapper_helper_calls(spec)
    actual = _forward_calls(host)
    visible = bool(expected) and all(
        any(_native_call_visible(call, candidate) for candidate in actual) for call in expected
    )
    return "native_helper_calls" if visible else None


def _wrapper_helper_calls(spec: Any) -> list[ast.Call]:
    """Read imported computation calls from the selected native wrapper body."""
    imports = {name for item in spec.imports for name in item.names}
    return [node for node in ast.walk(ast.parse(spec.subclass_shell)) if isinstance(node, ast.Call)
            and isinstance(node.func, ast.Name) and node.func.id in imports]


def _forward_calls(host: ast.ClassDef) -> list[ast.Call]:
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634


def _forward_calls(host: ast.ClassDef) -> list[ast.Call]:
    """Collect calls from the emitted dispatch and preserved local computation."""
    methods = [node for node in host.body if isinstance(node, ast.FunctionDef)
               and node.name in {"forward", "_forward_impl"}]
    return [node for method in methods for node in ast.walk(method) if isinstance(node, ast.Call)]


def _native_call_visible(expected: ast.Call, actual: ast.Call) -> bool:
    """Match a native helper and its explicit literal configuration arguments."""
    if ast.dump(expected.func) != ast.dump(actual.func):
        return False
    for index, argument in enumerate(expected.args):
        if isinstance(argument, ast.Constant) or isinstance(argument, ast.Name) and argument.id == "self":
            if index >= len(actual.args) or ast.dump(argument) != ast.dump(actual.args[index]):
                return False
    keywords = {item.arg: item.value for item in actual.keywords}
    return all(item.arg in keywords and ast.dump(item.value) == ast.dump(keywords[item.arg])
               for item in expected.keywords if isinstance(item.value, ast.Constant))


def _observed_method_form(host: ast.ClassDef, definition: str, native_type: type | None) -> str | None:
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664


def _observed_method_form(host: ast.ClassDef, definition: str, native_type: type | None) -> str | None:
    """Verify each observed computation, allowing only the existing boundary extraction."""
    native_base = f"{native_type.__module__}.{native_type.__name__}" if native_type is not None else ""
    if any(ast.unparse(base) == native_base for base in host.bases):
        definition = _imported_forward_definition(definition)
    methods = {node.name: node for node in host.body if isinstance(node, ast.FunctionDef)}
    for expected in ast.parse(definition).body:
        if not isinstance(expected, ast.FunctionDef):
            return None
        if ast.get_docstring(expected) is not None:
            expected.body[0].value.value = ast.get_docstring(expected)
        candidates = [methods.get(expected.name)]
        if expected.name == "forward":
            candidates.append(methods.get("_forward_impl"))
        matched = False
        for candidate in candidates:
            if candidate is None:
                continue
            candidate = ast.parse(ast.unparse(candidate)).body[0]
            candidate.name = expected.name
            if ast.get_docstring(candidate) is not None:
                candidate.body[0].value.value = ast.get_docstring(candidate)
            if ast.dump(candidate) == ast.dump(expected):
                matched = True
        if not matched:
            return None
    return "observed_native_methods"


def _verify_wrapper_records(
    classes: dict[str, ast.ClassDef], records: Any, replacements: Any, materialized: Any
753
754
755
756
757
758
759
760
761
762
763

def _tree_has_wrapper_record(tree: ast.AST, record: Any, replacements: Any) -> bool:
    """Return whether one source tree materializes an inner-wrapper record."""
    _, class_name, _ = _wrapper_identity(record)
    classes = _class_index(tree)
    host = classes.get(class_name)
    return host is not None and _wrapper_source_form(classes, host, record, replacements) is not None


def _class_dispatch_reads_state(host: ast.ClassDef, state_name: str) -> bool:
    """Return whether a class dispatches on one state flag in either layer."""
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
        "# Regenerate this file from the training YAML after strategy changes.",
        "#",
        "",
    ]
    for record in getattr(meta, "module_overrides", None) or ():
        source_type = (record.get("module_type") or "unknown").rsplit(".", 1)[-1]
        implementation = (record.get("construction") or {}).get("implementation")
        target = (implementation or record.get("factory") or record.get("replacement_target") or "unknown")
        target = target.replace(":", ".", 1).rsplit(".", 1)[-1]
        for fqn in record.get("fqns") or (record.get("fqn"),):
            if fqn is not None:
                lines.insert(-1, f"#   {fqn}: {source_type} -> {target}")
    if getattr(meta, "module_overrides", None):
        lines.insert(-1, "#")
    return "\n".join(lines)


def _source_dict(source: Any) -> dict[str, Any]:
hyper_parallel/codegen/emit/parallel.py
86
87
88
89
90
91
92
93
94
    """
    if _plan_field(frozen_plan, "status") == "not_required":
        raise ValueError("codegen emit: not_required snapshot has no parallel boundaries")
    edits: list[TextEdit] = []
    index = build_source_index(source_text)
    for class_name, form, emitted, func, injection, deferred_bias in iter_emitted_forms(
        source_text,
        frozen_plan,
        boundary_classes=boundary_classes,
109
110
111
112
113
114
115
116
117
118
                    "prunes to identity but declares deferred bias params; an "
                    "identity forward has no exit hook to re-add them"
                )
            continue
        host = index.find_class(class_name)
        dispatch = (_cp_dispatch_call(source_text[func.body_start:func.body_end])
                    if "_forward_impl" in host.methods else None)
        body = _build_forward_body(
            source_text, injection, func, form, emitted, deferred_bias,
            inner_compute=ast.unparse(dispatch) if dispatch is not None else None,
123
124
125
126
127
128
129
130
131
        # body at ``body_start`` — the two spans never overlap, so the
        # incremental-shift validation in ``_apply_edits`` passes.  The static
        # form additionally prefixes the class marker naming the form.
        marker = _TP_FORM_MARKER_LINE if emitted == FORM_TP_COLLECTIVE else None
        impl = None if dispatch is not None else _build_forward_impl_edit(source_text, func, prefix=marker)
        if impl is not None:
            edits.append(impl)
        edits.extend(replace_function_body(source_text, func, body, indent=""))
    if not edits:
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
564
565
566
567
568
569
570
571
572
573
574
575
576


def _cp_dispatch_pair(source_body: str) -> Optional[tuple[ast.Call, ast.Call]]:
    """Recognize the CP branch and local fallback with Python 3.9-compatible AST checks."""
    body = ast.parse(textwrap.dedent(source_body)).body
    if len(body) != 2 or not isinstance(body[0], ast.If) or not isinstance(body[1], ast.Return):
        return None
    branch, fallback = body
    if branch.orelse or len(branch.body) != 1 or not isinstance(branch.body[0], ast.Return):
        return None
    if ast.dump(branch.test) != ast.dump(ast.parse("self.cp_enable", mode="eval").body):
        return None
    call, original = branch.body[0].value, fallback.value
    if not isinstance(call, ast.Call) or not isinstance(original, ast.Call) or not call.args:
        return None
    if (ast.dump(call.args[0]) != ast.dump(ast.Name(id="self", ctx=ast.Load()))
            or ast.dump(original.func) != ast.dump(ast.parse("self._forward_impl", mode="eval").body)):
        return None
    return call, original


def _cp_dispatch_call(source_body: str) -> Optional[ast.Call]:
    """Recognize our passthrough CP shell and bind it to redistributed arguments."""
    pair = _cp_dispatch_pair(source_body)
    if pair is None:
        return None
    call, original = pair
    if [ast.dump(arg) for arg in call.args[1:]] != [ast.dump(arg) for arg in original.args]:
        return None
    originals = {ast.dump(keyword) for keyword in original.keywords}
    if not originals <= {ast.dump(keyword) for keyword in call.keywords}:
        return None
    call.args = [ast.Name(id="self", ctx=ast.Load()),
                 ast.Starred(value=ast.Name(id="args", ctx=ast.Load()), ctx=ast.Load())]
    call.keywords = [keyword for keyword in call.keywords if ast.dump(keyword) not in originals]
    call.keywords.append(ast.keyword(arg=None, value=ast.Name(id="kwargs", ctx=ast.Load())))
    return ast.fix_missing_locations(call)


def _build_forward_body(
    source_text: str,
608
609
610
611
612
613
614
615
616
            "can install the trainer's native Phase C wrapper"
        )
    # Keep source-visible CP dispatch inside the boundary and outside the
    # preserved local implementation that its helper may call back into.
    return _render_plain_redistribute(input_redist, out_redist, form, inner_compute)


def _render_input_redistribute(func: FunctionInfo) -> str:
    """Render the input-side redistribute call on the compiled boundary plan.
686
687
688
689
690
691
692
693
694
695
696
    ``==> dtensor redistribute`` for transitions the compiled plan's DTensor
    fallback owns), so a reader sees what the boundary communicates without
    re-deriving the plan.
    """
    compute = "        outputs = self._forward_impl(*args, **kwargs)"
    if inner_compute is not None:
        compute = (f"        if self.cp_enable:\n            outputs = {inner_compute}\n"
                   "        else:\n            outputs = self._forward_impl(*args, **kwargs)")
    return "\n".join([
        "        # [HYPER BOUNDARY] input redistribution",
        *_ordered_notes(form.in_notes),
hyper_parallel/codegen/emit/replacement.py
65
66
67
68
69
70
71
72
73
        if family is not None:
            record["factory"] = family["factory"].replace(":", ".", 1)
            record["replacement_target"] = record["factory"]
            record["target_config"] = {**family["kwargs"], "context": family["context"]}
        if application.get("construction"):
            record["construction"] = application["construction"]
        records.append(record)
    return tuple(records)

hyper_parallel/codegen/emit/snapshot_patches.py
170
171
172
173
174
175
176
177
178
    """Build one inner-wrapper emission record."""
    wrapper = injection.get("inner_wrapper")
    if wrapper is None:
        return None
    target_type = ((injection.get("observed_wrapper") or {}).get("target_type")
                   or replacement_types.get(module_fqn) or source_type or declared_type)
    if target_type is None:
        raise ValueError(
            "snapshot inner_wrapper requires an observed replacement or "
177
178
179
180
181
182
183
184
185
        raise ValueError(
            "snapshot inner_wrapper requires an observed replacement or "
            f"boundary class for {module_fqn!r}"
        )
    definition = (injection.get("observed_wrapper") or {}).get("definition")
    return {
        "module_fqn": module_fqn,
        "target_fqn": injection.get("inner_target") or "self",
        "wrapper": None if definition else import_target_path(wrapper),
hyper_parallel/codegen/inline/attention.py
183
184
185
186
187
188
189
190
191
192
193
194
195
196
            for alias in node.names:
                bound = alias.asname or alias.name.split(".")[0]
                line = f"import {alias.name}" + (f" as {alias.asname}" if alias.asname else "")
                lines.setdefault(bound, line)
        elif isinstance(node, ast.ImportFrom):
            module = (resolve_name("." * node.level + (node.module or ""), owner.__package__)
                      if node.level else node.module)
            for alias in node.names:
                bound = alias.asname or alias.name
                line = f"from {module} import {alias.name}" + (
                    f" as {alias.asname}" if alias.asname else ""
                )
                lines.setdefault(bound, line)
    return lines
245
246
247
248
249
250
251
252
253
254
255
256
        if name in resolved:
            return
        node = definitions.get(name)
        if node is not None:
            if not inline_definitions:
                resolved.add(name)
                imports.append(f"from {owner.__name__} import {name}")
                return
            resolved.add(name)  # before recursing: a helper may reference itself
            for dependency in sorted(_referenced_global_names(ast.unparse(node))):
                resolve(dependency)
            inlined.append(_definition_source(node))
hyper_parallel/codegen/inline/component_source.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
    Args:
        component: Concrete implementation already selected by native preparation.
        interface: Optional kernel interface used by the existing attention renderer.
    """
    if interface is not None:
        return render_attention_class(component, interface=interface)
    forward = ast.parse(textwrap.dedent(inspect.getsource(component.forward))).body[0]
    _strip_annotations(forward)
    forward.decorator_list = []
    tuple_output = any(isinstance(node, ast.Return) and isinstance(node.value, ast.Tuple)
                       for node in ast.walk(forward))
    forward.body = ast.parse(_native_forward_call(forward, tuple_output=tuple_output)).body
    owner = next(base for base in component.__mro__ if "forward" in base.__dict__)
    _, imports = _component_dependencies(owner, ast.unparse(forward), provided={component.__name__},
                                         inline_definitions=False)
    source = (f"class {component.__name__}({component.__module__}.{component.__name__}):\n"
              + textwrap.indent(ast.unparse(forward), "    ") + "\n")
    return ExpandedSource((f"import {component.__module__}", *imports), source)


def _native_forward_call(forward: ast.FunctionDef, *, tuple_output: bool = False) -> str:
    """Delegate all arguments without rebinding the native defining-class closure."""
    args = forward.args
    arguments = [arg.arg for arg in (*args.posonlyargs, *args.args)][1:]
    if args.vararg:
        arguments.append(f"*{args.vararg.arg}")
    arguments.extend(f"{arg.arg}={arg.arg}" for arg in args.kwonlyargs)
    if args.kwarg:
        arguments.append(f"**{args.kwarg.arg}")
    call = f"super().forward({', '.join(arguments)})"
    return f"return (*{call},)" if tuple_output else f"return {call}"


def collapse_unmodified_components(source: str) -> str:
    """Replace untouched native forwarding shells with their original class imports.
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
    Boundary lowering needs a signature to select its existing templates. Only
    shells that lowering left untouched can collapse; rewritten forwards remain
    visible and continue inheriting native constructors and parallel stages.
    """
    lines = source.splitlines(keepends=True)
    offsets = [0]
    for line in lines:
        offsets.append(offsets[-1] + len(line))
    tree = ast.parse(source)
    edits = []
    collapsed = {}
    for node in tree.body:
        module = _unchanged_component_base(node)
        if module is None:
            continue
        collapsed[node] = (module, node.name)
        edits.append(TextEdit(offsets[node.lineno - 1], offsets[node.end_lineno], ""))
    for node in tree.body:
        if not isinstance(node, ast.Import) or len(node.names) != 1:
            continue
        module = node.names[0].name
        names = sorted(name for owner, name in collapsed.values() if owner == module)
        if not names:
            continue
        still_used = _component_module_used(tree, module, collapsed)
        imports = (f"import {module}\n" if still_used else "") + f"from {module} import {', '.join(names)}\n"
        edits.append(TextEdit(offsets[node.lineno - 1], offsets[node.end_lineno], imports))
    return apply_edits(source, edits) if edits else source


def _component_module_used(tree: ast.Module, module: str, collapsed: dict) -> bool:
    """Keep namespace imports still used by rewritten subclasses or other source."""
    return any(
        isinstance(child, ast.Attribute) and ast.unparse(child).startswith(module + ".")
        for other in tree.body if other not in collapsed
        for child in ast.walk(other)
    )
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131


def _unchanged_component_base(node: ast.AST) -> str | None:
    """Recognize only a same-name native subclass forwarding all arguments unchanged."""
    if not isinstance(node, ast.ClassDef) or len(node.bases) != 1:
        return None
    base = node.bases[0]
    if not isinstance(base, ast.Attribute) or base.attr != node.name:
        return None
    module = ast.unparse(base.value)
    if not module.startswith("hyper_parallel.components.modules."):
        return None
    component = getattr(importlib.import_module(module), node.name)
    expected = ast.parse(render_component_source(component).source).body[0]
    return module if ast.dump(node) == ast.dump(expected) else None


__all__ = ["render_component_source", "observe_wrapper_source"]
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
    ``original_forward`` identifies the method saved by the native patch.
    Models and closures stay scoped; runtime mesh and communication state are
    never queried or synthesized by this source reader.
    """
    if getattr(forward, "__func__", forward) is getattr(original_forward, "__func__", original_forward):
        return {"body": None, "imports": []}
    function = getattr(forward, "__func__", forward)
    node, captures = _wrapper_capture(function)
    source_bindings = _installed_closure_bindings(function, node.name)
    target_names, original_names = _bound_capture_names(captures, target, original_forward)
    bindings, literals = _closure_bindings(function, captures, companions)
    cp_scalars = _native_cp_scalars(function, captures, bindings)
    if cp_scalars:
        offset = 1 if ast.get_docstring(node) is not None else 0
        node.body[offset:offset] = ast.parse("\n".join(
            f"{name} = cp_mesh.{method}()" for name, method in sorted(cp_scalars.items())
        )).body
    original = original_names[0] if original_names else "original_forward"
    target_name = target_names[0] if target_names else "target_module"
    parameters = ", ".join(sorted(set(captures) | {target_name} | ({"cp_mesh"} if cp_scalars else set())))
    attrs = ", ".join(f"{attr!r}: {name}" for name, attr in bindings.items() if attr is not None)
    source = (f"def observed({parameters}):\n    {original} = {target_name}.forward\n"
              + textwrap.indent(ast.unparse(node), "    ")
              + f"\n    return _ForwardRewriteRequest({target_name}, {node.name}, companion_attrs={{{attrs}}})\n")
    tree = ast.parse(source).body[0]
    body = _nested_forward_body(tree, node.name, target_name=target_name, literals=literals,
                                bound_globals=set(source_bindings))
    if body is None:
        raise RuntimeError(f"codegen cannot lower observed forward {forward.__qualname__}")
    globals_used = _referenced_global_names("\n".join((*source_bindings.values(), ast.unparse(node)))) - set(captures)
    owner = function.__globals__["__name__"]
    imports = [(owner, name) for name in sorted(globals_used & function.__globals__.keys())]
    if "_get_cp_submesh" in body:
        imports.append(("hyper_parallel.distributed._builder.applier", "_get_cp_submesh"))
    return {"body": body, "imports": imports, "bindings": tuple(source_bindings.values()),
            "definition": _wrapper_definition(node, body, getattr(forward, "__self__", None) is target)}


def _wrapper_capture(function: Any) -> tuple:
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
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276


def _wrapper_capture(function: Any) -> tuple:
    """Read an already-installed closure without executing its owner or runtime resources."""
    node = ast.parse(textwrap.dedent(inspect.getsource(function.__code__))).body[0]
    node.decorator_list = []
    _strip_annotations(node)
    return node, dict(inspect.getclosurevars(function).nonlocals)


def _installed_closure_bindings(function: Any, name: str) -> dict[str, str]:
    """Resolve the native owner's aliases without inspecting arbitrary global runtime objects."""
    qualname = getattr(function.__code__, "co_qualname", function.__qualname__)
    owner = function.__globals__.get(qualname.partition(".<locals>.")[0])
    node = ast.parse(textwrap.dedent(inspect.getsource(owner.__code__))).body[0] if inspect.isfunction(owner) else None
    imported = {symbol: value.__name__ for symbol, value in function.__globals__.items()
                if inspect.ismodule(value) or inspect.isfunction(value) or inspect.isbuiltin(value)}
    return _closure_source_bindings(node, name, imported)


def _closure_bindings(function: Any, captures: dict[str, Any], companions: dict[str, Any]) -> tuple[dict, dict]:
    """Project configuration and native-published state without retaining objects."""
    bindings = {name: next((attr for attr, value in companions.items() if value is captured), None)
                for name, captured in captures.items() if not isinstance(captured, (str, int, float, bool, type(None)))}
    declared, parameters = _native_companion_bindings(function)
    bindings.update({name: attr for name, attr in declared.items() if name in captures
                     and attr in companions and companions[attr] is captures[name]})
    literals = {name: value for name, value in captures.items()
                if isinstance(value, (str, int, float, bool, type(None)))
                and name not in {"cp_rank", "cp_size"} and name not in WRAPPER_CONTEXT
                and (not bindings.get(name) or name in parameters)}
    return bindings, literals


def _bound_capture_names(captures: dict[str, Any], target: Any, original: Any) -> tuple[list[str], list[str]]:
    """Identify the native target and the specific saved forward, not arbitrary methods."""
    targets = [name for name, value in captures.items() if value is target]
    forwards = [name for name, value in captures.items()
                if getattr(value, "__self__", None) is target
                and getattr(value, "__func__", None) is getattr(original, "__func__", None)]
    return targets, forwards


def _native_companion_bindings(function: Any) -> tuple[dict[str, str], set[str]]:
    """Preserve the native request's named state, including optional None contexts."""
    qualname = getattr(function.__code__, "co_qualname", function.__qualname__)
    owner = function.__globals__.get(qualname.partition(".<locals>.")[0])
    if not inspect.isfunction(owner):
        return {}, set()
    tree = ast.parse(textwrap.dedent(inspect.getsource(owner.__code__)))
    return _companion_attr_bindings(tree), set(inspect.signature(owner, follow_wrapped=False).parameters)


def _native_cp_scalars(function: Any, captures: dict[str, Any], bindings: dict[str, str]) -> dict[str, str]:
    """Prove captured CP scalars originate in native context fields without reading a mesh."""
    qualname = getattr(function.__code__, "co_qualname", function.__qualname__)
    owner = function.__globals__.get(qualname.partition(".<locals>.")[0])
    if not inspect.isfunction(owner):
        return {}
    tree = ast.parse(textwrap.dedent(inspect.getsource(owner.__code__)))
    parameters = set(inspect.signature(owner, follow_wrapped=False).parameters)
    cp_scalars = {}
    for node in tree.body[0].body:
        if not isinstance(node, ast.Assign) or len(node.targets) != 1 or not isinstance(node.targets[0], ast.Name):
            continue
        name = node.targets[0].id
        if bindings.get(name) or _cp_context_field(node.value, parameters, captures.get(name)) != name:
            continue
        if not _assigned_once(tree, name):
            continue
        cp_scalars[name] = "get_local_rank" if name == "cp_rank" else "size"
    return cp_scalars


def _cp_context_field(value: ast.expr, parameters: set[str], captured: Any) -> str | None:
    """Recognize one integer CP field read from an unchanged native context parameter."""
    if not isinstance(captured, int) or isinstance(captured, bool):
        return None
    arguments = _context_getattr_arguments(value)
    if not arguments:
        return None
    context, field = arguments[:2]
    if not isinstance(context, ast.Name) or context.id not in parameters:
        return None
    if not isinstance(field, ast.Constant) or field.value not in {"cp_rank", "cp_size"}:
        return None
    expected = ast.Constant(value=0 if field.value == "cp_rank" else 1)
    if len(arguments) == 3 and ast.dump(arguments[2]) != ast.dump(expected):
        return None
    return field.value


def _context_getattr_arguments(value: ast.expr) -> list[ast.expr]:
    """Read a native getattr or int(getattr(...)) using syntax accepted by the lint runtime."""
    if isinstance(value, ast.Call) and isinstance(value.func, ast.Name) and value.func.id == "int":
        if len(value.args) != 1 or value.keywords:
            return []
        value = value.args[0]
    if (isinstance(value, ast.Call) and isinstance(value.func, ast.Name) and value.func.id == "getattr"
            and len(value.args) in (2, 3) and not value.keywords):
        return value.args
    return []
hyper_parallel/codegen/inline/declaration_edits.py
32
33
34
35
36
37
38
39
40
41
42
43
    snippets: Iterable[ModuleSnippetPatch],
) -> list[TextEdit]:
    """Build ordered edits for generated imports and top-level snippets."""
    edits = []
    import_nodes = [node for node in ast.parse(source_text).body if isinstance(node, (ast.Import, ast.ImportFrom))]
    if import_nodes:
        # Component bases must follow the complete last import, not its line start.
        import_end = sum(len(line) for line in source_text.splitlines(keepends=True)[:import_nodes[-1].end_lineno])
    lines = _render_imports(source_text, imports)
    if lines:
        edits.append(insert_after_imports(
            source_text,
44
45
46
47
48
49
50
51
52
            import_end,
            "\n" + "\n".join(lines) + "\n",
            default_offset=docstring_end or 0,
        ))
    parts = _render_snippets(source_text, snippets)
    if parts:
        edits.append(insert_after_imports(
            source_text,
            import_end,
57
58
59
60
61
62
63
64
65
66
67
68
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


def _render_snippets(source_text: str, snippets: Iterable[ModuleSnippetPatch]) -> list[str]:
    """Keep shared native definitions once, rejecting conflicting source bindings."""
    definitions = _declared_bindings(source_text)
    parts = []
    for snippet in snippets:
        text = snippet.text.strip("\n")
        if not text or text in parts:
            continue
        current = _declared_bindings(text)
        for name, definition in current.items():
            if name in definitions and definitions[name] != definition:
                raise ValueError(f"codegen: conflicting source definition {name!r}")
        if current and current.keys() <= definitions.keys():
            continue
        definitions.update(current)
        parts.append(text)
    return parts


def _declared_bindings(source: str) -> dict[str, str]:
    """Index native definitions and early-bound aliases without evaluating them."""
    result = {}
    for node in ast.parse(source).body:
        if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
            result[node.name] = ast.dump(node)
        elif isinstance(node, (ast.Assign, ast.AnnAssign)):
            targets = node.targets if isinstance(node, ast.Assign) else (node.target,)
            for target in targets:
                for name in ast.walk(target):
                    if isinstance(name, ast.Name) and isinstance(name.ctx, ast.Store):
                        result[name.id] = ast.dump(node)
    return result


def _render_imports(
    source_text: str, imports: Iterable[ImportPatch]
 97
 98
 99
100
101
102
103
104
105
    grouped: dict[str, set[str]] = defaultdict(set)
    lines: list[str] = []
    for patch in imports:
        if patch.raw:
            if patch.raw not in source_text and patch.raw not in lines:
                lines.append(patch.raw)
            continue
        grouped[patch.module].update(patch.names)
    for module in sorted(grouped):
hyper_parallel/codegen/inline/forward_edits.py
41
42
43
44
45
46
47
48
49
50
51
    for patch in patch_list:
        cls = index.find_class(patch.class_name)
        if cls is None:
            continue
        if patch.definition is not None:
            edits.append(_definition_edit(source_text, cls, patch))
            continue
        func = cls.methods.get(patch.method_name)
        if func is None:
            continue
        body = _bind_forward_args(_bind_hidden_arg(patch.body, func), func)
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81


def _definition_edit(source_text: str, cls: ClassInfo, patch: ForwardExtractPatch) -> TextEdit:
    """Install actual native methods, preserving the old method only when called."""
    names = {node.name for node in ast.parse(patch.definition).body if isinstance(node, ast.FunctionDef)}
    collisions = (names - {patch.method_name}) & cls.methods.keys()
    if collisions:
        raise RuntimeError(f"codegen observed methods collide with source methods {sorted(collisions)}")
    definition = textwrap.indent(patch.definition.strip(), "    ") + "\n"
    func = cls.methods.get(patch.method_name)
    if func is None:
        return TextEdit(cls.end_offset, cls.end_offset, "\n" + definition)
    if "self._forward_impl(" in patch.definition:
        impl = _build_forward_impl_edit(source_text, func)
        if impl is None or "_forward_impl" in cls.methods:
            raise RuntimeError("codegen cannot preserve the original method for the observed wrapper")
        original = ast.parse(textwrap.dedent(source_text[func.def_offset:func.body_end])).body[0]
        decorators = "".join(f"    @{ast.unparse(item)}\n" for item in original.decorator_list)
        definition = decorators + impl.replacement + "\n" + definition
    return TextEdit(func.def_offset, func.body_end, definition)


def _parallel_state_prefix(body: str) -> str:
    """Render static enable flags read by a generated dispatch body."""
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
        args.append(f"*{func.vararg_name}")
    args.extend(f"{name}={name}" for name in func.kwonly_names)
    if func.kwarg_name:
        args.append(f"**{func.kwarg_name}")
    positional = list(func.param_names)
    if func.vararg_name:
        positional.append(f"*{func.vararg_name}")
    keywords = [f"{name!r}: {name}" for name in func.kwonly_names]
    if func.kwarg_name:
        keywords.append(f"**{func.kwarg_name}")
    positional_text = ", ".join(positional) + ("," if positional else "")
    bindings = []
    if "__hp_forward_positional__" in body:
        bindings.append(f"forward_args = ({positional_text})")
        body = body.replace("__hp_forward_positional__", "forward_args")
    if "__hp_forward_keywords__" in body:
        bindings.append("forward_kwargs = {" + ", ".join(keywords) + "}")
        body = body.replace("__hp_forward_keywords__", "forward_kwargs")
    return "\n".join([*bindings, body.replace(token, ", ".join(args))])


__all__ = ["forward_extract_edits"]
hyper_parallel/codegen/inline/framework_spec.py
451
452
453
454
455
456
457
458
459
460
461
    """
    if target is None:
        return None
    model_type = _family_key(model_type, target)
    key = (target, model_type, inner_wrapper, construction_kwargs)
    if key in _STRATEGY_CACHE:
        return _STRATEGY_CACHE[key]
    spec = _resolve_strategy_spec(target, inner_wrapper, construction_kwargs)
    _STRATEGY_CACHE[key] = spec
    return spec

463
464
465
466
467
468
469
470
471
def _resolve_strategy_spec(
    target: str, inner_wrapper: bool, construction_kwargs: tuple[str, ...],
) -> StrategySpec | None:
    if inner_wrapper:
        return _cp_strategy_spec(target, construction_kwargs=construction_kwargs)
    return None


def _cp_strategy_spec(target: str, *, construction_kwargs: tuple[str, ...] = ()) -> StrategySpec:
482
483
484
485
486
487
488
489
490
491
492
493
494
495

    Unrecognized wrappers carry no source body; artifact verification must
    reject a declared patch that was not materialized.
    """
    resolved = inner_wrapper_target(target, construction_kwargs=construction_kwargs)
    if resolved is None:
        return StrategySpec(kind=CP_ATTENTION_KIND, imports=())
    imports = tuple(ImportPatch(module, (name,)) for module, name in resolved.extra_imports)
    if resolved.helper_module and resolved.helper_name:
        imports = (ImportPatch(resolved.helper_module, (resolved.helper_name,)), *imports)
    if resolved.inline_body is not None:
        return StrategySpec(
            kind=CP_ATTENTION_KIND,
            subclass_shell=resolved.inline_body,
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
538
539
540


def observed_constructor_spec(rule: Any) -> ReplacementSpec | None:
    """Use the native-selected class and its existing construction contracts."""
    module_name, name = rule.construction["implementation"].replace(":", ".", 1).rsplit(".", 1)
    component = getattr(importlib.import_module(module_name), name)
    parameters = inspect.signature(component.__init__).parameters
    values = dict(item.split("=", 1) for item in rule.construction_kwargs)
    values.update({name: repr(value) for name, value in rule.construction.get("arguments", {}).items()})
    arguments = []
    ignored = _ignored_constructor_parameters(component)
    for key, value in values.items():
        if key in parameters and key not in ignored and key != "module_fqn" and value != "None":
            arguments.append(f"{key}={value}")
    mode = "wrap_source"
    if {"hidden_size", "eps"} <= parameters.keys():
        mode = "construct"
    elif ("config" in parameters and callable(getattr(component, "_initialize_source", None))
          and callable(getattr(component, "_initialize_config", None))):
        mode = "config"
    if mode == "wrap_source" and "module" not in parameters:
        return replacement_spec_for(rule.replace_target, module_type=rule.module_type)
    imports, snippets = _observed_component_source(component)
    return ReplacementSpec(
        old_ctor=class_name_of(rule.module_type), new_ctor=name,
        imports=imports, mode=mode,
        keyword_args=tuple(arguments), remove_class=False, snippets=snippets,
    )
541
542
543
544
545
546
547
548
549
550
551
552
553
554


def _observed_component_source(component: type) -> tuple[tuple[ImportPatch, ...], tuple[ModuleSnippetPatch, ...]]:
    """Expose native member stages absent from the legacy injection records."""
    if not callable(getattr(component, "parallel_module_spec", None)):
        return (ImportPatch(component.__module__, (component.__name__,)),), ()
    expanded = render_component_source(component)
    imports = tuple(ImportPatch(module="", names=(), raw=line) for line in expanded.imports)
    snippets = tuple(ModuleSnippetPatch(ast.unparse(node)) for node in ast.parse(expanded.source).body)
    return imports, snippets


@lru_cache(maxsize=None)
def _ignored_constructor_parameters(component: type) -> frozenset[str]:
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574

@lru_cache(maxsize=None)
def _ignored_constructor_parameters(component: type) -> frozenset[str]:
    """Read unused native arguments, following only explicit super keyword forwarding."""
    owner = next(base for base in component.__mro__ if "__init__" in base.__dict__)
    try:
        tree = ast.parse(textwrap.dedent(inspect.getsource(owner.__init__)))
    except (OSError, TypeError):
        return frozenset()
    inherited = _ignored_constructor_parameters(owner.__mro__[1]) if len(owner.__mro__) > 1 else frozenset()
    _discard_unused_super_keywords(tree, inherited)
    loaded = {node.id for node in ast.walk(tree) if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load)}
    return frozenset(inspect.signature(owner.__init__).parameters) - loaded - {"self"}


def _discard_unused_super_keywords(tree: ast.AST, inherited: frozenset[str]) -> None:
    """Exclude forwarding reads only when the native parent ignores the argument."""
    for call in (node for node in ast.walk(tree) if isinstance(node, ast.Call)):
        if (isinstance(call.func, ast.Attribute) and call.func.attr == "__init__"
                and isinstance(call.func.value, ast.Call) and isinstance(call.func.value.func, ast.Name)
                and call.func.value.func.id == "super"):
            call.keywords = [kw for kw in call.keywords
                             if not (kw.arg in inherited and isinstance(kw.value, ast.Name))]
hyper_parallel/codegen/inline/meta_plan.py
25
26
27
28
29
30
31
32
33

def normalize_inline_meta(meta: Any) -> Any:
    """Copy emission metadata and protect classes shared with non-boundary instances."""
    normalized = _copy_inline_meta(meta)
    _mark_shared_class_boundaries(normalized, normalized.boundary_classes)
    return normalized


def _copy_inline_meta(meta: Any) -> Any:
hyper_parallel/codegen/inline/patch_engine.py
47
48
49
50
51
52
53
54
55
        The patched source text.
    """

    text, hits = _apply_source_declarations(source_text, patch_set)
    text = _apply_constructor_followups(text, patch_set, hits, root_class_name)
    return _apply_forward_patches(text, patch_set.forward_extracts)


def _apply_source_declarations(
190
191
192
193
194
195
196
197
198
199
200
        if scope is not None and attr not in scope:
            continue
        patch = patches_by_old[name][0]
        hits[name] += 1
        start, end = _node_span(call, offsets)
        replacement = _constructor_replacement(source_text, tree, node, patch, offsets)
        edits.append(TextEdit(start, end, replacement))
    return _drop_nested_edits(edits)


def _constructor_replacement(source: str, tree: ast.Module, node: ast.Assign,
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249

def _constructor_replacement(source: str, tree: ast.Module, node: ast.Assign,
                             patch: ConstructorReplacePatch, offsets: list[int]) -> str:
    """Reuse a source call, wrapping it or binding its existing config argument."""
    call = node.value
    start, end = _node_span(call, offsets)
    original = source[start:end]
    extra = "".join(f", {arg}" for arg in patch.keyword_args)
    if patch.mode == "wrap_source":
        return f"{patch.new_ctor}(module={original}{extra})"
    if patch.mode in ("name", "construct"):
        _, function_end = _node_span(call.func, offsets)
        original = source[function_end:end]
        if patch.mode == "construct" and extra:
            original = original[:-1].rstrip().rstrip(",") + extra + ")"
        return patch.new_ctor + original
    if patch.mode != "config":
        raise ValueError(f"unknown constructor replacement mode: {patch.mode!r}")
    return _config_replacement(tree, node, patch, extra)


def _config_replacement(tree: ast.Module, node: ast.Assign, patch: ConstructorReplacePatch, extra: str) -> str:
    """Bind the config from the existing source constructor without evaluating it."""
    call = node.value
    owner = next(item for item in tree.body if isinstance(item, ast.ClassDef) and item.name == patch.old_ctor)
    constructor = next(item for item in owner.body if isinstance(item, ast.FunctionDef) and item.name == "__init__")
    names = [item.arg for item in (*constructor.args.posonlyargs, *constructor.args.args) if item.arg != "self"]
    arguments = dict(zip(names, call.args))
    arguments.update({kw.arg: kw.value for kw in call.keywords if kw.arg is not None})
    if "config" not in arguments:
        raise ValueError(f"codegen: {patch.old_ctor} has no source config argument")
    result = f"{patch.new_ctor}(config={ast.unparse(arguments['config'])}{extra})"
    return result + _preserved_source_attributes(constructor, node, arguments)


def _preserved_source_attributes(constructor: ast.FunctionDef, node: ast.Assign, arguments: dict) -> str:
    """Retain explicit source constructor identity fields such as layer indices."""
    lines = []
    for statement in constructor.body:
        if (isinstance(statement, ast.Assign) and isinstance(statement.value, ast.Name)
                and statement.value.id in arguments and statement.value.id != "config"):
            for target in statement.targets:
                if (isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name)
                        and target.value.id == "self"):
                    lines.append(f"\n{' ' * node.col_offset}{ast.unparse(node.targets[0])}.{target.attr} = "
                               f"{ast.unparse(arguments[statement.value.id])}")
    return "".join(lines)


def _scopes_by_old_ctor(
    patches: Iterable[ConstructorReplacePatch],
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
    insertions: dict[int, list[str]] = defaultdict(list)
    for patch in pending:
        if patch.mode != "wrap_source":
            continue
        loop_edit = _prepared_layer_replacement(tree, patch, root_class_name, offsets)
        if loop_edit is not None:
            insertions[loop_edit.start].append(loop_edit.replacement)
            hits[patch.old_ctor] += 1
            continue
        root_attr = patch.scope_fqns[0].split(".", 1)[0]
        constructors = _root_constructors(tree, root_attr, root_class_name)
        if len(constructors) != 1:
            continue
        function = constructors[0]
        _, end = _node_span(function.body[-1], offsets)
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452

def _prepared_layer_replacement(tree: ast.Module, patch: ConstructorReplacePatch,
                                root_class: str | None, offsets: list[int]) -> TextEdit | None:
    """Reuse an existing layer preparation loop when the child constructor is imported."""
    if patch.shared_fqns:
        return None
    scope = _layer_scope(patch.scope_fqns)
    if scope is None:
        return None
    paths, index, prefix, suffix = scope
    owner = _source_constructor(tree, root_class, prefix[:-1])
    if owner is None:
        return None
    candidates = _prepared_layer_aliases(owner, prefix[-1])
    if len(candidates) != 1:
        return None
    loop, alias = candidates[0]
    if any(isinstance(node, (ast.Break, ast.Continue, ast.Return)) for node in ast.walk(loop)):
        return None
    access = ".".join([alias.targets[0].id, *suffix])
    extra = "".join(f", {arg}" for arg in patch.keyword_args if not arg.startswith("module_fqn="))
    body = f"{access} = {patch.new_ctor}(module={access}{extra})"
    if not patch.scope_complete:
        selected = tuple(int(path[index]) for path in paths)
        body = f"if {loop.target.id} in {selected!r}:\n    {body}"
    indent = " " * alias.col_offset
    body = "\n" + "\n".join(indent + line for line in body.splitlines()) + "\n"
    _, end = _node_span(loop.body[-1], offsets)
    return TextEdit(end, end, body)


def _layer_scope(fqns: tuple[str, ...]) -> tuple | None:
    """Accept one literal indexed container and a common child suffix."""
    paths = [fqn.split(".") for fqn in fqns]
    numeric = [index for index, part in enumerate(paths[0]) if part.isdecimal()]
    if len(numeric) != 1:
        return None
    index = numeric[0]
    prefix, suffix = paths[0][:index], paths[0][index + 1:]
    if not prefix or not suffix or any(path[:index] != prefix or path[index + 1:] != suffix for path in paths):
        return None
    return paths, index, prefix, suffix


def _source_constructor(tree: ast.Module, root_class: str | None, path: list[str]) -> ast.FunctionDef | None:
    """Follow only literal self.child = LocalClass(...) ownership in copied source."""
    constructors = {
        cls.name: next((node for node in cls.body if isinstance(node, ast.FunctionDef)
                        and node.name == "__init__"), None)
        for cls in tree.body if isinstance(cls, ast.ClassDef)
    }
    constructor = constructors.get(root_class)
    for name in path:
        if constructor is None:
            return None
        calls = [node.value for node in ast.walk(constructor)
                 if isinstance(node, ast.Assign) and isinstance(node.value, ast.Call)
                 and _assigned_attr(node) == name and ast.unparse(node.targets[0]) == f"self.{name}"]
        if len(calls) != 1:
            return None
        constructor = constructors.get(_call_name(calls[0].func))
    return constructor


def _prepared_layer_aliases(owner: ast.FunctionDef, container: str) -> list[tuple[ast.For, ast.Assign]]:
    """Recognize native for-loops that bind layer = self.layers[index]."""
    candidates = []
    iteration = _container_iteration(owner, container)
    for loop in (node for node in ast.walk(owner) if isinstance(node, ast.For) and isinstance(node.target, ast.Name)):
        if ast.dump(loop.iter) != iteration:
            continue
        for node in loop.body:
            if (isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name)
                    and isinstance(node.value, ast.Subscript) and isinstance(node.value.value, ast.Attribute)
                    and ast.unparse(node.value.value) == f"self.{container}"
                    and ast.unparse(node.value.slice) == loop.target.id):
                candidates.append((loop, node))
    return candidates


def _container_iteration(owner: ast.FunctionDef, container: str) -> str | None:
    """Prove a preparation loop covers the same range used to create the ModuleList."""
    for node in owner.body:
        if (isinstance(node, ast.Assign) and _assigned_attr(node) == container
                and ast.unparse(node.targets[0]) == f"self.{container}"
                and isinstance(node.value, ast.Call) and node.value.args
                and ast.unparse(node.value.func) in ("nn.ModuleList", "torch.nn.ModuleList")):
            value = node.value.args[0]
            if isinstance(value, ast.ListComp) and len(value.generators) == 1:
                iteration = value.generators[0].iter
                if (isinstance(iteration, ast.Call) and ast.unparse(iteration.func) == "range"
                        and len(iteration.args) == 1 and not iteration.keywords):
                    return ast.dump(iteration)
    return None


def _root_constructors(
    tree: ast.Module, root_attr: str, root_class_name: str | None,
455
456
457
458
459
460
461
462
463
464
    constructors = []
    for node in tree.body:
        if not isinstance(node, ast.ClassDef):
            continue
        if root_class_name not in (None, node.name):
            continue
        for child in node.body:
            if not isinstance(child, ast.FunctionDef) or child.name != "__init__":
                continue
            if any(
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519


def _render_deferred_replacement(patch: ConstructorReplacePatch) -> str:
    """Render explicit module assignments, preserving observed shared ownership."""
    arguments = [arg for arg in patch.keyword_args if not arg.startswith("module_fqn=")]
    extra = "".join(f", {arg}" for arg in arguments)
    aliases = {fqn: group[0] for group in patch.shared_fqns for fqn in group[1:]}
    primaries = [fqn for fqn in patch.scope_fqns if fqn not in aliases]
    lines = []
    for fqn in primaries:
        value = (f"{patch.new_ctor}(\n"
                 f"            module={_module_access(fqn)}, module_fqn={fqn!r}{extra})")
        lines.extend((f"\n        # {fqn}: {patch.old_ctor} -> {patch.new_ctor}",
                      "        " + _module_assignment(fqn, value)))
    for fqn in patch.scope_fqns:
        if fqn in aliases:
            primary = aliases[fqn]
            if primary not in primaries:
                raise ValueError(f"codegen: shared module {fqn!r} has no replacement at {primary!r}")
            lines.extend((f"\n        # {fqn}: shares the replacement at {primary}",
                          "        " + _module_assignment(fqn, _module_access(primary))))
    return "\n".join(lines) + "\n"


def _module_access(fqn: str) -> str:
    """Access native child names without guessing their container type."""
    expression = "self"
    for name in fqn.split("."):
        expression = (f"{expression}.{name}" if name.isidentifier() and not keyword.iskeyword(name)
                      else f"getattr({expression}, {name!r})")
    return expression


def _module_assignment(fqn: str, value: str) -> str:
    """Keep ordinary attributes readable and support non-identifier child names."""
    parent, _, name = fqn.rpartition(".")
    if name.isidentifier() and not keyword.iskeyword(name):
        return f"{_module_access(fqn)} = {value}"
    return f"setattr({_module_access(parent) if parent else 'self'}, {name!r}, {value})"


def _drop_nested_edits(edits: list[TextEdit]) -> list[TextEdit]:
    """Keep outer constructor rewrites when constructor calls are nested."""
hyper_parallel/codegen/inline/pipeline.py
69
70
71
72
73
74
75
76
77
78
79
        _observed_boundary_classes(meta, patch_plan),
    )
    _add_recorded_forward_host_imports(source_text, patch_set, patch_plan)
    _materialize_imported_forward_hosts(source_text, patch_set)
    model_class = (getattr(meta, "source", None) or {}).get("model_class")
    root_class_name = model_class.rsplit(":", 1)[-1].rsplit(".", 1)[-1] if model_class else None
    rendered = apply_patch_set(source_text, patch_set, root_class_name=root_class_name)
    # The copied modeling source brings its own decorated helpers that share
    # names with the library functions the artifact imports, and a local
    # definition wins over the import: the native path calls the library
    # implementation (whose kernel binding is resolved in its own module), so a
83
84
85
86
87
88
89
90
91
    # on purpose) keep their definitions.
    rendered = drop_shadowed_definitions(
        rendered, _library_import_names(rendered) & _decorated_names(source_text)
    )
    normalized_meta = normalize_inline_meta(meta)
    return rendered, normalized_meta


def _add_recorded_forward_host_imports(
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
            continue
        rendered.add(patch.class_name)
        imported = patch_set.imports[import_index]
        other_names = tuple(name for name in imported.names if name != patch.class_name)
        replacement_imports = [ImportPatch(imported.module, other_names)] if other_names else []
        replacement_imports.append(ImportPatch("", (), raw=f"import {imported.module}"))
        patch_set.imports[import_index:import_index + 1] = replacement_imports
        base = f"{imported.module}.{patch.class_name}"
        if patch.definition is not None:
            definition = _imported_forward_definition(patch.definition)
            snippet = (f"class {patch.class_name}({base}):\n"
                       + _parallel_state_prefix(definition) + textwrap.indent(definition, "    ") + "\n")
            patch_set.module_snippets.append(ModuleSnippetPatch(snippet))
            continue
        body, local = _imported_forward_source(patch.body)
        state = _parallel_state_prefix(body)
        snippet = (
            f"class {patch.class_name}({base}):\n"
            f"{state}"
            f"{local}"
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242


def _imported_forward_definition(definition: str) -> str:
    """Bind the saved native method outside nested callbacks before rendering its real signature."""
    parts = []
    for node in ast.parse(definition).body:
        if isinstance(node, ast.FunctionDef):
            body = "\n".join(ast.unparse(statement) for statement in node.body)
            body, local = _imported_forward_source(body)
            node.body = ast.parse(body).body
            if local:
                parts.append(textwrap.dedent(local).strip())
        parts.append(ast.unparse(node))
    return "\n\n".join(parts)


def _imported_forward_source(body: str) -> tuple[str, str]:
    """Keep a helper's original-method callback separate from its imported host dispatch."""
    dispatch = _cp_dispatch_call(body)
    body = body.replace("__hp_forward_args__", "*args, **kwargs").replace(
        "__hp_forward_positional__", "args",
    ).replace("__hp_forward_keywords__", "kwargs")
    if dispatch is not None:
        local = ("    def _forward_impl(self, *args, **kwargs):\n"
                 "        return super().forward(*args, **kwargs)\n\n")
        return body, local
    body = body.replace("self._forward_impl(", "original_forward(")
    if "original_forward(" in body:
        body = "original_forward = super().forward\n" + body
    return body, ""


def render_inline_strategies_for_source_unit(
    source_text: str,
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
        node.name
        for node in ast.parse(source_text).body
        if isinstance(node, ast.ClassDef)
    }
    boundaries = _observed_boundary_classes(meta, patch_plan)
    owned_rules = tuple(
        rule for rule in strategy_rules
        if ((rule.observed_wrapper or {}).get("host_class") in source_classes
            or rule_block_classes(rule, boundaries) & source_classes)
    )
    patches = build_strategy_patches(
        owned_rules, model_type, boundaries,
    )
    patches.forward_extracts = [
        patch for patch in patches.forward_extracts
379
380
381
382
383
384
385
386
387
388
            uncovered.append(rule.replace_target)
        for target in (rule.local_compute_target, rule.inner_wrapper_target):
            if target is None:
                continue
            if target == rule.inner_wrapper_target and rule.observed_wrapper is not None:
                continue
            if strategy_spec(
                target, model_type, inner_wrapper=target == rule.inner_wrapper_target,
                construction_kwargs=rule.construction_kwargs if target == rule.inner_wrapper_target else (),
            ) is not None:
hyper_parallel/codegen/inline/recognition.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
def inner_wrapper_target(
    factory_path: str | None, *, construction_kwargs: tuple[str, ...] = (),
) -> InnerWrapperTarget | None:
    """Recover an inner wrapper's emitted helper contract from its source."""
    source = _wrapper_factory_ast(factory_path)
    if source is None:
        return None
    module_name, tree, factory_node = source
    request_owner = _request_owner(factory_node, tree)
    replacement_name = _replacement_callable(request_owner)
    literals = _wrapper_literals(factory_node, construction_kwargs)
    if request_owner is not None and request_owner is not factory_node:
        literals = _delegate_literals(factory_node, request_owner, literals)
    bindings = _closure_source_bindings(request_owner, replacement_name, _factory_imported_modules(tree))
    helper_name = (
        _forward_helper_name(request_owner, replacement_name)
        if request_owner is not None and replacement_name
        else None
241
242
243
244
245
246
247
248
249
250
251
        node.name
        for node in tree.body
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
    }
    module_symbols = module_functions | _factory_imported_modules(tree).keys()
    if not helper_name or helper_name not in module_functions:
        inline_body = _nested_forward_body(
            request_owner, replacement_name, target_name=_original_forward_target(request_owner),
            literals=literals, bound_globals=set(bindings),
        )
        if inline_body is None:
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
            literals=literals, bound_globals=set(bindings),
        )
        if inline_body is None:
            return None
        forward = next(node for node in ast.walk(request_owner)
                       if isinstance(node, ast.FunctionDef) and node.name == replacement_name)
        return InnerWrapperTarget(
            inline_body=inline_body,
            extra_imports=_body_imports("\n".join((*bindings.values(), inline_body)), module_name, module_symbols),
            definition=_wrapper_definition(forward, inline_body, False), bindings=tuple(bindings.values()),
        )
    inline_body = _helper_keyword_body(
        request_owner, replacement_name, _module_function(tree, helper_name),
        literals,
    )
    return InnerWrapperTarget(
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294


def _wrapper_factory_ast(path: str | None) -> tuple[str, ast.Module, Any] | None:
    """Find the declared factory without importing or invoking it."""
    module_name, _, name = (path or "").rpartition(".")
    if not module_name or not name:
        return None
    tree = _module_source_tree(module_name)
    if tree is None:
        return None
    factory = _module_function(tree, name)
    return (module_name, tree, factory) if factory is not None else None


def _body_imports(body: str | None, module: str, functions: set[str]) -> tuple[tuple[str, str], ...]:
    """Keep native helpers referenced by the lowered closure visible in its new module."""
    names = {node.id for node in ast.walk(ast.parse(body or "")) if isinstance(node, ast.Name)}
    imports = [(module, name) for name in sorted(names & functions)]
    if "_get_cp_submesh" in names:
        imports.append(("hyper_parallel.distributed._builder.applier", "_get_cp_submesh"))
    return tuple(imports)


def _single_helper_delegate(
    tree: ast.AST, replacement_name: str, helper_name: str,
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
def _single_helper_delegate(
    tree: ast.AST, replacement_name: str, helper_name: str,
) -> tuple[ast.FunctionDef, ast.Call | None]:
    """Identify a pure return call without discarding surrounding control flow."""
    forward = next(node for node in ast.walk(tree)
                   if isinstance(node, ast.FunctionDef) and node.name == replacement_name)
    body = forward.body[1:] if ast.get_docstring(forward) is not None else forward.body
    if len(body) != 1 or not isinstance(body[0], ast.Return):
        return forward, None
    call = body[0].value
    if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Name)
            and call.func.id == helper_name and any(item.arg is not None for item in call.keywords)):
        return forward, None
    return forward, call


def _positional_contract(args: ast.arguments, excluded: set[str]) -> tuple[tuple[str, bool, str | None], ...]:
    """Compare names, positional-only constraints and default expressions."""
    parameters = (*args.posonlyargs, *args.args)
    defaults = [None] * (len(parameters) - len(args.defaults)) + list(args.defaults)
    return tuple((item.arg, index < len(args.posonlyargs), ast.dump(value) if value is not None else None)
                 for index, (item, value) in enumerate(zip(parameters, defaults)) if item.arg not in excluded)


def _keyword_names(call: ast.Call) -> set[str]:
315
316
317
318
319
320
321
322
323


def _keyword_names(call: ast.Call) -> set[str]:
    """Collect symbols referenced by explicitly supplied helper keywords."""
    return {node.id for item in call.keywords if item.arg is not None
            for node in ast.walk(item.value) if isinstance(node, ast.Name)}


def _forwards_parameters(args: ast.arguments, call: ast.Call) -> bool:
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378


def _forwards_parameters(args: ast.arguments, call: ast.Call) -> bool:
    """Ensure the token can replace the native delegate's argument forwarding."""
    names = [item.arg for item in (*args.posonlyargs, *args.args)]
    if [ast.unparse(item) for item in call.args[1:]] != names:
        return False
    kwargs = [ast.unparse(item.value) for item in call.keywords if item.arg is None]
    if kwargs != ([args.kwarg.arg] if args.kwarg else []):
        return False
    return not set(names).intersection(_keyword_names(call))


def _helper_signature_matches(forward: ast.FunctionDef, helper: ast.FunctionDef, call: ast.Call) -> bool:
    """Reject signature adaptation rather than changing positional/default behavior."""
    if forward.args.vararg or forward.args.kwonlyargs:
        return False
    parameters = (*helper.args.posonlyargs, *helper.args.args)
    if not parameters:
        return False
    excluded = {item.arg for item in call.keywords if item.arg is not None} | {parameters[0].arg}
    if _positional_contract(forward.args, set()) != _positional_contract(helper.args, excluded):
        return False
    return _forwards_parameters(forward.args, call)


def _original_forward_target(tree: ast.AST | None) -> str | None:
    """Find the owner whose original forward the wrapper saves."""
    if tree is None:
        return None
    for node in ast.walk(tree):
        if (isinstance(node, ast.Assign) and isinstance(node.value, ast.Attribute)
                and node.value.attr == "forward" and isinstance(node.value.value, ast.Name)):
            return node.value.value.id
    return None


def _wrapper_literals(factory: ast.FunctionDef, construction_kwargs: tuple[str, ...]) -> dict[str, Any]:
    """Read only literal native defaults and recorded overrides, never runtime resources."""
    parameters = (*factory.args.posonlyargs, *factory.args.args)
    values = {}
    for parameter, value in zip(parameters[len(parameters) - len(factory.args.defaults):], factory.args.defaults):
        if parameter.arg in WRAPPER_CONTEXT:
            continue
        try:
            values[parameter.arg] = ast.literal_eval(value)
        except (ValueError, TypeError):
            continue
    for argument in construction_kwargs:
        name, text = argument.split("=", 1)
        if name in WRAPPER_CONTEXT:
            raise ValueError(f"codegen: native runtime argument {name!r} cannot be frozen as configuration")
        values[name] = ast.literal_eval(text)
    return values


def _helper_keyword_body(
    tree: ast.AST, replacement_name: str, helper: ast.FunctionDef, literals: dict[str, Any],
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
def _helper_keyword_body(
    tree: ast.AST, replacement_name: str, helper: ast.FunctionDef, literals: dict[str, Any],
) -> str | None:
    """Keep explicit keywords only when native argument forwarding is preserved."""
    forward, call = _single_helper_delegate(tree, replacement_name, helper.name)
    if call is None:
        return None
    if not _helper_signature_matches(forward, helper, call):
        raise RuntimeError(f"codegen: helper delegate {replacement_name!r} is not an argument passthrough")
    target = _original_forward_target(tree)
    if target is None:
        raise RuntimeError(
            f"codegen: cannot preserve helper arguments for {replacement_name!r} without its target binding"
        )
    if not call.args or not isinstance(call.args[0], ast.Name) or call.args[0].id != target:
        raise RuntimeError(f"codegen: helper delegate {replacement_name!r} has a different target")
    lowered = ast.parse(_nested_forward_body(tree, replacement_name, target_name=target, literals=literals))
    for item in ast.walk(lowered):
        if isinstance(item, ast.Call) and isinstance(item.func, ast.Name) and item.func.id == helper.name:
            names = _keyword_names(item)
            if names - {"self", "_get_cp_submesh"}:
                raise RuntimeError(f"codegen: helper delegate has unresolved keyword names {sorted(names - {'self'})}")
            item.args = [ast.Name(id="self", ctx=ast.Load()), ast.Name(id="__hp_forward_args__", ctx=ast.Load())]
            item.keywords = [keyword for keyword in item.keywords if keyword.arg is not None]
    active = ast.unparse(ast.fix_missing_locations(lowered))
    return (f"if self.cp_enable:\n{textwrap.indent(active, '    ')}\n\n"
            "return self._forward_impl(__hp_forward_args__)")


def _module_function(tree: ast.Module, name: str) -> ast.AST | None:
440
441
442
443
444
445
446
447
448
            continue
        if not isinstance(node.value.func, ast.Name):
            continue
        delegate = functions.get(node.value.func.id)
        if delegate is not None and (
            _rewrite_request_callable(delegate) is not None or _returned_nested_callable(delegate) is not None
        ):
            return delegate
    return None
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
479
480
481
482
483
484
485
486
487
488


def _delegate_literals(factory: ast.FunctionDef, delegate: ast.FunctionDef, values: dict[str, Any]) -> dict[str, Any]:
    """Bind one same-module delegate using only native defaults, literals and configured arguments."""
    result = {}
    for name, expression in _delegate_expressions(factory, delegate).items():
        if name in WRAPPER_CONTEXT:
            if not isinstance(expression, ast.Name) or expression.id != name:
                raise RuntimeError(f"codegen cannot reinterpret native delegate context {name!r}")
            continue
        if isinstance(expression, ast.Name) and expression.id in values:
            result[name] = values[expression.id]
            continue
        try:
            result[name] = ast.literal_eval(expression)
        except (ValueError, TypeError):
            continue
    return result


def _delegate_expressions(factory: ast.FunctionDef, delegate: ast.FunctionDef) -> dict[str, ast.expr]:
    """Project one direct delegate call onto its native positional and keyword parameters."""
    call = next(node.value for node in ast.walk(factory) if isinstance(node, ast.Return)
                and isinstance(node.value, ast.Call) and isinstance(node.value.func, ast.Name)
                and node.value.func.id == delegate.name)
    parameters = (*delegate.args.posonlyargs, *delegate.args.args)
    expressions = {param.arg: value for param, value in zip(
        parameters[len(parameters) - len(delegate.args.defaults):], delegate.args.defaults,
    )}
    expressions.update({param.arg: value for param, value in zip(delegate.args.kwonlyargs, delegate.args.kw_defaults)
                        if value is not None})
    expressions.update({param.arg: value for param, value in zip(parameters, call.args)})
    if any(keyword.arg is None for keyword in call.keywords):
        raise RuntimeError("codegen cannot bind dynamic inner-wrapper delegate keywords")
    expressions.update({keyword.arg: keyword.value for keyword in call.keywords})
    return expressions


def _closure_source_bindings(
    owner: ast.AST | None, name: str | None, imported: dict[str, str],
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
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
538
def _closure_source_bindings(
    owner: ast.AST | None, name: str | None, imported: dict[str, str],
) -> dict[str, str]:
    """Keep native module imports and callable aliases outside the generated forward."""
    if owner is None or name is None:
        return {}
    forward = next((node for node in ast.walk(owner) if isinstance(node, ast.FunctionDef) and node.name == name), None)
    if forward is None:
        return {}
    captured = _captured_forward_names(owner, name)
    callables = {node.func.id for node in ast.walk(forward)
                 if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)}
    assignments = {node.targets[0].id: node for node in owner.body if isinstance(node, ast.Assign)
                   and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name)}
    bindings: dict[str, str] = {}
    attempted: set[str] = set()

    def resolve(symbol: str) -> bool:
        """Accept only aliases rooted in native imports, with no object construction."""
        if symbol in imported or symbol in bindings:
            return True
        if symbol in attempted:
            return False
        attempted.add(symbol)
        statement = assignments.get(symbol)
        if statement is None:
            return False
        if not _assigned_once(owner, symbol):
            return False
        value = statement.value
        if not _module_import_expression(value, imported):
            if symbol not in callables:
                return False
            while isinstance(value, ast.Attribute):
                value = value.value
            if not isinstance(value, ast.Name) or value.id == symbol or not resolve(value.id):
                return False
        bindings[symbol] = ast.unparse(statement)
        return True

    for symbol in sorted(captured):
        resolve(symbol)
    return bindings


def _assigned_once(owner: ast.AST, name: str) -> bool:
    """Require one lexical assignment before interpreting a captured native binding."""
    return sum(isinstance(node, ast.Name) and node.id == name and isinstance(node.ctx, ast.Store)
               for node in ast.walk(owner)) == 1


def _module_import_expression(value: ast.expr, imported: dict[str, str]) -> bool:
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
564
565
566
567
568


def _module_import_expression(value: ast.expr, imported: dict[str, str]) -> bool:
    """Recognize only a literal importlib module load, never an executor constructor."""
    if not isinstance(value, ast.Call) or not isinstance(value.func, ast.Attribute):
        return False
    function = value.func
    if not isinstance(function.value, ast.Name) or function.attr != "import_module":
        return False
    if imported.get(function.value.id) != "importlib" or value.keywords or len(value.args) != 1:
        return False
    return isinstance(value.args[0], ast.Constant) and isinstance(value.args[0].value, str)


def _wrapper_definition(node: ast.FunctionDef, body: str, bound: bool) -> str:
    """Reuse the native wrapper signature instead of guessing its variadic arguments."""
    node = deepcopy(node)
    node.name = "forward"
    node.decorator_list = []
    _strip_annotations(node)
    if not bound:
        parameters = node.args.posonlyargs if node.args.posonlyargs else node.args.args
        parameters.insert(0, ast.arg(arg="self"))
    if node.args.vararg:
        body = body.replace("__hp_forward_positional__", node.args.vararg.arg)
    if node.args.kwarg:
        body = body.replace("__hp_forward_keywords__", node.args.kwarg.arg)
    node.body = ast.parse(body).body
    return ast.unparse(ast.fix_missing_locations(node))


def _returned_nested_callable(tree: ast.AST) -> str | None:
    """Return a nested callable returned directly by an inner wrapper."""
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648


def _captured_forward_names(tree: ast.AST, name: str) -> set[str]:
    """Read lexical captures without importing or executing the wrapper."""
    pending = list(symtable.symtable(ast.unparse(tree), "<codegen wrapper>", "exec").get_children())
    while pending:
        scope = pending.pop()
        if scope.get_name() == name and scope.get_type() == "function":
            return set(scope.get_frees())
        pending.extend(scope.get_children())
    return set()


def _uses_native_cp_argument(tree: ast.FunctionDef) -> bool:
    """Do not reinterpret an unrelated local or reassigned mesh as native CP."""
    return (
        "cp_mesh" in {item.arg for item in (*tree.args.posonlyargs, *tree.args.args, *tree.args.kwonlyargs)}
        and not any(isinstance(item, ast.Name) and item.id == "cp_mesh" and isinstance(item.ctx, ast.Store)
                    for item in ast.walk(tree))
    )
676
677
678
679
680
681
682
683
684
685
686
687
688
689
    companion_attrs = _companion_attr_bindings(tree)
    original_forward = _original_forward_binding(tree)
    if original_forward is None:
        return None
    captured = _captured_forward_names(tree, replacement_name)
    runtime_cp = _uses_native_cp_argument(tree)
    variadic = {}
    if forward.args.vararg:
        variadic[forward.args.vararg.arg] = "__hp_forward_positional__"
    if forward.args.kwarg:
        variadic[forward.args.kwarg.arg] = "__hp_forward_keywords__"

    class ClosureBindings(ast.NodeTransformer):
        """Rewrite captured closure bindings to generated-instance state."""
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
        """Rewrite captured closure bindings to generated-instance state."""

        def visit_Name(self, node: ast.Name) -> ast.AST:  # pylint: disable=invalid-name
            """Rewrite a referenced symbol into its resolved source form."""
            if node.id in variadic and isinstance(node.ctx, ast.Load):
                return ast.copy_location(ast.Name(id=variadic[node.id], ctx=node.ctx), node)
            if node.id == target_name:
                return ast.copy_location(ast.Name(id="self", ctx=node.ctx), node)
            if literals is not None and node.id in captured and node.id in literals:
                return ast.copy_location(ast.parse(repr(literals[node.id]), mode="eval").body, node)
            if runtime_cp and node.id == "cp_mesh" and node.id in captured and node.id not in companion_attrs:
                return ast.copy_location(ast.parse(
                    "_get_cp_submesh(self._hp_boundary.compiled.mesh, "
                    "self._hp_boundary.compiled.mesh_dim_names)", mode="eval",
                ).body, node)
            attr = companion_attrs.get(node.id)
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
                    ctx=ast.Load(),
                )
            return node

    body = forward.body[1:] if ast.get_docstring(forward) is not None else forward.body
    lowered = [ClosureBindings().visit(ast.fix_missing_locations(node)) for node in body]
    if not lowered:
        return None
    _require_bound_captures(captured - set(bound_globals), lowered, replacement_name)
    return "\n".join(ast.unparse(node) for node in lowered)


def _require_bound_captures(captured: set[str], statements: list[ast.stmt], name: str) -> None:
    """Reject emitted closure state without a source-visible binding."""
    unresolved = sorted(captured & {
        node.id for statement in statements for node in ast.walk(statement)
        if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load)
    })
    if unresolved:
        raise RuntimeError(
            f"codegen: cannot inline {name!r}; unresolved captured state {unresolved}"
        )

hyper_parallel/codegen/inline/replacement_pass.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
    patch_set = InlinePatchSet()
    scopes_by_target: dict[tuple, set[str]] = defaultdict(set)
    fqns_by_target: dict[tuple, set[str]] = defaultdict(set)
    specs_by_target: dict[tuple, Any] = {}
    source_fqns_by_target: dict[tuple, set[str]] = defaultdict(set)
    shared_by_target: dict[tuple, list[tuple[str, ...]]] = defaultdict(list)
    for rule in rules:
        target = rule.replace_target
        if target is None:
            continue
        spec = _rule_replacement_spec(rule, target, model_type)
        if spec is None:
            continue
        key = (target, rule.module_type, spec.keyword_args)
        specs_by_target.setdefault(key, spec)
        if rule.construction is not None:
            source_fqns_by_target[key].update(rule.construction["source_fqns"])
        if len(rule.shared_fqns) > 1:
            shared_by_target[key].append(rule.shared_fqns)
        scopes_by_target[key].update(_scope_attrs(rule))
        fqns_by_target[key].update(fqn for fqn in rule.match if fqn)
    for target, spec in specs_by_target.items():
        scope_attrs = tuple(sorted(scopes_by_target[target]))
 94
 95
 96
 97
 98
 99
100
101
102
            patch_set.module_snippets.append(
                ModuleSnippetPatch(f"# Codegen replacement: {spec.replacement_note}")
            )
        patch_set.module_snippets.extend(spec.snippets)
        deferred = _requires_deferred_scope(spec, source_fqns_by_target[target],
                                            scope_attrs, fqns_by_target[target], shared_by_target[target])
        patch_set.constructor_replaces.append(
            ConstructorReplacePatch(
                old_ctor=spec.old_ctor,
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145


def _rule_replacement_spec(rule: SourceObservation, target: str, model_type: str | None) -> Any:
    """Keep observed constructors separate from legacy declaration-only rules."""
    if rule.construction is not None:
        return observed_constructor_spec(rule)
    spec = replacement_spec(target, model_type, module_type=rule.module_type)
    if spec is None:
        return None
    arguments = {item.split("=", 1)[0]: item for item in spec.keyword_args}
    arguments.update({item.split("=", 1)[0]: item for item in rule.construction_kwargs})
    return replace(spec, keyword_args=tuple(arguments.values()))


def _requires_deferred_scope(spec: Any, source_fqns: set[str], attrs: tuple[str, ...],
                             matches: set[str], shared: list[tuple[str, ...]]) -> bool:
143
144
145
146
147
148

def _requires_deferred_scope(spec: Any, source_fqns: set[str], attrs: tuple[str, ...],
                             matches: set[str], shared: list[tuple[str, ...]]) -> bool:
    """Do not widen a partial or shared instance replacement into a class rewrite."""
    available = {fqn for fqn in source_fqns if fqn.rsplit(".", 1)[-1] in attrs}
    return spec.defer_to_fqns or bool(shared) or bool(source_fqns) and available != matches
hyper_parallel/codegen/inline/strategy_pass.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
    Host classes come from each rule's observed FQNs. Local-compute methods
    are materialized separately from native records by ``emit.recorded``.
    """
    patch_set = InlinePatchSet()
    imported: set[str] = set()
    subclassed: dict[str, str] = {}
    for rule in rules:
        target = rule.inner_wrapper_target
        if target is None:
            continue
        spec = _rule_strategy(rule, target, model_type)
        if spec is None:
            continue
        patch_set.imports.extend(spec.imports)
        if target not in imported:
            imported.add(target)
            patch_set.module_snippets.extend(spec.snippets)
        if spec.subclass_shell is not None:
            _materialize_cp_forward(
                patch_set, spec, rule, target, model_type,
                boundary_classes, subclassed,
            )
    return patch_set
87
88
89
90
91
92
93
94
95
    boundary_classes: Mapping[str, str] | None,
    subclassed: dict[str, str],
) -> None:
    """Materialize CP dispatch in the original host class exactly once."""
    host_classes = ({rule.observed_wrapper["host_class"]} if rule.observed_wrapper is not None
                    else rule_block_classes(rule, boundary_classes))
    if not host_classes:
        raise _unmaterialized_strategy_error(spec.kind, target, rule, model_type)
    for host_class in sorted(host_classes):
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
    if not host_classes:
        raise _unmaterialized_strategy_error(spec.kind, target, rule, model_type)
    for host_class in sorted(host_classes):
        if host_class in subclassed:
            if subclassed[host_class] != (spec.definition or spec.subclass_shell):
                raise RuntimeError(f"codegen: conflicting CP bindings for source class {host_class!r}")
            continue
        subclassed[host_class] = spec.definition or spec.subclass_shell
        patch_set.forward_extracts.append(
            ForwardExtractPatch(
                class_name=host_class,
                method_name=spec.method_name,
124
125
126
127
128
129
130
131
132
133
def _rule_strategy(
    rule: SourceObservation, target: str, model_type: str | None,
) -> StrategySpec | None:
    """Use an already-installed factory-tail method or the declared wrapper source."""
    if rule.observed_wrapper is not None:
        return StrategySpec(
            kind=CP_ATTENTION_KIND, subclass_shell=rule.observed_wrapper["body"],
            definition=rule.observed_wrapper.get("definition"),
            imports=tuple(ImportPatch(module, (name,)) for module, name in rule.observed_wrapper["imports"]),
            snippets=tuple(ModuleSnippetPatch(source) for source in rule.observed_wrapper.get("bindings", ())),
131
132
133
134
135
            definition=rule.observed_wrapper.get("definition"),
            imports=tuple(ImportPatch(module, (name,)) for module, name in rule.observed_wrapper["imports"]),
            snippets=tuple(ModuleSnippetPatch(source) for source in rule.observed_wrapper.get("bindings", ())),
        )
    return strategy_spec(target, model_type, inner_wrapper=True, construction_kwargs=rule.construction_kwargs)
hyper_parallel/codegen/model_build_overlay.py
150
151
152
153
154
155
156
157
158
159
160
161
        family = get_family_build_info(candidate)
        if family is not None:
            # Model depth is needed by expert constructors even when their source
            # does not retain a config. Keep the native result without runtime owners.
            context = args[0] if args else kwargs["context"]
            construction_context = {f"{axis}_size": size for axis, size in family.resolved.axis_sizes.items()}
            if context.get("num_layers") is not None:
                construction_context["num_layers"] = context["num_layers"]
            pending[(target.module_fqns, id(candidate))]["family_request"] = {
                "factory": replacement_api._symbol_path(family.request.target),  # pylint: disable=protected-access
                "kwargs": dict(family.request.kwargs),
                "context": construction_context,
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
        return candidate, transforms

    def _observe_install(root: Any, candidates: Any) -> Any:
        candidates = tuple(candidates)
        source_scopes = {}
        for fqn, module in root.named_modules(remove_duplicate=False):
            source_scopes.setdefault(replacement_api._symbol_path(type(module)), []).append(fqn)
        result = original_install(root, candidates)
        for fqns, _, candidate in candidates:
            record = pending.pop((fqns, id(candidate)), None)
            if record is not None:
                record["construction"] = {
                    "implementation": record["replacement_type"],
                    "source_fqns": sorted(source_scopes.get(record["source_type"], [])),
                }
                if hasattr(candidate, "rms_norm_cast_order"):
                    record["construction"]["arguments"] = {
                        "cast_order": candidate.rms_norm_cast_order, "fp32_weight": candidate.fp32_weight,
                    }
                applications.append(record)
        return result
335
336
337
338
339
340
341
342
343
            getattr(distributed_setup, "low_precision_config", None),
            load_base_model,
            session,
        )
        model_builder._tie_model_weights_before_parallelism(model)  # pylint: disable=protected-access
        if freeze_config is not None:
            model_builder._apply_parameter_freezing(  # pylint: disable=protected-access
                model,
                freeze_config,
345
346
347
348
349
350
351
352
353
354
355
356
357
358
        model_builder._apply_model_method_replacements(  # pylint: disable=protected-access
            model, distributed_setup, getattr(distributed_setup, "low_precision_config", None),
        )
        _observe_plan(model, mesh, sharding_planner, is_hf_model, session)
        if on_observed is not None:
            on_observed(model)
        else:
            snapshot = _publish_session(session, artifact_dir, result)
            result.snapshot = snapshot
            model._hp_codegen_snapshot = snapshot  # pylint: disable=protected-access
        model.train()
        return model

    return _build_model
374
375
376
377
378
379
380
381
382
383
384
385
386
387
    """
    model_class = auto_model._BaseHyperAutoModelClass  # pylint: disable=protected-access
    original = model_class.__dict__["_build_model"]
    result = CodegenModelBuildResult()
    pending = []

    def _defer(model: Any) -> None:
        """Keep live references only inside this factory observation scope."""
        result.model = model
        pending.append((model, {fqn: module.forward for fqn, module in model.named_modules()}))

    model_class._build_model = classmethod(  # pylint: disable=protected-access
        _codegen_build_model(session, artifact_dir, result, _defer if defer_publish else None)
    )
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
        _codegen_build_model(session, artifact_dir, result, _defer if defer_publish else None)
    )
    try:
        yield result
        if pending:
            model, originals = pending.pop()
            if result.model is not model:
                raise RuntimeError("codegen outer factory returned a different model root")
            session.observe_final_forwards(model, originals)
            result.snapshot = _publish_session(session, artifact_dir, result)
    finally:
        pending.clear()
        result.model = None
        model_class._build_model = original  # pylint: disable=protected-access


__all__ = ["CodegenModelBuildResult", "use_codegen_model_build_overlay"]
hyper_parallel/codegen/plan/observation.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172


def observe_final_forwards(model: Any, originals: dict[str, Any]) -> list[dict[str, Any]]:
    """Read only methods changed after inner construction; never replay their factories."""
    additions = []
    for fqn, original in originals.items():
        target = model.get_submodule(fqn)
        forward = target.forward
        if getattr(forward, "__func__", forward) is getattr(original, "__func__", original):
            continue
        if getattr(original, "__self__", None) is not target:
            raise RuntimeError(f"codegen outer factory replaced observed module {fqn!r}")
        source = observe_wrapper_source(target, forward, vars(target), original_forward=original)
        source.update(host_class=type(target).__name__,
                      target_type=f"{type(target).__module__}:{type(target).__qualname__}")
        function = getattr(forward, "__func__", forward)
        qualname = getattr(function.__code__, "co_qualname", function.__qualname__)
        additions.append({"match": fqn, "inner_target": "self", "observed_wrapper": source,
                          "inner_wrapper": f"{function.__globals__['__name__']}.{qualname}"})
    return additions
hyper_parallel/codegen/session.py
44
45
46
47
48
49
50
51
52
        self._source_recorded = False
        self._replacements_recorded = False
        self._diagnostics_recorded = False
        self._finished = False
        self._final_forwards_recorded = False
        self._snapshot: Optional[CodegenSnapshot] = None

    @property
    def status(self) -> CodegenStatus:
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
        self.record_plan(observed_plan)

    def observe_final_forwards(self, model: Any, originals: Mapping[str, Any]) -> None:
        """Append factory-tail facts once, before freezing the existing native plan."""
        self._require_open(CodegenStatus.DERIVED, CodegenStatus.NOT_REQUIRED)
        if self._final_forwards_recorded:
            raise RuntimeError("codegen final forwards have already been observed")
        additions = observe_final_forwards(model, originals)
        self._final_forwards_recorded = True
        if additions:
            if self._plan is None:
                self._plan = observe_emission_plan(None, None).to_dict()
            self._plan.setdefault("injections", []).extend(additions)
            self._status = CodegenStatus.DERIVED
            self._reason = None

    def record_diagnostics(self, diagnostics: Mapping[str, Any]) -> None:
        """Record optional counters and audit facts once."""
        self._require_open()