Skip to content

JuliaCall: add nogil option to seval - #850

Open
MilesCranmerBot wants to merge 1 commit into
JuliaPy:mainfrom
MilesCranmerBot:juliacall-nogil-load
Open

MilesCranmerBot wants to merge 1 commit into
JuliaPy:mainfrom
MilesCranmerBot:juliacall-nogil-load

Conversation

@MilesCranmerBot

Copy link
Copy Markdown
Contributor

Why

Python packages built on JuliaCall usually load their Julia package at import time with jl.seval("using Foo"). That load does not use Python, but it holds the GIL, so the package cannot import its Python dependencies at the same time. This adds jl.seval(code, nogil=True) so the load can overlap with Python work on another thread.

What changed

  • ModuleValue.seval(code, *, nogil=False). With nogil=True, the string is converted with the GIL held, then parsed and evaluated with the GIL unlocked, and the result is converted with the GIL held again.
  • The new Julia method is precompiled, like seval in Precompile the first calls of a JuliaCall session #837.
  • Reference docs, a short example in the multi-threading guide, and a changelog entry.

Scope

  • Same contract as _jl_call_nogil: the code, and the __init__ of every package it loads, must not use Python.
  • Does not change seval without the keyword.

Tradeoffs

  • _jl_call_nogil can already do this through a closure (jl.seval("code -> Base.eval(Main, Meta.parseall(code))")._jl_call_nogil(code)), but that first call compiles the argument conversion and the closure at runtime, about 0.5 s at import in PySR.
  • A keyword, not a new _jl_seval_nogil method: _jl_call_nogil is a method only because __call__ passes keywords through to Julia, and seval has no such clash.

Verification

  • New test_seval_nogil: two seval("Libc.systemsleep(1)", nogil=True) calls on two Python threads finish in about 1 s (2.3 s with the GIL held); Julia errors raise JuliaError and the GIL is locked again.
  • PySR using this: import pysr 2.95 s → 2.08 s (median of 7, Julia 1.13, Apple M-series).

`jl.seval(code, nogil=True)` evaluates code with the GIL unlocked, so a package can
load its Julia packages while another Python thread imports its Python dependencies.
The new method is precompiled, unlike a closure called with `_jl_call_nogil`.

Co-authored-by: Miles Cranmer <miles.cranmer@gmail.com>
@MilesCranmer

Copy link
Copy Markdown
Contributor

@cjdoris this helped a ton with startup times in PySR!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants