| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | from collections.abc import Iterable, Sequence |
| 4 | from functools import partial |
| 5 | |
| 6 | import numpy as np |
| 7 | import torch |
| 8 | |
| 9 | from vllm.logger import init_logger |
| 10 | from vllm.triton_utils import tl, triton |
| 11 | from vllm.utils.platform_utils import is_uva_available |
| 12 | from vllm.utils.torch_utils import ( |
| 13 | async_tensor_h2d, |
| 14 | get_accelerator_view_from_cpu_tensor, |
| 15 | ) |
| 16 | |
| 17 | logger = init_logger(__name__) |
| 18 | |
| 19 | # Default round-robin depth for the UVA buffer pools. Must be >= the number of |
| 20 | # concurrent in-flight steps (engine batch_queue_size). |
| 21 | _DEFAULT_MAX_CONCURRENCY = 2 |
| 22 | |
| 23 | |
| 24 | def set_default_max_concurrency(n: int) -> None: |
| 25 | global _DEFAULT_MAX_CONCURRENCY |
| 26 | _DEFAULT_MAX_CONCURRENCY = max(2, n) |
| 27 | |
| 28 | |
| 29 | class UvaBuffer: |
| 30 | def __init__(self, size: int | Sequence[int], dtype: torch.dtype): |
| 31 | if not is_uva_available(): |
| 32 | raise RuntimeError("UVA is not available") |
| 33 | self.cpu = torch.zeros(size, dtype=dtype, device="cpu", pin_memory=True) |
| 34 | self.np = self.cpu.numpy() |
| 35 | self._uva = get_accelerator_view_from_cpu_tensor(self.cpu) |
| 36 | |
| 37 | def uva(self, n: int | None = None) -> torch.Tensor: |
| 38 | return self._uva[:n] if n is not None else self._uva |
| 39 | |
| 40 | |
| 41 | class NonUvaBuffer: |
| 42 | """Explicit-copy fallback for platforms without pinned memory.""" |
| 43 | |
| 44 | def __init__(self, size: int | Sequence[int], dtype: torch.dtype): |
| 45 | from vllm.platforms import current_platform |
| 46 | |
| 47 | logger.warning_once( |
| 48 | "Pinned memory is not available on this platform; falling back " |
| 49 | "to device memory for UVA buffers." |
| 50 | ) |
| 51 | self.cpu = torch.zeros(size, dtype=dtype, device="cpu") |
| 52 | self.np = self.cpu.numpy() |
| 53 | self._uva = torch.zeros(size, dtype=dtype, device=current_platform.device_type) |
| 54 | |
| 55 | def uva(self, n: int | None = None) -> torch.Tensor: |
| 56 | if n is None: |
| 57 | return self._uva.copy_(self.cpu) |
| 58 | return self._uva[:n].copy_(self.cpu[:n]) |
| 59 | |
| 60 | |
| 61 | class UvaBufferPool: |
| 62 | """Preallocate each slot at size, growing its first dimension as needed. |
| 63 | |
| 64 | Callers must retire a slot's GPU readers before reuse, including growth. |
| 65 | """ |
| 66 | |
| 67 | def __init__( |
| 68 | self, |
| 69 | size: int | Sequence[int], |
| 70 | dtype: torch.dtype, |
| 71 | max_concurrency: int | None = None, |
| 72 | ): |
| 73 | if max_concurrency is None: |
| 74 | max_concurrency = _DEFAULT_MAX_CONCURRENCY |
| 75 | self.size = size |
| 76 | self.dtype = dtype |
| 77 | self.max_concurrency = max_concurrency |
| 78 | |
| 79 | # UVA buffers for concurrency |
| 80 | self._buffer_cls = UvaBuffer if is_uva_available() else NonUvaBuffer |
| 81 | self._uva_bufs = [self._buffer_cls(size, dtype) for _ in range(max_concurrency)] |
| 82 | # Current buffer index |
| 83 | self._curr = 0 |
| 84 | |
| 85 | def copy_to_uva(self, x: torch.Tensor | np.ndarray | list) -> torch.Tensor: |
| 86 | # Round robin to the next buffer. |
| 87 | self._curr = (self._curr + 1) % self.max_concurrency |
| 88 | buf = self._uva_bufs[self._curr] |
| 89 | n = len(x) |
| 90 | if n > buf.cpu.shape[0]: |
| 91 | capacity = 1 << (n - 1).bit_length() |
| 92 | buf = self._buffer_cls((capacity, *buf.cpu.shape[1:]), self.dtype) |
| 93 | self._uva_bufs[self._curr] = buf |
| 94 | # CPU-to-CPU copy |
| 95 | dst = buf.cpu if isinstance(x, torch.Tensor) else buf.np |
| 96 | dst[:n] = x |
| 97 | return buf.uva(n) |
| 98 | |
| 99 | def copy_to_gpu( |
| 100 | self, |
| 101 | x: torch.Tensor | np.ndarray, |
| 102 | out: torch.Tensor | None = None, |
| 103 | ) -> torch.Tensor: |
| 104 | uva = self.copy_to_uva(x) |
| 105 | # CPU-to-GPU copy |
| 106 | return uva.clone() if out is None else out.copy_(uva, non_blocking=True) |
| 107 | |
| 108 | |
| 109 | class UvaBackedTensor: |
| 110 | def __init__( |
| 111 | self, |
| 112 | size: int | Sequence[int], |
| 113 | dtype: torch.dtype, |
| 114 | max_concurrency: int | None = None, |
| 115 | ): |
| 116 | self.dtype = dtype |
| 117 | |
| 118 | # Source of truth |
| 119 | self.cpu = torch.zeros(size, dtype=dtype, device="cpu", pin_memory=False) |
| 120 | self.np = self.cpu.numpy() |
| 121 | |
| 122 | # Buffers for concurrency |
| 123 | self.pool = UvaBufferPool(size, dtype, max_concurrency) |
| 124 | self.gpu = self.pool.copy_to_uva(self.np) |
| 125 | |
| 126 | def copy_to_uva(self, n: int | None = None) -> torch.Tensor: |
| 127 | # CPU-to-CPU copy |
| 128 | self.gpu = self.pool.copy_to_uva(self.np[:n] if n is not None else self.np) |
| 129 | return self.gpu |
| 130 | |
| 131 | |
| 132 | class StagedWriteTensor: |
| 133 | def __init__( |
| 134 | self, |
| 135 | size: int | Sequence[int], |
| 136 | dtype: torch.dtype, |
| 137 | device: torch.device, |
| 138 | max_concurrency: int | None = None, |
| 139 | uva_instead_of_gpu: bool = False, |
| 140 | ): |
| 141 | if max_concurrency is None: |
| 142 | max_concurrency = _DEFAULT_MAX_CONCURRENCY |
| 143 | supported_dtypes = [torch.int32, torch.int64, torch.float32] |
| 144 | if dtype not in supported_dtypes: |
| 145 | raise ValueError( |
| 146 | f"Unsupported dtype {dtype}: should be one of {supported_dtypes}" |
| 147 | ) |
| 148 | self.num_rows = size if isinstance(size, int) else size[0] |
| 149 | self.dtype = dtype |
| 150 | self.device = device |
| 151 | self.max_concurrency = max_concurrency |
| 152 | |
| 153 | # Without UVA, large-but-cold tensors live on the GPU directly. |
| 154 | uva_instead_of_gpu = uva_instead_of_gpu and is_uva_available() |
| 155 | |
| 156 | if not uva_instead_of_gpu: |
| 157 | # Create a GPU tensor (default) |
| 158 | self.gpu = torch.zeros(size, dtype=dtype, device=device) |
| 159 | else: |
| 160 | # For a large but not-frequently-accessed tensor, we can use UVA instead of |
| 161 | # GPU to save GPU memory |
| 162 | self._uva_buf = UvaBuffer(size, dtype) |
| 163 | self.gpu = self._uva_buf.uva() |
| 164 | |
| 165 | self._staged_write_indices: list[int] = [] |
| 166 | self._staged_write_starts: list[int] = [] |
| 167 | self._staged_write_contents: list[int | float] = [] |
| 168 | self._staged_write_cu_lens: list[int] = [] |
| 169 | |
| 170 | new_buffer = partial(UvaBufferPool, max_concurrency=max_concurrency) |
| 171 | |
| 172 | self.write_indices = new_buffer(self.num_rows, dtype=torch.int32) |
| 173 | self.write_starts = new_buffer(self.num_rows, dtype=torch.int32) |
| 174 | self.write_cu_lens = new_buffer(self.num_rows, dtype=torch.int32) |
| 175 | self.write_contents = new_buffer(1, dtype=dtype) if uva_instead_of_gpu else None |
| 176 | |
| 177 | def stage_write( |
| 178 | self, index: int, start: int, x: Iterable[int] | Iterable[float] |
| 179 | ) -> None: |
| 180 | assert index >= 0 |
| 181 | assert start >= 0 |
| 182 | if not x: |
| 183 | return |
| 184 | self._staged_write_indices.append(index) |
| 185 | self._staged_write_starts.append(start) |
| 186 | self._staged_write_contents.extend(x) |
| 187 | self._staged_write_cu_lens.append(len(self._staged_write_contents)) |
| 188 | |
| 189 | def stage_write_elem(self, index: int, x: int) -> None: |
| 190 | assert index >= 0 |
| 191 | self._staged_write_indices.append(index) |
| 192 | self._staged_write_starts.append(0) |
| 193 | self._staged_write_contents.append(x) |
| 194 | self._staged_write_cu_lens.append(len(self._staged_write_contents)) |
| 195 | |
| 196 | def apply_write(self) -> None: |
| 197 | n = len(self._staged_write_indices) |
| 198 | if n == 0: |
| 199 | return |
| 200 | |
| 201 | indices_uva = self.write_indices.copy_to_uva(self._staged_write_indices) |
| 202 | starts_uva = self.write_starts.copy_to_uva(self._staged_write_starts) |
| 203 | cu_lens_uva = self.write_cu_lens.copy_to_uva(self._staged_write_cu_lens) |
| 204 | |
| 205 | if self.write_contents is None: |
| 206 | write_contents = async_tensor_h2d( |
| 207 | self._staged_write_contents, device=self.device, dtype=self.dtype |
| 208 | ) |
| 209 | else: |
| 210 | write_contents = self.write_contents.copy_to_uva( |
| 211 | self._staged_write_contents |
| 212 | ) |
| 213 | |
| 214 | # Write diffs to the GPU buffer |
| 215 | _apply_write_kernel[(n,)]( |
| 216 | self.gpu, |
| 217 | self.gpu.stride(0), |
| 218 | indices_uva, |
| 219 | starts_uva, |
| 220 | write_contents, |
| 221 | cu_lens_uva, |
| 222 | None, |
| 223 | BLOCK_SIZE=1024, |
| 224 | MULTI_GROUP=False, |
| 225 | ) |
| 226 | # Clear the staged writes |
| 227 | self.clear_staged_writes() |
| 228 | |
| 229 | def clear_staged_writes(self) -> None: |
| 230 | self._staged_write_indices.clear() |
| 231 | self._staged_write_starts.clear() |
| 232 | self._staged_write_contents.clear() |
| 233 | self._staged_write_cu_lens.clear() |
| 234 | |
| 235 | |
| 236 | class FusedStagedWriter: |
| 237 | """Applies the staged writes of several `StagedWriteTensor`s at once.""" |
| 238 | |
| 239 | def __init__( |
| 240 | self, device: torch.device, max_writes: int, max_concurrency: int | None = None |
| 241 | ): |
| 242 | new_pool = partial( |
| 243 | UvaBufferPool, dtype=torch.int32, max_concurrency=max_concurrency |
| 244 | ) |
| 245 | self.group_ids = new_pool(max_writes) |
| 246 | self.indices = new_pool(max_writes) |
| 247 | self.starts = new_pool(max_writes) |
| 248 | self.cu_lens = new_pool(max_writes) |
| 249 | self.device = device |
| 250 | |
| 251 | def apply( |
| 252 | self, |
| 253 | tensors: Sequence[StagedWriteTensor], |
| 254 | output_ptrs: torch.Tensor, |
| 255 | output_strides: torch.Tensor, |
| 256 | ) -> None: |
| 257 | """Apply and clear the staged writes of `tensors` with one kernel.""" |
| 258 | group_ids: list[int] = [] |
| 259 | indices: list[int] = [] |
| 260 | starts: list[int] = [] |
| 261 | contents: list[int | float] = [] |
| 262 | cu_lens: list[int] = [] |
| 263 | |
| 264 | for group_id, t in enumerate(tensors): |
| 265 | n = len(t._staged_write_indices) |
| 266 | if n == 0: |
| 267 | continue |
| 268 | |
| 269 | group_ids.extend([group_id] * n) |
| 270 | indices.extend(t._staged_write_indices) |
| 271 | starts.extend(t._staged_write_starts) |
| 272 | content_base = len(contents) |
| 273 | contents.extend(t._staged_write_contents) |
| 274 | cu_lens.extend(content_base + cu_len for cu_len in t._staged_write_cu_lens) |
| 275 | |
| 276 | if not group_ids: |
| 277 | return |
| 278 | |
| 279 | group_ids_uva = self.group_ids.copy_to_uva(group_ids) |
| 280 | indices_uva = self.indices.copy_to_uva(indices) |
| 281 | starts_uva = self.starts.copy_to_uva(starts) |
| 282 | cu_lens_uva = self.cu_lens.copy_to_uva(cu_lens) |
| 283 | contents_gpu = async_tensor_h2d(contents, device=self.device, dtype=torch.int32) |
| 284 | |
| 285 | _apply_write_kernel[(len(group_ids),)]( |
| 286 | output_ptrs, |
| 287 | output_strides, |
| 288 | indices_uva, |
| 289 | starts_uva, |
| 290 | contents_gpu, |
| 291 | cu_lens_uva, |
| 292 | group_ids_uva, |
| 293 | BLOCK_SIZE=1024, |
| 294 | MULTI_GROUP=True, |
| 295 | ) |
| 296 | for t in tensors: |
| 297 | t.clear_staged_writes() |
| 298 | |
| 299 | |
| 300 | @triton.jit |
| 301 | def _apply_write_kernel( |
| 302 | output_ptr, # MULTI_GROUP: ptr-to-ptrs [num_groups]; else: data ptr |
| 303 | output_stride, # MULTI_GROUP: ptr-to-strides [num_groups]; else: row stride |
| 304 | write_indices_ptr, |
| 305 | write_starts_ptr, |
| 306 | write_contents_ptr, |
| 307 | write_cu_lens_ptr, |
| 308 | write_group_ids_ptr, # [num_writes], used only when MULTI_GROUP |
| 309 | BLOCK_SIZE: tl.constexpr, |
| 310 | MULTI_GROUP: tl.constexpr, |
| 311 | ): |
| 312 | pid = tl.program_id(0) |
| 313 | row_idx = tl.load(write_indices_ptr + pid) |
| 314 | start_idx = tl.load(write_starts_ptr + pid) |
| 315 | |
| 316 | cu_start = tl.load(write_cu_lens_ptr + pid - 1) if pid > 0 else 0 |
| 317 | cu_end = tl.load(write_cu_lens_ptr + pid) |
| 318 | content_len = cu_end - cu_start |
| 319 | |
| 320 | if MULTI_GROUP: |
| 321 | # Each write targets a different output tensor (KV cache group); |
| 322 | # resolve its base pointer and row stride per write. |
| 323 | group_id = tl.load(write_group_ids_ptr + pid) |
| 324 | row_ptr = _load_ptr(output_ptr + group_id, tl.int32) |
| 325 | row_stride = tl.load(output_stride + group_id) |
| 326 | else: |
| 327 | row_ptr = output_ptr |
| 328 | row_stride = output_stride |
| 329 | row_ptr += row_idx * row_stride + start_idx |
| 330 | |
| 331 | for i in range(0, content_len, BLOCK_SIZE): |
| 332 | block = i + tl.arange(0, BLOCK_SIZE) |
| 333 | mask = block < content_len |
| 334 | content = tl.load(write_contents_ptr + cu_start + block, mask=mask) |
| 335 | tl.store(row_ptr + block, content, mask=mask) |
| 336 | |
| 337 | |
| 338 | @triton.jit |
| 339 | def _load_ptr(ptr_to_ptr, elem_dtype): |
| 340 | ptr = tl.load(ptr_to_ptr) |
| 341 | ptr = tl.cast(ptr, tl.pointer_type(elem_dtype)) |
| 342 | return tl.multiple_of(ptr, 16) |