Skip to content

fix(pcie): support head-major DCP reduce outputs - #54

Merged
lukealonso merged 2 commits into
local-inference-lab:masterfrom
voipmonitor:fix/head-major-dcp-output-20260721
Jul 21, 2026
Merged

fix(pcie): support head-major DCP reduce outputs#54
lukealonso merged 2 commits into
local-inference-lab:masterfrom
voipmonitor:fix/head-major-dcp-output-20260721

Conversation

@voipmonitor

@voipmonitor voipmonitor commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Summary

Fixes the DCP PCIe LSE reduce output contract so callers can provide a BHD tensor whose logical layout is token-major but whose physical storage is head-major. This avoids handing cuBLAS a strided view backed by a tight IPC/custom allocation in the downstream MLA V up-projection path.

Root Cause

The GLM MLA _v_up_proj call uses a strided batched GEMM layout. Guarded repros showed cuBLAS can legally read ahead to the next 64 KiB boundary for this pattern. Normal PyTorch allocator segments make that safe, but tight DCP IPC/pool outputs can fault on the first unmapped page after the logical tensor.

Padding every allocation or cloning pool outputs fixes correctness but costs either KV capacity or decode latency. This PR instead lets the DCP producer write directly into caller-provided head-major storage while preserving the public BHD shape.

Changes

  • Accept packed token-major and capacity-strided head-major BHD tensors in the PCIe DCP LSE reduce path.
  • Pass input/output batch/head strides into the CUDA kernel instead of assuming contiguous tensors.
  • Add head_major_output scratch planning for sparse MLA output buffers.
  • Add CPU validation tests and extend the PCIe DCP GPU test to cover head-major input/output views across batch sizes.

Validation

  • python3 -m pytest tests/comm/test_pcie_dcp_a2a.py::test_runtime_accepts_head_major_input_and_output tests/comm/test_pcie_dcp_a2a.py::test_runtime_validates_and_dispatches_to_extension -q -> 2 passed
  • Scratch head-major smoke script using SPARKINFERSparseMLAScratchCaps(head_major_output=True) -> passed
  • Earlier overlay validation on 8x RTX PRO 6000 Blackwell with the same logic:
    • B12X PCIe DCP GPU integration test -> passed
    • GLM 5.2 TP8/DCP2 long-context decode smoke -> no Xid / no CJK / no CUDA errors
    • GLM 5.2 TP8/DCP4 long-context decode smoke -> no Xid / no CJK / no CUDA errors

Summary by CodeRabbit

  • New Features
    • Added support for head-major output layouts in sparse MLA scratch buffers.
    • Extended PCIe DCP LSE reduce-scatter to work with compatible head-major tensor views.
    • Allow reuse of preallocated output buffers while preserving the requested layout.
  • Bug Fixes
    • Improved layout validation and error messaging for unsupported input/output views.
  • Tests
    • Added parameterized tests for head-major scratch bindings across decode/extend.
    • Expanded PCIe test coverage, including head-major paths and larger batch scenarios.

@coderabbitai

coderabbitai Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9cb88e2d-7e3f-4f90-a837-468d5e6365cf

📥 Commits

Reviewing files that changed from the base of the PR and between 9351034 and 6e49ebb.

📒 Files selected for processing (1)
  • sparkinfer/comm/pcie/pcie_dcp_a2a.py

📝 Walkthrough

Walkthrough

The change adds head-major output support to sparse MLA scratch buffers and PCIe LSE reduce-scatter. It introduces stride-aware buffer construction and CUDA indexing, validates token-major or head-major layouts, and expands Python and GPU tests for output placement and batch coverage.

Changes

Head-major layout support

Layer / File(s) Summary
Sparse MLA scratch output views
sparkinfer/attention/_shared/workspace.py, sparkinfer/attention/sparse_mla/_scratch.py, tests/attention/test_compressed_scratch_bindings.py
Scratch capabilities and views expose head_major_output; split and non-split materialization create corresponding strides and aliases, with binding coverage for decode and extend modes.
PCIe layout validation and kernel strides
sparkinfer/comm/pcie/pcie_dcp_a2a.py, sparkinfer/comm/pcie/pcie_dcp_a2a.cu
PCIe validation accepts packed token-major or head-major tensors, and the reduction kernel receives explicit batch and head strides for staging, reduction, and output writes.
Head-major layout coverage
tests/comm/test_pcie_dcp_a2a.py, tests/comm/test_pcie_dcp_a2a_gpu.py
Runtime tests cover head-major inputs, outputs, invalid layouts, preallocated output identity, expanded batch sizes, and CUDA graph buffer strides.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant lse_reduce_scatter
  participant PCIeDCPA2A
  participant dcp_lse_reduce_kernel
  Caller->>lse_reduce_scatter: provide partial output and output tensors
  lse_reduce_scatter->>lse_reduce_scatter: validate layouts and derive strides
  lse_reduce_scatter->>PCIeDCPA2A: pass tensors and stride parameters
  PCIeDCPA2A->>dcp_lse_reduce_kernel: launch stride-aware reduction
  dcp_lse_reduce_kernel->>Caller: write reduced output tensor
Loading

Suggested reviewers: lukealonso

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: adding head-major support to PCIe DCP reduce outputs.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
sparkinfer/attention/sparse_mla/_scratch.py (1)

434-448: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate head-major stride formula.

The literal (v_head_dim, max_total_q * v_head_dim, 1) here duplicates the same head-major stride computation already expressed (generically, from output.shape) in workspace.py's _split_output_buffer_from_tmp. If the head-major convention ever changes, only one of the two spots is likely to get updated.

♻️ Suggested consolidation
-        if caps.head_major_output:
-            output_buffer, _ = materialize_scratch_strided_view(
-                scratch_storage,
-                offset_bytes=layout.output_offset_bytes,
-                shape=(max_total_q, num_q_heads, v_head_dim),
-                stride=(v_head_dim, max_total_q * v_head_dim, 1),
-                dtype=caps.dtype,
-            )
+        if caps.head_major_output:
+            output_buffer, _ = materialize_scratch_strided_view(
+                scratch_storage,
+                offset_bytes=layout.output_offset_bytes,
+                shape=(max_total_q, num_q_heads, v_head_dim),
+                stride=_split_tmp_output_stride(
+                    max_total_q=max_total_q,
+                    num_q_heads=num_q_heads,
+                    max_chunks_per_row=1,
+                    v_head_dim=v_head_dim,
+                    head_major_output=True,
+                )[:3] + (1,),
+                dtype=caps.dtype,
+            )

(or extract a small shared 3-tuple helper in workspace.py reused by both call sites.)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@sparkinfer/attention/sparse_mla/_scratch.py` around lines 434 - 448,
Consolidate the head-major stride calculation used by the
`caps.head_major_output` branch in the surrounding output-buffer setup with the
existing generic computation in `_split_output_buffer_from_tmp`. Reuse a shared
helper or established workspace logic instead of hardcoding `(v_head_dim,
max_total_q * v_head_dim, 1)`, while preserving the current shape and layout
behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@sparkinfer/comm/pcie/pcie_dcp_a2a.py`:
- Around line 33-47: Update _is_supported_bhd_layout so
capacity_strided_head_major additionally requires stride_head to be divisible by
8, matching the CUDA extension’s alignment requirement. Keep the existing
dimensional, contiguous-last-dimension, minimum-capacity-stride, and
packed-token-major checks unchanged so _validate can reject unaligned head-major
tensors cleanly.

---

Nitpick comments:
In `@sparkinfer/attention/sparse_mla/_scratch.py`:
- Around line 434-448: Consolidate the head-major stride calculation used by the
`caps.head_major_output` branch in the surrounding output-buffer setup with the
existing generic computation in `_split_output_buffer_from_tmp`. Reuse a shared
helper or established workspace logic instead of hardcoding `(v_head_dim,
max_total_q * v_head_dim, 1)`, while preserving the current shape and layout
behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c6a95f66-ffe1-498f-8cb7-15aaf5e26926

📥 Commits

Reviewing files that changed from the base of the PR and between ec2cd4d and 9351034.

📒 Files selected for processing (7)
  • sparkinfer/attention/_shared/workspace.py
  • sparkinfer/attention/sparse_mla/_scratch.py
  • sparkinfer/comm/pcie/pcie_dcp_a2a.cu
  • sparkinfer/comm/pcie/pcie_dcp_a2a.py
  • tests/attention/test_compressed_scratch_bindings.py
  • tests/comm/test_pcie_dcp_a2a.py
  • tests/comm/test_pcie_dcp_a2a_gpu.py

Comment thread sparkinfer/comm/pcie/pcie_dcp_a2a.py Outdated
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@lukealonso
lukealonso merged commit 2188eee into local-inference-lab:master Jul 21, 2026
1 check was pending
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