Skip to content

GlobalAlloc that uses PyMem_Raw* methods #6268

Description

@anuraaga

It could be convenient if there is a utility module that provides a rust GlobalAlloc backed by PyMem_Raw - this is particularly important on free-threaded Python where Rust would still use the system allocator which usually performs much worse with contention (article provides some context). While the extension can compile in mimalloc, that's a pretty large library for what's already in the interpreter, multiplied by all extensions. And regardless of that, users can get tracemalloc integration for free.

The idea is to basically just have this alloc.rs available in PyO3 somewhere. I don't think it should be registered by default, notably it is questionable for libraries that allocate after detaching, normally it will be fine but tracemalloc would itself cause acquiring GIL on arbitrary possibly async Rust threads. But it's probably still applicable relatively broadly and some trickiesh code that may be helpful.

https://github.com/bufbuild/protobuf-py/pull/46/changes#diff-d860a3c1b220287bc41b2a02c7830aab1867404d09509c63d4c7cf07bab2f7a5

I notice #81 brought the idea up a long time ago, back then free-threaded may not have been well known as a motivation for this, so maybe it can be reconsidered.

Activity

  1. added theissue type on Jul 31, 2026
  2. davidhewitt commented on Jul 31, 2026

    @davidhewitt
    Member

    I remember looking into this area previously and concluding (at the time) that PyMem_Malloc was not suitable for building a global allocator due to the need for the attached thread state.

    I forget why I didn't look harder at the PyMem_Raw* methods - perhaps it was long enough ago that the free-threading case wasn't relevant, and I didn't see much advantage adding indirection over the system allocator.

    Overall this seems like a good idea as an opt-in feature 👍

  3. chirizxc commented on Jul 31, 2026

    @chirizxc
    Contributor

    @anuraaga сan you share ur benchmark code? I mean, did you run benchmarks comparing default alloc, mimalloc, snmalloc, and PyMemRawAllocator? Or any others?

  4. mejrs commented on Jul 31, 2026

    @mejrs
    Member

    Overall this seems like a good idea as an opt-in feature 👍

    To be clear, we wouldn't declare the global allocator, that's up to the user. We simply create a struct and implement GlobalAllocator for it by forwarding calls to PyMem_Raw*.

    So a feature is not necessary.

  5. anuraaga commented on Aug 3, 2026

    @anuraaga
    ContributorAuthor

    Thanks for the help on this @chirizxc - I only did limited benchmarking in downstream code

    https://github.com/bufbuild/protobuf-py/blob/main/packages/bench/tests/test_bench.py#L209

    I got around 20% improvement across several runs using PyMemRawAllocator. Note that this is not a allocation-heavy test case, our code essentially only allocates a power-of-2 output buffer in Rust. More threads or more allocation-heavy code will benefit more I think.

    I checked our other benches both with and without free-threaded to see no change, expected since the extra indirection is tiny.

    I didn't check mimalloc / snmalloc in Rust since my main objective was to take advantage of what Python is providing. I'm sure it would be interesting though when upstreaming here as a reference point though.

  6. ngoldbaum commented on Aug 7, 2026

    @ngoldbaum
    Contributor

    mimalloc also scales better under multithreaded use, see section 5: https://labs.quansight.org/blog/scaling-numpy-on-free-threaded-python.

    Ping @kumaraditya303, since he did the work to make the raw allocators in CPython use mimalloc on the free-threaded build.

  7. chirizxc commented on Aug 7, 2026

    @chirizxc
    Contributor

    Also, based on my mini benchmarks at toml-rs, I get roughly the following results:

    ❯ py b.py
    file: example.toml
    size: 3.93 KiB
    runs: 1,000 x 5
    
    allocator                 time    vs default        memory        wall
    --------------------------------------------------------------------------
    default               0.0547s        1.00x      15.33 MB     0.496s
    mimalloc              0.0410s        1.33x      15.69 MB     0.314s
    snmalloc              0.0452s        1.21x      17.64 MB     0.349s
    py-mem-alloc          0.0515s        1.06x      15.34 MB     0.376s
    ❯ py b.py
    file: example.toml
    size: 3.93 KiB
    runs: 1,000 x 5
    
    allocator                 time    vs default        memory        wall
    --------------------------------------------------------------------------
    default               0.0497s        1.00x      15.14 MB     0.353s
    mimalloc              0.0452s        1.10x      15.49 MB     0.352s
    snmalloc              0.0440s        1.13x      17.82 MB     0.328s
    py-mem-alloc          0.0584s        0.85x      15.18 MB     0.406s
    ❯ py b.py
    file: example.toml
    size: 3.93 KiB
    runs: 1,000 x 5
    
    allocator                 time    vs default        memory        wall
    --------------------------------------------------------------------------
    default               0.0547s        1.00x      15.15 MB     0.385s
    mimalloc              0.0417s        1.31x      15.59 MB     0.327s
    snmalloc              0.0414s        1.32x      17.75 MB     0.304s
    py-mem-alloc          0.0503s        1.09x      15.42 MB     0.357s
    ❯ py b.py
    file: example.toml
    size: 3.93 KiB
    runs: 1,000 x 5
    
    allocator                 time    vs default        memory        wall
    --------------------------------------------------------------------------
    default               0.0502s        1.00x      15.30 MB     0.359s
    mimalloc              0.0413s        1.21x      15.62 MB     0.305s
    snmalloc              0.0414s        1.21x      18.00 MB     0.317s
    py-mem-alloc          0.0469s        1.07x      15.37 MB     0.337s
  8. anuraaga commented on Aug 10, 2026

    @anuraaga
    ContributorAuthor

    @chirizxc BTW in case you used 3.14 etc, you will need to use python 3.15 rc to get the mimalloc backend for PyMem_Raw*, the improvement I found of 20% with Python 3.15 looks quite similar to your mimalloc number there.

  9. ngoldbaum commented on Aug 10, 2026

    @ngoldbaum
    Contributor
  10. anuraaga commented on Aug 10, 2026

    @anuraaga
    ContributorAuthor

    Thanks @ngoldbaum - I couldn't find any indication the recent changes to have PyMem_Raw use mimalloc (not pymem_alloc) were backported to 3.14 (at least on the 3.14t I tried, there was no change in performance from using PyMem_Raw in my benchmark)

  11. davidhewitt commented on Aug 10, 2026

    @davidhewitt
    Member

    https://docs.python.org/3.14/c-api/memory.html#default-memory-allocators seems to suggest mimalloc is indeed used for free threaded 3.14 for all allocator domains.

  12. kumaraditya303 commented on Aug 10, 2026

    @kumaraditya303

    mimalloc was only used for the object allocator on 3.14 on free-threading, the change to use mimalloc for raw allocator is 3.15 only. See python/cpython#144914

  13. chirizxc commented on Aug 10, 2026

    @chirizxc
    Contributor
    ❯ py b.py                                                                                                                                      
    file: example.toml                                                                                                                             
    size: 3.93 KiB
    runs: 1,000 x 5
    
    allocator                   time  vs default    memory    wall
    -----------------------  -------  ----------  --------  ------
    default                  0.0453s       1.00x  16.62 MB  0.354s
    mimalloc                 0.0405s       1.12x  16.91 MB  0.284s
    mimalloc with fast path  0.0405s       1.12x  16.93 MB  0.288s
    py-mem-raw-allocator     0.0408s       1.11x  16.65 MB  0.288s
    ❯ py b.py                                                                                                                                      
    file: example.toml                                                                                                                             
    size: 3.93 KiB
    runs: 1,000 x 5
    
    allocator                   time  vs default    memory    wall
    -----------------------  -------  ----------  --------  ------
    default                  0.0499s       1.00x  16.63 MB  0.354s
    mimalloc                 0.0404s       1.24x  16.91 MB  0.277s
    mimalloc with fast path  0.0413s       1.21x  16.95 MB  0.300s
    py-mem-raw-allocator     0.0416s       1.20x  16.65 MB  0.300s
    ❯ py b.py                                                                                                                                      
    file: example.toml                                                                                                                             
    size: 3.93 KiB
    runs: 1,000 x 5
    
    allocator                   time  vs default    memory    wall
    -----------------------  -------  ----------  --------  ------
    default                  0.0488s       1.00x  16.64 MB  0.327s
    mimalloc                 0.0407s       1.20x  16.90 MB  0.298s
    mimalloc with fast path  0.0404s       1.21x  16.95 MB  0.282s
    py-mem-raw-allocator     0.0408s       1.20x  16.64 MB  0.292s
    ❯ py b.py                                                                                                                                      
    file: example.toml                                                                                                                             
    size: 3.93 KiB
    runs: 1,000 x 5
    
    allocator                   time  vs default    memory    wall
    -----------------------  -------  ----------  --------  ------
    default                  0.0449s       1.00x  16.64 MB  0.338s
    mimalloc                 0.0402s       1.12x  16.90 MB  0.290s
    mimalloc with fast path  0.0405s       1.11x  16.93 MB  0.286s
    py-mem-raw-allocator     0.0423s       1.06x  16.66 MB  0.300s
    ❯ py b.py                                                                                                                                      
    file: example.toml                                                                                                                             
    size: 3.93 KiB
    runs: 1,000 x 5
    
    allocator                   time  vs default    memory    wall
    -----------------------  -------  ----------  --------  ------
    default                  0.0465s       1.00x  16.62 MB  0.339s
    mimalloc                 0.0403s       1.15x  16.90 MB  0.285s
    mimalloc with fast path  0.0405s       1.15x  16.96 MB  0.285s
    py-mem-raw-allocator     0.0409s       1.14x  16.66 MB  0.284s
    ❯ py b.py                                                                                                                                      
    file: example.toml                                                                                                                             
    size: 3.93 KiB
    runs: 1,000 x 5
    
    allocator                   time  vs default    memory    wall
    -----------------------  -------  ----------  --------  ------
    default                  0.0449s       1.00x  16.64 MB  0.314s
    mimalloc                 0.0406s       1.11x  16.89 MB  0.291s
    mimalloc with fast path  0.0406s       1.11x  16.95 MB  0.288s
    py-mem-raw-allocator     0.0410s       1.10x  16.66 MB  0.283s
    ❯ py b.py                                                                                                                                      
    file: example.toml                                                                                                                             
    size: 3.93 KiB
    runs: 1,000 x 5
    
    allocator                   time  vs default    memory    wall
    -----------------------  -------  ----------  --------  ------
    default                  0.0458s       1.00x  16.61 MB  0.337s
    mimalloc                 0.0408s       1.12x  16.90 MB  0.290s
    mimalloc with fast path  0.0411s       1.11x  16.96 MB  0.304s
    py-mem-raw-allocator     0.0411s       1.11x  16.64 MB  0.294s
    ❯ py b.py                                                                                                                                      
    file: example.toml                                                                                                                             
    size: 3.93 KiB
    runs: 1,000 x 5
    
    allocator                   time  vs default    memory    wall
    -----------------------  -------  ----------  --------  ------
    default                  0.0492s       1.00x  16.62 MB  0.350s
    mimalloc                 0.0404s       1.22x  16.89 MB  0.282s
    mimalloc with fast path  0.0406s       1.21x  16.96 MB  0.283s
    py-mem-raw-allocator     0.0405s       1.22x  16.65 MB  0.282s
    ❯ py b.py                                                                                                                                      
    file: example.toml                                                                                                                             
    size: 3.93 KiB
    runs: 1,000 x 5
    
    allocator                   time  vs default    memory    wall
    -----------------------  -------  ----------  --------  ------
    default                  0.0458s       1.00x  16.55 MB  0.345s
    mimalloc                 0.0407s       1.13x  16.91 MB  0.286s
    mimalloc with fast path  0.0432s       1.06x  16.94 MB  0.304s
    py-mem-raw-allocator     0.0415s       1.10x  16.66 MB  0.297s
    ❯ py b.py                                                                                                                                      
    file: example.toml                                                                                                                             
    size: 3.93 KiB
    runs: 1,000 x 5
    
    allocator                   time  vs default    memory    wall
    -----------------------  -------  ----------  --------  ------
    default                  0.0491s       1.00x  16.64 MB  0.348s
    mimalloc                 0.0407s       1.21x  16.90 MB  0.282s
    mimalloc with fast path  0.0405s       1.21x  16.95 MB  0.280s
    py-mem-raw-allocator     0.0452s       1.08x  16.67 MB  0.316s
    ❯ py b.py                                                                                                                                      
    file: example.toml                                                                                                                             
    size: 3.93 KiB
    runs: 1,000 x 5
    
    allocator                   time  vs default    memory    wall
    -----------------------  -------  ----------  --------  ------
    default                  0.0465s       1.00x  16.50 MB  0.339s
    mimalloc                 0.0406s       1.15x  16.90 MB  0.295s
    mimalloc with fast path  0.0406s       1.15x  16.96 MB  0.286s
    py-mem-raw-allocator     0.0421s       1.11x  16.65 MB  0.297s
    toml-rs\benchmark on  more-wheels via 🐍 v3.15.0rc1 (3.15t) 
    ❯ 
    

    Chat GPT table:

    Image
  14. ngoldbaum commented on Aug 10, 2026

    @ngoldbaum
    Contributor

    Thanks for clarifying Kumar!

  15. ngoldbaum commented on Aug 12, 2026

    @ngoldbaum
    Contributor

    I was chatting with @emmatyping about this and she brought up that there may be soundness issues around panic-unwinding. I thought about this today and came up with the following scenario, which doesn't require unwinding at all. However if you install the raw allocator as the global allocator, then this sort of allocation can happen in a Drop implementation, for example, and this becomes a process hang during panic unwinding.

    Add this to pymem_alloc.rs on top of #6279 and then cargo test --lib should deadlock on this test.

          #[test]
          fn detached_raw_alloc_deadlocks_under_tracemalloc() {
              use crate::Python;
              Python::initialize();
              Python::attach(|py| {
                  py.run(c"import tracemalloc; tracemalloc.start()", None, None)
                      .unwrap();
                  std::thread::spawn(|| {
                      let layout = Layout::from_size_align(64, 8).unwrap();
                      // SAFETY: non-zero layout; freed immediately. Blocks in PyGILState_Ensure().
                      unsafe {
                          let p = PyMemRawAllocator.alloc(layout);
                          assert!(!p.is_null());
                          PyMemRawAllocator.dealloc(p, layout);
                      }
                  })
                  .join()
                  .unwrap();
              });
          }

    Maybe tracemalloc shouldn't use blocking calls for instrumenting the raw domain? But that's how it works right now, with a PyGilState_Ensure.

  16. anuraaga commented on Aug 13, 2026

    @anuraaga
    ContributorAuthor

    Thanks @ngoldbaum - we have been trying to word out some docs on this topic

    #6279 (comment)

    I think the summary is that if your code never spawns threads or detaches, like a JSON marshaler, the allocations all happen under the GIL and there is no chance of issues. If you do, then tracemalloc can introduce possible issues including deadlock depending on what the code does.

  17. chirizxc commented on Aug 13, 2026

    @chirizxc
    Contributor

    Maybe tracemalloc shouldn't use blocking calls for instrumenting the raw domain? But that's how it works right now, with a PyGilState_Ensure.

    Maybe bug (maybe it's just a matter of updating the documentation)

    To be honest, I think this is a CPython bug

    tracemalloc's raw-domain allocator hook requires an attached thread
    state (PyGILState_Ensure(): tracemalloc_alloc / tracemalloc_realloc) , which violates the documented PYMEM_DOMAIN_RAW contract:

    MRE

    import ctypes
    import sys
    import threading
    import tracemalloc
    
    if not sys.platform.startswith("linux"):
        msg = "This MRE requires Linux"
        raise RuntimeError(msg)
    
    pythonapi = ctypes.pythonapi
    pythonapi.PyMem_RawMalloc.restype = ctypes.c_void_p
    pythonapi.PyMem_RawMalloc.argtypes = [ctypes.c_size_t]
    pythonapi.PyMem_RawFree.argtypes = [ctypes.c_void_p]
    
    
    # this is only needed to creat a native thread
    # without a `PyThreadState` attached to it
    libc_cdll = ctypes.CDLL(None)
    libc_cdll.pthread_create.restype = ctypes.c_int
    libc_cdll.usleep.argtypes = [ctypes.c_uint]
    
    # unlike CDLL, PyDLL does NOT release the GIL around the call
    # this is intentional, so that the main thread holds the GIL for
    # the full 5 seconds creating conditions under which the raw-allocator
    # hook cannot acquire the GIL, even if it were to request it
    blocking_libc = ctypes.PyDLL(None)
    blocking_libc.sleep.argtypes = [ctypes.c_uint]
    
    THREAD_FN = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p)
    done = threading.Event()
    
    
    @THREAD_FN
    def native_thread_entry(_arg: ctypes.c_void_p) -> ctypes.c_void_p:
        # this thread was created using `pthread_create()`, not
        # `threading.Thread` it does NOT have an associated `PyThreadState`
        libc_cdll.usleep(500_000)
    
        # according to the `PyMem_SetAllocator` contract for `PYMEM_DOMAIN_RAW`
        # ("a thread state is not attached when the allocator is called"),
        # the call below MUST execute without blocking on the GIL
        ptr = pythonapi.PyMem_RawMalloc(64)
        pythonapi.PyMem_RawFree(ptr)
    
        # if the allocator internally calls `PyGILState_Ensure()`,
        # then this code will never reach this point while the GIL is busy
        done.set()
    
    
    def main() -> None:
        # tracemalloc.start() sets a hook on `PYMEM_DOMAIN_RAW`
        tracemalloc.start()
        thread_id = ctypes.c_ulong()
        libc_cdll.pthread_create(ctypes.byref(thread_id), None, native_thread_entry, None)
        # The main thread holds the GIL continuously for 5 seconds (`PyDLL.sleep` does not
        # release the GIL). If the raw-allocator hook requires the GIL, a deadlock occurs
        blocking_libc.sleep(5)
    
        # deadlock
        print("DEADLOCK" if not done.is_set() else "OK")
    
    
    main()

    Per documented contract, PyMem_RawMalloc / RawFree must be callable safely
    from a thread with no attached thread state, regardless of tracemalloc
    state, and must not require GIL acquisition to complete

  18. ngoldbaum commented on Aug 13, 2026

    @ngoldbaum
    Contributor

    @chirizxc note that in my example with a deadlock, there's already an attached thread state. So it's not, technically, violating the contract that one doesn't need an attached thread state.

    I agree though that this is probably a CPython bug. Would you like to open an upstream issue?

    Rather than using ctypes though it's better if you report issues like this using a small C extension. The triagers and core devs will probably look at that less askance than ctypes hacks, even if they are doing exactly the same thing.

  19. ZeroIntensity commented on Aug 13, 2026

    @ZeroIntensity

    Hi, coming from the CPython issue. I'm not so sure this is a bug on our end. The contract says that the caller doesn't hold an attached thread state for PYMEM_DOMAIN_RAW. It says nothing about what the callback can do. Where is this causing deadlocks in practice?

  20. ngoldbaum commented on Aug 13, 2026

    @ngoldbaum
    Contributor

    Nowhere yet but it could perhaps preclude PyO3 from including this functionality because of the deadlock risk. It may also be OK to simply document it.

  21. chirizxc commented on Aug 31, 2026

    @chirizxc
    Contributor

    python/cpython#155725 (comment)

    Should the new GlobalAlloc be #[cfg(Py_3_15)]?

  22. ngoldbaum commented on Sep 2, 2026

    @ngoldbaum
    Contributor

    Should the new GlobalAlloc be #[cfg(Py_3_15)]?

    And maybe also with some note in the docs that it's provisional and experimental as we shake out issues like the tracemalloc problem we ran into?

    I also think if someone wanted to spend some time figuring out and documenting how to wrap mimalloc, tcmalloc, or jemalloc in a crate using PyO3, that would be even nicer.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions