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 91.8% 576,578,589,593
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 100%  
hyper_parallel/codegen/inline/attention.py 100%  
hyper_parallel/codegen/inline/component_source.py 93.1% 44,85,100,105,161-162
hyper_parallel/codegen/inline/declaration_edits.py 95.5% 74
hyper_parallel/codegen/inline/forward_edits.py 90.9% 65,69,73
hyper_parallel/codegen/inline/framework_spec.py 98.2% 532
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 96.3% 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 100%  
hyper_parallel/codegen/model_build_overlay.py 92.9% 175,389
hyper_parallel/codegen/plan/observation.py 87.5% 162,164
hyper_parallel/codegen/session.py 100%  
hyper_parallel/codegen/emit/modeling.py
572
573
574
575
576
577
578
579
580
581
582
        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
585
586
587
588
589
590
591
592
593
594
595
596
597
                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(
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/inline/component_source.py
40
41
42
43
44
45
46
47
48
        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)
    node = ast.parse(textwrap.dedent(inspect.getsource(component))).body[0]
    parts = [(component, node)]
    if "forward" not in component.__dict__:
        owner = next(base for base in component.__mro__[1:] if "forward" in base.__dict__)
81
82
83
84
85
86
87
88
89
    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)
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
              + 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)}

157
158
159
160
161
162
    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/declaration_edits.py
70
71
72
73
74
75
76
77
        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
hyper_parallel/codegen/inline/forward_edits.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
    """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)

hyper_parallel/codegen/inline/framework_spec.py
528
529
530
531
532
533
534
535
536
    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,
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
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/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
        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()
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)