From b9073e5483713f370755b3180d94c1f22c1ba740 Mon Sep 17 00:00:00 2001 From: Matheus Britto <55333133+matheusbrittod3v@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:40:02 -0300 Subject: [PATCH 01/65] jinja : support Unicode whitespace and multi-byte chars in strip/trim (#33461) * jinja : support Unicode whitespace and multi-byte chars in strip/trim Assisted-by: Antigravity * jinja : clarify Unicode strip comments and use args.func_name Assisted-by: Antigravity --------- Co-authored-by: matheusbrito --- common/jinja/string.cpp | 117 ++++++++++++++++++++++++++++------------ common/jinja/value.cpp | 47 ++++++++-------- tests/test-jinja.cpp | 23 ++++++++ 3 files changed, 128 insertions(+), 59 deletions(-) diff --git a/common/jinja/string.cpp b/common/jinja/string.cpp index 22189fa6f47c..ec661184faad 100644 --- a/common/jinja/string.cpp +++ b/common/jinja/string.cpp @@ -1,5 +1,6 @@ #include "jinja/string.h" #include "jinja/value.h" +#include "unicode.h" #include #include @@ -205,53 +206,103 @@ string string::titlecase() { return res; }); } -string string::strip(bool left, bool right, std::optional chars) { - static auto strip_part = [](const std::string & s, bool left, bool right, std::optional chars) -> std::string { - size_t start = 0; - size_t end = s.length(); - auto match_char = [&chars](unsigned char c) -> bool { - return chars ? (*chars).find(c) != std::string::npos : isspace(c); - }; - if (left) { - while (start < end && match_char(static_cast(s[start]))) { - ++start; - } - } - if (right) { - while (end > start && match_char(static_cast(s[end - 1]))) { - --end; - } +// mirrors Python str.isspace() (CPython Py_UNICODE_ISSPACE) +static bool is_unicode_whitespace(uint32_t cp) { + return (cp >= 0x0009 && cp <= 0x000D) || + (cp >= 0x001C && cp <= 0x0020) || + cp == 0x0085 || + cp == 0x00A0 || + cp == 0x1680 || + (cp >= 0x2000 && cp <= 0x200A) || + cp == 0x2028 || + cp == 0x2029 || + cp == 0x202F || + cp == 0x205F || + cp == 0x3000; +} + +static std::vector decode_utf8_cpts(std::string_view s) { + std::vector cpts; + size_t pos = 0; + while (pos < s.size()) { + auto parsed = common_parse_utf8_codepoint(s, pos); + if (parsed.status == utf8_parse_result::SUCCESS) { + cpts.push_back(parsed.codepoint); + pos += parsed.bytes_consumed; + } else { + // skip invalid UTF-8 bytes so they never match non-strippable raw bytes in the input + pos += 1; } - return s.substr(start, end - start); - }; + } + return cpts; +} + +string string::strip(bool left, bool right, std::optional chars) { if (parts.empty()) { return *this; } + + std::vector char_cpts; + if (chars) { + char_cpts = decode_utf8_cpts(*chars); + } + + auto match_cp = [&](uint32_t cp) -> bool { + if (chars) { + return std::find(char_cpts.begin(), char_cpts.end(), cp) != char_cpts.end(); + } + return is_unicode_whitespace(cp); + }; + + const std::string full = str(); + size_t start = 0; + size_t end = full.size(); + if (left) { - for (size_t i = 0; i < parts.size(); ++i) { - parts[i].val = strip_part(parts[i].val, true, false, chars); - if (parts[i].val.empty()) { - // remove empty part - parts.erase(parts.begin() + i); - --i; - continue; - } else { + while (start < end) { + auto parsed = common_parse_utf8_codepoint(full, start); + if (parsed.status != utf8_parse_result::SUCCESS || !match_cp(parsed.codepoint)) { break; } + start += parsed.bytes_consumed; } } + if (right) { - for (size_t i = parts.size(); i-- > 0;) { - parts[i].val = strip_part(parts[i].val, false, true, chars); - if (parts[i].val.empty()) { - // remove empty part - parts.erase(parts.begin() + i); - continue; + size_t new_end = start; + size_t pos = start; + while (pos < end) { + auto parsed = common_parse_utf8_codepoint(full, pos); + if (parsed.status != utf8_parse_result::SUCCESS) { + pos += 1; + new_end = pos; } else { - break; + pos += parsed.bytes_consumed; + if (!match_cp(parsed.codepoint)) { + new_end = pos; + } } } + end = new_end; + } + + std::vector new_parts; + size_t offset = 0; + for (const auto & part : parts) { + const size_t part_start = offset; + const size_t part_end = offset + part.val.size(); + offset = part_end; + + const size_t keep_start = std::max(part_start, start); + const size_t keep_end = std::min(part_end, end); + if (keep_start < keep_end) { + new_parts.push_back({ + part.is_input, + part.val.substr(keep_start - part_start, keep_end - keep_start) + }); + } } + parts = std::move(new_parts); return *this; } diff --git a/common/jinja/value.cpp b/common/jinja/value.cpp index 79d79b2dbe51..04e78c16ac1f 100644 --- a/common/jinja/value.cpp +++ b/common/jinja/value.cpp @@ -739,6 +739,24 @@ static bool string_endswith(const std::string & str, const std::string & suffix) throw not_implemented_exception("String join builtin not implemented"); } +static value string_strip_impl(const func_args & args, bool left, bool right) { + args.ensure_kwargs({"chars"}); + args.ensure_count(1, 2); + const std::string & name = args.func_name; + value val_input = args.get_pos(0); + if (!is_val(val_input)) { + throw raised_exception(name + "() first argument must be a string"); + } + value val_chars = args.get_kwarg_or_pos("chars", 1); + if (val_chars->is_undefined() || is_val(val_chars)) { + return mk_val(val_input->as_string().strip(left, right)); + } + if (!is_val(val_chars)) { + throw raised_exception(name + "() argument must be None or str"); + } + return mk_val(val_input->as_string().strip(left, right, val_chars->as_string().str())); +} + const func_builtins & value_string_t::get_builtins() const { static const func_builtins builtins = { {"default", default_value}, @@ -757,36 +775,13 @@ const func_builtins & value_string_t::get_builtins() const { return mk_val(str); }}, {"strip", [](const func_args & args) -> value { - args.ensure_kwargs({"chars"}); - args.ensure_count(1, 2); - value val_input = args.get_pos(0); - if (!is_val(val_input)) { - throw raised_exception("strip() first argument must be a string"); - } - value val_chars = args.get_kwarg_or_pos("chars", 1); - if (val_chars->is_undefined()) { - return mk_val(args.get_pos(0)->as_string().strip(true, true)); - } else { - return mk_val(args.get_pos(0)->as_string().strip(true, true, val_chars->as_string().str())); - } + return string_strip_impl(args, true, true); }}, {"rstrip", [](const func_args & args) -> value { - args.ensure_vals(); - value val_chars = args.get_kwarg_or_pos("chars", 1); - if (val_chars->is_undefined()) { - return mk_val(args.get_pos(0)->as_string().strip(false, true)); - } else { - return mk_val(args.get_pos(0)->as_string().strip(false, true, val_chars->as_string().str())); - } + return string_strip_impl(args, false, true); }}, {"lstrip", [](const func_args & args) -> value { - args.ensure_vals(); - value val_chars = args.get_kwarg_or_pos("chars", 1); - if (val_chars->is_undefined()) { - return mk_val(args.get_pos(0)->as_string().strip(true, false)); - } else { - return mk_val(args.get_pos(0)->as_string().strip(true, false, val_chars->as_string().str())); - } + return string_strip_impl(args, true, false); }}, {"title", [](const func_args & args) -> value { args.ensure_kwargs(); diff --git a/tests/test-jinja.cpp b/tests/test-jinja.cpp index b72b00b12b0d..331745a185f9 100644 --- a/tests/test-jinja.cpp +++ b/tests/test-jinja.cpp @@ -1018,6 +1018,29 @@ static void test_filters(testing & t) { ); } + test_template(t, "trim and strip unicode whitespace", + "[{{ s|trim }}]|[{{ s.strip() }}]|[{{ s.lstrip() }}]|[{{ s.rstrip() }}]", + {{"s", "\u3000\u00a0hello\u2003\u202f"}}, + "[hello]|[hello]|[hello\u2003\u202f]|[\u3000\u00a0hello]" + ); + + test_template(t, "trim and strip multibyte custom chars", + "[{{ t|trim(c) }}]|[{{ t.strip(c) }}]|[{{ u|trim(c) }}]", + {{"t", "\u3001hi\u3002"}, {"u", "\u3000\u3001hi\u3000"}, {"c", "\u3000"}}, + "[\u3001hi\u3002]|[\u3001hi\u3002]|[\u3001hi]" + ); + + test_template(t, "trim and strip with none", + "[{{ s|trim(none) }}]|[{{ s|trim(chars=none) }}]|[{{ s.strip(none) }}]|[{{ s.lstrip(none) }}]|[{{ s.rstrip(none) }}]", + {{"s", "\u3000hello\u00a0"}}, + "[hello]|[hello]|[hello]|[hello\u00a0]|[\u3000hello]" + ); + + test_template_error(t, "strip rejects non-string non-none chars", + "{{ 'hello'.strip(123) }}", + "strip() argument must be None or str" + ); + test_template(t, "length string", "{{ 'hello'|length }}", json::object(), From 509468d5aa49609466d9e05e660d8c98c6d07b12 Mon Sep 17 00:00:00 2001 From: Animesh Date: Wed, 2 Dec 2026 01:55:42 +0530 Subject: [PATCH 02/65] ggml-cuda : optimize mmvq nwarps for Pascal DP4A (#25479) --- ggml/src/ggml-cuda/mmvq.cu | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/ggml/src/ggml-cuda/mmvq.cu b/ggml/src/ggml-cuda/mmvq.cu index fad806d76682..5a4a6108bf15 100644 --- a/ggml/src/ggml-cuda/mmvq.cu +++ b/ggml/src/ggml-cuda/mmvq.cu @@ -91,6 +91,7 @@ static constexpr __host__ __device__ int get_vdr_mmvq(ggml_type type) { enum mmvq_parameter_table_id { MMVQ_PARAMETERS_GENERIC = 0, + MMVQ_PARAMETERS_PASCAL_DP4A, MMVQ_PARAMETERS_TURING, MMVQ_PARAMETERS_GCN, MMVQ_PARAMETERS_RDNA1, @@ -118,6 +119,8 @@ static constexpr __device__ mmvq_parameter_table_id get_device_table_id() { return MMVQ_PARAMETERS_GB10; #elif __CUDA_ARCH__ == GGML_CUDA_CC_ORIN return MMVQ_PARAMETERS_ORIN; +#elif defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= GGML_CUDA_CC_DP4A && __CUDA_ARCH__ < GGML_CUDA_CC_VOLTA + return MMVQ_PARAMETERS_PASCAL_DP4A; #else return MMVQ_PARAMETERS_GENERIC; #endif @@ -148,6 +151,9 @@ static __host__ mmvq_parameter_table_id get_device_table_id(int cc) { if (GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) == GGML_CUDA_CC_ORIN) { return MMVQ_PARAMETERS_ORIN; } + if (GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) >= GGML_CUDA_CC_DP4A && ggml_cuda_highest_compiled_arch(cc) < GGML_CUDA_CC_VOLTA) { + return MMVQ_PARAMETERS_PASCAL_DP4A; + } return MMVQ_PARAMETERS_GENERIC; } @@ -478,7 +484,11 @@ static constexpr __device__ int get_mmvq_mmid_max_batch_for_device() { } static constexpr __host__ __device__ int calc_nwarps(ggml_type type, int ncols_dst, mmvq_parameter_table_id table_id, bool small_k = false, bool halve_iters = false) { - if (table_id == MMVQ_PARAMETERS_GENERIC) { + if (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_PASCAL_DP4A) { + // Pascal cc 6.1/6.2 decode is bandwidth-bound on small SMs: 2 warps beat 4 for single-token. + if (table_id == MMVQ_PARAMETERS_PASCAL_DP4A && ncols_dst == 1) { + return 2; + } switch (ncols_dst) { case 1: case 2: @@ -641,7 +651,7 @@ static constexpr __host__ __device__ bool mmvq_two_rows_ncols1(ggml_type type) { } static constexpr __host__ __device__ int calc_rows_per_block(ggml_type type, int ncols_dst, int table_id, bool small_k = false, int nwarps = 1) { - if (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_GCN || table_id == MMVQ_PARAMETERS_TURING || table_id == MMVQ_PARAMETERS_GB10 || table_id == MMVQ_PARAMETERS_RDNA1) { + if (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_PASCAL_DP4A || table_id == MMVQ_PARAMETERS_GCN || table_id == MMVQ_PARAMETERS_TURING || table_id == MMVQ_PARAMETERS_GB10 || table_id == MMVQ_PARAMETERS_RDNA1) { switch (ncols_dst) { case 1: if (small_k) { @@ -650,7 +660,7 @@ static constexpr __host__ __device__ int calc_rows_per_block(ggml_type type, int if (table_id == MMVQ_PARAMETERS_GB10) { return type == GGML_TYPE_IQ2_S || type == GGML_TYPE_IQ3_S ? 2 : 1; } - return (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_RDNA1) && mmvq_two_rows_ncols1(type) ? 2 : 1; + return (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_PASCAL_DP4A || table_id == MMVQ_PARAMETERS_RDNA1) && mmvq_two_rows_ncols1(type) ? 2 : 1; case 2: case 3: case 4: From 92f76e5c564e0510e1e0a9574dc82209d509491b Mon Sep 17 00:00:00 2001 From: Ehsan Bateni Date: Tue, 1 Dec 2026 15:28:58 -0500 Subject: [PATCH 03/65] hexagon: optimize IQ2_XSS grid gathers (#33407) Co-authored-by: Max Krasnyansky --- ggml/src/ggml-hexagon/htp/htp-tensor.h | 11 +++++++++-- ggml/src/ggml-hexagon/htp/iq2xxs-tables.h | 2 +- ggml/src/ggml-hexagon/htp/matmul-internal.h | 9 ++++++--- ggml/src/ggml-hexagon/htp/matmul-ops.c | 22 ++++++++++++++++++++- 4 files changed, 37 insertions(+), 7 deletions(-) diff --git a/ggml/src/ggml-hexagon/htp/htp-tensor.h b/ggml/src/ggml-hexagon/htp/htp-tensor.h index 9d2de3081c92..b02bd963a49f 100644 --- a/ggml/src/ggml-hexagon/htp/htp-tensor.h +++ b/ggml/src/ggml-hexagon/htp/htp-tensor.h @@ -22,11 +22,18 @@ #define HTP_TENSOR_TILE_SIZE_IQ4_NL 576 #define HTP_TENSOR_TILE_SIZE_MXFP4 544 #define HTP_TENSOR_TILE_SIZE_NVFP4 576 -#define HTP_TENSOR_TILE_SIZE_IQ2_XXS 264 +#define HTP_TENSOR_TILE_SIZE_IQ2_XXS 264 #define HTP_TENSOR_TILE_SCRATCH_IQ2_XXS 256 #define HTP_IQ2XXS_NIBBLE_BYTES 128 // 16 words for vlut16, padded to a vector #define HTP_IQ2XXS_GRID_BYTES 512 // 256 entries x 8 elements x 2-bit magnitude code -#define HTP_IQ2XXS_LUT_BYTES (HTP_IQ2XXS_NIBBLE_BYTES + HTP_IQ2XXS_GRID_BYTES) +#define HTP_IQ2XXS_TABLE_BYTES (HTP_IQ2XXS_NIBBLE_BYTES + HTP_IQ2XXS_GRID_BYTES) +#define HTP_IQ2XXS_LANE_OFF_BYTES 128 // per-lane copy offsets for grid gathers, one vector +#define HTP_IQ2XXS_GRID_COPIES 16 // gather lane h reads copy (h % 16) to spread bank conflicts +#define HTP_IQ2XXS_GRID_SKEW 4 // bank skew between copies +#define HTP_IQ2XXS_GRID_STRIDE (HTP_IQ2XXS_GRID_BYTES + HTP_IQ2XXS_GRID_SKEW) +#define HTP_IQ2XXS_GRID_REGION (HTP_IQ2XXS_GRID_COPIES * HTP_IQ2XXS_GRID_STRIDE) +#define HTP_IQ2XXS_GRID_OFF (HTP_IQ2XXS_NIBBLE_BYTES + HTP_IQ2XXS_LANE_OFF_BYTES) +#define HTP_IQ2XXS_LUT_BYTES ((HTP_IQ2XXS_GRID_OFF + HTP_IQ2XXS_GRID_REGION + 127) & ~127) #define HTP_TENSOR_TILE_SIZE_Q4_K 640 #define HTP_TENSOR_TILE_SIZE_Q5_K 768 #define HTP_TENSOR_TILE_SIZE_Q6_K 896 diff --git a/ggml/src/ggml-hexagon/htp/iq2xxs-tables.h b/ggml/src/ggml-hexagon/htp/iq2xxs-tables.h index 5a3dbe26e3ad..8176b5b2fc15 100644 --- a/ggml/src/ggml-hexagon/htp/iq2xxs-tables.h +++ b/ggml/src/ggml-hexagon/htp/iq2xxs-tables.h @@ -8,7 +8,7 @@ #include #include "htp-tensor.h" -static const uint8_t __attribute__((aligned(128))) htp_iq2xxs_lut[HTP_IQ2XXS_LUT_BYTES] = { +static const uint8_t __attribute__((aligned(128))) htp_iq2xxs_lut[HTP_IQ2XXS_TABLE_BYTES] = { 0x08, 0x08, 0x00, 0x00, 0x19, 0x08, 0x00, 0x00, 0x2b, 0x08, 0x00, 0x00, 0x2b, 0x08, 0x00, 0x00, 0x08, 0x19, 0x00, 0x00, 0x19, 0x19, 0x00, 0x00, 0x2b, 0x19, 0x00, 0x00, 0x2b, 0x19, 0x00, 0x00, 0x08, 0x2b, 0x00, 0x00, 0x19, 0x2b, 0x00, 0x00, 0x2b, 0x2b, 0x00, 0x00, 0x2b, 0x2b, 0x00, 0x00, diff --git a/ggml/src/ggml-hexagon/htp/matmul-internal.h b/ggml/src/ggml-hexagon/htp/matmul-internal.h index de4221c47266..51d0697a522a 100644 --- a/ggml/src/ggml-hexagon/htp/matmul-internal.h +++ b/ggml/src/ggml-hexagon/htp/matmul-internal.h @@ -183,7 +183,8 @@ static inline HVX_Vector * iq2xxs_tile_scratch(const uint8_t * tile) { // IQ2_XXS: start the 2 halfword grid-code gathers of a tile into its scratch, returns the sign/scale words static inline HVX_Vector iq2xxs_gather_issue(const uint8_t * restrict tile) { HVX_Vector * restrict v_scr = iq2xxs_tile_scratch(tile); - const uint8_t * grid = iq2xxs_vtcm_lut + HTP_IQ2XXS_NIBBLE_BYTES; + const uint8_t * grid = iq2xxs_vtcm_lut + HTP_IQ2XXS_GRID_OFF; + const HVX_Vector v_lane = hvx_vmem(iq2xxs_vtcm_lut + HTP_IQ2XXS_NIBBLE_BYTES); // lo: 4 grid indices per row, hi: 4 sign indices + scale per row HVX_VectorPair p = Q6_W_vdeal_VVR(hvx_vmem(tile + VLEN), hvx_vmem(tile), -IQ2XXS_WORD_BYTES); @@ -194,8 +195,10 @@ static inline HVX_Vector iq2xxs_gather_issue(const uint8_t * restrict tile) { Q6_V_vand_VV(Q6_Vw_vasl_VwR(v_idx, IQ2XXS_CODE_SHIFT + IQ2XXS_IDX_BITS), Q6_V_vsplat_R(IQ2XXS_IDX_HI_MASK))); HVX_Vector v_off1 = Q6_V_vor_VV(Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_idx, 2 * IQ2XXS_IDX_BITS - IQ2XXS_CODE_SHIFT), Q6_V_vsplat_R(IQ2XXS_IDX_LO_MASK)), Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_idx, IQ2XXS_IDX_BITS - IQ2XXS_CODE_SHIFT), Q6_V_vsplat_R(IQ2XXS_IDX_HI_MASK))); - Q6_vgather_ARMVh(&v_scr[0], (size_t) grid, HTP_IQ2XXS_GRID_BYTES - 1, v_off0); - Q6_vgather_ARMVh(&v_scr[1], (size_t) grid, HTP_IQ2XXS_GRID_BYTES - 1, v_off1); + v_off0 = Q6_Vh_vadd_VhVh(v_off0, v_lane); + v_off1 = Q6_Vh_vadd_VhVh(v_off1, v_lane); + Q6_vgather_ARMVh(&v_scr[0], (size_t) grid, HTP_IQ2XXS_GRID_REGION - 1, v_off0); + Q6_vgather_ARMVh(&v_scr[1], (size_t) grid, HTP_IQ2XXS_GRID_REGION - 1, v_off1); return Q6_V_hi_W(p); } diff --git a/ggml/src/ggml-hexagon/htp/matmul-ops.c b/ggml/src/ggml-hexagon/htp/matmul-ops.c index d8dddef1fea1..289e14c01ffe 100644 --- a/ggml/src/ggml-hexagon/htp/matmul-ops.c +++ b/ggml/src/ggml-hexagon/htp/matmul-ops.c @@ -38,10 +38,30 @@ const uint8_t __attribute__((aligned(VLEN))) kvalues_mxfp4_lut[] = { const uint8_t * iq2xxs_vtcm_lut; +_Static_assert((HTP_IQ2XXS_GRID_COPIES & (HTP_IQ2XXS_GRID_COPIES - 1)) == 0, "grid copies must be a power of 2"); + +// VTCM layout: nibble table, per-lane grid copy offsets, then HTP_IQ2XXS_GRID_COPIES skewed grid copies void iq2xxs_lut_copy(uint8_t * restrict lut) { - for (uint32_t i = 0; i < HTP_IQ2XXS_LUT_BYTES / VLEN; i++) { + uint16_t __attribute__((aligned(VLEN))) lane_off[HTP_IQ2XXS_LANE_OFF_BYTES / sizeof(uint16_t)]; + for (uint32_t h = 0; h < HTP_IQ2XXS_LANE_OFF_BYTES / sizeof(uint16_t); h++) { + lane_off[h] = (h & (HTP_IQ2XXS_GRID_COPIES - 1)) * HTP_IQ2XXS_GRID_STRIDE; + } + + for (uint32_t i = 0; i < HTP_IQ2XXS_NIBBLE_BYTES / VLEN; i++) { hvx_vmem(lut + i * VLEN) = hvx_vmem(htp_iq2xxs_lut + i * VLEN); } + hvx_vmem(lut + HTP_IQ2XXS_NIBBLE_BYTES) = hvx_vmem(lane_off); + + HVX_Vector v_grid[HTP_IQ2XXS_GRID_BYTES / VLEN]; + for (uint32_t i = 0; i < HTP_IQ2XXS_GRID_BYTES / VLEN; i++) { + v_grid[i] = hvx_vmem(htp_iq2xxs_lut + HTP_IQ2XXS_NIBBLE_BYTES + i * VLEN); + } + for (uint32_t c = 0; c < HTP_IQ2XXS_GRID_COPIES; c++) { + for (uint32_t i = 0; i < HTP_IQ2XXS_GRID_BYTES / VLEN; i++) { + hvx_vmemu(lut + HTP_IQ2XXS_GRID_OFF + c * HTP_IQ2XXS_GRID_STRIDE + i * VLEN) = v_grid[i]; + } + } + iq2xxs_vtcm_lut = lut; } From 94be107ac2f2069d8751950487fa7c117242111f Mon Sep 17 00:00:00 2001 From: George Burton <8233643+gecBurton@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:31:39 +0000 Subject: [PATCH 04/65] model: add clef-omni (#33354) * add: model clef-omni Co-authored-by: WestWaters <100190545+WestWaters@users.noreply.github.com> * add: has_lm_head to prevent double loading output.weight * fix: potential key/index error in _load_clef_hparams * remove: trailing ggml_build_forward_expand(gf, cur), fix: provenance comment * add: test_decision_media_order to show that the media order matters * fix: decision_order_media so that media is ordered correctly * fix: comment in llama_tensor_get_type_impl * remove: unsused ggml_build_forward_expand(), fix: comment in build_arch_graph * fix: set min and max vison pixels for ClefOmniMmprojModel * add: decision type for cloudflare-clef-omni and reject video media * add: top-level audio in server-decision.cpp --------- Co-authored-by: WestWaters <100190545+WestWaters@users.noreply.github.com> --- common/common.cpp | 2 + common/common.h | 1 + conversion/__init__.py | 2 + conversion/clef.py | 66 ++++++++++--- gguf-py/gguf/constants.py | 50 ++++++++++ src/llama-arch.cpp | 2 + src/llama-arch.h | 1 + src/llama-model.cpp | 4 + src/llama-quant.cpp | 8 +- src/models/clef-omni.cpp | 96 ++++++++++++++++++ src/models/clef.cpp | 164 +++++++++++++++++-------------- src/models/models.h | 60 ++++++++--- src/models/qwen3vlmoe.cpp | 12 ++- tests/test-llama-archs.cpp | 3 +- tests/test-server-component.cpp | 120 ++++++++++++++++++++++ tools/server/README.md | 16 +-- tools/server/server-common.cpp | 1 + tools/server/server-decision.cpp | 54 ++++++++-- tools/server/server-decision.h | 9 +- 19 files changed, 548 insertions(+), 123 deletions(-) create mode 100644 src/models/clef-omni.cpp diff --git a/common/common.cpp b/common/common.cpp index b009d460d697..da7657d13399 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -1170,6 +1170,7 @@ static const std::map COMMON_DECISION_TYPE_NA { COMMON_DECISION_TYPE_MINICPM_OCR_JEV, "openbmb-minicpm-ocr-jev" }, { COMMON_DECISION_TYPE_LFM3_D1, "lfm3-d1" }, { COMMON_DECISION_TYPE_LFM3_D1_OMNI, "lfm3-d1-omni" }, + { COMMON_DECISION_TYPE_CLEF_OMNI, "cloudflare-clef-omni" }, // for future models, ALWAYS add org name prefix to avoid name collisions, e.g. "orgname-modelname" }; @@ -1298,6 +1299,7 @@ common_init_result::common_init_result(common_params & params, bool model_only) const auto decision_type = common_get_decision_type(model); // minicpm-ocr-jev reads its class scores from the pooled output, the pooling type is the one of the GGUF if (decision_type == COMMON_DECISION_TYPE_LAYA || decision_type == COMMON_DECISION_TYPE_KEV || decision_type == COMMON_DECISION_TYPE_CLEF || + decision_type == COMMON_DECISION_TYPE_CLEF_OMNI || decision_type == COMMON_DECISION_TYPE_LFM2_D1_OMNI || decision_type == COMMON_DECISION_TYPE_VLLM_DECISION2 || decision_type == COMMON_DECISION_TYPE_MINICPM_OCR_JEV) { const auto pooling_type = decision_type == COMMON_DECISION_TYPE_MINICPM_OCR_JEV ? LLAMA_POOLING_TYPE_UNSPECIFIED : LLAMA_POOLING_TYPE_NONE; diff --git a/common/common.h b/common/common.h index aa454944c98b..1d8d57d714a3 100644 --- a/common/common.h +++ b/common/common.h @@ -1002,6 +1002,7 @@ enum common_decision_type { COMMON_DECISION_TYPE_MINICPM_OCR_JEV, // one score per class, the pooled embeddings output of the last token COMMON_DECISION_TYPE_LFM3_D1, // same as lfm2-d1, non-causal, label codes A..Z then AA, AB.. COMMON_DECISION_TYPE_LFM3_D1_OMNI, // same as lfm3-d1 + COMMON_DECISION_TYPE_CLEF_OMNI, // same as clef, with audio input and no video input COMMON_DECISION_TYPE_UNKNOWN, // a decision model of a type that is not supported }; diff --git a/conversion/__init__.py b/conversion/__init__.py index 87624f653205..9b72df673cb6 100644 --- a/conversion/__init__.py +++ b/conversion/__init__.py @@ -50,6 +50,7 @@ "ChatGLMModel": "chatglm", "ChatterboxModel": "chatterbox", "ClefModel": "clef", + "ClefOmniModel": "clef", "CloverMoeModelLM": "clover", "CodeShellForCausalLM": "codeshell", "CogVLMForCausalLM": "cogvlm", @@ -361,6 +362,7 @@ "AudioFlamingo3ForConditionalGeneration": "ultravox", "ChatterboxModel": "chatterbox", "ClefModel": "clef", + "ClefOmniModel": "clef", "CogVLMForCausalLM": "cogvlm", "Cohere2VisionForConditionalGeneration": "command_r", "PplxDeciderModel": "pplx_decider", diff --git a/conversion/clef.py b/conversion/clef.py index b793d92c8d32..ff9afa801c1b 100644 --- a/conversion/clef.py +++ b/conversion/clef.py @@ -4,7 +4,7 @@ import math from pathlib import Path -from typing import Any, Iterable, Iterator, TYPE_CHECKING +from typing import Any, Callable, Iterable, Iterator, TYPE_CHECKING import torch @@ -13,7 +13,7 @@ from .base import ModelBase, gguf, logger from .qwen import Qwen3_5TextModel -from .qwen3vl import Qwen3VLVisionModel +from .qwen3vl import Qwen3OmniMmprojModel, Qwen3OmniMoeTextModel, Qwen3VLVisionModel def _is_clef_checkpoint(dir_model: Path) -> bool: @@ -24,16 +24,16 @@ def _is_clef_checkpoint(dir_model: Path) -> bool: def _load_clef_hparams(dir_model: Path) -> dict[str, Any]: logger.info("gguf: detected Clef checkpoint") hparams = ModelBase.load_hparams(dir_model, False, guess=False) - hparams["architectures"] = ["ClefModel"] + # clef-omni has the same head on the Qwen3-Omni thinker + is_omni = "thinker_config" in hparams + hparams["architectures"] = ["ClefOmniModel" if is_omni else "ClefModel"] with open(dir_model / "joint_head_config.json", encoding="utf-8") as f: hparams["decision"] = json.load(f) return hparams -@ModelBase.register("ClefModel") -class ClefModel(Qwen3_5TextModel): - model_arch = gguf.MODEL_ARCH.CLEF - no_mtp = True # the checkpoint has no MTP head +class _ClefHeadMixin: + # the joint schema head, on top of the text model of the class that uses this mixin # prompt follows joint_schema_model.py of the model repo _SYSTEM_PROMPT = ( @@ -42,6 +42,17 @@ class ClefModel(Qwen3_5TextModel): ) # torch.nn.LayerNorm default, used by the head _HEAD_NORM_EPS = 1e-5 + # clef-omni puts a newline after each image, clef after all of them + _NEWLINE_PER_IMAGE = False + _DECISION_TYPE = gguf.DecisionType.CLEF + + model_arch: gguf.MODEL_ARCH + hparams: dict[str, Any] + block_count: int + gguf_writer: gguf.GGUFWriter + dir_model: Path + format_tensor_name: Callable[..., str] + map_tensor_name: Callable[..., str] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -52,7 +63,7 @@ def __init__(self, *args, **kwargs): self._scales: dict[str, float] = {} def set_vocab(self): - super().set_vocab() + super().set_vocab() # ty: ignore[missing-attribute] self.gguf_writer.add_chat_template([{"name": "systemone", "template": self._systemone_template()}]) @classmethod @@ -75,9 +86,13 @@ def render(name: str) -> str: "{% endif %}" "{{ ({'option_id': o.key} if d is none else {'description': d, 'option_id': o.key}) | tojson(separators=[',', ':']) }}" ) + if cls._NEWLINE_PER_IMAGE: + images = "{% for image in images %}{{ image }}" + text("\n") + "{% endfor %}" + else: + images = "{% for image in images %}{{ image }}{% endfor %}" + text("\n") return ( text(f"<|im_start|>system\n{cls._SYSTEM_PROMPT}<|im_end|>\n<|im_start|>user\nSTATE:\n") - + "{% if images %}{{ sep }}{% for image in images %}{{ image }}{% endfor %}" + text("\n") + "{% endif %}" + + "{% if images %}{{ sep }}" + images + "{% endif %}" + "{{ sep }}" + render("state") + "{{ sep }}" + text("\n\nSCHEMA FIELDS:\n") + "{% for q in questions %}" @@ -96,23 +111,23 @@ def render(name: str) -> str: ) def set_gguf_parameters(self): - super().set_gguf_parameters() + super().set_gguf_parameters() # ty: ignore[missing-attribute] head = self.hparams["decision"] - self.gguf_writer.add_decision_type(gguf.DecisionType.CLEF) + self.gguf_writer.add_decision_type(self._DECISION_TYPE) self.gguf_writer.add_decision_routing_block_count(head["routing_layers"]) self.gguf_writer.add_decision_block_count(head["layers"]) self.gguf_writer.add_decision_head_count(head["heads"]) self.gguf_writer.add_layer_norm_eps(self._HEAD_NORM_EPS) def get_tensors(self) -> Iterator[tuple[str, Tensor]]: - yield from super().get_tensors() + yield from super().get_tensors() # ty: ignore[missing-attribute] from safetensors.torch import load_file for name, data in load_file(self.dir_model / "joint_head.safetensors").items(): yield "joint_head." + name, data def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: if not name.startswith("joint_head."): - yield from super().modify_tensors(data_torch, name, bid) + yield from super().modify_tensors(data_torch, name, bid) # ty: ignore[missing-attribute] return parts = name.split(".") @@ -145,6 +160,31 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter yield self.map_tensor_name(name), data_torch +@ModelBase.register("ClefModel") +class ClefModel(_ClefHeadMixin, Qwen3_5TextModel): + model_arch = gguf.MODEL_ARCH.CLEF + no_mtp = True # the checkpoint has no MTP head + + @ModelBase.register("ClefModel") class ClefVisionModel(Qwen3VLVisionModel): pass + + +@ModelBase.register("ClefOmniModel") +class ClefOmniModel(_ClefHeadMixin, Qwen3OmniMoeTextModel): + model_arch = gguf.MODEL_ARCH.CLEF_OMNI + _NEWLINE_PER_IMAGE = True + _DECISION_TYPE = gguf.DecisionType.CLEF_OMNI + + +@ModelBase.register("ClefOmniModel") +class ClefOmniMmprojModel(Qwen3OmniMmprojModel): + # IMAGE_SIZE of joint_schema_model.py, the image budget is set there and not in the processor config + _IMAGE_MIN_PIXELS = 65_536 + _IMAGE_MAX_PIXELS = 1_048_576 + + def set_gguf_parameters(self): + super().set_gguf_parameters() + self.gguf_writer.add_vision_min_pixels(self._IMAGE_MIN_PIXELS) + self.gguf_writer.add_vision_max_pixels(self._IMAGE_MAX_PIXELS) diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py index ccae76f8282b..43dc461ae563 100644 --- a/gguf-py/gguf/constants.py +++ b/gguf-py/gguf/constants.py @@ -653,6 +653,7 @@ class MODEL_ARCH(IntEnum): QWEN35MOE = auto() CLEF = auto() VLLM_DECISION2 = auto() + CLEF_OMNI = auto() CLOVER_MOE = auto() QWEN4EXP = auto() PHI2 = auto() @@ -1684,6 +1685,7 @@ class MODEL_TENSOR(IntEnum): MODEL_ARCH.QWEN35MOE: "qwen35moe", MODEL_ARCH.CLEF: "clef", MODEL_ARCH.VLLM_DECISION2: "vllm-decision2", + MODEL_ARCH.CLEF_OMNI: "clef-omni", MODEL_ARCH.CLOVER_MOE: "clover_moe", MODEL_ARCH.QWEN4EXP: "qwen4exp", MODEL_ARCH.PHI2: "phi2", @@ -3775,6 +3777,53 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.DECISION_SCORER, MODEL_TENSOR.DECISION_SCORER_OUT, ], + MODEL_ARCH.CLEF_OMNI: [ + MODEL_TENSOR.TOKEN_EMBD, + MODEL_TENSOR.OUTPUT_NORM, + MODEL_TENSOR.OUTPUT, + MODEL_TENSOR.ATTN_NORM, + MODEL_TENSOR.ATTN_Q, + MODEL_TENSOR.ATTN_Q_NORM, + MODEL_TENSOR.ATTN_K, + MODEL_TENSOR.ATTN_K_NORM, + MODEL_TENSOR.ATTN_V, + MODEL_TENSOR.ATTN_OUT, + MODEL_TENSOR.ATTN_QKV, + MODEL_TENSOR.FFN_NORM, + MODEL_TENSOR.FFN_GATE_INP, + MODEL_TENSOR.FFN_DOWN_EXP, + MODEL_TENSOR.FFN_UP_EXP, + MODEL_TENSOR.FFN_GATE_EXP, + # decision head + MODEL_TENSOR.TOKEN_TYPES, + MODEL_TENSOR.DEC_ATTN_NORM, + MODEL_TENSOR.DEC_ATTN_Q, + MODEL_TENSOR.DEC_ATTN_K, + MODEL_TENSOR.DEC_ATTN_V, + MODEL_TENSOR.DEC_ATTN_OUT, + MODEL_TENSOR.DEC_CROSS_ATTN_NORM, + MODEL_TENSOR.DEC_CROSS_ATTN_NORM_KV, + MODEL_TENSOR.DEC_CROSS_ATTN_Q, + MODEL_TENSOR.DEC_CROSS_ATTN_K, + MODEL_TENSOR.DEC_CROSS_ATTN_V, + MODEL_TENSOR.DEC_CROSS_ATTN_OUT, + MODEL_TENSOR.DEC_FFN_NORM, + MODEL_TENSOR.DEC_FFN_DOWN, + MODEL_TENSOR.DEC_FFN_UP, + MODEL_TENSOR.DECISION_HIDDEN_NORM, + MODEL_TENSOR.DECISION_PROJ_MEMORY, + MODEL_TENSOR.DECISION_PROJ_QUESTION, + MODEL_TENSOR.DECISION_PROJ_OPTION_QUESTION, + MODEL_TENSOR.DECISION_PROJ_GLOBAL, + MODEL_TENSOR.DECISION_PROJ_OPTION_CONTEXT, + MODEL_TENSOR.DECISION_PROJ_OPTION_LEXICAL, + MODEL_TENSOR.DECISION_OPTION_SUMMARY_NORM, + MODEL_TENSOR.DECISION_FIELD_NORM, + MODEL_TENSOR.DECISION_OPTION_NORM, + MODEL_TENSOR.DECISION_SCALES, + MODEL_TENSOR.DECISION_SCORER, + MODEL_TENSOR.DECISION_SCORER_OUT, + ], MODEL_ARCH.VLLM_DECISION2: [ MODEL_TENSOR.TOKEN_EMBD, MODEL_TENSOR.OUTPUT_NORM, @@ -7654,6 +7703,7 @@ class DecisionType: GRANITE_SWITCH = "granite-switch" # same as openjev, run by the decision aLoRA of granite switch H2O_LIGHTNING = "h2o-lightning" # same as openjev, labels read after an answer prefill MINICPM_OCR_JEV = "openbmb-minicpm-ocr-jev" # class scores of a value head read at the last token, one fixed task + CLEF_OMNI = "cloudflare-clef-omni" # same as clef on the Qwen3-Omni thinker, with audio input and no video input class VisionProjectorType: diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index e78c3d2a8479..f41434f7ab7a 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -45,6 +45,7 @@ static const std::map LLM_ARCH_NAMES = { { LLM_ARCH_QWEN35, "qwen35" }, { LLM_ARCH_QWEN35MOE, "qwen35moe" }, { LLM_ARCH_CLEF, "clef" }, + { LLM_ARCH_CLEF_OMNI, "clef-omni" }, { LLM_ARCH_VLLM_DECISION2, "vllm-decision2" }, { LLM_ARCH_QWEN4EXP, "qwen4exp" }, { LLM_ARCH_PHI2, "phi2" }, @@ -1655,6 +1656,7 @@ bool llama_arch_supports_save(llm_arch arch) { case LLM_ARCH_T5: case LLM_ARCH_STEP35: case LLM_ARCH_CLEF: // the head tensors are not saved + case LLM_ARCH_CLEF_OMNI: case LLM_ARCH_INKLING2_LOOP: // the loop tensors are not saved and the cache slots are expanded at load case LLM_ARCH_VLLM_DECISION2: return false; diff --git a/src/llama-arch.h b/src/llama-arch.h index 03e8b8c80e61..7508fd2af0dd 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -48,6 +48,7 @@ enum llm_arch { LLM_ARCH_QWEN35, LLM_ARCH_QWEN35MOE, LLM_ARCH_CLEF, + LLM_ARCH_CLEF_OMNI, LLM_ARCH_VLLM_DECISION2, LLM_ARCH_CLOVER_MOE, LLM_ARCH_QWEN4EXP, diff --git a/src/llama-model.cpp b/src/llama-model.cpp index 7b6e9ea118f2..4de14366632a 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -373,6 +373,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params return new llama_model_qwen35moe(params); case LLM_ARCH_CLEF: return new llama_model_clef(params); + case LLM_ARCH_CLEF_OMNI: + return new llama_model_clef_omni(params); case LLM_ARCH_VLLM_DECISION2: return new llama_model_vllm_decision2(params); case LLM_ARCH_CLOVER_MOE: @@ -3044,6 +3046,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, case LLM_ARCH_LLADA_MOE: case LLM_ARCH_RND1: case LLM_ARCH_CLEF: + case LLM_ARCH_CLEF_OMNI: case LLM_ARCH_KOKORO: case LLM_ARCH_TINY_VOCA: { @@ -3977,6 +3980,7 @@ llama_rope_type llama_model_rope_type(const llama_model * model) { case LLM_ARCH_QWEN35: case LLM_ARCH_QWEN35MOE: case LLM_ARCH_CLEF: + case LLM_ARCH_CLEF_OMNI: case LLM_ARCH_QWEN4EXP: case LLM_ARCH_QWEN3TTS: return LLAMA_ROPE_TYPE_IMROPE; diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp index 38eb0d588ba8..2c93e16dca8f 100644 --- a/src/llama-quant.cpp +++ b/src/llama-quant.cpp @@ -528,7 +528,13 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type if (n_expert > 1) { // 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 (sscanf(tname, "blk.%d.", &i_layer) != 1) { + // the blocks of a decision head use their own numbering, block N is treated like backbone layer N + if (sscanf(tname, "dec.blk.%d.", &i_layer) == 1) { + return std::make_pair(i_layer, n_layer); + } + 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)); } } diff --git a/src/models/clef-omni.cpp b/src/models/clef-omni.cpp new file mode 100644 index 000000000000..d54332cf018d --- /dev/null +++ b/src/models/clef-omni.cpp @@ -0,0 +1,96 @@ +#include "models.h" + +void llama_model_clef_omni::load_arch_hparams(llama_model_loader & ml) { + llama_model_qwen3vlmoe::load_arch_hparams(ml); + head.load_hparams(ml, hparams); +} + +void llama_model_clef_omni::load_arch_tensors(llama_model_loader & ml) { + llama_model_qwen3vlmoe::load_arch_tensors(ml); + head.load_tensors(ml, *this); +} + +std::unique_ptr llama_model_clef_omni::build_arch_graph(const llm_graph_params & params) const { + return std::make_unique(params); +} + +// the backbone is copied from llama_model_qwen3vlmoe::graph, without the memory module +// it also drops inp_out_ids (the head reads all tokens) and build_cvec(), as clef does +llama_model_clef_omni::graph::graph(const llm_graph_params & params) : llm_graph_context(params) { + const auto & model = static_cast(*params.model); + + const int64_t n_embd_head = hparams.n_embd_head_v(); + + GGML_ASSERT(n_embd_head == hparams.n_embd_head_k()); + GGML_ASSERT(n_embd_head == n_rot); + + ggml_tensor * cur; + ggml_tensor * inpL; + + inpL = build_inp_embd(model.tok_embd); + + ggml_tensor * inp_pos = build_inp_pos(); + + auto * inp_attn = llama_clef_head::build_attn_inp_causal(*this); + + for (int il = 0; il < n_layer; ++il) { + ggml_tensor * inpSA = inpL; + + cur = build_norm(inpL, model.layers[il].attn_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "attn_norm", il); + + auto [Qcur, Kcur, Vcur] = build_qkv(model.layers[il], cur, n_embd_head, n_head, n_head_kv, il); + + Qcur = build_norm(Qcur, model.layers[il].attn_q_norm, NULL, LLM_NORM_RMS, il); + cb(Qcur, "Qcur_normed", il); + + Qcur = build_rope(Qcur, inp_pos, il); + + Kcur = build_norm(Kcur, model.layers[il].attn_k_norm, NULL, LLM_NORM_RMS, il); + cb(Kcur, "Kcur_normed", il); + + Kcur = build_rope(Kcur, inp_pos, il); + + cur = build_attn(inp_attn, + model.layers[il].wo, model.layers[il].wo_b, + Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f/sqrtf(float(n_embd_head)), il); + + ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA); + cb(ffn_inp, "ffn_inp", il); + + cur = build_norm(ffn_inp, model.layers[il].ffn_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "ffn_norm", il); + + cur = build_moe_ffn(cur, + model.layers[il].ffn_gate_inp, + model.layers[il].ffn_up_exps, + model.layers[il].ffn_gate_exps, + model.layers[il].ffn_down_exps, + nullptr, + n_expert, n_expert_used, + LLM_FFN_SILU, true, + hparams.expert_weights_scale, + LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, + il); + cb(cur, "ffn_moe_out", il); + + cur = ggml_add(ctx0, cur, ffn_inp); + cb(cur, "l_out", il); + + if (il < (int) hparams.n_deepstack_layers) { + ggml_tensor * ds = ggml_view_2d(ctx0, res->t_inp_embd, n_embd, n_tokens, res->t_inp_embd->nb[1], (il + 1) * n_embd * sizeof(float)); + cur = ggml_add(ctx0, cur, ds); + cb(cur, "deepstack_out", il); + } + + inpL = cur; + } + + cur = build_norm(inpL, model.output_norm, NULL, LLM_NORM_RMS, -1); + cb(cur, "result_norm", -1); + + // the head is always evaluated, so that the graph has the same nodes for every batch + cur = model.head.build(*this, cur); + + res->t_embd = cur; +} diff --git a/src/models/clef.cpp b/src/models/clef.cpp index d7d94f49b825..13756147612a 100644 --- a/src/models/clef.cpp +++ b/src/models/clef.cpp @@ -5,9 +5,7 @@ #include #include -void llama_model_clef::load_arch_hparams(llama_model_loader & ml) { - llama_model_qwen35::load_arch_hparams(ml); - +void llama_clef_head::load_hparams(llama_model_loader & ml, llama_hparams & hparams) { ml.get_key(LLM_KV_DECISION_ROUTING_BLOCK_COUNT, n_layer_routing); ml.get_key(LLM_KV_DECISION_BLOCK_COUNT, n_layer_joint); ml.get_key(LLM_KV_DECISION_HEAD_COUNT, n_head_decision); @@ -23,10 +21,18 @@ void llama_model_clef::load_arch_hparams(llama_model_loader & ml) { hparams.n_embd_out_impl = 1; } -void llama_model_clef::load_arch_tensors(llama_model_loader & ml) { - llama_model_qwen35::load_arch_tensors(ml); +void llama_model_clef::load_arch_hparams(llama_model_loader & ml) { + llama_model_qwen35::load_arch_hparams(ml); + head.load_hparams(ml, hparams); +} - LLAMA_LOAD_LOCALS; +void llama_clef_head::load_tensors(llama_model_loader & ml, llama_model_base & model) { + const auto & tn = model.tn; + const int64_t n_embd = model.hparams.n_embd; + + auto create_tensor = [&](const LLM_TN_IMPL & name, const std::initializer_list & ne, int flags) { + return model.create_tensor(ml, name, ne, flags); + }; const auto * w_memory = ml.get_weight(tn(LLM_TENSOR_DECISION_PROJ_MEMORY, "weight").str().c_str()); const auto * w_ffn = ml.get_weight(tn(LLM_TENSOR_DEC_FFN_UP, "weight", 0).str().c_str()); @@ -82,10 +88,10 @@ void llama_model_clef::load_arch_tensors(llama_model_loader & ml) { load_norm(field_norm, LLM_TENSOR_DECISION_FIELD_NORM, n_embd_h); load_norm(option_norm, LLM_TENSOR_DECISION_OPTION_NORM, n_embd_h); - output_lexical = create_tensor(tn(LLM_TENSOR_OUTPUT_LEXICAL, "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED); + output_lexical = create_tensor(tn(LLM_TENSOR_OUTPUT_LEXICAL, "weight"), {n_embd, model.vocab.n_tokens()}, model.TENSOR_NOT_REQUIRED); if (output_lexical == nullptr) { - output_lexical = tok_embd; + output_lexical = model.tok_embd; } proj_memory = create_tensor(tn(LLM_TENSOR_DECISION_PROJ_MEMORY, "weight"), {n_embd, n_embd_h}, 0); @@ -104,6 +110,11 @@ void llama_model_clef::load_arch_tensors(llama_model_loader & ml) { scorer_out_b = create_tensor(tn(LLM_TENSOR_DECISION_SCORER_OUT, "bias"), {1}, 0); } +void llama_model_clef::load_arch_tensors(llama_model_loader & ml) { + llama_model_qwen35::load_arch_tensors(ml); + head.load_tensors(ml, *this); +} + std::unique_ptr llama_model_clef::build_arch_graph(const llm_graph_params & params) const { return std::make_unique(params); } @@ -185,7 +196,7 @@ static size_t clef_n_questions(int64_t n_tokens) { return n_tokens / 2 + 1; } static size_t clef_n_options (int64_t n_tokens) { return std::max(n_tokens - 1, 1); } // pooling matrices and indices computed from the spans -class llama_model_clef::input_decision : public llm_graph_input_i { +class llama_clef_head::input_decision : public llm_graph_input_i { public: input_decision(const llama_ubatch & ubatch) : n_tokens(ubatch.n_tokens), n_questions(clef_n_questions(n_tokens)), n_options(clef_n_options(n_tokens)) {} @@ -277,11 +288,7 @@ llama_model_clef::graph::graph(const llm_graph_params & params) : ggml_tensor * inp_pos = build_inp_pos(); - auto * inp_attn = build_attn_inp_causal(); - - auto inp_decision_ptr = std::make_unique(ubatch); - auto * inp_decision = inp_decision_ptr.get(); - res->add_input(std::move(inp_decision_ptr)); + auto * inp_attn = llama_clef_head::build_attn_inp_causal(*this); for (int il = 0; il < n_layer; ++il) { ggml_tensor * inpSA = inpL; @@ -321,16 +328,9 @@ llama_model_clef::graph::graph(const llm_graph_params & params) : cb(cur, "result_norm", -1); // the head is always evaluated, so that the graph has the same nodes for every batch - cur = build_head(cur, inp_decision); - - // row i of the output is the score of option i - cur = ggml_pad(ctx0, cur, 0, n_tokens - cur->ne[1], 0, 0); - cur = ggml_add(ctx0, cur, inp_decision->status); - cb(cur, "result_decision", -1); + cur = model.head.build(*this, cur); res->t_embd = cur; - - ggml_build_forward_expand(gf, cur); } // causal mask by batch order: the tokens of an image share the same position @@ -361,16 +361,16 @@ class llm_graph_input_attn_clef : public llm_graph_input_attn_no_cache { }; // same as build_attn_inp_no_cache(), with a causal mask even if the batch is processed by the encoder path -llm_graph_input_attn_no_cache * llama_model_clef::graph::build_attn_inp_causal() { - auto inp = std::make_unique(hparams, cparams); +llm_graph_input_attn_no_cache * llama_clef_head::build_attn_inp_causal(const llm_graph_context & ctx) { + auto inp = std::make_unique(ctx.hparams, ctx.cparams); - const auto type_mask = cparams.flash_attn ? GGML_TYPE_F16 : GGML_TYPE_F32; + const auto type_mask = ctx.cparams.flash_attn ? GGML_TYPE_F16 : GGML_TYPE_F32; - inp->self_attn_mask.raw = ggml_new_tensor_4d(ctx0, type_mask, GGML_PAD(n_tokens, 256), n_tokens, 1, 1); + inp->self_attn_mask.raw = ggml_new_tensor_4d(ctx.ctx0, type_mask, GGML_PAD(ctx.n_tokens, 256), ctx.n_tokens, 1, 1); ggml_set_input(inp->self_attn_mask.raw); - cb(inp->self_attn_mask.raw, "self_kq_mask", -1); + ctx.cb(inp->self_attn_mask.raw, "self_kq_mask", -1); - return (llm_graph_input_attn_no_cache *) res->add_input(std::move(inp)); + return (llm_graph_input_attn_no_cache *) ctx.res->add_input(std::move(inp)); } ggml_tensor * llama_model_clef::graph::build_layer_attn( @@ -496,21 +496,23 @@ ggml_tensor * llama_model_clef::graph::build_layer_attn_linear( return ggml_reshape_2d(ctx0, cur, n_embd, n_tokens); } -ggml_tensor * llama_model_clef::graph::build_head_norm(ggml_tensor * cur, const norm & n) { - return build_norm(cur, n.w, n.b, LLM_NORM, -1); +ggml_tensor * llama_clef_head::build_head_norm(const llm_graph_context & ctx, ggml_tensor * cur, const norm & n) const { + return ctx.build_norm(cur, n.w, n.b, LLM_NORM, -1); } // q: [n_embd_h, n_q], kv: [n_embd_h, n_kv], kq_mask: [n_kv, n_q] or null -ggml_tensor * llama_model_clef::graph::build_head_attn(ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask) { +ggml_tensor * llama_clef_head::build_head_attn(const llm_graph_context & ctx, ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask) const { + ggml_context * ctx0 = ctx.ctx0; + const int64_t n_embd_h = q->ne[0]; - const int64_t n_head_h = model.n_head_decision; + const int64_t n_head_h = n_head_decision; const int64_t d_head = n_embd_h / n_head_h; const int64_t n_q = q->ne[1]; const int64_t n_kv = kv->ne[1]; - ggml_tensor * Qcur = ggml_add(ctx0, build_lora_mm(a.wq, q), a.bq); - ggml_tensor * Kcur = ggml_add(ctx0, build_lora_mm(a.wk, kv), a.bk); - ggml_tensor * Vcur = ggml_add(ctx0, build_lora_mm(a.wv, kv), a.bv); + ggml_tensor * Qcur = ggml_add(ctx0, ctx.build_lora_mm(a.wq, q), a.bq); + ggml_tensor * Kcur = ggml_add(ctx0, ctx.build_lora_mm(a.wk, kv), a.bk); + ggml_tensor * Vcur = ggml_add(ctx0, ctx.build_lora_mm(a.wv, kv), a.bv); Qcur = ggml_permute(ctx0, ggml_reshape_3d(ctx0, Qcur, d_head, n_head_h, n_q), 0, 2, 1, 3); // [d_head, n_q, n_head] Kcur = ggml_permute(ctx0, ggml_reshape_3d(ctx0, Kcur, d_head, n_head_h, n_kv), 0, 2, 1, 3); // [d_head, n_kv, n_head] @@ -523,18 +525,29 @@ ggml_tensor * llama_model_clef::graph::build_head_attn(ggml_tensor * q, ggml_ten ggml_tensor * cur = ggml_mul_mat(ctx0, Vcur, kq); // [d_head, n_q, n_head] cur = ggml_cont_2d(ctx0, ggml_permute(ctx0, cur, 0, 2, 1, 3), n_embd_h, n_q); - return ggml_add(ctx0, build_lora_mm(a.wo, cur), a.bo); + return ggml_add(ctx0, ctx.build_lora_mm(a.wo, cur), a.bo); } -ggml_tensor * llama_model_clef::graph::build_head_ffn(ggml_tensor * cur, const head_layer & layer) { - cur = build_head_norm(cur, layer.ffn_norm); - cur = ggml_add(ctx0, build_lora_mm(layer.ffn_up, cur), layer.ffn_up_b); +ggml_tensor * llama_clef_head::build_head_ffn(const llm_graph_context & ctx, ggml_tensor * cur, const head_layer & layer) const { + ggml_context * ctx0 = ctx.ctx0; + + cur = build_head_norm(ctx, cur, layer.ffn_norm); + cur = ggml_add(ctx0, ctx.build_lora_mm(layer.ffn_up, cur), layer.ffn_up_b); cur = ggml_gelu_erf(ctx0, cur); - return ggml_add(ctx0, build_lora_mm(layer.ffn_down, cur), layer.ffn_down_b); + return ggml_add(ctx0, ctx.build_lora_mm(layer.ffn_down, cur), layer.ffn_down_b); } // ref: JointSchemaHead in joint_schema_model.py of the model repo -ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_decision * inp) { +ggml_tensor * llama_clef_head::build(const llm_graph_context & ctx, ggml_tensor * hidden) const { + ggml_context * ctx0 = ctx.ctx0; + + const int64_t n_embd = hidden->ne[0]; + const int64_t n_tokens = hidden->ne[1]; + + auto inp_ptr = std::make_unique(ctx.ubatch); + auto * inp = inp_ptr.get(); + ctx.res->add_input(std::move(inp_ptr)); + const int64_t n_questions = inp->n_questions; const int64_t n_options = inp->n_options; @@ -550,9 +563,9 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de ggml_set_input(t); } - hidden = build_head_norm(hidden, model.hidden_norm); + hidden = build_head_norm(ctx, hidden, hidden_norm); - ggml_tensor * memory = build_lora_mm(model.proj_memory, hidden); // [n_embd_h, n_tokens] + ggml_tensor * memory = ctx.build_lora_mm(proj_memory, hidden); // [n_embd_h, n_tokens] const int64_t n_embd_h = memory->ne[0]; @@ -565,29 +578,29 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de ggml_tensor * opt_ctx = ggml_mul_mat(ctx0, hidden_t, inp->pool_o); // [n_embd, n_options] // mean of the output embeddings of the tokens of each option - ggml_tensor * lexical = ggml_get_rows(ctx0, model.output_lexical, inp->tokens); + ggml_tensor * lexical = ggml_get_rows(ctx0, output_lexical, inp->tokens); lexical = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, lexical)), inp->pool_o); // [n_embd, n_options] // one query per option - ggml_tensor * options = build_lora_mm(model.proj_option_context, opt_ctx); - options = ggml_add(ctx0, options, build_lora_mm(model.proj_option_lexical, lexical)); - options = ggml_add(ctx0, options, ggml_get_rows(ctx0, build_lora_mm(model.proj_option_question, question), inp->option_question)); + ggml_tensor * options = ctx.build_lora_mm(proj_option_context, opt_ctx); + options = ggml_add(ctx0, options, ctx.build_lora_mm(proj_option_lexical, lexical)); + options = ggml_add(ctx0, options, ggml_get_rows(ctx0, ctx.build_lora_mm(proj_option_question, question), inp->option_question)); // the options read the prompt - for (uint32_t il = 0; il < model.n_layer_routing; ++il) { - const auto & layer = model.head_layers[il]; + for (uint32_t il = 0; il < n_layer_routing; ++il) { + const auto & layer = head_layers[il]; - ggml_tensor * cur = build_head_attn( - build_head_norm(options, layer.cross_norm), - build_head_norm(memory, layer.cross_norm_kv), + ggml_tensor * cur = build_head_attn(ctx, + build_head_norm(ctx, options, layer.cross_norm), + build_head_norm(ctx, memory, layer.cross_norm_kv), layer.cross_attn); options = ggml_add(ctx0, options, cur); - options = ggml_add(ctx0, options, build_head_ffn(options, layer)); + options = ggml_add(ctx0, options, build_head_ffn(ctx, options, layer)); } - cb(options, "decision_options", -1); + ctx.cb(options, "decision_options", -1); // one vector per question: its text, a summary of its options, the end of the prompt and its type - ggml_tensor * fields = build_lora_mm(model.proj_question, question); // [n_embd_h, n_questions] + ggml_tensor * fields = ctx.build_lora_mm(proj_question, question); // [n_embd_h, n_questions] { // each question weights its own options ggml_tensor * weights = ggml_mul_mat(ctx0, options, fields); // [n_options, n_questions] @@ -596,25 +609,25 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de ggml_tensor * summary = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, options)), weights); - fields = ggml_add(ctx0, fields, build_head_norm(summary, model.option_summary_norm)); - fields = ggml_add(ctx0, fields, build_lora_mm(model.proj_global, global)); - fields = ggml_add(ctx0, fields, ggml_get_rows(ctx0, model.type_embd, inp->question_type)); + fields = ggml_add(ctx0, fields, build_head_norm(ctx, summary, option_summary_norm)); + fields = ggml_add(ctx0, fields, ctx.build_lora_mm(proj_global, global)); + fields = ggml_add(ctx0, fields, ggml_get_rows(ctx0, type_embd, inp->question_type)); } // the questions read each other and the prompt - for (uint32_t il = model.n_layer_routing; il < model.head_layers.size(); ++il) { - const auto & layer = model.head_layers[il]; + for (uint32_t il = n_layer_routing; il < head_layers.size(); ++il) { + const auto & layer = head_layers[il]; - ggml_tensor * cur = build_head_norm(fields, layer.self_norm); - fields = ggml_add(ctx0, fields, build_head_attn(cur, cur, layer.self_attn, inp->question_mask)); + ggml_tensor * cur = build_head_norm(ctx, fields, layer.self_norm); + fields = ggml_add(ctx0, fields, build_head_attn(ctx, cur, cur, layer.self_attn, inp->question_mask)); - cur = build_head_norm(fields, layer.cross_norm); - fields = ggml_add(ctx0, fields, build_head_attn(cur, memory, layer.cross_attn)); + cur = build_head_norm(ctx, fields, layer.cross_norm); + fields = ggml_add(ctx0, fields, build_head_attn(ctx, cur, memory, layer.cross_attn)); - fields = ggml_add(ctx0, fields, build_head_ffn(fields, layer)); + fields = ggml_add(ctx0, fields, build_head_ffn(ctx, fields, layer)); } - fields = build_head_norm(fields, model.field_norm); - cb(fields, "decision_fields", -1); + fields = build_head_norm(ctx, fields, field_norm); + ctx.cb(fields, "decision_fields", -1); const float eps = 1e-12f; @@ -624,7 +637,7 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de ggml_tensor * prior = ggml_sum_rows(ctx0, ggml_mul(ctx0, ggml_l2_norm(ctx0, lexical, eps), anchor)); // [1, n_options] // joint: each option against the vector of its question - options = build_head_norm(options, model.option_norm); + options = build_head_norm(ctx, options, option_norm); ggml_tensor * field = ggml_get_rows(ctx0, fields, inp->option_question); // [n_embd_h, n_options] ggml_tensor * cosine = ggml_sum_rows(ctx0, ggml_mul(ctx0, ggml_l2_norm(ctx0, field, eps), ggml_l2_norm(ctx0, options, eps))); @@ -633,15 +646,22 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de features = ggml_concat(ctx0, features, ggml_mul(ctx0, field, options), 0); features = ggml_concat(ctx0, features, ggml_abs(ctx0, ggml_sub(ctx0, field, options)), 0); - ggml_tensor * residual = ggml_add(ctx0, build_lora_mm(model.scorer, features), model.scorer_b); + ggml_tensor * residual = ggml_add(ctx0, ctx.build_lora_mm(scorer, features), scorer_b); residual = ggml_gelu_erf(ctx0, residual); - residual = ggml_add(ctx0, build_lora_mm(model.scorer_out, residual), model.scorer_out_b); // [1, n_options] + residual = ggml_add(ctx0, ctx.build_lora_mm(scorer_out, residual), scorer_out_b); // [1, n_options] auto scale = [&](int i) { - return ggml_view_1d(ctx0, model.scales, 1, i * ggml_element_size(model.scales)); + return ggml_view_1d(ctx0, scales, 1, i * ggml_element_size(scales)); }; ggml_tensor * joint = ggml_add(ctx0, ggml_mul(ctx0, cosine, scale(1)), residual); - return ggml_add(ctx0, ggml_mul(ctx0, prior, scale(0)), ggml_mul(ctx0, joint, scale(2))); + ggml_tensor * cur = ggml_add(ctx0, ggml_mul(ctx0, prior, scale(0)), ggml_mul(ctx0, joint, scale(2))); + + // row i of the output is the score of option i + cur = ggml_pad(ctx0, cur, 0, n_tokens - cur->ne[1], 0, 0); + cur = ggml_add(ctx0, cur, inp->status); + ctx.cb(cur, "result_decision", -1); + + return cur; } diff --git a/src/models/models.h b/src/models/models.h index 893e74251703..e4bd4eb5877f 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -701,6 +701,8 @@ struct llama_model_qwen3vlmoe : public llama_model_base { graph(const llm_graph_params & params); }; + // if false, the derived model does not use the LM head and builds its own output + virtual bool has_lm_head() const { return true; } std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; }; @@ -3004,12 +3006,8 @@ struct llama_model_qwen35 : public llama_model_base { std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; }; -// Qwen3.5 backbone evaluated without memory, with a joint decision head on top of its hidden states -struct llama_model_clef : public llama_model_qwen35 { - llama_model_clef(const struct llama_model_params & params) : llama_model_qwen35(params) {} - void load_arch_hparams(llama_model_loader & ml) override; - void load_arch_tensors(llama_model_loader & ml) override; - +// joint decision head of clef, on top of the final hidden states of a backbone evaluated without memory +struct llama_clef_head { struct attn { ggml_tensor * wq = nullptr; ggml_tensor * bq = nullptr; @@ -3058,6 +3056,7 @@ struct llama_model_clef : public llama_model_qwen35 { ggml_tensor * proj_option_context = nullptr; ggml_tensor * proj_option_lexical = nullptr; ggml_tensor * scales = nullptr; // prior scale, joint scale, residual gate + ggml_tensor * type_embd = nullptr; ggml_tensor * scorer = nullptr; ggml_tensor * scorer_b = nullptr; ggml_tensor * scorer_out = nullptr; @@ -3066,11 +3065,33 @@ struct llama_model_clef : public llama_model_qwen35 { class input_decision; + void load_hparams(llama_model_loader & ml, llama_hparams & hparams); + void load_tensors(llama_model_loader & ml, llama_model_base & model); + + // causal mask by batch order, for the attention layers of the backbone + static llm_graph_input_attn_no_cache * build_attn_inp_causal(const llm_graph_context & ctx); + + // hidden: [n_embd, n_tokens] + // returns [1, n_tokens], row i is the score of option i + ggml_tensor * build(const llm_graph_context & ctx, ggml_tensor * hidden) const; + +private: + ggml_tensor * build_head_norm(const llm_graph_context & ctx, ggml_tensor * cur, const norm & n) const; + ggml_tensor * build_head_attn(const llm_graph_context & ctx, ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask = nullptr) const; + ggml_tensor * build_head_ffn (const llm_graph_context & ctx, ggml_tensor * cur, const head_layer & layer) const; +}; + +// Qwen3.5 backbone evaluated without memory, with a joint decision head on top of its hidden states +struct llama_model_clef : public llama_model_qwen35 { + llama_model_clef(const struct llama_model_params & params) : llama_model_qwen35(params) {} + void load_arch_hparams(llama_model_loader & ml) override; + void load_arch_tensors(llama_model_loader & ml) override; + + llama_clef_head head; + struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); private: - llm_graph_input_attn_no_cache * build_attn_inp_causal(); - ggml_tensor * build_layer_attn( llm_graph_input_attn_no_cache * inp_attn, ggml_tensor * cur, @@ -3081,16 +3102,23 @@ struct llama_model_clef : public llama_model_qwen35 { ggml_tensor * cur, int il); - // hidden: [n_embd, n_tokens], returns one score per option: [1, n_options] - ggml_tensor * build_head( - ggml_tensor * hidden, - input_decision * inp); + const llama_model_clef & model; + }; - ggml_tensor * build_head_norm(ggml_tensor * cur, const norm & n); - ggml_tensor * build_head_attn(ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask = nullptr); - ggml_tensor * build_head_ffn (ggml_tensor * cur, const head_layer & layer); + bool has_lm_head() const override { return false; } + std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; +}; - const llama_model_clef & model; +// Qwen3-Omni thinker (Qwen3 MoE) backbone evaluated without memory, with the clef decision head +struct llama_model_clef_omni : public llama_model_qwen3vlmoe { + llama_model_clef_omni(const struct llama_model_params & params) : llama_model_qwen3vlmoe(params) {} + void load_arch_hparams(llama_model_loader & ml) override; + void load_arch_tensors(llama_model_loader & ml) override; + + llama_clef_head head; + + struct graph : public llm_graph_context { + graph(const llm_graph_params & params); }; bool has_lm_head() const override { return false; } diff --git a/src/models/qwen3vlmoe.cpp b/src/models/qwen3vlmoe.cpp index 0d13a1dc5425..acab474ef5d6 100644 --- a/src/models/qwen3vlmoe.cpp +++ b/src/models/qwen3vlmoe.cpp @@ -20,10 +20,14 @@ void llama_model_qwen3vlmoe::load_arch_tensors(llama_model_loader &) { // output output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0); - output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED); - // if output is NULL, init from the input tok embed - if (output == NULL) { - output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED); + + if (has_lm_head()) { + output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED); + + // if output is NULL, init from the input tok embed + if (output == NULL) { + output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED); + } } for (int i = 0; i < n_layer; ++i) { diff --git a/tests/test-llama-archs.cpp b/tests/test-llama-archs.cpp index dc4eeaba4d7c..7b53cd947a53 100644 --- a/tests/test-llama-archs.cpp +++ b/tests/test-llama-archs.cpp @@ -1184,6 +1184,7 @@ static bool moe_mandatory(const llm_arch arch) { case LLM_ARCH_QWEN3MOE: case LLM_ARCH_QWEN3NEXT: case LLM_ARCH_QWEN3VLMOE: + case LLM_ARCH_CLEF_OMNI: case LLM_ARCH_QWEN35MOE: case LLM_ARCH_CLOVER_MOE: case LLM_ARCH_QWEN4EXP: @@ -1297,7 +1298,7 @@ static bool arch_supported(const llm_arch arch) { if (arch == LLM_ARCH_PLM) { return false; // TODO tensor shapes } - if (arch == LLM_ARCH_CLEF || arch == LLM_ARCH_VLLM_DECISION2) { + if (arch == LLM_ARCH_CLEF || arch == LLM_ARCH_CLEF_OMNI || arch == LLM_ARCH_VLLM_DECISION2) { return false; // TODO decision head tensors } if (arch == LLM_ARCH_DEEPSEEK2OCR) { diff --git a/tests/test-server-component.cpp b/tests/test-server-component.cpp index d5933167e746..6f0dc64d041b 100644 --- a/tests/test-server-component.cpp +++ b/tests/test-server-component.cpp @@ -773,6 +773,40 @@ static void test_decision_ocr_jev_validation(testing & t) { reject_state("two images, three given", files_of(3), "this model needs exactly 2 images"); } +// server_decision_context::parse_state: "images" and "audio" are aliases of "files" +// + +static void test_decision_media_fields(testing & t) { + server_decision_context ctx; + ctx.type = COMMON_DECISION_TYPE_CLEF_OMNI; + + // only base64-decoded, the media itself is not parsed here + const std::string image = "data:image/png;base64,AAAA"; + const std::string audio = "data:audio/wav;base64,AQID"; + + std::vector files; + ctx.parse_state({{"state", "x"}, {"audio", json::array({audio})}}, files); + t.assert_equal("audio is read", (size_t) 1, files.size()); + t.assert_true("audio content", files[0] == raw_buffer({1, 2, 3})); + + files.clear(); + ctx.parse_state({{"state", "x"}, {"files", json::array({image})}, {"images", json::array({image})}, {"audio", json::array({audio})}}, files); + t.assert_equal("all fields are read", (size_t) 3, files.size()); + t.assert_true("audio after files and images", files[2] == raw_buffer({1, 2, 3})); + + files.clear(); + ctx.parse_state({{"state", "x"}, {"audio", nullptr}}, files); + t.assert_true("null audio", files.empty()); + + std::string error; + try { + ctx.parse_state({{"state", "x"}, {"audio", audio}}, files); + } catch (const std::invalid_argument & e) { + error = e.what(); + } + t.assert_true("audio must be an array: " + error, error.find("\"audio\" must be an array") != std::string::npos); +} + // server_decision_context: the recursive functions stop at RECURSIVE_LIMIT // @@ -798,6 +832,90 @@ static void test_decision_depth(testing & t) { }); } +// +// server_decision_context: the joint head reads media grouped by kind (images, then audio, then video) +// + +static std::vector make_wav_16khz(size_t n_samples) { + std::vector b(44 + 2 * n_samples, 0); + const auto put32 = [&](size_t o, uint32_t v) { b[o] = v; b[o + 1] = v >> 8; b[o + 2] = v >> 16; b[o + 3] = v >> 24; }; + const auto put16 = [&](size_t o, uint16_t v) { b[o] = v; b[o + 1] = v >> 8; }; + memcpy(b.data(), "RIFF", 4); + put32(4, 36 + (uint32_t) (2 * n_samples)); + memcpy(b.data() + 8, "WAVEfmt ", 8); + put32(16, 16); // fmt chunk size + put16(20, 1); // PCM + put16(22, 1); // channels + put32(24, 16000); // sample rate + put32(28, 16000 * 2); // byte rate + put16(32, 2); // block align + put16(34, 16); // bits per sample + memcpy(b.data() + 36, "data", 4); + put32(40, (uint32_t) (2 * n_samples)); + return b; +} + +static void test_decision_media_order(testing & t) { + const mtmd_helper_init_opt opt = mtmd_helper_init_opt_default(); + + const std::vector png = { // a 1x1 grayscale PNG + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x3a, 0x7e, 0x9b, + 0x55, 0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x60, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x01, 0x48, 0xaf, 0xa4, 0x71, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, + 0x42, 0x60, 0x82, + }; + const raw_buffer image = png; + const raw_buffer audio_a = make_wav_16khz(16); + const raw_buffer audio_b = make_wav_16khz(32); + + // the detector recognizes the buffers, so the test exercises the real grouping + mtmd_helper_media_meta meta; + t.assert_true("image detected", mtmd_helper_get_media_meta(image.data(), image.size(), opt, &meta) == 0 && meta.type == MTMD_HELPER_MEDIA_TYPE_IMAGE); + t.assert_true("audio detected", mtmd_helper_get_media_meta(audio_a.data(), audio_a.size(), opt, &meta) == 0 && meta.type == MTMD_HELPER_MEDIA_TYPE_AUDIO); + + // images come first even when the request lists audio first + const std::vector grouped = decision_order_media({audio_a, image}, opt); + t.assert_equal("count", (size_t) 2, grouped.size()); + t.assert_true("image first", grouped[0] == image); + t.assert_true("audio last", grouped[1] == audio_a); + + // the order within a kind is kept + const std::vector stable = decision_order_media({audio_b, image, audio_a}, opt); + t.assert_equal("stable count", (size_t) 3, stable.size()); + t.assert_true("stable image first", stable[0] == image); + t.assert_true("stable audio order", stable[1] == audio_b && stable[2] == audio_a); + + // a decoder that reads any buffer as a video, the built-in one needs ffmpeg + static int decoder_state = 0; + mtmd_helper_video_decoder decoder = {}; + decoder.open = [](void *, const char *, const unsigned char *, size_t, mtmd_helper_video_stream_info * info) -> void * { + *info = {16, 16, 2.0f, 4, 2.0f}; + return &decoder_state; + }; + decoder.read_frame = [](void *, unsigned char *, uint32_t, uint32_t) { return false; }; + decoder.close = [](void *) {}; + + mtmd_helper_init_opt opt_video = opt; + opt_video.video_params.decoder = &decoder; + + const raw_buffer video = {'v', 'i', 'd', 'e', 'o'}; + t.assert_true("video detected", mtmd_helper_get_media_meta(video.data(), video.size(), opt_video, &meta) == 0 && meta.type == MTMD_HELPER_MEDIA_TYPE_VIDEO); + + const std::vector with_video = decision_order_media({video, audio_a, image}, opt_video); + t.assert_true("video last", with_video.size() == 3 && with_video[0] == image && with_video[1] == audio_a && with_video[2] == video); + + // cloudflare-clef-omni + std::string error; + try { + decision_order_media({image, video}, opt_video, false); + } catch (const std::invalid_argument & e) { + error = e.what(); + } + t.assert_true("video rejected: " + error, error.find("video input is not supported") != std::string::npos); + t.assert_equal("no video, nothing rejected", (size_t) 2, decision_order_media({audio_a, image}, opt_video, false).size()); +} + // DRY sequence breakers // @@ -992,7 +1110,9 @@ int main(int argc, char ** argv) { t.test("rerank_template", test_rerank_template); t.test("decision_class_scores", test_decision_class_scores); t.test("decision_ocr_jev_validation", test_decision_ocr_jev_validation); + t.test("decision_media_fields", test_decision_media_fields); t.test("decision_depth", test_decision_depth); + t.test("decision_media_order", test_decision_media_order); t.test("glob_match", test_glob_match); t.test("dry_sequence_breakers", test_dry_sequence_breakers); t.test("stop_strings", test_stop_strings); diff --git a/tools/server/README.md b/tools/server/README.md index f690d7c04843..6dda4de48b77 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -1932,6 +1932,8 @@ Follows the [TypeSafe API](https://docs.typesafe.ai/api), streaming is not suppo `images`: Optional. An alias of `files`. +`audio`: Optional. An alias of `files`. + `questions`: An object that maps a question id to a question. Each question has these fields: - `type`: One of `choice`, `score`, `noul`. @@ -1941,11 +1943,11 @@ Follows the [TypeSafe API](https://docs.typesafe.ai/api), streaming is not suppo - `score`: An array of 2 to 10 level descriptions, lowest level first. - `noul`: Optional. An object with the descriptions of `true` and `false`. -The questions of a request are answered independently, an answer does not depend on the other questions. The exceptions are clef, which reads all the questions in one prompt and decides them jointly, and lfm3-d1 and lfm3-d1-omni, which read up to 16 questions after the state in one pass, as the models were trained (requests with a spoken question read one question per pass). +The questions of a request are answered independently, an answer does not depend on the other questions. The exceptions are clef and cloudflare-clef-omni, which read all the questions in one prompt and decide them jointly, and lfm3-d1 and lfm3-d1-omni, which read up to 16 questions after the state in one pass, as the models were trained (requests with a spoken question read one question per pass). -The number of options of a `choice` question is limited by the model, for example: 52 for openjev, 255 for granite-switch, laya, clef, pplx-decider, vllm-decision2, vllm-d3, lfm2-d1, lfm2-d1-omni and h2o-lightning, 2 for openbmb-minicpm-ocr-jev. For laya, long questions and options are truncated to the token budget the model was trained with. +The number of options of a `choice` question is limited by the model, for example: 52 for openjev, 255 for granite-switch, laya, clef, cloudflare-clef-omni, pplx-decider, vllm-decision2, vllm-d3, lfm2-d1, lfm2-d1-omni and h2o-lightning, 2 for openbmb-minicpm-ocr-jev. For laya, long questions and options are truncated to the token budget the model was trained with. -For laya, clef, vllm-d3, lfm2-d1-omni, lfm3-d1 and lfm3-d1-omni, the whole prompt is evaluated in one batch: it must fit in `--ubatch-size`. An lfm2-d1-omni prompt is cut to 16384 tokens. For vllm-decision2, the options of a question and the end of the prompt must fit in one batch. An h2o-lightning state longer than 32000 tokens keeps its first and last 16000 tokens. A server that runs clef only serves this endpoint, text generation is not available. A decision model that is also a text model, such as granite-switch, serves both and reports `["text", "decisions"]`. +For laya, clef, cloudflare-clef-omni, vllm-d3, lfm2-d1-omni, lfm3-d1 and lfm3-d1-omni, the whole prompt is evaluated in one batch: it must fit in `--ubatch-size`. An lfm2-d1-omni prompt is cut to 16384 tokens. For vllm-decision2, the options of a question and the end of the prompt must fit in one batch. An h2o-lightning state longer than 32000 tokens keeps its first and last 16000 tokens. A server that runs clef or cloudflare-clef-omni only serves this endpoint, text generation is not available. A decision model that is also a text model, such as granite-switch, serves both and reports `["text", "decisions"]`. openbmb-minicpm-ocr-jev answers one fixed question: is an OCR text, rendered as an image, consistent with the original image? `state` is the OCR text, as a string, special tokens written in it are escaped. `files` (or `images`) has exactly 2 images: the original, then the rendered one, both are required. The request has one question and no `instructions`: the task is part of the prompt of the model, so a request that sends one is rejected. It is either a `choice` with the `criteria` `{"0": null, "1": null}`, where `1` means consistent, or a `noul` without `criteria`, which returns the probability of `1`. The model has no LM head, so text generation is not available. @@ -1953,14 +1955,16 @@ Its prompt carries two images, so it is much longer than a text-only one: size t *Image input:* -Image input needs a model that supports it (for example: openjev, clef, pplx-decider, vllm-d3, lfm2-d1, lfm2-d1-omni, h2o-lightning, openbmb-minicpm-ocr-jev) and its multimodal projector, see `--mmproj`. +Image input needs a model that supports it (for example: openjev, clef, cloudflare-clef-omni, pplx-decider, vllm-d3, lfm2-d1, lfm2-d1-omni, h2o-lightning, openbmb-minicpm-ocr-jev) and its multimodal projector, see `--mmproj`. Images can be given in two ways, and both can be used in the same request: -- The `files` field, or its alias `images`. +- The `files` field, or its aliases `images` and `audio`. - A `state` made of chat messages, either an array of messages or an object with a `messages` array. An `image_url` part in the `content` of a message is taken as an image, in the same format as chat completions. Only data URLs are accepted. For lfm2-d1-omni, an `input_audio` part is taken as an audio clip, as base64 data. -All the images are placed before the state in the prompt, the ones from `files` and `images` first. The image parts are removed from the state. +All the images are placed before the state in the prompt, the ones from `files`, `images` and `audio` first. The image parts are removed from the state. + +For clef and cloudflare-clef-omni, the files are grouped by kind, as the models were trained: images, then audio clips, then videos. A video is rejected by cloudflare-clef-omni. *Response:* diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp index 18564b6e47cb..5097c60ca0d3 100644 --- a/tools/server/server-common.cpp +++ b/tools/server/server-common.cpp @@ -241,6 +241,7 @@ std::vector server_model_output_modalities(common_decision_type dec case COMMON_DECISION_TYPE_MINICPM_OCR_JEV: case COMMON_DECISION_TYPE_LFM3_D1: case COMMON_DECISION_TYPE_LFM3_D1_OMNI: + case COMMON_DECISION_TYPE_CLEF_OMNI: out = {"decisions"}; break; case COMMON_DECISION_TYPE_GRANITE_SWITCH: diff --git a/tools/server/server-decision.cpp b/tools/server/server-decision.cpp index 32eeec361010..0db4d53c0c28 100644 --- a/tools/server/server-decision.cpp +++ b/tools/server/server-decision.cpp @@ -153,7 +153,7 @@ void server_decision_context::init(const llama_model * model) { throw std::runtime_error("decision model has no valid max_head_tokens"); } n_options_max = 255; - } else if (model_type == COMMON_DECISION_TYPE_CLEF) { + } else if (model_type == COMMON_DECISION_TYPE_CLEF || model_type == COMMON_DECISION_TYPE_CLEF_OMNI) { n_options_max = 255; noul_true_first = true; choice_sorted = true; @@ -410,6 +410,40 @@ static void decision_load_audio(const json & data, std::vector & fil handle_media(files, data.get(), ""); } +// the joint head reads media grouped by kind, as the model was trained: images, then audio, then video +std::vector decision_order_media(const std::vector & files, const mtmd_helper_init_opt & init_opt, bool allow_video) { + auto rank_of = [&](const raw_buffer & file) -> int { + mtmd_helper_media_meta meta; + if (mtmd_helper_get_media_meta(file.data(), file.size(), init_opt, &meta) == 0) { + switch (meta.type) { + case MTMD_HELPER_MEDIA_TYPE_IMAGE: return 0; + case MTMD_HELPER_MEDIA_TYPE_AUDIO: return 1; + case MTMD_HELPER_MEDIA_TYPE_VIDEO: + if (!allow_video) { + throw std::invalid_argument("video input is not supported by this model"); + } + return 2; + default: break; + } + } + return 3; // mtmd reports the error when the prompt is tokenized + }; + + std::vector> ranked; + ranked.reserve(files.size()); + for (const auto & file : files) { + ranked.emplace_back(rank_of(file), &file); + } + std::stable_sort(ranked.begin(), ranked.end(), [](const auto & a, const auto & b) { return a.first < b.first; }); + + std::vector out; + out.reserve(files.size()); + for (const auto & entry : ranked) { + out.push_back(*entry.second); + } + return out; +} + json server_decision_context::parse_state(const json & body, std::vector & files) const { if (type == COMMON_DECISION_TYPE_MINICPM_OCR_JEV && !body.at("state").is_string()) { throw std::invalid_argument("\"state\" must be the OCR text"); @@ -417,8 +451,8 @@ json server_decision_context::parse_state(const json & body, std::vector media = decision_order_media(files, init_opt, type != COMMON_DECISION_TYPE_CLEF_OMNI); + + // the template puts one media marker per file json images = json::array(); - if (!files.empty()) { + if (!media.empty()) { inp = decision_replace_text(inp, get_media_marker(), " "); - for (size_t i = 0; i < files.size(); i++) { + for (size_t i = 0; i < media.size(); i++) { images.push_back(get_media_marker()); } } @@ -1579,7 +1617,7 @@ void server_decision_context::fill_task_joint( size_t i_piece = 0; task.tokens = server_tokens(llama_tokens(), false); - if (!files.empty()) { + if (!media.empty()) { // the text before the images is tokenized with them, a vision token separates the pieces anyway std::string head; while (i_piece < pieces.size() && head.find(get_media_marker()) == std::string::npos) { @@ -1588,7 +1626,7 @@ void server_decision_context::fill_task_joint( if (head.find(get_media_marker()) == std::string::npos || head.find(CLEF_MARKER) != std::string::npos) { throw invalid; } - task.tokens = process_mtmd_prompt(mctx, head, files, init_opt); + task.tokens = process_mtmd_prompt(mctx, head, media, init_opt); task.decision.order.resize(task.tokens.size(), LLAMA_DECISION_ORDER_NONE); } diff --git a/tools/server/server-decision.h b/tools/server/server-decision.h index 175aa46ebac3..a02c7b9eed1a 100644 --- a/tools/server/server-decision.h +++ b/tools/server/server-decision.h @@ -56,7 +56,7 @@ struct server_decision_context { // true if all the questions of a request go in one prompt, see fill_task_joint() bool is_joint() const { - return type == COMMON_DECISION_TYPE_CLEF; + return type == COMMON_DECISION_TYPE_CLEF || type == COMMON_DECISION_TYPE_CLEF_OMNI; } bool is_lfm3_d1() const { @@ -76,6 +76,7 @@ struct server_decision_context { case COMMON_DECISION_TYPE_MINICPM_OCR_JEV: case COMMON_DECISION_TYPE_LFM3_D1: case COMMON_DECISION_TYPE_LFM3_D1_OMNI: + case COMMON_DECISION_TYPE_CLEF_OMNI: return true; default: return false; @@ -96,7 +97,7 @@ struct server_decision_context { json prepare_state(const json & state) const; // returns the state without its images, they are appended to files in order - // images come from "files" (alias "images") and from the image_url and input_audio parts of a state made of chat messages + // images come from "files" (aliases "images" and "audio") and from the image_url and input_audio parts of a state made of chat messages // an image can be an audio clip if the model supports it json parse_state(const json & body, std::vector & files) const; @@ -207,5 +208,9 @@ struct server_decision_context { // note: the order of the tasks is preserved std::vector server_decision_group_tasks(std::vector && tasks, size_t n_slots); +// order the media as the joint head reads them: images, then audio, then video +// throw std::invalid_argument on a video if allow_video is false +std::vector decision_order_media(const std::vector & files, const mtmd_helper_init_opt & init_opt, bool allow_video = true); + // write "<|name|>" with U+00A6 in place of "|", so text from the request is not parsed as special tokens std::string server_decision_escape_special_tokens(const std::string & text); From 08dc1cea9e96f2f6fab5ba0dcb29d5f2b802090d Mon Sep 17 00:00:00 2001 From: Xuan-Son Nguyen Date: Wed, 2 Dec 2026 01:53:54 +0100 Subject: [PATCH 05/65] llama : refactor decision model api (#33305) * non-overlap version * wip * drop ggml_prec_set --- common/common.cpp | 8 +- common/common.h | 5 +- src/llama-batch.cpp | 137 ++++++++++++++++++++++++------- src/llama-batch.h | 40 ++++++--- src/llama-context.cpp | 65 ++++++++++++++- src/llama-context.h | 7 ++ src/llama-ext.h | 37 ++++++--- src/llama-graph.cpp | 77 ++++++++++++++--- src/llama-graph.h | 14 ++++ src/llama-kv-cache-dsv4.cpp | 5 +- src/models/clef.cpp | 76 ++++++++++------- src/models/models.h | 3 +- src/models/vllm-decision2.cpp | 87 ++++++++++++-------- tests/test-batch-alloc.cpp | 76 +++++++++++++++++ tools/server/server-context.cpp | 56 +++++++------ tools/server/server-decision.cpp | 36 ++++---- tools/server/server-task.h | 18 ++-- 17 files changed, 560 insertions(+), 187 deletions(-) diff --git a/common/common.cpp b/common/common.cpp index da7657d13399..9ea6b51ee99d 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -2338,11 +2338,11 @@ llama_batch_ext * common_batch::get_sub_batch(int32_t off, int32_t n) { if (t.state_row >= 0 && !llama_batch_ext_set_embd_state_row(res, idx, t.state_row)) { GGML_ABORT("%s: failed to set the state row of the entry at index %d\n", __func__, i); } - if (t.decision_order != 0) { - llama_batch_ext_set_decision_order(res, idx, (llama_decision_order) t.decision_order); + if (t.span != 0 && !(llama_batch_ext_set_pool_span(res, idx, t.span) && llama_batch_ext_set_pool_span_type(res, t.span, (llama_pool_span_type) t.span_type))) { + GGML_ABORT("%s: failed to set the span of the entry at index %d\n", __func__, i); } - if (t.decision_group != 0 && !llama_batch_ext_set_decision_group(res, idx, t.decision_group)) { - GGML_ABORT("%s: failed to set the decision group of the entry at index %d\n", __func__, i); + if (t.attn_scope != 0 && !llama_batch_ext_set_attn_scope(res, idx, t.attn_scope)) { + GGML_ABORT("%s: failed to set the attention scope of the entry at index %d\n", __func__, i); } } diff --git a/common/common.h b/common/common.h index 1d8d57d714a3..e5f4fb2afde1 100644 --- a/common/common.h +++ b/common/common.h @@ -1123,8 +1123,9 @@ struct common_batch { llama_embd embd; // non-owning view of the data passed to add_embd()/set_embd(), data == NULL if none llama_embd state; // non-owning view of the data passed to set_embd_state(), data == NULL if none std::vector seq_ids_extra; // see add_seq() - int32_t decision_order = 0; // see llama_batch_ext_set_decision_order() - int32_t decision_group = 0; // see llama_batch_ext_set_decision_group() + int32_t span = 0; // see llama_batch_ext_set_pool_span() + int32_t span_type = 0; // see llama_batch_ext_set_pool_span_type() + int32_t attn_scope = 0; // see llama_batch_ext_set_attn_scope() int32_t embd_row = -1; // see add_embd_row(), -1 if none int32_t state_row = -1; // see set_embd_state_row(), -1 if none }; diff --git a/src/llama-batch.cpp b/src/llama-batch.cpp index 3391cb49e858..b13a81a970a5 100644 --- a/src/llama-batch.cpp +++ b/src/llama-batch.cpp @@ -12,6 +12,27 @@ #include #include +std::vector llama_ubatch_get_spans(const llama_ubatch & ubatch) { + std::vector res; + if (ubatch.span == nullptr) { + return res; + } + + const int32_t n_tokens = ubatch.n_tokens; + for (int32_t i = 0; i < n_tokens;) { + int32_t end = i + 1; + while (end < n_tokens && ubatch.span[end] == ubatch.span[i]) { + end++; + } + if (ubatch.span[i] != 0) { + res.push_back({ ubatch.span[i], ubatch.span_type[i], i, end }); + } + i = end; + } + + return res; +} + llama_batch_allocr::llama_batch_allocr(uint32_t n_pos_per_embd, bool allow_mixed) : n_pos_per_embd(n_pos_per_embd), allow_mixed(allow_mixed) { const char * LLAMA_BATCH_DEBUG = getenv("LLAMA_BATCH_DEBUG"); debug = LLAMA_BATCH_DEBUG ? atoi(LLAMA_BATCH_DEBUG) : 0; @@ -255,16 +276,44 @@ bool llama_batch_allocr::init( // kept empty if no entry has one for (int32_t i = 0; i < n_tok; ++i) { - if (batch_inp.tokens[i].decision_order != 0) { - decision_order.resize(n_tok, 0); - decision_order[i] = batch_inp.tokens[i].decision_order; + const auto & tok = batch_inp.tokens[i]; + if (tok.span != 0) { + span.resize(n_tok, 0); + span_type.resize(n_tok, LLAMA_POOL_SPAN_TYPE_DEFAULT); + span[i] = tok.span; + const auto it = batch_inp.span_types.find(tok.span); + if (it != batch_inp.span_types.end()) { + span_type[i] = it->second; + } } - if (batch_inp.tokens[i].decision_group != 0) { - decision_group.resize(n_tok, 0); - decision_group[i] = batch_inp.tokens[i].decision_group; + if (tok.attn_scope != 0) { + attn_scope.resize(n_tok, 0); + attn_scope[i] = tok.attn_scope; } } + // a span is one run of entries in one sequence + if (!span.empty()) { + std::unordered_set seen; + for (int32_t i = 0; i < n_tok; ++i) { + if (span[i] == 0) { + continue; + } + if (i > 0 && span[i - 1] == span[i]) { + if (batch_inp.tokens[i].seq_ids != batch_inp.tokens[i - 1].seq_ids) { + LLAMA_LOG_ERROR("%s: the entries of span %d are not in the same sequence\n", __func__, span[i]); + return false; + } + continue; + } + if (!seen.insert(span[i]).second) { + LLAMA_LOG_ERROR("%s: the entries of span %d are not next to each other\n", __func__, span[i]); + return false; + } + } + n_spans = seen.size(); + } + // // set up the internal llama_batch to point to our owned arrays // @@ -356,8 +405,9 @@ bool llama_batch_allocr::init( /*.seq_idx =*/ this->seq_idx.data(), /*.output =*/ batch.logits, /*.type =*/ is_embd_vec.empty() ? nullptr : is_embd_vec.data(), - /*.decision_order =*/ decision_order.empty() ? nullptr : decision_order.data(), - /*.decision_group =*/ decision_group.empty() ? nullptr : decision_group.data(), + /*.span =*/ span.empty() ? nullptr : span.data(), + /*.span_type =*/ span_type.empty() ? nullptr : span_type.data(), + /*.attn_scope =*/ attn_scope.empty() ? nullptr : attn_scope.data(), /*.data =*/ {}, }; @@ -583,8 +633,9 @@ llama_ubatch llama_batch_allocr::ubatch_reserve(uint32_t n_seq_tokens, uint32_t /*.seq_idx =*/ udata->seq_idx.data(), /*.output =*/ udata->output.data(), /*.type =*/ nullptr, - /*.decision_order =*/ nullptr, - /*.decision_group =*/ nullptr, + /*.span =*/ nullptr, + /*.span_type =*/ nullptr, + /*.attn_scope =*/ nullptr, /*.data =*/ std::move(udata), }; @@ -607,6 +658,14 @@ uint32_t llama_batch_allocr::get_n_used() const { return n_used; } +bool llama_batch_allocr::has_spans() const { + return !span.empty(); +} + +uint32_t llama_batch_allocr::get_n_spans() const { + return n_spans; +} + std::vector & llama_batch_allocr::get_out_ids() { return out_ids; } @@ -892,8 +951,10 @@ void llama_batch_allocr::clear() { seq_id .clear(); seq_id_unq .clear(); output .clear(); - decision_order.clear(); - decision_group.clear(); + span .clear(); + n_spans = 0; + span_type .clear(); + attn_scope .clear(); for (auto & cur : seq_pos) { cur.clear(); @@ -949,8 +1010,9 @@ llama_ubatch llama_batch_allocr::ubatch_add(const std::vector & idxs, u udata->seq_idx .resize(LLAMA_MAX_SEQ, -1); udata->output .resize(n_tokens); udata->type .resize(mixed ? n_tokens : 0); - udata->decision_order.resize(decision_order.empty() ? 0 : n_tokens); - udata->decision_group.resize(decision_group.empty() ? 0 : n_tokens); + udata->span .resize(span.empty() ? 0 : n_tokens); + udata->span_type .resize(span.empty() ? 0 : n_tokens); + udata->attn_scope.resize(attn_scope.empty() ? 0 : n_tokens); udata->batch_idxs = idxs; udata->seq_id_data.reserve(n_tokens); @@ -989,11 +1051,12 @@ llama_ubatch llama_batch_allocr::ubatch_add(const std::vector & idxs, u udata->n_seq_id[i] = batch.n_seq_id[idxs[i]]; udata->output[i] = batch.logits[idxs[i]]; - if (!decision_order.empty()) { - udata->decision_order[i] = decision_order[idxs[i]]; + if (!span.empty()) { + udata->span[i] = span[idxs[i]]; + udata->span_type[i] = span_type[idxs[i]]; } - if (!decision_group.empty()) { - udata->decision_group[i] = decision_group[idxs[i]]; + if (!attn_scope.empty()) { + udata->attn_scope[i] = attn_scope[idxs[i]]; } for (int s = 0; s < udata->n_seq_id[i]; ++s) { @@ -1040,8 +1103,9 @@ llama_ubatch llama_batch_allocr::ubatch_add(const std::vector & idxs, u /*.seq_idx =*/ udata->seq_idx.data(), /*.output =*/ udata->output.data(), /*.type =*/ mixed ? udata->type.data() : nullptr, - /*.decision_order =*/ udata->decision_order.empty() ? nullptr : udata->decision_order.data(), - /*.decision_group =*/ udata->decision_group.empty() ? nullptr : udata->decision_group.data(), + /*.span =*/ udata->span.empty() ? nullptr : udata->span.data(), + /*.span_type =*/ udata->span_type.empty() ? nullptr : udata->span_type.data(), + /*.attn_scope =*/ udata->attn_scope.empty() ? nullptr : udata->attn_scope.data(), /*.data =*/ std::move(udata), }; @@ -1261,6 +1325,7 @@ void llama_batch_ext::clear() { tokens.clear(); embd .clear(); state .clear(); + span_types.clear(); n_embd = 0; } @@ -1438,19 +1503,27 @@ bool llama_batch_ext::set_output(int32_t idx, bool output_last) { return true; } -bool llama_batch_ext::set_decision_order(int32_t idx, int32_t order) { - if (idx < 0 || idx >= (int32_t) tokens.size()) { +bool llama_batch_ext::set_span(int32_t idx, int32_t span) { + if (idx < 0 || idx >= (int32_t) tokens.size() || span < 0) { + return false; + } + tokens[idx].span = span; + return true; +} + +bool llama_batch_ext::set_span_type(int32_t span, int32_t type) { + if (span <= 0 || type < LLAMA_POOL_SPAN_TYPE_DEFAULT || type > LLAMA_POOL_SPAN_TYPE_DECISION_OPTION) { return false; } - tokens[idx].decision_order = order; + span_types[span] = type; return true; } -bool llama_batch_ext::set_decision_group(int32_t idx, int32_t group) { - if (idx < 0 || idx >= (int32_t) tokens.size() || group < 0) { +bool llama_batch_ext::set_attn_scope(int32_t idx, int32_t scope) { + if (idx < 0 || idx >= (int32_t) tokens.size() || scope < 0) { return false; } - tokens[idx].decision_group = group; + tokens[idx].attn_scope = scope; return true; } @@ -1533,12 +1606,16 @@ bool llama_batch_ext_set_output_logits(llama_batch_ext * batch, int32_t idx, boo return batch->set_output(idx, value); } -bool llama_batch_ext_set_decision_order(llama_batch_ext * batch, int32_t idx, llama_decision_order order) { - return batch->set_decision_order(idx, order); +bool llama_batch_ext_set_pool_span(llama_batch_ext * batch, int32_t idx, int32_t span) { + return batch->set_span(idx, span); +} + +bool llama_batch_ext_set_pool_span_type(llama_batch_ext * batch, int32_t span, llama_pool_span_type type) { + return batch->set_span_type(span, type); } -bool llama_batch_ext_set_decision_group(llama_batch_ext * batch, int32_t idx, int32_t group) { - return batch->set_decision_group(idx, group); +bool llama_batch_ext_set_attn_scope(llama_batch_ext * batch, int32_t idx, int32_t scope) { + return batch->set_attn_scope(idx, scope); } // llama_batch_compat diff --git a/src/llama-batch.h b/src/llama-batch.h index e6f4be6a28a0..f46bb65dfa4a 100644 --- a/src/llama-batch.h +++ b/src/llama-batch.h @@ -60,8 +60,9 @@ struct llama_ubatch { int32_t * seq_idx; // [LLAMA_MAX_SEQ] | - | seq_idx int8_t * output; // [n_tokens] | i | - int8_t * type; // [n_tokens] | i | - (mixed ubatch only, 0 - token, 1 - embd) - int32_t * decision_order; // [n_tokens], NULL if no entry has one, see llama_batch_ext_set_decision_order() - int32_t * decision_group; // [n_tokens], NULL if no entry has one, see llama_batch_ext_set_decision_group() + int32_t * span; // [n_tokens], NULL if no entry has one, see llama_batch_ext_set_pool_span() + int32_t * span_type; // [n_tokens], NULL if no entry has a span + int32_t * attn_scope; // [n_tokens], NULL if no entry has one, see llama_batch_ext_set_attn_scope() struct data_t { std::vector token; @@ -77,8 +78,9 @@ struct llama_ubatch { std::vector output; std::vector type; std::vector batch_idxs; // original batch index for each token - std::vector decision_order; - std::vector decision_group; + std::vector span; + std::vector span_type; + std::vector attn_scope; std::vector seq_id_data; }; @@ -87,6 +89,17 @@ struct llama_ubatch { std::shared_ptr data; }; +// a span of a ubatch, see llama_batch_ext_set_pool_span() +struct llama_ubatch_span { + int32_t id; + int32_t type; // see llama_pool_span_type + int32_t start; // [start, end) in ubatch token indices + int32_t end; +}; + +// the spans of the ubatch, in the order of their first token +std::vector llama_ubatch_get_spans(const llama_ubatch & ubatch); + // crash if a mixed ubatch reaches code that expects only tokens or only embd #define ASSERT_EMBD_OR_TOKEN(ubatch) GGML_ASSERT(!(ubatch).is_mixed() && "mixed token/embd ubatch is not supported here") @@ -122,14 +135,15 @@ struct llama_batch_ext { int32_t embd_row = -1; // row of ctx_other's layer input device buffer used as embd, -1 if none int32_t state_row = -1; // row of ctx_state_src's h_nextn device buffer used as state, -1 if none bool output = false; // TODO: have dedicated output flags - int32_t decision_order = 0; // see llama_batch_ext_set_decision_order() - int32_t decision_group = 0; // see llama_batch_ext_set_decision_group() + int32_t span = 0; // see llama_batch_ext_set_pool_span() + int32_t attn_scope = 0; // see llama_batch_ext_set_attn_scope() std::unordered_set seq_ids; std::array pos = {0, 0, 0, 0}; }; std::vector tokens; std::vector embd; std::vector state; + std::unordered_map span_types; // span id -> llama_pool_span_type, default if missing llama_batch_ext(llama_context * ctx); @@ -157,8 +171,9 @@ struct llama_batch_ext { bool set_token_state_row(int32_t idx, int32_t row); bool set_token_pos(int32_t idx, const llama_pos * pos_in); bool set_output(int32_t idx, bool output_last); - bool set_decision_order(int32_t idx, int32_t order); - bool set_decision_group(int32_t idx, int32_t group); + bool set_span(int32_t idx, int32_t span); + bool set_span_type(int32_t span, int32_t type); + bool set_attn_scope(int32_t idx, int32_t scope); }; // a helper for sanitizing, fulfilling and splitting a batch @@ -178,6 +193,9 @@ class llama_batch_allocr { uint32_t get_n_outputs() const; uint32_t get_n_used() const; + bool has_spans() const; + uint32_t get_n_spans() const; + // the array of output indices in the order they were encountered during the ubatch splitting std::vector & get_out_ids(); @@ -244,8 +262,10 @@ class llama_batch_allocr { std::vector seq_id_unq; std::vector seq_idx; std::vector output; - std::vector decision_order; // empty if no entry has one - std::vector decision_group; // empty if no entry has one + std::vector span; // empty if no entry has one + uint32_t n_spans = 0; + std::vector span_type; // empty if no entry has a span + std::vector attn_scope; // empty if no entry has one using pos_set_t = std::set; using seq_cpl_t = std::vector; diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 88cc05630092..f6af3ac99a87 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -1168,6 +1168,30 @@ float * llama_context::get_embeddings_seq(llama_seq_id seq_id) { return it->second.data(); } +float * llama_context::get_embeddings_span(int32_t span) { + auto it = embd_span.find(span); + if (it == embd_span.end()) { + return nullptr; + } + + return it->second.data(); +} + +void llama_context::output_embd_spans(const llama_ubatch & ubatch, ggml_tensor * t_embd_span) { + ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(sched.get(), t_embd_span); + GGML_ASSERT(backend_embd != nullptr); + + const auto spans = llama_ubatch_get_spans(ubatch); + GGML_ASSERT((int64_t) spans.size() <= t_embd_span->ne[1]); + + const size_t n_row = t_embd_span->ne[0]; + for (size_t s = 0; s < spans.size(); ++s) { + auto & out = embd_span[spans[s].id]; + out.resize(n_row); + ggml_backend_tensor_get_async(backend_embd, t_embd_span, out.data(), s*n_row*sizeof(float), n_row*sizeof(float)); + } +} + float * llama_context::get_embeddings_nextn() { output_reorder(); @@ -1892,6 +1916,11 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { return -1; } + if (llm_graph_pools_spans(cparams) && balloc->get_n_spans() > LLAMA_MAX_POOL_SPANS) { + LLAMA_LOG_ERROR("%s: too many spans to pool, n_spans = %u > %d\n", __func__, balloc->get_n_spans(), LLAMA_MAX_POOL_SPANS); + return -1; + } + const uint32_t n_tokens = balloc->get_n_tokens(); // [TAG_NO_CACHE_PAD] @@ -1907,10 +1936,11 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { // TODO: this clear of the buffer can easily be forgotten - need something better // sync first so any in-flight async copies into embd_seq complete before it is freed - if (!embd_seq.empty()) { + if (!embd_seq.empty() || !embd_span.empty()) { synchronize(); } embd_seq.clear(); + embd_span.clear(); if (t_compute_start_us == 0) { t_compute_start_us = ggml_time_us(); @@ -1960,6 +1990,8 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { auto * t_embd = res->get_embd_pooled() ? res->get_embd_pooled() : res->get_embd(); auto * t_h_nextn = cparams.embeddings_nextn ? res->get_h_nextn() : nullptr; + auto * t_embd_span = ubatch.span ? res->get_embd_span() : nullptr; + // extract logits if (logits.data && t_logits) { ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(sched.get(), t_logits); @@ -1970,7 +2002,9 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { } // extract embeddings - if (embd.data && t_embd) { + if (embd.data && t_embd_span) { + output_embd_spans(ubatch, t_embd_span); + } else if (embd.data && t_embd) { ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(sched.get(), t_embd); GGML_ASSERT(backend_embd != nullptr); @@ -2204,14 +2238,27 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { GGML_ASSERT(n_tokens_all <= cparams.n_batch); + if (llm_graph_pools_spans(cparams) && balloc->get_n_spans() > LLAMA_MAX_POOL_SPANS) { + LLAMA_LOG_ERROR("%s: too many spans to pool, n_spans = %u > %d\n", __func__, balloc->get_n_spans(), LLAMA_MAX_POOL_SPANS); + return -1; + } + + // a span cannot be split over two ubatches + if (output_all && balloc->has_spans() && n_tokens_all > cparams.n_ubatch) { + LLAMA_LOG_ERROR("%s: a batch with spans is read in one pass, n_tokens = %u > n_ubatch = %u, increase n_ubatch (-ub)\n", + __func__, n_tokens_all, cparams.n_ubatch); + return -1; + } + GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens"); // TODO: this clear of the buffer can easily be forgotten - need something better // sync first so any in-flight async copies into embd_seq complete before it is freed - if (!embd_seq.empty()) { + if (!embd_seq.empty() || !embd_span.empty()) { synchronize(); } embd_seq.clear(); + embd_span.clear(); if (t_compute_start_us == 0) { t_compute_start_us = ggml_time_us(); @@ -2388,6 +2435,8 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { t_embd = res->get_embd_pooled(); } + auto * t_embd_span = cparams.embeddings && ubatch.span ? res->get_embd_span() : nullptr; + // extract logits if (logits.data && t_logits && n_outputs > 0 && needs_raw_logits(ubatch, sampling.samplers)) { ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(sched.get(), t_logits); @@ -2404,7 +2453,9 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { } // extract embeddings - if (embd.data && t_embd && n_outputs > 0) { + if (embd.data && t_embd_span) { + output_embd_spans(ubatch, t_embd_span); + } else if (embd.data && t_embd && n_outputs > 0) { ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(sched.get(), t_embd); GGML_ASSERT(backend_embd != nullptr); @@ -4692,6 +4743,12 @@ float * llama_get_embeddings_seq(llama_context * ctx, llama_seq_id seq_id) { return ctx->get_embeddings_seq(seq_id); } +float * llama_get_embeddings_pool_span(llama_context * ctx, int32_t span) { + ctx->synchronize(); + + return ctx->get_embeddings_span(span); +} + void llama_set_embeddings_nextn(llama_context * ctx, bool value, bool masked) { ctx->set_embeddings_nextn(value, masked); } diff --git a/src/llama-context.h b/src/llama-context.h index 3e3921c7df28..e7ababe51770 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -87,6 +87,7 @@ struct llama_context { float * get_embeddings(); float * get_embeddings_ith(int32_t i); float * get_embeddings_seq(llama_seq_id seq_id); + float * get_embeddings_span(int32_t span); float * get_embeddings_nextn(); float * get_embeddings_nextn_ith(int32_t i); @@ -251,6 +252,9 @@ struct llama_context { void output_reorder(); + // copy t_embd_span rows to embd_span, see llama_ubatch_get_spans() + void output_embd_spans(const llama_ubatch & ubatch, ggml_tensor * t_embd_span); + // map the output row index `i` to batch index int64_t output_resolve_row(int32_t i) const; @@ -386,6 +390,9 @@ struct llama_context { // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE std::map> embd_seq; + // span embeddings output, see llama_get_embeddings_pool_span() + std::map> embd_span; + // reuse the batch_allocr to avoid unnecessary memory allocations std::unique_ptr balloc; diff --git a/src/llama-ext.h b/src/llama-ext.h index a77b2f40948a..2dbe9fa2d7a1 100644 --- a/src/llama-ext.h +++ b/src/llama-ext.h @@ -125,23 +125,34 @@ LLAMA_API std::vector llama_memory_get_buffers(const llam // Useful for testing purposes. LLAMA_API void llama_model_set_attn_rot(struct llama_model * model, bool value); -// Marks the entries that a decision head (clef, vllm-decision2) reads, the default is 0 +// span id of an entry, 0 (default) = no span +// a span is one run of entries in one sequence, a batch with spans must fit in one ubatch +// with mean, cls or last pooling, each span is pooled instead of each sequence +// note: spans cannot overlap +// to pool overlapping or disjoint ranges, cut them into spans, then join the results: +// mean = sum(n_tokens(span) * mean(span)) / sum(n_tokens(span)), before normalization +// cls / last = result of the first / last span +LLAMA_API bool llama_batch_ext_set_pool_span(struct llama_batch_ext * batch, int32_t idx, int32_t span); + +// role of a span, read by a decision head (clef, vllm-decision2) // See https://github.com/ggml-org/llama.cpp/pull/29831 for details -// A run of entries with the same value is one span, spans must be separated by entries with value 0 // An option belongs to the last question before it -enum llama_decision_order { - LLAMA_DECISION_ORDER_NONE = 0, // not read by the head - LLAMA_DECISION_ORDER_QUESTION_NOUL = 1, // text of a question - LLAMA_DECISION_ORDER_QUESTION_CHOICE = 2, - LLAMA_DECISION_ORDER_QUESTION_SCORE = 3, - LLAMA_DECISION_ORDER_OPTION = 4, // text of an option +enum llama_pool_span_type { + LLAMA_POOL_SPAN_TYPE_DEFAULT = 0, // pooled with the context pooling type + LLAMA_POOL_SPAN_TYPE_DECISION_QUESTION_NOUL = 1, // text of a question + LLAMA_POOL_SPAN_TYPE_DECISION_QUESTION_CHOICE = 2, + LLAMA_POOL_SPAN_TYPE_DECISION_QUESTION_SCORE = 3, + LLAMA_POOL_SPAN_TYPE_DECISION_OPTION = 4, // text of an option }; -// The embeddings output has one value per entry: row i is the score of option i -LLAMA_API bool llama_batch_ext_set_decision_order(struct llama_batch_ext * batch, int32_t idx, enum llama_decision_order order); +LLAMA_API bool llama_batch_ext_set_pool_span_type(struct llama_batch_ext * batch, int32_t span, enum llama_pool_span_type type); -// Questions packed after a shared state in one sequence, contexts without memory only -// 0 (default) is the state, k > 0 the k-th question; full attention layers hide other questions from a question -LLAMA_API bool llama_batch_ext_set_decision_group(struct llama_batch_ext * batch, int32_t idx, int32_t group); +// result of a span of the last batch, nullptr if none +// n_embd_out pooled values, or 1 score for an option span of a decision head +LLAMA_API float * llama_get_embeddings_pool_span(struct llama_context * ctx, int32_t span); + +// entries packed after a shared prefix in one sequence, contexts without memory only +// 0 (default) is seen by all, scope k > 0 is hidden from other scopes in full attn layers +LLAMA_API bool llama_batch_ext_set_attn_scope(struct llama_batch_ext * batch, int32_t idx, int32_t scope); // Label of option i of a decision model (".decision.labels"), nullptr past the last one LLAMA_API const char * llama_model_decision_label(const struct llama_model * model, uint32_t i); diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 948a02ce7233..f1bef630d116 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -431,6 +431,21 @@ bool llm_graph_input_moe_ids::can_reuse(const llm_graph_params & params) { return res; } +bool llm_graph_pools_spans(const llama_cparams & cparams) { + return cparams.embeddings && ( + cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN || + cparams.pooling_type == LLAMA_POOLING_TYPE_CLS || + cparams.pooling_type == LLAMA_POOLING_TYPE_LAST); +} + +int64_t llm_graph_n_pooled(const llama_cparams & cparams, const llama_ubatch & ubatch) { + return llm_graph_pools_spans(cparams) ? std::max(LLAMA_MAX_POOL_SPANS, cparams.n_seq_max) : ubatch.n_seqs_unq; +} + +std::vector llm_graph_pooling_spans(const llama_cparams & cparams, const llama_ubatch & ubatch) { + return llm_graph_pools_spans(cparams) ? llama_ubatch_get_spans(ubatch) : std::vector(); +} + void llm_graph_input_mean::set_input(const llama_ubatch * ubatch) { if (cparams.embeddings && (cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN || @@ -444,7 +459,19 @@ void llm_graph_input_mean::set_input(const llama_ubatch * ubatch) { GGML_ASSERT(ggml_backend_buffer_is_host(mean->buffer)); float * data = (float *) mean->data; - memset(mean->data, 0, n_tokens*n_seqs_unq*ggml_element_size(mean)); + + memset(mean->data, 0, ggml_nbytes(mean)); + + const auto spans = llm_graph_pooling_spans(cparams, *ubatch); + if (!spans.empty()) { + GGML_ASSERT((int64_t) spans.size() <= mean->ne[1]); + for (size_t s = 0; s < spans.size(); ++s) { + for (int32_t i = spans[s].start; i < spans[s].end; ++i) { + data[s*n_tokens + i] = 1.0f/float(spans[s].end - spans[s].start); + } + } + return; + } std::vector sums(n_seqs_unq, 0); for (int i = 0; i < n_tokens; i += n_seq_tokens) { @@ -490,16 +517,26 @@ void llm_graph_input_cls::set_input(const llama_ubatch * ubatch) { GGML_ASSERT(ggml_backend_buffer_is_host(cls->buffer)); uint32_t * data = (uint32_t *) cls->data; - memset(cls->data, 0, n_seqs_unq*ggml_element_size(cls)); - - std::vector target_pos(n_seqs_unq, -1); - std::vector target_row(n_seqs_unq, -1); const bool last = ( cparams.pooling_type == LLAMA_POOLING_TYPE_LAST || (cparams.pooling_type == LLAMA_POOLING_TYPE_RANK && cparams.causal_attn) ); + memset(cls->data, 0, ggml_nbytes(cls)); + + const auto spans = llm_graph_pooling_spans(cparams, *ubatch); + if (!spans.empty()) { + GGML_ASSERT((int64_t) spans.size() <= cls->ne[0]); + for (size_t s = 0; s < spans.size(); ++s) { + data[s] = last ? spans[s].end - 1 : spans[s].start; + } + return; + } + + std::vector target_pos(n_seqs_unq, -1); + std::vector target_row(n_seqs_unq, -1); + for (int i = 0; i < n_tokens; ++i) { const llama_pos pos = ubatch->pos[i]; @@ -636,28 +673,28 @@ void llm_graph_input_attn_no_cache::set_input(const llama_ubatch * ubatch) { const int64_t n_kv = self_attn_mask.raw->ne[0]; const int64_t n_tokens = ubatch->n_tokens; - const auto fill_mask = [&](auto * data, int64_t ne, int n_swa, llama_swa_type swa_type, bool causal, const int32_t * group) { + const auto fill_mask = [&](auto * data, int64_t ne, int n_swa, llama_swa_type swa_type, bool causal, const int32_t * scope) { using T = std::remove_reference_t; std::fill(data, data + ne, llama_cast(-INFINITY)); for (int i1 = 0; i1 < n_tokens; ++i1) { const llama_seq_id s1 = ubatch->seq_id[i1][0]; const llama_pos p1 = ubatch->pos[i1]; - const int32_t g1 = group ? group[i1] : 0; + const int32_t g1 = scope ? scope[i1] : 0; const uint64_t idst = i1*n_kv; for (int i0 = 0; i0 < n_tokens; ++i0) { const llama_seq_id s0 = ubatch->seq_id[i0][0]; const llama_pos p0 = ubatch->pos[i0]; - const int32_t g0 = group ? group[i0] : 0; + const int32_t g0 = scope ? scope[i0] : 0; // mask different sequences if (s0 != s1) { continue; } - // mask other questions, see llama_batch_ext_set_decision_group() + // mask other scopes, see llama_batch_ext_set_attn_scope() if (g0 != 0 && g1 != 0 && g0 != g1) { continue; } @@ -688,9 +725,9 @@ void llm_graph_input_attn_no_cache::set_input(const llama_ubatch * ubatch) { GGML_ASSERT(self_attn_mask.raw); GGML_ASSERT(ggml_backend_buffer_is_host(self_attn_mask.raw->buffer)); if (self_attn_mask.raw->type == GGML_TYPE_F16) { - fill_mask((ggml_fp16_t *) self_attn_mask.raw->data, ggml_nelements(self_attn_mask.raw), 0, LLAMA_SWA_TYPE_NONE, causal, ubatch->decision_group); + fill_mask((ggml_fp16_t *) self_attn_mask.raw->data, ggml_nelements(self_attn_mask.raw), 0, LLAMA_SWA_TYPE_NONE, causal, ubatch->attn_scope); } else { - fill_mask((float *) self_attn_mask.raw->data, ggml_nelements(self_attn_mask.raw), 0, LLAMA_SWA_TYPE_NONE, causal, ubatch->decision_group); + fill_mask((float *) self_attn_mask.raw->data, ggml_nelements(self_attn_mask.raw), 0, LLAMA_SWA_TYPE_NONE, causal, ubatch->attn_scope); } if (hparams.swa_type != LLAMA_SWA_TYPE_NONE) { @@ -1587,6 +1624,7 @@ void llm_graph_result::reset() { t_logits = nullptr; t_embd = nullptr; t_embd_pooled = nullptr; + t_embd_span = nullptr; t_h_nextn = nullptr; t_layer_inp.resize(LLAMA_MAX_LAYERS + 1); @@ -1639,6 +1677,9 @@ void llm_graph_result::set_outputs(const llm_graph_params & params) { if (t_embd_pooled != nullptr) { ggml_set_output(t_embd_pooled); } + if (t_embd_span != nullptr) { + ggml_set_output(t_embd_span); + } if (t_h_nextn != nullptr) { ggml_set_output(t_h_nextn); } @@ -3019,7 +3060,7 @@ ggml_tensor * llm_graph_context::build_inp_mean() const { auto & cur = inp->mean; - cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, ubatch.n_seqs_unq); + cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, llm_graph_n_pooled(cparams, ubatch)); ggml_set_input(cur); ggml_set_name(cur, "mean"); @@ -3033,7 +3074,7 @@ ggml_tensor * llm_graph_context::build_inp_cls() const { auto & cur = inp->cls; - cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, ubatch.n_seqs_unq); + cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, llm_graph_n_pooled(cparams, ubatch)); ggml_set_input(cur); ggml_set_name(cur, "cls"); @@ -4517,6 +4558,8 @@ void llm_graph_context::build_dense_out( ggml_tensor * cur = res->t_embd_pooled != nullptr ? res->t_embd_pooled : res->t_embd; GGML_ASSERT(cur != nullptr && "missing t_embd_pooled/t_embd"); + const bool is_span = cur == res->t_embd_span; + if (dense_2) { cur = build_lora_mm(dense_2, cur); } @@ -4528,6 +4571,9 @@ void llm_graph_context::build_dense_out( } cb(cur, "result_embd_pooled", -1); res->t_embd_pooled = cur; + if (is_span) { + res->t_embd_span = cur; + } ggml_build_forward_expand(gf, cur); } @@ -4631,6 +4677,11 @@ void llm_graph_context::build_pooling( cb(cur, "result_embd_pooled", -1); res->t_embd_pooled = cur; + // a model with its own head has set it already + if (res->t_embd_span == nullptr && !llm_graph_pooling_spans(cparams, ubatch).empty()) { + res->t_embd_span = cur; + } + ggml_build_forward_expand(gf, cur); } diff --git a/src/llama-graph.h b/src/llama-graph.h index a9e155012bbc..4406399cc995 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -283,6 +283,18 @@ class llm_graph_input_moe_ids : public llm_graph_input_i { const int64_t n_expert; }; +// max number of spans pooled in one ubatch +#define LLAMA_MAX_POOL_SPANS 64 + +// true if the context pools spans instead of sequences +bool llm_graph_pools_spans(const llama_cparams & cparams); + +// number of pooled rows, fixed when pooling spans to avoid a realloc +int64_t llm_graph_n_pooled(const llama_cparams & cparams, const llama_ubatch & ubatch); + +// the spans to pool, empty if pooling per sequence +std::vector llm_graph_pooling_spans(const llama_cparams & cparams, const llama_ubatch & ubatch); + class llm_graph_input_mean : public llm_graph_input_i { public: llm_graph_input_mean(const llama_cparams & cparams) : cparams(cparams) {} @@ -1006,6 +1018,7 @@ class llm_graph_result { ggml_tensor * get_logits() const { return t_logits; } ggml_tensor * get_embd() const { return t_embd; } ggml_tensor * get_embd_pooled() const { return t_embd_pooled; } + ggml_tensor * get_embd_span() const { return t_embd_span; } ggml_tensor * get_h_nextn() const { return t_h_nextn; } ggml_tensor * get_layer_inp(int il) const { return t_layer_inp[il]; } @@ -1047,6 +1060,7 @@ class llm_graph_result { ggml_tensor * t_logits = nullptr; ggml_tensor * t_embd = nullptr; ggml_tensor * t_embd_pooled = nullptr; + ggml_tensor * t_embd_span = nullptr; // [n_embd_out or 1, n_pooled], one row per span ggml_tensor * t_h_nextn = nullptr; // [n_embd, n_outputs] hidden state before final output norm std::vector t_layer_inp; diff --git a/src/llama-kv-cache-dsv4.cpp b/src/llama-kv-cache-dsv4.cpp index 9c0a9b22dffc..8a8e6a424427 100644 --- a/src/llama-kv-cache-dsv4.cpp +++ b/src/llama-kv-cache-dsv4.cpp @@ -168,8 +168,9 @@ static llama_ubatch dsv4_build_raw_write_ubatch(const llama_ubatch & ubatch) { /*.seq_idx =*/ data->seq_idx.data(), /*.output =*/ data->output.data(), /*.type =*/ nullptr, - /*.decision_order =*/ nullptr, - /*.decision_group =*/ nullptr, + /*.span =*/ nullptr, + /*.span_type =*/ nullptr, + /*.attn_scope =*/ nullptr, /*.data =*/ data, }; diff --git a/src/models/clef.cpp b/src/models/clef.cpp index 13756147612a..01d1589dc069 100644 --- a/src/models/clef.cpp +++ b/src/models/clef.cpp @@ -17,7 +17,7 @@ void llama_clef_head::load_hparams(llama_model_loader & ml, llama_hparams & hpar // used by the head ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps); - // the output is one score per token, see llama_batch_ext_set_decision_order() + // the output is one score per span, see llama_batch_ext_set_pool_span_type() hparams.n_embd_out_impl = 1; } @@ -133,50 +133,47 @@ struct clef_spans { }; std::vector questions; std::vector