`@wp.kernel(module="unique")` Python-side decoration cost makes factory-pattern kernels expensive
@wp.kernel(module="unique") does enough Python-side work per call (source extraction, ast.parse, AST walk for reference collection / wp.static resolution / kernel_dim inference, module hashing, recursive @wp.func dep hashing) that factory functions producing parameterized kernels pay 1–4 ms per declaration, depending on kernel size.
Measured on mjwarp's 9 representative kernel factories (20 calls each, with the project's user-side cache_kernel memoization decorator bypassed to measure raw cost): ~167 ms for 180 declarations. The same workload with mjwarp's cache_kernel enabled is ~0.12 ms — a ~1000× ratio.
All of this work is recomputed on every factory call, even when the call produces a kernel that already exists in user_modules under the same hash-derived name.
The current best-practice workaround in downstream projects is to maintain a user-side memoization layer wrapping the factory (e.g. mjwarp's cache_kernel decorator), which makes the pattern usable but pushes what is in principle a Warp-internal cost into every downstream codebase.
Repro: mjwarp's _equality_flex, _sap_project, _solve_LD_sparse_island, etc. — any factory that returns @wp.kernel(module="unique", ...) with the inner function capturing factory arguments via closure. Can provide a minimal standalone repro if useful.
@fem.cache.dynamic_kernel still exists for the same reason -- the downside is that is requires specifying explicitly the memoization key (it does additional things though, like hashing kernel options, so still slower than plain caching)
Thanks - I didn't realize. I have a series of commits that give this pattern an order of magnitude speedup, but nothing beats just caching the kernel as a consumer indeed. So I think this line of work will greatly improve things but it will not even get close to just reusing the python kernel object. So if you know what you are doing, this should be the way to go.
Update: 81f95f838f72c7315d572351f7abe4e9ec9d51e6 landed on main as part of the kernel-factory decoration-cost work.
This change speeds up Adjoint.replace_static_expressions, one of the Python-side passes run while declaring kernels. It replaces the previous ast.NodeTransformer traversal, which rebuilt most of the AST even when few calls were wp.static, with a direct depth-first AST walker that only records and applies actual static-expression replacements. Loop-variable-dependent wp.static expressions are still deferred as before.
This does not replace downstream kernel-object caching, but it removes redundant AST traversal and rebuild work from Warp’s internal declaration path and is one of the incremental fixes for the broader cost profile.
Progress update: 18f59c97d0864309cf0c658344047b46f5455d08 and 69a08a1c55dda66d33d1d7db1256077d88f53a2e landed two complementary optimizations for repeated @wp.kernel(module="unique") factory declarations.
18f59c97d0864309cf0c658344047b46f5455d08 defers dependency scanning until after the unique-module deduplication decision. A duplicate declaration still computes the same module hash, but it no longer scans dependencies, creates dependency edges, and then removes those edges when its temporary module is discarded. Only a unique module that is retained performs the scan.
69a08a1c55dda66d33d1d7db1256077d88f53a2e caches extracted source, the parsed AST, and the collected reference-node tuple by Python code-object identity. Redeclarations from the same factory reuse those immutable products while closure and global reference resolution remain per-adjoint, preserving distinct hashes for different captured values and rebound globals.
Together, these changes remove repeated source extraction, parsing, reference-node discovery, and dependency-edge bookkeeping from eligible duplicate declarations. Transformers, explicit source=, and sources containing static remain excluded from source-tree sharing because those paths can rewrite the AST.
Public API behavior:
- No new API or semantic change is introduced.
- Existing
@wp.kernel(module="unique")factory declarations become cheaper when they are eligible for sharing or deduplicate to an existing module. - This does not replace downstream kernel-object memoization. Module hashing, per-adjoint reference resolution, recursive function hashing, and unresolved
wp.staticprocessing still occur per declaration.
Test coverage:
- 18f59c97d0864309cf0c658344047b46f5455d08 did not add or modify tests. Existing
warp/tests/test_unique_module.pycoverage exercises unique-module reuse, closure disambiguation, deferred static expressions, and discarded dependency edges. - 69a08a1c55dda66d33d1d7db1256077d88f53a2e added five tests in
warp/tests/test_codegen.py:test_shared_source_across_redeclarationstest_rebind_observed_through_shared_sourcetest_recompiled_equal_code_object_reextractstest_shared_source_lookup_requires_identitytest_shared_source_evicted_on_code_object_death
Behavioral verification:
- A targeted factory probe confirmed that 181 declarations reused one source extraction and parsed tree. The 179 duplicate declarations performed no dependency scans; only the two distinct modules that were retained were scanned. Kernels with distinct captured values produced the expected results.
- The original representative mjwarp workload still needs to be rerun to establish the cumulative end-to-end improvement.
The umbrella CHANGELOG entry now records the factory-kernel redeclaration speedup.
This is substantial progress, but #1486 should remain open while the representative workload and remaining per-declaration hashing costs are evaluated.
Spotted Improvements:
- Add a non-timing regression test asserting that duplicate unique-module declarations scan dependencies only when their module is retained.
- Record the representative factory benchmark to quantify cumulative improvement and remaining declaration cost.