Skip to content

Cache the memory back-end per device instead of per task #524

Description

@maleadt

cl.memory_backend() and cl.unified_memory_backend() are cached in task-local storage, so every new task works out its memory back-end again. default_memory_backend(dev) queries the device's USM, SVM and BDA support and reads the default_memory_backend preference. On PoCL that takes about 54 µs per task. It's the main cost of the first allocation in a fresh task:

using OpenCL, pocl_jll, Statistics
cl.platform!("pocl")
CLArray{Float32}(undef, 16)
t(f) = (t0 = time_ns(); f(); (time_ns() - t0) / 1e3)
same = [t(() -> CLArray{Float32}(undef, 16)) for _ in 1:200]
newt = [fetch(Threads.@spawn (cl.platform!("pocl"); cl.context(); cl.queue();
                              t(() -> CLArray{Float32}(undef, 16)))) for _ in 1:200]
median(same), median(newt)   # (11.4, 69.7) µs, OpenCL.jl main (937fc5e), PoCL 7.2, 2 threads

This adds up for code that allocates from many short-lived tasks (Threads.@threads loops, @spawn-per-chunk patterns, Dagger). The result only depends on the device, the unified flag and a load-time preference, so it can be cached once per (device, unified) in a global dict under a lock, like device_contexts in lib/cl/state.jl. The task-local entries can stay as the fast path, or be dropped. The maxlog=1 fallback warning in memory_backend() then also needs no task-local state.

Everything else per task is cheap: cl.context() and cl.queue() cost well under a microsecond in a fresh task, thanks to the global per-device contexts.

Also, while comparing with KernelAbstractions' PoCL back-end (which is moving to the same shared-context design): cl.Kernel's lock (75a01d4, "Serialize shared kernel launches") has no test. A test that launches one kernel from many threads with different arguments catches the race reliably. Without the equivalent lock, KA's version of that test segfaults inside PoCL within a few hundred launches on 4 threads. See test/pocl_session.jl on KernelAbstractions.jl's tb/pocl-shared-context branch.

Activity

  1. added
    runtime
    performance
    on Oct 19, 2026
  2. nishagoswamii commented on Nov 24, 2026

    @nishagoswamii

    Without cl.Kernel's lock, concurrent launches of one kernel with different arguments crash PoCL or write another launch's values, but only with several threads, and the test workers here run on one thread.
    Should the test start its own Julia process with --threads, like KernelAbstractions.jl's POCL session test?

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

    performanceruntime

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions