Skip to content

WASM: defer Numba gufunc compilation to first call (#930) - #957

Merged
mmcky merged 6 commits into
mainfrom
wasm/930-lazy-gufuncs
Sep 23, 2026
Merged

mmcky merged 6 commits into
mainfrom
wasm/930-lazy-gufuncs

Conversation

@mmcky

@mmcky mmcky commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Defers the four eagerly-compiled Numba gufuncs to first call, so they are no longer compiled during import quantecon. Part of #930, part of #925 (Phase 1).

This is @oyamad's implementation from the wasm-930-dynamic-gufuncs branch, opened as a PR in place of #943, which is closed.

What changes

Callable File Change
_probvec_parallel random/utilities.py explicit-signature gufunc built by a memoised factory on first call
_probvec_cpu random/utilities.py same
_sample_without_replacement random/utilities.py dynamic (signature-less) gufunc; caller supplies the output array
_ints_arr_to_bits game_theory/vertex_enumeration.py same

The explicit signature is kept for both _probvec targets deliberately, and the code now says why: the parallel target requires it, and an explicit-signature gufunc must not be mixed with a dynamic one of the same kernel under cache=True, because they share an incompatible cache entry (numba/numba#10128). That constraint was previously undocumented. The factories are memoised with functools.cache; main now declares requires-python = ">=3.12", so this adds no version floor.

sample_without_replacement now checks n with numbers.Integral before sampling. Under the old explicit signature NumPy rejected a float n with a TypeError; the dynamic gufunc would instead fail inside Numba with a TypingError, which is not a TypeError subclass. The check keeps the old contract, and a new test pins it: it passes on main and fails without the check.

No public API change. qe.random.probvec(..., parallel=...), qe.random.sample_without_replacement(...) and qe.game_theory.vertex_enumeration(...) are untouched.

Verification

Run on this branch merged with current main (which brings in #970 and the Numba 0.68.0rc1 CI bump from #968), against Numba 0.62.1 and 0.68.0rc1:

  • Full suite: 737 passed
  • flake8 --select=F401,F405,E231 quantecon: clean
  • Outputs of probvec (both targets), sample_without_replacement, random_mixed_actions and vertex_enumeration are bitwise identical to main's, with a cold and a warm cache
  • Deferral: after import quantecon, both _probvec factories are empty and the two dynamic gufuncs have no compiled loops; on main all four have one
  • Upgrade over a stale cache: a __pycache__ populated by main's explicit-signature gufuncs, then reused by this branch's code at the same path, runs cleanly on both Numba versions

Native import quantecon, single runs:

main this PR
Cold cache, Numba 0.62.1 1.54 s 0.72 s
Cold cache, Numba 0.68.0rc1 1.58 s 0.61 s
Warm cache, Numba 0.62.1 0.67 s 0.64 s
Warm cache, Numba 0.68.0rc1 0.61 s 0.53 s

The cold-cache rows are the closer native proxy for the browser, where these gufuncs are never cached (next section).

The measurement this still needs

#930's acceptance criterion 1 — warm-cache import quantecon timed in JupyterLite, before and after — is not satisfied by the native numbers above, and remains open. emscripten-forge Numba patch 0007 forces cache=False for every @guvectorize, so in the browser these four compiles are still paid once per session either way. This change moves that cost from import to first call rather than removing it, which is a clear win only if most notebooks never reach probvec, sample_without_replacement or vertex_enumeration.

For that reason this PR is part of #930 and does not close it. Either a manual JupyterLite timing settles criterion 1, or a maintainer waives it explicitly on #930, as that issue requires.

Unaffected

#944 (RuntimeError: no compiled object yet when a cache-miss caller links a cache-restored callee, reported upstream as emscripten-forge/recipes#6309) is unaffected. This change narrows the exposure but does not resolve it, and should not be cited as doing so.

Merging

The repo squash-merges with the commit messages as the default body, and two of them describe states the final diff no longer has (a requires-python bump, then lru_cache). Suggested replacement for the body above GitHub's --------- trailer block. Keep that block: under a squash merge it is what carries @oyamad's authorship onto main.

Defer the four eagerly compiled `guvectorize` functions to first call,
so `import quantecon` no longer compiles them:

* `_ints_arr_to_bits` and `_sample_without_replacement` become dynamic
  (signature-less) gufuncs; callers now supply the output array.
* `_probvec_parallel` and `_probvec_cpu` are built on first call by
  `functools.cache`d factories and keep their explicit signatures: the
  parallel target requires one, and an explicit-signature and a dynamic
  gufunc of the same kernel must not be mixed under `cache=True`
  (numba/numba#10128).
* `sample_without_replacement` checks that `n` is an integer, keeping
  the TypeError the explicit signature used to raise for a float `n`.

No public API change. Part of #930.

Part of #930. Replaces #943.

🤖 Generated with Claude Code

oyamad and others added 2 commits September 9, 2026 19:27
`import quantecon` compiled four `guvectorize` functions eagerly because
of their explicit type signatures. In the in-browser (Emscripten) Numba
build, where `cache=True` is disabled for gufuncs, that cost was paid on
every session on the import path. Defer all four to first call:

* `_ints_arr_to_bits` and `_sample_without_replacement` become dynamic
  (signature-less) gufuncs; the callers now supply the output array.

* `_probvec_parallel` and `_probvec_cpu` are constructed on first call
  by `functools.cache`d factories, keeping their explicit signatures.
  The parallel target requires one, and the cpu variant keeps one too:
  an explicit-signature gufunc and a dynamic gufunc of the same kernel
  share an incompatible cache entry when `cache=True`, which crashes
  the process.

Public API is unchanged. `functools.cache` requires Python 3.9, so
`requires-python` is raised from 3.7 to 3.9.

Co-Authored-By: Claude Fable 5 <[email protected]>
Two adjustments to the cherry-picked implementation, neither changing
its behaviour.

`functools.cache` is an alias for `functools.lru_cache(maxsize=None)`
added in 3.9 purely for convenience, so using `lru_cache` directly gives
identical memoisation without imposing a version floor.

That removes the need for the `requires-python` bump to 3.9, which is
reverted here: the floor is stale at ">=3.7" while CI tests 3.12-3.14,
but correcting it is #864's business and does not belong in a WASM
change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

The changes are localized, call sites appear consistently updated, and no correctness issues were found in the modified regions.

Pull request overview

Defers several Numba guvectorize compilations from import time to first call to reduce import quantecon overhead (especially relevant for WASM/JupyterLite where persistent ufunc caching is unavailable).

Changes:

  • Replaces module-level _probvec_parallel / _probvec_cpu gufunc objects with lazily-constructed, lru_cache-memoized factories.
  • Converts _sample_without_replacement and _ints_arr_to_bits to dynamic (signature-less) gufuncs, with callers supplying the output arrays.
  • Updates internal call sites to use the new factory / output-supplied calling patterns.
File summaries
File Description
quantecon/random/utilities.py Lazily constructs the _probvec_* gufuncs; makes _sample_without_replacement a dynamic gufunc with caller-supplied output.
quantecon/game_theory/vertex_enumeration.py Updates _ints_arr_to_bits to a dynamic gufunc and updates the caller to provide an output buffer.
quantecon/game_theory/random.py Updates _probvec_cpu usage to call the new memoized factory.
Review details
  • Files reviewed: 3/3 changed files
  • Comments generated: 1
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread quantecon/game_theory/random.py Resolved
@coveralls

coveralls commented Sep 9, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 93.992% (+0.01%) from 93.981% — wasm/930-lazy-gufuncs into main

oyamad and others added 2 commits September 10, 2026 10:54
Resolves two docstring conflicts with #864 by keeping this branch's
text: the `_sample_without_replacement` docstring (rewritten here;
already spells "compiled") and the `_ints_arr_to_bits` example (the
1-D-to-scalar form removed here no longer needs its repr updated).
`requires-python` takes main's ">=3.12".

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@oyamad

oyamad commented Sep 10, 2026

Copy link
Copy Markdown
Member

@mmcky Thanks!
Current main merged into this branch where requires-python = ">=3.12", I replaced ``functools.lru_cache(maxsize=None)with the shorterfunctools.cache`.

mmcky and others added 2 commits September 23, 2026 14:08
With the explicit `(i8, f8[:], i8[:])` signature, NumPy rejected a
float `n` with a TypeError before the kernel ran. The dynamic gufunc
compiles for whatever dtype arrives, so the same call now fails inside
Numba with a TypingError, which is not a TypeError subclass. Check `n`
up front with the `numbers.Integral` idiom used elsewhere in the
package, and pin the contract with a test that also passes on main.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@mmcky

mmcky commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

@oyamad I added 04f654a after your ready: sample_without_replacement now checks n with numbers.Integral, so a float n raises TypeError as it did under the explicit signature, rather than Numba's TypingError. Test added; description updated.

@mmcky
mmcky merged commit 79360d6 into main Sep 23, 2026
15 checks passed
@mmcky
mmcky deleted the wasm/930-lazy-gufuncs branch September 23, 2026 04:19
@mmcky mmcky mentioned this pull request Sep 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants