[Qwen4Exp] Serve PLE rows from the loader's mapped checkpoint shards (PR #58815)

Adds an opt-in backend, --engram-config '{"host_file_gather": true}', that
serves Qwen4Exp PLE rows from the checkpoint files through the page cache
instead of allocating the 47.7 GiB table on GPU or in pinned host memory.

- Qwen4ExpPLEFileGatherEmbedding allocates no table rows; load_weights keeps
  the default loader's zero-copy safetensors views of each shard. At bind
  (post-load hook) every view must be file-backed per /proc/self/maps (HF
  cache symlinks work; heap/pinned/anonymous memory is rejected) and the
  shards must cover the whole table.
- Each step, Qwen4ExpModelState.prepare_inputs computes the PLE n-gram ids,
  copies them to pinned host memory, syncs the stream once, issues
  POSIX_FADV_WILLNEED over the coalesced page ranges of the step's rows,
  gathers the rows on the host, and copies them into a fixed device staging
  buffer. The forward reads only the staging buffer, so FULL CUDA graph
  capture is unaffected.
- Rows stay in the checkpoint dtype (FP8 table stays FP8, dequantized on the
  GPU); dummy loads serve zeros; weight reload is rejected; takes precedence
  over cpu_offload; rejected on ROCm and with elastic EP.

Co-Authored-By: Hinata <hinata@idihore.id>
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-09-27 09:54:42 +07:00
co-authored by Hinata
parent 5af48b498c
commit 43fbd6510b
8 changed files with 684 additions and 15 deletions
@@ -48,7 +48,7 @@ logger = init_logger(__name__)
class Qwen4ExpPLEEmbedding(PLEVocabParallelEmbedding, ABC):
"""ETP-sharded PLE table shared by device and pinned-host backends."""
"""PLE table base shared by the device, pinned-host, and file-gather backends."""
supports_prefetch: ClassVar[bool] = False
@@ -157,9 +157,9 @@ class Qwen4ExpPLEEmbedding(PLEVocabParallelEmbedding, ABC):
class Qwen4ExpPLEEmbeddingMethod(QuantizeMethodBase):
"""Quantization interface shared by resident and pinned PLE tables."""
"""Quantization interface shared by device, pinned, and file-gather PLE tables."""
# PLE post-load processing only validates scales in their current storage.
# PLE post-load processing validates scales in place and binds host file shards.
requires_device_loading: bool = False
@staticmethod
@@ -216,6 +216,12 @@ class Qwen4ExpPLEEmbeddingMethod(QuantizeMethodBase):
def embedding(self, layer: nn.Module, input_: torch.Tensor) -> torch.Tensor:
return F.embedding(input_, layer.weight)
def process_weights_after_loading(self, layer: nn.Module) -> None:
"""Bind host-file-gather tables once every checkpoint shard is loaded."""
bind = getattr(layer, "bind_file_shards", None)
if bind is not None:
bind()
@abstractmethod
def dequantize(
self,
@@ -305,6 +311,7 @@ class Qwen4ExpPLEFp8EmbeddingMethod(Qwen4ExpPLEEmbeddingMethod):
sentinel = torch.finfo(torch.float32).min
if torch.any(layer.weight_scale == sentinel):
raise ValueError("FP8 PLE checkpoint is missing its global scale")
super().process_weights_after_loading(layer)
def dequantize(
self,
+21 -1
View File
@@ -13,6 +13,12 @@ from vllm.v1.worker.gpu.mm.encoder_cache import EncoderCache
from vllm.v1.worker.gpu.model_states.mamba_hybrid import MambaHybridModelState
from vllm.v1.worker.gpu.states import RequestState
from .ngram_embedding import (
Qwen4ExpNGramEmbedding,
Qwen4ExpPLEFileGatherEmbedding,
stage_checkpoint_rows,
)
class Qwen4ExpModelState(MambaHybridModelState):
"""Add rollback-safe PLE n-gram context to the model inputs."""
@@ -63,6 +69,12 @@ class Qwen4ExpModelState(MambaHybridModelState):
dtype=torch.int32,
device=self.device,
)
self.file_gather_modules = [
module
for module in model.modules()
if isinstance(module, Qwen4ExpNGramEmbedding)
and isinstance(module.ngram_embedding, Qwen4ExpPLEFileGatherEmbedding)
]
def _prepare_ngram_context(
self,
@@ -106,9 +118,17 @@ class Qwen4ExpModelState(MambaHybridModelState):
query_start_loc[: num_reqs_padded + 1].copy_(input_batch.query_start_loc)
# Represent unused capacity as trailing zero-length requests.
query_start_loc[num_reqs_padded + 1 :].copy_(input_batch.query_start_loc[-1])
ngram_context = self._prepare_ngram_context(input_batch, req_states)
if self.file_gather_modules:
stage_checkpoint_rows(
self.file_gather_modules,
input_batch.input_ids,
query_start_loc,
ngram_context,
)
model_inputs.update(
query_start_loc=query_start_loc,
ngram_context=self._prepare_ngram_context(input_batch, req_states),
ngram_context=ngram_context,
)
return model_inputs
+181 -3
View File
@@ -1,7 +1,9 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Qwen4Exp n-gram embeddings with device and pinned-host storage."""
"""Qwen4Exp n-gram embeddings with device, pinned-host and host-file-gather storage."""
import mmap
import os
from collections.abc import Iterable
import torch
@@ -40,6 +42,155 @@ __all__ = [
]
def _maps_entry(ptr: int) -> tuple[str, int]:
"""Return the path and file offset of ``ptr`` from ``/proc/self/maps``."""
with open("/proc/self/maps") as maps:
for line in maps:
fields = line.split(maxsplit=5)
low, high = (int(bound, 16) for bound in fields[0].split("-"))
if low <= ptr < high:
path = fields[5].rstrip("\n") if len(fields) > 5 else ""
return path, ptr - low + int(fields[2], 16)
return "", 0
class Qwen4ExpPLEFileGatherEmbedding(Qwen4ExpPLEEmbedding):
"""PLE rows gathered on the host from the loader's file-backed shard views."""
def __init__(
self,
num_embeddings: int,
embedding_dim: int,
*,
params_dtype: torch.dtype,
padding_size: int,
prefix: str,
embedding_method: Qwen4ExpPLEEmbeddingMethod,
num_ngram_heads: int = 1,
max_total_tokens: int = 0,
data_parallel_rank: int = 0,
) -> None:
super().__init__(
num_embeddings,
embedding_dim,
params_dtype=params_dtype,
padding_size=padding_size,
prefix=prefix,
embedding_method=embedding_method,
data_parallel_rank=data_parallel_rank,
)
self._dummy = get_current_vllm_config().load_config.load_format == "dummy"
shape = (max_total_tokens, num_ngram_heads, embedding_dim)
dtype, pin = self.weight.dtype, self.weight.device.type != "cpu"
self._staging = torch.zeros(shape, dtype=dtype, device=self.weight.device)
self._host_ids = torch.empty(
shape[:2], dtype=torch.int64, device="cpu", pin_memory=pin
)
# Step N+1 writes these rows only after its stream sync, so after step N's H2D.
self._host_rows = torch.empty(shape, dtype=dtype, device="cpu", pin_memory=pin)
self._shards: dict[int, torch.Tensor] | None = {}
self._shard_size = 0
self._bound = False
self._fds: dict[str, int] = {}
self._fds_t = self._bases = torch.empty(0, dtype=torch.int64)
def allocate_embedding_weight(
self,
num_embeddings: int,
embedding_dim: int,
dtype: torch.dtype,
) -> torch.Tensor:
"""Allocate no rows; they stay in the checkpoint files."""
return torch.empty(0, embedding_dim, dtype=dtype)
def accept_checkpoint_shard(
self,
shard_index: int,
loaded_weight: torch.Tensor,
shard_size: int,
) -> None:
"""Keep a checkpoint shard as a zero-copy byte view of its storage."""
if self._bound or self._shards is None:
self._shards = None
raise RuntimeError("PLE host file gather does not support weight reload")
if loaded_weight.dtype != self.weight.dtype:
raise ValueError(
f"PLE shard dtype {loaded_weight.dtype} must match the embedding "
f"dtype {self.weight.dtype}; host file gather serves rows as stored"
)
if shard_index in self._shards:
raise ValueError(f"Duplicate PLE embedding shard {shard_index}")
self._shards[shard_index] = loaded_weight.view(torch.uint8)
self._shard_size = shard_size
def bind_file_shards(self) -> None:
"""Check that file-backed shards cover every row; dummy loads serve zeros."""
assert self._shards is not None
if not self._dummy:
rows = sum(shard.shape[0] for shard in self._shards.values())
if rows != self.org_vocab_size:
raise ValueError(
f"PLE shards cover {rows} of {self.org_vocab_size} rows"
)
self._fds_t, self._bases = torch.zeros(2, len(self._shards)).long()
for index, shard in self._shards.items():
path, offset = _maps_entry(shard.data_ptr())
if not path or not os.path.isfile(path):
raise ValueError(
f"PLE embedding shard {index} is not a file-backed view "
f"({path or 'anonymous'})"
)
if path not in self._fds:
self._fds[path] = os.open(path, os.O_RDONLY)
self._fds_t[index], self._bases[index] = self._fds[path], offset
self._bound = True
def stage_rows(self, num_tokens: int) -> None:
"""Gather the rows for ``_host_ids[:num_tokens]`` and copy them to staging."""
shards = self._shards
if shards is None or not self._bound:
raise RuntimeError("PLE host file gather is unbound or was reloaded")
ids = self._host_ids[:num_tokens].flatten()
out = self._host_rows[:num_tokens].flatten(0, 1).view(torch.uint8)
if not shards:
out.zero_()
else:
ids, order = ids.sort()
shard = ids // self._shard_size
local = ids - shard * self._shard_size
counts = torch.bincount(shard, minlength=len(shards)).tolist()
page, row_bytes = mmap.PAGESIZE, out.shape[1]
start = self._bases[shard] + local * row_bytes
first, last = start // page, (start + row_bytes - 1) // page
run = torch.ones_like(first, dtype=torch.bool)
run[1:] = (first[1:] > last[:-1] + 1) | (shard[1:] != shard[:-1])
fds, lows = self._fds_t[shard[run]].tolist(), first[run].tolist()
# Queue every page read before the gather's first serial fault.
for fd, lo, hi in zip(fds, lows, last[run.roll(-1)].tolist()):
os.posix_fadvise(
fd, lo * page, (hi - lo + 1) * page, os.POSIX_FADV_WILLNEED
)
groups = zip(order.split(counts), local.split(counts))
for index, (rows, rows_local) in enumerate(groups):
if rows.numel():
out.index_copy_(0, rows, shards[index].index_select(0, rows_local))
self._staging[:num_tokens].copy_(
self._host_rows[:num_tokens], non_blocking=True
)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
"""Return the rows staged for this step."""
return self._staging[: hidden_states.shape[0]].flatten(-2)
def start_prefetch(
self,
hidden_states: torch.Tensor,
ngram_ids: torch.Tensor,
) -> None:
"""Rows are staged in ``prepare_inputs``, so prefetch is a no-op."""
return None
class Qwen4ExpNGramEmbedding(nn.Module):
_MASK64 = (1 << 64) - 1
_SPLITMIX_GAMMA = 0x9E3779B97F4A7C15
@@ -209,7 +360,9 @@ class Qwen4ExpNGramEmbedding(nn.Module):
params_dtype = torch.get_default_dtype()
engram_config = get_current_vllm_config().engram_config
embedding_cls = (
Qwen4ExpPLEPinnedHostEmbedding
Qwen4ExpPLEFileGatherEmbedding
if engram_config is not None and engram_config.host_file_gather
else Qwen4ExpPLEPinnedHostEmbedding
if engram_config is not None and engram_config.cpu_offload
else Qwen4ExpPLEDeviceEmbedding
)
@@ -358,7 +511,9 @@ class Qwen4ExpNGramEmbedding(nn.Module):
ngram_context: torch.Tensor,
) -> torch.Tensor:
embedding = self.ngram_embedding
if embedding.supports_prefetch:
if embedding.supports_prefetch or isinstance(
embedding, Qwen4ExpPLEFileGatherEmbedding
):
return embedding(hidden_states)
ngram_ids = self.compute_ngram_ids(input_ids, query_start_loc, ngram_context)
return self.ngram_embedding(ngram_ids).flatten(-2)
@@ -434,6 +589,12 @@ class Qwen4ExpNGramEmbedding(nn.Module):
f"expected {expected_shape}, got "
f"{tuple(loaded_weight.shape)}"
)
if isinstance(embedding, Qwen4ExpPLEFileGatherEmbedding):
embedding.accept_checkpoint_shard(
shard_index, loaded_weight, shard_size
)
loaded.add("ngram_embedding.weight")
continue
embedding.weight.weight_loader(
embedding.weight,
loaded_weight,
@@ -448,6 +609,23 @@ class Qwen4ExpNGramEmbedding(nn.Module):
return loaded
def stage_checkpoint_rows(
modules: list[Qwen4ExpNGramEmbedding],
input_ids: torch.Tensor,
query_start_loc: torch.Tensor,
ngram_context: torch.Tensor,
) -> None:
"""Stage host-file-gather PLE rows for one step behind a single stream sync."""
num_tokens = input_ids.shape[0]
for module in modules:
ids = module.compute_ngram_ids(input_ids, query_start_loc, ngram_context)
module.ngram_embedding._host_ids[:num_tokens].copy_(ids, non_blocking=True)
if input_ids.device.type != "cpu":
torch.accelerator.current_stream().synchronize()
for module in modules:
module.ngram_embedding.stage_rows(num_tokens)
__all__ = [
"Qwen4ExpNGramEmbedding",
]