Skip to content

WIP,DRAFT: Use WarpReduce for short-axis generic CUB block reductions - #10075

Closed
seberg wants to merge 1 commit into
cupy:mainfrom
seberg:cub-small-reduce-pr
Closed

seberg wants to merge 1 commit into
cupy:mainfrom
seberg:cub-small-reduce-pr

Conversation

@seberg

@seberg seberg commented Jul 6, 2026

Copy link
Copy Markdown
Member

This is mostly vie coded, and I'll include a fully vibe coded benchmark script in the details below.

I'll open another PR that just focuses on not using the generic CUB paths for very short reductions (maybe mostly for the simplicity).
For intermediate sizes 1028-4096 (very rough), there are places where a WrapReduce should get 2x speedup.

(The main reason why I will do the other PR first is that (a) if we go here I should review it a bit more myself but mainly (b) I am wondering about using different approaches for the whole thing and the minimal thing is at least enough to not be a gigantic performance issue)

Details
#!/usr/bin/env python3
"""Benchmark reductions while sweeping the last-axis size.

This script keeps the total input size roughly constant while varying the
last-axis reduction length.  It times:

* ``sum_device_cub``: ``cupy.sum(..., axis=-1)`` through the CUB routine path
* ``sum_generic_cub``: ``cupy.sum(..., axis=-1)`` through generic CUB reduction
  using the automatic group-size selector
* ``sum_generic_cub_warp<N>``: generic CUB with forced ``WarpReduce<N>``
* ``sum_generic_cub_block``: generic CUB with forced ``BlockReduce``
* ``sum_fallback``: ``cupy.sum(..., axis=-1)`` with CUB disabled
* ``vector_norm_generic_cub``: vector 2-norm through generic CUB reduction
  using the automatic group-size selector
* ``vector_norm_generic_cub_warp<N>``: vector 2-norm with forced
  ``WarpReduce<N>``
* ``vector_norm_generic_cub_block``: vector 2-norm with forced ``BlockReduce``
* ``vector_norm_fallback``: vector 2-norm with CUB disabled

Example:

    cd benchmarks
    python reduction_axis_scan.py --repeat 30 --warp-groups 2,4,8,16,32 \
      --cuda-profiler

For Nsight Systems, pair ``--cuda-profiler`` with:

    nsys profile -c cudaProfilerApi -o reduction_axis_scan \
      python reduction_axis_scan.py --cuda-profiler
"""

from __future__ import annotations

import argparse
import contextlib
import csv
import dataclasses
import math
import os
import pathlib
from typing import Callable


@dataclasses.dataclass(frozen=True)
class BenchCase:
    name: str
    op: str
    routine_accelerators: tuple[str, ...]
    reduction_accelerators: tuple[str, ...]
    cub_group_threads: str | None = None


def make_default_cases(warp_groups: tuple[int, ...]) -> tuple[BenchCase, ...]:
    cases = [
        BenchCase('sum_device_cub', 'sum', ('cub',), ()),
        BenchCase('sum_generic_cub', 'sum', (), ('cub',)),
        *(
            BenchCase(
                f'sum_generic_cub_warp{group}', 'sum', (), ('cub',),
                str(group))
            for group in warp_groups
        ),
        BenchCase('sum_generic_cub_block', 'sum', (), ('cub',), 'block'),
        BenchCase('sum_fallback', 'sum', (), ()),
        BenchCase('vector_norm_generic_cub', 'vector_norm', (), ('cub',)),
        *(
            BenchCase(
                f'vector_norm_generic_cub_warp{group}', 'vector_norm',
                (), ('cub',), str(group))
            for group in warp_groups
        ),
        BenchCase(
            'vector_norm_generic_cub_block', 'vector_norm', (), ('cub',),
            'block'),
        BenchCase('vector_norm_fallback', 'vector_norm', (), ()),
    ]
    return tuple(cases)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        '--total-elements', type=int, default=1 << 24,
        help='Approximate total input elements for each N.')
    parser.add_argument(
        '--max-n', type=int, default=100_000,
        help='Maximum last-axis reduction length in the default sweep.')
    parser.add_argument(
        '--n-values', default=None,
        help='Comma-separated explicit last-axis lengths.')
    parser.add_argument(
        '--dtype', default='float32',
        choices=('float16', 'float32', 'float64'),
        help='Input dtype.')
    parser.add_argument(
        '--repeat', type=int, default=10,
        help='Timed repeats per case.')
    parser.add_argument(
        '--warmup', type=int, default=3,
        help='Untimed warmup repeats per case.')
    parser.add_argument(
        '--max-duration', type=float, default=math.inf,
        help='Maximum benchmark duration per case, in seconds.')
    parser.add_argument(
        '--cases', default=None,
        help='Comma-separated case names. Defaults to all cases.')
    parser.add_argument(
        '--warp-groups', default='16',
        help='Comma-separated forced logical-warp group sizes to benchmark.')
    parser.add_argument(
        '--output-csv', default='reduction_axis_scan.csv',
        help='CSV output path.')
    parser.add_argument(
        '--output-plot', default='reduction_axis_scan.png',
        help='Plot output path.')
    parser.add_argument(
        '--no-plot', action='store_true',
        help='Skip matplotlib plot generation.')
    parser.add_argument(
        '--cuda-profiler', action='store_true',
        help='Bracket the benchmark loop with cudaProfilerStart/Stop.')
    return parser.parse_args()


