Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

## Unreleased

- HIP: ModelOpt NVFP4 checkpoints keep their e2m1 codes and group scales as stored, and the new NVFP4 tiles decode them in flight � the 128-row GEMM for a prompt and the stream tile for a round � so the weights hold a quarter of the bytes and a decode reads a quarter of the traffic; FP8 layers still widen to BF16 at load. The format is core `quant.nvfp4`: the device keeps the checkpoint's layout (as MLX's does), E4M3 group scales widen to BF16 at read (exact), and a stack is refused because its experts carry a global scale each. Every other backend refuses the format by name.


- Linux: an O_DIRECT checkpoint read of a file that ends inside the span it asked for reports end of file instead of a failed read, so Nemotron's CUDA checkpoint reads stop on `EndOfFile` as they do through the page cache (nothing was copied wrongly before; the error was wrong); Nemotron's CUDA checkpoint reader is now tested on the host through its io_uring ring and its thread fallback (#2602).

- CI: the nightly Linux host job now runs `test-pdf-worker`, which spawns the PDF render worker from a Linux `tensorfold-native` so its `/proc/self/statm` memory cap and `close_range` run on Linux, and the new `test-cache-fit-host`, so the prompt-cache budget's no-footprint branch runs at all; both steps were only built into the macOS Metal graph before (#2599).
Expand Down
17 changes: 17 additions & 0 deletions docs/quantization.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,23 @@ cold 8,192-token prompt in 4.41 s against `full`'s 7.96 s (1.81x; 1.82x at 2,048
52.3 ms against 50.1 ms without drafts: decode reads the same weight bytes either way, and `checkpoint` adds the
rows' quantization.

## NVIDIA's NVFP4 checkpoints on HIP

The HIP engine reads the same ModelOpt NVFP4 tensors as stored, without widening a weight: `weight` is U8 e2m1 codes
(even inputs in the low nibble of a byte), `weight_scale` an E4M3 scale every 16 inputs, and `weight_scale_2` the
projection's one global scale. The shared tiles decode a nibble to the e2m1 level of the build's activation type
(BF16, or FP16 on RDNA2) with a table lookup, so the product is W4A16: the codes and scales keep a quarter of a BF16
weight's bytes and a decode reads a quarter of the traffic.

The device keeps the checkpoint's own layout, as the MLX affine format does, so an upload is a copy. The only
transform is at read: an E4M3 group scale widens to BF16, exactly (three mantissa bits fit seven), which is the 16-bit
table the tiles read. A stack of experts is refused, as BF16's is, because ModelOpt writes one global scale a
projection; FP8 layers of a mixed checkpoint still widen to BF16 at load.

Prompt rows take the 128-row GEMM tile and a round's rows the stream tile, both decoding in flight; the GEMM is also
what a prompt uses regardless of its chunking, so a row's bits do not depend on where a chunk is cut. Other backends
name the format and refuse it rather than reading the codes as something else.

## GLM-5.3-Flash's float32 tensors on CUDA

The GLM CUDA loader keeps float32 where its kernels read float32: the hyper-connections' bases and scales, KDA's short
Expand Down
62 changes: 62 additions & 0 deletions zig/kernels/hip/quant/nvfp4.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#pragma once

// ModelOpt NVFP4's words: y[m, n] = global * sum_g scale[n, g] * sum_k x[m, k] * e2m1(code[n, k]).
// The scale of a group of 16 inputs is stored as the E4M3 ModelOpt wrote it in, as BF16 (exact: 4 bits fit 8),
// so a tile keeps its 16-bit table and folds the one global scale into the widened value.

#include <hip/hip_bfloat16.h>
#include <hip/hip_fp16.h>
#include <hip/hip_runtime.h>

#include <cstdint>

#include "quant/mlx.hpp"
#include "tiles/plan.hpp"

namespace tf {
namespace rocm {

// e2m1's sixteen levels, in the order its sign and three magnitude bits name them.
__host__ __device__ constexpr double kE2m1[16] = {
0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0,
};

// The same levels as BF16 and FP16 bits, so a tile makes a pair with two loads and no conversion.
__device__ constexpr unsigned short kE2m1Bf16[16] = {
0x0000, 0x3F00, 0x3F80, 0x3FC0, 0x4000, 0x4040, 0x4080, 0x40C0,
0x8000, 0xBF00, 0xBF80, 0xBFC0, 0xC000, 0xC040, 0xC080, 0xC0C0,
};
__device__ constexpr unsigned short kE2m1F16[16] = {
0x0000, 0x3800, 0x3C00, 0x3E00, 0x4000, 0x4200, 0x4400, 0x4600,
0x8000, 0xB800, 0xBC00, 0xBE00, 0xC000, 0xC200, 0xC400, 0xC600,
};

struct Nvfp4 {
const void* x; // (m, k) row major, bf16 or fp16
const uint32_t* words; // (n, k / 8) row major: 4-bit codes, 8 to a word
GroupTable scale; // (n, k / 16), E4M3's values as BF16
float* out; // (m, n)
int m, n, k, group;
int fp16; // 0 is bf16, 1 is fp16
Routing route = {};
__half* out16 = nullptr; // set: the tile rounds each output to the activation type here instead of writing out
float global = 1.0f; // the checkpoint's second scale, applied to the widened group scale
};

// A routed block takes item ``z``: its expert's weights and its rows. False when the item has no rows.
__device__ inline bool take_item(Nvfp4& a, int z) {
if (!a.route.items) return true;
const int* item = a.route.items + 3 * z;
const int count = item[2];
if (count <= 0) return false;
const long long expert = item[0];
const long long groups = a.k / a.group;
a.words += expert * a.n * (static_cast<long long>(a.k) / 8);
a.scale.p = static_cast<const char*>(a.scale.p) + expert * a.n * groups * 2;
a.route.first = item[1];
a.m = count;
return true;
}

} // namespace rocm
} // namespace tf
191 changes: 191 additions & 0 deletions zig/kernels/hip/quant/nvfp4_decoder.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
#pragma once

// The ModelOpt NVFP4 decoder: 4-bit e2m1 codes packed in 32-bit words, one E4M3 group scale a 16 inputs, no bias.
// It offers what MlxDecoder offers, so the shared tiles take it: only the code's value, the bias and the global differ.

#include <type_traits>
#include <utility>

#include "common/vec.hpp"
#include "quant/mlx_pieces.hpp"
#include "quant/nvfp4.hpp"

namespace tf {
namespace rocm {

using TableBits = unsigned __attribute__((ext_vector_type(2)));

template <int BITS>
struct Nvfp4Decoder {
using Args = Nvfp4;
static constexpr int kBits = BITS;
// Words of a 32-code chunk of a column.
static constexpr int kWords = BITS;
// No bias a group: the tiles leave out the x sums and the bias folds.
static constexpr bool kBias = false;

// ---- the plan: a routed item's expert and rows ----

__device__ static bool take_item(Args& a, int z) { return tf::rocm::take_item(a, z); }

// ---- a column's codes ----

__device__ static const uint32_t* words(const Args& a) { return a.words; }

template <typename Idx>
__device__ static Idx row_words(const Args& a) {
return static_cast<Idx>(a.k) * BITS / 32;
}

template <bool WIDE>
__device__ static void load(const uint32_t* src, uint32_t (&w)[BITS]) {
if constexpr (WIDE && BITS % 4 == 0) {
#pragma unroll
for (int i = 0; i < BITS / 4; ++i) {
const u32x4 v = reinterpret_cast<const u32x4*>(src)[i];
w[4 * i] = v.x;
w[4 * i + 1] = v.y;
w[4 * i + 2] = v.z;
w[4 * i + 3] = v.w;
}
} else if constexpr (WIDE && BITS % 2 == 0) {
#pragma unroll
for (int i = 0; i < BITS / 2; ++i) {
const uint2 v = reinterpret_cast<const uint2*>(src)[i];
w[2 * i] = v.x;
w[2 * i + 1] = v.y;
}
} else {
#pragma unroll
for (int i = 0; i < BITS; ++i) w[i] = src[i];
}
}

// A code's e2m1 level as the activation type's bits: one load from the sixteen, no conversion in flight.
template <typename T>
__device__ static unsigned short level(uint32_t c) {
if constexpr (std::is_same_v<typename T::elem, __half>) return kE2m1F16[c & 0xfu];
else return kE2m1Bf16[c & 0xfu];
}

// Two levels as the activation type's pair.
template <typename T>
__device__ static typename T::pair pack(unsigned short lo, unsigned short hi) {
return __builtin_bit_cast(typename T::pair, static_cast<uint32_t>(lo) | (static_cast<uint32_t>(hi) << 16));
}

// Code t of a chunk as the Dot's element type.
template <typename T>
__device__ static typename T::elem code(const uint32_t (&w)[BITS], int t) {
return __builtin_bit_cast(typename T::elem, level<T>(piece_bits<BITS>(w, t)));
}

// Codes t and t + 1 of a chunk, in order, as a pair.
template <typename T>
__device__ static typename T::pair pair(const uint32_t (&w)[BITS], int t) {
return pack<T>(level<T>(piece_bits<BITS>(w, t)), level<T>(piece_bits<BITS>(w, t + 1)));
}

// ---- the group terms: a scale a group of a column, the one global scale folded in ----

struct Term {
TableBits scale;
};

__device__ static TableBits table_bits(const GroupTable& t, long long i) {
const uint16_t* p = static_cast<const uint16_t*>(t.p);
const bool wide = t.kind == kScaleF32;
return TableBits{p[wide ? 2 * i : i], p[wide ? 2 * i + 1 : i]};
}

__device__ static float table_float(const GroupTable& t, TableBits b) {
if (t.kind == kScaleBF16) return __uint_as_float(b.x << 16);
if (t.kind == kScaleF16) return __half2float(__ushort_as_half(static_cast<unsigned short>(b.x)));
return __uint_as_float(b.x | (b.y << 16));
}

__device__ static Term term(const Args& a, long long i) { return Term{table_bits(a.scale, i)}; }

__device__ static float scale_value(const Args& a, const Term& t) {
return table_float(a.scale, t.scale) * a.global;
}
__device__ static float bias_value(const Args&, const Term&) { return 0.f; }

__device__ static float fold_scale(float acc, float dot, float scale) { return fmaf(dot, scale, acc); }
__device__ static float fold_bias(float acc, float, float) { return acc; }

// A non-finite stream sum: replay full groups only when an actual operand is non-finite.
template <typename T>
__device__ __attribute__((always_inline)) static inline float repair_stream(const Args& a, const typename T::elem* x,
int col, float original) {
const int groups = a.k / a.group;
const int words_row = row_words<int>(a);
const uint32_t* w = a.words + static_cast<long long>(col) * words_row;
bool exceptional = false;
double y = 0.0;
for (int g = 0; g < groups; ++g) {
const double scale = static_cast<double>(a.scale[static_cast<long long>(col) * groups + g]) *
static_cast<double>(a.global);
exceptional |= !__builtin_isfinite(scale);
double qx = 0.0;
for (int k = g * a.group; k < (g + 1) * a.group; ++k) {
const double v = static_cast<float>(x[k]);
const double q = kE2m1[affine_code(w, k, BITS, words_row) & 0xfu];
exceptional |= !__builtin_isfinite(v);
qx += q * v;
}
y += scale * qx;
}
return exceptional ? static_cast<float>(y) : original;
}

// ---- the decode stream tile: a lane owns a 32-code chunk, its pairs are made with two loads ----

static constexpr int kWideBytes = BITS % 4 == 0 ? 16 : BITS % 2 == 0 ? 8 : 4;

__device__ static bool wide_aligned(const Args& a) {
const long long words_row = static_cast<long long>(a.k) * BITS / 32;
return ((reinterpret_cast<uintptr_t>(a.words) | static_cast<uintptr_t>(words_row * 4)) & (kWideBytes - 1)) == 0;
}

template <class Sides>
__device__ static void bind(Args& a, const Sides& sides, int s) {
a.words = sides.words[s];
a.scale.p = sides.scale[s];
}

// Neighbours: a pair is codes 2 I and 2 I + 1, the x pair beside them. The MLX byte path packs integers.
static constexpr bool kGapPairs = false;

template <int I>
static constexpr int lo() {
return 2 * I;
}

static constexpr int gap() { return 1; }

template <typename T, int I>
__device__ static typename T::pair stream_pair(const uint32_t (&w)[BITS]) {
return pair<T>(w, 2 * I);
}

// The stream tile's group terms: the 16-bit E4M3-as-BF16 scale, the global folded in where it is widened.
struct StreamTerms {
const unsigned short* scale;
float global;

__device__ explicit StreamTerms(const Args& a)
: scale(static_cast<const unsigned short*>(a.scale.p)), global(a.global) {}

__device__ unsigned short scale_raw(long long at) const { return scale[at]; }
__device__ unsigned short bias_raw(long long) const { return 0; }

__device__ float widen(unsigned short v) const { return __uint_as_float(static_cast<uint32_t>(v) << 16) * global; }

__device__ float scale_value(unsigned short v) const { return widen(v); }
__device__ float bias_value(unsigned short) const { return 0.f; }
};
};

} // namespace rocm
} // namespace tf
54 changes: 54 additions & 0 deletions zig/kernels/hip/quant/nvfp4_tiles.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#pragma once

// ModelOpt NVFP4 kernels: the shared tiles over Nvfp4Decoder, named as the launcher will look them up.

#include <type_traits>

#include "quant/act.hpp"
#include "quant/mlx_tiles.hpp"
#include "quant/nvfp4_decoder.hpp"
#include "tiles/dot2.hpp"
#include "tiles/epilogue.hpp"
#include "tiles/gemm.hpp"
#include "tiles/matrix_gemm.hpp"
#include "tiles/matrix_item.hpp"
#include "tiles/stream.hpp"

namespace tf {
namespace rocm {

// e2m1's codes are a nibble, eight to a word.
constexpr int kNvfp4Bits = 4;

// ---- the prefill GEMM tile ----

template <typename T, int RT>
__global__ void __launch_bounds__(256) nvfp4_gemm_block(Nvfp4 a) {
gemm_tile<Nvfp4Decoder<kNvfp4Bits>, IdentityAct<T>, T, GemmOut<T>, RT>(a);
}

// ---- the prefill GEMM tile on the matrix cores of gfx11 ----

__global__ void __launch_bounds__(256) nvfp4_wmma_gemm(Nvfp4 a) {
wmma_gemm_tile<Nvfp4Decoder<kNvfp4Bits>, BF16Act, WmmaBF16, GemmOut<WmmaBF16>>(a);
}

// ---- the same on RM x 16 rows a block, for a routed item of few rows ----

template <int RM>
__global__ void __launch_bounds__(256) nvfp4_wmma_item(Nvfp4 a) {
wmma_item_tile<Nvfp4Decoder<kNvfp4Bits>, BF16Act, WmmaBF16, GemmOut<WmmaBF16>, RM>(a);
}

// ---- the decode stream tile ----

// Item z of the plan (or the plain product, or a group's side) at CB columns a lane, R rows; PAIR fuses the activation.
template <typename T, int R, int CB, bool PAIR>
__global__ void __launch_bounds__(32 * kStreamWaves) nvfp4_dot2_stream(Nvfp4 a, StreamSides sides, int lpc_log2,
int gshift) {
using Epi = std::conditional_t<PAIR, StreamSwiglu<T>, StreamRound<T>>;
stream_tile<Nvfp4Decoder<kNvfp4Bits>, IdentityAct<T>, T, Epi, R, CB>(a, sides, lpc_log2, gshift);
}

} // namespace rocm
} // namespace tf
20 changes: 20 additions & 0 deletions zig/kernels/hip/tiles/dot2_tiles.hip
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include "tiles/matrix_gemm.hpp"
#include "quant/mlx_tiles.hpp"
#include "quant/dense_tiles.hpp"
#include "quant/nvfp4_tiles.hpp"

namespace tf {
namespace rocm {
Expand Down Expand Up @@ -339,6 +340,25 @@ using Dot = DotBF16;
using Dot = DotF16;
#endif

// ModelOpt NVFP4's entry points: the build's activation type inside, so the launcher names them plainly.
extern "C" __global__ void tf_nvfp4_gemm(Nvfp4 a) {
nvfp4_gemm_block<Dot, GemmShape<Dot>::rt>(a);
}

#define TF_NVFP4_STREAM(R, CB) \
extern "C" __global__ void tf_nvfp4_stream_r##R##c##CB(Nvfp4 a, StreamSides sides, int l, int g) { \
nvfp4_dot2_stream<Dot, R, CB, false>(a, sides, l, g); \
}

TF_NVFP4_STREAM(1, 2)
TF_NVFP4_STREAM(1, 4)
TF_NVFP4_STREAM(1, 8)
TF_NVFP4_STREAM(2, 2)
TF_NVFP4_STREAM(2, 4)
TF_NVFP4_STREAM(2, 8)
TF_NVFP4_STREAM(4, 2)
TF_NVFP4_STREAM(4, 4)

#define TF_LANES(BITS, ROWS) \
template __global__ void affine_dot2_lanes<Dot, BITS, ROWS, 1>(Affine); \
template __global__ void affine_dot2_lanes<Dot, BITS, ROWS, 2>(Affine); \
Expand Down
Loading