[Perf] Integrate flash-maxsim Triton kernels for late-interaction scoring (#40337)
Signed-off-by: roi.pony <roi.pony@ibm.com> Co-authored-by: roi.pony <roi.pony@ibm.com> Co-authored-by: Taneem Ibrahim <taneem.ibrahim@gmail.com>
This commit is contained in:
co-authored by
roi.pony
Taneem Ibrahim
parent
083060d046
commit
e9be5323f0
@@ -0,0 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Fused Triton kernels for late-interaction (MaxSim) scoring."""
|
||||
|
||||
from .flash_maxsim_rerank import flash_maxsim_rerank_direct
|
||||
|
||||
__all__ = ["flash_maxsim_rerank_direct"]
|
||||
@@ -0,0 +1,85 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Shared utilities for flash-maxsim kernels: padding, autotune configs,
|
||||
and pruning."""
|
||||
|
||||
from vllm.triton_utils import triton
|
||||
|
||||
|
||||
def _next_pow2(x: int) -> int:
|
||||
return 1 << (x - 1).bit_length()
|
||||
|
||||
|
||||
def _get_configs() -> list:
|
||||
"""Autotune grid over (BLOCK_Q, BLOCK_D); `_prune_configs` filters by
|
||||
SMEM budget and Lq at runtime, so one list is safe across GPUs."""
|
||||
return [
|
||||
triton.Config({"BLOCK_Q": 16, "BLOCK_D": 16}, num_warps=2, num_stages=2),
|
||||
triton.Config({"BLOCK_Q": 16, "BLOCK_D": 32}, num_warps=2, num_stages=2),
|
||||
triton.Config({"BLOCK_Q": 32, "BLOCK_D": 16}, num_warps=2, num_stages=2),
|
||||
triton.Config({"BLOCK_Q": 32, "BLOCK_D": 32}, num_warps=4, num_stages=2),
|
||||
triton.Config({"BLOCK_Q": 32, "BLOCK_D": 64}, num_warps=4, num_stages=2),
|
||||
triton.Config({"BLOCK_Q": 32, "BLOCK_D": 128}, num_warps=8, num_stages=2),
|
||||
triton.Config({"BLOCK_Q": 64, "BLOCK_D": 64}, num_warps=4, num_stages=2),
|
||||
triton.Config({"BLOCK_Q": 64, "BLOCK_D": 128}, num_warps=8, num_stages=1),
|
||||
triton.Config({"BLOCK_Q": 128, "BLOCK_D": 64}, num_warps=8, num_stages=1),
|
||||
triton.Config({"BLOCK_Q": 128, "BLOCK_D": 128}, num_warps=8, num_stages=1),
|
||||
]
|
||||
|
||||
|
||||
def _smem_budget() -> int:
|
||||
"""Per-block opt-in shared-memory budget of the active device (bytes):
|
||||
Triton driver query, else a conservative capability table."""
|
||||
try:
|
||||
driver = triton.runtime.driver.active
|
||||
props = driver.utils.get_device_properties(driver.get_current_device())
|
||||
return int(props["max_shared_mem"])
|
||||
except Exception:
|
||||
try:
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
cap = current_platform.get_device_capability()
|
||||
if cap is not None:
|
||||
if cap.major >= 9:
|
||||
return 232_448 # Hopper+: 227 KB opt-in
|
||||
if cap.major == 8:
|
||||
return 101_376 # worst sm_8x (86/89); A100 has more
|
||||
except Exception:
|
||||
pass
|
||||
return 98_304 # conservative pre-Ampere default
|
||||
|
||||
|
||||
def _prune_configs(configs, named_args, **kwargs):
|
||||
"""Reject configs that exceed the GPU's shared-memory budget.
|
||||
|
||||
BLOCK_Q and BLOCK_D load fp16 tiles of size [BLOCK_*, d_pad] — the
|
||||
kernels index with ``tl.arange(0, d_pad)``, so the estimate must use
|
||||
the padded dimension, not the real one (d=513 pads to 1024 and
|
||||
nearly doubles the tile) — and the [BLOCK_Q, BLOCK_D] score tile is
|
||||
fp32. Total:
|
||||
(BLOCK_Q*d_pad + BLOCK_D*d_pad)*2 + BLOCK_Q*BLOCK_D*4 bytes.
|
||||
"""
|
||||
Lq = named_args.get("Lq", 32)
|
||||
d_pad = named_args.get("d_pad")
|
||||
if d_pad is None:
|
||||
d_pad = _next_pow2(max(named_args.get("d", 128), 16))
|
||||
smem_limit = _smem_budget()
|
||||
|
||||
def _est(cfg):
|
||||
bq = cfg.kwargs["BLOCK_Q"]
|
||||
bd = cfg.kwargs["BLOCK_D"]
|
||||
return (bq * d_pad + bd * d_pad) * 2 + bq * bd * 4
|
||||
|
||||
pruned = []
|
||||
for cfg in configs:
|
||||
if cfg.kwargs["BLOCK_Q"] > Lq * 2:
|
||||
continue
|
||||
if _est(cfg) > smem_limit:
|
||||
continue
|
||||
pruned.append(cfg)
|
||||
if pruned:
|
||||
return pruned
|
||||
# Nothing fits the estimate (large d_pad on a small-SMEM device).
|
||||
# Return the single smallest-footprint config — a deterministic
|
||||
# least-bad launch attempt — never arbitrary rejected configs.
|
||||
return [min(configs, key=_est)]
|
||||
@@ -0,0 +1,204 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Flash-MaxSim rerank: one query vs variable-length docs in a packed tensor.
|
||||
|
||||
The kernel reads doc embeddings directly from a packed [total_tokens, d]
|
||||
tensor using per-doc (offset, length) pairs — no padding, no per-doc
|
||||
tensors, no materialised [B, Lq, Ld] similarity tensor.
|
||||
|
||||
Entry point:
|
||||
flash_maxsim_rerank_direct(Q, batch_tensor, doc_offsets, doc_lengths, max_ld)
|
||||
doc_offsets[i] = start token index of doc i in batch_tensor.
|
||||
doc_lengths[i] = number of tokens in doc i.
|
||||
Docs can be scattered (non-contiguous) in the batch tensor.
|
||||
"""
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
from ._common import _get_configs, _next_pow2, _prune_configs
|
||||
|
||||
|
||||
def _round_to_bucket(x):
|
||||
"""Round up to nearest bucket: 32, 64, 128, 256, 512, 1024, 2048, 4096."""
|
||||
for b in [32, 64, 128, 256, 512, 1024, 2048, 4096]:
|
||||
if x <= b:
|
||||
return b
|
||||
return _next_pow2(x)
|
||||
|
||||
|
||||
# Kernel: shared Q, scattered D via (offset, length) per doc
|
||||
|
||||
|
||||
@triton.autotune(
|
||||
configs=_get_configs(),
|
||||
key=["Lq_bucket", "max_Ld_bucket", "d_pad"],
|
||||
prune_configs_by={"early_config_prune": _prune_configs},
|
||||
)
|
||||
@triton.jit
|
||||
def _maxsim_rerank_kernel(
|
||||
Q_ptr,
|
||||
D_ptr,
|
||||
doc_offsets_ptr,
|
||||
doc_lengths_ptr,
|
||||
scores_ptr,
|
||||
B,
|
||||
Lq,
|
||||
Lq_bucket: tl.constexpr,
|
||||
max_Ld_bucket: tl.constexpr,
|
||||
d: tl.constexpr,
|
||||
d_pad: tl.constexpr,
|
||||
stride_q_t,
|
||||
stride_q_d,
|
||||
stride_d_t,
|
||||
stride_d_d,
|
||||
BLOCK_Q: tl.constexpr,
|
||||
BLOCK_D: tl.constexpr,
|
||||
):
|
||||
"""One program per doc. Q shared (read from same location). D scattered."""
|
||||
pid = tl.program_id(0)
|
||||
if pid >= B:
|
||||
return
|
||||
|
||||
# Each doc has its own offset and length in the batch tensor.
|
||||
# int64: (d_start + d_off) * stride overflows int32 past ~16.7M batch
|
||||
# tokens (same widen-on-load as the pairs kernel below; the host-side
|
||||
# offsets tensor stays int32, which indexes any realistic batch).
|
||||
d_start = tl.load(doc_offsets_ptr + pid).to(tl.int64)
|
||||
d_len = tl.load(doc_lengths_ptr + pid).to(tl.int32)
|
||||
|
||||
k_off = tl.arange(0, d_pad)
|
||||
k_mask = k_off < d
|
||||
score_acc = tl.zeros([], dtype=tl.float32)
|
||||
|
||||
# Q is shared — always read from start of Q_ptr
|
||||
for q_blk in tl.static_range(0, Lq_bucket, BLOCK_Q):
|
||||
q_off = q_blk + tl.arange(0, BLOCK_Q)
|
||||
q_valid = q_off < Lq
|
||||
|
||||
Q_block = tl.load(
|
||||
Q_ptr + q_off[:, None] * stride_q_t + k_off[None, :] * stride_q_d,
|
||||
mask=q_valid[:, None] & k_mask[None, :],
|
||||
other=0.0,
|
||||
).to(tl.float16)
|
||||
|
||||
m = tl.full([BLOCK_Q], float("-inf"), dtype=tl.float32)
|
||||
|
||||
for d_blk in range(0, max_Ld_bucket, BLOCK_D):
|
||||
d_off = d_blk + tl.arange(0, BLOCK_D)
|
||||
d_valid = d_off < d_len
|
||||
|
||||
D_block = tl.load(
|
||||
D_ptr
|
||||
+ (d_start + d_off[:, None]) * stride_d_t
|
||||
+ k_off[None, :] * stride_d_d,
|
||||
mask=d_valid[:, None] & k_mask[None, :],
|
||||
other=0.0,
|
||||
).to(tl.float16)
|
||||
|
||||
S = tl.dot(Q_block, tl.trans(D_block))
|
||||
S = tl.where(d_valid[None, :], S, float("-inf"))
|
||||
m = tl.maximum(m, tl.max(S, axis=1))
|
||||
|
||||
m = tl.where(q_valid, m, 0.0)
|
||||
score_acc += tl.sum(m)
|
||||
|
||||
tl.store(scores_ptr + pid, score_acc)
|
||||
|
||||
|
||||
# Internal helper
|
||||
|
||||
|
||||
def _run_rerank_kernel(Q, D_tensor, doc_offsets, doc_lengths, max_seqlen_d):
|
||||
"""Common kernel launch for both rerank and rerank_direct."""
|
||||
assert Q.is_cuda, f"Q must be on CUDA, got {Q.device}"
|
||||
assert D_tensor.is_cuda, f"D must be on CUDA, got {D_tensor.device}"
|
||||
Lq, d = Q.shape
|
||||
B = doc_offsets.shape[0]
|
||||
d_pad = _next_pow2(max(d, 16))
|
||||
|
||||
Q = Q.contiguous().half()
|
||||
# D_tensor is NOT copied — kernel reads from it directly
|
||||
if not D_tensor.is_contiguous():
|
||||
D_tensor = D_tensor.contiguous()
|
||||
if D_tensor.dtype != torch.float16:
|
||||
D_tensor = D_tensor.half()
|
||||
|
||||
doc_offsets = doc_offsets.to(torch.int32).contiguous()
|
||||
doc_lengths = doc_lengths.to(torch.int32).contiguous()
|
||||
scores = torch.empty(B, device=Q.device, dtype=torch.float32)
|
||||
|
||||
if B == 0:
|
||||
return scores
|
||||
|
||||
# Pad Q dimension if needed (Q is small, safe to copy).
|
||||
# D is NOT padded — the kernel uses k_mask to handle d < d_pad.
|
||||
# This preserves zero-copy: D_tensor is read in-place.
|
||||
if d < d_pad:
|
||||
Q_pad = torch.zeros(Lq, d_pad, device=Q.device, dtype=Q.dtype)
|
||||
Q_pad[:, :d] = Q
|
||||
else:
|
||||
Q_pad = Q
|
||||
D_pad = D_tensor
|
||||
|
||||
Lq_bucket = _round_to_bucket(Lq)
|
||||
max_ld_bucket = _round_to_bucket(max_seqlen_d)
|
||||
|
||||
_maxsim_rerank_kernel[(B,)](
|
||||
Q_pad,
|
||||
D_pad,
|
||||
doc_offsets,
|
||||
doc_lengths,
|
||||
scores,
|
||||
B,
|
||||
Lq,
|
||||
Lq_bucket,
|
||||
max_ld_bucket,
|
||||
d,
|
||||
d_pad,
|
||||
Q_pad.stride(0),
|
||||
Q_pad.stride(1),
|
||||
D_pad.stride(0),
|
||||
D_pad.stride(1),
|
||||
)
|
||||
return scores
|
||||
|
||||
|
||||
# Public API
|
||||
|
||||
|
||||
def flash_maxsim_rerank_direct(
|
||||
Q: torch.Tensor,
|
||||
batch_tensor: torch.Tensor,
|
||||
doc_offsets: torch.Tensor,
|
||||
doc_lengths: torch.Tensor,
|
||||
max_seqlen_d: int,
|
||||
) -> torch.Tensor:
|
||||
"""TRUE zero-copy: score query against docs scattered in a batch tensor.
|
||||
|
||||
The kernel reads doc embeddings directly from batch_tensor at the
|
||||
positions specified by doc_offsets. No torch.stack, no torch.cat,
|
||||
no copy of any kind. The batch tensor is the model's output.
|
||||
|
||||
Memory for doc scoring: 0 bytes additional.
|
||||
|
||||
Args:
|
||||
Q: [Lq, d] — single query embedding (from cache)
|
||||
batch_tensor: [total_tokens, d] — the model's projected output tensor.
|
||||
Contains ALL requests' tokens (queries + docs + others).
|
||||
doc_offsets: [B] int32 — start token index of each doc in batch_tensor
|
||||
doc_lengths: [B] int32 — number of tokens per doc
|
||||
max_seqlen_d: int — max(doc_lengths)
|
||||
|
||||
Returns:
|
||||
scores: [B] float32 — one MaxSim score per document
|
||||
|
||||
"""
|
||||
assert Q.dim() == 2, f"Q must be 2D [Lq, d], got {Q.dim()}D"
|
||||
assert batch_tensor.dim() == 2, (
|
||||
f"batch_tensor must be 2D, got {batch_tensor.dim()}D"
|
||||
)
|
||||
assert Q.shape[1] == batch_tensor.shape[1]
|
||||
|
||||
return _run_rerank_kernel(Q, batch_tensor, doc_offsets, doc_lengths, max_seqlen_d)
|
||||
Reference in New Issue
Block a user