def default_n_values(max_n: int) -> list[int]:
    values = []
    power = 1
    while power <= max_n:
        values.append(power)
        midpoint = power + power // 2
        if midpoint <= max_n:
            values.append(midpoint)
        power *= 2
    if max_n not in values:
        values.append(max_n)
    return sorted(set(values))


def parse_warp_groups(args: argparse.Namespace) -> tuple[int, ...]:
    if args.warp_groups.strip() == '':
        return ()
    groups = tuple(
        sorted({int(v.strip()) for v in args.warp_groups.split(',')}))
    if any(group <= 0 for group in groups):
        raise ValueError('--warp-groups must contain positive integers')
    return groups


def parse_n_values(args: argparse.Namespace) -> list[int]:
    if args.n_values is None:
        values = default_n_values(args.max_n)
    else:
        values = [int(v.strip()) for v in args.n_values.split(',')]
    values = [v for v in values if v > 0]
    if not values:
        raise ValueError('at least one positive N is required')
    return values


def select_cases(
        args: argparse.Namespace, cases: tuple[BenchCase, ...],
) -> list[BenchCase]:
    cases_by_name = {case.name: case for case in cases}
    if args.cases is None:
        return list(cases)
    selected = []
    for name in (v.strip() for v in args.cases.split(',')):
        if name not in cases_by_name:
            known = ', '.join(cases_by_name)
            raise ValueError(f'unknown case {name!r}; choices: {known}')
        selected.append(cases_by_name[name])
    return selected


@contextlib.contextmanager
def accelerator_state(cupy, routine: tuple[str, ...],
                      reduction: tuple[str, ...]):
    from cupy._core import _accelerator

    old_routine = _accelerator.get_routine_accelerators()
    old_reduction = _accelerator.get_reduction_accelerators()
    try:
        _accelerator.set_routine_accelerators(list(routine))
        _accelerator.set_reduction_accelerators(list(reduction))
        yield
    finally:
        _accelerator.set_routine_accelerators(old_routine)
        _accelerator.set_reduction_accelerators(old_reduction)


@contextlib.contextmanager
def cub_group_threads_state(group_threads: str | None):
    env_name = 'CUPY_CUB_REDUCTION_GROUP_THREADS'
    old_group_threads = os.environ.get(env_name)
    try:
        if group_threads is None:
            os.environ.pop(env_name, None)
        else:
            os.environ[env_name] = group_threads
        yield
    finally:
        if old_group_threads is None:
            os.environ.pop(env_name, None)
        else:
            os.environ[env_name] = old_group_threads


def make_input(cupy, shape: tuple[int, int], dtype_name: str):
    dtype = getattr(cupy, dtype_name)
    size = shape[0] * shape[1]
    a = cupy.arange(size, dtype=cupy.float32)
    a = (a % 17) * cupy.float32(0.25)
    return a.astype(dtype, copy=False).reshape(shape)


def make_operation(cupy, case: BenchCase) -> Callable:
    if case.op == 'sum':
        return lambda a: cupy.sum(a, axis=-1)

    if case.op == 'vector_norm':
        if hasattr(cupy.linalg, 'vector_norm'):
            return lambda a: cupy.linalg.vector_norm(a, axis=-1)
        return lambda a: cupy.linalg.norm(a, axis=-1)

    raise AssertionError(f'unhandled op: {case.op}')


