Skip to content

Replace MPSGraph count_nonzero with custom Metal kernel - #180725

Closed
malfet wants to merge 8 commits into
gh/malfet/841/basefrom
gh/malfet/841/head
Closed

malfet wants to merge 8 commits into
gh/malfet/841/basefrom
gh/malfet/841/head

Conversation

@malfet

@malfet malfet commented Apr 18, 2026 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

Migrate count_nonzero to native Metal by extending the existing sum reduction kernels with a third LoadMode variant that counts nonzero elements.

Refactor the NAN_TO_ZERO bool template parameter in ReduceOps.metal to a LoadMode enum with three values: LOAD_IDENTITY (sum), LOAD_NAN_TO_ZERO (nansum), and LOAD_NONZERO (count_nonzero — contributes 1 per nonzero, 0 otherwise). The sum_reduction, sum_reduction_outer, and sum_reduction_inner templates all share the same load dispatch; the compiler eliminates dead branches per instantiation. Even though output is 64-bit integer, accumulates partial counts in uint32 rather than long as tensor dimension is always less that in32 on Metal.

Register count_nonzero_{,_outer,inner}long kernels for all supported input dtypes (float/half/bfloat/{int,long,short,char,uchar}/bool/float2/half2). Host-side count_nonzero_mps now builds a TensorIterator via make_reduction and dispatches to sum_nansum_kernel_mps with prefix "count_nonzero"

Remove MPSReductionType::COUNT_NONZERO and its MPSGraph branch.

Tweaked the two-pass full-reduction path to always dispatch pass 2 with LOAD_IDENTITY (plain sum), regardless of pass-1 mode: pass 1 has already applied the load-mode transform (NaN-to-zero, nonzero-as-one), so pass 2 only needs to combine the partials.

Benchmark vs torch 2.11 MPSGraph (median us, M4 Max):

shape op dtype 2.11 new speedup
(10000,) full float32 14.0 8.1 1.73x
(1000000,) full float32 14.2 10.8 1.31x
(1024,1024) full float32 16.4 11.6 1.41x
(1024,1024) dim=0 float32 13.0 6.0 2.18x
(1024,1024) dim=1 float32 12.9 4.9 2.62x
(4096,4096) full float32 131.2 121.9 1.08x
(4096,4096) dim=0 float32 132.4 127.1 1.04x
(1024,1024) full int64 15.5 12.8 1.21x
(1024,1024) dim=0 int64 12.9 7.6 1.70x
(1024,1024) dim=0 float16 14.7 4.7 3.13x
(1024,1024) full bool 15.1 11.2 1.34x
(1024,1024) dim=0 bool 13.2 4.8 2.76x
(4096,4096) dim=0 bool 48.8 26.2 1.86x

Dim reductions see parity or 1.7–3x speedups across dtypes.

Benchmark script
import torch
import torch.utils.benchmark as benchmark
import itertools

shapes_and_dims = [
    ((10_000,), None),
    ((1_000_000,), None),
    ((1024, 1024), None),
    ((1024, 1024), 0),
    ((1024, 1024), 1),
    ((4096, 4096), None),
    ((4096, 4096), 0),
    ((4096, 4096), 1),
]
sparsities = [0.2, 0.5, 0.8]

def make_input(shape, sparsity, dtype, device):
    if dtype == torch.bool:
        return torch.rand(shape, device=device) < sparsity
    x = torch.randn(shape, device=device, dtype=dtype)
    mask = torch.rand(shape, device=device) >= sparsity
    x[mask] = 0
    return x

def bench(x, dim):
    stmt = "torch.count_nonzero(x)" if dim is None else "torch.count_nonzero(x, dim=d)"
    t = benchmark.Timer(stmt=stmt, globals={"torch": torch, "x": x, "d": dim}, num_threads=1)
    for _ in range(2):
        result = t.timeit(500)
    return result.median

for (shape, dim), sparsity in itertools.product(shapes_and_dims, sparsities):
    x = make_input(shape, sparsity, torch.float32, "mps")
    m = bench(x, dim) * 1e6
    print(f"{str(shape):>14} {str(dim):>5} {sparsity:>5.2f} {m:>12.2f}")

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Apr 18, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 3215f3e with merge base b4a129a (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 ciflow/mps Run MPS tests (subset of trunk) release notes: mps Release notes category labels Apr 18, 2026
malfet added a commit that referenced this pull request Apr 18, 2026
Migrate count_nonzero to native Metal by extending the existing sum reduction kernels with a third LoadMode variant that counts nonzero elements.

Refactor the NAN_TO_ZERO bool template parameter in ReduceOps.metal to a LoadMode enum with three values: LOAD_IDENTITY (sum), LOAD_NAN_TO_ZERO (nansum), and LOAD_NONZERO (count_nonzero — contributes 1 per nonzero, 0 otherwise). The sum_reduction, sum_reduction_outer, and sum_reduction_inner templates all share the same load dispatch; the compiler eliminates dead branches per instantiation.

Register count_nonzero_{,_outer,_inner}_<TI>_long kernels for all supported input dtypes (float/half/bfloat/{int,long,short,char,uchar}/bool/float2/half2). Host-side count_nonzero_mps now builds a TensorIterator via make_reduction and dispatches to sum_nansum_kernel_mps with prefix "count_nonzero_"; remove MPSReductionType::COUNT_NONZERO and its MPSGraph branch.

Fix the two-pass full-reduction path: pass 2 combines partial counts by summing them, so it must use the "sum_" prefix even when pass 1 used "nansum_" or "count_nonzero_" (otherwise we'd re-count already-counted partials).

Benchmark vs torch 2.11 MPSGraph (median us, M5 Pro):

| shape       | op    | dtype   | 2.11 | new  | speedup |
|-------------|-------|---------|------|------|---------|
| (10000,)    | full  | float32 | 14.0 | 10.2 | 1.37x   |
| (1000000,)  | full  | float32 | 14.2 | 16.4 | 0.87x   |
| (1024,1024) | full  | float32 | 16.4 | 13.2 | 1.24x   |
| (1024,1024) | dim=0 | float32 | 13.0 |  6.0 | 2.18x   |
| (1024,1024) | dim=1 | float32 | 12.9 |  5.1 | 2.55x   |
| (4096,4096) | full  | float32 |131.2 |121.9 | 1.08x   |
| (4096,4096) | dim=0 | float32 |132.4 |127.1 | 1.04x   |
| (1024,1024) | full  | int64   | 29.8 | 13.1 | 2.28x   |
| (1024,1024) | dim=0 | int64   | 23.4 |  7.4 | 3.16x   |
| (1024,1024) | dim=0 | float16 | 22.3 |  5.1 | 4.37x   |
| (1024,1024) | full  | bool    | 30.4 | 37.7 | 0.81x   |
| (1024,1024) | dim=0 | bool    | 14.2 |  6.8 | 2.09x   |
| (4096,4096) | dim=0 | bool    | 48.9 | 29.1 | 1.68x   |

Dim reductions see 2–4x speedups across dtypes. Full reductions are comparable or faster in most cases; two minor regressions remain on small-data paths where fixed two-pass overhead dominates (1M fp32 full, 1024² bool full).

<details>
<summary>Benchmark script</summary>

```python
import torch
import torch.utils.benchmark as benchmark
import itertools

shapes_and_dims = [
    ((10_000,), None),
    ((1_000_000,), None),
    ((1024, 1024), None),
    ((1024, 1024), 0),
    ((1024, 1024), 1),
    ((4096, 4096), None),
    ((4096, 4096), 0),
    ((4096, 4096), 1),
]
sparsities = [0.2, 0.5, 0.8]

def make_input(shape, sparsity, dtype, device):
    if dtype == torch.bool:
        return torch.rand(shape, device=device) < sparsity
    x = torch.randn(shape, device=device, dtype=dtype)
    mask = torch.rand(shape, device=device) >= sparsity
    x[mask] = 0
    return x

def bench(x, dim):
    stmt = "torch.count_nonzero(x)" if dim is None else "torch.count_nonzero(x, dim=d)"
    t = benchmark.Timer(stmt=stmt, globals={"torch": torch, "x": x, "d": dim}, num_threads=1)
    for _ in range(2):
        result = t.timeit(500)
    return result.median

for (shape, dim), sparsity in itertools.product(shapes_and_dims, sparsities):
    x = make_input(shape, sparsity, torch.float32, "mps")
    m = bench(x, dim) * 1e6
    print(f"{str(shape):>14} {str(dim):>5} {sparsity:>5.2f} {m:>12.2f}")
```
</details>


ghstack-source-id: 182ab23
Pull-Request: #180725
@hvaara

hvaara commented Apr 18, 2026

Copy link
Copy Markdown
Contributor

This PR partially fixes #178497

[ghstack-poisoned]
malfet added a commit that referenced this pull request Apr 18, 2026
Migrate count_nonzero to native Metal by extending the existing sum reduction kernels with a third LoadMode variant that counts nonzero elements.

Refactor the NAN_TO_ZERO bool template parameter in ReduceOps.metal to a LoadMode enum with three values: LOAD_IDENTITY (sum), LOAD_NAN_TO_ZERO (nansum), and LOAD_NONZERO (count_nonzero — contributes 1 per nonzero, 0 otherwise). The sum_reduction, sum_reduction_outer, and sum_reduction_inner templates all share the same load dispatch; the compiler eliminates dead branches per instantiation.

Register count_nonzero_{,_outer,_inner}_<TI>_long kernels for all supported input dtypes (float/half/bfloat/{int,long,short,char,uchar}/bool/float2/half2). Host-side count_nonzero_mps now builds a TensorIterator via make_reduction and dispatches to sum_nansum_kernel_mps with prefix "count_nonzero_"; remove MPSReductionType::COUNT_NONZERO and its MPSGraph branch.

Fix the two-pass full-reduction path: pass 2 combines partial counts by summing them, so it must use the "sum_" prefix even when pass 1 used "nansum_" or "count_nonzero_" (otherwise we'd re-count already-counted partials).

Benchmark vs torch 2.11 MPSGraph (median us, M5 Pro):

| shape       | op    | dtype   | 2.11 | new  | speedup |
|-------------|-------|---------|------|------|---------|
| (10000,)    | full  | float32 | 14.0 | 10.2 | 1.37x   |
| (1000000,)  | full  | float32 | 14.2 | 16.4 | 0.87x   |
| (1024,1024) | full  | float32 | 16.4 | 13.2 | 1.24x   |
| (1024,1024) | dim=0 | float32 | 13.0 |  6.0 | 2.18x   |
| (1024,1024) | dim=1 | float32 | 12.9 |  5.1 | 2.55x   |
| (4096,4096) | full  | float32 |131.2 |121.9 | 1.08x   |
| (4096,4096) | dim=0 | float32 |132.4 |127.1 | 1.04x   |
| (1024,1024) | full  | int64   | 29.8 | 13.1 | 2.28x   |
| (1024,1024) | dim=0 | int64   | 23.4 |  7.4 | 3.16x   |
| (1024,1024) | dim=0 | float16 | 22.3 |  5.1 | 4.37x   |
| (1024,1024) | full  | bool    | 30.4 | 37.7 | 0.81x   |
| (1024,1024) | dim=0 | bool    | 14.2 |  6.8 | 2.09x   |
| (4096,4096) | dim=0 | bool    | 48.9 | 29.1 | 1.68x   |

Dim reductions see 2–4x speedups across dtypes. Full reductions are comparable or faster in most cases; two minor regressions remain on small-data paths where fixed two-pass overhead dominates (1M fp32 full, 1024² bool full).

<details>
<summary>Benchmark script</summary>

```python
import torch
import torch.utils.benchmark as benchmark
import itertools

shapes_and_dims = [
    ((10_000,), None),
    ((1_000_000,), None),
    ((1024, 1024), None),
    ((1024, 1024), 0),
    ((1024, 1024), 1),
    ((4096, 4096), None),
    ((4096, 4096), 0),
    ((4096, 4096), 1),
]
sparsities = [0.2, 0.5, 0.8]

def make_input(shape, sparsity, dtype, device):
    if dtype == torch.bool:
        return torch.rand(shape, device=device) < sparsity
    x = torch.randn(shape, device=device, dtype=dtype)
    mask = torch.rand(shape, device=device) >= sparsity
    x[mask] = 0
    return x

def bench(x, dim):
    stmt = "torch.count_nonzero(x)" if dim is None else "torch.count_nonzero(x, dim=d)"
    t = benchmark.Timer(stmt=stmt, globals={"torch": torch, "x": x, "d": dim}, num_threads=1)
    for _ in range(2):
        result = t.timeit(500)
    return result.median

for (shape, dim), sparsity in itertools.product(shapes_and_dims, sparsities):
    x = make_input(shape, sparsity, torch.float32, "mps")
    m = bench(x, dim) * 1e6
    print(f"{str(shape):>14} {str(dim):>5} {sparsity:>5.2f} {m:>12.2f}")
```
</details>

ghstack-source-id: bfa5b4d
Pull-Request: #180725
[ghstack-poisoned]
malfet added a commit that referenced this pull request Apr 18, 2026
Migrate count_nonzero to native Metal by extending the existing sum reduction kernels with a third LoadMode variant that counts nonzero elements.

Refactor the NAN_TO_ZERO bool template parameter in ReduceOps.metal to a LoadMode enum with three values: LOAD_IDENTITY (sum), LOAD_NAN_TO_ZERO (nansum), and LOAD_NONZERO (count_nonzero — contributes 1 per nonzero, 0 otherwise). The sum_reduction, sum_reduction_outer, and sum_reduction_inner templates all share the same load dispatch; the compiler eliminates dead branches per instantiation.

Register count_nonzero_{,_outer,_inner}_<TI>_long kernels for all supported input dtypes (float/half/bfloat/{int,long,short,char,uchar}/bool/float2/half2). Host-side count_nonzero_mps now builds a TensorIterator via make_reduction and dispatches to sum_nansum_kernel_mps with prefix "count_nonzero_"; remove MPSReductionType::COUNT_NONZERO and its MPSGraph branch.

Fix the two-pass full-reduction path: pass 2 combines partial counts by summing them, so it must use the "sum_" prefix even when pass 1 used "nansum_" or "count_nonzero_" (otherwise we'd re-count already-counted partials).

Benchmark vs torch 2.11 MPSGraph (median us, M5 Pro):

| shape       | op    | dtype   | 2.11 | new  | speedup |
|-------------|-------|---------|------|------|---------|
| (10000,)    | full  | float32 | 14.0 | 10.2 | 1.37x   |
| (1000000,)  | full  | float32 | 14.2 | 16.4 | 0.87x   |
| (1024,1024) | full  | float32 | 16.4 | 13.2 | 1.24x   |
| (1024,1024) | dim=0 | float32 | 13.0 |  6.0 | 2.18x   |
| (1024,1024) | dim=1 | float32 | 12.9 |  5.1 | 2.55x   |
| (4096,4096) | full  | float32 |131.2 |121.9 | 1.08x   |
| (4096,4096) | dim=0 | float32 |132.4 |127.1 | 1.04x   |
| (1024,1024) | full  | int64   | 29.8 | 13.1 | 2.28x   |
| (1024,1024) | dim=0 | int64   | 23.4 |  7.4 | 3.16x   |
| (1024,1024) | dim=0 | float16 | 22.3 |  5.1 | 4.37x   |
| (1024,1024) | full  | bool    | 30.4 | 37.7 | 0.81x   |
| (1024,1024) | dim=0 | bool    | 14.2 |  6.8 | 2.09x   |
| (4096,4096) | dim=0 | bool    | 48.9 | 29.1 | 1.68x   |

Dim reductions see 2–4x speedups across dtypes. Full reductions are comparable or faster in most cases; two minor regressions remain on small-data paths where fixed two-pass overhead dominates (1M fp32 full, 1024² bool full).

<details>
<summary>Benchmark script</summary>

```python
import torch
import torch.utils.benchmark as benchmark
import itertools

shapes_and_dims = [
    ((10_000,), None),
    ((1_000_000,), None),
    ((1024, 1024), None),
    ((1024, 1024), 0),
    ((1024, 1024), 1),
    ((4096, 4096), None),
    ((4096, 4096), 0),
    ((4096, 4096), 1),
]
sparsities = [0.2, 0.5, 0.8]

def make_input(shape, sparsity, dtype, device):
    if dtype == torch.bool:
        return torch.rand(shape, device=device) < sparsity
    x = torch.randn(shape, device=device, dtype=dtype)
    mask = torch.rand(shape, device=device) >= sparsity
    x[mask] = 0
    return x

def bench(x, dim):
    stmt = "torch.count_nonzero(x)" if dim is None else "torch.count_nonzero(x, dim=d)"
    t = benchmark.Timer(stmt=stmt, globals={"torch": torch, "x": x, "d": dim}, num_threads=1)
    for _ in range(2):
        result = t.timeit(500)
    return result.median

for (shape, dim), sparsity in itertools.product(shapes_and_dims, sparsities):
    x = make_input(shape, sparsity, torch.float32, "mps")
    m = bench(x, dim) * 1e6
    print(f"{str(shape):>14} {str(dim):>5} {sparsity:>5.2f} {m:>12.2f}")
```
</details>

ghstack-source-id: 076883a
Pull-Request: #180725
[ghstack-poisoned]
malfet added a commit that referenced this pull request Apr 18, 2026
Migrate count_nonzero to native Metal by extending the existing sum reduction kernels with a third LoadMode variant that counts nonzero elements.

Refactor the NAN_TO_ZERO bool template parameter in ReduceOps.metal to a LoadMode enum with three values: LOAD_IDENTITY (sum), LOAD_NAN_TO_ZERO (nansum), and LOAD_NONZERO (count_nonzero — contributes 1 per nonzero, 0 otherwise). The sum_reduction, sum_reduction_outer, and sum_reduction_inner templates all share the same load dispatch; the compiler eliminates dead branches per instantiation.

Register count_nonzero_{,_outer,_inner}_<TI>_long kernels for all supported input dtypes (float/half/bfloat/{int,long,short,char,uchar}/bool/float2/half2). Host-side count_nonzero_mps now builds a TensorIterator via make_reduction and dispatches to sum_nansum_kernel_mps with prefix "count_nonzero_"; remove MPSReductionType::COUNT_NONZERO and its MPSGraph branch.

Fix the two-pass full-reduction path: pass 2 combines partial counts by summing them, so it must use the "sum_" prefix even when pass 1 used "nansum_" or "count_nonzero_" (otherwise we'd re-count already-counted partials).

Benchmark vs torch 2.11 MPSGraph (median us, M5 Pro):

| shape       | op    | dtype   | 2.11 | new  | speedup |
|-------------|-------|---------|------|------|---------|
| (10000,)    | full  | float32 | 14.0 | 10.2 | 1.37x   |
| (1000000,)  | full  | float32 | 14.2 | 16.4 | 0.87x   |
| (1024,1024) | full  | float32 | 16.4 | 13.2 | 1.24x   |
| (1024,1024) | dim=0 | float32 | 13.0 |  6.0 | 2.18x   |
| (1024,1024) | dim=1 | float32 | 12.9 |  5.1 | 2.55x   |
| (4096,4096) | full  | float32 |131.2 |121.9 | 1.08x   |
| (4096,4096) | dim=0 | float32 |132.4 |127.1 | 1.04x   |
| (1024,1024) | full  | int64   | 29.8 | 13.1 | 2.28x   |
| (1024,1024) | dim=0 | int64   | 23.4 |  7.4 | 3.16x   |
| (1024,1024) | dim=0 | float16 | 22.3 |  5.1 | 4.37x   |
| (1024,1024) | full  | bool    | 30.4 | 37.7 | 0.81x   |
| (1024,1024) | dim=0 | bool    | 14.2 |  6.8 | 2.09x   |
| (4096,4096) | dim=0 | bool    | 48.9 | 29.1 | 1.68x   |

Dim reductions see 2–4x speedups across dtypes. Full reductions are comparable or faster in most cases; two minor regressions remain on small-data paths where fixed two-pass overhead dominates (1M fp32 full, 1024² bool full).

<details>
<summary>Benchmark script</summary>

```python
import torch
import torch.utils.benchmark as benchmark
import itertools

shapes_and_dims = [
    ((10_000,), None),
    ((1_000_000,), None),
    ((1024, 1024), None),
    ((1024, 1024), 0),
    ((1024, 1024), 1),
    ((4096, 4096), None),
    ((4096, 4096), 0),
    ((4096, 4096), 1),
]
sparsities = [0.2, 0.5, 0.8]

def make_input(shape, sparsity, dtype, device):
    if dtype == torch.bool:
        return torch.rand(shape, device=device) < sparsity
    x = torch.randn(shape, device=device, dtype=dtype)
    mask = torch.rand(shape, device=device) >= sparsity
    x[mask] = 0
    return x

def bench(x, dim):
    stmt = "torch.count_nonzero(x)" if dim is None else "torch.count_nonzero(x, dim=d)"
    t = benchmark.Timer(stmt=stmt, globals={"torch": torch, "x": x, "d": dim}, num_threads=1)
    for _ in range(2):
        result = t.timeit(500)
    return result.median

for (shape, dim), sparsity in itertools.product(shapes_and_dims, sparsities):
    x = make_input(shape, sparsity, torch.float32, "mps")
    m = bench(x, dim) * 1e6
    print(f"{str(shape):>14} {str(dim):>5} {sparsity:>5.2f} {m:>12.2f}")
```
</details>

ghstack-source-id: 2cc2334
Pull-Request: #180725
[ghstack-poisoned]
[ghstack-poisoned]
malfet added a commit that referenced this pull request Apr 19, 2026
Migrate count_nonzero to native Metal by extending the existing sum reduction kernels with a third LoadMode variant that counts nonzero elements.

Refactor the NAN_TO_ZERO bool template parameter in ReduceOps.metal to a LoadMode enum with three values: LOAD_IDENTITY (sum), LOAD_NAN_TO_ZERO (nansum), and LOAD_NONZERO (count_nonzero — contributes 1 per nonzero, 0 otherwise). The sum_reduction, sum_reduction_outer, and sum_reduction_inner templates all share the same load dispatch; the compiler eliminates dead branches per instantiation.

Register count_nonzero_{,_outer,_inner}_<TI>_long kernels for all supported input dtypes (float/half/bfloat/{int,long,short,char,uchar}/bool/float2/half2). Host-side count_nonzero_mps now builds a TensorIterator via make_reduction and dispatches to sum_nansum_kernel_mps with prefix "count_nonzero_"; remove MPSReductionType::COUNT_NONZERO and its MPSGraph branch.

Fix the two-pass full-reduction path: pass 2 combines partial counts by summing them, so it must use the "sum_" prefix even when pass 1 used "nansum_" or "count_nonzero_" (otherwise we'd re-count already-counted partials).

Benchmark vs torch 2.11 MPSGraph (median us, M5 Pro):

| shape       | op    | dtype   | 2.11 | new  | speedup |
|-------------|-------|---------|------|------|---------|
| (10000,)    | full  | float32 | 14.0 | 10.2 | 1.37x   |
| (1000000,)  | full  | float32 | 14.2 | 16.4 | 0.87x   |
| (1024,1024) | full  | float32 | 16.4 | 13.2 | 1.24x   |
| (1024,1024) | dim=0 | float32 | 13.0 |  6.0 | 2.18x   |
| (1024,1024) | dim=1 | float32 | 12.9 |  5.1 | 2.55x   |
| (4096,4096) | full  | float32 |131.2 |121.9 | 1.08x   |
| (4096,4096) | dim=0 | float32 |132.4 |127.1 | 1.04x   |
| (1024,1024) | full  | int64   | 29.8 | 13.1 | 2.28x   |
| (1024,1024) | dim=0 | int64   | 23.4 |  7.4 | 3.16x   |
| (1024,1024) | dim=0 | float16 | 22.3 |  5.1 | 4.37x   |
| (1024,1024) | full  | bool    | 30.4 | 37.7 | 0.81x   |
| (1024,1024) | dim=0 | bool    | 14.2 |  6.8 | 2.09x   |
| (4096,4096) | dim=0 | bool    | 48.9 | 29.1 | 1.68x   |

Dim reductions see 2–4x speedups across dtypes. Full reductions are comparable or faster in most cases; two minor regressions remain on small-data paths where fixed two-pass overhead dominates (1M fp32 full, 1024² bool full).

<details>
<summary>Benchmark script</summary>

```python
import torch
import torch.utils.benchmark as benchmark
import itertools

shapes_and_dims = [
    ((10_000,), None),
    ((1_000_000,), None),
    ((1024, 1024), None),
    ((1024, 1024), 0),
    ((1024, 1024), 1),
    ((4096, 4096), None),
    ((4096, 4096), 0),
    ((4096, 4096), 1),
]
sparsities = [0.2, 0.5, 0.8]

def make_input(shape, sparsity, dtype, device):
    if dtype == torch.bool:
        return torch.rand(shape, device=device) < sparsity
    x = torch.randn(shape, device=device, dtype=dtype)
    mask = torch.rand(shape, device=device) >= sparsity
    x[mask] = 0
    return x

def bench(x, dim):
    stmt = "torch.count_nonzero(x)" if dim is None else "torch.count_nonzero(x, dim=d)"
    t = benchmark.Timer(stmt=stmt, globals={"torch": torch, "x": x, "d": dim}, num_threads=1)
    for _ in range(2):
        result = t.timeit(500)
    return result.median

for (shape, dim), sparsity in itertools.product(shapes_and_dims, sparsities):
    x = make_input(shape, sparsity, torch.float32, "mps")
    m = bench(x, dim) * 1e6
    print(f"{str(shape):>14} {str(dim):>5} {sparsity:>5.2f} {m:>12.2f}")
```
</details>

ghstack-source-id: aa9130e
Pull-Request: #180725
[ghstack-poisoned]
malfet added a commit that referenced this pull request Apr 19, 2026
Migrate count_nonzero to native Metal by extending the existing sum reduction kernels with a third LoadMode variant that counts nonzero elements.

Refactor the NAN_TO_ZERO bool template parameter in ReduceOps.metal to a LoadMode enum with three values: LOAD_IDENTITY (sum), LOAD_NAN_TO_ZERO (nansum), and LOAD_NONZERO (count_nonzero — contributes 1 per nonzero, 0 otherwise). The sum_reduction, sum_reduction_outer, and sum_reduction_inner templates all share the same load dispatch; the compiler eliminates dead branches per instantiation.

Register count_nonzero_{,_outer,_inner}_<TI>_long kernels for all supported input dtypes (float/half/bfloat/{int,long,short,char,uchar}/bool/float2/half2). Host-side count_nonzero_mps now builds a TensorIterator via make_reduction and dispatches to sum_nansum_kernel_mps with prefix "count_nonzero_"; remove MPSReductionType::COUNT_NONZERO and its MPSGraph branch.

Fix the two-pass full-reduction path: pass 2 combines partial counts by summing them, so it must use the "sum_" prefix even when pass 1 used "nansum_" or "count_nonzero_" (otherwise we'd re-count already-counted partials).

Benchmark vs torch 2.11 MPSGraph (median us, M5 Pro):

| shape       | op    | dtype   | 2.11 | new  | speedup |
|-------------|-------|---------|------|------|---------|
| (10000,)    | full  | float32 | 14.0 | 10.2 | 1.37x   |
| (1000000,)  | full  | float32 | 14.2 | 16.4 | 0.87x   |
| (1024,1024) | full  | float32 | 16.4 | 13.2 | 1.24x   |
| (1024,1024) | dim=0 | float32 | 13.0 |  6.0 | 2.18x   |
| (1024,1024) | dim=1 | float32 | 12.9 |  5.1 | 2.55x   |
| (4096,4096) | full  | float32 |131.2 |121.9 | 1.08x   |
| (4096,4096) | dim=0 | float32 |132.4 |127.1 | 1.04x   |
| (1024,1024) | full  | int64   | 29.8 | 13.1 | 2.28x   |
| (1024,1024) | dim=0 | int64   | 23.4 |  7.4 | 3.16x   |
| (1024,1024) | dim=0 | float16 | 22.3 |  5.1 | 4.37x   |
| (1024,1024) | full  | bool    | 30.4 | 37.7 | 0.81x   |
| (1024,1024) | dim=0 | bool    | 14.2 |  6.8 | 2.09x   |
| (4096,4096) | dim=0 | bool    | 48.9 | 29.1 | 1.68x   |

Dim reductions see 2–4x speedups across dtypes. Full reductions are comparable or faster in most cases; two minor regressions remain on small-data paths where fixed two-pass overhead dominates (1M fp32 full, 1024² bool full).

<details>
<summary>Benchmark script</summary>

```python
import torch
import torch.utils.benchmark as benchmark
import itertools

shapes_and_dims = [
    ((10_000,), None),
    ((1_000_000,), None),
    ((1024, 1024), None),
    ((1024, 1024), 0),
    ((1024, 1024), 1),
    ((4096, 4096), None),
    ((4096, 4096), 0),
    ((4096, 4096), 1),
]
sparsities = [0.2, 0.5, 0.8]

def make_input(shape, sparsity, dtype, device):
    if dtype == torch.bool:
        return torch.rand(shape, device=device) < sparsity
    x = torch.randn(shape, device=device, dtype=dtype)
    mask = torch.rand(shape, device=device) >= sparsity
    x[mask] = 0
    return x

def bench(x, dim):
    stmt = "torch.count_nonzero(x)" if dim is None else "torch.count_nonzero(x, dim=d)"
    t = benchmark.Timer(stmt=stmt, globals={"torch": torch, "x": x, "d": dim}, num_threads=1)
    for _ in range(2):
        result = t.timeit(500)
    return result.median

for (shape, dim), sparsity in itertools.product(shapes_and_dims, sparsities):
    x = make_input(shape, sparsity, torch.float32, "mps")
    m = bench(x, dim) * 1e6
    print(f"{str(shape):>14} {str(dim):>5} {sparsity:>5.2f} {m:>12.2f}")
```
</details>

ghstack-source-id: f25a18a
Pull-Request: #180725
[ghstack-poisoned]
malfet added a commit that referenced this pull request Apr 19, 2026
Migrate count_nonzero to native Metal by extending the existing sum reduction kernels with a third LoadMode variant that counts nonzero elements.

Refactor the NAN_TO_ZERO bool template parameter in ReduceOps.metal to a LoadMode enum with three values: LOAD_IDENTITY (sum), LOAD_NAN_TO_ZERO (nansum), and LOAD_NONZERO (count_nonzero — contributes 1 per nonzero, 0 otherwise). The sum_reduction, sum_reduction_outer, and sum_reduction_inner templates all share the same load dispatch; the compiler eliminates dead branches per instantiation.

Register count_nonzero_{,_outer,_inner}_<TI>_long kernels for all supported input dtypes (float/half/bfloat/{int,long,short,char,uchar}/bool/float2/half2). Host-side count_nonzero_mps now builds a TensorIterator via make_reduction and dispatches to sum_nansum_kernel_mps with prefix "count_nonzero_"; remove MPSReductionType::COUNT_NONZERO and its MPSGraph branch.

Fix the two-pass full-reduction path: pass 2 combines partial counts by summing them, so it must use the "sum_" prefix even when pass 1 used "nansum_" or "count_nonzero_" (otherwise we'd re-count already-counted partials).

Benchmark vs torch 2.11 MPSGraph (median us, M5 Pro):

| shape       | op    | dtype   | 2.11 | new  | speedup |
|-------------|-------|---------|------|------|---------|
| (10000,)    | full  | float32 | 14.0 | 10.2 | 1.37x   |
| (1000000,)  | full  | float32 | 14.2 | 16.4 | 0.87x   |
| (1024,1024) | full  | float32 | 16.4 | 13.2 | 1.24x   |
| (1024,1024) | dim=0 | float32 | 13.0 |  6.0 | 2.18x   |
| (1024,1024) | dim=1 | float32 | 12.9 |  5.1 | 2.55x   |
| (4096,4096) | full  | float32 |131.2 |121.9 | 1.08x   |
| (4096,4096) | dim=0 | float32 |132.4 |127.1 | 1.04x   |
| (1024,1024) | full  | int64   | 29.8 | 13.1 | 2.28x   |
| (1024,1024) | dim=0 | int64   | 23.4 |  7.4 | 3.16x   |
| (1024,1024) | dim=0 | float16 | 22.3 |  5.1 | 4.37x   |
| (1024,1024) | full  | bool    | 30.4 | 37.7 | 0.81x   |
| (1024,1024) | dim=0 | bool    | 14.2 |  6.8 | 2.09x   |
| (4096,4096) | dim=0 | bool    | 48.9 | 29.1 | 1.68x   |

Dim reductions see 2–4x speedups across dtypes. Full reductions are comparable or faster in most cases; two minor regressions remain on small-data paths where fixed two-pass overhead dominates (1M fp32 full, 1024² bool full).

<details>
<summary>Benchmark script</summary>

```python
import torch
import torch.utils.benchmark as benchmark
import itertools

shapes_and_dims = [
    ((10_000,), None),
    ((1_000_000,), None),
    ((1024, 1024), None),
    ((1024, 1024), 0),
    ((1024, 1024), 1),
    ((4096, 4096), None),
    ((4096, 4096), 0),
    ((4096, 4096), 1),
]
sparsities = [0.2, 0.5, 0.8]

def make_input(shape, sparsity, dtype, device):
    if dtype == torch.bool:
        return torch.rand(shape, device=device) < sparsity
    x = torch.randn(shape, device=device, dtype=dtype)
    mask = torch.rand(shape, device=device) >= sparsity
    x[mask] = 0
    return x

def bench(x, dim):
    stmt = "torch.count_nonzero(x)" if dim is None else "torch.count_nonzero(x, dim=d)"
    t = benchmark.Timer(stmt=stmt, globals={"torch": torch, "x": x, "d": dim}, num_threads=1)
    for _ in range(2):
        result = t.timeit(500)
    return result.median

for (shape, dim), sparsity in itertools.product(shapes_and_dims, sparsities):
    x = make_input(shape, sparsity, torch.float32, "mps")
    m = bench(x, dim) * 1e6
    print(f"{str(shape):>14} {str(dim):>5} {sparsity:>5.2f} {m:>12.2f}")
```
</details>

ghstack-source-id: ce5a5eb
Pull-Request: #180725
@malfet malfet added the ciflow/trunk Trigger trunk jobs on your pull request label Apr 20, 2026
@malfet

malfet commented Apr 20, 2026

Copy link
Copy Markdown
Collaborator Author

@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

@github-actions
github-actions Bot deleted the gh/malfet/841/head branch May 21, 2026 02:29
aperson30 pushed a commit to aperson30/pytorch that referenced this pull request Jun 20, 2026
Migrate count_nonzero to native Metal by extending the existing sum reduction kernels with a third LoadMode variant that counts nonzero elements.

Refactor the NAN_TO_ZERO bool template parameter in ReduceOps.metal to a LoadMode enum with three values: `LOAD_IDENTITY` (sum), `LOAD_NAN_TO_ZERO` (nansum), and `LOAD_NONZERO` (count_nonzero — contributes 1 per nonzero, 0 otherwise). The sum_reduction, sum_reduction_outer, and sum_reduction_inner templates all share the same load dispatch; the compiler eliminates dead branches per instantiation. Even though output is 64-bit integer,  accumulates partial counts in `uint32` rather than `long` as tensor dimension is always less that in32 on Metal.

Register count_nonzero_{,_outer,_inner}_<TI>_long kernels for all supported input dtypes (float/half/bfloat/{int,long,short,char,uchar}/bool/float2/half2). Host-side count_nonzero_mps now builds a TensorIterator via make_reduction and dispatches to sum_nansum_kernel_mps with prefix "count_nonzero_"

Remove `MPSReductionType::COUNT_NONZERO` and its MPSGraph branch.

Tweaked the two-pass full-reduction path to always dispatch pass 2 with `LOAD_IDENTITY` (plain sum), regardless of pass-1 mode: pass 1 has already applied the load-mode transform (NaN-to-zero, nonzero-as-one), so pass 2 only needs to combine the partials.

Benchmark vs torch 2.11 MPSGraph (median us, M4 Max):

| shape       | op    | dtype   | 2.11 | new  | speedup |
|-------------|-------|---------|------|------|---------|
| (10000,)    | full  | float32 | 14.0 |  8.1 | 1.73x   |
| (1000000,)  | full  | float32 | 14.2 | 10.8 | 1.31x   |
| (1024,1024) | full  | float32 | 16.4 | 11.6 | 1.41x   |
| (1024,1024) | dim=0 | float32 | 13.0 |  6.0 | 2.18x   |
| (1024,1024) | dim=1 | float32 | 12.9 |  4.9 | 2.62x   |
| (4096,4096) | full  | float32 |131.2 |121.9 | 1.08x   |
| (4096,4096) | dim=0 | float32 |132.4 |127.1 | 1.04x   |
| (1024,1024) | full  | int64   | 15.5 | 12.8 | 1.21x   |
| (1024,1024) | dim=0 | int64   | 12.9 |  7.6 | 1.70x   |
| (1024,1024) | dim=0 | float16 | 14.7 |  4.7 | 3.13x   |
| (1024,1024) | full  | bool    | 15.1 | 11.2 | 1.34x   |
| (1024,1024) | dim=0 | bool    | 13.2 |  4.8 | 2.76x   |
| (4096,4096) | dim=0 | bool    | 48.8 | 26.2 | 1.86x   |

Dim reductions see parity or 1.7–3x speedups across dtypes.

<details>
<summary>Benchmark script</summary>

```python
import torch
import torch.utils.benchmark as benchmark
import itertools

shapes_and_dims = [
    ((10_000,), None),
    ((1_000_000,), None),
    ((1024, 1024), None),
    ((1024, 1024), 0),
    ((1024, 1024), 1),
    ((4096, 4096), None),
    ((4096, 4096), 0),
    ((4096, 4096), 1),
]
sparsities = [0.2, 0.5, 0.8]

def make_input(shape, sparsity, dtype, device):
    if dtype == torch.bool:
        return torch.rand(shape, device=device) < sparsity
    x = torch.randn(shape, device=device, dtype=dtype)
    mask = torch.rand(shape, device=device) >= sparsity
    x[mask] = 0
    return x

def bench(x, dim):
    stmt = "torch.count_nonzero(x)" if dim is None else "torch.count_nonzero(x, dim=d)"
    t = benchmark.Timer(stmt=stmt, globals={"torch": torch, "x": x, "d": dim}, num_threads=1)
    for _ in range(2):
        result = t.timeit(500)
    return result.median

for (shape, dim), sparsity in itertools.product(shapes_and_dims, sparsities):
    x = make_input(shape, sparsity, torch.float32, "mps")
    m = bench(x, dim) * 1e6
    print(f"{str(shape):>14} {str(dim):>5} {sparsity:>5.2f} {m:>12.2f}")
```
</details>
Pull Request resolved: pytorch#180725
Approved by: https://github.com/Skylion007
ghstack dependencies: pytorch#180709
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
Migrate count_nonzero to native Metal by extending the existing sum reduction kernels with a third LoadMode variant that counts nonzero elements.

Refactor the NAN_TO_ZERO bool template parameter in ReduceOps.metal to a LoadMode enum with three values: `LOAD_IDENTITY` (sum), `LOAD_NAN_TO_ZERO` (nansum), and `LOAD_NONZERO` (count_nonzero — contributes 1 per nonzero, 0 otherwise). The sum_reduction, sum_reduction_outer, and sum_reduction_inner templates all share the same load dispatch; the compiler eliminates dead branches per instantiation. Even though output is 64-bit integer,  accumulates partial counts in `uint32` rather than `long` as tensor dimension is always less that in32 on Metal.

Register count_nonzero_{,_outer,_inner}_<TI>_long kernels for all supported input dtypes (float/half/bfloat/{int,long,short,char,uchar}/bool/float2/half2). Host-side count_nonzero_mps now builds a TensorIterator via make_reduction and dispatches to sum_nansum_kernel_mps with prefix "count_nonzero_"

Remove `MPSReductionType::COUNT_NONZERO` and its MPSGraph branch.

Tweaked the two-pass full-reduction path to always dispatch pass 2 with `LOAD_IDENTITY` (plain sum), regardless of pass-1 mode: pass 1 has already applied the load-mode transform (NaN-to-zero, nonzero-as-one), so pass 2 only needs to combine the partials.

Benchmark vs torch 2.11 MPSGraph (median us, M4 Max):

| shape       | op    | dtype   | 2.11 | new  | speedup |
|-------------|-------|---------|------|------|---------|
| (10000,)    | full  | float32 | 14.0 |  8.1 | 1.73x   |
| (1000000,)  | full  | float32 | 14.2 | 10.8 | 1.31x   |
| (1024,1024) | full  | float32 | 16.4 | 11.6 | 1.41x   |
| (1024,1024) | dim=0 | float32 | 13.0 |  6.0 | 2.18x   |
| (1024,1024) | dim=1 | float32 | 12.9 |  4.9 | 2.62x   |
| (4096,4096) | full  | float32 |131.2 |121.9 | 1.08x   |
| (4096,4096) | dim=0 | float32 |132.4 |127.1 | 1.04x   |
| (1024,1024) | full  | int64   | 15.5 | 12.8 | 1.21x   |
| (1024,1024) | dim=0 | int64   | 12.9 |  7.6 | 1.70x   |
| (1024,1024) | dim=0 | float16 | 14.7 |  4.7 | 3.13x   |
| (1024,1024) | full  | bool    | 15.1 | 11.2 | 1.34x   |
| (1024,1024) | dim=0 | bool    | 13.2 |  4.8 | 2.76x   |
| (4096,4096) | dim=0 | bool    | 48.8 | 26.2 | 1.86x   |

Dim reductions see parity or 1.7–3x speedups across dtypes.

<details>
<summary>Benchmark script</summary>

```python
import torch
import torch.utils.benchmark as benchmark
import itertools

shapes_and_dims = [
    ((10_000,), None),
    ((1_000_000,), None),
    ((1024, 1024), None),
    ((1024, 1024), 0),
    ((1024, 1024), 1),
    ((4096, 4096), None),
    ((4096, 4096), 0),
    ((4096, 4096), 1),
]
sparsities = [0.2, 0.5, 0.8]

def make_input(shape, sparsity, dtype, device):
    if dtype == torch.bool:
        return torch.rand(shape, device=device) < sparsity
    x = torch.randn(shape, device=device, dtype=dtype)
    mask = torch.rand(shape, device=device) >= sparsity
    x[mask] = 0
    return x

def bench(x, dim):
    stmt = "torch.count_nonzero(x)" if dim is None else "torch.count_nonzero(x, dim=d)"
    t = benchmark.Timer(stmt=stmt, globals={"torch": torch, "x": x, "d": dim}, num_threads=1)
    for _ in range(2):
        result = t.timeit(500)
    return result.median

for (shape, dim), sparsity in itertools.product(shapes_and_dims, sparsities):
    x = make_input(shape, sparsity, torch.float32, "mps")
    m = bench(x, dim) * 1e6
    print(f"{str(shape):>14} {str(dim):>5} {sparsity:>5.2f} {m:>12.2f}")
```
</details>
Pull Request resolved: pytorch#180725
Approved by: https://github.com/Skylion007
ghstack dependencies: pytorch#180709
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
Migrate count_nonzero to native Metal by extending the existing sum reduction kernels with a third LoadMode variant that counts nonzero elements.

Refactor the NAN_TO_ZERO bool template parameter in ReduceOps.metal to a LoadMode enum with three values: `LOAD_IDENTITY` (sum), `LOAD_NAN_TO_ZERO` (nansum), and `LOAD_NONZERO` (count_nonzero — contributes 1 per nonzero, 0 otherwise). The sum_reduction, sum_reduction_outer, and sum_reduction_inner templates all share the same load dispatch; the compiler eliminates dead branches per instantiation. Even though output is 64-bit integer,  accumulates partial counts in `uint32` rather than `long` as tensor dimension is always less that in32 on Metal.

Register count_nonzero_{,_outer,_inner}_<TI>_long kernels for all supported input dtypes (float/half/bfloat/{int,long,short,char,uchar}/bool/float2/half2). Host-side count_nonzero_mps now builds a TensorIterator via make_reduction and dispatches to sum_nansum_kernel_mps with prefix "count_nonzero_"

Remove `MPSReductionType::COUNT_NONZERO` and its MPSGraph branch.

Tweaked the two-pass full-reduction path to always dispatch pass 2 with `LOAD_IDENTITY` (plain sum), regardless of pass-1 mode: pass 1 has already applied the load-mode transform (NaN-to-zero, nonzero-as-one), so pass 2 only needs to combine the partials.

Benchmark vs torch 2.11 MPSGraph (median us, M4 Max):

| shape       | op    | dtype   | 2.11 | new  | speedup |
|-------------|-------|---------|------|------|---------|
| (10000,)    | full  | float32 | 14.0 |  8.1 | 1.73x   |
| (1000000,)  | full  | float32 | 14.2 | 10.8 | 1.31x   |
| (1024,1024) | full  | float32 | 16.4 | 11.6 | 1.41x   |
| (1024,1024) | dim=0 | float32 | 13.0 |  6.0 | 2.18x   |
| (1024,1024) | dim=1 | float32 | 12.9 |  4.9 | 2.62x   |
| (4096,4096) | full  | float32 |131.2 |121.9 | 1.08x   |
| (4096,4096) | dim=0 | float32 |132.4 |127.1 | 1.04x   |
| (1024,1024) | full  | int64   | 15.5 | 12.8 | 1.21x   |
| (1024,1024) | dim=0 | int64   | 12.9 |  7.6 | 1.70x   |
| (1024,1024) | dim=0 | float16 | 14.7 |  4.7 | 3.13x   |
| (1024,1024) | full  | bool    | 15.1 | 11.2 | 1.34x   |
| (1024,1024) | dim=0 | bool    | 13.2 |  4.8 | 2.76x   |
| (4096,4096) | dim=0 | bool    | 48.8 | 26.2 | 1.86x   |

Dim reductions see parity or 1.7–3x speedups across dtypes.

<details>
<summary>Benchmark script</summary>

```python
import torch
import torch.utils.benchmark as benchmark
import itertools

shapes_and_dims = [
    ((10_000,), None),
    ((1_000_000,), None),
    ((1024, 1024), None),
    ((1024, 1024), 0),
    ((1024, 1024), 1),
    ((4096, 4096), None),
    ((4096, 4096), 0),
    ((4096, 4096), 1),
]
sparsities = [0.2, 0.5, 0.8]

def make_input(shape, sparsity, dtype, device):
    if dtype == torch.bool:
        return torch.rand(shape, device=device) < sparsity
    x = torch.randn(shape, device=device, dtype=dtype)
    mask = torch.rand(shape, device=device) >= sparsity
    x[mask] = 0
    return x

def bench(x, dim):
    stmt = "torch.count_nonzero(x)" if dim is None else "torch.count_nonzero(x, dim=d)"
    t = benchmark.Timer(stmt=stmt, globals={"torch": torch, "x": x, "d": dim}, num_threads=1)
    for _ in range(2):
        result = t.timeit(500)
    return result.median

for (shape, dim), sparsity in itertools.product(shapes_and_dims, sparsities):
    x = make_input(shape, sparsity, torch.float32, "mps")
    m = bench(x, dim) * 1e6
    print(f"{str(shape):>14} {str(dim):>5} {sparsity:>5.2f} {m:>12.2f}")
```
</details>
Pull Request resolved: pytorch#180725
Approved by: https://github.com/Skylion007
ghstack dependencies: pytorch#180709
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/mps Run MPS tests (subset of trunk) ciflow/trunk Trigger trunk jobs on your pull request Merged release notes: mps Release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants