verl icon indicating copy to clipboard operation
verl copied to clipboard

[RFC] Alternative design for vllm-omni rollout LoRA sync: tmpfs + cudaHostRegister preserving file-loading semantics

Open ultism opened this issue 7 months ago • 4 comments

[RFC] Alternative design for vllm-omni rollout LoRA sync: tmpfs + cudaHostRegister preserving file-loading semantics

Context

verl-project/verl#5616 integrated vllm-omni as a rollout backend for FlowGRPO. Since vllm-omni's DiffusionLoRAManager._load_adapter currently only accepts filesystem paths, and actor→rollout LoRA weight sync needs to avoid disk I/O, that PR:

  • Monkey-patches DiffusionLoRAManager._load_adapter at class level via VLLMOmniHijack.hijack().
  • Introduces OmniTensorLoRARequest(OmniLoRARequest) carrying peft_config / lora_tensors inline.
  • Routes tensor-bearing requests to LoRAModel.from_lora_tensors through an isinstance branch.

That was the pragmatic choice at the time; the PR is merged and the integration is working.

What this RFC is

An alternative design with different trade-offs to consider for a future iteration. We're filing it as an RFC rather than jumping straight to implementation because the approach leans on two OS/CUDA primitives (/dev/shm + cudaHostRegister) in a combination that isn't common in the PyTorch ecosystem. Putting it on the table for discussion before anyone commits to a rewrite seems appropriate.

Proposed alternative

Stage the LoRA adapter into tmpfs, keep the file-path semantics for vllm-omni's loader, and have the vllm-omni loader cudaHostRegister the mmap'd region internally (see the companion vllm-omni RFC):

actor worker                        rollout worker
────────────                        ──────────────
state_dict  ──►  /dev/shm/lora_<id>/ ◄── lora_path="/dev/shm/lora_<id>"
              ├─ adapter_config.json      │
              └─ adapter_model.safetensors│
                                          ▼
                          DiffusionLoRAManager._load_adapter
                                      ├─ PEFTHelper.from_local_dir   (mmap)
                                      ├─ cudaHostRegister(mmap region)   ← new
                                      └─ LoRAModel.from_local_checkpoint

Two observations underpin the design:

  1. /dev/shm is tmpfs — "writing a file" is a memcpy into RAM pages. No disk round-trip.
  2. safetensors.safe_open(..., framework="pt") is already mmap-based. cudaHostRegister on the mmap'd region pins those pages so the H2D copy runs as DMA, bypassing PyTorch's internal pinned bounce buffer.

Deployment caveat: Docker / Kubernetes containers default /dev/shm to 64 MB, smaller than typical LoRA adapters. Containerized deployments need docker run --shm-size=... or a K8s emptyDir with medium: Memory and an adequate sizeLimit. _InMemoryAdapterStage should expose the base directory as a config knob and fail fast with a clear message when the staging write hits ENOSPC.

Why the cudaHostRegister step must live inside the vllm-omni loader, not on the VERL side: the register call has to happen between mmap and H2D, and both steps occur inside the loader path (safetensors.safe_open through LoRAModel.from_local_checkpoint). Outside the loader we don't hold the mmap pointer and cannot register it; without registering, the memory isn't pinned and hits known issues on the H2D path. So this RFC isn't a "VERL-side-only change" — vllm-omni needs a companion change to land the register step cleanly (via a loader protocol or a host-register flag).

VERL-side sketch, ~30-50 lines (stage utility + glue):

class _InMemoryAdapterStage:
    """Stage (tensors + peft_config) into tmpfs; return a directory path
    accepted by any file-based LoRA loader. Optionally cudaHostRegister
    the mmap'd safetensors region."""

    def __init__(self, base_dir="/dev/shm/verl_lora", host_register=True): ...
    def stage(self, adapter_id, tensors, peft_config) -> str: ...
    def evict(self, adapter_id): ...

Then in vllm_omni_async_server.py:

path = self._adapter_stage.stage(adapter_id, state_dict, peft_config)
lora_request = LoRARequest(
    lora_name=VLLM_LORA_NAME, lora_int_id=VLLM_LORA_INT_ID, lora_path=path
)

VLLMOmniHijack, OmniTensorLoRARequest, and the class-level setattr all become unnecessary.

Trade-off comparison

Axis Current (hijack) Proposed (tmpfs + cudaHostRegister)
vllm-omni-side changes Class-level setattr on DiffusionLoRAManager Loader seam + host-register step (see companion vllm-omni RFC)
Scope of changes Process-global Confined to manager instances using the loader seam
Tracks internal changes in _load_adapter Downstream copy must be re-synced Inherits them automatically
Number of loader code paths Two (tensor + file branches) One (file)
Data path GPU → pageable CPU → pinned buffer (extra memcpy) → DMA H2D GPU → pinned mmap (direct D2H) → DMA H2D
Reusability outside this integration Integration-specific Generic utility
Prerequisite familiarity Python monkey-patching tmpfs + cudaHostRegister

The last row is the main reason we're filing this as an RFC rather than a PR: the pattern is straightforward once seen, but the combination of cudaHostRegister over a tmpfs mmap isn't a routine tool in RL / diffusion contributor circles. It's worth discussing before switching between approaches.

Why file-system semantics, not a tensor API

An obvious alternative would be asking vllm-omni to add add_adapter_from_tensors(name, tensors, peft_config) — a tensor-first API that accepts an in-memory state_dict directly. Considered but set aside:

  • Forks the loader into two semantics. Every future loader change (multi-LoRA composition, LyCORIS auto-detection, tensorizer integration, quantized adapters) would need re-implementing on both the file path and the tensor path, and the two drift apart over time. One source of LoRA means one code path to keep correct.
  • Doesn't match the vLLM engine's interface design. LoRA is modeled engine-side as a path-addressable asset (LoRARequest.lora_path), and adapter loading is one of the places where vLLM and vllm-omni are aligned. Adding a tensor-first path one layer up while leaving the engine API path-only is an asymmetry that will leak.

The file-system approach keeps semantics clean on both sides:

  • VERL side: responsibility ends at "produce a path". The stage utility is a ~50-line adapter between "I have tensors" and "file-based LoRA loaders expect a directory".
  • vllm-omni side: the loader doesn't need to know whether the path is backed by disk, NFS, tmpfs, a FUSE mount, or a memfd. One code path, one semantic.

And the data path can be strictly better than the current hijack — see the Benchmark section below. Moving off the monkey-patch isn't a regression; for realistic rank-8-to-128 adapters it's a 17–42% win on the LoRA-load step.

Benchmark

Microbenchmark on a single process simulating the actor→rollout hand-off inside the rollout worker (bfloat16, RTX-class GPU, CUDA 12.x). Four paths compared:

  • A (current hijack): LoRAModel.from_lora_tensors(tensors=gpu_sd, device="cpu") — .to("cpu") produces a pageable CPU tensor, .pin_memory() allocates a fresh pinned buffer and memcpys into it, .to("cuda") H2D-DMAs to GPU later.
  • B1 (naive file path): stage via safetensors.save_file → safe_open.get_tensor(...).pin_memory(). Still hits the pin_memory memcpy.
  • B2 (loader-side cudaHostRegister, naive): stage via save_file, mmap + cudaHostRegister the file, reconstruct tensors zero-copy from the registered mmap. Skips pin_memory.
  • B3 (loader-side cudaHostRegister, direct D2H): pre-allocate tmpfs + cudaHostRegister first, then D2H directly into the pinned mmap region. Single PCIe copy, no pageable CPU intermediate.

Median of 5 trials, warmup excluded, total = stage + H2D:

case size A B1 B2 B3 B3 / A
L=8, r=8, h=1024 1.0 MB 3.30 ms 4.26 6.45 2.26 0.69x
L=16, r=16, h=2048 8.0 MB 9.08 15.84 15.63 6.91 0.76x
L=32, r=32, h=2048 32.0 MB 37.79 63.07 40.08 22.03 0.58x
L=32, r=64, h=4096 128.0 MB 65.99 131.47 126.73 54.61 0.83x
L=64, r=128, h=4096 512.0 MB 214.87 509.35 598.92 243.86 1.13x

Takeaways:

  • H2D is identical across paths (all pinned DMA). All differences live in the stage step.
  • B3 beats the current hijack for realistic adapter sizes (1–128 MB, rank 8–128): 17–42% faster. The win comes from collapsing two CPU-side memcpys (hijack pays D2H-to-pageable + pageable→pinned memcpy inside pin_memory) into a single D2H that lands directly in a pre-registered tmpfs region.
  • The 512 MB row flips to 1.13x — cudaHostRegister's per-page pinning overhead grows linearly with size and eventually exceeds the saved pin_memory memcpy. Realistic training LoRA adapters don't reach that regime, but the crossover is worth being honest about.
  • B1 vs B2 comparable: cudaHostRegister on a region whose tensors are then fed through from_lora_tensors' internal pin_memory() is largely wasted. Realizing the win requires the loader to skip the redundant pin step when the source is already in a registered region. This is a loader-design constraint (flagged in the vllm-omni companion RFC §3), not an API constraint.

So the proposed design isn't "API unification at the cost of some perf" — in the typical regime it's faster than the current monkey-patch, and at worst (very large adapters) comparable. Benchmark script in the drafting repo: tmp/bench_lora_loader.py (~220 lines, reproducible end-to-end).

Why not just fix the hijack's data path directly

Fair question: if B3's win is really about a pre-allocated pinned destination, the hijack could get there without touching the API. Three routes, each uncorrelated with the problem the hijack was originally solving:

  1. Modify upstream LoRAModel.from_lora_tensors — replace .to("cpu") + .pin_memory() with torch.empty(..., pin_memory=True).copy_(src, non_blocking=True). This is vLLM-core; the change affects every LoRA consumer (LLM inference included), and requires re-auditing pinned-memory accounting because the allocation pattern shifts. RFC-level work at vLLM scope, unrelated to VERL's actor→rollout sync.
  2. Patch another layer on top of the hijack — monkey-patch from_lora_tensors or LoRALayerWeights assignment inside the existing hijack. Exactly the fragility this RFC is trying to remove, compounded.
  3. Fork the loader in VERL — reimplement LoRAModel construction locally, bypassing from_lora_tensors. Forces VERL to track every upstream change on the loader path (multi-LoRA composition, LyCORIS auto-detection, tensorizer) forever. A second decoupling in the wrong direction.

So B3-tier performance isn't unreachable from the hijack — it's just unreachable cheaply. The value of this RFC isn't "faster by X%"; it's that API unification and the data-flow optimization land in the same change, because mmap'ing a file for the loader already puts us in position to register a pinned destination, and skipping the redundant .pin_memory() inside the loader falls out for free. One review cost, two wins — versus the hijack where the two wins would be three pieces of work at three different scopes.

Spillover value

The staging utility isn't VERL-specific. The same primitive helps in:

  • Hot-swap serving (CivitAI-style runtime adapter download): stage to shm, reuse existing pipeline, no ~/.cache pollution or shared-volume round-trip.
  • Multi-tenant inference: LRU-cache hot adapters in shm; tmpfs already comes with OS-enforced memory bounding.
  • On-the-fly composition / merge: synthesize a combined adapter in memory, stage, feed through any file-loader pipeline.
  • Encrypted weights: decrypt to RAM → shm → plaintext never hits disk.
  • Tests: drop-in replacement for tempfile.TemporaryDirectory, which currently touches real disk and pollutes /tmp.

The common pattern for "I have tensors but the API wants a path" is tempfile.TemporaryDirectory, which does hit real disk. Swapping the medium to tmpfs preserves the semantics and removes the disk cost.

Compatibility with in-flight work

verl-project/verl#6077 (forward-compat for vllm-omni's lora_request/lora_scale → lora_requests/lora_scales rename) is orthogonal to this RFC and should merge on its own timeline. The current hijack continues to work; nothing here is urgent.

Phasing

  1. Land #6077 — purely mechanical forward-compat, no design dependency.
  2. vllm-omni opens a companion RFC (standalone PR, not folded into unrelated in-flight work) stabilizing the lora_path contract, exposing a lora_loader protocol seam, and landing the cudaHostRegister step inside the loader. This is the load-bearing piece of the proposal — the change isn't large, but decoupling the loader has to be done cleanly, not as a drive-by tweak.
  3. VERL lands _InMemoryAdapterStage and switches vllm_omni_async_server to use the new loader. The hijack can be removed once both sides are in place.

Each step is independently useful and revertible.

CC

@knlnguyen1802 @SamitHuang (authors of #5616).

The concrete shape of the alternative is open for discussion — no rush to pin it down.

AI assistance disclosure

RFC drafted with Claude Code. The human submitter reviews and defends the proposal end-to-end.

ultism avatar Apr 20 '26 15:04 ultism

Follow-up after a closer look at VERL's codebase (which I hadn't done thoroughly before filing this RFC):

verl/utils/vllm/utils.py uses exactly the same monkey-patch pattern as verl/utils/vllm_omni/utils.py — VLLMHijack.hijack() does a class-level setattr on LRUCacheWorkerLoRAManager._load_adapter, with a TensorLoRARequest(LoRARequest) subclass and an isinstance branch into LoRAModel.from_lora_tensors. Same root cause, same shape — the diffusion-side hijack is effectively a copy-adapt of this older LLM-side one (the docstring still says "VLLM does not support adding LoRA from tensors directly... we need to find a workaround").

I'd still suggest keeping the initial experiment on the vllm-omni side:

  • Smaller blast radius (smaller user base, faster ship cadence)
  • Narrower loader-path surface: vllm-omni's DiffusionLoRAManager passes model_vocab_size=None and doesn't handle target_embedding_padding / lora_extra_vocab_size, so the seam design has fewer edge cases to cover in v1. LRU cache lifecycle, tensorizer passthrough, and pinned-adapter tracking are present on both sides (the seam has to accommodate them either way) — vllm-omni just gives a cleaner starting point for validating the overall shape.
  • Once the LoRALoader Protocol seam is validated in vllm-omni with production data, proposing the same pattern to vLLM core becomes a "proven pattern migration" rather than a new design — a much easier review path.

Net takeaway: the RFC's shape doesn't change, but the scope of what it could eventually unlock is wider than the original framing — a decoupling pattern that can retire both VERL hijacks in sequence (vllm-omni first, plain vLLM later), not just the vllm-omni one. I think this is a good decoupling story.

Flagging for context, not to push for bundled scope.

ultism avatar Apr 20 '26 18:04 ultism

Overall, this refactor proposal is clear and should be helpful for code maintaince.

But as you mentioned, the default /dev/shm capacity 64MB in Docker/K8s is much smaller than LoRA adapter. If a user forgot to set --shm-size=8G in their job submission script, the resulting error can be hard to debug as it's nested in a Ray Rollout Worker.

SamitHuang avatar Apr 21 '26 02:04 SamitHuang

Ray already sits on this exact tradeoff — Plasma prefers /dev/shm and, when shm is undersized, logs a warning and falls back to /tmp file-backed storage automatically. Every verl user is running that codepath already, whether they notice or not.

So we don't need new error UX — mirroring Ray is the right reference:

  • _InMemoryAdapterStage checks /dev/shm capacity at init, same as raylet does at startup.
  • If under threshold, log a warning pointing at --shm-size / K8s emptyDir medium: Memory, then auto-fall-back to $TMPDIR. Training still runs, just without the tmpfs+cudaHostRegister fast path.
  • If a later write still hits ENOSPC (race, or threshold set too low), reraise with the same remediation hint.

Symmetry: a user willing to accept Ray silently degrading its object store to disk will accept LoRA staging doing the same. Whoever isn't, notices the warning — the same class of warning Ray already taught them to read — and fixes their shm-size.

Default: warn + auto-degrade. No opt-in flag. Matches Ray, matches user expectations.

ultism avatar Apr 21 '26 05:04 ultism

as mentioned in https://github.com/vllm-project/vllm-omni/issues/2957, I suggest to refactor and drop vllm monkey-patch first.

zhtmike avatar Apr 22 '26 02:04 zhtmike