← Back to Pull requests

[DO-NOT-MERGE] Prototype: driver memsets for ndarray.fill #43

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Nov 14, 2026 03:45 UTC
Author

Prototype, parked here until CuPy can rely on cuda-bindings (PR 10464 in cupy/cupy is a step toward that). The first two commits are PR 10474 in cupy/cupy by its author, which fixes fill(-0.0) losing the sign by sending such values to fill_kernel; the two commits on top are the prototype.

What it does

  • Driver memsets. ndarray.fill issues one cuMemsetD8Async / cuMemsetD16Async / cuMemsetD32Async call when the array is C-contiguous and the bytes of the value repeat every 1, 2 or 4 bytes. That covers every 1-, 2- and 4-byte dtype, any zero, and values such as int64 -1 or complex64 1+1j. Bytes are compared, so -0.0 stays distinct from +0.0 and remains a memset for float16 and float32. CUDA has no 64-bit memset, so other float64 / complex128 values still go through fill_kernel.

  • PyArray_Pack (second commit). Plain Python and NumPy scalars and 0-d NumPy arrays are converted straight into a stack buffer instead of going through numpy.asarray(value, dtype=...).
  • Numbers

    Host time per call in µs (launch only, no sync) on an RTX A6000 with CUDA 13.4 and NumPy 2.5, median of 4 interleaved rounds:

    | | main | PR 10474 | + driver memsets | + PyArray_Pack |
    |---|---:|---:|---:|---:|
    | float32 fill(1.0), 1000 elements | 6.20 | 6.80 | 2.74 | 2.24 |
    | float32 fill(-0.0), 1000 elements | 2.95 (sign lost) | 6.82 | 2.74 | 2.23 |
    | bool fill(True), 1000 elements | 8.08 | 6.78 | 2.73 | 2.23 |
    | complex64 fill(1+1j), 1000 elements | 6.20 | 7.05 | 3.52 | 2.95 |
    | float64 fill(0.0), 0-d | 2.94 | 3.51 | 2.68 | 2.23 |
    | cupy.ones(1000, float32) | 9.20 | 10.07 | 4.92 | 4.47 |
    | cupy.array(np.float32(1)) | 10.59 | 12.64 | 6.19 | 6.24 |
    | float64 fill(1.0), 1000 elements (kernel) | 6.18 | 7.02 | 5.97 | 5.26 |
    | float64 fill(-0.0), 1000 elements (kernel) | 3.71 (sign lost) | 6.82 | 5.96 | 5.29 |
    | cupy.ones(1000) | 9.20 | 10.52 | 8.87 | 7.98 |

    Launch plus sync for large arrays: float16 with 64M elements goes from 357 to 195 µs and float32 with 1M elements from 15.4 to 9.0 µs; float32 with 64M elements is unchanged (386 vs 383 µs).

    For reference, on the same machine one cuMemsetD32Async call costs about 1.9 µs, one cuLaunchKernel call about 2.6 µs and one ElementwiseKernel call about 5.1 µs. Fills that become a memset are therefore within about 0.3 µs of the floor. The float64 / complex128 values that stay on the kernel could get to roughly 3 µs with a dedicated cuLaunchKernel path; that is an estimate and is not part of this branch.

    Open items

  • Build. core.pyx cimports cuda.bindings.cydriver unconditionally, so the branch builds only with cuda-bindings installed and not for ROCm. HIP needs its own hipMemsetD8/D16/D32Async path, or the current code as a fallback.

  • Header version. cydriver.pxd needs a cuda.h at least as new as the cuda-bindings release: 13.5.0 does not compile against CUDA 13.4 headers (CUDA_FABRIC_COPY_BATCH_OP_st is undefined), 13.4.4 does.

  • Behavior change. With PyArray_Pack, an out-of-range NumPy scalar (for example np.int64(231 - 1) into an int8 array) raises OverflowError, as numpy.ndarray.fill does. Today it wraps silently.

  • Other devices. An array on another device than the current one keeps using the kernel, which turns on peer access. The branch of fill that takes a 0-d CuPy array as the value is unchanged: it still calls cudaMemsetAsync without that check, which on main fails with an invalid-value error for a zero fill of an array on another device until peer access is on.

  • Tests. Nothing new in the test suite yet beyond the test from PR 10474. The new paths were checked against NumPy with the script below (3292 cases: dtypes × values × shapes, non-contiguous and offset views, structured dtypes, a non-default stream, a second thread), and the existing core_tests/test_ndarray_copy_and_view.py, creation_tests/test_basic.py and creation_tests/test_from_data.py pass.

  • cupy.full goes through copyto rather than fill, so it does not benefit.

  • Base.** The branch is 12 commits behind main; none of them touch the two files changed here.
  • <details><summary>Benchmark script</summary>

    import json, statistics, sys, time
    import numpy as np
    import cupy as cp
    
    dev = cp.cuda.Device()
    N, BATCHES = 200, 300
    
    
    def host_ns(fn):
        # Time only the launch loop; sync between batches so the queue stays short.
        ts = []
        for _ in range(BATCHES):
            dev.synchronize()
            t0 = time.perf_counter_ns()
            for _ in range(N):
                fn()
            ts.append((time.perf_counter_ns() - t0) / N)
        dev.synchronize()
        return statistics.median(ts)
    
    
    def e2e_ns(fn, reps=30):
        # Launch + wait for the GPU: for large arrays, where the device time matters.
        ts = []
        for _ in range(reps):
            dev.synchronize()
            t0 = time.perf_counter_ns()
            fn()
            dev.synchronize()
            ts.append(time.perf_counter_ns() - t0)
        return statistics.median(ts)
    
    
    f32_0 = cp.empty((), cp.float32)
    f32 = cp.empty(1000, cp.float32)
    f16 = cp.empty(1000, cp.float16)
    i32 = cp.empty(1000, cp.int32)
    i8 = cp.empty(1000, cp.int8)
    b1 = cp.empty(1000, cp.bool_)
    c64 = cp.empty(1000, cp.complex64)
    f64_0 = cp.empty((), cp.float64)
    f64 = cp.empty(1000, cp.float64)
    i64 = cp.empty(1000, cp.int64)
    np_f32_one = np.float32(1.0)
    
    cases = {
        "f32 1k fill(0.0)": lambda: f32.fill(0.0),
        "f32 1k fill(1.0)": lambda: f32.fill(1.0),
        "f32 1k fill(-0.0)": lambda: f32.fill(-0.0),
        "f32 0d fill(1.0)": lambda: f32_0.fill(1.0),
        "f16 1k fill(1.0)": lambda: f16.fill(1.0),
        "i32 1k fill(1)": lambda: i32.fill(1),
        "i8 1k fill(7)": lambda: i8.fill(7),
        "bool 1k fill(True)": lambda: b1.fill(True),
        "c64 1k fill(1+1j)": lambda: c64.fill(1 + 1j),
        "c64 1k fill(1.0)": lambda: c64.fill(1.0),
        "f64 1k fill(0.0)": lambda: f64.fill(0.0),
        "f64 1k fill(1.0)": lambda: f64.fill(1.0),
        "f64 1k fill(-0.0)": lambda: f64.fill(-0.0),
        "f64 0d fill(0.0)": lambda: f64_0.fill(0.0),
        "f64 0d fill(1.0)": lambda: f64_0.fill(1.0),
        "i64 1k fill(-1)": lambda: i64.fill(-1),
        "ones(1000, f32)": lambda: cp.ones(1000, cp.float32),
        "ones(1000, i32)": lambda: cp.ones(1000, cp.int32),
        "ones(1000, bool)": lambda: cp.ones(1000, cp.bool_),
        "ones(1000) f64": lambda: cp.ones(1000),
        "zeros(1000) f64 [control]": lambda: cp.zeros(1000),
        "empty(1000) f64 [control]": lambda: cp.empty(1000),
        "array(np.float32(1))": lambda: cp.array(np_f32_one),
        "array(1.0) f64": lambda: cp.array(1.0),
        "array(0.0) f64": lambda: cp.array(0.0),
        "array(-0.0) f64": lambda: cp.array(-0.0),
        "array(True)": lambda: cp.array(True),
        "full(1000, 2.0, f32)": lambda: cp.full(1000, 2.0, cp.float32),
    }
    for fn in cases.values():  # warm up kernel caches
        fn()
    res = {k: host_ns(fn) for k, fn in cases.items()}
    
    big = {}
    for label, n in (("1M", 1 << 20), ("64M", 1 << 26)):
        x32 = cp.empty(n, cp.float32)
        x16 = cp.empty(n, cp.float16)
        x64 = cp.empty(n, cp.float64)
        for name, fn in (
            (f"e2e f32 {label} fill(0.0)", lambda: x32.fill(0.0)),
            (f"e2e f32 {label} fill(1.0)", lambda: x32.fill(1.0)),
            (f"e2e f16 {label} fill(1.0)", lambda: x16.fill(1.0)),
            (f"e2e f64 {label} fill(1.0)", lambda: x64.fill(1.0)),
        ):
            fn()
            big[name] = e2e_ns(fn)
        del x32, x16, x64
    
    json.dump({"res": res, "big": big}, sys.stdout)
    

    </details>

    <details><summary>Correctness script</summary>

    import itertools, sys, threading
    import numpy as np
    import cupy as cp
    
    fails = []
    n_checks = 0
    
    
    def check(name, got, exp):
        global n_checks
        n_checks += 1
        if got.dtype != exp.dtype or got.shape != exp.shape \
                or got.tobytes() != exp.tobytes():
            fails.append((name, got.ravel()[:4], exp.ravel()[:4]))
    
    
    dtypes = [np.bool_, np.int8, np.uint8, np.int16, np.uint16, np.int32,
              np.uint32, np.int64, np.uint64, np.float16, np.float32, np.float64,
              np.complex64, np.complex128]
    values = [0, 1, -1, 7, 0.0, -0.0, 1.0, 3.25, float('inf'), float('nan'),
              True, False, 1 + 1j, 1 - 2j, complex('-0-0j'), complex(0.0, -0.0),
              np.float32(-0.0), np.int64(2**31 - 1), np.float64(1e300),
              np.array(-0.0), np.array(5, dtype=np.int16)]
    shapes = [(), (1,), (7,), (3, 5), (0,), (1000,)]
    
    import warnings
    for dt, v, shape in itertools.product(dtypes, values, shapes):
        exp = np.full(shape, 123, dtype=dt)
        try:
            with warnings.catch_warnings():
                warnings.simplefilter('ignore')
                exp.fill(v)
        except Exception as e:
            exp_err = type(e)
        else:
            exp_err = None
        a = cp.full(shape, 123, dtype=dt)
        try:
            with warnings.catch_warnings():
                warnings.simplefilter('ignore')
                a.fill(v)
        except Exception as e:
            got_err = type(e)
        else:
            got_err = None
        n_checks += 1
        if exp_err is not got_err:
            fails.append((f"err {np.dtype(dt)} {v!r} {shape}", got_err, exp_err))
        elif exp_err is None:
            check(f"{np.dtype(dt)} {v!r} {shape}", a.get(), exp)
    
    # non-contiguous target: only the selected elements change
    for dt, v in itertools.product(dtypes, [0, 1, -0.0, 3.25]):
        try:
            exp = np.full((6, 4), 9, dtype=dt)
            with warnings.catch_warnings():
                warnings.simplefilter('ignore')
                exp[::2, 1::2].fill(v)
        except Exception:
            continue
        a = cp.full((6, 4), 9, dtype=dt)
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            a[::2, 1::2].fill(v)
        check(f"noncontig {np.dtype(dt)} {v!r}", a.get(), exp)
        # contiguous sub-view: neighbours must stay untouched
        exp = np.full(64, 9, dtype=dt)
        a = cp.full(64, 9, dtype=dt)
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            exp[5:17].fill(v)
            a[5:17].fill(v)
        check(f"subview {np.dtype(dt)} {v!r}", a.get(), exp)
    
    # Device pointer aligned to the item but not to anything larger (a view that
    # starts `off` items into a byte buffer). Misaligned views are not tested:
    # the kernel path already faults on them (cudaErrorMisalignedAddress).
    for dt, v in itertools.product(
            [np.int16, np.float16, np.int32, np.float32, np.complex64,
             np.float64], [1, -0.0, 3.25, 0]):
        item = np.dtype(dt).itemsize
        for off in (1, 3):
            raw = cp.full((off + 16 + 2) * item, 0xAB, dtype=cp.uint8)
            view = raw[off * item:(off + 16) * item].view(dt)
            exp_raw = np.full((off + 16 + 2) * item, 0xAB, dtype=np.uint8)
            exp_view = exp_raw[off * item:(off + 16) * item].view(dt)
            with warnings.catch_warnings():
                warnings.simplefilter('ignore')
                view.fill(v)
                exp_view.fill(v)
            check(f"offset+{off} {np.dtype(dt)} {v!r}", raw.get(), exp_raw)
    
    # structured dtypes
    st = np.dtype('i4,f4')
    for v in [(0, 0.0), (0, -0.0), (42, 3.14), (1, 1.0)]:
        exp = np.ones(5, st); exp.fill(v)
        a = cp.ones(5, st); a.fill(v)
        check(f"struct {v!r}", a.get(), exp)
    st2 = np.dtype('i4,i4')
    for v in [(1, 1), (0, 0), (1, 2)]:
        exp = np.ones(5, st2); exp.fill(v)
        a = cp.ones(5, st2); a.fill(v)
        check(f"struct2 {v!r}", a.get(), exp)
    
    # 0-d cupy array as the value
    for dt, v in itertools.product([np.float32, np.float64, np.int32],
                                   [0.0, -0.0, 1.0]):
        exp = np.ones((2, 3), dt); exp.fill(np.asarray(v))
        a = cp.ones((2, 3), dt); a.fill(cp.asarray(v))
        check(f"cupy 0-d value {np.dtype(dt)} {v!r}", a.get(), exp)
    
    # non-default stream, and a fresh thread (driver calls need a current context)
    with cp.cuda.Stream():
        a = cp.zeros(1000, cp.float32); a.fill(2.5)
        check("stream f32", a.get(), np.full(1000, 2.5, np.float32))
    shared = cp.zeros(1000, cp.float32)
    box = []
    
    
    def worker():
        try:
            shared.fill(4.5)
            b = cp.empty(10, cp.int16); b.fill(-3)
            box.append((shared.get(), b.get()))
        except Exception as e:  # noqa
            box.append(e)
    
    
    t = threading.Thread(target=worker); t.start(); t.join()
    n_checks += 1
    if isinstance(box[0], Exception):
        fails.append(("thread", repr(box[0]), None))
    else:
        check("thread f32", box[0][0], np.full(1000, 4.5, np.float32))
        check("thread i16", box[0][1], np.full(10, -3, np.int16))
    
    # non-scalar values are still rejected
    for bad in ([1, 2], np.ones(2), np.ones((1,)), cp.ones(2)):
        n_checks += 1
        try:
            cp.empty(3).fill(bad)
        except ValueError:
            pass
        else:
            fails.append(("non-scalar accepted", type(bad), None))
    
    print(f"{n_checks} checks, {len(fails)} failures")
    for f in fails[:40]:
        print("FAIL", f)
    sys.exit(1 if fails else 0)
    

    </details>

    -- Leo's bot

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: seberg Review duration: 23890m
    All Vouch review confidence checks passed
    Residual risk 0.30 = Change Risk (0.52) × (1 − Review Confidence (0.43)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    42%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #43"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 43.0% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 43.0% · Lower = rushed or shallow review
    43.0%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 29.7% · Safe to merge
    29.7%
    Repository