Skip to content

Speed up NumPy argmin and argmax on finite MX floats - #463

Open
ZenAlexa wants to merge 1 commit into
jax-ml:mainfrom
ZenAlexa:contrib/finite-mx-arg-reductions
Open

ZenAlexa wants to merge 1 commit into
jax-ml:mainfrom
ZenAlexa:contrib/finite-mx-arg-reductions

Conversation

@ZenAlexa

@ZenAlexa ZenAlexa commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

NumPy's argmin and argmax now stop when they encounter the first least or greatest representable value of a finite-only dtype. For float4_e2m1fn, float6_e2m3fn, and float6_e3m2fn, no later element can beat that value. The scan compares the native values directly and retains the first index on ties, including signed zero and noncanonical upper padding bits. NaN-bearing formats keep the existing scan: a NaN after a finite maximum must still win.

Measurement

I used the first 512 rows of model.layers.0.self_attn.q_proj.weight from NVIDIA's Qwen3-8B NVFP4 checkpoint. The packed tensor is uint8[4096, 2048], representing 4096 × 4096 weights. The 1 MiB sample contains 131,072 blocks of 16 weights, the quantization group size in the model config. About 66% of blocks contain +6 and about 66% contain −6.

Both source builds used GCC Release and NumPy 2.5.5 on Linux x86-64. Times are median milliseconds for one complete axis=1 reduction, with baseline 9cad2fd and this revision interleaved over 12 rounds on one CPU core.

FP4 input argmax, before → after argmin, before → after
Checkpoint blocks, already unpacked 10.11 → 5.57 10.30 → 5.07
Same blocks, including nibble unpacking 10.77 → 6.18 10.72 → 5.46
512 × 1024 rows with no endpoint 2.10 → 1.66 2.11 → 1.51
Same shape, endpoints in the final two positions 2.09 → 1.66 2.09 → 1.52

The last two cases still scan the full or nearly full row. Those timings measure the native comparisons without a useful early exit. These results cover CPU index reductions, not model inference.

Correctness

An independent decoder checked the first minimum and maximum index for all 65,536 ordered pairs of stored bytes per finite format, including every upper-padding pattern, repeated equal values, both signs of zero, reversed views and axis changes. The built wheel passed the Python suite with 27,015 passed, 133 skipped and 45 expected failures. The upstream Test workflow has no jobs yet and needs approval to run its platform matrix for e0a2412.

Reproduce the checkpoint measurements

Run this with NumPy and each revision of ml_dtypes installed. The byte range is the first 1 MiB of the pinned tensor; it does not download the whole model shard.

import statistics
import timeit
import urllib.request
import ml_dtypes
import numpy as np

root = "https://huggingface.co/nvidia/Qwen3-8B-NVFP4/resolve/"
rev = "ccd10a893cbca613259517c3efe08e151ddf2b8e"
first, size = 1747109584, 1 << 20
last = first + size - 1
url = f"{root}{rev}/model-00001-of-00002.safetensors?download=true&sample={first}-{last}"
req = urllib.request.Request(url, headers={"Range": f"bytes={first}-{last}"})
with urllib.request.urlopen(req) as res:
    if res.status != 206 or not res.headers["Content-Range"].startswith(f"bytes {first}-{last}/"):
        raise RuntimeError("expected a partial range response")
    raw = np.frombuffer(res.read(), dtype=np.uint8)

def unpack():
    codes = np.empty(raw.size * 2, dtype=np.uint8)
    codes[::2] = raw & 15
    codes[1::2] = raw >> 4
    return codes.view(ml_dtypes.float4_e2m1fn).reshape(-1, 16)

blocks = unpack()
for fun in (np.argmax, np.argmin):
    for include_unpack in (False, True):
        def call():
            return fun(unpack() if include_unpack else blocks, axis=1)
        if not np.array_equal(call(), fun(blocks.astype(np.float32), axis=1)):
            raise RuntimeError(f"{fun.__name__} changed the selected index")
        times = timeit.repeat(call, number=3, repeat=12)
        print(fun.__name__, include_unpack, statistics.median(times) * 1000 / 3, "ms")

Signed-off-by: Ziming Wang <zimingwang945@gmail.com>
@ZenAlexa
ZenAlexa marked this pull request as ready for review December 3, 2026 13:02
@jakevdp
jakevdp requested a review from hawkinsp December 3, 2026 20:18

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants