## 问题 `unilab/managers/rng.py` 的 `choice` 在每次调用时对概率表做 host 校验: ```python # rng.py:193 if p.numel() == 0 or not bool(torch.isfinite(p).all()) or bool((p < 0).any()): ``` 两个 `bool(...)` 都是 device→host 读。在 fixed-shape reset(每步全宽采样)里,`torch.cuda.set_sync_debug_mode("error")` 下会直接抛 `RuntimeError: called a synchronizing CUDA operation`,任何用 `choice(n, p=tensor)` 的 term 都无法进入 sync-free step。 ## 当前 workaround 我们把类别采样换成等价的逆 CDF 形式(设备侧、免同步): ```python cdf = torch.cumsum(probabilities, dim=0) bins = torch.searchsorted(cdf, rng.random((num_samples,)) * cdf[-1]).clamp(max=n - 1) ``` ## 请求 任选其一: 1. `choice(..., validate=False)` 跳过 host 校验(热路径调用方自担责任); 2. 或把校验挪到 `poll_finite_validation` 边界的设备 verdict(`env.require` 风格); 3. 或在文档中标注 `choice(p=...)` 非 sync-free,并提供官方 searchsorted 等价物。 ## 复现 任意 `env.step` 内调用 `rng.choice(n, p=<cuda tensor>)`,配 `torch.cuda.set_sync_debug_mode("error")`。 ## 环境 unilab 1.5.11,RTX 6000D / RTX 4090 均复现。上游关联:#2605(fixed-shape autoreset 的配套面)。
Activity
TATP-233 commentedon Nov 19, 2026
排查结论与处理方案
定位确认:问题出在
src/unilab/managers/rng.py的choice在每次调用时执行两个
bool(...)对 CUDA 张量是 device→host 读。在 fixed-shape autoreset(每步全宽采样)下,这直接阻断 sync-free step / CUDA graph 捕获,与 issue 描述一致。这个检查是否必要:否,属于冗余且违背仓库自身的校验架构
torch.multinomial自己对非法概率 fail fast,抛出清晰的RuntimeError: invalid multinomial distribution (encountering probability entry < 0)。MultinomialKernel.cu的 device-side assert 拦住(实测复现);这层校验唯一多拦住的是全零表(sum <= 0)这类构造期 bug,不该靠每步热路径校验来防。defer_finite_validation+poll_finite_validation的延迟 verdict 边界,唯独这里开了一个 eager 逐调用校验的口子。tests/managers/test_rng.py中所有pytest.raises断言均为 type/device/shape 元数据检查,无任何用例传 NaN/负数/全零表验证这个值校验;p.numel() == 0分支还是死代码(shape 检查已保证p.numel() == a > 0)。方案选择
在 issue 给的三个选项中,选择直接删除 eager 校验(而非
validate=False开关或接入延迟 verdict):choice变为 sync-free,fixed-shape autoreset 与 CUDA graph 热路径可直接使用;RuntimeError;CUDA 触发 device-side assert(报错体验变差,但仅当调用方传入非法概率这一既有 bug 时发生,非新增风险);validate=False开关会永久把责任推给调用方、污染 API 面;为构造期 bug 接入一套 verdict 接线则收益配不上复杂度。docstring 中已注明调用方契约:p须有限、非负、和为正。影响面:
ManagerRng的其他方法(uniform/normal/integers等)只查元数据、本就无 host 读,此问题为choice独有;仓库内生产代码无choice调用方,行为变更仅影响下游以choice(n, p=...)写 DR term 的用户——即本 issue 场景。修复 PR:#2625(已含 changelog 条目与 docstring 契约说明),"Closes #2624" 关联,合并后自动关闭本 issue。验证:
make check、make test-all通过;CUDA +set_sync_debug_mode("error")下choice(n, p=...)实测不再触发同步。