Diff Coverage

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

Source File Diff Coverage (%) Missing Lines
hyper_parallel/codegen/astkit/edits.py 100%  
hyper_parallel/codegen/build.py 100%  
hyper_parallel/codegen/emit/modeling.py 40.8% 537,570-594,691-693
hyper_parallel/codegen/emit/parallel.py 84.6% 611,613,616,619,630,633
hyper_parallel/codegen/emit/patches.py 100%  
hyper_parallel/codegen/emit/replacement.py 100%  
hyper_parallel/codegen/emit/snapshot_patches.py 0.0% 174,181
hyper_parallel/codegen/inline/component_source.py 92.1% 54,69,74,130-131
hyper_parallel/codegen/inline/forward_edits.py 51.5% 46-47,62-75
hyper_parallel/codegen/inline/framework_spec.py 97.9% 531
hyper_parallel/codegen/inline/ir.py 100%  
hyper_parallel/codegen/inline/patch_engine.py 95.7% 208,216,229,373,414,495
hyper_parallel/codegen/inline/pipeline.py 81.5% 226-227,229-230,401
hyper_parallel/codegen/inline/recognition.py 90.2% 281,310,317,320,335,344,347-348,352,368,372,501
hyper_parallel/codegen/inline/replacement_pass.py 95.2% 138
hyper_parallel/codegen/inline/strategy_pass.py 91.7% 187
hyper_parallel/codegen/model_build_overlay.py 89.3% 175,389,391
hyper_parallel/codegen/plan/observation.py 80.0% 162,164,171
hyper_parallel/codegen/session.py 42.9% 113,115-121
hyper_parallel/codegen/emit/modeling.py
533
534
535
536
537
538
539
540
541
) -> 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))
    if (
        "forward" in _class_methods(host)
        and "cp_enable" in _class_state_names(host)
        and _class_dispatch_reads_state(host, "cp_enable")
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598


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 = definition.replace("self._forward_impl(", "super().forward(")
    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
687
688
689
690
691
692
693
694
695
696
697

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."""
hyper_parallel/codegen/emit/parallel.py
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
    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]:
626
627
628
629
630
631
632
633
634
635
636
637
    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())))
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/component_source.py
50
51
52
53
54
55
56
57
58
    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)
    target_names, original_names = _bound_capture_names(captures, target, original_forward)
    bindings, literals = _closure_bindings(function, captures, companions)
65
66
67
68
69
70
71
72
73
74
75
76
77
              + 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)
    if body is None:
        raise RuntimeError(f"codegen cannot lower observed forward {forward.__qualname__}")
    globals_used = _referenced_global_names(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,
            "definition": _wrapper_definition(node, body, getattr(forward, "__self__", None) is target)}

126
127
128
129
130
131
    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)
hyper_parallel/codegen/inline/forward_edits.py
42
43
44
45
46
47
48
49
50
51
        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


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")
        definition = 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."""
hyper_parallel/codegen/inline/framework_spec.py
527
528
529
530
531
532
533
534
535
    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)
    return ReplacementSpec(
        old_ctor=class_name_of(rule.module_type), new_ctor=name,
        imports=(ImportPatch(module_name, (name,)),), mode=mode,
        keyword_args=tuple(arguments), remove_class=False,
hyper_parallel/codegen/inline/patch_engine.py
204
205
206
207
208
209
210
211
212
    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:
212
213
214
215
216
217
218
219
220
        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:
225
226
227
228
229
230
231
232
    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)

369
370
371
372
373
374
375
376
377
    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:
410
411
412
413
414
415
416
417
        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

491
492
493
494
495
496
497
498
    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"
hyper_parallel/codegen/inline/pipeline.py
222
223
224
225
226
227
228
229
230
231
232
233
234
        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 = patch.definition.replace("self._forward_impl(", "super().forward(")
            snippet = (f"class {patch.class_name}({base}):\n"
                       + 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"
397
398
399
400
401
402
403
404
405
        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
277
278
279
280
281
282
283
284
285
    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
306
307
308
309
310
311
312
313
314
    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:
313
314
315
316
317
318
319
320
321
322
323
324

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)
331
332
333
334
335
336
337
338
339
    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."""
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
    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

364
365
366
367
368
369
370
371
372
373
374
375
376
    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)
497
498
499
500
501
502
503
504
505
        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."""
hyper_parallel/codegen/inline/replacement_pass.py
134
135
136
137
138
139
140
141
    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()))
hyper_parallel/codegen/inline/strategy_pass.py
183
184
185
186
187
188
189
190
191
    rule: SourceObservation, target: str, model_type: str | None, inner_wrapper: bool,
) -> StrategySpec | None:
    """Use an already-installed factory-tail method or the declared wrapper source."""
    if inner_wrapper and 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"]),
        )
hyper_parallel/codegen/model_build_overlay.py
171
172
173
174
175
176
177
178
179
                    "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
385
386
387
388
389
390
391
392
393
394
395
        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
hyper_parallel/codegen/plan/observation.py
158
159
160
161
162
163
164
165
166
167
168
    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)
167
168
169
170
171
                      target_type=f"{type(target).__module__}:{type(target).__qualname__}")
        function = getattr(forward, "__func__", forward)
        additions.append({"match": fqn, "inner_target": "self", "observed_wrapper": source,
                          "inner_wrapper": f"{function.__globals__['__name__']}.{function.__code__.co_qualname}"})
    return additions
hyper_parallel/codegen/session.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
    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()