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 93.4% 593-594,596,642,644,655
hyper_parallel/codegen/emit/parallel.py 87.2% 547,550,553,564,567
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 50.0% 249-252
hyper_parallel/codegen/inline/component_source.py 85.5% 46,66,125,144,152-153,167,172,243-245,256-264,270-272,275
hyper_parallel/codegen/inline/declaration_edits.py 100%  
hyper_parallel/codegen/inline/forward_edits.py 85.7% 65,69,73,120-121
hyper_parallel/codegen/inline/framework_spec.py 98.4% 529
hyper_parallel/codegen/inline/ir.py 100%  
hyper_parallel/codegen/inline/meta_plan.py 100%  
hyper_parallel/codegen/inline/patch_engine.py 93.3% 212-214,216,223,232,246,263,407,448,529
hyper_parallel/codegen/inline/pipeline.py 95.3% 220,384
hyper_parallel/codegen/inline/recognition.py 90.5% 276,279,301,330,337,340,355,364,367-368,372,388,392,457,464-465,482,495,515,544,546,639
hyper_parallel/codegen/inline/replacement_pass.py 95.2% 138
hyper_parallel/codegen/inline/source_plan.py 100%  
hyper_parallel/codegen/inline/strategy_pass.py 95.8% 68
hyper_parallel/codegen/model_build_overlay.py 93.8% 179,393
hyper_parallel/codegen/plan/observation.py 87.5% 162,164
hyper_parallel/codegen/session.py 100%  
hyper_parallel/codegen/emit/modeling.py
589
590
591
592
593
594
595
596
597
598
599
600
        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)
638
639
640
641
642
643
644
645
646
647
648
        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
651
652
653
654
655
656
657
658
659
                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
hyper_parallel/codegen/emit/parallel.py
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
    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]:
560
561
562
563
564
565
566
567
568
569
570
571
    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/attention.py
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
42
43
44
45
46
47
48
49
50
        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)
62
63
64
65
66
67
68
69
70
    """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)})"
121
122
123
124
125
126
127
128
    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
140
141
142
143
144
145
146
147
148
    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)
148
149
150
151
152
153
154
155
156
157
    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"
163
164
165
166
167
168
169
170
171
172
173
174
175
    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)}

239
240
241
242
243
244
245
246
247
248
249
            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:
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
        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."""
266
267
268
269
270
271
272
273
274
275
276

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/forward_edits.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
    """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)
116
117
118
119
120
121
122
123
124
125
        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))])
hyper_parallel/codegen/inline/framework_spec.py
525
526
527
528
529
530
531
532
533
        if key in parameters and key not in ignored and key != "module_fqn" and value != "None":
            arguments.append(f"{key}={value}")
    mode = _observed_constructor_mode(component, parameters)
    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
208
209
210
211
212
213
214
215
216
217
218
219
220
        return f"{patch.new_ctor}(module={original}{extra})"
    if patch.mode == "construct":
        return _direct_constructor_replacement(tree, call, patch)
    if patch.mode == "name":
        _, function_end = _node_span(call.func, offsets)
        original = source[function_end:end]
        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 _direct_constructor_replacement(tree: ast.Module, call: ast.Call, patch: ConstructorReplacePatch) -> str:
219
220
221
222
223
224
225
226
227

def _direct_constructor_replacement(tree: ast.Module, call: ast.Call, patch: ConstructorReplacePatch) -> str:
    """Keep source defaults when a concrete member has different direct-construction defaults."""
    if any(isinstance(arg, ast.Starred) for arg in call.args) or any(kw.arg is None for kw in call.keywords):
        raise ValueError(f"codegen: {patch.old_ctor} has unpacked arguments that cannot be bound offline")
    positional, defaults = _source_constructor_parameters(tree, patch.old_ctor)
    supplied = set(positional[:len(call.args)]) | {kw.arg for kw in call.keywords}
    arguments = list(call.args)
    keywords = {kw.arg: kw.value for kw in call.keywords}
228
229
230
231
232
233
234
235
236
    keywords.update({name: value for name, value in defaults.items() if name not in supplied})
    overrides = ast.parse(f"_constructor({', '.join(patch.keyword_args)})", mode="eval").body
    for kw in overrides.keywords:
        if kw.arg in positional[:len(arguments)]:
            arguments[positional.index(kw.arg)] = kw.value
        else:
            keywords[kw.arg] = kw.value
    result = ast.Call(func=ast.Name(id=patch.new_ctor, ctx=ast.Load()), args=arguments,
                      keywords=[ast.keyword(arg=name, value=value) for name, value in keywords.items()])
242
243
244
245
246
247
248
249
250
    owner = next((item for item in tree.body if isinstance(item, ast.ClassDef) and item.name == name), None)
    constructor = next((item for item in owner.body if isinstance(item, ast.FunctionDef) and item.name == "__init__"),
                       None) if owner is not None else None
    if constructor is None:
        raise ValueError(f"codegen: {name} has no source constructor for direct replacement")
    positional = [item.arg for item in (*constructor.args.posonlyargs, *constructor.args.args)][1:]
    defaults = dict(zip(positional[-len(constructor.args.defaults):], constructor.args.defaults))
    defaults.update({arg.arg: value for arg, value in zip(constructor.args.kwonlyargs, constructor.args.kw_defaults)
                     if value is not None})
259
260
261
262
263
264
265
266
    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)

403
404
405
406
407
408
409
410
411
    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:
444
445
446
447
448
449
450
451
        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

525
526
527
528
529
530
531
532
    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
216
217
218
219
220
221
222
223
            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)

380
381
382
383
384
385
386
387
388
        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
272
273
274
275
276
277
278
279
280
281
282
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

297
298
299
300
301
302
303
304
305
    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
326
327
328
329
330
331
332
333
334
    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:
333
334
335
336
337
338
339
340
341
342
343
344

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)
351
352
353
354
355
356
357
358
359
    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."""
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
    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

384
385
386
387
388
389
390
391
392
393
394
395
396
    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)
453
454
455
456
457
458
459
460
461
    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
460
461
462
463
464
465
466
467
468
469
            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]:
478
479
480
481
482
483
484
485
    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

491
492
493
494
495
496
497
498
499
    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)
511
512
513
514
515
516
517
518
519
        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
540
541
542
543
544
545
546
547
548
549
550
    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:
635
636
637
638
639
640
641
642
643
        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
64
65
66
67
68
69
70
71
72
        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)
hyper_parallel/codegen/model_build_overlay.py
175
176
177
178
179
180
181
182
183
                    "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
389
390
391
392
393
394
395
396
397
        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)