From f505c30b92b5579e00532c9e75baa3aa74b70432 Mon Sep 17 00:00:00 2001 From: George Burton <8233643+gecBurton@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:22:46 +0000 Subject: [PATCH 001/275] mtmd: fix qwen3a audio tail (#32697) * add: test to reporduce error reported in https://github.com/ggml-org/llama.cpp/issues/32689 * fix: remove extra tokens from zero-padding of Qwen3-Omni / Qwen3-ASR audio * add: qwen3a_tokens_for_frames instead of magic numbers * refactor: only ggml_pad when required * refactor: move qwen3a_tokens_for_frames as static member of mtmd_graph_qwen3a and add test * remove: trailing empty line --------- Co-authored-by: george burton --- tests/test-mtmd-impl.cpp | 65 ++++++++++++++++++++++++++++++++++++ tools/mtmd/models/models.h | 4 +++ tools/mtmd/models/qwen3a.cpp | 17 +++++++--- tools/mtmd/mtmd-audio.cpp | 32 +++++++++--------- tools/mtmd/mtmd-audio.h | 1 + tools/mtmd/mtmd-model.cpp | 15 ++++++--- 6 files changed, 109 insertions(+), 25 deletions(-) diff --git a/tests/test-mtmd-impl.cpp b/tests/test-mtmd-impl.cpp index e24365e5969b..0c34f9c2bcce 100644 --- a/tests/test-mtmd-impl.cpp +++ b/tests/test-mtmd-impl.cpp @@ -609,6 +609,50 @@ MAKE_TEST(test_audio_preprocessor_whisper_chunks) { } } +MAKE_TEST(test_audio_preprocessor_qwen3a_tail) { + mtmd_hparams hparams; + hparams.n_mel_bins = 128; + hparams.audio_sample_rate = 16000; + hparams.audio_n_fft = 400; + hparams.audio_window_len = 400; + hparams.audio_hop_len = 160; + + ggml_backend_ptr backend(ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr)); + ggml_backend_t backends[] = { backend.get() }; + ggml_backend_sched_ptr sched(ggml_backend_sched_new(backends, nullptr, 1, 256, false, true)); + + mtmd_audio_preprocessor_qwen3a preproc(hparams, sched.get()); + preproc.initialize(); + + // one 800-frame window covers 128000 samples (hop 160), so longer audio is split; + // the last window is emitted with its exact frame count, the graph pads the final 100-frame chunk + // { sample count, expected n_len of each output window } + const std::vector>> cases = { + { 0, {} }, + { 1, {1} }, + { 32000, {200} }, + { 128000, {800} }, + { 128160, {800, 1} }, + { 168000, {800, 250} }, + { 170080, {800, 263} }, + { 176000, {800, 300} }, + }; + + for (const auto & [n_samples, expected] : cases) { + const std::string name = std::to_string(n_samples) + " samples"; + std::vector samples(n_samples, 0.0f); + if (n_samples > 0) { + samples.back() = 0.5f; + } + mtmd_audio_preproc_out out = preproc.preprocess(samples.data(), samples.size()); + t.assert_equal("windows for " + name, expected.size(), out.entries.size()); + for (size_t i = 0; i < out.entries.size(); i++) { + t.assert_equal("frames for " + name, expected[i], out.entries[i].nx()); + t.assert_equal("mel bins for " + name, 128, out.entries[i].ny()); + } + } +} + MAKE_TEST(test_audio_preprocessor_conformer) { mtmd_hparams hparams; hparams.n_mel_bins = 128; @@ -1062,6 +1106,27 @@ MAKE_TEST(test_kokoro_istft) { t.assert_true("constant signal, max error " + std::to_string(max_err), max_err < 1e-4f); } +// 13 tokens per 100-frame chunk; the tail is ceil^3 (one halving per stride-2 conv layer) +MAKE_TEST(test_qwen3a_tokens_for_frames) { + const std::vector> cases = { + { 0, 0 }, + { 1, 1 }, + { 99, 13 }, + { 100, 13 }, + { 101, 14 }, + { 110, 15 }, + { 200, 26 }, + { 210, 28 }, + { 1000, 130 }, + { 1024, 133 }, + }; + + for (const auto & [frames, expected] : cases) { + const std::string name = std::to_string(frames) + " frames"; + t.assert_equal(name, expected, mtmd_graph_qwen3a::qwen3a_tokens_for_frames(frames)); + } +} + // // main // diff --git a/tools/mtmd/models/models.h b/tools/mtmd/models/models.h index 278fcdb27eb3..c1feef493aab 100644 --- a/tools/mtmd/models/models.h +++ b/tools/mtmd/models/models.h @@ -387,6 +387,10 @@ struct mtmd_graph_mobilenetv5 : mtmd_graph { struct mtmd_graph_qwen3a : mtmd_graph { mtmd_graph_qwen3a(mtmd_subcontext * ctx, const mtmd_image_f32 & img) : mtmd_graph(ctx, img) {} ggml_cgraph * build() override; + + // audio tokens from n_frames mel frames: 13 per 100-frame chunk, ceil^3(tail) otherwise. + // shared with mtmd_model::n_output_tokens so they cannot drift + static int64_t qwen3a_tokens_for_frames(int64_t n_frames); }; struct mtmd_graph_mimo_audio : mtmd_graph { diff --git a/tools/mtmd/models/qwen3a.cpp b/tools/mtmd/models/qwen3a.cpp index 0ed6b9a8f537..24588f0c4579 100644 --- a/tools/mtmd/models/qwen3a.cpp +++ b/tools/mtmd/models/qwen3a.cpp @@ -6,14 +6,19 @@ ggml_cgraph * mtmd_graph_qwen3a::build() { // inp_raw: [n_frames, n_mel, 1] (nx=n_frames, ny=n_mel) ggml_tensor * inp = build_inp_raw(1); - const int64_t n_frames = inp->ne[0]; // total frames, padded to multiple of chunk_size const int64_t n_mel = inp->ne[1]; // 128 const int64_t chunk_size = 100; // n_window * 2 (n_window=50 from model config) - const int64_t n_chunks = n_frames / chunk_size; + const int64_t n_chunks = (inp->ne[0] + chunk_size - 1) / chunk_size; + const int64_t n_pre_pad = inp->ne[0]; - GGML_ASSERT(n_frames % chunk_size == 0); // preprocessor should already pad the input GGML_ASSERT(inp->type == GGML_TYPE_F32); + // zero-pad the last chunk to chunk_size, as the reference pads all chunks to the longest one + if (n_pre_pad % chunk_size > 0) { + inp = ggml_pad(ctx0, inp, n_chunks * chunk_size - n_pre_pad, 0, 0, 0); + } + const int64_t n_frames = inp->ne[0]; + // View mel spectrogram as batched 100-frame chunks: [chunk_size, n_mel, 1, n_chunks] inp = ggml_view_4d(ctx0, inp, chunk_size, n_mel, 1, n_chunks, @@ -69,7 +74,11 @@ ggml_cgraph * mtmd_graph_qwen3a::build() { inp = ggml_add(ctx0, inp, ggml_repeat(ctx0, pos_tmp, tgt)); } - ggml_tensor * cur = build_vit(inp, n_pos, + // drop the outputs of the padding in the last chunk + const int64_t n_out = qwen3a_tokens_for_frames(n_pre_pad); + inp = ggml_view_2d(ctx0, inp, inp->ne[0], n_out, inp->nb[1], 0); + + ggml_tensor * cur = build_vit(inp, n_out, NORM_TYPE_NORMAL, hparams.ffn_op, nullptr, // pos embd already added above nullptr); diff --git a/tools/mtmd/mtmd-audio.cpp b/tools/mtmd/mtmd-audio.cpp index 53c2cbb27676..e0b27b9a5443 100644 --- a/tools/mtmd/mtmd-audio.cpp +++ b/tools/mtmd/mtmd-audio.cpp @@ -594,9 +594,10 @@ bool mtmd_audio_preprocessor_whisper::process(const float * samp // // Matches the Python WhisperFeatureExtractor called with truncation=False: // - reflection padding of n_fft/2 samples at each end (center=True) -// - Whisper-style log10 + (max-8)/4 normalization applied to full audio -// - output split into ≤30s (3000 mel frames) windows, each padded to a -// multiple of 200 frames (n_window * 2) for the cgraph batch view +// - the last STFT frame is dropped, giving n_samples / hop_length frames +// - Whisper-style log10 + (max-8)/4 normalization over the kept frames +// - output split into 800-frame (n_window_infer) windows; the graph +// zero-pads the last 100-frame chunk // void mtmd_audio_preprocessor_qwen3a::initialize() { @@ -648,11 +649,17 @@ bool mtmd_audio_preprocessor_qwen3a::process(const float * sampl return false; } - // Whisper-style normalization: clamp to (max - 8), scale to [-1, 1] - { + // WhisperFeatureExtractor drops the last STFT frame, keeping n_samples / hop_length frames; + // sub-hop clips would give 0 frames, clamp to 1 so the cgraph stays non-empty + const int64_t n_eff = std::max(1, std::min(mel_full.n_len - 1, (int64_t)(n_samples / hparams.audio_hop_len))); + + // Whisper-style normalization over the kept frames: clamp to (max - 8), scale to [-1, 1] + if (!shape_only) { double mmax = -1e20; - for (float v : mel_full.data) { - if (v > mmax) mmax = v; + for (int64_t m = 0; m < mel_full.n_mel; m++) { + for (int64_t t = 0; t < n_eff; t++) { + mmax = std::max(mmax, (double)mel_full.data[m * mel_full.n_len + t]); + } } mmax -= 8.0; for (float & v : mel_full.data) { @@ -660,25 +667,16 @@ bool mtmd_audio_preprocessor_qwen3a::process(const float * sampl } } - // The effective frame count: center-padded STFT gives ~n_samples/hop_length frames. - // We take min(mel_full.n_len, n_samples/hop + 1) to avoid including excess frames. - const int64_t n_eff = std::min(mel_full.n_len, - (int64_t)(n_samples / hparams.audio_hop_len) + 1); - // Split into inference windows matching n_window_infer=800 from model config. - // Each window is padded to the next multiple of chunk_size for the cgraph. // The mtmd caller loops over output entries, so long audio is handled automatically. - const int chunk_size = 100; // conv sub-chunk size (n_window * 2, n_window=50) const int window_size = 800; // mel frames per forward pass (n_window_infer=800) for (int64_t off = 0; off < n_eff; off += window_size) { const int64_t win_eff = std::min((int64_t)window_size, n_eff - off); - const int64_t n_chunks = (win_eff + chunk_size - 1) / chunk_size; - const int64_t n_padded = n_chunks * chunk_size; mtmd_audio_mel out; out.n_mel = mel_full.n_mel; - out.n_len = n_padded; + out.n_len = win_eff; out.n_len_org = win_eff; out.data.assign((size_t)out.n_mel * (size_t)out.n_len, 0.0f); for (int64_t m = 0; m < out.n_mel; m++) { diff --git a/tools/mtmd/mtmd-audio.h b/tools/mtmd/mtmd-audio.h index 6d282721dd71..4ee78827617d 100644 --- a/tools/mtmd/mtmd-audio.h +++ b/tools/mtmd/mtmd-audio.h @@ -208,6 +208,7 @@ struct mtmd_audio_preprocessor_gemma4ua : mtmd_audio_preprocessor { struct mtmd_audio_preprocessor_qwen3a : mtmd_audio_preprocessor { mtmd_audio_preprocessor_qwen3a(const mtmd_model * model) : mtmd_audio_preprocessor(model) {} + mtmd_audio_preprocessor_qwen3a(const mtmd_hparams & hparams, ggml_backend_sched_t sched) : mtmd_audio_preprocessor(hparams, sched) {} void initialize() override; bool process(const float * samples, size_t n_samples, std::vector & output, bool shape_only) const override; diff --git a/tools/mtmd/mtmd-model.cpp b/tools/mtmd/mtmd-model.cpp index 570750b9b988..97dc47598ccc 100644 --- a/tools/mtmd/mtmd-model.cpp +++ b/tools/mtmd/mtmd-model.cpp @@ -4737,6 +4737,16 @@ int mtmd_model::n_output_tokens_y(const mtmd_image_f32 * img) const { return 1; } +int64_t mtmd_graph_qwen3a::qwen3a_tokens_for_frames(int64_t n_frames) { + const int64_t chunk_size = 100; // n_window * 2 + const int64_t tokens_per_chunk = 13; // 100 -> 50 -> 25 -> 13 after 3x stride-2 conv2d + const int64_t n_full = n_frames / chunk_size; + const int64_t n_tail = n_frames % chunk_size; + // ceil(ceil(ceil(n_tail / 2) / 2) / 2), one halving per conv layer + const int64_t n_tail_tokens = n_tail == 0 ? 0 : (((n_tail + 1) / 2 + 1) / 2 + 1) / 2; + return n_full * tokens_per_chunk + n_tail_tokens; +} + int mtmd_model::n_output_tokens(const mtmd_image_f32 * img) const { const auto & params = hparams; @@ -4946,10 +4956,7 @@ int mtmd_model::n_output_tokens(const mtmd_image_f32 * img) const { } break; case PROJECTOR_TYPE_QWEN3A: { - // chunk_size=100 frames --> 3x stride-2 conv2d --> 13 tokens per chunk - const int chunk_size = 100; - const int tokens_per_chunk = 13; - n_patches = (img->nx() / chunk_size) * tokens_per_chunk; + n_patches = (int) mtmd_graph_qwen3a::qwen3a_tokens_for_frames(img->nx()); } break; case PROJECTOR_TYPE_GLMA: { From 94f3af3d09e74a0fb35f703194318d3b4037714a Mon Sep 17 00:00:00 2001 From: yoch Date: Sun, 22 Nov 2026 23:04:24 +0200 Subject: [PATCH 002/275] mtmd: speed up shared audio FFT (#32815) * mtmd: speed up shared audio FFT Replace recursive radix-2 splitting with iterative stages and batch the existing odd-size DFT across subsequences, preserving the previous operation order. Input buffers now hold only N real values for FFT or 2N interleaved floats for inverse FFT. Add test_audio_fft for forward and inverse transforms. Assisted-by: Claude * nits --------- Co-authored-by: Xuan Son Nguyen --- tests/test-mtmd-impl.cpp | 58 ++++++++++ tools/mtmd/mtmd-audio.cpp | 224 ++++++++++++++++++-------------------- tools/mtmd/mtmd-audio.h | 8 +- 3 files changed, 168 insertions(+), 122 deletions(-) diff --git a/tests/test-mtmd-impl.cpp b/tests/test-mtmd-impl.cpp index 0c34f9c2bcce..319811b77315 100644 --- a/tests/test-mtmd-impl.cpp +++ b/tests/test-mtmd-impl.cpp @@ -881,6 +881,64 @@ static double tone_amplitude(const std::vector & x, double freq, int rate return 2.0 * std::sqrt(re * re + im * im) / (x.size() - 2 * skip); } +MAKE_TEST(test_audio_fft) { + // the sizes in use: powers of two, and an odd part (400 = 16 * 25, 736 = 32 * 23, 1920 = 128 * 15) + // plus small edge cases: 4 = gather + one stage, 6 = n_odd 3 with n_sub 2, 15 = odd composite with n_sub 1 + const int sizes[] = { 1, 2, 3, 4, 6, 12, 15, 256, 400, 512, 736, 1920 }; + const double pi = 3.14159265358979323846; + for (int n : sizes) { + mtmd_audio_cache cache; + cache.fill_sin_cos_table(n); + // phase offset so that x[0] != 0 (n = 1 would otherwise compare all zeros) + std::vector x(2 * n); + for (int i = 0; i < 2 * n; i++) { + x[i] = (float) std::sin(0.37 * i + 0.001 * i * i + 0.5); + } + std::vector out(8 * n); + for (bool inv : { false, true }) { + // input sized exactly as documented so that sanitizers catch any overread + const std::vector in(x.begin(), x.begin() + (inv ? 2 * n : n)); + if (inv) { + mtmd_audio_ifft(cache, in.data(), n, out.data()); + } else { + mtmd_audio_fft(cache, in.data(), n, out.data()); + } + double max_err = 0.0, max_ref = 0.0; + for (int k = 0; k < n; k++) { + double re = 0.0, im = 0.0; + for (int j = 0; j < n; j++) { + const double theta = (inv ? 2 : -2) * pi * (double) ((int64_t) j * k % n) / n; + const double a = inv ? x[2 * j] : x[j]; + const double b = inv ? x[2 * j + 1] : 0.0; + re += a * std::cos(theta) - b * std::sin(theta); + im += a * std::sin(theta) + b * std::cos(theta); + } + if (inv) { + re /= n; + im /= n; + } + max_err = std::max({ max_err, std::fabs(re - out[2 * k]), std::fabs(im - out[2 * k + 1]) }); + max_ref = std::max({ max_ref, std::fabs(re), std::fabs(im) }); + } + t.assert_true(std::string(inv ? "ifft" : "fft") + " n = " + std::to_string(n) + ", relative error " + std::to_string(max_err / max_ref), + max_ref > 0.0 && max_err <= 1e-5 * max_ref); + } + + // round trip: ifft(fft(x)) == x for real x + std::vector spec(8 * n); + mtmd_audio_fft(cache, x.data(), n, spec.data()); + const std::vector spec_in(spec.begin(), spec.begin() + 2 * n); + mtmd_audio_ifft(cache, spec_in.data(), n, out.data()); + double max_err = 0.0, max_ref = 0.0; + for (int k = 0; k < n; k++) { + max_err = std::max({ max_err, (double) std::fabs(out[2 * k] - x[k]), (double) std::fabs(out[2 * k + 1]) }); + max_ref = std::max(max_ref, (double) std::fabs(x[k])); + } + t.assert_true("fft round trip n = " + std::to_string(n) + ", relative error " + std::to_string(max_err / max_ref), + max_ref > 0.0 && max_err <= 1e-5 * max_ref); + } +} + static std::vector resample_chunked(mtmd_helper_resampler * rs, const std::vector & in, size_t chunk) { std::vector res; for (size_t off = 0; off < in.size(); off += chunk) { diff --git a/tools/mtmd/mtmd-audio.cpp b/tools/mtmd/mtmd-audio.cpp index e0b27b9a5443..bfea3a364a48 100644 --- a/tools/mtmd/mtmd-audio.cpp +++ b/tools/mtmd/mtmd-audio.cpp @@ -129,152 +129,140 @@ void mtmd_audio_cache::fill_mel_filterbank_matrix(int64_t n_mel, } } -// Unified DFT implementation for both forward and inverse transforms +// FFT/IFFT of N = n_sub * n_odd points (n_sub a power of two, n_odd odd): batched odd-size DFT of the n_sub subsequences into bit-reversed blocks, then iterative radix-2 stages +// matches the previous recursive implementation for finite inputs (the twiddle-1 multiply of the first stage is skipped when n_odd == 1) // Template parameters: -// Inverse: false = DFT with exp(-2πi·k·n/N), no scaling -// true = IDFT with exp(+2πi·k·n/N), scales by 1/N -// RealInput: true = input is real-valued (stride 1), avoids imaginary computations -// false = input is complex-valued (interleaved real/imag, stride 2) -template -static void dft_impl(const mtmd_audio_cache & cache, const float * in, int N, float * out) { - const int n_sin_cos_vals = cache.sin_vals.size(); - const int sin_cos_step = n_sin_cos_vals / N; - - constexpr float sign = Inverse ? 1.0f : -1.0f; - const float scale = Inverse ? (1.0f / N) : 1.0f; - - for (int k = 0; k < N; k++) { - float re = 0; - float im = 0; - - for (int n = 0; n < N; n++) { - int idx = (k * n * sin_cos_step) % n_sin_cos_vals; - float cos_val = cache.cos_vals[idx]; - float sin_val = cache.sin_vals[idx]; - - if constexpr (RealInput) { - // Real input: in_im = 0, simplifies to: - // re += in_re * cos_val - // im += sign * in_re * sin_val - float in_re = in[n]; - re += in_re * cos_val; - im += sign * in_re * sin_val; - } else { - float in_re = in[n * 2 + 0]; - float in_im = in[n * 2 + 1]; - // (a + bi) * (cos + sign*i*sin) = (a*cos - sign*b*sin) + (sign*a*sin + b*cos)i - re += in_re * cos_val - sign * in_im * sin_val; - im += sign * in_re * sin_val + in_im * cos_val; - } - } - - out[k * 2 + 0] = re * scale; - out[k * 2 + 1] = im * scale; - } -} - -// Cooley-Tukey FFT/IFFT unified implementation -// Template parameters: -// Inverse: false = FFT with exp(-2πi·k/N), no scaling -// true = IFFT with exp(+2πi·k/N), scales by 0.5 at each level +// Inverse: false = FFT with exp(-2 pi i k / N), no scaling +// true = IFFT with exp(+2 pi i k / N), scales by 1/N (1/n_odd in the DFT, 0.5 per stage) // RealInput: true = input is real-valued (stride 1) // false = input is complex-valued (interleaved real/imag, stride 2) +// in is not modified, out needs 2 * N floats + 2 * max(N / 2, n_sub) floats of scratch template -static void fft_impl(const mtmd_audio_cache & cache, float * in, int N, float * out) { +static void fft_impl(const mtmd_audio_cache & cache, const float * in, int N, float * out) { GGML_ASSERT(N > 0); const int n_sin_cos_vals = cache.sin_vals.size(); - if (N == 1) { - out[0] = in[0]; - if constexpr (RealInput) { - out[1] = 0.0f; - } else { - out[1] = in[1]; - } - return; - } + constexpr float sign = Inverse ? 1.0f : -1.0f; + constexpr float scale = Inverse ? 0.5f : 1.0f; + constexpr int n_in = RealInput ? 1 : 2; // floats per input value - const int half_N = N / 2; - if (N - half_N * 2 == 1) { - // Odd N: fall back to DFT - dft_impl(cache, in, N, out); - return; + int n_odd = N; + while (n_odd % 2 == 0) { + n_odd /= 2; } + const int n_sub = N / n_odd; - // Split into even and odd - if constexpr (RealInput) { - // Real input: stride is 1, copy only real values - float * even = in + N; - for (int i = 0; i < half_N; ++i) { - even[i] = in[2 * i]; + // j = bitrev(r) for r = 0, 1, ...: add 1 to j starting from its highest bit h + auto bitrev_next = [](int & j, int h) { + for (; j & h; h >>= 1) { + j ^= h; } - float * even_fft = out + 2 * N; - fft_impl(cache, even, half_N, even_fft); + j |= h; + }; - float * odd = even; - for (int i = 0; i < half_N; ++i) { - odd[i] = in[2 * i + 1]; + float * scratch = out + 2 * N; + int len = 2 * n_odd; // size of the blocks after the next stage + if (n_odd > 1) { + const int sin_cos_step = n_sin_cos_vals / n_odd; + const float dft_scale = Inverse ? (1.0f / n_odd) : 1.0f; + float * acc = scratch; + for (int k = 0; k < n_odd; k++) { + std::fill(acc, acc + 2 * n_sub, 0.0f); + int idx = 0; // (k * n * sin_cos_step) % n_sin_cos_vals + for (int n = 0; n < n_odd; n++) { + const float cos_val = cache.cos_vals[idx]; + const float sin_val = cache.sin_vals[idx]; + const float * x = in + n * n_sub * n_in; + for (int r = 0; r < n_sub; r++) { + if constexpr (RealInput) { + acc[2 * r + 0] += x[r] * cos_val; + acc[2 * r + 1] += sign * x[r] * sin_val; + } else { + // (a + bi) * (cos + sign*i*sin) = (a*cos - sign*b*sin) + (sign*a*sin + b*cos)i + acc[2 * r + 0] += x[2 * r + 0] * cos_val - sign * x[2 * r + 1] * sin_val; + acc[2 * r + 1] += sign * x[2 * r + 0] * sin_val + x[2 * r + 1] * cos_val; + } + } + idx += k * sin_cos_step; + if (idx >= n_sin_cos_vals) { + idx -= n_sin_cos_vals; + } + } + for (int r = 0, j = 0; r < n_sub; r++, bitrev_next(j, n_sub / 2)) { + out[2 * (j * n_odd + k) + 0] = acc[2 * r + 0] * dft_scale; + out[2 * (j * n_odd + k) + 1] = acc[2 * r + 1] * dft_scale; + } } - float * odd_fft = even_fft + N; - fft_impl(cache, odd, half_N, odd_fft); + } else if (N == 1) { + out[0] = in[0]; + out[1] = RealInput ? 0.0f : in[1]; + return; } else { - // Complex input: stride is 2, copy complex pairs - float * even = in + N * 2; - for (int i = 0; i < half_N; ++i) { - even[i * 2 + 0] = in[2 * i * 2 + 0]; - even[i * 2 + 1] = in[2 * i * 2 + 1]; + // size 1 subsequences: the values r and r + N / 2 form block bitrev(r) of the first stage + const int half_N = N / 2; + for (int j = 0, r = 0; j < half_N; j++, bitrev_next(r, half_N / 2)) { + const float * a = in + r * n_in; + const float * b = in + (r + half_N) * n_in; + if constexpr (RealInput) { + out[4 * j + 0] = scale * (a[0] + b[0]); + out[4 * j + 1] = 0.0f; + out[4 * j + 2] = scale * (a[0] - b[0]); + out[4 * j + 3] = 0.0f; + } else { + out[4 * j + 0] = scale * (a[0] + b[0]); + out[4 * j + 1] = scale * (a[1] + b[1]); + out[4 * j + 2] = scale * (a[0] - b[0]); + out[4 * j + 3] = scale * (a[1] - b[1]); + } } - float * even_fft = out + 2 * N; - fft_impl(cache, even, half_N, even_fft); - - float * odd = even; - for (int i = 0; i < half_N; ++i) { - odd[i * 2 + 0] = in[(2 * i + 1) * 2 + 0]; - odd[i * 2 + 1] = in[(2 * i + 1) * 2 + 1]; + len = 4; + } + + for (; len <= N; len *= 2) { + const int half_N = len / 2; + const int sin_cos_step = n_sin_cos_vals / len; + // twiddles of this stage, contiguous + float * twiddle = scratch; + for (int k = 0; k < half_N; k++) { + twiddle[2 * k + 0] = cache.cos_vals[k * sin_cos_step]; // t = 2*M_PI*k/len + twiddle[2 * k + 1] = sign * cache.sin_vals[k * sin_cos_step]; + } + for (int i = 0; i < N; i += len) { + float * even_fft = out + 2 * i; + float * odd_fft = even_fft + 2 * half_N; + for (int k = 0; k < half_N; k++) { + const float re = twiddle[2 * k + 0]; + const float im = twiddle[2 * k + 1]; + const float re_even = even_fft[2 * k + 0]; + const float im_even = even_fft[2 * k + 1]; + const float re_odd = odd_fft[2 * k + 0]; + const float im_odd = odd_fft[2 * k + 1]; + + even_fft[2 * k + 0] = scale * (re_even + re * re_odd - im * im_odd); + even_fft[2 * k + 1] = scale * (im_even + re * im_odd + im * re_odd); + + odd_fft[2 * k + 0] = scale * (re_even - re * re_odd + im * im_odd); + odd_fft[2 * k + 1] = scale * (im_even - re * im_odd - im * re_odd); + } } - float * odd_fft = even_fft + N; - fft_impl(cache, odd, half_N, odd_fft); - } - - float * even_fft = out + 2 * N; - float * odd_fft = even_fft + N; - - const int sin_cos_step = n_sin_cos_vals / N; - - constexpr float sign = Inverse ? 1.0f : -1.0f; - constexpr float scale = Inverse ? 0.5f : 1.0f; - - for (int k = 0; k < half_N; k++) { - int idx = k * sin_cos_step; // t = 2*M_PI*k/N - float re = cache.cos_vals[idx]; - float im = sign * cache.sin_vals[idx]; - - float re_odd = odd_fft[2 * k + 0]; - float im_odd = odd_fft[2 * k + 1]; - - out[2 * k + 0] = scale * (even_fft[2 * k + 0] + re * re_odd - im * im_odd); - out[2 * k + 1] = scale * (even_fft[2 * k + 1] + re * im_odd + im * re_odd); - - out[2 * (k + half_N) + 0] = scale * (even_fft[2 * k + 0] - re * re_odd + im * im_odd); - out[2 * (k + half_N) + 1] = scale * (even_fft[2 * k + 1] - re * im_odd - im * re_odd); } } // Forward FFT for real input (used by mel spectrogram) -static void fft(const mtmd_audio_cache & cache, float * in, int N, float * out) { +static void fft(const mtmd_audio_cache & cache, const float * in, int N, float * out) { fft_impl(cache, in, N, out); } // Inverse FFT for complex input -static void ifft(const mtmd_audio_cache & cache, float * in, int N, float * out) { +static void ifft(const mtmd_audio_cache & cache, const float * in, int N, float * out) { fft_impl(cache, in, N, out); } -void mtmd_audio_fft(const mtmd_audio_cache & cache, float * in, int N, float * out) { +void mtmd_audio_fft(const mtmd_audio_cache & cache, const float * in, int N, float * out) { fft(cache, in, N, out); } -void mtmd_audio_ifft(const mtmd_audio_cache & cache, float * in, int N, float * out) { +void mtmd_audio_ifft(const mtmd_audio_cache & cache, const float * in, int N, float * out) { ifft(cache, in, N, out); } @@ -1955,7 +1943,7 @@ mtmd_audio_zonos3_synth::mtmd_audio_zonos3_synth(const std::vector & mixe b.n_fft = n_fft[i]; b.cache.fill_sin_cos_table(b.n_fft); b.cache.fill_hann_window(b.n_fft, true); - b.ifft_in.assign((size_t) b.n_fft * 2 * 4, 0.0f); + b.ifft_in.assign((size_t) b.n_fft * 2, 0.0f); b.ifft_out.assign((size_t) b.n_fft * 2 * 4, 0.0f); b.mix_in.assign((size_t) h, 0.0f); b.mix_avail = h; @@ -2116,7 +2104,7 @@ mtmd_audio_streaming_istft::mtmd_audio_streaming_istft(int n_fft, int hop_length overlap_buffer(n_fft, 0.0f), window_sum_buffer(n_fft, 0.0f), padding_to_remove((n_fft - hop_length) / 2), - ifft_in(n_fft * 2 * 4, 0.0f), // extra space for recursive IFFT + ifft_in(n_fft * 2, 0.0f), ifft_out(n_fft * 2 * 4, 0.0f) { GGML_ASSERT(n_fft > 0 && hop_length > 0 && hop_length <= n_fft); cache.fill_sin_cos_table(n_fft); diff --git a/tools/mtmd/mtmd-audio.h b/tools/mtmd/mtmd-audio.h index 4ee78827617d..269e78cc40f5 100644 --- a/tools/mtmd/mtmd-audio.h +++ b/tools/mtmd/mtmd-audio.h @@ -52,10 +52,10 @@ struct mtmd_audio_cache { ); }; -// FFT of N real samples -> N complex values (interleaved), in needs 2 * N floats and out 8 * N floats (scratch) -void mtmd_audio_fft(const mtmd_audio_cache & cache, float * in, int N, float * out); -// inverse FFT of N complex values (interleaved), scaled by 1 / N; in and out need 8 * N floats (scratch) -void mtmd_audio_ifft(const mtmd_audio_cache & cache, float * in, int N, float * out); +// FFT of N real samples -> N complex values (interleaved), in holds N floats, out needs 8 * N floats (scratch) +void mtmd_audio_fft(const mtmd_audio_cache & cache, const float * in, int N, float * out); +// inverse FFT of N complex values (interleaved), scaled by 1 / N; in holds 2 * N floats, out needs 8 * N floats (scratch) +void mtmd_audio_ifft(const mtmd_audio_cache & cache, const float * in, int N, float * out); // compute one log10-mel frame from n_fft windowed samples, cache must be initialized for n_fft void mtmd_audio_log_mel_frame(const mtmd_audio_cache & cache, const float * samples, int n_fft, int n_mel, float * out); From 253671d8825729b607aeb7ad1ffc38547480c392 Mon Sep 17 00:00:00 2001 From: Xuan-Son Nguyen Date: Mon, 23 Nov 2026 01:20:22 +0100 Subject: [PATCH 003/275] chat: fix LFM2.5-VL template detection (#32843) --- common/chat.cpp | 2 +- models/templates/LFM2.5-VL.jinja | 92 ++++++++++++++++++++++++++++++++ tests/test-chat.cpp | 2 + 3 files changed, 95 insertions(+), 1 deletion(-) create mode 100644 models/templates/LFM2.5-VL.jinja diff --git a/common/chat.cpp b/common/chat.cpp index 3cff920cf16b..b6eac61f87ed 100644 --- a/common/chat.cpp +++ b/common/chat.cpp @@ -1406,7 +1406,7 @@ static common_chat_params_init_fn common_chat_template_detect_params_init(const } // LFM2.5 format detection: template uses plain "List of tools: [...]" with no special tokens - if (src.find("List of tools: [") != std::string::npos && + if (src.find("List of tools: ") != std::string::npos && src.find("<|tool_list_start|>") == std::string::npos) { LOG_DBG("Using specialized template: LFM2.5\n"); return common_chat_params_init_lfm2_5; diff --git a/models/templates/LFM2.5-VL.jinja b/models/templates/LFM2.5-VL.jinja new file mode 100644 index 000000000000..d409984f9902 --- /dev/null +++ b/models/templates/LFM2.5-VL.jinja @@ -0,0 +1,92 @@ +{{- bos_token -}} +{%- set keep_past_thinking = keep_past_thinking | default(false) -%} + +{%- macro format_arg_value(arg_value) -%} + {%- if arg_value is string -%} + {{- '"' + arg_value + '"' -}} + {%- elif arg_value is mapping -%} + {{- arg_value | tojson -}} + {%- else -%} + {{- arg_value | string -}} + {%- endif -%} +{%- endmacro -%} + +{%- macro parse_content(content) -%} + {%- if content is string -%} + {{- content -}} + {%- else -%} + {%- set _ns = namespace(result="") -%} + {%- for item in content -%} + {%- if item.type == "image" -%} + {%- set _ns.result = _ns.result + "" -%} + {%- elif item.type == "text" -%} + {%- set _ns.result = _ns.result + item.text -%} + {%- else -%} + {%- set _ns.result = _ns.result + item | tojson -%} + {%- endif -%} + {%- endfor -%} + {{- _ns.result -}} + {%- endif -%} +{%- endmacro -%} + +{%- macro render_tool_calls(tool_calls) -%} + {%- set tool_calls_ns = namespace(tool_calls=[]) -%} + {%- for tool_call in tool_calls -%} + {%- set func_name = tool_call.function.name -%} + {%- set func_args = tool_call.function.arguments -%} + {%- set args_ns = namespace(arg_strings=[]) -%} + {%- for arg_name, arg_value in func_args.items() -%} + {%- set args_ns.arg_strings = args_ns.arg_strings + [arg_name + "=" + format_arg_value(arg_value)] -%} + {%- endfor -%} + {%- set tool_calls_ns.tool_calls = tool_calls_ns.tool_calls + [func_name + "(" + (args_ns.arg_strings | join(", ")) + ")"] -%} + {%- endfor -%} + {{- "<|tool_call_start|>[" + (tool_calls_ns.tool_calls | join(", ")) + "]<|tool_call_end|>" -}} +{%- endmacro -%} + +{%- set ns = namespace(system_prompt="", last_assistant_index=-1) -%} +{%- if messages[0].role == "system" -%} + {%- if messages[0].content is defined -%} + {%- set ns.system_prompt = parse_content(messages[0].content) -%} + {%- endif -%} + {%- set messages = messages[1:] -%} +{%- endif -%} +{%- if tools -%} + {%- set ns.system_prompt = ns.system_prompt + ("\n\n" if ns.system_prompt else "") + "Today's date: " + strftime_now("%Y-%m-%d") + "\n\nList of tools: " + (tools | tojson) -%} +{%- endif -%} +{%- if ns.system_prompt -%} + {{- "<|im_start|>system\n" + ns.system_prompt + "<|im_end|>\n" -}} +{%- endif -%} +{%- for message in messages -%} + {%- if message.role == "assistant" -%} + {%- set ns.last_assistant_index = loop.index0 -%} + {%- endif -%} +{%- endfor -%} +{%- for message in messages -%} + {{- "<|im_start|>" + message.role + "\n" -}} + {%- if message.role == "assistant" -%} + {%- generation -%} + {%- if message.thinking is defined and (keep_past_thinking or loop.index0 == ns.last_assistant_index) -%} + {{- "" + message.thinking + "" -}} + {%- endif -%} + {%- if message.tool_calls is defined -%} + {{- render_tool_calls(message.tool_calls) -}} + {%- endif -%} + {%- if message.content is defined -%} + {%- set content = parse_content(message.content) -%} + {%- if not keep_past_thinking and loop.index0 != ns.last_assistant_index -%} + {%- if "" in content -%} + {%- set content = content.split("")[-1] | trim -%} + {%- endif -%} + {%- endif -%} + {{- content + ("" if (continue_final_message and loop.last) else "<|im_end|>\n") -}} + {%- endif -%} + {%- endgeneration -%} + {%- else %} + {%- if message.content is defined -%} + {{- parse_content(message.content) + "<|im_end|>\n" -}} + {%- endif -%} + {%- endif %} +{%- endfor -%} +{%- if add_generation_prompt -%} + {{- "<|im_start|>assistant\n" -}} +{%- endif -%} diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp index 11fa68f6a736..341e7acebd9d 100644 --- a/tests/test-chat.cpp +++ b/tests/test-chat.cpp @@ -6012,6 +6012,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { "models/templates/LFM2-8B-A1B.jinja", "models/templates/LFM2.5-Instruct.jinja", "models/templates/LFM2.5-8B-A1B.jinja", + "models/templates/LFM2.5-VL.jinja", }) { test_lfm2_parser(tmpl, detailed_debug); } @@ -8215,6 +8216,7 @@ static void test_template_generation_prompt() { "models/templates/LFM2-8B-A1B.jinja", "models/templates/LFM2.5-Instruct.jinja", "models/templates/LFM2.5-8B-A1B.jinja", + "models/templates/LFM2.5-VL.jinja", }) { auto tmpls = read_templates(tmpl); check(tmpls, basic(), "<|im_start|>assistant\n"); From f4f6f2e7db76e98c95cc9b7fc608ea669c806044 Mon Sep 17 00:00:00 2001 From: Alexey Kopytko Date: Mon, 23 Nov 2026 09:48:16 +0900 Subject: [PATCH 004/275] ggml-backend : generic fallback in ggml_backend_tensor_memset (#32574) --- ggml/src/ggml-backend-impl.h | 3 +- ggml/src/ggml-backend.cpp | 12 +++++- ggml/src/ggml-rpc/ggml-rpc.cpp | 4 -- src/llama-impl.cpp | 10 ----- src/llama-impl.h | 2 - src/llama-kv-cache.cpp | 12 +++--- src/llama-memory-recurrent.cpp | 6 +-- tests/test-backend-tensor.cpp | 67 ++++++++++++++++++++++++++++++++-- 8 files changed, 86 insertions(+), 30 deletions(-) diff --git a/ggml/src/ggml-backend-impl.h b/ggml/src/ggml-backend-impl.h index 545880b068c7..aaec8ac41d80 100644 --- a/ggml/src/ggml-backend-impl.h +++ b/ggml/src/ggml-backend-impl.h @@ -57,8 +57,9 @@ extern "C" { void * (*get_base) (ggml_backend_buffer_t buffer); // (optional) initialize a tensor in the buffer (eg. add tensor extras) enum ggml_status (*init_tensor)(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor); - // tensor data access + // (optional) fill tensor data with a value, ggml_backend_tensor_memset falls back to set_tensor void (*memset_tensor)(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, uint8_t value, size_t offset, size_t size); + // tensor data access void (*set_tensor) (ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size); void (*get_tensor) (ggml_backend_buffer_t buffer, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size); // (optional) 2d data copies diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp index d598ca3d86d1..8e175649b14d 100644 --- a/ggml/src/ggml-backend.cpp +++ b/ggml/src/ggml-backend.cpp @@ -761,7 +761,17 @@ void ggml_backend_tensor_memset(struct ggml_tensor * tensor, uint8_t value, size GGML_ASSERT(buf != NULL && "tensor buffer not set"); GGML_ASSERT(tensor->data != NULL && "tensor not allocated"); GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor write out of bounds"); - GGML_ASSERT(buf->iface.memset_tensor != NULL && "memset not implemented by backend buffer"); + + if (buf->iface.memset_tensor == NULL) { + GGML_ASSERT(buf->iface.set_tensor != NULL && "memset not implemented by backend buffer"); + + // fallback: write the value in chunks with set_tensor + const std::vector chunk(std::min(size, (size_t) 1024*1024), value); + for (size_t chunk_offset = 0; chunk_offset < size; chunk_offset += chunk.size()) { + ggml_backend_tensor_set(tensor, chunk.data(), offset + chunk_offset, std::min(size - chunk_offset, chunk.size())); + } + return; + } buf->iface.memset_tensor(buf, tensor, value, offset, size); } diff --git a/ggml/src/ggml-rpc/ggml-rpc.cpp b/ggml/src/ggml-rpc/ggml-rpc.cpp index e4a84cb0caf0..dbd7dd467709 100644 --- a/ggml/src/ggml-rpc/ggml-rpc.cpp +++ b/ggml/src/ggml-rpc/ggml-rpc.cpp @@ -1683,10 +1683,6 @@ bool rpc_server::memset_tensor(const rpc_msg_memset_tensor_req & request) { LOG_ERROR("[%s] tensor region out of buffer bounds\n", __func__); return false; } - if (tensor->buffer->iface.memset_tensor == nullptr) { - LOG_ERROR("[%s] memset not implemented by backend buffer\n", __func__); - return false; - } LOG_DBG2("[%s] tensor: %s, buffer: %p, data: %p, offset: %" PRIu64 ", size: %s, value: %u\n", __func__, rpc_log_format_tensor(tensor).c_str(), (void *) tensor->buffer, tensor->data, request.offset, diff --git a/src/llama-impl.cpp b/src/llama-impl.cpp index 4ca836ca66c3..9c39c921c00c 100644 --- a/src/llama-impl.cpp +++ b/src/llama-impl.cpp @@ -88,16 +88,6 @@ void llama_log_callback_default(ggml_log_level level, const char * text, void * fflush(stderr); } -void llama_clear_tensor_data(ggml_tensor * t, size_t offset, size_t size) { - static const std::vector zeros(1024*1024, 0); - - // not all backend buffers implement ggml_backend_tensor_memset(), so write zeros instead - // TODO: make this a generic fallback in `ggml_backend_tensor_memset` when `set_tensor` is available - for (size_t ofs = 0; ofs < size; ofs += zeros.size()) { - ggml_backend_tensor_set(t, zeros.data(), offset + ofs, std::min(size - ofs, zeros.size())); - } -} - void replace_all(std::string & s, const std::string & search, const std::string & replace) { if (search.empty()) { return; diff --git a/src/llama-impl.h b/src/llama-impl.h index 884dca647995..927657ba4025 100644 --- a/src/llama-impl.h +++ b/src/llama-impl.h @@ -96,8 +96,6 @@ struct buffer_view { } }; -void llama_clear_tensor_data(ggml_tensor * t, size_t offset, size_t size); - void replace_all(std::string & s, const std::string & search, const std::string & replace); // TODO: rename to llama_format ? diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index fbe422a2717a..bb546f7cdec8 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -2919,10 +2919,10 @@ void llama_kv_cache::state_clear(llama_seq_id seq_id, uint32_t strm, const slot_ const size_t k_size_row = ggml_row_size(k->type, n_embd_k_gqa); if (is_contiguous) { - llama_clear_tensor_data(k, sinfo.head() * k_size_row, cell_count * k_size_row); + ggml_backend_tensor_memset(k, 0, sinfo.head() * k_size_row, cell_count * k_size_row); } else { for (uint32_t i = 0; i < cell_count; ++i) { - llama_clear_tensor_data(k, sinfo.idxs[0][i] * k_size_row, k_size_row); + ggml_backend_tensor_memset(k, 0, sinfo.idxs[0][i] * k_size_row, k_size_row); } } } @@ -2941,10 +2941,10 @@ void llama_kv_cache::state_clear(llama_seq_id seq_id, uint32_t strm, const slot_ const size_t v_size_row = ggml_row_size(v->type, n_embd_v_gqa); if (is_contiguous) { - llama_clear_tensor_data(v, sinfo.head() * v_size_row, cell_count * v_size_row); + ggml_backend_tensor_memset(v, 0, sinfo.head() * v_size_row, cell_count * v_size_row); } else { for (uint32_t i = 0; i < cell_count; ++i) { - llama_clear_tensor_data(v, sinfo.idxs[0][i] * v_size_row, v_size_row); + ggml_backend_tensor_memset(v, 0, sinfo.idxs[0][i] * v_size_row, v_size_row); } } } else { @@ -2954,12 +2954,12 @@ void llama_kv_cache::state_clear(llama_seq_id seq_id, uint32_t strm, const slot_ const uint32_t h = sinfo.head(); for (uint32_t j = 0; j < n_embd_v_gqa; ++j) { - llama_clear_tensor_data(v, (h + j * cells.size()) * v_size_el, cell_count * v_size_el); + ggml_backend_tensor_memset(v, 0, (h + j * cells.size()) * v_size_el, cell_count * v_size_el); } } else { for (uint32_t j = 0; j < n_embd_v_gqa; ++j) { for (uint32_t i = 0; i < cell_count; ++i) { - llama_clear_tensor_data(v, (sinfo.idxs[0][i] + j * cells.size()) * v_size_el, v_size_el); + ggml_backend_tensor_memset(v, 0, (sinfo.idxs[0][i] + j * cells.size()) * v_size_el, v_size_el); } } } diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp index 2bb8ef18c118..0d5739695186 100644 --- a/src/llama-memory-recurrent.cpp +++ b/src/llama-memory-recurrent.cpp @@ -1265,17 +1265,17 @@ void llama_memory_recurrent::state_clear(llama_seq_id seq_id, uint32_t cell_head for (uint32_t il = 0; il < n_layer; ++il) { if (r_l[il] != nullptr) { const size_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r()); - llama_clear_tensor_data(r_l[il], cell_head * r_size_row, cell_count * r_size_row); + ggml_backend_tensor_memset(r_l[il], 0, cell_head * r_size_row, cell_count * r_size_row); } if (s_l[il] != nullptr) { const size_t s_size_row = ggml_row_size(s_l[il]->type, hparams.n_embd_s()); - llama_clear_tensor_data(s_l[il], cell_head * s_size_row, cell_count * s_size_row); + ggml_backend_tensor_memset(s_l[il], 0, cell_head * s_size_row, cell_count * s_size_row); } if (p_l[il] != nullptr) { const size_t p_size_row = ggml_row_size(p_l[il]->type, hparams.ple_conv_state()); - llama_clear_tensor_data(p_l[il], cell_head * p_size_row, cell_count * p_size_row); + ggml_backend_tensor_memset(p_l[il], 0, cell_head * p_size_row, cell_count * p_size_row); } } } diff --git a/tests/test-backend-tensor.cpp b/tests/test-backend-tensor.cpp index 84c4dc2bd30f..3f480a9ec3b8 100644 --- a/tests/test-backend-tensor.cpp +++ b/tests/test-backend-tensor.cpp @@ -357,14 +357,17 @@ static bool test_buft(ggml_backend_buffer_type_t buft) { // Mock buffer type // // Ad-hoc host-backed buffer type used to exercise the dispatch logic in -// ggml_backend_tensor_{set,get,copy}_n without relying on real backend hooks. +// ggml_backend_tensor_{set,get,copy}_n and ggml_backend_tensor_memset +// without relying on real backend hooks. // struct mock_config { + bool memset; bool set_n; bool get_n; bool cpy_n; bool cpy_n_result; + int set_calls; int set_n_calls; int get_n_calls; int cpy_n_calls; @@ -373,10 +376,12 @@ struct mock_config { static mock_config g_mock = {}; static void mock_config_reset(bool set_n, bool get_n, bool cpy_n, bool cpy_n_result) { + g_mock.memset = true; g_mock.set_n = set_n; g_mock.get_n = get_n; g_mock.cpy_n = cpy_n; g_mock.cpy_n_result = cpy_n_result; + g_mock.set_calls = 0; g_mock.set_n_calls = 0; g_mock.get_n_calls = 0; g_mock.cpy_n_calls = 0; @@ -397,6 +402,7 @@ static void mock_buffer_memset_tensor(ggml_backend_buffer_t buffer, struct ggml_ } static void mock_buffer_set_tensor(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) { + g_mock.set_calls++; memcpy((char *) tensor->data + offset, data, size); GGML_UNUSED(buffer); @@ -466,7 +472,7 @@ static ggml_backend_buffer_t mock_buft_alloc_buffer(ggml_backend_buffer_type_t b /* .free_buffer = */ mock_buffer_free_buffer, /* .get_base = */ mock_buffer_get_base, /* .init_tensor = */ NULL, - /* .memset_tensor = */ mock_buffer_memset_tensor, + /* .memset_tensor = */ NULL, /* .set_tensor = */ mock_buffer_set_tensor, /* .get_tensor = */ mock_buffer_get_tensor, /* .set_tensor_2d = */ NULL, @@ -478,6 +484,7 @@ static ggml_backend_buffer_t mock_buft_alloc_buffer(ggml_backend_buffer_type_t b /* .get_tensor_n = */ NULL, /* .cpy_tensor_n = */ NULL, }; + if (g_mock.memset) iface.memset_tensor = mock_buffer_memset_tensor; if (g_mock.set_n) iface.set_tensor_n = mock_buffer_set_tensor_n; if (g_mock.get_n) iface.get_tensor_n = mock_buffer_get_tensor_n; if (g_mock.cpy_n) iface.cpy_tensor_n = mock_buffer_cpy_tensor_n; @@ -665,13 +672,67 @@ static bool test_mock_grouping() { return true; } +// verify that memset routes to memset_tensor when the buffer has it and to set_tensor otherwise +static bool test_mock_memset(bool with_hook) { + mock_config_reset(false, false, false, true); + g_mock.memset = with_hook; + + ggml_init_params params = {}; + params.mem_size = ggml_tensor_overhead(); + params.no_alloc = true; + + ggml_context_ptr ctx(ggml_init(params)); + if (!ctx) { + return false; + } + + // the fallback writes in chunks of this size, see ggml_backend_tensor_memset + const size_t chunk_size = 1024*1024; + const int n_chunks = 2; + + std::vector tensors; + ggml_backend_buffer_ptr buf = alloc_tensors(ctx.get(), mock_buft(), { n_chunks*chunk_size/sizeof(float) }, tensors); + if (!buf) { + return false; + } + + const size_t n_bytes = ggml_nbytes(tensors[0]); + + // leaves untouched bytes at both ends + const size_t offset = 3; + const size_t size = n_bytes - 2*offset; + + std::vector expected(n_bytes, 0), out(n_bytes, 0); + memset(expected.data() + offset, 0xA5, size); + + ggml_backend_tensor_set(tensors[0], out.data(), 0, n_bytes); + + g_mock.set_calls = 0; + ggml_backend_tensor_memset(tensors[0], 0xA5, offset, size); + ggml_backend_tensor_get(tensors[0], out.data(), 0, n_bytes); + + if (out != expected) { + return false; + } + + // the hook writes without set_tensor, the fallback with one set_tensor call per chunk + const int expected_calls = with_hook ? 0 : n_chunks; + if (g_mock.set_calls != expected_calls) { + return false; + } + + return true; +} + static bool test_mock() { return test_mock_set_get_n(true) && test_mock_set_get_n(false) && test_mock_copy_n(true) && test_mock_copy_n(false) && - test_mock_grouping(); + test_mock_grouping() && + test_mock_memset(true) && + test_mock_memset(false); } int main() { From 7778de0c3fe4c4b05857d0abaad6195e470b6515 Mon Sep 17 00:00:00 2001 From: Aman Gupta Date: Mon, 23 Nov 2026 10:32:56 +0800 Subject: [PATCH 005/275] tests : compare only the guaranteed GDN snapshot slots (#32820) --- tests/test-backend-ops.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 91ff4c86a5f3..ca415adf0950 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -5366,6 +5366,14 @@ struct test_gated_delta_net : public test_case { // lower bound of the log-gate; a mild gate keeps the state alive over the whole sequence const float g_min; + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "GATED_DELTA_NET"; + } + + // compare only the view returned by build_graph, not the full op output + bool run_whole_graph() override { return K > 1 && n_seq_tokens > K; } + std::string vars() override { std::string s = VARS_TO_STR13(type, head_count, head_size, n_seq_tokens, n_seqs, v_repeat, permuted, kda, K, correlated, padded_v, padded_q, permuted_k); if (g_min != -20.0f) { @@ -5423,6 +5431,10 @@ struct test_gated_delta_net : public test_case { k = ggml_cpy(ctx, k, k_permuted); } ggml_tensor * out = ggml_gated_delta_net(ctx, q, k, v, g, beta, state, K); + if (K > 1 && n_seq_tokens > K) { + // n_tokens > K: only slot 0 is guaranteed, so keep the scores and slot 0 + out = ggml_view_2d(ctx, out, out->ne[0], out->ne[1] - (K - 1) * head_size * n_seqs, out->nb[1], 0); + } return out; } From 44d50873b56b568c28ef2ad8d6445069feaa9fbd Mon Sep 17 00:00:00 2001 From: lhez Date: Sun, 22 Nov 2026 18:46:40 -0800 Subject: [PATCH 006/275] opencl: add q4_k coop-k c8 GEMM for spec verify (#32716) * opencl: add q4_k coop-k c8 GEMM for spec verify Co-authored-by: Hongqiang Wang Assisted-by: Codex * opencl: enable q4_k c8 GEMM for n >= 2 for X2 --------- Co-authored-by: Hongqiang Wang --- ggml/src/ggml-opencl/CMakeLists.txt | 1 + ggml/src/ggml-opencl/ggml-opencl.cpp | 249 +++++++++++++++++- .../gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl | 187 +++++++++++++ 3 files changed, 428 insertions(+), 9 deletions(-) create mode 100644 ggml/src/ggml-opencl/kernels/gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl diff --git a/ggml/src/ggml-opencl/CMakeLists.txt b/ggml/src/ggml-opencl/CMakeLists.txt index aadf5ddb3321..d71802c0385c 100644 --- a/ggml/src/ggml-opencl/CMakeLists.txt +++ b/ggml/src/ggml-opencl/CMakeLists.txt @@ -226,6 +226,7 @@ set(GGML_OPENCL_KERNELS gemm_noshuffle_q4_0_q8_1_dp4a gemm_coopk_q4_0_q8_1_dp4a gemm_coopk_q4_k_q8_1_dp4a + gemm_coopk_q4_k_q8_1_dp4a_bin_c8 gemm_coopk_q6_k_q8_1_dp4a pack_b_f16_coopmat gemm_noshuffle_q4_0_f32_coopmat diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index d35c6d047167..c2f3b874a29f 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -1514,6 +1514,15 @@ struct ggml_backend_opencl_context { cl_kernel kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c2 = nullptr; int nsg_coopk_dp4a_q4_k_bin_c4 = 8; int nsg_coopk_dp4a_q4_k_bin_c2 = 8; + cl_kernel kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8 = nullptr; + cl_kernel kernel_quant_a_q8_1_k4 = nullptr; + int nsg_coopk_dp4a_q4_k_bin_c8 = 4; + cl_mem coopk_c8_qa_image = nullptr; + cl_mem coopk_c8_qa_buffer = nullptr; + size_t coopk_c8_qa_image_bytes = 0; + cl_mem coopk_c8_ds_image = nullptr; + cl_mem coopk_c8_ds_buffer = nullptr; + size_t coopk_c8_ds_image_bytes = 0; cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_c4 = nullptr; cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_c2 = nullptr; int nsg_coopk_dp4a_q6_k = 8; @@ -1521,6 +1530,22 @@ struct ggml_backend_opencl_context { #endif // GGML_OPENCL_USE_ADRENO_KERNELS ~ggml_backend_opencl_context() { +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + for (cl_kernel kernel : { + kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8, + kernel_quant_a_q8_1_k4 + } + ) { + if (kernel != nullptr) { + CL_CHECK(clReleaseKernel(kernel)); + } + } + for (cl_mem image : {coopk_c8_qa_image, coopk_c8_ds_image}) { + if (image != nullptr) { + CL_CHECK(clReleaseMemObject(image)); + } + } +#endif for (cl_kernel kernel : { kernel_mul_mm_f16_f32_kq_p8, kernel_mul_mm_q8_f32_kqv, @@ -1851,13 +1876,22 @@ static bool ggml_cl_coopk_dp4a_narrow_on(const ggml_backend_opencl_context * bac // COOPK_NSG sizes the local reduction buffer, so a smaller workgroup requires a rebuild. static cl_program ggml_cl_build_program_coopk(ggml_backend_opencl_context * backend_ctx, const char * kernel_src, const char * kernel_name, - const std::string & opts_base, int & nsg) { + const std::string & opts_base, int & nsg, bool fatal = true) { while (nsg >= 2) { const std::string opts = opts_base + " -DCOOPK_NSG=" + std::to_string(nsg); - cl_program program = build_program_from_source(backend_ctx, kernel_src, opts); + cl_program program = build_program_from_source(backend_ctx, kernel_src, opts, fatal); + if (program == nullptr) { + return nullptr; + } cl_int err; cl_kernel kernel = clCreateKernel(program, kernel_name, &err); - CL_CHECK(err); + if (err != CL_SUCCESS) { + CL_CHECK(clReleaseProgram(program)); + if (fatal) { + CL_CHECK(err); + } + return nullptr; + } size_t max_workgroup_size = 0; CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup_size), &max_workgroup_size, NULL)); @@ -1871,6 +1905,46 @@ static cl_program ggml_cl_build_program_coopk(ggml_backend_opencl_context * back return nullptr; } +static void load_cl_kernel_coopk_q4_k_bin_c8(ggml_backend_opencl_context * backend_ctx) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl"); +#endif + cl_program program = ggml_cl_build_program_coopk(backend_ctx, kernel_src.c_str(), + "kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8", backend_ctx->kernel_compile_opts, + backend_ctx->nsg_coopk_dp4a_q4_k_bin_c8, false); + if (program == nullptr) { + return; + } + + cl_int err; + + cl_kernel gemm = clCreateKernel(program, "kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8", &err); + if (err != CL_SUCCESS) { + CL_CHECK(clReleaseProgram(program)); + return; + } + + cl_kernel quant = clCreateKernel(program, "kernel_quant_a_q8_1_k4", &err); + CL_CHECK(clReleaseProgram(program)); + if (err != CL_SUCCESS) { + CL_CHECK(clReleaseKernel(gemm)); + return; + } + + if (backend_ctx->get_kernel_workgroup_size(quant) < 64) { + CL_CHECK(clReleaseKernel(gemm)); + CL_CHECK(clReleaseKernel(quant)); + return; + } + + backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8 = gemm; + backend_ctx->kernel_quant_a_q8_1_k4 = quant; +} + static void ggml_cl_coopk_build_narrow(ggml_backend_opencl_context * backend_ctx, const std::string & kernel_src, const char * kernel_name, int rows, int & nsg, cl_kernel & kernel_c4, cl_kernel & kernel_c2) { @@ -1940,8 +2014,12 @@ static void load_cl_kernels_gemm_coopk(ggml_backend_opencl_context * backend_ctx backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_c4, backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_c2); - const char * env = getenv("GGML_OPENCL_COOPK_Q4_K_BIN"); - if (use_adreno_bin_kernels(backend_ctx) && (!env || !*env || atoi(env) != 0)) { + static const bool use_coopk_bin = [] { + const char * env = getenv("GGML_OPENCL_COOPK_Q4_K_BIN"); + return !env || !*env || atoi(env) != 0; + }(); + + if (use_adreno_bin_kernels(backend_ctx) && use_coopk_bin) { const std::string base_opts = backend_ctx->kernel_compile_opts + " -DCOOPK_Q_BIN=1 -DCOOPK_ROWS=" + std::to_string(backend_ctx->rows_coopk_dp4a_q4_k); for (int cols = 4; cols >= 2; cols -= 2) { @@ -1965,6 +2043,7 @@ static void load_cl_kernels_gemm_coopk(ggml_backend_opencl_context * backend_ctx } nsg = nsg_eff; } + load_cl_kernel_coopk_q4_k_bin_c8(backend_ctx); } GGML_LOG_CONT("."); } @@ -28117,6 +28196,69 @@ static void ggml_cl_mul_mat_q8_0_f32_adreno(ggml_backend_t backend, const ggml_t } #ifdef GGML_OPENCL_USE_ADRENO_KERNELS +// make sure the image1d_buffer `image` is a proper view of `buffer` by either +// creating a new image1d_buffer or reuse existing one. +// upon success, `image_buffer` is set to the cl_mem in `buffer` and +// `image_bytes` the size in `buffer` and `image` is the image1d_buffer. +static bool ggml_cl_coopk_c8_image( + ggml_backend_opencl_context * backend_ctx, + ggml_cl_buffer & buffer, + size_t bytes, + cl_mem & image, + cl_mem & image_buffer, + size_t & image_bytes +) { + // required bytes exceed image1d_buffer limit + if (bytes / 16 > backend_ctx->image_max_buffer_size) { + return false; + } + // existing image1d_buffer can be reused + if (image != nullptr && image_buffer == buffer.buffer && image_bytes >= bytes) { + return true; + } + // a new one is needed, so release the existing one + if (image != nullptr) { + CL_CHECK(clReleaseMemObject(image)); + image = nullptr; + } + + image_buffer = nullptr; + image_bytes = 0; + + cl_image_format format = {CL_RGBA, CL_UNSIGNED_INT32}; + cl_image_desc desc = {}; + desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + desc.image_width = bytes / 16; + desc.buffer = buffer.buffer; + + cl_int err; + image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &format, &desc, nullptr, &err); + if (err != CL_SUCCESS) { + image = nullptr; + return false; + } + + image_buffer = buffer.buffer; + image_bytes = bytes; + return true; +} + +static int ggml_cl_coopk_ksplit(const ggml_backend_opencl_context * backend_ctx, int base_wg, int n_blocks) { + const int cu = MAX(1, (int) backend_ctx->fa.compute_units); + int ksplit = 1; + float best_eff = 0.0f; + for (int k = 1; k <= MIN(8, n_blocks); ++k) { + const int wg = base_wg * k; + const int waves = CEIL_DIV(wg, cu); + const float eff = (float) wg / (waves * cu); + if (eff > best_eff + 0.06f) { + best_eff = eff; + ksplit = k; + } + } + return ksplit; +} + static void ggml_cl_mul_mat_q4_k_f32_adreno_ila(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { GGML_ASSERT(src0); @@ -28154,11 +28296,100 @@ static void ggml_cl_mul_mat_q4_k_f32_adreno_ila(ggml_backend_t backend, const gg int N = ne1; int K = ne00; + const int coopk_c8_min_n = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E ? 2 : 5; + if (backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8 != nullptr && + N >= coopk_c8_min_n && N <= 8 && M > 0 && K > 0 && M % 256 == 0 && K % 256 == 0 && + src0->ne[0] == K && src0->ne[1] == M && dst->ne[1] == N && + K <= INT_MAX / 8 && (int64_t) M * K / 8 <= INT_MAX && + src0->ne[2] == 1 && src0->ne[3] == 1 && src0->view_src == nullptr && + src1->ne[2] == 1 && src1->ne[3] == 1 && dst->ne[2] == 1 && dst->ne[3] == 1 && + ggml_is_contiguous(src1) && ggml_is_contiguous(dst) + ) { + const int kb = K / 32; + const size_t qa_bytes = (size_t)8 * K; + const size_t ds_bytes = (size_t)16 * kb * sizeof(cl_half); + + backend_ctx->prealloc_moe_qa.allocate(context, qa_bytes); + backend_ctx->prealloc_moe_da.allocate(context, ds_bytes); + + if (ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_qa, qa_bytes, + backend_ctx->coopk_c8_qa_image, backend_ctx->coopk_c8_qa_buffer, backend_ctx->coopk_c8_qa_image_bytes) && + ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_da, ds_bytes, + backend_ctx->coopk_c8_ds_image, backend_ctx->coopk_c8_ds_buffer, backend_ctx->coopk_c8_ds_image_bytes) + ) { + const int n_blocks = N * kb; + + cl_kernel quant = backend_ctx->kernel_quant_a_q8_1_k4; + CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(quant, 4, sizeof(int), &n_blocks)); + CL_CHECK(clSetKernelArg(quant, 5, sizeof(int), &kb)); + + size_t quant_local[] = {64}; + size_t quant_global[] = {(size_t)8 * kb}; + backend_ctx->enqueue_ndrange_kernel(quant, 1, quant_global, quant_local, dst); + + int ksplit = ggml_cl_coopk_ksplit(backend_ctx, M / 256, kb); + if (backend_ctx->kernel_gemv_splitk_reduce_f32 == nullptr) { + ksplit = 1; + } + + cl_mem out = extrad->data_device; + cl_ulong out_offset = offsetd; + + if (ksplit > 1) { + backend_ctx->prealloc_splitk_partial.allocate(context, (size_t)ksplit * M * N * sizeof(float)); + out = backend_ctx->prealloc_splitk_partial.buffer; + out_offset = 0; + } + + const cl_uchar mask_d6 = 0x3F; + const cl_uchar mask_d4 = 0x0F; + const cl_uchar mask_hi2 = 0xC0; + + const size_t nsg = backend_ctx->nsg_coopk_dp4a_q4_k_bin_c8; + cl_kernel gemm = backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8; + + CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0_q4_k->q)); + CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0_q4_k->s)); + CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0_q4_k->d)); + CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &extra0_q4_k->dm)); + CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->coopk_c8_qa_image)); + CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->coopk_c8_ds_image)); + CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &out)); + CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_ulong), &out_offset)); + CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(gemm, 11, sizeof(cl_uchar), &mask_d6)); + CL_CHECK(clSetKernelArg(gemm, 12, sizeof(cl_uchar), &mask_d4)); + CL_CHECK(clSetKernelArg(gemm, 13, sizeof(cl_uchar), &mask_hi2)); + CL_CHECK(clSetKernelArg(gemm, 14, sizeof(int), &ksplit)); + + size_t local[] = {64, nsg, 1}; + size_t global[] = {(size_t)M / 4, nsg * ksplit, 1}; + backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); + + if (ksplit > 1) { + const int rows = M * N; + cl_kernel reduce = backend_ctx->kernel_gemv_splitk_reduce_f32; + CL_CHECK(clSetKernelArg(reduce, 0, sizeof(cl_mem), &out)); + CL_CHECK(clSetKernelArg(reduce, 1, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(reduce, 2, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(reduce, 3, sizeof(int), &rows)); + CL_CHECK(clSetKernelArg(reduce, 4, sizeof(int), &ksplit)); + size_t reduce_local[] = {64}; + size_t reduce_global[] = {(size_t)CEIL_DIV(rows, 64) * 64}; + backend_ctx->enqueue_ndrange_kernel(reduce, 1, reduce_global, reduce_local, dst); + } + return; + } + } + // CoopK handles with _bin use the bin weight layout (uint-transposed q), with K-major Q8_1 activations (K contiguous). - // This switch disables only this bin-layout path; weight conversion is unchanged. - static const char * env_coopk_bin = getenv("GGML_OPENCL_COOPK_Q4_K_BIN"); - const bool use_coopk_bin = !env_coopk_bin || !*env_coopk_bin || atoi(env_coopk_bin) != 0; - if (use_coopk_bin && ne1 >= 2 && ne1 <= 4 && + if (ne1 >= 2 && ne1 <= 4 && ggml_cl_coopk_dp4a_narrow_on(backend_ctx, dst, backend_ctx->rows_coopk_dp4a_q4_k) && backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c4 != nullptr && ((ne1 <= 2) ? backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c2 diff --git a/ggml/src/ggml-opencl/kernels/gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl b/ggml/src/ggml-opencl/kernels/gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl new file mode 100644 index 000000000000..15f79cbe1d91 --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl @@ -0,0 +1,187 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#ifdef cl_khr_integer_dot_product +#pragma OPENCL EXTENSION cl_khr_integer_dot_product : enable +#endif + +#ifndef COOPK_NSG +#define COOPK_NSG 4 +#endif +#define COK_SG 64 +#define COK_ROWS 4 + +#define COK_PACK4(a, b, c, e) \ + (((uint)(a) & 0xFFu) | (((uint)(b) & 0xFFu) << 8) | (((uint)(c) & 0xFFu) << 16) | (((uint)(e) & 0xFFu) << 24)) + +// Pack each four K values as (0, 2, 1, 3); scales and sums are interleaved at width eight. +kernel void kernel_quant_a_q8_1_k4( + global const float * src, + global uint * qa, + global half * ds, + ulong offset_src, + int total_blocks, + int k_b +) { + const int blk = get_global_id(0); + if (blk >= 8 * k_b) { + return; + } + const int col = blk / k_b; + const int b = blk % k_b; + if (blk >= total_blocks) { + vstore8((uint8)(0), 0, qa + blk * 8); + ds[(2 * b) * 8 + col] = (half)0; + ds[(2 * b + 1) * 8 + col] = (half)0; + return; + } + src = (global const float *)((global const char *)src + offset_src); + const int base = blk * 32; + float v[32]; + float amax = 0.0f; + #pragma unroll + for (int i = 0; i < 32; ++i) { + v[i] = src[base + i]; + amax = fmax(amax, fabs(v[i])); + } + const float d = amax / 127.0f; + const float id = amax > 0.0f ? 127.0f / amax : 0.0f; + int q[32]; + int sum = 0; + #pragma unroll + for (int i = 0; i < 32; ++i) { + q[i] = (int)rint(v[i] * id); + sum += q[i]; + } + uint8 out; + out.s0 = COK_PACK4(q[ 0], q[ 2], q[ 1], q[ 3]); + out.s1 = COK_PACK4(q[ 4], q[ 6], q[ 5], q[ 7]); + out.s2 = COK_PACK4(q[ 8], q[10], q[ 9], q[11]); + out.s3 = COK_PACK4(q[12], q[14], q[13], q[15]); + out.s4 = COK_PACK4(q[16], q[18], q[17], q[19]); + out.s5 = COK_PACK4(q[20], q[22], q[21], q[23]); + out.s6 = COK_PACK4(q[24], q[26], q[25], q[27]); + out.s7 = COK_PACK4(q[28], q[30], q[29], q[31]); + vstore8(out, 0, qa + blk * 8); + ds[(2 * b) * 8 + col] = (half)d; + ds[(2 * b + 1) * 8 + col] = (half)(d * (float)sum); +} + +#define COK_SPREAD(t) (((t) | ((t) << 12)) & 0x0F0F0F0Fu) +#define COK_DOT_RC4(r, c) \ + d##r.s##c = dot_acc_sat_4x8packed_ss_int(W0.s##r, A.s0, d##r.s##c); \ + d##r.s##c = dot_acc_sat_4x8packed_ss_int(W1.s##r, A.s1, d##r.s##c); \ + d##r.s##c = dot_acc_sat_4x8packed_ss_int(W2.s##r, A.s2, d##r.s##c); \ + d##r.s##c = dot_acc_sat_4x8packed_ss_int(W3.s##r, A.s3, d##r.s##c); +#define COK_DOT_COL4(c, t) \ + { const uint4 A = read_imageui(src1_qa, (c) * k_t + (t)); \ + COK_DOT_RC4(0, c) COK_DOT_RC4(1, c) COK_DOT_RC4(2, c) COK_DOT_RC4(3, c) } + +kernel void kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8( + global const uint * src0_q, + global const uchar * src0_s, + global const half * src0_d, + global const half * src0_dm, + read_only image1d_buffer_t src1_qa, + read_only image1d_buffer_t src1_ds, + global float * dst, + ulong offsetd, + int m, + int k, + int n_no_padding, + uchar mask_d6, + uchar mask_d4, + uchar mask_hi2, + int ksplit +) { + dst = (global float *)((global char *)dst + offsetd); + const int gx = get_global_id(0); + const int sg = get_local_id(1); + const int lane = get_local_id(0); + const int ks = get_group_id(1); + const int row0 = gx * COK_ROWS; + const int num_32blk = k / 32; + const int k_t = k >> 4; + const int fence = (int)(mask_d6 >> 6); + const int nslice = ksplit * COOPK_NSG; + const int chunk = (num_32blk + nslice - 1) / nslice; + const int b_beg = (ks * COOPK_NSG + sg) * chunk; + const int b_end = min(b_beg + chunk, num_32blk); + float8 acc0 = (float8)(0.0f), acc1 = (float8)(0.0f); + float8 acc2 = (float8)(0.0f), acc3 = (float8)(0.0f); + + for (int sb = b_beg >> 3; sb * 8 < b_end; ++sb) { + const half4 dd = vload4(0, src0_d + row0 + sb * m); + const half4 dmm = vload4(0, src0_dm + row0 + sb * m); + global const uchar * sc = src0_s + sb * 12 * m + row0; + const int j_beg = max(b_beg - sb * 8, 0); + const int j_end = min(b_end - sb * 8, 8); + for (int j = j_beg; j < j_end; ++j) { + const int blk = sb * 8 + j; + int8 d0 = (int8)(0), d1 = (int8)(0), d2 = (int8)(0), d3 = (int8)(0); + for (int h = 0; h < 2; ++h) { + const int u0 = (blk << 2) + (h << 1); + const int at = (blk << 1) + h; + const uint4 wa = vload4(0, src0_q + row0 + u0 * m); + const uint4 wb = vload4(0, src0_q + row0 + (u0 + 1) * m); + const uint4 W0 = COK_SPREAD(wa & 0xFFFFu); + const uint4 W1 = COK_SPREAD(wa >> 16); + const uint4 W2 = COK_SPREAD(wb & 0xFFFFu); + const uint4 W3 = COK_SPREAD(wb >> 16); + COK_DOT_COL4(0, at) COK_DOT_COL4(1, at) COK_DOT_COL4(2, at) COK_DOT_COL4(3, at) + // Keep the second activation group dependent on the first dot products. + const int at4 = at + (d0.s0 & fence); + COK_DOT_COL4(4, at4) COK_DOT_COL4(5, at4) COK_DOT_COL4(6, at4) COK_DOT_COL4(7, at4) + } + uchar4 scv, mnv; + if (j < 4) { + scv = vload4(0, sc + j * m) & (uchar4)(mask_d6); + mnv = vload4(0, sc + (j + 4) * m) & (uchar4)(mask_d6); + } else { + const uchar4 bh = vload4(0, sc + (j + 4) * m); + const uchar4 bl = vload4(0, sc + (j - 4) * m); + const uchar4 bj = vload4(0, sc + j * m); + scv = (bh & (uchar4)(mask_d4)) | ((bl >> (uchar4)(6)) << (uchar4)(4)); + mnv = (bh >> (uchar4)(4)) | ((bj >> (uchar4)(6)) << (uchar4)(4)); + } + const float4 scf = convert_float4(dd) * convert_float4(scv); + const float4 mnf = convert_float4(dmm) * convert_float4(mnv); + const float8 da = convert_float8(as_half8(read_imageui(src1_ds, 2 * blk))); + acc0 = mad(convert_float8(d0), da * scf.s0, acc0); + acc1 = mad(convert_float8(d1), da * scf.s1, acc1); + acc2 = mad(convert_float8(d2), da * scf.s2, acc2); + acc3 = mad(convert_float8(d3), da * scf.s3, acc3); + const float8 sa = convert_float8(as_half8(read_imageui(src1_ds, 2 * blk + 1))); + acc0 = mad(sa, -mnf.s0, acc0); + acc1 = mad(sa, -mnf.s1, acc1); + acc2 = mad(sa, -mnf.s2, acc2); + acc3 = mad(sa, -mnf.s3, acc3); + } + } + + local float8 reduceLM[COK_SG * (COOPK_NSG - 1)]; + float8 out0 = (float8)(0.0f), out1 = (float8)(0.0f); + float8 out2 = (float8)(0.0f), out3 = (float8)(0.0f); +#define COK_REDUCE(accv, outv) \ + barrier(CLK_LOCAL_MEM_FENCE); \ + if (sg > 0) { reduceLM[(sg - 1) * COK_SG + lane] = (accv); } \ + barrier(CLK_LOCAL_MEM_FENCE); \ + if (sg == 0) { \ + float8 sum = (accv); \ + for (int s = 0; s < COOPK_NSG - 1; s++) { sum += reduceLM[s * COK_SG + lane]; } \ + (outv) = sum; \ + } + COK_REDUCE(acc0, out0) + COK_REDUCE(acc1, out1) + COK_REDUCE(acc2, out2) + COK_REDUCE(acc3, out3) +#undef COK_REDUCE +#define COK_STORE_COL(c) \ + if ((c) < n_no_padding) { \ + vstore4((float4)(out0.s##c, out1.s##c, out2.s##c, out3.s##c), 0, dst + (c) * m + row0); \ + } + if (sg == 0) { + dst += (size_t)ks * (size_t)m * (size_t)n_no_padding; + COK_STORE_COL(0) COK_STORE_COL(1) COK_STORE_COL(2) COK_STORE_COL(3) + COK_STORE_COL(4) COK_STORE_COL(5) COK_STORE_COL(6) COK_STORE_COL(7) + } +#undef COK_STORE_COL +} From 1f8baae28d096624bd47d33d2d179ec479d47720 Mon Sep 17 00:00:00 2001 From: lhez Date: Sun, 22 Nov 2026 22:26:55 -0800 Subject: [PATCH 007/275] opencl: add xielu (#32791) Assisted-by: Codex --- docs/ops.md | 2 +- docs/ops/OpenCL.csv | 8 +-- ggml/src/ggml-opencl/ggml-opencl.cpp | 63 +++++++++++++++++++++++ ggml/src/ggml-opencl/kernels/unary_ext.cl | 26 ++++++++++ 4 files changed, 94 insertions(+), 5 deletions(-) diff --git a/docs/ops.md b/docs/ops.md index 88e92c701d10..855bf1cff83e 100644 --- a/docs/ops.md +++ b/docs/ops.md @@ -133,4 +133,4 @@ Legend: | TRI | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | | TRUNC | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ✅ | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | UPSCALE | ❌ | 🟡 | ✅ | ✅ | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | -| XIELU | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | +| XIELU | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | diff --git a/docs/ops/OpenCL.csv b/docs/ops/OpenCL.csv index e5f2bbd0cf00..bee117961fc8 100644 --- a/docs/ops/OpenCL.csv +++ b/docs/ops/OpenCL.csv @@ -16812,11 +16812,11 @@ "OpenCL","CUMSUM","type=f32,ne=[242004,1,1,1]","support","1","yes","OpenCL" "OpenCL","CUMSUM","type=f32,ne=[375960,1,1,1]","support","1","yes","OpenCL" "OpenCL","CUMSUM","type=f32,ne=[20481,4,1,1]","support","1","yes","OpenCL" -"OpenCL","XIELU","type=f32,ne=[10,5,4,3]","support","0","no","OpenCL" -"OpenCL","XIELU","type=f16,ne=[10,5,4,3]","support","0","no","OpenCL" +"OpenCL","XIELU","type=f32,ne=[10,5,4,3]","support","1","yes","OpenCL" +"OpenCL","XIELU","type=f16,ne=[10,5,4,3]","support","1","yes","OpenCL" "OpenCL","XIELU","type=bf16,ne=[10,5,4,3]","support","0","no","OpenCL" -"OpenCL","XIELU","type=f32,ne=[512,16,1,1]","support","0","no","OpenCL" -"OpenCL","XIELU","type=f16,ne=[512,16,1,1]","support","0","no","OpenCL" +"OpenCL","XIELU","type=f32,ne=[512,16,1,1]","support","1","yes","OpenCL" +"OpenCL","XIELU","type=f16,ne=[512,16,1,1]","support","1","yes","OpenCL" "OpenCL","XIELU","type=bf16,ne=[512,16,1,1]","support","0","no","OpenCL" "OpenCL","TRI","type=f32,ne=[10,10,4,3],tri_type=3","support","1","yes","OpenCL" "OpenCL","TRI","type=f32,ne=[10,10,4,3],tri_type=2","support","1","yes","OpenCL" diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index c2f3b874a29f..05a05fe9f95f 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -1163,6 +1163,8 @@ struct ggml_backend_opencl_context { cl_kernel kernel_sgn_f32, kernel_sgn_f32_4, kernel_sgn_f32_nc, kernel_sgn_f16, kernel_sgn_f16_4, kernel_sgn_f16_nc; cl_kernel kernel_step_f32, kernel_step_f32_4, kernel_step_f32_nc, kernel_step_f16, kernel_step_f16_4, kernel_step_f16_nc; cl_kernel kernel_elu_f32, kernel_elu_f32_4, kernel_elu_f32_nc, kernel_elu_f16, kernel_elu_f16_4, kernel_elu_f16_nc; + cl_kernel kernel_xielu_f32 = nullptr; + cl_kernel kernel_xielu_f16 = nullptr; cl_kernel kernel_hardswish_f32, kernel_hardswish_f32_4, kernel_hardswish_f32_nc, kernel_hardswish_f16, kernel_hardswish_f16_4, kernel_hardswish_f16_nc; cl_kernel kernel_hardsigmoid_f32, kernel_hardsigmoid_f32_4, kernel_hardsigmoid_f32_nc, kernel_hardsigmoid_f16, kernel_hardsigmoid_f16_4, kernel_hardsigmoid_f16_nc; cl_kernel kernel_floor_f32, kernel_floor_f32_4, kernel_floor_f32_nc, kernel_floor_f16, kernel_floor_f16_4, kernel_floor_f16_nc; @@ -1547,6 +1549,8 @@ struct ggml_backend_opencl_context { } #endif for (cl_kernel kernel : { + kernel_xielu_f32, + kernel_xielu_f16, kernel_mul_mm_f16_f32_kq_p8, kernel_mul_mm_q8_f32_kqv, kernel_fa_p8_fixup, @@ -4918,6 +4922,8 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { CL_UNARY_EXT_K(round) CL_UNARY_EXT_K(trunc) #undef CL_UNARY_EXT_K + CL_CHECK((backend_ctx->kernel_xielu_f32 = clCreateKernel(prog, "kernel_xielu_f32", &err), err)); + CL_CHECK((backend_ctx->kernel_xielu_f16 = clCreateKernel(prog, "kernel_xielu_f16", &err), err)); CL_CHECK(clReleaseProgram(prog)); GGML_LOG_CONT("."); } @@ -12286,6 +12292,14 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te case GGML_UNARY_OP_SILU: return op->src[0]->type == op->type && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16); + case GGML_UNARY_OP_XIELU: + for (int64_t ne : op->src[0]->ne) { + if (ne > INT_MAX) { + return false; + } + } + return op->src[0]->type == op->type && + (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16); case GGML_UNARY_OP_GELU: case GGML_UNARY_OP_RELU: case GGML_UNARY_OP_GELU_ERF: @@ -21318,6 +21332,51 @@ GGML_CL_UNARY_EXT_WRAP(ggml_cl_trunc, trunc) #undef GGML_CL_UNARY_EXT_WRAP +static void ggml_cl_xielu(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + UNUSED(src1); + + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + cl_kernel kernel = src0->type == GGML_TYPE_F16 ? backend_ctx->kernel_xielu_f16 : backend_ctx->kernel_xielu_f32; + + const auto * extra0 = (const ggml_tensor_extra_cl *) src0->extra; + const auto * extrad = (const ggml_tensor_extra_cl *) dst->extra; + + const cl_ulong offset0 = extra0->offset + src0->view_offs; + const cl_ulong offsetd = extrad->offset + dst->view_offs; + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); + + const float alpha_n = ggml_get_op_params_f32(dst, 1); + const float alpha_p = ggml_get_op_params_f32(dst, 2); + const float beta = ggml_get_op_params_f32(dst, 3); + const float eps = ggml_get_op_params_f32(dst, 4); + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(float), &alpha_n)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(float), &alpha_p)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(float), &beta)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(float), &eps)); + + const size_t nth = 64; + size_t global[] = {(size_t) ne01*nth, (size_t) ne02, (size_t) ne03}; + size_t local[] = {nth, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); +} + static void ggml_cl_softplus(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { GGML_ASSERT(src0); GGML_ASSERT(src0->extra); @@ -40747,6 +40806,10 @@ bool ggml_cl_compute_forward(ggml_backend_t backend, struct ggml_tensor * tensor if (!any_on_device) { return false; } func = ggml_cl_elu; break; + case GGML_UNARY_OP_XIELU: + if (!any_on_device) { return false; } + func = ggml_cl_xielu; + break; case GGML_UNARY_OP_HARDSWISH: if (!any_on_device) { return false; } func = ggml_cl_hardswish; diff --git a/ggml/src/ggml-opencl/kernels/unary_ext.cl b/ggml/src/ggml-opencl/kernels/unary_ext.cl index e86eadfa5f5c..e58cc0153ff1 100644 --- a/ggml/src/ggml-opencl/kernels/unary_ext.cl +++ b/ggml/src/ggml-opencl/kernels/unary_ext.cl @@ -83,3 +83,29 @@ UNARY_EXT(floor, floor(x), floor UNARY_EXT(ceil, ceil(x), ceil(x)) UNARY_EXT(round, round(x), round(x)) UNARY_EXT(trunc, trunc(x), trunc(x)) + +// xielu has more args, cannot fit in UNARY_EXT +inline float xielu(float x, float alpha_n, float alpha_p, float beta, float eps) { + return x > 0.0f ? alpha_p*x*x + beta*x : (expm1(fmin(x, eps)) - x)*alpha_n + beta*x; +} + +#define XIELU_KERNEL(NAME, TYPE) \ +kernel void kernel_xielu_##NAME( \ + global const char * src0, ulong offset0, \ + global char * dst, ulong offsetd, \ + int ne00, ulong nb00, ulong nb01, ulong nb02, ulong nb03, \ + ulong nb0, ulong nb1, ulong nb2, ulong nb3, \ + float alpha_n, float alpha_p, float beta, float eps) { \ + const size_t i3 = get_group_id(2); \ + const size_t i2 = get_group_id(1); \ + const size_t i1 = get_group_id(0); \ + src0 += offset0 + i3*nb03 + i2*nb02 + i1*nb01; \ + dst += offsetd + i3*nb3 + i2*nb2 + i1*nb1; \ + for (size_t i0 = get_local_id(0); i0 < (size_t) ne00; i0 += get_local_size(0)) { \ + const float x = *(global const TYPE *)(src0 + i0*nb00); \ + *(global TYPE *)(dst + i0*nb0) = xielu(x, alpha_n, alpha_p, beta, eps); \ + } \ +} + +XIELU_KERNEL(f32, float) +XIELU_KERNEL(f16, half) From dd53f70d089f8b57db9d9e4f44f3201a16668637 Mon Sep 17 00:00:00 2001 From: Aldehir Rojas Date: Mon, 23 Nov 2026 01:54:42 -0600 Subject: [PATCH 008/275] chat : improve inkling parser/grammar (#32833) --- common/parsers/inkling.cpp | 74 +++++++++++++++++++------------------- tests/test-chat.cpp | 41 ++++++++++++++++----- 2 files changed, 68 insertions(+), 47 deletions(-) diff --git a/common/parsers/inkling.cpp b/common/parsers/inkling.cpp index 9c30cdb87962..082bd86fdfd2 100644 --- a/common/parsers/inkling.cpp +++ b/common/parsers/inkling.cpp @@ -100,18 +100,18 @@ common_chat_params common_chat_params_init_inkling(const common_chat_template & auto use_tools = has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE; auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE; - data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) { - auto header = p.literal(HEADER); - auto end = p.literal(END); + data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) { + auto header = p.token(HEADER); + auto end = p.token(END); - auto think = p.literal(THINK); - auto thinking = p.rule("thinking", extract_reasoning ? think + p.reasoning(p.until(END)) + end : - p.atomic(p.content(think)) + p.content(p.until(END) + end)); - auto text = p.rule("text", p.literal(TEXT) + p.content(p.until(END)) + end); + auto think = p.token(THINK); + auto thinking = p.rule("thinking", extract_reasoning ? think + p.reasoning(p.until(end)) + end : + p.atomic(p.content(think)) + p.content(p.until(end) + end)); + auto text = p.rule("text", p.token(TEXT) + p.content(p.until(end)) + end); if (has_response_format) { auto response_format = p.rule("response-format", p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema))); - return p.zero_or_more(header + thinking) + header + p.literal(TEXT) + response_format + end; + return p.zero_or_more(header + thinking) + header + p.token(TEXT) + response_format + end; } auto blocks = p.zero_or_more(header + (thinking | text)); @@ -120,45 +120,43 @@ common_chat_params common_chat_params_init_inkling(const common_chat_template & return blocks; } - auto tool_choice = p.choice(); - foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) { - const auto & function = tool.at("function"); - std::string name = function.at("name"); - - auto open = p.tool_name(p.literal(name)) + p.literal(TOOL_JSON) + p.literal("{\"name\":" + json(name).dump() + ",\"args\":"); - auto args = p.tool_args(p.json()); - - tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(p.tool_open(open) + args + p.tool_close(p.literal("}")) + end)); - }); - - // tool calls are the last blocks of the turn - auto calls = inputs.parallel_tool_calls ? tool_choice + p.zero_or_more(header + tool_choice) : tool_choice; - auto tool_calls = header + p.trigger_rule("tool-calls", calls); + // the call takes the name in the JSON + auto tool_json = p.token(TOOL_JSON); + auto tool_body = [&](const common_peg_parser & json_name) { + return p.tool_open(p.literal("{")) << p.json_member("name", p.literal("\"") + p.tool_name(json_name) + p.literal("\"")) << p.literal(",") + << p.json_member("args", p.tool_args(p.json())) << p.tool_close(p.literal("}")) + end; + }; if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) { - return blocks + tool_calls; + auto tool_choice = p.choice(); + foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) { + const auto & function = tool.at("function"); + std::string name = function.at("name"); + std::string quoted = json(name).dump(); + + // The research model does not generate a tool name before the tool call token + auto json_name = p.literal(quoted.substr(1, quoted.size() - 2)); + tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(p.optional(p.literal(name)) + tool_json + tool_body(json_name))); + }); + + auto calls = inputs.parallel_tool_calls ? tool_choice + p.zero_or_more(header + tool_choice) : tool_choice; + return blocks + header + calls; } - return blocks + p.optional(tool_calls); + auto name = p.until(tool_json); + auto body = tool_body(p.string_content('"')); + auto next = p.rule("tool-call", header + p.tool(name + tool_json + body)); + auto more = inputs.parallel_tool_calls ? p.zero_or_more(next) : p.eps(); + auto calls = header + name + p.trigger_rule("tool-calls", tool_json, body + more); + + return blocks + p.optional(calls); }); if (has_response_format || use_tools) { - data.grammar_lazy = !has_response_format && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED; + data.grammar_lazy = false; data.grammar = build_grammar([&](const common_grammar_builder & builder) { - data.parser.build_grammar(builder, data.grammar_lazy); + data.parser.build_grammar(builder, !has_response_format && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO); }); - - if (data.grammar_lazy) { - // a header followed by text and not by a content token is a tool call, the grammar starts at the name - data.grammar_triggers = { - { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "<\\|message_model\\|>([^<])" }, - }; - // Inkling 1: the first header is in the generation prompt, and a lazy grammar does not get the prompt. - // an output that starts with no content token is a tool call. not for a continuation, it starts with text - if (!inputs.has_continuation()) { - data.grammar_triggers.push_back({ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL, "[^<]+" }); - } - } } return data; diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp index 341e7acebd9d..20a3cc6a0747 100644 --- a/tests/test-chat.cpp +++ b/tests/test-chat.cpp @@ -5653,6 +5653,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { for (const int version : { 1, 2 }) { auto tst = peg_tester(version == 1 ? "models/templates/thinkingmachines-Inkling.jinja" : "models/templates/thinkingmachines-Inkling-2-Small.jinja", detailed_debug); + tst.specials({ "<|message_model|>", "<|content_thinking|>", "<|content_text|>", "<|content_invoke_tool_json|>", "<|end_message|>" }); // Inkling 1 has the first header in the generation prompt, Inkling 2 writes it const std::string H = "<|message_model|>"; @@ -5693,7 +5694,8 @@ static void test_template_output_peg_parsers(bool detailed_debug) { .expect_tool_calls({ { "special_function", R"({"arg1":1})", "" }, }) - .expect_rules({ "tool-0" }) + .expect_rules({ "tool-calls" }) + .expect_grammar() .run(); // Thinking, content, then a tool call @@ -5721,20 +5723,41 @@ static void test_template_output_peg_parsers(bool detailed_debug) { }) .run(); - // The block closer inside a string argument does not end the block - tst.test(P + "python<|content_invoke_tool_json|>{\"name\":\"python\",\"args\":{\"code\":\"print('<|end_message|>')\"}}" + E) - .tools({ python_tool }) - .expect_tool_calls({ - { "python", R"JSON({"code":"print('<|end_message|>')"})JSON", "" }, - }) - .run(); - // Forced tool call tst.test(P + "<|content_thinking|>I should call it" + E + H + CALL) .reasoning_format(COMMON_REASONING_FORMAT_AUTO) .tool_choice(COMMON_CHAT_TOOL_CHOICE_REQUIRED) .tools({ special_function_tool }) .expect(simple_assist_msg("", "I should call it", "special_function", R"({"arg1":1})", "")) + .expect_rules({ "tool-0" }) + .expect_grammar() + .run(); + + // The research model does not write the name before the tool token + for (const auto tool_choice : { COMMON_CHAT_TOOL_CHOICE_AUTO, COMMON_CHAT_TOOL_CHOICE_REQUIRED }) { + tst.test(P + "<|content_invoke_tool_json|>{\"name\":\"special_function\",\"args\":{\"arg1\":1}}" + E) + .tool_choice(tool_choice) + .tools({ special_function_tool }) + .expect_tool_calls({ + { "special_function", R"({"arg1":1})", "" }, + }) + .run(); + } + + // A tool that is not in the list, with spaces in the JSON + tst.test(P + "unknown_tool<|content_invoke_tool_json|>{\"name\": \"unknown_tool\", \"args\": {\"arg1\": 1}}" + E) + .tools({ special_function_tool }) + .expect_tool_calls({ + { "unknown_tool", R"({"arg1": 1})", "" }, + }) + .run(); + + // The call takes the name in the JSON, not the one before the tool token + tst.test(P + "special<|content_invoke_tool_json|>{\"name\":\"special_function\",\"args\":{\"arg1\":1}}" + E) + .tools({ special_function_tool }) + .expect_tool_calls({ + { "special_function", R"({"arg1":1})", "" }, + }) .run(); // Response format From f5e6915c28f10330885fcb9243a93ae98d3115ab Mon Sep 17 00:00:00 2001 From: Leon <3077740163@qq.com> Date: Mon, 23 Nov 2026 15:56:54 +0800 Subject: [PATCH 009/275] webgpu : add ROLL support (#31887) * webgpu : add ROLL support * tests : keep ROLL cases portable across backends --- docs/ops.md | 2 +- docs/ops/WebGPU.csv | 8 ++++++- .../ggml-webgpu/ggml-webgpu-shader-lib.hpp | 2 +- ggml/src/ggml-webgpu/ggml-webgpu.cpp | 22 +++++++++++-------- tests/test-backend-ops.cpp | 19 +++++++++++----- 5 files changed, 36 insertions(+), 17 deletions(-) diff --git a/docs/ops.md b/docs/ops.md index 855bf1cff83e..6c226e150020 100644 --- a/docs/ops.md +++ b/docs/ops.md @@ -97,7 +97,7 @@ Legend: | REPEAT_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | | RMS_NORM | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | RMS_NORM_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | -| ROLL | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | +| ROLL | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | | ROPE | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | ✅ | 🟡 | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | | ROPE_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | | ROUND | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | diff --git a/docs/ops/WebGPU.csv b/docs/ops/WebGPU.csv index 2ad8ded659ec..8e09ddaf3de0 100644 --- a/docs/ops/WebGPU.csv +++ b/docs/ops/WebGPU.csv @@ -12345,7 +12345,13 @@ "WebGPU: WebGPU","PAD_REFLECT_1D","type=f32,ne_a=[257,7,1,1],pad_0=0,pad_1=256,view=0","support","1","yes","WebGPU" "WebGPU: WebGPU","PAD_REFLECT_1D","type=f32,ne_a=[2,16777217,1,1],pad_0=1,pad_1=1,view=0","support","1","yes","WebGPU" "WebGPU: WebGPU","PAD_REFLECT_1D","type=f32,ne_a=[3000,384,4,1],pad_0=10,pad_1=9,view=0","support","1","yes","WebGPU" -"WebGPU: WebGPU","ROLL","shift0=3,shift1=-2,shift3=1,shift4=-1","support","0","no","WebGPU" +"WebGPU: WebGPU","ROLL","shift0=3,shift1=-2,shift3=1,shift4=-1,permute=0,ne_a=[10,5,4,3]","support","1","yes","WebGPU" +"WebGPU: WebGPU","ROLL","shift0=3,shift1=-2,shift3=1,shift4=-1,permute=1,ne_a=[10,5,4,3]","support","1","yes","WebGPU" +"WebGPU: WebGPU","ROLL","shift0=0,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[1,1,1,1]","support","1","yes","WebGPU" +"WebGPU: WebGPU","ROLL","shift0=256,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[257,1,1,1]","support","1","yes","WebGPU" +"WebGPU: WebGPU","ROLL","shift0=-16,shift1=6,shift3=-2,shift4=1,permute=0,ne_a=[17,7,3,2]","support","1","yes","WebGPU" +"WebGPU: WebGPU","ROLL","shift0=4,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[42,512,1,1]","support","1","yes","WebGPU" +"WebGPU: WebGPU","ROLL","shift0=4,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[380,512,1,1]","support","1","yes","WebGPU" "WebGPU: WebGPU","ARANGE","type=f32,start=0.000000,stop=10.000000,step=1.000000","support","1","yes","WebGPU" "WebGPU: WebGPU","ARANGE","type=f32,start=3.000000,stop=3.500000,step=1.000000","support","1","yes","WebGPU" "WebGPU: WebGPU","ARANGE","type=f32,start=-10.000000,stop=10.000000,step=0.300000","support","1","yes","WebGPU" diff --git a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp index cc7f660ef8e4..8896efb5af4a 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp @@ -2117,7 +2117,7 @@ class ggml_webgpu_shader_lib { webgpu_pipeline get_pad_pipeline(const ggml_webgpu_shader_lib_context & context) { ggml_webgpu_pad_pipeline_key key = {}; key.reflect = context.dst->op == GGML_OP_PAD_REFLECT_1D; - key.circular = !key.reflect && ggml_get_op_params_i32(context.dst, 8) != 0; + key.circular = context.dst->op == GGML_OP_ROLL || (!key.reflect && ggml_get_op_params_i32(context.dst, 8) != 0); auto it = pad_pipelines.find(key); if (it != pad_pipelines.end()) { diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp index 886760849796..b857f4927764 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp @@ -964,16 +964,18 @@ static webgpu_encoded_op ggml_webgpu_pad(webgpu_context & ctx, ggml_tensor * src (uint32_t) dst->ne[1], (uint32_t) dst->ne[2], (uint32_t) dst->ne[3], - // Pad sizes - (uint32_t) ggml_get_op_params_i32(dst, 0), - (uint32_t) ggml_get_op_params_i32(dst, 1), - (uint32_t) ggml_get_op_params_i32(dst, 2), - (uint32_t) ggml_get_op_params_i32(dst, 3), - (uint32_t) ggml_get_op_params_i32(dst, 4), - (uint32_t) ggml_get_op_params_i32(dst, 5), - (uint32_t) ggml_get_op_params_i32(dst, 6), - (uint32_t) ggml_get_op_params_i32(dst, 7), }; + for (int i = 0; i < 4; i++) { + if (dst->op == GGML_OP_ROLL) { + // Circular padding with unchanged dimensions implements a roll. + const int64_t shift = ggml_get_op_params_i32(dst, i); + params.push_back((uint32_t) (shift < 0 ? shift + src->ne[i] : shift)); + params.push_back(0); + } else { + params.push_back((uint32_t) ggml_get_op_params_i32(dst, 2 * i)); + params.push_back((uint32_t) ggml_get_op_params_i32(dst, 2 * i + 1)); + } + } std::vector entries = { ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src), @@ -3740,6 +3742,7 @@ static std::optional ggml_webgpu_encode(webgpu_context ctx, return ggml_webgpu_pool2d(ctx, src0, node); case GGML_OP_COL2IM_1D: return ggml_webgpu_col2im_1d(ctx, src0, node); + case GGML_OP_ROLL: case GGML_OP_PAD_REFLECT_1D: case GGML_OP_PAD: return ggml_webgpu_pad(ctx, src0, node); @@ -5299,6 +5302,7 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const case GGML_OP_PAD_REFLECT_1D: supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32; break; + case GGML_OP_ROLL: case GGML_OP_PAD: supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32; break; diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index ca415adf0950..53961f776ef1 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9087,17 +9087,18 @@ struct test_roll : public test_case { const int shift3; const int shift4; const bool permute; + const std::array ne_a; std::string vars() override { - return VARS_TO_STR5(shift0, shift1, shift3, shift4, permute); + return VARS_TO_STR6(shift0, shift1, shift3, shift4, permute, ne_a); } - test_roll(int shift0 = 3, int shift1 = -2, int shift3 = 1, int shift4 = -1, bool permute = false) - : shift0(shift0), shift1(shift1), shift3(shift3), shift4(shift4), permute(permute) {} + test_roll(int shift0 = 3, int shift1 = -2, int shift3 = 1, int shift4 = -1, bool permute = false, + std::array ne_a = {10, 5, 4, 3}) + : shift0(shift0), shift1(shift1), shift3(shift3), shift4(shift4), permute(permute), ne_a(ne_a) {} ggml_tensor * build_graph(ggml_context * ctx) override { - int64_t ne[4] = {10, 5, 4, 3}; - ggml_tensor * a = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne); + ggml_tensor * a = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne_a.data()); ggml_set_name(a, "a"); if (permute) { @@ -13183,6 +13184,11 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_pad_reflect_1d(GGML_TYPE_F32, {3000, 384, 4, 1})); test_cases.emplace_back(new test_roll()); test_cases.emplace_back(new test_roll(3, -2, 1, -1, true)); + test_cases.emplace_back(new test_roll(0, 0, 0, 0, false, {1, 1, 1, 1})); + test_cases.emplace_back(new test_roll(256, 0, 0, 0, false, {257, 1, 1, 1})); + test_cases.emplace_back(new test_roll(-16, 6, -2, 1, false, {17, 7, 3, 2})); + test_cases.emplace_back(new test_roll(4, 0, 0, 0, false, {42, 512, 1, 1})); + test_cases.emplace_back(new test_roll(4, 0, 0, 0, false, {380, 512, 1, 1})); test_cases.emplace_back(new test_arange()); test_cases.emplace_back(new test_arange(GGML_TYPE_F32, 3.0f, 3.5f, 1.0f)); test_cases.emplace_back(new test_arange(GGML_TYPE_F32, -10.0f, 10.0f, 0.3f)); @@ -13916,6 +13922,9 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_arange(GGML_TYPE_F32, 0.0f, n, 1.0f)); } + test_cases.emplace_back(new test_roll(4, 0, 0, 0, false, {42, 512, 1, 1})); + test_cases.emplace_back(new test_roll(4, 0, 0, 0, false, {380, 512, 1, 1})); + // embedding lookups: one token (decode) and one batch of 2048 tokens (prefill) for (int r : {16, 32768}) { test_cases.emplace_back(new test_get_rows(GGML_TYPE_F8_E4M3, 160, 2000000, r, 1, 1, false)); // Qwen4-Exp n-gram table, 16 rows per token From 212c547fe908b288f6659d48741e6ffac1ff409c Mon Sep 17 00:00:00 2001 From: Wenyu Chen Date: Mon, 23 Nov 2026 03:27:44 -0500 Subject: [PATCH 010/275] ui: add cancel button to cancel model loading (#32225) --- .../app/models/ModelLoadControl.svelte | 24 ++++++++++++++++++- .../chat/src/lib/constants/icons.constants.ts | 2 ++ .../src/lib/stores/models/status.svelte.ts | 19 ++++++++++++--- 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/ui/apps/chat/src/lib/components/app/models/ModelLoadControl.svelte b/ui/apps/chat/src/lib/components/app/models/ModelLoadControl.svelte index 0607ddcedcc2..454b9f2c4b82 100644 --- a/ui/apps/chat/src/lib/components/app/models/ModelLoadControl.svelte +++ b/ui/apps/chat/src/lib/components/app/models/ModelLoadControl.svelte @@ -31,7 +31,29 @@
{#if isLoading} - + + +
+ modelsStore.status.cancelLoad(option.model)} + stopPropagationOnClick + tooltip="Cancel loading model" + tooltipAsTitle + /> +
{:else} {#if showAction && revealOnHover} diff --git a/ui/apps/chat/src/lib/constants/icons.constants.ts b/ui/apps/chat/src/lib/constants/icons.constants.ts index c096e9a69285..c61000967523 100644 --- a/ui/apps/chat/src/lib/constants/icons.constants.ts +++ b/ui/apps/chat/src/lib/constants/icons.constants.ts @@ -22,6 +22,7 @@ import LoadIcon from '@lucide/svelte/icons/power'; import RetryIcon from '@lucide/svelte/icons/rotate-cw'; import PromptCommandIcon from '@lucide/svelte/icons/sparkles'; import VideoIcon from '@lucide/svelte/icons/video'; +import CancelLoadIcon from '@lucide/svelte/icons/x'; import { ChatFormCommandAction, FileTypeCategory, ModelCapability } from '#lib/enums/index.ts'; import type { ModelCapabilities } from '#lib/types/models.js'; import type { Component } from 'svelte'; @@ -80,6 +81,7 @@ export const MODEL_DOWNLOAD_ICONS = { /** Icons the model load control shows for its states and actions. */ export const MODEL_LOAD_ICONS = { + cancel: CancelLoadIcon, failed: LoadFailedIcon, load: LoadIcon, loading: LoadingIcon, diff --git a/ui/apps/chat/src/lib/stores/models/status.svelte.ts b/ui/apps/chat/src/lib/stores/models/status.svelte.ts index ade2b701a881..01d36e96cda9 100644 --- a/ui/apps/chat/src/lib/stores/models/status.svelte.ts +++ b/ui/apps/chat/src/lib/stores/models/status.svelte.ts @@ -152,6 +152,8 @@ export class ModelStatusManager { private listedSidecarsByRepo = $derived.by(() => ModelsService.draftSidecarsByRepo(this.host.routerModels) ); + /** Models whose load the user cancelled; the failure the force-kill triggers is intentional, not a load failure. */ + private loadCancelRequests = new SvelteSet(); private loadingStates = new SvelteMap(); private loadProgress = new SvelteMap(); /** Paused downloads with their last reported progress, or null when none arrived before the pause. */ @@ -198,8 +200,8 @@ export class ModelStatusManager { }); // /models/sse feed state, the single source of truth for status and load progress private statusAbort: AbortController | null = null; - private statusReaderActive = false; + private statusReaderActive = false; private statusWaiters = new SvelteMap< string, { target: ServerModelStatus; resolve: () => void; reject: (e: Error) => void }[] @@ -269,10 +271,15 @@ export class ModelStatusManager { this.subscribe(); + // mark before the kill: the feed can report the child's death before + // this request returns, and load() must not toast it as a failure + this.loadCancelRequests.add(modelId); + try { await ModelsService.unload(modelId); toast.info(`Load cancelled: ${this.host.toDisplayName(modelId)}`); } catch (error) { + this.loadCancelRequests.delete(modelId); toast.error(`Failed to cancel load: ${this.host.toDisplayName(modelId)}`); throw error; @@ -516,11 +523,17 @@ export class ModelStatusManager { toast.success(`Model loaded: ${this.host.toDisplayName(modelId)}`); } catch (error) { this.rejectStatus(modelId, error instanceof Error ? error : new Error('load failed')); - this.host.error = error instanceof Error ? error.message : 'Failed to load model'; - toast.error(`Failed to load model: ${this.host.toDisplayName(modelId)}`); + + // a user cancel force-kills the child, which settles this waiter as a + // failure; cancelLoad already reported the cancel, so stay silent + if (!this.loadCancelRequests.delete(modelId)) { + this.host.error = error instanceof Error ? error.message : 'Failed to load model'; + toast.error(`Failed to load model: ${this.host.toDisplayName(modelId)}`); + } throw error; } finally { + this.loadCancelRequests.delete(modelId); this.loadingStates.set(modelId, false); } } From 7d9b931df9bb7c689f067a7fed23e7f5253951f6 Mon Sep 17 00:00:00 2001 From: Daniel Bevenius Date: Mon, 23 Nov 2026 11:05:21 +0100 Subject: [PATCH 011/275] ggml : update cmake MATH_LIBRARY check (#32864) This commit updates the cmake check for `MATH_LIBRARY` and removes the DEFINED operator for the if() command. The motivation for this is that on windows if a parent project of ggml calls find_library(MATH_LIBRARY) this could return `MATH_LIBRARY-NOTFOUND` which will cause the if clause to be true. Removing the DEFINED operator will work as intended will evaluate to false, as specified by cmake if command docs: ```console False if the constant is 0, OFF, NO, FALSE, N, IGNORE, NOTFOUND, the empty string, or ends in the suffix -NOTFOUND. ``` This commit was originally opened in a PR against whisper.cpp, see link below. Refs: https://github.com/ggml-org/whisper.cpp/pull/4168 Refs: https://cmake.org/cmake/help/latest/command/if.html#constant --- ggml/src/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ggml/src/CMakeLists.txt b/ggml/src/CMakeLists.txt index eee1a460d16b..74ddb51ca88e 100644 --- a/ggml/src/CMakeLists.txt +++ b/ggml/src/CMakeLists.txt @@ -621,7 +621,7 @@ endforeach() target_link_libraries(ggml-base PRIVATE Threads::Threads) -if (DEFINED MATH_LIBRARY) +if (MATH_LIBRARY) target_link_libraries(ggml-base PRIVATE ${MATH_LIBRARY}) elseif (NOT WIN32 AND NOT DEFINED ENV{ONEAPI_ROOT}) target_link_libraries(ggml-base PRIVATE m) From a8f8294c45076538f4509754e4c79fc51a1a486b Mon Sep 17 00:00:00 2001 From: Vladislav Merkulov <150796351+merkulovlad@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:45:31 +0300 Subject: [PATCH 012/275] tests : update Qwen3.6-27B snapshot (#32845) --- tests/snapshots/qwen3.6-27b.schema | 1928 +++++++++++++--------------- 1 file changed, 916 insertions(+), 1012 deletions(-) diff --git a/tests/snapshots/qwen3.6-27b.schema b/tests/snapshots/qwen3.6-27b.schema index 40802053364b..f36752ffcd8c 100644 --- a/tests/snapshots/qwen3.6-27b.schema +++ b/tests/snapshots/qwen3.6-27b.schema @@ -1,4 +1,4 @@ -# Model: Qwen3.5-27B +# Model: Qwen3.6-27B # n_embd=5120, n_ff=17408, n_vocab=248320, n_layer=64, n_head=24, n_head_kv=4 [F32] f32 @@ -21,146 +21,146 @@ output.weight q6_K [Q2_K] q2_K output.weight q6_K -blk.0.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K blk.0.ffn_down.weight q3_K -blk.1.attn_qkv.weight q4_K +blk.1.attn_qkv_gate.weight q4_K blk.1.ffn_down.weight q3_K -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight q3_K blk.3.attn_output.weight q3_K blk.3.attn_v.weight q4_K blk.3.ffn_down.weight q3_K -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight q3_K -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight q3_K -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight q3_K blk.7.attn_output.weight q3_K blk.7.attn_v.weight q4_K blk.7.ffn_down.weight q3_K -blk.8.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K blk.8.ffn_down.weight q3_K -blk.9.attn_qkv.weight q4_K +blk.9.attn_qkv_gate.weight q4_K blk.9.ffn_down.weight q3_K -blk.10.attn_qkv.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.10.ffn_down.weight q3_K blk.11.attn_output.weight q3_K blk.11.attn_v.weight q4_K blk.11.ffn_down.weight q3_K -blk.12.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K blk.12.ffn_down.weight q3_K -blk.13.attn_qkv.weight q4_K +blk.13.attn_qkv_gate.weight q4_K blk.13.ffn_down.weight q3_K -blk.14.attn_qkv.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.14.ffn_down.weight q3_K blk.15.attn_output.weight q3_K blk.15.attn_v.weight q4_K blk.15.ffn_down.weight q3_K -blk.16.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K blk.16.ffn_down.weight q3_K -blk.17.attn_qkv.weight q4_K +blk.17.attn_qkv_gate.weight q4_K blk.17.ffn_down.weight q3_K -blk.18.attn_qkv.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.18.ffn_down.weight q3_K blk.19.attn_output.weight q3_K blk.19.attn_v.weight q4_K blk.19.ffn_down.weight q3_K -blk.20.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K blk.20.ffn_down.weight q3_K -blk.21.attn_qkv.weight q4_K +blk.21.attn_qkv_gate.weight q4_K blk.21.ffn_down.weight q3_K -blk.22.attn_qkv.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.22.ffn_down.weight q3_K blk.23.attn_output.weight q3_K blk.23.attn_v.weight q4_K blk.23.ffn_down.weight q3_K -blk.24.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K blk.24.ffn_down.weight q3_K -blk.25.attn_qkv.weight q4_K +blk.25.attn_qkv_gate.weight q4_K blk.25.ffn_down.weight q3_K -blk.26.attn_qkv.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.26.ffn_down.weight q3_K blk.27.attn_output.weight q3_K blk.27.attn_v.weight q4_K blk.27.ffn_down.weight q3_K -blk.28.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K blk.28.ffn_down.weight q3_K -blk.29.attn_qkv.weight q4_K +blk.29.attn_qkv_gate.weight q4_K blk.29.ffn_down.weight q3_K -blk.30.attn_qkv.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.30.ffn_down.weight q3_K blk.31.attn_output.weight q3_K blk.31.attn_v.weight q4_K blk.31.ffn_down.weight q3_K -blk.32.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K blk.32.ffn_down.weight q3_K -blk.33.attn_qkv.weight q4_K +blk.33.attn_qkv_gate.weight q4_K blk.33.ffn_down.weight q3_K -blk.34.attn_qkv.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.34.ffn_down.weight q3_K blk.35.attn_output.weight q3_K blk.35.attn_v.weight q4_K blk.35.ffn_down.weight q3_K -blk.36.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K blk.36.ffn_down.weight q3_K -blk.37.attn_qkv.weight q4_K +blk.37.attn_qkv_gate.weight q4_K blk.37.ffn_down.weight q3_K -blk.38.attn_qkv.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.38.ffn_down.weight q3_K blk.39.attn_output.weight q3_K blk.39.attn_v.weight q4_K blk.39.ffn_down.weight q3_K -blk.40.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K blk.40.ffn_down.weight q3_K -blk.41.attn_qkv.weight q4_K +blk.41.attn_qkv_gate.weight q4_K blk.41.ffn_down.weight q3_K -blk.42.attn_qkv.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.42.ffn_down.weight q3_K blk.43.attn_output.weight q3_K blk.43.attn_v.weight q4_K blk.43.ffn_down.weight q3_K -blk.44.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K blk.44.ffn_down.weight q3_K -blk.45.attn_qkv.weight q4_K +blk.45.attn_qkv_gate.weight q4_K blk.45.ffn_down.weight q3_K -blk.46.attn_qkv.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.46.ffn_down.weight q3_K blk.47.attn_output.weight q3_K blk.47.attn_v.weight q4_K blk.47.ffn_down.weight q3_K -blk.48.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K blk.48.ffn_down.weight q3_K -blk.49.attn_qkv.weight q4_K +blk.49.attn_qkv_gate.weight q4_K blk.49.ffn_down.weight q3_K -blk.50.attn_qkv.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.50.ffn_down.weight q3_K blk.51.attn_output.weight q3_K blk.51.attn_v.weight q4_K blk.51.ffn_down.weight q3_K -blk.52.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K blk.52.ffn_down.weight q3_K -blk.53.attn_qkv.weight q4_K +blk.53.attn_qkv_gate.weight q4_K blk.53.ffn_down.weight q3_K -blk.54.attn_qkv.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.54.ffn_down.weight q3_K blk.55.attn_output.weight q3_K blk.55.attn_v.weight q4_K blk.55.ffn_down.weight q3_K -blk.56.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K blk.56.ffn_down.weight q3_K -blk.57.attn_qkv.weight q4_K +blk.57.attn_qkv_gate.weight q4_K blk.57.ffn_down.weight q3_K -blk.58.attn_qkv.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.58.ffn_down.weight q3_K blk.59.attn_output.weight q3_K blk.59.attn_v.weight q4_K blk.59.ffn_down.weight q3_K -blk.60.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K blk.60.ffn_down.weight q3_K -blk.61.attn_qkv.weight q4_K +blk.61.attn_qkv_gate.weight q4_K blk.61.ffn_down.weight q3_K -blk.62.attn_qkv.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.62.ffn_down.weight q3_K blk.63.attn_output.weight q3_K blk.63.attn_v.weight q4_K @@ -171,146 +171,146 @@ output.weight q6_K [Q3_K_M] q3_K output.weight q6_K -blk.0.attn_qkv.weight q5_K +blk.0.attn_qkv_gate.weight q5_K blk.0.ffn_down.weight q5_K -blk.1.attn_qkv.weight q5_K +blk.1.attn_qkv_gate.weight q5_K blk.1.ffn_down.weight q5_K -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight q5_K blk.3.attn_output.weight q4_K blk.3.attn_v.weight q4_K blk.3.ffn_down.weight q5_K -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight q4_K -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight q4_K -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight q4_K blk.7.attn_output.weight q4_K blk.7.attn_v.weight q4_K blk.7.ffn_down.weight q4_K -blk.8.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K blk.8.ffn_down.weight q4_K -blk.9.attn_qkv.weight q4_K +blk.9.attn_qkv_gate.weight q4_K blk.9.ffn_down.weight q4_K -blk.10.attn_qkv.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.10.ffn_down.weight q4_K blk.11.attn_output.weight q4_K blk.11.attn_v.weight q4_K blk.11.ffn_down.weight q4_K -blk.12.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K blk.12.ffn_down.weight q4_K -blk.13.attn_qkv.weight q4_K +blk.13.attn_qkv_gate.weight q4_K blk.13.ffn_down.weight q4_K -blk.14.attn_qkv.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.14.ffn_down.weight q4_K blk.15.attn_output.weight q4_K blk.15.attn_v.weight q4_K blk.15.ffn_down.weight q4_K -blk.16.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K blk.16.ffn_down.weight q4_K -blk.17.attn_qkv.weight q4_K +blk.17.attn_qkv_gate.weight q4_K blk.17.ffn_down.weight q4_K -blk.18.attn_qkv.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.18.ffn_down.weight q4_K blk.19.attn_output.weight q4_K blk.19.attn_v.weight q4_K blk.19.ffn_down.weight q4_K -blk.20.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K blk.20.ffn_down.weight q4_K -blk.21.attn_qkv.weight q4_K +blk.21.attn_qkv_gate.weight q4_K blk.21.ffn_down.weight q4_K -blk.22.attn_qkv.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.22.ffn_down.weight q4_K blk.23.attn_output.weight q4_K blk.23.attn_v.weight q4_K blk.23.ffn_down.weight q4_K -blk.24.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K blk.24.ffn_down.weight q4_K -blk.25.attn_qkv.weight q4_K +blk.25.attn_qkv_gate.weight q4_K blk.25.ffn_down.weight q4_K -blk.26.attn_qkv.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.26.ffn_down.weight q4_K blk.27.attn_output.weight q4_K blk.27.attn_v.weight q4_K blk.27.ffn_down.weight q4_K -blk.28.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K blk.28.ffn_down.weight q4_K -blk.29.attn_qkv.weight q4_K +blk.29.attn_qkv_gate.weight q4_K blk.29.ffn_down.weight q4_K -blk.30.attn_qkv.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.30.ffn_down.weight q4_K blk.31.attn_output.weight q4_K blk.31.attn_v.weight q4_K blk.31.ffn_down.weight q4_K -blk.32.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K blk.32.ffn_down.weight q4_K -blk.33.attn_qkv.weight q4_K +blk.33.attn_qkv_gate.weight q4_K blk.33.ffn_down.weight q4_K -blk.34.attn_qkv.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.34.ffn_down.weight q4_K blk.35.attn_output.weight q4_K blk.35.attn_v.weight q4_K blk.35.ffn_down.weight q4_K -blk.36.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K blk.36.ffn_down.weight q4_K -blk.37.attn_qkv.weight q4_K +blk.37.attn_qkv_gate.weight q4_K blk.37.ffn_down.weight q4_K -blk.38.attn_qkv.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.38.ffn_down.weight q4_K blk.39.attn_output.weight q4_K blk.39.attn_v.weight q4_K blk.39.ffn_down.weight q4_K -blk.40.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K blk.40.ffn_down.weight q4_K -blk.41.attn_qkv.weight q4_K +blk.41.attn_qkv_gate.weight q4_K blk.41.ffn_down.weight q4_K -blk.42.attn_qkv.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.42.ffn_down.weight q4_K blk.43.attn_output.weight q4_K blk.43.attn_v.weight q4_K blk.43.ffn_down.weight q4_K -blk.44.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K blk.44.ffn_down.weight q4_K -blk.45.attn_qkv.weight q4_K +blk.45.attn_qkv_gate.weight q4_K blk.45.ffn_down.weight q4_K -blk.46.attn_qkv.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.46.ffn_down.weight q4_K blk.47.attn_output.weight q4_K blk.47.attn_v.weight q4_K blk.47.ffn_down.weight q4_K -blk.48.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K blk.48.ffn_down.weight q4_K -blk.49.attn_qkv.weight q4_K +blk.49.attn_qkv_gate.weight q4_K blk.49.ffn_down.weight q4_K -blk.50.attn_qkv.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.50.ffn_down.weight q4_K blk.51.attn_output.weight q4_K blk.51.attn_v.weight q4_K blk.51.ffn_down.weight q4_K -blk.52.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K blk.52.ffn_down.weight q4_K -blk.53.attn_qkv.weight q4_K +blk.53.attn_qkv_gate.weight q4_K blk.53.ffn_down.weight q4_K -blk.54.attn_qkv.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.54.ffn_down.weight q4_K blk.55.attn_output.weight q4_K blk.55.attn_v.weight q4_K blk.55.ffn_down.weight q4_K -blk.56.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K blk.56.ffn_down.weight q4_K -blk.57.attn_qkv.weight q4_K +blk.57.attn_qkv_gate.weight q4_K blk.57.ffn_down.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.58.ffn_down.weight q4_K blk.59.attn_output.weight q4_K blk.59.attn_v.weight q4_K blk.59.ffn_down.weight q4_K -blk.60.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K blk.60.ffn_down.weight q4_K -blk.61.attn_qkv.weight q4_K +blk.61.attn_qkv_gate.weight q4_K blk.61.ffn_down.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.62.ffn_down.weight q4_K blk.63.attn_output.weight q4_K blk.63.attn_v.weight q4_K @@ -318,146 +318,146 @@ blk.63.ffn_down.weight q4_K [Q3_K_L] q3_K output.weight q6_K -blk.0.attn_qkv.weight q5_K +blk.0.attn_qkv_gate.weight q5_K blk.0.ffn_down.weight q5_K -blk.1.attn_qkv.weight q5_K +blk.1.attn_qkv_gate.weight q5_K blk.1.ffn_down.weight q5_K -blk.2.attn_qkv.weight q5_K +blk.2.attn_qkv_gate.weight q5_K blk.2.ffn_down.weight q5_K blk.3.attn_output.weight q5_K blk.3.attn_v.weight q5_K blk.3.ffn_down.weight q5_K -blk.4.attn_qkv.weight q5_K +blk.4.attn_qkv_gate.weight q5_K blk.4.ffn_down.weight q5_K -blk.5.attn_qkv.weight q5_K +blk.5.attn_qkv_gate.weight q5_K blk.5.ffn_down.weight q5_K -blk.6.attn_qkv.weight q5_K +blk.6.attn_qkv_gate.weight q5_K blk.6.ffn_down.weight q5_K blk.7.attn_output.weight q5_K blk.7.attn_v.weight q5_K blk.7.ffn_down.weight q5_K -blk.8.attn_qkv.weight q5_K +blk.8.attn_qkv_gate.weight q5_K blk.8.ffn_down.weight q5_K -blk.9.attn_qkv.weight q5_K +blk.9.attn_qkv_gate.weight q5_K blk.9.ffn_down.weight q5_K -blk.10.attn_qkv.weight q5_K +blk.10.attn_qkv_gate.weight q5_K blk.10.ffn_down.weight q5_K blk.11.attn_output.weight q5_K blk.11.attn_v.weight q5_K blk.11.ffn_down.weight q5_K -blk.12.attn_qkv.weight q5_K +blk.12.attn_qkv_gate.weight q5_K blk.12.ffn_down.weight q5_K -blk.13.attn_qkv.weight q5_K +blk.13.attn_qkv_gate.weight q5_K blk.13.ffn_down.weight q5_K -blk.14.attn_qkv.weight q5_K +blk.14.attn_qkv_gate.weight q5_K blk.14.ffn_down.weight q5_K blk.15.attn_output.weight q5_K blk.15.attn_v.weight q5_K blk.15.ffn_down.weight q5_K -blk.16.attn_qkv.weight q5_K +blk.16.attn_qkv_gate.weight q5_K blk.16.ffn_down.weight q5_K -blk.17.attn_qkv.weight q5_K +blk.17.attn_qkv_gate.weight q5_K blk.17.ffn_down.weight q5_K -blk.18.attn_qkv.weight q5_K +blk.18.attn_qkv_gate.weight q5_K blk.18.ffn_down.weight q5_K blk.19.attn_output.weight q5_K blk.19.attn_v.weight q5_K blk.19.ffn_down.weight q5_K -blk.20.attn_qkv.weight q5_K +blk.20.attn_qkv_gate.weight q5_K blk.20.ffn_down.weight q5_K -blk.21.attn_qkv.weight q5_K +blk.21.attn_qkv_gate.weight q5_K blk.21.ffn_down.weight q5_K -blk.22.attn_qkv.weight q5_K +blk.22.attn_qkv_gate.weight q5_K blk.22.ffn_down.weight q5_K blk.23.attn_output.weight q5_K blk.23.attn_v.weight q5_K blk.23.ffn_down.weight q5_K -blk.24.attn_qkv.weight q5_K +blk.24.attn_qkv_gate.weight q5_K blk.24.ffn_down.weight q5_K -blk.25.attn_qkv.weight q5_K +blk.25.attn_qkv_gate.weight q5_K blk.25.ffn_down.weight q5_K -blk.26.attn_qkv.weight q5_K +blk.26.attn_qkv_gate.weight q5_K blk.26.ffn_down.weight q5_K blk.27.attn_output.weight q5_K blk.27.attn_v.weight q5_K blk.27.ffn_down.weight q5_K -blk.28.attn_qkv.weight q5_K +blk.28.attn_qkv_gate.weight q5_K blk.28.ffn_down.weight q5_K -blk.29.attn_qkv.weight q5_K +blk.29.attn_qkv_gate.weight q5_K blk.29.ffn_down.weight q5_K -blk.30.attn_qkv.weight q5_K +blk.30.attn_qkv_gate.weight q5_K blk.30.ffn_down.weight q5_K blk.31.attn_output.weight q5_K blk.31.attn_v.weight q5_K blk.31.ffn_down.weight q5_K -blk.32.attn_qkv.weight q5_K +blk.32.attn_qkv_gate.weight q5_K blk.32.ffn_down.weight q5_K -blk.33.attn_qkv.weight q5_K +blk.33.attn_qkv_gate.weight q5_K blk.33.ffn_down.weight q5_K -blk.34.attn_qkv.weight q5_K +blk.34.attn_qkv_gate.weight q5_K blk.34.ffn_down.weight q5_K blk.35.attn_output.weight q5_K blk.35.attn_v.weight q5_K blk.35.ffn_down.weight q5_K -blk.36.attn_qkv.weight q5_K +blk.36.attn_qkv_gate.weight q5_K blk.36.ffn_down.weight q5_K -blk.37.attn_qkv.weight q5_K +blk.37.attn_qkv_gate.weight q5_K blk.37.ffn_down.weight q5_K -blk.38.attn_qkv.weight q5_K +blk.38.attn_qkv_gate.weight q5_K blk.38.ffn_down.weight q5_K blk.39.attn_output.weight q5_K blk.39.attn_v.weight q5_K blk.39.ffn_down.weight q5_K -blk.40.attn_qkv.weight q5_K +blk.40.attn_qkv_gate.weight q5_K blk.40.ffn_down.weight q5_K -blk.41.attn_qkv.weight q5_K +blk.41.attn_qkv_gate.weight q5_K blk.41.ffn_down.weight q5_K -blk.42.attn_qkv.weight q5_K +blk.42.attn_qkv_gate.weight q5_K blk.42.ffn_down.weight q5_K blk.43.attn_output.weight q5_K blk.43.attn_v.weight q5_K blk.43.ffn_down.weight q5_K -blk.44.attn_qkv.weight q5_K +blk.44.attn_qkv_gate.weight q5_K blk.44.ffn_down.weight q5_K -blk.45.attn_qkv.weight q5_K +blk.45.attn_qkv_gate.weight q5_K blk.45.ffn_down.weight q5_K -blk.46.attn_qkv.weight q5_K +blk.46.attn_qkv_gate.weight q5_K blk.46.ffn_down.weight q5_K blk.47.attn_output.weight q5_K blk.47.attn_v.weight q5_K blk.47.ffn_down.weight q5_K -blk.48.attn_qkv.weight q5_K +blk.48.attn_qkv_gate.weight q5_K blk.48.ffn_down.weight q5_K -blk.49.attn_qkv.weight q5_K +blk.49.attn_qkv_gate.weight q5_K blk.49.ffn_down.weight q5_K -blk.50.attn_qkv.weight q5_K +blk.50.attn_qkv_gate.weight q5_K blk.50.ffn_down.weight q5_K blk.51.attn_output.weight q5_K blk.51.attn_v.weight q5_K blk.51.ffn_down.weight q5_K -blk.52.attn_qkv.weight q5_K +blk.52.attn_qkv_gate.weight q5_K blk.52.ffn_down.weight q5_K -blk.53.attn_qkv.weight q5_K +blk.53.attn_qkv_gate.weight q5_K blk.53.ffn_down.weight q5_K -blk.54.attn_qkv.weight q5_K +blk.54.attn_qkv_gate.weight q5_K blk.54.ffn_down.weight q5_K blk.55.attn_output.weight q5_K blk.55.attn_v.weight q5_K blk.55.ffn_down.weight q5_K -blk.56.attn_qkv.weight q5_K +blk.56.attn_qkv_gate.weight q5_K blk.56.ffn_down.weight q5_K -blk.57.attn_qkv.weight q5_K +blk.57.attn_qkv_gate.weight q5_K blk.57.ffn_down.weight q5_K -blk.58.attn_qkv.weight q5_K +blk.58.attn_qkv_gate.weight q5_K blk.58.ffn_down.weight q5_K blk.59.attn_output.weight q5_K blk.59.attn_v.weight q5_K blk.59.ffn_down.weight q5_K -blk.60.attn_qkv.weight q5_K +blk.60.attn_qkv_gate.weight q5_K blk.60.ffn_down.weight q5_K -blk.61.attn_qkv.weight q5_K +blk.61.attn_qkv_gate.weight q5_K blk.61.ffn_down.weight q5_K -blk.62.attn_qkv.weight q5_K +blk.62.attn_qkv_gate.weight q5_K blk.62.ffn_down.weight q5_K blk.63.attn_output.weight q5_K blk.63.attn_v.weight q5_K @@ -465,11 +465,11 @@ blk.63.ffn_down.weight q5_K [Q4_K_S] q4_K output.weight q6_K -blk.0.attn_qkv.weight q5_K +blk.0.attn_qkv_gate.weight q5_K blk.0.ffn_down.weight q5_K -blk.1.attn_qkv.weight q5_K +blk.1.attn_qkv_gate.weight q5_K blk.1.ffn_down.weight q5_K -blk.2.attn_qkv.weight q5_K +blk.2.attn_qkv_gate.weight q5_K blk.2.ffn_down.weight q5_K blk.3.attn_v.weight q5_K blk.3.ffn_down.weight q5_K @@ -480,67 +480,67 @@ blk.7.ffn_down.weight q5_K [Q4_K_M] q4_K output.weight q6_K -blk.0.attn_qkv.weight q6_K +blk.0.attn_qkv_gate.weight q6_K blk.0.ffn_down.weight q6_K -blk.1.attn_qkv.weight q6_K +blk.1.attn_qkv_gate.weight q6_K blk.1.ffn_down.weight q6_K -blk.2.attn_qkv.weight q6_K +blk.2.attn_qkv_gate.weight q6_K blk.2.ffn_down.weight q6_K blk.3.attn_v.weight q6_K blk.3.ffn_down.weight q6_K -blk.4.attn_qkv.weight q6_K +blk.4.attn_qkv_gate.weight q6_K blk.4.ffn_down.weight q6_K -blk.5.attn_qkv.weight q6_K +blk.5.attn_qkv_gate.weight q6_K blk.5.ffn_down.weight q6_K -blk.6.attn_qkv.weight q6_K +blk.6.attn_qkv_gate.weight q6_K blk.6.ffn_down.weight q6_K blk.7.attn_v.weight q6_K blk.7.ffn_down.weight q6_K -blk.10.attn_qkv.weight q6_K +blk.10.attn_qkv_gate.weight q6_K blk.10.ffn_down.weight q6_K -blk.13.attn_qkv.weight q6_K +blk.13.attn_qkv_gate.weight q6_K blk.13.ffn_down.weight q6_K -blk.16.attn_qkv.weight q6_K +blk.16.attn_qkv_gate.weight q6_K blk.16.ffn_down.weight q6_K blk.19.attn_v.weight q6_K blk.19.ffn_down.weight q6_K -blk.22.attn_qkv.weight q6_K +blk.22.attn_qkv_gate.weight q6_K blk.22.ffn_down.weight q6_K -blk.25.attn_qkv.weight q6_K +blk.25.attn_qkv_gate.weight q6_K blk.25.ffn_down.weight q6_K -blk.28.attn_qkv.weight q6_K +blk.28.attn_qkv_gate.weight q6_K blk.28.ffn_down.weight q6_K blk.31.attn_v.weight q6_K blk.31.ffn_down.weight q6_K -blk.34.attn_qkv.weight q6_K +blk.34.attn_qkv_gate.weight q6_K blk.34.ffn_down.weight q6_K -blk.37.attn_qkv.weight q6_K +blk.37.attn_qkv_gate.weight q6_K blk.37.ffn_down.weight q6_K -blk.40.attn_qkv.weight q6_K +blk.40.attn_qkv_gate.weight q6_K blk.40.ffn_down.weight q6_K blk.43.attn_v.weight q6_K blk.43.ffn_down.weight q6_K -blk.46.attn_qkv.weight q6_K +blk.46.attn_qkv_gate.weight q6_K blk.46.ffn_down.weight q6_K -blk.49.attn_qkv.weight q6_K +blk.49.attn_qkv_gate.weight q6_K blk.49.ffn_down.weight q6_K -blk.52.attn_qkv.weight q6_K +blk.52.attn_qkv_gate.weight q6_K blk.52.ffn_down.weight q6_K blk.55.attn_v.weight q6_K blk.55.ffn_down.weight q6_K -blk.56.attn_qkv.weight q6_K +blk.56.attn_qkv_gate.weight q6_K blk.56.ffn_down.weight q6_K -blk.57.attn_qkv.weight q6_K +blk.57.attn_qkv_gate.weight q6_K blk.57.ffn_down.weight q6_K -blk.58.attn_qkv.weight q6_K +blk.58.attn_qkv_gate.weight q6_K blk.58.ffn_down.weight q6_K blk.59.attn_v.weight q6_K blk.59.ffn_down.weight q6_K -blk.60.attn_qkv.weight q6_K +blk.60.attn_qkv_gate.weight q6_K blk.60.ffn_down.weight q6_K -blk.61.attn_qkv.weight q6_K +blk.61.attn_qkv_gate.weight q6_K blk.61.ffn_down.weight q6_K -blk.62.attn_qkv.weight q6_K +blk.62.attn_qkv_gate.weight q6_K blk.62.ffn_down.weight q6_K blk.63.attn_v.weight q6_K blk.63.ffn_down.weight q6_K @@ -550,67 +550,67 @@ output.weight q6_K [Q5_K_M] q5_K output.weight q6_K -blk.0.attn_qkv.weight q6_K +blk.0.attn_qkv_gate.weight q6_K blk.0.ffn_down.weight q6_K -blk.1.attn_qkv.weight q6_K +blk.1.attn_qkv_gate.weight q6_K blk.1.ffn_down.weight q6_K -blk.2.attn_qkv.weight q6_K +blk.2.attn_qkv_gate.weight q6_K blk.2.ffn_down.weight q6_K blk.3.attn_v.weight q6_K blk.3.ffn_down.weight q6_K -blk.4.attn_qkv.weight q6_K +blk.4.attn_qkv_gate.weight q6_K blk.4.ffn_down.weight q6_K -blk.5.attn_qkv.weight q6_K +blk.5.attn_qkv_gate.weight q6_K blk.5.ffn_down.weight q6_K -blk.6.attn_qkv.weight q6_K +blk.6.attn_qkv_gate.weight q6_K blk.6.ffn_down.weight q6_K blk.7.attn_v.weight q6_K blk.7.ffn_down.weight q6_K -blk.10.attn_qkv.weight q6_K +blk.10.attn_qkv_gate.weight q6_K blk.10.ffn_down.weight q6_K -blk.13.attn_qkv.weight q6_K +blk.13.attn_qkv_gate.weight q6_K blk.13.ffn_down.weight q6_K -blk.16.attn_qkv.weight q6_K +blk.16.attn_qkv_gate.weight q6_K blk.16.ffn_down.weight q6_K blk.19.attn_v.weight q6_K blk.19.ffn_down.weight q6_K -blk.22.attn_qkv.weight q6_K +blk.22.attn_qkv_gate.weight q6_K blk.22.ffn_down.weight q6_K -blk.25.attn_qkv.weight q6_K +blk.25.attn_qkv_gate.weight q6_K blk.25.ffn_down.weight q6_K -blk.28.attn_qkv.weight q6_K +blk.28.attn_qkv_gate.weight q6_K blk.28.ffn_down.weight q6_K blk.31.attn_v.weight q6_K blk.31.ffn_down.weight q6_K -blk.34.attn_qkv.weight q6_K +blk.34.attn_qkv_gate.weight q6_K blk.34.ffn_down.weight q6_K -blk.37.attn_qkv.weight q6_K +blk.37.attn_qkv_gate.weight q6_K blk.37.ffn_down.weight q6_K -blk.40.attn_qkv.weight q6_K +blk.40.attn_qkv_gate.weight q6_K blk.40.ffn_down.weight q6_K blk.43.attn_v.weight q6_K blk.43.ffn_down.weight q6_K -blk.46.attn_qkv.weight q6_K +blk.46.attn_qkv_gate.weight q6_K blk.46.ffn_down.weight q6_K -blk.49.attn_qkv.weight q6_K +blk.49.attn_qkv_gate.weight q6_K blk.49.ffn_down.weight q6_K -blk.52.attn_qkv.weight q6_K +blk.52.attn_qkv_gate.weight q6_K blk.52.ffn_down.weight q6_K blk.55.attn_v.weight q6_K blk.55.ffn_down.weight q6_K -blk.56.attn_qkv.weight q6_K +blk.56.attn_qkv_gate.weight q6_K blk.56.ffn_down.weight q6_K -blk.57.attn_qkv.weight q6_K +blk.57.attn_qkv_gate.weight q6_K blk.57.ffn_down.weight q6_K -blk.58.attn_qkv.weight q6_K +blk.58.attn_qkv_gate.weight q6_K blk.58.ffn_down.weight q6_K blk.59.attn_v.weight q6_K blk.59.ffn_down.weight q6_K -blk.60.attn_qkv.weight q6_K +blk.60.attn_qkv_gate.weight q6_K blk.60.ffn_down.weight q6_K -blk.61.attn_qkv.weight q6_K +blk.61.attn_qkv_gate.weight q6_K blk.61.ffn_down.weight q6_K -blk.62.attn_qkv.weight q6_K +blk.62.attn_qkv_gate.weight q6_K blk.62.ffn_down.weight q6_K blk.63.attn_v.weight q6_K blk.63.ffn_down.weight q6_K @@ -620,251 +620,251 @@ blk.63.ffn_down.weight q6_K [IQ2_XXS] iq2_xxs output.weight q5_K token_embd.weight q2_K -blk.0.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K blk.0.ffn_down.weight q2_K -blk.1.attn_qkv.weight q4_K +blk.1.attn_qkv_gate.weight q4_K blk.1.ffn_down.weight q2_K -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight q2_K blk.3.attn_v.weight q4_K blk.3.ffn_down.weight q2_K -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight q2_K -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight q2_K -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight q2_K blk.7.attn_v.weight q4_K blk.7.ffn_down.weight q2_K -blk.8.attn_qkv.weight q4_K -blk.9.attn_qkv.weight q4_K -blk.10.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K +blk.9.attn_qkv_gate.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.11.attn_v.weight q4_K -blk.12.attn_qkv.weight q4_K -blk.13.attn_qkv.weight q4_K -blk.14.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K +blk.13.attn_qkv_gate.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.15.attn_v.weight q4_K -blk.16.attn_qkv.weight q4_K -blk.17.attn_qkv.weight q4_K -blk.18.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K +blk.17.attn_qkv_gate.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.19.attn_v.weight q4_K -blk.20.attn_qkv.weight q4_K -blk.21.attn_qkv.weight q4_K -blk.22.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K +blk.21.attn_qkv_gate.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.23.attn_v.weight q4_K -blk.24.attn_qkv.weight q4_K -blk.25.attn_qkv.weight q4_K -blk.26.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K +blk.25.attn_qkv_gate.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.27.attn_v.weight q4_K -blk.28.attn_qkv.weight q4_K -blk.29.attn_qkv.weight q4_K -blk.30.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K +blk.29.attn_qkv_gate.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.31.attn_v.weight q4_K -blk.32.attn_qkv.weight q4_K -blk.33.attn_qkv.weight q4_K -blk.34.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K +blk.33.attn_qkv_gate.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.35.attn_v.weight q4_K -blk.36.attn_qkv.weight q4_K -blk.37.attn_qkv.weight q4_K -blk.38.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K +blk.37.attn_qkv_gate.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.39.attn_v.weight q4_K -blk.40.attn_qkv.weight q4_K -blk.41.attn_qkv.weight q4_K -blk.42.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K +blk.41.attn_qkv_gate.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.43.attn_v.weight q4_K -blk.44.attn_qkv.weight q4_K -blk.45.attn_qkv.weight q4_K -blk.46.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K +blk.45.attn_qkv_gate.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.47.attn_v.weight q4_K -blk.48.attn_qkv.weight q4_K -blk.49.attn_qkv.weight q4_K -blk.50.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K +blk.49.attn_qkv_gate.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.51.attn_v.weight q4_K -blk.52.attn_qkv.weight q4_K -blk.53.attn_qkv.weight q4_K -blk.54.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K +blk.53.attn_qkv_gate.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.55.attn_v.weight q4_K -blk.56.attn_qkv.weight q4_K -blk.57.attn_qkv.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K +blk.57.attn_qkv_gate.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.59.attn_v.weight q4_K -blk.60.attn_qkv.weight q4_K -blk.61.attn_qkv.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K +blk.61.attn_qkv_gate.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.63.attn_v.weight q4_K [IQ2_XS] iq2_xs output.weight q5_K token_embd.weight q2_K -blk.0.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K blk.0.ffn_down.weight q2_K -blk.1.attn_qkv.weight q4_K +blk.1.attn_qkv_gate.weight q4_K blk.1.ffn_down.weight q2_K -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight q2_K blk.3.attn_v.weight q4_K blk.3.ffn_down.weight q2_K -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight q2_K -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight q2_K -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight q2_K blk.7.attn_v.weight q4_K blk.7.ffn_down.weight q2_K -blk.8.attn_qkv.weight q4_K -blk.9.attn_qkv.weight q4_K -blk.10.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K +blk.9.attn_qkv_gate.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.11.attn_v.weight q4_K -blk.12.attn_qkv.weight q4_K -blk.13.attn_qkv.weight q4_K -blk.14.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K +blk.13.attn_qkv_gate.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.15.attn_v.weight q4_K -blk.16.attn_qkv.weight q4_K -blk.17.attn_qkv.weight q4_K -blk.18.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K +blk.17.attn_qkv_gate.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.19.attn_v.weight q4_K -blk.20.attn_qkv.weight q4_K -blk.21.attn_qkv.weight q4_K -blk.22.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K +blk.21.attn_qkv_gate.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.23.attn_v.weight q4_K -blk.24.attn_qkv.weight q4_K -blk.25.attn_qkv.weight q4_K -blk.26.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K +blk.25.attn_qkv_gate.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.27.attn_v.weight q4_K -blk.28.attn_qkv.weight q4_K -blk.29.attn_qkv.weight q4_K -blk.30.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K +blk.29.attn_qkv_gate.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.31.attn_v.weight q4_K -blk.32.attn_qkv.weight q4_K -blk.33.attn_qkv.weight q4_K -blk.34.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K +blk.33.attn_qkv_gate.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.35.attn_v.weight q4_K -blk.36.attn_qkv.weight q4_K -blk.37.attn_qkv.weight q4_K -blk.38.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K +blk.37.attn_qkv_gate.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.39.attn_v.weight q4_K -blk.40.attn_qkv.weight q4_K -blk.41.attn_qkv.weight q4_K -blk.42.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K +blk.41.attn_qkv_gate.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.43.attn_v.weight q4_K -blk.44.attn_qkv.weight q4_K -blk.45.attn_qkv.weight q4_K -blk.46.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K +blk.45.attn_qkv_gate.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.47.attn_v.weight q4_K -blk.48.attn_qkv.weight q4_K -blk.49.attn_qkv.weight q4_K -blk.50.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K +blk.49.attn_qkv_gate.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.51.attn_v.weight q4_K -blk.52.attn_qkv.weight q4_K -blk.53.attn_qkv.weight q4_K -blk.54.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K +blk.53.attn_qkv_gate.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.55.attn_v.weight q4_K -blk.56.attn_qkv.weight q4_K -blk.57.attn_qkv.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K +blk.57.attn_qkv_gate.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.59.attn_v.weight q4_K -blk.60.attn_qkv.weight q4_K -blk.61.attn_qkv.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K +blk.61.attn_qkv_gate.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.63.attn_v.weight q4_K [Q2_K_S] q2_K output.weight q6_K -blk.0.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K blk.0.ffn_down.weight q4_K -blk.1.attn_qkv.weight q4_K +blk.1.attn_qkv_gate.weight q4_K blk.1.ffn_down.weight q4_K -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight q4_K blk.3.attn_v.weight q4_K blk.3.ffn_down.weight q4_K -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight q4_K -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight q4_K -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight q4_K blk.7.attn_v.weight q4_K blk.7.ffn_down.weight q4_K -blk.8.attn_qkv.weight q4_K -blk.9.attn_qkv.weight q4_K -blk.10.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K +blk.9.attn_qkv_gate.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.11.attn_v.weight q4_K -blk.12.attn_qkv.weight q4_K -blk.13.attn_qkv.weight q4_K -blk.14.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K +blk.13.attn_qkv_gate.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.15.attn_v.weight q4_K -blk.16.attn_qkv.weight q4_K -blk.17.attn_qkv.weight q4_K -blk.18.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K +blk.17.attn_qkv_gate.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.19.attn_v.weight q4_K -blk.20.attn_qkv.weight q4_K -blk.21.attn_qkv.weight q4_K -blk.22.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K +blk.21.attn_qkv_gate.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.23.attn_v.weight q4_K -blk.24.attn_qkv.weight q4_K -blk.25.attn_qkv.weight q4_K -blk.26.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K +blk.25.attn_qkv_gate.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.27.attn_v.weight q4_K -blk.28.attn_qkv.weight q4_K -blk.29.attn_qkv.weight q4_K -blk.30.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K +blk.29.attn_qkv_gate.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.31.attn_v.weight q4_K -blk.32.attn_qkv.weight q4_K -blk.33.attn_qkv.weight q4_K -blk.34.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K +blk.33.attn_qkv_gate.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.35.attn_v.weight q4_K -blk.36.attn_qkv.weight q4_K -blk.37.attn_qkv.weight q4_K -blk.38.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K +blk.37.attn_qkv_gate.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.39.attn_v.weight q4_K -blk.40.attn_qkv.weight q4_K -blk.41.attn_qkv.weight q4_K -blk.42.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K +blk.41.attn_qkv_gate.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.43.attn_v.weight q4_K -blk.44.attn_qkv.weight q4_K -blk.45.attn_qkv.weight q4_K -blk.46.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K +blk.45.attn_qkv_gate.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.47.attn_v.weight q4_K -blk.48.attn_qkv.weight q4_K -blk.49.attn_qkv.weight q4_K -blk.50.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K +blk.49.attn_qkv_gate.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.51.attn_v.weight q4_K -blk.52.attn_qkv.weight q4_K -blk.53.attn_qkv.weight q4_K -blk.54.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K +blk.53.attn_qkv_gate.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.55.attn_v.weight q4_K -blk.56.attn_qkv.weight q4_K -blk.57.attn_qkv.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K +blk.57.attn_qkv_gate.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.59.attn_v.weight q4_K -blk.60.attn_qkv.weight q4_K -blk.61.attn_qkv.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K +blk.61.attn_qkv_gate.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.63.attn_v.weight q4_K [IQ3_XS] iq3_s output.weight q6_K -blk.0.attn_qkv.weight q4_K -blk.1.attn_qkv.weight q4_K -blk.2.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K +blk.1.attn_qkv_gate.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.3.attn_k.weight iq3_xxs blk.3.attn_q.weight iq3_xxs blk.3.attn_v.weight q4_K -blk.4.attn_qkv.weight q4_K -blk.5.attn_qkv.weight q4_K -blk.6.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K +blk.5.attn_qkv_gate.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.7.attn_k.weight iq3_xxs blk.7.attn_q.weight iq3_xxs blk.7.attn_v.weight q4_K -blk.8.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K blk.8.ffn_gate.weight iq3_xxs blk.8.ffn_up.weight iq3_xxs -blk.9.attn_qkv.weight q4_K +blk.9.attn_qkv_gate.weight q4_K blk.9.ffn_gate.weight iq3_xxs blk.9.ffn_up.weight iq3_xxs -blk.10.attn_qkv.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.10.ffn_gate.weight iq3_xxs blk.10.ffn_up.weight iq3_xxs blk.11.attn_k.weight iq3_xxs @@ -872,13 +872,13 @@ blk.11.attn_q.weight iq3_xxs blk.11.attn_v.weight q4_K blk.11.ffn_gate.weight iq3_xxs blk.11.ffn_up.weight iq3_xxs -blk.12.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K blk.12.ffn_gate.weight iq3_xxs blk.12.ffn_up.weight iq3_xxs -blk.13.attn_qkv.weight q4_K +blk.13.attn_qkv_gate.weight q4_K blk.13.ffn_gate.weight iq3_xxs blk.13.ffn_up.weight iq3_xxs -blk.14.attn_qkv.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.14.ffn_gate.weight iq3_xxs blk.14.ffn_up.weight iq3_xxs blk.15.attn_k.weight iq3_xxs @@ -886,13 +886,13 @@ blk.15.attn_q.weight iq3_xxs blk.15.attn_v.weight q4_K blk.15.ffn_gate.weight iq3_xxs blk.15.ffn_up.weight iq3_xxs -blk.16.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K blk.16.ffn_gate.weight iq3_xxs blk.16.ffn_up.weight iq3_xxs -blk.17.attn_qkv.weight q4_K +blk.17.attn_qkv_gate.weight q4_K blk.17.ffn_gate.weight iq3_xxs blk.17.ffn_up.weight iq3_xxs -blk.18.attn_qkv.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.18.ffn_gate.weight iq3_xxs blk.18.ffn_up.weight iq3_xxs blk.19.attn_k.weight iq3_xxs @@ -900,13 +900,13 @@ blk.19.attn_q.weight iq3_xxs blk.19.attn_v.weight q4_K blk.19.ffn_gate.weight iq3_xxs blk.19.ffn_up.weight iq3_xxs -blk.20.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K blk.20.ffn_gate.weight iq3_xxs blk.20.ffn_up.weight iq3_xxs -blk.21.attn_qkv.weight q4_K +blk.21.attn_qkv_gate.weight q4_K blk.21.ffn_gate.weight iq3_xxs blk.21.ffn_up.weight iq3_xxs -blk.22.attn_qkv.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.22.ffn_gate.weight iq3_xxs blk.22.ffn_up.weight iq3_xxs blk.23.attn_k.weight iq3_xxs @@ -914,13 +914,13 @@ blk.23.attn_q.weight iq3_xxs blk.23.attn_v.weight q4_K blk.23.ffn_gate.weight iq3_xxs blk.23.ffn_up.weight iq3_xxs -blk.24.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K blk.24.ffn_gate.weight iq3_xxs blk.24.ffn_up.weight iq3_xxs -blk.25.attn_qkv.weight q4_K +blk.25.attn_qkv_gate.weight q4_K blk.25.ffn_gate.weight iq3_xxs blk.25.ffn_up.weight iq3_xxs -blk.26.attn_qkv.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.26.ffn_gate.weight iq3_xxs blk.26.ffn_up.weight iq3_xxs blk.27.attn_k.weight iq3_xxs @@ -928,13 +928,13 @@ blk.27.attn_q.weight iq3_xxs blk.27.attn_v.weight q4_K blk.27.ffn_gate.weight iq3_xxs blk.27.ffn_up.weight iq3_xxs -blk.28.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K blk.28.ffn_gate.weight iq3_xxs blk.28.ffn_up.weight iq3_xxs -blk.29.attn_qkv.weight q4_K +blk.29.attn_qkv_gate.weight q4_K blk.29.ffn_gate.weight iq3_xxs blk.29.ffn_up.weight iq3_xxs -blk.30.attn_qkv.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.30.ffn_gate.weight iq3_xxs blk.30.ffn_up.weight iq3_xxs blk.31.attn_k.weight iq3_xxs @@ -942,13 +942,13 @@ blk.31.attn_q.weight iq3_xxs blk.31.attn_v.weight q4_K blk.31.ffn_gate.weight iq3_xxs blk.31.ffn_up.weight iq3_xxs -blk.32.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K blk.32.ffn_gate.weight iq3_xxs blk.32.ffn_up.weight iq3_xxs -blk.33.attn_qkv.weight q4_K +blk.33.attn_qkv_gate.weight q4_K blk.33.ffn_gate.weight iq3_xxs blk.33.ffn_up.weight iq3_xxs -blk.34.attn_qkv.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.34.ffn_gate.weight iq3_xxs blk.34.ffn_up.weight iq3_xxs blk.35.attn_k.weight iq3_xxs @@ -956,13 +956,13 @@ blk.35.attn_q.weight iq3_xxs blk.35.attn_v.weight q4_K blk.35.ffn_gate.weight iq3_xxs blk.35.ffn_up.weight iq3_xxs -blk.36.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K blk.36.ffn_gate.weight iq3_xxs blk.36.ffn_up.weight iq3_xxs -blk.37.attn_qkv.weight q4_K +blk.37.attn_qkv_gate.weight q4_K blk.37.ffn_gate.weight iq3_xxs blk.37.ffn_up.weight iq3_xxs -blk.38.attn_qkv.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.38.ffn_gate.weight iq3_xxs blk.38.ffn_up.weight iq3_xxs blk.39.attn_k.weight iq3_xxs @@ -970,13 +970,13 @@ blk.39.attn_q.weight iq3_xxs blk.39.attn_v.weight q4_K blk.39.ffn_gate.weight iq3_xxs blk.39.ffn_up.weight iq3_xxs -blk.40.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K blk.40.ffn_gate.weight iq3_xxs blk.40.ffn_up.weight iq3_xxs -blk.41.attn_qkv.weight q4_K +blk.41.attn_qkv_gate.weight q4_K blk.41.ffn_gate.weight iq3_xxs blk.41.ffn_up.weight iq3_xxs -blk.42.attn_qkv.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.42.ffn_gate.weight iq3_xxs blk.42.ffn_up.weight iq3_xxs blk.43.attn_k.weight iq3_xxs @@ -984,13 +984,13 @@ blk.43.attn_q.weight iq3_xxs blk.43.attn_v.weight q4_K blk.43.ffn_gate.weight iq3_xxs blk.43.ffn_up.weight iq3_xxs -blk.44.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K blk.44.ffn_gate.weight iq3_xxs blk.44.ffn_up.weight iq3_xxs -blk.45.attn_qkv.weight q4_K +blk.45.attn_qkv_gate.weight q4_K blk.45.ffn_gate.weight iq3_xxs blk.45.ffn_up.weight iq3_xxs -blk.46.attn_qkv.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.46.ffn_gate.weight iq3_xxs blk.46.ffn_up.weight iq3_xxs blk.47.attn_k.weight iq3_xxs @@ -998,13 +998,13 @@ blk.47.attn_q.weight iq3_xxs blk.47.attn_v.weight q4_K blk.47.ffn_gate.weight iq3_xxs blk.47.ffn_up.weight iq3_xxs -blk.48.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K blk.48.ffn_gate.weight iq3_xxs blk.48.ffn_up.weight iq3_xxs -blk.49.attn_qkv.weight q4_K +blk.49.attn_qkv_gate.weight q4_K blk.49.ffn_gate.weight iq3_xxs blk.49.ffn_up.weight iq3_xxs -blk.50.attn_qkv.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.50.ffn_gate.weight iq3_xxs blk.50.ffn_up.weight iq3_xxs blk.51.attn_k.weight iq3_xxs @@ -1012,13 +1012,13 @@ blk.51.attn_q.weight iq3_xxs blk.51.attn_v.weight q4_K blk.51.ffn_gate.weight iq3_xxs blk.51.ffn_up.weight iq3_xxs -blk.52.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K blk.52.ffn_gate.weight iq3_xxs blk.52.ffn_up.weight iq3_xxs -blk.53.attn_qkv.weight q4_K +blk.53.attn_qkv_gate.weight q4_K blk.53.ffn_gate.weight iq3_xxs blk.53.ffn_up.weight iq3_xxs -blk.54.attn_qkv.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.54.ffn_gate.weight iq3_xxs blk.54.ffn_up.weight iq3_xxs blk.55.attn_k.weight iq3_xxs @@ -1026,15 +1026,15 @@ blk.55.attn_q.weight iq3_xxs blk.55.attn_v.weight q4_K blk.55.ffn_gate.weight iq3_xxs blk.55.ffn_up.weight iq3_xxs -blk.56.attn_qkv.weight q4_K -blk.57.attn_qkv.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K +blk.57.attn_qkv_gate.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.59.attn_k.weight iq3_xxs blk.59.attn_q.weight iq3_xxs blk.59.attn_v.weight q4_K -blk.60.attn_qkv.weight q4_K -blk.61.attn_qkv.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K +blk.61.attn_qkv_gate.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.63.attn_k.weight iq3_xxs blk.63.attn_q.weight iq3_xxs blk.63.attn_v.weight q4_K @@ -1042,176 +1042,176 @@ blk.63.attn_v.weight q4_K [IQ3_XXS] iq3_xxs output.weight q5_K token_embd.weight iq3_s -blk.0.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K blk.0.ffn_down.weight q4_K -blk.1.attn_qkv.weight q4_K +blk.1.attn_qkv_gate.weight q4_K blk.1.ffn_down.weight q4_K -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight q4_K blk.3.attn_k.weight iq2_s blk.3.attn_output.weight iq3_s blk.3.attn_q.weight iq2_s blk.3.attn_v.weight q4_K blk.3.ffn_down.weight q4_K -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight q4_K -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight q4_K -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight q4_K blk.7.attn_k.weight iq2_s blk.7.attn_output.weight iq3_s blk.7.attn_q.weight iq2_s blk.7.attn_v.weight q4_K blk.7.ffn_down.weight q4_K -blk.8.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K blk.8.ffn_down.weight q3_K -blk.9.attn_qkv.weight q4_K +blk.9.attn_qkv_gate.weight q4_K blk.9.ffn_down.weight q3_K -blk.10.attn_qkv.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.10.ffn_down.weight q3_K blk.11.attn_k.weight iq2_s blk.11.attn_output.weight iq3_s blk.11.attn_q.weight iq2_s blk.11.attn_v.weight q4_K blk.11.ffn_down.weight q3_K -blk.12.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K blk.12.ffn_down.weight q3_K -blk.13.attn_qkv.weight q4_K +blk.13.attn_qkv_gate.weight q4_K blk.13.ffn_down.weight q3_K -blk.14.attn_qkv.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.14.ffn_down.weight q3_K blk.15.attn_k.weight iq2_s blk.15.attn_output.weight iq3_s blk.15.attn_q.weight iq2_s blk.15.attn_v.weight q4_K blk.15.ffn_down.weight q3_K -blk.16.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K blk.16.ffn_down.weight q3_K -blk.17.attn_qkv.weight q4_K +blk.17.attn_qkv_gate.weight q4_K blk.17.ffn_down.weight q3_K -blk.18.attn_qkv.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.18.ffn_down.weight q3_K blk.19.attn_k.weight iq2_s blk.19.attn_output.weight iq3_s blk.19.attn_q.weight iq2_s blk.19.attn_v.weight q4_K blk.19.ffn_down.weight q3_K -blk.20.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K blk.20.ffn_down.weight q3_K -blk.21.attn_qkv.weight q4_K +blk.21.attn_qkv_gate.weight q4_K blk.21.ffn_down.weight q3_K -blk.22.attn_qkv.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.22.ffn_down.weight q3_K blk.23.attn_k.weight iq2_s blk.23.attn_output.weight iq3_s blk.23.attn_q.weight iq2_s blk.23.attn_v.weight q4_K blk.23.ffn_down.weight q3_K -blk.24.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K blk.24.ffn_down.weight q3_K -blk.25.attn_qkv.weight q4_K +blk.25.attn_qkv_gate.weight q4_K blk.25.ffn_down.weight q3_K -blk.26.attn_qkv.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.26.ffn_down.weight q3_K blk.27.attn_k.weight iq2_s blk.27.attn_output.weight iq3_s blk.27.attn_q.weight iq2_s blk.27.attn_v.weight q4_K blk.27.ffn_down.weight q3_K -blk.28.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K blk.28.ffn_down.weight q3_K -blk.29.attn_qkv.weight q4_K +blk.29.attn_qkv_gate.weight q4_K blk.29.ffn_down.weight q3_K -blk.30.attn_qkv.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.30.ffn_down.weight q3_K blk.31.attn_k.weight iq2_s blk.31.attn_output.weight iq3_s blk.31.attn_q.weight iq2_s blk.31.attn_v.weight q4_K blk.31.ffn_down.weight q3_K -blk.32.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K blk.32.ffn_down.weight q3_K -blk.33.attn_qkv.weight q4_K +blk.33.attn_qkv_gate.weight q4_K blk.33.ffn_down.weight q3_K -blk.34.attn_qkv.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.34.ffn_down.weight q3_K blk.35.attn_k.weight iq2_s blk.35.attn_output.weight iq3_s blk.35.attn_q.weight iq2_s blk.35.attn_v.weight q4_K blk.35.ffn_down.weight q3_K -blk.36.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K blk.36.ffn_down.weight q3_K -blk.37.attn_qkv.weight q4_K +blk.37.attn_qkv_gate.weight q4_K blk.37.ffn_down.weight q3_K -blk.38.attn_qkv.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.38.ffn_down.weight q3_K blk.39.attn_k.weight iq2_s blk.39.attn_output.weight iq3_s blk.39.attn_q.weight iq2_s blk.39.attn_v.weight q4_K blk.39.ffn_down.weight q3_K -blk.40.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K blk.40.ffn_down.weight q3_K -blk.41.attn_qkv.weight q4_K +blk.41.attn_qkv_gate.weight q4_K blk.41.ffn_down.weight q3_K -blk.42.attn_qkv.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.42.ffn_down.weight q3_K blk.43.attn_k.weight iq2_s blk.43.attn_output.weight iq3_s blk.43.attn_q.weight iq2_s blk.43.attn_v.weight q4_K blk.43.ffn_down.weight q3_K -blk.44.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K blk.44.ffn_down.weight q3_K -blk.45.attn_qkv.weight q4_K +blk.45.attn_qkv_gate.weight q4_K blk.45.ffn_down.weight q3_K -blk.46.attn_qkv.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.46.ffn_down.weight q3_K blk.47.attn_k.weight iq2_s blk.47.attn_output.weight iq3_s blk.47.attn_q.weight iq2_s blk.47.attn_v.weight q4_K blk.47.ffn_down.weight q3_K -blk.48.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K blk.48.ffn_down.weight q3_K -blk.49.attn_qkv.weight q4_K +blk.49.attn_qkv_gate.weight q4_K blk.49.ffn_down.weight q3_K -blk.50.attn_qkv.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.50.ffn_down.weight q3_K blk.51.attn_k.weight iq2_s blk.51.attn_output.weight iq3_s blk.51.attn_q.weight iq2_s blk.51.attn_v.weight q4_K blk.51.ffn_down.weight q3_K -blk.52.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K blk.52.ffn_down.weight q3_K -blk.53.attn_qkv.weight q4_K +blk.53.attn_qkv_gate.weight q4_K blk.53.ffn_down.weight q3_K -blk.54.attn_qkv.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.54.ffn_down.weight q3_K blk.55.attn_k.weight iq2_s blk.55.attn_output.weight iq3_s blk.55.attn_q.weight iq2_s blk.55.attn_v.weight q4_K blk.55.ffn_down.weight q3_K -blk.56.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K blk.56.ffn_down.weight q3_K -blk.57.attn_qkv.weight q4_K +blk.57.attn_qkv_gate.weight q4_K blk.57.ffn_down.weight q3_K -blk.58.attn_qkv.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.58.ffn_down.weight q3_K blk.59.attn_k.weight iq2_s blk.59.attn_output.weight iq3_s blk.59.attn_q.weight iq2_s blk.59.attn_v.weight q4_K blk.59.ffn_down.weight q3_K -blk.60.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K blk.60.ffn_down.weight q3_K -blk.61.attn_qkv.weight q4_K +blk.61.attn_qkv_gate.weight q4_K blk.61.ffn_down.weight q3_K -blk.62.attn_qkv.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.62.ffn_down.weight q3_K blk.63.attn_k.weight iq2_s blk.63.attn_output.weight iq3_s @@ -1222,676 +1222,676 @@ blk.63.ffn_down.weight q3_K [IQ1_S] iq1_s output.weight q5_K token_embd.weight q2_K -blk.0.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K blk.0.ffn_down.weight q2_K -blk.1.attn_qkv.weight q4_K +blk.1.attn_qkv_gate.weight q4_K blk.1.ffn_down.weight q2_K -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight q2_K blk.3.attn_output.weight iq2_xxs blk.3.attn_v.weight q4_K blk.3.ffn_down.weight q2_K -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight q2_K -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight q2_K -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight q2_K blk.7.attn_output.weight iq2_xxs blk.7.attn_v.weight q4_K blk.7.ffn_down.weight q2_K -blk.8.attn_qkv.weight q4_K -blk.9.attn_qkv.weight q4_K -blk.10.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K +blk.9.attn_qkv_gate.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.11.attn_output.weight iq2_xxs blk.11.attn_v.weight q4_K -blk.12.attn_qkv.weight q4_K -blk.13.attn_qkv.weight q4_K -blk.14.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K +blk.13.attn_qkv_gate.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.15.attn_output.weight iq2_xxs blk.15.attn_v.weight q4_K -blk.16.attn_qkv.weight q4_K -blk.17.attn_qkv.weight q4_K -blk.18.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K +blk.17.attn_qkv_gate.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.19.attn_output.weight iq2_xxs blk.19.attn_v.weight q4_K -blk.20.attn_qkv.weight q4_K -blk.21.attn_qkv.weight q4_K -blk.22.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K +blk.21.attn_qkv_gate.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.23.attn_output.weight iq2_xxs blk.23.attn_v.weight q4_K -blk.24.attn_qkv.weight q4_K -blk.25.attn_qkv.weight q4_K -blk.26.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K +blk.25.attn_qkv_gate.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.27.attn_output.weight iq2_xxs blk.27.attn_v.weight q4_K -blk.28.attn_qkv.weight q4_K -blk.29.attn_qkv.weight q4_K -blk.30.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K +blk.29.attn_qkv_gate.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.31.attn_output.weight iq2_xxs blk.31.attn_v.weight q4_K -blk.32.attn_qkv.weight q4_K -blk.33.attn_qkv.weight q4_K -blk.34.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K +blk.33.attn_qkv_gate.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.35.attn_output.weight iq2_xxs blk.35.attn_v.weight q4_K -blk.36.attn_qkv.weight q4_K -blk.37.attn_qkv.weight q4_K -blk.38.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K +blk.37.attn_qkv_gate.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.39.attn_output.weight iq2_xxs blk.39.attn_v.weight q4_K -blk.40.attn_qkv.weight q4_K -blk.41.attn_qkv.weight q4_K -blk.42.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K +blk.41.attn_qkv_gate.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.43.attn_output.weight iq2_xxs blk.43.attn_v.weight q4_K -blk.44.attn_qkv.weight q4_K -blk.45.attn_qkv.weight q4_K -blk.46.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K +blk.45.attn_qkv_gate.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.47.attn_output.weight iq2_xxs blk.47.attn_v.weight q4_K -blk.48.attn_qkv.weight q4_K -blk.49.attn_qkv.weight q4_K -blk.50.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K +blk.49.attn_qkv_gate.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.51.attn_output.weight iq2_xxs blk.51.attn_v.weight q4_K -blk.52.attn_qkv.weight q4_K -blk.53.attn_qkv.weight q4_K -blk.54.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K +blk.53.attn_qkv_gate.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.55.attn_output.weight iq2_xxs blk.55.attn_v.weight q4_K -blk.56.attn_qkv.weight q4_K -blk.57.attn_qkv.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K +blk.57.attn_qkv_gate.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.59.attn_output.weight iq2_xxs blk.59.attn_v.weight q4_K -blk.60.attn_qkv.weight q4_K -blk.61.attn_qkv.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K +blk.61.attn_qkv_gate.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.63.attn_output.weight iq2_xxs blk.63.attn_v.weight q4_K [IQ4_NL] iq4_nl output.weight q6_K -blk.0.attn_qkv.weight q5_K +blk.0.attn_qkv_gate.weight q5_K blk.0.ffn_down.weight q5_K -blk.1.attn_qkv.weight q5_K +blk.1.attn_qkv_gate.weight q5_K blk.1.ffn_down.weight q5_K -blk.2.attn_qkv.weight q5_K +blk.2.attn_qkv_gate.weight q5_K blk.2.ffn_down.weight q5_K blk.3.attn_v.weight q5_K blk.3.ffn_down.weight q5_K -blk.4.attn_qkv.weight q5_K +blk.4.attn_qkv_gate.weight q5_K blk.4.ffn_down.weight q5_K -blk.5.attn_qkv.weight q5_K +blk.5.attn_qkv_gate.weight q5_K blk.5.ffn_down.weight q5_K -blk.6.attn_qkv.weight q5_K +blk.6.attn_qkv_gate.weight q5_K blk.6.ffn_down.weight q5_K blk.7.attn_v.weight q5_K blk.7.ffn_down.weight q5_K -blk.8.attn_qkv.weight q5_K -blk.9.attn_qkv.weight q5_K -blk.10.attn_qkv.weight q5_K +blk.8.attn_qkv_gate.weight q5_K +blk.9.attn_qkv_gate.weight q5_K +blk.10.attn_qkv_gate.weight q5_K blk.11.attn_v.weight q5_K -blk.12.attn_qkv.weight q5_K -blk.13.attn_qkv.weight q5_K -blk.14.attn_qkv.weight q5_K +blk.12.attn_qkv_gate.weight q5_K +blk.13.attn_qkv_gate.weight q5_K +blk.14.attn_qkv_gate.weight q5_K blk.15.attn_v.weight q5_K -blk.16.attn_qkv.weight q5_K -blk.17.attn_qkv.weight q5_K -blk.18.attn_qkv.weight q5_K +blk.16.attn_qkv_gate.weight q5_K +blk.17.attn_qkv_gate.weight q5_K +blk.18.attn_qkv_gate.weight q5_K blk.19.attn_v.weight q5_K -blk.20.attn_qkv.weight q5_K -blk.21.attn_qkv.weight q5_K -blk.22.attn_qkv.weight q5_K +blk.20.attn_qkv_gate.weight q5_K +blk.21.attn_qkv_gate.weight q5_K +blk.22.attn_qkv_gate.weight q5_K blk.23.attn_v.weight q5_K -blk.24.attn_qkv.weight q5_K -blk.25.attn_qkv.weight q5_K -blk.26.attn_qkv.weight q5_K +blk.24.attn_qkv_gate.weight q5_K +blk.25.attn_qkv_gate.weight q5_K +blk.26.attn_qkv_gate.weight q5_K blk.27.attn_v.weight q5_K -blk.28.attn_qkv.weight q5_K -blk.29.attn_qkv.weight q5_K -blk.30.attn_qkv.weight q5_K +blk.28.attn_qkv_gate.weight q5_K +blk.29.attn_qkv_gate.weight q5_K +blk.30.attn_qkv_gate.weight q5_K blk.31.attn_v.weight q5_K -blk.32.attn_qkv.weight q5_K -blk.33.attn_qkv.weight q5_K -blk.34.attn_qkv.weight q5_K +blk.32.attn_qkv_gate.weight q5_K +blk.33.attn_qkv_gate.weight q5_K +blk.34.attn_qkv_gate.weight q5_K blk.35.attn_v.weight q5_K -blk.36.attn_qkv.weight q5_K -blk.37.attn_qkv.weight q5_K -blk.38.attn_qkv.weight q5_K +blk.36.attn_qkv_gate.weight q5_K +blk.37.attn_qkv_gate.weight q5_K +blk.38.attn_qkv_gate.weight q5_K blk.39.attn_v.weight q5_K -blk.40.attn_qkv.weight q5_K -blk.41.attn_qkv.weight q5_K -blk.42.attn_qkv.weight q5_K +blk.40.attn_qkv_gate.weight q5_K +blk.41.attn_qkv_gate.weight q5_K +blk.42.attn_qkv_gate.weight q5_K blk.43.attn_v.weight q5_K -blk.44.attn_qkv.weight q5_K -blk.45.attn_qkv.weight q5_K -blk.46.attn_qkv.weight q5_K +blk.44.attn_qkv_gate.weight q5_K +blk.45.attn_qkv_gate.weight q5_K +blk.46.attn_qkv_gate.weight q5_K blk.47.attn_v.weight q5_K -blk.48.attn_qkv.weight q5_K -blk.49.attn_qkv.weight q5_K -blk.50.attn_qkv.weight q5_K +blk.48.attn_qkv_gate.weight q5_K +blk.49.attn_qkv_gate.weight q5_K +blk.50.attn_qkv_gate.weight q5_K blk.51.attn_v.weight q5_K -blk.52.attn_qkv.weight q5_K -blk.53.attn_qkv.weight q5_K -blk.54.attn_qkv.weight q5_K +blk.52.attn_qkv_gate.weight q5_K +blk.53.attn_qkv_gate.weight q5_K +blk.54.attn_qkv_gate.weight q5_K blk.55.attn_v.weight q5_K -blk.56.attn_qkv.weight q5_K -blk.57.attn_qkv.weight q5_K -blk.58.attn_qkv.weight q5_K +blk.56.attn_qkv_gate.weight q5_K +blk.57.attn_qkv_gate.weight q5_K +blk.58.attn_qkv_gate.weight q5_K blk.59.attn_v.weight q5_K -blk.60.attn_qkv.weight q5_K -blk.61.attn_qkv.weight q5_K -blk.62.attn_qkv.weight q5_K +blk.60.attn_qkv_gate.weight q5_K +blk.61.attn_qkv_gate.weight q5_K +blk.62.attn_qkv_gate.weight q5_K blk.63.attn_v.weight q5_K [IQ3_S] iq3_s output.weight q6_K -blk.0.attn_qkv.weight q4_K -blk.1.attn_qkv.weight q4_K -blk.2.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K +blk.1.attn_qkv_gate.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.3.attn_v.weight q4_K -blk.4.attn_qkv.weight q4_K -blk.5.attn_qkv.weight q4_K -blk.6.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K +blk.5.attn_qkv_gate.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.7.attn_v.weight q4_K -blk.8.attn_qkv.weight q4_K -blk.9.attn_qkv.weight q4_K -blk.10.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K +blk.9.attn_qkv_gate.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.11.attn_v.weight q4_K -blk.12.attn_qkv.weight q4_K -blk.13.attn_qkv.weight q4_K -blk.14.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K +blk.13.attn_qkv_gate.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.15.attn_v.weight q4_K -blk.16.attn_qkv.weight q4_K -blk.17.attn_qkv.weight q4_K -blk.18.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K +blk.17.attn_qkv_gate.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.19.attn_v.weight q4_K -blk.20.attn_qkv.weight q4_K -blk.21.attn_qkv.weight q4_K -blk.22.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K +blk.21.attn_qkv_gate.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.23.attn_v.weight q4_K -blk.24.attn_qkv.weight q4_K -blk.25.attn_qkv.weight q4_K -blk.26.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K +blk.25.attn_qkv_gate.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.27.attn_v.weight q4_K -blk.28.attn_qkv.weight q4_K -blk.29.attn_qkv.weight q4_K -blk.30.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K +blk.29.attn_qkv_gate.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.31.attn_v.weight q4_K -blk.32.attn_qkv.weight q4_K -blk.33.attn_qkv.weight q4_K -blk.34.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K +blk.33.attn_qkv_gate.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.35.attn_v.weight q4_K -blk.36.attn_qkv.weight q4_K -blk.37.attn_qkv.weight q4_K -blk.38.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K +blk.37.attn_qkv_gate.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.39.attn_v.weight q4_K -blk.40.attn_qkv.weight q4_K -blk.41.attn_qkv.weight q4_K -blk.42.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K +blk.41.attn_qkv_gate.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.43.attn_v.weight q4_K -blk.44.attn_qkv.weight q4_K -blk.45.attn_qkv.weight q4_K -blk.46.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K +blk.45.attn_qkv_gate.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.47.attn_v.weight q4_K -blk.48.attn_qkv.weight q4_K -blk.49.attn_qkv.weight q4_K -blk.50.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K +blk.49.attn_qkv_gate.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.51.attn_v.weight q4_K -blk.52.attn_qkv.weight q4_K -blk.53.attn_qkv.weight q4_K -blk.54.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K +blk.53.attn_qkv_gate.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.55.attn_v.weight q4_K -blk.56.attn_qkv.weight q4_K -blk.57.attn_qkv.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K +blk.57.attn_qkv_gate.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.59.attn_v.weight q4_K -blk.60.attn_qkv.weight q4_K -blk.61.attn_qkv.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K +blk.61.attn_qkv_gate.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.63.attn_v.weight q4_K [IQ3_M] iq3_s output.weight q6_K -blk.0.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K blk.0.ffn_down.weight q4_K -blk.1.attn_qkv.weight q4_K +blk.1.attn_qkv_gate.weight q4_K blk.1.ffn_down.weight q4_K -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight q4_K blk.3.attn_output.weight q4_K blk.3.attn_v.weight q4_K blk.3.ffn_down.weight q4_K -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight q4_K -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight q4_K -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight q4_K blk.7.attn_output.weight q4_K blk.7.attn_v.weight q4_K blk.7.ffn_down.weight q4_K -blk.8.attn_qkv.weight q4_K -blk.9.attn_qkv.weight q4_K -blk.10.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K +blk.9.attn_qkv_gate.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.11.attn_output.weight q4_K blk.11.attn_v.weight q4_K -blk.12.attn_qkv.weight q4_K -blk.13.attn_qkv.weight q4_K -blk.14.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K +blk.13.attn_qkv_gate.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.15.attn_output.weight q4_K blk.15.attn_v.weight q4_K -blk.16.attn_qkv.weight q4_K -blk.17.attn_qkv.weight q4_K -blk.18.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K +blk.17.attn_qkv_gate.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.19.attn_output.weight q4_K blk.19.attn_v.weight q4_K -blk.20.attn_qkv.weight q4_K -blk.21.attn_qkv.weight q4_K -blk.22.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K +blk.21.attn_qkv_gate.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.23.attn_output.weight q4_K blk.23.attn_v.weight q4_K -blk.24.attn_qkv.weight q4_K -blk.25.attn_qkv.weight q4_K -blk.26.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K +blk.25.attn_qkv_gate.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.27.attn_output.weight q4_K blk.27.attn_v.weight q4_K -blk.28.attn_qkv.weight q4_K -blk.29.attn_qkv.weight q4_K -blk.30.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K +blk.29.attn_qkv_gate.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.31.attn_output.weight q4_K blk.31.attn_v.weight q4_K -blk.32.attn_qkv.weight q4_K -blk.33.attn_qkv.weight q4_K -blk.34.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K +blk.33.attn_qkv_gate.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.35.attn_output.weight q4_K blk.35.attn_v.weight q4_K -blk.36.attn_qkv.weight q4_K -blk.37.attn_qkv.weight q4_K -blk.38.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K +blk.37.attn_qkv_gate.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.39.attn_output.weight q4_K blk.39.attn_v.weight q4_K -blk.40.attn_qkv.weight q4_K -blk.41.attn_qkv.weight q4_K -blk.42.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K +blk.41.attn_qkv_gate.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.43.attn_output.weight q4_K blk.43.attn_v.weight q4_K -blk.44.attn_qkv.weight q4_K -blk.45.attn_qkv.weight q4_K -blk.46.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K +blk.45.attn_qkv_gate.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.47.attn_output.weight q4_K blk.47.attn_v.weight q4_K -blk.48.attn_qkv.weight q4_K -blk.49.attn_qkv.weight q4_K -blk.50.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K +blk.49.attn_qkv_gate.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.51.attn_output.weight q4_K blk.51.attn_v.weight q4_K -blk.52.attn_qkv.weight q4_K -blk.53.attn_qkv.weight q4_K -blk.54.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K +blk.53.attn_qkv_gate.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.55.attn_output.weight q4_K blk.55.attn_v.weight q4_K -blk.56.attn_qkv.weight q4_K -blk.57.attn_qkv.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K +blk.57.attn_qkv_gate.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.59.attn_output.weight q4_K blk.59.attn_v.weight q4_K -blk.60.attn_qkv.weight q4_K -blk.61.attn_qkv.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K +blk.61.attn_qkv_gate.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.63.attn_output.weight q4_K blk.63.attn_v.weight q4_K [IQ2_S] iq2_xs output.weight q5_K token_embd.weight iq3_s -blk.0.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K blk.0.ffn_down.weight iq3_s -blk.1.attn_qkv.weight q4_K +blk.1.attn_qkv_gate.weight q4_K blk.1.ffn_down.weight iq3_s -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight iq3_s blk.3.attn_output.weight iq3_s blk.3.attn_v.weight q4_K blk.3.ffn_down.weight iq3_s -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight iq3_s -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight iq3_s -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight iq3_s blk.7.attn_output.weight iq3_s blk.7.attn_v.weight q4_K blk.7.ffn_down.weight iq3_s -blk.8.attn_qkv.weight q4_K -blk.9.attn_qkv.weight q4_K -blk.10.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K +blk.9.attn_qkv_gate.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.11.attn_output.weight iq3_s blk.11.attn_v.weight q4_K -blk.12.attn_qkv.weight q4_K -blk.13.attn_qkv.weight q4_K -blk.14.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K +blk.13.attn_qkv_gate.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.15.attn_output.weight iq3_s blk.15.attn_v.weight q4_K -blk.16.attn_qkv.weight q4_K -blk.17.attn_qkv.weight q4_K -blk.18.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K +blk.17.attn_qkv_gate.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.19.attn_output.weight iq3_s blk.19.attn_v.weight q4_K -blk.20.attn_qkv.weight q4_K -blk.21.attn_qkv.weight q4_K -blk.22.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K +blk.21.attn_qkv_gate.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.23.attn_output.weight iq3_s blk.23.attn_v.weight q4_K -blk.24.attn_qkv.weight q4_K -blk.25.attn_qkv.weight q4_K -blk.26.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K +blk.25.attn_qkv_gate.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.27.attn_output.weight iq3_s blk.27.attn_v.weight q4_K -blk.28.attn_qkv.weight q4_K -blk.29.attn_qkv.weight q4_K -blk.30.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K +blk.29.attn_qkv_gate.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.31.attn_output.weight iq3_s blk.31.attn_v.weight q4_K -blk.32.attn_qkv.weight q4_K -blk.33.attn_qkv.weight q4_K -blk.34.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K +blk.33.attn_qkv_gate.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.35.attn_output.weight iq3_s blk.35.attn_v.weight q4_K -blk.36.attn_qkv.weight q4_K -blk.37.attn_qkv.weight q4_K -blk.38.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K +blk.37.attn_qkv_gate.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.39.attn_output.weight iq3_s blk.39.attn_v.weight q4_K -blk.40.attn_qkv.weight q4_K -blk.41.attn_qkv.weight q4_K -blk.42.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K +blk.41.attn_qkv_gate.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.43.attn_output.weight iq3_s blk.43.attn_v.weight q4_K -blk.44.attn_qkv.weight q4_K -blk.45.attn_qkv.weight q4_K -blk.46.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K +blk.45.attn_qkv_gate.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.47.attn_output.weight iq3_s blk.47.attn_v.weight q4_K -blk.48.attn_qkv.weight q4_K -blk.49.attn_qkv.weight q4_K -blk.50.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K +blk.49.attn_qkv_gate.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.51.attn_output.weight iq3_s blk.51.attn_v.weight q4_K -blk.52.attn_qkv.weight q4_K -blk.53.attn_qkv.weight q4_K -blk.54.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K +blk.53.attn_qkv_gate.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.55.attn_output.weight iq3_s blk.55.attn_v.weight q4_K -blk.56.attn_qkv.weight q4_K -blk.57.attn_qkv.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K +blk.57.attn_qkv_gate.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.59.attn_output.weight iq3_s blk.59.attn_v.weight q4_K -blk.60.attn_qkv.weight q4_K -blk.61.attn_qkv.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K +blk.61.attn_qkv_gate.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.63.attn_output.weight iq3_s blk.63.attn_v.weight q4_K [IQ2_M] iq2_s output.weight q5_K token_embd.weight iq3_s -blk.0.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K blk.0.ffn_down.weight iq3_s -blk.1.attn_qkv.weight q4_K +blk.1.attn_qkv_gate.weight q4_K blk.1.ffn_down.weight iq3_s -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight iq3_s blk.3.attn_output.weight iq3_s blk.3.attn_v.weight q4_K blk.3.ffn_down.weight iq3_s -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight iq3_s -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight iq3_s -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight iq3_s blk.7.attn_output.weight iq3_s blk.7.attn_v.weight q4_K blk.7.ffn_down.weight iq3_s -blk.8.attn_qkv.weight q4_K -blk.9.attn_qkv.weight q4_K -blk.10.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K +blk.9.attn_qkv_gate.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.11.attn_output.weight iq3_s blk.11.attn_v.weight q4_K -blk.12.attn_qkv.weight q4_K -blk.13.attn_qkv.weight q4_K -blk.14.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K +blk.13.attn_qkv_gate.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.15.attn_output.weight iq3_s blk.15.attn_v.weight q4_K -blk.16.attn_qkv.weight q4_K -blk.17.attn_qkv.weight q4_K -blk.18.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K +blk.17.attn_qkv_gate.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.19.attn_output.weight iq3_s blk.19.attn_v.weight q4_K -blk.20.attn_qkv.weight q4_K -blk.21.attn_qkv.weight q4_K -blk.22.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K +blk.21.attn_qkv_gate.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.23.attn_output.weight iq3_s blk.23.attn_v.weight q4_K -blk.24.attn_qkv.weight q4_K -blk.25.attn_qkv.weight q4_K -blk.26.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K +blk.25.attn_qkv_gate.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.27.attn_output.weight iq3_s blk.27.attn_v.weight q4_K -blk.28.attn_qkv.weight q4_K -blk.29.attn_qkv.weight q4_K -blk.30.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K +blk.29.attn_qkv_gate.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.31.attn_output.weight iq3_s blk.31.attn_v.weight q4_K -blk.32.attn_qkv.weight q4_K -blk.33.attn_qkv.weight q4_K -blk.34.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K +blk.33.attn_qkv_gate.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.35.attn_output.weight iq3_s blk.35.attn_v.weight q4_K -blk.36.attn_qkv.weight q4_K -blk.37.attn_qkv.weight q4_K -blk.38.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K +blk.37.attn_qkv_gate.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.39.attn_output.weight iq3_s blk.39.attn_v.weight q4_K -blk.40.attn_qkv.weight q4_K -blk.41.attn_qkv.weight q4_K -blk.42.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K +blk.41.attn_qkv_gate.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.43.attn_output.weight iq3_s blk.43.attn_v.weight q4_K -blk.44.attn_qkv.weight q4_K -blk.45.attn_qkv.weight q4_K -blk.46.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K +blk.45.attn_qkv_gate.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.47.attn_output.weight iq3_s blk.47.attn_v.weight q4_K -blk.48.attn_qkv.weight q4_K -blk.49.attn_qkv.weight q4_K -blk.50.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K +blk.49.attn_qkv_gate.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.51.attn_output.weight iq3_s blk.51.attn_v.weight q4_K -blk.52.attn_qkv.weight q4_K -blk.53.attn_qkv.weight q4_K -blk.54.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K +blk.53.attn_qkv_gate.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.55.attn_output.weight iq3_s blk.55.attn_v.weight q4_K -blk.56.attn_qkv.weight q4_K -blk.57.attn_qkv.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K +blk.57.attn_qkv_gate.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.59.attn_output.weight iq3_s blk.59.attn_v.weight q4_K -blk.60.attn_qkv.weight q4_K -blk.61.attn_qkv.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K +blk.61.attn_qkv_gate.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.63.attn_output.weight iq3_s blk.63.attn_v.weight q4_K [IQ4_XS] iq4_xs output.weight q6_K -blk.0.attn_qkv.weight q5_K +blk.0.attn_qkv_gate.weight q5_K blk.0.ffn_down.weight q5_K -blk.1.attn_qkv.weight q5_K +blk.1.attn_qkv_gate.weight q5_K blk.1.ffn_down.weight q5_K -blk.2.attn_qkv.weight q5_K +blk.2.attn_qkv_gate.weight q5_K blk.2.ffn_down.weight q5_K blk.3.attn_v.weight q5_K blk.3.ffn_down.weight q5_K -blk.4.attn_qkv.weight q5_K +blk.4.attn_qkv_gate.weight q5_K blk.4.ffn_down.weight q5_K -blk.5.attn_qkv.weight q5_K +blk.5.attn_qkv_gate.weight q5_K blk.5.ffn_down.weight q5_K -blk.6.attn_qkv.weight q5_K +blk.6.attn_qkv_gate.weight q5_K blk.6.ffn_down.weight q5_K blk.7.attn_v.weight q5_K blk.7.ffn_down.weight q5_K -blk.8.attn_qkv.weight q5_K -blk.9.attn_qkv.weight q5_K -blk.10.attn_qkv.weight q5_K +blk.8.attn_qkv_gate.weight q5_K +blk.9.attn_qkv_gate.weight q5_K +blk.10.attn_qkv_gate.weight q5_K blk.11.attn_v.weight q5_K -blk.12.attn_qkv.weight q5_K -blk.13.attn_qkv.weight q5_K -blk.14.attn_qkv.weight q5_K +blk.12.attn_qkv_gate.weight q5_K +blk.13.attn_qkv_gate.weight q5_K +blk.14.attn_qkv_gate.weight q5_K blk.15.attn_v.weight q5_K -blk.16.attn_qkv.weight q5_K -blk.17.attn_qkv.weight q5_K -blk.18.attn_qkv.weight q5_K +blk.16.attn_qkv_gate.weight q5_K +blk.17.attn_qkv_gate.weight q5_K +blk.18.attn_qkv_gate.weight q5_K blk.19.attn_v.weight q5_K -blk.20.attn_qkv.weight q5_K -blk.21.attn_qkv.weight q5_K -blk.22.attn_qkv.weight q5_K +blk.20.attn_qkv_gate.weight q5_K +blk.21.attn_qkv_gate.weight q5_K +blk.22.attn_qkv_gate.weight q5_K blk.23.attn_v.weight q5_K -blk.24.attn_qkv.weight q5_K -blk.25.attn_qkv.weight q5_K -blk.26.attn_qkv.weight q5_K +blk.24.attn_qkv_gate.weight q5_K +blk.25.attn_qkv_gate.weight q5_K +blk.26.attn_qkv_gate.weight q5_K blk.27.attn_v.weight q5_K -blk.28.attn_qkv.weight q5_K -blk.29.attn_qkv.weight q5_K -blk.30.attn_qkv.weight q5_K +blk.28.attn_qkv_gate.weight q5_K +blk.29.attn_qkv_gate.weight q5_K +blk.30.attn_qkv_gate.weight q5_K blk.31.attn_v.weight q5_K -blk.32.attn_qkv.weight q5_K -blk.33.attn_qkv.weight q5_K -blk.34.attn_qkv.weight q5_K +blk.32.attn_qkv_gate.weight q5_K +blk.33.attn_qkv_gate.weight q5_K +blk.34.attn_qkv_gate.weight q5_K blk.35.attn_v.weight q5_K -blk.36.attn_qkv.weight q5_K -blk.37.attn_qkv.weight q5_K -blk.38.attn_qkv.weight q5_K +blk.36.attn_qkv_gate.weight q5_K +blk.37.attn_qkv_gate.weight q5_K +blk.38.attn_qkv_gate.weight q5_K blk.39.attn_v.weight q5_K -blk.40.attn_qkv.weight q5_K -blk.41.attn_qkv.weight q5_K -blk.42.attn_qkv.weight q5_K +blk.40.attn_qkv_gate.weight q5_K +blk.41.attn_qkv_gate.weight q5_K +blk.42.attn_qkv_gate.weight q5_K blk.43.attn_v.weight q5_K -blk.44.attn_qkv.weight q5_K -blk.45.attn_qkv.weight q5_K -blk.46.attn_qkv.weight q5_K +blk.44.attn_qkv_gate.weight q5_K +blk.45.attn_qkv_gate.weight q5_K +blk.46.attn_qkv_gate.weight q5_K blk.47.attn_v.weight q5_K -blk.48.attn_qkv.weight q5_K -blk.49.attn_qkv.weight q5_K -blk.50.attn_qkv.weight q5_K +blk.48.attn_qkv_gate.weight q5_K +blk.49.attn_qkv_gate.weight q5_K +blk.50.attn_qkv_gate.weight q5_K blk.51.attn_v.weight q5_K -blk.52.attn_qkv.weight q5_K -blk.53.attn_qkv.weight q5_K -blk.54.attn_qkv.weight q5_K +blk.52.attn_qkv_gate.weight q5_K +blk.53.attn_qkv_gate.weight q5_K +blk.54.attn_qkv_gate.weight q5_K blk.55.attn_v.weight q5_K -blk.56.attn_qkv.weight q5_K -blk.57.attn_qkv.weight q5_K -blk.58.attn_qkv.weight q5_K +blk.56.attn_qkv_gate.weight q5_K +blk.57.attn_qkv_gate.weight q5_K +blk.58.attn_qkv_gate.weight q5_K blk.59.attn_v.weight q5_K -blk.60.attn_qkv.weight q5_K -blk.61.attn_qkv.weight q5_K -blk.62.attn_qkv.weight q5_K +blk.60.attn_qkv_gate.weight q5_K +blk.61.attn_qkv_gate.weight q5_K +blk.62.attn_qkv_gate.weight q5_K blk.63.attn_v.weight q5_K [IQ1_M] iq1_m output.weight q5_K token_embd.weight q2_K -blk.0.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K blk.0.ffn_down.weight q2_K -blk.1.attn_qkv.weight q4_K +blk.1.attn_qkv_gate.weight q4_K blk.1.ffn_down.weight q2_K -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight q2_K blk.3.attn_output.weight iq2_xxs blk.3.attn_v.weight q4_K blk.3.ffn_down.weight q2_K -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight q2_K -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight q2_K -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight q2_K blk.7.attn_output.weight iq2_xxs blk.7.attn_v.weight q4_K blk.7.ffn_down.weight q2_K -blk.8.attn_qkv.weight q4_K -blk.9.attn_qkv.weight q4_K -blk.10.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K +blk.9.attn_qkv_gate.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.11.attn_output.weight iq2_xxs blk.11.attn_v.weight q4_K -blk.12.attn_qkv.weight q4_K -blk.13.attn_qkv.weight q4_K -blk.14.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K +blk.13.attn_qkv_gate.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.15.attn_output.weight iq2_xxs blk.15.attn_v.weight q4_K -blk.16.attn_qkv.weight q4_K -blk.17.attn_qkv.weight q4_K -blk.18.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K +blk.17.attn_qkv_gate.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.19.attn_output.weight iq2_xxs blk.19.attn_v.weight q4_K -blk.20.attn_qkv.weight q4_K -blk.21.attn_qkv.weight q4_K -blk.22.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K +blk.21.attn_qkv_gate.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.23.attn_output.weight iq2_xxs blk.23.attn_v.weight q4_K -blk.24.attn_qkv.weight q4_K -blk.25.attn_qkv.weight q4_K -blk.26.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K +blk.25.attn_qkv_gate.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.27.attn_output.weight iq2_xxs blk.27.attn_v.weight q4_K -blk.28.attn_qkv.weight q4_K -blk.29.attn_qkv.weight q4_K -blk.30.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K +blk.29.attn_qkv_gate.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.31.attn_output.weight iq2_xxs blk.31.attn_v.weight q4_K -blk.32.attn_qkv.weight q4_K -blk.33.attn_qkv.weight q4_K -blk.34.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K +blk.33.attn_qkv_gate.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.35.attn_output.weight iq2_xxs blk.35.attn_v.weight q4_K -blk.36.attn_qkv.weight q4_K -blk.37.attn_qkv.weight q4_K -blk.38.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K +blk.37.attn_qkv_gate.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.39.attn_output.weight iq2_xxs blk.39.attn_v.weight q4_K -blk.40.attn_qkv.weight q4_K -blk.41.attn_qkv.weight q4_K -blk.42.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K +blk.41.attn_qkv_gate.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.43.attn_output.weight iq2_xxs blk.43.attn_v.weight q4_K -blk.44.attn_qkv.weight q4_K -blk.45.attn_qkv.weight q4_K -blk.46.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K +blk.45.attn_qkv_gate.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.47.attn_output.weight iq2_xxs blk.47.attn_v.weight q4_K -blk.48.attn_qkv.weight q4_K -blk.49.attn_qkv.weight q4_K -blk.50.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K +blk.49.attn_qkv_gate.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.51.attn_output.weight iq2_xxs blk.51.attn_v.weight q4_K -blk.52.attn_qkv.weight q4_K -blk.53.attn_qkv.weight q4_K -blk.54.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K +blk.53.attn_qkv_gate.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.55.attn_output.weight iq2_xxs blk.55.attn_v.weight q4_K -blk.56.attn_qkv.weight q4_K -blk.57.attn_qkv.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K +blk.57.attn_qkv_gate.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.59.attn_output.weight iq2_xxs blk.59.attn_v.weight q4_K -blk.60.attn_qkv.weight q4_K -blk.61.attn_qkv.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K +blk.61.attn_qkv_gate.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.63.attn_output.weight iq2_xxs blk.63.attn_v.weight q4_K @@ -1908,29 +1908,23 @@ token_embd.weight q4_K [MXFP4_MOE] mxfp4 output.weight q8_0 token_embd.weight q8_0 -blk.0.attn_gate.weight q8_0 -blk.0.attn_qkv.weight q8_0 +blk.0.attn_qkv_gate.weight q8_0 blk.0.ffn_down.weight q8_0 blk.0.ffn_gate.weight q8_0 blk.0.ffn_up.weight q8_0 -blk.0.ssm_alpha.weight q8_0 -blk.0.ssm_beta.weight q8_0 +blk.0.ssm_beta_alpha.weight q8_0 blk.0.ssm_out.weight q8_0 -blk.1.attn_gate.weight q8_0 -blk.1.attn_qkv.weight q8_0 +blk.1.attn_qkv_gate.weight q8_0 blk.1.ffn_down.weight q8_0 blk.1.ffn_gate.weight q8_0 blk.1.ffn_up.weight q8_0 -blk.1.ssm_alpha.weight q8_0 -blk.1.ssm_beta.weight q8_0 +blk.1.ssm_beta_alpha.weight q8_0 blk.1.ssm_out.weight q8_0 -blk.2.attn_gate.weight q8_0 -blk.2.attn_qkv.weight q8_0 +blk.2.attn_qkv_gate.weight q8_0 blk.2.ffn_down.weight q8_0 blk.2.ffn_gate.weight q8_0 blk.2.ffn_up.weight q8_0 -blk.2.ssm_alpha.weight q8_0 -blk.2.ssm_beta.weight q8_0 +blk.2.ssm_beta_alpha.weight q8_0 blk.2.ssm_out.weight q8_0 blk.3.attn_k.weight q8_0 blk.3.attn_output.weight q8_0 @@ -1939,29 +1933,23 @@ blk.3.attn_v.weight q8_0 blk.3.ffn_down.weight q8_0 blk.3.ffn_gate.weight q8_0 blk.3.ffn_up.weight q8_0 -blk.4.attn_gate.weight q8_0 -blk.4.attn_qkv.weight q8_0 +blk.4.attn_qkv_gate.weight q8_0 blk.4.ffn_down.weight q8_0 blk.4.ffn_gate.weight q8_0 blk.4.ffn_up.weight q8_0 -blk.4.ssm_alpha.weight q8_0 -blk.4.ssm_beta.weight q8_0 +blk.4.ssm_beta_alpha.weight q8_0 blk.4.ssm_out.weight q8_0 -blk.5.attn_gate.weight q8_0 -blk.5.attn_qkv.weight q8_0 +blk.5.attn_qkv_gate.weight q8_0 blk.5.ffn_down.weight q8_0 blk.5.ffn_gate.weight q8_0 blk.5.ffn_up.weight q8_0 -blk.5.ssm_alpha.weight q8_0 -blk.5.ssm_beta.weight q8_0 +blk.5.ssm_beta_alpha.weight q8_0 blk.5.ssm_out.weight q8_0 -blk.6.attn_gate.weight q8_0 -blk.6.attn_qkv.weight q8_0 +blk.6.attn_qkv_gate.weight q8_0 blk.6.ffn_down.weight q8_0 blk.6.ffn_gate.weight q8_0 blk.6.ffn_up.weight q8_0 -blk.6.ssm_alpha.weight q8_0 -blk.6.ssm_beta.weight q8_0 +blk.6.ssm_beta_alpha.weight q8_0 blk.6.ssm_out.weight q8_0 blk.7.attn_k.weight q8_0 blk.7.attn_output.weight q8_0 @@ -1970,29 +1958,23 @@ blk.7.attn_v.weight q8_0 blk.7.ffn_down.weight q8_0 blk.7.ffn_gate.weight q8_0 blk.7.ffn_up.weight q8_0 -blk.8.attn_gate.weight q8_0 -blk.8.attn_qkv.weight q8_0 +blk.8.attn_qkv_gate.weight q8_0 blk.8.ffn_down.weight q8_0 blk.8.ffn_gate.weight q8_0 blk.8.ffn_up.weight q8_0 -blk.8.ssm_alpha.weight q8_0 -blk.8.ssm_beta.weight q8_0 +blk.8.ssm_beta_alpha.weight q8_0 blk.8.ssm_out.weight q8_0 -blk.9.attn_gate.weight q8_0 -blk.9.attn_qkv.weight q8_0 +blk.9.attn_qkv_gate.weight q8_0 blk.9.ffn_down.weight q8_0 blk.9.ffn_gate.weight q8_0 blk.9.ffn_up.weight q8_0 -blk.9.ssm_alpha.weight q8_0 -blk.9.ssm_beta.weight q8_0 +blk.9.ssm_beta_alpha.weight q8_0 blk.9.ssm_out.weight q8_0 -blk.10.attn_gate.weight q8_0 -blk.10.attn_qkv.weight q8_0 +blk.10.attn_qkv_gate.weight q8_0 blk.10.ffn_down.weight q8_0 blk.10.ffn_gate.weight q8_0 blk.10.ffn_up.weight q8_0 -blk.10.ssm_alpha.weight q8_0 -blk.10.ssm_beta.weight q8_0 +blk.10.ssm_beta_alpha.weight q8_0 blk.10.ssm_out.weight q8_0 blk.11.attn_k.weight q8_0 blk.11.attn_output.weight q8_0 @@ -2001,29 +1983,23 @@ blk.11.attn_v.weight q8_0 blk.11.ffn_down.weight q8_0 blk.11.ffn_gate.weight q8_0 blk.11.ffn_up.weight q8_0 -blk.12.attn_gate.weight q8_0 -blk.12.attn_qkv.weight q8_0 +blk.12.attn_qkv_gate.weight q8_0 blk.12.ffn_down.weight q8_0 blk.12.ffn_gate.weight q8_0 blk.12.ffn_up.weight q8_0 -blk.12.ssm_alpha.weight q8_0 -blk.12.ssm_beta.weight q8_0 +blk.12.ssm_beta_alpha.weight q8_0 blk.12.ssm_out.weight q8_0 -blk.13.attn_gate.weight q8_0 -blk.13.attn_qkv.weight q8_0 +blk.13.attn_qkv_gate.weight q8_0 blk.13.ffn_down.weight q8_0 blk.13.ffn_gate.weight q8_0 blk.13.ffn_up.weight q8_0 -blk.13.ssm_alpha.weight q8_0 -blk.13.ssm_beta.weight q8_0 +blk.13.ssm_beta_alpha.weight q8_0 blk.13.ssm_out.weight q8_0 -blk.14.attn_gate.weight q8_0 -blk.14.attn_qkv.weight q8_0 +blk.14.attn_qkv_gate.weight q8_0 blk.14.ffn_down.weight q8_0 blk.14.ffn_gate.weight q8_0 blk.14.ffn_up.weight q8_0 -blk.14.ssm_alpha.weight q8_0 -blk.14.ssm_beta.weight q8_0 +blk.14.ssm_beta_alpha.weight q8_0 blk.14.ssm_out.weight q8_0 blk.15.attn_k.weight q8_0 blk.15.attn_output.weight q8_0 @@ -2032,29 +2008,23 @@ blk.15.attn_v.weight q8_0 blk.15.ffn_down.weight q8_0 blk.15.ffn_gate.weight q8_0 blk.15.ffn_up.weight q8_0 -blk.16.attn_gate.weight q8_0 -blk.16.attn_qkv.weight q8_0 +blk.16.attn_qkv_gate.weight q8_0 blk.16.ffn_down.weight q8_0 blk.16.ffn_gate.weight q8_0 blk.16.ffn_up.weight q8_0 -blk.16.ssm_alpha.weight q8_0 -blk.16.ssm_beta.weight q8_0 +blk.16.ssm_beta_alpha.weight q8_0 blk.16.ssm_out.weight q8_0 -blk.17.attn_gate.weight q8_0 -blk.17.attn_qkv.weight q8_0 +blk.17.attn_qkv_gate.weight q8_0 blk.17.ffn_down.weight q8_0 blk.17.ffn_gate.weight q8_0 blk.17.ffn_up.weight q8_0 -blk.17.ssm_alpha.weight q8_0 -blk.17.ssm_beta.weight q8_0 +blk.17.ssm_beta_alpha.weight q8_0 blk.17.ssm_out.weight q8_0 -blk.18.attn_gate.weight q8_0 -blk.18.attn_qkv.weight q8_0 +blk.18.attn_qkv_gate.weight q8_0 blk.18.ffn_down.weight q8_0 blk.18.ffn_gate.weight q8_0 blk.18.ffn_up.weight q8_0 -blk.18.ssm_alpha.weight q8_0 -blk.18.ssm_beta.weight q8_0 +blk.18.ssm_beta_alpha.weight q8_0 blk.18.ssm_out.weight q8_0 blk.19.attn_k.weight q8_0 blk.19.attn_output.weight q8_0 @@ -2063,29 +2033,23 @@ blk.19.attn_v.weight q8_0 blk.19.ffn_down.weight q8_0 blk.19.ffn_gate.weight q8_0 blk.19.ffn_up.weight q8_0 -blk.20.attn_gate.weight q8_0 -blk.20.attn_qkv.weight q8_0 +blk.20.attn_qkv_gate.weight q8_0 blk.20.ffn_down.weight q8_0 blk.20.ffn_gate.weight q8_0 blk.20.ffn_up.weight q8_0 -blk.20.ssm_alpha.weight q8_0 -blk.20.ssm_beta.weight q8_0 +blk.20.ssm_beta_alpha.weight q8_0 blk.20.ssm_out.weight q8_0 -blk.21.attn_gate.weight q8_0 -blk.21.attn_qkv.weight q8_0 +blk.21.attn_qkv_gate.weight q8_0 blk.21.ffn_down.weight q8_0 blk.21.ffn_gate.weight q8_0 blk.21.ffn_up.weight q8_0 -blk.21.ssm_alpha.weight q8_0 -blk.21.ssm_beta.weight q8_0 +blk.21.ssm_beta_alpha.weight q8_0 blk.21.ssm_out.weight q8_0 -blk.22.attn_gate.weight q8_0 -blk.22.attn_qkv.weight q8_0 +blk.22.attn_qkv_gate.weight q8_0 blk.22.ffn_down.weight q8_0 blk.22.ffn_gate.weight q8_0 blk.22.ffn_up.weight q8_0 -blk.22.ssm_alpha.weight q8_0 -blk.22.ssm_beta.weight q8_0 +blk.22.ssm_beta_alpha.weight q8_0 blk.22.ssm_out.weight q8_0 blk.23.attn_k.weight q8_0 blk.23.attn_output.weight q8_0 @@ -2094,29 +2058,23 @@ blk.23.attn_v.weight q8_0 blk.23.ffn_down.weight q8_0 blk.23.ffn_gate.weight q8_0 blk.23.ffn_up.weight q8_0 -blk.24.attn_gate.weight q8_0 -blk.24.attn_qkv.weight q8_0 +blk.24.attn_qkv_gate.weight q8_0 blk.24.ffn_down.weight q8_0 blk.24.ffn_gate.weight q8_0 blk.24.ffn_up.weight q8_0 -blk.24.ssm_alpha.weight q8_0 -blk.24.ssm_beta.weight q8_0 +blk.24.ssm_beta_alpha.weight q8_0 blk.24.ssm_out.weight q8_0 -blk.25.attn_gate.weight q8_0 -blk.25.attn_qkv.weight q8_0 +blk.25.attn_qkv_gate.weight q8_0 blk.25.ffn_down.weight q8_0 blk.25.ffn_gate.weight q8_0 blk.25.ffn_up.weight q8_0 -blk.25.ssm_alpha.weight q8_0 -blk.25.ssm_beta.weight q8_0 +blk.25.ssm_beta_alpha.weight q8_0 blk.25.ssm_out.weight q8_0 -blk.26.attn_gate.weight q8_0 -blk.26.attn_qkv.weight q8_0 +blk.26.attn_qkv_gate.weight q8_0 blk.26.ffn_down.weight q8_0 blk.26.ffn_gate.weight q8_0 blk.26.ffn_up.weight q8_0 -blk.26.ssm_alpha.weight q8_0 -blk.26.ssm_beta.weight q8_0 +blk.26.ssm_beta_alpha.weight q8_0 blk.26.ssm_out.weight q8_0 blk.27.attn_k.weight q8_0 blk.27.attn_output.weight q8_0 @@ -2125,29 +2083,23 @@ blk.27.attn_v.weight q8_0 blk.27.ffn_down.weight q8_0 blk.27.ffn_gate.weight q8_0 blk.27.ffn_up.weight q8_0 -blk.28.attn_gate.weight q8_0 -blk.28.attn_qkv.weight q8_0 +blk.28.attn_qkv_gate.weight q8_0 blk.28.ffn_down.weight q8_0 blk.28.ffn_gate.weight q8_0 blk.28.ffn_up.weight q8_0 -blk.28.ssm_alpha.weight q8_0 -blk.28.ssm_beta.weight q8_0 +blk.28.ssm_beta_alpha.weight q8_0 blk.28.ssm_out.weight q8_0 -blk.29.attn_gate.weight q8_0 -blk.29.attn_qkv.weight q8_0 +blk.29.attn_qkv_gate.weight q8_0 blk.29.ffn_down.weight q8_0 blk.29.ffn_gate.weight q8_0 blk.29.ffn_up.weight q8_0 -blk.29.ssm_alpha.weight q8_0 -blk.29.ssm_beta.weight q8_0 +blk.29.ssm_beta_alpha.weight q8_0 blk.29.ssm_out.weight q8_0 -blk.30.attn_gate.weight q8_0 -blk.30.attn_qkv.weight q8_0 +blk.30.attn_qkv_gate.weight q8_0 blk.30.ffn_down.weight q8_0 blk.30.ffn_gate.weight q8_0 blk.30.ffn_up.weight q8_0 -blk.30.ssm_alpha.weight q8_0 -blk.30.ssm_beta.weight q8_0 +blk.30.ssm_beta_alpha.weight q8_0 blk.30.ssm_out.weight q8_0 blk.31.attn_k.weight q8_0 blk.31.attn_output.weight q8_0 @@ -2156,29 +2108,23 @@ blk.31.attn_v.weight q8_0 blk.31.ffn_down.weight q8_0 blk.31.ffn_gate.weight q8_0 blk.31.ffn_up.weight q8_0 -blk.32.attn_gate.weight q8_0 -blk.32.attn_qkv.weight q8_0 +blk.32.attn_qkv_gate.weight q8_0 blk.32.ffn_down.weight q8_0 blk.32.ffn_gate.weight q8_0 blk.32.ffn_up.weight q8_0 -blk.32.ssm_alpha.weight q8_0 -blk.32.ssm_beta.weight q8_0 +blk.32.ssm_beta_alpha.weight q8_0 blk.32.ssm_out.weight q8_0 -blk.33.attn_gate.weight q8_0 -blk.33.attn_qkv.weight q8_0 +blk.33.attn_qkv_gate.weight q8_0 blk.33.ffn_down.weight q8_0 blk.33.ffn_gate.weight q8_0 blk.33.ffn_up.weight q8_0 -blk.33.ssm_alpha.weight q8_0 -blk.33.ssm_beta.weight q8_0 +blk.33.ssm_beta_alpha.weight q8_0 blk.33.ssm_out.weight q8_0 -blk.34.attn_gate.weight q8_0 -blk.34.attn_qkv.weight q8_0 +blk.34.attn_qkv_gate.weight q8_0 blk.34.ffn_down.weight q8_0 blk.34.ffn_gate.weight q8_0 blk.34.ffn_up.weight q8_0 -blk.34.ssm_alpha.weight q8_0 -blk.34.ssm_beta.weight q8_0 +blk.34.ssm_beta_alpha.weight q8_0 blk.34.ssm_out.weight q8_0 blk.35.attn_k.weight q8_0 blk.35.attn_output.weight q8_0 @@ -2187,29 +2133,23 @@ blk.35.attn_v.weight q8_0 blk.35.ffn_down.weight q8_0 blk.35.ffn_gate.weight q8_0 blk.35.ffn_up.weight q8_0 -blk.36.attn_gate.weight q8_0 -blk.36.attn_qkv.weight q8_0 +blk.36.attn_qkv_gate.weight q8_0 blk.36.ffn_down.weight q8_0 blk.36.ffn_gate.weight q8_0 blk.36.ffn_up.weight q8_0 -blk.36.ssm_alpha.weight q8_0 -blk.36.ssm_beta.weight q8_0 +blk.36.ssm_beta_alpha.weight q8_0 blk.36.ssm_out.weight q8_0 -blk.37.attn_gate.weight q8_0 -blk.37.attn_qkv.weight q8_0 +blk.37.attn_qkv_gate.weight q8_0 blk.37.ffn_down.weight q8_0 blk.37.ffn_gate.weight q8_0 blk.37.ffn_up.weight q8_0 -blk.37.ssm_alpha.weight q8_0 -blk.37.ssm_beta.weight q8_0 +blk.37.ssm_beta_alpha.weight q8_0 blk.37.ssm_out.weight q8_0 -blk.38.attn_gate.weight q8_0 -blk.38.attn_qkv.weight q8_0 +blk.38.attn_qkv_gate.weight q8_0 blk.38.ffn_down.weight q8_0 blk.38.ffn_gate.weight q8_0 blk.38.ffn_up.weight q8_0 -blk.38.ssm_alpha.weight q8_0 -blk.38.ssm_beta.weight q8_0 +blk.38.ssm_beta_alpha.weight q8_0 blk.38.ssm_out.weight q8_0 blk.39.attn_k.weight q8_0 blk.39.attn_output.weight q8_0 @@ -2218,29 +2158,23 @@ blk.39.attn_v.weight q8_0 blk.39.ffn_down.weight q8_0 blk.39.ffn_gate.weight q8_0 blk.39.ffn_up.weight q8_0 -blk.40.attn_gate.weight q8_0 -blk.40.attn_qkv.weight q8_0 +blk.40.attn_qkv_gate.weight q8_0 blk.40.ffn_down.weight q8_0 blk.40.ffn_gate.weight q8_0 blk.40.ffn_up.weight q8_0 -blk.40.ssm_alpha.weight q8_0 -blk.40.ssm_beta.weight q8_0 +blk.40.ssm_beta_alpha.weight q8_0 blk.40.ssm_out.weight q8_0 -blk.41.attn_gate.weight q8_0 -blk.41.attn_qkv.weight q8_0 +blk.41.attn_qkv_gate.weight q8_0 blk.41.ffn_down.weight q8_0 blk.41.ffn_gate.weight q8_0 blk.41.ffn_up.weight q8_0 -blk.41.ssm_alpha.weight q8_0 -blk.41.ssm_beta.weight q8_0 +blk.41.ssm_beta_alpha.weight q8_0 blk.41.ssm_out.weight q8_0 -blk.42.attn_gate.weight q8_0 -blk.42.attn_qkv.weight q8_0 +blk.42.attn_qkv_gate.weight q8_0 blk.42.ffn_down.weight q8_0 blk.42.ffn_gate.weight q8_0 blk.42.ffn_up.weight q8_0 -blk.42.ssm_alpha.weight q8_0 -blk.42.ssm_beta.weight q8_0 +blk.42.ssm_beta_alpha.weight q8_0 blk.42.ssm_out.weight q8_0 blk.43.attn_k.weight q8_0 blk.43.attn_output.weight q8_0 @@ -2249,29 +2183,23 @@ blk.43.attn_v.weight q8_0 blk.43.ffn_down.weight q8_0 blk.43.ffn_gate.weight q8_0 blk.43.ffn_up.weight q8_0 -blk.44.attn_gate.weight q8_0 -blk.44.attn_qkv.weight q8_0 +blk.44.attn_qkv_gate.weight q8_0 blk.44.ffn_down.weight q8_0 blk.44.ffn_gate.weight q8_0 blk.44.ffn_up.weight q8_0 -blk.44.ssm_alpha.weight q8_0 -blk.44.ssm_beta.weight q8_0 +blk.44.ssm_beta_alpha.weight q8_0 blk.44.ssm_out.weight q8_0 -blk.45.attn_gate.weight q8_0 -blk.45.attn_qkv.weight q8_0 +blk.45.attn_qkv_gate.weight q8_0 blk.45.ffn_down.weight q8_0 blk.45.ffn_gate.weight q8_0 blk.45.ffn_up.weight q8_0 -blk.45.ssm_alpha.weight q8_0 -blk.45.ssm_beta.weight q8_0 +blk.45.ssm_beta_alpha.weight q8_0 blk.45.ssm_out.weight q8_0 -blk.46.attn_gate.weight q8_0 -blk.46.attn_qkv.weight q8_0 +blk.46.attn_qkv_gate.weight q8_0 blk.46.ffn_down.weight q8_0 blk.46.ffn_gate.weight q8_0 blk.46.ffn_up.weight q8_0 -blk.46.ssm_alpha.weight q8_0 -blk.46.ssm_beta.weight q8_0 +blk.46.ssm_beta_alpha.weight q8_0 blk.46.ssm_out.weight q8_0 blk.47.attn_k.weight q8_0 blk.47.attn_output.weight q8_0 @@ -2280,29 +2208,23 @@ blk.47.attn_v.weight q8_0 blk.47.ffn_down.weight q8_0 blk.47.ffn_gate.weight q8_0 blk.47.ffn_up.weight q8_0 -blk.48.attn_gate.weight q8_0 -blk.48.attn_qkv.weight q8_0 +blk.48.attn_qkv_gate.weight q8_0 blk.48.ffn_down.weight q8_0 blk.48.ffn_gate.weight q8_0 blk.48.ffn_up.weight q8_0 -blk.48.ssm_alpha.weight q8_0 -blk.48.ssm_beta.weight q8_0 +blk.48.ssm_beta_alpha.weight q8_0 blk.48.ssm_out.weight q8_0 -blk.49.attn_gate.weight q8_0 -blk.49.attn_qkv.weight q8_0 +blk.49.attn_qkv_gate.weight q8_0 blk.49.ffn_down.weight q8_0 blk.49.ffn_gate.weight q8_0 blk.49.ffn_up.weight q8_0 -blk.49.ssm_alpha.weight q8_0 -blk.49.ssm_beta.weight q8_0 +blk.49.ssm_beta_alpha.weight q8_0 blk.49.ssm_out.weight q8_0 -blk.50.attn_gate.weight q8_0 -blk.50.attn_qkv.weight q8_0 +blk.50.attn_qkv_gate.weight q8_0 blk.50.ffn_down.weight q8_0 blk.50.ffn_gate.weight q8_0 blk.50.ffn_up.weight q8_0 -blk.50.ssm_alpha.weight q8_0 -blk.50.ssm_beta.weight q8_0 +blk.50.ssm_beta_alpha.weight q8_0 blk.50.ssm_out.weight q8_0 blk.51.attn_k.weight q8_0 blk.51.attn_output.weight q8_0 @@ -2311,29 +2233,23 @@ blk.51.attn_v.weight q8_0 blk.51.ffn_down.weight q8_0 blk.51.ffn_gate.weight q8_0 blk.51.ffn_up.weight q8_0 -blk.52.attn_gate.weight q8_0 -blk.52.attn_qkv.weight q8_0 +blk.52.attn_qkv_gate.weight q8_0 blk.52.ffn_down.weight q8_0 blk.52.ffn_gate.weight q8_0 blk.52.ffn_up.weight q8_0 -blk.52.ssm_alpha.weight q8_0 -blk.52.ssm_beta.weight q8_0 +blk.52.ssm_beta_alpha.weight q8_0 blk.52.ssm_out.weight q8_0 -blk.53.attn_gate.weight q8_0 -blk.53.attn_qkv.weight q8_0 +blk.53.attn_qkv_gate.weight q8_0 blk.53.ffn_down.weight q8_0 blk.53.ffn_gate.weight q8_0 blk.53.ffn_up.weight q8_0 -blk.53.ssm_alpha.weight q8_0 -blk.53.ssm_beta.weight q8_0 +blk.53.ssm_beta_alpha.weight q8_0 blk.53.ssm_out.weight q8_0 -blk.54.attn_gate.weight q8_0 -blk.54.attn_qkv.weight q8_0 +blk.54.attn_qkv_gate.weight q8_0 blk.54.ffn_down.weight q8_0 blk.54.ffn_gate.weight q8_0 blk.54.ffn_up.weight q8_0 -blk.54.ssm_alpha.weight q8_0 -blk.54.ssm_beta.weight q8_0 +blk.54.ssm_beta_alpha.weight q8_0 blk.54.ssm_out.weight q8_0 blk.55.attn_k.weight q8_0 blk.55.attn_output.weight q8_0 @@ -2342,29 +2258,23 @@ blk.55.attn_v.weight q8_0 blk.55.ffn_down.weight q8_0 blk.55.ffn_gate.weight q8_0 blk.55.ffn_up.weight q8_0 -blk.56.attn_gate.weight q8_0 -blk.56.attn_qkv.weight q8_0 +blk.56.attn_qkv_gate.weight q8_0 blk.56.ffn_down.weight q8_0 blk.56.ffn_gate.weight q8_0 blk.56.ffn_up.weight q8_0 -blk.56.ssm_alpha.weight q8_0 -blk.56.ssm_beta.weight q8_0 +blk.56.ssm_beta_alpha.weight q8_0 blk.56.ssm_out.weight q8_0 -blk.57.attn_gate.weight q8_0 -blk.57.attn_qkv.weight q8_0 +blk.57.attn_qkv_gate.weight q8_0 blk.57.ffn_down.weight q8_0 blk.57.ffn_gate.weight q8_0 blk.57.ffn_up.weight q8_0 -blk.57.ssm_alpha.weight q8_0 -blk.57.ssm_beta.weight q8_0 +blk.57.ssm_beta_alpha.weight q8_0 blk.57.ssm_out.weight q8_0 -blk.58.attn_gate.weight q8_0 -blk.58.attn_qkv.weight q8_0 +blk.58.attn_qkv_gate.weight q8_0 blk.58.ffn_down.weight q8_0 blk.58.ffn_gate.weight q8_0 blk.58.ffn_up.weight q8_0 -blk.58.ssm_alpha.weight q8_0 -blk.58.ssm_beta.weight q8_0 +blk.58.ssm_beta_alpha.weight q8_0 blk.58.ssm_out.weight q8_0 blk.59.attn_k.weight q8_0 blk.59.attn_output.weight q8_0 @@ -2373,29 +2283,23 @@ blk.59.attn_v.weight q8_0 blk.59.ffn_down.weight q8_0 blk.59.ffn_gate.weight q8_0 blk.59.ffn_up.weight q8_0 -blk.60.attn_gate.weight q8_0 -blk.60.attn_qkv.weight q8_0 +blk.60.attn_qkv_gate.weight q8_0 blk.60.ffn_down.weight q8_0 blk.60.ffn_gate.weight q8_0 blk.60.ffn_up.weight q8_0 -blk.60.ssm_alpha.weight q8_0 -blk.60.ssm_beta.weight q8_0 +blk.60.ssm_beta_alpha.weight q8_0 blk.60.ssm_out.weight q8_0 -blk.61.attn_gate.weight q8_0 -blk.61.attn_qkv.weight q8_0 +blk.61.attn_qkv_gate.weight q8_0 blk.61.ffn_down.weight q8_0 blk.61.ffn_gate.weight q8_0 blk.61.ffn_up.weight q8_0 -blk.61.ssm_alpha.weight q8_0 -blk.61.ssm_beta.weight q8_0 +blk.61.ssm_beta_alpha.weight q8_0 blk.61.ssm_out.weight q8_0 -blk.62.attn_gate.weight q8_0 -blk.62.attn_qkv.weight q8_0 +blk.62.attn_qkv_gate.weight q8_0 blk.62.ffn_down.weight q8_0 blk.62.ffn_gate.weight q8_0 blk.62.ffn_up.weight q8_0 -blk.62.ssm_alpha.weight q8_0 -blk.62.ssm_beta.weight q8_0 +blk.62.ssm_beta_alpha.weight q8_0 blk.62.ssm_out.weight q8_0 blk.63.attn_k.weight q8_0 blk.63.attn_output.weight q8_0 From 969d7333172c522d6a60fffb8dd35288ce8df236 Mon Sep 17 00:00:00 2001 From: Aaron Teo Date: Mon, 23 Nov 2026 19:30:24 +0800 Subject: [PATCH 013/275] cmake: treat kleidiai files as vendored (#32605) * cmake: treat kleidiai files as vendored Signed-off-by: Aaron Teo * cmake: use quotes and semicolon separators Signed-off-by: Aaron Teo --------- Signed-off-by: Aaron Teo --- ggml/src/ggml-cpu/kleidiai/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-cpu/kleidiai/CMakeLists.txt b/ggml/src/ggml-cpu/kleidiai/CMakeLists.txt index b36cb6d3a9d9..dece531f87ab 100644 --- a/ggml/src/ggml-cpu/kleidiai/CMakeLists.txt +++ b/ggml/src/ggml-cpu/kleidiai/CMakeLists.txt @@ -8,7 +8,7 @@ if (NOT TARGET kleidiai) endif() if (MSVC) - target_compile_options(kleidiai PRIVATE $<$:/WX->) + target_compile_options(kleidiai PRIVATE "$<$:/WX-;/w>") else() - target_compile_options(kleidiai PRIVATE $<$:-Wno-error>) + target_compile_options(kleidiai PRIVATE "$<$:-Wno-error;-w>") endif() From 4663f9ca8a97c525ba3d248711fa2b52050920ec Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Mon, 23 Nov 2026 14:12:41 +0100 Subject: [PATCH 014/275] ui: smooth height transition for every collapsible (#32873) * ui: give every collapsible the smooth height transition Llama UI's Collapsible.Content now force-mounts the bits-ui content and renders the animated region the chat used to keep as CollapsibleRegion: height eases open and shut, and the body unmounts once the collapse is over. The chat's standalone regions use Collapsible.Root/Content, so the tool groups in settings, the tools menu and drawer and the terminal block animate like the rest. Assisted-by: Claude (Opus 5.5 Medium) * ui: keep collapsible spacing inside the content Collapsible.Content now stays in the layout while closed, so a margin on it left a gap under a closed MCP tools list, connection log or server info. The margin moves onto the content inside, as does the story's spacing. Assisted-by: Claude (Opus 5.5 Medium) --- .../content/CollapsibleContentBlock.svelte | 26 +++---- .../content/CollapsibleTerminalBlock.svelte | 10 +-- .../app/mcp/McpConnectionLogs.svelte | 4 +- .../McpServerCardToolsList.svelte | 4 +- .../components/app/mcp/McpServerInfo.svelte | 4 +- .../app/misc/CollapsibleSection.svelte | 10 ++- .../components/app/misc/GroupedList.svelte | 30 ++++---- .../chat/src/lib/components/app/misc/index.ts | 1 - .../ModelsManagerModelsTable.svelte | 28 +++---- .../SidebarNavigationConversationList.svelte | 73 ++++++++++--------- .../SidebarNavigationGroupSection.svelte | 60 +++++++-------- .../chat/src/lib/constants/ui.constants.ts | 5 +- .../collapsible-lazy-body.svelte.test.ts | 14 ++-- ui/lib/ui/package-lock.json | 4 +- ui/lib/ui/package.json | 2 +- .../ui/collapsible/collapsible-content.svelte | 16 +++- .../ui/collapsible/collapsible-region.svelte} | 26 +++++-- ui/lib/ui/src/lib/constants/ui.constants.ts | 3 + .../display/Collapsible.stories.svelte | 13 ++-- 19 files changed, 181 insertions(+), 152 deletions(-) rename ui/{apps/chat/src/lib/components/app/misc/CollapsibleRegion.svelte => lib/ui/src/lib/components/ui/collapsible/collapsible-region.svelte} (69%) diff --git a/ui/apps/chat/src/lib/components/app/content/CollapsibleContentBlock.svelte b/ui/apps/chat/src/lib/components/app/content/CollapsibleContentBlock.svelte index 89a0b36218ec..797a4f2fecee 100644 --- a/ui/apps/chat/src/lib/components/app/content/CollapsibleContentBlock.svelte +++ b/ui/apps/chat/src/lib/components/app/content/CollapsibleContentBlock.svelte @@ -2,7 +2,6 @@ import * as Collapsible from '@ggml-org/llama-ui/ui/collapsible'; import { cn } from '@ggml-org/llama-ui/utils'; import ChevronDown from '@lucide/svelte/icons/chevron-down'; - import CollapsibleRegion from '#lib/components/app/misc/CollapsibleRegion.svelte'; import { ICON_CLASS_DEFAULT } from '#lib/constants/index.ts'; import type { Snippet } from 'svelte'; import type { Component } from 'svelte'; @@ -157,23 +156,16 @@ {/if} {#if collapsible} - - - -
-
- {@render children()} -
+ + +
+
+ {@render children()}
- +
{/if} diff --git a/ui/apps/chat/src/lib/components/app/content/CollapsibleTerminalBlock.svelte b/ui/apps/chat/src/lib/components/app/content/CollapsibleTerminalBlock.svelte index 798a0ed204f5..ebfcb7c2f9bd 100644 --- a/ui/apps/chat/src/lib/components/app/content/CollapsibleTerminalBlock.svelte +++ b/ui/apps/chat/src/lib/components/app/content/CollapsibleTerminalBlock.svelte @@ -95,13 +95,9 @@ - - {#if open} -
- {@render children()} -
- {/if} +
+ {@render children()} +
diff --git a/ui/apps/chat/src/lib/components/app/mcp/McpConnectionLogs.svelte b/ui/apps/chat/src/lib/components/app/mcp/McpConnectionLogs.svelte index 87efebf7a2e5..cff6fa0dbc3b 100644 --- a/ui/apps/chat/src/lib/components/app/mcp/McpConnectionLogs.svelte +++ b/ui/apps/chat/src/lib/components/app/mcp/McpConnectionLogs.svelte @@ -48,9 +48,9 @@
- +
{#each logs as log (log.timestamp.getTime() + log.message)} {@const IconComponent = getMcpLogLevelIcon(log.level)} diff --git a/ui/apps/chat/src/lib/components/app/mcp/McpServerCard/McpServerCardToolsList.svelte b/ui/apps/chat/src/lib/components/app/mcp/McpServerCard/McpServerCardToolsList.svelte index bc3631ddf28e..48846d3364bb 100644 --- a/ui/apps/chat/src/lib/components/app/mcp/McpServerCard/McpServerCardToolsList.svelte +++ b/ui/apps/chat/src/lib/components/app/mcp/McpServerCard/McpServerCardToolsList.svelte @@ -31,8 +31,8 @@ {toolsCount} tools available · Show details - -
+ +
{#each tools as tool (tool.name)}
{tool.name} diff --git a/ui/apps/chat/src/lib/components/app/mcp/McpServerInfo.svelte b/ui/apps/chat/src/lib/components/app/mcp/McpServerInfo.svelte index 220e6c6d954f..e895d8ce0a7a 100644 --- a/ui/apps/chat/src/lib/components/app/mcp/McpServerInfo.svelte +++ b/ui/apps/chat/src/lib/components/app/mcp/McpServerInfo.svelte @@ -26,8 +26,8 @@ Server instructions - -

+ +

{instructions}

diff --git a/ui/apps/chat/src/lib/components/app/misc/CollapsibleSection.svelte b/ui/apps/chat/src/lib/components/app/misc/CollapsibleSection.svelte index 86d6cc2c2bbc..5963a36f79f3 100644 --- a/ui/apps/chat/src/lib/components/app/misc/CollapsibleSection.svelte +++ b/ui/apps/chat/src/lib/components/app/misc/CollapsibleSection.svelte @@ -1,5 +1,5 @@ - + + + {#snippet child({ open, props })} + + {@render children?.()} + + {/snippet} + diff --git a/ui/apps/chat/src/lib/components/app/misc/CollapsibleRegion.svelte b/ui/lib/ui/src/lib/components/ui/collapsible/collapsible-region.svelte similarity index 69% rename from ui/apps/chat/src/lib/components/app/misc/CollapsibleRegion.svelte rename to ui/lib/ui/src/lib/components/ui/collapsible/collapsible-region.svelte index 40809de45819..9910753395da 100644 --- a/ui/apps/chat/src/lib/components/app/misc/CollapsibleRegion.svelte +++ b/ui/lib/ui/src/lib/components/ui/collapsible/collapsible-region.svelte @@ -1,16 +1,20 @@ -
+
{#if contentMounted}
- {@render children()} + {@render children?.()}
{/if}
@@ -80,4 +84,10 @@ overflow: clip; } } + + @media (prefers-reduced-motion: reduce) { + .collapsible-region { + transition: none; + } + } diff --git a/ui/lib/ui/src/lib/constants/ui.constants.ts b/ui/lib/ui/src/lib/constants/ui.constants.ts index ff1bde2c960f..9f538214100d 100644 --- a/ui/lib/ui/src/lib/constants/ui.constants.ts +++ b/ui/lib/ui/src/lib/constants/ui.constants.ts @@ -7,3 +7,6 @@ export const UI_DATA_ATTRS = { /** How close to the bottom (px) a streaming code block counts as at the bottom. */ export const SYNTAX_CODE_SCROLL_AT_BOTTOM_THRESHOLD_PX = 32; + +/** How long a collapsible's body takes to expand or collapse; matches the region's CSS transition. */ +export const COLLAPSIBLE_TRANSITION_MS = 200; diff --git a/ui/lib/ui/tests/stories/components/display/Collapsible.stories.svelte b/ui/lib/ui/tests/stories/components/display/Collapsible.stories.svelte index 2690a1f80c9a..0291f94140e0 100644 --- a/ui/lib/ui/tests/stories/components/display/Collapsible.stories.svelte +++ b/ui/lib/ui/tests/stories/components/display/Collapsible.stories.svelte @@ -16,7 +16,7 @@ {#snippet section(open: boolean)} - +
Advanced sampling @@ -29,12 +29,15 @@
-
temperature 0.8
+
temperature 0.8
- -
top_p 0.95
+ + +
+
top_p 0.95
-
min_p 0.05
+
min_p 0.05
+
{/snippet} From 46f4da217419ecac95708600e0f6ebc4bdb91cfd Mon Sep 17 00:00:00 2001 From: thelittlefireman <5165783+thelittlefireman@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:17:15 +0100 Subject: [PATCH 015/275] ggml-cuda : handle zero blocks in few-row MMQ quantization (#32566) Assisted-by: ChatGPT (GPT-6) --- ggml/src/ggml-cuda/quantize.cu | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-cuda/quantize.cu b/ggml/src/ggml-cuda/quantize.cu index b37ab3d0afd4..23936c305610 100644 --- a/ggml/src/ggml-cuda/quantize.cu +++ b/ggml/src/ggml-cuda/quantize.cu @@ -607,13 +607,13 @@ static __device__ __forceinline__ void quantize_mmq_few_store(const float4 xi, i float amax = fmaxf(fmaxf(fabsf(xi.x), fabsf(xi.y)), fmaxf(fabsf(xi.z), fabsf(xi.w))); amax = warp_reduce_max<8>(amax); - const float d_inv = 127.0f / amax; + const float d_inv = amax == 0.0f ? 0.0f : 127.0f / amax; char4 q; q.x = roundf(xi.x*d_inv); q.y = roundf(xi.y*d_inv); q.z = roundf(xi.z*d_inv); q.w = roundf(xi.w*d_inv); - const float d = 1.0f / d_inv; + const float d = amax == 0.0f ? 0.0f : 1.0f / d_inv; // as in quantize_mmq_q8_1: the sum of the quantized values; the int warp_reduce_sum reduces the whole warp on Ampere+ [[maybe_unused]] float sum = 0.0f; From 03813c56e47f6cd7a9b9bc2ad8edcebed88ce342 Mon Sep 17 00:00:00 2001 From: Aman Gupta Date: Mon, 23 Nov 2026 22:28:40 +0800 Subject: [PATCH 016/275] rpc : typed request helpers and a single validation step on the server (#32651) * rpc : typed request helpers and a single validation step on the server Client and server share one table (rpc_msg_types) that maps each fixed-size command to its request and response structs. The client sends them with dispatcher->call() and call_async(), the server serves them with rpc_serve(), so the per-command code in rpc_serve_client and at the call sites is gone and a wrong struct for a command does not compile. SET_TENSOR, SET_TENSOR_2D and GRAPH_COMPUTE get header structs, written with rpc_writer and parsed with a bounds-checked rpc_reader. The wire format is unchanged. Validation of client data is now in one place: - deserialize_tensor rejects what ggml_new_tensor would assert on (op range, ne[0] not a multiple of the block size, element count overflow) and computes the tensor size without overflow before the buffer check - rpc_check_region replaces the per-handler bounds checks and checks the request against the tensor size, which ggml_backend_tensor_set/get/memset assert on, so an in-buffer but out-of-tensor request no longer aborts - graph_compute builds the graph in one pass over the tensors, which the client sends in topological order: no recursion, and unknown or duplicate ids, duplicate nodes, sources sent after their users, compute nodes with unallocated operands and views outside their view_src buffer are rejected; a tensor may be its own source (ggml_cast) - GET_ALLOC_SIZE fails if a source tensor is invalid - a client-sized allocation that fails closes the connection instead of terminating the server * rpc : trim comments --- ggml/src/ggml-rpc/ggml-rpc.cpp | 1260 +++++++++++++------------------- 1 file changed, 513 insertions(+), 747 deletions(-) diff --git a/ggml/src/ggml-rpc/ggml-rpc.cpp b/ggml/src/ggml-rpc/ggml-rpc.cpp index dbd7dd467709..6197f01c285e 100644 --- a/ggml/src/ggml-rpc/ggml-rpc.cpp +++ b/ggml/src/ggml-rpc/ggml-rpc.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -245,7 +246,8 @@ struct rpc_msg_graph_recompute_req { uint64_t uid; }; -struct rpc_msg_get_tensor_2d_req { +// GET_TENSOR_2D request and SET_TENSOR_2D header +struct rpc_msg_tensor_2d_req { rpc_tensor tensor; uint64_t offset; uint64_t size; @@ -274,8 +276,49 @@ struct rpc_msg_comm_free_req { uint32_t device; }; +// SET_TENSOR header, followed by the data +struct rpc_msg_set_tensor_req { + rpc_tensor tensor; + uint8_t cache_flag; + uint64_t offset; +}; + +// GRAPH_COMPUTE header, followed by the node ids and the tensors +struct rpc_msg_graph_compute_req { + uint32_t device; + uint64_t uid; + uint32_t n_nodes; +}; + #pragma pack(pop) +// request and response types of the commands with fixed-size requests, void when there is no response +template struct rpc_msg_types; + +#define RPC_MSG_TYPES(cmd, req_t, rsp_t) \ + template <> struct rpc_msg_types { using req = req_t; using rsp = rsp_t; } + +RPC_MSG_TYPES(RPC_CMD_ALLOC_BUFFER, rpc_msg_alloc_buffer_req, rpc_msg_alloc_buffer_rsp); +RPC_MSG_TYPES(RPC_CMD_GET_ALIGNMENT, rpc_msg_get_alignment_req, rpc_msg_get_alignment_rsp); +RPC_MSG_TYPES(RPC_CMD_GET_MAX_SIZE, rpc_msg_get_max_size_req, rpc_msg_get_max_size_rsp); +RPC_MSG_TYPES(RPC_CMD_GET_ALLOC_SIZE, rpc_msg_get_alloc_size_req, rpc_msg_get_alloc_size_rsp); +RPC_MSG_TYPES(RPC_CMD_GET_DEVICE_MEMORY, rpc_msg_get_device_memory_req, rpc_msg_get_device_memory_rsp); +RPC_MSG_TYPES(RPC_CMD_BUFFER_GET_BASE, rpc_msg_buffer_get_base_req, rpc_msg_buffer_get_base_rsp); +RPC_MSG_TYPES(RPC_CMD_FREE_BUFFER, rpc_msg_free_buffer_req, void); +RPC_MSG_TYPES(RPC_CMD_BUFFER_CLEAR, rpc_msg_buffer_clear_req, void); +RPC_MSG_TYPES(RPC_CMD_INIT_TENSOR, rpc_msg_init_tensor_req, void); +RPC_MSG_TYPES(RPC_CMD_MEMSET_TENSOR, rpc_msg_memset_tensor_req, void); +RPC_MSG_TYPES(RPC_CMD_SET_TENSOR_HASH, rpc_msg_set_tensor_hash_req, rpc_msg_set_tensor_hash_rsp); +RPC_MSG_TYPES(RPC_CMD_GET_TENSOR, rpc_msg_get_tensor_req, std::vector); +RPC_MSG_TYPES(RPC_CMD_GET_TENSOR_2D, rpc_msg_tensor_2d_req, std::vector); +RPC_MSG_TYPES(RPC_CMD_COPY_TENSOR, rpc_msg_copy_tensor_req, rpc_msg_copy_tensor_rsp); +RPC_MSG_TYPES(RPC_CMD_GRAPH_RECOMPUTE, rpc_msg_graph_recompute_req, void); +RPC_MSG_TYPES(RPC_CMD_COMM_INIT, rpc_msg_comm_init_req, rpc_msg_comm_init_rsp); +RPC_MSG_TYPES(RPC_CMD_COMM_ALLREDUCE, rpc_msg_comm_allreduce_req, void); +RPC_MSG_TYPES(RPC_CMD_COMM_FREE, rpc_msg_comm_free_req, void); + +#undef RPC_MSG_TYPES + // RPC data structures static ggml_guid_t ggml_backend_rpc_guid() { @@ -325,6 +368,59 @@ static uint64_t fnv_hash(const uint8_t * data, size_t len, uint64_t hash = 0xcbf return hash; } +// builds a variable-size request; the buffer must not change once queued +struct rpc_writer { + std::shared_ptr> buf = std::make_shared>(); + + explicit rpc_writer(size_t capacity) { buf->reserve(capacity); } + + void write_bytes(const void * data, size_t size) { + const uint8_t * p = (const uint8_t *) data; + buf->insert(buf->end(), p, p + size); + } + + template + void write(const T & value) { + static_assert(std::is_trivially_copyable_v); + write_bytes(&value, sizeof(value)); + } + + std::shared_ptr data() const { return std::shared_ptr(buf, buf->data()); } + size_t size() const { return buf->size(); } +}; + +// bounds-checked cursor over a received request +struct rpc_reader { + const uint8_t * ptr; + size_t left; + + explicit rpc_reader(const std::vector & input) : ptr(input.data()), left(input.size()) {} + + // n elements of elem_size bytes, returned in place: the pointer has no alignment guarantee + bool read_bytes(const uint8_t *& out, size_t n, size_t elem_size = 1) { + if (elem_size != 0 && n > left / elem_size) { + return false; + } + out = ptr; + ptr += n*elem_size; + left -= n*elem_size; + return true; + } + + template + bool read(T & value) { + static_assert(std::is_trivially_copyable_v); + const uint8_t * p; + if (!read_bytes(p, sizeof(T))) { + return false; + } + memcpy(&value, p, sizeof(T)); + return true; + } + + bool empty() const { return left == 0; } +}; + static bool send_msg(socket_ptr sock, const void * msg, size_t msg_size) { if (!sock->send_data(&msg_size, sizeof(msg_size))) { return false; @@ -520,6 +616,36 @@ class rpc_dispatcher { void send(enum rpc_cmd cmd, std::shared_ptr input, size_t input_size, const void * payload, size_t payload_size, void * output, size_t output_size); void send_async(enum rpc_cmd cmd, std::shared_ptr input, size_t input_size, void * output = nullptr, size_t output_size = 0); + // sends the request of `cmd` and waits for the response, if the command has one + template + typename rpc_msg_types::rsp call(const typename rpc_msg_types::req & request) { + using req_t = typename rpc_msg_types::req; + using rsp_t = typename rpc_msg_types::rsp; + auto input = std::make_shared(request); + if constexpr (std::is_void_v) { + send(cmd, input, sizeof(req_t), nullptr, 0, nullptr, 0); + } else { + static_assert(std::is_trivially_copyable_v, "variable-size responses are read into caller memory with send()"); + rsp_t response = {}; + send(cmd, input, sizeof(req_t), nullptr, 0, &response, sizeof(response)); + return response; + } + } + + // queues the request of `cmd`; *response, if given, is written when the command completes + template + void call_async(const typename rpc_msg_types::req & request, typename rpc_msg_types::rsp * response = nullptr) { + using req_t = typename rpc_msg_types::req; + using rsp_t = typename rpc_msg_types::rsp; + auto input = std::make_shared(request); + if constexpr (std::is_void_v) { + send_async(cmd, input, sizeof(req_t)); + } else { + static_assert(std::is_trivially_copyable_v, "variable-size responses are read into caller memory with send_async()"); + send_async(cmd, input, sizeof(req_t), response, sizeof(rsp_t)); + } + } + ggml_backend_event_t event_new(ggml_backend_dev_t dev); void event_free(ggml_backend_event_t event); void event_synchronize(ggml_backend_event_t event); @@ -741,10 +867,8 @@ static std::shared_ptr get_dispatcher(const std::string & endpoi static void ggml_backend_rpc_buffer_free_buffer(ggml_backend_buffer_t buffer) { ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context; - auto request = std::make_shared(); - request->remote_ptr = ctx->remote_ptr; - LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 "\n", __func__, request->remote_ptr); - ctx->dispatcher->send(RPC_CMD_FREE_BUFFER, request, sizeof(*request), nullptr, 0, nullptr, 0); + LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 "\n", __func__, ctx->remote_ptr); + ctx->dispatcher->call({ ctx->remote_ptr }); delete ctx; } @@ -753,11 +877,8 @@ static void * ggml_backend_rpc_buffer_get_base(ggml_backend_buffer_t buffer) { if (ctx->base_ptr != nullptr) { return ctx->base_ptr; } - auto request = std::make_shared(); - request->remote_ptr = ctx->remote_ptr; LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 "\n", __func__, ctx->remote_ptr); - rpc_msg_buffer_get_base_rsp response; - ctx->dispatcher->send(RPC_CMD_BUFFER_GET_BASE, request, sizeof(*request), nullptr, 0, &response, sizeof(response)); + const auto response = ctx->dispatcher->call({ ctx->remote_ptr }); ctx->base_ptr = reinterpret_cast(response.base_ptr); return ctx->base_ptr; } @@ -821,9 +942,7 @@ static enum ggml_status ggml_backend_rpc_buffer_init_tensor(ggml_backend_buffer_ // In particular, only quantized tensors need padding if (ggml_is_quantized(tensor->type) && (tensor->ne[0] % 512 != 0) && (tensor->view_src == nullptr)) { LOG_DBG2("[%s] tensor: %s\n", __func__, rpc_log_format_tensor(tensor).c_str()); - auto request = std::make_shared(); - request->tensor = serialize_tensor(tensor); - ctx->dispatcher->send(RPC_CMD_INIT_TENSOR, request, sizeof(*request), nullptr, 0, nullptr, 0); + ctx->dispatcher->call({ serialize_tensor(tensor) }); } return GGML_STATUS_SUCCESS; } @@ -831,29 +950,9 @@ static enum ggml_status ggml_backend_rpc_buffer_init_tensor(ggml_backend_buffer_ static void ggml_backend_rpc_buffer_memset_tensor( ggml_backend_buffer_t buffer, ggml_tensor * tensor, uint8_t value, size_t offset, size_t size) { ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context; - auto request = std::make_shared(); - request->tensor = serialize_tensor(tensor); - request->offset = offset; - request->size = size; - request->value = value; LOG_DBG2("[%s] tensor: %s, offset: %zu, size: %s, value: %u\n", __func__, rpc_log_format_tensor(tensor).c_str(), offset, rpc_log_format_size(size).c_str(), value); - ctx->dispatcher->send(RPC_CMD_MEMSET_TENSOR, request, sizeof(*request), nullptr, 0, nullptr, 0); -} - -// input serialization format: | rpc_tensor | cache_flag (1 byte) | offset (8 bytes) | data (size bytes) -// with size == 0 only the header is serialized and data is sent separately as payload -static std::shared_ptr serialize_set_tensor(const rpc_tensor & rpc_tensor, uint8_t cache_flag, uint64_t offset, const void * data, size_t size, size_t & input_size) { - input_size = sizeof(rpc_tensor) + sizeof(cache_flag) + sizeof(offset) + size; - uint8_t * input = new uint8_t[input_size]; - uint8_t * p = input; - memcpy(p, &rpc_tensor, sizeof(rpc_tensor)); p += sizeof(rpc_tensor); - memcpy(p, &cache_flag, sizeof(cache_flag)); p += sizeof(cache_flag); - memcpy(p, &offset, sizeof(offset)); p += sizeof(offset); - if (size > 0) { - memcpy(p, data, size); - } - return std::shared_ptr(input, std::default_delete()); + ctx->dispatcher->call({ serialize_tensor(tensor), offset, size, value }); } // the hash cache is meant for weights, so that a model reload can skip re-sending them. @@ -865,53 +964,48 @@ static bool rpc_use_hash_cache(const rpc_dispatcher & dispatcher, const ggml_ten return dispatcher.get_send_tensor_hash() && size > HASH_THRESHOLD && tensor->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS; } +// true if the server loaded the data from its cache; on a miss, cache_flag asks it to cache the data sent next +static bool rpc_set_tensor_from_cache(rpc_dispatcher & dispatcher, const ggml_tensor * tensor, const rpc_tensor & wire, + const void * data, size_t offset, size_t size, uint8_t & cache_flag) { + cache_flag = 0; + if (!rpc_use_hash_cache(dispatcher, tensor, size)) { + return false; + } + // TODO: make this async + const rpc_msg_set_tensor_hash_req request = { wire, offset, fnv_hash((const uint8_t *) data, size) }; + const auto response = dispatcher.call(request); + LOG_DBG2("[%s] tensor: %s, hash: 0x%" PRIx64 ", cache: %s\n", __func__, rpc_log_format_tensor(tensor).c_str(), + request.hash, response.result ? "hit" : "miss"); + cache_flag = response.result ? 0 : 1; + return response.result != 0; +} + static void ggml_backend_rpc_buffer_set_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data, size_t offset, size_t size) { ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context; - rpc_tensor rpc_tensor = serialize_tensor(tensor); - uint8_t cache_flag = 0; + const rpc_tensor wire = serialize_tensor(tensor); LOG_DBG2("[%s] tensor: %s, offset: %zu, size: %s\n", __func__, rpc_log_format_tensor(tensor).c_str(), offset, rpc_log_format_size(size).c_str()); - if (rpc_use_hash_cache(*ctx->dispatcher, tensor, size)) { - auto request = std::make_shared(); - request->tensor = rpc_tensor; - request->offset = offset; - request->hash = fnv_hash((const uint8_t*)data, size); - rpc_msg_set_tensor_hash_rsp response; - ctx->dispatcher->send(RPC_CMD_SET_TENSOR_HASH, request, sizeof(*request), nullptr, 0, &response, sizeof(response)); - LOG_DBG2("[%s] tensor: %s, hash: 0x%" PRIx64 ", cache: %s\n", __func__, rpc_log_format_tensor(tensor).c_str(), - request->hash, response.result ? "hit" : "miss"); - if (response.result) { - // the server has the same data, no need to send it - return; - } - // the server has no cache entry for this tensor - ask it to save one - cache_flag = 1; + uint8_t cache_flag; + if (rpc_set_tensor_from_cache(*ctx->dispatcher, tensor, wire, data, offset, size, cache_flag)) { + return; } - size_t header_size; - auto header = serialize_set_tensor(rpc_tensor, cache_flag, offset, nullptr, 0, header_size); - ctx->dispatcher->send(RPC_CMD_SET_TENSOR, header, header_size, data, size, nullptr, 0); + // | rpc_msg_set_tensor_req | data (size bytes) | + auto request = std::make_shared(rpc_msg_set_tensor_req{ wire, cache_flag, offset }); + ctx->dispatcher->send(RPC_CMD_SET_TENSOR, request, sizeof(*request), data, size, nullptr, 0); } static void ggml_backend_rpc_buffer_set_tensor_2d(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data, size_t offset, size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data) { ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context; - rpc_tensor rpc_tensor = serialize_tensor(tensor); LOG_DBG2("[%s] tensor: %s, offset: %zu, size: %s, n_copies: %zu, stride: %zu\n", __func__, rpc_log_format_tensor(tensor).c_str(), offset, rpc_log_format_size(size).c_str(), n_copies, stride_tensor); - // input serialization format: | rpc_tensor | offset (8 bytes) | size (8 bytes) | n_copies (8 bytes) | stride (8 bytes) | data (size * n_copies bytes) | - size_t input_size = sizeof(rpc_tensor) + 4*sizeof(uint64_t) + size*n_copies; - uint8_t * input = new uint8_t[input_size](); - uint8_t * dest = input; - memcpy(dest, &rpc_tensor, sizeof(rpc_tensor)); - dest += sizeof(rpc_tensor); - uint64_t header[4] = { offset, size, n_copies, stride_tensor }; - memcpy(dest, header, sizeof(header)); - dest += sizeof(header); + // | rpc_msg_tensor_2d_req | data (size * n_copies bytes) | + rpc_writer writer(sizeof(rpc_msg_tensor_2d_req) + size*n_copies); + writer.write(rpc_msg_tensor_2d_req{ serialize_tensor(tensor), offset, size, n_copies, stride_tensor }); for (size_t i = 0; i < n_copies; i++) { - memcpy(dest + i*size, (const char *)data + i*stride_data, size); + writer.write_bytes((const char *) data + i*stride_data, size); } - std::shared_ptr input_ptr(input, std::default_delete()); - ctx->dispatcher->send(RPC_CMD_SET_TENSOR_2D, input_ptr, input_size, nullptr, 0, nullptr, 0); + ctx->dispatcher->send(RPC_CMD_SET_TENSOR_2D, writer.data(), writer.size(), nullptr, 0, nullptr, 0); } static void ggml_backend_rpc_buffer_get_tensor_2d(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data, @@ -919,7 +1013,7 @@ static void ggml_backend_rpc_buffer_get_tensor_2d(ggml_backend_buffer_t buffer, ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context; LOG_DBG2("[%s] tensor: %s, offset: %zu, size: %s, n_copies: %zu, stride: %zu\n", __func__, rpc_log_format_tensor(tensor).c_str(), offset, rpc_log_format_size(size).c_str(), n_copies, stride_tensor); - auto request = std::make_shared(); + auto request = std::make_shared(); request->tensor = serialize_tensor(tensor); request->offset = offset; request->size = size; @@ -960,23 +1054,15 @@ static bool ggml_backend_rpc_buffer_cpy_tensor(ggml_backend_buffer_t buffer, con } ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context; LOG_DBG2("[%s] src: %s -> dst: %s\n", __func__, rpc_log_format_tensor(src).c_str(), rpc_log_format_tensor(dst).c_str()); - auto request = std::make_shared(); - request->src = serialize_tensor(src); - request->dst = serialize_tensor(dst); - rpc_msg_copy_tensor_rsp response; - ctx->dispatcher->send(RPC_CMD_COPY_TENSOR, request, sizeof(*request), nullptr, 0, &response, sizeof(response)); - return response.result; + return ctx->dispatcher->call({ serialize_tensor(src), serialize_tensor(dst) }).result; } return false; } static void ggml_backend_rpc_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) { ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context; - auto request = std::make_shared(); - request->remote_ptr = ctx->remote_ptr; - request->value = value; - LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 ", value: %u\n", __func__, request->remote_ptr, request->value); - ctx->dispatcher->send(RPC_CMD_BUFFER_CLEAR, request, sizeof(*request), nullptr, 0, nullptr, 0); + LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 ", value: %u\n", __func__, ctx->remote_ptr, value); + ctx->dispatcher->call({ ctx->remote_ptr, value }); } static ggml_backend_buffer_i ggml_backend_rpc_buffer_interface = { @@ -1003,19 +1089,14 @@ static const char * ggml_backend_rpc_buffer_type_name(ggml_backend_buffer_type_t static ggml_backend_buffer_t ggml_backend_rpc_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) { ggml_backend_rpc_buffer_type_context * buft_ctx = (ggml_backend_rpc_buffer_type_context *)buft->context; - auto request = std::make_shared(); - request->device = buft_ctx->device; - request->size = size; - rpc_msg_alloc_buffer_rsp response; - auto dispatcher = get_dispatcher(buft_ctx->endpoint); if (dispatcher == nullptr) { return nullptr; } - dispatcher->send(RPC_CMD_ALLOC_BUFFER, request, sizeof(*request), nullptr, 0, &response, sizeof(response)); + const auto response = dispatcher->call({ buft_ctx->device, size }); if (response.remote_ptr != 0) { LOG_DBG("[%s] endpoint: %s, device: %u, size: %s -> remote_ptr: 0x%" PRIx64 ", remote_size: %s\n", - __func__, buft_ctx->endpoint.c_str(), buft_ctx->device, rpc_log_format_size(request->size).c_str(), + __func__, buft_ctx->endpoint.c_str(), buft_ctx->device, rpc_log_format_size(size).c_str(), response.remote_ptr, rpc_log_format_size(response.remote_size).c_str()); ggml_backend_buffer_t buffer = ggml_backend_buffer_init(buft, ggml_backend_rpc_buffer_interface, @@ -1024,16 +1105,13 @@ static ggml_backend_buffer_t ggml_backend_rpc_buffer_type_alloc_buffer(ggml_back return buffer; } else { LOG_WARN("[%s] endpoint: %s, device: %u, size: %s -> failed\n", - __func__, buft_ctx->endpoint.c_str(), buft_ctx->device, rpc_log_format_size(request->size).c_str()); + __func__, buft_ctx->endpoint.c_str(), buft_ctx->device, rpc_log_format_size(size).c_str()); return nullptr; } } static size_t get_alignment(const std::shared_ptr & dispatcher, uint32_t device) { - auto request = std::make_shared(); - request->device = device; - rpc_msg_get_alignment_rsp response; - dispatcher->send(RPC_CMD_GET_ALIGNMENT, request, sizeof(*request), nullptr, 0, &response, sizeof(response)); + const auto response = dispatcher->call({ device }); LOG_DBG2("[%s] device: %u, alignment: %s\n", __func__, device, rpc_log_format_size(response.alignment).c_str()); return response.alignment; } @@ -1044,10 +1122,7 @@ static size_t ggml_backend_rpc_buffer_type_get_alignment(ggml_backend_buffer_typ } static size_t get_max_size(const std::shared_ptr & dispatcher, uint32_t device) { - auto request = std::make_shared(); - request->device = device; - rpc_msg_get_max_size_rsp response; - dispatcher->send(RPC_CMD_GET_MAX_SIZE, request, sizeof(*request), nullptr, 0, &response, sizeof(response)); + const auto response = dispatcher->call({ device }); LOG_DBG2("[%s] device: %u, max_size: %s\n", __func__, device, rpc_log_format_size(response.max_size).c_str()); return response.max_size; } @@ -1120,22 +1195,21 @@ static size_t ggml_backend_rpc_buffer_type_get_alloc_size(ggml_backend_buffer_ty } } - auto request = std::make_shared(); - request->device = buft_ctx->device; - request->tensor = serialize_tensor(tensor); + rpc_msg_get_alloc_size_req request = {}; + request.device = buft_ctx->device; + request.tensor = serialize_tensor(tensor); // .get_alloc_size could be a function of the tensor's srcs, so we must serialize them as well for (int i = 0; i < GGML_MAX_SRC; i++) { - request->srcs[i] = serialize_tensor(tensor->src[i]); + request.srcs[i] = serialize_tensor(tensor->src[i]); } LOG_DBG2("[%s] cache miss: %s, querying server\n", __func__, rpc_log_format_tensor(tensor).c_str()); - rpc_msg_get_alloc_size_rsp response; auto dispatcher = get_dispatcher(buft_ctx->endpoint); if (dispatcher == nullptr) { return min_size; } - dispatcher->send(RPC_CMD_GET_ALLOC_SIZE, request, sizeof(*request), nullptr, 0, &response, sizeof(response)); + const auto response = dispatcher->call(request); { std::lock_guard lock(cache_mutex); @@ -1176,30 +1250,18 @@ static void ggml_backend_rpc_free(ggml_backend_t backend) { static void ggml_backend_rpc_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) { ggml_backend_rpc_context * ctx = (ggml_backend_rpc_context *)backend->context; - rpc_tensor rpc_tensor = serialize_tensor(tensor); - uint8_t cache_flag = 0; + const rpc_tensor wire = serialize_tensor(tensor); LOG_DBG2("[%s] tensor: %s, offset: %zu, size: %s\n", __func__, rpc_log_format_tensor(tensor).c_str(), offset, rpc_log_format_size(size).c_str()); - if (rpc_use_hash_cache(*ctx->dispatcher, tensor, size)) { - auto request = std::make_shared(); - request->tensor = rpc_tensor; - request->offset = offset; - request->hash = fnv_hash((const uint8_t*)data, size); - rpc_msg_set_tensor_hash_rsp response; - // TODO: make this async - ctx->dispatcher->send(RPC_CMD_SET_TENSOR_HASH, request, sizeof(*request), nullptr, 0, &response, sizeof(response)); - LOG_DBG2("[%s] tensor: %s, hash: 0x%" PRIx64 ", cache: %s\n", __func__, rpc_log_format_tensor(tensor).c_str(), - request->hash, response.result ? "hit" : "miss"); - if (response.result) { - // the server has the same data, no need to send it - return; - } - // the server has no cache entry for this tensor - ask it to save one - cache_flag = 1; + uint8_t cache_flag; + if (rpc_set_tensor_from_cache(*ctx->dispatcher, tensor, wire, data, offset, size, cache_flag)) { + return; } - size_t input_size; - auto input = serialize_set_tensor(rpc_tensor, cache_flag, offset, data, size, input_size); - ctx->dispatcher->send_async(RPC_CMD_SET_TENSOR, input, input_size); + // the caller may reuse data once this returns, so it is copied into the request + rpc_writer writer(sizeof(rpc_msg_set_tensor_req) + size); + writer.write(rpc_msg_set_tensor_req{ wire, cache_flag, offset }); + writer.write_bytes(data, size); + ctx->dispatcher->send_async(RPC_CMD_SET_TENSOR, writer.data(), writer.size()); } static void ggml_backend_rpc_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) { @@ -1218,6 +1280,7 @@ static void ggml_backend_rpc_synchronize(ggml_backend_t backend) { rpc_ctx->dispatcher->synchronize(); } +// adds the tensor after its sources and view_src, so that the server can build the graph in one pass static void add_tensor(ggml_tensor * tensor, const ggml_cgraph * cgraph, const rpc_dispatcher * dispatcher, std::vector & tensors, std::unordered_set & visited) { if (tensor == nullptr) { return; @@ -1238,34 +1301,23 @@ static void add_tensor(ggml_tensor * tensor, const ggml_cgraph * cgraph, const r tensors.push_back(result); } -static uint8_t * serialize_graph(uint32_t device, const ggml_cgraph * cgraph, const rpc_dispatcher * dispatcher, size_t * output_size) { - uint32_t n_nodes = cgraph->n_nodes; +// | rpc_msg_graph_compute_req | nodes (n_nodes * uint64_t) | n_tensors (uint32_t) | tensors (n_tensors * rpc_tensor) | +static rpc_writer serialize_graph(uint32_t device, const ggml_cgraph * cgraph, const rpc_dispatcher * dispatcher) { + const uint32_t n_nodes = cgraph->n_nodes; std::vector tensors; std::unordered_set visited; for (uint32_t i = 0; i < n_nodes; i++) { add_tensor(cgraph->nodes[i], cgraph, dispatcher, tensors, visited); } - // serialization format: - // | device (4 bytes) | uid (8 bytes) | n_nodes (4 bytes) | nodes (n_nodes * sizeof(uint64_t) | n_tensors (4 bytes) | tensors (n_tensors * sizeof(rpc_tensor)) | - uint32_t n_tensors = tensors.size(); - *output_size = 2*sizeof(uint32_t) + sizeof(uint64_t) + n_nodes * sizeof(uint64_t) + sizeof(uint32_t) + n_tensors * sizeof(rpc_tensor); - uint8_t * output = new uint8_t[*output_size](); - uint8_t * dest = output; - memcpy(dest, &device, sizeof(device)); - dest += sizeof(device); - memcpy(dest, &cgraph->uid, sizeof(cgraph->uid)); - dest += sizeof(cgraph->uid); - memcpy(dest, &n_nodes, sizeof(n_nodes)); - dest += sizeof(n_nodes); + const uint32_t n_tensors = tensors.size(); + rpc_writer writer(sizeof(rpc_msg_graph_compute_req) + n_nodes*sizeof(uint64_t) + sizeof(n_tensors) + n_tensors*sizeof(rpc_tensor)); + writer.write(rpc_msg_graph_compute_req{ device, cgraph->uid, n_nodes }); for (uint32_t i = 0; i < n_nodes; i++) { - memcpy(dest + i * sizeof(uint64_t), &cgraph->nodes[i], sizeof(uint64_t)); + writer.write(reinterpret_cast(cgraph->nodes[i])); } - dest += n_nodes * sizeof(uint64_t); - memcpy(dest, &n_tensors, sizeof(n_tensors)); - dest += sizeof(n_tensors); - rpc_tensor * out_tensors = (rpc_tensor *)dest; - memcpy(out_tensors, tensors.data(), n_tensors * sizeof(rpc_tensor)); - return output; + writer.write(n_tensors); + writer.write_bytes(tensors.data(), n_tensors*sizeof(rpc_tensor)); + return writer; } void rpc_dispatcher::graph_compute(uint32_t device, const ggml_cgraph * cgraph) { @@ -1275,10 +1327,7 @@ void rpc_dispatcher::graph_compute(uint32_t device, const ggml_cgraph * cgraph) bool reuse = cgraph->uid != 0 && device_graph_uids.count(cgraph->uid) > 0; LOG_DBG("[%s] device: %u, uid: %" PRIu64 ", n_nodes: %u, reuse: %s\n", __func__, device, cgraph->uid, cgraph->n_nodes, reuse ? "yes" : "no"); if (reuse) { - auto request = std::make_shared(); - request->device = device; - request->uid = cgraph->uid; - send_async(RPC_CMD_GRAPH_RECOMPUTE, request, sizeof(*request)); + call_async({ device, cgraph->uid }); } else { if (cgraph->uid != 0) { if (device_graph_uids.size() >= GRAPH_CACHE_MAX) { @@ -1288,11 +1337,9 @@ void rpc_dispatcher::graph_compute(uint32_t device, const ggml_cgraph * cgraph) } device_graph_uids.insert(cgraph->uid); } - size_t input_size = 0; - uint8_t * input = serialize_graph(device, cgraph, this, &input_size); - LOG_DBG2("[%s] serialized graph: %s\n", __func__, rpc_log_format_size(input_size).c_str()); - std::shared_ptr input_ptr(input, std::default_delete()); - send_async(RPC_CMD_GRAPH_COMPUTE, input_ptr, input_size); + rpc_writer writer = serialize_graph(device, cgraph, this); + LOG_DBG2("[%s] serialized graph: %s\n", __func__, rpc_log_format_size(writer.size()).c_str()); + send_async(RPC_CMD_GRAPH_COMPUTE, writer.data(), writer.size()); } } @@ -1413,10 +1460,7 @@ void ggml_backend_rpc_get_device_memory(const char * endpoint, uint32_t device, *total = 0; return; } - auto request = std::make_shared(); - request->device = device; - rpc_msg_get_device_memory_rsp response; - dispatcher->send(RPC_CMD_GET_DEVICE_MEMORY, request, sizeof(*request), nullptr, 0, &response, sizeof(response)); + const auto response = dispatcher->call({ device }); LOG_DBG2("[%s] device: %u, free: %s, total: %s\n", __func__, device, rpc_log_format_size(response.free_mem).c_str(), rpc_log_format_size(response.total_mem).c_str()); *free = response.free_mem; @@ -1425,6 +1469,92 @@ void ggml_backend_rpc_get_device_memory(const char * endpoint, uint32_t device, // RPC server-side implementation +// ggml_nbytes on the wire values, false if it overflows +static bool rpc_tensor_nbytes(const rpc_tensor & tensor, uint64_t & nbytes) { + nbytes = 0; + for (int i = 0; i < GGML_MAX_DIMS; i++) { + if (tensor.ne[i] == 0) { + return true; + } + } + // ne and nb are 32-bit on the wire, so every product fits in 64 bits and only the sums can overflow + const ggml_type type = (ggml_type) tensor.type; + const uint64_t blck_size = ggml_blck_size(type); + uint64_t n = blck_size == 1 ? ggml_type_size(type) + (uint64_t) (tensor.ne[0] - 1)*tensor.nb[0] + : (uint64_t) tensor.ne[0]*tensor.nb[0]/blck_size; + for (int i = 1; i < GGML_MAX_DIMS; i++) { + const uint64_t term = (uint64_t) (tensor.ne[i] - 1)*tensor.nb[i]; + if (term > UINT64_MAX - n) { + return false; + } + n += term; + } + if (n != (size_t) n) { + return false; + } + nbytes = n; + return true; +} + +static bool rpc_in_buffer(ggml_backend_buffer_t buffer, uint64_t addr, uint64_t size) { + const uint64_t base = (uint64_t) ggml_backend_buffer_get_base(buffer); + const uint64_t buf_size = (uint64_t) ggml_backend_buffer_get_size(buffer); + return addr >= base && addr - base <= buf_size && size <= buf_size - (addr - base); +} + +// checks [offset, offset + (n_copies - 1)*stride + size) against the tensor size, which ggml_backend_tensor_set/get assert on +static bool rpc_check_region(const char * func, const ggml_tensor * tensor, uint64_t offset, uint64_t size, + uint64_t n_copies = 1, uint64_t stride = 0) { + if (tensor == nullptr || tensor->buffer == nullptr || tensor->data == nullptr) { + LOG_ERROR("[%s] invalid or unallocated tensor\n", func); + return false; + } + // rows must not overlap, so size * n_copies <= span + if (n_copies == 0 || (n_copies > 1 && stride < size) || + (n_copies > 1 && stride != 0 && n_copies - 1 > (UINT64_MAX - size) / stride)) { + LOG_ERROR("[%s] invalid region: size=%" PRIu64 ", n_copies=%" PRIu64 ", stride=%" PRIu64 "\n", func, size, n_copies, stride); + return false; + } + const uint64_t span = (n_copies - 1)*stride + size; + const uint64_t nbytes = ggml_nbytes(tensor); + if (offset > nbytes || span > nbytes - offset) { + LOG_ERROR("[%s] region (offset=%" PRIu64 ", span=%" PRIu64 ") out of tensor '%s' bounds (%" PRIu64 ")\n", + func, offset, span, tensor->name, nbytes); + return false; + } + return true; +} + +// some backends address a view through view_src->data + view_offs, so that range must lie inside view_src's buffer +static bool rpc_check_view(const ggml_tensor * tensor) { + const ggml_tensor * view_src = tensor->view_src; + if (view_src == nullptr || tensor->buffer == nullptr || ggml_nbytes(tensor) == 0) { + return true; + } + if (view_src->buffer == nullptr) { + return false; + } + const uint64_t addr = (uint64_t) view_src->data; + return tensor->view_offs <= UINT64_MAX - addr && rpc_in_buffer(view_src->buffer, addr + tensor->view_offs, ggml_nbytes(tensor)); +} + +// a computed node and its sources must be allocated on this server +static bool rpc_check_node(const ggml_tensor * node) { + if (ggml_op_is_empty(node->op)) { + return true; + } + if (ggml_nelements(node) > 0 && node->buffer == nullptr) { + return false; + } + for (int i = 0; i < GGML_MAX_SRC; i++) { + const ggml_tensor * src = node->src[i]; + if (src != nullptr && ggml_nelements(src) > 0 && src->buffer == nullptr) { + return false; + } + } + return true; +} + class rpc_server { public: rpc_server(std::vector all_backends, const char * cache_dir) @@ -1446,7 +1576,7 @@ class rpc_server { bool set_tensor_2d(const std::vector & input); bool set_tensor_hash(const rpc_msg_set_tensor_hash_req & request, rpc_msg_set_tensor_hash_rsp & response); bool get_tensor(const rpc_msg_get_tensor_req & request, std::vector & response); - bool get_tensor_2d(const rpc_msg_get_tensor_2d_req & request, std::vector & response); + bool get_tensor_2d(const rpc_msg_tensor_2d_req & request, std::vector & response); bool copy_tensor(const rpc_msg_copy_tensor_req & request, rpc_msg_copy_tensor_rsp & response); bool graph_compute(const std::vector & input); bool graph_recompute(const rpc_msg_graph_recompute_req & request); @@ -1469,10 +1599,6 @@ class rpc_server { static bool comm_bootstrap_exchange(void * user_data, const void * send_buf, void * recv_buf, size_t size); bool get_cached_file(uint64_t hash, std::vector & data); ggml_tensor * deserialize_tensor(struct ggml_context * ctx, const rpc_tensor * tensor); - ggml_tensor * create_node(uint64_t id, - struct ggml_context * ctx, - const std::unordered_map & tensor_ptrs, - std::unordered_map & tensor_map); // Per-device state for one communicator. @@ -1539,6 +1665,9 @@ bool rpc_server::get_alloc_size(const rpc_msg_get_alloc_size_req & request, rpc_ for (int i = 0; i < GGML_MAX_SRC; i++) { if (request.srcs[i].id != 0) { tensor->src[i] = deserialize_tensor(ctx, &request.srcs[i]); + if (tensor->src[i] == nullptr) { + return false; + } } } @@ -1658,29 +1787,7 @@ bool rpc_server::memset_tensor(const rpc_msg_memset_tensor_req & request) { GGML_ASSERT(ctx_ptr != nullptr); ggml_context * ctx = ctx_ptr.get(); ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); - if (tensor == nullptr || tensor->buffer == nullptr) { - LOG_ERROR("[%s] error deserializing tensor\n", __func__); - return false; - } - - const uint64_t tensor_size = ggml_nbytes(tensor); - if (request.offset > tensor_size || request.size > tensor_size - request.offset) { - LOG_ERROR("[%s] tensor region (offset=%" PRIu64 ", size=%" PRIu64 ") out of tensor bounds [0, %" PRIu64 ")\n", - __func__, request.offset, request.size, tensor_size); - return false; - } - - const uint64_t buffer_start = (uint64_t) ggml_backend_buffer_get_base(tensor->buffer); - const uint64_t buffer_size = ggml_backend_buffer_get_size(tensor->buffer); - if (request.tensor.data < buffer_start) { - LOG_ERROR("[%s] tensor data before buffer start\n", __func__); - return false; - } - const uint64_t data_offset = request.tensor.data - buffer_start; - if (data_offset > buffer_size || - request.offset > buffer_size - data_offset || - request.size > buffer_size - data_offset - request.offset) { - LOG_ERROR("[%s] tensor region out of buffer bounds\n", __func__); + if (!rpc_check_region(__func__, tensor, request.offset, request.size)) { return false; } @@ -1691,52 +1798,54 @@ bool rpc_server::memset_tensor(const rpc_msg_memset_tensor_req & request) { return true; } +// rejects the values that ggml_new_tensor or the backends would assert on ggml_tensor * rpc_server::deserialize_tensor(struct ggml_context * ctx, const rpc_tensor * tensor) { - // Validate tensor type before using it - if (tensor->type >= GGML_TYPE_COUNT) { - LOG_ERROR("[%s] invalid tensor type received: %u\n", __func__, tensor->type); + if (tensor->type >= GGML_TYPE_COUNT || ggml_blck_size((ggml_type) tensor->type) == 0) { + LOG_ERROR("[%s] invalid tensor type: %u\n", __func__, tensor->type); return nullptr; } - - // Fix: Prevent division by zero if blck_size is 0 (e.g., deprecated types) - if (ggml_blck_size((enum ggml_type)tensor->type) == 0) { - LOG_ERROR("[%s] invalid tensor type received (blck_size is 0): %u\n", __func__, tensor->type); + const ggml_type type = (ggml_type) tensor->type; + if (tensor->op >= GGML_OP_COUNT) { + LOG_ERROR("[%s] invalid tensor op: %u\n", __func__, tensor->op); + return nullptr; + } + if (tensor->ne[0] % ggml_blck_size(type) != 0) { + LOG_ERROR("[%s] ne[0] = %u is not a multiple of the %s block size\n", __func__, tensor->ne[0], ggml_type_name(type)); + return nullptr; + } + // same element count check as ggml_new_tensor + uint64_t nelements = tensor->ne[0]; + for (int i = 1; i < GGML_MAX_DIMS; i++) { + if (tensor->ne[i] > 1) { + if ((uint64_t) INT64_MAX / tensor->ne[i] <= nelements) { + LOG_ERROR("[%s] element count overflows int64_t\n", __func__); + return nullptr; + } + nelements *= tensor->ne[i]; + } + } + uint64_t nbytes; + if (!rpc_tensor_nbytes(*tensor, nbytes)) { + LOG_ERROR("[%s] tensor size overflows\n", __func__); return nullptr; } - ggml_tensor * result = ggml_new_tensor_4d(ctx, (ggml_type) tensor->type, - tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]); - - // ggml_new_tensor_4d might fail if dimensions are invalid, although less likely to crash than invalid type - if (result == nullptr) { - LOG_ERROR("[%s] ggml_new_tensor_4d failed for type %u\n", __func__, tensor->type); + ggml_backend_buffer_t buffer = reinterpret_cast(tensor->buffer); + if (buffer && buffers.find(buffer) == buffers.end()) { + buffer = nullptr; + } + if (buffer && nbytes > 0 && !rpc_in_buffer(buffer, tensor->data, nbytes)) { + LOG_ERROR("[%s] tensor '%.*s' (op %s, type %s) data 0x%" PRIx64 " with size %" PRIu64 " out of buffer bounds " + "(base %p, size %zu)\n", __func__, (int) sizeof(tensor->name), tensor->name, ggml_op_name((ggml_op) tensor->op), + ggml_type_name(type), tensor->data, nbytes, ggml_backend_buffer_get_base(buffer), ggml_backend_buffer_get_size(buffer)); return nullptr; } + ggml_tensor * result = ggml_new_tensor_4d(ctx, type, tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]); for (uint32_t i = 0; i < GGML_MAX_DIMS; i++) { result->nb[i] = tensor->nb[i]; } - result->buffer = reinterpret_cast(tensor->buffer); - if (result->buffer && buffers.find(result->buffer) == buffers.end()) { - result->buffer = nullptr; - } - - if (result->buffer && ggml_nelements(result) > 0) { - // require that the tensor data does not go beyond the buffer end - uint64_t tensor_size = (uint64_t) ggml_nbytes(result); - uint64_t buffer_start = (uint64_t) ggml_backend_buffer_get_base(result->buffer); - uint64_t buffer_size = (uint64_t) ggml_backend_buffer_get_size(result->buffer); - if (tensor->data + tensor_size < tensor->data || - tensor->data < buffer_start || tensor->data + tensor_size > buffer_start + buffer_size) { - LOG_ERROR("[%s] tensor '%s' (op %s, type %s, ne [%" PRId64 ", %" PRId64 ", %" PRId64 ", %" PRId64 "]) " - "data [0x%" PRIx64 ", 0x%" PRIx64 ") out of buffer bounds [0x%" PRIx64 ", 0x%" PRIx64 ")\n", - __func__, tensor->name, ggml_op_name((ggml_op) tensor->op), ggml_type_name(result->type), - result->ne[0], result->ne[1], result->ne[2], result->ne[3], - tensor->data, tensor->data + tensor_size, buffer_start, buffer_start + buffer_size); - return nullptr; - } - } - + result->buffer = buffer; result->op = (ggml_op) tensor->op; for (uint32_t i = 0; i < GGML_MAX_OP_PARAMS / sizeof(int32_t); i++) { result->op_params[i] = tensor->op_params[i]; @@ -1750,19 +1859,14 @@ ggml_tensor * rpc_server::deserialize_tensor(struct ggml_context * ctx, const rp bool rpc_server::set_tensor(socket_ptr sock, uint64_t input_size) { sync_all_backends(); - // serialization format: | rpc_tensor | cache_flag (1 byte) | offset (8 bytes) | data (size bytes) | - // only the header is read here, the data is streamed from the socket below - uint8_t cache_flag; - uint64_t offset; - uint8_t header[sizeof(rpc_tensor) + sizeof(cache_flag) + sizeof(offset)]; - const size_t header_size = sizeof(header); - if (input_size < header_size || !sock->recv_data(header, header_size)) { + // | rpc_msg_set_tensor_req | data (size bytes) | + rpc_msg_set_tensor_req request; + if (input_size < sizeof(request) || !sock->recv_data(&request, sizeof(request))) { return false; } - const rpc_tensor * in_tensor = (const rpc_tensor *)header; - memcpy(&cache_flag, header + sizeof(rpc_tensor), sizeof(cache_flag)); - memcpy(&offset, header + sizeof(rpc_tensor) + sizeof(cache_flag), sizeof(offset)); - const size_t size = input_size - header_size; + const uint8_t cache_flag = request.cache_flag; + const uint64_t offset = request.offset; + const size_t size = input_size - sizeof(request); struct ggml_init_params params { /*.mem_size =*/ ggml_tensor_overhead(), @@ -1772,27 +1876,14 @@ bool rpc_server::set_tensor(socket_ptr sock, uint64_t input_size) { ggml_context_ptr ctx_ptr { ggml_init(params) }; GGML_ASSERT(ctx_ptr != nullptr); ggml_context * ctx = ctx_ptr.get(); - ggml_tensor * tensor = deserialize_tensor(ctx, in_tensor); - if (tensor == nullptr || tensor->buffer == nullptr) { - LOG_ERROR("[%s] error deserializing tensor\n", __func__); + ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); + if (!rpc_check_region(__func__, tensor, offset, size)) { return false; } LOG_DBG2("[%s] tensor: %s, buffer: %p, data: %p, offset: %" PRIu64 ", size: %s\n", __func__, rpc_log_format_tensor(tensor).c_str(), (void*)tensor->buffer, tensor->data, offset, rpc_log_format_size(size).c_str()); - // sanitize tensor->data - { - const size_t p0 = (size_t) ggml_backend_buffer_get_base(tensor->buffer); - const size_t p1 = p0 + ggml_backend_buffer_get_size(tensor->buffer); - - if (in_tensor->data + offset < p0 || in_tensor->data + offset >= p1 || size > (p1 - in_tensor->data - offset)) { - LOG_ERROR("[%s] tensor data region (data=0x%" PRIx64 ", offset=%" PRIu64 ", size=%zu) out of buffer bounds [0x%zx, 0x%zx)\n", - __func__, in_tensor->data, offset, size, p0, p1); - return false; - } - } - if (cache_dir && cache_flag) { // the whole data is needed to compute the hash std::vector data(size); @@ -1829,20 +1920,10 @@ bool rpc_server::set_tensor(socket_ptr sock, uint64_t input_size) { bool rpc_server::set_tensor_2d(const std::vector & input) { sync_all_backends(); - // serialization format: | rpc_tensor | offset (8 bytes) | size (8 bytes) | n_copies (8 bytes) | stride (8 bytes) | data (size * n_copies bytes) | - if (input.size() < sizeof(rpc_tensor) + 4*sizeof(uint64_t)) { - return false; - } - const rpc_tensor * in_tensor = (const rpc_tensor *)input.data(); - uint64_t header[4]; - memcpy(header, input.data() + sizeof(rpc_tensor), sizeof(header)); - const uint64_t offset = header[0]; - const uint64_t size = header[1]; - const uint64_t n_copies = header[2]; - const uint64_t stride = header[3]; - - const uint64_t data_size = input.size() - sizeof(rpc_tensor) - 4*sizeof(uint64_t); - if (n_copies == 0 || size == 0 || size > data_size / n_copies || size * n_copies != data_size) { + // | rpc_msg_tensor_2d_req | data (size * n_copies bytes) | + rpc_reader reader(input); + rpc_msg_tensor_2d_req request; + if (!reader.read(request)) { return false; } @@ -1854,38 +1935,20 @@ bool rpc_server::set_tensor_2d(const std::vector & input) { ggml_context_ptr ctx_ptr { ggml_init(params) }; GGML_ASSERT(ctx_ptr != nullptr); ggml_context * ctx = ctx_ptr.get(); - ggml_tensor * tensor = deserialize_tensor(ctx, in_tensor); - if (tensor == nullptr || tensor->buffer == nullptr) { - LOG_ERROR("[%s] error deserializing tensor\n", __func__); + ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); + if (!rpc_check_region(__func__, tensor, request.offset, request.size, request.n_copies, request.stride)) { return false; } - LOG_DBG2("[%s] tensor: %s, buffer: %p, data: %p, offset: %" PRIu64 ", size: %s, n_copies: %" PRIu64 ", stride: %" PRIu64 "\n", - __func__, rpc_log_format_tensor(tensor).c_str(), (void*)tensor->buffer, tensor->data, offset, - rpc_log_format_size(size).c_str(), n_copies, stride); - - // sanitize tensor->data - { - if (stride != 0 && n_copies - 1 > (UINT64_MAX - size) / stride) { - return false; - } - const uint64_t span = (n_copies - 1)*stride + size; - const uint64_t p0 = (uint64_t) ggml_backend_buffer_get_base(tensor->buffer); - const uint64_t p1 = p0 + ggml_backend_buffer_get_size(tensor->buffer); - - if (in_tensor->data < p0 || in_tensor->data > p1 || offset > p1 - in_tensor->data || span > p1 - in_tensor->data - offset) { - LOG_ERROR("[%s] tensor data region (data=0x%" PRIx64 ", offset=%" PRIu64 ", span=%" PRIu64 ") out of buffer bounds [0x%" PRIx64 ", 0x%" PRIx64 ")\n", - __func__, in_tensor->data, offset, span, p0, p1); - return false; - } - if (offset > ggml_nbytes(tensor) || span > ggml_nbytes(tensor) - offset) { - LOG_ERROR("[%s] tensor write region (offset=%" PRIu64 ", span=%" PRIu64 ") out of tensor bounds (%zu)\n", - __func__, offset, span, ggml_nbytes(tensor)); - return false; - } + const uint8_t * data; + if (!reader.read_bytes(data, request.n_copies, request.size) || !reader.empty()) { + LOG_ERROR("[%s] data size does not match size * n_copies\n", __func__); + return false; } + LOG_DBG2("[%s] tensor: %s, buffer: %p, data: %p, offset: %" PRIu64 ", size: %s, n_copies: %" PRIu64 ", stride: %" PRIu64 "\n", + __func__, rpc_log_format_tensor(tensor).c_str(), (void*)tensor->buffer, tensor->data, request.offset, + rpc_log_format_size(request.size).c_str(), request.n_copies, request.stride); - const void * data = input.data() + sizeof(rpc_tensor) + 4*sizeof(uint64_t); - ggml_backend_tensor_set_2d(tensor, data, offset, size, n_copies, stride, size); + ggml_backend_tensor_set_2d(tensor, data, request.offset, request.size, request.n_copies, request.stride, request.size); return true; } @@ -1921,8 +1984,7 @@ bool rpc_server::set_tensor_hash(const rpc_msg_set_tensor_hash_req & request, rp GGML_ASSERT(ctx_ptr != nullptr); ggml_context * ctx = ctx_ptr.get(); ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); - if (tensor == nullptr || tensor->buffer == nullptr) { - LOG_ERROR("[%s] error deserializing tensor\n", __func__); + if (!rpc_check_region(__func__, tensor, request.offset, 0)) { return false; } @@ -1938,18 +2000,8 @@ bool rpc_server::set_tensor_hash(const rpc_msg_set_tensor_hash_req & request, rp __func__, rpc_log_format_tensor(tensor).c_str(), (void*)tensor->buffer, tensor->data, request.offset, rpc_log_format_size(size).c_str(), request.hash); - // sanitize tensor->data - { - const size_t p0 = (size_t) ggml_backend_buffer_get_base(tensor->buffer); - const size_t p1 = p0 + ggml_backend_buffer_get_size(tensor->buffer); - - if (request.tensor.data + request.offset < p0 - || request.tensor.data + request.offset >= p1 - || size > (p1 - request.tensor.data - request.offset)) { - LOG_ERROR("[%s] tensor data region (data=0x%" PRIx64 ", offset=%" PRIu64 ", size=%zu, hash=0x%" PRIx64 ") out of buffer bounds [0x%zx, 0x%zx)\n", - __func__, request.tensor.data, request.offset, size, request.hash, p0, p1); - return false; - } + if (!rpc_check_region(__func__, tensor, request.offset, size)) { + return false; } ggml_backend_tensor_set(tensor, cached_file.data(), request.offset, size); response.result = 1; @@ -2004,34 +2056,19 @@ bool rpc_server::get_tensor(const rpc_msg_get_tensor_req & request, std::vector< GGML_ASSERT(ctx_ptr != nullptr); ggml_context * ctx = ctx_ptr.get(); ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); - if (tensor == nullptr || tensor->buffer == nullptr) { - LOG_ERROR("[%s] error deserializing tensor\n", __func__); + if (!rpc_check_region(__func__, tensor, request.offset, request.size)) { return false; } LOG_DBG2("[%s] tensor: %s, buffer: %p, data: %p, offset: %" PRIu64 ", size: %s\n", __func__, rpc_log_format_tensor(tensor).c_str(), (void*)tensor->buffer, tensor->data, request.offset, rpc_log_format_size(request.size).c_str()); - // sanitize tensor->data - { - const size_t p0 = (size_t) ggml_backend_buffer_get_base(tensor->buffer); - const size_t p1 = p0 + ggml_backend_buffer_get_size(tensor->buffer); - - if (request.tensor.data + request.offset < p0 || - request.tensor.data + request.offset >= p1 || - request.size > (p1 - request.tensor.data - request.offset)) { - LOG_ERROR("[%s] requested tensor region (data=0x%" PRIx64 ", offset=%" PRIu64 ", size=%" PRIu64 ") out of buffer bounds [0x%zx, 0x%zx)\n", - __func__, request.tensor.data, request.offset, request.size, p0, p1); - return false; - } - } - response.resize(request.size, 0); ggml_backend_tensor_get(tensor, response.data(), request.offset, request.size); return true; } -bool rpc_server::get_tensor_2d(const rpc_msg_get_tensor_2d_req & request, std::vector & response) { +bool rpc_server::get_tensor_2d(const rpc_msg_tensor_2d_req & request, std::vector & response) { sync_all_backends(); struct ggml_init_params params { /*.mem_size =*/ ggml_tensor_overhead(), @@ -2042,39 +2079,13 @@ bool rpc_server::get_tensor_2d(const rpc_msg_get_tensor_2d_req & request, std::v GGML_ASSERT(ctx_ptr != nullptr); ggml_context * ctx = ctx_ptr.get(); ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); - if (tensor == nullptr || tensor->buffer == nullptr) { - LOG_ERROR("[%s] error deserializing tensor\n", __func__); + if (!rpc_check_region(__func__, tensor, request.offset, request.size, request.n_copies, request.stride)) { return false; } LOG_DBG2("[%s] tensor: %s, buffer: %p, data: %p, offset: %" PRIu64 ", size: %s, n_copies: %" PRIu64 ", stride: %" PRIu64 "\n", __func__, rpc_log_format_tensor(tensor).c_str(), (void*)tensor->buffer, tensor->data, request.offset, rpc_log_format_size(request.size).c_str(), request.n_copies, request.stride); - // sanitize tensor->data - { - if (request.n_copies == 0 || request.size == 0 || request.size > UINT64_MAX / request.n_copies) { - return false; - } - if (request.stride != 0 && request.n_copies - 1 > (UINT64_MAX - request.size) / request.stride) { - return false; - } - const uint64_t span = (request.n_copies - 1)*request.stride + request.size; - const uint64_t p0 = (uint64_t) ggml_backend_buffer_get_base(tensor->buffer); - const uint64_t p1 = p0 + ggml_backend_buffer_get_size(tensor->buffer); - - if (request.tensor.data < p0 || request.tensor.data > p1 || request.offset > p1 - request.tensor.data || - span > p1 - request.tensor.data - request.offset) { - LOG_ERROR("[%s] tensor data region (data=0x%" PRIx64 ", offset=%" PRIu64 ", span=%" PRIu64 ") out of buffer bounds [0x%" PRIx64 ", 0x%" PRIx64 ")\n", - __func__, request.tensor.data, request.offset, span, p0, p1); - return false; - } - if (request.offset > ggml_nbytes(tensor) || span > ggml_nbytes(tensor) - request.offset) { - LOG_ERROR("[%s] tensor read region (offset=%" PRIu64 ", span=%" PRIu64 ") out of tensor bounds (%zu)\n", - __func__, request.offset, span, ggml_nbytes(tensor)); - return false; - } - } - response.resize(request.size * request.n_copies, 0); ggml_backend_tensor_get_2d(tensor, response.data(), request.offset, request.size, request.n_copies, request.stride, request.size); return true; @@ -2093,25 +2104,8 @@ bool rpc_server::copy_tensor(const rpc_msg_copy_tensor_req & request, rpc_msg_co ggml_tensor * src = deserialize_tensor(ctx, &request.src); ggml_tensor * dst = deserialize_tensor(ctx, &request.dst); - if (src == nullptr || dst == nullptr || src->buffer == nullptr || dst->buffer == nullptr) { - LOG_ERROR("[%s] error deserializing tensors\n", __func__); - return false; - } - - uint64_t src_size = (uint64_t) ggml_nbytes(src); - uint64_t dst_data = (uint64_t) dst->data; - uint64_t dst_base = (uint64_t) ggml_backend_buffer_get_base(dst->buffer); - uint64_t dst_buf_sz = (uint64_t) ggml_backend_buffer_get_size(dst->buffer); - - if (dst_data + src_size > dst_base + dst_buf_sz) { - LOG_ERROR("[%s] out-of-bounds write in rpc_server::copy_tensor:\n" - " write range : [0x%" PRIx64 ", 0x%" PRIx64 "]\n" - " buffer base: [0x%" PRIx64 ", 0x%" PRIx64 "]\n", - __func__, - dst_data, - dst_data + src_size, - dst_base, - dst_base + dst_buf_sz); + if (src == nullptr || src->buffer == nullptr || !rpc_check_region(__func__, dst, 0, ggml_nbytes(src))) { + LOG_ERROR("[%s] invalid tensors\n", __func__); return false; } @@ -2121,93 +2115,25 @@ bool rpc_server::copy_tensor(const rpc_msg_copy_tensor_req & request, rpc_msg_co return true; } -ggml_tensor * rpc_server::create_node(uint64_t id, - struct ggml_context * ctx, - const std::unordered_map & tensor_ptrs, - std::unordered_map & tensor_map) { - if (tensor_map.find(id) != tensor_map.end()) { - return tensor_map[id]; - } - // Safely find the tensor pointer - auto it_ptr = tensor_ptrs.find(id); - if (it_ptr == tensor_ptrs.end()) { - return nullptr; - } - const rpc_tensor * tensor = it_ptr->second; - - struct ggml_tensor * result = deserialize_tensor(ctx, tensor); - if (result == nullptr) { - return nullptr; - } - if (result->buffer == nullptr && result->data != nullptr) { - LOG_ERROR("[%s] invalid data ptr\n", __func__); - return nullptr; - } - tensor_map[id] = result; - for (int i = 0; i < GGML_MAX_SRC; i++) { - // Check if the source ID is 0 before calling create_node recursively - if (tensor->src[i] == 0) { - result->src[i] = nullptr; - } else { - result->src[i] = create_node(tensor->src[i], ctx, tensor_ptrs, tensor_map); - // If the recursive call failed for a non-zero ID, propagate the error - if (result->src[i] == nullptr) { - LOG_ERROR("[%s] failed to create source node %d (src_id=%" PRIu64 ") for node id %" PRIu64 "\n", - __func__, i, tensor->src[i], id); - // Must return nullptr to signal failure up the call stack - return nullptr; - } - } - } - - // Handle view_src similarly - if (tensor->view_src == 0) { - result->view_src = nullptr; - } else { - result->view_src = create_node(tensor->view_src, ctx, tensor_ptrs, tensor_map); - // If the recursive call failed for a non-zero ID, propagate the error - if (result->view_src == nullptr) { - LOG_ERROR("[%s] failed to create view_src node (view_src_id=%" PRIu64 ") for node id %" PRIu64 "\n", - __func__, tensor->view_src, id); - // Must return nullptr to signal failure up the call stack - return nullptr; - } - } - result->view_offs = tensor->view_offs; - return result; -} - bool rpc_server::graph_compute(const std::vector & input) { - // serialization format: - // | device (4 bytes) | uid (8 bytes) | n_nodes (4 bytes) | nodes (n_nodes * sizeof(uint64_t) | n_tensors (4 bytes) | tensors (n_tensors * sizeof(rpc_tensor)) | - if (input.size() < 2*sizeof(uint32_t) + sizeof(uint64_t)) { + // | rpc_msg_graph_compute_req | nodes (n_nodes * uint64_t) | n_tensors (uint32_t) | tensors (n_tensors * rpc_tensor) | + rpc_reader reader(input); + rpc_msg_graph_compute_req request; + const uint8_t * node_ids; + uint32_t n_tensors; + const uint8_t * tensor_data; + if (!reader.read(request) || !reader.read_bytes(node_ids, request.n_nodes, sizeof(uint64_t)) || + !reader.read(n_tensors) || !reader.read_bytes(tensor_data, n_tensors, sizeof(rpc_tensor)) || !reader.empty()) { + LOG_ERROR("[%s] malformed request\n", __func__); return false; } - const uint8_t * src = input.data(); - uint32_t device; - memcpy(&device, src, sizeof(device)); - src += sizeof(device); + const uint32_t device = request.device; + const uint64_t uid = request.uid; + const uint32_t n_nodes = request.n_nodes; if (device >= backends.size()) { return false; } - uint64_t uid; - memcpy(&uid, src, sizeof(uid)); - src += sizeof(uid); - uint32_t n_nodes; - memcpy(&n_nodes, src, sizeof(n_nodes)); - src += sizeof(n_nodes); - if (input.size() < 2*sizeof(uint32_t) + sizeof(uint64_t) + n_nodes*sizeof(uint64_t) + sizeof(uint32_t)) { - return false; - } - const uint64_t * nodes = (const uint64_t *)src; - src += n_nodes*sizeof(uint64_t); - uint32_t n_tensors; - memcpy(&n_tensors, src, sizeof(n_tensors)); - src += sizeof(n_tensors); - if (input.size() < 2*sizeof(uint32_t) + sizeof(uint64_t) + n_nodes*sizeof(uint64_t) + sizeof(uint32_t) + n_tensors*sizeof(rpc_tensor)) { - return false; - } - const rpc_tensor * tensors = (const rpc_tensor *)src; + const rpc_tensor * tensors = (const rpc_tensor *) tensor_data; LOG_DBG("[%s] device: %u, uid: %" PRIu64 ", n_nodes: %u, n_tensors: %u\n", __func__, device, uid, n_nodes, n_tensors); // graphs with uid == 0 are not cached, see GRAPH_CACHE_MAX for the eviction policy @@ -2233,32 +2159,78 @@ bool rpc_server::graph_compute(const std::vector & input) { ggml_context * ctx = ctx_ptr.get(); struct ggml_cgraph * graph = ggml_new_graph_custom(ctx, n_nodes, false); graph->n_nodes = n_nodes; - std::unordered_map tensor_ptrs; - tensor_ptrs.reserve(n_tensors); - for (uint32_t i = 0; i < n_tensors; i++) { - tensor_ptrs.emplace(tensors[i].id, &tensors[i]); - } - std::unordered_map tensor_map; - tensor_map.reserve(n_nodes); + // the compute itself is asynchronous, so building the graph is the only server-side cost // observable here - the round trip is timed on the client const auto t_deserialize = std::chrono::steady_clock::now(); + + // tensors come in topological order (see add_tensor), so the graph is built in one pass and a source sent + // after its user is rejected; a tensor may be its own source (ggml_cast) + std::unordered_map tensor_idx; + tensor_idx.reserve(n_tensors); + std::vector created(n_tensors); + auto lookup = [&](uint64_t id, ggml_tensor ** out) { + if (id == 0) { + *out = nullptr; + return true; + } + auto it = tensor_idx.find(id); + if (it == tensor_idx.end()) { + return false; + } + *out = created[it->second]; + return true; + }; + for (uint32_t i = 0; i < n_tensors; i++) { + const rpc_tensor & wire = tensors[i]; + ggml_tensor * result = deserialize_tensor(ctx, &wire); + if (result == nullptr) { + return false; + } + if (result->buffer == nullptr && result->data != nullptr) { + LOG_ERROR("[%s] tensor %u (id=%" PRIu64 ") has a data pointer but no buffer\n", __func__, i, wire.id); + return false; + } + if (wire.id == 0 || !tensor_idx.emplace(wire.id, i).second) { + LOG_ERROR("[%s] tensor %u has a zero or duplicate id %" PRIu64 "\n", __func__, i, wire.id); + return false; + } + created[i] = result; + bool found = lookup(wire.view_src, &result->view_src); + for (int s = 0; s < GGML_MAX_SRC; s++) { + found = found && lookup(wire.src[s], &result->src[s]); + } + if (!found) { + LOG_ERROR("[%s] tensor %u (id=%" PRIu64 ") references a tensor that was not sent before it\n", __func__, i, wire.id); + return false; + } + result->view_offs = wire.view_offs; + if (!rpc_check_view(result)) { + LOG_ERROR("[%s] view %u (id=%" PRIu64 ", view_offs=%" PRIu64 ") out of view_src bounds\n", __func__, i, wire.id, wire.view_offs); + return false; + } + } for (uint32_t i = 0; i < n_nodes; i++) { - int64_t id; - memcpy(&id, &nodes[i], sizeof(id)); - graph->nodes[i] = create_node(id, ctx, tensor_ptrs, tensor_map); - // Check if create_node failed for a *non-zero* ID. - // If id was 0, create_node returning nullptr is expected. - // If id was non-zero and create_node returned nullptr, it indicates a deserialization error. - if (graph->nodes[i] == nullptr && id != 0) { - LOG_ERROR("[%s] failed to create graph node %d (id=%" PRId64 ")\n", __func__, i, id); + uint64_t id; + memcpy(&id, node_ids + i*sizeof(id), sizeof(id)); + auto it = tensor_idx.find(id); + if (it == tensor_idx.end()) { + LOG_ERROR("[%s] graph node %u (id=%" PRIu64 ") is not in the tensor list\n", __func__, i, id); return false; } - if (graph->nodes[i] != nullptr) { - LOG_DBG3("[%s] node %u: id=%" PRId64 ", %s\n", __func__, i, id, rpc_log_format_tensor(graph->nodes[i]).c_str()); - const size_t hash_pos = ggml_hash_insert(&graph->visited_hash_set, graph->nodes[i]); - graph->use_counts[hash_pos] = tensor_ptrs.at(id)->use_count; + ggml_tensor * node = created[it->second]; + if (!rpc_check_node(node)) { + LOG_ERROR("[%s] graph node %u (%s) or one of its sources is not allocated on this server\n", __func__, i, node->name); + return false; + } + const size_t hash_pos = ggml_hash_insert(&graph->visited_hash_set, node); + if (hash_pos == GGML_HASHSET_ALREADY_EXISTS) { + LOG_ERROR("[%s] graph node %u (id=%" PRIu64 ") is a duplicate\n", __func__, i, id); + return false; } + graph->nodes[i] = node; + graph->use_counts[hash_pos] = tensors[it->second].use_count; + LOG_DBG3("[%s] node %u: id=%" PRIu64 ", %s\n", __func__, i, id, rpc_log_format_tensor(node).c_str()); } const std::chrono::duration deserialize_ms = std::chrono::steady_clock::now() - t_deserialize; @@ -2653,6 +2625,32 @@ rpc_server::~rpc_server() { } } +template +static bool rpc_send_rsp(const socket_ptr & sock, const T & response) { + return send_msg(sock, &response, sizeof(response)); +} + +static bool rpc_send_rsp(const socket_ptr & sock, const std::vector & response) { + return send_msg(sock, response.data(), response.size()); +} + +// receives the request of `cmd`, runs the handler and sends the response, if the command has one +template +static bool rpc_serve(const socket_ptr & sock, rpc_server & server, handler_t handler) { + using req_t = typename rpc_msg_types::req; + using rsp_t = typename rpc_msg_types::rsp; + req_t request; + if (!recv_msg(sock, &request, sizeof(request))) { + return false; + } + if constexpr (std::is_void_v) { + return (server.*handler)(request); + } else { + rsp_t response = {}; + return (server.*handler)(request, response) && rpc_send_rsp(sock, response); + } +} + static void rpc_serve_client(const std::vector & backends, const char * cache_dir, socket_ptr sock) { rpc_server server(backends, cache_dir); @@ -2693,6 +2691,7 @@ static void rpc_serve_client(const std::vector & backends, const // Activate transport upgrade using client's caps sock->update_caps(req.conn_caps); LOG_DBG("[%s] client connected, transport: %s\n", __func__, sock->transport_name()); + std::vector input; while (true) { if (!sock->recv_data(&cmd, 1)) { break; @@ -2703,280 +2702,52 @@ static void rpc_serve_client(const std::vector & backends, const break; } LOG_DBG2("[%s] %s\n", __func__, rpc_cmd_name((enum rpc_cmd)cmd)); - switch (cmd) { - case RPC_CMD_HELLO: { - // HELLO command is handled above - return; - } - case RPC_CMD_DEVICE_COUNT: { - if (!recv_msg(sock, nullptr, 0)) { - return; - } - rpc_msg_device_count_rsp response; - response.device_count = backends.size(); - if (!send_msg(sock, &response, sizeof(response))) { - return; - } - break; - } - case RPC_CMD_ALLOC_BUFFER: { - rpc_msg_alloc_buffer_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - rpc_msg_alloc_buffer_rsp response; - if (!server.alloc_buffer(request, response)) { - return; - } - if (!send_msg(sock, &response, sizeof(response))) { - return; - } - break; - } - case RPC_CMD_GET_ALLOC_SIZE: { - rpc_msg_get_alloc_size_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - rpc_msg_get_alloc_size_rsp response; - if (!server.get_alloc_size(request, response)) { - return; - } - if (!send_msg(sock, &response, sizeof(response))) { - return; - } - break; - } - case RPC_CMD_GET_ALIGNMENT: { - rpc_msg_get_alignment_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - rpc_msg_get_alignment_rsp response; - if (!server.get_alignment(request, response)) { - return; - } - if (!send_msg(sock, &response, sizeof(response))) { - return; - } - break; - } - case RPC_CMD_GET_MAX_SIZE: { - rpc_msg_get_max_size_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - rpc_msg_get_max_size_rsp response; - if (!server.get_max_size(request, response)) { - return; - } - if (!send_msg(sock, &response, sizeof(response))) { - return; - } - break; - } - case RPC_CMD_BUFFER_GET_BASE: { - rpc_msg_buffer_get_base_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - rpc_msg_buffer_get_base_rsp response; - if (!server.buffer_get_base(request, response)) { - return; - } - if (!send_msg(sock, &response, sizeof(response))) { - return; - } - break; - } - case RPC_CMD_FREE_BUFFER: { - rpc_msg_free_buffer_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - if (!server.free_buffer(request)) { - return; - } - break; - } - case RPC_CMD_BUFFER_CLEAR: { - rpc_msg_buffer_clear_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - if (!server.buffer_clear(request)) { - return; - } - break; - } - case RPC_CMD_MEMSET_TENSOR: { - rpc_msg_memset_tensor_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - if (!server.memset_tensor(request)) { - return; - } - break; - } - case RPC_CMD_SET_TENSOR: { - uint64_t input_size; - if (!sock->recv_data(&input_size, sizeof(input_size))) { - return; - } - if (!server.set_tensor(sock, input_size)) { - return; - } - break; - } - case RPC_CMD_SET_TENSOR_2D: { - std::vector input; - if (!recv_msg(sock, input)) { - return; - } - if (!server.set_tensor_2d(input)) { - return; - } - break; - } - case RPC_CMD_GET_TENSOR_2D: { - rpc_msg_get_tensor_2d_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; + bool ok = false; + try { + switch (cmd) { + case RPC_CMD_DEVICE_COUNT: { + const rpc_msg_device_count_rsp response = { (uint32_t) backends.size() }; + ok = recv_msg(sock, nullptr, 0) && send_msg(sock, &response, sizeof(response)); + break; } - std::vector response; - if (!server.get_tensor_2d(request, response)) { - return; + case RPC_CMD_SET_TENSOR: { + // the handler streams the data from the socket + uint64_t input_size; + ok = sock->recv_data(&input_size, sizeof(input_size)) && server.set_tensor(sock, input_size); + break; } - if (!send_msg(sock, response.data(), response.size())) { - return; - } - break; - } - case RPC_CMD_SET_TENSOR_HASH: { - rpc_msg_set_tensor_hash_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - rpc_msg_set_tensor_hash_rsp response; - if (!server.set_tensor_hash(request, response)) { - return; - } - if (!send_msg(sock, &response, sizeof(response))) { - return; - } - break; - } - case RPC_CMD_INIT_TENSOR: { - rpc_msg_init_tensor_req request; - if (!recv_msg(sock, &request,sizeof(request))) { - return; - } - if (!server.init_tensor(request)) { - return; - } - break; - } - case RPC_CMD_GET_TENSOR: { - rpc_msg_get_tensor_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - std::vector response; - if (!server.get_tensor(request, response)) { - return; - } - if (!send_msg(sock, response.data(), response.size())) { - return; - } - break; - } - case RPC_CMD_COPY_TENSOR: { - rpc_msg_copy_tensor_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - rpc_msg_copy_tensor_rsp response; - if (!server.copy_tensor(request, response)) { - return; - } - if (!send_msg(sock, &response, sizeof(response))) { - return; - } - break; - } - case RPC_CMD_GRAPH_COMPUTE: { - std::vector input; - if (!recv_msg(sock, input)) { - return; - } - if (!server.graph_compute(input)) { - return; - } - break; - } - case RPC_CMD_GRAPH_RECOMPUTE: { - rpc_msg_graph_recompute_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - if (!server.graph_recompute(request)) { - return; - } - break; - } - case RPC_CMD_COMM_INIT: { - rpc_msg_comm_init_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - rpc_msg_comm_init_rsp response; - if (!server.comm_init(request, response)) { - return; - } - if (!send_msg(sock, &response, sizeof(response))) { - return; - } - break; - } - case RPC_CMD_COMM_ALLREDUCE: { - rpc_msg_comm_allreduce_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - if (!server.comm_allreduce(request)) { - return; - } - break; - } - case RPC_CMD_COMM_FREE: { - rpc_msg_comm_free_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - if (!server.comm_free(request)) { - return; - } - break; - } - case RPC_CMD_GET_DEVICE_MEMORY: { - rpc_msg_get_device_memory_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - rpc_msg_get_device_memory_rsp response; - if (!server.get_device_memory(request, response)) { - return; - } - if (!send_msg(sock, &response, sizeof(response))) { - return; - } - break; - } - default: { - LOG_ERROR("Unhandled command: %s\n", rpc_cmd_name((enum rpc_cmd)cmd)); - return; + case RPC_CMD_SET_TENSOR_2D: ok = recv_msg(sock, input) && server.set_tensor_2d(input); break; + case RPC_CMD_GRAPH_COMPUTE: ok = recv_msg(sock, input) && server.graph_compute(input); break; + case RPC_CMD_ALLOC_BUFFER: ok = rpc_serve (sock, server, &rpc_server::alloc_buffer); break; + case RPC_CMD_GET_ALIGNMENT: ok = rpc_serve (sock, server, &rpc_server::get_alignment); break; + case RPC_CMD_GET_MAX_SIZE: ok = rpc_serve (sock, server, &rpc_server::get_max_size); break; + case RPC_CMD_GET_ALLOC_SIZE: ok = rpc_serve (sock, server, &rpc_server::get_alloc_size); break; + case RPC_CMD_GET_DEVICE_MEMORY: ok = rpc_serve(sock, server, &rpc_server::get_device_memory); break; + case RPC_CMD_BUFFER_GET_BASE: ok = rpc_serve (sock, server, &rpc_server::buffer_get_base); break; + case RPC_CMD_FREE_BUFFER: ok = rpc_serve (sock, server, &rpc_server::free_buffer); break; + case RPC_CMD_BUFFER_CLEAR: ok = rpc_serve (sock, server, &rpc_server::buffer_clear); break; + case RPC_CMD_INIT_TENSOR: ok = rpc_serve (sock, server, &rpc_server::init_tensor); break; + case RPC_CMD_MEMSET_TENSOR: ok = rpc_serve (sock, server, &rpc_server::memset_tensor); break; + case RPC_CMD_SET_TENSOR_HASH: ok = rpc_serve (sock, server, &rpc_server::set_tensor_hash); break; + case RPC_CMD_GET_TENSOR: ok = rpc_serve (sock, server, &rpc_server::get_tensor); break; + case RPC_CMD_GET_TENSOR_2D: ok = rpc_serve (sock, server, &rpc_server::get_tensor_2d); break; + case RPC_CMD_COPY_TENSOR: ok = rpc_serve (sock, server, &rpc_server::copy_tensor); break; + case RPC_CMD_GRAPH_RECOMPUTE: ok = rpc_serve (sock, server, &rpc_server::graph_recompute); break; + case RPC_CMD_COMM_INIT: ok = rpc_serve (sock, server, &rpc_server::comm_init); break; + case RPC_CMD_COMM_ALLREDUCE: ok = rpc_serve (sock, server, &rpc_server::comm_allreduce); break; + case RPC_CMD_COMM_FREE: ok = rpc_serve (sock, server, &rpc_server::comm_free); break; + default: + // HELLO is only valid as the first command + LOG_ERROR("Unhandled command: %s\n", rpc_cmd_name((enum rpc_cmd)cmd)); + break; } + } catch (const std::bad_alloc &) { + // allocation sizes come from the client, e.g. a large GET_TENSOR response + LOG_ERROR("[%s] %s: out of memory\n", __func__, rpc_cmd_name((enum rpc_cmd)cmd)); + ok = false; + } + if (!ok) { + return; } } } @@ -3213,9 +2984,7 @@ static void ggml_backend_rpc_comm_free(void * comm_ctx_v) { return; } for (const auto & rank : comm_ctx->ranks) { - auto request = std::make_shared(); - request->device = rank.device; - rank.dispatcher->send(RPC_CMD_COMM_FREE, request, sizeof(*request), nullptr, 0, nullptr, 0); + rank.dispatcher->call({ rank.device }); rank.dispatcher->busy_spin_release(); } delete comm_ctx; @@ -3264,15 +3033,15 @@ static void * ggml_backend_rpc_comm_init(ggml_backend_t * backends, size_t n_bac // until rank 1 has connected. std::vector responses(n_backends); for (size_t i = 0; i < n_backends; i++) { - auto request = std::make_shared(); - request->device = ranks[i].device; - request->rank = (uint32_t) i; - request->world = (uint32_t) n_backends; - request->port = comm_port; + rpc_msg_comm_init_req request = {}; + request.device = ranks[i].device; + request.rank = (uint32_t) i; + request.world = (uint32_t) n_backends; + request.port = comm_port; if (i > 0) { - memcpy(request->host, host0.c_str(), host0.size()); + memcpy(request.host, host0.c_str(), host0.size()); } - ranks[i].dispatcher->send_async(RPC_CMD_COMM_INIT, request, sizeof(*request), &responses[i], sizeof(responses[i])); + ranks[i].dispatcher->call_async(request, &responses[i]); } for (size_t i = 0; i < n_backends; i++) { ranks[i].dispatcher->synchronize(); @@ -3318,10 +3087,7 @@ static bool ggml_backend_rpc_comm_allreduce_tensor(void * comm_ctx_v, ggml_tenso } } for (size_t i = 0; i < n_ranks; i++) { - auto request = std::make_shared(); - request->device = comm_ctx->ranks[i].device; - request->tensor = serialize_tensor(tensors[i]); - comm_ctx->ranks[i].dispatcher->send_async(RPC_CMD_COMM_ALLREDUCE, request, sizeof(*request)); + comm_ctx->ranks[i].dispatcher->call_async({ comm_ctx->ranks[i].device, serialize_tensor(tensors[i]) }); } return true; } From 51fc2f90e23d4faf0f726f476a5452652b535145 Mon Sep 17 00:00:00 2001 From: Ravi Panchumarthy Date: Mon, 23 Nov 2026 06:29:20 -0800 Subject: [PATCH 017/275] ggml-openvino: CI fixes, new model support, fixes and improvements. (#32861) * ggml-openvino: keep the rope angle in f32 under the f16 inference hint * ggml-openvino: add a GGML_OP_ARGMAX translator * ggml-openvino: keep the token dim dynamic for a 2-D activation graph input * ggml-openvino: tolerate graph inputs and outputs with no backing storage * ggml-openvino: invalidate a cached graph when its output set changes * ggml-openvino: bound the compiled-model cache to N shapes instead of 1 * ggml-openvino: add GGML_OPENVINO_LOG_SUPPORTS_OP diagnostic * ggml-openvino: honour a node's dynamic-dim classification on non-split graphs too * ggml-openvino: fold consecutive SET_ROWS column writes into one scatter * ggml-openvino: keep the speculative decoding feature buffers in device memory * ggml-openvino: keep the fixed token count of static graph inputs for npu GDN In a static (NPU) graph that overwrites the fixed token count that get_graph_input_shape set just before, for example of inp_tokens, so the NPU graph got a dynamic token dimension. GATED_DELTA_NET models (Qwen3.5, Qwen3.6) then fail to translate: "GATED_DELTA_NET pad masking requires a static token dimension". Keep the change for dynamic graphs and the previous behaviour for static ones. * ggml-openvino: one output in the decode model of a static NPU pair The decode model of a static prefill/decode pair copied the compute params of the prefill graph, including output_len. With llama-perplexity the prefill graph has many outputs (128 at -c 256), so the decode model gathered 128 rows from its one token in the last layer. For a MoE model that layer then differs from the others and NPUW fails to lower its experts ("could not lower the isolated expert partition"). A decode step outputs one token; the model cache key already assumes it (decode_signature out=1). * ggml-openvino: fix gated delta net when v is a view with padded heads The GDN translator assumed v is a view of the fused qkv conv output with the heads packed in each row, and sliced H_v * S_v elements off that row. test-backend-ops now has padded_v cases, where v views a wider tensor and each head row is padded (nb[1] > S_v * nb[0]). The slice then read the padding, and the results were wrong on CPU and GPU. Take the packed path only when nb[1] == S_v * nb[0]. Any other view goes through the generic view resolution, which already returns [B, T, H_v, S_v], so the reshape of the packed case is skipped too. Model graphs build v with packed heads and keep the packed path. * ggml-openvino: make the f32 rope angle opt-in GGML_OPENVINO_ROPE_F32_ANGLE was on by default. It changes the RoPE of every model on every device, and it was validated on one model on the GPU only. On the CPU device, which computes in f32, its f16 round trip rounds cos and sin, and ROPE cases of test-backend-ops fail against the CPU backend. Turn it off by default; GGML_OPENVINO_ROPE_F32_ANGLE=1 turns it on. Fix the comment that called the round trip a no-op on f32 paths. Document the variable, and the two diagnostics added with it (GGML_OPENVINO_LOG_SUPPORTS_OP, GGML_OPENVINO_DIAG_GRAPH_IO), in the dev_doc. * docs : add the Muse-Glimmer-30B DFlash memory limit and env var samples Muse-Glimmer-30B with a DFlash draft peaks at about 45 GB of RAM on an integrated GPU. Add it to the GPU limitations as a runnable sample, and add samples for GGML_OPENVINO_LOG_SUPPORTS_OP and GGML_OPENVINO_DIAG_GRAPH_IO to the dev_doc. * ggml-openvino: fix weight zero points, buffer extras and cache-key gaps A code review of ggml/src/ggml-openvino found these bugs: - Q4_1 weights: `extract_q4_1_data` packs two zero points per byte from a `parallel_for` over blocks, so two threads can write the same byte. - Zero points out of the u4/u8 range wrap around instead of saturating. gemma-4-E2B has 6 Q4_K sub-blocks with a zero point of 16 or more; 16 wrapped to 0. - `set_tensor` overwrote the extra that `init_tensor` created for a weight without deleting it. - The two buffer constructors had separate id counters, and the buffer id is part of the shared graph key. - A freed weight buffer stayed in the release registry, so a later release could madvise memory it no longer owned. - `GGML_OPENVINO_ROPE_F32_ANGLE` changes the graph but was not in the compiled-model cache key. - On NPU, group-128 requantization ignored the row width. A model whose rows are not a multiple of 128 failed to load its weights (SmolLM2-360M). - The static Split cache held a strong reference to the Split on its own input (a reference cycle) and ignored the output port. - `rms_norm` took op_case 3 for both a direct and a packed pre-scaled GDN output, so the packed one was not sliced. - Smaller items: static decode read `out_ids` even when it is empty; the static path aborted where the dynamic path returns an error; a damaged weights `.meta` hash threw from `std::stoull`; `extract_layer_from_name` threw on a non-numeric suffix; `GGML_OP_FILL` was registered twice. - ggml-quants.cpp: one `parallel_for` iteration per zero point byte for Q4_1; clamp zero points to [0, 15] (u4) and [0, 255] (u8). - ggml-openvino.cpp: `ggml_openvino_set_extra` replaces and deletes the old extra at every site; one id counter; `ggml_openvino_unregister_weight_buffer` in the buffer destructor; a failed KV re-allocation returns `GGML_STATUS_ALLOC_FAILED`. - model-cache.cpp: hash `GGML_OPENVINO_ROPE_F32_ANGLE`, cache version 9; `strtoull` for the `.meta` hash. - npu_quant_policy.cpp: Q4_0_128 falls back to Q4_0_C when `ne[0] % 128 != 0`. ggml-openvino-extra.cpp: the group-64 requant targets fall back to Q8_0_C when `ne[0] % 64 != 0`. - openvino/utils.cpp: the static Split cache uses a weak reference and the output port in its key, like the dynamic one. - rms_norm.cpp, ggml-decoder.cpp: op_case 5 for a packed pre-scaled GDN output. - utils.cpp: static decode writes 0 to `out_ids`; a compile after a weight release returns `GGML_STATUS_FAILED`. - ggml-decoder.cpp: `extract_layer_from_name` returns nullopt for a non-numeric suffix. - op_table.cpp/.h: remove the duplicate `GGML_OP_FILL`. * ggml-openvino: copy the decoder once per graph conversion `GgmlOvDecoder::visit_subgraph` made a full copy of the decoder for every node it visited. Translators only read the decoder, so one copy per walk is enough. Graph conversion time drops 12-24x (Qwen3.5-0.8B: 4.1 s to 0.17 s over the six graphs of a short run). - ggml-decoder.cpp: make one decoder copy before the node loop. - utils.cpp: `get_static_attention_size` takes the decoder by const reference and does not copy the compute params. * ggml-openvino: remove dead code and fix stale comments Code that nothing calls or registers, and comments that no longer match the code. No behavior change. - Remove `translate_gated_delta_net_ref`, `translate_solve_tri` (not registered), the unused `FuseToSDPA` pass, `add_rope_sin_cos`, `checksum`, `save_ggml_tensor_data_to_txt`, `non_cont_dim`, the unused templates in openvino/utils.h and the undefined `getCurrentTime` declaration. - ggml-decoder.cpp: drop the VIEW op_case tail that only ever set 0. - utils.cpp: drop a duplicate `entry->ptr` store and the always-false `!model_leafs.empty() == false` term. - `ggml_openvino_manual_gqa_enabled()` replaces two copies of the GGML_OPENVINO_MANUAL_GQA_ATTN default (flash_attn_ext.cpp and the cache key). - ggml-openvino.cpp: remove the SSM_CONV case whose comment said it stays on CPU (it runs on OpenVINO); fix the gemma3n reason text (not GPU-only) and two typos. * ggml-openvino: track dynamic dims through bailingmoe3's GDN views and conv state bailingmoe3 uses GATED_DELTA_NET views to expose its attention and state outputs. Preserve their dynamic dimensions in the decoder. - Assign the dynamic dimensions of the translated attention and state outputs to the corresponding GATED_DELTA_NET result VIEWs. - Count the convolution state slots using the rows spanned by the destination view. bailingmoe3 packs the q/k/v convolution states into a single row. - Preserve the tracked dynamic dimension in RESHAPE op case 0 when the reshape only adds a trailing size-1 dimension. * ggml-openvino: translate the per-key gate of GATED_DELTA_NET Ling-3.0-tiny (bailingmoe3) uses a gate per key dimension (kda), which the backend previously rejected, causing these layers to fall back to the CPU. - Use the fused GatedDeltaNet when the OpenVINO runtime and target device support a rank-4 gate. - Detect support once by compiling a one-node GatedDeltaNet with a rank-4 gate and checking the target device with query_model. Older runtimes reject this gate, and the CPU plugin does not support it. - Fall back to the reference loop when the fused path is unavailable. - Support a dynamic token count in the reference loop by using dynamic reshapes and deriving the trip count from the input shape. - Reject unsupported cases with a reason: padded chunks, recurrent caches, state snapshots, and the native state layout. The loop currently handles one state in the ggml layout. * ggml-openvino: Fix issue highlighted by tests * ggml-openvino: reject a padded permuted v in gated delta net supports_op rejected a permuted v only when src2 was the PERMUTE itself. With padded heads, v is a VIEW of the PERMUTE, so the check missed it and the per-key gate reference loop ran on a v layout it does not handle. Look through the VIEW so this case falls back like the other permuted v inputs. * ggml-openvino: write back intermediate nodes of op-test graphs The ADD_RMS_NORM_MUL op test checks the intermediate sum of its graph as well as the final output. compute_model_outputs() made a node a model output only when the graph does not consume all of it, so the sum was never written back and the test read uninitialised memory (28 failures on GPU and CPU). MUL_MAT_ID_SHARED, which checks its routed and shared results, failed the same way on CPU. Op-test graphs (the naive path) can read any node, so make every non-in-place node a model output there. Model graphs are unchanged. --------- Co-authored-by: Mustafa Cavus Co-authored-by: yzhou51 Co-authored-by: Sabnis, Omkar --- docs/backend/OPENVINO.md | 10 + .../dev_doc/OpenVINO-ENV-VARS.md | 9 + .../ggml-openvino/device/npu_quant_policy.cpp | 8 +- ggml/src/ggml-openvino/ggml-decoder.cpp | 115 ++++---- ggml/src/ggml-openvino/ggml-decoder.h | 17 ++ .../src/ggml-openvino/ggml-openvino-extra.cpp | 24 +- ggml/src/ggml-openvino/ggml-openvino-extra.h | 4 + ggml/src/ggml-openvino/ggml-openvino.cpp | 266 +++++++++++++----- ggml/src/ggml-openvino/ggml-quants.cpp | 33 ++- ggml/src/ggml-openvino/model-cache.cpp | 10 +- ggml/src/ggml-openvino/openvino/op/argmax.cpp | 51 ++++ .../openvino/op/flash_attn_ext.cpp | 8 +- .../openvino/op/gated_delta_net.cpp | 88 ++++-- .../src/ggml-openvino/openvino/op/reshape.cpp | 4 + .../ggml-openvino/openvino/op/rms_norm.cpp | 4 +- .../ggml-openvino/openvino/op/set_rows.cpp | 33 ++- .../ggml-openvino/openvino/op/solve_tri.cpp | 108 ------- ggml/src/ggml-openvino/openvino/op_table.cpp | 4 +- ggml/src/ggml-openvino/openvino/op_table.h | 5 +- .../openvino/pass/fuse_to_sdpa.cpp | 60 ---- .../openvino/pass/fuse_to_sdpa.h | 17 -- .../openvino/translate_session.cpp | 30 -- ggml/src/ggml-openvino/openvino/utils.cpp | 101 +++++-- ggml/src/ggml-openvino/openvino/utils.h | 34 --- ggml/src/ggml-openvino/utils.cpp | 188 +++++++------ ggml/src/ggml-openvino/utils.h | 45 ++- 26 files changed, 721 insertions(+), 555 deletions(-) create mode 100644 ggml/src/ggml-openvino/openvino/op/argmax.cpp delete mode 100644 ggml/src/ggml-openvino/openvino/op/solve_tri.cpp delete mode 100644 ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.cpp delete mode 100644 ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.h diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md index a3a94aa16fb6..27c17c3eff8b 100644 --- a/docs/backend/OPENVINO.md +++ b/docs/backend/OPENVINO.md @@ -995,6 +995,16 @@ build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M. **GPU-specific** +- Muse-Glimmer-30B with a DFlash draft needs a 64 GB system (peak about 45 GB of RAM): + + ```bash + export GGML_OPENVINO_DEVICE=GPU + export GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill # local disk, not tmpfs + export GGML_OPENVINO_ROPE_F32_ANGLE=1 # long prompts + mkdir -p $GGML_OPENVINO_SPILL_DIR + ./build/ReleaseOV/bin/llama-server -m Muse-Glimmer-30B-Q4_K_M.gguf -md .gguf \ + --spec-type draft-dflash --spec-draft-n-max 4 + ``` - Multiple GPUs (`GGML_OPENVINO_DEVICE=GPU.0,GPU.1` with `-sm layer`): - `-sm tensor` is not supported. - Copies between GPUs go through host memory. There is no asynchronous copy and no peer-to-peer copy. diff --git a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md index a43ac1d6af38..9d72ceacb912 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -13,6 +13,8 @@ The variables for users, and the rules for values, are in [docs/backend/OPENVINO | `GGML_OPENVINO_DEBUG_NODE` | all | String | `not set` | Add the named graph nodes as outputs of the compiled model. Separate several names with commas. | | `GGML_OPENVINO_PRINT_CGRAPH_TENSOR_ADDRESS` | all | Boolean | `0` | Print the tensor address map once. | | `GGML_OPENVINO_LOG_UNSUPPORTED_OPS` | all | Boolean | `0` | Log each op that the backend does not support, with the tensor details and the reason. | +| `GGML_OPENVINO_LOG_SUPPORTS_OP` | all | Integer | `0` | Log what `supports_op` accepts and rejects. `1`: summary at exit. `2`: also each call (the first calls are missing). | +| `GGML_OPENVINO_DIAG_GRAPH_IO` | all | Boolean | `0` | When binding a tensor or `infer()` throws, log the graph key and the shapes of the model and the bound tensors. | | `GGML_OPENVINO_DISABLE_CACHE` | all | Boolean | `0` | Turn the in-process cache of compiled models and decoders off. | | `GGML_OPENVINO_FULL_GRAPH_KEY` | all | Boolean | `0` | Add the external inputs of a graph to the key of the in-process cache. By default the key is the node count and the names of the first and last nodes. Use it when two different graphs could share that key. | | `GGML_OPENVINO_LOG_SWA_LAYERS` | all | Boolean | `0` | Log the attention extent of each layer and which layers use sliding-window attention, on an `ov-swa:` line at the WARN level. | @@ -29,6 +31,12 @@ GGML_OPENVINO_DUMP_CGRAPH=1 GGML_OPENVINO_DUMP_IR=1 \ # Log unsupported ops. The lines have the WARN level, which the default log verbosity shows (-lv 2 or higher). GGML_OPENVINO_LOG_UNSUPPORTED_OPS=1 ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 +# What supports_op accepts and rejects: 1 = summary at exit, 2 = also each call +GGML_OPENVINO_LOG_SUPPORTS_OP=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 16 -no-cnv -p "Hello" 2>&1 | grep ov-supports-op + +# Graph key and tensor shapes when an inference throws +GGML_OPENVINO_DIAG_GRAPH_IO=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 16 -no-cnv -p "Hello" 2>&1 | grep DIAG + # NPUW dumps. They need an OpenVINO developer build (NPU_PLUGIN_DEVELOPER_BUILD). export GGML_OPENVINO_DEVICE=NPU export GGML_OPENVINO_NPUW_DUMP_SUBS=YES @@ -74,6 +82,7 @@ These options are off by default. They are not validated for general use: some h | `GGML_OPENVINO_GDN_NATIVE_STATE` | NPU | Boolean | `0` | Keep the `GATED_DELTA_NET` state in the layout of the OpenVINO op instead of the GGML layout. Every `GATED_DELTA_NET` must then run on the OpenVINO backend; the load aborts if one would run on the CPU backend. Saved states and `GGML_OPENVINO_DEBUG_NODE` dumps hold the OpenVINO layout. `test-backend-ops` fails with it. | | `GGML_OPENVINO_FORCE_STATIC` | CPU, GPU | Boolean | `0` | Run the static-shape path of the NPU on the CPU or the GPU, to separate translation bugs from NPU plugin or driver problems. Cannot be used with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY`. | | `GGML_OPENVINO_ENABLE_FALLBACK` | all | Boolean | `0` | Detect graphs that the scheduler splits between OpenVINO and another backend, and translate them as partial graphs, without the compiled model cache. By default every graph is treated as a complete model graph. Cannot be used with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY`. | +| `GGML_OPENVINO_ROPE_F32_ANGLE` | GPU | Boolean | `0` | Keep the RoPE angle in f32 under the f16 hint, for long prompts. Validated on one model. On CPU, `test-backend-ops -o ROPE` fails with it. | | `GGML_OPENVINO_NATIVE_SOFTPLUS` | all | Boolean | `0` | Translate `SOFTPLUS` to the OpenVINO `SoftPlus` op instead of the default `relu(x) + log(1 + exp(-abs(x)))`. | | `GGML_OPENVINO_KV_SCATTER_ELEMENTS` | all | Boolean | `0` | Use `ScatterElementsUpdate` instead of `ScatterUpdate` for single-row KV writes in stateless execution. | | `GGML_OPENVINO_ENABLE_KV_4D` | GPU | Boolean | `0` | Bind the KV cache as `[1, ctx, n_heads_kv, head_size]`, so the GPU plugin can update and read it in place. Needs an OpenVINO build newer than 2026.4.1; do not use it with 2026.4.1. | diff --git a/ggml/src/ggml-openvino/device/npu_quant_policy.cpp b/ggml/src/ggml-openvino/device/npu_quant_policy.cpp index 1f7343bba4c2..d29175ab0524 100644 --- a/ggml/src/ggml-openvino/device/npu_quant_policy.cpp +++ b/ggml/src/ggml-openvino/device/npu_quant_policy.cpp @@ -45,6 +45,10 @@ std::optional ggml_openvino_npu_token_embd_requant_type(const gg } std::optional ggml_openvino_npu_weight_requant_type(const ggml_tensor * tensor) { - GGML_UNUSED(tensor); - return ggml_openvino_get_npu_requant_type(); + const ExtraQuantType type = ggml_openvino_get_npu_requant_type(); + // a group must fit within a row + if (type == ExtraQuantType::Q4_0_128 && tensor->ne[0] % 128 != 0) { + return ExtraQuantType::Q4_0_C; + } + return type; } diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 519c35bc21a1..a9fac74b1ea1 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -9,9 +9,11 @@ #include #include +#include #include #include #include +#include #include #include #include @@ -31,10 +33,27 @@ #include #include #include -#include #include #include +static std::set collect_graph_output_names(const ggml_cgraph * cgraph) { + std::set outputs; + for (int node_n = 0; node_n < cgraph->n_nodes; node_n++) { + auto * node = cgraph->nodes[node_n]; + if (node->flags & GGML_TENSOR_FLAG_OUTPUT) { + outputs.insert(node->name); + } + } + return outputs; +} + +bool GgmlOvDecoder::has_same_graph_io(const ggml_cgraph * cgraph) const { + if (m_built_output_names.empty()) { + return true; // no snapshot (naive / test decoders): nothing to compare against + } + return collect_graph_output_names(cgraph) == m_built_output_names; +} + GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph, ModelParams & model_params, ComputeParams & compute_params, @@ -64,6 +83,8 @@ GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph, validate_cgraph(); + m_built_output_names = collect_graph_output_names(cgraph); + set_input_output(); compute_node_dynamic_dims(); compute_model_inputs(); @@ -79,6 +100,7 @@ GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph, void GgmlOvDecoder::update_io(ggml_cgraph * cgraph) { m_cgraph = cgraph; + m_built_output_names = collect_graph_output_names(cgraph); m_model_inputs.clear(); m_model_outputs.clear(); m_node_info_list.clear(); @@ -694,45 +716,6 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { op_case = 1; break; } - if (node->src[0]->op == GGML_OP_VIEW) { - auto * src = node->src[0]; - if (ggml_nelements(node) != ggml_nelements(src)) { - // throw std::runtime_error("Unsupported VIEW case"); - } - op_case = 0; - if (m_model_is_splitted && m_model_inputs.find(get_tensor_ov_name(m_cgraph, src)) != m_model_inputs.end()) { - op_case = 0; - } - } - { - auto * src = node->src[0]; - if (ggml_nelements(node) != ggml_nelements(src)) { - // Case 4: select one slice on src dim1 (via view offset), keep src dim2 as output dim1. - // Typical pattern: - // src: ne=[N, M, K, 1], nb=[b0, b1, b2, b3] - // dst: ne=[N, K, 1, 1], nb=[b0, b2, b3, b3] - if (node->ne[0] == src->ne[0] && node->ne[1] == src->ne[2] && node->ne[2] == 1 && - node->nb[0] == src->nb[0] && node->nb[1] == src->nb[2] && src->ne[1] > 1) { - op_case = 0; - break; - } - - // General case 3: shape differs from source (one or more dims) and is handled as VIEW slicing. - int diff_count = 0; - for (int i = 0; i < GGML_MAX_DIMS; i++) { - if (node->ne[i] != src->ne[i]) { - diff_count++; - } - // if node ne[i] > src ne[i], case = 0 - if (node->ne[i] > src->ne[i]) { - return 0; - } - } - if (diff_count >= 1) { - op_case = 0; - } - } - } break; } case GGML_OP_RMS_NORM: { @@ -744,7 +727,8 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { // pre-scaled, and the norm then scales its eps to match; 4: it is not. op_case = is_gdn_out_prescaled(node->src[0]->src[0]) ? 3 : 4; } else if (node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) { - op_case = is_gdn_out_prescaled(node->src[0]->src[0]) ? 3 : 2; + // packed [attn | state] output, sliced by the norm. 5: pre-scaled, as in 3; 2: not. + op_case = is_gdn_out_prescaled(node->src[0]->src[0]) ? 5 : 2; } } break; @@ -897,13 +881,10 @@ std::optional extract_layer_from_name(const std::string & name) { return std::nullopt; } pos1 += 2; - size_t pos2 = name.find(' ', pos1); - if (pos2 == std::string::npos) { - pos2 = name.length(); + if (pos1 >= name.size() || !std::isdigit(static_cast(name[pos1]))) { + return std::nullopt; } - std::string layer_str = name.substr(pos1, pos2 - pos1); - int layer = std::stoi(layer_str); - return layer; + return std::stoi(name.substr(pos1)); } // Recover the sliding window width from ggml's own SWA mask. llama.cpp never passes n_swa to a @@ -1202,7 +1183,11 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr } ggml_tensor * cache_k = cache_k_view->src[0]; - int layer = extract_layer_from_name(cache_k->name).value(); + const auto layer_opt = extract_layer_from_name(cache_k->name); + if (!layer_opt) { + continue; + } + const int layer = *layer_opt; // Classified by the pre-pass above, which groups layers by mask tensor identity. The // mask NAME cannot be used: build_attn_inp_kq_mask() gives both masks the same name. @@ -1372,7 +1357,9 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback; } if (is_conv || is_gdn) { - compute_params.s_copy_active_slot_len = (int) dest_view->ne[1]; + // One cache row per active sequence: [conv_state_size, n_seqs] (qwen35) or, with the q/k/v conv + // states packed in one row, [d_conv - 1, d_inner, n_seqs] (bailingmoe3), so count the rows spanned. + compute_params.s_copy_active_slot_len = (int) ((ggml_nbytes(dest_view) + row_bytes - 1) / row_bytes); } } } @@ -1573,7 +1560,10 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op, else { input_shape = ov::PartialShape{get_shape(input)}; } - if (dynamic_dim_index != -1 && m_model_is_splitted) { + // A static graph (NPU) keeps the fixed token count set above; only a split static graph, whose parts are + // fed by other backends, marks the dimension dynamic. Without this the token dimension of inp_tokens becomes + // dynamic in the NPU graph (and, for example, the GATED_DELTA_NET pad masking fails). + if (dynamic_dim_index != -1 && (!m_is_static || m_model_is_splitted)) { input_shape[3 - dynamic_dim_index] = -1; } if (op->op == GGML_OP_SOFT_MAX && op->src[1] != nullptr && op->src[1]->op == GGML_OP_NONE && @@ -1985,7 +1975,9 @@ void GgmlOvDecoder::compute_model_outputs() { } } } - if (input_use_count == cur_node_use_count) { + // op tests (the naive path) can read any node of the graph, e.g. the intermediate sum of a fused + // ADD + RMS_NORM + MUL, so every non-in-place node is a model output there + if (input_use_count == cur_node_use_count && (!m_naive || ::is_inplace_op(cur_node))) { cur_node = nullptr; } } @@ -2774,11 +2766,14 @@ size_t GgmlOvDecoder::get_output_op_offset(int node_idx) const { } void GgmlOvDecoder::visit_subgraph(std::function, int node_idx)> node_visitor) const { + // One copy for the whole walk: translators only read the decoder, and a copy per node costs a full + // copy of the node list for every node. + auto decoder = std::make_shared(*this); for (int node_idx = 0; node_idx < m_cgraph->n_nodes; node_idx++) { if (m_cgraph->nodes[node_idx]->op == GGML_OP_NONE) { continue; } - node_visitor(std::make_shared(*this), node_idx); + node_visitor(decoder, node_idx); } } @@ -2851,6 +2846,10 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { m_node_dynamic_dims[src] = 1; continue; } + if (is_inp_embd_2d(src, node)) { + m_node_dynamic_dims[src] = 1; + continue; + } self(self, src); } } @@ -2921,10 +2920,22 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { m_node_dynamic_dims[node] = node->view_offs == 0 ? 2 : -1; break; } + + // A VIEW that does not change the shape is a pass-through for dynamic-dim purposes. + if (is_same_shape(node->src[0], node)) { + m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[0]]; + break; + } // Use stride-based matching: the stride of a VIEW dimension directly // encodes which source dimension it indexes into, so it uniquely // identifies the dynamic dim even when two dims share the same size. m_node_dynamic_dims[node] = -1; + if (!m_model_params.has_rs_rollback && node->src[0]->op == GGML_OP_GATED_DELTA_NET) { + // The GDN translator publishes attention [S_v, H_v, n_tokens, n_seqs] and state directly under these + // VIEW names (get_output_names), not the packed [attention | state] the strides describe. + m_node_dynamic_dims[node] = node->view_offs == 0 ? 2 : -1; + break; + } if (m_node_dynamic_dims[node->src[0]] != -1) { auto dynamic_dim_idx = m_node_dynamic_dims[node->src[0]]; auto dynamic_dim_value = node->src[0]->ne[dynamic_dim_idx]; diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index 12b08cebce4b..39b3496e5669 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -458,6 +458,11 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { void update_io(ggml_cgraph * cgraph); bool is_bound_to(const ggml_cgraph * cgraph) const; + // Was this decoder built for a graph with the same OUTPUT set as `cgraph`? The cache key is + // only (n_nodes, first/last node name), which cannot see a change in which tensors are marked + // as outputs, and the compiled model's Results are fixed at compile time. + bool has_same_graph_io(const ggml_cgraph * cgraph) const; + static bool is_inp_tok(const ggml_tensor * tensor, const ggml_tensor * op) { return op->op == GGML_OP_GET_ROWS && tensor == op->src[1] && op->src[0]->op == GGML_OP_NONE; } @@ -501,6 +506,16 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { (tensor->op == GGML_OP_NONE || tensor->op == GGML_OP_CPY); } + // A 2-D float graph input feeding a matmul as src[1]. Speculative decoding hands the draft the + // target's hidden features this way ([n_embd, n_tokens], with no GET_ROWS lookup, so none of the + // other seeds match it) and the token count differs between the prompt pass and the shorter + // draft blocks, so its token dim must stay dynamic. + static bool is_inp_embd_2d(const ggml_tensor * tensor, const ggml_tensor * op) { + return (tensor->flags & GGML_TENSOR_FLAG_INPUT) && tensor->op == GGML_OP_NONE && + tensor->type == GGML_TYPE_F32 && tensor->ne[2] == 1 && tensor->ne[3] == 1 && + op->op == GGML_OP_MUL_MAT && tensor == op->src[1]; + } + static bool is_inp_mask(const ggml_tensor * tensor, const ggml_tensor * op) { return op->op == GGML_OP_CPY || (op->op == GGML_OP_FLASH_ATTN_EXT && tensor == op->src[3]) || (op->op == GGML_OP_SOFT_MAX && tensor == op->src[1]); @@ -759,6 +774,8 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { std::map> m_model_weights; std::map m_model_outputs; std::set m_model_output_names; + // The output set the compiled model was built from, for has_same_graph_io(). + std::set m_built_output_names; std::vector m_node_info_list; std::map m_node_dynamic_dims; std::set m_kvcache_4d; diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index 2537f8af3a31..7e6711dd88a0 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -179,6 +179,9 @@ constexpr env_var env_vars[] = { {"GGML_OPENVINO_RELEASE_WEIGHTS", env_type::BOOL}, {"GGML_OPENVINO_REDUCE_COMPILE_MEM", env_type::BOOL}, {"GGML_OPENVINO_LOG_UNSUPPORTED_OPS", env_type::BOOL}, + {"GGML_OPENVINO_LOG_SUPPORTS_OP", env_type::INT}, + {"GGML_OPENVINO_DIAG_GRAPH_IO", env_type::BOOL}, + {"GGML_OPENVINO_ROPE_F32_ANGLE", env_type::BOOL}, {"GGML_OPENVINO_LOG_SWA_LAYERS", env_type::BOOL}, {"GGML_OPENVINO_NATIVE_SOFTPLUS", env_type::BOOL}, {"GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS", env_type::BOOL}, @@ -543,6 +546,14 @@ std::string ggml_openvino_config_overrides_in_use() { return value ? std::string(name) + "=" + value : std::string(); } +bool ggml_openvino_manual_gqa_enabled() { + // set: a positive value enables it, 0 disables it; unset: on GPU only + if (ggml_openvino_getenv_str("GGML_OPENVINO_MANUAL_GQA_ATTN") != nullptr) { + return ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0; + } + return ggml_openvino_is_gpu(); +} + bool ggml_openvino_gdn_prescale_enabled() { // float value, so not getenv_int: "64.0" must enable it. Unset means on. const char * v = ggml_openvino_getenv_str("GGML_OPENVINO_GDN_Q_SCALE", nullptr); @@ -997,6 +1008,10 @@ std::optional ggml_openvino_get_requant_type(const ggml_tensor * const bool sym128_all = is_opt("q4_sym128_all"); const bool asym64_all = is_opt("q4_asym64_all"); const bool asym64 = is_opt("q4_asym64"); + // A group of 64 must fit within each row; other widths keep channel-wise INT8. + auto group64 = [tensor](ExtraQuantType type) { + return tensor->ne[0] % 64 == 0 ? type : ExtraQuantType::Q8_0_C; + }; // TODO: temporary workaround for slow GPU-plugin GatherMatmul prefill above 16 tokens. // Q4_1_64 experts let the plugin fuse the MoE into MOECompressed. @@ -1021,8 +1036,7 @@ std::optional ggml_openvino_get_requant_type(const ggml_tensor * return tensor->ne[0] % 64 == 0 ? ExtraQuantType::Q4_1_64 : ExtraQuantType::Q8_0_C; } if (tensor->type == GGML_TYPE_Q5_0) { - //return ExtraQuantType::Q4_0_128; - return ExtraQuantType::Q4_0_64; + return group64(ExtraQuantType::Q4_0_64); } // MoE expert weights (3D, ne[2] = n_expert) stored as Q5_1/Q8_0 are the expert-side // equivalent of Q6_K/Q5_K: kept at 8 bits by default while the rest of the model is at 4 @@ -1031,10 +1045,10 @@ std::optional ggml_openvino_get_requant_type(const ggml_tensor * // (704/64 = 11) and 128 does not. if (tensor->ne[2] > 1 && (tensor->type == GGML_TYPE_Q5_1 || tensor->type == GGML_TYPE_Q8_0)) { if (sym128 || sym128_all) { - return ExtraQuantType::Q4_0_64; + return group64(ExtraQuantType::Q4_0_64); } if (asym64 || asym64_all) { - return ExtraQuantType::Q4_1_64; + return group64(ExtraQuantType::Q4_1_64); } // TODO: temporary workaround for a known OpenVINO GPU-plugin bug -- remove once the // plugin computes grouped 8-bit GatherMatmulCompressed correctly. This costs accuracy @@ -1049,7 +1063,7 @@ std::optional ggml_openvino_get_requant_type(const ggml_tensor * // avoids the broken layout and restores correct output. // Opt out with GGML_OPENVINO_REQUANT_KQUANT=native. if (ggml_openvino_is_gpu() && !is_opt("native")) { - return ExtraQuantType::Q4_0_64; + return group64(ExtraQuantType::Q4_0_64); } } switch (tensor->type) { diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h index 406ac6d4cb5a..ca3227a41aab 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.h +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h @@ -206,6 +206,9 @@ bool ggml_openvino_is_gpu(); // Read n_seq_active and attention_size(_swa) from the KQ mask shape (off with GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK=1) bool ggml_openvino_shape_from_mask_enabled(); +// Manual GQA attention instead of SDPA (GGML_OPENVINO_MANUAL_GQA_ATTN, on GPU by default) +bool ggml_openvino_manual_gqa_enabled(); + // GDN q pre-scale for eligible graphs on the NPU static path. On by default; // GGML_OPENVINO_GDN_Q_SCALE=0 (or a negative or non-numeric value) turns it off. bool ggml_openvino_gdn_prescale_enabled(); @@ -242,6 +245,7 @@ size_t ggml_openvino_max_alloc_size(const std::string & device); // release: madvise(MADV_DONTNEED) all registered buffers, dropping their RSS. // released: true once release has run (used to fail-fast on post-release recompile). void ggml_openvino_register_weight_buffer(void * data, size_t size); +void ggml_openvino_unregister_weight_buffer(const void * data); void ggml_openvino_release_weight_buffers(); bool ggml_openvino_weight_buffers_released(); diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index bd49560d8e1e..b331349d1262 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -99,14 +100,20 @@ struct ggml_backend_openvino_buffer_context { // Used for re-allocation on device for kvcache void * data_prev = nullptr; + // data is in the weight buffer registry + bool weight_registered = false; + + // One counter for both constructors: the id is part of the weight identity in the graph key, so a host-pointer + // buffer and an allocated buffer must never share one. + static size_t next_buffer_id() { + static std::atomic next_id{1}; + return next_id.fetch_add(1); + } ggml_backend_openvino_buffer_context(int device, void * external_data, size_t size) : device(device), name(std::string(GGML_OPENVINO_NAME) + std::to_string(device)), - id([]() { - static std::atomic next_id{1}; - return next_id.fetch_add(1); - }()), + id(next_buffer_id()), data(external_data), size(size), is_remote(false), @@ -117,10 +124,7 @@ struct ggml_backend_openvino_buffer_context { ggml_backend_openvino_buffer_context(int device, size_t size, bool is_remote = false, bool lazy = false) : device(device), name(std::string(GGML_OPENVINO_NAME) + std::to_string(device)), - id([]() { - static std::atomic next_id{1}; - return next_id.fetch_add(1); - }()), + id(next_buffer_id()), data(nullptr), size(size), is_remote(is_remote) { @@ -260,6 +264,10 @@ struct ggml_backend_openvino_buffer_context { delete pair.second; } tensor_extras.clear(); + // a later release must not madvise memory this buffer no longer owns + if (weight_registered) { + ggml_openvino_unregister_weight_buffer(data); + } if (kv_on_demand) { ggml_openvino_kv_storage_unregister(data, size); } @@ -321,6 +329,17 @@ void ggml_openvino_register_weight_buffer(void * data, size_t size) { reg.buffers.emplace_back(data, size); } +void ggml_openvino_unregister_weight_buffer(const void * data) { + if (data == nullptr) { + return; + } + auto & reg = ov_weight_registry(); + std::lock_guard lock(reg.mutex); + reg.buffers.erase(std::remove_if(reg.buffers.begin(), reg.buffers.end(), + [data](const std::pair & b) { return b.first == data; }), + reg.buffers.end()); +} + bool ggml_openvino_weight_buffers_released() { auto & reg = ov_weight_registry(); std::lock_guard lock(reg.mutex); @@ -378,21 +397,53 @@ static bool is_self_contained_mmap_enabled() { ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR"); } +// Stores extra as the tensor's extra, deleting the one it replaces +static void ggml_openvino_set_extra(ggml_backend_openvino_buffer_context * ctx, + ggml_tensor * tensor, + ggml_openvino_extra_base * extra) { + auto it = ctx->tensor_extras.find(tensor); + if (it != ctx->tensor_extras.end() && it->second != extra) { + delete it->second; + } + ctx->tensor_extras[tensor] = extra; + tensor->extra = extra; +} + +// Replaces the buffer's context with a new allocation of the same size and moves tensor->data to it. The old +// allocation is freed first, so the two never take memory at the same time. Returns false when the new +// allocation fails. +static bool ggml_openvino_swap_buffer_context(ggml_backend_buffer_t buffer, + ggml_backend_openvino_buffer_context *& ctx, + ggml_tensor * tensor, + bool is_remote, + bool lazy) { + const int device = ctx->device; + const size_t size = ctx->size; + const size_t offset = (char *) tensor->data - (char *) ctx->data; + delete ctx; + ctx = new ggml_backend_openvino_buffer_context(device, size, is_remote, lazy); + buffer->context = ctx; + if (ctx->data == nullptr) { + return false; + } + tensor->data = (char *) ctx->data + offset; + return true; +} + static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) { // GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name); ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context; - // Put kvcache on device memory for GPU (NPU memory is too small even for kvcache) - if (strncmp(tensor->name, "cache_", 6) == 0 && !ctx->is_remote && ggml_openvino_is_gpu() && - !is_stateful_enabled()) { + // Put kvcache on device memory for GPU (NPU memory is too small even for kvcache). Same for the speculative + // decoding feature buffers (llama_context::layer_inp_dev / h_nextn_dev): every graph reads or writes the whole + // buffer, so in host memory the plugin copies it to the device and back on every inference. + const bool is_device_state = strncmp(tensor->name, "cache_", 6) == 0 || + strcmp(tensor->name, "layer_inp_dev") == 0 || strcmp(tensor->name, "h_nextn_dev") == 0; + if (is_device_state && !ctx->is_remote && ggml_openvino_is_gpu() && !is_stateful_enabled()) { GGML_ASSERT(ctx->tensor_extras.empty()); - auto device = ctx->device; - auto size = ctx->size; - auto * data_prev = ctx->data; - delete ctx; - ctx = new ggml_backend_openvino_buffer_context(device, size, true); - buffer->context = ctx; - tensor->data = (char *) ctx->data + ((char *) tensor->data - (char *) data_prev); + if (!ggml_openvino_swap_buffer_context(buffer, ctx, tensor, true, false)) { + return GGML_STATUS_ALLOC_FAILED; + } } // On-demand NPU KV: swap the eagerly committed buffer for demand-zero memory at its first KV tensor @@ -401,14 +452,10 @@ static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_bu if (is_kv_tensor && tensor->view_src == nullptr && !ctx->is_remote && ggml_openvino_npu_kv_on_demand_enabled() && tensor->ne[2] == 1 && tensor->ne[3] == 1 && tensor->nb[1] == ggml_row_size(tensor->type, tensor->ne[0])) { if (!ctx->kv_on_demand && ctx->tensor_extras.empty() && tensor->data == ctx->data) { - auto device = ctx->device; - auto size = ctx->size; - auto * data_prev = ctx->data; - delete ctx; - ctx = new ggml_backend_openvino_buffer_context(device, size, false, true); + if (!ggml_openvino_swap_buffer_context(buffer, ctx, tensor, false, true)) { + return GGML_STATUS_ALLOC_FAILED; + } ctx->kv_on_demand = true; - buffer->context = ctx; - tensor->data = (char *) ctx->data + ((char *) tensor->data - (char *) data_prev); } if (ctx->kv_on_demand) { ggml_openvino_kv_storage_register(tensor->data, tensor->nb[1], tensor->ne[1]); @@ -431,12 +478,7 @@ static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_bu if (ggml_openvino_tensor_extra * extra = ggml_openvino_create_tensor_extra(tensor, ctx->is_remote, ggml_openvino_get_available_devices()[ctx->device])) { - auto it = ctx->tensor_extras.find(tensor); - if (it != ctx->tensor_extras.end()) { - delete it->second; - } - ctx->tensor_extras[tensor] = extra; - tensor->extra = extra; + ggml_openvino_set_extra(ctx, tensor, extra); return GGML_STATUS_SUCCESS; } } @@ -451,12 +493,7 @@ static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_bu ggml_openvino_tensor_extra * extra = ggml_openvino_create_tensor_extra( tensor, ctx->is_remote, ggml_openvino_get_available_devices()[ctx->device]); if (extra != nullptr) { - auto it = ctx->tensor_extras.find(tensor); - if (it != ctx->tensor_extras.end()) { - delete it->second; - } - ctx->tensor_extras[tensor] = extra; - tensor->extra = extra; + ggml_openvino_set_extra(ctx, tensor, extra); } } @@ -644,8 +681,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer // } } - ctx->tensor_extras[tensor] = extra; - tensor->extra = extra; + ggml_openvino_set_extra(ctx, tensor, extra); // Register the host buffer so its pages can be dropped after the GPU // plugin has its own device copy (GGML_OPENVINO_RELEASE_WEIGHTS). @@ -661,6 +697,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer "multi-model runs."); } ggml_openvino_register_weight_buffer(ctx->data, ctx->size); + ctx->weight_registered = true; } if (!ctx->external_memory) { @@ -700,12 +737,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer return; } - auto it = ctx->tensor_extras.find(tensor); - if (it != ctx->tensor_extras.end()) { - delete it->second; - } - ctx->tensor_extras[tensor] = extra; - tensor->extra = extra; + ggml_openvino_set_extra(ctx, tensor, extra); } } @@ -1087,15 +1119,8 @@ void ggml_openvino_buffer_register_extra(ggml_tensor * tensor, ggml_openvino_ext GGML_ASSERT(tensor->buffer != nullptr); GGML_ASSERT(ggml_backend_buffer_is_openvino(tensor->buffer)); - auto * ctx = static_cast(tensor->buffer->context); - - auto it = ctx->tensor_extras.find(tensor); - if (it != ctx->tensor_extras.end()) { - delete it->second; - } - - ctx->tensor_extras[tensor] = extra; - tensor->extra = extra; + ggml_openvino_set_extra(static_cast(tensor->buffer->context), tensor, + extra); } bool ggml_backend_buft_is_openvino(ggml_backend_buffer_type_t buft) { @@ -1837,7 +1862,7 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { case GGML_OP_DIV: { // The GPU plugin can fuse broadcast DIV into the preceding FFN GEMM path // and produce infs for per-channel scale vectors. Keep those DIVs on CPU - // until the fused GPU kernel is reliable. (falied case llama-arch-test mpt) + // until the fused GPU kernel is reliable (failing case: test-llama-archs, mpt). // Only a weight divisor is such a scale; at one token an activation divisor has the same shape // (qwen2moe's shared-expert sigmoid, silu(x) / x). if (ggml_openvino_is_gpu() && op->src[1]->ne[0] == op->ne[0] && @@ -1898,11 +1923,10 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { memcpy(&max_bias, (const float *) op_params + 1, sizeof(float)); memcpy(&logit_softcap, (const float *) op_params + 2, sizeof(float)); - // Keep gemma3n flash-attn pattern on CPU for GPU runs to avoid - // accuracy drift in the OpenVINO path. Restrict by scale=1.0 to avoid - // affecting non-gemma3n models such as Llama-3.2. + // Keep gemma3n flash-attn pattern on CPU to avoid accuracy drift in the OpenVINO path. + // Restrict by scale=1.0 to avoid affecting non-gemma3n models such as Llama-3.2. if (fabsf(scale - 1.0f) < 1e-6f && is_gemma3n_flash_attn_pattern(op)) { - return {false, "FLASH_ATTN_EXT gemma3n pattern on GPU is not supported"}; + return {false, "FLASH_ATTN_EXT gemma3n pattern is not supported"}; } // K/V row lists (ggml_flash_attn_ext_rows) are not supported @@ -1948,7 +1972,7 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { return {false, "CPY with BF16 src[1] type is not supported"}; } if (ggml_openvino_is_npu() && (op->src[0]->type == GGML_TYPE_BF16 || op->src[1]->type == GGML_TYPE_BF16)) { - return {false, "CPY with BF16 is not supported is not supported on NPU"}; + return {false, "CPY with BF16 is not supported on NPU"}; } // CPY to a quantized destination (e.g. f32 -> q4_0) is numerically unstable with OpenVINO backend. if (ggml_is_quantized(op->type)) { @@ -2063,12 +2087,15 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { // return true; // } const char * reason = nullptr; - if (op->src[2]->op == GGML_OP_PERMUTE) { + // a VIEW of the PERMUTE (v with padded heads) is still a permuted v + const ggml_tensor * v_src = op->src[2]->op == GGML_OP_VIEW ? op->src[2]->src[0] : op->src[2]; + if (v_src->op == GGML_OP_PERMUTE) { reason = "GATED_DELTA_NET with PERMUTE src2 is not supported"; } - else if (op->src[3]->ne[0] != 1) { - // kda (per-key-dimension gating) not supported by fused GatedDeltaNet op - reason = "GATED_DELTA_NET with kda (per-key-dimension gating) is not supported"; + else if (op->src[3]->ne[0] != 1 && (op->op_params[0] > 1 || ggml_openvino_gdn_native_state_enabled()) && + !ov::frontend::ggml::op::gdn_per_key_gate_supported()) { + reason = "GATED_DELTA_NET with a per-key gate needs an OpenVINO GatedDeltaNet with a rank-4 gate for state " + "snapshots or the native state layout"; } else if (op->op_params[0] > 1) { if (ggml_openvino_is_static()) { @@ -2084,12 +2111,6 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { } break; } - case GGML_OP_SSM_CONV: { - // qwen3next is numerically unstable with OpenVINO SSM_CONV. - // Keep this op on CPU until the OpenVINO implementation is fixed. - // return true; - break; - } case GGML_OP_SSM_SCAN: { // SelectiveSSM implements the Mamba-2 recurrence: scalar decay per head, one final state if (op->src[3]->ne[0] != 1) { @@ -2292,9 +2313,6 @@ static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(gg if (!supported) { return {false, "GLU op " + std::string(ggml_glu_op_name(ggml_get_glu_op(op))) + " has no op translator"}; } - // if (has_view_op_input(op)) { - // return {false, "GLU op " + std::string(ggml_glu_op_name(ggml_get_glu_op(op))) + " with view input is not supported"}; - // } if (op->src[1] == nullptr && op->src[0]->ne[0] % 2 != 0) { // triggers bug in ov gpu return {false, "GLU op with odd src0 ne[0] and null src1 is not supported"}; @@ -2347,16 +2365,114 @@ static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(gg return {true, ""}; } +// Report what supports_op() accepts and rejects, so a graph that silently falls back to another +// backend can be diagnosed. Every op rejected here becomes a graph split; if nothing is rejected, +// the whole graph runs on OpenVINO. +// +// Gated by GGML_OPENVINO_LOG_SUPPORTS_OP: +// 1 one summary at exit listing every distinct op kind and verdict -- start here +// 2 additionally log every individual call, with the tensor name and shape +// +// This wraps the decision function instead of instrumenting it, so all of its return paths are +// covered -- including the several that reject without logging a reason of their own, and any +// added later. +// +// The summary is reported at exit rather than on each op's first occurrence, because the earliest +// calls happen before the log handler emits anything: with level 2 the first line to actually +// appear already reads "call 1244". A first-occurrence line would therefore be silently dropped +// for exactly the ops that are only ever seen early. Counting is unaffected, so the summary is the +// reliable view; treat the level-2 stream as a sample, not a complete trace. +namespace { + +struct supports_op_tally { + std::mutex mutex; + // key: ":ok" / ":no" -> number of calls + std::map counts; + + // Report totals once, at exit. Registered lazily so a run with the knob off costs nothing. + // atexit runs while the ggml log callback is still valid, which static destruction does not + // guarantee. + void arm_summary() { + static std::once_flag armed; + std::call_once(armed, [] { + std::atexit([] { + auto & self = instance(); + std::lock_guard lock(self.mutex); + + size_t n_accept_kinds = 0; + size_t n_reject_kinds = 0; + GGML_LOG_WARN("ov-supports-op: ---- summary (distinct op kinds, with call counts) ----\n"); + for (const auto & [key, count] : self.counts) { + const bool ok = key.size() > 3 && key.compare(key.size() - 3, 3, ":ok") == 0; + ok ? ++n_accept_kinds : ++n_reject_kinds; + GGML_LOG_WARN("ov-supports-op: %-8s %-24s %zu call(s)\n", ok ? "ACCEPT" : "REJECT", + key.substr(0, key.size() - 3).c_str(), count); + } + if (n_reject_kinds == 0) { + GGML_LOG_WARN("ov-supports-op: %zu op kind(s) accepted, 0 rejected" + " -- every op was supported, so no split originated here\n", + n_accept_kinds); + } else { + GGML_LOG_WARN("ov-supports-op: %zu op kind(s) accepted, %zu REJECTED" + " -- each rejected kind forces a graph split\n", + n_accept_kinds, n_reject_kinds); + } + }); + }); + } + + static supports_op_tally & instance() { + static supports_op_tally tally; + return tally; + } +}; + +} // namespace + static bool ggml_backend_openvino_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) { auto res = ggml_backend_openvino_device_supports_op_impl(dev, op); - if (!res.is_supported) { + const bool supported = res.is_supported; + if (!supported) { static const bool log_unsupported = ggml_openvino_getenv_int("GGML_OPENVINO_LOG_UNSUPPORTED_OPS") != 0; if (log_unsupported) { GGML_LOG_WARN("OpenVINO op unsupported: op '%s' (%s), type %s: %s\n", op->name, ggml_op_name(op->op), ggml_type_name(op->type), res.reason.c_str()); } } - return res.is_supported; + + static const int log_level = ggml_openvino_getenv_int("GGML_OPENVINO_LOG_SUPPORTS_OP"); + if (log_level <= 0) { + return supported; + } + + // Name the op the way ggml does: UNARY and GLU carry their real identity in a sub-enum, so + // logging only "UNARY" would merge SILU with everything else. + std::string op_desc = ggml_op_name(op->op); + if (op->op == GGML_OP_UNARY) { + op_desc += std::string("/") + ggml_unary_op_name(ggml_get_unary_op(op)); + } else if (op->op == GGML_OP_GLU) { + op_desc += std::string("/") + ggml_glu_op_name(ggml_get_glu_op(op)); + } + + // The scheduler calls supports_op() on every graph build and may do so from several threads, + // so the tally needs a lock. Keyed on op identity *and* verdict, because the same op can be + // accepted at one shape and rejected at another (e.g. a quantized 3-D src). + auto & tally = supports_op_tally::instance(); + tally.arm_summary(); + + size_t count; + { + std::lock_guard lock(tally.mutex); + count = ++tally.counts[op_desc + (supported ? ":ok" : ":no")]; + } + + if (log_level >= 2) { + GGML_LOG_WARN("ov-supports-op: %-6s %-22s name='%s' type=%s ne=[%ld,%ld,%ld,%ld] (call %zu)\n", + supported ? "ACCEPT" : "REJECT", op_desc.c_str(), op->name, ggml_type_name(op->type), + (long) op->ne[0], (long) op->ne[1], (long) op->ne[2], (long) op->ne[3], count); + } + + return supported; } static bool ggml_backend_openvino_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) { diff --git a/ggml/src/ggml-openvino/ggml-quants.cpp b/ggml/src/ggml-openvino/ggml-quants.cpp index 96b8da9be795..0c0501fec69e 100644 --- a/ggml/src/ggml-openvino/ggml-quants.cpp +++ b/ggml/src/ggml-openvino/ggml-quants.cpp @@ -154,19 +154,22 @@ void extract_q4_1_data(const ggml_tensor * tensor, }); } else { auto * zp = static_cast(zp_arr.data()); - ov::parallel_for(scales_arr.get_size(), [&](size_t i) { - float scale = static_cast(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block)))); - float min = static_cast(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block + 2)))); - scales[i] = ov::float16(scale); - // zp = -min / scale (bias = min, so zp = -bias/scale) - uint8_t zp_val = (scale != 0.0f) ? (uint8_t) std::round(-min / scale) : 0; - // Pack two 4-bit zero points per byte - if (i % 2 == 0) { - zp[i / 2] = zp_val & 0x0F; // Lower nibble - } else { - zp[i / 2] |= (zp_val << 4); // Upper nibble + const size_t n_blocks = scales_arr.get_size(); + // One iteration per zero point byte: the two blocks that share a byte are packed together, so no two + // threads write the same byte. + ov::parallel_for((n_blocks + 1) / 2, [&](size_t pair) { + uint8_t packed = 0; + for (size_t i = 2 * pair; i < std::min(2 * pair + 2, n_blocks); i++) { + float scale = static_cast(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block)))); + float min = + static_cast(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block + 2)))); + scales[i] = ov::float16(scale); + // zp = -min / scale (bias = min, so zp = -bias/scale), in the u4 range + const uint8_t zp_val = (scale != 0.0f) ? (uint8_t) std::clamp(std::lround(-min / scale), 0L, 15L) : 0; + packed |= (i % 2 == 0) ? zp_val : (uint8_t) (zp_val << 4); + unpack_32_4(data + i * bytes_per_block + 4, weights + i * 16); } - unpack_32_4(data + i * bytes_per_block + 4, weights + i * 16); + zp[pair] = packed; }); } } @@ -259,7 +262,7 @@ void extract_q5_1_data(const ggml_tensor * tensor, float min = static_cast(ov::float16::from_bits(read_u16(block + 2))); scales[i] = ov::float16(scale); // zp = -min / scale (dequant: (w - zp) * s == w*s + min) - zp[i] = (scale != 0.0f) ? (uint8_t) std::lround(-min / scale) : 0; + zp[i] = (scale != 0.0f) ? (uint8_t) std::clamp(std::lround(-min / scale), 0L, 255L) : 0; unpack_block(block, weights + i * qk); }); } @@ -378,7 +381,9 @@ void extract_q4_k_data(const ggml_tensor * tensor, bias_f16[i * 8 + j] = ov::float16(-min_vals[j]); } else { // zp = min / scale (since bias = -min and zp = -bias/scale) - uint8_t zp_val = (scale_vals[j] != 0.0f) ? (uint8_t) std::round(min_vals[j] / scale_vals[j]) : 0; + uint8_t zp_val = (scale_vals[j] != 0.0f) ? + (uint8_t) std::clamp(std::lround(min_vals[j] / scale_vals[j]), 0L, 15L) : + 0; // Pack two 4-bit zero points per byte size_t idx = i * 8 + j; if (idx % 2 == 0) { diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp index 7bfa7ad08b11..d35168750da8 100644 --- a/ggml/src/ggml-openvino/model-cache.cpp +++ b/ggml/src/ggml-openvino/model-cache.cpp @@ -186,6 +186,7 @@ static const char * cache_settings[] = { "GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK", "GGML_OPENVINO_KV_SCATTER_ELEMENTS", "GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN", + "GGML_OPENVINO_ROPE_F32_ANGLE", }; void ggml_openvino_model_cache_init() { @@ -368,7 +369,8 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph, // Version 6 clears recurrent-cache slots with Select, so a NaN in a cleared slot does not survive. // Version 7 reads ROPE frequency factors named other than rope_freqs.weight as a Constant, not a Parameter. // Version 8 drops result_norm from the outputs when it has a consumer, and hashes the output flags. - h = fnv1a_u64(h, 8); + // Version 9 hashes GGML_OPENVINO_ROPE_F32_ANGLE, which became opt-in. + h = fnv1a_u64(h, 9); h = fnv1a(h, graph_signature.data(), graph_signature.size()); for (const char * name : cache_settings) { const char * value = ggml_openvino_getenv_str(name, ""); @@ -548,8 +550,10 @@ static bool read_weights_hash(const std::string & path, uint64_t & hash) { std::string key, value; while (meta >> key >> value) { if (key == "hash") { - hash = std::stoull(value, nullptr, 16); - return true; + // a damaged record counts as no hash, so the caller rewrites the file + char * end = nullptr; + hash = std::strtoull(value.c_str(), &end, 16); + return end != value.c_str() && *end == '\0'; } } return false; diff --git a/ggml/src/ggml-openvino/openvino/op/argmax.cpp b/ggml/src/ggml-openvino/openvino/op/argmax.cpp new file mode 100644 index 000000000000..441a6a5b2ad6 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/op/argmax.cpp @@ -0,0 +1,51 @@ +#include "../node_context.h" +#include "../op_table.h" +#include "../utils.h" +#include "ggml.h" + +#include +#include +#include +#include +#include + +namespace ov { +namespace frontend { +namespace ggml { +namespace op { + +// GGML_OP_ARGMAX: src0 is a matrix [ne0, ne1]; the result is a 1-D I32 tensor of ne1 entries +// holding, for each row, the index of the maximum along ne0. ggml shapes arrive reversed here, so +// ne0 is the last OV axis and ne1 is axis 2. TopK(k=1, axis=last, MAX) yields exactly that index, +// then reshape to the [1,1,1,ne1] layout the decoder expects for a 1-D ggml output. +// +// Note ggml's argmax returns the FIRST maximum on a tie, while TopK's tie-breaking is not specified +// to match. Ties on real logits are vanishingly rare and none were observed, but the two are not +// proven equivalent. +OutputVector translate_argmax(const NodeContext & context) { + num_inputs_check(context, 1, 1); + + auto input = process_view_input_new(context, 0); + + auto k = ov::op::v0::Constant::create(ov::element::i64, {}, {1}); + auto topk = std::make_shared(input, + k, + 3, + ov::op::v11::TopK::Mode::MAX, + ov::op::v11::TopK::SortType::SORT_VALUES, + context.get_output_type(), + false); + + // ne1 is the dynamic row count, so build the target shape at runtime. + auto leading = ov::op::v0::Constant::create(ov::element::i64, {3}, {1, 1, 1}); + auto rows = get_dimensions(input.get_node_shared_ptr(), {2}); + auto target_shape = std::make_shared(OutputVector{leading, rows}, 0); + auto res = std::make_shared(topk->output(1), target_shape, false); + + return rename_outputs_with_suffix({res}, context.get_name()); +} + +} // namespace op +} // namespace ggml +} // namespace frontend +} // namespace ov diff --git a/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp b/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp index 065e92fcddcc..b83c6de3a1c4 100644 --- a/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp +++ b/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp @@ -182,13 +182,7 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) { // Manual GQA attention: enabled by default on GPU in stateless mode. // Set GGML_OPENVINO_MANUAL_GQA_ATTN to a positive value (e.g. 1) to force-enable, // or to 0 to force-disable. Unset falls back to the device-based default. - static const bool manual_gqa_enabled = []() { - const char * env = ggml_openvino_getenv_str("GGML_OPENVINO_MANUAL_GQA_ATTN"); - if (env != nullptr) { - return ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0; - } - return ggml_openvino_is_gpu(); - }(); + static const bool manual_gqa_enabled = ggml_openvino_manual_gqa_enabled(); // The manual path reshapes Q, K, V and the output with one head size; models whose K/V head sizes differ // from Q's (e.g. MLA) take the SDPA path. const bool same_head_size = k_shape[3] == q_shape[3] && v_shape[3] == q_shape[3]; diff --git a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp index 9acf3effb9d0..6caafeb4fde8 100644 --- a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp +++ b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -29,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -52,6 +54,31 @@ namespace op { static OutputVector translate_gated_delta_net_ref(const NodeContext & context); +// Asks the device: OpenVINO releases without the per-key gate reject a rank-4 gate when the node is built, and a plugin +// without a per-key kernel leaves the node out of query_model +bool gdn_per_key_gate_supported() { + static const bool supported = [] { + ov::ParameterVector params; + auto param = [¶ms](const ov::Shape & shape) { + params.push_back(std::make_shared(ov::element::f32, shape)); + return params.back(); + }; + std::shared_ptr gdn; + try { + gdn = std::make_shared(param({1, 1, 1, 2}), param({1, 1, 1, 2}), + param({1, 1, 1, 2}), param({1, 1, 2, 2}), + param({1, 1, 1, 2}), param({1, 1, 1})); + } catch (const ov::Exception &) { + return false; + } + const auto model = std::make_shared(gdn->outputs(), params); + return ov_singleton_core() + .query_model(model, ggml_openvino_get_device_name()) + .count(gdn->get_friendly_name()) != 0; + }(); + return supported; +} + static bool match_gdn_l2_norm(const Output & normalized, Output & input, float & eps) { // Match the RMSNorm decomposition emitted by translate_rms_norm, followed by GGML SCALE. const auto scale = ov::as_type_ptr(normalized.get_node_shared_ptr()); @@ -379,23 +406,36 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto auto v_shape = context.get_input_shape(2).to_shape(); // [B, T, H_v, S_v] auto q_shape = context.get_input_shape(0).to_shape(); // [B, T, H_k, S_k] - // Fused GatedDeltaNet op only supports scalar gate (kda=0). - // Fall back to reference implementation for per-key-dimension gating. - // if (kda) { - // return translate_gated_delta_net_ref(context); - // } + // g [B, T, H_v, 1] gates each head, g [B, T, H_v, S_k] each key dimension (kda); the fused op takes the latter as + // a rank-4 gate + const bool kda = context.get_input_shape(3)[3] != 1; + if (kda && !gdn_per_key_gate_supported()) { + // the reference loop reads and writes the state in the ggml layout, one state per call + FRONT_END_OP_CONVERSION_CHECK(!cache_inputs && context.get_output_op_params()[0] == 1 && + !ggml_openvino_gdn_native_state_enabled(), + "GATED_DELTA_NET with a per-key gate needs an OpenVINO GatedDeltaNet with a rank-4 " + "gate for recurrent caches, state snapshots or the native state layout"); + return translate_gated_delta_net_ref(context); + } - // const int64_t B = v_shape[0]; - // const int64_t T = v_shape[1]; const int64_t H_v = v_shape[2]; const int64_t S_v = v_shape[3]; const int64_t H_k = q_shape[2]; const int64_t snapshot_count = context.get_output_op_params()[0]; - // const int64_t S_k = q_shape[3]; + + // v is usually a VIEW of the fused qkv conv output, [S_v, H_v, T, B] over [conv_dim, T, B], with the heads packed + // in each row: a Slice of that row plus the Reshape below. Any other view layout, e.g. heads padded to a wider + // row, goes through the generic view resolution, which already returns [B, T, H_v, S_v]. + const bool v_is_view = context.get_view_input_size(2) > 0; + bool v_packed_heads = true; + if (v_is_view) { + const auto v_stride = context.get_view_input_stride(2, 0); // OV order: v_stride[3] = nb[0], v_stride[2] = nb[1] + v_packed_heads = v_stride.size() == 4 && v_stride[2] == (size_t) S_v * v_stride[3]; + } auto q = context.get_input(0); auto k = context.get_input(1); - auto v = process_view_input(context, 2, H_v * S_v, 3); + auto v = v_packed_heads ? process_view_input(context, 2, H_v * S_v, 3) : process_view_input_new(context, 2); auto g = context.get_input(3); auto beta = context.get_input(4); auto state = context.get_input(5); @@ -424,7 +464,7 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto k = std::make_shared(k, repeats); } - if (context.get_view_input_size(2)) { + if (v_is_view && v_packed_heads) { // Same as l2_norm case 1 v = std::make_shared(v, ov::op::v0::Constant::create(ov::element::i64, {1}, {0})); auto v_shape = context.get_input_shape(2).to_shape(); @@ -443,7 +483,9 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto state = std::make_shared(state, state_perm); } - g = std::make_shared(g, ov::op::v0::Constant::create(ov::element::i64, {1}, {3})); + if (!kda) { + g = std::make_shared(g, ov::op::v0::Constant::create(ov::element::i64, {1}, {3})); + } beta = std::make_shared(beta, ov::op::v0::Constant::create(ov::element::i64, {1}, {3})); if (context.has_input("chunk_valid_len")) { @@ -453,7 +495,7 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto // state equal to the state after the last real token. Attention output at those positions // is garbage but never read. const auto & g_ps = g.get_partial_shape(); - FRONT_END_OP_CONVERSION_CHECK(g_ps.rank().is_static() && g_ps.rank().get_length() == 3 && g_ps[1].is_static(), + FRONT_END_OP_CONVERSION_CHECK(g_ps.rank().is_static() && g_ps[1].is_static(), "GATED_DELTA_NET pad masking requires a static token dimension"); const int64_t n_tokens = g_ps[1].get_length(); std::vector positions(n_tokens); @@ -464,8 +506,12 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto auto mask = std::make_shared( std::make_shared(valid, g.get_element_type()), ov::op::v0::Constant::create(ov::element::i64, {2}, std::vector{0, 2})); - g = std::make_shared(g, mask); beta = std::make_shared(beta, mask); + if (kda) { + mask = std::make_shared(mask, + ov::op::v0::Constant::create(ov::element::i64, {1}, {3})); + } + g = std::make_shared(g, mask); } // std::cout << "GatedDeltaNet input shapes: q=" << q.get_partial_shape() << ", k=" << k.get_partial_shape() @@ -540,6 +586,8 @@ OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, co static OutputVector translate_gated_delta_net_ref(const NodeContext & context) { num_inputs_check(context, 6, 6); + FRONT_END_OP_CONVERSION_CHECK(!context.has_input("chunk_valid_len"), + "GATED_DELTA_NET reference loop does not support padded prefill chunks"); // Inputs (OV shapes are reversed from ggml): // ggml: q[S_k, H_k, T, B], k[S_k, H_k, T, B], v[S_v, H_v, T, B] @@ -559,8 +607,8 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) { auto q_shape = context.get_input_shape(0).to_shape(); // [B, T, H_k, S_k] auto g_shape = context.get_input_shape(3).to_shape(); // [B, T, H_v, 1 or S_v] + // The token count T is dynamic: shapes below use -1 for it and the loop runs once per input token. const int64_t B = v_shape[0]; - const int64_t T = v_shape[1]; const int64_t H_v = v_shape[2]; const int64_t S_v = v_shape[3]; const int64_t H_k = q_shape[2]; @@ -599,14 +647,14 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) { auto q_transposed = std::make_shared(q_bcast, perm_5d); auto k_transposed = std::make_shared(k_bcast, perm_5d); - auto new_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{B, H_v, T, S_v}); + auto new_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{B, H_v, -1, S_v}); q_bh = std::make_shared(q_transposed, new_shape, false); k_bh = std::make_shared(k_transposed, new_shape, false); } // Merge batch and head dims: [B*H_v, T, S_v] auto merge_bh = [&](const ov::Output & x, int64_t last_dim) { - auto shape = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector{B * H_v, T, last_dim}); + auto shape = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector{B * H_v, -1, last_dim}); return std::make_shared(x, shape, false); }; @@ -682,7 +730,9 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) { ov::OutputVector{body_cond_out, state_updated, attn_out_unsq}, ov::ParameterVector{body_iter, body_state, body_q, body_k, body_v, body_g, body_beta}); - auto trip_count = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector{T}); + auto vm_shape = std::make_shared(v_m, ov::element::i64); + auto trip_count = + std::make_shared(vm_shape, axis_1, ov::op::v0::Constant::create(ov::element::i64, {}, {0})); auto exec_cond = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, std::vector{true}); auto loop = std::make_shared(trip_count, exec_cond); @@ -709,7 +759,7 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) { // attn: [B, T, H_v, S_v] row-major, state: [B, H_v, S_v, S_v] row-major // attn: [B*H_v, T, S_v] -> [B, H_v, T, S_v] -> transpose to [B, T, H_v, S_v] -> flatten - auto attn_4d_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{B, H_v, T, S_v}); + auto attn_4d_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{B, H_v, -1, S_v}); auto attn_4d = std::make_shared(attn_concat_out, attn_4d_shape, false); auto attn_perm = std::make_shared(attn_4d, perm_0213); // [B, T, H_v, S_v] @@ -729,7 +779,7 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) { // Concat [attn | state] and reshape to final output auto packed = std::make_shared(ov::OutputVector{attn_1d, state_1d}, 0); auto out_shape = - ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{1, 1, T * B + S_v * B, S_v * H_v}); + ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{1, 1, -1, S_v * H_v}); auto res = std::make_shared(packed, out_shape, false); return rename_outputs_with_suffix({res}, context.get_name()); diff --git a/ggml/src/ggml-openvino/openvino/op/reshape.cpp b/ggml/src/ggml-openvino/openvino/op/reshape.cpp index 98ef6fa2c1da..203d3d396d54 100644 --- a/ggml/src/ggml-openvino/openvino/op/reshape.cpp +++ b/ggml/src/ggml-openvino/openvino/op/reshape.cpp @@ -30,6 +30,10 @@ OutputVector translate_reshape(const NodeContext & context) { std::shared_ptr new_shape_node; switch (op_case) { case 0: + // keep the tracked dynamic dim, e.g. the tokens of a reshape that only adds a trailing 1 (see translate_cont) + if (context.get_op_dynamic_dim() != -1) { + shape[3 - context.get_op_dynamic_dim()] = -1; + } break; case 1: case 9: diff --git a/ggml/src/ggml-openvino/openvino/op/rms_norm.cpp b/ggml/src/ggml-openvino/openvino/op/rms_norm.cpp index fb9eb5cc1680..078b31823c3e 100644 --- a/ggml/src/ggml-openvino/openvino/op/rms_norm.cpp +++ b/ggml/src/ggml-openvino/openvino/op/rms_norm.cpp @@ -34,7 +34,7 @@ OutputVector translate_rms_norm(const NodeContext & context) { input_node = context.get_input(0); } else if (op_case == 1) { input_node = process_view_input_new(context, 0); - } else if (op_case == 2 || op_case == 3) { + } else if (op_case == 2 || op_case == 5) { auto ssm_state_size = context.get_ssm_state_size(); // The GDN op packs [attn | new_state] along the row axis; the state occupies the last // ssm_state_size * n_seqs rows. Slice it off (scaling by the active sequence count) to keep @@ -83,7 +83,7 @@ OutputVector translate_rms_norm(const NodeContext & context) { float eps; memcpy(&eps, context.get_output_op_params(), sizeof(float)); - if (op_case == 3 && ggml_openvino_gdn_prescale_enabled()) { + if ((op_case == 3 || op_case == 5) && ggml_openvino_gdn_prescale_enabled()) { // input is the GDN output pre-scaled by ggml_openvino_gdn_q_scale(): rms_norm(s*x, s*s*eps) == rms_norm(x, eps) const float q_scale = ggml_openvino_gdn_q_scale(); eps *= q_scale * q_scale; diff --git a/ggml/src/ggml-openvino/openvino/op/set_rows.cpp b/ggml/src/ggml-openvino/openvino/op/set_rows.cpp index 476890911c04..24cbeac35cfa 100644 --- a/ggml/src/ggml-openvino/openvino/op/set_rows.cpp +++ b/ggml/src/ggml-openvino/openvino/op/set_rows.cpp @@ -118,16 +118,41 @@ static OutputVector translate_column_set_rows(const NodeContext & context) { if (data.get_element_type() != context.get_output_type()) { data = std::make_shared(data, context.get_output_type()); } - Output rows = std::make_shared(process_view_input_new(context, 1), i64_const({-1}), false); + auto row_ids = process_view_input_new(context, 1); + Output rows = std::make_shared(row_ids, i64_const({-1}), false); if (rows.get_element_type() != ov::element::i64) { rows = std::make_shared(rows, ov::element::i64); } auto axis = v0::Constant::create(ov::element::i64, {}, {2}); - auto buffer = std::make_shared(base, i64_const({1, 1, -1, row_size}), false); + Output buffer = std::make_shared(base, i64_const({1, 1, -1, row_size}), false); + Output base_shape_of = std::make_shared(base, ov::element::i64); + Output existing; + + // Every write copies the whole buffer, so fold this one into the previous column write when both use the same + // rows (DFlash writes every target layer at the same batch rows): splice into its rows and scatter once + auto rows_source = [](Output r) { + if (ov::as_type_ptr(r.get_node_shared_ptr())) { + r = r.get_node()->input_value(0); + } + return ov::as_type_ptr(r.get_node_shared_ptr()) ? r.get_node()->input_value(0) : Output(); + }; + auto prev_res = ov::as_type_ptr(base.get_node_shared_ptr()); + auto prev = prev_res ? ov::as_type_ptr(prev_res->get_input_node_shared_ptr(0)) : nullptr; + if (prev && rows_source(prev->input_value(1)) == row_ids && + prev->input_value(2).get_partial_shape().rank().is_static() && + prev->input_value(2).get_partial_shape()[3] == row_size) { + buffer = prev->input_value(0); + rows = prev->input_value(1); + existing = prev->input_value(2); + base_shape_of = prev_res->input_value(1); + } + Output updates = data; if (width < row_size) { - auto existing = std::make_shared(buffer, rows, axis); + if (!existing.get_node_shared_ptr()) { + existing = std::make_shared(buffer, rows, axis); + } auto col_axis = i64_const({3}); OutputVector parts; if (col_begin > 0) { @@ -142,7 +167,7 @@ static OutputVector translate_column_set_rows(const NodeContext & context) { updates = std::make_shared(parts, 3); } auto updated = std::make_shared(buffer, rows, updates, axis); - auto res = std::make_shared(updated, std::make_shared(base, ov::element::i64), false); + auto res = std::make_shared(updated, base_shape_of, false); return rename_outputs_with_suffix({res}, context.get_name()); } diff --git a/ggml/src/ggml-openvino/openvino/op/solve_tri.cpp b/ggml/src/ggml-openvino/openvino/op/solve_tri.cpp deleted file mode 100644 index 840233f85440..000000000000 --- a/ggml/src/ggml-openvino/openvino/op/solve_tri.cpp +++ /dev/null @@ -1,108 +0,0 @@ -#include "../node_context.h" -#include "../op_table.h" -#include "../utils.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ov { -namespace frontend { -namespace ggml { -namespace op { - -// GGML SOLVE_TRI: solve Ax = B for lower-triangular A via forward substitution. -// Currently only lower, right, non-unitriangular variant is implemented. -// -// ggml layout: A [n, n, B1, B2], B [k, n, B1, B2] → X [k, n, B1, B2] -// OV layout: A [B2, B1, n, n], B [B2, B1, n, k] → X [B2, B1, n, k] -// -// Forward substitution row i: -// x[i] = (b[i] - sum_{t(A_shape[2]); - - // Initial X: zeros with shape of B - auto B_shape_node = std::make_shared(B, ov::element::i64); - auto zero_f32 = ov::op::v0::Constant::create(ov::element::f32, {}, {0.0f}); - auto X_init = std::make_shared(zero_f32, B_shape_node); - - // --- Loop body parameters --- - // body_iter: iteration counter injected by the Loop op (i64, shape {1}) - auto body_iter = std::make_shared(ov::element::i64, ov::Shape{1}); - auto body_X = std::make_shared(ov::element::f32, ov::PartialShape::dynamic(4)); - auto body_A = std::make_shared(ov::element::f32, ov::PartialShape::dynamic(4)); - auto body_B_p = std::make_shared(ov::element::f32, ov::PartialShape::dynamic(4)); - - auto c_axis2 = ov::op::v0::Constant::create(ov::element::i64, {1}, {int64_t(2)}); - auto c_axis3 = ov::op::v0::Constant::create(ov::element::i64, {1}, {int64_t(3)}); - auto c_axis2_scalar = ov::op::v0::Constant::create(ov::element::i64, {}, {int64_t(2)}); - - // b_i = B[..., i, :] [B2, B1, 1, k] - auto b_i = std::make_shared(body_B_p, body_iter, c_axis2); - - // A_row_i = A[..., i, :] [B2, B1, 1, n] - auto A_row_i = std::make_shared(body_A, body_iter, c_axis2); - - // sum_i = A_row_i @ X [B2, B1, 1, k] - // (lower-tri zeros + unfilled-X zeros make this equal to the partial sum) - auto sum_i = std::make_shared(A_row_i, body_X, false, false); - - // diag_i = A[..., i, i] [B2, B1, 1, 1] - auto diag_i = std::make_shared(A_row_i, body_iter, c_axis3); - - // x_i = (b_i - sum_i) / diag_i [B2, B1, 1, k] - auto x_i = std::make_shared( - std::make_shared(b_i, sum_i), diag_i); - - // X_updated: scatter x_i into body_X at row i along axis 2 - auto X_updated = std::make_shared(body_X, body_iter, x_i, c_axis2_scalar); - - auto body_cond = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, {true}); - - auto body = std::make_shared( - ov::OutputVector{body_cond, X_updated}, - ov::ParameterVector{body_iter, body_X, body_A, body_B_p}); - - // --- Assemble Loop --- - auto trip_count = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector{n}); - auto exec_cond = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, {true}); - - auto loop = std::make_shared(trip_count, exec_cond); - loop->set_function(body); - // iter_counter_body_param_idx=0 (body_iter), exec_condition_body_result_idx=0 (body_cond) - loop->set_special_body_ports(ov::op::v5::Loop::SpecialBodyPorts{0, 0}); - - // Carried state: X feeds back from X_updated each iteration - loop->set_merged_input(body_X, X_init, X_updated); - // Invariant inputs passed through unchanged - loop->set_invariant_input(body_A, A); - loop->set_invariant_input(body_B_p, B); - - // Final output: value of X_updated after the last iteration - auto X_final = loop->get_iter_value(X_updated, -1); - - return rename_outputs_with_suffix({X_final}, context.get_name()); -} - -} // namespace op -} // namespace ggml -} // namespace frontend -} // namespace ov diff --git a/ggml/src/ggml-openvino/openvino/op_table.cpp b/ggml/src/ggml-openvino/openvino/op_table.cpp index defc428d1d4c..4983e2a7ccfe 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.cpp +++ b/ggml/src/ggml-openvino/openvino/op_table.cpp @@ -57,6 +57,7 @@ std::unordered_map get_supported_ops() { {"GGML_OP_SQR", op::translate_sqr }, {"GGML_OP_SQRT", op::translate_sqrt }, {"GGML_OP_SOFT_MAX", op::translate_soft_max }, + {"GGML_OP_ARGMAX", op::translate_argmax }, {"GGML_OP_ARGSORT", op::translate_argsort }, {"GGML_OP_SUB", op::translate_1to1_match_2_inputs}, {"GGML_OP_TRANSPOSE", op::translate_transpose }, @@ -102,7 +103,6 @@ std::unordered_map get_supported_ops() { {"GGML_OP_GATED_DELTA_NET", op::translate_gated_delta_net }, {"GGML_OP_REPEAT", op::translate_repeat }, {"GGML_OP_CUMSUM", op::translate_cumsum }, - {"GGML_OP_FILL", op::translate_fill }, {"GGML_OP_DIAG", op::translate_diag }, {"GGML_OP_TRI", op::translate_tri }, {"GGML_OP_SET", op::translate_set }, @@ -115,8 +115,6 @@ std::unordered_map get_supported_ops() { {"GGML_OP_CONV_TRANSPOSE_1D", op::translate_conv_transpose_1d }, {"GGML_OP_CONV_TRANSPOSE_2D", op::translate_conv_transpose_2d }, {"GGML_OP_CONV_3D", op::translate_conv_3d }, - // solve_tri has accuracy issues on GPU - // {"GGML_OP_SOLVE_TRI", op::translate_solve_tri }, }; } diff --git a/ggml/src/ggml-openvino/openvino/op_table.h b/ggml/src/ggml-openvino/openvino/op_table.h index 54c60c634bf6..766ca4e6f76c 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.h +++ b/ggml/src/ggml-openvino/openvino/op_table.h @@ -43,6 +43,7 @@ GGML_OP_CONVERTER(translate_glu_geglu); GGML_OP_CONVERTER(translate_glu_geglu_quick); GGML_OP_CONVERTER(translate_set_rows); GGML_OP_CONVERTER(translate_cpy); +GGML_OP_CONVERTER(translate_argmax); GGML_OP_CONVERTER(translate_argsort); GGML_OP_CONVERTER(translate_top_k); GGML_OP_CONVERTER(translate_flash_attn_ext); @@ -51,16 +52,16 @@ GGML_OP_CONVERTER(translate_pad); GGML_OP_CONVERTER(translate_ssm_conv); GGML_OP_CONVERTER(translate_ssm_scan); GGML_OP_CONVERTER(translate_gated_delta_net); +// The device runs GatedDeltaNet with a gate per key dimension; otherwise the translator falls back to its reference loop +bool gdn_per_key_gate_supported(); #ifdef GGML_OPENVINO_HAS_CACHE_UPDATE OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, const OutputVector & cache_inputs); #endif GGML_OP_CONVERTER(translate_repeat); GGML_OP_CONVERTER(translate_cumsum); -GGML_OP_CONVERTER(translate_fill); GGML_OP_CONVERTER(translate_set); GGML_OP_CONVERTER(translate_diag); GGML_OP_CONVERTER(translate_tri); -GGML_OP_CONVERTER(translate_solve_tri); GGML_OP_CONVERTER(translate_pool_1d); GGML_OP_CONVERTER(translate_pool_2d); GGML_OP_CONVERTER(translate_roll); diff --git a/ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.cpp b/ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.cpp deleted file mode 100644 index 0671542ee383..000000000000 --- a/ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.cpp +++ /dev/null @@ -1,60 +0,0 @@ -#include "fuse_to_sdpa.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ov { -namespace frontend { -namespace ggml { -namespace pass { - -FuseToSDPA::FuseToSDPA() { - // Not maintained since FLASH_ATTN_EXT has replaced this pattern - const auto m_k = ov::pass::pattern::any_input(); - const auto m_q = ov::pass::pattern::any_input(); - const auto m_qk = ov::pass::pattern::wrap_type({m_q, m_k}); - const auto m_qk_f32 = ov::pass::pattern::wrap_type({m_qk}); - const auto m_scale = ov::pass::pattern::any_input(); - const auto m_scaled_qk = ov::pass::pattern::wrap_type({m_qk_f32, m_scale}); - const auto m_mask = ov::pass::pattern::any_input(); - const auto m_masked_qk = ov::pass::pattern::wrap_type({m_scaled_qk, m_mask}); - const auto m_softmax_qk = ov::pass::pattern::wrap_type({m_masked_qk}); - const auto m_softmax_qk_f16 = ov::pass::pattern::wrap_type({m_softmax_qk}); - const auto m_v = ov::pass::pattern::any_input(); - const auto m_qkv = ov::pass::pattern::wrap_type({m_softmax_qk_f16, m_v}); - - const auto callback = [=](ov::pass::pattern::Matcher & m) { - auto & pattern_to_output = m.get_pattern_value_map(); - auto k = pattern_to_output[m_k]; - auto q = pattern_to_output[m_q]; - auto v = pattern_to_output[m_v]; - auto mask = pattern_to_output[m_mask]; - auto scale = pattern_to_output[m_scale]; - - auto mask_f16 = register_new_node(mask, ov::element::f16); - auto scale_f16 = register_new_node(scale, ov::element::f16); - auto sdpa = std::make_shared(q, k, v, mask_f16, scale_f16, false); - - ov::replace_node(m.get_match_root(), sdpa); - ov::copy_runtime_info(m.get_matched_nodes(), sdpa); - - return true; - }; - register_matcher(std::make_shared(m_qkv, "ov::frontend::ggml::pass::FuseToSDPA"), - callback); -} - -} // namespace pass -} // namespace ggml -} // namespace frontend -} // namespace ov diff --git a/ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.h b/ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.h deleted file mode 100644 index 8b5164d23293..000000000000 --- a/ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.h +++ /dev/null @@ -1,17 +0,0 @@ -#include "openvino/pass/matcher_pass.hpp" - -namespace ov { -namespace frontend { -namespace ggml { -namespace pass { - -class FuseToSDPA : public ov::pass::MatcherPass { -public: - OPENVINO_MATCHER_PASS_RTTI("ov::frontend::ggml::pass::FuseToSDPA") - FuseToSDPA(); -}; - -} // namespace pass -} // namespace ggml -} // namespace frontend -} // namespace ov diff --git a/ggml/src/ggml-openvino/openvino/translate_session.cpp b/ggml/src/ggml-openvino/openvino/translate_session.cpp index 3da712f72bdf..eddebd901dab 100644 --- a/ggml/src/ggml-openvino/openvino/translate_session.cpp +++ b/ggml/src/ggml-openvino/openvino/translate_session.cpp @@ -225,42 +225,12 @@ void add_position_mask_stateful_swa(TensorMap & tensor_map) { tensor_map["KQ_mask_swa_sliced"] = mask->output(0); } -void add_rope_sin_cos(TensorMap & tensor_map, GgmlDecoder & ggml_model_decoder) { - // When ROPE ops in the graph have divergent op_params (e.g. gemma4's mixed - // SWA/non-SWA layers with different n_dims or freq_base), a shared sin/cos - // precompute cannot broadcast across every ROPE use. Skip it here and let - // translate_rope() build sin/cos per-op from its own op_params. - if (ggml_model_decoder.has_mixed_rope_params()) { - return; - } - int32_t * rope_params = ggml_model_decoder.get_rope_params(); - if (tensor_map.find("inp_pos") == tensor_map.end() || rope_params == nullptr) { - return; - } - auto inp_pos = tensor_map.at("inp_pos").get_node_shared_ptr(); - std::shared_ptr rope_freqs_weight; - if (tensor_map.find("rope_freqs.weight") != tensor_map.end()) { - rope_freqs_weight = tensor_map.at("rope_freqs.weight").get_node_shared_ptr(); - } - - auto sin_cos = make_sin_cos(rope_params, inp_pos, rope_freqs_weight); - auto sin_theta = sin_cos.first; - auto cos_theta = sin_cos.second; - - cos_theta.get_node_shared_ptr()->set_friendly_name("rope_cos"); - sin_theta.get_node_shared_ptr()->set_friendly_name("rope_sin"); - tensor_map.insert({"rope_cos", cos_theta}); - tensor_map.insert({"rope_sin", sin_theta}); -} - // Create common patterns void preprocess(TensorMap & tensor_map, GgmlDecoder & ggml_model_decoder) { if (ggml_model_decoder.is_stateful()) { add_sliced_mask_stateful(tensor_map, ggml_model_decoder.get_rope_params()[2] == GGML_ROPE_TYPE_IMROPE); add_position_mask_stateful_swa(tensor_map); } - // This optimization is error-prone - // add_rope_sin_cos(tensor_map, ggml_model_decoder); } } // namespace diff --git a/ggml/src/ggml-openvino/openvino/utils.cpp b/ggml/src/ggml-openvino/openvino/utils.cpp index e82a6c92fc47..7094cb7338ea 100644 --- a/ggml/src/ggml-openvino/openvino/utils.cpp +++ b/ggml/src/ggml-openvino/openvino/utils.cpp @@ -31,6 +31,7 @@ #include #include #include +#include #include namespace ov { @@ -43,18 +44,6 @@ void num_inputs_check(const NodeContext & context, size_t min_inputs, size_t max FRONT_END_OP_CONVERSION_CHECK(input_size <= max_inputs, "Got more inputs than expected"); } -int non_cont_dim(std::vector ne, std::vector nb) { - int dim = nb.size() - 1; - size_t bytes = nb[dim]; - for (int i = dim; i > 0; i--) { - bytes *= ne[i]; - if (bytes != nb[i - 1]) { - return i; - } - } - return 0; -} - std::shared_ptr get_dimensions(const std::shared_ptr & shape, const std::vector & dims) { using namespace ov::op; @@ -311,14 +300,77 @@ std::pair, ov::Output> make_sin_cos(int32_t * rope_params } } - Output cos_theta = std::make_shared(theta); - Output sin_theta = std::make_shared(theta); + // Keep the ROPE ANGLE in f32 even under INFERENCE_PRECISION_HINT=f16. + // + // Everything above builds theta = pos * freq_factors with a declared f32 type, but a declared + // element type is not an execution precision: under the f16 hint the GPU plugin compresses these + // subgraphs to f16 anyway. theta's magnitude IS the token position, so at position 6525 it lands + // where f16 spacing is 4 and the value is not even representable. Worse, a model whose freq_base + // and head_dim make factor[0] == 1.0 exactly feeds the raw position in as the top-frequency + // angle, so an absolute error of 1-2 becomes an error of 1-2 RADIANS -- up to a third of a cycle. Sin/Cos of an angle wrong by radians is not approximately + // right, it is arbitrary, and trig amplifies the error without bound. + // + // Measured on a large decoder-only model at inp_pos=6525, same device, f16 vs f32 execution: the + // whole Q/K projection chain is clean at rel ~1e-4, then Cos jumps to rel 0.124 and Sin to 0.155, + // and K right after the rotation carries rel 0.081. The error is depth-dependent because f16 + // spacing grows with magnitude: sin rel is 0.006 at position 512 and 0.16 at 6525. + // + // mark_as_precision_sensitive disables fp16 compression of the subgraph feeding an input, which is + // exactly the guarantee needed. Marking Sin/Cos's input covers the whole theta chain back to the + // Convert of inp_pos. The cost is negligible: theta is a few dozen values per token, against the + // matmuls that dominate. The rotation itself and everything downstream stay f16. + // + // Off by default; GGML_OPENVINO_ROPE_F32_ANGLE=1 turns it on. It changes the RoPE of every model, + // it is validated on one model on the GPU only, and on an f32 path the round trip below makes + // cos and sin less accurate. + const bool pin_angle = ggml_openvino_getenv_int("GGML_OPENVINO_ROPE_F32_ANGLE") != 0; + + auto cos_op = std::make_shared(theta); + auto sin_op = std::make_shared(theta); + if (pin_angle) { + ov::mark_as_precision_sensitive(cos_op->input(0)); + ov::mark_as_precision_sensitive(sin_op->input(0)); + } + Output cos_theta = cos_op; + Output sin_theta = sin_op; if (mscale != 1.0f) { auto mscale_node = ov::op::v0::Constant::create(ov::element::f32, Shape{}, {mscale}); - cos_theta = std::make_shared(cos_theta, mscale_node); - sin_theta = std::make_shared(sin_theta, mscale_node); + auto cos_scaled = std::make_shared(cos_theta, mscale_node); + auto sin_scaled = std::make_shared(sin_theta, mscale_node); + // Mark this Constant's input too. Marking only Sin/Cos keeps those nodes f32 but leaves the + // sibling mscale Constant to be compressed to f16, and the pass does not reconcile the pair, + // so compilation fails with "Arguments do not have the same element type". + if (pin_angle) { + ov::mark_as_precision_sensitive(cos_scaled->input(1)); + ov::mark_as_precision_sensitive(sin_scaled->input(1)); + } + cos_theta = cos_scaled; + sin_theta = sin_scaled; + } + + // Close the f32 island explicitly with an f16 round trip. + // + // ConvertPrecision does not insert the boundary Convert: with only the marking above, the f32 + // region propagates forward through the shape-only ops of the cos/sin expansion and then collides + // with f16 data in the rotation, so the type mismatch just moves one step down the graph. + // + // Rounding the RESULT of the trig is harmless -- cos/sin are in [-1,1], where f16 spacing is ~6e-4, + // the ordinary f16 cost accepted everywhere else. What must not be rounded is the ANGLE, which the + // marking above protects. So this spends the cheap rounding to buy a type-consistent graph: the + // chain from inp_pos through Sin/Cos stays f32, everything downstream is f16, and the transition is + // a node we control rather than one the pass has to infer. + // + // Declared types are f32 on both sides at build time, so the frontend sees no type change. On an + // f32 path (the CPU device in test-backend-ops) the two Converts still round cos and sin to f16. + if (pin_angle) { + auto pin_boundary = [](Output x) -> Output { + auto down = std::make_shared(x, ov::element::f16); + return std::make_shared(down, ov::element::f32); + }; + cos_theta = pin_boundary(cos_theta); + sin_theta = pin_boundary(sin_theta); } return std::make_pair(sin_theta, cos_theta); @@ -784,20 +836,23 @@ ov::Output process_view_input_new(const NodeContext & context, int inp return split_node->output(static_cast(split_index)); } if (split_index >= 0 && split_index < num_splits && !dynamic_split) { + // as above: a weak reference, and one Split per output port auto src_node = input.get_node_shared_ptr(); - std::string rt_key = "split_dim_" + std::to_string(split_dim); + std::string rt_key = + "split_dim_static_" + std::to_string(split_dim) + "_" + std::to_string(input.get_index()); auto & rt_info = src_node->get_rt_info(); - - if (rt_info.find(rt_key) == rt_info.end()) { + std::shared_ptr split_node; + if (rt_info.count(rt_key) != 0) { + split_node = rt_info[rt_key].as>().lock(); + } + if (split_node == nullptr) { auto axis_const = ov::op::v0::Constant::create(ov::element::i64, {}, {static_cast(split_dim)}); - auto split_node = + split_node = std::make_shared(input, axis_const, static_cast(num_splits)); split_node->set_friendly_name(src_node->get_friendly_name() + "_split"); - rt_info[rt_key] = split_node; + rt_info[rt_key] = std::weak_ptr(split_node); } - - auto split_node = rt_info[rt_key].as>(); return split_node->output(static_cast(split_index)); } } diff --git a/ggml/src/ggml-openvino/openvino/utils.h b/ggml/src/ggml-openvino/openvino/utils.h index aaee05116445..3fe3b60f918b 100644 --- a/ggml/src/ggml-openvino/openvino/utils.h +++ b/ggml/src/ggml-openvino/openvino/utils.h @@ -13,42 +13,8 @@ namespace ov { namespace frontend { namespace ggml { -std::string getCurrentTime(); - void num_inputs_check(const NodeContext & context, size_t min_inputs, size_t max_inputs); -int non_cont_dim(std::vector ne, std::vector nb); - -template std::vector argsort_descend(const std::vector & v) { - std::vector idx(v.size()); - std::iota(idx.begin(), idx.end(), 0); - std::sort(idx.begin(), idx.end(), [&v](int i1, int i2) { return v[i1] > v[i2]; }); - return idx; -} - -template std::vector sorted_descend(std::vector v) { - std::sort(v.begin(), v.end(), [](T a, T b) { return a > b; }); - return v; -} - -template bool is_permuted(const std::vector & strides) { - for (size_t i = 0; i < strides.size() - 1; ++i) { - if (strides[i] < strides[i + 1]) { - return true; - } - } - return false; -} - -template std::vector permute(const std::vector & x, const std::vector & perm) { - std::vector result; - result.reserve(perm.size()); - for (int i : perm) { - result.push_back(x[i]); - } - return result; -} - std::shared_ptr get_dimensions(const std::shared_ptr & shape, const std::vector & dims); std::shared_ptr get_dimensions(const std::shared_ptr & node, const std::vector & dims); diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index c959ce0d9203..03479f35edd3 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -151,6 +151,12 @@ std::optional try_make_kv_sliced_tensor(const std::shared_ptrdata == nullptr) { + // unallocated input: let the caller build an owning zero tensor rather than slice a null + // pointer + return std::nullopt; + } + ov::Shape sliced_shape = full_shape; sliced_shape[2] = static_cast(n_kv); @@ -192,10 +198,10 @@ std::optional try_make_kv_4d_tensor(const std::shared_ptr ggml_decoder, const std::string & name) { +static size_t get_static_attention_size(const std::shared_ptr & ggml_decoder, const std::string & name) { const bool is_swa = ggml_decoder->is_swa_mask(ggml_decoder->get_input_ggml_tensor(name)); if (ggml_decoder->m_is_prefill ? ggml_openvino_kv_slice_enabled() : ggml_openvino_npu_decode_bucket() > 0) { - const auto params = ggml_decoder->get_compute_params(); + const auto & params = ggml_decoder->get_compute_params(); const int attention_size = is_swa ? params.attention_size_swa : params.attention_size; if (attention_size > 0) { return static_cast(attention_size); @@ -209,10 +215,7 @@ static size_t get_static_attention_size(std::shared_ptr ggml_deco } static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurrent) { - const char * manual_gqa_env = ggml_openvino_getenv_str("GGML_OPENVINO_MANUAL_GQA_ATTN"); - const bool manual_gqa_enabled = manual_gqa_env != nullptr ? - ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0 : - ggml_openvino_is_gpu(); + const bool manual_gqa_enabled = ggml_openvino_manual_gqa_enabled(); uint64_t extra_cfg = 15; // Recurrent caches are writable inputs without cache Results. #ifdef GGML_OPENVINO_HAS_CACHE_UPDATE @@ -561,6 +564,11 @@ ov::Tensor create_ov_output_tensor(const std::shared_ptr & ggml_d return context.create_tensor(output_type, output_shape, resolved); } + // A graph output can also have no backing storage. Give OV an owning tensor so the infer request + // has somewhere to write; nothing downstream reads it. + if (output_data == nullptr) { + return ov::Tensor(output_type, output_shape); + } ov::Tensor output_tensor(output_type, output_shape, output_data); return output_tensor; } @@ -713,6 +721,20 @@ ov::Tensor convert_ggml_input_to_ov(const std::shared_ptr & ggml_ return make_contiguous_split_input_tensor(ggml_tensor, input_shape); } + // A graph input may legitimately be left unallocated (data == nullptr, no buffer): llama.cpp + // skips filling the attention mask when a graph only stores K/V without attending, which is what + // a speculative KV-injection pass does. Such an input is never read, but OpenVINO still requires + // a backing tensor for the Parameter and constructing an ov::Tensor over a null pointer asserts. + // Hand OV an owning zero-filled tensor; its contents cannot affect the result because no op + // consumes them. + if (input_data == nullptr) { + GGML_LOG_WARN("ggml-openvino: unallocated INPUT '%s' (ggml name '%s', type %s, ne=[%ld,%ld,%ld,%ld]) " + "-> zero tensor\n", + name.c_str(), ggml_tensor->name, ggml_type_name(ggml_tensor->type), + (long) ggml_tensor->ne[0], (long) ggml_tensor->ne[1], (long) ggml_tensor->ne[2], + (long) ggml_tensor->ne[3]); + return ov::Tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape); + } auto input_tensor = ov::Tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape, input_data); return input_tensor; } @@ -790,10 +812,8 @@ ov::Tensor get_ov_input_tensor_static_decode(const std::shared_ptrdata); - assert(ggml_tensor->ne[0] == 1); - assert(inp_out_id == 0); - *input_tensor.data() = inp_out_id; + // The only decode token is row 0. out_ids is empty when the graph has no output, so it is not read. + *input_tensor.data() = 0; return input_tensor; } @@ -1256,13 +1276,15 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share cache_hit = it != r_ctx->decoder_cache.end(); if (cache_hit) { entry = it->second; + r_ctx->touch_locked(key); } else { - if (r_ctx->stateful || r_ctx->decoder_cache.size() >= 8) { + if (r_ctx->stateful) { r_ctx->clear_caches_locked(); } auto mutex = std::make_shared(); entry = std::make_shared(mutex); r_ctx->decoder_cache[key] = entry; + r_ctx->admit_locked(key); } } else { auto mutex = std::make_shared(); @@ -1276,10 +1298,21 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share if (cache_hit) { ggml_decoder = entry->ptr; + // The cache key is only (n_nodes, first/last node name), so it cannot see a change in + // WHICH tensors are graph outputs -- and the compiled model's Results are fixed when it is + // built. A consumer that starts requesting extra outputs later (speculative decoding marks + // the target's per-layer residuals only once the draft is initialised) would otherwise keep + // reusing a model that never produces them, and the host would read unwritten buffers as + // zeros. Recompile when the output set differs. old_m_params = ggml_decoder->get_model_params(); if (!ggml_decoder->is_splited_model()) { cache_hit = old_m_params.can_reuse_dynamically(m_params); } + // Must come AFTER can_reuse_dynamically(), which ASSIGNS to cache_hit rather than + // and-ing into it and would otherwise silently undo this invalidation. + if (cache_hit && !ggml_decoder->has_same_graph_io(cgraph)) { + cache_hit = false; + } } std::vector ov_input_names; @@ -1654,8 +1687,6 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share infer_request = std::make_shared(compiled_model.create_infer_request()); shared_model = compiled_model; - entry->ptr = ggml_decoder; - } // end non-imported (compile) path entry->ptr = ggml_decoder; @@ -1725,7 +1756,20 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share id = binding.staging_id; } if (needs_bind(binding, input_tensor, id)) { - infer_request->set_input_tensor(i, input_tensor); + try { + infer_request->set_input_tensor(i, input_tensor); + } catch (const std::exception & e) { + if (ggml_openvino_getenv_int("GGML_OPENVINO_DIAG_GRAPH_IO")) { + auto port = infer_request->get_compiled_model().input(i); + GGML_LOG_WARN( + "ggml-openvino: DIAG set_input_tensor[%zu] '%s' threw for n_nodes=%d first=%s last=%s: %s\n" + " model_shape=%s bound_shape=%s\n", + i, param_name.c_str(), key.n_nodes, key.first_node_name.c_str(), + key.last_node_name.c_str(), e.what(), port.get_partial_shape().to_string().c_str(), + input_tensor.get_shape().to_string().c_str()); + } + throw; + } } if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_INPUT")) { @@ -1786,12 +1830,40 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share id = binding.staging_id; } if (needs_bind(binding, output_tensor, id)) { - infer_request->set_output_tensor(i, output_tensor); + try { + infer_request->set_output_tensor(i, output_tensor); + } catch (const std::exception & e) { + if (ggml_openvino_getenv_int("GGML_OPENVINO_DIAG_GRAPH_IO")) { + auto port = infer_request->get_compiled_model().output(i); + GGML_LOG_WARN( + "ggml-openvino: DIAG set_output_tensor[%zu] '%s' threw for n_nodes=%d first=%s last=%s: %s\n" + " model_shape=%s bound_shape=%s\n", + i, ov_output_names[i].c_str(), key.n_nodes, key.first_node_name.c_str(), + key.last_node_name.c_str(), e.what(), port.get_partial_shape().to_string().c_str(), + output_tensor.get_shape().to_string().c_str()); + } + throw; + } } } ov_raw_infer_start = ggml_time_us(); - infer_request->infer(); + try { + infer_request->infer(); + } catch (const std::exception & e) { + if (ggml_openvino_getenv_int("GGML_OPENVINO_DIAG_GRAPH_IO")) { + auto cm = infer_request->get_compiled_model(); + GGML_LOG_WARN("ggml-openvino: DIAG infer() threw for n_nodes=%d first=%s last=%s: %s\n", key.n_nodes, + key.first_node_name.c_str(), key.last_node_name.c_str(), e.what()); + for (size_t i = 0; i < ov_input_names.size(); i++) { + auto port = cm.input(i); + GGML_LOG_WARN(" param[%zu] name=%s model_shape=%s bound_shape=%s\n", i, + ov_input_names[i].c_str(), port.get_partial_shape().to_string().c_str(), + infer_request->get_input_tensor(i).get_shape().to_string().c_str()); + } + } + throw; + } infer_end_time = ggml_time_us(); for (const auto & out : staged_outputs) { std::memcpy(out.dst, out.src, out.bytes); @@ -2190,11 +2262,12 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared cache_hit = it != r_ctx->decoder_cache.end(); if (cache_hit) { entry = it->second; + r_ctx->touch_locked(key); } else { - r_ctx->clear_caches_locked(); auto mutex = std::make_shared(); entry = std::make_shared(mutex); r_ctx->decoder_cache[key] = entry; + r_ctx->admit_locked(key); } } else { auto mutex = std::make_shared(); @@ -2265,10 +2338,8 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared // Same fail-fast as the dynamic path: once the host weight pages have been dropped // they read as zeros, so a recompile here would bake garbage into the new model. if (ggml_openvino_weight_buffers_released()) { - GGML_ABORT( - "ggml-openvino: a new graph needs to be compiled but host weight buffers were already " - "released via GGML_OPENVINO_RELEASE_WEIGHTS. This mode requires " - "stable graph shapes; disable host weight release for dynamic workloads."); + GGML_LOG_ERROR("ggml-openvino: cannot compile a new graph after releasing host weights\n"); + return GGML_STATUS_FAILED; } if (cache_enabled) { std::lock_guard map_lock(r_ctx->ctx_mutex); @@ -2318,6 +2389,10 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared } } else { auto decode_c_params = c_params; + // A decode step outputs its one token. llama-perplexity asks for many outputs in the prefill graph; the + // decode model of the pair keeps one (decode_signature below), or its last layer would gather more rows + // than the graph has tokens. + decode_c_params.output_len = 1; if (ggml_openvino_kv_slice_enabled()) { decode_c_params.attention_size = m_params.ctx_per_seq; decode_c_params.attention_size_swa = m_params.ctx_per_seq_swa; @@ -3322,7 +3397,7 @@ bool is_model_splitted(ggml_cgraph * cgraph) { // the src is also not the model weights, we think the model is splitted. // the src is also not in model leafs, we think the model is splitted. if (src != nullptr && model_nodes.find(src) == model_nodes.end() && - model_weights.find(std::string(src->name)) == model_weights.end() && !model_leafs.empty() == false && + model_weights.find(std::string(src->name)) == model_weights.end() && model_leafs.find(src) == model_leafs.end()) { if (GgmlOvDecoder::is_inp_tok(src, node)) { return false; @@ -3345,75 +3420,6 @@ bool is_naive(ggml_cgraph * cgraph) { return count < naive_graph_size_threshold; } -size_t checksum(const void * data, size_t size) { - const uint8_t * bytes = static_cast(data); - size_t sum = 0; - for (size_t i = 0; i < size; ++i) { - sum += (uint8_t) i; - sum += bytes[i]; - } - return sum; -} - -bool save_ggml_tensor_data_to_txt(const ggml_tensor * tensor, const std::string & file_path) { - if (tensor == nullptr || tensor->data == nullptr) { - return false; - } - - std::ofstream out(file_path); - if (!out.is_open()) { - return false; - } - - const size_t n = ggml_nelements(tensor); - out << "name: " << tensor->name << ", type: " << ggml_type_name(tensor->type) << ", shape: [" << tensor->ne[0] - << ", " << tensor->ne[1] << ", " << tensor->ne[2] << ", " << tensor->ne[3] << "]" << ", elements: " << n - << ", data:" << '\n'; - - switch (tensor->type) { - case GGML_TYPE_F32: { - const auto * data = static_cast(tensor->data); - for (size_t i = 0; i < n; ++i) { - out << data[i] << '\n'; - } - break; - } - case GGML_TYPE_F16: { - const auto * data = static_cast(tensor->data); - for (size_t i = 0; i < n; ++i) { - out << ggml_fp16_to_fp32(data[i]) << '\n'; - } - break; - } - case GGML_TYPE_BF16: { - const auto * data = static_cast(tensor->data); - for (size_t i = 0; i < n; ++i) { - out << ggml_bf16_to_fp32(data[i]) << '\n'; - } - break; - } - case GGML_TYPE_I32: { - const auto * data = static_cast(tensor->data); - for (size_t i = 0; i < n; ++i) { - out << data[i] << '\n'; - } - break; - } - case GGML_TYPE_I64: { - const auto * data = static_cast(tensor->data); - for (size_t i = 0; i < n; ++i) { - out << data[i] << '\n'; - } - break; - } - default: - out << "unsupported tensor type for text dump" << '\n'; - return false; - } - - return true; -} - void print_input_tensor_info(const std::string & name, const ov::Tensor & input) { // GPU inputs can be device (USM) tensors, whose data() throws; print a host copy of those. const bool is_remote = input.is(); diff --git a/ggml/src/ggml-openvino/utils.h b/ggml/src/ggml-openvino/utils.h index c4450a387748..270676b07dca 100644 --- a/ggml/src/ggml-openvino/utils.h +++ b/ggml/src/ggml-openvino/utils.h @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -158,6 +159,12 @@ struct ov_runtime_context { std::unordered_map, graph_key_hash> ov_output_names_cache; std::unordered_map, graph_key_hash> ov_input_names_cache_prefill; std::unordered_map, graph_key_hash> ov_output_names_cache_prefill; + // LRU order of decoder_cache's keys, oldest (least recently used) at the front. A pipeline + // that interleaves distinct graph shapes every call -- e.g. DFlash cycling target/draft/ + // injection graphs every round -- needs a slot per shape open at once; a single-entry cache + // would evict and recompile all of them, every call, forever. + std::list lru_keys; + static constexpr size_t max_cached_graphs = 8; size_t stateful_kv_size; std::map kv_state_input_name_map; // compute-only copies of graphs that carry unselected ggml_build_forward_select() branches @@ -169,6 +176,39 @@ struct ov_runtime_context { ov_runtime_context() : device("CPU"), stateful(false), stateful_kv_size(0) {} + // Mark `key` as the most recently used entry. Call on every cache hit and after inserting a + // new entry, so eviction always picks the graph shape that has gone longest unused. + void touch_locked(const graph_key & key) { + lru_keys.remove(key); + lru_keys.push_back(key); + } + + // Drop the least recently used graph shape's compiled model and its associated per-key + // caches. Leaves every other shape's compiled model intact. + void evict_lru_locked() { + if (lru_keys.empty()) { + return; + } + graph_key victim = lru_keys.front(); + lru_keys.pop_front(); + decoder_cache.erase(victim); + infer_request_cache.erase(victim); + infer_request_cache_prefill.erase(victim); + ov_input_names_cache.erase(victim); + ov_output_names_cache.erase(victim); + ov_input_names_cache_prefill.erase(victim); + ov_output_names_cache_prefill.erase(victim); + } + + // Make room for one more graph shape if the cache is at capacity, then mark `key` as most + // recently used. Call right after inserting `key` into decoder_cache. + void admit_locked(const graph_key & key) { + while (decoder_cache.size() > max_cached_graphs) { + evict_lru_locked(); + } + touch_locked(key); + } + void clear_caches_locked() { decoder_cache.clear(); infer_request_cache.clear(); @@ -177,6 +217,7 @@ struct ov_runtime_context { ov_output_names_cache.clear(); ov_input_names_cache_prefill.clear(); ov_output_names_cache_prefill.clear(); + lru_keys.clear(); kv_state_input_name_map.clear(); stateful_kv_size = 0; } @@ -192,10 +233,6 @@ enum ggml_status ov_graph_compute(struct ggml_cgraph * cgraph, ggml_backend_t ba // Releases the cached blobs this process imported (GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR). void ov_clear_imported_blobs(); -size_t checksum(const void * data, size_t size); - -bool save_ggml_tensor_data_to_txt(const ggml_tensor * tensor, const std::string & file_path); - void print_input_tensor_info(const std::string & name, const ov::Tensor & tensor); void print_output_tensor_info(const std::string & name, const ov::Tensor & tensor, const void * output_dst); From 2359d27a3694f220b190e5947684fcd4b3b2340f Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Mon, 23 Nov 2026 15:45:44 +0100 Subject: [PATCH 018/275] ui: name the PWA from the build env and default it to Llama Chat (#32890) The manifest is built in Node by its Vite plugin, where import.meta.env is not set, so it was always named llama-ui whatever VITE_PUBLIC_APP_NAME said. The plugin now names it from the env Vite loaded (.env files included), and the default name is Llama Chat. Assisted-by: Claude (Opus 5.5 Medium) --- ui/apps/chat/.env.example | 2 +- ui/apps/chat/scripts/vite-plugin-pwa-manifest.ts | 16 +++++++++++----- ui/apps/chat/src/lib/constants/app.constants.ts | 2 +- ui/apps/chat/src/lib/constants/pwa.constants.ts | 11 +++++++++++ 4 files changed, 24 insertions(+), 7 deletions(-) diff --git a/ui/apps/chat/.env.example b/ui/apps/chat/.env.example index ed46f9aded97..9760b0dd43fb 100644 --- a/ui/apps/chat/.env.example +++ b/ui/apps/chat/.env.example @@ -1,4 +1,4 @@ -VITE_PUBLIC_APP_NAME='llama-ui' +VITE_PUBLIC_APP_NAME='Llama Chat' VITE_DEBUG='true' VITE_PUBLIC_SERVER_ORIGIN='http://localhost:8033' diff --git a/ui/apps/chat/scripts/vite-plugin-pwa-manifest.ts b/ui/apps/chat/scripts/vite-plugin-pwa-manifest.ts index d6ba3d2aa505..a82eac906eeb 100644 --- a/ui/apps/chat/scripts/vite-plugin-pwa-manifest.ts +++ b/ui/apps/chat/scripts/vite-plugin-pwa-manifest.ts @@ -1,12 +1,11 @@ import { HEADERS } from '../src/lib/constants/headers.constants'; import { PWA_FILE_PATHS, - PWA_MANIFEST, - PWA_MANIFEST_PLUGIN + PWA_MANIFEST_PLUGIN, + pwaManifest } from '../src/lib/constants/pwa.constants'; import type { Plugin } from 'vite'; -const MANIFEST_SOURCE = JSON.stringify(PWA_MANIFEST); // the build writes files relative to its output directory: the path without its leading slash const MANIFEST_FILE = PWA_FILE_PATHS.MANIFEST.slice(1); @@ -15,17 +14,24 @@ const MANIFEST_FILE = PWA_FILE_PATHS.MANIFEST.slice(1); * The adapter copies the client output, so the file lands at the root of the build. */ export function pwaManifestPlugin(): Plugin { + let manifestSource = ''; + return { + // named from the env Vite loaded (.env files too): this module runs in Node, where + // import.meta.env is not set and APP_NAME would fall back to its default + configResolved(config) { + manifestSource = JSON.stringify(pwaManifest(config.env)); + }, configureServer(server) { server.middlewares.use(PWA_FILE_PATHS.MANIFEST, (_req, res) => { res.setHeader(HEADERS.CONTENT_TYPE, PWA_MANIFEST_PLUGIN.CONTENT_TYPE); - res.end(MANIFEST_SOURCE); + res.end(manifestSource); }); }, generateBundle() { if (this.environment.name !== PWA_MANIFEST_PLUGIN.ENVIRONMENT) return; - this.emitFile({ fileName: MANIFEST_FILE, source: MANIFEST_SOURCE, type: 'asset' }); + this.emitFile({ fileName: MANIFEST_FILE, source: manifestSource, type: 'asset' }); }, name: PWA_MANIFEST_PLUGIN.NAME }; diff --git a/ui/apps/chat/src/lib/constants/app.constants.ts b/ui/apps/chat/src/lib/constants/app.constants.ts index c598f480fd4d..8e87264c3afd 100644 --- a/ui/apps/chat/src/lib/constants/app.constants.ts +++ b/ui/apps/chat/src/lib/constants/app.constants.ts @@ -1 +1 @@ -export const APP_NAME = import.meta.env?.VITE_PUBLIC_APP_NAME || 'llama-ui'; +export const APP_NAME = import.meta.env?.VITE_PUBLIC_APP_NAME || 'Llama Chat'; diff --git a/ui/apps/chat/src/lib/constants/pwa.constants.ts b/ui/apps/chat/src/lib/constants/pwa.constants.ts index 734356fb72bc..71e9cbfebdda 100644 --- a/ui/apps/chat/src/lib/constants/pwa.constants.ts +++ b/ui/apps/chat/src/lib/constants/pwa.constants.ts @@ -45,6 +45,10 @@ export const APPLE_ASSETS = { TOUCH_ICON: 'apple-touch-icon-180x180.png' } as const; +/** + * The web app manifest. In the browser APP_NAME follows the env; the manifest plugin runs in + * Node, where import.meta.env is not set, so it names the manifest with pwaManifest(). + */ export const PWA_MANIFEST = { background_color: THEME_COLORS.BACKGROUND_LIGHT, description: 'Local AI chat interface powered by llama.cpp', @@ -68,6 +72,13 @@ export const PWA_MANIFEST = { theme_color: THEME_COLORS.BACKGROUND_LIGHT }; +/** PWA_MANIFEST with the name a build sets (VITE_PUBLIC_APP_NAME) */ +export function pwaManifest(env: Record) { + const name = env.VITE_PUBLIC_APP_NAME || PWA_MANIFEST.name; + + return { ...PWA_MANIFEST, name, short_name: name }; +} + export const PWA_ICON_PATHS = { MASKABLE_512: '/maskable-icon-512x512.png', PWA_64: '/pwa-64x64.png', From a0677c341ba6bbfbbf74fa3c966f4dba74e1c830 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Mon, 23 Nov 2026 15:47:30 +0100 Subject: [PATCH 019/275] ui: use a red edge on the send button's error state (#32856) The error state reused the primary button's edge, which shows as a light ring in dark mode. Use the danger button's edge instead. Assisted-by: Claude (Opus 5.5 Medium) --- .../chat/ChatForm/ChatFormActions/ChatFormActionSubmit.svelte | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionSubmit.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionSubmit.svelte index fa26d6bbc10e..a9682034f529 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionSubmit.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionSubmit.svelte @@ -28,7 +28,7 @@ class={[ 'md:size-8 size-9 rounded-full p-0', showErrorState && - 'bg-surface-danger text-fg-danger hover:bg-surface-danger/80 hover:text-fg-danger disabled:opacity-100' + '[--key-edge:var(--button-danger-edge)] bg-surface-danger text-fg-danger hover:bg-surface-danger/80 hover:text-fg-danger disabled:opacity-100' ]} disabled={isDisabled} type="submit" From 1f3ea67fbf857bb831d3fb9e3a91c0f8ad3fbe78 Mon Sep 17 00:00:00 2001 From: bri-prism <288398250+bri-prism@users.noreply.github.com> Date: Mon, 23 Nov 2026 07:15:34 -0800 Subject: [PATCH 020/275] metal: resolve gpu timeout on iPhone for Bonsai (#31815) --- ggml/src/ggml-metal/ggml-metal.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal.cpp b/ggml/src/ggml-metal/ggml-metal.cpp index 9a1bd2c773a3..aca83e13d59d 100644 --- a/ggml/src/ggml-metal/ggml-metal.cpp +++ b/ggml/src/ggml-metal/ggml-metal.cpp @@ -9,6 +9,8 @@ #include "ggml-metal-ops.h" #include "ggml-metal-tuning.h" +#include + #include #include @@ -653,6 +655,13 @@ static void ggml_backend_metal_graph_optimize(ggml_backend_t backend, ggml_cgrap ggml_metal_graph_optimize(ctx, cgraph); } +// iOS can stop a command buffer that runs for more than a few seconds, so split the graph into shorter ones there +#if TARGET_OS_IPHONE +#define GGML_METAL_DEFAULT_N_CB 8 +#else +#define GGML_METAL_DEFAULT_N_CB 1 +#endif // TARGET_OS_IPHONE + static void ggml_backend_metal_set_n_cb(ggml_backend_t backend, int n_cb) { GGML_ASSERT(ggml_backend_is_metal(backend)); @@ -704,7 +713,7 @@ ggml_backend_t ggml_backend_metal_init(void) { /* .context = */ ctx, }; - ggml_backend_metal_set_n_cb(backend, 1); + ggml_backend_metal_set_n_cb(backend, GGML_METAL_DEFAULT_N_CB); return backend; } @@ -799,7 +808,7 @@ static ggml_backend_t ggml_backend_metal_device_init_backend(ggml_backend_dev_t /* .context = */ ctx, }; - ggml_backend_metal_set_n_cb(backend, 1); + ggml_backend_metal_set_n_cb(backend, GGML_METAL_DEFAULT_N_CB); return backend; From b6d5ce4bc9a3691d26b3207cc6c9c63b732d67e8 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Mon, 23 Nov 2026 16:18:59 +0100 Subject: [PATCH 021/275] ui: drop tool calls cut off by Stop from the next request (#32738) * ui: drop tool calls cut off by Stop from the next request A tool call stopped mid-stream could stay on its message with cut-off arguments. The server parses every call's arguments as JSON, so the next message in that chat ("Continue") failed with "Failed to parse tool call arguments as JSON". Requests now leave such calls out, with the tool results that answer them, and send a call with no arguments as {}. Assisted-by: Claude (Opus 5.5 Medium) * ui: add a demo trace that ends in a stopped tool call A conversation whose last tool call was stopped while its arguments were still streaming, for recording the fix in the previous commit. Assisted-by: Claude (Opus 5.5 Medium) --- ui/apps/chat/demo/fixtures/traces.ts | 40 +++++++++- ui/apps/chat/src/lib/services/chat.service.ts | 8 +- .../src/lib/utils/incomplete-tool-calls.ts | 76 +++++++++++++++++++ .../tests/unit/incomplete-tool-calls.test.ts | 69 +++++++++++++++++ 4 files changed, 190 insertions(+), 3 deletions(-) create mode 100644 ui/apps/chat/src/lib/utils/incomplete-tool-calls.ts create mode 100644 ui/apps/chat/tests/unit/incomplete-tool-calls.test.ts diff --git a/ui/apps/chat/demo/fixtures/traces.ts b/ui/apps/chat/demo/fixtures/traces.ts index dc766458e478..ce673a85e8f9 100644 --- a/ui/apps/chat/demo/fixtures/traces.ts +++ b/ui/apps/chat/demo/fixtures/traces.ts @@ -47,6 +47,17 @@ class Trace { this.push({ content: '', role: 'system', type: 'root' }); } + /** An assistant turn whose tool call was stopped mid-stream: cut-off arguments and no result. */ + stoppedTool(name: string, cutArguments: string, content = ''): this { + const id = uuid(this.name, `call-${this.calls++}`).replaceAll('-', ''); + + return this.push({ + content, + role: 'assistant', + toolCalls: [{ function: { arguments: cutArguments, name }, id, type: 'function' }] + }); + } + toJsonl(): string { const last = this.messages.at(-1)!; const session = { @@ -330,11 +341,38 @@ function diagrams(): Trace { return trace; } +/** A chat whose last tool call was stopped while its arguments were still streaming. */ +function stoppedToolCall(): Trace { + const trace = new Trace('Smoke test for the slides page'); + + trace.user('Write a quick Playwright smoke test for slides.html and run it.'); + trace.stoppedTool( + 'exec_shell_command', + JSON.stringify({ + command: [ + "cat > /tmp/slides-smoke.mjs <<'EOF'", + "import { chromium } from 'playwright';", + '', + 'const browser = await chromium.launch();', + 'const page = await browser.newPage();', + '', + "await page.goto('file:///tmp/slides.html');", + 'EOF', + 'node /tmp/slides-smoke.mjs' + ].join('\n') + }).slice(0, 160), + 'I will write the script to a file and run it.' + ); + + return trace; +} + /** Built-in traces, by name. */ export const DEMO_TRACES: Record Trace> = { 'agentic-debugging': agenticDebugging, diagrams, - 'long-chat': longChat + 'long-chat': longChat, + 'stopped-tool-call': stoppedToolCall }; export function generateTrace(name: string): null | string { diff --git a/ui/apps/chat/src/lib/services/chat.service.ts b/ui/apps/chat/src/lib/services/chat.service.ts index 38c7eba144b1..9d0a146cd989 100644 --- a/ui/apps/chat/src/lib/services/chat.service.ts +++ b/ui/apps/chat/src/lib/services/chat.service.ts @@ -8,6 +8,7 @@ import { getAudioInputFormat } from '../utils/audio-format'; import { capImageDataURLSize } from '../utils/cap-img-size'; +import { dropIncompleteToolCalls } from '../utils/incomplete-tool-calls'; import { API_CHAT, API_SLOTS, @@ -851,8 +852,7 @@ export class ChatService { model?: string | null ): Promise { const options = ChatService.conversionOptionsFor(model); - - return ( + const converted = ( await Promise.all( messages.map((msg) => { if ('id' in msg && 'convId' in msg && 'timestamp' in msg) { @@ -875,6 +875,10 @@ export class ChatService { return true; }); + + // a tool call cut off by Stop can still sit on the message: the server + // would reject the whole request on its arguments + return dropIncompleteToolCalls(converted); } /** diff --git a/ui/apps/chat/src/lib/utils/incomplete-tool-calls.ts b/ui/apps/chat/src/lib/utils/incomplete-tool-calls.ts new file mode 100644 index 000000000000..62ba5806179f --- /dev/null +++ b/ui/apps/chat/src/lib/utils/incomplete-tool-calls.ts @@ -0,0 +1,76 @@ +import { MessageRole } from '#lib/enums/index.ts'; +import type { ApiChatCompletionToolCall, ApiChatMessageData } from '#lib/types/api.d.ts'; + +const EMPTY_ARGUMENTS = '{}'; + +/** + * Drop the tool calls a stopped stream left with cut-off arguments, and the + * tool results that answer them. The server parses every call's arguments as + * JSON and rejects the whole request when one doesn't parse, so a call cut + * off mid-stream would otherwise break every request after it. A call with + * no arguments at all is kept and sent with `{}`. + */ +export function dropIncompleteToolCalls(messages: ApiChatMessageData[]): ApiChatMessageData[] { + const droppedIds = new Set(); + const result: ApiChatMessageData[] = []; + + for (const message of messages) { + if ( + message.role === MessageRole.TOOL && + message.tool_call_id && + droppedIds.has(message.tool_call_id) + ) { + continue; + } + + if (!message.tool_calls?.length) { + result.push(message); + + continue; + } + + const calls = message.tool_calls; + const kept: ApiChatCompletionToolCall[] = []; + + for (const call of calls) { + const sendable = sendableToolCall(call); + + if (sendable) { + kept.push(sendable); + } else if (call.id) { + droppedIds.add(call.id); + } + } + + if (kept.length === calls.length && kept.every((call, i) => call === calls[i])) { + result.push(message); + + continue; + } + + const { tool_calls: _dropped, ...rest } = message; + + result.push(kept.length > 0 ? { ...rest, tool_calls: kept } : rest); + } + + return result; +} + +/** The call as it can be sent, or null when its name or arguments were cut off. */ +function sendableToolCall(call: ApiChatCompletionToolCall): ApiChatCompletionToolCall | null { + if (!call.function?.name) return null; + + const args = call.function.arguments; + + if (!args?.trim()) { + return { ...call, function: { ...call.function, arguments: EMPTY_ARGUMENTS } }; + } + + try { + JSON.parse(args); + + return call; + } catch { + return null; + } +} diff --git a/ui/apps/chat/tests/unit/incomplete-tool-calls.test.ts b/ui/apps/chat/tests/unit/incomplete-tool-calls.test.ts new file mode 100644 index 000000000000..f287b1cbf798 --- /dev/null +++ b/ui/apps/chat/tests/unit/incomplete-tool-calls.test.ts @@ -0,0 +1,69 @@ +import { MessageRole } from '#lib/enums/index.ts'; +import type { ApiChatCompletionToolCall, ApiChatMessageData } from '#lib/types/api.d.ts'; +import { dropIncompleteToolCalls } from '#lib/utils/incomplete-tool-calls.ts'; +import { describe, expect, it } from 'vitest'; + +function call(id: string, args: string, name = 'exec_shell_command'): ApiChatCompletionToolCall { + return { function: { arguments: args, name }, id, type: 'function' }; +} + +const CUT = '{"command": "cd /repo && cat > /tmp/x.mjs <<\'EOF\'\\nimport'; + +describe('dropIncompleteToolCalls', () => { + it('leaves complete tool calls and their results alone', () => { + const messages: ApiChatMessageData[] = [ + { content: 'run it', role: MessageRole.USER }, + { content: '', role: MessageRole.ASSISTANT, tool_calls: [call('a', '{"command":"ls"}')] }, + { content: 'file.txt', role: MessageRole.TOOL, tool_call_id: 'a' } + ]; + const result = dropIncompleteToolCalls(messages); + + expect(result).toEqual(messages); + expect(result[1]).toBe(messages[1]); + }); + + it('drops a call whose arguments were cut off, keeping the text of the message', () => { + const result = dropIncompleteToolCalls([ + { + content: 'Let me write the script.', + role: MessageRole.ASSISTANT, + tool_calls: [call('a', CUT)] + }, + { content: 'Continue', role: MessageRole.USER } + ]); + + expect(result).toEqual([ + { content: 'Let me write the script.', role: MessageRole.ASSISTANT }, + { content: 'Continue', role: MessageRole.USER } + ]); + }); + + it('keeps the complete calls of a message and drops the results of the cut one', () => { + const result = dropIncompleteToolCalls([ + { + content: '', + role: MessageRole.ASSISTANT, + tool_calls: [call('a', '{"command":"ls"}'), call('b', CUT)] + }, + { content: 'file.txt', role: MessageRole.TOOL, tool_call_id: 'a' }, + { content: 'error', role: MessageRole.TOOL, tool_call_id: 'b' } + ]); + + expect(result).toEqual([ + { content: '', role: MessageRole.ASSISTANT, tool_calls: [call('a', '{"command":"ls"}')] }, + { content: 'file.txt', role: MessageRole.TOOL, tool_call_id: 'a' } + ]); + }); + + it('drops a call with no name and sends a call with no arguments as {}', () => { + const result = dropIncompleteToolCalls([ + { + content: '', + role: MessageRole.ASSISTANT, + tool_calls: [call('a', '{}', ''), call('b', '', 'list_tasks')] + } + ]); + + expect(result[0].tool_calls).toEqual([call('b', '{}', 'list_tasks')]); + }); +}); From 27d0a1fc73f3a50bc32e13d13e163e462cc37316 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Mon, 23 Nov 2026 16:20:15 +0100 Subject: [PATCH 022/275] ui: unmount a closed collapsible's body after one transition (#32881) bits-ui rebuilds the Collapsible.Content snippet args when its close transition ends, which re-ran the region's effect and restarted the unmount timer, so a closed body stayed mounted for two transitions instead of one. Reading `open` through a derived keeps the effect from rerunning when only the args object changes. Assisted-by: Claude (Opus 5.5 Medium) --- .../components/ui/collapsible/collapsible-region.svelte | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/ui/lib/ui/src/lib/components/ui/collapsible/collapsible-region.svelte b/ui/lib/ui/src/lib/components/ui/collapsible/collapsible-region.svelte index 9910753395da..f56af787a7e7 100644 --- a/ui/lib/ui/src/lib/components/ui/collapsible/collapsible-region.svelte +++ b/ui/lib/ui/src/lib/components/ui/collapsible/collapsible-region.svelte @@ -18,8 +18,11 @@ // svelte-ignore state_referenced_locally let contentMounted = $state(open); + // bits-ui rebuilds the snippet args (with `open`) when its transition ends; the derived keeps that from restarting the unmount timer + const isOpen = $derived(open); + $effect(() => { - if (open) { + if (isOpen) { contentMounted = true; return; @@ -31,7 +34,7 @@ }); -
+
{#if contentMounted}
{@render children?.()} From 1094646c1fb706b0bc7cf3569c707a173032a01d Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Mon, 23 Nov 2026 16:21:45 +0100 Subject: [PATCH 023/275] ui: set code in messages at the size of the text around it (#32892) Inline code and code blocks were 14px next to 16px text. Llama Mono has Llama Sans's x-height, so the two read as one size without the mono being scaled down. The chat form's editor follows. Assisted-by: Claude (Opus 5.5 Medium) --- .../app/content/MarkdownContent/markdown-content.css | 11 ++++++----- .../app/content/MarkdownEditor/MarkdownEditor.svelte | 3 +-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-content.css b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-content.css index 5e894d0ae822..ed0bc932c29b 100644 --- a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-content.css +++ b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-content.css @@ -17,7 +17,7 @@ overflow-x: visible; border-radius: 0; border: none; - font-size: 0.875rem; + font-size: 1em; } /* Base typography styles */ @@ -92,13 +92,14 @@ opacity: 0.7; } -/* Inline code */ +/* Inline code. Code is set at the size of the text around it, here and in the blocks below: Llama Mono + has Llama Sans's x-height, so the two read as one size without the mono being scaled down. */ .markdown-content :global(code:not(pre code)) { background: var(--surface-muted); color: var(--fg-muted); padding: 0.125rem 0.375rem; border-radius: 0.375rem; - font-size: 0.875rem; + font-size: 1em; } .markdown-content :global(pre) { @@ -358,7 +359,7 @@ div.markdown-user-content :global(.table-wrapper) { margin: 0; border-radius: 0; border: none; - font-size: 0.875rem; + font-size: 1em; } /* Mentions and hashtags */ @@ -761,7 +762,7 @@ div.markdown-user-content :global(.table-wrapper) { margin: 0; border-radius: 0; border: none; - font-size: 0.875rem; + font-size: 1em; } .markdown-content :global([data-view-mode='source'] .mermaid-scroll-container), diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/MarkdownEditor.svelte b/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/MarkdownEditor.svelte index 7564574828cb..3d5e0103ec82 100644 --- a/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/MarkdownEditor.svelte +++ b/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/MarkdownEditor.svelte @@ -89,7 +89,7 @@ { fontStyle: 'italic', tag: tags.emphasis }, { color: 'var(--fg-muted)', fontStyle: 'italic', tag: tags.quote }, { opacity: '0.7', tag: tags.strikethrough, textDecoration: 'line-through' }, - { fontFamily: 'var(--font-mono)', fontSize: '0.875rem', tag: tags.monospace } + { fontFamily: 'var(--font-mono)', tag: tags.monospace } ]); // The markdown language alone: markdown() would also bring the html, css and @@ -389,7 +389,6 @@ div :global(.cm-md-raw-code) { padding-inline: 1rem; font-family: var(--font-mono); - font-size: 0.875rem; background: var(--surface-code); border-inline: 1px solid color-mix(in oklch, var(--line-default) 30%, transparent); } From 325914defd2c1279a039366d999dff4c19a75b54 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Mon, 23 Nov 2026 17:24:05 +0100 Subject: [PATCH 024/275] ui: show an agentic reply as a grouped Agent Trace (#32879) * ui: show tool calls in the trace as a grouped, plain-language log Tool calls and all the reasoning around them, up to the answer, collapse into one row whose title sums up what happened ("Ran 2 commands, read 1 file"), so a model that thinks before every call still reads as one row of work. Two calls, or one call with reasoning beside it, make a group; without per-turn stats a group spans turns. Each call reads as a sentence: built-in tools get hand-written phrasing in two tenses, MCP and unknown tools read as "Used ", and the generic block shows simple arguments as labelled fields. A call that has the argument a display setting picks (description by default, overridable per tool in Settings > Tools) shows it as the model wrote it instead, for any tool that declares it. A shell row always shows the command, after "Ran" or after that description, and opens into the terminal; the permission card shows the command that would run. An open group is a list of rows under one rule, with no icons in the headings; a running row shimmers. While a group is live its title says what is happening now ("Reading package.json", "Thinking"), with a timer since the prompt was sent, and the loop records the task's total time, which the response stats show. Thoughts and tool calls now stay collapsed while generating, with a one-time migration of the saved old default. Assisted-by: Claude (Opus 5.5 Medium) * ui: keep a live reply steady while its status changes The status line ( Loading weights, Processing 40% ) sat above the content before the first token and below it afterwards, and collapsed to nothing while tokens streamed, so the stats and actions under it jumped. It is now one row in the trace column with a trace row's box, shown only while nothing else is moving, and while a tool group closes the reply it becomes that group's live title instead. The model badge shows from the start of a live reply, the user message reserves its stats row while the prompt is processed, and a collapsed group title is muted. Assisted-by: Claude (Opus 5.5 Medium) * ui: glide a sent message to the top of the screen Sending snapped the page to its bottom in one frame, and layout that settled a moment later was followed with more snaps. The page now eases there: the target is read again every frame, so late layout bends the motion instead of ending it with a jump, and corrections shortly after a send are glided to as well. A frame that arrives late counts as one frame, so a busy page slows the glide instead of skipping it. Wheel, touch and scroll keys hand the page back at once; typing the next message does not. Reduced motion keeps the jump. Assisted-by: Claude (Opus 5.5 Medium) * ui: show tool images in the trace and in one slideshow of the thread A closed tool group shows every image its calls produced under its title, 64px tall at their own proportions, in a carousel once they overflow; the strip fades out when the group opens. A call with images shows tiny thumbnails beside its title while its row is closed. A group thumbnail, or an image in a user message, opens one slideshow of every image, audio clip and video in the open thread, in thread order, at the clicked item. Assisted-by: Claude (Opus 5.5 Medium) * ui: quiet the conversation around its messages Stats and actions under earlier messages stay hidden until the reader points at the message or tabs into it, changing only opacity so nothing moves; the latest exchange keeps them in view and touch screens keep them shown. A Display setting, Always show message statistics, keeps every message's statistics in view. With them out of sight the spacing tightens: messages sit 1rem apart, the answer sits 0.75rem from the trace rows around it, and the user message's stats and actions sit closer together. A queued message no longer sticks to the bottom of the screen and scrolls with the conversation. Assisted-by: Claude (Opus 5.5 Medium) * ui: name the agentic reply an Agent Trace and give basic chat its own view A reply that ran the agentic loop is now an Agent Trace: the component that renders it is ChatMessageAgentTrace, with matching class names and docs. A basic chat reply, with no tool calls, renders through the new ChatMessageAssistantResponse as its reasoning and its answer, without the trace's grouping, timer and permission handling. hasAgenticContent picks the view, so a live reply becomes a trace the moment its first tool call streams in. Assisted-by: Claude (Opus 5.5 Medium) --- ui/apps/chat/src/app.css | 24 + .../ChatAttachmentsList.svelte | 17 +- .../ChatMessageAssistant.svelte | 99 ++-- .../ChatMessageAssistantProcessingInfo.svelte | 24 +- .../ChatMessageAssistantResponse.svelte | 108 +++++ .../ChatMessageToolCallBlockDefault.svelte | 40 +- .../ChatMessageToolCallBlockEditFile.svelte | 48 +- ...essageToolCallBlockExecShellCommand.svelte | 174 ++++--- ...tMessageToolCallBlockFileGlobSearch.svelte | 6 +- ...ChatMessageToolCallBlockGetDatetime.svelte | 4 +- .../ChatMessageToolCallBlockGetInfo.svelte | 10 +- .../ChatMessageToolCallBlockGrepSearch.svelte | 4 +- .../ChatMessageToolCallBlockReadFile.svelte | 23 +- .../ChatMessageToolCallBlockReadMedia.svelte | 9 +- ...atMessageToolCallBlockRunJavascript.svelte | 4 +- ...atMessageToolCallBlockSearchResults.svelte | 17 +- .../ChatMessageToolCallBlockWriteFile.svelte | 25 +- .../ChatMessageToolCallGroup.svelte | 122 +++++ .../ChatMessageToolCall/ToolCallBlock.svelte | 124 +++-- .../ToolCallElapsed.svelte | 36 ++ .../ChatMessageToolCall/ToolCallTitle.svelte | 32 ++ .../ChatMessageToolCall/parsers/edit-file.ts | 39 +- .../parsers/tool-call-phrasing.ts | 445 ++++++++++++++++++ .../ChatMessageToolCall/tool-call-elapsed.ts | 28 ++ .../ChatMessageUser/ChatMessageUser.svelte | 28 +- .../ChatMessageUserBubble.svelte | 1 + .../ChatMessageUserPending.svelte | 2 +- .../ChatMessageActionCard.svelte | 10 +- ...tMessageActionCardPermissionRequest.svelte | 14 +- .../ChatMessages/ChatMessageAgentTrace.svelte | 410 ++++++++++++++++ .../ChatMessageAgenticContent.svelte | 273 ----------- .../ChatMessageReasoningBlock.svelte | 4 +- .../ChatMessageStatistics.svelte | 29 +- .../app/chat/ChatMessages/ChatMessages.svelte | 6 +- .../app/chat/ChatScreen/ChatScreen.svelte | 5 +- .../ChatScreenDialogsAndAlerts.svelte | 9 + .../chat/src/lib/components/app/chat/index.ts | 47 +- .../content/CollapsibleContentBlock.svelte | 57 ++- .../src/lib/components/app/content/index.ts | 4 + .../SettingsChat/SettingsChatToolsTab.svelte | 106 ++++- .../lib/constants/css-classes.constants.ts | 3 - ui/apps/chat/src/lib/constants/index.ts | 1 + .../lib/constants/settings-keys.constants.ts | 3 + .../src/lib/constants/settings.constants.ts | 29 +- .../constants/tool-call-phrasing.constants.ts | 175 +++++++ ui/apps/chat/src/lib/enums/index.ts | 1 + ui/apps/chat/src/lib/enums/tools.enums.ts | 13 + .../lib/hooks/use-stick-to-bottom.svelte.ts | 204 +++++++- .../src/lib/services/migration.service.ts | 37 +- .../src/lib/stores/agentic/gates.svelte.ts | 18 +- .../src/lib/stores/agentic/index.svelte.ts | 30 +- ui/apps/chat/src/lib/stores/index.ts | 3 + .../chat/src/lib/stores/mcp/index.svelte.ts | 1 + .../src/lib/stores/media-gallery.svelte.ts | 52 ++ ui/apps/chat/src/lib/types/agentic.d.ts | 14 +- ui/apps/chat/src/lib/types/chat.d.ts | 2 + ui/apps/chat/src/lib/types/index.ts | 3 + ui/apps/chat/src/lib/types/tools.d.ts | 31 +- ui/apps/chat/src/lib/utils/agentic.ts | 31 ++ ui/apps/chat/src/lib/utils/attachment-type.ts | 19 + ui/apps/chat/src/lib/utils/index.ts | 13 +- ui/apps/chat/src/lib/utils/memoize-bounded.ts | 28 ++ .../chat/src/lib/utils/tool-call-shown-arg.ts | 39 ++ ui/apps/chat/tests/client/README-perf.md | 2 +- .../client/agentic-stream.perf.svelte.test.ts | 2 +- .../client/assistant-response.svelte.test.ts | 63 +++ .../components/AgenticPerfWrapper.svelte | 4 +- ...xec-shell-command-streaming.svelte.test.ts | 48 +- .../tests/client/media-gallery.svelte.test.ts | 75 +++ .../permission-request-command.svelte.test.ts | 67 +++ .../client/stick-to-bottom.svelte.test.ts | 102 +++- .../tests/client/task-timer.svelte.test.ts | 84 ++++ .../tool-call-in-progress.svelte.test.ts | 16 +- .../ChatMessageToolCallBlock.stories.svelte | 5 + .../ChatMessageToolCallGroup.stories.svelte | 70 +++ .../messages/ToolCallGroupStoryHost.svelte | 46 ++ .../tests/stories/chat/messages/fixtures.ts | 67 +++ .../settings-tool-call-in-progress.test.ts | 6 +- .../tests/unit/tool-call-phrasing.test.ts | 344 ++++++++++++++ .../tests/unit/tool-call-shown-arg.test.ts | 38 ++ 80 files changed, 3595 insertions(+), 661 deletions(-) create mode 100644 ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantResponse.svelte create mode 100644 ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte create mode 100644 ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte create mode 100644 ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallTitle.svelte create mode 100644 ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts create mode 100644 ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/tool-call-elapsed.ts create mode 100644 ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte delete mode 100644 ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgenticContent.svelte create mode 100644 ui/apps/chat/src/lib/constants/tool-call-phrasing.constants.ts create mode 100644 ui/apps/chat/src/lib/stores/media-gallery.svelte.ts create mode 100644 ui/apps/chat/src/lib/utils/memoize-bounded.ts create mode 100644 ui/apps/chat/src/lib/utils/tool-call-shown-arg.ts create mode 100644 ui/apps/chat/tests/client/assistant-response.svelte.test.ts create mode 100644 ui/apps/chat/tests/client/media-gallery.svelte.test.ts create mode 100644 ui/apps/chat/tests/client/permission-request-command.svelte.test.ts create mode 100644 ui/apps/chat/tests/client/task-timer.svelte.test.ts create mode 100644 ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallGroup.stories.svelte create mode 100644 ui/apps/chat/tests/stories/chat/messages/ToolCallGroupStoryHost.svelte create mode 100644 ui/apps/chat/tests/unit/tool-call-phrasing.test.ts create mode 100644 ui/apps/chat/tests/unit/tool-call-shown-arg.test.ts diff --git a/ui/apps/chat/src/app.css b/ui/apps/chat/src/app.css index 24ba6cec44bb..03e0e7d27424 100644 --- a/ui/apps/chat/src/app.css +++ b/ui/apps/chat/src/app.css @@ -388,3 +388,27 @@ .stick-to-bottom-pin { height: 1px; } + +/* + * A message's stats and actions stay out of the way until the reader points at + * it or tabs into it. Only opacity changes, so their room is kept and nothing + * moves when they appear. Touch screens have no hover, so they keep them shown. + */ +@media (hover: hover) { + .message-meta { + opacity: 0; + transition: opacity 150ms ease-out; + } + + .chat-message-user:hover .message-meta, + .chat-message-assistant:hover .message-meta, + .message-meta:focus-within { + opacity: 1; + } +} + +@media (hover: hover) and (prefers-reduced-motion: reduce) { + .message-meta { + transition: none; + } +} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsList.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsList.svelte index cc9b940df6de..611e52a75e40 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsList.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsList.svelte @@ -6,8 +6,14 @@ ScrollCarousel } from '#lib/components/app/index.ts'; import { ScrollCarouselVariant } from '#lib/enums/index.ts'; + import { mediaGalleryStore } from '#lib/stores/index.ts'; import type { DatabaseMessageExtraMcpResource } from '#lib/types/index.ts'; - import { getAttachmentDisplayItems, isMcpPrompt, isMcpResource } from '#lib/utils/index.ts'; + import { + getAttachmentDisplayItems, + isMcpPrompt, + isMcpResource, + isMediaExtra + } from '#lib/utils/index.ts'; interface Props { class?: string; @@ -26,12 +32,15 @@ limitToSingleRow?: boolean; // For vision modality check activeModelId?: string; + /** A message's attachments: media opens the conversation's slideshow at it */ + conversationGallery?: boolean; } let { activeModelId, attachments = [], class: className = '', + conversationGallery = false, // Default to small size for form previews imageClass = '', imageHeight = 'h-24', @@ -55,6 +64,12 @@ event?.stopPropagation(); event?.preventDefault(); + if (conversationGallery && item.attachment && isMediaExtra(item.attachment)) { + mediaGalleryStore.show(item.attachment); + + return; + } + // Find the index of the clicked item among non-MCP attachments const nonMcpItems = displayItems.filter((i) => !isMcpPrompt(i) && !isMcpResource(i)); const index = nonMcpItems.findIndex((i) => i.id === item.id); diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte index 72679c8f1238..5a5b3cd92a5f 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte @@ -1,20 +1,21 @@ -
-
- - {modelLoadingText ?? - processingState.getPromptProgressText() ?? - processingState.getProcessingMessage() ?? - 'Processing...'} - -
+
+ {text}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantResponse.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantResponse.svelte new file mode 100644 index 000000000000..259da9a9a2f3 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantResponse.svelte @@ -0,0 +1,108 @@ + + +
+ {#each sections as section, index (index)} + {#if section.type === AgenticSectionType.TEXT} +
+ +
+ {:else if section.type === AgenticSectionType.REASONING || section.type === AgenticSectionType.REASONING_PENDING} + toggleExpanded(index, section)} + open={isExpanded(index, section)} + {section} + /> + {/if} + {/each} + + {#if showStatus} + + {/if} +
+ + diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockDefault.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockDefault.svelte index f959d00285db..0cbe86535a22 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockDefault.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockDefault.svelte @@ -3,7 +3,9 @@ // Renders section.toolArgs / section.toolResult directly using the // shared chrome shell. + import { simpleToolArgFields } from './parsers/tool-call-phrasing'; import ToolCallBlock from './ToolCallBlock.svelte'; + import ToolCallTitle from './ToolCallTitle.svelte'; import { Loader2 } from '@lucide/svelte'; import { MarkdownContent, SyntaxHighlightedCode } from '#lib/components/app/index.ts'; import { MAX_HEIGHT_CODE_BLOCK } from '#lib/constants/index.ts'; @@ -13,7 +15,6 @@ import { classifyToolResult, formatJsonPretty, - getToolUi, parseToolResultWithMedia } from '#lib/utils/index.ts'; @@ -27,14 +28,31 @@ let { attachments, isStreaming, onToggle, open, section }: Props = $props(); - const title = $derived(getToolUi(section.toolName)?.label ?? section.toolName ?? ''); + const argFields = $derived(simpleToolArgFields(section.toolArgs)); const outputKind = $derived(classifyToolResult(section.toolResult)); const parsedLines: ToolResultLine[] = $derived( section.toolResult ? parseToolResultWithMedia(section.toolResult, attachments) : [] ); - +{#snippet inputFields(fields: { label: string; value: string }[])} +
+ {#each fields as field, i (i)} +
{field.label}
+ +
{field.value}
+ {/each} +
+{/snippet} + + + {#snippet titleSnippet(phrase)} + + {/snippet} + {#snippet children(_meta, ctx)} {#if ctx.isStreamingCall}
@@ -70,12 +88,16 @@ Input
- + {#if argFields} + {@render inputFields(argFields)} + {:else} + + {/if} {/if}
- import { parseEditFileMeta, parseEditFileTitleMeta } from './parsers/edit-file'; + import { + editFileDiffStats, + parseEditFileMeta, + parseEditFileTitleMeta + } from './parsers/edit-file'; import ToolCallBlock from './ToolCallBlock.svelte'; + import ToolCallTitle from './ToolCallTitle.svelte'; import { XCircle } from '@lucide/svelte'; import { SyntaxHighlightedCode } from '#lib/components/app/index.ts'; import { MAX_HEIGHT_CODE_BLOCK, RESULT_STAT_SEPARATOR } from '#lib/constants/index.ts'; - import { FileTypeText } from '#lib/enums/index.ts'; + import { AgenticSectionType, FileTypeText } from '#lib/enums/index.ts'; import { toolsStore } from '#lib/stores/index.ts'; import type { AgenticSection } from '#lib/types/index.ts'; import { @@ -24,7 +29,7 @@ let { isStreaming, onToggle, open, section }: Props = $props(); const editFileMeta = $derived(parseEditFileTitleMeta(section)); - // body-only: the full meta parses the embedded edit strings, and these + // body-only: the full meta parses the embedded edit strings, and these two // deriveds are read solely from the children snippet, which renders only // while the block is expanded const editFileBody = $derived(parseEditFileMeta(section)); @@ -32,23 +37,36 @@ const editDiffs = $derived( (editFileBody?.edits ?? []).map((edit) => computeLineDiff(edit.oldText, edit.newText)) ); + + // Lines added and removed, for the title once the edit has applied. The + // title always renders and sections are rebuilt on every streamed chunk, + // so the parse and diff are remembered per call instead of re-run each time. + const diffStats = $derived( + section.type === AgenticSectionType.TOOL_CALL && section.toolResult + ? editFileDiffStats(section) + : null + ); - {#snippet titleSnippet()} - - Edit file - - - - {abbreviateHome(editFileMeta?.filePath ?? '', home)} + {#snippet titleSnippet(phrase)} + + {#if diffStats} + + +{diffStats.added} + + -{diffStats.removed} + {/if} - {#if editFileMeta?.errorMessage} - (failed) - {/if} - - + {#if editFileMeta?.errorMessage} + (failed) + {/if} + {/snippet} {#snippet children(_meta, ctx)} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockExecShellCommand.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockExecShellCommand.svelte index 06d417f7aa41..d795356138cf 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockExecShellCommand.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockExecShellCommand.svelte @@ -1,15 +1,15 @@ -{#snippet execShellTitle()} +{#snippet promptLine()} {#if cwd} {wdDisplay} - - $ {/if} + $ + {#if highlightedCommandHtml} {@html highlightedCommandHtml} {:else} @@ -239,73 +239,98 @@ {onToggle} {open} {section} - spinIconWhenActive={true} - wrapper={CollapsibleTerminalBlock} > - {#snippet titleSnippet()} - {@render execShellTitle()} + {#snippet titleSnippet(phrase)} + + + {phrase.label} + + {#if execShellMeta?.command} + + {execShellMeta.command} + + {/if} + {/snippet} {#snippet children(_meta, ctx)} - {#if (ctx.isPending && !commandStreaming) || (isLive && !section.toolResult)} -
- - Executing command... -
- {:else if ctx.isInterrupted} -
- - - Command interrupted before it returned output +
+
+ {@render promptLine()}
- {:else if execShellError} -
- - {execShellError} -
- {:else if section.toolResult} -
- {#each outputLines as line, i (i)} -
{line.text}
- - {#if line.media?.type === AttachmentType.IMAGE} - {line.media.name} - {/if} - {/each} + {#if (ctx.isPending && !commandStreaming) || (isLive && !section.toolResult)} +
+ + Executing command... +
+ {:else if ctx.isInterrupted} +
+ + + Command interrupted before it returned output +
+ {:else if execShellError} +
+ + + {execShellError} +
+ {:else if section.toolResult} +
+ {#each outputLines as line, i (i)} +
+ {line.text} +
+ + {#if line.media?.type === AttachmentType.IMAGE} + {line.media.name} + {/if} + {/each} - {#if isExitCodeFinalLine && execShellExitStatus} -
- {#if execShellExitStatus.timedOut} - + {#if isExitCodeFinalLine && execShellExitStatus} +
+ {#if execShellExitStatus.timedOut} + - timed out + timed out - · + · - exit {execShellExitStatus.code} - {:else if execShellExitStatus.code === 0} - + exit {execShellExitStatus.code} + {:else if execShellExitStatus.code === 0} + - exit 0 - {:else} - + exit 0 + {:else} + - exit {execShellExitStatus.code} - {/if} -
- {/if} -
- {/if} + exit {execShellExitStatus.code} + {/if} +
+ {/if} +
+ {/if} +
{/snippet} @@ -343,6 +368,29 @@ } } + .exec-title-command { + color: var(--fg-muted); + font-size: 0.92em; + } + + .terminal-frame { + display: grid; + gap: 0.5rem; + min-width: 0; + padding: 0.625rem 0.75rem; + border-radius: var(--radius-md, 0.375rem); + background: var(--surface-code); + border: 1px solid color-mix(in oklch, var(--line-default) 30%, transparent); + } + + .exec-prompt-line { + word-break: break-word; + } + + .exec-prompt-line :global(.font-mono) { + white-space: pre-wrap; + } + .terminal-output.is-clamped { max-height: 28rem; overflow-y: auto; diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockFileGlobSearch.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockFileGlobSearch.svelte index 67c5e15c348d..f2da8cbf7e52 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockFileGlobSearch.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockFileGlobSearch.svelte @@ -20,11 +20,9 @@ - {#snippet titleSnippet()} + {#snippet titleSnippet(phrase)} {#if fileGlobMeta} - {fileGlobMeta.include === '**' ? 'List files' : 'Search files'}  + {phrase.label}  {#if fileGlobMeta.include !== '**'} {fileGlobMeta.include} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetDatetime.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetDatetime.svelte index efcec2a3fced..0b3486b7e479 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetDatetime.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetDatetime.svelte @@ -1,5 +1,5 @@
- - {#if showSpinner} Current time diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte index 3b68a2d85d05..bfc1aff976f7 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte @@ -48,15 +48,7 @@ const cwdDisplay = $derived(abbreviateHome(infoMeta.cwd ?? '', home)); - + {#snippet children(meta, _ctx)} {#if meta?.errorMessage}
- {#snippet titleSnippet()} + {#snippet titleSnippet(phrase)} {#if grepMeta} - Search for  + {phrase.label}  {grepMeta.pattern} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadFile.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadFile.svelte index e8c424605b61..eefdc0021f88 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadFile.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadFile.svelte @@ -1,6 +1,7 @@ - {#snippet titleSnippet()} - - Read file - - - {readFileMeta?.fileName} - - {#if readFileMeta?.lineRange} - - (lines {readFileMeta.lineRange.start}-{readFileMeta.lineRange.end}) - - {/if} - - + {#snippet titleSnippet(phrase)} + + {#if readFileMeta?.lineRange} + + (lines {readFileMeta.lineRange.start}-{readFileMeta.lineRange.end}) + + {/if} + {/snippet} {#snippet children(_meta, _ctx)} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadMedia.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadMedia.svelte index 3961b86d0c2c..1091b8dcbbb9 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadMedia.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadMedia.svelte @@ -1,6 +1,7 @@ - {#snippet titleSnippet()} - - Read media - - {readMediaMeta?.fileName} - + {#snippet titleSnippet(phrase)} + {/snippet} {#snippet children(_meta, _ctx)} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockRunJavascript.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockRunJavascript.svelte index 2fd1866f3d29..e20a4f4bae3c 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockRunJavascript.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockRunJavascript.svelte @@ -6,7 +6,6 @@ import { MAX_HEIGHT_CODE_BLOCK } from '#lib/constants/index.ts'; import { FileTypeText } from '#lib/enums/index.ts'; import type { AgenticSection } from '#lib/types/index.ts'; - import { getToolUi } from '#lib/utils/index.ts'; interface Props { section: AgenticSection; @@ -18,10 +17,9 @@ let { isStreaming, onToggle, open, section }: Props = $props(); const runJsMeta = $derived(parseRunJavascriptMeta(section)); - const title = $derived(getToolUi(section.toolName)?.label ?? section.toolName ?? ''); - + {#snippet children(meta, ctx)} {#if ctx.isPending}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockSearchResults.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockSearchResults.svelte index 78fba40f98f8..efbbde97446a 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockSearchResults.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockSearchResults.svelte @@ -2,7 +2,6 @@ import * as HoverCard from '@ggml-org/llama-ui/ui/hover-card'; import { Globe, Loader2 } from '@lucide/svelte'; import { CollapsibleContentBlock } from '#lib/components/app/index.ts'; - import { ICON_CLASS_DEFAULT, ICON_CLASS_SPIN } from '#lib/constants/index.ts'; import { AgenticSectionType } from '#lib/enums/index.ts'; import { mcpStore } from '#lib/stores/index.ts'; import type { AgenticSection, SearchResult } from '#lib/types/index.ts'; @@ -30,13 +29,6 @@ const results = $derived(extractSearchResults(section.toolResult)); const query = $derived(extractSearchQuery(section.toolArgs)); - // Same icon-resolution chain as ChatMessageToolCallBlockDefault so - // MCP-server branding is consistent across both views. Spinner wins - // while the call is in flight so the user sees execution status. - const iconUrl = $derived(showSpinner ? null : mcpStore.getServerFaviconForTool(section.toolName)); - const icon = $derived(showSpinner ? Loader2 : undefined); - const iconClass = $derived(showSpinner ? ICON_CLASS_SPIN : ICON_CLASS_DEFAULT); - // Verb reflects state: "Searching" while the call is in flight, "Searched" // once results (or a definitive empty response) have arrived. Lets the // heading read as a live progress indicator rather than a completed @@ -154,7 +146,14 @@ {/if} {/snippet} - + {#if results.length > 0}
{#each results as result (result.url)} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockWriteFile.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockWriteFile.svelte index 394287ec1aca..c0fdfa8ed8db 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockWriteFile.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockWriteFile.svelte @@ -1,6 +1,7 @@ - {#snippet titleSnippet()} - - Write file - - - - {abbreviateHome(writeFileMeta?.filePath ?? '', home)} - - - {#if writeFileMeta?.errorMessage} - (failed) - {/if} - - + {#snippet titleSnippet(phrase)} + + {#if writeFileMeta?.errorMessage} + (failed) + {/if} + {/snippet} {#snippet children(_meta, ctx)} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte new file mode 100644 index 000000000000..3f8acb39ec2e --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte @@ -0,0 +1,122 @@ + + +
+ + {#snippet titleSnippet()} + + + {summary} + + {/snippet} + + {#snippet titleSuffix()} + {#if elapsedStartedAt !== null} + + {/if} + {/snippet} + +
+ {@render children()} +
+
+ + + {#if images.length > 0 && !open} +
+ + {#each images as image, i (i)} + + {/each} + +
+ {/if} +
+ + diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte index cafb077e5366..f8f9ee05be45 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte @@ -1,22 +1,27 @@ - + {#snippet titleSnippet()} + {#if blockTitle} + {@render blockTitle(phrase)} + {:else} + {title ?? formatToolCallLine(phrase)} + {/if} + {/snippet} + + {#snippet titleSuffix()} + {#if elapsedStart !== null} + + {/if} + + {#if images.length > 0 && !open} + + {#each images as image, i (i)} + + {/each} + + {/if} + {/snippet} + {@render children(meta, { isCodeStreaming, isInterrupted, @@ -148,4 +168,4 @@ isStreaming, isStreamingCall })} - + diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte new file mode 100644 index 000000000000..b83c74933036 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte @@ -0,0 +1,36 @@ + + + + {label} + diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallTitle.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallTitle.svelte new file mode 100644 index 000000000000..c16e0cdd85fe --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallTitle.svelte @@ -0,0 +1,32 @@ + + + + {label} + + {#if target || children} + + {#if target} + {target} + {/if} + + {@render children?.()} + + {/if} + diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts index 006ea186f405..72c1306a71af 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts @@ -11,14 +11,14 @@ import { parseToolArgs } from './_shared'; import { TOOL_ARG_PATH_KEYS } from '#lib/constants/index.ts'; -import { BuiltInTool } from '#lib/enums/index.ts'; +import { BuiltInTool, DiffLineKind } from '#lib/enums/index.ts'; import type { AgenticSection, EditFileEdit, EditFileMeta, EditFileTitleMeta } from '#lib/types/index.ts'; -import { tryParseToolResultObject } from '#lib/utils/index.ts'; +import { computeLineDiff, memoizeBounded, tryParseToolResultObject } from '#lib/utils/index.ts'; export function parseEditFileMeta(section: AgenticSection): EditFileMeta | null { const args = parseToolArgs(BuiltInTool.SERVER_EDIT_FILE, section, { partial: true }); @@ -112,3 +112,38 @@ export function parseEditFileTitleMeta(section: AgenticSection): EditFileTitleMe return { editsApplied, errorMessage, fileName, filePath, resultMessage }; } + +/** + * Lines added and removed by a finished `edit_file` call, or null when it + * failed or changed nothing. Memoized per call: the title that shows it + * renders for every row, while sections are rebuilt on every streamed chunk. + * The id names the call, so a call without one is computed uncached; the + * sizes guard against an id that another conversation reuses. + */ +export const editFileDiffStats = memoizeBounded( + buildEditFileDiffStats, + (section) => + section.toolCallId + ? `${section.toolCallId}:${section.toolArgs?.length ?? 0}:${section.toolResult?.length ?? 0}` + : null, + 64 +); + +function buildEditFileDiffStats( + section: AgenticSection +): { added: number; removed: number } | null { + const meta = parseEditFileMeta(section); + + if (!meta || meta.errorMessage || meta.edits.length === 0) return null; + + const stats = { added: 0, removed: 0 }; + + for (const edit of meta.edits) { + for (const line of computeLineDiff(edit.oldText, edit.newText)) { + if (line.kind === DiffLineKind.ADD) stats.added++; + else if (line.kind === DiffLineKind.REMOVE) stats.removed++; + } + } + + return stats; +} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts new file mode 100644 index 000000000000..8792bc90aac4 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts @@ -0,0 +1,445 @@ +// Plain-language lines for tool calls: what one call did ("Read a file +// sheet_new.jpg"), what it is doing now ("Reading package.json") and what +// a run of calls did ("Ran 3 commands, read 2 files"). A call that has the +// arg the settings pick (`description` by default) shows it as the model +// wrote it. Otherwise built-in tools use TOOL_CALL_PHRASING, and MCP and +// unknown tools read as "Used " with their main argument. + +import { extractToolArgString, fileNameFromPath } from './_shared'; +import { + TOOL_ARG_PATH_KEYS, + TOOL_CALL_MAIN_ARG_KEYS, + TOOL_CALL_PHRASING, + TOOL_CALL_SHOWN_ARG_DEFAULT, + TOOL_CALL_SIMPLE_ARG_MAX_CHARS, + TOOL_CALL_SUMMARY, + TOOL_CALL_TARGET_MAX_CHARS, + TOOL_CALL_THINKING_LABEL, + TOOL_SEARCH_LOAD_PHRASING, + TOOL_SEARCH_PHRASING_NAME, + TOOL_SEARCH_PHRASING_SELECT_PREFIX, + TOOL_SEARCH_QUERY_PHRASING, + WEB_SEARCH_PHRASING +} from '#lib/constants/index.ts'; +import { AgenticSectionType, BuiltInTool, ToolCallSummaryKind } from '#lib/enums/index.ts'; +import type { AgenticSection, ToolCallDescription, ToolCallPhrasing } from '#lib/types/index.ts'; +import { isWebSearchToolName, memoizeBounded, parsePartialJsonArgs } from '#lib/utils/index.ts'; + +/** How many results each cache below holds. */ +const CACHE_MAX_SIZE = 256; +/** Args longer than this ( whole files ) are not worth holding as cache keys. */ +const CACHE_MAX_ARGS_CHARS = 2000; + +type ToolArgField = { label: string; value: string }; + +function shorten(text: string): string { + const oneLine = text.replace(/\s+/g, ' ').trim(); + + return oneLine.length > TOOL_CALL_TARGET_MAX_CHARS + ? `${oneLine.slice(0, TOOL_CALL_TARGET_MAX_CHARS - 3)}...` + : oneLine; +} + +function stringArg(args: Record | null, key: string): string | undefined { + const value = args?.[key]; + + return typeof value === 'string' && value.trim() ? value : undefined; +} + +function genericMainArg(args: Record | null): string | undefined { + if (!args) return undefined; + + for (const key of TOOL_CALL_MAIN_ARG_KEYS) { + const value = stringArg(args, key); + + if (value) return value; + } + + for (const value of Object.values(args)) { + if (typeof value === 'number') return String(value); + + if (typeof value === 'string' && value.trim() && value.length <= TOOL_CALL_TARGET_MAX_CHARS) { + return value; + } + } + + return undefined; +} + +function genericPhrasing(toolName: string): ToolCallPhrasing { + return { + object: toolName, + past: 'Used', + present: 'Using', + summary: ToolCallSummaryKind.OTHER, + targetObject: toolName + }; +} + +interface ResolvedCall { + phrasing: ToolCallPhrasing; + target?: string; + count?: number; +} + +function resolveCall(toolName: string, toolArgs: string): ResolvedCall { + // write_file and edit_file args hold whole files: read the path with a + // targeted match instead of parsing the blob + if ( + toolName === BuiltInTool.SERVER_READ_FILE || + toolName === BuiltInTool.SERVER_WRITE_FILE || + toolName === BuiltInTool.SERVER_EDIT_FILE || + toolName === BuiltInTool.BROWSER_READ_MEDIA + ) { + const path = + extractToolArgString(toolArgs, TOOL_ARG_PATH_KEYS) ?? + stringArg(parsePartialJsonArgs(toolArgs), 'path'); + + return { phrasing: TOOL_CALL_PHRASING[toolName], target: fileNameFromPath(path) }; + } + + const args = toolArgs ? parsePartialJsonArgs(toolArgs) : null; + + if (toolName === BuiltInTool.SERVER_EXEC_SHELL_COMMAND) { + // the targeted match keeps the command in the line while a later arg + // is still streaming and the JSON does not parse + return { + phrasing: TOOL_CALL_PHRASING[toolName], + target: stringArg(args, 'command') ?? extractToolArgString(toolArgs, ['command']) + }; + } + + switch (toolName) { + case BuiltInTool.SERVER_GREP_SEARCH: + return { phrasing: TOOL_CALL_PHRASING[toolName], target: stringArg(args, 'pattern') }; + + case BuiltInTool.SERVER_FILE_GLOB_SEARCH: { + const include = stringArg(args, 'include'); + + return { + phrasing: TOOL_CALL_PHRASING[toolName], + target: include && include !== '**' ? include : undefined + }; + } + + case BuiltInTool.BROWSER_SEARCH_CHATS: { + const matches = Array.isArray(args?.by_matches) + ? args.by_matches.filter((m): m is string => typeof m === 'string' && m.trim() !== '') + : []; + + return { phrasing: TOOL_CALL_PHRASING[toolName], target: matches.join(', ') || undefined }; + } + + case TOOL_SEARCH_PHRASING_NAME: { + const query = stringArg(args, 'query')?.trim(); + + if (query?.startsWith(TOOL_SEARCH_PHRASING_SELECT_PREFIX)) { + const names = query + .slice(TOOL_SEARCH_PHRASING_SELECT_PREFIX.length) + .split(',') + .map((name) => name.trim()) + .filter(Boolean); + + return { + count: Math.max(names.length, 1), + phrasing: TOOL_SEARCH_LOAD_PHRASING, + target: names.join(', ') || undefined + }; + } + + return { phrasing: TOOL_SEARCH_QUERY_PHRASING, target: query }; + } + } + + if (isWebSearchToolName(toolName)) { + return { phrasing: WEB_SEARCH_PHRASING, target: stringArg(args, 'query') }; + } + + const known = TOOL_CALL_PHRASING[toolName]; + + if (known) return { phrasing: known }; + + return { phrasing: genericPhrasing(toolName), target: genericMainArg(args) }; +} + +/** An arg name the settings can pick: a plain key, so it is safe in a pattern. */ +const SHOWN_ARG_PATTERN = /^[\w-]+$/; + +/** + * The value of the arg a call's line shows, when the call has it. Whole-file + * args are not parsed for it: the targeted match reads it instead. + */ +function shownArgValue(toolArgs: string, shownArg: string | null): string | undefined { + if (!shownArg || !toolArgs || !SHOWN_ARG_PATTERN.test(shownArg)) return undefined; + + const value = + toolArgs.length <= CACHE_MAX_ARGS_CHARS + ? stringArg(parsePartialJsonArgs(toolArgs), shownArg) + : extractToolArgString(toolArgs, [shownArg]); + + return value?.trim() || undefined; +} + +/** + * Describe one tool call as a short sentence, in the past tense once it is + * done and the present tense while `running`. `shownArg` names the arg + * shown instead when the call has it ( null for none ). + */ +export function describeToolCall( + toolName: string | undefined, + toolArgs: string | undefined, + running = false, + shownArg: string | null = TOOL_CALL_SHOWN_ARG_DEFAULT +): ToolCallDescription { + return describeCached(toolName || 'a tool', toolArgs ?? '', running, shownArg ?? ''); +} + +// Sections are rebuilt on every streamed chunk, so the same finished call is +// described again and again: remember the answer for its args. Every caller +// of one call reads the same frozen object, so a title cannot edit the line +// out for the others. +const describeCached = memoizeBounded( + (name: string, args: string, running: boolean, shownArg: string) => + Object.freeze(buildDescription(name, args, running, shownArg || null)), + (name, args, running, shownArg) => + args.length <= CACHE_MAX_ARGS_CHARS + ? `${running ? 1 : 0}\0${shownArg}\0${name}\0${args}` + : null, + CACHE_MAX_SIZE +); + +function buildDescription( + name: string, + args: string, + running: boolean, + shownArg: string | null +): ToolCallDescription { + const { count = 1, phrasing, target } = resolveCall(name, args); + const shown = shownArgValue(args, shownArg); + // an arg the row already shows as its target ( a shell command ) would + // only repeat it + const described = shown && shown !== target?.trim() ? shown : undefined; + + if (described) { + return { + count, + described: true, + // shown as the model wrote it: rewriting its tense by rule mangles + // anything that does not start with a plain verb + label: shorten(described).replace(/[.\s]+$/, ''), + quoted: false, + summary: phrasing.summary + }; + } + + const verb = running ? phrasing.present : phrasing.past; + const shortTarget = target ? shorten(target) : undefined; + const object = shortTarget ? phrasing.targetObject : phrasing.object; + + return { + count, + label: object ? `${verb} ${object}` : verb, + quoted: Boolean(phrasing.quoteTarget && shortTarget), + summary: phrasing.summary, + target: shortTarget + }; +} + +/** One line of plain text for a description, e.g. `Searched for 'issue'`. */ +export function formatToolCallLine(description: ToolCallDescription): string { + if (!description.target) return description.label; + + const target = description.quoted ? `'${description.target}'` : description.target; + + return `${description.label} ${target}`; +} + +export function isToolCallSection(section: AgenticSection): boolean { + return ( + section.type === AgenticSectionType.TOOL_CALL || + section.type === AgenticSectionType.TOOL_CALL_PENDING || + section.type === AgenticSectionType.TOOL_CALL_STREAMING + ); +} + +/** True while the call has no result yet and the reply is still streaming. */ +export function isToolCallRunning(section: AgenticSection, isStreaming: boolean): boolean { + return ( + isStreaming && + (section.type === AgenticSectionType.TOOL_CALL_PENDING || + section.type === AgenticSectionType.TOOL_CALL_STREAMING) + ); +} + +/** + * Summarize a run of tool calls, e.g. "Ran 3 commands, read 2 files". + * Kinds keep the order they first appear in; other tools come last. + */ +export function summarizeToolCalls(sections: readonly AgenticSection[]): string { + const counts = new Map(); + + for (const section of sections) { + if (!isToolCallSection(section)) continue; + + const { count, summary } = describeToolCall(section.toolName, section.toolArgs); + + counts.set(summary, (counts.get(summary) ?? 0) + count); + } + + const other = counts.get(ToolCallSummaryKind.OTHER); + + if (other !== undefined) { + counts.delete(ToolCallSummaryKind.OTHER); + counts.set(ToolCallSummaryKind.OTHER, other); + } + + const clauses = [...counts].map(([kind, n]) => TOOL_CALL_SUMMARY[kind](n)); + const text = clauses.join(', '); + + return text.charAt(0).toUpperCase() + text.slice(1); +} + +/** + * What a run of calls is doing now, in user words ("Running a command", + * "Thinking"): the model thinking at its end, or the last call still + * running; null when neither is. + */ +export function describeToolActivity( + sections: readonly AgenticSection[], + isStreaming: boolean, + executingToolCallId?: string | null, + shownArgFor: (toolName: string | undefined) => string | null = () => TOOL_CALL_SHOWN_ARG_DEFAULT +): string | null { + // the model thinking at the end of the run, between calls or before its answer + if (isStreaming && sections.at(-1)?.type === AgenticSectionType.REASONING_PENDING) { + return TOOL_CALL_THINKING_LABEL; + } + + for (let i = sections.length - 1; i >= 0; i--) { + const section = sections[i]; + const executing = + section.toolCallId !== undefined && section.toolCallId === executingToolCallId; + + if (executing || isToolCallRunning(section, isStreaming)) { + return formatToolCallLine( + describeToolCall(section.toolName, section.toolArgs, true, shownArgFor(section.toolName)) + ); + } + } + + return null; +} + +/** + * Tool args as labelled fields when every value is a short, one-line + * scalar; null when the args need the JSON view instead. Memoized like + * describeToolCall: the row that shows them re-renders on every chunk. + */ +export function simpleToolArgFields(toolArgs: string | undefined): ToolArgField[] | null { + return toolArgs ? argFieldsCached(toolArgs) : null; +} + +const argFieldsCached = memoizeBounded( + buildSimpleToolArgFields, + (toolArgs) => (toolArgs.length <= CACHE_MAX_ARGS_CHARS ? toolArgs : null), + CACHE_MAX_SIZE +); + +function buildSimpleToolArgFields(toolArgs: string): ToolArgField[] | null { + let parsed: unknown; + + try { + parsed = JSON.parse(toolArgs); + } catch { + return null; + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null; + + const entries = Object.entries(parsed as Record); + + if (entries.length === 0) return null; + + const fields: ToolArgField[] = []; + + for (const [key, value] of entries) { + if (value !== null && typeof value === 'object') return null; + + const text = String(value); + + if (text.length > TOOL_CALL_SIMPLE_ARG_MAX_CHARS || text.includes('\n')) return null; + + fields.push({ label: humanizeArgKey(key), value: text }); + } + + return fields; +} + +/** `max_results` / `maxResults` -> `Max results`. */ +export function humanizeArgKey(key: string): string { + const words = key + .replace(/([a-z0-9])([A-Z])/g, '$1 $2') + .replace(/[_-]+/g, ' ') + .trim() + .toLowerCase(); + + return words.charAt(0).toUpperCase() + words.slice(1); +} + +export function isReasoningSection(section: AgenticSection): boolean { + return ( + section.type === AgenticSectionType.REASONING || + section.type === AgenticSectionType.REASONING_PENDING + ); +} + +/** + * Split section positions into single items and runs of tool work, e.g. + * [0, [1, 2, 3], 4]. A run is the calls and all the reasoning around them, + * up to the next text, so the answer follows the work as one row: it is + * grouped once it holds `minCalls` calls, or one call with reasoning beside + * it. Reasoning with no call in reach, and text, stay apart. + */ +export function groupToolCallRuns( + sections: readonly AgenticSection[], + indices: readonly number[], + minCalls: number +): (number | number[])[] { + const items: (number | number[])[] = []; + + let run: number[] = []; + let calls = 0; + // reasoning seen since the last call: it ends the run if text follows, + // and leads into it if another call does + let thinking: number[] = []; + + const flush = () => { + const whole = [...run, ...thinking]; + + if (calls >= minCalls || (calls > 0 && whole.length > calls)) items.push(whole); + else items.push(...whole); + + run = []; + thinking = []; + calls = 0; + }; + + for (const index of indices) { + const section = sections[index]; + + if (isToolCallSection(section)) { + run.push(...thinking, index); + thinking = []; + calls++; + } else if (isReasoningSection(section)) { + thinking.push(index); + } else { + flush(); + items.push(index); + } + } + + flush(); + + return items; +} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/tool-call-elapsed.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/tool-call-elapsed.ts new file mode 100644 index 000000000000..89a5fd2ebb26 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/tool-call-elapsed.ts @@ -0,0 +1,28 @@ +// The live task timer sits at the end of the last tool row while a reply runs. +// The trace sets it once, naming that row's call, so the per-tool blocks need +// no extra prop. + +import { getContext, setContext } from 'svelte'; + +const KEY = Symbol('tool-call-elapsed'); + +/** The call that shows the timer and the task start (ms since epoch), or null for no timer. */ +type ElapsedTarget = { startedAt: number; toolCallId: string } | null; + +export function setToolCallElapsedContext(getTarget: () => ElapsedTarget): void { + setContext(KEY, getTarget); +} + +/** + * Call during component init. Returns a reader of the task start for a call: + * its start when that call shows the timer, null otherwise. + */ +export function useToolCallElapsed(): (toolCallId: string | undefined) => number | null { + const getTarget = getContext<(() => ElapsedTarget) | undefined>(KEY); + + return (toolCallId) => { + const target = getTarget?.(); + + return target && target.toolCallId === toolCallId ? target.startedAt : null; + }; +} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUser.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUser.svelte index 1101287c767a..4c4df7ba9763 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUser.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUser.svelte @@ -6,6 +6,7 @@ ChatMessageStatistics, ChatMessageUserBubble } from '#lib/components/app/chat/index.ts'; + import { SETTINGS_KEYS } from '#lib/constants/index.ts'; import { getChatMessageEditContext } from '#lib/contexts/index.ts'; import { ChatMessageStatisticsMode, MessageRole } from '#lib/enums/index.ts'; import { useProcessingState } from '#lib/hooks/use-processing-state.svelte.ts'; @@ -50,6 +51,12 @@ }; }); + // the latest exchange keeps its stats and actions in view; earlier messages + // show them on hover, and the setting can keep their stats in view as well + let hidesStatsUntilHover = $derived( + !isLastUserMessage && !currentConfig[SETTINGS_KEYS.ALWAYS_SHOW_MESSAGE_STATS] + ); + let showStoredReadingStats = $derived( Boolean(currentConfig.showMessageStats) && storedReadingStats !== null ); @@ -67,7 +74,7 @@
{#if editCtx.isEditing} @@ -83,7 +90,12 @@ {#if showStoredReadingStats} -
+
@@ -96,8 +108,10 @@
{:else if showLiveReadingStats} {@const liveStats = processingState.getLiveProcessingStats()} - {#if liveStats} -
+ +
+ {#if liveStats}
@@ -108,12 +122,12 @@ promptTokens={liveStats.tokensProcessed} />
-
- {/if} + {/if} +
{/if} {#if message.timestamp} -
+
{/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserBubble.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserBubble.svelte index c4f823886354..4419454cae75 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserBubble.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserBubble.svelte @@ -56,6 +56,7 @@
{#if editCtx.isEditing} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCard.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCard.svelte index 452effa1e150..796f2a4d2a53 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCard.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCard.svelte @@ -5,10 +5,12 @@ interface Props { icon: Component<{ class?: string }>; message: Snippet; + /** What the decision is about, shown in full between the question and the actions. */ + detail?: Snippet; actions: Snippet; } - let { actions, icon: IconComponent, message }: Props = $props(); + let { actions, detail, icon: IconComponent, message }: Props = $props();
@@ -20,6 +22,12 @@
+ {#if detail} +
+ {@render detail()} +
+ {/if} +
{@render actions()}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte index 42561a63b564..9e50951e353d 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte @@ -12,10 +12,15 @@ interface Props { toolName: string; serverLabel: string; + /** + * The shell command the call would run, shown in full: the trace row may + * show the model's own description of it, which is not what gets executed. + */ + command?: string; onDecision: (decision: ToolPermissionDecision) => void; } - let { onDecision, serverLabel, toolName }: Props = $props(); + let { command, onDecision, serverLabel, toolName }: Props = $props(); @@ -24,6 +29,13 @@  from {serverLabel}{/if}? {/snippet} + {#snippet detail()} + {#if command} +
{command}
+ {/if} + {/snippet} + {#snippet actions()} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte new file mode 100644 index 000000000000..f0e7bffde8dd --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte @@ -0,0 +1,410 @@ + + +{#snippet renderSection(section: AgenticSection, index: number, inOpenGroup = false)} + {#if section.type === AgenticSectionType.TEXT} +
+ +
+ {:else if section.type === AgenticSectionType.REASONING || section.type === AgenticSectionType.REASONING_PENDING} + toggleExpanded(index, section)} + open={isExpanded(index, section)} + {section} + /> + {:else if section.type === AgenticSectionType.TOOL_CALL || section.type === AgenticSectionType.TOOL_CALL_PENDING || section.type === AgenticSectionType.TOOL_CALL_STREAMING} + toggleExpanded(index, section, inOpenGroup)} + open={isExpanded(index, section, inOpenGroup)} + {section} + /> + {/if} +{/snippet} + +{#snippet renderItem(item: TraceItem)} + {#if Array.isArray(item)} + {@const groupOpen = isGroupExpanded(item)} + toggleGroupExpanded(item)} + open={groupOpen} + sections={item.map((i) => sections[i])} + status={statusInGroup && item === lastItem ? statusText || REPLY_STATUS_FALLBACK : null} + > + {#each item as index (index)} + {@render renderSection(sections[index], index, groupOpen)} + {/each} + + {:else} + {@render renderSection(sections[item], item)} + {/if} +{/snippet} + +{#snippet renderItems(items: TraceItem[])} + {#each items as item (Array.isArray(item) ? `g${item[0]}` : item)} + {@render renderItem(item)} + {/each} +{/snippet} + +
+ {#each turns as items, turnIndex (turnIndex)} + {#if showTurnStats} + {@const turnStats = message?.timings?.agentic?.perTurn?.[turnIndex]} + +
+ {@render renderItems(items)} + + {#if turnStats} +
+ 0 + ? buildTurnAgenticTimings(turnStats) + : undefined} + hideSummary + initialView={ChatMessageStatsView.GENERATION} + predictedMs={turnStats.llm.predicted_ms} + predictedTokens={turnStats.llm.predicted_n} + promptMs={turnStats.llm.prompt_ms} + promptTokens={turnStats.llm.prompt_n} + /> +
+ {/if} +
+ {:else} + {@render renderItems(items)} + {/if} + {/each} + + {#if visiblePermission} + + {/if} + + {#if showContinue} + + {/if} + + {#if showStatus && !statusInGroup} + + {/if} +
+ + diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgenticContent.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgenticContent.svelte deleted file mode 100644 index fa97fcde3411..000000000000 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgenticContent.svelte +++ /dev/null @@ -1,273 +0,0 @@ - - -{#snippet renderSection(section: AgenticSection, index: number)} - {#if section.type === AgenticSectionType.TEXT} -
- -
- {:else if section.type === AgenticSectionType.REASONING || section.type === AgenticSectionType.REASONING_PENDING} - toggleExpanded(index, section)} - open={isExpanded(index, section)} - {section} - /> - {:else if section.type === AgenticSectionType.TOOL_CALL || section.type === AgenticSectionType.TOOL_CALL_PENDING || section.type === AgenticSectionType.TOOL_CALL_STREAMING} - toggleExpanded(index, section)} - open={isExpanded(index, section)} - {section} - /> - {/if} -{/snippet} - -
- {#if turnGroups.length > 1} - {#each turnGroups as turn, turnIndex (turnIndex)} - {@const turnStats = message?.timings?.agentic?.perTurn?.[turnIndex]} - -
- {#each turn.sections as section, sIdx (turn.flatIndices[sIdx])} - {@render renderSection(section, turn.flatIndices[sIdx])} - {/each} - - {#if turnStats && showAgenticTurnStats} -
- 0 - ? buildTurnAgenticTimings(turnStats) - : undefined} - hideSummary - initialView={ChatMessageStatsView.GENERATION} - predictedMs={turnStats.llm.predicted_ms} - predictedTokens={turnStats.llm.predicted_n} - promptMs={turnStats.llm.prompt_ms} - promptTokens={turnStats.llm.prompt_n} - /> -
- {/if} -
- {/each} - {:else} - {#each sections as section, index (index)} - {@render renderSection(section, index)} - {/each} - {/if} - - {#if visiblePermission} - - {/if} - - {#if showContinue} - - {/if} -
- - diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageReasoningBlock.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageReasoningBlock.svelte index f084d6cd6e97..b417f425602a 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageReasoningBlock.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageReasoningBlock.svelte @@ -1,5 +1,4 @@ {#if perfState.message} - { }); it('streams the partial command into the title with a cursor', async () => { - const { container } = render(ChatMessageAgenticContent, { + const { container } = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: messageWithArgs('{"command":"git sta'), @@ -89,16 +94,15 @@ describe('exec_shell_command streaming title', () => { await tick(); - const title = triggerText(container); - - expect(title).toContain('git sta'); - expect(title).toContain('$'); - expect(title).toContain(CWD); + expect(triggerText(container)).toContain('git sta'); + expect(promptText(container)).toContain('git sta'); + expect(promptText(container)).toContain('$'); + expect(promptText(container)).toContain(CWD); expect(hasCursor(container)).toBe(true); }); it('drops the cursor once the args JSON is complete', async () => { - const screen = render(ChatMessageAgenticContent, { + const screen = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: messageWithArgs('{"command":"git sta'), @@ -122,7 +126,7 @@ describe('exec_shell_command streaming title', () => { }); it('switches the prompt from the conversation cwd to the persisted one', async () => { - const screen = render(ChatMessageAgenticContent, { + const screen = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: messageWithArgs('{"command":"git status"}'), @@ -131,7 +135,7 @@ describe('exec_shell_command streaming title', () => { await tick(); - expect(triggerText(screen.container)).toContain(CWD); + expect(promptText(screen.container)).toContain(CWD); // Result message lands: its x-tool-cwd takes over the prompt. screen.rerender({ @@ -142,12 +146,12 @@ describe('exec_shell_command streaming title', () => { }); await tick(); - expect(triggerText(screen.container)).toContain('/other/dir'); - expect(triggerText(screen.container)).not.toContain(CWD); + expect(promptText(screen.container)).toContain('/other/dir'); + expect(promptText(screen.container)).not.toContain(CWD); }); it('shows the executing label only after the command finishes streaming', async () => { - const screen = render(ChatMessageAgenticContent, { + const screen = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: messageWithArgs('{"command":"git sta'), @@ -198,7 +202,7 @@ describe('exec_shell_command streaming title', () => { // writes growing toolCalls strings into the same store row per delta. conversationsStore.activeMessages = [messageWithArgs('')]; - const screen = render(ChatMessageAgenticContent, { + const screen = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: conversationsStore.activeMessages[0]!, @@ -232,7 +236,7 @@ describe('exec_shell_command interrupted call', () => { }); it('marks a call without a result as interrupted once streaming stops', async () => { - const { container } = render(ChatMessageAgenticContent, { + const { container } = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: false, message: messageWithArgs('{"command":"git status"}'), @@ -249,7 +253,7 @@ describe('exec_shell_command interrupted call', () => { it('marks a command stopped before any output as interrupted', async () => { // exec_shell_command creates its result message before running, so a // stop mid-run leaves an empty result rather than none. - const { container } = render(ChatMessageAgenticContent, { + const { container } = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: false, message: messageWithArgs('{"command":"sleep 40"}'), @@ -263,7 +267,7 @@ describe('exec_shell_command interrupted call', () => { }); it('does not keep spinning in an earlier message while a newer reply streams', async () => { - const { container } = render(ChatMessageAgenticContent, { + const { container } = render(ChatMessageAgentTrace, { isLastAssistantMessage: false, isStreaming: true, message: messageWithArgs('{"command":"git status"}'), diff --git a/ui/apps/chat/tests/client/media-gallery.svelte.test.ts b/ui/apps/chat/tests/client/media-gallery.svelte.test.ts new file mode 100644 index 000000000000..3a6279c259b6 --- /dev/null +++ b/ui/apps/chat/tests/client/media-gallery.svelte.test.ts @@ -0,0 +1,75 @@ +// Guards the conversation slideshow: a thumbnail opens every image, audio clip +// and video in the open thread, in thread order, at the item that was clicked, +// whether it came from a user attachment or a tool result. + +import { AttachmentType, MessageRole, MessageType } from '#lib/enums/index.ts'; +import { conversationsStore, mediaGalleryStore } from '#lib/stores/index.ts'; +import type { DatabaseMessage, DatabaseMessageExtra } from '#lib/types/index.ts'; +import { afterEach, describe, expect, it } from 'vitest'; + +function image(name: string): DatabaseMessageExtra { + return { base64Url: `data:image/png;base64,${name}`, name, type: AttachmentType.IMAGE }; +} + +function message(id: string, role: MessageRole, extra: DatabaseMessageExtra[]): DatabaseMessage { + return { + children: [], + content: '', + convId: 'conv-1', + extra, + id, + parent: null, + role, + timestamp: 0, + toolCalls: '', + type: MessageType.TEXT + }; +} + +afterEach(() => { + conversationsStore.activeMessages = []; + mediaGalleryStore.open = false; +}); + +describe('mediaGalleryStore', () => { + it('opens the media of the whole thread at the clicked item', () => { + const pasted = image('pasted'); + const shot = image('shot'); + const text: DatabaseMessageExtra = { + content: 'x', + name: 'notes.txt', + type: AttachmentType.TEXT + }; + + conversationsStore.activeMessages = [ + message('u1', MessageRole.USER, [pasted, text]), + message('t1', MessageRole.TOOL, [shot]) + ]; + + mediaGalleryStore.show(shot); + + expect(mediaGalleryStore.open).toBe(true); + expect(mediaGalleryStore.items).toEqual([pasted, shot]); + expect(mediaGalleryStore.index).toBe(1); + }); + + it('finds an item passed as a copy of the stored one', () => { + conversationsStore.activeMessages = [message('t1', MessageRole.TOOL, [image('a'), image('b')])]; + + mediaGalleryStore.show({ ...image('b') }); + + expect(mediaGalleryStore.index).toBe(1); + expect(mediaGalleryStore.items).toHaveLength(2); + }); + + it('opens an item outside the thread on its own', () => { + conversationsStore.activeMessages = [message('t1', MessageRole.TOOL, [image('a')])]; + + const stray = image('elsewhere'); + + mediaGalleryStore.show(stray); + + expect(mediaGalleryStore.items).toEqual([stray]); + expect(mediaGalleryStore.index).toBe(0); + }); +}); diff --git a/ui/apps/chat/tests/client/permission-request-command.svelte.test.ts b/ui/apps/chat/tests/client/permission-request-command.svelte.test.ts new file mode 100644 index 000000000000..b804a991b7bb --- /dev/null +++ b/ui/apps/chat/tests/client/permission-request-command.svelte.test.ts @@ -0,0 +1,67 @@ +// Guards what the reader approves: the trace row of a shell call may show the +// model's own description of it, so the permission card must show the command +// that would actually run, and the row must keep the command beside the +// description. + +import ChatMessageActionCardPermissionRequest from '#lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte'; +import ChatMessageAgentTrace from '#lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte'; +import { BuiltInTool, MessageRole, MessageType } from '#lib/enums/index.ts'; +import type { DatabaseMessage } from '#lib/types/index.ts'; +import { tick } from 'svelte'; +import { describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; + +const COMMAND = 'rm -rf ./build'; +const DESCRIPTION = 'List files'; + +function shellCall(): DatabaseMessage { + return { + children: [], + content: '', + convId: 'conv-1', + id: 'assistant-1', + parent: null, + role: MessageRole.ASSISTANT, + timestamp: 0, + toolCalls: JSON.stringify([ + { + function: { + arguments: JSON.stringify({ command: COMMAND, description: DESCRIPTION }), + name: BuiltInTool.SERVER_EXEC_SHELL_COMMAND + }, + id: 'c1' + } + ]), + type: MessageType.TEXT + }; +} + +describe('approving a shell command', () => { + it('shows the command in the permission card', async () => { + const { container } = render(ChatMessageActionCardPermissionRequest, { + command: COMMAND, + onDecision: () => {}, + serverLabel: 'Server Tools', + toolName: BuiltInTool.SERVER_EXEC_SHELL_COMMAND + }); + + await tick(); + + expect(container.querySelector('pre')?.textContent).toBe(COMMAND); + }); + + it('keeps the command beside a model description in the collapsed row', async () => { + const { container } = render(ChatMessageAgentTrace, { + isLastAssistantMessage: true, + isStreaming: true, + message: shellCall() + }); + + await tick(); + + const title = container.querySelector('[data-slot="collapsible-trigger"]')?.textContent ?? ''; + + expect(title).toContain(DESCRIPTION); + expect(title).toContain(COMMAND); + }); +}); diff --git a/ui/apps/chat/tests/client/stick-to-bottom.svelte.test.ts b/ui/apps/chat/tests/client/stick-to-bottom.svelte.test.ts index cc8589e444b2..d229bba0f023 100644 --- a/ui/apps/chat/tests/client/stick-to-bottom.svelte.test.ts +++ b/ui/apps/chat/tests/client/stick-to-bottom.svelte.test.ts @@ -1,7 +1,8 @@ // Guards the follow rules of StickToBottom: right after a press, growth of the // content stays put (the reader expanded something), while growth of an element // passed to followSizeOf - the chat form expanding on the reader's click - is -// still followed, so the latest message stays in view above it. +// still followed, so the latest message stays in view above it. A send glides to +// the bottom: eased, never jumping, and handed back the moment the reader scrolls. import { createStickToBottom } from '#lib/hooks/use-stick-to-bottom.svelte.ts'; import { afterEach, describe, expect, it } from 'vitest'; @@ -47,6 +48,26 @@ async function resizeObserved() { await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); } +function frame() { + return new Promise((resolve) => requestAnimationFrame(resolve)); +} + +/** + * Waits until the container rests at its bottom. A glide counts animated + * time, not wall time, so a runner that drops frames takes longer to get + * there: the deadline is only a guard against a glide that never arrives, + * set far beyond what one can take. + */ +const SETTLE_DEADLINE_MS = 20_000; + +async function settled(container: HTMLElement) { + const deadline = performance.now() + SETTLE_DEADLINE_MS; + + while (distanceFromBottom(container) > 1 && performance.now() < deadline) { + await frame(); + } +} + function distanceFromBottom(el: HTMLElement) { return el.scrollHeight - el.clientHeight - el.scrollTop; } @@ -86,4 +107,83 @@ describe('StickToBottom', () => { expect(container.scrollTop).toBe(0); }); + + it('glides to the new bottom after a send instead of jumping there', async () => { + const { container, content, stick } = setup(); + + stick.glideToBottom(); + content.style.height = '1400px'; + + const tops: number[] = []; + + // the first frames after the growth are on their way, not there yet + await frame(); + tops.push(container.scrollTop); + await frame(); + tops.push(container.scrollTop); + + expect(distanceFromBottom(container)).toBeGreaterThan(200); + + await settled(container); + + for (let i = 0; i < 5; i++) { + tops.push(container.scrollTop); + await frame(); + } + + expect(distanceFromBottom(container)).toBeLessThanOrEqual(1); + // only ever down: no overshoot, no step back + expect(tops).toEqual([...tops].sort((a, b) => a - b)); + }); + + it('glides to layout that settles shortly after a send', async () => { + const { container, content, stick } = setup(); + + stick.glideToBottom(); + content.style.height = '1400px'; + await settled(container); + + content.style.height = '1700px'; + await resizeObserved(); + + expect(distanceFromBottom(container)).toBeGreaterThan(100); + + await settled(container); + + expect(distanceFromBottom(container)).toBeLessThanOrEqual(1); + }); + + it('hands the page back the moment the reader scrolls', async () => { + const { container, content, stick } = setup(); + + stick.glideToBottom(); + content.style.height = '1400px'; + await frame(); + await frame(); + window.dispatchEvent(new WheelEvent('wheel')); + + const top = container.scrollTop; + + await resizeObserved(); + await frame(); + + expect(container.scrollTop).toBe(top); + expect(distanceFromBottom(container)).toBeGreaterThan(200); + }); + + it('keeps gliding while the reader types the next message', async () => { + const { container, content, stick } = setup(); + const field = document.createElement('textarea'); + + document.body.append(field); + cleanup.push(() => field.remove()); + + stick.glideToBottom(); + content.style.height = '1400px'; + await frame(); + field.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: ' ' })); + await settled(container); + + expect(distanceFromBottom(container)).toBeLessThanOrEqual(1); + }); }); diff --git a/ui/apps/chat/tests/client/task-timer.svelte.test.ts b/ui/apps/chat/tests/client/task-timer.svelte.test.ts new file mode 100644 index 000000000000..5c248cc2f3d6 --- /dev/null +++ b/ui/apps/chat/tests/client/task-timer.svelte.test.ts @@ -0,0 +1,84 @@ +// Guards the live task timer: while a reply runs, the last tool row shows the +// time since the task started. A single call reads it from context by its id; +// a group takes it as a prop; a finished reply shows none. + +import ChatMessageAgentTrace from '#lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte'; +import { MessageRole, MessageType } from '#lib/enums/index.ts'; +import { agenticStore } from '#lib/stores/index.ts'; +import type { DatabaseMessage } from '#lib/types/index.ts'; +import { tick } from 'svelte'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; + +const CONV_ID = 'conv-timer'; +const TIMER = '[title="Time since the task started"]'; + +type SessionPatch = { startedAt: number | null }; +type WithSession = { updateSession(conversationId: string, patch: SessionPatch): void }; + +function reply(calls: number): DatabaseMessage { + return { + children: [], + content: '', + convId: CONV_ID, + id: 'assistant-1', + parent: null, + role: MessageRole.ASSISTANT, + timestamp: 0, + toolCalls: JSON.stringify( + Array.from({ length: calls }, (_, i) => ({ + function: { arguments: `{"path":"file-${i}.ts"}`, name: 'read_file' }, + id: `call-${i}` + })) + ), + type: MessageType.TEXT + }; +} + +function setStartedAt(startedAt: number | null) { + // the loop sets this when a flow starts; there is no public setter + (agenticStore as unknown as WithSession).updateSession(CONV_ID, { startedAt }); +} + +describe('task timer', () => { + beforeEach(() => setStartedAt(Date.now() - 5000)); + afterEach(() => setStartedAt(null)); + + it('shows on a single running call', async () => { + const { container } = render(ChatMessageAgentTrace, { + isLastAssistantMessage: true, + isStreaming: true, + message: reply(1) + }); + + await tick(); + + expect(container.querySelectorAll(TIMER)).toHaveLength(1); + expect(container.querySelector(TIMER)?.textContent?.trim()).toMatch(/^\d+s$/); + }); + + it('shows once on a group, not on the calls inside it', async () => { + const { container } = render(ChatMessageAgentTrace, { + isLastAssistantMessage: true, + isStreaming: true, + message: reply(2) + }); + + await tick(); + + expect(container.querySelectorAll(TIMER)).toHaveLength(1); + expect(container.querySelector('.tool-call-group')?.querySelector(TIMER)).not.toBeNull(); + }); + + it('shows nothing once the reply is not streaming', async () => { + const { container } = render(ChatMessageAgentTrace, { + isLastAssistantMessage: true, + isStreaming: false, + message: reply(1) + }); + + await tick(); + + expect(container.querySelectorAll(TIMER)).toHaveLength(0); + }); +}); diff --git a/ui/apps/chat/tests/client/tool-call-in-progress.svelte.test.ts b/ui/apps/chat/tests/client/tool-call-in-progress.svelte.test.ts index 3d8b350df0f3..25b3a164a53c 100644 --- a/ui/apps/chat/tests/client/tool-call-in-progress.svelte.test.ts +++ b/ui/apps/chat/tests/client/tool-call-in-progress.svelte.test.ts @@ -7,7 +7,7 @@ // finished calls open and wins on its own. A manual toggle always overrides the // default, in both directions. -import ChatMessageAgenticContent from '#lib/components/app/chat/ChatMessages/ChatMessageAgenticContent.svelte'; +import ChatMessageAgentTrace from '#lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte'; import { COLLAPSIBLE_TRANSITION_MS, SETTINGS_KEYS } from '#lib/constants/index.ts'; import { MessageRole, MessageType } from '#lib/enums/index.ts'; import { settingsStore } from '#lib/stores/index.ts'; @@ -94,7 +94,7 @@ describe('Show tool call in progress', () => { it('expands a call that is still executing when the setting is on', async () => { setSettings({ alwaysShow: false, inProgress: true }); - const { container } = render(ChatMessageAgenticContent, { + const { container } = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: assistantMessage(), @@ -107,7 +107,7 @@ describe('Show tool call in progress', () => { }); it('keeps the call collapsed while executing when the setting is off', async () => { - const { container } = render(ChatMessageAgenticContent, { + const { container } = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: assistantMessage(), @@ -124,7 +124,7 @@ describe('Show tool call in progress', () => { it('folds the call back when its result arrives', async () => { setSettings({ alwaysShow: false, inProgress: true }); - const screen = render(ChatMessageAgenticContent, { + const screen = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: assistantMessage(), @@ -153,7 +153,7 @@ describe('Show tool call in progress', () => { it('keeps the manual choice once the result arrives', async () => { setSettings({ alwaysShow: false, inProgress: true }); - const screen = render(ChatMessageAgenticContent, { + const screen = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: assistantMessage(), @@ -180,7 +180,7 @@ describe('Show tool call in progress', () => { it('still expands a finished call when "always show" is on', async () => { setSettings({ alwaysShow: true, inProgress: false }); - const { container } = render(ChatMessageAgenticContent, { + const { container } = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: assistantMessage(), @@ -195,7 +195,7 @@ describe('Show tool call in progress', () => { it('lets a manual collapse win over the in-progress default', async () => { setSettings({ alwaysShow: false, inProgress: true }); - const screen = render(ChatMessageAgenticContent, { + const screen = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: assistantMessage(), @@ -213,7 +213,7 @@ describe('Show tool call in progress', () => { }); it('lets a manual expand win over the collapsed default', async () => { - const screen = render(ChatMessageAgenticContent, { + const screen = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: assistantMessage(), diff --git a/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallBlock.stories.svelte b/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallBlock.stories.svelte index 0d0accc04592..ca71b4862393 100644 --- a/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallBlock.stories.svelte +++ b/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallBlock.stories.svelte @@ -20,6 +20,7 @@ runJavascriptSection, searchResultsSection, seedChatStory, + toolSearchSection, writeFileSection } from './fixtures'; import { defineMeta } from '@storybook/addon-svelte-csf'; @@ -125,6 +126,10 @@ + + + + diff --git a/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallGroup.stories.svelte b/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallGroup.stories.svelte new file mode 100644 index 000000000000..848eac7d64d3 --- /dev/null +++ b/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallGroup.stories.svelte @@ -0,0 +1,70 @@ + + + seedChatStory()} name="States"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ui/apps/chat/tests/stories/chat/messages/ToolCallGroupStoryHost.svelte b/ui/apps/chat/tests/stories/chat/messages/ToolCallGroupStoryHost.svelte new file mode 100644 index 000000000000..dbbaa116316f --- /dev/null +++ b/ui/apps/chat/tests/stories/chat/messages/ToolCallGroupStoryHost.svelte @@ -0,0 +1,46 @@ + + + (open = !open)} + {open} + {sections} +> + {#each sections as section, i (i)} + {@const executing = section.toolCallId === executingToolCallId} + (openCalls[i] = !(openCalls[i] ?? executing))} + open={openCalls[i] ?? executing} + {section} + /> + {/each} + diff --git a/ui/apps/chat/tests/stories/chat/messages/fixtures.ts b/ui/apps/chat/tests/stories/chat/messages/fixtures.ts index 41aae1b3d582..a686c958f4fb 100644 --- a/ui/apps/chat/tests/stories/chat/messages/fixtures.ts +++ b/ui/apps/chat/tests/stories/chat/messages/fixtures.ts @@ -592,6 +592,73 @@ export const searchResultsSection = toolSection( ].join('\n') ); +export const toolSearchSection = toolSection( + 'tool_search', + { max_results: 1, query: 'select:Monitor' }, + 'Loaded 1 tool: Monitor' +); + +/* Tool call groups: runs of consecutive calls shown as one row */ + +function withId(section: AgenticSection, toolCallId: string): AgenticSection { + return { ...section, toolCallId }; +} + +const IMAGE_SECTION_COUNT = 4; + +export const toolGroupSections: AgenticSection[] = [ + withId(getInfoSection, 'group-info'), + withId(readFileSection, 'group-read'), + withId(grepSearchSection, 'group-grep'), + withId(editFileSection, 'group-edit'), + withId(execShellSection, 'group-exec'), + withId(writeFileSection, 'group-write') +]; + +export const toolGroupImageSections: AgenticSection[] = [ + withId(execShellSection, 'image-exec'), + ...Array.from({ length: IMAGE_SECTION_COUNT }, (_, i) => ({ + ...readMediaSection, + toolArgs: JSON.stringify({ path: `/home/user/charts/chart-${i + 1}.svg` }), + toolCallId: `image-media-${i}`, + toolResultExtras: [ + { + base64Url: i % 2 === 0 ? CHART_IMAGE_URL : SVG_IMAGE_URL, + name: 'mcp-attachment-usage.svg', + type: AttachmentType.IMAGE as const + } + ] + })) +]; + +export const toolGroupRunningSections: AgenticSection[] = [ + withId(readFileSection, 'running-read'), + withId(grepSearchSection, 'running-grep'), + toolSection( + BuiltInTool.SERVER_READ_FILE, + { path: 'package.json' }, + undefined, + AgenticSectionType.TOOL_CALL_PENDING + ) +]; + +export const TOOL_GROUP_EXECUTING_ID = 'running-exec'; + +export const toolGroupShellRunningSections: AgenticSection[] = [ + withId(readFileSection, 'shell-read'), + { + ...withId(execShellPendingSection, TOOL_GROUP_EXECUTING_ID), + toolResult: '> app@0.1.0 build\n> vite build\n\nvite v7.0.0 building for production...\n', + type: AgenticSectionType.TOOL_CALL + } +]; + +export const toolGroupMcpSections: AgenticSection[] = [ + withId(toolSearchSection, 'mcp-search'), + withId(defaultToolSection, 'mcp-weather'), + withId(defaultToolMarkdownSection, 'mcp-issue') +]; + /* Reasoning sections */ export const reasoningSection: AgenticSection = { diff --git a/ui/apps/chat/tests/unit/settings-tool-call-in-progress.test.ts b/ui/apps/chat/tests/unit/settings-tool-call-in-progress.test.ts index 792239f76d29..5c11b43f0b64 100644 --- a/ui/apps/chat/tests/unit/settings-tool-call-in-progress.test.ts +++ b/ui/apps/chat/tests/unit/settings-tool-call-in-progress.test.ts @@ -27,9 +27,9 @@ describe('showToolCallInProgress setting', () => { expect(field?.label).toBe('Show tool call in progress'); }); - it('ships enabled, like "Show thought in progress"', () => { - expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.SHOW_TOOL_CALL_IN_PROGRESS]).toBe(true); - expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.SHOW_THOUGHT_IN_PROGRESS]).toBe(true); + it('ships disabled, like "Show thought in progress", so the trace stays collapsed', () => { + expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.SHOW_TOOL_CALL_IN_PROGRESS]).toBe(false); + expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.SHOW_THOUGHT_IN_PROGRESS]).toBe(false); }); it('is listed next to its "always show" counterpart', () => { diff --git a/ui/apps/chat/tests/unit/tool-call-phrasing.test.ts b/ui/apps/chat/tests/unit/tool-call-phrasing.test.ts new file mode 100644 index 000000000000..1433d32250cd --- /dev/null +++ b/ui/apps/chat/tests/unit/tool-call-phrasing.test.ts @@ -0,0 +1,344 @@ +import { + describeToolActivity, + describeToolCall, + formatToolCallLine, + groupToolCallRuns, + humanizeArgKey, + simpleToolArgFields, + summarizeToolCalls +} from '#lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts'; +import { AgenticSectionType, BuiltInTool } from '#lib/enums/index.ts'; +import type { AgenticSection } from '#lib/types/index.ts'; +import { describe, expect, it } from 'vitest'; + +function call( + toolName: string, + args: Record | string = {}, + type = AgenticSectionType.TOOL_CALL, + toolCallId?: string +): AgenticSection { + return { + content: '', + toolArgs: typeof args === 'string' ? args : JSON.stringify(args), + toolCallId, + toolName, + toolResult: type === AgenticSectionType.TOOL_CALL ? 'ok' : undefined, + type + }; +} + +function line(toolName: string, args: Record | string = {}, running = false) { + return formatToolCallLine( + describeToolCall(toolName, typeof args === 'string' ? args : JSON.stringify(args), running) + ); +} + +describe('describeToolCall', () => { + it('phrases built-in tools in the past tense', () => { + expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, { command: 'git status' })).toBe( + 'Ran git status' + ); + expect(line(BuiltInTool.SERVER_READ_FILE, { path: '/tmp/x/sheet_new.jpg' })).toBe( + 'Read sheet_new.jpg' + ); + expect(line(BuiltInTool.SERVER_EDIT_FILE, { edits: [], path: 'a/harness-roadmap.html' })).toBe( + 'Edited harness-roadmap.html' + ); + expect(line(BuiltInTool.SERVER_WRITE_FILE, { content: 'x', file_path: 'b/notes.md' })).toBe( + 'Wrote notes.md' + ); + expect(line(BuiltInTool.SERVER_GREP_SEARCH, { path: '.', pattern: 'issue' })).toBe( + "Searched for 'issue'" + ); + expect(line(BuiltInTool.SERVER_FILE_GLOB_SEARCH, { include: '*.ts', path: '.' })).toBe( + "Listed files matching '*.ts'" + ); + expect(line(BuiltInTool.SERVER_FILE_GLOB_SEARCH, { include: '**', path: '.' })).toBe( + 'Listed files' + ); + expect(line(BuiltInTool.BROWSER_SEARCH_CHATS, { by_matches: ['llama', 'gguf'] })).toBe( + "Searched chats for 'llama, gguf'" + ); + expect(line(BuiltInTool.SERVER_GET_INFO)).toBe('Checked runtime info'); + expect(line(BuiltInTool.BROWSER_RUN_JAVASCRIPT, { code: '1+1' })).toBe('Ran JavaScript'); + }); + + it('uses the present tense while running', () => { + expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, { command: 'ls' }, true)).toBe('Running ls'); + expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, '{"comm', true)).toBe('Running a command'); + expect(line(BuiltInTool.SERVER_READ_FILE, { path: 'package.json' }, true)).toBe( + 'Reading package.json' + ); + expect(line(BuiltInTool.BROWSER_SEARCH_CHATS, {}, true)).toBe('Searching chats'); + }); + + it('falls back to the object when the target has not streamed yet', () => { + expect(line(BuiltInTool.SERVER_READ_FILE, '{"pa', true)).toBe('Reading a file'); + expect(line(BuiltInTool.SERVER_GREP_SEARCH, '')).toBe('Searched files'); + }); + + it('reads a path from partial args', () => { + expect( + line(BuiltInTool.SERVER_WRITE_FILE, '{"path": "src/app.ts", "content": "abc', true) + ).toBe('Writing app.ts'); + }); + + it('phrases tool_search select queries as loading tools', () => { + expect(line('tool_search', { query: 'select:Monitor' })).toBe('Loaded tools Monitor'); + expect(line('tool_search', { query: 'select:a, b' }, true)).toBe('Loading tools a, b'); + expect(line('tool_search', { query: 'slack messages' })).toBe( + "Searched tools for 'slack messages'" + ); + }); + + it('phrases web search tools', () => { + expect(line('web_search_exa', { query: 'llama.cpp' })).toBe("Searched the web for 'llama.cpp'"); + }); + + it('gives MCP and unknown tools a generic line with their main argument', () => { + expect(line('get_weather', { city: 'Warsaw' })).toBe('Used get_weather Warsaw'); + expect(line('fetch_page', { timeout: 5, url: 'https://example.com' })).toBe( + 'Used fetch_page https://example.com' + ); + expect(line('list_things', {})).toBe('Used list_things'); + expect(line('summarize_issue', { issue: 31273 })).toBe('Used summarize_issue 31273'); + expect(line('list_things', {}, true)).toBe('Using list_things'); + }); + + it('shortens long targets to one line', () => { + const text = describeToolCall('my_tool', JSON.stringify({ query: 'word '.repeat(40) })).target; + + expect(text?.length).toBe(60); + expect(text?.endsWith('...')).toBe(true); + expect(text).not.toContain('\n'); + }); +}); + +describe('the shown argument', () => { + const args = { command: 'git status', description: 'Check which files changed.' }; + + it('shows the description as the model wrote it, in both tenses', () => { + expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, args)).toBe('Check which files changed'); + expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, args, true)).toBe( + 'Check which files changed' + ); + expect( + describeToolCall(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, JSON.stringify(args)).described + ).toBe(true); + }); + + it('does not rewrite a description that starts with something other than a verb', () => { + const nouns = { command: 'ls', description: 'All files in src' }; + + expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, nouns)).toBe('All files in src'); + expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, nouns, true)).toBe('All files in src'); + }); + + it('keeps the command in the line while a later arg is still streaming', () => { + expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, '{"command":"date","timeout":', true)).toBe( + 'Running date' + ); + }); + + it('works for any tool that has the argument, MCP ones included', () => { + expect(line('get_weather', { city: 'Warsaw', description: 'Check the weather' })).toBe( + 'Check the weather' + ); + }); + + it('falls back to the sentence when the call does not have it', () => { + expect(line('get_weather', { city: 'Warsaw' })).toBe('Used get_weather Warsaw'); + }); + + it('reads the argument the settings pick, or none', () => { + const weather = JSON.stringify({ + city: 'Warsaw', + description: 'Check the weather', + units: 'metric' + }); + + expect(formatToolCallLine(describeToolCall('get_weather', weather, false, 'units'))).toBe( + 'metric' + ); + expect(formatToolCallLine(describeToolCall('get_weather', weather, false, null))).toBe( + 'Used get_weather Warsaw' + ); + }); + + it('does not repeat the target the row already shows', () => { + expect( + formatToolCallLine( + describeToolCall( + BuiltInTool.SERVER_EXEC_SHELL_COMMAND, + JSON.stringify(args), + false, + 'command' + ) + ) + ).toBe('Ran git status'); + }); + + it('ignores an argument name that is not a plain key', () => { + expect( + formatToolCallLine( + describeToolCall('get_weather', JSON.stringify({ city: 'Warsaw' }), false, '.*') + ) + ).toBe('Used get_weather Warsaw'); + }); +}); + +describe('summarizeToolCalls', () => { + it('counts calls per kind in first-seen order', () => { + const sections = [ + call(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, { command: 'a' }), + call(BuiltInTool.SERVER_READ_FILE, { path: 'a' }), + call(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, { command: 'b' }), + call(BuiltInTool.SERVER_WRITE_FILE, { path: 'c' }), + call(BuiltInTool.SERVER_WRITE_FILE, { path: 'd' }), + call(BuiltInTool.SERVER_READ_FILE, { path: 'b' }) + ]; + + expect(summarizeToolCalls(sections)).toBe('Ran 2 commands, read 2 files, wrote 2 files'); + }); + + it('uses singular forms and merges search tools', () => { + const sections = [ + call(BuiltInTool.SERVER_EDIT_FILE, { path: 'a' }), + call(BuiltInTool.SERVER_GREP_SEARCH, { pattern: 'x' }), + call(BuiltInTool.BROWSER_SEARCH_CHATS, { by_matches: ['y'] }) + ]; + + expect(summarizeToolCalls(sections)).toBe('Edited 1 file, searched 2 times'); + expect(summarizeToolCalls([call(BuiltInTool.SERVER_GREP_SEARCH)])).toBe('Searched once'); + }); + + it('puts other tools last', () => { + const sections = [call(BuiltInTool.SERVER_GET_INFO), call(BuiltInTool.SERVER_READ_FILE)]; + + expect(summarizeToolCalls(sections)).toBe('Read 1 file, used 1 tool'); + }); + + it('counts each tool a select query loads', () => { + const sections = [ + call('tool_search', { query: 'select:Monitor,Notebook' }), + call('get_weather', { city: 'x' }), + call('get_time') + ]; + + expect(summarizeToolCalls(sections)).toBe('Loaded 2 tools, used 2 tools'); + }); +}); + +describe('describeToolActivity', () => { + it('describes the last running call', () => { + const sections = [ + call(BuiltInTool.SERVER_READ_FILE, { path: 'a.ts' }), + call( + BuiltInTool.SERVER_READ_FILE, + { path: 'package.json' }, + AgenticSectionType.TOOL_CALL_PENDING + ) + ]; + + expect(describeToolActivity(sections, true)).toBe('Reading package.json'); + }); + + it('returns null when nothing runs or the reply stopped', () => { + const pending = [call(BuiltInTool.SERVER_READ_FILE, {}, AgenticSectionType.TOOL_CALL_PENDING)]; + + expect(describeToolActivity([call(BuiltInTool.SERVER_READ_FILE)], true)).toBeNull(); + expect(describeToolActivity(pending, false)).toBeNull(); + }); + + it('says the model is thinking while reasoning streams at the end of the run', () => { + const thinking: AgenticSection = { + content: '', + type: AgenticSectionType.REASONING_PENDING + }; + const sections = [call(BuiltInTool.SERVER_READ_FILE, { path: 'a.ts' }), thinking]; + + expect(describeToolActivity(sections, true)).toBe('Thinking'); + expect(describeToolActivity(sections, false)).toBeNull(); + }); + + it('treats the executing call as running even once its result exists', () => { + const sections = [ + call( + BuiltInTool.SERVER_EXEC_SHELL_COMMAND, + { command: 'ls' }, + AgenticSectionType.TOOL_CALL, + 'c1' + ) + ]; + + expect(describeToolActivity(sections, true, 'c1')).toBe('Running ls'); + }); +}); + +describe('simpleToolArgFields', () => { + it('lists short scalar args as labelled fields', () => { + expect( + simpleToolArgFields(JSON.stringify({ max_results: 1, query: 'select:Monitor' })) + ).toEqual([ + { label: 'Max results', value: '1' }, + { label: 'Query', value: 'select:Monitor' } + ]); + }); + + it('returns null for nested, multi-line, long or invalid args', () => { + expect(simpleToolArgFields(JSON.stringify({ a: { b: 1 } }))).toBeNull(); + expect(simpleToolArgFields(JSON.stringify({ a: 'x\ny' }))).toBeNull(); + expect(simpleToolArgFields(JSON.stringify({ a: 'x'.repeat(300) }))).toBeNull(); + expect(simpleToolArgFields('{"a":')).toBeNull(); + expect(simpleToolArgFields('{}')).toBeNull(); + expect(simpleToolArgFields(undefined)).toBeNull(); + }); +}); + +describe('humanizeArgKey', () => { + it('turns snake and camel case into words', () => { + expect(humanizeArgKey('max_results')).toBe('Max results'); + expect(humanizeArgKey('filePath')).toBe('File path'); + expect(humanizeArgKey('q')).toBe('Q'); + }); +}); + +describe('groupToolCallRuns', () => { + const text: AgenticSection = { content: 'hi', type: AgenticSectionType.TEXT }; + const tool = call(BuiltInTool.SERVER_READ_FILE); + + it('groups runs of consecutive calls and keeps single calls apart', () => { + const sections = [text, tool, tool, tool, text, tool, text]; + + expect(groupToolCallRuns(sections, [0, 1, 2, 3, 4, 5, 6], 2)).toEqual([0, [1, 2, 3], 4, 5, 6]); + }); + + const think: AgenticSection = { content: 'hm', type: AgenticSectionType.REASONING }; + + it('takes in all the reasoning around the calls, up to the answer', () => { + // think, call, think, call, think, text + const sections = [think, tool, think, tool, think, text]; + + expect(groupToolCallRuns(sections, [0, 1, 2, 3, 4, 5], 2)).toEqual([[0, 1, 2, 3, 4], 5]); + }); + + it('groups one call with reasoning beside it', () => { + expect(groupToolCallRuns([think, tool, think, text], [0, 1, 2, 3], 2)).toEqual([[0, 1, 2], 3]); + expect(groupToolCallRuns([text, tool, think], [0, 1, 2], 2)).toEqual([0, [1, 2]]); + }); + + it('keeps a lone call, and reasoning with no call in reach, apart', () => { + expect(groupToolCallRuns([text, tool, text], [0, 1, 2], 2)).toEqual([0, 1, 2]); + expect(groupToolCallRuns([think, text, think], [0, 1, 2], 2)).toEqual([0, 1, 2]); + }); + + it('does not count reasoning as a call in the summary', () => { + expect(summarizeToolCalls([think, tool, think, tool])).toBe('Read 2 files'); + }); + + it('works on a subset of indices and a trailing run', () => { + const sections = [text, text, tool, tool]; + + expect(groupToolCallRuns(sections, [1, 2, 3], 2)).toEqual([1, [2, 3]]); + }); +}); diff --git a/ui/apps/chat/tests/unit/tool-call-shown-arg.test.ts b/ui/apps/chat/tests/unit/tool-call-shown-arg.test.ts new file mode 100644 index 000000000000..7bc63725933c --- /dev/null +++ b/ui/apps/chat/tests/unit/tool-call-shown-arg.test.ts @@ -0,0 +1,38 @@ +import { SETTINGS_KEYS } from '#lib/constants/index.ts'; +import { parseToolCallShownArgOverrides, toolCallShownArg } from '#lib/utils/index.ts'; +import { describe, expect, it } from 'vitest'; + +function config(shownArg: string, overrides: Record | string = {}) { + return { + [SETTINGS_KEYS.TOOL_CALL_SHOWN_ARG]: shownArg, + [SETTINGS_KEYS.TOOL_CALL_SHOWN_ARG_OVERRIDES]: + typeof overrides === 'string' ? overrides : JSON.stringify(overrides) + }; +} + +describe('toolCallShownArg', () => { + it('uses the global argument for a tool without its own', () => { + expect(toolCallShownArg(config('description'), 'get_weather')).toBe('description'); + }); + + it("prefers the tool's own argument", () => { + expect(toolCallShownArg(config('description', { get_weather: 'city' }), 'get_weather')).toBe( + 'city' + ); + expect(toolCallShownArg(config('description', { get_weather: 'city' }), 'other')).toBe( + 'description' + ); + }); + + it('returns null for none, globally or per tool', () => { + expect(toolCallShownArg(config(''), 'get_weather')).toBeNull(); + expect(toolCallShownArg(config('description', { get_weather: '' }), 'get_weather')).toBeNull(); + }); + + it('reads unreadable overrides as none', () => { + expect(parseToolCallShownArgOverrides('not json')).toEqual({}); + expect(parseToolCallShownArgOverrides('[1]')).toEqual({}); + expect(parseToolCallShownArgOverrides('{"a":"x","b":1}')).toEqual({ a: 'x' }); + expect(toolCallShownArg(config('description', 'not json'), 'get_weather')).toBe('description'); + }); +}); From 1d3aad2fd811a2a5efdd4eeb192eaefc1764519c Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Mon, 23 Nov 2026 17:28:56 +0100 Subject: [PATCH 025/275] server: ask exec_shell_command for a short description of the command (#32894) The shell tool's schema gains a required `description` argument, listed first: a short plain-language line on what the command does. The tool ignores it, as before; clients can show it in place of the raw command while the call streams and in their logs. Calls without it still run. Assisted-by: Claude (Opus 5.5 Medium) --- tools/server/server-tools.cpp | 4 +++- tools/server/tests/unit/test_tools_builtin.py | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/tools/server/server-tools.cpp b/tools/server/server-tools.cpp index 060361968c59..7f4650157ec1 100644 --- a/tools/server/server-tools.cpp +++ b/tools/server/server-tools.cpp @@ -1274,11 +1274,13 @@ struct server_tool_exec_shell_command : server_tool { {"parameters", { {"type", "object"}, {"properties", { + // first, so a client can show it while the command still streams; the tool ignores it + {"description", {{"type", "string"}, {"description", "Short plain-language description of what this command does, starting with a verb, e.g. 'List files in the project root'. 3 to 10 words. Shown to the user."}}}, {"command", {{"type", "string"}, {"description", "Shell command to execute"}}}, {"timeout", {{"type", "integer"}, {"description", string_format("Timeout in seconds (default 10, max %d)", SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_TIMEOUT)}}}, {"max_output_size", {{"type", "integer"}, {"description", string_format("Maximum output size in bytes (default %zu)", SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_OUTPUT_SIZE)}}}, }}, - {"required", json::array({"command"})}, + {"required", json::array({"description", "command"})}, }}, }}, }; diff --git a/tools/server/tests/unit/test_tools_builtin.py b/tools/server/tests/unit/test_tools_builtin.py index c830b0642f63..486ba8481700 100755 --- a/tools/server/tests/unit/test_tools_builtin.py +++ b/tools/server/tests/unit/test_tools_builtin.py @@ -191,6 +191,23 @@ def test_tools_builtin_edit_file_rejects_non_unique_old_text(tmp_path): os.remove(log_path) +def test_tools_builtin_exec_shell_command_asks_for_a_description(): + global server + server.start() + + res = server.make_request("GET", "/tools") + assert res.status_code == 200, res.body + tool = next(t for t in res.body if t["tool"] == "exec_shell_command") + params = tool["definition"]["function"]["parameters"] + # first, so a client can show it while the command still streams + assert list(params["properties"])[0] == "description" + assert "description" in params["required"] + + # the tool runs without it, as before + res = call_tool("exec_shell_command", {"command": "echo hi"}) + assert "hi" in res["plain_text_response"] + + def test_tools_builtin_exec_shell_command_stream(): global server server.start() From 87f816e87f35f91c8a6f7e561b1f1a7899bee254 Mon Sep 17 00:00:00 2001 From: Georgi Gerganov Date: Mon, 23 Nov 2026 18:46:12 +0200 Subject: [PATCH 026/275] metal : support BF16/F32 src1 for MUL_MAT and MUL_MAT_ID (#32677) * llama, metal : support BF16 src1 for MUL_MAT and MUL_MAT_ID Add GGML_PREC_BF16 handling for src1 on the Metal backend when the tensor API is available: MUL_MAT with an F32 src0 stages the A tile as bfloat, and MUL_MAT_ID stages src1 as bfloat instead of F16. The tensor path keeps src1 in F32 when it reads the operand directly. Add a temporary LLAMA_MOE_AMAX_SKIP env var that disables the graph-level amax rescaling for the MoE down projection and sets the BF16 src1 hint instead. Apply the hint inside build_lora_mm_id so it reaches the matmul before the per-expert scale and LoRA nodes wrap it. Add MUL_MAT_ID src1 BF16 test cases to test-backend-ops. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : support BF16 src1 without the tensor API Allow GGML_PREC_BF16 when the device has bfloat, not only when it has the Metal4 tensor API. Add legacy _prec_bf16 kernels for MUL_MAT and MUL_MAT_ID that stage src1 as bfloat in the threadgroup and run the simdgroup multiply with bfloat A and B. The F16 MUL_MAT_ID kernel uses half A on the tensor path and bfloat A on the legacy path. Cast the quantized dequantize outputs to the destination element type: the older Metal compiler on M2 rejects implicit float to bfloat. Tested on M2 Ultra (legacy): MUL_MAT_PREC_SRC1 24/24 and MUL_MAT_ID_PREC_SRC1_BF16 30/30. Flint Q4_K_M with LLAMA_MOE_AMAX_SKIP=1: pp512 -2.1%, tg128 +25.5% vs master. On M5 Max: pp512 +2.1%, tg128 +22.2%. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : derive matrix types with value_type helpers Add value_type_4x4/value_type_2x4/value_type_8x8 helpers and use them in the MUL_MAT and MUL_MAT_ID kernels so the templates take only the underlying types and derive the matrix types. Add TODOs for the remaining kernels. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : derive matrix types in the remaining kernels Use the value_type_* helpers in the flash-attention, top-k-mask, mul-mv and count-equal kernels to derive the matrix/vector types from the underlying scalar types, and simplify the FA_TYPES macros. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : enable BF16 in the tensor API metallib The tensor API requires macOS 26, where bfloat is always available, so define GGML_METAL_HAS_BF16 when compiling the tensor metallib. This makes the bfloat specializations of the value_type helpers visible to fa_tensor.metal and includes the prec_bf16 kernels in the prebuilt tensor metallib. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : support GGML_PREC_F32 for src1 in MUL_MAT and MUL_MAT_ID Split the tensor-API and legacy simdgroup mul_mm/mul_mm_id kernels into separate files and library kinds, following the fa_tensor.metal example. The legacy kernels, including the new _prec_f32 variants that stage src0 and src1 as float in shared memory, are compiled into the default mul_mm library; the tensor variants live in a separate mul_mm_tensor library kind and carry a _tensor host-name infix. Tensor devices run F32 src1 matmuls on the simdgroup path instead of the tensor API, which rounds float operands to a reduced precision. This removes the MUL_MM_SG kind and the #undef GGML_METAL_HAS_TENSOR compile. Add MUL_MAT_ID_PREC_SRC1_F32 tests. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * cont : indentation * llama : move the MoE amax skip into the precision policy Add llm_arch_mmid_down_bf16() for the architectures whose MoE down projection uses the graph-level amax rescaling. Extract the precision policy setup from load_tensors() into llama_model_base::load_prec_policy(), and move the LLAMA_MOE_AMAX_SKIP handling there: it sets prec_src1 = BF16 for ffn_down_exps before the per-tensor policy is loaded. build_moe_ffn() now skips the amax rescaling when the policy requests BF16. Apply the policy with the original weight so cached experts get it, drop the prec_src1 parameter from build_lora_mm_id(), and remove the prec_src1 serialization from the model saver. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * cont : minor --- ggml/src/ggml-metal/CMakeLists.txt | 11 +- ggml/src/ggml-metal/ggml-metal-device.cpp | 36 +- ggml/src/ggml-metal/ggml-metal-device.m | 13 +- ggml/src/ggml-metal/kernels/common.h | 43 ++ ggml/src/ggml-metal/kernels/dequantize.h | 76 +-- ggml/src/ggml-metal/kernels/fa_common.metal | 44 +- ggml/src/ggml-metal/kernels/fa_f16.metal | 39 +- ggml/src/ggml-metal/kernels/fa_f32.metal | 39 +- ggml/src/ggml-metal/kernels/fa_q4_0.metal | 39 +- ggml/src/ggml-metal/kernels/fa_q4_1.metal | 39 +- ggml/src/ggml-metal/kernels/fa_q5_0.metal | 39 +- ggml/src/ggml-metal/kernels/fa_q5_1.metal | 39 +- ggml/src/ggml-metal/kernels/fa_q8_0.metal | 39 +- ggml/src/ggml-metal/kernels/fa_tensor.metal | 33 +- .../ggml-metal/kernels/fa_vec_common.metal | 19 +- ggml/src/ggml-metal/kernels/fa_vec_f16.metal | 24 +- ggml/src/ggml-metal/kernels/fa_vec_f32.metal | 24 +- ggml/src/ggml-metal/kernels/fa_vec_q4_0.metal | 24 +- ggml/src/ggml-metal/kernels/fa_vec_q4_1.metal | 24 +- ggml/src/ggml-metal/kernels/fa_vec_q5_0.metal | 24 +- ggml/src/ggml-metal/kernels/fa_vec_q5_1.metal | 24 +- ggml/src/ggml-metal/kernels/fa_vec_q8_0.metal | 24 +- ggml/src/ggml-metal/kernels/misc.metal | 26 +- ggml/src/ggml-metal/kernels/mul_mm.metal | 624 +++++++----------- .../ggml-metal/kernels/mul_mm_tensor.metal | 537 +++++++++++++++ ggml/src/ggml-metal/kernels/mul_mv.metal | 41 +- src/llama-arch.cpp | 12 + src/llama-arch.h | 1 + src/llama-graph.cpp | 10 +- src/llama-model-saver.cpp | 12 - src/llama-model.cpp | 48 +- src/llama-model.h | 14 +- tests/test-backend-ops.cpp | 90 +++ 33 files changed, 1367 insertions(+), 764 deletions(-) create mode 100644 ggml/src/ggml-metal/kernels/mul_mm_tensor.metal diff --git a/ggml/src/ggml-metal/CMakeLists.txt b/ggml/src/ggml-metal/CMakeLists.txt index 91691b223669..0ecc07c45fff 100644 --- a/ggml/src/ggml-metal/CMakeLists.txt +++ b/ggml/src/ggml-metal/CMakeLists.txt @@ -56,6 +56,7 @@ set(METALLIB_KERNEL_SOURCES kernels/mul_mv.metal kernels/mul_mv_mma.metal kernels/mul_mm.metal + kernels/mul_mm_tensor.metal kernels/quantize.metal kernels/softmax.metal kernels/norm.metal @@ -223,21 +224,21 @@ else() # the tensor API kernels go in a separate metallib, loaded only where supported if (GGML_METAL_HAS_TENSOR_LIB) - set(AIR_MM_TENSOR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/mul_mm_tensor.air") + set(AIR_MM_TENSOR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/mul_mm_tensor_tensor.air") # the tensor API needs OS 26+ set(XC_FLAGS_TENSOR ${XC_FLAGS} -mtargetos=${GGML_METAL_TARGET_OS}26.0${METAL_TARGET_SIM}) add_custom_command( OUTPUT ${AIR_MM_TENSOR} - COMMAND xcrun -sdk ${METAL_SDK} metal ${XC_FLAGS_TENSOR} -DGGML_METAL_HAS_TENSOR -I ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} -c ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/mul_mm.metal -o ${AIR_MM_TENSOR} - DEPENDS kernels/mul_mm.metal kernels/common.h kernels/dequantize.h ${METALLIB_COMMON} ggml-metal-impl.h - COMMENT "Compiling kernels/mul_mm.metal (tensor API)" + COMMAND xcrun -sdk ${METAL_SDK} metal ${XC_FLAGS_TENSOR} -DGGML_METAL_HAS_TENSOR -DGGML_METAL_HAS_BF16 -I ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} -c ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/mul_mm_tensor.metal -o ${AIR_MM_TENSOR} + DEPENDS kernels/mul_mm_tensor.metal kernels/common.h kernels/dequantize.h ${METALLIB_COMMON} ggml-metal-impl.h + COMMENT "Compiling kernels/mul_mm_tensor.metal (tensor API)" VERBATIM ) set(AIR_FA_TENSOR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/fa_tensor_tensor.air") add_custom_command( OUTPUT ${AIR_FA_TENSOR} - COMMAND xcrun -sdk ${METAL_SDK} metal ${XC_FLAGS_TENSOR} -DGGML_METAL_HAS_TENSOR -I ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} -c ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/fa_tensor.metal -o ${AIR_FA_TENSOR} + COMMAND xcrun -sdk ${METAL_SDK} metal ${XC_FLAGS_TENSOR} -DGGML_METAL_HAS_TENSOR -DGGML_METAL_HAS_BF16 -I ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} -c ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/fa_tensor.metal -o ${AIR_FA_TENSOR} DEPENDS kernels/fa_tensor.metal kernels/common.h ${METALLIB_COMMON} ggml-metal-impl.h COMMENT "Compiling kernels/fa_tensor.metal (tensor API)" VERBATIM diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp index cd9e0785053c..88ca0b832738 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.cpp +++ b/ggml/src/ggml-metal/ggml-metal-device.cpp @@ -974,7 +974,15 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm(ggml_meta constexpr int NRA = SZ_SIMDGROUP * N_MM_BLOCK_Y * N_MM_SIMD_GROUP_Y; constexpr int NRB = SZ_SIMDGROUP * N_MM_BLOCK_X * N_MM_SIMD_GROUP_X; - const bool has_tensor = ggml_metal_device_get_props(ggml_metal_library_get_device(lib))->has_tensor; + const ggml_metal_device_props * props_dev = ggml_metal_device_get_props(ggml_metal_library_get_device(lib)); + + const bool has_tensor = props_dev->has_tensor; + + const bool prec_bf16 = props_dev->has_bfloat && + ggml_prec_get_src(op, 1) == GGML_PREC_BF16 && tsrc1 == GGML_TYPE_F32 && + (has_tensor ? tsrc0 == GGML_TYPE_F32 : tsrc0 != GGML_TYPE_BF16); + + const bool prec_f32 = ggml_prec_get_src(op, 1) == GGML_PREC_F32 && tsrc1 == GGML_TYPE_F32; const bool bc_out = has_tensor ? (op->ne[0] % NRA != 0 || op->ne[1] % NRB != 0) @@ -986,7 +994,11 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm(ggml_meta const int16_t r2 = (int16_t) (ne12 / op->src[0]->ne[2]); const int16_t r3 = (int16_t) (ne13 / op->src[0]->ne[3]); - snprintf(base, 256, "kernel_mul_mm_%s_%s", ggml_type_name(tsrc0), ggml_type_name(tsrc1)); + const bool use_tensor = has_tensor && !prec_f32; + + const char * infix = use_tensor ? "_tensor" : ""; + const char * suffix = prec_f32 ? "_prec_f32" : (prec_bf16 ? "_prec_bf16" : ""); + snprintf(base, 256, "kernel_mul_mm%s_%s_%s%s", infix, ggml_type_name(tsrc0), ggml_type_name(tsrc1), suffix); snprintf(name, 256, "%s_bci=%d_bco=%d_ne12=%d_ne13=%d_r2=%d_r3=%d", base, bc_inp, bc_out, ne12, ne13, r2, r3); @@ -1006,7 +1018,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm(ggml_meta ggml_metal_cv_free(cv); } - if (has_tensor) { + if (use_tensor) { res.nr0 = NRA; res.nr1 = NRB; @@ -1016,7 +1028,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm(ggml_meta res.nr0 = 64; res.nr1 = 32; - res.smem = bc_out ? 8192 : (4096 + 2048); + res.smem = prec_f32 ? 12288 : (bc_out ? 8192 : (4096 + 2048)); } res.nsg = N_MM_SIMD_GROUP_X * N_MM_SIMD_GROUP_Y; @@ -1305,9 +1317,21 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm_id(ggml_m const ggml_type tsrc0 = op->src[0]->type; const ggml_type tsrc1 = op->src[1]->type; + const ggml_metal_device_props * props_dev = ggml_metal_device_get_props(ggml_metal_library_get_device(lib)); + + const bool prec_bf16 = props_dev->has_bfloat && + ggml_prec_get_src(op, 1) == GGML_PREC_BF16 && tsrc1 == GGML_TYPE_F32 && + tsrc0 != GGML_TYPE_BF16 && tsrc0 != GGML_TYPE_MXFP4; + + const bool prec_f32 = ggml_prec_get_src(op, 1) == GGML_PREC_F32 && tsrc1 == GGML_TYPE_F32; + const bool bc_inp = op->src[0]->ne[0] % 32 != 0; - snprintf(base, 256, "kernel_mul_mm_id_%s_%s", ggml_type_name(tsrc0), ggml_type_name(tsrc1)); + const bool use_tensor = props_dev->has_tensor && !prec_f32; + + const char * infix = use_tensor ? "_tensor" : ""; + const char * suffix = prec_f32 ? "_prec_f32" : (prec_bf16 ? "_prec_bf16" : ""); + snprintf(base, 256, "kernel_mul_mm_id%s_%s_%s%s", infix, ggml_type_name(tsrc0), ggml_type_name(tsrc1), suffix); snprintf(name, 256, "%s_bci=%d", base, bc_inp); ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name); @@ -1321,7 +1345,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm_id(ggml_m ggml_metal_cv_free(cv); } - res.smem = 8192; + res.smem = prec_f32 ? 12288 : 8192; return res; } diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index 2e085453adb9..293400ff256f 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -129,6 +129,7 @@ int ggml_metal_pipeline_max_theads_per_threadgroup(struct ggml_metal_pipeline_wi X(MUL_MV, mul_mv) \ X(MUL_MV_MMA, mul_mv_mma) \ X(MUL_MM, mul_mm) \ + X(MUL_MM_TENSOR, mul_mm_tensor) \ X(QUANTIZE, quantize) \ X(SOFTMAX, softmax) \ X(NORM, norm) \ @@ -1510,14 +1511,16 @@ void ggml_metal_device_get_memory(ggml_metal_device_t dev, size_t * free, size_t } } -static bool ggml_metal_supports_mul_mat_src1_prec(const struct ggml_tensor * op, bool has_tensor) { +static bool ggml_metal_supports_mul_mat_src1_prec(const struct ggml_tensor * op, bool has_bfloat) { + GGML_ASSERT(op->op == GGML_OP_MUL_MAT || op->op == GGML_OP_MUL_MAT_ID); + const enum ggml_prec prec = ggml_prec_get_src(op, 1); if (prec == GGML_PREC_F32) { - return false; + return true; } if (prec == GGML_PREC_BF16) { - return has_tensor && op->op == GGML_OP_MUL_MAT && op->src[0]->type != GGML_TYPE_F32; + return has_bfloat && op->src[1]->type == GGML_TYPE_F32; } return true; } @@ -1907,7 +1910,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te case GGML_OP_SOLVE_TRI: return has_simdgroup_reduction && op->src[0]->type == GGML_TYPE_F32; case GGML_OP_MUL_MAT: - if (!ggml_metal_supports_mul_mat_src1_prec(op, dev->props.has_tensor)) { + if (!ggml_metal_supports_mul_mat_src1_prec(op, dev->props.has_bfloat)) { return false; } // the FWHT kernels read an F16 source directly; every other F16 src1 path @@ -1920,7 +1923,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te has_simdgroup_reduction, op, true, ggml_metal_op_mul_mat_use_mm(op, has_simdgroup_mm)); case GGML_OP_MUL_MAT_ID: - if (!ggml_metal_supports_mul_mat_src1_prec(op, dev->props.has_tensor)) { + if (!ggml_metal_supports_mul_mat_src1_prec(op, dev->props.has_bfloat)) { return false; } return ggml_metal_supports_mul_mat_op( diff --git a/ggml/src/ggml-metal/kernels/common.h b/ggml/src/ggml-metal/kernels/common.h index c4d674394480..551a4d7c8e81 100644 --- a/ggml/src/ggml-metal/kernels/common.h +++ b/ggml/src/ggml-metal/kernels/common.h @@ -124,3 +124,46 @@ template<> inline float4 elu_approx(float4 x) { return res; } + +template struct value_type; +template <> struct value_type { typedef float type; }; +template <> struct value_type { typedef half type; }; +#if defined(GGML_METAL_HAS_BF16) +template <> struct value_type { typedef bfloat type; }; +#endif + +template struct value_type_4x4; +template <> struct value_type_4x4 { typedef float4x4 type; }; +template <> struct value_type_4x4 { typedef half4x4 type; }; +#if defined(GGML_METAL_HAS_BF16) +template <> struct value_type_4x4 { typedef bfloat4x4 type; }; +#endif + +template struct value_type_2x4; +template <> struct value_type_2x4 { typedef float2x4 type; }; +template <> struct value_type_2x4 { typedef half2x4 type; }; +#if defined(GGML_METAL_HAS_BF16) +template <> struct value_type_2x4 { typedef bfloat2x4 type; }; +#endif + +template struct value_type_8x8; +template <> struct value_type_8x8 { typedef simdgroup_float8x8 type; }; +template <> struct value_type_8x8 { typedef simdgroup_half8x8 type; }; +#if defined(GGML_METAL_HAS_BF16) +template <> struct value_type_8x8 { typedef simdgroup_bfloat8x8 type; }; +#endif + +template struct value_type_4; +template <> struct value_type_4 { typedef float4 type; }; +template <> struct value_type_4 { typedef half4 type; }; +template <> struct value_type_4 { typedef int4 type; }; +#if defined(GGML_METAL_HAS_BF16) +template <> struct value_type_4 { typedef bfloat4 type; }; +#endif + +template struct value_type_2; +template <> struct value_type_2 { typedef float2 type; }; +template <> struct value_type_2 { typedef half2 type; }; +#if defined(GGML_METAL_HAS_BF16) +template <> struct value_type_2 { typedef bfloat2 type; }; +#endif diff --git a/ggml/src/ggml-metal/kernels/dequantize.h b/ggml/src/ggml-metal/kernels/dequantize.h index 54e00faf6f00..96b16d7fb442 100644 --- a/ggml/src/ggml-metal/kernels/dequantize.h +++ b/ggml/src/ggml-metal/kernels/dequantize.h @@ -393,7 +393,7 @@ void dequantize_q2_K(device const block_q2_K *xb, short il, thread type4x4 & reg uchar mask = il>1 ? (il>2 ? 192 : 48) : (il>0 ? 12 : 3); dl = d * (sc & 0xF) * coef, ml = min * (sc >> 4); for (int i = 0; i < 16; ++i) { - reg[i/4][i%4] = dl * (q[i] & mask) - ml; + reg[i/4][i%4] = (typename value_type::type) (dl * (q[i] & mask) - ml); } } @@ -422,7 +422,7 @@ void dequantize_q3_K(device const block_q3_K *xb, short il, thread type4x4 & reg dl *= coef; for (int i = 0; i < 16; ++i) { - reg[i/4][i%4] = dl * (q[i] & mask) - (h[i] & m ? 0 : ml); + reg[i/4][i%4] = (typename value_type::type) (dl * (q[i] & mask) - (h[i] & m ? 0 : ml)); } } @@ -446,7 +446,7 @@ void dequantize_q4_K(device const block_q4_K * xb, short il, thread type4x4 & re const ushort mask = il < 2 ? 0x0F : 0xF0; for (int i = 0; i < 16; ++i) { - reg[i/4][i%4] = dl * (q[i] & mask) - ml; + reg[i/4][i%4] = (typename value_type::type) (dl * (q[i] & mask) - ml); } } @@ -469,7 +469,7 @@ void dequantize_q5_K(device const block_q5_K *xb, short il, thread type4x4 & reg const ushort mask = il<2 ? 0x0F : 0xF0; const float qh_val = il<2 ? 16.f : 256.f; for (int i = 0; i < 16; ++i) { - reg[i/4][i%4] = dl * ((q[i] & mask) + (qh[i] & ul ? qh_val : 0)) - ml; + reg[i/4][i%4] = (typename value_type::type) (dl * ((q[i] & mask) + (qh[i] & ul ? qh_val : 0)) - ml); } } @@ -499,10 +499,10 @@ void dequantize_q6_K(device const block_q6_K *xb, short il, thread type4x4 & reg const uint32_t low = (ql[2*i] | (uint32_t)(ql[2*i+1] << 16)) & kmask2; const uint32_t high = (qh[2*i] | (uint32_t)(qh[2*i+1] << 16)) & kmask1; const uint32_t q = ((high << shl_h) >> shr_h) | (low >> shr_l); - reg[i][0] = dl0 * ((half)(q & 0xFF)) - ml; - reg[i][1] = dl1 * ((float)(q & 0xFF00)) - ml; - reg[i][2] = dl2 * ((float)(q & 0xFF0000)) - ml; - reg[i][3] = dl3 * ((float)(q & 0xFF000000)) - ml; + reg[i][0] = (typename value_type::type) (dl0 * ((half)(q & 0xFF)) - ml); + reg[i][1] = (typename value_type::type) (dl1 * ((float)(q & 0xFF00)) - ml); + reg[i][2] = (typename value_type::type) (dl2 * ((float)(q & 0xFF0000)) - ml); + reg[i][3] = (typename value_type::type) (dl3 * ((float)(q & 0xFF000000)) - ml); } } @@ -522,12 +522,12 @@ void dequantize_iq2_xxs(device const block_iq2_xxs * xb, short il, thread type4x constant uint8_t * grid = (constant uint8_t *)(iq2xxs_grid + aux8[2*il+0]); uint8_t signs = ksigns_iq2xs[(aux32_s >> 14*il) & 127]; for (int i = 0; i < 8; ++i) { - reg[i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f); + reg[i/4][i%4] = (typename value_type::type) (dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f)); } grid = (constant uint8_t *)(iq2xxs_grid + aux8[2*il+1]); signs = ksigns_iq2xs[(aux32_s >> (14*il+7)) & 127]; for (int i = 0; i < 8; ++i) { - reg[2+i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f); + reg[2+i/4][i%4] = (typename value_type::type) (dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f)); } } @@ -543,12 +543,12 @@ void dequantize_iq2_xs(device const block_iq2_xs * xb, short il, thread type4x4 constant uint8_t * grid = (constant uint8_t *)(iq2xs_grid + (q2[2*il+0] & 511)); uint8_t signs = ksigns_iq2xs[q2[2*il+0] >> 9]; for (int i = 0; i < 8; ++i) { - reg[i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f); + reg[i/4][i%4] = (typename value_type::type) (dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f)); } grid = (constant uint8_t *)(iq2xs_grid + (q2[2*il+1] & 511)); signs = ksigns_iq2xs[q2[2*il+1] >> 9]; for (int i = 0; i < 8; ++i) { - reg[2+i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f); + reg[2+i/4][i%4] = (typename value_type::type) (dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f)); } } @@ -567,15 +567,15 @@ void dequantize_iq3_xxs(device const block_iq3_xxs * xb, short il, thread type4x constant uint8_t * grid2 = (constant uint8_t *)(iq3xxs_grid + q3[4*il+1]); uint8_t signs = ksigns_iq2xs[(aux32 >> 14*il) & 127]; for (int i = 0; i < 4; ++i) { - reg[0][i] = dl * grid1[i] * (signs & kmask_iq2xs[i+0] ? -1.f : 1.f); - reg[1][i] = dl * grid2[i] * (signs & kmask_iq2xs[i+4] ? -1.f : 1.f); + reg[0][i] = (typename value_type::type) (dl * grid1[i] * (signs & kmask_iq2xs[i+0] ? -1.f : 1.f)); + reg[1][i] = (typename value_type::type) (dl * grid2[i] * (signs & kmask_iq2xs[i+4] ? -1.f : 1.f)); } grid1 = (constant uint8_t *)(iq3xxs_grid + q3[4*il+2]); grid2 = (constant uint8_t *)(iq3xxs_grid + q3[4*il+3]); signs = ksigns_iq2xs[(aux32 >> (14*il+7)) & 127]; for (int i = 0; i < 4; ++i) { - reg[2][i] = dl * grid1[i] * (signs & kmask_iq2xs[i+0] ? -1.f : 1.f); - reg[3][i] = dl * grid2[i] * (signs & kmask_iq2xs[i+4] ? -1.f : 1.f); + reg[2][i] = (typename value_type::type) (dl * grid1[i] * (signs & kmask_iq2xs[i+0] ? -1.f : 1.f)); + reg[3][i] = (typename value_type::type) (dl * grid2[i] * (signs & kmask_iq2xs[i+4] ? -1.f : 1.f)); } } @@ -593,14 +593,14 @@ void dequantize_iq3_s(device const block_iq3_s * xb, short il, thread type4x4 & constant uint8_t * grid1 = (constant uint8_t *)(iq3s_grid + (qs[4*il+0] | ((qh << 8) & 256))); constant uint8_t * grid2 = (constant uint8_t *)(iq3s_grid + (qs[4*il+1] | ((qh << 7) & 256))); for (int i = 0; i < 4; ++i) { - reg[0][i] = dl * grid1[i] * select(1, -1, signs[0] & kmask_iq2xs[i+0]); - reg[1][i] = dl * grid2[i] * select(1, -1, signs[0] & kmask_iq2xs[i+4]); + reg[0][i] = (typename value_type::type) (dl * grid1[i] * select(1, -1, signs[0] & kmask_iq2xs[i+0])); + reg[1][i] = (typename value_type::type) (dl * grid2[i] * select(1, -1, signs[0] & kmask_iq2xs[i+4])); } grid1 = (constant uint8_t *)(iq3s_grid + (qs[4*il+2] | ((qh << 6) & 256))); grid2 = (constant uint8_t *)(iq3s_grid + (qs[4*il+3] | ((qh << 5) & 256))); for (int i = 0; i < 4; ++i) { - reg[2][i] = dl * grid1[i] * select(1, -1, signs[1] & kmask_iq2xs[i+0]); - reg[3][i] = dl * grid2[i] * select(1, -1, signs[1] & kmask_iq2xs[i+4]); + reg[2][i] = (typename value_type::type) (dl * grid1[i] * select(1, -1, signs[1] & kmask_iq2xs[i+0])); + reg[3][i] = (typename value_type::type) (dl * grid2[i] * select(1, -1, signs[1] & kmask_iq2xs[i+4])); } } @@ -618,8 +618,8 @@ void dequantize_iq2_s(device const block_iq2_s * xb, short il, thread type4x4 & constant uint8_t * grid1 = (constant uint8_t *)(iq2s_grid + (qs[0] | ((qh << 8) & 0x300))); constant uint8_t * grid2 = (constant uint8_t *)(iq2s_grid + (qs[1] | ((qh << 6) & 0x300))); for (int i = 0; i < 8; ++i) { - reg[i/4+0][i%4] = dl * grid1[i] * select(1, -1, signs[0] & kmask_iq2xs[i]); - reg[i/4+2][i%4] = dl * grid2[i] * select(1, -1, signs[1] & kmask_iq2xs[i]); + reg[i/4+0][i%4] = (typename value_type::type) (dl * grid1[i] * select(1, -1, signs[0] & kmask_iq2xs[i])); + reg[i/4+2][i%4] = (typename value_type::type) (dl * grid2[i] * select(1, -1, signs[1] & kmask_iq2xs[i])); } } @@ -637,10 +637,10 @@ void dequantize_iq1_s(device const block_iq1_s * xb, short il, thread type4x4 & constant uint8_t * grid1 = (constant uint8_t *)(iq1s_grid_gpu + (qs[0] | ((h << 8) & 0x700))); constant uint8_t * grid2 = (constant uint8_t *)(iq1s_grid_gpu + (qs[1] | ((h << 5) & 0x700))); for (int i = 0; i < 4; ++i) { - reg[0][i] = dl * (grid1[i] & 0xf) + ml; - reg[1][i] = dl * (grid1[i] >> 4) + ml; - reg[2][i] = dl * (grid2[i] & 0xf) + ml; - reg[3][i] = dl * (grid2[i] >> 4) + ml; + reg[0][i] = (typename value_type::type) (dl * (grid1[i] & 0xf) + ml); + reg[1][i] = (typename value_type::type) (dl * (grid1[i] >> 4) + ml); + reg[2][i] = (typename value_type::type) (dl * (grid2[i] & 0xf) + ml); + reg[3][i] = (typename value_type::type) (dl * (grid2[i] >> 4) + ml); } } @@ -664,10 +664,10 @@ void dequantize_iq1_m(device const block_iq1_m * xb, short il, thread type4x4 & constant uint8_t * grid1 = (constant uint8_t *)(iq1s_grid_gpu + (qs[0] | ((qh[0] << 8) & 0x700))); constant uint8_t * grid2 = (constant uint8_t *)(iq1s_grid_gpu + (qs[1] | ((qh[0] << 4) & 0x700))); for (int i = 0; i < 4; ++i) { - reg[0][i] = dl * (grid1[i] & 0xf) + ml1; - reg[1][i] = dl * (grid1[i] >> 4) + ml1; - reg[2][i] = dl * (grid2[i] & 0xf) + ml2; - reg[3][i] = dl * (grid2[i] >> 4) + ml2; + reg[0][i] = (typename value_type::type) (dl * (grid1[i] & 0xf) + ml1); + reg[1][i] = (typename value_type::type) (dl * (grid1[i] >> 4) + ml1); + reg[2][i] = (typename value_type::type) (dl * (grid2[i] & 0xf) + ml2); + reg[3][i] = (typename value_type::type) (dl * (grid2[i] >> 4) + ml2); } } @@ -679,10 +679,10 @@ void dequantize_iq4_nl(device const block_iq4_nl * xb, short il, thread type4x4 thread const uint8_t * q8 = (thread const uint8_t *)&aux32; for (int i = 0; i < 4; ++i) { aux32 = ((q4[2*i] | (q4[2*i+1] << 16)) >> 4*il) & 0x0f0f0f0f; - reg[i][0] = d * kvalues_iq4nl_f[q8[0]]; - reg[i][1] = d * kvalues_iq4nl_f[q8[1]]; - reg[i][2] = d * kvalues_iq4nl_f[q8[2]]; - reg[i][3] = d * kvalues_iq4nl_f[q8[3]]; + reg[i][0] = (typename value_type::type) (d * kvalues_iq4nl_f[q8[0]]); + reg[i][1] = (typename value_type::type) (d * kvalues_iq4nl_f[q8[1]]); + reg[i][2] = (typename value_type::type) (d * kvalues_iq4nl_f[q8[2]]); + reg[i][3] = (typename value_type::type) (d * kvalues_iq4nl_f[q8[3]]); } } @@ -712,10 +712,10 @@ void dequantize_iq4_xs(device const block_iq4_xs * xb, short il, thread type4x4 thread const uint8_t * q8 = (thread const uint8_t *)&aux32; for (int i = 0; i < 4; ++i) { aux32 = (q4[i] >> 4*il) & 0x0f0f0f0f; - reg[i][0] = d * kvalues_iq4nl_f[q8[0]]; - reg[i][1] = d * kvalues_iq4nl_f[q8[1]]; - reg[i][2] = d * kvalues_iq4nl_f[q8[2]]; - reg[i][3] = d * kvalues_iq4nl_f[q8[3]]; + reg[i][0] = (typename value_type::type) (d * kvalues_iq4nl_f[q8[0]]); + reg[i][1] = (typename value_type::type) (d * kvalues_iq4nl_f[q8[1]]); + reg[i][2] = (typename value_type::type) (d * kvalues_iq4nl_f[q8[2]]); + reg[i][3] = (typename value_type::type) (d * kvalues_iq4nl_f[q8[3]]); } } diff --git a/ggml/src/ggml-metal/kernels/fa_common.metal b/ggml/src/ggml-metal/kernels/fa_common.metal index 5e08bf85fa89..35265bb1b7ee 100644 --- a/ggml/src/ggml-metal/kernels/fa_common.metal +++ b/ggml/src/ggml-metal/kernels/fa_common.metal @@ -17,28 +17,17 @@ constant int32_t FC_flash_attn_ext_nsg [[function_constant(FC_FLASH_ATTN_EXT + // ref: https://arxiv.org/pdf/2307.08691.pdf template< typename q_t, // query types in shared memory - typename q4_t, - typename q8x8_t, typename k_t, // key types in shared memory - typename k4x4_t, - typename k8x8_t, typename v_t, // value types in shared memory - typename v4x4_t, - typename v8x8_t, typename qk_t, // Q*K types - typename qk8x8_t, typename s_t, // soft-max types - typename s2_t, - typename s8x8_t, typename o_t, // attention accumulation types - typename o4_t, - typename o8x8_t, typename kd4x4_t, // key type in device memory short nl_k, - void (*deq_k)(device const kd4x4_t *, short, thread k4x4_t &), + void (*deq_k)(device const kd4x4_t *, short, thread typename value_type_4x4::type &), typename vd4x4_t, // value type in device memory short nl_v, - void (*deq_v)(device const vd4x4_t *, short, thread v4x4_t &), + void (*deq_v)(device const vd4x4_t *, short, thread typename value_type_4x4::type &), short DK, // K head size short DV, // V head size short Q, // queries per threadgroup @@ -58,6 +47,18 @@ void kernel_flash_attn_ext_impl( uint3 tgpig, ushort tiisg, ushort sgitg) { + using q4_t = typename value_type_4 ::type; + using q8x8_t = typename value_type_8x8 ::type; + using k4x4_t = typename value_type_4x4 ::type; + using k8x8_t = typename value_type_8x8 ::type; + using v4x4_t = typename value_type_4x4 ::type; + using v8x8_t = typename value_type_8x8 ::type; + using qk8x8_t = typename value_type_8x8::type; + using s2_t = typename value_type_2 ::type; + using s8x8_t = typename value_type_8x8 ::type; + using o4_t = typename value_type_4 ::type; + using o8x8_t = typename value_type_8x8 ::type; + const ushort iq3 = tgpig[2]; const ushort iq2 = tgpig[1]; const ushort iq1 = tgpig[0]*Q; @@ -656,28 +657,17 @@ void kernel_flash_attn_ext_impl( template< typename q_t, // query types in shared memory - typename q4_t, - typename q8x8_t, typename k_t, // key types in shared memory - typename k4x4_t, - typename k8x8_t, typename v_t, // value types in shared memory - typename v4x4_t, - typename v8x8_t, typename qk_t, // Q*K types - typename qk8x8_t, typename s_t, // soft-max types - typename s2_t, - typename s8x8_t, typename o_t, // attention accumulation types - typename o4_t, - typename o8x8_t, typename kd4x4_t, // key type in device memory short nl_k, - void (*deq_k)(device const kd4x4_t *, short, thread k4x4_t &), + void (*deq_k)(device const kd4x4_t *, short, thread typename value_type_4x4::type &), typename vd4x4_t, // value type in device memory short nl_v, - void (*deq_v)(device const vd4x4_t *, short, thread v4x4_t &), + void (*deq_v)(device const vd4x4_t *, short, thread typename value_type_4x4::type &), short DK, // K head size short DV, // V head size short Q = OP_FLASH_ATTN_EXT_NQPSG, // queries per threadgroup @@ -696,7 +686,7 @@ kernel void kernel_flash_attn_ext( uint3 tgpig[[threadgroup_position_in_grid]], ushort tiisg[[thread_index_in_simdgroup]], ushort sgitg[[simdgroup_index_in_threadgroup]]) { -#define FWD_TMPL q_t, q4_t, q8x8_t, k_t, k4x4_t, k8x8_t, v_t, v4x4_t, v8x8_t, qk_t, qk8x8_t, s_t, s2_t, s8x8_t, o_t, o4_t, o8x8_t, kd4x4_t, nl_k, deq_k, vd4x4_t, nl_v, deq_v, DK, DV, Q, C +#define FWD_TMPL q_t, k_t, v_t, qk_t, s_t, o_t, kd4x4_t, nl_k, deq_k, vd4x4_t, nl_v, deq_v, DK, DV, Q, C #define FWD_ARGS args, q, k, v, mask, sinks, pad, blk, dst, shmem_f16, tgpig, tiisg, sgitg switch (FC_flash_attn_ext_nsg) { // note: disabled cases to reduce library load time diff --git a/ggml/src/ggml-metal/kernels/fa_f16.metal b/ggml/src/ggml-metal/kernels/fa_f16.metal index 6e30b09e3a5a..616b9377acfc 100644 --- a/ggml/src/ggml-metal/kernels/fa_f16.metal +++ b/ggml/src/ggml-metal/kernels/fa_f16.metal @@ -6,31 +6,28 @@ // template to be able to explore different combinations #define FA_TYPES \ - half, half4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_BF \ - bfloat, bfloat4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - half, half4, simdgroup_half8x8 - //float, float4, simdgroup_float8x8 + bfloat, \ + bfloat, \ + bfloat, \ + float, \ + float, \ + half #define FA_TYPES_F32 \ - half, half4, simdgroup_half8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext) flash_attn_ext_t; diff --git a/ggml/src/ggml-metal/kernels/fa_f32.metal b/ggml/src/ggml-metal/kernels/fa_f32.metal index 449079e8f6e5..15e499cbf00c 100644 --- a/ggml/src/ggml-metal/kernels/fa_f32.metal +++ b/ggml/src/ggml-metal/kernels/fa_f32.metal @@ -3,31 +3,28 @@ #include "fa_common.metal" #define FA_TYPES \ - half, half4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_BF \ - bfloat, bfloat4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - half, half4, simdgroup_half8x8 - //float, float4, simdgroup_float8x8 + bfloat, \ + bfloat, \ + bfloat, \ + float, \ + float, \ + half #define FA_TYPES_F32 \ - half, half4, simdgroup_half8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext) flash_attn_ext_t; diff --git a/ggml/src/ggml-metal/kernels/fa_q4_0.metal b/ggml/src/ggml-metal/kernels/fa_q4_0.metal index 6b05b5df6bdf..812f1f25ec79 100644 --- a/ggml/src/ggml-metal/kernels/fa_q4_0.metal +++ b/ggml/src/ggml-metal/kernels/fa_q4_0.metal @@ -3,31 +3,28 @@ #include "fa_common.metal" #define FA_TYPES \ - half, half4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_BF \ - bfloat, bfloat4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - half, half4, simdgroup_half8x8 - //float, float4, simdgroup_float8x8 + bfloat, \ + bfloat, \ + bfloat, \ + float, \ + float, \ + half #define FA_TYPES_F32 \ - half, half4, simdgroup_half8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext) flash_attn_ext_t; diff --git a/ggml/src/ggml-metal/kernels/fa_q4_1.metal b/ggml/src/ggml-metal/kernels/fa_q4_1.metal index 87fac701ea92..10f5c7946fae 100644 --- a/ggml/src/ggml-metal/kernels/fa_q4_1.metal +++ b/ggml/src/ggml-metal/kernels/fa_q4_1.metal @@ -3,31 +3,28 @@ #include "fa_common.metal" #define FA_TYPES \ - half, half4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_BF \ - bfloat, bfloat4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - half, half4, simdgroup_half8x8 - //float, float4, simdgroup_float8x8 + bfloat, \ + bfloat, \ + bfloat, \ + float, \ + float, \ + half #define FA_TYPES_F32 \ - half, half4, simdgroup_half8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext) flash_attn_ext_t; diff --git a/ggml/src/ggml-metal/kernels/fa_q5_0.metal b/ggml/src/ggml-metal/kernels/fa_q5_0.metal index cd0e31f715a7..d0ce34ea931f 100644 --- a/ggml/src/ggml-metal/kernels/fa_q5_0.metal +++ b/ggml/src/ggml-metal/kernels/fa_q5_0.metal @@ -3,31 +3,28 @@ #include "fa_common.metal" #define FA_TYPES \ - half, half4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_BF \ - bfloat, bfloat4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - half, half4, simdgroup_half8x8 - //float, float4, simdgroup_float8x8 + bfloat, \ + bfloat, \ + bfloat, \ + float, \ + float, \ + half #define FA_TYPES_F32 \ - half, half4, simdgroup_half8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext) flash_attn_ext_t; diff --git a/ggml/src/ggml-metal/kernels/fa_q5_1.metal b/ggml/src/ggml-metal/kernels/fa_q5_1.metal index 4d74951acc5f..dee7fee1b2b2 100644 --- a/ggml/src/ggml-metal/kernels/fa_q5_1.metal +++ b/ggml/src/ggml-metal/kernels/fa_q5_1.metal @@ -3,31 +3,28 @@ #include "fa_common.metal" #define FA_TYPES \ - half, half4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_BF \ - bfloat, bfloat4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - half, half4, simdgroup_half8x8 - //float, float4, simdgroup_float8x8 + bfloat, \ + bfloat, \ + bfloat, \ + float, \ + float, \ + half #define FA_TYPES_F32 \ - half, half4, simdgroup_half8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext) flash_attn_ext_t; diff --git a/ggml/src/ggml-metal/kernels/fa_q8_0.metal b/ggml/src/ggml-metal/kernels/fa_q8_0.metal index bb29a262c1ea..52ad4fe6489d 100644 --- a/ggml/src/ggml-metal/kernels/fa_q8_0.metal +++ b/ggml/src/ggml-metal/kernels/fa_q8_0.metal @@ -3,31 +3,28 @@ #include "fa_common.metal" #define FA_TYPES \ - half, half4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_BF \ - bfloat, bfloat4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - half, half4, simdgroup_half8x8 - //float, float4, simdgroup_float8x8 + bfloat, \ + bfloat, \ + bfloat, \ + float, \ + float, \ + half #define FA_TYPES_F32 \ - half, half4, simdgroup_half8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext) flash_attn_ext_t; diff --git a/ggml/src/ggml-metal/kernels/fa_tensor.metal b/ggml/src/ggml-metal/kernels/fa_tensor.metal index 4a9ed30e3b25..8fba8f63b5a9 100644 --- a/ggml/src/ggml-metal/kernels/fa_tensor.metal +++ b/ggml/src/ggml-metal/kernels/fa_tensor.metal @@ -10,7 +10,6 @@ constant bool FC_flash_attn_ext_tensor_has_scap [[function_constant(FC_FLASH_AT // ref: https://arxiv.org/pdf/2307.08691.pdf template< typename T, // Q, K, V and P types - typename T4, short DK, // K head size short DV, // V head size short Q = OP_FLASH_ATTN_EXT_TENSOR_NQPSG, // queries per threadgroup @@ -29,6 +28,8 @@ kernel void kernel_flash_attn_ext_tensor( uint3 tgpig [[threadgroup_position_in_grid]], ushort tiisg [[thread_index_in_simdgroup]], ushort sgitg [[simdgroup_index_in_threadgroup]]) { + using T4 = typename value_type_4::type; + constexpr short NW = N_SIMDWIDTH; constexpr short NT = NW*NSG; constexpr short NQ = Q/NSG; @@ -279,20 +280,20 @@ kernel void kernel_flash_attn_ext_tensor( co.store(td); } -typedef decltype(kernel_flash_attn_ext_tensor) flash_attn_ext_tensor_t; - -template [[host_name("kernel_flash_attn_ext_tensor_f16_dk64_dv64" )]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; -template [[host_name("kernel_flash_attn_ext_tensor_f16_dk128_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; -template [[host_name("kernel_flash_attn_ext_tensor_f16_dk192_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; -template [[host_name("kernel_flash_attn_ext_tensor_f16_dk256_dv256")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; -template [[host_name("kernel_flash_attn_ext_tensor_f16_dk512_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; -template [[host_name("kernel_flash_attn_ext_tensor_f16_dk576_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; - -template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk64_dv64" )]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; -template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk128_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; -template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk192_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; -template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk256_dv256")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; -template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk512_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; -template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk576_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +typedef decltype(kernel_flash_attn_ext_tensor) flash_attn_ext_tensor_t; + +template [[host_name("kernel_flash_attn_ext_tensor_f16_dk64_dv64" )]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +template [[host_name("kernel_flash_attn_ext_tensor_f16_dk128_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +template [[host_name("kernel_flash_attn_ext_tensor_f16_dk192_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +template [[host_name("kernel_flash_attn_ext_tensor_f16_dk256_dv256")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +template [[host_name("kernel_flash_attn_ext_tensor_f16_dk512_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +template [[host_name("kernel_flash_attn_ext_tensor_f16_dk576_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; + +template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk64_dv64" )]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk128_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk192_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk256_dv256")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk512_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk576_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; #endif // GGML_METAL_HAS_TENSOR diff --git a/ggml/src/ggml-metal/kernels/fa_vec_common.metal b/ggml/src/ggml-metal/kernels/fa_vec_common.metal index 1a96c6f7ec8b..cf37e492442b 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_common.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_common.metal @@ -15,19 +15,18 @@ constant int32_t FC_flash_attn_ext_vec_nwg [[function_constant(FC_FLASH_ATTN_EX constant bool FC_flash_attn_ext_vec_has_sparse [[function_constant(FC_FLASH_ATTN_EXT_VEC + 5)]]; constant bool FC_flash_attn_ext_vec_has_rows [[function_constant(FC_FLASH_ATTN_EXT_VEC + 6)]]; template< - typename q4_t, // query types in shared memory - typename k4_t, // key types in shared memory - typename v4_t, // value types in shared memory + typename q_t, // query types in shared memory + typename k_t, // key types in shared memory + typename v_t, // value types in shared memory typename qk_t, // Q*K types typename s_t, // soft-max types - typename s4_t, - typename o4_t, // attention accumulation types + typename o_t, // attention accumulation types typename kd4_t, // key type in device memory short nl_k, - void (*deq_k_t4)(device const kd4_t *, short, thread k4_t &), + void (*deq_k_t4)(device const kd4_t *, short, thread typename value_type_4::type &), typename vd4_t, // value type in device memory short nl_v, - void (*deq_v_t4)(device const vd4_t *, short, thread v4_t &), + void (*deq_v_t4)(device const vd4_t *, short, thread typename value_type_4::type &), short DK, // K head size short DV, // V head size short NE = 4, // head elements per thread @@ -48,6 +47,12 @@ kernel void kernel_flash_attn_ext_vec( uint3 tgpig[[threadgroup_position_in_grid]], ushort tiisg[[thread_index_in_simdgroup]], ushort sgitg[[simdgroup_index_in_threadgroup]]) { + using q4_t = typename value_type_4::type; + using k4_t = typename value_type_4::type; + using v4_t = typename value_type_4::type; + using s4_t = typename value_type_4::type; + using o4_t = typename value_type_4::type; + static_assert(DK % 32 == 0, "DK must be divisible by 32"); static_assert(DV % 32 == 0, "DV must be divisible by 32"); diff --git a/ggml/src/ggml-metal/kernels/fa_vec_f16.metal b/ggml/src/ggml-metal/kernels/fa_vec_f16.metal index bea54f9f73fd..94377e39fef5 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_f16.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_f16.metal @@ -3,20 +3,20 @@ #include "fa_vec_common.metal" #define FA_TYPES \ - half4, \ - half4, \ - half4, \ - float, \ - float, float4, \ - float4 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_F32 \ - half4, \ - float4, \ - float4, \ - float, \ - float, float4, \ - float4 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext_vec) flash_attn_ext_vec_t; diff --git a/ggml/src/ggml-metal/kernels/fa_vec_f32.metal b/ggml/src/ggml-metal/kernels/fa_vec_f32.metal index 18f862966a78..ebc0b4791c26 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_f32.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_f32.metal @@ -3,20 +3,20 @@ #include "fa_vec_common.metal" #define FA_TYPES \ - half4, \ - half4, \ - half4, \ - float, \ - float, float4, \ - float4 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_F32 \ - half4, \ - float4, \ - float4, \ - float, \ - float, float4, \ - float4 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext_vec) flash_attn_ext_vec_t; diff --git a/ggml/src/ggml-metal/kernels/fa_vec_q4_0.metal b/ggml/src/ggml-metal/kernels/fa_vec_q4_0.metal index 6bf5fad75cf1..3a496f313f3f 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_q4_0.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_q4_0.metal @@ -3,20 +3,20 @@ #include "fa_vec_common.metal" #define FA_TYPES \ - half4, \ - half4, \ - half4, \ - float, \ - float, float4, \ - float4 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_F32 \ - half4, \ - float4, \ - float4, \ - float, \ - float, float4, \ - float4 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext_vec) flash_attn_ext_vec_t; diff --git a/ggml/src/ggml-metal/kernels/fa_vec_q4_1.metal b/ggml/src/ggml-metal/kernels/fa_vec_q4_1.metal index 37277ee10203..5c7424665893 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_q4_1.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_q4_1.metal @@ -3,20 +3,20 @@ #include "fa_vec_common.metal" #define FA_TYPES \ - half4, \ - half4, \ - half4, \ - float, \ - float, float4, \ - float4 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_F32 \ - half4, \ - float4, \ - float4, \ - float, \ - float, float4, \ - float4 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext_vec) flash_attn_ext_vec_t; diff --git a/ggml/src/ggml-metal/kernels/fa_vec_q5_0.metal b/ggml/src/ggml-metal/kernels/fa_vec_q5_0.metal index 26868a228a40..509f0f1b34d1 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_q5_0.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_q5_0.metal @@ -3,20 +3,20 @@ #include "fa_vec_common.metal" #define FA_TYPES \ - half4, \ - half4, \ - half4, \ - float, \ - float, float4, \ - float4 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_F32 \ - half4, \ - float4, \ - float4, \ - float, \ - float, float4, \ - float4 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext_vec) flash_attn_ext_vec_t; diff --git a/ggml/src/ggml-metal/kernels/fa_vec_q5_1.metal b/ggml/src/ggml-metal/kernels/fa_vec_q5_1.metal index 9d39dc58a8d5..77cd8131e53b 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_q5_1.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_q5_1.metal @@ -3,20 +3,20 @@ #include "fa_vec_common.metal" #define FA_TYPES \ - half4, \ - half4, \ - half4, \ - float, \ - float, float4, \ - float4 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_F32 \ - half4, \ - float4, \ - float4, \ - float, \ - float, float4, \ - float4 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext_vec) flash_attn_ext_vec_t; diff --git a/ggml/src/ggml-metal/kernels/fa_vec_q8_0.metal b/ggml/src/ggml-metal/kernels/fa_vec_q8_0.metal index 7686ccc00126..dd789c89d710 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_q8_0.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_q8_0.metal @@ -3,20 +3,20 @@ #include "fa_vec_common.metal" #define FA_TYPES \ - half4, \ - half4, \ - half4, \ - float, \ - float, float4, \ - float4 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_F32 \ - half4, \ - float4, \ - float4, \ - float, \ - float, float4, \ - float4 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext_vec) flash_attn_ext_vec_t; diff --git a/ggml/src/ggml-metal/kernels/misc.metal b/ggml/src/ggml-metal/kernels/misc.metal index 5dfd4a60c3ab..51b435aeb47f 100644 --- a/ggml/src/ggml-metal/kernels/misc.metal +++ b/ggml/src/ggml-metal/kernels/misc.metal @@ -465,6 +465,8 @@ kernel void kernel_count_equal( ushort sgitg[[simdgroup_index_in_threadgroup]], ushort tiisg[[thread_index_in_simdgroup]], ushort3 ntg[[threads_per_threadgroup]]) { + using T4 = typename value_type_4::type; + const short NSG = FC_count_equal_nsg; const int i3 = tgpig.z; @@ -913,12 +915,14 @@ constant bool FC_top_k_mask_has_extra [[function_constant(FC_TOP_K_MASK + 2)]]; constant bool FC_top_k_mask_vec [[function_constant(FC_TOP_K_MASK + 3)]]; // the fill runs before the scatter, both are fully parallel over the whole dst and over the picks of one row -template +template kernel void kernel_top_k_mask_fill( constant ggml_metal_kargs_top_k_mask & args, device char * dst, uint tid[[thread_position_in_grid]], uint ntot[[threads_per_grid]]) { + using T4 = typename value_type_4::type; + const T ninf = T(-INFINITY); if (FC_top_k_mask_vec) { @@ -934,14 +938,14 @@ kernel void kernel_top_k_mask_fill( } } -typedef decltype(kernel_top_k_mask_fill) kernel_top_k_mask_fill_h_t; -typedef decltype(kernel_top_k_mask_fill) kernel_top_k_mask_fill_f_t; +typedef decltype(kernel_top_k_mask_fill) kernel_top_k_mask_fill_h_t; +typedef decltype(kernel_top_k_mask_fill) kernel_top_k_mask_fill_f_t; -template [[host_name("kernel_top_k_mask_fill_f16")]] kernel kernel_top_k_mask_fill_h_t kernel_top_k_mask_fill; -template [[host_name("kernel_top_k_mask_fill_f32")]] kernel kernel_top_k_mask_fill_f_t kernel_top_k_mask_fill; +template [[host_name("kernel_top_k_mask_fill_f16")]] kernel kernel_top_k_mask_fill_h_t kernel_top_k_mask_fill; +template [[host_name("kernel_top_k_mask_fill_f32")]] kernel kernel_top_k_mask_fill_f_t kernel_top_k_mask_fill; // one threadgroup per row: copy the mask cells of the live picks and of the extra cells over the fill -template +template kernel void kernel_top_k_mask( constant ggml_metal_kargs_top_k_mask & args, device const char * mask, @@ -953,6 +957,8 @@ kernel void kernel_top_k_mask( uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg_max[[threads_per_threadgroup]]) { + using T4 = typename value_type_4::type; + const int i1 = tgpig.x; const int i2 = tgpig.y; const int i3 = tgpig.z; @@ -997,8 +1003,8 @@ kernel void kernel_top_k_mask( } } -typedef decltype(kernel_top_k_mask) kernel_top_k_mask_h_t; -typedef decltype(kernel_top_k_mask) kernel_top_k_mask_f_t; +typedef decltype(kernel_top_k_mask) kernel_top_k_mask_h_t; +typedef decltype(kernel_top_k_mask) kernel_top_k_mask_f_t; -template [[host_name("kernel_top_k_mask_f16")]] kernel kernel_top_k_mask_h_t kernel_top_k_mask; -template [[host_name("kernel_top_k_mask_f32")]] kernel kernel_top_k_mask_f_t kernel_top_k_mask; +template [[host_name("kernel_top_k_mask_f16")]] kernel kernel_top_k_mask_h_t kernel_top_k_mask; +template [[host_name("kernel_top_k_mask_f32")]] kernel kernel_top_k_mask_f_t kernel_top_k_mask; diff --git a/ggml/src/ggml-metal/kernels/mul_mm.metal b/ggml/src/ggml-metal/kernels/mul_mm.metal index fab720097399..e16a8ec79649 100644 --- a/ggml/src/ggml-metal/kernels/mul_mm.metal +++ b/ggml/src/ggml-metal/kernels/mul_mm.metal @@ -1,157 +1,20 @@ #include "common.h" #include "dequantize.h" -constant bool FC_mul_mm_bc_inp [[function_constant(FC_MUL_MM + 0)]]; -constant bool FC_mul_mm_bc_out [[function_constant(FC_MUL_MM + 1)]]; -constant short FC_mul_mm_ne12 [[function_constant(FC_MUL_MM + 2)]]; -constant short FC_mul_mm_ne13 [[function_constant(FC_MUL_MM + 3)]]; -constant short FC_mul_mm_r2 [[function_constant(FC_MUL_MM + 4)]]; -constant short FC_mul_mm_r3 [[function_constant(FC_MUL_MM + 5)]]; +constant bool FC_mul_mm_bc_inp [[function_constant(FC_MUL_MM + 0)]]; +constant bool FC_mul_mm_bc_out [[function_constant(FC_MUL_MM + 1)]]; +constant short FC_mul_mm_ne12 [[function_constant(FC_MUL_MM + 2)]]; +constant short FC_mul_mm_ne13 [[function_constant(FC_MUL_MM + 3)]]; +constant short FC_mul_mm_r2 [[function_constant(FC_MUL_MM + 4)]]; +constant short FC_mul_mm_r3 [[function_constant(FC_MUL_MM + 5)]]; constant int32_t FC_mul_mm_id_map0_ne02 [[function_constant(FC_MUL_MM + 7)]]; // each block_q contains 16*nl weights -#ifdef GGML_METAL_HAS_TENSOR -template< - typename SA, typename SA_4x4, typename SA_8x8, - typename SB, typename SB_2x4, typename SB_8x8, - typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread SA_4x4 &), - typename T0, typename T0_4x4, typename T1, typename T1_2x4> -kernel void kernel_mul_mm( - constant ggml_metal_kargs_mul_mm & args, - device const char * srcA, - device const char * srcB, - device char * dst, - threadgroup char * shmem [[threadgroup(0)]], - uint3 tgpig [[threadgroup_position_in_grid]], - ushort tiitg [[thread_index_in_threadgroup]], - ushort sgitg [[simdgroup_index_in_threadgroup]]) { - (void) sgitg; - - // Matrix dimensions: A(M,K) x B(K,N) -> C(M,N) - const int K = args.ne00; - const int M = args.ne0; - const int N = args.ne1; - - // Batch dimension handling - const int im = tgpig.z; - const int i12 = im % FC_mul_mm_ne12; - const int i13 = im / FC_mul_mm_ne12; - - // Batch offsets for srcA and srcB - const uint64_t offset0 = (i12/FC_mul_mm_r2)*args.nb02 + (i13/FC_mul_mm_r3)*args.nb03; - - // Tile dimensions - constexpr int NRB = SZ_SIMDGROUP * N_MM_BLOCK_X * N_MM_SIMD_GROUP_X; - constexpr int NRA = SZ_SIMDGROUP * N_MM_BLOCK_Y * N_MM_SIMD_GROUP_Y; - - // Tile offsets in output matrix - const int ra = tgpig.y * NRA; - const int rb = tgpig.x * NRB; - - // Threadgroup memory for dequantized A tile only - threadgroup SA * sa = (threadgroup SA *)(shmem); - - // Work-item count for A loading - constexpr int A_WORK_ITEMS = NRA * N_MM_NK; - constexpr int NUM_THREADS = N_SIMDWIDTH * N_MM_SIMD_GROUP_X * N_MM_SIMD_GROUP_Y; - - // tA wraps threadgroup memory - auto tA = tensor(sa, dextents(N_MM_NK_TOTAL, NRA)); - - // tB wraps device memory directly - device T1 * ptrB = (device T1 *)(srcB + args.nb12*i12 + args.nb13*i13); - const int strideB = args.nb11 / sizeof(T1); - auto tB = tensor(ptrB, dextents(K, N), array({1, strideB})); - - // Configure matmul operation - // note: K is dynamic_extent (clamped to the valid range in PHASE 2), since a static - // N_MM_NK_TOTAL K tile would read src1 out of bounds when K % N_MM_NK_TOTAL != 0 - // ref: https://github.com/ggml-org/llama.cpp/pull/27064 - mpp::tensor_ops::matmul2d< - mpp::tensor_ops::matmul2d_descriptor( - NRB, NRA, static_cast(dynamic_extent), false, true, true, - mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate), - execution_simdgroups> mm; - - auto cT = mm.get_destination_cooperative_tensor(); - - // Accumulate partial results over K dimension - for (int loop_k = 0; loop_k < K; loop_k += N_MM_NK_TOTAL) { - // === PHASE 1: Dequantization of A into threadgroup memory === - for (int work = tiitg; work < A_WORK_ITEMS; work += NUM_THREADS) { - const int row = work / N_MM_NK; - const int k_chunk = work % N_MM_NK; - const int k_pos = loop_k + k_chunk * 16; - const short k_base = k_chunk * 16; - - // Bounds check: skip device read if row is out of matrix bounds - if (ra + row < M) { - if (is_same::value && FC_mul_mm_bc_inp) { - // Element-wise reads when K is not aligned (nb01 not aligned for half4x4/float4x4). - // MSL spec Table 2.5: half4x4 requires 8-byte alignment. When K is odd, - // nb01 = K*2 is not 8-byte aligned, so odd-row pointers are misaligned. - // Mirrors the legacy kernel's existing guard. - device const T0 * row_ptr = (device const T0 *)(srcA + args.nb01 * (ra + row) + offset0); - - FOR_UNROLL (short i = 0; i < 16; i++) { - sa[row * N_MM_NK_TOTAL + (k_base + i)] = (k_pos + i < K) ? (SA) row_ptr[k_pos + i] : (SA)0; - } - } else { - const int block_idx = k_pos / (16 * nl); - const short il = (k_pos / 16) % nl; - - device const block_q * row_ptr = (device const block_q *)(srcA + args.nb01 * (ra + row) + offset0); - - SA_4x4 temp_a; - dequantize_func(row_ptr + block_idx, il, temp_a); - - FOR_UNROLL (short i = 0; i < 16; i++) { - // Zero-pad A for K positions beyond valid range (handles partial K iterations) - sa[row * N_MM_NK_TOTAL + (k_base + i)] = (k_pos + i < K) ? temp_a[i/4][i%4] : (SA)0; - } - } - } else { - // Zero-pad rows beyond matrix bounds - FOR_UNROLL (short i = 0; i < 16; i++) { - sa[row * N_MM_NK_TOTAL + (k_base + i)] = (SA)0; - } - } - } - - threadgroup_barrier(mem_flags::mem_threadgroup); - - // === PHASE 2: Tensor matmul === - // Clamp the K extent of both operand tensors to the remaining valid K range so - // the dynamic-K op never reads past the K extent of src1 (or the staged A tile). - const int kExt = min(N_MM_NK_TOTAL, K - loop_k); - - auto tAv = tensor(sa, dextents(kExt, NRA), array({1, N_MM_NK_TOTAL})); - auto tBv = tensor(ptrB + loop_k + rb * strideB, dextents(kExt, N - rb), array({1, strideB})); - - mm.run(tBv, tAv, cT); - - threadgroup_barrier(mem_flags::mem_threadgroup); - } - - // Store result tile to output matrix (with batch offset) - // a slice is not used because its byte offset is int32 and wraps at 2 GiB - // ref: https://github.com/ggml-org/llama.cpp/pull/28748 - const int tileM = min(NRA, M - ra); - const int tileN = min(NRB, N - rb); - - device float * dstTile = (device float *)dst + (uint64_t) im * N * M + (uint64_t) rb * M + ra; - - auto tD = tensor(dstTile, dextents(tileM, tileN), array({1, M})); - cT.store(tD); -} - -#else template< - typename S0, typename S0_4x4, typename S0_8x8, - typename S1, typename S1_2x4, typename S1_8x8, - typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread S0_4x4 &), - typename T0, typename T0_4x4, typename T1, typename T1_2x4> + typename S0, typename S1, + typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread typename value_type_4x4::type &), + typename T0, typename T1> kernel void kernel_mul_mm( constant ggml_metal_kargs_mul_mm & args, device const char * src0, @@ -162,8 +25,12 @@ kernel void kernel_mul_mm( ushort tiitg[[thread_index_in_threadgroup]], ushort sgitg[[simdgroup_index_in_threadgroup]]) { - threadgroup S0 * sa = (threadgroup S0 *)(shmem); - threadgroup S1 * sb = (threadgroup S1 *)(shmem + 4096); + using S0_4x4 = typename value_type_4x4::type; + using S0_8x8 = typename value_type_8x8::type; + using S1_2x4 = typename value_type_2x4::type; + using S1_8x8 = typename value_type_8x8::type; + using T0_4x4 = typename value_type_4x4::type; + using T1_2x4 = typename value_type_2x4::type; constexpr int NR0 = 64; constexpr int NR1 = 32; @@ -172,6 +39,9 @@ kernel void kernel_mul_mm( constexpr int NL0 = NK/16; constexpr int NL1 = NK/8; + threadgroup S0 * sa = (threadgroup S0 *)(shmem); + threadgroup S1 * sb = (threadgroup S1 *)(shmem + NR0*NK*sizeof(S0)); + const int im = tgpig.z; const int r0 = tgpig.y*NR0; const int r1 = tgpig.x*NR1; @@ -362,7 +232,6 @@ kernel void kernel_mul_mm( } } -#endif // GGML_METAL_HAS_TENSOR template // n_expert_used kernel void kernel_mul_mm_id_map0( @@ -544,8 +413,7 @@ template [[host_name("kernel_mul_mm_id_map0_ne20_10")]] kernel kernel_mul_mm_id_ template [[host_name("kernel_mul_mm_id_map0_ne20_16")]] kernel kernel_mul_mm_id_map0_t kernel_mul_mm_id_map0<16>; template [[host_name("kernel_mul_mm_id_map0_ne20_22")]] kernel kernel_mul_mm_id_map0_t kernel_mul_mm_id_map0<22>; -// TODO: refactor into two seperate functions to avoid ifdef branching: with and without tensor support -template +template::type &), typename T0, typename T1> kernel void kernel_mul_mm_id( constant ggml_metal_kargs_mul_mm_id & args, device const char * src0, @@ -558,12 +426,12 @@ kernel void kernel_mul_mm_id( ushort tiitg[[thread_index_in_threadgroup]], ushort tiisg[[thread_index_in_simdgroup]], ushort sgitg[[simdgroup_index_in_threadgroup]]) { - threadgroup S0 * sa = (threadgroup S0 *)(shmem); - threadgroup S1 * sb = (threadgroup S1 *)(shmem + 4096); - -#ifdef GGML_METAL_HAS_TENSOR - threadgroup float * sc = (threadgroup float *)(shmem); -#endif + using S0_4x4 = typename value_type_4x4::type; + using S0_8x8 = typename value_type_8x8::type; + using S1_2x4 = typename value_type_2x4::type; + using S1_8x8 = typename value_type_8x8::type; + using T0_4x4 = typename value_type_4x4::type; + using T1_2x4 = typename value_type_2x4::type; constexpr int NR0 = 64; constexpr int NR1 = 32; @@ -572,6 +440,10 @@ kernel void kernel_mul_mm_id( constexpr int NL0 = NK/16; constexpr int NL1 = NK/8; + threadgroup S0 * sa = (threadgroup S0 *)(shmem); + threadgroup S1 * sb = (threadgroup S1 *)(shmem + NR0*NK*sizeof(S0)); + + const int tile = tgpig.x; // entry tile, described by the prepass const int r0 = tgpig.y*NR0; @@ -608,23 +480,10 @@ kernel void kernel_mul_mm_id( // skip the upper half of the token tile when the expert did not fill it constexpr short NR1H = NR1/2; -#ifndef GGML_METAL_HAS_TENSOR S0_8x8 ma[4]; S1_8x8 mb[2]; simdgroup_float8x8 mc[8]; -#else - auto tA = tensor, tensor_inline>(sa, dextents(NK, NR0)); - - // sb is [NR1][NK] row-major - auto tB0 = tensor, tensor_inline>(sb, dextents(NK, NR1H)); - auto tB1 = tensor, tensor_inline>(sb + NR1H*NK, dextents(NK, NR1H)); - - mpp::tensor_ops::matmul2d< - mpp::tensor_ops::matmul2d_descriptor(NR1H, NR0, NK, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate), - execution_simdgroups<4>> mm; - -#endif const short lr1 = ((short)tiitg/NL1) < nr1 ? ((short)tiitg/NL1) : nr1 - 1; // 0 .. 31 @@ -645,20 +504,14 @@ kernel void kernel_mul_mm_id( const bool has_hi = nr1 > NR1H; -#ifndef GGML_METAL_HAS_TENSOR for (short i = 0; i < 8; i++){ mc[i] = make_filled_simdgroup_matrix(0.f); } // simdgroups 2,3 own rows NR1H..NR1-1 const bool sg_active = has_hi || sgitg < 2; -#else - auto cT0 = mm.get_destination_cooperative_tensor(); - auto cT1 = mm.get_destination_cooperative_tensor(); -#endif for (int loop_k = 0; loop_k < args.ne00; loop_k += NK) { -#ifndef GGML_METAL_HAS_TENSOR // load data and store to threadgroup memory if (is_same::value && FC_mul_mm_bc_inp) { threadgroup_barrier(mem_flags::mem_threadgroup); @@ -728,66 +581,6 @@ kernel void kernel_mul_mm_id( *(threadgroup S1_2x4 *)(sb + 64*ib + 8*ly) = (S1_2x4)(*((device T1_2x4 *) y)); } -#else - // load data and store to threadgroup memory - if (is_same::value && FC_mul_mm_bc_inp) { - threadgroup_barrier(mem_flags::mem_threadgroup); - - // no need for dequantization - for (short i = 0; i < 16; i++) { - const short sx = 2*il0 + i/8; - const short sy = (tiitg/NL0)/8; - - const short lx = i%8; - const short ly = (tiitg/NL0)%8; - //const short lx = (tiitg/NL0)%8; - //const short ly = i%8; - - *(sa + NK*(8*sy + ly) + 8*sx + lx) = loop_k + 16*il + i < args.ne00 ? (S0) *((device T0 *) x + i) : 0; - } - } else { - S0_4x4 temp_a; - dequantize_func(x, il, temp_a); - - threadgroup_barrier(mem_flags::mem_threadgroup); - - FOR_UNROLL (short i = 0; i < 16; i++) { - const short sx = 2*il0 + i/8; - const short sy = (tiitg/NL0)/8; - - const short lx = i%8; - const short ly = (tiitg/NL0)%8; - //const short lx = (tiitg/NL0)%8; - //const short ly = i%8; - - *(sa + NK*(8*sy + ly) + 8*sx + lx) = temp_a[i/4][i%4]; - } - } - - if (FC_mul_mm_bc_inp) { - for (short i = 0; i < 8; ++i) { - const short sx = (tiitg%NL1); - const short sy = (tiitg/NL1)/8; - - const short lx = i; - const short ly = (tiitg/NL1)%8; - //const short lx = (tiitg/NL1)%8; - //const short ly = i; - - *(sb + NK*(8*sy + ly) + 8*sx + lx) = loop_k + iy + i < args.ne00 ? (S1) *((device T1 *) y + i) : 0; - } - } else { - const short sx = (tiitg%NL1); - const short sy = (tiitg/NL1)/8; - - //const short lx = i; - const short ly = (tiitg/NL1)%8; - //const short lx = (tiitg/NL1)%8; - //const short ly = i; - - *(threadgroup S1_2x4 *)(sb + NK*(8*sy + ly) + 8*sx) = (S1_2x4)(*((device T1_2x4 *) y)); - } -#endif il = (il + 2 < nl) ? il + 2 : il % 2; x = (il < 2) ? x + (2 + nl - 1)/nl : x; @@ -796,7 +589,6 @@ kernel void kernel_mul_mm_id( threadgroup_barrier(mem_flags::mem_threadgroup); -#ifndef GGML_METAL_HAS_TENSOR if (sg_active) { // load matrices from threadgroup memory and conduct outer products threadgroup const S0 * lsma = (sa + 4*64*(sgitg%2)); @@ -825,32 +617,11 @@ kernel void kernel_mul_mm_id( lsmb += 4*64; } } -#else - auto sA = tA.slice(0, 0); - auto sB0 = tB0.slice(0, 0); - - mm.run(sB0, sA, cT0); - - if (has_hi) { - auto sB1 = tB1.slice(0, 0); - - mm.run(sB1, sA, cT1); - } -#endif } // block is smaller than 64x32, we should avoid writing data outside of the matrix threadgroup_barrier(mem_flags::mem_threadgroup); -#ifdef GGML_METAL_HAS_TENSOR - auto tC0 = tensor, tensor_inline>(sc, dextents(NR0, NR1H)); - cT0.store(tC0); - - if (has_hi) { - auto tC1 = tensor, tensor_inline>(sc + NR1H*NR0, dextents(NR0, NR1H)); - cT1.store(tC1); - } -#else if (sg_active) { threadgroup float * temp_str = ((threadgroup float *) shmem) + 32*(sgitg&1) + (16*(sgitg >> 1))*NR0; @@ -858,7 +629,6 @@ kernel void kernel_mul_mm_id( simdgroup_store(mc[i], temp_str + 8*(i%4) + 8*NR0*(i/4), NR0, 0, false); } } -#endif threadgroup_barrier(mem_flags::mem_threadgroup); @@ -886,133 +656,249 @@ kernel void kernel_mul_mm_id( } } -// // matrix-matrix multiplication // -typedef decltype(kernel_mul_mm) mul_mm_t; +typedef decltype(kernel_mul_mm) mul_mm_t; + +template [[host_name("kernel_mul_mm_f32_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_f16_f32")]] kernel mul_mm_t kernel_mul_mm; +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_f32_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +#endif + +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_f16_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q1_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q2_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_1_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_1_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q8_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_mxfp4_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q2_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q3_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q6_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_xxs_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_xs_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq3_xxs_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq3_s_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_s_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq1_s_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq1_m_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq4_nl_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq4_xs_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_tq2_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +#endif +template [[host_name("kernel_mul_mm_f32_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_f16_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q1_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q2_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_1_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_1_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q8_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_mxfp4_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q2_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q3_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q6_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_xxs_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_xs_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq3_xxs_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq3_s_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_s_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq1_s_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq1_m_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq4_nl_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq4_xs_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_tq2_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_f32_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_f16_f32")]] kernel mul_mm_t kernel_mul_mm; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_mul_mm_bf16_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_bf16_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_bf16_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_bf16_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_bf16_bf16")]] kernel mul_mm_t kernel_mul_mm; #endif -template [[host_name("kernel_mul_mm_q1_0_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q2_0_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q4_0_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q4_1_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q5_0_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q5_1_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q8_0_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_mxfp4_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q2_K_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q3_K_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q4_K_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q5_K_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q6_K_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq2_xxs_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq2_xs_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq3_xxs_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq3_s_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq2_s_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq1_s_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq1_m_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq4_nl_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq4_xs_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_tq2_0_f32")]] kernel mul_mm_t kernel_mul_mm; - -template [[host_name("kernel_mul_mm_f32_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_f16_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q1_0_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q2_0_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q4_0_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q4_1_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q5_0_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q5_1_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q8_0_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_mxfp4_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q2_K_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q3_K_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q4_K_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q5_K_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q6_K_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq2_xxs_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq2_xs_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq3_xxs_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq3_s_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq2_s_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq1_s_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq1_m_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq4_nl_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq4_xs_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_tq2_0_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q1_0_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q2_0_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_0_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_1_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_0_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_1_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q8_0_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_mxfp4_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q2_K_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q3_K_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_K_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_K_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q6_K_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_xxs_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_xs_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq3_xxs_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq3_s_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_s_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq1_s_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq1_m_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq4_nl_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq4_xs_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_tq2_0_f32")]] kernel mul_mm_t kernel_mul_mm; + +template [[host_name("kernel_mul_mm_f32_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_f16_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q1_0_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q2_0_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_0_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_1_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_0_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_1_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q8_0_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_mxfp4_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q2_K_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q3_K_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_K_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_K_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q6_K_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_xxs_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_xs_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq3_xxs_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq3_s_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_s_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq1_s_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq1_m_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq4_nl_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq4_xs_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_tq2_0_f16")]] kernel mul_mm_t kernel_mul_mm; // // indirect matrix-matrix multiplication // -typedef decltype(kernel_mul_mm_id) mul_mm_id; +typedef decltype(kernel_mul_mm_id) mul_mm_id; -template [[host_name("kernel_mul_mm_id_f32_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_f16_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_f32_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_f16_f32")]] kernel mul_mm_id kernel_mul_mm_id; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_mul_mm_id_bf16_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_bf16_f32")]] kernel mul_mm_id kernel_mul_mm_id; #endif -template [[host_name("kernel_mul_mm_id_q1_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q2_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q4_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q4_1_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q5_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q5_1_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q8_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q1_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q2_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_1_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_1_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q8_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_mul_mm_id_mxfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_mxfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id; #else -template [[host_name("kernel_mul_mm_id_mxfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_mxfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id; #endif -template [[host_name("kernel_mul_mm_id_q2_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q3_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q4_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q5_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q6_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq2_xxs_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq2_xs_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq3_xxs_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq3_s_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq2_s_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq1_s_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq1_m_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq4_nl_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq4_xs_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_tq2_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; - -template [[host_name("kernel_mul_mm_id_f32_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_f16_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q1_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q2_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q4_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q4_1_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q5_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q5_1_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q8_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q2_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q3_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q6_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_xxs_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_xs_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq3_xxs_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq3_s_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_s_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq1_s_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq1_m_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq4_nl_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq4_xs_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_tq2_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; + +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_id_f32_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +#endif + +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_id_f16_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q1_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q2_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_1_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_1_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q8_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q2_K_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q3_K_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_K_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_K_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q6_K_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_xxs_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_xs_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq3_xxs_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq3_s_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_s_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq1_s_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq1_m_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq4_nl_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq4_xs_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_tq2_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +#endif + +template [[host_name("kernel_mul_mm_id_f32_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_f16_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q1_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q2_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_1_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_1_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q8_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_mxfp4_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q2_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q3_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q6_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_xxs_f32_prec_f32")]]kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_xs_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq3_xxs_f32_prec_f32")]]kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq3_s_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_s_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq1_s_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq1_m_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq4_nl_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq4_xs_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_tq2_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; + +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_id_bf16_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +#endif + +template [[host_name("kernel_mul_mm_id_f32_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_f16_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q1_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q2_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_1_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_1_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q8_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_mul_mm_id_mxfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_mxfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id; #else -template [[host_name("kernel_mul_mm_id_mxfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_mxfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id; #endif -template [[host_name("kernel_mul_mm_id_q2_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q3_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q4_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q5_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q6_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq2_xxs_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq2_xs_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq3_xxs_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq3_s_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq2_s_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq1_s_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq1_m_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq4_nl_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq4_xs_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_tq2_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q2_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q3_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q6_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_xxs_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_xs_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq3_xxs_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq3_s_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_s_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq1_s_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq1_m_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq4_nl_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq4_xs_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_tq2_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; diff --git a/ggml/src/ggml-metal/kernels/mul_mm_tensor.metal b/ggml/src/ggml-metal/kernels/mul_mm_tensor.metal new file mode 100644 index 000000000000..9c1aee0c5690 --- /dev/null +++ b/ggml/src/ggml-metal/kernels/mul_mm_tensor.metal @@ -0,0 +1,537 @@ +#include "common.h" +#include "dequantize.h" + +#ifdef GGML_METAL_HAS_TENSOR + +constant bool FC_mul_mm_bc_inp [[function_constant(FC_MUL_MM + 0)]]; +constant bool FC_mul_mm_bc_out [[function_constant(FC_MUL_MM + 1)]]; +constant short FC_mul_mm_ne12 [[function_constant(FC_MUL_MM + 2)]]; +constant short FC_mul_mm_ne13 [[function_constant(FC_MUL_MM + 3)]]; +constant short FC_mul_mm_r2 [[function_constant(FC_MUL_MM + 4)]]; +constant short FC_mul_mm_r3 [[function_constant(FC_MUL_MM + 5)]]; +constant int32_t FC_mul_mm_id_map0_ne02 [[function_constant(FC_MUL_MM + 7)]]; + +// each block_q contains 16*nl weights +template< + typename SA, typename SB, + typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread typename value_type_4x4::type &), + typename T0, typename T1> +kernel void kernel_mul_mm_tensor( + constant ggml_metal_kargs_mul_mm & args, + device const char * srcA, + device const char * srcB, + device char * dst, + threadgroup char * shmem [[threadgroup(0)]], + uint3 tgpig [[threadgroup_position_in_grid]], + ushort tiitg [[thread_index_in_threadgroup]], + ushort sgitg [[simdgroup_index_in_threadgroup]]) { + using SA_4x4 = typename value_type_4x4::type; + using SA_8x8 = typename value_type_8x8::type; + using SB_2x4 = typename value_type_2x4::type; + using SB_8x8 = typename value_type_8x8::type; + using T0_4x4 = typename value_type_4x4::type; + using T1_2x4 = typename value_type_2x4::type; + + (void) sgitg; + + // Matrix dimensions: A(M,K) x B(K,N) -> C(M,N) + const int K = args.ne00; + const int M = args.ne0; + const int N = args.ne1; + + // Batch dimension handling + const int im = tgpig.z; + const int i12 = im % FC_mul_mm_ne12; + const int i13 = im / FC_mul_mm_ne12; + + // Batch offsets for srcA and srcB + const uint64_t offset0 = (i12/FC_mul_mm_r2)*args.nb02 + (i13/FC_mul_mm_r3)*args.nb03; + + // Tile dimensions + constexpr int NRB = SZ_SIMDGROUP * N_MM_BLOCK_X * N_MM_SIMD_GROUP_X; + constexpr int NRA = SZ_SIMDGROUP * N_MM_BLOCK_Y * N_MM_SIMD_GROUP_Y; + + // Tile offsets in output matrix + const int ra = tgpig.y * NRA; + const int rb = tgpig.x * NRB; + + // Threadgroup memory for dequantized A tile only + threadgroup SA * sa = (threadgroup SA *)(shmem); + + // Work-item count for A loading + constexpr int A_WORK_ITEMS = NRA * N_MM_NK; + constexpr int NUM_THREADS = N_SIMDWIDTH * N_MM_SIMD_GROUP_X * N_MM_SIMD_GROUP_Y; + + // tA wraps threadgroup memory + auto tA = tensor(sa, dextents(N_MM_NK_TOTAL, NRA)); + + // tB wraps device memory directly + device T1 * ptrB = (device T1 *)(srcB + args.nb12*i12 + args.nb13*i13); + const int strideB = args.nb11 / sizeof(T1); + auto tB = tensor(ptrB, dextents(K, N), array({1, strideB})); + + // Configure matmul operation + // note: K is dynamic_extent (clamped to the valid range in PHASE 2), since a static + // N_MM_NK_TOTAL K tile would read src1 out of bounds when K % N_MM_NK_TOTAL != 0 + // ref: https://github.com/ggml-org/llama.cpp/pull/27064 + mpp::tensor_ops::matmul2d< + mpp::tensor_ops::matmul2d_descriptor( + NRB, NRA, static_cast(dynamic_extent), false, true, true, + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate), + execution_simdgroups> mm; + + auto cT = mm.get_destination_cooperative_tensor(); + + // Accumulate partial results over K dimension + for (int loop_k = 0; loop_k < K; loop_k += N_MM_NK_TOTAL) { + // === PHASE 1: Dequantization of A into threadgroup memory === + for (int work = tiitg; work < A_WORK_ITEMS; work += NUM_THREADS) { + const int row = work / N_MM_NK; + const int k_chunk = work % N_MM_NK; + const int k_pos = loop_k + k_chunk * 16; + const short k_base = k_chunk * 16; + + // Bounds check: skip device read if row is out of matrix bounds + if (ra + row < M) { + if (is_same::value && FC_mul_mm_bc_inp) { + // Element-wise reads when K is not aligned (nb01 not aligned for half4x4/float4x4). + // MSL spec Table 2.5: half4x4 requires 8-byte alignment. When K is odd, + // nb01 = K*2 is not 8-byte aligned, so odd-row pointers are misaligned. + // Mirrors the legacy kernel's existing guard. + device const T0 * row_ptr = (device const T0 *)(srcA + args.nb01 * (ra + row) + offset0); + + FOR_UNROLL (short i = 0; i < 16; i++) { + sa[row * N_MM_NK_TOTAL + (k_base + i)] = (k_pos + i < K) ? (SA) row_ptr[k_pos + i] : (SA)0; + } + } else { + const int block_idx = k_pos / (16 * nl); + const short il = (k_pos / 16) % nl; + + device const block_q * row_ptr = (device const block_q *)(srcA + args.nb01 * (ra + row) + offset0); + + SA_4x4 temp_a; + dequantize_func(row_ptr + block_idx, il, temp_a); + + FOR_UNROLL (short i = 0; i < 16; i++) { + // Zero-pad A for K positions beyond valid range (handles partial K iterations) + sa[row * N_MM_NK_TOTAL + (k_base + i)] = (k_pos + i < K) ? temp_a[i/4][i%4] : (SA)0; + } + } + } else { + // Zero-pad rows beyond matrix bounds + FOR_UNROLL (short i = 0; i < 16; i++) { + sa[row * N_MM_NK_TOTAL + (k_base + i)] = (SA)0; + } + } + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + // === PHASE 2: Tensor matmul === + // Clamp the K extent of both operand tensors to the remaining valid K range so + // the dynamic-K op never reads past the K extent of src1 (or the staged A tile). + const int kExt = min(N_MM_NK_TOTAL, K - loop_k); + + auto tAv = tensor(sa, dextents(kExt, NRA), array({1, N_MM_NK_TOTAL})); + auto tBv = tensor(ptrB + loop_k + rb * strideB, dextents(kExt, N - rb), array({1, strideB})); + + mm.run(tBv, tAv, cT); + + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + // Store result tile to output matrix (with batch offset) + // a slice is not used because its byte offset is int32 and wraps at 2 GiB + // ref: https://github.com/ggml-org/llama.cpp/pull/28748 + const int tileM = min(NRA, M - ra); + const int tileN = min(NRB, N - rb); + + device float * dstTile = (device float *)dst + (uint64_t) im * N * M + (uint64_t) rb * M + ra; + + auto tD = tensor(dstTile, dextents(tileM, tileN), array({1, M})); + cT.store(tD); +} + +template::type &), typename T0, typename T1> +kernel void kernel_mul_mm_id_tensor( + constant ggml_metal_kargs_mul_mm_id & args, + device const char * src0, + device const char * src1, + device const char * htpe, + device const char * hids, + device char * dst, + threadgroup char * shmem [[threadgroup(0)]], + uint3 tgpig[[threadgroup_position_in_grid]], + ushort tiitg[[thread_index_in_threadgroup]], + ushort tiisg[[thread_index_in_simdgroup]], + ushort sgitg[[simdgroup_index_in_threadgroup]]) { + using S0_4x4 = typename value_type_4x4::type; + using S0_8x8 = typename value_type_8x8::type; + using S1_2x4 = typename value_type_2x4::type; + using S1_8x8 = typename value_type_8x8::type; + using T0_4x4 = typename value_type_4x4::type; + using T1_2x4 = typename value_type_2x4::type; + + constexpr int NR0 = 64; + constexpr int NR1 = 32; + + constexpr int NK = 32; + constexpr int NL0 = NK/16; + constexpr int NL1 = NK/8; + + threadgroup S0 * sa = (threadgroup S0 *)(shmem); + threadgroup S1 * sb = (threadgroup S1 *)(shmem + NR0*NK*sizeof(S0)); + + threadgroup float * sc = (threadgroup float *)(shmem); + + const int tile = tgpig.x; // entry tile, described by the prepass + const int r0 = tgpig.y*NR0; + + device const uint32_t * tpe_u32 = (device const uint32_t *) (htpe); + device const int32_t * ids_i32 = (device const int32_t *) (hids); + + // the prepass emits one (expert, first entry, valid rows) descriptor per tile that has + // work - the grid is sized by a static upper bound, so the tail early exits + if (tile >= (int) tpe_u32[0]) { + return; + } + + const int im = tpe_u32[1 + 3*tile]; // expert + const int idb = tpe_u32[1 + 3*tile + 1]; // first entry of this tile in hids + + // number of entries in this tile, always <= NR1 + const short nr1 = (short) ((tpe_u32[1 + 3*tile + 2] < NR1) ? tpe_u32[1 + 3*tile + 2] : NR1); + + // if this block is of 64x32 shape or smaller + const short nr0 = (args.ne0 - r0 < NR0) ? (args.ne0 - r0) : NR0; + + // a thread shouldn't load data outside of the matrix + const short lr0 = ((short)tiitg/NL0) < nr0 ? ((short)tiitg/NL0) : nr0 - 1; // 0 .. 63 + + const short il0 = (tiitg % NL0); + + const short i13 = 0; + + const uint64_t offset0 = im*args.nb02 + i13*args.nb03; + const short offset1 = il0/nl; + + const short iy = 8*(tiitg % NL1); + + // skip the upper half of the token tile when the expert did not fill it + constexpr short NR1H = NR1/2; + + auto tA = tensor, tensor_inline>(sa, dextents(NK, NR0)); + + // sb is [NR1][NK] row-major + auto tB0 = tensor, tensor_inline>(sb, dextents(NK, NR1H)); + auto tB1 = tensor, tensor_inline>(sb + NR1H*NK, dextents(NK, NR1H)); + + mpp::tensor_ops::matmul2d< + mpp::tensor_ops::matmul2d_descriptor(NR1H, NR0, NK, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate), + execution_simdgroups<4>> mm; + + + const short lr1 = ((short)tiitg/NL1) < nr1 ? ((short)tiitg/NL1) : nr1 - 1; // 0 .. 31 + + short il = il0; + + const int id = ids_i32[idb + lr1]; + + const short i11 = (id % args.ne20) % args.ne11; + const int i12 = (id / args.ne20); + + device const block_q * x = (device const block_q *)(src0 + args.nb01*(r0 + lr0) + offset0) + offset1; + + device const T1 * y = (device const T1 *)(src1 + + args.nb13*i13 + + args.nb12*i12 + + args.nb11*i11 + + args.nb10*iy); + + const bool has_hi = nr1 > NR1H; + + auto cT0 = mm.get_destination_cooperative_tensor(); + auto cT1 = mm.get_destination_cooperative_tensor(); + + for (int loop_k = 0; loop_k < args.ne00; loop_k += NK) { + // load data and store to threadgroup memory + if (is_same::value && FC_mul_mm_bc_inp) { + threadgroup_barrier(mem_flags::mem_threadgroup); + + // no need for dequantization + for (short i = 0; i < 16; i++) { + const short sx = 2*il0 + i/8; + const short sy = (tiitg/NL0)/8; + + const short lx = i%8; + const short ly = (tiitg/NL0)%8; + //const short lx = (tiitg/NL0)%8; + //const short ly = i%8; + + *(sa + NK*(8*sy + ly) + 8*sx + lx) = loop_k + 16*il + i < args.ne00 ? (S0) *((device T0 *) x + i) : 0; + } + } else { + S0_4x4 temp_a; + dequantize_func(x, il, temp_a); + + threadgroup_barrier(mem_flags::mem_threadgroup); + + FOR_UNROLL (short i = 0; i < 16; i++) { + const short sx = 2*il0 + i/8; + const short sy = (tiitg/NL0)/8; + + const short lx = i%8; + const short ly = (tiitg/NL0)%8; + //const short lx = (tiitg/NL0)%8; + //const short ly = i%8; + + *(sa + NK*(8*sy + ly) + 8*sx + lx) = temp_a[i/4][i%4]; + } + } + + if (FC_mul_mm_bc_inp) { + for (short i = 0; i < 8; ++i) { + const short sx = (tiitg%NL1); + const short sy = (tiitg/NL1)/8; + + const short lx = i; + const short ly = (tiitg/NL1)%8; + //const short lx = (tiitg/NL1)%8; + //const short ly = i; + + *(sb + NK*(8*sy + ly) + 8*sx + lx) = loop_k + iy + i < args.ne00 ? (S1) *((device T1 *) y + i) : 0; + } + } else { + const short sx = (tiitg%NL1); + const short sy = (tiitg/NL1)/8; + + //const short lx = i; + const short ly = (tiitg/NL1)%8; + //const short lx = (tiitg/NL1)%8; + //const short ly = i; + + *(threadgroup S1_2x4 *)(sb + NK*(8*sy + ly) + 8*sx) = (S1_2x4)(*((device T1_2x4 *) y)); + } + + il = (il + 2 < nl) ? il + 2 : il % 2; + x = (il < 2) ? x + (2 + nl - 1)/nl : x; + + y += NK; + + threadgroup_barrier(mem_flags::mem_threadgroup); + + auto sA = tA.slice(0, 0); + auto sB0 = tB0.slice(0, 0); + + mm.run(sB0, sA, cT0); + + if (has_hi) { + auto sB1 = tB1.slice(0, 0); + + mm.run(sB1, sA, cT1); + } + } + + // block is smaller than 64x32, we should avoid writing data outside of the matrix + threadgroup_barrier(mem_flags::mem_threadgroup); + + auto tC0 = tensor, tensor_inline>(sc, dextents(NR0, NR1H)); + cT0.store(tC0); + + if (has_hi) { + auto tC1 = tensor, tensor_inline>(sc + NR1H*NR0, dextents(NR0, NR1H)); + cT1.store(tC1); + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + for (short j = sgitg; j < nr1; j += 4) { + const int id = ids_i32[idb + j]; + + const short ide = id % args.ne20; + const int idt = id / args.ne20; + + device float * D = (device float *) dst + r0 + (uint64_t) ide*args.ne0 + (uint64_t) idt*args.ne1*args.ne0; + device float4 * D4 = (device float4 *) D; + + threadgroup float * C = (threadgroup float *) shmem + j*NR0; + threadgroup float4 * C4 = (threadgroup float4 *) C; + + int i = tiisg; + for (; i < nr0/4; i += 32) { + *(D4 + i) = *(C4 + i); + } + + i = (4*(nr0/4)) + tiisg; + for (; i < nr0; i += 32) { + *(D + i) = *(C + i); + } + } +} + +// matrix-matrix multiplication +// + +typedef decltype(kernel_mul_mm_tensor) mul_mm_tensor_t; + +template [[host_name("kernel_mul_mm_tensor_f32_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_f16_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_tensor_f32_f32_prec_bf16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +#endif + + +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_tensor_bf16_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_bf16_bf16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +#endif +template [[host_name("kernel_mul_mm_tensor_q1_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q2_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q4_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q4_1_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q5_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q5_1_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q8_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_mxfp4_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q2_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q3_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q4_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q5_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q6_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq2_xxs_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq2_xs_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq3_xxs_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq3_s_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq2_s_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq1_s_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq1_m_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq4_nl_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq4_xs_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_tq2_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; + +template [[host_name("kernel_mul_mm_tensor_f32_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_f16_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q1_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q2_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q4_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q4_1_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q5_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q5_1_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q8_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_mxfp4_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q2_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q3_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q4_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q5_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q6_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq2_xxs_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq2_xs_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq3_xxs_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq3_s_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq2_s_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq1_s_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq1_m_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq4_nl_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq4_xs_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_tq2_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; + +// +// indirect matrix-matrix multiplication +// + +typedef decltype(kernel_mul_mm_id_tensor) mul_mm_id_tensor_t; + +template [[host_name("kernel_mul_mm_id_tensor_f32_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_f16_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_id_tensor_bf16_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +#endif +template [[host_name("kernel_mul_mm_id_tensor_q1_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q2_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q4_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q4_1_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q5_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q5_1_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q8_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +#else +template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +#endif +template [[host_name("kernel_mul_mm_id_tensor_q2_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q3_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q4_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q5_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q6_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq2_xxs_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq2_xs_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq3_xxs_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq3_s_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq2_s_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq1_s_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq1_m_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq4_nl_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq4_xs_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_tq2_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; + +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_id_tensor_f32_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +#endif + +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_id_tensor_f16_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q1_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q2_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q4_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q4_1_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q5_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q5_1_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q8_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q2_K_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q3_K_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q4_K_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q5_K_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q6_K_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq2_xxs_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq2_xs_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq3_xxs_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq3_s_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq2_s_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq1_s_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq1_m_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq4_nl_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq4_xs_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_tq2_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +#endif + +template [[host_name("kernel_mul_mm_id_tensor_f32_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_f16_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q1_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q2_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q4_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q4_1_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q5_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q5_1_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q8_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +#else +template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +#endif +template [[host_name("kernel_mul_mm_id_tensor_q2_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q3_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q4_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q5_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q6_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq2_xxs_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq2_xs_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq3_xxs_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq3_s_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq2_s_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq1_s_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq1_m_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq4_nl_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq4_xs_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_tq2_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; + +#endif // GGML_METAL_HAS_TENSOR diff --git a/ggml/src/ggml-metal/kernels/mul_mv.metal b/ggml/src/ggml-metal/kernels/mul_mv.metal index de9d76ff60dd..95e9515d5a23 100644 --- a/ggml/src/ggml-metal/kernels/mul_mv.metal +++ b/ggml/src/ggml-metal/kernels/mul_mv.metal @@ -1046,7 +1046,7 @@ template [[host_name("kernel_mul_mv_bf16_bf16")]] kernel mul_mv_t_t kernel_mul_m template [[host_name("kernel_mul_mv_f32_bf16")]] kernel mul_mv_t_t kernel_mul_mv_t_t; #endif -template +template void kernel_mul_mv_t_t_4_impl( args_t args, device const char * src0, @@ -1056,6 +1056,9 @@ void kernel_mul_mv_t_t_4_impl( uint3 tgpig, ushort tiisg, ushort sgitg) { + using T04 = typename value_type_4::type; + using T14 = typename value_type_4::type; + const short NSG = FC_mul_mv_nsg; constexpr short NW = N_SIMDWIDTH; @@ -1129,7 +1132,7 @@ void kernel_mul_mv_t_t_4_impl( helper_mv_reduce_and_write(dst_f32, sumf, r0, args.ne01, tiisg, sgitg, shmem); } -template +template void kernel_mul_mv_t_t_4_disp( args_t args, device const char * src0, @@ -1140,14 +1143,14 @@ void kernel_mul_mv_t_t_4_disp( ushort tiisg, ushort sgitg) { switch (args.nr0) { - //case 1: kernel_mul_mv_t_t_4_impl(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break; - case 2: kernel_mul_mv_t_t_4_impl(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break; - //case 3: kernel_mul_mv_t_t_4_impl(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break; - //case 4: kernel_mul_mv_t_t_4_impl(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break; + //case 1: kernel_mul_mv_t_t_4_impl(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break; + case 2: kernel_mul_mv_t_t_4_impl(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break; + //case 3: kernel_mul_mv_t_t_4_impl(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break; + //case 4: kernel_mul_mv_t_t_4_impl(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break; }; } -template +template kernel void kernel_mul_mv_t_t_4( constant ggml_metal_kargs_mul_mv & args, device const char * src0, @@ -1157,18 +1160,18 @@ kernel void kernel_mul_mv_t_t_4( uint3 tgpig[[threadgroup_position_in_grid]], ushort tiisg[[thread_index_in_simdgroup]], ushort sgitg[[simdgroup_index_in_threadgroup]]) { - kernel_mul_mv_t_t_4_disp(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); + kernel_mul_mv_t_t_4_disp(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); } -typedef decltype(kernel_mul_mv_t_t_4) mul_mv_t_t_4; +typedef decltype(kernel_mul_mv_t_t_4) mul_mv_t_t_4; -template [[host_name("kernel_mul_mv_f32_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; -template [[host_name("kernel_mul_mv_f16_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; -template [[host_name("kernel_mul_mv_f16_f16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; +template [[host_name("kernel_mul_mv_f32_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; +template [[host_name("kernel_mul_mv_f16_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; +template [[host_name("kernel_mul_mv_f16_f16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_mul_mv_bf16_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; -template [[host_name("kernel_mul_mv_bf16_bf16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; -template [[host_name("kernel_mul_mv_f32_bf16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; +template [[host_name("kernel_mul_mv_bf16_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; +template [[host_name("kernel_mul_mv_bf16_bf16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; +template [[host_name("kernel_mul_mv_f32_bf16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; #endif template @@ -3389,17 +3392,17 @@ kernel void kernel_mul_mv_id( typedef decltype(kernel_mul_mv_id>>) kernel_mul_mv_id_t; -typedef decltype(kernel_mul_mv_id>>) kernel_mul_mv_id_4_t; +typedef decltype(kernel_mul_mv_id>>) kernel_mul_mv_id_4_t; template [[host_name("kernel_mul_mv_id_f32_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; template [[host_name("kernel_mul_mv_id_f16_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; #if defined(GGML_METAL_HAS_BF16) template [[host_name("kernel_mul_mv_id_bf16_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; #endif -template [[host_name("kernel_mul_mv_id_f32_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id>>; -template [[host_name("kernel_mul_mv_id_f16_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id>>; +template [[host_name("kernel_mul_mv_id_f32_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id>>; +template [[host_name("kernel_mul_mv_id_f16_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id>>; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_mul_mv_id_bf16_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id>>; +template [[host_name("kernel_mul_mv_id_bf16_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id>>; #endif template [[host_name("kernel_mul_mv_id_q8_0_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index cdb1f3794fe1..9019fb26d20e 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -1592,6 +1592,18 @@ bool llm_arch_supports_sm_tensor(const llm_arch & arch) { } } +bool llm_arch_mmid_down_bf16(const llm_arch & arch) { + switch (arch) { + case LLM_ARCH_MISTRAL4: + case LLM_ARCH_MELLUM: + case LLM_ARCH_FLINT: + case LLM_ARCH_LAGUNA: + return true; + default: + return false; + } +} + bool llama_arch_supports_save(llm_arch arch) { switch (arch) { case LLM_ARCH_SENSENOVA_U1: diff --git a/src/llama-arch.h b/src/llama-arch.h index 6517a3ea7ea9..45ef8bc093cc 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -1037,3 +1037,4 @@ bool llm_arch_is_diffusion (const llm_arch & arch); bool llm_arch_supports_sm_tensor(const llm_arch & arch); bool llm_arch_supports_rs_rollback(const llm_arch & arch); bool llm_arch_supports_mixed_batch(const llm_arch & arch); +bool llm_arch_mmid_down_bf16(const llm_arch & arch); diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 1bd3f8d0f85e..862476a5f60a 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1823,7 +1823,7 @@ ggml_tensor * llm_graph_context::build_lora_mm( } - prec_policy.apply(res); + prec_policy.apply(res, w); if (w_s) { res = ggml_mul(ctx0, res, w_s); @@ -1894,7 +1894,6 @@ ggml_tensor * llm_graph_context::build_lora_mm_id( ggml_tensor * slots, bool cached) const { ggml_tensor * w_s = model.get_w_scale(w); - // as in build_lora_mm: the folded weight reads the transformed input, the LoRA delta reads `cur` ggml_tensor * cur_mm = build_hadamard_input(w, cur); // the experts in the MoE cache are selected by their slots @@ -1907,7 +1906,7 @@ ggml_tensor * llm_graph_context::build_lora_mm_id( } // after the NVFP4 default, so that the policy can request a higher precision - prec_policy.apply(res); + prec_policy.apply(res, w); if (w_s) { const int64_t n_expert = w_s->ne[0]; @@ -2656,15 +2655,16 @@ ggml_tensor * llm_graph_context::build_moe_ffn( // ggml_prec_set_src(experts, GGML_PREC_BF16, 1); // the amax op cannot be split across devices, so these architectures are denied -sm tensor [TAG_MOE_AMAX_SCALE] // ref: https://github.com/ggml-org/llama.cpp/pull/30656#issuecomment-6269597922 + const bool use_amax = llm_arch_mmid_down_bf16(arch) && prec_policy.get_src1(down_exps) != GGML_PREC_BF16; + llm_graph_amax_src1 amax_src1 = { nullptr, nullptr }; - if (arch == LLM_ARCH_MISTRAL4 || arch == LLM_ARCH_MELLUM || arch == LLM_ARCH_FLINT || arch == LLM_ARCH_LAGUNA) { + if (use_amax) { amax_src1 = build_amax_src1_f16(cur); cur = amax_src1.res; } ggml_tensor * experts = build_lora_mm_id(down_exps, cur, ids, mm_ids, cached); // [n_embd, n_expert_used, n_tokens] - //ggml_prec_set_src(experts, GGML_PREC_BF16, 1); // (see TODO above) cb(experts, "ffn_moe_down", il); if (amax_src1.scale_s) { diff --git a/src/llama-model-saver.cpp b/src/llama-model-saver.cpp index c01d4dd51b5f..4a62064e7dc6 100644 --- a/src/llama-model-saver.cpp +++ b/src/llama-model-saver.cpp @@ -173,18 +173,6 @@ void llama_model_saver::add_kv_from_model() { // add_kv(LLM_KV_GENERAL_SAMPLING_MIROSTAT_ETA, ???); add_kv(LLM_KV_GENERAL_NAME, model->name); - if (!model->prec_policy.prec_src1.empty()) { - std::vector tensor_names; - std::vector values; - tensor_names.reserve(model->prec_policy.prec_src1.size()); - values.reserve(model->prec_policy.prec_src1.size()); - for (const auto & [w, prec] : model->prec_policy.prec_src1) { - tensor_names.push_back(ggml_get_name(w)); - values.push_back(prec == GGML_PREC_Q8 ? 0 : 1); - } - add_kv(LLM_KV_GENERAL_TENSOR_EXTRA_NAME, tensor_names); - gguf_set_arr_data(gguf_ctx, llm_kv(LLM_KV_GENERAL_TENSOR_EXTRA_PREC_A4).c_str(), GGUF_TYPE_BOOL, values.data(), values.size()); - } // add_kv(LLM_KV_GENERAL_AUTHOR, ???); // add_kv(LLM_KV_GENERAL_VERSION, ???); // add_kv(LLM_KV_GENERAL_URL, ???); diff --git a/src/llama-model.cpp b/src/llama-model.cpp index 06eb7c929281..fa20378aa6d2 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -1405,19 +1406,24 @@ struct llama_model::impl { std::vector tensor_split_owned; }; -bool llama_prec_policy::apply(ggml_tensor * res) const { - if (!res || !res->src[0]) { +bool llama_prec_policy::apply(ggml_tensor * res, const ggml_tensor * w) const { + if (!res) { + return false; + } + + const ggml_tensor * key = w ? w : res->src[0]; + if (!key) { return false; } bool applied = false; - const auto it_acc = prec_acc.find(res->src[0]); + const auto it_acc = prec_acc.find(key); if (it_acc != prec_acc.end()) { applied |= ggml_prec_set_acc(res, it_acc->second); } - const auto it_src1 = prec_src1.find(res->src[0]); + const auto it_src1 = prec_src1.find(key); if (it_src1 != prec_src1.end()) { applied |= ggml_prec_set_src(res, it_src1->second, 1); } @@ -1724,6 +1730,30 @@ void llama_model_base::load_vocab(llama_model_loader & ml) { vocab.load(ml, kv); } +void llama_model_base::load_prec_policy(llama_model_loader & ml) { + // the reference computes the router in F32: https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash/blob/60d8d70770c6776ff598c94bb586a859a38244f1/inference/model.py#L565 + if (hparams.expert_gating_func == LLAMA_EXPERT_GATING_FUNC_TYPE_SQRT_SOFTPLUS || hparams.expert_router_f32) { + for (const auto & layer : layers) { + prec_policy.set_acc(layer.ffn_gate_inp, GGML_PREC_F32); + } + } + + if (getenv("LLAMA_MOE_AMAX_SKIP") != nullptr) { + LLAMA_LOG_WARN("LLAMA_MOE_AMAX_SKIP is set - the MoE amax rescaling is disabled\n"); + + if (llm_arch_mmid_down_bf16(arch)) { + for (const auto & layer : layers) { + if (layer.ffn_down_exps) { + prec_policy.set_src1(layer.ffn_down_exps, GGML_PREC_BF16); + } + } + } + } + + // per-tensor activation precision policy + prec_policy.load(ml, *this); +} + bool llama_model_base::load_tensors(llama_model_loader & ml) { const auto & split_mode = params.split_mode; const bool use_mlock = params.load_mode == LLAMA_LOAD_MODE_MLOCK || params.load_mode == LLAMA_LOAD_MODE_MMAP_MLOCK; @@ -2080,15 +2110,7 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) { } } - // the reference computes the router in F32: https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash/blob/60d8d70770c6776ff598c94bb586a859a38244f1/inference/model.py#L565 - if (hparams.expert_gating_func == LLAMA_EXPERT_GATING_FUNC_TYPE_SQRT_SOFTPLUS || hparams.expert_router_f32) { - for (const auto & layer : layers) { - prec_policy.set_acc(layer.ffn_gate_inp, GGML_PREC_F32); - } - } - - // per-tensor activation precision policy - prec_policy.load(ml, *this); + load_prec_policy(ml); ml.init_mappings(true, use_mlock ? &pimpl->mlock_mmaps : nullptr); pimpl->mappings.reserve(ml.mappings.size()); diff --git a/src/llama-model.h b/src/llama-model.h index eae5c68486ab..d7285d226173 100644 --- a/src/llama-model.h +++ b/src/llama-model.h @@ -743,7 +743,7 @@ struct llama_prec_policy { // the key is the weight tensor `res->src[0]`, stores the recommended activation precision type std::unordered_map prec_src1; - bool apply(ggml_tensor * res) const; + bool apply(ggml_tensor * res, const ggml_tensor * w = nullptr) const; void set_acc(const ggml_tensor * w, ggml_prec prec) { if (w) { @@ -751,6 +751,17 @@ struct llama_prec_policy { } } + void set_src1(const ggml_tensor * w, ggml_prec prec) { + if (w) { + prec_src1[w] = prec; + } + } + + ggml_prec get_src1(const ggml_tensor * w) const { + const auto it = prec_src1.find(w); + return it != prec_src1.end() ? it->second : GGML_PREC_UNDEFINED; + } + void load(llama_model_loader & ml, const llama_model & model); }; @@ -1146,6 +1157,7 @@ struct llama_model_base : public llama_model { void load_hparams(llama_model_loader & ml) override; void load_vocab (llama_model_loader & ml) override; bool load_tensors(llama_model_loader & ml) override; + void load_prec_policy(llama_model_loader & ml); // model must define these void load_arch_hparams(llama_model_loader & ml) override = 0; diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 53961f776ef1..318225c8509a 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -6161,6 +6161,79 @@ struct test_mul_mat_id_w4a8 : public test_mul_mat_id { } }; +// src1 GGML_PREC_BF16: the implementation may keep src1 in F32 or BF16, but must not convert it down to F16 +struct test_mul_mat_id_prec_src1_bf16 : public test_mul_mat_id { + test_mul_mat_id_prec_src1_bf16(ggml_type type_a = GGML_TYPE_F32, + int n_mats = 8, int n_used = 2, bool b = false, + int64_t m = 32, int64_t n = 32, int64_t k = 256) + : test_mul_mat_id(type_a, GGML_TYPE_F32, n_mats, n_used, b, m, n, k) {} + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * out = test_mul_mat_id::build_graph(ctx); + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + if (t->op == GGML_OP_MUL_MAT_ID) { + ggml_prec_set_src(t, GGML_PREC_BF16, 1); + } + } + return out; + } + void initialize_tensors(ggml_context * ctx) override { + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + if (t->type == GGML_TYPE_I32) { + continue; + } + if (strcmp(t->name, "b") == 0) { + init_tensor_uniform(t, -1e6f, 1e6f); + } else { + init_tensor_uniform(t); + } + } + init_mul_mat_id_ids(ctx, n_mats, skip); + } + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "MUL_MAT_ID_PREC_SRC1_BF16"; + } +}; + +struct test_mul_mat_id_prec_src1_f32 : public test_mul_mat_id { + test_mul_mat_id_prec_src1_f32(ggml_type type_a = GGML_TYPE_F32, + int n_mats = 8, int n_used = 2, bool b = false, + int64_t m = 32, int64_t n = 32, int64_t k = 256) + : test_mul_mat_id(type_a, GGML_TYPE_F32, n_mats, n_used, b, m, n, k) {} + double max_nmse_err() override { + if (type_a == GGML_TYPE_F32 || type_a == GGML_TYPE_F16) { + return 1e-10; + } + return test_mul_mat_id::max_nmse_err(); + } + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * out = test_mul_mat_id::build_graph(ctx); + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + if (t->op == GGML_OP_MUL_MAT_ID) { + ggml_prec_set_src(t, GGML_PREC_F32, 1); + } + } + return out; + } + void initialize_tensors(ggml_context * ctx) override { + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + if (t->type == GGML_TYPE_I32) { + continue; + } + if (strcmp(t->name, "b") == 0) { + init_tensor_uniform(t, -1e6f, 1e6f); + } else { + init_tensor_uniform(t); + } + } + init_mul_mat_id_ids(ctx, n_mats, skip); + } + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "MUL_MAT_ID_PREC_SRC1_F32"; + } +}; + // FP4 native W4A4 path on the MoE path (default precision) struct test_mul_mat_id_w4a4 : public test_mul_mat_id { test_mul_mat_id_w4a4(ggml_type type_a = GGML_TYPE_NVFP4, ggml_type type_b = GGML_TYPE_F32, @@ -12125,6 +12198,23 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_mul_mat_prec_src1_bf16_src0(GGML_TYPE_F32, 67, 33, 100)); test_cases.emplace_back(new test_mul_mat_prec_src1_bf16_src0(GGML_TYPE_F32, 64, 32, 256, {2, 3}, {2, 1})); + // src1 precision on the MoE path: mm_id (n >= 32) and mv_id (n < 32), broadcast and partial K + for (ggml_type type_a : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_K, GGML_TYPE_MXFP4}) { + test_cases.emplace_back(new test_mul_mat_id_prec_src1_bf16(type_a, 8, 2, false, 64, 1, 256)); + test_cases.emplace_back(new test_mul_mat_id_prec_src1_bf16(type_a, 8, 2, false, 64, 32, 256)); + test_cases.emplace_back(new test_mul_mat_id_prec_src1_bf16(type_a, 8, 2, false, 64, 512, 256)); + test_cases.emplace_back(new test_mul_mat_id_prec_src1_bf16(type_a, 16, 4, true, 72, 33, 256)); + test_cases.emplace_back(new test_mul_mat_id_prec_src1_bf16(type_a, 4, 2, false, 67, 100, 256)); + } + + for (ggml_type type_a : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_K, GGML_TYPE_MXFP4}) { + test_cases.emplace_back(new test_mul_mat_id_prec_src1_f32(type_a, 8, 2, false, 64, 1, 256)); + test_cases.emplace_back(new test_mul_mat_id_prec_src1_f32(type_a, 8, 2, false, 64, 32, 256)); + test_cases.emplace_back(new test_mul_mat_id_prec_src1_f32(type_a, 8, 2, false, 64, 512, 256)); + test_cases.emplace_back(new test_mul_mat_id_prec_src1_f32(type_a, 16, 4, true, 72, 33, 256)); + test_cases.emplace_back(new test_mul_mat_id_prec_src1_f32(type_a, 4, 2, false, 67, 100, 256)); + } + // FP4 activation precision (default = native W4A4, src1 GGML_PREC_Q8 = W4A8) test_cases.emplace_back(new test_mul_mat_w4a8(GGML_TYPE_NVFP4, GGML_TYPE_F32, 32, 1, 256)); test_cases.emplace_back(new test_mul_mat_w4a8(GGML_TYPE_NVFP4, GGML_TYPE_F32, 32, 32, 256)); From 30ec35ae2e27f1eca486af02b9d3d53fa7a26950 Mon Sep 17 00:00:00 2001 From: Ed Addario <29247825+EAddario@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:06:26 +0000 Subject: [PATCH 027/275] quantize: add option to automatically choose optimal quant types to reach a file/bpw target size at lowest error (#15550) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Refactor pareto optimise and convexify * Refactor lagrange_penalty() * Refactor quantisation checks into its own function * Exit loop if no better solution found * Replace slope with cross product * Adjust for small vector size * Simplify candidates sorting * Add comments to explain magic numbers * Increase scale multiplier * Move is_iq() into a lambda and remove unused variables * Combine quant types * Reduce bpw range * Refactor outlier trimming * Tighten worker allocator * Check for direction reversal * Simplify dequantisation * Calculate bpw over all tensors * Compute rows based on tensor shape and slice count * Prioritise important tensors * Select quantization type if target_bpw is set unless user specifies type and threads * Relax lambda clamping * Add signal handler * Add save_bpw_state() * Add load_bpw_state() * Add delete_bpw_state() * Persist progress * Uninstall signal handler and cleanup * Fix trimming logic * Generate model ID hash * Remove bias mode computation * Remove --no-bias option * Automatically determine if bias error is significant * Reduce compute time by parallelising tensor processing - courtesy of https://github.com/ddh0 * Add quant types * Add --keep-bpw-state option * Refactor signal handlers * Update quant types * Minor refactoring * Add tensor type and depth heuristics * Add option to override bpw state file name * Minor refactoring * Finetune heuristics * Update usage * Fix lambda capture * Update epsilon specifier * Finetune heuristics * Simplify tensor selection * Read statistics from imatrix * Add Euclidean-Cosine score to identify important tensors * Improved is_important() logic * Fix lambda capture bug in Windows and initialise candidate_types struct * Remove processing statistics_data * Add --disable-tensor-importance option * Use more descriptive option naming * Relax target bpw range * Increase importance boost for final pass * Add B/F16 to get_ftype() * Process bpw targets up to B/F16 * Improve state checkpoint filename * Add code comments * Update usage() * Update README.md * Change checkpoint file magic * Prepare for future optimization algorithms * Add parse_target_size() * Add --target-size option * Implement target_size logic * Update usage() * Refactor parameter names * Refactor option names * Update parameter names * Improve file handling * Remove file deletion * Refactor variable names * Update usage() * Add use_wce option * Read statistics_data from imatrix * Add experimental entropy-modulated weighted cosine error (WCE) * Performance optimisations (AI assisted) * Memory optimisations (AI assisted) * Update output log * Fix state file name generation and simplify_pareto() lambda capture * Change tensor importance score logic * Refactor is_quantizable() * Improve WCE to be magnitude-aware * Expected Output Error MSE * Fix scale factor overwrite bug * Test removing unused headers * Remove wce flag * Angle-aware/Magnitude-aware (MSE/WCE) hybrid error estimation * Revert to weighted cosine error estimation * Enhanced scaling factor * Use centered‑normalized importance scaling factor (CNIF) * Remove redundant logs * Improve state file handling * Update usage instructions * Update ftype parsing logic * Flag experimental features subject to future removal * Fix --target-size description * Fix "casts away qualifiers" compiler warning * Exclude user defined tensors (--tensor-type) from the Lagrangian optimization (courtesy of https://github.com/AesSedai) * TurboQuant bias factor for inner-product sensitive tensors * TurboQuant outlier mitigation * Refactor TurboQuant improvements * Fix remap tensor bug * Remove --importance-pct option * Refactor llama_model_quantize_params to expose a pure C interface * Consolidate load/save process and remove --save-state flag * Minor log output changes * Use the tensor statistics' schema * Add quant types * Release finished tensors mmap allocation * Reuse sample buffers * Fix C2327 error when target compilation is a MS platform * Minor refactoring and AI assisted optimizations * Add uv.lock * Minor refactoring and AI assisted optimizations * Add Halko, Martinsson & Tropp randomized SVD condition number estimator * Add kappa squashing functio * Remove unnecessary includes * Add required include * Update python dependencies * Fine-tune kappa mapping parameters * Fine-tune CNIF beta parameters * Fix fallback counter error * Move to libllama and unmap weights offloaded to backend * Remove unmap weights offloaded to backend * Add winsorization * Add adaptive tensor boosting * Minor cosmetic changes * Refactor processing of unused kv tensors * Minor cosmetic change * Implement --max-buffer-size in target_bpw_type() * Fix 32-block fallback case * tensor_type_override_for() DRY refactoring * Fix typo and remove unused option * Fix #28491 linking bug when compiling with BUILD_SHARED_LIBS=OFF * Remove GGML_USE_METAL conditional macro and let the optimizer decide\ * Add --target-exclude * Remove and ignore uv.lock * Fix pinned tensors safety limits calculation * Fix truncation error * Add downwards greedy upgrade * Add target bpw/size tests * Guard imatrix schema * Update --target-bpw/size descriptions and README.md * Harden state checkpoint's file operations * Link model and imatrix to state checkpoint * Enforce and consume stats schema data * Add stats schema tests * Refactor signal handlers out of lib and harden the logic * Improve handling of pinned tensors * Add tests * Add include to keep ubuntu-webgpu happy * Moving new API entries to prevent brittle downstream apps failing * Fix miscellaneous issues --- common/imatrix-loader.cpp | 27 + common/imatrix-loader.h | 2 + include/llama.h | 9 + src/llama-ext.h | 2 +- src/llama-quant.cpp | 3516 ++++++++++++++++++++++++++------ tests/CMakeLists.txt | 1 + tests/test-quantize-target.cpp | 938 +++++++++ tools/quantize/README.md | 107 +- tools/quantize/quantize.cpp | 477 ++++- 9 files changed, 4307 insertions(+), 772 deletions(-) create mode 100644 tests/test-quantize-target.cpp diff --git a/common/imatrix-loader.cpp b/common/imatrix-loader.cpp index ec057cac2d40..ece91ff0951f 100644 --- a/common/imatrix-loader.cpp +++ b/common/imatrix-loader.cpp @@ -117,14 +117,32 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) { imatrix.chunk_size = chunk_size_key != -1 ? gguf_get_val_u32(ctx_gguf, chunk_size_key) : 0; imatrix.n_layer_nextn = nextn_key != -1 ? gguf_get_val_u32(ctx_gguf, nextn_key) : 0; + const int64_t schema_idx = gguf_find_key(ctx_gguf, LLM_KV_IMATRIX_STATS_SCHEMA); + if (schema_idx != -1 && gguf_get_kv_type(ctx_gguf, schema_idx) == GGUF_TYPE_ARRAY && + gguf_get_arr_type(ctx_gguf, schema_idx) == GGUF_TYPE_STRING) { + const int64_t n_schema = gguf_get_arr_n(ctx_gguf, schema_idx); + imatrix.stats_schema.resize(n_schema); + for (int64_t i = 0; i < n_schema; ++i) { imatrix.stats_schema[i] = gguf_get_arr_str(ctx_gguf, schema_idx, i); } + } else { + if (schema_idx != -1) { + LOG_WRN("%s: %s in %s is not an array of strings, using the default order\n", __func__, LLM_KV_IMATRIX_STATS_SCHEMA, fname.c_str()); + } + + imatrix.stats_schema = { + "sum_sq", "mean", "elements", "std_deviation", "skewness", "kurtosis", "gain", "h_norm", "l2_dist", "cossim", "pearson", "covariance", + }; + } + const std::string in_sum_suffix{ ".in_sum" }; const std::string in_sum2_suffix{ ".in_sum2" }; const std::string counts_suffix{ ".counts" }; + const std::string stats_suffix{ ".stats" }; struct sum_tensors { struct ggml_tensor * in_sum = nullptr; struct ggml_tensor * in_sum2 = nullptr; struct ggml_tensor * counts = nullptr; + struct ggml_tensor * stats = nullptr; }; std::map sums_counts_for; @@ -138,6 +156,8 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) { sums_counts_for[std::move(name)].in_sum2 = cur; } else if (string_remove_suffix(name, counts_suffix)) { sums_counts_for[std::move(name)].counts = cur; + } else if (string_remove_suffix(name, stats_suffix)) { + sums_counts_for[std::move(name)].stats = cur; } } @@ -146,6 +166,7 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) { const struct ggml_tensor * in_sum = sc.second.in_sum; const struct ggml_tensor * in_sum2 = sc.second.in_sum2; const struct ggml_tensor * counts = sc.second.counts; + const struct ggml_tensor * stats = sc.second.stats; if (!in_sum2 || !counts || (in_sum != nullptr && ggml_nelements(in_sum) != ggml_nelements(in_sum2))) { LOG_ERR("%s: mismatched sums and counts for %s\n", __func__, name.c_str()); @@ -182,6 +203,12 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) { e.activations[j] = ((const float *) in_sum->data)[j]; } } + + if (stats && stats->type == GGML_TYPE_F32) { + const int64_t n_stats = ggml_nelements(stats); + e.stats.resize(n_stats); + for (int64_t j = 0; j < n_stats; ++j) { e.stats[j] = ((const float *) stats->data)[j]; } + } } gguf_free(ctx_gguf); diff --git a/common/imatrix-loader.h b/common/imatrix-loader.h index d4616bf304af..1b6d8c4c0436 100644 --- a/common/imatrix-loader.h +++ b/common/imatrix-loader.h @@ -15,11 +15,13 @@ struct common_imatrix_entry { std::vector sums; std::vector activations; std::vector counts; + std::vector stats; }; struct common_imatrix { std::map entries; std::vector datasets; + std::vector stats_schema; int32_t chunk_count = 0; int32_t chunk_size = 0; int32_t n_layer_nextn = 0; diff --git a/include/llama.h b/include/llama.h index 7122143e5c61..9cc17a82b529 100644 --- a/include/llama.h +++ b/include/llama.h @@ -466,6 +466,15 @@ extern "C" { const struct llama_model_tensor_override * tt_overrides; // pointer to tensor overrides const int32_t * prune_layers; // pointer to layer indices to prune size_t max_buf_size; // max bytes of tensor rows kept in memory at once, 0 = default (8 GiB) + const struct llama_model_imatrix_data * activations; // pointer to activations data + const struct llama_model_imatrix_data * statistics; // pointer to statistics data + const char * const * stats_schema; // pointer to statistics schema names + float target_bpw; // target bits per weight (bpw) + int64_t target_size; // target file size in bytes + const char * state_file; // pointer to bpw state file + const enum ggml_type * target_exclude; // pointer to excluded GGML_TYPEs + ggml_abort_callback abort_callback; // callback to abort quantization + void * abort_callback_data; // pointer to user data for abort_callback } llama_model_quantize_params; typedef struct llama_logit_bias { diff --git a/src/llama-ext.h b/src/llama-ext.h index b8b7fba0bf77..a77b2f40948a 100644 --- a/src/llama-ext.h +++ b/src/llama-ext.h @@ -51,7 +51,7 @@ LLAMA_API quantize_state_impl * llama_quant_init( const llama_model * model, const llama_model_quantize_params * params); -LLAMA_API void llama_quant_free(quantize_state_impl * qs); +LLAMA_API void llama_quant_free(const quantize_state_impl * qs); // Descriptor for constructing a mock model for quantization testing. struct llama_quant_model_desc { diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp index 0515756dcee9..c66f060f621e 100644 --- a/src/llama-quant.cpp +++ b/src/llama-quant.cpp @@ -2,58 +2,63 @@ #include "llama-model.h" #include "llama-model-loader.h" #include "llama-ext.h" -#include "llama.h" +#include "llama-quant.h" #include -#include -#include +#include +#include +#include #include +#include +#include +#include #include #include +#include +#include +#include +#include #include #include #include +#include // result of parsing --tensor-type option // (changes to this struct must be reflected in tools/quantize/quantize.cpp) struct tensor_type_option { std::string name; - ggml_type type = GGML_TYPE_COUNT; + ggml_type type = GGML_TYPE_COUNT; }; // tensor categorization - used to avoid repeated string matching in quantization logic. // this is different from LLM_TN - we want broad categories, not specific tensor names per arch. -enum class tensor_category { - TOKEN_EMBD, - ATTENTION_Q, - ATTENTION_V, - ATTENTION_K, - ATTENTION_QKV, - ATTENTION_KV_B, - ATTENTION_OUTPUT, - ATTENTION_GATE, - FFN_UP, - FFN_GATE, - FFN_DOWN, - FFN_LATENT, - OUTPUT, - OTHER +enum tensor_category { + TENSOR_CATEGORY_TOKEN_EMBD, + TENSOR_CATEGORY_ATTENTION_Q, + TENSOR_CATEGORY_ATTENTION_V, + TENSOR_CATEGORY_ATTENTION_K, + TENSOR_CATEGORY_ATTENTION_QKV, + TENSOR_CATEGORY_ATTENTION_KV_B, + TENSOR_CATEGORY_ATTENTION_OUTPUT, + TENSOR_CATEGORY_ATTENTION_GATE, + TENSOR_CATEGORY_FFN_UP, + TENSOR_CATEGORY_FFN_GATE, + TENSOR_CATEGORY_FFN_DOWN, + TENSOR_CATEGORY_FFN_LATENT, + TENSOR_CATEGORY_OUTPUT, + TENSOR_CATEGORY_OTHER }; // max amount of tensor data kept in memory while quantizing a single tensor static const size_t LLAMA_QUANT_MAX_BUF_SIZE = 8ull*1024*1024*1024; -static void zeros(std::ofstream & file, size_t n) { - char zero = 0; - for (size_t i = 0; i < n; ++i) { - file.write(&zero, 1); - } +static void zeros(std::ofstream & file, const size_t n) { + constexpr char zero = 0; + for (size_t i = 0; i < n; ++i) { file.write(& zero, 1); } } static std::string remap_layer(const std::string & orig_name, const std::vector & prune, std::map & mapped, int & next_id) { - if (prune.empty()) { - return orig_name; - } + if (prune.empty()) { return orig_name; } static const std::regex pattern(R"(blk\.(\d+)\.)"); if (std::smatch match; std::regex_search(orig_name, match, pattern)) { @@ -79,9 +84,7 @@ static std::string remap_layer(const std::string & orig_name, const std::vector< } static std::string remap_imatrix(const std::string & orig_name, const std::map & mapped) { - if (mapped.empty()) { - return orig_name; - } + if (mapped.empty()) { return orig_name; } static const std::regex pattern(R"(blk\.(\d+)\.)"); if (std::smatch match; std::regex_search(orig_name, match, pattern)) { @@ -89,20 +92,16 @@ static std::string remap_imatrix(const std::string & orig_name, const std::map= n_unused_from; } + + return false; +} + +// tensor categorization for quantization +static tensor_category tensor_get_category(const std::string & tensor_name) { + if (tensor_name_match_output_weight(tensor_name.c_str())) { return TENSOR_CATEGORY_OUTPUT; } + if (tensor_name_match_token_embd(tensor_name.c_str())) { return TENSOR_CATEGORY_TOKEN_EMBD; } // attn_qkv_gate is [attn_qkv | attn_gate] in one weight, the qkv rows decide its type - if (tensor_name.find("attn_qkv.weight") != std::string::npos || tensor_name.find("attn_qkv_gate.weight") != std::string::npos) { - return tensor_category::ATTENTION_QKV; - } - if (tensor_name.find("attn_kv_b.weight") != std::string::npos) { - return tensor_category::ATTENTION_KV_B; - } - if (tensor_name.find("attn_v.weight") != std::string::npos) { - return tensor_category::ATTENTION_V; - } - if (tensor_name.find("attn_k.weight") != std::string::npos) { - return tensor_category::ATTENTION_K; - } - if (tensor_name.find("attn_q.weight") != std::string::npos) { - return tensor_category::ATTENTION_Q; - } - if (tensor_name.find("attn_output.weight") != std::string::npos) { - return tensor_category::ATTENTION_OUTPUT; - } - if (tensor_name.find("ffn_up") != std::string::npos) { - return tensor_category::FFN_UP; - } - if (tensor_name.find("ffn_gate") != std::string::npos) { - return tensor_category::FFN_GATE; - } - if (tensor_name.find("ffn_latent") != std::string::npos) { - return tensor_category::FFN_LATENT; - } - if (tensor_name.find("attn_gate.weight") != std::string::npos) { - return tensor_category::ATTENTION_GATE; - } - if (tensor_name.find("ffn_down") != std::string::npos) { - return tensor_category::FFN_DOWN; - } - return tensor_category::OTHER; + if (tensor_name.find("attn_qkv.weight") != std::string::npos || tensor_name.find("attn_qkv_gate.weight") != std::string::npos) { return TENSOR_CATEGORY_ATTENTION_QKV; } + if (tensor_name.find("attn_kv_b.weight") != std::string::npos) { return TENSOR_CATEGORY_ATTENTION_KV_B; } + if (tensor_name.find("attn_v.weight") != std::string::npos) { return TENSOR_CATEGORY_ATTENTION_V; } + if (tensor_name.find("attn_k.weight") != std::string::npos) { return TENSOR_CATEGORY_ATTENTION_K; } + if (tensor_name.find("attn_q.weight") != std::string::npos) { return TENSOR_CATEGORY_ATTENTION_Q; } + if (tensor_name.find("attn_output.weight") != std::string::npos) { return TENSOR_CATEGORY_ATTENTION_OUTPUT; } + if (tensor_name.find("ffn_up") != std::string::npos) { return TENSOR_CATEGORY_FFN_UP; } + if (tensor_name.find("ffn_gate") != std::string::npos) { return TENSOR_CATEGORY_FFN_GATE; } + if (tensor_name.find("ffn_latent") != std::string::npos) { return TENSOR_CATEGORY_FFN_LATENT; } + if (tensor_name.find("attn_gate.weight") != std::string::npos) { return TENSOR_CATEGORY_ATTENTION_GATE; } + if (tensor_name.find("ffn_down") != std::string::npos) { return TENSOR_CATEGORY_FFN_DOWN; } + + return TENSOR_CATEGORY_OTHER; } // check if tensor is a MoE expert tensor (used by GGML_OP_MUL_MAT_ID) @@ -169,16 +150,11 @@ static bool tensor_is_expert(const std::string & tensor_name) { } // check if category is for attention-v-like tensors (more sensitive to quantization) -static bool category_is_attn_v(tensor_category cat) { - return cat == tensor_category::ATTENTION_V || - cat == tensor_category::ATTENTION_QKV || - cat == tensor_category::ATTENTION_KV_B; +static bool category_is_attn_v(const tensor_category cat) { + return cat == TENSOR_CATEGORY_ATTENTION_V || cat == TENSOR_CATEGORY_ATTENTION_QKV || cat == TENSOR_CATEGORY_ATTENTION_KV_B; } -// // quantization state -// - struct quantize_state_impl { const llama_model & model; const llama_model_quantize_params * params; @@ -191,29 +167,55 @@ struct quantize_state_impl { int i_ffn_down = 0; int i_ffn_gate = 0; int i_ffn_up = 0; - - int n_fallback = 0; - + int n_fallback = 0; bool has_imatrix = false; // used to figure out if a model has tied embeddings (tok_embd shares weights with output) bool has_tied_embeddings = true; // assume tied until we see output.weight + bool has_activations = false; - // tensor type override patterns (compiled once, used twice) - std::vector> tensor_type_patterns; + // tensor type override patterns (compiled once, queried via tensor_type_override_for()) + struct tensor_type_pattern { + std::string pattern; + std::regex regex; + ggml_type type; + }; - quantize_state_impl(const llama_model & model, const llama_model_quantize_params * params): - model(model), params(params) - { + std::vector tensor_type_patterns; + std::array ignored_types{}; + bool has_ignored_types = false; + + quantize_state_impl(const llama_model & model, const llama_model_quantize_params * params) : model(model), params(params) { // compile regex patterns once - they are expensive if (params->tt_overrides) { - for (const auto * p = params->tt_overrides; p->pattern != nullptr; p++) { - tensor_type_patterns.emplace_back(std::regex(p->pattern), p->type); + for (const auto * o = params->tt_overrides; o->pattern != nullptr; o++) { + tensor_type_patterns.push_back({o->pattern, std::regex(o->pattern), o->type}); + } + } + + if (params->target_exclude) { + for (const auto * t = params->target_exclude; * t != GGML_TYPE_COUNT; t++) { + if (* t >= 0 && * t < GGML_TYPE_COUNT) { + ignored_types[*t] = true; + has_ignored_types = true; + } } } } }; +// the --tensor-type override for the tensor or GGML_TYPE_COUNT if none +static ggml_type tensor_type_override_for(const quantize_state_impl & qs, const char * tensor_name) { + if (qs.tensor_type_patterns.empty()) { return GGML_TYPE_COUNT; } + + const std::string name(tensor_name); + for (const auto & p : qs.tensor_type_patterns) { + if (std::regex_search(name, p.regex)) { return p.type; } + } + + return GGML_TYPE_COUNT; +} + // per-tensor metadata, computed in the preliminary loop and used in the main loop struct tensor_metadata { std::string name; @@ -224,68 +226,55 @@ struct tensor_metadata { bool requires_imatrix; }; -// // dequantization -// - -static void llama_tensor_dequantize_impl( - ggml_type type, const void * data, float * f32_output, std::vector & workers, - const size_t nelements, const int nthread +static void llama_tensor_dequantize_impl(ggml_type type, + const void * data, + float * f32_output, + std::vector & workers, + const size_t nelements, + const int nthread ) { const ggml_type_traits * qtype = ggml_get_type_traits(type); if (ggml_is_quantized(type) || type == GGML_TYPE_F8_E4M3) { - if (qtype->to_float == NULL) { + if (qtype->to_float == nullptr) { throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(type))); } - } else if (type != GGML_TYPE_F16 && - type != GGML_TYPE_BF16) { + } else if (type != GGML_TYPE_F16 && type != GGML_TYPE_BF16) { throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(type))); } if (nthread < 2) { - if (type == GGML_TYPE_F16) { - ggml_fp16_to_fp32_row((const ggml_fp16_t *)data, f32_output, nelements); - } else if (type == GGML_TYPE_BF16) { - ggml_bf16_to_fp32_row((const ggml_bf16_t *)data, f32_output, nelements); - } else if (ggml_is_quantized(type) || type == GGML_TYPE_F8_E4M3) { - qtype->to_float(data, f32_output, nelements); - } else { - GGML_ABORT("fatal error"); // unreachable - } + if (type == GGML_TYPE_F16) { ggml_fp16_to_fp32_row((const ggml_fp16_t *)data, f32_output, nelements); } + else if (type == GGML_TYPE_BF16) { ggml_bf16_to_fp32_row((const ggml_bf16_t *)data, f32_output, nelements); } + else if (ggml_is_quantized(type) || type == GGML_TYPE_F8_E4M3) { qtype->to_float(data, f32_output, nelements); } + else { GGML_ABORT("fatal error"); } + return; } size_t block_size; - if (type == GGML_TYPE_F16 || - type == GGML_TYPE_BF16) { - block_size = 1; - } else { - block_size = (size_t)ggml_blck_size(type); - } + if (type == GGML_TYPE_F16 || type == GGML_TYPE_BF16) { block_size = 1; } + else { block_size = (size_t)ggml_blck_size(type); } - size_t block_size_bytes = ggml_type_size(type); + const size_t block_size_bytes = ggml_type_size(type); GGML_ASSERT(nelements % block_size == 0); - size_t nblocks = nelements / block_size; - size_t blocks_per_thread = nblocks / nthread; - size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count + const size_t nblocks = nelements / block_size; + const size_t blocks_per_thread = nblocks / nthread; + const size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count size_t in_buff_offs = 0; size_t out_buff_offs = 0; for (int tnum = 0; tnum < nthread; tnum++) { - size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread + const size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread size_t thr_elems = thr_blocks * block_size; // number of elements for this thread - size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread + const size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread auto compute = [qtype] (ggml_type typ, const uint8_t * inbuf, float * outbuf, int nels) { - if (typ == GGML_TYPE_F16) { - ggml_fp16_to_fp32_row((const ggml_fp16_t *)inbuf, outbuf, nels); - } else if (typ == GGML_TYPE_BF16) { - ggml_bf16_to_fp32_row((const ggml_bf16_t *)inbuf, outbuf, nels); - } else { - qtype->to_float(inbuf, outbuf, nels); - } + if (typ == GGML_TYPE_F16) { ggml_fp16_to_fp32_row((const ggml_fp16_t *)inbuf, outbuf, nels); } + else if (typ == GGML_TYPE_BF16) { ggml_bf16_to_fp32_row((const ggml_bf16_t *)inbuf, outbuf, nels); } + else { qtype->to_float(inbuf, outbuf, nels); } }; workers.emplace_back(compute, type, (const uint8_t *) data + in_buff_offs, f32_output + out_buff_offs, thr_elems); in_buff_offs += thr_block_bytes; @@ -295,21 +284,17 @@ static void llama_tensor_dequantize_impl( workers.clear(); } -// // do we allow this tensor to be quantized? -// - static bool tensor_allows_quantization(const llama_model_quantize_params * params, llm_arch arch, const ggml_tensor * tensor) { - // trivial checks first -- no string ops needed - if (params->only_copy) return false; + if (params->only_copy) { return false; } // quantize only 2D+ tensors (matrices, experts, conv kernels) - if (ggml_n_dims(tensor) < 2) return false; + if (ggml_n_dims(tensor) < 2) { return false; } const std::string name = ggml_get_name(tensor); - // This used to be a regex, but has an extreme cost to compile times. - bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'? + // ends with 'weight'? + bool quantize = name.rfind("weight") == name.size() - 6; // do not quantize norm tensors quantize &= name.find("_norm.weight") == std::string::npos; @@ -317,7 +302,6 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param quantize &= params->quantize_output_tensor || name != "output.weight"; // do not quantize expert gating tensors - // NOTE: can't use LLM_TN here because the layer number is not known quantize &= name.find("ffn_gate_inp.weight") == std::string::npos; // do not quantize the i32 token-id -> expert-id routing table (DeepSeek-V4) @@ -360,7 +344,6 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param quantize &= name != LLM_TN(arch)(LLM_TENSOR_TOKEN_TYPES, "weight"); // do not quantize Mamba/Kimi's small conv1d weights - // NOTE: can't use LLM_TN here because the layer number is not known quantize &= name.find("ssm_conv1d") == std::string::npos; quantize &= name.find("shortconv.conv.weight") == std::string::npos; @@ -458,90 +441,77 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param return quantize; } -// -// tensor type selection -// +// mapping from an incompatible target type to its block-size-32 substitute +static ggml_type fallback_type_for(const ggml_type target_type) { + switch (target_type) { + // types on the left, block size 256; types on the right, block size 32 + case GGML_TYPE_IQ1_S: + case GGML_TYPE_IQ1_M: + case GGML_TYPE_IQ2_XXS: + case GGML_TYPE_IQ2_XS: + case GGML_TYPE_IQ2_S: + case GGML_TYPE_IQ3_XXS: + case GGML_TYPE_IQ3_S: + case GGML_TYPE_IQ4_XS: return GGML_TYPE_IQ4_NL; + case GGML_TYPE_Q2_0: + case GGML_TYPE_Q2_K: + case GGML_TYPE_Q3_K: + case GGML_TYPE_TQ1_0: + case GGML_TYPE_TQ2_0: return GGML_TYPE_Q4_0; + case GGML_TYPE_Q4_K: return GGML_TYPE_Q5_0; + case GGML_TYPE_Q5_K: return GGML_TYPE_Q5_1; + case GGML_TYPE_Q6_K: return GGML_TYPE_Q8_0; + default: + if (ggml_blck_size(target_type) <= 32) { return GGML_TYPE_COUNT; } // nothing smaller to demote to + throw std::runtime_error(format("no tensor type fallback is defined for type %s", ggml_type_name(target_type))); + } +} // incompatible tensor shapes are handled here - fallback to a compatible type static ggml_type tensor_type_fallback(quantize_state_impl & qs, const ggml_tensor * t, const ggml_type target_type) { - ggml_type return_type = target_type; - const int64_t ncols = t->ne[0]; const int64_t qk_k = ggml_blck_size(target_type); - - if (ncols % qk_k != 0) { // this tensor's shape is incompatible with this quant - LLAMA_LOG_WARN("warning: %-36s - ncols %6" PRId64 " not divisible by %3" PRId64 " (required for type %7s) ", - t->name, ncols, qk_k, ggml_type_name(target_type)); - ++qs.n_fallback; - - switch (target_type) { - // types on the left: block size 256 - case GGML_TYPE_IQ1_S: - case GGML_TYPE_IQ1_M: - case GGML_TYPE_IQ2_XXS: - case GGML_TYPE_IQ2_XS: - case GGML_TYPE_IQ2_S: - case GGML_TYPE_IQ3_XXS: - case GGML_TYPE_IQ3_S: // types on the right: block size 32 - case GGML_TYPE_IQ4_XS: return_type = GGML_TYPE_IQ4_NL; break; - case GGML_TYPE_Q2_0: - case GGML_TYPE_Q2_K: - case GGML_TYPE_Q3_K: - case GGML_TYPE_TQ1_0: - case GGML_TYPE_TQ2_0: return_type = GGML_TYPE_Q4_0; break; - case GGML_TYPE_Q4_K: return_type = GGML_TYPE_Q5_0; break; - case GGML_TYPE_Q5_K: return_type = GGML_TYPE_Q5_1; break; - case GGML_TYPE_Q6_K: return_type = GGML_TYPE_Q8_0; break; - default: - if (qk_k <= 32) { - // the target is already a 32-block type, so there is no smaller block to demote to - // the check below turns it into F16, as a 256-block type does when its fallback does not fit - return_type = target_type; - break; - } - throw std::runtime_error(format("no tensor type fallback is defined for type %s", - ggml_type_name(target_type))); - } - if (ncols % ggml_blck_size(return_type) != 0) { - // - // the fallback return type is still not compatible for this tensor! - // - // most likely, this tensor's first dimension is not divisible by 32. - // this is very rare. we can either abort the quantization, or - // fallback to F16 / F32. - // - LLAMA_LOG_WARN("(WARNING: must use F16 due to unusual shape) "); - return_type = GGML_TYPE_F16; - } - LLAMA_LOG_WARN("-> falling back to %7s\n", ggml_type_name(return_type)); - } - return return_type; + if (ncols % qk_k == 0) { return target_type; } // this tensor's shape is compatible with this quant + ++qs.n_fallback; + LLAMA_LOG_WARN("warning: %-36s - ncols %6" PRId64 " not divisible by %3" PRId64 " (required for type %7s) ", + t->name, ncols, qk_k, ggml_type_name(target_type)); + + ggml_type fallback_type = fallback_type_for(target_type); + if (fallback_type == GGML_TYPE_COUNT || ncols % ggml_blck_size(fallback_type) != 0) { + // + // the fallback return type is still not compatible for this tensor! + // + // most likely, this tensor's first dimension is not divisible by 32. + // this is very rare. we can either abort the quantization, or + // fallback to F16 / F32. + // + LLAMA_LOG_WARN("(WARNING: must use F16 due to unusual shape) "); + fallback_type = GGML_TYPE_F16; + } + LLAMA_LOG_WARN("-> falling back to %7s\n", ggml_type_name(fallback_type)); + + return fallback_type; } -// internal standard logic for selecting the target tensor type based on tensor category, ftype, and model arch +// select the target tensor type based on tensor category, ftype, and model arch static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype, tensor_category category) { const std::string name = ggml_get_name(tensor); // TODO: avoid hardcoded tensor names - use the TN_* constants const llm_arch arch = qs.model.arch; - - auto use_more_bits = [](int i_layer, int n_layers) -> bool { - return i_layer < n_layers/8 || i_layer >= 7*n_layers/8 || (i_layer - n_layers/8)%3 == 2; + auto use_more_bits = [](const int i_layer, const int n_layers) -> bool { + return i_layer < n_layers / 8 || i_layer >= 7 * n_layers / 8 || (i_layer - n_layers / 8) % 3 == 2; }; + const int n_expert = std::max(1, (int)qs.model.hparams.n_expert); - auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) { + auto layer_info = [n_expert] (int i_layer, int n_layer, const char * tname) { if (n_expert > 1) { - // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but occasionally randomly - // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work - // for getting the current layer as I initially thought, and we need to resort to parsing the - // tensor name. - if (sscanf(name, "blk.%d.", &i_layer) != 1) { - throw std::runtime_error(format("Failed to determine layer for tensor %s", name)); - } - if (i_layer < 0 || i_layer >= n_layer) { - throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer)); - } + // Experts may not be consecutive and simply dividing i_ffn_down by n_expert does not work, + // so we need to parse the tensor name + if (sscanf(tname, "blk.%d.", &i_layer) != 1) { throw std::runtime_error(format("Failed to determine layer for tensor %s", tname)); } + if (i_layer < 0 || i_layer >= n_layer) { throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, tname, n_layer)); } } + return std::make_pair(i_layer, n_layer); }; @@ -564,22 +534,16 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type // bumping to q8_0 is preferred since these tensors are not really big // TODO: nemotron 3 super shares ffn_latent and afmoe, bailingmoe3, dots3note, hy-v4, kimi-k3 and laguna share attn_gate. // Widening the guard is likely a win there too, but it changes their files, so it wants a perplexity comparison per architecture first. - if (arch == LLM_ARCH_MUSE_SPARK && - (category == tensor_category::FFN_LATENT || category == tensor_category::ATTENTION_GATE)) { - auto bits_per_weight = [](ggml_type t) { - return 8.0 * ggml_type_size(t) / ggml_blck_size(t); - }; - if (ggml_is_quantized(new_type) && bits_per_weight(new_type) < bits_per_weight(GGML_TYPE_Q8_0)) { - new_type = GGML_TYPE_Q8_0; - } + if (arch == LLM_ARCH_MUSE_SPARK && (category == TENSOR_CATEGORY_FFN_LATENT || category == TENSOR_CATEGORY_ATTENTION_GATE)) { + auto bits_per_weight = [](ggml_type t) { return 8.0 * ggml_type_size(t) / ggml_blck_size(t); }; + if (ggml_is_quantized(new_type) && bits_per_weight(new_type) < bits_per_weight(GGML_TYPE_Q8_0)) { new_type = GGML_TYPE_Q8_0; } } - // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings - // with the quantization of the output tensor - if (category == tensor_category::OUTPUT || (qs.has_tied_embeddings && category == tensor_category::TOKEN_EMBD)) { - if (qs.params->output_tensor_type < GGML_TYPE_COUNT) { - new_type = qs.params->output_tensor_type; - } else { + // for arches that share the same tensor between the token embeddings and the output, + // we quantize the token embeddings with the quantization of the output tensor + if (category == TENSOR_CATEGORY_OUTPUT || (qs.has_tied_embeddings && category == TENSOR_CATEGORY_TOKEN_EMBD)) { + if (qs.params->output_tensor_type < GGML_TYPE_COUNT) { new_type = qs.params->output_tensor_type; } + else { const int64_t nx = tensor->ne[0]; const int64_t qk_k = ggml_blck_size(new_type); @@ -599,14 +563,14 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type } } } else if (ftype == LLAMA_FTYPE_MOSTLY_MXFP4_MOE) { - // MoE tensors -> MXFP4 - // other tensors -> Q8_0 if (tensor_is_expert(name)) { + // MoE tensors -> MXFP4 new_type = GGML_TYPE_MXFP4; } else { + // other tensors -> Q8_0 new_type = GGML_TYPE_Q8_0; } - } else if (category == tensor_category::TOKEN_EMBD) { + } else if (category == TENSOR_CATEGORY_TOKEN_EMBD) { if (qs.params->token_embedding_type < GGML_TYPE_COUNT) { new_type = qs.params->token_embedding_type; } else { @@ -627,242 +591,189 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) { if (category_is_attn_v(category)) { - if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K; - else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K; + if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) { new_type = GGML_TYPE_Q4_K; } + else { new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K; } + ++qs.i_attention_wv; } - else if (qs.model.hparams.n_expert == 8 && category == tensor_category::ATTENTION_K) { - new_type = GGML_TYPE_Q4_K; - } - else if (category == tensor_category::FFN_DOWN) { + else if (qs.model.hparams.n_expert == 8 && category == TENSOR_CATEGORY_ATTENTION_K) { new_type = GGML_TYPE_Q4_K; } + else if (category == TENSOR_CATEGORY_FFN_DOWN) { if (qs.i_ffn_down < qs.n_ffn_down/8) { new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K; } + ++qs.i_ffn_down; } - else if (category == tensor_category::ATTENTION_OUTPUT) { - if (qs.model.hparams.n_expert == 8) { - new_type = GGML_TYPE_Q5_K; - } else { - if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS; - else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S; + else if (category == TENSOR_CATEGORY_ATTENTION_OUTPUT) { + if (qs.model.hparams.n_expert == 8) { new_type = GGML_TYPE_Q5_K; } + else { + if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) { new_type = GGML_TYPE_IQ2_XXS; } + else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) { new_type = GGML_TYPE_IQ3_S; } } } } else if (category_is_attn_v(category)) { - if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) { - new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K; - } - else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) { - new_type = GGML_TYPE_Q4_K; - } + if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) { new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) { new_type = GGML_TYPE_Q4_K; } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) { new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS; } - else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) { - new_type = GGML_TYPE_Q4_K; - } - else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) { - new_type = GGML_TYPE_Q4_K; - } - else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) { - new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K; - } - else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K; - else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) { - new_type = GGML_TYPE_Q5_K; - } + else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) { new_type = GGML_TYPE_Q4_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) { new_type = GGML_TYPE_Q4_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) { new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) { new_type = GGML_TYPE_Q5_K; } + else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) { new_type = GGML_TYPE_Q5_K; } else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) && - use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K; - else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K; + use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) { new_type = GGML_TYPE_Q6_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) { new_type = GGML_TYPE_Q5_K; } if (qs.model.type == LLM_TYPE_70B) { // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with // nearly negligible increase in model size by quantizing this tensor with more bits: - if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K; + if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) { new_type = GGML_TYPE_Q5_K; } } if (qs.model.hparams.n_expert == 8) { // for the 8-expert model, bumping this to Q8_0 trades just ~128MB // TODO: explore better strategies new_type = GGML_TYPE_Q8_0; } + ++qs.i_attention_wv; - } else if (category == tensor_category::ATTENTION_K) { + } else if (category == TENSOR_CATEGORY_ATTENTION_K) { if (qs.model.hparams.n_expert == 8) { - // for the 8-expert model, bumping this to Q8_0 trades just ~128MB // TODO: explore better strategies new_type = GGML_TYPE_Q8_0; } - else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) { - new_type = GGML_TYPE_IQ3_XXS; - } - else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) { - new_type = GGML_TYPE_IQ2_S; - } - } else if (category == tensor_category::ATTENTION_Q) { - if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) { - new_type = GGML_TYPE_IQ3_XXS; - } - else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) { - new_type = GGML_TYPE_IQ2_S; - } - } else if (category == tensor_category::FFN_DOWN) { + else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) { new_type = GGML_TYPE_IQ3_XXS; } + else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) { new_type = GGML_TYPE_IQ2_S; } + } else if (category == TENSOR_CATEGORY_ATTENTION_Q) { + if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) { new_type = GGML_TYPE_IQ3_XXS; } + else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) { new_type = GGML_TYPE_IQ2_S; } + } else if (category == TENSOR_CATEGORY_FFN_DOWN) { auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str()); int i_layer = info.first, n_layer = info.second; - if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K; - else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) { - if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K; - } - else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) { - new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K; - } + if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) { new_type = GGML_TYPE_Q3_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) { if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) { new_type = i_layer < n_layer / 8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K; } else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) { new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K; } - else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 || - (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) { + else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer / 8 || (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) { new_type = GGML_TYPE_Q4_K; } - else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) { - new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K; - } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) { new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K; } else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) { if (arch == LLM_ARCH_FALCON) { - new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K : - use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K; - } else { - if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K; - } + new_type = i_layer < n_layer / 16 ? GGML_TYPE_Q6_K : use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K; + } else if (use_more_bits(i_layer, n_layer)) { new_type = GGML_TYPE_Q6_K; } } - else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) { + else if (i_layer < n_layer / 8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) { new_type = GGML_TYPE_Q5_K; } - else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K; - else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) { - new_type = GGML_TYPE_Q5_K; - } - else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0) - && qs.has_imatrix && i_layer < n_layer/8) { - // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0. - // We only do it when an imatrix is provided because a) we want to make sure that one can always get the - // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix. + else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) { new_type = GGML_TYPE_Q6_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) { new_type = GGML_TYPE_Q5_K; } + else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0) && qs.has_imatrix && i_layer < n_layer / 8) { + // Safeguard against instability in the initial ffn_down layers, which can occur with Q4_0/Q5_0 quantization even when an imatrix is used. + // The rationale is two-fold: first, to guarantee that the resulting quantization remains consistent with the pre-imatrix state, + // and second, because Q4_1/Q5_1 tend to exhibit instability in ffn_down layers without an imatrix. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1; } + ++qs.i_ffn_down; - } else if (category == tensor_category::ATTENTION_OUTPUT) { + } else if (category == TENSOR_CATEGORY_ATTENTION_OUTPUT) { if (arch != LLM_ARCH_FALCON) { if (qs.model.hparams.n_expert == 8) { if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S || - ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) { - new_type = GGML_TYPE_Q5_K; - } + ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) { new_type = GGML_TYPE_Q5_K; } } else { - if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K; - else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S; - else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K; - else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K; - else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K; + if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) { new_type = GGML_TYPE_Q3_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) { new_type = GGML_TYPE_IQ3_S; } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) { new_type = GGML_TYPE_Q4_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) { new_type = GGML_TYPE_Q5_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) { new_type = GGML_TYPE_Q4_K; } } - } else { - if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K; - } + } else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) { new_type = GGML_TYPE_Q4_K; } } - else if (category == tensor_category::ATTENTION_QKV) { - if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) { - new_type = GGML_TYPE_Q4_K; - } - else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K; - else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K; + else if (category == TENSOR_CATEGORY_ATTENTION_QKV) { + if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) { new_type = GGML_TYPE_Q4_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) { new_type = GGML_TYPE_Q5_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) { new_type = GGML_TYPE_Q6_K; } } - else if (category == tensor_category::FFN_GATE) { + else if (category == TENSOR_CATEGORY_FFN_GATE) { auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str()); int i_layer = info.first, n_layer = info.second; - if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) { - new_type = GGML_TYPE_IQ3_XXS; - } + if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && i_layer >= n_layer / 8 && i_layer < 7 * n_layer / 8) { new_type = GGML_TYPE_IQ3_XXS; } + ++qs.i_ffn_gate; } - else if (category == tensor_category::FFN_UP) { + else if (category == TENSOR_CATEGORY_FFN_UP) { auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str()); int i_layer = info.first, n_layer = info.second; - if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) { - new_type = GGML_TYPE_IQ3_XXS; - } + if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && i_layer >= n_layer / 8 && i_layer < 7 * n_layer / 8) { new_type = GGML_TYPE_IQ3_XXS; } + ++qs.i_ffn_up; } return new_type; } -// outer wrapper: determine the ggml_type that this tensor should be quantized to -static ggml_type llama_tensor_get_type(quantize_state_impl & qs, const llama_model_quantize_params * params, const ggml_tensor * tensor, ggml_type default_type, const tensor_metadata & tm) { - if (!tensor_allows_quantization(params, qs.model.arch, tensor)) { - return tensor->type; - } - if (params->token_embedding_type < GGML_TYPE_COUNT && tm.category == tensor_category::TOKEN_EMBD) { +// determine the ggml_type that this tensor should be quantized to +static ggml_type llama_tensor_get_type(quantize_state_impl & qs, + const llama_model_quantize_params * params, + const ggml_tensor * tensor, + const ggml_type default_type, + const tensor_metadata & tm +) { + if (params->target_bpw != -1.0f || params->target_size != -1) { return tensor->type; } + if (!tensor_allows_quantization(params, qs.model.arch, tensor)) { return tensor->type; } + if (params->token_embedding_type < GGML_TYPE_COUNT && tm.category == TENSOR_CATEGORY_TOKEN_EMBD) { // per_layer_token_embd follows --token-embedding-type by default, but it is a large // separate table, so let an explicit --tensor-type name it - bool named = false; - if (std::strcmp(tensor->name, "per_layer_token_embd.weight") == 0) { - const std::string tensor_name(tensor->name); - for (const auto & [pattern, qtype] : qs.tensor_type_patterns) { - if (std::regex_search(tensor_name, pattern)) { - named = true; - break; - } - } - } - if (!named) { - return params->token_embedding_type; - } - } - if (params->output_tensor_type < GGML_TYPE_COUNT && tm.category == tensor_category::OUTPUT) { - return params->output_tensor_type; + const bool named = std::strcmp(tensor->name, "per_layer_token_embd.weight") == 0 && tensor_type_override_for(qs, tensor->name) != GGML_TYPE_COUNT; + if (!named) { return params->token_embedding_type; } } + if (params->output_tensor_type < GGML_TYPE_COUNT && tm.category == TENSOR_CATEGORY_OUTPUT) { return params->output_tensor_type; } ggml_type new_type = default_type; // get more optimal quantization type based on the tensor shape, layer, etc. if (ggml_is_quantized(default_type)) { - // if the user provided tensor types - use those - bool manual = false; - if (!qs.tensor_type_patterns.empty()) { - const std::string tensor_name(tensor->name); - for (const auto & [pattern, qtype] : qs.tensor_type_patterns) { - if (std::regex_search(tensor_name, pattern)) { - if (qtype != new_type) { - LLAMA_LOG_WARN("%s: %-36s - applying manual override: %s -> %s\n", - __func__, tensor_name.c_str(), ggml_type_name(new_type), ggml_type_name(qtype)); - new_type = qtype; - } - manual = true; - break; - } - } + // if the user provided tensor types, use those + const ggml_type manual_type = tensor_type_override_for(qs, tensor->name); + const bool manual = manual_type != GGML_TYPE_COUNT; + if (manual && manual_type != new_type) { + LLAMA_LOG_WARN("%s: %-36s - applying manual override: %s -> %s\n", + __func__, tensor->name, ggml_type_name(new_type), ggml_type_name(manual_type)); + new_type = manual_type; } - // if not manual - use the standard logic for choosing the quantization type based on the selected mixture - if (!manual && !params->pure) { - new_type = llama_tensor_get_type_impl(qs, new_type, tensor, params->ftype, tm.category); - } + // otherwise, use the standard logic + if (!manual && !params->pure) { new_type = llama_tensor_get_type_impl(qs, new_type, tensor, params->ftype, tm.category); } - // incompatible tensor shapes are handled here - fallback to a compatible type + // if incompatible tensor shape, fallback to a compatible type new_type = tensor_type_fallback(qs, tensor, new_type); } return new_type; } -// -// quantization implementation -// - // quantize rows [first_row, first_row + nrows), indexed globally across all expert matrices // note: chunks never cross an expert boundary since each expert has its own imatrix slice -static size_t llama_tensor_quantize_impl(enum ggml_type new_type, const float * f32_data, void * new_data, const int64_t chunk_size, int64_t first_row, int64_t nrows, int64_t nrows_per_expert, int64_t n_per_row, const float * imatrix, std::vector & workers, const int nthread) { +static size_t llama_tensor_quantize_impl(ggml_type new_type, + const float * f32_data, + void * new_data, + const int64_t chunk_size, + int64_t first_row, + int64_t nrows, + int64_t nrows_per_expert, + int64_t n_per_row, + const float * imatrix, + std::vector & workers, + const int nthread +) { const size_t row_size = ggml_row_size(new_type, n_per_row); auto imatrix_for_row = [=](int64_t row_global) { @@ -877,12 +788,12 @@ static size_t llama_tensor_quantize_impl(enum ggml_type new_type, const float * const int64_t this_nrow = std::min(nrows - row, nrows_per_expert - row_global % nrows_per_expert); void * this_data = (char *) new_data + row * row_size; size_t this_size = ggml_quantize_chunk(new_type, f32_data + row * n_per_row, this_data, 0, this_nrow, n_per_row, imatrix_for_row(row_global)); - if (!ggml_validate_row_data(new_type, this_data, this_size)) { - throw std::runtime_error("quantized data validation failed"); - } + if (!ggml_validate_row_data(new_type, this_data, this_size)) { throw std::runtime_error("quantized data validation failed"); } + new_size += this_size; row += this_nrow; } + return new_size; } @@ -891,15 +802,13 @@ static size_t llama_tensor_quantize_impl(enum ggml_type new_type, const float * size_t new_size = 0; bool valid = true; auto compute = [&mutex, &counter, &new_size, &valid, new_type, f32_data, new_data, chunk_size, - first_row, nrows, nrows_per_expert, n_per_row, row_size, imatrix_for_row]() { + first_row, nrows, nrows_per_expert, n_per_row, row_size, imatrix_for_row] { const int64_t nrows_per_chunk = chunk_size / n_per_row; size_t local_size = 0; while (true) { std::unique_lock lock(mutex); if (counter >= nrows) { - if (local_size > 0) { - new_size += local_size; - } + if (local_size > 0) { new_size += local_size; } break; } const int64_t row = counter; @@ -921,140 +830,2346 @@ static size_t llama_tensor_quantize_impl(enum ggml_type new_type, const float * } } }; - for (int it = 0; it < nthread - 1; ++it) { - workers.emplace_back(compute); - } + + for (int it = 0; it < nthread - 1; ++it) { workers.emplace_back(compute); } compute(); for (auto & w : workers) { w.join(); } workers.clear(); - if (!valid) { - throw std::runtime_error("quantized data validation failed"); - } + if (!valid) { throw std::runtime_error("quantized data validation failed"); } + return new_size; } -// -// imatrix requirement check -// +// Returns tensor type overrides that meet a global file size or bpw target +static std::unordered_map target_bpw_type( + llama_model_loader & ml, + quantize_state_impl & qs, + const std::vector & tensors, + const std::map & mapped, + const std::unordered_map> * values_data, + const std::unordered_map> * activations_data, + const std::unordered_map> * statistics_data, + const std::vector * stats_schema, + const std::unordered_map * locked_tensors, + int nthread +) { + bool interrupted = false; + std::mutex interrupt_mutex; + auto poll_interrupt = [&]() { + if (!qs.params->abort_callback) { return false; } + std::lock_guard lock(interrupt_mutex); + if (!interrupted) { interrupted = qs.params->abort_callback(qs.params->abort_callback_data); } + return interrupted; + }; -static bool tensor_requires_imatrix(const char * tensor_name, const ggml_type dst_type, const llama_ftype ftype) { - if (tensor_name_match_token_embd(tensor_name) || tensor_name_match_output_weight(tensor_name)) { - return false; - } - switch (dst_type) { - case GGML_TYPE_IQ3_XXS: - case GGML_TYPE_IQ2_XXS: - case GGML_TYPE_IQ2_XS: - case GGML_TYPE_IQ2_S: - case GGML_TYPE_IQ1_M: - case GGML_TYPE_IQ1_S: - return true; - case GGML_TYPE_Q2_K: - // as a general rule, the k-type quantizations don't require imatrix data. - // the only exception is Q2_K tensors that are part of a Q2_K_S file. - return ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S; - default: - return false; - } -} + // GGML_TYPE scores + struct type_scores { + ggml_type type = GGML_TYPE_COUNT; + float bpw = 0.0f; + size_t bytes = 0; + double error = 0.0; + double mse = 0.0; + double wce = 0.0; + }; -// -// given a file type, get the default tensor type -// + // Tensor quantization type choice + struct type_choice { + const llama_model_loader::llama_tensor_weight * w = nullptr; + std::vector candidates; + int choice = -1; + float min_bpw = 0.0; + float max_bpw = 0.0; + size_t n_elements = 0; + float boost = 1.0f; + }; -ggml_type llama_ftype_get_default_type(llama_ftype ftype) { - switch (ftype) { - case LLAMA_FTYPE_MOSTLY_Q4_0: return GGML_TYPE_Q4_0; - case LLAMA_FTYPE_MOSTLY_Q4_1: return GGML_TYPE_Q4_1; - case LLAMA_FTYPE_MOSTLY_Q5_0: return GGML_TYPE_Q5_0; - case LLAMA_FTYPE_MOSTLY_Q5_1: return GGML_TYPE_Q5_1; - case LLAMA_FTYPE_MOSTLY_Q8_0: return GGML_TYPE_Q8_0; - case LLAMA_FTYPE_MOSTLY_F16: return GGML_TYPE_F16; - case LLAMA_FTYPE_MOSTLY_BF16: return GGML_TYPE_BF16; - case LLAMA_FTYPE_ALL_F32: return GGML_TYPE_F32; - case LLAMA_FTYPE_MOSTLY_Q1_0: return GGML_TYPE_Q1_0; - case LLAMA_FTYPE_MOSTLY_Q2_0: return GGML_TYPE_Q2_0; + // Quantization types + constexpr ggml_type quant_types[] = { + GGML_TYPE_IQ1_S, + GGML_TYPE_IQ1_M, + GGML_TYPE_IQ2_XXS, + GGML_TYPE_IQ2_XS, + GGML_TYPE_IQ2_S, + GGML_TYPE_IQ3_XXS, + GGML_TYPE_IQ3_S, + GGML_TYPE_IQ4_XS, + GGML_TYPE_IQ4_NL, + GGML_TYPE_Q2_K, + GGML_TYPE_Q3_K, + GGML_TYPE_Q4_0, + GGML_TYPE_Q4_1, + GGML_TYPE_Q4_K, + GGML_TYPE_Q5_0, + GGML_TYPE_Q5_1, + GGML_TYPE_Q5_K, + GGML_TYPE_Q6_K, + GGML_TYPE_Q8_0, + GGML_TYPE_F16, + GGML_TYPE_BF16, + }; - case LLAMA_FTYPE_MOSTLY_MXFP4_MOE: return GGML_TYPE_MXFP4; + constexpr double EPSILON = 1e-12; + constexpr double INFINITE = std::numeric_limits::infinity(); + constexpr uint64_t STATE_MAGIC = 0x4250572d5632; // "BPW-V2" + constexpr uint64_t HASH_MAGIC = 0xeabada55cafed00d; + constexpr float ffn_down_boost = 6.0f; + constexpr float output_boost = 3.0f; + constexpr float tied_embd_boost = 2.5f; + constexpr float attn_v_boost = 1.25f; + constexpr float boost_taper = 2.2f; // boost starves other tensors below 2.2 bpw + constexpr double downward_threshold = 0.08; // potential gains smaller than 8% are not trusted + const char * func = __func__; - // K-quants - case LLAMA_FTYPE_MOSTLY_Q2_K_S: - case LLAMA_FTYPE_MOSTLY_Q2_K: return GGML_TYPE_Q2_K; - case LLAMA_FTYPE_MOSTLY_IQ3_XS: return GGML_TYPE_IQ3_S; - case LLAMA_FTYPE_MOSTLY_Q3_K_S: - case LLAMA_FTYPE_MOSTLY_Q3_K_M: - case LLAMA_FTYPE_MOSTLY_Q3_K_L: return GGML_TYPE_Q3_K; - case LLAMA_FTYPE_MOSTLY_Q4_K_S: - case LLAMA_FTYPE_MOSTLY_Q4_K_M: return GGML_TYPE_Q4_K; - case LLAMA_FTYPE_MOSTLY_Q5_K_S: - case LLAMA_FTYPE_MOSTLY_Q5_K_M: return GGML_TYPE_Q5_K; - case LLAMA_FTYPE_MOSTLY_Q6_K: return GGML_TYPE_Q6_K; - case LLAMA_FTYPE_MOSTLY_TQ1_0: return GGML_TYPE_TQ1_0; - case LLAMA_FTYPE_MOSTLY_TQ2_0: return GGML_TYPE_TQ2_0; - case LLAMA_FTYPE_MOSTLY_IQ2_XXS: return GGML_TYPE_IQ2_XXS; - case LLAMA_FTYPE_MOSTLY_IQ2_XS: return GGML_TYPE_IQ2_XS; - case LLAMA_FTYPE_MOSTLY_IQ2_S: return GGML_TYPE_IQ2_XS; - case LLAMA_FTYPE_MOSTLY_IQ2_M: return GGML_TYPE_IQ2_S; - case LLAMA_FTYPE_MOSTLY_IQ3_XXS: return GGML_TYPE_IQ3_XXS; - case LLAMA_FTYPE_MOSTLY_IQ1_S: return GGML_TYPE_IQ1_S; - case LLAMA_FTYPE_MOSTLY_IQ1_M: return GGML_TYPE_IQ1_M; - case LLAMA_FTYPE_MOSTLY_IQ4_NL: return GGML_TYPE_IQ4_NL; - case LLAMA_FTYPE_MOSTLY_IQ4_XS: return GGML_TYPE_IQ4_XS; - case LLAMA_FTYPE_MOSTLY_IQ3_S: - case LLAMA_FTYPE_MOSTLY_IQ3_M: return GGML_TYPE_IQ3_S; + // --target-exclude must leave at least one quant type in the pool + if (qs.has_ignored_types) { + bool all_ignored = true; + for (const ggml_type t : quant_types) { + if (!qs.ignored_types[t]) { all_ignored = false; break; } + } - default: return GGML_TYPE_COUNT; + if (all_ignored) { throw std::runtime_error(format("%s: --target-exclude bars every quant type in the selection pool\n", func)); } } -} + // Tensor size in bytes for a given type + auto tensor_bytes = [](const ggml_tensor * gt, const ggml_type gq) -> size_t { + return (size_t)ggml_nrows(gt) * ggml_row_size(gq, gt->ne[0]); + }; -static void init_quantize_state_counters(quantize_state_impl & qs, std::vector & metadata) { - for (auto & tm : metadata) { - tensor_category cat = tensor_get_category(tm.name); - tm.category = cat; + // Tensor bpw for a given type + auto tensor_bpw = [&](const ggml_tensor * gt, const ggml_type gq) -> double { + return (double)tensor_bytes(gt, gq) * 8.0 / (double)ggml_nelements(gt); + }; - if (category_is_attn_v(cat)) { - ++qs.n_attention_wv; - } + // Check if tensor is compatible with quantization type + auto is_compatible = [](const ggml_tensor * gt, const ggml_type gq) -> bool { + const int64_t blck = ggml_blck_size(gq); + return blck <= 1 || gt->ne[0] % blck == 0; + }; + + // Get suitable fallback for type + auto make_compatible = [&](const ggml_tensor * gt, const ggml_type gq) -> ggml_type { + if (is_compatible(gt, gq)) { return gq; } + const ggml_type fb = fallback_type_for(gq); + return fb != GGML_TYPE_COUNT && is_compatible(gt, fb) ? fb : GGML_TYPE_F16; + }; - if (cat == tensor_category::OUTPUT) { - qs.has_tied_embeddings = false; + // Check if tensor is an IQ type + auto is_iq = [](const enum ggml_type gt) { + switch (gt) { + case GGML_TYPE_IQ1_S: + case GGML_TYPE_IQ1_M: + case GGML_TYPE_IQ2_XXS: + case GGML_TYPE_IQ2_XS: + case GGML_TYPE_IQ2_S: + case GGML_TYPE_IQ3_XXS: + case GGML_TYPE_IQ3_S: + case GGML_TYPE_IQ4_NL: + case GGML_TYPE_IQ4_XS: + return true; + default: + return false; } - } - qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)qs.model.hparams.n_layer_all; -} + }; -// -// main quantization driver -// + // Check if tensor can be quantized + auto can_quantize = [&](const ggml_tensor * gt) -> bool { + if (ggml_n_dims(gt) < 2 || ggml_n_dims(gt) > 3) { return false; } // skip 1D & 4D+ tensors + return tensor_allows_quantization(qs.params, qs.model.arch, gt); + }; -static void llama_model_quantize_impl(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) { - llama_ftype ftype = params->ftype; + // DJB2 hashing algorithm + auto djb2_hash = [&](const uint8_t * data, const size_t n, uint64_t h = 5381) -> uint64_t { + for (size_t i = 0; i < n; ++i) { h = (h << 5) + h + data[i]; } + return h ? h : HASH_MAGIC; + }; - int nthread = params->nthread; + // Model ID from the metadata, the imatrix data and the pruned layers + const uint64_t model_id = [&] { + const size_t sz = gguf_get_meta_size(ml.metadata); + std::vector buf(sz); + gguf_get_meta_data(ml.metadata, buf.data()); + uint64_t h = djb2_hash(buf.data(), buf.size()); + auto hash_bytes = [&](const void * data, const size_t n) { h = djb2_hash((const uint8_t *)data, n, h); }; + auto hash_size = [&](const uint64_t n) { hash_bytes(& n, sizeof(n)); }; + + for (const auto * m : { values_data, activations_data, statistics_data }) { + const uint8_t present = m != nullptr; + hash_bytes(& present, sizeof(present)); + if (!m) { continue; } + + // the maps have no fixed order + std::vector names; + names.reserve(m->size()); + for (const auto & e : * m) { names.push_back(e.first); } + std::sort(names.begin(), names.end()); + + hash_size(names.size()); + for (const auto & name : names) { + const std::vector & v = m->at(name); + hash_size(name.size()); + hash_bytes(name.data(), name.size()); + hash_size(v.size()); + hash_bytes(v.data(), v.size() * sizeof(float)); + } + } - if (nthread <= 0) { - nthread = std::thread::hardware_concurrency(); - } + const uint8_t has_schema = stats_schema != nullptr; + hash_bytes(& has_schema, sizeof(has_schema)); + if (stats_schema) { + hash_size(stats_schema->size()); + for (const auto & name : * stats_schema) { + hash_size(name.size()); + hash_bytes(name.data(), name.size()); + } + } - ggml_type default_type = llama_ftype_get_default_type(ftype); - if (default_type == GGML_TYPE_COUNT) { - throw std::runtime_error(format("invalid output file type %d\n", ftype)); - } + for (const auto & [blk, num] : mapped) { + const int32_t b = blk; + hash_bytes(& b, sizeof(b)); + hash_size(num.size()); + hash_bytes(num.data(), num.size()); + } - // mmap consistently increases speed on Linux, and also increases speed on Windows with - // hot cache. It may cause a slowdown on macOS, possibly related to free memory. -#if defined(__linux__) || defined(_WIN32) - constexpr llama_load_mode load_mode = LLAMA_LOAD_MODE_MMAP; -#else - constexpr llama_load_mode load_mode = LLAMA_LOAD_MODE_NONE; -#endif + return h; + }(); - const llama_model_kv_override * kv_overrides = params->kv_overrides; - std::vector splits = {}; - llama_model_loader ml(/*metadata*/ nullptr, /*set_tensor_data*/ nullptr, /*set_tensor_data_ud*/ nullptr, - fname_inp, splits, /*file*/ nullptr, /*load_mode*/ load_mode, /*check_tensors*/ true, /*no_alloc*/ false, /*load_mtp*/ true, kv_overrides, nullptr); - ml.init_mappings(false); // no prefetching + std::string checkpoint_file; + + { + char hex[17]; + std::string name; + std::snprintf(hex, sizeof(hex), "%016" PRIx64, (uint64_t)model_id); + ml.get_key(LLM_KV_GENERAL_NAME, name, false); + name.erase(0, name.find_last_of('/') + 1); + std::replace(name.begin(), name.end(), ' ', '_'); + name.empty() ? checkpoint_file = ml.arch_name : checkpoint_file = name; + checkpoint_file += "-" + std::string(hex) + ".bpw_state"; + + if (qs.params->state_file) { + if (qs.params->state_file[0] != '\0') { checkpoint_file = qs.params->state_file; } + const char * fname = checkpoint_file.c_str(); + FILE * f = std::fopen(fname, "rb"); + if (!f && errno == ENOENT) { + f = std::fopen(fname, "wbx"); + if (!f) { throw std::runtime_error(format("%s: failed to open %s: %s\n", func, fname, std::strerror(errno))); } + std::fclose(f); + if (std::remove(fname) != 0) { LLAMA_LOG_WARN("%s: failed to remove %s: %s\n", func, fname, std::strerror(errno)); } + } else { + const bool readable = f && (std::fgetc(f) != EOF || !std::ferror(f)); + const int err = errno; + if (f) { std::fclose(f); } + if (!readable) { throw std::runtime_error(format("%s: failed to open %s: %s\n", func, fname, std::strerror(err))); } + } + } + } + + // Save vector state to disk + auto save_state = [&](const std::vector & all_tensors) { + const std::string tmp = checkpoint_file + ".tmp"; + std::ofstream ofs(tmp, std::ios::binary | std::ios::trunc); + if (!ofs) { + LLAMA_LOG_WARN("\n\t%s: failed to save progress to %s (open error)\n", func, tmp.c_str()); + return; + } + ofs.write((const char *)& STATE_MAGIC, sizeof(STATE_MAGIC)); + ofs.write((const char *)& model_id, sizeof(model_id)); + const uint64_t n = all_tensors.size(); + ofs.write((const char *)& n, sizeof(n)); + for (const auto & tn : all_tensors) { + const std::string name = ggml_get_name(tn.w->tensor); + const auto len = (uint32_t)name.size(); + ofs.write((const char *)& len, sizeof(len)); + ofs.write(name.data(), len); + + const uint64_t sz = tn.candidates.size(); + ofs.write((const char *)& sz, sizeof(sz)); + ofs.write((const char *)& tn.choice, sizeof(tn.choice)); + ofs.write((const char *)& tn.min_bpw, sizeof(tn.min_bpw)); + ofs.write((const char *)& tn.max_bpw, sizeof(tn.max_bpw)); + const uint64_t ne = tn.n_elements; + ofs.write((const char *)& ne, sizeof(ne)); + + for (const auto & c : tn.candidates) { + const int32_t tp = c.type; + const uint64_t bt = c.bytes; + ofs.write((const char *)& tp, sizeof(tp)); + ofs.write((const char *)& c.bpw, sizeof(c.bpw)); + ofs.write((const char *)& bt, sizeof(bt)); + ofs.write((const char *)& c.error, sizeof(c.error)); + } + } + + const bool werr = ofs.fail() || ofs.bad(); + ofs.close(); + if (werr || ofs.fail() || ofs.bad()) { + std::remove(tmp.c_str()); + LLAMA_LOG_WARN("\n\t%s: failed to save progress to %s (write error)\n", func, tmp.c_str()); + return; + } + + std::remove(checkpoint_file.c_str()); + if (std::rename(tmp.c_str(), checkpoint_file.c_str()) != 0) { + LLAMA_LOG_WARN("\n\t%s: failed to save progress to %s (rename error), kept in %s\n", func, checkpoint_file.c_str(), tmp.c_str()); + return; + } + + LLAMA_LOG_INFO("\t%s: saved target progress for %zu tensors to %s\n", func, all_tensors.size(), checkpoint_file.c_str()); + }; + + // Load vector state from disk + auto load_state = [&]() -> std::unordered_map { + std::ifstream ifs(checkpoint_file, std::ios::binary); + if (!ifs) { return {}; } + + uint64_t magic = 0; + uint64_t id = 0; + ifs.read((char *)& magic, sizeof(magic)); + ifs.read((char *)& id, sizeof(id)); + if (id != model_id) { + LLAMA_LOG_WARN("%s: state file does not match this model, imatrix or pruned layers, ignoring\n", func); + return {}; + } + + if (magic != STATE_MAGIC) { + LLAMA_LOG_WARN("%s: invalid state file, ignoring\n", func); + return {}; + } + + std::unordered_map out; + uint64_t n = 0; + ifs.read((char *)& n, sizeof(n)); + for (uint64_t i = 0; i < n; ++i) { + if (!ifs.good()) { break; } + uint32_t len = 0; + ifs.read((char *)& len, sizeof(len)); + if (len >= GGML_MAX_NAME) { + LLAMA_LOG_WARN("%s: state file name length exceeds limits, ignoring\n", func); + return {}; + } + std::string name(len, '\0'); + ifs.read(name.data(), len); + + type_choice si; + uint64_t sz = 0; + ifs.read((char *)& sz, sizeof(sz)); + if (!ifs.good()) { break; } + if (sz == 0 || sz > std::size(quant_types)) { + LLAMA_LOG_WARN("%s: candidate count out of range, ignoring state file\n", func); + return {}; + } + ifs.read((char *)& si.choice, sizeof(si.choice)); + ifs.read((char *)& si.min_bpw, sizeof(si.min_bpw)); + ifs.read((char *)& si.max_bpw, sizeof(si.max_bpw)); + uint64_t ne = 0; + ifs.read((char *)& ne, sizeof(ne)); + si.n_elements = (size_t)ne; + + si.candidates.resize(sz); + for (auto & cd : si.candidates) { + if (!ifs.good()) { break; } + int32_t t = 0; + uint64_t b = 0; + ifs.read((char *)& t, sizeof(t)); + if (!ifs.good()) { break; } + if (std::find(std::begin(quant_types), std::end(quant_types), t) == std::end(quant_types)) { + LLAMA_LOG_WARN("%s: candidate type is not in the selection pool, ignoring state file\n", func); + return {}; + } + cd.type = (ggml_type)t; + ifs.read((char *)& cd.bpw, sizeof(cd.bpw)); + ifs.read((char *)& b, sizeof(b)); + cd.bytes = (size_t)b; + ifs.read((char *)& cd.error, sizeof(cd.error)); + } + + out.emplace(std::move(name), std::move(si)); + } + + if (!ifs.good()) { + LLAMA_LOG_WARN("%s: state file truncated or read error, ignoring\n", func); + return {}; + } + + LLAMA_LOG_INFO("\t%s: using %s (data for %zu tensors loaded)\n", func, checkpoint_file.c_str(), out.size()); + return out; + }; + + // Check for interruptions and try save progress + auto throw_if_aborted = [&](const std::vector & all_tensors) { + if (interrupted) { + if (qs.params->state_file) { + if (qs.has_ignored_types) { + LLAMA_LOG_WARN("\n\t%s: interrupted; state checkpoint is not written while --target-exclude is active\n", func); + } else { + LLAMA_LOG_INFO("\n\t%s: interrupted, saving progress for %zu tensors to %s\n", func, all_tensors.size(), checkpoint_file.c_str()); + save_state(all_tensors); + } + } else { + LLAMA_LOG_INFO("\n\t%s: interrupted\n", func); + } + + throw std::runtime_error("interrupted"); + } + }; + + // Quality metrics + struct quant_error { + double error = std::numeric_limits::infinity(); + double mse = 0.0; + double wce = 0.0; + }; + + // Pre-calculated stats for MSE + struct mse_cache { + std::vector row_sq_norm; + }; + + // Pre-calculated stats for WCE + struct wce_cache { + std::vector row_sq_norm; + }; + + // Determine optimization strategy + auto is_angle_sensitive = [](const std::string & name) -> bool { + return name.find("attn_q.weight") != std::string::npos || + name.find("attn_k.weight") != std::string::npos || + name.find("attn_qkv.weight") != std::string::npos || + name.find("attn_q_a.weight") != std::string::npos || + name.find("attn_q_b.weight") != std::string::npos; + }; + + // Tensors sensitive to distortion in dot-product/inner-product calculations (TurboQuant) + auto is_inner_product_sensitive = [](const std::string & name) -> bool { + // Query/Key and variants (fused, latent, and enc/dec) + if (name.find("attn_q") != std::string::npos || name.find("attn_k") != std::string::npos) { return true; } + // Attention Output and variants (standard, enc/dec, cross-attn) + if (name.find("attn_o") != std::string::npos) { return true; } + // Value and variants + if (name.find("attn_v") != std::string::npos) { return true; } + + return false; + }; + + // Estimate error for a given type using a sampled subset of rows + auto compute_quant_error = [&]( + const ggml_tensor * t, + const ggml_type quant_type, + const std::vector & f32_sample, + const std::vector & rows_sample, + const float * values_sample, + const float * activations_sample, + std::vector & quantized_buffer, + std::vector & dequantized_buffer, + const wce_cache * ref_wce = nullptr, + const mse_cache * ref_mse = nullptr, + const float * values_winsorized = nullptr + ) -> quant_error + { + const int64_t n_per_row = t->ne[0]; + const int64_t ne2 = t->ne[2] > 0 ? t->ne[2] : 1; + const size_t sample_elems = f32_sample.size(); + const size_t sample_rows = n_per_row > 0 ? sample_elems / (size_t)n_per_row : 0; + + quant_error qe; + if (sample_rows == 0) { + qe.error = 0.0; + return qe; + } + + const size_t row_sz = ggml_row_size(quant_type, n_per_row); + constexpr size_t SAFETY_PADDING = 256; + if (quantized_buffer.size() < row_sz + SAFETY_PADDING) { quantized_buffer.resize(row_sz + SAFETY_PADDING); } + if (dequantized_buffer.size() < (size_t)n_per_row) { dequantized_buffer.resize((size_t)n_per_row); } + + const ggml_type_traits * traits = ggml_get_type_traits(quant_type); + if (!traits || !traits->to_float) { return qe; } + + auto quant_dequant_row = [&](const float * src, float * dst, const float * v) { + ggml_quantize_chunk(quant_type, src, quantized_buffer.data(), 0, 1, n_per_row, v); + if (quant_type == GGML_TYPE_F16) { ggml_fp16_to_fp32_row((const ggml_fp16_t *)quantized_buffer.data(), dst, (int)n_per_row); } + else if (quant_type == GGML_TYPE_BF16) { ggml_bf16_to_fp32_row((const ggml_bf16_t *)quantized_buffer.data(), dst, (int)n_per_row); } + else { traits->to_float(quantized_buffer.data(), dst, (int)n_per_row); } + }; + + const bool has_vals = values_sample != nullptr; + const bool has_acts = activations_sample != nullptr; + const bool use_wce = has_acts && has_vals && is_angle_sensitive(t->name); + const float * valw = values_winsorized ? values_winsorized : values_sample; + + // Sampled stats for MSE + std::vector local_row_sq_norm; + const std::vector * ptr_row_sq_norm = nullptr; + + // Setup reference stats pointers for MSE + if (!use_wce) { + if (ref_mse) { + ptr_row_sq_norm = & ref_mse->row_sq_norm; + } else { + local_row_sq_norm.reserve(sample_rows); + size_t off = 0; + for (int64_t s = 0; s < ne2; ++s) { + const int64_t rs = rows_sample[s]; + const float * val = has_vals ? valw + s * n_per_row : nullptr; + const float * act = has_acts ? activations_sample + s * n_per_row : nullptr; + for (int64_t r = 0; r < rs; ++r) { + const float * x = f32_sample.data() + off; + double sum = 0.0; + double bias_sum = 0.0; + if (val && act) { + for (int64_t j = 0; j < n_per_row; ++j) { + const double act_j = act[j]; + const double variance = std::max(0.0, (double)val[j] - act_j * act_j); + sum += variance * x[j] * x[j]; + bias_sum += act_j * x[j]; + } + sum += bias_sum * bias_sum; + } else if (val) { + for (int64_t j = 0; j < n_per_row; ++j) { sum += std::max(0.0f, val[j]) * x[j] * x[j]; } + } else { + for (int64_t j = 0; j < n_per_row; ++j) { sum += x[j] * x[j]; } + } + + local_row_sq_norm.push_back(sum); + off += (size_t)n_per_row; + } + } + + ptr_row_sq_norm = & local_row_sq_norm; + } + } + + // Helper for trimmed mean + auto trimmed_mean = [](std::vector & v) -> double { + const auto n = v.size(); + if (n == 0) { return 0.0; } + if (n < 100) { return std::accumulate(v.begin(), v.end(), 0.0) / (double)n; } + const auto k = (size_t)((double)n * 0.01); // trim 1% from each end + std::nth_element(v.begin(), v.begin() + k, v.end()); + std::nth_element(v.begin() + k, v.end() - k, v.end()); + return std::accumulate(v.begin() + k, v.end() - k, 0.0) / std::max(1.0, (double)(n - 2 * k)); + }; + + // Weighted Cosine Error (WCE) + if (use_wce) { + double total_cos_error = 0.0; + size_t off = 0; + size_t sample_idx = 0; + + const std::vector * cached_norm_x = ref_wce && !ref_wce->row_sq_norm.empty() ? & ref_wce->row_sq_norm : nullptr; + + for (int64_t s = 0; s < ne2; ++s) { + const int64_t rs = rows_sample[s]; + if (rs == 0) { continue; } + + const float * v = values_sample + s * n_per_row; + const float * vw = valw + s * n_per_row; + double slice_sum = 0.0; + + for (int64_t r = 0; r < rs; ++r, ++sample_idx) { + const float * wx = f32_sample.data() + off; + float * wy = dequantized_buffer.data(); + quant_dequant_row(wx, wy, v); + + double dot = 0.0; + double ny = 0.0; + double nx = 0.0; + const bool calc_nx = !cached_norm_x; + + if (calc_nx) { + for (int64_t j = 0; j < n_per_row; ++j) { + const double w = std::max(0.0f, vw[j]); + const double xj = wx[j]; + const double yj = wy[j]; + const double yw = yj * w; + dot += xj * yw; + ny += yj * yw; + nx += xj * xj * w; + } + } else { + nx = (* cached_norm_x)[sample_idx]; + for (int64_t j = 0; j < n_per_row; ++j) { + const double w = std::max(0.0f, vw[j]); + const double yj = wy[j]; + const double yw = yj * w; + dot += (double) wx[j] * yw; + ny += yj * yw; + } + } + + // Cosine Distance + double cos_sim; + const double norm_prod = nx * ny; + + if (norm_prod <= EPSILON) { cos_sim = nx <= EPSILON && ny <= EPSILON ? 1.0 : 0.0; } + else { cos_sim = dot / std::sqrt(norm_prod); } + + if (cos_sim > 1.0) { cos_sim = 1.0; } + else if (cos_sim < -1.0) { cos_sim = -1.0; } + + slice_sum += 1.0 - cos_sim; + off += (size_t) n_per_row; + } + + const double nrows = t->ne[1]; + total_cos_error += slice_sum / (double)rs * (double)nrows; + } + + qe.wce = total_cos_error; + qe.error = qe.wce; + return qe; + } + + // Expected Output Error MSE (EOE-MSE) + size_t off = 0; + size_t row_idx = 0; + double total_wmse = 0.0; + + for (int64_t s = 0; s < ne2; ++s) { + const int64_t rs = rows_sample[s]; + if (rs == 0) { continue; } + + const float * val = has_vals ? values_sample + s * n_per_row : nullptr; + const float * mval = has_vals ? valw + s * n_per_row : nullptr; + const float * act = has_acts ? activations_sample + s * n_per_row : nullptr; + + std::vector slice_mse_norm; + slice_mse_norm.reserve(rs); + + for (int64_t r = 0; r < rs; ++r, ++row_idx) { + const float * x = f32_sample.data() + off; + float * y = dequantized_buffer.data(); + quant_dequant_row(x, y, val); + + double w_err = 0.0; + double bias_num = 0.0; + + if (mval && act) { + for (int64_t j = 0; j < n_per_row; ++j) { + const double w = std::max(0.0f, mval[j]); + const double a = act[j]; + const double e = (double)y[j] - (double)x[j]; + w_err += w * e * e; + bias_num += a * e; + } + w_err += bias_num * bias_num; + } else if (mval) { + for (int64_t j = 0; j < n_per_row; ++j) { + const double w = std::max(0.0f, mval[j]); + const double e = (double)y[j] - (double)x[j]; + w_err += w * e * e; + } + } else { + for (int64_t j = 0; j < n_per_row; ++j) { + const double e = (double)y[j] - (double)x[j]; + w_err += e * e; + } + } + + const double rsn = (* ptr_row_sq_norm)[row_idx]; + const double m_norm = rsn > EPSILON ? w_err / rsn : 0.0; + slice_mse_norm.push_back(std::isfinite(m_norm) ? m_norm : INFINITE); + + off += (size_t)n_per_row; + } + + const int64_t nrows = t->ne[1]; + const double slice_mean_mse = trimmed_mean(slice_mse_norm) * (double)nrows; + + total_wmse += slice_mean_mse; + } + + qe.mse = total_wmse; + qe.error = total_wmse; + return qe; + }; + + std::unordered_map bpw_data; + if (qs.params->state_file && !checkpoint_file.empty()) { bpw_data = load_state(); } + + auto has_side_data = [&](const auto * m, const std::string & name, const int64_t n2, const int64_t n_per_row) { + if (!m) { return false; } + auto it = m->find(name); + if (it == m->end()) { return false; } + const size_t req = (size_t) n2 * (size_t) n_per_row; + const size_t sz = it->second.size(); + return sz == req || sz == (size_t) n_per_row; + }; + + // Look up stats used by CNIF + enum { ENERGY, H_NORM, L2_DIST, COSSIM, PCC, N_STATS }; + const char * stat_names[N_STATS] = { "sum_sq", "h_norm", "l2_dist", "cossim", "pearson" }; + size_t stat_pos[N_STATS] = {}; + size_t min_stats = 0; + bool use_cnif = statistics_data && !statistics_data->empty(); + for (int i = 0; use_cnif && i < N_STATS; ++i) { + const size_t n = stats_schema ? stats_schema->size() : 0; + size_t p = 0; + while (p < n && (* stats_schema)[p] != stat_names[i]) { ++p; } + if (p == n) { + LLAMA_LOG_WARN("%s: statistics have no %s metric, skipping CNIF; model quality may be compromised\n", func, stat_names[i]); + use_cnif = false; + } + stat_pos[i] = p; + min_stats = std::max(min_stats, p + 1); + } + + // Precompute the Centered‑Normalized Importance Factor (CNIF) + std::unordered_map cnif_scores; + if (use_cnif) { + struct tensor_score { + std::string name; + float score = 0.0f; + }; + + auto corr_error = [](float x) { + if (!std::isfinite(x)) { return 0.0f; } + return 1.0f - std::abs(std::clamp(x, -1.0f, 1.0f)); + }; + + auto sort_scores = [](std::vector & scores) { + std::sort(scores.begin(), scores.end(), [](const tensor_score & a, const tensor_score & b) { + return a.score < b.score || (a.score == b.score && a.name < b.name); + }); + }; + + auto median = [](const auto & values, auto get_value) { + const size_t mid = values.size() / 2; + if (values.size() % 2 != 0) { return get_value(values[mid]); } + return 0.5f * (get_value(values[mid - 1]) + get_value(values[mid])); + }; + + auto rank = [&](std::vector & scores, const float beta) { + if (scores.empty()) { return; } + + sort_scores(scores); + + if (scores.size() == 1) { + cnif_scores[scores[0].name] = 1.0f; + return; + } + + for (size_t i = 0; i < scores.size();) { + size_t j = i + 1; + while (j < scores.size() && std::abs(scores[j].score - scores[i].score) <= 1e-6f) { ++j; } + + const float p = 0.5f * (float)(i + j - 1) / (float)(scores.size() - 1); + const float scale = std::exp(beta * (2.0f * p - 1.0f)); + for (size_t k = i; k < j; ++k) { cnif_scores[scores[k].name] = scale; } + i = j; + } + }; + + auto cnif = [&](std::vector & scores, const float beta) { + constexpr size_t min_scores = 8; + constexpr float eps = 1e-6f; + constexpr float mad_factor = 1.4826f; // Median Absolute Deviation estimator for normal distributions + + if (scores.size() < min_scores) { + rank(scores, beta); + return; + } + + sort_scores(scores); + + const float med = median(scores, [](const tensor_score & s) { return s.score; }); + std::vector deviations; + deviations.reserve(scores.size()); + for (const auto & score : scores) { deviations.push_back(std::abs(score.score - med)); } + + std::sort(deviations.begin(), deviations.end()); + const float mad = median(deviations, [](float x) { return x; }); + if (mad <= eps) { + rank(scores, beta); + return; + } + + const float inv_scale = 1.0f / (mad_factor * mad + eps); + for (const auto & score : scores) { + const float z = std::clamp((score.score - med) * inv_scale, -4.0f, 4.0f); + cnif_scores[score.name] = std::exp(beta * std::tanh(0.8f * z)); + } + }; + + std::vector mse_scores; + std::vector wce_scores; + mse_scores.reserve(tensors.size()); + wce_scores.reserve(tensors.size()); + cnif_scores.reserve(tensors.size()); + + for (const auto * tw : tensors) { + const ggml_tensor * tensor = tw->tensor; + if (!can_quantize(tensor)) { continue; } + + const std::string name = remap_imatrix(ggml_get_name(tensor), mapped); + auto it = statistics_data->find(name); + if (it == statistics_data->end() || it->second.size() < min_stats) { continue; } + + // Heads have no previous-layer counterpart so they stay outside the pool at cnif = 1.0 + if (tensor_name_match_token_embd(ggml_get_name(tensor)) || tensor_name_match_output_weight(ggml_get_name(tensor))) { continue; } + + const auto & ts = it->second; + const float h_norm = std::isfinite(ts[stat_pos[H_NORM]]) ? std::clamp(ts[stat_pos[H_NORM]], 0.0f, 100.0f) : 100.0f; + const float concentration = 1.0f - h_norm / 100.0f; + const float energy = std::isfinite(ts[stat_pos[ENERGY]]) ? std::max(0.0f, ts[stat_pos[ENERGY]]) : 0.0f; + const float l2_dist = std::isfinite(ts[stat_pos[L2_DIST]]) ? std::max(0.0f, ts[stat_pos[L2_DIST]]) : 0.0f; + const float rel_l2 = l2_dist / (std::sqrt(energy) + EPSILON); + const float density = rel_l2 / (1.0f + rel_l2); + const float fragility = 0.5f * (corr_error(ts[stat_pos[COSSIM]]) + corr_error(ts[stat_pos[PCC]])); + + const int64_t n_per_row = tensor->ne[0]; + const int64_t ne2 = tensor->ne[2] > 0 ? tensor->ne[2] : 1; + const bool has_vals = has_side_data(values_data, name, ne2, n_per_row); + const bool has_acts = has_side_data(activations_data, name, ne2, n_per_row); + const bool use_wce = has_vals && has_acts && is_angle_sensitive(name); + + // parameters tuned for better results at low bitrates (<= 4.5 bits) + const float score = use_wce + ? 0.75f * concentration + 0.15f * density + 0.10f * fragility + : 0.40f * concentration + 0.35f * density + 0.25f * fragility; + + auto & scores = use_wce ? wce_scores : mse_scores; + scores.push_back({ name, score }); + } + + cnif(mse_scores, 0.40f); + cnif(wce_scores, 0.25f); + } + + // Outlier mitigation (simulate TurboQuant rotation) + auto outlier_smoothing = [&](const std::vector& src, std::vector& dst, const int64_t n_rows, const int64_t len) { + dst.resize(src.size()); + for (int64_t r = 0; r < n_rows; ++r) { + const float* src_row = src.data() + r * len; + float* dst_row = dst.data() + r * len; + + // Fast variance estimation + double mean_d = 0.0; + double M2 = 0.0; + for (int64_t i = 0; i < len; ++i) { + double delta = src_row[i] - mean_d; + mean_d += delta / (i + 1); + M2 += delta * (src_row[i] - mean_d); + } + + const float mean = mean_d; + float variance = M2 / len; + const float std_dev = std::sqrt(std::max(0.0f, variance)); + + // Clip at 4 standard deviations to simulate the effect of rotation spreading the outlier energy + float clip_val = 4.0f * std_dev; + + if (clip_val > 1e-4f) { + for (int64_t i = 0; i < len; ++i) { dst_row[i] = std::clamp(src_row[i], mean - clip_val, mean + clip_val); } + } else { + std::memcpy(dst_row, src_row, len * sizeof(float)); + } + } + }; + + // HMT Randomized SVD condition number estimator: kappa = sigma 1 / sigma 20. See https://arxiv.org/abs/0909.4061 + auto randomized_svd_condition_number = [&](const std::vector & f32_sample, const int64_t n_per_row, const int64_t total_rows_sampled) -> float { + constexpr int64_t target_rank = 25; + constexpr int64_t k = 20; // 20th singular value for condition number estimation + constexpr float eps_norm = 1e-8f; + constexpr float eps_eig = EPSILON; + constexpr int jacobi_sweeps = 20; + if (total_rows_sampled < 1 || n_per_row < 1) { return INFINITE; } + + const int64_t m = total_rows_sampled; + const int64_t n = n_per_row; + + // Jacobi eigenvalue decomposition for symmetric matrix + auto jacobi_diag = [&](std::vector & A, const int64_t dim, const int max_sweeps) { + for (int sweep = 0; sweep < max_sweeps; ++sweep) { + bool converged = true; + for (int64_t p = 0; p < dim - 1; ++p) { + for (int64_t q = p + 1; q < dim; ++q) { + const float app = A[p * dim + p]; + const float aqq = A[q * dim + q]; + const float apq = A[p * dim + q]; + if (std::abs(apq) <= eps_eig) { continue; } + converged = false; + + const float tau = (aqq - app) / (2.0f * apq); + const float t = tau >= 0.0f + ? 1.0f / (tau + std::sqrt(1.0f + tau * tau)) + : -1.0f / (-tau + std::sqrt(1.0f + tau * tau)); + const float c = 1.0f / std::sqrt(1.0f + t * t); + const float s = c * t; + + A[p * dim + p] = app - t * apq; + A[q * dim + q] = aqq + t * apq; + A[p * dim + q] = 0.0f; + A[q * dim + p] = 0.0f; + + for (int64_t r = 0; r < dim; ++r) { + if (r == p || r == q) { continue; } + const float arp = A[r * dim + p]; + const float arq = A[r * dim + q]; + A[r * dim + p] = c * arp - s * arq; + A[p * dim + r] = A[r * dim + p]; + A[r * dim + q] = s * arp + c * arq; + A[q * dim + r] = A[r * dim + q]; + } + } + } + + if (converged) { break; } + } + }; + + auto matmul_a = [&]( + const std::vector & A, const int64_t rows_a, + const int64_t cols_a, const std::vector & B, + const int64_t cols_b, std::vector & C + ) + { + C.assign((size_t)rows_a * (size_t)cols_b, 0.0f); + for (int64_t i = 0; i < rows_a; ++i) { + const size_t i_a = (size_t)i * (size_t)cols_a; + const size_t i_c = (size_t)i * (size_t)cols_b; + for (int64_t l = 0; l < cols_a; ++l) { + const float aik = A[i_a + (size_t)l]; + if (aik == 0.0f) { continue; } + const size_t k_b = (size_t)l * (size_t)cols_b; + for (int64_t j = 0; j < cols_b; ++j) { + C[i_c + (size_t)j] += aik * B[k_b + (size_t)j]; + } + } + } + }; + + // C = A^T * B (A is rows_a x cols_a, B is rows_a x cols_b, C is cols_a x cols_b) + auto matmul_b = [&]( + const std::vector & A, + const int64_t rows_a, + const int64_t cols_a, + const std::vector & B, const int64_t cols_b, + std::vector & C + ) + { + C.assign((size_t)cols_a * (size_t)cols_b, 0.0f); + for (int64_t i = 0; i < cols_a; ++i) { + const size_t i_c = (size_t)i * (size_t)cols_b; + for (int64_t l = 0; l < rows_a; ++l) { + const float aki = A[(size_t)l * (size_t)cols_a + (size_t)i]; + if (aki == 0.0f) { continue; } + const size_t k_b = (size_t)l * (size_t)cols_b; + for (int64_t j = 0; j < cols_b; ++j) { + C[i_c + (size_t)j] += aki * B[k_b + (size_t)j]; + } + } + } + }; + + // Modified Gram-Schmidt QR Decomposition. Q gets orthonormal columns from Y (Y is rows x cols) + auto mgs_qr = [&]( + const std::vector & Y, + const int64_t rows, const int64_t cols, + std::vector & Q + ) + { + Q.assign((size_t)rows * (size_t)cols, 0.0f); + std::vector v(rows); + for (int64_t j = 0; j < cols; ++j) { + for (int64_t i = 0; i < rows; ++i) { + v[i] = Y[(size_t)i * (size_t)cols + (size_t)j]; + } + + for (int64_t b = 0; b < j; ++b) { + double dot = 0.0; + for (int64_t i = 0; i < rows; ++i) { + dot += (double)v[i] * (double)Q[(size_t)i * (size_t)cols + (size_t)b]; + } + for (int64_t i = 0; i < rows; ++i) { + v[i] -= (float)dot * Q[(size_t)i * (size_t)cols + (size_t)b]; + } + } + + double norm_sq = 0.0; + for (int64_t i = 0; i < rows; ++i) { + norm_sq += (double)v[i] * (double)v[i]; + } + + const float norm = std::sqrt((float)norm_sq); + if (norm > eps_norm) { + const float inv = 1.0f / norm; + for (int64_t i = 0; i < rows; ++i) { + Q[(size_t)i * (size_t)cols + (size_t)j] = v[i] * inv; + } + } + } + }; + + // Filter and row-normalize valid rows (exclude NaN/Inf and near zero norm rows) + std::vector norm_matrix; + norm_matrix.reserve((size_t)m * (size_t)n); + for (int64_t r = 0; r < m; ++r) { + const float * row = f32_sample.data() + r * n; + double l2_sq = 0.0; + for (int64_t j = 0; j < n; ++j) { + const float val = row[j]; + if (!std::isfinite(val)) { l2_sq = -1.0; break; } + l2_sq += (double)val * (double)val; + } + + if (l2_sq < 0.0) { continue; } + const float l2 = std::sqrt((float)l2_sq); + if (l2 <= eps_norm) { continue; } + const float inv_l2 = 1.0f / l2; + const size_t cur = norm_matrix.size(); + norm_matrix.resize(cur + (size_t)n); + float * dst = norm_matrix.data() + cur; + for (int64_t j = 0; j < n; ++j) { dst[j] = row[j] * inv_l2; } + } + + const int64_t valid_m = (int64_t)norm_matrix.size() / n; + if (valid_m < 2) { return INFINITE; } + const bool hmt_direct = valid_m >= target_rank; + const bool hmt_transpose = !hmt_direct && n >= target_rank; + + // Deterministic random Gaussian projection using Golden Ratio * Random Scrambling Hashing + std::mt19937 rng((uint64_t)(n_per_row * 0x9E3779B97F4A7C15ULL + valid_m * 0xBF58476D1CE4E5B9ULL)); + std::normal_distribution normal(0.0f, 1.0f); + + // Estimate the condition number (kappa) + auto condition_number = [&](const std::vector & eigenvalues) -> float { + if ((int64_t)eigenvalues.size() < k) { return INFINITE; } + const float sigma_max = std::sqrt(std::max(0.0f, eigenvalues[0])); + const float sigma_min = std::sqrt(std::max(0.0f, eigenvalues[k - 1])); + if (sigma_min <= eps_eig) { return INFINITE; } + + return sigma_max / sigma_min; + }; + + if (hmt_direct) { + // HMT on A (valid_m x n) with q=1 power iteration + std::vector Omega((size_t)n * (size_t)target_rank); + for (auto & v : Omega) { v = normal(rng); } + + std::vector Y0; + std::vector Z; + std::vector Y1; + std::vector Q; + std::vector B; + std::vector C; + matmul_a(norm_matrix, valid_m, n, Omega, target_rank, Y0); // Y0 = A * Omega + matmul_b(norm_matrix, valid_m, n, Y0, target_rank, Z); // Z = A^T * Y0 + matmul_a(norm_matrix, valid_m, n, Z, target_rank, Y1); // Y1 = A * Z + mgs_qr(Y1, valid_m, target_rank, Q); + matmul_b(Q, valid_m, target_rank, norm_matrix, n, B); // B = Q^T * A + + // C = B * B^T (target_rank x target_rank) + C.assign((size_t)target_rank * (size_t)target_rank, 0.0f); + for (int64_t i = 0; i < target_rank; ++i) { + for (int64_t j = 0; j < target_rank; ++j) { + double sum = 0.0; + for (int64_t l = 0; l < n; ++l) { + sum += (double)B[(size_t)i * (size_t)n + (size_t)l] * (double)B[(size_t)j * (size_t)n + (size_t)l]; + } + + C[(size_t)i * (size_t)target_rank + (size_t)j] = (float)sum; + } + } + + jacobi_diag(C, target_rank, jacobi_sweeps); + std::vector eigenvalues; + eigenvalues.reserve(target_rank); + for (int64_t i = 0; i < target_rank; ++i) { eigenvalues.push_back(C[i * target_rank + i]); } + std::sort(eigenvalues.begin(), eigenvalues.end(), std::greater()); + + return condition_number(eigenvalues); + } + + if (hmt_transpose) { + // HMT on A^T (n x valid_m) with q=1 power iteration + std::vector Omega((size_t)valid_m * (size_t)target_rank); + for (auto & v : Omega) { v = normal(rng); } + + std::vector Y0; + std::vector Z; + std::vector Y1; + std::vector Q; + std::vector B; + std::vector C; + matmul_b(norm_matrix, valid_m, n, Omega, target_rank, Y0); // Y0 = A^T * Omega + matmul_a(norm_matrix, valid_m, n, Y0, target_rank, Z); // Z = A * Y0 + matmul_b(norm_matrix, valid_m, n, Z, target_rank, Y1); // Y1 = A^T * Z + mgs_qr(Y1, n, target_rank, Q); + + // B = Q^T * A^T (target_rank x valid_m) + B.assign((size_t)target_rank * (size_t)valid_m, 0.0f); + for (int64_t j = 0; j < target_rank; ++j) { + for (int64_t k = 0; k < valid_m; ++k) { + double sum = 0.0; + for (int64_t i = 0; i < n; ++i) { + sum += (double)Q[(size_t)i * (size_t)target_rank + (size_t)j] * (double)norm_matrix[(size_t)k * (size_t)n + (size_t)i]; + } + + B[(size_t)j * (size_t)valid_m + (size_t)k] = (float)sum; + } + } + + // C = B * B^T (target_rank x target_rank) + C.assign((size_t)target_rank * (size_t)target_rank, 0.0f); + for (int64_t i = 0; i < target_rank; ++i) { + for (int64_t j = 0; j < target_rank; ++j) { + double sum = 0.0; + for (int64_t l = 0; l < valid_m; ++l) { + sum += (double)B[(size_t)i * (size_t)valid_m + (size_t)l] * (double)B[(size_t)j * (size_t)valid_m + (size_t)l]; + } + + C[(size_t)i * (size_t)target_rank + (size_t)j] = (float)sum; + } + } + + jacobi_diag(C, target_rank, jacobi_sweeps); + std::vector eigenvalues; + eigenvalues.reserve(target_rank); + for (int64_t i = 0; i < target_rank; ++i) { eigenvalues.push_back(C[i * target_rank + i]); } + std::sort(eigenvalues.begin(), eigenvalues.end(), std::greater()); + + return condition_number(eigenvalues); + } + + // Fallback: full thin SVD via Gram matrix of smaller dimension + Jacobi + const bool gram_rows = valid_m <= n; + if (gram_rows) { + const int64_t gram_dim = valid_m; + std::vector G((size_t)gram_dim * (size_t)gram_dim, 0.0f); + for (int64_t i = 0; i < gram_dim; ++i) { + for (int64_t j = i; j < gram_dim; ++j) { + double sum = 0.0; + for (int64_t l = 0; l < n; ++l) { + sum += (double)norm_matrix[(size_t)i * (size_t)n + (size_t)l] * (double)norm_matrix[(size_t)j * (size_t)n + (size_t)l]; + } + + G[(size_t)i * (size_t)gram_dim + (size_t)j] = (float)sum; + G[(size_t)j * (size_t)gram_dim + (size_t)i] = (float)sum; + } + } + + jacobi_diag(G, gram_dim, jacobi_sweeps); + std::vector eigenvalues; + eigenvalues.reserve(gram_dim); + for (int64_t i = 0; i < gram_dim; ++i) { eigenvalues.push_back(G[i * gram_dim + i]); } + std::sort(eigenvalues.begin(), eigenvalues.end(), std::greater()); + + return condition_number(eigenvalues); + } + + // G = A^T * A (n x n) + const int64_t gram_dim = n; + std::vector G((size_t)gram_dim * (size_t)gram_dim, 0.0f); + for (int64_t i = 0; i < gram_dim; ++i) { + for (int64_t j = i; j < gram_dim; ++j) { + double sum = 0.0; + for (int64_t l = 0; l < valid_m; ++l) { + sum += (double)norm_matrix[(size_t)l * (size_t)n + (size_t)i] * (double)norm_matrix[(size_t)l * (size_t)n + (size_t)j]; + } + + G[(size_t)i * (size_t)gram_dim + (size_t)j] = (float)sum; + G[(size_t)j * (size_t)gram_dim + (size_t)i] = (float)sum; + } + } + + jacobi_diag(G, gram_dim, jacobi_sweeps); + std::vector eigenvalues; + eigenvalues.reserve(gram_dim); + for (int64_t i = 0; i < gram_dim; ++i) { eigenvalues.push_back(G[i * gram_dim + i]); } + std::sort(eigenvalues.begin(), eigenvalues.end(), std::greater()); + + return condition_number(eigenvalues); + }; + + // Map [1, ∞) to [1, M]; alpha controls mapping aggressiveness towards M + auto squash_kappa = [](float kappa) -> float { + constexpr float M = 5.0f; + constexpr float alpha = 0.15f; + if (!std::isfinite(kappa)) { return M; } + + return 1.0f + (M - 1.0f) * std::tanh(alpha * std::log(kappa)); + }; + + // Parallelize tensor processing (courtesy of https://github.com/ddh0) + const int n_workers = std::max(1, std::min(nthread, (int) tensors.size())); + const size_t max_buf_worker = std::max(1, (qs.params->max_buf_size ? qs.params->max_buf_size : LLAMA_QUANT_MAX_BUF_SIZE) / n_workers); + + auto process_tensor = [&]( + const llama_model_loader::llama_tensor_weight * tw, + std::vector> & thread_local_buffer, + std::vector & f32_sample, + std::vector & smoothed_sample, + std::vector & val_cache, + std::vector & act_cache, + std::mutex & loader_mutex, + std::mutex & log_mutex + ) -> std::optional + { + ggml_tensor * tensor = tw->tensor; + struct tensor_guard { + ggml_tensor * t; + void * orig; + ~tensor_guard() { t->data = orig; } + } guard{tensor, tensor->data}; + + const std::string name = ggml_get_name(tensor); + if (poll_interrupt()) { return std::nullopt; } + + const std::string remapped_name = remap_imatrix(name, mapped); + + // Check cache + if (auto tn = bpw_data.find(name); tn != bpw_data.end()) { + type_choice tc; + tc.w = tw; + tc.candidates = tn->second.candidates; + tc.choice = tn->second.choice; + tc.min_bpw = tn->second.min_bpw; + tc.max_bpw = tn->second.max_bpw; + tc.n_elements = tn->second.n_elements ? tn->second.n_elements : (size_t)ggml_nelements(tensor); + // remove ignored types + if (qs.has_ignored_types) { + tc.candidates.erase(std::remove_if(tc.candidates.begin(), tc.candidates.end(), + [&](const type_scores & c) { return c.type >= 0 && c.type < GGML_TYPE_COUNT && qs.ignored_types[c.type]; }), + tc.candidates.end()); + + if (tc.candidates.empty()) { + // locked tensors are exempt + const bool is_locked = locked_tensors && locked_tensors->find(name) != locked_tensors->end(); + if (!is_locked) { + throw std::runtime_error(format("%s: tensor '%s' has %zu quant type candidates left after --target-exclude\n", func, name.c_str(), tc.candidates.size())); + } + + type_scores fb; + fb.type = tensor->type; + fb.bytes = ggml_nbytes(tensor); + fb.bpw = fb.bytes * 8.0f / tc.n_elements; + tc.candidates.push_back(fb); + } + + tc.choice = 0; + } + + return tc; + } + + { + std::lock_guard lock(log_mutex); + LLAMA_LOG_INFO("\t%s: - processing tensor %45s \t(%12" PRId64 " elements)\n", func, name.c_str(), ggml_nelements(tensor)); + } + + const size_t tensor_nbytes = ggml_nbytes(tensor); + const size_t row_nbytes = ggml_row_size(tensor->type, tensor->ne[0]); + const bool stream_rows = !ml.use_mmap && tensor_nbytes > max_buf_worker; + + if (!stream_rows) { + if (!ml.use_mmap && thread_local_buffer.size() < tensor_nbytes) { thread_local_buffer.resize(tensor_nbytes); } + std::lock_guard lock(loader_mutex); + tensor->data = const_cast(ml.load_data_range(*tw, 0, tensor_nbytes, thread_local_buffer.data())); + } else if (thread_local_buffer.size() < row_nbytes) { + thread_local_buffer.resize(row_nbytes); + } + + auto load_row = [&](const int64_t slice, const int64_t row) -> const uint8_t * { + const size_t offs = ((size_t) slice*tensor->ne[1] + row) * row_nbytes; + if (!stream_rows) { return (const uint8_t *) tensor->data + offs; } + std::lock_guard lock(loader_mutex); + return (const uint8_t *) ml.load_data_range(*tw, offs, row_nbytes, thread_local_buffer.data()); + }; + + // Sampling + const int64_t n_per_row = tensor->ne[0]; + const int64_t nrows_total = tensor->ne[1]; + const int64_t ne2 = tensor->ne[2] > 0 ? tensor->ne[2] : 1; + + // Compute rows based on tensor shape and slice count + auto sample_count = [&](const int64_t n, const int64_t rows, const int64_t n2, const bool has_acts) { + constexpr double k_scale = 1.0; + const double tensor_budget = (has_acts ? 1.0 : 0.5) * k_scale * 1024.0 * 1024.0; + const double scale = std::clamp(std::sqrt(std::max(1.0, (double)rows) / 4096.0), 0.5, 2.0); // more rows for large tensors + const double slice_budget = tensor_budget * scale / std::max(1, n2); + const int64_t min_r = (has_acts ? 512 : 256) * (int64_t)k_scale; + const int64_t max_r = 4096 * (int64_t)k_scale; + int64_t tr = std::llround(slice_budget / std::max(1, n)); + tr = std::max(min_r, std::min(tr, std::min(rows, max_r))); + if (rows <= min_r * 2) { tr = rows; } + return tr; + }; + + const int64_t rows_to_sample = sample_count(n_per_row, nrows_total, ne2, activations_data != nullptr); + f32_sample.clear(); + f32_sample.reserve((size_t)ne2 * (size_t)std::min(nrows_total, rows_to_sample) * (size_t)n_per_row); + std::vector rows_sample(ne2, 0); + + // Populate f32_sample + { + const ggml_type src_type = tensor->type; + const ggml_type_traits * traits = ggml_get_type_traits(src_type); + + for (int64_t slice = 0; slice < ne2; ++slice) { + std::mt19937 rng(djb2_hash((const uint8_t*)name.data(), name.size()) ^ HASH_MAGIC ^ slice); + const int64_t limit = std::max(1, std::min(nrows_total, rows_to_sample)); + const double stride = (double)nrows_total / limit; + int64_t offset = stride > 1.0 ? std::uniform_int_distribution(0, (int64_t)stride - 1)(rng) : 0; + + int64_t count = 0; + for (int64_t i = 0; i < limit; ++i) { + int64_t r = offset + std::llround(i * stride); + if (r >= nrows_total) { break; } + + const uint8_t * src = load_row(slice, r); + size_t cur_sz = f32_sample.size(); + f32_sample.resize(cur_sz + n_per_row); + float * dst = f32_sample.data() + cur_sz; + + if (src_type == GGML_TYPE_F32) { std::memcpy(dst, src, n_per_row * sizeof(float)); } + else if (src_type == GGML_TYPE_F16) { ggml_fp16_to_fp32_row((const ggml_fp16_t*)src, dst, (int)n_per_row); } + else if (src_type == GGML_TYPE_BF16) { ggml_bf16_to_fp32_row((const ggml_bf16_t*)src, dst, (int)n_per_row); } + else if (traits && traits->to_float) { traits->to_float(src, dst, (int)n_per_row); } + else { throw std::runtime_error(format("unsupported source type %s for sampling", ggml_type_name(src_type))); } + + ++count; + } + + rows_sample[slice] = count; + } + } + + smoothed_sample.clear(); + bool is_outlier_heavy = remapped_name.find("ffn_down") != std::string::npos; + if (is_outlier_heavy) { outlier_smoothing(f32_sample, smoothed_sample, rows_to_sample * ne2, n_per_row); } + + // Prepare side data + auto get_side_data = [&](const auto * m) { + if (!m) { return std::pair{nullptr, 0}; } + auto it = m->find(remapped_name); + return it != m->end() ? std::pair{it->second.data(), it->second.size()} : std::pair{nullptr, 0}; + }; + + auto [val_ptr, val_sz] = get_side_data(values_data); + auto [act_ptr, act_sz] = get_side_data(activations_data); + + // Cache WCE stats per tensor + const float * val_vec_ptr = nullptr; + const float * act_vec_ptr = nullptr; + + auto prepare_broadcast = [&](const float* src, size_t sz, std::vector& storage, const float*& out_ptr) { + if (!src) { + out_ptr = nullptr; + return; + } + size_t req = (size_t)ne2 * n_per_row; + if (sz == req) { out_ptr = src; } + else if (sz == (size_t)n_per_row) { + storage.resize(req); + for (int s = 0; s < ne2; ++s) { std::memcpy(storage.data() + s * n_per_row, src, n_per_row * sizeof(float)); } + out_ptr = storage.data(); + } else { + std::lock_guard lock(log_mutex); + out_ptr = nullptr; + LLAMA_LOG_WARN("%s: side data mismatch for %s\n", func, name.c_str()); + } + }; + + prepare_broadcast(val_ptr, val_sz, val_cache, val_vec_ptr); + prepare_broadcast(act_ptr, act_sz, act_cache, act_vec_ptr); + + // Cap (winsorize) each row-slice at exp(med + 4 * 1.4826 * mad) of ln(val) to reduce noise and prevent skewness + // Activation-side equivalent of the ±4 sigma weight clip in outlier_smoothing + std::vector val_metric; + const float * ptr_val_metric = nullptr; + if (val_vec_ptr) { + val_metric.assign(val_vec_ptr, val_vec_ptr + (size_t)ne2 * n_per_row); + std::vector scratch; + for (int64_t s = 0; s < ne2; ++s) { + const float * vrow = val_vec_ptr + s * n_per_row; + scratch.clear(); + for (int64_t j = 0; j < n_per_row; ++j) { + const float v = vrow[j]; + if (v > 0.0f) { scratch.push_back(std::log(v)); } + } + + if (scratch.size() < 8 || scratch.size() < (size_t)n_per_row / 2) { continue; } // too few positive entries; leave untouched + auto mid = scratch.begin() + scratch.size() / 2; + std::nth_element(scratch.begin(), mid, scratch.end()); + const float med = * mid; + for (auto & d : scratch) { d = std::fabs(d - med); } + std::nth_element(scratch.begin(), mid, scratch.end()); + const float mad = * mid; + if (mad <= 1e-6f * std::max(1.0f, std::fabs(med))) { continue; } // abnormal row stats: leave untouched + const float cap = std::exp(med + 4.0f * 1.4826f * mad); + float * dst = val_metric.data() + s * n_per_row; + float row_max = -INFINITY; + for (int64_t j = 0; j < n_per_row; ++j) { + row_max = std::max(row_max, dst[j]); + dst[j] = std::min(dst[j], cap); + } + } + + ptr_val_metric = val_metric.data(); + } + + const bool use_wce = val_vec_ptr && act_vec_ptr && is_angle_sensitive(remapped_name); + + // Precompute WCE reference stats + wce_cache ref_wce; + mse_cache ref_mse; + size_t total_rows_sampled = 0; + for (int64_t r : rows_sample) { total_rows_sampled += r; } + + if (use_wce) { + ref_wce.row_sq_norm.reserve(total_rows_sampled); + size_t off = 0; + for (int64_t s = 0; s < ne2; ++s) { + const int64_t rs = rows_sample[s]; + if (rs == 0) { continue; } + const float * v = ptr_val_metric + s * n_per_row; + for (int64_t r = 0; r < rs; ++r) { + const float * wx = f32_sample.data() + off; + double norm_x = 0.0; + for (int64_t j = 0; j < n_per_row; ++j) { + const double w = v ? std::max(0.0f, v[j]) : 1.0; + norm_x += (double)wx[j] * wx[j] * w; + } + ref_wce.row_sq_norm.push_back(norm_x); + off += n_per_row; + } + } + } else { + // Precompute MSE reference stats + ref_mse.row_sq_norm.reserve(total_rows_sampled); + const bool has_acts = act_vec_ptr != nullptr; + const bool has_vals = val_vec_ptr != nullptr; + + size_t off = 0; + for (int64_t s = 0; s < ne2; ++s) { + const int64_t rs = rows_sample[s]; + const float * val = has_vals ? ptr_val_metric + s * n_per_row : nullptr; + const float * act = has_acts ? act_vec_ptr + s * n_per_row : nullptr; + for (int64_t r = 0; r < rs; ++r) { + const float * x = f32_sample.data() + off; + double sum = 0.0; + double bias_sum = 0.0; + if (val && act) { + for (int64_t j = 0; j < n_per_row; ++j) { + const double act_j = act[j]; + const double variance = std::max(0.0, (double)val[j] - act_j * act_j); + sum += variance * x[j] * x[j]; + bias_sum += act_j * x[j]; + } + sum += bias_sum * bias_sum; + } else if (val) { + for (int64_t j = 0; j < n_per_row; ++j) { + sum += std::max(0.0f, val[j]) * x[j] * x[j]; + } + } else { + for (int64_t j = 0; j < n_per_row; ++j) { sum += x[j] * x[j]; } + } + + ref_mse.row_sq_norm.push_back(sum); + off += (size_t)n_per_row; + } + } + } + + float kappa_raw = std::numeric_limits::quiet_NaN(); + float kappa_factor = 1.0f; + if (statistics_data && !statistics_data->empty()) { + kappa_raw = randomized_svd_condition_number(f32_sample, n_per_row, (int64_t)total_rows_sampled); + kappa_factor = squash_kappa(kappa_raw); + } + + // Build candidates + std::vector valid_types; + valid_types.reserve(std::size(quant_types)); + size_t max_row_sz = 0; + const bool valid_matrix = val_vec_ptr != nullptr; + + for (auto t : quant_types) { + if (is_iq(t) && !valid_matrix) { continue; } + if (qs.ignored_types[t]) { continue; } + ggml_type compat = make_compatible(tensor, t); + if (qs.ignored_types[compat]) { continue; } + if (!is_compatible(tensor, compat)) { continue; } + valid_types.push_back(compat); + max_row_sz = std::max(max_row_sz, ggml_row_size(compat, n_per_row)); + } + + std::sort(valid_types.begin(), valid_types.end()); + valid_types.erase(std::unique(valid_types.begin(), valid_types.end()), valid_types.end()); + + // Evaluate candidates + std::vector evaluations; + evaluations.reserve(valid_types.size()); + std::vector q_buf; + std::vector dq_buf; + if (total_rows_sampled > 0 && max_row_sz > 0) { + q_buf.reserve(max_row_sz + 256); // safety padding + dq_buf.reserve(n_per_row); + } + + float cnif_score = 1.0f; + if (auto it = cnif_scores.find(remapped_name); it != cnif_scores.end()) { cnif_score = it->second; } + const float scaling_factor = cnif_score * kappa_factor; + const bool ip_sensitive = is_inner_product_sensitive(remapped_name); + + std::vector raw_errors; + raw_errors.reserve(valid_types.size()); + + for (ggml_type vt : valid_types) { + if (poll_interrupt()) { return std::nullopt; } + const wce_cache * ptr_ref_wce = use_wce && !ref_wce.row_sq_norm.empty() ? & ref_wce : nullptr; + const mse_cache * ptr_ref_mse = !use_wce && !ref_mse.row_sq_norm.empty() ? & ref_mse : nullptr; + const float bpw = (float)ggml_type_size(vt) * 8.0f / (float)ggml_blck_size(vt); + const std::vector& eval_sample = is_outlier_heavy && bpw < 3.0f ? smoothed_sample : f32_sample; + + quant_error qe = compute_quant_error( + tensor, + vt, + eval_sample, + rows_sample, + val_vec_ptr, + act_vec_ptr, + q_buf, + dq_buf, + ptr_ref_wce, + ptr_ref_mse, + ptr_val_metric + ); + + double error = qe.error; + if (ip_sensitive) { error *= 1.0f + 0.5f * std::pow(2.0f, 3.0f - bpw); } // error adjustment for inner-product sensitive tensors at low bpw + + type_scores candidate; + candidate.type = vt; + candidate.bpw = (float)tensor_bpw(tensor, vt); + candidate.bytes = tensor_bytes(tensor, vt); + candidate.error = error * scaling_factor; + candidate.mse = qe.mse; + candidate.wce = qe.wce; + evaluations.push_back(candidate); + raw_errors.push_back(qe.error); + } + + type_choice ch; + ch.w = tw; + ch.n_elements = ggml_nelements(tensor); + + for (const auto & ev : evaluations) { + if (ev.bytes == 0) { continue; } + ch.candidates.push_back(ev); + } + + if (ch.candidates.empty()) { + const bool is_locked = locked_tensors && locked_tensors->find(name) != locked_tensors->end(); + if (qs.has_ignored_types && !is_locked) { + throw std::runtime_error(format("%s: tensor '%s' has %zu quant type candidates left after --target-exclude\n", func, name.c_str(), ch.candidates.size())); + } + + type_scores fb; + fb.type = tensor->type; + fb.bytes = ggml_nbytes(tensor); + fb.bpw = fb.bytes * 8.0f / ch.n_elements; + ch.candidates.push_back(fb); + } + + auto simplify_pareto = [&](std::vector & candidates) { + std::sort(candidates.begin(), candidates.end(), [](const auto& a, const auto& b) { + return a.bytes < b.bytes || (a.bytes == b.bytes && (a.error < b.error || (a.error == b.error && a.type < b.type))); + }); + candidates.erase(std::unique(candidates.begin(), candidates.end(), + [](const auto & a, const auto &b) { return a.bytes == b.bytes; }), candidates.end()); + + std::vector hull; + double min_err = INFINITE; + for(const auto & c : candidates) { + if (c.error < min_err) { + min_err = c.error; + hull.push_back(c); + } + } + candidates = std::move(hull); + + if (candidates.size() < 3) { return; } + std::vector convex; + auto cross = [](const auto& a, const auto& b, const auto& c) { + return ((double)b.bytes - (double)a.bytes) * (c.error - a.error) - ((double)c.bytes - (double)a.bytes) * (b.error - a.error); + }; + + for (const auto & c : candidates) { + while (convex.size() >= 2 && cross(convex[convex.size()-2], convex.back(), c) <= EPSILON) { convex.pop_back(); } + convex.push_back(c); + } + + candidates = std::move(convex); + }; + + simplify_pareto(ch.candidates); + ch.choice = 0; + ch.min_bpw = ch.candidates.front().bpw; + ch.max_bpw = ch.candidates.back().bpw; + return ch; + }; + + std::vector all_tensors; // this vector will be populated by the parallel workers + { + std::atomic idx{0}; + std::mutex m_load; + std::mutex m_log; + std::mutex m_res; + std::exception_ptr w_exception; + std::atomic w_failed{false}; + std::vector threads; + threads.reserve(n_workers); + + for (int i = 0; i < n_workers; ++i) { + threads.emplace_back([&](){ + try { + std::vector> buf; + std::vector f32_sample; + std::vector smoothed_sample; + std::vector val_cache; + std::vector act_cache; + while(true) { + if (w_failed.load(std::memory_order_relaxed) || poll_interrupt()) { break; } + const size_t cur = idx.fetch_add(1); + if (cur >= tensors.size()) { break; } + if (!can_quantize(tensors[cur]->tensor)) { continue; } + + auto res = process_tensor(tensors[cur], buf, f32_sample, smoothed_sample, val_cache, act_cache, m_load, m_log); + if (res) { + std::lock_guard lock(m_res); + all_tensors.push_back(std::move(*res)); + } else { + break; + } + } + } catch (...) { + std::lock_guard lock(m_res); + if (!w_failed.exchange(true)) { + w_exception = std::current_exception(); + } + } + }); + } + + for(auto& t : threads) { t.join(); } + + if (w_exception) { + std::rethrow_exception(w_exception); + } + } + + if (interrupted) { + std::unordered_set reached; + for (const auto & tc : all_tensors) { reached.insert(ggml_get_name(tc.w->tensor)); } + for (const auto * tw : tensors) { + const std::string name = ggml_get_name(tw->tensor); + const auto it = bpw_data.find(name); + if (it == bpw_data.end() || reached.count(name)) { continue; } + type_choice tc = it->second; + tc.w = tw; + all_tensors.push_back(std::move(tc)); + } + } + + throw_if_aborted(all_tensors); + if (qs.params->state_file) { + if (qs.has_ignored_types) { LLAMA_LOG_WARN("\t%s: state checkpoint cannot be saved while --target-exclude is active\n", func); } + else { save_state(all_tensors); } + } + + if (all_tensors.empty()) { return {}; } + + // Compute total elements across all tensors and bytes for non-quantizable tensors + size_t n_elements = 0; + size_t nq_bytes = 0; + for (const auto * it : tensors) { + const ggml_tensor * tensor = it->tensor; + n_elements += (size_t)ggml_nelements(tensor); + if (!can_quantize(tensor)) { nq_bytes += ggml_nbytes(tensor); } + } + + // Exclude user defined tensors (--tensor-type) from the Lagrangian optimization (courtesy of https://github.com/AesSedai) + std::vector pinned_tensors; + if (locked_tensors && !locked_tensors->empty()) { + std::vector variable_tensors; + variable_tensors.reserve(all_tensors.size()); + for (auto & tn : all_tensors) { + const std::string name = ggml_get_name(tn.w->tensor); + auto lt = locked_tensors->find(name); + if (lt != locked_tensors->end()) { + const ggml_type mc = tensor_type_fallback(qs, tn.w->tensor, lt->second); + int idx = -1; + for (int j = 0; j < (int)tn.candidates.size(); ++j) { + if (tn.candidates[j].type == mc) { + idx = j; + break; + } + } + + if (idx == -1) { + // Pinned type was pareto-pruned or not evaluated; add with unknown error + type_scores ts; + ts.type = mc; + ts.bpw = (float)tensor_bpw(tn.w->tensor, mc); + ts.bytes = tensor_bytes(tn.w->tensor, mc); + ts.error = std::numeric_limits::quiet_NaN(); + tn.candidates.push_back(ts); + idx = (int)tn.candidates.size() - 1; + } + + tn.choice = idx; + pinned_tensors.push_back(std::move(tn)); + } else { + variable_tensors.push_back(std::move(tn)); + } + } + + all_tensors = std::move(variable_tensors); + } + + size_t pinned_bytes = 0; + for (const auto & tc : pinned_tensors) { pinned_bytes += tc.candidates[tc.choice].bytes; } + + size_t min_total_bytes = 0; + size_t max_total_bytes = 0; + for (const auto & tn : all_tensors) { + min_total_bytes += tn.candidates.front().bytes; + max_total_bytes += tn.candidates.back().bytes; + } + + size_t total_budget_bytes = 0; + size_t total_fixed_bytes = nq_bytes + pinned_bytes; + if (qs.params->target_size != -1) { + total_fixed_bytes += gguf_get_meta_size(ml.metadata); + total_budget_bytes = (size_t)qs.params->target_size; + } else { + total_budget_bytes = std::llround(qs.params->target_bpw * (double)n_elements / 8.0); + } + + size_t pinned_min_bytes = 0; + for (const auto & tc : pinned_tensors) { pinned_min_bytes += tc.candidates.front().bytes; } + + const size_t min_bytes = total_fixed_bytes + min_total_bytes; + const size_t unpinned_min_bytes = min_bytes - pinned_bytes + pinned_min_bytes; + const bool clamped = total_budget_bytes < min_bytes; + + auto size_str = [&](const size_t bytes) { + return qs.params->target_size != -1 ? format("%zu bytes", bytes) : format("%.4f bpw", (double)bytes * 8.0 / n_elements); + }; + + const std::string requested = qs.params->target_size != -1 ? format("file size %zu", total_budget_bytes) : format("bpw %.4f", qs.params->target_bpw); + size_t budget_bytes = 0; + if (!clamped) { + budget_bytes = total_budget_bytes - total_fixed_bytes; + if (!pinned_tensors.empty() && budget_bytes > max_total_bytes) { + LLAMA_LOG_WARN("\t%s: target %s is not reachable with the pinned tensors (maximum ~%s); clamping to maximum\n", + func, requested.c_str(), size_str(total_fixed_bytes + max_total_bytes).c_str()); + } + } else { + if (total_budget_bytes >= unpinned_min_bytes) { + throw std::runtime_error(format("%s: target %s is not reachable with the pinned tensors (minimum ~%s)", + func, requested.c_str(), size_str(min_bytes).c_str())); + } + + const std::string pinned_min = pinned_tensors.empty() ? "" : format(" (~%s with the pinned tensors)", size_str(min_bytes).c_str()); + LLAMA_LOG_WARN("\t%s: requested %s is smaller than minimum possible model size (~%s); clamping to minimum%s\n", + func, requested.c_str(), size_str(unpinned_min_bytes).c_str(), pinned_min.c_str()); + + budget_bytes = min_total_bytes; + } + + // pins starve the selection process when remaining bpw is below boost_taper + if (!pinned_tensors.empty() && !all_tensors.empty()) { + size_t pinned_elements = 0; + for (const auto & tc : pinned_tensors) { pinned_elements += tc.n_elements; } + size_t rest_elements = 0; + for (const auto & tn : all_tensors) { rest_elements += tn.n_elements; } + + const size_t other_fixed_bytes = total_fixed_bytes - pinned_bytes; + const double shared_bpw = std::max(0.0, 8.0 * ((double)total_budget_bytes - (double)other_fixed_bytes) / (double)(pinned_elements + rest_elements)); + const double rest_bpw = 8.0 * (double)std::min(budget_bytes, max_total_bytes) / (double)rest_elements; + LLAMA_LOG_INFO("\t%s: pinning %zu tensors (%.2f%% of weights) leaves %.4f bpw available for the rest\n", + func, pinned_tensors.size(), 100.0 * pinned_elements / (pinned_elements + rest_elements), rest_bpw); + + if (!clamped && rest_bpw < boost_taper && shared_bpw >= boost_taper) { + LLAMA_LOG_WARN("\t%s: remaining bpw is below the %.1f safety limit; model's quality may be severely compromised\n", func, boost_taper); + } + } + + // Get the types' override + auto build_mix = [&]() -> std::unordered_map { + std::unordered_map quant_mix; + std::unordered_map optimized; + std::unordered_map pinned; + optimized.reserve(all_tensors.size()); + for (const auto & tn : all_tensors) { optimized[ggml_get_name(tn.w->tensor)] = & tn; } + pinned.reserve(pinned_tensors.size()); + for (const auto & tn : pinned_tensors) { pinned[ggml_get_name(tn.w->tensor)] = & tn; } + + LLAMA_LOG_INFO("\t%s: tensor quantization mix:\n", func); + for (const auto * tn : tensors) { + const std::string name = ggml_get_name(tn->tensor); + + auto pd = pinned.find(name); + bool is_pinned = pd != pinned.end(); + const auto * tn_ptr = is_pinned ? pd->second : nullptr; + + if (!tn_ptr) { + auto opt = optimized.find(name); + if (opt != optimized.end()) { tn_ptr = opt->second; } + } + + if (tn_ptr) { + const auto & tp = * tn_ptr; + const auto & choice = tp.candidates[tp.choice]; + + LLAMA_LOG_INFO("\t%s: %45s %s\t%8s, \t%1.4f bpw,\terror: %.4f%s\n", + func, + name.c_str(), + tp.boost > 1.0f ? "⬆︎" : "-", + ggml_type_name(choice.type), + choice.bpw, + choice.error, + is_pinned ? " (pinned)" : ""); + + quant_mix[name] = choice.type; + } + } + + return quant_mix; + }; + + if (budget_bytes <= min_total_bytes) { + for(auto & tn : all_tensors) { tn.choice = 0; } + return build_mix(); + } + if (budget_bytes >= max_total_bytes) { + for(auto & tn : all_tensors) { tn.choice = (int)tn.candidates.size() - 1; } + return build_mix(); + } + + // Certain tensors have a higher impact on model quality, so they get a boost + size_t total_elements = 0; + for (const auto & tn : all_tensors) { total_elements += tn.n_elements; } + const double global_bpw = 8.0 * (double)budget_bytes / (double)total_elements; + for (auto & tn : all_tensors) { + const std::string tensor_name = ggml_get_name(tn.w->tensor); + if (tensor_name.find("ffn_down.weight") != std::string::npos) { + if (global_bpw < boost_taper) { + for (auto & candidate : tn.candidates) { candidate.error *= 1.0 + std::pow(2.0, 3.0 - candidate.bpw); } + } else { + tn.boost = ffn_down_boost; + } + } else if (tensor_name == "output.weight") { + tn.boost = output_boost; + } else if (tensor_name.find("attn_v") != std::string::npos) { + tn.boost = attn_v_boost; + } else if (qs.has_tied_embeddings && tensor_name == "token_embd.weight" && global_bpw >= boost_taper) { + const double embd_share = (double)tn.n_elements / (double)total_elements; + tn.boost = embd_share <= 0.10 ? tied_embd_boost : (float)std::max(1.25, (double)tied_embd_boost * (1.0 - 3.0 * (embd_share - 0.10))); + } + } + + // Minimize error subject to a size target constraint + auto lagrangian_relaxation = [&](const double mu, std::vector & choices, size_t & bytes, double & cost) { + choices.resize(all_tensors.size()); + bytes = 0; + cost = 0.0; + for (size_t i = 0; i < all_tensors.size(); ++i) { + const auto & tn = all_tensors[i]; + const double eff_mu = mu / tn.boost; // boosted tensors get a lower penalty + int best = 0; + for(int j = 1; j < (int)tn.candidates.size(); ++j) { + double lr = (tn.candidates[j].error - tn.candidates[best].error) + eff_mu * ((double)tn.candidates[j].bytes - (double)tn.candidates[best].bytes) * 8.0; + if (lr < -EPSILON || (std::abs(lr) <= EPSILON && tn.candidates[j].bytes < tn.candidates[best].bytes)) { + best = j; + } + } + + choices[i] = best; + bytes += tn.candidates[best].bytes; + cost += tn.candidates[best].error; + } + }; + + // Binary search for mu then greedy upgrade upwards followed by greedy upgrade downwards of any leftover budget + auto run_auction = [&](const size_t budget) { + size_t min_bytes = 0; + size_t max_bytes = 0; + for (const auto & tn : all_tensors) { + min_bytes += tn.candidates.front().bytes; + max_bytes += tn.candidates.back().bytes; + } + + if (budget <= min_bytes) { + for (auto & tn : all_tensors) { tn.choice = 0; } + return; + } + + if (budget >= max_bytes) { + for (auto & tn : all_tensors) { tn.choice = (int)tn.candidates.size() - 1; } + return; + } + + // Binary search for mu + double mu_lo = 0.0; + double mu_hi = 1.0; + std::vector ch_lo; + std::vector ch_hi; + std::vector ch_under; + std::vector ch_over; + size_t bt_lo; + size_t bt_hi; + size_t bt_mid; + double dummy; + + lagrangian_relaxation(mu_lo, ch_lo, bt_lo, dummy); + int safety = 0; + + do { + lagrangian_relaxation(mu_hi, ch_hi, bt_hi, dummy); + if (bt_hi <= budget || bt_hi == std::numeric_limits::max()) { break; } + mu_hi *= 2.0; + } while(++safety < 60); + + double gap_under = INFINITE; + double gap_over = INFINITE; + + for(int i = 0; i < 40; ++i) { + double mu = 0.5 * (mu_lo + mu_hi); + std::vector ch_mid; + double cost_mid = 0.0; + lagrangian_relaxation(mu, ch_mid, bt_mid, cost_mid); + + double gap = std::abs((double)bt_mid - (double)budget); + if (bt_mid > budget) { + mu_lo = mu; + if (gap < gap_over) { + gap_over = gap; + ch_over = ch_mid; + } + } else { + mu_hi = mu; + if (gap < gap_under) { + gap_under = gap; + ch_under = ch_mid; + } + } + } + + if (!ch_under.empty()) { + for(size_t i = 0; i < all_tensors.size(); ++i) { all_tensors[i].choice = ch_under[i]; } + } + else if (!ch_over.empty()) { + for(size_t i = 0; i < all_tensors.size(); ++i) { all_tensors[i].choice = ch_over[i]; } + } + else if (bt_hi <= budget && !ch_hi.empty()) { + for(size_t i = 0; i < all_tensors.size(); ++i) { all_tensors[i].choice = ch_hi[i]; } + } + else { + for(auto& tn : all_tensors) { tn.choice = 0; } + } + + auto current_bytes = [&] { + size_t cb = 0; + for(const auto & tn : all_tensors) { cb += tn.candidates[tn.choice].bytes; } + return cb; + }; + + struct tensor_upgrade { + int index; + int next_choice; + double score; + bool operator<(const tensor_upgrade & other) const { + return score < other.score; + } + }; + + // greedy upwards/downwards upgrades in case there is budget left + auto allocate_remaining = [&] { + size_t cb = current_bytes(); + std::priority_queue queue; + + auto push_next = [&](const int i) { + const auto & tn = all_tensors[i]; + int next = tn.choice + 1; + if (next < (int)tn.candidates.size()) { + const double err = std::max(0.0, tn.candidates[tn.choice].error - tn.candidates[next].error); + auto bytes = (double)(tn.candidates[next].bytes - tn.candidates[tn.choice].bytes); + if (bytes > EPSILON) { + double ratio = err / bytes; + ratio *= tn.boost; // boosted tensors get a higher priority + queue.push({i, next, ratio}); + } + } + }; + + for (size_t i = 0; i < all_tensors.size(); ++i) { push_next((int)i); } + + while (!queue.empty()) { + auto top = queue.top(); + queue.pop(); + + int i = top.index; + int next = top.next_choice; + if (all_tensors[i].choice >= next) { continue; } + + size_t delta_bt = all_tensors[i].candidates[next].bytes - all_tensors[i].candidates[all_tensors[i].choice].bytes; + if (cb + delta_bt <= budget) { + cb += delta_bt; + all_tensors[i].choice = next; + push_next(i); + } + } + }; + + // upwards upgrade + allocate_remaining(); + + // upgrade cannot swap one large for several small so we try downwards too + auto total_cost = [&] { + double cost = 0.0; + for (const auto & tn : all_tensors) { cost += tn.boost * tn.candidates[tn.choice].error; } + return cost; + }; + + std::vector under_choices(all_tensors.size()); + for (size_t i = 0; i < all_tensors.size(); ++i) { under_choices[i] = all_tensors[i].choice; } + const double under_cost = total_cost(); + + const std::vector & over = ch_over.empty() ? ch_lo : ch_over; + for (size_t i = 0; i < all_tensors.size(); ++i) { all_tensors[i].choice = over[i]; } + + // drop the step with the least boosted error per byte, counting no more bytes than are still over budget + size_t cb = current_bytes(); + while (cb > budget) { + int best = -1; + double best_score = INFINITE; + for (size_t i = 0; i < all_tensors.size(); ++i) { + const auto & tn = all_tensors[i]; + if (tn.choice == 0) { continue; } + const double err = tn.boost * std::max(0.0, tn.candidates[tn.choice - 1].error - tn.candidates[tn.choice].error); + const size_t freed = tn.candidates[tn.choice].bytes - tn.candidates[tn.choice - 1].bytes; + const double score = err / (double)std::min(freed, cb - budget); + if (score < best_score) { + best_score = score; + best = (int)i; + } + } + + if (best < 0) { break; } + auto & tn = all_tensors[best]; + cb -= tn.candidates[tn.choice].bytes - tn.candidates[tn.choice - 1].bytes; + --tn.choice; + } + + allocate_remaining(); + if (current_bytes() > budget || total_cost() >= under_cost * (1.0 - downward_threshold)) { + for (size_t i = 0; i < all_tensors.size(); ++i) { all_tensors[i].choice = under_choices[i]; } + } + }; + + run_auction(budget_bytes); + + // Dense ffn_down cap + if (global_bpw >= boost_taper) { + const std::regex dense_ffn_down("blk\\.[0-9]+\\.ffn_down\\.weight"); + std::vector role; + for (size_t i = 0; i < all_tensors.size(); ++i) { + if (std::regex_match(std::string(ggml_get_name(all_tensors[i].w->tensor)), dense_ffn_down)) { + role.push_back(i); + } + } + + if (role.size() >= 8) { + std::vector role_bpw; + role_bpw.reserve(role.size()); + for (const size_t i : role) { role_bpw.push_back(all_tensors[i].candidates[all_tensors[i].choice].bpw); } + std::sort(role_bpw.begin(), role_bpw.end()); + const size_t mid = role_bpw.size() / 2; + const double median_bpw = role_bpw.size() % 2 ? role_bpw[mid] : 0.5 * (role_bpw[mid - 1] + role_bpw[mid]); + + std::vector outlier; + for (const size_t i : role) { + if (median_bpw - (double)all_tensors[i].candidates[all_tensors[i].choice].bpw > 2.0) { outlier.push_back(i); } + } + + if (!outlier.empty()) { + // nominal-bpw tie break: K-quants first, then IQ, then legacy + auto family_rank = [&](const ggml_type gt) { + switch (gt) { + case GGML_TYPE_Q2_K: + case GGML_TYPE_Q3_K: + case GGML_TYPE_Q4_K: + case GGML_TYPE_Q5_K: + case GGML_TYPE_Q6_K: + return 0; + default: + return is_iq(gt) ? 1 : 2; + } + }; + + ggml_type fill = GGML_TYPE_Q8_0; + double fill_bpw = INFINITE; + int fill_rank = 3; + for (const ggml_type t : quant_types) { + if (!ggml_is_quantized(t)) { continue; } + if (qs.ignored_types[t]) { continue; } + const double nominal = (double)ggml_type_size(t) * 8.0 / (double)ggml_blck_size(t); + if (nominal < median_bpw) { continue; } + const int rank = family_rank(t); + if (nominal < fill_bpw || (nominal == fill_bpw && rank < fill_rank)) { + fill = t; + fill_bpw = nominal; + fill_rank = rank; + } + } + + if (fill_bpw == INFINITE && qs.ignored_types[fill]) { + LLAMA_LOG_WARN("\t%s: ffn_down type %s is ignored by --target-exclude, keeping the auto-selected type\n", func, ggml_type_name(fill)); + } else { + size_t locked_bytes = 0; + std::vector remaining; + remaining.reserve(all_tensors.size()); + for (size_t i = 0; i < all_tensors.size(); ++i) { + auto & tn = all_tensors[i]; + if (!std::binary_search(outlier.begin(), outlier.end(), i)) { + remaining.push_back(std::move(tn)); + continue; + } + + const ggml_tensor * tensor = tn.w->tensor; + const ggml_type mc = make_compatible(tensor, fill); + if (qs.ignored_types[mc]) { + // the fill resolution is barred - keep the auction-chosen type + remaining.push_back(std::move(tn)); + continue; + } + int idx = -1; + for (int j = 0; j < (int)tn.candidates.size(); ++j) { + if (tn.candidates[j].type == mc) { idx = j; break; } + } + + if (idx == -1) { + type_scores ts; + ts.type = mc; + ts.bpw = (float)tensor_bpw(tensor, mc); + ts.bytes = tensor_bytes(tensor, mc); + ts.error = std::numeric_limits::quiet_NaN(); + tn.candidates.push_back(ts); + idx = (int)tn.candidates.size() - 1; + } + + tn.choice = idx; + locked_bytes += tn.candidates[idx].bytes; + pinned_tensors.push_back(std::move(tn)); + } + + all_tensors = std::move(remaining); + run_auction(budget_bytes > locked_bytes ? budget_bytes - locked_bytes : 0); + } + } + } + } + + // Expert down-projection cap + if (global_bpw < boost_taper) { + const std::regex expert_ffn_down("blk\\.[0-9]+\\.ffn_down_exps\\.weight"); + const std::regex expert_ffn_gate("blk\\.[0-9]+\\.ffn_gate_exps\\.weight"); + const std::regex expert_ffn_up ("blk\\.[0-9]+\\.ffn_up_exps\\.weight"); + + // Element-weighted mean of the chosen bpw + auto mean_bpw = [&](const std::regex & re, std::vector * members) -> double { + double num = 0.0; + double den = 0.0; + for (size_t i = 0; i < all_tensors.size(); ++i) { + const auto & tn = all_tensors[i]; + if (!std::regex_match(std::string(ggml_get_name(tn.w->tensor)), re)) { continue; } + num += (double)tn.n_elements * (double)tn.candidates[tn.choice].bpw; + den += (double)tn.n_elements; + if (members) { members->push_back(i); } + } + + return den > 0.0 ? num / den : -1.0; + }; + + std::vector role; + std::vector siblings; + const double down_bpw = mean_bpw(expert_ffn_down, &role); + // mean_bpw appends so siblings gets both the gate and the up tensors + const double gate_bpw = mean_bpw(expert_ffn_gate, &siblings); + const double up_bpw = mean_bpw(expert_ffn_up, &siblings); + const double sibling_bpw = std::max(gate_bpw, up_bpw); + std::sort(siblings.begin(), siblings.end()); + if (!role.empty() && sibling_bpw > 0.0 && down_bpw > sibling_bpw) { + std::vector outliers; + for (const size_t i : role) { + if ((double)all_tensors[i].candidates[all_tensors[i].choice].bpw > sibling_bpw) { outliers.push_back(i); } + } + + if (!outliers.empty()) { + size_t locked_bytes = 0; + std::vector remaining; + remaining.reserve(all_tensors.size()); + for (size_t i = 0; i < all_tensors.size(); ++i) { + auto & tn = all_tensors[i]; + if (!std::binary_search(outliers.begin(), outliers.end(), i)) { + if (std::binary_search(siblings.begin(), siblings.end(), i)) { + locked_bytes += tn.candidates[tn.choice].bytes; + pinned_tensors.push_back(std::move(tn)); + continue; + } + + if (std::binary_search(role.begin(), role.end(), i)) { + const ggml_type chosen = tn.candidates[tn.choice].type; + std::vector kept; + kept.reserve(tn.candidates.size()); + for (const auto & c : tn.candidates) { + if ((double)c.bpw <= sibling_bpw) { kept.push_back(c); } + } + + int new_choice = -1; + for (int j = 0; j < (int)kept.size(); ++j) { + if (kept[j].type == chosen) { new_choice = j; break; } + } + + if (new_choice >= 0) { + tn.candidates = std::move(kept); + tn.choice = new_choice; + } + } + + remaining.push_back(std::move(tn)); + continue; + } + + int idx = -1; + for (int j = 0; j < (int)tn.candidates.size(); ++j) { + if ((double)tn.candidates[j].bpw > sibling_bpw) { continue; } + if (idx == -1 || tn.candidates[j].bpw > tn.candidates[idx].bpw) { idx = j; } + } + + if (idx == -1) { + remaining.push_back(std::move(tn)); + continue; + } + + tn.choice = idx; + locked_bytes += tn.candidates[idx].bytes; + pinned_tensors.push_back(std::move(tn)); + } + + all_tensors = std::move(remaining); + run_auction(budget_bytes > locked_bytes ? budget_bytes - locked_bytes : 0); + } + } + } + + return build_mix(); +} + +// imatrix requirement check +static bool tensor_requires_imatrix(const char * tensor_name, const ggml_type dst_type, const llama_ftype ftype) { + if (tensor_name_match_token_embd(tensor_name) || tensor_name_match_output_weight(tensor_name)) { return false; } + switch (dst_type) { + case GGML_TYPE_IQ3_XXS: + case GGML_TYPE_IQ2_XXS: + case GGML_TYPE_IQ2_XS: + case GGML_TYPE_IQ2_S: + case GGML_TYPE_IQ1_M: + case GGML_TYPE_IQ1_S: + return true; + case GGML_TYPE_Q2_K: + // as a general rule, the k-type quantizations don't require imatrix data. + // the only exception is Q2_K tensors that are part of a Q2_K_S file. + return ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S; + default: + return false; + } +} + +// given a file type, get the default tensor type +ggml_type llama_ftype_get_default_type(const llama_ftype ftype) { + switch (ftype) { + case LLAMA_FTYPE_MOSTLY_Q4_0: return GGML_TYPE_Q4_0; + case LLAMA_FTYPE_MOSTLY_Q4_1: return GGML_TYPE_Q4_1; + case LLAMA_FTYPE_MOSTLY_Q5_0: return GGML_TYPE_Q5_0; + case LLAMA_FTYPE_MOSTLY_Q5_1: return GGML_TYPE_Q5_1; + case LLAMA_FTYPE_MOSTLY_Q8_0: return GGML_TYPE_Q8_0; + case LLAMA_FTYPE_MOSTLY_F16: return GGML_TYPE_F16; + case LLAMA_FTYPE_MOSTLY_BF16: return GGML_TYPE_BF16; + case LLAMA_FTYPE_ALL_F32: return GGML_TYPE_F32; + case LLAMA_FTYPE_MOSTLY_Q1_0: return GGML_TYPE_Q1_0; + case LLAMA_FTYPE_MOSTLY_Q2_0: return GGML_TYPE_Q2_0; + + case LLAMA_FTYPE_MOSTLY_MXFP4_MOE: return GGML_TYPE_MXFP4; + + // K-quants + case LLAMA_FTYPE_MOSTLY_Q2_K_S: + case LLAMA_FTYPE_MOSTLY_Q2_K: return GGML_TYPE_Q2_K; + case LLAMA_FTYPE_MOSTLY_IQ3_XS: return GGML_TYPE_IQ3_S; + case LLAMA_FTYPE_MOSTLY_Q3_K_S: + case LLAMA_FTYPE_MOSTLY_Q3_K_M: + case LLAMA_FTYPE_MOSTLY_Q3_K_L: return GGML_TYPE_Q3_K; + case LLAMA_FTYPE_MOSTLY_Q4_K_S: + case LLAMA_FTYPE_MOSTLY_Q4_K_M: return GGML_TYPE_Q4_K; + case LLAMA_FTYPE_MOSTLY_Q5_K_S: + case LLAMA_FTYPE_MOSTLY_Q5_K_M: return GGML_TYPE_Q5_K; + case LLAMA_FTYPE_MOSTLY_Q6_K: return GGML_TYPE_Q6_K; + // Ternary quants + case LLAMA_FTYPE_MOSTLY_TQ1_0: return GGML_TYPE_TQ1_0; + case LLAMA_FTYPE_MOSTLY_TQ2_0: return GGML_TYPE_TQ2_0; + // Lattice and Non-linear quants + case LLAMA_FTYPE_MOSTLY_IQ2_XXS: return GGML_TYPE_IQ2_XXS; + case LLAMA_FTYPE_MOSTLY_IQ2_XS: return GGML_TYPE_IQ2_XS; + case LLAMA_FTYPE_MOSTLY_IQ2_S: return GGML_TYPE_IQ2_XS; + case LLAMA_FTYPE_MOSTLY_IQ2_M: return GGML_TYPE_IQ2_S; + case LLAMA_FTYPE_MOSTLY_IQ3_XXS: return GGML_TYPE_IQ3_XXS; + case LLAMA_FTYPE_MOSTLY_IQ1_S: return GGML_TYPE_IQ1_S; + case LLAMA_FTYPE_MOSTLY_IQ1_M: return GGML_TYPE_IQ1_M; + case LLAMA_FTYPE_MOSTLY_IQ4_NL: return GGML_TYPE_IQ4_NL; + case LLAMA_FTYPE_MOSTLY_IQ4_XS: return GGML_TYPE_IQ4_XS; + case LLAMA_FTYPE_MOSTLY_IQ3_S: + case LLAMA_FTYPE_MOSTLY_IQ3_M: return GGML_TYPE_IQ3_S; + + default: return GGML_TYPE_COUNT; + } +} + +static void init_quantize_state_counters(quantize_state_impl & qs, std::vector & metadata) { + for (auto & tm : metadata) { + tm.category = tensor_get_category(tm.name); + if (category_is_attn_v(tm.category)) { ++qs.n_attention_wv; } + if (tm.category == TENSOR_CATEGORY_OUTPUT) { qs.has_tied_embeddings = false; } + } + + qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)qs.model.hparams.n_layer_all; +} + +// main quantization driver +static void llama_model_quantize_impl(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) { + llama_ftype ftype = params->ftype; + int nthread = params->nthread; + if (nthread <= 0) { nthread = (int)std::thread::hardware_concurrency(); } + + const ggml_type default_type = llama_ftype_get_default_type(ftype); + if (default_type == GGML_TYPE_COUNT) { throw std::runtime_error(format("invalid output file type %d\n", ftype)); } + + // mmap consistently increases speed on Linux, and also increases speed on Windows with + // hot cache. It may cause a slowdown on macOS, possibly related to free memory. +#if defined(__linux__) || defined(_WIN32) + constexpr llama_load_mode load_mode = LLAMA_LOAD_MODE_MMAP; +#else + constexpr llama_load_mode load_mode = LLAMA_LOAD_MODE_NONE; +#endif + + const llama_model_kv_override * kv_overrides = params->kv_overrides; + std::vector splits = {}; + llama_model_loader ml(/*metadata*/ nullptr, /*set_tensor_data*/ nullptr, /*set_tensor_data_ud*/ nullptr, + fname_inp, splits, /*file*/ nullptr, /*load_mode*/ load_mode, /*check_tensors*/ true, /*no_alloc*/ false, /*load_mtp*/ true, kv_overrides, nullptr); + ml.init_mappings(false); // no prefetching auto mparams = llama_model_default_params(); std::unique_ptr model_ptr(llama_model_create(ml, mparams)); @@ -1069,39 +3184,70 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: quantize_state_impl qs(*model, params); - if (params->only_copy) { - ftype = ml.ftype; - } - std::unordered_map> i_data; - const std::unordered_map> * imatrix_data = nullptr; + if (params->only_copy) { ftype = ml.ftype; } + const std::unordered_map> * values_data = nullptr; + const std::unordered_map> * activations_data = nullptr; + const std::unordered_map> * statistics_data = nullptr; + std::unordered_map> vdata; + std::unordered_map> adata; + std::unordered_map> sdata; + const std::vector * stats_schema = nullptr; + std::vector sschema; if (params->imatrix) { - for (const llama_model_imatrix_data * p = params->imatrix; p->name != nullptr; p++) { - i_data.emplace(p->name, std::vector(p->data, p->data + p->size)); + for (const llama_model_imatrix_data * i = params->imatrix; i->name != nullptr; i++) { + vdata.emplace(i->name, std::vector(i->data, i->data + i->size)); } - imatrix_data = & i_data; - if (imatrix_data) { - LLAMA_LOG_INFO("\n%s: have importance matrix data with %d entries\n", - __func__, (int)imatrix_data->size()); + + values_data = & vdata; + if (values_data) { + LLAMA_LOG_INFO("%s: have importance matrix data with %d entries", __func__, (int)values_data->size()); qs.has_imatrix = true; // check imatrix for nans or infs - for (const auto & kv : *imatrix_data) { + for (const auto & kv : * values_data) { for (float f : kv.second) { - if (!std::isfinite(f)) { - throw std::runtime_error(format("imatrix contains non-finite value %f\n", f)); - } + if (!std::isfinite(f)) { throw std::runtime_error(format("imatrix contains non-finite value %f\n", f)); } } } } } + if (params->activations) { + for (const llama_model_imatrix_data * a = params->activations; a->name != nullptr; a++) { + adata.emplace(a->name, std::vector(a->data, a->data + a->size)); + } + + activations_data = & adata; + if (activations_data) { + LLAMA_LOG_INFO(" - %d activations", (int)activations_data->size()); + qs.has_activations = true; + // check activations for nans or infs + for (const auto & kv : * activations_data) { + for (float f : kv.second) { + if (!std::isfinite(f)) { throw std::runtime_error(format("activations contain non-finite value %f\n", f)); } + } + } + } + } + if (params->statistics) { + for (const llama_model_imatrix_data * s = params->statistics; s->name != nullptr; s++) { + sdata.emplace(s->name, std::vector(s->data, s->data + s->size)); + } + if (params->stats_schema) { + for (const char * const * s = params->stats_schema; * s != nullptr; s++) { sschema.emplace_back(* s); } + stats_schema = & sschema; + } + + statistics_data = & sdata; + if (statistics_data) { LLAMA_LOG_INFO(" and %d statistics", (int)statistics_data->size()); + } + } + LLAMA_LOG_INFO("\n"); const size_t align = GGUF_DEFAULT_ALIGNMENT; gguf_context_ptr ctx_out { gguf_init_empty() }; std::vector prune_list = {}; if (params->prune_layers) { - for (const int32_t * p = params->prune_layers; * p != -1; p++) { - prune_list.push_back(* p); - } + for (const int32_t * p = params->prune_layers; * p != -1; p++) { prune_list.push_back(* p); } } // copy the KV pairs from the input file @@ -1115,27 +3261,38 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: gguf_remove_key(ctx_out.get(), ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str()); if (params->kv_overrides) { - for (const llama_model_kv_override * o = params->kv_overrides; o->key[0] != 0; ++o) { - if (o->tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) { - gguf_set_val_f32(ctx_out.get(), o->key, o->val_f64); - } else if (o->tag == LLAMA_KV_OVERRIDE_TYPE_INT) { + for (const llama_model_kv_override * kvo = params->kv_overrides; kvo->key[0] != 0; ++kvo) { + if (kvo->tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) { + gguf_set_val_f32(ctx_out.get(), kvo->key, kvo->val_f64); + } else if (kvo->tag == LLAMA_KV_OVERRIDE_TYPE_INT) { // Setting type to UINT32. See https://github.com/ggml-org/llama.cpp/pull/14182 for context - gguf_set_val_u32(ctx_out.get(), o->key, (uint32_t)std::abs(o->val_i64)); - } else if (o->tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) { - gguf_set_val_bool(ctx_out.get(), o->key, o->val_bool); - } else if (o->tag == LLAMA_KV_OVERRIDE_TYPE_STR) { - gguf_set_val_str(ctx_out.get(), o->key, o->val_str); + gguf_set_val_u32(ctx_out.get(), kvo->key, (uint32_t)std::abs(kvo->val_i64)); + } else if (kvo->tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) { + gguf_set_val_bool(ctx_out.get(), kvo->key, kvo->val_bool); + } else if (kvo->tag == LLAMA_KV_OVERRIDE_TYPE_STR) { + gguf_set_val_str(ctx_out.get(), kvo->key, kvo->val_str); } else { - LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o->key); + LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, kvo->key); } } } + // first layer without its own kv cache + int n_unused_kv_from = -1; + { + uint32_t n_block = 0; + uint32_t n_shared = 0; + ml.get_key(LLM_KV_BLOCK_COUNT, n_block, false); + ml.get_key(LLM_KV_ATTENTION_SHARED_KV_LAYERS, n_shared, false); + if (n_shared > 0 && n_shared <= n_block) { n_unused_kv_from = (int)(n_block - n_shared); } + } + std::map mapped; int blk_id = 0; // make a list of weights std::vector tensors; + std::unordered_set unused_kv_tensors; tensors.reserve(ml.weights_map.size()); for (const auto & it : ml.weights_map) { const std::string remapped_name(remap_layer(it.first, prune_list, mapped, blk_id)); @@ -1143,32 +3300,28 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: LLAMA_LOG_DEBUG("%s: pruning tensor %s\n", __func__, it.first.c_str()); continue; } - if (remapped_name != it.first) { ggml_set_name(it.second.tensor, remapped_name.c_str()); LLAMA_LOG_DEBUG("%s: tensor %s remapped to %s\n", __func__, it.first.c_str(), ggml_get_name(it.second.tensor)); } + if (tensor_name_match_unused_kv(it.first, n_unused_kv_from)) { unused_kv_tensors.insert(remapped_name); } + tensors.push_back(&it.second); } - if (!prune_list.empty()) { - gguf_set_val_u32(ctx_out.get(), ml.llm_kv(LLM_KV_BLOCK_COUNT).c_str(), blk_id); - } + + if (!prune_list.empty()) { gguf_set_val_u32(ctx_out.get(), ml.llm_kv(LLM_KV_BLOCK_COUNT).c_str(), blk_id); } // keep_split requires that the weights are sorted by split index if (params->keep_split) { std::sort(tensors.begin(), tensors.end(), [](const llama_model_loader::llama_tensor_weight * a, const llama_model_loader::llama_tensor_weight * b) { - if (a->idx == b->idx) { - return a->offs < b->offs; - } + if (a->idx == b->idx) { return a->offs < b->offs; } return a->idx < b->idx; }); } // compute tensor metadata once and cache it std::vector metadata(tensors.size()); - for (size_t i = 0; i < tensors.size(); ++i) { - metadata[i].name = ggml_get_name(tensors[i]->tensor); - } + for (size_t i = 0; i < tensors.size(); ++i) { metadata[i].name = ggml_get_name(tensors[i]->tensor); } // initialize quantization state counters and metadata categories init_quantize_state_counters(qs, metadata); @@ -1178,46 +3331,41 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: // Assume split index is continuous if (params->keep_split) { - for (const auto * it : tensors) { - n_split = std::max(uint16_t(it->idx + 1), n_split); - } + for (const auto * it : tensors) { n_split = std::max((uint16_t)(it->idx + 1), n_split); } } + std::vector ctx_outs(n_split); ctx_outs[0] = std::move(ctx_out); // flag for --dry-run bool will_require_imatrix = false; - // // preliminary iteration over all weights - // - for (size_t i = 0; i < tensors.size(); ++i) { const auto * it = tensors[i]; const struct ggml_tensor * tensor = it->tensor; uint16_t i_split = params->keep_split ? it->idx : 0; - if (!ctx_outs[i_split]) { - ctx_outs[i_split].reset(gguf_init_empty()); - } + if (!ctx_outs[i_split]) { ctx_outs[i_split].reset(gguf_init_empty()); } gguf_add_tensor(ctx_outs[i_split].get(), tensor); metadata[i].allows_quantization = tensor_allows_quantization(params, model->arch, tensor); - if (metadata[i].allows_quantization) { - metadata[i].target_type = llama_tensor_get_type(qs, params, tensor, default_type, metadata[i]); - } else { - metadata[i].target_type = tensor->type; + if (metadata[i].allows_quantization) { metadata[i].target_type = llama_tensor_get_type(qs, params, tensor, default_type, metadata[i]); } + else { metadata[i].target_type = tensor->type; } + + if (metadata[i].allows_quantization && unused_kv_tensors.count(metadata[i].name)) { + metadata[i].target_type = tensor_type_fallback(qs, tensor, GGML_TYPE_Q4_0); + LLAMA_LOG_INFO("%s: unused tensor (%s shares an earlier layer's kv cache) - converting to %s\n", + __func__, metadata[i].name.c_str(), ggml_type_name(metadata[i].target_type)); } metadata[i].requires_imatrix = tensor_requires_imatrix(tensor->name, metadata[i].target_type, ftype); - if (params->imatrix) { - metadata[i].remapped_imatrix_name = remap_imatrix(tensor->name, mapped); - } else if (metadata[i].allows_quantization && metadata[i].requires_imatrix) { - if (params->dry_run) { - will_require_imatrix = true; - } else { + if (params->imatrix) { metadata[i].remapped_imatrix_name = remap_imatrix(tensor->name, mapped); } + else if (metadata[i].allows_quantization && metadata[i].requires_imatrix) { + if (params->dry_run) { will_require_imatrix = true; } + else { LLAMA_LOG_ERROR("\n============================================================================\n" " ERROR: this quantization requires an importance matrix!\n" " - offending tensor: %s\n" @@ -1229,6 +3377,22 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: } } + // report missing imatrix coverage early + if (values_data) { + std::vector no_imatrix; + for (size_t i = 0; i < tensors.size(); ++i) { + const char * name = metadata[i].name.c_str(); + if (!metadata[i].allows_quantization || unused_kv_tensors.count(metadata[i].name)) { continue; } + if (tensor_name_match_token_embd(name) || tensor_name_match_output_weight(name)) { continue; } + if (!values_data->count(metadata[i].remapped_imatrix_name)) { no_imatrix.push_back(metadata[i].name); } + } + + if (!no_imatrix.empty()) { + LLAMA_LOG_WARN("%s: %zu quantizable tensors have no imatrix data:\n", __func__, no_imatrix.size()); + for (const auto & name : no_imatrix) { LLAMA_LOG_WARN("%s: %s\n", __func__, name.c_str()); } + } + } + // Set split info if needed if (n_split > 1) { for (size_t i = 0; i < ctx_outs.size(); ++i) { @@ -1250,6 +3414,92 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: const size_t max_buf_size = params->max_buf_size ? params->max_buf_size : LLAMA_QUANT_MAX_BUF_SIZE; + std::unordered_map bpw_overrides = {}; + if ((params->target_bpw != -1.0f || params->target_size != -1) && !params->only_copy) { + if (params->imatrix) { + if (params->pure) { + LLAMA_LOG_WARN("%s: --target-bpw/--target-size specified with --pure, ignoring --pure\n", __func__); + } + if (params->target_size >= 0) { + LLAMA_LOG_INFO("%s: computing tensor quantization mix to achieve file size %.2f MiB\n", __func__, (double)params->target_size / 1024.0 / 1024.0); + } else { + LLAMA_LOG_INFO("%s: computing tensor quantization mix to achieve %.4f bpw\n", __func__, params->target_bpw); + } + + if (qs.has_ignored_types) { + std::string barred; + for (size_t i = 0; i < qs.ignored_types.size(); ++i) { + if (qs.ignored_types[i]) { + if (!barred.empty()) { barred += ", "; } + barred += ggml_type_name((ggml_type)i); + } + } + + LLAMA_LOG_INFO("%s: --target-exclude ignores quant types: %s\n", __func__, barred.c_str()); + + // pinned types have precedence over ignored + for (const auto & p : qs.tensor_type_patterns) { + if (p.type < GGML_TYPE_COUNT && qs.ignored_types[p.type]) { + LLAMA_LOG_WARN("%s: --tensor-type pattern '%s' pins type %s which is ignored by --target-exclude, keeping the pinned type\n", + __func__, p.pattern.c_str(), ggml_type_name(p.type)); + } + } + + const std::pair type_flags[] = { + { "--token-embedding-type", params->token_embedding_type }, + { "--output-tensor-type", params->output_tensor_type }, + }; + for (const auto & [flag, type] : type_flags) { + if (type < GGML_TYPE_COUNT && qs.ignored_types[type]) { + LLAMA_LOG_WARN("%s: %s pins type %s which is ignored by --target-exclude, keeping the pinned type\n", __func__, flag, ggml_type_name(type)); + } + } + } + + // Build tensor type map from --tensor-type + embedding + output flags + std::unordered_map locked_tensors; + for (size_t i = 0; i < tensors.size(); ++i) { + if (!metadata[i].allows_quantization) { continue; } + const char * name = ggml_get_name(tensors[i]->tensor); + ggml_type locked = tensor_type_override_for(qs, name); + if (metadata[i].category == TENSOR_CATEGORY_TOKEN_EMBD) { + const bool named = locked != GGML_TYPE_COUNT && std::strcmp(name, "per_layer_token_embd.weight") == 0; + if (params->token_embedding_type < GGML_TYPE_COUNT && !named) { + locked = params->token_embedding_type; + } else if (locked == GGML_TYPE_COUNT && qs.has_tied_embeddings && params->output_tensor_type < GGML_TYPE_COUNT) { + // tied embeddings take the output type, same as in llama_tensor_get_type_impl + locked = params->output_tensor_type; + } + } else if (metadata[i].category == TENSOR_CATEGORY_OUTPUT && params->output_tensor_type < GGML_TYPE_COUNT) { + locked = params->output_tensor_type; + } + + if (locked != GGML_TYPE_COUNT) { locked_tensors[name] = locked; } + } + + // do not allocate budget to unused kv tensors + for (size_t i = 0; i < tensors.size(); ++i) { + if (metadata[i].allows_quantization && unused_kv_tensors.count(metadata[i].name)) { + locked_tensors[metadata[i].name] = metadata[i].target_type; + } + } + + // get quantization type overrides targeting a given bits per weight budget + const auto * lt = locked_tensors.empty() ? nullptr : & locked_tensors; + bpw_overrides = target_bpw_type(ml, qs, tensors, mapped, values_data, activations_data, statistics_data, stats_schema, lt, nthread); + for (size_t i = 0; i < tensors.size(); ++i) { + const std::string name = ggml_get_name(tensors[i]->tensor); + auto it = bpw_overrides.find(name); + if (it != bpw_overrides.end()) { + metadata[i].target_type = it->second; + metadata[i].requires_imatrix = tensor_requires_imatrix(name.c_str(), metadata[i].target_type, ftype); + } + } + } else { + throw std::runtime_error(format("--target-bpw/--target-size require an imatrix but none was provided\n")); + } + } + int cur_split = -1; std::ofstream fout; auto close_ofstream = [&]() { @@ -1280,15 +3530,11 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: }; // no output file for --dry-run - if (!params->dry_run) { - new_ofstream(0); - } + if (!params->dry_run) { new_ofstream(0); } - // // main loop: iterate over all weights - // - for (size_t i = 0; i < tensors.size(); ++i) { + if (params->abort_callback && params->abort_callback(params->abort_callback_data)) { throw std::runtime_error("interrupted"); } const auto & weight = *tensors[i]; const auto & tm = metadata[i]; ggml_tensor * tensor = weight.tensor; @@ -1309,16 +3555,12 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: }; LLAMA_LOG_INFO("[%4d/%4d] %-36s - [%s], type = %6s, ", - ++idx, ml.n_tensors, - ggml_get_name(tensor), - llama_format_tensor_shape(tensor).c_str(), - ggml_type_name(tensor->type)); + ++idx, ml.n_tensors, ggml_get_name(tensor), llama_format_tensor_shape(tensor).c_str(), ggml_type_name(tensor->type)); const ggml_type cur_type = tensor->type; const ggml_type new_type = tm.target_type; - // If we've decided to quantize to the same type the tensor is already - // in then there's nothing to do. + // If we've decided to quantize to the same type the tensor is already in then there's nothing to do. bool quantize = cur_type != new_type; size_t new_size; @@ -1327,25 +3569,19 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: // the --dry-run option calculates the final quantization size without quantizing if (quantize) { new_size = ggml_nrows(tensor) * ggml_row_size(new_type, tensor->ne[0]); - LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB (%s)\n", - tensor_size/1024.0/1024.0, - new_size/1024.0/1024.0, - ggml_type_name(new_type)); - if (!will_require_imatrix && tm.requires_imatrix) { - will_require_imatrix = true; - } + LLAMA_LOG_INFO("size = %.2f MiB -> %.2f MiB (%s)\n", tensor_size/1024.0/1024.0, new_size/1024.0/1024.0, ggml_type_name(new_type)); + if (!will_require_imatrix && tm.requires_imatrix) { will_require_imatrix = true; } } else { new_size = tensor_size; - LLAMA_LOG_INFO("size = %8.3f MiB\n", new_size/1024.0/1024.0); + LLAMA_LOG_INFO("size = %.2f MiB\n", new_size/1024.0/1024.0); } total_size_org += tensor_size; total_size_new += new_size; - continue; } else { // no --dry-run, perform quantization if (!quantize) { new_size = tensor_size; - LLAMA_LOG_INFO("size = %8.3f MiB\n", tensor_size/1024.0/1024.0); + LLAMA_LOG_INFO("size = %.2f MiB\n", tensor_size/1024.0/1024.0); // copy in slabs of whole rows, so that each slab can be validated const size_t row_size = ggml_row_size(tensor->type, tensor->ne[0]); @@ -1357,16 +3593,16 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: } } else { const float * imatrix = nullptr; - if (imatrix_data) { - auto it = imatrix_data->find(tm.remapped_imatrix_name); - if (it == imatrix_data->end()) { - LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name); + if (values_data) { + auto it = values_data->find(tm.remapped_imatrix_name); + if (it == values_data->end()) { + LLAMA_LOG_INFO("\n====== %s: did not find imatrix data for %s\n", __func__, tensor->name); } else { if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]*tensor->ne[3]) { imatrix = it->second.data(); } else { LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__, - int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]*tensor->ne[3]), tensor->name); + (int)it->second.size(), (int)tensor->ne[0] * (int)tensor->ne[2] * (int)tensor->ne[3], tensor->name); // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix // this is a significant error and it may be good idea to abort the process if this happens, @@ -1374,7 +3610,7 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: // tok_embd should be ignored in this case, since it always causes this warning if (!tensor_name_match_token_embd(tensor->name)) { throw std::runtime_error(format("imatrix size %d is different from tensor size %d for %s", - int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]*tensor->ne[3]), tensor->name)); + (int)it->second.size(), (int)tensor->ne[0] * (int)tensor->ne[2] * (int)tensor->ne[3], tensor->name)); } } } @@ -1391,7 +3627,7 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type))); } - LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type)); + LLAMA_LOG_INFO("converting to %7s ", ggml_type_name(new_type)); fflush(stdout); const int64_t n_per_row = tensor->ne[0]; @@ -1405,7 +3641,7 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: const size_t bytes_per_row = row_size_src + row_size_dst + (tensor->type == GGML_TYPE_F32 ? 0 : n_per_row*sizeof(float)); const int64_t nrows_slab = std::max(1, std::min(nrows_total, max_buf_size/bytes_per_row)); - static const int64_t min_chunk_size = 32 * 512; + static constexpr int64_t min_chunk_size = 32 * 512; const int64_t chunk_size = (n_per_row >= min_chunk_size ? n_per_row : n_per_row * ((min_chunk_size + n_per_row - 1)/n_per_row)); // process rows across all experts in one pass to keep all threads busy @@ -1439,7 +3675,7 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: fout.write((const char *) work.data(), size_cur); new_size += size_cur; } - LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", tensor_size/1024.0/1024.0, new_size/1024.0/1024.0); + LLAMA_LOG_INFO("size = %.2f MiB -> %.2f MiB\n", tensor_size/1024.0/1024.0, new_size/1024.0/1024.0); } total_size_org += tensor_size; total_size_new += new_size; @@ -1453,33 +3689,24 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: // unmap the tensor to free memory if (ml.use_mmap) { ml.unmap_weight(weight); } - - } // no --dry-run - } // main loop - - if (!params->dry_run) { - close_ofstream(); + } } - LLAMA_LOG_INFO("%s: model size = %8.2f MiB (%.2f BPW)\n", __func__, total_size_org/1024.0/1024.0, total_size_org*8.0/ml.n_elements); - LLAMA_LOG_INFO("%s: quant size = %8.2f MiB (%.2f BPW)\n", __func__, total_size_new/1024.0/1024.0, total_size_new*8.0/ml.n_elements); + if (!params->dry_run) { close_ofstream(); } + + LLAMA_LOG_INFO("%s: model size = %8.2f MiB (%7.4f BPW)\n", __func__, total_size_org/1024.0/1024.0, total_size_org*8.0/ml.n_elements); + LLAMA_LOG_INFO("%s: quant size = %8.2f MiB (%7.4f BPW)\n", __func__, total_size_new/1024.0/1024.0, total_size_new*8.0/ml.n_elements); if (!params->imatrix && params->dry_run && will_require_imatrix) { - LLAMA_LOG_WARN("%s: WARNING: dry run completed successfully, but actually completing this quantization will require an imatrix!\n", - __func__ - ); + LLAMA_LOG_WARN("%s: WARNING: dry run completed successfully, but actually completing this quantization will require an imatrix!\n", __func__); } if (qs.n_fallback > 0) { - LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n", - __func__, qs.n_fallback, ml.n_tensors); + LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n", __func__, qs.n_fallback, ml.n_tensors); } } -// // interface implementation -// - llama_model_quantize_params llama_model_quantize_default_params() { llama_model_quantize_params result = { /*.nthread =*/ 0, @@ -1494,21 +3721,26 @@ llama_model_quantize_params llama_model_quantize_default_params() { /*.dry_run =*/ false, /*.imatrix =*/ nullptr, /*.kv_overrides =*/ nullptr, - /*.tensor_type =*/ nullptr, + /*.tt_overrides =*/ nullptr, /*.prune_layers =*/ nullptr, - /*.max_buf_size =*/ LLAMA_QUANT_MAX_BUF_SIZE + /*.max_buf_size =*/ LLAMA_QUANT_MAX_BUF_SIZE, + /*.activations =*/ nullptr, + /*.statistics =*/ nullptr, + /*.stats_schema =*/ nullptr, + /*.target_bpw =*/ -1.0f, + /*.target_size =*/ -1, + /*.state_file =*/ nullptr, + /*.target_exclude =*/ nullptr, + /*.abort_callback =*/ nullptr, + /*.abort_callback_data =*/ nullptr }; return result; } -uint32_t llama_model_quantize( - const char * fname_inp, - const char * fname_out, - const llama_model_quantize_params * params) { - try { - llama_model_quantize_impl(fname_inp, fname_out, params); - } catch (const std::exception & err) { +uint32_t llama_model_quantize(const char * fname_inp, const char * fname_out, const llama_model_quantize_params * params) { + try { llama_model_quantize_impl(fname_inp, fname_out, params); } + catch (const std::exception & err) { LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what()); return 1; } @@ -1516,32 +3748,25 @@ uint32_t llama_model_quantize( return 0; } -// // Helper functions for external tools exposed in llama-ext.h -// - -quantize_state_impl * llama_quant_init( - const llama_model * model, - const llama_model_quantize_params * params) { +quantize_state_impl * llama_quant_init(const llama_model * model, const llama_model_quantize_params * params) { return new quantize_state_impl(*model, params); } -void llama_quant_free(quantize_state_impl * qs) { +void llama_quant_free(const quantize_state_impl * qs) { delete qs; } llama_model * llama_quant_model_from_metadata(const llama_quant_model_desc * desc) { struct llama_model_params mparams = llama_model_default_params(); - auto arch = llm_arch_from_string(desc->architecture); + const auto arch = llm_arch_from_string(desc->architecture); auto * model = llama_model_create(arch, mparams); model->arch = arch; // infer llm_type: only LLM_TYPE_70B matters for quantization logic - if (model->arch == LLM_ARCH_LLAMA && desc->n_layer == 80 && desc->n_head != desc->n_head_kv) { - model->type = LLM_TYPE_70B; - } + if (model->arch == LLM_ARCH_LLAMA && desc->n_layer == 80 && desc->n_head != desc->n_head_kv) { model->type = LLM_TYPE_70B; } - model->hparams.n_embd = desc->n_embd; + model->hparams.n_embd = desc->n_embd; model->hparams.n_embd_head_k_full = desc->n_embd_head_k; model->hparams.n_embd_head_v_full = desc->n_embd_head_v; model->hparams.n_layer_all = desc->n_layer; @@ -1549,44 +3774,41 @@ llama_model * llama_quant_model_from_metadata(const llama_quant_model_desc * des model->hparams.n_expert = desc->n_expert; for (uint32_t i = 0; i < desc->n_layer; i++) { - model->hparams.n_head_arr[i] = desc->n_head; + model->hparams.n_head_arr[i] = desc->n_head; model->hparams.n_head_kv_arr[i] = desc->n_head_kv; - model->hparams.n_ff_arr[i] = desc->n_ff; + model->hparams.n_ff_arr[i] = desc->n_ff; } return model; } -bool llama_quant_tensor_allows_quantization( - const quantize_state_impl * qs, - const ggml_tensor * tensor) { +bool llama_quant_tensor_allows_quantization(const quantize_state_impl * qs, const ggml_tensor * tensor) { return tensor_allows_quantization(qs->params, qs->model.arch, tensor); } void llama_quant_compute_types( - quantize_state_impl * qs, - llama_ftype ftype, - ggml_tensor ** tensors, - ggml_type * result_types, - size_t n_tensors) { + quantize_state_impl * qs, + const llama_ftype ftype, + ggml_tensor ** tensors, + ggml_type * result_types, + const size_t n_tensors +) { // reset per-computation state - qs->n_attention_wv = 0; - qs->n_ffn_down = 0; - qs->n_ffn_gate = 0; - qs->n_ffn_up = 0; - qs->i_attention_wv = 0; - qs->i_ffn_down = 0; - qs->i_ffn_gate = 0; - qs->i_ffn_up = 0; - qs->n_fallback = 0; - qs->has_imatrix = false; + qs->n_attention_wv = 0; + qs->n_ffn_down = 0; + qs->n_ffn_gate = 0; + qs->n_ffn_up = 0; + qs->i_attention_wv = 0; + qs->i_ffn_down = 0; + qs->i_ffn_gate = 0; + qs->i_ffn_up = 0; + qs->n_fallback = 0; + qs->has_imatrix = false; qs->has_tied_embeddings = true; // build metadata from tensor names std::vector metadata(n_tensors); - for (size_t i = 0; i < n_tensors; i++) { - metadata[i].name = ggml_get_name(tensors[i]); - } + for (size_t i = 0; i < n_tensors; i++) { metadata[i].name = ggml_get_name(tensors[i]); } // initialize counters and categories init_quantize_state_counters(*qs, metadata); @@ -1595,10 +3817,8 @@ void llama_quant_compute_types( llama_model_quantize_params local_params = *qs->params; local_params.ftype = ftype; - ggml_type default_type = llama_ftype_get_default_type(ftype); + const ggml_type default_type = llama_ftype_get_default_type(ftype); // compute types - for (size_t i = 0; i < n_tensors; i++) { - result_types[i] = llama_tensor_get_type(*qs, &local_params, tensors[i], default_type, metadata[i]); - } + for (size_t i = 0; i < n_tensors; i++) { result_types[i] = llama_tensor_get_type(*qs, &local_params, tensors[i], default_type, metadata[i]); } } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 5b997e91bbcf..2e0edcb497c2 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -350,6 +350,7 @@ llama_build_and_test(test-thread-safety.cpp LABEL "main backend" ARGS -m "${MO set_tests_properties(test-thread-safety PROPERTIES FIXTURES_REQUIRED test-download-model) llama_build_and_test(test-arg-parser.cpp LABEL behavior) +llama_build_and_test(test-quantize-target.cpp LABEL "main behavior backend" LINK llama) llama_build_and_test(test-model-resolution.cpp LABEL behavior) # the test serves its repos from an httplib server, and the library links it privately target_link_libraries(test-model-resolution PRIVATE cpp-httplib) diff --git a/tests/test-quantize-target.cpp b/tests/test-quantize-target.cpp new file mode 100644 index 000000000000..9b11584048ab --- /dev/null +++ b/tests/test-quantize-target.cpp @@ -0,0 +1,938 @@ +#include "testing.h" + +#include "ggml-backend.h" +#include "ggml-cpp.h" +#include "gguf.h" +#include "llama-cpp.h" +#include "llama.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#endif + +static const uint32_t n_vocab = 256; +static const uint32_t n_embd = 256; +static const uint32_t n_ff = 512; +static const uint32_t n_head = 2; +static const uint32_t n_layer = 4; +static const float target_bpw = 4.5f; +static bool verbose = false; + +static void set_tensor_data(ggml_tensor * tensor, void * /*userdata*/) { + std::mt19937 gen(std::hash{}(tensor->name)); + std::normal_distribution dis(0.0f, 0.1f); + std::vector data(ggml_nelements(tensor)); + for (float & v : data) { v = dis(gen); } + ggml_backend_tensor_set(tensor, data.data(), 0, ggml_nbytes(tensor)); +} + +// test model +static bool save_model(const std::string & fname) { + gguf_context_ptr meta(gguf_init_empty()); + gguf_set_val_str(meta.get(), "general.architecture", "llama"); + gguf_set_val_u32(meta.get(), "llama.vocab_size", n_vocab); + gguf_set_val_u32(meta.get(), "llama.context_length", 256); + gguf_set_val_u32(meta.get(), "llama.embedding_length", n_embd); + gguf_set_val_u32(meta.get(), "llama.feed_forward_length", n_ff); + gguf_set_val_u32(meta.get(), "llama.block_count", n_layer); + gguf_set_val_u32(meta.get(), "llama.attention.head_count", n_head); + gguf_set_val_u32(meta.get(), "llama.attention.head_count_kv", n_head); + gguf_set_val_f32(meta.get(), "llama.attention.layer_norm_rms_epsilon", 1e-5f); + gguf_set_val_str(meta.get(), "tokenizer.ggml.model", "none"); + + llama_model_params mparams = llama_model_default_params(); + ggml_backend_dev_t devs[] = { nullptr }; + mparams.devices = devs; + + llama_model_ptr model(llama_model_init_from_user(meta.get(), set_tensor_data, nullptr, mparams)); + if (!model) { return false; } + llama_model_save_to_file(model.get(), fname.c_str()); + return true; +} + +// test imatrix +struct imatrix_data { + std::vector names; + std::vector> values; + std::vector> activations; + std::vector> statistics; + std::vector stats_schema; +}; + +// stats schema +static const std::vector default_stats_schema = { + "sum_sq", "mean", "elements", "std_deviation", "skewness", "kurtosis", "gain", "h_norm", "l2_dist", "cossim", "pearson", "covariance" +}; + +static std::vector make_stats(std::mt19937 & gen, const int64_t n_per_row) { + std::uniform_real_distribution u(0.0f, 1.0f); + return { + 100.0f + 100.0f * u(gen), // sum_sq + 0.01f * (u(gen) - 0.5f), // mean + (float) n_per_row, // elements + 1.0f + u(gen), // std_deviation + u(gen) - 0.5f, // skewness + 3.0f * u(gen), // kurtosis + 1.0f + u(gen), // gain + 80.0f + 20.0f * u(gen), // h_norm + 10.0f * u(gen), // l2_dist + 0.5f + 0.5f * u(gen), // cossim + 0.5f + 0.5f * u(gen), // pearson + u(gen), // covariance + }; +} + +static imatrix_data make_imatrix(const std::string & fname_model, const uint32_t seed) { + imatrix_data im; + + ggml_context * ctx_meta = nullptr; + const gguf_init_params params = { /*.no_alloc =*/ true, /*.ctx =*/ &ctx_meta }; + gguf_context_ptr ctx(gguf_init_from_file(fname_model.c_str(), params)); + ggml_context_ptr meta(ctx_meta); + if (!ctx) { return im; } + + std::mt19937 gen(seed); + std::uniform_real_distribution u(0.0f, 1.0f); + for (int64_t i = 0; i < gguf_get_n_tensors(ctx.get()); i++) { + const char * name = gguf_get_tensor_name(ctx.get(), i); + const ggml_tensor * tensor = ggml_get_tensor(meta.get(), name); + if (ggml_n_dims(tensor) < 2 || strcmp(name, "token_embd.weight") == 0) { continue; } + + const int64_t n_per_row = tensor->ne[0]; + std::vector values(n_per_row); + std::vector activations(n_per_row); + for (int64_t j = 0; j < n_per_row; j++) { + activations[j] = u(gen) - 0.5f; + values[j] = activations[j] * activations[j] + std::exp(2.0f * u(gen) - 1.0f); + } + + im.names.push_back(name); + im.values.push_back(std::move(values)); + im.activations.push_back(std::move(activations)); + im.statistics.push_back(make_stats(gen, n_per_row)); + } + + im.stats_schema = default_stats_schema; + + return im; +} + +static std::vector imatrix_list(const imatrix_data & im, const std::vector> & data) { + std::vector list; + for (size_t i = 0; i < im.names.size(); i++) { + if (data[i].empty()) { continue; } + list.push_back({ im.names[i].c_str(), data[i].data(), data[i].size() }); + } + + list.push_back({ nullptr, nullptr, 0 }); + + return list; +} + +struct quant_run { + uint32_t rc = 1; // 0 when quantization succeeds and output is processed + std::string log; + std::map types; + size_t n_bytes = 0; // tensor data + size_t n_elements = 0; + size_t file_size = 0; +}; + +static void log_callback(ggml_log_level /*level*/, const char * text, void * user_data) { + if (user_data) { static_cast(user_data)->append(text); } + if (verbose) { fputs(text, stderr); } +} + +static quant_run quantize(const std::string & fname_inp, const std::string & fname_out, const imatrix_data & im, llama_model_quantize_params params) { + const auto values = imatrix_list(im, im.values); + const auto activations = imatrix_list(im, im.activations); + const auto statistics = imatrix_list(im, im.statistics); + std::vector stats_schema; + for (const auto & name : im.stats_schema) { stats_schema.push_back(name.c_str()); } + stats_schema.push_back(nullptr); + params.imatrix = values.data(); + params.activations = activations.data(); + params.statistics = statistics.data(); + params.stats_schema = im.stats_schema.empty() ? nullptr : stats_schema.data(); + + quant_run run; + // clear previous run's output + std::filesystem::remove(fname_out); + llama_log_set(log_callback, &run.log); + run.rc = llama_model_quantize(fname_inp.c_str(), fname_out.c_str(), ¶ms); + llama_log_set(log_callback, nullptr); + if (run.rc != 0) { return run; } + + ggml_context * ctx_meta = nullptr; + const gguf_init_params gparams = { /*.no_alloc =*/ true, /*.ctx =*/ &ctx_meta }; + gguf_context_ptr ctx(gguf_init_from_file(fname_out.c_str(), gparams)); + ggml_context_ptr meta(ctx_meta); + if (!ctx) { + run.rc = 1; + return run; + } + + for (int64_t i = 0; i < gguf_get_n_tensors(ctx.get()); i++) { + const char * name = gguf_get_tensor_name(ctx.get(), i); + run.types[name] = gguf_get_tensor_type(ctx.get(), i); + run.n_bytes += gguf_get_tensor_size(ctx.get(), i); + run.n_elements += ggml_nelements(ggml_get_tensor(meta.get(), name)); + } + + run.file_size = std::filesystem::file_size(fname_out); + + return run; +} + +static size_t count_matches(const std::string & log, const std::string & text) { + size_t n = 0; + for (size_t pos = log.find(text); pos != std::string::npos; pos = log.find(text, pos + text.size())) { n++; } + + return n; +} + +static size_t logged_number(const std::string & log, const std::string & text) { + const size_t pos = log.find(text); + return pos == std::string::npos ? SIZE_MAX : (size_t) std::strtoull(log.c_str() + pos + text.size(), nullptr, 10); +} + +static size_t count_type(const quant_run & run, const ggml_type type) { + size_t n = 0; + for (const auto & it : run.types) { n += it.second == type; } + + return n; +} + +static size_t count_type_changes(const quant_run & a, const quant_run & b) { + size_t n = 0; + for (const auto & it : a.types) { + const auto other = b.types.find(it.first); + n += other == b.types.end() || other->second != it.second; + } + + return n; +} + +// the type name of a tensor in a run's output, or "none" if the output has no such tensor +static std::string type_name_of(const quant_run & run, const std::string & name) { + const auto it = run.types.find(name); + return it == run.types.end() ? "none" : ggml_type_name(it->second); +} + +// tensor quantization mix rows +static std::vector mix_rows(const quant_run & run) { + std::vector rows; + for (size_t pos = run.log.find("\terror: "); pos != std::string::npos; pos = run.log.find("\terror: ", pos + 1)) { + const size_t start = run.log.rfind('\n', pos) + 1; + rows.push_back(run.log.substr(start, run.log.find('\n', pos) - start)); + } + + return rows; +} + +static size_t count_row_changes(const quant_run & a, const quant_run & b) { + const std::vector rows_a = mix_rows(a); + const std::vector rows_b = mix_rows(b); + if (rows_a.empty() || rows_a.size() != rows_b.size()) { return SIZE_MAX; } + + size_t n = 0; + for (size_t i = 0; i < rows_a.size(); i++) { n += rows_a[i] != rows_b[i]; } + + return n; +} + +static std::string read_file(const std::string & fname) { + std::ifstream file(fname, std::ios::binary); + return std::string(std::istreambuf_iterator(file), std::istreambuf_iterator()); +} + +static void write_file(const std::string & fname, const std::string & data) { + std::ofstream file(fname, std::ios::binary); + file << data; +} + +static const size_t state_header_size = 24; // magic, model id, tensor count +static const size_t state_entry_size = 28; // candidate count, choice, min and max bpw, elements +static const size_t state_candidate_size = 24; // type, bpw, bytes, error + +// offset of the first tensor's candidate count; 0 if the checkpoint holds no candidate +static size_t first_count_offset(const std::string & state) { + uint32_t len = 0; + if (state.size() < state_header_size + sizeof(len)) { return 0; } + memcpy(&len, state.data() + state_header_size, sizeof(len)); + const size_t offset = state_header_size + sizeof(len) + len; + + return state.size() >= offset + state_entry_size + state_candidate_size ? offset : 0; +} + +struct fixture { + std::string fname_model; + std::string fname_out; + std::string fname_state; + imatrix_data im; + quant_run base; +}; + +// first run parameters +static llama_model_quantize_params base_params(const fixture & f) { + llama_model_quantize_params params = llama_model_quantize_default_params(); + params.nthread = 4; + params.target_bpw = target_bpw; + params.state_file = f.fname_state.c_str(); + + return params; +} + +static std::string sibling_path(const fixture & f, const std::string & name) { + return (std::filesystem::path(f.fname_state).parent_path() / name).string(); +} + +static void test_target_bpw(testing & t, const fixture & f) { + const double bpw = 8.0 * f.base.n_bytes / f.base.n_elements; + t.log("final bpw " + std::to_string(bpw)); + t.assert_true("bpw does not exceed the target", bpw <= target_bpw); + t.assert_true("bpw is within 0.05 of the target", bpw > target_bpw - 0.05); +} + +static void test_state_checkpoint(testing & t, const fixture & f) { + const size_t n_scored = count_matches(f.base.log, "processing tensor"); + const std::string n_tensors = std::to_string(n_scored) + " tensors"; + t.assert_true("first run scores tensors", n_scored > 0); + t.assert_equal("first run saves the checkpoint", (size_t) 1, count_matches(f.base.log, "saved target progress for " + n_tensors + " to " + f.fname_state)); + + const quant_run run = quantize(f.fname_model, f.fname_out, f.im, base_params(f)); + t.assert_equal("quantize succeeds", 0u, run.rc); + t.assert_equal("second run loads the checkpoint", (size_t) 1, count_matches(run.log, "using " + f.fname_state + " (data for " + n_tensors + " loaded)")); + t.assert_equal("second run scores no tensor", (size_t) 0, count_matches(run.log, "processing tensor")); + t.assert_equal("tensors whose type changed", (size_t) 0, count_type_changes(f.base, run)); +} + +static void test_target_size(testing & t, const fixture & f) { + llama_model_quantize_params params = base_params(f); + params.target_bpw = -1.0f; + params.target_size = (int64_t) f.base.file_size * 9 / 10; + + const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("quantize succeeds", 0u, run.rc); + + const int64_t diff = (int64_t) run.file_size - params.target_size; + t.log("file size " + std::to_string(run.file_size) + ", " + std::to_string(diff) + " bytes from the target"); + t.assert_true("the file is within 8 KiB of the target", std::abs(diff) <= 8 * 1024); +} + +static void test_excluded_type(testing & t, const fixture & f) { + ggml_type excluded = GGML_TYPE_COUNT; + for (const auto & it : f.base.types) { + if (it.second != GGML_TYPE_F32 && (excluded == GGML_TYPE_COUNT || count_type(f.base, it.second) > count_type(f.base, excluded))) { + excluded = it.second; + } + } + + t.assert_true("first run selects a type", excluded != GGML_TYPE_COUNT); + if (excluded == GGML_TYPE_COUNT) { return; } + t.log(std::string("excluding ") + ggml_type_name(excluded) + ", the type of " + std::to_string(count_type(f.base, excluded)) + " tensors"); + + const ggml_type exclude[] = { excluded, GGML_TYPE_COUNT }; + llama_model_quantize_params params = base_params(f); + params.target_exclude = exclude; + + params.state_file = nullptr; + const quant_run scored = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("quantize succeeds", 0u, scored.rc); + t.assert_equal("scored with excluded types, tensors of the excluded type", (size_t) 0, count_type(scored, excluded)); + + params.state_file = f.fname_state.c_str(); + const std::string n_tensors = std::to_string(count_matches(f.base.log, "processing tensor")) + " tensors"; + const quant_run loaded = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("quantize succeeds", 0u, loaded.rc); + t.assert_equal("run loads the checkpoint", (size_t) 1, count_matches(loaded.log, "using " + f.fname_state + " (data for " + n_tensors + " loaded)")); + t.assert_equal("run scores no tensor", (size_t) 0, count_matches(loaded.log, "processing tensor")); + t.assert_equal("loaded from checkpoint, tensors of the excluded type", (size_t) 0, count_type(loaded, excluded)); + t.assert_equal("run warns that the checkpoint is not saved", (size_t) 1, count_matches(loaded.log, "state checkpoint cannot be saved while --target-exclude is active")); + t.assert_equal("checkpoint is not saved while types are excluded", (size_t) 0, count_matches(loaded.log, "saved target progress")); +} + +static void test_unknown_type(testing & t, const fixture & f) { + std::string state = read_file(f.fname_state); + const size_t offset = first_count_offset(state); + t.assert_true("first run's checkpoint holds a candidate", offset > 0); + if (offset == 0) { return; } + + // type 4 was Q4_2; within ggml_type range but invalid + const int32_t type = 4; + memcpy(&state[offset + state_entry_size], &type, sizeof(type)); + const std::string fname = sibling_path(f, "unknown.bpw_state"); + write_file(fname, state); + + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("quantize succeeds", 0u, run.rc); + t.assert_equal("unknown type is reported", (size_t) 1, count_matches(run.log, "candidate type is not in the selection pool, ignoring state file")); + t.assert_equal("unknown checkpoint is not loaded", (size_t) 0, count_matches(run.log, "using " + fname)); + t.assert_equal("unknown checkpoint is scored again", count_matches(f.base.log, "processing tensor"), count_matches(run.log, "processing tensor")); + t.assert_equal("scored again, tensors whose type changed", (size_t) 0, count_type_changes(f.base, run)); +} + +static void test_zero_candidates(testing & t, const fixture & f) { + std::string state = read_file(f.fname_state); + const size_t offset = first_count_offset(state); + t.assert_true("the first run's checkpoint holds a candidate", offset > 0); + if (offset == 0) { return; } + + // drop the first tensor's candidates + uint64_t n = 0; + memcpy(&n, &state[offset], sizeof(n)); + state.erase(offset + state_entry_size, n * state_candidate_size); + n = 0; + memcpy(&state[offset], &n, sizeof(n)); + const std::string fname = sibling_path(f, "zero.bpw_state"); + write_file(fname, state); + + // with a type excluded, an empty candidate list that is loaded fails the call instead of crashing the test + const ggml_type exclude[] = { GGML_TYPE_IQ1_S, GGML_TYPE_COUNT }; + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + params.target_exclude = exclude; + const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("quantize succeeds", 0u, run.rc); + t.assert_equal("empty candidate list is reported", (size_t) 1, count_matches(run.log, "candidate count out of range, ignoring state file")); + t.assert_equal("checkpoint with an empty candidate list is not loaded", (size_t) 0, count_matches(run.log, "using " + fname)); + t.assert_equal("checkpoint with an empty candidate list is scored again", count_matches(f.base.log, "processing tensor"), count_matches(run.log, "processing tensor")); +} + +static void test_truncated(testing & t, const fixture & f) { + const std::string state = read_file(f.fname_state); + const size_t offset = first_count_offset(state); + t.assert_true("first run's checkpoint has a candidate", offset > 0); + if (offset == 0) { return; } + + // cut before the first candidate count, then before the first candidate type + const std::string fname = sibling_path(f, "truncated.bpw_state"); + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + write_file(fname, state.substr(0, offset)); + const quant_run at_count = quantize(f.fname_model, f.fname_out, f.im, params); + write_file(fname, state.substr(0, offset + state_entry_size)); + const quant_run at_type = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("quantize succeeds", 0u, at_count.rc); + t.assert_equal("checkpoint cut before a candidate count is reported as truncated", (size_t) 1, count_matches(at_count.log, "state file truncated or read error, ignoring")); + t.assert_equal("quantize succeeds", 0u, at_type.rc); + t.assert_equal("checkpoint cut before a candidate type is reported as truncated", (size_t) 1, count_matches(at_type.log, "state file truncated or read error, ignoring")); +} + +static void test_missing_dir(testing & t, const fixture & f) { + const std::string dir = sibling_path(f, "no-such-dir"); + const std::string fname = (std::filesystem::path(dir) / "model.bpw_state").string(); + + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("path in missing directory fails", 1u, run.rc); + t.assert_equal("path in missing directory is reported", (size_t) 1, count_matches(run.log, "failed to open " + fname + ": ")); + t.assert_equal("path in missing directory stops execution before scoring", (size_t) 0, count_matches(run.log, "processing tensor")); + t.assert_true("missing directory is not created", !std::filesystem::exists(dir)); +} + +static void test_unreadable_file(testing & t, const fixture & f) { +#ifdef _WIN32 + GGML_UNUSED(f); + t.skip("POSIX permissions only"); +#else + namespace fs = std::filesystem; + std::error_code ec; + const std::string fname = sibling_path(f, "locked.bpw_state"); + write_file(fname, "forbidden"); + // write-only, so that a probe that opens the file for writing could still damage it + fs::permissions(fname, fs::perms::owner_write, ec); + if (std::ifstream(fname).good()) { + fs::permissions(fname, fs::perms::owner_read | fs::perms::owner_write, ec); + t.skip("the file can still be read, as by root"); + return; + } + + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params); + const bool kept_perms = fs::status(fname, ec).permissions() == fs::perms::owner_write; + fs::permissions(fname, fs::perms::owner_read | fs::perms::owner_write, ec); + t.assert_equal("an unreadable file fails the call", 1u, run.rc); + t.assert_equal("an unreadable file is reported", (size_t) 1, count_matches(run.log, "failed to open " + fname + ": ")); + t.assert_equal("an unreadable file stops the run before scoring", (size_t) 0, count_matches(run.log, "processing tensor")); + t.assert_true("an unreadable file keeps its permissions", kept_perms); + t.assert_true("an unreadable file keeps its content", read_file(fname) == "forbidden"); +#endif +} + +static void test_directory_path(testing & t, const fixture & f) { + const std::string fname = sibling_path(f, "dir.bpw_state"); + std::filesystem::create_directory(fname); + + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("a directory instead of a file fails the call", 1u, run.rc); + t.assert_equal("a directory instead of a file is reported", (size_t) 1, count_matches(run.log, "failed to open " + fname + ": ")); + t.assert_equal("a directory stops the run before scoring", (size_t) 0, count_matches(run.log, "processing tensor")); + t.assert_true("the directory is left as it was", std::filesystem::is_directory(fname) && std::filesystem::is_empty(fname)); +} + +static void test_save_error(testing & t, const fixture & f) { + const std::string fname = sibling_path(f, "unsaved.bpw_state"); + write_file(fname, read_file(f.fname_state)); + std::filesystem::create_directory(fname + ".tmp"); + + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("quantize succeeds", 0u, run.rc); + t.assert_equal("a failed save is reported", (size_t) 1, count_matches(run.log, "failed to save progress to " + fname + ".tmp (open error)")); + t.assert_equal("a failed save logs no saved checkpoint", (size_t) 0, count_matches(run.log, "saved target progress")); +} + +static void test_imatrix_swap(testing & t, const fixture & f) { + const imatrix_data im = make_imatrix(f.fname_model, 4321); + const std::string fname = sibling_path(f, "swap.bpw_state"); + write_file(fname, read_file(f.fname_state)); + + llama_model_quantize_params params = base_params(f); + params.state_file = nullptr; + const quant_run fresh = quantize(f.fname_model, f.fname_out, im, params); + params.state_file = fname.c_str(); + const quant_run reused = quantize(f.fname_model, f.fname_out, im, params); + t.log(std::to_string(count_type_changes(f.base, fresh)) + " tensors change type with the other imatrix"); + t.assert_equal("quantize succeeds", 0u, fresh.rc); + t.assert_equal("quantize succeeds", 0u, reused.rc); + t.assert_equal("a checkpoint from another imatrix is reported", (size_t) 1, count_matches(reused.log, "state file does not match this model, imatrix or pruned layers, ignoring")); + t.assert_equal("a checkpoint from another imatrix is scored again", count_matches(f.base.log, "processing tensor"), count_matches(reused.log, "processing tensor")); + t.assert_equal("scored again with another imatrix, tensors whose type differs from a fresh run", (size_t) 0, count_type_changes(fresh, reused)); +} + +static void test_imatrix_parts(testing & t, const fixture & f) { + // one float doubled in one list at a time + auto check = [&](const std::string & part, const imatrix_data & im) { + const std::string fname = sibling_path(f, part + ".bpw_state"); + write_file(fname, read_file(f.fname_state)); + + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + const quant_run run = quantize(f.fname_model, f.fname_out, im, params); + t.assert_equal("quantize succeeds", 0u, run.rc); + t.assert_equal("a checkpoint from other " + part + " is reported", (size_t) 1, count_matches(run.log, "state file does not match this model, imatrix or pruned layers, ignoring")); + t.assert_equal("a checkpoint from other " + part + " is scored again", count_matches(f.base.log, "processing tensor"), count_matches(run.log, "processing tensor")); + }; + + imatrix_data im = f.im; + im.values[0][0] *= 2.0f; + check("values", im); + + im = f.im; + im.activations[0][0] *= 2.0f; + check("activations", im); + + im = f.im; + im.statistics[0][0] *= 2.0f; + check("statistics", im); +} + +static void test_imatrix_order(testing & t, const fixture & f) { + // the same imatrix data, passed in reverse order + imatrix_data im = f.im; + std::reverse(im.names.begin(), im.names.end()); + std::reverse(im.values.begin(), im.values.end()); + std::reverse(im.activations.begin(), im.activations.end()); + std::reverse(im.statistics.begin(), im.statistics.end()); + const std::string fname = sibling_path(f, "reversed.bpw_state"); + write_file(fname, read_file(f.fname_state)); + + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + const std::string n_tensors = std::to_string(count_matches(f.base.log, "processing tensor")) + " tensors"; + const quant_run run = quantize(f.fname_model, f.fname_out, im, params); + t.assert_equal("quantize succeeds", 0u, run.rc); + t.assert_equal("the same imatrix in another order loads the checkpoint", (size_t) 1, count_matches(run.log, "using " + fname + " (data for " + n_tensors + " loaded)")); + t.assert_equal("the same imatrix in another order scores no tensor", (size_t) 0, count_matches(run.log, "processing tensor")); +} + +static void test_pruned_layer(testing & t, const fixture & f) { + // pruning a block renumbers the ones after it + const int32_t prune[] = { 1, -1 }; + const std::string fname = sibling_path(f, "pruned.bpw_state"); + write_file(fname, read_file(f.fname_state)); + + llama_model_quantize_params params = base_params(f); + params.prune_layers = prune; + params.state_file = nullptr; + const quant_run fresh = quantize(f.fname_model, f.fname_out, f.im, params); + params.state_file = fname.c_str(); + const quant_run reused = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("quantize succeeds", 0u, fresh.rc); + t.assert_equal("quantize succeeds", 0u, reused.rc); + t.assert_equal("a checkpoint without pruning is reported", (size_t) 1, count_matches(reused.log, "state file does not match this model, imatrix or pruned layers, ignoring")); + t.assert_equal("a checkpoint without pruning is scored again", count_matches(fresh.log, "processing tensor"), count_matches(reused.log, "processing tensor")); + t.assert_equal("scored again with a pruned block, tensors whose type differs from a fresh run", (size_t) 0, count_type_changes(fresh, reused)); + + // another block pruned, reusing the checkpoint saved for block 1 + const int32_t prune_other[] = { 2, -1 }; + params.prune_layers = prune_other; + const quant_run other = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("the pruned run saves its checkpoint", (size_t) 1, count_matches(reused.log, "saved target progress")); + t.assert_equal("quantize succeeds", 0u, other.rc); + t.assert_equal("a checkpoint for another pruned block is reported", (size_t) 1, count_matches(other.log, "state file does not match this model, imatrix or pruned layers, ignoring")); + t.assert_equal("a checkpoint for another pruned block is scored again", count_matches(fresh.log, "processing tensor"), count_matches(other.log, "processing tensor")); +} + +static void test_stats_order(testing & t, const fixture & f) { + // stats in reverse order + imatrix_data im = f.im; + std::reverse(im.stats_schema.begin(), im.stats_schema.end()); + for (auto & stats : im.statistics) { std::reverse(stats.begin(), stats.end()); } + + llama_model_quantize_params params = base_params(f); + params.state_file = nullptr; + const quant_run run = quantize(f.fname_model, f.fname_out, im, params); + t.assert_equal("quantize succeeds", 0u, run.rc); + t.assert_equal("statistics in different order", (size_t) 0, count_matches(run.log, "skipping CNIF")); + t.assert_equal("statistics in different order, rows that changed", (size_t) 0, count_row_changes(f.base, run)); +} + +static void test_stats_missing(testing & t, const fixture & f) { + // tensor whose stats vector is cut short or left out + const size_t k = std::find(f.im.names.begin(), f.im.names.end(), "blk.1.ffn_down.weight") - f.im.names.begin(); + t.assert_true("imatrix has blk.1.ffn_down.weight", k < f.im.names.size()); + if (k == f.im.names.size()) { return; } + + // pearson under another name + imatrix_data renamed = f.im; + std::replace(renamed.stats_schema.begin(), renamed.stats_schema.end(), std::string("pearson"), std::string("spearman")); + const std::string fname = sibling_path(f, "renamed.bpw_state"); + write_file(fname, read_file(f.fname_state)); + + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + const quant_run missing = quantize(f.fname_model, f.fname_out, renamed, params); + + // no names + imatrix_data unnamed = f.im; + unnamed.stats_schema.clear(); + params.state_file = nullptr; + const quant_run no_names = quantize(f.fname_model, f.fname_out, unnamed, params); + + // stats vector cut before pearson + imatrix_data cut = f.im; + cut.statistics[k].resize(10); + const quant_run short_stats = quantize(f.fname_model, f.fname_out, cut, params); + imatrix_data dropped = f.im; + dropped.statistics[k].clear(); + const quant_run no_stats = quantize(f.fname_model, f.fname_out, dropped, params); + + const size_t n_changed = count_row_changes(f.base, missing); + t.log(std::to_string(n_changed) + " mix rows change without CNIF"); + t.assert_equal("quantize succeeds", 0u, missing.rc); + t.assert_true("missing metric changes the mix", n_changed > 0 && n_changed != SIZE_MAX); + t.assert_equal("missing metric is reported", (size_t) 1, count_matches(missing.log, "statistics have no pearson metric, skipping CNIF")); + t.assert_equal("checkpoint with different statistics names is reported", (size_t) 1, count_matches(missing.log, "state file does not match this model, imatrix or pruned layers, ignoring")); + t.assert_equal("checkpoint with different statistics names is scored again", count_matches(f.base.log, "processing tensor"), count_matches(missing.log, "processing tensor")); + t.assert_equal("quantize succeeds", 0u, no_names.rc); + t.assert_equal("statistics without names are reported", (size_t) 1, count_matches(no_names.log, "statistics have no sum_sq metric, skipping CNIF")); + t.assert_equal("statistics without names log one line", (size_t) 1, count_matches(no_names.log, "skipping CNIF")); + t.assert_equal("statistics without names, rows that differ from a missing metric", (size_t) 0, count_row_changes(missing, no_names)); + t.assert_equal("quantize succeeds", 0u, short_stats.rc); + t.assert_equal("a short stats vector is not reported as a missing metric", (size_t) 0, count_matches(short_stats.log, "skipping CNIF")); + t.assert_equal("quantize succeeds", 0u, no_stats.rc); + t.assert_equal("a short stats vector, rows that differ from a left-out one", (size_t) 0, count_row_changes(no_stats, short_stats)); +} + +// counts its calls, and asks to stop at call number stop_at only +struct terminate_probe { + size_t n_calls = 0; + size_t stop_at = 0; +}; + +static bool terminate_at(void * data) { + auto * probe = static_cast(data); + return ++probe->n_calls == probe->stop_at; +} + +static void test_abort_callback(testing & t, const fixture & f) { + // full scoring no interruptions + terminate_probe counter; + llama_model_quantize_params params = base_params(f); + params.state_file = nullptr; + params.abort_callback = terminate_at; + params.abort_callback_data = &counter; + const quant_run counted = quantize(f.fname_model, f.fname_out, f.im, params); + + // interrupt at half the calls + terminate_probe stopper; + stopper.stop_at = counter.n_calls / 2; + const std::string fname = sibling_path(f, "interrupted.bpw_state"); + params.state_file = fname.c_str(); + params.abort_callback_data = &stopper; + const quant_run stopped = quantize(f.fname_model, f.fname_out, f.im, params); + const bool stopped_wrote = std::filesystem::exists(f.fname_out); + params.abort_callback = nullptr; + const quant_run resumed = quantize(f.fname_model, f.fname_out, f.im, params); + + const size_t n_total = count_matches(f.base.log, "processing tensor"); + const size_t n_saved = logged_number(stopped.log, "interrupted, saving progress for "); + t.log(std::to_string(n_saved) + " of " + std::to_string(n_total) + " tensors scored before the stop at call " + std::to_string(stopper.stop_at) + " of " + std::to_string(counter.n_calls)); + t.assert_equal("quantize succeeds", 0u, counted.rc); + t.assert_equal("a callback that never asks to stop, mix rows that changed", (size_t) 0, count_row_changes(f.base, counted)); + t.assert_equal("the interrupted call fails", 1u, stopped.rc); + t.assert_equal("the stop is reported", (size_t) 1, count_matches(stopped.log, "failed to quantize: interrupted")); + t.assert_true("the stop comes part way through the scoring", n_saved > 0 && n_saved < n_total); + t.assert_equal("the stopped run saves what it scored", (size_t) 1, count_matches(stopped.log, "saved target progress for " + std::to_string(n_saved) + " tensors to " + fname)); + t.assert_true("the stopped run writes no output", !stopped_wrote); + t.assert_equal("quantize succeeds", 0u, resumed.rc); + t.assert_equal("the resumed run loads the saved tensors", (size_t) 1, count_matches(resumed.log, "using " + fname + " (data for " + std::to_string(n_saved) + " tensors loaded)")); + t.assert_equal("the resumed run scores the rest", n_total - n_saved, count_matches(resumed.log, "processing tensor")); + t.assert_equal("resumed, mix rows that differ from the first run", (size_t) 0, count_row_changes(f.base, resumed)); + + // without a target, the main loop calls it once per tensor + terminate_probe loop_stopper; + loop_stopper.stop_at = 2; + llama_model_quantize_params plain = llama_model_quantize_default_params(); + plain.nthread = 4; + plain.abort_callback = terminate_at; + plain.abort_callback_data = &loop_stopper; + const quant_run main_loop = quantize(f.fname_model, f.fname_out, f.im, plain); + t.assert_equal("a stop in the main loop fails the call", 1u, main_loop.rc); + t.assert_equal("a stop in the main loop is reported", (size_t) 1, count_matches(main_loop.log, "failed to quantize: interrupted")); + t.assert_equal("the main loop stops at the call that asks", (size_t) 2, loop_stopper.n_calls); +} + +static void test_interrupt_first_call(testing & t, const fixture & f) { + // a copy of the checkpoint, stopped at the first call, before the workers read it back + const size_t n_total = count_matches(f.base.log, "processing tensor"); + const std::string fname = sibling_path(f, "first-call.bpw_state"); + write_file(fname, read_file(f.fname_state)); + terminate_probe stopper; + stopper.stop_at = 1; + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + params.abort_callback = terminate_at; + params.abort_callback_data = &stopper; + const quant_run stopped = quantize(f.fname_model, f.fname_out, f.im, params); + params.abort_callback = nullptr; + const quant_run resumed = quantize(f.fname_model, f.fname_out, f.im, params); + + t.assert_equal("the stopped call fails", 1u, stopped.rc); + t.assert_equal("the checkpoint keeps its tensors", (size_t) 1, count_matches(resumed.log, "using " + fname + " (data for " + std::to_string(n_total) + " tensors loaded)")); + t.assert_equal("the next run scores nothing", (size_t) 0, count_matches(resumed.log, "processing tensor")); +} + +#ifndef _WIN32 +static void app_signal_handler(int, siginfo_t *, void *) {} + +// true when both have the same handler, flags and mask +static bool same_action(const struct sigaction & a, const struct sigaction & b) { + if (a.sa_flags != b.sa_flags) { return false; } + if ((a.sa_flags & SA_SIGINFO) ? a.sa_sigaction != b.sa_sigaction : a.sa_handler != b.sa_handler) { return false; } + for (int sig = 1; sig < NSIG; sig++) { + if (sigismember(&a.sa_mask, sig) != sigismember(&b.sa_mask, sig)) { return false; } + } + + return true; +} + +// read SIGINT and SIGTERM disposition +struct disposition_probe { + size_t n_calls = 0; + struct sigaction during[2]; +}; + +static bool probe_dispositions(void * data) { + auto * probe = static_cast(data); + if (probe->n_calls++ == 0) { + sigaction(SIGINT, nullptr, &probe->during[0]); + sigaction(SIGTERM, nullptr, &probe->during[1]); + } + + return false; +} +#endif + +static void test_signal_handlers(testing & t, const fixture & f) { +#ifdef _WIN32 + GGML_UNUSED(f); + t.skip("POSIX signals only"); +#else + struct sigaction app = {}; + app.sa_sigaction = app_signal_handler; + app.sa_flags = SA_SIGINFO; + sigemptyset(&app.sa_mask); + sigaddset(&app.sa_mask, SIGTERM); + + const int signals[] = { SIGINT, SIGTERM }; + struct sigaction prev[2], before[2], after[2]; + for (int i = 0; i < 2; i++) { + sigaction(signals[i], &app, &prev[i]); + sigaction(signals[i], nullptr, &before[i]); + } + + // checkpoint exists, should not score + const std::string fname = sibling_path(f, "signals.bpw_state"); + write_file(fname, read_file(f.fname_state)); + disposition_probe probe = {}; + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + params.abort_callback = probe_dispositions; + params.abort_callback_data = &probe; + const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params); + + for (int i = 0; i < 2; i++) { + sigaction(signals[i], nullptr, &after[i]); + sigaction(signals[i], &prev[i], nullptr); + } + t.assert_equal("quantize succeeds", 0u, run.rc); + t.assert_true("the callback is called", probe.n_calls > 0); + t.assert_true("SIGINT keeps its handler, flags and mask during a call", same_action(before[0], probe.during[0])); + t.assert_true("SIGTERM keeps its handler, flags and mask during a call", same_action(before[1], probe.during[1])); + t.assert_true("SIGINT keeps its handler, flags and mask after a call", same_action(before[0], after[0])); + t.assert_true("SIGTERM keeps its handler, flags and mask after a call", same_action(before[1], after[1])); +#endif +} + +static void test_type_flags(testing & t, const fixture & f) { + t.assert_true("without the flags, neither tensor has its flag's type", type_name_of(f.base, "token_embd.weight") != "q8_0" && type_name_of(f.base, "output.weight") != "q6_K"); + + // a copy of the checkpoint, so that nothing is scored + const std::string fname = sibling_path(f, "flags.bpw_state"); + write_file(fname, read_file(f.fname_state)); + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + params.token_embedding_type = GGML_TYPE_Q8_0; + params.output_tensor_type = GGML_TYPE_Q6_K; + const quant_run flags = quantize(f.fname_model, f.fname_out, f.im, params); + + // the same two tensors pinned through --tensor-type + const llama_model_tensor_override same[] = { + { "^token_embd\\.weight$", GGML_TYPE_Q8_0 }, { "^output\\.weight$", GGML_TYPE_Q6_K }, { nullptr, GGML_TYPE_COUNT }, + }; + llama_model_quantize_params patterns = base_params(f); + patterns.state_file = fname.c_str(); + patterns.tt_overrides = same; + const quant_run by_pattern = quantize(f.fname_model, f.fname_out, f.im, patterns); + + // --tensor-type names both tensors too, at another type + const llama_model_tensor_override other[] = { + { "^token_embd\\.weight$", GGML_TYPE_Q5_0 }, { "^output\\.weight$", GGML_TYPE_Q5_0 }, { nullptr, GGML_TYPE_COUNT }, + }; + params.tt_overrides = other; + const quant_run named = quantize(f.fname_model, f.fname_out, f.im, params); + + // the flags' types barred + constexpr ggml_type exclude[] = { GGML_TYPE_Q8_0, GGML_TYPE_Q6_K, GGML_TYPE_COUNT }; + params.tt_overrides = nullptr; + params.target_exclude = exclude; + const quant_run barred = quantize(f.fname_model, f.fname_out, f.im, params); + + // only --output-tensor-type: the model is not tied, so the token embedding is not pinned + params.token_embedding_type = GGML_TYPE_COUNT; + params.target_exclude = nullptr; + const quant_run output_only = quantize(f.fname_model, f.fname_out, f.im, params); + + const double bpw = 8.0 * flags.n_bytes / flags.n_elements; + t.log("realised bpw with the flags " + std::to_string(bpw)); + t.assert_equal("quantize succeeds", 0u, flags.rc); + t.assert_equal("--token-embedding-type sets the token embedding", std::string("q8_0"), type_name_of(flags, "token_embd.weight")); + t.assert_equal("--output-tensor-type sets the output", std::string("q6_K"), type_name_of(flags, "output.weight")); + t.assert_equal("flags pin two tensors", (size_t) 2, count_matches(flags.log, "(pinned)")); + t.assert_true("bpw does not exceed the target", bpw <= target_bpw); + t.assert_true("bpw is within 0.05 of the target", bpw > target_bpw - 0.05); + t.assert_equal("quantize succeeds", 0u, by_pattern.rc); + t.assert_equal("flags and same --tensor-type pins, mix rows that differ", (size_t) 0, count_row_changes(by_pattern, flags)); + t.assert_equal("quantize succeeds", 0u, named.rc); + t.assert_equal("--token-embedding-type beats --tensor-type", std::string("q8_0"), type_name_of(named, "token_embd.weight")); + t.assert_equal("--output-tensor-type beats --tensor-type", std::string("q6_K"), type_name_of(named, "output.weight")); + t.assert_equal("quantize succeeds", 0u, barred.rc); + t.assert_equal("excluded --token-embedding-type is reported", (size_t) 1, count_matches(barred.log, "--token-embedding-type pins type q8_0 which is ignored by --target-exclude, keeping the pinned type")); + t.assert_equal("excluded --output-tensor-type is reported", (size_t) 1, count_matches(barred.log, "--output-tensor-type pins type q6_K which is ignored by --target-exclude, keeping the pinned type")); + t.assert_equal("excluded --token-embedding-type keeps its type", std::string("q8_0"), type_name_of(barred, "token_embd.weight")); + t.assert_equal("excluded --output-tensor-type keeps its type", std::string("q6_K"), type_name_of(barred, "output.weight")); + t.assert_equal("quantize succeeds", 0u, output_only.rc); + t.assert_equal("--output-tensor-type alone sets the output", std::string("q6_K"), type_name_of(output_only, "output.weight")); + t.assert_equal("--output-tensor-type alone pins one tensor", (size_t) 1, count_matches(output_only.log, "(pinned)")); +} + +static int run_tests(testing & t, const std::filesystem::path & dir) { + fixture f; + f.fname_model = (dir / "model-f32.gguf").string(); + f.fname_out = (dir / "model-out.gguf").string(); + f.fname_state = (dir / "model.bpw_state").string(); + if (!save_model(f.fname_model)) { + fprintf(stderr, "failed to create the model\n"); + return 1; + } + + f.im = make_imatrix(f.fname_model, 1234); + if (f.im.names.empty()) { + fprintf(stderr, "failed to read the model\n"); + return 1; + } + + f.base = quantize(f.fname_model, f.fname_out, f.im, base_params(f)); + if (f.base.rc != 0) { + fprintf(stderr, "the first quantization failed:\n%s", f.base.log.c_str()); + return 1; + } + + t.test("target_bpw", [&](testing & t) { test_target_bpw(t, f); }); + t.test("target_size", [&](testing & t) { test_target_size(t, f); }); + t.test("state_checkpoint", [&](testing & t) { test_state_checkpoint(t, f); }); + t.test("excluded_type", [&](testing & t) { test_excluded_type(t, f); }); + t.test("unknown_type", [&](testing & t) { test_unknown_type(t, f); }); + t.test("zero_candidates", [&](testing & t) { test_zero_candidates(t, f); }); + t.test("truncated", [&](testing & t) { test_truncated(t, f); }); + t.test("missing_dir", [&](testing & t) { test_missing_dir(t, f); }); + t.test("unreadable_file", [&](testing & t) { test_unreadable_file(t, f); }); + t.test("directory_path", [&](testing & t) { test_directory_path(t, f); }); + t.test("save_error", [&](testing & t) { test_save_error(t, f); }); + t.test("imatrix_swap", [&](testing & t) { test_imatrix_swap(t, f); }); + t.test("imatrix_parts", [&](testing & t) { test_imatrix_parts(t, f); }); + t.test("imatrix_order", [&](testing & t) { test_imatrix_order(t, f); }); + t.test("pruned_layer", [&](testing & t) { test_pruned_layer(t, f); }); + t.test("stats_order", [&](testing & t) { test_stats_order(t, f); }); + t.test("stats_missing", [&](testing & t) { test_stats_missing(t, f); }); + t.test("abort_callback", [&](testing & t) { test_abort_callback(t, f); }); + t.test("interrupt_first_call", [&](testing & t) { test_interrupt_first_call(t, f); }); + t.test("signal_handlers", [&](testing & t) { test_signal_handlers(t, f); }); + t.test("type_flags", [&](testing & t) { test_type_flags(t, f); }); + + return t.summary(); +} + +int main(int argc, char ** argv) { + testing t; + + const char * env = getenv("LLAMA_TEST_VERBOSE"); + verbose = env && std::string(env) == "1"; + t.verbose = verbose; + llama_log_set(log_callback, nullptr); + + if (argc > 1) { t.set_filter(argv[1]); } + + llama_backend_init(); + const std::filesystem::path dir = std::filesystem::temp_directory_path() / ("test-quantize-target-" + std::to_string(std::random_device{}())); + std::filesystem::create_directories(dir); + const int ret = run_tests(t, dir); + std::filesystem::remove_all(dir); + llama_backend_free(); + + return ret; +} diff --git a/tools/quantize/README.md b/tools/quantize/README.md index 27384bebf697..3d5cb72ce447 100644 --- a/tools/quantize/README.md +++ b/tools/quantize/README.md @@ -60,11 +60,19 @@ Options: * `--output-tensor-type` use a specific quant type for the output.weight tensor * `--token-embedding-type` use a specific quant type for the token embeddings tensor * `--keep-split` generate the quantized model in the same shards as the input file instead of a single quantized file +* `--dry-run` simulate the quantization process +* `--max-buffer-size MiB` cap the amount of tensor rows kept in memory while quantizing one tensor (default: 8192). Lower it to quantize models with very large tensors on a machine with little RAM Advanced options: -* `--tensor-type` quantize specific tensor(s) to specific quant types. Supports regex syntax. May be specified multiple times. +* `--tensor-type` quantize specific tensor(s) to specific quant types. Supports regex syntax. May be specified multiple times * `--prune-layers` prune (remove) the layers in the list -* `--override-kv` option to override model metadata by key in the quantized model. May be specified multiple times. +* `--override-kv` option to override model metadata by key in the quantized model. May be specified multiple times +* `--target-bpw` automatically choose quant types to meet an overall bits per weight (bpw) target +* `--target-size` automatically choose quant types to meet a file size target +* `--state-file` file name to store or load the bpw/size scores. If left unspecified it defaults to `-.bpw_state`; progress is automatically preserved upon interruptions (SIGTERM or Ctrl-C) allowing execution of the same command to resume the process +* `--target-exclude` comma-separated list of quant types (names or ordinals) that automatic quant type selection must ignore; for use with `--target-bpw`/`--target-size`. May be specified multiple times. A state checkpoint is not written while this option is active + +When using `--target-bpw` or `--target-size`, any tensors specified by `--tensor-type`, `--token-embedding-type`, or `--output-tensor-type` retain their defined types, with their total size counted toward the overall target. Quantization will fail if the budget allocated to these tensors leaves insufficient capacity for the remainder of the model. ## (Optional) Convert the multimodal components @@ -92,6 +100,16 @@ python convert_hf_to_gguf.py --mmproj --outfile mmproj-gemma-4-E2B-it-Q8_0.gguf ./llama-quantize input-model-f32.gguf q4_k_m 8 ``` +```bash +# simulate naive Q4_K_M quantization process. No model will be generated +./llama-quantize --dry-run input-model-f32.gguf q4_k_m 8 +``` + +```bash +# naive Q4_K_M quantization overriding general.name and model.rope.freq_base metadata values +./llama-quantize --override-kv general.name=str:"New model name" --override-kv model.rope.freq_base=float:1.234e+08 input-model-f32.gguf q4_k_m 8 +``` + ```bash # quantize model enabling re-quantization, leaving the output tensor unquantized and all others quantized at the same level (Q4_K) ./llama-quantize --allow-requantize --leave-output-tensor --pure input-model-f32.gguf q4_k_m 8 @@ -122,59 +140,69 @@ python convert_hf_to_gguf.py --mmproj --outfile mmproj-gemma-4-E2B-it-Q8_0.gguf ./llama-quantize --imatrix imatrix.gguf --override-kv qwen3moe.expert_used_count=int:16 --prune-layers 20,21,22 input-model-f32.gguf pruned-model-f32.gguf copy 8 ``` +```bash +# quantize model targeting a specific bpw average and save the target computations to the default file. Model type is optional and can be omitted +./llama-quantize --target-bpw 4.5678 --state-file --imatrix imatrix.gguf input-model-f32.gguf output-model.gguf +``` + +```bash +# quantize model targeting a specific bpw average using the default state checkpoint (if available) and ignoring IQ2_XXS, IQ2_XS and IQ2_S types (checkpoint is not saved) +./llama-quantize --target-bpw 4.5678 --target-exclude IQ2_XXS,IQ2_XS,IQ2_S --state-file --imatrix imatrix.gguf input-model-f32.gguf output-model.gguf +``` + +```bash +# quantize model targeting a specific bpw average reusing previous target computations in default file (e.g. input-model-8fd7a8bef0803042.bpw_state) +./llama-quantize --target-bpw 2.345 --state-file --imatrix imatrix.gguf input-model-f32.gguf output-model.gguf +``` + +```bash +# quantize model targeting a specific file size and save the target computations to a custom file. +./llama-quantize --target-size 1.5g --state-file my-state-file.dat --imatrix imatrix.gguf input-model-f32.gguf output-model.gguf +``` + ## Memory/Disk Requirements When running the larger models, make sure you have enough disk space to store all the intermediate files. As the models are currently fully loaded into memory, you will need adequate disk space to save them and sufficient RAM to load them. At the moment, memory and disk requirements are the same. For example (Llama 3.1): | Model | Original size | Quantized size (Q4_K_M) | -| ----: | ------------: | ----------------------: | +|------:|--------------:|------------------------:| | 8B | 32.1 GB | 4.9 GB | | 70B | 280.9 GB | 43.1 GB | | 405B | 1,625.1 GB | 249.1 GB | - ## Quantization Several quantization methods are supported. They differ in the resulting model disk size and inference speed. For example, ### [meta-llama/Llama-3.1-8B](https://huggingface.co/meta-llama/Llama-3.1-8B) -| Measure | IQ1_S | IQ1_M | IQ2_XXS | IQ2_XS | IQ2_S | IQ2_M | -| --------------------------- | ------------ | ------------ | ------------ | ------------- | ------------- | ------------ | -| bits/weight | 2.0042 | 2.1460 | 2.3824 | 2.5882 | 2.7403 | 2.9294 | -| size (GiB) | 1.87 | 2.01 | 2.23 | 2.42 | 2.56 | 2.74 | -| prompt processing t/s @ 512 | 858.88 ±1.22 | 847.99 ±0.47 | 852.39 ±0.85 | 826.99 ±12.51 | 783.55 ±13.73 | 787.68 ±7.00 | -| text generation t/s @ 128 | 79.73 ±0.79 | 72.92 ±0.14 | 79.86 ±0.22 | 78.04 ±0.46 | 77.30 ±2.47 | 74.44 ±0.15 | - -| Measure | IQ3_XXS | IQ3_XS | IQ3_S | IQ3_M | IQ4_XS | IQ4_NL | -| --------------------------- | ------------ | ------------ | ------------ | ------------- | ------------- | ------------ | -| bits/weight | 3.2548 | 3.4977 | 3.6606 | 3.7628 | 4.4597 | 4.6818 | -| size (GiB) | 3.04 | 3.27 | 3.42 | 3.52 | 4.17 | 4.38 | -| prompt processing t/s @ 512 | 813.88 ±6.53 | 708.71 ±1.26 | 798.78 ±8.81 | 768.70 ±13.73 | 771.80 ±11.38 | 806.03 ±7.07 | -| text generation t/s @ 128 | 73.95 ±0.20 | 71.67 ±0.54 | 69.31 ±0.63 | 70.15 ±0.33 | 77.51 ±0.20 | 76.63 ±0.28 | - - -| Measure | Q2_K_S | Q2_K | Q3_K_S | Q3_K_M | Q3_K_L | Q4_K_S | -| --------------------------- | ------------ | ------------ | ------------ | ------------ | ------------ | ------------ | -| bits/weight | 2.9697 | 3.1593 | 3.6429 | 3.9960 | 4.2979 | 4.6672 | -| size (GiB) | 2.78 | 2.95 | 3.41 | 3.74 | 4.02 | 4.36 | -| prompt processing t/s @ 512 | 798.91 ±6.40 | 784.45 ±7.85 | 752.17 ±7.94 | 783.44 ±9.92 | 761.17 ±7.55 | 818.55 ±9.58 | -| text generation t/s @ 128 | 90.01 ±0.12 | 79.85 ±0.20 | 69.84 ±0.18 | 71.68 ±0.22 | 69.38 ±0.49 | 76.71 ±0.20 | - -| Measure | Q4_K_S | Q4_K_M | Q5_K_S | Q5_K_M | Q6_K | Q8_0 | -| --------------------------- | ------------ | ------------- | ------------ | ------------ | ------------- | ------------ | -| bits/weight | 4.6672 | 4.8944 | 5.5704 | 5.7036 | 6.5633 | 8.5008 | -| size (GiB) | 4.36 | 4.58 | 5.21 | 5.33 | 6.14 | 7.95 | -| prompt processing t/s @ 512 | 818.55 ±9.58 | 821.81 ±21.44 | 752.52 ±0.99 | 758.69 ±7.43 | 812.01 ±10.82 | 865.09 ±8.30 | -| text generation t/s @ 128 | 76.71 ±0.20 | 71.93 ±1.52 | 69.53 ±0.18 | 67.23 ±1.08 | 58.67 ±3.13 | 50.93 ±0.08 | - -| Measure | F16 | -| --------------------------- | ------------ | -| bits/weight | 16.0005 | -| size (GiB) | 14.96 | -| prompt processing t/s @ 512 | 923.49 ±0.53 | -| text generation t/s @ 128 | 29.17 ±0.04 | +| Quant Type | bits/weight | size (GiB) | prompt processing t/s @ 512 | text generation t/s @ 128 | +|:----------:|------------:|-----------:|----------------------------:|--------------------------:| +| IQ1_S | 2.0042 | 1.87 | 858.88 ±1.22 | 79.73 ±0.79 | +| IQ1_M | 2.1460 | 2.01 | 847.99 ±0.47 | 72.92 ±0.14 | +| IQ2_XXS | 2.3824 | 2.23 | 852.39 ±0.85 | 79.86 ±0.22 | +| IQ2_XS | 2.5882 | 2.42 | 826.99 ±12.51 | 78.04 ±0.46 | +| IQ2_S | 2.7403 | 2.56 | 783.55 ±13.73 | 77.30 ±2.47 | +| IQ2_M | 2.9294 | 2.74 | 787.68 ±7.00 | 74.44 ±0.15 | +| IQ3_XXS | 3.2548 | 3.04 | 813.88 ±6.53 | 73.95 ±0.20 | +| IQ3_XS | 3.4977 | 3.27 | 708.71 ±1.26 | 71.67 ±0.54 | +| IQ3_S | 3.6606 | 3.42 | 798.78 ±8.81 | 69.31 ±0.63 | +| IQ3_M | 3.7628 | 3.52 | 768.70 ±13.73 | 70.15 ±0.33 | +| IQ4_XS | 4.4597 | 4.17 | 771.80 ±11.38 | 77.51 ±0.20 | +| IQ4_NL | 4.6818 | 4.38 | 806.03 ±7.07 | 76.63 ±0.28 | +| Q2_K_S | 2.9697 | 2.78 | 798.91 ±6.40 | 90.01 ±0.12 | +| Q2_K | 3.1593 | 2.95 | 784.45 ±7.85 | 79.85 ±0.20 | +| Q3_K_S | 3.6429 | 3.41 | 752.17 ±7.94 | 69.84 ±0.18 | +| Q3_K_M | 3.9960 | 3.74 | 783.44 ±9.92 | 71.68 ±0.22 | +| Q3_K_L | 4.2979 | 4.02 | 761.17 ±7.55 | 69.38 ±0.49 | +| Q4_K_S | 4.6672 | 4.36 | 818.55 ±9.58 | 76.71 ±0.20 | +| Q4_K_M | 4.8944 | 4.58 | 821.81 ±21.44 | 71.93 ±1.52 | +| Q5_K_S | 5.5704 | 5.21 | 752.52 ±0.99 | 69.53 ±0.18 | +| Q5_K_M | 5.7036 | 5.33 | 758.69 ±7.43 | 67.23 ±1.08 | +| Q6_K | 6.5633 | 6.14 | 812.01 ±10.82 | 58.67 ±3.13 | +| Q8_0 | 8.5008 | 7.95 | 865.09 ±8.30 | 50.93 ±0.08 | +| F16 | 16.0005 | 14.96 | 923.49 ±0.53 | 29.17 ±0.04 | ## Background information on llama-quantize @@ -194,3 +222,4 @@ Several quantization methods are supported. They differ in the resulting model d - [#5060 - Q3_K_XS](https://github.com/ggml-org/llama.cpp/pull/5060) - [#5196 - 3-bit i-quants](https://github.com/ggml-org/llama.cpp/pull/5196) - [quantization tuning](https://github.com/ggml-org/llama.cpp/pull/5320), [another one](https://github.com/ggml-org/llama.cpp/pull/5334), and [another one](https://github.com/ggml-org/llama.cpp/pull/5361) +- [target bpw/size](https://github.com/ggml-org/llama.cpp/pull/15550) diff --git a/tools/quantize/quantize.cpp b/tools/quantize/quantize.cpp index 0debcfddaffa..d58695196301 100644 --- a/tools/quantize/quantize.cpp +++ b/tools/quantize/quantize.cpp @@ -1,24 +1,24 @@ -#include "llama.h" - #include "build-info.h" #include "common.h" #include "imatrix-loader.h" -#include "gguf.h" - -#include -#include -#include +#include #include -#include +#include #include -#include -#include -#include -#include #include +#include +#include +#include + +#if defined(_WIN32) +#define WIN32_LEAN_AND_MEAN +#ifndef NOMINMAX +# define NOMINMAX +#endif +#include +#endif -// result of parsing --tensor-type option // changes to this struct must also be reflected in src/llama-quant.cpp struct tensor_type_option { std::string name; @@ -121,8 +121,8 @@ static bool try_parse_ftype(const std::string & ftype_str_in, llama_ftype & ftyp [[noreturn]] static void usage(const char * executable) { printf("usage: %s [--help] [--allow-requantize] [--leave-output-tensor] [--pure] [--imatrix] [--include-weights]\n", executable); - printf(" [--exclude-weights] [--output-tensor-type] [--token-embedding-type] [--tensor-type] [--tensor-type-file]\n"); - printf(" [--prune-layers] [--keep-split] [--override-kv] [--dry-run] [--max-buffer-size]\n"); + printf(" [--exclude-weights] [--output-tensor-type] [--token-embedding-type] [--tensor-type] [--tensor-type-file] [--prune-layers]\n"); + printf(" [--keep-split] [--override-kv] [--dry-run] [--max-buffer-size] [--target-bpw] [--target-size] [--target-exclude] [--state-file]\n"); printf(" model-f32.gguf [model-quant.gguf] type [nthreads]\n\n"); printf(" --allow-requantize\n"); printf(" allow requantizing tensors that have already been quantized\n"); @@ -145,7 +145,7 @@ static void usage(const char * executable) { printf(" use this ggml_type for the token embeddings tensor\n"); printf(" --tensor-type tensor_name=ggml_type\n"); printf(" quantize this tensor to this ggml_type\n"); - printf(" this is an advanced option to selectively quantize tensors. may be specified multiple times.\n"); + printf(" this is an advanced option to selectively quantize tensors; may be specified multiple times.\n"); printf(" example: --tensor-type attn_q=q8_0\n"); printf(" --tensor-type-file tensor_types.txt\n"); printf(" list of tensors to quantize to a specific ggml_type\n"); @@ -157,7 +157,7 @@ static void usage(const char * executable) { printf(" --keep-split\n"); printf(" generate quantized model in the same shards as input\n"); printf(" --override-kv KEY=TYPE:VALUE\n"); - printf(" override model metadata by key in the quantized model. may be specified multiple times.\n"); + printf(" override model metadata by key in the quantized model; may be specified multiple times.\n"); printf(" WARNING: this is an advanced option, use with care.\n"); printf(" --dry-run\n"); printf(" calculate and show the final quantization size without performing quantization\n"); @@ -165,7 +165,21 @@ static void usage(const char * executable) { printf(" --max-buffer-size MiB\n"); printf(" max amount of tensor rows kept in memory while quantizing one tensor (default: 8192)\n"); printf(" lower it to quantize models with very large tensors on a machine with little RAM\n\n"); - printf("note: --include-weights and --exclude-weights cannot be used together\n\n"); + printf(" --target-bpw n\n"); + printf(" target a bits per weight (bpw); must be a number between 0.0 and 16.0, 0 means the smallest possible model\n"); + printf(" advanced option to automatically select quantization types to achieve a total bits per weight (bpw) target\n\n"); + printf(" --target-size n\n"); + printf(" target a file size; must be 0 or more, 0 means the smallest possible model\n"); + printf(" advanced option to automatically select quantization types to achieve a total file size\n"); + printf(" allowed units: b, k|kib, m|mib, g|gib, t|tib; defaults to b (bytes) if none is provided\n\n"); + printf(" --state-file [filename]\n"); + printf(" file name to use/save; if none is provided, the default name will be used\n\n"); + printf(" --target-exclude type[,type...]\n"); + printf(" comma-separated ggml_type (names or ordinals) that automatic quant type selection must ignore\n"); + printf(" advanced option for --target-bpw/--target-size; may be specified multiple times\n\n"); + printf("note: --include-weights and --exclude-weights cannot be used together\n"); + printf(" --target-bpw and --target-size cannot be used together\n"); + printf(" --exclude-weights excludes tensor NAMES, while --target-exclude excludes quant TYPES\n\n"); printf("-----------------------------------------------------------------------------\n"); printf(" allowed quantization types\n"); printf("-----------------------------------------------------------------------------\n\n"); @@ -180,7 +194,13 @@ static void usage(const char * executable) { exit(1); } -static int load_imatrix(const std::string & imatrix_file, std::vector & imatrix_datasets, std::unordered_map> & imatrix_data) { +static int load_imatrix(const std::string & imatrix_file, + std::vector & imatrix_datasets, + std::unordered_map> & values_data, + std::unordered_map> & activations_data, + std::unordered_map> & statistics_data, + std::vector & statistics_schema) +{ common_imatrix loaded; if (!common_imatrix_load(imatrix_file, loaded)) { fprintf(stderr, "%s: failed to load imatrix from '%s'\n", __func__, imatrix_file.c_str()); @@ -193,59 +213,84 @@ static int load_imatrix(const std::string & imatrix_file, std::vector 0.0f) { for (int64_t i = 0; i < ne0; ++i) { - e[j*ne0 + i] = entry.sums[j*ne0 + i] / count; + values[j*ne0 + i] = entry.sums[j*ne0 + i] / count; } } else { for (int64_t i = 0; i < ne0; ++i) { - e[j*ne0 + i] = 1; + values[j*ne0 + i] = 1; } } } + } else { + const int64_t ncall = entry.counts[0]; + if (ncall > 0) { + for (int64_t i = 0; i < nsums; ++i) { + values[i] = entry.sums[i] / ncall; + } + } else { + for (int64_t i = 0; i < nsums; ++i) { + values[i] = entry.sums[i]; + } + } + } - if (getenv("LLAMA_TRACE")) { - float max_count = 0.0f; + if (!entry.activations.empty()) { + auto & activations = activations_data[name]; + activations.resize(entry.activations.size()); + if (!loaded.is_legacy) { for (int64_t j = 0; j < ncounts; ++j) { const float count = (float) entry.counts[j]; - if (count > max_count) { - max_count = count; + if (count > 0.0f) { + for (int64_t i = 0; i < ne0; ++i) { + activations[j*ne0 + i] = entry.activations[j*ne0 + i] / count; + } + } else { + for (int64_t i = 0; i < ne0; ++i) { + activations[j*ne0 + i] = 0; + } } } - printf("%s: loaded data (size = %6d, n_tokens = %6d, n_chunks = %6d) for '%s'\n", - __func__, int(e.size()), int(max_count), int(max_count / loaded.chunk_size), name.c_str()); - } - } else { - // Legacy format: sums contain (raw/count)*ncall, divide by ncall - const int64_t ncall = entry.counts.empty() ? 0 : entry.counts[0]; - if (ncall > 0) { - for (size_t i = 0; i < entry.sums.size(); ++i) { - e[i] = entry.sums[i] / ncall; - } } else { - for (size_t i = 0; i < entry.sums.size(); ++i) { - e[i] = entry.sums[i]; + const int64_t ncall = entry.counts[0]; + if (ncall > 0) { + for (size_t i = 0; i < entry.activations.size(); ++i) { + activations[i] = entry.activations[i] / ncall; + } + } else { + for (size_t i = 0; i < entry.activations.size(); ++i) { + activations[i] = entry.activations[i]; + } } } + } - if (getenv("LLAMA_TRACE")) { - printf("%s: loaded data (size = %6d, ncall = %6d) for '%s'\n", - __func__, int(e.size()), int(ncall), name.c_str()); - } + if (!entry.stats.empty()) { + statistics_data[name] = entry.stats; } } imatrix_datasets = std::move(loaded.datasets); + statistics_schema = std::move(loaded.stats_schema); if (!imatrix_datasets.empty()) { printf("%s: imatrix datasets=['%s'", __func__, imatrix_datasets[0].c_str()); @@ -255,7 +300,7 @@ static int load_imatrix(const std::string & imatrix_file, std::vector & imatrix_dataset, const std::vector & included_weights, const std::vector & excluded_weights, - std::unordered_map> & imatrix_data) { + std::unordered_map> & values_data, + std::unordered_map> & activations_data, + std::unordered_map> & statistics_data, + std::vector & stats_schema) { int m_last_call = -1; if (!imatrix_file.empty()) { - m_last_call = load_imatrix(imatrix_file, imatrix_dataset, imatrix_data); + m_last_call = load_imatrix(imatrix_file, imatrix_dataset, values_data, activations_data, statistics_data, stats_schema); } - if (imatrix_data.empty()) { + if (values_data.empty()) { return m_last_call; } if (!excluded_weights.empty()) { for (const auto & name : excluded_weights) { - for (auto it = imatrix_data.begin(); it != imatrix_data.end();) { - auto pos = it->first.find(name); + for (auto vt = values_data.begin(); vt != values_data.end();) { + auto pos = vt->first.find(name); + if (pos != std::string::npos) { + vt = values_data.erase(vt); + } else { + ++vt; + } + } + for (auto at = activations_data.begin(); at != activations_data.end();) { + auto pos = at->first.find(name); + if (pos != std::string::npos) { + at = activations_data.erase(at); + } else { + ++at; + } + } + for (auto st = statistics_data.begin(); st != statistics_data.end();) { + auto pos = st->first.find(name); if (pos != std::string::npos) { - it = imatrix_data.erase(it); + st = statistics_data.erase(st); } else { - ++it; + ++st; } } } } if (!included_weights.empty()) { - std::unordered_map> tmp; + std::unordered_map> tmp_values; + std::unordered_map> tmp_activations; + std::unordered_map> tmp_statistics; for (const auto & name : included_weights) { - for (auto & e : imatrix_data) { + for (auto & e : values_data) { auto pos = e.first.find(name); if (pos != std::string::npos) { - tmp.emplace(std::move(e)); + tmp_values.emplace(std::move(e)); + } + } + for (auto & a : activations_data) { + auto pos = a.first.find(name); + if (pos != std::string::npos) { + tmp_activations.emplace(std::move(a)); + } + } + for (auto & s : statistics_data) { + auto pos = s.first.find(name); + if (pos != std::string::npos) { + tmp_statistics.emplace(std::move(s)); } } } - imatrix_data = std::move(tmp); - } - if (!imatrix_data.empty()) { - printf("%s: have %d importance matrix entries\n", __func__, int(imatrix_data.size())); + values_data = std::move(tmp_values); + activations_data = std::move(tmp_activations); + statistics_data = std::move(tmp_statistics); } + return m_last_call; } @@ -389,6 +467,139 @@ static bool parse_layer_prune(const char * data, std::vector & prune_layers return true; } +static bool parse_target_bpw(const char * data, float & target_bpw) { + if (!data) { + printf("\n%s: no target bits per weight (bpw) provided\n\n", __func__); + return false; + } + + try { + target_bpw = std::stof(data); + if (!std::isfinite(target_bpw) || target_bpw < 0.0f || target_bpw > 16.0f) { + printf("\n%s: target bits per weight (bpw) must be a number between 0.0 and 16.0\n\n", __func__); + return false; + } + } + catch (const std::exception & e) { + printf("\n%s: '%s' is not valid. Target bits per weight (bpw) must be a number between 0.0 and 16.0\n\n", __func__, data); + return false; + } + + return true; +} + +static bool parse_target_size(const char * data, int64_t & target_size) { + if (!data) { + printf("\n%s: no target file size provided\n\n", __func__); + return false; + } + + char * end = nullptr; + const double val = std::strtod(data, &end); + if (end == data || !std::isfinite(val) || val < 0) { + printf("\n%s: invalid target file size '%s'\n\n", __func__, data); + return false; + } + + std::string suffix(end); + for (auto & c : suffix) { c = std::tolower(c); } + + int64_t mul = 0; + if (suffix.empty() || suffix == "b") { + mul = 1; + } else if (suffix == "k" || suffix == "kib") { + mul = 1024; + } else if (suffix == "m" || suffix == "mib") { + mul = 1024 * 1024; + } else if (suffix == "g" || suffix == "gib") { + mul = 1024 * 1024 * 1024; + } else if (suffix == "t" || suffix == "tib") { + mul = 1024LL * 1024 * 1024 * 1024; + } else { + printf("\n%s: invalid unit '%s' in '%s'. Allowed: b, k or kib, m or mib, g or gib, t or tib\n\n", __func__, suffix.c_str(), data); + return false; + } + + if (val * mul >= (double)INT64_MAX) { + printf("\n%s: invalid target file size '%s'\n\n", __func__, data); + return false; + } + + target_size = (int64_t)(val * mul); + return true; +} + +static bool parse_target_exclude(const char * data, std::vector & target_exclude) { + if (!data) { + printf("\n%s: no quant types provided\n\n", __func__); + return false; + } + + const auto tokens = string_split(data, ','); + for (const auto & token : tokens) { + ggml_type type = GGML_TYPE_COUNT; + for (int i = 0; i < GGML_TYPE_COUNT; ++i) { + const char * name = ggml_type_name((ggml_type)i); + if (name && striequals(name, token.c_str())) { + type = (ggml_type)i; + break; + } + } + + if (type == GGML_TYPE_COUNT) { + const bool numeric = !token.empty() && std::all_of(token.begin(), token.end(), [](unsigned char c) { return std::isdigit(c); }); + const long ordinal = numeric ? std::strtol(token.c_str(), nullptr, 10) : -1; + if (ordinal >= 0 && ordinal < GGML_TYPE_COUNT) { + type = (ggml_type)ordinal; + } + } + + if (type == GGML_TYPE_COUNT) { + printf("\n%s: invalid quant type '%s' for --target-exclude\n\n", __func__, token.c_str()); + return false; + } + + if (std::find(target_exclude.begin(), target_exclude.end(), type) == target_exclude.end()) { + target_exclude.emplace_back(type); + } + } + + return true; +} + +static const char * get_ftype(const float bpw) { + const std::map quant_bpw = { + {1.5625, "IQ1_S"}, + {1.7500, "IQ1_M"}, + {2.0625, "IQ2_XXS"}, + {2.3125, "IQ2_XS"}, + {2.5625, "IQ2_S"}, + {2.6250, "Q2_K"}, + {3.0625, "IQ3_XXS"}, + {3.4375, "Q3_K"}, + {4.2500, "IQ4_XS"}, + {4.5000, "Q4_K"}, + {5.5000, "Q5_K"}, + {6.5625, "Q6_K"}, + {8.5000, "Q8_0"}, + {16.0000, "F16"} + }; + + return quant_bpw.lower_bound(bpw)->second; +} + +static std::atomic interrupt_signal{ 0 }; + +#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32) +// try to save the state checkpoint if interrupted while scoring +static void signal_handler(int signo) { + int expected = 0; + interrupt_signal.compare_exchange_strong(expected, signo); +} +#endif + +static bool is_interrupted(void * /*data*/) { return interrupt_signal.load() != 0; } + // satisfies -Wmissing-declarations int llama_quantize(int argc, char ** argv); @@ -402,10 +613,14 @@ int llama_quantize(int argc, char ** argv) { int arg_idx = 1; std::string imatrix_file; - std::vector included_weights, excluded_weights; + std::vector included_weights; + std::vector excluded_weights; std::vector kv_overrides; std::vector tensor_type_opts; std::vector prune_layers; + std::vector target_exclude; + float target_bpw = -1.0f; + int64_t target_size = -1; for (; arg_idx < argc && strncmp(argv[arg_idx], "--", 2) == 0; arg_idx++) { if (strcmp(argv[arg_idx], "--leave-output-tensor") == 0) { @@ -436,6 +651,25 @@ int llama_quantize(int argc, char ** argv) { if (arg_idx == argc-1 || !parse_tensor_type_file(argv[++arg_idx], tensor_type_opts)) { usage(argv[0]); } + } else if (strcmp(argv[arg_idx], "--target-bpw") == 0) { + if (arg_idx == argc-1 || !parse_target_bpw(argv[++arg_idx], target_bpw)) { + usage(argv[0]); + } + } else if (strcmp(argv[arg_idx], "--target-size") == 0) { + if (arg_idx == argc-1 || !parse_target_size(argv[++arg_idx], target_size)) { + usage(argv[0]); + } + } else if (strcmp(argv[arg_idx], "--target-exclude") == 0) { + if (arg_idx == argc-1 || !parse_target_exclude(argv[++arg_idx], target_exclude)) { + usage(argv[0]); + } + } else if (strcmp(argv[arg_idx], "--state-file") == 0) { + if (arg_idx + 1 < argc && argv[arg_idx + 1][0] != '-') { + params.state_file = argv[++arg_idx]; + } else { + static char empty[] = ""; + params.state_file = empty; + } } else if (strcmp(argv[arg_idx], "--prune-layers") == 0) { if (arg_idx == argc-1 || !parse_layer_prune(argv[++arg_idx], prune_layers)) { usage(argv[0]); @@ -492,20 +726,28 @@ int llama_quantize(int argc, char ** argv) { if (!included_weights.empty() && !excluded_weights.empty()) { usage(argv[0]); } + if (target_bpw != -1.0f && target_size != -1) { + usage(argv[0]); + } std::vector imatrix_datasets; - std::unordered_map> imatrix_data; - int m_last_call = prepare_imatrix(imatrix_file, imatrix_datasets, included_weights, excluded_weights, imatrix_data); - - std::vector i_data; - std::vector t_override; - if (!imatrix_data.empty()) { - i_data.reserve(imatrix_data.size() + 1); - for (const auto & kv : imatrix_data) { - i_data.push_back({kv.first.c_str(), kv.second.data(), kv.second.size()}); - } - i_data.push_back({nullptr, nullptr, 0}); // array terminator - params.imatrix = i_data.data(); + std::unordered_map> values_data; + std::unordered_map> activations_data; + std::unordered_map> statistics_data; + std::vector stats_schema; + int m_last_call = prepare_imatrix(imatrix_file, imatrix_datasets, included_weights, excluded_weights, values_data, activations_data, statistics_data, stats_schema); + + std::vector vdata; + std::vector adata; + std::vector sdata; + std::vector sschema; + std::vector tto; + + if (!values_data.empty()) { + vdata.reserve(values_data.size() + 1); + for (const auto & kv : values_data) { vdata.push_back({kv.first.c_str(), kv.second.data(), kv.second.size()}); } + vdata.push_back({nullptr, nullptr, 0}); // array terminator + params.imatrix = vdata.data(); { llama_model_kv_override kvo; std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_FILE); @@ -529,7 +771,7 @@ int llama_quantize(int argc, char ** argv) { llama_model_kv_override kvo; std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_N_ENTRIES); kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT; - kvo.val_i64 = imatrix_data.size(); + kvo.val_i64 = values_data.size(); kv_overrides.emplace_back(std::move(kvo)); } if (m_last_call > 0) { @@ -540,23 +782,47 @@ int llama_quantize(int argc, char ** argv) { kv_overrides.emplace_back(std::move(kvo)); } } + if (!activations_data.empty()) { + adata.reserve(activations_data.size() + 1); + for (const auto & kv : activations_data) { adata.push_back({kv.first.c_str(), kv.second.data(), kv.second.size()}); } + adata.push_back({nullptr, nullptr, 0}); // array terminator + params.activations = adata.data(); + } + if (!statistics_data.empty()) { + sdata.reserve(statistics_data.size() + 1); + for (const auto & kv : statistics_data) { sdata.push_back({kv.first.c_str(), kv.second.data(), kv.second.size()}); } + sdata.push_back({nullptr, nullptr, 0}); // array terminator + params.statistics = sdata.data(); + sschema.reserve(stats_schema.size() + 1); + for (const auto & name : stats_schema) { sschema.push_back(name.c_str()); } + sschema.push_back(nullptr); // array terminator + params.stats_schema = sschema.data(); + } if (!kv_overrides.empty()) { kv_overrides.emplace_back(); kv_overrides.back().key[0] = 0; params.kv_overrides = kv_overrides.data(); } if (!tensor_type_opts.empty()) { - t_override.reserve(tensor_type_opts.size() + 1); - for (const auto & tt : tensor_type_opts) { - t_override.push_back({tt.name.c_str(), tt.type}); - } - t_override.push_back({nullptr, GGML_TYPE_COUNT}); // array terminator - params.tt_overrides = t_override.data(); + tto.reserve(tensor_type_opts.size() + 1); + for (const auto & tt : tensor_type_opts) { tto.push_back({tt.name.c_str(), tt.type}); } + tto.push_back({nullptr, GGML_TYPE_COUNT}); // array terminator + params.tt_overrides = tto.data(); + } + if (!target_exclude.empty()) { + target_exclude.push_back(GGML_TYPE_COUNT); // array terminator + params.target_exclude = target_exclude.data(); } if (!prune_layers.empty()) { prune_layers.push_back(-1); // array terminator params.prune_layers = prune_layers.data(); } + if (target_bpw != -1.0f) { + params.target_bpw = target_bpw; + } + if (target_size != -1) { + params.target_size = target_size; + } llama_backend_init(); @@ -567,6 +833,7 @@ int llama_quantize(int argc, char ** argv) { std::string ftype_str; std::string suffix = ".gguf"; + std::vector tmp_argv(argv, argv + argc); if (try_parse_ftype(argv[arg_idx], params.ftype, ftype_str)) { // argv[arg_idx] is the ftype directly: if (!params.dry_run) { @@ -594,7 +861,22 @@ int llama_quantize(int argc, char ** argv) { } arg_idx++; - if (argc <= arg_idx) { + // If --target-bpw or --target-size are set, select a quantization type and ignore any user specified type + if (params.target_bpw != -1.0f || params.target_size != -1) { + auto * ftype = params.target_bpw != -1.0f ? const_cast(get_ftype(params.target_bpw)) : const_cast("F16"); + bool added_type = false; + if (argc == arg_idx) { + tmp_argv.push_back(ftype); + added_type = true; + } else { + tmp_argv[arg_idx] = ftype; + } + tmp_argv.push_back(nullptr); + argv = const_cast(tmp_argv.data()); + if (added_type) { + argc++; + } + } else if (argc <= arg_idx) { fprintf(stderr, "%s: missing ftype\n", __func__); return 1; } @@ -639,6 +921,24 @@ int llama_quantize(int argc, char ** argv) { } fprintf(stderr, "\n"); + // handle SIGINT and SIGTERM + { +#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) + struct sigaction sigint_action; + sigint_action.sa_handler = signal_handler; + sigemptyset(&sigint_action.sa_mask); + sigint_action.sa_flags = SA_RESTART; + sigaction(SIGINT, &sigint_action, nullptr); + sigaction(SIGTERM, &sigint_action, nullptr); +#elif defined (_WIN32) + auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL { + return (ctrl_type == CTRL_C_EVENT) ? (signal_handler(SIGINT), true) : false; + }; + SetConsoleCtrlHandler(reinterpret_cast(console_ctrl_handler), true); +#endif + params.abort_callback = is_interrupted; + } + const int64_t t_main_start_us = llama_time_us(); int64_t t_quantize_us = 0; @@ -649,7 +949,16 @@ int llama_quantize(int argc, char ** argv) { if (llama_model_quantize(fname_inp.c_str(), fname_out.c_str(), ¶ms)) { fprintf(stderr, "%s: failed to quantize model from '%s'\n", __func__, fname_inp.c_str()); - return 1; + const int signo = interrupt_signal.load(); +#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) + // ensure that a calling shell or script stops too... + if (signo) { + signal(signo, SIG_DFL); + raise(signo); + } +#endif + // ...as a shell reports a process that the signal killed + return signo ? 128 + signo : 1; } t_quantize_us = llama_time_us() - t_start_us; From 239242322dc24e8c15a458b1beae5064e3358cf8 Mon Sep 17 00:00:00 2001 From: "Piotr Wilkin (ilintar)" Date: Mon, 23 Nov 2026 18:17:11 +0100 Subject: [PATCH 028/275] ggml: compact bias on the existing FLASH_ATTN_EXT (#32740) * compact bias on the existing FLASH_ATTN_EXT for CUDA, ROCm and Vulkan * fixup! compact bias on the existing FLASH_ATTN_EXT for CUDA, ROCm and Vulkan * remove the Vulkan support from this PR * move the CUDA/HIP and Inkling 2 graph changes out of this PR * CPU reference implementation of the indexed bias * move the indexed bias test to test-backend-ops, add the bias in F32 on CPU * incorporate review remarks --- ggml/include/ggml.h | 9 ++ ggml/src/ggml-backend-meta.cpp | 4 + ggml/src/ggml-cann/ggml-cann.cpp | 4 +- ggml/src/ggml-cpu/ggml-cpu.cpp | 4 + ggml/src/ggml-cpu/ops.cpp | 28 +++- ggml/src/ggml-cuda/fattn.cu | 4 + ggml/src/ggml-et/ggml-et.cpp | 1 + ggml/src/ggml-hexagon/htp-kparams.cpp | 4 +- ggml/src/ggml-metal/ggml-metal-device.m | 3 + ggml/src/ggml-opencl/ggml-opencl.cpp | 4 +- ggml/src/ggml-openvino/ggml-openvino.cpp | 4 + ggml/src/ggml-sycl/ggml-sycl.cpp | 4 +- ggml/src/ggml-virtgpu/ggml-backend-device.cpp | 4 + ggml/src/ggml-vulkan/ggml-vulkan.cpp | 3 +- ggml/src/ggml-webgpu/ggml-webgpu.cpp | 5 +- ggml/src/ggml-zdnn/fattn.cpp | 2 +- ggml/src/ggml.c | 27 ++++ tests/test-backend-ops.cpp | 133 ++++++++++++++++++ 18 files changed, 232 insertions(+), 15 deletions(-) diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h index 2f466e2e4e46..161e8e0cef47 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -2292,6 +2292,15 @@ extern "C" { struct ggml_tensor * a, struct ggml_tensor * sinks); + GGML_API bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a); + + // Add table[indices[key, query], head, query] to the mask, in F32. + // Queries from all streams are flattened in stream order. Indices must be in [0, table->ne[0]). + GGML_API void ggml_flash_attn_ext_add_indexed_bias( + struct ggml_tensor * a, + struct ggml_tensor * table, + struct ggml_tensor * indices); + // TODO: needs to be adapted to ggml_flash_attn_ext GGML_API struct ggml_tensor * ggml_flash_attn_back( struct ggml_context * ctx, diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp index 54d85b597fda..9aed3b7808b8 100644 --- a/ggml/src/ggml-backend-meta.cpp +++ b/ggml/src/ggml-backend-meta.cpp @@ -152,6 +152,10 @@ static ggml_backend_buffer_type_t ggml_backend_meta_device_get_buffer_type(ggml_ static ggml_backend_buffer_type_t ggml_backend_meta_device_get_host_buffer_type(ggml_backend_dev_t dev); static bool ggml_backend_meta_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) { + if (ggml_flash_attn_ext_has_indexed_bias(op)) { + return false; + } + GGML_ASSERT(ggml_backend_dev_is_meta(dev)); const ggml_backend_meta_device_context * meta_dev_ctx = (const ggml_backend_meta_device_context *) dev->context; return std::all_of(meta_dev_ctx->simple_devs.begin(), meta_dev_ctx->simple_devs.end(), diff --git a/ggml/src/ggml-cann/ggml-cann.cpp b/ggml/src/ggml-cann/ggml-cann.cpp index 0adc8680f5a4..4ea2f216d066 100644 --- a/ggml/src/ggml-cann/ggml-cann.cpp +++ b/ggml/src/ggml-cann/ggml-cann.cpp @@ -2679,8 +2679,8 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten return true; case GGML_OP_FLASH_ATTN_EXT: { - // K/V row lists (ggml_flash_attn_ext_rows) are not supported - if (op->src[5] != nullptr) { + // K/V row lists and indexed bias are not supported + if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) { return false; } #ifdef ASCEND_310P diff --git a/ggml/src/ggml-cpu/ggml-cpu.cpp b/ggml/src/ggml-cpu/ggml-cpu.cpp index 29783400186d..f6a9f5cba20a 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.cpp +++ b/ggml/src/ggml-cpu/ggml-cpu.cpp @@ -422,6 +422,10 @@ static ggml_backend_buffer_t ggml_backend_cpu_device_buffer_from_host_ptr(ggml_b } static bool ggml_backend_cpu_device_supports_op(ggml_backend_dev_t dev, const struct ggml_tensor * op) { + if (ggml_flash_attn_ext_has_indexed_bias(op)) { + return false; + } + const struct ggml_tensor * src0 = op->src[0]; const struct ggml_tensor * src1 = op->src[1]; diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index f984f13a6c3c..26b4a01c96eb 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -8981,6 +8981,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( const ggml_tensor * mask = dst->src[3]; const ggml_tensor * sinks = dst->src[4]; const ggml_tensor * kv_rows = dst->src[5]; + const ggml_tensor * bias_table = dst->src[6]; + const ggml_tensor * bias_indices = dst->src[7]; GGML_TENSOR_LOCALS(int64_t, neq, q, ne) GGML_TENSOR_LOCALS(size_t, nbq, q, nb) @@ -9022,6 +9024,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( const int64_t rv2 = neq2/nev2; const int64_t rv3 = neq3/nev3; + const int64_t n_bins = bias_table ? bias_table->ne[0] : 0; + // parallelize by q rows using ggml_vec_dot_f32 float scale = 1.0f; @@ -9085,12 +9089,21 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( const int32_t * rows = kv_rows ? (const int32_t *) ((const char *) kv_rows->data + iq3*kv_rows->nb[1]) : nullptr; + // bias rows of this query and head, queries of all streams are flattened + const float * bias = bias_table ? (const float *) ((const char *) bias_table->data + (iq3*neq1 + iq1)*bias_table->nb[2] + iq2*bias_table->nb[1]) : nullptr; + const int32_t * bins = bias_indices ? (const int32_t *) ((const char *) bias_indices->data + (iq3*neq1 + iq1)*bias_indices->nb[1]) : nullptr; + // online softmax / attention // loop over n_kv and n_head_kv // ref: https://arxiv.org/pdf/2112.05682.pdf for (int64_t ic = ic_start; ic < ic_end; ++ic) { - const float mv = mp ? slope*GGML_CPU_FP16_TO_FP32(mp[ic]) : 0.0f; + float mv = mp ? GGML_CPU_FP16_TO_FP32(mp[ic]) : 0.0f; + if (bias) { + GGML_ASSERT(bins[ic] >= 0 && bins[ic] < n_bins); + mv += bias[bins[ic]]; + } + mv *= slope; if (mv == -INFINITY) { continue; } @@ -9268,6 +9281,10 @@ static void ggml_compute_forward_flash_attn_ext_tiled( const ggml_tensor * kv_rows = dst->src[5]; const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : nek1; + const ggml_tensor * bias_table = dst->src[6]; + const ggml_tensor * bias_indices = dst->src[7]; + const int64_t n_bins = bias_table ? bias_table->ne[0] : 0; + int ir = ir0; while (ir < ir1) { // q indices for the start of this tile @@ -9346,8 +9363,15 @@ static void ggml_compute_forward_flash_attn_ext_tiled( bool can_skip = true; for (int tq = 0; tq < tile_rows; tq++) { const ggml_fp16_t * mp_row = (const ggml_fp16_t *)((const char *) mask->data + (iq1 + tq)*mask->nb[1] + (iq2%mask->ne[2])*mask->nb[2] + (iq3%mask->ne[3])*mask->nb[3]); + const float * bias = bias_table ? (const float *) ((const char *) bias_table->data + (iq3*neq1 + iq1 + tq)*bias_table->nb[2] + iq2*bias_table->nb[1]) : nullptr; + const int32_t * bins = bias_indices ? (const int32_t *) ((const char *) bias_indices->data + (iq3*neq1 + iq1 + tq)*bias_indices->nb[1]) : nullptr; for (int tk = 0; tk < kv_tile; tk++) { - mask32[tq * KV_TILE_SZ + tk] = slope * GGML_CPU_FP16_TO_FP32(mp_row[ic + tk]); + float m = GGML_CPU_FP16_TO_FP32(mp_row[ic + tk]); + if (bias) { + GGML_ASSERT(bins[ic + tk] >= 0 && bins[ic + tk] < n_bins); + m += bias[bins[ic + tk]]; + } + mask32[tq * KV_TILE_SZ + tk] = slope * m; if (mask32[tq * KV_TILE_SZ + tk] != -INFINITY) { can_skip = false; } diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 10aa5af15863..b37065c31dfb 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -582,6 +582,10 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const return BEST_FATTN_KERNEL_NONE; #endif// FLASH_ATTN_AVAILABLE + if (ggml_flash_attn_ext_has_indexed_bias(dst)) { + return BEST_FATTN_KERNEL_NONE; + } + const ggml_tensor * KQV = dst; const ggml_tensor * Q = dst->src[0]; const ggml_tensor * K = dst->src[1]; diff --git a/ggml/src/ggml-et/ggml-et.cpp b/ggml/src/ggml-et/ggml-et.cpp index 53e64b323e5a..e575ee78b45c 100644 --- a/ggml/src/ggml-et/ggml-et.cpp +++ b/ggml/src/ggml-et/ggml-et.cpp @@ -1277,6 +1277,7 @@ static bool ggml_backend_et_device_supports_op(ggml_backend_dev_t dev, const ggm if (op->type == GGML_TYPE_F32 && op->src[0] && op->src[0]->type == GGML_TYPE_F32 && op->src[1] && (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) && op->src[2] && (op->src[2]->type == GGML_TYPE_F32 || op->src[2]->type == GGML_TYPE_F16) && op->src[4] == nullptr && op->src[5] == nullptr && + !ggml_flash_attn_ext_has_indexed_bias(op) && ggml_is_contiguous_rows(op) && ggml_is_contiguous_rows(op->src[0])) { float max_bias = 0.0f; float logit_softcap = 0.0f; diff --git a/ggml/src/ggml-hexagon/htp-kparams.cpp b/ggml/src/ggml-hexagon/htp-kparams.cpp index 6d365b8119c7..4e3c5cb8d3df 100644 --- a/ggml/src/ggml-hexagon/htp-kparams.cpp +++ b/ggml/src/ggml-hexagon/htp-kparams.cpp @@ -355,8 +355,8 @@ static bool htp_kparams_solve_flash_attn( return false; } - // K/V row lists (ggml_flash_attn_ext_rows) are not supported - if (op->src[5] != nullptr) { + // K/V row lists and indexed bias are not supported + if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) { return false; } diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index 293400ff256f..9afaaca3697c 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1747,6 +1747,9 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te case GGML_OP_ROLL: return ggml_is_contiguous(op->src[0]); case GGML_OP_FLASH_ATTN_EXT: + if (ggml_flash_attn_ext_has_indexed_bias(op)) { + return false; + } // K/V row lists (ggml_flash_attn_ext_rows): one list of cache rows per q slice if (op->src[5] != NULL) { const struct ggml_tensor * kv_rows = op->src[5]; diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index 05a05fe9f95f..2a3f709a2f30 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -12662,8 +12662,8 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te case GGML_OP_MEAN: return op->src[0]->type == GGML_TYPE_F32; case GGML_OP_FLASH_ATTN_EXT: { - // K/V row lists (ggml_flash_attn_ext_rows) are not supported - if (op->src[5] != nullptr) { + // K/V row lists and indexed bias are not supported + if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) { return false; } #ifdef GGML_OPENCL_USE_ADRENO_KERNELS diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index b331349d1262..7e64c03c2bc1 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -1929,6 +1929,10 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { return {false, "FLASH_ATTN_EXT gemma3n pattern is not supported"}; } + if (ggml_flash_attn_ext_has_indexed_bias(op)) { + return {false, "FLASH_ATTN_EXT with indexed bias is not supported"}; + } + // K/V row lists (ggml_flash_attn_ext_rows) are not supported if (op->src[5] != nullptr) { return {false, "FLASH_ATTN_EXT with K/V row lists is not supported"}; diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp index 7dda19dfd761..75df12c733cb 100644 --- a/ggml/src/ggml-sycl/ggml-sycl.cpp +++ b/ggml/src/ggml-sycl/ggml-sycl.cpp @@ -7741,8 +7741,8 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons case GGML_OP_SOLVE_TRI: return op->src[0]->ne[0] <= SYCL_SOLVE_TRI_MAX_N && op->src[1]->ne[0] <= SYCL_SOLVE_TRI_MAX_K; case GGML_OP_FLASH_ATTN_EXT: - // K/V row lists (ggml_flash_attn_ext_rows) are not supported - return op->src[5] == nullptr && ggml_sycl_flash_attn_ext_supported(device, op); + // K/V row lists and indexed bias are not supported + return op->src[5] == nullptr && !ggml_flash_attn_ext_has_indexed_bias(op) && ggml_sycl_flash_attn_ext_supported(device, op); default: return false; } diff --git a/ggml/src/ggml-virtgpu/ggml-backend-device.cpp b/ggml/src/ggml-virtgpu/ggml-backend-device.cpp index 86df4cc5f3b2..e4d84fc98d27 100644 --- a/ggml/src/ggml-virtgpu/ggml-backend-device.cpp +++ b/ggml/src/ggml-virtgpu/ggml-backend-device.cpp @@ -30,6 +30,10 @@ static void ggml_backend_remoting_device_get_memory(ggml_backend_dev_t dev, size } static bool ggml_backend_remoting_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) { + if (ggml_flash_attn_ext_has_indexed_bias(op)) { + return false; + } + if ((op->op == GGML_OP_ROPE || op->op == GGML_OP_ROPE_BACK) && !ggml_rope_get_truncate(op)) { return false; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index 60cebe49445e..0711166f9671 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -16774,8 +16774,7 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm } case GGML_OP_FLASH_ATTN_EXT: { - // K/V row lists (ggml_flash_attn_ext_rows) are not supported - if (op->src[5] != nullptr) { + if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) { return false; } bool coopmat2 = device->coopmat2; diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp index b857f4927764..4bb43926daaa 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp @@ -5086,8 +5086,9 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const { // conservative support checks for whether the more resource-intensive shader paths // can be used, to avoid cases where flash_attn is assigned to the CPU later on - // K/V row lists (ggml_flash_attn_ext_rows) are not supported - supports_op = op->src[5] == nullptr && src0->type == GGML_TYPE_F32 && + // K/V row lists and indexed bias are not supported + supports_op = op->src[5] == nullptr && !ggml_flash_attn_ext_has_indexed_bias(op) && + src0->type == GGML_TYPE_F32 && (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_Q4_0 || src1->type == GGML_TYPE_Q8_0) && (src2->type == GGML_TYPE_F32 || src2->type == GGML_TYPE_F16 || diff --git a/ggml/src/ggml-zdnn/fattn.cpp b/ggml/src/ggml-zdnn/fattn.cpp index e6a0c24cadaf..5e74e67a4936 100644 --- a/ggml/src/ggml-zdnn/fattn.cpp +++ b/ggml/src/ggml-zdnn/fattn.cpp @@ -21,7 +21,7 @@ bool ggml_zdnn_supports_flash_attn_ext(const ggml_backend_zdnn_device_context * memcpy(&logit_softcap, (const float *) op->op_params + 2, sizeof(float)); // sinks, alibi, softcap, sparse k/v sets and k/v row lists are not implemented - if (op->src[4] != nullptr || op->src[5] != nullptr || max_bias != 0.0f || logit_softcap != 0.0f || ggml_get_op_params_i32(op, 4) != 0) { + if (op->src[4] != nullptr || op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op) || max_bias != 0.0f || logit_softcap != 0.0f || ggml_get_op_params_i32(op, 4) != 0) { return false; } diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index 3389dcd63d7c..947342125327 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -5545,6 +5545,33 @@ void ggml_flash_attn_ext_add_sinks( a->src[4] = sinks; } +bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a) { + return a->op == GGML_OP_FLASH_ATTN_EXT && ggml_get_op_params_i32(a, 5) != 0; +} + +void ggml_flash_attn_ext_add_indexed_bias( + struct ggml_tensor * a, + struct ggml_tensor * table, + struct ggml_tensor * indices) { + GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT); + GGML_ASSERT((table == NULL) == (indices == NULL)); + a->src[6] = table; + a->src[7] = indices; + ggml_set_op_params_i32(a, 5, table != NULL); + if (!table) { + return; + } + + const struct ggml_tensor * q = a->src[0]; + const struct ggml_tensor * mask = a->src[3]; + GGML_ASSERT(mask && mask->ne[0] == (a->src[5] ? a->src[5]->ne[0] : a->src[1]->ne[1]) && mask->ne[1] == q->ne[1]); + GGML_ASSERT(mask->ne[2] == 1 && mask->ne[3] == q->ne[3]); + GGML_ASSERT(table->type == GGML_TYPE_F32 && ggml_is_contiguous(table)); + GGML_ASSERT(table->ne[1] == q->ne[2] && table->ne[0] > 0 && table->ne[2] == q->ne[1]*q->ne[3] && table->ne[3] == 1); + GGML_ASSERT(indices->type == GGML_TYPE_I32 && ggml_is_contiguous(indices) && ggml_is_matrix(indices)); + GGML_ASSERT(indices->ne[0] == mask->ne[0] && indices->ne[1] == table->ne[2]); +} + // ggml_flash_attn_back struct ggml_tensor * ggml_flash_attn_back( diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 318225c8509a..84f0e5709031 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9551,6 +9551,124 @@ struct test_flash_attn_ext_kv_rows : public test_case { } }; +// GGML_OP_FLASH_ATTN_EXT with an indexed bias: mask[key, query] += table[indices[key, query], head, query] +struct test_flash_attn_ext_indexed_bias : public test_case { + const int64_t hs; + const int64_t nh; // K/V heads + const int64_t gqa; + const int64_t kv; // mask columns + const int64_t nb; // queries per stream + const int64_t n_stream; + const int64_t n_bins; + const bool kv_rows; // all streams read one K/V cache of 2*kv rows through kv_rows + const bool sinks; + const ggml_type type_KV; + + std::vector rows; + + std::string vars() override { + return VARS_TO_STR10(hs, nh, gqa, kv, nb, n_stream, n_bins, kv_rows, sinks, type_KV); + } + + double max_nmse_err() override { + return 5e-4; + } + + test_flash_attn_ext_indexed_bias(int64_t hs = 128, int64_t nh = 2, int64_t gqa = 3, int64_t kv = 768, int64_t nb = 7, int64_t n_stream = 2, + int64_t n_bins = 17, bool kv_rows = false, bool sinks = true, ggml_type type_KV = GGML_TYPE_F16) + : hs(hs), nh(nh), gqa(gqa), kv(kv), nb(nb), n_stream(n_stream), n_bins(n_bins), kv_rows(kv_rows), sinks(sinks), type_KV(type_KV) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, hs, nb, nh*gqa, n_stream); + ggml_set_name(q, "q"); + + ggml_tensor * k = ggml_new_tensor_4d(ctx, type_KV, hs, kv_rows ? 2*kv : kv, nh, kv_rows ? 1 : n_stream); + ggml_tensor * v = ggml_new_tensor_4d(ctx, type_KV, hs, kv_rows ? 2*kv : kv, nh, kv_rows ? 1 : n_stream); + ggml_set_name(k, "k"); + ggml_set_name(v, "v"); + + ggml_tensor * m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, kv, nb, 1, n_stream); + ggml_set_name(m, "m"); + + ggml_tensor * r = nullptr; + if (kv_rows) { + r = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, kv, n_stream); + ggml_set_name(r, "r"); + } + + ggml_tensor * table = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_bins, nh*gqa, nb*n_stream); + ggml_set_name(table, "table"); + + ggml_tensor * indices = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, kv, nb*n_stream); + ggml_set_name(indices, "indices"); + + ggml_tensor * out = ggml_flash_attn_ext_rows(ctx, q, k, v, m, r, 1.0f/sqrtf(hs), 0.0f, 0.0f); + if (sinks) { + ggml_tensor * s = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nh*gqa); + ggml_set_name(s, "s"); + ggml_flash_attn_ext_add_sinks(out, s); + } + ggml_flash_attn_ext_add_indexed_bias(out, table, indices); + ggml_prec_set_acc(out, GGML_PREC_F32); + ggml_set_name(out, "out"); + + return out; + } + + void initialize_tensors(ggml_context * ctx) override { + std::mt19937 gen(0x1B1A); + + // distinct random cells per stream, some of them padding + rows.assign(kv*n_stream, -1); + if (kv_rows) { + std::vector order(2*kv); + for (int64_t s = 0; s < n_stream; ++s) { + for (int64_t i = 0; i < 2*kv; ++i) { + order[i] = i; + } + std::shuffle(order.begin(), order.end(), gen); + for (int64_t i = 0; i < kv; ++i) { + rows[s*kv + i] = i % 19 == 7 ? -1 : order[i]; + } + } + } + + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + if (strcmp(t->name, "r") == 0) { + ggml_backend_tensor_set(t, rows.data(), 0, rows.size()*sizeof(int32_t)); + } else if (strcmp(t->name, "m") == 0) { + std::vector f(ggml_nelements(t)); + std::uniform_real_distribution dis(-1.0f, 1.0f); + for (int64_t s = 0; s < n_stream; ++s) { + for (int64_t j = 0; j < nb; ++j) { + for (int64_t i = 0; i < kv; ++i) { + const bool pad = kv_rows && rows[s*kv + i] < 0; + const bool drop = (i + 3*j + 5*s) % 11 == 0; + f[(s*nb + j)*kv + i] = pad || drop ? -INFINITY : dis(gen); + } + } + } + std::vector h(f.size()); + ggml_fp32_to_fp16_row(f.data(), h.data(), f.size()); + ggml_backend_tensor_set(t, h.data(), 0, h.size()*sizeof(ggml_fp16_t)); + } else if (strcmp(t->name, "indices") == 0) { + std::vector idx(ggml_nelements(t)); + std::uniform_int_distribution dis(0, n_bins - 1); + for (auto & i : idx) { + i = dis(gen); + } + ggml_backend_tensor_set(t, idx.data(), 0, idx.size()*sizeof(int32_t)); + } else if (strcmp(t->name, "table") == 0) { + init_tensor_uniform(t, -4.0f, 4.0f); + } else if (strcmp(t->name, "s") == 0) { + init_tensor_uniform(t, -10.0f, 10.0f); + } else { + init_tensor_uniform(t); + } + } + } +}; + // GGML_OP_CROSS_ENTROPY_LOSS struct test_cross_entropy_loss : public test_case { const ggml_type type; @@ -13544,6 +13662,21 @@ static std::vector> make_test_cases_eval() { } } + // flash attention with an indexed bias (Inkling 2 relative-position bias) + for (bool kv_rows : {false, true}) { + for (int64_t nb : {1, 7, 65}) { + for (int64_t n_stream : {1, 2}) { + test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, nb, n_stream, 17, kv_rows)); + } + } + test_cases.emplace_back(new test_flash_attn_ext_indexed_bias( 64, 2, 3, 768, 7, 2, 17, kv_rows, false)); + test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 8, 3, 512, 65, 1, 1025, kv_rows)); + for (ggml_type type : {GGML_TYPE_Q8_0, GGML_TYPE_Q4_0}) { + test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, 1, 1, 17, kv_rows, true, type)); + test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, 7, 2, 17, kv_rows, true, type)); + } + } + // sparse mask with large batch size test_cases.emplace_back(new test_flash_attn_ext(512, 512, 1, { 8, 1}, 4096, 64, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 512)); test_cases.emplace_back(new test_flash_attn_ext(512, 512, 1, { 8, 1}, 4096, 64, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 2048)); From ab789a246c1a59fbade35a28100bc2d38ea19188 Mon Sep 17 00:00:00 2001 From: Georgi Gerganov Date: Mon, 23 Nov 2026 21:01:41 +0200 Subject: [PATCH 029/275] metal : batch concat rows and copy them in vector chunks (#32824) * metal : batch concat rows and copy them in vector chunks The concat kernel copied one element per thread, so wide rows with many rows ran at a fraction of the memory bandwidth. Batch several rows per threadgroup and copy the contiguous dim-0 elements in 4-element chunks when the row is contiguous. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * test : cover concat vector and misaligned row paths Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB) * metal : hoist the concat src1 row offset into scalars Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB) * metal : peel to align the concat vector copy Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB) * metal : vectorize concat rows along any dimension Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB) * metal : specialize concat with function constants Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB) * metal : drop the concat row-batch dispatch Batching several rows per threadgroup reduces the number of threads by the batch factor. On machines with a large GPU this leaves too few requests in flight and the copy becomes latency bound: M5 Ultra (36 CPU) f16 [1024,8,256,1] d=0 8.1 us -> 17.2 us f32 [4096,8,256,1] d=0 35.4 us -> 118.5 us f16 [4096,8,256,1] d=2 50.9 us -> 102.0 us An interleaved sweep of the (nth, nrptg) dispatch over the concat perf cases on an M2 Ultra and an M5 Ultra shows that the base dispatch is best or tied for every shape once the rows are vectorized, and that the gains of the previous commit come from the vector copy alone: M2 Ultra f16 [1024,8,256,1] d=0 32.4 us -> 17.0 us M5 Ultra f16 [1024,8,256,1] d=0 13.3 us -> 8.1 us Keep the vector copy and the function-constant specialization, and return to the original dispatch. Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB) * metal : revert the concat function constants Specializing the concat kernel on the concat dimension and on whether a row is split across threadgroups with function constants makes the strided scalar path slower. Interleaved over the concat perf cases on an M5 Ultra, the specialized kernel is not faster than the plain one, and it costs up to 18% on shapes that are already at the memory bandwidth limit: f32 [2050,8,256,1] b=255 d=0 21.0 us -> 25.1 us f32 [2050,8,256,1] b=256 d=2 31.1 us -> 36.7 us f16 [4096,8,256,1] b=256 d=2 31.2 us -> 36.7 us Revert the specialization and keep copying rows with the runtime arguments. The concat change is now limited to the kernel itself. Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB) --- ggml/src/ggml-metal/kernels/quantize.metal | 78 +++++++++++++++++++--- tests/test-backend-ops.cpp | 28 ++++++++ 2 files changed, 98 insertions(+), 8 deletions(-) diff --git a/ggml/src/ggml-metal/kernels/quantize.metal b/ggml/src/ggml-metal/kernels/quantize.metal index 663e47d5fd2f..b2624565d8a6 100644 --- a/ggml/src/ggml-metal/kernels/quantize.metal +++ b/ggml/src/ggml-metal/kernels/quantize.metal @@ -159,6 +159,47 @@ template [[host_name("kernel_cpy_q8_0_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32< template [[host_name("kernel_cpy_tq2_0_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32; +template +static void concat_copy(device const char * src, device char * dst, const int n, const int tid, const int nth) { + if (n <= 0) { + return; + } + + constexpr int N = 16/sizeof(T); + typedef vec T16; + + device const T * x = (device const T *)src; + device T * y = (device T *)dst; + + const size_t rx = (size_t)x % 16; + + if (rx != (size_t)y % 16 || rx % sizeof(T) != 0) { + for (int i = tid; i < n; i += nth) { + y[i] = x[i]; + } + + return; + } + + const int np = min((int)(((16 - rx) % 16)/sizeof(T)), n); + const int n16 = (n - np)/N; + + for (int i = tid; i < np; i += nth) { + y[i] = x[i]; + } + + device const T16 * x16 = (device const T16 *)(x + np); + device T16 * y16 = (device T16 *)(y + np); + + for (int i = tid; i < n16; i += nth) { + y16[i] = x16[i]; + } + + for (int i = np + n16*N + tid; i < n; i += nth) { + y[i] = x[i]; + } +} + template kernel void kernel_concat( constant ggml_metal_kargs_concat & args, @@ -178,20 +219,39 @@ kernel void kernel_concat( return; } - int o[4] = {0, 0, 0, 0}; - o[args.dim] = args.dim == 0 ? args.ne00 : (args.dim == 1 ? args.ne01 : (args.dim == 2 ? args.ne02 : args.ne03)); + const int o0 = args.dim == 0 ? args.ne00 : 0; + const int o1 = args.dim == 1 ? args.ne01 : 0; + const int o2 = args.dim == 2 ? args.ne02 : 0; + const int o3 = args.dim == 3 ? args.ne03 : 0; // chunk ic of nc0 along the row const int n0 = (args.ne0 + args.nc0 - 1)/args.nc0; - const int i0e = min(args.ne0, (ic + 1)*n0); + const int i0b = ntg.y == 1 ? ic*n0 : 0; + const int i0e = ntg.y == 1 ? min(args.ne0, (ic + 1)*n0) : args.ne0; - for (int i0 = ic*n0 + tpitg.x; i0 < i0e; i0 += ntg.x) { + if (args.nb0 == sizeof(T) && args.nb00 == sizeof(T) && args.nb10 == sizeof(T)) { + const bool in0 = i1 < args.ne01 && i2 < args.ne02 && i3 < args.ne03; + + const int na = in0 ? min(i0e - i0b, max(0, args.ne00 - i0b)) : 0; + const int nb = i0e - i0b - na; + + device const char * r0 = src0 + i3*args.nb03 + i2*args.nb02 + i1*args.nb01; + device const char * r1 = src1 + (i3 - o3)*args.nb13 + (i2 - o2)*args.nb12 + (i1 - o1)*args.nb11; + device char * rd = dst + i3*args.nb3 + i2*args.nb2 + i1*args.nb1; + + concat_copy(r0 + i0b*sizeof(T), rd + i0b*sizeof(T), na, tpitg.x, ntg.x); + concat_copy(r1 + (i0b + na - o0)*sizeof(T), rd + (i0b + na)*sizeof(T), nb, tpitg.x, ntg.x); + + return; + } + + for (int i0 = i0b + tpitg.x; i0 < i0e; i0 += ntg.x) { device const T * x; if (i0 < args.ne00 && i1 < args.ne01 && i2 < args.ne02 && i3 < args.ne03) { x = (device const T *)(src0 + (i3 )*args.nb03 + (i2 )*args.nb02 + (i1 )*args.nb01 + (i0 )*args.nb00); } else { - x = (device const T *)(src1 + (i3 - o[3])*args.nb13 + (i2 - o[2])*args.nb12 + (i1 - o[1])*args.nb11 + (i0 - o[0])*args.nb10); + x = (device const T *)(src1 + (i3 - o3)*args.nb13 + (i2 - o2)*args.nb12 + (i1 - o1)*args.nb11 + (i0 - o0)*args.nb10); } device T * y = (device T *)(dst + i3*args.nb3 + i2*args.nb2 + i1*args.nb1 + i0*args.nb0); @@ -232,8 +292,10 @@ kernel void kernel_concat_q( return; } - int o[4] = {0, 0, 0, 0}; - o[args.dim] = args.dim == 0 ? args.ne00 : (args.dim == 1 ? args.ne01 : (args.dim == 2 ? args.ne02 : args.ne03)); + const int o0 = args.dim == 0 ? args.ne00 : 0; + const int o1 = args.dim == 1 ? args.ne01 : 0; + const int o2 = args.dim == 2 ? args.ne02 : 0; + const int o3 = args.dim == 3 ? args.ne03 : 0; // chunk ic of nc0 along the row const int n0 = (args.ne0 + args.nc0 - 1)/args.nc0; @@ -245,7 +307,7 @@ kernel void kernel_concat_q( if (i0 < args.ne00 && i1 < args.ne01 && i2 < args.ne02 && i3 < args.ne03) { x = (device const block_q *)(src0 + (i3 )*args.nb03 + (i2 )*args.nb02 + (i1 )*args.nb01 + (i0 )*args.nb00); } else { - x = (device const block_q *)(src1 + (i3 - o[3])*args.nb13 + (i2 - o[2])*args.nb12 + (i1 - o[1])*args.nb11 + (i0 - o[0])*args.nb10); + x = (device const block_q *)(src1 + (i3 - o3)*args.nb13 + (i2 - o2)*args.nb12 + (i1 - o1)*args.nb11 + (i0 - o0)*args.nb10); } device block_q * y = (device block_q *)(dst + i3*args.nb3 + i2*args.nb2 + i1*args.nb1 + i0*args.nb0); diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 84f0e5709031..a0268b638a5e 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -13201,6 +13201,21 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_concat(GGML_TYPE_Q8_0, {8192, 2, 1, 1}, dim == 0 ? 4096 : 1, dim, 0)); } + for (ggml_type type : { GGML_TYPE_F32, GGML_TYPE_F16 }) { + test_cases.emplace_back(new test_concat(type, {64, 4, 512, 1}, 512, 2, 0)); + test_cases.emplace_back(new test_concat(type, {66, 4, 512, 1}, 512, 2, 0)); + test_cases.emplace_back(new test_concat(type, {128, 4, 512, 1}, 512, 2, 1)); + + for (int dim : { 0, 1, 3 }) { + test_cases.emplace_back(new test_concat(type, {300, 4, 5, 1}, 300, dim, 0)); + } + test_cases.emplace_back(new test_concat(type, {1025, 4, 512, 1}, 1025, 0, 0)); + test_cases.emplace_back(new test_concat(type, {3, 4, 512, 1}, 5, 0, 0)); + } + + test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {98306, 8, 1, 1}, 286, 0, 0)); + test_cases.emplace_back(new test_concat(GGML_TYPE_F16, {98306, 8, 1, 1}, 286, 0, 0)); + // GDN conv_input for (int64_t ne_b_d : { 31, 32, 33, 64 }) { test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {3, 10240, 1, 1}, ne_b_d, 0, 16)); @@ -14195,6 +14210,19 @@ static std::vector> make_test_cases_perf() { } } + for (ggml_type type : { GGML_TYPE_F32, GGML_TYPE_F16 }) { + for (int64_t ne0 : { 64, 1024, 4096, 16384 }) { + test_cases.emplace_back(new test_concat(type, {ne0, 8, 256, 1}, 256, 2, 0)); + } + test_cases.emplace_back(new test_concat(type, {2050, 8, 256, 1}, 256, 2, 0)); + test_cases.emplace_back(new test_concat(type, {1024, 8, 2048, 1}, 2048, 2, 0)); + + for (int64_t ne0 : { 64, 1024, 4096, 16384 }) { + test_cases.emplace_back(new test_concat(type, {ne0, 8, 256, 1}, 256, 0, 0)); + } + test_cases.emplace_back(new test_concat(type, {2050, 8, 256, 1}, 255, 0, 0)); + } + // CONT of a 0<->2 permute at DeepSeek-V4 lightning-indexer shapes: // indexer_kq is [n_kv, n_tokens, n_head=64] and gets ggml_cont(ggml_permute(.., 2,1,0,3)). for (int64_t n_kv : { 1024, 1280, 2048, 2304 }) { From 51831d47d0a47b8a7d07c9ff262ebe4b0a211790 Mon Sep 17 00:00:00 2001 From: Georgi Gerganov Date: Mon, 23 Nov 2026 21:02:30 +0200 Subject: [PATCH 030/275] metal : add NVFP4 support (#32825) * metal : add NVFP4 support Follow the MXFP4 path: add the UE4M3 scale decode, the NVFP4 dequantizers, a dedicated mat-vec kernel with its MUL_MAT_ID, small-batch and MMA variants, the mul_mm / mul_mm_id and tensor-op variants, and the get_rows and cpy kernels. Enable the type in supports_op. Tested on an M5 Max with ggml-org/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-GGUF:NVFP4 and test-backend-ops (MUL_MAT, MUL_MAT_ID, W4A8/W4A4, CPY, GET_ROWS). Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (2x DGX Spark (RDMA, TP=2)) * metal : skip the small-batch path for NVFP4 With the few-row MMA kernels covering ne11 3..16, the small-batch mat-vec kernels are only reachable at ne11 = 2, where they are 17-59% slower than the generic mat-vec kernel on an M2 Ultra and an M5 Max. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (2x DGX Spark (RDMA, TP=2)) --- ggml/src/ggml-metal/ggml-metal-common.cpp | 2 + ggml/src/ggml-metal/ggml-metal-device.cpp | 12 +- ggml/src/ggml-metal/ggml-metal-device.m | 5 +- ggml/src/ggml-metal/ggml-metal-impl.h | 3 + ggml/src/ggml-metal/kernels/common.h | 13 ++ ggml/src/ggml-metal/kernels/dequantize.h | 39 +++++ ggml/src/ggml-metal/kernels/mul_mm.metal | 9 ++ .../ggml-metal/kernels/mul_mm_tensor.metal | 6 + ggml/src/ggml-metal/kernels/mul_mv.metal | 134 ++++++++++++++++-- ggml/src/ggml-metal/kernels/mul_mv_mma.metal | 1 + ggml/src/ggml-metal/kernels/quantize.metal | 3 + 11 files changed, 214 insertions(+), 13 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal-common.cpp b/ggml/src/ggml-metal/ggml-metal-common.cpp index f363122540cf..e8c3cdcc1d37 100644 --- a/ggml/src/ggml-metal/ggml-metal-common.cpp +++ b/ggml/src/ggml-metal/ggml-metal-common.cpp @@ -85,6 +85,7 @@ static bool ggml_metal_mul_mv_mma_type_supported(enum ggml_type type) { case GGML_TYPE_Q1_0: case GGML_TYPE_Q2_0: case GGML_TYPE_MXFP4: + case GGML_TYPE_NVFP4: case GGML_TYPE_Q2_K: case GGML_TYPE_Q3_K: case GGML_TYPE_IQ2_XXS: @@ -134,6 +135,7 @@ static int64_t ggml_metal_mul_mv_mma_rows_min(enum ggml_type type) { case GGML_TYPE_Q2_K: case GGML_TYPE_IQ4_NL: case GGML_TYPE_MXFP4: + case GGML_TYPE_NVFP4: return 3; default: return 2; diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp index 88ca0b832738..7a732e29e73c 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.cpp +++ b/ggml/src/ggml-metal/ggml-metal-device.cpp @@ -1116,6 +1116,11 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mv(ggml_meta nsg = N_SG_MXFP4; nr0 = N_R0_MXFP4; } break; + case GGML_TYPE_NVFP4: + { + nsg = N_SG_NVFP4; + nr0 = N_R0_NVFP4; + } break; case GGML_TYPE_Q2_K: { nsg = N_SG_Q2_K; @@ -1321,7 +1326,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm_id(ggml_m const bool prec_bf16 = props_dev->has_bfloat && ggml_prec_get_src(op, 1) == GGML_PREC_BF16 && tsrc1 == GGML_TYPE_F32 && - tsrc0 != GGML_TYPE_BF16 && tsrc0 != GGML_TYPE_MXFP4; + tsrc0 != GGML_TYPE_BF16 && tsrc0 != GGML_TYPE_MXFP4 && tsrc0 != GGML_TYPE_NVFP4; const bool prec_f32 = ggml_prec_get_src(op, 1) == GGML_PREC_F32 && tsrc1 == GGML_TYPE_F32; @@ -1423,6 +1428,11 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mv_id(ggml_m nsg = N_SG_MXFP4; nr0 = N_R0_MXFP4; } break; + case GGML_TYPE_NVFP4: + { + nsg = N_SG_NVFP4; + nr0 = N_R0_NVFP4; + } break; case GGML_TYPE_Q2_K: { nsg = N_SG_Q2_K; diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index 9afaaca3697c..da2f0acee316 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1532,7 +1532,6 @@ static bool ggml_metal_supports_mul_mat_op( bool mm_path) { if (!has_simdgroup_reduction || op->src[0]->type == GGML_TYPE_F8_E4M3 || - op->src[0]->type == GGML_TYPE_NVFP4 || op->src[0]->type == GGML_TYPE_TQ1_0) { return false; } @@ -1981,6 +1980,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te case GGML_TYPE_Q5_1: case GGML_TYPE_Q8_0: case GGML_TYPE_TQ2_0: + case GGML_TYPE_NVFP4: switch (op->type) { case GGML_TYPE_F32: case GGML_TYPE_F16: @@ -1995,8 +1995,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te }; } case GGML_OP_GET_ROWS: - return op->src[0]->type != GGML_TYPE_NVFP4 && - op->src[0]->type != GGML_TYPE_TQ1_0 && + return op->src[0]->type != GGML_TYPE_TQ1_0 && op->src[0]->type != GGML_TYPE_F8_E4M3; case GGML_OP_SET_ROWS: { diff --git a/ggml/src/ggml-metal/ggml-metal-impl.h b/ggml/src/ggml-metal/ggml-metal-impl.h index aad014d837e9..4e28b2cb99b9 100644 --- a/ggml/src/ggml-metal/ggml-metal-impl.h +++ b/ggml/src/ggml-metal/ggml-metal-impl.h @@ -50,6 +50,9 @@ #define N_R0_MXFP4 2 #define N_SG_MXFP4 2 +#define N_R0_NVFP4 2 +#define N_SG_NVFP4 2 + #define N_R0_Q2_K 4 #define N_SG_Q2_K 2 diff --git a/ggml/src/ggml-metal/kernels/common.h b/ggml/src/ggml-metal/kernels/common.h index 551a4d7c8e81..237ccfb26b03 100644 --- a/ggml/src/ggml-metal/kernels/common.h +++ b/ggml/src/ggml-metal/kernels/common.h @@ -41,6 +41,7 @@ constexpr constant static float kvalues_iq4nl_f[16] = { -127.f, -104.f, -83.f, -65.f, -49.f, -35.f, -22.f, -10.f, 1.f, 13.f, 25.f, 38.f, 53.f, 69.f, 89.f, 113.f }; +// E2M1 values, shared by MXFP4 and NVFP4 constexpr constant static float kvalues_mxfp4_f[16] = { 0, .5f, 1.f, 1.5f, 2.f, 3.f, 4.f, 6.f, -0, -.5f, -1.f, -1.5f, -2.f, -3.f, -4.f, -6.f }; @@ -68,6 +69,18 @@ static inline float e8m0_to_fp32(uint8_t x) { return as_type(bits); } +// UE4M3: unsigned, 4 exponent bits with bias 7, 3 mantissa bits - the NVFP4 sub-block scale +static inline float ue4m3_to_fp32(uint8_t x) { + if (x == 0x7F) { + return 0.0f; + } + + const int e = (x >> 3) & 0xF; + const int m = x & 0x7; + + return e == 0 ? m*(1.0f/512.0f) : as_type((uint32_t) (((e + 120) << 23) | (m << 20))); +} + static inline float dot(float x, float y) { return x*y; } diff --git a/ggml/src/ggml-metal/kernels/dequantize.h b/ggml/src/ggml-metal/kernels/dequantize.h index 96b16d7fb442..d99a48666ca9 100644 --- a/ggml/src/ggml-metal/kernels/dequantize.h +++ b/ggml/src/ggml-metal/kernels/dequantize.h @@ -378,6 +378,45 @@ void dequantize_mxfp4_t4(device const block_mxfp4 * xb, short il, thread type4 & reg[3] = d * kvalues_mxfp4_f[(q2[4*il4 + 3] >> shr) & 0x0F]; } +// NVFP4: 64 weights per block split into four 16-weight sub-blocks, each with its own UE4M3 scale. +// the 16 weights of a sub-block are the low nibbles of its 8 bytes followed by the high nibbles +template +void dequantize_nvfp4(device const block_nvfp4 * xb, short il, thread type4x4 & reg) { + device const uint8_t * q = (device const uint8_t *)xb->qs + 8*il; + + const float d = ue4m3_to_fp32(xb->d[il]); + + float4x4 reg_f; + + for (int i = 0; i < 4; ++i) { + device const uint8_t * qb = q + 4*(i % 2); + const uint8_t shr = i < 2 ? 0 : 4; + + reg_f[i][0] = d * kvalues_mxfp4_f[(qb[0] >> shr) & 0x0F]; + reg_f[i][1] = d * kvalues_mxfp4_f[(qb[1] >> shr) & 0x0F]; + reg_f[i][2] = d * kvalues_mxfp4_f[(qb[2] >> shr) & 0x0F]; + reg_f[i][3] = d * kvalues_mxfp4_f[(qb[3] >> shr) & 0x0F]; + } + + reg = (type4x4) reg_f; +} + +template +void dequantize_nvfp4_t4(device const block_nvfp4 * xb, short il, thread type4 & reg) { + const short s = il/4; // sub-block + const short il4 = il%4; // 4-weight chunk within the sub-block + + device const uint8_t * q = (device const uint8_t *)xb->qs + 8*s + 4*(il4 % 2); + + const float d = ue4m3_to_fp32(xb->d[s]); + const uint8_t shr = il4 >= 2 ? 4 : 0; + + reg[0] = d * kvalues_mxfp4_f[(q[0] >> shr) & 0x0F]; + reg[1] = d * kvalues_mxfp4_f[(q[1] >> shr) & 0x0F]; + reg[2] = d * kvalues_mxfp4_f[(q[2] >> shr) & 0x0F]; + reg[3] = d * kvalues_mxfp4_f[(q[3] >> shr) & 0x0F]; +} + template void dequantize_q2_K(device const block_q2_K *xb, short il, thread type4x4 & reg) { const float d = xb->d; diff --git a/ggml/src/ggml-metal/kernels/mul_mm.metal b/ggml/src/ggml-metal/kernels/mul_mm.metal index e16a8ec79649..1d47b9166158 100644 --- a/ggml/src/ggml-metal/kernels/mul_mm.metal +++ b/ggml/src/ggml-metal/kernels/mul_mm.metal @@ -677,6 +677,7 @@ template [[host_name("kernel_mul_mm_q5_0_f32_prec_bf16")]] kernel mul_mm_t ke template [[host_name("kernel_mul_mm_q5_1_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q8_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_mxfp4_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_nvfp4_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q2_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q3_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q4_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; @@ -703,6 +704,7 @@ template [[host_name("kernel_mul_mm_q5_0_f32_prec_f32")]] kernel mul_mm_t ker template [[host_name("kernel_mul_mm_q5_1_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q8_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_mxfp4_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_nvfp4_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q2_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q3_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q4_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; @@ -732,6 +734,7 @@ template [[host_name("kernel_mul_mm_q5_0_f32")]] kernel mul_mm_t kernel_mul_m template [[host_name("kernel_mul_mm_q5_1_f32")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q8_0_f32")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_mxfp4_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_nvfp4_f32")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q2_K_f32")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q3_K_f32")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q4_K_f32")]] kernel mul_mm_t kernel_mul_mm; @@ -758,6 +761,7 @@ template [[host_name("kernel_mul_mm_q5_0_f16")]] kernel mul_mm_t kernel_mul_m template [[host_name("kernel_mul_mm_q5_1_f16")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q8_0_f16")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_mxfp4_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_nvfp4_f16")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q2_K_f16")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q3_K_f16")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q4_K_f16")]] kernel mul_mm_t kernel_mul_mm; @@ -794,8 +798,10 @@ template [[host_name("kernel_mul_mm_id_q5_1_f32")]] kernel mul_mm_id kernel_m template [[host_name("kernel_mul_mm_id_q8_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; #if defined(GGML_METAL_HAS_BF16) template [[host_name("kernel_mul_mm_id_mxfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_nvfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id; #else template [[host_name("kernel_mul_mm_id_mxfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_nvfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id; #endif template [[host_name("kernel_mul_mm_id_q2_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; template [[host_name("kernel_mul_mm_id_q3_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; @@ -853,6 +859,7 @@ template [[host_name("kernel_mul_mm_id_q5_0_f32_prec_f32")]] kernel mul_mm_id template [[host_name("kernel_mul_mm_id_q5_1_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; template [[host_name("kernel_mul_mm_id_q8_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; template [[host_name("kernel_mul_mm_id_mxfp4_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_nvfp4_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; template [[host_name("kernel_mul_mm_id_q2_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; template [[host_name("kernel_mul_mm_id_q3_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; template [[host_name("kernel_mul_mm_id_q4_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; @@ -884,8 +891,10 @@ template [[host_name("kernel_mul_mm_id_q5_1_f16")]] kernel mul_mm_id kernel_m template [[host_name("kernel_mul_mm_id_q8_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; #if defined(GGML_METAL_HAS_BF16) template [[host_name("kernel_mul_mm_id_mxfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_nvfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id; #else template [[host_name("kernel_mul_mm_id_mxfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_nvfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id; #endif template [[host_name("kernel_mul_mm_id_q2_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; template [[host_name("kernel_mul_mm_id_q3_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; diff --git a/ggml/src/ggml-metal/kernels/mul_mm_tensor.metal b/ggml/src/ggml-metal/kernels/mul_mm_tensor.metal index 9c1aee0c5690..2ccce5f41358 100644 --- a/ggml/src/ggml-metal/kernels/mul_mm_tensor.metal +++ b/ggml/src/ggml-metal/kernels/mul_mm_tensor.metal @@ -393,6 +393,7 @@ template [[host_name("kernel_mul_mm_tensor_q5_0_f32")]] kernel mul_mm_tensor_ template [[host_name("kernel_mul_mm_tensor_q5_1_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; template [[host_name("kernel_mul_mm_tensor_q8_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; template [[host_name("kernel_mul_mm_tensor_mxfp4_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_nvfp4_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; template [[host_name("kernel_mul_mm_tensor_q2_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; template [[host_name("kernel_mul_mm_tensor_q3_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; template [[host_name("kernel_mul_mm_tensor_q4_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; @@ -419,6 +420,7 @@ template [[host_name("kernel_mul_mm_tensor_q5_0_f16")]] kernel mul_mm_tensor_ template [[host_name("kernel_mul_mm_tensor_q5_1_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; template [[host_name("kernel_mul_mm_tensor_q8_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; template [[host_name("kernel_mul_mm_tensor_mxfp4_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_nvfp4_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; template [[host_name("kernel_mul_mm_tensor_q2_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; template [[host_name("kernel_mul_mm_tensor_q3_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; template [[host_name("kernel_mul_mm_tensor_q4_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; @@ -455,8 +457,10 @@ template [[host_name("kernel_mul_mm_id_tensor_q5_1_f32")]] kernel mul_mm_id_t template [[host_name("kernel_mul_mm_id_tensor_q8_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; #if defined(GGML_METAL_HAS_BF16) template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_nvfp4_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; #else template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_nvfp4_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; #endif template [[host_name("kernel_mul_mm_id_tensor_q2_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; template [[host_name("kernel_mul_mm_id_tensor_q3_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; @@ -515,8 +519,10 @@ template [[host_name("kernel_mul_mm_id_tensor_q5_1_f16")]] kernel mul_mm_id_t template [[host_name("kernel_mul_mm_id_tensor_q8_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; #if defined(GGML_METAL_HAS_BF16) template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_nvfp4_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; #else template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_nvfp4_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; #endif template [[host_name("kernel_mul_mm_id_tensor_q2_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; template [[host_name("kernel_mul_mm_id_tensor_q3_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; diff --git a/ggml/src/ggml-metal/kernels/mul_mv.metal b/ggml/src/ggml-metal/kernels/mul_mv.metal index 95e9515d5a23..1d6123f42e97 100644 --- a/ggml/src/ggml-metal/kernels/mul_mv.metal +++ b/ggml/src/ggml-metal/kernels/mul_mv.metal @@ -894,6 +894,11 @@ template [[host_name("kernel_mul_mv_ext_mxfp4_f32_r1_3")]] kernel mul_mv_ext_q4 template [[host_name("kernel_mul_mv_ext_mxfp4_f32_r1_4")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<4, block_mxfp4, 32, dequantize_mxfp4_t4>; template [[host_name("kernel_mul_mv_ext_mxfp4_f32_r1_5")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<5, block_mxfp4, 32, dequantize_mxfp4_t4>; +template [[host_name("kernel_mul_mv_ext_nvfp4_f32_r1_2")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<2, block_nvfp4, 64, dequantize_nvfp4_t4>; +template [[host_name("kernel_mul_mv_ext_nvfp4_f32_r1_3")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<3, block_nvfp4, 64, dequantize_nvfp4_t4>; +template [[host_name("kernel_mul_mv_ext_nvfp4_f32_r1_4")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<4, block_nvfp4, 64, dequantize_nvfp4_t4>; +template [[host_name("kernel_mul_mv_ext_nvfp4_f32_r1_5")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<5, block_nvfp4, 64, dequantize_nvfp4_t4>; + template [[host_name("kernel_mul_mv_ext_iq4_nl_f32_r1_2")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<2, block_iq4_nl, 32, dequantize_iq4_nl_t4>; template [[host_name("kernel_mul_mv_ext_iq4_nl_f32_r1_3")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<3, block_iq4_nl, 32, dequantize_iq4_nl_t4>; template [[host_name("kernel_mul_mv_ext_iq4_nl_f32_r1_4")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<4, block_iq4_nl, 32, dequantize_iq4_nl_t4>; @@ -3035,18 +3040,18 @@ kernel void kernel_mul_mv_iq4_xs_f32( // decode the E2M1 value in the low nibble of n, scaled by 2^-14, without a lookup table: the 3 magnitude bits // land in the fp16 exponent/mantissa (e=0 gives the 0.5 subnormal). same decode as MLX's fp4_e2m1 -static inline half mxfp4_dq1(uint32_t n) { +static inline half e2m1_dq1(uint32_t n) { const half c = as_type(ushort((n & 7) << 9)); return (n & 8) ? -c : c; } // low / high nibbles of the 4 bytes of w, in byte order, scaled by 2^-14 -static inline float4 mxfp4_lo4(uint32_t w) { - return float4(mxfp4_dq1(w), mxfp4_dq1(w >> 8), mxfp4_dq1(w >> 16), mxfp4_dq1(w >> 24)); +static inline float4 e2m1_lo4(uint32_t w) { + return float4(e2m1_dq1(w), e2m1_dq1(w >> 8), e2m1_dq1(w >> 16), e2m1_dq1(w >> 24)); } -static inline float4 mxfp4_hi4(uint32_t w) { - return float4(mxfp4_dq1(w >> 4), mxfp4_dq1(w >> 12), mxfp4_dq1(w >> 20), mxfp4_dq1(w >> 28)); +static inline float4 e2m1_hi4(uint32_t w) { + return float4(e2m1_dq1(w >> 4), e2m1_dq1(w >> 12), e2m1_dq1(w >> 20), e2m1_dq1(w >> 28)); } template @@ -3111,10 +3116,10 @@ void kernel_mul_mv_mxfp4_f32_impl( const uint32_t w0 = (a >> sh) | ((b << 1) << (31 - sh)); const uint32_t w1 = (b >> sh) | ((c << 1) << (31 - sh)); - float4 acc1 = yl[0]*mxfp4_lo4(w0); - float4 acc2 = yl[1]*mxfp4_hi4(w0); - float4 acc3 = yl[2]*mxfp4_lo4(w1); - float4 acc4 = yl[3]*mxfp4_hi4(w1); + float4 acc1 = yl[0]*e2m1_lo4(w0); + float4 acc2 = yl[1]*e2m1_hi4(w0); + float4 acc3 = yl[2]*e2m1_lo4(w1); + float4 acc4 = yl[3]*e2m1_hi4(w1); acc1 = (acc1 + acc3) + (acc2 + acc4); @@ -3149,6 +3154,116 @@ kernel void kernel_mul_mv_mxfp4_f32( kernel_mul_mv_mxfp4_f32_impl(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); } +// NVFP4: a 64-weight block holds four 16-weight sub-blocks, each scaled by its own UE4M3 value. +// a thread handles the two sub-blocks of one half of the block, so 16 blocks per loop iteration +template +void kernel_mul_mv_nvfp4_f32_impl( + args_t args, + device const char * src0, + device const char * src1, + device char * dst, + threadgroup char * shmem, + uint3 tgpig, + ushort tiisg, + ushort sgitg) { + const short NSG = FC_mul_mv_nsg; + + const int r0 = tgpig.x; + const int r1 = tgpig.y; + const int im = tgpig.z; + + const int first_row = (r0 * NSG + sgitg) * NR0; + + const uint i12 = im%FC_mul_mv_ne12; + const uint i13 = im/FC_mul_mv_ne12; + + const uint64_t offset0 = first_row*args.nb01 + (i12/FC_mul_mv_r2)*args.nb02 + (i13/FC_mul_mv_r3)*args.nb03; + const uint64_t offset1 = r1*args.nb11 + (i12 )*args.nb12 + (i13 )*args.nb13; + + device const block_nvfp4 * x = (device const block_nvfp4 *) (src0 + offset0); + device const float * y = (device const float *) (src1 + offset1); + + const int nb = args.ne00/QK_NVFP4; + const int ns01 = args.nb01/args.nb00; // this can be larger than nb for permuted src0 tensors + + const short ix = tiisg/2; // 0...15 + const short it = tiisg%2; // 0 or 1 + + float4 yl[8]; + float sumf[NR0]={0.f}; + + device const float * yb = y + ix*QK_NVFP4 + it*32; + + // note: just the check `ib < nb` is enough, but adding the redundant `&& ib < ns01` check makes the kernel a bit faster + // no idea why that is - needs some deeper investigation [TAG_MUL_MV_WEIRD] + for (int ib = ix; ib < nb && ib < ns01; ib += 16) { + device const float4 * y4 = (device const float4 *) yb; + + yl[0] = y4[0]; + yl[1] = y4[2]; + yl[2] = y4[1]; + yl[3] = y4[3]; + yl[4] = y4[4]; + yl[5] = y4[6]; + yl[6] = y4[5]; + yl[7] = y4[7]; + + FOR_UNROLL (short row = 0; row < NR0; row++) { + device const block_nvfp4 & xb = x[row*ns01 + ib]; + + // a block is 36 bytes, so its 16 quant bytes are 4-byte aligned and read as four words + device const uint32_t * pw = (device const uint32_t *)(xb.qs + 16*it); + + const uint32_t w0 = pw[0]; + const uint32_t w1 = pw[1]; + const uint32_t w2 = pw[2]; + const uint32_t w3 = pw[3]; + + float4 acc1 = yl[0]*e2m1_lo4(w0); + float4 acc2 = yl[1]*e2m1_hi4(w0); + float4 acc3 = yl[2]*e2m1_lo4(w1); + float4 acc4 = yl[3]*e2m1_hi4(w1); + + float4 acc5 = yl[4]*e2m1_lo4(w2); + float4 acc6 = yl[5]*e2m1_hi4(w2); + float4 acc7 = yl[6]*e2m1_lo4(w3); + float4 acc8 = yl[7]*e2m1_hi4(w3); + + acc1 = (acc1 + acc3) + (acc2 + acc4); + acc5 = (acc5 + acc7) + (acc6 + acc8); + + // 16384 undoes the 2^-14 of the decode + sumf[row] += ue4m3_to_fp32(xb.d[2*it + 0])*16384.0f*((acc1[0] + acc1[1]) + (acc1[2] + acc1[3])) + + ue4m3_to_fp32(xb.d[2*it + 1])*16384.0f*((acc5[0] + acc5[1]) + (acc5[2] + acc5[3])); + } + + yb += 16 * QK_NVFP4; + } + + device float * dst_f32 = (device float *) dst + (uint64_t)im*args.ne0*args.ne1 + (uint64_t)r1*args.ne0; + + for (int row = 0; row < NR0 && first_row + row < args.ne0; ++row) { + float sum_all = simd_sum(sumf[row]); + if (tiisg == 0) { + dst_f32[first_row + row] = sum_all; + } + } +} + +[[host_name("kernel_mul_mv_nvfp4_f32")]] +kernel void kernel_mul_mv_nvfp4_f32( + constant ggml_metal_kargs_mul_mv & args, + device const char * src0, + device const char * src1, + device char * dst, + threadgroup char * shmem [[threadgroup(0)]], + uint3 tgpig[[threadgroup_position_in_grid]], + ushort tiisg[[thread_index_in_simdgroup]], + ushort sgitg[[simdgroup_index_in_threadgroup]]) { + + kernel_mul_mv_nvfp4_f32_impl(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); +} + template void kernel_mul_mv_tq2_0_f32_impl( args_t args, @@ -3415,6 +3530,7 @@ template [[host_name("kernel_mul_mv_id_q5_0_f32")]] kernel kernel_mul_mv_id_t template [[host_name("kernel_mul_mv_id_q5_1_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; template [[host_name("kernel_mul_mv_id_mxfp4_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; +template [[host_name("kernel_mul_mv_id_nvfp4_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; template [[host_name("kernel_mul_mv_id_q2_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; template [[host_name("kernel_mul_mv_id_q3_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; diff --git a/ggml/src/ggml-metal/kernels/mul_mv_mma.metal b/ggml/src/ggml-metal/kernels/mul_mv_mma.metal index 5cf245d5210d..287834e3e9e3 100644 --- a/ggml/src/ggml-metal/kernels/mul_mv_mma.metal +++ b/ggml/src/ggml-metal/kernels/mul_mv_mma.metal @@ -611,6 +611,7 @@ MUL_MV_MMA_GEN("bf16", bfloat4x4, 1, dequantize_bf16) MUL_MV_MMA_GEN("q1_0", block_q1_0, 8, dequantize_q1_0) MUL_MV_MMA_GEN("q2_0", block_q2_0, 4, dequantize_q2_0) MUL_MV_MMA_GEN("mxfp4", block_mxfp4, 2, dequantize_mxfp4) +MUL_MV_MMA_GEN("nvfp4", block_nvfp4, 4, dequantize_nvfp4) MUL_MV_MMA_GEN("q2_K", block_q2_K, QK_NL, dequantize_q2_K) MUL_MV_MMA_GEN("q3_K", block_q3_K, QK_NL, dequantize_q3_K) MUL_MV_MMA_GEN("iq2_xxs", block_iq2_xxs, QK_NL, dequantize_iq2_xxs) diff --git a/ggml/src/ggml-metal/kernels/quantize.metal b/ggml/src/ggml-metal/kernels/quantize.metal index b2624565d8a6..d2940ed763b4 100644 --- a/ggml/src/ggml-metal/kernels/quantize.metal +++ b/ggml/src/ggml-metal/kernels/quantize.metal @@ -146,6 +146,7 @@ template [[host_name("kernel_cpy_q4_1_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32< template [[host_name("kernel_cpy_q5_0_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32; template [[host_name("kernel_cpy_q5_1_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32; template [[host_name("kernel_cpy_q8_0_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32; +template [[host_name("kernel_cpy_nvfp4_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32; template [[host_name("kernel_cpy_tq2_0_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32; @@ -156,6 +157,7 @@ template [[host_name("kernel_cpy_q4_1_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32< template [[host_name("kernel_cpy_q5_0_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32; template [[host_name("kernel_cpy_q5_1_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32; template [[host_name("kernel_cpy_q8_0_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32; +template [[host_name("kernel_cpy_nvfp4_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32; template [[host_name("kernel_cpy_tq2_0_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32; @@ -403,6 +405,7 @@ template [[host_name("kernel_get_rows_q5_0")]] kernel get_rows_q_t kernel_get template [[host_name("kernel_get_rows_q5_1")]] kernel get_rows_q_t kernel_get_rows_q; template [[host_name("kernel_get_rows_q8_0")]] kernel get_rows_q_t kernel_get_rows_q; template [[host_name("kernel_get_rows_mxfp4")]] kernel get_rows_q_t kernel_get_rows_q; +template [[host_name("kernel_get_rows_nvfp4")]] kernel get_rows_q_t kernel_get_rows_q; template [[host_name("kernel_get_rows_q2_K")]] kernel get_rows_q_t kernel_get_rows_q; template [[host_name("kernel_get_rows_q3_K")]] kernel get_rows_q_t kernel_get_rows_q; template [[host_name("kernel_get_rows_q4_K")]] kernel get_rows_q_t kernel_get_rows_q; From 8355b886250efcb490dec7431c3c0ec1463277a5 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Mon, 23 Nov 2026 21:38:18 +0100 Subject: [PATCH 031/275] ui: remove the Matte theme and the Light surfaces setting (#32906) Paper is now the only light theme: its surface tokens stay the base values, and the theme-matte overrides, the setting, its enum and the Storybook surface switch are gone. Assisted-by: Claude (Opus 5.5 Medium) --- ui/apps/chat/.storybook/preview.ts | 23 +----------------- ui/apps/chat/DESIGN.md | 24 ++++--------------- ui/apps/chat/scripts/design-md.js | 5 +--- .../settings/SettingsChat/SettingsChat.svelte | 5 ---- .../lib/constants/settings-keys.constants.ts | 1 - .../src/lib/constants/settings.constants.ts | 15 +----------- ui/apps/chat/src/lib/enums/index.ts | 1 - ui/apps/chat/src/lib/enums/ui.enums.ts | 6 ----- ui/apps/chat/src/lib/utils/css.ts | 12 ---------- ui/apps/chat/src/lib/utils/index.ts | 2 +- ui/apps/chat/src/routes/+layout.svelte | 7 +----- ui/lib/ui/.storybook/preview.ts | 23 ------------------ ui/lib/ui/README.md | 2 +- ui/lib/ui/src/lib/styles/theme.css | 2 +- .../ui/src/lib/styles/tokens/components.css | 5 ---- ui/lib/ui/src/lib/styles/tokens/semantic.css | 18 ++++---------- 16 files changed, 16 insertions(+), 135 deletions(-) diff --git a/ui/apps/chat/.storybook/preview.ts b/ui/apps/chat/.storybook/preview.ts index 7e7a58d167a8..22f04dd88609 100644 --- a/ui/apps/chat/.storybook/preview.ts +++ b/ui/apps/chat/.storybook/preview.ts @@ -1,7 +1,5 @@ import '../src/app.css'; import { MEDIA_QUERIES } from '#lib/constants/pwa.constants.ts'; -import { SurfaceTheme } from '#lib/enums/ui.enums.ts'; -import { applySurfaceTheme } from '#lib/utils/css.ts'; // the docs pages' styles, shared with the library's Storybook import '../../../lib/ui/.storybook/docs.css'; import { applyColorScheme } from './color-scheme'; @@ -97,31 +95,12 @@ const preview: Preview = { ], title: 'Interaction pace' } - }, - // the light surface theme: Paper (white panels on a grey page) or Matte (grey glass on white) - surface: { - description: 'Light surface theme', - toolbar: { - dynamicTitle: true, - icon: 'paintbrush', - items: [ - { title: 'Paper', value: SurfaceTheme.PAPER }, - { title: 'Matte', value: SurfaceTheme.MATTE } - ], - title: 'Surface' - } } }, initialGlobals: { - interactionPace: 'human', - surface: SurfaceTheme.PAPER + interactionPace: 'human' }, decorators: [ - (story, context) => { - applySurfaceTheme(context.globals.surface); - - return story(); - }, // `parameters.colorScheme` fixes a story to light or dark, whatever the viewer chose (a scene in a store screenshot) (story, context) => ({ Component: ModeWatcherDecorator, diff --git a/ui/apps/chat/DESIGN.md b/ui/apps/chat/DESIGN.md index efbc65d93685..fc624676d487 100644 --- a/ui/apps/chat/DESIGN.md +++ b/ui/apps/chat/DESIGN.md @@ -5,8 +5,7 @@ description: >- Llama UI, the design system and components of Llama Chat, the chat client llama-server bundles. Neutral and quiet: frosted matte surfaces with faint blue-grey hairlines, near-flat fills, and status colours for success, warning, error and info. Tokens come in - three tiers: primitives, semantic tokens (with a "-dark" twin where dark mode differs and a - "-matte" twin where the Matte light theme does) and components. The colors, typography and + three tiers: primitives, semantic tokens (with a "-dark" twin where dark mode differs) and components. The colors, typography and rounded sections are generated from ui/lib/ui/src/lib/styles by `npm run design:tokens` in ui/apps/chat; spacing, components and the prose are kept in sync with the CSS by hand. colors: @@ -123,14 +122,6 @@ colors: highlight-inverse: '{colors.white-a12}' sheen-start: '{colors.white-a20}' elevation-ring: '{colors.black-a5}' - surface-page-matte: '{colors.neutral-0}' - surface-glass-matte: 'oklch(0.97 0 0 / 0.6)' - surface-code-matte: '{colors.neutral-50}' - surface-success-matte: 'color-mix(in oklab, {colors.fill-success} 11%, {colors.surface-page-matte})' - surface-warning-matte: 'color-mix(in oklab, {colors.fill-warning} 11%, {colors.surface-page-matte})' - surface-danger-matte: 'color-mix(in oklab, {colors.fill-danger} 11%, {colors.surface-page-matte})' - surface-info-matte: 'color-mix(in oklab, {colors.fill-info} 11%, {colors.surface-page-matte})' - field-background-matte: '{colors.surface-page-matte}' surface-page-dark: '{colors.neutral-925}' surface-muted-dark: '{colors.neutral-800}' surface-emphasis-dark: '{colors.neutral-750}' @@ -815,9 +806,8 @@ here. The `spacing` and `components` sections and the prose are written by hand; disagree with the CSS, the CSS wins and this file is updated to match. Storybook shows every tier under **Llama UI › Foundations › Colors**. -Paper light mode is the base. A semantic token that resolves differently in dark mode has a -`-dark` twin here, and one that resolves differently in Matte a `-matte` twin; components list -a `-dark` entry wherever their colours change. Translucent component +Light mode is the base. A semantic token that resolves differently in dark mode has a +`-dark` twin here; components list a `-dark` entry wherever their colours change. Translucent component fills are given as they render over the page, so contrast checks see the real colour. ## Colors @@ -841,12 +831,8 @@ creative (a shape, a numeral, an illustration). Artwork takes its colours from t the `art-*` primitives: the day sky and the night sky (llama.app's light and dark hero grounds) and cinder, the accent orange; never from the status colours, and never red. -Light mode has two surface themes, which share everything else (the palette, buttons, fields, -badges, shadows and dark mode): **Paper**, the default, sets white panels, fields and keys on a -faint grey page (`neutral-25`); **Matte** sets grey glass on a white page. Matte is the -`theme-matte` class on ``, chosen with the Light surfaces setting (Settings → General) or -the Surface switch in Storybook's toolbar, and only its surface tokens differ: `surface-page`, -`surface-glass`, `surface-code`, `field-background` and `float-panel-background-modal`. +Light mode sets white panels, fields and keys on a faint grey page (`neutral-25`). Dark mode shares the +palette, buttons, fields, badges and shadows. - **Surfaces:** `surface-page` for the page, `surface-muted` for quiet panels, `surface-emphasis` and `surface-selected` for stronger fills and hover or selected rows, diff --git a/ui/apps/chat/scripts/design-md.js b/ui/apps/chat/scripts/design-md.js index 94c90b1f5452..385d99e3c102 100644 --- a/ui/apps/chat/scripts/design-md.js +++ b/ui/apps/chat/scripts/design-md.js @@ -28,10 +28,7 @@ const SOURCES = { theme: fileURLToPath(new URL('theme.css', styles)) }; // the selectors of the themes a semantic token may change in, and the suffix its twin takes here -const THEMES = [ - { selector: '.theme-matte:not(.dark)', suffix: '-matte' }, - { selector: '.dark', suffix: '-dark' } -]; +const THEMES = [{ selector: '.dark', suffix: '-dark' }]; // the type roles, by the @theme names Tailwind turns into text-body, text-label-sm, ...: a size with a line height const TYPE_ROLE = /^--text-([a-z]+(?:-[a-z]+)*)$/; // body and caption text takes the weight around it, which is regular unless a parent says otherwise diff --git a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte index d54d56a20017..fd058cea6679 100644 --- a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte +++ b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte @@ -21,7 +21,6 @@ import { ColorMode } from '#lib/enums/ui.enums.ts'; import { modelsStore, serverStore, settingsStore } from '#lib/stores/index.ts'; import type { SettingsSection, SettingsSectionTitle } from '#lib/types/index.ts'; - import { applySurfaceTheme } from '#lib/utils/index.ts'; import { setMode } from 'mode-watcher'; import { fade } from 'svelte/transition'; interface Props { @@ -91,9 +90,6 @@ function handleConfigChange(key: string, value: string | boolean) { localConfig[key] = value; - // the surface theme previews at once, like the colour theme - if (key === SETTINGS_KEYS.SURFACE_THEME) applySurfaceTheme(value); - // discover needs the hub metadata reads: checking it turns the hub on, // unchecking it turns the hub back off, so the checkbox never lies if (key === SETTINGS_KEYS.ENABLE_DISCOVER_MODELS) { @@ -108,7 +104,6 @@ function handleReset() { localConfig = { ...settingsStore.config }; setMode(localConfig.theme as ColorMode); - applySurfaceTheme(localConfig[SETTINGS_KEYS.SURFACE_THEME]); mobileHeader?.updateCarousel(); } diff --git a/ui/apps/chat/src/lib/constants/settings-keys.constants.ts b/ui/apps/chat/src/lib/constants/settings-keys.constants.ts index b3d37b0e0826..375b935b0a5a 100644 --- a/ui/apps/chat/src/lib/constants/settings-keys.constants.ts +++ b/ui/apps/chat/src/lib/constants/settings-keys.constants.ts @@ -73,7 +73,6 @@ export const SETTINGS_KEYS = { SHOW_THOUGHT_IN_PROGRESS: 'showThoughtInProgress', SHOW_TOOL_CALL_IN_PROGRESS: 'showToolCallInProgress', SINGLE_ROW_CHAT_FORM: 'singleRowChatForm', - SURFACE_THEME: 'surfaceTheme', SYMBOLIC_MATH_ENABLED: 'symbolicMathEnabled', SYSTEM_MESSAGE: 'systemMessage', // Sampling diff --git a/ui/apps/chat/src/lib/constants/settings.constants.ts b/ui/apps/chat/src/lib/constants/settings.constants.ts index 0c4d4c25078e..3109299c3feb 100644 --- a/ui/apps/chat/src/lib/constants/settings.constants.ts +++ b/ui/apps/chat/src/lib/constants/settings.constants.ts @@ -11,9 +11,7 @@ import { VOICE_MICROPHONE_AUTO } from '@ggml-org/llama-voice'; import AudioLines from '@lucide/svelte/icons/audio-lines'; import Code from '@lucide/svelte/icons/code'; import Database from '@lucide/svelte/icons/database'; -import File from '@lucide/svelte/icons/file'; import Funnel from '@lucide/svelte/icons/funnel'; -import GlassWater from '@lucide/svelte/icons/glass-water'; import ListRestart from '@lucide/svelte/icons/list-restart'; import Mic from '@lucide/svelte/icons/mic'; import Monitor from '@lucide/svelte/icons/monitor'; @@ -22,7 +20,7 @@ import PencilRuler from '@lucide/svelte/icons/pencil-ruler'; import SlidersVertical from '@lucide/svelte/icons/sliders-vertical'; import Sun from '@lucide/svelte/icons/sun'; import TextCursorInput from '@lucide/svelte/icons/text-cursor-input'; -import { SurfaceTheme, SyncableParameterType, VoiceInputMode } from '#lib/enums/index.ts'; +import { SyncableParameterType, VoiceInputMode } from '#lib/enums/index.ts'; import { SettingsFieldType } from '#lib/enums/settings.enums.ts'; import { ColorMode } from '#lib/enums/ui.enums.ts'; import type { @@ -84,17 +82,6 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [ ], type: SettingsFieldType.SELECT }, - { - defaultValue: SurfaceTheme.PAPER, - help: 'Choose how the light theme draws its surfaces: Paper puts white panels, fields and buttons on a faint grey page; Matte puts grey glass on a white page. Dark mode is the same for both.', - key: SETTINGS_KEYS.SURFACE_THEME, - label: 'Light surfaces', - options: [ - { icon: File, label: 'Paper', value: SurfaceTheme.PAPER }, - { icon: GlassWater, label: 'Matte', value: SurfaceTheme.MATTE } - ], - type: SettingsFieldType.SELECT - }, { defaultValue: '', help: `Set the API Key if you are using ${CLI_FLAGS.API_KEY} option for the server.`, diff --git a/ui/apps/chat/src/lib/enums/index.ts b/ui/apps/chat/src/lib/enums/index.ts index 1c42190aa41d..9fb53f8af05c 100644 --- a/ui/apps/chat/src/lib/enums/index.ts +++ b/ui/apps/chat/src/lib/enums/index.ts @@ -105,7 +105,6 @@ export { ScrollCarouselVariant, SidebarAction, SidebarSectionKind, - SurfaceTheme, TooltipSide, UrlProtocol } from './ui.enums'; diff --git a/ui/apps/chat/src/lib/enums/ui.enums.ts b/ui/apps/chat/src/lib/enums/ui.enums.ts index c4605943408c..fd55508d0a0d 100644 --- a/ui/apps/chat/src/lib/enums/ui.enums.ts +++ b/ui/apps/chat/src/lib/enums/ui.enums.ts @@ -1,11 +1,5 @@ export { ColorMode, MouseButton, PointerType, TooltipSide } from '@ggml-org/llama-ui/enums'; -/** The light surface theme: Paper (white panels on a faint grey page) or Matte (grey glass on white). */ -export enum SurfaceTheme { - MATTE = 'matte', - PAPER = 'paper' -} - /** * ScrollCarousel arrow placement. */ diff --git a/ui/apps/chat/src/lib/utils/css.ts b/ui/apps/chat/src/lib/utils/css.ts index eaca26f1b501..99351a7f4493 100644 --- a/ui/apps/chat/src/lib/utils/css.ts +++ b/ui/apps/chat/src/lib/utils/css.ts @@ -1,15 +1,3 @@ -import { SurfaceTheme } from '#lib/enums/index.ts'; - -/** - * Applies the light surface theme: Matte sets the theme-matte class on , which the tokens - * read (see tokens/semantic.css); Paper, the default, needs no class. - */ -export function applySurfaceTheme(theme: unknown): void { - if (typeof document === 'undefined') return; - - document.documentElement.classList.toggle('theme-matte', theme === SurfaceTheme.MATTE); -} - /** * Converts a rem CSS value to pixels based on the document root font size. */ diff --git a/ui/apps/chat/src/lib/utils/index.ts b/ui/apps/chat/src/lib/utils/index.ts index c1e2ee4a129d..ae28ff9cd23c 100644 --- a/ui/apps/chat/src/lib/utils/index.ts +++ b/ui/apps/chat/src/lib/utils/index.ts @@ -390,7 +390,7 @@ export { type GgufMetadata, type GgufValue, readGgufMetadata } from './gguf-meta export { uuid } from './uuid'; // CSS utilities -export { applySurfaceTheme, remToPx } from './css'; +export { remToPx } from './css'; // Audio format helper (used by agentic store and chat service) export { getAudioInputFormat } from './audio-format'; diff --git a/ui/apps/chat/src/routes/+layout.svelte b/ui/apps/chat/src/routes/+layout.svelte index 8dfebfe4c394..8fcef551be52 100644 --- a/ui/apps/chat/src/routes/+layout.svelte +++ b/ui/apps/chat/src/routes/+layout.svelte @@ -33,7 +33,7 @@ } from '#lib/stores/index.ts'; import { initStores } from '#lib/stores/init.ts'; import { withBase } from '#lib/utils/base-path.ts'; - import { applySurfaceTheme, hapticTap } from '#lib/utils/index.ts'; + import { hapticTap } from '#lib/utils/index.ts'; import { browser } from '$app/env'; import { afterNavigate, goto } from '$app/navigation'; import { page } from '$app/state'; @@ -53,11 +53,6 @@ let chatSidebar: { editActiveConversation?: () => void } | undefined = $state(); - // the light surface theme (Paper or Matte) follows the saved setting - $effect(() => { - applySurfaceTheme(settingsStore.config[SETTINGS_KEYS.SURFACE_THEME]); - }); - let showBuildVersion = $derived( settingsStore.config[SETTINGS_KEYS.SHOW_BUILD_VERSION] as boolean ); diff --git a/ui/lib/ui/.storybook/preview.ts b/ui/lib/ui/.storybook/preview.ts index 05ff2ad7c38d..c1793e1040ea 100644 --- a/ui/lib/ui/.storybook/preview.ts +++ b/ui/lib/ui/.storybook/preview.ts @@ -49,30 +49,7 @@ const preview: Preview = { test: 'todo' } }, - globalTypes: { - // the light surface theme: Paper (white panels on a grey page) or Matte (grey glass on white) - surface: { - description: 'Light surface theme', - toolbar: { - dynamicTitle: true, - icon: 'paintbrush', - items: [ - { title: 'Paper', value: 'paper' }, - { title: 'Matte', value: 'matte' } - ], - title: 'Surface' - } - } - }, - initialGlobals: { - surface: 'paper' - }, decorators: [ - (story, context) => { - document.documentElement.classList.toggle('theme-matte', context.globals.surface === 'matte'); - - return story(); - }, // `parameters.colorScheme` fixes a story to light or dark, whatever the viewer chose (a scene in a store screenshot) (story, context) => ({ Component: ModeWatcherDecorator, diff --git a/ui/lib/ui/README.md b/ui/lib/ui/README.md index 60abf7592c04..83a42f33d063 100644 --- a/ui/lib/ui/README.md +++ b/ui/lib/ui/README.md @@ -27,7 +27,7 @@ beside the apps built on it in `ui/apps`. `tw-animate-css` (both peer dependencies) and `@ggml-org/llama-brand`'s `css/colors.css` imported before it. - `tokens.css`: the three tiers of tokens only, also after `@ggml-org/llama-brand`'s `css/colors.css`. `fonts.css`: Llama Sans and Llama Mono. `surfaces.css`: the matte surface utilities. -- Dark mode is the `dark` class on ``; the Matte light surfaces are the `theme-matte` class. +- Dark mode is the `dark` class on ``. ## What's in it diff --git a/ui/lib/ui/src/lib/styles/theme.css b/ui/lib/ui/src/lib/styles/theme.css index 4f89b25718be..03ff92773c1e 100644 --- a/ui/lib/ui/src/lib/styles/theme.css +++ b/ui/lib/ui/src/lib/styles/theme.css @@ -10,7 +10,7 @@ * @import '@ggml-org/llama-brand/css/colors.css'; * @import '@ggml-org/llama-ui/theme.css'; * - * Dark mode is the `dark` class on ; the Matte light surfaces are the `theme-matte` class. + * Dark mode is the `dark` class on . */ @import './fonts.css'; diff --git a/ui/lib/ui/src/lib/styles/tokens/components.css b/ui/lib/ui/src/lib/styles/tokens/components.css index 43e5fc345911..24e6143b4d57 100644 --- a/ui/lib/ui/src/lib/styles/tokens/components.css +++ b/ui/lib/ui/src/lib/styles/tokens/components.css @@ -71,11 +71,6 @@ /* status lamps and orbs read the status tokens through orb-danger and friends */ } -/* Matte: dialogs on the page colour (white), like the page under them */ -.theme-matte:not(.dark) { - --float-panel-background-modal: var(--surface-page); -} - .dark { /* in dark the keys stay frosted glass and quiet fills, lighter than the page */ --button-secondary-background: var(--surface-glass); diff --git a/ui/lib/ui/src/lib/styles/tokens/semantic.css b/ui/lib/ui/src/lib/styles/tokens/semantic.css index 2301689a08d8..842e7085912f 100644 --- a/ui/lib/ui/src/lib/styles/tokens/semantic.css +++ b/ui/lib/ui/src/lib/styles/tokens/semantic.css @@ -6,15 +6,13 @@ * mixed from another semantic token by a fixed rule and so follows it through every theme. The rules: * soft text is the text colour at 70%; a hover fill is the fill at 90%; a status surface is its fill mixed * into the page and a status line its fill mixed into the default line; a dark shadow is the light one, - * --elevation-strength times as dense. Derivations are declared once, in :root: .dark and .theme-matte sit - * on the same element, so they resolve from that theme's picks. + * --elevation-strength times as dense. Derivations are declared once, in :root: .dark sits on the + * same element, so they resolve from that theme's picks. * - * Light mode comes in two surface themes that share everything else (colours, buttons, fields, - * shadows): Paper, the default, puts white panels, fields and keys on a faint grey page; Matte - * (the theme-matte class on ) puts grey glass on a white page. + * The light surfaces are paper: white panels, fields and keys on a faint grey page. */ :root { - /* surfaces: what a region of the page sits on. Paper: the page a faint grey, so glass, fields + /* surfaces: what a region of the page sits on. The page a faint grey, so glass, fields and keys, white, sit lighter than it */ --surface-page: var(--neutral-25); --surface-muted: var(--neutral-100); @@ -133,14 +131,6 @@ --blur-control: 0.75rem; } -/* Matte, the alternative light theme: grey glass on a white page, fields on the page colour */ -.theme-matte:not(.dark) { - --surface-page: var(--neutral-0); - --surface-glass: color-mix(in oklch, var(--neutral-100) 60%, transparent); - --surface-code: var(--neutral-50); - --field-background: var(--surface-page); -} - .dark { --surface-page: var(--neutral-925); --surface-muted: var(--neutral-800); From fd24ee26ade8e39a1722aac1b08976fec29f5e17 Mon Sep 17 00:00:00 2001 From: Hongqiang Wang Date: Mon, 23 Nov 2026 12:39:04 -0800 Subject: [PATCH 032/275] opencl: fetch the Adreno binary kernel library at configure time for Windows on Snapdragon (#31759) * opencl: fetch the Adreno binary kernel library at configure time Make GGML_OPENCL_USE_ADRENO_BIN_KERNELS an option, default ON, and add GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH, default ON. On Windows, CMake downloads the pinned adreno-opencl-kernels release from the Qualcomm Software Center, verifies its SHA256, and copies the DLL and its license next to the executables. A failed download is only a warning; the backend then uses its builtin kernels. The opencl-adreno release job turns the fetch off, since it ships only ggml-opencl.dll. * opencl: fetch the Adreno binary kernel library only on ARM64 The library is built for Windows on ARM64 only. * opencl: add download timeout and better handle output dir Assisted-by: Codex * opencl: add .txt to license file Assisted-by: Codex --------- Co-authored-by: Li He --- .github/workflows/release.yml | 2 +- docs/backend/OPENCL.md | 25 ++++++---- ggml/CMakeLists.txt | 2 + ggml/src/ggml-opencl/CMakeLists.txt | 72 +++++++++++++++++++++++++++++ 4 files changed, 91 insertions(+), 10 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c918feb06916..11c97ea2cee4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1129,7 +1129,7 @@ jobs: target: 'ggml-vulkan' - backend: 'opencl-adreno' arch: 'arm64' - defines: '-G "Ninja Multi-Config" -D CMAKE_TOOLCHAIN_FILE=cmake/arm64-windows-llvm.cmake -DCMAKE_PREFIX_PATH="$env:RUNNER_TEMP/opencl-arm64-release" -DGGML_OPENCL=ON -DGGML_OPENCL_USE_ADRENO_KERNELS=ON' + defines: '-G "Ninja Multi-Config" -D CMAKE_TOOLCHAIN_FILE=cmake/arm64-windows-llvm.cmake -DCMAKE_PREFIX_PATH="$env:RUNNER_TEMP/opencl-arm64-release" -DGGML_OPENCL=ON -DGGML_OPENCL_USE_ADRENO_KERNELS=ON -DGGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=OFF' target: 'ggml-opencl' steps: diff --git a/docs/backend/OPENCL.md b/docs/backend/OPENCL.md index 0a9a324fd68d..c912d331cbc2 100644 --- a/docs/backend/OPENCL.md +++ b/docs/backend/OPENCL.md @@ -83,22 +83,29 @@ Since common quantizations are supported now, it is recommanded to download GGUF A prebuilt binary kernel library has been introduced for Adreno GPUs. It currently targets X2 GPUs (X2-90, X2-85 and X2-45) found in Snapdragon X2 SoC. The library currently contains kernels for MUL_MAT_ID with Q4_0, Q4_1, Q4_K, MXFP4. -The library must be manually downloaded from https://softwarecenter.qualcomm.com/catalog/item/Adreno_Kernel_Library_GGML. - -To allow using the kernel library, add `-DGGML_OPENCL_USE_ADRENO_BIN_KERNELS=ON` when configuring with CMake. -Then, extract `adreno-opencl-kernels.dll` from the zip file downloaded from the above URL and put it alongside the executables. +The library is published at https://softwarecenter.qualcomm.com/catalog/item/Adreno_Kernel_Library_GGML. +Its use is subject to the license in the `license.txt` file shipped with it. + +The library is enabled by default (`GGML_OPENCL_USE_ADRENO_BIN_KERNELS=ON`). +On Windows on ARM64, CMake downloads the library version pinned in `ggml/src/ggml-opencl/CMakeLists.txt` during configuration (`GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=ON`). +The download is verified against a SHA256 hash, and the build copies `adreno-opencl-kernels.dll` and `LICENSE-adreno-opencl-kernels.txt` alongside the executables. +If the download fails, configuration continues with a warning. +To skip the download, add `-DGGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=OFF`, then extract `adreno-opencl-kernels.dll` from the zip file downloaded from the above URL and put it alongside the executables yourself. If kernels compatible with the current GPU are found in the library, they will be loaded and used. +If the library is missing, the builtin kernels are used. +Add `-DGGML_OPENCL_USE_ADRENO_BIN_KERNELS=OFF` to disable the library entirely. ## CMake Options The OpenCL backend has the following CMake options that control the behavior of the backend. -| CMake options | Default value | Description | -|:------------------------------------:|:--------------:|:------------------------------------------| -| `GGML_OPENCL_EMBED_KERNELS` | `ON` | Embed OpenCL kernels into the executable. | -| `GGML_OPENCL_USE_ADRENO_KERNELS` | `ON` | Use kernels optimized for Adreno. | -| `GGML_OPENCL_USE_ADRENO_BIN_KERNELS` | `OFF` | Allow using binary kernel lib for Adreno. | +| CMake options | Default value | Description | +|:--------------------------------------:|:--------------:|:--------------------------------------------------------| +| `GGML_OPENCL_EMBED_KERNELS` | `ON` | Embed OpenCL kernels into the executable. | +| `GGML_OPENCL_USE_ADRENO_KERNELS` | `ON` | Use kernels optimized for Adreno. | +| `GGML_OPENCL_USE_ADRENO_BIN_KERNELS` | `ON` | Allow using binary kernel lib for Adreno. | +| `GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH` | `ON` | Download the binary kernel lib for Adreno (Windows ARM64). | ## Decomposed Flash Attention diff --git a/ggml/CMakeLists.txt b/ggml/CMakeLists.txt index 03bdb03edae1..06278c2d3433 100644 --- a/ggml/CMakeLists.txt +++ b/ggml/CMakeLists.txt @@ -269,6 +269,8 @@ option(GGML_OPENCL "ggml: use OpenCL" option(GGML_OPENCL_PROFILING "ggml: use OpenCL profiling (increases overhead)" OFF) option(GGML_OPENCL_EMBED_KERNELS "ggml: embed kernels" ON) option(GGML_OPENCL_USE_ADRENO_KERNELS "ggml: use optimized kernels for Adreno" ON) +option(GGML_OPENCL_USE_ADRENO_BIN_KERNELS "ggml: load the Adreno binary kernel library" ON) +option(GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH "ggml: fetch the Adreno binary kernel library" ON) set (GGML_OPENCL_TARGET_VERSION "300" CACHE STRING "ggml: OpenCL API version to target") diff --git a/ggml/src/ggml-opencl/CMakeLists.txt b/ggml/src/ggml-opencl/CMakeLists.txt index d71802c0385c..1520f8d40e3a 100644 --- a/ggml/src/ggml-opencl/CMakeLists.txt +++ b/ggml/src/ggml-opencl/CMakeLists.txt @@ -36,6 +36,78 @@ endif () if (GGML_OPENCL_USE_ADRENO_BIN_KERNELS) message(STATUS "OpenCL will use precompiled binary kernels for Adreno (improved performance on some platforms)") add_compile_definitions(GGML_OPENCL_USE_ADRENO_BIN_KERNELS) + target_link_libraries(${TARGET_NAME} PRIVATE ${CMAKE_DL_LIBS}) +endif () + +# The library is only published for Windows on ARM64. A failed download is not +# fatal: without the library the backend uses its builtin kernels. +string(TOLOWER "${CMAKE_SYSTEM_PROCESSOR}" ADRENO_BIN_KERNELS_SYSTEM_PROCESSOR) +if (GGML_OPENCL_USE_ADRENO_BIN_KERNELS AND GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH AND + WIN32 AND ADRENO_BIN_KERNELS_SYSTEM_PROCESSOR MATCHES "^(aarch64|arm64)$") + # Bump the version and hash together when a new library release is published. + set(ADRENO_BIN_KERNELS_VERSION "0.0.15") + set(ADRENO_BIN_KERNELS_ZIP_SHA256 "325c89a3bce51abe95f40c6bacece005d5ca9cf6166eb5f17d33592cd13ab795") + set(ADRENO_BIN_KERNELS_URL "https://softwarecenter.qualcomm.com/api/download/software/tools/Adreno_Kernel_Library_GGML/Windows/${ADRENO_BIN_KERNELS_VERSION}/adreno-opencl-kernels-${ADRENO_BIN_KERNELS_VERSION}.zip") + + set(ADRENO_BIN_KERNELS_ROOT "${CMAKE_BINARY_DIR}/_deps/adreno-opencl-kernels-${ADRENO_BIN_KERNELS_VERSION}") + set(ADRENO_BIN_KERNELS_ZIP "${ADRENO_BIN_KERNELS_ROOT}.zip") + set(ADRENO_BIN_KERNELS_DLL "${ADRENO_BIN_KERNELS_ROOT}/adreno-opencl-kernels.dll") + set(ADRENO_BIN_KERNELS_LICENSE "${ADRENO_BIN_KERNELS_ROOT}/license.txt") + + if (NOT EXISTS "${ADRENO_BIN_KERNELS_DLL}" OR NOT EXISTS "${ADRENO_BIN_KERNELS_LICENSE}") + message(STATUS "OpenCL: fetching Adreno binary kernel library ${ADRENO_BIN_KERNELS_VERSION} from Qualcomm; its use is subject to the license in license.txt") + file(DOWNLOAD "${ADRENO_BIN_KERNELS_URL}" "${ADRENO_BIN_KERNELS_ZIP}" + TLS_VERIFY ON + TIMEOUT 120 + INACTIVITY_TIMEOUT 30 + STATUS ADRENO_BIN_KERNELS_DOWNLOAD_STATUS) + list(GET ADRENO_BIN_KERNELS_DOWNLOAD_STATUS 0 ADRENO_BIN_KERNELS_DOWNLOAD_RESULT) + if (ADRENO_BIN_KERNELS_DOWNLOAD_RESULT EQUAL 0) + file(SHA256 "${ADRENO_BIN_KERNELS_ZIP}" ADRENO_BIN_KERNELS_ZIP_ACTUAL_SHA256) + if (NOT ADRENO_BIN_KERNELS_ZIP_ACTUAL_SHA256 STREQUAL ADRENO_BIN_KERNELS_ZIP_SHA256) + file(REMOVE "${ADRENO_BIN_KERNELS_ZIP}") + message(FATAL_ERROR "Adreno binary kernel library hash mismatch: expected ${ADRENO_BIN_KERNELS_ZIP_SHA256}, got ${ADRENO_BIN_KERNELS_ZIP_ACTUAL_SHA256}") + endif () + + file(MAKE_DIRECTORY "${ADRENO_BIN_KERNELS_ROOT}") + execute_process( + COMMAND ${CMAKE_COMMAND} -E tar xf "${ADRENO_BIN_KERNELS_ZIP}" + WORKING_DIRECTORY "${ADRENO_BIN_KERNELS_ROOT}" + RESULT_VARIABLE ADRENO_BIN_KERNELS_EXTRACT_RESULT) + if (NOT ADRENO_BIN_KERNELS_EXTRACT_RESULT EQUAL 0) + message(WARNING "Failed to extract the Adreno binary kernel library from ${ADRENO_BIN_KERNELS_ZIP}") + endif () + else () + list(GET ADRENO_BIN_KERNELS_DOWNLOAD_STATUS 1 ADRENO_BIN_KERNELS_DOWNLOAD_ERROR) + message(WARNING "Failed to download the Adreno binary kernel library (${ADRENO_BIN_KERNELS_DOWNLOAD_ERROR}); " + "the builtin kernels will be used. Set GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=OFF to skip the download.") + endif () + file(REMOVE "${ADRENO_BIN_KERNELS_ZIP}") + endif () + + if (EXISTS "${ADRENO_BIN_KERNELS_DLL}" AND EXISTS "${ADRENO_BIN_KERNELS_LICENSE}") + if (COMMAND license_add_file) + license_add_file("Adreno OpenCL kernels" "${ADRENO_BIN_KERNELS_LICENSE}") + endif () + + set(ADRENO_BIN_KERNELS_OUTPUT_DIR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}") + if (CMAKE_CONFIGURATION_TYPES AND NOT ADRENO_BIN_KERNELS_OUTPUT_DIR MATCHES "\\$<") + string(APPEND ADRENO_BIN_KERNELS_OUTPUT_DIR "/$") + endif () + foreach (CONFIG IN LISTS CMAKE_CONFIGURATION_TYPES CMAKE_BUILD_TYPE) + string(TOUPPER "${CONFIG}" CONFIG_UPPER) + if (DEFINED CMAKE_RUNTIME_OUTPUT_DIRECTORY_${CONFIG_UPPER}) + set(ADRENO_BIN_KERNELS_OUTPUT_DIR "$<$:${CMAKE_RUNTIME_OUTPUT_DIRECTORY_${CONFIG_UPPER}}>$<$>:${ADRENO_BIN_KERNELS_OUTPUT_DIR}>") + endif () + endforeach () + add_custom_target(ggml-opencl-adreno-bin-kernels ALL + COMMAND ${CMAKE_COMMAND} -E make_directory "${ADRENO_BIN_KERNELS_OUTPUT_DIR}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${ADRENO_BIN_KERNELS_DLL}" "${ADRENO_BIN_KERNELS_OUTPUT_DIR}/adreno-opencl-kernels.dll" + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${ADRENO_BIN_KERNELS_LICENSE}" "${ADRENO_BIN_KERNELS_OUTPUT_DIR}/LICENSE-adreno-opencl-kernels.txt") + add_dependencies(${TARGET_NAME} ggml-opencl-adreno-bin-kernels) + install(FILES "${ADRENO_BIN_KERNELS_DLL}" DESTINATION ${CMAKE_INSTALL_BINDIR}) + install(FILES "${ADRENO_BIN_KERNELS_LICENSE}" DESTINATION ${CMAKE_INSTALL_BINDIR} RENAME LICENSE-adreno-opencl-kernels.txt) + endif () endif () function(ggml_opencl_add_kernel KNAME) From c212d25ad34ff1fdf775793cda07e009560cf66b Mon Sep 17 00:00:00 2001 From: Evan Huus Date: Mon, 23 Nov 2026 15:50:29 -0500 Subject: [PATCH 033/275] server : preserve a prompt-cache entry until restores succeed (#32828) Assisted-by: Codex --- tools/server/server-slot-sched.cpp | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/tools/server/server-slot-sched.cpp b/tools/server/server-slot-sched.cpp index 9f977934828f..fccfb709a6db 100644 --- a/tools/server/server-slot-sched.cpp +++ b/tools/server/server-slot-sched.cpp @@ -211,7 +211,7 @@ bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tok const int64_t t_start = ggml_time_us(); { - auto & data = it_best->data.main; + const auto & data = it_best->data.main; const size_t size = data.size(); const size_t n = llama_state_seq_set_data_ext(ctx_tgt, data.data(), size, id_slot, 0); @@ -220,13 +220,10 @@ bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tok return false; } - - data.clear(); - data.shrink_to_fit(); } { - auto & data = it_best->data.drft; + const auto & data = it_best->data.drft; if (!data.empty()) { GGML_ASSERT(ctx_dft); @@ -238,9 +235,6 @@ bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tok return false; } - - data.clear(); - data.shrink_to_fit(); } } From d35dc4d9e6827db8e08426a2340d8a71ea863cd9 Mon Sep 17 00:00:00 2001 From: Aman Gupta Date: Tue, 24 Nov 2026 07:06:02 +0800 Subject: [PATCH 034/275] GDN: use replay instead of rollback (#31669) * GDN: use replay instead of rollback [WIP] * memory : move rs_max with the sequence when find_slot swaps cells find_slot swapped pos/src/rs_pend/seq_id of the cell it moves out of the way, but not rs_max, so that sequence inherited the rollback depth of the cell's previous owner. A smaller value made seq_rm refuse the rollback (#31656), a larger one made snapshot mode restore the previous owner's snapshots. With rs_replay the pending columns are copied along with the state, so rs_max follows the sequence. Without it only the final state is copied and the snapshots stay behind, so the moved sequence gets rs_max 0. * delta_net: drop the graph replay fallback The graph fallback ran the replay as two gdn ops and copied the committed state from the replay gdn when keep, from the main gdn otherwise. Backends whose graph_optimize reorders nodes (Metal, Vulkan) then give keep and non keep ubatches a different node order for the same node count, and the scheduler reallocates on every switch (abort under GGML_SCHED_DEBUG_REALLOC). The replay now always runs in the gdn op. A device without the replay in its gdn op leaves the op to the CPU through the scheduler, as for any unsupported op. This removes LLAMA_RS_REPLAY=2, the replay probe, rs_replay_fused and the rep_mask input. * metal: replay the pending gated delta net tokens in the kernel The gated delta net kernel replays the pending tokens of each seq before the new ones, with the same state update as the main loop and no attention output. With keep, it writes the state after the replay and skips the final state. The replay is a function constant of the pipeline, keep is a kernel argument as on CUDA. The pending buffers fall back to src0 when the op has no replay. * vulkan: replay the pending gated delta net tokens in the shader The gated delta net shader replays the pending tokens of each seq before the new ones, with the same state update as the main loop and no attention output. With keep, it writes the state after the replay and skips the final state. The replay is a specialization constant of the pipeline, keep is a push constant as on CUDA. The pending buffers bind q when the op has no replay. The result checker clones the op with its replay sources. * webgpu: replay the pending gated delta net tokens in the shader The gated delta net shader replays the pending tokens of each seq before the new ones, with the same state update as the main loop and no attention output. With keep, it writes the state after the replay and skips the final state. The replay is a define of the pipeline, keep is a param as on CUDA. The replay count goes through workgroupUniformLoad, so that the loop around the workgroup barriers stays uniform. * delta_net: share the replay conv window views across layers Each replay layer took its own view of the rs_rep_cols input. The scheduler copies every view of a host input as a separate split input, so a verify graph uploaded one copy per layer. The views of the delta net and the PLE conv windows are now built once per graph, like the s_copy views. * vulkan: clamp the gated delta net replay count to n_pend The replay count comes from a buffer, so the shader bounds it to the pending rows before looping over them. The pipeline array comment now names the replay index next to the other ones. Address review from 0cc4m. * hex-gdn: add support for replay Enable replay in HVX path Enable replay in HMX path * gdn: fix rebase conflicts (missing cparams, etc) * llama : drop the fused GDN probes brought back by the rebase il parameter of build_delta_net. The rebase kept them (unused, auto_fgdn was always false), so restore master's version of that code. * delta_net : replay for the KDA models and Clover-MoE Clover-MoE has the Qwen 3.5 layout and only needs the arch gate. Kimi K3, Kimi K3.1, GLM5-Next and BailingMoE3 keep the q, k and v conv windows one after the other in a row. With replay the row holds three channels-first histories [d_inner, window + pending]: build_conv_state_replay takes the gathered rows of the layer and the block index. The pending gate rows hold S_v gates per head (KDA). GLM5-Next gets the -sm tensor split rules for the replay rows. Tested with test-llama-archs models: logits match snapshots bit for bit with random rollbacks (CUDA, Vulkan, CPU), no graph re-plans, and test-llama-context passes in both modes. * cuda : same KDA update in the gated delta net main and replay loops The KDA main loop called expf(g) twice inline, the replay loop reads g from registers. On sm_89 nvcc fused the two loops differently, so a replayed state was a few ulp off the state of the first pass. Compute g into registers in the main loop too: replay matches snapshots bit for bit on sm_89, and the sm_120 output does not change. * opencl: support replay in GDN * llama : replay inputs for the hybrid iswa rel memory input build_inp_mem_hybrid_iswa_rel came in with the rebase: pass hparams and cparams to build_rs_inp_impl and fill the replay inputs in set_input, like the other hybrid inputs. * webgpu: keep the gated delta net replay within the storage buffer limit * delta_net : add ggml_gated_delta_net_ext, replay is the only rollback ggml_gated_delta_net_ext takes the optional replay inputs and always outputs one state. ggml_gated_delta_net(..., K) is back to its master signature and is deprecated; both build the same op, so the backends are unchanged. The delta-net models (qwen35, qwen35moe, qwen4exp, clover-moe and the KDA models) now always replay the kept tokens when n_rs_seq > 0. The LLAMA_RS_REPLAY env flag and the snapshot branch of build_recurrent_attn are removed. test-backend-ops drops the K > 1 snapshot cases and the K parameter of the gated delta net tests. The cache fusion test copies the single state. * ggml-cpu : spacemit: leave the gdn replay to the generic kernel The RVV gated delta net kernel does not read the replay inputs. Return false when op param 1 (n_pend) is set, so that the generic kernel runs the op. * vulkan : fill views at any offset ggml_vk_fill bound dst without allowing a misaligned offset, so a fill of a view whose offset is not a multiple of minStorageBufferOffsetAlignment aborted. The recurrent state zeroing in build_rs hits this with the wider replay conv rows on devices with a 64-byte alignment. Bind dst from the aligned offset below it and pass the element offset in KY. test_fill gets an offset to fill a view in place. --------- Co-authored-by: Pascal Co-authored-by: Max Krasnyansky Co-authored-by: Li He --- ggml/include/ggml.h | 36 ++- ggml/src/ggml-backend-meta.cpp | 11 + ggml/src/ggml-cpu/ggml-cpu.c | 7 +- ggml/src/ggml-cpu/ops.cpp | 56 +++- ggml/src/ggml-cpu/spacemit/ime.cpp | 3 +- ggml/src/ggml-cuda/gated-delta-net-mma.cu | 4 + ggml/src/ggml-cuda/gated-delta-net-mma.cuh | 2 + ggml/src/ggml-cuda/gated_delta_net.cu | 204 ++++++++++++-- ggml/src/ggml-cuda/gated_delta_net.cuh | 5 + ggml/src/ggml-cuda/ggml-cuda.cu | 41 +++ ggml/src/ggml-et/ggml-et.cpp | 3 +- ggml/src/ggml-hexagon/htp-kparams.cpp | 21 ++ .../ggml-hexagon/htp/gated-delta-net-ops.c | 98 +++++-- ggml/src/ggml-metal/ggml-metal-device.cpp | 11 +- ggml/src/ggml-metal/ggml-metal-impl.h | 11 + ggml/src/ggml-metal/ggml-metal-ops.cpp | 21 ++ .../ggml-metal/kernels/gated_delta_net.metal | 64 ++++- ggml/src/ggml-opencl/ggml-opencl.cpp | 76 +++++- .../ggml-opencl/kernels/gated_delta_net.cl | 86 ++++++ ggml/src/ggml-openvino/ggml-openvino.cpp | 3 + ggml/src/ggml-sycl/ggml-sycl.cpp | 4 +- ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp | 7 +- .../ggml-vulkan/ggml-vulkan-push-constants.h | 4 + ggml/src/ggml-vulkan/ggml-vulkan-types.h | 4 +- ggml/src/ggml-vulkan/ggml-vulkan.cpp | 54 +++- ggml/src/ggml-vulkan/vulkan-shaders/fill.comp | 4 +- .../vulkan-shaders/gated_delta_net.comp | 63 ++++- .../ggml-webgpu/ggml-webgpu-shader-lib.hpp | 11 +- ggml/src/ggml-webgpu/ggml-webgpu.cpp | 42 ++- .../wgsl-shaders/gated_delta_net.wgsl | 109 +++++++- ggml/src/ggml.c | 61 ++++- src/llama-context.cpp | 9 + src/llama-cparams.h | 1 + src/llama-graph.cpp | 75 +++++- src/llama-graph.h | 13 + src/llama-memory-hybrid-idx.cpp | 3 +- src/llama-memory-hybrid-idx.h | 1 + src/llama-memory-hybrid-iswa.cpp | 1 + src/llama-memory-hybrid.cpp | 2 + src/llama-memory-hybrid.h | 1 + src/llama-memory-recurrent.cpp | 167 ++++++++++-- src/llama-memory-recurrent.h | 20 +- src/llama-model.cpp | 68 ++++- src/models/bailingmoe3.cpp | 33 ++- src/models/delta-net-base.cpp | 232 ++++++++++++---- src/models/glm5-next.cpp | 33 ++- src/models/kimi-k3.cpp | 33 ++- src/models/kimi-k31.cpp | 33 ++- src/models/models.h | 33 ++- src/models/qwen4exp.cpp | 4 + tests/llama-context/cases-rs.cpp | 2 +- tests/test-backend-ops.cpp | 253 +++++++++++++----- 52 files changed, 1827 insertions(+), 316 deletions(-) diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h index 161e8e0cef47..0007fa18f80e 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -2435,11 +2435,17 @@ extern "C" { // beta : [1, H_v, n_tokens, n_seqs] // state : [S_v, S_v, H_v, n_seqs] -- initial recurrent state s0 // - // the output packs the attention scores [S_v, H_v, n_tokens, n_seqs] followed by K state - // snapshots, most-recent first (slot 0 = final state, slot s = state s tokens back). K == 1 - // keeps only the final state; when n_tokens < K only slots 0..n_tokens-1 are written. - // when n_tokens > K only slot 0 is guaranteed; backends may leave slots 1..K-1 unwritten. - GGML_API struct ggml_tensor * ggml_gated_delta_net( + // the output packs the attention scores [S_v, H_v, n_tokens, n_seqs] followed by the final state [S_v, S_v, H_v, n_seqs] + // + // replay (optional, set all of pend_k, pend_v, pend_gb and n_rep, or none): first runs the pending tokens of the + // previous ubatch, so that a rollback only drops pending tokens instead of restoring a snapshot + // pend_k : [S_k, H_k, n_pend, n_seqs] + // pend_v : [S_v, H_v, n_pend, n_seqs] + // pend_gb : [g0, H_v, 2*n_pend, n_seqs], the gates of the n_pend tokens, then their betas (in element 0) + // n_rep : I32 [n_seqs], number of pending tokens to replay (<= n_pend) + // the state output is the state after the replay if keep is true, else the final state. + // op param 1 is n_pend (0 without replay): backends that do not implement the replay reject the op when it is set + GGML_API struct ggml_tensor * ggml_gated_delta_net_ext( struct ggml_context * ctx, struct ggml_tensor * q, struct ggml_tensor * k, @@ -2447,7 +2453,25 @@ extern "C" { struct ggml_tensor * g, struct ggml_tensor * beta, struct ggml_tensor * state, - int64_t K); + struct ggml_tensor * pend_k, + struct ggml_tensor * pend_v, + struct ggml_tensor * pend_gb, + struct ggml_tensor * n_rep, + bool keep); + + // the output packs the attention scores followed by K state snapshots, most-recent first (slot 0 = final state, + // slot s = state s tokens back). when n_tokens < K only slots 0..n_tokens-1 are written. when n_tokens > K only + // slot 0 is guaranteed; backends may leave slots 1..K-1 unwritten. + GGML_DEPRECATED(GGML_API struct ggml_tensor * ggml_gated_delta_net( + struct ggml_context * ctx, + struct ggml_tensor * q, + struct ggml_tensor * k, + struct ggml_tensor * v, + struct ggml_tensor * g, + struct ggml_tensor * beta, + struct ggml_tensor * state, + int64_t K), + "use ggml_gated_delta_net_ext instead"); // DSA lightning indexer // diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp index 9aed3b7808b8..42a4b4479d04 100644 --- a/ggml/src/ggml-backend-meta.cpp +++ b/ggml/src/ggml-backend-meta.cpp @@ -875,11 +875,22 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state( }; auto handle_gated_delta_net = [&](const std::vector & src_ss) -> ggml_backend_meta_split_state { + // replay (src 6..9): the pending k, v and gates/betas are split by heads like k, v and g, n_rep is per seq + const bool replay = tensor->src[6] != nullptr; if (src_ss[0].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[1].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[2].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[3].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[4].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[5].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED) { + for (int i = 6; replay && i < 10; i++) { + GGML_ASSERT(src_ss[i].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED); + } return src_ss[0]; } + if (replay) { + GGML_ASSERT(src_ss[6].axis == GGML_BACKEND_SPLIT_AXIS_1); + GGML_ASSERT(src_ss[7].axis == GGML_BACKEND_SPLIT_AXIS_1); + GGML_ASSERT(src_ss[8].axis == GGML_BACKEND_SPLIT_AXIS_1); + GGML_ASSERT(src_ss[9].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED); + } GGML_ASSERT(src_ss[0].axis == GGML_BACKEND_SPLIT_AXIS_1); GGML_ASSERT(src_ss[1].axis == GGML_BACKEND_SPLIT_AXIS_1); GGML_ASSERT(src_ss[2].axis == GGML_BACKEND_SPLIT_AXIS_1); diff --git a/ggml/src/ggml-cpu/ggml-cpu.c b/ggml/src/ggml-cpu/ggml-cpu.c index ba075ff8d316..dc0c95bf40c4 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.c +++ b/ggml/src/ggml-cpu/ggml-cpu.c @@ -3068,9 +3068,10 @@ struct ggml_cplan ggml_graph_plan( } break; case GGML_OP_GATED_DELTA_NET: { - const int64_t S_v = node->src[2]->ne[0]; - const int64_t K = ggml_get_op_params_i32(node, 0); - const int64_t per_thread = S_v + (K > 1 ? S_v * S_v : 0); + const int64_t S_v = node->src[2]->ne[0]; + const int64_t K = ggml_get_op_params_i32(node, 0); + const bool keep = node->src[6] && ggml_get_op_params_i32(node, 2) != 0; + const int64_t per_thread = S_v + (K > 1 || keep ? S_v * S_v : 0); cur = per_thread * sizeof(float) * n_tasks; } break; case GGML_OP_COUNT: diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index 26b4a01c96eb..72dd3e6910a2 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -11313,11 +11313,19 @@ static void ggml_compute_forward_gated_delta_net_one_chunk( // per-seq stride in floats (seq s starts at state + s * seq_stride) const int64_t state_seq_stride = src_state->nb[3] / sizeof(float); - const int64_t per_thread = S_v + (K > 1 ? S_v * S_v : 0); + // replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext) + const ggml_tensor * src_pk = dst->src[6]; + const ggml_tensor * src_pv = dst->src[7]; + const ggml_tensor * src_pgb = dst->src[8]; + const ggml_tensor * src_n_rep = dst->src[9]; + const int64_t n_pend = src_pk ? ggml_get_op_params_i32(dst, 1) : 0; + const bool keep = src_pk && ggml_get_op_params_i32(dst, 2) != 0; + + const int64_t per_thread = S_v + (K > 1 || keep ? S_v * S_v : 0); const int ith = params->ith; float * delta = (float *)params->wdata + ith * per_thread + CACHE_LINE_SIZE_F32; - float * state_work = K > 1 ? (delta + S_v) : nullptr; + float * state_work = K > 1 || keep ? (delta + S_v) : nullptr; // output layout: [attn_scores | new_states] // attn_scores: S_v * H * n_tokens * n_seqs floats @@ -11351,7 +11359,7 @@ static void ggml_compute_forward_gated_delta_net_one_chunk( // For K=1, write directly to the single output slot to avoid an extra memcpy at the end. // For K>1, work in scratch and copy out per-token when the slot is in range. - float * s_out = (K > 1) + float * s_out = (K > 1 || keep) ? state_work : state_out_base + (iv3 * H + iv1) * S_v * S_v; @@ -11360,6 +11368,48 @@ static void ggml_compute_forward_gated_delta_net_one_chunk( const float * s_in = state_in_base + iv3 * state_seq_stride + iv1 * S_v * S_v; memcpy(s_out, s_in, S_v * S_v * sizeof(float)); + if (src_pk) { + const int64_t n_r = ((const int32_t *) src_n_rep->data)[iv3]; + GGML_ASSERT(n_r >= 0 && n_r <= n_pend); + + const char * pk = (const char *) src_pk->data + iv3*src_pk->nb[3] + ik1*src_pk->nb[1]; + const char * pv = (const char *) src_pv->data + iv3*src_pv->nb[3] + iv1*src_pv->nb[1]; + const char * pgb = (const char *) src_pgb->data + iv3*src_pgb->nb[3] + iv1*src_pgb->nb[1]; + + for (int64_t t = 0; t < n_r; t++) { + const float * k_d = (const float *) (pk + t*src_pk->nb[2]); + const float * v_d = (const float *) (pv + t*src_pv->nb[2]); + const float * g_d = (const float *) (pgb + t*src_pgb->nb[2]); + const float beta_val = *(const float *) (pgb + (n_pend + t)*src_pgb->nb[2]); + + if (kda) { + for (int64_t i = 0; i < S_v; ++i) { + delta[i] = expf(g_d[i]); + } + for (int64_t j = 0; j < S_v; ++j) { + ggml_vec_mul_f32(S_v, &s_out[j * S_v], &s_out[j * S_v], delta); + } + } else { + ggml_vec_scale_f32(S_v * S_v, s_out, expf(g_d[0])); + } + + for (int64_t j = 0; j < S_v; ++j) { + float sum = 0.0f; + ggml_vec_dot_f32(S_v, &sum, 0, &s_out[j * S_v], 0, k_d, 0, 1); + delta[j] = (v_d[j] - sum) * beta_val; + } + + for (int64_t j = 0; j < S_v; ++j) { + ggml_vec_mad_f32(S_v, &s_out[j * S_v], k_d, delta[j]); + } + } + + // the committed state, the new tokens go on in the scratch + if (keep) { + memcpy(state_out_base + (iv3 * H + iv1) * S_v * S_v, s_out, S_v * S_v * sizeof(float)); + } + } + // attn output pointer for first token of this (head, seq) float * attn_data = attn_out_base + (iv3 * n_tokens * H + iv1) * S_v; diff --git a/ggml/src/ggml-cpu/spacemit/ime.cpp b/ggml/src/ggml-cpu/spacemit/ime.cpp index 0794c115de47..a23e70bc415b 100644 --- a/ggml/src/ggml-cpu/spacemit/ime.cpp +++ b/ggml/src/ggml-cpu/spacemit/ime.cpp @@ -1156,7 +1156,8 @@ class tensor_traits_common : public tensor_traits_base { } return true; case GGML_OP_GATED_DELTA_NET: - if (params->use_ref) { + // the generic kernel does the replay of pending tokens (op param 1) + if (params->use_ref || ggml_get_op_params_i32(op, 1) != 0) { return false; } switch (op->src[0]->type) { diff --git a/ggml/src/ggml-cuda/gated-delta-net-mma.cu b/ggml/src/ggml-cuda/gated-delta-net-mma.cu index 427a334747e6..8fdb1edd4d28 100644 --- a/ggml/src/ggml-cuda/gated-delta-net-mma.cu +++ b/ggml/src/ggml-cuda/gated-delta-net-mma.cu @@ -485,6 +485,10 @@ static gdn_path select_gdn_mma_path(int device, const ggml_cuda_gdn_mma_args & a } // namespace using namespace ggml_cuda_gated_delta_net_mma; +bool ggml_cuda_gdn_mma_supported(int device, const ggml_cuda_gdn_mma_args & a) { + return a.state_out && select_gdn_mma_path(device, a) != gdn_path::ar; +} + bool ggml_cuda_gdn_mma_launch(int device, const ggml_cuda_gdn_mma_args & a, cudaStream_t stream) { if (!a.state_out) { return false; diff --git a/ggml/src/ggml-cuda/gated-delta-net-mma.cuh b/ggml/src/ggml-cuda/gated-delta-net-mma.cuh index 8eb7c4f33647..8659d9ffb191 100644 --- a/ggml/src/ggml-cuda/gated-delta-net-mma.cuh +++ b/ggml/src/ggml-cuda/gated-delta-net-mma.cuh @@ -32,4 +32,6 @@ struct ggml_cuda_gdn_mma_args { bool eligible; }; +// true when ggml_cuda_gdn_mma_launch would run the chunked kernel for these args +bool ggml_cuda_gdn_mma_supported(int device, const ggml_cuda_gdn_mma_args & args); bool ggml_cuda_gdn_mma_launch(int device, const ggml_cuda_gdn_mma_args & args, cudaStream_t stream); diff --git a/ggml/src/ggml-cuda/gated_delta_net.cu b/ggml/src/ggml-cuda/gated_delta_net.cu index ae2374cbcdd7..526030007ea2 100644 --- a/ggml/src/ggml-cuda/gated_delta_net.cu +++ b/ggml/src/ggml-cuda/gated_delta_net.cu @@ -6,7 +6,25 @@ constexpr int gdn_cols_per_warp = 4; -template +// replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext) +struct gdn_replay_args { + const float * pk; // [S_v, H_k, n_pend, n_seqs] + const float * pv; // [S_v, H, n_pend, n_seqs] + const float * pgb; // [g0, H, 2*n_pend, n_seqs], gates then betas + const int32_t * n_rep; // [n_seqs] + int64_t sk1, sk2, sk3; // head, token and seq strides in floats + int64_t sv1, sv2, sv3; + int64_t sg1, sg2, sg3; + int n_pend; + bool keep; // write the state after the replay, not the final one + + // optional: store the k, v, g, beta inputs of the new tokens (fused cpys) + float * st[4]; + int64_t st2[4]; // token stride in floats + int64_t st3[4]; // seq stride in floats +}; + +template __global__ void __launch_bounds__((ggml_cuda_get_physical_warp_size() < S_v ? ggml_cuda_get_physical_warp_size() : S_v) * 4, 2) gated_delta_net_cuda(const float * q, const float * k, @@ -32,7 +50,8 @@ gated_delta_net_cuda(const float * q, const uint3 rq3_magic, float scale, int64_t state_slot_stride, - int K) { + int K, + const gdn_replay_args rep) { const uint32_t h_idx = blockIdx.x; const uint32_t sequence = blockIdx.y; @@ -72,6 +91,53 @@ gated_delta_net_cuda(const float * q, s_shard[r] = curr_state[i]; } + if constexpr (replay) { + const int n_r = rep.n_rep[sequence]; + const float * pk = rep.pk + sequence * rep.sk3 + iq1 * rep.sk1; + const float * pv = rep.pv + sequence * rep.sv3 + h_idx * rep.sv1; + const float * pgb = rep.pgb + sequence * rep.sg3 + h_idx * rep.sg1; + + for (int t = 0; t < n_r; t++) { + const float * k_t = pk + t * rep.sk2; + const float v_col = pv[t * rep.sv2 + col]; + const float * g_t = pgb + t * rep.sg2; + const float beta_val = pgb[(rep.n_pend + t) * rep.sg2]; + + float k_reg[rows_per_lane]; +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + k_reg[r] = k_t[r * lanes_per_col + lane_in_col]; + } + + float g_reg[rows_per_lane]; +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + g_reg[r] = expf(KDA ? g_t[r * lanes_per_col + lane_in_col] : g_t[0]); + } + + // same update as below, without the attention output + float kv_shard = 0.0f; +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + kv_shard += (KDA ? g_reg[r] : 1.0f) * s_shard[r] * k_reg[r]; + } + const float kv_col = warp_reduce_sum(kv_shard); + const float delta_col = (v_col - (KDA ? 1.0f : g_reg[0]) * kv_col) * beta_val; + +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + s_shard[r] = g_reg[r] * s_shard[r] + k_reg[r] * delta_col; + } + } + + if (rep.keep) { +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + state[col * S_v + r * lanes_per_col + lane_in_col] = s_shard[r]; + } + } + } + for (int t = 0; t < n_tokens; t++) { const float * q_t = q + iq3 * sq3 + t * sq2 + iq1 * sq1; const float * k_t = k + iq3 * sq3 + t * sq2 + iq1 * sq1; @@ -93,6 +159,27 @@ gated_delta_net_cuda(const float * q, q_reg[r] = q_t[i]; } + if constexpr (replay && !KDA) { + if (rep.st[0] != nullptr) { + // keep the inputs of this token pending: one CTA per k head writes k, each column its v + const bool first = blockIdx.z == 0 && threadIdx.y == 0 && col_in_warp == 0; + if (first && h_idx < neqk1_magic.z) { + float * dk = rep.st[0] + sequence * rep.st3[0] + t * rep.st2[0] + h_idx * S_v; +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + dk[r * lanes_per_col + lane_in_col] = k_reg[r]; + } + } + if (lane_in_col == 0) { + rep.st[1][sequence * rep.st3[1] + t * rep.st2[1] + h_idx * S_v + col] = v_t[col]; + } + if (first && lane_in_col == 0) { + rep.st[2][sequence * rep.st3[2] + t * rep.st2[2] + h_idx] = *g_t; + rep.st[3][sequence * rep.st3[3] + t * rep.st2[3] + h_idx] = beta_val; + } + } + } + if constexpr (!KDA) { const float g_val = expf(*g_t); @@ -122,12 +209,18 @@ gated_delta_net_cuda(const float * q, attn_data[col] = attn_col * scale; } } else { + // same arithmetic as the replay loop, so that a replayed state matches bit for bit + float g_reg[rows_per_lane]; +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + g_reg[r] = expf(g_t[r * lanes_per_col + lane_in_col]); + } + // kv[col] = sum_i g[i] * S[i][col] * k[i] float kv_shard = 0.0f; #pragma unroll for (int r = 0; r < rows_per_lane; r++) { - const int i = r * lanes_per_col + lane_in_col; - kv_shard += expf(g_t[i]) * s_shard[r] * k_reg[r]; + kv_shard += g_reg[r] * s_shard[r] * k_reg[r]; } float kv_col = warp_reduce_sum(kv_shard); @@ -140,8 +233,7 @@ gated_delta_net_cuda(const float * q, float attn_partial = 0.0f; #pragma unroll for (int r = 0; r < rows_per_lane; r++) { - const int i = r * lanes_per_col + lane_in_col; - s_shard[r] = expf(g_t[i]) * s_shard[r] + k_reg[r] * delta_col; + s_shard[r] = g_reg[r] * s_shard[r] + k_reg[r] * delta_col; attn_partial += s_shard[r] * q_reg[r]; } @@ -170,6 +262,9 @@ gated_delta_net_cuda(const float * q, } if constexpr (!keep_rs_t) { + if (replay && rep.keep) { + return; + } #pragma unroll for (int r = 0; r < rows_per_lane; r++) { const int i = r * lanes_per_col + lane_in_col; @@ -178,7 +273,7 @@ gated_delta_net_cuda(const float * q, } } -template +template static void launch_gated_delta_net( const float * q_d, const float * k_d, const float * v_d, const float * g_d, const float * b_d, const float * s_d, @@ -188,7 +283,7 @@ static void launch_gated_delta_net( int64_t sv1, int64_t sv2, int64_t sv3, int64_t sb1, int64_t sb2, int64_t sb3, int64_t neqk1, int64_t rq3, - float scale, int64_t state_slot_stride, int K, cudaStream_t stream) { + float scale, int64_t state_slot_stride, int K, const gdn_replay_args & rep, cudaStream_t stream) { //TODO: Add chunked kernel for even faster pre-fill const int warp_size = ggml_cuda_info().devices[ggml_cuda_get_device()].warp_size; // four columns per warp (see the kernel); shrink the CTA when the wider CTA would leave @@ -209,29 +304,29 @@ static void launch_gated_delta_net( const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(grid_dims, block_dims, 0, stream); switch (S_v) { case 16: - ggml_cuda_kernel_launch(gated_delta_net_cuda<16, KDA, keep_rs_t>, launch_params, + ggml_cuda_kernel_launch(gated_delta_net_cuda<16, KDA, keep_rs_t, replay>, launch_params, q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); + sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep); break; case 32: - ggml_cuda_kernel_launch(gated_delta_net_cuda<32, KDA, keep_rs_t>, launch_params, + ggml_cuda_kernel_launch(gated_delta_net_cuda<32, KDA, keep_rs_t, replay>, launch_params, q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); + sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep); break; case 64: { - ggml_cuda_kernel_launch(gated_delta_net_cuda<64, KDA, keep_rs_t>, launch_params, + ggml_cuda_kernel_launch(gated_delta_net_cuda<64, KDA, keep_rs_t, replay>, launch_params, q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); + sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep); break; } case 128: { - ggml_cuda_kernel_launch(gated_delta_net_cuda<128, KDA, keep_rs_t>, launch_params, + ggml_cuda_kernel_launch(gated_delta_net_cuda<128, KDA, keep_rs_t, replay>, launch_params, q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); + sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep); break; } default: @@ -353,34 +448,85 @@ static void ggml_cuda_op_gated_delta_net_impl( state_slot_stride = cache->slot_stride; } - { + const ggml_tensor * src_pend = dst->src[6]; + + gdn_replay_args rep = {}; + if (src_pend) { + const ggml_tensor * src_pv = dst->src[7]; + const ggml_tensor * src_pgb = dst->src[8]; + + GGML_ASSERT(K == 1); + rep.pk = (const float *) src_pend->data; + rep.pv = (const float *) src_pv->data; + rep.pgb = (const float *) src_pgb->data; + rep.n_rep = (const int32_t *) dst->src[9]->data; + rep.sk1 = src_pend->nb[1] / sizeof(float); + rep.sk2 = src_pend->nb[2] / sizeof(float); + rep.sk3 = src_pend->nb[3] / sizeof(float); + rep.sv1 = src_pv->nb[1] / sizeof(float); + rep.sv2 = src_pv->nb[2] / sizeof(float); + rep.sv3 = src_pv->nb[3] / sizeof(float); + rep.sg1 = src_pgb->nb[1] / sizeof(float); + rep.sg2 = src_pgb->nb[2] / sizeof(float); + rep.sg3 = src_pgb->nb[3] / sizeof(float); + rep.n_pend = ggml_get_op_params_i32(dst, 1); + rep.keep = ggml_get_op_params_i32(dst, 2) != 0; + if (cache != nullptr) { + for (int i = 0; i < 4; ++i) { + rep.st[i] = cache->in_dst[i]; + rep.st2[i] = cache->in_nb2[i]; + rep.st3[i] = cache->in_nb3[i]; + } + } + } + +#define GDN_LAUNCH_N(KDA, KEEP, REPLAY, N_TOKENS, REP) \ + launch_gated_delta_net(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, \ + S_v, H, N_TOKENS, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, \ + sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, REP, stream) +#define GDN_LAUNCH(KDA, KEEP, REPLAY) GDN_LAUNCH_N(KDA, KEEP, REPLAY, n_tokens, rep) + + if (!src_pend) { ggml_cuda_gdn_mma_args args = ggml_cuda_gdn_mma_args_from_tensor(dst); args.state_out = state_d; if (ggml_cuda_gdn_mma_launch(ctx.device, args, stream)) { return; } + } else if (!rep.keep && rep.st[0] == nullptr) { + // the chunked kernels (not KDA) do not replay: replay the pending tokens into the state output, then + // run the new tokens from there in place (each thread reads and writes the same state elements) + ggml_cuda_gdn_mma_args args = ggml_cuda_gdn_mma_args_from_tensor(dst); + args.state = state_d; + args.state_out = state_d; + if (ggml_cuda_gdn_mma_supported(ctx.device, args)) { + gdn_replay_args rep_only = rep; + rep_only.keep = true; + GDN_LAUNCH_N(false, false, true, 0, rep_only); + ggml_cuda_gdn_mma_launch(ctx.device, args, stream); + return; + } } + if (kda) { if (keep_rs) { - launch_gated_delta_net(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, - S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream); + GDN_LAUNCH(true, true, false); + } else if (src_pend) { + GDN_LAUNCH(true, false, true); } else { - launch_gated_delta_net(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, - S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream); + GDN_LAUNCH(true, false, false); } } else { if (keep_rs) { - launch_gated_delta_net(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, - S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream); + GDN_LAUNCH(false, true, false); + } else if (src_pend) { + GDN_LAUNCH(false, false, true); } else { - launch_gated_delta_net(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, - S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream); + GDN_LAUNCH(false, false, false); } } + +#undef GDN_LAUNCH +#undef GDN_LAUNCH_N } void ggml_cuda_op_gated_delta_net(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { diff --git a/ggml/src/ggml-cuda/gated_delta_net.cuh b/ggml/src/ggml-cuda/gated_delta_net.cuh index f9bf43706789..97c3e0963eff 100644 --- a/ggml/src/ggml-cuda/gated_delta_net.cuh +++ b/ggml/src/ggml-cuda/gated_delta_net.cuh @@ -5,6 +5,11 @@ struct ggml_cuda_gated_delta_net_fused_cache { float * data; // rollback slot 0 int64_t slot_stride; // between rollback slots (0 when K==1) + + // rs_replay: the cpys of the k, v, g, beta inputs into the pending rows, null when not fused + float * in_dst[4] = {}; + int64_t in_nb2[4] = {}; // token stride in elements + int64_t in_nb3[4] = {}; // seq stride in elements }; void ggml_cuda_op_gated_delta_net(ggml_backend_cuda_context & ctx, ggml_tensor * dst); diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index 3e1f167e9936..a07e9a6226a2 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -3647,6 +3647,47 @@ static int ggml_cuda_try_gdn_cache_fusion( fused_state_cpy.data = (float *) dst->data; // rollback group 0 (newest) fused_state_cpy.slot_stride = K > 1 ? (int64_t) (dst->nb[2] / sizeof(float)) : 0; + + // rs_replay: the next 4 real nodes may store the k, v, g, beta inputs into the pending rows + if (gdn->src[6] != nullptr && gdn->src[3]->ne[0] == 1) { + int j = node_idx + skip + 1; + int skip_in = skip; + float * in_dst[4]; + int64_t in_nb2[4]; + int64_t in_nb3[4]; + int i = 0; + for (; i < 4 && j < cgraph->n_nodes; ++j) { + const ggml_tensor * n = cgraph->nodes[j]; + if (ggml_cuda_is_view_or_noop(n)) { + continue; + } + const ggml_tensor * in = gdn->src[1 + i]; + const ggml_tensor * d = n->src[1]; + // the cpy reads the whole input, directly or through a view of the same data + const ggml_tensor * s0 = n->src[0]; + const bool whole_in = s0 == in || (s0 != nullptr && s0->data == in->data && ggml_are_same_shape(s0, in) && + ggml_are_same_stride(s0, in)); + if (n->op != GGML_OP_CPY || (n->flags & GGML_TENSOR_FLAG_OUTPUT) || !whole_in || + d->type != GGML_TYPE_F32 || d->data == nullptr || !ggml_are_same_shape(d, in) || + d->nb[0] != sizeof(float) || d->nb[1] != d->ne[0]*sizeof(float) || d->nb[2] != d->ne[0]*d->ne[1]*sizeof(float)) { + break; + } + in_dst[i] = (float *) d->data; + in_nb2[i] = d->nb[2] / sizeof(float); + in_nb3[i] = d->nb[3] / sizeof(float); + skip_in = j - node_idx; + ++i; + } + if (i == 4) { + for (int c = 0; c < 4; ++c) { + fused_state_cpy.in_dst[c] = in_dst[c]; + fused_state_cpy.in_nb2[c] = in_nb2[c]; + fused_state_cpy.in_nb3[c] = in_nb3[c]; + } + skip = skip_in; + } + } + return skip; } diff --git a/ggml/src/ggml-et/ggml-et.cpp b/ggml/src/ggml-et/ggml-et.cpp index e575ee78b45c..42aa72279625 100644 --- a/ggml/src/ggml-et/ggml-et.cpp +++ b/ggml/src/ggml-et/ggml-et.cpp @@ -1537,7 +1537,8 @@ static bool ggml_backend_et_device_supports_op(ggml_backend_dev_t dev, const ggm op->src[4]->ne[0] == 1 && // beta is scalar per position et_ggml_is_row_contiguous(op->src[0]) && et_ggml_is_row_contiguous(op->src[1]) && et_ggml_is_row_contiguous(op->src[2]) && ggml_is_contiguous(op->src[3]) && - ggml_is_contiguous(op->src[4]) && ggml_is_contiguous(op->src[5])) { + ggml_is_contiguous(op->src[4]) && ggml_is_contiguous(op->src[5]) && + ggml_get_op_params_i32(op, 1) == 0) { // no replay of pending tokens supported = true; } else { supported = false; diff --git a/ggml/src/ggml-hexagon/htp-kparams.cpp b/ggml/src/ggml-hexagon/htp-kparams.cpp index 4e3c5cb8d3df..122d6aee878b 100644 --- a/ggml/src/ggml-hexagon/htp-kparams.cpp +++ b/ggml/src/ggml-hexagon/htp-kparams.cpp @@ -514,7 +514,12 @@ static bool htp_kparams_solve_gated_delta_net( const struct ggml_tensor * g = op->src[3]; const struct ggml_tensor * beta = op->src[4]; const struct ggml_tensor * state = op->src[5]; + const struct ggml_tensor * pend_k = op->src[6]; + const struct ggml_tensor * pend_v = op->src[7]; + const struct ggml_tensor * pend_gb = op->src[8]; + const struct ggml_tensor * n_rep = op->src[9]; const struct ggml_tensor * dst = op; + const bool replay = pend_k != nullptr; if (q->type != GGML_TYPE_F32 || k->type != GGML_TYPE_F32 || v->type != GGML_TYPE_F32 || g->type != GGML_TYPE_F32 || beta->type != GGML_TYPE_F32 || state->type != GGML_TYPE_F32 || @@ -552,6 +557,22 @@ static bool htp_kparams_solve_gated_delta_net( dst->ne[2] != 1 || dst->ne[3] != 1) { return false; } + if ((pend_v != nullptr) != replay || (pend_gb != nullptr) != replay || (n_rep != nullptr) != replay) { + return false; + } + if (replay) { + const int64_t n_pend = ggml_get_op_params_i32(op, 1); + + if (K != 1 || n_pend < 0 || pend_k->type != GGML_TYPE_F32 || pend_v->type != GGML_TYPE_F32 || + pend_gb->type != GGML_TYPE_F32 || n_rep->type != GGML_TYPE_I32 || + pend_k->nb[0] != sizeof(float) || pend_v->nb[0] != sizeof(float) || pend_gb->nb[0] != sizeof(float) || + pend_k->ne[0] != k->ne[0] || pend_k->ne[1] != k->ne[1] || pend_k->ne[2] != n_pend || pend_k->ne[3] != n_seqs || + pend_v->ne[0] != S_v || pend_v->ne[1] != H || pend_v->ne[2] != n_pend || pend_v->ne[3] != n_seqs || + pend_gb->ne[0] != g->ne[0] || pend_gb->ne[1] != H || pend_gb->ne[2] != 2*n_pend || pend_gb->ne[3] != n_seqs || + !ggml_is_contiguous(n_rep) || ggml_nelements(n_rep) != n_seqs) { + return false; + } + } const uint32_t rq3 = (uint32_t) (n_seqs / q->ne[3]); const uint32_t rk3 = (uint32_t) (n_seqs / k->ne[3]); diff --git a/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c b/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c index 0280f99a4af4..68b9c1d4767d 100644 --- a/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c +++ b/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c @@ -574,7 +574,7 @@ static inline HVX_Vector gdn_add_scaled_dot8_f32(float * restrict dst0, float * return Q6_V_vmux_QVV(q16, rA, Q6_V_vror_VR(rB, 128 - 16)); } -static inline void gdn_step_kda_f32( +static __attribute__((noinline)) void gdn_step_kda_f32( float * restrict s_work, float * restrict attn_out, const float * restrict q_t, @@ -662,7 +662,7 @@ static inline void gdn_step_kda_f32( } } -static inline void gdn_step_scalar_f32( +static __attribute__((noinline)) void gdn_step_scalar_f32( float * restrict s_work, float * restrict attn_out, const float * restrict q_t, @@ -748,6 +748,48 @@ static inline void gdn_step_scalar_f32( } } +static inline void gdn_replay_f32( + const struct htp_ops_context * octx, + float * restrict s_work, + uint32_t ik1, + uint32_t iv1, + uint32_t iv3, + bool kda, + float scale, + uint32_t S_v +) { + const struct htp_tensor * pend_k = octx->src[6]; + const struct htp_tensor * pend_v = octx->src[7]; + const struct htp_tensor * pend_gb = octx->src[8]; + const struct htp_tensor * n_rep = octx->src[9]; + + if (!pend_k) { + return; + } + + const uint32_t n_pend = (uint32_t) octx->op_params[1]; + const int32_t raw_n_rep = ((const int32_t *) (uintptr_t) n_rep->data)[iv3]; + const uint32_t n_steps = raw_n_rep <= 0 ? 0 : MIN((uint32_t) raw_n_rep, n_pend); + float unused_attn[128] __attribute__((aligned(128))); + + const uint8_t * pk = (const uint8_t *) (uintptr_t) pend_k->data + (uint64_t) iv3 * pend_k->nb[3] + (uint64_t) ik1 * pend_k->nb[1]; + const uint8_t * pv = (const uint8_t *) (uintptr_t) pend_v->data + (uint64_t) iv3 * pend_v->nb[3] + (uint64_t) iv1 * pend_v->nb[1]; + const uint8_t * pgb = (const uint8_t *) (uintptr_t) pend_gb->data + (uint64_t) iv3 * pend_gb->nb[3] + (uint64_t) iv1 * pend_gb->nb[1]; + + for (uint32_t t = 0; t < n_steps; ++t) { + const float * k_t = (const float *) (pk + (uint64_t) t * pend_k->nb[2]); + const float * v_t = (const float *) (pv + (uint64_t) t * pend_v->nb[2]); + const float * g_t = (const float *) (pgb + (uint64_t) t * pend_gb->nb[2]); + const float beta_val = *(const float *) (pgb + (uint64_t) (n_pend + t) * pend_gb->nb[2]); + + if (kda) { + gdn_step_kda_f32(s_work, unused_attn, k_t, k_t, v_t, g_t, beta_val, scale, S_v); + } else { + gdn_step_scalar_f32(s_work, unused_attn, k_t, k_t, v_t, g_t, beta_val, scale, S_v); + } + } +} + static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { struct htp_gdn_context * gctx = (struct htp_gdn_context *) data; struct htp_ops_context * octx = gctx->octx; @@ -792,6 +834,7 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int const uint32_t state_seq_stride = kparams->state_seq_stride; const uint64_t state_size_per_snap = (uint64_t) kparams->state_size_per_snap; const dma_addr_t state_out_dma_base = dst_cache ? dst_cache->data : (dst->data + S_v * H * n_tokens * n_seqs * sizeof(float)); + const bool keep = octx->src[6] && octx->op_params[2] != 0; uint32_t ir_prefetch = gctx->row_start + ith; int spad_idx = 0; @@ -838,6 +881,10 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int float * attn_data = dst_base + ((uint64_t) iv3 * n_tokens * H + iv1) * S_v; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); + gdn_replay_f32(octx, s_work_curr, ik1, iv1, iv3, kparams->kda, scale, S_v); + if (keep) { + hvx_copy_f32_uu((uint8_t *) (uintptr_t) s_out, (const uint8_t *) s_work_curr, S_v * S_v); + } for (uint32_t t = 0; t < n_tokens; ++t) { const float * q_t = (const float *) ((const uint8_t *) (uintptr_t) q->data + (uint64_t) iq3 * q->nb[3] + (uint64_t) t * q->nb[2] + (uint64_t) iq1 * q->nb[1]); @@ -868,10 +915,9 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); - // Push real write-back dma_queue_push(dma_q, dma_make_data(s_out, s_work_curr), S_v * sizeof(float), S_v * sizeof(float), - S_v * sizeof(float), S_v); + S_v * sizeof(float), keep ? 0 : S_v); // Prefetch next block (if any) if (ir_prefetch < row_end) { @@ -932,6 +978,7 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int const uint32_t state_seq_stride = kparams->state_seq_stride; const dma_addr_t state_out_dma_base = dst_cache ? dst_cache->data : (dst->data + S_v * H * n_seqs * sizeof(float)); + const bool keep = octx->src[6] && octx->op_params[2] != 0; uint32_t ir_prefetch = gctx->row_start + ith; int spad_idx = 0; @@ -989,6 +1036,10 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int (uint64_t) iv3 * beta->nb[3] + (uint64_t) iv1 * beta->nb[1]); htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); + gdn_replay_f32(octx, s_work_curr, ik1, iv1, iv3, kparams->kda, scale, S_v); + if (keep) { + hvx_copy_f32_uu((uint8_t *) (uintptr_t) s_out, (const uint8_t *) s_work_curr, S_v * S_v); + } if (kparams->kda) { gdn_step_kda_f32(s_work_curr, attn_data, q_t, k_t, v_t, g_t, beta_val, scale, S_v); } else { @@ -996,10 +1047,9 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); - // Push real write-back dma_queue_push(dma_q, dma_make_data(s_out, s_work_curr), S_v * sizeof(float), S_v * sizeof(float), - S_v * sizeof(float), S_v); + S_v * sizeof(float), keep ? 0 : S_v); // Prefetch next block (if any) if (ir_prefetch < row_end) { @@ -1654,13 +1704,15 @@ struct htp_gdn_batch_context { const struct htp_gdn_kernel_params * kparams; }; -static void gdn_hvx_init_state_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { +static void gdn_hvx_replay_init_state_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { (void) n; struct htp_gdn_batch_context * bctx = (struct htp_gdn_batch_context *) data; struct htp_thread_trace * tr = th->trace; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, 0); struct htp_gdn_head_ptrs * head = &bctx->heads[i]; + gdn_replay_f32(bctx->octx, head->s_state, head->ik1, head->iv1, head->iv3, + bctx->kparams->kda, bctx->scale, bctx->S_v); gdn_pack_s_col_tiles(head->s_col_tiles, head->s_f16, head->s_state, bctx->S_v); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, 0); @@ -2038,6 +2090,7 @@ static int gated_delta_net_f32_hmx_chunked( const uint32_t chunk_size = kparams->chunk_size; const uint32_t n_chunks = kparams->n_chunks; const uint32_t n_sv_tiles = S_v / 32; + const bool keep = octx->src[6] && octx->op_params[2] != 0; struct htp_gdn_hmx_vtcm_layout L; htp_gdn_hmx_vtcm_layout_build(&L, S_v, chunk_size, kparams->n_heads_batch, kparams->n_hvx, kparams->pipeline != 0); @@ -2101,7 +2154,17 @@ static int gated_delta_net_f32_hmx_chunked( } if (n_chunks > 0) { - work_queue_run(wp, gdn_hvx_init_state_worker, &bctx, n_batch); + work_queue_run(wp, gdn_hvx_replay_init_state_worker, &bctx, n_batch); + + if (keep) { + for (uint32_t h = 0; h < n_batch; ++h) { + dma_queue_push(dma_q, dma_make_data(heads[h].state_out_dma, heads[h].s_state), + S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v); + } + for (uint32_t h = 0; h < n_batch; ++h) { + dma_queue_pop(dma_q); + } + } const uint32_t chunk0_tokens = hex_smin(chunk_size, n_tokens); for (uint32_t h = 0; h < n_batch; ++h) { @@ -2254,12 +2317,14 @@ static int gated_delta_net_f32_hmx_chunked( } } - for (uint32_t h = 0; h < n_batch; ++h) { - dma_queue_push(dma_q, dma_make_data(heads[h].state_out_dma, heads[h].s_state), - S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v); - } - for (uint32_t h = 0; h < n_batch; ++h) { - dma_queue_pop(dma_q); + if (!keep) { + for (uint32_t h = 0; h < n_batch; ++h) { + dma_queue_push(dma_q, dma_make_data(heads[h].state_out_dma, heads[h].s_state), + S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v); + } + for (uint32_t h = 0; h < n_batch; ++h) { + dma_queue_pop(dma_q); + } } } @@ -2270,7 +2335,7 @@ static int gated_delta_net_f32_hmx_chunked( int op_gated_delta_net(struct htp_ops_context * octx) { const struct htp_tensor * dst = octx->dst; - for (int i = 0; i < 6; i++) { + for (int i = 0; i < 10; i++) { if (htp_tensor_is_extended(octx->src[i])) { return HTP_STATUS_NO_SUPPORT; } @@ -2308,9 +2373,6 @@ int op_gated_delta_net(struct htp_ops_context * octx) { ); row_start = range.start; nrows = range.count; - } else if (octx->op_params[1] != 0) { - row_start = octx->op_params[1]; - nrows = octx->op_params[2]; } if (nrows == 0) { diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp index 7a732e29e73c..c4e6ded8b721 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.cpp +++ b/ggml/src/ggml-metal/ggml-metal-device.cpp @@ -752,6 +752,8 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_gated_delta_net( const int ne30 = op->src[3]->ne[0]; // G // state is src[5], 4D [S_v, S_v, H_v, n_seqs] (s0 only); K is op param 0. const int K = ggml_get_op_params_i32(op, 0); + // replay of pending tokens, see ggml_gated_delta_net_ext + const bool replay = op->src[6] != nullptr; const int nsg = op->src[2]->ne[0]/32; @@ -760,15 +762,16 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_gated_delta_net( GGML_ASSERT(ne20 % 32 == 0); snprintf(base, 256, "kernel_gated_delta_net_%s_%d", ggml_type_name(op->src[0]->type), nsg); - snprintf(name, 256, "%s_ne20=%d_ne30=%d_K=%d", base, ne20, ne30, K); + snprintf(name, 256, "%s_ne20=%d_ne30=%d_K=%d_rep=%d", base, ne20, ne30, K, replay ? 1 : 0); ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name); if (!res.pipeline) { ggml_metal_cv_t cv = ggml_metal_cv_init(); - ggml_metal_cv_set_int16(cv, ne20, FC_GATED_DELTA_NET + 0); - ggml_metal_cv_set_int16(cv, ne30, FC_GATED_DELTA_NET + 1); - ggml_metal_cv_set_int16(cv, K, FC_GATED_DELTA_NET + 2); + ggml_metal_cv_set_int16(cv, ne20, FC_GATED_DELTA_NET + 0); + ggml_metal_cv_set_int16(cv, ne30, FC_GATED_DELTA_NET + 1); + ggml_metal_cv_set_int16(cv, K, FC_GATED_DELTA_NET + 2); + ggml_metal_cv_set_bool (cv, replay, FC_GATED_DELTA_NET + 3); res = ggml_metal_library_compile_pipeline(lib, base, name, cv); diff --git a/ggml/src/ggml-metal/ggml-metal-impl.h b/ggml/src/ggml-metal/ggml-metal-impl.h index 4e28b2cb99b9..c0042a8c1020 100644 --- a/ggml/src/ggml-metal/ggml-metal-impl.h +++ b/ggml/src/ggml-metal/ggml-metal-impl.h @@ -1037,6 +1037,17 @@ typedef struct { uint64_t nb2; uint64_t nb3; uint64_t nb_out; // 0 => snapshots are appended after the attn scores (unfused) + int32_t n_pend; // replay: pending tokens per seq in pend_k, pend_v and pend_gb + int32_t keep; // replay: write the state after the replay, not the final one + uint64_t nb61; // pend_k + uint64_t nb62; + uint64_t nb63; + uint64_t nb71; // pend_v + uint64_t nb72; + uint64_t nb73; + uint64_t nb81; // pend_gb + uint64_t nb82; + uint64_t nb83; } ggml_metal_kargs_gated_delta_net; typedef struct { diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp index a7a1ef61e9cf..e1f8610c5b2d 100644 --- a/ggml/src/ggml-metal/ggml-metal-ops.cpp +++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp @@ -2104,6 +2104,12 @@ int ggml_metal_op_gated_delta_net(ggml_metal_op_t ctx, int idx) { } } + // replay of pending tokens, see ggml_gated_delta_net_ext + const ggml_tensor * pk = op->src[6]; + const ggml_tensor * pv = op->src[7]; + const ggml_tensor * pgb = op->src[8]; + const ggml_tensor * rep = op->src[9]; + int ida = 0; ggml_metal_kargs_gated_delta_net args = { @@ -2143,6 +2149,17 @@ int ggml_metal_op_gated_delta_net(ggml_metal_op_t ctx, int idx) { /*.nb2 =*/ nb2, /*.nb3 =*/ nb3, /*.nb_out =*/ nb_out, + /*.n_pend =*/ pk ? ggml_get_op_params_i32(op, 1) : 0, + /*.keep =*/ pk ? ggml_get_op_params_i32(op, 2) : 0, + /*.nb61 =*/ pk ? pk->nb[1] : 0, + /*.nb62 =*/ pk ? pk->nb[2] : 0, + /*.nb63 =*/ pk ? pk->nb[3] : 0, + /*.nb71 =*/ pv ? pv->nb[1] : 0, + /*.nb72 =*/ pv ? pv->nb[2] : 0, + /*.nb73 =*/ pv ? pv->nb[3] : 0, + /*.nb81 =*/ pgb ? pgb->nb[1] : 0, + /*.nb82 =*/ pgb ? pgb->nb[2] : 0, + /*.nb83 =*/ pgb ? pgb->nb[3] : 0, }; ggml_metal_encoder_set_pipeline(enc, pipeline); @@ -2155,6 +2172,10 @@ int ggml_metal_op_gated_delta_net(ggml_metal_op_t ctx, int idx) { ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(op->src[5]), ida++); // state ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(op), ida++); // dst (attn) ggml_metal_encoder_set_buffer (enc, bid_out, ida++); // state_out + ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(pk ? pk : op->src[0]), ida++); // pend_k + ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(pv ? pv : op->src[0]), ida++); // pend_v + ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(pgb ? pgb : op->src[0]), ida++); // pend_gb + ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(rep ? rep : op->src[0]), ida++); // n_rep const int nsg = pipeline.nsg; diff --git a/ggml/src/ggml-metal/kernels/gated_delta_net.metal b/ggml/src/ggml-metal/kernels/gated_delta_net.metal index 5e4861ece360..8e8e04963f5a 100644 --- a/ggml/src/ggml-metal/kernels/gated_delta_net.metal +++ b/ggml/src/ggml-metal/kernels/gated_delta_net.metal @@ -3,6 +3,7 @@ constant short FC_gated_delta_net_ne20 [[function_constant(FC_GATED_DELTA_NET + 0)]]; constant short FC_gated_delta_net_ne30 [[function_constant(FC_GATED_DELTA_NET + 1)]]; constant short FC_gated_delta_net_K [[function_constant(FC_GATED_DELTA_NET + 2)]]; +constant bool FC_gated_delta_net_rep [[function_constant(FC_GATED_DELTA_NET + 3)]]; #if 1 template @@ -16,6 +17,10 @@ kernel void kernel_gated_delta_net_impl( device const char * s, device char * dst, device char * dst_fuse, + device const char * pk, + device const char * pv, + device const char * pgb, + device const char * n_rep, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { @@ -72,6 +77,62 @@ kernel void kernel_gated_delta_net_impl( const device float * state_out = fused ? (device float *)dst_fuse : (device float *)dst + attn_size; const uint slot_stride = fused ? (uint)args.nb_out : state_size_per_snap; + // replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext) + if (FC_gated_delta_net_rep) { + const int n_r = ((device const int32_t *) n_rep)[i23]; + + device const char * pk_ptr = pk + i23*args.nb63 + i11*args.nb61; + device const char * pv_ptr = pv + i23*args.nb73 + i21*args.nb71; + device const char * pgb_ptr = pgb + i23*args.nb83 + i21*args.nb81; + + for (int t = 0; t < n_r; t++) { + device const float * k_t = (device const float *) (pk_ptr + t*args.nb62); + device const float * g_t = (device const float *) (pgb_ptr + t*args.nb82); + + const float v_t = ((device const float *) (pv_ptr + t*args.nb72))[i20]; + const float beta_t = *(device const float *) (pgb_ptr + (args.n_pend + t)*args.nb82); + + // same update as below, without the attention output + float s_k = 0.0f; + + if (G == 1) { + const float g_exp = exp(g_t[0]); + + FOR_UNROLL (short j = 0; j < NSG; j++) { + const short is = tx*NSG + j; + ls[j] *= g_exp; + + s_k += ls[j]*k_t[is]; + } + } else { + // KDA + FOR_UNROLL (short j = 0; j < NSG; j++) { + const short is = tx*NSG + j; + ls[j] *= exp(g_t[is]); + + s_k += ls[j]*k_t[is]; + } + } + + s_k = simd_sum(s_k); + + const float d = (v_t - s_k)*beta_t; + + FOR_UNROLL (short j = 0; j < NSG; j++) { + const short is = tx*NSG + j; + ls[j] += k_t[is]*d; + } + } + + if (args.keep) { + device float * dst_state = (device float *)state_out + state_out_base; + FOR_UNROLL (short j = 0; j < NSG; j++) { + const short is = tx*NSG + j; + dst_state[is] = ls[j]; + } + } + } + for (short t = 0; t < args.ne22; t++) { float s_k = 0.0f; @@ -132,7 +193,8 @@ kernel void kernel_gated_delta_net_impl( } } - if (K == 1) { + // replay with keep: the state output is the state after the replay + if (K == 1 && !(FC_gated_delta_net_rep && args.keep)) { device float * dst_state = (device float *)state_out + state_out_base; FOR_UNROLL (short j = 0; j < NSG; j++) { const short is = tx*NSG + j; diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index 2a3f709a2f30..54038a503ad5 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -1181,9 +1181,9 @@ struct ggml_backend_opencl_context { cl_kernel kernel_conv_2d_f16_f32; cl_kernel kernel_conv2d_dw_f32_f32, kernel_conv2d_dwf16_f32; cl_kernel kernel_ssm_conv_f32_f32, kernel_ssm_conv_f32_f32_4; - // [size_idx][kda][tgpp] where size_idx: 0=S_V=16, 1=32, 2=64, 3=128; kda: 0 or 1. + // [size_idx][kda][tgpp][replay] where size_idx: 0=S_V=16, 1=32, 2=64, 3=128; kda: 0 or 1. // tgpp 0 = TG variant (COLS_PER_LANE_GROUP=1), tgpp 1 = prefill variant (COLS_PER_LANE_GROUP=4). - cl_kernel kernel_gated_delta_net_f32[4][2][2] = {}; + cl_kernel kernel_gated_delta_net_f32[4][2][2][2] = {}; cl_kernel kernel_ssm_scan_f32 = nullptr; cl_kernel kernel_ssm_scan_f32_mamba2_d128 = nullptr; cl_kernel kernel_ssm_scan_f32_mamba2_d256 = nullptr; @@ -5170,7 +5170,7 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { GGML_LOG_CONT("."); } - // gated_delta_net: one kernel per (S_V, KDA, tgpp) triple. + // gated_delta_net: one kernel per (S_V, KDA, tgpp, replay). { #ifdef GGML_OPENCL_EMBED_KERNELS const std::string kernel_src { @@ -5238,11 +5238,14 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { // Please remember to implement code to handle it. opts += " -DSUBGROUPS_PER_WG=" + std::to_string(spw); - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts); + for (int replay = 0; replay < 2; replay++) { + const std::string opts_rep = opts + " -DREPLAY=" + std::to_string(replay); + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts_rep); - CL_CHECK((backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp] = - clCreateKernel(prog, "kernel_gated_delta_net", &err), err)); - CL_CHECK(clReleaseProgram(prog)); + CL_CHECK((backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp][replay] = + clCreateKernel(prog, "kernel_gated_delta_net", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + } } } } @@ -40476,6 +40479,9 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) { const cl_uint n_tokens = (cl_uint) src_v->ne[2]; const cl_uint n_seqs = (cl_uint) src_v->ne[3]; const cl_uint K = (cl_uint) ggml_get_op_params_i32(dst, 0); + const bool replay = dst->src[6] != nullptr; + const cl_uint n_pend = replay ? (cl_uint) ggml_get_op_params_i32(dst, 1) : 0; + const cl_uint keep = replay ? (cl_uint) ggml_get_op_params_i32(dst, 2) : 0; int si; switch (S_v) { @@ -40509,7 +40515,7 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) { // spw needs adjustment when S_v != 128 const int spw = (tgpp == 0) ? 1 : 1; - cl_kernel kernel = backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp]; + cl_kernel kernel = backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp][replay]; GGML_ASSERT(kernel != nullptr); const cl_uint s_off = S_v * H_v * n_tokens * n_seqs; @@ -40576,7 +40582,59 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) { CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &H_k)); CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &rq3)); CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(float), &scale)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &K)); + + if (replay) { + const ggml_tensor * src_pk = dst->src[6]; + const ggml_tensor * src_pv = dst->src[7]; + const ggml_tensor * src_pgb = dst->src[8]; + const ggml_tensor * src_rep = dst->src[9]; + + GGML_ASSERT(src_pk && src_pk->extra); + GGML_ASSERT(src_pv && src_pv->extra); + GGML_ASSERT(src_pgb && src_pgb->extra); + GGML_ASSERT(src_rep && src_rep->extra); + + const ggml_tensor_extra_cl * extra_pk = (const ggml_tensor_extra_cl *) src_pk->extra; + const ggml_tensor_extra_cl * extra_pv = (const ggml_tensor_extra_cl *) src_pv->extra; + const ggml_tensor_extra_cl * extra_pgb = (const ggml_tensor_extra_cl *) src_pgb->extra; + const ggml_tensor_extra_cl * extra_rep = (const ggml_tensor_extra_cl *) src_rep->extra; + + const cl_ulong off_pk = extra_pk->offset + src_pk->view_offs; + const cl_ulong off_pv = extra_pv->offset + src_pv->view_offs; + const cl_ulong off_pgb = extra_pgb->offset + src_pgb->view_offs; + const cl_ulong off_rep = extra_rep->offset + src_rep->view_offs; + + const cl_ulong spk1 = src_pk->nb[1] / sizeof(float); + const cl_ulong spk2 = src_pk->nb[2] / sizeof(float); + const cl_ulong spk3 = src_pk->nb[3] / sizeof(float); + const cl_ulong spv1 = src_pv->nb[1] / sizeof(float); + const cl_ulong spv2 = src_pv->nb[2] / sizeof(float); + const cl_ulong spv3 = src_pv->nb[3] / sizeof(float); + const cl_ulong spg1 = src_pgb->nb[1] / sizeof(float); + const cl_ulong spg2 = src_pgb->nb[2] / sizeof(float); + const cl_ulong spg3 = src_pgb->nb[3] / sizeof(float); + + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &n_pend)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &keep)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pk->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pk)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk2)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk3)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pv->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pv)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv2)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv3)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pgb->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pgb)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg2)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg3)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_rep->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_rep)); + } + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &K)); // Subgroup size is 64 for Adreno and 32 for Intel const int sg_size = backend_ctx->gpu_family == GPU_FAMILY::ADRENO ? 64 : backend_ctx->gpu_family == GPU_FAMILY::INTEL ? 32 : -1; diff --git a/ggml/src/ggml-opencl/kernels/gated_delta_net.cl b/ggml/src/ggml-opencl/kernels/gated_delta_net.cl index 319c9829529a..78b807cfdbba 100644 --- a/ggml/src/ggml-opencl/kernels/gated_delta_net.cl +++ b/ggml/src/ggml-opencl/kernels/gated_delta_net.cl @@ -18,6 +18,9 @@ #ifndef KDA #define KDA 0 #endif +#ifndef REPLAY +#define REPLAY 0 +#endif #ifndef SUBGROUP_SIZE #define SUBGROUP_SIZE 64 #endif @@ -97,6 +100,13 @@ kernel void kernel_gated_delta_net( uint H_k, uint rq3, float scale, +#if REPLAY + uint n_pend, uint keep, + global const char * pk_buf, ulong off_pk, ulong spk1, ulong spk2, ulong spk3, + global const char * pv_buf, ulong off_pv, ulong spv1, ulong spv2, ulong spv3, + global const char * pgb_buf, ulong off_pgb, ulong spg1, ulong spg2, ulong spg3, + global const char * rep_buf, ulong off_rep, +#endif uint K) { global const float * data_q = (global const float *)(q_buf + off_q); @@ -144,6 +154,77 @@ kernel void kernel_gated_delta_net( } } +#if REPLAY + global const float * data_pk = (global const float *)(pk_buf + off_pk); + global const float * data_pv = (global const float *)(pv_buf + off_pv); + global const float * data_pgb = (global const float *)(pgb_buf + off_pgb); + global const int * data_n_rep = (global const int *)(rep_buf + off_rep); + const uint n_r = (uint)clamp(data_n_rep[seq_id], 0, (int)n_pend); + + for (uint t = 0; t < n_r; t++) { + const ulong k_off = seq_id * spk3 + t * spk2 + iq1 * spk1; + const ulong v_off = seq_id * spv3 + t * spv2 + head_id * spv1; + const ulong g_off = seq_id * spg3 + t * spg2 + head_id * spg1; + const float beta_val = data_pgb[g_off + n_pend * spg2]; + + float k_reg[ROWS_PER_LANE]; + #pragma unroll + for (uint r = 0; r < ROWS_PER_LANE; r++) { + k_reg[r] = data_pk[k_off + r * LANES_PER_COLUMN + lane]; + } + +#if KDA + float g_exp[ROWS_PER_LANE]; + #pragma unroll + for (uint r = 0; r < ROWS_PER_LANE; r++) { + g_exp[r] = exp(data_pgb[g_off + r * LANES_PER_COLUMN + lane]); + } +#else + const float g_val = exp(data_pgb[g_off]); +#endif + + // Same state update as the main loop, without the attention output. + #pragma unroll + for (uint cg = 0; cg < COLS_PER_LANE_GROUP; cg++) { + const uint col = sg_col_base + cg * LANE_GROUPS_PER_SG + lane_group; + float kv_shard = 0.0f; + #pragma unroll + for (uint r = 0; r < ROWS_PER_LANE; r++) { +#if KDA + kv_shard += g_exp[r] * s_shard[cg][r] * k_reg[r]; +#else + kv_shard += s_shard[cg][r] * k_reg[r]; +#endif + } +#if !KDA + kv_shard *= g_val; +#endif + const float kv_col = REDUCE_PARTIAL(kv_shard, temp_ptr, sg_lid); + const float delta_col = (data_pv[v_off + col] - kv_col) * beta_val; + #pragma unroll + for (uint r = 0; r < ROWS_PER_LANE; r++) { +#if KDA + const float gs = g_exp[r] * s_shard[cg][r]; +#else + const float gs = g_val * s_shard[cg][r]; +#endif + s_shard[cg][r] = gs + k_reg[r] * delta_col; + } + } + } + + if (keep) { + #pragma unroll + for (uint cg = 0; cg < COLS_PER_LANE_GROUP; cg++) { + const uint col = sg_col_base + cg * LANE_GROUPS_PER_SG + lane_group; + #pragma unroll + for (uint r = 0; r < ROWS_PER_LANE; r++) { + data_dst[s_off + state_base + col * S_V + r * LANES_PER_COLUMN + lane] = s_shard[cg][r]; + } + } + } +#endif + // snapshot slot mapping: slot 0 = most recent state, slot s = s tokens back. // When n_tokens < K only slots 0..n_tokens-1 are written; older slots are caller-owned. uint attn_off = (seq_id * n_tokens * H_v + head_id) * S_V; @@ -236,6 +317,11 @@ kernel void kernel_gated_delta_net( } } +#if REPLAY + if (keep) { + return; + } +#endif if (K == 1u) { #pragma unroll for (uint cg = 0; cg < COLS_PER_LANE_GROUP; cg++) { diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 7e64c03c2bc1..e1ba0baeb94b 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -2113,6 +2113,9 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { } return {false, reason}; } + if (((const int32_t *) op->op_params)[1] != 0) { + return {false, "GATED_DELTA_NET with replay of pending tokens is not supported"}; + } break; } case GGML_OP_SSM_SCAN: { diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp index 75df12c733cb..12d1bdfba36c 100644 --- a/ggml/src/ggml-sycl/ggml-sycl.cpp +++ b/ggml/src/ggml-sycl/ggml-sycl.cpp @@ -7709,10 +7709,12 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons case GGML_OP_RWKV_WKV6: case GGML_OP_RWKV_WKV7: case GGML_OP_GATED_LINEAR_ATTN: - case GGML_OP_GATED_DELTA_NET: case GGML_OP_OPT_STEP_ADAMW: case GGML_OP_OPT_STEP_SGD: return true; + case GGML_OP_GATED_DELTA_NET: + // replay of pending tokens (op param 1) is not implemented + return ggml_get_op_params_i32(op, 1) == 0; case GGML_OP_SSM_CONV: return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32 && diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp b/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp index 79258b871145..42f058bd8e26 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp @@ -1370,9 +1370,10 @@ void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph } else if (tensor->op == GGML_OP_LIGHTNING_INDEXER) { tensor_clone = ggml_lightning_indexer(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3]); } else if (tensor->op == GGML_OP_GATED_DELTA_NET) { - tensor_clone = ggml_gated_delta_net(ggml_ctx, src_clone[0], src_clone[1], - src_clone[2], src_clone[3], src_clone[4], src_clone[5], - ggml_get_op_params_i32(tensor, 0)); + GGML_ASSERT(ggml_get_op_params_i32(tensor, 0) == 1); // K > 1 comes from the deprecated ggml_gated_delta_net + tensor_clone = ggml_gated_delta_net_ext(ggml_ctx, src_clone[0], src_clone[1], + src_clone[2], src_clone[3], src_clone[4], src_clone[5], src_clone[6], src_clone[7], src_clone[8], src_clone[9], + ggml_get_op_params_i32(tensor, 2) != 0); } else if (tensor->op == GGML_OP_OPT_STEP_ADAMW) { src_clone[0]->flags = tensor->src[0]->flags; tensor_clone = ggml_opt_step_adamw(ggml_ctx, src_clone[0], src_clone[1], diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h index 7a48c08dc3a9..026ad8935e34 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h @@ -794,6 +794,10 @@ struct vk_op_gated_delta_net_push_constants { uint32_t neq1, rq3; float scale; uint32_t K; + uint32_t n_pend, keep; // replay: pending tokens per seq, write the state after the replay + uint32_t spk1, spk2, spk3; // replay: pend_k, pend_v and pend_gb strides in floats + uint32_t spv1, spv2, spv3; + uint32_t spg1, spg2, spg3; }; struct vk_op_ssm_scan_push_constants { diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-types.h b/ggml/src/ggml-vulkan/ggml-vulkan-types.h index 211948ee793b..f200b43d30f5 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-types.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-types.h @@ -1013,8 +1013,8 @@ struct vk_device_struct { vk_pipeline pipeline_rwkv_wkv7_f32; vk_pipeline pipeline_gated_linear_attn_f32; vk_pipeline pipeline_lightning_indexer_f32[GGML_TYPE_COUNT]; - // [size_idx][kda] where size_idx: 0=d16, 1=d32, 2=d64, 3=d128 - vk_pipeline pipeline_gated_delta_net[4][2]; + // [size_idx][kda][replay] where size_idx: 0=d16, 1=d32, 2=d64, 3=d128 + vk_pipeline pipeline_gated_delta_net[4][2][2]; vk_pipeline pipeline_gated_delta_net_cm; vk_pipeline pipeline_gated_delta_net_cm_v32; vk_pipeline pipeline_gated_delta_net_cm_v128; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index 0711166f9671..88e595f4a8e9 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -4212,9 +4212,12 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { const std::array wg_denoms = {1u, 1u, cols_per_wg}; for (uint32_t kda = 0; kda < 2; kda++) { - ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net[si][kda], - gdn_names[si][kda], gdn_len, gdn_data, "main", 7, sizeof(vk_op_gated_delta_net_push_constants), - wg_denoms, {S_V, kda, gdn_subgroup_size, lanes_per_column, uint32_t(gdn_packed_rows)}, 1, true, use_subgroup_ops, gdn_subgroup_size); + for (uint32_t rep = 0; rep < 2; rep++) { + const std::string name = std::string(gdn_names[si][kda]) + (rep ? "_rep" : ""); + ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net[si][kda][rep], + name.c_str(), gdn_len, gdn_data, "main", 11, sizeof(vk_op_gated_delta_net_push_constants), + wg_denoms, {S_V, kda, gdn_subgroup_size, lanes_per_column, uint32_t(gdn_packed_rows), rep}, 1, true, use_subgroup_ops, gdn_subgroup_size); + } } } @@ -10235,6 +10238,7 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { const uint32_t S_v = dst->src[2]->ne[0]; const uint32_t kda = (dst->src[3]->ne[0] == (int64_t)S_v) ? 1 : 0; + const uint32_t rep = dst->src[6] != nullptr ? 1 : 0; uint32_t si; switch (S_v) { case 16: si = 0; break; @@ -10243,7 +10247,7 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const case 128: si = 3; break; default: return nullptr; } - return ctx->device->pipeline_gated_delta_net[si][kda]; + return ctx->device->pipeline_gated_delta_net[si][kda][rep]; } return nullptr; case GGML_OP_SSM_SCAN: @@ -11357,7 +11361,8 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, const bool use_cm = (ctx->device->pipeline_gated_delta_net_cm != nullptr || ctx->device->pipeline_gated_delta_net_cm_v32 != nullptr || ctx->device->pipeline_gated_delta_net_cm_v128 != nullptr) && - src_g->ne[0] == 1 && S_v == 128 && dst->src[0]->ne[0] == 128 && K == 1 && n_tokens >= cm_min_tokens; + src_g->ne[0] == 1 && S_v == 128 && dst->src[0]->ne[0] == 128 && K == 1 && n_tokens >= cm_min_tokens && + dst->src[6] == nullptr; // the chunked kernels do not replay const bool use_cm2 = use_cm && ctx->device->coopmat2; const bool have_v64 = ctx->device->pipeline_gated_delta_net_cm != nullptr; @@ -11389,9 +11394,10 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst); - vk_subbuffer src_buf[6] = {}; - for (int i = 0; i < 6; i++) { - src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]); + vk_subbuffer src_buf[10] = {}; + for (int i = 0; i < 10; i++) { + // the replay sources 6..9 bind q when the op has no replay + src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i] ? dst->src[i] : src_q); } vk_subbuffer mirror_buf{}; @@ -11409,6 +11415,11 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, mirror_buf = vk_subbuffer{ ctx->prealloc_x, 0, ctx->prealloc_x->size }; } + // replay of pending tokens, see ggml_gated_delta_net_ext + const ggml_tensor * src_pk = dst->src[6]; + const ggml_tensor * src_pv = dst->src[7]; + const ggml_tensor * src_pgb = dst->src[8]; + const uint32_t sq1 = (uint32_t)(src_q->nb[1] / sizeof(float)); const uint32_t sq2 = (uint32_t)(src_q->nb[2] / sizeof(float)); const uint32_t sq3 = (uint32_t)(src_q->nb[3] / sizeof(float)); @@ -11434,7 +11445,18 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, sb1, sb2, sb3, neq1, rq3, scale, - K + K, + src_pk ? (uint32_t)ggml_get_op_params_i32(dst, 1) : 0u, + src_pk ? (uint32_t)ggml_get_op_params_i32(dst, 2) : 0u, + src_pk ? (uint32_t)(src_pk->nb[1] / sizeof(float)) : 0u, + src_pk ? (uint32_t)(src_pk->nb[2] / sizeof(float)) : 0u, + src_pk ? (uint32_t)(src_pk->nb[3] / sizeof(float)) : 0u, + src_pv ? (uint32_t)(src_pv->nb[1] / sizeof(float)) : 0u, + src_pv ? (uint32_t)(src_pv->nb[2] / sizeof(float)) : 0u, + src_pv ? (uint32_t)(src_pv->nb[3] / sizeof(float)) : 0u, + src_pgb ? (uint32_t)(src_pgb->nb[1] / sizeof(float)) : 0u, + src_pgb ? (uint32_t)(src_pgb->nb[2] / sizeof(float)) : 0u, + src_pgb ? (uint32_t)(src_pgb->nb[3] / sizeof(float)) : 0u, }; if (use_v128) { @@ -11442,10 +11464,15 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf, mirror_buf}, pc, std::array{ S_v / cm_V, n_seqs, H }); ctx->prealloc_x_need_sync = true; - } else { + } else if (use_cm) { ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf}, - pc, use_cm ? std::array{ S_v / cm_V, n_seqs, H } : std::array{ H, n_seqs, S_v }); + pc, std::array{ S_v / cm_V, n_seqs, H }); + } else { + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf, + src_buf[6], src_buf[7], src_buf[8], src_buf[9]}, + pc, std::array{ H, n_seqs, S_v }); } } @@ -11692,9 +11719,10 @@ void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor const uint64_t n = ggml_nelements(dst); GGML_ASSERT(n > 0); + // dst can be a view at any offset: bind from the aligned offset below it, the shader skips KY elements vk_op_push_constants pc = { (uint32_t)n, - 1, + get_misalign_bytes(ctx, dst) / (uint32_t)ggml_type_size(dst->type), ggml_get_op_params_f32(dst, 0), 0.0f, 0.0f, 0.0f, @@ -11710,7 +11738,7 @@ void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor GGML_ASSERT(wg_y <= ctx->device->properties.limits.maxComputeWorkGroupCount[1]); ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); - vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false); + vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true); std::array elements = { wg_x * pipeline->wg_denoms[0], wg_y * pipeline->wg_denoms[1], 1 }; ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements); diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/fill.comp b/ggml/src/ggml-vulkan/vulkan-shaders/fill.comp index b5cc33322078..bfae6a3d128c 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/fill.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/fill.comp @@ -16,6 +16,6 @@ void main() { return; } - // p.param1 = fill value - data_d[i] = D_TYPE(p.param1); + // p.param1 = fill value, p.KY = element offset of dst in the bound buffer + data_d[p.KY + i] = D_TYPE(p.param1); } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp index ad2ced78aa39..75c32a067595 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp @@ -16,6 +16,7 @@ layout(constant_id = 1) const uint KDA = 0; layout(constant_id = 2) const uint SUBGROUP_SIZE = 32; layout(constant_id = 3) const uint LANES_PER_COLUMN = 32; layout(constant_id = 4) const bool PACKED_ROWS = false; +layout(constant_id = 5) const uint REPLAY = 0; const uint COLS_PER_WG = SUBGROUP_SIZE / LANES_PER_COLUMN; const uint ROWS_PER_LANE = S_V / LANES_PER_COLUMN; @@ -42,6 +43,10 @@ layout(push_constant) uniform Parameters { uint neq1, rq3; float scale; uint K; + uint n_pend, keep; + uint spk1, spk2, spk3; + uint spv1, spv2, spv3; + uint spg1, spg2, spg3; }; layout(binding = 0) readonly buffer QBuf { FLOAT_TYPE data_q[]; }; @@ -52,6 +57,12 @@ layout(binding = 4) readonly buffer BetaBuf { FLOAT_TYPE data_beta[]; }; layout(binding = 5) readonly buffer StateBuf { FLOAT_TYPE data_state[]; }; layout(binding = 6) buffer DstBuf { FLOAT_TYPE data_dst[]; }; +// replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext) +layout(binding = 7) readonly buffer PKBuf { FLOAT_TYPE data_pk[]; }; +layout(binding = 8) readonly buffer PVBuf { FLOAT_TYPE data_pv[]; }; +layout(binding = 9) readonly buffer PGBBuf { FLOAT_TYPE data_pgb[]; }; +layout(binding = 10) readonly buffer NRepBuf { int data_n_rep[]; }; + #if !USE_SUBGROUP_ADD && !USE_SUBGROUP_CLUSTERED shared FLOAT_TYPE temp[SUBGROUP_SIZE]; @@ -123,6 +134,55 @@ void main() { s_shard[r] = FLOAT_TYPE(data_state[state_in_base + col * S_V + row_index(r, lane)]); } + if (REPLAY != 0) { + const uint n_r = uint(clamp(data_n_rep[seq_id], 0, int(n_pend))); + + for (uint t = 0; t < n_r; t++) { + const uint k_off = seq_id * spk3 + t * spk2 + iq1 * spk1; + const uint v_off = seq_id * spv3 + t * spv2 + head_id * spv1; + const uint g_off = seq_id * spg3 + t * spg2 + head_id * spg1; + const FLOAT_TYPE beta_val = FLOAT_TYPE(data_pgb[g_off + n_pend * spg2]); + + FLOAT_TYPE k_reg[ROWS_PER_LANE]; + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + k_reg[r] = FLOAT_TYPE(data_pk[k_off + row_index(r, lane)]); + } + + FLOAT_TYPE g_exp[ROWS_PER_LANE]; + if (KDA == 0) { + const FLOAT_TYPE g_val = exp(FLOAT_TYPE(data_pgb[g_off])); + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + g_exp[r] = g_val; + } + } else { + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + g_exp[r] = exp(FLOAT_TYPE(data_pgb[g_off + row_index(r, lane)])); + } + } + + const FLOAT_TYPE v_val = FLOAT_TYPE(data_pv[v_off + col]); + + // same update as below, without the attention output + FLOAT_TYPE kv_shard = 0.0; + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + kv_shard += g_exp[r] * s_shard[r] * k_reg[r]; + } + FLOAT_TYPE kv_col = reduce_partial(kv_shard); + + FLOAT_TYPE delta_col = (v_val - kv_col) * beta_val; + + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + s_shard[r] = g_exp[r] * s_shard[r] + k_reg[r] * delta_col; + } + } + + if (keep != 0) { + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + data_dst[s_off + state_out_base + col * S_V + row_index(r, lane)] = s_shard[r]; + } + } + } + // snapshot slot mapping: slot 0 = most recent state, slot s = s tokens back. // When n_tokens < K, only slots 0..n_tokens-1 are written; older slots are caller-owned. @@ -191,7 +251,8 @@ void main() { } } - if (K == 1u) { + // replay with keep: the state output is the state after the replay + if (K == 1u && !(REPLAY != 0 && keep != 0)) { [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { data_dst[s_off + state_out_base + col * S_V + row_index(r, lane)] = s_shard[r]; } diff --git a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp index 8896efb5af4a..6b618bb16370 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp @@ -450,9 +450,11 @@ struct ggml_webgpu_gated_delta_net_pipeline_key { int s_v; int kda; bool fused_cache; + bool replay; bool operator==(const ggml_webgpu_gated_delta_net_pipeline_key & other) const { - return type == other.type && s_v == other.s_v && kda == other.kda && fused_cache == other.fused_cache; + return type == other.type && s_v == other.s_v && kda == other.kda && fused_cache == other.fused_cache && + replay == other.replay; } }; @@ -462,6 +464,7 @@ struct ggml_webgpu_gated_delta_net_pipeline_key_hash { ggml_webgpu_hash_combine(seed, key.type); ggml_webgpu_hash_combine(seed, key.s_v); ggml_webgpu_hash_combine(seed, key.kda); + ggml_webgpu_hash_combine(seed, key.replay); return seed; } }; @@ -2015,6 +2018,7 @@ class ggml_webgpu_shader_lib { key.s_v = (int) context.src2->ne[0]; key.kda = context.src3->ne[0] == context.src2->ne[0]; key.fused_cache = context.dst_fuse != nullptr; + key.replay = context.dst->src[6] != nullptr; auto it = gated_delta_net_pipelines.find(key); if (it != gated_delta_net_pipelines.end()) { @@ -2042,6 +2046,11 @@ class ggml_webgpu_shader_lib { variant += "_fused_cache"; } + if (key.replay) { + defines.push_back("REPLAY"); + variant += "_replay"; + } + defines.push_back("S_V=" + std::to_string(key.s_v) + "u"); defines.push_back("WG_SIZE=" + std::to_string(key.s_v) + "u"); diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp index 4bb43926daaa..daf83ee83ce4 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp @@ -1497,6 +1497,11 @@ static webgpu_encoded_op ggml_webgpu_ssm_scan(webgpu_context & ctx, return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y); } +// storage buffers of the gated delta net shader: q, k, v, g, beta, state and dst, the fused cache, then the replay inputs +static uint32_t ggml_webgpu_gated_delta_net_n_storage_buffers(const ggml_tensor * op, bool fused_cache) { + return 7 + (fused_cache ? 1 : 0) + (op->src[6] != nullptr ? 4 : 0); +} + static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx, ggml_tensor * src0, ggml_tensor * src1, @@ -1527,6 +1532,12 @@ static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx, uint32_t scale_u32; memcpy(&scale_u32, &scale, sizeof(scale_u32)); + // replay of pending tokens, see ggml_gated_delta_net_ext + ggml_tensor * pend_k = dst->src[6]; + ggml_tensor * pend_v = dst->src[7]; + ggml_tensor * pend_gb = dst->src[8]; + ggml_tensor * n_rep = dst->src[9]; + std::vector params = { h, n_tokens, @@ -1551,6 +1562,21 @@ static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx, scale_u32, dst_fuse ? (uint32_t) (dst_fuse->nb[2] / ggml_type_size(dst_fuse->type)) : 0, dst_fuse ? (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst_fuse) / ggml_type_size(dst_fuse->type)) : 0, + + pend_k ? (uint32_t) ggml_get_op_params_i32(dst, 1) : 0, + pend_k ? (uint32_t) ggml_get_op_params_i32(dst, 2) : 0, + + pend_k ? (uint32_t) (pend_k->nb[1] / ggml_type_size(pend_k->type)) : 0, + pend_k ? (uint32_t) (pend_k->nb[2] / ggml_type_size(pend_k->type)) : 0, + pend_k ? (uint32_t) (pend_k->nb[3] / ggml_type_size(pend_k->type)) : 0, + + pend_v ? (uint32_t) (pend_v->nb[1] / ggml_type_size(pend_v->type)) : 0, + pend_v ? (uint32_t) (pend_v->nb[2] / ggml_type_size(pend_v->type)) : 0, + pend_v ? (uint32_t) (pend_v->nb[3] / ggml_type_size(pend_v->type)) : 0, + + pend_gb ? (uint32_t) (pend_gb->nb[1] / ggml_type_size(pend_gb->type)) : 0, + pend_gb ? (uint32_t) (pend_gb->nb[2] / ggml_type_size(pend_gb->type)) : 0, + pend_gb ? (uint32_t) (pend_gb->nb[3] / ggml_type_size(pend_gb->type)) : 0, }; std::vector entries = { @@ -1564,6 +1590,14 @@ static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx, entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 7, dst_fuse)); } + if (pend_k) { + const uint32_t binding = dst_fuse ? 8 : 7; + entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 0, pend_k)); + entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 1, pend_v)); + entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 2, pend_gb)); + entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 3, n_rep)); + } + return ggml_backend_webgpu_build(ctx, pipeline, params, entries, h, n_seqs); } @@ -3728,7 +3762,9 @@ static std::optional ggml_webgpu_encode(webgpu_context ctx, return ggml_webgpu_ssm_scan(ctx, src0, src1, src2, node->src[3], node->src[4], node->src[5], node->src[6], node); case GGML_OP_GATED_DELTA_NET: - if (ggml_webgpu_can_fuse_gdn_cache(cgraph, node_idx, num_encoded_ops)) { + if (ggml_webgpu_gated_delta_net_n_storage_buffers(node, true) <= + ctx->global_ctx->capabilities.limits.maxStorageBuffersPerShaderStage && + ggml_webgpu_can_fuse_gdn_cache(cgraph, node_idx, num_encoded_ops)) { ggml_tensor * dst_fuse = cgraph->nodes[node_idx + num_encoded_ops - 1]->src[1]; return ggml_webgpu_gated_delta_net(ctx, src0, src1, src2, node->src[3], node->src[4], node->src[5], node, dst_fuse); @@ -5270,7 +5306,9 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const src2->type == GGML_TYPE_F32 && op->src[3]->type == GGML_TYPE_F32 && op->src[4]->type == GGML_TYPE_F32 && op->src[5]->type == GGML_TYPE_F32 && s_v <= ctx->webgpu_global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup && - ggml_are_same_stride(src0, src1); + ggml_are_same_stride(src0, src1) && + ggml_webgpu_gated_delta_net_n_storage_buffers(op, false) <= + ctx->webgpu_global_ctx->capabilities.limits.maxStorageBuffersPerShaderStage; } break; case GGML_OP_CLAMP: diff --git a/ggml/src/ggml-webgpu/wgsl-shaders/gated_delta_net.wgsl b/ggml/src/ggml-webgpu/wgsl-shaders/gated_delta_net.wgsl index 6f4b5a31c16c..1a5b3208bec0 100644 --- a/ggml/src/ggml-webgpu/wgsl-shaders/gated_delta_net.wgsl +++ b/ggml/src/ggml-webgpu/wgsl-shaders/gated_delta_net.wgsl @@ -23,10 +23,31 @@ var dst: array; @group(0) @binding(7) var dst_fuse: array; #define DST_SNAP dst_fuse -#define PARAMS_BINDING 8 +#define NEXT_BINDING 8 #else #define DST_SNAP dst -#define PARAMS_BINDING 7 +#define NEXT_BINDING 7 +#endif + +#ifdef REPLAY +// pending tokens to run before the new ones (see ggml_gated_delta_net_ext) +@group(0) @binding(NEXT_BINDING) +var pend_k: array; + +@group(0) @binding(NEXT_BINDING + 1) +var pend_v: array; + +@group(0) @binding(NEXT_BINDING + 2) +var pend_gb: array; + +@group(0) @binding(NEXT_BINDING + 3) +var n_rep: array; + +var wg_n_rep: u32; + +#define PARAMS_BINDING (NEXT_BINDING + 4) +#else +#define PARAMS_BINDING NEXT_BINDING #endif struct Params { @@ -53,6 +74,21 @@ struct Params { scale: f32, dst_fuse_nb2: u32, dst_fuse_off: u32, + + n_pend: u32, + keep: u32, + + spk1: u32, + spk2: u32, + spk3: u32, + + spv1: u32, + spv2: u32, + spv3: u32, + + spg1: u32, + spg2: u32, + spg3: u32, }; @group(0) @binding(PARAMS_BINDING) @@ -92,6 +128,66 @@ fn main( state[i] = src_state[state_in_base + col * S_V + i]; } +#ifdef REPLAY + if (col == 0u) { + wg_n_rep = u32(n_rep[seq_id]); + } + let n_r = workgroupUniformLoad(&wg_n_rep); + + for (var t = 0u; t < n_r; t++) { + let k_off = seq_id * params.spk3 + t * params.spk2 + iq1 * params.spk1; + let v_off = seq_id * params.spv3 + t * params.spv2 + head_id * params.spv1; + let g_off = seq_id * params.spg3 + t * params.spg2 + head_id * params.spg1; + + sh_k[col] = pend_k[k_off + col]; + +#ifdef KDA + sh_g[col] = exp(pend_gb[g_off + col]); +#endif + + workgroupBarrier(); + + let v_val = pend_v[v_off + col]; + let beta_val = pend_gb[g_off + params.n_pend * params.spg2]; + + // same update as below, without the attention output + var kv_col = 0.0; + var delta_col = 0.0; + +#ifdef KDA + for (var i = 0u; i < S_V; i++) { + kv_col += (sh_g[i] * state[i]) * sh_k[i]; + } + + delta_col = (v_val - kv_col) * beta_val; + + for (var i = 0u; i < S_V; i++) { + state[i] = sh_g[i] * state[i] + sh_k[i] * delta_col; + } +#else + let g_val = exp(pend_gb[g_off]); + + for (var i = 0u; i < S_V; i++) { + kv_col += state[i] * sh_k[i]; + } + + delta_col = (v_val - g_val * kv_col) * beta_val; + + for (var i = 0u; i < S_V; i++) { + state[i] = g_val * state[i] + sh_k[i] * delta_col; + } +#endif + + workgroupBarrier(); + } + + if (params.keep != 0u) { + for (var i = 0u; i < S_V; i++) { + DST_SNAP[snap_off + state_out_base + col * S_V + i] = state[i]; + } + } +#endif + var attn_off = (seq_id * params.n_tokens * params.h + head_id) * S_V; for (var t = 0u; t < params.n_tokens; t++) { @@ -160,7 +256,14 @@ fn main( workgroupBarrier(); } - if (params.K == 1u) { +#ifdef REPLAY + // replay with keep: the state output is the state after the replay + let write_state = params.K == 1u && params.keep == 0u; +#else + let write_state = params.K == 1u; +#endif + + if (write_state) { for (var i = 0u; i < S_V; i++) { DST_SNAP[snap_off + state_out_base + col * S_V + i] = state[i]; } diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index 947342125327..88ade6e8ae3a 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -6373,7 +6373,7 @@ struct ggml_tensor * ggml_solve_tri( // ggml_gated_delta_net -struct ggml_tensor * ggml_gated_delta_net( +static struct ggml_tensor * ggml_gated_delta_net_impl( struct ggml_context * ctx, struct ggml_tensor * q, struct ggml_tensor * k, @@ -6381,7 +6381,12 @@ struct ggml_tensor * ggml_gated_delta_net( struct ggml_tensor * g, struct ggml_tensor * beta, struct ggml_tensor * state, - int64_t K) { + struct ggml_tensor * pend_k, + struct ggml_tensor * pend_v, + struct ggml_tensor * pend_gb, + struct ggml_tensor * n_rep, + int64_t K, + bool keep) { GGML_ASSERT(ggml_is_contiguous_rows(q)); GGML_ASSERT(ggml_is_contiguous_rows(k)); GGML_ASSERT(ggml_is_contiguous_rows(v)); @@ -6425,9 +6430,61 @@ struct ggml_tensor * ggml_gated_delta_net( result->src[4] = beta; result->src[5] = state; + const bool replay = pend_k != NULL; + GGML_ASSERT((pend_v != NULL) == replay && (pend_gb != NULL) == replay && (n_rep != NULL) == replay); + GGML_ASSERT(replay || !keep); + if (replay) { + const int64_t n_pend = pend_k->ne[2]; + + GGML_ASSERT(K == 1); + GGML_ASSERT(pend_k->type == GGML_TYPE_F32 && pend_v->type == GGML_TYPE_F32 && pend_gb->type == GGML_TYPE_F32); + GGML_ASSERT(n_rep->type == GGML_TYPE_I32); + GGML_ASSERT(pend_k->nb[0] == sizeof(float) && pend_v->nb[0] == sizeof(float) && pend_gb->nb[0] == sizeof(float)); + GGML_ASSERT(pend_k->ne[0] == k->ne[0] && pend_k->ne[1] == k->ne[1] && pend_k->ne[3] == n_seqs); + GGML_ASSERT(pend_v->ne[0] == S_v && pend_v->ne[1] == H && pend_v->ne[2] == n_pend && pend_v->ne[3] == n_seqs); + GGML_ASSERT(pend_gb->ne[0] == g->ne[0] && pend_gb->ne[1] == H && pend_gb->ne[2] == 2*n_pend && pend_gb->ne[3] == n_seqs); + GGML_ASSERT(ggml_is_contiguous(n_rep) && ggml_nelements(n_rep) == n_seqs); + + ggml_set_op_params_i32(result, 1, (int32_t) n_pend); + ggml_set_op_params_i32(result, 2, keep ? 1 : 0); + + result->src[6] = pend_k; + result->src[7] = pend_v; + result->src[8] = pend_gb; + result->src[9] = n_rep; + } + return result; } +struct ggml_tensor * ggml_gated_delta_net_ext( + struct ggml_context * ctx, + struct ggml_tensor * q, + struct ggml_tensor * k, + struct ggml_tensor * v, + struct ggml_tensor * g, + struct ggml_tensor * beta, + struct ggml_tensor * state, + struct ggml_tensor * pend_k, + struct ggml_tensor * pend_v, + struct ggml_tensor * pend_gb, + struct ggml_tensor * n_rep, + bool keep) { + return ggml_gated_delta_net_impl(ctx, q, k, v, g, beta, state, pend_k, pend_v, pend_gb, n_rep, 1, keep); +} + +struct ggml_tensor * ggml_gated_delta_net( + struct ggml_context * ctx, + struct ggml_tensor * q, + struct ggml_tensor * k, + struct ggml_tensor * v, + struct ggml_tensor * g, + struct ggml_tensor * beta, + struct ggml_tensor * state, + int64_t K) { + return ggml_gated_delta_net_impl(ctx, q, k, v, g, beta, state, NULL, NULL, NULL, NULL, K, false); +} + // ggml_lightning_indexer struct ggml_tensor * ggml_lightning_indexer( diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 07a0dbafc17e..4caca65f3674 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -190,6 +190,14 @@ llama_context::llama_context( cparams.n_rs_seq = 0; } + // delta-net rollback keeps one state and the inputs of the last ubatch; the gdn op replays the kept tokens before the new ones + cparams.rs_replay = cparams.n_rs_seq > 0 && ( + model.arch == LLM_ARCH_QWEN35 || model.arch == LLM_ARCH_QWEN35MOE || model.arch == LLM_ARCH_QWEN4EXP || + model.arch == LLM_ARCH_CLOVER_MOE || + // KDA + model.arch == LLM_ARCH_KIMI_K3 || model.arch == LLM_ARCH_KIMI_K31 || model.arch == LLM_ARCH_GLM5_NEXT || + model.arch == LLM_ARCH_BAILINGMOE3); + cparams.n_threads = params.n_threads; cparams.n_threads_batch = params.n_threads_batch; cparams.yarn_ext_factor = params.yarn_ext_factor >= 0.0f ? params.yarn_ext_factor : hparams.yarn_ext_factor; @@ -435,6 +443,7 @@ llama_context::llama_context( LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base); LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale); LLAMA_LOG_INFO("%s: n_rs_seq = %u\n", __func__, cparams.n_rs_seq); + LLAMA_LOG_INFO("%s: rs_replay = %s\n", __func__, cparams.rs_replay ? "true" : "false"); LLAMA_LOG_INFO("%s: n_outputs_max = %u\n", __func__, cparams.n_outputs_max); LLAMA_LOG_INFO("%s: n_outputs_max_per_seq = %u\n", __func__, cparams.n_outputs_max_per_seq); diff --git a/src/llama-cparams.h b/src/llama-cparams.h index c93494fafeb1..c71582a3cd2e 100644 --- a/src/llama-cparams.h +++ b/src/llama-cparams.h @@ -14,6 +14,7 @@ struct llama_cparams { uint32_t n_ubatch; uint32_t n_seq_max; uint32_t n_rs_seq; // number of recurrent-state snapshots per seq for rollback + bool rs_replay; // roll back by replaying kept tokens instead of keeping n_rs_seq snapshots uint32_t n_outputs_max; // max outputs supported by the context uint32_t n_outputs_max_per_seq; int32_t n_threads; // number of threads to use for generation diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 862476a5f60a..5fef4c42168a 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -527,8 +527,6 @@ void llm_graph_input_cls::set_input(const llama_ubatch * ubatch) { } void llm_graph_input_rs::set_input(const llama_ubatch * ubatch) { - GGML_UNUSED(ubatch); - const int64_t n_rs = mctx->get_n_rs(); if (s_copy) { @@ -540,6 +538,34 @@ void llm_graph_input_rs::set_input(const llama_ubatch * ubatch) { data[i] = mctx->s_copy(i); } } + + set_input_rep(mctx, ubatch); +} + +void llm_graph_input_rs::set_input_rep(const llama_memory_recurrent_context * mctx, const llama_ubatch * ubatch) { + if (!has_rep) { + return; + } + + const int64_t n_seqs = ubatch->n_seqs; + + int32_t * reps = (int32_t *) rep_n->data; + int32_t * cols = (int32_t *) rep_cols->data; + + GGML_ASSERT(ggml_backend_buffer_is_host(rep_n->buffer)); + GGML_ASSERT(ggml_backend_buffer_is_host(rep_cols->buffer)); + + for (int64_t s = 0; s < n_seqs; ++s) { + const int64_t n_rep = mctx->get_rs_rep(s); + GGML_ASSERT(n_rep <= n_pend); + + reps[s] = n_rep; + + // the conv history is [window | pending]: the window after the kept tokens + for (int64_t c = 0; c < n_conv; ++c) { + cols[s*n_conv + c] = n_rep + c; + } + } } bool llm_graph_input_rs::can_reuse(const llm_graph_params & params) { @@ -1261,6 +1287,8 @@ void llm_graph_input_mem_hybrid::set_input(const llama_ubatch * ubatch) { data[i] = mctx->get_recr()->s_copy(i); } } + + inp_rs->set_input_rep(mctx->get_recr(), ubatch); } bool llm_graph_input_mem_hybrid::can_reuse(const llm_graph_params & params) { @@ -1307,6 +1335,8 @@ void llm_graph_input_mem_hybrid_k::set_input(const llama_ubatch * ubatch) { data[i] = mctx->get_recr()->s_copy(i); } } + + inp_rs->set_input_rep(mctx->get_recr(), ubatch); } bool llm_graph_input_mem_hybrid_k::can_reuse(const llm_graph_params & params) { @@ -1364,6 +1394,8 @@ void llm_graph_input_mem_hybrid_iswa::set_input(const llama_ubatch * ubatch) { data[i] = mctx->get_recr()->s_copy(i); } } + + inp_rs->set_input_rep(mctx->get_recr(), ubatch); } bool llm_graph_input_mem_hybrid_iswa::can_reuse(const llm_graph_params & params) { @@ -1443,6 +1475,8 @@ void llm_graph_input_mem_hybrid_iswa_rel::set_input(const llama_ubatch * ubatch) data[i] = mctx->get_recr()->s_copy(i); } } + + inp_rs->set_input_rep(mctx->get_recr(), ubatch); } bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & params) { @@ -4136,6 +4170,8 @@ ggml_tensor * llm_graph_context::build_rs( static std::unique_ptr build_rs_inp_impl( ggml_context * ctx0, const llama_ubatch & ubatch, + const llama_hparams & hparams, + const llama_cparams & cparams, const llama_memory_recurrent_context * mctx_cur) { auto inp = std::make_unique(mctx_cur); @@ -4153,13 +4189,38 @@ static std::unique_ptr build_rs_inp_impl( inp->head = mctx_cur->get_head(); inp->rs_z = mctx_cur->get_rs_z(); + inp->has_rep = mctx_cur->get_rs_replay(); + if (inp->has_rep) { + // the widest conv window of the model: the delta-net conv, or the PLE n-gram conv (qwen4exp) + const int64_t n_conv_r = hparams.ssm_d_conv - 1; + const int64_t n_conv_p = hparams.ple_conv_state() > 0 ? (int64_t) (hparams.ple_conv_kernel - 1)*hparams.ple_ngram_size : 0; + + inp->n_conv = std::max(n_conv_r, n_conv_p); + inp->n_pend = cparams.n_rs_seq + 1; + + inp->rep_cols = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, inp->n_conv, n_seqs); + ggml_set_input(inp->rep_cols); + ggml_set_name(inp->rep_cols, "rs_rep_cols"); + + const auto win = [&](int64_t n) { + return n == inp->n_conv ? inp->rep_cols : ggml_view_2d(ctx0, inp->rep_cols, n, n_seqs, inp->rep_cols->nb[1], 0); + }; + + inp->rep_cols_r = win(n_conv_r); + inp->rep_cols_p = n_conv_p > 0 ? win(n_conv_p) : nullptr; + + inp->rep_n = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_seqs); + ggml_set_input(inp->rep_n); + ggml_set_name(inp->rep_n, "rs_rep_n"); + } + return inp; } llm_graph_input_rs * llm_graph_context::build_rs_inp() const { const auto * mctx_cur = static_cast(mctx); - auto inp = build_rs_inp_impl(ctx0, ubatch, mctx_cur); + auto inp = build_rs_inp_impl(ctx0, ubatch, hparams, cparams, mctx_cur); return (llm_graph_input_rs *) res->add_input(std::move(inp)); } @@ -4286,7 +4347,7 @@ ggml_tensor * llm_graph_context::build_rwkv_token_shift_store( llm_graph_input_mem_hybrid * llm_graph_context::build_inp_mem_hybrid() const { const auto * mctx_cur = static_cast(mctx); - auto inp_rs = build_rs_inp_impl (ctx0, ubatch, mctx_cur->get_recr()); + auto inp_rs = build_rs_inp_impl (ctx0, ubatch, hparams, cparams, mctx_cur->get_recr()); auto inp_attn = build_attn_inp_kv_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_attn()); auto inp = std::make_unique(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur); @@ -4297,7 +4358,7 @@ llm_graph_input_mem_hybrid * llm_graph_context::build_inp_mem_hybrid() const { llm_graph_input_mem_hybrid_k * llm_graph_context::build_inp_mem_hybrid_k() const { const auto * mctx_cur = static_cast(mctx); - auto inp_rs = build_rs_inp_impl (ctx0, ubatch, mctx_cur->get_recr()); + auto inp_rs = build_rs_inp_impl (ctx0, ubatch, hparams, cparams, mctx_cur->get_recr()); auto inp_attn = build_attn_inp_k_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_attn()); auto inp = std::make_unique(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur); @@ -4308,7 +4369,7 @@ llm_graph_input_mem_hybrid_k * llm_graph_context::build_inp_mem_hybrid_k() const llm_graph_input_mem_hybrid_iswa * llm_graph_context::build_inp_mem_hybrid_iswa() const { const auto * mctx_cur = static_cast(mctx); - auto inp_rs = build_rs_inp_impl(ctx0, ubatch, mctx_cur->get_recr()); + auto inp_rs = build_rs_inp_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_recr()); // build iswa attention input const auto * attn_ctx = mctx_cur->get_attn(); @@ -4345,7 +4406,7 @@ llm_graph_input_mem_hybrid_iswa_rel * llm_graph_context::build_inp_mem_hybrid_is uint32_t extent_swa) const { const auto * mctx_cur = static_cast(mctx); - auto inp_rs = build_rs_inp_impl(ctx0, ubatch, mctx_cur->get_recr()); + auto inp_rs = build_rs_inp_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_recr()); const auto * attn_ctx = mctx_cur->get_attn(); diff --git a/src/llama-graph.h b/src/llama-graph.h index 116b7132a53e..ff155f14d2f6 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -323,6 +323,19 @@ class llm_graph_input_rs : public llm_graph_input_i { ggml_tensor * s_copy_main; // I32 [n_seqs] ggml_tensor * s_copy_tail; // I32 [n_rs - 1] + // rs_replay: the ubatch first replays the kept pending tokens of the last ubatch (none is a no-op) + bool has_rep = false; + int64_t n_conv = 0; // conv window columns, the widest conv of the model + int64_t n_pend = 0; // pending slots per seq + ggml_tensor * rep_n = nullptr; // I32 [n_seqs], kept pending tokens + ggml_tensor * rep_cols = nullptr; // I32 [n_conv, n_seqs], conv history columns of the window after the kept tokens + + // views of rep_cols for the delta-net conv and the PLE conv windows, computed once per graph and shared across layers + ggml_tensor * rep_cols_r = nullptr; + ggml_tensor * rep_cols_p = nullptr; + + void set_input_rep(const llama_memory_recurrent_context * mctx, const llama_ubatch * ubatch); + const llama_memory_recurrent_context * mctx; // used in view offsets, need to match for valid graph reuse diff --git a/src/llama-memory-hybrid-idx.cpp b/src/llama-memory-hybrid-idx.cpp index 0199c734e341..3866d5980f37 100644 --- a/src/llama-memory-hybrid-idx.cpp +++ b/src/llama-memory-hybrid-idx.cpp @@ -33,6 +33,7 @@ llama_memory_hybrid_idx::llama_memory_hybrid_idx( /* common */ uint32_t n_seq_max, uint32_t n_rs_seq, + bool rs_replay, bool offload, bool unified, /* layer filters */ @@ -44,7 +45,7 @@ llama_memory_hybrid_idx::llama_memory_hybrid_idx( no_alloc, type_k, type_v, v_trans, kv_size, n_swa, swa_type, type_r, type_s, rs_size, - n_seq_max, n_rs_seq, offload, unified, + n_seq_max, n_rs_seq, rs_replay, offload, unified, filter_attn, filter_recr), hparams_idx(model.hparams), mem_idx(filter_idx == nullptr ? nullptr : [&] { diff --git a/src/llama-memory-hybrid-idx.h b/src/llama-memory-hybrid-idx.h index 85a2a91ec28b..ebd082ab5685 100644 --- a/src/llama-memory-hybrid-idx.h +++ b/src/llama-memory-hybrid-idx.h @@ -33,6 +33,7 @@ class llama_memory_hybrid_idx : public llama_memory_hybrid { /* common */ uint32_t n_seq_max, uint32_t n_rs_seq, + bool rs_replay, bool offload, bool unified, /* layer filters */ diff --git a/src/llama-memory-hybrid-iswa.cpp b/src/llama-memory-hybrid-iswa.cpp index 6d843c76ee86..569a09ee2192 100644 --- a/src/llama-memory-hybrid-iswa.cpp +++ b/src/llama-memory-hybrid-iswa.cpp @@ -59,6 +59,7 @@ llama_memory_hybrid_iswa::llama_memory_hybrid_iswa( rs_size, n_seq_max, n_rs_seq, + false, filter_recr == nullptr ? [&](int32_t il) { return hparams.is_recr(il); } : filter_recr diff --git a/src/llama-memory-hybrid.cpp b/src/llama-memory-hybrid.cpp index 7d3b279088e6..a93e256b05a7 100644 --- a/src/llama-memory-hybrid.cpp +++ b/src/llama-memory-hybrid.cpp @@ -25,6 +25,7 @@ llama_memory_hybrid::llama_memory_hybrid( /* common */ uint32_t n_seq_max, uint32_t n_rs_seq, + bool rs_replay, bool offload, bool unified, /* layer filters */ @@ -60,6 +61,7 @@ llama_memory_hybrid::llama_memory_hybrid( rs_size, n_seq_max, n_rs_seq, + rs_replay, filter_recr == nullptr ? [&](int32_t il) { return hparams.is_recr(il); } : filter_recr diff --git a/src/llama-memory-hybrid.h b/src/llama-memory-hybrid.h index 2b4d1269c3c2..b4df21f15155 100644 --- a/src/llama-memory-hybrid.h +++ b/src/llama-memory-hybrid.h @@ -35,6 +35,7 @@ class llama_memory_hybrid : public llama_memory_i { /* common */ uint32_t n_seq_max, uint32_t n_rs_seq, + bool rs_replay, bool offload, bool unified, /* layer filters */ diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp index 0d5739695186..bab6276f65d2 100644 --- a/src/llama-memory-recurrent.cpp +++ b/src/llama-memory-recurrent.cpp @@ -26,6 +26,7 @@ llama_memory_recurrent::llama_memory_recurrent( uint32_t mem_size, uint32_t n_seq_max, uint32_t n_rs_seq, + bool rs_replay, const layer_filter_cb & filter) : hparams(model.hparams), n_seq_max(n_seq_max), ctxs_bufs(no_alloc) { const int32_t n_layer = hparams.n_layer(); @@ -33,7 +34,8 @@ llama_memory_recurrent::llama_memory_recurrent( size = mem_size; used = 0; - this->n_rs_seq = n_rs_seq; + this->n_rs_seq = n_rs_seq; + this->rs_replay = rs_replay && n_rs_seq > 0; rs_idx.assign(n_seq_max, 0); cells.clear(); @@ -53,7 +55,7 @@ llama_memory_recurrent::llama_memory_recurrent( if (it == ctx_map.end()) { ggml_init_params params = { // r and s per layer, plus the separate PLE conv row where the model has one - /*.mem_size =*/ size_t((hparams.ple_conv_state() > 0 ? 3u : 2u)*n_layer*ggml_tensor_overhead()), + /*.mem_size =*/ size_t((hparams.ple_conv_state() > 0 ? 6u : 5u)*n_layer*ggml_tensor_overhead()), /*.mem_buffer =*/ NULL, /*.no_alloc =*/ true, }; @@ -74,6 +76,9 @@ llama_memory_recurrent::llama_memory_recurrent( r_l.resize(n_layer); s_l.resize(n_layer); p_l.resize(n_layer); + spk_l.resize(n_layer); + spv_l.resize(n_layer); + spgb_l.resize(n_layer); for (int i = 0; i < n_layer; i++) { if (filter && !filter(i)) { @@ -99,17 +104,45 @@ llama_memory_recurrent::llama_memory_recurrent( throw std::runtime_error("failed to create ggml context for rs cache"); } - const uint32_t n_rows = mem_size * (1 + n_rs_seq); - ggml_tensor * r = ggml_new_tensor_2d(ctx, type_r, hparams.n_embd_r(), n_rows); + // rs_replay: r is the conv history [channels, d_conv - 1 + n_pend], the window then the pending columns, + // and spk, spv, spgb hold the gdn k, v, gate and beta of up to n_pend pending tokens + const int64_t n_pend = n_rs_seq + 1; + const int64_t n_ch = hparams.n_embd_r() / std::max(1, hparams.ssm_d_conv - 1); + const int64_t n_embd_r = this->rs_replay ? n_ch*(hparams.ssm_d_conv - 1 + n_pend) : hparams.n_embd_r(); + + const uint32_t n_rows = mem_size * (this->rs_replay ? 1 : 1 + n_rs_seq); + ggml_tensor * r = ggml_new_tensor_2d(ctx, type_r, n_embd_r, n_rows); ggml_tensor * s = ggml_new_tensor_2d(ctx, type_s, hparams.n_embd_s(), n_rows); ggml_format_name(r, "cache_r_l%d", i); ggml_format_name(s, "cache_s_l%d", i); r_l[i] = r; s_l[i] = s; + if (this->rs_replay) { + // k [S_k, H_k, n_pend], v [S_v, H_v, n_pend], gb [g0, H_v, 2*n_pend]: separate rows, so that a split by heads + // is one axis of each (-sm tensor). The gate is a scalar per head (g0 = 1), or per key dim for KDA (g0 = S_v) + const bool kda = hparams.n_embd_head_kda != 0; + const int64_t n_k = kda ? (int64_t) hparams.n_embd_head_kda*hparams.n_head() : (int64_t) hparams.ssm_d_state*hparams.ssm_n_group; + const int64_t n_v = kda ? n_k : (int64_t) hparams.ssm_d_inner; + const int64_t n_gb = kda ? n_k : (int64_t) hparams.ssm_dt_rank; + ggml_tensor * spk = ggml_new_tensor_2d(ctx, type_s, n_k*n_pend, mem_size); + ggml_tensor * spv = ggml_new_tensor_2d(ctx, type_s, n_v*n_pend, mem_size); + ggml_tensor * spgb = ggml_new_tensor_2d(ctx, type_s, n_gb*2*n_pend, mem_size); + ggml_format_name(spk, "cache_spk_l%d", i); + ggml_format_name(spv, "cache_spv_l%d", i); + ggml_format_name(spgb, "cache_spgb_l%d", i); + spk_l[i] = spk; + spv_l[i] = spv; + spgb_l[i] = spgb; + } + // the PLE history needs its own row: Meta must mirror it while the delta-net conv state next door stays split if (hparams.ple_conv_state() > 0 && hparams.is_ple(i)) { - ggml_tensor * p = ggml_new_tensor_2d(ctx, type_r, hparams.ple_conv_state(), n_rows); + // rs_replay: [channels, window + n_pend], like r + const int64_t n_win_p = (int64_t) (hparams.ple_conv_kernel - 1)*hparams.ple_ngram_size; + const int64_t n_embd_p = this->rs_replay ? hparams.ple_conv_state()/n_win_p*(n_win_p + n_pend) : hparams.ple_conv_state(); + + ggml_tensor * p = ggml_new_tensor_2d(ctx, type_r, n_embd_p, n_rows); ggml_format_name(p, "cache_ple_r_l%d", i); p_l[i] = p; } @@ -124,7 +157,8 @@ llama_memory_recurrent::llama_memory_recurrent( if (is_empty()) { if (n_rs_seq > 0) { - n_rs_seq = 0; + n_rs_seq = 0; + rs_replay = false; LLAMA_LOG_INFO("%s: disabling rollback snapshots because the memory module is empty\n", __func__); } } @@ -134,8 +168,8 @@ llama_memory_recurrent::llama_memory_recurrent( const size_t memory_size_s = size_s_bytes(); const size_t memory_size_p = size_p_bytes(); - LLAMA_LOG_INFO("%s: size = %7.2f MiB (%6u cells, %3d layers, %2u seqs %2u rs_seq), R (%s): %7.2f MiB, S (%s): %7.2f MiB, P (%s): %7.2f MiB\n", __func__, - (float)(memory_size_r + memory_size_s + memory_size_p) / (1024.0f * 1024.0f), mem_size, n_layer, n_seq_max, n_rs_seq, + LLAMA_LOG_INFO("%s: size = %7.2f MiB (%6u cells, %3d layers, %2u seqs %2u rs_seq%s), R (%s): %7.2f MiB, S (%s): %7.2f MiB, P (%s): %7.2f MiB\n", __func__, + (float)(memory_size_r + memory_size_s + memory_size_p) / (1024.0f * 1024.0f), mem_size, n_layer, n_seq_max, n_rs_seq, rs_replay ? " replay" : "", ggml_type_name(type_r), (float)memory_size_r / (1024.0f * 1024.0f), ggml_type_name(type_s), (float)memory_size_s / (1024.0f * 1024.0f), ggml_type_name(type_r), (float)memory_size_p / (1024.0f * 1024.0f)); @@ -149,6 +183,8 @@ void llama_memory_recurrent::clear(bool data) { cells[i].src = -1; cells[i].tail = -1; cells[i].rs_max = 0; + cells[i].rs_pend = 0; + cells[i].rs_rep = 0; } head = 0; @@ -210,7 +246,13 @@ bool llama_memory_recurrent::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos // pending rollback is single-use const bool pending = rs_idx[seq_id] != 0; if (!pending && rollback >= 1 && rollback <= (llama_pos) cell.rs_max) { - set_rs_idx(seq_id, (uint32_t) rollback); + if (rs_replay) { + // the next ubatch replays only the kept pending tokens + cell.rs_pend -= rollback; + cell.rs_max = 0; + } else { + set_rs_idx(seq_id, (uint32_t) rollback); + } cell.pos = p0 - 1; return true; } @@ -615,6 +657,7 @@ bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) { auto & orig_cell = cells[seq_meta.tail]; empty_cell.pos = orig_cell.pos; empty_cell.src = orig_cell.src; + empty_cell.rs_pend = orig_cell.rs_pend; orig_cell.seq_id.erase(seq_id); empty_cell.seq_id.insert(seq_id); // will be overwritten GGML_ASSERT(!orig_cell.is_empty()); // has at least one remaining seq_id @@ -645,7 +688,13 @@ bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) { std::swap(dst_cell.pos, src_cell.pos); std::swap(dst_cell.src, src_cell.src); + std::swap(dst_cell.rs_max, src_cell.rs_max); + std::swap(dst_cell.rs_pend, src_cell.rs_pend); std::swap(dst_cell.seq_id, src_cell.seq_id); + // the cell moved out only gets its final state copied, its rollback snapshots stay behind + if (!rs_replay) { + src_cell.rs_max = 0; + } // swap tails for (uint32_t j = 0; j < size; ++j) { @@ -674,6 +723,11 @@ bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) { } cell.pos = last_pos; cell.rs_max = n_seq_tokens <= n_rs_seq + 1 ? n_seq_tokens - 1 : 0; + if (rs_replay) { + // replay what the last ubatch left pending, then keep this ubatch pending if it can be rolled back + cell.rs_rep = cell.src >= 0 ? cell.rs_pend : 0; + cell.rs_pend = cell.rs_max > 0 ? n_seq_tokens : 0; + } cell.seq_id.clear(); for (int32_t j = 0; j < ubatch.n_seq_id[i]; ++j) { const llama_seq_id seq_id = ubatch.seq_id[i][j]; @@ -753,6 +807,7 @@ size_t llama_memory_recurrent::size_r_bytes() const { } } + return size_r_bytes; } @@ -765,6 +820,14 @@ size_t llama_memory_recurrent::size_s_bytes() const { } } + for (const auto * sp : { &spk_l, &spv_l, &spgb_l }) { + for (const auto & s : *sp) { + if (s != nullptr) { + size_s_bytes += ggml_nbytes(s); + } + } + } + return size_s_bytes; } @@ -907,6 +970,10 @@ void llama_memory_recurrent::state_write_meta(llama_io_write_i & io, const std:: io.write(&seq_id, sizeof(seq_id)); } } + + if (rs_replay) { + io.write(&cell.rs_pend, sizeof(cell.rs_pend)); + } } } } @@ -929,7 +996,7 @@ void llama_memory_recurrent::state_write_data(llama_io_write_i & io, const std:: io.write(&r_type_i, sizeof(r_type_i)); // Write row size of R tensor - const uint64_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r()); + const uint64_t r_size_row = r_l[il]->nb[1]; io.write(&r_size_row, sizeof(r_size_row)); // Write each logical cell row range. With pending recurrent rollback, @@ -942,7 +1009,7 @@ void llama_memory_recurrent::state_write_data(llama_io_write_i & io, const std:: // the PLE conv history is a second recurrent row, so it has to travel with the first if (p_l[il] != nullptr) { - const uint64_t p_size_row = ggml_row_size(p_l[il]->type, hparams.ple_conv_state()); + const uint64_t p_size_row = p_l[il]->nb[1]; io.write(&p_size_row, sizeof(p_size_row)); for (const auto & range : cell_ranges) { @@ -1004,6 +1071,22 @@ void llama_memory_recurrent::state_write_data(llama_io_write_i & io, const std:: } } } + + // rs_replay pending inputs travel with their cells + if (rs_replay) { + for (uint32_t il = 0; il < n_layer; ++il) { + for (ggml_tensor * t : { spk_l[il], spv_l[il], spgb_l[il] }) { + if (t == nullptr) continue; + + const uint64_t size_row = t->nb[1]; + io.write(&size_row, sizeof(size_row)); + + for (const auto & range : cell_ranges) { + io.write_tensor(t, range.first * size_row, (range.second - range.first) * size_row); + } + } + } + } } bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell_count, llama_seq_id dest_seq_id) { @@ -1024,6 +1107,8 @@ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell llama_ubatch ubatch = balloc.ubatch_reserve(cell_count, 1); + std::vector rs_pend(cell_count, 0); + for (uint32_t i = 0; i < cell_count; ++i) { llama_pos pos; uint32_t n_seq_id; @@ -1036,6 +1121,10 @@ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell return false; } + if (rs_replay) { + io.read(&rs_pend[i], sizeof(rs_pend[i])); + } + ubatch.pos[i] = pos; } ubatch.n_seq_id[0] = 1; @@ -1053,6 +1142,11 @@ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell GGML_ASSERT(cells[head + cell_count - 1].pos == ubatch.pos[cell_count - 1]); GGML_ASSERT(cells[head].has_seq_id(dest_seq_id)); GGML_ASSERT(cells[head + cell_count - 1].has_seq_id(dest_seq_id)); + + for (uint32_t i = 0; i < cell_count; ++i) { + cells[head + i].rs_pend = rs_pend[i]; + cells[head + i].rs_max = 0; + } } else { // whole KV cache restore @@ -1092,6 +1186,10 @@ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell } tail = i; } + + if (rs_replay) { + io.read(&cell.rs_pend, sizeof(cell.rs_pend)); + } } head = 0; @@ -1143,7 +1241,7 @@ bool llama_memory_recurrent::state_read_data(llama_io_read_i & io, uint32_t cell // Read row size of key uint64_t r_size_row_ref; io.read(&r_size_row_ref, sizeof(r_size_row_ref)); - const size_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r()); + const size_t r_size_row = r_l[il]->nb[1]; if (r_size_row != r_size_row_ref) { LLAMA_LOG_ERROR("%s: mismatched r row size (%zu != %zu, layer %d)\n", __func__, r_size_row, (size_t) r_size_row_ref, il); return false; @@ -1157,7 +1255,7 @@ bool llama_memory_recurrent::state_read_data(llama_io_read_i & io, uint32_t cell if (p_l[il] != nullptr) { uint64_t p_size_row_ref; io.read(&p_size_row_ref, sizeof(p_size_row_ref)); - const size_t p_size_row = ggml_row_size(p_l[il]->type, hparams.ple_conv_state()); + const size_t p_size_row = p_l[il]->nb[1]; if (p_size_row != p_size_row_ref) { LLAMA_LOG_ERROR("%s: mismatched ple row size (%zu != %zu, layer %d)\n", __func__, p_size_row, (size_t) p_size_row_ref, il); return false; @@ -1242,6 +1340,25 @@ bool llama_memory_recurrent::state_read_data(llama_io_read_i & io, uint32_t cell } } + if (rs_replay) { + for (uint32_t il = 0; il < n_layer; ++il) { + for (ggml_tensor * t : { spk_l[il], spv_l[il], spgb_l[il] }) { + if (t == nullptr) continue; + + uint64_t size_row_ref; + io.read(&size_row_ref, sizeof(size_row_ref)); + if (size_row_ref != t->nb[1]) { + LLAMA_LOG_ERROR("%s: mismatched pending row size (%zu != %zu, layer %d)\n", __func__, t->nb[1], (size_t) size_row_ref, il); + return false; + } + + if (cell_count) { + io.read_tensor(t, head * t->nb[1], cell_count * t->nb[1]); + } + } + } + } + return true; } @@ -1264,7 +1381,7 @@ void llama_memory_recurrent::state_clear(llama_seq_id seq_id, uint32_t cell_head for (uint32_t il = 0; il < n_layer; ++il) { if (r_l[il] != nullptr) { - const size_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r()); + const size_t r_size_row = r_l[il]->nb[1]; ggml_backend_tensor_memset(r_l[il], 0, cell_head * r_size_row, cell_count * r_size_row); } @@ -1274,7 +1391,7 @@ void llama_memory_recurrent::state_clear(llama_seq_id seq_id, uint32_t cell_head } if (p_l[il] != nullptr) { - const size_t p_size_row = ggml_row_size(p_l[il]->type, hparams.ple_conv_state()); + const size_t p_size_row = p_l[il]->nb[1]; ggml_backend_tensor_memset(p_l[il], 0, cell_head * p_size_row, cell_count * p_size_row); } } @@ -1360,6 +1477,26 @@ ggml_tensor * llama_memory_recurrent_context::get_p_l(int32_t il) const { return mem->p_l[il]; } +ggml_tensor * llama_memory_recurrent_context::get_spk_l(int32_t il) const { + return mem->spk_l[il]; +} + +ggml_tensor * llama_memory_recurrent_context::get_spv_l(int32_t il) const { + return mem->spv_l[il]; +} + +ggml_tensor * llama_memory_recurrent_context::get_spgb_l(int32_t il) const { + return mem->spgb_l[il]; +} + +bool llama_memory_recurrent_context::get_rs_replay() const { + return mem->rs_replay; +} + +uint32_t llama_memory_recurrent_context::get_rs_rep(int i) const { + return is_full ? 0 : mem->cells[i + mem->head].rs_rep; +} + int32_t llama_memory_recurrent_context::s_copy(int i) const { const uint32_t cell_idx = i + mem->head; const int32_t src0 = mem->cells[cell_idx].src0; diff --git a/src/llama-memory-recurrent.h b/src/llama-memory-recurrent.h index 6442fc1c15d7..5efe9c3b49ce 100644 --- a/src/llama-memory-recurrent.h +++ b/src/llama-memory-recurrent.h @@ -25,6 +25,7 @@ class llama_memory_recurrent : public llama_memory_i { uint32_t mem_size, uint32_t n_seq_max, uint32_t n_rs_seq, + bool rs_replay, const layer_filter_cb & filter); ~llama_memory_recurrent() = default; @@ -77,6 +78,9 @@ class llama_memory_recurrent : public llama_memory_i { // per-seq rollback index std::vector rs_idx; + // deferred commit: keep one state plane plus the inputs of the last ubatch, replay the accepted part in the next ubatch + bool rs_replay = false; + void set_rs_idx(llama_seq_id seq_id, uint32_t idx); // computed before each graph build @@ -93,9 +97,13 @@ class llama_memory_recurrent : public llama_memory_i { int32_t tail = -1; // largest rollback whose snapshot the last ubatch guarantees: a ubatch of n <= n_rs_seq + 1 tokens - // writes snapshots 0..n-1, a longer one only guarantees the final state (ggml_gated_delta_net) + // writes snapshots 0..n-1, a longer one only guarantees the final state (ggml_ssm_scan) uint32_t rs_max = 0; + // rs_replay: valid tokens in the pending rows, and the pending tokens the current ubatch replays + uint32_t rs_pend = 0; + uint32_t rs_rep = 0; + std::set seq_id; bool has_seq_id(const llama_seq_id & id) const { @@ -118,6 +126,10 @@ class llama_memory_recurrent : public llama_memory_i { std::vector s_l; // a second conv history that must stay replicated across devices, so it cannot share the r row std::vector p_l; + // rs_replay pending gdn inputs: k, v, and the gates then the betas + std::vector spk_l; + std::vector spv_l; + std::vector spgb_l; private: //const llama_model & model; @@ -184,9 +196,15 @@ class llama_memory_recurrent_context : public llama_memory_context_i { ggml_tensor * get_r_l(int32_t il) const; ggml_tensor * get_s_l(int32_t il) const; ggml_tensor * get_p_l(int32_t il) const; + ggml_tensor * get_spk_l (int32_t il) const; + ggml_tensor * get_spv_l (int32_t il) const; + ggml_tensor * get_spgb_l(int32_t il) const; int32_t s_copy(int i) const; + bool get_rs_replay() const; + uint32_t get_rs_rep(int i) const; // pending tokens replayed by ubatch seq i + private: const llama_memory_status status; diff --git a/src/llama-model.cpp b/src/llama-model.cpp index fa20378aa6d2..b20459646ece 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -468,6 +468,9 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str static const std::regex pattern_r_cache ("cache_r_l\\d*"); static const std::regex pattern_ple_r_cache ("cache_ple_r_l\\d*"); static const std::regex pattern_s_cache ("cache_s_l\\d*"); + static const std::regex pattern_spk_cache ("cache_spk_l\\d*"); + static const std::regex pattern_spv_cache ("cache_spv_l\\d*"); + static const std::regex pattern_spgb_cache ("cache_spgb_l\\d*"); static const std::regex pattern_ssm_conv1d ("blk\\.\\d*\\.ssm_conv1d.weight"); static const std::regex pattern_ssm_out_weight ("blk\\.\\d*\\.ssm_out.weight"); static const std::regex pattern_kda_conv1d ("blk\\.\\d*\\.ssm_conv1d_(q|k|v)\\.weight"); @@ -577,7 +580,9 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_2, "attn_output.weight"); } if (std::regex_match(tensor_name, pattern_ssm_dt) || std::regex_match(tensor_name, pattern_ssm_a) || - std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache)) { + std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache) || + std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache) || + std::regex_match(tensor_name, pattern_spgb_cache)) { return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_0, "attn_output.weight"); } } @@ -642,7 +647,9 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str std::regex_match(tensor_name, pattern_ssm_beta_alpha) || std::regex_match(tensor_name, pattern_ssm_beta_alpha_cat)) { return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_1, "ssm_out.weight"); } - if (std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache)) { + if (std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache) || + std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache) || + std::regex_match(tensor_name, pattern_spgb_cache)) { if (ud->model->arch == LLM_ARCH_LFM2 || ud->model->arch == LLM_ARCH_LFM2MOE || ud->model->arch == LLM_ARCH_LFM3) { // the LFM2 shortconv block runs fully mirrored, so its conv state must be mirrored too return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_MIRRORED, ""); @@ -697,10 +704,22 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str auto get_split_segments = [&](int axis, uint32_t il) -> std::vector> { if (is_glm5_next && std::regex_match(tensor_name, pattern_r_cache)) { // the conv state holds the q, k and v windows one after the other - const int64_t conv_state_size = (hparams.ssm_d_conv - 1) * hparams.n_head(il) * hparams.n_embd_head_kda; - GGML_ASSERT(tensor->ne[axis] == 3*conv_state_size); + const int64_t d_inner = hparams.n_head(il) * hparams.n_embd_head_kda; + const int64_t conv_state_size = (hparams.ssm_d_conv - 1) * d_inner; + if (tensor->ne[axis] != 3*conv_state_size) { + // replay: q, k and v histories [d_inner, window + pending], every column is a block of heads + GGML_ASSERT(tensor->ne[axis] % (3*d_inner) == 0); + return {{d_inner, uint32_t(tensor->ne[axis] / d_inner)}}; + } return {{conv_state_size, 3}}; } + if (is_glm5_next && (std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache) || + std::regex_match(tensor_name, pattern_spgb_cache))) { + // replay pending inputs, per token: k [S_k, H], v [S_v, H], then the gates [S_v, H] and the betas (in element 0) + const int64_t d_inner = hparams.n_head(il) * hparams.n_embd_head_kda; + GGML_ASSERT(tensor->ne[axis] % d_inner == 0); + return {{d_inner, uint32_t(tensor->ne[axis] / d_inner)}}; + } // TODO: deduplicate condition [TAG_SPLIT_QGATE_QWEN] // zonos3 has the qwen35 GDN layout, its attention layers have no fused qkv if (ud->model->arch == LLM_ARCH_QWEN3NEXT || ud->model->arch == LLM_ARCH_QWEN35 || ud->model->arch == LLM_ARCH_QWEN35MOE || ud->model->arch == LLM_ARCH_CLEF || ud->model->arch == LLM_ARCH_CLOVER_MOE || @@ -731,6 +750,8 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str return {{key_dim, 2}, {value_dim, 1}}; } if (std::regex_match(tensor_name, pattern_r_cache)) { + // the replay layouts need the Qwen 3.5 pattern, llama_context keeps Qwen 3 Next on snapshots + GGML_ASSERT(tensor->ne[axis] == (2*key_dim + value_dim) * (hparams.ssm_d_conv - 1)); return {{key_dim * (hparams.ssm_d_conv - 1), 2}, {value_dim * (hparams.ssm_d_conv - 1), 1}}; } } else { @@ -755,11 +776,26 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str return {{n_k_heads, head_ratio}}; } if (std::regex_match(tensor_name, pattern_r_cache)) { + const int64_t n_conv_ch = 2*key_dim + value_dim; + if (tensor->ne[axis] != n_conv_ch * (hparams.ssm_d_conv - 1)) { + // replay: [channels, window + pending] per cell, every column is a q, k, v block + GGML_ASSERT(tensor->ne[axis] % n_conv_ch == 0); + return {{key_dim, uint32_t((2 + head_ratio) * (tensor->ne[axis] / n_conv_ch))}}; + } return {{key_dim * (hparams.ssm_d_conv - 1), 2 + head_ratio}}; } if (std::regex_match(tensor_name, pattern_s_cache)) { return {{n_k_heads * head_v_dim * head_v_dim, head_ratio}}; } + // replay pending inputs, per token: k [S_k, H_k], v [S_v, H_v], then the gates and betas [H_v] + if (std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache)) { + GGML_ASSERT(tensor->ne[axis] % key_dim == 0); + return {{key_dim, uint32_t(tensor->ne[axis] / key_dim)}}; + } + if (std::regex_match(tensor_name, pattern_spgb_cache)) { + GGML_ASSERT(tensor->ne[axis] % n_k_heads == 0); + return {{n_k_heads, uint32_t(tensor->ne[axis] / n_k_heads)}}; + } } // the FFN is the same for Qwen 3 Next and Qwen 3.5: @@ -815,7 +851,14 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str return {granularity_qkv / head_dim}; } if (std::regex_match(tensor_name, pattern_r_cache)) { - return std::vector(segments.size(), granularity_qkv * (hparams.ssm_d_conv - 1)); + // replay: channels first, each segment is a single conv column + const int64_t conv_state_size = (hparams.ssm_d_conv - 1) * hparams.n_head(il) * head_dim; + const bool replay = tensor->ne[0] != 3*conv_state_size; + return std::vector(segments.size(), granularity_qkv * (replay ? 1 : hparams.ssm_d_conv - 1)); + } + if (std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache) || + std::regex_match(tensor_name, pattern_spgb_cache)) { + return std::vector(segments.size(), granularity_qkv); } if (std::regex_match(tensor_name, pattern_s_cache)) { return {granularity_qkv * head_dim}; @@ -852,11 +895,20 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str return std::vector(segments.size(), 2 * (granularity_qkv / head_dim)); } if (std::regex_match(tensor_name, pattern_r_cache)) { - return std::vector(segments.size(), granularity_qkv * (hparams.ssm_d_conv - 1)); + // replay: [channels, window + pending], each segment is a single conv column + const int64_t n_conv_ch = 2*hparams.ssm_n_group*hparams.ssm_d_state + hparams.ssm_d_inner; + const bool replay = tensor->ne[0] != n_conv_ch * (hparams.ssm_d_conv - 1); + return std::vector(segments.size(), granularity_qkv * (replay ? 1 : hparams.ssm_d_conv - 1)); } if (std::regex_match(tensor_name, pattern_s_cache)) { return std::vector(segments.size(), granularity_qkv * head_dim); } + if (std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache)) { + return std::vector(segments.size(), granularity_qkv); + } + if (std::regex_match(tensor_name, pattern_spgb_cache)) { + return std::vector(segments.size(), granularity_qkv / head_dim); + } } else { // regular attention const uint32_t n_gqa = hparams.n_gqa(il); @@ -3220,6 +3272,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, /* recurrent_rs_size */ std::max((uint32_t) 1, cparams.n_seq_max), /* n_seq_max */ cparams.n_seq_max, /* n_rs_seq */ cparams.n_rs_seq, + /* rs_replay */ cparams.rs_replay, /* offload */ cparams.offload_kqv, /* unified */ cparams.kv_unified, /* filter_attn */ std::move(filter_attn), @@ -3433,6 +3486,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, std::max((uint32_t) 1, cparams.n_seq_max), cparams.n_seq_max, cparams.n_rs_seq, + false, nullptr); } else if (llm_arch_is_hybrid(arch) && !mtp_on_hybrid_qwen && !mtp_on_hybrid_nemotron) { // The main difference between hybrid architectures is the @@ -3527,6 +3581,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, /* recurrent_kv_size */ std::max((uint32_t) 1, cparams.n_seq_max), /* n_seq_max */ cparams.n_seq_max, /* n_rs_seq */ cparams.n_rs_seq, + /* rs_replay */ cparams.rs_replay, /* offload */ cparams.offload_kqv, /* unified */ cparams.kv_unified, /* filter_attn */ std::move(filter_attn), @@ -3547,6 +3602,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, /* recurrent_kv_size */ std::max((uint32_t) 1, cparams.n_seq_max), /* n_seq_max */ cparams.n_seq_max, /* n_rs_seq */ cparams.n_rs_seq, + /* rs_replay */ cparams.rs_replay, /* offload */ cparams.offload_kqv, /* unified */ cparams.kv_unified, /* filter_attn */ std::move(filter_attn), diff --git a/src/models/bailingmoe3.cpp b/src/models/bailingmoe3.cpp index ad1f0ee27b1f..20d940ca32e4 100644 --- a/src/models/bailingmoe3.cpp +++ b/src/models/bailingmoe3.cpp @@ -163,22 +163,29 @@ std::unique_ptr llama_model_bailingmoe3::build_arch_graph(con ggml_tensor * llama_model_bailingmoe3::graph::build_causal_conv1d( llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all, int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w, - int64_t d_conv, int64_t head_dim, int64_t n_head, int64_t n_seq_tokens, int64_t n_seqs) { + int64_t d_conv, int64_t head_dim, int64_t n_head, int64_t n_seq_tokens, int64_t n_seqs, int il) { const int64_t d_inner = head_dim * n_head; const int64_t conv_state_size = (d_conv - 1) * d_inner; const int64_t total_state_size = 3 * conv_state_size; - ggml_tensor * conv_state = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs, - (d_conv - 1) * ggml_element_size(conv_state_all), - total_state_size * ggml_element_size(conv_state_all), - qkv * conv_state_size * ggml_element_size(conv_state_all)); - ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x); x_proj = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs); - ggml_tensor * conv_x = ggml_concat(ctx0, conv_state, ggml_transpose(ctx0, x_proj), 0); - build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1, - ggml_row_size(conv_states_all->type, qkv * conv_state_size)); + ggml_tensor * conv_x = nullptr; + if (cparams.rs_replay) { + // the row holds the q, k and v conv histories one after the other + conv_x = build_conv_state_replay(inp_rs, conv_states_all, x_proj, d_conv - 1, d_inner, il, conv_state_all, qkv); + } else { + ggml_tensor * conv_state = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs, + (d_conv - 1) * ggml_element_size(conv_state_all), + total_state_size * ggml_element_size(conv_state_all), + qkv * conv_state_size * ggml_element_size(conv_state_all)); + + conv_x = ggml_concat(ctx0, conv_state, ggml_transpose(ctx0, x_proj), 0); + + build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1, + ggml_row_size(conv_states_all->type, qkv * conv_state_size)); + } ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner); ggml_tensor * out = ggml_ssm_conv(ctx0, conv_x, conv_weight); @@ -227,17 +234,17 @@ llama_model_bailingmoe3::graph::graph(const llm_graph_params & params) : if (hparams.is_recr(il)) { const auto * mctx_cur = inp_rs->mctx; ggml_tensor * conv_states_all = mctx_cur->get_r_l(il); - ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, hparams.n_embd_r(), n_seqs); + ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs); ggml_tensor * q = build_causal_conv1d( inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, - d_conv, head_dim, n_head, n_seq_tokens, n_seqs); + d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il); ggml_tensor * k = build_causal_conv1d( inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, - d_conv, head_dim, n_head, n_seq_tokens, n_seqs); + d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il); ggml_tensor * v = build_causal_conv1d( inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, - d_conv, head_dim, n_head, n_seq_tokens, n_seqs); + d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il); ggml_tensor * gate = ggml_mul_mat(ctx0, layer.ssm_f_a, cur); gate = ggml_add(ctx0, gate, layer.ssm_dt_b); diff --git a/src/models/delta-net-base.cpp b/src/models/delta-net-base.cpp index 45b2de4bbc9d..f05bd8c0a2ba 100644 --- a/src/models/delta-net-base.cpp +++ b/src/models/delta-net-base.cpp @@ -32,8 +32,8 @@ std::pair llm_build_delta_net_base::build_delta_ne GGML_ASSERT(b->ne[0] == 1 && b->ne[1] == H_v && b->ne[2] == n_tokens && b->ne[3] == n_seqs); GGML_ASSERT(s->ne[0] == S_v && s->ne[1] == S_v && s->ne[2] == H_v && s->ne[3] == n_seqs); - // K=1: output carries the final state only. state s is 4D [S_v, S_v, H_v, n_seqs]. - ggml_tensor * result = ggml_gated_delta_net(ctx0, q, k, v, g, b, s, /*K=*/1); + // output carries the final state. state s is 4D [S_v, S_v, H_v, n_seqs]. + ggml_tensor * result = ggml_gated_delta_net_ext(ctx0, q, k, v, g, b, s, nullptr, nullptr, nullptr, nullptr, false); ggml_tensor * output = ggml_view_4d(ctx0, result, S_v, H_v, n_tokens, n_seqs, ggml_row_size(result->type, S_v), @@ -59,6 +59,10 @@ ggml_tensor * llm_build_delta_net_base::build_conv_state( int il) { const int64_t n_seqs = ubatch.n_seqs; + if (cparams.rs_replay) { + return build_conv_state_replay(inp, conv_states_all, qkv_mixed, conv_kernel_size - 1, conv_channels, il); + } + ggml_tensor * conv_states = build_rs(inp, conv_states_all, hparams.n_embd_r(), n_seqs); cb(conv_states, "conv_states", il); @@ -76,7 +80,80 @@ ggml_tensor * llm_build_delta_net_base::build_conv_state( return conv_input; } -ggml_tensor * llm_build_delta_net_base::build_recurrent_attn( +// [TAG_RECURRENT_REPLAY] +// rs_replay keeps one committed state per seq plus the inputs of the last ubatch when it is short enough to be rolled +// back (2 <= n_seq_tokens <= n_rs_seq + 1). The next ubatch first replays the pending tokens that seq_rm kept, commits +// the result and then runs its own tokens. Must match the rule in llama_memory_recurrent::find_slot. +// Every ubatch builds the same nodes, with or without pending tokens, so the allocation planned at reserve time +// stays valid and the scheduler never re-plans. +static bool rs_replay_keep(const llama_cparams & cparams, int64_t n_seq_tokens) { + return n_seq_tokens >= 2 && n_seq_tokens <= (int64_t) cparams.n_rs_seq + 1; +} + +ggml_tensor * llm_build_delta_net_base::build_conv_state_replay( + llm_graph_input_rs * inp, + ggml_tensor * conv_states_all, + ggml_tensor * x, + int64_t n_conv, + int64_t channels, + int il, + ggml_tensor * hist_rows, + int64_t blk) { + const auto * mctx_cur = inp->mctx; + + const auto kv_head = mctx_cur->get_head(); + + const int64_t n_hist = n_conv + cparams.n_rs_seq + 1; + const int64_t n_seqs = ubatch.n_seqs; + const int64_t n_seq_tokens = ubatch.n_seq_tokens; + + GGML_ASSERT(conv_states_all->ne[0] % (channels*n_hist) == 0); + const int64_t n_blk = conv_states_all->ne[0] / (channels*n_hist); + + GGML_ASSERT(blk >= 0 && blk < n_blk); + GGML_ASSERT(x->ne[0] == channels && x->ne[1] == n_seq_tokens && x->ne[2] == n_seqs); + GGML_ASSERT(n_conv <= inp->n_conv); + + if (hist_rows == nullptr) { + hist_rows = build_rs(inp, conv_states_all, conv_states_all->ne[0], n_seqs); + } + GGML_ASSERT(hist_rows->ne[0] == conv_states_all->ne[0] && hist_rows->ne[1] == n_seqs); + + // channels first: [window | pending], the histories of a row one after the other + ggml_tensor * hist = nullptr; + if (n_blk == 1) { + hist = ggml_reshape_3d(ctx0, hist_rows, channels, n_hist, n_seqs); + } else { + hist = ggml_reshape_4d(ctx0, hist_rows, channels, n_hist, n_blk, n_seqs); + hist = ggml_view_3d(ctx0, hist, channels, n_hist, n_seqs, hist->nb[1], hist->nb[3], blk*hist->nb[2]); + } + cb(hist, "conv_hist", il); + + ggml_tensor * win_cols = n_conv == inp->rep_cols_r->ne[0] ? inp->rep_cols_r : inp->rep_cols_p; + GGML_ASSERT(win_cols && win_cols->ne[0] == n_conv); + + // [channels, n_conv + n_seq_tokens]: the window after the kept pending tokens, then the new tokens + // (built channels first, a transposed concat is much slower than a concat and a transpose) + ggml_tensor * cols = ggml_concat(ctx0, ggml_get_rows(ctx0, hist, win_cols), x, 1); + + ggml_tensor * conv_input = ggml_cont(ctx0, ggml_transpose(ctx0, cols)); + cb(conv_input, "conv_input", il); + + // keep: the new tokens stay pending behind the committed window, else commit the last n_conv columns + const int64_t n_dst = rs_replay_keep(cparams, n_seq_tokens) ? n_conv + n_seq_tokens : n_conv; + + ggml_tensor * tail = ggml_view_3d(ctx0, cols, channels, n_dst, n_seqs, cols->nb[1], cols->nb[2], + (n_conv + n_seq_tokens - n_dst)*cols->nb[1]); + // the rows as [channels, n_blk*n_hist, cells], so that the view of the ubatch cells keeps their strides (-sm tensor) + ggml_tensor * hist_all = ggml_reshape_3d(ctx0, conv_states_all, channels, n_blk*n_hist, conv_states_all->ne[1]); + ggml_tensor * hist_dst = ggml_view_3d(ctx0, hist_all, channels, n_dst, n_seqs, hist_all->nb[1], hist_all->nb[2], + kv_head*hist_all->nb[2] + blk*n_hist*hist_all->nb[1]); + ggml_build_forward_expand(gf, ggml_cpy(ctx0, tail, hist_dst)); + + return conv_input; +} + +ggml_tensor * llm_build_delta_net_base::build_recurrent_attn_replay( llm_graph_input_rs * inp, ggml_tensor * ssm_states_all, ggml_tensor * q, @@ -86,67 +163,112 @@ ggml_tensor * llm_build_delta_net_base::build_recurrent_attn( ggml_tensor * b, ggml_tensor * s, int il) { - const auto * mctx_cur = inp->mctx; - const auto kv_head = mctx_cur->get_head(); - const uint32_t mem_size = mctx_cur->get_size(); - - const int64_t S_v = s->ne[0]; - const int64_t H_v = s->ne[2]; - const int64_t n_seqs = s->ne[3]; - const int64_t n_seq_tokens = q->ne[2]; - - const bool keep = cparams.n_rs_seq > 0; - - if (!keep) { - auto attn_out = build_delta_net(q, k, v, g, b, s); - ggml_tensor * output = attn_out.first; - ggml_tensor * new_state = attn_out.second; - cb(output, "attn_output", il); - cb(new_state, "new_state", il); - - ggml_build_forward_expand(gf, - ggml_cpy(ctx0, new_state, - ggml_view_2d(ctx0, ssm_states_all, hparams.n_embd_s(), n_seqs, ssm_states_all->nb[1], - kv_head * hparams.n_embd_s() * ggml_element_size(ssm_states_all)))); - - return output; - } + const auto * mctx_cur = inp->mctx; + + const auto kv_head = mctx_cur->get_head(); - const int64_t D = S_v * S_v * H_v; - const int64_t K = cparams.n_rs_seq + 1; + const int64_t n_pend = cparams.n_rs_seq + 1; + const int64_t n_seqs = ubatch.n_seqs; + const int64_t n_seq_tokens = ubatch.n_seq_tokens; + + const int64_t S_k = k->ne[0]; + const int64_t H_k = k->ne[1]; + const int64_t S_v = v->ne[0]; + const int64_t H_v = v->ne[1]; + const int64_t g0 = g->ne[0]; - // state s is 4D [S_v, S_v, H_v, n_seqs]; K snapshot slots are written into the output. - ggml_tensor * gdn_out = ggml_gated_delta_net(ctx0, q, k, v, g, b, s, K); - const int64_t attn_score_elems = S_v * H_v * n_seq_tokens * n_seqs; - const int64_t state_size_per_snap = S_v * S_v * H_v * n_seqs; + const size_t row_size = ggml_row_size(ssm_states_all->type, hparams.n_embd_s()); - ggml_tensor * output = ggml_view_4d(ctx0, gdn_out, - S_v, H_v, n_seq_tokens, n_seqs, - ggml_row_size(gdn_out->type, S_v), - ggml_row_size(gdn_out->type, S_v * H_v), - ggml_row_size(gdn_out->type, S_v * H_v * n_seq_tokens), - 0); + // the pending inputs of the cells: k [S_k, H_k, n_pend], v [S_v, H_v, n_pend], gb [g0, H_v, 2*n_pend] (the gates, + // then the betas). The views of the ubatch cells keep the strides of these 4D views, so that -sm tensor can split + // them by heads + ggml_tensor * spk = mctx_cur->get_spk_l(il); + ggml_tensor * spv = mctx_cur->get_spv_l(il); + ggml_tensor * spgb = mctx_cur->get_spgb_l(il); + + ggml_tensor * ck = ggml_reshape_4d(ctx0, spk, S_k, H_k, n_pend, spk->ne[1]); + ggml_tensor * cv = ggml_reshape_4d(ctx0, spv, S_v, H_v, n_pend, spv->ne[1]); + ggml_tensor * cgb = ggml_reshape_4d(ctx0, spgb, g0, H_v, 2*n_pend, spgb->ne[1]); + + const auto gather = [&](ggml_tensor * rows, ggml_tensor * c) { + return ggml_reshape_4d(ctx0, build_rs(inp, rows, rows->ne[0], n_seqs), c->ne[0], c->ne[1], c->ne[2], n_seqs); + }; + + ggml_tensor * pk = gather(spk, ck); + ggml_tensor * pv = gather(spv, cv); + ggml_tensor * pgb = gather(spgb, cgb); + + const bool keep = rs_replay_keep(cparams, n_seq_tokens); + + ggml_tensor * state_dst = ggml_view_2d(ctx0, ssm_states_all, hparams.n_embd_s(), n_seqs, ssm_states_all->nb[1], kv_head*row_size); + + // store the inputs of the new tokens as pending; only used when keep, a longer ubatch stores its first n_pend tokens + const auto store_inputs = [&]() { + const int64_t n_st = std::min(n_seq_tokens, n_pend); + + const auto store = [&](ggml_tensor * x, ggml_tensor * c, int64_t t0) { + ggml_tensor * x_st = ggml_view_4d(ctx0, x, x->ne[0], x->ne[1], n_st, n_seqs, x->nb[1], x->nb[2], x->nb[3], 0); + ggml_tensor * dst = ggml_view_4d(ctx0, c, x->ne[0], x->ne[1], n_st, n_seqs, c->nb[1], c->nb[2], c->nb[3], + kv_head*c->nb[3] + t0*c->nb[2]); + ggml_build_forward_expand(gf, ggml_cpy(ctx0, x_st, dst)); + }; + + store(k, ck, 0); + store(v, cv, 0); + store(g, cgb, 0); + store(b, cgb, n_pend); + }; + + // the gdn op replays the kept pending tokens, then runs the new tokens + ggml_tensor * result = ggml_gated_delta_net_ext(ctx0, q, k, v, g, b, s, pk, pv, pgb, inp->rep_n, keep); + + ggml_tensor * output = ggml_view_4d(ctx0, result, S_v, H_v, n_seq_tokens, n_seqs, + ggml_row_size(result->type, S_v), + ggml_row_size(result->type, S_v*H_v), + ggml_row_size(result->type, S_v*H_v*n_seq_tokens), 0); cb(output, "attn_output", il); - const size_t row_size = hparams.n_embd_s() * ggml_element_size(ssm_states_all); + // keep: the state after the replay, else the final state + ggml_tensor * new_state = ggml_view_2d(ctx0, result, hparams.n_embd_s(), n_seqs, + ggml_row_size(result->type, hparams.n_embd_s()), + ggml_row_size(result->type, S_v*H_v*n_seq_tokens*n_seqs)); + ggml_build_forward_expand(gf, ggml_cpy(ctx0, new_state, state_dst)); + + store_inputs(); + + return output; +} + +ggml_tensor * llm_build_delta_net_base::build_recurrent_attn( + llm_graph_input_rs * inp, + ggml_tensor * ssm_states_all, + ggml_tensor * q, + ggml_tensor * k, + ggml_tensor * v, + ggml_tensor * g, + ggml_tensor * b, + ggml_tensor * s, + int il) { + if (cparams.rs_replay) { + return build_recurrent_attn_replay(inp, ssm_states_all, q, k, v, g, b, s, il); + } - // op writes the last min(n_seq_tokens, K) snapshots; trailing slots are left unwritten - const int64_t n_written = std::min(n_seq_tokens, K); + // a rollback replays the kept tokens, the gdn op does not write state snapshots + GGML_ASSERT(cparams.n_rs_seq == 0); - // write the produced snapshots into the recurrent cache (snapshot slot i -> rollback group i) - ggml_tensor * src = ggml_view_3d(ctx0, gdn_out, - D, n_seqs, n_written, - ggml_row_size(gdn_out->type, D), - ggml_row_size(gdn_out->type, state_size_per_snap), - ggml_row_size(gdn_out->type, attn_score_elems)); + const auto kv_head = inp->mctx->get_head(); + const int64_t n_seqs = s->ne[3]; - ggml_tensor * dst = ggml_view_3d(ctx0, ssm_states_all, - D, n_seqs, n_written, - ssm_states_all->nb[1], - (size_t) mem_size * row_size, - (size_t) kv_head * row_size); + auto attn_out = build_delta_net(q, k, v, g, b, s); + ggml_tensor * output = attn_out.first; + ggml_tensor * new_state = attn_out.second; + cb(output, "attn_output", il); + cb(new_state, "new_state", il); - ggml_build_forward_expand(gf, ggml_cpy(ctx0, src, dst)); + ggml_build_forward_expand(gf, + ggml_cpy(ctx0, new_state, + ggml_view_2d(ctx0, ssm_states_all, hparams.n_embd_s(), n_seqs, ssm_states_all->nb[1], + kv_head * hparams.n_embd_s() * ggml_element_size(ssm_states_all)))); return output; } diff --git a/src/models/glm5-next.cpp b/src/models/glm5-next.cpp index 51a26df3deaf..5d3944af28a7 100644 --- a/src/models/glm5-next.cpp +++ b/src/models/glm5-next.cpp @@ -194,22 +194,29 @@ std::unique_ptr llama_model_glm5_next::build_arch_graph(const ggml_tensor * llama_model_glm5_next::graph::build_kda_conv1d( llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all, int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w, - int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs) { + int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il) { const int64_t d_inner = head_dim * n_head_kda; const int64_t conv_state_size = (d_conv - 1) * d_inner; const int64_t n_embd_r_total = 3 * conv_state_size; - ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs, - (d_conv - 1) * ggml_element_size(conv_state_all), - n_embd_r_total * ggml_element_size(conv_state_all), - qkv * conv_state_size * ggml_element_size(conv_state_all)); - ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x); ggml_tensor * x_3d = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs); - ggml_tensor * conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0); - build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1, - ggml_row_size(conv_states_all->type, qkv * conv_state_size)); + ggml_tensor * conv_x = nullptr; + if (cparams.rs_replay) { + // the row holds the q, k and v conv histories one after the other + conv_x = build_conv_state_replay(inp_rs, conv_states_all, x_3d, d_conv - 1, d_inner, il, conv_state_all, qkv); + } else { + ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs, + (d_conv - 1) * ggml_element_size(conv_state_all), + n_embd_r_total * ggml_element_size(conv_state_all), + qkv * conv_state_size * ggml_element_size(conv_state_all)); + + conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0); + + build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1, + ggml_row_size(conv_states_all->type, qkv * conv_state_size)); + } ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner); ggml_tensor * Xcur = ggml_ssm_conv(ctx0, conv_x, conv_weight); @@ -796,11 +803,11 @@ ggml_tensor * llama_model_glm5_next::graph::build_kda_layer( const auto * mctx_cur = inp_rs->mctx; ggml_tensor * conv_states_all = mctx_cur->get_r_l(il); - ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, hparams.n_embd_r(), n_seqs); + ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs); - ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs); - ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs); - ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs); + ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); + ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); + ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); cb(Qcur, "kda_q_conv", il); cb(Kcur, "kda_k_conv", il); cb(Vcur, "kda_v_conv", il); diff --git a/src/models/kimi-k3.cpp b/src/models/kimi-k3.cpp index 2e91c5243a64..e0ef7b6cd40a 100644 --- a/src/models/kimi-k3.cpp +++ b/src/models/kimi-k3.cpp @@ -355,22 +355,29 @@ llama_model_kimi_k3::graph::graph(const llm_graph_params & params) : ggml_tensor * llama_model_kimi_k3::graph::build_kda_conv1d( llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all, int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w, - int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs) { + int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il) { const int64_t d_inner = head_dim * n_head_kda; const int64_t conv_state_size = (d_conv - 1) * d_inner; const int64_t n_embd_r_total = 3 * conv_state_size; - ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs, - (d_conv - 1) * ggml_element_size(conv_state_all), - n_embd_r_total * ggml_element_size(conv_state_all), - qkv * conv_state_size * ggml_element_size(conv_state_all)); - ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x); ggml_tensor * x_3d = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs); - ggml_tensor * conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0); - build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1, - ggml_row_size(conv_states_all->type, qkv * conv_state_size)); + ggml_tensor * conv_x = nullptr; + if (cparams.rs_replay) { + // the row holds the q, k and v conv histories one after the other + conv_x = build_conv_state_replay(inp_rs, conv_states_all, x_3d, d_conv - 1, d_inner, il, conv_state_all, qkv); + } else { + ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs, + (d_conv - 1) * ggml_element_size(conv_state_all), + n_embd_r_total * ggml_element_size(conv_state_all), + qkv * conv_state_size * ggml_element_size(conv_state_all)); + + conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0); + + build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1, + ggml_row_size(conv_states_all->type, qkv * conv_state_size)); + } ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner); ggml_tensor * Xcur = ggml_ssm_conv(ctx0, conv_x, conv_weight); @@ -388,11 +395,11 @@ ggml_tensor * llama_model_kimi_k3::graph::build_kda_layer( const auto * mctx_cur = inp_rs->mctx; ggml_tensor * conv_states_all = mctx_cur->get_r_l(il); - ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, hparams.n_embd_r(), n_seqs); + ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs); - ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs); - ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs); - ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs); + ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); + ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); + ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); cb(Qcur, "kda_q_conv", il); cb(Kcur, "kda_k_conv", il); cb(Vcur, "kda_v_conv", il); diff --git a/src/models/kimi-k31.cpp b/src/models/kimi-k31.cpp index 3f99eca4a183..049f667dea40 100644 --- a/src/models/kimi-k31.cpp +++ b/src/models/kimi-k31.cpp @@ -391,22 +391,29 @@ llama_model_kimi_k31::graph::graph(const llm_graph_params & params) : ggml_tensor * llama_model_kimi_k31::graph::build_kda_conv1d( llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all, int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w, - int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs) { + int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il) { const int64_t d_inner = head_dim * n_head_kda; const int64_t conv_state_size = (d_conv - 1) * d_inner; const int64_t n_embd_r_total = 3 * conv_state_size; - ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs, - (d_conv - 1) * ggml_element_size(conv_state_all), - n_embd_r_total * ggml_element_size(conv_state_all), - qkv * conv_state_size * ggml_element_size(conv_state_all)); - ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x); ggml_tensor * x_3d = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs); - ggml_tensor * conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0); - build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1, - ggml_row_size(conv_states_all->type, qkv * conv_state_size)); + ggml_tensor * conv_x = nullptr; + if (cparams.rs_replay) { + // the row holds the q, k and v conv histories one after the other + conv_x = build_conv_state_replay(inp_rs, conv_states_all, x_3d, d_conv - 1, d_inner, il, conv_state_all, qkv); + } else { + ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs, + (d_conv - 1) * ggml_element_size(conv_state_all), + n_embd_r_total * ggml_element_size(conv_state_all), + qkv * conv_state_size * ggml_element_size(conv_state_all)); + + conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0); + + build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1, + ggml_row_size(conv_states_all->type, qkv * conv_state_size)); + } ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner); ggml_tensor * Xcur = ggml_ssm_conv(ctx0, conv_x, conv_weight); @@ -424,11 +431,11 @@ ggml_tensor * llama_model_kimi_k31::graph::build_kda_layer( const auto * mctx_cur = inp_rs->mctx; ggml_tensor * conv_states_all = mctx_cur->get_r_l(il); - ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, hparams.n_embd_r(), n_seqs); + ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs); - ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs); - ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs); - ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs); + ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); + ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); + ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); cb(Qcur, "kda_q_conv", il); cb(Kcur, "kda_k_conv", il); cb(Vcur, "kda_v_conv", il); diff --git a/src/models/models.h b/src/models/models.h index b12642fb9a70..3b4f04c19454 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -67,6 +67,31 @@ struct llm_build_delta_net_base : public llm_graph_context { ggml_tensor * b, ggml_tensor * s, int il); + + // rs_replay variants: replay the kept pending tokens, then keep or commit the new ones [TAG_RECURRENT_REPLAY] + // x: [channels, n_seq_tokens, n_seqs] new conv inputs; returns [n_conv + n_seq_tokens, channels, n_seqs] + // a row of conv_states_all can hold several histories [channels, n_conv + n_pend] one after the other (KDA: q, k, v): + // blk picks one, and hist_rows are the rows of the ubatch cells (build_rs) shared by the blocks, nullptr gathers them + ggml_tensor * build_conv_state_replay( + llm_graph_input_rs * inp, + ggml_tensor * conv_states_all, + ggml_tensor * x, + int64_t n_conv, + int64_t channels, + int il, + ggml_tensor * hist_rows = nullptr, + int64_t blk = 0); + + ggml_tensor * build_recurrent_attn_replay( + llm_graph_input_rs * inp, + ggml_tensor * ssm_states_all, + ggml_tensor * q, + ggml_tensor * k, + ggml_tensor * v, + ggml_tensor * g, + ggml_tensor * b, + ggml_tensor * s, + int il); }; struct llm_build_lfm_base : public llm_graph_context { @@ -2209,7 +2234,7 @@ struct llama_model_bailingmoe3 : public llama_model_base { // causal conv1d over one of Q/K/V, qkv selects which third of the conv state row is used ggml_tensor * build_causal_conv1d(llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all, int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w, - int64_t d_conv, int64_t head_dim, int64_t n_head, int64_t n_seq_tokens, int64_t n_seqs); + int64_t d_conv, int64_t head_dim, int64_t n_head, int64_t n_seq_tokens, int64_t n_seqs, int il); }; struct graph_mtp : public llm_graph_context { @@ -3170,7 +3195,7 @@ struct llama_model_kimi_k3 : public llama_model_base { // causal conv1d over one of Q/K/V, qkv selects which third of the conv state row is used ggml_tensor * build_kda_conv1d(llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all, int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w, - int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs); + int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il); ggml_tensor * build_mla_layer(ggml_tensor * cur, const llama_layer & layer, llm_graph_input_attn_k * inp_attn_k, @@ -3207,7 +3232,7 @@ struct llama_model_kimi_k31 : public llama_model_base { ggml_tensor * conv_states_all, ggml_tensor * conv_state_all, int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w, int64_t d_conv, int64_t head_dim, int64_t n_head_kda, - int64_t n_seq_tokens, int64_t n_seqs); + int64_t n_seq_tokens, int64_t n_seqs, int il); ggml_tensor * build_kda_layer(ggml_tensor * cur, const llama_layer & layer, llm_graph_input_rs * inp_rs, @@ -3294,7 +3319,7 @@ struct llama_model_glm5_next : public llama_model_base { // causal conv1d over one of Q/K/V, qkv selects which third of the conv state row is used ggml_tensor * build_kda_conv1d(llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all, int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w, - int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs); + int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il); ggml_tensor * build_kpool_select(ggml_tensor * cur, ggml_tensor * qr, const llama_layer & layer, const llama_memory_hybrid_idx_context * mctx_hyb, llm_graph_input_kpool * inp_kpool, int il); diff --git a/src/models/qwen4exp.cpp b/src/models/qwen4exp.cpp index 106530490fd7..f77e6f5090f8 100644 --- a/src/models/qwen4exp.cpp +++ b/src/models/qwen4exp.cpp @@ -1373,6 +1373,10 @@ ggml_tensor * llama_model_qwen4exp::graph::build_conv_state_at( int64_t state_cols, int64_t channels, int il) { + if (cparams.rs_replay) { + return build_conv_state_replay(inp, conv_states_all, x, state_cols, channels, il); + } + const int64_t n_seqs = ubatch.n_seqs; const int64_t row_total = conv_states_all->ne[0]; diff --git a/tests/llama-context/cases-rs.cpp b/tests/llama-context/cases-rs.cpp index a26322b30b27..ba4b71c7ec97 100644 --- a/tests/llama-context/cases-rs.cpp +++ b/tests/llama-context/cases-rs.cpp @@ -357,7 +357,7 @@ struct case_rollback_bound : ctx_test { const llm_arch arch = llama_arch_from_string(arch_name); // the DSV4 cache rebuilds snapshot d from the state before the ubatch, so d <= n is exact; - // the recurrent memory gets snapshots 0..n-1 from ggml_gated_delta_net, only for n <= n_rs_seq + 1 + // the recurrent memory gets snapshots 0..n-1 from ggml_ssm_scan, only for n <= n_rs_seq + 1 const bool from_ubatch_start = arch == LLM_ARCH_DEEPSEEK4 || arch == LLM_ARCH_DEEPSEEK41; const auto make_ctx = [&]() { diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index a0268b638a5e..5947cc1b0d17 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -5358,7 +5358,6 @@ struct test_gated_delta_net : public test_case { const int v_repeat; const bool permuted; const bool kda; - const int64_t K; // snapshot slot count: 1 = final-only, >1 = last K states const bool correlated; const bool padded_v; const bool padded_q; @@ -5366,16 +5365,8 @@ struct test_gated_delta_net : public test_case { // lower bound of the log-gate; a mild gate keeps the state alive over the whole sequence const float g_min; - std::string op_desc(ggml_tensor * t) override { - GGML_UNUSED(t); - return "GATED_DELTA_NET"; - } - - // compare only the view returned by build_graph, not the full op output - bool run_whole_graph() override { return K > 1 && n_seq_tokens > K; } - std::string vars() override { - std::string s = VARS_TO_STR13(type, head_count, head_size, n_seq_tokens, n_seqs, v_repeat, permuted, kda, K, correlated, padded_v, padded_q, permuted_k); + std::string s = VARS_TO_STR12(type, head_count, head_size, n_seq_tokens, n_seqs, v_repeat, permuted, kda, correlated, padded_v, padded_q, permuted_k); if (g_min != -20.0f) { s += "," + VAR_TO_STR(g_min); } @@ -5384,9 +5375,9 @@ struct test_gated_delta_net : public test_case { test_gated_delta_net(ggml_type type = GGML_TYPE_F32, int64_t head_count = 4, int64_t head_size = 16, int64_t n_seq_tokens = 1, int64_t n_seqs = 1, - int v_repeat = 1, bool permuted = false, bool kda = false, int64_t K = 1, bool correlated = false, bool padded_v = false, bool padded_q = false, bool permuted_k = false, float g_min = -20.0f) + int v_repeat = 1, bool permuted = false, bool kda = false, bool correlated = false, bool padded_v = false, bool padded_q = false, bool permuted_k = false, float g_min = -20.0f) : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), - v_repeat(v_repeat), permuted(permuted), kda(kda), K(K), correlated(correlated), padded_v(padded_v), padded_q(padded_q), permuted_k(permuted_k), g_min(g_min) {} + v_repeat(v_repeat), permuted(permuted), kda(kda), correlated(correlated), padded_v(padded_v), padded_q(padded_q), permuted_k(permuted_k), g_min(g_min) {} ggml_tensor * build_graph(ggml_context * ctx) override { ggml_tensor * q; @@ -5430,11 +5421,7 @@ struct test_gated_delta_net : public test_case { k_permuted = ggml_permute(ctx, k_permuted, 0, 2, 1, 3); k = ggml_cpy(ctx, k, k_permuted); } - ggml_tensor * out = ggml_gated_delta_net(ctx, q, k, v, g, beta, state, K); - if (K > 1 && n_seq_tokens > K) { - // n_tokens > K: only slot 0 is guaranteed, so keep the scores and slot 0 - out = ggml_view_2d(ctx, out, out->ne[0], out->ne[1] - (K - 1) * head_size * n_seqs, out->nb[1], 0); - } + ggml_tensor * out = ggml_gated_delta_net_ext(ctx, q, k, v, g, beta, state, nullptr, nullptr, nullptr, nullptr, false); return out; } @@ -5462,6 +5449,115 @@ struct test_gated_delta_net : public test_case { } }; +// GGML_OP_GATED_DELTA_NET with a replay of pending tokens (ggml_gated_delta_net_replay) +struct test_gated_delta_net_replay : public test_case { + const int64_t head_count; // k heads + const int64_t head_size; + const int64_t n_seq_tokens; + const int64_t n_seqs; + const int v_repeat; + const bool kda; + const int64_t n_pend; + const bool keep; + + std::string vars() override { + return VARS_TO_STR8(head_count, head_size, n_seq_tokens, n_seqs, v_repeat, kda, n_pend, keep); + } + + test_gated_delta_net_replay(int64_t head_count = 4, int64_t head_size = 32, int64_t n_seq_tokens = 4, int64_t n_seqs = 1, + int v_repeat = 1, bool kda = false, int64_t n_pend = 4, bool keep = true) + : head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), + v_repeat(v_repeat), kda(kda), n_pend(n_pend), keep(keep) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + const int64_t S = head_size; + const int64_t H_k = head_count; + const int64_t H = head_count * v_repeat; + const int64_t g0 = kda ? S : 1; + + ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, H_k, n_seq_tokens, n_seqs); + ggml_tensor * k = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, H_k, n_seq_tokens, n_seqs); + ggml_tensor * v = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, H, n_seq_tokens, n_seqs); + ggml_tensor * g = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, g0, H, n_seq_tokens, n_seqs); + ggml_tensor * beta = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 1, H, n_seq_tokens, n_seqs); + ggml_tensor * state = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, S, H, n_seqs); + // one spare token per seq in pend_k, so that its seq stride is not the dense one + ggml_tensor * pk = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, H_k, n_pend + 1, n_seqs); + ggml_tensor * pv = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, H, n_pend, n_seqs); + ggml_tensor * pgb = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, g0, H, 2*n_pend, n_seqs); + ggml_tensor * n_rep = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_seqs); + ggml_set_name(g, "g"); + ggml_set_name(beta, "beta"); + ggml_set_name(v, "v"); + ggml_set_name(pk, "pend_k"); + ggml_set_name(pv, "pend_v"); + ggml_set_name(pgb, "pend_gb"); + ggml_set_name(n_rep, "n_rep"); + + q = ggml_l2_norm(ctx, q, 1e-6f); + k = ggml_l2_norm(ctx, k, 1e-6f); + + ggml_tensor * pk_tok = ggml_view_4d(ctx, pk, S, H_k, n_pend, n_seqs, pk->nb[1], pk->nb[2], pk->nb[3], 0); + + return ggml_gated_delta_net_ext(ctx, q, k, v, g, beta, state, pk_tok, pv, pgb, n_rep, keep); + } + + void initialize_tensors(ggml_context * ctx) override { + std::mt19937 rng(0x6d4e); + const int64_t S = head_size; + const int64_t H = head_count * v_repeat; + const int64_t g0 = kda ? S : 1; + + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) { + if (ggml_is_view_op(t->op)) { continue; } + if (strcmp(t->name, "g") == 0) { + init_tensor_uniform(t, -20.0f, -1e-4f); + } else if (strcmp(t->name, "beta") == 0) { + init_tensor_uniform(t, 0.0f, 1.0f); + } else if (strcmp(t->name, "v") == 0) { + init_tensor_uniform(t, -0.3f, 5.0f); + } else if (strcmp(t->name, "n_rep") == 0) { + std::vector data(n_seqs); + for (auto & x : data) { + x = std::uniform_int_distribution(0, n_pend)(rng); + } + ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(int32_t)); + } else if (strcmp(t->name, "pend_k") == 0) { + // unit rows, as the l2 norm leaves them + std::vector data(ggml_nelements(t)); + std::uniform_real_distribution u(-1.0f, 1.0f); + for (int64_t i = 0; i < ggml_nelements(t)/S; ++i) { + float n2 = 0.0f; + for (int64_t j = 0; j < S; ++j) { data[i*S + j] = u(rng); n2 += data[i*S + j]*data[i*S + j]; } + for (int64_t j = 0; j < S; ++j) { data[i*S + j] /= sqrtf(n2); } + } + ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(float)); + } else if (strcmp(t->name, "pend_v") == 0) { + 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) + std::vector data(ggml_nelements(t), 0.0f); + std::uniform_real_distribution u(0.0f, 1.0f); + for (int64_t s = 0; s < n_seqs; ++s) { + for (int64_t r = 0; r < 2*n_pend; ++r) { + 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; } + } else { + row[h*g0] = u(rng); + } + } + } + } + ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(float)); + } else { + init_tensor_uniform(t); + } + } + } +}; + // GGML_OP_GATED_DELTA_NET + GGML_OP_CPY (recurrent cache fusion) struct test_gated_delta_net_cache_fusion : public test_case { const ggml_type type; @@ -5470,25 +5566,22 @@ struct test_gated_delta_net_cache_fusion : public test_case { const int64_t head_size; const int64_t n_seq_tokens; const int64_t n_seqs; - const int64_t K; // snapshot slot count (>1) ggml_tensor * cpy_node = nullptr; std::string vars() override { - return VARS_TO_STR6(type, head_count, head_size, n_seq_tokens, n_seqs, K); + return VARS_TO_STR5(type, head_count, head_size, n_seq_tokens, n_seqs); } test_gated_delta_net_cache_fusion(ggml_type type = GGML_TYPE_F32, - int64_t head_count = 4, int64_t head_size = 32, int64_t n_seq_tokens = 2, int64_t n_seqs = 1, - int64_t K = 2) - : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), K(K) {} + int64_t head_count = 4, int64_t head_size = 32, int64_t n_seq_tokens = 2, int64_t n_seqs = 1) + : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs) {} ggml_tensor * build_graph(ggml_context * ctx) override { const int64_t S_v = head_size; const int64_t H_v = head_count; const int64_t H_k = head_count; const int64_t D = S_v * S_v * H_v; - const int64_t n_written = std::min(n_seq_tokens, K); ggml_tensor * q = ggml_new_tensor_4d(ctx, type, head_size, H_k, n_seq_tokens, n_seqs); ggml_tensor * k = ggml_new_tensor_4d(ctx, type, head_size, H_k, n_seq_tokens, n_seqs); @@ -5506,7 +5599,7 @@ struct test_gated_delta_net_cache_fusion : public test_case { q = ggml_l2_norm(ctx, q, 1e-6f); k = ggml_l2_norm(ctx, k, 1e-6f); - ggml_tensor * gdn_out = ggml_gated_delta_net(ctx, q, k, v, g, beta, state, K); + ggml_tensor * gdn_out = ggml_gated_delta_net_ext(ctx, q, k, v, g, beta, state, nullptr, nullptr, nullptr, nullptr, false); ggml_set_name(gdn_out, "gdn_out"); // attn scores view (first part of the gdn output) @@ -5517,21 +5610,19 @@ struct test_gated_delta_net_cache_fusion : public test_case { ggml_row_size(gdn_out->type, S_v * H_v * n_seq_tokens), 0); ggml_set_name(attn, "attn"); - // snapshot tail view [D, n_seqs, n_written] + // state tail view [D, n_seqs] const int64_t attn_score_elems = S_v * H_v * n_seq_tokens * n_seqs; - ggml_tensor * src = ggml_view_3d(ctx, gdn_out, - D, n_seqs, n_written, + ggml_tensor * src = ggml_view_2d(ctx, gdn_out, + D, n_seqs, ggml_row_size(gdn_out->type, D), - ggml_row_size(gdn_out->type, D * n_seqs), ggml_row_size(gdn_out->type, attn_score_elems)); - // recurrent cache view [D, n_seqs, n_written] - ggml_tensor * cache = ggml_new_tensor_3d(ctx, type, D, n_seqs, n_written); + // recurrent cache view [D, n_seqs] + ggml_tensor * cache = ggml_new_tensor_2d(ctx, type, D, n_seqs); ggml_set_name(cache, "cache"); - ggml_tensor * dst = ggml_view_3d(ctx, cache, - D, n_seqs, n_written, - ggml_row_size(cache->type, D), - ggml_row_size(cache->type, D * n_seqs), 0); + ggml_tensor * dst = ggml_view_2d(ctx, cache, + D, n_seqs, + ggml_row_size(cache->type, D), 0); ggml_tensor * cpy = ggml_cpy(ctx, src, dst); ggml_set_name(cpy, "gdn_cache_cpy"); @@ -10004,14 +10095,34 @@ struct test_fill : public test_case { const ggml_type type; const std::array ne; float c; + const int64_t offset; // > 0: fill in place a view that starts offset elements into its buffer - std::string vars() override { return VARS_TO_STR3(type, ne, c); } + std::string vars() override { + std::string s = VARS_TO_STR3(type, ne, c); + if (offset != 0) { + s += "," + VAR_TO_STR(offset); + } + return s; + } test_fill(float c, ggml_type type = GGML_TYPE_F32, - std::array ne = { 10, 10, 4, 3 }) - : type(type), ne(ne), c(c) {} + std::array ne = { 10, 10, 4, 3 }, int64_t offset = 0) + : type(type), ne(ne), c(c), offset(offset) {} ggml_tensor * build_graph(ggml_context * ctx) override { + if (offset != 0) { + ggml_tensor * a = ggml_new_tensor_1d(ctx, type, offset + ne[0]*ne[1]*ne[2]*ne[3]); + ggml_set_name(a, "a"); + + ggml_tensor * v = ggml_view_4d(ctx, a, ne[0], ne[1], ne[2], ne[3], + ne[0]*ggml_type_size(type), ne[0]*ne[1]*ggml_type_size(type), ne[0]*ne[1]*ne[2]*ggml_type_size(type), + offset*ggml_type_size(type)); + + ggml_tensor * out = ggml_fill_inplace(ctx, v, c); + ggml_set_name(out, "out"); + return out; + } + ggml_tensor * a = ggml_new_tensor_4d(ctx, type, ne[0], ne[1], ne[2], ne[3]); ggml_set_param(a); ggml_set_name(a, "a"); @@ -13469,6 +13580,9 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_fill(2.0f, GGML_TYPE_F16, { 303, 207, 11, 3 })); test_cases.emplace_back(new test_fill(-152.0f, GGML_TYPE_F16, { 800, 600, 4, 4 })); test_cases.emplace_back(new test_fill(3.5f, GGML_TYPE_F16, { 2048, 512, 2, 2 })); + test_cases.emplace_back(new test_fill(0.0f, GGML_TYPE_F32, { 303, 7, 1, 1 }, 1)); + test_cases.emplace_back(new test_fill(2.0f, GGML_TYPE_F32, { 96, 4, 1, 1 }, 37)); + test_cases.emplace_back(new test_fill(2.0f, GGML_TYPE_F16, { 303, 7, 1, 1 }, 3)); test_cases.emplace_back(new test_sleep(0)); test_cases.emplace_back(new test_sleep(10, GGML_TYPE_F16, { 128, 4, 2, 2 })); @@ -14006,6 +14120,19 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_moe_reduce(2048, 16, 32, false, true)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 1, 1)); + for (bool keep : { true, false }) { + test_cases.emplace_back(new test_gated_delta_net_replay(4, 32, 4, 1, 1, false, 4, keep)); + test_cases.emplace_back(new test_gated_delta_net_replay(4, 64, 2, 3, 3, false, 4, keep)); + test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 4, 1, 3, false, 4, keep)); + test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 8, 2, 3, false, 8, keep)); + test_cases.emplace_back(new test_gated_delta_net_replay(4, 32, 1, 2, 2, false, 3, keep)); + test_cases.emplace_back(new test_gated_delta_net_replay(4, 64, 3, 2, 1, true, 4, keep)); + } + // prefill sized: the replay runs before the chunked kernels (CUDA from 64 tokens, HIP from 2048) + test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 65, 1, 1, false, 4, false)); + test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 257, 1, 3, false, 4, false)); + test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 513, 2, 2, false, 8, false)); + test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 2048, 1, 3, false, 4, false)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 16, 1, 1)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 16, 1, 1, 1, true, true)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 16, 1, 1, 1, false, true)); @@ -14041,9 +14168,8 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 64, 1, 1, false, true)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 65, 2, 2, true, true)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 1, 1, false, true)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 65, 1, 1, false, true, 1, true)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 1, 1, true, true, 1, true, true)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 4, 2, 2, false, true, 4)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 65, 1, 1, false, true, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 1, 1, true, true, true, true)); // MMA-eligible GDN shapes: whole heads, value slices, tails, and the HIP prefill threshold. test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 65, 1, 1)); @@ -14064,53 +14190,43 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 512, 2, 2)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 2, 2, true)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 129, 1, 1, false, false, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 129, 1, 1, false, false, false, true)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 4095, 1, 2)); // Correlated keys, high beta, and weak decay stress the chunked triangular solve. for (int64_t n_tokens : {64, 65, 257}) { - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, n_tokens, 1, 1, false, false, 1, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, n_tokens, 1, 1, false, false, true)); } // Odd V strides require element loads instead of aligned matrix loads. - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 65, 1, 1, false, false, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 65, 1, 1, false, false, false, true)); // Q and K can have different strides in both scalar and chunked paths. for (int64_t n_tokens : {4, 65}) { - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, 1, false, false, true)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, 1, false, false, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, false, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, false, false, false, true)); } - // mild decay keeps the state alive across the sequence; qwen35 prefill layout with K=5 snapshots + // mild decay keeps the state alive across the sequence; qwen35 prefill layout for (int64_t n : { 5, 300, 2048 }) { - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, n, 1, 3, false, false, /*K=*/5, false, false, false, false, /*g_min=*/-0.05f)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, n, 1, 3, false, false, false, false, false, false, /*g_min=*/-0.05f)); } - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 300, 2, 2, true, false, /*K=*/1, false, false, false, false, /*g_min=*/-0.05f)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 200, 1, 1, false, false, /*K=*/5, false, false, false, false, /*g_min=*/-0.05f)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 300, 2, 2, true, false, false, false, false, false, /*g_min=*/-0.05f)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 200, 1, 1, false, false, false, false, false, false, /*g_min=*/-0.05f)); // a backend may pick its kernel by head count: few and many heads, per head size, plain and KDA for (int64_t s : { 16, 32, 64, 128 }) { for (int64_t h : { 4 * 128 / s, 64 * 128 / s }) { - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, h, s, 37, 1, 1, false, false, /*K=*/4, false, false, false, false, /*g_min=*/-0.05f)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, h, s, 37, 1, 1, false, true, /*K=*/1, false, false, false, false, /*g_min=*/-0.05f)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, h, s, 37, 1, 1, false, false, false, false, false, false, /*g_min=*/-0.05f)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, h, s, 37, 1, 1, false, true, false, false, false, false, /*g_min=*/-0.05f)); } } - // K > 1: output keeps the last min(n_tokens, K) per-token snapshots, ordered most-recent-first - // (slot 0 = final state, slot s = state s tokens back). - // exact-match cases (K == n_seq_tokens): - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 16, 2, 1, 1, false, false, /*K=*/2)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 32, 4, 1, 1, false, false, /*K=*/4)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 4, 2, 1, false, false, /*K=*/4)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 8, 128, 4, 1, 1, false, false, /*K=*/4)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 4, 2, 1, false, true, /*K=*/4)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 8, 32, 4, 2, 2, false, true, /*K=*/4)); - - // gdn + cache cpy fusion (K > 1) - test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 2, 1, 2)); - test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 64, 4, 1, 2)); - test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 4, 1, 4)); - test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 8, 32, 4, 2, 4)); - test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 128, 64, 4, 1, 4)); - test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 8, 1, 4)); + // gdn + cache cpy fusion + test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 2, 1)); + test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 64, 4, 1)); + test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 4, 1)); + test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 8, 32, 4, 2)); + test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 128, 64, 4, 1)); + test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 8, 1)); #if 0 // these tests are disabled to save execution time, sbut they can be handy for debugging @@ -14795,7 +14911,6 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 8192, 1)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 20, 128, 1536, 1)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 20, 128, 2048, 1)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 2048, 1, 3, false, false, 5)); // qwen35 PP-2048, K=5 // lightning_indexer for (int kv : { 256, 4096, 65536 }) { From 38b9cad71d14fa69b20393f42ebcd22ced77934e Mon Sep 17 00:00:00 2001 From: Aldehir Rojas Date: Mon, 23 Nov 2026 17:41:33 -0600 Subject: [PATCH 035/275] quantize : make local const static for MSVC (#32902) --- src/llama-quant.cpp | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp index c66f060f621e..fd85c0f4031e 100644 --- a/src/llama-quant.cpp +++ b/src/llama-quant.cpp @@ -884,7 +884,7 @@ static std::unordered_map target_bpw_type( }; // Quantization types - constexpr ggml_type quant_types[] = { + static constexpr ggml_type quant_types[] = { GGML_TYPE_IQ1_S, GGML_TYPE_IQ1_M, GGML_TYPE_IQ2_XXS, @@ -908,16 +908,16 @@ static std::unordered_map target_bpw_type( GGML_TYPE_BF16, }; - constexpr double EPSILON = 1e-12; - constexpr double INFINITE = std::numeric_limits::infinity(); - constexpr uint64_t STATE_MAGIC = 0x4250572d5632; // "BPW-V2" - constexpr uint64_t HASH_MAGIC = 0xeabada55cafed00d; - constexpr float ffn_down_boost = 6.0f; - constexpr float output_boost = 3.0f; - constexpr float tied_embd_boost = 2.5f; - constexpr float attn_v_boost = 1.25f; - constexpr float boost_taper = 2.2f; // boost starves other tensors below 2.2 bpw - constexpr double downward_threshold = 0.08; // potential gains smaller than 8% are not trusted + static constexpr double EPSILON = 1e-12; + static constexpr double INFINITE = std::numeric_limits::infinity(); + static constexpr uint64_t STATE_MAGIC = 0x4250572d5632; // "BPW-V2" + static constexpr uint64_t HASH_MAGIC = 0xeabada55cafed00d; + static constexpr float ffn_down_boost = 6.0f; + static constexpr float output_boost = 3.0f; + static constexpr float tied_embd_boost = 2.5f; + static constexpr float attn_v_boost = 1.25f; + static constexpr float boost_taper = 2.2f; // boost starves other tensors below 2.2 bpw + static constexpr double downward_threshold = 0.08; // potential gains smaller than 8% are not trusted const char * func = __func__; // --target-exclude must leave at least one quant type in the pool From c74c71a6f7a0b06df30f979520e5d9a86a4d60ad Mon Sep 17 00:00:00 2001 From: Max Krasnyansky Date: Mon, 23 Nov 2026 15:47:20 -0800 Subject: [PATCH 036/275] fix editor config in master (#32914) --- ggml/src/ggml.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index 88ade6e8ae3a..c616fa39bf96 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -5545,7 +5545,7 @@ void ggml_flash_attn_ext_add_sinks( a->src[4] = sinks; } -bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a) { +bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a) { return a->op == GGML_OP_FLASH_ATTN_EXT && ggml_get_op_params_i32(a, 5) != 0; } From af5c58347fdbc2cd19e65b278e81c8f528f8a175 Mon Sep 17 00:00:00 2001 From: lhez Date: Mon, 23 Nov 2026 17:12:33 -0800 Subject: [PATCH 037/275] opencl: add c8 q6_k coopk GEMM for up to n=8 spec verify (#32909) Assisted-by: Codex Co-authored-by: Hongqiang Wang --- ggml/src/ggml-opencl/CMakeLists.txt | 1 + ggml/src/ggml-opencl/ggml-opencl.cpp | 143 +++++++++++- .../gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl | 214 ++++++++++++++++++ 3 files changed, 357 insertions(+), 1 deletion(-) create mode 100644 ggml/src/ggml-opencl/kernels/gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl diff --git a/ggml/src/ggml-opencl/CMakeLists.txt b/ggml/src/ggml-opencl/CMakeLists.txt index 1520f8d40e3a..6d55f5d3de5f 100644 --- a/ggml/src/ggml-opencl/CMakeLists.txt +++ b/ggml/src/ggml-opencl/CMakeLists.txt @@ -300,6 +300,7 @@ set(GGML_OPENCL_KERNELS gemm_coopk_q4_k_q8_1_dp4a gemm_coopk_q4_k_q8_1_dp4a_bin_c8 gemm_coopk_q6_k_q8_1_dp4a + gemm_coopk_q6_k_q8_1_dp4a_bin_c8 pack_b_f16_coopmat gemm_noshuffle_q4_0_f32_coopmat gemm_noshuffle_q5_0_f32_coopmat diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index 54038a503ad5..ba18fde3635d 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -1529,13 +1529,18 @@ struct ggml_backend_opencl_context { cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_c2 = nullptr; int nsg_coopk_dp4a_q6_k = 8; int rows_coopk_dp4a_q6_k = 4; + cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8 = nullptr; + cl_kernel kernel_quant_a_q8_1_k4h = nullptr; + int nsg_coopk_dp4a_q6_k_bin_c8 = 4; #endif // GGML_OPENCL_USE_ADRENO_KERNELS ~ggml_backend_opencl_context() { #ifdef GGML_OPENCL_USE_ADRENO_KERNELS for (cl_kernel kernel : { kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8, - kernel_quant_a_q8_1_k4 + kernel_quant_a_q8_1_k4, + kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8, + kernel_quant_a_q8_1_k4h } ) { if (kernel != nullptr) { @@ -1949,6 +1954,46 @@ static void load_cl_kernel_coopk_q4_k_bin_c8(ggml_backend_opencl_context * backe backend_ctx->kernel_quant_a_q8_1_k4 = quant; } +static void load_cl_kernel_coopk_q6_k_bin_c8(ggml_backend_opencl_context * backend_ctx) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl"); +#endif + cl_program program = ggml_cl_build_program_coopk(backend_ctx, kernel_src.c_str(), + "kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8", backend_ctx->kernel_compile_opts, + backend_ctx->nsg_coopk_dp4a_q6_k_bin_c8, false); + if (program == nullptr) { + return; + } + + cl_int err; + + cl_kernel gemm = clCreateKernel(program, "kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8", &err); + if (err != CL_SUCCESS) { + CL_CHECK(clReleaseProgram(program)); + return; + } + + cl_kernel quant = clCreateKernel(program, "kernel_quant_a_q8_1_k4h", &err); + CL_CHECK(clReleaseProgram(program)); + if (err != CL_SUCCESS) { + CL_CHECK(clReleaseKernel(gemm)); + return; + } + + if (backend_ctx->get_kernel_workgroup_size(quant) < 64) { + CL_CHECK(clReleaseKernel(gemm)); + CL_CHECK(clReleaseKernel(quant)); + return; + } + + backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8 = gemm; + backend_ctx->kernel_quant_a_q8_1_k4h = quant; +} + static void ggml_cl_coopk_build_narrow(ggml_backend_opencl_context * backend_ctx, const std::string & kernel_src, const char * kernel_name, int rows, int & nsg, cl_kernel & kernel_c4, cl_kernel & kernel_c2) { @@ -2065,6 +2110,15 @@ static void load_cl_kernels_gemm_coopk(ggml_backend_opencl_context * backend_ctx backend_ctx->rows_coopk_dp4a_q6_k, backend_ctx->nsg_coopk_dp4a_q6_k, backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_c4, backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_c2); + + static const bool use_coopk_bin = [] { + const char * env = getenv("GGML_OPENCL_COOPK_Q6_K_BIN"); + return !env || !*env || atoi(env) != 0; + }(); + + if (use_adreno_bin_kernels(backend_ctx) && use_coopk_bin) { + load_cl_kernel_coopk_q6_k_bin_c8(backend_ctx); + } GGML_LOG_CONT("."); } } @@ -29446,6 +29500,93 @@ static void ggml_cl_mul_mat_q6_K_f32_adreno_ila(ggml_backend_t backend, const gg const int N = ne1; const int K = ne00; + if (backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8 != nullptr && + N >= 2 && N <= 8 && M > 0 && K > 0 && M % 4 == 0 && K % 256 == 0 && + src0->ne[0] == K && src0->ne[1] == M && dst->ne[1] == N && + K <= INT_MAX / 8 && (int64_t) M * K / 8 <= INT_MAX && + src0->ne[2] == 1 && src0->ne[3] == 1 && src0->view_src == nullptr && + src1->ne[2] == 1 && src1->ne[3] == 1 && dst->ne[2] == 1 && dst->ne[3] == 1 && + ggml_is_contiguous(src1) && ggml_is_contiguous(dst) + ) { + const int kb = K / 32; + const size_t qa_bytes = (size_t)8 * K; + const size_t ds_bytes = (size_t)24 * kb * sizeof(cl_half); + + backend_ctx->prealloc_moe_qa.allocate(context, qa_bytes); + backend_ctx->prealloc_moe_da.allocate(context, ds_bytes); + + if (ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_qa, qa_bytes, + backend_ctx->coopk_c8_qa_image, backend_ctx->coopk_c8_qa_buffer, backend_ctx->coopk_c8_qa_image_bytes) && + ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_da, ds_bytes, + backend_ctx->coopk_c8_ds_image, backend_ctx->coopk_c8_ds_buffer, backend_ctx->coopk_c8_ds_image_bytes) + ) { + const int n_blocks = N * kb; + + cl_kernel quant = backend_ctx->kernel_quant_a_q8_1_k4h; + CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(quant, 4, sizeof(int), &n_blocks)); + CL_CHECK(clSetKernelArg(quant, 5, sizeof(int), &kb)); + + size_t quant_local[] = {64}; + size_t quant_global[] = {(size_t)8 * kb}; + backend_ctx->enqueue_ndrange_kernel(quant, 1, quant_global, quant_local, dst); + + int ksplit = ggml_cl_coopk_ksplit(backend_ctx, CEIL_DIV(M / 4, 64), kb); + if (backend_ctx->kernel_gemv_splitk_reduce_f32 == nullptr) { + ksplit = 1; + } + + cl_mem out = extrad->data_device; + cl_ulong out_offset = offsetd; + + if (ksplit > 1) { + backend_ctx->prealloc_splitk_partial.allocate(context, (size_t)ksplit * M * N * sizeof(float)); + out = backend_ctx->prealloc_splitk_partial.buffer; + out_offset = 0; + } + + const cl_uchar mask_c0 = 0xC0; + + const size_t nsg = backend_ctx->nsg_coopk_dp4a_q6_k_bin_c8; + cl_kernel gemm = backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8; + + CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0_q6_K->ql)); + CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0_q6_K->qh)); + CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0_q6_K->s)); + CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &extra0_q6_K->d)); + CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->coopk_c8_qa_image)); + CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->coopk_c8_ds_image)); + CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &out)); + CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_ulong), &out_offset)); + CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(gemm, 11, sizeof(cl_uchar), &mask_c0)); + CL_CHECK(clSetKernelArg(gemm, 12, sizeof(int), &ksplit)); + + size_t local[] = {64, nsg, 1}; + size_t global[] = {(size_t)CEIL_DIV(M / 4, 64) * 64, nsg * ksplit, 1}; + backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); + + if (ksplit > 1) { + const int rows = M * N; + cl_kernel reduce = backend_ctx->kernel_gemv_splitk_reduce_f32; + CL_CHECK(clSetKernelArg(reduce, 0, sizeof(cl_mem), &out)); + CL_CHECK(clSetKernelArg(reduce, 1, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(reduce, 2, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(reduce, 3, sizeof(int), &rows)); + CL_CHECK(clSetKernelArg(reduce, 4, sizeof(int), &ksplit)); + size_t reduce_local[] = {64}; + size_t reduce_global[] = {(size_t)CEIL_DIV(rows, 64) * 64}; + backend_ctx->enqueue_ndrange_kernel(reduce, 1, reduce_global, reduce_local, dst); + } + return; + } + } + if (ne1 == 1) { cl_mem b_sub_buf = nullptr; cl_mem b_img = nullptr; diff --git a/ggml/src/ggml-opencl/kernels/gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl b/ggml/src/ggml-opencl/kernels/gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl new file mode 100644 index 000000000000..b561c577a961 --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl @@ -0,0 +1,214 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#ifdef cl_khr_integer_dot_product +#pragma OPENCL EXTENSION cl_khr_integer_dot_product : enable +#endif + +#ifndef COOPK_NSG +#define COOPK_NSG 4 +#endif +#define COK_SG 64 +#define COK_ROWS 4 + +#define COK_PACK4(a, b, c, e) \ + ( ((uint)(a) & 0xFFu) | (((uint)(b) & 0xFFu) << 8) \ + | (((uint)(c) & 0xFFu) << 16) | (((uint)(e) & 0xFFu) << 24) ) + +// Pack (0, 2, 1, 3) K bytes and store scales plus both 16-value sums at width eight. +kernel void kernel_quant_a_q8_1_k4h( + global const float * src, + global uint * qa, + global half * ds, + ulong offset_src, + int total_blocks, + int k_b +) { + const int blk = get_global_id(0); + if (blk >= 8 * k_b) { + return; + } + const int col = blk / k_b; + const int b = blk % k_b; + if (blk >= total_blocks) { + vstore8((uint8)(0), 0, qa + blk * 8); + ds[(3 * b) * 8 + col] = (half)0; + ds[(3 * b + 1) * 8 + col] = (half)0; + ds[(3 * b + 2) * 8 + col] = (half)0; + return; + } + src = (global const float *)((global const char *)src + offset_src); + const int base = blk * 32; + + float v[32]; + float amax = 0.0f; + #pragma unroll + for (int i = 0; i < 32; ++i) { + v[i] = src[base + i]; + amax = fmax(amax, fabs(v[i])); + } + + const float d = amax / 127.0f; + const float id = (amax > 0.0f) ? (127.0f / amax) : 0.0f; + + int q[32]; + int sum_lo = 0, sum_hi = 0; + #pragma unroll + for (int i = 0; i < 16; ++i) { + q[i] = (int)rint(v[i] * id); + sum_lo += q[i]; + } + #pragma unroll + for (int i = 16; i < 32; ++i) { + q[i] = (int)rint(v[i] * id); + sum_hi += q[i]; + } + + uint8 out; + out.s0 = COK_PACK4(q[ 0], q[ 2], q[ 1], q[ 3]); + out.s1 = COK_PACK4(q[ 4], q[ 6], q[ 5], q[ 7]); + out.s2 = COK_PACK4(q[ 8], q[10], q[ 9], q[11]); + out.s3 = COK_PACK4(q[12], q[14], q[13], q[15]); + out.s4 = COK_PACK4(q[16], q[18], q[17], q[19]); + out.s5 = COK_PACK4(q[20], q[22], q[21], q[23]); + out.s6 = COK_PACK4(q[24], q[26], q[25], q[27]); + out.s7 = COK_PACK4(q[28], q[30], q[29], q[31]); + vstore8(out, 0, qa + blk * 8); + + ds[(3 * b) * 8 + col] = (half)d; + ds[(3 * b + 1) * 8 + col] = (half)(d * (float)sum_lo); + ds[(3 * b + 2) * 8 + col] = (half)(d * (float)sum_hi); +} + +// Cast before shifting to keep all four K values on Adreno compilers. +#define COK_LO(u) (((uint)(u) | ((uint)(ushort)((u) >> 4) << 16)) & 0x0F0F0F0Fu) +#define COK_HI(h) ((((((uint)(h)) & 0x33u) * 0x110u) & 0x3030u) | (((((uint)(h)) & 0xCCu) * 0x440000u) & 0x30300000u)) + +#define COK_UNPACK(r) \ + const uint w0_##r = COK_LO(bl0.s##r) | COK_HI(bh0.s##r); \ + const uint w1_##r = COK_LO(bl1.s##r) | COK_HI(bh1.s##r); \ + const uint w2_##r = COK_LO(bl2.s##r) | COK_HI(bh2.s##r); \ + const uint w3_##r = COK_LO(bl3.s##r) | COK_HI(bh3.s##r); + +#define COK_DOT_RC(r, c) \ + d##r.s##c = dot_acc_sat_4x8packed_ss_int(w0_##r, A.s0, d##r.s##c); \ + d##r.s##c = dot_acc_sat_4x8packed_ss_int(w1_##r, A.s1, d##r.s##c); \ + d##r.s##c = dot_acc_sat_4x8packed_ss_int(w2_##r, A.s2, d##r.s##c); \ + d##r.s##c = dot_acc_sat_4x8packed_ss_int(w3_##r, A.s3, d##r.s##c); + +#define COK_DOT_COL(c, t) \ + { const uint4 A = read_imageui(src1_qa, (c) * k_t + (t)); \ + COK_DOT_RC(0, c) COK_DOT_RC(1, c) COK_DOT_RC(2, c) COK_DOT_RC(3, c) } + +kernel void kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8( + global const uint * src0_ql, + global const uint * src0_qh, + global const ushort * src0_s, + global const half * src0_d, + read_only image1d_buffer_t src1_qa, + read_only image1d_buffer_t src1_ds, + global float * dst, + ulong offsetd, + int m, + int k, + int n_no_padding, + uchar mask_c0, + int ksplit +) { + dst = (global float *)((global char *)dst + offsetd); + + const int gx = get_global_id(0); + const int sg = get_local_id(1); + const int lane = get_local_id(0); + const int ks = get_group_id(1); + + const bool live = gx * COK_ROWS < m; + const int row0 = live ? gx * COK_ROWS : m - COK_ROWS; + const int num_32blk = k / 32; + const int k_t = k >> 4; + const int fence = (int)(mask_c0 >> 6) - 3; + + const int nslice = ksplit * COOPK_NSG; + const int b_beg = ks * COOPK_NSG + sg; + + float8 acc0 = (float8)(0.0f), acc1 = (float8)(0.0f); + float8 acc2 = (float8)(0.0f), acc3 = (float8)(0.0f); + + for (int bg = b_beg; bg * 8 < num_32blk; bg += nslice) { + ushort8 sr0 = vload8(0, src0_s + (row0 + 0) * num_32blk + bg * 8); + ushort8 sr1 = vload8(0, src0_s + (row0 + 1) * num_32blk + bg * 8); + ushort8 sr2 = vload8(0, src0_s + (row0 + 2) * num_32blk + bg * 8); + ushort8 sr3 = vload8(0, src0_s + (row0 + 3) * num_32blk + bg * 8); + for (int jb = 0; jb < 8; ++jb) { + const int blk = bg * 8 + jb; + const ushort4 spk = (ushort4)(sr0.s0, sr1.s0, sr2.s0, sr3.s0); + sr0 = sr0.s12345670; sr1 = sr1.s12345670; sr2 = sr2.s12345670; sr3 = sr3.s12345670; + const half4 scd = vload4(0, src0_d + row0 + (blk >> 3) * m); + const float8 da = convert_float8(as_half8(read_imageui(src1_ds, 3 * blk))); + + for (int h = 0; h < 2; ++h) { + const int g0 = (blk << 3) + (h << 2); + const int at = (blk << 1) + h; + + const uint4 l01 = vload4(0, src0_ql + row0 + ((g0 >> 1) ) * m); + const uint4 l23 = vload4(0, src0_ql + row0 + ((g0 >> 1) + 1) * m); + const uint4 hq = vload4(0, src0_qh + row0 + (g0 >> 2) * m); + + const ushort4 bl0 = (ushort4)((ushort)l01.s0, (ushort)l01.s1, (ushort)l01.s2, (ushort)l01.s3); + const ushort4 bl1 = (ushort4)((ushort)(l01.s0 >> 16), (ushort)(l01.s1 >> 16), (ushort)(l01.s2 >> 16), (ushort)(l01.s3 >> 16)); + const ushort4 bl2 = (ushort4)((ushort)l23.s0, (ushort)l23.s1, (ushort)l23.s2, (ushort)l23.s3); + const ushort4 bl3 = (ushort4)((ushort)(l23.s0 >> 16), (ushort)(l23.s1 >> 16), (ushort)(l23.s2 >> 16), (ushort)(l23.s3 >> 16)); + const uchar4 bh0 = (uchar4)((uchar)hq.s0, (uchar)hq.s1, (uchar)hq.s2, (uchar)hq.s3); + const uchar4 bh1 = (uchar4)((uchar)(hq.s0 >> 8), (uchar)(hq.s1 >> 8), (uchar)(hq.s2 >> 8), (uchar)(hq.s3 >> 8)); + const uchar4 bh2 = (uchar4)((uchar)(hq.s0 >> 16), (uchar)(hq.s1 >> 16), (uchar)(hq.s2 >> 16), (uchar)(hq.s3 >> 16)); + const uchar4 bh3 = (uchar4)((uchar)(hq.s0 >> 24), (uchar)(hq.s1 >> 24), (uchar)(hq.s2 >> 24), (uchar)(hq.s3 >> 24)); + + COK_UNPACK(0) COK_UNPACK(1) COK_UNPACK(2) COK_UNPACK(3) + + int8 d0 = (int8)(0), d1 = (int8)(0), d2 = (int8)(0), d3 = (int8)(0); + COK_DOT_COL(0, at) COK_DOT_COL(1, at) COK_DOT_COL(2, at) COK_DOT_COL(3, at) + const int at4 = at + (d0.s0 & fence); + COK_DOT_COL(4, at4) COK_DOT_COL(5, at4) COK_DOT_COL(6, at4) COK_DOT_COL(7, at4) + + const float8 sa = convert_float8(as_half8(read_imageui(src1_ds, 3 * blk + 1 + h))); + // Apply the signed-code offset with the sum for this 16-value half. + const float8 sm = sa * -32.0f; + const float s0f = (float)(h ? as_char2(spk.s0).s1 : as_char2(spk.s0).s0) * (float)scd.s0; + const float s1f = (float)(h ? as_char2(spk.s1).s1 : as_char2(spk.s1).s0) * (float)scd.s1; + const float s2f = (float)(h ? as_char2(spk.s2).s1 : as_char2(spk.s2).s0) * (float)scd.s2; + const float s3f = (float)(h ? as_char2(spk.s3).s1 : as_char2(spk.s3).s0) * (float)scd.s3; + acc0 = mad(mad(da, convert_float8(d0), sm), s0f, acc0); + acc1 = mad(mad(da, convert_float8(d1), sm), s1f, acc1); + acc2 = mad(mad(da, convert_float8(d2), sm), s2f, acc2); + acc3 = mad(mad(da, convert_float8(d3), sm), s3f, acc3); + } + } + } + + local float8 reduceLM[COK_SG * (COOPK_NSG - 1)]; + float8 out0 = (float8)(0.0f), out1 = (float8)(0.0f); + float8 out2 = (float8)(0.0f), out3 = (float8)(0.0f); +#define COK_REDUCE(accv, outv) \ + barrier(CLK_LOCAL_MEM_FENCE); \ + if (sg > 0) { reduceLM[(sg - 1) * COK_SG + lane] = (accv); } \ + barrier(CLK_LOCAL_MEM_FENCE); \ + if (sg == 0) { \ + float8 sum = (accv); \ + for (int s = 0; s < COOPK_NSG - 1; s++) { sum += reduceLM[s * COK_SG + lane]; } \ + (outv) = sum; \ + } + COK_REDUCE(acc0, out0) + COK_REDUCE(acc1, out1) + COK_REDUCE(acc2, out2) + COK_REDUCE(acc3, out3) +#undef COK_REDUCE + +#define COK_STORE_COL(c) \ + if ((c) < n_no_padding) { \ + vstore4((float4)(out0.s##c, out1.s##c, out2.s##c, out3.s##c), 0, dst + (c) * m + row0); \ + } + if (sg == 0 && live) { + dst += (size_t)ks * (size_t)m * (size_t)n_no_padding; + COK_STORE_COL(0) COK_STORE_COL(1) COK_STORE_COL(2) COK_STORE_COL(3) + COK_STORE_COL(4) COK_STORE_COL(5) COK_STORE_COL(6) COK_STORE_COL(7) + } +#undef COK_STORE_COL +} From 12d47ba2f462439240329b4e34a5e173e3267d66 Mon Sep 17 00:00:00 2001 From: lhez Date: Mon, 23 Nov 2026 21:14:37 -0800 Subject: [PATCH 038/275] opencl: fix GDN QK offsets (#32747) Assisted-by: Codex --- ggml/src/ggml-opencl/ggml-opencl.cpp | 6 ++++++ ggml/src/ggml-opencl/kernels/gated_delta_net.cl | 4 +++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index ba18fde3635d..700d214c3c8a 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -40664,6 +40664,9 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) { const cl_uint sq1 = (cl_uint)(src_q->nb[1] / sizeof(float)); const cl_uint sq2 = (cl_uint)(src_q->nb[2] / sizeof(float)); const cl_uint sq3 = (cl_uint)(src_q->nb[3] / sizeof(float)); + const cl_uint sk1 = (cl_uint)(src_k->nb[1] / sizeof(float)); + const cl_uint sk2 = (cl_uint)(src_k->nb[2] / sizeof(float)); + const cl_uint sk3 = (cl_uint)(src_k->nb[3] / sizeof(float)); const cl_uint sv1 = (cl_uint)(src_v->nb[1] / sizeof(float)); const cl_uint sv2 = (cl_uint)(src_v->nb[2] / sizeof(float)); const cl_uint sv3 = (cl_uint)(src_v->nb[3] / sizeof(float)); @@ -40714,6 +40717,9 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) { CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sq1)); CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sq2)); CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sq3)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sk1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sk2)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sk3)); CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sv1)); CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sv2)); CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sv3)); diff --git a/ggml/src/ggml-opencl/kernels/gated_delta_net.cl b/ggml/src/ggml-opencl/kernels/gated_delta_net.cl index 78b807cfdbba..b254703e481f 100644 --- a/ggml/src/ggml-opencl/kernels/gated_delta_net.cl +++ b/ggml/src/ggml-opencl/kernels/gated_delta_net.cl @@ -95,6 +95,7 @@ kernel void kernel_gated_delta_net( uint n_seqs, uint s_off, uint sq1, uint sq2, uint sq3, + uint sk1, uint sk2, uint sk3, uint sv1, uint sv2, uint sv3, uint sb1, uint sb2, uint sb3, uint H_k, @@ -136,6 +137,7 @@ kernel void kernel_gated_delta_net( // input state holds s0 only [S_v, S_v, H, n_seqs]: per-seq stride is H*D. const uint state_base = (seq_id * H_v + head_id) * state_size; const uint q_off_base = iq3 * sq3 + iq1 * sq1; + const uint k_off_base = iq3 * sk3 + iq1 * sk1; const uint v_off_base = seq_id * sv3 + head_id * sv1; const uint gb_off_base = seq_id * sb3 + head_id * sb1; const uint state_out_base = (seq_id * H_v + head_id) * state_size; @@ -231,7 +233,7 @@ kernel void kernel_gated_delta_net( for (uint t = 0; t < n_tokens; t++) { const uint q_off = q_off_base + t * sq2; - const uint k_off = q_off; + const uint k_off = k_off_base + t * sk2; const uint v_off = v_off_base + t * sv2; const uint gb_off = gb_off_base + t * sb2; const float beta_val = data_beta[gb_off]; From d141011c25781519123be51019441cd710260cb2 Mon Sep 17 00:00:00 2001 From: losewayy Date: Tue, 24 Nov 2026 15:25:31 +0800 Subject: [PATCH 039/275] vulkan: support state size 96 in ssm_scan (#32162) * vulkan: support state size 96 in ssm_scan Assisted-by: Claude Code * vulkan: specialize ssm_scan state size Assisted-by: Codex * vulkan: clarify ssm_scan constant names Assisted-by: Codex --- ggml/src/ggml-vulkan/ggml-vulkan-types.h | 1 + ggml/src/ggml-vulkan/ggml-vulkan.cpp | 21 ++++++++++------ .../ggml-vulkan/vulkan-shaders/ssm_scan.comp | 25 ++++++++++++------- tests/test-backend-ops.cpp | 2 ++ 4 files changed, 32 insertions(+), 17 deletions(-) diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-types.h b/ggml/src/ggml-vulkan/ggml-vulkan-types.h index f200b43d30f5..a121436e6b08 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-types.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-types.h @@ -1018,6 +1018,7 @@ struct vk_device_struct { vk_pipeline pipeline_gated_delta_net_cm; vk_pipeline pipeline_gated_delta_net_cm_v32; vk_pipeline pipeline_gated_delta_net_cm_v128; + vk_pipeline pipeline_ssm_scan_f32_d96; vk_pipeline pipeline_ssm_scan_f32_d128; vk_pipeline pipeline_ssm_scan_f32_d256; vk_pipeline pipeline_ssm_conv_f32; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index 88e595f4a8e9..74486b8500ba 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -4273,12 +4273,15 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { GGML_UNUSED(gdn_shmem); } + // Pad 96 states to a 128-thread workgroup for 32- and 64-lane subgroups. if (device->subgroup_arithmetic && device->subgroup_require_full_support) { - ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size}, 1, true, true); - ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size}, 1, true, true); + ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d96, "ssm_scan_96_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 96}, 1, true, true); + ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 128}, 1, true, true); + ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 256}, 1, true, true); } else { - ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 16}, 1, true, true); - ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 16}, 1, true, true); + ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d96, "ssm_scan_96_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 96}, 1, true, true); + ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 128}, 1, true, true); + ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 256}, 1, true, true); } ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_f32, "ssm_conv_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 4, sizeof(vk_op_ssm_conv_push_constants), {32, 16, 1}, {32, 16, 0, 0}, 1); @@ -10253,7 +10256,9 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const case GGML_OP_SSM_SCAN: if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { const uint32_t d_state = src0->ne[0]; - if (d_state == 128) { + if (d_state == 96) { + return ctx->device->pipeline_ssm_scan_f32_d96; + } else if (d_state == 128) { return ctx->device->pipeline_ssm_scan_f32_d128; } else if (d_state == 256) { return ctx->device->pipeline_ssm_scan_f32_d256; @@ -11523,7 +11528,7 @@ void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_te std::array elements; const uint32_t d_state = src0->ne[0]; - uint32_t num_subgroups = d_state / ctx->device->subgroup_size; + uint32_t num_subgroups = (d_state == 96 ? 128 : d_state) / ctx->device->subgroup_size; const uint32_t num_workgroups_x = CEIL_DIV(n_head * head_dim, num_subgroups); const uint32_t num_workgroups_y = n_seq; elements = { num_workgroups_x, num_workgroups_y, 1 }; @@ -17273,11 +17278,11 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm return false; } - if ((d_state != 128 && d_state != 256) || head_dim % 16 != 0) { + if ((d_state != 96 && d_state != 128 && d_state != 256) || head_dim % 16 != 0) { return false; } - size_t shmem_size = d_state * sizeof(float); + size_t shmem_size = (d_state == 96 ? 128 : d_state) * sizeof(float); if (shmem_size > device->properties.limits.maxComputeSharedMemorySize) { return false; diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/ssm_scan.comp b/ggml/src/ggml-vulkan/vulkan-shaders/ssm_scan.comp index 4fecb3aa5ace..ec9b9e60abf0 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/ssm_scan.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/ssm_scan.comp @@ -8,10 +8,11 @@ #include "types.glsl" -layout(constant_id = 0) const uint D_STATE = 128; +layout(constant_id = 0) const uint BLOCK_SIZE = 128; layout(constant_id = 1) const uint SUBGROUP_SIZE = 32; +layout(constant_id = 2) const uint D_STATE = 128; -const uint32_t c_factor = D_STATE / SUBGROUP_SIZE; +const uint32_t c_factor = (D_STATE + SUBGROUP_SIZE - 1) / SUBGROUP_SIZE; layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in; @@ -46,14 +47,14 @@ float softplus(float x) { } #if !USE_SUBGROUP_ADD -shared float temp[D_STATE]; +shared float temp[BLOCK_SIZE]; #endif void main() { const uint subgroup = gl_SubgroupID; const uint lane = gl_SubgroupInvocationID; const uint tid = gl_SubgroupID * SUBGROUP_SIZE + lane; - const uint subgroup_idx = gl_WorkGroupID.x * c_factor + subgroup; + const uint subgroup_idx = gl_WorkGroupID.x * (BLOCK_SIZE / SUBGROUP_SIZE) + subgroup; const uint head_idx = subgroup_idx / d_head; const uint head_off = (subgroup_idx % d_head) * 4; @@ -78,7 +79,8 @@ void main() { float state[c_factor]; [[unroll]] for (uint j = 0; j < c_factor; j++) { - state[j] = s0[s0_base_idx + SUBGROUP_SIZE * j + lane]; + const uint state_idx = SUBGROUP_SIZE * j + lane; + state[j] = D_STATE % SUBGROUP_SIZE == 0 || state_idx < D_STATE ? s0[s0_base_idx + state_idx] : 0.0f; } float a = A[A_base_idx]; @@ -91,8 +93,9 @@ void main() { const float dA = exp(dt_soft_plus * a); const float x_dt = x[x_base_idx + i * stride_x] * dt_soft_plus; [[unroll]] for (uint j = 0; j < c_factor; j++) { - float B_val = B[B_base_idx + i * stride_B + SUBGROUP_SIZE * j + lane]; - float C_val = C[C_base_idx + i * stride_C + SUBGROUP_SIZE * j + lane]; + const uint state_idx = SUBGROUP_SIZE * j + lane; + float B_val = D_STATE % SUBGROUP_SIZE == 0 || state_idx < D_STATE ? B[B_base_idx + i * stride_B + state_idx] : 0.0f; + float C_val = D_STATE % SUBGROUP_SIZE == 0 || state_idx < D_STATE ? C[C_base_idx + i * stride_C + state_idx] : 0.0f; state[j] = (state[j] * dA) + (B_val * x_dt); state_sum += state[j] * C_val; } @@ -121,7 +124,9 @@ void main() { if (slot > 0u && slot < K) { const uint snapshot_base_idx = s_base_idx + slot * n_seq * (nb03 / 4u); [[unroll]] for (uint j = 0; j < c_factor; j++) { - d[snapshot_base_idx + SUBGROUP_SIZE * j + lane] = state[j]; + if (D_STATE % SUBGROUP_SIZE == 0 || SUBGROUP_SIZE * j + lane < D_STATE) { + d[snapshot_base_idx + SUBGROUP_SIZE * j + lane] = state[j]; + } } } } @@ -129,6 +134,8 @@ void main() { // write back the state [[unroll]] for (int j = 0; j < c_factor; j++) { - d[s_base_idx + SUBGROUP_SIZE * j + lane] = state[j]; + if (D_STATE % SUBGROUP_SIZE == 0 || SUBGROUP_SIZE * j + lane < D_STATE) { + d[s_base_idx + SUBGROUP_SIZE * j + lane] = state[j]; + } } } diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 5947cc1b0d17..dc9e4a1ae69d 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -14854,6 +14854,8 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_ssm_conv(GGML_TYPE_F32, {4, 3328, 1, 1}, {4, 3328, 1, 1})); // generate test_cases.emplace_back(new test_ssm_conv_bias_silu(GGML_TYPE_F32, {515, 3328, 1, 1}, {4, 3328, 1, 1}, true)); // prefill test_cases.emplace_back(new test_ssm_conv_bias_silu(GGML_TYPE_F32, {4, 3328, 1, 1}, {4, 3328, 1, 1}, true)); // generate + test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 96, 64, 128, 8, 512, 1)); // Nemotron-3-Puzzle prefill + test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 96, 64, 128, 8, 1, 1)); // Nemotron-3-Puzzle generate test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 48, 1, 512, 1)); // prefill test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 48, 1, 1, 1)); // generate test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 80, 128, 1, 512, 1)); // Nemotron-9B prefill From b12f22d2f27412db16f8746280cf65f33bc1a0dd Mon Sep 17 00:00:00 2001 From: Georgi Gerganov Date: Tue, 24 Nov 2026 09:30:43 +0200 Subject: [PATCH 040/275] ggml : use a range-reduced log1p for softplus (#32655) * metal : use a range-reduced log1p for softplus Use the atanh series for x in [-0.5, 1] and precise::log(1 + x) otherwise. This avoids the cancellation in log(1 + exp(x)) for negative inputs and does not rely on fast-math folding of (1 + e) - 1. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * tests : add a softplus test for negative inputs Use inputs in [-16.6, -16.0], where log(1 + exp(x)) has up to ~2x relative error. This catches both the old form and the fast-math-folded compensated form. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * ggml : use log1pf in ggml_compute_softplus_f32 Use log1pf(expf(input)) so the host helper keeps the true value for x < -16.64. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) Co-authored-by: IsNot-10 <209144869@qq.com> * vulkan : use a range-reduced log1p for softplus Use the atanh series for x in [-0.5, 1] and log(1 + x) otherwise. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) Co-authored-by: IsNot-10 <209144869@qq.com> * opencl : use a range-reduced log1p for softplus Use the atanh series for x in [-0.5, 1] and log(1 + x) otherwise. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) Co-authored-by: IsNot-10 <209144869@qq.com> * vulkan : move log1p to utils.glsl Move the range-reduced log1p out of unary.comp into utils.glsl so that other ops such as topk_moe and ssm_scan can include it. The body is unchanged; only the call site in op_softplus is renamed. Co-authored-by: IsNot-10 <209144869@qq.com> Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (MacBook, M5 Max, 128GB) --------- Co-authored-by: IsNot-10 <209144869@qq.com> --- ggml/src/ggml-impl.h | 2 +- ggml/src/ggml-metal/kernels/unary.metal | 21 +++++++- ggml/src/ggml-opencl/kernels/softplus.cl | 52 ++++++++++++++++--- .../src/ggml-vulkan/vulkan-shaders/unary.comp | 3 +- .../src/ggml-vulkan/vulkan-shaders/utils.glsl | 20 +++++++ tests/test-backend-ops.cpp | 16 +++++- 6 files changed, 104 insertions(+), 10 deletions(-) diff --git a/ggml/src/ggml-impl.h b/ggml/src/ggml-impl.h index 7df7e1efd589..095ff643328c 100644 --- a/ggml/src/ggml-impl.h +++ b/ggml/src/ggml-impl.h @@ -105,7 +105,7 @@ static inline bool ggml_impl_is_view(const struct ggml_tensor * t) { } static inline float ggml_compute_softplus_f32(float input) { - return (input > 20.0f) ? input : logf(1 + expf(input)); + return (input > 20.0f) ? input : log1pf(expf(input)); } // compute correction dims for YaRN RoPE scaling diff --git a/ggml/src/ggml-metal/kernels/unary.metal b/ggml/src/ggml-metal/kernels/unary.metal index b361da996ffa..c8a441609848 100644 --- a/ggml/src/ggml-metal/kernels/unary.metal +++ b/ggml/src/ggml-metal/kernels/unary.metal @@ -21,6 +21,25 @@ inline bfloat4 ggml_metal_unary_cast(float x) { } #endif +template +inline T ggml_metal_log1p(T x) { + const T y = x / (T(2.0f) + x); + const T y2 = y * y; + T p = T(1.0f / 13.0f); + p = p * y2 + T(1.0f / 11.0f); + p = p * y2 + T(1.0f / 9.0f); + p = p * y2 + T(1.0f / 7.0f); + p = p * y2 + T(1.0f / 5.0f); + p = p * y2 + T(1.0f / 3.0f); + p = p * y2 + T(1.0f); + const T s = T(2.0f) * y * p; + const T l = precise::log(T(1.0f) + x); + const auto in_series = (x >= T(-0.5f)) & (x <= T(1.0f)); + const auto tiny = fabs(x) < T(2.5e-38f); + const T r = select(l, s, in_series); + return select(r, x, tiny); +} + template kernel void kernel_unary_impl( constant ggml_metal_kargs_unary & args, @@ -166,7 +185,7 @@ kernel void kernel_unary_impl( } if (FC_OP == OP_UNARY_NUM_SOFTPLUS) { - dst_ptr[i0] = ggml_metal_unary_cast(select(log(1 + exp(x)), x, x > 20)); + dst_ptr[i0] = ggml_metal_unary_cast(select(ggml_metal_log1p(precise::exp(x)), x, x > TC(20.0f))); } if (FC_OP == OP_UNARY_NUM_EXPM1) { diff --git a/ggml/src/ggml-opencl/kernels/softplus.cl b/ggml/src/ggml-opencl/kernels/softplus.cl index 6f8b7474165f..8c59c0ae48a7 100644 --- a/ggml/src/ggml-opencl/kernels/softplus.cl +++ b/ggml/src/ggml-opencl/kernels/softplus.cl @@ -4,6 +4,46 @@ // softplus //------------------------------------------------------------------------------ +inline float op_log1p(float x) { + const float y = x / (2.0f + x); + const float y2 = y * y; + float p = 1.0f / 13.0f; + p = p * y2 + 1.0f / 11.0f; + p = p * y2 + 1.0f / 9.0f; + p = p * y2 + 1.0f / 7.0f; + p = p * y2 + 1.0f / 5.0f; + p = p * y2 + 1.0f / 3.0f; + p = p * y2 + 1.0f; + const float s = 2.0f * y * p; + const float l = log(1.0f + x); + const float r = select(l, s, (x >= -0.5f) & (x <= 1.0f)); + return select(r, x, fabs(x) < 2.5e-38f); +} + +inline float4 op_log1p4(float4 x) { + const float4 y = x / ((float4)(2.0f) + x); + const float4 y2 = y * y; + float4 p = (float4)(1.0f / 13.0f); + p = p * y2 + (float4)(1.0f / 11.0f); + p = p * y2 + (float4)(1.0f / 9.0f); + p = p * y2 + (float4)(1.0f / 7.0f); + p = p * y2 + (float4)(1.0f / 5.0f); + p = p * y2 + (float4)(1.0f / 3.0f); + p = p * y2 + (float4)(1.0f); + const float4 s = (float4)(2.0f) * y * p; + const float4 l = log((float4)(1.0f) + x); + const float4 r = select(l, s, (x >= (float4)(-0.5f)) & (x <= (float4)(1.0f))); + return select(r, x, fabs(x) < (float4)(2.5e-38f)); +} + +inline float softplus_f32(float x) { + return select(op_log1p(exp(x)), x, x > 20.0f); +} + +inline float4 softplus_f32_4(float4 x) { + return select(op_log1p4(exp(x)), x, x > (float4)(20.0f)); +} + kernel void kernel_softplus_f32( global const float * src0, ulong offset0, @@ -13,7 +53,7 @@ kernel void kernel_softplus_f32( src0 = (global float*)((global char*)src0 + offset0); dst = (global float*)((global char*)dst + offsetd); - dst[get_global_id(0)] = (src0[get_global_id(0)] > 20.0f) ? src0[get_global_id(0)] : log(1.0f + exp(src0[get_global_id(0)])); + dst[get_global_id(0)] = softplus_f32(src0[get_global_id(0)]); } kernel void kernel_softplus_f32_4( @@ -25,7 +65,7 @@ kernel void kernel_softplus_f32_4( src0 = (global float4*)((global char*)src0 + offset0); dst = (global float4*)((global char*)dst + offsetd); - dst[get_global_id(0)] = (src0[get_global_id(0)] > 20.0f) ? src0[get_global_id(0)] : log(1.0f + exp(src0[get_global_id(0)])); + dst[get_global_id(0)] = softplus_f32_4(src0[get_global_id(0)]); } kernel void kernel_softplus_f16( @@ -38,7 +78,7 @@ kernel void kernel_softplus_f16( dst = (global half*)((global char*)dst + offsetd); const float x = convert_float(src0[get_global_id(0)]); - dst[get_global_id(0)] = convert_half_rte((x > 20.0f) ? x : log(1.0f + exp(x))); + dst[get_global_id(0)] = convert_half_rte(softplus_f32(x)); } kernel void kernel_softplus_f16_4( @@ -51,7 +91,7 @@ kernel void kernel_softplus_f16_4( dst = (global half4*)((global char*)dst + offsetd); const float4 x = convert_float4(src0[get_global_id(0)]); - dst[get_global_id(0)] = convert_half4_rte((x > 20.0f) ? x : log(1.0f + exp(x))); + dst[get_global_id(0)] = convert_half4_rte(softplus_f32_4(x)); } kernel void kernel_softplus_f32_nc( @@ -80,7 +120,7 @@ kernel void kernel_softplus_f32_nc( global const float * x = (global const float *)(src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00); global float * y = (global float *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0); - *y = (*x > 20.0f) ? *x : log(1.0f + exp(*x)); + *y = softplus_f32(*x); } } @@ -111,6 +151,6 @@ kernel void kernel_softplus_f16_nc( global half * hy = (global half *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0); const float x = convert_float(*hx); - *hy = convert_half_rte((x > 20.0f) ? x : log(1.0f + exp(x))); + *hy = convert_half_rte(softplus_f32(x)); } } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/unary.comp b/ggml/src/ggml-vulkan/vulkan-shaders/unary.comp index 04a3756bd7d1..756c70b1d1e4 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/unary.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/unary.comp @@ -1,6 +1,7 @@ #version 450 #include "types.glsl" +#include "utils.glsl" #if defined(UNARY_MUL_FUSION) #include "generic_binary_head.glsl" #else @@ -116,7 +117,7 @@ float op_expm1(float x) { } float op_softplus(float x) { - return (x > 20.0f) ? x : log(1.0f + exp(x)); + return (x > 20.0f) ? x : log1p(exp(x)); } float op_gelu_erf(float a) { diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/utils.glsl b/ggml/src/ggml-vulkan/vulkan-shaders/utils.glsl index 8aac64d75932..1f3b74783e63 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/utils.glsl +++ b/ggml/src/ggml-vulkan/vulkan-shaders/utils.glsl @@ -25,6 +25,26 @@ uint fastdiv_small(uint a, uint b) { return (a < b) ? 0 : (a / b); } +// log(1 + x); the atanh series 2*y*(1 + y^2/3 + ... + y^12/13), y = x/(2+x), +// keeps the precision that log(1 + x) loses for x in [-0.5, 1]. +float log1p(float x) { + float y = x / (2.0f + x); + float y2 = y * y; + float p = 1.0f / 13.0f; + p = p * y2 + 1.0f / 11.0f; + p = p * y2 + 1.0f / 9.0f; + p = p * y2 + 1.0f / 7.0f; + p = p * y2 + 1.0f / 5.0f; + p = p * y2 + 1.0f / 3.0f; + p = p * y2 + 1.0f; + float s = 2.0f * y * p; + float l = log(1.0f + x); + bool in_series = (x >= -0.5f) && (x <= 1.0f); + bool tiny = abs(x) < 2.5e-38f; + float r = in_series ? s : l; + return tiny ? x : r; +} + void get_indices(uint idx, out uint i00, out uint i01, out uint i02, out uint i03, uint ne00, uint ne01, uint ne02, uint ne03) { i03 = fastdiv_small(idx, (ne02*ne01*ne00)); const uint i03_offset = i03 * ne02*ne01*ne00; diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index dc9e4a1ae69d..2d50c607cab3 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -2258,6 +2258,20 @@ struct test_unary : public test_case { }; +struct test_unary_softplus_neg : public test_unary { + test_unary_softplus_neg() : test_unary(GGML_UNARY_OP_SOFTPLUS) {} + + std::string vars() override { + return test_unary::vars() + ",neg"; + } + + void initialize_tensors(ggml_context * ctx) override { + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + init_tensor_uniform(t, -16.6f, -16.0f); + } + } +}; + // GGML_OP_GLU struct test_glu : public test_case { const ggml_glu_op op; @@ -11130,7 +11144,7 @@ static std::vector> make_test_cases_eval() { std::default_random_engine rng(0); // unary ops - // TODO: add GGML_UNARY_OP_SOFTPLUS test that is sensitive to using `log1p(exp(x))` vs `log(exp(x) + 1)` + test_cases.emplace_back(new test_unary_softplus_neg()); for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32, GGML_TYPE_BF16}) { for (int v : {0, 1}) { for (int op = 0; op < GGML_UNARY_OP_COUNT; op++) { From 4af4bb6d8ad83ec0b3ef84a3bc477ccfe179b4ff Mon Sep 17 00:00:00 2001 From: Aman Gupta Date: Tue, 24 Nov 2026 15:43:50 +0800 Subject: [PATCH 041/275] rpc : reuse one context for request tensors on the server (#32896) --- ggml/src/ggml-rpc/ggml-rpc.cpp | 133 +++++++++------------------------ 1 file changed, 35 insertions(+), 98 deletions(-) diff --git a/ggml/src/ggml-rpc/ggml-rpc.cpp b/ggml/src/ggml-rpc/ggml-rpc.cpp index 6197f01c285e..1814002ce4c6 100644 --- a/ggml/src/ggml-rpc/ggml-rpc.cpp +++ b/ggml/src/ggml-rpc/ggml-rpc.cpp @@ -1561,6 +1561,13 @@ class rpc_server { : backends(std::move(all_backends)), cache_dir(cache_dir) { stored_graphs.resize(backends.size()); comm_states.resize(backends.size()); + ggml_init_params params { + /*.mem_size =*/ ggml_tensor_overhead()*(1 + GGML_MAX_SRC), + /*.mem_buffer =*/ NULL, + /*.no_alloc =*/ true, + }; + req_ctx.reset(ggml_init(params)); + GGML_ASSERT(req_ctx != nullptr); } ~rpc_server(); @@ -1593,6 +1600,16 @@ class rpc_server { }; private: + // empty context for the tensors of one request, valid until the next call + ggml_context * request_ctx() { + ggml_reset(req_ctx.get()); + return req_ctx.get(); + } + // nullptr if the buffer was not allocated by this server + ggml_backend_buffer_t find_buffer(uint64_t remote_ptr) const { + ggml_backend_buffer_t buffer = reinterpret_cast(remote_ptr); + return buffers.find(buffer) != buffers.end() ? buffer : nullptr; + } void sync_all_backends(); void comm_free_device(uint32_t dev_id); static bool comm_allreduce_pairwise(void * comm_ctx_v, ggml_tensor ** tensors); @@ -1631,6 +1648,7 @@ class rpc_server { std::vector comm_states; // SET_TENSOR data is received in chunks through this buffer std::vector set_tensor_buf; + ggml_context_ptr req_ctx; }; void rpc_server::hello(rpc_msg_hello_rsp & response) { @@ -1647,15 +1665,7 @@ bool rpc_server::get_alloc_size(const rpc_msg_get_alloc_size_req & request, rpc_ return false; } ggml_backend_buffer_type_t buft; - struct ggml_init_params params { - /*.mem_size =*/ ggml_tensor_overhead()*(1 + GGML_MAX_SRC), - /*.mem_buffer =*/ NULL, - /*.no_alloc =*/ true, - }; - - ggml_context_ptr ctx_ptr { ggml_init(params) }; - GGML_ASSERT(ctx_ptr != nullptr); - ggml_context * ctx = ctx_ptr.get(); + ggml_context * ctx = request_ctx(); ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); if (tensor == nullptr) { @@ -1733,8 +1743,8 @@ bool rpc_server::get_max_size(const rpc_msg_get_max_size_req & request, rpc_msg_ bool rpc_server::buffer_get_base(const rpc_msg_buffer_get_base_req & request, rpc_msg_buffer_get_base_rsp & response) { LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 "\n", __func__, request.remote_ptr); - ggml_backend_buffer_t buffer = reinterpret_cast(request.remote_ptr); - if (buffers.find(buffer) == buffers.end()) { + ggml_backend_buffer_t buffer = find_buffer(request.remote_ptr); + if (buffer == nullptr) { LOG_ERROR("[%s] buffer not found\n", __func__); return false; } @@ -1746,8 +1756,8 @@ bool rpc_server::buffer_get_base(const rpc_msg_buffer_get_base_req & request, rp bool rpc_server::free_buffer(const rpc_msg_free_buffer_req & request) { sync_all_backends(); LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 "\n", __func__, request.remote_ptr); - ggml_backend_buffer_t buffer = reinterpret_cast(request.remote_ptr); - if (buffers.find(buffer) == buffers.end()) { + ggml_backend_buffer_t buffer = find_buffer(request.remote_ptr); + if (buffer == nullptr) { LOG_ERROR("[%s] buffer not found\n", __func__); return false; } @@ -1767,8 +1777,8 @@ bool rpc_server::free_buffer(const rpc_msg_free_buffer_req & request) { bool rpc_server::buffer_clear(const rpc_msg_buffer_clear_req & request) { sync_all_backends(); LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 ", value: %u\n", __func__, request.remote_ptr, request.value); - ggml_backend_buffer_t buffer = reinterpret_cast(request.remote_ptr); - if (buffers.find(buffer) == buffers.end()) { + ggml_backend_buffer_t buffer = find_buffer(request.remote_ptr); + if (buffer == nullptr) { LOG_ERROR("[%s] buffer not found\n", __func__); return false; } @@ -1778,15 +1788,7 @@ bool rpc_server::buffer_clear(const rpc_msg_buffer_clear_req & request) { bool rpc_server::memset_tensor(const rpc_msg_memset_tensor_req & request) { sync_all_backends(); - struct ggml_init_params params { - /*.mem_size =*/ ggml_tensor_overhead(), - /*.mem_buffer =*/ NULL, - /*.no_alloc =*/ true, - }; - ggml_context_ptr ctx_ptr { ggml_init(params) }; - GGML_ASSERT(ctx_ptr != nullptr); - ggml_context * ctx = ctx_ptr.get(); - ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); + ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor); if (!rpc_check_region(__func__, tensor, request.offset, request.size)) { return false; } @@ -1830,10 +1832,7 @@ ggml_tensor * rpc_server::deserialize_tensor(struct ggml_context * ctx, const rp return nullptr; } - ggml_backend_buffer_t buffer = reinterpret_cast(tensor->buffer); - if (buffer && buffers.find(buffer) == buffers.end()) { - buffer = nullptr; - } + ggml_backend_buffer_t buffer = find_buffer(tensor->buffer); if (buffer && nbytes > 0 && !rpc_in_buffer(buffer, tensor->data, nbytes)) { LOG_ERROR("[%s] tensor '%.*s' (op %s, type %s) data 0x%" PRIx64 " with size %" PRIu64 " out of buffer bounds " "(base %p, size %zu)\n", __func__, (int) sizeof(tensor->name), tensor->name, ggml_op_name((ggml_op) tensor->op), @@ -1868,15 +1867,7 @@ bool rpc_server::set_tensor(socket_ptr sock, uint64_t input_size) { const uint64_t offset = request.offset; const size_t size = input_size - sizeof(request); - struct ggml_init_params params { - /*.mem_size =*/ ggml_tensor_overhead(), - /*.mem_buffer =*/ NULL, - /*.no_alloc =*/ true, - }; - ggml_context_ptr ctx_ptr { ggml_init(params) }; - GGML_ASSERT(ctx_ptr != nullptr); - ggml_context * ctx = ctx_ptr.get(); - ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); + ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor); if (!rpc_check_region(__func__, tensor, offset, size)) { return false; } @@ -1927,15 +1918,7 @@ bool rpc_server::set_tensor_2d(const std::vector & input) { return false; } - struct ggml_init_params params { - /*.mem_size =*/ ggml_tensor_overhead(), - /*.mem_buffer =*/ NULL, - /*.no_alloc =*/ true, - }; - ggml_context_ptr ctx_ptr { ggml_init(params) }; - GGML_ASSERT(ctx_ptr != nullptr); - ggml_context * ctx = ctx_ptr.get(); - ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); + ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor); if (!rpc_check_region(__func__, tensor, request.offset, request.size, request.n_copies, request.stride)) { return false; } @@ -1975,15 +1958,7 @@ bool rpc_server::get_cached_file(uint64_t hash, std::vector & data) { bool rpc_server::set_tensor_hash(const rpc_msg_set_tensor_hash_req & request, rpc_msg_set_tensor_hash_rsp & response) { sync_all_backends(); - struct ggml_init_params params { - /*.mem_size =*/ ggml_tensor_overhead(), - /*.mem_buffer =*/ NULL, - /*.no_alloc =*/ true, - }; - ggml_context_ptr ctx_ptr { ggml_init(params) }; - GGML_ASSERT(ctx_ptr != nullptr); - ggml_context * ctx = ctx_ptr.get(); - ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); + ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor); if (!rpc_check_region(__func__, tensor, request.offset, 0)) { return false; } @@ -2010,15 +1985,7 @@ bool rpc_server::set_tensor_hash(const rpc_msg_set_tensor_hash_req & request, rp bool rpc_server::init_tensor(const rpc_msg_init_tensor_req & request) { sync_all_backends(); - struct ggml_init_params params { - /*.mem_size =*/ ggml_tensor_overhead(), - /*.mem_buffer =*/ NULL, - /*.no_alloc =*/ true, - }; - ggml_context_ptr ctx_ptr { ggml_init(params) }; - GGML_ASSERT(ctx_ptr != nullptr); - ggml_context * ctx = ctx_ptr.get(); - ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); + ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor); if (tensor == nullptr) { LOG_ERROR("Null tensor pointer passed to server init_tensor function.\n"); return false; @@ -2047,15 +2014,7 @@ bool rpc_server::init_tensor(const rpc_msg_init_tensor_req & request) { bool rpc_server::get_tensor(const rpc_msg_get_tensor_req & request, std::vector & response) { sync_all_backends(); - struct ggml_init_params params { - /*.mem_size =*/ ggml_tensor_overhead(), - /*.mem_buffer =*/ NULL, - /*.no_alloc =*/ true, - }; - ggml_context_ptr ctx_ptr { ggml_init(params) }; - GGML_ASSERT(ctx_ptr != nullptr); - ggml_context * ctx = ctx_ptr.get(); - ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); + ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor); if (!rpc_check_region(__func__, tensor, request.offset, request.size)) { return false; } @@ -2070,15 +2029,7 @@ bool rpc_server::get_tensor(const rpc_msg_get_tensor_req & request, std::vector< bool rpc_server::get_tensor_2d(const rpc_msg_tensor_2d_req & request, std::vector & response) { sync_all_backends(); - struct ggml_init_params params { - /*.mem_size =*/ ggml_tensor_overhead(), - /*.mem_buffer =*/ NULL, - /*.no_alloc =*/ true, - }; - ggml_context_ptr ctx_ptr { ggml_init(params) }; - GGML_ASSERT(ctx_ptr != nullptr); - ggml_context * ctx = ctx_ptr.get(); - ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); + ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor); if (!rpc_check_region(__func__, tensor, request.offset, request.size, request.n_copies, request.stride)) { return false; } @@ -2093,14 +2044,7 @@ bool rpc_server::get_tensor_2d(const rpc_msg_tensor_2d_req & request, std::vecto bool rpc_server::copy_tensor(const rpc_msg_copy_tensor_req & request, rpc_msg_copy_tensor_rsp & response) { sync_all_backends(); - struct ggml_init_params params { - /*.mem_size =*/ 2*ggml_tensor_overhead(), - /*.mem_buffer =*/ NULL, - /*.no_alloc =*/ true, - }; - ggml_context_ptr ctx_ptr { ggml_init(params) }; - GGML_ASSERT(ctx_ptr != nullptr); - ggml_context * ctx = ctx_ptr.get(); + ggml_context * ctx = request_ctx(); ggml_tensor * src = deserialize_tensor(ctx, &request.src); ggml_tensor * dst = deserialize_tensor(ctx, &request.dst); @@ -2559,14 +2503,7 @@ bool rpc_server::comm_allreduce(const rpc_msg_comm_allreduce_req & request) { return false; } - struct ggml_init_params params = { - /*.mem_size =*/ ggml_tensor_overhead(), - /*.mem_buffer =*/ NULL, - /*.no_alloc =*/ true, - }; - ggml_context_ptr ctx_ptr { ggml_init(params) }; - GGML_ASSERT(ctx_ptr != nullptr); - ggml_tensor * t_dst = deserialize_tensor(ctx_ptr.get(), &request.tensor); + ggml_tensor * t_dst = deserialize_tensor(request_ctx(), &request.tensor); if (t_dst == nullptr || t_dst->buffer == nullptr) { LOG_ERROR("[%s] error deserializing tensor\n", __func__); return false; From 3fccd98e9dba9f19b2f5bf3818e06c3262adcf3e Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Tue, 24 Nov 2026 09:25:04 +0100 Subject: [PATCH 042/275] ui: let the chat form's model selection decide the submit state (#32920) When the last assistant message came from a model that is no longer available, the submit button stayed red and disabled even after an available model was picked in the form, since availability checked the conversation's model first. The form's selection now decides it; the conversation's model only counts when nothing is selected. Assisted-by: Claude (Opus 5.5 Medium) --- .../lib/hooks/use-chat-form-model.svelte.ts | 26 +++--- ui/apps/chat/src/lib/utils/model-selection.ts | 43 ++++++++++ ...hat-form-model-availability.svelte.test.ts | 84 +++++++++++++++++++ .../tests/unit/chat-form-model-state.test.ts | 70 ++++++++++++++++ 4 files changed, 208 insertions(+), 15 deletions(-) create mode 100644 ui/apps/chat/src/lib/utils/model-selection.ts create mode 100644 ui/apps/chat/tests/client/chat-form-model-availability.svelte.test.ts create mode 100644 ui/apps/chat/tests/unit/chat-form-model-state.test.ts diff --git a/ui/apps/chat/src/lib/hooks/use-chat-form-model.svelte.ts b/ui/apps/chat/src/lib/hooks/use-chat-form-model.svelte.ts index d9f81b6adef3..a2b559ac7c0a 100644 --- a/ui/apps/chat/src/lib/hooks/use-chat-form-model.svelte.ts +++ b/ui/apps/chat/src/lib/hooks/use-chat-form-model.svelte.ts @@ -11,6 +11,7 @@ import { conversationsStore, modelsStore, serverStore } from '#lib/stores/index.ts'; import type { DatabaseMessage } from '#lib/types/database.js'; import { getConversationModel } from '#lib/utils/index.ts'; +import { getChatFormModelState } from '#lib/utils/model-selection.ts'; export function useChatFormModel() { const isRouter = $derived(serverStore.isRouterMode); @@ -82,22 +83,17 @@ export function useChatFormModel() { return activeModelId ? modelsStore.props.modelSupportsVision(activeModelId) : false; }); - const hasModelSelected = $derived( - !isRouter || !!conversationModel || !!modelsStore.selectedModelId + // the form's selection decides the state; the conversation's model only counts when nothing is selected + const modelState = $derived( + getChatFormModelState({ + conversationModel, + isRouter, + models: modelsStore.models, + selectedModelId: modelsStore.selectedModelId + }) ); - const isSelectedModelInCache = $derived.by(() => { - if (!isRouter) return true; - - if (conversationModel) { - return modelsStore.models.some((option) => option.model === conversationModel); - } - - const currentModelId = modelsStore.selectedModelId; - - if (!currentModelId) return false; - - return modelsStore.models.some((option) => option.id === currentModelId); - }); + const hasModelSelected = $derived(modelState.hasModelSelected); + const isSelectedModelInCache = $derived(modelState.isSelectedModelAvailable); return { get conversationModel() { diff --git a/ui/apps/chat/src/lib/utils/model-selection.ts b/ui/apps/chat/src/lib/utils/model-selection.ts new file mode 100644 index 000000000000..948c7efef713 --- /dev/null +++ b/ui/apps/chat/src/lib/utils/model-selection.ts @@ -0,0 +1,43 @@ +import type { ModelOption } from '#lib/types/models.js'; + +export interface ChatFormModelStateInput { + conversationModel: string | null; + isRouter: boolean; + models: readonly Pick[]; + selectedModelId: string | null; +} + +export interface ChatFormModelState { + hasModelSelected: boolean; + isSelectedModelAvailable: boolean; +} + +/** + * Whether the chat form has a model to send with and whether that model is available. + * The form's own selection always wins; the conversation's last model only counts + * when nothing is selected in the form. + */ +export function getChatFormModelState({ + conversationModel, + isRouter, + models, + selectedModelId +}: ChatFormModelStateInput): ChatFormModelState { + if (!isRouter) return { hasModelSelected: true, isSelectedModelAvailable: true }; + + if (selectedModelId) { + return { + hasModelSelected: true, + isSelectedModelAvailable: models.some((option) => option.id === selectedModelId) + }; + } + + if (conversationModel) { + return { + hasModelSelected: true, + isSelectedModelAvailable: models.some((option) => option.model === conversationModel) + }; + } + + return { hasModelSelected: false, isSelectedModelAvailable: false }; +} diff --git a/ui/apps/chat/tests/client/chat-form-model-availability.svelte.test.ts b/ui/apps/chat/tests/client/chat-form-model-availability.svelte.test.ts new file mode 100644 index 000000000000..2ea96c70495d --- /dev/null +++ b/ui/apps/chat/tests/client/chat-form-model-availability.svelte.test.ts @@ -0,0 +1,84 @@ +// Regression: when the conversation's last assistant message names a model that is no +// longer available, picking an available model in the chat form must clear the submit +// button's error state. The form's selection always decides it. + +import ChatFormTestWrapper from './components/ChatFormTestWrapper.svelte'; +import { MessageRole, ServerRole } from '#lib/enums/index.ts'; +import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts'; +import { serverStore } from '#lib/stores/llama-server.svelte.ts'; +import { modelsStore } from '#lib/stores/models/index.svelte.ts'; +import type { DatabaseMessage, ModelOption } from '#lib/types/index.ts'; +import { tick } from 'svelte'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; + +const AVAILABLE: ModelOption = { + capabilities: [], + id: 'org/available:Q4_K_M', + model: 'org/available:Q4_K_M', + name: 'org/available:Q4_K_M' +}; +const GONE = 'org/gone:Q4_K_M'; + +function assistantMessage(model: string): DatabaseMessage { + return { + children: [], + content: 'Hello', + convId: 'c1', + id: 'm1', + model, + parent: null, + role: MessageRole.ASSISTANT, + timestamp: 0, + type: 'text' + } as DatabaseMessage; +} + +function sendButton(container: HTMLElement) { + const button = container.querySelector('button[type="submit"]'); + + if (!button) throw new Error('send button not rendered'); + + return button; +} + +const isErrorState = (button: HTMLButtonElement) => button.classList.contains('bg-surface-danger'); + +beforeEach(() => { + serverStore.role = ServerRole.ROUTER; + modelsStore.models = [AVAILABLE]; + modelsStore.clearSelection(); + conversationsStore.activeMessages = [assistantMessage(GONE)]; +}); + +afterEach(() => { + conversationsStore.activeMessages = []; + modelsStore.clearSelection(); + modelsStore.models = []; +}); + +describe('ChatForm model availability', () => { + it('shows the error state while the only model is the conversation one that is gone', async () => { + const { container } = render(ChatFormTestWrapper, { initialValue: 'Hi' }); + + await tick(); + + const button = sendButton(container); + + expect(isErrorState(button)).toBe(true); + expect(button.disabled).toBe(true); + }); + + it('clears the error state once an available model is selected in the form', async () => { + const { container } = render(ChatFormTestWrapper, { initialValue: 'Hi' }); + + await tick(); + await modelsStore.selectModelById(AVAILABLE.id); + await tick(); + + const button = sendButton(container); + + expect(isErrorState(button)).toBe(false); + expect(button.disabled).toBe(false); + }); +}); diff --git a/ui/apps/chat/tests/unit/chat-form-model-state.test.ts b/ui/apps/chat/tests/unit/chat-form-model-state.test.ts new file mode 100644 index 000000000000..ab8281206c66 --- /dev/null +++ b/ui/apps/chat/tests/unit/chat-form-model-state.test.ts @@ -0,0 +1,70 @@ +// Guards which model decides the chat form's submit state: the form's own selection +// always wins over the model of the conversation's last assistant message. + +import { getChatFormModelState } from '#lib/utils/model-selection.ts'; +import { describe, expect, it } from 'vitest'; + +const AVAILABLE = { id: 'org/available:Q4_K_M', model: 'org/available:Q4_K_M' }; +const GONE = 'org/gone:Q4_K_M'; + +describe('getChatFormModelState', () => { + it('reports an available model when the form selects one, even if the conversation used a gone model', () => { + expect( + getChatFormModelState({ + conversationModel: GONE, + isRouter: true, + models: [AVAILABLE], + selectedModelId: AVAILABLE.id + }) + ).toEqual({ hasModelSelected: true, isSelectedModelAvailable: true }); + }); + + it('reports an unavailable model when the form selects one that left the list', () => { + expect( + getChatFormModelState({ + conversationModel: AVAILABLE.model, + isRouter: true, + models: [AVAILABLE], + selectedModelId: GONE + }) + ).toEqual({ hasModelSelected: true, isSelectedModelAvailable: false }); + }); + + it('falls back to the conversation model when nothing is selected in the form', () => { + const state = (conversationModel: string) => + getChatFormModelState({ + conversationModel, + isRouter: true, + models: [AVAILABLE], + selectedModelId: null + }); + + expect(state(GONE)).toEqual({ hasModelSelected: true, isSelectedModelAvailable: false }); + expect(state(AVAILABLE.model)).toEqual({ + hasModelSelected: true, + isSelectedModelAvailable: true + }); + }); + + it('has no model selected on a router with neither a selection nor a conversation model', () => { + expect( + getChatFormModelState({ + conversationModel: null, + isRouter: true, + models: [AVAILABLE], + selectedModelId: null + }) + ).toEqual({ hasModelSelected: false, isSelectedModelAvailable: false }); + }); + + it('always has an available model outside router mode', () => { + expect( + getChatFormModelState({ + conversationModel: GONE, + isRouter: false, + models: [], + selectedModelId: null + }) + ).toEqual({ hasModelSelected: true, isSelectedModelAvailable: true }); + }); +}); From a6ac41c757c066941766164439f6876f2deaab04 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Tue, 24 Nov 2026 09:25:18 +0100 Subject: [PATCH 043/275] ui: match tool call timer font size to its title (#32922) Assisted-by: Claude (Opus 5.5 Medium) --- .../ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte index b83c74933036..9174148ac615 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte @@ -29,7 +29,7 @@ {label} From 82dd9704742e8514088914b61d61fbcd35d599ee Mon Sep 17 00:00:00 2001 From: Aircg <64237451+cgair@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:54:31 +0800 Subject: [PATCH 044/275] server : fix skipped prompt cache lookups (#28992) * server : fix skipped prompt cache lookups Assisted-by: Claude Opus 5 * server : let the slot scheduler ask the prompt cache Move the prompt cache lookup into server_slot_sched::select() so the plan alone decides whether the cache is updated, and the caller only applies it. find_better() and has_better() are now const, and find_better() also returns the common prefix, so load() no longer recomputes it. --------- Co-authored-by: Pascal --- tools/server/server-context.cpp | 2 +- tools/server/server-slot-sched.cpp | 49 ++++++++++++---- tools/server/server-slot-sched.h | 10 +++- tools/server/tests/unit/test_completion.py | 65 ++++++++++++++++++++++ 4 files changed, 113 insertions(+), 13 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 89f884e6548c..932d08bc71dd 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -2973,7 +2973,7 @@ struct server_context_impl { const int id_task = task.id; - const auto plan = slot_sched.select(get_slot_infos(), task, get_task_lora(task)); + const auto plan = slot_sched.select(get_slot_infos(), task, get_task_lora(task), prompt_cache.get()); server_slot * slot = plan.id_slot == -1 ? nullptr : get_slot_by_id(plan.id_slot); diff --git a/tools/server/server-slot-sched.cpp b/tools/server/server-slot-sched.cpp index fccfb709a6db..526a144c31a4 100644 --- a/tools/server/server-slot-sched.cpp +++ b/tools/server/server-slot-sched.cpp @@ -164,21 +164,21 @@ server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & pro return &states.back(); } -bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tokens_new, const std::vector & lora_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot) { +std::list::const_iterator server_prompt_cache::find_better(const server_prompt & prompt, const server_tokens & tokens_new, const std::vector & lora_new, int & lcp) const { // a prompt made with another lora config is cleared before the new one starts, so it counts as empty const bool is_empty = prompt.tokens.empty() || lora_should_clear_cache(prompt.lora, lora_new); - int lcp_best = is_empty ? 0 : prompt.tokens.get_common_prefix(tokens_new); + lcp = is_empty ? 0 : prompt.tokens.get_common_prefix(tokens_new); - float f_keep_best = is_empty ? -1.0f : float(lcp_best) / prompt.tokens.size(); // empty slot: any cache entry wins - float f_sim_best = float(lcp_best) / tokens_new.size(); + float f_keep_best = is_empty ? -1.0f : float(lcp) / prompt.tokens.size(); // empty slot: any cache entry wins + float f_sim_best = float(lcp) / tokens_new.size(); SRV_TRC(" - looking for better prompt, base f_keep = %.3f, f_sim = %.3f\n", f_keep_best, f_sim_best); - auto it_best = states.end(); + auto it_best = states.cend(); // find the most similar cached prompt, that would also preserve the most context - for (auto it = states.begin(); it != states.end(); ++it) { + for (auto it = states.cbegin(); it != states.cend(); ++it) { if (lora_should_clear_cache(it->prompt.lora, lora_new)) { SRV_TRC(" - prompt with length %7zu, skipping, other lora config\n", it->prompt.tokens.size()); continue; @@ -199,15 +199,34 @@ bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tok if (f_keep_best < f_keep_cur && f_sim_best < f_sim_cur) { f_keep_best = f_keep_cur; f_sim_best = f_sim_cur; - lcp_best = lcp_cur; + lcp = lcp_cur; it_best = it; } } - if (it_best != states.end()) { + if (it_best != states.cend()) { SRV_TRC(" - found better prompt with f_keep = %.3f, f_sim = %.3f\n", f_keep_best, f_sim_best); + } + + return it_best; +} + +bool server_prompt_cache::has_better(const server_prompt & prompt, const server_tokens & tokens_new, const std::vector & lora_new) const { + int lcp = 0; + + return find_better(prompt, tokens_new, lora_new, lcp) != states.cend(); +} + +bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tokens_new, const std::vector & lora_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot) { + int lcp_best = 0; + + const auto it_found = find_better(prompt, tokens_new, lora_new, lcp_best); + // an empty erase gives a mutable iterator to the same entry, its prompt is moved out below + const auto it_best = states.erase(it_found, it_found); + + if (it_best != states.end()) { const int64_t t_start = ggml_time_us(); { @@ -321,7 +340,7 @@ std::vector server_slot_sched::get_free_slots(const std::vector & slots, const server_task & task, const std::vector & lora) const { +server_slot_plan server_slot_sched::select(const std::vector & slots, const server_task & task, const std::vector & lora, const server_prompt_cache * prompt_cache) const { const server_slot_info * ret = nullptr; bool update_cache = false; @@ -392,7 +411,9 @@ server_slot_plan server_slot_sched::select(const std::vector & } if (ret != nullptr) { - const float f_keep = (f_sim_best*task.tokens.size()) / ret->prompt->tokens.size(); + // empty slot: nothing to keep, avoid 0/0 + const float f_keep = ret->prompt->tokens.size() > 0 ? + (f_sim_best*task.tokens.size()) / ret->prompt->tokens.size() : 0.0f; if (task.id_slot == -1) { SLT_INF(*ret, "selected slot by LCP similarity, f_sim_best = %.3f (> %.3f thold), f_keep = %.3f\n", @@ -424,7 +445,13 @@ server_slot_plan server_slot_sched::select(const std::vector & } // cache prompts only for the tasks that reuse them - update_cache = update_cache && !task.is_stateless(); + if (prompt_cache == nullptr || task.is_stateless()) { + return { ret->id, false }; + } + + // the checks above only tell if the outgoing state is worth saving + // the cache can still hold a better start for this task, so ask it + update_cache = update_cache || prompt_cache->has_better(*ret->prompt, task.tokens, lora); return { ret->id, update_cache }; } diff --git a/tools/server/server-slot-sched.h b/tools/server/server-slot-sched.h index fc0099dc04fa..f1be0fe2f54b 100644 --- a/tools/server/server-slot-sched.h +++ b/tools/server/server-slot-sched.h @@ -97,7 +97,14 @@ struct server_prompt_cache { server_prompt_cache_state * alloc(const server_prompt & prompt, size_t state_size_main, size_t state_size_drft); + // the cached state that is a better starting point than `prompt` for `tokens_new`, states.end() if none + // lcp: the common prefix of that state with `tokens_new` // lora_new: the lora config of the new prompt, the states made with another config are skipped + std::list::const_iterator find_better(const server_prompt & prompt, const server_tokens & tokens_new, const std::vector & lora_new, int & lcp) const; + + bool has_better(const server_prompt & prompt, const server_tokens & tokens_new, const std::vector & lora_new) const; + + // restore the result of find_better into the slot `id_slot` bool load(server_prompt & prompt, const server_tokens & tokens_new, const std::vector & lora_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot); void update(); @@ -130,5 +137,6 @@ struct server_slot_sched { std::vector get_free_slots(const std::vector & slots, size_t n_slots_needed, int exclude_id_slot) const; // lora: the lora config of the task - server_slot_plan select(const std::vector & slots, const server_task & task, const std::vector & lora) const; + // prompt_cache: nullptr if disabled + server_slot_plan select(const std::vector & slots, const server_task & task, const std::vector & lora, const server_prompt_cache * prompt_cache) const; }; diff --git a/tools/server/tests/unit/test_completion.py b/tools/server/tests/unit/test_completion.py index aa29454b1e49..1d58f9e2b21c 100644 --- a/tools/server/tests/unit/test_completion.py +++ b/tools/server/tests/unit/test_completion.py @@ -865,3 +865,68 @@ def assert_same_output(actual, expected): assert actual["timings"]["cache_n"] == len(prefix) + len(first["tokens"]) - 1 assert actual["timings"]["prompt_n"] == len(suffix) + 1 assert_same_output(actual, expected) + + +# the prompt cache has to be consulted even when the selected slot already holds a usable prefix, and even when the slot was picked by id +# ref: https://github.com/ggml-org/llama.cpp/issues/28139 +# ref: https://github.com/ggml-org/llama.cpp/issues/28276 +PROMPT_HEAD = "The capital of France is Paris. " * 2 +PROMPT_TAIL = "The river Seine runs slowly through the middle of the old stone city. " + +# PROMPT_SHORT is a strict prefix of PROMPT_LONG and covers more of it than the default --slot-prompt-similarity, so the slot is selected by the LCP loop +PROMPT_SHORT = PROMPT_HEAD + PROMPT_TAIL*6 +PROMPT_LONG = PROMPT_SHORT + PROMPT_TAIL*18 +PROMPT_OTHER = "Whiskers the cat climbed the tall oak tree behind the red barn. " * 12 + + +def prompt_cache_server(): + global server + server.n_slots = 2 + server.n_ctx = 2048 + server.n_batch = 512 + server.cache_ram = 512 + server.start() + + +def completion_cached(prompt: str, id_slot: int | None = None): + data = {"prompt": prompt, "cache_prompt": True, "n_predict": 0, "temperature": 0.0} + if id_slot is not None: + data["id_slot"] = id_slot + res = server.make_request("POST", "/completion", data=data) + assert res.status_code == 200 + return res.body["timings"]["prompt_n"], res.body["timings"]["cache_n"] + + +def test_prompt_cache_used_when_slot_pinned_by_id_is_empty(): + global server + prompt_cache_server() + + n_cold, _ = completion_cached(PROMPT_LONG, id_slot=0) + assert n_cold > 100 + + # push the state of slot 0 into the prompt cache + completion_cached(PROMPT_OTHER, id_slot=0) + + # slot 1 is empty, so f_keep has no meaning here - the cache still holds the exact state for this prompt and has to be used + n_pinned, n_cached = completion_cached(PROMPT_LONG, id_slot=1) + assert n_cached == n_cold - n_pinned + assert n_pinned < n_cold + + +def test_prompt_cache_used_when_slot_holds_a_shorter_prefix(): + global server + prompt_cache_server() + + # warm slot 1 before the long state reaches the cache, otherwise this request would consume the cached entry itself + n_short, _ = completion_cached(PROMPT_SHORT, id_slot=1) + + n_cold, _ = completion_cached(PROMPT_LONG, id_slot=0) + assert n_cold > n_short + + # push the long state of slot 0 into the prompt cache + completion_cached(PROMPT_OTHER, id_slot=0) + + # slot 1 holds a prefix of PROMPT_LONG and would be reused as is, but the cache holds the whole state and is the better start + n_reuse, n_cached = completion_cached(PROMPT_LONG, id_slot=1) + assert n_cached == n_cold - n_reuse + assert n_reuse < n_cold - n_short From 5fe49068594967a70b32deb3f9f401d7e4b7fedd Mon Sep 17 00:00:00 2001 From: Georgi Gerganov Date: Tue, 24 Nov 2026 12:11:19 +0200 Subject: [PATCH 045/275] ci : disable test-llama-context on ubuntu-llvmpipe (#32932) The dummy-model context sweep no longer fits within the job timeout on the llvmpipe runner. Exclude it from the ctest run there, keeping the coverage in the other jobs. Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB) --- .github/workflows/build-vulkan.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build-vulkan.yml b/.github/workflows/build-vulkan.yml index b699f2a1723c..3ad308583017 100644 --- a/.github/workflows/build-vulkan.yml +++ b/.github/workflows/build-vulkan.yml @@ -167,7 +167,8 @@ jobs: export GGML_VK_VISIBLE_DEVICES=0 export GGML_VK_DISABLE_F16=1 export GGML_VK_DISABLE_COOPMAT=1 - ctest -L main --verbose --timeout 900 + # TODO: too slow on llvmpipe + ctest -L main -E "test-llama-context" --verbose --timeout 900 windows: name: windows / ${{ matrix.arch }} From ae6a7ad2c5754dd8db93d04c84fda70435864f6e Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Tue, 24 Nov 2026 11:12:47 +0100 Subject: [PATCH 046/275] ui: move the agentic loop and trace phrasing into @ggml-org/llama-harness (#32927) * ui: add @ggml-org/llama-harness, the agentic loop as a package, in ui/lib/harness Llama Harness is the agentic loop as headless TypeScript with no UI, no DOM and no dependencies. It streams a turn, runs the tools the model called, gives it the results, and repeats until the model answers without a tool call. An app gives it an inference client and tools, and reads the run as a stream of events: run(messages, tools, signal). It ships a client for any OpenAI-compatible endpoint, so it also runs on its own in Node. The UI workflow type-checks, tests and packs it. Assisted-by: Claude (Fable 5.2) * ui: run Llama Chat's agentic loop through @ggml-org/llama-harness The loop leaves the agentic store, which now gives the harness what the app owns: ChatService as its inference client, the enabled tools behind the permission gate, and the callbacks that store each turn. Its API and the flow's callbacks are unchanged. A unit test runs the flow end to end with the server and the tools mocked. Chat compiles the harness from source through an alias, so the builds that copy or isolate ui/apps/chat now bring ui/lib/harness along: CMake and Nix through LLAMA_HARNESS_DIR, the Dockerfiles with a COPY. Assisted-by: Claude (Fable 5.2) * ui: bring the architecture docs in line with the ui/ folder The layout card no longer calls the move planned, the harness is in the pages, and they say that Llama Chat does not import @ggml-org/llama-ui yet. Assisted-by: Claude (Opus 5.5 Medium) * ui: phrase agent traces in @ggml-org/llama-harness The plain-language lines of an agent trace move out of Llama Chat into the harness, as a headless trace module any app on it can use: what one tool call did ("Read app.ts"), what it is doing now ("Running npm test", "Thinking"), what a run of calls did ("Ran 3 commands, read 2 files"), and how calls fold into one row with the reasoning around them. createTracePhraser knows llama-server's built-in tools. An app adds its own with resolvers and a phrasing table; any other tool reads as "Used " with its main argument, and a call with a description shows the model's own words. The lenient parse of streamed arguments and the targeted read of a path in a whole-file argument move with it. Llama Chat keeps its Svelte components and phrases only its own tools: the browser tools, web search and tool_search. Its functions keep their names and signatures, so nothing that renders a trace changes. Assisted-by: Claude (Opus 5.5 Medium) --- .devops/cann.Dockerfile | 3 +- .devops/cpu.Dockerfile | 3 +- .devops/cuda.Dockerfile | 3 +- .devops/intel.Dockerfile | 3 +- .devops/musa.Dockerfile | 3 +- .devops/nix/package.nix | 2 +- .devops/openvino.Dockerfile | 3 +- .devops/rocm.Dockerfile | 3 +- .devops/vulkan.Dockerfile | 3 +- .devops/zendnn.Dockerfile | 3 +- .github/workflows/ui-self-hosted.yml | 2 + .github/workflows/ui.yml | 31 + scripts/ui-assets.cmake | 13 +- ui/README.md | 21 +- ui/apps/chat/AGENTS.md | 2 +- ui/apps/chat/README.md | 21 +- ui/apps/chat/sources.cmake | 3 +- .../ChatMessageToolCallBlockDefault.svelte | 2 +- .../ChatMessageToolCall/ToolCallBlock.svelte | 13 +- .../ChatMessageToolCall/parsers/_shared.ts | 57 +- .../ChatMessageToolCall/parsers/edit-file.ts | 8 +- .../parsers/tool-call-phrasing.ts | 428 +----- .../ChatMessageToolCall/parsers/write-file.ts | 8 +- .../ChatMessages/ChatMessageAgentTrace.svelte | 9 +- .../src/lib/constants/settings.constants.ts | 2 +- .../lib/constants/tool-call-args.constants.ts | 8 - .../constants/tool-call-phrasing.constants.ts | 107 +- ui/apps/chat/src/lib/enums/agentic.enums.ts | 32 + ui/apps/chat/src/lib/enums/index.ts | 3 +- ui/apps/chat/src/lib/enums/tools.enums.ts | 13 - .../src/lib/stores/agentic/index.svelte.ts | 931 ++++++------ ui/apps/chat/src/lib/types/index.ts | 2 - ui/apps/chat/src/lib/types/tools.d.ts | 31 +- ui/apps/chat/src/lib/utils/async-queue.ts | 50 + ui/apps/chat/src/lib/utils/index.ts | 1 - .../src/lib/utils/parse-partial-json-args.ts | 124 -- ui/apps/chat/tests/unit/agentic-flow.test.ts | 373 +++++ .../chat/tests/unit/agentic-hotpath.bench.ts | 2 +- ui/apps/chat/tests/unit/async-queue.test.ts | 42 + .../tests/unit/tool-call-phrasing.test.ts | 8 +- ui/apps/chat/tsconfig.json | 3 +- ui/apps/chat/vite.config.ts | 6 +- ui/lib/harness/.gitignore | 6 + ui/lib/harness/.npmrc | 1 + ui/lib/harness/LICENSE | 21 + ui/lib/harness/README.md | 83 ++ ui/lib/harness/package-lock.json | 1255 +++++++++++++++++ ui/lib/harness/package.json | 39 + ui/lib/harness/src/abort.ts | 17 + ui/lib/harness/src/harness.ts | 375 +++++ ui/lib/harness/src/index.ts | 5 + ui/lib/harness/src/openai-client.ts | 143 ++ ui/lib/harness/src/trace/args.ts | 158 +++ ui/lib/harness/src/trace/index.ts | 33 + ui/lib/harness/src/trace/phrasing.ts | 497 +++++++ ui/lib/harness/src/trace/types.ts | 94 ++ ui/lib/harness/src/types.ts | 209 +++ ui/lib/harness/tests/harness.test.ts | 316 +++++ ui/lib/harness/tests/openai-client.test.ts | 130 ++ ui/lib/harness/tests/trace.test.ts | 123 ++ ui/lib/harness/tsconfig.build.json | 10 + ui/lib/harness/tsconfig.json | 13 + 62 files changed, 4584 insertions(+), 1329 deletions(-) create mode 100644 ui/apps/chat/src/lib/utils/async-queue.ts delete mode 100644 ui/apps/chat/src/lib/utils/parse-partial-json-args.ts create mode 100644 ui/apps/chat/tests/unit/agentic-flow.test.ts create mode 100644 ui/apps/chat/tests/unit/async-queue.test.ts create mode 100644 ui/lib/harness/.gitignore create mode 100644 ui/lib/harness/.npmrc create mode 100644 ui/lib/harness/LICENSE create mode 100644 ui/lib/harness/README.md create mode 100644 ui/lib/harness/package-lock.json create mode 100644 ui/lib/harness/package.json create mode 100644 ui/lib/harness/src/abort.ts create mode 100644 ui/lib/harness/src/harness.ts create mode 100644 ui/lib/harness/src/index.ts create mode 100644 ui/lib/harness/src/openai-client.ts create mode 100644 ui/lib/harness/src/trace/args.ts create mode 100644 ui/lib/harness/src/trace/index.ts create mode 100644 ui/lib/harness/src/trace/phrasing.ts create mode 100644 ui/lib/harness/src/trace/types.ts create mode 100644 ui/lib/harness/src/types.ts create mode 100644 ui/lib/harness/tests/harness.test.ts create mode 100644 ui/lib/harness/tests/openai-client.test.ts create mode 100644 ui/lib/harness/tests/trace.test.ts create mode 100644 ui/lib/harness/tsconfig.build.json create mode 100644 ui/lib/harness/tsconfig.json diff --git a/.devops/cann.Dockerfile b/.devops/cann.Dockerfile index 791b583ca6a5..83beced0add1 100644 --- a/.devops/cann.Dockerfile +++ b/.devops/cann.Dockerfile @@ -25,10 +25,11 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI and Llama Voice from their sources next to it +# the app compiles Llama UI, Llama Voice and the harness from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ +COPY ui/lib/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM ${CANN_BASE_IMAGE} AS build diff --git a/.devops/cpu.Dockerfile b/.devops/cpu.Dockerfile index f63e005ec930..fb3b5e9d9744 100644 --- a/.devops/cpu.Dockerfile +++ b/.devops/cpu.Dockerfile @@ -15,10 +15,11 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI and Llama Voice from their sources next to it +# the app compiles Llama UI, Llama Voice and the harness from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ +COPY ui/lib/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/ubuntu:$UBUNTU_VERSION AS build diff --git a/.devops/cuda.Dockerfile b/.devops/cuda.Dockerfile index cf1715d43a4c..058212e2c2a8 100644 --- a/.devops/cuda.Dockerfile +++ b/.devops/cuda.Dockerfile @@ -23,10 +23,11 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI and Llama Voice from their sources next to it +# the app compiles Llama UI, Llama Voice and the harness from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ +COPY ui/lib/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM ${BASE_CUDA_DEV_CONTAINER} AS build diff --git a/.devops/intel.Dockerfile b/.devops/intel.Dockerfile index 0783ef738c9f..5a4ddabe5796 100644 --- a/.devops/intel.Dockerfile +++ b/.devops/intel.Dockerfile @@ -17,10 +17,11 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI and Llama Voice from their sources next to it +# the app compiles Llama UI, Llama Voice and the harness from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ +COPY ui/lib/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/intel/deep-learning-essentials:$ONEAPI_VERSION AS build diff --git a/.devops/musa.Dockerfile b/.devops/musa.Dockerfile index 3ae62a676e4b..66568885590b 100644 --- a/.devops/musa.Dockerfile +++ b/.devops/musa.Dockerfile @@ -21,10 +21,11 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI and Llama Voice from their sources next to it +# the app compiles Llama UI, Llama Voice and the harness from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ +COPY ui/lib/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM ${BASE_MUSA_DEV_CONTAINER} AS build diff --git a/.devops/nix/package.nix b/.devops/nix/package.nix index 4ac844ff959d..887270fb23bd 100644 --- a/.devops/nix/package.nix +++ b/.devops/nix/package.nix @@ -182,7 +182,7 @@ effectiveStdenv.mkDerivation (finalAttrs: { webui = stdenvNoCC.mkDerivation { pname = "webui"; version = llamaVersion; - # the app compiles Llama UI from its source in ../../lib/ui, so the source is ui/ as a whole + # the app compiles Llama UI and the harness from their sources in ../../lib, so the source is ui/ as a whole src = lib.cleanSource ../../ui; sourceRoot = "source/apps/chat"; diff --git a/.devops/openvino.Dockerfile b/.devops/openvino.Dockerfile index fb8cb4c61f66..1509796dd225 100644 --- a/.devops/openvino.Dockerfile +++ b/.devops/openvino.Dockerfile @@ -34,10 +34,11 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI and Llama Voice from their sources next to it +# the app compiles Llama UI, Llama Voice and the harness from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ +COPY ui/lib/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build ## Build Image diff --git a/.devops/rocm.Dockerfile b/.devops/rocm.Dockerfile index ba9e85a0ed19..b7e5938d935a 100644 --- a/.devops/rocm.Dockerfile +++ b/.devops/rocm.Dockerfile @@ -23,10 +23,11 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI and Llama Voice from their sources next to it +# the app compiles Llama UI, Llama Voice and the harness from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ +COPY ui/lib/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build ### Build image diff --git a/.devops/vulkan.Dockerfile b/.devops/vulkan.Dockerfile index 023847628366..4e97422d6d07 100644 --- a/.devops/vulkan.Dockerfile +++ b/.devops/vulkan.Dockerfile @@ -15,10 +15,11 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI and Llama Voice from their sources next to it +# the app compiles Llama UI, Llama Voice and the harness from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ +COPY ui/lib/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/ubuntu:$UBUNTU_VERSION AS build diff --git a/.devops/zendnn.Dockerfile b/.devops/zendnn.Dockerfile index e49df81ca45f..da2fea2dfc58 100644 --- a/.devops/zendnn.Dockerfile +++ b/.devops/zendnn.Dockerfile @@ -15,10 +15,11 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI and Llama Voice from their sources next to it +# the app compiles Llama UI, Llama Voice and the harness from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ +COPY ui/lib/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/ubuntu:$UBUNTU_VERSION AS build diff --git a/.github/workflows/ui-self-hosted.yml b/.github/workflows/ui-self-hosted.yml index 4967de07ca21..f254f3b0c7d2 100644 --- a/.github/workflows/ui-self-hosted.yml +++ b/.github/workflows/ui-self-hosted.yml @@ -20,6 +20,7 @@ on: 'ui/apps/chat/**.*', 'ui/lib/ui/**.*', 'ui/lib/voice/**.*', + 'ui/lib/harness/**.*', 'tools/server/tests/**.*' ] pull_request: @@ -30,6 +31,7 @@ on: 'ui/apps/chat/**.*', 'ui/lib/ui/**.*', 'ui/lib/voice/**.*', + 'ui/lib/harness/**.*', 'tools/server/tests/**.*' ] diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml index 65e5c36ffdbf..bba032416bfb 100644 --- a/.github/workflows/ui.yml +++ b/.github/workflows/ui.yml @@ -181,6 +181,37 @@ jobs: run: npm run prepack working-directory: ui/lib/voice + harness-checks: + name: Harness checks + runs-on: ubuntu-24.04 + steps: + - name: Checkout code + uses: actions/checkout@v6 + with: + ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }} + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: "24" + package-manager-cache: false + + - name: Install dependencies + run: npm ci + working-directory: ui/lib/harness + + - name: Run type checking + run: npm run check + working-directory: ui/lib/harness + + - name: Run tests + run: npm test + working-directory: ui/lib/harness + + - name: Build the package + run: npm run prepack + working-directory: ui/lib/harness + e2e-tests: name: E2E Tests needs: ui-build diff --git a/scripts/ui-assets.cmake b/scripts/ui-assets.cmake index a3b4f16d7b68..8079c1c09651 100644 --- a/scripts/ui-assets.cmake +++ b/scripts/ui-assets.cmake @@ -21,11 +21,13 @@ set(DIST_DIR "${UI_BINARY_DIR}/dist") set(SRC_DIST_DIR "${UI_SOURCE_DIR}/dist") # The stage keeps the layout of ui/: the app in apps/chat, with the sources of # Llama UI that it compiles next to it in lib/ui (see ui/apps/chat/scripts/llama-ui.js), -# and those of Llama Voice in lib/voice (see ui/apps/chat/vite.config.ts). +# and those of Llama Voice and the harness in lib/voice and lib/harness (see +# ui/apps/chat/vite.config.ts). set(STAGE_DIR "${UI_BINARY_DIR}/ui-src") set(WORK_DIR "${STAGE_DIR}/apps/chat") set(UI_LIB_DIR "${UI_SOURCE_DIR}/../../lib/ui") set(UI_VOICE_DIR "${UI_SOURCE_DIR}/../../lib/voice") +set(HARNESS_DIR "${UI_SOURCE_DIR}/../../lib/harness") set(STAMP_FILE "${UI_BINARY_DIR}/.ui-stamp") set(EMBED_STAMP "${UI_BINARY_DIR}/.ui-embed.sha256") set(UI_CPP "${UI_BINARY_DIR}/ui.cpp") @@ -325,7 +327,7 @@ function(npm_build_should_skip out_var) endfunction() function(stage_sources) - # everything but the app goes: the library, restaged below, and what a stage + # everything but the app goes: the packages, restaged below, and what a stage # from before this layout left at the top, its node_modules included if(EXISTS "${STAGE_DIR}") file(GLOB staged RELATIVE "${STAGE_DIR}" "${STAGE_DIR}/*") @@ -349,7 +351,8 @@ function(stage_sources) PATTERN "node_modules" EXCLUDE ) - # what the app reads of the library: its sources and the dependency list + # what the app reads of the packages: Llama UI's sources and dependency list, + # and the harness's sources file(COPY "${UI_LIB_DIR}/package.json" DESTINATION "${STAGE_DIR}/lib/ui" NO_SOURCE_PERMISSIONS @@ -364,6 +367,10 @@ function(stage_sources) DESTINATION "${STAGE_DIR}/lib/voice" NO_SOURCE_PERMISSIONS ) + file(COPY "${HARNESS_DIR}/src" + DESTINATION "${STAGE_DIR}/lib/harness" + NO_SOURCE_PERMISSIONS + ) endfunction() function(npm_build out_var) diff --git a/ui/README.md b/ui/README.md index 0f210a40c80c..3d6521b58ac4 100644 --- a/ui/README.md +++ b/ui/README.md @@ -5,10 +5,11 @@ The UI of llama.cpp: the packages in `lib` and the apps built on them. ```text ui/ ├── lib/ -│ ├── ui/ @ggml-org/llama-ui: design tokens, fonts, surfaces and components -│ └── voice/ @ggml-org/llama-voice: microphone capture, transcription and dictation +│ ├── ui/ @ggml-org/llama-ui: design tokens, fonts, surfaces and components +│ ├── voice/ @ggml-org/llama-voice: microphone capture, transcription and dictation +│ └── harness/ @ggml-org/llama-harness: the agentic loop, headless └── apps/ - └── chat/ Llama Chat, the chat app that llama-server serves + └── chat/ Llama Chat, the chat app that llama-server serves ``` - [`lib/ui`](lib/ui/README.md) draws the parts and handles interaction, with no business logic. It is built with @@ -17,12 +18,18 @@ ui/ - [`lib/voice`](lib/voice/README.md) records the microphone and turns speech into text through llama-server, with no UI: Llama UI draws the voice parts. It is plain TypeScript built with `tsc`, plus a Svelte entry (`@ggml-org/llama-voice/svelte`). Apps in this repo compile its sources too. It is not published to npm yet. -- [`apps/chat`](apps/chat/README.md) talks to llama-server, stores conversations and runs the agentic loop. CMake - builds it into llama-server (see `scripts/ui-assets.cmake`), and it is published to npm as `@ggml-org/llama-chat` - (with `llama-chat` as its short name), so `npx llama-chat` runs it against any llama-server. +- [`lib/harness`](lib/harness/README.md) is the agentic loop: plain TypeScript with no UI and no dependencies. An app + gives it an inference client and tools, and reads its events. +- [`apps/chat`](apps/chat/README.md) talks to llama-server, stores conversations and runs the agentic loop through the + harness. CMake builds it into llama-server (see `scripts/ui-assets.cmake`), and it is published to npm as + `@ggml-org/llama-chat` (with `llama-chat` as its short name), so `npx llama-chat` runs it against any llama-server. Each folder is its own npm package with its own `package-lock.json`: run `npm ci` in the one you work on. Building, -checking and testing `apps/chat` needs no install in `lib/ui` or `lib/voice`. +checking and testing `apps/chat` needs no install in `lib/ui`, `lib/voice` or `lib/harness`. + +The split between library and app is not finished. Llama Chat takes its tokens, fonts, surfaces and base components +from `lib/ui`, but still has its own versions of what the library holds above those (ActionIcon, SearchInput, Logo, +SyntaxHighlightedCode and the Model UI), and `DESIGN.md`, `BRAND.md` and the full Storybook still sit beside the app. ## Releases diff --git a/ui/apps/chat/AGENTS.md b/ui/apps/chat/AGENTS.md index 32e6a009a2c9..0b4884de3167 100644 --- a/ui/apps/chat/AGENTS.md +++ b/ui/apps/chat/AGENTS.md @@ -1,6 +1,6 @@ # Instructions for ui/apps/chat -These add to the repository's [AGENTS.md](../../../AGENTS.md) for work in `ui/apps/chat`: **Llama Chat**, the chat client that llama-server bundles. **Llama UI**, the library, is `ui/lib/ui` (`@ggml-org/llama-ui`): Chat imports its tokens, fonts and base components from there (`@ggml-org/llama-ui/ui/`) and keeps no copy of them. `DESIGN.md` and the Storybook live here; the brand book, `BRAND.md`, and the brand and communications pages are in [ggml-org/llama-brand](https://github.com/ggml-org/llama-brand), with their own Storybook. +These add to the repository's [AGENTS.md](../../../AGENTS.md) for work in `ui/apps/chat`: **Llama Chat**, the chat client that llama-server bundles. **Llama UI**, the library, is `ui/lib/ui` (`@ggml-org/llama-ui`): Chat imports its tokens, fonts and base components from there (`@ggml-org/llama-ui/ui/`) and keeps no copy of them. `DESIGN.md` and the Storybook live here; the brand book, `BRAND.md`, and the brand and communications pages are in [ggml-org/llama-brand](https://github.com/ggml-org/llama-brand), with their own Storybook. The agentic loop is `ui/lib/harness` (`@ggml-org/llama-harness`). - **Design:** [DESIGN.md](DESIGN.md) holds the tokens, roles and rules, written for agents. Follow it for anything visual. Its token sections (`colors`, `typography`, `rounded`) are generated from the CSS with `npm run design:tokens`, and CI checks they are current; the rest is written by hand, and when it and the CSS disagree, the CSS wins and DESIGN.md is updated. - **Stories:** a story lives with the code it shows. Llama UI's (its foundations, base components, app components and Model UI) are in `ui/lib/ui/tests/stories`, titled `Llama UI/...`, and run as the library's tests; this app's Storybook shows them too. Llama Chat's are in `tests/stories/`, one folder per `src/lib/components/app/` (`chat/` has one per Chat folder), titled `Llama Chat//`. An accessibility story sits next to its component's, as `.a11y.stories.svelte`, titled `...//Accessibility`. The story helpers both Storybooks use (the Editorial the prose pages are set in, `StateGallery`) live with the library's stories and are imported here as `$llama-ui-stories/...`; reuse them rather than copying them here. diff --git a/ui/apps/chat/README.md b/ui/apps/chat/README.md index abee5d43bb0d..891fe6b2a422 100644 --- a/ui/apps/chat/README.md +++ b/ui/apps/chat/README.md @@ -84,16 +84,17 @@ Llama Chat is the first app on Llama UI, and the reference for the line between The app imports the library as `@ggml-org/llama-ui/ui/` and compiles its sources in its own build, with no install of the library (see `scripts/vite-plugin-llama-ui.ts`). Data flows one way, through these layers: -| Layer | Lives in | What it holds | -| -------------- | ------------------------- | --------------------------------------------------------------------------------------------------- | -| Routes | `src/routes` | `/`, `/chat/[id]`, `/models`, `/mcp-servers`, `/settings`, `/search` | -| App components | `src/lib/components/app` | Chat, navigation, models, MCP, settings and dialogs, grouped by area | -| UI components | `ui/lib/ui` | shadcn-svelte on bits-ui, from Llama UI | -| Voice | `ui/lib/voice` | Microphone capture, transcription and dictation, from Llama Voice (`@ggml-org/llama-voice`) | -| Hooks | `src/lib/hooks` | View logic between components and stores: scroll, drag and drop, pickers, keyboard | -| Stores | `src/lib/stores` | Application state as Svelte 5 runes: chat, conversations, the agentic loop, tools, models, settings | -| Services | `src/lib/services` | Stateless I/O: the llama-server API, IndexedDB, MCP, the Hugging Face Hub, the tool sandbox | -| Storage + API | the browser, llama-server | IndexedDB and localStorage; llama-server's `/v1`, `/props`, `/models`, `/tools`, `/slots` | +| Layer | Lives in | What it holds | +| -------------- | ------------------------- | ---------------------------------------------------------------------------------------------------- | +| Routes | `src/routes` | `/`, `/chat/[id]`, `/models`, `/mcp-servers`, `/settings`, `/search` | +| App components | `src/lib/components/app` | Chat, navigation, models, MCP, settings and dialogs, grouped by area | +| UI components | `ui/lib/ui` | shadcn-svelte on bits-ui, from Llama UI | +| Voice | `ui/lib/voice` | Microphone capture, transcription and dictation, from Llama Voice (`@ggml-org/llama-voice`) | +| Hooks | `src/lib/hooks` | View logic between components and stores: scroll, drag and drop, pickers, keyboard | +| Stores | `src/lib/stores` | Application state as Svelte 5 runes: chat, conversations, the agentic loop, tools, models, settings | +| Agentic loop | `ui/lib/harness` | Llama Harness: streams a turn, runs the tools the model called, repeats until it answers without one | +| Services | `src/lib/services` | Stateless I/O: the llama-server API, IndexedDB, MCP, the Hugging Face Hub, the tool sandbox | +| Storage + API | the browser, llama-server | IndexedDB and localStorage; llama-server's `/v1`, `/props`, `/models`, `/tools`, `/slots` | ```mermaid flowchart LR diff --git a/ui/apps/chat/sources.cmake b/ui/apps/chat/sources.cmake index d3daee6c9d37..f12daa8134c1 100644 --- a/ui/apps/chat/sources.cmake +++ b/ui/apps/chat/sources.cmake @@ -3,10 +3,11 @@ set(UI_SOURCE_GLOBS src/* static/* - # Llama UI, which the app compiles from source + # Llama UI and the harness, which the app compiles from source ../../lib/ui/src/lib/* # Llama Voice, also compiled from source ../../lib/voice/src/* + ../../lib/harness/src/* ) set(UI_SOURCE_FILES diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockDefault.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockDefault.svelte index 0cbe86535a22..9485dc8f11cf 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockDefault.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockDefault.svelte @@ -3,9 +3,9 @@ // Renders section.toolArgs / section.toolResult directly using the // shared chrome shell. - import { simpleToolArgFields } from './parsers/tool-call-phrasing'; import ToolCallBlock from './ToolCallBlock.svelte'; import ToolCallTitle from './ToolCallTitle.svelte'; + import { simpleToolArgFields } from '@ggml-org/llama-harness'; import { Loader2 } from '@lucide/svelte'; import { MarkdownContent, SyntaxHighlightedCode } from '#lib/components/app/index.ts'; import { MAX_HEIGHT_CODE_BLOCK } from '#lib/constants/index.ts'; diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte index f8f9ee05be45..2f45f9a37ca3 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte @@ -8,17 +8,18 @@ // Components supply only their `meta`, a title snippet, and a body // snippet - everything around them is this single source of truth. - import { - describeToolCall, - formatToolCallLine, - isToolCallRunning - } from './parsers/tool-call-phrasing'; + import { describeToolCall } from './parsers/tool-call-phrasing'; import { useToolCallElapsed } from './tool-call-elapsed'; import ToolCallElapsed from './ToolCallElapsed.svelte'; + import { + formatToolCallLine, + isToolCallRunning, + type ToolCallDescription + } from '@ggml-org/llama-harness'; import { CollapsibleContentBlock } from '#lib/components/app/index.ts'; import { AgenticSectionType } from '#lib/enums/index.ts'; import { settingsStore } from '#lib/stores/index.ts'; - import type { AgenticSection, ToolCallDescription } from '#lib/types/index.ts'; + import type { AgenticSection } from '#lib/types/index.ts'; import { imageExtras, toolCallShownArg } from '#lib/utils/index.ts'; import type { Snippet } from 'svelte'; import { fade } from 'svelte/transition'; diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/_shared.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/_shared.ts index e11a1fa4d336..122d70b540fb 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/_shared.ts +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/_shared.ts @@ -4,14 +4,10 @@ // args-present check, JSON parse), plus the same path aliases - keeping // them here lets each parser stay focused on its own format quirks. -import { - FILE_PATH_SEPARATOR_REGEX, - TOOL_ARG_PATH_KEYS, - TOOL_ARG_STRING_FIELD_PATTERN_TEMPLATE -} from '#lib/constants/index.ts'; +import { parsePartialJsonArgs } from '@ggml-org/llama-harness'; +import { TOOL_ARG_PATH_KEYS } from '#lib/constants/index.ts'; import { BuiltInTool } from '#lib/enums/index.ts'; import type { AgenticSection } from '#lib/types/agentic.js'; -import { parsePartialJsonArgs } from '#lib/utils/parse-partial-json-args.ts'; /** * Strict (final-state) JSON parser for a tool-args blob. Mirrors the @@ -33,55 +29,6 @@ function parseFinalToolArgs(blob: string): Record | null { } } -// Compiled per key on first use; the key set is tiny and fixed. -const toolArgStringRegexes = new Map(); - -/** - * Extract a string field from a JSON tool-args blob without parsing the - * whole document. write_file and edit_file args embed full file contents, - * yet the block title needs only the path; a targeted key match plus a - * JSON.parse of the captured string literal alone keeps title rendering - * O(path) instead of O(blob). Returns undefined when the key is missing - * or its value is not a string; callers fall back to the full parse. - */ -export function extractToolArgString( - toolArgs: string, - keys: readonly string[] -): string | undefined { - for (const key of keys) { - let pattern = toolArgStringRegexes.get(key); - - if (!pattern) { - pattern = new RegExp(TOOL_ARG_STRING_FIELD_PATTERN_TEMPLATE.replace('{key}', key)); - toolArgStringRegexes.set(key, pattern); - } - - const match = pattern.exec(toolArgs); - - if (!match) continue; - - try { - const value: unknown = JSON.parse(`"${match[1]}"`); - - if (typeof value === 'string') return value; - } catch { - // fall through to the next key; the full parse is the fallback - } - } - - return undefined; -} - -/** - * File name shown in a block title, from a tool-call path. Undefined when - * the call carries no path; the title then shows the tool label alone. - */ -export function fileNameFromPath(filePath: string | undefined): string | undefined { - if (!filePath) return undefined; - - return filePath.split(FILE_PATH_SEPARATOR_REGEX).pop() || filePath; -} - /** * Read the path argument out of an already parsed args object, checking * the aliases in `TOOL_ARG_PATH_KEYS`. Returns undefined when the call diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts index 72c1306a71af..d36979f82321 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts @@ -4,12 +4,8 @@ // `error` fields. The path is display-only (block title), so a call // that has not streamed one still shows its diffs. -import { - extractToolArgPath, - extractToolArgString, - fileNameFromPath, - parseToolArgs -} from './_shared'; +import { extractToolArgPath, parseToolArgs } from './_shared'; +import { extractToolArgString, fileNameFromPath } from '@ggml-org/llama-harness'; import { TOOL_ARG_PATH_KEYS } from '#lib/constants/index.ts'; import { BuiltInTool, DiffLineKind } from '#lib/enums/index.ts'; import type { diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts index 8792bc90aac4..91d864e60cf1 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts @@ -1,44 +1,24 @@ -// Plain-language lines for tool calls: what one call did ("Read a file -// sheet_new.jpg"), what it is doing now ("Reading package.json") and what -// a run of calls did ("Ran 3 commands, read 2 files"). A call that has the -// arg the settings pick (`description` by default) shows it as the model -// wrote it. Otherwise built-in tools use TOOL_CALL_PHRASING, and MCP and -// unknown tools read as "Used " with their main argument. +// Plain-language lines for the tool calls of a trace. The phrasing itself is +// Llama Harness's (`createTracePhraser`), which knows llama-server's built-in +// tools; this module adds Llama Chat's own: the browser tools, web search and +// tool_search. -import { extractToolArgString, fileNameFromPath } from './_shared'; import { - TOOL_ARG_PATH_KEYS, - TOOL_CALL_MAIN_ARG_KEYS, + createTracePhraser, + fileNameFromPath, + toolCallPath, + type ToolCallResolver +} from '@ggml-org/llama-harness'; +import { TOOL_CALL_PHRASING, - TOOL_CALL_SHOWN_ARG_DEFAULT, - TOOL_CALL_SIMPLE_ARG_MAX_CHARS, - TOOL_CALL_SUMMARY, - TOOL_CALL_TARGET_MAX_CHARS, - TOOL_CALL_THINKING_LABEL, TOOL_SEARCH_LOAD_PHRASING, TOOL_SEARCH_PHRASING_NAME, TOOL_SEARCH_PHRASING_SELECT_PREFIX, TOOL_SEARCH_QUERY_PHRASING, WEB_SEARCH_PHRASING } from '#lib/constants/index.ts'; -import { AgenticSectionType, BuiltInTool, ToolCallSummaryKind } from '#lib/enums/index.ts'; -import type { AgenticSection, ToolCallDescription, ToolCallPhrasing } from '#lib/types/index.ts'; -import { isWebSearchToolName, memoizeBounded, parsePartialJsonArgs } from '#lib/utils/index.ts'; - -/** How many results each cache below holds. */ -const CACHE_MAX_SIZE = 256; -/** Args longer than this ( whole files ) are not worth holding as cache keys. */ -const CACHE_MAX_ARGS_CHARS = 2000; - -type ToolArgField = { label: string; value: string }; - -function shorten(text: string): string { - const oneLine = text.replace(/\s+/g, ' ').trim(); - - return oneLine.length > TOOL_CALL_TARGET_MAX_CHARS - ? `${oneLine.slice(0, TOOL_CALL_TARGET_MAX_CHARS - 3)}...` - : oneLine; -} +import { BuiltInTool } from '#lib/enums/index.ts'; +import { isWebSearchToolName } from '#lib/utils/index.ts'; function stringArg(args: Record | null, key: string): string | undefined { const value = args?.[key]; @@ -46,92 +26,25 @@ function stringArg(args: Record | null, key: string): string | return typeof value === 'string' && value.trim() ? value : undefined; } -function genericMainArg(args: Record | null): string | undefined { - if (!args) return undefined; - - for (const key of TOOL_CALL_MAIN_ARG_KEYS) { - const value = stringArg(args, key); - - if (value) return value; - } - - for (const value of Object.values(args)) { - if (typeof value === 'number') return String(value); - - if (typeof value === 'string' && value.trim() && value.length <= TOOL_CALL_TARGET_MAX_CHARS) { - return value; - } - } - - return undefined; -} - -function genericPhrasing(toolName: string): ToolCallPhrasing { - return { - object: toolName, - past: 'Used', - present: 'Using', - summary: ToolCallSummaryKind.OTHER, - targetObject: toolName - }; -} - -interface ResolvedCall { - phrasing: ToolCallPhrasing; - target?: string; - count?: number; -} - -function resolveCall(toolName: string, toolArgs: string): ResolvedCall { - // write_file and edit_file args hold whole files: read the path with a - // targeted match instead of parsing the blob - if ( - toolName === BuiltInTool.SERVER_READ_FILE || - toolName === BuiltInTool.SERVER_WRITE_FILE || - toolName === BuiltInTool.SERVER_EDIT_FILE || - toolName === BuiltInTool.BROWSER_READ_MEDIA - ) { - const path = - extractToolArgString(toolArgs, TOOL_ARG_PATH_KEYS) ?? - stringArg(parsePartialJsonArgs(toolArgs), 'path'); - - return { phrasing: TOOL_CALL_PHRASING[toolName], target: fileNameFromPath(path) }; - } - - const args = toolArgs ? parsePartialJsonArgs(toolArgs) : null; - - if (toolName === BuiltInTool.SERVER_EXEC_SHELL_COMMAND) { - // the targeted match keeps the command in the line while a later arg - // is still streaming and the JSON does not parse - return { - phrasing: TOOL_CALL_PHRASING[toolName], - target: stringArg(args, 'command') ?? extractToolArgString(toolArgs, ['command']) - }; - } - - switch (toolName) { - case BuiltInTool.SERVER_GREP_SEARCH: - return { phrasing: TOOL_CALL_PHRASING[toolName], target: stringArg(args, 'pattern') }; - - case BuiltInTool.SERVER_FILE_GLOB_SEARCH: { - const include = stringArg(args, 'include'); - +const chatToolResolver: ToolCallResolver = (call) => { + switch (call.name) { + case BuiltInTool.BROWSER_READ_MEDIA: return { - phrasing: TOOL_CALL_PHRASING[toolName], - target: include && include !== '**' ? include : undefined + phrasing: TOOL_CALL_PHRASING[call.name], + target: fileNameFromPath(toolCallPath(call)) }; - } case BuiltInTool.BROWSER_SEARCH_CHATS: { - const matches = Array.isArray(args?.by_matches) - ? args.by_matches.filter((m): m is string => typeof m === 'string' && m.trim() !== '') + const byMatches = call.args()?.by_matches; + const matches = Array.isArray(byMatches) + ? byMatches.filter((m): m is string => typeof m === 'string' && m.trim() !== '') : []; - return { phrasing: TOOL_CALL_PHRASING[toolName], target: matches.join(', ') || undefined }; + return { phrasing: TOOL_CALL_PHRASING[call.name], target: matches.join(', ') || undefined }; } case TOOL_SEARCH_PHRASING_NAME: { - const query = stringArg(args, 'query')?.trim(); + const query = stringArg(call.args(), 'query')?.trim(); if (query?.startsWith(TOOL_SEARCH_PHRASING_SELECT_PREFIX)) { const names = query @@ -151,295 +64,14 @@ function resolveCall(toolName: string, toolArgs: string): ResolvedCall { } } - if (isWebSearchToolName(toolName)) { - return { phrasing: WEB_SEARCH_PHRASING, target: stringArg(args, 'query') }; - } - - const known = TOOL_CALL_PHRASING[toolName]; - - if (known) return { phrasing: known }; - - return { phrasing: genericPhrasing(toolName), target: genericMainArg(args) }; -} - -/** An arg name the settings can pick: a plain key, so it is safe in a pattern. */ -const SHOWN_ARG_PATTERN = /^[\w-]+$/; - -/** - * The value of the arg a call's line shows, when the call has it. Whole-file - * args are not parsed for it: the targeted match reads it instead. - */ -function shownArgValue(toolArgs: string, shownArg: string | null): string | undefined { - if (!shownArg || !toolArgs || !SHOWN_ARG_PATTERN.test(shownArg)) return undefined; - - const value = - toolArgs.length <= CACHE_MAX_ARGS_CHARS - ? stringArg(parsePartialJsonArgs(toolArgs), shownArg) - : extractToolArgString(toolArgs, [shownArg]); - - return value?.trim() || undefined; -} - -/** - * Describe one tool call as a short sentence, in the past tense once it is - * done and the present tense while `running`. `shownArg` names the arg - * shown instead when the call has it ( null for none ). - */ -export function describeToolCall( - toolName: string | undefined, - toolArgs: string | undefined, - running = false, - shownArg: string | null = TOOL_CALL_SHOWN_ARG_DEFAULT -): ToolCallDescription { - return describeCached(toolName || 'a tool', toolArgs ?? '', running, shownArg ?? ''); -} - -// Sections are rebuilt on every streamed chunk, so the same finished call is -// described again and again: remember the answer for its args. Every caller -// of one call reads the same frozen object, so a title cannot edit the line -// out for the others. -const describeCached = memoizeBounded( - (name: string, args: string, running: boolean, shownArg: string) => - Object.freeze(buildDescription(name, args, running, shownArg || null)), - (name, args, running, shownArg) => - args.length <= CACHE_MAX_ARGS_CHARS - ? `${running ? 1 : 0}\0${shownArg}\0${name}\0${args}` - : null, - CACHE_MAX_SIZE -); - -function buildDescription( - name: string, - args: string, - running: boolean, - shownArg: string | null -): ToolCallDescription { - const { count = 1, phrasing, target } = resolveCall(name, args); - const shown = shownArgValue(args, shownArg); - // an arg the row already shows as its target ( a shell command ) would - // only repeat it - const described = shown && shown !== target?.trim() ? shown : undefined; - - if (described) { - return { - count, - described: true, - // shown as the model wrote it: rewriting its tense by rule mangles - // anything that does not start with a plain verb - label: shorten(described).replace(/[.\s]+$/, ''), - quoted: false, - summary: phrasing.summary - }; - } - - const verb = running ? phrasing.present : phrasing.past; - const shortTarget = target ? shorten(target) : undefined; - const object = shortTarget ? phrasing.targetObject : phrasing.object; - - return { - count, - label: object ? `${verb} ${object}` : verb, - quoted: Boolean(phrasing.quoteTarget && shortTarget), - summary: phrasing.summary, - target: shortTarget - }; -} - -/** One line of plain text for a description, e.g. `Searched for 'issue'`. */ -export function formatToolCallLine(description: ToolCallDescription): string { - if (!description.target) return description.label; - - const target = description.quoted ? `'${description.target}'` : description.target; - - return `${description.label} ${target}`; -} - -export function isToolCallSection(section: AgenticSection): boolean { - return ( - section.type === AgenticSectionType.TOOL_CALL || - section.type === AgenticSectionType.TOOL_CALL_PENDING || - section.type === AgenticSectionType.TOOL_CALL_STREAMING - ); -} - -/** True while the call has no result yet and the reply is still streaming. */ -export function isToolCallRunning(section: AgenticSection, isStreaming: boolean): boolean { - return ( - isStreaming && - (section.type === AgenticSectionType.TOOL_CALL_PENDING || - section.type === AgenticSectionType.TOOL_CALL_STREAMING) - ); -} - -/** - * Summarize a run of tool calls, e.g. "Ran 3 commands, read 2 files". - * Kinds keep the order they first appear in; other tools come last. - */ -export function summarizeToolCalls(sections: readonly AgenticSection[]): string { - const counts = new Map(); - - for (const section of sections) { - if (!isToolCallSection(section)) continue; - - const { count, summary } = describeToolCall(section.toolName, section.toolArgs); - - counts.set(summary, (counts.get(summary) ?? 0) + count); - } - - const other = counts.get(ToolCallSummaryKind.OTHER); - - if (other !== undefined) { - counts.delete(ToolCallSummaryKind.OTHER); - counts.set(ToolCallSummaryKind.OTHER, other); - } - - const clauses = [...counts].map(([kind, n]) => TOOL_CALL_SUMMARY[kind](n)); - const text = clauses.join(', '); - - return text.charAt(0).toUpperCase() + text.slice(1); -} - -/** - * What a run of calls is doing now, in user words ("Running a command", - * "Thinking"): the model thinking at its end, or the last call still - * running; null when neither is. - */ -export function describeToolActivity( - sections: readonly AgenticSection[], - isStreaming: boolean, - executingToolCallId?: string | null, - shownArgFor: (toolName: string | undefined) => string | null = () => TOOL_CALL_SHOWN_ARG_DEFAULT -): string | null { - // the model thinking at the end of the run, between calls or before its answer - if (isStreaming && sections.at(-1)?.type === AgenticSectionType.REASONING_PENDING) { - return TOOL_CALL_THINKING_LABEL; - } - - for (let i = sections.length - 1; i >= 0; i--) { - const section = sections[i]; - const executing = - section.toolCallId !== undefined && section.toolCallId === executingToolCallId; - - if (executing || isToolCallRunning(section, isStreaming)) { - return formatToolCallLine( - describeToolCall(section.toolName, section.toolArgs, true, shownArgFor(section.toolName)) - ); - } - } - - return null; -} - -/** - * Tool args as labelled fields when every value is a short, one-line - * scalar; null when the args need the JSON view instead. Memoized like - * describeToolCall: the row that shows them re-renders on every chunk. - */ -export function simpleToolArgFields(toolArgs: string | undefined): ToolArgField[] | null { - return toolArgs ? argFieldsCached(toolArgs) : null; -} - -const argFieldsCached = memoizeBounded( - buildSimpleToolArgFields, - (toolArgs) => (toolArgs.length <= CACHE_MAX_ARGS_CHARS ? toolArgs : null), - CACHE_MAX_SIZE -); - -function buildSimpleToolArgFields(toolArgs: string): ToolArgField[] | null { - let parsed: unknown; - - try { - parsed = JSON.parse(toolArgs); - } catch { - return null; - } - - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null; - - const entries = Object.entries(parsed as Record); - - if (entries.length === 0) return null; - - const fields: ToolArgField[] = []; - - for (const [key, value] of entries) { - if (value !== null && typeof value === 'object') return null; - - const text = String(value); - - if (text.length > TOOL_CALL_SIMPLE_ARG_MAX_CHARS || text.includes('\n')) return null; - - fields.push({ label: humanizeArgKey(key), value: text }); + if (isWebSearchToolName(call.name)) { + return { phrasing: WEB_SEARCH_PHRASING, target: stringArg(call.args(), 'query') }; } - return fields; -} - -/** `max_results` / `maxResults` -> `Max results`. */ -export function humanizeArgKey(key: string): string { - const words = key - .replace(/([a-z0-9])([A-Z])/g, '$1 $2') - .replace(/[_-]+/g, ' ') - .trim() - .toLowerCase(); - - return words.charAt(0).toUpperCase() + words.slice(1); -} - -export function isReasoningSection(section: AgenticSection): boolean { - return ( - section.type === AgenticSectionType.REASONING || - section.type === AgenticSectionType.REASONING_PENDING - ); -} - -/** - * Split section positions into single items and runs of tool work, e.g. - * [0, [1, 2, 3], 4]. A run is the calls and all the reasoning around them, - * up to the next text, so the answer follows the work as one row: it is - * grouped once it holds `minCalls` calls, or one call with reasoning beside - * it. Reasoning with no call in reach, and text, stay apart. - */ -export function groupToolCallRuns( - sections: readonly AgenticSection[], - indices: readonly number[], - minCalls: number -): (number | number[])[] { - const items: (number | number[])[] = []; - - let run: number[] = []; - let calls = 0; - // reasoning seen since the last call: it ends the run if text follows, - // and leads into it if another call does - let thinking: number[] = []; - - const flush = () => { - const whole = [...run, ...thinking]; - - if (calls >= minCalls || (calls > 0 && whole.length > calls)) items.push(whole); - else items.push(...whole); - - run = []; - thinking = []; - calls = 0; - }; - - for (const index of indices) { - const section = sections[index]; - - if (isToolCallSection(section)) { - run.push(...thinking, index); - thinking = []; - calls++; - } else if (isReasoningSection(section)) { - thinking.push(index); - } else { - flush(); - items.push(index); - } - } - - flush(); + return undefined; +}; - return items; -} +export const { describeToolActivity, describeToolCall, summarizeToolCalls } = createTracePhraser({ + phrasings: TOOL_CALL_PHRASING, + resolvers: [chatToolResolver] +}); diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/write-file.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/write-file.ts index 3a88fb5f9f21..63557211c5c4 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/write-file.ts +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/write-file.ts @@ -4,12 +4,8 @@ // result blob. The path is display-only (title + highlight language), // so a call that has not streamed one still shows its content. -import { - extractToolArgPath, - extractToolArgString, - fileNameFromPath, - parseToolArgs -} from './_shared'; +import { extractToolArgPath, parseToolArgs } from './_shared'; +import { extractToolArgString, fileNameFromPath } from '@ggml-org/llama-harness'; import { CODE_BLOCK, TOOL_ARG_PATH_KEYS } from '#lib/constants/index.ts'; import { BuiltInTool } from '#lib/enums/index.ts'; import type { AgenticSection, WriteFileMeta, WriteFileTitleMeta } from '#lib/types/index.ts'; diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte index f0e7bffde8dd..988cb11d9afa 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte @@ -2,12 +2,9 @@ import ChatMessageToolCallBlock from './ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlock.svelte'; import ChatMessageToolCallGroup from './ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte'; import { parseExecShellCommandMeta } from './ChatMessage/ChatMessageToolCall/parsers/exec-shell-command'; - import { - groupToolCallRuns, - isToolCallSection - } from './ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing'; import { setToolCallElapsedContext } from './ChatMessage/ChatMessageToolCall/tool-call-elapsed'; import ChatMessageReasoningBlock from './ChatMessageReasoningBlock.svelte'; + import { groupToolCallRuns, isToolCallStep } from '@ggml-org/llama-harness'; import { ChatMessageActionCardContinueRequest, ChatMessageActionCardPermissionRequest, @@ -168,7 +165,7 @@ result.push(groupToolCallRuns(sections, indices, TOOL_CALL_GROUP_MIN_CALLS)); for (let i = 0; i < sections.length; i++) { - const isTool = isToolCallSection(sections[i]); + const isTool = isToolCallStep(sections[i]); // a turn ends where its tool calls do if (!isTool && prevWasTool && indices.length > 0) { @@ -202,7 +199,7 @@ return toolCallId ? { startedAt: taskStartedAt, toolCallId } : null; }); - const lastToolIndex = $derived(sections.findLastIndex((section) => isToolCallSection(section))); + const lastToolIndex = $derived(sections.findLastIndex((section) => isToolCallStep(section))); // The status row shows only while nothing else in the reply is moving: a // running row, a permission card or streaming text already says what is diff --git a/ui/apps/chat/src/lib/constants/settings.constants.ts b/ui/apps/chat/src/lib/constants/settings.constants.ts index 3109299c3feb..8182fb372575 100644 --- a/ui/apps/chat/src/lib/constants/settings.constants.ts +++ b/ui/apps/chat/src/lib/constants/settings.constants.ts @@ -4,9 +4,9 @@ import { COMPACTION } from './compaction.constants'; import { DEFAULT_MCP_CONFIG } from './mcp.constants'; import { SETTINGS_KEYS } from './settings-keys.constants'; import { TITLE_GENERATION } from './title-generation.constants'; -import { TOOL_CALL_SHOWN_ARG_DEFAULT } from './tool-call-phrasing.constants'; import { VOICE_TRANSCRIPTION_MODEL_AUTO } from './voice.constants'; import { FILE_GLOB_SEARCH_PICKERS } from './working-directory.constants'; +import { TOOL_CALL_SHOWN_ARG_DEFAULT } from '@ggml-org/llama-harness'; import { VOICE_MICROPHONE_AUTO } from '@ggml-org/llama-voice'; import AudioLines from '@lucide/svelte/icons/audio-lines'; import Code from '@lucide/svelte/icons/code'; diff --git a/ui/apps/chat/src/lib/constants/tool-call-args.constants.ts b/ui/apps/chat/src/lib/constants/tool-call-args.constants.ts index e74260be2993..47db87d725dc 100644 --- a/ui/apps/chat/src/lib/constants/tool-call-args.constants.ts +++ b/ui/apps/chat/src/lib/constants/tool-call-args.constants.ts @@ -13,11 +13,3 @@ export const JSON_OBJECT_OPEN = '{'; /** Opening character of a JSON array; successful sandbox output is one. */ export const JSON_ARRAY_OPEN = '['; - -/** - * Matches `"": ""` in a JSON args blob ( whitespace between - * tokens allowed ), capturing the raw string literal so only that literal - * gets decoded; escaped quotes stay inside the value group. `{key}` is - * replaced with the field name before use. - */ -export const TOOL_ARG_STRING_FIELD_PATTERN_TEMPLATE = '"{key}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"'; diff --git a/ui/apps/chat/src/lib/constants/tool-call-phrasing.constants.ts b/ui/apps/chat/src/lib/constants/tool-call-phrasing.constants.ts index e811ee243b48..66d73a119fd0 100644 --- a/ui/apps/chat/src/lib/constants/tool-call-phrasing.constants.ts +++ b/ui/apps/chat/src/lib/constants/tool-call-phrasing.constants.ts @@ -1,10 +1,9 @@ -// Plain-language phrasing for tool calls in the chat trace: the line each -// call reads as ("Read a file", "Searched for 'issue'"), the live -// description while it runs ("Reading package.json") and the counts in a -// group summary ("Ran 3 commands, read 2 files"). +// Phrasing of Llama Chat's own tools in the chat trace: the browser tools, web +// search and tool_search. Llama Harness phrases llama-server's built-in tools +// and any other tool (see createTracePhraser). -import { BuiltInTool, ToolCallSummaryKind } from '#lib/enums/index.ts'; -import type { ToolCallPhrasing } from '#lib/types/index.ts'; +import { type ToolCallPhrasing, ToolCallSummaryKind } from '@ggml-org/llama-harness'; +import { BuiltInTool } from '#lib/enums/index.ts'; /** * A tool that loads tools on demand, and the `select:` prefix its query uses @@ -14,37 +13,13 @@ import type { ToolCallPhrasing } from '#lib/types/index.ts'; export const TOOL_SEARCH_PHRASING_NAME = 'tool_search'; export const TOOL_SEARCH_PHRASING_SELECT_PREFIX = 'select:'; -/** Longest target shown after the verb before it is cut with "...". */ -export const TOOL_CALL_TARGET_MAX_CHARS = 60; - /** Fewest consecutive tool calls that collapse into one group row. */ export const TOOL_CALL_GROUP_MIN_CALLS = 2; -/** Live title of a tool group while the model thinks inside it. */ -export const TOOL_CALL_THINKING_LABEL = 'Thinking'; - /** Status shown while a reply waits on the server and no finer status is known. */ export const REPLY_STATUS_FALLBACK = 'Processing...'; -/** Args a generic (MCP or unknown) tool call is described by, first match wins. */ -export const TOOL_CALL_MAIN_ARG_KEYS: readonly string[] = [ - 'query', - 'q', - 'path', - 'file_path', - 'filePath', - 'url', - 'name', - 'command', - 'pattern', - 'prompt', - 'text', - 'id' -]; - -/** Args that count as "simple" stay below this length and on one line. */ -export const TOOL_CALL_SIMPLE_ARG_MAX_CHARS = 200; - +/** Llama Chat's browser tools; llama-server's tools are phrased by Llama Harness. */ export const TOOL_CALL_PHRASING: Readonly> = { // its own row reads "Current time is ...", so this entry serves group titles [BuiltInTool.BROWSER_GET_DATETIME]: { @@ -72,52 +47,6 @@ export const TOOL_CALL_PHRASING: Readonly> = { quoteTarget: true, summary: ToolCallSummaryKind.SEARCH, targetObject: 'chats for' - }, - [BuiltInTool.SERVER_EDIT_FILE]: { - object: 'a file', - past: 'Edited', - present: 'Editing', - summary: ToolCallSummaryKind.EDIT - }, - [BuiltInTool.SERVER_EXEC_SHELL_COMMAND]: { - object: 'a command', - past: 'Ran', - present: 'Running', - summary: ToolCallSummaryKind.COMMAND - }, - [BuiltInTool.SERVER_FILE_GLOB_SEARCH]: { - object: 'files', - past: 'Listed', - present: 'Listing', - quoteTarget: true, - summary: ToolCallSummaryKind.SEARCH, - targetObject: 'files matching' - }, - [BuiltInTool.SERVER_GET_INFO]: { - object: 'runtime info', - past: 'Checked', - present: 'Checking', - summary: ToolCallSummaryKind.OTHER - }, - [BuiltInTool.SERVER_GREP_SEARCH]: { - object: 'files', - past: 'Searched', - present: 'Searching', - quoteTarget: true, - summary: ToolCallSummaryKind.SEARCH, - targetObject: 'for' - }, - [BuiltInTool.SERVER_READ_FILE]: { - object: 'a file', - past: 'Read', - present: 'Reading', - summary: ToolCallSummaryKind.READ - }, - [BuiltInTool.SERVER_WRITE_FILE]: { - object: 'a file', - past: 'Wrote', - present: 'Writing', - summary: ToolCallSummaryKind.WRITE } }; @@ -147,29 +76,5 @@ export const WEB_SEARCH_PHRASING: ToolCallPhrasing = { targetObject: 'the web for' }; -function counted(n: number, singular: string, plural: string): string { - return `${n} ${n === 1 ? singular : plural}`; -} - -/** Group summary clause per kind, in lower case; the summary capitalizes the first one. */ -export const TOOL_CALL_SUMMARY: Readonly string>> = { - [ToolCallSummaryKind.COMMAND]: (n) => `ran ${counted(n, 'command', 'commands')}`, - [ToolCallSummaryKind.EDIT]: (n) => `edited ${counted(n, 'file', 'files')}`, - [ToolCallSummaryKind.LOAD_TOOLS]: (n) => `loaded ${counted(n, 'tool', 'tools')}`, - [ToolCallSummaryKind.OTHER]: (n) => `used ${counted(n, 'tool', 'tools')}`, - [ToolCallSummaryKind.READ]: (n) => `read ${counted(n, 'file', 'files')}`, - [ToolCallSummaryKind.SCRIPT]: (n) => `ran ${counted(n, 'script', 'scripts')}`, - [ToolCallSummaryKind.SEARCH]: (n) => (n === 1 ? 'searched once' : `searched ${n} times`), - [ToolCallSummaryKind.VIEW]: (n) => `viewed ${counted(n, 'media file', 'media files')}`, - [ToolCallSummaryKind.WRITE]: (n) => `wrote ${counted(n, 'file', 'files')}` -}; - -/** - * Arg a call's line shows by default when the call has it: tools that want a - * readable line declare it in their own schema, and the line reads it as the - * model wrote it. Settings can pick another arg, globally or per tool. - */ -export const TOOL_CALL_SHOWN_ARG_DEFAULT = 'description'; - /** Per-tool choice that turns the shown arg off and keeps the sentence. */ export const TOOL_CALL_SHOWN_ARG_NONE = ''; diff --git a/ui/apps/chat/src/lib/enums/agentic.enums.ts b/ui/apps/chat/src/lib/enums/agentic.enums.ts index 6dc46b0850ac..31f72bafd992 100644 --- a/ui/apps/chat/src/lib/enums/agentic.enums.ts +++ b/ui/apps/chat/src/lib/enums/agentic.enums.ts @@ -43,3 +43,35 @@ export enum DiffLineKind { CONTEXT = 'context', REMOVE = 'remove' } + +/** + * Events of a harness run. The values mirror `HarnessEvent` of `@ggml-org/llama-harness`. + */ +export enum HarnessEventType { + COMPLETION_ID = 'completion_id', + DONE = 'done', + ERROR = 'error', + MESSAGE = 'message', + MODEL = 'model', + REASONING = 'reasoning', + TEXT = 'text', + TIMINGS = 'timings', + TOOL_CALL = 'tool_call', + TOOL_CALL_DELTA = 'tool_call_delta', + TOOL_RESULT = 'tool_result', + TOOL_UPDATE = 'tool_update', + TURN_END = 'turn_end', + TURN_START = 'turn_start' +} + +/** + * Events of one streamed completion. The values mirror `InferenceEvent` of `@ggml-org/llama-harness`. + */ +export enum InferenceEventType { + COMPLETION_ID = 'completion_id', + MODEL = 'model', + REASONING = 'reasoning', + TEXT = 'text', + TIMINGS = 'timings', + TOOL_CALLS = 'tool_calls' +} diff --git a/ui/apps/chat/src/lib/enums/index.ts b/ui/apps/chat/src/lib/enums/index.ts index 9fb53f8af05c..510e3d18fb7a 100644 --- a/ui/apps/chat/src/lib/enums/index.ts +++ b/ui/apps/chat/src/lib/enums/index.ts @@ -10,6 +10,8 @@ export { AgenticSectionType, ContinueIntentKind, DiffLineKind, + HarnessEventType, + InferenceEventType, ToolResultKind, ToolCallType } from './agentic.enums'; @@ -116,7 +118,6 @@ export { GlobSearchType, SearchChatsMessageSelection, SearchChatsOrder, - ToolCallSummaryKind, ToolSource, ToolPermissionDecision, ToolResponseField diff --git a/ui/apps/chat/src/lib/enums/tools.enums.ts b/ui/apps/chat/src/lib/enums/tools.enums.ts index 5049be5cb790..2bda6872284b 100644 --- a/ui/apps/chat/src/lib/enums/tools.enums.ts +++ b/ui/apps/chat/src/lib/enums/tools.enums.ts @@ -67,16 +67,3 @@ export enum SearchChatsOrder { ASC = 'asc', DESC = 'desc' } - -/** Bucket a tool call counts in for a tool-call group's summary line. */ -export enum ToolCallSummaryKind { - COMMAND = 'command', - EDIT = 'edit', - LOAD_TOOLS = 'load_tools', - OTHER = 'other', - READ = 'read', - SCRIPT = 'script', - SEARCH = 'search', - VIEW = 'view', - WRITE = 'write' -} diff --git a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts index b4e0fa335179..602d49bfb367 100644 --- a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts +++ b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts @@ -1,15 +1,26 @@ /** - * AgenticStore - Multi-turn agentic loop orchestration + * AgenticStore - Llama Chat's side of the agentic loop * - * Drives the agentic loop over MCP tools: streams each LLM turn, detects - * tool calls, executes them via mcpStore, and enforces the turn limit. Each - * turn produces one assistant message (with tool_calls) and one tool result - * message per executed call, persisted as separate DB rows. + * The loop itself is `@ggml-org/llama-harness`: it streams each LLM turn, runs + * the tool calls and enforces the turn limit. This store gives it what the + * app owns: ChatService as its inference client, the enabled tools behind + * the permission gate, and the callbacks that persist each turn as one + * assistant message (with tool_calls) and one tool result message per call. * - * Uses ChatService for streaming and mcpStore for tool execution; waits on - * the permission/continue/steering gates owned by {@link AgenticGates}. + * Waits on the permission/continue/steering gates owned by {@link AgenticGates}. */ +import { + type ContentPart, + createHarness, + type InferenceClient, + type InferenceEvent, + type Message, + type Tool, + type ToolCall, + type ToolContext, + type ToolResult +} from '@ggml-org/llama-harness'; import { DEFAULT_AGENTIC_CONFIG, NEWLINE } from '#lib/constants/index.ts'; import { AUDIO_MIME_TO_EXTENSION, @@ -24,6 +35,8 @@ import { BuiltInTool, ToolPermissionDecision, ToolSource } from '#lib/enums/inde import { AttachmentType, ContentPartType, + HarnessEventType, + InferenceEventType, MessageRole, MimeTypePrefix, ToolCallType @@ -44,25 +57,13 @@ import type { AgenticFlowCallbacks, AgenticFlowOptions, AgenticMessage, - AgenticToolCallList, AgenticToolPolicy, PendingPermissionRequest, SteeringMessage } from '#lib/types/agentic.js'; +import type { ApiChatMessageData } from '#lib/types/api.js'; +import type { ChatMessagePromptProgress, ChatMessageTimings } from '#lib/types/chat.js'; import type { - ApiChatCompletionToolCall, - ApiChatMessageContentPart, - ApiChatMessageData -} from '#lib/types/api.js'; -import type { - ChatMessageAgenticTimings, - ChatMessageAgenticTurnStats, - ChatMessagePromptProgress, - ChatMessageTimings, - ChatMessageToolCallTiming -} from '#lib/types/chat.js'; -import type { - DatabaseMessage, DatabaseMessageExtra, DatabaseMessageExtraAudioFile, DatabaseMessageExtraImageFile @@ -77,11 +78,13 @@ import type { ToolExecutionResult } from '#lib/types/index.ts'; import type { OpenAIToolDefinition } from '#lib/types/mcp.js'; +import { createAsyncQueue } from '#lib/utils/async-queue.ts'; import { executeBrowserInfoTool, executeGetDatetimeTool, getAudioInputFormat, - isAbortError + isAbortError, + throwIfAborted } from '#lib/utils/index.ts'; import { SvelteMap } from 'svelte/reactivity'; @@ -145,9 +148,14 @@ function toAgenticMessages(messages: ApiChatMessageData[]): AgenticMessage[] { }); } +/** The timings with the task's wall time since `startedAt` on its run totals, when it has them. */ +function withTotalTime(timings: T, startedAt: number): T { + if (!timings?.agentic) return timings; + + return { ...timings, agentic: { ...timings.agentic, totalMs: Date.now() - startedAt } }; +} + class AgenticStore { - /** When each running flow started, keyed by its timings object; see buildFinalTimings */ - private flowStarts = new WeakMap(); // permission, continue and steering gates the loop waits on between turns private gates = new AgenticGates(); private sessions = new SvelteMap(); @@ -416,27 +424,142 @@ class AgenticStore { return `${MCP_ATTACHMENT_NAME_PREFIX}-${Date.now()}-${index}.${extension}`; } - private buildFinalTimings( - capturedTimings: ChatMessageTimings | undefined, - agenticTimings: ChatMessageAgenticTimings - ): ChatMessageTimings | undefined { - if (agenticTimings.toolCallsCount === 0) return capturedTimings; + /** + * The media of a tool result as content parts, only what the model can read. + */ + private buildContentParts( + attachments: DatabaseMessageExtra[], + effectiveModel: string + ): ContentPart[] { + const contentParts: ContentPart[] = []; + + for (const attachment of attachments) { + if (attachment.type === AttachmentType.AUDIO) { + if (modelsStore.props.modelSupportsAudio(effectiveModel)) { + contentParts.push({ + input_audio: { + data: (attachment as DatabaseMessageExtraAudioFile).base64Data, + format: getAudioInputFormat((attachment as DatabaseMessageExtraAudioFile).mimeType) + }, + type: ContentPartType.INPUT_AUDIO + }); + } + } else if (attachment.type === AttachmentType.IMAGE) { + if (modelsStore.props.modelSupportsVision(effectiveModel)) { + contentParts.push({ + image_url: { + url: (attachment as DatabaseMessageExtraImageFile).base64Url + }, + type: ContentPartType.IMAGE_URL + }); + } else { + console.info( + `[AgenticStore] Skipping image attachment (model "${effectiveModel}" does not support vision)` + ); + } + } + } - const startedAt = this.flowStarts.get(agenticTimings); + return contentParts; + } - return { - agentic: - startedAt === undefined - ? agenticTimings - : { ...agenticTimings, totalMs: Date.now() - startedAt }, - cache_n: capturedTimings?.cache_n, - predicted_ms: capturedTimings?.predicted_ms, - predicted_n: capturedTimings?.predicted_n, - prompt_ms: capturedTimings?.prompt_ms, - prompt_n: capturedTimings?.prompt_n + /** + * Run a tool call where its source runs it: on llama-server, in the + * browser or on an MCP server. Throws when the call fails. + */ + private async dispatchTool(params: { + callbacks: AgenticFlowCallbacks; + context: ToolContext; + conversationId: string; + effectiveModel: string; + toolCall: ToolCall; + }): Promise { + const { callbacks, context, conversationId, effectiveModel, toolCall } = params; + const { signal } = context; + const toolName = toolCall.function.name; + const toolSource = toolsStore.getToolSource(toolName); + + if ( + toolSource === ToolSource.SERVER && + toolName === BuiltInTool.SERVER_EXEC_SHELL_COMMAND && + callbacks.createToolResultMessage && + callbacks.updateToolResultMessage + ) { + const args = this.parseToolArguments(toolCall.function.arguments); + const cwd = conversationsStore.activeConversation?.cwd; + + // the first update creates the result message, so the output shows live + context.update(''); + + let accumulated = ''; + let isError = false; + + for await (const ev of ToolsService.streamTool(toolName, args, signal, cwd)) { + if (ev.chunk !== null) { + accumulated += ev.chunk; + context.update(accumulated); + } + + if (ev.done) { + if (ev.error) { + accumulated = accumulated ? `${accumulated}\nError: ${ev.error}` : `Error: ${ev.error}`; + context.update(accumulated); + isError = true; + } + + break; + } + } + + return { content: accumulated, isError }; + } + + if (toolSource === ToolSource.SERVER) { + const args = this.parseToolArguments(toolCall.function.arguments); + const cwd = conversationsStore.activeConversation?.cwd; + + return ToolsService.executeTool(toolName, args, signal, cwd); + } + + if (toolSource === ToolSource.BROWSER) { + const args = this.parseToolArguments(toolCall.function.arguments); + + if (toolName === BuiltInTool.BROWSER_GET_DATETIME) return executeGetDatetimeTool(); + + if (toolName === BuiltInTool.SERVER_GET_INFO) return executeBrowserInfoTool(); + + if (toolName === BuiltInTool.BROWSER_SEARCH_CHATS) { + return SearchChatsService.executeTool(args, conversationId); + } + + if (toolName === BuiltInTool.BROWSER_READ_MEDIA) { + return ReadMediaService.executeTool( + args, + { + audio: modelsStore.props.modelSupportsAudio(effectiveModel), + vision: modelsStore.props.modelSupportsVision(effectiveModel) + }, + signal, + conversationsStore.activeConversation?.cwd + ); + } + + return SandboxService.executeTool(toolName, args, signal); + } + + const mcpCall: MCPToolCall = { + function: { arguments: toolCall.function.arguments, name: toolName }, + id: toolCall.id }; + const executionResult = await mcpStore.executeTool(mcpCall, signal); + + return { content: executionResult.content, isError: false }; } + /** + * Run the harness and turn its events into the flow's callbacks and the + * session state the UI reads. + */ private async executeAgenticLoop(params: { conversationId: string; messages: ApiChatMessageData[]; @@ -462,551 +585,255 @@ class AgenticStore { onTurnComplete, updateToolResultMessage } = callbacks; - const sessionMessages: AgenticMessage[] = toAgenticMessages(messages); - - let capturedTimings: ChatMessageTimings | undefined; - let totalToolCallCount = 0; - - const agenticTimings: ChatMessageAgenticTimings = { - llm: { predicted_ms: 0, predicted_n: 0, prompt_ms: 0, prompt_n: 0 }, - perTurn: [], - toolCalls: [], - toolCallsCount: 0, - toolsMs: 0, - turns: 0 - }; - - // the run's start travels with its timings, so every exit of the loop - // stamps the total task time without being handed it - this.flowStarts.set(agenticTimings, this.sessions.get(conversationId)?.startedAt ?? Date.now()); - - const maxTurns = agenticConfig.maxTurns; + // the task's wall time, waits included, is stamped on every timings the run reports + const startedAt = this.sessions.get(conversationId)?.startedAt ?? Date.now(); const effectiveModel = options.model || modelsStore.models[0]?.model || ''; - - let turn = 0; - - while (true) { - if (turn >= maxTurns) { + const harness = createHarness(this.inferenceClient(options, conversationId)); + const harnessTools: Tool[] = tools.map((definition) => ({ + definition, + execute: (toolCall, context) => + this.executeTool({ callbacks, context, conversationId, effectiveModel, toolCall }) + })); + // result messages of streaming tools, created while the tool runs, by tool call id + const streamedResults = new SvelteMap(); + const events = harness.run(toAgenticMessages(messages) as Message[], harnessTools, signal, { + interrupted: () => this.gates.hasPendingSteeringMessage(conversationId), + maxTurns: agenticConfig.maxTurns, + onTurnLimit: async () => { // Turn limit reached - ask user whether to continue const shouldContinue = await this.gates.requestContinue(conversationId, signal); // Yield to allow Svelte to flush the UI update await new Promise((r) => setTimeout(r, 0)); - if (!shouldContinue || signal?.aborted) { - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); - - return; - } - - // User chose to continue - extend the limit - turn = 0; - } - - this.updateSession(conversationId, { currentTurn: turn + 1 }); - agenticTimings.turns = turn + 1; - - if (signal?.aborted) { - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); - - return; - } - - // For turns > 0, create a new assistant message via callback - if (turn > 0 && createAssistantMessage) { - await createAssistantMessage(); + return shouldContinue; } + }); - let turnContent = ''; - let turnReasoningContent = ''; - let turnToolCalls: ApiChatCompletionToolCall[] = []; - let lastStreamingToolCallName = ''; - let lastStreamingToolCallArgsLength = 0; - let turnTimings: ChatMessageTimings | undefined; - - const turnStats: ChatMessageAgenticTurnStats = { - llm: { predicted_ms: 0, predicted_n: 0, prompt_ms: 0, prompt_n: 0 }, - toolCalls: [], - toolsMs: 0, - turn: turn + 1 - }; - - try { - await ChatService.sendMessage( - sessionMessages as ApiChatMessageData[], - { - ...options, - onChunk: (chunk: string) => { - turnContent += chunk; - onChunk?.(chunk); - }, - onComplete: () => { - /* Completion handled after sendMessage resolves */ - }, - onCompletionId, - onError: (error: Error) => { - throw error; - }, - onModel, - onReasoningChunk: (chunk: string) => { - turnReasoningContent += chunk; - onReasoningChunk?.(chunk); - }, - onTimings: (timings?: ChatMessageTimings, progress?: ChatMessagePromptProgress) => { - onTimings?.(timings, progress); - - if (timings) { - capturedTimings = timings; - turnTimings = timings; - - // completed turns + in-flight turn live counts - this.updateSession(conversationId, { - liveLlm: { - predicted_ms: agenticTimings.llm.predicted_ms + (timings.predicted_ms ?? 0), - predicted_n: agenticTimings.llm.predicted_n + (timings.predicted_n ?? 0), - prompt_ms: agenticTimings.llm.prompt_ms + (timings.prompt_ms ?? 0), - prompt_n: agenticTimings.llm.prompt_n + (timings.prompt_n ?? 0) - } - }); - } - }, - onToolCallChunk: (serialized: string) => { - try { - turnToolCalls = JSON.parse(serialized) as ApiChatCompletionToolCall[]; - - onToolCallsStreaming?.(turnToolCalls); - - if (turnToolCalls.length > 0 && turnToolCalls[0]?.function) { - const name = turnToolCalls[0].function.name || ''; - const args = turnToolCalls[0].function.arguments || ''; - const argsLengthBucket = Math.floor(args.length / 100); - - if ( - name !== lastStreamingToolCallName || - argsLengthBucket !== lastStreamingToolCallArgsLength - ) { - lastStreamingToolCallName = name; - lastStreamingToolCallArgsLength = argsLengthBucket; - this.updateSession(conversationId, { - streamingToolCall: { arguments: args, name } - }); - } - } - } catch { - /* Ignore parse errors during streaming */ - } - }, - stream: true, - tools: tools.length > 0 ? tools : undefined - }, - conversationId, - signal - ); - - this.updateSession(conversationId, { streamingToolCall: null }); - - if (turnTimings) { - agenticTimings.llm.predicted_n += turnTimings.predicted_n || 0; - agenticTimings.llm.predicted_ms += turnTimings.predicted_ms || 0; - agenticTimings.llm.prompt_n += turnTimings.prompt_n || 0; - agenticTimings.llm.prompt_ms += turnTimings.prompt_ms || 0; - turnStats.llm.predicted_n = turnTimings.predicted_n || 0; - turnStats.llm.predicted_ms = turnTimings.predicted_ms || 0; - turnStats.llm.prompt_n = turnTimings.prompt_n || 0; - turnStats.llm.prompt_ms = turnTimings.prompt_ms || 0; - } - } catch (error) { - if (signal?.aborted) { - // Save whatever we have for this turn before exiting - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - this.buildFinalTimings(capturedTimings, agenticTimings), - undefined - ); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); + let totalToolCallCount = 0; + let lastStreamingToolCallName = ''; + let lastStreamingToolCallArgsLength = 0; - return; - } + for await (const event of events) { + switch (event.type) { + case HarnessEventType.TURN_START: + this.updateSession(conversationId, { currentTurn: event.turn }); + lastStreamingToolCallName = ''; + lastStreamingToolCallArgsLength = 0; - const normalizedError = error instanceof Error ? error : new Error('LLM stream error'); + // the caller created the first turn's assistant message + if (event.turn > 1 && createAssistantMessage) await createAssistantMessage(); - // preserve partial output as is, the outer error dialog informs the user separately - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - this.buildFinalTimings(capturedTimings, agenticTimings), - undefined - ); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); + break; - throw normalizedError; - } + case HarnessEventType.TEXT: + onChunk?.(event.delta); - // If the abort landed while ChatService.sendMessage was still resolving, the - // outer catch above never fires because ChatService swallows the AbortError - // and returns normally. Bail out here so a half-received tool_call (truncated - // arguments JSON) is not persisted as if it were complete. - if (signal?.aborted) { - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - this.buildFinalTimings(capturedTimings, agenticTimings), - undefined - ); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); + break; - return; - } + case HarnessEventType.REASONING: + onReasoningChunk?.(event.delta); - // === Steering check: if a user message was queued during this turn, exit the flow. - // The caller (chatStore) will consume the pending message and re-send it normally. - if (this.gates.hasPendingSteeringMessage(conversationId)) { - console.log('[AgenticStore] Steering message detected after turn, exiting agentic flow'); - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - this.buildFinalTimings(capturedTimings, agenticTimings), - turnToolCalls.length > 0 ? this.normalizeToolCalls(turnToolCalls) : undefined - ); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); + break; - return; - } + case HarnessEventType.TOOL_CALL_DELTA: { + onToolCallsStreaming?.(event.toolCalls); - // No tool calls = final turn, save and complete - if (turnToolCalls.length === 0) { - agenticTimings.perTurn!.push(turnStats); + const streamingCall = event.toolCalls[0]?.function; - const finalTimings = this.buildFinalTimings(capturedTimings, agenticTimings); + if (streamingCall) { + const name = streamingCall.name || ''; + const args = streamingCall.arguments || ''; + const argsLengthBucket = Math.floor(args.length / 100); - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - finalTimings, - undefined - ); + if ( + name !== lastStreamingToolCallName || + argsLengthBucket !== lastStreamingToolCallArgsLength + ) { + lastStreamingToolCallName = name; + lastStreamingToolCallArgsLength = argsLengthBucket; + this.updateSession(conversationId, { + streamingToolCall: { arguments: args, name } + }); + } + } - if (finalTimings) onTurnComplete?.(finalTimings); + break; + } - onFlowComplete?.(finalTimings); + case HarnessEventType.TIMINGS: + onTimings?.(event.timings, event.progress); - return; - } + // completed turns + in-flight turn live counts + if (event.llm) this.updateSession(conversationId, { liveLlm: event.llm }); - // Normalize and save assistant turn with tool calls - const normalizedCalls = this.normalizeToolCalls(turnToolCalls); + break; - if (normalizedCalls.length === 0) { - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - this.buildFinalTimings(capturedTimings, agenticTimings), - undefined - ); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); + case HarnessEventType.MODEL: + onModel?.(event.model); - return; - } + break; - totalToolCallCount += normalizedCalls.length; - this.updateSession(conversationId, { totalToolCalls: totalToolCallCount }); - - // Save the assistant message with its tool calls - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - turnTimings, - normalizedCalls - ); - - // Add assistant message to session history - sessionMessages.push({ - content: turnContent || undefined, - reasoning_content: turnReasoningContent || undefined, - role: MessageRole.ASSISTANT, - tool_calls: normalizedCalls - }); + case HarnessEventType.COMPLETION_ID: + onCompletionId?.(event.id); - // Execute each tool call and create result messages - for (let i = 0; i < normalizedCalls.length; i++) { - const toolCall = normalizedCalls[i]; + break; - if (signal?.aborted) { - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); + case HarnessEventType.MESSAGE: + this.updateSession(conversationId, { streamingToolCall: null }); - return; - } + if (event.toolCalls && !event.final) { + totalToolCallCount += event.toolCalls.length; + this.updateSession(conversationId, { totalToolCalls: totalToolCallCount }); + } - // Check for pending steering message - skip remaining tool calls - if (this.gates.hasPendingSteeringMessage(conversationId)) { - console.log( - `[AgenticStore] Steering message detected, skipping ${normalizedCalls.length - i} remaining tool call(s)` + await onAssistantTurnComplete?.( + event.content, + event.reasoning, + withTotalTime(event.timings, startedAt), + event.toolCalls ); - for (let j = i; j < normalizedCalls.length; j++) { - const remainingCall = normalizedCalls[j]; - const interruptedContent = 'Tool execution was interrupted by a new user message.'; - if (createToolResultMessage) { - await createToolResultMessage(remainingCall.id, interruptedContent); - } + break; - sessionMessages.push({ - content: interruptedContent, - role: MessageRole.TOOL, - tool_call_id: remainingCall.id + case HarnessEventType.TOOL_UPDATE: { + if (!createToolResultMessage || !updateToolResultMessage) break; + + const streamed = streamedResults.get(event.toolCall.id); + + if (streamed) { + streamed.content = event.content; + await updateToolResultMessage(streamed.messageId, event.content); + } else { + const message = await createToolResultMessage( + event.toolCall.id, + event.content, + undefined, + conversationsStore.activeConversation?.cwd + ); + + streamedResults.set(event.toolCall.id, { + content: event.content, + messageId: message.id }); } break; } - const toolName = toolCall.function.name; - const serverLabel = toolsStore.getToolServerLabel(toolName); - // Ask for permission before executing the tool - const permission = await this.gates.requestPermission( - conversationId, - toolName, - serverLabel, - toolCall.id, - signal - ); - - // Yield to allow Svelte to flush the UI update (hide permission dialog) - await new Promise((r) => setTimeout(r, 0)); - - if (signal?.aborted) { - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); - - return; - } - - const toolStartTime = performance.now(); - const toolSource = toolsStore.getToolSource(toolName); - - let result = ''; - let toolSuccess = true; - let createdToolResultMessageId: string | null = null; - - // Streaming tools (currently only exec_shell_command): mark - // the session so the matching renderer can switch to live mode. - // Cleared unconditionally below. - this.updateSession(conversationId, { executingToolCallId: toolCall.id }); - - if (permission === ToolPermissionDecision.DENY) { - result = 'Tool execution was denied by the user.'; - toolSuccess = false; - } else { - try { - if ( - toolSource === ToolSource.SERVER && - toolName === BuiltInTool.SERVER_EXEC_SHELL_COMMAND && - createToolResultMessage && - updateToolResultMessage - ) { - const args = this.parseToolArguments(toolCall.function.arguments); - const cwd = conversationsStore.activeConversation?.cwd; - const msg = await createToolResultMessage(toolCall.id, '', undefined, cwd); - - createdToolResultMessageId = msg.id; - - let accumulated = ''; - - for await (const ev of ToolsService.streamTool(toolName, args, signal, cwd)) { - if (ev.chunk !== null) { - accumulated += ev.chunk; - await updateToolResultMessage(msg.id, accumulated); - } - - if (ev.done) { - if (ev.error) { - accumulated = accumulated - ? `${accumulated}\nError: ${ev.error}` - : `Error: ${ev.error}`; - await updateToolResultMessage(msg.id, accumulated); - toolSuccess = false; - } - - break; - } - } - result = accumulated; - } else if (toolSource === ToolSource.SERVER) { - const args = this.parseToolArguments(toolCall.function.arguments); - const cwd = conversationsStore.activeConversation?.cwd; - const executionResult = await ToolsService.executeTool(toolName, args, signal, cwd); - - result = executionResult.content; - - if (executionResult.isError) toolSuccess = false; - } else if (toolSource === ToolSource.BROWSER) { - const args = this.parseToolArguments(toolCall.function.arguments); - - let executionResult: ToolExecutionResult; - - if (toolName === BuiltInTool.BROWSER_GET_DATETIME) { - executionResult = executeGetDatetimeTool(); - } else if (toolName === BuiltInTool.SERVER_GET_INFO) { - executionResult = executeBrowserInfoTool(); - } else if (toolName === BuiltInTool.BROWSER_SEARCH_CHATS) { - executionResult = await SearchChatsService.executeTool(args, conversationId); - } else if (toolName === BuiltInTool.BROWSER_READ_MEDIA) { - executionResult = await ReadMediaService.executeTool( - args, - { - audio: modelsStore.props.modelSupportsAudio(effectiveModel), - vision: modelsStore.props.modelSupportsVision(effectiveModel) - }, - signal, - conversationsStore.activeConversation?.cwd - ); - } else { - executionResult = await SandboxService.executeTool(toolName, args, signal); - } - - result = executionResult.content; + case HarnessEventType.TOOL_RESULT: { + const { content } = event.result; + const attachments = (event.result.details as DatabaseMessageExtra[] | undefined) ?? []; + const extras = attachments.length > 0 ? attachments : undefined; + const streamed = streamedResults.get(event.toolCall.id); - if (executionResult.isError) toolSuccess = false; - } else { - const mcpCall: MCPToolCall = { - function: { arguments: toolCall.function.arguments, name: toolName }, - id: toolCall.id - }; - const executionResult = await mcpStore.executeTool(mcpCall, signal); + let toolResultMessageId: string | undefined; - result = executionResult.content; - } - } catch (error) { - if (isAbortError(error)) { - this.updateSession(conversationId, { executingToolCallId: null }); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); - - return; - } - - // Carry the partial stream contents already mirrored to the UI - - // they show up as live output even if the stream broke off mid-run. - result = result - ? `${result}\nError: ${error instanceof Error ? error.message : String(error)}` - : `Error: ${error instanceof Error ? error.message : String(error)}`; - toolSuccess = false; + if (streamed) { + toolResultMessageId = streamed.messageId; - if (createdToolResultMessageId && updateToolResultMessage) { - await updateToolResultMessage(createdToolResultMessageId, result); + // the message already shows the streamed output: rewrite it only when the result differs + if (extras || content !== streamed.content) { + await updateToolResultMessage?.(streamed.messageId, content, extras); } + } else if (createToolResultMessage) { + toolResultMessageId = ( + await createToolResultMessage(event.toolCall.id, content, extras) + ).id; } - } - this.updateSession(conversationId, { executingToolCallId: null }); + if (extras && toolResultMessageId) onAttachments?.(toolResultMessageId, extras); - const toolDurationMs = performance.now() - toolStartTime; - const toolTiming: ChatMessageToolCallTiming = { - duration_ms: Math.round(toolDurationMs), - name: toolCall.function.name, - success: toolSuccess - }; + break; + } - agenticTimings.toolCalls!.push(toolTiming); - agenticTimings.toolCallsCount++; - agenticTimings.toolsMs += Math.round(toolDurationMs); - turnStats.toolCalls.push(toolTiming); - turnStats.toolsMs += Math.round(toolDurationMs); + case HarnessEventType.TURN_END: + onTurnComplete?.(withTotalTime(event.timings, startedAt)); - if (signal?.aborted) { - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); + break; - return; - } + case HarnessEventType.DONE: + onFlowComplete?.(withTotalTime(event.timings, startedAt)); - const { attachments, cleanedResult } = this.extractBase64Attachments(result); + break; - // For streaming tools the result message was created empty - // at the start of execution and updated in place as chunks - // arrived via updateToolResultMessage. Skip the second - // create call - just attach any base64 attachments found in - // the final accumulator (rare, since chunks usually don't - // carry image data URIs) and emit the attachments callback. - let toolResultMessage: DatabaseMessage | undefined; + case HarnessEventType.ERROR: + onFlowComplete?.(withTotalTime(event.timings, startedAt)); - if (createdToolResultMessageId) { - toolResultMessage = { id: createdToolResultMessageId } as DatabaseMessage; + throw event.error; + } + } + } - if (attachments.length > 0 && updateToolResultMessage) { - await updateToolResultMessage(createdToolResultMessageId, cleanedResult, attachments); - } - } else if (createToolResultMessage) { - toolResultMessage = await createToolResultMessage( - toolCall.id, - cleanedResult, - attachments.length > 0 ? attachments : undefined - ); - } + /** + * A tool of the harness: the permission gate, then the call, then the + * result with its media taken out of the text. + */ + private async executeTool(params: { + callbacks: AgenticFlowCallbacks; + context: ToolContext; + conversationId: string; + effectiveModel: string; + toolCall: ToolCall; + }): Promise { + const { callbacks, context, conversationId, effectiveModel, toolCall } = params; + const toolName = toolCall.function.name; + const serverLabel = toolsStore.getToolServerLabel(toolName); + // Ask for permission before executing the tool + const permission = await this.gates.requestPermission( + conversationId, + toolName, + serverLabel, + toolCall.id, + context.signal + ); - if (attachments.length > 0 && toolResultMessage) { - onAttachments?.(toolResultMessage.id, attachments); - } + // Yield to allow Svelte to flush the UI update (hide permission dialog) + await new Promise((r) => setTimeout(r, 0)); - // Build content parts for session history (including images for vision models) - const contentParts: ApiChatMessageContentPart[] = [ - { text: cleanedResult, type: ContentPartType.TEXT } - ]; - - for (const attachment of attachments) { - if (attachment.type === AttachmentType.AUDIO) { - if (modelsStore.props.modelSupportsAudio(effectiveModel)) { - contentParts.push({ - input_audio: { - data: (attachment as DatabaseMessageExtraAudioFile).base64Data, - format: getAudioInputFormat( - (attachment as DatabaseMessageExtraAudioFile).mimeType - ) - }, - type: ContentPartType.INPUT_AUDIO - }); - } - } else if (attachment.type === AttachmentType.IMAGE) { - if (modelsStore.props.modelSupportsVision(effectiveModel)) { - contentParts.push({ - image_url: { - url: (attachment as DatabaseMessageExtraImageFile).base64Url - }, - type: ContentPartType.IMAGE_URL - }); - } else { - console.info( - `[AgenticStore] Skipping image attachment (model "${effectiveModel}" does not support vision)` - ); - } - } - } + throwIfAborted(context.signal); - sessionMessages.push({ - content: contentParts.length === 1 ? cleanedResult : contentParts, - role: MessageRole.TOOL, - tool_call_id: toolCall.id - }); - } + // the time waiting for permission does not count + const toolStartTime = performance.now(); - if (turnStats.toolCalls.length > 0) { - agenticTimings.perTurn!.push(turnStats); + let execution: ToolExecutionResult; - const intermediateTimings = this.buildFinalTimings(capturedTimings, agenticTimings); + // Streaming tools (currently only exec_shell_command): mark + // the session so the matching renderer can switch to live mode. + this.updateSession(conversationId, { executingToolCallId: toolCall.id }); - if (intermediateTimings) onTurnComplete?.(intermediateTimings); - } + try { + execution = + permission === ToolPermissionDecision.DENY + ? { content: 'Tool execution was denied by the user.', isError: true } + : await this.dispatchTool({ + callbacks, + context, + conversationId, + effectiveModel, + toolCall + }); + } catch (error) { + if (isAbortError(error)) throw error; - // If tools were interrupted by a steering message, exit now instead of starting another LLM turn - if (this.gates.hasPendingSteeringMessage(conversationId)) { - console.log( - '[AgenticStore] Steering message detected after tool execution, exiting agentic flow' - ); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); + execution = { + content: `Error: ${error instanceof Error ? error.message : String(error)}`, + isError: true + }; + } finally { + this.updateSession(conversationId, { executingToolCallId: null }); + } - return; - } + const durationMs = performance.now() - toolStartTime; + const { attachments, cleanedResult } = this.extractBase64Attachments(execution.content); - turn++; - } + return { + content: cleanedResult, + details: attachments, + durationMs, + isError: execution.isError, + parts: this.buildContentParts(attachments, effectiveModel) + }; } private extractBase64Attachments(result: string): { @@ -1064,17 +891,57 @@ class AgenticStore { return { attachments, cleanedResult: cleanedLines.join(NEWLINE) }; } - private normalizeToolCalls(toolCalls: ApiChatCompletionToolCall[]): AgenticToolCallList { - if (!toolCalls) return []; + /** + * ChatService as the harness's inference client: one streamed completion + * per turn, its callbacks turned into events. + */ + private inferenceClient(options: AgenticFlowOptions, conversationId: string): InferenceClient { + return { + stream: ({ messages, signal, tools }) => { + const events = createAsyncQueue(); - return toolCalls.map((call, index) => ({ - function: { - arguments: call?.function?.arguments ?? '', - name: call?.function?.name ?? '' - }, - id: call?.id ?? `tool_${index}`, - type: (call?.type as ToolCallType.FUNCTION) ?? ToolCallType.FUNCTION - })); + ChatService.sendMessage( + messages as ApiChatMessageData[], + { + ...options, + onChunk: (chunk: string) => + events.push({ delta: chunk, type: InferenceEventType.TEXT }), + onComplete: () => { + /* Completion handled after sendMessage resolves */ + }, + onCompletionId: (id: string) => + events.push({ id, type: InferenceEventType.COMPLETION_ID }), + onError: (error: Error) => { + throw error; + }, + onModel: (model: string) => events.push({ model, type: InferenceEventType.MODEL }), + onReasoningChunk: (chunk: string) => + events.push({ delta: chunk, type: InferenceEventType.REASONING }), + onTimings: (timings?: ChatMessageTimings, progress?: ChatMessagePromptProgress) => + events.push({ progress, timings, type: InferenceEventType.TIMINGS }), + onToolCallChunk: (serialized: string) => { + try { + events.push({ + toolCalls: JSON.parse(serialized), + type: InferenceEventType.TOOL_CALLS + }); + } catch { + /* Ignore parse errors during streaming */ + } + }, + stream: true, + tools + }, + conversationId, + signal + ).then( + () => events.close(), + (error: unknown) => events.fail(error) + ); + + return events; + } + }; } private parseToolArguments(args: string | Record): Record { diff --git a/ui/apps/chat/src/lib/types/index.ts b/ui/apps/chat/src/lib/types/index.ts index b931f76ee43b..eb3ef07017d1 100644 --- a/ui/apps/chat/src/lib/types/index.ts +++ b/ui/apps/chat/src/lib/types/index.ts @@ -245,8 +245,6 @@ export type { EditFileEdit, EditFileMeta, EditFileTitleMeta, - ToolCallDescription, - ToolCallPhrasing, ToolEntry, ToolGroup, ToolUiEntry, diff --git a/ui/apps/chat/src/lib/types/tools.d.ts b/ui/apps/chat/src/lib/types/tools.d.ts index a96a7e3ce840..4f1ab120a1f2 100644 --- a/ui/apps/chat/src/lib/types/tools.d.ts +++ b/ui/apps/chat/src/lib/types/tools.d.ts @@ -1,5 +1,5 @@ import type { OpenAIToolDefinition } from './mcp'; -import type { ToolCallSummaryKind, ToolSource } from '#lib/enums/index.ts'; +import type { ToolSource } from '#lib/enums/index.ts'; import type { Component } from 'svelte'; /** @@ -81,32 +81,3 @@ export interface EditFileTitleMeta { editsApplied?: number; errorMessage?: string; } - -/** How a tool call reads in the chat trace; see TOOL_CALL_PHRASING. */ -export interface ToolCallPhrasing { - /** Verb once the call is done, e.g. "Read". */ - past: string; - /** Verb while the call runs, e.g. "Reading". */ - present: string; - /** Words after the verb when the call has no target, e.g. "a file". */ - object: string; - /** Words between the verb and the target, e.g. "for". */ - targetObject?: string; - /** Show the target in quotes, for search terms. */ - quoteTarget?: boolean; - summary: ToolCallSummaryKind; -} - -/** A tool call as one plain sentence: label, then an optional target. */ -export interface ToolCallDescription { - /** Verb and object, e.g. "Read a file" or "Searched for". */ - label: string; - /** What the call acted on, e.g. a file name or a search term. */ - target?: string; - quoted: boolean; - summary: ToolCallSummaryKind; - /** How many things the call counts as in the group summary. */ - count: number; - /** True when the label is the model's own description of the call. */ - described?: boolean; -} diff --git a/ui/apps/chat/src/lib/utils/async-queue.ts b/ui/apps/chat/src/lib/utils/async-queue.ts new file mode 100644 index 000000000000..48988dd93951 --- /dev/null +++ b/ui/apps/chat/src/lib/utils/async-queue.ts @@ -0,0 +1,50 @@ +/** + * A queue read as an async iterable, to turn a callback API into a stream. + * The iteration ends after `close`, and throws after `fail`, once the pushed items are read. + */ +export interface AsyncQueue extends AsyncIterable { + push(item: T): void; + close(): void; + fail(error: unknown): void; +} + +export function createAsyncQueue(): AsyncQueue { + const items: T[] = []; + + let closed = false; + let failure: { error: unknown } | undefined; + let wake: (() => void) | undefined; + + const notify = () => { + wake?.(); + wake = undefined; + }; + + return { + close() { + closed = true; + notify(); + }, + fail(error) { + failure = { error }; + notify(); + }, + push(item) { + items.push(item); + notify(); + }, + async *[Symbol.asyncIterator]() { + while (true) { + if (items.length > 0) { + yield items.shift()!; + } else if (failure) { + throw failure.error; + } else if (closed) { + return; + } else { + await new Promise((resolve) => (wake = resolve)); + } + } + } + }; +} diff --git a/ui/apps/chat/src/lib/utils/index.ts b/ui/apps/chat/src/lib/utils/index.ts index ae28ff9cd23c..4476ac63f40f 100644 --- a/ui/apps/chat/src/lib/utils/index.ts +++ b/ui/apps/chat/src/lib/utils/index.ts @@ -295,7 +295,6 @@ export { computeLineDiff, prefixFor, renderUnifiedDiff, type DiffLine } from './ // Partial-incremental JSON parser for streaming tool arguments export { memoizeBounded } from './memoize-bounded'; -export { parsePartialJsonArgs } from './parse-partial-json-args'; // `exec_shell_command` result parsing export { parseExecShellCommandError } from './parse-exec-shell-error'; diff --git a/ui/apps/chat/src/lib/utils/parse-partial-json-args.ts b/ui/apps/chat/src/lib/utils/parse-partial-json-args.ts deleted file mode 100644 index 49bc1bc70434..000000000000 --- a/ui/apps/chat/src/lib/utils/parse-partial-json-args.ts +++ /dev/null @@ -1,124 +0,0 @@ -// JSON delimiters used while scanning partial streamed JSON. Single-char -// tokens so they only need eq-comparison, but naming them keeps the -// scanner readable and keeps the literal source-of-truth in one place. -const JSON_QUOTE = '"'; -const JSON_BACKSLASH = '\\'; -const JSON_OBJECT_OPEN = '{'; -const JSON_OBJECT_CLOSE = '}'; -const JSON_ARRAY_OPEN = '['; -const JSON_ARRAY_CLOSE = ']'; -// Trailing punctuation to strip before re-closing a partial object/array. -// Matches an optional trailing comma plus any trailing whitespace; lets -// us re-emit a syntactically-valid JSON document without an orphaned -// comma when the model cut off mid-key. -const TRAILING_JSON_PUNCTUATION_REGEX = /,?\s*$/; -/** Bounded cache for parsePartialJsonArgs results. */ -const PARTIAL_JSON_CACHE_MAX_SIZE = 32; -const partialJsonCache = new Map | null>(); - -function cacheResult(input: string, result: Record | null): void { - if (partialJsonCache.size >= PARTIAL_JSON_CACHE_MAX_SIZE) { - partialJsonCache.delete(partialJsonCache.keys().next().value!); - } - - partialJsonCache.set(input, result); -} - -// Parse partial tool-arg JSON streamed token-by-token. Closes any -// unterminated string and dangling open containers (in reverse order), -// so parsers can still surface keys already received while the call -// is still in flight. Memoized: the char-by-char scanner runs on every -// render during streaming even when toolArgs hasn't changed. -export function parsePartialJsonArgs(toolArgsString: string): Record | null { - const cached = partialJsonCache.get(toolArgsString); - - if (cached !== undefined) return cached; - - let result: Record | null; - - try { - const parsed: unknown = JSON.parse(toolArgsString); - - result = - parsed && typeof parsed === 'object' && !Array.isArray(parsed) - ? (parsed as Record) - : null; - } catch { - result = scanPartialJson(toolArgsString); - } - - cacheResult(toolArgsString, result); - - return result; -} - -/** Char-by-char scanner for unterminated partial JSON. */ -function scanPartialJson(toolArgsString: string): Record | null { - let inString = false; - let escape = false; - - const stack: ('{' | '[')[] = []; - - for (let i = 0; i < toolArgsString.length; i++) { - const ch = toolArgsString[i]; - - if (escape) { - escape = false; - - continue; - } - - if (ch === JSON_BACKSLASH && inString) { - escape = true; - - continue; - } - - if (ch === JSON_QUOTE) { - inString = !inString; - - continue; - } - - if (inString) continue; - - if (ch === JSON_OBJECT_OPEN) stack.push(JSON_OBJECT_OPEN); - else if (ch === JSON_OBJECT_CLOSE) { - if (stack.length === 0 || stack[stack.length - 1] !== JSON_OBJECT_OPEN) return null; - - stack.pop(); - } else if (ch === JSON_ARRAY_OPEN) stack.push(JSON_ARRAY_OPEN); - else if (ch === JSON_ARRAY_CLOSE) { - if (stack.length === 0 || stack[stack.length - 1] !== JSON_ARRAY_OPEN) return null; - - stack.pop(); - } - } - - let completed = toolArgsString; - - if (escape) { - // Dangling escape at end of partial JSON: escape the trailing - // backslash as a literal so we can close the string cleanly. - completed += JSON_BACKSLASH; - } - - if (inString) completed += JSON_QUOTE; - - if (!inString) completed = completed.replace(TRAILING_JSON_PUNCTUATION_REGEX, ''); - - // Close in reverse nesting order: innermost container first. - for (let i = stack.length - 1; i >= 0; i--) { - completed += stack[i] === JSON_OBJECT_OPEN ? JSON_OBJECT_CLOSE : JSON_ARRAY_CLOSE; - } - - try { - const parsed: unknown = JSON.parse(completed); - - return parsed && typeof parsed === 'object' && !Array.isArray(parsed) - ? (parsed as Record) - : null; - } catch { - return null; - } -} diff --git a/ui/apps/chat/tests/unit/agentic-flow.test.ts b/ui/apps/chat/tests/unit/agentic-flow.test.ts new file mode 100644 index 000000000000..1003f8fcb871 --- /dev/null +++ b/ui/apps/chat/tests/unit/agentic-flow.test.ts @@ -0,0 +1,373 @@ +// The agentic flow end to end, with the server and the tools mocked: what the +// model is sent each turn, and the order the flow's callbacks fire in. + +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('#lib/services/database.service.ts', () => ({ + DatabaseService: {} +})); + +import { BuiltInTool, MessageRole, ToolPermissionDecision, ToolSource } from '#lib/enums/index.ts'; +import { ChatService } from '#lib/services/chat.service.ts'; +import { ToolsService } from '#lib/services/tools.service.ts'; +import { agenticStore } from '#lib/stores/agentic/index.svelte.ts'; +import { modelsStore } from '#lib/stores/models/index.svelte.ts'; +import { permissionsStore } from '#lib/stores/permissions.svelte.ts'; +import { toolsStore } from '#lib/stores/tools.svelte.ts'; +import type { AgenticFlowCallbacks } from '#lib/types/agentic.js'; +import type { ApiChatMessageData } from '#lib/types/api.js'; +import type { ChatMessageTimings } from '#lib/types/chat.js'; +import type { DatabaseMessage } from '#lib/types/database.js'; + +const CONV_ID = 'conv-1'; +const USER_MESSAGES: ApiChatMessageData[] = [{ content: 'hi', role: MessageRole.USER }]; +const IMAGE_DATA_URI = 'data:image/png;base64,AAAA'; + +type StreamOptions = { + onChunk?: (chunk: string) => void; + onReasoningChunk?: (chunk: string) => void; + onTimings?: (timings?: ChatMessageTimings) => void; + onToolCallChunk?: (serialized: string) => void; +}; +type Turn = (options: StreamOptions) => void | Promise; + +function toolCalls(...names: string[]): string { + return JSON.stringify( + names.map((name, index) => ({ function: { arguments: '{}', name }, id: `call_${index}` })) + ); +} + +// each request plays the next scripted turn; returns what every request was sent +function mockTurns(...turns: Turn[]): ApiChatMessageData[][] { + const requests: ApiChatMessageData[][] = []; + + vi.spyOn(ChatService, 'sendMessage').mockImplementation(async (messages, options) => { + requests.push(structuredClone(messages) as ApiChatMessageData[]); + await turns[requests.length - 1]?.(options as StreamOptions); + }); + + return requests; +} + +function mockTools(source: ToolSource, ...names: string[]) { + vi.spyOn(toolsStore, 'getEnabledToolsForLLM').mockReturnValue( + names.map((name) => ({ function: { name, parameters: {} }, type: 'function' })) + ); + vi.spyOn(toolsStore, 'getToolSource').mockReturnValue(source); +} + +// callbacks that log their calls in order +function recorder() { + const calls: unknown[][] = []; + const log = + (name: string) => + (...args: unknown[]) => { + calls.push([name, ...args]); + }; + + let nextMessageId = 0; + + const createMessage = + (name: string) => + async (...args: unknown[]) => { + calls.push([name, ...args]); + + return { id: `msg_${nextMessageId++}` } as DatabaseMessage; + }; + const callbacks: AgenticFlowCallbacks = { + createAssistantMessage: createMessage('createAssistantMessage'), + createToolResultMessage: createMessage('createToolResultMessage'), + onAssistantTurnComplete: async (...args) => { + calls.push(['onAssistantTurnComplete', ...args]); + }, + onAttachments: log('onAttachments'), + onChunk: log('onChunk'), + onError: log('onError'), + onFlowComplete: log('onFlowComplete'), + onReasoningChunk: log('onReasoningChunk'), + onToolCallsStreaming: log('onToolCallsStreaming'), + onTurnComplete: log('onTurnComplete'), + updateToolResultMessage: async (...args) => { + calls.push(['updateToolResultMessage', ...args]); + } + }; + + return { + callbacks, + calls, + named: (name: string) => calls.filter((call) => call[0] === name), + names: () => calls.map((call) => call[0]) + }; +} + +function runFlow(callbacks: AgenticFlowCallbacks, signal?: AbortSignal) { + return agenticStore.runAgenticFlow({ + callbacks, + conversationId: CONV_ID, + messages: USER_MESSAGES, + signal + }); +} + +beforeEach(() => { + vi.restoreAllMocks(); + agenticStore.clearSession(CONV_ID); + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(ChatService, 'normalizeMessagesForApi').mockImplementation( + async (messages) => messages as ApiChatMessageData[] + ); + vi.spyOn(toolsStore, 'fetchServerTools').mockResolvedValue(); + vi.spyOn(toolsStore, 'getToolServerLabel').mockReturnValue('Browser'); + vi.spyOn(toolsStore, 'getPermissionKey').mockReturnValue('tool-key'); + vi.spyOn(permissionsStore, 'hasTool').mockReturnValue(true); +}); + +describe('agentic flow', () => { + it('is not handled when no tool is enabled', async () => { + vi.spyOn(toolsStore, 'getEnabledToolsForLLM').mockReturnValue([]); + + const send = vi.spyOn(ChatService, 'sendMessage'); + + expect(await runFlow(recorder().callbacks)).toEqual({ handled: false }); + expect(send).not.toHaveBeenCalled(); + }); + + it('runs a tool call, then lets the model answer', async () => { + mockTools(ToolSource.BROWSER, BuiltInTool.BROWSER_GET_DATETIME); + + const requests = mockTurns( + (options) => { + options.onChunk?.('checking'); + options.onToolCallChunk?.(toolCalls(BuiltInTool.BROWSER_GET_DATETIME)); + options.onTimings?.({ predicted_ms: 10, predicted_n: 4, prompt_ms: 20, prompt_n: 8 }); + }, + (options) => { + options.onReasoningChunk?.('hm'); + options.onChunk?.('it is noon'); + options.onTimings?.({ predicted_ms: 5, predicted_n: 2, prompt_ms: 1, prompt_n: 1 }); + } + ); + const { callbacks, named, names } = recorder(); + + expect(await runFlow(callbacks)).toEqual({ handled: true }); + expect(names()).toEqual([ + 'onChunk', + 'onToolCallsStreaming', + 'onAssistantTurnComplete', + 'createToolResultMessage', + 'onTurnComplete', + 'createAssistantMessage', + 'onReasoningChunk', + 'onChunk', + 'onAssistantTurnComplete', + 'onTurnComplete', + 'onFlowComplete' + ]); + + const [toolTurn, finalTurn] = named('onAssistantTurnComplete'); + const call = { + function: { arguments: '{}', name: BuiltInTool.BROWSER_GET_DATETIME }, + id: 'call_0', + type: 'function' + }; + + expect(toolTurn.slice(1)).toEqual([ + 'checking', + undefined, + { predicted_ms: 10, predicted_n: 4, prompt_ms: 20, prompt_n: 8 }, + [call] + ]); + expect(finalTurn.slice(1, 3)).toEqual(['it is noon', 'hm']); + expect(finalTurn[4]).toBeUndefined(); + + const [, toolCallId, toolResult, extras] = named('createToolResultMessage')[0]; + + expect([toolCallId, extras]).toEqual(['call_0', undefined]); + expect(requests[1].slice(1)).toEqual([ + { content: 'checking', role: 'assistant', tool_calls: [call] }, + { content: toolResult, role: 'tool', tool_call_id: 'call_0' } + ]); + expect(named('onFlowComplete')[0][1]).toMatchObject({ + agentic: { + llm: { predicted_ms: 15, predicted_n: 6, prompt_ms: 21, prompt_n: 9 }, + perTurn: [{ turn: 1 }, { turn: 2 }], + toolCalls: [{ name: BuiltInTool.BROWSER_GET_DATETIME, success: true }], + toolCallsCount: 1, + turns: 2 + }, + predicted_n: 2 + }); + expect(agenticStore.getTotalToolCalls(CONV_ID)).toBe(1); + expect(agenticStore.isRunning(CONV_ID)).toBe(false); + }); + + it('waits for permission and tells the model when it is denied', async () => { + mockTools(ToolSource.BROWSER, BuiltInTool.BROWSER_GET_DATETIME); + vi.mocked(permissionsStore.hasTool).mockReturnValue(false); + + const requests = mockTurns( + (options) => options.onToolCallChunk?.(toolCalls(BuiltInTool.BROWSER_GET_DATETIME)), + (options) => options.onChunk?.('ok') + ); + const { callbacks, named } = recorder(); + const flow = runFlow(callbacks); + + await vi.waitFor(() => + expect(agenticStore.getPendingPermissionRequest(CONV_ID)).toEqual({ + serverLabel: 'Browser', + toolCallId: 'call_0', + toolName: BuiltInTool.BROWSER_GET_DATETIME + }) + ); + agenticStore.resolvePermission(CONV_ID, ToolPermissionDecision.DENY); + await flow; + + expect(named('createToolResultMessage')[0].slice(1)).toEqual([ + 'call_0', + 'Tool execution was denied by the user.', + undefined + ]); + expect(requests[1][2]).toMatchObject({ content: 'Tool execution was denied by the user.' }); + expect(named('onFlowComplete')[0][1]).toMatchObject({ + agentic: { toolCalls: [{ success: false }] } + }); + }); + + it('reports a failing tool to the model and goes on', async () => { + mockTools(ToolSource.SERVER, 'read_file'); + vi.spyOn(ToolsService, 'executeTool').mockRejectedValue(new Error('no such file')); + + const requests = mockTurns( + (options) => options.onToolCallChunk?.(toolCalls('read_file')), + (options) => options.onChunk?.('sorry') + ); + const { callbacks } = recorder(); + + expect(await runFlow(callbacks)).toEqual({ handled: true }); + expect(requests[1][2]).toMatchObject({ content: 'Error: no such file', role: 'tool' }); + }); + + it('shows the output of a streaming tool while it runs', async () => { + mockTools(ToolSource.SERVER, BuiltInTool.SERVER_EXEC_SHELL_COMMAND); + vi.spyOn(ToolsService, 'streamTool').mockImplementation(async function* () { + yield { chunk: 'one\n', done: false }; + await new Promise((resolve) => setTimeout(resolve, 0)); + yield { chunk: 'two\n', done: false }; + await new Promise((resolve) => setTimeout(resolve, 0)); + yield { chunk: null, done: true }; + }); + + const requests = mockTurns( + (options) => options.onToolCallChunk?.(toolCalls(BuiltInTool.SERVER_EXEC_SHELL_COMMAND)), + (options) => options.onChunk?.('done') + ); + const { callbacks, named } = recorder(); + + await runFlow(callbacks); + + // created empty when the tool starts, then rewritten in place: never created twice + expect(named('createToolResultMessage').map((call) => call.slice(1))).toEqual([ + ['call_0', '', undefined, undefined] + ]); + expect(named('updateToolResultMessage').map((call) => call.slice(1))).toEqual([ + ['msg_0', 'one\n'], + ['msg_0', 'one\ntwo\n'] + ]); + expect(requests[1][2]).toMatchObject({ content: 'one\ntwo\n', role: 'tool' }); + }); + + it('takes an image out of a tool result and sends it to a model with vision', async () => { + mockTools(ToolSource.SERVER, 'screenshot'); + vi.spyOn(ToolsService, 'executeTool').mockResolvedValue({ + content: `saved\n${IMAGE_DATA_URI}`, + isError: false + }); + vi.spyOn(modelsStore.props, 'modelSupportsVision').mockReturnValue(true); + + const requests = mockTurns( + (options) => options.onToolCallChunk?.(toolCalls('screenshot')), + (options) => options.onChunk?.('here') + ); + const { callbacks, named } = recorder(); + + await runFlow(callbacks); + + const [, , content, extras] = named('createToolResultMessage')[0]; + + expect(content).toMatch(/^saved\n\[Attachment saved: .+\.png\]$/); + expect(extras).toMatchObject([{ base64Url: IMAGE_DATA_URI, type: 'IMAGE' }]); + expect(named('onAttachments')[0].slice(1)).toEqual(['msg_0', extras]); + expect(requests[1][2]).toEqual({ + content: [ + { text: content, type: 'text' }, + { image_url: { url: IMAGE_DATA_URI }, type: 'image_url' } + ], + role: 'tool', + tool_call_id: 'call_0' + }); + }); + + it('leaves the flow when a steering message is queued, skipping the tool calls left', async () => { + mockTools(ToolSource.SERVER, 'first', 'second'); + vi.spyOn(ToolsService, 'executeTool').mockImplementation(async () => { + agenticStore.injectSteeringMessage(CONV_ID, 'wait'); + + return { content: 'first ran', isError: false }; + }); + + const requests = mockTurns((options) => + options.onToolCallChunk?.(toolCalls('first', 'second')) + ); + const { callbacks, named, names } = recorder(); + + expect(await runFlow(callbacks)).toEqual({ handled: true }); + expect(named('createToolResultMessage').map((call) => call.slice(1, 3))).toEqual([ + ['call_0', 'first ran'], + ['call_1', 'Tool execution was interrupted by a new user message.'] + ]); + expect(names().slice(-2)).toEqual(['onTurnComplete', 'onFlowComplete']); + expect(requests).toHaveLength(1); + expect(agenticStore.consumePendingSteeringMessage(CONV_ID)).toMatchObject({ content: 'wait' }); + }); + + it('keeps the partial turn and reports the error when the stream fails', async () => { + mockTools(ToolSource.BROWSER, BuiltInTool.BROWSER_GET_DATETIME); + mockTurns((options) => { + options.onChunk?.('par'); + + throw new Error('HTTP 500'); + }); + + const { callbacks, named, names } = recorder(); + const result = await runFlow(callbacks); + + expect(result).toMatchObject({ error: { message: 'HTTP 500' }, handled: true }); + expect(names()).toEqual(['onChunk', 'onAssistantTurnComplete', 'onFlowComplete', 'onError']); + expect(named('onAssistantTurnComplete')[0].slice(1)).toEqual([ + 'par', + undefined, + undefined, + undefined + ]); + expect(agenticStore.getLastError(CONV_ID)?.message).toBe('HTTP 500'); + }); + + it('stops without a tool result when the user aborts during a tool call', async () => { + const controller = new AbortController(); + + mockTools(ToolSource.SERVER, 'slow'); + vi.spyOn(ToolsService, 'executeTool').mockImplementation(async () => { + controller.abort(); + + return { content: 'late', isError: false }; + }); + + const requests = mockTurns((options) => options.onToolCallChunk?.(toolCalls('slow'))); + const { callbacks, named, names } = recorder(); + + expect(await runFlow(callbacks, controller.signal)).toEqual({ handled: true }); + expect(named('createToolResultMessage')).toEqual([]); + expect(names().slice(-1)).toEqual(['onFlowComplete']); + expect(requests).toHaveLength(1); + }); +}); diff --git a/ui/apps/chat/tests/unit/agentic-hotpath.bench.ts b/ui/apps/chat/tests/unit/agentic-hotpath.bench.ts index c46f3fe4bf68..0da763bd3d76 100644 --- a/ui/apps/chat/tests/unit/agentic-hotpath.bench.ts +++ b/ui/apps/chat/tests/unit/agentic-hotpath.bench.ts @@ -6,6 +6,7 @@ // // Run: npx vitest bench --project=unit tests/unit/agentic-hotpath.bench.ts +import { parsePartialJsonArgs } from '@ggml-org/llama-harness'; import { classifyToolResult, parseToolResultWithMedia } from '#lib/utils/agentic.ts'; import { detectIncompleteCodeBlock, @@ -14,7 +15,6 @@ import { } from '#lib/utils/code.ts'; import { computeLineDiff } from '#lib/utils/compute-line-diff.ts'; import { preprocessLaTeX } from '#lib/utils/latex-protection.ts'; -import { parsePartialJsonArgs } from '#lib/utils/parse-partial-json-args.ts'; import { extractSearchQuery, extractSearchResults } from '#lib/utils/search-results.ts'; import { all as lowlightAll } from 'lowlight'; import rehypeHighlight from 'rehype-highlight'; diff --git a/ui/apps/chat/tests/unit/async-queue.test.ts b/ui/apps/chat/tests/unit/async-queue.test.ts new file mode 100644 index 000000000000..4856f74d3ba6 --- /dev/null +++ b/ui/apps/chat/tests/unit/async-queue.test.ts @@ -0,0 +1,42 @@ +import { createAsyncQueue } from '#lib/utils/async-queue.ts'; +import { describe, expect, it } from 'vitest'; + +async function collect(queue: AsyncIterable): Promise { + const items: T[] = []; + + for await (const item of queue) items.push(item); + + return items; +} + +describe('createAsyncQueue', () => { + it('yields the items pushed before and during the iteration, then ends on close', async () => { + const queue = createAsyncQueue(); + + queue.push(1); + + const collected = collect(queue); + + await Promise.resolve(); + queue.push(2); + queue.push(3); + queue.close(); + + expect(await collected).toEqual([1, 2, 3]); + }); + + it('throws the failure after the pushed items are read', async () => { + const queue = createAsyncQueue(); + const seen: number[] = []; + + queue.push(1); + queue.fail(new Error('cut')); + + await expect( + (async () => { + for await (const item of queue) seen.push(item); + })() + ).rejects.toThrow('cut'); + expect(seen).toEqual([1]); + }); +}); diff --git a/ui/apps/chat/tests/unit/tool-call-phrasing.test.ts b/ui/apps/chat/tests/unit/tool-call-phrasing.test.ts index 1433d32250cd..459ff227f4dd 100644 --- a/ui/apps/chat/tests/unit/tool-call-phrasing.test.ts +++ b/ui/apps/chat/tests/unit/tool-call-phrasing.test.ts @@ -1,10 +1,12 @@ import { - describeToolActivity, - describeToolCall, formatToolCallLine, groupToolCallRuns, humanizeArgKey, - simpleToolArgFields, + simpleToolArgFields +} from '@ggml-org/llama-harness'; +import { + describeToolActivity, + describeToolCall, summarizeToolCalls } from '#lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts'; import { AgenticSectionType, BuiltInTool } from '#lib/enums/index.ts'; diff --git a/ui/apps/chat/tsconfig.json b/ui/apps/chat/tsconfig.json index 74af0cce0360..fed5bbe9d198 100644 --- a/ui/apps/chat/tsconfig.json +++ b/ui/apps/chat/tsconfig.json @@ -47,7 +47,8 @@ "tw-animate-css/*": ["./node_modules/tw-animate-css/*"], "vaul-svelte": ["./node_modules/vaul-svelte"], "vaul-svelte/*": ["./node_modules/vaul-svelte/*"], - "@lucide/svelte/icons/*": ["./node_modules/@lucide/svelte/dist/icons/*"] + "@lucide/svelte/icons/*": ["./node_modules/@lucide/svelte/dist/icons/*"], + "@ggml-org/llama-harness": ["../../lib/harness/src/index.ts"] }, "sourceMap": true, "strict": true diff --git a/ui/apps/chat/vite.config.ts b/ui/apps/chat/vite.config.ts index fb9c666a9577..68493dad9656 100644 --- a/ui/apps/chat/vite.config.ts +++ b/ui/apps/chat/vite.config.ts @@ -17,6 +17,8 @@ import { defineConfig, loadEnv, searchForWorkspaceRoot } from 'vite'; const __dirname = dirname(fileURLToPath(import.meta.url)); const LLAMA_VOICE_SOURCE = resolve(__dirname, '../../lib/voice/src'); +// the harness has no build step in the repo: the app compiles it from source +const LLAMA_HARNESS_ENTRY = resolve(__dirname, '../../lib/harness/src/index.ts'); // eslint-disable-next-line @typescript-eslint/no-explicit-any const browserBaseConfig: any = { enabled: true, @@ -85,6 +87,7 @@ export default defineConfig(({ mode }) => { replacement: resolve(LLAMA_VOICE_SOURCE, 'svelte/index.ts') }, { find: /^@ggml-org\/llama-voice$/, replacement: resolve(LLAMA_VOICE_SOURCE, 'index.ts') }, + { find: /^@ggml-org\/llama-harness$/, replacement: LLAMA_HARNESS_ENTRY }, { find: 'katex-fonts', replacement: resolve('node_modules/katex/dist/fonts') } ] }, @@ -94,7 +97,8 @@ export default defineConfig(({ mode }) => { allow: [ searchForWorkspaceRoot(process.cwd()), resolve(__dirname, 'tests'), - LLAMA_VOICE_SOURCE + LLAMA_VOICE_SOURCE, + resolve(__dirname, '../../lib/harness') ] }, headers: { diff --git a/ui/lib/harness/.gitignore b/ui/lib/harness/.gitignore new file mode 100644 index 000000000000..16339ab2e87f --- /dev/null +++ b/ui/lib/harness/.gitignore @@ -0,0 +1,6 @@ +node_modules +/dist + +# OS +.DS_Store +Thumbs.db diff --git a/ui/lib/harness/.npmrc b/ui/lib/harness/.npmrc new file mode 100644 index 000000000000..b6f27f135954 --- /dev/null +++ b/ui/lib/harness/.npmrc @@ -0,0 +1 @@ +engine-strict=true diff --git a/ui/lib/harness/LICENSE b/ui/lib/harness/LICENSE new file mode 100644 index 000000000000..50c59c51c158 --- /dev/null +++ b/ui/lib/harness/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) ggml + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/ui/lib/harness/README.md b/ui/lib/harness/README.md new file mode 100644 index 000000000000..140a06d9e58b --- /dev/null +++ b/ui/lib/harness/README.md @@ -0,0 +1,83 @@ +# @ggml-org/llama-harness + +Llama Harness, the agentic loop of Llama Chat, as a package: it streams a turn, runs the tools the model called, gives it the results, and repeats until the model answers without a tool call. It is headless TypeScript with no UI, no DOM and no dependencies, so the same loop runs in a browser, in Node and in a worker. It lives in llama.cpp at `ui/lib/harness`. + +It talks to llama-server's chat completions endpoint (`/v1/chat/completions`) and reads the timings and prompt progress llama-server adds. + +## Use + +```ts +import { createHarness, createOpenAIClient, type Tool } from "@ggml-org/llama-harness"; + +const harness = createHarness(createOpenAIClient({ baseUrl: "http://localhost:8080" })); + +const getTime: Tool = { + definition: { + type: "function", + function: { + name: "get_time", + description: "The current time", + parameters: { type: "object", properties: {} }, + }, + }, + execute: async () => ({ content: new Date().toISOString() }), +}; + +for await (const event of harness.run([{ role: "user", content: "What time is it?" }], [getTime])) { + if (event.type === "text") process.stdout.write(event.delta); +} +``` + +## The contract + +```ts +interface Harness { + run(messages, tools, signal?, options?): AsyncIterable; +} +``` + +- **Messages and tools** use the OpenAI shapes. A tool is its definition plus an `execute` function. +- **Events:** `turn_start`, `text`, `reasoning`, `tool_call_delta`, `timings`, `model`, `completion_id`, `message` (a turn's assistant message), `tool_call`, `tool_update` (a streaming tool's output so far), `tool_result`, `turn_end`, and last `done` or `error`. `run` never throws. +- **The loop waits for you.** It does not go on until you ask for the next event, so you can store each message before the next step runs. +- **It keeps nothing.** No conversation state, no storage: the app owns the history and passes it in. +- **Stopping:** `signal` stops at once. `options.interrupted` ends the run at the next safe point, e.g. when the user sent a new message. `options.maxTurns` with `options.onTurnLimit` asks before it goes past a turn limit. + +An app can put another loop behind the same `Harness` interface. What sits above the loop is the same for every loop: the tools, and whatever an app wraps around `execute`, such as a permission prompt. + +## Traces + +A run's steps also read as an agent trace: what each tool call did, in plain words. That part is headless too, so any app on the harness can show the same lines. + +```ts +import { createTracePhraser, formatToolCallLine, groupToolCallRuns } from "@ggml-org/llama-harness"; + +const { describeToolCall, summarizeToolCalls, describeToolActivity } = createTracePhraser(); + +formatToolCallLine(describeToolCall("read_file", '{"path":"src/app.ts"}')); // "Read app.ts" +summarizeToolCalls(steps); // "Ran 3 commands, read 2 files" +describeToolActivity(steps, true); // "Running npm test", or "Thinking" +``` + +- **Steps** are anything with a `type` from `TraceStepType` (text, reasoning, or a tool call that is done, pending or still streaming) plus the call's name and arguments. +- **Phrasing** knows llama-server's built-in tools. An app adds its own tools with `resolvers` (a function per tool or family of tools) and `phrasings` (a table by name); any other tool reads as "Used " with its main argument. A call whose arguments carry `description` shows the model's own words instead. +- **Streaming:** arguments are read while they stream (`parsePartialJsonArgs`), and arguments that hold whole files are read for their path only (`extractToolArgString`). +- **Grouping:** `groupToolCallRuns` folds the calls and the reasoning around them into one row, up to the next text. + +## What the app keeps + +Llama Chat (`ui/apps/chat`) is the first app on it. Its agentic store gives the harness: + +- **An inference client:** its own chat service, which knows the servers, the settings and how to resume a stream. +- **The tools:** built-in tools, llama-server tools and MCP tools, each behind the permission gate. +- **Storage:** it turns the events into messages in its database. + +## Develop + +```sh +npm ci +npm run check # type check +npm test # unit tests +npm run prepack # build dist/ and lint the package +``` + +Llama Chat does not need a build of this package: it compiles `src/` directly, through the `@ggml-org/llama-harness` alias in its `vite.config.ts`. diff --git a/ui/lib/harness/package-lock.json b/ui/lib/harness/package-lock.json new file mode 100644 index 000000000000..952987aff8df --- /dev/null +++ b/ui/lib/harness/package-lock.json @@ -0,0 +1,1255 @@ +{ + "name": "@ggml-org/llama-harness", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@ggml-org/llama-harness", + "version": "0.1.0", + "license": "MIT", + "devDependencies": { + "@types/node": "^24", + "publint": "^0.3.21", + "typescript": "^6.0.3", + "vitest": "5.0.5" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", + "dev": true, + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@publint/pack": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@publint/pack/-/pack-0.1.7.tgz", + "integrity": "sha512-4EDEmvxWtgsCnnVeBvtFIFZtUhPPt1+bA9JrSwU4Sa//6oKtzCSlGGXYJr44OD9aGISymbieJ4mCKHUygUDU+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyexec": "^1.3.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://bjornlu.com/sponsor" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.18.tgz", + "integrity": "sha512-ubTG+4KlidvioxjOFdsdEa2F6JVGZb8m2ByJUqQ7fYzUeT1cEn194POcsQ10PKH4p//q0YQn4SB3YpSuzcA1Yg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.18.tgz", + "integrity": "sha512-2Xa1t/JeFGTZn5TbzgPppcCftF8sCVnTNvrIvoSdcZhoFzAuVy1L3xxQUQ4sfWDtwVzg1u6Yi1R3SlJugRNV2Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.18.tgz", + "integrity": "sha512-iUzw9HshVvrWci9gVXjxWS7/M/IcLvNo67vu2c/w9zKBz4hIvPRixdUpIW/iCfhldLaq9ER2hecsI9UY5z0/yA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.18.tgz", + "integrity": "sha512-XuDHFzbFEtZl0QGJi92+fmG67tfnp1iZ9VOeDkwasGyTq2VG3/5PnJnvAr+MTzFh/rNScJ3VhN+XpZyyGsN7Jw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.18.tgz", + "integrity": "sha512-MM8opLfsLK15oEXDz6iBc0t3ahu+ew9jsAmha+ovZ33hSwYgqo7YmpRITqFTfW7xA71BLEQ3jJdTsaCmhB1c9w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.18.tgz", + "integrity": "sha512-J6EoCWiy5RnFQzHrKyHXXevZ9lukQfGpnchX/zG/k/WC2nc9O9XyS1JgA8kI9VxMFggMbCPjpv7LcikriXfehw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.18.tgz", + "integrity": "sha512-HIkFuLF7CdDeki+1aCZLLbLq0hk/PHntb+z4/YCTo47JbksTD6jJEELIz92tYROmDmvMrNqUMqBi71BkJLDR+A==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.18.tgz", + "integrity": "sha512-4oqWItLLYt7IceOnElCct8T2ek5p7PmD7LN04TRJRXGo5f3HtKTgGH6PhYRFK4C2ICkq/LMUU0BVPvvlAKhm8g==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.18.tgz", + "integrity": "sha512-+AkRly5SrCEgnPhGRfub7pucASYEC2fTsxZg7VCcnozpA2+Wn/gCYy1t7LuJS67/xyJu/7noYBJncDUkbwgw2A==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.18.tgz", + "integrity": "sha512-Ttg1r9vVykMnQrE/GwYO9icKtXiuiMfRe/w74xJkeoVuvhRG+WtT6LEMOf58Yl63yd77lhHzO8Y55R8CC3XALA==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.18.tgz", + "integrity": "sha512-xX1Tt4o5jUMma0vJsXp5eRZA9nOuyigb2dKJMMzZRmzMxLYGE9PaKKSqHPzPvSQgM8ZOEacSTQwDQcwWfh0xmQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.18.tgz", + "integrity": "sha512-4VVlGI5K2kociZlW3lSN8VjG3TW5yQIlAcfCdBXMgGjJxZll15Fa4ocRHXHvIVVnwlibCw/NQajJrNDiqqpiiw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.18.tgz", + "integrity": "sha512-PApTsgH1jLYuyy3tSCz9De82Gq5qXwi7vImVZhEzTgX1C4150Cp5M2ZfL3pLvbCvbEHL0oJeC6pd6podtv8Y5w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.18.tgz", + "integrity": "sha512-J2XjWjx/SP+4x0H4r6dz3Vzb5WVkg7re40Do9K7HJ3sK2/xcmZrWwakXlSwaMvOkvruLJCD4CL/3wqsIR/thgg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.18.tgz", + "integrity": "sha512-XwRJxRQvkuEtS0hIIt29QrqPJ+JzMJSNYHJw4ae/mc6uEarfRG1ceyg4HmmWiBdL/YCb6g7N5BLbSvmRJRYZHw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.0.tgz", + "integrity": "sha512-K+NU2HDCEem4sClgHH4ZZXwdJeNFkJo+hRk479DIwdIviAPN2hFJH1KHHwg8CxHQXvi0M5XY4deTXINfIiSG6w==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.19.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz", + "integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": ">=7.24.0 <7.24.7" + } + }, + "node_modules/@vitest/mocker": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.5.tgz", + "integrity": "sha512-xLL3lkDegJZw+MGoGaCCsFayDZthGgpAtr3Vziyfc4p7xH89K7KRPcRBBh/kEYm0Aqkt5DtTmkYpBtRV/FrHZg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.0.5", + "estree-walker": "^3.0.3", + "magic-string": "^1.4.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9 || ^3.0.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/spy": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.5.tgz", + "integrity": "sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "peer": true, + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/mri": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", + "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "peer": true, + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/package-manager-detector": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/package-manager-detector/-/package-manager-detector-1.9.0.tgz", + "integrity": "sha512-zAMfbta9nPA8AKkA4WdmNAT8R8s6Dk0/xwPsqNnRidMFcLo1YkLuPDTgs2f64XdzS8vbLNnoJ+uUIkgbz7oRHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "peer": true, + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/publint": { + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/publint/-/publint-0.3.25.tgz", + "integrity": "sha512-WMMbn/d7JqRlfXQL/JUI4n5skC8cJ5WVr8/wT5mmiYWkUdENkZr1I5rgs2+dQPVRgoJd+JRYtB46MTsuDylw9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@publint/pack": "^0.1.7", + "package-manager-detector": "^1.8.0", + "picocolors": "^1.1.1", + "sade": "^1.8.1" + }, + "bin": { + "publint": "src/cli.js" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://bjornlu.com/sponsor" + } + }, + "node_modules/rolldown": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.18.tgz", + "integrity": "sha512-C1uuT3UR60SShuCaPQFAAZyefJCWZlAKB02BV3BuPE2Rs4fevRQltEKoFO2tV5W9/eJhU5RieV6vJj3euulfNQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@oxc-project/types": "=0.156.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.18", + "@rolldown/binding-android-arm64": "1.2.18", + "@rolldown/binding-darwin-arm64": "1.2.18", + "@rolldown/binding-darwin-x64": "1.2.18", + "@rolldown/binding-freebsd-x64": "1.2.18", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.18", + "@rolldown/binding-linux-arm64-gnu": "1.2.18", + "@rolldown/binding-linux-arm64-musl": "1.2.18", + "@rolldown/binding-linux-ppc64-gnu": "1.2.18", + "@rolldown/binding-linux-s390x-gnu": "1.2.18", + "@rolldown/binding-linux-x64-gnu": "1.2.18", + "@rolldown/binding-linux-x64-musl": "1.2.18", + "@rolldown/binding-openharmony-arm64": "1.2.18", + "@rolldown/binding-win32-arm64-msvc": "1.2.18", + "@rolldown/binding-win32-x64-msvc": "1.2.18" + } + }, + "node_modules/sade": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz", + "integrity": "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mri": "^1.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz", + "integrity": "sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "8.3.7", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.7.tgz", + "integrity": "sha512-oxh0dMxrayBr33ScJvvBJ2HBQ2jc1TBrXKR2NyL/MJ9WPuX19mN2DXWUmywKdyw5RFVQBo8hmtb2FMC0LHrnng==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.5.tgz", + "integrity": "sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.0.5", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.3", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.2", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.0.5", + "@vitest/browser-preview": "5.0.5", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.0.5", + "@vitest/coverage-v8": "5.0.5", + "@vitest/ui": "5.0.5", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + } + } +} diff --git a/ui/lib/harness/package.json b/ui/lib/harness/package.json new file mode 100644 index 000000000000..b93deffb207d --- /dev/null +++ b/ui/lib/harness/package.json @@ -0,0 +1,39 @@ +{ + "name": "@ggml-org/llama-harness", + "version": "0.1.0", + "description": "Headless agentic loop for llama.cpp frontend apps.", + "homepage": "https://github.com/ggml-org/llama.cpp/tree/master/ui/lib/harness", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/ggml-org/llama.cpp.git", + "directory": "ui/lib/harness" + }, + "files": [ + "dist" + ], + "type": "module", + "sideEffects": false, + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "scripts": { + "build": "tsc -p tsconfig.build.json", + "check": "tsc --noEmit", + "prepack": "npm run build && publint", + "test": "vitest --run" + }, + "devDependencies": { + "@types/node": "^24", + "publint": "^0.3.21", + "typescript": "^6.0.3", + "vitest": "5.0.5" + }, + "engines": { + "node": ">=20" + } +} diff --git a/ui/lib/harness/src/abort.ts b/ui/lib/harness/src/abort.ts new file mode 100644 index 000000000000..636dd21ed718 --- /dev/null +++ b/ui/lib/harness/src/abort.ts @@ -0,0 +1,17 @@ +const ABORT_ERROR_NAME = "AbortError"; +// TypeErrors a browser throws when a fetch stream is cut by page unload, navigation or a network drop +const ABORT_LIKE_MESSAGE_PATTERNS = [ + /input stream/i, + /network connection was lost/i, + /load failed/i, +]; + +export function isAbortError(error: unknown): boolean { + if (!(error instanceof Error)) return false; + + if (error.name === ABORT_ERROR_NAME) return true; + + return ( + error instanceof TypeError && ABORT_LIKE_MESSAGE_PATTERNS.some((re) => re.test(error.message)) + ); +} diff --git a/ui/lib/harness/src/harness.ts b/ui/lib/harness/src/harness.ts new file mode 100644 index 000000000000..e58e7ea25188 --- /dev/null +++ b/ui/lib/harness/src/harness.ts @@ -0,0 +1,375 @@ +import { isAbortError } from "./abort.js"; +import type { + DoneReason, + Harness, + HarnessEvent, + InferenceClient, + LlmTimings, + LlmTotals, + Message, + PartialToolCall, + RunOptions, + RunTimings, + Timings, + Tool, + ToolCall, + ToolResult, + TurnStats, +} from "./types.js"; + +/** The result of a tool call that did not run because the run was interrupted. */ +export const INTERRUPTED_TOOL_RESULT = "Tool execution was interrupted by a new user message."; + +function emptyTotals(): LlmTotals { + return { predicted_ms: 0, predicted_n: 0, prompt_ms: 0, prompt_n: 0 }; +} + +function addTimings(totals: LlmTotals, timings: LlmTimings): LlmTotals { + return { + predicted_ms: totals.predicted_ms + (timings.predicted_ms ?? 0), + predicted_n: totals.predicted_n + (timings.predicted_n ?? 0), + prompt_ms: totals.prompt_ms + (timings.prompt_ms ?? 0), + prompt_n: totals.prompt_n + (timings.prompt_n ?? 0), + }; +} + +function toToolCalls(partial: PartialToolCall[]): ToolCall[] { + return partial.map((call, index) => ({ + function: { + arguments: call?.function?.arguments ?? "", + name: call?.function?.name ?? "", + }, + id: call?.id ?? `tool_${index}`, + type: "function", + })); +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +/** + * The default loop: stream a turn, run the tools the model called, give it the results, and repeat until it answers + * without a tool call. It keeps no state between runs and stores nothing: the app owns the conversation. + */ +export function createHarness(client: InferenceClient): Harness { + return { + run: (messages, tools, signal, options) => run(client, messages, tools, signal, options), + }; +} + +async function* run( + client: InferenceClient, + messages: Message[], + tools: Tool[], + signal?: AbortSignal, + options: RunOptions = {}, +): AsyncGenerator { + const { interrupted = () => false, maxTurns = Infinity, onTurnLimit } = options; + const history = [...messages]; + const definitions = tools.map((tool) => tool.definition); + const toolsByName = new Map(tools.map((tool) => [tool.definition.function.name, tool])); + const totals: RunTimings = { + llm: emptyTotals(), + perTurn: [], + toolCalls: [], + toolCallsCount: 0, + toolsMs: 0, + turns: 0, + }; + + let lastTimings: LlmTimings | undefined; + let turn = 0; + + const runTimings = (): Timings | undefined => { + if (totals.toolCallsCount === 0) return lastTimings; + + return { + agentic: totals, + cache_n: lastTimings?.cache_n, + predicted_ms: lastTimings?.predicted_ms, + predicted_n: lastTimings?.predicted_n, + prompt_ms: lastTimings?.prompt_ms, + prompt_n: lastTimings?.prompt_n, + }; + }; + const done = (reason: DoneReason): HarnessEvent => ({ + reason, + timings: runTimings(), + type: "done", + }); + + while (true) { + if (turn >= maxTurns) { + const more = onTurnLimit ? await onTurnLimit(signal) : false; + + if (!more || signal?.aborted) { + yield done(signal?.aborted ? "aborted" : "turn_limit"); + + return; + } + + turn = 0; + } + + totals.turns = turn + 1; + + if (signal?.aborted) { + yield done("aborted"); + + return; + } + + yield { turn: turn + 1, type: "turn_start" }; + + let content = ""; + let reasoning = ""; + let partialCalls: PartialToolCall[] = []; + let turnTimings: LlmTimings | undefined; + + const stats: TurnStats = { llm: emptyTotals(), toolCalls: [], toolsMs: 0, turn: turn + 1 }; + // the turn's message when the run ends after it: what streamed so far, with the run's timings + const lastMessage = (toolCalls?: ToolCall[]): HarnessEvent => ({ + content, + final: true, + reasoning: reasoning || undefined, + timings: runTimings(), + toolCalls, + type: "message", + }); + + try { + const stream = client.stream({ + messages: history, + signal, + tools: definitions.length > 0 ? definitions : undefined, + }); + + for await (const event of stream) { + if (event.type === "text") { + content += event.delta; + yield event; + } else if (event.type === "reasoning") { + reasoning += event.delta; + yield event; + } else if (event.type === "tool_calls") { + partialCalls = event.toolCalls; + yield { toolCalls: partialCalls, type: "tool_call_delta" }; + } else if (event.type === "timings") { + if (event.timings) { + lastTimings = event.timings; + turnTimings = event.timings; + } + + yield { ...event, llm: event.timings && addTimings(totals.llm, event.timings) }; + } else { + yield event; + } + } + + if (turnTimings) { + totals.llm = addTimings(totals.llm, turnTimings); + stats.llm = addTimings(stats.llm, turnTimings); + } + } catch (error) { + // keep the partial output in both cases + yield lastMessage(); + + if (signal?.aborted) { + yield done("aborted"); + } else { + yield { + error: error instanceof Error ? error : new Error("LLM stream error"), + timings: runTimings(), + type: "error", + }; + } + + return; + } + + // a client can swallow the abort and end the stream normally: do not take a cut tool call for a complete one + if (signal?.aborted) { + yield lastMessage(); + yield done("aborted"); + + return; + } + + if (interrupted()) { + yield lastMessage(partialCalls.length > 0 ? toToolCalls(partialCalls) : undefined); + yield done("interrupted"); + + return; + } + + if (partialCalls.length === 0) { + totals.perTurn.push(stats); + + const timings = runTimings(); + + yield lastMessage(); + + if (timings) yield { timings, type: "turn_end" }; + + yield done("complete"); + + return; + } + + const toolCalls = toToolCalls(partialCalls); + + yield { + content, + final: false, + reasoning: reasoning || undefined, + timings: turnTimings, + toolCalls, + type: "message", + }; + + history.push({ + content: content || undefined, + reasoning_content: reasoning || undefined, + role: "assistant", + tool_calls: toolCalls, + }); + + for (let i = 0; i < toolCalls.length; i++) { + const toolCall = toolCalls[i]; + + if (signal?.aborted) { + yield done("aborted"); + + return; + } + + if (interrupted()) { + for (const skippedCall of toolCalls.slice(i)) { + yield { + result: { content: INTERRUPTED_TOOL_RESULT }, + skipped: true, + toolCall: skippedCall, + type: "tool_result", + }; + + history.push({ + content: INTERRUPTED_TOOL_RESULT, + role: "tool", + tool_call_id: skippedCall.id, + }); + } + + break; + } + + yield { toolCall, type: "tool_call" }; + + const tool = toolsByName.get(toolCall.function.name); + const startTime = performance.now(); + + let result: ToolResult; + + if (!tool) { + result = { content: `Error: Unknown tool: ${toolCall.function.name}`, isError: true }; + } else { + // only the latest update matters, so a slow consumer skips the ones in between + let pendingUpdate: string | undefined; + let settled = false; + let wake: (() => void) | undefined; + + const notify = () => { + wake?.(); + wake = undefined; + }; + const execution = Promise.resolve() + .then(() => + tool.execute(toolCall, { + signal, + update: (updated) => { + pendingUpdate = updated; + notify(); + }, + }), + ) + .finally(() => { + settled = true; + notify(); + }); + + // the rejection is handled below, after the updates are drained + execution.catch(() => {}); + + while (true) { + if (pendingUpdate !== undefined) { + const updated = pendingUpdate; + + pendingUpdate = undefined; + yield { content: updated, toolCall, type: "tool_update" }; + } else if (settled) { + break; + } else { + await new Promise((resolve) => (wake = resolve)); + } + } + + try { + result = await execution; + } catch (error) { + if (isAbortError(error)) { + yield done("aborted"); + + return; + } + + result = { content: `Error: ${errorMessage(error)}`, isError: true }; + } + } + + const durationMs = Math.round(result.durationMs ?? performance.now() - startTime); + const timing = { + duration_ms: durationMs, + name: toolCall.function.name, + success: !result.isError, + }; + + totals.toolCalls.push(timing); + totals.toolCallsCount++; + totals.toolsMs += durationMs; + stats.toolCalls.push(timing); + stats.toolsMs += durationMs; + + if (signal?.aborted) { + yield done("aborted"); + + return; + } + + yield { result, skipped: false, toolCall, type: "tool_result" }; + + history.push({ + content: result.parts?.length + ? [{ text: result.content, type: "text" }, ...result.parts] + : result.content, + role: "tool", + tool_call_id: toolCall.id, + }); + } + + if (stats.toolCalls.length > 0) { + totals.perTurn.push(stats); + + const timings = runTimings(); + + if (timings) yield { timings, type: "turn_end" }; + } + + if (interrupted()) { + yield done("interrupted"); + + return; + } + + turn++; + } +} diff --git a/ui/lib/harness/src/index.ts b/ui/lib/harness/src/index.ts new file mode 100644 index 000000000000..1cbaf8aded43 --- /dev/null +++ b/ui/lib/harness/src/index.ts @@ -0,0 +1,5 @@ +export { isAbortError } from "./abort.js"; +export { createHarness, INTERRUPTED_TOOL_RESULT } from "./harness.js"; +export { createOpenAIClient, type OpenAIClientOptions } from "./openai-client.js"; +export type * from "./types.js"; +export * from "./trace/index.js"; diff --git a/ui/lib/harness/src/openai-client.ts b/ui/lib/harness/src/openai-client.ts new file mode 100644 index 000000000000..c1c45d9b840d --- /dev/null +++ b/ui/lib/harness/src/openai-client.ts @@ -0,0 +1,143 @@ +import type { InferenceClient, InferenceEvent, PartialToolCall } from "./types.js"; + +const CHAT_COMPLETIONS_PATH = "/v1/chat/completions"; +const SSE_DATA_PREFIX = "data:"; +const SSE_DONE = "[DONE]"; + +export interface OpenAIClientOptions { + /** Server root, e.g. `http://localhost:8080`. */ + baseUrl: string; + apiKey?: string; + model?: string; + /** Extra fields of the request body, e.g. `temperature`. */ + params?: Record; + headers?: Record; + /** Default: the global fetch. */ + fetch?: typeof fetch; +} + +interface ToolCallDelta extends PartialToolCall { + index?: number; +} + +function mergeToolCallDeltas(toolCalls: PartialToolCall[], deltas: ToolCallDelta[]): void { + for (const delta of deltas) { + // without an index, a delta with an id opens a call and any other one continues the last call + const index = + delta.index ?? (delta.id || toolCalls.length === 0 ? toolCalls.length : toolCalls.length - 1); + const call = (toolCalls[index] ??= { function: { arguments: "", name: "" } }); + + if (delta.id) call.id = delta.id; + + if (delta.type) call.type = delta.type; + + call.function = { + arguments: (call.function?.arguments ?? "") + (delta.function?.arguments ?? ""), + name: (call.function?.name ?? "") + (delta.function?.name ?? ""), + }; + } +} + +async function errorFromResponse(response: Response): Promise { + const body = await response.text().catch(() => ""); + + let message = body; + + try { + message = JSON.parse(body).error?.message ?? body; + } catch { + // not JSON: keep the body text + } + + return new Error(`HTTP ${response.status}${message ? `: ${message}` : ""}`); +} + +/** + * An inference client for llama-server's chat completions endpoint. It reads the `timings` and + * `prompt_progress` fields llama-server adds. + */ +export function createOpenAIClient(options: OpenAIClientOptions): InferenceClient { + const { apiKey, baseUrl, headers, model, params } = options; + const url = baseUrl.replace(/\/+$/, "") + CHAT_COMPLETIONS_PATH; + + return { + async *stream({ messages, signal, tools }): AsyncGenerator { + const response = await (options.fetch ?? fetch)(url, { + body: JSON.stringify({ ...params, messages, model, stream: true, tools }), + headers: { + "Content-Type": "application/json", + ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}), + ...headers, + }, + method: "POST", + signal, + }); + + if (!response.ok) throw await errorFromResponse(response); + + if (!response.body) throw new Error("The response has no body"); + + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + const toolCalls: PartialToolCall[] = []; + + let buffer = ""; + let completionId: string | undefined; + let modelName: string | undefined; + + try { + while (true) { + const { done, value } = await reader.read(); + + if (done) return; + + buffer += decoder.decode(value, { stream: true }); + + const lines = buffer.split("\n"); + + buffer = lines.pop() ?? ""; + + for (const line of lines) { + if (!line.startsWith(SSE_DATA_PREFIX)) continue; + + const data = line.slice(SSE_DATA_PREFIX.length).trim(); + + if (data === SSE_DONE) return; + + const chunk = JSON.parse(data); + + if (chunk.error) throw new Error(chunk.error.message ?? "Stream error"); + + if (chunk.id && chunk.id !== completionId) { + completionId = chunk.id; + yield { id: chunk.id, type: "completion_id" }; + } + + if (chunk.model && chunk.model !== modelName) { + modelName = chunk.model; + yield { model: chunk.model, type: "model" }; + } + + const delta = chunk.choices?.[0]?.delta; + const reasoning = delta?.reasoning_content ?? delta?.reasoning; + + if (reasoning) yield { delta: reasoning, type: "reasoning" }; + + if (delta?.content) yield { delta: delta.content, type: "text" }; + + if (delta?.tool_calls?.length) { + mergeToolCallDeltas(toolCalls, delta.tool_calls); + yield { toolCalls: toolCalls.map((call) => ({ ...call })), type: "tool_calls" }; + } + + if (chunk.timings || chunk.prompt_progress) { + yield { progress: chunk.prompt_progress, timings: chunk.timings, type: "timings" }; + } + } + } + } finally { + reader.cancel().catch(() => {}); + } + }, + }; +} diff --git a/ui/lib/harness/src/trace/args.ts b/ui/lib/harness/src/trace/args.ts new file mode 100644 index 000000000000..7349ee49579d --- /dev/null +++ b/ui/lib/harness/src/trace/args.ts @@ -0,0 +1,158 @@ +// Reading tool-call arguments while they stream: a lenient parse for cut-off +// JSON, and a targeted read of one string field for arguments that hold +// whole files. + +const PARTIAL_JSON_CACHE_MAX_SIZE = 32; +const partialJsonCache = new Map | null>(); + +function asObject(value: unknown): Record | null { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : null; +} + +/** + * Parse tool-call arguments that may be cut short mid-stream: an open string + * and open containers are closed so the keys received so far can be read. + * Null when the arguments are not an object. Memoized, since a trace parses the + * same arguments on every streamed chunk. + */ +export function parsePartialJsonArgs(args: string): Record | null { + const cached = partialJsonCache.get(args); + + if (cached !== undefined) return cached; + + let result: Record | null; + + try { + result = asObject(JSON.parse(args)); + } catch { + result = scanPartialJson(args); + } + + if (partialJsonCache.size >= PARTIAL_JSON_CACHE_MAX_SIZE) { + partialJsonCache.delete(partialJsonCache.keys().next().value!); + } + + partialJsonCache.set(args, result); + + return result; +} + +function scanPartialJson(args: string): Record | null { + let inString = false; + let escape = false; + + const stack: ("{" | "[")[] = []; + + for (const ch of args) { + if (escape) { + escape = false; + + continue; + } + + if (ch === "\\" && inString) { + escape = true; + + continue; + } + + if (ch === '"') { + inString = !inString; + + continue; + } + + if (inString) continue; + + if (ch === "{" || ch === "[") stack.push(ch); + else if (ch === "}" || ch === "]") { + if (stack.pop() !== (ch === "}" ? "{" : "[")) return null; + } + } + + let completed = args; + + // a dangling escape: keep the backslash as a literal so the string can close + if (escape) completed += "\\"; + + if (inString) completed += '"'; + else completed = completed.replace(/,?\s*$/, ""); + + for (let i = stack.length - 1; i >= 0; i--) completed += stack[i] === "{" ? "}" : "]"; + + try { + return asObject(JSON.parse(completed)); + } catch { + return null; + } +} + +const fieldPatterns = new Map(); + +/** + * Read one string field out of tool-call arguments without parsing them all: + * write and edit tools carry whole files, and a trace line needs only the + * path. The first of `keys` that holds a string wins; undefined when none does. + */ +export function extractToolArgString(args: string, keys: readonly string[]): string | undefined { + for (const key of keys) { + let pattern = fieldPatterns.get(key); + + if (!pattern) { + pattern = new RegExp(`"${key}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`); + fieldPatterns.set(key, pattern); + } + + const match = pattern.exec(args); + + if (!match) continue; + + try { + const value: unknown = JSON.parse(`"${match[1]}"`); + + if (typeof value === "string") return value; + } catch { + // the next key, then the caller's full parse + } + } + + return undefined; +} + +/** The file name of a path, for a trace line; undefined without a path. */ +export function fileNameFromPath(path: string | undefined): string | undefined { + if (!path) return undefined; + + return path.split(/[\\/]/).pop() || path; +} + +/** + * Memoize `fn` by a string key, holding at most `maxSize` results; a full cache + * is emptied, which suits values that are cheap to rebuild. `keyOf` returns + * null for a call not worth caching. + */ +export function memoizeBounded( + fn: (...args: Args) => Result, + keyOf: (...args: Args) => string | null, + maxSize: number, +): (...args: Args) => Result { + const cache = new Map(); + + return (...args) => { + const key = keyOf(...args); + + if (key === null) return fn(...args); + + if (cache.has(key)) return cache.get(key) as Result; + + const result = fn(...args); + + if (cache.size >= maxSize) cache.clear(); + + cache.set(key, result); + + return result; + }; +} diff --git a/ui/lib/harness/src/trace/index.ts b/ui/lib/harness/src/trace/index.ts new file mode 100644 index 000000000000..75dfc649e255 --- /dev/null +++ b/ui/lib/harness/src/trace/index.ts @@ -0,0 +1,33 @@ +export { extractToolArgString, fileNameFromPath, parsePartialJsonArgs } from "./args.js"; +export { + createTracePhraser, + formatToolCallLine, + groupToolCallRuns, + humanizeArgKey, + isReasoningStep, + isToolCallRunning, + isToolCallStep, + LLAMA_SERVER_TOOL_PHRASING, + llamaServerToolResolver, + simpleToolArgFields, + TOOL_ARG_PATH_KEYS, + TOOL_CALL_MAIN_ARG_KEYS, + TOOL_CALL_SHOWN_ARG_DEFAULT, + TOOL_CALL_SIMPLE_ARG_MAX_CHARS, + TOOL_CALL_SUMMARY, + TOOL_CALL_TARGET_MAX_CHARS, + TOOL_CALL_THINKING_LABEL, + toolCallPath, + type TracePhraser, + type TracePhraserOptions, +} from "./phrasing.js"; +export { ToolCallSummaryKind, TraceStepType } from "./types.js"; +export type { + ResolvedToolCall, + ToolArgField, + ToolCallDescription, + ToolCallInput, + ToolCallPhrasing, + ToolCallResolver, + TraceStep, +} from "./types.js"; diff --git a/ui/lib/harness/src/trace/phrasing.ts b/ui/lib/harness/src/trace/phrasing.ts new file mode 100644 index 000000000000..1cbd02508574 --- /dev/null +++ b/ui/lib/harness/src/trace/phrasing.ts @@ -0,0 +1,497 @@ +// Plain-language lines for the tool calls of an agent trace: what one call did +// ("Read a file sheet_new.jpg"), what it is doing now ("Reading package.json") +// and what a run of calls did ("Ran 3 commands, read 2 files"). A call that +// has the argument the app picks (`description` by default) shows it as the +// model wrote it. Otherwise the app's resolvers phrase it, then llama-server's +// built-in tools, then a phrasing table, and any other tool reads as +// "Used " with its main argument. + +import { extractToolArgString, fileNameFromPath, memoizeBounded, parsePartialJsonArgs } from "./args.js"; +import { + type ResolvedToolCall, + type ToolArgField, + type ToolCallDescription, + type ToolCallInput, + type ToolCallPhrasing, + type ToolCallResolver, + ToolCallSummaryKind, + type TraceStep, + TraceStepType, +} from "./types.js"; + +/** Longest target shown after the verb before it is cut with "...". */ +export const TOOL_CALL_TARGET_MAX_CHARS = 60; + +/** Arguments of a short, one-line value read as fields instead of JSON. */ +export const TOOL_CALL_SIMPLE_ARG_MAX_CHARS = 200; + +/** The argument a call's line shows when the call has it: the model's own words for it. */ +export const TOOL_CALL_SHOWN_ARG_DEFAULT = "description"; + +/** Live title of a run of calls while the model thinks inside it. */ +export const TOOL_CALL_THINKING_LABEL = "Thinking"; + +/** Arguments a tool without a phrasing is described by; the first one present wins. */ +export const TOOL_CALL_MAIN_ARG_KEYS: readonly string[] = [ + "query", + "q", + "path", + "file_path", + "filePath", + "url", + "name", + "command", + "pattern", + "prompt", + "text", + "id", +]; + +/** Argument names a path can come under. */ +export const TOOL_ARG_PATH_KEYS: readonly string[] = ["path", "file_path", "filePath"]; + +function counted(n: number, singular: string, plural: string): string { + return `${n} ${n === 1 ? singular : plural}`; +} + +/** The group summary's clause per kind, in lower case; the summary capitalizes the first. */ +export const TOOL_CALL_SUMMARY: Readonly string>> = { + [ToolCallSummaryKind.COMMAND]: (n) => `ran ${counted(n, "command", "commands")}`, + [ToolCallSummaryKind.EDIT]: (n) => `edited ${counted(n, "file", "files")}`, + [ToolCallSummaryKind.LOAD_TOOLS]: (n) => `loaded ${counted(n, "tool", "tools")}`, + [ToolCallSummaryKind.OTHER]: (n) => `used ${counted(n, "tool", "tools")}`, + [ToolCallSummaryKind.READ]: (n) => `read ${counted(n, "file", "files")}`, + [ToolCallSummaryKind.SCRIPT]: (n) => `ran ${counted(n, "script", "scripts")}`, + [ToolCallSummaryKind.SEARCH]: (n) => (n === 1 ? "searched once" : `searched ${n} times`), + [ToolCallSummaryKind.VIEW]: (n) => `viewed ${counted(n, "media file", "media files")}`, + [ToolCallSummaryKind.WRITE]: (n) => `wrote ${counted(n, "file", "files")}`, +}; + +/** How llama-server's built-in tools read (`--tools`). */ +export const LLAMA_SERVER_TOOL_PHRASING: Readonly> = { + edit_file: { object: "a file", past: "Edited", present: "Editing", summary: ToolCallSummaryKind.EDIT }, + exec_shell_command: { + object: "a command", + past: "Ran", + present: "Running", + summary: ToolCallSummaryKind.COMMAND, + }, + file_glob_search: { + object: "files", + past: "Listed", + present: "Listing", + quoteTarget: true, + summary: ToolCallSummaryKind.SEARCH, + targetObject: "files matching", + }, + get_info: { object: "runtime info", past: "Checked", present: "Checking", summary: ToolCallSummaryKind.OTHER }, + grep_search: { + object: "files", + past: "Searched", + present: "Searching", + quoteTarget: true, + summary: ToolCallSummaryKind.SEARCH, + targetObject: "for", + }, + read_file: { object: "a file", past: "Read", present: "Reading", summary: ToolCallSummaryKind.READ }, + write_file: { object: "a file", past: "Wrote", present: "Writing", summary: ToolCallSummaryKind.WRITE }, +}; + +function stringArg(args: Record | null, key: string): string | undefined { + const value = args?.[key]; + + return typeof value === "string" && value.trim() ? value : undefined; +} + +/** The path of a call, read without parsing arguments that may hold a whole file. */ +export function toolCallPath(call: ToolCallInput): string | undefined { + return extractToolArgString(call.rawArgs, TOOL_ARG_PATH_KEYS) ?? stringArg(call.args(), "path"); +} + +/** Phrases llama-server's built-in tools, with what each acted on. */ +export const llamaServerToolResolver: ToolCallResolver = (call) => { + const phrasing = LLAMA_SERVER_TOOL_PHRASING[call.name]; + + if (!phrasing) return undefined; + + switch (call.name) { + case "read_file": + case "write_file": + case "edit_file": + return { phrasing, target: fileNameFromPath(toolCallPath(call)) }; + + case "exec_shell_command": + // the targeted read keeps the command in the line while a later + // argument still streams and the JSON does not parse + return { + phrasing, + target: stringArg(call.args(), "command") ?? extractToolArgString(call.rawArgs, ["command"]), + }; + + case "grep_search": + return { phrasing, target: stringArg(call.args(), "pattern") }; + + case "file_glob_search": { + const include = stringArg(call.args(), "include"); + + return { phrasing, target: include && include !== "**" ? include : undefined }; + } + } + + return { phrasing }; +}; + +function shorten(text: string): string { + const oneLine = text.replace(/\s+/g, " ").trim(); + + return oneLine.length > TOOL_CALL_TARGET_MAX_CHARS + ? `${oneLine.slice(0, TOOL_CALL_TARGET_MAX_CHARS - 3)}...` + : oneLine; +} + +function genericMainArg(args: Record | null): string | undefined { + if (!args) return undefined; + + for (const key of TOOL_CALL_MAIN_ARG_KEYS) { + const value = stringArg(args, key); + + if (value) return value; + } + + for (const value of Object.values(args)) { + if (typeof value === "number") return String(value); + + if (typeof value === "string" && value.trim() && value.length <= TOOL_CALL_TARGET_MAX_CHARS) { + return value; + } + } + + return undefined; +} + +function genericPhrasing(toolName: string): ToolCallPhrasing { + return { + object: toolName, + past: "Used", + present: "Using", + summary: ToolCallSummaryKind.OTHER, + targetObject: toolName, + }; +} + +/** Results each cache below holds. */ +const CACHE_MAX_SIZE = 256; +/** Arguments longer than this (whole files) are not worth holding as cache keys. */ +const CACHE_MAX_ARGS_CHARS = 2000; + +/** An argument name an app can pick: a plain key, so it is safe in a pattern. */ +const SHOWN_ARG_PATTERN = /^[\w-]+$/; + +/** The value of the argument a call's line shows, when the call has it. */ +function shownArgValue(toolArgs: string, shownArg: string | null): string | undefined { + if (!shownArg || !toolArgs || !SHOWN_ARG_PATTERN.test(shownArg)) return undefined; + + const value = + toolArgs.length <= CACHE_MAX_ARGS_CHARS + ? stringArg(parsePartialJsonArgs(toolArgs), shownArg) + : extractToolArgString(toolArgs, [shownArg]); + + return value?.trim() || undefined; +} + +/** One line of plain text for a description, e.g. `Searched for 'issue'`. */ +export function formatToolCallLine(description: ToolCallDescription): string { + if (!description.target) return description.label; + + const target = description.quoted ? `'${description.target}'` : description.target; + + return `${description.label} ${target}`; +} + +export function isToolCallStep(step: TraceStep): boolean { + return ( + step.type === TraceStepType.TOOL_CALL || + step.type === TraceStepType.TOOL_CALL_PENDING || + step.type === TraceStepType.TOOL_CALL_STREAMING + ); +} + +export function isReasoningStep(step: TraceStep): boolean { + return step.type === TraceStepType.REASONING || step.type === TraceStepType.REASONING_PENDING; +} + +/** True while the call has no result yet and the reply is still streaming. */ +export function isToolCallRunning(step: TraceStep, isStreaming: boolean): boolean { + return ( + isStreaming && + (step.type === TraceStepType.TOOL_CALL_PENDING || step.type === TraceStepType.TOOL_CALL_STREAMING) + ); +} + +export interface TracePhraserOptions { + /** The app's own tools, tried in order before llama-server's built-in ones. */ + resolvers?: readonly ToolCallResolver[]; + /** Phrasing for tools whose line names no target, by tool name. */ + phrasings?: Readonly>; +} + +export interface TracePhraser { + /** + * One tool call as a short sentence, in the past tense once it is done and + * the present tense while `running`. `shownArg` names the argument shown + * instead when the call has it (null for none). + */ + describeToolCall( + toolName: string | undefined, + toolArgs: string | undefined, + running?: boolean, + shownArg?: string | null, + ): ToolCallDescription; + /** A run of calls in one line, e.g. "Ran 3 commands, read 2 files". */ + summarizeToolCalls(steps: readonly TraceStep[]): string; + /** + * What a run of calls is doing now ("Running a command", "Thinking"): the + * model thinking at its end, or the last call still running; null when neither. + */ + describeToolActivity( + steps: readonly TraceStep[], + isStreaming: boolean, + executingToolCallId?: string | null, + shownArgFor?: (toolName: string | undefined) => string | null, + ): string | null; +} + +/** Phrasing for an app's traces: its own tools first, then llama-server's, then any tool. */ +export function createTracePhraser(options: TracePhraserOptions = {}): TracePhraser { + const resolvers = [...(options.resolvers ?? []), llamaServerToolResolver]; + const phrasings = options.phrasings ?? {}; + + function resolveCall(name: string, rawArgs: string): ResolvedToolCall { + let parsed: Record | null | undefined; + + const call: ToolCallInput = { + args: () => (parsed === undefined ? (parsed = rawArgs ? parsePartialJsonArgs(rawArgs) : null) : parsed), + name, + rawArgs, + }; + + for (const resolve of resolvers) { + const resolved = resolve(call); + + if (resolved) return resolved; + } + + const known = phrasings[name]; + + if (known) return { phrasing: known }; + + return { phrasing: genericPhrasing(name), target: genericMainArg(call.args()) }; + } + + function buildDescription( + name: string, + args: string, + running: boolean, + shownArg: string | null, + ): ToolCallDescription { + const { count = 1, phrasing, target } = resolveCall(name, args); + const shown = shownArgValue(args, shownArg); + // an argument the line already shows as its target (a shell command) would only repeat it + const described = shown && shown !== target?.trim() ? shown : undefined; + + if (described) { + return { + count, + described: true, + // as the model wrote it: rewriting its tense by rule mangles anything + // that does not start with a plain verb + label: shorten(described).replace(/[.\s]+$/, ""), + quoted: false, + summary: phrasing.summary, + }; + } + + const verb = running ? phrasing.present : phrasing.past; + const shortTarget = target ? shorten(target) : undefined; + const object = shortTarget ? phrasing.targetObject : phrasing.object; + + return { + count, + label: object ? `${verb} ${object}` : verb, + quoted: Boolean(phrasing.quoteTarget && shortTarget), + summary: phrasing.summary, + target: shortTarget, + }; + } + + // A trace is rebuilt on every streamed chunk, so the same finished call is + // described again and again: remember the answer for its arguments. Every + // caller of one call reads the same frozen object. + const describeCached = memoizeBounded( + (name: string, args: string, running: boolean, shownArg: string) => + Object.freeze(buildDescription(name, args, running, shownArg || null)), + (name, args, running, shownArg) => + args.length <= CACHE_MAX_ARGS_CHARS ? `${running ? 1 : 0}\0${shownArg}\0${name}\0${args}` : null, + CACHE_MAX_SIZE, + ); + + const describeToolCall: TracePhraser["describeToolCall"] = ( + toolName, + toolArgs, + running = false, + shownArg = TOOL_CALL_SHOWN_ARG_DEFAULT, + ) => describeCached(toolName || "a tool", toolArgs ?? "", running, shownArg ?? ""); + + return { + describeToolActivity(steps, isStreaming, executingToolCallId, shownArgFor = () => TOOL_CALL_SHOWN_ARG_DEFAULT) { + // the model thinking at the end of the run, between calls or before its answer + if (isStreaming && steps.at(-1)?.type === TraceStepType.REASONING_PENDING) { + return TOOL_CALL_THINKING_LABEL; + } + + for (let i = steps.length - 1; i >= 0; i--) { + const step = steps[i]; + const executing = step.toolCallId !== undefined && step.toolCallId === executingToolCallId; + + if (executing || isToolCallRunning(step, isStreaming)) { + return formatToolCallLine(describeToolCall(step.toolName, step.toolArgs, true, shownArgFor(step.toolName))); + } + } + + return null; + }, + + describeToolCall, + + summarizeToolCalls(steps) { + const counts = new Map(); + + for (const step of steps) { + if (!isToolCallStep(step)) continue; + + const { count, summary } = describeToolCall(step.toolName, step.toolArgs); + + counts.set(summary, (counts.get(summary) ?? 0) + count); + } + + // kinds keep the order they first appear in; other tools come last + const other = counts.get(ToolCallSummaryKind.OTHER); + + if (other !== undefined) { + counts.delete(ToolCallSummaryKind.OTHER); + counts.set(ToolCallSummaryKind.OTHER, other); + } + + const text = [...counts].map(([kind, n]) => TOOL_CALL_SUMMARY[kind](n)).join(", "); + + return text.charAt(0).toUpperCase() + text.slice(1); + }, + }; +} + +/** + * Tool arguments as labelled fields when every value is a short, one-line + * scalar; null when they need the JSON view instead. Memoized: the row that + * shows them re-renders on every chunk. + */ +export function simpleToolArgFields(toolArgs: string | undefined): ToolArgField[] | null { + return toolArgs ? argFieldsCached(toolArgs) : null; +} + +const argFieldsCached = memoizeBounded( + buildSimpleToolArgFields, + (toolArgs) => (toolArgs.length <= CACHE_MAX_ARGS_CHARS ? toolArgs : null), + CACHE_MAX_SIZE, +); + +function buildSimpleToolArgFields(toolArgs: string): ToolArgField[] | null { + let parsed: unknown; + + try { + parsed = JSON.parse(toolArgs); + } catch { + return null; + } + + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null; + + const entries = Object.entries(parsed as Record); + + if (entries.length === 0) return null; + + const fields: ToolArgField[] = []; + + for (const [key, value] of entries) { + if (value !== null && typeof value === "object") return null; + + const text = String(value); + + if (text.length > TOOL_CALL_SIMPLE_ARG_MAX_CHARS || text.includes("\n")) return null; + + fields.push({ label: humanizeArgKey(key), value: text }); + } + + return fields; +} + +/** `max_results` / `maxResults` -> `Max results`. */ +export function humanizeArgKey(key: string): string { + const words = key + .replace(/([a-z0-9])([A-Z])/g, "$1 $2") + .replace(/[_-]+/g, " ") + .trim() + .toLowerCase(); + + return words.charAt(0).toUpperCase() + words.slice(1); +} + +/** + * Split step positions into single items and runs of tool work, e.g. + * [0, [1, 2, 3], 4]. A run is the calls and all the reasoning around them, up + * to the next text, so the answer follows the work as one row: it is grouped + * once it holds `minCalls` calls, or one call with reasoning beside it. + * Reasoning with no call in reach, and text, stay apart. + */ +export function groupToolCallRuns( + steps: readonly TraceStep[], + indices: readonly number[], + minCalls: number, +): (number | number[])[] { + const items: (number | number[])[] = []; + + let run: number[] = []; + let calls = 0; + // reasoning seen since the last call: it ends the run if text follows, and + // leads into it if another call does + let thinking: number[] = []; + + const flush = () => { + const whole = [...run, ...thinking]; + + if (calls >= minCalls || (calls > 0 && whole.length > calls)) items.push(whole); + else items.push(...whole); + + run = []; + thinking = []; + calls = 0; + }; + + for (const index of indices) { + const step = steps[index]; + + if (isToolCallStep(step)) { + run.push(...thinking, index); + thinking = []; + calls++; + } else if (isReasoningStep(step)) { + thinking.push(index); + } else { + flush(); + items.push(index); + } + } + + flush(); + + return items; +} diff --git a/ui/lib/harness/src/trace/types.ts b/ui/lib/harness/src/trace/types.ts new file mode 100644 index 000000000000..f445e6805427 --- /dev/null +++ b/ui/lib/harness/src/trace/types.ts @@ -0,0 +1,94 @@ +/** + * What a step of an agent trace is: the model's text, its reasoning, or a tool + * call, finished or still in flight. Apps keep their own step type; anything + * with these values in `type` reads as a trace step. + */ +export const TraceStepType = { + REASONING: "reasoning", + REASONING_PENDING: "reasoning_pending", + TEXT: "text", + TOOL_CALL: "tool_call", + TOOL_CALL_PENDING: "tool_call_pending", + TOOL_CALL_STREAMING: "tool_call_streaming", +} as const; + +export type TraceStepType = (typeof TraceStepType)[keyof typeof TraceStepType]; + +/** One step of an agent trace, as much of it as the phrasing reads. */ +export interface TraceStep { + /** A TraceStepType value. */ + type: string; + toolCallId?: string; + toolName?: string; + /** The call's arguments as streamed: JSON, possibly cut short. */ + toolArgs?: string; +} + +/** Which clause a call counts under in a group summary ("ran 3 commands"). */ +export const ToolCallSummaryKind = { + COMMAND: "command", + EDIT: "edit", + LOAD_TOOLS: "load_tools", + OTHER: "other", + READ: "read", + SCRIPT: "script", + SEARCH: "search", + VIEW: "view", + WRITE: "write", +} as const; + +export type ToolCallSummaryKind = (typeof ToolCallSummaryKind)[keyof typeof ToolCallSummaryKind]; + +/** How a tool call reads in a trace. */ +export interface ToolCallPhrasing { + /** Verb once the call is done, e.g. "Read". */ + past: string; + /** Verb while the call runs, e.g. "Reading". */ + present: string; + /** Words after the verb when the call has no target, e.g. "a file". */ + object: string; + /** Words between the verb and the target, e.g. "for". */ + targetObject?: string; + /** Show the target in quotes, for search terms. */ + quoteTarget?: boolean; + summary: ToolCallSummaryKind; +} + +/** A tool call as one plain sentence: label, then an optional target. */ +export interface ToolCallDescription { + /** Verb and object, e.g. "Read a file" or "Searched for". */ + label: string; + /** What the call acted on, e.g. a file name or a search term. */ + target?: string; + quoted: boolean; + summary: ToolCallSummaryKind; + /** How many things the call counts as in the group summary. */ + count: number; + /** True when the label is the model's own description of the call. */ + described?: boolean; +} + +/** A tool call as a resolver sees it. */ +export interface ToolCallInput { + name: string; + /** The arguments as streamed. Whole files for write tools: read them with extractToolArgString. */ + rawArgs: string; + /** The arguments parsed leniently, cut-off JSON included; parsed on first call. */ + args(): Record | null; +} + +/** How one call reads: its phrasing, what it acted on, and how many things it counts as. */ +export interface ResolvedToolCall { + phrasing: ToolCallPhrasing; + target?: string; + count?: number; +} + +/** Phrases the calls of one tool, or of a family of tools; undefined passes the call on. */ +export type ToolCallResolver = (call: ToolCallInput) => ResolvedToolCall | undefined; + +/** A tool argument shown as a labelled field. */ +export interface ToolArgField { + label: string; + value: string; +} diff --git a/ui/lib/harness/src/types.ts b/ui/lib/harness/src/types.ts new file mode 100644 index 000000000000..9167e37ca111 --- /dev/null +++ b/ui/lib/harness/src/types.ts @@ -0,0 +1,209 @@ +// Messages and tools use the OpenAI chat-completions shapes, so they go to the endpoint as they are. + +export interface TextPart { + type: "text"; + text: string; +} + +export interface ImagePart { + type: "image_url"; + image_url: { url: string }; +} + +export interface AudioPart { + type: "input_audio"; + input_audio: { data: string; format: string }; +} + +export type ContentPart = TextPart | ImagePart | AudioPart; + +export interface ToolCall { + id: string; + type: "function"; + function: { name: string; arguments: string }; +} + +/** A tool call as it streams in: any field can still be missing. */ +export interface PartialToolCall { + id?: string; + type?: string; + function?: { name?: string; arguments?: string }; +} + +export type Message = + | { role: "system" | "user"; content: string | ContentPart[] } + | { + role: "assistant"; + content?: string | ContentPart[]; + reasoning_content?: string; + tool_calls?: ToolCall[]; + } + | { role: "tool"; tool_call_id: string; content: string | ContentPart[] }; + +export interface ToolDefinition { + type: "function"; + function: { + name: string; + description?: string; + parameters?: Record; + }; +} + +export interface ToolContext { + signal?: AbortSignal; + /** Report the output so far of a tool that streams. Each call replaces the previous content. */ + update(content: string): void; +} + +export interface ToolResult { + /** Text the model reads. */ + content: string; + /** Media the model reads after the text, e.g. an image the tool produced. */ + parts?: ContentPart[]; + isError?: boolean; + /** Set it when the tool times itself, e.g. to leave out a wait for approval. Default: the time execute took. */ + durationMs?: number; + /** App data the loop does not read. It comes back on the tool_result event. */ + details?: unknown; +} + +export interface Tool { + definition: ToolDefinition; + /** Run the call. Reject with an AbortError to end the run, with any other error to report it to the model. */ + execute(call: ToolCall, context: ToolContext): Promise; +} + +/** Token counts and times of one request, as llama-server reports them. */ +export interface LlmTimings { + cache_n?: number; + predicted_ms?: number; + predicted_n?: number; + prompt_ms?: number; + prompt_n?: number; +} + +export interface LlmTotals { + predicted_ms: number; + predicted_n: number; + prompt_ms: number; + prompt_n: number; +} + +export interface ToolCallTiming { + name: string; + duration_ms: number; + success: boolean; +} + +export interface TurnStats { + turn: number; + llm: LlmTotals; + toolCalls: ToolCallTiming[]; + toolsMs: number; +} + +/** Totals of a run: every turn's requests and tool calls. */ +export interface RunTimings { + turns: number; + toolCallsCount: number; + toolsMs: number; + toolCalls: ToolCallTiming[]; + perTurn: TurnStats[]; + llm: LlmTotals; +} + +/** The last request's timings, with the run's totals once a tool has run. */ +export interface Timings extends LlmTimings { + agentic?: RunTimings; +} + +export interface PromptProgress { + cache: number; + processed: number; + time_ms: number; + total: number; +} + +export interface InferenceRequest { + messages: Message[]; + tools?: ToolDefinition[]; + signal?: AbortSignal; +} + +export type InferenceEvent = + | { type: "text"; delta: string } + | { type: "reasoning"; delta: string } + /** Every tool call of the response so far, not only the new part. */ + | { type: "tool_calls"; toolCalls: PartialToolCall[] } + | { type: "timings"; timings?: LlmTimings; progress?: PromptProgress } + | { type: "model"; model: string } + | { type: "completion_id"; id: string }; + +/** + * One streamed chat completion. The loop needs nothing else from llama-server. + * Timings, model and completion id are optional extras. + */ +export interface InferenceClient { + stream(request: InferenceRequest): AsyncIterable; +} + +export type DoneReason = + /** The model answered without calling a tool. */ + | "complete" + | "aborted" + /** `interrupted` returned true. */ + | "interrupted" + /** The turn limit was reached and `onTurnLimit` did not grant more turns. */ + | "turn_limit"; + +export type HarnessEvent = + /** `turn` starts at 1, and again at 1 once `onTurnLimit` grants more turns. */ + | { type: "turn_start"; turn: number } + | { type: "text"; delta: string } + | { type: "reasoning"; delta: string } + | { type: "tool_call_delta"; toolCalls: PartialToolCall[] } + /** `llm` is the run's totals including the request in flight. */ + | { type: "timings"; timings?: LlmTimings; progress?: PromptProgress; llm?: LlmTotals } + | { type: "model"; model: string } + | { type: "completion_id"; id: string } + /** The assistant message of a turn. `final` is true when the run ends after it and none of its tool calls runs. */ + | { + type: "message"; + content: string; + reasoning?: string; + toolCalls?: ToolCall[]; + timings?: Timings; + final: boolean; + } + | { type: "tool_call"; toolCall: ToolCall } + | { type: "tool_update"; toolCall: ToolCall; content: string } + /** `skipped` is true when the call did not run because the run was interrupted. */ + | { type: "tool_result"; toolCall: ToolCall; result: ToolResult; skipped: boolean } + | { type: "turn_end"; timings: Timings } + | { type: "done"; reason: DoneReason; timings?: Timings } + | { type: "error"; error: Error; timings?: Timings }; + +export interface RunOptions { + /** Turns before `onTurnLimit` is asked. Default: no limit. */ + maxTurns?: number; + /** Resolve true to run `maxTurns` more turns. Default: the run ends. */ + onTurnLimit?: (signal?: AbortSignal) => Promise; + /** + * Return true to end the run at the next safe point, e.g. when the user sent a new message. Tool calls that did + * not run yet get a result that says so. Use `signal` to stop at once. + */ + interrupted?: () => boolean; +} + +/** + * The contract an app runs a loop through. `run` never throws: it ends with a `done` or an `error` event. It waits + * for the consumer between events, so the consumer can store each one before the loop goes on. + */ +export interface Harness { + run( + messages: Message[], + tools: Tool[], + signal?: AbortSignal, + options?: RunOptions, + ): AsyncIterable; +} diff --git a/ui/lib/harness/tests/harness.test.ts b/ui/lib/harness/tests/harness.test.ts new file mode 100644 index 000000000000..4e302a14c5fe --- /dev/null +++ b/ui/lib/harness/tests/harness.test.ts @@ -0,0 +1,316 @@ +import { describe, expect, it } from "vitest"; +import { + createHarness, + INTERRUPTED_TOOL_RESULT, + type HarnessEvent, + type InferenceClient, + type InferenceEvent, + type InferenceRequest, + type Message, + type RunOptions, + type Tool, + type ToolResult, +} from "../src/index.js"; + +const USER: Message[] = [{ content: "hi", role: "user" }]; + +function callEvent(...names: string[]): InferenceEvent { + return { + toolCalls: names.map((name, index) => ({ + function: { arguments: "{}", name }, + id: `call_${index}`, + })), + type: "tool_calls", + }; +} + +// a client that plays one scripted turn per request and records what it was sent +function scriptedClient(turns: Array) { + const requests: InferenceRequest[] = []; + const client: InferenceClient = { + async *stream(request) { + requests.push({ ...request, messages: [...request.messages] }); + + const turn = turns[requests.length - 1] ?? []; + + if (turn instanceof Error) throw turn; + + yield* turn; + }, + }; + + return { client, requests }; +} + +function tool( + name: string, + execute: Tool["execute"] = async () => ({ content: `${name} ran` }), +): Tool { + return { definition: { function: { name }, type: "function" }, execute }; +} + +async function collect( + client: InferenceClient, + tools: Tool[] = [], + options?: RunOptions, + signal?: AbortSignal, +): Promise { + const events: HarnessEvent[] = []; + + for await (const event of createHarness(client).run(USER, tools, signal, options)) + events.push(event); + + return events; +} + +function types(events: HarnessEvent[]): string[] { + return events.map((event) => event.type); +} + +function last(events: HarnessEvent[]): HarnessEvent { + return events[events.length - 1]; +} + +function results(events: HarnessEvent[]) { + return events.filter((event) => event.type === "tool_result"); +} + +describe("createHarness", () => { + it("ends after a turn without tool calls", async () => { + const { client, requests } = scriptedClient([ + [ + { delta: "think", type: "reasoning" }, + { delta: "Hel", type: "text" }, + { delta: "lo", type: "text" }, + ], + ]); + const events = await collect(client); + + expect(types(events)).toEqual(["turn_start", "reasoning", "text", "text", "message", "done"]); + expect(events[4]).toMatchObject({ content: "Hello", final: true, reasoning: "think" }); + expect(last(events)).toMatchObject({ reason: "complete" }); + expect(requests[0].tools).toBeUndefined(); + }); + + it("runs the called tool and sends its result with the next request", async () => { + const { client, requests } = scriptedClient([ + [{ delta: "let me look", type: "text" }, callEvent("read")], + [{ delta: "done", type: "text" }], + ]); + const events = await collect(client, [tool("read")]); + + expect(types(events)).toEqual([ + "turn_start", + "text", + "tool_call_delta", + "message", + "tool_call", + "tool_result", + "turn_end", + "turn_start", + "text", + "message", + "turn_end", + "done", + ]); + expect(events[3]).toMatchObject({ + final: false, + toolCalls: [{ id: "call_0", type: "function" }], + }); + expect(requests[1].messages.slice(1)).toEqual([ + { + content: "let me look", + reasoning_content: undefined, + role: "assistant", + tool_calls: [ + { function: { arguments: "{}", name: "read" }, id: "call_0", type: "function" }, + ], + }, + { content: "read ran", role: "tool", tool_call_id: "call_0" }, + ]); + expect(requests[0].tools).toEqual([{ function: { name: "read" }, type: "function" }]); + }); + + it("sends a result's media parts after its text", async () => { + const image = { image_url: { url: "data:image/png;base64,AAAA" }, type: "image_url" } as const; + const { client, requests } = scriptedClient([[callEvent("shot")], []]); + + await collect(client, [tool("shot", async () => ({ content: "saved", parts: [image] }))]); + + expect(requests[1].messages[2]).toEqual({ + content: [{ text: "saved", type: "text" }, image], + role: "tool", + tool_call_id: "call_0", + }); + }); + + it("reports an unknown tool and a tool that throws to the model", async () => { + const { client } = scriptedClient([[callEvent("missing", "broken")], []]); + const events = await collect(client, [ + tool("broken", async () => { + throw new Error("boom"); + }), + ]); + + expect(results(events).map((event) => event.result)).toEqual([ + { content: "Error: Unknown tool: missing", isError: true }, + { content: "Error: boom", isError: true }, + ]); + expect(last(events)).toMatchObject({ + timings: { + agentic: { toolCalls: [{ success: false }, { success: false }], toolCallsCount: 2 }, + }, + }); + }); + + it("emits a streaming tool's updates before its result", async () => { + const { client } = scriptedClient([[callEvent("shell")], []]); + const events = await collect(client, [ + tool("shell", async (_call, { update }) => { + update(""); + await Promise.resolve(); + update("a"); + update("ab"); + + return { content: "ab" }; + }), + ]); + const updates = events.filter((event) => event.type === "tool_update"); + + // "a" was replaced before the consumer asked for it + expect(updates.map((event) => event.content)).toEqual(["", "ab"]); + expect(types(events).indexOf("tool_result")).toBeGreaterThan( + types(events).lastIndexOf("tool_update"), + ); + }); + + it("uses the duration a tool reports", async () => { + const { client } = scriptedClient([[callEvent("slow")], []]); + const events = await collect(client, [ + tool("slow", async () => ({ content: "", durationMs: 1234 })), + ]); + + expect(last(events)).toMatchObject({ timings: { agentic: { toolsMs: 1234 } } }); + }); + + it("ends without a result when a tool rejects with an AbortError", async () => { + const { client, requests } = scriptedClient([[callEvent("gated")], []]); + const events = await collect(client, [ + tool("gated", async () => { + throw new DOMException("Operation was aborted", "AbortError"); + }), + ]); + + expect(results(events)).toEqual([]); + expect(last(events)).toMatchObject({ reason: "aborted" }); + expect(requests).toHaveLength(1); + }); + + it("keeps the partial output when the signal aborts mid-stream", async () => { + const controller = new AbortController(); + const client: InferenceClient = { + async *stream() { + yield { delta: "par", type: "text" }; + controller.abort(); + throw new DOMException("Operation was aborted", "AbortError"); + }, + }; + const events = await collect(client, [], undefined, controller.signal); + + expect(types(events)).toEqual(["turn_start", "text", "message", "done"]); + expect(events[2]).toMatchObject({ content: "par", final: true }); + expect(last(events)).toMatchObject({ reason: "aborted" }); + }); + + it("ends with an error event when the stream fails", async () => { + const { client } = scriptedClient([new Error("HTTP 500")]); + const events = await collect(client); + + expect(types(events)).toEqual(["turn_start", "message", "error"]); + expect(last(events)).toMatchObject({ error: { message: "HTTP 500" } }); + }); + + it("keeps the tool calls of the turn it is interrupted after, and runs none", async () => { + const { client, requests } = scriptedClient([[callEvent("read")], []]); + const events = await collect(client, [tool("read")], { interrupted: () => true }); + + expect(types(events)).toEqual(["turn_start", "tool_call_delta", "message", "done"]); + expect(events[2]).toMatchObject({ final: true, toolCalls: [{ id: "call_0" }] }); + expect(last(events)).toMatchObject({ reason: "interrupted" }); + expect(requests).toHaveLength(1); + }); + + it("skips the tool calls left when it is interrupted between two", async () => { + let interrupted = false; + + const { client, requests } = scriptedClient([[callEvent("first", "second", "third")], []]); + const events = await collect( + client, + [ + tool("first", async (): Promise => { + interrupted = true; + + return { content: "first ran" }; + }), + tool("second"), + tool("third"), + ], + { interrupted: () => interrupted }, + ); + + expect(results(events).map((event) => [event.result.content, event.skipped])).toEqual([ + ["first ran", false], + [INTERRUPTED_TOOL_RESULT, true], + [INTERRUPTED_TOOL_RESULT, true], + ]); + expect(last(events)).toMatchObject({ reason: "interrupted" }); + expect(requests).toHaveLength(1); + }); + + it("asks at the turn limit and starts the turn count again when it goes on", async () => { + const answers = [true, false]; + const { client } = scriptedClient([[callEvent("read")], [callEvent("read")], []]); + const events = await collect(client, [tool("read")], { + maxTurns: 1, + onTurnLimit: async () => answers.shift() ?? false, + }); + const turns = events.filter((event) => event.type === "turn_start"); + + expect(turns.map((event) => event.turn)).toEqual([1, 1]); + expect(last(events)).toMatchObject({ reason: "turn_limit" }); + }); + + it("adds up the timings of every turn", async () => { + const timings = (n: number): InferenceEvent => ({ + timings: { cache_n: 1, predicted_ms: n, predicted_n: n, prompt_ms: n, prompt_n: n }, + type: "timings", + }); + const { client } = scriptedClient([[timings(10), callEvent("read")], [timings(5)]]); + const events = await collect(client, [tool("read")]); + const live = events + .filter((event) => event.type === "timings") + .map((event) => event.llm?.predicted_n); + + expect(live).toEqual([10, 15]); + expect(last(events)).toMatchObject({ + timings: { + agentic: { + llm: { predicted_ms: 15, predicted_n: 15, prompt_ms: 15, prompt_n: 15 }, + perTurn: [{ turn: 1 }, { turn: 2 }], + toolCallsCount: 1, + turns: 2, + }, + cache_n: 1, + predicted_n: 5, + }, + }); + }); + + it("reports the last request's timings alone when no tool ran", async () => { + const { client } = scriptedClient([[{ timings: { predicted_n: 3 }, type: "timings" }]]); + const events = await collect(client); + + expect(types(events)).toEqual(["turn_start", "timings", "message", "turn_end", "done"]); + expect(last(events)).toEqual({ reason: "complete", timings: { predicted_n: 3 }, type: "done" }); + }); +}); diff --git a/ui/lib/harness/tests/openai-client.test.ts b/ui/lib/harness/tests/openai-client.test.ts new file mode 100644 index 000000000000..fedcb59a0a8c --- /dev/null +++ b/ui/lib/harness/tests/openai-client.test.ts @@ -0,0 +1,130 @@ +import { describe, expect, it } from "vitest"; +import { createOpenAIClient, type InferenceEvent } from "../src/index.js"; + +function sse(...chunks: unknown[]): string { + return chunks.map((chunk) => `data: ${JSON.stringify(chunk)}\n\n`).join("") + "data: [DONE]\n\n"; +} + +// answers every request with the given body, cut into pieces to cross read boundaries +function fakeFetch(body: string, init: ResponseInit = {}, pieceLength = 7) { + const calls: Array<{ url: string; init: RequestInit }> = []; + const fetch = (async (url: string, requestInit: RequestInit) => { + calls.push({ init: requestInit, url }); + + const bytes = new TextEncoder().encode(body); + const stream = new ReadableStream({ + start(controller) { + for (let i = 0; i < bytes.length; i += pieceLength) { + controller.enqueue(bytes.slice(i, i + pieceLength)); + } + + controller.close(); + }, + }); + + return new Response(stream, init); + }) as typeof globalThis.fetch; + + return { calls, fetch }; +} + +async function collect(stream: AsyncIterable): Promise { + const events: InferenceEvent[] = []; + + for await (const event of stream) events.push(event); + + return events; +} + +const delta = (fields: object, rest: object = {}) => ({ + choices: [{ delta: fields }], + id: "cmpl-1", + model: "m", + ...rest, +}); + +describe("createOpenAIClient", () => { + it("posts a streaming request to the chat completions endpoint", async () => { + const { calls, fetch } = fakeFetch(sse()); + const client = createOpenAIClient({ + apiKey: "key", + baseUrl: "http://localhost:8080/", + fetch, + model: "m", + params: { temperature: 0 }, + }); + + await collect(client.stream({ messages: [{ content: "hi", role: "user" }] })); + + expect(calls[0].url).toBe("http://localhost:8080/v1/chat/completions"); + expect(calls[0].init.headers).toMatchObject({ Authorization: "Bearer key" }); + expect(JSON.parse(calls[0].init.body as string)).toEqual({ + messages: [{ content: "hi", role: "user" }], + model: "m", + stream: true, + temperature: 0, + }); + }); + + it("turns the chunks into events", async () => { + const timings = { predicted_n: 2 }; + const { fetch } = fakeFetch( + sse( + delta({ reasoning_content: "hm" }), + delta({ content: "Hel" }), + delta({ content: "lo" }), + delta({}, { timings }), + ), + ); + const events = await collect( + createOpenAIClient({ baseUrl: "http://x", fetch }).stream({ messages: [] }), + ); + + expect(events).toEqual([ + { id: "cmpl-1", type: "completion_id" }, + { model: "m", type: "model" }, + { delta: "hm", type: "reasoning" }, + { delta: "Hel", type: "text" }, + { delta: "lo", type: "text" }, + { progress: undefined, timings, type: "timings" }, + ]); + }); + + it("merges tool call deltas by index", async () => { + const { fetch } = fakeFetch( + sse( + delta({ + tool_calls: [ + { function: { arguments: "", name: "read" }, id: "a", index: 0, type: "function" }, + ], + }), + delta({ tool_calls: [{ function: { arguments: '{"path"' }, index: 0 }] }), + delta({ + tool_calls: [ + { function: { arguments: ':"x"}' }, index: 0 }, + { function: { arguments: "{}", name: "list" }, id: "b", index: 1, type: "function" }, + ], + }), + ), + ); + const events = await collect( + createOpenAIClient({ baseUrl: "http://x", fetch }).stream({ messages: [] }), + ); + const toolCalls = events.filter((event) => event.type === "tool_calls"); + + expect(toolCalls).toHaveLength(3); + expect(toolCalls[2].toolCalls).toEqual([ + { function: { arguments: '{"path":"x"}', name: "read" }, id: "a", type: "function" }, + { function: { arguments: "{}", name: "list" }, id: "b", type: "function" }, + ]); + }); + + it("throws the server's error message", async () => { + const { fetch } = fakeFetch(JSON.stringify({ error: { message: "no model" } }), { + status: 400, + }); + const stream = createOpenAIClient({ baseUrl: "http://x", fetch }).stream({ messages: [] }); + + await expect(collect(stream)).rejects.toThrow("HTTP 400: no model"); + }); +}); diff --git a/ui/lib/harness/tests/trace.test.ts b/ui/lib/harness/tests/trace.test.ts new file mode 100644 index 000000000000..093c0366e0a6 --- /dev/null +++ b/ui/lib/harness/tests/trace.test.ts @@ -0,0 +1,123 @@ +import { describe, expect, it } from "vitest"; +import { + createTracePhraser, + extractToolArgString, + formatToolCallLine, + groupToolCallRuns, + humanizeArgKey, + parsePartialJsonArgs, + simpleToolArgFields, + ToolCallSummaryKind, + type TraceStep, + TraceStepType, +} from "../src/index.js"; + +function call(toolName: string, args: object | string, type: string = TraceStepType.TOOL_CALL): TraceStep { + return { toolArgs: typeof args === "string" ? args : JSON.stringify(args), toolName, type }; +} + +const phraser = createTracePhraser(); +const line = (name: string, args: object | string, running = false) => + formatToolCallLine(phraser.describeToolCall(name, typeof args === "string" ? args : JSON.stringify(args), running)); + +describe("parsePartialJsonArgs", () => { + it("reads the keys of arguments cut off mid-stream", () => { + expect(parsePartialJsonArgs('{"path": "src/a.ts", "content": "line')).toEqual({ + content: "line", + path: "src/a.ts", + }); + expect(parsePartialJsonArgs('{"items": [1, 2,')).toEqual({ items: [1, 2] }); + expect(parsePartialJsonArgs("[1, 2]")).toBeNull(); + }); + + it("reads one field of a whole-file argument without parsing it", () => { + expect(extractToolArgString('{"content": "x\\"y", "path": "a\\\\b.ts"}', ["file_path", "path"])).toBe("a\\b.ts"); + }); +}); + +describe("llama-server tools", () => { + it("say what each call acted on, in the past or present tense", () => { + expect(line("read_file", { path: "/repo/src/app.ts" })).toBe("Read app.ts"); + expect(line("read_file", { path: "/repo/src/app.ts" }, true)).toBe("Reading app.ts"); + expect(line("exec_shell_command", { command: "npm test" })).toBe("Ran npm test"); + expect(line("grep_search", { pattern: "TODO" })).toBe("Searched for 'TODO'"); + expect(line("file_glob_search", { include: "**" })).toBe("Listed files"); + }); + + it("keep the command in the line while a later argument still streams", () => { + expect(line("exec_shell_command", '{"command": "ls -la", "timeout": 1')).toBe("Ran ls -la"); + }); +}); + +describe("createTracePhraser", () => { + it("shows the model's own description of a call as it wrote it", () => { + expect(line("exec_shell_command", { command: "npm test", description: "Run the tests." })).toBe("Run the tests"); + }); + + it("reads any other tool as Used, with its main argument", () => { + expect(line("create_issue", { title: "Bug", query: "crash" })).toBe("Used create_issue crash"); + }); + + it("asks the app's resolvers first, then its phrasing table", () => { + const app = createTracePhraser({ + phrasings: { + get_datetime: { object: "the time", past: "Checked", present: "Checking", summary: ToolCallSummaryKind.OTHER }, + }, + resolvers: [ + (c) => + c.name === "read_file" + ? { phrasing: { object: "notes", past: "Opened", present: "Opening", summary: ToolCallSummaryKind.READ } } + : undefined, + ], + }); + + expect(formatToolCallLine(app.describeToolCall("read_file", '{"path":"a"}'))).toBe("Opened notes"); + expect(formatToolCallLine(app.describeToolCall("get_datetime", "{}"))).toBe("Checked the time"); + }); + + it("summarizes a run by kind, other tools last", () => { + const steps = [ + call("create_issue", {}), + call("exec_shell_command", { command: "a" }), + call("read_file", { path: "x" }), + call("exec_shell_command", { command: "b" }), + { type: TraceStepType.TEXT }, + ]; + + expect(phraser.summarizeToolCalls(steps)).toBe("Ran 2 commands, read 1 file, used 1 tool"); + }); + + it("describes what is running now, or the model thinking", () => { + const steps = [call("read_file", { path: "a.ts" }), call("grep_search", { pattern: "x" }, TraceStepType.TOOL_CALL_PENDING)]; + + expect(phraser.describeToolActivity(steps, true)).toBe("Searching for 'x'"); + expect(phraser.describeToolActivity(steps, false)).toBeNull(); + expect(phraser.describeToolActivity([{ type: TraceStepType.REASONING_PENDING }], true)).toBe("Thinking"); + }); +}); + +describe("groupToolCallRuns", () => { + it("groups calls with the reasoning around them, up to the next text", () => { + const steps: TraceStep[] = [ + { type: TraceStepType.REASONING }, + call("read_file", {}), + { type: TraceStepType.REASONING }, + call("grep_search", {}), + { type: TraceStepType.TEXT }, + call("read_file", {}), + ]; + + expect(groupToolCallRuns(steps, [0, 1, 2, 3, 4, 5], 2)).toEqual([[0, 1, 2, 3], 4, 5]); + }); +}); + +describe("tool arguments", () => { + it("read as fields only when every value is short and on one line", () => { + expect(simpleToolArgFields('{"max_results": 5, "query": "llama"}')).toEqual([ + { label: "Max results", value: "5" }, + { label: "Query", value: "llama" }, + ]); + expect(simpleToolArgFields('{"body": "a\\nb"}')).toBeNull(); + expect(humanizeArgKey("filePath")).toBe("File path"); + }); +}); diff --git a/ui/lib/harness/tsconfig.build.json b/ui/lib/harness/tsconfig.build.json new file mode 100644 index 000000000000..cb6a3121d48a --- /dev/null +++ b/ui/lib/harness/tsconfig.build.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist", + "declaration": true, + "sourceMap": true + }, + "include": ["src"] +} diff --git a/ui/lib/harness/tsconfig.json b/ui/lib/harness/tsconfig.json new file mode 100644 index 000000000000..caa8927c4fc5 --- /dev/null +++ b/ui/lib/harness/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "verbatimModuleSyntax": true, + "skipLibCheck": true, + "types": ["node"] + }, + "include": ["src", "tests"] +} From 6970118ef1f19aab1eeeef07bd121f8d9744dc21 Mon Sep 17 00:00:00 2001 From: uvos Date: Tue, 24 Nov 2026 12:35:00 +0100 Subject: [PATCH 047/275] HIP: CDNA1 MMQ config without stream-k (#32837) --- ggml/src/ggml-cuda/mmq-config-cdna.cuh | 344 ++++++++++++------------- ggml/src/ggml-cuda/mmq.cuh | 8 +- 2 files changed, 177 insertions(+), 175 deletions(-) diff --git a/ggml/src/ggml-cuda/mmq-config-cdna.cuh b/ggml/src/ggml-cuda/mmq-config-cdna.cuh index 4a8d89f72019..8666d79b8b54 100644 --- a/ggml/src/ggml-cuda/mmq-config-cdna.cuh +++ b/ggml/src/ggml-cuda/mmq-config-cdna.cuh @@ -1,185 +1,185 @@ static constexpr __host__ __device__ ggml_cuda_mmq_config ggml_cuda_mmq_get_config_cdna(ggml_type type, int J, bool fallback) { - CASE(GGML_TYPE_Q1_0, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q1_0, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q1_0, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q1_0, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q1_0, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q1_0, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q1_0, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_Q2_0, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q2_0, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q2_0, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q2_0, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q2_0, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q2_0, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q2_0, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_Q4_0, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q4_0, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q4_0, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q4_0, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q4_0, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q4_0, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q4_0, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_Q4_1, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q4_1, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q4_1, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q4_1, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q4_1, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q4_1, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q4_1, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_Q5_0, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q5_0, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q5_0, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q5_0, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q5_0, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q5_0, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q5_0, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_Q5_1, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q5_1, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q5_1, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q5_1, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q5_1, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q5_1, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q5_1, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_Q8_0, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q8_0, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q8_0, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q8_0, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q8_0, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q8_0, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q8_0, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q1_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q1_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q1_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q1_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q1_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q1_0, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q1_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_Q2_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q2_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q2_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q2_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q2_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q2_0, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q2_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_Q4_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q4_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q4_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q4_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q4_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q4_0, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q4_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_Q4_1, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q4_1, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q4_1, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q4_1, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q4_1, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q4_1, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q4_1, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_Q5_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q5_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q5_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q5_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q5_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q5_0, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q5_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_Q5_1, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q5_1, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q5_1, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q5_1, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q5_1, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q5_1, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q5_1, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_Q8_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q8_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q8_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q8_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q8_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q8_0, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q8_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); // --------------------------------------------------------------------------------------------- - CASE(GGML_TYPE_Q2_K, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q2_K, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q2_K, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q2_K, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q2_K, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q2_K, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q2_K, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_Q3_K, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q3_K, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q3_K, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q3_K, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q3_K, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q3_K, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q3_K, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_Q4_K, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q4_K, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q4_K, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q4_K, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q4_K, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q4_K, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q4_K, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_Q5_K, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q5_K, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q5_K, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q5_K, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q5_K, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q5_K, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q5_K, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_Q6_K, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q6_K, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q6_K, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q6_K, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q6_K, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q6_K, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q6_K, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q2_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q2_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q2_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q2_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q2_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q2_K, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q2_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_Q3_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q3_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q3_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q3_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q3_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q3_K, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q3_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_Q4_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q4_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q4_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q4_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q4_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q4_K, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q4_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_Q5_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q5_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q5_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q5_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q5_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q5_K, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q5_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_Q6_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q6_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q6_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q6_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q6_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q6_K, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q6_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, false); // --------------------------------------------------------------------------------------------- - CASE(GGML_TYPE_IQ1_S, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ1_S, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ1_S, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ1_S, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ1_S, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ1_S, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ1_S, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_IQ2_XXS, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ2_XXS, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ2_XXS, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ2_XXS, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ2_XXS, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ2_XXS, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ2_XXS, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_IQ2_XS, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ2_XS, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ2_XS, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ2_XS, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ2_XS, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ2_XS, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ2_XS, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_IQ2_S, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ2_S, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ2_S, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ2_S, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ2_S, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ2_S, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ2_S, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_IQ3_XXS, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ3_XXS, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ3_XXS, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ3_XXS, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ3_XXS, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ3_XXS, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ3_XXS, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_IQ3_S, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ3_S, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ3_S, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ3_S, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ3_S, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ3_S, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ3_S, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_IQ4_XS, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ4_XS, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ4_XS, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ4_XS, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ4_XS, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ4_XS, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ4_XS, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_IQ4_NL, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ4_NL, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ4_NL, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ4_NL, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ4_NL, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ4_NL, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ4_NL, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ1_S, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ1_S, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ1_S, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ1_S, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ1_S, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ1_S, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ1_S, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_IQ2_S, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ2_S, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ2_S, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ2_S, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ2_S, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ2_S, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ2_S, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); // --------------------------------------------------------------------------------------------- - CASE(GGML_TYPE_MXFP4, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_MXFP4, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_MXFP4, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_MXFP4, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_MXFP4, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_MXFP4, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_MXFP4, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_NVFP4, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_NVFP4, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_NVFP4, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_NVFP4, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_NVFP4, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_NVFP4, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_NVFP4, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_MXFP4, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_MXFP4, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_MXFP4, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_MXFP4, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_MXFP4, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_MXFP4, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_MXFP4, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_NVFP4, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_NVFP4, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_NVFP4, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_NVFP4, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_NVFP4, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_NVFP4, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_NVFP4, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, false); return ggml_cuda_mmq_config(GGML_TYPE_COUNT, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, 256, false, true); } diff --git a/ggml/src/ggml-cuda/mmq.cuh b/ggml/src/ggml-cuda/mmq.cuh index be2f11430079..5030ae1da617 100644 --- a/ggml/src/ggml-cuda/mmq.cuh +++ b/ggml/src/ggml-cuda/mmq.cuh @@ -1536,13 +1536,15 @@ static void launch_mul_mat_q(ggml_backend_cuda_context & ctx, const mmq_args & a const int ntiles_dst = args.ntj * nti * ntzw; const int tiles_nwaves = (ntiles_dst + nsm - 1) / nsm; const int tiles_efficiency_percent = 100 * ntiles_dst / (nsm*tiles_nwaves); - const int stream_k_blocks = GGML_CUDA_CC_IS_GCN(cc) ? nsm * config.occupancy : nsm; + // GCN and CDNA configs run several blocks per CU, so stream-k uses one block per occupancy slot. + const bool multi_block_cu = GGML_CUDA_CC_IS_GCN(cc) || GGML_CUDA_CC_IS_CDNA(cc); + const int stream_k_blocks = multi_block_cu ? nsm * config.occupancy : nsm; const int k_chunks = (args.ncols_x + config.K_vram - 1) / config.K_vram; // Use tiling when Stream-K is unlikely to improve performance: // With at least 2 full waves of tiles, tiling already saturates the device and Stream-K only adds overhead. // With few K chunks per tile, the extra parallelism of Stream-K is not needed. - const bool force_tiling = GGML_CUDA_CC_IS_GCN(cc) && + const bool force_tiling = multi_block_cu && (tiles_efficiency_percent >= 90 || ntiles_dst >= 2*stream_k_blocks || k_chunks <= config.occupancy * tiles_nwaves); @@ -1563,7 +1565,7 @@ static void launch_mul_mat_q(ggml_backend_cuda_context & ctx, const mmq_args & a const int nwork = ntiles_dst * k_chunks; // Maximum number of CUDA blocks that can do useful work. int nblocks_stream_k = GGML_CUDA_CC_IS_NVIDIA(cc) && tiles_efficiency_percent >= 90 ? ntiles_dst : std::min(stream_k_blocks, nwork); - if (GGML_CUDA_CC_IS_GCN(cc) && ntiles_dst < nsm) { + if (multi_block_cu && ntiles_dst < nsm) { // Use a 512-thread budget per CU when the tiles do not fill the device. nblocks_stream_k = std::min(nwork, nsm * std::max(1, 512 / config.nthreads)); } From a8ed7789149479dbf2abf0367c8fe8d10d73be82 Mon Sep 17 00:00:00 2001 From: thelittlefireman <5165783+thelittlefireman@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:36:32 +0100 Subject: [PATCH 048/275] hip: use MMQ over MMVQ for Q4_K,N8 and NVFP4,N7-8 on VEGA20 (#32805) --- ggml/src/ggml-cuda/mmvq.cu | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/ggml/src/ggml-cuda/mmvq.cu b/ggml/src/ggml-cuda/mmvq.cu index 6f10428e682b..3549fbe3215a 100644 --- a/ggml/src/ggml-cuda/mmvq.cu +++ b/ggml/src/ggml-cuda/mmvq.cu @@ -441,6 +441,17 @@ bool ggml_cuda_should_use_mmvq(enum ggml_type type, int cc, int64_t ne11) { return ne11 <= MMVQ_MAX_BATCH_SIZE; } } + // VEGA20 devices are the only devices with dense MMQ -> ggml_cuda_should_use_mmq() + if (cc == GGML_CUDA_CC_VEGA20) { + switch (type) { // tuned on MI50 (gfx906) + case GGML_TYPE_Q4_K: + return ne11 <= 7; + case GGML_TYPE_NVFP4: + return ne11 <= 6; + default: + return ne11 <= MMVQ_MAX_BATCH_SIZE; + } + } return ne11 <= MMVQ_MAX_BATCH_SIZE; } From 94165b288d74e9fca6101018b4471881808c6f18 Mon Sep 17 00:00:00 2001 From: Takamichi Ohara Date: Tue, 24 Nov 2026 20:37:10 +0900 Subject: [PATCH 049/275] webgpu : add POOL_1D support (#32254) --- docs/ops.md | 2 +- docs/ops/WebGPU.csv | 288 +++++++++++++++--- .../ggml-webgpu/ggml-webgpu-shader-lib.hpp | 21 ++ ggml/src/ggml-webgpu/ggml-webgpu.cpp | 35 +++ ggml/src/ggml-webgpu/wgsl-shaders/pool1d.wgsl | 44 +++ 5 files changed, 341 insertions(+), 49 deletions(-) create mode 100644 ggml/src/ggml-webgpu/wgsl-shaders/pool1d.wgsl diff --git a/docs/ops.md b/docs/ops.md index 6c226e150020..e217fce87d56 100644 --- a/docs/ops.md +++ b/docs/ops.md @@ -89,7 +89,7 @@ Legend: | OUT_PROD | 🟡 | 🟡 | 🟡 | 🟡 | ❌ | ❌ | ❌ | ❌ | ❌ | 🟡 | 🟡 | ❌ | ❌ | ❌ | | PAD | ❌ | 🟡 | ✅ | 🟡 | ❌ | ✅ | 🟡 | ✅ | 🟡 | 🟡 | ✅ | ✅ | ❌ | ❌ | | PAD_REFLECT_1D | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ❌ | ✅ | ❌ | ❌ | -| POOL_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | +| POOL_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | | POOL_2D | ❌ | 🟡 | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | | REGLU | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | RELU | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | diff --git a/docs/ops/WebGPU.csv b/docs/ops/WebGPU.csv index 8e09ddaf3de0..1b2080f3cf07 100644 --- a/docs/ops/WebGPU.csv +++ b/docs/ops/WebGPU.csv @@ -1283,54 +1283,246 @@ "WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=0,p1=1","support","1","yes","WebGPU" "WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=1,p1=0","support","1","yes","WebGPU" "WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=1,p1=1","support","1","yes","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=1","support","0","no","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=10,s0=10,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,1024,1,1],k0=10,s0=10,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,3,2,1],k0=128,s0=128,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,1024,1,1],k0=128,s0=128,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[256,3,2,1],k0=256,s0=256,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[256,1024,1,1],k0=256,s0=256,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[1000,3,2,1],k0=1000,s0=1000,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[1000,1024,1,1],k0=1000,s0=1000,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[2048,3,2,1],k0=2048,s0=2048,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[2048,1024,1,1],k0=2048,s0=2048,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[4099,3,2,1],k0=4099,s0=4099,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[4099,1024,1,1],k0=4099,s0=4099,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=10,s0=10,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,1024,1,1],k0=10,s0=10,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,3,2,1],k0=128,s0=128,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,1024,1,1],k0=128,s0=128,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[256,3,2,1],k0=256,s0=256,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[256,1024,1,1],k0=256,s0=256,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[1000,3,2,1],k0=1000,s0=1000,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[1000,1024,1,1],k0=1000,s0=1000,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[2048,3,2,1],k0=2048,s0=2048,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[2048,1024,1,1],k0=2048,s0=2048,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[4099,3,2,1],k0=4099,s0=4099,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[4099,1024,1,1],k0=4099,s0=4099,p0=0","support","1","yes","WebGPU" "WebGPU: WebGPU","IM2COL","type_input=f32,type_kernel=f32,dst_type=f32,ne_input=[3000,128,1,1],ne_kernel=[3,128,1280,1],s0=1,s1=0,p0=1,p1=0,d0=1,d1=0,is_2D=0","support","1","yes","WebGPU" "WebGPU: WebGPU","IM2COL","type_input=f32,type_kernel=f16,dst_type=f32,ne_input=[3000,128,1,1],ne_kernel=[3,128,1280,1],s0=1,s1=0,p0=1,p1=0,d0=1,d1=0,is_2D=0","support","1","yes","WebGPU" "WebGPU: WebGPU","IM2COL","type_input=f32,type_kernel=f16,dst_type=f16,ne_input=[3000,128,1,1],ne_kernel=[3,128,1280,1],s0=1,s1=0,p0=1,p1=0,d0=1,d1=0,is_2D=0","support","1","yes","WebGPU" diff --git a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp index 6b618bb16370..b256ce6b863c 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp @@ -1276,6 +1276,7 @@ class ggml_webgpu_shader_lib { std::unordered_map arange_pipelines; // key is fixed, no variants yet std::unordered_map count_equal_pipelines; // key is src_overlap std::unordered_map timestep_embedding_pipelines; // key is fixed, no variants yet + std::unordered_map pool1d_pipelines; std::unordered_map pool2d_pipelines; // key is ggml_op_pool std::unordered_map row_norm_pipelines; // op/inplace @@ -2078,6 +2079,26 @@ class ggml_webgpu_shader_lib { return arange_pipelines[1]; } + webgpu_pipeline get_pool1d_pipeline(const ggml_webgpu_shader_lib_context & context) { + const int key = ggml_get_op_params_i32(context.dst, 0); + + auto it = pool1d_pipelines.find(key); + if (it != pool1d_pipelines.end()) { + return it->second; + } + + std::vector defines = { "WG_SIZE=" + std::to_string(context.max_wg_size) }; + const char * variant = "pool1d_avg"; + if (key == GGML_OP_POOL_MAX) { + defines.emplace_back("POOL_MAX"); + variant = "pool1d_max"; + } + + auto pipeline = ggml_webgpu_create_pipeline(device, preprocessor.preprocess(wgsl_pool1d, defines), variant); + pool1d_pipelines.emplace(key, pipeline); + return pipeline; + } + webgpu_pipeline get_pool2d_pipeline(const ggml_webgpu_shader_lib_context & context) { const int key = ggml_get_op_params_i32(context.dst, 0); diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp index daf83ee83ce4..74e6581b65a6 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp @@ -989,6 +989,38 @@ static webgpu_encoded_op ggml_webgpu_pad(webgpu_context & ctx, ggml_tensor * src return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y); } +static webgpu_encoded_op ggml_webgpu_pool1d(webgpu_context & ctx, ggml_tensor * src, ggml_tensor * dst) { + ggml_webgpu_shader_lib_context shader_lib_ctx = {}; + shader_lib_ctx.dst = dst; + shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup; + + webgpu_pipeline pipeline = ctx->shader_lib->get_pool1d_pipeline(shader_lib_ctx); + + const uint32_t ne = (uint32_t) ggml_nelements(dst); + + std::vector params = { + ne, + (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src) / sizeof(float)), + (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / sizeof(float)), + (uint32_t) src->ne[0], + (uint32_t) dst->ne[0], + (uint32_t) ggml_get_op_params_i32(dst, 1), + (uint32_t) ggml_get_op_params_i32(dst, 2), + (uint32_t) ggml_get_op_params_i32(dst, 3), + }; + + std::vector entries = { + ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src), + ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst), + }; + + uint32_t wg_x; + uint32_t wg_y; + const uint32_t total_wg = CEIL_DIV(ne, shader_lib_ctx.max_wg_size); + compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y); + return ggml_backend_webgpu_build(ctx, pipeline, std::move(params), std::move(entries), wg_x, wg_y); +} + static webgpu_encoded_op ggml_webgpu_pool2d(webgpu_context & ctx, ggml_tensor * src, ggml_tensor * dst) { ggml_webgpu_shader_lib_context shader_lib_ctx = {}; shader_lib_ctx.src0 = src; @@ -3774,6 +3806,8 @@ static std::optional ggml_webgpu_encode(webgpu_context ctx, } case GGML_OP_ARANGE: return ggml_webgpu_arange(ctx, node); + case GGML_OP_POOL_1D: + return ggml_webgpu_pool1d(ctx, src0, node); case GGML_OP_POOL_2D: return ggml_webgpu_pool2d(ctx, src0, node); case GGML_OP_COL2IM_1D: @@ -5335,6 +5369,7 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const case GGML_OP_ARANGE: supports_op = op->type == GGML_TYPE_F32 && ggml_is_contiguous(op); break; + case GGML_OP_POOL_1D: case GGML_OP_POOL_2D: supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32 && ggml_is_contiguous(src0); break; diff --git a/ggml/src/ggml-webgpu/wgsl-shaders/pool1d.wgsl b/ggml/src/ggml-webgpu/wgsl-shaders/pool1d.wgsl new file mode 100644 index 000000000000..3a212ed782fe --- /dev/null +++ b/ggml/src/ggml-webgpu/wgsl-shaders/pool1d.wgsl @@ -0,0 +1,44 @@ +struct Params { + ne: u32, + offset_src: u32, + offset_dst: u32, + src_ne0: u32, + dst_ne0: u32, + k0: i32, + s0: i32, + p0: i32, +}; + +@group(0) @binding(0) var src: array; +@group(0) @binding(1) var dst: array; +@group(0) @binding(2) var params: Params; + +@compute @workgroup_size(WG_SIZE) +fn main(@builtin(num_workgroups) num_wg: vec3, @builtin(global_invocation_id) gid: vec3) { + let idx = gid.x + num_wg.x * u32(WG_SIZE) * gid.y; + if (idx >= params.ne) { + return; + } + + let row = params.offset_src + (idx / params.dst_ne0) * params.src_ne0; + let x0 = i32(idx % params.dst_ne0) * params.s0 - params.p0; + let x_begin = max(x0, 0); + let x_end = min(x0 + params.k0, i32(params.src_ne0)); +#ifdef POOL_MAX + var value = bitcast(0xff7fffffu); +#else + var value = 0.0f; +#endif + for (var x = x_begin; x < x_end; x++) { + let v = src[row + u32(x)]; +#ifdef POOL_MAX + value = max(value, v); +#else + value += v; +#endif + } +#ifndef POOL_MAX + value /= f32(max(x_end - x_begin, 1)); +#endif + dst[params.offset_dst + idx] = value; +} From 6ac648d7a9ef8f1a8141aaa52d0bdb780e2571b7 Mon Sep 17 00:00:00 2001 From: Nikhil Jain Date: Tue, 24 Nov 2026 03:37:56 -0800 Subject: [PATCH 050/275] webgpu : Fix indexing bug in softmax kernel (#32691) * Only run webgpu CI on my fork * Add webgpu only workflow * resolve merge conflicts * add row check for softmax * add test * Add test to test case eval --- ggml/src/ggml-webgpu/ggml-webgpu.cpp | 3 ++- ggml/src/ggml-webgpu/wgsl-shaders/soft_max.wgsl | 4 ++++ tests/test-backend-ops.cpp | 3 +++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp index 74e6581b65a6..8bf62e1ca85d 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp @@ -3237,7 +3237,8 @@ static webgpu_encoded_op ggml_webgpu_soft_max(webgpu_context & ctx, ggml_webgpu_u32_from_f32(max_bias), ggml_webgpu_u32_from_f32(n_head_log2), ggml_webgpu_u32_from_f32(m0), - ggml_webgpu_u32_from_f32(m1) + ggml_webgpu_u32_from_f32(m1), + (uint32_t) ggml_nrows(dst) }; std::vector entries = { ggml_webgpu_make_bind_group_entry( diff --git a/ggml/src/ggml-webgpu/wgsl-shaders/soft_max.wgsl b/ggml/src/ggml-webgpu/wgsl-shaders/soft_max.wgsl index 8f92a04c1b15..86d4828aaa2a 100644 --- a/ggml/src/ggml-webgpu/wgsl-shaders/soft_max.wgsl +++ b/ggml/src/ggml-webgpu/wgsl-shaders/soft_max.wgsl @@ -40,6 +40,7 @@ struct Params { n_head_log2: f32, m0: f32, m1: f32, + nrows: u32, }; #define SRC_BINDING 0 @@ -128,6 +129,9 @@ fn main(@builtin(workgroup_id) wid: vec3, @builtin(local_invocation_id) lid: vec3) { var i = wid.x + wid.y * num_wg.x; + if (i >= params.nrows) { + return; + } let i3 = i / (params.ne2 * params.ne1); i = i % (params.ne2 * params.ne1); let i2 = i / params.ne1; diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 2d50c607cab3..a7380dcb1d58 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -13170,6 +13170,7 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {4, 1, 1, 1}, false, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f)); test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {4, 1023, 1, 1}, false, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f)); test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {643251, 3, 1, 1}, false, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f)); + test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {16, 65537, 1, 1})); for (float max_bias : {0.0f, 8.0f}) { for (float scale : {1.0f, 0.1f}) { @@ -14515,6 +14516,8 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {256, 256, 20, 1}, false, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f)); test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {64, 64, 20, 1}, false, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f)); test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {77, 64, 20, 1}, false, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f)); + test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {16, 65537, 1, 1})); + for (int64_t n : {256, 1024}) { test_cases.emplace_back(new test_count_equal(GGML_TYPE_F32, {4, n, 1, 1})); From 6fb428332ecef16ac82c4e8cf961ac287bb3217b Mon Sep 17 00:00:00 2001 From: Plasmatix Ultra Date: Tue, 24 Nov 2026 03:38:47 -0800 Subject: [PATCH 051/275] CUDA: NVFP4 dequant, pack 8 blocks per CTA (#32875) Launch dequantize_block_nvfp4 with dim3(32, 8) so each CTA covers 8 NVFP4 blocks (256 values), as the K-quants do. Assisted-by: Claude Code Co-authored-by: plasmatixultra --- ggml/src/ggml-cuda/convert.cu | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-cuda/convert.cu b/ggml/src/ggml-cuda/convert.cu index a8f5047a2302..601c63232178 100644 --- a/ggml/src/ggml-cuda/convert.cu +++ b/ggml/src/ggml-cuda/convert.cu @@ -385,7 +385,7 @@ static __global__ void dequantize_block_nvfp4( const void * __restrict__ vx, dst_t * __restrict__ yy, const int64_t ne) { - const int64_t i = blockIdx.x; + const int64_t i = (int64_t) blockIdx.x*blockDim.y + threadIdx.y; const int tid = threadIdx.x; const int64_t base = i * QK_NVFP4; @@ -417,7 +417,7 @@ static void dequantize_row_nvfp4_cuda( cudaStream_t stream) { GGML_ASSERT(k % QK_NVFP4 == 0); const int nb = k / QK_NVFP4; - dequantize_block_nvfp4<<>>(vx, y, k); + dequantize_block_nvfp4<<<(nb + 7)/8, dim3(32, 8), 0, stream>>>(vx, y, k); } template static __global__ void convert_unary( From 2a487782f2f218bc6c01e1f366a7e73f002faf08 Mon Sep 17 00:00:00 2001 From: IsNot <209144869@qq.com> Date: Tue, 24 Nov 2026 19:41:21 +0800 Subject: [PATCH 052/275] vocab : speed up BPE tokenization (#32859) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * vocab : avoid string allocations in BPE tokenization * whitespace-- --------- Co-authored-by: Sigbjørn Skjæret --- src/llama-vocab.cpp | 53 +++++++++++++++++++-------------------------- src/llama-vocab.h | 3 ++- 2 files changed, 24 insertions(+), 32 deletions(-) diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp index 20357e8ef192..c97fa906c8e7 100644 --- a/src/llama-vocab.cpp +++ b/src/llama-vocab.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -274,7 +275,6 @@ struct llm_bigram_bpe { using queue = llama_priority_queue; llm_symbol::index left; llm_symbol::index right; - std::string text; int rank; size_t size; }; @@ -755,14 +755,10 @@ struct llm_tokenizer_bpe_session { auto & left_symbol = symbols[bigram.left]; auto & right_symbol = symbols[bigram.right]; - if (left_symbol.n == 0 || right_symbol.n == 0) { + if (left_symbol.n == 0 || right_symbol.n == 0 || + left_symbol.n + right_symbol.n != bigram.size) { continue; } - std::string left_token = std::string(left_symbol.text, left_symbol.n); - std::string right_token = std::string(right_symbol.text, right_symbol.n); - if (left_token + right_token != bigram.text) { - continue; // Skip this bigram if it's outdated - } // merge the right sym into the left one left_symbol.n += right_symbol.n; @@ -835,12 +831,9 @@ struct llm_tokenizer_bpe_session { if (left == -1 || right == -1) { return; } - std::string left_token = std::string(symbols[left].text, symbols[left].n); - std::string right_token = std::string(symbols[right].text, symbols[right].n); - - int rank_found = -1; - - rank_found = vocab.find_bpe_rank(left_token, right_token); + int rank_found = vocab.find_bpe_rank( + std::string_view(symbols[left].text, symbols[left].n), + std::string_view(symbols[right].text, symbols[right].n)); if (rank_found < 0) { return; @@ -850,8 +843,7 @@ struct llm_tokenizer_bpe_session { bigram.left = left; bigram.right = right; - bigram.text = left_token + right_token; - bigram.size = left_token.size() + right_token.size(); + bigram.size = symbols[left].n + symbols[right].n; bigram.rank = rank_found; work_queue.push(bigram); @@ -2153,13 +2145,15 @@ struct llama_vocab::impl { std::vector cache_special_tokens; std::vector cache_token_to_piece; // llama_token_to_piece(special = true); + using bpe_rank_key = std::pair; struct pair_hash { - size_t operator()(const std::pair & p) const { - return std::hash{}(p.first) ^ //create some hash for pair - (std::hash{}(p.second) << 1); + size_t operator()(const bpe_rank_key & p) const { + return std::hash{}(p.first) ^ + (std::hash{}(p.second) << 1); } }; - std::unordered_map, int, pair_hash> bpe_ranks; + std::deque bpe_rank_strs; // stable backing storage for bpe_ranks keys + std::unordered_map bpe_ranks; // set of all tokens that cause "end of generation" std::set special_eog_ids; @@ -2173,6 +2167,8 @@ struct llama_vocab::impl { impl(const llama_vocab & vocab) : vocab(vocab) { } + impl(const impl &) = delete; + ~impl() = default; void load(llama_model_loader & ml, const LLM_KV & kv); @@ -2261,17 +2257,12 @@ bool llama_vocab::impl::load_bpe_ranks(const gguf_context * ctx, const LLM_KV & bpe_ranks.reserve(n_merges); for (int i = 0; i < n_merges; i++) { const char * word = gguf_get_arr_str(ctx, merges_keyidx, i); - std::string first; - std::string second; const char * sep = *word ? strchr(word + 1, ' ') : nullptr; - if (sep) { - first.assign(word, sep - word); - second.assign(sep + 1); - } - - bpe_ranks.emplace(std::make_pair(std::move(first), std::move(second)), i); + auto & left = bpe_rank_strs.emplace_back(word, sep ? sep - word : 0); + auto & right = bpe_rank_strs.emplace_back(sep ? sep + 1 : ""); + bpe_ranks.emplace(bpe_rank_key(left, right), i); } return true; } @@ -4613,9 +4604,9 @@ int llama_vocab::max_token_len() const { return pimpl->max_token_len; } -int llama_vocab::find_bpe_rank(const std::string & token_left, const std::string & token_right) const { - GGML_ASSERT(token_left.find(' ') == std::string::npos); - GGML_ASSERT(token_right.find(' ') == std::string::npos); +int llama_vocab::find_bpe_rank(std::string_view token_left, std::string_view token_right) const { + GGML_ASSERT(token_left.find(' ') == std::string_view::npos); + GGML_ASSERT(token_right.find(' ') == std::string_view::npos); auto it = pimpl->bpe_ranks.find(std::make_pair(token_left, token_right)); if (it == pimpl->bpe_ranks.end()) { @@ -4633,7 +4624,7 @@ std::vector llama_vocab::get_bpe_merges() const { std::vector result(max_rank + 1); for (const auto & pair : pimpl->bpe_ranks) { - result[pair.second] = pair.first.first + " " + pair.first.second; + result[pair.second] = std::string(pair.first.first) + " " + std::string(pair.first.second); } return result; diff --git a/src/llama-vocab.h b/src/llama-vocab.h index 9345275f55d6..357ce931e30e 100644 --- a/src/llama-vocab.h +++ b/src/llama-vocab.h @@ -3,6 +3,7 @@ #include "llama.h" #include +#include #include #include @@ -174,7 +175,7 @@ struct llama_vocab { int max_token_len() const; - int find_bpe_rank(const std::string & token_left, const std::string & token_right) const; + int find_bpe_rank(std::string_view token_left, std::string_view token_right) const; std::vector get_bpe_merges() const; std::vector get_precompiled_charsmap() const; From 4c92c5bfb7cab395af9fc0fe0939e34ae5083345 Mon Sep 17 00:00:00 2001 From: Eddie Zhou Date: Tue, 24 Nov 2026 05:04:00 -0700 Subject: [PATCH 053/275] CUDA: reduce all cooperative softmax partials when nsm > 256 (#32897) * CUDA: reduce all cooperative softmax partials when nsm > 256 Fixes #32852 * CUDA: drop the remaining cooperative softmax grid size assert --- ggml/src/ggml-cuda/softmax.cu | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/ggml/src/ggml-cuda/softmax.cu b/ggml/src/ggml-cuda/softmax.cu index b9182af54932..18929fcd9d59 100644 --- a/ggml/src/ggml-cuda/softmax.cu +++ b/ggml/src/ggml-cuda/softmax.cu @@ -176,11 +176,9 @@ static __device__ void soft_max_f32_parallelize_cols_single_row(const float * __ } g.sync(); - assert(gridDim.x < blockDim.x); - if (tid < gridDim.x) { - local_max = tmp_maxs[tid]; - } else { - local_max = -INFINITY; + local_max = -INFINITY; + for (int i = tid; i < (int) gridDim.x; i += blockDim.x) { + local_max = fmaxf(local_max, tmp_maxs[i]); } local_max = block_reduce(local_max, shared_vals_max); @@ -202,10 +200,9 @@ static __device__ void soft_max_f32_parallelize_cols_single_row(const float * __ } g.sync(); - if (tid < gridDim.x) { - tmp_expf = tmp_sums[tid]; - } else { - tmp_expf = 0.0f; + tmp_expf = 0.0f; + for (int i = tid; i < (int) gridDim.x; i += blockDim.x) { + tmp_expf += tmp_sums[i]; } tmp_expf = block_reduce(tmp_expf, shared_vals_sum); @@ -247,11 +244,9 @@ static __device__ void soft_max_f32_parallelize_cols_single_row(const float * __ g.sync(); // Compute compute global max from CTA-level maxs - assert(gridDim.x < blockDim.x); // currently we only support this case - if (tid < gridDim.x) { - local_max = tmp_maxs[tid]; - } else { - local_max = -INFINITY; + local_max = -INFINITY; + for (int i = tid; i < (int) gridDim.x; i += blockDim.x) { + local_max = fmaxf(local_max, tmp_maxs[i]); } local_max = block_reduce(local_max, shared_vals_max); @@ -285,10 +280,9 @@ static __device__ void soft_max_f32_parallelize_cols_single_row(const float * __ g.sync(); // Compute global sum from CTA-level sums - if (tid < gridDim.x) { - tmp_expf = tmp_sums[tid]; - } else { - tmp_expf = 0.0f; + tmp_expf = 0.0f; + for (int i = tid; i < (int) gridDim.x; i += blockDim.x) { + tmp_expf += tmp_sums[i]; } tmp_expf = block_reduce(tmp_expf, shared_vals_sum); From e683365a74d5a09b184b3faf3dee240129439b80 Mon Sep 17 00:00:00 2001 From: Aman Gupta Date: Tue, 24 Nov 2026 20:47:28 +0800 Subject: [PATCH 054/275] model : inkling2 clip with ggml_l2_norm (#32940) Assisted-by: Claude Opus 5.5 --- src/models/inkling2.cpp | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 45477a69e35e..4a685fd166b6 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -167,12 +167,8 @@ ggml_tensor * llama_model_inkling2::graph::clip(ggml_tensor * cur, ggml_tensor * cur = ggml_mul(ctx0, cur, scale); } - ggml_tensor * norm = ggml_sqrt(ctx0, ggml_sum_rows(ctx0, ggml_sqr(ctx0, cur))); - norm = ggml_scale_bias(ctx0, norm, 1.0f, 1e-6f); - - ggml_tensor * factor = ggml_div(ctx0, ggml_fill(ctx0, norm, threshold), norm); - - return ggml_mul(ctx0, cur, ggml_clamp(ctx0, factor, 0.0f, 1.0f)); + // x*min(1, t/|x|) = t*x/max(|x|, t), and l2_norm(x, eps) = x/max(|x|, eps) + return ggml_scale(ctx0, ggml_l2_norm(ctx0, cur, threshold), threshold); } // attention over the depth: mix the earlier block outputs and cur with learned queries From 9578bd3fe48b793cf193c2e4615ec2f24a2ea92a Mon Sep 17 00:00:00 2001 From: Aman Gupta Date: Tue, 24 Nov 2026 20:48:02 +0800 Subject: [PATCH 055/275] CUDA: ignore strides of size-1 dims in bin_bcast (#32854) After collapsing contiguous dims, the stride of a trailing dim of size 1 becomes the size of the whole tensor. Its index is always 0, but the uint32 stride asserts still fire once the tensor has more than 2^32 elements, e.g. the per-head relative-position mask add of inkling2 at n_kv > ~87k with -ub 2048. Fixes #32804 Assisted-by: Claude Opus 5.5 --- ggml/src/ggml-cuda/binbcast.cu | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/ggml/src/ggml-cuda/binbcast.cu b/ggml/src/ggml-cuda/binbcast.cu index f7c3a7322f28..7e1c5c300057 100644 --- a/ggml/src/ggml-cuda/binbcast.cu +++ b/ggml/src/ggml-cuda/binbcast.cu @@ -256,6 +256,18 @@ static void launch_bin_bcast_pack(const ggml_tensor * src0, const ggml_tensor * size_t s02 = nb02 / sizeof(src0_t); size_t s03 = nb03 / sizeof(src0_t); + // the index of a dim of size 1 is always 0, so its stride is never applied, + // but after collapsing contiguous dims it can be the whole tensor size and exceed 32 bits + if (cne0[1] == 1) { s01 = 0; } + if (cne0[2] == 1) { s02 = 0; } + if (cne0[3] == 1) { s03 = 0; } + if (cne1[1] == 1) { s11 = 0; } + if (cne1[2] == 1) { s12 = 0; } + if (cne1[3] == 1) { s13 = 0; } + if (ne1 == 1) { s1 = 0; } + if (ne2 == 1) { s2 = 0; } + if (ne3 == 1) { s3 = 0; } + GGML_ASSERT(ne0 <= std::numeric_limits::max()); GGML_ASSERT(ne1 <= std::numeric_limits::max()); GGML_ASSERT(ne2 <= std::numeric_limits::max()); From 26f5048d5c288cec7ccacc4131ccfafaedbc52a7 Mon Sep 17 00:00:00 2001 From: Sebastian Kuzminsky Date: Tue, 24 Nov 2026 06:07:00 -0700 Subject: [PATCH 056/275] fix building in symlinked directories (#32903) * fix building in symlinked directories My checkout is in a symlinked directory, so that the cmake CWD differs from its realpath: ``` $ echo $PWD /home/[READACTED]/llama.cpp $ realpath $PWD /data/home/[READACTED]/llama.cpp ``` The build here fails with this error: ``` CMake Error: Unable to read from file: ../../../../../../../../data/home/[READACTED]/llama.cpp/build/ui/apps/chat/dist/_app/immutable/assets/0.Cc4cGcci.css because: Can't lstat ../../../../../../../../data/home/[READACTED]/llama.cpp/build/ui/apps/chat/dist/_app/immutable/assets/0.Cc4cGcci.css CMake Error at /home/[REDACTED]/llama.cpp/scripts/ui-assets.cmake:229 (file): file failed to compress: /home/[REDACTED]/llama.cpp/build/ui/apps/chat/ui-gzip/_gzip/_app/immutable/assets/0.Cc4cGcci.css Call Stack (most recent call first): /home/[REDACTED]/llama.cpp/scripts/ui-assets.cmake:629 (emit_files) ``` This is because the cmake `emit_files` function uses relative paths and is inconsistent about its use of realpath. This commit fixes the build in my environment by switching from relative to absolute paths for the archive member files, so that the distinction between realpath and non-realpath doesn't mess things up. * refactor: Apply suggestion --------- Co-authored-by: Aleksander Grygier --- scripts/ui-assets.cmake | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/scripts/ui-assets.cmake b/scripts/ui-assets.cmake index 8079c1c09651..62f58e423af6 100644 --- a/scripts/ui-assets.cmake +++ b/scripts/ui-assets.cmake @@ -225,7 +225,10 @@ function(emit_files dist_dir) set(gzip_dir "${gzip_root}/_gzip") file(REMOVE_RECURSE "${gzip_root}") foreach(f IN LISTS assets) - get_filename_component(asset_path "${dist_dir}/${f}" REALPATH) + get_filename_component(asset_path "${dist_dir}/${f}" ABSOLUTE) + if(IS_SYMLINK "${asset_path}") + get_filename_component(asset_path "${asset_path}" REALPATH) + endif() get_filename_component(dst_dir "${gzip_dir}/${f}" DIRECTORY) file(MAKE_DIRECTORY "${dst_dir}") file(ARCHIVE_CREATE From 40fe9164f43b4e7b4bf2a261813eed768c367468 Mon Sep 17 00:00:00 2001 From: Noah <99681487+NoahOksuz@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:13:59 +0000 Subject: [PATCH 057/275] server : retry prompt cache restore after clearing idle slots (#30997) With a unified KV cache, a RAM-cached prompt can fail to restore because another idle slot still holds the cells it needs. Save and clear the other idle slots and retry the restore once in update_prompt_cache(). Builds on #32828, which keeps the cache entry intact when a restore fails. Fixes #30961. --- tools/server/server-context.cpp | 57 +++++++++++++------ .../tests/unit/test_kv_keep_only_active.py | 38 +++++++++++++ 2 files changed, 77 insertions(+), 18 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 932d08bc71dd..2f927d74fe19 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -1824,6 +1824,29 @@ struct server_context_impl { return res; } + // save idle slots (except id_slot_keep) to the prompt cache; with a unified KV cache, also clear them + void cache_idle_slots(int32_t id_slot_keep = -1) { + if (!params_base.cache_idle_slots) { + return; + } + + for (auto & slot : slots) { + if (slot.id != id_slot_keep && !slot.is_processing()) { + SLT_TRC(slot, "%s", "saving idle slot to prompt cache\n"); + + if (slot.prompt_save(*prompt_cache)) { + SLT_DBG(slot, "%s", "__TEST_TAG_CACHE_IDLE_SLOT__\n"); + prompt_cache->update(); + } + + if (params_base.kv_unified) { + // [TAG_IDLE_SLOT_CLEAR] + slot.prompt_clear(); + } + } + } + } + // call only when the task is sure to launch on the slot void update_prompt_cache(server_slot & slot, const server_task & task) { SRV_TRC("%s", "updating prompt cache\n"); @@ -1832,8 +1855,22 @@ struct server_context_impl { slot.prompt_save(*prompt_cache); - if (!slot.prompt_load(*prompt_cache, task.tokens, get_task_lora(task))) { + const auto lora = get_task_lora(task); + + if (!slot.prompt_load(*prompt_cache, task.tokens, lora)) { slot.prompt_clear(); + + // with a unified KV cache, the restore can fail because idle slots still hold the cells it needs + // the cache entry is kept on failure, so free those slots and retry once + if (params_base.kv_unified && params_base.cache_idle_slots) { + cache_idle_slots(slot.id); + + SLT_INF(slot, "%s", "retrying prompt restore after clearing idle slots\n"); + + if (!slot.prompt_load(*prompt_cache, task.tokens, lora)) { + slot.prompt_clear(); + } + } } prompt_cache->update(); @@ -3022,23 +3059,7 @@ struct server_context_impl { break; // drop the task } - if (params_base.cache_idle_slots) { - for (auto & slot : slots) { - if (!slot.is_processing()) { - SLT_TRC(slot, "%s", "saving idle slot to prompt cache\n"); - - if (slot.prompt_save(*prompt_cache)) { - SLT_DBG(slot, "%s", "__TEST_TAG_CACHE_IDLE_SLOT__\n"); - prompt_cache->update(); - } - - if (params_base.kv_unified) { - // [TAG_IDLE_SLOT_CLEAR] - slot.prompt_clear(); - } - } - } - } + cache_idle_slots(); } break; case SERVER_TASK_TYPE_CANCEL: { diff --git a/tools/server/tests/unit/test_kv_keep_only_active.py b/tools/server/tests/unit/test_kv_keep_only_active.py index 44c05fab0cbc..d8838f9e053a 100644 --- a/tools/server/tests/unit/test_kv_keep_only_active.py +++ b/tools/server/tests/unit/test_kv_keep_only_active.py @@ -89,6 +89,44 @@ def test_clear_and_restore(): assert "__TEST_TAG_CACHE_IDLE_SLOT__" not in log.drain() +@pytest.mark.parametrize("n_slots,n_ctx,cache_ram,n_tokens_a,n_tokens_b", [ + (2, 512, 100, 350, 300), + (3, 512, 100, 350, 300), + # Both prompts fit in KV, but their states do not fit together in RAM. + (2, 2048, 1, 1200, 700), +]) +def test_restore_under_cache_pressure(n_slots, n_ctx, cache_ram, n_tokens_a, n_tokens_b): + global server + server.n_slots = n_slots + server.n_ctx = n_ctx + server.cache_ram = cache_ram + server.override_kv = f"llama.context_length=int:{n_ctx}" + server.start() + + res = server.make_request("POST", "/tokenize", data={"content": "Hello world"}) + assert res.status_code == 200 + tokens = res.body["tokens"] + prompt_a = [tokens[0]] * n_tokens_a + prompt_b = [tokens[-1]] * n_tokens_b + + for prompt, n_cached in [ + (prompt_a, 0), + (prompt_a + [tokens[0]] * 10, n_tokens_a), + (prompt_b, 0), + (prompt_a + [tokens[0]] * 20, n_tokens_a + 10), + (prompt_b + [tokens[-1]] * 10, n_tokens_b), + (prompt_a + [tokens[0]] * 30, n_tokens_a + 20), + ]: + res = server.make_request("POST", "/completion", data={ + "prompt": prompt, + "n_predict": 1, + "cache_prompt": True, + }) + assert res.status_code == 200 + assert res.body["timings"]["cache_n"] >= n_cached + assert res.body["timings"]["prompt_n"] <= len(prompt) - n_cached + + def test_disabled_with_flag(): global server server.no_cache_idle_slots = True From 97bbf98fdfeb311e50e313fc807d3af1a1ff32d4 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Tue, 24 Nov 2026 15:00:46 +0100 Subject: [PATCH 058/275] ui: make Llama Chat a plain chat unless llama-server offers agent features (#32949) Llama Chat showed its tools, MCP and agentic settings and ran the agentic loop for every server. Now it does so only for a llama-server that offers its built-in tools or its proxy, which --agent turns on together; the app reads this from /props and /tools. Without them it is a plain chat: a message and its reply, with reasoning when the model gives it. The chat store sends the classic request, the tools store has no tools and the MCP store connects to no server, so the tools menu, the working folder, the MCP entry and page, and the Tools and Agentic settings are gone. Tool calls in earlier conversations still display. The Show MCP setting moves from General to the Agentic settings, with the rest of what agent mode adds. VITE_PUBLIC_AGENTIC=false builds an app that is a plain chat for every server, and leaves Llama Harness's loop out of the bundle: the harness gets a ./trace entry with the phrasing alone, and Vite resolves the package to a small stub that re-exports it. A CI job builds the variant and checks the loop is not in it. Assisted-by: Claude (Opus 5.5 Medium) --- .github/workflows/ui.yml | 32 +++++++ ui/apps/chat/.env.example | 2 + ui/apps/chat/.storybook/preview.ts | 4 + ui/apps/chat/README.md | 4 + ui/apps/chat/package.json | 1 + .../ChatFormActionAddButton.svelte | 7 +- .../ChatFormActionAddDropdown.svelte | 11 ++- .../app/dialogs/DialogSearch.svelte | 5 +- .../SidebarNavigation.svelte | 9 +- .../SidebarNavigationFooter.svelte | 5 +- .../settings/SettingsChat/SettingsChat.svelte | 22 ++--- .../chat/src/lib/constants/app.constants.ts | 9 ++ .../constants/attachment-menu.constants.ts | 5 +- .../src/lib/constants/settings.constants.ts | 25 ++++-- .../chat/src/lib/constants/ui.constants.ts | 7 ++ .../src/lib/stores/agentic-mode.svelte.ts | 35 ++++++++ .../lib/stores/agentic/harness-chat-only.ts | 10 +++ .../chat/src/lib/stores/chat/index.svelte.ts | 6 +- .../chat/src/lib/stores/mcp/index.svelte.ts | 4 + ui/apps/chat/src/lib/stores/tools.svelte.ts | 11 ++- .../chat/src/routes/mcp-servers/+page.svelte | 9 +- ui/apps/chat/src/routes/mcp-servers/+page.ts | 9 +- .../form/ChatScreenForm.a11y.stories.svelte | 6 +- .../chat/form/ChatScreenForm.stories.svelte | 4 +- .../chat/tests/unit/chat-only-build.test.ts | 87 +++++++++++++++++++ ui/apps/chat/tsconfig.json | 3 +- ui/apps/chat/vite.config.ts | 15 +++- ui/apps/chat/vitest-setup-client.ts | 4 + ui/lib/harness/package.json | 4 + 29 files changed, 311 insertions(+), 44 deletions(-) create mode 100644 ui/apps/chat/src/lib/stores/agentic-mode.svelte.ts create mode 100644 ui/apps/chat/src/lib/stores/agentic/harness-chat-only.ts create mode 100644 ui/apps/chat/tests/unit/chat-only-build.test.ts diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml index bba032416bfb..3547bf4c61e5 100644 --- a/.github/workflows/ui.yml +++ b/.github/workflows/ui.yml @@ -212,6 +212,38 @@ jobs: run: npm run prepack working-directory: ui/lib/harness + chat-only-build: + name: Chat-only build + runs-on: ubuntu-24.04 + steps: + - name: Checkout code + uses: actions/checkout@v6 + with: + ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }} + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: "24" + package-manager-cache: false + + - name: Install dependencies + run: npm ci + working-directory: ui/apps/chat + + - name: Build without the agentic loop + run: npm run build + working-directory: ui/apps/chat + env: + VITE_PUBLIC_AGENTIC: "false" + + - name: Check the harness loop is not in the bundle + run: | + if grep -rlq "Tool execution was interrupted by a new user message" dist; then + echo "The chat-only bundle contains Llama Harness's loop" && exit 1 + fi + working-directory: ui/apps/chat + e2e-tests: name: E2E Tests needs: ui-build diff --git a/ui/apps/chat/.env.example b/ui/apps/chat/.env.example index 9760b0dd43fb..269e65278648 100644 --- a/ui/apps/chat/.env.example +++ b/ui/apps/chat/.env.example @@ -1,4 +1,6 @@ VITE_PUBLIC_APP_NAME='Llama Chat' +# 'false' builds a chat-only app: no tools, no MCP, no agentic loop +# VITE_PUBLIC_AGENTIC='false' VITE_DEBUG='true' VITE_PUBLIC_SERVER_ORIGIN='http://localhost:8033' diff --git a/ui/apps/chat/.storybook/preview.ts b/ui/apps/chat/.storybook/preview.ts index 22f04dd88609..47c884fd0f99 100644 --- a/ui/apps/chat/.storybook/preview.ts +++ b/ui/apps/chat/.storybook/preview.ts @@ -1,5 +1,6 @@ import '../src/app.css'; import { MEDIA_QUERIES } from '#lib/constants/pwa.constants.ts'; +import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts'; // the docs pages' styles, shared with the library's Storybook import '../../../lib/ui/.storybook/docs.css'; import { applyColorScheme } from './color-scheme'; @@ -7,6 +8,9 @@ import ModeWatcherDecorator from './decorators/ModeWatcherDecorator.svelte'; import TooltipProviderDecorator from './decorators/TooltipProviderDecorator.svelte'; import type { Preview } from '@storybook/sveltekit'; +// the stories show the app as with a llama-server started with --agent +agenticMode.serverHasTools = true; + applyColorScheme(); window.matchMedia(MEDIA_QUERIES.PREFERS_DARK).addEventListener('change', applyColorScheme); diff --git a/ui/apps/chat/README.md b/ui/apps/chat/README.md index 891fe6b2a422..6ba2e8957d10 100644 --- a/ui/apps/chat/README.md +++ b/ui/apps/chat/README.md @@ -154,6 +154,10 @@ llama-server serves the UI with `Cross-Origin-Embedder-Policy: require-corp` and llama-server embeds it: when llama-server is built, `scripts/ui-assets.cmake` takes `ui/apps/chat/dist` if it exists, runs `npm run build` if `LLAMA_BUILD_UI` is on, or downloads the release's prebuilt `dist.tar.gz` from Hugging Face, and compiles every file into the binary. The same `dist` is what `npx @ggml-org/llama-chat` serves. +**Plain chat and agent mode.** Llama Chat is a plain chat, a message and its reply with reasoning when the model gives it, unless llama-server offers the agentic features: its built-in tools or its proxy, which `llama-server --agent` turns on together. The app reads this from `/props` and `/tools`. With them it shows the tools menu, the working folder, MCP and the Tools and Agentic settings, and runs the agentic loop; without them it shows none of these and sends the classic request. Tool calls in earlier conversations still display. + +**Chat-only build.** `VITE_PUBLIC_AGENTIC=false npm run build` builds an app that is a plain chat for every server, and `npm run dev:chat-only` runs the dev server the same way. Llama Harness's loop is left out of its bundle. + ```text ui/apps/chat/ ├── src/ diff --git a/ui/apps/chat/package.json b/ui/apps/chat/package.json index bc3f0d3315d1..76146f41e5b0 100644 --- a/ui/apps/chat/package.json +++ b/ui/apps/chat/package.json @@ -43,6 +43,7 @@ "build": "npm run build-pwa-assets && vite build", "build-pwa-assets": "pwa-assets-generator --root . --config pwa-assets.config.ts && pwa-assets-generator --root . --config pwa-assets-dark.config.ts && node scripts/make-icons-circular.js", "dev": "bash scripts/dev.sh", + "dev:chat-only": "VITE_PUBLIC_AGENTIC=false bash scripts/dev.sh", "preview": "vite preview", "prepare": "svelte-kit sync || echo ''", "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddButton.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddButton.svelte index e25bcb56f72c..11c8a19544dd 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddButton.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddButton.svelte @@ -2,7 +2,8 @@ import { Button } from '@ggml-org/llama-ui/ui/button'; import * as Tooltip from '@ggml-org/llama-ui/ui/tooltip'; import { Plus } from '@lucide/svelte'; - import { ATTACHMENT_TOOLTIP_TEXT, ICON_CLASS_DEFAULT } from '#lib/constants/index.ts'; + import { attachmentTooltipText, ICON_CLASS_DEFAULT } from '#lib/constants/index.ts'; + import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts'; interface Props { disabled?: boolean; @@ -21,13 +22,13 @@ type="button" variant="ghost" > - {ATTACHMENT_TOOLTIP_TEXT} + {attachmentTooltipText(agenticMode.enabled)} -

{ATTACHMENT_TOOLTIP_TEXT}

+

{attachmentTooltipText(agenticMode.enabled)}

diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDropdown.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDropdown.svelte index 78153bfbdfbe..d86d663f3808 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDropdown.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDropdown.svelte @@ -9,13 +9,14 @@ ATTACHMENT_FILE_ITEMS, ATTACHMENT_MENU_TEXT, ATTACHMENT_MODALITY_TEXT, - ATTACHMENT_TOOLTIP_TEXT, + attachmentTooltipText, ICON_CLASS_DEFAULT, MODALITY_ICONS } from '#lib/constants/index.ts'; import { getChatFormActionsContext } from '#lib/contexts/index.ts'; import { AttachmentAction, AttachmentItemEnabledWhen, ModelModality } from '#lib/enums/index.ts'; import { useAttachmentMenu } from '#lib/hooks/use-attachment-menu.svelte.ts'; + import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts'; import type { Component } from 'svelte'; interface Props { @@ -84,7 +85,7 @@ )} disabled={chatFormActions.disabled} > - {ATTACHMENT_TOOLTIP_TEXT} + {attachmentTooltipText(agenticMode.enabled)} @@ -92,7 +93,7 @@ -

{ATTACHMENT_TOOLTIP_TEXT}

+

{attachmentTooltipText(agenticMode.enabled)}

@@ -160,7 +161,9 @@ {/if} - + {#if agenticMode.enabled} + + {/if}
diff --git a/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte b/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte index 9a241af2835b..80d0cb5fdc6f 100644 --- a/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte +++ b/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte @@ -22,7 +22,7 @@ ICON_CLASS_SM, ICON_CLASS_XS, SIDEBAR_ACTIONS_ITEMS, - SIDEBAR_FOOTER_ITEMS + sidebarFooterItems } from '#lib/constants/index.ts'; import { KeyboardKey, SidebarAction } from '#lib/enums/index.ts'; import { useDebouncedSearch } from '#lib/hooks/use-debounced-search.svelte.ts'; @@ -32,6 +32,7 @@ HuggingFaceService } from '#lib/services/index.ts'; import { RouterService } from '#lib/services/router.service.ts'; + import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts'; import { conversationsStore, deviceStore, @@ -248,7 +249,7 @@ const actionEntries = $derived.by((): SearchEntry[] => // every sidebar action the sidebar shows but Search itself, which is what opened this // dialog, and the models manager on a phone, which picks its models in the selector - [...SIDEBAR_ACTIONS_ITEMS, ...SIDEBAR_FOOTER_ITEMS] + [...SIDEBAR_ACTIONS_ITEMS, ...sidebarFooterItems(agenticMode.enabled)] .filter( (item) => item.action && diff --git a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte index 4ca101874ce6..ebbc539f6418 100644 --- a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte +++ b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte @@ -22,18 +22,19 @@ SIDEBAR_COLLAPSE_WIDTH, SIDEBAR_COLLAPSED_WIDTH, SIDEBAR_CONTENT_FADE_MS, - SIDEBAR_FOOTER_ITEMS, SIDEBAR_MAX_WIDTH, SIDEBAR_MIN_WIDTH, SIDEBAR_OVERSTRETCH_PX, SIDEBAR_REVEAL_ACTION_DELAY_MS, SIDEBAR_SETTLE_MS, - SIDEBAR_TOGGLE_MS + SIDEBAR_TOGGLE_MS, + sidebarFooterItems } from '#lib/constants/index.ts'; import { SidebarAction, TooltipSide } from '#lib/enums/index.ts'; import { useKeyboardShortcuts } from '#lib/hooks/use-keyboard-shortcuts.svelte.ts'; import { useMarqueeSelection } from '#lib/hooks/use-marquee-selection.svelte.ts'; import { RouterService } from '#lib/services/router.service.ts'; + import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts'; import { chatStore, conversationsStore, @@ -668,7 +669,9 @@ diff --git a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte index b236dc3db653..714d0f64627d 100644 --- a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte +++ b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte @@ -1,7 +1,8 @@ diff --git a/ui/apps/chat/src/routes/mcp-servers/+page.ts b/ui/apps/chat/src/routes/mcp-servers/+page.ts index 3c3deac5178a..76161de8783a 100644 --- a/ui/apps/chat/src/routes/mcp-servers/+page.ts +++ b/ui/apps/chat/src/routes/mcp-servers/+page.ts @@ -1,4 +1,11 @@ import type { PageLoad } from './$types'; +import { redirect } from '@sveltejs/kit'; +import { AGENTIC_ENABLED, ROUTES } from '#lib/constants/index.ts'; import { loadAppRoute } from '#lib/stores/init.ts'; -export const load: PageLoad = ({ fetch }) => loadAppRoute(fetch); +export const load: PageLoad = ({ fetch }) => { + // a chat-only build has no MCP + if (!AGENTIC_ENABLED) redirect(307, ROUTES.START); + + return loadAppRoute(fetch); +}; diff --git a/ui/apps/chat/tests/stories/chat/form/ChatScreenForm.a11y.stories.svelte b/ui/apps/chat/tests/stories/chat/form/ChatScreenForm.a11y.stories.svelte index b1058822af45..ad443f61ccdf 100644 --- a/ui/apps/chat/tests/stories/chat/form/ChatScreenForm.a11y.stories.svelte +++ b/ui/apps/chat/tests/stories/chat/form/ChatScreenForm.a11y.stories.svelte @@ -1,7 +1,7 @@ {#if showChip} - + onclick={onOpen} + type="button" + > + + +
{/if} - - {/if} +
+ {#if showWorkingDirectory} + + + {/if} + + {#if systemMessageChip} + + {/if} +
+ import { Card } from '@ggml-org/llama-ui/ui/card'; + import { MessageSquareText, X } from '@lucide/svelte'; + import { ActionIcon, DialogSystemMessageEdit } from '#lib/components/app/index.ts'; + import { chatStore } from '#lib/stores/index.ts'; + + interface Props { + class?: string; + content: string; + disabled?: boolean; + } + + let { class: className = '', content, disabled = false }: Props = $props(); + + let isOpen = $state(false); + + +
+
+ + + Custom system message +
+ + + + {#if !disabled} +
+ chatStore.removeSystemPrompt()} + stopPropagationOnClick + tooltip="Remove" + /> +
+ {/if} +
+ + chatStore.saveSystemPrompt(next)} +/> diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormSystemMessageChip.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormSystemMessageChip.svelte new file mode 100644 index 000000000000..d797ce2086c5 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormSystemMessageChip.svelte @@ -0,0 +1,40 @@ + + +{#if hasContent} +
+ +
+ + chatStore.saveSystemPrompt(next)} + /> +{/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte index 21bd62201f34..93dea8c1fd24 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte @@ -1,8 +1,9 @@ + + + + + + + Custom system message + + + + The starting message that defines how the model behaves in this conversation. + + + + + />
{/if} -
+ +
{#if showWorkingDirectory} { - if (!isOpen) return; + if (!isOpen || inline) return; setTimeout(() => searchInputRef?.focus(), FOCUS_DELAY_MS); }); @@ -160,32 +167,14 @@ return; } - try { - // Generous limit: ranking is client-side, only the top - // MAX_RESULTS_SHOWN are shown. - // A plain query navigates home as if typed after `~/`; a query - // starting from a root or `~` navigates the absolute tree. - const res = await runGlobSearchWithChildren( - toHomeRelativeQuery(trimmed, homeBase), - homeBase ?? HOME_TILDE, - SEARCH.MAX_DEPTH, - SEARCH.LIMIT, - signal, - { type: GlobSearchType.DIR } - ); - + // Every round of results starts with its first folder highlighted. A stale + // search must not touch the list: the next one is already running. + const show = (res: GlobSearchChildResult) => { if (!isCurrent()) return; - if (res.error) { - queryResults = []; - nav.reset(-1); - searchError = res.error; - - return; - } - searchScope = res.exactDir ?? res.args.path; queryResults = res.entries.map((e) => e.path).slice(0, SEARCH.MAX_RESULTS_SHOWN); + searchError = res.error ?? null; if (queryResults.length > 0) { nav.reset(0); @@ -193,8 +182,10 @@ } else { nav.reset(-1); } + }; - searchError = null; + try { + show(await runFolderSearch(trimmed, homeBase, signal, show)); } catch (err) { if (!isCurrent() || signal.aborted) return; @@ -261,25 +252,60 @@ closePicker(); } - function handleKeydown(event: KeyboardEvent) { - if (event.key === KeyboardKey.ENTER) { + /** True when the key was the picker's: the chat input then leaves it alone. */ + function handlePickerKeydown(event: KeyboardEvent): boolean { + // a key that confirms or moves within an IME composition belongs to the text + if (isIMEComposing(event)) return false; + + // Enter picks a suggestion, never the typed text: before the results arrive it does + // nothing. Only without file search, where nothing is suggested, does it take the path + // as typed + if (event.key === KeyboardKey.ENTER && !event.shiftKey) { event.preventDefault(); if (nav.hoveredIndex >= 0 && queryResults[nav.hoveredIndex]) { commit(queryResults[nav.hoveredIndex]); - } else if (queryResults.length === 0) { + } else if (!fileSearchEnabled) { handleSubmit(); } - } else if (event.key === KeyboardKey.ARROW_DOWN) { - if (queryResults.length > 0) { - event.preventDefault(); - nav.move(1); - } - } else if (event.key === KeyboardKey.ARROW_UP) { - if (queryResults.length > 0) { - event.preventDefault(); - nav.move(-1); - } + + return true; + } + + if ( + (event.key === KeyboardKey.ARROW_DOWN || event.key === KeyboardKey.ARROW_UP) && + queryResults.length > 0 + ) { + event.preventDefault(); + nav.move(event.key === KeyboardKey.ARROW_DOWN ? 1 : -1); + + return true; + } + + if (inline && event.key === KeyboardKey.ESCAPE) { + event.preventDefault(); + closePicker(); + + return true; + } + + return false; + } + + /** The chat input's keys while the path is typed on its `/cwd` line. */ + export function handleKeydown(event: KeyboardEvent): boolean { + if (!isOpen || !inline) return false; + + return handlePickerKeydown(event); + } + + // Inline, the chat input is the picker's field: pressing in the form (to move the caret, + // say) keeps the picker open + function handleInteractOutside(event: PointerEvent) { + const target = event.target; + + if (inline && target instanceof Node && customAnchor?.closest('form')?.contains(target)) { + event.preventDefault(); } } @@ -380,14 +406,27 @@ {#snippet picker(inDrawer: boolean)} -
- + +
+ {#if inline} + {#if fileSearchEnabled && !query.trim()} +
+ Type a folder name or path after /cwd +
+ {/if} + {:else} + + {/if} {#if !fileSearchEnabled}
{searchUnavailableMessage}
@@ -460,7 +499,7 @@ {#if deviceStore.isMobile} - + Working directory @@ -484,16 +523,20 @@ Open working directory picker + event.preventDefault()} + onInteractOutside={handleInteractOutside} onOpenAutoFocus={(event) => event.preventDefault()} - onkeydown={handleKeydown} + onkeydown={handlePickerKeydown} preventScroll={false} side="top" sideOffset={12} + trapFocus={!inline} > {@render picker(false)} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte index bc368ac74a14..659f9f62dc01 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte @@ -2,7 +2,7 @@ import { cn } from '@ggml-org/llama-ui/utils'; import { Folder } from '@lucide/svelte'; import { UI_DATA_ATTRS } from '#lib/constants/index.ts'; - import { highlightMatch } from '#lib/utils/index.ts'; + import { hasPointerMoved, highlightMatch } from '#lib/utils/index.ts'; import { fly } from 'svelte/transition'; // Fly-in transition for the results list. @@ -53,7 +53,9 @@ )} data-highlighted={index === hoveredIndex ? '' : undefined} onclick={() => onCommit?.(path)} - onmouseenter={() => onHover?.(index)} + onmousemove={(event) => { + if (hasPointerMoved(event)) onHover?.(index); + }} > diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPicker/ChatFormPickerListItem.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPicker/ChatFormPickerListItem.svelte index 03a76e61b5ea..180cb1fbc308 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPicker/ChatFormPickerListItem.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPicker/ChatFormPickerListItem.svelte @@ -1,12 +1,14 @@
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTaskRow.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTaskRow.svelte new file mode 100644 index 000000000000..2508bdf8b940 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTaskRow.svelte @@ -0,0 +1,113 @@ + + +
+
+ + {task.description || task.command} + + + +
+ + + {#snippet titleSnippet()} + + {/snippet} + +
+
+ task {task.id} · started + {formatRelativeTime(task.started_at * MS_PER_SECOND)} +
+ + {#if log.skipped > 0} +
+ {BACKGROUND_TASK_SKIPPED_LABEL(log.skipped)} +
+ {/if} + +
{log.text || BACKGROUND_TASK_NO_OUTPUT_LABEL}
+
+
+
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTasks.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTasks.svelte new file mode 100644 index 000000000000..06217388d86c --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTasks.svelte @@ -0,0 +1,77 @@ + + + (hidden = document.hidden)} /> + +{#if store.available && count > 0} + (store.dialogOpen = true)}> + + + {BACKGROUND_TASKS_RUNNING_LABEL(count)} + +{/if} + + + + + {BACKGROUND_TASKS_DIALOG_TITLE} + + {#if count > 1} + + {/if} + + + + + + + {BACKGROUND_TASKS_DIALOG_DESCRIPTION} + +
+ {#each store.tasks as task (task.id)} + + {:else} +

{BACKGROUND_TASKS_EMPTY_LABEL}

+ {/each} +
+
+
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormSystemMessageChip.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormSystemMessageChip.svelte index d797ce2086c5..fe7ebc656c80 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormSystemMessageChip.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormSystemMessageChip.svelte @@ -1,4 +1,5 @@ -{#snippet promptLine()} - {#if cwd} - {wdDisplay} - {/if} - - $ - - {#if highlightedCommandHtml} - {@html highlightedCommandHtml} - {:else} - {execShellMeta?.command} - {/if} - - {#if commandStreaming} - - {/if} -{/snippet} -
- {@render promptLine()} +
{#if (ctx.isPending && !commandStreaming) || (isLive && !section.toolResult)} @@ -334,40 +350,24 @@ {/snippet}
- diff --git a/ui/apps/chat/src/lib/components/app/content/index.ts b/ui/apps/chat/src/lib/components/app/content/index.ts index c3d69b6d69cf..7b4e7c6bd9b1 100644 --- a/ui/apps/chat/src/lib/components/app/content/index.ts +++ b/ui/apps/chat/src/lib/components/app/content/index.ts @@ -126,6 +126,15 @@ export { default as CollapsibleContentBlock } from './CollapsibleContentBlock.sv */ export { default as CollapsibleTerminalBlock } from './CollapsibleTerminalBlock.svelte'; +/** + * **ShellPromptLine** - A shell command as a terminal prompt shows it + * + * The working directory (home abbreviated), a dim `$` and the command, optionally + * highlighted and with a typing cursor. Shared by the shell tool call and the + * background tasks list so both read the same. + */ +export { default as ShellPromptLine } from './ShellPromptLine.svelte'; + /** * **MermaidPreview** - Pan and zoom viewer for a diagram's svg * diff --git a/ui/apps/chat/src/lib/constants/api-endpoints.constants.ts b/ui/apps/chat/src/lib/constants/api-endpoints.constants.ts index 2f6efb94cba3..532fa147e044 100644 --- a/ui/apps/chat/src/lib/constants/api-endpoints.constants.ts +++ b/ui/apps/chat/src/lib/constants/api-endpoints.constants.ts @@ -24,6 +24,14 @@ export const API_TOOLS = { LIST: '/tools' }; +// the background tasks of a conversation: `POST` moves a running command to the background, +// `DELETE` stops one, and both answer with the task they changed +export const API_TOOLS_TASKS = { + EVENTS: '/tools/tasks/events', + OUTPUT: '/tools/tasks/output', + TASKS: '/tools/tasks' +}; + // resumable stream routes, the conv::model identity travels as the conv_id query param // because model names can contain slashes that a path segment cannot carry // resume retry cadence while the owning model is still loading (server answers 503) diff --git a/ui/apps/chat/src/lib/constants/background-tasks.constants.ts b/ui/apps/chat/src/lib/constants/background-tasks.constants.ts new file mode 100644 index 000000000000..61aa63b55df8 --- /dev/null +++ b/ui/apps/chat/src/lib/constants/background-tasks.constants.ts @@ -0,0 +1,37 @@ +// how long the task event stream waits before it reads again after it went away, doubling +// each time up to the maximum +export const BACKGROUND_TASKS_RETRY_MS = 1000; +export const BACKGROUND_TASKS_RETRY_MAX_MS = 15_000; + +// how much of a task's output the chat keeps, the same as the server does: the front is +// dropped past it +export const BACKGROUND_TASK_LOG_MAX_LENGTH = 256 * 1024; + +/** The background tasks dialog's title, and what it says while the conversation runs none */ +export const BACKGROUND_TASKS_DIALOG_TITLE = 'Background tasks'; +export const BACKGROUND_TASKS_EMPTY_LABEL = 'Nothing is running in the background.'; +export const BACKGROUND_TASKS_DIALOG_DESCRIPTION = + 'Commands llama-server keeps running for this conversation, with their output'; + +/** What an open task row shows before the task printed anything */ +export const BACKGROUND_TASK_NO_OUTPUT_LABEL = 'No output yet'; + +/** Stopping a task, from its row or all of them at once */ +export const BACKGROUND_TASK_STOP_LABEL = 'Stop'; +export const BACKGROUND_TASK_STOP_ARIA_LABEL = 'Stop task'; +export const BACKGROUND_TASK_STOP_FAILED = 'Could not stop the task'; +export const BACKGROUND_TASKS_STOP_ALL_LABEL = 'Stop all'; + +/** Above an output only the end of was kept */ +export const BACKGROUND_TASK_SKIPPED_LABEL = (bytes: number): string => + `[${bytes} earlier bytes dropped]`; + +/** The button under a running shell call that lets it go on as a background task */ +export const BACKGROUND_TASK_DETACH_LABEL = 'Move to background'; +export const BACKGROUND_TASK_DETACH_TITLE = + 'Keep it running as a background task and let the agent go on'; +export const BACKGROUND_TASK_DETACH_FAILED = 'Could not move the command to the background'; + +/** The chip's label: how many tasks the conversation runs */ +export const BACKGROUND_TASKS_RUNNING_LABEL = (count: number): string => + `${count} background ${count === 1 ? 'task' : 'tasks'}`; diff --git a/ui/apps/chat/src/lib/constants/index.ts b/ui/apps/chat/src/lib/constants/index.ts index b01f3f57f652..bc482b5962b9 100644 --- a/ui/apps/chat/src/lib/constants/index.ts +++ b/ui/apps/chat/src/lib/constants/index.ts @@ -4,6 +4,7 @@ export * from './agentic.constants'; export * from './api-endpoints.constants'; export * from './app.constants'; +export * from './background-tasks.constants'; export * from './backend.constants'; export * from './chat-tabs.constants'; export * from './database.constants'; diff --git a/ui/apps/chat/src/lib/constants/tool-ui.constants.ts b/ui/apps/chat/src/lib/constants/tool-ui.constants.ts index dce125262e3e..f0970379ee0c 100644 --- a/ui/apps/chat/src/lib/constants/tool-ui.constants.ts +++ b/ui/apps/chat/src/lib/constants/tool-ui.constants.ts @@ -8,6 +8,7 @@ // ChatMessageToolCallBlockSearchResults for prior art). import Braces from '@lucide/svelte/icons/braces'; +import CircleDashed from '@lucide/svelte/icons/circle-dashed'; import Clock from '@lucide/svelte/icons/clock'; import Eye from '@lucide/svelte/icons/eye'; import FilePen from '@lucide/svelte/icons/file-pen'; @@ -38,6 +39,11 @@ export const TOOL_UI: Readonly> = { label: 'Search chats', source: ToolSource.BROWSER }, + [BuiltInTool.SERVER_BACKGROUND_TASK]: { + icon: CircleDashed, + label: 'Background task', + source: ToolSource.SERVER + }, [BuiltInTool.SERVER_EDIT_FILE]: { icon: FilePen, label: 'Edit file', source: ToolSource.SERVER }, [BuiltInTool.SERVER_EXEC_SHELL_COMMAND]: { icon: Terminal, diff --git a/ui/apps/chat/src/lib/enums/index.ts b/ui/apps/chat/src/lib/enums/index.ts index 088d0d0c738e..3e52bc46bee2 100644 --- a/ui/apps/chat/src/lib/enums/index.ts +++ b/ui/apps/chat/src/lib/enums/index.ts @@ -121,6 +121,8 @@ export { export { KeyboardKey } from './keyboard.enums'; export { + BackgroundTaskStatus, + BackgroundTasksServerEvent, BuiltInTool, GlobSearchType, SearchChatsMessageSelection, diff --git a/ui/apps/chat/src/lib/enums/tools.enums.ts b/ui/apps/chat/src/lib/enums/tools.enums.ts index 2bda6872284b..7381b3b81ee0 100644 --- a/ui/apps/chat/src/lib/enums/tools.enums.ts +++ b/ui/apps/chat/src/lib/enums/tools.enums.ts @@ -46,6 +46,7 @@ export enum BuiltInTool { BROWSER_READ_MEDIA = 'read_media', BROWSER_RUN_JAVASCRIPT = 'run_javascript', BROWSER_SEARCH_CHATS = 'search_chats', + SERVER_BACKGROUND_TASK = 'background_task', SERVER_EDIT_FILE = 'edit_file', SERVER_EXEC_SHELL_COMMAND = 'exec_shell_command', SERVER_FILE_GLOB_SEARCH = 'file_glob_search', @@ -67,3 +68,18 @@ export enum SearchChatsOrder { ASC = 'asc', DESC = 'desc' } + +/** What a background task is doing, as llama-server names it */ +export enum BackgroundTaskStatus { + EXITED = 'exited', + RUNNING = 'running', + STOPPED = 'stopped' +} + +/** The events llama-server sends on `GET /tools/tasks/events` */ +export enum BackgroundTasksServerEvent { + SNAPSHOT = 'snapshot', + TASK_EXITED = 'task_exited', + TASK_OUTPUT = 'task_output', + TASK_STARTED = 'task_started' +} diff --git a/ui/apps/chat/src/lib/services/background-tasks.service.ts b/ui/apps/chat/src/lib/services/background-tasks.service.ts new file mode 100644 index 000000000000..7fc675513b52 --- /dev/null +++ b/ui/apps/chat/src/lib/services/background-tasks.service.ts @@ -0,0 +1,87 @@ +/** + * BackgroundTasksService - The commands llama-server keeps running for a conversation + * + * `exec_shell_command` runs every command as a task. A task outlives its call once it moves to + * the background - the model asks for that when it starts the command, the user asks for it while + * the command runs - and it then belongs to the conversation the call carried in its + * `X-Conversation-Id` header, which `ToolsService` sends. Every route is scoped to the + * conversation the request names, so every call here names one. The server side, and what each + * route answers, is documented in `tools/server/README-dev.md`. + * + * No state: the tasks of the conversation the chat is on live in `backgroundTasksStore`. + */ + +import { API_TOOLS_TASKS } from '#lib/constants/index.ts'; +import type { + BackgroundTask, + BackgroundTaskOutput, + BackgroundTasksEvent +} from '#lib/types/index.ts'; +import { apiFetch } from '#lib/utils/api-fetch.ts'; +import { getAuthHeaders } from '#lib/utils/api-headers.ts'; +import { serverUrl } from '#lib/utils/server-config.ts'; +import { parseSseJsonStream } from '#lib/utils/sse.ts'; + +/** The query of a route that works on one task of one conversation */ +function taskParams(conversationId: string, id: number): URLSearchParams { + return new URLSearchParams({ conv_id: conversationId, id: String(id) }); +} + +export class BackgroundTasksService { + /** Move a running command to the background: its call returns at once, the command goes on */ + static detach(conversationId: string, execId: number): Promise { + return apiFetch(API_TOOLS_TASKS.TASKS, { + body: JSON.stringify({ conv_id: conversationId, from_exec_id: execId }), + method: 'POST' + }); + } + + /** + * The tasks of a conversation: a `snapshot` of them, then an event every time one starts, + * prints or ends. The stream stays open while the page keeps reading it, so a caller reads + * it again when this generator returns or throws. + */ + static async *events( + conversationId: string, + signal?: AbortSignal + ): AsyncGenerator { + const params = new URLSearchParams({ conv_ids: conversationId }); + const response = await fetch(`${serverUrl(API_TOOLS_TASKS.EVENTS)}?${params}`, { + headers: { Accept: 'text/event-stream', ...getAuthHeaders() }, + signal + }); + + if (!response.ok || !response.body) { + throw new Error(`background tasks answered ${response.status}`); + } + + for await (const { data } of parseSseJsonStream(response, signal)) { + yield data; + } + } + + /** What a task printed since `from`; `skipped` says how much the server had dropped by then */ + static output( + conversationId: string, + id: number, + from: number, + signal?: AbortSignal + ): Promise { + const params = taskParams(conversationId, id); + + params.set('from', String(from)); + + return apiFetch(`${API_TOOLS_TASKS.OUTPUT}?${params}`, { + authOnly: true, + signal + }); + } + + /** Stop a task, with everything it started */ + static stop(conversationId: string, id: number): Promise { + return apiFetch(`${API_TOOLS_TASKS.TASKS}?${taskParams(conversationId, id)}`, { + authOnly: true, + method: 'DELETE' + }); + } +} diff --git a/ui/apps/chat/src/lib/services/tools.service.ts b/ui/apps/chat/src/lib/services/tools.service.ts index 2f0dd8fa82bb..ada76941ffe6 100644 --- a/ui/apps/chat/src/lib/services/tools.service.ts +++ b/ui/apps/chat/src/lib/services/tools.service.ts @@ -20,16 +20,20 @@ export class ToolsService { * @param cwd - Working directory for the tool call, sent as the * x-tool-cwd request header. The server resolves relative paths * against it; the model cannot override it. + * @param conversationId - The conversation the call belongs to, sent as the + * X-Conversation-Id header: a command it starts can then move to the + * background as a task of that conversation. */ static async executeTool( toolName: string, params: Record, signal?: AbortSignal, - cwd?: string + cwd?: string, + conversationId?: string ): Promise { const result = await apiFetch>(API_TOOLS.EXECUTE, { body: JSON.stringify({ params, tool: toolName }), - headers: cwd ? { [HEADERS.X_TOOL_CWD_HEADER]: cwd } : undefined, + headers: toolHeaders(cwd, conversationId), method: 'POST', signal }); @@ -131,12 +135,10 @@ export class ToolsService { toolName: string, params: Record, signal?: AbortSignal, - cwd?: string + cwd?: string, + conversationId?: string ): AsyncGenerator { - const headers = getJsonHeaders(); - - if (cwd) headers[HEADERS.X_TOOL_CWD_HEADER] = cwd; - + const headers = { ...getJsonHeaders(), ...toolHeaders(cwd, conversationId) }; const response = await fetch(serverUrl(API_TOOLS.EXECUTE), { body: JSON.stringify({ params, stream: true, tool: toolName }), headers, @@ -159,7 +161,11 @@ export class ToolsService { const event = next.value.data; - if (event.chunk !== undefined) { + if (event.exec_id !== undefined) { + yield { chunk: null, done: false, execId: event.exec_id }; + } + + if (event.chunk) { yield { chunk: event.chunk, done: false }; } @@ -182,6 +188,8 @@ export interface ToolStreamEvent { chunk: string | null; done: boolean; error?: string; + /** The server's id of the command an `exec_shell_command` call runs, sent first */ + execId?: number; } /** Wire shape of one SSE event from `POST /tools?stream=true`. */ @@ -189,6 +197,18 @@ interface ToolServerEvent { chunk?: string; done?: boolean; error?: string; + exec_id?: number; +} + +/** The headers that tell the server where a tool call runs and which conversation it is for */ +function toolHeaders(cwd?: string, conversationId?: string): Record { + const headers: Record = {}; + + if (cwd) headers[HEADERS.X_TOOL_CWD_HEADER] = cwd; + + if (conversationId) headers[HEADERS.X_CONVERSATION_ID_HEADER] = conversationId; + + return headers; } async function formatNonOkResponse(response: Response): Promise { diff --git a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts index 78524ba3391e..7d4b4497883a 100644 --- a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts +++ b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts @@ -46,6 +46,7 @@ import { SearchChatsService } from '#lib/services/search-chats.service.ts'; import { ToolsService } from '#lib/services/tools.service.ts'; // direct imports between stores, not via the barrel, to avoid circular deps import { AgenticGates } from '#lib/stores/agentic/gates.svelte.ts'; +import { backgroundTasksStore } from '#lib/stores/background-tasks.svelte.ts'; import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts'; import { mcpStore } from '#lib/stores/mcp/index.svelte.ts'; import { modelsStore } from '#lib/stores/models/index.svelte.ts'; @@ -458,21 +459,39 @@ class AgenticStore { let accumulated = ''; let isError = false; - for await (const ev of ToolsService.streamTool(toolName, args, signal, cwd)) { - if (ev.chunk !== null) { - accumulated += ev.chunk; - context.update(accumulated); - } + // the command can move to the background from its row while it runs, as a task of + // this conversation + try { + for await (const ev of ToolsService.streamTool( + toolName, + args, + signal, + cwd, + conversationId + )) { + if (ev.execId !== undefined) { + backgroundTasksStore.attach(conversationId, toolCall.id, ev.execId); + } - if (ev.done) { - if (ev.error) { - accumulated = accumulated ? `${accumulated}\nError: ${ev.error}` : `Error: ${ev.error}`; + if (ev.chunk !== null) { + accumulated += ev.chunk; context.update(accumulated); - isError = true; } - break; + if (ev.done) { + if (ev.error) { + accumulated = accumulated + ? `${accumulated}\nError: ${ev.error}` + : `Error: ${ev.error}`; + context.update(accumulated); + isError = true; + } + + break; + } } + } finally { + backgroundTasksStore.forget(toolCall.id); } return { content: accumulated, isError }; @@ -482,7 +501,7 @@ class AgenticStore { const args = this.parseToolArguments(toolCall.function.arguments); const cwd = conversationsStore.activeConversation?.cwd; - return ToolsService.executeTool(toolName, args, signal, cwd); + return ToolsService.executeTool(toolName, args, signal, cwd, conversationId); } if (toolSource === ToolSource.BROWSER) { diff --git a/ui/apps/chat/src/lib/stores/background-tasks.svelte.ts b/ui/apps/chat/src/lib/stores/background-tasks.svelte.ts new file mode 100644 index 000000000000..8509347b874e --- /dev/null +++ b/ui/apps/chat/src/lib/stores/background-tasks.svelte.ts @@ -0,0 +1,262 @@ +/** + * backgroundTasksStore - The commands the agent left running in this conversation + * + * llama-server runs every `exec_shell_command` as a task, and a task moved to the background + * belongs to the conversation that started it. This store follows the running tasks of the + * conversation the chat is on over the server's event stream, reads what they print, moves a + * command that is still running to the background, and stops one. The chat form lists them; a + * command still attached to its call is detached from its own row in the trace. + * + * The server owns the list and the processes: this only reads the stream, and a conversation + * keeps its tasks when the user goes back to it. + */ + +import { + BACKGROUND_TASK_DETACH_FAILED, + BACKGROUND_TASK_STOP_FAILED, + BACKGROUND_TASKS_RETRY_MAX_MS, + BACKGROUND_TASKS_RETRY_MS +} from '#lib/constants/index.ts'; +import { BackgroundTasksServerEvent, BackgroundTaskStatus, BuiltInTool } from '#lib/enums/index.ts'; +import { BackgroundTasksService } from '#lib/services/background-tasks.service.ts'; +import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts'; +import { toolsStore } from '#lib/stores/tools.svelte.ts'; +import type { BackgroundTask, BackgroundTaskLog, BackgroundTasksEvent } from '#lib/types/index.ts'; +import { appendTaskOutput, emptyTaskLog, sleep } from '#lib/utils/index.ts'; +import { untrack } from 'svelte'; +import { toast } from 'svelte-sonner'; + +class BackgroundTasksStore { + dialogOpen = $state(false); + + // a command still attached to the call that started it: its tool call, and the server's id of it + private attached = $state>({}); + + // the running tasks of the followed conversation, by id + private byId = $state>({}); + + // the conversation whose tasks are kept, empty until the chat is on one + private followed = ''; + + // what has been read of each task's output + private logs = $state>({}); + + // rows open on screen: only their tasks are read when the server says there is new output + private open = new Set(); + + // a read of a task in flight, so two events do not read it twice + private reading = new Set(); + + // tasks that printed again while a read was in flight: read once more when it lands + private stale = new Set(); + + /** The server runs commands, and keeps the ones that outlive their call */ + get available(): boolean { + return agenticMode.enabled && toolsStore.hasServerTool(BuiltInTool.SERVER_BACKGROUND_TASK); + } + + /** The conversation's running tasks, the newest first */ + get tasks(): BackgroundTask[] { + return Object.values(this.byId).sort((a, b) => b.started_at - a.started_at || b.id - a.id); + } + + /** A call whose command is running and can still be moved to the background */ + attach(conversationId: string, toolCallId: string, execId: number): void { + this.attached[toolCallId] = { conversationId, execId }; + } + + /** + * Moves the command of a running call to the background: its call returns at once and the + * command keeps running as a task of the conversation. + */ + async detach(toolCallId: string): Promise { + const call = this.attached[toolCallId]; + + if (!call) return; + + try { + const task = await BackgroundTasksService.detach(call.conversationId, call.execId); + + this.forget(toolCallId); + this.keep(call.conversationId, task); + } catch (error) { + // a command that ended on its own a moment before has left `attached`: nothing to say + if (this.attached[toolCallId]) { + toast.error(BACKGROUND_TASK_DETACH_FAILED, { + description: error instanceof Error ? error.message : undefined + }); + } + } + } + + /** The command a running call is still attached to, by the id of that call */ + execIdOf(toolCallId?: string): number | undefined { + return toolCallId ? this.attached[toolCallId]?.execId : undefined; + } + + /** Its call is over: the command either ended with it or is a task the list shows */ + forget(toolCallId: string): void { + delete this.attached[toolCallId]; + } + + /** What the chat has read of a task's output */ + log(taskId: number): BackgroundTaskLog { + return this.logs[taskId] ?? emptyTaskLog(); + } + + /** Stops a task, with everything it started */ + async stop(taskId: number): Promise { + const conversationId = this.followed; + + if (!this.byId[taskId]) return; + + try { + this.keep(conversationId, await BackgroundTasksService.stop(conversationId, taskId)); + } catch (error) { + // a task that ended on its own a moment before has left the list: nothing to say + if (conversationId === this.followed && this.byId[taskId]) { + toast.error(BACKGROUND_TASK_STOP_FAILED, { + description: error instanceof Error ? error.message : undefined + }); + } + } + } + + async stopAll(): Promise { + await Promise.all(this.tasks.map((task) => this.stop(task.id))); + } + + /** + * Keeps the tasks of a conversation, and reads their event stream while `follow` is set; + * call it from an `$effect` and hand the effect the return value. The list starts empty + * when the chat moves to another conversation; a stream that stops and starts again on the + * same one (the tab was hidden, the server went away) keeps what was read. + */ + watch(conversationId: string, follow: boolean): void | (() => void) { + if (conversationId !== this.followed) this.reset(conversationId); + + if (!conversationId || !follow) return; + + const controller = new AbortController(); + + // the request reads settings for its headers: none of that is this effect's business + untrack(() => void this.follow(conversationId, controller.signal)); + + return () => controller.abort(); + } + + /** + * Reads a task's output while its row is open, and once at once to fill the row in; + * give the return value to an `$effect`. + */ + watchOutput(taskId: number): () => void { + this.open.add(taskId); + void this.read(taskId); + + return () => this.open.delete(taskId); + } + + /** One event of the task stream */ + private apply(conversationId: string, event: BackgroundTasksEvent): void { + switch (event.event) { + case BackgroundTasksServerEvent.SNAPSHOT: + this.byId = {}; + + for (const task of event.tasks) this.keep(conversationId, task); + + // the stream may have missed what the open rows printed while it was away + for (const taskId of this.open) void this.read(taskId); + + break; + case BackgroundTasksServerEvent.TASK_STARTED: + case BackgroundTasksServerEvent.TASK_EXITED: + this.keep(conversationId, event.task); + + break; + case BackgroundTasksServerEvent.TASK_OUTPUT: + if (this.open.has(event.id)) void this.read(event.id); + + break; + } + } + + // Reads the task stream of a conversation, again when it goes away, until it is aborted. + private async follow(conversationId: string, signal: AbortSignal): Promise { + let delay = BACKGROUND_TASKS_RETRY_MS; + + while (!signal.aborted) { + try { + for await (const event of BackgroundTasksService.events(conversationId, signal)) { + if (signal.aborted) return; + + delay = BACKGROUND_TASKS_RETRY_MS; + this.apply(conversationId, event); + } + } catch { + // the server went away: read again below + } + + if (signal.aborted) return; + + await sleep(delay); + delay = Math.min(delay * 2, BACKGROUND_TASKS_RETRY_MAX_MS); + } + } + + // A task as the server last answered it: listed while it runs, gone once it is done. An + // answer that lands after the chat moved to another conversation is not this list's. + private keep(conversationId: string, task: BackgroundTask): void { + if (conversationId !== this.followed) return; + + if (task.status === BackgroundTaskStatus.RUNNING) { + this.byId[task.id] = task; + } else { + delete this.byId[task.id]; + delete this.logs[task.id]; + } + } + + // What a running task printed since the last read + private async read(taskId: number): Promise { + const conversationId = this.followed; + + if (!this.byId[taskId]) return; + + if (this.reading.has(taskId)) { + this.stale.add(taskId); + + return; + } + + this.reading.add(taskId); + + try { + const read = await BackgroundTasksService.output( + conversationId, + taskId, + this.logs[taskId]?.offset ?? 0 + ); + + if (conversationId === this.followed) { + this.logs[taskId] = appendTaskOutput(this.logs[taskId], read); + } + } catch { + // the server went away, or the task left its list: keep what is known of it + } finally { + this.reading.delete(taskId); + } + + if (this.stale.delete(taskId)) await this.read(taskId); + } + + /** The chat moved to another conversation: start its list empty */ + private reset(conversationId: string): void { + this.followed = conversationId; + this.byId = {}; + this.logs = {}; + this.open.clear(); + this.stale.clear(); + } +} + +export const backgroundTasksStore = new BackgroundTasksStore(); diff --git a/ui/apps/chat/src/lib/stores/index.ts b/ui/apps/chat/src/lib/stores/index.ts index 3ca69b1d928f..438810960527 100644 --- a/ui/apps/chat/src/lib/stores/index.ts +++ b/ui/apps/chat/src/lib/stores/index.ts @@ -34,6 +34,9 @@ export { agenticStore } from './agentic/index.svelte'; // CONVERSATION MEDIA (one slideshow of the thread's images, audio and video) export { mediaGalleryStore } from './media-gallery.svelte'; +// BACKGROUND TASKS (commands llama-server keeps running for a conversation, e.g. dev servers) +export { backgroundTasksStore } from './background-tasks.svelte'; + // CONVERSATIONS export { sidebarDragStore } from './sidebar-drag.svelte'; export { conversationsStore } from './conversations/index.svelte'; diff --git a/ui/apps/chat/src/lib/stores/tools.svelte.ts b/ui/apps/chat/src/lib/stores/tools.svelte.ts index 153e44389017..87ebfc836f56 100644 --- a/ui/apps/chat/src/lib/stores/tools.svelte.ts +++ b/ui/apps/chat/src/lib/stores/tools.svelte.ts @@ -360,6 +360,10 @@ class ToolsStore { }); } + hasServerTool(name: BuiltInTool): boolean { + return this._serverTools.some((def) => def.function.name === name); + } + /** * Load persisted disabled tools and fetch the builtin tool list. * Called by initStores() after migrations have run. @@ -524,10 +528,6 @@ class ToolsStore { } } - private hasServerTool(name: BuiltInTool): boolean { - return this._serverTools.some((def) => def.function.name === name); - } - private inferTypeFromDefault(value: unknown): string | undefined { if (typeof value === 'string') return 'string'; diff --git a/ui/apps/chat/src/lib/types/index.ts b/ui/apps/chat/src/lib/types/index.ts index eb3ef07017d1..3c416a9600d6 100644 --- a/ui/apps/chat/src/lib/types/index.ts +++ b/ui/apps/chat/src/lib/types/index.ts @@ -242,6 +242,10 @@ export type { DesktopIconStripItem, MenuAction } from './navigation'; // Tools types export type { + BackgroundTask, + BackgroundTaskLog, + BackgroundTaskOutput, + BackgroundTasksEvent, EditFileEdit, EditFileMeta, EditFileTitleMeta, diff --git a/ui/apps/chat/src/lib/types/tools.d.ts b/ui/apps/chat/src/lib/types/tools.d.ts index 4f1ab120a1f2..4c5313065b40 100644 --- a/ui/apps/chat/src/lib/types/tools.d.ts +++ b/ui/apps/chat/src/lib/types/tools.d.ts @@ -1,5 +1,9 @@ import type { OpenAIToolDefinition } from './mcp'; -import type { ToolSource } from '#lib/enums/index.ts'; +import type { + BackgroundTasksServerEvent, + BackgroundTaskStatus, + ToolSource +} from '#lib/enums/index.ts'; import type { Component } from 'svelte'; /** @@ -81,3 +85,50 @@ export interface EditFileTitleMeta { editsApplied?: number; errorMessage?: string; } + +/** + * A command llama-server keeps running for one conversation after the tool call + * that started it returned, as its routes answer it (`tools/server/README-dev.md`). + * The server owns the list; Llama Chat only reads it. + */ +export interface BackgroundTask { + /** the server's id of the command: the call that started it and the task it became share it */ + id: number; + command: string; + /** the model's description of the call, may be empty */ + description: string; + /** the working directory the command runs in */ + cwd: string; + /** unix seconds */ + started_at: number; + status: BackgroundTaskStatus; +} + +/** One read of `GET /tools/tasks/output`: the task, and what it printed since the offset asked */ +export interface BackgroundTaskOutput extends BackgroundTask { + output: string; + /** where the read after this one starts */ + next: number; + /** bytes the server dropped between the offset asked and where `output` starts */ + skipped?: number; +} + +/** What the chat has read of a task's output, so a re-read only asks for the new bytes */ +export interface BackgroundTaskLog { + text: string; + /** the offset the next read starts at */ + offset: number; + /** what was dropped from the front, so the text does not start at the beginning */ + skipped: number; +} + +/** One event of `GET /tools/tasks/events` */ +export type BackgroundTasksEvent = + /** the conversation's tasks right now, sent first */ + | { event: BackgroundTasksServerEvent.SNAPSHOT; tasks: BackgroundTask[] } + | { + event: BackgroundTasksServerEvent.TASK_EXITED | BackgroundTasksServerEvent.TASK_STARTED; + task: BackgroundTask; + } + /** a task printed: the offset its output reaches now */ + | { event: BackgroundTasksServerEvent.TASK_OUTPUT; id: number; offset: number }; diff --git a/ui/apps/chat/src/lib/utils/background-tasks.ts b/ui/apps/chat/src/lib/utils/background-tasks.ts new file mode 100644 index 000000000000..cdad2657bec9 --- /dev/null +++ b/ui/apps/chat/src/lib/utils/background-tasks.ts @@ -0,0 +1,26 @@ +import { BACKGROUND_TASK_LOG_MAX_LENGTH } from '#lib/constants/index.ts'; +import type { BackgroundTaskLog, BackgroundTaskOutput } from '#lib/types/index.ts'; + +/** An output nothing has been read of yet */ +export function emptyTaskLog(): BackgroundTaskLog { + return { offset: 0, skipped: 0, text: '' }; +} + +/** + * A read added to what the chat has of a task's output. Only the end of a long output is + * kept: what is cut from the front counts as skipped, like what the server dropped. + */ +export function appendTaskOutput( + current: BackgroundTaskLog | undefined, + read: BackgroundTaskOutput +): BackgroundTaskLog { + const log = current ?? emptyTaskLog(); + const text = log.text + read.output; + const cut = Math.max(0, text.length - BACKGROUND_TASK_LOG_MAX_LENGTH); + + return { + offset: Math.max(log.offset, read.next), + skipped: log.skipped + (read.skipped ?? 0) + cut, + text: text.slice(cut) + }; +} diff --git a/ui/apps/chat/src/lib/utils/index.ts b/ui/apps/chat/src/lib/utils/index.ts index ed7d04d70b6b..68b48a588b40 100644 --- a/ui/apps/chat/src/lib/utils/index.ts +++ b/ui/apps/chat/src/lib/utils/index.ts @@ -223,6 +223,8 @@ export { // Data URL utilities export { createBase64DataUrl } from './data-url'; +export { sleep } from './sleep'; +export { appendTaskOutput, emptyTaskLog } from './background-tasks'; // Header utilities export { parseHeadersToArray, serializeHeaders } from './headers'; diff --git a/ui/apps/chat/src/lib/utils/sleep.ts b/ui/apps/chat/src/lib/utils/sleep.ts new file mode 100644 index 000000000000..254db906f50e --- /dev/null +++ b/ui/apps/chat/src/lib/utils/sleep.ts @@ -0,0 +1,4 @@ +/** Resolves after `ms` milliseconds */ +export function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/ui/apps/chat/tests/client/exec-shell-command-streaming.svelte.test.ts b/ui/apps/chat/tests/client/exec-shell-command-streaming.svelte.test.ts index 0503f8e2e679..09c12cca0f39 100644 --- a/ui/apps/chat/tests/client/exec-shell-command-streaming.svelte.test.ts +++ b/ui/apps/chat/tests/client/exec-shell-command-streaming.svelte.test.ts @@ -61,7 +61,7 @@ function promptText(container: Element): string { } function hasCursor(container: Element): boolean { - return container.querySelector('.exec-cursor') !== null; + return container.querySelector('.shell-cursor') !== null; } describe('exec_shell_command streaming title', () => { diff --git a/ui/apps/chat/tests/stories/chat/form/ChatFormBackgroundTaskRow.stories.svelte b/ui/apps/chat/tests/stories/chat/form/ChatFormBackgroundTaskRow.stories.svelte new file mode 100644 index 000000000000..d8b8c896c79a --- /dev/null +++ b/ui/apps/chat/tests/stories/chat/form/ChatFormBackgroundTaskRow.stories.svelte @@ -0,0 +1,49 @@ + + + + + + + + + + + + + diff --git a/ui/apps/chat/tests/unit/background-tasks.test.ts b/ui/apps/chat/tests/unit/background-tasks.test.ts new file mode 100644 index 000000000000..a5289c4c0c27 --- /dev/null +++ b/ui/apps/chat/tests/unit/background-tasks.test.ts @@ -0,0 +1,48 @@ +import { BACKGROUND_TASK_LOG_MAX_LENGTH } from '#lib/constants/index.ts'; +import { BackgroundTaskStatus } from '#lib/enums/index.ts'; +import type { BackgroundTaskOutput } from '#lib/types/index.ts'; +import { appendTaskOutput } from '#lib/utils/background-tasks.ts'; +import { describe, expect, it } from 'vitest'; + +const read = (overrides: Partial): BackgroundTaskOutput => ({ + command: 'npx -y http-server /tmp/hello-world -p 8780', + cwd: '/tmp', + description: 'Serve the hello world page', + id: 7, + next: 0, + output: '', + started_at: 1_800_000_000, + status: BackgroundTaskStatus.RUNNING, + ...overrides +}); + +describe('appendTaskOutput', () => { + it('adds what a task printed since the last read', () => { + const log = appendTaskOutput(undefined, read({ next: 6, output: 'hello ' })); + + expect(log).toEqual({ offset: 6, skipped: 0, text: 'hello ' }); + expect(appendTaskOutput(log, read({ next: 11, output: 'world' }))).toEqual({ + offset: 11, + skipped: 0, + text: 'hello world' + }); + }); + + it('counts what the server dropped before the read', () => { + expect(appendTaskOutput(undefined, read({ next: 500, output: 'end', skipped: 497 }))).toEqual({ + offset: 500, + skipped: 497, + text: 'end' + }); + }); + + it('keeps only the end of a long output', () => { + const extra = 10; + const output = 'a'.repeat(extra) + 'b'.repeat(BACKGROUND_TASK_LOG_MAX_LENGTH); + const log = appendTaskOutput(undefined, read({ next: output.length, output })); + + expect(log.text).toBe('b'.repeat(BACKGROUND_TASK_LOG_MAX_LENGTH)); + expect(log.skipped).toBe(extra); + expect(log.offset).toBe(output.length); + }); +}); diff --git a/ui/lib/ui/src/lib/components/ui/button/button.svelte b/ui/lib/ui/src/lib/components/ui/button/button.svelte index ae5708010dda..0d4f6b6d8bd3 100644 --- a/ui/lib/ui/src/lib/components/ui/button/button.svelte +++ b/ui/lib/ui/src/lib/components/ui/button/button.svelte @@ -17,13 +17,17 @@ 'icon-lg': 'size-(--height-control-lg)', 'icon-sm': 'size-5 rounded-sm', lg: 'h-control-lg rounded-lg px-6 has-[>svg]:px-4', - sm: 'h-control-sm gap-1.5 rounded-md px-3 has-[>svg]:px-2.5' + sm: 'h-control-sm gap-1.5 rounded-md px-3 has-[>svg]:px-2.5', + // a compact action inside a row or a block: caption text, no fixed height + xs: 'gap-1.5 rounded-md px-2 py-1 text-caption [&_svg:not([class*=size-])]:size-icon-xs' }, variant: { default: 'matte-key-solid [--key-edge:var(--button-primary-edge)] bg-(--action-primary) text-(--fg-on-action) hover:bg-(--action-primary-hover)', destructive: 'matte-key-solid [--key-edge:var(--button-danger-edge)] [--key-sheen-solid:var(--button-danger-sheen)] bg-(--action-danger) hover:bg-(--action-danger-hover) focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 text-(--fg-on-danger)!', + 'danger-secondary': + 'bg-(--action-danger-secondary) text-(--fg-danger) hover:bg-(--action-danger-secondary-hover) focus-visible:bg-(--action-danger-secondary-hover) focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40', ghost: 'hover:text-(--fg-default) hover:bg-(--action-ghost-hover) hover:shadow-(--button-shadow) backdrop-blur-sm', outline: diff --git a/ui/lib/ui/src/lib/components/ui/chip/chip.svelte b/ui/lib/ui/src/lib/components/ui/chip/chip.svelte new file mode 100644 index 000000000000..95cce745bca2 --- /dev/null +++ b/ui/lib/ui/src/lib/components/ui/chip/chip.svelte @@ -0,0 +1,32 @@ + + + + + diff --git a/ui/lib/ui/src/lib/components/ui/chip/index.ts b/ui/lib/ui/src/lib/components/ui/chip/index.ts new file mode 100644 index 000000000000..408c0c2fc123 --- /dev/null +++ b/ui/lib/ui/src/lib/components/ui/chip/index.ts @@ -0,0 +1,2 @@ +export { default as Chip } from './chip.svelte'; +export { chipVariants } from './chip.svelte'; diff --git a/ui/lib/ui/src/lib/styles/tokens/semantic.css b/ui/lib/ui/src/lib/styles/tokens/semantic.css index 842e7085912f..b467071e630d 100644 --- a/ui/lib/ui/src/lib/styles/tokens/semantic.css +++ b/ui/lib/ui/src/lib/styles/tokens/semantic.css @@ -75,6 +75,9 @@ /* one red for every danger state: the danger action is the status fill itself, the alerts' red */ --action-danger: var(--fill-danger); --action-danger-hover: color-mix(in oklch, var(--action-danger) 90%, transparent); + /* the quiet danger action: red text on a faint wash of the same red, stronger on hover */ + --action-danger-secondary: color-mix(in oklch, var(--fill-danger) 8%, transparent); + --action-danger-secondary-hover: color-mix(in oklch, var(--fill-danger) 16%, transparent); --action-quiet: color-mix(in oklch, var(--neutral-100) 30%, transparent); --action-quiet-hover: var(--neutral-100); --action-ghost-hover: color-mix(in oklch, var(--neutral-500) 10%, transparent); @@ -174,6 +177,8 @@ /* the same red as every danger state, as matte glass: the status fill, frosted and translucent over the page */ --action-danger: color-mix(in oklch, var(--fill-danger) 58%, transparent); --action-danger-hover: color-mix(in oklch, var(--fill-danger) 68%, transparent); + --action-danger-secondary: color-mix(in oklch, var(--fill-danger) 12%, transparent); + --action-danger-secondary-hover: color-mix(in oklch, var(--fill-danger) 22%, transparent); --action-quiet: color-mix(in oklch, var(--neutral-400) 15%, transparent); --action-quiet-hover: color-mix(in oklch, var(--neutral-400) 25%, transparent); --action-ghost-hover: color-mix(in oklch, var(--neutral-400) 10%, transparent); diff --git a/ui/lib/ui/tests/stories/components/actions/Button.stories.svelte b/ui/lib/ui/tests/stories/components/actions/Button.stories.svelte index bbabfd5a03e8..30d8df9a0360 100644 --- a/ui/lib/ui/tests/stories/components/actions/Button.stories.svelte +++ b/ui/lib/ui/tests/stories/components/actions/Button.stories.svelte @@ -20,9 +20,10 @@ 'tertiary', 'outline', 'ghost', - 'destructive' + 'destructive', + 'danger-secondary' ]; - const sizes: NonNullable[] = ['sm', 'default', 'lg']; + const sizes: NonNullable[] = ['xs', 'sm', 'default', 'lg']; @@ -48,6 +49,8 @@ + +
diff --git a/ui/lib/ui/tests/stories/components/actions/Chip.stories.svelte b/ui/lib/ui/tests/stories/components/actions/Chip.stories.svelte new file mode 100644 index 000000000000..4e58062fb01f --- /dev/null +++ b/ui/lib/ui/tests/stories/components/actions/Chip.stories.svelte @@ -0,0 +1,33 @@ + + + + + + 1 background task + + + + + A custom system message that runs long + + + + + Custom system message + + + From 04586184cedb8802623b81e025355f4fa1b0050f Mon Sep 17 00:00:00 2001 From: Mustafa Camurcu Date: Tue, 1 Dec 2026 06:42:58 -0800 Subject: [PATCH 267/275] vulkan: read IQ1/IQ2/IQ3 grid tables from a storage buffer (#32915) Upload the grid tables once per device and copy them to shared memory from a storage buffer instead of from GLSL constant arrays, avoiding divergent constant loads in init_iq_shmem. Assisted-by: Claude Opus 5.5 --- ggml/src/ggml-vulkan/ggml-vulkan-types.h | 9 + ggml/src/ggml-vulkan/ggml-vulkan.cpp | 59 +- .../src/ggml-vulkan/vulkan-shaders/types.glsl | 1032 +---------------- 3 files changed, 102 insertions(+), 998 deletions(-) diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-types.h b/ggml/src/ggml-vulkan/ggml-vulkan-types.h index fb2dfecd6d35..47383d50afe3 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-types.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-types.h @@ -234,6 +234,13 @@ static bool is_pow2(uint32_t x) { return x > 1 && (x & (x-1)) == 0; } #define MAX_PARAMETER_COUNT 12 +// binding of the IQ1/IQ2/IQ3 grid tables (see vk_iq_grids), after the regular parameters. +// It is written once per descriptor set and never changes. +#define IQ_GRID_BINDING MAX_PARAMETER_COUNT + +// bindings in the descriptor set layout shared by all pipelines +#define NUM_DESCRIPTOR_BINDINGS (MAX_PARAMETER_COUNT + 1) + #define MAX_FUSED_ADDS (MAX_PARAMETER_COUNT - 3) #define GGML_VK_GDN_CM_V 64u @@ -1070,6 +1077,8 @@ struct vk_device_struct { vk::Fence fence; vk_buffer sync_staging; + vk_buffer iq_grid_buf; + ggml_backend_buffer_type buffer_type; bool disable_fusion; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index ca6bcb2963da..1cdb392c4c63 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -1,5 +1,9 @@ #include "ggml-vulkan-common.h" +#define GGML_COMMON_DECL_CPP +#define GGML_COMMON_IMPL_CPP +#include "ggml-common.h" + static vk_device_architecture get_device_architecture(const vk::PhysicalDevice& device) { vk::PhysicalDeviceProperties props = device.getProperties(); @@ -576,6 +580,45 @@ static bool ggml_vk_roll_bk_loop(const uint32_t * code, size_t word_count, std:: return true; } +// Grid tables of the IQ1/IQ2/IQ3 types, read by the shaders at IQ_GRID_BINDING. +// The offsets must match the IQ*_GRID_OFFSET values in types.glsl (bytes). +struct vk_iq_grids { + uint32_t iq1s[NGRID_IQ1S/2]; // 2 bits per value (v & 3), two grid entries per uint32 + uint32_t iq1s_gpu[NGRID_IQ1S]; // 4 bits per value (v + 1), values 0-3 in the low nibbles + uint64_t iq2xxs[256]; + uint64_t iq2xs[512]; + uint64_t iq2s[1024]; + uint32_t iq3xxs[256]; + uint32_t iq3s[512]; +}; +static_assert(offsetof(vk_iq_grids, iq1s_gpu) == 4096); +static_assert(offsetof(vk_iq_grids, iq2xxs) == 12288); +static_assert(offsetof(vk_iq_grids, iq2xs) == 14336); +static_assert(offsetof(vk_iq_grids, iq2s) == 18432); +static_assert(offsetof(vk_iq_grids, iq3xxs) == 26624); +static_assert(offsetof(vk_iq_grids, iq3s) == 27648); + +static void ggml_vk_init_iq_grids(vk_device & device) { + auto grids = std::make_unique(); // zero-initialized + for (int i = 0; i < NGRID_IQ1S; ++i) { + const int8_t * g = (const int8_t *) &iq1s_grid[i]; + uint32_t gpu = 0; + for (int j = 0; j < 8; ++j) { + grids->iq1s[i / 2] |= (uint32_t)(g[j] & 3) << (16 * (i % 2) + 2 * j); + gpu |= (uint32_t)(g[j] + 1) << (8 * (j % 4) + 4 * (j / 4)); + } + grids->iq1s_gpu[i] = gpu; + } + memcpy(grids->iq2xxs, iq2xxs_grid, sizeof(grids->iq2xxs)); + memcpy(grids->iq2xs, iq2xs_grid, sizeof(grids->iq2xs)); + memcpy(grids->iq2s, iq2s_grid, sizeof(grids->iq2s)); + memcpy(grids->iq3xxs, iq3xxs_grid, sizeof(grids->iq3xxs)); + memcpy(grids->iq3s, iq3s_grid, sizeof(grids->iq3s)); + + device->iq_grid_buf = ggml_vk_create_buffer_device(device, sizeof(vk_iq_grids)); + ggml_vk_buffer_write(device->iq_grid_buf, 0, grids.get(), sizeof(vk_iq_grids)); +} + static void ggml_vk_create_pipeline_func(vk_device& device, vk_pipeline& pipeline, size_t spv_size, const void* spv_data, const std::string entrypoint, uint32_t parameter_count, std::array wg_denoms, std::vector specialization_constants, bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) { @@ -877,7 +920,7 @@ void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) { pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE; if (pool_idx >= ctx->descriptor_pools.size()) { - vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, MAX_PARAMETER_COUNT * VK_DEVICE_DESCRIPTOR_POOL_SIZE); + vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, NUM_DESCRIPTOR_BINDINGS * VK_DEVICE_DESCRIPTOR_POOL_SIZE); vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size); ctx->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info)); } @@ -888,6 +931,15 @@ void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) { } vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(ctx->descriptor_pools[pool_idx], alloc_count, layouts.data()); std::vector sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info); + + // the IQ grid tables live at the same binding in every set; shaders that don't use them ignore it + const vk::DescriptorBufferInfo iq_grid_info{ device->iq_grid_buf->buffer, 0, VK_WHOLE_SIZE }; + std::vector iq_grid_writes; + for (const vk::DescriptorSet & set : sets) { + iq_grid_writes.push_back({ set, IQ_GRID_BINDING, 0, 1, vk::DescriptorType::eStorageBuffer, nullptr, &iq_grid_info }); + } + device->device.updateDescriptorSets(iq_grid_writes, {}); + ctx->descriptor_sets.insert(ctx->descriptor_sets.end(), sets.begin(), sets.end()); pool_idx++; @@ -5677,7 +5729,7 @@ vk_device ggml_vk_get_device(size_t idx) { std::vector dsl_binding; std::vector dsl_binding_flags; - for (uint32_t i = 0; i < MAX_PARAMETER_COUNT; i++) { + for (uint32_t i = 0; i < NUM_DESCRIPTOR_BINDINGS; i++) { dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute}); dsl_binding_flags.push_back({}); } @@ -5719,6 +5771,8 @@ vk_device ggml_vk_get_device(size_t idx) { device->fence = device->device.createFence({}); + ggml_vk_init_iq_grids(device); + device->buffer_type = { /* .iface = */ ggml_backend_vk_buffer_type_interface, /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx), @@ -18417,6 +18471,7 @@ vk_device_struct::~vk_device_struct() { device.destroyFence(fence); ggml_vk_destroy_buffer(sync_staging); + ggml_vk_destroy_buffer(iq_grid_buf); if (compute_queue) compute_queue->cmd_pool.destroy(device); if (transfer_queue) transfer_queue->cmd_pool.destroy(device); diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/types.glsl b/ggml/src/ggml-vulkan/vulkan-shaders/types.glsl index 39772acbaeb7..a5dd7fdc4730 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/types.glsl +++ b/ggml/src/ggml-vulkan/vulkan-shaders/types.glsl @@ -567,438 +567,60 @@ struct block_iq1_m_packed64 { #define A_TYPE_PACKED32 block_iq1_m_packed32 #endif +// IQ1/IQ2/IQ3 grid tables are read from a storage buffer and copied to shared memory by init_iq_shmem. +// The binding and offsets must match IQ_GRID_BINDING and vk_iq_grids in ggml-vulkan. +#define IQ_GRID_BINDING 12 +// Offsets are in bytes; divide by the element size when indexing. +#define IQ1S_GRID_OFFSET 0 +#define IQ1S_GRID_GPU_OFFSET 4096 +#define IQ2XXS_GRID_OFFSET 12288 +#define IQ2XS_GRID_OFFSET 14336 +#define IQ2S_GRID_OFFSET 18432 +#define IQ3XXS_GRID_OFFSET 26624 +#define IQ3S_GRID_OFFSET 27648 + #if defined(DATA_A_IQ1_S) || defined(DATA_A_IQ1_M) #define IQ1S_DELTA 0.125f #define IQ1M_DELTA 0.125f -// Packed IQ1S grid where every 2 vec8 are encoded on 32 bits (2 bits per coordinate). -const uint[1024] iq1s_grid_const = { - 0xfffdffff, 0xfff7fff0, 0xffccfff5, 0xffdfffc0, 0xffd7ffdd, 0xff30ffd5, 0xff03ff0c, 0xff10ff01, - 0xff7dff7f, 0xff75ff77, 0xff5fff40, 0xff57ff5d, 0xfcf3ff55, 0xfcccfcf0, 0xfcc1fcc3, 0xfcc5fcc4, - 0xfc3cfcd0, 0xfc34fc31, 0xfc00fc0d, 0xfc1cfc05, 0xfc11fc13, 0xfc70fc17, 0xfc43fc4c, 0xfc50fc41, - 0xfdfdfdff, 0xfdf5fdf7, 0xfddffdc0, 0xfdd7fddd, 0xfd30fdd5, 0xfd04fd0c, 0xfd14fd13, 0xfd7dfd7f, - 0xfd75fd77, 0xfd40fd4c, 0xfd5ffd44, 0xfd57fd5d, 0xf3ccfd55, 0xf3c1f3c3, 0xf33cf3d0, 0xf300f334, - 0xf313f305, 0xf34cf310, 0xf350f344, 0xf0f3f0fc, 0xf0f1f0f0, 0xf0c7f0c0, 0xf0d4f0c5, 0xf030f03f, - 0xf00ff035, 0xf003f00c, 0xf001f000, 0xf01ff004, 0xf010f01d, 0xf015f017, 0xf04cf07c, 0xf047f040, - 0xf05cf045, 0xf050f053, 0xf054f051, 0xf1c4f1c3, 0xf133f13c, 0xf10df10f, 0xf107f100, 0xf11cf11f, - 0xf114f111, 0xf14cf170, 0xf144f143, 0xf7fdf7ff, 0xf7f5f7f7, 0xf7dff7c0, 0xf7d7f7dd, 0xf730f7d5, - 0xf701f70c, 0xf77ff710, 0xf777f77d, 0xf740f775, 0xf75df75f, 0xf755f757, 0xf4ccf4f0, 0xf4c4f4c3, - 0xf4d0f4d3, 0xf40ff43c, 0xf400f40c, 0xf413f41c, 0xf44cf414, 0xf441f443, 0xf450f444, 0xf5fdf5ff, - 0xf5f5f5f7, 0xf5dff5c0, 0xf5d7f5dd, 0xf530f5d5, 0xf504f50c, 0xf510f51c, 0xf57df57f, 0xf577f570, - 0xf540f575, 0xf55df55f, 0xf555f557, 0xcfcccfcf, 0xcfc4cfc3, 0xcfd0cfd3, 0xcf33cf3c, 0xcf00cf0f, - 0xcf1ccf07, 0xcf10cf13, 0xcf4ccf14, 0xcf41cf43, 0xcf50cf5c, 0xccf3ccfc, 0xccf4ccf1, 0xcccdcccf, - 0xccc7ccc0, 0xccd3ccdc, 0xcc30ccd4, 0xcc0fcc35, 0xcc0dcc0c, 0xcc00cc03, 0xcc04cc01, 0xcc10cc1f, - 0xcc4dcc73, 0xcc5ccc40, 0xcdcccc53, 0xcdc1cdc3, 0xcd3fcdd0, 0xcd34cd31, 0xcd00cd0d, 0xcd05cd07, - 0xcd11cd13, 0xcd4ccd70, 0xcd41cd43, 0xc3fccd50, 0xc3f4c3f1, 0xc3c0c3c3, 0xc3c4c3c7, 0xc3d1c3dc, - 0xc330c33c, 0xc337c331, 0xc30cc335, 0xc300c303, 0xc304c301, 0xc310c31d, 0xc373c317, 0xc34fc374, - 0xc340c343, 0xc344c347, 0xc35cc345, 0xc350c353, 0xc0fdc354, 0xc0f5c0f0, 0xc0c3c0cc, 0xc0c1c0c0, - 0xc0dfc0c4, 0xc0d0c0dd, 0xc0d5c0d7, 0xc033c03c, 0xc031c030, 0xc00dc00c, 0xc000c003, 0xc004c001, - 0xc01cc005, 0xc010c013, 0xc014c011, 0xc07dc07f, 0xc070c073, 0xc075c077, 0xc04cc04f, 0xc040c043, - 0xc044c041, 0xc05fc045, 0xc050c05d, 0xc1f3c1fc, 0xc1f1c1f0, 0xc1c1c1c0, 0xc1c5c1c7, 0xc1d1c1dc, - 0xc13dc13f, 0xc130c133, 0xc135c137, 0xc100c10c, 0xc107c101, 0xc11cc104, 0xc110c113, 0xc114c117, - 0xc171c115, 0xc14dc175, 0xc153c140, 0xc7ccc154, 0xc7d0c7c1, 0xc733c73c, 0xc734c731, 0xc700c70f, - 0xc705c707, 0xc71cc71f, 0xc711c713, 0xc770c714, 0xc743c74c, 0xc4cfc750, 0xc4c0c4cd, 0xc4dcc4c5, - 0xc43dc4d0, 0xc430c433, 0xc40cc437, 0xc400c403, 0xc404c401, 0xc41fc405, 0xc415c410, 0xc44cc474, - 0xc440c44d, 0xc45cc447, 0xc454c451, 0xc5c1c5f4, 0xc5d1c5d3, 0xc531c533, 0xc50fc534, 0xc500c50d, - 0xc51cc507, 0xc514c511, 0xc54cc570, 0xc545c541, 0xdffddfff, 0xdff5dff7, 0xdfdfdfc0, 0xdfd0dfdd, - 0xdfd5dfd7, 0xdf0cdf30, 0xdf1cdf04, 0xdf7fdf10, 0xdf77df7d, 0xdf40df75, 0xdf5ddf5f, 0xdf57df50, - 0xdcf0df55, 0xdcc3dccc, 0xdcd0dcc4, 0xdc33dc3d, 0xdc00dc34, 0xdc05dc07, 0xdc13dc1c, 0xdc11dc10, - 0xdc4fdc70, 0xdc44dc41, 0xddfcdc50, 0xddf5ddf7, 0xddc0ddcc, 0xdddddddf, 0xddd5ddd7, 0xdd0cdd30, - 0xdd04dd01, 0xdd7cdd10, 0xdd75dd77, 0xdd40dd4c, 0xdd5ddd5f, 0xdd55dd57, 0xd3c3d3f0, 0xd3c4d3c1, - 0xd333d3d0, 0xd331d330, 0xd30dd334, 0xd307d300, 0xd311d305, 0xd34cd370, 0xd344d343, 0xd350d35c, - 0xd0c0d0f4, 0xd0d4d0dc, 0xd030d03f, 0xd00cd037, 0xd000d003, 0xd01dd004, 0xd017d010, 0xd04fd074, - 0xd040d043, 0xd045d047, 0xd053d05c, 0xd054d051, 0xd1cfd1f0, 0xd1c4d1cd, 0xd13cd1d0, 0xd100d134, - 0xd11cd11f, 0xd173d114, 0xd14fd171, 0xd7ffd145, 0xd7f7d7fd, 0xd7c0d7f5, 0xd7ddd7df, 0xd7d5d7d7, - 0xd70cd730, 0xd710d703, 0xd77dd77f, 0xd775d777, 0xd75dd75f, 0xd755d757, 0xd4ccd4f4, 0xd4c4d4c3, - 0xd431d4d0, 0xd40dd434, 0xd41cd400, 0xd411d413, 0xd470d414, 0xd441d44f, 0xd453d444, 0xd5ffd450, - 0xd5f7d5fd, 0xd5dfd5f5, 0xd5d7d5dd, 0xd530d5d5, 0xd501d50c, 0xd510d504, 0xd57dd57f, 0xd575d577, - 0xd55fd540, 0xd557d55d, 0x3ff0d555, 0x3fc13fcc, 0x3f343fd0, 0x3f003f0d, 0x3f053f07, 0x3f133f1c, - 0x3f433f11, 0x3f5c3f44, 0x3cff3f51, 0x3cf33cfc, 0x3cf43cf1, 0x3cc03ccd, 0x3cc73cc1, 0x3cdc3cc5, - 0x3cd43cd1, 0x3c373c30, 0x3c0c3c35, 0x3c003c03, 0x3c043c01, 0x3c103c05, 0x3c153c17, 0x3c733c7c, - 0x3c4f3c71, 0x3c403c4d, 0x3c5c3c5f, 0x3df03c5d, 0x3dc33dcc, 0x3dd03dc1, 0x3d0d3d3c, 0x3d053d00, - 0x3d143d13, 0x3d433d74, 0x33fc3d50, 0x33c433c0, 0x333033d4, 0x33353337, 0x3303330c, 0x33013300, - 0x331d331c, 0x33173310, 0x337c3315, 0x33743371, 0x334d334f, 0x335f3340, 0x3354335c, 0x30fd30fc, - 0x30f530f0, 0x30c330cc, 0x30c130c0, 0x30df30c4, 0x30d530d0, 0x3033303c, 0x30313030, 0x300f3034, - 0x3003300c, 0x30013000, 0x30043007, 0x3013301c, 0x30113010, 0x307d3014, 0x30703073, 0x304c3077, - 0x30403043, 0x30443041, 0x30503045, 0x30553057, 0x31f031fc, 0x31c331f4, 0x31c731c0, 0x31dc31c5, - 0x31d431d3, 0x313d313f, 0x31373130, 0x310c310f, 0x3100310d, 0x31043101, 0x3110311d, 0x317c3117, - 0x31753170, 0x31403143, 0x3153315c, 0x37f03151, 0x37c037cc, 0x37d037c5, 0x3734373d, 0x3700370f, - 0x371c3707, 0x37113713, 0x37703714, 0x3743374c, 0x37443741, 0x34fc3750, 0x34f134f0, 0x34cf34f5, - 0x34c034c3, 0x34dc34c7, 0x34d134d3, 0x3430343f, 0x340c3435, 0x3403340d, 0x34013400, 0x341f3404, - 0x3410341d, 0x34153411, 0x34743471, 0x3440344d, 0x34473441, 0x3453345c, 0x34543451, 0x353335c1, - 0x35343531, 0x35073500, 0x35133505, 0x35433514, 0x0ffc3550, 0x0ff00ff3, 0x0ff40ff1, 0x0fc00fcd, - 0x0fdc0fc5, 0x0fd40fd3, 0x0f300f3f, 0x0f0c0f37, 0x0f000f03, 0x0f040f01, 0x0f170f10, 0x0f740f71, - 0x0f470f40, 0x0f5c0f5f, 0x0f540f51, 0x0cf70cf0, 0x0cf50cf4, 0x0cc30ccc, 0x0cc10cc0, 0x0cc40cc7, - 0x0cd00cdf, 0x0cd70cd1, 0x0c3c0cd5, 0x0c300c33, 0x0c340c31, 0x0c0c0c0f, 0x0c030c0d, 0x0c010c00, - 0x0c040c07, 0x0c1c0c05, 0x0c100c13, 0x0c140c11, 0x0c700c7d, 0x0c430c4c, 0x0c410c40, 0x0c5f0c44, - 0x0c550c50, 0x0df10dfc, 0x0dc00dcd, 0x0ddc0dc5, 0x0d3d0dd3, 0x0d350d30, 0x0d030d0c, 0x0d010d00, - 0x0d1d0d04, 0x0d700d10, 0x0d4d0d4f, 0x0d440d40, 0x0d530d45, 0x03f003f3, 0x03c303cc, 0x03c103c0, - 0x03c403c7, 0x03d003dc, 0x03d503d7, 0x0333033c, 0x03310330, 0x03350334, 0x030c030f, 0x03000303, - 0x03070301, 0x03050304, 0x031d031c, 0x03100313, 0x03140311, 0x0377037f, 0x034c0375, 0x03400343, - 0x03440341, 0x0353035c, 0x03550350, 0x00fd00fc, 0x00f000f3, 0x00f400f1, 0x00cc00cf, 0x00c300cd, - 0x00c100c0, 0x00c500c4, 0x00d300dc, 0x00d100d0, 0x003f00d4, 0x003d003c, 0x00300033, 0x00370031, - 0x000f0034, 0x000d000c, 0x00000003, 0x00070001, 0x00050004, 0x001c001f, 0x00100013, 0x00170011, - 0x00150014, 0x0073007c, 0x00740070, 0x004f0075, 0x0043004c, 0x00410040, 0x00440047, 0x0053005c, - 0x00510050, 0x01ff0054, 0x01fd01fc, 0x01f101f3, 0x01f401f7, 0x01c301cc, 0x01c701c0, 0x01df01c4, - 0x01dd01dc, 0x01d001d3, 0x01d701d1, 0x013c01d4, 0x01310130, 0x01340137, 0x010f0135, 0x010d010c, - 0x01000103, 0x01070101, 0x01050104, 0x0113011c, 0x01140110, 0x0170017d, 0x01770171, 0x01750174, - 0x0140014c, 0x015d0145, 0x01510150, 0x01540157, 0x07f007f3, 0x07f407f1, 0x07c007cf, 0x07dc07c7, - 0x073007d5, 0x07350737, 0x0703070c, 0x07010700, 0x07040707, 0x071d071f, 0x07100713, 0x0774077d, - 0x074d074f, 0x07470740, 0x0754075c, 0x04fd04fc, 0x04f504f0, 0x04c304cc, 0x04c104c0, 0x04d004c4, - 0x0433043c, 0x04310430, 0x040f0434, 0x040d040c, 0x04000403, 0x04070401, 0x04050404, 0x0413041c, - 0x04110410, 0x047c0414, 0x04740470, 0x0443044c, 0x04410440, 0x04440447, 0x05f30450, 0x05c005f7, - 0x05df05c5, 0x05d105d0, 0x053005d4, 0x05340537, 0x0500050c, 0x05070501, 0x051d0504, 0x05170510, - 0x057c0515, 0x054d0575, 0x05410540, 0x05450547, 0x1ff0055c, 0x1fc11fc3, 0x1fd01fc4, 0x1f0f1f33, - 0x1f011f00, 0x1f051f07, 0x1f131f1c, 0x1f141f11, 0x1f411f7c, 0x1cfc1f50, 0x1cf11cf3, 0x1ccd1cf4, - 0x1cdc1cc0, 0x1cd11cdd, 0x1c301cd4, 0x1c0c1c34, 0x1c011c00, 0x1c101c04, 0x1c151c11, 0x1c751c73, - 0x1c401c4d, 0x1c511c5c, 0x1dcc1c54, 0x1dc41dc1, 0x1d3c1d3f, 0x1d001d31, 0x1d071d01, 0x1d701d1f, - 0x1d411d4c, 0x13cc1d50, 0x13c013cd, 0x13c513c1, 0x13d113dc, 0x133f13d4, 0x1330133d, 0x13351337, - 0x1303130c, 0x13011300, 0x13051304, 0x131d131f, 0x13731310, 0x13741370, 0x134d134f, 0x13401343, - 0x13471341, 0x135c1345, 0x13541353, 0x10f710f0, 0x10cc10f5, 0x10c110c0, 0x103310c4, 0x10311030, - 0x100f1034, 0x1003100c, 0x10011000, 0x101c1004, 0x10101013, 0x10141011, 0x10741071, 0x104c1075, - 0x10411040, 0x10451044, 0x1050105d, 0x10571051, 0x11f411fd, 0x11df11c0, 0x11d711d1, 0x113f11d4, - 0x11371130, 0x110c1135, 0x11001103, 0x11071101, 0x111f1105, 0x11171110, 0x117d117f, 0x11751170, - 0x11411143, 0x11441147, 0x1153115f, 0x11551151, 0x17c417c1, 0x173c17d0, 0x1700170d, 0x171c1705, - 0x17701714, 0x1747174c, 0x14fc1751, 0x14cf14f3, 0x14dc14c0, 0x14d114d3, 0x143f14d4, 0x1430143c, - 0x14371431, 0x1403140c, 0x14011400, 0x141f1404, 0x14151410, 0x1473147d, 0x14401475, 0x1453145c, - 0x14541450, 0x15c115cc, 0x153c15c7, 0x15341533, 0x1500150f, 0x15051507, 0x15101513, 0x15711514, - 0x15471543, 0x15511545, 0x7ffd7fff, 0x7ff57ff7, 0x7fdd7fdf, 0x7fd57fd7, 0x7f0f7f30, 0x7f037f0c, - 0x7f047f01, 0x7f7f7f10, 0x7f777f7d, 0x7f407f75, 0x7f5d7f5f, 0x7f557f57, 0x7ccc7cf0, 0x7cc17cc3, - 0x7cd07cc4, 0x7c337c3c, 0x7c0f7c34, 0x7c007c0d, 0x7c077c01, 0x7c137c04, 0x7c147c11, 0x7c747c70, - 0x7c417c43, 0x7c507c44, 0x7dfd7dff, 0x7df57df7, 0x7ddf7dc0, 0x7dd77ddd, 0x7d0c7dd5, 0x7d047d03, - 0x7d7f7d10, 0x7d777d7d, 0x7d407d75, 0x7d5d7d5f, 0x7d557d57, 0x73c473c3, 0x7333733c, 0x7300730c, - 0x731c7305, 0x73147313, 0x73447343, 0x70f470fc, 0x70c070cd, 0x70d170c5, 0x703f70d4, 0x7030703c, - 0x700c7037, 0x70007003, 0x70047001, 0x70107005, 0x70177011, 0x707c7015, 0x70717073, 0x704f7074, - 0x7040704d, 0x70517047, 0x71c171cc, 0x71d071c4, 0x7133713c, 0x71357134, 0x7100710f, 0x71057104, - 0x7111711c, 0x71707115, 0x7145714c, 0x77ff7153, 0x77f777fd, 0x77c077f5, 0x77dd77df, 0x77d577d7, - 0x7730773c, 0x7703770c, 0x77107704, 0x777f7714, 0x7777777d, 0x77407775, 0x775d775f, 0x77557757, - 0x74f174f0, 0x74c374cc, 0x74d074c1, 0x7433743c, 0x74347431, 0x740d740f, 0x74057400, 0x7413741c, - 0x74417470, 0x74507444, 0x75fd75ff, 0x75f575f7, 0x75df75c0, 0x75d775dd, 0x753075d5, 0x7503750c, - 0x757f7501, 0x7577757d, 0x75407575, 0x755d755f, 0x75557557, 0x4fcc4ff0, 0x4fc74fc1, 0x4fd04fc4, - 0x4f314f3c, 0x4f004f34, 0x4f054f07, 0x4f154f14, 0x4f4c4f70, 0x4f414f43, 0x4f504f44, 0x4cf34cfc, - 0x4cf44cf1, 0x4cc04ccf, 0x4cc54cc7, 0x4cd34cdc, 0x4cd44cd1, 0x4c304c3f, 0x4c0c4c0f, 0x4c004c03, - 0x4c044c01, 0x4c104c1d, 0x4c714c73, 0x4c404c4d, 0x4c5c4c47, 0x4c514c53, 0x4df04c54, 0x4dc34dcc, - 0x4dd04dc4, 0x4d314d33, 0x4d0f4d34, 0x4d004d0d, 0x4d114d07, 0x4d704d14, 0x4d414d43, 0x43fc4d54, - 0x43f143f3, 0x43c043cf, 0x43d143c7, 0x4335433f, 0x4303430c, 0x43014300, 0x43044307, 0x431c431f, - 0x4310431d, 0x43714373, 0x4343434d, 0x43474340, 0x4354435c, 0x40f040ff, 0x40f540f7, 0x40cc40cf, - 0x40c040c3, 0x40c440c1, 0x40d040dc, 0x40d540d4, 0x4033403c, 0x40314030, 0x400f4034, 0x400d400c, - 0x40004003, 0x40074001, 0x40054004, 0x4013401c, 0x40114010, 0x407c4014, 0x40774070, 0x404d404c, - 0x40404043, 0x40444041, 0x405f4045, 0x4050405d, 0x40554057, 0x41f341fc, 0x41c041cf, 0x41df41c4, - 0x41d441d1, 0x41374130, 0x410c4134, 0x4100410d, 0x41044101, 0x41174110, 0x4173417d, 0x41754174, - 0x4143414d, 0x41534140, 0x41544151, 0x47c147f0, 0x47d047c4, 0x4731473c, 0x470d470f, 0x47014700, - 0x47134705, 0x47704710, 0x4741474c, 0x47504744, 0x44f144f3, 0x44cf44f4, 0x44c044cd, 0x44c544c7, - 0x44dc44df, 0x44d144d3, 0x443d443f, 0x44374430, 0x440c4435, 0x44004403, 0x44044401, 0x4410441d, - 0x44154411, 0x4473447c, 0x444d444f, 0x44454440, 0x4451445c, 0x45c045f0, 0x453345d0, 0x45344531, - 0x4500450f, 0x451c4507, 0x454c4570, 0x45404543, 0x5fff4541, 0x5ff75ffd, 0x5fc05ff5, 0x5fdd5fdf, - 0x5fd55fd7, 0x5f0c5f30, 0x5f015f03, 0x5f7f5f04, 0x5f775f7d, 0x5f405f75, 0x5f5d5f5f, 0x5f555f57, - 0x5cf45cf0, 0x5cc35ccc, 0x5cc45cc1, 0x5c315cc5, 0x5c0c5c34, 0x5c075c00, 0x5c1c5c05, 0x5c705c13, - 0x5c4d5c4f, 0x5c445c41, 0x5df75dfd, 0x5dcf5df5, 0x5ddd5dc4, 0x5dd55dd7, 0x5d0c5d30, 0x5d045d01, - 0x5d7f5d10, 0x5d775d7d, 0x5d405d75, 0x5d5d5d5f, 0x5d555d57, 0x53d053c4, 0x5333533c, 0x5303530f, - 0x53075300, 0x531c5305, 0x53115310, 0x53145317, 0x50f15370, 0x50cf50f4, 0x50c050cd, 0x50d150c7, - 0x503d50d4, 0x500c5030, 0x50005003, 0x50045001, 0x50155010, 0x5073507c, 0x50715070, 0x504d5074, - 0x50475040, 0x51cc51f0, 0x51c551c1, 0x51d051dc, 0x51315133, 0x510d5135, 0x51015100, 0x511f5107, - 0x5171511d, 0x5140514f, 0x51445141, 0x5153515c, 0x57ff5151, 0x57f757fd, 0x57df57f5, 0x57d757dd, - 0x570c57d5, 0x57015703, 0x577f5704, 0x5777577d, 0x57405775, 0x575d575f, 0x57555757, 0x54c354f0, - 0x54dc54c4, 0x543c54d0, 0x5400540f, 0x541c5405, 0x54145411, 0x5441544f, 0x55fd55ff, 0x55f555f7, - 0x55dd55df, 0x55d555d7, 0x5503550c, 0x557f5501, 0x5577557d, 0x55405575, 0x555d555f, 0x55555557 -}; +layout (binding = IQ_GRID_BINDING) readonly buffer IQGrid { uint32_t iq_grid[]; }; -#if defined(NEEDS_IQ1S_GRID_GPU) -// Same content as iq1s_grid_const except each 2-bit value is expanded to 4-bit -// and has 1 added to it (allows packed values to be extracted with & 0x0F0F0F0F -// and 0xF0F0F0F0). This is only used by the q8_1/int-dot vector path. -const uint32_t[2048] iq1s_grid_gpu_const = { - 0x00000000, 0x00000002, 0x00000101, 0x00000200, 0x00000202, 0x00010001, 0x00010101, 0x00020000, - 0x00020002, 0x00020200, 0x00020202, 0x01000101, 0x01010001, 0x01010100, 0x01010102, 0x01020101, - 0x02000000, 0x02000002, 0x02000200, 0x02000202, 0x02010101, 0x02020000, 0x02020002, 0x02020200, - 0x02020202, 0x00000110, 0x00000111, 0x00010011, 0x00010110, 0x00010112, 0x00010211, 0x00010212, - 0x00020111, 0x01000011, 0x01000112, 0x01000211, 0x01010012, 0x01010111, 0x01010212, 0x01020011, - 0x01020110, 0x01020112, 0x01020210, 0x02000111, 0x02010011, 0x02010110, 0x02010112, 0x02020111, - 0x00000020, 0x00000022, 0x00000220, 0x00000222, 0x00010121, 0x00020020, 0x00020022, 0x00020220, - 0x00020222, 0x01000121, 0x01010021, 0x01010221, 0x01020120, 0x01020221, 0x02000020, 0x02000022, - 0x02000220, 0x02000222, 0x02010021, 0x02010121, 0x02010221, 0x02020020, 0x02020022, 0x02020220, - 0x02020222, 0x00011001, 0x00011100, 0x00011102, 0x00021101, 0x01001001, 0x01001201, 0x01011101, - 0x01011202, 0x01021100, 0x01021101, 0x02011001, 0x02011201, 0x02021101, 0x00001011, 0x00001110, - 0x00001111, 0x00001112, 0x00011111, 0x00011210, 0x00011212, 0x00021211, 0x01001010, 0x01001111, - 0x01001212, 0x01011010, 0x01011011, 0x01011110, 0x01011111, 0x01011112, 0x01011211, 0x01021010, - 0x01021012, 0x01021111, 0x01021210, 0x01021212, 0x02001011, 0x02011011, 0x02011111, 0x02011210, - 0x02011212, 0x02021011, 0x02021110, 0x02021111, 0x02021112, 0x02021211, 0x00011120, 0x00011221, - 0x01001021, 0x01001120, 0x01011020, 0x01011022, 0x01011121, 0x01011220, 0x01021020, 0x01021021, - 0x01021122, 0x01021221, 0x02001121, 0x02011021, 0x02011120, 0x02011221, 0x00002000, 0x00002002, - 0x00002200, 0x00002202, 0x00012101, 0x00022000, 0x00022002, 0x00022200, 0x00022202, 0x01002101, - 0x01012001, 0x01012102, 0x01022101, 0x02002000, 0x02002002, 0x02002200, 0x02002202, 0x02012101, - 0x02022000, 0x02022002, 0x02022200, 0x02022202, 0x00002111, 0x00012011, 0x00012110, 0x00012211, - 0x00022110, 0x00022111, 0x01002011, 0x01012010, 0x01012011, 0x01012111, 0x01022011, 0x01022110, - 0x01022211, 0x02012011, 0x02012110, 0x02012112, 0x02012211, 0x02022111, 0x00002020, 0x00002022, - 0x00002220, 0x00002222, 0x00012121, 0x00022020, 0x00022022, 0x00022220, 0x00022222, 0x01002121, - 0x01012021, 0x01012221, 0x01022021, 0x01022121, 0x02002020, 0x02002022, 0x02002121, 0x02002220, - 0x02002222, 0x02012121, 0x02022020, 0x02022022, 0x02022220, 0x02022222, 0x00110000, 0x00110001, - 0x00110100, 0x00110201, 0x00120100, 0x00120101, 0x01100001, 0x01100100, 0x01110000, 0x01110101, - 0x01110200, 0x01120001, 0x01120100, 0x01120101, 0x01120201, 0x02110001, 0x02110100, 0x02110102, - 0x02120001, 0x02120101, 0x00100011, 0x00100110, 0x00100112, 0x00100211, 0x00110010, 0x00110012, - 0x00110111, 0x00110210, 0x00120011, 0x00120110, 0x00120211, 0x01100111, 0x01100212, 0x01110010, - 0x01110011, 0x01110012, 0x01110110, 0x01110111, 0x01110112, 0x01110211, 0x01120010, 0x01120111, - 0x02100110, 0x02110012, 0x02110111, 0x02120011, 0x02120110, 0x00110021, 0x00110120, 0x00110122, - 0x00120121, 0x01100020, 0x01100122, 0x01100221, 0x01110022, 0x01110121, 0x01110220, 0x01110222, - 0x01120120, 0x01120122, 0x02100121, 0x02110021, 0x02110120, 0x02110122, 0x02120121, 0x00101001, - 0x00101102, 0x00101201, 0x00111100, 0x00111101, 0x00111200, 0x00111201, 0x00121001, 0x00121102, - 0x01101001, 0x01101101, 0x01101102, 0x01101200, 0x01101202, 0x01111001, 0x01111100, 0x01111101, - 0x01111102, 0x01111201, 0x01121002, 0x01121101, 0x01121200, 0x02101100, 0x02101201, 0x02111000, - 0x02111100, 0x02111101, 0x02111200, 0x02111201, 0x02111202, 0x02121001, 0x02121100, 0x02121101, - 0x02121201, 0x00101012, 0x00101111, 0x00101212, 0x00111011, 0x00111110, 0x00111111, 0x00111112, - 0x00111211, 0x00121010, 0x00121012, 0x00121111, 0x00121210, 0x00121212, 0x01101011, 0x01101110, - 0x01101111, 0x01101112, 0x01111011, 0x01111012, 0x01111110, 0x01111111, 0x01111112, 0x01111211, - 0x01111212, 0x01121011, 0x01121110, 0x01121111, 0x01121112, 0x01121211, 0x02101010, 0x02101012, - 0x02101110, 0x02101111, 0x02101210, 0x02101212, 0x02111010, 0x02111011, 0x02111110, 0x02111111, - 0x02111112, 0x02111211, 0x02111212, 0x02121010, 0x02121012, 0x02121111, 0x00101021, 0x00101120, - 0x00101121, 0x00101122, 0x00111121, 0x00111122, 0x00111220, 0x00111222, 0x00121021, 0x00121122, - 0x01101020, 0x01101022, 0x01101120, 0x01101121, 0x01101220, 0x01101222, 0x01111021, 0x01111121, - 0x01111122, 0x01111220, 0x01111221, 0x01121021, 0x01121120, 0x01121121, 0x01121220, 0x01121221, - 0x01121222, 0x02101122, 0x02101222, 0x02111022, 0x02111121, 0x02121120, 0x02121221, 0x00112001, - 0x00112102, 0x00122101, 0x01102001, 0x01102100, 0x01102102, 0x01102201, 0x01112000, 0x01112101, - 0x01112200, 0x01112202, 0x01122000, 0x01122001, 0x01122100, 0x01122102, 0x01122201, 0x02102101, - 0x02112001, 0x02112100, 0x02122101, 0x00112010, 0x00112012, 0x00112111, 0x00112212, 0x00122011, - 0x00122111, 0x01102012, 0x01102110, 0x01102111, 0x01102210, 0x01112011, 0x01112110, 0x01112111, - 0x01112112, 0x01112211, 0x01112212, 0x01122010, 0x01122111, 0x01122212, 0x02102211, 0x02112011, - 0x02112012, 0x02112111, 0x02112210, 0x02122011, 0x02122112, 0x02122211, 0x00102221, 0x00112122, - 0x00122120, 0x00122122, 0x01102120, 0x01102122, 0x01102221, 0x01112020, 0x01112022, 0x01112121, - 0x01112220, 0x01122021, 0x01122122, 0x01122221, 0x02102121, 0x02112021, 0x02112122, 0x02112222, - 0x00200000, 0x00200002, 0x00200200, 0x00200202, 0x00210101, 0x00220000, 0x00220002, 0x00220101, - 0x00220200, 0x00220202, 0x01200101, 0x01210001, 0x01210201, 0x01220001, 0x01220101, 0x02200000, - 0x02200002, 0x02200200, 0x02200202, 0x02210101, 0x02220000, 0x02220002, 0x02220101, 0x02220200, - 0x02220202, 0x00200111, 0x00210011, 0x00210110, 0x00210211, 0x00220111, 0x01200012, 0x01200110, - 0x01200211, 0x01210111, 0x01210210, 0x01210212, 0x01220011, 0x01220110, 0x01220111, 0x01220112, - 0x02200111, 0x02210010, 0x02210112, 0x02210211, 0x02220111, 0x00200021, 0x00200220, 0x00200222, - 0x00210021, 0x00210121, 0x00220020, 0x00220022, 0x00220220, 0x00220222, 0x01200121, 0x01210021, - 0x01210122, 0x01210221, 0x01220121, 0x02200021, 0x02200220, 0x02200222, 0x02210021, 0x02210121, - 0x02220020, 0x02220022, 0x02220220, 0x02220222, 0x00201101, 0x00211100, 0x00211102, 0x00211201, - 0x00221101, 0x01201100, 0x01201101, 0x01201102, 0x01201201, 0x01211002, 0x01211101, 0x01211200, - 0x01211202, 0x01221102, 0x02201101, 0x02211001, 0x02211100, 0x02211201, 0x02221001, 0x02221101, - 0x00201211, 0x00211111, 0x00221011, 0x00221211, 0x01201010, 0x01201111, 0x01201210, 0x01211011, - 0x01211110, 0x01211111, 0x01211211, 0x01221012, 0x01221111, 0x01221210, 0x02201211, 0x02211010, - 0x02211110, 0x02211111, 0x02211210, 0x02211212, 0x02221011, 0x02221110, 0x02221112, 0x02221211, - 0x00201121, 0x00211020, 0x00211022, 0x00211221, 0x00221121, 0x01201021, 0x01201221, 0x01211121, - 0x01221020, 0x01221021, 0x01221221, 0x02201120, 0x02201122, 0x02211020, 0x02211222, 0x00202000, - 0x00202002, 0x00202200, 0x00202202, 0x00212101, 0x00222000, 0x00222002, 0x00222200, 0x00222202, - 0x01202101, 0x01212001, 0x01212100, 0x01222101, 0x02202000, 0x02202002, 0x02202200, 0x02202202, - 0x02222000, 0x02222002, 0x02222200, 0x02222202, 0x00202211, 0x00212011, 0x00212110, 0x00212211, - 0x00222111, 0x01202112, 0x01202211, 0x01212012, 0x01212111, 0x01222011, 0x01222110, 0x01222112, - 0x01222211, 0x02202111, 0x02212010, 0x02212112, 0x02212211, 0x02222110, 0x02222111, 0x00202020, - 0x00202022, 0x00202220, 0x00202222, 0x00222020, 0x00222022, 0x00222220, 0x00222222, 0x01202121, - 0x01212021, 0x01212122, 0x01212221, 0x01222121, 0x02202020, 0x02202022, 0x02202220, 0x02202222, - 0x02212121, 0x02222020, 0x02222022, 0x02222220, 0x02222222, 0x10000101, 0x10010001, 0x10010102, - 0x10020101, 0x11000201, 0x11010002, 0x11010101, 0x11010200, 0x11010202, 0x11020001, 0x11020100, - 0x11020102, 0x12010100, 0x12010201, 0x12020001, 0x12020102, 0x10000010, 0x10000011, 0x10000110, - 0x10000112, 0x10000211, 0x10010012, 0x10010111, 0x10010112, 0x10010210, 0x10010212, 0x10020011, - 0x10020112, 0x10020211, 0x11000111, 0x11000210, 0x11000212, 0x11010011, 0x11010110, 0x11010111, - 0x11010112, 0x11010211, 0x11010212, 0x11020111, 0x11020210, 0x11020212, 0x12000011, 0x12000110, - 0x12000112, 0x12010010, 0x12010012, 0x12010111, 0x12020010, 0x12020011, 0x12020012, 0x10000121, - 0x10010021, 0x10010120, 0x10010122, 0x10020121, 0x11000021, 0x11010022, 0x11010121, 0x11010222, - 0x11020120, 0x11020221, 0x12000221, 0x12010120, 0x12020121, 0x10001001, 0x10011101, 0x10011201, - 0x10021201, 0x11001101, 0x11001200, 0x11001202, 0x11011001, 0x11011100, 0x11011101, 0x11011102, - 0x11021001, 0x11021002, 0x11021101, 0x11021200, 0x11021202, 0x12001001, 0x12001102, 0x12001201, - 0x12011000, 0x12011002, 0x12011101, 0x12021000, 0x12021001, 0x12021201, 0x10001011, 0x10001012, - 0x10001111, 0x10001212, 0x10011011, 0x10011110, 0x10011111, 0x10011112, 0x10011211, 0x10021010, - 0x10021111, 0x10021212, 0x11001011, 0x11001110, 0x11001111, 0x11001112, 0x11001211, 0x11011010, - 0x11011011, 0x11011110, 0x11011111, 0x11011112, 0x11011210, 0x11011211, 0x11021011, 0x11021110, - 0x11021111, 0x11021112, 0x11021211, 0x12001012, 0x12001110, 0x12001111, 0x12001210, 0x12011011, - 0x12011110, 0x12011111, 0x12011112, 0x12011211, 0x12011212, 0x12021111, 0x12021210, 0x12021212, - 0x10001021, 0x10001121, 0x10001221, 0x10011120, 0x10011121, 0x10011220, 0x10011222, 0x10021021, - 0x10021120, 0x10021221, 0x11001020, 0x11001022, 0x11001121, 0x11001220, 0x11011020, 0x11011021, - 0x11011022, 0x11011121, 0x11011122, 0x11011221, 0x11021022, 0x11021121, 0x11021220, 0x12001021, - 0x12001121, 0x12001222, 0x12011120, 0x12011121, 0x12021021, 0x12021120, 0x12021122, 0x10002101, - 0x10012001, 0x10012101, 0x10012202, 0x10022101, 0x11002002, 0x11002201, 0x11012000, 0x11012101, - 0x11012200, 0x11022001, 0x11022100, 0x11022102, 0x11022201, 0x12002101, 0x12012001, 0x12012100, - 0x12012102, 0x12012201, 0x12022101, 0x10002011, 0x10002111, 0x10002112, 0x10002212, 0x10012010, - 0x10012110, 0x10012111, 0x10012210, 0x10022011, 0x10022110, 0x10022112, 0x11002010, 0x11002111, - 0x11002212, 0x11012011, 0x11012012, 0x11012110, 0x11012111, 0x11012112, 0x11012211, 0x11022010, - 0x11022012, 0x11022111, 0x11022112, 0x11022212, 0x12002112, 0x12002211, 0x12012012, 0x12012111, - 0x12012112, 0x12012210, 0x12022011, 0x12022110, 0x12022112, 0x12022211, 0x10012122, 0x11002120, - 0x11002122, 0x11002221, 0x11012121, 0x11012220, 0x11012222, 0x11022120, 0x11022221, 0x12012120, - 0x12022121, 0x10100001, 0x10100100, 0x10100101, 0x10100102, 0x10100201, 0x10110002, 0x10110101, - 0x10110202, 0x10120001, 0x10120100, 0x10120201, 0x11100000, 0x11100101, 0x11100200, 0x11110001, - 0x11110100, 0x11110101, 0x11110102, 0x11110201, 0x11120101, 0x11120200, 0x12100102, 0x12100201, - 0x12110101, 0x12110200, 0x12120000, 0x12120001, 0x12120102, 0x12120201, 0x10100111, 0x10100210, - 0x10100211, 0x10100212, 0x10110011, 0x10110110, 0x10110111, 0x10110112, 0x10110210, 0x10110211, - 0x10120010, 0x10120111, 0x10120112, 0x10120210, 0x10120212, 0x11100011, 0x11100110, 0x11100111, - 0x11100112, 0x11100211, 0x11110010, 0x11110011, 0x11110012, 0x11110110, 0x11110111, 0x11110112, - 0x11110210, 0x11110211, 0x11110212, 0x11120011, 0x11120110, 0x11120111, 0x11120112, 0x11120211, - 0x12100012, 0x12100111, 0x12110011, 0x12110110, 0x12110111, 0x12110112, 0x12110211, 0x12120010, - 0x12120111, 0x12120212, 0x10100021, 0x10100122, 0x10110022, 0x10110121, 0x10110222, 0x10120021, - 0x10120120, 0x11100022, 0x11100121, 0x11100222, 0x11110021, 0x11110120, 0x11110121, 0x11110122, - 0x11110221, 0x11120022, 0x11120121, 0x12100121, 0x12110020, 0x12110022, 0x12110121, 0x12110221, - 0x12110222, 0x12120120, 0x10101100, 0x10101101, 0x10111001, 0x10111100, 0x10111101, 0x10111102, - 0x10111200, 0x10111201, 0x10121001, 0x10121101, 0x10121200, 0x10121202, 0x11101001, 0x11101100, - 0x11101101, 0x11101102, 0x11101201, 0x11101202, 0x11111000, 0x11111001, 0x11111100, 0x11111101, - 0x11111102, 0x11111200, 0x11111201, 0x11111202, 0x11121001, 0x11121002, 0x11121100, 0x11121101, - 0x11121102, 0x11121201, 0x12101000, 0x12101200, 0x12101202, 0x12111001, 0x12111100, 0x12111101, - 0x12111102, 0x12111201, 0x12121001, 0x12121100, 0x12121101, 0x12121202, 0x10101011, 0x10101012, - 0x10101110, 0x10101111, 0x10101112, 0x10101211, 0x10111010, 0x10111011, 0x10111012, 0x10111110, - 0x10111111, 0x10111112, 0x10111211, 0x10111212, 0x10121011, 0x10121110, 0x10121111, 0x10121112, - 0x10121211, 0x11101010, 0x11101011, 0x11101012, 0x11101110, 0x11101111, 0x11101112, 0x11101210, - 0x11101211, 0x11111010, 0x11111011, 0x11111012, 0x11111110, 0x11111111, 0x11111112, 0x11111210, - 0x11111211, 0x11111212, 0x11121010, 0x11121011, 0x11121110, 0x11121111, 0x11121112, 0x11121210, - 0x11121211, 0x11121212, 0x12101011, 0x12101110, 0x12101111, 0x12101211, 0x12101212, 0x12111010, - 0x12111011, 0x12111110, 0x12111111, 0x12111112, 0x12111210, 0x12111211, 0x12121011, 0x12121110, - 0x12121111, 0x12121112, 0x12121211, 0x10101020, 0x10101021, 0x10101022, 0x10101120, 0x10101122, - 0x10101220, 0x10101221, 0x10111021, 0x10111120, 0x10111121, 0x10111220, 0x10111221, 0x10121020, - 0x10121021, 0x10121022, 0x10121120, 0x10121121, 0x10121122, 0x10121220, 0x10121221, 0x11101021, - 0x11101121, 0x11101122, 0x11101220, 0x11101221, 0x11101222, 0x11111020, 0x11111021, 0x11111022, - 0x11111120, 0x11111121, 0x11111122, 0x11111220, 0x11111221, 0x11111222, 0x11121021, 0x11121120, - 0x11121121, 0x11121221, 0x12101022, 0x12101121, 0x12101122, 0x12101220, 0x12101221, 0x12101222, - 0x12111021, 0x12111121, 0x12111222, 0x12121022, 0x12121121, 0x12121122, 0x12121220, 0x12121221, - 0x10102100, 0x10102101, 0x10102102, 0x10102201, 0x10112000, 0x10112101, 0x10112200, 0x10122001, - 0x10122202, 0x11102101, 0x11102200, 0x11102202, 0x11112001, 0x11112100, 0x11112101, 0x11112102, - 0x11112200, 0x11112201, 0x11122000, 0x11122002, 0x11122100, 0x11122101, 0x12102002, 0x12102201, - 0x12112000, 0x12112002, 0x12112101, 0x12112200, 0x12122001, 0x12122201, 0x10102011, 0x10102012, - 0x10102111, 0x10102212, 0x10112011, 0x10112110, 0x10112111, 0x10112112, 0x10112211, 0x10122111, - 0x11102011, 0x11102110, 0x11102111, 0x11102112, 0x11102211, 0x11112010, 0x11112011, 0x11112012, - 0x11112110, 0x11112111, 0x11112112, 0x11112210, 0x11112211, 0x11112212, 0x11122011, 0x11122110, - 0x11122111, 0x11122112, 0x11122211, 0x12102011, 0x12102111, 0x12102211, 0x12112011, 0x12112110, - 0x12112111, 0x12112112, 0x12112210, 0x12112211, 0x12122111, 0x10102120, 0x10102220, 0x10112121, - 0x10112222, 0x10122020, 0x10122121, 0x10122122, 0x10122221, 0x11102121, 0x11102220, 0x11102221, - 0x11112021, 0x11112121, 0x11112122, 0x11112220, 0x11112221, 0x11122022, 0x11122121, 0x11122220, - 0x11122222, 0x12102021, 0x12102222, 0x12112022, 0x12112121, 0x12112122, 0x12112220, 0x12112222, - 0x12122021, 0x10200101, 0x10210100, 0x10210102, 0x10210201, 0x10220101, 0x11200100, 0x11210000, - 0x11210101, 0x11210102, 0x11210200, 0x11210202, 0x11220001, 0x11220100, 0x11220102, 0x11220201, - 0x12200001, 0x12210102, 0x12220101, 0x10200011, 0x10200110, 0x10200112, 0x10200211, 0x10210012, - 0x10210111, 0x10220011, 0x10220012, 0x10220112, 0x10220211, 0x11200111, 0x11200211, 0x11210011, - 0x11210111, 0x11210112, 0x11210211, 0x11220111, 0x11220112, 0x11220212, 0x12200110, 0x12200212, - 0x12210012, 0x12210111, 0x12220011, 0x12220112, 0x12220211, 0x10210021, 0x10210122, 0x10210221, - 0x11200020, 0x11200021, 0x11200122, 0x11210121, 0x11210122, 0x11210220, 0x11220020, 0x12200121, - 0x12210021, 0x12210122, 0x12220121, 0x10211001, 0x10211002, 0x10211101, 0x10211102, 0x10211202, - 0x10221001, 0x10221102, 0x10221201, 0x11201000, 0x11201002, 0x11201101, 0x11201200, 0x11201202, - 0x11211001, 0x11211100, 0x11211101, 0x11211102, 0x11211201, 0x11211202, 0x11221000, 0x11221002, - 0x11221101, 0x12201100, 0x12201101, 0x12201201, 0x12211000, 0x12211002, 0x12211100, 0x12211101, - 0x12211102, 0x12211200, 0x12211202, 0x12221001, 0x12221100, 0x12221201, 0x10201111, 0x10201210, - 0x10201212, 0x10211011, 0x10211111, 0x10211112, 0x10211211, 0x11201110, 0x11201111, 0x11201112, - 0x11201211, 0x11211010, 0x11211011, 0x11211110, 0x11211111, 0x11211112, 0x11211211, 0x11221011, - 0x11221110, 0x11221111, 0x11221112, 0x11221211, 0x12201112, 0x12201211, 0x12201212, 0x12211011, - 0x12211111, 0x12211112, 0x12211211, 0x12211212, 0x12221012, 0x12221111, 0x12221112, 0x12221210, - 0x10201022, 0x10201221, 0x10211121, 0x10221020, 0x10221122, 0x10221220, 0x10221221, 0x11201020, - 0x11201121, 0x11201220, 0x11201222, 0x11211021, 0x11211120, 0x11211121, 0x11211122, 0x11211220, - 0x11211222, 0x11221020, 0x11221121, 0x11221220, 0x12201020, 0x12201022, 0x12201121, 0x12201222, - 0x12211120, 0x12211122, 0x12211220, 0x12211221, 0x12221020, 0x12221120, 0x12221122, 0x12221222, - 0x10212102, 0x10212201, 0x10222101, 0x11202001, 0x11212002, 0x11212101, 0x11212202, 0x11222001, - 0x11222201, 0x12202101, 0x12212001, 0x12212200, 0x12222102, 0x10202011, 0x10202110, 0x10212010, - 0x10212111, 0x10222011, 0x10222110, 0x10222112, 0x10222211, 0x11202010, 0x11202011, 0x11202111, - 0x11202112, 0x11202210, 0x11212011, 0x11212110, 0x11212111, 0x11212112, 0x11212211, 0x11222010, - 0x11222111, 0x11222212, 0x12202012, 0x12202110, 0x12202212, 0x12212111, 0x12222011, 0x12222110, - 0x12222111, 0x12222211, 0x10212021, 0x10212122, 0x10212220, 0x11202021, 0x11202120, 0x11202221, - 0x11212020, 0x11212121, 0x11212220, 0x11212222, 0x11222120, 0x11222121, 0x11222221, 0x12202122, - 0x12212120, 0x12212220, 0x12212222, 0x12222122, 0x20000000, 0x20000002, 0x20000200, 0x20000202, - 0x20020000, 0x20020002, 0x20020200, 0x20020202, 0x21000101, 0x21010000, 0x21010001, 0x21010100, - 0x21010102, 0x21010201, 0x21020101, 0x22000000, 0x22000002, 0x22000200, 0x22000202, 0x22010101, - 0x22020000, 0x22020002, 0x22020200, 0x22020202, 0x20000111, 0x20010011, 0x20010110, 0x20010112, - 0x20010211, 0x20020111, 0x21000011, 0x21000110, 0x21000211, 0x21010010, 0x21010012, 0x21010111, - 0x21010112, 0x21010210, 0x21010211, 0x21020110, 0x21020112, 0x21020211, 0x22000111, 0x22000211, - 0x22010110, 0x22010112, 0x22010211, 0x22020111, 0x20000020, 0x20000022, 0x20000220, 0x20000222, - 0x20010121, 0x20020020, 0x20020022, 0x20020220, 0x20020222, 0x21010021, 0x21010120, 0x21010221, - 0x21020121, 0x22000020, 0x22000022, 0x22000220, 0x22000222, 0x22010121, 0x22020020, 0x22020022, - 0x22020220, 0x22020222, 0x20011100, 0x20011201, 0x21001001, 0x21001100, 0x21011001, 0x21011101, - 0x21011202, 0x21021001, 0x21021100, 0x21021201, 0x22011100, 0x22011201, 0x20001011, 0x20001211, - 0x20011012, 0x20011111, 0x20011212, 0x20021112, 0x20021211, 0x21001010, 0x21001011, 0x21001111, - 0x21001210, 0x21011011, 0x21011110, 0x21011111, 0x21011112, 0x21011211, 0x21011212, 0x21021111, - 0x21021112, 0x21021210, 0x21021212, 0x22001011, 0x22001110, 0x22001112, 0x22001211, 0x22011010, - 0x22011012, 0x22011111, 0x22011210, 0x22021112, 0x20011021, 0x20011122, 0x20011221, 0x20021121, - 0x21001021, 0x21001120, 0x21001221, 0x21001222, 0x21011020, 0x21011121, 0x21011221, 0x21011222, - 0x21021021, 0x21021122, 0x21021222, 0x22001121, 0x22011021, 0x22011222, 0x22021120, 0x20002000, - 0x20002002, 0x20002200, 0x20002202, 0x20012101, 0x20022000, 0x20022002, 0x20022200, 0x20022202, - 0x21002001, 0x21002101, 0x21012001, 0x21012100, 0x21012201, 0x21022101, 0x21022201, 0x22002000, - 0x22002002, 0x22002200, 0x22002202, 0x22012101, 0x22022000, 0x22022002, 0x22022200, 0x22022202, - 0x20002111, 0x20002112, 0x20012011, 0x20012110, 0x20012112, 0x20022111, 0x21002011, 0x21002110, - 0x21002112, 0x21002211, 0x21012010, 0x21012012, 0x21012111, 0x21012212, 0x21022011, 0x21022110, - 0x22002111, 0x22012112, 0x22012211, 0x22022111, 0x20002020, 0x20002022, 0x20002220, 0x20002222, - 0x20012121, 0x20022020, 0x20022022, 0x20022220, 0x20022222, 0x21002121, 0x21012021, 0x21012120, - 0x21012122, 0x22002020, 0x22002022, 0x22002220, 0x22002222, 0x22012121, 0x22022020, 0x22022022, - 0x22022220, 0x22022222, 0x20100101, 0x20110001, 0x20110102, 0x20110200, 0x20110201, 0x20120101, - 0x21100001, 0x21100102, 0x21100201, 0x21110101, 0x21110200, 0x21110202, 0x21120201, 0x21120202, - 0x22100101, 0x22110001, 0x22110100, 0x22110102, 0x22110201, 0x22120101, 0x20100011, 0x20100110, - 0x20100112, 0x20100211, 0x20110010, 0x20110111, 0x20110210, 0x20110212, 0x20120011, 0x20120110, - 0x20120112, 0x20120211, 0x21100010, 0x21100111, 0x21110010, 0x21110011, 0x21110110, 0x21110111, - 0x21110112, 0x21110211, 0x21120012, 0x21120111, 0x22100110, 0x22100112, 0x22110012, 0x22110111, - 0x22110210, 0x22120011, 0x22120110, 0x22120112, 0x22120211, 0x20100121, 0x20110021, 0x20110120, - 0x20110221, 0x20120121, 0x21100120, 0x21100122, 0x21100221, 0x21110020, 0x21110022, 0x21110121, - 0x21110220, 0x21120122, 0x21120221, 0x22100121, 0x22110120, 0x22110122, 0x22120221, 0x20101001, - 0x20101100, 0x20101102, 0x20111000, 0x20111101, 0x20111200, 0x20121102, 0x21101000, 0x21101202, - 0x21111001, 0x21111100, 0x21111101, 0x21111102, 0x21111200, 0x21111201, 0x21121000, 0x21121001, - 0x21121002, 0x21121101, 0x22101100, 0x22101102, 0x22111002, 0x22111100, 0x22111101, 0x22111200, - 0x22121001, 0x22121201, 0x20101010, 0x20101111, 0x20101210, 0x20101212, 0x20111010, 0x20111011, - 0x20111110, 0x20111111, 0x20111112, 0x20111211, 0x20121011, 0x20121111, 0x20121211, 0x20121212, - 0x21101011, 0x21101110, 0x21101111, 0x21101112, 0x21101211, 0x21111010, 0x21111011, 0x21111012, - 0x21111110, 0x21111111, 0x21111112, 0x21111210, 0x21111211, 0x21111212, 0x21121011, 0x21121110, - 0x21121111, 0x21121112, 0x21121211, 0x22101011, 0x22101111, 0x22101210, 0x22111011, 0x22111012, - 0x22111110, 0x22111111, 0x22111112, 0x22111211, 0x22111212, 0x22121010, 0x22121012, 0x22121111, - 0x22121210, 0x22121212, 0x20101021, 0x20101120, 0x20111020, 0x20111121, 0x20111221, 0x20121020, - 0x20121122, 0x20121221, 0x21101121, 0x21101220, 0x21101221, 0x21111021, 0x21111022, 0x21111121, - 0x21111122, 0x21111221, 0x21121121, 0x21121220, 0x22101022, 0x22101120, 0x22101221, 0x22101222, - 0x22111022, 0x22111120, 0x22111121, 0x22121120, 0x22121122, 0x22121221, 0x20102101, 0x20112102, - 0x20112201, 0x20122101, 0x21102001, 0x21102102, 0x21112000, 0x21112002, 0x21112101, 0x21112102, - 0x21112202, 0x21122100, 0x21122101, 0x22102101, 0x22112001, 0x22112102, 0x22112201, 0x22122101, - 0x20102110, 0x20102112, 0x20102211, 0x20112010, 0x20112012, 0x20112111, 0x20112210, 0x20112212, - 0x20122010, 0x20122011, 0x20122110, 0x20122112, 0x21102010, 0x21102012, 0x21102111, 0x21102210, - 0x21102212, 0x21112011, 0x21112110, 0x21112111, 0x21112112, 0x21112211, 0x21122012, 0x21122111, - 0x21122112, 0x21122212, 0x22102011, 0x22102110, 0x22112010, 0x22112012, 0x22112111, 0x22112212, - 0x22122011, 0x22122112, 0x20102121, 0x20112121, 0x20122121, 0x21102120, 0x21102122, 0x21102221, - 0x21112020, 0x21112121, 0x21112220, 0x21122021, 0x22102121, 0x22112021, 0x22112120, 0x22112121, - 0x22112122, 0x20200000, 0x20200002, 0x20200200, 0x20200202, 0x20210101, 0x20220000, 0x20220002, - 0x20220200, 0x20220202, 0x21200101, 0x21210001, 0x21210100, 0x21210102, 0x21210201, 0x22200000, - 0x22200002, 0x22200200, 0x22200202, 0x22210101, 0x22220000, 0x22220002, 0x22220200, 0x22220202, - 0x20200111, 0x20200211, 0x20210011, 0x20210110, 0x20210112, 0x20210211, 0x20210212, 0x21200112, - 0x21200211, 0x21210011, 0x21210111, 0x21210210, 0x21210212, 0x21220011, 0x21220110, 0x22200111, - 0x22210010, 0x22210012, 0x22210112, 0x22210211, 0x20200022, 0x20200220, 0x20200222, 0x20210020, - 0x20210221, 0x20220022, 0x20220220, 0x20220222, 0x21200121, 0x21210021, 0x21210122, 0x21210221, - 0x21220121, 0x22200020, 0x22200022, 0x22200220, 0x22200222, 0x22210121, 0x22220020, 0x22220022, - 0x22220220, 0x22220222, 0x20211201, 0x20221101, 0x21201001, 0x21201100, 0x21211000, 0x21211100, - 0x21211101, 0x21211200, 0x21211202, 0x21221001, 0x21221101, 0x21221102, 0x21221200, 0x21221201, - 0x22201101, 0x20201112, 0x20201211, 0x20211010, 0x20211012, 0x20211111, 0x20211210, 0x20221112, - 0x20221211, 0x21201012, 0x21201111, 0x21211011, 0x21211110, 0x21211111, 0x21211112, 0x21211211, - 0x21221111, 0x21221212, 0x22201011, 0x22201110, 0x22201111, 0x22201112, 0x22201211, 0x22211012, - 0x22211111, 0x22211210, 0x20201121, 0x20211021, 0x20211122, 0x20211222, 0x20221021, 0x20221121, - 0x21201120, 0x21201122, 0x21201222, 0x21211022, 0x21211121, 0x21211122, 0x21211220, 0x21221020, - 0x21221022, 0x22201122, 0x22211020, 0x22211121, 0x22211122, 0x22211221, 0x22221021, 0x22221120, - 0x22221122, 0x20202000, 0x20202002, 0x20202200, 0x20202202, 0x20222000, 0x20222002, 0x20222200, - 0x20222202, 0x21212001, 0x21212100, 0x21212102, 0x21212201, 0x22202000, 0x22202002, 0x22202200, - 0x22202202, 0x22212101, 0x22222000, 0x22222002, 0x22222200, 0x22222202, 0x20202111, 0x20212110, - 0x20212211, 0x20222011, 0x20222111, 0x21202011, 0x21212010, 0x21212111, 0x21212212, 0x21222011, - 0x21222112, 0x21222211, 0x22212010, 0x22212112, 0x20202020, 0x20202022, 0x20202220, 0x20202222, - 0x20222020, 0x20222022, 0x20222220, 0x20222222, 0x21212021, 0x21212120, 0x21212122, 0x22202020, - 0x22202022, 0x22202220, 0x22202222, 0x22212121, 0x22222020, 0x22222022, 0x22222220, 0x22222222, -}; -#endif +#define IQ1S_GRID_SIZE 2048 +// The buffer packs two 16-bit grid entries per uint32, so it needs no 16-bit storage buffer support +#define IQ1S_GRID_PACKED_LEN (IQ1S_GRID_SIZE / 2) -shared uint16_t iq1s_grid[2048]; +shared uint16_t iq1s_grid[IQ1S_GRID_SIZE]; #if defined(NEEDS_IQ1S_GRID_GPU) -shared uint32_t iq1s_grid_gpu[2048]; +shared uint32_t iq1s_grid_gpu[IQ1S_GRID_SIZE]; #endif -#if defined(DATA_A_IQ1_S) || defined(DATA_A_IQ1_M) #define NEEDS_INIT_IQ_SHMEM void init_iq_shmem(uvec3 wgsize) { // copy the table into shared memory and sync - [[unroll]] for (uint i = 0; i < iq1s_grid_const.length(); i += wgsize.x) { + [[unroll]] for (uint i = 0; i < IQ1S_GRID_PACKED_LEN; i += wgsize.x) { uint idx = i + gl_LocalInvocationIndex.x; - if (iq1s_grid_const.length() % wgsize.x == 0 || idx < iq1s_grid_const.length()) { - u16vec2 g = unpack16(iq1s_grid_const[idx]); + if (IQ1S_GRID_PACKED_LEN % wgsize.x == 0 || idx < IQ1S_GRID_PACKED_LEN) { + u16vec2 g = unpack16(iq_grid[IQ1S_GRID_OFFSET / 4 + idx]); // bytes to uint32 index iq1s_grid[2*idx+0] = g.x; iq1s_grid[2*idx+1] = g.y; } } #if defined(NEEDS_IQ1S_GRID_GPU) - [[unroll]] for (uint i = 0; i < iq1s_grid_gpu_const.length(); i += wgsize.x) { + [[unroll]] for (uint i = 0; i < iq1s_grid_gpu.length(); i += wgsize.x) { uint idx = i + gl_LocalInvocationIndex.x; - if (iq1s_grid_gpu_const.length() % wgsize.x == 0 || idx < iq1s_grid_gpu_const.length()) { - iq1s_grid_gpu[idx] = iq1s_grid_gpu_const[idx]; + if (iq1s_grid_gpu.length() % wgsize.x == 0 || idx < iq1s_grid_gpu.length()) { + iq1s_grid_gpu[idx] = iq_grid[IQ1S_GRID_GPU_OFFSET / 4 + idx]; // bytes to uint32 index } } #endif barrier(); } #endif -#endif #if defined(DATA_A_IQ2_XXS) || defined(DATA_A_IQ2_XS) || defined(DATA_A_IQ2_S) +layout (binding = IQ_GRID_BINDING) readonly buffer IQGrid { uvec2 iq_grid[]; }; + #if defined(DATA_A_IQ2_S) shared uvec2 iq2s_grid[1024]; #elif defined(DATA_A_IQ2_XS) @@ -1023,96 +645,24 @@ struct block_iq2_xxs_packed16 uint16_t qs[QUANT_K_IQ2_XXS/8]; }; -#if defined(DATA_A_IQ2_XXS) - -const uvec2[256] iq2xxs_grid_const = { - uvec2(0x08080808, 0x08080808), uvec2(0x0808082b, 0x08080808), uvec2(0x08081919, 0x08080808), uvec2(0x08082b08, 0x08080808), - uvec2(0x08082b2b, 0x08080808), uvec2(0x08190819, 0x08080808), uvec2(0x08191908, 0x08080808), uvec2(0x082b0808, 0x08080808), - uvec2(0x082b082b, 0x08080808), uvec2(0x082b2b08, 0x08080808), uvec2(0x082b2b2b, 0x08080808), uvec2(0x19080819, 0x08080808), - uvec2(0x19081908, 0x08080808), uvec2(0x19190808, 0x08080808), uvec2(0x19192b08, 0x08080808), uvec2(0x192b0819, 0x08080808), - uvec2(0x192b1908, 0x08080808), uvec2(0x2b080808, 0x08080808), uvec2(0x2b08082b, 0x08080808), uvec2(0x2b082b2b, 0x08080808), - uvec2(0x2b2b082b, 0x08080808), uvec2(0x08080819, 0x08080819), uvec2(0x08081908, 0x08080819), uvec2(0x08190808, 0x08080819), - uvec2(0x08191919, 0x08080819), uvec2(0x19080808, 0x08080819), uvec2(0x2b081908, 0x08080819), uvec2(0x2b192b08, 0x08080819), - uvec2(0x08080808, 0x0808082b), uvec2(0x0808082b, 0x0808082b), uvec2(0x082b082b, 0x0808082b), uvec2(0x2b08082b, 0x0808082b), - uvec2(0x08080819, 0x08081908), uvec2(0x08081908, 0x08081908), uvec2(0x08190808, 0x08081908), uvec2(0x082b0819, 0x08081908), - uvec2(0x082b1908, 0x08081908), uvec2(0x19080808, 0x08081908), uvec2(0x1908082b, 0x08081908), uvec2(0x19082b08, 0x08081908), - uvec2(0x192b0808, 0x08081908), uvec2(0x2b080819, 0x08081908), uvec2(0x2b081908, 0x08081908), uvec2(0x2b190808, 0x08081908), - uvec2(0x2b2b1908, 0x08081908), uvec2(0x08080808, 0x08081919), uvec2(0x0808082b, 0x08081919), uvec2(0x08082b08, 0x08081919), - uvec2(0x082b0808, 0x08081919), uvec2(0x1908192b, 0x08081919), uvec2(0x192b2b19, 0x08081919), uvec2(0x2b080808, 0x08081919), - uvec2(0x2b190819, 0x08081919), uvec2(0x08082b19, 0x0808192b), uvec2(0x08190808, 0x0808192b), uvec2(0x19080808, 0x0808192b), - uvec2(0x2b081908, 0x0808192b), uvec2(0x2b2b1908, 0x0808192b), uvec2(0x08080808, 0x08082b08), uvec2(0x08081919, 0x08082b08), - uvec2(0x08082b08, 0x08082b08), uvec2(0x08191908, 0x08082b08), uvec2(0x082b2b08, 0x08082b08), uvec2(0x19080819, 0x08082b08), - uvec2(0x19081908, 0x08082b08), uvec2(0x19190808, 0x08082b08), uvec2(0x1919082b, 0x08082b08), uvec2(0x2b082b08, 0x08082b08), - uvec2(0x08081908, 0x08082b19), uvec2(0x19080808, 0x08082b19), uvec2(0x0808082b, 0x08082b2b), uvec2(0x08191908, 0x08082b2b), - uvec2(0x08080819, 0x08190808), uvec2(0x08081908, 0x08190808), uvec2(0x08190808, 0x08190808), uvec2(0x082b0819, 0x08190808), - uvec2(0x19080808, 0x08190808), uvec2(0x192b0808, 0x08190808), uvec2(0x2b081908, 0x08190808), uvec2(0x2b190808, 0x08190808), - uvec2(0x2b191919, 0x08190808), uvec2(0x08080808, 0x08190819), uvec2(0x08082b08, 0x08190819), uvec2(0x082b0808, 0x08190819), - uvec2(0x19190808, 0x08190819), uvec2(0x19192b2b, 0x08190819), uvec2(0x2b080808, 0x08190819), uvec2(0x082b1908, 0x0819082b), - uvec2(0x19081919, 0x0819082b), uvec2(0x08080808, 0x08191908), uvec2(0x08082b08, 0x08191908), uvec2(0x082b0808, 0x08191908), - uvec2(0x082b1919, 0x08191908), uvec2(0x19082b19, 0x08191908), uvec2(0x2b080808, 0x08191908), uvec2(0x08192b08, 0x08191919), - uvec2(0x192b082b, 0x08191919), uvec2(0x08080808, 0x0819192b), uvec2(0x0819192b, 0x0819192b), uvec2(0x08080819, 0x08192b08), - uvec2(0x08081908, 0x08192b08), uvec2(0x08190808, 0x08192b08), uvec2(0x19080808, 0x08192b08), uvec2(0x2b080819, 0x08192b08), - uvec2(0x08080808, 0x08192b19), uvec2(0x08081919, 0x08192b19), uvec2(0x2b2b0808, 0x08192b19), uvec2(0x19190819, 0x08192b2b), - uvec2(0x08080808, 0x082b0808), uvec2(0x0808082b, 0x082b0808), uvec2(0x08082b2b, 0x082b0808), uvec2(0x19081908, 0x082b0808), - uvec2(0x192b0819, 0x082b0808), uvec2(0x2b080808, 0x082b0808), uvec2(0x2b08082b, 0x082b0808), uvec2(0x082b2b19, 0x082b0819), - uvec2(0x19082b08, 0x082b0819), uvec2(0x08080808, 0x082b082b), uvec2(0x0808082b, 0x082b082b), uvec2(0x08080819, 0x082b1908), - uvec2(0x08081908, 0x082b1908), uvec2(0x08190808, 0x082b1908), uvec2(0x19080808, 0x082b1908), uvec2(0x1919192b, 0x082b1908), - uvec2(0x08080808, 0x082b1919), uvec2(0x19080819, 0x082b1919), uvec2(0x192b1908, 0x082b1919), uvec2(0x2b190808, 0x082b192b), - uvec2(0x08082b08, 0x082b2b08), uvec2(0x082b0808, 0x082b2b08), uvec2(0x2b191908, 0x082b2b08), uvec2(0x19081908, 0x082b2b2b), - uvec2(0x08080819, 0x19080808), uvec2(0x08081908, 0x19080808), uvec2(0x08190808, 0x19080808), uvec2(0x08192b08, 0x19080808), - uvec2(0x082b0819, 0x19080808), uvec2(0x082b1908, 0x19080808), uvec2(0x19080808, 0x19080808), uvec2(0x19082b08, 0x19080808), - uvec2(0x1919192b, 0x19080808), uvec2(0x192b0808, 0x19080808), uvec2(0x2b080819, 0x19080808), uvec2(0x2b081908, 0x19080808), - uvec2(0x2b190808, 0x19080808), uvec2(0x08080808, 0x19080819), uvec2(0x082b0808, 0x19080819), uvec2(0x192b0819, 0x19080819), - uvec2(0x2b080808, 0x19080819), uvec2(0x2b081919, 0x19080819), uvec2(0x08080819, 0x1908082b), uvec2(0x08190808, 0x1908082b), - uvec2(0x19082b08, 0x1908082b), uvec2(0x1919192b, 0x1908082b), uvec2(0x192b2b08, 0x1908082b), uvec2(0x08080808, 0x19081908), - uvec2(0x08082b08, 0x19081908), uvec2(0x082b0808, 0x19081908), uvec2(0x2b080808, 0x19081908), uvec2(0x2b192b19, 0x19081908), - uvec2(0x0819082b, 0x19081919), uvec2(0x082b1908, 0x19081919), uvec2(0x08080808, 0x1908192b), uvec2(0x08080819, 0x19082b08), - uvec2(0x08081908, 0x19082b08), uvec2(0x08190808, 0x19082b08), uvec2(0x19080808, 0x19082b08), uvec2(0x19081919, 0x19082b08), - uvec2(0x08080808, 0x19082b19), uvec2(0x19192b08, 0x19082b19), uvec2(0x192b0819, 0x19082b19), uvec2(0x2b08082b, 0x19082b19), - uvec2(0x19081919, 0x19082b2b), uvec2(0x2b190808, 0x19082b2b), uvec2(0x08080808, 0x19190808), uvec2(0x08082b08, 0x19190808), - uvec2(0x08190819, 0x19190808), uvec2(0x08192b19, 0x19190808), uvec2(0x082b0808, 0x19190808), uvec2(0x2b080808, 0x19190808), - uvec2(0x2b082b08, 0x19190808), uvec2(0x08081908, 0x19190819), uvec2(0x1908082b, 0x19190819), uvec2(0x2b2b1908, 0x19190819), - uvec2(0x2b190819, 0x1919082b), uvec2(0x2b190808, 0x19191908), uvec2(0x2b19082b, 0x19191908), uvec2(0x08082b2b, 0x19191919), - uvec2(0x08080819, 0x1919192b), uvec2(0x19191908, 0x1919192b), uvec2(0x08080808, 0x19192b08), uvec2(0x08190819, 0x19192b08), - uvec2(0x08192b19, 0x19192b08), uvec2(0x192b1908, 0x19192b08), uvec2(0x19080808, 0x19192b19), uvec2(0x08082b08, 0x19192b2b), - uvec2(0x08081908, 0x192b0808), uvec2(0x08190808, 0x192b0808), uvec2(0x19080808, 0x192b0808), uvec2(0x192b2b08, 0x192b0808), - uvec2(0x08080808, 0x192b0819), uvec2(0x19191919, 0x192b0819), uvec2(0x08192b08, 0x192b082b), uvec2(0x192b0808, 0x192b082b), - uvec2(0x08080808, 0x192b1908), uvec2(0x08081919, 0x192b1908), uvec2(0x08190808, 0x192b1919), uvec2(0x0819082b, 0x192b1919), - uvec2(0x2b081908, 0x192b1919), uvec2(0x1908082b, 0x192b2b08), uvec2(0x08080808, 0x2b080808), uvec2(0x0808082b, 0x2b080808), - uvec2(0x08082b2b, 0x2b080808), uvec2(0x19080819, 0x2b080808), uvec2(0x2b08082b, 0x2b080808), uvec2(0x08081908, 0x2b080819), - uvec2(0x08192b08, 0x2b080819), uvec2(0x19080808, 0x2b080819), uvec2(0x08190819, 0x2b08082b), uvec2(0x08080819, 0x2b081908), - uvec2(0x08081908, 0x2b081908), uvec2(0x08190808, 0x2b081908), uvec2(0x08191919, 0x2b081908), uvec2(0x19080808, 0x2b081908), - uvec2(0x192b0808, 0x2b081908), uvec2(0x08080808, 0x2b081919), uvec2(0x1908192b, 0x2b081919), uvec2(0x2b191908, 0x2b081919), - uvec2(0x08082b19, 0x2b08192b), uvec2(0x19080808, 0x2b08192b), uvec2(0x192b0808, 0x2b08192b), uvec2(0x0808082b, 0x2b082b08), - uvec2(0x08081908, 0x2b082b19), uvec2(0x08190819, 0x2b082b2b), uvec2(0x08081908, 0x2b190808), uvec2(0x08190808, 0x2b190808), - uvec2(0x082b1908, 0x2b190808), uvec2(0x19080808, 0x2b190808), uvec2(0x2b2b0819, 0x2b190808), uvec2(0x0819192b, 0x2b190819), - uvec2(0x2b080808, 0x2b190819), uvec2(0x19081919, 0x2b19082b), uvec2(0x08080808, 0x2b191908), uvec2(0x082b082b, 0x2b191908), - uvec2(0x19081908, 0x2b191908), uvec2(0x19190819, 0x2b191919), uvec2(0x2b080819, 0x2b192b08), uvec2(0x082b0808, 0x2b192b19), - uvec2(0x0808082b, 0x2b2b0808), uvec2(0x19190808, 0x2b2b0808), uvec2(0x2b081919, 0x2b2b0808), uvec2(0x08082b19, 0x2b2b0819), - uvec2(0x08080808, 0x2b2b082b), uvec2(0x08192b08, 0x2b2b1908), uvec2(0x19190808, 0x2b2b2b08), uvec2(0x08081908, 0x2b2b2b19) -}; - #if defined(DATA_A_IQ2_XXS) #define NEEDS_INIT_IQ_SHMEM void init_iq_shmem(uvec3 wgsize) { // copy the table into shared memory and sync [[unroll]] for (uint i = 0; i < iq2xxs_grid.length(); i += wgsize.x) { - if (iq2xxs_grid_const.length() % wgsize.x == 0 || i + gl_LocalInvocationIndex.x < iq2xxs_grid_const.length()) { - iq2xxs_grid[i + gl_LocalInvocationIndex.x] = iq2xxs_grid_const[i + gl_LocalInvocationIndex.x]; + if (iq2xxs_grid.length() % wgsize.x == 0 || i + gl_LocalInvocationIndex.x < iq2xxs_grid.length()) { + iq2xxs_grid[i + gl_LocalInvocationIndex.x] = iq_grid[IQ2XXS_GRID_OFFSET / 8 + i + gl_LocalInvocationIndex.x]; // bytes to uvec2 index } } barrier(); } -#endif -#if defined(DATA_A_IQ2_XXS) #define QUANT_K QUANT_K_IQ2_XXS #define QUANT_R QUANT_R_IQ2_XXS #define A_TYPE block_iq2_xxs #define A_TYPE_PACKED16 block_iq2_xxs_packed16 #endif -#endif #define QUANT_K_IQ2_XS 256 #define QUANT_R_IQ2_XS 1 @@ -1131,160 +681,24 @@ struct block_iq2_xs_packed16 uint16_t scales[QUANT_K_IQ2_XS/64]; }; -#if defined(DATA_A_IQ2_XS) - -const uvec2 iq2xs_grid_const[512] = { - uvec2(0x08080808, 0x08080808), uvec2(0x0808082b, 0x08080808), uvec2(0x08081919, 0x08080808), uvec2(0x08082b08, 0x08080808), - uvec2(0x08082b2b, 0x08080808), uvec2(0x08190819, 0x08080808), uvec2(0x08191908, 0x08080808), uvec2(0x0819192b, 0x08080808), - uvec2(0x08192b19, 0x08080808), uvec2(0x082b0808, 0x08080808), uvec2(0x082b082b, 0x08080808), uvec2(0x082b1919, 0x08080808), - uvec2(0x082b2b08, 0x08080808), uvec2(0x19080819, 0x08080808), uvec2(0x19081908, 0x08080808), uvec2(0x1908192b, 0x08080808), - uvec2(0x19082b19, 0x08080808), uvec2(0x19190808, 0x08080808), uvec2(0x1919082b, 0x08080808), uvec2(0x19191919, 0x08080808), - uvec2(0x19192b08, 0x08080808), uvec2(0x192b0819, 0x08080808), uvec2(0x192b1908, 0x08080808), uvec2(0x2b080808, 0x08080808), - uvec2(0x2b08082b, 0x08080808), uvec2(0x2b081919, 0x08080808), uvec2(0x2b082b08, 0x08080808), uvec2(0x2b190819, 0x08080808), - uvec2(0x2b191908, 0x08080808), uvec2(0x2b192b19, 0x08080808), uvec2(0x2b2b0808, 0x08080808), uvec2(0x08080819, 0x08080819), - uvec2(0x08081908, 0x08080819), uvec2(0x0808192b, 0x08080819), uvec2(0x08082b19, 0x08080819), uvec2(0x08190808, 0x08080819), - uvec2(0x0819082b, 0x08080819), uvec2(0x08191919, 0x08080819), uvec2(0x08192b08, 0x08080819), uvec2(0x08192b2b, 0x08080819), - uvec2(0x082b0819, 0x08080819), uvec2(0x082b1908, 0x08080819), uvec2(0x19080808, 0x08080819), uvec2(0x1908082b, 0x08080819), - uvec2(0x19081919, 0x08080819), uvec2(0x19082b08, 0x08080819), uvec2(0x19190819, 0x08080819), uvec2(0x19191908, 0x08080819), - uvec2(0x192b0808, 0x08080819), uvec2(0x192b2b08, 0x08080819), uvec2(0x2b080819, 0x08080819), uvec2(0x2b081908, 0x08080819), - uvec2(0x2b190808, 0x08080819), uvec2(0x08080808, 0x0808082b), uvec2(0x0808082b, 0x0808082b), uvec2(0x08081919, 0x0808082b), - uvec2(0x08082b08, 0x0808082b), uvec2(0x08190819, 0x0808082b), uvec2(0x08191908, 0x0808082b), uvec2(0x082b0808, 0x0808082b), - uvec2(0x19080819, 0x0808082b), uvec2(0x19081908, 0x0808082b), uvec2(0x19190808, 0x0808082b), uvec2(0x19191919, 0x0808082b), - uvec2(0x2b080808, 0x0808082b), uvec2(0x2b082b2b, 0x0808082b), uvec2(0x08080819, 0x08081908), uvec2(0x08081908, 0x08081908), - uvec2(0x0808192b, 0x08081908), uvec2(0x08082b19, 0x08081908), uvec2(0x08190808, 0x08081908), uvec2(0x0819082b, 0x08081908), - uvec2(0x08191919, 0x08081908), uvec2(0x08192b08, 0x08081908), uvec2(0x082b0819, 0x08081908), uvec2(0x082b1908, 0x08081908), - uvec2(0x19080808, 0x08081908), uvec2(0x1908082b, 0x08081908), uvec2(0x19081919, 0x08081908), uvec2(0x19082b08, 0x08081908), - uvec2(0x19190819, 0x08081908), uvec2(0x19191908, 0x08081908), uvec2(0x1919192b, 0x08081908), uvec2(0x192b0808, 0x08081908), - uvec2(0x2b080819, 0x08081908), uvec2(0x2b081908, 0x08081908), uvec2(0x2b190808, 0x08081908), uvec2(0x08080808, 0x08081919), - uvec2(0x0808082b, 0x08081919), uvec2(0x08081919, 0x08081919), uvec2(0x08082b08, 0x08081919), uvec2(0x08190819, 0x08081919), - uvec2(0x08191908, 0x08081919), uvec2(0x082b0808, 0x08081919), uvec2(0x19080819, 0x08081919), uvec2(0x19081908, 0x08081919), - uvec2(0x19190808, 0x08081919), uvec2(0x192b0819, 0x08081919), uvec2(0x2b080808, 0x08081919), uvec2(0x08080819, 0x0808192b), - uvec2(0x08081908, 0x0808192b), uvec2(0x08190808, 0x0808192b), uvec2(0x082b192b, 0x0808192b), uvec2(0x19080808, 0x0808192b), - uvec2(0x1908082b, 0x0808192b), uvec2(0x2b081908, 0x0808192b), uvec2(0x08080808, 0x08082b08), uvec2(0x0808082b, 0x08082b08), - uvec2(0x08081919, 0x08082b08), uvec2(0x08082b08, 0x08082b08), uvec2(0x08082b2b, 0x08082b08), uvec2(0x08190819, 0x08082b08), - uvec2(0x08191908, 0x08082b08), uvec2(0x082b0808, 0x08082b08), uvec2(0x082b1919, 0x08082b08), uvec2(0x19080819, 0x08082b08), - uvec2(0x19081908, 0x08082b08), uvec2(0x19190808, 0x08082b08), uvec2(0x19192b08, 0x08082b08), uvec2(0x2b080808, 0x08082b08), - uvec2(0x2b2b0808, 0x08082b08), uvec2(0x2b2b2b2b, 0x08082b08), uvec2(0x08080819, 0x08082b19), uvec2(0x08081908, 0x08082b19), - uvec2(0x08190808, 0x08082b19), uvec2(0x19080808, 0x08082b19), uvec2(0x2b080819, 0x08082b19), uvec2(0x2b082b19, 0x08082b19), - uvec2(0x08080808, 0x08082b2b), uvec2(0x082b0808, 0x08082b2b), uvec2(0x082b2b08, 0x08082b2b), uvec2(0x2b19192b, 0x08082b2b), - uvec2(0x2b2b0808, 0x08082b2b), uvec2(0x08080819, 0x08190808), uvec2(0x08081908, 0x08190808), uvec2(0x0808192b, 0x08190808), - uvec2(0x08082b19, 0x08190808), uvec2(0x08190808, 0x08190808), uvec2(0x0819082b, 0x08190808), uvec2(0x08191919, 0x08190808), - uvec2(0x08192b08, 0x08190808), uvec2(0x082b0819, 0x08190808), uvec2(0x082b1908, 0x08190808), uvec2(0x19080808, 0x08190808), - uvec2(0x1908082b, 0x08190808), uvec2(0x19081919, 0x08190808), uvec2(0x19082b08, 0x08190808), uvec2(0x19190819, 0x08190808), - uvec2(0x19191908, 0x08190808), uvec2(0x192b0808, 0x08190808), uvec2(0x192b2b2b, 0x08190808), uvec2(0x2b080819, 0x08190808), - uvec2(0x2b081908, 0x08190808), uvec2(0x2b190808, 0x08190808), uvec2(0x08080808, 0x08190819), uvec2(0x0808082b, 0x08190819), - uvec2(0x08081919, 0x08190819), uvec2(0x08082b08, 0x08190819), uvec2(0x08190819, 0x08190819), uvec2(0x08191908, 0x08190819), - uvec2(0x082b0808, 0x08190819), uvec2(0x19080819, 0x08190819), uvec2(0x19081908, 0x08190819), uvec2(0x19190808, 0x08190819), - uvec2(0x2b080808, 0x08190819), uvec2(0x2b191908, 0x08190819), uvec2(0x2b19192b, 0x08190819), uvec2(0x08080819, 0x0819082b), - uvec2(0x08081908, 0x0819082b), uvec2(0x0808192b, 0x0819082b), uvec2(0x08190808, 0x0819082b), uvec2(0x19080808, 0x0819082b), - uvec2(0x192b0808, 0x0819082b), uvec2(0x08080808, 0x08191908), uvec2(0x0808082b, 0x08191908), uvec2(0x08081919, 0x08191908), - uvec2(0x08082b08, 0x08191908), uvec2(0x08190819, 0x08191908), uvec2(0x08191908, 0x08191908), uvec2(0x082b0808, 0x08191908), - uvec2(0x19080819, 0x08191908), uvec2(0x19081908, 0x08191908), uvec2(0x19082b19, 0x08191908), uvec2(0x19190808, 0x08191908), - uvec2(0x192b1908, 0x08191908), uvec2(0x2b080808, 0x08191908), uvec2(0x08080819, 0x08191919), uvec2(0x08081908, 0x08191919), - uvec2(0x08190808, 0x08191919), uvec2(0x19080808, 0x08191919), uvec2(0x08080808, 0x0819192b), uvec2(0x08191908, 0x0819192b), - uvec2(0x19082b19, 0x0819192b), uvec2(0x08080819, 0x08192b08), uvec2(0x08081908, 0x08192b08), uvec2(0x08190808, 0x08192b08), - uvec2(0x0819082b, 0x08192b08), uvec2(0x19080808, 0x08192b08), uvec2(0x19191908, 0x08192b08), uvec2(0x2b08192b, 0x08192b08), - uvec2(0x08080808, 0x08192b19), uvec2(0x08081919, 0x08192b19), uvec2(0x192b192b, 0x08192b19), uvec2(0x19190819, 0x08192b2b), - uvec2(0x2b2b2b19, 0x08192b2b), uvec2(0x08080808, 0x082b0808), uvec2(0x0808082b, 0x082b0808), uvec2(0x08081919, 0x082b0808), - uvec2(0x08082b08, 0x082b0808), uvec2(0x08082b2b, 0x082b0808), uvec2(0x08190819, 0x082b0808), uvec2(0x08191908, 0x082b0808), - uvec2(0x082b0808, 0x082b0808), uvec2(0x19080819, 0x082b0808), uvec2(0x19081908, 0x082b0808), uvec2(0x19190808, 0x082b0808), - uvec2(0x2b080808, 0x082b0808), uvec2(0x2b2b0808, 0x082b0808), uvec2(0x08080819, 0x082b0819), uvec2(0x08081908, 0x082b0819), - uvec2(0x08190808, 0x082b0819), uvec2(0x19080808, 0x082b0819), uvec2(0x19082b08, 0x082b0819), uvec2(0x192b1919, 0x082b0819), - uvec2(0x08080808, 0x082b082b), uvec2(0x082b082b, 0x082b082b), uvec2(0x2b080808, 0x082b082b), uvec2(0x2b2b2b08, 0x082b082b), - uvec2(0x08080819, 0x082b1908), uvec2(0x08081908, 0x082b1908), uvec2(0x08190808, 0x082b1908), uvec2(0x082b2b19, 0x082b1908), - uvec2(0x19080808, 0x082b1908), uvec2(0x08080808, 0x082b1919), uvec2(0x19080819, 0x082b1919), uvec2(0x1919082b, 0x082b1919), - uvec2(0x2b192b19, 0x082b1919), uvec2(0x08080819, 0x082b192b), uvec2(0x08192b2b, 0x082b192b), uvec2(0x2b2b192b, 0x082b192b), - uvec2(0x08080808, 0x082b2b08), uvec2(0x08082b08, 0x082b2b08), uvec2(0x08082b2b, 0x082b2b08), uvec2(0x082b0808, 0x082b2b08), - uvec2(0x19191919, 0x082b2b08), uvec2(0x2b082b08, 0x082b2b08), uvec2(0x2b2b082b, 0x082b2b08), uvec2(0x192b2b08, 0x082b2b19), - uvec2(0x2b190808, 0x082b2b19), uvec2(0x08082b08, 0x082b2b2b), uvec2(0x082b0808, 0x082b2b2b), uvec2(0x2b08082b, 0x082b2b2b), - uvec2(0x2b082b08, 0x082b2b2b), uvec2(0x2b082b2b, 0x082b2b2b), uvec2(0x08080819, 0x19080808), uvec2(0x08081908, 0x19080808), - uvec2(0x0808192b, 0x19080808), uvec2(0x08082b19, 0x19080808), uvec2(0x08190808, 0x19080808), uvec2(0x0819082b, 0x19080808), - uvec2(0x08191919, 0x19080808), uvec2(0x08192b08, 0x19080808), uvec2(0x082b0819, 0x19080808), uvec2(0x082b1908, 0x19080808), - uvec2(0x19080808, 0x19080808), uvec2(0x1908082b, 0x19080808), uvec2(0x19081919, 0x19080808), uvec2(0x19082b08, 0x19080808), - uvec2(0x19082b2b, 0x19080808), uvec2(0x19190819, 0x19080808), uvec2(0x19191908, 0x19080808), uvec2(0x192b0808, 0x19080808), - uvec2(0x192b1919, 0x19080808), uvec2(0x2b080819, 0x19080808), uvec2(0x2b081908, 0x19080808), uvec2(0x2b190808, 0x19080808), - uvec2(0x08080808, 0x19080819), uvec2(0x0808082b, 0x19080819), uvec2(0x08081919, 0x19080819), uvec2(0x08082b08, 0x19080819), - uvec2(0x08190819, 0x19080819), uvec2(0x08191908, 0x19080819), uvec2(0x082b0808, 0x19080819), uvec2(0x19080819, 0x19080819), - uvec2(0x19081908, 0x19080819), uvec2(0x19190808, 0x19080819), uvec2(0x2b080808, 0x19080819), uvec2(0x2b081919, 0x19080819), - uvec2(0x2b2b082b, 0x19080819), uvec2(0x08080819, 0x1908082b), uvec2(0x08081908, 0x1908082b), uvec2(0x08190808, 0x1908082b), - uvec2(0x0819082b, 0x1908082b), uvec2(0x082b2b19, 0x1908082b), uvec2(0x19080808, 0x1908082b), uvec2(0x08080808, 0x19081908), - uvec2(0x0808082b, 0x19081908), uvec2(0x08081919, 0x19081908), uvec2(0x08082b08, 0x19081908), uvec2(0x08190819, 0x19081908), - uvec2(0x08191908, 0x19081908), uvec2(0x08192b19, 0x19081908), uvec2(0x082b0808, 0x19081908), uvec2(0x19080819, 0x19081908), - uvec2(0x19081908, 0x19081908), uvec2(0x19190808, 0x19081908), uvec2(0x2b080808, 0x19081908), uvec2(0x2b191908, 0x19081908), - uvec2(0x08080819, 0x19081919), uvec2(0x08081908, 0x19081919), uvec2(0x08190808, 0x19081919), uvec2(0x082b1908, 0x19081919), - uvec2(0x19080808, 0x19081919), uvec2(0x2b192b2b, 0x19081919), uvec2(0x08080808, 0x1908192b), uvec2(0x08082b2b, 0x1908192b), - uvec2(0x19081908, 0x1908192b), uvec2(0x19190808, 0x1908192b), uvec2(0x08080819, 0x19082b08), uvec2(0x08081908, 0x19082b08), - uvec2(0x08190808, 0x19082b08), uvec2(0x19080808, 0x19082b08), uvec2(0x19081919, 0x19082b08), uvec2(0x19191908, 0x19082b08), - uvec2(0x192b082b, 0x19082b08), uvec2(0x08080808, 0x19082b19), uvec2(0x08190819, 0x19082b19), uvec2(0x19081908, 0x19082b19), - uvec2(0x19190808, 0x19082b19), uvec2(0x192b2b19, 0x19082b19), uvec2(0x08081908, 0x19082b2b), uvec2(0x08080808, 0x19190808), - uvec2(0x0808082b, 0x19190808), uvec2(0x08081919, 0x19190808), uvec2(0x08082b08, 0x19190808), uvec2(0x08190819, 0x19190808), - uvec2(0x08191908, 0x19190808), uvec2(0x082b0808, 0x19190808), uvec2(0x082b2b08, 0x19190808), uvec2(0x19080819, 0x19190808), - uvec2(0x19081908, 0x19190808), uvec2(0x19190808, 0x19190808), uvec2(0x2b080808, 0x19190808), uvec2(0x08080819, 0x19190819), - uvec2(0x08081908, 0x19190819), uvec2(0x08190808, 0x19190819), uvec2(0x08191919, 0x19190819), uvec2(0x19080808, 0x19190819), - uvec2(0x1908082b, 0x19190819), uvec2(0x08080808, 0x1919082b), uvec2(0x19081908, 0x1919082b), uvec2(0x2b2b2b2b, 0x1919082b), - uvec2(0x08080819, 0x19191908), uvec2(0x08081908, 0x19191908), uvec2(0x08190808, 0x19191908), uvec2(0x082b0819, 0x19191908), - uvec2(0x19080808, 0x19191908), uvec2(0x192b0808, 0x19191908), uvec2(0x2b080819, 0x19191908), uvec2(0x2b2b0819, 0x19191908), - uvec2(0x08080808, 0x19191919), uvec2(0x08082b08, 0x19191919), uvec2(0x2b080808, 0x19191919), uvec2(0x2b082b08, 0x19191919), - uvec2(0x082b0819, 0x1919192b), uvec2(0x192b2b08, 0x1919192b), uvec2(0x2b2b0819, 0x1919192b), uvec2(0x08080808, 0x19192b08), - uvec2(0x08191908, 0x19192b08), uvec2(0x19080819, 0x19192b08), uvec2(0x19190808, 0x19192b08), uvec2(0x2b192b19, 0x19192b08), - uvec2(0x08192b2b, 0x19192b19), uvec2(0x19080808, 0x19192b19), uvec2(0x1908082b, 0x19192b19), uvec2(0x2b081919, 0x19192b2b), - uvec2(0x08080819, 0x192b0808), uvec2(0x08081908, 0x192b0808), uvec2(0x08190808, 0x192b0808), uvec2(0x19080808, 0x192b0808), - uvec2(0x19191908, 0x192b0808), uvec2(0x192b082b, 0x192b0808), uvec2(0x2b08192b, 0x192b0808), uvec2(0x2b2b2b19, 0x192b0808), - uvec2(0x08080808, 0x192b0819), uvec2(0x082b1908, 0x192b082b), uvec2(0x19082b2b, 0x192b082b), uvec2(0x2b19082b, 0x192b082b), - uvec2(0x08080808, 0x192b1908), uvec2(0x0819192b, 0x192b1908), uvec2(0x08190808, 0x192b1919), uvec2(0x19080808, 0x192b1919), - uvec2(0x19081919, 0x192b1919), uvec2(0x2b2b1908, 0x192b1919), uvec2(0x08080819, 0x192b2b08), uvec2(0x192b2b2b, 0x192b2b08), - uvec2(0x082b1919, 0x192b2b19), uvec2(0x0808192b, 0x192b2b2b), uvec2(0x19191908, 0x192b2b2b), uvec2(0x192b082b, 0x192b2b2b), - uvec2(0x08080808, 0x2b080808), uvec2(0x0808082b, 0x2b080808), uvec2(0x08081919, 0x2b080808), uvec2(0x08082b08, 0x2b080808), - uvec2(0x08190819, 0x2b080808), uvec2(0x08191908, 0x2b080808), uvec2(0x082b0808, 0x2b080808), uvec2(0x082b2b2b, 0x2b080808), - uvec2(0x19080819, 0x2b080808), uvec2(0x19081908, 0x2b080808), uvec2(0x19190808, 0x2b080808), uvec2(0x2b080808, 0x2b080808), - uvec2(0x2b08082b, 0x2b080808), uvec2(0x2b2b2b08, 0x2b080808), uvec2(0x2b2b2b2b, 0x2b080808), uvec2(0x08080819, 0x2b080819), - uvec2(0x08081908, 0x2b080819), uvec2(0x0808192b, 0x2b080819), uvec2(0x08190808, 0x2b080819), uvec2(0x19080808, 0x2b080819), - uvec2(0x19190819, 0x2b080819), uvec2(0x19192b19, 0x2b080819), uvec2(0x08080808, 0x2b08082b), uvec2(0x082b0808, 0x2b08082b), - uvec2(0x2b080808, 0x2b08082b), uvec2(0x2b08082b, 0x2b08082b), uvec2(0x2b2b0808, 0x2b08082b), uvec2(0x2b2b2b08, 0x2b08082b), - uvec2(0x08080819, 0x2b081908), uvec2(0x08081908, 0x2b081908), uvec2(0x08190808, 0x2b081908), uvec2(0x0819082b, 0x2b081908), - uvec2(0x08191919, 0x2b081908), uvec2(0x19080808, 0x2b081908), uvec2(0x192b0808, 0x2b081908), uvec2(0x2b082b19, 0x2b081908), - uvec2(0x08080808, 0x2b081919), uvec2(0x19081908, 0x2b081919), uvec2(0x2b2b1919, 0x2b081919), uvec2(0x08192b08, 0x2b08192b), - uvec2(0x192b2b2b, 0x2b08192b), uvec2(0x08080808, 0x2b082b08), uvec2(0x08082b08, 0x2b082b08), uvec2(0x082b1919, 0x2b082b08), - uvec2(0x19192b2b, 0x2b082b08), uvec2(0x2b080808, 0x2b082b08), uvec2(0x2b08082b, 0x2b082b08), uvec2(0x2b2b2b08, 0x2b082b08), - uvec2(0x0808192b, 0x2b082b19), uvec2(0x082b082b, 0x2b082b2b), uvec2(0x2b080808, 0x2b082b2b), uvec2(0x2b082b08, 0x2b082b2b), - uvec2(0x2b19192b, 0x2b082b2b), uvec2(0x2b2b2b08, 0x2b082b2b), uvec2(0x08080819, 0x2b190808), uvec2(0x08081908, 0x2b190808), - uvec2(0x08190808, 0x2b190808), uvec2(0x19080808, 0x2b190808), uvec2(0x1919192b, 0x2b190808), uvec2(0x2b081908, 0x2b190808), - uvec2(0x08080808, 0x2b190819), uvec2(0x082b082b, 0x2b190819), uvec2(0x192b1908, 0x2b190819), uvec2(0x1919192b, 0x2b19082b), - uvec2(0x2b082b19, 0x2b19082b), uvec2(0x08080808, 0x2b191908), uvec2(0x08081919, 0x2b191908), uvec2(0x19081908, 0x2b191908), - uvec2(0x19190808, 0x2b191908), uvec2(0x19192b08, 0x2b191908), uvec2(0x082b2b19, 0x2b191919), uvec2(0x2b190808, 0x2b191919), - uvec2(0x2b19082b, 0x2b191919), uvec2(0x19080819, 0x2b19192b), uvec2(0x19190819, 0x2b192b08), uvec2(0x2b2b192b, 0x2b192b08), - uvec2(0x19082b19, 0x2b192b19), uvec2(0x08191919, 0x2b192b2b), uvec2(0x192b0808, 0x2b192b2b), uvec2(0x08080808, 0x2b2b0808), - uvec2(0x0808082b, 0x2b2b0808), uvec2(0x08082b08, 0x2b2b0808), uvec2(0x08082b2b, 0x2b2b0808), uvec2(0x082b0808, 0x2b2b0808), - uvec2(0x082b2b2b, 0x2b2b0808), uvec2(0x2b2b0808, 0x2b2b0808), uvec2(0x19190819, 0x2b2b0819), uvec2(0x19192b19, 0x2b2b0819), - uvec2(0x2b2b192b, 0x2b2b0819), uvec2(0x08080808, 0x2b2b082b), uvec2(0x0808082b, 0x2b2b082b), uvec2(0x08082b08, 0x2b2b082b), - uvec2(0x082b2b2b, 0x2b2b082b), uvec2(0x2b080808, 0x2b2b082b), uvec2(0x2b2b0808, 0x2b2b082b), uvec2(0x19080808, 0x2b2b1908), - uvec2(0x2b191919, 0x2b2b1908), uvec2(0x192b1919, 0x2b2b192b), uvec2(0x2b192b08, 0x2b2b192b), uvec2(0x08082b2b, 0x2b2b2b08), - uvec2(0x082b0808, 0x2b2b2b08), uvec2(0x082b082b, 0x2b2b2b08), uvec2(0x082b2b08, 0x2b2b2b08), uvec2(0x2b2b0808, 0x2b2b2b08), - uvec2(0x2b2b2b08, 0x2b2b2b08), uvec2(0x08081908, 0x2b2b2b19), uvec2(0x2b081908, 0x2b2b2b19), uvec2(0x2b08192b, 0x2b2b2b19), - uvec2(0x082b2b08, 0x2b2b2b2b), uvec2(0x082b2b2b, 0x2b2b2b2b), uvec2(0x2b190819, 0x2b2b2b2b), uvec2(0x2b2b2b2b, 0x2b2b2b2b), -}; - #if defined(DATA_A_IQ2_XS) #define NEEDS_INIT_IQ_SHMEM void init_iq_shmem(uvec3 wgsize) { // copy the table into shared memory and sync [[unroll]] for (uint i = 0; i < iq2xs_grid.length(); i += wgsize.x) { - if (iq2xs_grid.length() % wgsize.x == 0 || i + gl_LocalInvocationIndex.x < iq2xs_grid_const.length()) { - iq2xs_grid[i + gl_LocalInvocationIndex.x] = iq2xs_grid_const[i + gl_LocalInvocationIndex.x]; + if (iq2xs_grid.length() % wgsize.x == 0 || i + gl_LocalInvocationIndex.x < iq2xs_grid.length()) { + iq2xs_grid[i + gl_LocalInvocationIndex.x] = iq_grid[IQ2XS_GRID_OFFSET / 8 + i + gl_LocalInvocationIndex.x]; // bytes to uvec2 index } } barrier(); } -#endif -#if defined(DATA_A_IQ2_XS) #define QUANT_K QUANT_K_IQ2_XS #define QUANT_R QUANT_R_IQ2_XS #define A_TYPE block_iq2_xs #define A_TYPE_PACKED16 block_iq2_xs_packed16 #endif -#endif #define QUANT_K_IQ2_S 256 #define QUANT_R_IQ2_S 1 @@ -1305,290 +719,28 @@ struct block_iq2_s_packed16 uint16_t scales[QUANT_K_IQ2_S/64]; }; -#if defined(DATA_A_IQ2_S) - -const uvec2 iq2s_grid_const[1024] = { - uvec2(0x08080808, 0x08080808), uvec2(0x0808082b, 0x08080808), uvec2(0x08081919, 0x08080808), uvec2(0x08082b08, 0x08080808), - uvec2(0x08082b2b, 0x08080808), uvec2(0x08190819, 0x08080808), uvec2(0x08191908, 0x08080808), uvec2(0x0819192b, 0x08080808), - uvec2(0x08192b19, 0x08080808), uvec2(0x082b0808, 0x08080808), uvec2(0x082b082b, 0x08080808), uvec2(0x082b1919, 0x08080808), - uvec2(0x082b2b08, 0x08080808), uvec2(0x19080819, 0x08080808), uvec2(0x19081908, 0x08080808), uvec2(0x1908192b, 0x08080808), - uvec2(0x19082b19, 0x08080808), uvec2(0x19190808, 0x08080808), uvec2(0x1919082b, 0x08080808), uvec2(0x19191919, 0x08080808), - uvec2(0x19192b08, 0x08080808), uvec2(0x192b0819, 0x08080808), uvec2(0x192b1908, 0x08080808), uvec2(0x192b192b, 0x08080808), - uvec2(0x192b2b19, 0x08080808), uvec2(0x2b080808, 0x08080808), uvec2(0x2b08082b, 0x08080808), uvec2(0x2b081919, 0x08080808), - uvec2(0x2b082b08, 0x08080808), uvec2(0x2b190819, 0x08080808), uvec2(0x2b191908, 0x08080808), uvec2(0x2b2b0808, 0x08080808), - uvec2(0x2b2b1919, 0x08080808), uvec2(0x2b2b2b2b, 0x08080808), uvec2(0x08080819, 0x08080819), uvec2(0x08081908, 0x08080819), - uvec2(0x0808192b, 0x08080819), uvec2(0x08082b19, 0x08080819), uvec2(0x08190808, 0x08080819), uvec2(0x0819082b, 0x08080819), - uvec2(0x08191919, 0x08080819), uvec2(0x08192b08, 0x08080819), uvec2(0x082b0819, 0x08080819), uvec2(0x082b1908, 0x08080819), - uvec2(0x19080808, 0x08080819), uvec2(0x1908082b, 0x08080819), uvec2(0x19081919, 0x08080819), uvec2(0x19082b08, 0x08080819), - uvec2(0x19190819, 0x08080819), uvec2(0x19191908, 0x08080819), uvec2(0x1919192b, 0x08080819), uvec2(0x19192b19, 0x08080819), - uvec2(0x192b0808, 0x08080819), uvec2(0x192b1919, 0x08080819), uvec2(0x192b2b08, 0x08080819), uvec2(0x2b080819, 0x08080819), - uvec2(0x2b081908, 0x08080819), uvec2(0x2b190808, 0x08080819), uvec2(0x2b19082b, 0x08080819), uvec2(0x2b191919, 0x08080819), - uvec2(0x2b2b0819, 0x08080819), uvec2(0x2b2b1908, 0x08080819), uvec2(0x08080808, 0x0808082b), uvec2(0x0808082b, 0x0808082b), - uvec2(0x08081919, 0x0808082b), uvec2(0x08082b08, 0x0808082b), uvec2(0x08190819, 0x0808082b), uvec2(0x08191908, 0x0808082b), - uvec2(0x082b0808, 0x0808082b), uvec2(0x082b2b2b, 0x0808082b), uvec2(0x19080819, 0x0808082b), uvec2(0x19081908, 0x0808082b), - uvec2(0x1908192b, 0x0808082b), uvec2(0x19082b19, 0x0808082b), uvec2(0x19190808, 0x0808082b), uvec2(0x19191919, 0x0808082b), - uvec2(0x2b080808, 0x0808082b), uvec2(0x2b081919, 0x0808082b), uvec2(0x2b082b2b, 0x0808082b), uvec2(0x2b191908, 0x0808082b), - uvec2(0x2b2b082b, 0x0808082b), uvec2(0x08080819, 0x08081908), uvec2(0x08081908, 0x08081908), uvec2(0x0808192b, 0x08081908), - uvec2(0x08082b19, 0x08081908), uvec2(0x08190808, 0x08081908), uvec2(0x0819082b, 0x08081908), uvec2(0x08191919, 0x08081908), - uvec2(0x08192b08, 0x08081908), uvec2(0x082b0819, 0x08081908), uvec2(0x082b1908, 0x08081908), uvec2(0x082b192b, 0x08081908), - uvec2(0x082b2b19, 0x08081908), uvec2(0x19080808, 0x08081908), uvec2(0x1908082b, 0x08081908), uvec2(0x19081919, 0x08081908), - uvec2(0x19082b08, 0x08081908), uvec2(0x19082b2b, 0x08081908), uvec2(0x19190819, 0x08081908), uvec2(0x19191908, 0x08081908), - uvec2(0x1919192b, 0x08081908), uvec2(0x19192b19, 0x08081908), uvec2(0x192b0808, 0x08081908), uvec2(0x192b082b, 0x08081908), - uvec2(0x192b1919, 0x08081908), uvec2(0x2b080819, 0x08081908), uvec2(0x2b081908, 0x08081908), uvec2(0x2b08192b, 0x08081908), - uvec2(0x2b082b19, 0x08081908), uvec2(0x2b190808, 0x08081908), uvec2(0x2b191919, 0x08081908), uvec2(0x2b192b08, 0x08081908), - uvec2(0x2b2b0819, 0x08081908), uvec2(0x2b2b1908, 0x08081908), uvec2(0x08080808, 0x08081919), uvec2(0x0808082b, 0x08081919), - uvec2(0x08081919, 0x08081919), uvec2(0x08082b08, 0x08081919), uvec2(0x08082b2b, 0x08081919), uvec2(0x08190819, 0x08081919), - uvec2(0x08191908, 0x08081919), uvec2(0x0819192b, 0x08081919), uvec2(0x08192b19, 0x08081919), uvec2(0x082b0808, 0x08081919), - uvec2(0x082b1919, 0x08081919), uvec2(0x082b2b08, 0x08081919), uvec2(0x19080819, 0x08081919), uvec2(0x19081908, 0x08081919), - uvec2(0x1908192b, 0x08081919), uvec2(0x19082b19, 0x08081919), uvec2(0x19190808, 0x08081919), uvec2(0x1919082b, 0x08081919), - uvec2(0x19191919, 0x08081919), uvec2(0x19192b08, 0x08081919), uvec2(0x192b0819, 0x08081919), uvec2(0x192b1908, 0x08081919), - uvec2(0x2b080808, 0x08081919), uvec2(0x2b08082b, 0x08081919), uvec2(0x2b081919, 0x08081919), uvec2(0x2b082b08, 0x08081919), - uvec2(0x2b190819, 0x08081919), uvec2(0x2b191908, 0x08081919), uvec2(0x2b2b0808, 0x08081919), uvec2(0x08080819, 0x0808192b), - uvec2(0x08081908, 0x0808192b), uvec2(0x0808192b, 0x0808192b), uvec2(0x08082b19, 0x0808192b), uvec2(0x08190808, 0x0808192b), - uvec2(0x08191919, 0x0808192b), uvec2(0x19080808, 0x0808192b), uvec2(0x19081919, 0x0808192b), uvec2(0x19082b08, 0x0808192b), - uvec2(0x19190819, 0x0808192b), uvec2(0x19191908, 0x0808192b), uvec2(0x192b0808, 0x0808192b), uvec2(0x2b080819, 0x0808192b), - uvec2(0x2b081908, 0x0808192b), uvec2(0x2b190808, 0x0808192b), uvec2(0x08080808, 0x08082b08), uvec2(0x0808082b, 0x08082b08), - uvec2(0x08081919, 0x08082b08), uvec2(0x08082b08, 0x08082b08), uvec2(0x08190819, 0x08082b08), uvec2(0x08191908, 0x08082b08), - uvec2(0x0819192b, 0x08082b08), uvec2(0x08192b19, 0x08082b08), uvec2(0x082b0808, 0x08082b08), uvec2(0x082b1919, 0x08082b08), - uvec2(0x082b2b2b, 0x08082b08), uvec2(0x19080819, 0x08082b08), uvec2(0x19081908, 0x08082b08), uvec2(0x1908192b, 0x08082b08), - uvec2(0x19082b19, 0x08082b08), uvec2(0x19190808, 0x08082b08), uvec2(0x1919082b, 0x08082b08), uvec2(0x19191919, 0x08082b08), - uvec2(0x19192b08, 0x08082b08), uvec2(0x192b0819, 0x08082b08), uvec2(0x192b1908, 0x08082b08), uvec2(0x2b080808, 0x08082b08), - uvec2(0x2b081919, 0x08082b08), uvec2(0x2b191908, 0x08082b08), uvec2(0x2b2b2b2b, 0x08082b08), uvec2(0x08080819, 0x08082b19), - uvec2(0x08081908, 0x08082b19), uvec2(0x08190808, 0x08082b19), uvec2(0x0819082b, 0x08082b19), uvec2(0x08191919, 0x08082b19), - uvec2(0x08192b08, 0x08082b19), uvec2(0x082b0819, 0x08082b19), uvec2(0x19080808, 0x08082b19), uvec2(0x19081919, 0x08082b19), - uvec2(0x19082b08, 0x08082b19), uvec2(0x19190819, 0x08082b19), uvec2(0x19191908, 0x08082b19), uvec2(0x192b0808, 0x08082b19), - uvec2(0x2b080819, 0x08082b19), uvec2(0x2b190808, 0x08082b19), uvec2(0x08080808, 0x08082b2b), uvec2(0x08190819, 0x08082b2b), - uvec2(0x08191908, 0x08082b2b), uvec2(0x082b082b, 0x08082b2b), uvec2(0x082b2b08, 0x08082b2b), uvec2(0x082b2b2b, 0x08082b2b), - uvec2(0x19190808, 0x08082b2b), uvec2(0x2b192b19, 0x08082b2b), uvec2(0x08080819, 0x08190808), uvec2(0x08081908, 0x08190808), - uvec2(0x0808192b, 0x08190808), uvec2(0x08082b19, 0x08190808), uvec2(0x08190808, 0x08190808), uvec2(0x0819082b, 0x08190808), - uvec2(0x08191919, 0x08190808), uvec2(0x08192b08, 0x08190808), uvec2(0x082b0819, 0x08190808), uvec2(0x082b1908, 0x08190808), - uvec2(0x082b192b, 0x08190808), uvec2(0x19080808, 0x08190808), uvec2(0x1908082b, 0x08190808), uvec2(0x19081919, 0x08190808), - uvec2(0x19082b08, 0x08190808), uvec2(0x19190819, 0x08190808), uvec2(0x19191908, 0x08190808), uvec2(0x1919192b, 0x08190808), - uvec2(0x19192b19, 0x08190808), uvec2(0x192b0808, 0x08190808), uvec2(0x192b082b, 0x08190808), uvec2(0x192b1919, 0x08190808), - uvec2(0x192b2b08, 0x08190808), uvec2(0x2b080819, 0x08190808), uvec2(0x2b081908, 0x08190808), uvec2(0x2b08192b, 0x08190808), - uvec2(0x2b190808, 0x08190808), uvec2(0x2b191919, 0x08190808), uvec2(0x2b192b08, 0x08190808), uvec2(0x2b2b0819, 0x08190808), - uvec2(0x2b2b1908, 0x08190808), uvec2(0x08080808, 0x08190819), uvec2(0x0808082b, 0x08190819), uvec2(0x08081919, 0x08190819), - uvec2(0x08082b08, 0x08190819), uvec2(0x08082b2b, 0x08190819), uvec2(0x08190819, 0x08190819), uvec2(0x08191908, 0x08190819), - uvec2(0x0819192b, 0x08190819), uvec2(0x08192b19, 0x08190819), uvec2(0x082b0808, 0x08190819), uvec2(0x082b082b, 0x08190819), - uvec2(0x082b1919, 0x08190819), uvec2(0x082b2b08, 0x08190819), uvec2(0x19080819, 0x08190819), uvec2(0x19081908, 0x08190819), - uvec2(0x1908192b, 0x08190819), uvec2(0x19082b19, 0x08190819), uvec2(0x19190808, 0x08190819), uvec2(0x1919082b, 0x08190819), - uvec2(0x19191919, 0x08190819), uvec2(0x19192b08, 0x08190819), uvec2(0x192b0819, 0x08190819), uvec2(0x192b1908, 0x08190819), - uvec2(0x2b080808, 0x08190819), uvec2(0x2b08082b, 0x08190819), uvec2(0x2b081919, 0x08190819), uvec2(0x2b082b08, 0x08190819), - uvec2(0x2b190819, 0x08190819), uvec2(0x2b191908, 0x08190819), uvec2(0x08080819, 0x0819082b), uvec2(0x08081908, 0x0819082b), - uvec2(0x08082b19, 0x0819082b), uvec2(0x08190808, 0x0819082b), uvec2(0x08191919, 0x0819082b), uvec2(0x082b0819, 0x0819082b), - uvec2(0x082b1908, 0x0819082b), uvec2(0x19080808, 0x0819082b), uvec2(0x19081919, 0x0819082b), uvec2(0x19190819, 0x0819082b), - uvec2(0x19191908, 0x0819082b), uvec2(0x2b080819, 0x0819082b), uvec2(0x2b081908, 0x0819082b), uvec2(0x2b190808, 0x0819082b), - uvec2(0x08080808, 0x08191908), uvec2(0x0808082b, 0x08191908), uvec2(0x08081919, 0x08191908), uvec2(0x08082b08, 0x08191908), - uvec2(0x08190819, 0x08191908), uvec2(0x08191908, 0x08191908), uvec2(0x0819192b, 0x08191908), uvec2(0x08192b19, 0x08191908), - uvec2(0x082b0808, 0x08191908), uvec2(0x082b1919, 0x08191908), uvec2(0x082b2b08, 0x08191908), uvec2(0x19080819, 0x08191908), - uvec2(0x19081908, 0x08191908), uvec2(0x1908192b, 0x08191908), uvec2(0x19082b19, 0x08191908), uvec2(0x19190808, 0x08191908), - uvec2(0x1919082b, 0x08191908), uvec2(0x19191919, 0x08191908), uvec2(0x19192b08, 0x08191908), uvec2(0x192b0819, 0x08191908), - uvec2(0x192b1908, 0x08191908), uvec2(0x2b080808, 0x08191908), uvec2(0x2b08082b, 0x08191908), uvec2(0x2b081919, 0x08191908), - uvec2(0x2b082b08, 0x08191908), uvec2(0x2b190819, 0x08191908), uvec2(0x2b191908, 0x08191908), uvec2(0x2b2b0808, 0x08191908), - uvec2(0x08080819, 0x08191919), uvec2(0x08081908, 0x08191919), uvec2(0x0808192b, 0x08191919), uvec2(0x08082b19, 0x08191919), - uvec2(0x08190808, 0x08191919), uvec2(0x0819082b, 0x08191919), uvec2(0x08191919, 0x08191919), uvec2(0x08192b08, 0x08191919), - uvec2(0x082b0819, 0x08191919), uvec2(0x082b1908, 0x08191919), uvec2(0x19080808, 0x08191919), uvec2(0x1908082b, 0x08191919), - uvec2(0x19081919, 0x08191919), uvec2(0x19082b08, 0x08191919), uvec2(0x19190819, 0x08191919), uvec2(0x19191908, 0x08191919), - uvec2(0x192b0808, 0x08191919), uvec2(0x2b080819, 0x08191919), uvec2(0x2b081908, 0x08191919), uvec2(0x2b190808, 0x08191919), - uvec2(0x08080808, 0x0819192b), uvec2(0x08081919, 0x0819192b), uvec2(0x08082b08, 0x0819192b), uvec2(0x08190819, 0x0819192b), - uvec2(0x08191908, 0x0819192b), uvec2(0x082b0808, 0x0819192b), uvec2(0x19080819, 0x0819192b), uvec2(0x19081908, 0x0819192b), - uvec2(0x19190808, 0x0819192b), uvec2(0x2b080808, 0x0819192b), uvec2(0x2b2b2b2b, 0x0819192b), uvec2(0x08080819, 0x08192b08), - uvec2(0x08081908, 0x08192b08), uvec2(0x0808192b, 0x08192b08), uvec2(0x08082b19, 0x08192b08), uvec2(0x08190808, 0x08192b08), - uvec2(0x08191919, 0x08192b08), uvec2(0x08192b08, 0x08192b08), uvec2(0x082b0819, 0x08192b08), uvec2(0x19080808, 0x08192b08), - uvec2(0x1908082b, 0x08192b08), uvec2(0x19081919, 0x08192b08), uvec2(0x19082b08, 0x08192b08), uvec2(0x19190819, 0x08192b08), - uvec2(0x19191908, 0x08192b08), uvec2(0x192b0808, 0x08192b08), uvec2(0x2b080819, 0x08192b08), uvec2(0x2b081908, 0x08192b08), - uvec2(0x08080808, 0x08192b19), uvec2(0x0808082b, 0x08192b19), uvec2(0x08081919, 0x08192b19), uvec2(0x08082b08, 0x08192b19), - uvec2(0x08190819, 0x08192b19), uvec2(0x08191908, 0x08192b19), uvec2(0x082b0808, 0x08192b19), uvec2(0x19080819, 0x08192b19), - uvec2(0x19081908, 0x08192b19), uvec2(0x19190808, 0x08192b19), uvec2(0x192b2b19, 0x08192b19), uvec2(0x2b2b082b, 0x08192b19), - uvec2(0x08081908, 0x08192b2b), uvec2(0x08190808, 0x08192b2b), uvec2(0x19080808, 0x08192b2b), uvec2(0x1919192b, 0x08192b2b), - uvec2(0x08080808, 0x082b0808), uvec2(0x0808082b, 0x082b0808), uvec2(0x08081919, 0x082b0808), uvec2(0x08082b08, 0x082b0808), - uvec2(0x08190819, 0x082b0808), uvec2(0x08191908, 0x082b0808), uvec2(0x0819192b, 0x082b0808), uvec2(0x08192b19, 0x082b0808), - uvec2(0x082b0808, 0x082b0808), uvec2(0x082b1919, 0x082b0808), uvec2(0x082b2b2b, 0x082b0808), uvec2(0x19080819, 0x082b0808), - uvec2(0x19081908, 0x082b0808), uvec2(0x19190808, 0x082b0808), uvec2(0x1919082b, 0x082b0808), uvec2(0x19191919, 0x082b0808), - uvec2(0x192b1908, 0x082b0808), uvec2(0x2b080808, 0x082b0808), uvec2(0x2b082b2b, 0x082b0808), uvec2(0x2b191908, 0x082b0808), - uvec2(0x2b2b2b2b, 0x082b0808), uvec2(0x08080819, 0x082b0819), uvec2(0x08081908, 0x082b0819), uvec2(0x08190808, 0x082b0819), - uvec2(0x0819082b, 0x082b0819), uvec2(0x08191919, 0x082b0819), uvec2(0x082b0819, 0x082b0819), uvec2(0x19080808, 0x082b0819), - uvec2(0x1908082b, 0x082b0819), uvec2(0x19081919, 0x082b0819), uvec2(0x19190819, 0x082b0819), uvec2(0x19191908, 0x082b0819), - uvec2(0x192b0808, 0x082b0819), uvec2(0x2b080819, 0x082b0819), uvec2(0x2b081908, 0x082b0819), uvec2(0x2b190808, 0x082b0819), - uvec2(0x08080808, 0x082b082b), uvec2(0x08082b2b, 0x082b082b), uvec2(0x082b082b, 0x082b082b), uvec2(0x082b2b08, 0x082b082b), - uvec2(0x082b2b2b, 0x082b082b), uvec2(0x19081908, 0x082b082b), uvec2(0x19190808, 0x082b082b), uvec2(0x2b082b08, 0x082b082b), - uvec2(0x2b082b2b, 0x082b082b), uvec2(0x2b2b2b08, 0x082b082b), uvec2(0x08080819, 0x082b1908), uvec2(0x08081908, 0x082b1908), - uvec2(0x0808192b, 0x082b1908), uvec2(0x08082b19, 0x082b1908), uvec2(0x08190808, 0x082b1908), uvec2(0x08191919, 0x082b1908), - uvec2(0x08192b08, 0x082b1908), uvec2(0x082b0819, 0x082b1908), uvec2(0x082b1908, 0x082b1908), uvec2(0x19080808, 0x082b1908), - uvec2(0x1908082b, 0x082b1908), uvec2(0x19081919, 0x082b1908), uvec2(0x19082b08, 0x082b1908), uvec2(0x19190819, 0x082b1908), - uvec2(0x19191908, 0x082b1908), uvec2(0x192b0808, 0x082b1908), uvec2(0x2b080819, 0x082b1908), uvec2(0x2b081908, 0x082b1908), - uvec2(0x2b190808, 0x082b1908), uvec2(0x08080808, 0x082b1919), uvec2(0x08081919, 0x082b1919), uvec2(0x08082b08, 0x082b1919), - uvec2(0x08190819, 0x082b1919), uvec2(0x08191908, 0x082b1919), uvec2(0x082b0808, 0x082b1919), uvec2(0x19080819, 0x082b1919), - uvec2(0x19081908, 0x082b1919), uvec2(0x19190808, 0x082b1919), uvec2(0x192b192b, 0x082b1919), uvec2(0x2b080808, 0x082b1919), - uvec2(0x08080819, 0x082b192b), uvec2(0x08081908, 0x082b192b), uvec2(0x08190808, 0x082b192b), uvec2(0x19080808, 0x082b192b), - uvec2(0x19192b19, 0x082b192b), uvec2(0x08080808, 0x082b2b08), uvec2(0x08081919, 0x082b2b08), uvec2(0x08190819, 0x082b2b08), - uvec2(0x08191908, 0x082b2b08), uvec2(0x19080819, 0x082b2b08), uvec2(0x19081908, 0x082b2b08), uvec2(0x19190808, 0x082b2b08), - uvec2(0x2b082b2b, 0x082b2b08), uvec2(0x2b2b2b2b, 0x082b2b08), uvec2(0x08080819, 0x082b2b19), uvec2(0x08081908, 0x082b2b19), - uvec2(0x08190808, 0x082b2b19), uvec2(0x2b191919, 0x082b2b19), uvec2(0x08082b2b, 0x082b2b2b), uvec2(0x082b082b, 0x082b2b2b), - uvec2(0x192b1908, 0x082b2b2b), uvec2(0x2b082b08, 0x082b2b2b), uvec2(0x2b082b2b, 0x082b2b2b), uvec2(0x08080819, 0x19080808), - uvec2(0x08081908, 0x19080808), uvec2(0x0808192b, 0x19080808), uvec2(0x08082b19, 0x19080808), uvec2(0x08190808, 0x19080808), - uvec2(0x0819082b, 0x19080808), uvec2(0x08191919, 0x19080808), uvec2(0x08192b08, 0x19080808), uvec2(0x08192b2b, 0x19080808), - uvec2(0x082b0819, 0x19080808), uvec2(0x082b1908, 0x19080808), uvec2(0x082b192b, 0x19080808), uvec2(0x19080808, 0x19080808), - uvec2(0x1908082b, 0x19080808), uvec2(0x19081919, 0x19080808), uvec2(0x19082b08, 0x19080808), uvec2(0x19082b2b, 0x19080808), - uvec2(0x19190819, 0x19080808), uvec2(0x19191908, 0x19080808), uvec2(0x1919192b, 0x19080808), uvec2(0x19192b19, 0x19080808), - uvec2(0x192b0808, 0x19080808), uvec2(0x192b082b, 0x19080808), uvec2(0x192b1919, 0x19080808), uvec2(0x2b080819, 0x19080808), - uvec2(0x2b081908, 0x19080808), uvec2(0x2b190808, 0x19080808), uvec2(0x2b191919, 0x19080808), uvec2(0x2b192b08, 0x19080808), - uvec2(0x2b2b0819, 0x19080808), uvec2(0x2b2b1908, 0x19080808), uvec2(0x08080808, 0x19080819), uvec2(0x0808082b, 0x19080819), - uvec2(0x08081919, 0x19080819), uvec2(0x08082b08, 0x19080819), uvec2(0x08190819, 0x19080819), uvec2(0x08191908, 0x19080819), - uvec2(0x0819192b, 0x19080819), uvec2(0x08192b19, 0x19080819), uvec2(0x082b0808, 0x19080819), uvec2(0x082b082b, 0x19080819), - uvec2(0x082b1919, 0x19080819), uvec2(0x19080819, 0x19080819), uvec2(0x19081908, 0x19080819), uvec2(0x1908192b, 0x19080819), - uvec2(0x19082b19, 0x19080819), uvec2(0x19190808, 0x19080819), uvec2(0x1919082b, 0x19080819), uvec2(0x19191919, 0x19080819), - uvec2(0x19192b08, 0x19080819), uvec2(0x192b0819, 0x19080819), uvec2(0x192b1908, 0x19080819), uvec2(0x2b080808, 0x19080819), - uvec2(0x2b08082b, 0x19080819), uvec2(0x2b081919, 0x19080819), uvec2(0x2b082b08, 0x19080819), uvec2(0x2b190819, 0x19080819), - uvec2(0x2b191908, 0x19080819), uvec2(0x2b2b0808, 0x19080819), uvec2(0x08080819, 0x1908082b), uvec2(0x08081908, 0x1908082b), - uvec2(0x08190808, 0x1908082b), uvec2(0x0819082b, 0x1908082b), uvec2(0x08191919, 0x1908082b), uvec2(0x08192b08, 0x1908082b), - uvec2(0x082b1908, 0x1908082b), uvec2(0x19080808, 0x1908082b), uvec2(0x19081919, 0x1908082b), uvec2(0x19082b08, 0x1908082b), - uvec2(0x19190819, 0x1908082b), uvec2(0x19191908, 0x1908082b), uvec2(0x192b0808, 0x1908082b), uvec2(0x2b080819, 0x1908082b), - uvec2(0x2b081908, 0x1908082b), uvec2(0x08080808, 0x19081908), uvec2(0x0808082b, 0x19081908), uvec2(0x08081919, 0x19081908), - uvec2(0x08082b08, 0x19081908), uvec2(0x08082b2b, 0x19081908), uvec2(0x08190819, 0x19081908), uvec2(0x08191908, 0x19081908), - uvec2(0x0819192b, 0x19081908), uvec2(0x08192b19, 0x19081908), uvec2(0x082b0808, 0x19081908), uvec2(0x082b082b, 0x19081908), - uvec2(0x082b1919, 0x19081908), uvec2(0x082b2b08, 0x19081908), uvec2(0x19080819, 0x19081908), uvec2(0x19081908, 0x19081908), - uvec2(0x1908192b, 0x19081908), uvec2(0x19082b19, 0x19081908), uvec2(0x19190808, 0x19081908), uvec2(0x1919082b, 0x19081908), - uvec2(0x19191919, 0x19081908), uvec2(0x19192b08, 0x19081908), uvec2(0x192b0819, 0x19081908), uvec2(0x192b1908, 0x19081908), - uvec2(0x2b080808, 0x19081908), uvec2(0x2b08082b, 0x19081908), uvec2(0x2b081919, 0x19081908), uvec2(0x2b082b08, 0x19081908), - uvec2(0x2b190819, 0x19081908), uvec2(0x2b191908, 0x19081908), uvec2(0x2b2b0808, 0x19081908), uvec2(0x08080819, 0x19081919), - uvec2(0x08081908, 0x19081919), uvec2(0x0808192b, 0x19081919), uvec2(0x08082b19, 0x19081919), uvec2(0x08190808, 0x19081919), - uvec2(0x0819082b, 0x19081919), uvec2(0x08191919, 0x19081919), uvec2(0x08192b08, 0x19081919), uvec2(0x082b0819, 0x19081919), - uvec2(0x082b1908, 0x19081919), uvec2(0x19080808, 0x19081919), uvec2(0x1908082b, 0x19081919), uvec2(0x19081919, 0x19081919), - uvec2(0x19082b08, 0x19081919), uvec2(0x19190819, 0x19081919), uvec2(0x19191908, 0x19081919), uvec2(0x192b0808, 0x19081919), - uvec2(0x192b2b2b, 0x19081919), uvec2(0x2b080819, 0x19081919), uvec2(0x2b081908, 0x19081919), uvec2(0x2b190808, 0x19081919), - uvec2(0x08080808, 0x1908192b), uvec2(0x0808082b, 0x1908192b), uvec2(0x08081919, 0x1908192b), uvec2(0x08082b08, 0x1908192b), - uvec2(0x08190819, 0x1908192b), uvec2(0x08191908, 0x1908192b), uvec2(0x082b0808, 0x1908192b), uvec2(0x19080819, 0x1908192b), - uvec2(0x19081908, 0x1908192b), uvec2(0x19190808, 0x1908192b), uvec2(0x2b080808, 0x1908192b), uvec2(0x2b2b1919, 0x1908192b), - uvec2(0x08080819, 0x19082b08), uvec2(0x08081908, 0x19082b08), uvec2(0x08082b19, 0x19082b08), uvec2(0x08190808, 0x19082b08), - uvec2(0x0819082b, 0x19082b08), uvec2(0x08191919, 0x19082b08), uvec2(0x08192b08, 0x19082b08), uvec2(0x082b0819, 0x19082b08), - uvec2(0x082b1908, 0x19082b08), uvec2(0x19080808, 0x19082b08), uvec2(0x1908082b, 0x19082b08), uvec2(0x19081919, 0x19082b08), - uvec2(0x19082b08, 0x19082b08), uvec2(0x19190819, 0x19082b08), uvec2(0x19191908, 0x19082b08), uvec2(0x192b0808, 0x19082b08), - uvec2(0x2b081908, 0x19082b08), uvec2(0x2b190808, 0x19082b08), uvec2(0x08080808, 0x19082b19), uvec2(0x0808082b, 0x19082b19), - uvec2(0x08081919, 0x19082b19), uvec2(0x08082b08, 0x19082b19), uvec2(0x08190819, 0x19082b19), uvec2(0x08191908, 0x19082b19), - uvec2(0x082b0808, 0x19082b19), uvec2(0x19080819, 0x19082b19), uvec2(0x19081908, 0x19082b19), uvec2(0x19190808, 0x19082b19), - uvec2(0x2b080808, 0x19082b19), uvec2(0x2b19192b, 0x19082b19), uvec2(0x08080819, 0x19082b2b), uvec2(0x08081908, 0x19082b2b), - uvec2(0x08190808, 0x19082b2b), uvec2(0x19080808, 0x19082b2b), uvec2(0x08080808, 0x19190808), uvec2(0x0808082b, 0x19190808), - uvec2(0x08081919, 0x19190808), uvec2(0x08082b08, 0x19190808), uvec2(0x08190819, 0x19190808), uvec2(0x08191908, 0x19190808), - uvec2(0x0819192b, 0x19190808), uvec2(0x08192b19, 0x19190808), uvec2(0x082b0808, 0x19190808), uvec2(0x082b082b, 0x19190808), - uvec2(0x082b1919, 0x19190808), uvec2(0x082b2b08, 0x19190808), uvec2(0x19080819, 0x19190808), uvec2(0x19081908, 0x19190808), - uvec2(0x1908192b, 0x19190808), uvec2(0x19082b19, 0x19190808), uvec2(0x19190808, 0x19190808), uvec2(0x1919082b, 0x19190808), - uvec2(0x19191919, 0x19190808), uvec2(0x19192b08, 0x19190808), uvec2(0x192b0819, 0x19190808), uvec2(0x192b1908, 0x19190808), - uvec2(0x2b080808, 0x19190808), uvec2(0x2b08082b, 0x19190808), uvec2(0x2b081919, 0x19190808), uvec2(0x2b082b08, 0x19190808), - uvec2(0x2b190819, 0x19190808), uvec2(0x2b191908, 0x19190808), uvec2(0x08080819, 0x19190819), uvec2(0x08081908, 0x19190819), - uvec2(0x0808192b, 0x19190819), uvec2(0x08082b19, 0x19190819), uvec2(0x08190808, 0x19190819), uvec2(0x0819082b, 0x19190819), - uvec2(0x08191919, 0x19190819), uvec2(0x08192b08, 0x19190819), uvec2(0x082b0819, 0x19190819), uvec2(0x082b1908, 0x19190819), - uvec2(0x19080808, 0x19190819), uvec2(0x1908082b, 0x19190819), uvec2(0x19081919, 0x19190819), uvec2(0x19082b08, 0x19190819), - uvec2(0x19190819, 0x19190819), uvec2(0x19191908, 0x19190819), uvec2(0x192b0808, 0x19190819), uvec2(0x2b080819, 0x19190819), - uvec2(0x2b081908, 0x19190819), uvec2(0x2b190808, 0x19190819), uvec2(0x08080808, 0x1919082b), uvec2(0x08081919, 0x1919082b), - uvec2(0x08082b08, 0x1919082b), uvec2(0x08190819, 0x1919082b), uvec2(0x08191908, 0x1919082b), uvec2(0x082b0808, 0x1919082b), - uvec2(0x19080819, 0x1919082b), uvec2(0x19081908, 0x1919082b), uvec2(0x19190808, 0x1919082b), uvec2(0x192b2b19, 0x1919082b), - uvec2(0x2b080808, 0x1919082b), uvec2(0x08080819, 0x19191908), uvec2(0x08081908, 0x19191908), uvec2(0x0808192b, 0x19191908), - uvec2(0x08082b19, 0x19191908), uvec2(0x08190808, 0x19191908), uvec2(0x0819082b, 0x19191908), uvec2(0x08191919, 0x19191908), - uvec2(0x08192b08, 0x19191908), uvec2(0x082b0819, 0x19191908), uvec2(0x082b1908, 0x19191908), uvec2(0x19080808, 0x19191908), - uvec2(0x1908082b, 0x19191908), uvec2(0x19081919, 0x19191908), uvec2(0x19082b08, 0x19191908), uvec2(0x19190819, 0x19191908), - uvec2(0x19191908, 0x19191908), uvec2(0x192b0808, 0x19191908), uvec2(0x2b080819, 0x19191908), uvec2(0x2b081908, 0x19191908), - uvec2(0x2b190808, 0x19191908), uvec2(0x08080808, 0x19191919), uvec2(0x0808082b, 0x19191919), uvec2(0x08081919, 0x19191919), - uvec2(0x08082b08, 0x19191919), uvec2(0x08190819, 0x19191919), uvec2(0x08191908, 0x19191919), uvec2(0x082b0808, 0x19191919), - uvec2(0x19080819, 0x19191919), uvec2(0x19081908, 0x19191919), uvec2(0x19190808, 0x19191919), uvec2(0x2b080808, 0x19191919), - uvec2(0x08080819, 0x1919192b), uvec2(0x08081908, 0x1919192b), uvec2(0x08190808, 0x1919192b), uvec2(0x082b192b, 0x1919192b), - uvec2(0x19080808, 0x1919192b), uvec2(0x08080808, 0x19192b08), uvec2(0x0808082b, 0x19192b08), uvec2(0x08081919, 0x19192b08), - uvec2(0x08082b08, 0x19192b08), uvec2(0x08190819, 0x19192b08), uvec2(0x08191908, 0x19192b08), uvec2(0x082b0808, 0x19192b08), - uvec2(0x19080819, 0x19192b08), uvec2(0x19081908, 0x19192b08), uvec2(0x19190808, 0x19192b08), uvec2(0x19192b2b, 0x19192b08), - uvec2(0x2b080808, 0x19192b08), uvec2(0x08080819, 0x19192b19), uvec2(0x08081908, 0x19192b19), uvec2(0x08190808, 0x19192b19), - uvec2(0x19080808, 0x19192b19), uvec2(0x08080808, 0x19192b2b), uvec2(0x08192b19, 0x19192b2b), uvec2(0x2b081919, 0x19192b2b), - uvec2(0x2b2b2b08, 0x19192b2b), uvec2(0x08080819, 0x192b0808), uvec2(0x08081908, 0x192b0808), uvec2(0x0808192b, 0x192b0808), - uvec2(0x08190808, 0x192b0808), uvec2(0x0819082b, 0x192b0808), uvec2(0x08191919, 0x192b0808), uvec2(0x08192b08, 0x192b0808), - uvec2(0x082b0819, 0x192b0808), uvec2(0x082b1908, 0x192b0808), uvec2(0x19080808, 0x192b0808), uvec2(0x19081919, 0x192b0808), - uvec2(0x19082b08, 0x192b0808), uvec2(0x19190819, 0x192b0808), uvec2(0x19191908, 0x192b0808), uvec2(0x192b0808, 0x192b0808), - uvec2(0x2b081908, 0x192b0808), uvec2(0x2b190808, 0x192b0808), uvec2(0x08080808, 0x192b0819), uvec2(0x0808082b, 0x192b0819), - uvec2(0x08081919, 0x192b0819), uvec2(0x08082b08, 0x192b0819), uvec2(0x08190819, 0x192b0819), uvec2(0x08191908, 0x192b0819), - uvec2(0x082b0808, 0x192b0819), uvec2(0x19080819, 0x192b0819), uvec2(0x19081908, 0x192b0819), uvec2(0x19190808, 0x192b0819), - uvec2(0x2b080808, 0x192b0819), uvec2(0x2b192b19, 0x192b0819), uvec2(0x08081908, 0x192b082b), uvec2(0x08190808, 0x192b082b), - uvec2(0x19080808, 0x192b082b), uvec2(0x1919192b, 0x192b082b), uvec2(0x2b2b0819, 0x192b082b), uvec2(0x08080808, 0x192b1908), - uvec2(0x08081919, 0x192b1908), uvec2(0x08082b08, 0x192b1908), uvec2(0x08190819, 0x192b1908), uvec2(0x08191908, 0x192b1908), - uvec2(0x082b0808, 0x192b1908), uvec2(0x19080819, 0x192b1908), uvec2(0x19081908, 0x192b1908), uvec2(0x19190808, 0x192b1908), - uvec2(0x2b080808, 0x192b1908), uvec2(0x08080819, 0x192b1919), uvec2(0x08081908, 0x192b1919), uvec2(0x08190808, 0x192b1919), - uvec2(0x19080808, 0x192b1919), uvec2(0x19082b2b, 0x192b1919), uvec2(0x192b2b08, 0x192b1919), uvec2(0x2b19082b, 0x192b1919), - uvec2(0x08080808, 0x192b192b), uvec2(0x2b191908, 0x192b192b), uvec2(0x08080819, 0x192b2b08), uvec2(0x08081908, 0x192b2b08), - uvec2(0x08190808, 0x192b2b08), uvec2(0x192b1919, 0x192b2b08), uvec2(0x2b192b08, 0x192b2b08), uvec2(0x08080808, 0x192b2b19), - uvec2(0x082b2b2b, 0x192b2b19), uvec2(0x1908082b, 0x192b2b2b), uvec2(0x2b2b0819, 0x192b2b2b), uvec2(0x08080808, 0x2b080808), - uvec2(0x0808082b, 0x2b080808), uvec2(0x08081919, 0x2b080808), uvec2(0x08082b08, 0x2b080808), uvec2(0x08190819, 0x2b080808), - uvec2(0x08191908, 0x2b080808), uvec2(0x08192b19, 0x2b080808), uvec2(0x082b0808, 0x2b080808), uvec2(0x082b1919, 0x2b080808), - uvec2(0x19080819, 0x2b080808), uvec2(0x19081908, 0x2b080808), uvec2(0x19190808, 0x2b080808), uvec2(0x1919082b, 0x2b080808), - uvec2(0x19191919, 0x2b080808), uvec2(0x19192b08, 0x2b080808), uvec2(0x192b0819, 0x2b080808), uvec2(0x2b080808, 0x2b080808), - uvec2(0x2b081919, 0x2b080808), uvec2(0x2b190819, 0x2b080808), uvec2(0x2b191908, 0x2b080808), uvec2(0x08080819, 0x2b080819), - uvec2(0x08081908, 0x2b080819), uvec2(0x08082b19, 0x2b080819), uvec2(0x08190808, 0x2b080819), uvec2(0x0819082b, 0x2b080819), - uvec2(0x08191919, 0x2b080819), uvec2(0x08192b08, 0x2b080819), uvec2(0x082b0819, 0x2b080819), uvec2(0x082b1908, 0x2b080819), - uvec2(0x19080808, 0x2b080819), uvec2(0x1908082b, 0x2b080819), uvec2(0x19081919, 0x2b080819), uvec2(0x19082b08, 0x2b080819), - uvec2(0x19190819, 0x2b080819), uvec2(0x19191908, 0x2b080819), uvec2(0x2b080819, 0x2b080819), uvec2(0x2b081908, 0x2b080819), - uvec2(0x2b190808, 0x2b080819), uvec2(0x2b2b2b19, 0x2b080819), uvec2(0x08080808, 0x2b08082b), uvec2(0x08081919, 0x2b08082b), - uvec2(0x08082b2b, 0x2b08082b), uvec2(0x08190819, 0x2b08082b), uvec2(0x08191908, 0x2b08082b), uvec2(0x19080819, 0x2b08082b), - uvec2(0x19081908, 0x2b08082b), uvec2(0x19190808, 0x2b08082b), uvec2(0x08080819, 0x2b081908), uvec2(0x08081908, 0x2b081908), - uvec2(0x0808192b, 0x2b081908), uvec2(0x08082b19, 0x2b081908), uvec2(0x08190808, 0x2b081908), uvec2(0x0819082b, 0x2b081908), - uvec2(0x08191919, 0x2b081908), uvec2(0x08192b08, 0x2b081908), uvec2(0x082b0819, 0x2b081908), uvec2(0x19080808, 0x2b081908), - uvec2(0x1908082b, 0x2b081908), uvec2(0x19081919, 0x2b081908), uvec2(0x19082b08, 0x2b081908), uvec2(0x19190819, 0x2b081908), - uvec2(0x19191908, 0x2b081908), uvec2(0x192b0808, 0x2b081908), uvec2(0x2b080819, 0x2b081908), uvec2(0x2b081908, 0x2b081908), - uvec2(0x2b190808, 0x2b081908), uvec2(0x08080808, 0x2b081919), uvec2(0x0808082b, 0x2b081919), uvec2(0x08081919, 0x2b081919), - uvec2(0x08082b08, 0x2b081919), uvec2(0x08190819, 0x2b081919), uvec2(0x08191908, 0x2b081919), uvec2(0x082b0808, 0x2b081919), - uvec2(0x19080819, 0x2b081919), uvec2(0x19081908, 0x2b081919), uvec2(0x19190808, 0x2b081919), uvec2(0x2b080808, 0x2b081919), - uvec2(0x2b082b2b, 0x2b081919), uvec2(0x08080819, 0x2b08192b), uvec2(0x08081908, 0x2b08192b), uvec2(0x08190808, 0x2b08192b), - uvec2(0x082b2b19, 0x2b08192b), uvec2(0x19080808, 0x2b08192b), uvec2(0x08080808, 0x2b082b08), uvec2(0x08081919, 0x2b082b08), - uvec2(0x08190819, 0x2b082b08), uvec2(0x08191908, 0x2b082b08), uvec2(0x19080819, 0x2b082b08), uvec2(0x19081908, 0x2b082b08), - uvec2(0x19190808, 0x2b082b08), uvec2(0x2b2b082b, 0x2b082b08), uvec2(0x08080819, 0x2b082b19), uvec2(0x08081908, 0x2b082b19), - uvec2(0x19080808, 0x2b082b19), uvec2(0x192b1919, 0x2b082b19), uvec2(0x082b082b, 0x2b082b2b), uvec2(0x19192b08, 0x2b082b2b), - uvec2(0x19192b2b, 0x2b082b2b), uvec2(0x2b08082b, 0x2b082b2b), uvec2(0x2b2b082b, 0x2b082b2b), uvec2(0x08080819, 0x2b190808), - uvec2(0x08081908, 0x2b190808), uvec2(0x08082b19, 0x2b190808), uvec2(0x08190808, 0x2b190808), uvec2(0x0819082b, 0x2b190808), - uvec2(0x08191919, 0x2b190808), uvec2(0x08192b08, 0x2b190808), uvec2(0x082b1908, 0x2b190808), uvec2(0x19080808, 0x2b190808), - uvec2(0x1908082b, 0x2b190808), uvec2(0x19081919, 0x2b190808), uvec2(0x19082b08, 0x2b190808), uvec2(0x19190819, 0x2b190808), - uvec2(0x19191908, 0x2b190808), uvec2(0x192b0808, 0x2b190808), uvec2(0x2b080819, 0x2b190808), uvec2(0x2b081908, 0x2b190808), - uvec2(0x2b190808, 0x2b190808), uvec2(0x08080808, 0x2b190819), uvec2(0x08081919, 0x2b190819), uvec2(0x08190819, 0x2b190819), - uvec2(0x08191908, 0x2b190819), uvec2(0x19080819, 0x2b190819), uvec2(0x19081908, 0x2b190819), uvec2(0x19190808, 0x2b190819), - uvec2(0x19192b2b, 0x2b190819), uvec2(0x08080819, 0x2b19082b), uvec2(0x08081908, 0x2b19082b), uvec2(0x08190808, 0x2b19082b), - uvec2(0x19080808, 0x2b19082b), uvec2(0x2b2b192b, 0x2b19082b), uvec2(0x08080808, 0x2b191908), uvec2(0x0808082b, 0x2b191908), - uvec2(0x08081919, 0x2b191908), uvec2(0x08082b08, 0x2b191908), uvec2(0x08190819, 0x2b191908), uvec2(0x08191908, 0x2b191908), - uvec2(0x082b0808, 0x2b191908), uvec2(0x19080819, 0x2b191908), uvec2(0x19081908, 0x2b191908), uvec2(0x19190808, 0x2b191908), - uvec2(0x2b080808, 0x2b191908), uvec2(0x2b19192b, 0x2b191908), uvec2(0x08080819, 0x2b191919), uvec2(0x08081908, 0x2b191919), - uvec2(0x08190808, 0x2b191919), uvec2(0x19080808, 0x2b191919), uvec2(0x2b192b08, 0x2b191919), uvec2(0x2b2b0819, 0x2b191919), - uvec2(0x08080808, 0x2b19192b), uvec2(0x1908192b, 0x2b19192b), uvec2(0x192b1908, 0x2b19192b), uvec2(0x08080819, 0x2b192b08), - uvec2(0x08081908, 0x2b192b08), uvec2(0x08190808, 0x2b192b08), uvec2(0x082b192b, 0x2b192b08), uvec2(0x19080808, 0x2b192b08), - uvec2(0x2b2b2b19, 0x2b192b08), uvec2(0x08080808, 0x2b192b19), uvec2(0x19082b19, 0x2b192b19), uvec2(0x1919082b, 0x2b192b19), - uvec2(0x2b190808, 0x2b192b2b), uvec2(0x08080808, 0x2b2b0808), uvec2(0x08081919, 0x2b2b0808), uvec2(0x08082b2b, 0x2b2b0808), - uvec2(0x08191908, 0x2b2b0808), uvec2(0x082b082b, 0x2b2b0808), uvec2(0x082b2b2b, 0x2b2b0808), uvec2(0x19080819, 0x2b2b0808), - uvec2(0x19081908, 0x2b2b0808), uvec2(0x19190808, 0x2b2b0808), uvec2(0x2b2b082b, 0x2b2b0808), uvec2(0x2b2b2b2b, 0x2b2b0808), - uvec2(0x19080808, 0x2b2b0819), uvec2(0x192b1919, 0x2b2b0819), uvec2(0x0808082b, 0x2b2b082b), uvec2(0x08082b2b, 0x2b2b082b), - uvec2(0x082b082b, 0x2b2b082b), uvec2(0x082b2b08, 0x2b2b082b), uvec2(0x082b2b2b, 0x2b2b082b), uvec2(0x2b08082b, 0x2b2b082b), - uvec2(0x2b082b08, 0x2b2b082b), uvec2(0x2b082b2b, 0x2b2b082b), uvec2(0x2b2b2b08, 0x2b2b082b), uvec2(0x08080819, 0x2b2b1908), - uvec2(0x08081908, 0x2b2b1908), uvec2(0x08190808, 0x2b2b1908), uvec2(0x19080808, 0x2b2b1908), uvec2(0x2b082b19, 0x2b2b1908), - uvec2(0x2b2b1908, 0x2b2b1908), uvec2(0x08080808, 0x2b2b1919), uvec2(0x08192b19, 0x2b2b1919), uvec2(0x19190819, 0x2b2b192b), - uvec2(0x08082b2b, 0x2b2b2b08), uvec2(0x082b2b08, 0x2b2b2b08), uvec2(0x2b2b082b, 0x2b2b2b08), uvec2(0x19191908, 0x2b2b2b19), - uvec2(0x2b08192b, 0x2b2b2b19), uvec2(0x08082b08, 0x2b2b2b2b), uvec2(0x08082b2b, 0x2b2b2b2b), uvec2(0x082b0808, 0x2b2b2b2b), - uvec2(0x082b082b, 0x2b2b2b2b), uvec2(0x082b2b08, 0x2b2b2b2b), uvec2(0x2b082b08, 0x2b2b2b2b), uvec2(0x2b2b2b2b, 0x2b2b2b2b) -}; - #if defined(DATA_A_IQ2_S) #define NEEDS_INIT_IQ_SHMEM void init_iq_shmem(uvec3 wgsize) { // copy the table into shared memory and sync [[unroll]] for (uint i = 0; i < iq2s_grid.length(); i += wgsize.x) { - if (iq2s_grid.length() % wgsize.x == 0 || i + gl_LocalInvocationIndex.x < iq2s_grid_const.length()) { - iq2s_grid[i + gl_LocalInvocationIndex.x] = iq2s_grid_const[i + gl_LocalInvocationIndex.x]; + if (iq2s_grid.length() % wgsize.x == 0 || i + gl_LocalInvocationIndex.x < iq2s_grid.length()) { + iq2s_grid[i + gl_LocalInvocationIndex.x] = iq_grid[IQ2S_GRID_OFFSET / 8 + i + gl_LocalInvocationIndex.x]; // bytes to uvec2 index } } barrier(); } -#endif -#if defined(DATA_A_IQ2_S) #define QUANT_K QUANT_K_IQ2_S #define QUANT_R QUANT_R_IQ2_S #define A_TYPE block_iq2_s #define A_TYPE_PACKED16 block_iq2_s_packed16 #endif -#endif #if defined(DATA_A_IQ3_XXS) || defined(DATA_A_IQ3_S) +layout (binding = IQ_GRID_BINDING) readonly buffer IQGrid { uint32_t iq_grid[]; }; + #if defined(DATA_A_IQ3_S) shared uint32_t iq3s_grid[512]; #else @@ -1611,43 +763,6 @@ struct block_iq3_xxs_packed16 uint16_t qs[QUANT_K_IQ3_XXS/8 + QUANT_K_IQ3_XXS/16]; }; -#if defined(DATA_A_IQ3_XXS) - -const uint32_t iq3xxs_grid_const[256] = { - 0x04040404, 0x04040414, 0x04040424, 0x04040c0c, 0x04040c1c, 0x04040c3e, 0x04041404, 0x04041414, - 0x04041c0c, 0x04042414, 0x04043e1c, 0x04043e2c, 0x040c040c, 0x040c041c, 0x040c0c04, 0x040c0c14, - 0x040c140c, 0x040c142c, 0x040c1c04, 0x040c1c14, 0x040c240c, 0x040c2c24, 0x040c3e04, 0x04140404, - 0x04140414, 0x04140424, 0x04140c0c, 0x04141404, 0x04141414, 0x04141c0c, 0x04141c1c, 0x04141c3e, - 0x04142c0c, 0x04142c3e, 0x04143e2c, 0x041c040c, 0x041c043e, 0x041c0c04, 0x041c0c14, 0x041c142c, - 0x041c3e04, 0x04240c1c, 0x04241c3e, 0x04242424, 0x04242c3e, 0x04243e1c, 0x04243e2c, 0x042c040c, - 0x042c043e, 0x042c1c14, 0x042c2c14, 0x04341c2c, 0x04343424, 0x043e0c04, 0x043e0c24, 0x043e0c34, - 0x043e241c, 0x043e340c, 0x0c04040c, 0x0c04041c, 0x0c040c04, 0x0c040c14, 0x0c04140c, 0x0c04141c, - 0x0c041c04, 0x0c041c14, 0x0c041c24, 0x0c04243e, 0x0c042c04, 0x0c0c0404, 0x0c0c0414, 0x0c0c0c0c, - 0x0c0c1404, 0x0c0c1414, 0x0c14040c, 0x0c14041c, 0x0c140c04, 0x0c140c14, 0x0c14140c, 0x0c141c04, - 0x0c143e14, 0x0c1c0404, 0x0c1c0414, 0x0c1c1404, 0x0c1c1c0c, 0x0c1c2434, 0x0c1c3434, 0x0c24040c, - 0x0c24042c, 0x0c242c04, 0x0c2c1404, 0x0c2c1424, 0x0c2c2434, 0x0c2c3e0c, 0x0c34042c, 0x0c3e1414, - 0x0c3e2404, 0x14040404, 0x14040414, 0x14040c0c, 0x14040c1c, 0x14041404, 0x14041414, 0x14041434, - 0x14041c0c, 0x14042414, 0x140c040c, 0x140c041c, 0x140c042c, 0x140c0c04, 0x140c0c14, 0x140c140c, - 0x140c1c04, 0x140c341c, 0x140c343e, 0x140c3e04, 0x14140404, 0x14140414, 0x14140c0c, 0x14140c3e, - 0x14141404, 0x14141414, 0x14141c3e, 0x14142404, 0x14142c2c, 0x141c040c, 0x141c0c04, 0x141c0c24, - 0x141c3e04, 0x141c3e24, 0x14241c2c, 0x14242c1c, 0x142c041c, 0x142c143e, 0x142c240c, 0x142c3e24, - 0x143e040c, 0x143e041c, 0x143e0c34, 0x143e242c, 0x1c04040c, 0x1c040c04, 0x1c040c14, 0x1c04140c, - 0x1c04141c, 0x1c042c04, 0x1c04342c, 0x1c043e14, 0x1c0c0404, 0x1c0c0414, 0x1c0c1404, 0x1c0c1c0c, - 0x1c0c2424, 0x1c0c2434, 0x1c14040c, 0x1c14041c, 0x1c140c04, 0x1c14142c, 0x1c142c14, 0x1c143e14, - 0x1c1c0c0c, 0x1c1c1c1c, 0x1c241c04, 0x1c24243e, 0x1c243e14, 0x1c2c0404, 0x1c2c0434, 0x1c2c1414, - 0x1c2c2c2c, 0x1c340c24, 0x1c341c34, 0x1c34341c, 0x1c3e1c1c, 0x1c3e3404, 0x24040424, 0x24040c3e, - 0x24041c2c, 0x24041c3e, 0x24042c1c, 0x24042c3e, 0x240c3e24, 0x24141404, 0x24141c3e, 0x24142404, - 0x24143404, 0x24143434, 0x241c043e, 0x241c242c, 0x24240424, 0x24242c0c, 0x24243424, 0x242c142c, - 0x242c241c, 0x242c3e04, 0x243e042c, 0x243e0c04, 0x243e0c14, 0x243e1c04, 0x2c040c14, 0x2c04240c, - 0x2c043e04, 0x2c0c0404, 0x2c0c0434, 0x2c0c1434, 0x2c0c2c2c, 0x2c140c24, 0x2c141c14, 0x2c143e14, - 0x2c1c0414, 0x2c1c2c1c, 0x2c240c04, 0x2c24141c, 0x2c24143e, 0x2c243e14, 0x2c2c0414, 0x2c2c1c0c, - 0x2c342c04, 0x2c3e1424, 0x2c3e2414, 0x34041424, 0x34042424, 0x34042434, 0x34043424, 0x340c140c, - 0x340c340c, 0x34140c3e, 0x34143424, 0x341c1c04, 0x341c1c34, 0x34242424, 0x342c042c, 0x342c2c14, - 0x34341c1c, 0x343e041c, 0x343e140c, 0x3e04041c, 0x3e04042c, 0x3e04043e, 0x3e040c04, 0x3e041c14, - 0x3e042c14, 0x3e0c1434, 0x3e0c2404, 0x3e140c14, 0x3e14242c, 0x3e142c14, 0x3e1c0404, 0x3e1c0c2c, - 0x3e1c1c1c, 0x3e1c3404, 0x3e24140c, 0x3e24240c, 0x3e2c0404, 0x3e2c0414, 0x3e2c1424, 0x3e341c04, -}; - #if defined(DATA_A_IQ3_XXS) #define NEEDS_INIT_IQ_SHMEM void init_iq_shmem(uvec3 wgsize) @@ -1655,20 +770,17 @@ void init_iq_shmem(uvec3 wgsize) // copy the table into shared memory and sync [[unroll]] for (uint i = 0; i < iq3xxs_grid.length(); i += wgsize.x) { if (iq3xxs_grid.length() % wgsize.x == 0 || i + gl_LocalInvocationIndex.x < iq3xxs_grid.length()) { - iq3xxs_grid[i + gl_LocalInvocationIndex.x] = iq3xxs_grid_const[i + gl_LocalInvocationIndex.x]; + iq3xxs_grid[i + gl_LocalInvocationIndex.x] = iq_grid[IQ3XXS_GRID_OFFSET / 4 + i + gl_LocalInvocationIndex.x]; // bytes to uint32 index } } barrier(); } -#endif -#if defined(DATA_A_IQ3_XXS) #define QUANT_K QUANT_K_IQ3_XXS #define QUANT_R QUANT_R_IQ3_XXS #define A_TYPE block_iq3_xxs #define A_TYPE_PACKED16 block_iq3_xxs_packed16 #endif -#endif #define QUANT_K_IQ3_S 256 #define QUANT_R_IQ3_S 1 @@ -1691,75 +803,6 @@ struct block_iq3_s_packed16 uint16_t scales[QUANT_K_IQ3_S/64/2]; }; -#if defined(DATA_A_IQ3_S) - -const uint32_t iq3s_grid_const[512] = { - 0x01010101, 0x01010103, 0x01010105, 0x0101010b, 0x0101010f, 0x01010301, 0x01010303, 0x01010305, - 0x01010309, 0x0101030d, 0x01010501, 0x01010503, 0x0101050b, 0x01010707, 0x01010901, 0x01010905, - 0x0101090b, 0x0101090f, 0x01010b03, 0x01010b07, 0x01010d01, 0x01010d05, 0x01010f03, 0x01010f09, - 0x01010f0f, 0x01030101, 0x01030103, 0x01030105, 0x01030109, 0x01030301, 0x01030303, 0x0103030b, - 0x01030501, 0x01030507, 0x0103050f, 0x01030703, 0x0103070b, 0x01030909, 0x01030d03, 0x01030d0b, - 0x01030f05, 0x01050101, 0x01050103, 0x0105010b, 0x0105010f, 0x01050301, 0x01050307, 0x0105030d, - 0x01050503, 0x0105050b, 0x01050701, 0x01050709, 0x01050905, 0x0105090b, 0x0105090f, 0x01050b03, - 0x01050b07, 0x01050f01, 0x01050f07, 0x01070107, 0x01070303, 0x0107030b, 0x01070501, 0x01070505, - 0x01070703, 0x01070707, 0x0107070d, 0x01070909, 0x01070b01, 0x01070b05, 0x01070d0f, 0x01070f03, - 0x01070f0b, 0x01090101, 0x01090307, 0x0109030f, 0x01090503, 0x01090509, 0x01090705, 0x01090901, - 0x01090907, 0x01090b03, 0x01090f01, 0x010b0105, 0x010b0109, 0x010b0501, 0x010b0505, 0x010b050d, - 0x010b0707, 0x010b0903, 0x010b090b, 0x010b090f, 0x010b0d0d, 0x010b0f07, 0x010d010d, 0x010d0303, - 0x010d0307, 0x010d0703, 0x010d0b05, 0x010d0f03, 0x010f0101, 0x010f0105, 0x010f0109, 0x010f0501, - 0x010f0505, 0x010f050d, 0x010f0707, 0x010f0b01, 0x010f0b09, 0x03010101, 0x03010103, 0x03010105, - 0x03010109, 0x03010301, 0x03010303, 0x03010307, 0x0301030b, 0x0301030f, 0x03010501, 0x03010505, - 0x03010703, 0x03010709, 0x0301070d, 0x03010b09, 0x03010b0d, 0x03010d03, 0x03010f05, 0x03030101, - 0x03030103, 0x03030107, 0x0303010d, 0x03030301, 0x03030309, 0x03030503, 0x03030701, 0x03030707, - 0x03030903, 0x03030b01, 0x03030b05, 0x03030f01, 0x03030f0d, 0x03050101, 0x03050305, 0x0305030b, - 0x0305030f, 0x03050501, 0x03050509, 0x03050705, 0x03050901, 0x03050907, 0x03050b0b, 0x03050d01, - 0x03050f05, 0x03070103, 0x03070109, 0x0307010f, 0x03070301, 0x03070307, 0x03070503, 0x0307050f, - 0x03070701, 0x03070709, 0x03070903, 0x03070d05, 0x03070f01, 0x03090107, 0x0309010b, 0x03090305, - 0x03090309, 0x03090703, 0x03090707, 0x03090905, 0x0309090d, 0x03090b01, 0x03090b09, 0x030b0103, - 0x030b0301, 0x030b0307, 0x030b0503, 0x030b0701, 0x030b0705, 0x030b0b03, 0x030d0501, 0x030d0509, - 0x030d050f, 0x030d0909, 0x030d090d, 0x030f0103, 0x030f0107, 0x030f0301, 0x030f0305, 0x030f0503, - 0x030f070b, 0x030f0903, 0x030f0d05, 0x030f0f01, 0x05010101, 0x05010103, 0x05010107, 0x0501010b, - 0x0501010f, 0x05010301, 0x05010305, 0x05010309, 0x0501030d, 0x05010503, 0x05010507, 0x0501050f, - 0x05010701, 0x05010705, 0x05010903, 0x05010907, 0x0501090b, 0x05010b01, 0x05010b05, 0x05010d0f, - 0x05010f01, 0x05010f07, 0x05010f0b, 0x05030101, 0x05030105, 0x05030301, 0x05030307, 0x0503030f, - 0x05030505, 0x0503050b, 0x05030703, 0x05030709, 0x05030905, 0x05030b03, 0x05050103, 0x05050109, - 0x0505010f, 0x05050503, 0x05050507, 0x05050701, 0x0505070f, 0x05050903, 0x05050b07, 0x05050b0f, - 0x05050f03, 0x05050f09, 0x05070101, 0x05070105, 0x0507010b, 0x05070303, 0x05070505, 0x05070509, - 0x05070703, 0x05070707, 0x05070905, 0x05070b01, 0x05070d0d, 0x05090103, 0x0509010f, 0x05090501, - 0x05090507, 0x05090705, 0x0509070b, 0x05090903, 0x05090f05, 0x05090f0b, 0x050b0109, 0x050b0303, - 0x050b0505, 0x050b070f, 0x050b0901, 0x050b0b07, 0x050b0f01, 0x050d0101, 0x050d0105, 0x050d010f, - 0x050d0503, 0x050d0b0b, 0x050d0d03, 0x050f010b, 0x050f0303, 0x050f050d, 0x050f0701, 0x050f0907, - 0x050f0b01, 0x07010105, 0x07010303, 0x07010307, 0x0701030b, 0x0701030f, 0x07010505, 0x07010703, - 0x07010707, 0x0701070b, 0x07010905, 0x07010909, 0x0701090f, 0x07010b03, 0x07010d07, 0x07010f03, - 0x07030103, 0x07030107, 0x0703010b, 0x07030309, 0x07030503, 0x07030507, 0x07030901, 0x07030d01, - 0x07030f05, 0x07030f0d, 0x07050101, 0x07050305, 0x07050501, 0x07050705, 0x07050709, 0x07050b01, - 0x07070103, 0x07070301, 0x07070309, 0x07070503, 0x07070507, 0x0707050f, 0x07070701, 0x07070903, - 0x07070907, 0x0707090f, 0x07070b0b, 0x07070f07, 0x07090107, 0x07090303, 0x0709030d, 0x07090505, - 0x07090703, 0x07090b05, 0x07090d01, 0x07090d09, 0x070b0103, 0x070b0301, 0x070b0305, 0x070b050b, - 0x070b0705, 0x070b0909, 0x070b0b0d, 0x070b0f07, 0x070d030d, 0x070d0903, 0x070f0103, 0x070f0107, - 0x070f0501, 0x070f0505, 0x070f070b, 0x09010101, 0x09010109, 0x09010305, 0x09010501, 0x09010509, - 0x0901050f, 0x09010705, 0x09010903, 0x09010b01, 0x09010f01, 0x09030105, 0x0903010f, 0x09030303, - 0x09030307, 0x09030505, 0x09030701, 0x0903070b, 0x09030907, 0x09030b03, 0x09030b0b, 0x09050103, - 0x09050107, 0x09050301, 0x0905030b, 0x09050503, 0x09050707, 0x09050901, 0x09050b0f, 0x09050d05, - 0x09050f01, 0x09070109, 0x09070303, 0x09070307, 0x09070501, 0x09070505, 0x09070703, 0x0907070b, - 0x09090101, 0x09090105, 0x09090509, 0x0909070f, 0x09090901, 0x09090f03, 0x090b010b, 0x090b010f, - 0x090b0503, 0x090b0d05, 0x090d0307, 0x090d0709, 0x090d0d01, 0x090f0301, 0x090f030b, 0x090f0701, - 0x090f0907, 0x090f0b03, 0x0b010105, 0x0b010301, 0x0b010309, 0x0b010505, 0x0b010901, 0x0b010909, - 0x0b01090f, 0x0b010b05, 0x0b010d0d, 0x0b010f09, 0x0b030103, 0x0b030107, 0x0b03010b, 0x0b030305, - 0x0b030503, 0x0b030705, 0x0b030f05, 0x0b050101, 0x0b050303, 0x0b050507, 0x0b050701, 0x0b05070d, - 0x0b050b07, 0x0b070105, 0x0b07010f, 0x0b070301, 0x0b07050f, 0x0b070909, 0x0b070b03, 0x0b070d0b, - 0x0b070f07, 0x0b090103, 0x0b090109, 0x0b090501, 0x0b090705, 0x0b09090d, 0x0b0b0305, 0x0b0b050d, - 0x0b0b0b03, 0x0b0b0b07, 0x0b0d0905, 0x0b0f0105, 0x0b0f0109, 0x0b0f0505, 0x0d010303, 0x0d010307, - 0x0d01030b, 0x0d010703, 0x0d010707, 0x0d010d01, 0x0d030101, 0x0d030501, 0x0d03050f, 0x0d030d09, - 0x0d050305, 0x0d050709, 0x0d050905, 0x0d050b0b, 0x0d050d05, 0x0d050f01, 0x0d070101, 0x0d070309, - 0x0d070503, 0x0d070901, 0x0d09050b, 0x0d090907, 0x0d090d05, 0x0d0b0101, 0x0d0b0107, 0x0d0b0709, - 0x0d0b0d01, 0x0d0d010b, 0x0d0d0901, 0x0d0f0303, 0x0d0f0307, 0x0f010101, 0x0f010109, 0x0f01010f, - 0x0f010501, 0x0f010505, 0x0f01070d, 0x0f010901, 0x0f010b09, 0x0f010d05, 0x0f030105, 0x0f030303, - 0x0f030509, 0x0f030907, 0x0f03090b, 0x0f050103, 0x0f050109, 0x0f050301, 0x0f05030d, 0x0f050503, - 0x0f050701, 0x0f050b03, 0x0f070105, 0x0f070705, 0x0f07070b, 0x0f070b07, 0x0f090103, 0x0f09010b, - 0x0f090307, 0x0f090501, 0x0f090b01, 0x0f0b0505, 0x0f0b0905, 0x0f0d0105, 0x0f0d0703, 0x0f0f0101, -}; - #if defined(DATA_A_IQ3_S) #define NEEDS_INIT_IQ_SHMEM void init_iq_shmem(uvec3 wgsize) @@ -1767,20 +810,17 @@ void init_iq_shmem(uvec3 wgsize) // copy the table into shared memory and sync [[unroll]] for (uint i = 0; i < iq3s_grid.length(); i += wgsize.x) { if (iq3s_grid.length() % wgsize.x == 0 || i + gl_LocalInvocationIndex.x < iq3s_grid.length()) { - iq3s_grid[i + gl_LocalInvocationIndex.x] = iq3s_grid_const[i + gl_LocalInvocationIndex.x]; + iq3s_grid[i + gl_LocalInvocationIndex.x] = iq_grid[IQ3S_GRID_OFFSET / 4 + i + gl_LocalInvocationIndex.x]; // bytes to uint32 index } } barrier(); } -#endif -#if defined(DATA_A_IQ3_S) #define QUANT_K QUANT_K_IQ3_S #define QUANT_R QUANT_R_IQ3_S #define A_TYPE block_iq3_s #define A_TYPE_PACKED16 block_iq3_s_packed16 #endif -#endif #define QUANT_K_IQ4_XS 256 #define QUANT_R_IQ4_XS 1 From 6d0716cff4966cb587c758b1c1baec13ee950fcd Mon Sep 17 00:00:00 2001 From: Pascal Date: Tue, 1 Dec 2026 15:43:55 +0100 Subject: [PATCH 268/275] gguf: document and test the NUL byte rule for keys and tensor names (#33443) State in the format description at the top of gguf.h that keys and tensor names must not contain null bytes while string values can. Add handcrafted test cases for both: a key with an embedded NUL placed before the key it would shadow, and tensor names that only differ after a NUL. Both files are now expected to be rejected. --- ggml/include/gguf.h | 1 + tests/test-gguf.cpp | 16 ++++++++++++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/ggml/include/gguf.h b/ggml/include/gguf.h index b3a1e1230a06..7423d3fcce66 100644 --- a/ggml/include/gguf.h +++ b/ggml/include/gguf.h @@ -24,6 +24,7 @@ // 7. The tensor data binary blob (optional, aligned). // // Strings are serialized as the string length (uint64_t) followed by the C string without the null terminator. +// Keys and tensor names must not contain null bytes, string values can. // All enums are stored as int32_t. // All bool values are stored as int8_t. // If the special key "general.alignment" (uint32_t) is defined it is used for alignment, diff --git a/tests/test-gguf.cpp b/tests/test-gguf.cpp index 6c63ecaeb4d7..f011710763bc 100644 --- a/tests/test-gguf.cpp +++ b/tests/test-gguf.cpp @@ -30,6 +30,7 @@ enum handcrafted_file_type { HANDCRAFTED_KV_BAD_TYPE = 20 + offset_has_kv, // HANDCRAFTED_KV_BAD_VALUE_SIZE = 30 + offset_has_kv, // removed because it can result in allocations > 1 TB (default sanitizer limit) HANDCRAFTED_KV_DUPLICATE_KEY = 40 + offset_has_kv, + HANDCRAFTED_KV_NUL_KEY = 45 + offset_has_kv, HANDCRAFTED_KV_BAD_ALIGN = 50 + offset_has_kv, HANDCRAFTED_KV_WRONG_TYPE_ALIGN = 55 + offset_has_kv, HANDCRAFTED_KV_SUCCESS = 800 + offset_has_kv, @@ -44,6 +45,7 @@ enum handcrafted_file_type { HANDCRAFTED_TENSORS_BAD_TYPE = 50 + offset_has_tensors, HANDCRAFTED_TENSORS_BAD_OFFSET = 60 + offset_has_tensors, HANDCRAFTED_TENSORS_DUPLICATE_NAME = 70 + offset_has_tensors, + HANDCRAFTED_TENSORS_NUL_NAME = 72 + offset_has_tensors, HANDCRAFTED_TENSORS_BAD_ALIGN = 75 + offset_has_tensors, HANDCRAFTED_TENSORS_INCONSISTENT_ALIGN = 80 + offset_has_tensors, HANDCRAFTED_TENSORS_SUCCESS = 800 + offset_has_tensors, @@ -71,6 +73,7 @@ static std::string handcrafted_file_type_name(const enum handcrafted_file_type h case HANDCRAFTED_KV_EMPTY_KEY: return "KV_EMPTY_KEY"; case HANDCRAFTED_KV_BAD_TYPE: return "KV_BAD_TYPE"; case HANDCRAFTED_KV_DUPLICATE_KEY: return "KV_DUPLICATE_KEY"; + case HANDCRAFTED_KV_NUL_KEY: return "KV_NUL_KEY"; case HANDCRAFTED_KV_BAD_ALIGN: return "KV_BAD_ALIGN"; case HANDCRAFTED_KV_WRONG_TYPE_ALIGN: return "KV_WRONG_TYPE_ALIGN"; case HANDCRAFTED_KV_SUCCESS: return "KV_RANDOM_KV"; @@ -85,6 +88,7 @@ static std::string handcrafted_file_type_name(const enum handcrafted_file_type h case HANDCRAFTED_TENSORS_BAD_TYPE: return "TENSORS_BAD_TYPE"; case HANDCRAFTED_TENSORS_BAD_OFFSET: return "TENSORS_BAD_OFFSET"; case HANDCRAFTED_TENSORS_DUPLICATE_NAME: return "TENSORS_DUPLICATE_NAME"; + case HANDCRAFTED_TENSORS_NUL_NAME: return "TENSORS_NUL_NAME"; case HANDCRAFTED_TENSORS_BAD_ALIGN: return "TENSORS_BAD_ALIGN"; case HANDCRAFTED_TENSORS_INCONSISTENT_ALIGN: return "TENSORS_INCONSISTENT_ALIGN"; case HANDCRAFTED_TENSORS_SUCCESS: return "TENSORS_SUCCESS"; @@ -302,9 +306,12 @@ static FILE * get_handcrafted_file(const unsigned int seed, const enum handcraft const enum gguf_type type = gguf_type(hft == HANDCRAFTED_KV_BAD_TYPE ? GGUF_TYPE_COUNT : kv_types[i].first); const enum gguf_type type_arr = gguf_type(hft == HANDCRAFTED_KV_BAD_TYPE ? GGUF_TYPE_COUNT : kv_types[i].second); - const std::string key = hft == HANDCRAFTED_KV_EMPTY_KEY + std::string key = hft == HANDCRAFTED_KV_EMPTY_KEY ? "" - : "my_key_" + std::to_string((hft == HANDCRAFTED_KV_DUPLICATE_KEY ? i/2 : i)); + : "my_key_" + std::to_string((hft == HANDCRAFTED_KV_DUPLICATE_KEY || hft == HANDCRAFTED_KV_NUL_KEY ? i/2 : i)); + if (hft == HANDCRAFTED_KV_NUL_KEY && i % 2 == 0) { + key += std::string("\0x", 2); + } if (hft == HANDCRAFTED_KV_BAD_KEY_SIZE) { const uint64_t n = -1; @@ -401,6 +408,9 @@ static FILE * get_handcrafted_file(const unsigned int seed, const enum handcraft const std::array shape = tensor_configs[i].second; std::string name = "my_tensor"; + if (hft == HANDCRAFTED_TENSORS_NUL_NAME) { + name += '\0'; + } if (hft != HANDCRAFTED_TENSORS_DUPLICATE_NAME) { name += "_" + std::to_string(i); } @@ -773,6 +783,7 @@ static std::pair test_handcrafted_file(const unsigned int seed) { HANDCRAFTED_KV_EMPTY_KEY, HANDCRAFTED_KV_BAD_TYPE, HANDCRAFTED_KV_DUPLICATE_KEY, + HANDCRAFTED_KV_NUL_KEY, HANDCRAFTED_KV_BAD_ALIGN, HANDCRAFTED_KV_WRONG_TYPE_ALIGN, HANDCRAFTED_KV_SUCCESS, @@ -787,6 +798,7 @@ static std::pair test_handcrafted_file(const unsigned int seed) { HANDCRAFTED_TENSORS_BAD_TYPE, HANDCRAFTED_TENSORS_BAD_OFFSET, HANDCRAFTED_TENSORS_DUPLICATE_NAME, + HANDCRAFTED_TENSORS_NUL_NAME, HANDCRAFTED_TENSORS_BAD_ALIGN, HANDCRAFTED_TENSORS_INCONSISTENT_ALIGN, HANDCRAFTED_TENSORS_SUCCESS, From 30b900181be8193ff2e5267a28e9259eba5d1b0c Mon Sep 17 00:00:00 2001 From: ErsongWang <158176536+ErsongWang@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:47:26 +0800 Subject: [PATCH 269/275] CUDA/HIP: Use the MMA FA kernel for maskless attention on RDNA (#32930) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * CUDA/HIP: Use the MMA FA kernel for maskless attention on RDNA Vision encoders commonly use non-causal, maskless attention. On RDNA GPUs, the MMA kernel runs faster than the tile kernel for this workload. However, the current AMD MMA path is only selected for GQA-optimized attention. Enable the wide MMA kernel (`ncols1 = 64`, `ncols2 = 1`) for maskless attention when `n_queries >= 128` on all AMD GPUs that support WMMA. Assisted-by: GitHub Copilot * Remove extra tests Co-authored-by: Johannes Gäßler * CUDA: fix ALiBi slope in RDNA3 mma FA kernel Assisted-by: GitHub Copilot --------- Co-authored-by: uvos Co-authored-by: Johannes Gäßler --- ggml/src/ggml-cuda/fattn-mma-f16.cuh | 4 ++-- ggml/src/ggml-cuda/fattn.cu | 6 ++++++ tests/test-backend-ops.cpp | 2 ++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-mma-f16.cuh b/ggml/src/ggml-cuda/fattn-mma-f16.cuh index 8c0e9328c2a6..2cc338195ff1 100644 --- a/ggml/src/ggml-cuda/fattn-mma-f16.cuh +++ b/ggml/src/ggml-cuda/fattn-mma-f16.cuh @@ -754,7 +754,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( const int i = i0 + T_C_KQ::get_j(l); const int j = ((threadIdx.y / np)*cols_per_warp + T_C_KQ::get_i(l)) / ncols2; - KQ_C[i00/(np*T_C_KQ::J)].x[l] += __half2float(tile_mask[j*(nbatch_fa + 8) + i]); + KQ_C[i00/(np*T_C_KQ::J)].x[l] += slope*__half2float(tile_mask[j*(nbatch_fa + 8) + i]); } #else #pragma unroll @@ -1913,7 +1913,7 @@ static __global__ void flash_attn_ext_f16( #endif // __CUDA_ARCH__ == GGML_CUDA_CC_TURING #if defined(AMD_WMMA_AVAILABLE) - if (ncols1*ncols2 < 16 || ncols2 == 1 || DKQ > 256) { + if (ncols1*ncols2 < 16 || DKQ > 256) { NO_DEVICE_CODE; return; } diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 3f2fb0193447..f19ed620357a 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -860,6 +860,12 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const return BEST_FATTN_KERNEL_MMA_F16; } + // Mask-less attention with many queries (e.g. vision encoders) cannot use the GQA tiles above. + // The WMMA kernel is still much faster than the tile kernel for this case: + if (amd_wmma_available(cc) && !mask && Q->ne[0] <= 256 && Q->ne[1] >= 128) { + return BEST_FATTN_KERNEL_MMA_F16; + } + // If there are no tensor cores available, use the generic tile kernel: if (can_use_vector_kernel) { if (!ggml_is_quantized(K->type) && !ggml_is_quantized(V->type)) { diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 5136668ff58c..648cf98d4d33 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -16067,6 +16067,8 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_flash_attn_ext(72, 72, 16, {1, 1}, 5776, 5776, false, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16)); // Same non-causal vision-encoder shape for the other head size padded in-kernel by the CUDA MMA kernels test_cases.emplace_back(new test_flash_attn_ext(40, 40, 16, {1, 1}, 5776, 5776, false, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16)); + // Same for the Qwen2.5-VL head size + test_cases.emplace_back(new test_flash_attn_ext(80, 80, 16, {1, 1}, 4096, 4096, false, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16)); // GCN sparse attention break-even for multiple query tokens. for (int64_t kv : {16384, 32768, 65536}) { From 06fa894b15f744d952df69357d4d2591cddac0d3 Mon Sep 17 00:00:00 2001 From: Niklas Wenzel Date: Tue, 1 Dec 2026 15:48:04 +0100 Subject: [PATCH 270/275] metal : detect Neural Accelerators without hardcoding chips (#33272) So that applications built with today's version of llama.cpp will properly use the tensor API on chips released in the future without requiring a llama.cpp update. --- ggml/src/ggml-metal/ggml-metal-device.m | 49 ++++++++++++++++--------- 1 file changed, 31 insertions(+), 18 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index e87187a12437..50e8fd938282 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -28,6 +28,9 @@ static const NSInteger MTLGPUFamilyMetal3_GGML = 5001; static const NSInteger MTLGPUFamilyMetal4_GGML = 5002; +// overload of MTLGPUFamilyAppleX (not available in some environments) +static const NSInteger MTLGPUFamilyApple10_GGML = 1010; + // MTLLanguageVersion4_0 is not present in older SDKs static const NSUInteger MTLLanguageVersion4_0_GGML = 4 << 16; @@ -1109,6 +1112,33 @@ static enum ggml_metal_device_id ggml_metal_device_id_parse(const char * name) { return "GGML_METAL_DEVICE_GENERIC"; } +static bool ggml_metal_has_tensor(id device) { + if (![device supportsFamily:MTLGPUFamilyMetal4_GGML]) { + return false; + } + + if (getenv("GGML_METAL_TENSOR_DISABLE") != NULL) { + return false; + } + + if (getenv("GGML_METAL_TENSOR_ENABLE") != NULL) { + return true; + } + + // enable the tensor API by default for M5+ and A19+ + // disable it for older chips because with the current implementation it is not useful + // - M2 Ultra: ~5% slower + // - M4, M4 Max: no significant difference + // + // TODO: try to update the tensor API kernels to at least match the simdgroup performance + if ([device supportsFamily:MTLGPUFamilyApple10_GGML]) { + return true; + } + + GGML_LOG_INFO("%s: tensor API disabled for pre-M5 and pre-A19 devices\n", __func__); + return false; +} + ggml_metal_device_t ggml_metal_device_init(int device, int n_devices) { ggml_metal_device_t dev = calloc(1, sizeof(struct ggml_metal_device)); @@ -1145,24 +1175,7 @@ ggml_metal_device_t ggml_metal_device_init(int device, int n_devices) { dev->props.has_bfloat = false; } - dev->props.has_tensor = [dev->mtl_device supportsFamily:MTLGPUFamilyMetal4_GGML]; - if (getenv("GGML_METAL_TENSOR_DISABLE") != NULL) { - dev->props.has_tensor = false; - } - - // note: disable the tensor API by default for old chips because with the current implementation it is not useful - // - M2 Ultra: ~5% slower - // - M4, M4 Max: no significant difference - // - // TODO: try to update the tensor API kernels to at least match the simdgroup performance - if (getenv("GGML_METAL_TENSOR_ENABLE") == NULL && - ![[dev->mtl_device name] containsString:@"M5"] && - ![[dev->mtl_device name] containsString:@"M6"] && - ![[dev->mtl_device name] containsString:@"A19"] && - ![[dev->mtl_device name] containsString:@"A20"]) { - GGML_LOG_INFO("%s: tensor API disabled for pre-M5 and pre-A19 devices\n", __func__); - dev->props.has_tensor = false; - } + dev->props.has_tensor = ggml_metal_has_tensor(dev->mtl_device); // double-check that the tensor API compiles if (dev->props.has_tensor) { From 94524527648367390024e2b48d29cd7b1dd417db Mon Sep 17 00:00:00 2001 From: Marin Radic Date: Tue, 1 Dec 2026 16:24:37 +0100 Subject: [PATCH 271/275] ggml-et : fix multi-line L2 flush and replace L2-SCP polling with FCC 0 (#33313) FlushVA encodes numlines - 1 in 4 bits (max 16 lines), so the 32-line Q4_0 panel flush in mul_mat_Q4_0_matrix_engine silently dropped lines 16..31. Add flush_to_l2_multi() in platform.h to chunk flushes by 16. L2-SCP also persists across kernel launches, so ready_ctr/consumed_ctr polling in mul_mat_Q4_0_matrix_engine and mul_mat_f16_matrix_engine raced at entry and could corrupt results or deadlock. Replace the L2-SCP counters with FCC 0 semaphores (et_sem_post/et_sem_wait) plus hart 1 exit credit drain (matching flash_attn_ext_f16_me.c), which avoids FLB 0 aliasing with uberkernel barriers and improves Q4_0 4096x512x14336 throughput from 632.9 to 668.1 GFLOPS (+5.6%). Assisted-by: Antigravity --- .../src/mul_mat_Q4_0_matrix_engine.c | 59 +++++------------ .../src/mul_mat_f16_matrix_engine.c | 63 +++++-------------- ggml/src/ggml-et/et-kernels/src/platform.h | 17 +++++ 3 files changed, 51 insertions(+), 88 deletions(-) diff --git a/ggml/src/ggml-et/et-kernels/src/mul_mat_Q4_0_matrix_engine.c b/ggml/src/ggml-et/et-kernels/src/mul_mat_Q4_0_matrix_engine.c index 28a10303235a..762760c7284b 100644 --- a/ggml/src/ggml-et/et-kernels/src/mul_mat_Q4_0_matrix_engine.c +++ b/ggml/src/ggml-et/et-kernels/src/mul_mat_Q4_0_matrix_engine.c @@ -25,32 +25,11 @@ #define A_L1_START 0 // L1 SCP lines 0..15 for A (activations) #define B_L1_START 16 // L1 SCP lines 16..31 for B (dequantized weights) -// L2 SCP layout per minion (double-buffered dequant panel + sync counters). +// L2 SCP layout per minion (double-buffered dequant panel). // panel = BLOCK_K k-lines x TILE_M m (FP32) = 32 * 64 = 2048 bytes, in TenB // [k][m] order: panel[k*TILE_M + m]. -#define SCP_PANEL_SIZE (BLOCK_K * TILE_M * (uint64_t) sizeof(float)) // 2048 -#define SCP_READY_OFF (2 * SCP_PANEL_SIZE) // 4096 -#define SCP_CONSUMED_OFF (SCP_READY_OFF + 64) // 4160 -#define SCP_PER_MINION (SCP_CONSUMED_OFF + 64) // 4224 - -// Signal a counter value to the other hart via L2 SCP. -static inline void __attribute__((always_inline)) scp_signal(volatile uint32_t * flag, uint32_t value) { - *flag = value; - FENCE; - evict_to_l2((const void *) flag, 1, 64); - WAIT_CACHEOPS; -} - -// Wait for a counter in L2 SCP to reach the expected value. -static inline void __attribute__((always_inline)) scp_wait(volatile uint32_t * flag, uint32_t expected) { - while (1) { - evict_to_l2((const void *) flag, 1, 64); - WAIT_CACHEOPS; - if (*flag >= expected) { - return; - } - } -} +#define SCP_PANEL_SIZE (BLOCK_K * TILE_M * (uint64_t) sizeof(float)) // 2048 +#define SCP_PER_MINION (2 * SCP_PANEL_SIZE) // 4096 // Dequantize one 32-element Q4_0 block of TILE_M weight rows into the FP32 // panel, written directly in TenB [k][m] order: panel[k*TILE_M + m]. @@ -192,22 +171,17 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { const int64_t kb_start = k_split * k_steps_per_split; // first block const int64_t kb_end = kb_start + k_steps_per_split; // one past last - // L2 SCP pointers for this minion's double-buffered panels + sync. + // L2 SCP pointers for this minion's double-buffered panels. uint64_t scp_base = local_minion * SCP_PER_MINION; float * scp_panel[2] = { (float *) et_shire_l2scp_local(scp_base), (float *) et_shire_l2scp_local(scp_base + SCP_PANEL_SIZE), }; - volatile uint32_t * ready_ctr = (volatile uint32_t *) et_shire_l2scp_local(scp_base + SCP_READY_OFF); - volatile uint32_t * consumed_ctr = (volatile uint32_t *) et_shire_l2scp_local(scp_base + SCP_CONSUMED_OFF); // ================================================================ // Hart 1: Q4_0 weight dequant producer // ================================================================ if (is_hart1) { - scp_signal(ready_ctr, 0); - scp_signal(consumed_ctr, 0); - uint32_t chunk_id = 0; for (int64_t tile = (int64_t) shire_id + local_tile_idx * NUM_COMPUTE_SHIRES; tile < base_tiles; @@ -229,22 +203,28 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { for (int64_t kb = kb_start; kb < kb_end; ++kb) { int buf = chunk_id & 1; - // Back-pressure: wait for hart 0 to finish with this buffer. + // Back-pressure via FCC 0 (avoids FLB 0 aliasing with uberkernel barriers). if (chunk_id >= 2) { - scp_wait(consumed_ctr, chunk_id - 1); + et_sem_wait(ET_BARRIER_MINION); } dequant_q4_0_panel(scp_panel[buf], src0_batch, mb, kb, nb1_0); FENCE; - flush_to_l2(scp_panel[buf], BLOCK_K, 64); + flush_to_l2_multi(scp_panel[buf], BLOCK_K, 64); WAIT_CACHEOPS; + et_sem_post(ET_BARRIER_MINION); chunk_id++; - scp_signal(ready_ctr, chunk_id); } } + // Drain the up to 2 unconsumed FCC 0 credits from the wait-skip on chunks 0 and 1. + uint32_t drain = (chunk_id < 2) ? chunk_id : 2; + for (uint32_t d = 0; d < drain; ++d) { + et_sem_wait(ET_BARRIER_MINION); + } + FENCE; return 0; } @@ -261,11 +241,6 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { #endif CLEAR_TENSOR_ERROR; - evict_to_l2((const void *) ready_ctr, 1, 64); - WAIT_CACHEOPS; - evict_to_l2((const void *) consumed_ctr, 1, 64); - WAIT_CACHEOPS; - uint32_t chunk_id = 0; for (int64_t tile = (int64_t) shire_id + local_tile_idx * NUM_COMPUTE_SHIRES; tile < base_tiles; @@ -307,8 +282,7 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { int buf = chunk_id & 1; // Wait for hart 1 to finish dequantizing this block. - chunk_id++; - scp_wait(ready_ctr, chunk_id); + et_sem_wait(ET_BARRIER_MINION); // Two FMA passes over the 32-wide block (16 K-cols each). for (int half = 0; half < 2; ++half) { @@ -337,7 +311,8 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { } // Signal that this buffer is free for hart 1 to reuse. - scp_signal(consumed_ctr, chunk_id); + et_sem_post(ET_BARRIER_MINION); + chunk_id++; } // K-split ring reduce. diff --git a/ggml/src/ggml-et/et-kernels/src/mul_mat_f16_matrix_engine.c b/ggml/src/ggml-et/et-kernels/src/mul_mat_f16_matrix_engine.c index 2aab87ad5e52..25e6a27f9985 100644 --- a/ggml/src/ggml-et/et-kernels/src/mul_mat_f16_matrix_engine.c +++ b/ggml/src/ggml-et/et-kernels/src/mul_mat_f16_matrix_engine.c @@ -10,7 +10,7 @@ // Hart 0: tensor engine (load A, load B from SCP, FMA, reduce, store) // Hart 1: pack B into double-buffered L2 SCP panels, flush for tensor_load // -// Sync: monotonic counters in L2 SCP with evict-based coherency. +// Sync: FCC 0 semaphores (et_sem_post / et_sem_wait). // Double-buffered bpanel allows pack/FMA overlap. // #define NUM_COMPUTE_SHIRES 32 @@ -28,34 +28,11 @@ typedef uint16_t et_fp16_t; -// L2 SCP layout per minion (double-buffered bpanel + sync counters) +// L2 SCP layout per minion (double-buffered bpanel) // [0..1023] bpanel buffer 0 (16 lines x 64 bytes) // [1024..2047] bpanel buffer 1 -// [2048..2111] ready counter (hart1 -> hart0, own cache line) -// [2112..2175] consumed counter (hart0 -> hart1, own cache line) -#define SCP_BPANEL_SIZE (16 * 32 * sizeof(et_fp16_t)) // 1024 bytes -#define SCP_READY_OFF (2 * SCP_BPANEL_SIZE) // 2048 -#define SCP_CONSUMED_OFF (SCP_READY_OFF + 64) // 2112 -#define SCP_PER_MINION (SCP_CONSUMED_OFF + 64) // 2176 - -// Signal a counter value to the other hart via L2 SCP. -static inline void __attribute__((always_inline)) scp_signal(volatile uint32_t * flag, uint32_t value) { - *flag = value; - FENCE; - evict_to_l2((const void *) flag, 1, 64); - WAIT_CACHEOPS; -} - -// Wait for a counter in L2 SCP to reach the expected value. -static inline void __attribute__((always_inline)) scp_wait(volatile uint32_t * flag, uint32_t expected) { - while (1) { - evict_to_l2((const void *) flag, 1, 64); - WAIT_CACHEOPS; - if (*flag >= expected) { - return; - } - } -} +#define SCP_BPANEL_SIZE (16 * 32 * sizeof(et_fp16_t)) // 1024 bytes +#define SCP_PER_MINION (2 * SCP_BPANEL_SIZE) // 2048 bytes /** * Build the interleaved B panel that TensorFMA16A32 expects (vectorized). @@ -170,23 +147,17 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { const int64_t k_start = k_split * k_steps_per_split * TILE_K; const int64_t k_end = k_start + k_steps_per_split * TILE_K; - // L2 SCP pointers for this minion's double-buffered panels + sync + // L2 SCP pointers for this minion's double-buffered panels uint64_t scp_base = local_minion * SCP_PER_MINION; et_fp16_t * scp_bp[2] = { (et_fp16_t *) et_shire_l2scp_local(scp_base), (et_fp16_t *) et_shire_l2scp_local(scp_base + SCP_BPANEL_SIZE), }; - volatile uint32_t * ready_ctr = (volatile uint32_t *) et_shire_l2scp_local(scp_base + SCP_READY_OFF); - volatile uint32_t * consumed_ctr = (volatile uint32_t *) et_shire_l2scp_local(scp_base + SCP_CONSUMED_OFF); // ================================================================ // Hart 1: B-panel packer // ================================================================ if (is_hart1) { - // Initialize sync counters - scp_signal(ready_ctr, 0); - scp_signal(consumed_ctr, 0); - uint32_t chunk_id = 0; for (int64_t tile = (int64_t) shire_id + local_tile_idx * NUM_COMPUTE_SHIRES; tile < base_tiles; @@ -208,9 +179,9 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { for (int64_t kb = k_start; kb < k_end; kb += TILE_K) { int buf = chunk_id & 1; - // Back-pressure: wait for hart 0 to finish with this buffer + // Back-pressure via FCC 0 (avoids FLB 0 aliasing with uberkernel barriers). if (chunk_id >= 2) { - scp_wait(consumed_ctr, chunk_id - 1); + et_sem_wait(ET_BARRIER_MINION); } pack_b_interleaved(scp_bp[buf], src0_batch, mb, kb, nb1_0); @@ -219,11 +190,17 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { flush_to_l2(scp_bp[buf], 16, 64); WAIT_CACHEOPS; + et_sem_post(ET_BARRIER_MINION); chunk_id++; - scp_signal(ready_ctr, chunk_id); } } + // Drain the up to 2 unconsumed FCC 0 credits from the wait-skip on chunks 0 and 1. + uint32_t drain = (chunk_id < 2) ? chunk_id : 2; + for (uint32_t d = 0; d < drain; ++d) { + et_sem_wait(ET_BARRIER_MINION); + } + FENCE; return 0; } @@ -240,12 +217,6 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { #endif CLEAR_TENSOR_ERROR; - // Evict any stale L1D copies of sync counters - evict_to_l2((const void *) ready_ctr, 1, 64); - WAIT_CACHEOPS; - evict_to_l2((const void *) consumed_ctr, 1, 64); - WAIT_CACHEOPS; - uint32_t chunk_id = 0; for (int64_t tile = (int64_t) shire_id + local_tile_idx * NUM_COMPUTE_SHIRES; tile < base_tiles; @@ -282,8 +253,7 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { (uint64_t) nb1_1, 0); // Wait for hart 1 to finish packing this chunk - chunk_id++; - scp_wait(ready_ctr, chunk_id); + et_sem_wait(ET_BARRIER_MINION); // Load B from L2 SCP (hart 1 already flushed it) tensor_load(false, false, B_L1_START, TENSOR_LOAD_PLAIN, 0, (uint64_t) scp_bp[buf], 0, 15, 64, 1); @@ -298,7 +268,8 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { tensor_wait(TENSOR_FMA_WAIT); // Signal that this buffer is free for hart 1 to reuse - scp_signal(consumed_ctr, chunk_id); + et_sem_post(ET_BARRIER_MINION); + chunk_id++; } // K-split ring reduce diff --git a/ggml/src/ggml-et/et-kernels/src/platform.h b/ggml/src/ggml-et/et-kernels/src/platform.h index cbec4c98d741..2ea9592a394c 100644 --- a/ggml/src/ggml-et/et-kernels/src/platform.h +++ b/ggml/src/ggml-et/et-kernels/src/platform.h @@ -476,6 +476,23 @@ static inline void __attribute__((always_inline)) flush_to_l2(const void * addr, : "x31", "memory"); } +// Flush any number of cache lines to L2 in 16-line chunks (FlushVA hardware cap). +static inline void __attribute__((always_inline)) flush_to_l2_multi(const void * addr, + uint64_t nlines, + uint64_t stride) { + const char * p = (const char *) addr; + const uint64_t step = stride & 0xFFFFFFFFFFC0ULL; + + while (nlines > 16) { + flush_to_l2(p, 16, step); + p += 16 * step; + nlines -= 16; + } + if (nlines > 0) { + flush_to_l2(p, nlines, step); + } +} + // Evict nlines cache lines at stride apart starting at addr from L1 to L2. // Uses EvictVA (CSR 0x89F). Unlike flush_to_l2, this guarantees the line is // NOT present in L1 after the operation - subsequent loads will miss and go From 562f4b85b24784965ca2c391b2ddfd2996889121 Mon Sep 17 00:00:00 2001 From: lhez Date: Tue, 1 Dec 2026 09:14:33 -0800 Subject: [PATCH 272/275] opencl: add log and non-contig scale (#33237) * opencl: refactor scale Assisted-by: Codex * opencl: add log Assisted-by: Codex * docs: update OpenCL operation support --- docs/ops.md | 2 +- docs/ops/OpenCL.csv | 25 +++-- ggml/src/ggml-opencl/ggml-opencl.cpp | 116 ++++++++++++++-------- ggml/src/ggml-opencl/kernels/scale.cl | 114 +++++++++++++++++---- ggml/src/ggml-opencl/kernels/unary_ext.cl | 1 + 5 files changed, 191 insertions(+), 67 deletions(-) diff --git a/docs/ops.md b/docs/ops.md index 6c838cad34b6..33da412ae068 100644 --- a/docs/ops.md +++ b/docs/ops.md @@ -69,7 +69,7 @@ Legend: | L2_NORM | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | ❌ | ❌ | | LEAKY_RELU | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | 🟡 | 🟡 | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | | LIGHTNING_INDEXER | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | 🟡 | ❌ | ❌ | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ | -| LOG | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | +| LOG | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | MEAN | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | 🟡 | ✅ | 🟡 | ✅ | ✅ | ❌ | ❌ | | MUL | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | MUL_MAT | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | diff --git a/docs/ops/OpenCL.csv b/docs/ops/OpenCL.csv index bee117961fc8..23d3da3e8f33 100644 --- a/docs/ops/OpenCL.csv +++ b/docs/ops/OpenCL.csv @@ -8979,10 +8979,14 @@ "OpenCL","SCALE","type=bf16,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=0,v=0","support","0","no","OpenCL" "OpenCL","SCALE","type=bf16,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=1,v=0","support","0","no","OpenCL" "OpenCL","SCALE","type=bf16,ne=[100,10,10,10],scale=0.500000,bias=0.000000,inplace=0,v=0","support","0","no","OpenCL" -"OpenCL","SCALE","type=f32,ne=[10,10,10,10],scale=2.000000,bias=0.000000,inplace=0,v=1","support","0","no","OpenCL" -"OpenCL","SCALE","type=f32,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=0,v=1","support","0","no","OpenCL" -"OpenCL","SCALE","type=f32,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=1,v=1","support","0","no","OpenCL" +"OpenCL","SCALE","type=f16,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=0,v=0","support","1","yes","OpenCL" +"OpenCL","SCALE","type=f16,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=1,v=0","support","1","yes","OpenCL" +"OpenCL","SCALE","type=f16,ne=[100,10,10,10],scale=0.500000,bias=0.000000,inplace=0,v=0","support","1","yes","OpenCL" +"OpenCL","SCALE","type=f32,ne=[10,10,10,10],scale=2.000000,bias=0.000000,inplace=0,v=1","support","1","yes","OpenCL" +"OpenCL","SCALE","type=f32,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=0,v=1","support","1","yes","OpenCL" +"OpenCL","SCALE","type=f32,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=1,v=1","support","1","yes","OpenCL" "OpenCL","SCALE","type=bf16,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=1,v=1","support","0","no","OpenCL" +"OpenCL","SCALE","type=f16,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=0,v=1","support","1","yes","OpenCL" "OpenCL","SILU_BACK","type=f32,ne=[64,5,4,3],eps=0.000001","support","0","no","OpenCL" "OpenCL","NORM","type=f32,ne=[64,5,4,3],v=0,eps=0.000000,noncontig_rows=0","support","1","yes","OpenCL" "OpenCL","RMS_NORM","type=f32,ne=[64,5,4,3],v=0,eps=0.000000,inplace=0","support","1","yes","OpenCL" @@ -14821,7 +14825,7 @@ "OpenCL","ADD_ID","type_a=f32,type_b=f32,n_embd=129,n_experts=8,n_experts_used=4,n_token=129,skip=1","support","1","yes","OpenCL" "OpenCL","SQR","type=f16,ne=[10,5,4,3]","support","1","yes","OpenCL" "OpenCL","SQRT","type=f16,ne=[10,3,3,2]","support","1","yes","OpenCL" -"OpenCL","LOG","type=f16,ne=[10,5,4,3]","support","0","no","OpenCL" +"OpenCL","LOG","type=f16,ne=[10,5,4,3]","support","1","yes","OpenCL" "OpenCL","SIN","type=f16,ne=[10,2,2,2]","support","0","no","OpenCL" "OpenCL","COS","type=f16,ne=[10,2,2,2]","support","0","no","OpenCL" "OpenCL","CLAMP","type=f16,ne=[10,5,4,3],min=-0.500000,max=0.500000,v=0","support","0","no","OpenCL" @@ -14835,8 +14839,8 @@ "OpenCL","SQR","type=f16,ne=[1024,1024,1,1]","support","1","yes","OpenCL" "OpenCL","SQRT","type=f16,ne=[7,1,5,3]","support","1","yes","OpenCL" "OpenCL","SQRT","type=f16,ne=[1024,1024,1,1]","support","1","yes","OpenCL" -"OpenCL","LOG","type=f16,ne=[7,1,5,3]","support","0","no","OpenCL" -"OpenCL","LOG","type=f16,ne=[1024,1024,1,1]","support","0","no","OpenCL" +"OpenCL","LOG","type=f16,ne=[7,1,5,3]","support","1","yes","OpenCL" +"OpenCL","LOG","type=f16,ne=[1024,1024,1,1]","support","1","yes","OpenCL" "OpenCL","SIN","type=f16,ne=[7,1,5,3]","support","0","no","OpenCL" "OpenCL","SIN","type=f16,ne=[1024,1024,1,1]","support","0","no","OpenCL" "OpenCL","COS","type=f16,ne=[7,1,5,3]","support","0","no","OpenCL" @@ -14855,7 +14859,7 @@ "OpenCL","TRUNC","type=f16,ne=[1024,1024,1,1]","support","1","yes","OpenCL" "OpenCL","SQR","type=f32,ne=[10,5,4,3]","support","1","yes","OpenCL" "OpenCL","SQRT","type=f32,ne=[10,3,3,2]","support","1","yes","OpenCL" -"OpenCL","LOG","type=f32,ne=[10,5,4,3]","support","0","no","OpenCL" +"OpenCL","LOG","type=f32,ne=[10,5,4,3]","support","1","yes","OpenCL" "OpenCL","SIN","type=f32,ne=[10,2,2,2]","support","0","no","OpenCL" "OpenCL","COS","type=f32,ne=[10,2,2,2]","support","0","no","OpenCL" "OpenCL","CLAMP","type=f32,ne=[10,5,4,3],min=-0.500000,max=0.500000,v=0","support","1","yes","OpenCL" @@ -14869,8 +14873,11 @@ "OpenCL","SQR","type=f32,ne=[1024,1024,1,1]","support","1","yes","OpenCL" "OpenCL","SQRT","type=f32,ne=[7,1,5,3]","support","1","yes","OpenCL" "OpenCL","SQRT","type=f32,ne=[1024,1024,1,1]","support","1","yes","OpenCL" -"OpenCL","LOG","type=f32,ne=[7,1,5,3]","support","0","no","OpenCL" -"OpenCL","LOG","type=f32,ne=[1024,1024,1,1]","support","0","no","OpenCL" +"OpenCL","LOG","type=f32,ne=[7,1,5,3]","support","1","yes","OpenCL" +"OpenCL","LOG","type=f32,ne=[1024,1024,1,1]","support","1","yes","OpenCL" +"OpenCL","LOG","type=bf16,ne=[10,5,4,3]","support","0","no","OpenCL" +"OpenCL","LOG","type=bf16,ne=[7,1,5,3]","support","0","no","OpenCL" +"OpenCL","LOG","type=bf16,ne=[1024,1024,1,1]","support","0","no","OpenCL" "OpenCL","SIN","type=f32,ne=[7,1,5,3]","support","0","no","OpenCL" "OpenCL","SIN","type=f32,ne=[1024,1024,1,1]","support","0","no","OpenCL" "OpenCL","COS","type=f32,ne=[7,1,5,3]","support","0","no","OpenCL" diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index 26e65e5b811e..635dcc0114d6 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -870,7 +870,8 @@ struct ggml_backend_opencl_context { cl_kernel kernel_sub, kernel_sub_row, kernel_sub_f16, kernel_sub_row_f16; cl_kernel kernel_add_id; cl_kernel kernel_add_id_add_id_swiglu_oai; - cl_kernel kernel_scale_f32, kernel_scale_f32_4; + cl_kernel kernel_scale_f32, kernel_scale_f32_4, kernel_scale_f32_nc; + cl_kernel kernel_scale_f16, kernel_scale_f16_4, kernel_scale_f16_nc; cl_kernel kernel_sqr_cont_f32, kernel_sqr_cont_f32_4, kernel_sqr_cont_f16, kernel_sqr_cont_f16_4; cl_kernel kernel_sqrt_cont_f32, kernel_sqrt_cont_f32_4, kernel_sqrt_cont_f16, kernel_sqrt_cont_f16_4; cl_kernel kernel_mean_f32, kernel_mean_f32_4; @@ -1172,6 +1173,7 @@ struct ggml_backend_opencl_context { cl_kernel kernel_ceil_f32, kernel_ceil_f32_4, kernel_ceil_f32_nc, kernel_ceil_f16, kernel_ceil_f16_4, kernel_ceil_f16_nc; cl_kernel kernel_round_f32, kernel_round_f32_4, kernel_round_f32_nc, kernel_round_f16, kernel_round_f16_4, kernel_round_f16_nc; cl_kernel kernel_trunc_f32, kernel_trunc_f32_4, kernel_trunc_f32_nc, kernel_trunc_f16, kernel_trunc_f16_4, kernel_trunc_f16_nc; + cl_kernel kernel_log_f32, kernel_log_f32_4, kernel_log_f32_nc, kernel_log_f16, kernel_log_f16_4, kernel_log_f16_nc; cl_kernel kernel_softplus_f32, kernel_softplus_f32_4, kernel_softplus_f32_nc; cl_kernel kernel_softplus_f16, kernel_softplus_f16_4, kernel_softplus_f16_nc; cl_kernel kernel_upscale; @@ -4693,8 +4695,12 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_scale_f32 = clCreateKernel(prog, "kernel_scale_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_scale_f32_4 = clCreateKernel(prog, "kernel_scale_f32_4", &err), err)); + CL_CHECK((backend_ctx->kernel_scale_f32 = clCreateKernel(prog, "kernel_scale_f32", &err), err)); + CL_CHECK((backend_ctx->kernel_scale_f32_4 = clCreateKernel(prog, "kernel_scale_f32_4", &err), err)); + CL_CHECK((backend_ctx->kernel_scale_f32_nc = clCreateKernel(prog, "kernel_scale_f32_nc", &err), err)); + CL_CHECK((backend_ctx->kernel_scale_f16 = clCreateKernel(prog, "kernel_scale_f16", &err), err)); + CL_CHECK((backend_ctx->kernel_scale_f16_4 = clCreateKernel(prog, "kernel_scale_f16_4", &err), err)); + CL_CHECK((backend_ctx->kernel_scale_f16_nc = clCreateKernel(prog, "kernel_scale_f16_nc", &err), err)); CL_CHECK(clReleaseProgram(prog)); GGML_LOG_CONT("."); } @@ -5192,6 +5198,7 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { CL_UNARY_EXT_K(ceil) CL_UNARY_EXT_K(round) CL_UNARY_EXT_K(trunc) + CL_UNARY_EXT_K(log) #undef CL_UNARY_EXT_K CL_CHECK((backend_ctx->kernel_xielu_f32 = clCreateKernel(prog, "kernel_xielu_f32", &err), err)); CL_CHECK((backend_ctx->kernel_xielu_f16 = clCreateKernel(prog, "kernel_xielu_f16", &err), err)); @@ -12829,7 +12836,8 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te op->type == op->src[1]->type; } case GGML_OP_SCALE: - return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous(op->src[0]); + return (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) && + op->src[0]->type == op->type && ggml_is_contiguous_rows(op->src[0]); case GGML_OP_ADD: if (op->type == GGML_TYPE_F16) { const bool src0_ok = op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32; @@ -12846,6 +12854,8 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16); case GGML_OP_ADD_ID: return op->src[0]->type == GGML_TYPE_F32; + case GGML_OP_LOG: + return op->src[0]->type == op->type && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16); case GGML_OP_SQR: case GGML_OP_SQRT: return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) && @@ -21893,6 +21903,7 @@ GGML_CL_UNARY_EXT_WRAP(ggml_cl_floor, floor) GGML_CL_UNARY_EXT_WRAP(ggml_cl_ceil, ceil) GGML_CL_UNARY_EXT_WRAP(ggml_cl_round, round) GGML_CL_UNARY_EXT_WRAP(ggml_cl_trunc, trunc) +GGML_CL_UNARY_EXT_WRAP(ggml_cl_log, log) #undef GGML_CL_UNARY_EXT_WRAP @@ -39863,54 +39874,75 @@ static void ggml_cl_mul_mat_ext(ggml_backend_t backend, const ggml_tensor * src0 } static void ggml_cl_scale(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); + GGML_ASSERT(src0 && src0->extra); + GGML_ASSERT(dst && dst->extra); GGML_UNUSED(src1); - GGML_ASSERT(ggml_is_contiguous(src0)); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const auto * extra0 = (const ggml_tensor_extra_cl *) src0->extra; + const auto * extrad = (const ggml_tensor_extra_cl *) dst->extra; - float scale; - float bias; - memcpy(&scale, ((int32_t *) dst->op_params) + 0, sizeof(float)); - memcpy(&bias, ((int32_t *) dst->op_params) + 1, sizeof(float)); + const cl_ulong offset0 = extra0->offset + src0->view_offs; + const cl_ulong offsetd = extrad->offset + dst->view_offs; + const float scale = ggml_get_op_params_f32(dst, 0); + const float bias = ggml_get_op_params_f32(dst, 1); + const bool is_f16 = src0->type == GGML_TYPE_F16; - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + cl_kernel kernel; - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; + if (ggml_is_contiguous(src0) && ggml_is_contiguous(dst)) { + size_t n = ggml_nelements(dst); + const size_t alignment = 4 * ggml_element_size(src0); + if (n % 4 == 0 && offset0 % alignment == 0 && offsetd % alignment == 0) { + kernel = is_f16 ? backend_ctx->kernel_scale_f16_4 : backend_ctx->kernel_scale_f32_4; + n /= 4; + } else { + kernel = is_f16 ? backend_ctx->kernel_scale_f16 : backend_ctx->kernel_scale_f32; + } - cl_kernel kernel; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(float), &bias)); - int n = ggml_nelements(dst); + size_t global_work_size[] = {n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + size_t * local_work_size_ptr = local_work_size; + if (n % local_work_size[0] != 0 && !backend_ctx->non_uniform_workgroups) { + local_work_size_ptr = nullptr; + } - if (n % 4 == 0) { - kernel = backend_ctx->kernel_scale_f32_4; - n /= 4; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); } else { - kernel = backend_ctx->kernel_scale_f32; - } + kernel = is_f16 ? backend_ctx->kernel_scale_f16_nc : backend_ctx->kernel_scale_f32_nc; + const cl_ulong ne00 = src0->ne[0]; + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(float), &scale)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(float), &bias)); + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(float), &bias)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb3)); - size_t global_work_size[] = {(size_t)n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; + const size_t nth = 64; + size_t global_work_size[] = {(size_t)src0->ne[1] * nth, (size_t)src0->ne[2], (size_t)src0->ne[3]}; + size_t local_work_size[] = {nth, 1, 1}; - size_t * local_work_size_ptr = local_work_size; - if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { - local_work_size_ptr = nullptr; // Let driver choose the work-group sizes. + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); } static void ggml_cl_cpy(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { @@ -41859,6 +41891,12 @@ bool ggml_cl_compute_forward(ggml_backend_t backend, struct ggml_tensor * tensor } func = ggml_cl_sub; break; + case GGML_OP_LOG: + if (!any_on_device) { + return false; + } + func = ggml_cl_log; + break; case GGML_OP_SQR: if (!any_on_device) { return false; diff --git a/ggml/src/ggml-opencl/kernels/scale.cl b/ggml/src/ggml-opencl/kernels/scale.cl index 17ed97f0d660..e01a2a81566a 100644 --- a/ggml/src/ggml-opencl/kernels/scale.cl +++ b/ggml/src/ggml-opencl/kernels/scale.cl @@ -1,27 +1,105 @@ #pragma OPENCL EXTENSION cl_khr_fp16 : enable kernel void kernel_scale_f32( - global float * src0, - ulong offset0, - global float * dst, - ulong offsetd, - float scale, - float bias + global const float * src0, + ulong offset0, + global float * dst, + ulong offsetd, + float scale, + float bias ) { - src0 = (global float*)((global char*)src0 + offset0); - dst = (global float*)((global char*)dst + offsetd); - dst[get_global_id(0)] = src0[get_global_id(0)] * scale + bias; + src0 = (global const float *)((global const char *)src0 + offset0); + dst = (global float *)((global char *)dst + offsetd); + const size_t i = get_global_id(0); + dst[i] = src0[i] * scale + bias; } kernel void kernel_scale_f32_4( - global float4 * src0, - ulong offset0, - global float4 * dst, - ulong offsetd, - float scale, - float bias + global const float4 * src0, + ulong offset0, + global float4 * dst, + ulong offsetd, + float scale, + float bias ) { - src0 = (global float4*)((global char*)src0 + offset0); - dst = (global float4*)((global char*)dst + offsetd); - dst[get_global_id(0)] = src0[get_global_id(0)] * scale + bias; + src0 = (global const float4 *)((global const char *)src0 + offset0); + dst = (global float4 *)((global char *)dst + offsetd); + const size_t i = get_global_id(0); + dst[i] = src0[i] * scale + bias; +} + +kernel void kernel_scale_f16( + global const half * src0, + ulong offset0, + global half * dst, + ulong offsetd, + float scale, + float bias +) { + src0 = (global const half *)((global const char *)src0 + offset0); + dst = (global half *)((global char *)dst + offsetd); + const size_t i = get_global_id(0); + dst[i] = convert_half(convert_float(src0[i]) * scale + bias); +} + +kernel void kernel_scale_f16_4( + global const half4 * src0, + ulong offset0, + global half4 * dst, + ulong offsetd, + float scale, + float bias +) { + src0 = (global const half4 *)((global const char *)src0 + offset0); + dst = (global half4 *)((global char *)dst + offsetd); + const size_t i = get_global_id(0); + dst[i] = convert_half4(convert_float4(src0[i]) * scale + bias); +} + +kernel void kernel_scale_f32_nc( + global const char * src0, + ulong offset0, + global char * dst, + ulong offsetd, + float scale, + float bias, + ulong ne00, + ulong nb00, ulong nb01, ulong nb02, ulong nb03, + ulong nb0, ulong nb1, ulong nb2, ulong nb3 +) { + const size_t i1 = get_group_id(0); + const size_t i2 = get_group_id(1); + const size_t i3 = get_group_id(2); + src0 += offset0 + i1*nb01 + i2*nb02 + i3*nb03; + dst += offsetd + i1*nb1 + i2*nb2 + i3*nb3; + + for (size_t i0 = get_local_id(0); i0 < ne00; i0 += get_local_size(0)) { + global const float * x = (global const float *)(src0 + i0*nb00); + global float * y = (global float *)(dst + i0*nb0); + *y = *x * scale + bias; + } +} + +kernel void kernel_scale_f16_nc( + global const char * src0, + ulong offset0, + global char * dst, + ulong offsetd, + float scale, + float bias, + ulong ne00, + ulong nb00, ulong nb01, ulong nb02, ulong nb03, + ulong nb0, ulong nb1, ulong nb2, ulong nb3 +) { + const size_t i1 = get_group_id(0); + const size_t i2 = get_group_id(1); + const size_t i3 = get_group_id(2); + src0 += offset0 + i1*nb01 + i2*nb02 + i3*nb03; + dst += offsetd + i1*nb1 + i2*nb2 + i3*nb3; + + for (size_t i0 = get_local_id(0); i0 < ne00; i0 += get_local_size(0)) { + global const half * x = (global const half *)(src0 + i0*nb00); + global half * y = (global half *)(dst + i0*nb0); + *y = convert_half(convert_float(*x) * scale + bias); + } } diff --git a/ggml/src/ggml-opencl/kernels/unary_ext.cl b/ggml/src/ggml-opencl/kernels/unary_ext.cl index e58cc0153ff1..c5dcfec257bd 100644 --- a/ggml/src/ggml-opencl/kernels/unary_ext.cl +++ b/ggml/src/ggml-opencl/kernels/unary_ext.cl @@ -74,6 +74,7 @@ kernel void kernel_##NAME##_f16_nc( \ } \ } +UNARY_EXT(log, log(x), log(x)) UNARY_EXT(sgn, sign(x), sign(x)) UNARY_EXT(step, x > 0.0f ? 1.0f : 0.0f, select((float4)0.0f, (float4)1.0f, x > 0.0f)) UNARY_EXT(elu, x > 0.0f ? x : expm1(x), select(expm1(x), x, x > 0.0f)) From cda9b4113cd4caa58b206e9f3f0478092686890e Mon Sep 17 00:00:00 2001 From: Pascal Date: Tue, 1 Dec 2026 18:21:04 +0100 Subject: [PATCH 273/275] metal : add apertus to the Metal fusion baseline (#33453) --- tests/fusion/MTL.csv | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/fusion/MTL.csv b/tests/fusion/MTL.csv index d33dee2a4b92..4796cc805e25 100644 --- a/tests/fusion/MTL.csv +++ b/tests/fusion/MTL.csv @@ -4,6 +4,7 @@ afmoe ,1 ,any ,MUL+ADD , 2 afmoe ,1 ,any ,RMS_NORM+MUL , 10 afmoe ,1 ,any ,RMS_NORM+MUL+ADD , 3 afmoe ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 +apertus ,0 ,any ,RMS_NORM+MUL , 9 arcee ,0 ,any ,RMS_NORM+MUL , 5 arctic ,1 ,any ,MUL+ADD , 4 arctic ,1 ,any ,RMS_NORM+MUL , 7 From e5cd6e34ba1070a3e39c49d2388d7f188ef4fe35 Mon Sep 17 00:00:00 2001 From: Pascal Date: Tue, 1 Dec 2026 18:38:28 +0100 Subject: [PATCH 274/275] Vulkan: one thread per row for soft_max and sum_rows on short rows (#33197) * vulkan : one thread per row for soft_max and sum_rows on short rows A row of at most 8 columns got a whole workgroup with a shared memory reduction. Each invocation now handles a whole row, with fastdiv for the row indices, and sum_rows covers mean through its weight. On 3.4M rows of 4 on an RTX PRO 6000, soft_max goes from 1653 to 42 us and sum_rows from 1662 to 10 us. Hy4 flash decode goes from 53 to 60 t/s at 4k context and from 9.6 to 54.8 t/s at 16k. * vulkan : initialize soft_max fastdiv push constants * vulkan : use vec4 loads in the short row soft_max and sum_rows Rows of 4 or 8 floats were read and written one element at a time, so each load of a subgroup hit addresses 16 or 32 bytes apart. When the row length is a multiple of 4 and the strides are aligned, move whole vec4 instead, and keep the scalar loop otherwise. On a RTX PRO 6000 with 3.44M rows of 4 floats, soft_max goes from 42 to 19 us and sum_rows/mean from 10.3 to 9.5 us. * tests : remove the temporary short row cases * vulkan : revert the vec4 loads in the short row soft_max and sum_rows The vec4 path halves the soft_max kernel time on rows of 4 floats, but Hy4 flash decode is unchanged on a RTX PRO 6000 and sum_rows gets slower with 8 floats per row, so keep the simpler scalar loop. --- .../ggml-vulkan/ggml-vulkan-push-constants.h | 7 ++ ggml/src/ggml-vulkan/ggml-vulkan-types.h | 2 + ggml/src/ggml-vulkan/ggml-vulkan.cpp | 15 ++- .../vulkan-shaders/soft_max_short.comp | 94 +++++++++++++++++++ .../vulkan-shaders/sum_rows_short.comp | 35 +++++++ .../vulkan-shaders/vulkan-shaders-gen.cpp | 3 + 6 files changed, 155 insertions(+), 1 deletion(-) create mode 100644 ggml/src/ggml-vulkan/vulkan-shaders/soft_max_short.comp create mode 100644 ggml/src/ggml-vulkan/vulkan-shaders/sum_rows_short.comp diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h index bd01b766fa93..72e7b26a4ae2 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h @@ -614,8 +614,15 @@ struct vk_op_soft_max_push_constants { uint32_t n_head_log2; uint32_t nrows_x; uint32_t has_sinks; + uint32_t ne0_1mp, ne0_1L; + uint32_t ne0_12mp, ne0_12L; }; +template <> inline void init_pushconst_fastdiv(vk_op_soft_max_push_constants &p) { + init_fastdiv_values(p.ne01*p.ne02, p.ne0_12mp, p.ne0_12L); + init_fastdiv_values(p.ne01, p.ne0_1mp, p.ne0_1L); +} + struct vk_op_argsort_push_constants { uint32_t ncols; uint32_t ncols_padded; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-types.h b/ggml/src/ggml-vulkan/ggml-vulkan-types.h index 47383d50afe3..ea22c613527f 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-types.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-types.h @@ -978,6 +978,7 @@ struct vk_device_struct { vk_pipeline pipeline_silu_back_f32; vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16; + vk_pipeline pipeline_soft_max_short_f32, pipeline_soft_max_short_f32_f16; vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512; vk_pipeline pipeline_soft_max_back_f32; @@ -995,6 +996,7 @@ struct vk_device_struct { vk_pipeline pipeline_topk_radix_f32; vk_pipeline pipeline_topk_radix_qsa; // qwen4 QSA indexer fusion (f16 mask) vk_pipeline pipeline_sum_rows_f32; + vk_pipeline pipeline_sum_rows_short_f32; vk_pipeline pipeline_cross_entropy_loss_f32, pipeline_cross_entropy_loss_f32_wg512; vk_pipeline pipeline_cross_entropy_loss_back_f32, pipeline_cross_entropy_loss_back_f32_wg512; vk_pipeline pipeline_fwht_f32[num_fwht_pipelines]; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index 1cdb392c4c63..0ce67f21dd25 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -4108,6 +4108,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_wg512, "soft_max_f32_wg512", soft_max_f32_len, soft_max_f32_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1); ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_f16, "soft_max_f32_f16", soft_max_f32_f16_len, soft_max_f32_f16_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1); ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_f16_wg512, "soft_max_f32_f16_wg512", soft_max_f32_f16_len, soft_max_f32_f16_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1); + ggml_vk_create_pipeline(device, device->pipeline_soft_max_short_f32, "soft_max_short_f32", soft_max_short_f32_len, soft_max_short_f32_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {256, 1, 1}, { 256 }, 1); + ggml_vk_create_pipeline(device, device->pipeline_soft_max_short_f32_f16, "soft_max_short_f32_f16", soft_max_short_f32_f16_len, soft_max_short_f32_f16_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {256, 1, 1}, { 256 }, 1); ggml_vk_create_pipeline(device, device->pipeline_soft_max_back_f32, "soft_max_back_f32", soft_max_back_f32_len, soft_max_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1, true); ggml_vk_create_pipeline(device, device->pipeline_soft_max_large1_f32, "soft_max_large1_f32", soft_max_large1_f32_len, soft_max_large1_f32_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true); @@ -4179,6 +4181,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { ggml_vk_create_pipeline(device, device->pipeline_argmax_f32, "argmax_f32", argmax_f32_len, argmax_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1); ggml_vk_create_pipeline(device, device->pipeline_sum_rows_f32, "sum_rows_f32", sum_rows_f32_len, sum_rows_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {1, 1, 1}, { device->subgroup_size }, 1, true); + ggml_vk_create_pipeline(device, device->pipeline_sum_rows_short_f32, "sum_rows_short_f32", sum_rows_short_f32_len, sum_rows_short_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {256, 1, 1}, { 256 }, 1, true); ggml_vk_create_pipeline(device, device->pipeline_cross_entropy_loss_f32, "cross_entropy_loss_f32", cross_entropy_loss_f32_len, cross_entropy_loss_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1); ggml_vk_create_pipeline(device, device->pipeline_cross_entropy_loss_f32_wg512, "cross_entropy_loss_f32_wg512", cross_entropy_loss_f32_len, cross_entropy_loss_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, { 512 }, 1); ggml_vk_create_pipeline(device, device->pipeline_cross_entropy_loss_back_f32, "cross_entropy_loss_back_f32", cross_entropy_loss_back_f32_len, cross_entropy_loss_back_f32_data, "main", 4, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1); @@ -10620,9 +10623,15 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const } if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) { + if (src0->ne[0] <= 8) { + return ctx->device->pipeline_soft_max_short_f32; + } return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32; } if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) { + if (src0->ne[0] <= 8) { + return ctx->device->pipeline_soft_max_short_f32_f16; + } return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16; } return nullptr; @@ -10684,6 +10693,9 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const case GGML_OP_SUM_ROWS: case GGML_OP_MEAN: if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { + if (op != GGML_OP_SUM && src0->ne[0] <= 8) { + return ctx->device->pipeline_sum_rows_short_f32; + } return ctx->device->pipeline_sum_rows_f32; } return nullptr; @@ -12945,7 +12957,8 @@ void ggml_vk_soft_max(ggml_backend_vk_context * ctx, vk_context& subctx, const g m0, m1, n_head_log2, nrows_x, - src2 != nullptr + src2 != nullptr, + 0, 0, 0, 0, }; if (ncols <= 16384) { diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/soft_max_short.comp b/ggml/src/ggml-vulkan/vulkan-shaders/soft_max_short.comp new file mode 100644 index 000000000000..c11dcc21b20d --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/soft_max_short.comp @@ -0,0 +1,94 @@ +#version 450 + +#extension GL_EXT_control_flow_attributes : enable + +layout (push_constant) uniform parameter +{ + uint KX; + uint KY; + uint ne00; + uint ne01; + uint ne02; + uint ne12; + uint ne13; + uint nb11; + uint nb12; + uint nb13; + float scale; + float max_bias; + float m0; + float m1; + uint n_head_log2; + uint nrows_x; + uint has_sinks; + uint ne0_1mp, ne0_1L; + uint ne0_12mp, ne0_12L; +} p; + +#include "types.glsl" +#include "utils.glsl" + +layout(constant_id = 0) const uint BLOCK_SIZE = 256; +layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in; + +layout (binding = 0) readonly buffer X {A_TYPE data_a[];}; +layout (binding = 1) readonly buffer Y {B_TYPE data_b[];}; +layout (binding = 2) readonly buffer Z {float data_c[];}; +layout (binding = 3) buffer D {D_TYPE data_d[];}; + +const uint MAX_COLS = 8; + +void main() { + const uint rowx = gl_GlobalInvocationID.z * 262144 + gl_GlobalInvocationID.y * 512 + gl_GlobalInvocationID.x; + + if (rowx >= p.nrows_x) { + return; + } + + const uint i03 = fastdiv(rowx, p.ne0_12mp, p.ne0_12L); + const uint i012 = rowx - i03 * p.ne01 * p.ne02; + const uint i02 = fastdiv(i012, p.ne0_1mp, p.ne0_1L); + const uint i01 = i012 - i02 * p.ne01; + + uint rowy_start = 0; + if (p.KY > 0) { + rowy_start = i01 * p.nb11 + fastmod(i02, p.ne12) * p.nb12 + fastmod(i03, p.ne13) * p.nb13; + } + + float slope = 1.0f; + + if (p.max_bias > 0.0f) { + const float base = i02 < p.n_head_log2 ? p.m0 : p.m1; + const uint exp = i02 < p.n_head_log2 ? i02 + 1 : 2*(i02 - p.n_head_log2) + 1; + + slope = pow(base, exp); + } + + FLOAT_TYPE vals[MAX_COLS]; + FLOAT_TYPE max_val = p.has_sinks == 0 ? uintBitsToFloat(0xFF800000) : data_c[i02]; + + [[unroll]] for (uint col = 0; col < MAX_COLS; ++col) { + if (col < p.KX) { + const FLOAT_TYPE b = p.KY > 0 ? FLOAT_TYPE(data_b[rowy_start + col]) : FLOAT_TYPE(0.0f); + vals[col] = FLOAT_TYPE(data_a[rowx * p.KX + col]) * p.scale + slope * b; + max_val = max(max_val, vals[col]); + } + } + + FLOAT_TYPE sum = p.has_sinks == 0 ? FLOAT_TYPE(0.0f) : FLOAT_TYPE(exp(FLOAT_TYPE(data_c[i02]) - max_val)); + + [[unroll]] for (uint col = 0; col < MAX_COLS; ++col) { + if (col < p.KX) { + vals[col] = exp(vals[col] - max_val); + sum += vals[col]; + } + } + + const FLOAT_TYPE rcpdivisor = 1.0/sum; + + [[unroll]] for (uint col = 0; col < MAX_COLS; ++col) { + if (col < p.KX) { + data_d[rowx * p.KX + col] = D_TYPE(vals[col] * rcpdivisor); + } + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/sum_rows_short.comp b/ggml/src/ggml-vulkan/vulkan-shaders/sum_rows_short.comp new file mode 100644 index 000000000000..a0bc50ed48f4 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/sum_rows_short.comp @@ -0,0 +1,35 @@ +#version 450 + +#include "types.glsl" +#include "sum_rows.glsl" + +#extension GL_EXT_control_flow_attributes : enable + +layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in; + +layout (binding = 0) readonly buffer A {A_TYPE data_a[];}; +layout (binding = 1) writeonly buffer D {D_TYPE data_d[];}; + +layout (constant_id = 0) const uint BLOCK_SIZE = 256; + +void main() { + const uint row = gl_GlobalInvocationID.z * 262144 + gl_GlobalInvocationID.y * 512 + gl_GlobalInvocationID.x; + + if (row >= p.ne01 * p.ne02 * p.ne03) { return; } + + const uint i03 = fastdiv(row, p.ne0_12mp, p.ne0_12L); + const uint i03_offset = i03 * p.ne01*p.ne02; + const uint i02 = fastdiv(row - i03_offset, p.ne0_1mp, p.ne0_1L); + const uint i01 = row - i03_offset - i02*p.ne01; + + const uint src_idx = get_aoffset() + i01 * p.nb01 + i02 * p.nb02 + i03 * p.nb03; + const uint dst_idx = get_doffset() + i01 * p.nb11 + i02 * p.nb12 + i03 * p.nb13; + + FLOAT_TYPE sum = FLOAT_TYPE(0.0); + + for (uint i = 0; i < p.n_cols; ++i) { + sum += FLOAT_TYPE(data_a[src_idx + i]); + } + + data_d[dst_idx] = D_TYPE(sum * p.weight); +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp index 8e15600974c8..dc0c61e73534 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp @@ -1059,6 +1059,8 @@ void process_shaders() { string_to_spv("soft_max_f32", "soft_max.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}})); string_to_spv("soft_max_f32_f16", "soft_max.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float16_t"}, {"D_TYPE", "float"}})); + string_to_spv("soft_max_short_f32", "soft_max_short.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}})); + string_to_spv("soft_max_short_f32_f16", "soft_max_short.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float16_t"}, {"D_TYPE", "float"}})); string_to_spv("soft_max_back_f32", "soft_max_back.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}})); string_to_spv("soft_max_large1_f32", "soft_max_large1.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}})); @@ -1093,6 +1095,7 @@ void process_shaders() { string_to_spv("argmax_f32", "argmax.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "int"}})); string_to_spv("sum_rows_f32", "sum_rows.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}})); + string_to_spv("sum_rows_short_f32", "sum_rows_short.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}})); string_to_spv("cross_entropy_loss_f32", "cross_entropy_loss.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}})); string_to_spv("cross_entropy_loss_back_f32", "cross_entropy_loss_back.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}})); string_to_spv("fwht_f32", "fwht.comp", {{"A_TYPE", "float"}}); From 2a2140f1f61a24546078039f9124acbae6bdbd9f Mon Sep 17 00:00:00 2001 From: rafasmour <54501936+rafasmour@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:57:46 +0000 Subject: [PATCH 275/275] cuda : keep indexed K/V loads on AMD WMMA, no dequantized gemm for NVFP4, no sparse tile instances for quantized K/V Assisted-by: Claude Sonnet 5.5 --- ggml/src/ggml-cuda/fattn-mma-f16.cuh | 6 ++++-- ggml/src/ggml-cuda/mmq.cu | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-mma-f16.cuh b/ggml/src/ggml-cuda/fattn-mma-f16.cuh index a6fcf296d779..37789a50b2fb 100644 --- a/ggml/src/ggml-cuda/fattn-mma-f16.cuh +++ b/ggml/src/ggml-cuda/fattn-mma-f16.cuh @@ -628,7 +628,8 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( constexpr int nstages = ggml_cuda_fattn_mma_get_nstages (DKQ, DV, ncols1, ncols2, use_sparse); // FIXME this is causing performance regressions on AMD/V100. -#ifdef TURING_MMA_AVAILABLE + // The fork keeps it on for AMD WMMA: K/V rows are read through the index list of the launch (null without rows). +#if defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) constexpr bool KV_indirection = true; #else constexpr bool KV_indirection = use_sparse; @@ -1335,7 +1336,8 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( constexpr int nstages = ggml_cuda_fattn_mma_get_nstages (DKQ, DV, ncols1, ncols2, use_sparse); // FIXME this is causing performance regressions on AMD/V100. -#ifdef TURING_MMA_AVAILABLE + // The fork keeps it on for AMD WMMA: K/V rows are read through the index list of the launch (null without rows). +#if defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) constexpr bool KV_indirection = true; #else constexpr bool KV_indirection = use_sparse; diff --git a/ggml/src/ggml-cuda/mmq.cu b/ggml/src/ggml-cuda/mmq.cu index fb13dc2af09c..5a2520b6fb04 100644 --- a/ggml/src/ggml-cuda/mmq.cu +++ b/ggml/src/ggml-cuda/mmq.cu @@ -509,7 +509,7 @@ bool ggml_cuda_should_use_mmq(enum ggml_type type, int cc, int64_t ne11, int64_t // - for Q4_K with 4096 or more columns per row the F16 gemm on the dequantized weights is faster from a // batch of 256 (prompt speed of a 9B model +6% with 512 columns, +9% with 1024). Narrower Q5_K // matrices lose 1.5%, IQ2/IQ3 gain under 2% and stay on MMQ. - if (GGML_CUDA_CC_IS_RDNA3_0(cc) && ne01 > 0) { + if (GGML_CUDA_CC_IS_RDNA3_0(cc) && ne01 > 0 && type != GGML_TYPE_NVFP4) { if (ne01 <= 64) { return false; }