[Perf] Avoid some more unnecessary GPU<->CPU syncs (#51458)

Signed-off-by: Nick Hill <nickhill123@gmail.com>
This commit is contained in:
Nick Hill
2026-08-08 17:13:26 -07:00
committed by GitHub
parent d608dfabfd
commit 9b0afeb4f6
13 changed files with 99 additions and 49 deletions
+32 -4
View File
@@ -55,6 +55,7 @@ from vllm.multimodal.processing import (
)
from vllm.sequence import IntermediateTensors
from vllm.utils.tensor_schema import TensorSchema, TensorShape
from vllm.utils.torch_utils import async_tensor_h2d
from .interfaces import (
MultiModalEmbeddings,
@@ -819,8 +820,20 @@ class ChameleonImageVocabularyMapping:
def convert_img2bpe(self, img_batch: torch.Tensor) -> torch.Tensor:
device = img_batch.device
img_tokens = self.img2bpe_mapping_tensor[img_batch.to("cpu")]
return img_tokens.to(device)
# Cache a per-device copy of the (small, static) mapping tensor so we
# can index entirely on `device` instead of forcing a D2H on
# `img_batch` and an H2D on the result.
cache = getattr(self, "_img2bpe_mapping_cache", None)
if cache is None:
cache = {}
self._img2bpe_mapping_cache = cache
mapping_on_device = cache.get(device)
if mapping_on_device is None:
mapping_on_device = async_tensor_h2d(
self.img2bpe_mapping_tensor, device=device
)
cache[device] = mapping_on_device
return mapping_on_device[img_batch]
class ChameleonModel(nn.Module):
@@ -1025,8 +1038,23 @@ class ChameleonForConditionalGeneration(
# Disallow image tokens which does not include special
# begin-image and end-image tokens
if logits is not None:
image_tokens = self.model.vocabulary_mapping.image_tokens
logits[:, image_tokens] = torch.finfo(logits.dtype).min
# Cache a per-device index tensor for the (static) image-token
# set, and use `index_fill_` instead of advanced-index assign
# so the scatter runs entirely on device (no host roundtrip
# for the scalar fill value or for the Python-list indices).
cache = getattr(self, "_image_tokens_index_cache", None)
if cache is None:
cache = {}
self._image_tokens_index_cache = cache
image_tokens_idx = cache.get(logits.device)
if image_tokens_idx is None:
image_tokens_idx = async_tensor_h2d(
self.model.vocabulary_mapping.image_tokens,
dtype=torch.long,
device=logits.device,
)
cache[logits.device] = image_tokens_idx
logits.index_fill_(1, image_tokens_idx, torch.finfo(logits.dtype).min)
return logits