[BugFix][310P][v0.18.0] Use CPU generator cache for sampling (#8624)

### What this PR does / why we need it?
This PR introduces a caching mechanism for CPU-based `torch.Generator`
objects in the `_random_sample_310p` function to optimize sampling
performance. It includes unit tests for cache persistence and state
recovery. Feedback highlights a critical bug where keying the cache by
batch index instead of generator ID can break RNG reproducibility during
request re-scheduling, and notes a potential memory leak in the global
cache.

### Does this PR introduce _any_ user-facing change?
No.

### How was this patch tested?
Tested via new unit tests in `tests/ut/_310p/sample/test_sampler_310.py`
verifying cache logic and error handling.

---------

Signed-off-by: csoulnd <daidaicurry@foxmail.com>
This commit is contained in:
csoulnd
2026-04-24 09:34:14 +08:00
committed by GitHub
parent 00ddacf4e7
commit 97dbcaf919
2 changed files with 215 additions and 1 deletions

View File

@@ -25,6 +25,8 @@ from vllm_ascend.sample.sampler import (
)
from vllm_ascend.utils import global_stream, npu_stream_switch
_CPU_GENERATOR_CACHE_310P: dict[int, tuple[torch.Generator, int]] = {}
def _random_sample_310p(
probs: torch.Tensor,
@@ -38,7 +40,18 @@ def _random_sample_310p(
q.exponential_()
if generators:
for i, generator in generators.items():
q[i].exponential_(generator=generator)
cache_entry = _CPU_GENERATOR_CACHE_310P.get(i)
if cache_entry is None or cache_entry[1] != id(generator):
cpu_generator = torch.Generator(device="cpu")
try:
# Keep RNG stream consistent with the original generator.
cpu_generator.set_state(generator.get_state())
except Exception:
cpu_generator.manual_seed(generator.initial_seed())
cache_entry = (cpu_generator, id(generator))
_CPU_GENERATOR_CACHE_310P[i] = cache_entry
cpu_generator, _ = cache_entry
q[i].exponential_(generator=cpu_generator)
q = q.npu()
torch.npu.current_stream().wait_stream(global_stream())
return probs.div_(q).argmax(dim=-1).view(-1)