Skip to content

feat(xpu): add Intel GPU (XPU) support#1167

Open
aslanxie wants to merge 1 commit into
alibaba:mainfrom
aslanxie:feat/xpu-support-cp310
Open

feat(xpu): add Intel GPU (XPU) support#1167
aslanxie wants to merge 1 commit into
alibaba:mainfrom
aslanxie:feat/xpu-support-cp310

Conversation

@aslanxie

@aslanxie aslanxie commented Jul 7, 2026

Copy link
Copy Markdown

Overview

Add Intel GPU (XPU) inference support to RTP-LLM, reusing vllm-xpu-kernels to optimize performance on Intel GPU.

Guiding principles:

  1. Follow the NVIDIA and AMD GPU integration pattern — add Intel GPU code side by side
  2. All changes are behind --config=xpu — DO NOT break existing code logic

Changes

1. Build Infrastructure

  • Bazel XPU toolchain with SYCL cross-compilation support (xpu_configure.bzl, xpu_cc_toolchain_config.bzl.tpl, crosstool_wrapper_driver_xpu.tpl)
  • XPU auto-detection via xpu_configure.bzl (analogous to cuda_configure), plus torch_xpu_configure.bzl to locate PyTorch XPU headers/libs
  • .bazelrc --config=xpu preset with -DUSING_XPU=1 and oneAPI compiler flags
  • pip_xpu_torch Bazel repo rule gated behind TF_NEED_XPU, so bazel sync on non-XPU Python 3.10 containers never resolves XPU-only pins
  • XPU pip requirements (requirements_xpu.txt) and dependency lockfile (requirements_lock_xpu.txt)

2. C++ Device Generalization

  • Device-agnostic abstractions across CUDA/ROCm/XPU code paths in NormalEngine, KVCacheManager, BlockPool, MemoryEvaluationHelper, Sampler, ModelTypes, ComputeInit
  • XPU-specific Bazel select() branches in BUILD, BUILD.pytorch, bazel/defs.bzl, bazel/device_defs.bzl
  • XPUCachingAllocator integration with DeviceGuard for ctor thread; prefill warm-up and emptyCache() support
  • Beam search, sampling, and runtime op implementations for XPU
  • Memory management and device sync adaptations for SYCL runtime

3. Python Device & Attention

  • XPU device detection, initialization, and lifecycle management (XpuImpl extends GpuImpl, device_type.py)
  • vLLM flash-attention backends for XPU
    • Paged KV cache with block table management
    • Rejects unsupported RoPE styles (Yarn/Llama3/Mrope/Glm2/DynamicNTK) with fast-fail errors
  • XPU activation, normalization (RMSNorm/LayerNorm), and MoE gating op implementations
  • ~40 ops registered as pure-PyTorch fallbacks on XPU via RegisterXpuBaseBindings.hpp (RMSNorm, LayerNorm, attention, sampling, KV cache ops, write_cache_store)

4. Module Factories & Server Integration

  • XPU branches in attention, embedding, and linear module factories (f16_linear.py, fused MoE stubs)
  • All hard-coded torch::kCUDA / .cuda() calls replaced with getTorchDevice(); pinned memory disabled on XPU (kPinHostMem=false)
  • Server startup and configuration adaptations for XPU devices (server_config_setup.py, start_backend_server.py) — device selection via ZE_AFFINITY_MASK
  • Auto-model device routing for XPU inference pipelines (loader.py, weight_manager.py, frontend_app.py, base_model.py)
  • Unit tests: test_kv_cache_layout.py, test_no_rope.py

Test Environment

  • GPU: Intel Arc Pro B60
  • Software: PyTorch 2.12.0+xpu, torchvision 0.27.0+xpu

How to Build

# Inside intel/vllm container
bazelisk build //rtp_llm:rtp_llm_xpu --verbose_failures --config=xpu --test_output=errors --test_env="LOG_LEVEL=INFO" --jobs=32

@aslanxie aslanxie requested a review from LLLLKKKK as a code owner July 7, 2026 13:35
Copilot AI review requested due to automatic review settings July 7, 2026 13:35
@LLLLKKKK

LLLLKKKK commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator

AI Code Review - PR #1167

Status: BLOCKING

Summary: P0/0 · P1/0 · P2/2 · P3/1

Non-blocking Suggestions

P2

  • uvicorn auto_loop_factory 别名为 auto_loop_setup 存在语义偏差 @ rtp_llm/frontend/frontend_app.py:133
    • 建议:在回退分支显式处理工厂语义,例如 factory = auto_loop_factory(); asyncio.set_event_loop_policy(...) 或直接用 loop_factory 构造并 asyncio.set_event_loop(factory()),而不是把工厂当作 setup 调用后丢弃;或在注释中明确记录“新版 uvicorn 下退化为默认 asyncio 循环”的取舍。
  • XPU 与 CUDA 之间 transformers 大版本差异带来的兼容风险 @ arch_config/arch_select.bzl:1506
    • 建议:明确记录 XPU 支持的模型/transformers 版本矩阵,并在 XPU smoke 中覆盖至少一个依赖 transformers 新 API 的目标模型,确认 4.57.6 下无回归;或在 PR 描述中显式声明“XPU 后端仅承诺兼容 transformers 4.57.x 的模型子集”,避免后续升级时产生跨平台隐式分叉。

P3

  • 共享宏 CHECK_CPU 语义在非 XPU 构建下被顺带收紧 @ rtp_llm/cpp/pybind/th_utils.h:49
    • 建议:保持现状可接受(新语义更正确),但建议在提交信息或该行注释中说明“CHECK_CPU 由 !is_cuda 收紧为 is_cpu 同时影响 CUDA/ROCm 构建”,便于后续排查;若担心边界,可确认现有 CHECK_CPU_INPUT 调用点不会传入 meta/非 CPU 且非 CUDA 的 tensor。

Checklist Violations (2 fail / 56 total)

General Principles Checklist

  • [6.1] Architecture — 兼容性:公开 API/持久数据/配置/环境迁移安全 → issue XPU 与 CUDA 之间 transformers 大版本差异带来的兼容风险
    _whl_reqs_static 中 CUDA/ROCm wheel 声明 transformers==5.2.0,而 _XPU_VERSION_OVERRIDES["transformers"] = "transformers==4.57.6",且 requirements_xpu.txt 亦 pin transformers==4.57.6。transformers 4.x 与 5.x 为大版本差异,若 rtp_llm 的模型实现/renderer 依赖 transformers>=5 的 API,则在 XPU 上会出现导入或运行时行为差异(非编译期可见)。同类差异还存在于 sentence-transformers(XPU 无 override,requirements_xpu.txt pin 2.7.0)等。
  • [6.1] Quality — 逻辑变更未混入无关格式化 → issue 共享宏 CHECK_CPU 语义在非 XPU 构建下被顺带收紧
    非 XPU 分支 CHECK_CPUTORCH_CHECK(!x.is_cuda(), ...) 改为 TORCH_CHECK(x.is_cpu(), ...)。该改动对 XPU 是必要的(XPU tensor 会让 !is_cuda() 误通过),但同时也收紧了 CUDA/ROCm 构建的语义:此前任何“非 CUDA”tensor(如 meta/其它设备)都能通过,现在必须严格为 CPU。实测下 pinned CPU tensor 的 is_cpu() 仍为真,常规调用点不受影响,属低风险;但这是对共享宏在既有平台上的行为改动,混入了大型 XPU PR 中。

Strengths

  • 设备抽象干净:getTorchDevice()/maybePinMemory() 内联封装使 CUDA 路径字节等价,XPU 差异集中在一处,避免了散落的 #if 污染热路径。
  • 明确的 fail-fast 契约:所有 XPU 未实现能力(MLA、speculative、beam/rejection sampling、cuda_ipc、no_repeat_ngram_size、weight-only 量化、多卡)均抛出清晰错误,杜绝“静默产生错误 token/结果”,符合错误语义显式原则(G.6.1.10)。
  • RTP_LLM_DEVICE_TYPE override + 混合 XPU/CUDA 主机默认优先 CUDA 的处理,避免了检测顺序导致的隐式后端切换,兼容性设计周到。
  • Bazel 门控设计(xpu_pip_gate 基于 TF_NEED_XPU)保证非 XPU 容器与 bazel sync 不会去 download.pytorch.org 拉取 XPU wheel,隔离到位。
  • 新增 XPU KV cache 布局(NSHD)与消费端 vllm_flash_attn.py 的一致性有专门单测 test_kv_cache_layout.py 守护 producer/consumer 漂移,并有 test_no_rope.py 覆盖 RopeStyle.No 分支。
  • BlockInfo::is_cuda 语义扩展有清晰注释并留有 TODO(xpu) 重命名计划,权衡了低风险与可读性。

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Note

Copilot couldn't run its full agentic review because no GitHub Actions runner was available. Make sure your repository has a runner available to run Copilot's review, or add a copilot-setup-steps.yml file specifying one with the runs-on attribute. See the docs for more details.

Adds Intel GPU (XPU) inference support to RTP-LLM while keeping existing CUDA/ROCm flows intact by gating behavior behind --config=xpu and device-type resolution.

Changes:

  • Introduces XPU device detection/selection (Python) and XPU runtime support (C++), including memory/accounting, sampling, and beam-search fallbacks.
  • Adds XPU attention + KV-cache layout adaptation and registers XPU-specific module factories/ops (with CPU-runnable unit tests).
  • Extends Bazel build + dependency plumbing for SYCL/oneAPI toolchains, torch-xpu discovery, and XPU-specific wheel/requirements handling.

Reviewed changes

Copilot reviewed 93 out of 97 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
rtp_llm/start_backend_server.py Uses device-agnostic GPU helpers and XPU-aware env binding / startup guards
rtp_llm/ops/init.py Adds XPU-specific note around libpython linkage behavior
rtp_llm/models_py/utils/arch.py Adds CUDA-only guard for get_sm()
rtp_llm/models_py/standalone/auto_model.py Binds per-rank device early; XPU MHA override; XPU KV cache layout + pinning tweak
rtp_llm/models_py/modules/hybrid/causal_attention.py Imports XPU fused norm implementation
rtp_llm/models_py/modules/factory/linear/impl/xpu/f16_linear.py Adds XPU F16/BF16 linear strategy (PyTorch fallback)
rtp_llm/models_py/modules/factory/linear/impl/xpu/init.py Registers XPU linear strategy
rtp_llm/models_py/modules/factory/linear/init.py Loads XPU linear registry based on device type
rtp_llm/models_py/modules/factory/fused_moe/impl/xpu/init.py Adds XPU MoE placeholder package
rtp_llm/models_py/modules/factory/fused_moe/init.py XPU uses batched triton MoE fallback only
rtp_llm/models_py/modules/factory/attention/xpu_impl/test/test_no_rope.py Adds CPU-runnable test ensuring RoPE isn’t applied for RopeStyle.No
rtp_llm/models_py/modules/factory/attention/xpu_impl/test/test_kv_cache_layout.py Adds CPU-runnable test guarding XPU NSHD KV-cache layout contract
rtp_llm/models_py/modules/factory/attention/xpu_impl/test/BUILD Adds Bazel py_tests for XPU attention helpers
rtp_llm/models_py/modules/factory/attention/common.py Makes write_cache_store no-op when kv_cache is None
rtp_llm/models_py/modules/factory/attention/init.py Registers XPU vLLM flash-attn implementations
rtp_llm/models_py/modules/base/xpu/vllm_xpu_ops.py Wraps vllm-xpu-kernels with PyTorch fallbacks
rtp_llm/models_py/modules/base/xpu/select_topk.py Adds XPU MoE top-k selection fallback
rtp_llm/models_py/modules/base/xpu/not_implemented_ops.py Adds explicit XPU stubs for not-yet-supported ops
rtp_llm/models_py/modules/base/xpu/norm.py Adds XPU norm implementations (vllm kernels + fallbacks)
rtp_llm/models_py/modules/base/xpu/moe_gating.py Adds XPU MoE gating fallback
rtp_llm/models_py/modules/base/xpu/activation.py Adds XPU fused activation fallback
rtp_llm/models_py/modules/base/common/embedding.py Adds fallback/fast-fail behavior when compiled embedding op missing
rtp_llm/models_py/modules/base/init.py Adds XPU base op wiring (norm/activation/moe stubs)
rtp_llm/models_py/model_desc/disaggregate_qwen3.py Selects block map per layer during micro-batch processing
rtp_llm/models_py/bindings/xpu/XpuTorchExt.h Adds XPU-only torch extension include wrapper
rtp_llm/models_py/bindings/xpu/RegisterXpuOps.cc Registers XPU pybind ops
rtp_llm/models_py/bindings/xpu/BUILD Adds Bazel target for XPU bindings registration
rtp_llm/models_py/bindings/core/ExecOps.h Introduces getTorchDevice() + maybePinMemory() helpers
rtp_llm/models_py/bindings/core/ExecOps.cc Adds XPU runtime sync/event/device/memory accounting support
rtp_llm/models_py/bindings/core/CudaSampleOp.cc Adds XPU sampling fallback; disables speculative/rejection sampling on XPU
rtp_llm/models_py/bindings/core/CudaOps.cc Adds XPU copy + mask-logits fallbacks
rtp_llm/models_py/bindings/core/CudaBeamSearchOp.cc Adds XPU beam-search fallback implemented via PyTorch ops
rtp_llm/models_py/bindings/core/BUILD Updates BUILD selects/features and sampling deps across CUDA/ROCm/XPU
rtp_llm/models_py/bindings/common/kernels/BUILD Avoids compiling CUDA fuse-copy kernel in XPU builds
rtp_llm/models_py/bindings/common/FusedCopyOp.cc Adds SYCL memcpy fallback for fused copy ops on XPU
rtp_llm/models_py/bindings/common/BUILD Adjusts bindings compilation/linking for XPU; adds xpu_sycl_compile feature
rtp_llm/models_py/bindings/OpDefs.h Adds XPU KV-cache reshaping (NSHD) and XPU-only attention inputs field
rtp_llm/models_py/bindings/OpDefs.cc Exposes XPU-only position_ids to Python via pybind
rtp_llm/models/base_model.py Uses resolved device string instead of always cuda
rtp_llm/model_loader/weight_manager.py Avoids CUDA streams + CUDA IPC on XPU; adds XPU sync path
rtp_llm/model_loader/loader.py Uses XPU-aware memory cleanup and XPU memory stats logging
rtp_llm/frontend/frontend_app.py Adds uvicorn import fallback for loop setup API changes
rtp_llm/device/device_type.py Adds DeviceType.Xpu, override mechanism, and cached resolution
rtp_llm/device/device_impl.py Adds XpuImpl and device-agnostic helpers (count/set/name/masks)
rtp_llm/device/init.py Wires XpuImpl into device factory
rtp_llm/cpp/utils/TensorDebugUtils.h Treats XPU tensors as “device tensors” for debug dump behavior
rtp_llm/cpp/utils/ErrorCode.h Adds missing include for XPU toolchain
rtp_llm/cpp/pybind/th_utils.h Fixes CPU tensor checks and makes CHECK_TH_CUDA XPU-aware
rtp_llm/cpp/pybind/ComputeInit.cc Enables exec ctx bindings for XPU builds
rtp_llm/cpp/pybind/BUILD Adds XPU selects for pybind linking and exec ops
rtp_llm/cpp/normal_engine/speculative/SpeculativeSampler.cc Routes device tensors through getTorchDevice(); handles XPU D2H
rtp_llm/cpp/normal_engine/speculative/MtpExecutor.cc Switches to getTorchDevice() and uses maybePinMemory()
rtp_llm/cpp/normal_engine/speculative/MtpBatchStreamProcessor.cc Adds XPU-safe pinning + device routing
rtp_llm/cpp/normal_engine/NormalSamplerInputGatherer.cc Allocates sampler tensors on resolved device
rtp_llm/cpp/normal_engine/NormalOutputDispatcher.cc Moves label tensor to resolved device for loss computation
rtp_llm/cpp/normal_engine/NormalModelInputGatherer.cc Moves multimodal tensors via resolved device routing
rtp_llm/cpp/normal_engine/NormalEngine.cc Adds XPU ctor guard + warmup + emptyCache path
rtp_llm/cpp/models/logits_processor/MultiSeqLogitsProcessor.cc Moves vocab mask to resolved device
rtp_llm/cpp/models/logits_processor/BaseLogitsProcessor.cc Moves vocab mask to resolved device
rtp_llm/cpp/models/eplb/ExpertBalancer.cc Uses getTorchDevice() and maybePinMemory() for buffers
rtp_llm/cpp/models/Sampler.cc Routes tensors to resolved device; adds XPU-specific success handling
rtp_llm/cpp/models/PyWrappedModel.h Adds XPU stream include and disables prefill-CP on XPU
rtp_llm/cpp/models/PyWrappedModel.cc Makes host pinning conditional; uses getTorchDevice() throughout
rtp_llm/cpp/models/ModelTypes.cc Uses maybePinMemory() and routes device tensors via getTorchDevice()
rtp_llm/cpp/models/BUILD Adjusts deps for XPU build (no CUDA graph impl on XPU)
rtp_llm/cpp/engine_base/stream/GenerateStream.cc Adds XPU generator support and treats XPU tensors like CUDA for D2H
rtp_llm/cpp/engine_base/WeightsConverter.cc Copies tensors to resolved device, not hardcoded CUDA
rtp_llm/cpp/engine_base/TorchProfiler.h Enables profiling activities for XPU (Kineto)
rtp_llm/cpp/cache/connector/p2p/transfer/tcp/CudaCopyUtil.cc Routes wrapRawPtr device to getTorchDevice()
rtp_llm/cpp/cache/connector/p2p/LayerBlockConverterImpl.h Treats XPU tensors like device tensors in block info
rtp_llm/cpp/cache/connector/memory/KVCacheMemoryConnector.cc Uses getTorchDevice() for device buffers
rtp_llm/cpp/cache/MemoryLayoutStrategy.cc Treats XPU tensors like device tensors in block info
rtp_llm/cpp/cache/MemoryEvaluationHelper.cc Adds XPU memory accounting via XPUCachingAllocator and device props
rtp_llm/cpp/cache/KVCacheManager.cc Uses resolved device and maybePinMemory() for sync buffers
rtp_llm/cpp/cache/BlockPool.cc Avoids pin_memory on XPU; uses resolved device for GPU buffers
rtp_llm/cpp/cache/BlockInfo.h Documents is_cuda semantics for XPU and notes rename TODO
rtp_llm/config/server_config_setup.py XPU seq_size defaults, device binding via gpu_set_device, and XPU speculative guard
rtp_llm/BUILD Filters wheel requirements for XPU to avoid CUDA-only deps
deps/requirements_xpu.txt Adds dedicated XPU requirements set (torch +xpu pinned)
deps/pip.bzl Adds pip_parse for XPU lockfile and TF_NEED_XPU-gated requirement exports
deps/BUILD Adds lockfile compilation rule for XPU requirements
bazel/device_defs.bzl Adds XPU test env marker
arch_config/arch_select.bzl Adds XPU requirement resolver, filtering/remapping for XPU wheel metadata
WORKSPACE Adds XPU and torch-xpu configure rules; gates XPU wheel install_deps
BUILD.pytorch Adds using_xpu config + links torch XPU libs + XPU python headers
BUILD Adds using_xpu config_setting
3rdparty/gpus/xpu_configure.bzl Adds oneAPI/SYCL toolchain auto-config + XPU python runtime wiring
3rdparty/gpus/xpu/BUILD.tpl Adds XPU runtime/header Bazel targets template
3rdparty/gpus/torch_xpu_configure.bzl Adds torch-xpu site-packages auto-detection with TF_NEED_XPU enforcement
3rdparty/gpus/crosstool/xpu_cc_toolchain_config.bzl.tpl Defines Bazel cc_toolchain_config for SYCL (xpu_sycl_compile feature)
3rdparty/gpus/crosstool/clang/bin/crosstool_wrapper_driver_xpu.tpl Adds icx/icpx wrapper that filters unsupported flags + rewrites @params
.bazelrc Adds --config=xpu with toolchain, defines, env, and SYCL target settings
Comments suppressed due to low confidence (5)

rtp_llm/start_backend_server.py:1

  • On XPU, cuda_device_list comes from get_visible_device_list(), which strips sub-device selectors (e.g. 0.0) down to 0. Writing this back into ZE_AFFINITY_MASK can silently change device visibility/partitioning on systems using sub-devices. Prefer not rewriting ZE_AFFINITY_MASK at all when it is already set, or preserve the original (raw) entries (e.g. keep 0.0,1.0) when computing the per-rank mask.
    rtp_llm/models_py/standalone/auto_model.py:1
  • This condition disables pinned-memory on ROCm as well (since get_device_string() returns \"cuda\" for both CUDA and ROCm). If pinning is still intended on ROCm, gate this on the resolved device type (e.g. not _is_xpu_device() / maybePinMemory(...)) rather than self.device == \"cuda\".
    rtp_llm/models_py/modules/base/xpu/vllm_xpu_ops.py:1
  • Using assert for runtime validation is unsafe because asserts can be stripped with Python optimizations (-O), which would turn a required precondition into unchecked behavior. Raise a ValueError/RuntimeError instead so the failure mode is consistent in production.
    rtp_llm/models_py/bindings/core/CudaSampleOp.cc:1
  • The XPU sampling path mutates params.top_k in-place (via data_ptr) even though it is conceptually an input. If the caller reuses the same top_k tensor across steps/requests, this will persistently change the configuration and can lead to incorrect sampling behavior. Prefer computing an internal top_k_effective (clone/copy) used only inside this function, leaving params.top_k untouched.
    rtp_llm/start_backend_server.py:1
  • The function name _get_cuda_device_list() no longer matches its behavior (it now returns a generic GPU/XPU-visible device list). Renaming it (e.g. _get_gpu_device_list) would avoid confusion and reduce the chance of future CUDA-only assumptions creeping back in.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread deps/pip.bzl
Comment on lines +76 to +82
pip_parse(
name = "pip_xpu_torch",
requirements_lock = "@rtp_deps//:requirements_lock_xpu.txt",
python_interpreter = "/opt/conda310/bin/python3",
extra_pip_args = PIP_EXTRA_ARGS + ["--extra-index-url=https://download.pytorch.org/whl/xpu"],
timeout = 3600,
)
@LLLLKKKK

LLLLKKKK commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator

AI Code Review - PR #1167

Status: BLOCKING

Summary: P0/0 · P1/1 · P2/0 · P3/0

Blocking Issues

P1

  • XPU 主推理路径仍无条件分配 pinned CPU 张量 @ rtp_llm/cpp/normal_engine/NormalModelInputGatherer.cc:211
    • 建议:将 NormalModelInputGatherer 和 NormalSamplerInputGatherer 的 CPU 张量分配统一改为 maybePinMemory 或 kPinHostMem 分支;补充一个 XPU normal engine smoke/UT,覆盖 prefill 输入 gather 到 sampler 参数 gather 的完整首请求路径。

Checklist Violations (2 fail / 134 total)

General Principles Checklist

  • [6.1] Architecture — 状态不变量:创建/更新/失败/重试/回滚路径有效 → issue XPU 主推理路径仍无条件分配 pinned CPU 张量
    PR 已在 ExecOps.h 增加 maybePinMemory,并在 PyWrappedModel/BlockPool 注释中说明 XPU 不支持 CUDA 风格 pinned host memory;但 NormalModelInputGatherer 仍用 pinned_memory(true) 创建 tokens、lengths、KV block 表,NormalSamplerInputGatherer 也同样创建采样参数。XPU 首个正常请求会重新触发该不支持路径。
  • [6.1] Tests — 分布式/跨平台变更有对应覆盖 → issue XPU 主推理路径仍无条件分配 pinned CPU 张量
    PR 已在 ExecOps.h 增加 maybePinMemory,并在 PyWrappedModel/BlockPool 注释中说明 XPU 不支持 CUDA 风格 pinned host memory;但 NormalModelInputGatherer 仍用 pinned_memory(true) 创建 tokens、lengths、KV block 表,NormalSamplerInputGatherer 也同样创建采样参数。XPU 首个正常请求会重新触发该不支持路径。

Strengths

  • XPU 不支持能力有显式 fail-fast,例如 speculative decoding、多卡启动、prefix cache 等路径没有静默降级成错误结果。
  • PyWrappedModel、BlockPool、MtpExecutor 等多处已开始统一使用 getTorchDevice / maybePinMemory,说明跨平台迁移边界在收敛。

Copilot AI review requested due to automatic review settings July 8, 2026 01:01
@aslanxie aslanxie force-pushed the feat/xpu-support-cp310 branch 2 times, most recently from 6420b3c to ab6345f Compare July 8, 2026 01:11

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 93 out of 97 changed files in this pull request and generated 1 comment.

Comments suppressed due to low confidence (8)

rtp_llm/models_py/bindings/core/CudaSampleOp.cc:1

  • Reinterpreting an int32_t* from params.top_k as uint32_t* is undefined behavior under C++ strict-aliasing rules and can miscompile under optimization. Use int32_t* (or auto* = params.top_k.data_ptr<int32_t>()) and compare against integer constants without changing the pointer type (cast per-value if you need unsigned semantics).
    rtp_llm/models_py/bindings/core/CudaSampleOp.cc:1
  • Reinterpreting an int32_t* from params.top_k as uint32_t* is undefined behavior under C++ strict-aliasing rules and can miscompile under optimization. Use int32_t* (or auto* = params.top_k.data_ptr<int32_t>()) and compare against integer constants without changing the pointer type (cast per-value if you need unsigned semantics).
    rtp_llm/models_py/modules/base/xpu/vllm_xpu_ops.py:1
  • This is a runtime correctness check but uses assert, which is stripped when Python runs with optimizations (-O), potentially turning a clear error into a later, harder-to-debug failure. Replace with an explicit conditional that raises ValueError/RuntimeError when either cu_seqlens_q or cu_seqlens_k is missing.
    rtp_llm/models_py/modules/base/xpu/moe_gating.py:1
  • These input validations use assert, which can be disabled with python -O, removing safety checks and potentially causing silent misbehavior or confusing tensor errors. Prefer raising ValueError (or RuntimeError) with the same message so the checks are always enforced.
    rtp_llm/cpp/models/PyWrappedModel.cc:1
  • This reintroduces a local pin-memory flag that duplicates the new shared helpers in ExecOps.h (kPinHostMemory / maybePinMemory). To reduce drift and future backend conditionals, consider switching these call sites to use the shared helpers instead of defining a second compile-time flag in this translation unit.
    rtp_llm/device/device_impl.py:1
  • Stripping the sub-device portion from ZE_AFFINITY_MASK changes semantics when users intentionally target tiles/sub-devices (e.g. 0.0). This can cause the parent process to widen affinity unintentionally once it re-exports ZE_AFFINITY_MASK. A safer approach is to preserve the raw mask tokens for re-exporting and only derive a separate 'device index list' for torch.xpu.set_device() mapping.
    rtp_llm/start_backend_server.py:1
  • This error message is hard to parse (grammar, line continuation, and the meaning of 'result'). Since this block is now device-agnostic, consider raising RuntimeError with a clearer message such as: world_size must be <= device_count or divisible by device_count, and include the resolved backend (CUDA/ROCm/XPU) and the visible-device mask env var for easier debugging.
    rtp_llm/model_loader/loader.py:1
  • This helper now handles both CUDA and XPU, but the name force_clean_cuda_memory suggests CUDA-only behavior. Consider renaming to something backend-neutral like force_clean_gpu_memory (and optionally keeping force_clean_cuda_memory as a backward-compatible alias) to avoid misleading call sites as more backends are added.

Comment on lines +96 to +99
elif normalized in _XPU_PACKAGE_REMAP:
xpu_reqs.append(_XPU_PACKAGE_REMAP[normalized])
else:
xpu_reqs.append(req)
Copilot AI review requested due to automatic review settings July 8, 2026 01:18

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

@LLLLKKKK

LLLLKKKK commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator

AI Code Review - PR #1167

Status: BLOCKING

Summary: P0/0 · P1/2 · P2/0 · P3/0

Blocking Issues

P1

  • XPU wheel 依赖覆盖版本与 lockfile 不一致 @ arch_config/arch_select.bzl:33
    • 建议:将 _XPU_VERSION_OVERRIDESrequirements_lock_xpu.txt 同步,或改为从 lockfile 生成/校验这些覆盖项;同时增加一个轻量测试,校验 filter_xpu_whl_reqs() 输出的 XPU wheel 依赖与 XPU lockfile 中对应包版本一致。
  • XPU decode 未拒绝多 KV group 会复用错误 block table @ rtp_llm/models_py/modules/factory/attention/xpu_impl/vllm_flash_attn.py:740
    • 建议:在实现完整分组前,对 XPU attention 显式拒绝多 KV group/hybrid cache/sliding-window 这类需要 layer-specific block table 的模型;或在 decode/prefill 中按 layer_idx -> kv_cache_layer_to_group 选择对应 host/device block ids,并把 group/layer 纳入缓存 key。补充一个 kv_cache_layer_to_group=[0,1] 且两个 group block table 不同的回归测试。

Checklist Violations (5 fail / 56 total)

General Principles Checklist

  • [6.1] Architecture — 兼容性:公开 API/持久数据/配置/环境迁移安全 → issue XPU wheel 依赖覆盖版本与 lockfile 不一致
    _XPU_VERSION_OVERRIDES 注释说明这些版本用于 XPU wheel 元数据,但 fastapi/setuptools/tiktoken/timm/uvicorn 的覆盖值与 deps/requirements_lock_xpu.txt 中实际锁定版本不一致。XPU wheel 会声明一组未经 lockfile 验证的依赖,安装时可能解析到与构建/测试环境不同的版本。
  • [6.1] Architecture — 状态不变量:创建/更新/失败/重试/回滚路径有效 → issue XPU decode 未拒绝多 KV group 会复用错误 block table
    代码注释已说明 hybrid KV 需要按 group/layer 使用不同 block table,但当前 XPU decode 仍按单一 needed_bids 构建 _block_table_cache 并跨 layer 复用;support() 也没有在存在多 KV group 或 kv_cache_layer_to_group 时 fail-fast。多 group 模型会让后续层读写错误 KV block。
  • [6.1] Architecture — 错误语义:fail-fast/retry/fallback/silent 行为显式 → issue XPU decode 未拒绝多 KV group 会复用错误 block table
    代码注释已说明 hybrid KV 需要按 group/layer 使用不同 block table,但当前 XPU decode 仍按单一 needed_bids 构建 _block_table_cache 并跨 layer 复用;support() 也没有在存在多 KV group 或 kv_cache_layer_to_group 时 fail-fast。多 group 模型会让后续层读写错误 KV block。
  • [6.1] Tests — 新逻辑有聚焦单测 + 相关集成/smoke 测试 → issue XPU decode 未拒绝多 KV group 会复用错误 block table
    代码注释已说明 hybrid KV 需要按 group/layer 使用不同 block table,但当前 XPU decode 仍按单一 needed_bids 构建 _block_table_cache 并跨 layer 复用;support() 也没有在存在多 KV group 或 kv_cache_layer_to_group 时 fail-fast。多 group 模型会让后续层读写错误 KV block。
  • [6.1] Tests — 边界 case 覆盖(空、单元素、最大值) → issue XPU decode 未拒绝多 KV group 会复用错误 block table
    代码注释已说明 hybrid KV 需要按 group/layer 使用不同 block table,但当前 XPU decode 仍按单一 needed_bids 构建 _block_table_cache 并跨 layer 复用;support() 也没有在存在多 KV group 或 kv_cache_layer_to_group 时 fail-fast。多 group 模型会让后续层读写错误 KV block。

Strengths

  • XPU 设备相关实现基本按现有 Device/Model/pybind 层次接入,新增路径没有大范围侵入 CUDA 主路径。
  • 新增的 KV cache layout 与 no-RoPE 测试覆盖了部分 XPU attention 辅助逻辑,降低了纯适配代码的回归风险。

Copilot AI review requested due to automatic review settings July 9, 2026 00:52
@aslanxie aslanxie force-pushed the feat/xpu-support-cp310 branch from ab6345f to bc6a7d1 Compare July 9, 2026 00:52

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 97 out of 101 changed files in this pull request and generated no new comments.

Comments suppressed due to low confidence (8)

rtp_llm/models_py/bindings/core/CudaOps.cc:1

  • c10::xpu::getCurrentXPUStream() is typically an XPUStream object, not a sycl::queue&. This is likely to fail to compile (or bind to the wrong type) on some PyTorch XPU versions. Prefer retrieving the SYCL queue from the XPU stream explicitly (e.g., get the current XPU stream, then access its underlying queue) and include the appropriate SYCL headers if needed.
    rtp_llm/models_py/bindings/common/FusedCopyOp.cc:1
  • Same issue as in CudaOps.cc: binding c10::xpu::getCurrentXPUStream() directly to sycl::queue& is likely incorrect (PyTorch commonly exposes an XPUStream wrapper). Please fetch the queue from the stream explicitly (and ensure required SYCL headers are present) so this code compiles reliably across supported torch-xpu versions.
    rtp_llm/device/device_impl.py:1
  • Stripping sub-device (tile) selectors from ZE_AFFINITY_MASK changes semantics for users who intentionally specify sub-devices (e.g. 0.0,0.1). This becomes more problematic because start_backend_server.py later writes ZE_AFFINITY_MASK back from this list, effectively overwriting the user’s original mask with the stripped version. Consider returning the raw entries for XPU (preserve 0.0) and only deriving a separate 'device indices' list where strictly required for torch.xpu.set_device() indexing.
    rtp_llm/start_backend_server.py:1
  • Overwriting ZE_AFFINITY_MASK in the parent process can unintentionally discard a user-provided affinity (including sub-device selection), and can also affect sibling ranks because the parent env is shared during process spawn. A safer pattern is: (1) only set the mask if it is not already set, or (2) avoid rewriting ZE_AFFINITY_MASK altogether and rely on per-rank torch.xpu.set_device() in the child, or (3) if you need per-rank masking, set per-rank ZE_AFFINITY_MASK to a single entry (not the full list) derived from the rank.
    rtp_llm/models_py/utils/arch.py:1
  • is_xpu is imported but not used in this module (based on the shown file content). Please remove the unused import to avoid lint/type-check noise.
    rtp_llm/models_py/bindings/core/CudaSampleOp.cc:1
  • Reinterpreting an int32_t tensor buffer as uint32_t* is brittle and makes sentinel/negative top_k values harder to reason about. Prefer keeping top_k as int32_t* and applying forcing logic without type-punning; also consider using a local copy of top_k rather than mutating params.top_k in place if callers expect it to remain an input.
    rtp_llm/models_py/bindings/core/CudaBeamSearchOp.cc:1
  • token_ids_out is allocated and then immediately replaced by the result of gather, which discards the original allocation. This causes an avoidable allocation. Prefer constructing token_ids_out directly from the gather result (or copy_ into the preallocated buffer if you need to control memory reuse).
    rtp_llm/models_py/bindings/core/CudaBeamSearchOp.cc:1
  • token_ids_out is allocated and then immediately replaced by the result of gather, which discards the original allocation. This causes an avoidable allocation. Prefer constructing token_ids_out directly from the gather result (or copy_ into the preallocated buffer if you need to control memory reuse).

@LLLLKKKK

LLLLKKKK commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator

AI Code Review - PR #1167

Status: BLOCKING

Summary: P0/0 · P1/2 · P2/0 · P3/0

Blocking Issues

P1

  • XPU 采样器仍强制分配 pinned host buffer @ rtp_llm/cpp/models/Sampler.cc:26
    • 建议:将这里改为 pinned_memory(kPinHostMemory) 或复用 maybePinMemory,并补一个 XPU sampler 初始化/greedy smoke 覆盖,确保服务启动和首 token 采样不依赖 CUDA pinned allocator。
  • XPU decode 的 FA2 依赖未进入可验证安装契约 @ rtp_llm/models_py/modules/factory/attention/xpu_impl/vllm_flash_attn.py:647
    • 建议:把 vllm-xpu-kernels/FA2 纳入 XPU wheel 或镜像的可验证依赖契约;如果无法公开声明依赖,则在 XPU 启动阶段做 FA2 preflight 并给出明确失败信息,避免服务运行到 decode 才报错。

Checklist Violations (4 fail / 55 total)

General Principles Checklist

  • [6.1] Architecture — 兼容性:外部 HTTP/RPC API、持久数据、配置、环境迁移安全 → issue XPU decode 的 FA2 依赖未进入可验证安装契约
    XPU 只注册 XpuVllmFlashAttnDecodeImpl,其 support() 在 FA2 不可用时直接抛 NotImplementedError;但 deps/requirements_xpu.txt 又说明 vllm-xpu-kernels 不在依赖解析内、需手动安装。按当前 XPU requirements/wheel 安装后,decode 可能无实现可选。
  • [6.1] Architecture — 状态不变量:创建/更新/失败/重试/回滚路径有效 → issue XPU 采样器仍强制分配 pinned host buffer
    XPU 路径已在 ExecOpsBlockPoolPyWrappedModel 中显式关闭 pinned memory,但 Sampler::allocateGreedySamplingBuffers 仍使用 pinned_memory(true)NormalExecutor 启动时会按 max_generate_batch_size 构造 Sampler,XPU 服务可能在采样 buffer 创建阶段直接失败。
  • [6.1] Architecture — 错误语义:fail-fast/retry/fallback/silent 行为显式 → issue XPU decode 的 FA2 依赖未进入可验证安装契约
    XPU 只注册 XpuVllmFlashAttnDecodeImpl,其 support() 在 FA2 不可用时直接抛 NotImplementedError;但 deps/requirements_xpu.txt 又说明 vllm-xpu-kernels 不在依赖解析内、需手动安装。按当前 XPU requirements/wheel 安装后,decode 可能无实现可选。
  • [6.1] Tests — 分布式/跨平台变更有对应覆盖 → issue XPU 采样器仍强制分配 pinned host buffer
    XPU 路径已在 ExecOpsBlockPoolPyWrappedModel 中显式关闭 pinned memory,但 Sampler::allocateGreedySamplingBuffers 仍使用 pinned_memory(true)NormalExecutor 启动时会按 max_generate_batch_size 构造 Sampler,XPU 服务可能在采样 buffer 创建阶段直接失败。

Strengths

  • 设备抽象从多处 CUDA 硬编码迁移到 getTorchDevice / gpu_* helper,并在启动阶段对 XPU 多卡和 speculative decoding 做了 fail-fast,降低误用风险。
  • XPU attention 对 KV cache NSHD 布局、多 KV group、No-RoPE 分支增加了聚焦测试和显式拒绝逻辑,避免静默错读 KV。

Copilot AI review requested due to automatic review settings July 9, 2026 06:55
@aslanxie aslanxie force-pushed the feat/xpu-support-cp310 branch from bc6a7d1 to fe77bda Compare July 9, 2026 06:55

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 98 out of 102 changed files in this pull request and generated no new comments.

Comments suppressed due to low confidence (6)

rtp_llm/models_py/bindings/core/CudaSampleOp.cc:1

  • params.logits is overwritten with softmax probabilities (lines 665-667), but later the “original logits” argmax fallback (line 731) uses the mutated tensor. This breaks the documented intent and can change behavior for degenerate rows (NaN/Inf), where softmax can further distort values. Keep an orig_logits tensor (or avoid mutating params.logits) and compute the fallback argmax from the pre-softmax logits.
    rtp_llm/models_py/bindings/core/CudaSampleOp.cc:1
  • params.logits is overwritten with softmax probabilities (lines 665-667), but later the “original logits” argmax fallback (line 731) uses the mutated tensor. This breaks the documented intent and can change behavior for degenerate rows (NaN/Inf), where softmax can further distort values. Keep an orig_logits tensor (or avoid mutating params.logits) and compute the fallback argmax from the pre-softmax logits.
    rtp_llm/start_backend_server.py:1
  • The raised exception type (Exception) and message are hard to interpret (“result: … not support … local gpu”, plus a backslash continuation). Prefer ValueError/RuntimeError and a clearer message that explains the constraint (e.g., “WORLD_SIZE must be <= device_count or divisible by device_count”) and includes world_size + device_count once.
    rtp_llm/start_backend_server.py:1
  • _get_cuda_device_list() now returns a generic GPU-visible device list for CUDA/ROCm/XPU. Renaming it to _get_gpu_device_list() (and updating callers accordingly) would prevent confusion now that this function is no longer CUDA-specific.
    rtp_llm/models_py/modules/factory/attention/xpu_impl/test/BUILD:1
  • This comment conflicts with test_kv_cache_layout.py, which explicitly imports compiled bindings (rtp_llm.ops.compute_ops / KVCache) and only skips at runtime if the import fails. Please clarify the comment (e.g., that tests are “pure Python” but may require the compiled rtp_llm.ops extension at runtime, and will SkipTest otherwise) to avoid misleading future maintainers.
    rtp_llm/models_py/bindings/core/CudaSampleOp.cc:1
  • The new XPU sampleGreedy path implements complex sampling semantics (temperature=0 fast-path, per-row greedy via do_sample, top-k/top-p filters, degenerate probability handling, generator handling) but there’s no targeted unit test coverage validating output tokens / success for these cases. Adding focused C++ tests (similar to existing Sampler tests) for at least temperature==0, top_k==1, top_p filtering, and NaN/Inf/all-zero row behavior would significantly reduce regression risk.

@LLLLKKKK

LLLLKKKK commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator

AI Code Review - PR #1167

Status: BLOCKING

Summary: P0/0 · P1/1 · P2/0 · P3/0

Blocking Issues

P1

  • XPU 依赖映射漏掉 triton-kernels 会导致构建解析失败 @ arch_config/arch_select.bzl:12
    • 建议:如果 XPU 不需要 triton-kernels,把 triton-kernels 加入 _XPU_EXCLUDED_PACKAGES;如果需要,则加入 deps/requirements_xpu.txt 并重新生成 lockfile。建议扩展现有 XPU 依赖测试,校验 rtp_llm/BUILD 的 requirement 列表在 XPU 下都能命中 lock/remap/exclude 之一。

Checklist Violations (2 fail / 55 total)

General Principles Checklist

  • [6.1] Architecture — 兼容性:外部 HTTP/RPC API、持久数据、配置、环境迁移安全 → issue XPU 依赖映射漏掉 triton-kernels 会导致构建解析失败
    XPU 构建仍会处理 rtp_llm/BUILD 中的 requirement([... "triton-kernels" ...])arch_select.requirement() 对未排除包会调用 requirement_xpu(name),但 XPU lockfile 只有 triton-xpu,没有 triton-kernels,因此 --config=xpu 会引用不存在的 pip target。
  • [6.1] Tests — 新逻辑有聚焦单测 + 相关集成/smoke 测试 → issue XPU 依赖映射漏掉 triton-kernels 会导致构建解析失败
    XPU 构建仍会处理 rtp_llm/BUILD 中的 requirement([... "triton-kernels" ...])arch_select.requirement() 对未排除包会调用 requirement_xpu(name),但 XPU lockfile 只有 triton-xpu,没有 triton-kernels,因此 --config=xpu 会引用不存在的 pip target。

Strengths

  • XPU 不支持的 speculative、多卡、量化 KV cache、prefix cache 等路径多数采用 fail-fast,降低静默错误风险。
  • XPU KV cache NSHD 布局在 producer/consumer 两侧都有显式断言,并新增了针对布局、No-RoPE、多 KV group 拒绝的测试。
  • 多处原 CUDA 假设被收敛到 getTorchDevice()kPinHostMemory 和设备抽象函数,迁移面较清晰。

Copilot AI review requested due to automatic review settings July 10, 2026 01:25
@LLLLKKKK

Copy link
Copy Markdown
Collaborator

AI Code Review - PR #1167

Status: BLOCKING

Summary: P0/0 · P1/1 · P2/0 · P3/0

Blocking Issues

P1

  • XPU copy op 直接把 XPUStream 当作 sycl::queue 使用 @ rtp_llm/models_py/bindings/common/FusedCopyOp.cc:35
    • 建议:改为先取得 XPUStream 再通过正确接口取底层 queue,或复用 ATen/PyTorch 的 XPU copy API;同时补一个覆盖 fuse_copy_opexec_ctx_ops 的 XPU 编译测试,防止绑定层再次绕过平台 CI。

Checklist Violations (2 fail / 55 total)

General Principles Checklist

  • [6.1] Tests — 分布式/跨平台变更有对应覆盖 → issue XPU copy op 直接把 XPUStream 当作 sycl::queue 使用
    XPU 分支在 FusedCopyOp.cc:35/58 和 CudaOps.cc:179 把 c10::xpu::getCurrentXPUStream() 直接绑定到 sycl::queue&;该 API 返回的是 XPUStream,不能隐式当作 sycl::queue 引用使用。只要 --config=xpu 编译命中这些 copy op,目标会在编译阶段失败。
  • [6.1] Tests — 新逻辑有聚焦单测 + 相关集成/smoke 测试 → issue XPU copy op 直接把 XPUStream 当作 sycl::queue 使用
    XPU 分支在 FusedCopyOp.cc:35/58 和 CudaOps.cc:179 把 c10::xpu::getCurrentXPUStream() 直接绑定到 sycl::queue&;该 API 返回的是 XPUStream,不能隐式当作 sycl::queue 引用使用。只要 --config=xpu 编译命中这些 copy op,目标会在编译阶段失败。

Strengths

  • XPU 路径对 speculative decoding、multi-rank、prefix cache、KV dtype 等暂不支持能力做了显式 fail-fast,避免静默走错后端。
  • 依赖与 Bazel 配置按架构拆分,新增了部分 arch select 与 XPU 模块测试,便于后续逐步补齐平台覆盖。

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 98 out of 102 changed files in this pull request and generated no new comments.

Comments suppressed due to low confidence (7)

rtp_llm/start_backend_server.py:1

  • On XPU this overwrites ZE_AFFINITY_MASK using cuda_device_list, which is derived from get_visible_device_list() and strips sub-device/tile selectors (e.g. 0.0). This can silently change the affinity mask and bind the child process to the wrong subdevice(s). A safer approach is to (a) not overwrite ZE_AFFINITY_MASK if it is already set, or (b) preserve and re-use the raw ZE_AFFINITY_MASK entries when re-exporting, while keeping a separate list of integer device indices for torch.xpu.set_device().
    rtp_llm/device/device_impl.py:1
  • CUDA_VISIBLE_DEVICES can legally be set to an empty/whitespace string to indicate 'no devices'. In that case split(',') returns [''], and downstream int('') conversions (or list indexing) will fail in non-obvious places. Consider treating empty/whitespace-only values as an empty device list (or falling back to gpu_device_count()==0) by checking cuda_devices.strip() before splitting.
    rtp_llm/models_py/bindings/core/CudaSampleOp.cc:1
  • Reinterpreting the int32_t top_k buffer as uint32_t* breaks the intended <= 0 semantics: negative top_k values (often used to mean 'disabled' / 'no top-k') become large unsigned values, causing has_top_k to evaluate incorrectly and changing behavior vs CUDA/ROCm. It also introduces strict-aliasing/UB risk. Use an int32_t* (or auto* top_k_ptr = params.top_k.data_ptr<int32_t>();) and perform signed comparisons/clamping on int64_t k derived from that signed value.
    rtp_llm/cpp/models/PyWrappedModel.cc:1
  • This introduces a second pinned-memory compile-time flag (kPinHostMem) with duplicated logic, while rtp_llm/models_py/bindings/core/ExecOps.h already defines kPinHostMemory and maybePinMemory(...). To prevent the pinned-memory contract from drifting across files/backends, prefer reusing kPinHostMemory and/or maybePinMemory(t) here instead of maintaining a separate local preprocessor-based flag.
    rtp_llm/cpp/models/PyWrappedModel.cc:1
  • This introduces a second pinned-memory compile-time flag (kPinHostMem) with duplicated logic, while rtp_llm/models_py/bindings/core/ExecOps.h already defines kPinHostMemory and maybePinMemory(...). To prevent the pinned-memory contract from drifting across files/backends, prefer reusing kPinHostMemory and/or maybePinMemory(t) here instead of maintaining a separate local preprocessor-based flag.
    rtp_llm/start_backend_server.py:1
  • This error message is hard to interpret ("result:" and "not support"), and it still hard-codes "local gpu" even when the selected backend is XPU. Consider raising a ValueError/RuntimeError with a clearer description like: world_size must be <= device_count or divisible by device_count, and include the resolved device type (cuda/xpu) plus the relevant visible-device env var name (CUDA_VISIBLE_DEVICES vs ZE_AFFINITY_MASK).
    rtp_llm/models_py/bindings/core/CudaSampleOp.cc:1
  • The XPU sampling path is a new, substantial behavioral fork from the CUDA/ROCm kernels (temperature==0 fast path, top_k/top_p filtering, do_sample overrides, and degenerate-row handling). Please add unit coverage that compares XPU sampling behavior against the existing CUDA/ROCm expectations for a few representative cases (e.g., negative/zero top_k semantics, top_p edge values, mixed temperature rows including 0, and do_sample=false rows). This will also catch regressions like the signed/unsigned top_k handling issue.

Copilot AI review requested due to automatic review settings July 10, 2026 03:38

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 98 out of 102 changed files in this pull request and generated 1 comment.

Comments suppressed due to low confidence (11)

rtp_llm/device/device_impl.py:1

  • gpu_is_available() checks torch.xpu.device_count()>0 for XPU but does not check torch.cuda.device_count()>0 for CUDA/ROCm. With CUDA_VISIBLE_DEVICES masking all GPUs, torch.cuda.is_available() can still be true while device_count()==0, which makes call sites take GPU paths and later fail. Make CUDA availability symmetric by including a torch.cuda.device_count() > 0 check (and optionally treat empty/invalid masks as unavailable).
    rtp_llm/device/device_impl.py:1
  • get_visible_device_list() can return invalid/empty entries when ZE_AFFINITY_MASK or CUDA_VISIBLE_DEVICES contains whitespace or is set to an empty string (e.g. CUDA_VISIBLE_DEVICES='' produces ['']). This can later crash when converting to int (e.g. in XpuImpl.get_device_id()), or produce confusing device pinning. Strip whitespace and filter out empty tokens for both masks before returning the list.
    rtp_llm/start_backend_server.py:1
  • The helper is now GPU-backend agnostic (CUDA/ROCm/XPU) but is still named _get_cuda_device_list(). Rename it (and its local variable usages like cuda_device_list) to something backend-neutral (e.g. _get_gpu_device_list) to avoid confusion and reduce the chance of future CUDA-only assumptions creeping back in.
    rtp_llm/start_backend_server.py:1
  • This error message is hard to interpret ("result:") and is now used for non-CUDA backends as well, but still says "local gpu". Consider raising a ValueError/RuntimeError with a clearer explanation, e.g. that WORLD_SIZE must be either <= device_count or a multiple of device_count, and include the resolved device type (cuda/xpu) in the message. Also avoid the \\ line continuation inside the f-string to prevent odd whitespace/newlines in the final message.
    rtp_llm/models_py/modules/base/xpu/vllm_xpu_ops.py:1
  • This uses a Python assert for required runtime validation. Asserts can be disabled with python -O, which would turn this into undefined behavior later in the function. Replace this with an explicit check that raises a deterministic exception (e.g. ValueError/RuntimeError) when cu_seqlens_q or cu_seqlens_k is missing.
    rtp_llm/models_py/bindings/core/CudaSampleOp.cc:1
  • Reinterpreting int32_t* as uint32_t* can violate C++ strict-aliasing rules and is unnecessary here since you only compare/assign small positive values. Prefer keeping int32_t* and doing comparisons/assignments in signed integers (or copy into a std::vector<int32_t> if you need a host-side view). This avoids undefined behavior on compilers with aggressive aliasing optimizations.
    rtp_llm/models_py/bindings/core/CudaSampleOp.cc:1
  • Reinterpreting int32_t* as uint32_t* can violate C++ strict-aliasing rules and is unnecessary here since you only compare/assign small positive values. Prefer keeping int32_t* and doing comparisons/assignments in signed integers (or copy into a std::vector<int32_t> if you need a host-side view). This avoids undefined behavior on compilers with aggressive aliasing optimizations.
    rtp_llm/models_py/bindings/core/CudaBeamSearchOp.cc:1
  • The XPU beam search fallback introduces substantial new decoding logic (topk flattening, history gather, scatter write at sequence_lengths, overflow masking). There should be unit tests covering at least: (1) correct token history propagation across steps, (2) correct beam_indices_out mapping, (3) sequence_lengths increment behavior, and (4) overflow (sequence_lengths >= max_seq_len) handling. Adding a small deterministic test (CPU/XPU-tensor based) would help prevent subtle regressions.
    rtp_llm/models_py/bindings/core/CudaBeamSearchOp.cc:1
  • The XPU beam search fallback introduces substantial new decoding logic (topk flattening, history gather, scatter write at sequence_lengths, overflow masking). There should be unit tests covering at least: (1) correct token history propagation across steps, (2) correct beam_indices_out mapping, (3) sequence_lengths increment behavior, and (4) overflow (sequence_lengths >= max_seq_len) handling. Adding a small deterministic test (CPU/XPU-tensor based) would help prevent subtle regressions.
    rtp_llm/cpp/pybind/ComputeInit.cc:1
  • This preprocessor block is empty and has no effect. It should be removed to reduce noise and avoid confusion about missing conditional code.
    rtp_llm/cpp/models/PyWrappedModel.cc:1
  • This duplicates the project-wide pinned-memory policy that was already introduced in ExecOps.h (kPinHostMemory and maybePinMemory). To keep pinning behavior consistent across the codebase, prefer reusing kPinHostMemory/maybePinMemory here instead of defining a local kPinHostMem that could drift from the canonical definition.

Comment on lines +19 to +36
def _find_repo_root(start):
cur = os.path.abspath(start)
while True:
if os.path.exists(os.path.join(cur, "arch_config", "arch_select.bzl")) and \
os.path.exists(os.path.join(cur, "deps", "requirements_lock_xpu.txt")):
return cur
parent = os.path.dirname(cur)
if parent == cur:
raise RuntimeError(
"Could not locate repo root containing arch_config/arch_select.bzl "
"and deps/requirements_lock_xpu.txt"
)
cur = parent


_REPO_ROOT = _find_repo_root(os.path.dirname(__file__))
_BZL_PATH = os.path.join(_REPO_ROOT, "arch_config", "arch_select.bzl")
_LOCK_PATH = os.path.join(_REPO_ROOT, "deps", "requirements_lock_xpu.txt")
@LLLLKKKK

Copy link
Copy Markdown
Collaborator

AI Code Review - PR #1167

Status: BLOCKING

Summary: P0/0 · P1/1 · P2/0 · P3/0

Blocking Issues

P1

  • XPU 注意力测试在关键依赖缺失时会被跳过 @ rtp_llm/models_py/modules/factory/attention/xpu_impl/test/test_kv_cache_layout.py:21
    • 建议:XPU 标签或 XPU 配置下应把这些导入失败视为测试失败,只在非 XPU 环境跳过。可以按环境变量或设备类型区分跳过条件,或拆出不依赖 package-level preflight 的纯 Python helper 测试,同时让缺失 vllm-xpu-kernelsrtp_llm.ops、FA2 binding 的情况在 XPU CI 中硬失败。

Checklist Violations (2 fail / 55 total)

General Principles Checklist

  • [6.1] Tests — 分布式/跨平台变更有对应覆盖 → issue XPU 注意力测试在关键依赖缺失时会被跳过
    test_kv_cache_layout.py 在导入 rtp_llm.ops 或 XPU attention 失败时捕获所有异常并设置 _IMPORT_OK=False,随后 setUp 直接 SkipTesttest_no_rope.pytest_multi_kv_group.py 也采用同样模式。XPU attention 工厂现在缺少 FA2 会启动失败,因此依赖/pybind 配置错误会变成测试跳过而不是 CI 失败。
  • [6.1] Tests — 新逻辑有聚焦单测 + 相关集成/smoke 测试 → issue XPU 注意力测试在关键依赖缺失时会被跳过
    test_kv_cache_layout.py 在导入 rtp_llm.ops 或 XPU attention 失败时捕获所有异常并设置 _IMPORT_OK=False,随后 setUp 直接 SkipTesttest_no_rope.pytest_multi_kv_group.py 也采用同样模式。XPU attention 工厂现在缺少 FA2 会启动失败,因此依赖/pybind 配置错误会变成测试跳过而不是 CI 失败。

Strengths

  • XPU 后端的缺失能力在工厂注册、设备类型、KV cache 布局和 Python fallback 上做了成体系的接入,并对 FA2、prefix cache、多 KV group 等暂不支持场景保留了 fail-fast 行为。
  • arch_select.bzltest_xpu_version_overrides.py 对 XPU lockfile 版本覆盖做了显式校验,降低了依赖 pin 漂移风险。

aslanxie added a commit to aslanxie/rtp-llm-xpu that referenced this pull request Jul 11, 2026
Under RTP_LLM_DEVICE_TYPE=xpu, a missing rtp_llm.ops / xpu consumer
import (broken build or pybind config) is a real regression, not an
environment gap. Add _skip_or_fail_on_missing_import() helper that
fails the test on XPU when the package-level import fails, and only
skips when not targeting XPU.

Addresses PR alibaba#1167 review comment.
Copilot AI review requested due to automatic review settings July 11, 2026 13:13

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 98 out of 102 changed files in this pull request and generated 5 comments.

Comment on lines +228 to +232
auto safe_mask = (write_pos < max_seq_len).squeeze(-1); // [batch, beam_out]
write_pos = write_pos.clamp(0, max_seq_len - 1);
// Write tokens only for beams that have not overflowed (device-side where).
auto safe_ids = output_ids.where(safe_mask, token_ids_out.gather(2, write_pos).squeeze(-1));
token_ids_out.scatter_(2, write_pos, safe_ids.unsqueeze(-1));
Comment on lines +548 to +554
auto top_k_force = reinterpret_cast<uint32_t*>(params.top_k.data_ptr<int32_t>());
for (int64_t b = 0; b < batch_size; b++) {
if (params.temperature.data_ptr<float>()[b] == 0.0f) {
top_k_force[b] = 1;
}
}
}
Comment on lines +648 to +651
// 3. Top-k=1 fast path (greedy argmax)
auto top_k_ptr = reinterpret_cast<uint32_t*>(params.top_k.data_ptr<int32_t>());
if (std::all_of(top_k_ptr, top_k_ptr + batch_size, [](uint32_t t) { return t == 1; })
&& !params.output_all_probs.has_value()) {
Comment on lines +673 to +675
auto filtered_probs = probs_t.clone();
bool has_top_k = !std::all_of(top_k_ptr, top_k_ptr + batch_size, [](uint32_t t) { return t <= 0; });
if (has_top_k) {
Comment thread WORKSPACE
Comment on lines +69 to +73
# XPU wheel installation is gated on TF_NEED_XPU (set by --config=xpu) via the
# xpu_pip_gate repo declared in pip_deps(). On non-XPU containers and plain
# `bazel sync`, install_deps() is a no-op, so the pip_xpu_torch_* whl_library
# repos are never declared and XPU-only pins (e.g. scikit-learn==1.8.0, which
# Requires-Python>=3.11) are never resolved under Python 3.10.
@LLLLKKKK

Copy link
Copy Markdown
Collaborator

AI Code Review - PR #1167

Status: BLOCKING

Summary: P0/0 · P1/1 · P2/0 · P3/0

Blocking Issues

P1

  • XPU Bazel 测试未注入判定变量,导入回归仍会被跳过 @ rtp_llm/models_py/modules/factory/attention/xpu_impl/test/test_kv_cache_layout.py:35
    • 建议:在三个 py_test target 中通过 select() 显式注入 XPU 平台标识,并让 helper 读取同一标识,例如接入现有 TEST_USING_DEVICE=XPU 约定,或为 XPU 分支设置 RTP_LLM_DEVICE_TYPE=xpu。同时补充 _IMPORT_OK=False 时 XPU 必须失败、非 XPU 才允许 skip 的聚焦回归测试。

Checklist Violations (2 fail / 68 total)

General Principles Checklist

  • [6.1] Tests — 分布式/跨平台变更有对应覆盖 → issue XPU Bazel 测试未注入判定变量,导入回归仍会被跳过
    三个文件都只用 RTP_LLM_DEVICE_TYPE == "xpu" 决定 fail 或 skip;但对应 py_test target 仅设置 tags = ["xpu"],仓库的 --config=xpu 也未通过 --test_env 注入该变量。因此标准 XPU Bazel 测试发生 import failure 时 _ON_XPU 仍为 false,helper 继续抛出 SkipTest,本提交要修复的 CI 漏检仍然存在。另两个文件的同类判定分别位于第 32、28 行。
  • [6.1] Tests — 新逻辑有聚焦单测 + 相关集成/smoke 测试 → issue XPU Bazel 测试未注入判定变量,导入回归仍会被跳过
    三个文件都只用 RTP_LLM_DEVICE_TYPE == "xpu" 决定 fail 或 skip;但对应 py_test target 仅设置 tags = ["xpu"],仓库的 --config=xpu 也未通过 --test_env 注入该变量。因此标准 XPU Bazel 测试发生 import failure 时 _ON_XPU 仍为 false,helper 继续抛出 SkipTest,本提交要修复的 CI 漏检仍然存在。另两个文件的同类判定分别位于第 32、28 行。

Strengths

  • 修复方向正确,保留了非 XPU 环境的 skip 行为,并在失败信息中携带原始 import exception,便于定位 binding 或依赖问题。
  • 三个增量测试文件均使用一致的 fail/skip 语义,改动范围集中。

aslanxie added a commit to aslanxie/rtp-llm-xpu that referenced this pull request Jul 12, 2026
The previous fix (skip-vs-fail based on RTP_LLM_DEVICE_TYPE=xpu) never
triggered in real CI: the three xpu-tagged py_test targets never set
that env var, so _ON_XPU stayed false and import failures kept being
skipped.

- BUILD: wire env = device_test_envs() (//bazel:device_defs.bzl) into
  the xpu-tagged py_test targets, injecting the repo's existing
  TEST_USING_DEVICE=XPU convention (select on @//:using_xpu).
- Extract the skip-vs-fail policy into a shared, stdlib-only
  _import_guard.py (is_xpu_test_env() checks both TEST_USING_DEVICE=XPU
  and RTP_LLM_DEVICE_TYPE=xpu; skip_or_fail_on_missing_import() fails on
  XPU, skips elsewhere), used by all three existing test files instead
  of duplicated per-file logic.
- Add test_import_guard.py: focused regression tests for the helper
  itself (no rtp_llm/torch import, so it always runs) covering all
  four fail/skip x xpu/non-xpu combinations end-to-end.

Addresses PR alibaba#1167 review comment.
Copilot AI review requested due to automatic review settings July 12, 2026 00:24

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 100 out of 104 changed files in this pull request and generated 2 comments.

Comment on lines 48 to +50
#define CHECK_TH_CUDA(x) TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor")
#define CHECK_CPU(x) TORCH_CHECK(!x.is_cuda(), #x " must be a CPU tensor")
#endif
Comment on lines +517 to +519
if (params.do_sample.has_value()) {
auto top_k_ptr = params.top_k.data_ptr<int32_t>();
bool any_greedy = false;
Copilot AI review requested due to automatic review settings July 12, 2026 05:28
@aslanxie aslanxie force-pushed the feat/xpu-support-cp310 branch from 81dfd62 to 178fff6 Compare July 12, 2026 05:28

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 100 out of 104 changed files in this pull request and generated 5 comments.

Comment on lines +1202 to +1207
if _is_xpu_device():
xpu_mask = os.environ.get("ZE_AFFINITY_MASK", None)
if xpu_mask is not None and xpu_mask.strip():
# ZE_AFFINITY_MASK may use dotted format "0.0,1.0" for sub-devices;
# extract only the device portion (before the dot) for indexing.
return [e.split(".")[0] for e in xpu_mask.split(",")]
params.logits[b].copy_(saved_logits[b]);
}
}
saved_logits.reset();
// are 0, so mark those rows top_k=1 to make the per-row top_k filter pick
// the argmax token deterministically (instead of softmax/multinomial).
{
auto top_k_force = reinterpret_cast<uint32_t*>(params.top_k.data_ptr<int32_t>());
}

// 3. Top-k=1 fast path (greedy argmax)
auto top_k_ptr = reinterpret_cast<uint32_t*>(params.top_k.data_ptr<int32_t>());
// which must remain the original (pre-filter) softmax source for
// return_original_all_probs and cum_log_probs.
auto filtered_probs = probs_t.clone();
bool has_top_k = !std::all_of(top_k_ptr, top_k_ptr + batch_size, [](uint32_t t) { return t <= 0; });
- Add --config=xpu to .bazelrc; new xpu_configure.bzl (479 lines) that
  auto-detects the Intel oneAPI/SYCL toolchain and emits a Bazel C++
  toolchain (xpu_cc_toolchain_config.bzl.tpl, crosstool_wrapper_driver_xpu.tpl)
- Add torch_xpu_configure.bzl to locate PyTorch XPU headers/libs
- Extend arch_select.bzl to select XPU platform; update BUILD, BUILD.pytorch,
  bazel/defs.bzl, bazel/device_defs.bzl with USING_XPU compile-time flag
- Add pip_xpu_torch Bazel repo rule for XPU Python deps (requirements_xpu.txt,
  requirements_lock_xpu.txt); gate the rule behind TF_NEED_XPU so that
  `bazel sync` on non-XPU Python 3.10 containers never resolves XPU-only
  pins (e.g. scikit-learn==1.8.0 requires Python>=3.11)

- NormalEngine: include XPUCachingAllocator; add DeviceGuard for ctor
  thread; enable prefill warm-up and emptyCache() via XPU caching allocator
- PyWrappedModel: replace all hard-coded torch::kCUDA / .cuda() calls with
  getTorchDevice(); add kPinHostMem=false on XPU (pinned memory unsupported);
  guard kv_cache_block_id_host and block_id pin_memory() calls accordingly
- KVCacheManager, BlockPool, MemoryEvaluationHelper: add XPU memory
  evaluation and KV cache layout support
- Sampler, ModelTypes, ComputeInit: add XPU device branching

- New bindings/xpu/: RegisterXpuBaseBindings.hpp registers ~40 ops as
  pure-PyTorch fallbacks on XPU (RMSNorm, LayerNorm, attention, sampling,
  KV cache ops, write_cache_store)
- New modules/base/xpu/: activation.py, norm.py (RMSNorm/LayerNorm),
  moe_gating.py, select_topk.py, vllm_xpu_ops.py (flash_attn_varlen
  wrapper with SDPA fallback when vllm-xpu-kernels FA2 is absent)
- New modules/factory/attention/xpu_impl/vllm_flash_attn.py (906 lines):
  full paged-KV-cache attention for prefill and decode using flash_attn_varlen;
  rejects unsupported RoPE styles (Yarn/Llama3/Mrope/Glm2/DynamicNTK);
  hoist decode hash computation to step boundary (layer_idx wrap-around
  detection) instead of recomputing per layer
- New modules/factory/linear/impl/xpu/f16_linear.py and
  modules/factory/fused_moe/impl/xpu/ stubs
- Add unit tests: test_kv_cache_layout.py, test_no_rope.py

- Add XpuImpl class extending GpuImpl: get_device_id() with fallback to
  LOCAL_RANK + ZE_AFFINITY_MASK; _get_mem_info() via torch.xpu.mem_get_info;
  guard empty ZE_AFFINITY_MASK to avoid spurious device-0 targeting
- device_type.py: add XPU enum value and auto-detection logic

- server_config_setup.py: device selection via ZE_AFFINITY_MASK
- start_backend_server.py: XPU startup path
- model_loader/loader.py, weight_manager.py: XPU weight loading; use
  gpu_is_available() + XPU memory APIs for fastsafetensor progress log
- frontend_app.py, base_model.py: XPU path plumbing
Copilot AI review requested due to automatic review settings July 14, 2026 00:59
@aslanxie aslanxie force-pushed the feat/xpu-support-cp310 branch from 178fff6 to ad1c03b Compare July 14, 2026 00:59

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 100 out of 104 changed files in this pull request and generated 2 comments.

Comment on lines +1203 to +1207
xpu_mask = os.environ.get("ZE_AFFINITY_MASK", None)
if xpu_mask is not None and xpu_mask.strip():
# ZE_AFFINITY_MASK may use dotted format "0.0,1.0" for sub-devices;
# extract only the device portion (before the dot) for indexing.
return [e.split(".")[0] for e in xpu_mask.split(",")]
import torch

from rtp_llm.device.device_type import DeviceType, get_device_type, is_cuda, is_hip
from rtp_llm.device.device_type import DeviceType, get_device_type, is_cuda, is_hip, is_xpu
@LLLLKKKK

Copy link
Copy Markdown
Collaborator

AI Code Review - PR #1167

Status: BLOCKING

Summary: P0/0 · P1/4 · P2/0 · P3/0

Blocking Issues

P1

  • prompt target logprob 仍把标签搬到 CUDA @ rtp_llm/cpp/normal_engine/NormalOutputDispatcher.cc:166
    • 建议:改为使用 getTorchDevice() 创建标签,并增加真实 XPU 环境下覆盖 prompt logits、target logprob 和非空 slice 的集成测试。
  • 必需的 FA2 依赖没有可复现的版本与打包闭环 @ deps/requirements_xpu.txt:70
    • 建议:将经过验证的精确版本或兼容下限纳入 wheel、镜像和 lockfile 安装链路;启动时同时校验版本及所需 ABI/stride 能力,对不兼容版本明确 fail-fast。
  • KV cache 容量基于估算值而非 XPU 实际空闲显存 @ rtp_llm/models_py/bindings/core/ExecOps.cc:405
    • 建议:在 C++ 路径查询驱动层实际空闲显存,再从该值扣除运行时余量;增加存在外部显存占用或多 context 时的定容测试,验证 cache 不会超过真实可用空间。
  • sampler_test 仍固定到 CUDA,新增 XPU 采样路径没有生效覆盖 @ rtp_llm/cpp/test/SamplerTest.cc:71
    • 建议:测试中统一使用 getTorchDevice() 和平台感知的 pin-memory helper,并将 target 接入真实 XPU test env;补充与 CPU 参考实现对比的 greedy、混合 batch、top-k/top-p、penalty、seed、all_probs 和 beam search 用例。

Checklist Violations (10 fail / 137 total)

General Principles Checklist

  • [6.1] Architecture — 兼容性:外部 HTTP/RPC API、持久数据、配置、环境迁移安全 → issue 必需的 FA2 依赖没有可复现的版本与打包闭环
    文件声明 FA2 为必需依赖,却只保留手工安装占位版本,未进入可安装依赖或 lockfile。attention 实现又明确依赖 vllm-xpu-kernels v0.1.10 的非连续 paged K/V stride 能力,而启动检查只验证模块可导入。缺包会阻止启动,旧版本则可能在 decode 阶段违反 stride 契约。
  • [6.1] Architecture — 状态不变量:创建/更新/失败/重试/回滚路径有效 → issue KV cache 容量基于估算值而非 XPU 实际空闲显存
    XPU 分支用“总显存减本进程 allocator reserved,再固定扣除 10%”估算可用显存,无法反映驱动和其他进程的占用;该值随后基本全部用于 KV cache 定容。外部占用超过固定余量时,cache 会超配并在启动或推理期间 OOM。同一变更中的 Python 实现已使用 torch.xpu.mem_get_info 获取实际空闲值。
  • [6.1] Architecture — 错误语义:fail-fast/retry/fallback/silent 行为显式 → issue prompt target logprob 仍把标签搬到 CUDA
    XPU 请求启用 returnPromptLogits()return_target_logprob 后,该分支仍执行 .to(torch::kCUDA)。此时 sliced_logits 位于 XPU,标签要么在无 CUDA 的环境中创建失败,要么在后续 gather 时触发跨设备错误,导致请求失败。
  • [6.1] Tests — 分布式/跨平台变更有对应覆盖 → issue sampler_test 仍固定到 CUDA,新增 XPU 采样路径没有生效覆盖
    测试中的输入仍显式 .to(torch::kCUDA),并无条件调用 pin_memory();对应 BUILD target 也仍绑定 CUDA GPU 环境。本次新增的测试只检查 pin flag,没有执行新增的 XPU greedy sampling 和 beam search,因此 batch、seed、top-k/top-p、penalty、概率输出等核心语义缺少真实 XPU 覆盖。
  • [6.1] Tests — 新逻辑有聚焦单测 + 相关集成/smoke 测试 → issue sampler_test 仍固定到 CUDA,新增 XPU 采样路径没有生效覆盖
    测试中的输入仍显式 .to(torch::kCUDA),并无条件调用 pin_memory();对应 BUILD target 也仍绑定 CUDA GPU 环境。本次新增的测试只检查 pin flag,没有执行新增的 XPU greedy sampling 和 beam search,因此 batch、seed、top-k/top-p、penalty、概率输出等核心语义缺少真实 XPU 覆盖。

RTP-LLM Checklist

  • [A] 兼容性与配置 — 依赖、lockfile、wheel metadata、optional extras 和平台 override 必须同源一致;默认安装依赖不得包含明文 HTTP、内部 URL、个人绝对路径、本地 symlink/local_repository 或未同步 lock 的版本漂移 → issue 必需的 FA2 依赖没有可复现的版本与打包闭环
    文件声明 FA2 为必需依赖,却只保留手工安装占位版本,未进入可安装依赖或 lockfile。attention 实现又明确依赖 vllm-xpu-kernels v0.1.10 的非连续 paged K/V stride 能力,而启动检查只验证模块可导入。缺包会阻止启动,旧版本则可能在 decode 阶段违反 stride 契约。
  • [B] 正确性与逻辑 — Sampler/LogitsProcessor/top-k/top-p/recommendation 变更必须保持合法候选 mask、batch tiling、RNG 和分布语义,并有 reference 分布或边界测试 → issue sampler_test 仍固定到 CUDA,新增 XPU 采样路径没有生效覆盖
    测试中的输入仍显式 .to(torch::kCUDA),并无条件调用 pin_memory();对应 BUILD target 也仍绑定 CUDA GPU 环境。本次新增的测试只检查 pin flag,没有执行新增的 XPU greedy sampling 和 beam search,因此 batch、seed、top-k/top-p、penalty、概率输出等核心语义缺少真实 XPU 覆盖。
  • [D] 性能 — 通信 / buffer 开销评估 → issue KV cache 容量基于估算值而非 XPU 实际空闲显存
    XPU 分支用“总显存减本进程 allocator reserved,再固定扣除 10%”估算可用显存,无法反映驱动和其他进程的占用;该值随后基本全部用于 KV cache 定容。外部占用超过固定余量时,cache 会超配并在启动或推理期间 OOM。同一变更中的 Python 实现已使用 torch.xpu.mem_get_info 获取实际空闲值。
  • [F] 跨平台 — ROCm/XPU/CUDA fallback 的 shape、stride、dtype、sentinel/mask、sampling/beam/logits 数值语义必须与 CUDA/CPU reference 对齐;不支持时必须 graceful reject → issue sampler_test 仍固定到 CUDA,新增 XPU 采样路径没有生效覆盖
    测试中的输入仍显式 .to(torch::kCUDA),并无条件调用 pin_memory();对应 BUILD target 也仍绑定 CUDA GPU 环境。本次新增的测试只检查 pin flag,没有执行新增的 XPU greedy sampling 和 beam search,因此 batch、seed、top-k/top-p、penalty、概率输出等核心语义缺少真实 XPU 覆盖。
  • [H] 测试与 CI — 新增、迁移或删除测试必须证明目标行为仍在 CI 中执行;DISABLED_、#if 0、open_skip、导入即失败、未被 target 引用的用例不得计为覆盖 → issue sampler_test 仍固定到 CUDA,新增 XPU 采样路径没有生效覆盖
    测试中的输入仍显式 .to(torch::kCUDA),并无条件调用 pin_memory();对应 BUILD target 也仍绑定 CUDA GPU 环境。本次新增的测试只检查 pin flag,没有执行新增的 XPU greedy sampling 和 beam search,因此 batch、seed、top-k/top-p、penalty、概率输出等核心语义缺少真实 XPU 覆盖。

Strengths

  • XPU attention 对 multi-KV-group、prefix cache 等未支持组合采用显式拒绝,并提供了对应测试,避免静默产生错误结果。
  • XPU wheel override 与 lockfile 的版本一致性已有自动测试约束。
  • 设备抽象覆盖了多处公共路径,且对不支持的 speculative、multi-rank 等模式保留了清晰的 fail-fast 行为。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants