Compare commits

...
7 Commits
Author SHA1 Message Date
Aleksander Grygier 6d8a8886fa ui: draw markdown tables with row rules instead of a cell grid (#33195)
A table in a chat column drew a rule around every cell, a band behind the
header and a frame around its scroll wrapper. The lines did the separating
twice over, so the table read heavier than the prose around it.

A hairline under each row carries the structure on its own now: no cell grid,
no header band, no frame, and the outer columns line up with the text above
and below. GFM column alignment arrives as an align attribute, which an
authored text-align beats, so the three values are restated and a
right-aligned column keeps its figures under its header. Numbers take tabular
figures, code in a cell stays one token, and a table of six or more columns
keeps a width a word sits on and scrolls in its wrapper.

The Tables story covers it: alignment, code and links in cells, a list and a
line break in a cell, escaped pipes and an empty cell, and a table wider than
the column.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-27 17:20:19 +01:00
Pedro Cuenca 4c7344447c [Inkling 2] Support nvfp4 pass-through (#33062) 2026-11-27 15:44:37 +01:00
fox5611 3ab385146c CUDA: fix ADD_ID launch for more than 65535 tokens (#33162)
The grid's y dimension came directly from the token count, so ADD_ID
launches with more than 65535 tokens failed with "invalid configuration
argument". NVIDIA and HIP are equally affected, since gridDim.y is
capped at 65535 on both.

Clamp the grid and stride over ne2 in the kernel, matching convert.cu
and pad.cu. Add a test case at 70000 tokens; the existing cases top out
at 129.

Assisted-by: Claude Opus 5
2026-11-27 15:32:42 +01:00
Ruben Ortlam d67b7a99d8 vulkan: handle empty conv3d kernel, fixes validation error (#33106) 2026-11-27 15:31:18 +01:00
Jeff Bolz 3b103f75e9 vulkan: further optimize coopmat2 GDN (#32860)
* vulkan: further optimize coopmat2 GDN

Refactor split+store callbacks so hi and lo portions are all stored together.
This should help allow the stores to be vectorized.

Interleave the state store callbacks with the gram_pmat work. The compiler
doesn't seem to let these things overlap without manual effort like this. I
suspect this is because the compiler doesn't have smart enough alias analyssis
to know what can/can't conflict.

Similarly, split the invert function into separate calculation/store calls,
so the inverse work can interleave better with the MMAs.

Move "solved" from sh_dh to sh_sh - reusing sh_dh needed a barrier but sh_sh
doesn't.

* interact properly with new replay code
2026-11-27 15:26:19 +01:00
Aaron Teo 4346838ad8 ggml-zdnn: make zTensor memory usage visible for fitting (#31849)
* ggml-zdnn: make memory usage visible for fitting

Signed-off-by: Aaron Teo <aaron.teo1@ibm.com>

* ggml-zdnn: switch to a flag check for ztensor buffer storage

Signed-off-by: Aaron Teo <aaron.teo1@ibm.com>

* ggml-zdnn: fix rebase conflicts

Signed-off-by: Aaron Teo <aaron.teo1@ibm.com>

---------

Signed-off-by: Aaron Teo <aaron.teo1@ibm.com>
2026-11-27 15:22:50 +01:00
NoahandJohannes Gäßler 0020197457 CUDA: cache the device type at init (#33142)
* CUDA: cache the device type at init

ggml_backend_cuda_device_get_type called cudaGetDeviceProperties on every
call, which takes ~0.7-1 ms with the CUDA 12 runtime. With tensor
overrides on multiple GPUs the scheduler queries the device type for every
split input, so this ran dozens of times per token.

Store the device type in ggml_cuda_device_info at init. It is derived from
prop.integrated, not from the integrated flag, which is forced off (#15034).

Ref #33132

* Apply suggestion from @JohannesGaessler

---------

Co-authored-by: Johannes Gäßler <johannesg@5d6.de>
2026-11-27 15:18:23 +01:00
15 changed files with 500 additions and 150 deletions
+67 -11
View File
@@ -65,6 +65,26 @@ def _dequant_expert_chunk(weight: Callable[[], Tensor], scale: Callable[[], Tens
return values
def _repack_nvfp4_rows(packed: np.ndarray, scales: np.ndarray, name: str, expert: int) -> np.ndarray:
if np.any(scales & 0x80) or np.any(scales == 0x7F):
raise ValueError(f"Inkling2: {name}_scale expert {expert}: NVFP4 block scales must be finite and nonnegative")
n_rows = packed.shape[0]
n_blocks = scales.shape[1]
nibbles = np.stack([packed & 0x0F, packed >> 4], axis=-1).reshape(n_rows, n_blocks, 16)
qs = (nibbles[:, :, :8] | (nibbles[:, :, 8:] << 4)).astype(np.uint8)
n_super = n_blocks // 4
blocks = np.concatenate([scales.reshape(n_rows, n_super, 4), qs.reshape(n_rows, n_super, 32)], axis=-1)
return blocks.reshape(n_rows, n_super * 36)
def _repack_nvfp4_expert(weight: Callable[[], Tensor], scale: Callable[[], Tensor], name: str, expert: int, w13: bool) -> np.ndarray:
packed = LazyTorchTensor.to_eager(weight().view(torch.uint8)[expert]).numpy()
scales = LazyTorchTensor.to_eager(scale().view(torch.uint8)[expert]).numpy()
if not w13:
return _repack_nvfp4_rows(packed, scales, name, expert)
return np.concatenate([_repack_nvfp4_rows(packed[half::2], scales[half::2], name, expert) for half in (0, 1)])
def _is_inkling2(dir_model: Path) -> bool:
if not (dir_model / "config.json").is_file():
return False
@@ -84,9 +104,11 @@ def _load_inkling2_hparams(dir_model: Path):
class Inkling2Model(TextModel):
model_arch = gguf.MODEL_ARCH.INKLING2
def __init__(self, dir_model: Path, *args, **kwargs):
def __init__(self, dir_model: Path, ftype: gguf.LlamaFileType, *args, **kwargs):
self._expert_quant: dict[str, dict] = {}
self._packed_experts: dict[str, gguf.LazyChunkedTensor] = {}
self._native_experts: dict[str, tuple[gguf.LazyChunkedTensor, np.ndarray]] = {}
self._preserve_nvfp4 = ftype == gguf.LlamaFileType.GUESSED
quant_path = dir_model / "hf_quant_config.json"
if quant_path.is_file():
with open(quant_path, encoding="utf-8") as f:
@@ -99,7 +121,7 @@ class Inkling2Model(TextModel):
if name in self._expert_quant:
raise ValueError(f"Inkling2: duplicate hf_quant_config.json scheme for {name}")
self._expert_quant[name] = group
super().__init__(dir_model, *args, **kwargs)
super().__init__(dir_model, ftype, *args, **kwargs)
logger.warning("Inkling2: converting the text backbone only; vision and MTP tensors are skipped")
hp = self.hparams
for name, default in (("q_bias", False), ("o_bias", False), ("n_shared_experts", 0), ("use_value_norm_no_gamma", True), ("attn_res_normalize_values", True), ("scoring_func", "sigmoid")):
@@ -165,15 +187,38 @@ class Inkling2Model(TextModel):
t = gen()
if t.dtype != torch.float32 or tuple(t.shape) != expected:
raise ValueError(f"Inkling2: {companion}: expected F32 {expected}, got {t.dtype} {tuple(t.shape)}")
chunks: list[Callable[[], np.ndarray]] = []
for expert in range(experts):
for half in range(2 if w13 else 1):
for start in range(0, rows // 2 if w13 else rows, _EXPERT_CHUNK_ROWS):
stop = min(start + _EXPERT_CHUNK_ROWS, rows // 2 if w13 else rows)
# The same packed row slice selects the weight and its scale groups.
row_slice = slice(2 * start + half, 2 * stop + half, 2) if w13 else slice(start, stop)
chunks.append(partial(_dequant_expert_chunk, weight, scale, amax, denominator, name, expert, row_slice))
self._packed_experts[name] = gguf.LazyChunkedTensor(chunks, shape, np.float32)
preserve_nvfp4 = nvfp4 and self._preserve_nvfp4
if preserve_nvfp4 and cols % 64 != 0:
logger.warning("Inkling2: %s: %d columns are not a multiple of 64; dequantizing NVFP4", name, cols)
preserve_nvfp4 = False
chunks: list[Callable[[], np.ndarray]]
if preserve_nvfp4:
assert amax is not None and denominator is not None
a = LazyTorchTensor.to_eager(amax()).numpy().astype(np.float32)
d = LazyTorchTensor.to_eager(denominator()).numpy().astype(np.float32)
if not np.isfinite(a).all() or (a < 0).any():
raise ValueError(f"Inkling2: {name}_amax: expected finite nonnegative values")
if not np.isfinite(d).all() or (d <= 0).any():
raise ValueError(f"Inkling2: {name}_outer_scale_denominator: expected finite positive value")
with np.errstate(over="ignore", invalid="ignore"):
outer_scale = a / d
if not np.isfinite(outer_scale).all():
raise ValueError(f"Inkling2: {name}: non-finite outer scale")
chunks = [partial(_repack_nvfp4_expert, weight, scale, name, expert, w13) for expert in range(experts)]
byte_shape = (experts, rows, cols // 64 * 36)
self._native_experts[name] = (gguf.LazyChunkedTensor(chunks, byte_shape, np.uint8), outer_scale)
else:
chunks = []
for expert in range(experts):
for half in range(2 if w13 else 1):
for start in range(0, rows // 2 if w13 else rows, _EXPERT_CHUNK_ROWS):
stop = min(start + _EXPERT_CHUNK_ROWS, rows // 2 if w13 else rows)
# The same packed row slice selects the weight and its scale groups.
row_slice = slice(2 * start + half, 2 * stop + half, 2) if w13 else slice(start, stop)
chunks.append(partial(_dequant_expert_chunk, weight, scale, amax, denominator, name, expert, row_slice))
self._packed_experts[name] = gguf.LazyChunkedTensor(chunks, shape, np.float32)
if not nvfp4 and self._fp8_as_q8:
self._fp8_dequantized.add(name)
self.model_tensors[name] = lambda shape=shape: torch.empty(shape, dtype=torch.float32, device="meta")
for companion in required:
del self.model_tensors[companion]
@@ -181,6 +226,7 @@ class Inkling2Model(TextModel):
t = gen()
if not t.dtype.is_floating_point or t.element_size() == 1 or name.endswith(("_weight_scale", "_weight_amax", "_weight_outer_scale_denominator")):
raise ValueError(f"Inkling2: unexpected packed tensor or orphan companion {name}")
self._is_nvfp4 = bool(self._native_experts)
@classmethod
def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
@@ -254,6 +300,16 @@ class Inkling2Model(TextModel):
if name.endswith(".o_proj.gate_proj.weight"):
yield self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_GATE, bid), data_torch
return
if name in self._native_experts:
target = name.replace(".w13_weight", ".gate_up_proj").replace(".w2_weight", ".down_proj")
new_name = self.map_tensor_name(target, try_suffixes=()) + ".weight"
packed, scale = self._native_experts[name]
shape = gguf.quant_shape_from_byte_shape(packed.shape, gguf.GGMLQuantizationType.NVFP4)
shape_str = f"{{{', '.join(str(n) for n in reversed(shape))}}}"
logger.info(f"{new_name}, NVFP4 --> NVFP4, shape = {shape_str}")
self.gguf_writer.add_tensor(new_name, cast("np.ndarray", packed), raw_dtype=gguf.GGMLQuantizationType.NVFP4)
self._write_scales_tensor(new_name.removesuffix(".weight") + ".scale", scale.tolist())
return
if name in self._packed_experts:
target = name.replace(".w13_weight", ".gate_up_proj").replace(".w2_weight", ".down_proj")
yield self.map_tensor_name(target, try_suffixes=()) + ".weight", cast("Tensor", self._packed_experts[name])
+14 -12
View File
@@ -2,26 +2,28 @@
static __global__ void add_id_kernel(
const float * src0, const float * src1, const int32_t * src2, float * dst,
int64_t ne0, int64_t ne1,
int64_t ne0, int64_t ne1, int64_t ne2,
size_t nb01, size_t nb02,
size_t nb11,
size_t nb21
) {
const int64_t i1 = blockIdx.x;
const int64_t i2 = blockIdx.y;
const int i11 = *(const int32_t *) ((const char *) src2 + i1*sizeof(int32_t) + i2*nb21);
// gridDim.y is capped at 65535, blocks stride over larger ne2
for (int64_t i2 = blockIdx.y; i2 < ne2; i2 += gridDim.y) {
const int i11 = *(const int32_t *) ((const char *) src2 + i1*sizeof(int32_t) + i2*nb21);
const size_t nb1 = ne0 * sizeof(float);
const size_t nb2 = ne1 * nb1;
const size_t nb1 = ne0 * sizeof(float);
const size_t nb2 = ne1 * nb1;
float * dst_row = (float *)((char *)dst + i1*nb1 + i2*nb2);
const float * src0_row = (const float *)((const char *)src0 + i1*nb01 + i2*nb02);
const float * src1_row = (const float *)((const char *)src1 + i11*nb11);
float * dst_row = (float *)((char *)dst + i1*nb1 + i2*nb2);
const float * src0_row = (const float *)((const char *)src0 + i1*nb01 + i2*nb02);
const float * src1_row = (const float *)((const char *)src1 + i11*nb11);
for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) {
dst_row[i0] = src0_row[i0] + src1_row[i0];
for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) {
dst_row[i0] = src0_row[i0] + src1_row[i0];
}
}
}
@@ -47,10 +49,10 @@ void ggml_cuda_op_add_id(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
float * dst_d = (float *)dst->data;
int threads = std::min((int)ne00, 768); // cols
dim3 blocks(ne01, ne02); // n_experts_used, n_tokens
dim3 blocks(ne01, std::min(ne02, (int64_t)65535)); // n_experts_used, n_tokens
add_id_kernel<<<blocks, threads, 0, ctx.stream()>>>(
src0_d, src1_d, src2_d, dst_d,
ne0, ne1,
ne0, ne1, ne2,
nb01, nb02,
nb11,
nb21
+1
View File
@@ -1309,6 +1309,7 @@ struct ggml_cuda_device_info {
size_t smpb; // max. shared memory per block
size_t smpbo; // max. shared memory per block (with opt-in)
bool integrated; // Device is integrated as opposed to discrete
enum ggml_backend_dev_type type; // GPU or IGPU, from cudaDeviceProp::integrated
bool vmm; // virtual memory support
size_t vmm_granularity; // granularity of virtual memory
size_t total_vram;
+2 -6
View File
@@ -404,6 +404,7 @@ static ggml_cuda_device_info ggml_cuda_init() {
info.default_tensor_split[id] = total_vram;
total_vram += device_vram;
info.devices[id].integrated = false; // Temporarily disabled due to issues with corrupted output (e.g. #15034)
info.devices[id].type = prop.integrated ? GGML_BACKEND_DEVICE_TYPE_IGPU : GGML_BACKEND_DEVICE_TYPE_GPU;
info.devices[id].nsm = prop.multiProcessorCount;
info.devices[id].smpb = prop.sharedMemPerBlock;
info.devices[id].warp_size = prop.warpSize;
@@ -4096,12 +4097,7 @@ static void ggml_backend_cuda_device_get_memory(ggml_backend_dev_t dev, size_t *
static enum ggml_backend_dev_type ggml_backend_cuda_device_get_type(ggml_backend_dev_t dev) {
ggml_backend_cuda_device_context * ctx = (ggml_backend_cuda_device_context *) dev->context;
cudaDeviceProp prop;
CUDA_CHECK(cudaGetDeviceProperties(&prop, ggml_cuda_get_physical_device(ctx->device)));
return prop.integrated
? GGML_BACKEND_DEVICE_TYPE_IGPU
: GGML_BACKEND_DEVICE_TYPE_GPU;
return ggml_cuda_info().devices[ctx->device].type;
}
static void ggml_backend_cuda_device_get_props(ggml_backend_dev_t dev, ggml_backend_dev_props * props) {
+7
View File
@@ -13261,6 +13261,13 @@ void ggml_vk_conv_3d(ggml_backend_vk_context * ctx, vk_context & subctx, const g
GGML_ASSERT(src1->type == GGML_TYPE_F32);
GGML_ASSERT(dst->type == GGML_TYPE_F32);
if (ggml_is_empty(src0)) {
const vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true);
const size_t size = ggml_nbytes(dst);
subctx->s->buffer->buf.fillBuffer(dst_buf.buffer->buffer, dst_buf.offset + dst_buf.size - size, size, 0);
return;
}
GGML_TENSOR_BINARY_OP_LOCALS
GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
GGML_ASSERT(nb10 == sizeof(float));
@@ -36,7 +36,7 @@ shared OPD sh_kqh[2 * C * LDP], sh_kql[2 * C * LDP];
shared OPD sh_sh[V * LDP], sh_sl[V * LDP]; // state mirror [V x D] row-major (D padded)
shared OPD sh_ph[C * C], sh_pl[C * C];
shared OPD sh_ih[C * C], sh_il[C * C];
shared OPD sh_dh[C * LDV], sh_dl[C * LDV]; // delta / solved [C x V] row-major (V padded)
shared OPD sh_dh[C * LDV], sh_dl[C * LDV]; // delta [C x V] row-major (V padded)
shared float sh_lower[C * (C - 1) / 2]; // packed strictly-lower Gram entries
shared float sh_prefix[C], sh_ep[C], sh_beta[C], sh_carry[C];
@@ -70,9 +70,15 @@ float StoreGramPmat(const in uint32_t r, const in uint32_t c, const in float ele
return elem;
}
float SplitRowS(const in uint32_t r, const in uint32_t c, const in float elem) {
const uint i = r * LDP + c;
split(elem, sh_sh[i], sh_sl[i]);
// The bf16 hi and lo parts go to the state mirror in separate callbacks, so
// that a thread's stores of neighboring elements are adjacent and vectorize.
float StoreHi(const in uint32_t r, const in uint32_t c, const in float elem, const in uint32_t c0) {
sh_sh[r * LDP + c0 + c] = OPD(elem);
return elem;
}
float StoreLo(const in uint32_t r, const in uint32_t c, const in float elem, const in uint32_t c0) {
sh_sl[r * LDP + c0 + c] = OPD(elem - float(OPD(elem)));
return elem;
}
@@ -92,13 +98,8 @@ float StoreDeltaV(const in uint32_t r, const in uint32_t c, const in float ks, c
return ks;
}
float StoreSolved(const in uint32_t r, const in uint32_t c, const in float elem) {
const uint i = c * LDV + r;
split(elem, sh_dh[i], sh_dl[i]);
// The state mirror is no longer needed after KS/QS.
const uint j = r * LDP + c;
split(sh_carry[c] * elem, sh_sh[j], sh_sl[j]);
return elem;
float ScaleCarry(const in uint32_t r, const in uint32_t c, const in float elem) {
return sh_carry[c] * elem;
}
float StoreOut(const in uint32_t r, const in uint32_t c, const in float elem,
@@ -146,8 +147,9 @@ void stage_inputs(const in float q[NQK], const in float k[NQK]) {
}
}
// [K; Q] * K^T computes Gram and P in one 32-row matrix.
void gram_pmat() {
// [K; Q] * K^T computes Gram and P in one 32-row matrix. Each state block's
// hi/lo split for the S*K^T/S*Q^T products runs interleaved with these MMAs.
void gram_pmat(in coopmat<float, WG, V, KT, MACC> state[D / KT]) {
coopmat<float, WG, KQ_ROWS, C, MACC> x = coopmat<float, WG, KQ_ROWS, C, MACC>(0.0);
[[unroll]] for (uint kk = 0; kk < D; kk += KT) {
coopmat<OPD, WG, KQ_ROWS, KT, MUA> ah, al;
@@ -157,17 +159,20 @@ void gram_pmat() {
coopMatLoad(bh, sh_kqh, kk, LDP, COL);
coopMatLoad(bl, sh_kql, kk, LDP, COL);
PRODUCT(x, ah, al, bh, bl);
coopMatPerElementNV(state[kk / KT], state[kk / KT], StoreHi, kk);
coopMatPerElementNV(state[kk / KT], state[kk / KT], StoreLo, kk);
}
coopMatPerElementNV(x, x, StoreGramPmat);
}
void invert() {
// The elimination steps only write registers; store_inverse() runs after the
// S*K^T/S*Q^T products, so the compiler can overlap the steps with them.
void invert(out float x[C / (2 * NSUB)]) {
const uint col = gl_SubgroupInvocationID % C;
// Each half-subgroup covers all columns of its assigned rows.
const uint section = gl_SubgroupInvocationID / C;
const uint row_base = (gl_SubgroupID * 2u + section) * (C / (2 * NSUB));
// Keep the diagonal zero so pivots at or above the row do nothing.
float x[C / (2 * NSUB)];
[[unroll]] for (uint j = 0; j < C / (2 * NSUB); ++j) {
const uint row = row_base + j;
x[j] = col < row ? -sh_lower[row * (row - 1) / 2 + col] : 0.0;
@@ -179,6 +184,11 @@ void invert() {
x[j] -= xp * lower;
}
}
}
void store_inverse(const in float x[C / (2 * NSUB)]) {
const uint col = gl_SubgroupInvocationID % C;
const uint row_base = (gl_SubgroupID * 2u + gl_SubgroupInvocationID / C) * (C / (2 * NSUB));
[[unroll]] for (uint j = 0; j < C / (2 * NSUB); ++j) {
const uint row = row_base + j;
split(col == row ? 1.0 : x[j], sh_ih[row * C + col], sh_il[row * C + col]);
@@ -195,17 +205,25 @@ float replay_update(const in uint32_t r, const in uint32_t c, const in float s,
return s + data_pk[k_off + c] * (beta * (data_pv[v_off + r] - dot));
}
void replay(inout coopmat<float, WG, V, D, MACC> state, uint seq_id, uint head_id, uint iq1, uint v0) {
// The products of the state blocks with their slices of k are summed per
// element first, so one row reduction gives the dot product over all of D.
void replay(inout coopmat<float, WG, V, KT, MACC> state[D / KT], uint seq_id, uint head_id, uint iq1, uint v0) {
const uint n_rep = replay_count(seq_id);
[[dont_unroll]] for (uint t = 0; t < n_rep; ++t) {
uint k_off, v_off;
float decay, beta;
replay_inputs(seq_id, head_id, iq1, t, k_off, v_off, decay, beta);
state *= decay;
coopmat<float, WG, V, D, MACC> dot;
coopMatPerElementNV(dot, state, replay_product, k_off);
coopmat<float, WG, V, KT, MACC> dot = coopmat<float, WG, V, KT, MACC>(0.0);
[[unroll]] for (uint b = 0; b < D / KT; ++b) {
state[b] *= decay;
coopmat<float, WG, V, KT, MACC> prod;
coopMatPerElementNV(prod, state[b], replay_product, k_off + b * KT);
dot += prod;
}
coopMatReduceNV(dot, dot, gl_CooperativeMatrixReduceRowNV, replay_sum);
coopMatPerElementNV(state, state, replay_update, dot, k_off, v_off + v0, beta);
[[unroll]] for (uint b = 0; b < D / KT; ++b) {
coopMatPerElementNV(state[b], state[b], replay_update, dot, k_off + b * KT, v_off + v0, beta);
}
}
}
#endif
@@ -224,8 +242,11 @@ void main() {
const uint out_base = (seq_id * p.n_tokens * p.H + head_id) * D + v0;
// Transposing the state-side products gives them V=32 rows with C=16 columns.
coopmat<float, WG, V, D, MACC> state;
coopMatLoad(state, data_state, state_base, D, ROW);
// It is kept as one [V x KT] block per K-tile.
coopmat<float, WG, V, KT, MACC> state[D / KT];
[[unroll]] for (uint t = 0; t < D / KT; ++t) {
coopMatLoad(state[t], data_state, state_base + t * KT, D, ROW);
}
#ifdef GDN_REPLAY
replay(state, seq_id, head_id, iq1, v0);
@@ -267,11 +288,10 @@ void main() {
// Current inputs are in shared memory; keep the next chunk in registers.
prefetch(t0 + C, q_base, k_base, gb_base, qreg, kreg, greg, breg);
gram_pmat();
barrier();
invert();
coopMatPerElementNV(state, state, SplitRowS);
gram_pmat(state);
barrier();
float inv[C / (2 * NSUB)];
invert(inv);
coopmat<float, WG, V, C, MACC> ks = coopmat<float, WG, V, C, MACC>(0.0), base_r = coopmat<float, WG, V, C, MACC>(0.0);
[[unroll]] for (uint kk = 0; kk < D; kk += KT) {
@@ -286,6 +306,7 @@ void main() {
PRODUCT(ks, ah, al, kh, kl);
PRODUCT(base_r, ah, al, qh, ql);
}
store_inverse(inv);
coopMatPerElementNV(base_r, base_r, ApplyExpPrefix);
coopMatPerElementNV(ks, ks, StoreDeltaV, vmat);
barrier();
@@ -300,15 +321,21 @@ void main() {
coopMatLoad(il, sh_il, 0, C, COL);
PRODUCT(solved, rh, rl, ih, il);
}
barrier();
coopMatPerElementNV(solved, solved, StoreSolved);
// The state mirror is no longer needed after KS/QS. Unlike the delta
// buffer, it needs no barrier before solved is stored there.
coopmat<float, WG, V, C, MACC> carry_solved;
coopMatPerElementNV(carry_solved, solved, ScaleCarry);
coopMatPerElementNV(carry_solved, carry_solved, StoreHi, 0u);
coopMatPerElementNV(carry_solved, carry_solved, StoreLo, 0u);
coopMatPerElementNV(solved, solved, StoreHi, uint(C));
coopMatPerElementNV(solved, solved, StoreLo, uint(C));
barrier();
{
coopmat<OPD, WG, V, C, MUA> xh, xl;
coopmat<OPD, WG, C, C, MUB> ph, pl;
coopMatLoad(xh, sh_dh, 0, LDV, COL);
coopMatLoad(xl, sh_dl, 0, LDV, COL);
coopMatLoad(xh, sh_sh, C, LDP, ROW);
coopMatLoad(xl, sh_sl, C, LDP, ROW);
coopMatLoad(ph, sh_ph, 0, C, COL);
coopMatLoad(pl, sh_pl, 0, C, COL);
PRODUCT(base_r, xh, xl, ph, pl);
@@ -316,14 +343,18 @@ void main() {
coopMatPerElementNV(base_r, base_r, StoreOut, out_base + t0 * (p.H * D), valid);
coopmat<OPD, WG, V, C, MUA> xh, xl;
coopmat<OPD, WG, C, D, MUB> kh, kl;
coopMatLoad(xh, sh_sh, 0, LDP, ROW);
coopMatLoad(xl, sh_sl, 0, LDP, ROW);
coopMatLoad(kh, sh_kqh, 0, LDP, ROW);
coopMatLoad(kl, sh_kql, 0, LDP, ROW);
state *= sh_ep[valid - 1];
PRODUCT(state, xh, xl, kh, kl);
[[unroll]] for (uint t = 0; t < D / KT; ++t) {
coopmat<OPD, WG, C, KT, MUB> kh, kl;
coopMatLoad(kh, sh_kqh, t * KT, LDP, ROW);
coopMatLoad(kl, sh_kql, t * KT, LDP, ROW);
state[t] *= sh_ep[valid - 1];
PRODUCT(state[t], xh, xl, kh, kl);
}
}
coopMatStore(state, data_dst, p.s_off + state_base, D, ROW);
[[unroll]] for (uint t = 0; t < D / KT; ++t) {
coopMatStore(state[t], data_dst, p.s_off + state_base + t * KT, D, ROW);
}
}
+3 -1
View File
@@ -17,7 +17,8 @@
#include <utility>
#include <vector>
#define GGML_ZDNN_NAME "zDNN"
#define GGML_ZDNN_NAME "zDNN"
#define GGML_ZDNN_ZTENSOR_ALIGN 4096
#define ZDNN_CHECK(stmt) \
do { \
@@ -47,6 +48,7 @@ struct ggml_backend_zdnn_buffer {
zdnn_tensor_desc pre_tfm_desc;
zdnn_tensor_desc tfm_desc;
zdnn_ztensor ztensor;
bool ztensor_in_buffer = false; // the ztensor uses the ggml buffer memory and is freed with it
std::vector<float> scales; // per-row scales for quantized weights
std::vector<float> channel_scales; // per-input-channel scales for quantized weights, applied to the inputs
+21 -3
View File
@@ -270,7 +270,9 @@ static void ggml_backend_zdnn_buffer_free_buffer(ggml_backend_buffer_t buffer) {
// Free any extra buffer allocated for the tensor. E.g., bias for GGML_OP_MUL_MAT
if (buf->extra != nullptr) free(buf->extra->data);
if (buf->ztensor.buffer_size > 0) ZDNN_CHECK(zdnn_free_ztensor_buffer(&buf->ztensor));
if (buf->ztensor.buffer_size > 0 && !buf->ztensor_in_buffer) {
ZDNN_CHECK(zdnn_free_ztensor_buffer(&buf->ztensor));
}
}
if (ctx->owned) {
@@ -427,7 +429,7 @@ static void ggml_backend_zdnn_buffer_reset(ggml_backend_buffer_t buffer) {
free(buf->extra->data);
}
if (buf->ztensor.buffer_size > 0) {
if (buf->ztensor.buffer_size > 0 && !buf->ztensor_in_buffer) {
ZDNN_CHECK(zdnn_free_ztensor_buffer(&buf->ztensor));
}
}
@@ -509,6 +511,22 @@ static size_t ggml_backend_zdnn_buffer_type_get_alignment(ggml_backend_buffer_ty
GGML_UNUSED(buft);
}
static size_t ggml_backend_zdnn_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
// views share the ztensor of their source, empty tensors have none, and the rest cannot grow
if (tensor->view_src != nullptr || ggml_is_empty(tensor) || !ggml_zdnn_ztensor_in_alloc(tensor)) {
return ggml_nbytes(tensor);
}
zdnn_tensor_desc pre_tfm_desc;
zdnn_tensor_desc tfm_desc;
ggml_zdnn_init_tensor_desc(pre_tfm_desc, tfm_desc, tensor);
// room for the ztensor after the tensor data, at the next 4K boundary
return ggml_nbytes(tensor) + GGML_ZDNN_ZTENSOR_ALIGN - 1 + zdnn_getsize_ztensor(&tfm_desc);
GGML_UNUSED(buft);
}
static bool ggml_backend_zdnn_buffer_type_is_host(ggml_backend_buffer_type_t buft) {
return true;
@@ -523,7 +541,7 @@ ggml_backend_buffer_type_t ggml_backend_zdnn_buffer_type(void) {
/* .alloc_buffer_n = */ NULL,
/* .get_alignment = */ ggml_backend_zdnn_buffer_type_get_alignment,
/* .get_max_size = */ NULL,
/* .get_alloc_size = */ NULL, // defaults to ggml_nbytes
/* .get_alloc_size = */ ggml_backend_zdnn_buffer_type_get_alloc_size, // used with autofitting
/* .get_alloc_size_n = */ NULL,
/* .is_host = */ ggml_backend_zdnn_buffer_type_is_host,
},
+38 -15
View File
@@ -1,4 +1,5 @@
#include "ggml.h"
#include "ggml-backend-impl.h"
#include "utils.hpp"
#include <algorithm>
@@ -158,7 +159,14 @@ void ggml_zdnn_load_weights(ggml_backend_zdnn_buffer * buffer, const ggml_tensor
}
}
void ggml_zdnn_init_tensor(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor) {
// ggml allows a larger allocation only for these tensors, the others keep a ztensor allocated by zDNN
bool ggml_zdnn_ztensor_in_alloc(const ggml_tensor * tensor) {
return ggml_op_is_empty(tensor->op) || ggml_is_quantized(tensor->type) || ggml_op_alloc_size_may_expand(tensor->op);
}
void ggml_zdnn_init_tensor_desc(zdnn_tensor_desc & pre_tfm_desc,
zdnn_tensor_desc & tfm_desc,
const ggml_tensor * tensor) {
if (ggml_is_quantized(tensor->type)) {
GGML_ASSERT(ggml_is_matrix(tensor));
@@ -171,26 +179,19 @@ void ggml_zdnn_init_tensor(ggml_backend_zdnn_buffer * buffer, const ggml_tensor
zdnn_init_pre_transformed_desc(
ZDNN_3DS,
INT8,
&buffer->pre_tfm_desc,
&pre_tfm_desc,
n_groups, gs, tensor->ne[1]
);
buffer->scales.resize(n_groups * tensor->ne[1]);
} else {
zdnn_init_pre_transformed_desc(
ZDNN_2D,
INT8,
&buffer->pre_tfm_desc,
&pre_tfm_desc,
tensor->ne[0], tensor->ne[1]
);
buffer->scales.resize(tensor->ne[1]);
}
buffer->channel_scales.resize(tensor->ne[0]);
ZDNN_CHECK(zdnn_generate_quantized_transformed_desc(&buffer->pre_tfm_desc, QUANTIZED_WEIGHTS_INT8, &buffer->tfm_desc));
ZDNN_CHECK(zdnn_init_quantized_ztensor_with_malloc(&buffer->pre_tfm_desc, &buffer->tfm_desc, 1.0f, 0.0f, &buffer->ztensor));
ZDNN_CHECK(zdnn_generate_quantized_transformed_desc(&pre_tfm_desc, QUANTIZED_WEIGHTS_INT8, &tfm_desc));
return;
}
@@ -200,7 +201,7 @@ void ggml_zdnn_init_tensor(ggml_backend_zdnn_buffer * buffer, const ggml_tensor
zdnn_init_pre_transformed_desc(
ZDNN_2D,
ggml_zdnn_type_mapping(tensor->type),
&buffer->pre_tfm_desc,
&pre_tfm_desc,
tensor->ne[1], tensor->ne[0]
);
} break;
@@ -214,7 +215,7 @@ void ggml_zdnn_init_tensor(ggml_backend_zdnn_buffer * buffer, const ggml_tensor
zdnn_init_pre_transformed_desc(
ZDNN_NHWC,
ggml_zdnn_type_mapping(tensor->type),
&buffer->pre_tfm_desc,
&pre_tfm_desc,
tensor->ne[3], tensor->ne[2], tensor->ne[1], tensor->ne[0]
);
@@ -224,6 +225,28 @@ void ggml_zdnn_init_tensor(ggml_backend_zdnn_buffer * buffer, const ggml_tensor
} break;
}
ZDNN_CHECK(zdnn_generate_transformed_desc(&buffer->pre_tfm_desc, &buffer->tfm_desc));
ZDNN_CHECK(zdnn_init_ztensor_with_malloc(&buffer->pre_tfm_desc, &buffer->tfm_desc, &buffer->ztensor));
ZDNN_CHECK(zdnn_generate_transformed_desc(&pre_tfm_desc, &tfm_desc));
}
void ggml_zdnn_init_tensor(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor) {
ggml_zdnn_init_tensor_desc(buffer->pre_tfm_desc, buffer->tfm_desc, tensor);
if (ggml_is_quantized(tensor->type)) {
const bool stacked = buffer->pre_tfm_desc.layout == ZDNN_3DS;
buffer->scales.resize((stacked ? buffer->pre_tfm_desc.dim3 : 1) * tensor->ne[1]);
buffer->channel_scales.resize(tensor->ne[0]);
zdnn_init_quantized_ztensor(&buffer->pre_tfm_desc, &buffer->tfm_desc, 1.0f, 0.0f, &buffer->ztensor);
} else if (ggml_zdnn_ztensor_in_alloc(tensor)) {
zdnn_init_ztensor(&buffer->pre_tfm_desc, &buffer->tfm_desc, &buffer->ztensor);
} else {
ZDNN_CHECK(zdnn_init_ztensor_with_malloc(&buffer->pre_tfm_desc, &buffer->tfm_desc, &buffer->ztensor));
return;
}
// the ztensor uses the memory after the tensor data, see ggml_backend_zdnn_buffer_type_get_alloc_size
buffer->ztensor.buffer = (void *)GGML_PAD((uintptr_t)tensor->data + ggml_nbytes(tensor), GGML_ZDNN_ZTENSOR_ALIGN);
buffer->ztensor.buffer_size = zdnn_getsize_ztensor(&buffer->tfm_desc);
buffer->ztensor_in_buffer = true;
}
+6
View File
@@ -20,6 +20,12 @@ void ggml_zdnn_load_tensor_q(ggml_backend_zdnn_buffer * buffer, const ggml_tenso
void ggml_zdnn_load_weights(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor);
bool ggml_zdnn_ztensor_in_alloc(const ggml_tensor * tensor);
void ggml_zdnn_init_tensor_desc(zdnn_tensor_desc & pre_tfm_desc,
zdnn_tensor_desc & tfm_desc,
const ggml_tensor * tensor);
void ggml_zdnn_init_tensor(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor);
#endif // GGML_ZDNN_UTILITIES_HPP
+7 -1
View File
@@ -6182,6 +6182,9 @@ struct test_gated_delta_net_replay : public test_case {
init_tensor_uniform(t, -2.0f, 2.0f);
} else if (strcmp(t->name, "pend_gb") == 0) {
// the gates < 0, then the betas in [0, 1] (element 0 of each gate group)
// Gates down to -20 leave almost nothing of the state for the replayed
// updates to depend on. Keep them mild with prefill sizes, like g.
const float g_min = n_seq_tokens >= 64 ? -0.125f : -20.0f;
std::vector<float> data(ggml_nelements(t), 0.0f);
std::uniform_real_distribution<float> u(0.0f, 1.0f);
for (int64_t s = 0; s < n_seqs; ++s) {
@@ -6189,7 +6192,7 @@ struct test_gated_delta_net_replay : public test_case {
float * row = data.data() + (s*2*n_pend + r)*g0*H;
for (int64_t h = 0; h < H; ++h) {
if (r < n_pend) {
for (int64_t j = 0; j < g0; ++j) { row[h*g0 + j] = -20.0f*u(rng) - 1e-4f; }
for (int64_t j = 0; j < g0; ++j) { row[h*g0 + j] = g_min*u(rng) - 1e-4f; }
} else {
row[h*g0] = u(rng);
}
@@ -14164,6 +14167,9 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
}
}
// add_id with more than 65535 tokens, exercises the gridDim.y limit
test_cases.emplace_back(new test_add_id(GGML_TYPE_F32, GGML_TYPE_F32, 32, 4, 2, 70000));
for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_F32}) {
test_cases.emplace_back(new test_sqr (type));
test_cases.emplace_back(new test_sqrt (type));
+92 -9
View File
@@ -648,11 +648,12 @@ class TestInkling2PackedConversion(unittest.TestCase):
decoded = packed.float() * torch.exp2(scales.float() - 127).repeat_interleave(32, -1)
return {"": packed, "_scale": scales}, decoded
def packed_checkpoint(self):
def packed_checkpoint(self, n_ff=None):
"""Layer 0 is NVFP4, layer 1 is MXFP8. Returns the checkpoint tensors, the hf_quant_config groups and the expected GGUF tensors."""
n_ff = self.N_FF if n_ff is None else n_ff
tensors, quant_groups, expected = {}, [], {}
w13_shape = (self.N_EXPERT, 2 * self.N_FF, self.N_EMBD)
w2_shape = (self.N_EXPERT, self.N_EMBD, self.N_FF)
w13_shape = (self.N_EXPERT, 2 * n_ff, self.N_EMBD)
w2_shape = (self.N_EXPERT, self.N_EMBD, n_ff)
for layer, scheme in enumerate(("nvfp4_nearest", "mxfp8_nearest")):
names = []
for projection, shape, target in (("w13", w13_shape, "gate_up"), ("w2", w2_shape, "down")):
@@ -672,13 +673,16 @@ class TestInkling2PackedConversion(unittest.TestCase):
quant_groups.append({"tensors": names, "weight_transform": scheme, "weight_scale_format": "amax_denominator", "weight_block_shape": block_shape})
return tensors, quant_groups, expected
def converter(self, path, tensors, quant_groups, ftype=gguf.LlamaFileType.ALL_F32, eager=False):
def converter(self, path, tensors, quant_groups, ftype=gguf.LlamaFileType.ALL_F32, eager=False, n_ff=None, fp8_as_q8=False, quant_config=None):
"""Writes the checkpoint to path and returns an Inkling2Model on it."""
hp = {"model_type": "inkling2_text", "architectures": ["Inkling2ForCausalLM"], "num_hidden_layers": 2, "hidden_size": self.N_EMBD, "moe_intermediate_size": self.N_FF, "n_routed_experts": self.N_EXPERT, "layer_types": ["hybrid_sliding", "hybrid"]}
n_ff = self.N_FF if n_ff is None else n_ff
hp = {"model_type": "inkling2_text", "architectures": ["Inkling2ForCausalLM"], "num_hidden_layers": 2, "hidden_size": self.N_EMBD, "moe_intermediate_size": n_ff, "n_routed_experts": self.N_EXPERT, "layer_types": ["hybrid_sliding", "hybrid"]}
if quant_config is not None:
hp["quantization_config"] = quant_config
(path / "config.json").write_text(json.dumps(hp))
(path / "hf_quant_config.json").write_text(json.dumps({"model": {"parameter_groups": quant_groups}}))
save_file(tensors, path / "model.safetensors")
return Inkling2Model(path, ftype, path / "unused.gguf", hparams=hp, eager=eager)
return Inkling2Model(path, ftype, path / "unused.gguf", hparams=hp, eager=eager, fp8_as_q8=fp8_as_q8)
def test_lookup_semantics(self):
"""The converter decode tables agree with torch.float8_e4m3fn; bytes 127 and 255 are NaN; E2M1 code 8 is -0."""
@@ -688,22 +692,24 @@ class TestInkling2PackedConversion(unittest.TestCase):
self.assertTrue(np.signbit(_E2M1[8]))
def test_mixed_schemes_and_streaming_outtypes(self):
"""Both schemes convert bit-exact to every outtype, lazily, in chunks of at most 128 rows."""
"""Explicit outtypes dequantize both schemes bit-exact, lazily, in chunks of at most 128 rows."""
tensors, quant_groups, expected = self.packed_checkpoint()
outtypes = (
(gguf.LlamaFileType.GUESSED, gguf.GGMLQuantizationType.F16),
(gguf.LlamaFileType.ALL_F32, gguf.GGMLQuantizationType.F32),
(gguf.LlamaFileType.MOSTLY_F16, gguf.GGMLQuantizationType.F16),
(gguf.LlamaFileType.MOSTLY_BF16, gguf.GGMLQuantizationType.BF16),
(gguf.LlamaFileType.MOSTLY_Q8_0, gguf.GGMLQuantizationType.Q8_0),
)
quant_config = {"quant_method": "modelopt", "quant_algo": "NVFP4"}
for eager in (False, True):
for ftype, qtype in outtypes:
with self.subTest(eager=eager, outtype=qtype), tempfile.TemporaryDirectory() as directory:
path = Path(directory)
model = self.converter(path, tensors, quant_groups, ftype, eager)
model = self.converter(path, tensors, quant_groups, ftype, eager, quant_config=quant_config)
with self.assertLogs("hf-to-gguf", level="WARNING") as logs:
model.prepare_tensors()
self.assertTrue(any("[32, 32]" in m and "[1, 32]" in m for m in logs.output))
self.assertFalse(model._is_nvfp4)
infos = model.gguf_writer.tensors[0]
self.assertEqual(infos.keys(), expected.keys())
for name, info in infos.items():
@@ -718,6 +724,83 @@ class TestInkling2PackedConversion(unittest.TestCase):
reference = gguf.quantize(expected[name], qtype)
self.assertEqual(self.written_bytes(info.tensor, path / "tensor.bin"), reference.tobytes(), name)
def test_auto_preserves_nvfp4_and_fp8_as_q8(self):
"""--outtype auto repacks NVFP4 experts lazily with per-expert scales; --fp8-as-q8 stores MXFP8 as Q8_0."""
n_ff = 192
tensors, quant_groups, expected = self.packed_checkpoint(n_ff=n_ff)
for eager in (False, True):
for fp8_as_q8 in (False, True):
with self.subTest(eager=eager, fp8_as_q8=fp8_as_q8), tempfile.TemporaryDirectory() as directory:
path = Path(directory)
model = self.converter(path, tensors, quant_groups, gguf.LlamaFileType.GUESSED, eager, n_ff=n_ff, fp8_as_q8=fp8_as_q8)
with self.assertLogs("hf-to-gguf", level="WARNING"):
model.prepare_tensors()
self.assertTrue(model._is_nvfp4)
infos = model.gguf_writer.tensors[0]
expected_keys = set(expected.keys()) | {"blk.0.ffn_gate_up_exps.scale", "blk.0.ffn_down_exps.scale"}
self.assertEqual(infos.keys(), expected_keys)
for target in ("gate_up", "down"):
w_name = f"blk.0.ffn_{target}_exps.weight"
s_name = f"blk.0.ffn_{target}_exps.scale"
w_info, s_info = infos[w_name], infos[s_name]
self.assertEqual(w_info.dtype, gguf.GGMLQuantizationType.NVFP4)
self.assertEqual(tuple(w_info.shape), expected[w_name].shape)
self.assertIsInstance(w_info.tensor, gguf.LazyChunkedTensor)
self.assertEqual(len(w_info.tensor._chunks), self.N_EXPERT)
with self.assertRaises(TypeError):
np.asarray(w_info.tensor)
raw = np.frombuffer(self.written_bytes(w_info.tensor, path / "tensor.bin"), dtype=np.uint8)
byte_shape = (expected[w_name].shape[0], expected[w_name].shape[1], expected[w_name].shape[2] // 64 * 36)
dequant = gguf.dequantize(raw.reshape(byte_shape), gguf.GGMLQuantizationType.NVFP4)
scale = np.asarray(s_info.tensor, dtype=np.float32)
self.assertEqual(s_info.dtype, gguf.GGMLQuantizationType.F32)
self.assertEqual(tuple(s_info.shape), (self.N_EXPERT,))
np.testing.assert_array_equal(dequant * scale[:, None, None], expected[w_name])
mxfp8_name = f"blk.1.ffn_{target}_exps.weight"
mxfp8_info = infos[mxfp8_name]
expected_qtype = gguf.GGMLQuantizationType.Q8_0 if fp8_as_q8 else gguf.GGMLQuantizationType.F16
self.assertEqual(mxfp8_info.dtype, expected_qtype)
reference = gguf.quantize(expected[mxfp8_name], expected_qtype)
self.assertEqual(self.written_bytes(mxfp8_info.tensor, path / "tensor.bin"), reference.tobytes(), mxfp8_name)
def test_auto_falls_back_when_nvfp4_cols_not_multiple_of_64(self):
"""NVFP4 projections whose row width is not a multiple of 64 fall back to dequantization on --outtype auto."""
tensors, quant_groups, _ = self.packed_checkpoint(n_ff=160)
with tempfile.TemporaryDirectory() as directory:
path = Path(directory)
model = self.converter(path, tensors, quant_groups, gguf.LlamaFileType.GUESSED, n_ff=160)
with self.assertLogs("hf-to-gguf", level="WARNING") as logs:
model.prepare_tensors()
self.assertTrue(any("not a multiple of 64" in m for m in logs.output))
infos = model.gguf_writer.tensors[0]
self.assertEqual(infos["blk.0.ffn_gate_up_exps.weight"].dtype, gguf.GGMLQuantizationType.NVFP4)
self.assertIn("blk.0.ffn_gate_up_exps.scale", infos)
self.assertEqual(infos["blk.0.ffn_down_exps.weight"].dtype, gguf.GGMLQuantizationType.F16)
self.assertNotIn("blk.0.ffn_down_exps.scale", infos)
def test_auto_nvfp4_rejects_invalid_scales(self):
"""Native NVFP4 preservation rejects negative or NaN block scales and invalid outer scales."""
for bad_byte in (0x80, 0x7F, 0xFF):
tensors, quant_groups, _ = self.packed_checkpoint(n_ff=192)
name = quant_groups[0]["tensors"][0]
tensors[name + "_scale"].view(torch.uint8)[1, 0, 0] = bad_byte
with self.subTest(bad_byte=hex(bad_byte)), tempfile.TemporaryDirectory() as directory:
path = Path(directory)
model = self.converter(path, tensors, quant_groups, gguf.LlamaFileType.GUESSED, n_ff=192)
model.prepare_tensors()
tensor = model.gguf_writer.tensors[0]["blk.0.ffn_gate_up_exps.weight"].tensor
with self.assertRaisesRegex(ValueError, r"w13_weight_scale expert 1"):
self.written_bytes(tensor, path / "tensor.bin")
for suffix, bad_val in (("_amax", -1.0), ("_amax", float("nan")), ("_outer_scale_denominator", 0.0)):
tensors, quant_groups, _ = self.packed_checkpoint(n_ff=192)
name = quant_groups[0]["tensors"][0]
tensors[name + suffix][-1] = bad_val
with self.subTest(suffix=suffix, bad_val=bad_val), tempfile.TemporaryDirectory() as directory:
model = self.converter(Path(directory), tensors, quant_groups, gguf.LlamaFileType.GUESSED, n_ff=192)
with self.assertRaisesRegex(ValueError, "Inkling2:"):
model.prepare_tensors()
def test_projection_and_companions_in_separate_shards(self):
"""A packed weight and its scale, amax and denominator can be in different safetensors shards."""
tensors, quant_groups, expected = self.packed_checkpoint()
@@ -197,39 +197,92 @@
border-radius: 0 0.375rem 0.375rem 0;
}
/* Tables */
/* Tables: one hairline under each row, no cell grid and no outer frame. The
header is set heavier instead of filled, so it reads without a band. */
.markdown-content :global(table) {
/* one line colour for the whole table, so a tinted surface can retint it once */
--table-line: color-mix(in oklch, var(--line-default) 55%, transparent);
width: 100%;
margin: 1.5rem 0;
margin: 1rem 0;
border-collapse: collapse;
border: 1px solid var(--line-default);
border-radius: 0.375rem;
overflow: hidden;
/* a table is reference material, so it sits a step under the prose */
font-size: 0.875rem;
line-height: 1.5;
/* a column of numbers keeps its digits under each other */
font-variant-numeric: tabular-nums;
}
.markdown-content :global(th),
.markdown-content :global(td) {
/* wide gutters carry the column separation that the vertical rules used to */
padding: 0.5rem 1.25rem;
text-align: start;
vertical-align: top;
border-bottom: 1px solid var(--table-line);
}
/* the outer columns line up with the prose above and below the table */
.markdown-content :global(:is(th, td):first-child) {
padding-inline-start: 0;
}
.markdown-content :global(:is(th, td):last-child) {
padding-inline-end: 0;
}
.markdown-content :global(th) {
background: hsl(var(--surface-muted) / 0.3);
border: 1px solid var(--line-default);
padding: 0.5rem 0.75rem;
text-align: left;
/* a header that wraps to two lines keeps its second line on the rule */
padding-block: 0.375rem 0.5rem;
font-weight: 600;
vertical-align: bottom;
}
.markdown-content :global(td) {
border: 1px solid var(--line-default);
padding: 0.5rem 0.75rem;
/* GFM column alignment arrives as an align attribute, which any authored
text-align beats, so the three cases are restated rather than inherited */
.markdown-content :global(:is(th, td)[align='left']) {
text-align: start;
}
.markdown-content :global(tr:nth-child(even)) {
background: hsl(var(--surface-muted) / 0.1);
.markdown-content :global(:is(th, td)[align='center']) {
text-align: center;
}
/* User message markdown should keep table borders visible on light primary backgrounds */
div.markdown-user-content :global(table),
div.markdown-user-content :global(th),
div.markdown-user-content :global(td),
div.markdown-user-content :global(.table-wrapper) {
border-color: currentColor;
.markdown-content :global(:is(th, td)[align='right']) {
text-align: end;
}
/* A table this wide is scrolled either way, so its columns keep a width a word
can sit on instead of crumbling to three lines each */
.markdown-content :global(.table-wrapper table:has(th:nth-child(6)) :is(th, td)) {
min-width: 7rem;
}
/* a flag or a path stays one token in its cell, and the wrapper scrolls */
.markdown-content :global(:is(th, td) code:not(pre code)) {
white-space: nowrap;
}
/* a list restored into a cell keeps the row as tight as its neighbours */
.markdown-content :global(:is(th, td) :is(ul, ol)) {
margin: 0;
padding-inline-start: 1.125rem;
}
.markdown-content :global(:is(th, td) li) {
margin-bottom: 0.125rem;
}
/* A user bubble breaks at anywhere to fit its width, which pulls a table's
columns down to a few letters each; break-word keeps the min-content width */
div.markdown-user-content :global(:is(th, td)) {
overflow-wrap: break-word;
word-break: normal;
}
/* ...and its hairlines stay visible on the tinted bubble background */
div.markdown-user-content :global(table) {
--table-line: color-mix(in oklch, currentColor 25%, transparent);
}
/* Horizontal rules */
@@ -387,21 +440,10 @@ div.markdown-user-content :global(.table-wrapper) {
}
}
/* Advanced table enhancements */
.markdown-content :global(table) {
transition: all 0.2s ease;
}
/* A row lights up under the pointer, to follow a value across a wide table */
@media (hover: hover) and (pointer: fine) {
.markdown-content :global(table:hover) {
box-shadow:
0 4px 6px -1px rgb(0 0 0 / 0.1),
0 2px 4px -2px rgb(0 0 0 / 0.1);
}
.markdown-content :global(th:hover),
.markdown-content :global(td:hover) {
background: var(--surface-muted);
.markdown-content :global(tbody tr:hover td) {
background: color-mix(in oklch, var(--surface-muted) 45%, transparent);
}
}
@@ -411,13 +453,8 @@ div.markdown-user-content :global(.table-wrapper) {
color: inherit;
}
.markdown-user-content :global(table:hover) {
box-shadow: none;
}
.markdown-user-content :global(th:hover),
.markdown-user-content :global(td:hover) {
background: inherit;
.markdown-user-content :global(tbody tr:hover td) {
background: transparent;
}
/* Enhanced blockquotes */
@@ -505,19 +542,18 @@ div.markdown-user-content :global(.table-wrapper) {
border-radius: 50%;
}
/* Scrollable tables */
/* Scrollable tables: the wrapper is only a scroll port. The hairlines belong to
the rows, so a table that fits shows no box around it */
.markdown-content :global(.table-wrapper) {
overflow-x: auto;
margin: 1.5rem 0;
border-radius: 0.5rem;
border: 1px solid var(--line-default);
margin: 1rem 0;
/* a wide table scrolls here, it does not widen the column */
max-width: 100%;
overscroll-behavior-x: contain;
}
.markdown-content :global(.table-wrapper table) {
margin: 0;
border: none;
}
/* Responsive adjustments */
@@ -534,18 +570,10 @@ div.markdown-user-content :global(.table-wrapper) {
font-size: 1.125rem;
}
.markdown-content :global(table) {
font-size: 0.875rem;
}
/* a narrower gutter, and no full-bleed: it hid the outer columns */
.markdown-content :global(th),
.markdown-content :global(td) {
padding: 0.375rem 0.5rem;
}
/* no full-bleed: it hid the outer columns */
.markdown-content :global(.table-wrapper) {
margin: 1rem 0;
padding-inline: 0.875rem;
}
}
@@ -1,5 +1,6 @@
<script lang="ts" module>
import { AI_TUTORIAL_MD } from '../fixtures/ai-tutorial.js';
import { MARKDOWN_TABLES_MD } from '../fixtures/markdown-tables.js';
import { MERMAID_DIAGRAMS_MD } from '../fixtures/mermaid-diagrams.js';
import { defineMeta } from '@storybook/addon-svelte-csf';
import { MarkdownContent } from '#lib/components/app/index.ts';
@@ -19,6 +20,48 @@
name="Default"
/>
<Story
args={{ class: 'max-w-[56rem] w-[calc(100vw-2rem)]', content: MARKDOWN_TABLES_MD }}
name="Tables"
play={async ({ canvasElement }) => {
const tables = await waitFor(() => {
const found = [...canvasElement.querySelectorAll('table')];
expect(found).toHaveLength(5);
return found;
});
const numbers = tables[1];
const sizeCell = numbers.querySelectorAll('td')[2];
const sizeHeader = numbers.querySelectorAll('th')[2];
const wrapper = numbers.closest('.table-wrapper') as HTMLElement;
// the lean look: no frame, no filled header, one hairline under each row
await expect(getComputedStyle(wrapper).borderTopWidth).toBe('0px');
await expect(getComputedStyle(sizeHeader).backgroundColor).toBe('rgba(0, 0, 0, 0)');
await expect(getComputedStyle(sizeHeader).borderBottomWidth).toBe('1px');
await expect(getComputedStyle(sizeCell).borderLeftWidth).toBe('0px');
// a right-aligned column stays aligned in the header and in the cells
await expect(getComputedStyle(sizeHeader).textAlign).toBe('end');
await expect(getComputedStyle(sizeCell).textAlign).toBe('end');
// markup models put in cells still renders: a list, and a wrapped line
await expect(canvasElement.querySelector('td ul li')).not.toBeNull();
await expect(canvasElement.querySelector('td br')).not.toBeNull();
// too many columns for the column: the wrapper scrolls, the page does not
const wide = (tables[4] as HTMLElement).closest('.table-wrapper') as HTMLElement;
await expect(wide.scrollWidth).toBeGreaterThan(wide.clientWidth);
await expect(document.documentElement.scrollWidth).toBeLessThanOrEqual(window.innerWidth);
// and it scrolls on a width a model name sits on, rather than crumbling
await expect(wide.querySelector('td')!.getBoundingClientRect().width).toBeGreaterThanOrEqual(
100
);
}}
/>
<Story
args={{ class: 'max-w-[56rem] w-[calc(100vw-2rem)]', content: MERMAID_DIAGRAMS_MD }}
name="Diagrams"
@@ -0,0 +1,48 @@
// Tables the way models write them: mixed column alignment, code and links in
// cells, numbers meant to line up, a cell that wraps, escaped pipes and empty
// cells, and one table too wide for the chat column.
const tick = '`';
export const MARKDOWN_TABLES_MD = `Here are a few tables with different alignments and content:
## Server flags
| Flag | Default | Description |
| :--- | :---: | --- |
| ${tick}--ctx-size${tick} | 4096 | Context size in tokens |
| ${tick}--parallel${tick} | 1 | Slots that serve requests at once |
| ${tick}--jinja${tick} | on | Use the model's own chat template |
## Quantization types
| Type | Bits per weight | Size (7B) | Notes |
| :--- | ---: | ---: | :--- |
| ${tick}Q4_K_M${tick} | 4.85 | 4.07 GB | A good default for most models |
| ${tick}Q5_K_M${tick} | 5.69 | 4.78 GB | A little more quality for a little more memory |
| ${tick}Q8_0${tick} | 8.50 | 7.16 GB | Close to the original weights, see [the docs](https://github.com/ggml-org/llama.cpp) |
| ${tick}F16${tick} | 16.00 | 13.50 GB | **Full** half precision |
## Build status
| Package | Status | Version | Notes |
| :--- | :--- | ---: | :--- |
| ${tick}@ggml-org/llama-ui${tick} | ✅ Passing | 0.4.2 | See [ui/lib/ui](https://github.com/ggml-org/llama.cpp/tree/master/ui/lib/ui) |
| ${tick}llama-storybook${tick} | ⚠️ Flaky | 0.3.0 | **Needs** a rerun on CI |
| ${tick}llama-brand${tick} | ❌ Failing | 0.1.9 | Missing ${tick}BRAND.md${tick} |
## Cells that hold more than a word
| Input | Output | Escaped pipe |
| :--- | :--- | :--- |
| ${tick}a \\| b${tick} | ${tick}a or b${tick} | ✔ |
| | (empty input) | ✘ |
| A list | <ul><li>first</li><li>second</li></ul> | — |
| Two lines | first<br>second | — |
## A wide table
| Model | Family | Parameters | Context | Quantization | Prompt t/s | Generation t/s | Memory | Backend | Notes |
| :--- | :--- | ---: | ---: | :--- | ---: | ---: | ---: | :--- | :--- |
| gpt-oss-20b | GPT-OSS | 20.9B | 131072 | MXFP4 | 1890.4 | 74.2 | 12.1 GB | Metal | Reasoning effort low, medium and high |
| Qwen3-8B | Qwen3 | 8.2B | 40960 | Q4_K_M | 1312.7 | 58.9 | 5.0 GB | Metal | Thinking can be turned off per request |
`;