| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | from typing import Any, Protocol, cast |
| 5 | |
| 6 | |
| 7 | class AdmissionCounterBuffer(Protocol): |
| 8 | def __getitem__(self, index: int) -> int: ... |
| 9 | |
| 10 | def __setitem__(self, index: int, value: int) -> None: ... |
| 11 | |
| 12 | |
| 13 | class SharedAdmissionStats: |
| 14 | """Lock-free admission stats shared by API server processes. |
| 15 | |
| 16 | Each process writes exclusively to its own cache-line-sized slot. Readers |
| 17 | aggregate the slots, avoiding both inter-process locks and cache-line |
| 18 | contention on the request path. |
| 19 | """ |
| 20 | |
| 21 | # Space per-process counters 64 bytes apart to avoid false sharing on CPUs |
| 22 | # with 64-byte cache lines: one process's writes would otherwise invalidate |
| 23 | # the cache line containing another process's counter. |
| 24 | CACHE_LINE_BYTES = 64 |
| 25 | COUNTER_BYTES = 8 |
| 26 | COUNTERS_PER_SLOT = CACHE_LINE_BYTES // COUNTER_BYTES |
| 27 | |
| 28 | def __init__( |
| 29 | self, |
| 30 | client_addresses: dict[str, Any], |
| 31 | client_count: int = 1, |
| 32 | client_index: int = 0, |
| 33 | ): |
| 34 | self._counters = cast( |
| 35 | AdmissionCounterBuffer, |
| 36 | client_addresses.pop("mp_admission_counters"), |
| 37 | ) |
| 38 | self._client_count = client_count |
| 39 | self._slot_offset = client_index * self.COUNTERS_PER_SLOT |
| 40 | |
| 41 | @classmethod |
| 42 | def num_counters(cls, client_count: int) -> int: |
| 43 | return client_count * cls.COUNTERS_PER_SLOT |
| 44 | |
| 45 | def set_num_requests(self, count: int) -> None: |
| 46 | self._counters[self._slot_offset] = count |
| 47 | |
| 48 | def get_num_requests(self) -> int: |
| 49 | return sum( |
| 50 | self._counters[client_index * self.COUNTERS_PER_SLOT] |
| 51 | for client_index in range(self._client_count) |
| 52 | ) |