Skip to content

[Store] Batch XPU copies and drop the global lock from pointer checks - #5192

Open
kpjeeja wants to merge 3 commits into
kvcache-ai:mainfrom
kpjeeja:jeeja/fix_xpu_copy_store
Open

kpjeeja wants to merge 3 commits into
kvcache-ai:mainfrom
kpjeeja:jeeja/fix_xpu_copy_store

Conversation

@kpjeeja

@kpjeeja kpjeeja commented Nov 3, 2026 •

Copy link
Copy Markdown

Title: [Store] Batch XPU copies and drop the global lock from pointer checks

Description

The Store's Intel XPU accelerator device ran every copy one at a time behind a single lock:

  • XpuRuntime took one global mutex on every QueryPointer, Copy, AllocHost and FreeHost, so all Store transfer threads took turns.
  • Copy waited once per slice, so the memcpy worker paid a full submit-and-wait round trip for every small op.

Changes:

  • No lock on the hot path. context_ and queues_ are written once in Init() and published through an atomic ready_ flag (release/acquire). Every other method reads them without the lock; mu_ now only serialises Init().
  • Batched copies. AcceleratorDevice gains CopyAsync() / Synchronize(). The default implementation calls Copy() synchronously, so CUDA and the other vendors are unchanged. The XPU override keeps the memcpy events in a thread-local list and waits once in Synchronize(). A copy to or from pageable host memory still waits at once: the driver finishes such a copy before submit returns, so holding its event only added overhead (it measured 8% slower).
  • The memcpy worker batches a task's accelerator copies. On failure or exception it still waits for every copy already started before reporting TRANSFER_FAIL, because the caller may free the buffers. Ops come from caller slices, which can overlap (e.g. READ destinations), so a task whose ops share written bytes falls back to waiting per op.
  • Exceptions. Init, DeviceIndexOf, Copy, AllocHost and FreeHost also catch non-SYCL exceptions (e.g. std::bad_alloc) and return failure. SYCL messages and the type of a std::exception are logged.
  • Memory on a GPU without a queue. Device memory owned by a GPU the runtime did not enumerate was silently copied on device 0's queue. It is now reported as device memory with device_id = -1, the copy fails, and a warning is logged once per such GPU. SetContext now records negative ids so that Copy can reject them. The owner lookup is a pure helper (xpu_accelerator_device_internal.h) so it can be unit-tested without a second GPU.

Suggested Merge Priority

  • P0 — Urgent

  • P1 — High

  • P2 — Normal: Routine bug fix, validated performance/compatibility improvement, or new feature for a confirmed use case## Module

  • Mooncake Store (mooncake-store)

Type of Change

  • Bug fix
  • Performance improvement

How Has This Been Tested?

Hardware: 8× Intel Arc Pro B60, oneAPI 2026.1 (Level Zero V2 adapter).

Test commands:

source /opt/intel/oneapi/setvars.sh
cmake -S . -B build-xpu -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx \
  -DUSE_TENT=ON -DUSE_XPU=ON -DUSE_CUDA=OFF -DWITH_STORE_RUST=OFF -DBUILD_UNIT_TESTS=ON
cmake --build build-xpu --target xpu_accelerator_device_test transfer_task_test runtime_accelerator_test
build-xpu/mooncake-store/tests/xpu_accelerator_device_test
build-xpu/mooncake-store/tests/transfer_task_test
build-xpu/mooncake-store/tests/runtime_accelerator_test

Note: on current main, mooncake_store does not compile with USE_XPU=ON (crc32c.h uses __builtin_cpu_supports, which the SYCL device pass rejects). Open PRs #5176, #5154, #5078, #5090 and #5152 fix that. I built with that fix applied locally; it is not part of this PR.

Accuracy

New mooncake-store/tests/xpu_accelerator_device_test.cpp (12 tests, all pass):

Test Checks
ConcurrentQueryPointerAndCopy 16 threads classify device, pageable and USM-host pointers and copy H2D/D2H at once; every classification, device index and byte is correct
ManySmallOpsInOneTask/{Pageable,Pinned} One MemcpyWorkerPool task of 1024 × 4 KiB mixed H2D/D2H ops completes with correct bytes, 20 repetitions
FailedBatchWaitsForStartedCopies 64 × 4 MiB batch with an injected failure at op 32 reports TRANSFER_FAIL, and ops 0–31 are fully written at the moment it returns
OverlappingOpsRunInOrder A chain that writes a device slot and reads it straight back sees every write
CopyFaultsReturnFailure Injected std::bad_alloc and sycl::exception from Copy / CopyAsync return false and do not throw
CopyWithNullPointerFails A null-pointer copy returns false and does not throw
CopyWithoutDeviceQueueFails device_id -1 or out of range makes the copy fail instead of running on device 0
EveryGpuMapsToItsIndex Memory on each of the 8 GPUs maps to its own index
XpuOwnerQueueIndexTest.* Owner lookup on fake devices: a missing owner gives "unsupported"; the warning fires once per device

Existing suites: transfer_task_test 15 passed, 3 skipped (they need MC_USE_TENT, unrelated); runtime_accelerator_test 9/9.

Known limit: on this driver, OverlappingOpsRunInOrder still passes when the overlap fallback is disabled, because the out-of-order queue happens to serialise overlapping USM copies. SYCL does not guarantee that ordering, so the fallback stays.

Performance

Same machine. Main and branch runs alternated, 5 runs each; each value is the median of the 5. A task value is the median of 20 tasks.

Benchmark main this PR Change
QueryPointer, 16 threads × 20k calls 0.43 M calls/s 0.85 M calls/s ~2.0×
1024 × 4 KiB mixed H2D/D2H task, pinned (USM) host 5.66 ms 4.22 ms 1.34× faster
1024 × 4 KiB mixed H2D/D2H task, pageable host 7.04 ms 7.11 ms no change (within noise)

Pinned host memory is the realistic case: AllocatePinnedHost hands out sycl::malloc_host buffers. QueryPointer is now bounded by sycl::get_pointer_device itself, which manages about 0.97 M calls/s at 16 threads on its own.

Test results:

  • Unit tests pass
  • Integration tests pass (if applicable)
  • Manual testing done (benchmarks above)

Checklist

  • Every commit I contribute includes my Signed-off-by trailer certifying the DCO
  • I have performed a self-review of my own code
  • I have formatted my code using ./scripts/code_format.sh
  • I have run pre-commit on the files changed in this PR and all hooks pass
  • I have updated the documentation (if applicable)
  • I have added tests to prove my changes are effective
  • For changes >500 LOC: I have filed an RFC issue

AI Assistance Disclosure

  • No AI tools were used

  • AI tools were used (specify below)

  • P3 — Low

XpuRuntime took one global mutex on every QueryPointer, Copy, AllocHost
and FreeHost, and Copy waited once per slice, so the MemcpyWorkerPool
paid a full submit-and-wait round trip for every small op.

- context_/queues_ are written once in Init() and published through an
  atomic ready_ flag (release/acquire); everything else reads them
  without the lock. mu_ now serialises Init() only.
- AcceleratorDevice gains CopyAsync()/Synchronize(). The default runs
  Copy() synchronously, so CUDA and the other vendors are unchanged. The
  XPU override keeps the memcpy events in a thread-local list and
  Synchronize() waits for them once. A copy to or from pageable host
  memory still waits at once: the driver copies it before submit
  returns, and holding its event only cost time.
- The memcpy worker batches a task's accelerator copies and waits once.
  On failure or exception it still waits for every copy already started
  before reporting TRANSFER_FAIL. Ops come from caller slices that can
  overlap (e.g. READ destinations), so a task whose ops share written
  bytes falls back to waiting per op.
- Init/DeviceIndexOf/Copy/AllocHost/FreeHost also catch non-SYCL
  exceptions (e.g. std::bad_alloc) and report failure.
- Device memory on a GPU without a queue is no longer copied on device
  0's queue: it is reported as device memory with device_id -1, the
  copy fails, and a warning is logged once per such GPU. SetContext now
  records negative ids so Copy can reject them.

Add xpu_accelerator_device_test: 16-thread QueryPointer+Copy, one task
of 1024 x 4 KiB mixed H2D/D2H ops (pageable and pinned host), a batch
whose middle op fails (started copies are finished when it returns),
overlapping ops, fault injection (std::bad_alloc, sycl::exception),
and the owner-index helper on fake devices.

Perf, Arc Pro B60 x8, oneAPI 2026.1, median of 5 interleaved runs:
  QueryPointer, 16 threads:         0.43 -> 0.85 M calls/s
  1024 x 4 KiB task, pinned host:   5.66 -> 4.22 ms
  1024 x 4 KiB task, pageable host: 7.04 -> 7.11 ms (no change)
QueryPointer is now bounded by sycl::get_pointer_device itself (about
0.97 M calls/s at 16 threads in isolation).

Signed-off-by: KP, Jeeja <jeeja.kp@intel.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings November 3, 2026 08:37
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-03T08:41:30.978641Z 2ae0de5 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2ae0de505a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

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.

Warning

Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

Copilot review overview

2 open issues
What changed in this PR

Improves Intel XPU (SYCL) Store transfer throughput by removing a global runtime lock from pointer checks and enabling batched async copies with a single synchronization point. Adds XPU-specific unit tests and updates the memcpy worker to batch accelerator transfers when safe.

Changes:

  • Add CopyAsync() / Synchronize() to the accelerator device API and implement XPU batching via per-thread pending SYCL events.
  • Update MemcpyWorkerPool to batch accelerator copies per task, with an overlap check to preserve correctness.
  • Add a new XPU accelerator device test suite and wire it into the test build when USE_XPU is enabled.
File Description
mooncake-store/​include/​device/​accelerator_device.h Introduces CopyAsync/Synchronize API for batched copies.
mooncake-store/​include/​device/​xpu_accelerator_device_internal.h Adds testable internals: owner lookup, once-per-key helper, fault injection.
mooncake-store/​src/​device/​xpu_accelerator_device.cpp Removes hot-path locking, adds runtime publishing via atomic flag, implements async copy batching + fault injection.
mooncake-store/​src/​transfer_task.cpp Batches per-task accelerator copies when operations don’t overlap; synchronizes pending copies before task completion/failure.
mooncake-store/​tests/​xpu_accelerator_device_test.cpp Adds concurrency, batching, failure, overlap, and owner-lookup unit tests for XPU.
mooncake-store/​tests/​CMakeLists.txt Registers the new XPU test binary under USE_XPU.

Review effort: Lite

Comment thread mooncake-store/src/transfer_task.cpp Resolved
Review follow-up. MemcpyOperationsOverlap computed range ends as
begin + size; a range that wrapped past the top of the address space got
an end below its begin, so the sweep could miss an overlap and allow
batching. A wrapping range now counts as overlapping.

MemcpyOperationsOverlap is declared in transfer_task.h so it can be
unit-tested on its own: transfer_task_test gains host-only cases for
disjoint, adjacent, shared-read, zero-length, write/write,
read-after-write in both op orders, self-overlapping and wrapping ops.
With the guard removed, WrappingRangePreventsBatching fails.

Signed-off-by: KP, Jeeja <jeeja.kp@intel.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added run-ci Store size/M 100-1000 changed lines (additions + deletions) labels Nov 3, 2026

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

run-ci size/M 100-1000 changed lines (additions + deletions) Store

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants