This is the pytorch repo. When I use torch.compile to compile a function that calls…
- User
This is the pytorch repo. When I use torch.compile to compile a function that calls another already compiled function, will there be optimizations across the function boundary?
- Assistant
Short answer: generally no—not if the callee is already wrapped with its own
torch.compile.torch.compileoptimizes at the level of the captured FX graph. If you compile two functions separately and one calls the other, you usually end up with separate compiled regions, so Inductor can’t do cross-boundary fusion/scheduling across them.What does allow cross-boundary optimization is compiling only the outer function (and letting Dynamo trace through normal Python helper calls when possible). In that case, both bodies can land in one graph and be optimized together.
Practical rule of thumb:
- Compile the top-level entrypoint once for best global optimization.
- Pre-compiling inner helpers tends to create boundaries (good for modularity/reuse, not for cross-function fusion).
- User
Can we somehow unwrap the compiled function to the non-compiled version, and only compile the outer function?
- Assistant
Yes—best approach is to keep/use the original callable and compile only the outer one.
def inner(x): return x.sin() * 2 inner_c = torch.compile(inner) # maybe already done def outer(x): return inner(x) + 1 # call ORIGINAL inner, not inner_c outer_c = torch.compile(outer)If you already only have
inner_c, there are a couple of ways to get back to the original, but they’re less stable:inner_c.__wrapped__(often present)inner_c._torchdynamo_orig_callable(private/internal)
Example:
inner_orig = getattr(inner_c, "__wrapped__", None) or getattr(inner_c, "_torchdynamo_orig_callable", None)Notes:
- Relying on
__wrapped__/_torchdynamo_orig_callableis not as robust as just keepinginneraround yourself. - For
nn.Module, similarly keep the original module object and compile the outer entrypoint that calls it.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.