Skip to content

[ROCm] Support large inputs for coalesceValuesKernel - #158281

Closed
xinyazhang wants to merge 7 commits into
pytorch:mainfrom
ROCm:xinyazhang/swdev-523284
Closed

xinyazhang wants to merge 7 commits into
pytorch:mainfrom
ROCm:xinyazhang/swdev-523284

Conversation

@xinyazhang

@xinyazhang xinyazhang commented Jul 14, 2025 •

Copy link
Copy Markdown
Collaborator

Description

.coalesce cannot handle large inputs on ROCM due to maximal grid size limit.

This PR splits axis X into axes X and Y, and repurposes Z for original Y on ROCm to avoid such limitation.

Confirmed the new approach can handle large inputs. Correctness needs validation.

Testing Command

python torch_spmv.py 22500000 272500000

Script torch_spmv.py

import torch
import argparse

def parse_args():
    parser = argparse.ArgumentParser(
        description="Sparse COO Matrix by Dense Vector Multiplication using PyTorch"
    )
    parser.add_argument("n", type=int, help="Size of the NxN matrix")
    parser.add_argument("nnz", type=int, help="Number of non-zero entries")
    return parser.parse_args()

def main():
    args = parse_args()
    n = args.n
    nnz = args.nnz
    dtype = torch.float32
    device = torch.device('cuda')

    # Generate random indices for the sparse matrix in COO format.
    torch.manual_seed(42)
    rows = torch.randint(0, n, (nnz,), dtype=torch.int64, device=device)
    cols = torch.randint(0, n, (nnz,), dtype=torch.int64, device=device)
    indices = torch.stack([rows, cols], dim=0)

    # Generate random values.
    values = torch.randn(nnz, dtype=torch.float32, device=device)

    # Create the sparse COO matrix and move it to the target device.
    sparse_matrix = torch.sparse_coo_tensor(indices, values, size=(n, n), dtype=torch.float32, device=device)
    sparse_matrix = sparse_matrix.coalesce()

    # Generate a random dense vector.
    dense_vector = torch.randn(n, dtype=torch.float32, device=device)

    # Perform sparse matrix - dense vector multiplication.
    # Using torch.sparse.mm which expects a 2D tensor for the vector.
    result = torch.sparse.mm(sparse_matrix, dense_vector.unsqueeze(1)).squeeze()
    # result = torch.mv(sparse_matrix, dense_vector)

    # Print the result.
    print("Result of the multiplication:")
    print(torch.sum(result))

if __name__ == "__main__":
    main()

cc @jeffdaily @sunway513 @jithunnair-amd @pruthvistony @ROCmSupport @dllehr-amd @jataylo @hongxiayang @naromero77amd

@pytorch-bot

pytorch-bot Bot commented Jul 14, 2025 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/158281

Note: Links to docs will display an error until the docs builds have been completed.

✅ No Failures

As of commit 1516d3d with merge base 9903ca4 (image):
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added module: rocm AMD GPU support for Pytorch release notes: sparse release notes category ciflow/rocm labels Jul 14, 2025
@pytorch-bot

pytorch-bot Bot commented Jul 14, 2025

Copy link
Copy Markdown

To add the ciflow label ciflow/rocm please first approve the workflows that are awaiting approval (scroll to the bottom of this page).

This helps ensure we don't trigger CI on this PR until it is actually authorized to do so. Please ping one of the reviewers if you do not have access to approve and run workflows.

@pytorch-bot pytorch-bot Bot removed the ciflow/rocm label Jul 14, 2025
@xinyazhang xinyazhang changed the title Support large inputs for kernel coalesceValuesKernel on ROCM [ROCm] Support large inputs for coalesceValuesKernel Jul 14, 2025
@xinyazhang

Copy link
Copy Markdown
Collaborator Author

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased xinyazhang/swdev-523284 onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout xinyazhang/swdev-523284 && git pull --rebase)

@pytorchmergebot
pytorchmergebot force-pushed the xinyazhang/swdev-523284 branch from d78c5cb to 5196199 Compare July 16, 2025 16:21
@xinyazhang
xinyazhang force-pushed the xinyazhang/swdev-523284 branch from 5196199 to 19a12c7 Compare July 17, 2025 04:21
@jithunnair-amd jithunnair-amd added keep-going Don't stop on first failure, keep running tests until the end ci-no-td Do not run TD on this PR labels Jul 17, 2025
@xinyazhang

Copy link
Copy Markdown
Collaborator Author

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased xinyazhang/swdev-523284 onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout xinyazhang/swdev-523284 && git pull --rebase)

@pytorchmergebot
pytorchmergebot force-pushed the xinyazhang/swdev-523284 branch from dcb748d to 5fdec5a Compare July 28, 2025 16:39
@jithunnair-amd jithunnair-amd added ciflow/rocm ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 labels Jul 29, 2025
jithunnair-amd
jithunnair-amd previously approved these changes Jul 29, 2025
@xinyazhang
xinyazhang marked this pull request as ready for review July 29, 2025 14:35
jeffdaily
jeffdaily previously approved these changes Aug 12, 2025
@jithunnair-amd

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -f "unrelated CI failures"

@pytorch-bot pytorch-bot Bot removed the ciflow/trunk Trigger trunk jobs on your pull request label Aug 13, 2025
@jeffdaily jeffdaily added the ciflow/trunk Trigger trunk jobs on your pull request label Aug 13, 2025
@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorch-bot

pytorch-bot Bot commented Aug 14, 2025

Copy link
Copy Markdown

This PR needs to be approved by an authorized maintainer before merge.

chuanhaozhuge pushed a commit that referenced this pull request Aug 14, 2025
# Description

`.coalesce` cannot handle large inputs on ROCM due to maximal grid size limit.

This PR splits axis `X` into axes `X` and `Y`, and repurposes `Z` for original `Y` on ROCm to avoid such limitation.

Confirmed the new approach can handle large inputs. Correctness needs validation.

# Testing Command

`python torch_spmv.py 22500000 272500000`

## Script `torch_spmv.py`

``` python
import torch
import argparse

def parse_args():
    parser = argparse.ArgumentParser(
        description="Sparse COO Matrix by Dense Vector Multiplication using PyTorch"
    )
    parser.add_argument("n", type=int, help="Size of the NxN matrix")
    parser.add_argument("nnz", type=int, help="Number of non-zero entries")
    return parser.parse_args()

def main():
    args = parse_args()
    n = args.n
    nnz = args.nnz
    dtype = torch.float32
    device = torch.device('cuda')

    # Generate random indices for the sparse matrix in COO format.
    torch.manual_seed(42)
    rows = torch.randint(0, n, (nnz,), dtype=torch.int64, device=device)
    cols = torch.randint(0, n, (nnz,), dtype=torch.int64, device=device)
    indices = torch.stack([rows, cols], dim=0)

    # Generate random values.
    values = torch.randn(nnz, dtype=torch.float32, device=device)

    # Create the sparse COO matrix and move it to the target device.
    sparse_matrix = torch.sparse_coo_tensor(indices, values, size=(n, n), dtype=torch.float32, device=device)
    sparse_matrix = sparse_matrix.coalesce()

    # Generate a random dense vector.
    dense_vector = torch.randn(n, dtype=torch.float32, device=device)

    # Perform sparse matrix - dense vector multiplication.
    # Using torch.sparse.mm which expects a 2D tensor for the vector.
    result = torch.sparse.mm(sparse_matrix, dense_vector.unsqueeze(1)).squeeze()
    # result = torch.mv(sparse_matrix, dense_vector)

    # Print the result.
    print("Result of the multiplication:")
    print(torch.sum(result))

if __name__ == "__main__":
    main()
```

Pull Request resolved: #158281
Approved by: https://github.com/jithunnair-amd, https://github.com/jeffdaily
@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

chuanhaozhuge pushed a commit that referenced this pull request Aug 18, 2025
# Description

`.coalesce` cannot handle large inputs on ROCM due to maximal grid size limit.

This PR splits axis `X` into axes `X` and `Y`, and repurposes `Z` for original `Y` on ROCm to avoid such limitation.

Confirmed the new approach can handle large inputs. Correctness needs validation.

# Testing Command

`python torch_spmv.py 22500000 272500000`

## Script `torch_spmv.py`

``` python
import torch
import argparse

def parse_args():
    parser = argparse.ArgumentParser(
        description="Sparse COO Matrix by Dense Vector Multiplication using PyTorch"
    )
    parser.add_argument("n", type=int, help="Size of the NxN matrix")
    parser.add_argument("nnz", type=int, help="Number of non-zero entries")
    return parser.parse_args()

def main():
    args = parse_args()
    n = args.n
    nnz = args.nnz
    dtype = torch.float32
    device = torch.device('cuda')

    # Generate random indices for the sparse matrix in COO format.
    torch.manual_seed(42)
    rows = torch.randint(0, n, (nnz,), dtype=torch.int64, device=device)
    cols = torch.randint(0, n, (nnz,), dtype=torch.int64, device=device)
    indices = torch.stack([rows, cols], dim=0)

    # Generate random values.
    values = torch.randn(nnz, dtype=torch.float32, device=device)

    # Create the sparse COO matrix and move it to the target device.
    sparse_matrix = torch.sparse_coo_tensor(indices, values, size=(n, n), dtype=torch.float32, device=device)
    sparse_matrix = sparse_matrix.coalesce()

    # Generate a random dense vector.
    dense_vector = torch.randn(n, dtype=torch.float32, device=device)

    # Perform sparse matrix - dense vector multiplication.
    # Using torch.sparse.mm which expects a 2D tensor for the vector.
    result = torch.sparse.mm(sparse_matrix, dense_vector.unsqueeze(1)).squeeze()
    # result = torch.mv(sparse_matrix, dense_vector)

    # Print the result.
    print("Result of the multiplication:")
    print(torch.sum(result))

if __name__ == "__main__":
    main()
```

Pull Request resolved: #158281
Approved by: https://github.com/jithunnair-amd, https://github.com/jeffdaily
can-gaa-hou pushed a commit to can-gaa-hou/pytorch that referenced this pull request Aug 22, 2025
# Description

`.coalesce` cannot handle large inputs on ROCM due to maximal grid size limit.

This PR splits axis `X` into axes `X` and `Y`, and repurposes `Z` for original `Y` on ROCm to avoid such limitation.

Confirmed the new approach can handle large inputs. Correctness needs validation.

# Testing Command

`python torch_spmv.py 22500000 272500000`

## Script `torch_spmv.py`

``` python
import torch
import argparse

def parse_args():
    parser = argparse.ArgumentParser(
        description="Sparse COO Matrix by Dense Vector Multiplication using PyTorch"
    )
    parser.add_argument("n", type=int, help="Size of the NxN matrix")
    parser.add_argument("nnz", type=int, help="Number of non-zero entries")
    return parser.parse_args()

def main():
    args = parse_args()
    n = args.n
    nnz = args.nnz
    dtype = torch.float32
    device = torch.device('cuda')

    # Generate random indices for the sparse matrix in COO format.
    torch.manual_seed(42)
    rows = torch.randint(0, n, (nnz,), dtype=torch.int64, device=device)
    cols = torch.randint(0, n, (nnz,), dtype=torch.int64, device=device)
    indices = torch.stack([rows, cols], dim=0)

    # Generate random values.
    values = torch.randn(nnz, dtype=torch.float32, device=device)

    # Create the sparse COO matrix and move it to the target device.
    sparse_matrix = torch.sparse_coo_tensor(indices, values, size=(n, n), dtype=torch.float32, device=device)
    sparse_matrix = sparse_matrix.coalesce()

    # Generate a random dense vector.
    dense_vector = torch.randn(n, dtype=torch.float32, device=device)

    # Perform sparse matrix - dense vector multiplication.
    # Using torch.sparse.mm which expects a 2D tensor for the vector.
    result = torch.sparse.mm(sparse_matrix, dense_vector.unsqueeze(1)).squeeze()
    # result = torch.mv(sparse_matrix, dense_vector)

    # Print the result.
    print("Result of the multiplication:")
    print(torch.sum(result))

if __name__ == "__main__":
    main()
```

Pull Request resolved: pytorch#158281
Approved by: https://github.com/jithunnair-amd, https://github.com/jeffdaily
can-gaa-hou pushed a commit to can-gaa-hou/pytorch that referenced this pull request Aug 22, 2025
# Description

`.coalesce` cannot handle large inputs on ROCM due to maximal grid size limit.

This PR splits axis `X` into axes `X` and `Y`, and repurposes `Z` for original `Y` on ROCm to avoid such limitation.

Confirmed the new approach can handle large inputs. Correctness needs validation.

# Testing Command

`python torch_spmv.py 22500000 272500000`

## Script `torch_spmv.py`

``` python
import torch
import argparse

def parse_args():
    parser = argparse.ArgumentParser(
        description="Sparse COO Matrix by Dense Vector Multiplication using PyTorch"
    )
    parser.add_argument("n", type=int, help="Size of the NxN matrix")
    parser.add_argument("nnz", type=int, help="Number of non-zero entries")
    return parser.parse_args()

def main():
    args = parse_args()
    n = args.n
    nnz = args.nnz
    dtype = torch.float32
    device = torch.device('cuda')

    # Generate random indices for the sparse matrix in COO format.
    torch.manual_seed(42)
    rows = torch.randint(0, n, (nnz,), dtype=torch.int64, device=device)
    cols = torch.randint(0, n, (nnz,), dtype=torch.int64, device=device)
    indices = torch.stack([rows, cols], dim=0)

    # Generate random values.
    values = torch.randn(nnz, dtype=torch.float32, device=device)

    # Create the sparse COO matrix and move it to the target device.
    sparse_matrix = torch.sparse_coo_tensor(indices, values, size=(n, n), dtype=torch.float32, device=device)
    sparse_matrix = sparse_matrix.coalesce()

    # Generate a random dense vector.
    dense_vector = torch.randn(n, dtype=torch.float32, device=device)

    # Perform sparse matrix - dense vector multiplication.
    # Using torch.sparse.mm which expects a 2D tensor for the vector.
    result = torch.sparse.mm(sparse_matrix, dense_vector.unsqueeze(1)).squeeze()
    # result = torch.mv(sparse_matrix, dense_vector)

    # Print the result.
    print("Result of the multiplication:")
    print(torch.sum(result))

if __name__ == "__main__":
    main()
```

Pull Request resolved: pytorch#158281
Approved by: https://github.com/jeffdaily
markc-614 pushed a commit to markc-614/pytorch that referenced this pull request Sep 17, 2025
# Description

`.coalesce` cannot handle large inputs on ROCM due to maximal grid size limit.

This PR splits axis `X` into axes `X` and `Y`, and repurposes `Z` for original `Y` on ROCm to avoid such limitation.

Confirmed the new approach can handle large inputs. Correctness needs validation.

# Testing Command

`python torch_spmv.py 22500000 272500000`

## Script `torch_spmv.py`

``` python
import torch
import argparse

def parse_args():
    parser = argparse.ArgumentParser(
        description="Sparse COO Matrix by Dense Vector Multiplication using PyTorch"
    )
    parser.add_argument("n", type=int, help="Size of the NxN matrix")
    parser.add_argument("nnz", type=int, help="Number of non-zero entries")
    return parser.parse_args()

def main():
    args = parse_args()
    n = args.n
    nnz = args.nnz
    dtype = torch.float32
    device = torch.device('cuda')

    # Generate random indices for the sparse matrix in COO format.
    torch.manual_seed(42)
    rows = torch.randint(0, n, (nnz,), dtype=torch.int64, device=device)
    cols = torch.randint(0, n, (nnz,), dtype=torch.int64, device=device)
    indices = torch.stack([rows, cols], dim=0)

    # Generate random values.
    values = torch.randn(nnz, dtype=torch.float32, device=device)

    # Create the sparse COO matrix and move it to the target device.
    sparse_matrix = torch.sparse_coo_tensor(indices, values, size=(n, n), dtype=torch.float32, device=device)
    sparse_matrix = sparse_matrix.coalesce()

    # Generate a random dense vector.
    dense_vector = torch.randn(n, dtype=torch.float32, device=device)

    # Perform sparse matrix - dense vector multiplication.
    # Using torch.sparse.mm which expects a 2D tensor for the vector.
    result = torch.sparse.mm(sparse_matrix, dense_vector.unsqueeze(1)).squeeze()
    # result = torch.mv(sparse_matrix, dense_vector)

    # Print the result.
    print("Result of the multiplication:")
    print(torch.sum(result))

if __name__ == "__main__":
    main()
```

Pull Request resolved: pytorch#158281
Approved by: https://github.com/jithunnair-amd, https://github.com/jeffdaily
markc-614 pushed a commit to markc-614/pytorch that referenced this pull request Sep 17, 2025
# Description

`.coalesce` cannot handle large inputs on ROCM due to maximal grid size limit.

This PR splits axis `X` into axes `X` and `Y`, and repurposes `Z` for original `Y` on ROCm to avoid such limitation.

Confirmed the new approach can handle large inputs. Correctness needs validation.

# Testing Command

`python torch_spmv.py 22500000 272500000`

## Script `torch_spmv.py`

``` python
import torch
import argparse

def parse_args():
    parser = argparse.ArgumentParser(
        description="Sparse COO Matrix by Dense Vector Multiplication using PyTorch"
    )
    parser.add_argument("n", type=int, help="Size of the NxN matrix")
    parser.add_argument("nnz", type=int, help="Number of non-zero entries")
    return parser.parse_args()

def main():
    args = parse_args()
    n = args.n
    nnz = args.nnz
    dtype = torch.float32
    device = torch.device('cuda')

    # Generate random indices for the sparse matrix in COO format.
    torch.manual_seed(42)
    rows = torch.randint(0, n, (nnz,), dtype=torch.int64, device=device)
    cols = torch.randint(0, n, (nnz,), dtype=torch.int64, device=device)
    indices = torch.stack([rows, cols], dim=0)

    # Generate random values.
    values = torch.randn(nnz, dtype=torch.float32, device=device)

    # Create the sparse COO matrix and move it to the target device.
    sparse_matrix = torch.sparse_coo_tensor(indices, values, size=(n, n), dtype=torch.float32, device=device)
    sparse_matrix = sparse_matrix.coalesce()

    # Generate a random dense vector.
    dense_vector = torch.randn(n, dtype=torch.float32, device=device)

    # Perform sparse matrix - dense vector multiplication.
    # Using torch.sparse.mm which expects a 2D tensor for the vector.
    result = torch.sparse.mm(sparse_matrix, dense_vector.unsqueeze(1)).squeeze()
    # result = torch.mv(sparse_matrix, dense_vector)

    # Print the result.
    print("Result of the multiplication:")
    print(torch.sum(result))

if __name__ == "__main__":
    main()
```

Pull Request resolved: pytorch#158281
Approved by: https://github.com/jeffdaily
@doplxyz

doplxyz commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

On gfx1201 this can leave part of newValues unwritten in coalesce_sparse_cuda

This PR moved the feature axis from blockIdx.y to blockIdx.z, but the multiplier did not
follow. Measured on an RX 9070 XT (gfx1201, wave32); the same code is still on main
(b1716d913ad13513f6184bad3d025a5b259329f3, fetched 2026-08-25) and in both
2.9.1+rocm7.2.4.git39497456 and 2.12.0+rocm7.14.0.

The mismatch

The host builds blockIdx.z as an index over feature tiles of width warp_size * SZ
(SparseCUDATensor.cu:112, :116):

dim3 grid(s_batch, (s_batch==1) ? nsegments : BATCHING_SEGMENT,
          ceil_div(stride, (int64_t) warp_size*SZ));
dim3 block(warp_size, SZ);

The kernel multiplies blockIdx.z by nsegments * SZ instead
(SparseCUDAApplyUtils.cuh:211, and the bool overload at :273):

#ifdef USE_ROCM
    const int startFeature = threadIdx.x + blockIdx.z * nsegments * SZ;
#else
    const int startFeature = threadIdx.x + blockIdx.y * blockDim.x * SZ;
#endif

nsegments = ceil_div(newNnz, SZ) counts 4-row segments of the output; it is unrelated to the
feature-tile width. So each z-block covers [z*nsegments*SZ, z*nsegments*SZ + warp_size*SZ)
instead of [z*warp_size*SZ, (z+1)*warp_size*SZ). Columns outside the union of those intervals
are never written, and newValues is at::empty (SparseCUDATensor.cu:100).

Firing condition (both parts required):
gridDim.z > 1, i.e. stride > warp_size*SZ (128 on wave32) — and nsegments != warp_size.
When nsegments == warp_size the two expressions coincide and the result is correct. On wave32
that is newNnz ∈ [125,128]; I measured that band explicitly at D=256, gridDim.z=2:

newNnz 120 124 125 126 127 128 129 132 160
nsegments 30 31 32 32 32 32 33 33 40
columns showing the poison value 8 4 0 0 0 0 4 4 32

How this was measured (indirect — please read this before the numbers)

I cannot observe writes directly from Python. Instead I filled a same-shaped block with a poison
value and freed it immediately before coalesce(), so the caching allocator is likely to hand
that block back for newValues; columns still holding the poison afterwards were not written.
This visualises unwritten regions only when the poisoned block is actually reused — where it
is not, the method shows nothing, which is not evidence that the region was written.

Inputs are torch.sparse_coo_tensor(unique_rows, ones, ...) followed by .coalesce() — no
nn.Embedding involved, rows are unique so nnz == newNnz, and every correct output value is
exactly 1.0.

Across 33 configurations (a 5×6 grid of D × nnz in fp32, plus fp16/bf16/fp64 at
D=256, nnz=64), the set of poison-showing columns matched the set predicted by the interval
model above in 31 of them, on each of the two stacks independently.
Counts:

D \ nnz 4 16 64 128 512 4096
128 0 0 0 0 0 0
256 124 112 64 [192,255] 0 128 128
512 372 336 192 [320,511] 0 384 384
1024 868 784 448 0 768 896
2048 1860 1680 960 0 1536 1920

The nnz=128 column is clean at every D for the nsegments == warp_size reason above.
The 2 non-matching configurations are fp16 and bf16 at D=256, nnz=64, where the poison did not
come back — i.e. inconclusive by this method, not clean. Without poisoning, those same two
configurations produced wrong values in exactly the predicted 64 columns, so within the dtypes
I tested (fp16, bf16, fp32, fp64) I saw no dtype that avoided it. I did not test all dtypes.

Observability depends on allocator state. Without poisoning, one failing configuration
repeated 10 times alternated between 64 and 0 wrong columns. I did not inspect allocator
bookkeeping, so I can only say the recycled block sometimes already contained the expected value;
a 0 there means "no wrong value observed", not "written". With poisoning the same case was
64/64/…, 10 out of 10.

Reached through autograd, the effect is silent: with nn.Embedding(N, D, sparse=True), the
uncoalesced gradient returned by backward() is correct (values all exactly 1.0, checked at
D = 64/256/512), and the wrong values appear only after an explicit .coalesce(). At D=256
they came back as ordinary-looking floats rather than anything obviously invalid — in one run
(D=256, 64 unique rows, fp32, on the 2.9.1+rocm7.2.4 image) the wrong columns ranged over
roughly −3.84 … 3.90. I did not determine what previously occupied that memory, and this range is
just what that one run happened to contain.

Suggested fix

-    const int startFeature = threadIdx.x + blockIdx.z * nsegments * SZ;
+    const int startFeature = threadIdx.x + blockIdx.z * blockDim.x * SZ;

in both overloads, matching the non-ROCm expression. In the current file nsegments appears only
as the kernel parameter (:193, :255) and in these two lines, so it would become unused there
— whether to remove the parameter is your call.

I checked this at the index-arithmetic level, not in-tree: a standalone HIP program using the same
grid/block construction, built with hipcc --offload-arch=gfx1201, counting writes per feature
column with plain hipMalloc/hipMemset (no PyTorch allocator involved). Both overloads contain
the identical expression, so I compiled the arithmetic once. Over 30 configurations:

configs with unwritten columns with duplicate writes
current expression 20 / 30 12 / 30
with the change above 0 / 30 0 / 30

Those 20 are exactly the configurations the firing condition predicts — D > 128 with
nsegments != warp_size, i.e. every cell of the grid except the six at D=128 and the four at
nnz=128 — and they are the same 20 non-zero cells as the poison table above. The per-column
counts agree too (e.g. D=256, nnz=64 → 64 columns starting at 192; D=512, nnz=64 → 192
starting at 320). Duplicate writes occurred only in configurations that also had unwritten
columns, never on their own.

Two limits worth stating plainly: I have not built PyTorch in-tree with this change, so the
patch is unverified in the real kernel — only the arithmetic is. And everything measured here is
gfx1201 (wave32) only; I have no CDNA hardware, so I am making no claim about behaviour or
thresholds there — the warp_size in these expressions is simply where I would look next.

Found while investigating #193704, which turned out to be a different problem: its repro uses
D=64, where gridDim.z == 1 and this term is multiplied by zero.

pytorchmergebot pushed a commit that referenced this pull request Oct 2, 2026
## Issue being fixed

Fixes #199483

## BC-breaking?

No

## Summary (human written only)

This PR fixes the ROCm path of `coalesceValuesKernel` described in #199483. In #158281, feature tile offset relied on `nsegments` instead of blockDim.x, so dense sizes wider than 256 (on CDNA) were never written. This  PR restores the same offset logic as in CUDA, cleans-up unused arguments and adds regression test.

## Agent details (if applicable)

> Prepared with Claude Code (AI assistant) and reviewed by me:
>
> Restores the ROCm tile offset to blockIdx.z * blockDim.x * SZ, matching the CUDA branch, in both coalesceValuesKernel overloads. Drops the now unused nsegments kernel argument and merges the ROCm and CUDA dispatch blocks, which became identical. The grid split for large inputs from #158281 is unchanged. Adds test_coalesce_wide_dense_dims to test/test_sparse.py, which compares accelerator and CPU coalesce for dense sizes spanning several tiles. On gfx950 it fails on nightly 2.15.0.dev20260930 and passes with this change. A 1794 case fuzz against CPU coalesce (11 dtypes, nnz up to 70000 including the batched grid path) also passes. Lint: lintrunner reports no issues on the changed files.

Pull Request resolved: #199484
Approved by: https://github.com/jeffdaily
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
## Issue being fixed

Fixes pytorch#199483

## BC-breaking?

No

## Summary (human written only)

This PR fixes the ROCm path of `coalesceValuesKernel` described in pytorch#199483. In pytorch#158281, feature tile offset relied on `nsegments` instead of blockDim.x, so dense sizes wider than 256 (on CDNA) were never written. This  PR restores the same offset logic as in CUDA, cleans-up unused arguments and adds regression test.

## Agent details (if applicable)

> Prepared with Claude Code (AI assistant) and reviewed by me:
>
> Restores the ROCm tile offset to blockIdx.z * blockDim.x * SZ, matching the CUDA branch, in both coalesceValuesKernel overloads. Drops the now unused nsegments kernel argument and merges the ROCm and CUDA dispatch blocks, which became identical. The grid split for large inputs from pytorch#158281 is unchanged. Adds test_coalesce_wide_dense_dims to test/test_sparse.py, which compares accelerator and CPU coalesce for dense sizes spanning several tiles. On gfx950 it fails on nightly 2.15.0.dev20260930 and passes with this change. A 1794 case fuzz against CPU coalesce (11 dtypes, nnz up to 70000 including the batched grid path) also passes. Lint: lintrunner reports no issues on the changed files.

Pull Request resolved: pytorch#199484
Approved by: https://github.com/jeffdaily
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-no-td Do not run TD on this PR ciflow/trunk Trigger trunk jobs on your pull request keep-going Don't stop on first failure, keep running tests until the end Merged module: rocm AMD GPU support for Pytorch open source release notes: sparse release notes category Reverted triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants