With the switch unset, the PLE took upstream's UVA backend, whose Triton lookup kernel needs fp8e4nv, which sm_86 does not have, so a launcher without the switch failed at profile_run. Unset now means on, the shipped value; 0 still selects upstream's path. Co-Authored-By: Hinata <hinata@idihore.id> Signed-off-by: MOVZX <movzx@yahoo.com>
344 lines
14 KiB
Python
344 lines
14 KiB
Python
# SPDX-License-Identifier: Apache-2.0
|
|
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
|
"""The fork's PLE pull transport, re-seated on vLLM v0.30.0.
|
|
|
|
v0.30.0 split the E2 base's offload-aware ``Qwen4ExpNGramEmbedding`` into an
|
|
upstream-only module (``ngram_embedding.py``, device or pinned-host UVA table).
|
|
This module puts the E2 pull transport back WITHOUT editing that upstream
|
|
class: ``Qwen4ExpNGramEmbeddingPull`` inherits it and ``PleOffloadLayer``.
|
|
|
|
* In a GPU worker, ``PleOffloadLayer.__init_subclass__`` skips the constructor:
|
|
the module is an empty placeholder with no table. ``PleOffloadConnector``
|
|
binds it to a host-mapped flag/buffer; its forward is the captured
|
|
``ple_offload_wait_copy`` op. Only the FP8 global scale is kept on the GPU.
|
|
* In the CPU-only offload process the constructor runs in full, on CPU. The
|
|
table is upstream's ``Qwen4ExpPLEDeviceEmbedding`` allocated on CPU;
|
|
``forward_impl`` computes n-gram IDs and gathers raw (FP8) rows.
|
|
|
|
Selected when ``VLLM_E2_PLE_PULL_TRANSPORT`` is ``1`` or unset (the fork default
|
|
since v2.5); with ``=0`` this module is never imported by the model and the
|
|
tree is upstream.
|
|
|
|
Supported table formats: FP8 (global scale) and unquantized -- the two
|
|
``Qwen4ExpPLEEmbeddingMethod`` families v0.30.0 itself supports. The E2 NVFP4
|
|
path is not carried (v0.30.0 has no NVFP4 PLE method to select).
|
|
"""
|
|
|
|
from collections.abc import Iterable
|
|
|
|
import torch
|
|
|
|
from vllm.config import get_current_vllm_config
|
|
from vllm.logger import init_logger
|
|
from vllm.model_executor.layers.ple_offload_layer import (
|
|
PleOffloadLayer,
|
|
is_offload_process,
|
|
)
|
|
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
|
|
from vllm.transformers_utils.configs.qwen4_exp import Qwen4ExpTextConfig
|
|
|
|
from .ngram_embedding import (
|
|
Qwen4ExpNGramEmbedding,
|
|
Qwen4ExpPLEEmbeddingMethod,
|
|
Qwen4ExpPLEFp8EmbeddingMethod,
|
|
Qwen4ExpPLEUnquantizedEmbeddingMethod,
|
|
)
|
|
|
|
logger = init_logger(__name__)
|
|
|
|
#: The backend name this module reports in the PLE producer log line.
|
|
PULL_BACKEND_NAME = "E2PullTransport"
|
|
|
|
|
|
class Qwen4ExpNGramEmbeddingPull(PleOffloadLayer, Qwen4ExpNGramEmbedding):
|
|
"""Upstream n-gram embedding whose table lives in the offload process."""
|
|
|
|
#: GPU placeholder: the method the offload process will use for the table,
|
|
#: resolved with upstream's own selector (set by ``build``).
|
|
_offload_quant_method: Qwen4ExpPLEEmbeddingMethod | None = None
|
|
|
|
def __init__(
|
|
self,
|
|
config: Qwen4ExpTextConfig,
|
|
embedding_dim: int,
|
|
ple_dense_layer_id: int,
|
|
max_total_tokens: int,
|
|
*,
|
|
data_parallel_rank: int,
|
|
prefix: str,
|
|
quant_config: QuantizationConfig | None = None,
|
|
params_dtype: torch.dtype | None = None,
|
|
) -> None:
|
|
# Runs only in the offload process (guarded by PleOffloadLayer).
|
|
engram_config = get_current_vllm_config().engram_config
|
|
if engram_config is not None and engram_config.cpu_offload:
|
|
raise RuntimeError(
|
|
"PLE pull transport: the offload process resolved "
|
|
"cpu_offload=True; refusing to build upstream's UVA table here."
|
|
)
|
|
Qwen4ExpNGramEmbedding.__init__(
|
|
self,
|
|
config,
|
|
embedding_dim,
|
|
ple_dense_layer_id,
|
|
max_total_tokens,
|
|
data_parallel_rank=data_parallel_rank,
|
|
prefix=prefix,
|
|
quant_config=quant_config,
|
|
params_dtype=params_dtype,
|
|
)
|
|
|
|
@classmethod
|
|
def build(
|
|
cls,
|
|
config: Qwen4ExpTextConfig,
|
|
embedding_dim: int,
|
|
ple_dense_layer_id: int,
|
|
max_total_tokens: int,
|
|
*,
|
|
data_parallel_rank: int,
|
|
prefix: str,
|
|
quant_config: QuantizationConfig | None,
|
|
params_dtype: torch.dtype | None,
|
|
) -> "Qwen4ExpNGramEmbeddingPull":
|
|
"""Construct the placeholder (GPU) or the full CPU module (offload)."""
|
|
# The offload process builds the surrounding model on meta; this
|
|
# subtree must own real CPU storage. In a GPU worker the constructor is
|
|
# skipped, so the device context allocates nothing.
|
|
with torch.device(cls.get_target_device()):
|
|
module = cls(
|
|
config,
|
|
embedding_dim,
|
|
ple_dense_layer_id,
|
|
max_total_tokens,
|
|
data_parallel_rank=data_parallel_rank,
|
|
prefix=prefix,
|
|
quant_config=quant_config,
|
|
params_dtype=params_dtype,
|
|
)
|
|
embedding_prefix = f"{prefix}.ngram_embedding"
|
|
method = Qwen4ExpPLEEmbeddingMethod.from_quant_config(
|
|
quant_config,
|
|
embedding_prefix,
|
|
getattr(config, "ple_embedding_dtype", None),
|
|
)
|
|
if not isinstance(
|
|
method,
|
|
(Qwen4ExpPLEFp8EmbeddingMethod, Qwen4ExpPLEUnquantizedEmbeddingMethod),
|
|
):
|
|
raise NotImplementedError(
|
|
f"PLE pull transport does not support {type(method).__name__}"
|
|
)
|
|
module._offload_quant_method = method
|
|
module._pull_params_dtype = params_dtype or torch.get_default_dtype()
|
|
module._pull_embedding_prefix = embedding_prefix
|
|
if not is_offload_process():
|
|
# The GPU-rank producer line, in upstream's format plus backend=
|
|
# (the offload process logs its own table line from upstream's
|
|
# constructor). The table lives in the offload process's CPU memory
|
|
# and is not pinned; rows cross via host-mapped buffers.
|
|
logger.info(
|
|
"Initialized PLE embedding %s: quantization_method=%s, "
|
|
"weight_dtype=%s, weight_device=%s, pinned=%s, backend=%s",
|
|
embedding_prefix,
|
|
type(method).__name__,
|
|
module.get_offload_output_dtype(module._pull_params_dtype),
|
|
"cpu",
|
|
False,
|
|
PULL_BACKEND_NAME,
|
|
)
|
|
return module
|
|
|
|
# ------------------------------------------------------------- formats
|
|
|
|
def get_offload_output_dtype(self, default_dtype: torch.dtype) -> torch.dtype:
|
|
"""Rows cross the transport in their table storage dtype."""
|
|
embedding = getattr(self, "ngram_embedding", None)
|
|
weight = getattr(embedding, "weight", None)
|
|
if weight is not None:
|
|
return weight.dtype
|
|
if isinstance(self._offload_quant_method, Qwen4ExpPLEFp8EmbeddingMethod):
|
|
return torch.float8_e4m3fn
|
|
return getattr(self, "_pull_params_dtype", default_dtype)
|
|
|
|
def get_offload_output_dim(self, default_dim: int) -> int:
|
|
return default_dim
|
|
|
|
def initialize_dummy_offload_metadata(self, device: torch.device) -> None:
|
|
"""Dummy loads skip checkpoint scales; give FP8 a unit scale."""
|
|
if isinstance(self._offload_quant_method, Qwen4ExpPLEFp8EmbeddingMethod):
|
|
self.register_buffer(
|
|
"_offload_weight_scale",
|
|
torch.ones((), dtype=torch.float32, device=device),
|
|
persistent=False,
|
|
)
|
|
|
|
def dequantize_pulled(
|
|
self, embeddings: torch.Tensor, output_dtype: torch.dtype
|
|
) -> torch.Tensor:
|
|
"""GPU-side dequantization of rows DMA'd from the offload process.
|
|
|
|
Same arithmetic as upstream ``Qwen4ExpPLEFp8EmbeddingMethod.dequantize``
|
|
(and the E2 ``_dequantize_embeddings`` FP8 branch).
|
|
"""
|
|
method = self._offload_quant_method
|
|
if isinstance(method, Qwen4ExpPLEUnquantizedEmbeddingMethod):
|
|
return embeddings
|
|
weight_scale = getattr(self, "_offload_weight_scale", None)
|
|
if weight_scale is None:
|
|
raise RuntimeError(
|
|
"FP8 PLE pull transport is missing its global scale on the GPU"
|
|
)
|
|
if weight_scale.device != embeddings.device:
|
|
raise RuntimeError("FP8 PLE embedding scale must be on the output device")
|
|
return embeddings.to(output_dtype) * weight_scale.to(output_dtype)
|
|
|
|
# ------------------------------------------------------------- execution
|
|
|
|
def start_prefetch(
|
|
self,
|
|
hidden_states: torch.Tensor,
|
|
input_ids: torch.Tensor,
|
|
query_start_loc: torch.Tensor,
|
|
ngram_context: torch.Tensor,
|
|
) -> None:
|
|
"""No prefetch: rows are published by the offload process."""
|
|
return None
|
|
|
|
def _compute_ngram_ids_offload(
|
|
self,
|
|
input_ids: torch.Tensor,
|
|
query_start_loc: torch.Tensor,
|
|
ngram_context: torch.Tensor,
|
|
) -> torch.Tensor:
|
|
"""CPU n-gram IDs, carried unchanged from the E2 offload path.
|
|
|
|
Differs from upstream's CPU branch in two E2 fixes: the packed layout
|
|
is (num_reqs, max_seq_len) rather than (num_reqs, num_tokens), and
|
|
CUDA-graph padding rows beyond ``query_start_loc[-1]`` are not written,
|
|
so they cannot overwrite a request's final real token.
|
|
"""
|
|
input_ids = input_ids.reshape(-1).long()
|
|
query_start_loc = query_start_loc.long()
|
|
num_reqs = query_start_loc.numel() - 1
|
|
num_tokens = input_ids.shape[0]
|
|
if num_reqs <= 0:
|
|
raise ValueError("PLE requires at least one request")
|
|
max_seq_len = max(
|
|
1,
|
|
int((query_start_loc[1:] - query_start_loc[:-1]).max().item()),
|
|
)
|
|
num_valid_tokens = min(int(query_start_loc[-1].item()), num_tokens)
|
|
|
|
positions = torch.arange(num_tokens, device=input_ids.device, dtype=torch.int64)
|
|
packed = torch.full(
|
|
(num_reqs, max_seq_len),
|
|
self.eos_token_id,
|
|
device=input_ids.device,
|
|
dtype=torch.int64,
|
|
)
|
|
request_indices = torch.searchsorted(query_start_loc, positions, right=True) - 1
|
|
request_indices.clamp_(max=num_reqs - 1)
|
|
columns = (positions - query_start_loc[request_indices]).clamp(
|
|
0, packed.shape[1] - 1
|
|
)
|
|
packed[request_indices[:num_valid_tokens], columns[:num_valid_tokens]] = (
|
|
input_ids[:num_valid_tokens]
|
|
)
|
|
ngram_context = ngram_context[:num_reqs].to(
|
|
device=input_ids.device, dtype=torch.long
|
|
)
|
|
|
|
context = torch.cat([ngram_context, packed], dim=-1)
|
|
positions_2d, position_in_segment = self._shift_precompute(
|
|
context, self.eos_token_id
|
|
)
|
|
shifted = [context]
|
|
for shift in range(1, self.ngram_size):
|
|
shifted.append(
|
|
self._shift_apply(
|
|
context,
|
|
positions_2d,
|
|
position_in_segment,
|
|
shift,
|
|
self.eos_token_id,
|
|
)
|
|
)
|
|
adjusted_columns = columns + self.ngram_size - 1
|
|
id_blocks = []
|
|
for ngram in range(2, self.ngram_size + 1):
|
|
start = (ngram - 2) * self.heads_per_ngram
|
|
end = start + self.heads_per_ngram
|
|
mixed = shifted[0] * self.layer_multipliers[0]
|
|
for index in range(1, ngram):
|
|
mixed = torch.bitwise_xor(
|
|
mixed, shifted[index] * self.layer_multipliers[index]
|
|
)
|
|
sizes = self.ngram_heads_vocab_sizes[start:end]
|
|
offsets = self.ngram_heads_offsets[start:end]
|
|
ids = torch.remainder(mixed.unsqueeze(-1), sizes) + offsets
|
|
id_blocks.append(ids[request_indices, adjusted_columns])
|
|
return torch.cat(id_blocks, dim=-1)
|
|
|
|
def forward_impl( # type: ignore[override]
|
|
self,
|
|
hidden_states: torch.Tensor,
|
|
input_ids: torch.Tensor,
|
|
query_start_loc: torch.Tensor,
|
|
ngram_context: torch.Tensor,
|
|
output_buffer: torch.Tensor | None = None,
|
|
) -> torch.Tensor:
|
|
"""Offload process only: gather raw table rows for these tokens."""
|
|
del hidden_states
|
|
if not is_offload_process():
|
|
raise RuntimeError(
|
|
"PLE pull transport: forward_impl ran outside the offload "
|
|
"process -- the GPU placeholder was never bound by the connector"
|
|
)
|
|
ngram_ids = self._compute_ngram_ids_offload(
|
|
input_ids, query_start_loc, ngram_context
|
|
)
|
|
num_tokens = input_ids.reshape(-1).shape[0]
|
|
weight = self.ngram_embedding.weight
|
|
if output_buffer is not None:
|
|
output = output_buffer[:num_tokens, : self.embedding_dim]
|
|
torch.index_select(
|
|
weight,
|
|
0,
|
|
ngram_ids.reshape(-1),
|
|
out=output.reshape(-1, self.head_dim),
|
|
)
|
|
return output
|
|
return torch.index_select(weight, 0, ngram_ids.reshape(-1)).reshape(
|
|
num_tokens, self.embedding_dim
|
|
)
|
|
|
|
# ------------------------------------------------------------- loading
|
|
|
|
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
|
"""Offload process: upstream loading. GPU worker: keep the FP8 scale.
|
|
|
|
The GPU placeholder owns no table; every other checkpoint tensor for
|
|
this subtree is consumed and dropped here (the offload process loads
|
|
the table itself). Prefix grouping may call this more than once.
|
|
"""
|
|
if is_offload_process():
|
|
return Qwen4ExpNGramEmbedding.load_weights(self, weights)
|
|
retained: set[str] = set()
|
|
fp8 = isinstance(self._offload_quant_method, Qwen4ExpPLEFp8EmbeddingMethod)
|
|
for name, loaded_weight in weights:
|
|
if fp8 and name == "ngram_embedding.weight_scale":
|
|
self.register_buffer(
|
|
"_offload_weight_scale",
|
|
loaded_weight.reshape(()).to(
|
|
device=torch.accelerator.current_accelerator(),
|
|
dtype=torch.float32,
|
|
),
|
|
persistent=False,
|
|
)
|
|
retained.add(name)
|
|
return retained
|
|
|
|
|
|
__all__ = ["PULL_BACKEND_NAME", "Qwen4ExpNGramEmbeddingPull"]
|