Skip to content

feat(mars): add llama flash attention operators - #1055

Open
wooway777 wants to merge 2 commits into
masterfrom
feat/mars-llama-flash-attn
Open

wooway777 wants to merge 2 commits into
masterfrom
feat/mars-llama-flash-attn

Conversation

@wooway777

@wooway777 wooway777 commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Add Mars FlashAttention providers for FlashAttnVarlenFunc and FlashAttnWithKvcache, backed by HPCC libhcFlashAttn.so.
  • Add shared HPCC dtype/tensor/stream/status helpers in src/native/cuda/mars/ops/flash_attn_common.h.
  • Add scripts/configs/infiniops_ops_mars_llama.json for llama inference, selecting ATen Argmax at implementation slot 8.
  • Update the Mars build: link hcFlashAttn, filter temporary .cc.cu symlinks, remove CONFIGURE_DEPENDS from the Mars source glob, make the offline nlohmann/json path relative, and pass -DWITH_TORCH=1 to Torch sources.
  • Instantiate CPU ATen providers when WITH_TORCH=ON, even when the native CPU backend is disabled.

Motivation

Enable the llama inference workflow on Mars/HPCC with both paged-attn and flash-attn. Using ATen for Argmax avoids a hand-written Mars reduction kernel. The build changes are needed to link HPCC FlashAttention and to keep the Torch backend self-consistent without enabling the native CPU backend.

No linked issue.

Type of Change

  • feat — new feature / new operator / new platform
  • fix — bug fix
  • perf — performance improvement (no behavioral change)
  • refactor — code restructuring without behavior change
  • test — adding or fixing tests only
  • docs — documentation only
  • build / ci — build system or CI configuration
  • chore — tooling, formatting, or other non-code changes
  • Breaking change (requires a ! in the Conventional Commits prefix or a BREAKING CHANGE: footer)

Platforms Affected

  • Mars (WITH_MARS)
  • CPU (WITH_CPU) — ATen CPU provider instantiation only; native CPU backend behavior is unchanged
  • NVIDIA (WITH_NVIDIA)
  • Iluvatar (WITH_ILUVATAR)
  • MetaX (WITH_METAX)
  • Cambricon (WITH_CAMBRICON)
  • Moore (WITH_MOORE)
  • Ascend (WITH_ASCEND)
  • PyTorch C++ bindings (WITH_TORCH)
  • Build system / CMake / CI
  • Python bindings / user-facing API

Smoke Test Result

# InfiniOps build: Mars + ATen
cmake -S third_party/InfiniCore/submodules/InfiniOps \
  -B build/infiniops -G Ninja \
  -DCMAKE_BUILD_TYPE=Release \
  -DCMAKE_SUPPRESS_REGENERATION=ON \
  -DWITH_MARS=ON -DWITH_CPU=OFF -DWITH_TORCH=ON \
  -DINFINI_OPS_OPS=/opt/pepe-tools/llama-mars-ops.json \
  -DINFINI_OPS_TORCH_OPS=argmax \
  -DPython_EXECUTABLE=/opt/conda/bin/python
ninja -C build/infiniops -j16 infiniops
[12/12] Linking CXX shared library src/libinfiniops.so

# InfiniLM end-to-end smoke on tj-metax-23
pepe 'cd /home/wuwei/InfiniLM; PYTHONPATH=/home/wuwei/InfiniLM/python \
  python examples/test_infer.py --device=mars \
  --model=/private/wei/projects/tiny-llama-mars --backend=cpp \
  --prompt=Hello --attn=flash-attn --enable-paged-attn \
  --max-new-tokens=2 --top-k=1 --temperature=0'
===Response===
tok108tok59
total_time: 695.25 ms

The same InfiniLM smoke command also passed on tj-metax-24:

===Response===
tok108tok59
total_time: 723.96 ms

Test Results on Supported Platforms

Platform Affected Build / Smoke Result Full Result / Notes
Mars Yes passed InfiniLM flash-attn end-to-end smoke passed; full InfiniOps pytest not run
CPU Yes N/A - native CPU backend not built ATen CPU provider instantiation changed; no native CPU runtime test
NVIDIA No N/A - not affected
Iluvatar No N/A - not affected
MetaX No N/A - not affected
Cambricon No N/A - not affected
Moore No N/A - not affected
Ascend No N/A - not affected
Full `pytest` output (optional)
Not run. Validation was the Mars InfiniOps build plus InfiniLM end-to-end inference.

Benchmark / Performance Impact

N/A. This is not a performance PR. End-to-end tiny-llama smoke timing was about 0.70 s on tj-metax-23 and 0.72 s on tj-metax-24 for 2 generated tokens.

Notes for Reviewers

  • HPCC mha_fwd_kvcache requires a valid contiguous softmax_lse tensor even when LSE is not returned; the provider allocates a workspace for it.
  • The Mars source glob no longer uses CONFIGURE_DEPENDS because htcc_wrapper.sh creates temporary .cc.cu symlinks. Re-run CMake after adding new Mars source files.
  • Build with WITH_TORCH=ON and INFINI_OPS_TORCH_OPS=argmax to generate the ATen Argmax provider. The Mars llama profile selects implementation slot 8.
  • Full InfiniOps pytest was not run; validation was the Mars build and InfiniLM end-to-end smoke.

@wooway777
wooway777 requested a review from a team November 25, 2026 02:35
@baominghelly

Copy link
Copy Markdown
Collaborator

/ai-pr-review

@github-actions

Copy link
Copy Markdown

AI PR Review

Reviewed PR: #1055
Head SHA: 30227c63450a3ff35b985be9d0de28cdd7befc97

Verdict

  • Finding count: B=3, N=8, G=5
  • Summary: The PR adds native Mars flash-attention providers at slot 0 and a llama build config, but both providers inherit the base supports() and therefore shadow the existing slot-16 linked providers while rejecting configurations the base contract admits (ALiBi, attention-probability outputs, k/v append, rotary, non-paged varlen). The kvcache workspace is not checked against the caller-supplied size, and no Mars build/test evidence is provided; the shared varlen suite reaches the paged ALiBi case on Mars and will throw. Add Mars-specific supports() predicates, validate the workspace, and attach Mars smoke/test results before merge.

Blocking findings

  • [B1] src/native/cuda/mars/ops/flash_attn_varlen_func/kernel.h:13 — Slot-0 Mars providers shadow slot 16 and advertise the full base contract

    • Evidence: Operator<FlashAttnVarlenFunc, Device::Type::kMars, 0> and Operator<FlashAttnWithKvcache, Device::Type::kMars, 0> (src/native/cuda/mars/ops/flash_attn_with_kvcache/kernel.h:13) declare no supports(), so they inherit FlashAttnVarlenFunc::supports and FlashAttnWithKvcache::supports. Those predicates admit non-paged varlen (src/base/flash_attn_varlen_func.h:34), ALiBi (:43), and return_attn_probs/softmax_lse/s_dmask (:48-50), plus k/v cache append, rotary, cache_batch_idx/cache_leftpad, ALiBi, and return_softmax_lse (src/base/flash_attn_with_kvcache.h:108-112, :143-148). The Mars kernels throw for every one of those inputs (src/native/cuda/mars/ops/flash_attn_varlen_func/kernel.cu:14-23, src/native/cuda/mars/ops/flash_attn_with_kvcache/kernel.cu:32-42). Automatic dispatch iterates active slots in ascending order and stops at the first supports match (src/operator.h:760-764), so slot 0 wins over the existing linked slot-16 providers (src/linked/torch/mars/ops/flash_attn_varlen_func/flash_attn.h:11, src/linked/torch/mars/ops/flash_attn_with_kvcache/flash_attn.h:11).
    • Impact: Existing Mars callers that relied on slot 16 for ALiBi, return_attn_probs/return_softmax_lse, k/v append, rotary, cache_batch_idx, or non-paged varlen now get std::invalid_argument at call time; the linked provider is never tried. The new scripts/configs/infiniops_ops_mars_llama.json selects "all" for both ops, making slot 0 the default.
    • Suggestion: Add Mars-specific supports() overloads (or a shared Supports predicate) to both slot-0 providers that reject every configuration the native kernel rejects, including non-paged varlen, ALiBi, attn-prob/LSE outputs, k/v append, rotary, cache metadata, and MLA if the HPCC library does not serve it. Keep slot 16 as the fallback, and add dispatch tests that assert unsupported configurations fall through to slot 16.
  • [B2] src/native/cuda/mars/ops/flash_attn_with_kvcache/kernel.cu:50 — Kvcache workspace is not size-checked before use

    • Evidence: The kernel only checks !workspace_ and then builds an FP32 [batch, heads, seqlen] descriptor over workspace_ (:50-58). Operator::Call honors an explicit handle workspace without checking its size (src/operator.h:544-546), and the comment there explicitly says providers must validate their own requirements. Other providers do: src/native/cuda/nvidia/ops/argmax/kernel.h:82, src/native/cuda/nvidia/ops/i8_gemm/kernel.h:114, and the NVIDIA flash-attention WorkspaceLease rejects available < required (src/native/cuda/nvidia/ops/flash_workspace.h:45).
    • Impact: A caller that passes a smaller explicit workspace (a supported Handle contract) gets an out-of-bounds write by the HPCC library, i.e. memory corruption. Alignment requirements are also unchecked.
    • Suggestion: Check workspace_size_in_bytes_ >= workspace_size_in_bytes() (and the required alignment) before make_tensor3d, and throw a clear diagnostic otherwise. Consider a small RAII lease like native_flash::WorkspaceLease for consistency.
  • [B3] tests/test_flash_attn_varlen_func.py:77 — No Mars validation; the shared varlen suite fails on the paged ALiBi case

    • Evidence: Mars is not in the CI matrix (.github/workflows/ci_test.yml:15 lists nvidia,iluvatar,metax,moore,cambricon,ascend), and context/checks.json has no Mars check. The PR description's Smoke Test Result and Test Results tables are empty (context/pr.json:4). The parametrization includes a paged causal ALiBi case (tests/test_flash_attn_varlen_func.py:31); the skip at :77-81 does not skip it because paged and causal and window_size == (-1, -1) is true, so on Mars (device="cuda", implementation_index=0) it reaches the native provider and hits the throw at src/native/cuda/mars/ops/flash_attn_varlen_func/kernel.cu:17-20. Conversely, many tests use device == "cuda" and implementation_index == 0 as an "Iluvatar native" skip (tests/test_flash_attn_with_kvcache.py:260, tests/test_flash_attn_varlen_func.py:77), so the new Mars provider is silently skipped there.
    • Impact: The new native providers ship with no proof of numerical correctness on the only platform they affect, and the shared test suite is red on Mars while most coverage is skipped rather than reported.
    • Suggestion: Add Mars smoke build/test results (HPCC SDK version, commands, pass/skip counts), add Mars-specific tests for both slots (paged causal, paged ALiBi if supported, non-default stream), and replace the Iluvatar-specific skip conditions with provider-aware skips.

Non-blocking findings

  • [N1] src/native/cuda/mars/ops/flash_attn_varlen_func/kernel.cu:31 — hc_block_table is created but never passed to mha_varlen_fwd

    • Evidence: hc_block_table is created at :31 and released at :51, but the call at :42-48 passes five nullptr arguments plus extend; the block table is only supplied through set_extend_parameter_block_table (:33-36).
    • Impact: If the HPCC API expects the block table as a Tensor_t argument, paged attention runs without it; if extend is the only mechanism, the descriptor is a dead allocation. The intent is unclear either way.
    • Suggestion: Remove the unused descriptor or pass it to the API, and document which argument carries the block table.
  • [N2] src/native/cuda/mars/ops/flash_attn_with_kvcache/kernel.cu:35 — num_splits is accepted but ignored

    • Evidence: The kernel rejects only num_splits < 0 (:35-37) and hardcodes 1 in the HPCC call (:67).
    • Impact: A caller requesting split-KV (num_splits=4) silently gets one split; the requested contract is not honored, even if results are numerically equivalent.
    • Suggestion: Pass num_splits through if the HPCC API supports it, or reject values other than 0/1 and narrow supports() accordingly.
  • [N3] src/native/cuda/mars/ops/flash_attn_common.h:68 — Stream conversion bypasses the runtime abstraction and diagnostics omit the status code

    • Evidence: ToHcStream uses reinterpret_cast<hcStream_t>(stream) (:68-70); the kernels use the redundant stream_ ? stream_ : nullptr (src/native/cuda/mars/ops/flash_attn_varlen_func/kernel.cu:48, src/native/cuda/mars/ops/flash_attn_with_kvcache/kernel.cu:67); CheckHcStatus reports only the call name (:72-75).
    • Impact: This violates the repository rule to keep vendor stream types in runtime adapters and makes stream conversion and vendor failures harder to maintain and diagnose.
    • Suggestion: Use Runtime<Device::Type::kMars>/Backend::GetStream (or the Mars runtime's stream accessor) and include the numeric hcflashattnStatus_t in the error message.
  • [N4] src/CMakeLists.txt:54 — Build changes are underdocumented and reduce maintainability

    • Evidence: The new block auto-detects ${CMAKE_CURRENT_SOURCE_DIR}/../../../../json and force-sets FETCHCONTENT_SOURCE_DIR_NLOHMANN_JSON (:54-66), potentially overriding an explicit user -DFETCHCONTENT_SOURCE_DIR_NLOHMANN_JSON. The Mars glob drops CONFIGURE_DEPENDS (:394) while every other backend keeps it; :397 adds a .cc.cu filter that matches no file; :407 discovers hcFlashAttn in src/CMakeLists.txt while the other HPCC libraries are discovered in the root CMakeLists.txt:608.
    • Impact: Environment-specific build behavior, silent override of user cache variables, stale source lists on incremental Mars builds, and an undocumented new hard SDK dependency.
    • Suggestion: Move HPCC flash-attention discovery next to the other HPCC libraries, document the minimum HPCC SDK version and make the offline json override opt-in, restore CONFIGURE_DEPENDS or explain why it must be removed, and delete the no-op filter.
  • [N5] src/torch/instantiate.h:6 — CPU torch instantiation change is broader than the PR and unexplained

    • Evidence: INFINI_OPS_TORCH_INSTANTIATE_CPU now expands for any WITH_TORCH translation unit (src/torch/instantiate.h:6), and src/CMakeLists.txt:1247 adds -DWITH_TORCH=1 to the torch compile flags.
    • Impact: This changes link/compile behavior for every WITH_TORCH build without native CPU (not just Mars), increasing binary size and compile time and changing which CPU ATen symbols are available. No test or rationale is given.
    • Suggestion: Document why CPU ATen instantiation is needed without WITH_CPU, add a configure/build test for -DWITH_TORCH=ON -DWITH_CPU=OFF, and consider splitting it into a separate PR.
  • [N6] src/native/cuda/mars/ops/flash_attn_common.h:39 — Integer narrowing and non-finite scale are unchecked

    • Evidence: MakeHcTensor casts sizes/strides to int (:39-44); total_k, batch, heads, and query_length are also narrowed (src/native/cuda/mars/ops/flash_attn_varlen_func/kernel.cu:38-39, src/native/cuda/mars/ops/flash_attn_with_kvcache/kernel.cu:53-55); SoftmaxScaleOrDefault returns the scale without an isfinite check (:78-81), unlike the NVIDIA provider (src/native/cuda/nvidia/ops/flash_attn_varlen_func/kernel.cc:162-163).
    • Impact: Large KV caches or long sequences can silently truncate dimensions, and NaN/Inf scale propagates into the HPCC kernel.
    • Suggestion: Add INT_MAX and std::isfinite checks with clear diagnostics, or use 64-bit API variants where available.
  • [N7] src/native/cuda/mars/ops/flash_attn_with_kvcache/kernel.h:37 — capture_safe() = true is asserted without evidence

    • Evidence: Both Mars providers return true (src/native/cuda/mars/ops/flash_attn_with_kvcache/kernel.h:37, src/native/cuda/mars/ops/flash_attn_varlen_func/kernel.h:31), but the kvcache path uses workspace_ and an opaque vendor call; the NVIDIA provider explicitly checks stream capture and requires stable external workspace (src/native/cuda/nvidia/ops/flash_workspace.h:54).
    • Impact: If the HPCC library allocates or synchronizes during capture, graph capture fails or corrupts memory; the claim is untested.
    • Suggestion: Either justify capture safety with a Mars graph-capture test and a stable-workspace contract, or return false until verified.
  • [N8] context/pr.json:4 — PR template is unfilled and commit types are inconsistent

    • Evidence: The body has empty Summary/Motivation, unchecked Type of Change and Platforms Affected, and empty Smoke Test Result and Test Results tables. The second commit is fix(mars): use ATen argmax for llama inference (context/commits.json:9) in a feat PR/branch.
    • Impact: Reviewers cannot tell which platforms are affected or what was tested; the commit history misrepresents the change type. The change touches Mars, CMake, and torch bindings, but none of those boxes are ticked.
    • Suggestion: Fill the template (tick Mars, Build system/CMake/CI, and PyTorch C++ bindings), add smoke/test commands and results, and reword the second commit to feat(mars): ... or squash it.

Evidence gaps

  • [G1] src/native/cuda/mars/ops/flash_attn_varlen_func/kernel.cu:42 — HPCC hcflashattn API contract is unavailable

    • Missing evidence: The flash_attn/flash_attn.h header and a Mars build/test log.
    • Why it matters: The correctness of both providers depends on the argument order and Tensor_t layout of mha_varlen_fwd/mha_fwd_kvcache; total_k = k.size(0) * k.size(1) may be block capacity rather than actual key tokens, and releasing Tensor_t/extend immediately may be unsafe if the library retains pointers. Non-contiguous strides (the base only requires stride(-1) == 1) are also unverified.
    • Suggested evidence: The HPCC SDK version and the relevant header declarations, plus a Mars smoke test comparing slot 0 against slot 16.
  • [G2] .github/workflows/ci_test.yml:15 — Mars has no CI coverage and no smoke results are attached

    • Missing evidence: Mars build and test logs.
    • Why it matters: The new native code is untested on the only platform it affects; all unit checks in context/checks.json are failing or absent for Mars.
    • Suggested evidence: python -m pip install .[dev] ... and pytest tests/test_flash_attn_varlen_func.py tests/test_flash_attn_with_kvcache.py --devices mars output with pass/skip counts.
  • [G3] src/native/cuda/mars/ops/flash_attn_with_kvcache/kernel.h:37 — Graph-capture safety is unverified

    • Missing evidence: A Mars graph-capture test or vendor documentation that the calls are capture-safe.
    • Why it matters: capture_safe() returns true; if the library allocates or synchronizes, capture breaks.
    • Suggested evidence: A capture test using the runtime's graph API, or set capture_safe() to false.
  • [G4] scripts/configs/infiniops_ops_mars_llama.json:1 — The intended build configuration is undocumented

    • Missing evidence: The exact CMake command (WITH_TORCH, WITH_LINKED, INFINI_OPS_TORCH_OPS, INFINI_OPS_SMOKE_BUILD) and whether public_api_only ops are expected to execute.
    • Why it matters: The config selects argmax slot 8, but the smoke torch-op list is abs clamp exp relu (src/CMakeLists.txt:710), so INFINI_OPS_SMOKE_BUILD=ON with this config can fail at configure time; 41 ops are public_api_only (not executable).
    • Suggested evidence: A documented build command and a configure log showing the config resolves.
  • [G5] src/CMakeLists.txt:407 — Minimum HPCC SDK version is undocumented

    • Missing evidence: The SDK version used by the author and the version that introduced libhcFlashAttn/flash_attn/flash_attn.h.
    • Why it matters: find_library(... REQUIRED) makes the library a hard requirement for every Mars build; older SDKs fail with a generic error.
    • Suggested evidence: Document the minimum HPCC version and add a clear configure diagnostic.

AI review is advisory and does not replace maintainer review or CI.
Reviewed PR: #1055

Comment thread src/torch/instantiate.h
// Emit definitions only for the backends enabled in this translation unit.

#ifdef WITH_CPU
#if defined(WITH_CPU) || defined(WITH_TORCH)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

这个可能是因为你链接的InfiniRT用了CPU编译,InfiniOps没用CPU编译, 所以报错,如果对齐的话,可能不需要这个修改

Comment thread src/CMakeLists.txt

# Vendor-specific defines required by forked `torch` headers.
set(_torch_extra_flags "")
list(APPEND _torch_extra_flags "-DWITH_TORCH=1")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

如果instantiate.h不改,这里应该也可以不改

const std::vector<int64_t> window_size, const double softcap,
const bool deterministic, const bool return_attn_probs, Tensor out,
std::optional<Tensor> softmax_lse, std::optional<Tensor> s_dmask) const {
if (!block_table.has_value())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

请把修改中所有的throw error都改成assert吧,这个代码库目前贡献准则中指定用assert,不用error。link
示例

@baominghelly baominghelly left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

请参考PR中的comment

This branch has not been deployed

No deployments
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.

2 participants