def benchmark_case(cupy, profiler, case: BenchCase, a, args):
    op = make_operation(cupy, case)
    with accelerator_state(cupy, case.routine_accelerators,
                           case.reduction_accelerators), \
            cub_group_threads_state(case.cub_group_threads):
        # Compile and populate memory-pool state before timing.
        op(a)
        cupy.cuda.get_current_stream().synchronize()
        perf = profiler.benchmark(
            op, (a,), n_repeat=args.repeat, n_warmup=args.warmup,
            max_duration=args.max_duration, name=case.name)
    gpu_times = perf.gpu_times[0]
    return {
        'case': case.name,
        'op': case.op,
        'gpu_mean_us': float(gpu_times.mean() * 1e6),
        'gpu_std_us': float(gpu_times.std() * 1e6),
        'gpu_min_us': float(gpu_times.min() * 1e6),
        'gpu_max_us': float(gpu_times.max() * 1e6),
        'repeats': int(gpu_times.size),
        'cub_group_threads': case.cub_group_threads or 'auto',
    }


def write_csv(path: pathlib.Path, rows: list[dict]) -> None:
    if not rows:
        return
    fieldnames = list(rows[0])
    with path.open('w', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(rows)


def plot_results(path: pathlib.Path, rows: list[dict]) -> None:
    import matplotlib.pyplot as plt

    ops = sorted({row['op'] for row in rows})
    fig, axes = plt.subplots(
        len(ops), 1, figsize=(8, 3.8 * len(ops)), squeeze=False,
        sharex=True)
    for ax, op in zip(axes[:, 0], ops):
        op_rows = [row for row in rows if row['op'] == op]
        for case in sorted({row['case'] for row in op_rows}):
            case_rows = [row for row in op_rows if row['case'] == case]
            case_rows.sort(key=lambda row: row['N'])
            ax.plot(
                [row['N'] for row in case_rows],
                [row['gpu_mean_us'] for row in case_rows],
                marker='o', label=case)
        ax.set_xscale('log')
        ax.set_yscale('log')
        ax.set_ylabel('GPU time (us)')
        ax.set_title(op)
        ax.grid(True, which='both', alpha=0.3)
        ax.legend()
    axes[-1, 0].set_xlabel('last-axis reduction length N')
    fig.tight_layout()
    fig.savefig(path, dpi=160)

    plt.show()


def main() -> None:
    args = parse_args()

    import cupy
    from cupyx import profiler

    warp_groups = parse_warp_groups(args)
    all_cases = make_default_cases(warp_groups)
    n_values = parse_n_values(args)
    cases = select_cases(args, all_cases)
    rows = []

    profile_context = (
        profiler.profile() if args.cuda_profiler else contextlib.nullcontext())
    with profile_context:
        for n in n_values:
            outer = max(1, args.total_elements // n)
            shape = (outer, n)
            a = make_input(cupy, shape, args.dtype)
            actual_elements = shape[0] * shape[1]
            for case in cases:
                result = benchmark_case(cupy, profiler, case, a, args)
                result.update({
                    'N': n,
                    'outer': outer,
                    'elements': actual_elements,
                    'dtype': args.dtype,
                    'input_mib': a.nbytes / (1024 ** 2),
                })
                rows.append(result)
                print(
                    f"N={n:<5d} outer={outer:<7d} {case.name:<24s} "
                    f"{result['gpu_mean_us']:9.3f} us")

    csv_path = pathlib.Path(args.output_csv)
    write_csv(csv_path, rows)
    print(f'wrote {csv_path}')

    if not args.no_plot:
        plot_path = pathlib.Path(args.output_plot)
        plot_results(plot_path, rows)
        print(f'wrote {plot_path}')


if __name__ == '__main__':
    main()

Select among the fallback kernel, WarpReduce, and BlockReduce based on
the contiguous reduction-axis size. Keep the BlockLoad fast path when
BlockReduce handles an identity pre-map.

Also use CUB's fixed-size int API for device segmented reduce on CUDA
when segment_size fits in int, avoiding offset-iterator workspace.
@mergify

mergify Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

This pull request is now in conflicts. Could you fix it @seberg? 🙏

@seberg

seberg commented Oct 6, 2026

Copy link
Copy Markdown
Member Author

Closing this for now as the big issue is solved (with cub segmented reduce using fixed-width path and naive fallback for others). Since it would be nice to use cuda-compute soon where this should drop out much cleaner/simpler.

@seberg seberg closed this Oct 6, 2026
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.

1 participant