diff --git a/.github/workflows/build-ibm.yml b/.github/workflows/build-ibm.yml index e896b87017ad..67ca8b683e40 100644 --- a/.github/workflows/build-ibm.yml +++ b/.github/workflows/build-ibm.yml @@ -100,7 +100,7 @@ jobs: run: | cd build echo "Fetch llama2c big-endian model" - wget https://huggingface.co/ggml-org/models/resolve/main/tinyllamas/stories260K-be.gguf + wget https://huggingface.co/ggml-org-dev/stories260K/resolve/main/stories260K-be.gguf ./bin/llama-completion -m stories260K-be.gguf -p "One day, Lily met a Shoggoth" -n 500 -c 256 - name: Test quantize (s390x) diff --git a/.github/workflows/ci-self-hosted-webgpu.yml b/.github/workflows/ci-self-hosted-webgpu.yml index e2ef40cd25d1..f94689006dbe 100644 --- a/.github/workflows/ci-self-hosted-webgpu.yml +++ b/.github/workflows/ci-self-hosted-webgpu.yml @@ -58,12 +58,7 @@ jobs: - name: Install dependencies run: | sudo apt update - sudo apt install -y software-properties-common - sudo add-apt-repository ppa:deadsnakes/ppa - sudo apt update - sudo apt install -y build-essential cmake libxcb-xinput0 libxcb-xinerama0 libxcb-cursor-dev libvulkan1 mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 libssl-dev time unzip wget python3.12 python3.12-venv - sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.12 1 - sudo update-alternatives --config python3 + sudo apt install -y build-essential cmake libxcb-xinput0 libxcb-xinerama0 libxcb-cursor-dev libvulkan1 mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 libssl-dev time unzip wget python3 python3-venv python3-pip - name: ccache uses: ggml-org/ccache-action@v1.2.24 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3b08ad94a3e1..867dcaf49420 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1363,6 +1363,8 @@ jobs: cp "${{ env.ONEAPI_ROOT }}/mkl/latest/bin/mkl_def.3.dll" ./build/bin cp "${{ env.ONEAPI_ROOT }}/mkl/latest/bin/mkl_avx2.3.dll" ./build/bin cp "${{ env.ONEAPI_ROOT }}/mkl/latest/bin/mkl_tbb_thread.3.dll" ./build/bin + cp "${{ env.ONEAPI_ROOT }}/mkl/latest/bin/mkl_intel_thread.3.dll" ./build/bin + cp "${{ env.ONEAPI_ROOT }}/mkl/latest/bin/libimalloc.dll" ./build/bin cp "${{ env.ONEAPI_ROOT }}/compiler/latest/bin/ur_adapter_level_zero.dll" ./build/bin cp "${{ env.ONEAPI_ROOT }}/compiler/latest/bin/ur_adapter_level_zero_v2.dll" ./build/bin diff --git a/.github/workflows/ui-build.yml b/.github/workflows/ui-build.yml index e0d8dd065e98..f229fcd04480 100644 --- a/.github/workflows/ui-build.yml +++ b/.github/workflows/ui-build.yml @@ -15,7 +15,7 @@ permissions: jobs: build: - runs-on: ubuntu-slim + runs-on: ubuntu-26.04-arm steps: - name: Checkout code diff --git a/README.md b/README.md index e1831c731e16..84e9eb5d9295 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # llama.cpp -![llama.cpp](https://raw.githubusercontent.com/ggml-org/llama.brand/refs/heads/master/logo/svg/cover/llama-cpp/cover-llama-cpp-dark.svg) +![llama.cpp](https://raw.githubusercontent.com/ggml-org/llama-brand/refs/heads/master/logo/svg/cover/llama-cpp/cover-llama-cpp-dark.svg)
diff --git a/cmake/download-models.cmake b/cmake/download-models.cmake index de252906a01f..57c141265be7 100644 --- a/cmake/download-models.cmake +++ b/cmake/download-models.cmake @@ -2,11 +2,11 @@ get_filename_component(DEST_DIR "${DEST}" DIRECTORY) file(MAKE_DIRECTORY "${DEST_DIR}") if(NOT EXISTS "${DEST}") - message(STATUS "Downloading ${NAME} from ggml-org/models...") + message(STATUS "Downloading ${NAME} from ${REPO}...") endif() file(DOWNLOAD - "https://huggingface.co/ggml-org/models/resolve/main/${NAME}?download=true" + "https://huggingface.co/${REPO}/resolve/main/${NAME}?download=true" "${DEST}" TLS_VERIFY ON EXPECTED_HASH ${HASH} diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 8e3c88dac9dc..e38485ca017c 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -66,6 +66,8 @@ add_library(${TARGET} chat-diff-analyzer.cpp chat-peg-parser.cpp chat-peg-parser.h + chat-tts-norm.cpp + chat-tts-norm.h chat.cpp chat.h common.cpp diff --git a/common/arg.cpp b/common/arg.cpp index 4b716398e8f3..6bf9355fb0ff 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -943,8 +943,8 @@ static bool common_params_parse_ex(int argc, char ** argv, common_params_context } const bool mcp_enabled = !params.mcp_servers_config.empty() || !params.mcp_servers_json.empty(); - if ((!params.server_tools.empty() || mcp_enabled) && !params.cors_origins_explicit) { - LOG_WRN("server tools or MCP servers are enabled, using localhost as default CORS origin (change via --cors-origins)\n"); + if ((!params.server_tools.empty() || mcp_enabled || params.ui_mcp_proxy) && !params.cors_origins_explicit) { + LOG_WRN("server tools, MCP servers or MCP proxy are enabled, using localhost as default CORS origin (change via --cors-origins)\n"); params.cors_origins = "localhost"; } @@ -2501,15 +2501,6 @@ common_params_context common_params_parser_init(common_params & params, llama_ex params.ppl_output_type = value; } ).set_examples({LLAMA_EXAMPLE_PERPLEXITY})); - add_opt(common_arg( - {"-dt", "--defrag-thold"}, "N", - string_format("KV cache defragmentation threshold (DEPRECATED)"), - [](common_params & params, const std::string & value) { - GGML_UNUSED(params); - GGML_UNUSED(value); - LOG_WRN("DEPRECATED: --defrag-thold is deprecated and no longer necessary to specify\n"); - } - ).set_env("LLAMA_ARG_DEFRAG_THOLD")); if (ex == LLAMA_EXAMPLE_SERVER) { // this is to make sure this option appears in the server-specific section of the help message add_opt(common_arg( @@ -3361,7 +3352,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex {"--cors-origins"}, "ORIGINS", string_format( "comma-separated list of allowed origins for CORS (default: %s)\n" - "if set to special value 'localhost', reflect the Origin header only if it is localhost", + "if set to special value 'localhost', only allow same-origin requests (e.g. the built-in UI)", params.cors_origins.c_str()), [](common_params & params, const std::string & value) { params.cors_origins = value; @@ -3417,7 +3408,8 @@ common_params_context common_params_parser_init(common_params & params, llama_ex add_opt(common_arg( {"--ui-mcp-proxy", "--webui-mcp-proxy"}, {"--no-ui-mcp-proxy", "--no-webui-mcp-proxy"}, - "experimental: whether to enable MCP CORS proxy - do not enable in untrusted environments (default: disabled)", + "experimental: whether to enable MCP CORS proxy, for the Web UI to reach public MCP servers without CORS headers; local and private addresses are refused - do not enable in untrusted environments (default: disabled)\n" + "note: for security reasons, this will limit --cors-origins to localhost by default", [](common_params & params, bool value) { params.ui_mcp_proxy = value; } @@ -3443,6 +3435,13 @@ common_params_context common_params_parser_init(common_params & params, llama_ex params.server_tools_runtime = value; } ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_TOOLS_RUNTIME")); + add_opt(common_arg( + {"--allow-unauthenticated-tools"}, + "allow server tools, MCP servers or MCP proxy on a non-loopback address without an API key - only for trusted networks (default: disabled)", + [](common_params & params) { + params.server_tools_allow_unauth = true; + } + ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_ALLOW_UNAUTHENTICATED_TOOLS")); add_opt(common_arg( {"--mcp-servers-config"}, "PATH", "experimental: path to JSON file with MCP server definitions (Cursor-compatible format) - do not enable in untrusted environments (default: none)\n" @@ -3668,6 +3667,13 @@ common_params_context common_params_parser_init(common_params & params, llama_ex } } ).set_examples({LLAMA_EXAMPLE_SERVER})); + add_opt(common_arg( + {"--media-allow-private-urls"}, + "allow http(s) media URLs (e.g. image_url) that point to local or private addresses (default: disabled, only public addresses)", + [](common_params & params) { + params.media_allow_private_urls = true; + } + ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_MEDIA_ALLOW_PRIVATE_URLS")); add_opt(common_arg( {"--models-dir"}, "PATH", "directory containing models for the router server (default: disabled)", diff --git a/common/chat-peg-parser.cpp b/common/chat-peg-parser.cpp index 4440b2ebd207..968cbfa98f6c 100644 --- a/common/chat-peg-parser.cpp +++ b/common/chat-peg-parser.cpp @@ -973,6 +973,21 @@ void common_chat_peg_gemma4_mapper::from_ast(const common_peg_ast_arena & arena, } } +using gemma4 = common_chat_peg_gemma4_mapper; + +// Collects the nearest descendants carrying tag, looking through the rules the parser +// wraps around the tagged nodes. +static void gemma4_collect(const common_peg_ast_arena & arena, const common_peg_ast_node & node, const std::string & tag, std::vector & out) { + for (auto child_id : node.children) { + const auto & child = arena.get(child_id); + if (child.tag == tag) { + out.push_back(child_id); + } else { + gemma4_collect(arena, child, tag, out); + } + } +} + static std::string gemma4_to_json(const common_peg_ast_arena & arena, common_peg_ast_id id) { const auto & node = arena.get(id); @@ -980,51 +995,45 @@ static std::string gemma4_to_json(const common_peg_ast_arena & arena, common_peg return ""; } - if (node.rule == "gemma4-number" || node.rule == "gemma4-bool" || node.rule == "gemma4-null") { + if (node.tag == gemma4::NUMBER || node.tag == gemma4::BOOL || node.tag == gemma4::NULL_) { return std::string(node.text); } - if (node.rule == "gemma4-string-content") { + if (node.tag == gemma4::STRING_CONTENT) { return escape_json_string_inner(node.sanitized_text()); } - if (node.rule == "gemma4-string") { + if (node.tag == gemma4::STRING) { std::string result = "\""; - if (!node.children.empty()) { - result += gemma4_to_json(arena, node.children[0]); - if (!node.is_partial) { - result += "\""; - } + for (auto child_id : node.children) { + result += gemma4_to_json(arena, child_id); + } + if (!node.is_partial) { + result += "\""; } return result; } - if (node.rule == "gemma4-array") { + if (node.tag == gemma4::ARRAY) { std::string result = "["; - - bool add_comma = false; - for (auto child_id : node.children) { - if (add_comma) { + for (size_t i = 0; i < node.children.size(); i++) { + if (i > 0) { result += ','; } - add_comma = true; - result += gemma4_to_json(arena, child_id); + result += gemma4_to_json(arena, node.children[i]); } - if (!node.is_partial) { result += ']'; } return result; } - if (node.rule == "gemma4-dict-key-name") { - return std::string(node.text); - } + if (node.tag == gemma4::DICT_KEY) { + auto name_id = arena.find_by_tag(node, gemma4::DICT_KEY_NAME); - if (node.rule == "gemma4-dict-key") { std::string result = "\""; - if (!node.children.empty()) { - result += escape_json_string_inner(gemma4_to_json(arena, node.children[0])); + if (name_id != COMMON_PEG_INVALID_AST_ID) { + result += escape_json_string_inner(std::string(arena.get(name_id).text)); } if (!node.is_partial) { result += "\":"; @@ -1032,40 +1041,29 @@ static std::string gemma4_to_json(const common_peg_ast_arena & arena, common_peg return result; } - if (node.rule == "gemma4-dict-kv") { - std::string result; - for (auto child_id : node.children) { - result += gemma4_to_json(arena, child_id); - } - return result; - } + if (node.tag == gemma4::DICT) { + std::vector members; + gemma4_collect(arena, node, gemma4::DICT_KV, members); - if (node.rule == "gemma4-dict") { std::string result = "{"; - - bool add_comma = false; - for (auto child_id : node.children) { - if (add_comma) { + for (size_t i = 0; i < members.size(); i++) { + if (i > 0) { result += ','; } - add_comma = true; - result += gemma4_to_json(arena, child_id); + result += gemma4_to_json(arena, members[i]); } - if (!node.is_partial) { result += '}'; } return result; } - if (node.rule == "gemma4-value") { - if (!node.children.empty()) { - return gemma4_to_json(arena, node.children[0]); - } - return ""; + // members, rules and other wrappers + std::string result; + for (auto child_id : node.children) { + result += gemma4_to_json(arena, child_id); } - - return ""; + return result; } void common_chat_peg_gemma4_mapper::visit(const common_peg_ast_arena & arena, common_peg_ast_id id) { diff --git a/common/chat-peg-parser.h b/common/chat-peg-parser.h index 114fa049fa74..b827b60b059c 100644 --- a/common/chat-peg-parser.h +++ b/common/chat-peg-parser.h @@ -34,6 +34,18 @@ class common_chat_peg_mapper { class common_chat_peg_gemma4_mapper : public common_chat_peg_mapper { public: + // Tags of the Gemma 4 argument syntax. The parser may wrap them in any rules. + static constexpr const char * STRING = "gemma4-string"; + static constexpr const char * STRING_CONTENT = "gemma4-string-content"; + static constexpr const char * NUMBER = "gemma4-number"; + static constexpr const char * BOOL = "gemma4-bool"; + static constexpr const char * NULL_ = "gemma4-null"; + static constexpr const char * ARRAY = "gemma4-array"; + static constexpr const char * DICT = "gemma4-dict"; + static constexpr const char * DICT_KV = "gemma4-dict-kv"; + static constexpr const char * DICT_KEY = "gemma4-dict-key"; + static constexpr const char * DICT_KEY_NAME = "gemma4-dict-key-name"; + common_chat_peg_gemma4_mapper(common_chat_msg & msg) : common_chat_peg_mapper(msg) {} virtual void from_ast(const common_peg_ast_arena & arena, const common_peg_parse_result & result); private: diff --git a/common/chat-tts-norm.cpp b/common/chat-tts-norm.cpp new file mode 100644 index 000000000000..f84540ff96e0 --- /dev/null +++ b/common/chat-tts-norm.cpp @@ -0,0 +1,864 @@ +#include "chat-tts-norm.h" + +#include "jinja/runtime.h" +#include "jinja/value.h" + +#include +#include +#include +#include +#include + +// TTS normalization patterns, see docs/tts-norm-patterns.md for the specification +// keep this file in sync with the python reference: scripts/chat_tts_norm.py + +using namespace jinja; + +// +// character classes +// they are defined with explicit codepoint ranges, independent of any unicode database version, +// so that the C++ and python implementations agree on every codepoint +// + +struct tts_norm_range { + uint32_t lo; + uint32_t hi; +}; + +static const tts_norm_range TTS_NORM_SPACE[] = { + {0x0009, 0x000D}, {0x0020, 0x0020}, {0x0085, 0x0085}, {0x00A0, 0x00A0}, {0x1680, 0x1680}, + {0x2000, 0x200A}, {0x2028, 0x2029}, {0x202F, 0x202F}, {0x205F, 0x205F}, {0x3000, 0x3000}, +}; + +static const tts_norm_range TTS_NORM_PUNCT[] = { + {0x0021, 0x002F}, {0x003A, 0x0040}, {0x005B, 0x0060}, {0x007B, 0x007E}, + {0x00A1, 0x00A9}, {0x00AB, 0x00B4}, {0x00B6, 0x00B9}, {0x00BB, 0x00BF}, {0x00D7, 0x00D7}, {0x00F7, 0x00F7}, + {0x2010, 0x2027}, {0x2030, 0x205E}, {0x20A0, 0x20CF}, {0x2100, 0x218F}, {0x2190, 0x2BFF}, + {0x3001, 0x3003}, {0x3008, 0x3020}, {0x3030, 0x3030}, {0x303D, 0x303D}, {0x30FB, 0x30FB}, + {0xFE10, 0xFE19}, {0xFE30, 0xFE4F}, {0xFE50, 0xFE6B}, + {0xFF01, 0xFF0F}, {0xFF1A, 0xFF20}, {0xFF3B, 0xFF40}, {0xFF5B, 0xFF65}, + {0x1F000, 0x1FAFF}, +}; + +static const tts_norm_range TTS_NORM_CONTROL[] = { + {0x0000, 0x001F}, {0x007F, 0x009F}, {0x200B, 0x200F}, {0x2060, 0x206F}, {0xFEFF, 0xFEFF}, +}; + +static const tts_norm_range TTS_NORM_HAN[] = { + {0x2E80, 0x2FDF}, {0x3005, 0x3005}, {0x3007, 0x3007}, {0x3021, 0x3029}, {0x3038, 0x303B}, + {0x3400, 0x4DBF}, {0x4E00, 0x9FFF}, {0xF900, 0xFAFF}, {0x20000, 0x323AF}, +}; + +template +static bool tts_norm_in(const tts_norm_range (&ranges)[N], uint32_t c) { + for (const auto & r : ranges) { + if (c >= r.lo && c <= r.hi) { + return true; + } + } + return false; +} + +static bool tts_norm_is_alpha(uint32_t c) { + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { + return true; + } + if (c == 0xAA || c == 0xB5 || c == 0xBA) { + return true; + } + return c >= 0xC0 && !tts_norm_in(TTS_NORM_SPACE, c) && !tts_norm_in(TTS_NORM_PUNCT, c) && !tts_norm_in(TTS_NORM_CONTROL, c); +} + +// kind is one of "dspawulhc" +static bool tts_norm_class_match(char kind, uint32_t c) { + switch (kind) { + case 'd': return c >= '0' && c <= '9'; + case 's': return tts_norm_in(TTS_NORM_SPACE, c); + case 'p': return tts_norm_in(TTS_NORM_PUNCT, c); + case 'a': return tts_norm_is_alpha(c); + case 'w': return tts_norm_is_alpha(c) || (c >= '0' && c <= '9'); + case 'u': return c >= 'A' && c <= 'Z'; + case 'l': return c >= 'a' && c <= 'z'; + case 'h': return tts_norm_in(TTS_NORM_HAN, c); + case 'c': return tts_norm_in(TTS_NORM_CONTROL, c); + } + return false; +} + +static bool tts_norm_is_class_letter(uint32_t c) { + if (c >= 'A' && c <= 'Z') { + c += 'a' - 'A'; + } + return c < 0x80 && std::string("dspawulhc").find(static_cast(c)) != std::string::npos; +} + +static uint32_t tts_norm_ascii_lower(uint32_t c) { + return (c >= 'A' && c <= 'Z') ? c + ('a' - 'A') : c; +} + +static uint32_t tts_norm_ascii_swapcase(uint32_t c) { + if (c >= 'A' && c <= 'Z') return c + ('a' - 'A'); + if (c >= 'a' && c <= 'z') return c - ('a' - 'A'); + return c; +} + +static bool tts_norm_is_ascii_alnum(uint32_t c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); +} + +// invalid bytes are decoded as U+FFFD, one per byte; offs[i] is the byte offset of codepoint i, offs[n] = text size +static void tts_norm_decode_utf8(const std::string & s, std::vector & cpts, std::vector & offs) { + cpts.clear(); + offs.clear(); + size_t i = 0; + const size_t n = s.size(); + while (i < n) { + offs.push_back(i); + const unsigned char c = static_cast(s[i]); + uint32_t cp = 0; + size_t len = 0; + if (c < 0x80) { + cp = c; len = 1; + } else if ((c & 0xE0) == 0xC0) { + cp = c & 0x1F; len = 2; + } else if ((c & 0xF0) == 0xE0) { + cp = c & 0x0F; len = 3; + } else if ((c & 0xF8) == 0xF0) { + cp = c & 0x07; len = 4; + } + bool ok = len > 0 && i + len <= n; + for (size_t k = 1; ok && k < len; k++) { + const unsigned char cc = static_cast(s[i + k]); + if ((cc & 0xC0) != 0x80) { + ok = false; + } else { + cp = (cp << 6) | (cc & 0x3F); + } + } + if (!ok) { + cpts.push_back(0xFFFD); + i += 1; + } else { + cpts.push_back(cp); + i += len; + } + } + offs.push_back(n); +} + +// +// AST +// + +enum class tts_norm_op { + LITERAL, // one codepoint + SET, // one codepoint from a set; class escapes like %d are sets with a single class + ANY, // any codepoint + START, // ^ + END, // $ + BOUNDARY, // %b + GROUP, // (...), (?:...), (?...) + LOOKAHEAD, // (?=...), (?!...) + LOOKBEHIND, // (?<=c), (?> ranges; + std::vector classes; +}; + +struct tts_norm_item; +using tts_norm_seq = std::vector; + +struct tts_norm_pattern_node { + tts_norm_op op = tts_norm_op::GROUP; + uint32_t cp = 0; // LITERAL + tts_norm_set set; // SET + std::vector alts; // GROUP, LOOKAHEAD; LOOKBEHIND holds a single item + int capture = -1; // GROUP: capture index, -1 for non-capturing + bool neg = false; // LOOKAHEAD, LOOKBEHIND +}; + +static constexpr int TTS_NORM_INF = INT_MAX; +static constexpr int TTS_NORM_MAX_REPEAT = 1000; +static constexpr size_t TTS_NORM_MAX_PATTERN_LEN = 4096; + +struct tts_norm_item { + tts_norm_pattern_node atom; + int min = 1; + int max = 1; +}; + +static bool tts_norm_is_zero_width(tts_norm_op op) { + return op == tts_norm_op::START || op == tts_norm_op::END || op == tts_norm_op::BOUNDARY + || op == tts_norm_op::LOOKAHEAD || op == tts_norm_op::LOOKBEHIND; +} + +// +// parser +// + +struct tts_norm_parser { + std::vector s; + size_t p = 0; + size_t & n_caps; + + tts_norm_parser(std::vector src, size_t & n_caps) : s(std::move(src)), n_caps(n_caps) {} + + [[noreturn]] void fail(const std::string & msg) const { + throw std::runtime_error("invalid TTS norm pattern: " + msg + " at position " + std::to_string(p)); + } + + bool eof() const { return p >= s.size(); } + uint32_t peek() const { return s[p]; } + bool peek_is(uint32_t c) const { return !eof() && s[p] == c; } + + void expect(uint32_t c, const char * what) { + if (!peek_is(c)) { + fail(std::string("expected ") + what); + } + p++; + } + + std::vector parse_alts() { + std::vector alts; + alts.push_back(parse_seq()); + while (peek_is('|')) { + p++; + alts.push_back(parse_seq()); + } + return alts; + } + + tts_norm_seq parse_seq() { + tts_norm_seq seq; + while (!eof() && peek() != '|' && peek() != ')') { + tts_norm_item item; + item.atom = parse_atom(); + parse_quantifier(item); + seq.push_back(std::move(item)); + } + return seq; + } + + int parse_int() { + if (eof() || peek() < '0' || peek() > '9') { + fail("expected number in quantifier"); + } + int v = 0; + while (!eof() && peek() >= '0' && peek() <= '9') { + v = v * 10 + static_cast(peek() - '0'); + if (v > TTS_NORM_MAX_REPEAT) { + fail("repetition count exceeds " + std::to_string(TTS_NORM_MAX_REPEAT)); + } + p++; + } + return v; + } + + void parse_quantifier(tts_norm_item & item) { + if (eof()) { + return; + } + const uint32_t c = peek(); + if (c != '?' && c != '*' && c != '+' && c != '{') { + return; + } + if (tts_norm_is_zero_width(item.atom.op)) { + fail("zero-width assertion cannot be repeated"); + } + p++; + if (c == '?') { + item.min = 0; item.max = 1; + } else if (c == '*') { + item.min = 0; item.max = TTS_NORM_INF; + } else if (c == '+') { + item.min = 1; item.max = TTS_NORM_INF; + } else { + item.min = parse_int(); + item.max = item.min; + if (peek_is(',')) { + p++; + item.max = peek_is('}') ? TTS_NORM_INF : parse_int(); + } + expect('}', "'}' to close quantifier"); + if (item.max < item.min) { + fail("quantifier max is smaller than min"); + } + } + if (!eof() && (peek() == '?' || peek() == '*' || peek() == '+' || peek() == '{')) { + fail("multiple quantifiers"); + } + } + + tts_norm_pattern_node parse_group() { + // '(' already consumed + tts_norm_pattern_node node; + node.op = tts_norm_op::GROUP; + if (peek_is('?')) { + p++; + if (eof()) { + fail("unterminated group"); + } + const uint32_t c = peek(); + if (c == ':') { + p++; + } else if (c == '=' || c == '!') { + p++; + node.op = tts_norm_op::LOOKAHEAD; + node.neg = c == '!'; + } else if (c == '<' && p + 1 < s.size() && (s[p + 1] == '=' || s[p + 1] == '!')) { + node.op = tts_norm_op::LOOKBEHIND; + node.neg = s[p + 1] == '!'; + p += 2; + tts_norm_item item; + if (eof() || peek() == ')') { + fail("lookbehind must contain exactly one codepoint matcher"); + } + item.atom = parse_atom(); + if (item.atom.op != tts_norm_op::LITERAL && item.atom.op != tts_norm_op::SET && item.atom.op != tts_norm_op::ANY) { + fail("lookbehind must contain exactly one codepoint matcher"); + } + if (!peek_is(')')) { + fail("lookbehind must contain exactly one codepoint matcher"); + } + p++; + node.alts.push_back(tts_norm_seq{}); + node.alts[0].push_back(std::move(item)); + return node; + } else if (c == 'i') { + fail("(?i) is only allowed at the start of the pattern"); + } else { + fail("unknown group type"); + } + } else { + node.capture = static_cast(n_caps++); + } + node.alts = parse_alts(); + expect(')', "')' to close group"); + return node; + } + + // after '%' inside or outside of a set + // returns true if it is a class (stored in cls), false if it is a literal (stored in lit) + bool parse_escape(bool in_set, tts_norm_class & cls, uint32_t & lit, bool & boundary) { + boundary = false; + if (eof()) { + fail("dangling '%'"); + } + const uint32_t e = s[p++]; + if (tts_norm_is_class_letter(e)) { + cls.kind = static_cast(tts_norm_ascii_lower(e)); + cls.neg = e >= 'A' && e <= 'Z'; + return true; + } + if (e == 'b' && !in_set) { + boundary = true; + return false; + } + if (tts_norm_is_ascii_alnum(e)) { + p--; + fail(std::string("unknown escape '%") + static_cast(e) + "'"); + } + lit = e; + return false; + } + + tts_norm_pattern_node parse_set() { + // '[' already consumed + tts_norm_pattern_node node; + node.op = tts_norm_op::SET; + if (peek_is('^')) { + node.set.neg = true; + p++; + } + bool empty = true; + while (true) { + if (eof()) { + fail("unterminated set"); + } + if (peek() == ']') { + p++; + break; + } + empty = false; + uint32_t lo = 0; + if (peek() == '%') { + p++; + tts_norm_class cls{}; + bool boundary = false; + if (parse_escape(true, cls, lo, boundary)) { + node.set.classes.push_back(cls); + continue; + } + } else { + lo = s[p++]; + } + uint32_t hi = lo; + if (peek_is('-') && p + 1 < s.size() && s[p + 1] != ']') { + p++; + if (peek() == '%') { + p++; + tts_norm_class cls{}; + bool boundary = false; + if (parse_escape(true, cls, hi, boundary)) { + fail("character class cannot be used in a range"); + } + } else { + hi = s[p++]; + } + if (hi < lo) { + fail("invalid range in set"); + } + } + node.set.ranges.emplace_back(lo, hi); + } + if (empty) { + fail("empty set"); + } + return node; + } + + tts_norm_pattern_node parse_atom() { + const uint32_t c = s[p++]; + tts_norm_pattern_node node; + switch (c) { + case '(': + return parse_group(); + case '[': + return parse_set(); + case '.': + node.op = tts_norm_op::ANY; + return node; + case '^': + node.op = tts_norm_op::START; + return node; + case '$': + node.op = tts_norm_op::END; + return node; + case '%': { + tts_norm_class cls{}; + uint32_t lit = 0; + bool boundary = false; + if (parse_escape(false, cls, lit, boundary)) { + node.op = tts_norm_op::SET; + node.set.classes.push_back(cls); + } else if (boundary) { + node.op = tts_norm_op::BOUNDARY; + } else { + node.op = tts_norm_op::LITERAL; + node.cp = lit; + } + return node; + } + case '?': + case '*': + case '+': + case '{': + p--; + fail("nothing to repeat"); + case ']': + case '}': + p--; + fail(std::string("unescaped '") + static_cast(c) + "', use '%" + static_cast(c) + "'"); + default: + node.op = tts_norm_op::LITERAL; + node.cp = c; + return node; + } + } +}; + +// +// matcher +// PEG-style: alternatives are ordered (the first one that matches wins) and quantifiers are greedy and possessive +// (they never give back what they consumed), so there is no backtracking +// + +struct tts_norm_matcher { + const std::vector & t; + bool icase; + std::vector> caps; + + bool is_w(size_t i) const { + return i < t.size() && tts_norm_class_match('w', t[i]); + } + + bool set_match(const tts_norm_set & st, uint32_t c) const { + auto test = [&](uint32_t x) { + for (const auto & r : st.ranges) { + if (x >= r.first && x <= r.second) { + return true; + } + } + for (const auto & k : st.classes) { + if (tts_norm_class_match(k.kind, x) != k.neg) { + return true; + } + } + return false; + }; + bool m = test(c); + if (!m && icase) { + const uint32_t o = tts_norm_ascii_swapcase(c); + if (o != c) { + m = test(o); + } + } + return m != st.neg; + } + + bool match_alts(const std::vector & alts, size_t i, size_t & end) { + for (const auto & seq : alts) { + auto saved = caps; + if (match_seq(seq, i, end)) { + return true; + } + caps = std::move(saved); + } + return false; + } + + bool match_seq(const tts_norm_seq & seq, size_t i, size_t & end) { + size_t pos = i; + for (const auto & it : seq) { + int count = 0; + while (count < it.max) { + const bool is_group = it.atom.op == tts_norm_op::GROUP; + std::vector> saved; + if (is_group) { + saved = caps; + } + size_t e = pos; + if (!match_once(it.atom, pos, e)) { + if (is_group) { + caps = std::move(saved); + } + break; + } + if (e == pos) { + // an empty iteration would repeat forever, it satisfies any remaining minimum + count = std::max(count + 1, it.min); + break; + } + pos = e; + count++; + } + if (count < it.min) { + return false; + } + } + end = pos; + return true; + } + + bool match_once(const tts_norm_pattern_node & node, size_t i, size_t & end) { + const size_t n = t.size(); + switch (node.op) { + case tts_norm_op::LITERAL: + if (i < n && (t[i] == node.cp || (icase && tts_norm_ascii_lower(t[i]) == tts_norm_ascii_lower(node.cp)))) { + end = i + 1; + return true; + } + return false; + case tts_norm_op::SET: + if (i < n && set_match(node.set, t[i])) { + end = i + 1; + return true; + } + return false; + case tts_norm_op::ANY: + if (i < n) { + end = i + 1; + return true; + } + return false; + case tts_norm_op::START: + end = i; + return i == 0; + case tts_norm_op::END: + end = i; + return i == n; + case tts_norm_op::BOUNDARY: + end = i; + return (i > 0 && is_w(i - 1)) != is_w(i); + case tts_norm_op::GROUP: { + size_t e = i; + if (!match_alts(node.alts, i, e)) { + return false; + } + if (node.capture >= 0) { + caps[node.capture] = {static_cast(i), static_cast(e)}; + } + end = e; + return true; + } + case tts_norm_op::LOOKAHEAD: { + // captures made inside a lookahead are discarded + auto saved = caps; + size_t e = i; + const bool ok = match_alts(node.alts, i, e); + caps = std::move(saved); + end = i; + return ok != node.neg; + } + case tts_norm_op::LOOKBEHIND: { + size_t e = 0; + const bool ok = i > 0 && match_once(node.alts[0][0].atom, i - 1, e) && e == i; + end = i; + return ok != node.neg; + } + } + return false; + } +}; + +// +// common_tts_norm_pattern +// + +common_tts_norm_pattern::common_tts_norm_pattern(const std::string & src) { + if (src.size() > TTS_NORM_MAX_PATTERN_LEN) { + throw std::runtime_error("invalid TTS norm pattern: pattern is longer than " + std::to_string(TTS_NORM_MAX_PATTERN_LEN) + " bytes"); + } + std::vector cpts; + std::vector offs; + tts_norm_decode_utf8(src, cpts, offs); + + tts_norm_parser parser(std::move(cpts), n_caps); + static const std::vector icase_prefix = {'(', '?', 'i', ')'}; + if (parser.s.size() >= 4 && std::equal(icase_prefix.begin(), icase_prefix.end(), parser.s.begin())) { + icase = true; + parser.p = 4; + } + + root = std::make_unique(); + root->op = tts_norm_op::GROUP; + root->alts = parser.parse_alts(); + if (!parser.eof()) { + parser.fail("unbalanced ')'"); + } +} + +common_tts_norm_pattern::~common_tts_norm_pattern() = default; +common_tts_norm_pattern::common_tts_norm_pattern(common_tts_norm_pattern &&) noexcept = default; +common_tts_norm_pattern & common_tts_norm_pattern::operator=(common_tts_norm_pattern &&) noexcept = default; + +bool common_tts_norm_pattern::match_at(const std::vector & cpts, size_t pos, size_t & end, std::vector> & groups) const { + tts_norm_matcher m{cpts, icase, std::vector>(n_caps, {-1, -1})}; + size_t e = pos; + if (!m.match_alts(root->alts, pos, e)) { + return false; + } + end = e; + groups = std::move(m.caps); + return true; +} + +size_t common_tts_norm_pattern::n_groups() const { + return n_caps; +} + +// +// scan / sub +// + +std::vector common_tts_norm_scan(const std::string & text, const std::vector & rules) { + std::vector cpts; + std::vector offs; + tts_norm_decode_utf8(text, cpts, offs); + + std::vector out; + const size_t n = cpts.size(); + size_t i = 0; + size_t pending = 0; // start of the current unmatched run + std::vector> groups; + + while (i < n) { + bool matched = false; + for (size_t r = 0; r < rules.size(); r++) { + size_t end = i; + if (rules[r]->match_at(cpts, i, end, groups) && end > i) { + if (pending < i) { + out.push_back({-1, offs[pending], offs[i], {}}); + } + common_tts_norm_segment seg; + seg.rule = static_cast(r); + seg.start = offs[i]; + seg.end = offs[end]; + for (const auto & g : groups) { + if (g.first < 0) { + seg.groups.emplace_back(std::string::npos, std::string::npos); + } else { + seg.groups.emplace_back(offs[g.first], offs[g.second]); + } + } + out.push_back(std::move(seg)); + i = end; + pending = i; + matched = true; + break; + } + } + if (!matched) { + i++; + } + } + if (pending < n) { + out.push_back({-1, offs[pending], offs[n], {}}); + } + return out; +} + +struct tts_norm_repl_piece { + std::string literal; + int group = -1; // 0 = whole match, 1.. = groups +}; + +static std::vector tts_norm_parse_repl(const std::string & repl, const common_tts_norm_pattern & pattern) { + std::vector pieces; + std::string lit; + auto flush = [&]() { + if (!lit.empty()) { + pieces.push_back({lit, -1}); + lit.clear(); + } + }; + for (size_t i = 0; i < repl.size(); i++) { + if (repl[i] != '%') { + lit += repl[i]; + continue; + } + if (i + 1 >= repl.size()) { + throw std::runtime_error("invalid TTS norm replacement: dangling '%'"); + } + const char c = repl[++i]; + if (c == '%') { + lit += '%'; + } else if (c >= '0' && c <= '9') { + const int g = c - '0'; + if (static_cast(g) > pattern.n_groups()) { + throw std::runtime_error("invalid TTS norm replacement: group %" + std::string(1, c) + " does not exist"); + } + flush(); + pieces.push_back({"", g}); + } else { + throw std::runtime_error("invalid TTS norm replacement: unknown escape '%" + std::string(1, c) + "'"); + } + } + flush(); + return pieces; +} + +std::string common_tts_norm_sub(const std::string & text, const common_tts_norm_pattern & pattern, const std::string & repl) { + const auto pieces = tts_norm_parse_repl(repl, pattern); + std::string out; + for (const auto & seg : common_tts_norm_scan(text, {&pattern})) { + if (seg.rule < 0) { + out.append(text, seg.start, seg.end - seg.start); + continue; + } + for (const auto & piece : pieces) { + if (piece.group < 0) { + out += piece.literal; + } else if (piece.group == 0) { + out.append(text, seg.start, seg.end - seg.start); + } else { + const auto & g = seg.groups[piece.group - 1]; + if (g.first != std::string::npos) { + out.append(text, g.first, g.second - g.first); + } + } + } + } + return out; +} + +// +// template builtins +// + +// rules can be: a pattern string (rule name "match"), a dict {name: pattern}, or a list of [name, pattern] pairs +static std::vector> tts_norm_rules_from_value(const value & v) { + std::vector> rules; + if (is_val(v)) { + rules.emplace_back("match", v->as_string().str()); + } else if (is_val(v)) { + for (const auto & kv : v->as_ordered_object()) { + if (!is_val(kv.second)) { + throw std::runtime_error("tts_norm_scan: rule pattern must be a string"); + } + rules.emplace_back(kv.first->as_string().str(), kv.second->as_string().str()); + } + } else if (is_val(v)) { + for (const auto & item : v->as_array()) { + if (!is_val(item) || item->as_array().size() != 2 + || !is_val(item->as_array()[0]) || !is_val(item->as_array()[1])) { + throw std::runtime_error("tts_norm_scan: each rule must be a [name, pattern] pair of strings"); + } + rules.emplace_back(item->as_array()[0]->as_string().str(), item->as_array()[1]->as_string().str()); + } + } else { + throw std::runtime_error("tts_norm_scan: rules must be a string, a dict or a list of [name, pattern] pairs, got " + v->type()); + } + return rules; +} + +static value tts_norm_builtin_scan(const func_args & args) { + args.ensure_count(2, 2); + args.ensure_val(args.get_pos(0)); + const string text_val = args.get_pos(0)->as_string(); + const std::string text = text_val.str(); + const bool is_input = text_val.all_parts_are_input(); + + const auto rule_srcs = tts_norm_rules_from_value(args.get_pos(1)); + std::vector patterns; + patterns.reserve(rule_srcs.size()); + std::vector ptrs; + for (const auto & r : rule_srcs) { + patterns.emplace_back(r.second); + } + for (const auto & p : patterns) { + ptrs.push_back(&p); + } + + auto mk_str = [&](size_t start, size_t end) -> value { + return mk_val(string(text.substr(start, end - start), is_input)); + }; + + auto out = mk_val(); + for (const auto & seg : common_tts_norm_scan(text, ptrs)) { + auto groups = mk_val(); + for (const auto & g : seg.groups) { + // groups that did not participate are empty strings, so they render as nothing and are falsy + groups->push_back(g.first == std::string::npos ? mk_str(0, 0) : mk_str(g.first, g.second)); + } + auto obj = mk_val(); + obj->insert("rule", seg.rule < 0 ? value(mk_val()) : value(mk_val(rule_srcs[seg.rule].first))); + obj->insert("text", mk_str(seg.start, seg.end)); + obj->insert("groups", groups); + out->push_back(obj); + } + return out; +} + +static value tts_norm_builtin_sub(const func_args & args) { + args.ensure_count(3, 3); + args.ensure_vals(); + const string text_val = args.get_pos(0)->as_string(); + const common_tts_norm_pattern pattern(args.get_pos(1)->as_string().str()); + const std::string res = common_tts_norm_sub(text_val.str(), pattern, args.get_pos(2)->as_string().str()); + return mk_val(string(res, text_val.all_parts_are_input())); +} + +void common_chat_tts_norm_add_builtins(context & ctx) { + ctx.set_val("tts_norm_scan", mk_val("tts_norm_scan", tts_norm_builtin_scan)); + ctx.set_val("tts_norm_sub", mk_val("tts_norm_sub", tts_norm_builtin_sub)); +} + diff --git a/common/chat-tts-norm.h b/common/chat-tts-norm.h new file mode 100644 index 000000000000..14695bb52d99 --- /dev/null +++ b/common/chat-tts-norm.h @@ -0,0 +1,62 @@ +#pragma once + +#include +#include +#include +#include +#include + +// TTS normalization patterns: a small, fully specified matching language for TTS text normalization templates +// +// it is NOT a regex engine: the semantics are defined by llama.cpp (see docs/tts-norm-patterns.md), so that this +// implementation and the python reference (scripts/chat_tts_norm.py) give the same result for every input +// +// two functions are exposed to task templates (e.g. "tts") via common_chat_tts_norm_add_builtins(): +// tts_norm_scan(text, rules) -> list of segments {rule, text, groups} +// tts_norm_sub(text, pattern, repl) -> string + +namespace jinja { +struct context; +} + +struct tts_norm_pattern_node; + +class common_tts_norm_pattern { +public: + // throws std::runtime_error on invalid pattern + explicit common_tts_norm_pattern(const std::string & src); + ~common_tts_norm_pattern(); + common_tts_norm_pattern(common_tts_norm_pattern &&) noexcept; + common_tts_norm_pattern & operator=(common_tts_norm_pattern &&) noexcept; + + // match anchored at codepoint index pos; on success, end is the codepoint index after the match + // groups[i] holds [start, end) codepoint indices of capture i+1, or {-1, -1} if the group did not participate + bool match_at(const std::vector & cpts, size_t pos, size_t & end, std::vector> & groups) const; + + size_t n_groups() const; + +private: + std::unique_ptr root; + size_t n_caps = 0; + bool icase = false; +}; + +// segment produced by common_tts_norm_scan(); byte offsets into the input text +struct common_tts_norm_segment { + int rule = -1; // index of the matched rule, -1 for unmatched text + size_t start = 0; + size_t end = 0; + std::vector> groups; // byte offsets; {npos, npos} for groups that did not participate +}; + +// split text into matched and unmatched segments +// at each position, rules are tried in order and the first non-empty match wins; otherwise one codepoint is skipped +std::vector common_tts_norm_scan(const std::string & text, const std::vector & rules); + +// replace every non-overlapping match of pattern with repl +// repl references: %0 (whole match), %1..%9 (groups), %% (literal percent) +std::string common_tts_norm_sub(const std::string & text, const common_tts_norm_pattern & pattern, const std::string & repl); + +// add tts_norm_scan() and tts_norm_sub() to the context of a task template +// they are not jinja global builtins on purpose: chat templates are not affected +void common_chat_tts_norm_add_builtins(jinja::context & ctx); diff --git a/common/chat.cpp b/common/chat.cpp index ef9b853f022c..da29cd671d4c 100644 --- a/common/chat.cpp +++ b/common/chat.cpp @@ -3,6 +3,7 @@ #include "chat-auto-parser-helpers.h" #include "chat-auto-parser.h" #include "chat-peg-parser.h" +#include "chat-tts-norm.h" #include "common.h" #include "ggml.h" #include "json-schema-to-grammar.h" @@ -807,6 +808,8 @@ bool common_chat_templates_was_explicit(const struct common_chat_templates * tmp // renders a task template (e.g. "tts") with the given variables static std::string common_chat_template_render(const common_chat_template & tmpl, const json & vars) { jinja::context ctx(tmpl.source()); + // text normalization helpers: tts_norm_scan() and tts_norm_sub(), see docs/tts-norm-patterns.md + common_chat_tts_norm_add_builtins(ctx); jinja::global_from_json(ctx, vars, false); ctx.set_val("bos_token", jinja::mk_val(tmpl.bos_token())); ctx.set_val("eos_token", jinja::mk_val(tmpl.eos_token())); @@ -1274,13 +1277,6 @@ static common_chat_params common_chat_params_init_lfm2_5(const common_chat_templ return common_chat_params_init_lfm2(tmpl, inputs, /* tool_list_tokens = */ false); } -// Older gemma4 templates need their tool responses rewritten before rendering -static common_chat_params common_chat_params_init_gemma4_legacy(const common_chat_template & tmpl, const autoparser::generation_params & inputs) { - auto adjusted = inputs; - workaround::convert_tool_responses_gemma4(adjusted.messages); - return common_chat_params_init_gemma4(tmpl, adjusted); -} - // Pick the dedicated handler for a template from its source, or null for the autoparser. // Order matters: the first match wins, and later checks assume the earlier ones did not match. static common_chat_params_init_fn common_chat_template_detect_params_init(const std::string & src) { @@ -1415,11 +1411,6 @@ static common_chat_params_init_fn common_chat_template_detect_params_init(const // Gemma4 format detection if (src.find("'<|tool_call>call:'") != std::string::npos) { LOG_DBG("Using specialized template: Gemma4\n"); - if (src.find("{#- OpenAI Chat Completions:") == std::string::npos) { - LOG_WRN("%s: detected an outdated gemma4 chat template, applying compatibility workarounds. " - "Consider updating to the official template.\n", __func__); - return common_chat_params_init_gemma4_legacy; - } return common_chat_params_init_gemma4; } diff --git a/common/common.h b/common/common.h index cc6eef833bb3..6043ab34239f 100644 --- a/common/common.h +++ b/common/common.h @@ -705,6 +705,7 @@ struct common_params { // enable built-in tools std::vector server_tools; std::string server_tools_runtime; + bool server_tools_allow_unauth = false; // allow tools/MCP on a non-loopback address without API key // MCP server configs (Cursor-compatible JSON) std::string mcp_servers_config; // path to JSON file with MCP server definitions @@ -722,6 +723,7 @@ struct common_params { std::string slot_save_path; std::string media_path; // path to directory for loading media files + bool media_allow_private_urls = false; // allow http(s) media URLs on local or private addresses float slot_prompt_similarity = 0.1f; @@ -1147,7 +1149,7 @@ struct common_batch { // attach a state embedding (e.g. the target hidden state for MTP) to the entry at idx, can only be set once per entry bool set_embd_state(int32_t idx, llama_embd state); - // the state of entry idx is row `row` of the h_nextn device buffer of the state source context, see llama_set_embd_state_src() + // the state of entry idx is row `row` of the h_nextn device buffer of the state source context, see llama_set_ctx_state_src() bool set_embd_state_row(int32_t idx, int32_t row); // add an embedding-only entry (no token id) diff --git a/common/download.cpp b/common/download.cpp index fbd192721589..682fd6e3ef7a 100644 --- a/common/download.cpp +++ b/common/download.cpp @@ -461,38 +461,55 @@ static int common_download_file_single_online(const std::string & url, return finish(success ? head->status : -1); } -std::pair> common_remote_get_content(const std::string & url, +std::pair> common_remote_get_content(const std::string & url_in, const common_remote_params & params) { - auto [cli, parts] = common_http_client(url); + static constexpr int max_redirects = 5; + std::string url = url_in; + for (int n_redirects = 0; ; n_redirects++) { + auto [cli, parts] = common_http_client(url); + + httplib::Headers headers; + for (const auto & h : params.headers) { + headers.emplace(h.first, h.second); + } + if (headers.find("User-Agent") == headers.end()) { + headers.emplace("User-Agent", "llama-cpp/" + std::string(llama_build_info())); + } - httplib::Headers headers; - for (const auto & h : params.headers) { - headers.emplace(h.first, h.second); - } - if (headers.find("User-Agent") == headers.end()) { - headers.emplace("User-Agent", "llama-cpp/" + std::string(llama_build_info())); - } + if (params.timeout > 0) { + cli.set_read_timeout(params.timeout, 0); + cli.set_write_timeout(params.timeout, 0); + } + if (params.resolve_host) { + // pin checked address, follow redirects manually to check each hop + cli.set_direct_hostname_addr_map({{parts.host, params.resolve_host(parts.host)}}); + cli.set_follow_location(false); + } - if (params.timeout > 0) { - cli.set_read_timeout(params.timeout, 0); - cli.set_write_timeout(params.timeout, 0); - } + std::vector buf; + auto res = cli.Get(parts.path, headers, + [&](const char *data, size_t len) { + buf.insert(buf.end(), data, data + len); + return params.max_size == 0 || + buf.size() <= static_cast(params.max_size); + }, + nullptr + ); + + if (!res) { + throw std::runtime_error("error: cannot make GET request"); + } - std::vector buf; - auto res = cli.Get(parts.path, headers, - [&](const char *data, size_t len) { - buf.insert(buf.end(), data, data + len); - return params.max_size == 0 || - buf.size() <= static_cast(params.max_size); - }, - nullptr - ); + if (params.resolve_host && res->status >= 300 && res->status < 400 && res->has_header("Location")) { + if (n_redirects >= max_redirects) { + throw std::runtime_error("error: too many redirects"); + } + url = common_http_resolve_location(url, res->get_header_value("Location")); + continue; + } - if (!res) { - throw std::runtime_error("error: cannot make GET request"); + return { res->status, std::move(buf) }; } - - return { res->status, std::move(buf) }; } int common_download_file_single(const std::string & url, diff --git a/common/download.h b/common/download.h index dd09d68eeff9..c0ff5da2f687 100644 --- a/common/download.h +++ b/common/download.h @@ -31,6 +31,8 @@ struct common_remote_params { common_header_list headers; long timeout = 0; // in seconds, 0 means no timeout long max_size = 0; // unlimited if 0 + // if set: called per hop (redirects too), returns the address to connect to, throws to refuse + std::function resolve_host; }; // get remote file content, returns diff --git a/common/http.h b/common/http.h index 10d017f17ed5..d8cfde262019 100644 --- a/common/http.h +++ b/common/http.h @@ -99,6 +99,26 @@ static common_http_url common_http_parse_url(const std::string & url) { return parts; } +// resolve a redirect Location against the URL it came from +static std::string common_http_resolve_location(const std::string & base_url, const std::string & location) { + if (location.find("://") != std::string::npos) { + return location; + } + const common_http_url base = common_http_parse_url(base_url); + if (location.compare(0, 2, "//") == 0) { + return base.scheme + ":" + location; + } + const std::string origin = base.scheme + "://" + common_http_format_host(base.host) + ":" + std::to_string(base.port); + const std::string path = base.path.substr(0, base.path.find('?')); + if (!location.empty() && location[0] == '/') { + return origin + location; + } + if (!location.empty() && location[0] == '?') { + return origin + path + location; + } + return origin + path.substr(0, path.rfind('/') + 1) + location; +} + // match a loopback destination: a remote proxy can never reach the client machine's own // loopback, so these hosts are always contacted directly, before NO_PROXY is consulted // (similar to Go's net/http) diff --git a/common/jinja/lexer.h b/common/jinja/lexer.h index 439c85764c24..3f4ebb62a8d5 100644 --- a/common/jinja/lexer.h +++ b/common/jinja/lexer.h @@ -37,6 +37,7 @@ struct token { call_operator, // () additive_binary_operator, // + - ~ multiplicative_binary_operator, // * / % + power_operator, // ** comparison_binary_operator, // < > <= >= == != unary_operator, // ! - + comment, // {# ... #} @@ -71,6 +72,7 @@ static std::string type_to_string(token::type t) { case token::call_operator: return "call_operator"; case token::additive_binary_operator: return "additive_binary_operator"; case token::multiplicative_binary_operator: return "multiplicative_binary_operator"; + case token::power_operator: return "power_operator"; case token::comparison_binary_operator: return "comparison_binary_operator"; case token::unary_operator: return "unary_operator"; case token::comment: return "comment"; @@ -137,6 +139,7 @@ struct lexer { {"+", token::additive_binary_operator}, {"-", token::additive_binary_operator}, {"~", token::additive_binary_operator}, + {"**", token::power_operator}, {"*", token::multiplicative_binary_operator}, {"/", token::multiplicative_binary_operator}, {"%", token::multiplicative_binary_operator}, diff --git a/common/jinja/parser.cpp b/common/jinja/parser.cpp index 7e99a1ac8fd0..0841828c454a 100644 --- a/common/jinja/parser.cpp +++ b/common/jinja/parser.cpp @@ -178,7 +178,7 @@ class parser { // bool has_caller_args = false; if (is(token::open_paren)) { // Optional caller arguments, e.g. {% call(user) dump_users(...) %} - caller_args = parse_args(); + caller_args = parse_args(false); // has_caller_args = true; } auto callee = parse_primary_expression(); @@ -283,7 +283,7 @@ class parser { statement_ptr parse_macro_statement(size_t start_pos) { auto name = parse_primary_expression(); - auto args = parse_args(); + auto args = parse_args(false); expect(token::close_statement, "Expected %}"); statements body; // Keep going until we hit {% endmacro @@ -397,11 +397,13 @@ class parser { statement_ptr parse_comparison_expression() { // NOTE: membership has same precedence as comparison - // e.g., ('a' in 'apple' == 'b' in 'banana') evaluates as ('a' in ('apple' == ('b' in 'banana'))) - auto left = parse_additive_expression(); + // e.g., ('a' in 'apple' == 'b' in 'banana') evaluates as ('a' in 'apple' and 'apple' == 'b' and 'b' in 'banana') + statements operands; + std::vector ops; + operands.push_back(parse_additive_expression()); + size_t pos = current; while (true) { token op; - size_t start_pos = current; if (is_identifier("not") && peek(1).t == token::identifier && peek(1).value == "in") { op = {token::identifier, "not in", tokens[current].pos}; ++current; // consume 'not' @@ -411,9 +413,17 @@ class parser { } else if (is(token::comparison_binary_operator)) { op = next(); } else break; - left = mk_stmt(start_pos, op, std::move(left), parse_additive_expression()); + ops.push_back(std::move(op)); + operands.push_back(parse_additive_expression()); } - return left; + if (ops.empty()) { + return std::move(operands[0]); + } + if (ops.size() == 1) { + return mk_stmt(pos, ops[0], std::move(operands[0]), std::move(operands[1])); + } + // chained comparison, e.g. 1 <= x <= 100 + return mk_stmt(pos, std::move(operands), std::move(ops)); } statement_ptr parse_additive_expression() { @@ -500,17 +510,22 @@ class parser { return parse_call_expression(std::move(member)); // foo.x()() } - statements parse_args() { + statements parse_args(bool allow_spread = true) { // comma-separated arguments list expect(token::open_paren, "Expected ("); statements args; while (!is(token::close_paren)) { statement_ptr arg; - // unpacking: *expr - if (peek().t == token::multiplicative_binary_operator && peek().value == "*") { + // unpacking: *expr or **expr + const auto & t = peek(); + if (t.t == token::power_operator || (t.t == token::multiplicative_binary_operator && t.value == "*")) { + if (!allow_spread) { + throw std::runtime_error("Unexpected token: " + t.value + " of type " + std::to_string(t.t)); + } size_t start_pos = current; - ++current; // consume * - arg = mk_stmt(start_pos, parse_expression()); + ++current; // consume * or ** + bool is_kwargs = t.t == token::power_operator; + arg = mk_stmt(start_pos, parse_expression(), is_kwargs); } else { arg = parse_expression(); if (is(token::equals)) { diff --git a/common/jinja/runtime.cpp b/common/jinja/runtime.cpp index d32c79fa5cb5..d60a99d2591e 100644 --- a/common/jinja/runtime.cpp +++ b/common/jinja/runtime.cpp @@ -117,20 +117,8 @@ value object_literal::execute_impl(context & ctx) const { return obj; } -value binary_expression::execute_impl(context & ctx) const { - value left_val = left->execute(ctx); - - // Logical operators - if (op.value == "and") { - JJ_DEBUG("Executing logical test: %s AND %s", left->type().c_str(), right->type().c_str()); - return left_val->as_bool() ? right->execute(ctx) : std::move(left_val); - } else if (op.value == "or") { - JJ_DEBUG("Executing logical test: %s OR %s", left->type().c_str(), right->type().c_str()); - return left_val->as_bool() ? std::move(left_val) : right->execute(ctx); - } - +static value exec_binary_op(context & ctx, const token & op, value left_val, value right_val) { // Equality operators - value right_val = right->execute(ctx); JJ_DEBUG("Executing binary expression %s '%s' %s", left_val->type().c_str(), op.value.c_str(), right_val->type().c_str()); if (op.value == "==") { return mk_val(*left_val == *right_val); @@ -307,6 +295,67 @@ value binary_expression::execute_impl(context & ctx) const { throw std::runtime_error("Unknown operator \"" + op.value + "\" between " + left_val->type() + " and " + right_val->type()); } +value binary_expression::execute_impl(context & ctx) const { + value left_val = left->execute(ctx); + + // Logical operators + if (op.value == "and") { + JJ_DEBUG("Executing logical test: %s AND %s", left->type().c_str(), right->type().c_str()); + return left_val->as_bool() ? right->execute(ctx) : std::move(left_val); + } else if (op.value == "or") { + JJ_DEBUG("Executing logical test: %s OR %s", left->type().c_str(), right->type().c_str()); + return left_val->as_bool() ? std::move(left_val) : right->execute(ctx); + } + + return exec_binary_op(ctx, op, std::move(left_val), right->execute(ctx)); +} + +value comparison_chain_expression::execute_impl(context & ctx) const { + value left_val = operands[0]->execute(ctx); + value res; + for (size_t i = 0; i < ops.size(); ++i) { + value right_val = operands[i + 1]->execute(ctx); + res = exec_binary_op(ctx, ops[i], left_val, right_val); + if (!res->as_bool()) { + break; // same as "and", the next operands are not executed + } + left_val = std::move(right_val); + } + return res; +} + +static void exec_call_args(context & ctx, const statements & arg_stmts, func_args & args) { + for (const auto & arg_stmt : arg_stmts) { + if (!is_stmt(arg_stmt)) { + auto arg_val = arg_stmt->execute(ctx); + JJ_DEBUG(" Argument type: %s", arg_val->type().c_str()); + args.push_back(arg_val); + continue; + } + auto spread = cast_stmt(arg_stmt); + value val = spread->argument->execute(ctx); + JJ_DEBUG(" Unpacked argument type: %s", val->type().c_str()); + if (spread->is_kwargs) { + if (!is_val(val)) { + throw std::runtime_error("Argument after ** must be an object, got " + val->type()); + } + for (const auto & pair : val->as_ordered_object()) { + if (!is_val(pair.first)) { + throw std::runtime_error("Keyword argument key must be a string, got " + pair.first->type()); + } + args.push_back(mk_val(pair.first->as_string().str(), pair.second)); + } + } else { + if (!is_val(val)) { + throw std::runtime_error("Argument after * must be an array, got " + val->type()); + } + for (const auto & item : val->as_array()) { + args.push_back(item); + } + } + } +} + static value apply_filter(context & ctx, const statement_ptr & filter, value input) { JJ_DEBUG("Applying filter to %s", input->type().c_str()); @@ -324,9 +373,7 @@ static value apply_filter(context & ctx, const statement_ptr & filter, value inp JJ_DEBUG("Applying filter '%s' with arguments to %s", filter_id.c_str(), input->type().c_str()); func_args args(ctx); - for (const auto & arg_expr : call->args) { - args.push_back(arg_expr->execute(ctx)); - } + exec_call_args(ctx, call->args, args); return apply_filter_by_name(ctx, filter_id, input, args); @@ -369,9 +416,7 @@ value test_expression::execute_impl(context & ctx) const { test_id = cast_stmt(call->callee)->val; JJ_DEBUG("Applying test '%s' with arguments to %s", test_id.c_str(), input->type().c_str()); - for (const auto & arg_expr : call->args) { - args.push_back(arg_expr->execute(ctx)); - } + exec_call_args(ctx, call->args, args); } else { throw std::runtime_error("Invalid test expression"); @@ -762,12 +807,7 @@ value call_statement::execute_impl(context & ctx) const { call_ctx.set_val("caller", mk_val("caller", func)); func_args args(call_ctx); - - for (const auto & arg_expr : call_expr->args) { - auto arg_val = arg_expr->execute(ctx); - JJ_DEBUG(" Argument type: %s", arg_val->type().c_str()); - args.push_back(arg_val); - } + exec_call_args(ctx, call_expr->args, args); JJ_DEBUG("Calling macro '%s' with %zu arguments", callee_func->name.c_str(), args.count()); return callee_func->invoke(args); @@ -907,11 +947,7 @@ value member_expression::execute_impl(context & ctx) const { value call_expression::execute_impl(context & ctx) const { // gather arguments func_args args(ctx); - for (auto & arg_stmt : this->args) { - auto arg_val = arg_stmt->execute(ctx); - JJ_DEBUG(" Argument type: %s", arg_val->type().c_str()); - args.push_back(arg_val); - } + exec_call_args(ctx, this->args, args); // execute callee value callee_val = callee->execute(ctx); if (!is_val(callee_val)) { diff --git a/common/jinja/runtime.h b/common/jinja/runtime.h index 101e927c4b7f..43e1085516da 100644 --- a/common/jinja/runtime.h +++ b/common/jinja/runtime.h @@ -471,6 +471,28 @@ struct binary_expression : public expression { } }; +/** + * Two or more comparisons in a row, e.g. `a < b <= c` + * It is the same as `a < b and b <= c`, but each operand is executed only one time. + */ +struct comparison_chain_expression : public expression { + statements operands; + std::vector ops; + + comparison_chain_expression(statements && operands, std::vector && ops) + : operands(std::move(operands)), ops(std::move(ops)) { + assert(this->operands.size() == this->ops.size() + 1); + for (const auto & operand : this->operands) chk_type(operand); + } + std::string type() const override { return "ComparisonChainExpression"; } + value execute_impl(context & ctx) const override; + void visit(context & ctx) const override { + ctx.visitor(false, this, { + {"operands", stmts_to_ptr(operands)} + }); + } +}; + /** * An operation with two sides, separated by the | operator. * Operator precedence: https://github.com/pallets/jinja/issues/379#issuecomment-168076202 @@ -633,7 +655,9 @@ struct keyword_argument_expression : public expression { struct spread_expression : public expression { statement_ptr argument; - explicit spread_expression(statement_ptr && argument) : argument(std::move(argument)) { + bool is_kwargs; + spread_expression(statement_ptr && argument, bool is_kwargs) + : argument(std::move(argument)), is_kwargs(is_kwargs) { chk_type(this->argument); } std::string type() const override { return "SpreadExpression"; } diff --git a/common/json-schema.h b/common/json-schema.h index 084208c96201..b203e7777aa8 100644 --- a/common/json-schema.h +++ b/common/json-schema.h @@ -85,92 +85,124 @@ struct common_chat_schema { static const char * kind_name(node_kind kind); static const char * type_name(value_type type); + + template + const T & as() const { + GGML_ASSERT(kind() == T::KIND); + return static_cast(*this); + } }; using common_chat_schema_ptr = std::unique_ptr; struct common_chat_schema_any : common_chat_schema { - node_kind kind() const override { return KIND_ANY; } + static constexpr node_kind KIND = KIND_ANY; + + node_kind kind() const override { return KIND; } }; // {"$ref": "#/..."}, only references into the same document are supported struct common_chat_schema_ref : common_chat_schema { + static constexpr node_kind KIND = KIND_REF; + std::string ref; const common_chat_schema * target = nullptr; // owned by common_chat_schema_document::refs explicit common_chat_schema_ref(std::string ref) : ref(std::move(ref)) {} - node_kind kind() const override { return KIND_REF; } + node_kind kind() const override { return KIND; } }; // oneOf / anyOf, or a "type" array expanded to one alternative per type struct common_chat_schema_any_of : common_chat_schema { + static constexpr node_kind KIND = KIND_ANY_OF; + std::vector children; - node_kind kind() const override { return KIND_ANY_OF; } + node_kind kind() const override { return KIND; } }; struct common_chat_schema_all_of : common_chat_schema { + static constexpr node_kind KIND = KIND_ALL_OF; + std::vector children; - node_kind kind() const override { return KIND_ALL_OF; } + node_kind kind() const override { return KIND; } }; struct common_chat_schema_const : common_chat_schema { + static constexpr node_kind KIND = KIND_CONST; + common_json value; explicit common_chat_schema_const(common_json value) : value(std::move(value)) {} - node_kind kind() const override { return KIND_CONST; } + node_kind kind() const override { return KIND; } }; struct common_chat_schema_enum : common_chat_schema { + static constexpr node_kind KIND = KIND_ENUM; + std::vector values; - node_kind kind() const override { return KIND_ENUM; } + node_kind kind() const override { return KIND; } }; struct common_chat_schema_null : common_chat_schema { - node_kind kind() const override { return KIND_NULL; } + static constexpr node_kind KIND = KIND_NULL; + + node_kind kind() const override { return KIND; } }; struct common_chat_schema_boolean : common_chat_schema { - node_kind kind() const override { return KIND_BOOLEAN; } + static constexpr node_kind KIND = KIND_BOOLEAN; + + node_kind kind() const override { return KIND; } }; struct common_chat_schema_number : common_chat_schema { - node_kind kind() const override { return KIND_NUMBER; } + static constexpr node_kind KIND = KIND_NUMBER; + + node_kind kind() const override { return KIND; } }; // bounds are inclusive, exclusiveMinimum / exclusiveMaximum are folded in struct common_chat_schema_integer : common_chat_schema { + static constexpr node_kind KIND = KIND_INTEGER; + int64_t minimum = INT64_MIN; // INT64_MIN for unbounded int64_t maximum = INT64_MAX; // INT64_MAX for unbounded - node_kind kind() const override { return KIND_INTEGER; } + node_kind kind() const override { return KIND; } }; struct common_chat_schema_string : common_chat_schema { + static constexpr node_kind KIND = KIND_STRING; + std::string pattern; // empty when absent string_format format = FORMAT_NONE; int min_length = 0; int max_length = -1; // -1 for unbounded - node_kind kind() const override { return KIND_STRING; } + node_kind kind() const override { return KIND; } }; struct common_chat_schema_array : common_chat_schema { + static constexpr node_kind KIND = KIND_ARRAY; + common_chat_schema_ptr items; // a common_chat_schema_any when "items" is absent int min_items = 0; int max_items = -1; // -1 for unbounded - node_kind kind() const override { return KIND_ARRAY; } + node_kind kind() const override { return KIND; } }; struct common_chat_schema_tuple : common_chat_schema { + static constexpr node_kind KIND = KIND_TUPLE; + std::vector items; - node_kind kind() const override { return KIND_TUPLE; } + node_kind kind() const override { return KIND; } }; struct common_chat_schema_property { @@ -180,10 +212,12 @@ struct common_chat_schema_property { }; struct common_chat_schema_object : common_chat_schema { + static constexpr node_kind KIND = KIND_OBJECT; + std::vector properties; // in schema order common_chat_schema_ptr additional_properties; // null when not allowed - node_kind kind() const override { return KIND_OBJECT; } + node_kind kind() const override { return KIND; } }; struct common_chat_schema_document { diff --git a/common/parsers/gemma4.cpp b/common/parsers/gemma4.cpp index 1a63fa927c40..5902e290bbc6 100644 --- a/common/parsers/gemma4.cpp +++ b/common/parsers/gemma4.cpp @@ -1,152 +1,284 @@ #include "parsers.h" -namespace workaround { - -// Gemma4 uses a custom tool_responses field instead of role:tool messages. -// -// This will transform a sequence of messages: -// assistant(tool_call+) -> tool+ -> assistant(content) -// -// Into a single assistant message containing a tool_responses field: -// assistant(content + tool_call + tool_responses) -// -// This is necessary for the Gemma4 chat template to properly format the prompt. -// See https://ai.google.dev/gemma/docs/core/prompt-formatting-gemma4 -struct gemma4_model_turn_builder { - json & messages; - size_t pos; - json tool_calls = json::array(); - json tool_responses = json::array(); - json content; - json reasoning_content; - - gemma4_model_turn_builder(json & msgs, size_t pos) : messages(msgs), pos(pos) {} - - void collect() { - // Collect the first assistant message - auto & msg = messages[pos]; - if (msg.contains("reasoning_content") && msg.at("reasoning_content").is_string()) { - // According to the prompt formatting guide, we need to preserve reasoning_content - // between function calls. The current chat templates do not support this, but we will do it anyway. - reasoning_content = msg.at("reasoning_content"); - } - for (auto & tc : msg.at("tool_calls")) { - tool_calls.push_back(tc); - } - pos++; +#include "log.h" + +#include +#include +#include +#include + +namespace { + +using gemma4 = common_chat_peg_gemma4_mapper; - // Collect tool call results - while (pos < messages.size() && messages[pos].value("role", "") == "tool") { - collect_result(messages[pos]); - pos++; +struct depth_guard { + int & depth; + depth_guard(int & depth) : depth(depth) { + if (++depth > COMMON_RECURSIVE_LIMIT) { + throw std::invalid_argument("JSON schema is nested more than " + std::to_string(COMMON_RECURSIVE_LIMIT) + " levels deep"); } + } + ~depth_guard() { depth--; } +}; - // Check if the next assistant message is the final message - if (pos < messages.size() && messages[pos].value("role", "") == "assistant") { - auto & next = messages[pos]; - if (!has_tool_calls(next) && has_content(next)) { - content = next.at("content"); - pos++; - } +// Gemma 4 value parsers +void gemma4_value_rules(common_chat_peg_builder & p) { + // The tags are what gemma4_to_json() in the mapper reads, the rules may wrap them freely. + p.rule("gemma4-string", p.tag(gemma4::STRING, p.literal("<|\"|>") + p.tag(gemma4::STRING_CONTENT, p.until("<|\"|>")) + p.literal("<|\"|>"))); + + p.rule("gemma4-bool", p.tag(gemma4::BOOL, p.json_bool())); + + p.rule("gemma4-null", p.tag(gemma4::NULL_, p.json_null())); + + p.rule("gemma4-number", p.tag(gemma4::NUMBER, p.json_number())); + + // Keys are bare in the template, but Gemma 4 occasionally wraps them in quotes + p.rule("gemma4-dict-key", p.tag(gemma4::DICT_KEY, p.choice({ + p.literal("<|\"|>") + p.tag(gemma4::DICT_KEY_NAME, p.until("<|\"|>")) + p.literal("<|\"|>"), + p.literal("\"") + p.tag(gemma4::DICT_KEY_NAME, p.chars("[^\"]", 1, -1)) + p.literal("\""), + p.literal("'") + p.tag(gemma4::DICT_KEY_NAME, p.chars("[^']", 1, -1)) + p.literal("'"), + p.tag(gemma4::DICT_KEY_NAME, p.chars("[^:}]", 1, -1)), + }) + p.literal(":"))); + + p.rule("gemma4-dict-kv", p.tag(gemma4::DICT_KV, p.ref("gemma4-dict-key") + p.space() + p.ref("gemma4-value"))); + + p.rule("gemma4-dict", [&]() { + auto ws = p.space(); + auto member = p.ref("gemma4-dict-kv"); + auto members = p.sequence({member, p.zero_or_more(p.sequence({p.literal(","), ws, member}))}); + return p.tag(gemma4::DICT, p.sequence({ + p.literal("{"), ws, + p.choice({p.literal("}"), p.sequence({members, ws, p.literal("}")})}) + })); + }); + + p.rule("gemma4-array", [&]() { + auto ws = p.space(); + auto value = p.ref("gemma4-value"); + auto elements = p.sequence({value, p.zero_or_more(p.sequence({p.literal(","), ws, value}))}); + return p.tag(gemma4::ARRAY, p.sequence({ + p.literal("["), ws, + p.choice({p.literal("]"), p.sequence({elements, ws, p.literal("]")})}) + })); + }); + + p.rule("gemma4-value", [&]() { + return p.choice({ + p.ref("gemma4-string"), p.ref("gemma4-dict"), p.ref("gemma4-array"), + p.ref("gemma4-number"), p.ref("gemma4-bool"), p.ref("gemma4-null") + }); + }); +} + +// Gemma 4 uses different delimiters and cannot leverage the json-schema-to-grammar implementation. +// This implements a subset to enforce properties. +class gemma4_schema_parser { + common_chat_peg_builder & p_; + std::string root_; + int depth_ = 0; + + std::map refs_; + + public: + gemma4_schema_parser(common_chat_peg_builder & p, std::string root) : p_(p), root_(std::move(root)) {} + + common_peg_parser visit(const common_chat_schema & node) { return visit(node, root_); } + + private: + common_peg_parser visit(const common_chat_schema & node, const std::string & name) { + depth_guard guard(depth_); + switch (node.kind()) { + case common_chat_schema::KIND_REF: return visit_ref(node.as()); + case common_chat_schema::KIND_ANY_OF: return visit_any_of(node.as(), name); + case common_chat_schema::KIND_ALL_OF: return visit_all_of(node.as(), name); + case common_chat_schema::KIND_ARRAY: return visit_array(node.as(), name); + case common_chat_schema::KIND_TUPLE: return visit_tuple(node.as(), name); + case common_chat_schema::KIND_OBJECT: return visit_object(node.as(), name); + default: return p_.ref("gemma4-value"); } } - void collect_result(const json & curr) { - json response; - if (curr.contains("content")) { - const auto & content = curr.at("content"); - if (content.is_string()) { - // Try to parse the content as JSON; fall back to raw string - try { - response = json::parse(content.get()); - } catch (...) { - response = content; + // Whether a schema contributes a shape of its own, as opposed to accepting any value. + static bool shaped(const common_chat_schema & node) { + switch (node.kind()) { + case common_chat_schema::KIND_REF: + return node.as().target != nullptr; + case common_chat_schema::KIND_ANY_OF: + for (const auto & child : node.as().children) { + if (shaped(*child)) { + return true; + } } - } else { - response = content; + return false; + case common_chat_schema::KIND_ALL_OF: { + const auto & children = node.as().children; + return children.size() == 1 && shaped(*children[0]); } + case common_chat_schema::KIND_ARRAY: + case common_chat_schema::KIND_TUPLE: + case common_chat_schema::KIND_OBJECT: + return true; + default: + return false; } + } - std::string name; + // The template writes keys bare. Models keep that for identifiers and quote anything else, + // with single or double quotes or the string delimiter, so those are accepted as well. + common_peg_parser key(const std::string & key) { + auto name = [&]() { return p_.tag(gemma4::DICT_KEY_NAME, p_.literal(key)); }; - // Match name with corresponding tool call - size_t idx = tool_responses.size(); - if (idx < tool_calls.size()) { - auto & tc = tool_calls[idx]; - if (tc.contains("function")) { - name = tc.at("function").value("name", ""); + bool identifier = !key.empty() && !std::isdigit(static_cast(key[0])); + for (char c : key) { + if (!std::isalnum(static_cast(c)) && c != '_') { + identifier = false; } } - - // Fallback to the tool call id - if (name.empty()) { - name = curr.value("tool_call_id", ""); + if (identifier) { + return p_.tag(gemma4::DICT_KEY, name() + p_.literal(":")); } - tool_responses.push_back({{"name", name}, {"response", response}}); + auto alts = p_.choice(); + if (!key.empty() && key.find_first_of(":}") == std::string::npos && std::string("'\"<").find(key[0]) == std::string::npos) { + // Check if key is unambiguous + alts |= name(); + } + // Gemma 4 may emit keys in its string delimiters or quotes + alts |= p_.literal("<|\"|>") + name() + p_.literal("<|\"|>"); + if (key.find('\'') == std::string::npos) { + alts |= p_.literal("'") + name() + p_.literal("'"); + } + if (key.find('"') == std::string::npos) { + alts |= p_.literal("\"") + name() + p_.literal("\""); + } + return p_.tag(gemma4::DICT_KEY, alts + p_.literal(":")); } - json build() { - collect(); - - json msg = { - {"role", "assistant"}, - {"tool_calls", tool_calls}, - }; - if (!tool_responses.empty()) { - msg["tool_responses"] = tool_responses; + common_peg_parser visit_ref(const common_chat_schema_ref & ref) { + if (!ref.target) { + return p_.ref("gemma4-value"); } - if (!content.is_null()) { - msg["content"] = content; + auto it = refs_.find(ref.target); + if (it != refs_.end()) { + return p_.ref(it->second); } - if (!reasoning_content.is_null()) { - msg["reasoning_content"] = reasoning_content; - } - return msg; + // A target reached from several places gets one rule, named by the order it was first seen. + auto rule = root_ + "-ref-" + std::to_string(refs_.size()); + refs_[ref.target] = rule; + return p_.rule(rule, [&]() { return visit(*ref.target, rule + "-value"); }); } - static bool has_content(const json & msg) { - if (!msg.contains("content") || msg.at("content").is_null()) { - return false; + // Shaped alternatives are tried first, then anything else collapses into one generic value. + common_peg_parser visit_any_of(const common_chat_schema_any_of & node, const std::string & name) { + if (!shaped(node)) { + return p_.ref("gemma4-value"); + } + if (node.children.size() == 1) { + return visit(*node.children[0], name); } - const auto & content = msg.at("content"); - if (content.is_string() && !content.get().empty()) { - return true; + auto alts = p_.choice(); + bool loose = false; + for (size_t i = 0; i < node.children.size(); i++) { + if (shaped(*node.children[i])) { + alts |= visit(*node.children[i], name + "-" + std::to_string(i)); + } else { + loose = true; + } } - if (content.is_array() && !content.empty()) { - return true; + if (loose) { + alts |= p_.ref("gemma4-value"); } - return false; + return p_.rule(name, alts); } - static bool has_tool_calls(const json & msg) { - return msg.contains("tool_calls") && msg.at("tool_calls").is_array() && !msg.at("tool_calls").empty(); + common_peg_parser visit_all_of(const common_chat_schema_all_of & node, const std::string & name) { + if (node.children.size() == 1) { + return visit(*node.children[0], name); + } + return p_.ref("gemma4-value"); } -}; -void convert_tool_responses_gemma4(json & messages) { - json result = json::array(); - size_t i = 0; + common_peg_parser visit_array(const common_chat_schema_array & node, const std::string & name) { + auto ws = p_.space(); + auto item = node.items && shaped(*node.items) ? visit(*node.items, name + "-item") : p_.ref("gemma4-value"); + auto elements = item + p_.zero_or_more(p_.literal(",") + ws + item); + return p_.rule(name, p_.tag(gemma4::ARRAY, + p_.literal("[") + ws + (p_.literal("]") | (elements + ws + p_.literal("]"))))); + } - while (i < messages.size()) { - auto & msg = messages[i]; + common_peg_parser visit_tuple(const common_chat_schema_tuple & node, const std::string & name) { + auto ws = p_.space(); + auto items = p_.sequence(); + for (size_t i = 0; i < node.items.size(); i++) { + if (i > 0) { + items = items + p_.literal(",") + ws; + } + items = items + visit(*node.items[i], name + "-" + std::to_string(i)); + } + return p_.rule(name, p_.tag(gemma4::ARRAY, p_.literal("[") + ws + items + ws + p_.literal("]"))); + } + + common_peg_parser visit_object(const common_chat_schema_object & node, const std::string & name) { + auto ws = p_.space(); - if (msg.value("role", "") != "assistant" || !msg.contains("tool_calls") || - !msg.at("tool_calls").is_array() || msg.at("tool_calls").empty()) { - result.push_back(msg); - i++; - continue; + std::vector props; + for (const auto & prop : node.properties) { + props.push_back(&prop); } - gemma4_model_turn_builder builder(messages, i); - result.push_back(builder.build()); - i = builder.pos; - } + // The Gemma 4 jinja template sorts properties, so our rules need to match. + auto lower = [](const std::string & s) { + std::string out = s; + for (auto & c : out) { + c = static_cast(std::tolower(static_cast(c))); + } + return out; + }; + std::stable_sort(props.begin(), props.end(), [&](const auto * a, const auto * b) { + return lower(a->name) < lower(b->name); + }); - messages = result; -} + if (props.empty()) { + if (node.additional_properties) { + return p_.ref("gemma4-dict"); + } + return p_.rule(name, p_.tag(gemma4::DICT, p_.literal("{") + ws + p_.literal("}"))); + } -} + std::optional rest; + std::optional first; + if (node.additional_properties) { + auto kv = p_.ref("gemma4-dict-kv"); + rest = p_.zero_or_more(p_.literal(",") + ws + kv); + first = p_.optional(kv + *rest); + } + + auto then_rest = [&](const common_peg_parser & parser) { + return rest ? parser + *rest : parser; + }; + + for (size_t i = props.size(); i-- > 0;) { + const auto & prop = *props[i]; + auto kv = p_.tag(gemma4::DICT_KV, key(prop.name) + ws + visit(*prop.schema, name + "-" + std::to_string(i))); + + common_peg_parser rest_i = then_rest(p_.literal(",") + ws + kv); + common_peg_parser first_i = then_rest(kv); + if (!prop.required) { + rest_i = then_rest(p_.optional(p_.literal(",") + ws + kv)); + first_i = first ? (first_i | *first) : p_.optional(first_i); + } + + if (i > 0) { + rest = p_.rule(name + "-rest-" + std::to_string(i), rest_i); + } + first = first_i; + } + + return p_.rule(name, p_.tag(gemma4::DICT, p_.literal("{") + ws + *first + ws + p_.literal("}"))); + } +}; + +} // namespace common_chat_params common_chat_params_init_gemma4(const common_chat_template & tmpl, const autoparser::generation_params & inputs) { @@ -218,51 +350,29 @@ common_chat_params common_chat_params_init_gemma4(const common_chat_template & } if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) { - // Gemma4 tool calling syntax - // Rules should match traversal logic in gemma4_to_json() - p.rule("gemma4-string-content", p.until("<|\"|>")); - p.rule("gemma4-string", p.literal("<|\"|>") + p.ref("gemma4-string-content") + p.literal("<|\"|>")); - p.rule("gemma4-bool", p.json_bool()); - p.rule("gemma4-null", p.json_null()); - p.rule("gemma4-number", p.json_number()); - p.rule("gemma4-dict-key", p.rule("gemma4-dict-key-name", p.chars("[^:}]", 1, -1)) + p.literal(":")); - p.rule("gemma4-dict-kv", p.ref("gemma4-dict-key") + p.space() + p.ref("gemma4-value")); - p.rule("gemma4-dict", [&]() { - auto ws = p.space(); - auto member = p.ref("gemma4-dict-kv"); - auto members = p.sequence({member, p.zero_or_more(p.sequence({p.literal(","), ws, member}))}); - return p.sequence({ - p.literal("{"), ws, - p.choice({p.literal("}"), p.sequence({members, ws, p.literal("}")})}) - }); - }); - p.rule("gemma4-array", [&]() { - auto ws = p.space(); - auto value = p.ref("gemma4-value"); - auto elements = p.sequence({value, p.zero_or_more(p.sequence({p.literal(","), ws, value}))}); - return p.sequence({ - p.literal("["), ws, - p.choice({p.literal("]"), p.sequence({elements, ws, p.literal("]")})}) - }); - }); - p.rule("gemma4-value", [&]() { - return p.choice({ - p.ref("gemma4-string"), p.ref("gemma4-dict"), p.ref("gemma4-array"), - p.ref("gemma4-number"), p.ref("gemma4-bool"), p.ref("gemma4-null") - }); - }); + gemma4_value_rules(p); auto tool_choice = p.choice(); foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) { const auto & function = tool.at("function"); std::string name = function.at("name"); - // TODO @aldehir : need to extend json-schema-to-grammar to produce more than JSON rules - // const auto & params = function.at("parameters"); + + // Arguments follow the shape of the parameter schema when it is an object, + // see gemma4_schema_parser, and are a generic dict otherwise. + auto args = p.ref("gemma4-dict"); + try { + auto doc = common_chat_schema_from_json(common_chat_tool_parameters(function)); + if (doc.root->kind() == common_chat_schema::KIND_OBJECT) { + args = gemma4_schema_parser(p, "tool-" + std::to_string(tool_index) + "-args").visit(*doc.root); + } + } catch (const std::exception & e) { + LOG_WRN("%s: tool %s uses the generic argument parser: %s\n", __func__, name.c_str(), e.what()); + } tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(p.sequence({ p.tool_open(p.tool_name(p.literal(name)) + p.peek(p.literal("{"))), - p.tool_args(p.ref("gemma4-dict")), + p.tool_args(args), }))); }); diff --git a/common/parsers/parsers.h b/common/parsers/parsers.h index 532a44f014fe..b1b6d166a124 100644 --- a/common/parsers/parsers.h +++ b/common/parsers/parsers.h @@ -41,12 +41,6 @@ std::string common_chat_template_generation_prompt_impl( bool is_lfm2_template(const std::string & src); -namespace workaround { - -void convert_tool_responses_gemma4(json & messages); - -} - common_chat_params common_chat_params_init_cohere2moe(const common_chat_template & tmpl, const autoparser::generation_params & inputs); common_chat_params common_chat_params_init_deepseek_v3_2(const common_chat_template & tmpl, const autoparser::generation_params & inputs); diff --git a/common/speculative.cpp b/common/speculative.cpp index 8a189a9b1b9f..aa37d8bb8228 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -10,8 +10,6 @@ #include "ngram-mod.h" #include "sampling.h" -#include "../src/llama-ext.h" // staging API: llama_set_embeddings_nextn / llama_get_embeddings_nextn_ith (used by MTP) - #include #include #include @@ -1681,9 +1679,9 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { // shared memory and chained heads keep the host rows if (!is_mem_shared && !chain_heads) { - dev_rows = llama_set_embeddings_nextn_dev(ctx_tgt, true) && llama_set_embd_state_src(ctx_dft, ctx_tgt); + dev_rows = llama_set_embeddings_nextn_dev(ctx_tgt, true) && llama_set_ctx_state_src(ctx_dft, ctx_tgt); if (!dev_rows) { - llama_set_embd_state_src(ctx_dft, nullptr); + llama_set_ctx_state_src(ctx_dft, nullptr); llama_set_embeddings_nextn_dev(ctx_tgt, false); } } @@ -1693,7 +1691,7 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { ~common_speculative_impl_draft_mtp() override { auto * ctx_dft = this->params.ctx_dft; if (dev_rows) { - llama_set_embd_state_src(ctx_dft, nullptr); + llama_set_ctx_state_src(ctx_dft, nullptr); llama_set_embeddings_nextn_dev(this->params.ctx_tgt, false); } for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) backend_chains.size(); ++seq_id) { diff --git a/conversion/qwen.py b/conversion/qwen.py index 83c844ce64af..376535460a2c 100644 --- a/conversion/qwen.py +++ b/conversion/qwen.py @@ -493,6 +493,45 @@ class _LinearAttentionVReorderBase(Qwen3NextModel): interleaved repeat: [G0_v0, G1_v0, ..., G0_v1, G1_v1, ...]. """ + _SHARED_INPUT_MERGES: tuple[tuple[gguf.MODEL_TENSOR, tuple[gguf.MODEL_TENSOR, gguf.MODEL_TENSOR], bool], ...] = () + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._merge_parts: dict[tuple[int, gguf.MODEL_TENSOR], dict[int, Tensor]] = {} + + # caches one half of a merged weight until the other half arrives, then yields [a | b] + def _merge_shared_input(self, new_name: str, data: Tensor, bid: int | None) -> Iterable[tuple[str, Tensor]]: + # a pre-quantized checkpoint carries per-tensor scales, which one merged weight cannot hold + if not self._SHARED_INPUT_MERGES or bid is None or self.hparams.get("quantization_config") or self._fp8_e4m3_preserved or self.hadamard_folded_names() or hasattr(data, "get_lora_A_B"): + yield (new_name, data) + return + + layer_types = self.hparams.get("layer_types") + if layer_types is None: + is_linear = bid < self.hparams["num_hidden_layers"] and (bid + 1) % self.hparams.get("full_attention_interval", 4) != 0 + else: + is_linear = bid < len(layer_types) and layer_types[bid] == "linear_attention" + + match = next(((merged, parts.index(part)) for merged, parts, linear_only in self._SHARED_INPUT_MERGES + if merged in gguf.MODEL_TENSORS[self.model_arch] + for part in parts + if (is_linear or not linear_only) and self.match_model_tensor_name(new_name, part, bid)), None) + if match is None: + yield (new_name, data) + return + + merged, idx = match + halves = self._merge_parts.setdefault((bid, merged), {}) + halves[idx] = data + if len(halves) == 2: + del self._merge_parts[(bid, merged)] + yield (self.format_tensor_name(merged, bid), torch.cat([halves[0], halves[1]], dim=0)) + + def prepare_tensors(self): + super().prepare_tensors() + if self._merge_parts: + raise ValueError(f"merged weights missing a half: {sorted((bid, t.name) for bid, t in self._merge_parts)}") + @staticmethod def _reorder_v_heads(tensor: Tensor, dim: int, num_k_heads: int, num_v_per_k: int, head_dim: int) -> Tensor: """Reorder V heads from grouped (by K head) to tiled order along the given dimension.""" @@ -672,7 +711,8 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter # Out projection weight: reorder columns (input dimension) data_torch = self._reorder_v_heads(data_torch, 1, num_k_heads, num_v_per_k, head_v_dim) - yield from super().modify_tensors(data_torch, name, bid) + for new_name, data in super().modify_tensors(data_torch, name, bid): + yield from self._merge_shared_input(new_name, data, bid) class _Qwen35MRopeMixin: @@ -696,6 +736,11 @@ def set_gguf_parameters(self): class Qwen3_5TextModel(_Qwen35MRopeMixin, _LinearAttentionVReorderBase): model_arch = gguf.MODEL_ARCH.QWEN35 + _SHARED_INPUT_MERGES = ( + (gguf.MODEL_TENSOR.ATTN_QKV_GATE, (gguf.MODEL_TENSOR.ATTN_QKV, gguf.MODEL_TENSOR.ATTN_GATE), True), + (gguf.MODEL_TENSOR.SSM_BETA_ALPHA_CAT, (gguf.MODEL_TENSOR.SSM_BETA, gguf.MODEL_TENSOR.SSM_ALPHA), True), + ) + def __init__(self, dir_model, *args, **kwargs): # Inner TextModel does not own mtp.*. Set no_mtp before mixin bumps block_count. hparams = kwargs.pop("hparams", None) diff --git a/conversion/qwen4exp.py b/conversion/qwen4exp.py index 8a55d678d74a..9680d2937dfb 100644 --- a/conversion/qwen4exp.py +++ b/conversion/qwen4exp.py @@ -41,8 +41,6 @@ def __init__(self, *args, **kwargs): self._ple_shards: dict[int, str] = {} self._ple_row_dim: int | None = None self._mtp_fc: dict[str, Tensor] = {} - # halves of the merged weights, keyed by (bid, merged tensor), see _merge_shared_input - self._merge_parts: dict[tuple[int, gguf.MODEL_TENSOR], dict[int, Tensor]] = {} @classmethod def filter_tensors(cls, item): @@ -171,8 +169,7 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter yield (self.map_tensor_name(name), data_torch.squeeze()) return - for new_name, data in super().modify_tensors(data_torch, name, bid): - yield from self._merge_shared_input(new_name, data, bid) + yield from super().modify_tensors(data_torch, name, bid) # matmuls that read the same input, written as one weight [a | b] so the runtime does one matmul: # (merged tensor, (a, b), linear-attention layers only) @@ -183,30 +180,6 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter (gguf.MODEL_TENSOR.SSM_BETA_ALPHA_CAT, (gguf.MODEL_TENSOR.SSM_BETA, gguf.MODEL_TENSOR.SSM_ALPHA), True), ) - # caches one half of a merged weight until the other half arrives, then yields [a | b] - def _merge_shared_input(self, new_name: str, data: Tensor, bid: int | None) -> Iterable[tuple[str, Tensor]]: - # a pre-quantized checkpoint carries per-tensor scales, which one merged weight cannot hold - if bid is None or self.hparams.get("quantization_config"): - yield (new_name, data) - return - - layer_types = self.hparams.get("layer_types") or [] - is_linear = bid < len(layer_types) and layer_types[bid] == "linear_attention" - - match = next(((merged, parts.index(part)) for merged, parts, linear_only in self._SHARED_INPUT_MERGES - for part in parts - if (is_linear or not linear_only) and self.match_model_tensor_name(new_name, part, bid)), None) - if match is None: - yield (new_name, data) - return - - merged, idx = match - halves = self._merge_parts.setdefault((bid, merged), {}) - halves[idx] = data - if len(halves) == 2: - del self._merge_parts[(bid, merged)] - yield (self.format_tensor_name(merged, bid), torch.cat([halves[0], halves[1]], dim=0)) - # the shards concatenate into a tensor of well over 100 GB # use LazyChunkedTensor here, a single shard resident at a time def _place_ple_shard(self, data_torch: Tensor, name: str) -> Iterable[tuple[str, Tensor]]: @@ -251,8 +224,6 @@ def prepare_tensors(self): super().prepare_tensors() if self._mtp_fc: raise ValueError(f"MTP projection missing its other half: {sorted(self._mtp_fc)}") - if self._merge_parts: - raise ValueError(f"merged weights missing a half: {sorted((bid, t.name) for bid, t in self._merge_parts)}") n_parts = self.hparams.get("split_ngram_parts", 0) if self._ple_shards and len(self._ple_shards) != n_parts: raise ValueError( diff --git a/docs/backend/snapdragon/developer.md b/docs/backend/snapdragon/developer.md index 95b6127a497f..69a8d5f7d318 100644 --- a/docs/backend/snapdragon/developer.md +++ b/docs/backend/snapdragon/developer.md @@ -60,7 +60,7 @@ Implementation: [`htp-repack.cpp`](../../../ggml/src/ggml-hexagon/htp-repack.cpp ### Tile Dimensions and Grid Layout Each tile represents a submatrix of `N_rows = 32` rows and `K_cols` columns: -- Standard types (`Q4_0`, `Q4_1`, `Q8_0`, `IQ4_NL`, `MXFP4`, and K-quants): `K_cols = 32` (`HTP_TENSOR_TILE_N_COLS = 32`). +- Standard types (`Q4_0`, `Q4_1`, `Q5_0`, `Q5_1`, `Q8_0`, `IQ4_NL`, `MXFP4`, and K-quants): `K_cols = 32` (`HTP_TENSOR_TILE_N_COLS = 32`). - `Q2_0`: `K_cols = 64` (`HTP_TENSOR_TILE_K_Q2_0 = 64`). - `Q1_0`: `K_cols = 128` (`HTP_TENSOR_TILE_K_Q1_0 = 128`). @@ -123,6 +123,17 @@ Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`): - **Scales** (bytes 512..639, 128 bytes): 32 pairs of FP16 values (`ggml_half`): `scale[2 * row + 0] = d` (scale) and `scale[2 * row + 1] = m` (min) for each row `row = 0..31`. +- **Q5_0** (704 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q5_0`): + - **Quants** (bytes 0..511): same 4-bit nibble transposition and storage layout as `Q4_0`, holding the low 4 bits. + - **5th-bit plane** (bytes 512..639): byte `32*c + row` (`c = 0..3`) holds a flag for `k = 2*(4i + c)` at bit `2i` and for `k = 2*(4i + c) + 1` at bit `2i + 1`, for `i = 0..3`. The flag is set when the 5th bit of the quant is clear. + - **Scales** (bytes 640..703, 64 bytes): 32 FP16 values, storing scale `d` for each row `row = 0..31`. + - **Dequantization**: `0xF0` is OR-ed into the nibble where the flag is set, giving the signed value `q - 16` (-16..15), scaled by `d`. + +- **Q5_1** (768 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q5_1`, same layout as the Q5_K tile): + - **Quants** (bytes 0..511) and **scales** (bytes 512..639): same as `Q4_1`, holding the low 4 bits and `(d, m)` pairs. + - **5th-bit plane** (bytes 640..767): same as `Q5_K`; a bit is set when the 5th bit of the quant is set. + - Uses the `Q5_K` HVX/HMX kernels (Q8_1 activations with block sums). + ### Q1_0 Format (1-Bit Quantization) `Q1_0` packs 128 columns per tile (`K_cols = 128`, `HTP_TENSOR_TILE_K_Q1_0 = 128`): diff --git a/docs/build.md b/docs/build.md index 4e3bfe651b39..e369aad01f49 100644 --- a/docs/build.md +++ b/docs/build.md @@ -608,7 +608,7 @@ You can test with: If the following info is output on screen, you are using `llama.cpp` with the CANN backend: ```bash llm_load_tensors: CANN model buffer size = 13313.00 MiB -llama_new_context_with_model: CANN compute buffer size = 1260.81 MiB +llama_init_from_model: CANN compute buffer size = 1260.81 MiB ``` For detailed info, such as model/device supports, CANN install, please refer to [llama.cpp for CANN](./backend/CANN.md). diff --git a/docs/ops.md b/docs/ops.md index c8204465b703..3c2bcd239bb1 100644 --- a/docs/ops.md +++ b/docs/ops.md @@ -40,7 +40,6 @@ Legend: | CROSS_ENTROPY_LOSS_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | | CUMSUM | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | | DIAG | ❌ | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | -| DIAG_MASK_INF | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | 🟡 | ✅ | ✅ | ❌ | ❌ | ❌ | | DIV | ❌ | ✅ | ✅ | ✅ | ❌ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | DSV4_HC_COMB | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | | DSV4_HC_POST | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | diff --git a/docs/ops/BLAS.csv b/docs/ops/BLAS.csv index 3af72452aadb..eabdd6f8118b 100644 --- a/docs/ops/BLAS.csv +++ b/docs/ops/BLAS.csv @@ -8741,9 +8741,6 @@ "BLAS","ROUND","type=f32,ne=[1024,1024,1,1]","support","0","no","BLAS" "BLAS","TRUNC","type=f32,ne=[7,1,5,3]","support","0","no","BLAS" "BLAS","TRUNC","type=f32,ne=[1024,1024,1,1]","support","0","no","BLAS" -"BLAS","DIAG_MASK_INF","type=f32,ne=[10,10,1,1],n_past=5","support","0","no","BLAS" -"BLAS","DIAG_MASK_INF","type=f32,ne=[10,10,3,1],n_past=5","support","0","no","BLAS" -"BLAS","DIAG_MASK_INF","type=f32,ne=[10,10,3,2],n_past=5","support","0","no","BLAS" "BLAS","SOFT_MAX","type=f32,ne=[16,16,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","0","no","BLAS" "BLAS","SOFT_MAX","type=f32,ne=[15,15,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","0","no","BLAS" "BLAS","SOFT_MAX","type=f32,ne=[16,1024,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","0","no","BLAS" diff --git a/docs/ops/CANN.csv b/docs/ops/CANN.csv index 8434461a5f7e..de317ad1588b 100644 --- a/docs/ops/CANN.csv +++ b/docs/ops/CANN.csv @@ -8764,9 +8764,6 @@ "CANN0","ROUND","type=f32,ne=[1024,1024,1,1]","support","0","no","CANN" "CANN0","TRUNC","type=f32,ne=[7,1,5,3]","support","0","no","CANN" "CANN0","TRUNC","type=f32,ne=[1024,1024,1,1]","support","0","no","CANN" -"CANN0","DIAG_MASK_INF","type=f32,ne=[10,10,1,1],n_past=5","support","1","yes","CANN" -"CANN0","DIAG_MASK_INF","type=f32,ne=[10,10,3,1],n_past=5","support","1","yes","CANN" -"CANN0","DIAG_MASK_INF","type=f32,ne=[10,10,3,2],n_past=5","support","1","yes","CANN" "CANN0","SOFT_MAX","type=f32,ne=[16,16,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","CANN" "CANN0","SOFT_MAX","type=f32,ne=[15,15,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","CANN" "CANN0","SOFT_MAX","type=f32,ne=[16,1024,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","CANN" diff --git a/docs/ops/CPU.csv b/docs/ops/CPU.csv index 5d491fc4bf5d..49803f22700a 100644 --- a/docs/ops/CPU.csv +++ b/docs/ops/CPU.csv @@ -12962,9 +12962,6 @@ "CPU","ROUND","type=f32,ne=[1024,1024,1,1]","support","1","yes","CPU" "CPU","TRUNC","type=f32,ne=[7,1,5,3]","support","1","yes","CPU" "CPU","TRUNC","type=f32,ne=[1024,1024,1,1]","support","1","yes","CPU" -"CPU","DIAG_MASK_INF","type=f32,ne=[10,10,1,1],n_past=5","support","1","yes","CPU" -"CPU","DIAG_MASK_INF","type=f32,ne=[10,10,3,1],n_past=5","support","1","yes","CPU" -"CPU","DIAG_MASK_INF","type=f32,ne=[10,10,3,2],n_past=5","support","1","yes","CPU" "CPU","SOFT_MAX","type=f32,ne=[16,16,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","CPU" "CPU","SOFT_MAX","type=f32,ne=[15,15,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","CPU" "CPU","SOFT_MAX","type=f32,ne=[16,1024,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","CPU" diff --git a/docs/ops/CUDA.csv b/docs/ops/CUDA.csv index 7499a492767b..2b8c8b7a8ef8 100644 --- a/docs/ops/CUDA.csv +++ b/docs/ops/CUDA.csv @@ -8725,9 +8725,6 @@ "CUDA0","ROUND","type=f32,ne=[1024,1024,1,1]","support","1","yes","CUDA" "CUDA0","TRUNC","type=f32,ne=[7,1,5,3]","support","1","yes","CUDA" "CUDA0","TRUNC","type=f32,ne=[1024,1024,1,1]","support","1","yes","CUDA" -"CUDA0","DIAG_MASK_INF","type=f32,ne=[10,10,1,1],n_past=5","support","1","yes","CUDA" -"CUDA0","DIAG_MASK_INF","type=f32,ne=[10,10,3,1],n_past=5","support","1","yes","CUDA" -"CUDA0","DIAG_MASK_INF","type=f32,ne=[10,10,3,2],n_past=5","support","1","yes","CUDA" "CUDA0","SOFT_MAX","type=f32,ne=[16,16,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","CUDA" "CUDA0","SOFT_MAX","type=f32,ne=[15,15,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","CUDA" "CUDA0","SOFT_MAX","type=f32,ne=[16,1024,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","CUDA" diff --git a/docs/ops/ET.csv b/docs/ops/ET.csv index 91774c58e84b..56a8f970596a 100644 --- a/docs/ops/ET.csv +++ b/docs/ops/ET.csv @@ -9637,9 +9637,6 @@ "ET","ROUND","type=f32,ne=[1024,1024,1,1]","support","1","yes","ET" "ET","TRUNC","type=f32,ne=[7,1,5,3]","support","0","no","ET" "ET","TRUNC","type=f32,ne=[1024,1024,1,1]","support","1","yes","ET" -"ET","DIAG_MASK_INF","type=f32,ne=[10,10,1,1],n_past=5","support","0","no","ET" -"ET","DIAG_MASK_INF","type=f32,ne=[10,10,3,1],n_past=5","support","0","no","ET" -"ET","DIAG_MASK_INF","type=f32,ne=[10,10,3,2],n_past=5","support","0","no","ET" "ET","SOFT_MAX","type=f32,ne=[16,16,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","ET" "ET","SOFT_MAX","type=f32,ne=[15,15,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","ET" "ET","SOFT_MAX","type=f32,ne=[16,1024,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","ET" diff --git a/docs/ops/Hexagon.csv b/docs/ops/Hexagon.csv index c9608b715dd7..160c414992d6 100644 --- a/docs/ops/Hexagon.csv +++ b/docs/ops/Hexagon.csv @@ -14564,9 +14564,6 @@ "HTP0","ROUND","type=f32,ne=[1024,1024,1,1]","support","0","no","HTP" "HTP0","TRUNC","type=f32,ne=[7,1,5,3]","support","0","no","HTP" "HTP0","TRUNC","type=f32,ne=[1024,1024,1,1]","support","0","no","HTP" -"HTP0","DIAG_MASK_INF","type=f32,ne=[10,10,1,1],n_past=5","support","0","no","HTP" -"HTP0","DIAG_MASK_INF","type=f32,ne=[10,10,3,1],n_past=5","support","0","no","HTP" -"HTP0","DIAG_MASK_INF","type=f32,ne=[10,10,3,2],n_past=5","support","0","no","HTP" "HTP0","SOFT_MAX","type=f32,ne=[16,16,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","HTP" "HTP0","SOFT_MAX","type=f32,ne=[15,15,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","HTP" "HTP0","SOFT_MAX","type=f32,ne=[16,1024,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","HTP" diff --git a/docs/ops/Metal.csv b/docs/ops/Metal.csv index ec34bb66b899..8d38300a0ced 100644 --- a/docs/ops/Metal.csv +++ b/docs/ops/Metal.csv @@ -9628,9 +9628,6 @@ "MTL0","ROUND","type=f32,ne=[1024,1024,1,1]","support","1","yes","MTL" "MTL0","TRUNC","type=f32,ne=[7,1,5,3]","support","1","yes","MTL" "MTL0","TRUNC","type=f32,ne=[1024,1024,1,1]","support","1","yes","MTL" -"MTL0","DIAG_MASK_INF","type=f32,ne=[10,10,1,1],n_past=5","support","0","no","MTL" -"MTL0","DIAG_MASK_INF","type=f32,ne=[10,10,3,1],n_past=5","support","0","no","MTL" -"MTL0","DIAG_MASK_INF","type=f32,ne=[10,10,3,2],n_past=5","support","0","no","MTL" "MTL0","SOFT_MAX","type=f32,ne=[16,16,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","MTL" "MTL0","SOFT_MAX","type=f32,ne=[15,15,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","MTL" "MTL0","SOFT_MAX","type=f32,ne=[16,1024,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","MTL" diff --git a/docs/ops/OpenCL.csv b/docs/ops/OpenCL.csv index 4a6e90456883..8b595e4b9d89 100644 --- a/docs/ops/OpenCL.csv +++ b/docs/ops/OpenCL.csv @@ -14887,9 +14887,6 @@ "OpenCL","ROUND","type=f32,ne=[1024,1024,1,1]","support","1","yes","OpenCL" "OpenCL","TRUNC","type=f32,ne=[7,1,5,3]","support","1","yes","OpenCL" "OpenCL","TRUNC","type=f32,ne=[1024,1024,1,1]","support","1","yes","OpenCL" -"OpenCL","DIAG_MASK_INF","type=f32,ne=[10,10,1,1],n_past=5","support","1","yes","OpenCL" -"OpenCL","DIAG_MASK_INF","type=f32,ne=[10,10,3,1],n_past=5","support","1","yes","OpenCL" -"OpenCL","DIAG_MASK_INF","type=f32,ne=[10,10,3,2],n_past=5","support","0","no","OpenCL" "OpenCL","SOFT_MAX","type=f32,ne=[16,16,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","OpenCL" "OpenCL","SOFT_MAX","type=f32,ne=[15,15,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","OpenCL" "OpenCL","SOFT_MAX","type=f32,ne=[16,1024,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","OpenCL" diff --git a/docs/ops/SYCL.csv b/docs/ops/SYCL.csv index 3ef1ca1d7718..e01a536a7284 100644 --- a/docs/ops/SYCL.csv +++ b/docs/ops/SYCL.csv @@ -14534,9 +14534,6 @@ "SYCL0","ROUND","type=f32,ne=[1024,1024,1,1]","support","1","yes","SYCL" "SYCL0","TRUNC","type=f32,ne=[7,1,5,3]","support","1","yes","SYCL" "SYCL0","TRUNC","type=f32,ne=[1024,1024,1,1]","support","1","yes","SYCL" -"SYCL0","DIAG_MASK_INF","type=f32,ne=[10,10,1,1],n_past=5","support","1","yes","SYCL" -"SYCL0","DIAG_MASK_INF","type=f32,ne=[10,10,3,1],n_past=5","support","1","yes","SYCL" -"SYCL0","DIAG_MASK_INF","type=f32,ne=[10,10,3,2],n_past=5","support","1","yes","SYCL" "SYCL0","SOFT_MAX","type=f32,ne=[16,16,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","SYCL" "SYCL0","SOFT_MAX","type=f32,ne=[15,15,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","SYCL" "SYCL0","SOFT_MAX","type=f32,ne=[16,1024,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","SYCL" diff --git a/docs/ops/Vulkan.csv b/docs/ops/Vulkan.csv index 13e67eb797ff..65ac8bf33984 100644 --- a/docs/ops/Vulkan.csv +++ b/docs/ops/Vulkan.csv @@ -12313,9 +12313,6 @@ "Vulkan0","ROUND","type=f32,ne=[1024,1024,1,1]","support","1","yes","Vulkan" "Vulkan0","TRUNC","type=f32,ne=[7,1,5,3]","support","1","yes","Vulkan" "Vulkan0","TRUNC","type=f32,ne=[1024,1024,1,1]","support","1","yes","Vulkan" -"Vulkan0","DIAG_MASK_INF","type=f32,ne=[10,10,1,1],n_past=5","support","1","yes","Vulkan" -"Vulkan0","DIAG_MASK_INF","type=f32,ne=[10,10,3,1],n_past=5","support","1","yes","Vulkan" -"Vulkan0","DIAG_MASK_INF","type=f32,ne=[10,10,3,2],n_past=5","support","1","yes","Vulkan" "Vulkan0","SOFT_MAX","type=f32,ne=[16,16,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","Vulkan" "Vulkan0","SOFT_MAX","type=f32,ne=[15,15,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","Vulkan" "Vulkan0","SOFT_MAX","type=f32,ne=[16,1024,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","Vulkan" diff --git a/docs/ops/WebGPU.csv b/docs/ops/WebGPU.csv index 1da1a0f0469a..3b874fd68e59 100644 --- a/docs/ops/WebGPU.csv +++ b/docs/ops/WebGPU.csv @@ -10560,9 +10560,6 @@ "WebGPU: WebGPU","ROUND","type=f32,ne=[1024,1024,1,1]","support","1","yes","WebGPU" "WebGPU: WebGPU","TRUNC","type=f32,ne=[7,1,5,3]","support","1","yes","WebGPU" "WebGPU: WebGPU","TRUNC","type=f32,ne=[1024,1024,1,1]","support","1","yes","WebGPU" -"WebGPU: WebGPU","DIAG_MASK_INF","type=f32,ne=[10,10,1,1],n_past=5","support","0","no","WebGPU" -"WebGPU: WebGPU","DIAG_MASK_INF","type=f32,ne=[10,10,3,1],n_past=5","support","0","no","WebGPU" -"WebGPU: WebGPU","DIAG_MASK_INF","type=f32,ne=[10,10,3,2],n_past=5","support","0","no","WebGPU" "WebGPU: WebGPU","SOFT_MAX","type=f32,ne=[16,16,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","WebGPU" "WebGPU: WebGPU","SOFT_MAX","type=f32,ne=[15,15,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","WebGPU" "WebGPU: WebGPU","SOFT_MAX","type=f32,ne=[16,1024,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","1","yes","WebGPU" diff --git a/docs/ops/ZenDNN.csv b/docs/ops/ZenDNN.csv index 19d579fb8c50..b309f1a0d880 100644 --- a/docs/ops/ZenDNN.csv +++ b/docs/ops/ZenDNN.csv @@ -9319,9 +9319,6 @@ "ZenDNN","ROUND","type=f32,ne=[1024,1024,1,1]","support","0","no","ZenDNN" "ZenDNN","TRUNC","type=f32,ne=[7,1,5,3]","support","0","no","ZenDNN" "ZenDNN","TRUNC","type=f32,ne=[1024,1024,1,1]","support","0","no","ZenDNN" -"ZenDNN","DIAG_MASK_INF","type=f32,ne=[10,10,1,1],n_past=5","support","0","no","ZenDNN" -"ZenDNN","DIAG_MASK_INF","type=f32,ne=[10,10,3,1],n_past=5","support","0","no","ZenDNN" -"ZenDNN","DIAG_MASK_INF","type=f32,ne=[10,10,3,2],n_past=5","support","0","no","ZenDNN" "ZenDNN","SOFT_MAX","type=f32,ne=[16,16,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","0","no","ZenDNN" "ZenDNN","SOFT_MAX","type=f32,ne=[15,15,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","0","no","ZenDNN" "ZenDNN","SOFT_MAX","type=f32,ne=[16,1024,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","0","no","ZenDNN" diff --git a/docs/ops/zDNN.csv b/docs/ops/zDNN.csv index 005a1cb4de99..a44ef3ebba83 100644 --- a/docs/ops/zDNN.csv +++ b/docs/ops/zDNN.csv @@ -14550,9 +14550,6 @@ "zDNN","ROUND","type=f32,ne=[1024,1024,1,1]","support","0","no","zDNN" "zDNN","TRUNC","type=f32,ne=[7,1,5,3]","support","0","no","zDNN" "zDNN","TRUNC","type=f32,ne=[1024,1024,1,1]","support","0","no","zDNN" -"zDNN","DIAG_MASK_INF","type=f32,ne=[10,10,1,1],n_past=5","support","0","no","zDNN" -"zDNN","DIAG_MASK_INF","type=f32,ne=[10,10,3,1],n_past=5","support","0","no","zDNN" -"zDNN","DIAG_MASK_INF","type=f32,ne=[10,10,3,2],n_past=5","support","0","no","zDNN" "zDNN","SOFT_MAX","type=f32,ne=[16,16,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","0","no","zDNN" "zDNN","SOFT_MAX","type=f32,ne=[15,15,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","0","no","zDNN" "zDNN","SOFT_MAX","type=f32,ne=[16,1024,1,1],mask=0,sinks=0,m_prec=f32,nr23=[1,1],scale=1.000000,max_bias=0.000000,inplace=0","support","0","no","zDNN" diff --git a/docs/tts-norm-patterns.md b/docs/tts-norm-patterns.md new file mode 100644 index 000000000000..802dde5ce7e0 --- /dev/null +++ b/docs/tts-norm-patterns.md @@ -0,0 +1,125 @@ +# TTS normalization patterns + +Text-to-speech models often need their input normalized before tokenization: numbers, currencies, dates and symbols spelled out, punctuation mapped, spacing fixed. The exact rules are model-specific (they must match what the model was trained on), so they live in the model's `tts` task template rather than in C++. + +Jinja has no regex support, and exposing `std::regex` / Python `re` would not help: the two differ in many details (`\d`, `\w`, `\b`, lookbehind, case folding, backtracking limits), so a template could give different results in llama.cpp and in Python. Instead, task templates get two functions with a small matching language whose semantics are defined here: + +- `tts_norm_scan(text, rules)`: split text into matched and unmatched segments +- `tts_norm_sub(text, pattern, repl)`: replace every match + +Implementations: +- C++: [common/chat-tts-norm.cpp](../common/chat-tts-norm.cpp), injected into task templates by `common_chat_template_render()` in [common/chat.cpp](../common/chat.cpp). They are not available to chat templates. +- Python reference: [scripts/chat_tts_norm.py](../scripts/chat_tts_norm.py), for use with `jinja2` (`env.globals["tts_norm_scan"] = chat_tts_norm.tts_norm_scan`) +- Both are checked against each other by `tests/test-jinja.cpp` (`test-jinja -py "tts norm patterns.*"`) + +## Example + +```jinja +{%- for s in tts_norm_scan(text, [ + ['money', '%$(%d+)(?:%.(%d%d))?'], + ['percent', '(%d+)%%'], + ['time', '(%d%d?):(%d%d)(?!%d)'], + ['neg', '(?src[0] == a); -// assert(c->src[1] == b); -// } -// -// The multi-dimensional tensors are stored in row-major order. The ggml_tensor struct contains fields for the -// number of elements in each dimension ("ne") as well as the number of bytes ("nb", a.k.a. stride). This allows -// to store tensors that are not contiguous in memory, which is useful for operations such as transposition and -// permutation. All tensor operations have to take the stride into account and not assume that the tensor is -// contiguous in memory. -// -// The data of the tensor is accessed via the "data" pointer. For example: -// -// { -// const int nx = 2; -// const int ny = 3; -// -// struct ggml_tensor * a = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, nx, ny); -// -// for (int y = 0; y < ny; y++) { -// for (int x = 0; x < nx; x++) { -// *(float *) ((char *) a->data + y*a->nb[1] + x*a->nb[0]) = x + y; -// } -// } -// -// ... -// } -// -// Alternatively, there are helper functions, such as ggml_get_f32_1d() and ggml_set_f32_1d() that can be used. -// -// ## The matrix multiplication operator (ggml_mul_mat) -// -// TODO -// -// -// ## Multi-threading -// -// TODO -// -// -// ## Overview of ggml.c -// -// TODO -// -// -// ## SIMD optimizations -// -// TODO -// -// -// ## Debugging ggml -// -// TODO -// -// - #ifdef GGML_SHARED # if defined(_WIN32) && !defined(__MINGW32__) # ifdef GGML_BUILD @@ -445,7 +272,6 @@ extern "C" { // the precision parameters are stored as ggml_tensor.op_params to the respective ops enum ggml_prec { GGML_PREC_UNDEFINED = 0, - GGML_PREC_DEFAULT = 0, // note: deprecated, use GGML_PREC_UNDEFINED GGML_PREC_F32 = 10, GGML_PREC_BF16 = 15, GGML_PREC_F16 = 20, @@ -499,7 +325,6 @@ extern "C" { GGML_OP_DUP, GGML_OP_ADD, GGML_OP_ADD_ID, - GGML_OP_ADD1, GGML_OP_ACC, GGML_OP_SUB, GGML_OP_MUL, @@ -541,8 +366,6 @@ extern "C" { GGML_OP_GET_ROWS_BACK, GGML_OP_SET_ROWS, GGML_OP_DIAG, - GGML_OP_DIAG_MASK_INF, - GGML_OP_DIAG_MASK_ZERO, GGML_OP_SOFT_MAX, GGML_OP_SOFT_MAX_BACK, GGML_OP_ROPE, @@ -765,10 +588,6 @@ extern "C" { GGML_API size_t ggml_type_size(enum ggml_type type); // size in bytes for all elements in a block GGML_API size_t ggml_row_size (enum ggml_type type, int64_t ne); // size in bytes for all elements in a row - GGML_DEPRECATED( - GGML_API double ggml_type_sizef(enum ggml_type type), // ggml_type_size()/ggml_blck_size() as float - "use ggml_row_size() instead"); - GGML_API const char * ggml_type_name(enum ggml_type type); GGML_API const char * ggml_op_name (enum ggml_op op); GGML_API const char * ggml_op_symbol(enum ggml_op op); @@ -937,18 +756,6 @@ extern "C" { struct ggml_tensor * b, struct ggml_tensor * ids); - GGML_DEPRECATED(GGML_API struct ggml_tensor * ggml_add1( - struct ggml_context * ctx, - struct ggml_tensor * a, - struct ggml_tensor * b), - "use ggml_add instead"); - - GGML_DEPRECATED(GGML_API struct ggml_tensor * ggml_add1_inplace( - struct ggml_context * ctx, - struct ggml_tensor * a, - struct ggml_tensor * b), - "use ggml_add_inplace instead"); - // dst = a // view(dst, nb1, nb2, nb3, offset) += b // return dst @@ -1500,13 +1307,6 @@ extern "C" { struct ggml_tensor * a, struct ggml_tensor * b); - // change the precision of a matrix multiplication - // set to GGML_PREC_F32 for higher precision (useful for phi-2) - GGML_DEPRECATED(GGML_API void ggml_mul_mat_set_prec( - struct ggml_tensor * a, - enum ggml_prec prec), - "use ggml_prec_set_acc() instead"); - // change the hint of a matrix multiplication GGML_API void ggml_mul_mat_set_hint( struct ggml_tensor * a, @@ -1778,30 +1578,6 @@ extern "C" { struct ggml_context * ctx, struct ggml_tensor * a); - // set elements above the diagonal to -INF - GGML_API struct ggml_tensor * ggml_diag_mask_inf( - struct ggml_context * ctx, - struct ggml_tensor * a, - int n_past); - - // in-place, returns view(a) - GGML_API struct ggml_tensor * ggml_diag_mask_inf_inplace( - struct ggml_context * ctx, - struct ggml_tensor * a, - int n_past); - - // set elements above the diagonal to 0 - GGML_API struct ggml_tensor * ggml_diag_mask_zero( - struct ggml_context * ctx, - struct ggml_tensor * a, - int n_past); - - // in-place, returns view(a) - GGML_API struct ggml_tensor * ggml_diag_mask_zero_inplace( - struct ggml_context * ctx, - struct ggml_tensor * a, - int n_past); - GGML_API struct ggml_tensor * ggml_clamp( struct ggml_context * ctx, struct ggml_tensor * a, @@ -2005,36 +1781,6 @@ extern "C" { float beta_fast, float beta_slow); - GGML_DEPRECATED(GGML_API struct ggml_tensor * ggml_rope_custom( - struct ggml_context * ctx, - struct ggml_tensor * a, - struct ggml_tensor * b, - int n_dims, - int mode, - int n_ctx_orig, - float freq_base, - float freq_scale, - float ext_factor, - float attn_factor, - float beta_fast, - float beta_slow), - "use ggml_rope_ext instead"); - - GGML_DEPRECATED(GGML_API struct ggml_tensor * ggml_rope_custom_inplace( - struct ggml_context * ctx, - struct ggml_tensor * a, - struct ggml_tensor * b, - int n_dims, - int mode, - int n_ctx_orig, - float freq_base, - float freq_scale, - float ext_factor, - float attn_factor, - float beta_fast, - float beta_slow), - "use ggml_rope_ext_inplace instead"); - // rotary position embedding backward, i.e compute dx from dy // a - dy GGML_API struct ggml_tensor * ggml_rope_ext_back( @@ -2340,7 +2086,7 @@ extern "C" { GGML_SCALE_MODE_BILINEAR = 1, GGML_SCALE_MODE_BICUBIC = 2, - GGML_SCALE_MODE_COUNT + GGML_SCALE_MODE_COUNT = 3 }; enum ggml_scale_flag { @@ -2356,18 +2102,6 @@ extern "C" { int scale_factor, enum ggml_scale_mode mode); - // interpolate - // interpolate scale to specified dimensions - GGML_DEPRECATED(GGML_API struct ggml_tensor * ggml_upscale_ext( - struct ggml_context * ctx, - struct ggml_tensor * a, - int ne0, - int ne1, - int ne2, - int ne3, - enum ggml_scale_mode mode), - "use ggml_interpolate instead"); - // Up- or downsamples the input to the specified size. // 2D scale modes (eg. bilinear) are applied to the first two dimensions. GGML_API struct ggml_tensor * ggml_interpolate( @@ -2536,11 +2270,6 @@ extern "C" { float max_bias, float logit_softcap); - GGML_DEPRECATED(GGML_API void ggml_flash_attn_ext_set_prec( - struct ggml_tensor * a, - enum ggml_prec prec), - "use ggml_prec_set_acc() instead"); - GGML_API enum ggml_prec ggml_flash_attn_ext_get_prec( const struct ggml_tensor * a); diff --git a/ggml/src/ggml-alloc.c b/ggml/src/ggml-alloc.c index b0c067b49135..65d2bea27726 100644 --- a/ggml/src/ggml-alloc.c +++ b/ggml/src/ggml-alloc.c @@ -23,11 +23,8 @@ bool ggml_op_can_inplace(enum ggml_op op) { switch (op) { case GGML_OP_FILL: case GGML_OP_SCALE: - case GGML_OP_DIAG_MASK_ZERO: - case GGML_OP_DIAG_MASK_INF: case GGML_OP_ADD: case GGML_OP_ADD_ID: - case GGML_OP_ADD1: case GGML_OP_SUB: case GGML_OP_MUL: case GGML_OP_DIV: diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp index 991398316aac..595a5824aafe 100644 --- a/ggml/src/ggml-backend-meta.cpp +++ b/ggml/src/ggml-backend-meta.cpp @@ -939,7 +939,6 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state( case GGML_OP_ADD_ID: { split_state = handle_bin_bcast(src_ss); } break; - case GGML_OP_ADD1: case GGML_OP_ACC: { split_state = handle_generic(src_ss, /*scalar_only =*/ true); } break; @@ -1020,9 +1019,7 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state( case GGML_OP_SET_ROWS: { split_state = handle_set_rows(src_ss); } break; - case GGML_OP_DIAG: - case GGML_OP_DIAG_MASK_INF: - case GGML_OP_DIAG_MASK_ZERO: { + case GGML_OP_DIAG: { split_state = handle_generic(src_ss, /*scalar_only =*/ true); } break; case GGML_OP_SOFT_MAX: diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp index 961990f85979..b70d0d8741e9 100644 --- a/ggml/src/ggml-backend.cpp +++ b/ggml/src/ggml-backend.cpp @@ -2172,8 +2172,13 @@ static void ggml_backend_sched_prefetch_inputs(ggml_backend_sched_t sched, int s continue; } - // not if this split computes or writes the input + // only results of earlier splits, the copy callback of this split runs later and can write other tensors (e.g. the MoE cache) const struct ggml_tensor * base = input->view_src ? input->view_src : input; + if (base->buffer == NULL || ggml_backend_buffer_get_usage(base->buffer) != GGML_BACKEND_BUFFER_USAGE_COMPUTE) { + continue; + } + + // not if this split computes or writes the input bool written = false; for (int j = 0; j < split->graph.n_nodes && !written; j++) { const struct ggml_tensor * node = split->graph.nodes[j]; diff --git a/ggml/src/ggml-cann/aclnn_ops.cpp b/ggml/src/ggml-cann/aclnn_ops.cpp index 66e011ef098d..e602e4bf3b11 100644 --- a/ggml/src/ggml-cann/aclnn_ops.cpp +++ b/ggml/src/ggml-cann/aclnn_ops.cpp @@ -1347,31 +1347,6 @@ void ggml_cann_rms_norm(ggml_backend_cann_context & ctx, ggml_tensor * dst) { GGML_CANN_CALL_ACLNN_OP(ctx, RmsNorm, acl_src.get(), acl_gamma.get(), eps, acl_dst.get(), acl_rstd.get()); } -// TODO: performace is low. -void ggml_cann_diag_mask(ggml_backend_cann_context & ctx, ggml_tensor * dst, float value) { - ggml_tensor * src = dst->src[0]; - - acl_tensor_ptr acl_src = ggml_cann_create_tensor(src); - acl_tensor_ptr acl_dst = ggml_cann_create_tensor(dst); - - const int n_past = ((int32_t *) dst->op_params)[0]; - - ggml_cann_pool_alloc one_tensor_allocator(ctx.pool(), ggml_nbytes(src)); - void * buffer = one_tensor_allocator.get(); - - acl_tensor_ptr mask_tensor = ggml_cann_create_tensor(buffer, ggml_cann_type_mapping(src->type), - ggml_type_size(src->type), src->ne, src->nb, GGML_MAX_DIMS); - - aclnn_fill_scalar(ctx, value, mask_tensor.get()); - - float alphaValue = 1.0f; - acl_scalar_ptr alpha = ggml_cann_create_scalar(&alphaValue, aclDataType::ACL_FLOAT); - - GGML_CANN_CALL_ACLNN_OP(ctx, InplaceTriu, mask_tensor.get(), n_past + 1); - GGML_CANN_CALL_ACLNN_OP(ctx, Tril, acl_src.get(), n_past + 1, acl_dst.get()); - GGML_CANN_CALL_ACLNN_OP(ctx, InplaceAdd, acl_dst.get(), mask_tensor.get(), alpha.get()); -} - /** * @brief Permutes the dimensions of a tensor according to a specified order. * diff --git a/ggml/src/ggml-cann/aclnn_ops.h b/ggml/src/ggml-cann/aclnn_ops.h index 678f4d654e7f..f470042cf7af 100644 --- a/ggml/src/ggml-cann/aclnn_ops.h +++ b/ggml/src/ggml-cann/aclnn_ops.h @@ -466,21 +466,6 @@ void ggml_cann_dup(ggml_backend_cann_context & ctx, ggml_tensor * dst); */ void ggml_cann_rms_norm(ggml_backend_cann_context & ctx, ggml_tensor * dst); -/** - * @brief Applies a diagonal mask to the tensor with a specified value. - * - * @details This function creates a mask tensor filled with ones, then applies - * an upper triangular and lower triangular operation to it based on - * the number of past elements specified. Afterward, it adds the masked - * tensor to the destination tensor in-place. - * - * @param ctx The backend CANN context used for operations. - * @param dst The destination tensor where the result will be stored. dst->op is - * `GGML_OP_DIAG_MASK` - * @param value The value to use for masking. - */ -void ggml_cann_diag_mask(ggml_backend_cann_context & ctx, ggml_tensor * dst, float value); - /** * @brief Performs an image-to-column transformation on the input tensor. * diff --git a/ggml/src/ggml-cann/ggml-cann.cpp b/ggml/src/ggml-cann/ggml-cann.cpp index b49aee73d52a..0bfb960095c5 100644 --- a/ggml/src/ggml-cann/ggml-cann.cpp +++ b/ggml/src/ggml-cann/ggml-cann.cpp @@ -1793,7 +1793,6 @@ static bool ggml_cann_compute_forward(ggml_backend_cann_context & ctx, struct gg ggml_cann_dup(ctx, dst); break; case GGML_OP_ADD: - case GGML_OP_ADD1: ggml_cann_binary_op(ctx, dst); break; case GGML_OP_SUB: @@ -1958,9 +1957,6 @@ static bool ggml_cann_compute_forward(ggml_backend_cann_context & ctx, struct gg case GGML_OP_PERMUTE: case GGML_OP_TRANSPOSE: break; - case GGML_OP_DIAG_MASK_INF: - ggml_cann_diag_mask(ctx, dst, -INFINITY); - break; case GGML_OP_SOFT_MAX: ggml_cann_softmax(ctx, dst); break; @@ -2618,7 +2614,6 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten case GGML_OP_TRANSPOSE: case GGML_OP_NORM: case GGML_OP_ADD: - case GGML_OP_ADD1: case GGML_OP_SUB: case GGML_OP_MUL: case GGML_OP_DIV: @@ -2626,7 +2621,6 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten case GGML_OP_SQR: case GGML_OP_SQRT: case GGML_OP_CLAMP: - case GGML_OP_DIAG_MASK_INF: case GGML_OP_SUM_ROWS: case GGML_OP_ARGSORT: case GGML_OP_ACC: diff --git a/ggml/src/ggml-cpu/ggml-cpu.c b/ggml/src/ggml-cpu/ggml-cpu.c index 40e93ccabc84..a76af8487e11 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.c +++ b/ggml/src/ggml-cpu/ggml-cpu.c @@ -1782,10 +1782,6 @@ static void ggml_compute_forward(struct ggml_compute_params * params, struct ggm { ggml_compute_forward_add_id(params, tensor); } break; - case GGML_OP_ADD1: - { - ggml_compute_forward_add1(params, tensor); - } break; case GGML_OP_ACC: { ggml_compute_forward_acc(params, tensor); @@ -1926,14 +1922,6 @@ static void ggml_compute_forward(struct ggml_compute_params * params, struct ggm { ggml_compute_forward_diag(params, tensor); } break; - case GGML_OP_DIAG_MASK_INF: - { - ggml_compute_forward_diag_mask_inf(params, tensor); - } break; - case GGML_OP_DIAG_MASK_ZERO: - { - ggml_compute_forward_diag_mask_zero(params, tensor); - } break; case GGML_OP_SOFT_MAX: { ggml_compute_forward_soft_max(params, tensor); @@ -2285,7 +2273,6 @@ static int ggml_get_n_tasks(struct ggml_tensor * node, int n_threads) { case GGML_OP_CONT: case GGML_OP_ADD: case GGML_OP_ADD_ID: - case GGML_OP_ADD1: case GGML_OP_ACC: case GGML_OP_CUMSUM: case GGML_OP_TRI: @@ -2407,8 +2394,6 @@ static int ggml_get_n_tasks(struct ggml_tensor * node, int n_threads) { { n_tasks = 1; } break; - case GGML_OP_DIAG_MASK_ZERO: - case GGML_OP_DIAG_MASK_INF: case GGML_OP_SOFT_MAX_BACK: case GGML_OP_ROPE: case GGML_OP_ROPE_BACK: @@ -2889,7 +2874,6 @@ struct ggml_cplan ggml_graph_plan( } break; case GGML_OP_ADD: case GGML_OP_ADD_ID: - case GGML_OP_ADD1: { if (ggml_is_quantized(node->src[0]->type) || node->src[0]->type == GGML_TYPE_F8_E4M3) { cur = ggml_type_size(GGML_TYPE_F32) * node->src[0]->ne[0] * n_tasks; diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index 00a81405198c..eed5d69e3c19 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -5704,94 +5704,6 @@ void ggml_compute_forward_diag( } } -// ggml_compute_forward_diag_mask_inf - -static void ggml_compute_forward_diag_mask_f32( - const ggml_compute_params * params, - ggml_tensor * dst, - const float value) { - - const ggml_tensor * src0 = dst->src[0]; - - const int ith = params->ith; - const int nth = params->nth; - - const int n_past = ((int32_t *) dst->op_params)[0]; - const bool inplace = src0->data == dst->data; - - GGML_ASSERT(n_past >= 0); - - if (!inplace) { - if (ith == 0) { - // memcpy needs to be synchronized across threads to avoid race conditions. - // => do it in INIT phase - GGML_ASSERT(ggml_nelements(dst) == ggml_nelements(src0)); - GGML_ASSERT(ggml_is_contiguous(dst) && ggml_is_contiguous(src0)); - memcpy( - ((char *) dst->data), - ((char *) src0->data), - ggml_nbytes(dst)); - } - ggml_barrier(params->threadpool); - } - - // TODO: handle transposed/permuted matrices - - const int n = ggml_nrows(src0); - const int nc = src0->ne[0]; - const int nr = src0->ne[1]; - const int nz = n/nr; - - GGML_ASSERT( dst->nb[0] == sizeof(float)); - GGML_ASSERT(src0->nb[0] == sizeof(float)); - - for (int k = 0; k < nz; k++) { - for (int j = ith; j < nr; j += nth) { - for (int i = n_past; i < nc; i++) { - if (i > n_past + j) { - *(float *)((char *) dst->data + k*dst->nb[2] + j*dst->nb[1] + i*dst->nb[0]) = value; - } - } - } - } -} - -void ggml_compute_forward_diag_mask_inf( - const ggml_compute_params * params, - ggml_tensor * dst) { - - const ggml_tensor * src0 = dst->src[0]; - - switch (src0->type) { - case GGML_TYPE_F32: - { - ggml_compute_forward_diag_mask_f32(params, dst, -INFINITY); - } break; - default: - { - GGML_ABORT("fatal error"); - } - } -} - -void ggml_compute_forward_diag_mask_zero( - const ggml_compute_params * params, - ggml_tensor * dst) { - - const ggml_tensor * src0 = dst->src[0]; - - switch (src0->type) { - case GGML_TYPE_F32: - { - ggml_compute_forward_diag_mask_f32(params, dst, 0); - } break; - default: - { - GGML_ABORT("fatal error"); - } - } -} - // ggml_compute_forward_soft_max static void ggml_compute_forward_soft_max_f32( @@ -8911,14 +8823,9 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( float * VKQ32 = (float *) params->wdata + ith*(1*DK + 2*DV + CACHE_LINE_SIZE_F32); // FP32 VKQ accumulator float * V32 = (VKQ32 + 1*DV); // (temporary) FP32 V buffer - ggml_fp16_t * VKQ16 = (ggml_fp16_t *) (VKQ32 + 1*DV); // (temporary) FP16 VKQ accumulator ggml_fp16_t * Q_q = (ggml_fp16_t *) (VKQ32 + 2*DV); // (temporary) buffer for Q converted to quantized/FP16 - if (v->type == GGML_TYPE_F16) { - memset(VKQ16, 0, DV*sizeof(ggml_fp16_t)); - } else { - memset(VKQ32, 0, DV*sizeof(float)); - } + memset(VKQ32, 0, DV*sizeof(float)); const ggml_fp16_t * mp = mask ? (ggml_fp16_t *)((char *) mask->data + iq1*mask->nb[1] + (iq2%mask->ne[2])*mask->nb[2] + (iq3%mask->ne[3])*mask->nb[3]) : NULL; @@ -8970,53 +8877,32 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( const char * v_data = ((const char *) v->data + (ik1*nbv1 + iv2*nbv2 + iv3*nbv3)); - if (v->type == GGML_TYPE_F16) { - if (s > M) { - // s is new maximum, ms < 1.0f, vs == expf(s - s) == 1.0f - M = s; - ms = expf(Mold - M); - - // V = V*expf(Mold - M) - ggml_vec_scale_f16(DV, VKQ16, ms); - } else { - // no new maximum, ms == 1.0f, vs != 1.0f - vs = expf(s - M); - } + if (s > M) { + // s is new maximum, ms < 1.0f, vs == expf(s - s) == 1.0f + M = s; + ms = expf(Mold - M); - // V += v*expf(s - M) - ggml_vec_mad_f16(DV, VKQ16, (const ggml_fp16_t *) v_data, vs); + // V = V*expf(Mold - M) + ggml_vec_scale_f32(DV, VKQ32, ms); } else { - if (s > M) { - // s is new maximum, ms < 1.0f, vs == expf(s - s) == 1.0f - M = s; - ms = expf(Mold - M); - - // V = V*expf(Mold - M) - ggml_vec_scale_f32(DV, VKQ32, ms); - } else { - // no new maximum, ms == 1.0f, vs != 1.0f - vs = expf(s - M); - } + // no new maximum, ms == 1.0f, vs != 1.0f + vs = expf(s - M); + } - // V += v*expf(s - M) - if (v_to_float) { - v_to_float(v_data, V32, DV); - ggml_vec_mad_f32(DV, VKQ32, V32, vs); - } else { - // V is F32 - ggml_vec_mad_f32(DV, VKQ32, (const float *) v_data, vs); - } + // V += v*expf(s - M) + if (v->type == GGML_TYPE_F16) { + ggml_vec_mad_f16_f32(DV, VKQ32, (const ggml_fp16_t *) v_data, vs); + } else if (v_to_float) { + v_to_float(v_data, V32, DV); + ggml_vec_mad_f32(DV, VKQ32, V32, vs); + } else { + // V is F32 + ggml_vec_mad_f32(DV, VKQ32, (const float *) v_data, vs); } S = S*ms + vs; // scale and increment sum with partial sum } - if (v->type == GGML_TYPE_F16) { - for (int64_t d = 0; d < DV; ++d) { - VKQ32[d] = GGML_CPU_FP16_TO_FP32(VKQ16[d]); - } - } - // sinks - apply only on the first kv-chunk if (sinks && ic_start == 0) { const float s = ((float *)((char *) sinks->data))[h]; diff --git a/ggml/src/ggml-cpu/ops.h b/ggml/src/ggml-cpu/ops.h index 00a2ea7dc2de..aac527a64c54 100644 --- a/ggml/src/ggml-cpu/ops.h +++ b/ggml/src/ggml-cpu/ops.h @@ -56,8 +56,6 @@ void ggml_compute_forward_get_rows(const struct ggml_compute_params * params, st void ggml_compute_forward_get_rows_back(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_set_rows(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_diag(const struct ggml_compute_params * params, struct ggml_tensor * dst); -void ggml_compute_forward_diag_mask_inf(const struct ggml_compute_params * params, struct ggml_tensor * dst); -void ggml_compute_forward_diag_mask_zero(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_soft_max(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_soft_max_ext_back(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_rope(const struct ggml_compute_params * params, struct ggml_tensor * dst); diff --git a/ggml/src/ggml-cpu/simd-gemm.h b/ggml/src/ggml-cpu/simd-gemm.h index 6832444fec1e..969ffd13ff02 100644 --- a/ggml/src/ggml-cpu/simd-gemm.h +++ b/ggml/src/ggml-cpu/simd-gemm.h @@ -9,7 +9,7 @@ // TODO: untested on avx512 // These are in units of GGML_F32_EPR -#if defined(__AVX512F__) || defined (__ARM_NEON__) +#if defined(__AVX512F__) || defined(__ARM_NEON) static constexpr int GEMM_RM = 4; static constexpr int GEMM_RN = 4; // 16+4+1 = 25/32 #elif defined(__AVX2__) || defined(__AVX__) diff --git a/ggml/src/ggml-cpu/spacemit/ime.cpp b/ggml/src/ggml-cpu/spacemit/ime.cpp index 6cf24305833b..dc51ad0aa4dd 100644 --- a/ggml/src/ggml-cpu/spacemit/ime.cpp +++ b/ggml/src/ggml-cpu/spacemit/ime.cpp @@ -1154,9 +1154,17 @@ class tensor_traits_common : public tensor_traits_base { ggml_compute_forward_concat(params, op); } return true; - // TODO For GGML_OP_GATED_DELTA_NET - // case GGML_OP_GATED_DELTA_NET: - // return true; + case GGML_OP_GATED_DELTA_NET: + if (params->use_ref) { + return false; + } + switch (op->src[0]->type) { + case GGML_TYPE_F32: + spacemit_kernels::rvv::forward_gated_delta_net_f32(params, op); + return true; + default: + GGML_ABORT("fatal error"); + } default: break; } @@ -1315,11 +1323,10 @@ static const ggml::cpu::tensor_traits * ggml_riscv64_spacemit_get_optimal_repack case GGML_TYPE_Q4_1: { #if defined(RISCV64_SPACEMIT_IME2) - // TODO - // if (cur->ne[1] % 32 == 0 && cur->ne[0] % 256 == 0 && - // (ggml::cpu::riscv64_spacemit::global_spine_env_info.use_ime2)) { - // return &ggml::cpu::riscv64_spacemit::q4_1_32x256_q8_0; - // } + if (cur->ne[1] % 32 == 0 && cur->ne[0] % 256 == 0 && + (ggml::cpu::riscv64_spacemit::global_spine_env_info.use_ime2)) { + return &ggml::cpu::riscv64_spacemit::q4_1_32x256_q8_0; + } if (cur->ne[1] % 32 == 0 && (ggml::cpu::riscv64_spacemit::global_spine_env_info.use_ime2)) { return &ggml::cpu::riscv64_spacemit::q4_1_32x32_q8_0; @@ -1661,7 +1668,7 @@ class extra_buffer_type : ggml::cpu::extra_buffer_type { case GGML_OP_SUM_ROWS: case GGML_OP_GET_ROWS: case GGML_OP_CONCAT: - // case GGML_OP_GATED_DELTA_NET: + case GGML_OP_GATED_DELTA_NET: return (ggml::cpu::tensor_traits *) (&ggml::cpu::riscv64_spacemit::rvv_impl); default: // GGML_ABORT("fatal error"); diff --git a/ggml/src/ggml-cpu/spacemit/ime2_kernels.cpp b/ggml/src/ggml-cpu/spacemit/ime2_kernels.cpp index bb04ff6b871d..92b84a90b0fb 100644 --- a/ggml/src/ggml-cpu/spacemit/ime2_kernels.cpp +++ b/ggml/src/ggml-cpu/spacemit/ime2_kernels.cpp @@ -2999,8 +2999,107 @@ void gemm_kernel_i8i4_hp_m1(size_t blk_len, "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31", "fa0", "fa1", "ft0", "ft1"); } } else { - // TODO: support quant_b_zp for i8i4 hp kernel - GGML_ABORT("gemm_kernel_i8i4_hp_m1 with quant_b_zp is not supported yet"); + const _Float16 hp_scale_0125 = 0.125; + for (size_t ni = 0; ni < count_n; ni += 32) { + const size_t nb_real = std::min(NB_COLS, count_n - ni); + if (nb_real != NB_COLS) { + break; + } + + uint8_t * b_data = (uint8_t *) quant_b_data + (ni / NB_COLS) * b_tile_stride; + int8_t * a_data = (int8_t *) quant_a_ptr; + float * dst_c = c_ptr + ni; + + asm volatile( + "vsetvli t0, x0, e16, m1 \n\t" + "vxor.vv v31, v31, v31 \n\t" + "mv t4, %[BK] \n\t" + "li t0, 0x4c00 \n\t" + "fmv.h.x fa0, t0 \n\t" + + ".align 4 \n\t" + "BLK_LOOP%=: \n\t" + "li t1, 4608 \n\t" + "add s6, %[B], t1 \n\t" + "li t5, 8 \n\t" + "addi t6, %[A], 288 \n\t" + "flh ft1, (t6) \n\t" + "addi t6, %[A], 272 \n\t" + + "vsetvli t0, x0, e16, m1 \n\t" + "vxor.vv v16, v18, v18 \n\t" + "vxor.vv v17, v18, v18 \n\t" + "vxor.vv v18, v18, v18 \n\t" + "vxor.vv v19, v18, v18 \n\t" + + "INNER_BLK_LOOP%=: \n\t" + "flh fa1, (t6) \n\t" + "addi t6, t6, 2 \n\t" + "flh ft0, (%[A]) \n\t" + "addi %[A], %[A], 2 \n\t" + "vsetvli t0, x0, e8, mf4 \n\t" + "vle8.v v3, (%[A]) \n\t" + "addi %[A], %[A], 32 \n\t" + + "vsetvli t0, x0, e16, mf2 \n\t" + "vle16.v v8, (%[B]) \n\t" + "addi %[B], %[B], 64 \n\t" + "vl4r.v v4, (%[B]) \n\t" + "addi %[B], %[B], 512 \n\t" + "vfmul.vf v8, v8, ft0 \n\t" + "vfmul.vf v9, v8, fa0 \n\t" + "vsetvli t0, x0, e8, mf4 \n\t" + "vle8.v v11, (s6) \n\t" + "addi s6, s6, 32 \n\t" + "vfwcvt.f.xu.v v13, v11 \n\t" + "fmul.h ft2, fa1, %[HP0125] \n\t" + "vsetvli t0, x0, e16, mf2 \n\t" + "vfmul.vv v10, v13, v8 \n\t" + "vfmul.vf v10, v10, ft2 \n\t" + "vfwmacc.vf v31, ft1, v10 \n\t" + + "vsetvli t0, x0, e8, m1 \n\t" + "vpack.vv v0, v8, v9, 3 \n\t" + "vsrl.vi v28, v3, 4 \n\t" + + "vsetvli t0, x0, e16, m1 \n\t" + "vnpack4.vv v2, v3, v3, 3 \n\t" + "vnpack4.vv v3, v28, v28, 3 \n\t" + + "vsetvli t0, x0, e16, m1 \n\t" + "vmadotsu.hp v16, v3, v4, v0, 4, i4 \n\t" + "vmadotsu.hp v17, v3, v5, v0, 5, i4 \n\t" + "vmadotsu.hp v18, v3, v6, v0, 6, i4 \n\t" + "vmadotsu.hp v19, v3, v7, v0, 7, i4 \n\t" + "vmadotu.hp v16, v2, v4, v0, 0, i4 \n\t" + "vmadotu.hp v17, v2, v5, v0, 1, i4 \n\t" + "vmadotu.hp v18, v2, v6, v0, 2, i4 \n\t" + "vmadotu.hp v19, v2, v7, v0, 3, i4 \n\t" + + "addi t5, t5, -1 \n\t" + "bgtz t5, INNER_BLK_LOOP%= \n\t" + + "vpack.vv v8, v16, v17, 1 \n\t" + "vpack.vv v12, v18, v19, 1 \n\t" + "vpack.vv v20, v8, v12, 2 \n\t" + + "vsetvli t0, x0, e16, mf2 \n\t" + "addi t4, t4, -1 \n\t" + "vfwmacc.vf v31, ft1, v20 \n\t" + + "addi %[A], t6, 2 \n\t" + "mv %[B], s6 \n\t" + + "bgtz t4, BLK_LOOP%= \n\t" + + "vsetvli t0, x0, e32, m1 \n\t" + "vse32.v v31, (%[DST]) \n\t" + : [A] "+r"(a_data), [B] "+r"(b_data) + : [DST] "r"(dst_c), [BK] "r"(k_blks), [HP0125] "f"(hp_scale_0125) + : "t0", "t1", "t2", "t3", "t4", "t5", "t6", "s6", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", + "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", + "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31", "fa0", "fa1", "ft0", "ft1", "ft2"); + } } } diff --git a/ggml/src/ggml-cpu/spacemit/rvv_kernels.cpp b/ggml/src/ggml-cpu/spacemit/rvv_kernels.cpp index 13b84dcbe72b..e27a006eab0d 100644 --- a/ggml/src/ggml-cpu/spacemit/rvv_kernels.cpp +++ b/ggml/src/ggml-cpu/spacemit/rvv_kernels.cpp @@ -3175,4 +3175,199 @@ template void forward_get_rows(ggml_compute_params * params, ggml_tenso template void forward_concat(ggml_compute_params * params, ggml_tensor * op); template void forward_concat(ggml_compute_params * params, ggml_tensor * op); +static inline float rvv_dot_f32(const float * x, const float * y, int64_t n) { + size_t vl = __riscv_vsetvlmax_e32m4(); + vfloat32m4_t vsum = __riscv_vfmv_v_f_f32m4(0.0f, vl); + for (int64_t i = 0; i < n; i += vl) { + vl = __riscv_vsetvl_e32m4(n - i); + vfloat32m4_t ax = __riscv_vle32_v_f32m4(x + i, vl); + vfloat32m4_t ay = __riscv_vle32_v_f32m4(y + i, vl); + vsum = __riscv_vfmacc_vv_f32m4_tu(vsum, ax, ay, vl); + } + vl = __riscv_vsetvlmax_e32m4(); + vfloat32m1_t vs = __riscv_vfmv_v_f_f32m1(0.0f, 1); + vs = __riscv_vfredusum_vs_f32m4_f32m1(vsum, vs, vl); + return __riscv_vfmv_f_s_f32m1_f32(vs); +} + +static void forward_gated_delta_net_one_chunk( + const ggml_compute_params * params, + ggml_tensor * dst, + int64_t ir0, + int64_t ir1) { + + ggml_tensor * src_q = dst->src[0]; + ggml_tensor * src_k = dst->src[1]; + ggml_tensor * src_v = dst->src[2]; + ggml_tensor * src_g = dst->src[3]; + ggml_tensor * src_beta = dst->src[4]; + ggml_tensor * src_state = dst->src[5]; + + const int64_t S_v = src_v->ne[0]; + const int64_t H = src_v->ne[1]; + const int64_t n_tokens = src_v->ne[2]; + const int64_t n_seqs = src_v->ne[3]; + + GGML_ASSERT(ggml_is_contiguous_rows(src_q)); + GGML_ASSERT(ggml_is_contiguous_rows(src_k)); + GGML_ASSERT(ggml_is_contiguous_rows(src_v)); + GGML_ASSERT(ggml_is_contiguous(src_g)); + GGML_ASSERT(ggml_is_contiguous(src_beta)); + GGML_ASSERT(ggml_is_contiguous(src_state)); + + GGML_ASSERT(src_g->ne[0] == 1 || src_g->ne[0] == S_v); + GGML_ASSERT(src_beta->ne[0] == 1); + + GGML_TENSOR_LOCALS(int64_t, neq, src_q, ne); + GGML_TENSOR_LOCALS(size_t, nbq, src_q, nb); + GGML_TENSOR_LOCALS(int64_t, nek, src_k, ne); + GGML_TENSOR_LOCALS(size_t, nbk, src_k, nb); + GGML_TENSOR_LOCALS(int64_t, nev, src_v, ne); + GGML_TENSOR_LOCALS(size_t, nbv, src_v, nb); + GGML_TENSOR_LOCALS(int64_t, neg, src_g, ne); + GGML_TENSOR_LOCALS(size_t, nbg, src_g, nb); + GGML_TENSOR_LOCALS(size_t, nbb, src_beta, nb); + + const bool kda = (neg0 == S_v); + + const int64_t K = ggml_get_op_params_i32(dst, 0); + GGML_ASSERT(K >= 1); + const int64_t state_seq_stride = src_state->nb[3] / sizeof(float); + + const int64_t per_thread = S_v + (K > 1 ? S_v * S_v : 0); + const int ith = params->ith; + + float * delta = (float *) params->wdata + ith * per_thread + CACHE_LINE_SIZE_F32; + float * state_work = K > 1 ? (delta + S_v) : nullptr; + + const int64_t attn_score_elems = S_v * H * n_tokens * n_seqs; + const int64_t state_size_per_snap = S_v * S_v * H * n_seqs; + float * attn_out_base = (float *) dst->data; + float * state_out_base = (float *) dst->data + attn_score_elems; + + const float * state_in_base = (const float *) src_state->data; + + const int64_t rq3 = nev3 / neq3; + const int64_t rk3 = nev3 / nek3; + + const float scale = 1.0f / sqrtf((float) S_v); + + for (int64_t ir = ir0; ir < ir1; ++ir) { + const int64_t iv1 = ir % H; + const int64_t iv3 = ir / H; + + const int64_t iq1 = iv1 % neq1; + const int64_t ik1 = iv1 % nek1; + + const int64_t iq3 = iv3 / rq3; + const int64_t ik3 = iv3 / rk3; + + float * s_out = (K > 1) + ? state_work + : state_out_base + (iv3 * H + iv1) * S_v * S_v; + + const float * s_in = state_in_base + iv3 * state_seq_stride + iv1 * S_v * S_v; + memcpy(s_out, s_in, S_v * S_v * sizeof(float)); + + float * attn_data = attn_out_base + (iv3 * n_tokens * H + iv1) * S_v; + + for (int64_t t = 0; t < n_tokens; t++) { + const float * q_d = (const float *) ((const char *) src_q->data + iq3 * nbq3 + t * nbq2 + iq1 * nbq1); + const float * k_d = (const float *) ((const char *) src_k->data + ik3 * nbk3 + t * nbk2 + ik1 * nbk1); + const float * v_d = (const float *) ((const char *) src_v->data + iv3 * nbv3 + t * nbv2 + iv1 * nbv1); + + const float beta_val = *(const float *) ((const char *) src_beta->data + iv3 * nbb3 + t * nbb2 + iv1 * nbb1); + const float * g_d = (const float *) ((const char *) src_g->data + iv3 * nbg3 + t * nbg2 + iv1 * nbg1); + + if (kda) { + for (int64_t i = 0; i < S_v; ++i) { + delta[i] = expf(g_d[i]); + } + for (int64_t j = 0; j < S_v; ++j) { + float * row = s_out + j * S_v; + const float * d = delta; + int64_t remaining = S_v; + while (remaining > 0) { + const size_t vl = __riscv_vsetvl_e32m4(remaining); + vfloat32m4_t vr = __riscv_vle32_v_f32m4(row, vl); + vfloat32m4_t vd = __riscv_vle32_v_f32m4(d, vl); + vr = __riscv_vfmul_vv_f32m4(vr, vd, vl); + __riscv_vse32_v_f32m4(row, vr, vl); + row += vl; + d += vl; + remaining -= vl; + } + } + } else { + const float gate = expf(g_d[0]); + float * p = s_out; + int64_t remaining = S_v * S_v; + while (remaining > 0) { + const size_t vl = __riscv_vsetvl_e32m4(remaining); + vfloat32m4_t v = __riscv_vle32_v_f32m4(p, vl); + v = __riscv_vfmul_vf_f32m4(v, gate, vl); + __riscv_vse32_v_f32m4(p, v, vl); + p += vl; + remaining -= vl; + } + } + + for (int64_t j = 0; j < S_v; ++j) { + const float sum = rvv_dot_f32(s_out + j * S_v, k_d, S_v); + delta[j] = (v_d[j] - sum) * beta_val; + } + + for (int64_t j = 0; j < S_v; ++j) { + float * row = s_out + j * S_v; + const float * k = k_d; + const float dj = delta[j]; + int64_t remaining = S_v; + while (remaining > 0) { + const size_t vl = __riscv_vsetvl_e32m4(remaining); + vfloat32m4_t vr = __riscv_vle32_v_f32m4(row, vl); + vfloat32m4_t vk = __riscv_vle32_v_f32m4(k, vl); + vr = __riscv_vfmacc_vf_f32m4(vr, dj, vk, vl); + __riscv_vse32_v_f32m4(row, vr, vl); + row += vl; + k += vl; + remaining -= vl; + } + } + + for (int64_t j = 0; j < S_v; ++j) { + const float sum = rvv_dot_f32(s_out + j * S_v, q_d, S_v); + attn_data[j] = sum * scale; + } + + attn_data += S_v * H; + + if (K > 1) { + const int64_t target_slot = n_tokens - 1 - t; + if (target_slot >= 0 && target_slot < K) { + float * curr_state_o = state_out_base + target_slot * state_size_per_snap + + (iv3 * H + iv1) * S_v * S_v; + memcpy(curr_state_o, s_out, S_v * S_v * sizeof(float)); + } + } + } + } +} + +void forward_gated_delta_net_f32(ggml_compute_params * params, ggml_tensor * dst) { + ggml_tensor * src_v = dst->src[2]; + + int ith = params->ith; + int nth = params->nth; + + const auto nr = src_v->ne[1] * src_v->ne[3]; + const auto task_per_thread = (nr + nth - 1) / nth; + + const auto task_begin = ith * task_per_thread; + const auto task_end = std::min((ith + 1) * task_per_thread, nr); + + if (task_begin < task_end) { + forward_gated_delta_net_one_chunk(params, dst, task_begin, task_end); + } +} + } // namespace spacemit_kernels::rvv diff --git a/ggml/src/ggml-cpu/spacemit/rvv_kernels.h b/ggml/src/ggml-cpu/spacemit/rvv_kernels.h index edddf957c21d..a085613a3071 100644 --- a/ggml/src/ggml-cpu/spacemit/rvv_kernels.h +++ b/ggml/src/ggml-cpu/spacemit/rvv_kernels.h @@ -62,6 +62,8 @@ void forward_rms_norm_f32(ggml_compute_params * params, ggml_tensor * op); void forward_norm_f32(ggml_compute_params * params, ggml_tensor * op); +void forward_gated_delta_net_f32(ggml_compute_params * params, ggml_tensor * op); + void forward_cont_with_permute(ggml_compute_params * params, ggml_tensor * op); void forward_cpy_with_permute(ggml_compute_params * params, ggml_tensor * op); diff --git a/ggml/src/ggml-cpu/vec.h b/ggml/src/ggml-cpu/vec.h index 6598016d375a..c54ed3f07787 100644 --- a/ggml/src/ggml-cpu/vec.h +++ b/ggml/src/ggml-cpu/vec.h @@ -436,6 +436,41 @@ inline static void ggml_vec_mad_f32(const int n, float * GGML_RESTRICT y, const #endif } +// y (F32) += x (F16)*v +// on AVX512, AVX with F16C, NEON and RVV, x is widened to F32 in-register and fused into the multiply-add +inline static void ggml_vec_mad_f16_f32(const int n, float * GGML_RESTRICT y, const ggml_fp16_t * GGML_RESTRICT x, const float v) { + int i = 0; +#if defined(__AVX512F__) + const __m512 vx = _mm512_set1_ps(v); + for (; i + 16 <= n; i += 16) { + const __m512 ax = _mm512_cvtph_ps(_mm256_loadu_si256((const __m256i *)(x + i))); + _mm512_storeu_ps(y + i, _mm512_fmadd_ps(ax, vx, _mm512_loadu_ps(y + i))); + } +#elif defined(__AVX__) && defined(__F16C__) + const __m256 vx = _mm256_set1_ps(v); + for (; i + 8 <= n; i += 8) { + const __m256 ax = _mm256_cvtph_ps(_mm_loadu_si128((const __m128i *)(x + i))); + _mm256_storeu_ps(y + i, GGML_F32x8_FMA(_mm256_loadu_ps(y + i), ax, vx)); + } +#elif defined(__ARM_NEON) && defined(__ARM_FEATURE_FMA) && defined(__ARM_FP16_FORMAT_IEEE) + const float32x4_t vx = vdupq_n_f32(v); + for (; i + 8 <= n; i += 8) { + const float16x8_t ax = vld1q_f16((const __fp16 *)(x + i)); + vst1q_f32(y + i + 0, vfmaq_f32(vld1q_f32(y + i + 0), vcvt_f32_f16(vget_low_f16 (ax)), vx)); + vst1q_f32(y + i + 4, vfmaq_f32(vld1q_f32(y + i + 4), vcvt_f32_f16(vget_high_f16(ax)), vx)); + } +#elif defined(__riscv_v_intrinsic) && defined(__riscv_zvfhmin) + for (int vl; i < n; i += vl) { + vl = __riscv_vsetvl_e16m2(n - i); + const vfloat32m4_t ax = __riscv_vfwcvt_f_f_v_f32m4(__riscv_vle16_v_f16m2((const _Float16 *)x + i, vl), vl); + __riscv_vse32_v_f32m4(y + i, __riscv_vfmacc_vf_f32m4(__riscv_vle32_v_f32m4(y + i, vl), v, ax, vl), vl); + } +#endif + for (; i < n; ++i) { + y[i] += GGML_CPU_FP16_TO_FP32(x[i])*v; + } +} + inline static void ggml_vec_mad_f16(const int n, ggml_fp16_t * GGML_RESTRICT y, const ggml_fp16_t * GGML_RESTRICT x, const float v) { #if defined(GGML_SIMD) && defined(__ARM_FEATURE_SVE) const int sve_register_length = svcntb() * 8; diff --git a/ggml/src/ggml-cuda/common.cuh b/ggml/src/ggml-cuda/common.cuh index 66aa1553c320..a1a92b67663f 100644 --- a/ggml/src/ggml-cuda/common.cuh +++ b/ggml/src/ggml-cuda/common.cuh @@ -137,6 +137,14 @@ static __device__ __forceinline__ void ggml_cuda_syncwarp() { #endif // GGML_USE_HIP } +static __device__ __forceinline__ void ggml_cuda_prefetch_l2(const void * p) { +#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) + asm volatile("prefetch.global.L2 [%0];" :: "l"(p)); +#else + GGML_UNUSED(p); +#endif // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) +} + static __device__ __forceinline__ void ggml_cuda_pdl_sync() { #if defined(GGML_CUDA_USE_PDL) && __CUDA_ARCH__ >= GGML_CUDA_CC_HOPPER cudaGridDependencySynchronize(); @@ -1276,6 +1284,8 @@ const ggml_cuda_device_info & ggml_cuda_info(); void ggml_cuda_set_device(int device); int ggml_cuda_get_device(); +bool ggml_cuda_pool_debug_enabled(); + struct ggml_cuda_pool { virtual ~ggml_cuda_pool() = default; @@ -1402,10 +1412,14 @@ struct ggml_backend_cuda_context { CUBLAS_CHECK(cublasCreate(&cublas_handles[device][curr_stream_no])); CUBLAS_CHECK(cublasSetMathMode(cublas_handles[device][curr_stream_no], CUBLAS_TF32_TENSOR_OP_MATH)); CUBLAS_CHECK(cublasSetStream(cublas_handles[device][curr_stream_no], stream())); -#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && (CUBLAS_VER_MAJOR > 11 || (CUBLAS_VER_MAJOR == 11 && CUBLAS_VER_MINOR >= 2)) +#if (defined(GGML_USE_HIP) && HIP_VERSION >= 70000000) || (!defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && (CUBLAS_VER_MAJOR > 11 || (CUBLAS_VER_MAJOR == 11 && CUBLAS_VER_MINOR >= 2))) if (cublas_workspace_sizes[device] == 0) { +#if defined(GGML_USE_HIP) + cublas_workspace_sizes[device] = 32 * 1024 * 1024; +#else const int cc = ggml_cuda_info().devices[device].cc; cublas_workspace_sizes[device] = (cc >= GGML_CUDA_CC_HOPPER) ? 32 * 1024 * 1024 : 4 * 1024 * 1024; +#endif } CUDA_CHECK(cudaMalloc(&cublas_workspaces[device][curr_stream_no], cublas_workspace_sizes[device])); CUBLAS_CHECK(cublasSetWorkspace(cublas_handles[device][curr_stream_no], cublas_workspaces[device][curr_stream_no], cublas_workspace_sizes[device])); diff --git a/ggml/src/ggml-cuda/cp-async.cuh b/ggml/src/ggml-cuda/cp-async.cuh index 63d0c482ff72..1071352e7b94 100644 --- a/ggml/src/ggml-cuda/cp-async.cuh +++ b/ggml/src/ggml-cuda/cp-async.cuh @@ -55,3 +55,23 @@ static __device__ __forceinline__ void cp_async_wait_all() { NO_DEVICE_CODE; #endif // CP_ASYNC_AVAILABLE } + +// Commits the copies issued since the last commit as one group. +static __device__ __forceinline__ void cp_async_commit_group() { +#ifdef CP_ASYNC_AVAILABLE + asm volatile("cp.async.commit_group;"); +#else + NO_DEVICE_CODE; +#endif // CP_ASYNC_AVAILABLE +} + +// Makes each thread wait until at most n of its copy groups are pending. +// Like cp_async_wait_all, this does NOT provide any additional synchronization. +template +static __device__ __forceinline__ void cp_async_wait_group() { +#ifdef CP_ASYNC_AVAILABLE + asm volatile("cp.async.wait_group %0;" : : "n"(n)); +#else + NO_DEVICE_CODE; +#endif // CP_ASYNC_AVAILABLE +} diff --git a/ggml/src/ggml-cuda/diagmask.cu b/ggml/src/ggml-cuda/diagmask.cu deleted file mode 100644 index 4b713ba22eb5..000000000000 --- a/ggml/src/ggml-cuda/diagmask.cu +++ /dev/null @@ -1,40 +0,0 @@ -#include "diagmask.cuh" - -static __global__ void diag_mask_inf_f32(const float * x, float * dst, const int ncols, const int rows_per_channel, const int n_past) { - const int col = blockDim.y*blockIdx.y + threadIdx.y; - const int row = blockDim.x*blockIdx.x + threadIdx.x; - - if (col >= ncols) { - return; - } - - const int i = row*ncols + col; - //dst[i] = col > (n_past + row % rows_per_channel) ? -INFINITY : x[i]; - //dst[i] = x[i] - (col > n_past + row % rows_per_channel) * INT_MAX; // equivalent within rounding error but slightly faster on GPU - dst[i] = x[i] - (col > n_past + row % rows_per_channel) * FLT_MAX; -} - -static void diag_mask_inf_f32_cuda(const float * x, float * dst, const int ncols_x, const int nrows_x, const int rows_per_channel, const int n_past, cudaStream_t stream) { - const dim3 block_dims(1, CUDA_DIAG_MASK_INF_BLOCK_SIZE, 1); - const int block_num_x = (ncols_x + CUDA_DIAG_MASK_INF_BLOCK_SIZE - 1) / CUDA_DIAG_MASK_INF_BLOCK_SIZE; - const dim3 block_nums(nrows_x, block_num_x, 1); - diag_mask_inf_f32<<>>(x, dst, ncols_x, rows_per_channel, n_past); -} - -void ggml_cuda_op_diag_mask_inf(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { - const ggml_tensor * src0 = dst->src[0]; - const float * src0_d = (const float *)src0->data; - float * dst_d = (float *)dst->data; - cudaStream_t stream = ctx.stream(); - - GGML_ASSERT(src0->type == GGML_TYPE_F32); - GGML_ASSERT( dst->type == GGML_TYPE_F32); - - const int64_t ne00 = src0->ne[0]; - const int64_t ne01 = src0->ne[1]; - const int nrows0 = ggml_nrows(src0); - - const int n_past = ((int32_t *) dst->op_params)[0]; - - diag_mask_inf_f32_cuda(src0_d, dst_d, ne00, nrows0, ne01, n_past, stream); -} diff --git a/ggml/src/ggml-cuda/diagmask.cuh b/ggml/src/ggml-cuda/diagmask.cuh deleted file mode 100644 index 6cdbef17e345..000000000000 --- a/ggml/src/ggml-cuda/diagmask.cuh +++ /dev/null @@ -1,5 +0,0 @@ -#include "common.cuh" - -#define CUDA_DIAG_MASK_INF_BLOCK_SIZE 32 - -void ggml_cuda_op_diag_mask_inf(ggml_backend_cuda_context & ctx, ggml_tensor * dst); diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index 1e4fd16c8721..1a41c91a721c 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -25,7 +25,6 @@ #include "ggml-cuda/cpy.cuh" #include "ggml-cuda/cross-entropy-loss.cuh" #include "ggml-cuda/cumsum.cuh" -#include "ggml-cuda/diagmask.cuh" #include "ggml-cuda/diag.cuh" #include "ggml-cuda/fattn.cuh" #include "ggml-cuda/fp8.cuh" @@ -34,6 +33,7 @@ #include "ggml-cuda/im2col.cuh" #include "ggml-cuda/mmf.cuh" #include "ggml-cuda/mmq.cuh" +#include "ggml-cuda/mmq-few.cuh" #include "ggml-cuda/mmvf.cuh" #include "ggml-cuda/mmvq.cuh" #include "ggml-cuda/moe-weighted-reduction.cuh" @@ -181,6 +181,11 @@ static bool ggml_cuda_p2p_enabled() { return enabled; } +bool ggml_cuda_pool_debug_enabled() { + static const bool enabled = ggml_cuda_env_flag("GGML_CUDA_POOL_DEBUG"); + return enabled; +} + static int ggml_cuda_op_offload_min_batch() { static const int min_batch = ggml_cuda_env_int("GGML_OP_OFFLOAD_MIN_BATCH", 32); return min_batch; @@ -736,9 +741,43 @@ struct ggml_cuda_pool_vmm : public ggml_cuda_pool { }; #endif // defined(GGML_USE_VMM) +// Debug pool for NVIDIA compute-sanitizer, e.g. +// `GGML_CUDA_POOL_DEBUG=1 compute-sanitizer --tool memcheck ./build/bin/test-backend-ops -b CUDA0` +// Allocations are exact-size and freed on release, +// allowing memcheck to catch out-of-bounds and use-after-free. +struct ggml_cuda_pool_debug : public ggml_cuda_pool { + int device; + size_t pool_size = 0; // leak check (error if not zero at destruction) + + explicit ggml_cuda_pool_debug(int device) : + device(device) { + } + + ~ggml_cuda_pool_debug() { + GGML_ASSERT(pool_size == 0); + } + + void * alloc(size_t size, size_t * actual_size) override { + void * ptr; + CUDA_CHECK(ggml_cuda_device_malloc(&ptr, size, device)); + *actual_size = size; + pool_size += size; + return ptr; + } + + void free(void * ptr, size_t size) override { + ggml_cuda_set_device(device); + CUDA_CHECK(cudaFree(ptr)); + pool_size -= size; + } +}; + std::unique_ptr ggml_backend_cuda_context::new_pool_for_device(ggml_backend_cuda_context & ctx, int device, [[maybe_unused]] int stream_no) { + if (ggml_cuda_pool_debug_enabled()) { + return std::unique_ptr(new ggml_cuda_pool_debug(device)); + } #if defined(GGML_USE_VMM) if (ggml_cuda_info().devices[device].vmm) { return std::unique_ptr(new ggml_cuda_pool_vmm(device)); @@ -2462,6 +2501,10 @@ static bool ggml_cuda_should_fuse_mul_mat_q(const ggml_tensor * up, const ggml_t const int64_t ncols = is_id ? y->ne[2] : y->ne[1]; const int64_t nchannels = is_id ? x_up->ne[2] : y->ne[2]*y->ne[3]; const bool use_mmvq = is_id ? ncols <= get_mmvq_mmid_max_batch(x_up->type, cc) : ggml_cuda_should_use_mmvq(x_up->type, cc, ncols); + // do not fuse the matmuls that few-row MMQ takes in ggml_cuda_mul_mat + if (!is_id && ggml_cuda_should_use_mmq_few(x_up, y, cc)) { + return false; + } if (use_mmvq || !ggml_cuda_should_use_mmq(x_up->type, cc, ncols, /*n_experts =*/ is_id ? x_up->ne[2] : 0, is_id ? 0 : x_up->ne[0], is_id ? 0 : x_up->ne[1])) { return false; @@ -2515,10 +2558,16 @@ static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor ggml_cuda_mul_mat_f(ctx, src0, src1, nullptr, dst); return; } - if (ggml_cuda_should_use_mmvq(src0->type, cc, ne11)) { + // from a per-type number of src1 columns up to 24, few-row MMQ is faster than MMVQ and MMQ + const bool use_mmq_few = ggml_cuda_should_use_mmq_few(src0, src1, cc); + if (!use_mmq_few && ggml_cuda_should_use_mmvq(src0->type, cc, ne11)) { ggml_cuda_mul_mat_vec_q(ctx, src0, src1, nullptr, dst); return; } + if (use_mmq_few) { + ggml_cuda_mul_mat_q_few(ctx, src0, src1, dst); + return; + } if (ggml_cuda_should_use_mmq(src0->type, cc, ne11, /*n_experts =*/ 0, ne00, ne01)) { ggml_cuda_mul_mat_q(ctx, src0, src1, nullptr, dst); return; @@ -2763,7 +2812,6 @@ static bool ggml_cuda_compute_forward(ggml_backend_cuda_context & ctx, struct gg ggml_cuda_dup(ctx, dst); break; case GGML_OP_ADD: - case GGML_OP_ADD1: // TODO: more efficient implementation ggml_cuda_op_add(ctx, dst); break; case GGML_OP_ADD_ID: @@ -2958,9 +3006,6 @@ static bool ggml_cuda_compute_forward(ggml_backend_cuda_context & ctx, struct gg case GGML_OP_DIAG: ggml_cuda_op_diag(ctx, dst); break; - case GGML_OP_DIAG_MASK_INF: - ggml_cuda_op_diag_mask_inf(ctx, dst); - break; case GGML_OP_SOFT_MAX: ggml_cuda_op_soft_max(ctx, dst); break; @@ -3310,7 +3355,54 @@ static bool ggml_cuda_graph_update_required(ggml_backend_cuda_context * cuda_ctx return res; } -static void ggml_cuda_graph_update_executable(cudaGraphExec_t & instance, cudaGraph_t cuda_graph) { +#ifdef USE_CUDA_GRAPH_CLUSTER_CHECK +static std::vector ggml_cuda_graph_get_clusters(cudaGraph_t cuda_graph, int device) { + std::vector clusters; + static const bool runtime_affected = [] { + int version = 0; + CUDA_CHECK(cudaRuntimeGetVersion(&version)); + // TODO: upper bound once fixed in the CUDA runtime + return version >= 11080; + }(); + if (!runtime_affected || ggml_cuda_info().devices[device].cc < GGML_CUDA_CC_HOPPER) { + return clusters; + } + size_t n_nodes = 0; + CUDA_CHECK(cudaGraphGetNodes(cuda_graph, nullptr, &n_nodes)); + std::vector nodes(n_nodes); + CUDA_CHECK(cudaGraphGetNodes(cuda_graph, nodes.data(), &n_nodes)); + for (size_t i = 0; i < n_nodes; ++i) { + cudaGraphNodeType type; + CUDA_CHECK(cudaGraphNodeGetType(nodes[i], &type)); + if (type != cudaGraphNodeTypeKernel) { + continue; + } + cudaLaunchAttributeValue val = {}; + CUDA_CHECK(cudaGraphKernelNodeGetAttribute(nodes[i], cudaLaunchAttributeClusterDimension, &val)); + if (val.clusterDim.x * val.clusterDim.y * val.clusterDim.z > 1) { + clusters.push_back({ i, val.clusterDim.x, val.clusterDim.y, val.clusterDim.z }); + } + } + return clusters; +} +#endif // USE_CUDA_GRAPH_CLUSTER_CHECK + +static void ggml_cuda_graph_update_executable(ggml_cuda_graph_instance & instance, cudaGraph_t cuda_graph, int device) { +#ifdef USE_CUDA_GRAPH_CLUSTER_CHECK + std::vector clusters = ggml_cuda_graph_get_clusters(cuda_graph, device); + if (instance.clusters != clusters) { + if (ggml_cuda_graph_debug_enabled()) { + GGML_LOG_DEBUG("%s: cluster dims changed, re-instantiating CUDA graph\n", __func__); + } + CUDA_CHECK(cudaGraphExecDestroy(instance)); + CUDA_CHECK(cudaGraphInstantiate(&instance.handle, cuda_graph, nullptr, nullptr, 0)); + instance.clusters = std::move(clusters); + return; + } +#else + GGML_UNUSED(device); +#endif // USE_CUDA_GRAPH_CLUSTER_CHECK + #if CUDART_VERSION >= 12000 cudaGraphExecUpdateResultInfo result_info; cudaError_t stat = cudaGraphExecUpdate(instance, cuda_graph, &result_info); @@ -3329,8 +3421,8 @@ static void ggml_cuda_graph_update_executable(cudaGraphExec_t & instance, cudaGr // so instead clear error and re-instantiate (void)cudaGetLastError(); CUDA_CHECK(cudaGraphExecDestroy(instance)); - instance = nullptr; - CUDA_CHECK(cudaGraphInstantiate(&instance, cuda_graph, nullptr, nullptr, 0)); + instance.handle = nullptr; + CUDA_CHECK(cudaGraphInstantiate(&instance.handle, cuda_graph, nullptr, nullptr, 0)); } else { GGML_ASSERT(stat == cudaSuccess); } @@ -3351,11 +3443,14 @@ static void ggml_cuda_graph_launch_chunk(ggml_backend_cuda_context * cuda_ctx, g CUDA_CHECK(cudaStreamEndCapture(cuda_ctx->stream(), &cuda_graph)); if (idx < graph->instances.size()) { - ggml_cuda_graph_update_executable(graph->instances[idx], cuda_graph); + ggml_cuda_graph_update_executable(graph->instances[idx], cuda_graph, cuda_ctx->device); } else { GGML_ASSERT(idx == graph->instances.size()); - graph->instances.emplace_back(nullptr); - CUDA_CHECK(cudaGraphInstantiate(&graph->instances[idx], cuda_graph, nullptr, nullptr, 0)); + graph->instances.emplace_back(); + CUDA_CHECK(cudaGraphInstantiate(&graph->instances[idx].handle, cuda_graph, nullptr, nullptr, 0)); +#ifdef USE_CUDA_GRAPH_CLUSTER_CHECK + graph->instances[idx].clusters = ggml_cuda_graph_get_clusters(cuda_graph, cuda_ctx->device); +#endif // USE_CUDA_GRAPH_CLUSTER_CHECK } CUDA_CHECK(cudaGraphDestroy(cuda_graph)); @@ -5053,6 +5148,23 @@ static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph return 1; } + if (!with_bias && src0->type == GGML_TYPE_NVFP4 && src1->type == GGML_TYPE_F32 && mm_node->type == GGML_TYPE_F32) { + const int cc = ggml_cuda_info().devices[cuda_ctx->device].cc; + const bool is_id = op == GGML_OP_MUL_MAT_ID; + const int64_t ncols = is_id ? src1->ne[2] : src1->ne[1]; + const bool use_mmvq = is_id ? ncols <= get_mmvq_mmid_max_batch(src0->type, cc) : + ggml_cuda_should_use_mmvq(src0->type, cc, ncols); + const bool bad_padding_clear = ggml_backend_buffer_get_usage(src0->buffer) == GGML_BACKEND_BUFFER_USAGE_COMPUTE && + ggml_nbytes(src0) != ggml_backend_buffer_get_alloc_size(src0->buffer, src0) && + src0->view_src; + if (!use_mmvq && !bad_padding_clear && + ggml_cuda_should_use_mmq(src0->type, cc, ncols, /*n_experts =*/ is_id ? src0->ne[2] : 0)) { + fusion_data.prec_src1 = ggml_prec_get_src(mm_node, 1); + ggml_cuda_mul_mat_q(*cuda_ctx, src0, src1, ids, out_node, &fusion_data); + return n_ops - 1; + } + } + if (ggml_cuda_should_fuse_mul_mat_vec_q(mm_node, out_node, bias)) { ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, out_node, &fusion_data); fused_mul_mat_vec = true; @@ -6672,7 +6784,6 @@ static bool ggml_backend_cuda_device_supports_op(ggml_backend_dev_t dev, const g case GGML_OP_PERMUTE: case GGML_OP_TRANSPOSE: case GGML_OP_ADD_ID: - case GGML_OP_ADD1: case GGML_OP_SQR: case GGML_OP_SQRT: case GGML_OP_SIN: @@ -6719,8 +6830,6 @@ static bool ggml_backend_cuda_device_supports_op(ggml_backend_dev_t dev, const g } case GGML_OP_CONT: return true; - case GGML_OP_DIAG_MASK_INF: - return true; case GGML_OP_SOFT_MAX: return true; case GGML_OP_SOFT_MAX_BACK: { diff --git a/ggml/src/ggml-cuda/graph.cuh b/ggml/src/ggml-cuda/graph.cuh index 3481de07221a..7b9c277898e1 100644 --- a/ggml/src/ggml-cuda/graph.cuh +++ b/ggml/src/ggml-cuda/graph.cuh @@ -9,6 +9,36 @@ #include #include +#ifdef USE_CUDA_GRAPH +// cudaGraphExecUpdate keeps stale kernel cluster dims (cuBLAS sm90), re-instantiate when they change +// TODO: add a test, fails on H100 (driver 590.48.01, CUDA runtime 12.9.79, cuBLAS 12.9.1.4) for F16 MUL_MAT with +// ne01 1200 <-> 1040 (k=768, n=1024) between graph updates, see https://github.com/ggml-org/llama.cpp/pull/31284 +#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && CUDART_VERSION >= 11080 +#define USE_CUDA_GRAPH_CLUSTER_CHECK +#endif + +#ifdef USE_CUDA_GRAPH_CLUSTER_CHECK +// cluster dims of a clustered kernel node +struct ggml_cuda_graph_cluster { + size_t node; + uint32_t x, y, z; + + bool operator==(const ggml_cuda_graph_cluster & other) const { + return node == other.node && x == other.x && y == other.y && z == other.z; + } +}; +#endif + +struct ggml_cuda_graph_instance { + cudaGraphExec_t handle = nullptr; +#ifdef USE_CUDA_GRAPH_CLUSTER_CHECK + std::vector clusters; +#endif + + operator cudaGraphExec_t() const { return handle; } +}; +#endif // USE_CUDA_GRAPH + struct ggml_cuda_graph { #ifdef USE_CUDA_GRAPH ~ggml_cuda_graph() { @@ -17,7 +47,7 @@ struct ggml_cuda_graph { } } // the ggml graph is captured as a series of CUDA graphs, so the GPU can run one chunk while the next is enqueued - std::vector instances; + std::vector instances; size_t num_nodes = 0; std::vector nodes; bool disable_due_to_gpu_arch = false; @@ -34,7 +64,7 @@ struct ggml_cuda_graph { bool is_enabled() const { static const bool disable_cuda_graphs_due_to_env = (getenv("GGML_CUDA_DISABLE_GRAPHS") != nullptr); - return !(disable_due_to_gpu_arch || disable_cuda_graphs_due_to_env); + return !(disable_due_to_gpu_arch || disable_cuda_graphs_due_to_env || ggml_cuda_pool_debug_enabled()); } #endif }; diff --git a/ggml/src/ggml-cuda/mmq-few.cu b/ggml/src/ggml-cuda/mmq-few.cu new file mode 100644 index 000000000000..2c2a2745e3ec --- /dev/null +++ b/ggml/src/ggml-cuda/mmq-few.cu @@ -0,0 +1,876 @@ +#include "mmq-few.cuh" +#include "cp-async.cuh" +#include "mma.cuh" +#include "quantize.cuh" +#include "vecdotq.cuh" + +#include + +// NVIDIA only: the kernel uses the NVIDIA int8 MMA fragment layout and cp.async. +#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) + +using namespace ggml_cuda_mma; + +// Few-row MMQ: int8 MMA mat-mul for 2-24 src1 columns. A CUDA block has 16 src0 rows (32 for 2 column groups on large matrices). +// Its warps split K in units of 256 values and copy raw src0 rows into their own cp.async ring, src1 is quantized to the MMA fragment layout. + +static constexpr int MMQ_FEW_MAX_NCG = 3; // max. number of column groups +static constexpr int MMQ_FEW_NROWS = 16; // src0 rows of one MMA tile +static constexpr int MMQ_FEW_NWARPS = 4; + +template +static constexpr __host__ __device__ int mmq_few_unit_size_of() { + return QK_K/ggml_cuda_type_traits::qk*ggml_cuda_type_traits::bs; +} + +// src0 bytes per 256 values, 0 for the types without a few-row decoder. +static constexpr __host__ __device__ int mmq_few_unit_size(const ggml_type type) { + switch (type) { + case GGML_TYPE_Q8_0: return mmq_few_unit_size_of(); + case GGML_TYPE_Q3_K: return mmq_few_unit_size_of(); + case GGML_TYPE_Q4_K: return mmq_few_unit_size_of(); + case GGML_TYPE_Q5_K: return mmq_few_unit_size_of(); + case GGML_TYPE_Q6_K: return mmq_few_unit_size_of(); + case GGML_TYPE_IQ3_S: return mmq_few_unit_size_of(); + case GGML_TYPE_IQ4_NL: return mmq_few_unit_size_of(); + case GGML_TYPE_IQ4_XS: return mmq_few_unit_size_of(); + default: return 0; + } +} + +// Q4_K and Q5_K also need the src1 sums for their mins. +static constexpr __host__ __device__ mmq_q8_1_ds_layout mmq_few_ds_layout(const ggml_type type) { + return type == GGML_TYPE_Q4_K || type == GGML_TYPE_Q5_K ? MMQ_Q8_1_DS_LAYOUT_DS4 : MMQ_Q8_1_DS_LAYOUT_D4; +} + +// Units of 256 values per ring stage: 1 for Q6_K, 3 column groups (fewer free registers) and 32-row tiles (2 blocks per SM), else 2. +static constexpr __host__ __device__ int mmq_few_nunits_stage(const ggml_type type, const int ncg, const int nmt) { + return type == GGML_TYPE_Q6_K || ncg > 2 || nmt > 1 ? 1 : 2; +} + +// A third ring stage only makes Q6_K faster, the other types get slower on large matrices. +static constexpr __host__ __device__ int mmq_few_nstages(const ggml_type type) { + return type == GGML_TYPE_Q6_K ? 3 : 2; +} + +// The src0 data of a ring stage does not fill whole 16 byte chunks, it is copied from the preceding 16 byte boundary. +static constexpr __host__ __device__ bool mmq_few_unaligned(const ggml_type type, const int nunits_stage) { + return (nunits_stage*mmq_few_unit_size(type)) % 16 != 0; +} + +// for unaligned data the max. over the 8 possible start offsets +static constexpr __host__ __device__ int mmq_few_nchunks(const ggml_type type, const int nunits_stage) { + const int nbytes = nunits_stage*mmq_few_unit_size(type); + return mmq_few_unaligned(type, nunits_stage) ? (14 + nbytes + 15)/16 : nbytes/16; +} + +// Unaligned rows are padded to an odd number of 16 byte chunks against bank conflicts, for aligned rows the padding costs more than it saves. +static constexpr __host__ __device__ int mmq_few_sram_stride(const ggml_type type, const int nunits_stage) { + const int nchunks = mmq_few_nchunks(type, nunits_stage); + return mmq_few_unaligned(type, nunits_stage) && nchunks % 2 == 0 ? 16*(nchunks + 1) : 16*nchunks; +} + +static constexpr __host__ __device__ int mmq_few_nbytes_shared(const ggml_type type, const int ncg, const int nmt) { + return MMQ_FEW_NWARPS*mmq_few_nstages(type)*nmt*MMQ_FEW_NROWS*mmq_few_sram_stride(type, mmq_few_nunits_stage(type, ncg, nmt)); +} + +// With Q6_K and Q8_0 two CUDA blocks with 32-row tiles would not fit into an SM. +static constexpr __host__ __device__ bool mmq_few_tall_supported(const ggml_type type) { + return type == GGML_TYPE_Q3_K || type == GGML_TYPE_Q4_K || type == GGML_TYPE_Q5_K || + type == GGML_TYPE_IQ3_S || type == GGML_TYPE_IQ4_NL || type == GGML_TYPE_IQ4_XS; +} + +#if defined(CP_ASYNC_AVAILABLE) + +// The src1 fragments of a lane for one unit of 256 values, see quantize.cuh. +struct mmq_few_y_frag { + int4 qs[4]; + int4 ds[4]; +}; + +static __device__ __forceinline__ void mmq_few_load_y(mmq_few_y_frag & yf, const int4 * y) { +#pragma unroll + for (int j = 0; j < 4; ++j) { + yf.qs[j] = y[j*WARP_SIZE + threadIdx.x]; + } +#pragma unroll + for (int j = 0; j < 4; ++j) { + yf.ds[j] = y[4*WARP_SIZE + 4*(threadIdx.x % 4) + j]; + } +} + +static __device__ __forceinline__ int2 mmq_few_get_b(const mmq_few_y_frag & yf, const int s) { + const int4 q = yf.qs[s/2]; + return s % 2 == 0 ? make_int2(q.x, q.y) : make_int2(q.z, q.w); +} + +template +static __device__ __forceinline__ float2 mmq_few_get_d(const mmq_few_y_frag & yf, const int s) { + if constexpr (ds_layout == MMQ_Q8_1_DS_LAYOUT_D4) { + const float * d = (const float *) &yf.ds[s/2]; + return make_float2(d[2*(s % 2) + 0], d[2*(s % 2) + 1]); + } else { + const half2 * ds = (const half2 *) &yf.ds[s/2]; + return make_float2(__low2float(ds[2*(s % 2) + 0]), __low2float(ds[2*(s % 2) + 1])); + } +} + +static __device__ __forceinline__ float2 mmq_few_get_sum(const mmq_few_y_frag & yf, const int s) { + const half2 * ds = (const half2 *) &yf.ds[s/2]; + return make_float2(__high2float(ds[2*(s % 2) + 0]), __high2float(ds[2*(s % 2) + 1])); +} + +// C.x[0], C.x[1]: row g, columns 2t and 2t+1. C.x[2], C.x[3]: row g+8. +static __device__ __forceinline__ tile<16, 8, int> mmq_few_mma(const int (&lo)[2], const int (&hi)[2], const int2 b) { + tile<16, 8, int> A; + A.x[0] = lo[0]; + A.x[1] = lo[1]; + A.x[2] = hi[0]; + A.x[3] = hi[1]; + tile<8, 8, int> B; + B.x[0] = b.x; + B.x[1] = b.y; + tile<16, 8, int> C; + mma(C, A, B); + return C; +} + +static __device__ __forceinline__ tile<16, 8, int> mmq_few_mma_k16(const int (&a)[2], const int b) { + tile<16, 4, int> A; + A.x[0] = a[0]; + A.x[1] = a[1]; + tile<8, 4, int> B; + B.x[0] = b; + tile<16, 8, int> C; + mma(C, A, B); + return C; +} + +// sum_d += d * (C * ls) of sub-block s for all column groups, ls are the src0 row scales +template +static __device__ __forceinline__ void mmq_few_mma_add( + const int (&lo)[2], const int (&hi)[2], const scale_t (&ls)[2], const mmq_few_y_frag (&yf)[ncg], const int s, float (&sum_d)[ncg][4]) { +#pragma unroll + for (int c = 0; c < ncg; ++c) { + const tile<16, 8, int> C = mmq_few_mma(lo, hi, mmq_few_get_b(yf[c], s)); + + const float2 d = mmq_few_get_d(yf[c], s); + sum_d[c][0] += d.x * float(C.x[0]*ls[0]); + sum_d[c][1] += d.y * float(C.x[1]*ls[0]); + sum_d[c][2] += d.x * float(C.x[2]*ls[1]); + sum_d[c][3] += d.y * float(C.x[3]*ls[1]); + } +} + +// Same with one k=16 MMA per half of sub-block s, the int8 scales of the halves are bytes 0 and 1 of sc[r]. +template +static __device__ __forceinline__ void mmq_few_mma_k16_add( + const int (&lo)[2], const int (&hi)[2], const int (&sc)[2], const mmq_few_y_frag (&yf)[ncg], const int s, float (&sum_d)[ncg][4]) { + const int sc_lo[2] = {(int8_t) sc[0], (int8_t) sc[1]}; + const int sc_hi[2] = {(int8_t) (sc[0] >> 8), (int8_t) (sc[1] >> 8)}; +#pragma unroll + for (int c = 0; c < ncg; ++c) { + const int2 b = mmq_few_get_b(yf[c], s); + const tile<16, 8, int> C_lo = mmq_few_mma_k16(lo, b.x); + const tile<16, 8, int> C_hi = mmq_few_mma_k16(hi, b.y); + + const float2 d = mmq_few_get_d(yf[c], s); + sum_d[c][0] += d.x * float(C_lo.x[0]*sc_lo[0] + C_hi.x[0]*sc_hi[0]); + sum_d[c][1] += d.y * float(C_lo.x[1]*sc_lo[0] + C_hi.x[1]*sc_hi[0]); + sum_d[c][2] += d.x * float(C_lo.x[2]*sc_lo[1] + C_hi.x[2]*sc_hi[1]); + sum_d[c][3] += d.y * float(C_lo.x[3]*sc_lo[1] + C_hi.x[3]*sc_hi[1]); + } +} + +template +static __device__ __forceinline__ void mmq_few_add_scaled(float (&sum)[ncg][4], const float (&d)[2], const float (&sum_d)[ncg][4]) { +#pragma unroll + for (int c = 0; c < ncg; ++c) { +#pragma unroll + for (int l = 0; l < 4; ++l) { + sum[c][l] += d[l/2]*sum_d[c][l]; + } + } +} + +// vec_dot: one unit of 256 values of the 16 rows of a warp, x[0] and x[1] are the rows g and g+8 of lane (g, t). +// The lane decodes the values [4t, 4t + 4) and [16 + 4t, 16 + 4t + 4) of each sub-block, its A fragments. + +template +static __device__ __forceinline__ void mmq_few_vec_dot_q45_K(const char * const (&x)[2], const mmq_few_y_frag (&yf)[ncg], float (&sum)[ncg][4]) { + using block_t = std::conditional_t; + const int t = threadIdx.x % 4; + + int qs[2][4][2]; + [[maybe_unused]] int qh[2][2]; // Q5_K: bit s holds the high bit of sub-block s + int sc[2][2]; + int mn[2][2]; + float d[2]; + float dmin[2]; +#pragma unroll + for (int r = 0; r < 2; ++r) { + const block_t * bx = (const block_t *) x[r]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + qs[r][j][0] = get_int_b4(bx->qs + 32*j, t); + qs[r][j][1] = get_int_b4(bx->qs + 32*j + 16, t); + } + if constexpr (type == GGML_TYPE_Q5_K) { + qh[r][0] = get_int_b4(bx->qh, t); + qh[r][1] = get_int_b4(bx->qh + 16, t); + } + const int4 hdr = *(const int4 *) bx; // dm and the 12 scale bytes + const int scales[3] = {hdr.y, hdr.z, hdr.w}; + sc[r][0] = unpack_scales_q45_K(scales, 0); + sc[r][1] = unpack_scales_q45_K(scales, 1); + mn[r][0] = unpack_scales_q45_K(scales, 2); + mn[r][1] = unpack_scales_q45_K(scales, 3); + const float2 dm = __half22float2(bx->dm); + d[r] = dm.x; + dmin[r] = dm.y; + } + + float sum_d[ncg][4] = {{0.0f}}; + float sum_m[ncg][4] = {{0.0f}}; +#pragma unroll + for (int s = 0; s < 8; ++s) { + const int j = s/2; + const int shift = 4*(s % 2); + int lo[2]; + int hi[2]; +#pragma unroll + for (int r = 0; r < 2; ++r) { + lo[r] = (qs[r][j][0] >> shift) & 0x0F0F0F0F; + hi[r] = (qs[r][j][1] >> shift) & 0x0F0F0F0F; + if constexpr (type == GGML_TYPE_Q5_K) { + lo[r] |= ((qh[r][0] >> s) & 0x01010101) << 4; + hi[r] |= ((qh[r][1] >> s) & 0x01010101) << 4; + } + } + const int ls[2] = {(sc[0][s/4] >> (8*(s % 4))) & 0xFF, (sc[1][s/4] >> (8*(s % 4))) & 0xFF}; + const float m0 = (mn[0][s/4] >> (8*(s % 4))) & 0xFF; + const float m1 = (mn[1][s/4] >> (8*(s % 4))) & 0xFF; + mmq_few_mma_add(lo, hi, ls, yf, s, sum_d); +#pragma unroll + for (int c = 0; c < ncg; ++c) { + const float2 sm = mmq_few_get_sum(yf[c], s); + sum_m[c][0] += m0 * sm.x; + sum_m[c][1] += m0 * sm.y; + sum_m[c][2] += m1 * sm.x; + sum_m[c][3] += m1 * sm.y; + } + } +#pragma unroll + for (int c = 0; c < ncg; ++c) { +#pragma unroll + for (int l = 0; l < 4; ++l) { + sum[c][l] += d[l/2]*sum_d[c][l] - dmin[l/2]*sum_m[c][l]; + } + } +} + +// Q6_K and Q3_K have a scale per 16 values: one k=16 MMA per half of a sub-block. +template +static __device__ __forceinline__ void mmq_few_vec_dot_q6_K(const char * const (&x)[2], const mmq_few_y_frag (&yf)[ncg], float (&sum)[ncg][4]) { + const int t = threadIdx.x % 4; + + float d[2]; +#pragma unroll + for (int r = 0; r < 2; ++r) { + d[r] = __half2float(((const block_q6_K *) x[r])->d); + } + + float sum_d[ncg][4] = {{0.0f}}; +#pragma unroll + for (int n = 0; n < 2; ++n) { + int ql[2][2][2]; // [row][ql offset 0 or 32][lo or hi] + int qh[2][2]; + int sc[2][2]; +#pragma unroll + for (int r = 0; r < 2; ++r) { + const block_q6_K * bx = (const block_q6_K *) x[r]; +#pragma unroll + for (int k = 0; k < 2; ++k) { + ql[r][k][0] = get_int_b2(bx->ql + 64*n + 32*k, t); + ql[r][k][1] = get_int_b2(bx->ql + 64*n + 32*k + 16, t); + } + qh[r][0] = get_int_b2(bx->qh + 32*n, t); + qh[r][1] = get_int_b2(bx->qh + 32*n + 16, t); + sc[r][0] = get_int_b2(bx->scales + 8*n, 0); + sc[r][1] = get_int_b2(bx->scales + 8*n, 1); + } +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int s = 4*n + j; + int lo[2]; + int hi[2]; +#pragma unroll + for (int r = 0; r < 2; ++r) { + lo[r] = __vsub4(((ql[r][j % 2][0] >> (4*(j/2))) & 0x0F0F0F0F) | (((qh[r][0] >> (2*j)) & 0x03030303) << 4), 0x20202020); + hi[r] = __vsub4(((ql[r][j % 2][1] >> (4*(j/2))) & 0x0F0F0F0F) | (((qh[r][1] >> (2*j)) & 0x03030303) << 4), 0x20202020); + } + const int sc_s[2] = {sc[0][j/2] >> (16*(j % 2)), sc[1][j/2] >> (16*(j % 2))}; // scales 2s and 2s+1 + mmq_few_mma_k16_add(lo, hi, sc_s, yf, s, sum_d); + } + } + mmq_few_add_scaled(sum, d, sum_d); +} + +template +static __device__ __forceinline__ void mmq_few_vec_dot_q3_K(const char * const (&x)[2], const mmq_few_y_frag (&yf)[ncg], float (&sum)[ncg][4]) { + const int t = threadIdx.x % 4; + + int hm[2][2]; + int sc[2][4]; // the 16 scales of a row as int8, minus 32 + float d[2]; +#pragma unroll + for (int r = 0; r < 2; ++r) { + const block_q3_K * bx = (const block_q3_K *) x[r]; + hm[r][0] = ~get_int_b2(bx->hmask, t); // a set bit means that 4 is subtracted + hm[r][1] = ~get_int_b2(bx->hmask + 16, t); +#pragma unroll + for (int ksc = 0; ksc < 4; ++ksc) { + sc[r][ksc] = unpack_scales_q3_K(bx->scales, ksc); + } + d[r] = __half2float(bx->d); + } + + float sum_d[ncg][4] = {{0.0f}}; +#pragma unroll + for (int n = 0; n < 2; ++n) { + int qs[2][2]; +#pragma unroll + for (int r = 0; r < 2; ++r) { + const block_q3_K * bx = (const block_q3_K *) x[r]; + qs[r][0] = get_int_b2(bx->qs + 32*n, t); + qs[r][1] = get_int_b2(bx->qs + 32*n + 16, t); + } +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int s = 4*n + j; + int lo[2]; + int hi[2]; +#pragma unroll + for (int r = 0; r < 2; ++r) { + lo[r] = __vsub4((qs[r][0] >> (2*j)) & 0x03030303, ((hm[r][0] >> s) & 0x01010101) << 2); + hi[r] = __vsub4((qs[r][1] >> (2*j)) & 0x03030303, ((hm[r][1] >> s) & 0x01010101) << 2); + } + const int sc_s[2] = {sc[0][s/2] >> (16*(s % 2)), sc[1][s/2] >> (16*(s % 2))}; // scales 2s and 2s+1 + mmq_few_mma_k16_add(lo, hi, sc_s, yf, s, sum_d); + } + } + mmq_few_add_scaled(sum, d, sum_d); +} + +template +static __device__ __forceinline__ void mmq_few_vec_dot_iq4_xs(const char * const (&x)[2], const mmq_few_y_frag (&yf)[ncg], float (&sum)[ncg][4]) { + const int t = threadIdx.x % 4; + + float d[2]; + int scales_h[2]; + int scales_l[2]; +#pragma unroll + for (int r = 0; r < 2; ++r) { + const block_iq4_xs * bx = (const block_iq4_xs *) x[r]; + d[r] = __half2float(bx->d); + scales_h[r] = bx->scales_h; + scales_l[r] = get_int_b4(bx->scales_l, 0); + } + + float sum_d[ncg][4] = {{0.0f}}; +#pragma unroll + for (int s = 0; s < 8; ++s) { + int lo[2]; + int hi[2]; + int ls[2]; +#pragma unroll + for (int r = 0; r < 2; ++r) { + const block_iq4_xs * bx = (const block_iq4_xs *) x[r]; + const int2 v = get_int_from_table_16(get_int_b4(bx->qs + 16*s, t), kvalues_iq4nl); + lo[r] = v.x; + hi[r] = v.y; + ls[r] = (((scales_l[r] >> (4*s)) & 0x0F) | (((scales_h[r] >> (2*s)) & 0x03) << 4)) - 32; + } + mmq_few_mma_add(lo, hi, ls, yf, s, sum_d); + } + mmq_few_add_scaled(sum, d, sum_d); +} + +// Q8_0 and IQ4_NL have a block with its own scale per 32 values. +template +static __device__ __forceinline__ void mmq_few_vec_dot_q8_0_iq4_nl(const char * const (&x)[2], const mmq_few_y_frag (&yf)[ncg], float (&sum)[ncg][4]) { + const int t = threadIdx.x % 4; + +#pragma unroll + for (int s = 0; s < 8; ++s) { + int lo[2]; + int hi[2]; + float d[2]; +#pragma unroll + for (int r = 0; r < 2; ++r) { + if constexpr (type == GGML_TYPE_Q8_0) { + const block_q8_0 * bx = (const block_q8_0 *) x[r] + s; + lo[r] = get_int_b2(bx->qs, t); + hi[r] = get_int_b2(bx->qs + 16, t); + d[r] = __half2float(bx->d); + } else { + const block_iq4_nl * bx = (const block_iq4_nl *) x[r] + s; + const int2 v = get_int_from_table_16(get_int_b2(bx->qs, t), kvalues_iq4nl); + lo[r] = v.x; + hi[r] = v.y; + d[r] = __half2float(bx->d); + } + } + mmq_few_mma_add(lo, hi, d, yf, s, sum); + } +} + +template +static __device__ __forceinline__ void mmq_few_vec_dot_iq3_s(const char * const (&x)[2], const mmq_few_y_frag (&yf)[ncg], float (&sum)[ncg][4]) { + const int t = threadIdx.x % 4; + + float d[2]; +#pragma unroll + for (int r = 0; r < 2; ++r) { + d[r] = __half2float(((const block_iq3_s *) x[r])->d); + } + + float sum_d[ncg][4] = {{0.0f}}; +#pragma unroll + for (int s = 0; s < 8; ++s) { + int lo[2]; + int hi[2]; + int ls[2]; +#pragma unroll + for (int r = 0; r < 2; ++r) { + const block_iq3_s * bx = (const block_iq3_s *) x[r]; + const int qh = bx->qh[s]; + // the values [4k, 4k + 4) of a sub-block come from grid entry k, with the signs in bits 4*(k%2) of byte k/2 + const int k_lo = t; + const int k_hi = 4 + t; + const int grid_lo = iq3s_grid[bx->qs[8*s + k_lo] | (((qh >> k_lo) & 1) << 8)]; + const int grid_hi = iq3s_grid[bx->qs[8*s + k_hi] | (((qh >> k_hi) & 1) << 8)]; + const int sign_lo = (bx->signs[4*s + k_lo/2] >> (4*(k_lo % 2))) & 0x0F; + const int sign_hi = (bx->signs[4*s + k_hi/2] >> (4*(k_hi % 2))) & 0x0F; + const int mask_lo = __vcmpne4(((sign_lo & 0x03) << 7) | ((sign_lo & 0x0C) << 21), 0x00000000); + const int mask_hi = __vcmpne4(((sign_hi & 0x03) << 7) | ((sign_hi & 0x0C) << 21), 0x00000000); + lo[r] = __vsub4(grid_lo ^ mask_lo, mask_lo); + hi[r] = __vsub4(grid_hi ^ mask_hi, mask_hi); + ls[r] = 1 + 2*((bx->scales[s/2] >> (4*(s % 2))) & 0x0F); + } + mmq_few_mma_add(lo, hi, ls, yf, s, sum_d); + } + mmq_few_add_scaled(sum, d, sum_d); +} + +template +static __device__ __forceinline__ void mmq_few_vec_dot(const char * const (&x)[2], const mmq_few_y_frag (&yf)[ncg], float (&sum)[ncg][4]) { + if constexpr (type == GGML_TYPE_Q8_0 || type == GGML_TYPE_IQ4_NL) { + mmq_few_vec_dot_q8_0_iq4_nl(x, yf, sum); + } else if constexpr (type == GGML_TYPE_Q3_K) { + mmq_few_vec_dot_q3_K(x, yf, sum); + } else if constexpr (type == GGML_TYPE_Q4_K || type == GGML_TYPE_Q5_K) { + mmq_few_vec_dot_q45_K(x, yf, sum); + } else if constexpr (type == GGML_TYPE_Q6_K) { + mmq_few_vec_dot_q6_K(x, yf, sum); + } else if constexpr (type == GGML_TYPE_IQ3_S) { + mmq_few_vec_dot_iq3_s(x, yf, sum); + } else if constexpr (type == GGML_TYPE_IQ4_XS) { + mmq_few_vec_dot_iq4_xs(x, yf, sum); + } else { + static_assert(type == GGML_TYPE_COUNT, "unsupported type"); + } +} + +#endif // defined(CP_ASYNC_AVAILABLE) + +template +__launch_bounds__(MMQ_FEW_NWARPS*ggml_cuda_get_physical_warp_size(), 1) +static __global__ void mul_mat_q_few( + const char * x, const int4 * y_ptr, float * dst, + const int nunits, const int nrows_x, const int ncols_dst, const int64_t stride_row_x, const int stride_col_dst, + const int channel_ratio, const int64_t stride_channel_x, const int stride_channel_dst, + const int sample_ratio, const int64_t stride_sample_x, const int stride_sample_dst, const bool x_is_constant) { +#if defined(CP_ASYNC_AVAILABLE) + constexpr int nwarps = MMQ_FEW_NWARPS; + constexpr int warp_size = ggml_cuda_get_physical_warp_size(); + static_assert(warp_size == WARP_SIZE, "unsupported warp size"); + + constexpr int unit_size = mmq_few_unit_size(type); + constexpr int nrows = nmt*MMQ_FEW_NROWS; + constexpr int nunits_stage = mmq_few_nunits_stage(type, ncg, nmt); + constexpr int nstages = mmq_few_nstages(type); + constexpr bool unaligned = mmq_few_unaligned(type, nunits_stage); + constexpr int nchunks = mmq_few_nchunks(type, nunits_stage); + constexpr int sram_stride = mmq_few_sram_stride(type, nunits_stage); + constexpr int nbytes_stage = nrows*sram_stride; + constexpr int ncopies = nrows*nchunks; + static_assert(unit_size > 0, "unsupported type"); + + extern __shared__ char data_mmq_few[]; + char * ring = data_mmq_few + threadIdx.y*nstages*nbytes_stage; + + const int row0 = blockIdx.x*nrows; + const int channel_dst = blockIdx.y; + const int sample_dst = blockIdx.z; + const int nchannels = gridDim.y; + + x += int64_t(sample_dst/sample_ratio)*stride_sample_x + int64_t(channel_dst/channel_ratio)*stride_channel_x; + dst += int64_t(sample_dst)*stride_sample_dst + int64_t(channel_dst)*stride_channel_dst; + const int4 * GGML_CUDA_RESTRICT y = y_ptr + (int64_t(sample_dst)*nchannels + channel_dst)*nunits*ncg*MMQ_FEW_Q8_1_INT4; + + // No bounds check for the units, the gate makes nunits a multiple of nunits_stage. + // The extra bytes of unaligned data are inside the allocation, which ggml aligns and pads to 128 bytes. + auto load_stage = [&](const int stage, const int iu0) { + const unsigned int dst_stage = ggml_cuda_cvta_generic_to_shared(ring + stage*nbytes_stage); +#pragma unroll + for (int c0 = 0; c0 < ncopies; c0 += warp_size) { + const int c = c0 + threadIdx.x; + const int i = c / nchunks; + const int ic = c % nchunks; + if (ncopies % warp_size == 0 || c < ncopies) { + const int row = min(row0 + i, nrows_x - 1); + const char * src = x + int64_t(row)*stride_row_x + int64_t(iu0)*unit_size; + if constexpr (unaligned) { + const int off = (uintptr_t) src % 16; + if (16*ic < off + nunits_stage*unit_size) { + cp_async_cg_16<0>(dst_stage + i*sram_stride + 16*ic, src - off + 16*ic); + } + } else { + cp_async_cg_16<0>(dst_stage + i*sram_stride + 16*ic, src + 16*ic); + } + } + } + }; + + // offsets of the rows of this lane from their 16 byte boundary + int off_row[2*nmt] = {0}; + if constexpr (unaligned) { +#pragma unroll + for (int r = 0; r < 2*nmt; ++r) { + const int row = min(row0 + int(threadIdx.x)/4 + 8*r, nrows_x - 1); + off_row[r] = (uintptr_t) (x + int64_t(row)*stride_row_x) % 16; + } + } + + // Only weights, which no preceding kernel writes, are read before the PDL wait. + if (!x_is_constant) { + ggml_cuda_pdl_sync(); + } + +#if __CUDA_ARCH__ == GGML_CUDA_CC_DGX_SPARK + // DGX Spark DRAM serves the short row pieces of the stage copies slowly, so the rows of the block are first prefetched into L2 in address order. + { + const int tid = threadIdx.y*warp_size + threadIdx.x; + const int nrows_blk = min(nrows, nrows_x - row0); + const int64_t row_bytes = int64_t(nunits)*unit_size; + const bool contig = stride_row_x == row_bytes; + for (int ir = 0; ir < (contig ? 1 : nrows_blk); ++ir) { + const uintptr_t p0 = (uintptr_t) (x + int64_t(row0 + ir)*stride_row_x); + const uintptr_t p1 = p0 + (contig ? nrows_blk*row_bytes : row_bytes); + for (uintptr_t p = (p0 & ~uintptr_t(127)) + 128*tid; p < p1; p += 128*nwarps*warp_size) { + ggml_cuda_prefetch_l2((const void *) p); + } + } + } +#endif // __CUDA_ARCH__ == GGML_CUDA_CC_DGX_SPARK + + const int iu_step = nunits_stage*nwarps; + +#pragma unroll + for (int stage = 0; stage < nstages - 1; ++stage) { + const int iu0 = nunits_stage*threadIdx.y + stage*iu_step; + if (iu0 < nunits) { + load_stage(stage, iu0); + } + cp_async_commit_group(); + } + if (x_is_constant) { + ggml_cuda_pdl_sync(); + } + + auto load_y = [&](mmq_few_y_frag (&yf)[ncg], const int iu) { +#pragma unroll + for (int c = 0; c < ncg; ++c) { + mmq_few_load_y(yf[c], y + (int64_t(iu)*ncg + c)*MMQ_FEW_Q8_1_INT4); + } + }; + + // The next src1 fragments are loaded right after the MMAs that use the current ones, an earlier load is slower. + mmq_few_y_frag yf[nunits_stage][ncg]; + if (nunits_stage*threadIdx.y < nunits) { +#pragma unroll + for (int k = 0; k < nunits_stage; ++k) { + load_y(yf[k], nunits_stage*threadIdx.y + k); + } + } + + float sum[nmt][ncg][4] = {{{0.0f}}}; + + for (int iter = 0, iu0 = nunits_stage*threadIdx.y; iu0 < nunits; ++iter, iu0 += iu_step) { + const int iu_load = iu0 + (nstages - 1)*iu_step; + if (iu_load < nunits) { + load_stage((iter + nstages - 1) % nstages, iu_load); + } + cp_async_commit_group(); + + const bool has_next = iu0 + iu_step < nunits; + + cp_async_wait_group(); + ggml_cuda_syncwarp(); + + const char * xs = ring + (iter % nstages)*nbytes_stage; + const int off_stage = unaligned ? (iu0*unit_size) % 16 : 0; +#pragma unroll + for (int k = 0; k < nunits_stage; ++k) { +#pragma unroll + for (int m = 0; m < nmt; ++m) { + const char * const xr[2] = { + xs + (MMQ_FEW_NROWS*m + threadIdx.x/4 + 0)*sram_stride + (off_row[2*m + 0] + off_stage) % 16 + k*unit_size, + xs + (MMQ_FEW_NROWS*m + threadIdx.x/4 + 8)*sram_stride + (off_row[2*m + 1] + off_stage) % 16 + k*unit_size, + }; + mmq_few_vec_dot(xr, yf[k], sum[m]); + } + if (has_next) { + load_y(yf[k], iu0 + iu_step + k); + } + } + + ggml_cuda_syncwarp(); // the stage is overwritten in the next iteration + } + cp_async_wait_all(); + + ggml_cuda_pdl_lc(); + + // reduce the sums over the warps as one flat array + constexpr int nsum = nmt*ncg*4; + float * sum_flat = &sum[0][0][0]; + + float * buf_sum = (float *) data_mmq_few; + __syncthreads(); + if (threadIdx.y > 0) { +#pragma unroll + for (int i = 0; i < nsum; ++i) { + buf_sum[((threadIdx.y - 1)*nsum + i)*warp_size + threadIdx.x] = sum_flat[i]; + } + } + __syncthreads(); + if (threadIdx.y > 0) { + return; + } +#pragma unroll + for (int w = 0; w < nwarps - 1; ++w) { +#pragma unroll + for (int i = 0; i < nsum; ++i) { + sum_flat[i] += buf_sum[(w*nsum + i)*warp_size + threadIdx.x]; + } + } + +#pragma unroll + for (int m = 0; m < nmt; ++m) { +#pragma unroll + for (int c = 0; c < ncg; ++c) { +#pragma unroll + for (int l = 0; l < 4; ++l) { + const int i = row0 + MMQ_FEW_NROWS*m + tile<16, 8, int>::get_i(l); + const int j = c*MMQ_FEW_NCOLS + tile<16, 8, int>::get_j(l); + if (i < nrows_x && j < ncols_dst) { + dst[int64_t(j)*stride_col_dst + i] = sum[m][c][l]; + } + } + } + } +#else + GGML_UNUSED_VARS(x, y_ptr, dst, nunits, nrows_x, ncols_dst, stride_row_x, stride_col_dst, + channel_ratio, stride_channel_x, stride_channel_dst, + sample_ratio, stride_sample_x, stride_sample_dst, x_is_constant); + NO_DEVICE_CODE; +#endif // defined(CP_ASYNC_AVAILABLE) +} + +// ggml_is_constant (static in ggml.c) on the tensor that a view points to +static bool mmq_few_is_constant(const ggml_tensor * src0) { + const ggml_tensor * x_root = src0->view_src ? src0->view_src : src0; + return x_root->buffer && ggml_backend_buffer_get_usage(x_root->buffer) == GGML_BACKEND_BUFFER_USAGE_WEIGHTS && + !(x_root->flags & GGML_TENSOR_FLAG_PARAM); +} + +template +static void launch_mul_mat_q_few(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, + const int4 * src1_q, cudaStream_t stream) { + GGML_TENSOR_BINARY_OP_LOCALS; + + const int nunits = ne00 / QK_K; + GGML_ASSERT(nunits % mmq_few_nunits_stage(type, ncg, nmt) == 0); + + const int warp_size = ggml_cuda_info().devices[ggml_cuda_get_device()].warp_size; + const int nbytes_shared = mmq_few_nbytes_shared(type, ncg, nmt); + CUDA_SET_SHARED_MEMORY_LIMIT((mul_mat_q_few), nbytes_shared); + + const bool x_is_constant = mmq_few_is_constant(src0); + + const dim3 block_nums((ne01 + nmt*MMQ_FEW_NROWS - 1) / (nmt*MMQ_FEW_NROWS), ne12, ne13); + const dim3 block_dims(warp_size, MMQ_FEW_NWARPS, 1); + const ggml_cuda_kernel_launch_params params(block_nums, block_dims, nbytes_shared, stream); + ggml_cuda_kernel_launch(mul_mat_q_few, params, + (const char *) src0->data, src1_q, (float *) dst->data, + nunits, (int) ne01, (int) ne1, (int64_t) nb01, (int) (nb1/sizeof(float)), + (int) (ne12/ne02), (int64_t) nb02, (int) (nb2/sizeof(float)), + (int) (ne13/ne03), (int64_t) nb03, (int) (nb3/sizeof(float)), x_is_constant); +} + +static int mmq_few_ncg(const int64_t ncols) { + return (ncols + MMQ_FEW_NCOLS - 1) / MMQ_FEW_NCOLS; +} + +// With 2 column groups, 32-row tiles halve the src1 loads per src0 byte. With 3 column groups they spill registers. +static int mmq_few_nmt(const ggml_type type, const int ncg, const int64_t nrows_x) { + const int nsm = ggml_cuda_info().devices[ggml_cuda_get_device()].nsm; + return mmq_few_tall_supported(type) && ncg == 2 && nrows_x >= int64_t(nsm)*2*MMQ_FEW_NROWS ? 2 : 1; +} + +template +static void launch_mul_mat_q_few_tall(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, + const int4 * src1_q, cudaStream_t stream) { + if constexpr (mmq_few_tall_supported(type)) { + if (mmq_few_nmt(type, 2, src0->ne[1]) == 2) { + launch_mul_mat_q_few(src0, src1, dst, src1_q, stream); + return; + } + } + launch_mul_mat_q_few(src0, src1, dst, src1_q, stream); +} + +template +static void launch_mul_mat_q_few_switch_ncg(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, + const int4 * src1_q, const int ncg, cudaStream_t stream) { + switch (ncg) { + case 1: + launch_mul_mat_q_few(src0, src1, dst, src1_q, stream); + break; + case 2: + launch_mul_mat_q_few_tall(src0, src1, dst, src1_q, stream); + break; + case 3: + launch_mul_mat_q_few(src0, src1, dst, src1_q, stream); + break; + default: + GGML_ABORT("fatal error"); + } +} + +void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_BINARY_OP_LOCALS; + + GGML_ASSERT(src1->type == GGML_TYPE_F32); + GGML_ASSERT( dst->type == GGML_TYPE_F32); + GGML_ASSERT(nb00 == ggml_type_size(src0->type)); + GGML_ASSERT(nb10 == sizeof(float)); + GGML_ASSERT(nb0 == sizeof(float)); + GGML_ASSERT(ne11 <= MMQ_FEW_MAX_NCG*MMQ_FEW_NCOLS); + GGML_ASSERT(ne00 % QK_K == 0); + GGML_ASSERT(ne12 % ne02 == 0 && ne13 % ne03 == 0); + + cudaStream_t stream = ctx.stream(); + + const int nunits = ne00 / QK_K; + const int ncg = mmq_few_ncg(ne11); + + ggml_cuda_pool_alloc src1_q(ctx.pool(), int64_t(ne12)*ne13*nunits*ncg*MMQ_FEW_Q8_1_INT4); + quantize_mmq_few_q8_1_cuda((const float *) src1->data, src1_q.get(), mmq_few_ds_layout(src0->type), ne10, nb11/sizeof(float), nb12/sizeof(float), nb13/sizeof(float), + ne11, ne12, ne13, stream); + + switch (src0->type) { + case GGML_TYPE_Q8_0: + launch_mul_mat_q_few_switch_ncg(src0, src1, dst, src1_q.get(), ncg, stream); + break; + case GGML_TYPE_Q3_K: + launch_mul_mat_q_few_switch_ncg(src0, src1, dst, src1_q.get(), ncg, stream); + break; + case GGML_TYPE_Q4_K: + launch_mul_mat_q_few_switch_ncg(src0, src1, dst, src1_q.get(), ncg, stream); + break; + case GGML_TYPE_Q5_K: + launch_mul_mat_q_few_switch_ncg(src0, src1, dst, src1_q.get(), ncg, stream); + break; + case GGML_TYPE_Q6_K: + launch_mul_mat_q_few_switch_ncg(src0, src1, dst, src1_q.get(), ncg, stream); + break; + case GGML_TYPE_IQ3_S: + launch_mul_mat_q_few_switch_ncg(src0, src1, dst, src1_q.get(), ncg, stream); + break; + case GGML_TYPE_IQ4_NL: + launch_mul_mat_q_few_switch_ncg(src0, src1, dst, src1_q.get(), ncg, stream); + break; + case GGML_TYPE_IQ4_XS: + launch_mul_mat_q_few_switch_ncg(src0, src1, dst, src1_q.get(), ncg, stream); + break; + default: + GGML_ABORT("unsupported type for few-row MMQ"); + } +} + +// Min. number of src1 columns for the few-row MMQ, 0 if it is not used for this type, GPU and row length. +static int ggml_cuda_mmq_few_min_ncols(const ggml_type type, const int cc, const int64_t ne00) { +#ifdef GGML_CUDA_FORCE_CUBLAS + return 0; +#endif // GGML_CUDA_FORCE_CUBLAS + + // NVIDIA Ampere to Blackwell + if (!ampere_mma_available(cc) || cc >= GGML_CUDA_CC_RUBIN) { + return 0; + } + // on DGX Spark the kernel needs its L2 prefetch, which is only in the DGX Spark device code + if (cc == GGML_CUDA_CC_DGX_SPARK && ggml_cuda_highest_compiled_arch(cc) != GGML_CUDA_CC_DGX_SPARK) { + return 0; + } + // with fewer than 8 units of 256 values per row the warps idle, MMVQ and MMQ are better there + if (mmq_few_unit_size(type) == 0 || ne00 < 8*QK_K) { + return 0; + } + if (cc == GGML_CUDA_CC_DGX_SPARK) { // tuned on DGX Spark GB10 + return type == GGML_TYPE_IQ4_XS || type == GGML_TYPE_IQ4_NL ? 8 : 2; + } + switch (type) { // all GPUs except DGX Spark, tuned on RTX 5090 + case GGML_TYPE_Q3_K: return 3; + case GGML_TYPE_Q5_K: return 3; + case GGML_TYPE_Q4_K: return 4; + case GGML_TYPE_IQ4_NL: return 4; + case GGML_TYPE_Q6_K: return 4; + case GGML_TYPE_Q8_0: return 5; + case GGML_TYPE_IQ3_S: return 5; + case GGML_TYPE_IQ4_XS: return 6; + default: return 0; + } +} + +bool ggml_cuda_should_use_mmq_few(const ggml_tensor * src0, const ggml_tensor * src1, const int cc) { + const int min_ncols = ggml_cuda_mmq_few_min_ncols(src0->type, cc, src0->ne[0]); + if (min_ncols == 0 || src1->ne[1] < min_ncols || src1->ne[1] > MMQ_FEW_MAX_NCG*MMQ_FEW_NCOLS) { + return false; + } + // the row must hold a whole number of ring stages of the launched kernel + const int ncg = mmq_few_ncg(src1->ne[1]); + const int nmt = mmq_few_nmt(src0->type, ncg, src0->ne[1]); + const int nunits_stage = mmq_few_nunits_stage(src0->type, ncg, nmt); + if (src0->ne[0] % (nunits_stage*QK_K) != 0) { + return false; + } + // unaligned data needs the alignment of the decoder loads + const int x_alignment = mmq_few_unaligned(src0->type, nunits_stage) ? (ggml_type_size(src0->type) % 4 == 0 ? 4 : 2) : 16; + return ggml_cuda_is_aligned(src0, x_alignment) && ggml_cuda_is_aligned(src1, 16); +} + +#else // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) + +void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_UNUSED_VARS(ctx, src0, src1, dst); + GGML_ABORT("few-row MMQ is not supported on HIP or MUSA"); +} + +bool ggml_cuda_should_use_mmq_few(const ggml_tensor * src0, const ggml_tensor * src1, const int cc) { + GGML_UNUSED_VARS(src0, src1, cc); + return false; +} + +#endif // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) diff --git a/ggml/src/ggml-cuda/mmq-few.cuh b/ggml/src/ggml-cuda/mmq-few.cuh new file mode 100644 index 000000000000..016834998f72 --- /dev/null +++ b/ggml/src/ggml-cuda/mmq-few.cuh @@ -0,0 +1,7 @@ +#pragma once + +#include "common.cuh" + +bool ggml_cuda_should_use_mmq_few(const ggml_tensor * src0, const ggml_tensor * src1, int cc); + +void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); diff --git a/ggml/src/ggml-cuda/mmq-load-tiles.cuh b/ggml/src/ggml-cuda/mmq-load-tiles.cuh index da0e11f2c0f5..80f54703b6f0 100644 --- a/ggml/src/ggml-cuda/mmq-load-tiles.cuh +++ b/ggml/src/ggml-cuda/mmq-load-tiles.cuh @@ -629,6 +629,13 @@ template static __device__ __forceinline_ } } +// The 6-bit scales 4*ksc .. 4*ksc + 3 of a q3_K block, minus 32, as int8. +static __device__ __forceinline__ int unpack_scales_q3_K(const uint8_t * scales, const int ksc) { + const int sc_low = (get_int_b2(scales, ksc % 2) >> (4 * (ksc / 2))) & 0x0F0F0F0F; + const int sc_high = ((get_int_b2(scales, 2) >> (2 * ksc)) << 4) & 0x30303030; + return __vsub4(sc_low | sc_high, 0x20202020); +} + template static __device__ __forceinline__ void ggml_cuda_mmq_load_tiles_q3_K( const char * __restrict__ x, const char * __restrict__ x_gate, int * __restrict__ x_tile, const int kbx0, const int i_max, const int stride) { GGML_UNUSED(x_gate); @@ -695,15 +702,7 @@ template static __device__ __forceinline_ const int ksc = threadIdx.x % 4; - const int ksc_low = ksc % (QI3_K/8); - const int shift_low = 4 * (ksc / (QI3_K/8)); - const int sc_low = (get_int_b2(bxi->scales, ksc_low) >> shift_low) & 0x0F0F0F0F; - - const int ksc_high = QI3_K/8; - const int shift_high = 2 * ksc; - const int sc_high = ((get_int_b2(bxi->scales, ksc_high) >> shift_high) << 4) & 0x30303030; - - const int sc = __vsub4(sc_low | sc_high, 0x20202020); + const int sc = unpack_scales_q3_K(bxi->scales, ksc); #if defined(AMD_MFMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) const int8_t * sc8 = (const int8_t *) ≻ diff --git a/ggml/src/ggml-cuda/mmq.cu b/ggml/src/ggml-cuda/mmq.cu index 5cd485833ce3..148b69c42a92 100644 --- a/ggml/src/ggml-cuda/mmq.cu +++ b/ggml/src/ggml-cuda/mmq.cu @@ -169,21 +169,27 @@ void ggml_cuda_mul_mat_q( GGML_ASSERT(!ids || ids->type == GGML_TYPE_I32); // Optional, used for batched GGML_MUL_MAT_ID. // Fused gate/up/GLU: src0 is the up weight, dst the GLU output. + // Fused scale (no gate): dst is the MUL that applies the weight scale to the MUL_MAT. const ggml_tensor * gate = fusion ? fusion->gate : nullptr; ggml_cuda_mm_fusion_args_device fusion_device = {}; if (fusion) { - GGML_ASSERT(gate && !fusion->x_bias && !fusion->gate_bias && !fusion->x_scale == !fusion->gate_scale); - GGML_ASSERT(gate->type == src0->type && ggml_are_same_shape(gate, src0) && ggml_are_same_stride(gate, src0)); + GGML_ASSERT(!fusion->x_bias && !fusion->gate_bias); // NVFP4 weight scales (only applied for NVFP4): one value per tensor, or one per expert with ids. for (const ggml_tensor * scale : { fusion->x_scale, fusion->gate_scale }) { GGML_ASSERT(!scale || (src0->type == GGML_TYPE_NVFP4 && scale->type == GGML_TYPE_F32 && ggml_is_contiguous(scale) && ggml_nelements(scale) == (ids ? src0->ne[2] : 1))); } - fusion_device.gate = gate->data; - fusion_device.x_scale = fusion->x_scale ? fusion->x_scale->data : nullptr; - fusion_device.gate_scale = fusion->gate_scale ? fusion->gate_scale->data : nullptr; - fusion_device.glu_op = fusion->glu_op; - fusion_device.glu_limit = fusion->glu_limit; + if (gate) { + GGML_ASSERT(!fusion->x_scale == !fusion->gate_scale); + GGML_ASSERT(gate->type == src0->type && ggml_are_same_shape(gate, src0) && ggml_are_same_stride(gate, src0)); + fusion_device.gate = gate->data; + fusion_device.gate_scale = fusion->gate_scale ? fusion->gate_scale->data : nullptr; + fusion_device.glu_op = fusion->glu_op; + fusion_device.glu_limit = fusion->glu_limit; + } else { + GGML_ASSERT(!fusion->gate_scale && fusion->x_scale); + } + fusion_device.x_scale = fusion->x_scale ? fusion->x_scale->data : nullptr; } GGML_TENSOR_BINARY_OP_LOCALS; @@ -231,8 +237,8 @@ void ggml_cuda_mul_mat_q( const bool fallback = ggml_cuda_mmq_needs_fallback(ne01); - // With fusion dst is the GLU output, not a MUL_MAT; the src1 precision requested by both fused MUL_MATs is in the fusion args. - const ggml_prec prec_src1 = ggml_cuda_mmq_get_prec_src1(src0->type, gate ? fusion->prec_src1 : ggml_prec_get_src(dst, 1), cc); + // With fusion dst is the GLU output or the scale node, not a MUL_MAT; the src1 precision requested by the fused MUL_MATs is in the fusion args. + const ggml_prec prec_src1 = ggml_cuda_mmq_get_prec_src1(src0->type, fusion ? fusion->prec_src1 : ggml_prec_get_src(dst, 1), cc); const bool use_native_fp4 = prec_src1 == GGML_PREC_Q4; const size_t y_block_size = use_native_fp4 ? sizeof(block_fp4_mmq) : sizeof(block_q8_1_mmq); diff --git a/ggml/src/ggml-cuda/mmq.cuh b/ggml/src/ggml-cuda/mmq.cuh index 9ff7dff5a3cb..c6af3cbae6bc 100644 --- a/ggml/src/ggml-cuda/mmq.cuh +++ b/ggml/src/ggml-cuda/mmq.cuh @@ -465,7 +465,11 @@ template static __de const float * __restrict__ sum, const int32_t * __restrict__ ids_dst, float * __restrict__ dst, const float * __restrict__ y_scale, const int stride, const int i_max, const int j_sup, const ggml_glu_op glu_op, const float glu_limit, const float * __restrict__ x_scale, const float * __restrict__ gate_scale) { - GGML_UNUSED_VARS(glu_op, glu_limit, x_scale, gate_scale); + GGML_UNUSED_VARS(glu_op, glu_limit, gate_scale); + + // NVFP4 weight scale of a fused MUL (per tensor, or of the expert of this tile), 1 without. + const float scale = type == GGML_TYPE_NVFP4 && x_scale ? *x_scale : 1.0f; + constexpr int warp_size = ggml_cuda_get_physical_warp_size(); constexpr int nwarps = ggml_cuda_mmq_get_nthreads(type, J, fallback, prec_src1) / warp_size; constexpr int I = ggml_cuda_mmq_get_I(type, J, fallback, prec_src1); @@ -489,11 +493,15 @@ template static __de continue; } - if (y_scale_used) { - dst[ids_dst[j]*stride + i] = y_scale[j] * sum[(j0/nwarps) * (I/warp_size) + i0/warp_size]; + float value = sum[(j0/nwarps) * (I/warp_size) + i0/warp_size]; + if constexpr (type == GGML_TYPE_NVFP4) { + if (y_scale_used) { + value *= y_scale[j]; + } } else { - dst[ids_dst[j]*stride + i] = sum[(j0/nwarps) * (I/warp_size) + i0/warp_size]; + GGML_UNUSED(y_scale_used); } + dst[ids_dst[j]*stride + i] = value * scale; } } } @@ -520,9 +528,9 @@ static __device__ __forceinline__ void ggml_cuda_mmq_write_back_mma( const bool y_scale_used = type == GGML_TYPE_NVFP4 && y_scale != nullptr; - // Fused NVFP4: load the weight scales once, 1 without scales. + // NVFP4: load the weight scales once, 1 without scales. Without fusion x_scale is the scale of a fused MUL. constexpr bool fused_nvfp4 = has_fusion && type == GGML_TYPE_NVFP4; - const float scale_up = fused_nvfp4 && x_scale ? *x_scale : 1.0f; + const float scale_up = type == GGML_TYPE_NVFP4 && x_scale ? *x_scale : 1.0f; const float scale_gate = fused_nvfp4 && gate_scale ? *gate_scale : 1.0f; #pragma unroll @@ -556,10 +564,16 @@ static __device__ __forceinline__ void ggml_cuda_mmq_write_back_mma( gate *= scale_gate; } dst[ids_dst[j]*stride + i] = ggml_cuda_op_glu_single(glu_op, gate, up, glu_limit); - } else if (y_scale_used) { - dst[ids_dst[j]*stride + i] = y_scale[j] * sum[(j0/tile_C::J + n)*tile_C::ne + l]; } else { - dst[ids_dst[j]*stride + i] = sum[(j0/tile_C::J + n)*tile_C::ne + l]; + float value = sum[(j0/tile_C::J + n)*tile_C::ne + l]; + if constexpr (type == GGML_TYPE_NVFP4) { + if (y_scale_used) { + value *= y_scale[j]; + } + } else { + GGML_UNUSED(y_scale_used); + } + dst[ids_dst[j]*stride + i] = value * scale_up; } } } @@ -1316,10 +1330,12 @@ static __global__ void mul_mat_q( const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + fastdiv(zt, channel_ratio)*stride_channel_x + it*I*stride_row_x; + const float * x_scale_tile = x_scale && ids_dst ? x_scale + zt : x_scale; + constexpr bool fixup = false; // All but (potentially) the last iterations write their data to dst rather than the fixup buffer. mul_mat_q_process_tile (x, x_gate, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, y_scale_tile, - glu_op, glu_limit, x_scale, gate_scale, stride_row_x, ncols_y, stride_col_dst, + glu_op, glu_limit, x_scale_tile, gate_scale, stride_row_x, ncols_y, stride_col_dst, tile_x_i_max, col_high - col_low, kb0_start, kb0_stop); kbc += blocks_per_ne00.z; @@ -1390,10 +1406,12 @@ static __global__ void mul_mat_q( const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + fastdiv(zt, channel_ratio)*stride_channel_x + it*I*stride_row_x; + const float * x_scale_tile = x_scale && ids_dst ? x_scale + zt : x_scale; + constexpr bool fixup = true; // Last index writes its data to fixup buffer to avoid data races with other blocks. mul_mat_q_process_tile (x, x_gate, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, y_scale_tile, - glu_op, glu_limit, x_scale, gate_scale, stride_row_x, ncols_y, stride_col_dst, + glu_op, glu_limit, x_scale_tile, gate_scale, stride_row_x, ncols_y, stride_col_dst, tile_x_i_max, col_high - col_low, kb0_start, kb0_stop); } @@ -1511,6 +1529,10 @@ static __global__ void mul_mat_q_stream_k_fixup( const int col_high = tsj.col_high; const int j_sup = col_high - col_low; + if (j_sup <= 0) { + return; + } + for (int j = threadIdx.y*warp_size + threadIdx.x; j < J; j += nwarps*warp_size) { ids_dst_shared[j] = ids_dst[col_low + j]; } diff --git a/ggml/src/ggml-cuda/mmvq.cu b/ggml/src/ggml-cuda/mmvq.cu index 42d437a6c9c5..86f932644b05 100644 --- a/ggml/src/ggml-cuda/mmvq.cu +++ b/ggml/src/ggml-cuda/mmvq.cu @@ -29,10 +29,6 @@ static constexpr __host__ __device__ bool mmvq_should_prefetch(ggml_type type) { return false; } } - -static __device__ __forceinline__ void mmvq_prefetch_l2(const void * p) { - asm volatile("prefetch.global.L2 [%0];" :: "l"(p)); -} #endif typedef float (*vec_dot_q_cuda_t)(const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & kbx, const int & iqs); @@ -823,10 +819,10 @@ static __global__ void mul_mat_vec_q( #pragma unroll for (int i = 0; i < rows_per_cuda_block; ++i) { const size_t off = (size_t)(kbx_offset + i*stride_row_x + kbx_pf) * ggml_cuda_type_traits::bs; - mmvq_prefetch_l2((const char *) vx + off); + ggml_cuda_prefetch_l2((const char *) vx + off); if constexpr (has_fusion) { if (use_gate) { - mmvq_prefetch_l2((const char *) vgate + off); + ggml_cuda_prefetch_l2((const char *) vgate + off); } } } diff --git a/ggml/src/ggml-cuda/quantize.cu b/ggml/src/ggml-cuda/quantize.cu index 4ec8b774b0b2..2acf1f6d0e21 100644 --- a/ggml/src/ggml-cuda/quantize.cu +++ b/ggml/src/ggml-cuda/quantize.cu @@ -600,6 +600,81 @@ void quantize_mmq_q8_1_cuda( } } +// Each thread quantizes 4 values of one column, see quantize.cuh for the layout. +template +static __global__ void quantize_mmq_few_q8_1( + const float * x_ptr, void * vy_ptr, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03, + const int ne1, const int ne2) { + ggml_cuda_pdl_lc(); + const float * GGML_CUDA_RESTRICT x = x_ptr; + int4 * GGML_CUDA_RESTRICT vy = (int4 *) vy_ptr; + const int64_t i0 = ((int64_t)blockDim.x*blockIdx.y + threadIdx.x)*4; + + if (i0 >= ne00) { + return; + } + ggml_cuda_pdl_sync(); + + const int64_t i2 = blockIdx.z % ne2; + const int64_t i3 = blockIdx.z / ne2; + const float4 xi = (int) blockIdx.x < ne1 ? *(const float4 *) (x + i3*s03 + i2*s02 + blockIdx.x*s01 + i0) : make_float4(0.0f, 0.0f, 0.0f, 0.0f); + + // the 32 values of a sub-block are held by 8 threads + float amax = fmaxf(fmaxf(fabsf(xi.x), fabsf(xi.y)), fmaxf(fabsf(xi.z), fabsf(xi.w))); + amax = warp_reduce_max<8>(amax); + + const float d_inv = 127.0f / amax; + char4 q; + q.x = roundf(xi.x*d_inv); + q.y = roundf(xi.y*d_inv); + q.z = roundf(xi.z*d_inv); + q.w = roundf(xi.w*d_inv); + const float d = 1.0f / d_inv; + + // as in quantize_mmq_q8_1: the sum of the quantized values; the int warp_reduce_sum reduces the whole warp on Ampere+ + [[maybe_unused]] float sum = 0.0f; + if constexpr (ds_layout != MMQ_Q8_1_DS_LAYOUT_D4) { + sum = d*warp_reduce_sum<8>(float(q.x + q.y + q.z + q.w)); + } + + const int s = i0 % QK_K / QK8_1; // sub-block + const int k = i0 % QK8_1; // first value in sub-block + const int g = blockIdx.x % MMQ_FEW_NCOLS; // column in group + int4 * yg = vy + ((blockIdx.z*(ne00/QK_K) + i0/QK_K)*(gridDim.x/MMQ_FEW_NCOLS) + blockIdx.x/MMQ_FEW_NCOLS)*MMQ_FEW_Q8_1_INT4; + ((int *) (yg + (s/2)*WARP_SIZE + 4*g + (k % 16)/4))[2*(s % 2) + k/16] = *(const int *) &q; + if (k == 0) { + int4 * ds = yg + 4*WARP_SIZE + 4*(g/2) + s/2; + if constexpr (ds_layout == MMQ_Q8_1_DS_LAYOUT_D4) { + ((float *) ds)[2*(s % 2) + g % 2] = d; + } else { + ((half2 *) ds)[2*(s % 2) + g % 2] = make_half2(d, sum); + } + } +} + +void quantize_mmq_few_q8_1_cuda( + const float * x, void * vy, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03, + const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) { + GGML_ASSERT(ne00 % QK_K == 0); + + const int64_t block_num_y = (ne00 + 4*CUDA_QUANTIZE_BLOCK_SIZE_MMQ - 1) / (4*CUDA_QUANTIZE_BLOCK_SIZE_MMQ); + const dim3 num_blocks(GGML_PAD(ne1, MMQ_FEW_NCOLS), block_num_y, ne2*ne3); + const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1); + const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(num_blocks, block_size, 0, stream); + switch (ds_layout) { + case MMQ_Q8_1_DS_LAYOUT_D4: + ggml_cuda_kernel_launch(quantize_mmq_few_q8_1, launch_params, + x, vy, ne00, s01, s02, s03, (int) ne1, (int) ne2); + break; + case MMQ_Q8_1_DS_LAYOUT_DS4: + ggml_cuda_kernel_launch(quantize_mmq_few_q8_1, launch_params, + x, vy, ne00, s01, s02, s03, (int) ne1, (int) ne2); + break; + default: + GGML_ABORT("fatal error"); + } +} + // scatter=true reuses the quant kernel: grid over tokens, ids = inverse map (token slot -> compact row) void quantize_scatter_mmq_q8_1_cuda( const float * x, const int32_t * ids_src1_inv, void * vy, const ggml_type type_src0, diff --git a/ggml/src/ggml-cuda/quantize.cuh b/ggml/src/ggml-cuda/quantize.cuh index 9ae72ee44ead..11720ef93bad 100644 --- a/ggml/src/ggml-cuda/quantize.cuh +++ b/ggml/src/ggml-cuda/quantize.cuh @@ -21,6 +21,17 @@ void quantize_mmq_q8_1_cuda( ggml_type type_src0, int64_t ne00, int64_t s01, int64_t s02, int64_t s03, int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3, cudaStream_t stream); +// src1 of the few-row MMQ in the layout of the MMA fragments. Per channel, 256 values and group of MMQ_FEW_NCOLS columns: +// qs: int4[4][32], [j][lane] holds the B fragments of sub-blocks 2j and 2j+1 of lane (g, t): the values [4t, 4t + 4) and [16 + 4t, 16 + 4t + 4) of column g. +// ds: int4[4][4], [t][j] holds d (D4, float) or (d, sum) (DS4, half2) of the columns 2t and 2t+1 for sub-block 2j, then 2j+1. +// The column groups of a unit are adjacent, columns beyond ne1 are zero. +static constexpr int MMQ_FEW_NCOLS = 8; // src1 columns per column group +static constexpr int MMQ_FEW_Q8_1_INT4 = 4*WARP_SIZE + 4*4; // int4 per 256 values and column group + +void quantize_mmq_few_q8_1_cuda( + const float * x, void * vy, mmq_q8_1_ds_layout ds_layout, int64_t ne00, int64_t s01, int64_t s02, int64_t s03, + int64_t ne1, int64_t ne2, int64_t ne3, cudaStream_t stream); + void quantize_mmq_fp4_cuda(const float * x, const int32_t * ids, void * vy, diff --git a/ggml/src/ggml-cuda/vendors/hip.h b/ggml/src/ggml-cuda/vendors/hip.h index 12e1b5c3ce7c..f99618fcf680 100644 --- a/ggml/src/ggml-cuda/vendors/hip.h +++ b/ggml/src/ggml-cuda/vendors/hip.h @@ -43,6 +43,9 @@ #define cublasHandle_t hipblasHandle_t #define cublasSetMathMode(handle, mode) CUBLAS_STATUS_SUCCESS #define cublasSetStream hipblasSetStream +#if HIP_VERSION >= 70000000 +#define cublasSetWorkspace hipblasSetWorkspace +#endif // HIP_VERSION >= 70000000 #define cublasSgemm hipblasSgemm #define cublasSgemmBatched hipblasSgemmBatched #define cublasSgemmStridedBatched hipblasSgemmStridedBatched diff --git a/ggml/src/ggml-hexagon/ggml-hexagon.cpp b/ggml/src/ggml-hexagon/ggml-hexagon.cpp index c38d0005c1d9..03da443c8318 100644 --- a/ggml/src/ggml-hexagon/ggml-hexagon.cpp +++ b/ggml/src/ggml-hexagon/ggml-hexagon.cpp @@ -3428,6 +3428,10 @@ static void ggml_hexagon_init(ggml_backend_reg * reg) { "please update hexagon_type to match ggml_type"); static_assert((unsigned int) HTP_TYPE_Q4_1 == (unsigned int) GGML_TYPE_Q4_1, "please update hexagon_type to match ggml_type"); + static_assert((unsigned int) HTP_TYPE_Q5_0 == (unsigned int) GGML_TYPE_Q5_0, + "please update hexagon_type to match ggml_type"); + static_assert((unsigned int) HTP_TYPE_Q5_1 == (unsigned int) GGML_TYPE_Q5_1, + "please update hexagon_type to match ggml_type"); static_assert((unsigned int) HTP_TYPE_Q8_0 == (unsigned int) GGML_TYPE_Q8_0, "please update hexagon_type to match ggml_type"); static_assert((unsigned int) HTP_TYPE_MXFP4 == (unsigned int) GGML_TYPE_MXFP4, diff --git a/ggml/src/ggml-hexagon/htp-kparams.cpp b/ggml/src/ggml-hexagon/htp-kparams.cpp index 2fbd419ac152..8c75be289ba4 100644 --- a/ggml/src/ggml-hexagon/htp-kparams.cpp +++ b/ggml/src/ggml-hexagon/htp-kparams.cpp @@ -953,6 +953,8 @@ static bool htp_matmul_check_types( case GGML_TYPE_Q2_0: case GGML_TYPE_Q4_0: case GGML_TYPE_Q4_1: + case GGML_TYPE_Q5_0: + case GGML_TYPE_Q5_1: case GGML_TYPE_Q8_0: case GGML_TYPE_IQ4_NL: case GGML_TYPE_MXFP4: @@ -995,6 +997,8 @@ static bool htp_matmul_check_types( case GGML_TYPE_Q2_0: case GGML_TYPE_Q4_0: case GGML_TYPE_Q4_1: + case GGML_TYPE_Q5_0: + case GGML_TYPE_Q5_1: case GGML_TYPE_Q8_0: case GGML_TYPE_IQ4_NL: case GGML_TYPE_MXFP4: diff --git a/ggml/src/ggml-hexagon/htp-repack.cpp b/ggml/src/ggml-hexagon/htp-repack.cpp index d2e3df2cf4b4..b5413791c183 100644 --- a/ggml/src/ggml-hexagon/htp-repack.cpp +++ b/ggml/src/ggml-hexagon/htp-repack.cpp @@ -15,7 +15,7 @@ # include #endif -// --- 4-bit block-32 nibble helpers (shared by Q4_0, IQ4_NL, Q4_1, MXFP4) --- +// --- 4-bit block-32 nibble helpers (shared by Q4_0, IQ4_NL, Q4_1, Q5_0, Q5_1, MXFP4) --- static inline void unpack_nibbles_32(uint8_t * dst, const uint8_t * qs) { for (unsigned int i = 0; i < 16; ++i) { @@ -48,6 +48,28 @@ static inline void transpose_tile_to_nibbles(uint8_t tile_quants[32][32], const } } +// 5th-bit plane of one row (qh bit k = quant k), same bit layout as the Q5_K plane +static inline void pack_q5_plane(uint8_t * plane, int row, uint32_t qh) { + for (int c = 0; c < 4; c++) { + uint32_t v = 0; + for (int i = 0; i < 4; i++) { + v |= ((qh >> (8 * i + 2 * c)) & 3) << (2 * i); + } + plane[c * 32 + row] = (uint8_t) v; + } +} + +static inline uint32_t unpack_q5_plane(const uint8_t * plane, int row) { + uint32_t qh = 0; + for (int c = 0; c < 4; c++) { + const uint32_t v = plane[c * 32 + row]; + for (int i = 0; i < 4; i++) { + qh |= ((v >> (2 * i)) & 3) << (8 * i + 2 * c); + } + } + return qh; +} + #if defined(__ARM_NEON) || defined(__aarch64__) static void repack_neon_transpose8x8(const uint8x8_t rows[8], uint8x8_t columns[8]) { const uint8x8x2_t t0 = vtrn_u8(rows[0], rows[1]); @@ -433,7 +455,7 @@ static void unpack_from_tiled_grid_32(void * data, const ggml_tensor * t, size_t } } -// --- Block-32 Quantized Types (Q4_0, IQ4_NL, Q4_1, Q8_0, MXFP4) --- +// --- Block-32 Quantized Types (Q4_0, IQ4_NL, Q4_1, Q5_0, Q5_1, Q8_0, MXFP4) --- static void repack_q4_0_tiled(ggml_tensor * t, const void * data, size_t offset, size_t size) { repack_to_tiled_grid_32(t, data, offset, size, HTP_TENSOR_TILE_SIZE_Q4_0, @@ -546,6 +568,141 @@ static void repack_tiled_q4_1(void * data, const ggml_tensor * t, size_t offset, }); } +static void repack_q5_0_tiled(ggml_tensor * t, const void * data, size_t offset, size_t size) { + repack_to_tiled_grid_32(t, data, offset, size, HTP_TENSOR_TILE_SIZE_Q5_0, + [](uint8_t * tile_dst, const block_q5_0 * src_slice, int64_t ne0, int64_t ne1, int64_t row_stride, int ct, int kt) { + uint8_t * plane_dst = tile_dst + 512; + ggml_half * scale_dst = (ggml_half *) (tile_dst + 640); +#if defined(__ARM_NEON) || defined(__aarch64__) + if (ct * 32 + 32 <= ne1 && kt < ne0 / 32) { + for (int row0 = 0; row0 < 32; row0 += 8) { + const uint8_t * qs[8]; + for (int rr = 0; rr < 8; ++rr) { + qs[rr] = src_slice[(ct * 32 + row0 + rr) * row_stride + kt].qs; + } + repack_neon_4bit_rows(qs, tile_dst, row0); + } + + for (int row = 0; row < 32; ++row) { + const block_q5_0 & src_block = src_slice[(ct * 32 + row) * row_stride + kt]; + uint32_t qh; + memcpy(&qh, src_block.qh, sizeof(qh)); + pack_q5_plane(plane_dst, row, ~qh); + scale_dst[row] = src_block.d; + } + return; + } +#endif + uint8_t tile_quants[32][32]; + for (int row = 0; row < 32; row++) { + const int64_t r = ct * 32 + row; + if (r < ne1 && kt < ne0 / 32) { + const block_q5_0 & b = src_slice[r * row_stride + kt]; + unpack_nibbles_32(tile_quants[row], b.qs); + uint32_t qh; + memcpy(&qh, b.qh, sizeof(qh)); + pack_q5_plane(plane_dst, row, ~qh); + scale_dst[row] = b.d; + } else { + memset(tile_quants[row], 0, 32); + pack_q5_plane(plane_dst, row, 0); + scale_dst[row] = 0; + } + } + transpose_nibbles_to_tile(tile_dst, tile_quants); + }); +} + +static void repack_tiled_q5_0(void * data, const ggml_tensor * t, size_t offset, size_t size) { + unpack_from_tiled_grid_32(data, t, offset, size, HTP_TENSOR_TILE_SIZE_Q5_0, + [](block_q5_0 * dst_slice, const uint8_t * tile_src, int64_t ne0, int64_t start_row, int64_t end_row, int64_t row_stride, int ct, int kt) { + uint8_t tile_quants[32][32]; + transpose_tile_to_nibbles(tile_quants, tile_src); + const uint8_t * plane_src = tile_src + 512; + const ggml_half * scale_src = (const ggml_half *) (tile_src + 640); + for (int row = 0; row < 32; row++) { + const int64_t r = ct * 32 + row; + if (r >= start_row && r < end_row && kt < ne0 / 32) { + block_q5_0 & b = dst_slice[(r - start_row) * row_stride + kt]; + pack_nibbles_32(b.qs, tile_quants[row]); + const uint32_t qh = ~unpack_q5_plane(plane_src, row); + memcpy(b.qh, &qh, sizeof(qh)); + b.d = scale_src[row]; + } + } + }); +} + +// Q5_1 uses the Q5_K tile layout +static void repack_q5_1_tiled(ggml_tensor * t, const void * data, size_t offset, size_t size) { + repack_to_tiled_grid_32(t, data, offset, size, HTP_TENSOR_TILE_SIZE_Q5_1, + [](uint8_t * tile_dst, const block_q5_1 * src_slice, int64_t ne0, int64_t ne1, int64_t row_stride, int ct, int kt) { + ggml_half * scale_dst = (ggml_half *) (tile_dst + 512); + uint8_t * plane_dst = tile_dst + 640; +#if defined(__ARM_NEON) || defined(__aarch64__) + if (ct * 32 + 32 <= ne1 && kt < ne0 / 32) { + for (int row0 = 0; row0 < 32; row0 += 8) { + const uint8_t * qs[8]; + for (int rr = 0; rr < 8; ++rr) { + qs[rr] = src_slice[(ct * 32 + row0 + rr) * row_stride + kt].qs; + } + repack_neon_4bit_rows(qs, tile_dst, row0); + } + + for (int row = 0; row < 32; ++row) { + const block_q5_1 & src_block = src_slice[(ct * 32 + row) * row_stride + kt]; + uint32_t qh; + memcpy(&qh, src_block.qh, sizeof(qh)); + pack_q5_plane(plane_dst, row, qh); + scale_dst[2 * row + 0] = src_block.d; + scale_dst[2 * row + 1] = src_block.m; + } + return; + } +#endif + uint8_t tile_quants[32][32]; + for (int row = 0; row < 32; row++) { + const int64_t r = ct * 32 + row; + if (r < ne1 && kt < ne0 / 32) { + const block_q5_1 & b = src_slice[r * row_stride + kt]; + unpack_nibbles_32(tile_quants[row], b.qs); + uint32_t qh; + memcpy(&qh, b.qh, sizeof(qh)); + pack_q5_plane(plane_dst, row, qh); + scale_dst[2 * row + 0] = b.d; + scale_dst[2 * row + 1] = b.m; + } else { + memset(tile_quants[row], 0, 32); + pack_q5_plane(plane_dst, row, 0); + scale_dst[2 * row + 0] = 0; + scale_dst[2 * row + 1] = 0; + } + } + transpose_nibbles_to_tile(tile_dst, tile_quants); + }); +} + +static void repack_tiled_q5_1(void * data, const ggml_tensor * t, size_t offset, size_t size) { + unpack_from_tiled_grid_32(data, t, offset, size, HTP_TENSOR_TILE_SIZE_Q5_1, + [](block_q5_1 * dst_slice, const uint8_t * tile_src, int64_t ne0, int64_t start_row, int64_t end_row, int64_t row_stride, int ct, int kt) { + uint8_t tile_quants[32][32]; + transpose_tile_to_nibbles(tile_quants, tile_src); + const ggml_half * scale_src = (const ggml_half *) (tile_src + 512); + const uint8_t * plane_src = tile_src + 640; + for (int row = 0; row < 32; row++) { + const int64_t r = ct * 32 + row; + if (r >= start_row && r < end_row && kt < ne0 / 32) { + block_q5_1 & b = dst_slice[(r - start_row) * row_stride + kt]; + pack_nibbles_32(b.qs, tile_quants[row]); + const uint32_t qh = unpack_q5_plane(plane_src, row); + memcpy(b.qh, &qh, sizeof(qh)); + b.d = scale_src[2 * row + 0]; + b.m = scale_src[2 * row + 1]; + } + } + }); +} + static void repack_mxfp4_tiled(ggml_tensor * t, const void * data, size_t offset, size_t size) { repack_to_tiled_grid_32(t, data, offset, size, HTP_TENSOR_TILE_SIZE_MXFP4, [](uint8_t * tile_dst, const block_mxfp4 * src_slice, int64_t ne0, int64_t ne1, int64_t row_stride, int ct, int kt) { @@ -1538,6 +1695,12 @@ void htp_repack_tensor_tiled(ggml_tensor * tensor, const void * data, size_t siz case GGML_TYPE_Q4_1: repack_q4_1_tiled(tensor, data, 0, size); break; + case GGML_TYPE_Q5_0: + repack_q5_0_tiled(tensor, data, 0, size); + break; + case GGML_TYPE_Q5_1: + repack_q5_1_tiled(tensor, data, 0, size); + break; case GGML_TYPE_Q8_0: repack_q8_0_tiled(tensor, data, 0, size); break; @@ -1593,6 +1756,12 @@ void htp_unpack_tensor_tiled(void * data, const ggml_tensor * tensor, size_t off case GGML_TYPE_Q4_1: repack_tiled_q4_1(data, tensor, offset, size); break; + case GGML_TYPE_Q5_0: + repack_tiled_q5_0(data, tensor, offset, size); + break; + case GGML_TYPE_Q5_1: + repack_tiled_q5_1(data, tensor, offset, size); + break; case GGML_TYPE_Q8_0: repack_tiled_q8_0(data, tensor, offset, size); break; diff --git a/ggml/src/ggml-hexagon/htp-repack.h b/ggml/src/ggml-hexagon/htp-repack.h index f3206bc87632..5b71f9c5aae1 100644 --- a/ggml/src/ggml-hexagon/htp-repack.h +++ b/ggml/src/ggml-hexagon/htp-repack.h @@ -10,6 +10,7 @@ static inline bool htp_is_tiled_weight_type(enum ggml_type type) { return type == GGML_TYPE_Q1_0 || type == GGML_TYPE_Q2_0 || type == GGML_TYPE_Q4_0 || type == GGML_TYPE_Q4_1 || + type == GGML_TYPE_Q5_0 || type == GGML_TYPE_Q5_1 || type == GGML_TYPE_MXFP4 || type == GGML_TYPE_IQ4_NL || type == GGML_TYPE_Q8_0 || type == GGML_TYPE_Q6_K || type == GGML_TYPE_Q2_K || type == GGML_TYPE_Q3_K || diff --git a/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled.h b/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled.h index 590167492f1f..a828012dd7fc 100644 --- a/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled.h +++ b/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled.h @@ -647,6 +647,106 @@ static void dequantize_tiled_weight_to_fp16_task_q5_k( } } +static void dequantize_tiled_weight_to_fp16_task_q5_0( + const tiled_dequantize_state_t *state, + uint32_t start_tile, uint32_t end_tile) { + + const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F); + + for (uint32_t t = start_tile; t < end_tile; t++) { + const uint8_t * tile_src = state->src + t * state->aligned_tile_size; + __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS; + + HVX_Vector v_sc = hvx_vmem(tile_src + 640); + HVX_Vector v_scale_duplicated = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); + + // Load all 4 groups in parallel + HVX_Vector vq0 = hvx_vmem(tile_src + 0 * 128); + HVX_Vector vq1 = hvx_vmem(tile_src + 1 * 128); + HVX_Vector vq2 = hvx_vmem(tile_src + 2 * 128); + HVX_Vector vq3 = hvx_vmem(tile_src + 3 * 128); + + // Nibble extraction + HVX_Vector v_lo0 = Q6_V_vand_VV(vq0, mask_h4); + HVX_Vector v_hi0 = Q6_Vub_vlsr_VubR(vq0, 4); + HVX_Vector v_lo1 = Q6_V_vand_VV(vq1, mask_h4); + HVX_Vector v_hi1 = Q6_Vub_vlsr_VubR(vq1, 4); + HVX_Vector v_lo2 = Q6_V_vand_VV(vq2, mask_h4); + HVX_Vector v_hi2 = Q6_Vub_vlsr_VubR(vq2, 4); + HVX_Vector v_lo3 = Q6_V_vand_VV(vq3, mask_h4); + HVX_Vector v_hi3 = Q6_Vub_vlsr_VubR(vq3, 4); + + // Q5_0: OR 0xF0 where the plane flags a clear 5th bit (q - 16) + HVX_Vector v_plane = hvx_vmem(tile_src + 512); + v_lo0 = hvx_q5_0_or_neg(v_lo0, v_plane, 0); + v_hi0 = hvx_q5_0_or_neg(v_hi0, v_plane, 1); + v_lo1 = hvx_q5_0_or_neg(v_lo1, v_plane, 2); + v_hi1 = hvx_q5_0_or_neg(v_hi1, v_plane, 3); + v_lo2 = hvx_q5_0_or_neg(v_lo2, v_plane, 4); + v_hi2 = hvx_q5_0_or_neg(v_hi2, v_plane, 5); + v_lo3 = hvx_q5_0_or_neg(v_lo3, v_plane, 6); + v_hi3 = hvx_q5_0_or_neg(v_hi3, v_plane, 7); + + // Shuffling + HVX_VectorPair vp_shuf0 = Q6_W_vshuff_VVR(v_hi0, v_lo0, -1); + HVX_VectorPair vp_shuf1 = Q6_W_vshuff_VVR(v_hi1, v_lo1, -1); + HVX_VectorPair vp_shuf2 = Q6_W_vshuff_VVR(v_hi2, v_lo2, -1); + HVX_VectorPair vp_shuf3 = Q6_W_vshuff_VVR(v_hi3, v_lo3, -1); + + // Unpack to 16-bit + HVX_VectorPair vp_int16_lo0 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf0)); + HVX_VectorPair vp_int16_hi0 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf0)); + HVX_VectorPair vp_int16_lo1 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf1)); + HVX_VectorPair vp_int16_hi1 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf1)); + HVX_VectorPair vp_int16_lo2 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf2)); + HVX_VectorPair vp_int16_hi2 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf2)); + HVX_VectorPair vp_int16_lo3 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf3)); + HVX_VectorPair vp_int16_hi3 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf3)); + + // Convert and scale multiplication + HVX_Vector v_grp0_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo0)), v_scale_duplicated)); + HVX_Vector v_grp0_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo0)), v_scale_duplicated)); + HVX_Vector v_grp0_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi0)), v_scale_duplicated)); + HVX_Vector v_grp0_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi0)), v_scale_duplicated)); + + HVX_Vector v_grp1_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo1)), v_scale_duplicated)); + HVX_Vector v_grp1_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo1)), v_scale_duplicated)); + HVX_Vector v_grp1_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi1)), v_scale_duplicated)); + HVX_Vector v_grp1_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi1)), v_scale_duplicated)); + + HVX_Vector v_grp2_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo2)), v_scale_duplicated)); + HVX_Vector v_grp2_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo2)), v_scale_duplicated)); + HVX_Vector v_grp2_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi2)), v_scale_duplicated)); + HVX_Vector v_grp2_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi2)), v_scale_duplicated)); + + HVX_Vector v_grp3_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo3)), v_scale_duplicated)); + HVX_Vector v_grp3_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo3)), v_scale_duplicated)); + HVX_Vector v_grp3_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi3)), v_scale_duplicated)); + HVX_Vector v_grp3_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi3)), v_scale_duplicated)); + + // Parallel Stores + hvx_vmem(dst_ptr + 0 * 64) = v_grp0_0; + hvx_vmem(dst_ptr + 1 * 64) = v_grp0_1; + hvx_vmem(dst_ptr + 2 * 64) = v_grp0_2; + hvx_vmem(dst_ptr + 3 * 64) = v_grp0_3; + + hvx_vmem(dst_ptr + 4 * 64) = v_grp1_0; + hvx_vmem(dst_ptr + 5 * 64) = v_grp1_1; + hvx_vmem(dst_ptr + 6 * 64) = v_grp1_2; + hvx_vmem(dst_ptr + 7 * 64) = v_grp1_3; + + hvx_vmem(dst_ptr + 8 * 64) = v_grp2_0; + hvx_vmem(dst_ptr + 9 * 64) = v_grp2_1; + hvx_vmem(dst_ptr + 10 * 64) = v_grp2_2; + hvx_vmem(dst_ptr + 11 * 64) = v_grp2_3; + + hvx_vmem(dst_ptr + 12 * 64) = v_grp3_0; + hvx_vmem(dst_ptr + 13 * 64) = v_grp3_1; + hvx_vmem(dst_ptr + 14 * 64) = v_grp3_2; + hvx_vmem(dst_ptr + 15 * 64) = v_grp3_3; + } +} + // Q6_K stores 6-bit weights and one fp16 scale per 16 k, see HTP_TENSOR_TILE_SIZE_Q6_K. // A k-group holds 4 k per row, the HMX tile holds 2, so each group is dealt into two tiles. static void dequantize_tiled_weight_to_fp16_task_q6_k( diff --git a/ggml/src/ggml-hexagon/htp/htp-ops.h b/ggml/src/ggml-hexagon/htp/htp-ops.h index 7c4b973070e6..c28b8d61cb3e 100644 --- a/ggml/src/ggml-hexagon/htp/htp-ops.h +++ b/ggml/src/ggml-hexagon/htp/htp-ops.h @@ -21,6 +21,8 @@ enum htp_data_type { HTP_TYPE_F16 = 1, HTP_TYPE_Q4_0 = 2, HTP_TYPE_Q4_1 = 3, + HTP_TYPE_Q5_0 = 6, + HTP_TYPE_Q5_1 = 7, HTP_TYPE_Q8_0 = 8, HTP_TYPE_Q2_K = 10, HTP_TYPE_Q3_K = 11, diff --git a/ggml/src/ggml-hexagon/htp/htp-tensor.h b/ggml/src/ggml-hexagon/htp/htp-tensor.h index a5ea0d533984..beacc7e4db58 100644 --- a/ggml/src/ggml-hexagon/htp/htp-tensor.h +++ b/ggml/src/ggml-hexagon/htp/htp-tensor.h @@ -17,6 +17,8 @@ #define HTP_TENSOR_TILE_SIZE_F16 2048 #define HTP_TENSOR_TILE_SIZE_Q4_0 576 #define HTP_TENSOR_TILE_SIZE_Q4_1 640 +#define HTP_TENSOR_TILE_SIZE_Q5_0 704 +#define HTP_TENSOR_TILE_SIZE_Q5_1 768 #define HTP_TENSOR_TILE_SIZE_Q8_0 1088 #define HTP_TENSOR_TILE_SIZE_IQ4_NL 576 #define HTP_TENSOR_TILE_SIZE_MXFP4 544 @@ -30,7 +32,7 @@ #define HTP_TENSOR_TILE_K_Q2_0 64 #define HTP_TENSOR_TILE_SIZE_Q2_0 576 -// Tiled weight tensor layouts (Q4_0, Q8_0, IQ4_NL, MXFP4, Q1_0, Q2_0, K-quants): +// Tiled weight tensor layouts (Q4_0, Q5_0, Q5_1, Q8_0, IQ4_NL, MXFP4, Q1_0, Q2_0, K-quants): // See docs/backend/snapdragon/developer.md ("Tiled Weight Formats"). struct htp_tensor_mdev_range { @@ -143,6 +145,8 @@ static inline uint32_t htp_tensor_get_tile_size(int type) { case HTP_TYPE_Q4_0: return HTP_TENSOR_TILE_SIZE_Q4_0; case HTP_TYPE_IQ4_NL: return HTP_TENSOR_TILE_SIZE_IQ4_NL; case HTP_TYPE_Q4_1: return HTP_TENSOR_TILE_SIZE_Q4_1; + case HTP_TYPE_Q5_0: return HTP_TENSOR_TILE_SIZE_Q5_0; + case HTP_TYPE_Q5_1: return HTP_TENSOR_TILE_SIZE_Q5_1; case HTP_TYPE_Q4_K: return HTP_TENSOR_TILE_SIZE_Q4_K; case HTP_TYPE_Q8_0: return HTP_TENSOR_TILE_SIZE_Q8_0; case HTP_TYPE_Q5_K: return HTP_TENSOR_TILE_SIZE_Q5_K; @@ -182,6 +186,8 @@ static inline uint32_t htp_tensor_get_row_size(int type, uint32_t ne00) { case HTP_TYPE_Q4_0: case HTP_TYPE_IQ4_NL: return (ne00 / 32) * 18; case HTP_TYPE_Q4_1: return (ne00 / 32) * 20; + case HTP_TYPE_Q5_0: return (ne00 / 32) * 22; + case HTP_TYPE_Q5_1: return (ne00 / 32) * 24; case HTP_TYPE_MXFP4: return (ne00 / 32) * 17; case HTP_TYPE_Q2_K: return (ne00 / 256) * 84; case HTP_TYPE_Q2_0: return (ne00 / 64) * 18; diff --git a/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-tiled.h b/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-tiled.h index 01c671679664..4a6b2b5ea216 100644 --- a/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-tiled.h +++ b/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-tiled.h @@ -639,6 +639,74 @@ static inline HVX_VectorPair accum_5bit_32x2( return Q6_W_vcombine_VV(v_sum1, v_sum0); } +// OR 0xF0 into every lane of v whose flag j is set in the plane, i.e. 4-bit value | 0xF0 = q - 16 where the 5th bit is clear (Q5_0) +static inline HVX_Vector hvx_q5_0_or_neg(HVX_Vector v, HVX_Vector v_plane, int j) { + HVX_VectorPred q = Q6_Q_vand_VR(v_plane, 0x01010101u << j); + return Q6_V_vandor_VQR(v, q, 0xF0F0F0F0); +} + +// Q5_0: signed bytes (q - 16) straight from the nibbles and the plane +static inline HVX_VectorPair unpack_and_interleave_q5_0_x2(HVX_Vector v_src, HVX_Vector v_plane, int i, HVX_Vector mask_h4) { + HVX_Vector v_lo = hvx_q5_0_or_neg(Q6_V_vand_VV(v_src, mask_h4), v_plane, 2 * i); + HVX_Vector v_hi = hvx_q5_0_or_neg(Q6_Vub_vlsr_VubR(v_src, 4), v_plane, 2 * i + 1); + HVX_VectorPair v01_pair = Q6_W_vshuff_VVR(v_hi, v_lo, -1); + HVX_Vector v01_lo = Q6_V_lo_W(v01_pair); + HVX_Vector v01_hi = Q6_V_hi_W(v01_pair); + + HVX_Vector v23_lo = Q6_V_valign_VVR(v01_hi, v01_lo, 64); + HVX_Vector v_W0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v23_lo, v01_lo, -2)); + + HVX_Vector v67_lo = Q6_V_valign_VVR(v01_lo, v01_hi, 64); + HVX_Vector v_W1 = Q6_V_lo_W(Q6_W_vshuff_VVR(v67_lo, v01_hi, -2)); + + return Q6_W_vcombine_VV(v_W1, v_W0); +} + +static inline HVX_Vector accum_q5_0_32x1( + const HVX_Vector * restrict vptr, + const HVX_Vector * restrict v_act +) { + HVX_Vector v_sum0 = Q6_V_vzero(); + HVX_Vector v_sum1 = Q6_V_vzero(); + HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F); + HVX_Vector v_plane = vptr[4]; + + #pragma unroll + for (int i = 0; i < 4; i++) { + HVX_VectorPair v_W_pair = unpack_and_interleave_q5_0_x2(vptr[i], v_plane, i, mask_h4); + v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, Q6_V_lo_W(v_W_pair), v_act[i * 2 + 0]); + v_sum1 = Q6_Vw_vrmpyacc_VwVbVb(v_sum1, Q6_V_hi_W(v_W_pair), v_act[i * 2 + 1]); + } + + return Q6_Vw_vadd_VwVw(v_sum0, v_sum1); +} + +static inline HVX_VectorPair accum_q5_0_32x2( + const HVX_Vector * restrict vptr, + const HVX_Vector * restrict v_act0, + const HVX_Vector * restrict v_act1 +) { + HVX_Vector v_sum0 = Q6_V_vzero(); + HVX_Vector v_sum1 = Q6_V_vzero(); + HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F); + HVX_Vector v_plane = vptr[4]; + + #pragma unroll + for (int i = 0; i < 4; i++) { + HVX_VectorPair v_W_pair = unpack_and_interleave_q5_0_x2(vptr[i], v_plane, i, mask_h4); + HVX_Vector v_W0 = Q6_V_lo_W(v_W_pair); + HVX_Vector v_W1 = Q6_V_hi_W(v_W_pair); + + v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act0[i * 2 + 0]); + v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W1, v_act0[i * 2 + 1]); + + v_sum1 = Q6_Vw_vrmpyacc_VwVbVb(v_sum1, v_W0, v_act1[i * 2 + 0]); + v_sum1 = Q6_Vw_vrmpyacc_VwVbVb(v_sum1, v_W1, v_act1[i * 2 + 1]); + } + + return Q6_W_vcombine_VV(v_sum1, v_sum0); +} + // Q6_K weights are stored unsigned (0..63), see HTP_TENSOR_TILE_SIZE_Q6_K. Unpack k-group g of a tile to signed bytes (q - 32) static inline HVX_Vector unpack_q6_k_group(const HVX_Vector * restrict vptr, int g, HVX_Vector mask_0f, HVX_Vector mask_03, HVX_Vector i32) { HVX_Vector v_lo = (g & 1) ? Q6_Vub_vlsr_VubR(vptr[g >> 1], 4) : Q6_V_vand_VV(vptr[g >> 1], mask_0f); @@ -1251,6 +1319,82 @@ static void tiled_vec_dot_q8_0_32x2(const uint32_t n, float * restrict s0, float } } +static void tiled_vec_dot_q5_0_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) { + const uint8_t * restrict tile_ptr = vx; + const uint8_t * restrict y_q = vy; + + HVX_Vector v_sum_float = Q6_V_vzero(); + + uint32_t n_k_tiles = n / 32; + for (uint32_t kt = 0; kt < n_k_tiles; kt++) { + const HVX_Vector * restrict vptr = (const HVX_Vector *) (tile_ptr + kt * 768); + const HVX_Vector * restrict v_act = (const HVX_Vector *) (y_q + kt * 1152); + + HVX_Vector v_sum = accum_q5_0_32x1(vptr, v_act); + HVX_Vector v_sum_sf = Q6_Vsf_equals_Vw(v_sum); + + HVX_Vector v_scale_w = vptr[5]; + HVX_Vector v_scale_a = v_act[8]; + HVX_Vector v_scale_comb = hvx_vec_mul_f16_f16_to_f32_lower32(v_scale_w, v_scale_a); + HVX_Vector v_sum_scaled = hvx_vec_mul_f32_f32(v_sum_sf, v_scale_comb); + + v_sum_float = hvx_vec_add_f32_f32(v_sum_float, v_sum_scaled); + } + + if (sz) { + hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz))); + } else { + hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float); + } +} + +static void tiled_vec_dot_q5_0_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) { + const uint8_t * restrict tile_ptr = vx; + const uint8_t * restrict y0_q = vy0; + const uint8_t * restrict y1_q = vy1; + + HVX_Vector v_sum_float_c0 = Q6_V_vzero(); + HVX_Vector v_sum_float_c1 = Q6_V_vzero(); + + uint32_t n_k_tiles = n / 32; + for (uint32_t kt = 0; kt < n_k_tiles; kt++) { + const HVX_Vector * restrict vptr = (const HVX_Vector *) (tile_ptr + kt * 768); + const HVX_Vector * restrict v_act0 = (const HVX_Vector *) (y0_q + kt * 1152); + const HVX_Vector * restrict v_act1 = (const HVX_Vector *) (y1_q + kt * 1152); + + HVX_VectorPair v_sums = accum_q5_0_32x2(vptr, v_act0, v_act1); + HVX_Vector v_sum_c0 = Q6_V_lo_W(v_sums); + HVX_Vector v_sum_c1 = Q6_V_hi_W(v_sums); + + HVX_Vector v_sum_sf_c0 = Q6_Vsf_equals_Vw(v_sum_c0); + HVX_Vector v_sum_sf_c1 = Q6_Vsf_equals_Vw(v_sum_c1); + + HVX_Vector v_scale_w = vptr[5]; + HVX_Vector v_scale_a_c0 = v_act0[8]; + HVX_Vector v_scale_a_c1 = v_act1[8]; + + HVX_Vector v_scale_comb_c0 = hvx_vec_mul_f16_f16_to_f32_lower32(v_scale_w, v_scale_a_c0); + HVX_Vector v_scale_comb_c1 = hvx_vec_mul_f16_f16_to_f32_lower32(v_scale_w, v_scale_a_c1); + + HVX_Vector v_sum_scaled_c0 = hvx_vec_mul_f32_f32(v_sum_sf_c0, v_scale_comb_c0); + HVX_Vector v_sum_scaled_c1 = hvx_vec_mul_f32_f32(v_sum_sf_c1, v_scale_comb_c1); + + v_sum_float_c0 = hvx_vec_add_f32_f32(v_sum_float_c0, v_sum_scaled_c0); + v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, v_sum_scaled_c1); + } + + if (sz0) { + hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0))); + } else { + hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0); + } + if (sz1) { + hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1))); + } else { + hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1); + } +} + static void tiled_vec_dot_q5_k_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y_q = vy; diff --git a/ggml/src/ggml-hexagon/htp/matmul-ops.c b/ggml/src/ggml-hexagon/htp/matmul-ops.c index fb15310cfa64..2d0750954c1b 100644 --- a/ggml/src/ggml-hexagon/htp/matmul-ops.c +++ b/ggml/src/ggml-hexagon/htp/matmul-ops.c @@ -1664,6 +1664,12 @@ static int hvx_mm_init_tiled_vec_dot(struct htp_mm_context * mmctx, enum htp_dat mmctx->vec_dot_32x1 = tiled_vec_dot_q8_0_32x1; mmctx->vec_dot_32x2 = tiled_vec_dot_q8_0_32x2; return 0; + case HTP_TYPE_Q5_0: + mmctx->type = "q5_0_tiled-f32"; + mmctx->vec_dot_32x1 = tiled_vec_dot_q5_0_32x1; + mmctx->vec_dot_32x2 = tiled_vec_dot_q5_0_32x2; + return 0; + case HTP_TYPE_Q5_1: case HTP_TYPE_Q5_K: mmctx->type = "q5_k_tiled-f32"; mmctx->vec_dot_32x1 = tiled_vec_dot_q5_k_32x1; @@ -2316,6 +2322,8 @@ static inline tiled_dequant_task_fn_t hmx_get_dequant_worker_fn(int weight_type, case HTP_TYPE_Q4_K: return dequantize_tiled_weight_to_fp16_task_q4_1; case HTP_TYPE_MXFP4: return dequantize_tiled_weight_to_fp16_task_mxfp4; case HTP_TYPE_Q8_0: return dequantize_tiled_weight_to_fp16_task_q8_0; + case HTP_TYPE_Q5_0: return dequantize_tiled_weight_to_fp16_task_q5_0; + case HTP_TYPE_Q5_1: case HTP_TYPE_Q5_K: return dequantize_tiled_weight_to_fp16_task_q5_k; case HTP_TYPE_Q6_K: return dequantize_tiled_weight_to_fp16_task_q6_k; case HTP_TYPE_Q3_K: return dequantize_tiled_weight_to_fp16_task_q3_k; diff --git a/ggml/src/ggml-hexagon/htp/matmul-ops.h b/ggml/src/ggml-hexagon/htp/matmul-ops.h index 0c16fe7b82aa..7a85624cf9b6 100644 --- a/ggml/src/ggml-hexagon/htp/matmul-ops.h +++ b/ggml/src/ggml-hexagon/htp/matmul-ops.h @@ -185,7 +185,7 @@ static inline int htp_mm_hmx_compute_chunks(size_t vtcm_total, // (Q2_K: per-16 k sums, q8_1_s16) static inline bool htp_mm_weight_has_offset(int weight_type) { return weight_type == HTP_TYPE_Q4_1 || weight_type == HTP_TYPE_Q4_K || weight_type == HTP_TYPE_Q5_K || - weight_type == HTP_TYPE_Q2_K || weight_type == HTP_TYPE_Q2_0; + weight_type == HTP_TYPE_Q2_K || weight_type == HTP_TYPE_Q2_0 || weight_type == HTP_TYPE_Q5_1; } // --- Activation/Row Size Helpers --- diff --git a/ggml/src/ggml-metal/kernels/solve_tri.metal b/ggml/src/ggml-metal/kernels/solve_tri.metal index 50f16facbf2e..216f605fe29b 100644 --- a/ggml/src/ggml-metal/kernels/solve_tri.metal +++ b/ggml/src/ggml-metal/kernels/solve_tri.metal @@ -39,7 +39,9 @@ kernel void kernel_solve_tri_f32( for (short t = 0; t*NW < N; ++t) { const short idx = t*NW + tiisg; - sh0_cur[idx] = src0_ptr[idx]; + if (rr + sgitg < N && idx < N) { + sh0_cur[idx] = src0_ptr[idx]; + } } src0_ptr += NSG*N; @@ -60,7 +62,9 @@ kernel void kernel_solve_tri_f32( for (short t = 0; t*NW < r; ++t) { const short idx = t*NW + tiisg; - sum += sh0_cur[idx] * dst_ptr[idx*K] * (idx < r); + if (idx < r) { + sum += sh0_cur[idx] * dst_ptr[idx*K]; + } } sum = simd_sum(sum); diff --git a/ggml/src/ggml-opencl/CMakeLists.txt b/ggml/src/ggml-opencl/CMakeLists.txt index e2a82d5bc9b1..cdf4a5d54455 100644 --- a/ggml/src/ggml-opencl/CMakeLists.txt +++ b/ggml/src/ggml-opencl/CMakeLists.txt @@ -76,7 +76,6 @@ set(GGML_OPENCL_KERNELS clamp cpy cvt - diag_mask_inf diag div dsv4_hc @@ -322,11 +321,14 @@ set(GGML_OPENCL_KERNELS repeat mul_mat_f16_f32 mul_mm_f16_f32_kq_kqv + mul_mm_f16_f32_kq_p8 + mul_mm_q8_f32_kqv conv2d conv2d_f16_f32 conv2_dw flash_attn_repack flash_attn_pre_f16 + flash_attn_pv_direct flash_attn_f32_f16 flash_attn_f32_q8_0 flash_attn_f32_q4_0 diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index c25a13dc6f04..7fa1a8e35b6b 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -79,6 +79,11 @@ bool ggml_cl_compute_forward(ggml_backend_t backend, struct ggml_tensor * tensor static bool ggml_cl_is_q4_0_soa(const ggml_tensor * tensor); static bool ggml_cl_is_q8_0_soa(const ggml_tensor * tensor); static void ggml_cl_mul_mat(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +static void ggml_cl_cpy(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +static void ggml_cl_fa_decompose_soft_max(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst, cl_mem sums); +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +static void ggml_cl_mul_mat_kq_kqv_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool is_kq); +#endif // See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1. // Precompute mp (m' in the paper) and L such that division @@ -571,6 +576,8 @@ struct ggml_opencl_fa_kernels { std::map, cl_kernel> kv_pad_f16; std::map, cl_kernel> mask_pad_f16; std::map, cl_kernel> blk_f16; + // decomposed prefill: V^T, built with the prepass + std::map, cl_kernel> v_transpose_f16; // generic prefill tile dims (f16 / f32 paths) std::map, int> bm; std::map, int> bn; @@ -760,6 +767,18 @@ struct ggml_backend_opencl_context { ggml_cl_buffer prealloc_src1; ggml_cl_buffer prealloc_top_k; + // scratch for the decomposed flash attention prefill, sized per query chunk + ggml_cl_buffer prealloc_fa_vt; + ggml_cl_buffer prealloc_fa_kq; + ggml_cl_buffer prealloc_fa_kqv; + ggml_cl_buffer prealloc_fa_sums; + ggml_cl_buffer prealloc_fa_vtq; + ggml_cl_buffer prealloc_fa_vtd; + ggml_cl_buffer prealloc_fa_pq; + ggml_cl_buffer prealloc_fa_pd; + ggml_cl_buffer prealloc_fa_bmax; + ggml_cl_buffer prealloc_fa_bsum; + #ifdef GGML_OPENCL_USE_ADRENO_KERNELS ggml_cl_buffer prealloc_adreno_xmem_const; bool adreno_xmem_gemm_enabled = false; @@ -779,7 +798,6 @@ struct ggml_backend_opencl_context { cl_program program_moe_add_id_glu; cl_program program_clamp; cl_program program_cvt; - cl_program program_diag_mask_inf; cl_program program_gelu; cl_program program_gemv_noshuffle_general; cl_program program_gemv_noshuffle; @@ -867,10 +885,16 @@ struct ggml_backend_opencl_context { cl_kernel kernel_rms_norm_mul_add = nullptr; // fused rms_norm(x)*w + b (residual) cl_kernel kernel_l2_norm_f32; cl_kernel kernel_group_norm, kernel_group_norm_mul_add; - cl_kernel kernel_diag_mask_inf, kernel_diag_mask_inf_8; cl_kernel kernel_diag_f32; cl_kernel kernel_soft_max, kernel_soft_max_4; cl_kernel kernel_soft_max_f16, kernel_soft_max_4_f16; + cl_kernel kernel_fa_decompose_soft_max_4_f16, kernel_fa_decompose_scale_rows_f32; + cl_kernel kernel_mul_mm_f16_f32_kq_p8 = nullptr; + cl_kernel kernel_mul_mm_q8_f32_kqv = nullptr; + cl_kernel kernel_fa_p8_fixup = nullptr; + cl_kernel kernel_fa_kqv_direct_f16 = nullptr; + cl_kernel kernel_fa_kqv_direct_reduce = nullptr; + cl_kernel kernel_fa_v_transpose_q8 = nullptr; ggml_opencl_fa_kernels fa; #ifdef GGML_OPENCL_USE_ADRENO_KERNELS ggml_cl_adreno_xmem_attn_state adreno_xmem_attn; @@ -1374,6 +1398,7 @@ struct ggml_backend_opencl_context { cl_kernel kernel_gemv_noshuffle_q4_0_f32; cl_kernel kernel_gemv_noshuffle_q4_0_f32_mc3; // multi-column (N=3) verify GEMV (spec/MTP) cl_kernel kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin; + cl_kernel kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin; cl_kernel kernel_gemm_noshuffle_q4_0_q8_1_dp4a_ila_a8_bin; cl_kernel kernel_gemv_noshuffle_q4_0_f32_32b_trans; cl_kernel kernel_gemv_noshuffle_q4_0_f32_4096_1_11008; @@ -1473,6 +1498,11 @@ struct ggml_backend_opencl_context { #endif // GGML_OPENCL_USE_ADRENO_KERNELS ~ggml_backend_opencl_context() { + for (cl_kernel kernel : {kernel_mul_mm_f16_f32_kq_p8, kernel_mul_mm_q8_f32_kqv, kernel_fa_p8_fixup, kernel_fa_v_transpose_q8, kernel_fa_kqv_direct_f16, kernel_fa_kqv_direct_reduce}) { + if (kernel != nullptr) { + CL_CHECK(clReleaseKernel(kernel)); + } + } if (kernel_dsv4_hc_pre) { CL_CHECK(clReleaseKernel(kernel_dsv4_hc_pre)); } @@ -2259,23 +2289,6 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { GGML_LOG_CONT("."); } - // diag_mask_inf - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "diag_mask_inf.cl.h" - }; -#else - const std::string kernel_src = read_file("diag_mask_inf.cl"); -#endif - backend_ctx->program_diag_mask_inf = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_diag_mask_inf_8 = clCreateKernel(backend_ctx->program_diag_mask_inf, "kernel_diag_mask_inf_8", &err), err)); - CL_CHECK((backend_ctx->kernel_diag_mask_inf = clCreateKernel(backend_ctx->program_diag_mask_inf, "kernel_diag_mask_inf", &err), err)); - GGML_LOG_CONT("."); - } - // diag { #ifdef GGML_OPENCL_EMBED_KERNELS @@ -3972,6 +3985,26 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { GGML_LOG_CONT("."); } +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + // mul_mm_f16_f32_kq_p8 + if (backend_ctx->gpu_family == ADRENO && backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_f16_f32_kq_p8.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_f16_f32_kq_p8.cl"); +#endif + cl_program prog = build_program_from_source_ex(backend_ctx->context, backend_ctx->device, kernel_src.c_str(), + compile_opts, /*fatal=*/false); + if (prog != nullptr) { + CL_CHECK((backend_ctx->kernel_mul_mm_f16_f32_kq_p8 = clCreateKernel(prog, "mul_mm_f16_f32_kq_p8", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + } + GGML_LOG_CONT("."); + } +#endif + // mul { #ifdef GGML_OPENCL_EMBED_KERNELS @@ -4178,9 +4211,51 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); CL_CHECK((backend_ctx->kernel_soft_max_4_f16 = clCreateKernel(backend_ctx->program_softmax_4_f16, "kernel_soft_max_4_f16", &err), err)); + CL_CHECK((backend_ctx->kernel_fa_decompose_soft_max_4_f16 = clCreateKernel(backend_ctx->program_softmax_4_f16, "kernel_fa_decompose_soft_max_4_f16", &err), err)); + CL_CHECK((backend_ctx->kernel_fa_decompose_scale_rows_f32 = clCreateKernel(backend_ctx->program_softmax_4_f16, "kernel_fa_decompose_scale_rows_f32", &err), err)); + CL_CHECK((backend_ctx->kernel_fa_p8_fixup = clCreateKernel(backend_ctx->program_softmax_4_f16, "kernel_fa_p8_fixup", &err), err)); + GGML_LOG_CONT("."); + } + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || + backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X || + backend_ctx->adreno_gen == ADRENO_GPU_GEN::X1E) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "flash_attn_pv_direct.cl.h" + }; +#else + const std::string kernel_src = read_file("flash_attn_pv_direct.cl"); +#endif + cl_program prog = build_program_from_source_ex(backend_ctx->context, backend_ctx->device, kernel_src.c_str(), + compile_opts, /*fatal=*/false); + if (prog != nullptr) { + CL_CHECK((backend_ctx->kernel_fa_kqv_direct_f16 = clCreateKernel(prog, "kernel_fa_kqv_direct_f16", &err), err)); + CL_CHECK((backend_ctx->kernel_fa_kqv_direct_reduce = clCreateKernel(prog, "kernel_fa_kqv_direct_reduce", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + } GGML_LOG_CONT("."); } + if (backend_ctx->gpu_family == ADRENO && backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_q8_f32_kqv.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_q8_f32_kqv.cl"); +#endif + cl_program prog = build_program_from_source_ex(backend_ctx->context, backend_ctx->device, kernel_src.c_str(), + compile_opts, /*fatal=*/false); + if (prog != nullptr) { + CL_CHECK((backend_ctx->kernel_mul_mm_q8_f32_kqv = clCreateKernel(prog, "kernel_mul_mm_q8_f32_kqv", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + } + GGML_LOG_CONT("."); + } +#endif + // div { #ifdef GGML_OPENCL_EMBED_KERNELS @@ -6073,6 +6148,7 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { backend_ctx->kernel_gemv_noshuffle_q4_0_f32_32b_trans = nullptr; backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin = nullptr; + backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin = nullptr; backend_ctx->kernel_gemm_noshuffle_q4_0_q8_1_dp4a_ila_a8_bin = nullptr; { { @@ -6117,6 +6193,17 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { CL_CHECK(clReleaseProgram(bin_prog)); GGML_LOG_CONT("."); } + + kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q4_0_f32_32b_trans_ila_a7", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program bin_prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); + + CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin = + clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7", &err), err)); + CL_CHECK(clReleaseProgram(bin_prog)); + GGML_LOG_CONT("."); + } } } @@ -7825,6 +7912,17 @@ static void ggml_opencl_ensure_fa_pre_kernels(ggml_backend_opencl_context * back backend_ctx->fa.kv_pad_f16[{dk, dv}] = k_kv_pad_f16; backend_ctx->fa.mask_pad_f16[{dk, dv}] = k_mask_pad_f16; backend_ctx->fa.blk_f16[{dk, dv}] = k_blk_f16; + // optional, the decomposed prefill checks for it and falls back to the fused tile + cl_kernel k_v_transpose_f16 = clCreateKernel(prog_pre_f16, "flash_attn_v_transpose_f16", &err); + if (err == CL_SUCCESS) { + backend_ctx->fa.v_transpose_f16[{dk, dv}] = k_v_transpose_f16; + } + if (backend_ctx->kernel_fa_v_transpose_q8 == nullptr && backend_ctx->has_integer_dot) { + backend_ctx->kernel_fa_v_transpose_q8 = clCreateKernel(prog_pre_f16, "flash_attn_v_transpose_q8", &err); + if (err != CL_SUCCESS) { + backend_ctx->kernel_fa_v_transpose_q8 = nullptr; + } + } clReleaseProgram(prog_pre_f16); } @@ -11511,7 +11609,8 @@ inline bool enable_adreno_trans_weight_q5_K(const ggml_backend_opencl_context *b inline bool use_q4_0_bin_kernels(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { #ifdef GGML_OPENCL_USE_ADRENO_KERNELS if (!backend_ctx->kernel_gemv_noshuffle_q4_0_f32_32b_trans || - !backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin) { + !(backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin || + backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin)) { return false; } @@ -12096,8 +12195,6 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te return true; case GGML_OP_DIAG: return true; - case GGML_OP_DIAG_MASK_INF: - return op->ne[3] == 1; case GGML_OP_ROPE: { const int mode = ((const int32_t *) op->op_params)[2]; if (!ggml_rope_get_truncate(op)) { @@ -22699,6 +22796,610 @@ static void ggml_cl_flash_attn_prefill_bin(ggml_backend_t backend, const ggml_te } #endif // GGML_OPENCL_USE_ADRENO_KERNELS +static void ggml_cl_fa_kq_p8_dispatch( + ggml_backend_t backend, + const ggml_tensor * q, const ggml_tensor * k, + const ggml_tensor * mask, const ggml_tensor * sinks, + const ggml_tensor * dst, + int64_t q0, int nqc, float scale, float max_bias, int p_pitch +) { + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + auto * extra_k = (ggml_tensor_extra_cl *) (k->view_src ? k->view_src->extra : k->extra); + auto * extra_q = (ggml_tensor_extra_cl *) q->extra; + auto * extra_m = (ggml_tensor_extra_cl *) mask->extra; + + const int M = k->ne[1]; + const int K = k->ne[0]; + const int N = nqc; + const int D_A = k->ne[2]; + const int D_B = q->ne[2]; + + cl_int err; + + cl_buffer_region region = {extra_k->offset + k->view_offs, k->nb[1] * k->ne[1]}; + cl_mem k_sub = clCreateSubBuffer(extra_k->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + cl_image_format fmt = {CL_RGBA, CL_FLOAT}; + cl_image_desc desc = {}; + desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + desc.image_width = region.size / 16; + desc.buffer = k_sub; + cl_mem k_img = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &fmt, &desc, nullptr, &err); + CL_CHECK(err); + + region.origin = extra_q->offset + q->view_offs + q0 * q->nb[1]; + region.size = (size_t) K * N * D_B * sizeof(float); + cl_mem q_sub = clCreateSubBuffer(extra_q->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + const cl_ulong off_mask = extra_m->offset + mask->view_offs + q0 * mask->nb[1]; + const cl_ulong mask_nb1 = mask->nb[1]; + const int n_head_log2 = 1u << (unsigned) floorf(log2f((float) D_B)); + const float m0 = powf(2.0f, -max_bias / n_head_log2); + const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2); + + cl_uint a = 0; + + cl_kernel kernel = backend_ctx->kernel_mul_mm_f16_f32_kq_p8; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &k_img)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &q_sub)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bmax.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bsum.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_m->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_mask)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &mask_nb1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &max_bias)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m0)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head_log2)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_A)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_B)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &p_pitch)); + + const size_t n_tiles = (N + 31) / 32; + size_t gws[3] = {64, n_tiles, (size_t)(M / 64) * D_B}; + + const bool two_tiles = n_tiles % 2 == 0 && backend_ctx->get_kernel_workgroup_size(kernel) >= 128; + size_t lws[3] = {64, two_tiles ? (size_t) 2 : (size_t) 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + CL_CHECK(clReleaseMemObject(k_img)); + CL_CHECK(clReleaseMemObject(k_sub)); + CL_CHECK(clReleaseMemObject(q_sub)); + + cl_mem sinks_buf = extra_q->data_device; + cl_ulong sinks_off = 0; + const int has_sinks = sinks != nullptr; + + if (sinks) { + auto * extra_s = (ggml_tensor_extra_cl *) sinks->extra; + sinks_buf = extra_s->data_device; + sinks_off = extra_s->offset + sinks->view_offs; + } + + const int nblk = M / 32; + const int row_blk = p_pitch / 32; + + kernel = backend_ctx->kernel_fa_p8_fixup; + + a = 0; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bmax.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bsum.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pd.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_sums.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &sinks_buf)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &sinks_off)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &has_sinks)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nblk)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &row_blk)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &N)); + + size_t gws_fixup[3] = {(size_t) 64 * N, (size_t) D_B, 1}; + size_t lws_fixup[3] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws_fixup, lws_fixup, dst); +} + +static void ggml_cl_fa_decompose_scratch_tensor( + ggml_tensor & t, ggml_tensor_extra_cl & extra, cl_mem buffer, ggml_type type, + int64_t ne0, int64_t ne1, int64_t ne2 +) { + memset(&t, 0, sizeof(t)); + t.type = type; + t.ne[0] = ne0; t.ne[1] = ne1; t.ne[2] = ne2; t.ne[3] = 1; + t.nb[0] = ggml_type_size(type); + t.nb[1] = t.nb[0]*ne0; + t.nb[2] = t.nb[1]*ne1; + t.nb[3] = t.nb[2]*ne2; + + extra.reset(); + extra.data_device = buffer; + t.extra = &extra; +} + +static void ggml_cl_fa_decompose_write_chunk( + ggml_backend_t backend, const ggml_tensor & kqv, int64_t q0, ggml_tensor * dst +) { + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const int64_t dv = kqv.ne[0]; + const int64_t nqc = kqv.ne[1]; + const int64_t n_head = kqv.ne[2]; + + // apply the deferred 1/sum to the KQV rows + { + cl_kernel kernel = backend_ctx->kernel_fa_decompose_scale_rows_f32; + const cl_ulong offset_kqv = 0; + const cl_ulong offset_sums = 0; + const int dv_i = (int) dv; + const int nqc_i = (int) nqc; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &backend_ctx->prealloc_fa_kqv.buffer)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset_kqv)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &backend_ctx->prealloc_fa_sums.buffer)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset_sums)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &dv_i)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &nqc_i)); + + size_t gws[3] = { (size_t) 64 * nqc, (size_t) n_head, 1 }; + size_t lws[3] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } + + // permute into dst: [dv, nqc, n_head] -> dst[dv, n_head, q0 .. q0+nqc) + { + ggml_tensor kqv_perm = kqv; + kqv_perm.ne[1] = n_head; + kqv_perm.ne[2] = nqc; + kqv_perm.nb[1] = kqv.nb[2]; + kqv_perm.nb[2] = kqv.nb[1]; + + ggml_tensor dst_chunk = *dst; + dst_chunk.ne[2] = nqc; + dst_chunk.view_offs = dst->view_offs + (size_t) q0 * dst->nb[2]; + + ggml_cl_cpy(backend, &kqv_perm, &dst_chunk, nullptr); + } +} + +static void ggml_cl_flash_attn_decompose( + ggml_backend_t backend, + const ggml_tensor * q, const ggml_tensor * k, ggml_tensor * dst, + int64_t n_q_chunk, float scale, float max_bias +) { + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * v = dst->src[2]; + const ggml_tensor * mask = dst->src[3]; + const ggml_tensor * sinks = dst->src[4]; + const int64_t n_q = q->ne[1]; + const int64_t n_kv = k->ne[1]; + const int64_t dv = v->ne[0]; + const int64_t n_head = q->ne[2]; + const int64_t n_head_kv = k->ne[2]; + + const std::pair dk_dv = {(int) q->ne[0], (int) dv}; + + // The image GEMMs work in 64 x 32 tiles and can touch past the exact extent, + // so size each scratch by the padded shape plus one extra head. + auto pad_up = [](int64_t x, int64_t a) { return ((x + a - 1) / a) * a; }; + const int64_t kq_m = pad_up(n_kv, 64); + const int64_t kqv_m = pad_up(dv, 64); + const int64_t tile_n = pad_up(n_q_chunk, 32); + + backend_ctx->prealloc_fa_vt.allocate(backend_ctx->context, (size_t)(n_kv * kqv_m * (n_head_kv + 1)) * sizeof(ggml_fp16_t)); + backend_ctx->prealloc_fa_kq.allocate(backend_ctx->context, (size_t)(kq_m * tile_n * (n_head + 1)) * sizeof(float)); + backend_ctx->prealloc_fa_kqv.allocate(backend_ctx->context, (size_t)(kqv_m * tile_n * (n_head + 1)) * sizeof(float)); + backend_ctx->prealloc_fa_sums.allocate(backend_ctx->context, (size_t)(n_q_chunk * n_head) * sizeof(float)); + + // V^T once per call: [dv, n_kv, n_head_kv] -> [n_kv, dv, n_head_kv] + { + ggml_tensor_extra_cl * extra_v = (ggml_tensor_extra_cl *)v->extra; + cl_kernel kernel = backend_ctx->fa.v_transpose_f16.at(dk_dv); + + const cl_ulong offset_v = extra_v->offset + v->view_offs; + const cl_ulong v_nb1 = v->nb[1]; + const cl_ulong v_nb2 = v->nb[2]; + const int n_kv_i = (int) n_kv; + const int dv_i = (int) dv; + const int n_head_kv_i = (int) n_head_kv; + + cl_uint a = 0; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_v->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &offset_v)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_vt.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_kv_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &dv_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head_kv_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb2)); + + size_t gws[3] = { (size_t)((dv + 31) / 32) * 32, (size_t)((n_kv + 31) / 32) * 8, (size_t) n_head_kv }; + size_t lws[3] = { 32, 8, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } + + ggml_tensor_extra_cl extra_vt; + ggml_tensor_extra_cl extra_kq; + ggml_tensor_extra_cl extra_kqv; + ggml_tensor vt; + ggml_tensor kq; + ggml_tensor kqv; + ggml_cl_fa_decompose_scratch_tensor(vt, extra_vt, backend_ctx->prealloc_fa_vt.buffer, GGML_TYPE_F16, n_kv, dv, n_head_kv); + + for (int64_t q0 = 0; q0 < n_q; q0 += n_q_chunk) { + const int64_t nqc = MIN(n_q_chunk, n_q - q0); + + // KQ: [dk, n_kv, n_head_kv] x [dk, nqc, n_head] -> [n_kv, nqc, n_head] + ggml_cl_fa_decompose_scratch_tensor(kq, extra_kq, backend_ctx->prealloc_fa_kq.buffer, GGML_TYPE_F32, n_kv, nqc, n_head); + + { + ggml_tensor q_chunk = *q; + q_chunk.ne[1] = nqc; + q_chunk.view_offs = q->view_offs + (size_t) q0 * q->nb[1]; + ggml_cl_mul_mat(backend, k, &q_chunk, &kq); + } + + // softmax in place, the row sums go to prealloc_fa_sums + { + memcpy((float *) kq.op_params + 0, &scale, sizeof(float)); + memcpy((float *) kq.op_params + 1, &max_bias, sizeof(float)); + + ggml_tensor mask_chunk = *mask; + mask_chunk.ne[1] = nqc; + mask_chunk.view_offs = mask->view_offs + (size_t) q0 * mask->nb[1]; + + ggml_cl_fa_decompose_soft_max(backend, &kq, &mask_chunk, sinks, &kq, backend_ctx->prealloc_fa_sums.buffer); + } + + // KQV: [n_kv, dv, n_head_kv] x [n_kv, nqc, n_head] -> [dv, nqc, n_head] + // V^T is contiguous, so mul_mat would not pick the KQV image kernel; call it here. + ggml_cl_fa_decompose_scratch_tensor(kqv, extra_kqv, backend_ctx->prealloc_fa_kqv.buffer, GGML_TYPE_F32, dv, nqc, n_head); +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (backend_ctx->kernel_mul_mm_f16_f32_kqv != nullptr && + (dv % 64) == 0 && (n_kv % 16) == 0 && nqc >= 32 && + ((size_t)(vt.nb[2] * n_head_kv / 4) / 4 <= backend_ctx->image_max_buffer_size) && + ((size_t)(dv * nqc * n_head) <= backend_ctx->image_max_buffer_size)) { + ggml_cl_mul_mat_kq_kqv_adreno(backend, &vt, &kq, &kqv, /*is_kq =*/ false); + } else +#endif + { + ggml_cl_mul_mat(backend, &vt, &kq, &kqv); + } + + ggml_cl_fa_decompose_write_chunk(backend, kqv, q0, dst); + } +} + +static void ggml_cl_fa_pv_direct(ggml_backend_t backend, ggml_tensor * dst, int kv_pitch) { + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * q = dst->src[0]; + const ggml_tensor * v = dst->src[2]; + auto * extra_v = (ggml_tensor_extra_cl *) v->extra; + + const int dv = v->ne[0]; + const int n_q = q->ne[1]; + const int n_head = q->ne[2]; + const int n_head_kv = v->ne[2]; + const int gqa = n_head / n_head_kv; + const int nblk = v->ne[1] / 32; + const int d_blocks = dv / 128; + // Split the KV range to give a small query batch about 256 workgroups. + const int want = MAX(1, 256 / (d_blocks * n_head_kv)); + const int blocks_per_split = (nblk + want - 1) / want; + const int n_split = (nblk + blocks_per_split - 1) / blocks_per_split; + const int n_elem = n_head * n_q * dv; + backend_ctx->prealloc_fa_kq.allocate(backend_ctx->context, (size_t) n_split * n_elem * sizeof(float)); + + const cl_ulong off_v = extra_v->offset + v->view_offs; + const cl_ulong v_nb1 = v->nb[1]; + const cl_ulong v_nb2 = v->nb[2]; + { + cl_kernel kernel = backend_ctx->kernel_fa_kqv_direct_f16; + cl_uint a = 0; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_v->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_v)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb2)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pd.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_kq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &dv)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_q)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &gqa)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nblk)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &blocks_per_split)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &kv_pitch)); + size_t gws[3] = {(size_t) d_blocks * 64, (size_t) n_head_kv, (size_t) n_split}; + size_t lws[3] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } + { + cl_kernel kernel = backend_ctx->kernel_fa_kqv_direct_reduce; + cl_uint a = 0; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_kq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_kqv.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_elem)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_split)); + size_t gws[3] = {((size_t) n_elem + 63) / 64 * 64, 1, 1}; + size_t lws[3] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } +} + +static void ggml_cl_flash_attn_decompose_kq_p8( + ggml_backend_t backend, + const ggml_tensor * q, const ggml_tensor * k, + ggml_tensor * dst, + int64_t n_q_chunk, float scale, float max_bias, bool kqv_direct +) { + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * v = dst->src[2]; + const ggml_tensor * mask = dst->src[3]; + const ggml_tensor * sinks = dst->src[4]; + const int64_t n_q = q->ne[1]; + const int64_t n_kv = k->ne[1]; + const int64_t dv = v->ne[0]; + const int64_t n_head = q->ne[2]; + const int64_t n_head_kv = k->ne[2]; + + auto pad_up = [](int64_t x, int64_t a) { return ((x + a - 1) / a) * a; }; + const int64_t kqv_m = pad_up(dv, 64); + const int64_t tile_n = pad_up(n_q_chunk, 32); + + // Pad the int8 row pitch by one cache line, as in the P8 KQV kernel. + const int kv_pitch = (int) n_kv + 64; + const size_t nblk = (size_t) kv_pitch / 32; + + backend_ctx->prealloc_fa_pq.allocate(backend_ctx->context, (size_t) kv_pitch * n_q_chunk * n_head); + backend_ctx->prealloc_fa_pd.allocate(backend_ctx->context, nblk * n_q_chunk * n_head * sizeof(float)); + backend_ctx->prealloc_fa_bmax.allocate(backend_ctx->context, nblk * n_q_chunk * n_head * sizeof(float)); + backend_ctx->prealloc_fa_bsum.allocate(backend_ctx->context, nblk * n_q_chunk * n_head * sizeof(float)); + backend_ctx->prealloc_fa_kqv.allocate(backend_ctx->context, (size_t)(kqv_m * tile_n * (n_head + 1)) * sizeof(float)); + backend_ctx->prealloc_fa_sums.allocate(backend_ctx->context, (size_t)(n_q_chunk * n_head) * sizeof(float)); + + // Direct PV reads the original V cache and needs no transposed copy. + if (!kqv_direct) { + backend_ctx->prealloc_fa_vtq.allocate(backend_ctx->context, (size_t) kv_pitch * dv * n_head_kv); + backend_ctx->prealloc_fa_vtd.allocate(backend_ctx->context, nblk * dv * n_head_kv * sizeof(cl_half)); + + ggml_tensor_extra_cl * extra_v = (ggml_tensor_extra_cl *)v->extra; + cl_kernel kernel = backend_ctx->kernel_fa_v_transpose_q8; + + const cl_ulong offset_v = extra_v->offset + v->view_offs; + const cl_ulong v_nb1 = v->nb[1]; + const cl_ulong v_nb2 = v->nb[2]; + const cl_ulong v_nb3 = v->nb[3]; + const int n_kv_i = (int) n_kv; + const int dv_i = (int) dv; + const int n_head_kv_i = (int) n_head_kv; + + cl_uint a = 0; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_v->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &offset_v)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_vtq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_vtd.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_kv_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &dv_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head_kv_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb2)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb3)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &kv_pitch)); + + size_t gws[3] = { (size_t)((dv + 31) / 32) * 32, (size_t)((n_kv + 31) / 32) * 8, (size_t) n_head_kv }; + size_t lws[3] = { 32, 8, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } + + ggml_tensor_extra_cl extra_kqv; + ggml_tensor kqv; + + for (int64_t q0 = 0; q0 < n_q; q0 += n_q_chunk) { + const int64_t nqc = MIN(n_q_chunk, n_q - q0); + + ggml_cl_fa_kq_p8_dispatch(backend, q, k, mask, sinks, dst, q0, nqc, scale, max_bias, kv_pitch); + + ggml_cl_fa_decompose_scratch_tensor(kqv, extra_kqv, backend_ctx->prealloc_fa_kqv.buffer, GGML_TYPE_F32, dv, nqc, n_head); + + if (kqv_direct) { + GGML_ASSERT(q0 == 0 && nqc == n_q); + ggml_cl_fa_pv_direct(backend, dst, kv_pitch); + } else { + const cl_ulong zero = 0; + const int dv_i = dv; + const int nkv_i = n_kv; + const int nqc_i = nqc; + const int nh_i = n_head; + const int nhkv_i = n_head_kv; + + cl_kernel kernel = backend_ctx->kernel_mul_mm_q8_f32_kqv; + + cl_uint a = 0; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_vtq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &zero)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_vtd.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &zero)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &zero)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pd.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &zero)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_kqv.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &zero)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &dv_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nkv_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nqc_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nh_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nhkv_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &kv_pitch)); + size_t gws[3] = {(size_t)(dv / 64) * 64, (size_t)(n_head / n_head_kv) * ((nqc + 31) / 32), (size_t) n_head_kv}; + size_t lws[3] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } + + ggml_cl_fa_decompose_write_chunk(backend, kqv, q0, dst); + } +} + +// Decomposed flash attention prefill. +// +// On Adreno the fused prefill tile is slow at large head sizes, while the +// KQ / KQV image GEMMs are fast. -fa 0 uses those GEMMs, but it keeps KQ for +// the whole ubatch in the graph. Here the FLASH_ATTN_EXT node stays, and the +// queries are split into chunks. For each chunk: KQ -> softmax -> KQV into +// backend scratch, so the scratch size depends on the chunk and not on the +// ubatch, and the KV cache keeps the flash attention layout. +// +// Returns false when the shape is not supported, then the fused tile runs. +// GGML_OPENCL_FA_DECOMPOSE=0 disables it, =1 enables it for any Adreno GPU and +// head size. GGML_OPENCL_FA_DECOMPOSE_MB sets the KQ scratch budget (default 256). +// GGML_OPENCL_FA_KQ_P8=0 disables U8 probabilities and int8 KQV. +// GGML_OPENCL_FA_KQV_DIRECT=0 disables direct PV for small query batches. +static bool ggml_cl_flash_attn_decompose_dispatch( + ggml_backend_t backend, + const ggml_tensor * q, const ggml_tensor * k, ggml_tensor * dst +) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + + const ggml_tensor * v = dst->src[2]; + const ggml_tensor * mask = dst->src[3]; + + if (backend_ctx->gpu_family != ADRENO) { + return false; + } + + static const int env = []{ + const char * e = getenv("GGML_OPENCL_FA_DECOMPOSE"); + return (e && e[0]) ? (e[0] != '0' ? 1 : 0) : -1; + }(); + + if (env == 0) { + return false; + } + + const int64_t n_q = q->ne[1]; + const int64_t n_kv = k->ne[1]; + const int64_t dk = q->ne[0]; + const int64_t dv = v->ne[0]; + const int64_t n_head = q->ne[2]; + const int64_t n_head_kv = k->ne[2]; + + const bool measured_gen = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || + backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X || + backend_ctx->adreno_gen == ADRENO_GPU_GEN::X1E; + + if (n_q < 2) { + return false; + } + if (q->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 || + k->type != GGML_TYPE_F16 || v->type != GGML_TYPE_F16) { + return false; + } + if (q->ne[3] != 1 || k->ne[3] != 1 || v->ne[3] != 1 || dst->ne[3] != 1) { + return false; + } + if (n_head_kv <= 0 || n_head < n_head_kv || n_head % n_head_kv != 0) { + return false; + } + if (k->nb[0] != ggml_type_size(k->type) || v->nb[0] != ggml_type_size(v->type)) { + return false; + } + // K and Q must be packed [dk, head, row], as the KV cache and the permuted Q + // are. mul_mat sends the KQ to the image KQ kernel only for this layout; + // other K views can reach the KQV image kernel there and give wrong results. + if (k->nb[2] != (size_t) dk * sizeof(ggml_fp16_t) || k->nb[1] != (size_t) dk * n_head_kv * sizeof(ggml_fp16_t) || + q->nb[0] != sizeof(float) || q->nb[2] != (size_t) dk * sizeof(float) || q->nb[1] != (size_t) dk * n_head * sizeof(float)) { + return false; + } + + // soft_max applies scale, mask, ALiBi and sinks, but not the softcap. + float scale; + float max_bias; + float logit_softcap; + memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float)); + memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float)); + memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float)); + if (logit_softcap != 0.0f) { + return false; + } + + // The deferred softmax kernel needs an f16 mask and rows that divide by 4. + if (mask == nullptr || mask->type != GGML_TYPE_F16 || mask->ne[0] < n_kv || (n_kv % 4) != 0) { + return false; + } + + const std::pair dk_dv = {(int) dk, (int) dv}; + if (backend_ctx->fa.v_transpose_f16.count(dk_dv) == 0) { + return false; + } + + static const char * p8_env = getenv("GGML_OPENCL_FA_KQ_P8"); + const bool kq_p8 = (!p8_env || p8_env[0] != '0') && measured_gen && + backend_ctx->kernel_mul_mm_f16_f32_kq_p8 != nullptr && + backend_ctx->kernel_mul_mm_q8_f32_kqv != nullptr && + backend_ctx->kernel_fa_v_transpose_q8 != nullptr && + n_kv <= INT_MAX - 64 && k->nb[1] <= INT_MAX && + (n_kv % 64) == 0 && (dk % 16) == 0 && (dv % 64) == 0 && + mask->ne[2] == 1 && mask->ne[3] == 1 && mask->nb[0] == sizeof(ggml_fp16_t) && + (mask->nb[1] % sizeof(ggml_fp16_t)) == 0 && + k->nb[1] * n_kv / 16 <= backend_ctx->image_max_buffer_size; + + // Keep DK64 with attention sinks opt-in until its accuracy is validated. + const bool dk64_ok = kq_p8 && dst->src[4] == nullptr && n_head / n_head_kv >= 2 && + n_kv >= 1024 && n_q <= n_kv / 2; + const int min_dk = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E ? (dk64_ok ? 64 : 128) : 256; + if (env != 1 && !(measured_gen && dk >= min_dk)) { + return false; + } + + static const char * direct_env = getenv("GGML_OPENCL_FA_KQV_DIRECT"); + const bool kqv_direct = (!direct_env || direct_env[0] != '0') && kq_p8 && + backend_ctx->kernel_fa_kqv_direct_f16 != nullptr && backend_ctx->kernel_fa_kqv_direct_reduce != nullptr && + v->ne[1] == n_kv && v->ne[2] == n_head_kv && + n_q <= 32 / (n_head / n_head_kv) && dv >= 128 && dv <= INT_MAX && (dv % 128) == 0 && + n_head <= INT_MAX / (n_q * dv) && (v->nb[1] % 4) == 0 && (v->nb[2] % 4) == 0; + const bool small_p8 = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && + kq_p8 && dk >= 128 && n_kv >= 1024; + // Small batches without direct PV need P8 and a long KV cache on X2E. + if (n_q < 32 && !kqv_direct && !small_p8) { + return false; + } + + // Chunk size: a byte budget for KQ, at least 8 tiles of 32 queries so the + // GEMMs get usable shapes, and below the image1d_buffer limit of the KQ dst. + static const size_t budget_bytes = []{ + const char * e = getenv("GGML_OPENCL_FA_DECOMPOSE_MB"); + const int mb = (e && e[0]) ? atoi(e) : 256; + return (size_t)(mb > 0 ? mb : 256) * 1024 * 1024; + }(); + + const size_t kq_row_bytes = (size_t) n_kv * n_head * sizeof(float); + int64_t n_q_chunk = MIN((int64_t)(budget_bytes / kq_row_bytes), n_q); + n_q_chunk = MAX(n_q_chunk, MIN((int64_t) 8 * 32, n_q)); + + if (!kq_p8) { + n_q_chunk = MIN(n_q_chunk, (int64_t)(backend_ctx->image_max_buffer_size / (n_kv * n_head))); + } + if (n_q_chunk < 32 && n_q_chunk < n_q) { + return false; + } + + // even out the chunks, then align to the 32-wide n-tile + const int64_t n_chunks = (n_q + n_q_chunk - 1) / n_q_chunk; + n_q_chunk = MIN(n_q_chunk, ((n_q + n_chunks - 1) / n_chunks + 31) & ~(int64_t) 31); + + if (kq_p8) { + ggml_cl_flash_attn_decompose_kq_p8(backend, q, k, dst, n_q_chunk, scale, max_bias, kqv_direct); + } else { + ggml_cl_flash_attn_decompose(backend, q, k, dst, n_q_chunk, scale, max_bias); + } + return true; +} + static void ggml_cl_flash_attn(ggml_backend_t backend, const ggml_tensor * q, const ggml_tensor * k, ggml_tensor * dst) { const ggml_tensor * v = dst->src[2]; const ggml_tensor * mask = dst->src[3]; @@ -22808,15 +23509,23 @@ static void ggml_cl_flash_attn(ggml_backend_t backend, const ggml_tensor * q, co ((d_head_q == 256 && (mq_gqa == 2 || mq_gqa == 6)) || (d_head_q == 512 && (mq_gqa == 2 || mq_gqa == 16)) || (d_head_q == 128 && mq_gqa == 16 && backend_ctx->has_subgroup_shuffle)); - const bool mq_decode_shape = backend_ctx->gpu_family == ADRENO && is_mixed && n_q == 1 && - d_head_q == d_head_v && n_head_kv > 0 && n_head % n_head_kv == 0 && - ((((d_head_q == 64 && mq_gqa == 8) || (d_head_q == 128 && mq_gqa == 4)) && - backend_ctx->has_subgroup_shuffle) || - ((d_head_q == 256 || d_head_q == 512) && (mq_gqa == 4 || mq_gqa == 8)) || - mq_decode_x2e); - if (mq_decode_shape && n_kv >= 32) { + const bool mq_decode_kernel = backend_ctx->gpu_family == ADRENO && is_mixed && + d_head_q == d_head_v && n_head_kv > 0 && n_head % n_head_kv == 0 && + ((((d_head_q == 64 && mq_gqa == 8) || (d_head_q == 128 && mq_gqa == 4)) && + backend_ctx->has_subgroup_shuffle) || + ((d_head_q == 256 || d_head_q == 512) && (mq_gqa == 4 || mq_gqa == 8)) || + mq_decode_x2e); + const bool mq_decode_shape = mq_decode_kernel && n_q == 1; + // compile on the first call for this shape (the warmup is a prefill), not on the first decode + if (mq_decode_kernel) { ggml_opencl_ensure_fa_f32_f16_mq_decode(backend_ctx, d_head_q, d_head_v, mq_gqa); } + + // after all lazy compiles, so the decode kernels are built during warmup as on the fused path + if (n_q > 1 && ggml_cl_flash_attn_decompose_dispatch(backend, q, k, dst)) { + return; + } + const bool use_native_q8_0_q1 = is_q8_0 && n_q == 1 && backend_ctx->fa.f32_q8_0_q1.count(dk_dv) > 0; // Native q8_0 prefill — reads q8_0 directly, wg_size = cfg->bm. @@ -24641,7 +25350,8 @@ static void ggml_cl_mul_mat_q4_0_f32_adreno_ila(ggml_backend_t backend, const gg CL_CHECK(clReleaseMemObject(b_sub_buf)); CL_CHECK(clReleaseMemObject(b_img)); } else { - const int gemm_tile_n = 64; + const bool have_a8 = backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin != nullptr; + const int gemm_tile_n = have_a8 ? 64 : 32; int N_pad = (N + gemm_tile_n - 1) & ~(gemm_tile_n - 1); cl_mem a_img = extra0_q4_0->q_img; @@ -24741,6 +25451,53 @@ static void ggml_cl_mul_mat_q4_0_f32_adreno_ila(ggml_backend_t backend, const gg cl_mem b_img; CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + int line_stride_matrix_A_in_bytes = M * 4; + int line_stride_matrix_S_in_bytes = M * 2; + int line_stride_matrix_B_in_bytes = K * 4; + int line_stride_matrix_C_in_bytes = M * 4; + + const int b_offset_for_kernel = 0; + + if (!have_a8) { + const int c_offset_for_kernel = (int)offsetd; + + kernel = backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin; + + cl_uint k_arg = 0; + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &a_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_0->d)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &b_offset_for_kernel)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &c_offset_for_kernel)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_matrix_A_in_bytes)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_matrix_S_in_bytes)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_matrix_B_in_bytes)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_matrix_C_in_bytes)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &N)); + + size_t m_tiles = (size_t)CEIL_DIV(M, 64); + if ((m_tiles % 2) != 0) { + // keep the work-group count in y even so every work-group is full + m_tiles += 1; + } + + size_t local_work_size[3] = { 64, 2, 4 }; + size_t global_work_size[3] = { 64, m_tiles, (size_t)CEIL_DIV(N_pad, gemm_tile_n) }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_img)); + if (b_sub_buf) { + CL_CHECK(clReleaseMemObject(b_sub_buf)); + } + if (b_padded) { + CL_CHECK(clReleaseMemObject(b_padded)); + } + return; + } + region.origin = offsetd; region.size = (size_t)M * N * sizeof(float); cl_mem d_sub_buf; @@ -24754,13 +25511,7 @@ static void ggml_cl_mul_mat_q4_0_f32_adreno_ila(ggml_backend_t backend, const gg cl_mem d_img; CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - int line_stride_matrix_A_in_bytes = M * 4; - int line_stride_matrix_S_in_bytes = M * 2; - int line_stride_matrix_B_in_bytes = K * 4; - int line_stride_matrix_C_in_bytes = M * 4; - - int c_offset_for_kernel = 0; - int b_offset_for_kernel = 0; + const int c_offset_for_kernel = 0; kernel = backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin; @@ -24780,19 +25531,19 @@ static void ggml_cl_mul_mat_q4_0_f32_adreno_ila(ggml_backend_t backend, const gg CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &N)); size_t local_work_size[3] = { 64, 2, 2 }; - size_t m_tiles = (size_t)CEIL_DIV(M, 64); - size_t global_work_size[3] = { 64, m_tiles, (size_t)CEIL_DIV(N_pad, gemm_tile_n) }; + size_t global_work_size[3] = { 64, (size_t)CEIL_DIV(M, 64), (size_t)CEIL_DIV(N_pad, gemm_tile_n) }; backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + CL_CHECK(clReleaseMemObject(d_img)); + CL_CHECK(clReleaseMemObject(d_sub_buf)); CL_CHECK(clReleaseMemObject(b_img)); + if (b_sub_buf) { CL_CHECK(clReleaseMemObject(b_sub_buf)); } if (b_padded) { CL_CHECK(clReleaseMemObject(b_padded)); } - CL_CHECK(clReleaseMemObject(d_img)); - CL_CHECK(clReleaseMemObject(d_sub_buf)); } } #endif // GGML_OPENCL_USE_ADRENO_KERNELS @@ -37176,68 +37927,6 @@ static void ggml_cl_set(ggml_backend_t backend, const ggml_tensor * src0, const backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); } -static void ggml_cl_diag_mask_inf(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src1); - - int n_past = ((int32_t *)(dst->op_params))[0]; - - const int ne00 = src0 ? src0->ne[0] : 0; - const int ne01 = src0 ? src0->ne[1] : 0; - const int ne02 = src0 ? src0->ne[2] : 0; - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - cl_kernel kernel; - - if (ne00%8 == 0) { - kernel = backend_ctx->kernel_diag_mask_inf_8; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &n_past)); - - size_t global_work_size[] = {(size_t)ne00*ne01*ne02/8, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } else { - kernel = backend_ctx->kernel_diag_mask_inf; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &n_past)); - - size_t global_work_size[] = {(size_t)ne00, (size_t)ne01, (size_t)ne02}; - size_t local_work_size[] = {64, 1, 1}; - - size_t * local_work_size_ptr = local_work_size; - if (ne00 % 64 != 0 && !backend_ctx->non_uniform_workgroups) { - local_work_size_ptr = nullptr; // Let driver choose the work-group sizes. - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); - } -} - static void ggml_cl_diag(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { GGML_ASSERT(src0); GGML_ASSERT(src0->extra); @@ -37409,6 +38098,102 @@ static void ggml_cl_soft_max(ggml_backend_t backend, const ggml_tensor * src0, c backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); } +// Softmax for the decomposed flash attention: like ggml_cl_soft_max, but dst keeps +// exp(x - max) and the row sums go to `sums`, one float per (row, head). src2 is the +// optional sinks tensor. +static void ggml_cl_fa_decompose_soft_max(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst, cl_mem sums) { + GGML_ASSERT(src0 && src0->extra); + GGML_ASSERT(src1 && src1->extra && src1->type == GGML_TYPE_F16); + GGML_ASSERT(dst && dst->extra); + GGML_ASSERT(sums != nullptr); + GGML_ASSERT(src0->ne[0] % 4 == 0); + + if (src2) { + GGML_ASSERT(src2->extra); + } + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extra2 = src2 ? (ggml_tensor_extra_cl *)src2->extra : nullptr; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offset2 = extra2 ? extra2->offset + src2->view_offs : offset0; + cl_ulong offsetd = extrad->offset + dst->view_offs; + cl_ulong offsets = 0; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + const int ne03 = src0->ne[3]; + + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + const cl_ulong nb03 = src0->nb[3]; + + const int ne12 = src1->ne[2]; + const int ne13 = src1->ne[3]; + + const cl_ulong nb11 = src1->nb[1]; + const cl_ulong nb12 = src1->nb[2]; + const cl_ulong nb13 = src1->nb[3]; + + const cl_ulong nb1 = dst->nb[1]; + const cl_ulong nb2 = dst->nb[2]; + const cl_ulong nb3 = dst->nb[3]; + + float scale, max_bias; + memcpy(&scale, dst->op_params + 0, sizeof(float)); + memcpy(&max_bias, dst->op_params + 1, sizeof(float)); + + const int n_head = src0->ne[2]; + const int n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head)); + + const float m0 = powf(2.0f, -(max_bias ) / n_head_log2); + const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2); + + // one wave per row, same as ggml_cl_soft_max on Adreno + const int nth = 64; + + cl_kernel kernel = backend_ctx->kernel_fa_decompose_soft_max_4_f16; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), extra2 ? &extra2->data_device : &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_mem), &sums)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &offsets)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne13)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb3)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(float), &max_bias)); + CL_CHECK(clSetKernelArg(kernel, 24, sizeof(float), &m0)); + CL_CHECK(clSetKernelArg(kernel, 25, sizeof(float), &m1)); + CL_CHECK(clSetKernelArg(kernel, 26, sizeof(int), &n_head_log2)); + + size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + static void ggml_cl_rope(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { GGML_ASSERT(src0); GGML_ASSERT(src0->extra); @@ -39067,12 +39852,6 @@ bool ggml_cl_compute_forward(ggml_backend_t backend, struct ggml_tensor * tensor } func = ggml_cl_diag; break; - case GGML_OP_DIAG_MASK_INF: - if (!any_on_device) { - return false; - } - func = ggml_cl_diag_mask_inf; - break; case GGML_OP_SOFT_MAX: if (!any_on_device) { return false; diff --git a/ggml/src/ggml-opencl/kernels/diag_mask_inf.cl b/ggml/src/ggml-opencl/kernels/diag_mask_inf.cl deleted file mode 100644 index 36eff0439fa7..000000000000 --- a/ggml/src/ggml-opencl/kernels/diag_mask_inf.cl +++ /dev/null @@ -1,58 +0,0 @@ -#pragma OPENCL EXTENSION cl_khr_fp16 : enable - -//------------------------------------------------------------------------------ -// diag_mask_inf kernels -//------------------------------------------------------------------------------ -kernel void kernel_diag_mask_inf( - global float * src0, - ulong offset0, - global float * dst, - ulong offsetd, - int ne00, - int ne01, - int n_past -) { - src0 = (global float*)((global char*)src0 + offset0); - dst = (global float*)((global char*)dst + offsetd); - - int i02 = get_global_id(2); - int i01 = get_global_id(1); - int i00 = get_global_id(0); - - if (i00 > n_past + i01) { - dst[i02*ne01*ne00 + i01*ne00 + i00] = -INFINITY; - } else { - dst[i02*ne01*ne00 + i01*ne00 + i00] = src0[i02*ne01*ne00 + i01*ne00 + i00]; - } -} - -kernel void kernel_diag_mask_inf_8( - global float4 * src0, - ulong offset0, - global float4 * dst, - ulong offsetd, - int ne00, - int ne01, - int n_past -) { - src0 = (global float4*)((global char*)src0 + offset0); - dst = (global float4*)((global char*)dst + offsetd); - - int i = 2*get_global_id(0); - - dst[i+0] = src0[i+0]; - dst[i+1] = src0[i+1]; - int i4 = 4*i; - int i02 = i4/(ne00*ne01); i4 -= i02*ne00*ne01; - int i01 = i4/(ne00); i4 -= i01*ne00; - int i00 = i4; - for (int k = 3; k >= 0; --k) { - if (i00 + 4 + k <= n_past + i01) { - break; - } - (&dst[i+1])[k] = -INFINITY; - if (i00 + k > n_past + i01) { - (&dst[i])[k] = -INFINITY; - } - } -} diff --git a/ggml/src/ggml-opencl/kernels/flash_attn_pre_f16.cl b/ggml/src/ggml-opencl/kernels/flash_attn_pre_f16.cl index 88ead4bcb513..74aa67b08367 100644 --- a/ggml/src/ggml-opencl/kernels/flash_attn_pre_f16.cl +++ b/ggml/src/ggml-opencl/kernels/flash_attn_pre_f16.cl @@ -154,3 +154,123 @@ __kernel void flash_attn_blk_f16( blk[((ulong) mask_slice * (ulong) n_q_blocks + (ulong) q_block_idx) * (ulong) n_kv_blocks + (ulong) kv_block_idx] = res; } + +// V^T for the decomposed flash attention: [dv, n_kv, n_head_kv] (strided) -> [n_kv, dv, n_head_kv] +// (contiguous). This is the layout the Adreno KQV image GEMM reads. A local tile keeps both the +// read and the write coalesced, and the +1 column avoids bank conflicts. +#define FA_VT_TILE 32 +#define FA_VT_ROWS 8 +__kernel void flash_attn_v_transpose_f16( + const global void * v_void, ulong v_offset, + global void * vt_void, + const int n_kv, + const int dv, + const int n_head_kv, + const ulong v_nb1, + const ulong v_nb2 +) { + __local half tile[FA_VT_TILE][FA_VT_TILE + 1]; + + const int d0 = get_group_id(0) * FA_VT_TILE; + const int k0 = get_group_id(1) * FA_VT_TILE; + const int head_kv_idx = get_group_id(2); + + const int lx = get_local_id(0); + const int ly = get_local_id(1); + + const global char * v_head = (const global char *) v_void + v_offset + (ulong) head_kv_idx * v_nb2; + + for (int r = 0; r < FA_VT_TILE; r += FA_VT_ROWS) { + const int d = d0 + lx; + const int kv = k0 + ly + r; + half val = (half) 0.0f; + if (d < dv && kv < n_kv) { + val = ((const global half *) (v_head + (ulong) kv * v_nb1))[d]; + } + tile[ly + r][lx] = val; + } + + barrier(CLK_LOCAL_MEM_FENCE); + + global half * vt_head = (global half *) vt_void + (ulong) head_kv_idx * (ulong) n_kv * (ulong) dv; + + for (int r = 0; r < FA_VT_TILE; r += FA_VT_ROWS) { + const int kv = k0 + lx; + const int d = d0 + ly + r; + if (d < dv && kv < n_kv) { + vt_head[(ulong) d * (ulong) n_kv + (ulong) kv] = tile[lx][ly + r]; + } + } +} + +// Transpose V and quantize each block of 32 KV rows for the int8 KQV GEMM. +__kernel void flash_attn_v_transpose_q8( + const global void * v_void, ulong v_offset, + global void * vt_q_void, // char, [n_head_kv][dv][kv_pitch] + global void * vt_d_void, // half, [n_head_kv][dv][kv_pitch/32] + const int n_kv, + const int dv, + const int n_head_kv, + const ulong v_nb1, + const ulong v_nb2, + const ulong v_nb3, + const int kv_pitch // bytes per V^T row, >= n_kv, multiple of 32 +) { + __local half tile[FA_VT_TILE][FA_VT_TILE + 1]; + + const int d0 = get_group_id(0) * FA_VT_TILE; + const int k0 = get_group_id(1) * FA_VT_TILE; + const int head_kv_idx = get_group_id(2) % n_head_kv; + const int batch_idx = get_group_id(2) / n_head_kv; + + const int lx = get_local_id(0); + const int ly = get_local_id(1); + + const global char * v_head = (const global char *) v_void + v_offset + + (ulong) batch_idx * v_nb3 + (ulong) head_kv_idx * v_nb2; + + for (int r = 0; r < FA_VT_TILE; r += FA_VT_ROWS) { + const int d = d0 + lx; + const int kv = k0 + ly + r; + half val = (half) 0.0f; + if (d < dv && kv < n_kv) { + val = ((const global half *) (v_head + (ulong) kv * v_nb1))[d]; + } + tile[ly + r][lx] = val; + } + + barrier(CLK_LOCAL_MEM_FENCE); + + const int lid = ly * FA_VT_TILE + lx; + const int nblk = kv_pitch / FA_VT_TILE; + + if (lid < FA_VT_TILE) { + const int d = d0 + lid; + if (d < dv) { + const ulong hbase = ((ulong) batch_idx * (ulong) n_head_kv + (ulong) head_kv_idx); + + global char * qrow = (global char *) vt_q_void + hbase*(ulong)kv_pitch*(ulong)dv + (ulong) d * (ulong) kv_pitch; + global half * drow = (global half *) vt_d_void + hbase*(ulong)nblk*(ulong)dv + (ulong) d * (ulong) nblk; + + float v[FA_VT_TILE]; + float amax = 0.0f; + + for (int i = 0; i < FA_VT_TILE; ++i) { + v[i] = (float) tile[i][lid]; + amax = fmax(amax, fabs(v[i])); + } + + const float dq = amax / 127.0f; + const float id = amax > 0.0f ? 127.0f / amax : 0.0f; + + drow[k0 / FA_VT_TILE] = (half) dq; + + for (int i = 0; i < FA_VT_TILE; ++i) { + const int kv = k0 + i; + if (kv < n_kv) { + qrow[kv] = (char) clamp((int) rint(v[i] * id), -127, 127); + } + } + } + } +} diff --git a/ggml/src/ggml-opencl/kernels/flash_attn_pv_direct.cl b/ggml/src/ggml-opencl/kernels/flash_attn_pv_direct.cl new file mode 100644 index 000000000000..201fe444359d --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/flash_attn_pv_direct.cl @@ -0,0 +1,106 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_khr_subgroups : enable +#pragma OPENCL EXTENSION cl_qcom_reqd_sub_group_size : enable + +#define FA_KQVD_MAXC 32 + +// Read F16 V in its cache layout. Share each V row across the queries and heads of one KV group. +// P8 and its block scales are expanded in local memory; KV splits write separate partial sums. +__attribute__((qcom_reqd_sub_group_size("half"))) +kernel void kernel_fa_kqv_direct_f16( + global const char * v, + ulong off_v, + ulong v_nb1, + ulong v_nb2, + global const uchar * pq, + global const float * pd, + global float * part, // [split][head][n_q][dv] + int dv, + int n_q, + int gqa, + int n_head, + int nblk, + int blk_per_split, + int p_pitch +) { + const int lid = get_local_id(0); + const int d = get_group_id(0)*128 + lid*2; + const int head_kv = get_group_id(1); + const int split = get_group_id(2); + const int ncol = n_q*gqa; + const int b0 = split*blk_per_split; + const int b1 = min(b0 + blk_per_split, nblk); + const int nbp = p_pitch / 32; + + __local float sh_p[32][FA_KQVD_MAXC]; + + float2 acc[FA_KQVD_MAXC]; + #pragma unroll + for (int c = 0; c < FA_KQVD_MAXC; ++c) { + acc[c] = (float2)(0.0f); + } + + global const char * vbase = v + off_v + (size_t)head_kv*v_nb2 + (size_t)d*sizeof(half); + + for (int b = b0; b < b1; ++b) { + barrier(CLK_LOCAL_MEM_FENCE); + // Each lane expands 16 KV entries for one column. + const int c = lid % FA_KQVD_MAXC; + const int r0 = (lid / FA_KQVD_MAXC)*16; + float16 f = (float16)(0.0f); + if (c < ncol) { + const int n = c / gqa; + const int h = head_kv*gqa + c % gqa; + const size_t row = (size_t)h*n_q + n; + const float sc = pd[row*nbp + b]; + const uchar16 u = vload16(0, pq + row*p_pitch + (size_t)b*32 + r0); + f = convert_float16(u)*sc; + } + sh_p[r0+ 0][c] = f.s0; sh_p[r0+ 1][c] = f.s1; sh_p[r0+ 2][c] = f.s2; sh_p[r0+ 3][c] = f.s3; + sh_p[r0+ 4][c] = f.s4; sh_p[r0+ 5][c] = f.s5; sh_p[r0+ 6][c] = f.s6; sh_p[r0+ 7][c] = f.s7; + sh_p[r0+ 8][c] = f.s8; sh_p[r0+ 9][c] = f.s9; sh_p[r0+10][c] = f.sa; sh_p[r0+11][c] = f.sb; + sh_p[r0+12][c] = f.sc; sh_p[r0+13][c] = f.sd; sh_p[r0+14][c] = f.se; sh_p[r0+15][c] = f.sf; + barrier(CLK_LOCAL_MEM_FENCE); + + global const char * vr = vbase + (size_t)b*32*v_nb1; + for (int r = 0; r < 32; ++r) { + const float2 x = vload_half2(0, (global const half *)(vr + (size_t)r*v_nb1)); + #pragma unroll + for (int c = 0; c < FA_KQVD_MAXC; c += 4) { + if (c < ncol) { + const float4 pv = vload4(0, &sh_p[r][c]); + acc[c+0] = mad((float2)(pv.x), x, acc[c+0]); + acc[c+1] = mad((float2)(pv.y), x, acc[c+1]); + acc[c+2] = mad((float2)(pv.z), x, acc[c+2]); + acc[c+3] = mad((float2)(pv.w), x, acc[c+3]); + } + } + } + } + + #pragma unroll + for (int c = 0; c < FA_KQVD_MAXC; ++c) { + if (c < ncol) { + const int n = c / gqa; + const int h = head_kv*gqa + c % gqa; + vstore2(acc[c], 0, part + (((size_t)split*n_head + h)*n_q + n)*dv + d); + } + } +} + +kernel void kernel_fa_kqv_direct_reduce( + global const float * part, + global float * dst, + int n_elem, + int n_split +) { + const int i = get_global_id(0); + if (i >= n_elem) { + return; + } + float s = 0.0f; + for (int k = 0; k < n_split; ++k) { + s += part[(size_t)k*n_elem + i]; + } + dst[i] = s; +} diff --git a/ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_kq_p8.cl b/ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_kq_p8.cl new file mode 100644 index 000000000000..2c0a56c855c7 --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_kq_p8.cl @@ -0,0 +1,250 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_khr_subgroups : enable + +#define LM_FIRST_256B 0 +#define LM_SECOND_256B 64 +#define LM_THIRD_256B 128 +#define LM_FOURTH_256B 192 + + +inline float16 mm_load_a( + image1d_buffer_t matrix_A, + uint subMatrixAStartInElements, + int line_stride_matrix_A_in_bytes +) { + __private float8 regA; + size_t sub_block_id_m = get_local_id(0); + + uint a_texCoord = subMatrixAStartInElements/2 + (sub_block_id_m * line_stride_matrix_A_in_bytes/4); + + regA.s0123 = read_imagef(matrix_A, a_texCoord/4); + regA.s4567 = read_imagef(matrix_A, (a_texCoord+4)/4); + + return convert_float16(as_half16(regA)); +} + +inline float4 alu_32( + float16 regA, + __local float4 * matrix_B_vec +) { + + __private float4 rC = 0; + int i = get_sub_group_id() * 64; + + rC += regA.s0 * matrix_B_vec[i]; + rC += regA.s1 * matrix_B_vec[i + 16]; + rC += regA.s4 * matrix_B_vec[i + 1]; + rC += regA.s5 * matrix_B_vec[i + 17]; + rC += regA.s8 * matrix_B_vec[i + 2]; + rC += regA.s9 * matrix_B_vec[i + 18]; + rC += regA.sc * matrix_B_vec[i + 3]; + rC += regA.sd * matrix_B_vec[i + 19]; + + i += 32; + + rC += regA.s2 * matrix_B_vec[i]; + rC += regA.s3 * matrix_B_vec[i + 16]; + rC += regA.s6 * matrix_B_vec[i + 1]; + rC += regA.s7 * matrix_B_vec[i + 17]; + rC += regA.sa * matrix_B_vec[i + 2]; + rC += regA.sb * matrix_B_vec[i + 18]; + rC += regA.se * matrix_B_vec[i + 3]; + rC += regA.sf * matrix_B_vec[i + 19]; + + return rC; +} + +inline float16 alu_16( + float16 regA, + __local float * matrix_B_local +) { + float16 out; + __local float4 * matrix_B_vec = (__local float4*)matrix_B_local; + + out.s0123 = alu_32(regA, matrix_B_vec); + out.s4567 = alu_32(regA, matrix_B_vec + 4); + out.s89ab = alu_32(regA, matrix_B_vec + 8); + out.scdef = alu_32(regA, matrix_B_vec + 12); + + return out; +} + +inline void mm_mad( + __local float * matrix_B_local, + float16 regA, + float8 regB, + uint b_localOffsetInWords, + float16 * regC0_ptr, + float16 * regC1_ptr +) { + int offset = b_localOffsetInWords + get_sub_group_id() * 256; + + matrix_B_local[offset + LM_FIRST_256B] = regB.s0; + matrix_B_local[offset + LM_SECOND_256B] = regB.s1; + matrix_B_local[offset + LM_THIRD_256B] = regB.s2; + matrix_B_local[offset + LM_FOURTH_256B] = regB.s3; + + float16 add0 = alu_16(regA, matrix_B_local); + *regC0_ptr += add0; + + matrix_B_local[offset + LM_FIRST_256B] = regB.s4; + matrix_B_local[offset + LM_SECOND_256B] = regB.s5; + matrix_B_local[offset + LM_THIRD_256B] = regB.s6; + matrix_B_local[offset + LM_FOURTH_256B] = regB.s7; + + float16 add1 = alu_16(regA, matrix_B_local); + *regC1_ptr += add1; +} + +#define TILESIZE_K 16 +#define TILESIZE_M 64 +#define TILESIZE_N 32 +// Fuse KQ and block softmax into U8 P, block maxima and sums. No F32 score matrix is stored. +__kernel void mul_mm_f16_f32_kq_p8( + __read_only image1d_buffer_t matrix_A, + __global float * matrix_B, + __global uchar * qp, // u8 P, [D_B][N][p_pitch] + __global float * bmax, // per 32-row block max, [D_B][N][p_pitch/32] + __global float * bsum, // per block sum of exp(s - bmax), [D_B][N][p_pitch/32] + __global char * mask, // f16 [>=M][N] view (chunk rows), row stride mask_nb1 bytes + ulong offset_mask, + ulong mask_nb1, + float scale, + float max_bias, + float m0, + float m1, + int n_head_log2, + int M, + int K, + int N, + int D_A, + int D_B, + int p_pitch // bytes per P row, >= M, multiple of 32 +) { + + // Match the n-tile-first grid in ggml_cl_fa_kq_p8_dispatch. + const uint m_blocks = (M+TILESIZE_M-1)/TILESIZE_M; + uint block_id_n = get_global_id(1); + uint block_id_m = get_global_id(2) % m_blocks; + uint block_id_d = get_global_id(2) / m_blocks; + + __private float16 regA; + __private float8 regB; + __private float16 regC0 = (float16)(0.0f); + __private float16 regC1 = (float16)(0.0f); + + const uint col = block_id_m * TILESIZE_M; + const uint row = block_id_n * TILESIZE_N; + const uint depth_A = block_id_d / (D_B/D_A); + const uint depth_B = block_id_d; + + int line_stride_matrix_A_in_bytes = K * D_A * 2; + int line_stride_matrix_B_in_bytes = K * D_B * 4; + + const uint strideAinElements = line_stride_matrix_A_in_bytes / 2; + const uint strideBinElements = line_stride_matrix_B_in_bytes / 4; + + size_t sub_block_id_m = get_local_id(0); + + uint b_localOffsetInWords = (sub_block_id_m/16)*16 + + ((((sub_block_id_m)>>0)&1)<<2) + + ((((sub_block_id_m)>>1)&1)<<3) + + ((((sub_block_id_m)>>2)&1)<<0) + + ((((sub_block_id_m)>>3)&1)<<1); + + uint2 b_globalOffsetInWords_xy = {((sub_block_id_m%4)*4), (sub_block_id_m>>2)}; + uint subMatrixAStartInElements = col * strideAinElements + depth_A * K; + uint subMatrixBStartInElements = 0; + + __local float matrix_B_local[1024]; + + // Clamp Q loads in the last tile; columns past N are not stored. + const uint c0 = min(row + b_globalOffsetInWords_xy.y, (uint)N - 1); + const uint c1 = min(row + b_globalOffsetInWords_xy.y + 16, (uint)N - 1); + const uint b_globalOffsetInWords00 = c0*strideBinElements + depth_B*K + b_globalOffsetInWords_xy.x; + const uint b_globalOffsetInWords16 = c1*strideBinElements + depth_B*K + b_globalOffsetInWords_xy.x; + + for (uint step=0; step < K; step+=TILESIZE_K) { + regA = mm_load_a(matrix_A, subMatrixAStartInElements, line_stride_matrix_A_in_bytes); + + uint b_coordInWords00 = subMatrixBStartInElements + b_globalOffsetInWords00; + uint b_coordInWords16 = subMatrixBStartInElements + b_globalOffsetInWords16; + + regB.s0123 = vload4(b_coordInWords00/4, matrix_B); + regB.s4567 = vload4(b_coordInWords16/4, matrix_B); + + mm_mad(matrix_B_local, regA, regB, b_localOffsetInWords, ®C0, ®C1); + + subMatrixAStartInElements += TILESIZE_K; + subMatrixBStartInElements += TILESIZE_K; + } + + // Transpose each score tile in local memory so one lane owns a 32-row softmax block. + __local float p8_lds[2048]; + __local float * lds = p8_lds + get_sub_group_id() * 1024; + const uint lane = get_local_id(0); + __global const half * mrow = (__global const half *)(mask + offset_mask); + const uint mstride = (uint)(mask_nb1 / 2); + const int nblk = p_pitch / 32; + + #pragma unroll + for (int half_ = 0; half_ < 2; ++half_) { + barrier(CLK_LOCAL_MEM_FENCE); + const float16 cc = half_ == 0 ? regC0 : regC1; + lds[ 0*64 + lane] = cc.s0; lds[ 1*64 + lane] = cc.s1; lds[ 2*64 + lane] = cc.s2; lds[ 3*64 + lane] = cc.s3; + lds[ 4*64 + lane] = cc.s4; lds[ 5*64 + lane] = cc.s5; lds[ 6*64 + lane] = cc.s6; lds[ 7*64 + lane] = cc.s7; + lds[ 8*64 + lane] = cc.s8; lds[ 9*64 + lane] = cc.s9; lds[10*64 + lane] = cc.sa; lds[11*64 + lane] = cc.sb; + lds[12*64 + lane] = cc.sc; lds[13*64 + lane] = cc.sd; lds[14*64 + lane] = cc.se; lds[15*64 + lane] = cc.sf; + barrier(CLK_LOCAL_MEM_FENCE); + if (lane < 32) { + const int j = lane >> 1; + const int b = lane & 1; + const uint n = row + half_*16 + j; + const uint h = depth_B; + if (n < (uint)N) { + float slope = 1.0f; + if (max_bias > 0.0f) { + const float base = (int)h < n_head_log2 ? m0 : m1; + const int ex = (int)h < n_head_log2 ? (int)h + 1 : 2*((int)h - n_head_log2) + 1; + slope = pow(base, ex); + } + const uint kvb = col + b*32; // first kv row of this block + const __local float * src = lds + j*64 + b*32; + float16 s0 = vload16(0, src); + float16 s1 = vload16(1, src); + const __global half * mp = mrow + (size_t)n*mstride + kvb; + const float16 m0v = convert_float16(vload16(0, mp)); + const float16 m1v = convert_float16(vload16(1, mp)); + s0 = s0*scale + slope*m0v; + s1 = s1*scale + slope*m1v; + const float16 mx16 = fmax(s0, s1); + const float8 mx8 = fmax(mx16.lo, mx16.hi); + const float4 mx4 = fmax(mx8.lo, mx8.hi); + const float2 mx2 = fmax(mx4.lo, mx4.hi); + const float amax = fmax(mx2.x, mx2.y); + const uint prow = h*(uint)N + n; + const uint blk = kvb >> 5; + float sum = 0.0f; + uchar16 q0 = (uchar16)(0); + uchar16 q1 = (uchar16)(0); + // Use a finite sentinel: -cl-finite-math-only can remove infinity checks. + if (amax > -1.0e30f) { + const float16 e0 = exp(s0 - amax); + const float16 e1 = exp(s1 - amax); + const float16 a16 = e0 + e1; + const float8 a8 = a16.lo + a16.hi; + const float4 a4 = a8.lo + a8.hi; + const float2 a2 = a4.lo + a4.hi; + sum = a2.x + a2.y; + q0 = convert_uchar16_sat_rte(e0*255.0f); + q1 = convert_uchar16_sat_rte(e1*255.0f); + } + __global uchar * qdst = qp + (size_t)prow*(size_t)p_pitch + (size_t)kvb; + vstore16(q0, 0, qdst); + vstore16(q1, 1, qdst); + bmax[(size_t)prow*nblk + blk] = amax; + bsum[(size_t)prow*nblk + blk] = sum; + } + } + } +} diff --git a/ggml/src/ggml-opencl/kernels/mul_mm_q8_f32_kqv.cl b/ggml/src/ggml-opencl/kernels/mul_mm_q8_f32_kqv.cl new file mode 100644 index 000000000000..08d80961ca88 --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/mul_mm_q8_f32_kqv.cl @@ -0,0 +1,131 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_khr_subgroups : enable +#ifdef cl_khr_integer_dot_product +#pragma OPENCL EXTENSION cl_khr_integer_dot_product : enable +#endif + +// Multiply U8 P by S8 V^T, with one scale per 32 KV entries. +// Group query heads by KV head to share V^T in L2. +// The packed dot takes the V word (registers) first: swapped operands miscompile on Adreno. + +#define KQV_TM 64 // d rows per workgroup, one per lane +#ifndef KQV_TN +#define KQV_TN 32 // queries per workgroup, all owned by every lane +#endif +#ifndef KQV_NB +#define KQV_NB 8 // 32-blocks of P staged per barrier +#endif +#define KQV_WG 64 + +__attribute__((qcom_wave_pair_mode(1))) +kernel void kernel_mul_mm_q8_f32_kqv( + global const uint * vq, // V^T int8, [head_kv][dv][kv_pitch] as packed uints + ulong off_vq, + global const half * vd, // V^T scales, [head_kv][dv][kv_pitch/32] + ulong off_vd, + global const uint * pq, // P u8, [head][n_q][kv_pitch] as packed uints + ulong off_pq, + global const float * pd, // P scales f32, [head][n_q][kv_pitch/32] + ulong off_pd, + global float * dst, // [head][n_q][dv] + ulong off_dst, + int dv, + int n_kv, + int n_q, + int n_head, + int n_head_kv, + int kv_pitch // bytes per V^T row and per P row, >= n_kv, multiple of 32 +) { + vq = (global const uint *)((global const char *)vq + off_vq); + vd = (global const half *)((global const char *)vd + off_vd); + pq = (global const uint *)((global const char *)pq + off_pq); + pd = (global const float *)((global const char *)pd + off_pd); + dst = (global float *)((global const char *)dst + off_dst); + + const int lid = get_local_id(0); + const int gsz = n_head / n_head_kv; // query heads per KV head + const int g1 = get_group_id(1); + const int head_kv = get_group_id(2); + const int head = head_kv*gsz + (g1 % gsz); + const int qn0 = (g1 / gsz) * KQV_TN; // first query of this tile + const int d = get_group_id(0)*KQV_TM + lid; // this lane's d row + + const int nblk = n_kv / 32; // dispatch guarantees n_kv % 32 == 0 + const int nu = kv_pitch / 4; // uints per row + const int nbp = kv_pitch / 32; // scales per row + + __local uint sh_pq[KQV_TN][KQV_NB][8]; + __local float sh_pd[KQV_TN][KQV_NB]; + + float acc[KQV_TN]; + #pragma unroll + for (int t = 0; t < KQV_TN; ++t) { + acc[t] = 0.0f; + } + + const int dl = min(d, dv - 1); // clamp so a tail lane loads in bounds + const size_t vbase = ((size_t)head_kv*dv + dl)*nu; + const size_t vdbas = ((size_t)head_kv*dv + dl)*nbp; + const size_t pbase = (size_t)head*n_q; + + for (int bg = 0; bg < nblk; bg += KQV_NB) { + const int nb_here = min(KQV_NB, nblk - bg); + + // stage P: each (query, block) is 8 uints = two 16-byte loads + for (int i = lid; i < KQV_TN*KQV_NB*2; i += KQV_WG) { + const int t = i / (KQV_NB*2); + const int bb = (i / 2) % KQV_NB; + const int h = (i & 1) * 4; + const int qi = qn0 + t; + uint4 v = (uint4)(0u); + if (qi < n_q && bb < nb_here) { + v = vload4(0, &pq[(pbase + qi)*nu + (size_t)(bg + bb)*8 + h]); + } + vstore4(v, 0, &sh_pq[t][bb][h]); + } + for (int i = lid; i < KQV_TN*KQV_NB; i += KQV_WG) { + const int t = i / KQV_NB; + const int bb = i % KQV_NB; + const int qi = qn0 + t; + sh_pd[t][bb] = (qi < n_q && bb < nb_here) + ? pd[(pbase + qi)*nbp + bg + bb] : 0.0f; + } + barrier(CLK_LOCAL_MEM_FENCE); + + for (int bb = 0; bb < nb_here; ++bb) { + const uint4 w0 = vload4(0, &vq[vbase + (size_t)(bg + bb)*8]); + const uint4 w1 = vload4(0, &vq[vbase + (size_t)(bg + bb)*8 + 4]); + const float dvs = (float)vd[vdbas + bg + bb]; + + #pragma unroll + for (int t = 0; t < KQV_TN; ++t) { + const uint4 a0 = vload4(0, &sh_pq[t][bb][0]); + const uint4 a1 = vload4(0, &sh_pq[t][bb][4]); + int raw = 0; + raw = dot_acc_sat_4x8packed_su_int(w0.s0, a0.s0, raw); + raw = dot_acc_sat_4x8packed_su_int(w0.s1, a0.s1, raw); + raw = dot_acc_sat_4x8packed_su_int(w0.s2, a0.s2, raw); + raw = dot_acc_sat_4x8packed_su_int(w0.s3, a0.s3, raw); + raw = dot_acc_sat_4x8packed_su_int(w1.s0, a1.s0, raw); + raw = dot_acc_sat_4x8packed_su_int(w1.s1, a1.s1, raw); + raw = dot_acc_sat_4x8packed_su_int(w1.s2, a1.s2, raw); + raw = dot_acc_sat_4x8packed_su_int(w1.s3, a1.s3, raw); + acc[t] += dvs * sh_pd[t][bb] * (float)raw; + } + } + barrier(CLK_LOCAL_MEM_FENCE); + } + + if (d >= dv) { + return; + } + + // dst is [head][n_q][dv] with dv contiguous, so the 64 lanes of a d-block write contiguously + #pragma unroll + for (int t = 0; t < KQV_TN; ++t) { + const int qi = qn0 + t; + if (qi < n_q) { + dst[(pbase + qi)*dv + d] = acc[t]; + } + } +} diff --git a/ggml/src/ggml-opencl/kernels/softmax_4_f16.cl b/ggml/src/ggml-opencl/kernels/softmax_4_f16.cl index 571d16507c6f..8dfc5519de52 100644 --- a/ggml/src/ggml-opencl/kernels/softmax_4_f16.cl +++ b/ggml/src/ggml-opencl/kernels/softmax_4_f16.cl @@ -106,3 +106,176 @@ kernel void kernel_soft_max_4_f16( pdst4[i00] /= sum; } } + +// Same as kernel_soft_max_4_f16, but leaves exp(x - max) in dst and writes the row sum to psums. +// The decomposed flash attention applies 1/sum to the KQV result, which is much smaller than P. +#ifdef ADRENO_GPU +REQD_SUBGROUP_SIZE_64 +#endif +kernel void kernel_fa_decompose_soft_max_4_f16( + global char * src0, + ulong offset0, + global char * src1, + ulong offset1, + global char * src2, + ulong offset2, + global char * dst, + ulong offsetd, + global char * psums, + ulong offset_sums, + int ne00, + ulong nb01, + ulong nb02, + ulong nb03, + int ne12, + int ne13, + ulong nb11, + ulong nb12, + ulong nb13, + ulong nb1, + ulong nb2, + ulong nb3, + float scale, + float max_bias, + float m0, + float m1, + int n_head_log2 +) { + src0 = src0 + offset0; + src1 = src1 + offset1; + src2 = src2 + offset2; + dst = dst + offsetd; + + int i03 = get_group_id(2); + int i02 = get_group_id(1); + int i01 = get_group_id(0); + + int i13 = i03%ne13; + int i12 = i02%ne12; + int i11 = i01; + + global float4 * psrc4 = (global float4 *)(src0 + i01*nb01 + i02*nb02 + i03*nb03); + global half4 * pmask = src1 != src0 ? (global half4 *)(src1 + i11*nb11 + i12*nb12 + i13*nb13) : 0; + global float * psrc2 = src2 != src0 ? (global float *)(src2) : 0; + global float4 * pdst4 = (global float4 *)(dst + i01*nb1 + i02*nb2 + i03*nb3); + + float slope = 1.0f; + + // ALiBi + if (max_bias > 0.0f) { + int h = i02; + + float base = h < n_head_log2 ? m0 : m1; + int exp = h < n_head_log2 ? h + 1 : 2*(h - n_head_log2) + 1; + + slope = pow(base, exp); + } + + // parallel max + float4 lmax4 = psrc2 ? psrc2[i02] : -INFINITY; + for (int i00 = get_local_id(0); i00 < ne00/4; i00 += get_local_size(0)) { + lmax4 = fmax(lmax4, psrc4[i00]*scale + slope*(pmask ? convert_float4(pmask[i00]) : 0.0f)); + } + float lmax = fmax(fmax(lmax4.s0, lmax4.s1), fmax(lmax4.s2, lmax4.s3)); + + float max = sub_group_reduce_max(lmax); + // Avoid -inf - (-inf) for fully masked rows. + if (max == -INFINITY) { + max = 0.0f; + } + + // parallel sum + float4 lsum4 = 0.0f; + for (int i00 = get_local_id(0); i00 < ne00/4; i00 += get_local_size(0)) { + const float4 exp_psrc4 = exp((psrc4[i00]*scale + slope*(pmask ? convert_float4(pmask[i00]) : 0.0f)) - max); + lsum4 += exp_psrc4; + pdst4[i00] = exp_psrc4; + } + float lsum = lsum4.s0 + lsum4.s1 + lsum4.s2 + lsum4.s3; + + float sum = sub_group_reduce_add(lsum); + + if (psrc2) { + sum += exp(psrc2[i02] - max); + } + + if (get_local_id(0) == 0) { + global float * sums = (global float *)(psums + offset_sums); + sums[(i03*get_num_groups(1) + i02)*get_num_groups(0) + i01] = sum; + } +} + +// out[:, n, h] *= 1/sums[h*ne1 + n], out is [dv, ne1, n_head] contiguous. +kernel void kernel_fa_decompose_scale_rows_f32( + global char * dst, + ulong offsetd, + global char * psums, + ulong offset_sums, + int dv, + int ne1 +) { + global float * out = (global float *)(dst + offsetd); + global float * sums = (global float *)(psums + offset_sums); + + const int n = get_group_id(0); + const int h = get_group_id(1); + + const float s = sums[h*ne1 + n]; + const float r = s > 0.0f ? 1.0f/s : 0.0f; + + global float * row = out + ((size_t)h*ne1 + n)*dv; + for (int i = get_local_id(0); i < dv; i += get_local_size(0)) { + row[i] *= r; + } +} + +// Merge the P8 block maxima and sums into F32 block scales and row sums. +#ifdef ADRENO_GPU +REQD_SUBGROUP_SIZE_64 +#endif +kernel void kernel_fa_p8_fixup( + global float * bmax, + global float * bsum, + global float * dp, + global float * psums, + global char * sinks, + ulong offset_sinks, + int has_sinks, + int nblk, + int row_blk, // blocks per row of bmax/bsum/dp (the padded pitch), >= nblk + int N +) { + const int n = get_group_id(0); + const int head = get_group_id(1); + const uint row = (uint)head*(uint)N + (uint)n; + global float * bm = bmax + (size_t)row*row_blk; + global float * bs = bsum + (size_t)row*row_blk; + global float * dr = dp + (size_t)row*row_blk; + + float lmax = -INFINITY; + for (int b = get_local_id(0); b < nblk; b += get_local_size(0)) { + lmax = fmax(lmax, bm[b]); + } + float rowmax = sub_group_reduce_max(lmax); + float sink = 0.0f; + if (has_sinks) { + sink = ((global float *)(sinks + offset_sinks))[head]; + rowmax = fmax(rowmax, sink); + } + + float lsum = 0.0f; + for (int b = get_local_id(0); b < nblk; b += get_local_size(0)) { + const float m = bm[b]; + // Use a finite sentinel: -cl-finite-math-only can remove infinity checks. + const float f = (m > -1.0e30f && rowmax > -1.0e30f) ? exp(m - rowmax) : 0.0f; + dr[b] = f / 255.0f; + lsum += bs[b]*f; + } + float sum = sub_group_reduce_add(lsum); + if (has_sinks && rowmax > -1.0e30f) { + sum += exp(sink - rowmax); + } + if (get_local_id(0) == 0) { + psums[row] = sum; + } +} diff --git a/ggml/src/ggml-openvino/openvino/op_table.cpp b/ggml/src/ggml-openvino/openvino/op_table.cpp index 23b3a2cff3ea..857fbf175ebc 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.cpp +++ b/ggml/src/ggml-openvino/openvino/op_table.cpp @@ -33,7 +33,6 @@ std::unordered_map get_supported_ops() { using namespace ov::op; return { {"GGML_OP_ADD", op::translate_add }, - {"GGML_OP_ADD1", op::translate_1to1_match_2_inputs }, {"GGML_OP_ADD_ID", op::translate_add_id }, {"GGML_OP_CONCAT", op::translate_concat }, {"GGML_OP_CONT", op::translate_cont }, diff --git a/ggml/src/ggml-sycl/CMakeLists.txt b/ggml/src/ggml-sycl/CMakeLists.txt index 35d36e583734..8312a83052ca 100644 --- a/ggml/src/ggml-sycl/CMakeLists.txt +++ b/ggml/src/ggml-sycl/CMakeLists.txt @@ -221,7 +221,7 @@ if (GGML_SYCL_TARGET STREQUAL "INTEL") if (NOT GGML_SYCL_DEVICE_ARCH) target_link_options(ggml-sycl PRIVATE -Xs -ze-intel-greater-than-4GB-buffer-required) else() - message(STATUS "Skipping -ze-intel-greater-than-4GB-buffer-required for spir64_gen AOT") + message(STATUS "spir64_gen AOT: -ze-intel-greater-than-4GB-buffer-required passed to ocloc") endif() # Link against Intel oneMKL @@ -251,7 +251,7 @@ if (GGML_SYCL_DEVICE_ARCH) target_compile_options( ggml-sycl PRIVATE -fsycl-targets=spir64_gen - "SHELL:-Xsycl-target-backend=spir64_gen \"-device ${GGML_SYCL_DEVICE_ARCH}\"" + "SHELL:-Xsycl-target-backend=spir64_gen \"-device ${GGML_SYCL_DEVICE_ARCH} -options -ze-intel-greater-than-4GB-buffer-required\"" ) # Pass through parallel job (process) count for parallelising the @@ -266,7 +266,7 @@ if (GGML_SYCL_DEVICE_ARCH) target_link_options( ggml-sycl PRIVATE -fsycl-targets=spir64_gen - "SHELL:-Xsycl-target-backend=spir64_gen \"-device ${GGML_SYCL_DEVICE_ARCH}\"" + "SHELL:-Xsycl-target-backend=spir64_gen \"-device ${GGML_SYCL_DEVICE_ARCH} -options -ze-intel-greater-than-4GB-buffer-required\"" -fsycl-max-parallel-link-jobs=${GGML_SYCL_MAX_PARALLEL_LINK_JOBS} ) diff --git a/ggml/src/ggml-sycl/common.hpp b/ggml/src/ggml-sycl/common.hpp index 99da9713e1f1..f19b0631d32a 100644 --- a/ggml/src/ggml-sycl/common.hpp +++ b/ggml/src/ggml-sycl/common.hpp @@ -47,6 +47,7 @@ namespace syclexp = sycl::ext::oneapi::experimental; #if GGML_SYCL_DNNL #include "dnnl.hpp" #include "dnnl_sycl.hpp" +#include "oneapi/dnnl/dnnl_graph.hpp" #endif #define GGML_COMMON_DECL_SYCL @@ -237,9 +238,9 @@ typedef sycl::float2 dfloat2; #define MMVQ_MAX_BATCH_SIZE 8 -#if defined(__INTEL_LLVM_COMPILER) && __has_include() +#if defined(GGML_SYCL_SUPPORT_XMX) && defined(__INTEL_LLVM_COMPILER) && __has_include() # define GGML_SYCL_MMVQ_HAS_XMX -#endif // __INTEL_LLVM_COMPILER +#endif // GGML_SYCL_SUPPORT_XMX && __INTEL_LLVM_COMPILER // default of the most columns the XMX mul_mat_vec_q handles (GGML_SYCL_XMX_MAX_COLS), wider batches use other kernels #define GGML_SYCL_XMX_MAX_COLS_DEFAULT 80 @@ -484,6 +485,16 @@ struct ggml_sycl_graph { static_assert(std::is_trivial::value, "node_properties must be trivial"); #endif +#if GGML_SYCL_DNNL +struct sdpa_partition { + dnnl::graph::compiled_partition cp; + std::vector ins; + dnnl::graph::logical_tensor out; + size_t id_q = 0, id_k = 0, id_v = 0, id_scale = 0, id_mask = 0; + bool ok = false; +}; +#endif + struct ggml_backend_sycl_context { int device; std::string name; @@ -552,6 +563,8 @@ struct ggml_backend_sycl_context { dnnl::stream stream_dnnl() { return stream_dnnl(device, 0); } + + std::unordered_map sdpa_partitions; #endif // pool diff --git a/ggml/src/ggml-sycl/esimd.hpp b/ggml/src/ggml-sycl/esimd.hpp index 85cc93e21ef1..568173e7a9df 100644 --- a/ggml/src/ggml-sycl/esimd.hpp +++ b/ggml/src/ggml-sycl/esimd.hpp @@ -2,11 +2,14 @@ #define GGML_SYCL_ESIMD_HPP #include -#include #include #include "common.hpp" +#ifdef GGML_SYCL_MMVQ_HAS_XMX +#include +#endif + namespace ggml_sycl_esimd { constexpr int GGML_SYCL_DMMV_ESIMD_WG_SIZE = 4; @@ -586,6 +589,7 @@ template <> struct esimd_reorder_q_traits { } }; + // // Multi-column mul_mat_vec for reordered K-quant weights on the XMX engines (int8 DPAS). // A thread owns 16 weight rows (B operand, one dword is 4 weights of a row), the q8_1 activation @@ -1024,6 +1028,7 @@ template constexpr int xmx_grf() { return FUSED || NC >= T::nc_wide ? 256 : 128; } +#ifdef GGML_SYCL_MMVQ_HAS_XMX // One DPAS of a block of RC columns: the int32 products of the weights B and the activations A, as float and scaled // per weight row. Every quant type sums one or two of these per group of 32. template @@ -1394,6 +1399,8 @@ static void xmx_mul_mat_ncols(const void * vx, } } +#endif // GGML_SYCL_MMVQ_HAS_XMX + } // namespace ggml_sycl_esimd #endif // GGML_SYCL_ESIMD_HPP diff --git a/ggml/src/ggml-sycl/fattn-onednn.cpp b/ggml/src/ggml-sycl/fattn-onednn.cpp index bd7ce8936d69..66ff32f15eaf 100644 --- a/ggml/src/ggml-sycl/fattn-onednn.cpp +++ b/ggml/src/ggml-sycl/fattn-onednn.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -25,6 +26,20 @@ bool ggml_sycl_fattn_onednn_binds_kv(const ggml_tensor * K, const ggml_tensor * return bindable(K) && bindable(V); } +#if GGML_SYCL_DNNL +// per device: set once a oneDNN SDPA execute throws, so dispatch stops picking oneDNN there +static std::atomic g_ggml_sycl_fa_onednn_failed[GGML_SYCL_MAX_DEVICES] = {}; +#endif + +bool ggml_sycl_flash_attn_ext_onednn_failed(int device) { +#if GGML_SYCL_DNNL + return g_ggml_sycl_fa_onednn_failed[device].load(std::memory_order_relaxed); +#else + GGML_UNUSED(device); + return false; +#endif +} + bool ggml_sycl_flash_attn_ext_onednn_supported(const ggml_tensor * dst, bool use_shape_limit) { #if !GGML_SYCL_DNNL GGML_UNUSED(dst); @@ -146,14 +161,6 @@ static void permute_sdpa_out_sycl(const sycl::half * out, float * dst, }); } -struct sdpa_partition { - compiled_partition cp; - std::vector ins; - logical_tensor out; - size_t id_q = 0, id_k = 0, id_v = 0, id_scale = 0, id_mask = 0; - bool ok = false; -}; - // Build + compile the contiguous-input GQA SDPA graph (MatMul->Divide->Add->SoftMax->MatMul), f32 out. // Mirrors the hardware-verified scratch/onednn_sdpa_probe.cpp build_gqa (partitions=1, sdp_primitive_kernel_t). static sdpa_partition build_sdpa(const engine & eng, int H, int Hkv, int q, int seq, int d, @@ -361,17 +368,16 @@ void ggml_sycl_flash_attn_ext_onednn(ggml_backend_sycl_context & ctx, ggml_tenso outf_ptr = outf_pool->get(); } - // compile once per (device, shape, KV strides), reuse across layers/calls. Stride 2 always - // repeats stride 1 and stride 4 is always 1, so the key covers every entry that can differ. - static std::unordered_map cache; + // compile once per (shape, KV strides) in this device's context, reuse across layers/calls. Stride 2 + // always repeats stride 1 and stride 4 is always 1, so the key covers every entry that can differ. char keyb[256]; - snprintf(keyb, sizeof(keyb), "%d:%lld:%lld:%lld:%lld:%lld:%lld:%lld:%lld:%lld:%lld:%lld", ggml_sycl_get_device(), + snprintf(keyb, sizeof(keyb), "%lld:%lld:%lld:%lld:%lld:%lld:%lld:%lld:%lld:%lld:%lld", (long long) H, (long long) Hkv, (long long) q, (long long) seq, (long long) d, (long long) k_str[0], (long long) k_str[1], (long long) k_str[3], (long long) v_str[0], (long long) v_str[1], (long long) v_str[3]); - auto it = cache.find(keyb); - if (it == cache.end()) { - it = cache.emplace(keyb, build_sdpa(eng, (int) H, (int) Hkv, (int) q, (int) seq, (int) d, k_str, v_str)).first; + auto it = ctx.sdpa_partitions.find(keyb); + if (it == ctx.sdpa_partitions.end()) { + it = ctx.sdpa_partitions.emplace(keyb, build_sdpa(eng, (int) H, (int) Hkv, (int) q, (int) seq, (int) d, k_str, v_str)).first; } sdpa_partition & E = it->second; if (!E.ok) { @@ -407,8 +413,10 @@ void ggml_sycl_flash_attn_ext_onednn(ggml_backend_sycl_context & ctx, ggml_tenso } } catch (const std::exception & e) { - // any oneDNN/SYCL failure is non-fatal: fall back to the existing kernel (strictly additive). - GGML_LOG_WARN("%s: oneDNN SDPA failed (%s); falling back to TILE kernel\n", __func__, e.what()); + // any oneDNN/SYCL failure is non-fatal: warn once, stop picking oneDNN on this device, run TILE instead + if (!g_ggml_sycl_fa_onednn_failed[ctx.device].exchange(true)) { + GGML_LOG_WARN("%s: oneDNN SDPA failed (%s); falling back to TILE kernel\n", __func__, e.what()); + } ggml_sycl_flash_attn_ext_tile(ctx, dst); } diff --git a/ggml/src/ggml-sycl/fattn-onednn.hpp b/ggml/src/ggml-sycl/fattn-onednn.hpp index 9669d1bd27a6..4756b240a76a 100644 --- a/ggml/src/ggml-sycl/fattn-onednn.hpp +++ b/ggml/src/ggml-sycl/fattn-onednn.hpp @@ -7,6 +7,10 @@ // (f16 KV, no softcap/ALiBi, single stream, tuned head_dim, prefill-sized q.) bool ggml_sycl_flash_attn_ext_onednn_supported(const ggml_tensor * dst, bool use_shape_limit = true); +// True once a oneDNN SDPA execute has failed on this device. Not part of _supported(): that also sizes the +// FA scratch buffer, and a size that depends on runtime state can come out smaller than a later call needs. +bool ggml_sycl_flash_attn_ext_onednn_failed(int device); + // True when the oneDNN path binds an F16 KV cache in place instead of staging a dense copy of // it. Depends only on the types and strides of K and V, so the answer holds for every call. bool ggml_sycl_fattn_onednn_binds_kv(const ggml_tensor * K, const ggml_tensor * V); diff --git a/ggml/src/ggml-sycl/fattn.cpp b/ggml/src/ggml-sycl/fattn.cpp index 6f5f8a832951..525e6fd8c095 100644 --- a/ggml/src/ggml-sycl/fattn.cpp +++ b/ggml/src/ggml-sycl/fattn.cpp @@ -134,7 +134,7 @@ static best_fattn_kernel ggml_sycl_get_best_fattn_kernel(const int device, const // XMX-accelerated path: oneDNN SDPA (native F16 and dequant+non-F16). // ONEDNN requires min 32 query tokens — short-circuit decode to avoid // calling _supported() on every decode FA call. - if (Q->ne[1] >= 32 + if (Q->ne[1] >= 32 && !ggml_sycl_flash_attn_ext_onednn_failed(device) && ggml_sycl_flash_attn_ext_onednn_supported(dst)) { return BEST_FATTN_KERNEL_ONEDNN; } @@ -259,7 +259,7 @@ static best_fattn_kernel ggml_sycl_get_best_fattn_kernel(const int device, const // Fused-XMX path: oneDNN Graph SDPA (flash attention). Strictly // additive -- taken only when statically supported, otherwise falls through to VEC/TILE below. - if (ggml_sycl_flash_attn_ext_onednn_supported(dst)) { + if (!ggml_sycl_flash_attn_ext_onednn_failed(device) && ggml_sycl_flash_attn_ext_onednn_supported(dst)) { return BEST_FATTN_KERNEL_ONEDNN; } diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp index f634a7f1c6ff..fdd526425c40 100644 --- a/ggml/src/ggml-sycl/ggml-sycl.cpp +++ b/ggml/src/ggml-sycl/ggml-sycl.cpp @@ -2517,23 +2517,6 @@ k_argsort_f32_i32(const float *x, int *dst, const int ncols, int ncols_pad, } } -static void diag_mask_inf_f32(const float * x, float * dst, const int ncols, const int rows_per_channel, const int n_past, - const sycl::nd_item<3> &item_ct1) { - const int col = item_ct1.get_local_range(1) * item_ct1.get_group(1) + - item_ct1.get_local_id(1); - const int row = item_ct1.get_local_range(2) * item_ct1.get_group(2) + - item_ct1.get_local_id(2); - - if (col >= ncols) { - return; - } - - const int i = row*ncols + col; - //dst[i] = col > (n_past + row % rows_per_channel) ? -INFINITY : x[i]; - //dst[i] = x[i] - (col > n_past + row % rows_per_channel) * INT_MAX; // equivalent within rounding error but slightly faster on GPU - dst[i] = x[i] - (col > n_past + row % rows_per_channel) * FLT_MAX; -} - static void scale_f32(const float * x, float * dst, const float scale, const float bias, const int k, const sycl::nd_item<3> &item_ct1) { const int i = item_ct1.get_local_range(2) * item_ct1.get_group(2) + @@ -3139,20 +3122,6 @@ static void argmax_f32_i32_sycl(const float *x, int *dst, const int ncols, }); }); } -static void diag_mask_inf_f32_sycl(const float *x, float *dst, - const int ncols_x, const int nrows_x, - const int rows_per_channel, const int n_past, - queue_ptr stream) { - const sycl::range<3> block_dims(1, SYCL_DIAG_MASK_INF_BLOCK_SIZE, 1); - const int block_num_x = (ncols_x + SYCL_DIAG_MASK_INF_BLOCK_SIZE - 1) / SYCL_DIAG_MASK_INF_BLOCK_SIZE; - const sycl::range<3> block_nums(1, block_num_x, nrows_x); - stream->parallel_for(sycl::nd_range<3>(block_nums * block_dims, block_dims), - [=](sycl::nd_item<3> item_ct1) { - diag_mask_inf_f32(x, dst, ncols_x, - rows_per_channel, n_past, - item_ct1); - }); -} static dpct::err0 ggml_sycl_cpy_tensor_2d(void *dst, const struct ggml_tensor *src, @@ -3536,25 +3505,6 @@ inline void ggml_sycl_op_argmax(ggml_backend_sycl_context & ctx, ggml_tensor * d argmax_f32_i32_sycl(src0_dd, dst_dd, ncols, nrows, main_stream); } -inline void ggml_sycl_op_diag_mask_inf(ggml_backend_sycl_context & ctx, ggml_tensor * dst) { - GGML_ASSERT(dst->src[0]->type == GGML_TYPE_F32); - GGML_ASSERT( dst->type == GGML_TYPE_F32); - dpct::queue_ptr main_stream = ctx.stream(); - SYCL_CHECK(ggml_sycl_set_device(ctx.device)); - const float * src0_dd = static_cast(dst->src[0]->data); - float * dst_dd = static_cast(dst->data); - - const int64_t ne00 = dst->src[0]->ne[0]; - const int64_t ne01 = dst->src[0]->ne[1]; - const int nrows0 = ggml_nrows(dst->src[0]); - // the kernel indexes in 32-bit - GGML_ASSERT(ne00 * nrows0 <= INT32_MAX); - - const int n_past = ((int32_t *) dst->op_params)[0]; - - diag_mask_inf_f32_sycl(src0_dd, dst_dd, ne00, nrows0, ne01, n_past, main_stream); -} - static void tri_f32_sycl( const float * src, float * dst, @@ -6045,11 +5995,6 @@ static void ggml_sycl_scale(ggml_backend_sycl_context & ctx, ggml_tensor * dst) ggml_sycl_op_scale(ctx, dst); } -static void ggml_sycl_diag_mask_inf(ggml_backend_sycl_context & ctx, ggml_tensor * dst) { - scope_op_debug_print scope_dbg_print(__func__, dst, /*num_src=*/1); - ggml_sycl_op_diag_mask_inf(ctx, dst); -} - static void ggml_sycl_pool2d(ggml_backend_sycl_context & ctx, ggml_tensor * dst) { scope_op_debug_print scope_dbg_print(__func__, dst, /*num_src=*/1); ggml_sycl_op_pool2d(ctx, dst); @@ -6112,7 +6057,7 @@ static void ggml_sycl_argmax(ggml_backend_sycl_context & ctx, ggml_tensor * dst) static void ggml_sycl_set_main_device(const int main_device) try { - if (dpct::get_current_device_id() == static_cast (main_device)) { + if (get_current_device_id() == main_device) { return; } check_allow_gpu_index(main_device); @@ -6193,7 +6138,6 @@ static bool ggml_sycl_compute_forward(ggml_backend_sycl_context & ctx, struct gg ggml_sycl_dup(ctx, dst); break; case GGML_OP_ADD: - case GGML_OP_ADD1: // TODO: more efficient implementation ggml_sycl_add(ctx, dst); break; case GGML_OP_ADD_ID: @@ -6396,9 +6340,6 @@ static bool ggml_sycl_compute_forward(ggml_backend_sycl_context & ctx, struct gg case GGML_OP_TRI: ggml_sycl_op_tri(ctx, dst); break; - case GGML_OP_DIAG_MASK_INF: - ggml_sycl_diag_mask_inf(ctx, dst); - break; case GGML_OP_SOFT_MAX: ggml_sycl_op_soft_max(ctx, dst); break; @@ -7639,7 +7580,6 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons case GGML_OP_PERMUTE: case GGML_OP_TRANSPOSE: case GGML_OP_ADD: - case GGML_OP_ADD1: case GGML_OP_ADD_ID: case GGML_OP_SUB: case GGML_OP_COUNT_EQUAL: @@ -7674,8 +7614,6 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons op->type == GGML_TYPE_F32 && ggml_is_contiguous(src0); } - case GGML_OP_DIAG_MASK_INF: - return true; case GGML_OP_SOFT_MAX: return true; case GGML_OP_SOFT_MAX_BACK: { diff --git a/ggml/src/ggml-sycl/presets.hpp b/ggml/src/ggml-sycl/presets.hpp index eeb803ca125a..e9fa6c8a6b12 100644 --- a/ggml/src/ggml-sycl/presets.hpp +++ b/ggml/src/ggml-sycl/presets.hpp @@ -35,7 +35,6 @@ #define SYCL_SCALE_BLOCK_SIZE 256 #define SYCL_ROPE_BLOCK_SIZE 256 #define SYCL_ALIBI_BLOCK_SIZE 32 -#define SYCL_DIAG_MASK_INF_BLOCK_SIZE 32 #define SYCL_QUANTIZE_BLOCK_SIZE 256 #define SYCL_DEQUANTIZE_BLOCK_SIZE 256 #define SYCL_GET_ROWS_BLOCK_SIZE 256 diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-buffers.cpp b/ggml/src/ggml-vulkan/ggml-vulkan-buffers.cpp index 3e04eef618e7..9c6edb569cbf 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-buffers.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan-buffers.cpp @@ -404,6 +404,33 @@ void ggml_vk_ensure_sync_staging_buffer(ggml_backend_vk_context * ctx, size_t si } } +static vk_context ggml_vk_begin_sync_ctx(vk_device & device, vk_command_pool & pool) { + vk_context subctx = ggml_vk_create_temporary_context(pool); + ggml_vk_ctx_begin(device, subctx); + return subctx; +} + +static void ggml_vk_submit_sync(vk_device & device, vk_context & subctx) { + ggml_vk_ctx_end(subctx); + + for (auto & cpy : subctx->in_memcpys) { + memcpy(cpy.dst, cpy.src, cpy.n); + } + + for (auto & mset : subctx->memsets) { + memset(mset.dst, mset.val, mset.n); + } + + ggml_vk_submit(subctx, device->fence); + VK_CHECK(device->device.waitForFences({ device->fence }, true, UINT64_MAX), "vk_submit_sync waitForFences", device); + device->device.resetFences({ device->fence }); + ggml_vk_queue_command_pools_cleanup(device); + + for (auto & cpy : subctx->out_memcpys) { + memcpy(cpy.dst, cpy.src, cpy.n); + } +} + static void ggml_vk_buffer_write_nc_async(ggml_backend_vk_context * ctx, vk_context& subctx, vk_buffer& dst, size_t offset, const ggml_tensor * tensor, bool sync_staging = false) { VK_LOG_DEBUG("ggml_vk_buffer_write_nc_async(" << tensor << ")"); GGML_ASSERT(!ggml_is_contiguous(tensor)); @@ -590,24 +617,10 @@ void ggml_vk_buffer_write_2d(vk_buffer& dst, size_t offset, const void * src, si } else { std::lock_guard guard(dst->device->mutex); - vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue->cmd_pool); - ggml_vk_ctx_begin(dst->device, subctx); + vk_context subctx = ggml_vk_begin_sync_ctx(dst->device, dst->device->transfer_queue->cmd_pool); bool ret = ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, spitch, dpitch, width, height, true); GGML_ASSERT(ret); - ggml_vk_ctx_end(subctx); - - for (auto& cpy : subctx->in_memcpys) { - memcpy(cpy.dst, cpy.src, cpy.n); - } - - for (auto& mset : subctx->memsets) { - memset(mset.dst, mset.val, mset.n); - } - - ggml_vk_submit(subctx, dst->device->fence); - VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences", dst->device); - dst->device->device.resetFences({ dst->device->fence }); - ggml_vk_queue_command_pools_cleanup(dst->device); + ggml_vk_submit_sync(dst->device, subctx); } } @@ -695,21 +708,24 @@ static bool ggml_vk_buffer_read_async(vk_context subctx, vk_buffer& src, size_t return ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, size, size, size, 1, sync_staging); } -void ggml_vk_buffer_read_2d(vk_buffer& src, size_t offset, void * dst, size_t spitch, size_t dpitch, size_t width, size_t height) { - VK_LOG_DEBUG("ggml_vk_buffer_read_2d(" << src->buffer << ", " << offset << ", " << width << ", " << height << ")"); - +static bool ggml_vk_buffer_host_read_direct(const vk_buffer & buf) { // If the device is not an UMA device the memory is host-accessible through rebar. While writing // through PCIe is sufficient fast reading back data from PCIe is slower than going through // the HW device to host copy path. // AMD UMA: uncached host-visible memory is write-combined, CPU reads are slow - const bool slow_host_read = src->device->vendor_id == VK_VENDOR_ID_AMD && - !(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCached); - if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible && src->device->uma && !slow_host_read) { + const bool slow_host_read = buf->device->vendor_id == VK_VENDOR_ID_AMD && + !(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCached); + return (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) && buf->device->uma && !slow_host_read; +} + +void ggml_vk_buffer_read_2d(vk_buffer& src, size_t offset, void * dst, size_t spitch, size_t dpitch, size_t width, size_t height) { + VK_LOG_DEBUG("ggml_vk_buffer_read_2d(" << src->buffer << ", " << offset << ", " << width << ", " << height << ")"); + + if (ggml_vk_buffer_host_read_direct(src)) { GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent); std::lock_guard guard(src->device->mutex); - vk_context subctx = ggml_vk_create_temporary_context(src->device->compute_queue->cmd_pool); - ggml_vk_ctx_begin(src->device, subctx); + vk_context subctx = ggml_vk_begin_sync_ctx(src->device, src->device->compute_queue->cmd_pool); subctx->s->buffer->buf.pipelineBarrier( vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eHost, @@ -717,12 +733,7 @@ void ggml_vk_buffer_read_2d(vk_buffer& src, size_t offset, void * dst, size_t sp { { vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferWrite, vk::AccessFlagBits::eHostRead } }, {}, {}); - ggml_vk_ctx_end(subctx); - ggml_vk_submit(subctx, src->device->fence); - VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), - "vk_buffer_read_2d uma waitForFences", src->device); - src->device->device.resetFences({ src->device->fence }); - ggml_vk_queue_command_pools_cleanup(src->device); + ggml_vk_submit_sync(src->device, subctx); if (width == spitch && width == dpitch) { memcpy(dst, (const uint8_t *) src->ptr + offset, width * height); @@ -734,20 +745,10 @@ void ggml_vk_buffer_read_2d(vk_buffer& src, size_t offset, void * dst, size_t sp } else { std::lock_guard guard(src->device->mutex); - vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue->cmd_pool); - ggml_vk_ctx_begin(src->device, subctx); + vk_context subctx = ggml_vk_begin_sync_ctx(src->device, src->device->transfer_queue->cmd_pool); bool ret = ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, spitch, dpitch, width, height, true); GGML_ASSERT(ret); - ggml_vk_ctx_end(subctx); - - ggml_vk_submit(subctx, src->device->fence); - VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_read_2d waitForFences", src->device); - src->device->device.resetFences({ src->device->fence }); - ggml_vk_queue_command_pools_cleanup(src->device); - - for (auto& cpy : subctx->out_memcpys) { - memcpy(cpy.dst, cpy.src, cpy.n); - } + ggml_vk_submit_sync(src->device, subctx); } } @@ -771,14 +772,9 @@ void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size std::lock_guard guard(src->device->mutex); VK_LOG_DEBUG("ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")"); // Copy within the device - vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue->cmd_pool); - ggml_vk_ctx_begin(src->device, subctx); + vk_context subctx = ggml_vk_begin_sync_ctx(src->device, src->device->transfer_queue->cmd_pool); ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size); - ggml_vk_ctx_end(subctx); - ggml_vk_submit(subctx, src->device->fence); - VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences", src->device); - src->device->device.resetFences({ src->device->fence }); - ggml_vk_queue_command_pools_cleanup(src->device); + ggml_vk_submit_sync(src->device, subctx); } else { VK_LOG_DEBUG("ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")"); // Copy device to device @@ -814,15 +810,222 @@ void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t siz } std::lock_guard guard(dst->device->mutex); - vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue->cmd_pool); - ggml_vk_ctx_begin(dst->device, subctx); + vk_context subctx = ggml_vk_begin_sync_ctx(dst->device, dst->device->transfer_queue->cmd_pool); subctx->s->buffer->buf.fillBuffer(dst->buffer, offset, size, c); - ggml_vk_ctx_end(subctx); + ggml_vk_submit_sync(dst->device, subctx); +} + +static size_t ggml_vk_staging_size_n(const vk_device & device, const std::vector & regions) { + size_t total = 0; + size_t max = 0; + for (const auto & r : regions) { + vk_buffer pinned; + size_t pinned_offset; + ggml_vk_host_get(device, r.host, pinned, pinned_offset); + if (pinned != nullptr) { + continue; + } + total += r.size; + max = std::max(max, r.size); + } + return std::max(max, std::min(total, (size_t) device->suballocation_block_size)); +} + +// returns number of regions recorded, stops when staging is full +size_t ggml_vk_buffer_write_n_async(vk_context& subctx, const vk_buffer_region * regions, size_t n, vk_buffer * staging, size_t * staging_offset) { + VK_LOG_DEBUG("ggml_vk_buffer_write_n_async(" << n << ")"); + ggml_vk_sync_buffers(nullptr, subctx); + + size_t i = 0; + for (; i < n; i++) { + const vk_buffer_region & r = regions[i]; + + vk_buffer pinned = nullptr; + size_t pinned_offset = 0; + ggml_vk_host_get(r.buf->device, r.host, pinned, pinned_offset); + + if (pinned != nullptr) { + subctx->s->buffer->buf.copyBuffer(pinned->buffer, r.buf->buffer, { vk::BufferCopy{ pinned_offset, r.offset, r.size } }); + continue; + } + + if (staging == nullptr || *staging_offset + r.size > (*staging)->size) { + break; + } + + subctx->s->buffer->buf.copyBuffer((*staging)->buffer, r.buf->buffer, { vk::BufferCopy{ *staging_offset, r.offset, r.size } }); + deferred_memcpy((uint8_t *) (*staging)->ptr + *staging_offset, r.host, r.size, &subctx->in_memcpys); + *staging_offset += r.size; + } + return i; +} + +// returns number of regions recorded, stops when staging is full +size_t ggml_vk_buffer_read_n_async(vk_context& subctx, const vk_buffer_region * regions, size_t n, vk_buffer * staging, size_t * staging_offset) { + VK_LOG_DEBUG("ggml_vk_buffer_read_n_async(" << n << ")"); + ggml_vk_sync_buffers(nullptr, subctx); + + size_t i = 0; + for (; i < n; i++) { + const vk_buffer_region & r = regions[i]; + + vk_buffer pinned = nullptr; + size_t pinned_offset = 0; + ggml_vk_host_get(r.buf->device, r.host, pinned, pinned_offset); + + if (pinned != nullptr) { + subctx->s->buffer->buf.copyBuffer(r.buf->buffer, pinned->buffer, { vk::BufferCopy{ r.offset, pinned_offset, r.size } }); + continue; + } + + if (staging == nullptr || *staging_offset + r.size > (*staging)->size) { + break; + } + + subctx->s->buffer->buf.copyBuffer(r.buf->buffer, (*staging)->buffer, { vk::BufferCopy{ r.offset, *staging_offset, r.size } }); + deferred_memcpy(r.host, (const uint8_t *) (*staging)->ptr + *staging_offset, r.size, &subctx->out_memcpys); + *staging_offset += r.size; + } + return i; +} + +void ggml_vk_buffer_copy_n_async(vk_context& subctx, const vk_buffer_copy_region * regions, size_t n) { + VK_LOG_DEBUG("ggml_vk_buffer_copy_n_async(" << n << ")"); + ggml_vk_sync_buffers(nullptr, subctx); + + for (size_t i = 0; i < n; i++) { + const vk_buffer_copy_region & r = regions[i]; + GGML_ASSERT(r.src->device == r.dst->device); + subctx->s->buffer->buf.copyBuffer(r.src->buffer, r.dst->buffer, { vk::BufferCopy{ r.src_offset, r.dst_offset, r.size } }); + } +} + +void ggml_vk_buffer_write_n(const vk_buffer_region * regions, size_t n) { + VK_LOG_DEBUG("ggml_vk_buffer_write_n(" << n << ")"); + std::vector pending; + + for (size_t i = 0; i < n; i++) { + const vk_buffer_region & r = regions[i]; + if (r.size == 0) { + continue; + } + if (r.buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) { + GGML_ASSERT(r.buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent); + memcpy((uint8_t *) r.buf->ptr + r.offset, r.host, r.size); + continue; + } + GGML_ASSERT(pending.empty() || r.buf->device == pending[0].buf->device); + pending.push_back(r); + } + + if (pending.empty()) { + return; + } + + vk_device device = pending[0].buf->device; + std::lock_guard guard(device->mutex); + const size_t staging_size = ggml_vk_staging_size_n(device, pending); + if (staging_size > 0) { + ggml_vk_ensure_sync_staging_buffer(device, staging_size); + } + + for (size_t i = 0; i < pending.size();) { + vk_context subctx = ggml_vk_begin_sync_ctx(device, device->transfer_queue->cmd_pool); + size_t staging_offset = 0; + const size_t recorded = ggml_vk_buffer_write_n_async(subctx, pending.data() + i, pending.size() - i, &device->sync_staging, &staging_offset); + GGML_ASSERT(recorded > 0); + ggml_vk_submit_sync(device, subctx); + i += recorded; + } +} + +void ggml_vk_buffer_read_n(const vk_buffer_region * regions, size_t n) { + VK_LOG_DEBUG("ggml_vk_buffer_read_n(" << n << ")"); + std::vector direct; + std::vector pending; + + for (size_t i = 0; i < n; i++) { + const vk_buffer_region & r = regions[i]; + if (r.size == 0) { + continue; + } + GGML_ASSERT((direct.empty() && pending.empty()) || r.buf->device == (direct.empty() ? pending[0] : direct[0]).buf->device); + if (ggml_vk_buffer_host_read_direct(r.buf)) { + GGML_ASSERT(r.buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent); + direct.push_back(r); + } else { + pending.push_back(r); + } + } + + if (direct.empty() && pending.empty()) { + return; + } + + vk_device device = (direct.empty() ? pending[0] : direct[0]).buf->device; + std::lock_guard guard(device->mutex); + + if (!direct.empty()) { + vk_context subctx = ggml_vk_begin_sync_ctx(device, device->compute_queue->cmd_pool); + subctx->s->buffer->buf.pipelineBarrier( + vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer, + vk::PipelineStageFlagBits::eHost, + {}, + { { vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferWrite, + vk::AccessFlagBits::eHostRead } }, + {}, {}); + ggml_vk_submit_sync(device, subctx); + + for (const auto & r : direct) { + memcpy(r.host, (const uint8_t *) r.buf->ptr + r.offset, r.size); + } + } + + if (pending.empty()) { + return; + } + + const size_t staging_size = ggml_vk_staging_size_n(device, pending); + if (staging_size > 0) { + ggml_vk_ensure_sync_staging_buffer(device, staging_size); + } + + for (size_t i = 0; i < pending.size();) { + vk_context subctx = ggml_vk_begin_sync_ctx(device, device->transfer_queue->cmd_pool); + size_t staging_offset = 0; + const size_t recorded = ggml_vk_buffer_read_n_async(subctx, pending.data() + i, pending.size() - i, &device->sync_staging, &staging_offset); + GGML_ASSERT(recorded > 0); + ggml_vk_submit_sync(device, subctx); + i += recorded; + } +} + +void ggml_vk_buffer_copy_n(const vk_buffer_copy_region * regions, size_t n) { + VK_LOG_DEBUG("ggml_vk_buffer_copy_n(" << n << ")"); + std::vector same_device; + + for (size_t i = 0; i < n; i++) { + vk_buffer_copy_region r = regions[i]; + if (r.size == 0) { + continue; + } + if (r.src->device != r.dst->device) { + ggml_vk_buffer_copy(r.dst, r.dst_offset, r.src, r.src_offset, r.size); + continue; + } + GGML_ASSERT(same_device.empty() || r.dst->device == same_device[0].dst->device); + same_device.push_back(std::move(r)); + } + + if (same_device.empty()) { + return; + } - ggml_vk_submit(subctx, dst->device->fence); - VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_memset waitForFences", dst->device); - dst->device->device.resetFences({ dst->device->fence }); - ggml_vk_queue_command_pools_cleanup(dst->device); + vk_device device = same_device[0].dst->device; + std::lock_guard guard(device->mutex); + vk_context subctx = ggml_vk_begin_sync_ctx(device, device->transfer_queue->cmd_pool); + ggml_vk_buffer_copy_n_async(subctx, same_device.data(), same_device.size()); + ggml_vk_submit_sync(device, subctx); } ggml_backend_buffer_i ggml_backend_vk_buffer_interface = { @@ -837,9 +1040,9 @@ ggml_backend_buffer_i ggml_backend_vk_buffer_interface = { /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor, /* .clear = */ ggml_backend_vk_buffer_clear, /* .reset = */ NULL, - /* .set_tensor_n = */ NULL, - /* .get_tensor_n = */ NULL, - /* .cpy_tensor_n = */ NULL, + /* .set_tensor_n = */ ggml_backend_vk_buffer_set_tensor_n, + /* .get_tensor_n = */ ggml_backend_vk_buffer_get_tensor_n, + /* .cpy_tensor_n = */ ggml_backend_vk_buffer_cpy_tensor_n, }; vk_buffer ggml_vk_buffer_from_host_ptr(vk_device & device, void * ptr, size_t size) { diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-common.h b/ggml/src/ggml-vulkan/ggml-vulkan-common.h index b5491fc4b318..4e05fb81839b 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-common.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-common.h @@ -59,6 +59,12 @@ void ggml_vk_buffer_read_2d(vk_buffer& src, size_t offset, void * dst, size_t sp void ggml_vk_buffer_read(vk_buffer& src, size_t offset, void * dst, size_t size); void ggml_vk_buffer_copy_async(vk_context& ctx, vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size); void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size); +size_t ggml_vk_buffer_write_n_async(vk_context& subctx, const vk_buffer_region * regions, size_t n, vk_buffer * staging = nullptr, size_t * staging_offset = nullptr); +size_t ggml_vk_buffer_read_n_async(vk_context& subctx, const vk_buffer_region * regions, size_t n, vk_buffer * staging = nullptr, size_t * staging_offset = nullptr); +void ggml_vk_buffer_copy_n_async(vk_context& subctx, const vk_buffer_copy_region * regions, size_t n); +void ggml_vk_buffer_write_n(const vk_buffer_region * regions, size_t n); +void ggml_vk_buffer_read_n(const vk_buffer_region * regions, size_t n); +void ggml_vk_buffer_copy_n(const vk_buffer_copy_region * regions, size_t n); void ggml_vk_buffer_memset_async(vk_context& ctx, vk_buffer& dst, size_t offset, uint32_t c, size_t size); void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t size); vk_buffer ggml_vk_buffer_from_host_ptr(vk_device & device, void * ptr, size_t size); @@ -166,7 +172,6 @@ void ggml_vk_l2_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const gg void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst); void ggml_vk_xielu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst); void ggml_vk_glu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); -void ggml_vk_diag_mask_inf(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst); void ggml_vk_soft_max(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst); void ggml_vk_soft_max_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); void ggml_vk_topk_moe(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx); @@ -227,6 +232,9 @@ void ggml_backend_vk_buffer_set_tensor_2d(ggml_backend_buffer_t buffer, ggml_ten void ggml_backend_vk_buffer_get_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data, size_t offset, size_t size); void ggml_backend_vk_buffer_get_tensor_2d(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data, size_t offset, size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data); bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst); +void ggml_backend_vk_buffer_set_tensor_n(ggml_backend_buffer_t buffer, ggml_tensor * const * tensors, const void * const * data, const size_t * offsets, const size_t * sizes, size_t n_tensors); +void ggml_backend_vk_buffer_get_tensor_n(ggml_backend_buffer_t buffer, const ggml_tensor * const * tensors, void * const * data, const size_t * offsets, const size_t * sizes, size_t n_tensors); +bool ggml_backend_vk_buffer_cpy_tensor_n(ggml_backend_buffer_t buffer, const ggml_tensor * const * srcs, ggml_tensor * const * dsts, size_t n_tensors); void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value); const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft); ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size); diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp b/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp index 792093ccf991..2c9c09c06be7 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp @@ -1035,8 +1035,6 @@ void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph } else if (tensor->op == GGML_OP_SCALE) { const float * params = (const float *)tensor->op_params; tensor_clone = ggml_scale_bias(ggml_ctx, src_clone[0], params[0], params[1]); - } else if (tensor->op == GGML_OP_ADD1) { - tensor_clone = ggml_add1(ggml_ctx, src_clone[0], src_clone[1]); } else if (tensor->op == GGML_OP_ARANGE) { const float start = ggml_get_op_params_f32(tensor, 0); const float stop = ggml_get_op_params_f32(tensor, 1); @@ -1101,8 +1099,6 @@ void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph } } else if (tensor->op == GGML_OP_SOFT_MAX_BACK) { tensor_clone = ggml_soft_max_ext_back(ggml_ctx, src_clone[0], src_clone[1], ((float *)tensor->op_params)[0], ((float *)tensor->op_params)[1]); - } else if (tensor->op == GGML_OP_DIAG_MASK_INF) { - tensor_clone = ggml_diag_mask_inf(ggml_ctx, src_clone[0], tensor->op_params[0]); } else if (tensor->op == GGML_OP_ROPE || tensor->op == GGML_OP_ROPE_BACK) { const int n_dims = ((int32_t *) tensor->op_params)[1]; const int mode = ((int32_t *) tensor->op_params)[2]; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h index 0b3ebe9b8065..1ef00477bfef 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h @@ -124,22 +124,30 @@ struct vk_flash_attn_push_constants { static_assert(sizeof(vk_flash_attn_push_constants) <= 128, "sizeof(vk_flash_attn_push_constants) must be <= 128"); -struct vk_fa_xe_opt_push_constants { - uint32_t kv_seq_len; - uint32_t activation_length; - uint32_t q_head; - uint32_t kv_head; - uint32_t qk_ratio; - uint32_t qk_sub_groups; +struct vk_xe_fa_push_constants { + uint32_t neq1; + uint32_t neq2; + uint32_t neq3; + uint32_t nek1; + uint32_t nek2; + uint32_t nek3; + uint32_t nev2; + uint32_t nev3; + uint32_t nem1; + uint32_t nem2; + uint32_t nem3; + uint32_t nbq1; + uint32_t nbq2; + uint32_t nbk1; + uint32_t nbk2; + uint32_t nbv1; + uint32_t nbv2; + uint32_t nbq3; + uint32_t nbk3; + uint32_t nbv3; + uint32_t nb3; uint32_t flag; - uint32_t nbkv_tok; - uint32_t nbkv_head; - uint32_t batch_stride_q; - uint32_t batch_stride_k; - uint32_t batch_stride_v; - uint32_t batch_stride_m; - uint32_t batch_stride_o; - float softmax_scale; + float scale; }; struct vk_op_push_constants { @@ -454,12 +462,6 @@ struct vk_op_add_id_push_constants { uint32_t s21; }; -struct vk_op_diag_mask_push_constants { - uint32_t ncols; - uint32_t rows_per_channel; - int32_t n_past; -}; - struct vk_op_rope_push_constants { uint32_t rope_mode; uint32_t nrows; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-types.h b/ggml/src/ggml-vulkan/ggml-vulkan-types.h index 786f8f01971c..81fd5b8a84ba 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-types.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-types.h @@ -433,6 +433,21 @@ struct vk_fa_pipeline_state { } }; +struct vk_xe_fa_pipeline_state { + uint32_t HSK, HSV; + uint32_t qk_ratio, pv_ratio; + uint32_t decode_n; + bool unaligned_seq_len; + bool unaligned_q; + bool partial_row_mask; + bool multi_head_mask; + + bool operator<(const vk_xe_fa_pipeline_state &b) const { + return std::tie(HSK, HSV, qk_ratio, pv_ratio, decode_n, unaligned_seq_len, unaligned_q, partial_row_mask, multi_head_mask) < + std::tie(b.HSK, b.HSV, b.qk_ratio, b.pv_ratio, b.decode_n, b.unaligned_seq_len, b.unaligned_q, b.partial_row_mask, b.multi_head_mask); + } +}; + struct vk_conv2d_pipeline_state { vk_conv2d_pipeline_state(uint32_t s0, uint32_t s1, uint32_t p0, uint32_t p1, uint32_t d0, uint32_t d1, uint32_t KW, uint32_t KH, uint32_t aligned) : s0(s0), s1(s1), p0(p0), p1(p1), d0(d0), d1(d1), KW(KW), KH(KH), aligned(aligned) {} @@ -763,6 +778,9 @@ struct vk_device_struct { bool dot2_f16 {}; bool ocp_fp4 {}; + bool workgroup_memory_explicit_layout {}; + bool workgroup_memory_explicit_layout_16bit {}; + bool pipeline_executable_properties_support {}; bool device_fault {}; @@ -925,7 +943,6 @@ struct vk_device_struct { vk_pipeline pipeline_leaky_relu[2]; vk_pipeline pipeline_silu_back_f32; - vk_pipeline pipeline_diag_mask_inf_f32; vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16; vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512; vk_pipeline pipeline_soft_max_back_f32; @@ -1006,7 +1023,8 @@ struct vk_device_struct { bool fa_sparse_compact_use_subgroups; vk_pipeline pipeline_flash_attn_split_k_reduce; - std::map, std::pair> pipeline_xe_fa_decode_dual_phases; + std::map> pipeline_xe_fa_decode_dual_phases; + std::map pipeline_xe_fa_prefill; vk_pipeline pipeline_count_experts; // [2] is for whether to take n_experts from spec constant (0) or push constant (1) @@ -1028,6 +1046,7 @@ struct vk_device_struct { bool disable_host_visible_vidmem; bool allow_sysmem_fallback; bool disable_graph_optimize; + bool xe_fa_support {}; std::unique_ptr memory_logger; @@ -1135,6 +1154,21 @@ struct vk_staging_memset { size_t n; }; +struct vk_buffer_region { + vk_buffer buf; + size_t offset; + void * host; + size_t size; +}; + +struct vk_buffer_copy_region { + vk_buffer dst; + size_t dst_offset; + vk_buffer src; + size_t src_offset; + size_t size; +}; + struct vk_context_struct { vk_submission * s; std::vector seqs; @@ -1392,6 +1426,34 @@ struct vk_fa_tuning_params { } }; +struct vk_xe_fa_tuning_params { + size_t shmem_sz; + std::array workgroup_size; + std::array subgroup_size; + uint32_t tm; + uint32_t tn; + uint32_t tk; + + struct { + uint32_t wg_row; + uint32_t gqa_fold; + uint32_t q_in_reg; + uint32_t p_per_iter; + uint32_t sg_col; + uint32_t acc_count; + uint32_t pipeline_flag; + } prefill_params; + + struct { + uint32_t p_chunk_ph1; + uint32_t out_per_wg_ph1; + uint32_t split_p_per_iter_ph2; + uint32_t out_row_per_wg_ph2; + uint32_t out_col_per_wg_ph2; + uint32_t pipeline_flag_ph2; + } decode_params; +}; + struct GpuPipelineConfig { // GPU architecture identifier. // Example: vk_device_architecture::AMD_GCN diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index 502f73344e8e..22641f5fbdb4 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -1434,6 +1434,186 @@ static std::vector get_fa_spec_constants(const vk_fa_pipeline_state& s }; } +static vk_xe_fa_tuning_params get_xe_fa_tuning_params(const vk_device_struct * device, const vk_xe_fa_pipeline_state& pipeline_state, bool use_prefill) { + vk_xe_fa_tuning_params params {}; + size_t shmem_sz = 0; + uint32_t sg_sz = 32u; + std::array matrix_mnk = { 16u, 16u, 16u }; + bool intel_gpu = device->vendor_id == VK_VENDOR_ID_INTEL; + + if (device->architecture == INTEL_XE1) { + sg_sz = 8u; + matrix_mnk = { 8u, 8u, 16u }; + } else if (device->architecture == INTEL_XE2) { + sg_sz = 16u; + matrix_mnk = { 8u, 16u, 16u }; + } + + uint32_t tm = matrix_mnk[0]; + uint32_t tn = matrix_mnk[1]; + uint32_t tk = matrix_mnk[2]; + uint32_t hsk = pipeline_state.HSK; + uint32_t hsv = pipeline_state.HSV; + uint32_t qk_ratio = pipeline_state.qk_ratio; + uint32_t pv_ratio = pipeline_state.pv_ratio; + uint32_t sg_per_gw; + + params.tm = tm; + params.tn = tn; + params.tk = tk; + GGML_ASSERT(hsv % tm == 0); + + if (use_prefill) { + sg_per_gw = sg_sz == 8 ? 32 : 16; + uint32_t wg_sz = sg_per_gw * sg_sz; + uint32_t output_div = hsk > 256 ? 8 : hsk > 160 ? 4 : hsk > 64 ? 2 : 1; + uint32_t p_per_iter = intel_gpu ? (hsk > 256 ? 16 : 32) : 16; + uint32_t q_in_reg = hsk > 512 ? hsk - 384 : std::min(128u, hsk); + uint32_t q_in_shmem = hsk - q_in_reg; + uint32_t wg_row = 256u / output_div; + uint32_t gqa_fold = (pipeline_state.multi_head_mask || qk_ratio != pv_ratio) ? 1 : 16; + uint32_t max_fold_rows = sg_sz <= 16 ? 16 : 8; + + while (gqa_fold > 1 && (qk_ratio % gqa_fold != 0 || gqa_fold * output_div > max_fold_rows)) { + gqa_fold = gqa_fold / 2; + } + + uint32_t mask_row = wg_row / gqa_fold; + uint32_t k_col = (hsk % 64 == 0 && hsk <= 512 && wg_sz <= 256) ? 8 : 4; + uint32_t k_loops = CEIL_DIV(hsk * p_per_iter, k_col * wg_sz); + + bool k_in_shmem = hsk <= 576u; + bool v_in_shmem = hsk <= 128u && hsv <= 128u; + bool emf_in_shmem = wg_row / matrix_mnk[1] != sg_per_gw; + bool mask_in_shmem = mask_row <= 64; + size_t shmem_q_sz = q_in_shmem * wg_row * sizeof(ggml_fp16_t); + size_t shmem_oob_staging_sz = sg_per_gw * tm * tk * sizeof(ggml_fp16_t); + size_t shmem_mask_sz = mask_in_shmem ? (mask_row * p_per_iter * sizeof(ggml_fp16_t)) : 0; + size_t shmem_k_sz = k_in_shmem ? (k_loops * k_col * wg_sz * sizeof(ggml_fp16_t)) : shmem_oob_staging_sz; + size_t shmem_v_sz = v_in_shmem ? (hsv * p_per_iter * sizeof(ggml_fp16_t)) : 0; + size_t shmem_p_sz = wg_row * p_per_iter * sizeof(float); + size_t shmem_emf_sz = emf_in_shmem ? (wg_row * sizeof(float)) : 0; + size_t shmem_pv_sz = intel_gpu ? 0 : (sg_per_gw * tm * tn * sizeof(float)); + + // Reuse section sits at tail of shmem, reused with k + mask/kv oob staging/pv staging + size_t shmem_reuse_sz = shmem_k_sz + shmem_mask_sz; + // When v is not in shmem, its staging reuses the k + mask region; size the reuse section to the larger of the two + shmem_reuse_sz = v_in_shmem ? shmem_reuse_sz : std::max(shmem_reuse_sz, shmem_oob_staging_sz); + shmem_reuse_sz = std::max(shmem_pv_sz, shmem_reuse_sz); + + // Q shmem size check for prologue staging is safe to bypass: + // 1. Prologue q staging shmem is released right after prologue, so it never overlaps other shmem sections + // 2. Extreme large hsk one-time q staging is capped within shader (max_q_reg_staging = shmem_size / 2 / Wr) + shmem_sz = shmem_q_sz + shmem_reuse_sz + shmem_v_sz + shmem_p_sz + shmem_emf_sz; + + uint32_t sg_col = hsv / tm; + uint32_t pipeline_flag = 0; + sg_col = (sg_col + output_div - 1) / output_div; + sg_col = sg_col * tm; + if (pipeline_state.unaligned_seq_len) { + pipeline_flag |= 1 << 0; + } + + if (pipeline_state.unaligned_q) { + pipeline_flag |= 1 << 1; + } + + if (pipeline_state.partial_row_mask) { + pipeline_flag |= 1 << 2; + } + + if (intel_gpu) { + pipeline_flag |= 1 << 3; + } + + params.workgroup_size = { wg_sz }; + params.subgroup_size = { sg_sz }; + params.shmem_sz = shmem_sz; + params.prefill_params.pipeline_flag = pipeline_flag; + params.prefill_params.wg_row = wg_row; + params.prefill_params.gqa_fold = gqa_fold; + params.prefill_params.q_in_reg = q_in_reg; + params.prefill_params.p_per_iter = p_per_iter; + params.prefill_params.sg_col = sg_col; + params.prefill_params.acc_count = tm == 8 ? (sg_col % 16 == 0 ? 2 : 1) : 1; + } else { + auto upper_power_of_2 = [&](uint32_t in) { + GGML_ASSERT(in != 0); + if (in <= 1) return 1u; + uint32_t ret = in - 1; + ret |= ret >> 1; + ret |= ret >> 2; + ret |= ret >> 4; + ret |= ret >> 8; + ret |= ret >> 16; + return ret + 1; + }; + + size_t shmem_ph1_sz = 0; + size_t shmem_ph2_sz = 0; + + // Phase 1 shmem size calculation + const uint32_t p_chunk_ph1 = 32; + // Phase 1 k shmem staging for extreme large hsk is capped within shader, bypass that check + uint32_t pmat_row = CEIL_DIV(qk_ratio, tn); + uint32_t aligned_q_len = upper_power_of_2(pipeline_state.decode_n); + uint32_t group_sz_ph1 = std::min(std::max(aligned_q_len * sg_sz, 64u), 256u); + uint32_t out_per_wg_ph1 = std::min(pipeline_state.decode_n, 256u / sg_sz); + size_t shmem_k_sz = group_sz_ph1 / sg_sz * tm * tk * sizeof(ggml_fp16_t); + size_t shmem_mask_sz = out_per_wg_ph1 * p_chunk_ph1 * sizeof(float); + size_t shmem_p_sz = p_chunk_ph1 * pmat_row * tn * sizeof(float); + // K shmem is reused with mask/p, calculate the max size + shmem_ph1_sz = std::max(shmem_k_sz, shmem_mask_sz + shmem_p_sz); + + // Phase 2 shmem size calculation + uint32_t aligned_pv_ratio = upper_power_of_2(pv_ratio); + uint32_t split_p_per_iter_ph2 = (pv_ratio <= 32) ? 256 : 128; + uint32_t out_col_per_wg_ph2 = intel_gpu ? (pv_ratio > 16 ? 8 : 16) : 16; + uint32_t split_p_per_warp = 16; + uint32_t group_sz_ph2 = (split_p_per_iter_ph2 / split_p_per_warp) * sg_sz; + sg_per_gw = group_sz_ph2 / sg_sz; + uint32_t out_row_per_wg_ph2 = std::min(std::max(16u / aligned_pv_ratio, 1u), pipeline_state.decode_n); + uint32_t o_row = pv_ratio * out_row_per_wg_ph2; + uint32_t omat_row = CEIL_DIV(o_row, tn) * tn; + uint32_t global_max_loops = CEIL_DIV(o_row, sg_per_gw); + size_t shmem_global_max_sz = CEIL_DIV(global_max_loops * sg_per_gw, sg_sz) * sg_sz * sizeof(float); + + uint32_t size_max = o_row * split_p_per_iter_ph2 / p_chunk_ph1; + size_t shmem_group_max_sz = CEIL_DIV(size_max, group_sz_ph2) * group_sz_ph2 * sizeof(float); + + uint32_t p_loop_col = group_sz_ph2 * 4; + uint32_t p_loops = CEIL_DIV(o_row * split_p_per_iter_ph2, p_loop_col); + shmem_p_sz = std::max(p_loop_col * p_loops * sizeof(ggml_fp16_t), omat_row * split_p_per_iter_ph2 * sizeof(ggml_fp16_t)); + + size_t shmem_lf_sz = CEIL_DIV(sg_per_gw * p_loops, sg_sz) * sg_sz * sizeof(float); + size_t shmem_oob_staging_sz = sg_per_gw * tm * tk * sizeof(ggml_fp16_t); + size_t shmem_o_sz = sg_per_gw * out_col_per_wg_ph2 * omat_row * sizeof(float); + size_t shmem_reuse_sz = 2 * shmem_group_max_sz + std::max(shmem_oob_staging_sz, 2 * shmem_p_sz); + + shmem_ph2_sz = shmem_lf_sz + shmem_global_max_sz; + // Shmem of p/group max is reused with output accumulation, calculate the max size + shmem_ph2_sz += std::max(shmem_reuse_sz, shmem_o_sz); + shmem_sz = std::max(shmem_ph1_sz, shmem_ph2_sz); + + params.workgroup_size = { group_sz_ph1, group_sz_ph2 }; + params.subgroup_size = { sg_sz, sg_sz }; + params.shmem_sz = shmem_sz; + params.decode_params.p_chunk_ph1 = p_chunk_ph1; + params.decode_params.out_per_wg_ph1 = out_per_wg_ph1; + params.decode_params.split_p_per_iter_ph2 = split_p_per_iter_ph2; + params.decode_params.out_row_per_wg_ph2 = out_row_per_wg_ph2; + params.decode_params.out_col_per_wg_ph2 = out_col_per_wg_ph2; + params.decode_params.pipeline_flag_ph2 = pipeline_state.unaligned_seq_len ? (1u << 0) : 0; + } + + if (shmem_sz > device->properties.limits.maxComputeSharedMemorySize) { + VK_LOG_DEBUG("get_xe_fa_tuning_params(HSK=" << hsk << ", HSV=" << hsv << ", qk_ratio=" << qk_ratio << ", pv_ratio=" << pv_ratio << "), " + "shmem_sz = " << shmem_sz << ", exceeding max shmem size = " << device->properties.limits.maxComputeSharedMemorySize); + } + + return params; +} + static bool ggml_vk_matmul_shmem_support(const vk_device& device, const std::vector& warptile, bool mul_mat_id, ggml_type src0_type) { uint32_t lut_size = 0; @@ -3202,43 +3382,36 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { ggml_vk_create_pipeline(device, device->pipeline_flash_attn_split_k_reduce, "fa_split_k_reduce", fa_split_k_reduce_len, fa_split_k_reduce_data, "main", 3, sizeof(vk_op_flash_attn_split_k_reduce_push_constants), {1, device->subgroup_size, 1}, {device->subgroup_size}, 1, true); #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) - if (device->vendor_id == VK_VENDOR_ID_INTEL && (device->architecture == INTEL_XE2 || (device->architecture == INTEL_XE1 && device->coopmat_support && device->uma))) { - auto upper_power_of_2 = [&](uint32_t in) { - GGML_ASSERT(in != 0); - if (in <= 1) return 1u; - uint32_t ret = in - 1; - ret |= ret >> 1; - ret |= ret >> 2; - ret |= ret >> 4; - ret |= ret >> 8; - ret |= ret >> 16; - return ret + 1; - }; - - uint32_t xe_native_sub_group_size = 16; - if (device->architecture == INTEL_XE1) { - xe_native_sub_group_size = 8; - } + if (device->xe_fa_support) { + uint32_t shmem_sz = (uint32_t)device->properties.limits.maxComputeSharedMemorySize; + vk_xe_fa_tuning_params xe_fa_params {}; for (auto& it : device->pipeline_xe_fa_decode_dual_phases) { - const uint32_t split_p_chunk = 32; - auto HdQk = it.first; + auto pipeline_state = it.first; auto& pipelines = it.second; - uint32_t head_dim_qk = std::get<0>(HdQk); - uint32_t head_dim_pv = std::get<1>(HdQk); - uint32_t gqa_ratio = std::get<2>(HdQk); - uint32_t q_len = std::get<3>(HdQk); - const uint32_t out_dim_per_wg = gqa_ratio > 16 ? 8 : 16; - uint32_t aligned_q_len = upper_power_of_2(q_len); - uint32_t group_sz_ph1 = std::min(std::max(aligned_q_len * xe_native_sub_group_size, 64u), 256u); - uint32_t out_per_wg_ph1 = std::min(q_len, 256u / xe_native_sub_group_size); - uint32_t aligned_gqa_ratio = upper_power_of_2(gqa_ratio); - uint32_t split_p_per_iter_ph2 = 256; - uint32_t split_p_per_warp = 16; - uint32_t group_sz_ph2 = (split_p_per_iter_ph2 / split_p_per_warp) * xe_native_sub_group_size; - uint32_t out_per_wg_ph2 = std::min(std::max(16u / aligned_gqa_ratio, 1u), q_len); - ggml_vk_create_pipeline(device, pipelines.first, "xe_fa_decode_ph1", fa_decode_ph1_cm1_len, fa_decode_ph1_cm1_data, "main", 5, sizeof(vk_fa_xe_opt_push_constants), { 1, 32, 1 }, { group_sz_ph1, gqa_ratio, head_dim_qk, xe_native_sub_group_size, split_p_chunk, out_per_wg_ph1 }, 1, false, true, xe_native_sub_group_size); - ggml_vk_create_pipeline(device, pipelines.second, "xe_fa_decode_ph2", fa_decode_ph2_cm1_len, fa_decode_ph2_cm1_data, "main", 5, sizeof(vk_fa_xe_opt_push_constants), { 1, 1, 1 }, { group_sz_ph2, gqa_ratio, head_dim_pv, out_per_wg_ph2, xe_native_sub_group_size, split_p_per_iter_ph2, split_p_chunk, out_dim_per_wg }, 1, false, true, xe_native_sub_group_size); + xe_fa_params = get_xe_fa_tuning_params(device.get(), pipeline_state, false); + std::vector sc_ph1 = { xe_fa_params.workgroup_size[0], pipeline_state.qk_ratio, pipeline_state.HSK, + xe_fa_params.subgroup_size[0], xe_fa_params.decode_params.p_chunk_ph1, + xe_fa_params.decode_params.out_per_wg_ph1, xe_fa_params.decode_params.p_chunk_ph1 / xe_fa_params.tm, + xe_fa_params.tm, xe_fa_params.tn, shmem_sz }; + std::vector sc_ph2 = { xe_fa_params.workgroup_size[1], pipeline_state.pv_ratio, pipeline_state.HSV, + xe_fa_params.decode_params.out_row_per_wg_ph2, xe_fa_params.subgroup_size[1], xe_fa_params.decode_params.split_p_per_iter_ph2, + xe_fa_params.decode_params.p_chunk_ph1, xe_fa_params.decode_params.out_col_per_wg_ph2, + xe_fa_params.tm, xe_fa_params.tn, xe_fa_params.decode_params.pipeline_flag_ph2 }; + ggml_vk_create_pipeline(device, pipelines.first, "xe_fa_decode_ph1", fa_decode_ph1_cm1_len, fa_decode_ph1_cm1_data, "main", 5, sizeof(vk_xe_fa_push_constants), { 1, xe_fa_params.decode_params.p_chunk_ph1, 1 }, sc_ph1, 1, false, true, xe_fa_params.subgroup_size[0]); + ggml_vk_create_pipeline(device, pipelines.second, "xe_fa_decode_ph2", fa_decode_ph2_cm1_len, fa_decode_ph2_cm1_data, "main", 5, sizeof(vk_xe_fa_push_constants), { 1, 1, 1 }, sc_ph2, 1, false, true, xe_fa_params.subgroup_size[0]); + } + + for (auto& it : device->pipeline_xe_fa_prefill) { + auto pipeline_state = it.first; + auto& pipelines = it.second; + xe_fa_params = get_xe_fa_tuning_params(device.get(), pipeline_state, true); + + std::vector sc = { xe_fa_params.workgroup_size[0], xe_fa_params.prefill_params.wg_row, xe_fa_params.prefill_params.sg_col, + pipeline_state.HSK, pipeline_state.HSV, pipeline_state.qk_ratio, xe_fa_params.prefill_params.p_per_iter, + xe_fa_params.tm, xe_fa_params.tn, xe_fa_params.prefill_params.q_in_reg, shmem_sz, xe_fa_params.prefill_params.acc_count, + xe_fa_params.prefill_params.pipeline_flag, xe_fa_params.subgroup_size[0], xe_fa_params.prefill_params.gqa_fold }; + ggml_vk_create_pipeline(device, pipelines, "xe_fa_prefill", fa_prefill_cm1_len, fa_prefill_cm1_data, "main", 6, sizeof(vk_xe_fa_push_constants), { xe_fa_params.prefill_params.gqa_fold, xe_fa_params.prefill_params.wg_row / xe_fa_params.prefill_params.gqa_fold, 1 }, sc, 1, false, true, xe_fa_params.subgroup_size[0]); } } #endif @@ -3503,10 +3676,6 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { CREATE_UNARY_MUL(softplus, 3) #undef CREATE_UNARY_MUL - ggml_vk_create_pipeline(device, device->pipeline_add1_f16_f16, "add1_f16_f16", add1_f16_f16_len, add1_f16_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_add1_f16_f32, "add1_f16_f32", add1_f16_f32_len, add1_f16_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_add1_f32_f32, "add1_f32_f32", add1_f32_f32_len, add1_f32_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_arange_f32, "arange_f32", arange_f32_len, arange_f32_data, "main", 1, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); ggml_vk_create_pipeline(device, device->pipeline_fill_f32, "fill_f32", fill_f32_len, fill_f32_data, "main", 1, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); @@ -3527,8 +3696,6 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { ggml_vk_create_pipeline(device, device->pipeline_silu_back_f32, "silu_back_f32", silu_back_f32_len, silu_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_diag_mask_inf_f32, "diag_mask_inf_f32", diag_mask_inf_f32_len, diag_mask_inf_f32_data, "main", 2, sizeof(vk_op_diag_mask_push_constants), {1, 512, 1}, {}, 1, true); - ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32, "soft_max_f32", soft_max_f32_len, soft_max_f32_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1); ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_wg512, "soft_max_f32_wg512", soft_max_f32_len, soft_max_f32_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1); ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_f16, "soft_max_f32_f16", soft_max_f32_f16_len, soft_max_f32_f16_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1); @@ -4125,6 +4292,7 @@ vk_device ggml_vk_get_device(size_t idx) { bool dot2_f16_support = false; bool ocp_microscaling_extension = false; bool shader_float8_extension = false; + bool workgroup_memory_explicit_layout_support = false; for (const auto& properties : ext_props) { if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) { @@ -4180,6 +4348,10 @@ vk_device ggml_vk_get_device(size_t idx) { dot2_f16_support = true; } else if (strcmp("VK_KHR_pipeline_executable_properties", properties.extensionName) == 0) { pipeline_executable_properties_support = true; +#if defined(VK_KHR_workgroup_memory_explicit_layout) + } else if (strcmp("VK_KHR_workgroup_memory_explicit_layout", properties.extensionName) == 0) { + workgroup_memory_explicit_layout_support = true; +#endif } else if (strcmp("VK_EXT_memory_priority", properties.extensionName) == 0 && getenv("GGML_VK_ENABLE_MEMORY_PRIORITY")) { device->memory_priority = true; @@ -4532,6 +4704,16 @@ vk_device ggml_vk_get_device(size_t idx) { device_extensions.push_back("VK_KHR_pipeline_executable_properties"); } +#if defined(VK_KHR_workgroup_memory_explicit_layout) + VkPhysicalDeviceWorkgroupMemoryExplicitLayoutFeaturesKHR wg_explicit_layout_features {}; + wg_explicit_layout_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_WORKGROUP_MEMORY_EXPLICIT_LAYOUT_FEATURES_KHR; + if (workgroup_memory_explicit_layout_support) { + last_struct->pNext = (VkBaseOutStructure *)&wg_explicit_layout_features; + last_struct = (VkBaseOutStructure *)&wg_explicit_layout_features; + device_extensions.push_back("VK_KHR_workgroup_memory_explicit_layout"); + } +#endif + if (device->external_memory_host) { device_extensions.push_back("VK_EXT_external_memory_host"); } @@ -4593,6 +4775,16 @@ vk_device ggml_vk_get_device(size_t idx) { shader_float8_extension && shader_float8_features.shaderFloat8 && !getenv("GGML_VK_DISABLE_OCP_FP4"); +#if defined(VK_KHR_workgroup_memory_explicit_layout) + device->workgroup_memory_explicit_layout = workgroup_memory_explicit_layout_support && + wg_explicit_layout_features.workgroupMemoryExplicitLayout; + device->workgroup_memory_explicit_layout_16bit = device->workgroup_memory_explicit_layout && + wg_explicit_layout_features.workgroupMemoryExplicitLayout16BitAccess; +#else + device->workgroup_memory_explicit_layout = false; + device->workgroup_memory_explicit_layout_16bit = false; +#endif + device->pipeline_robustness = pl_robustness_features.pipelineRobustness; device->multi_add = vk12_props.shaderRoundingModeRTEFloat16 && @@ -4958,6 +5150,13 @@ vk_device ggml_vk_get_device(size_t idx) { descriptor_set_layout_create_info.setPNext(&dslbfci); device->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info); +#if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) + device->xe_fa_support = device->coopmat_support && device->properties.limits.maxComputeSharedMemorySize >= 48 * 1024 && + device->workgroup_memory_explicit_layout && device->workgroup_memory_explicit_layout_16bit && + ((device->vendor_id == VK_VENDOR_ID_INTEL && (device->architecture == INTEL_XE2 || (device->architecture == INTEL_XE1 && device->uma))) || + (device->subgroup_size == 32 && device->coopmat_support_16x16x16_f32acc && (getenv("GGML_VK_FORCE_XE_FA") != nullptr))); +#endif + ggml_vk_load_shaders(device); // Prefer a dedicated transfer queue on AMD dGPUs (non-GCN) when graphics queue use is disabled. @@ -8403,32 +8602,98 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const vk_pipeline pipeline = nullptr; + auto tensor_aligned_with = [&](const ggml_tensor * t, uint32_t in) { + GGML_ASSERT(t != nullptr && in != 0); + return t->nb[1] % in == 0 && t->nb[2] % in == 0 && t->nb[3] % in == 0 && ggml_vk_tensor_buffer_offset(ctx, t) % in == 0; + }; + auto vk_dev = ctx->device.get(); bool xe_fa_opt = false; - bool fa_copy_qstate = false; - bool xe_fa_supported_platform = - (ctx->device.get()->architecture == INTEL_XE2 && ctx->device.get()->properties.deviceID != 0xFD80 && ctx->device.get()->properties.deviceID != 0xFD81) || - (ctx->device.get()->architecture == INTEL_XE1 && ctx->device.get()->coopmat_support && ctx->device.get()->uma); - bool xe_fa_supported_usage = neq0 % 32 == 0 && nev0 % 16 == 0 && q->nb[1] > q->nb[2] && k->nb[1] > k->nb[2] && v->nb[1] > v->nb[2] && mask != nullptr; - bool xe_fa_supported_dtype = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F16 && v->type == GGML_TYPE_F16 && (mask != nullptr && mask->type == GGML_TYPE_F16); + bool xe_fa_use_2phases = false; + bool xe_fa_supported_platform = vk_dev->xe_fa_support && vk_dev->properties.deviceID != 0xFD80 && vk_dev->properties.deviceID != 0xFD81; + bool xe_fa_supported_usage = neq0 % 32 == 0 && nev0 % 16 == 0 && mask != nullptr && !use_sparse && max_bias == 0.0f && logit_softcap == 0.0f && + tensor_aligned_with(k, 16u) && tensor_aligned_with(v, 16u); + bool xe_fa_supported_dtype = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F16 && v->type == GGML_TYPE_F16 && + mask != nullptr && mask->type == GGML_TYPE_F16; + xe_fa_opt = xe_fa_supported_platform && xe_fa_supported_usage && xe_fa_supported_dtype; std::pair xe_fa_pipeline_dual_phases = { nullptr , nullptr }; vk_pipeline xe_fa_pipeline = nullptr; + size_t size_q_staging = 0; size_t size_p = 0; size_t size_group_max = 0; + size_t size_decode_temp = 0; + uint32_t pv_ratio = uint32_t(neq2 / nev2); + vk_xe_fa_tuning_params xe_fa_params {}; { std::lock_guard guard(ctx->device->compile_mutex); - auto &pipelines = ctx->device->pipeline_flash_attn_f32_f16; - auto it = pipelines.find(fa_pipeline_state); - if (it != pipelines.end()) { - pipeline = it->second; - } else { - pipelines[fa_pipeline_state] = pipeline = std::make_shared(); + if (xe_fa_opt) { + if (neq1 > 8 || pv_ratio > 64) { + uint32_t head_stride_q = uint32_t(nbq2 / ggml_type_size(q->type)); + uint32_t batch_stride_q = uint32_t(nbq3 / ggml_type_size(q->type)); + vk_xe_fa_pipeline_state prefill_state = { (uint32_t)neq0, (uint32_t)nev0, qk_ratio, pv_ratio, 0, false, false, false, false }; + prefill_state.unaligned_seq_len = nek1 % 32 != 0; + prefill_state.unaligned_q = head_stride_q % 8 != 0 || q_stride % 8 != 0 || batch_stride_q % 8 != 0; + prefill_state.partial_row_mask = neq1 > nem1; + prefill_state.multi_head_mask = nem2 > 1; + xe_fa_params = get_xe_fa_tuning_params(vk_dev, prefill_state, true); + if (xe_fa_params.shmem_sz <= vk_dev->properties.limits.maxComputeSharedMemorySize) { + auto& xe_fa_pipelines = ctx->device->pipeline_xe_fa_prefill; + auto it = xe_fa_pipelines.find(prefill_state); + if (it != xe_fa_pipelines.end()) { + xe_fa_pipeline = it->second; + } else { + xe_fa_pipelines[prefill_state] = xe_fa_pipeline = std::make_shared(); + } + } else { + xe_fa_opt = false; + } + } else { + vk_xe_fa_pipeline_state decode_state = { (uint32_t)neq0, (uint32_t)nev0, qk_ratio, pv_ratio, (uint32_t)neq1, false, false, false, false }; + decode_state.unaligned_seq_len = nek1 % 256 != 0; + xe_fa_params = get_xe_fa_tuning_params(vk_dev, decode_state, false); + const uint32_t split_p_size = xe_fa_params.decode_params.p_chunk_ph1; + const size_t max_dim = std::max(CEIL_DIV(nek1, split_p_size), 1); + const size_t p_dim = max_dim * split_p_size; + const size_t q_head_padding = 16; + size_q_staging = neq0 * neq1 * (neq2 * neq3 + q_head_padding) * sizeof(ggml_fp16_t); + size_p = neq1 * neq2 * p_dim * neq3 * sizeof(ggml_fp16_t); + size_group_max = neq1 * neq2 * max_dim * neq3 * sizeof(float); + size_decode_temp = size_q_staging + size_p + size_group_max; + uint32_t ph1_wg1 = CEIL_DIV(nek1, xe_fa_params.decode_params.p_chunk_ph1); + if (xe_fa_params.shmem_sz <= vk_dev->properties.limits.maxComputeSharedMemorySize && + ph1_wg1 <= ctx->device->properties.limits.maxComputeWorkGroupCount[1] && + size_decode_temp <= ctx->device->properties.limits.maxStorageBufferRange) { + auto& pipelines = ctx->device->pipeline_xe_fa_decode_dual_phases; + auto it = pipelines.find(decode_state); + if (it != pipelines.end()) { + xe_fa_pipeline_dual_phases = it->second; + } else { + pipelines[decode_state] = xe_fa_pipeline_dual_phases = + std::make_pair(std::make_shared(), std::make_shared()); + } + xe_fa_use_2phases = true; + } else { + xe_fa_opt = false; + } + } + } + + if (!xe_fa_opt) { + auto &pipelines = ctx->device->pipeline_flash_attn_f32_f16; + auto it = pipelines.find(fa_pipeline_state); + if (it != pipelines.end()) { + pipeline = it->second; + } else { + pipelines[fa_pipeline_state] = pipeline = std::make_shared(); + } } } - assert(pipeline); - // Compile early to initialize wg_denoms. - ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); + if (!xe_fa_opt) { + assert(pipeline); + // Compile early to initialize wg_denoms. + ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); + } uint32_t split_kv = KV; uint32_t split_k = 1; @@ -8442,7 +8707,9 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const const uint32_t Br = fa_pipeline_state.Br; const uint32_t Bc = fa_pipeline_state.Bc; - GGML_ASSERT(Br == pipeline->wg_denoms[0]); + if (!xe_fa_opt) { + GGML_ASSERT(Br == pipeline->wg_denoms[0]); + } const uint32_t Tr = CEIL_DIV(N, Br); // Try to use split_k when KV is large enough to be worth the overhead. @@ -8472,45 +8739,24 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const // of "align", so recompute split_k based on that. split_kv = ROUNDUP_POW2(std::max(1u, KV / split_k), alignment); split_k = CEIL_DIV(KV, split_kv); - xe_fa_opt = xe_fa_supported_platform && xe_fa_supported_usage && xe_fa_supported_dtype; - if (xe_fa_opt) { - const uint32_t split_p_size = 32; - const size_t max_dim = (nek1 + split_p_size - 1) / split_p_size; - const size_t p_dim = max_dim * split_p_size; -#if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) - std::lock_guard guard(ctx->device->compile_mutex); - auto& pipelines = ctx->device->pipeline_xe_fa_decode_dual_phases; - auto it = pipelines.find({ (uint32_t)neq0, (uint32_t)nev0, qk_ratio, (uint32_t)neq1 }); - if (it != pipelines.end()) { - xe_fa_pipeline_dual_phases = it->second; - } else { - pipelines[{(uint32_t)neq0, (uint32_t)nev0, qk_ratio, (uint32_t)neq1}] = xe_fa_pipeline_dual_phases = std::make_pair(std::make_shared(), std::make_shared()); + } + + if (xe_fa_opt) { + // Bypass mask_opt and split_k buffer grow when they are not in use + use_mask_opt = false; + split_k = 1; + if (xe_fa_use_2phases) { + if (ctx->prealloc_size_x < size_decode_temp) { + ctx->prealloc_size_x = size_decode_temp; + ggml_vk_preallocate_buffers(ctx, subctx); } -#endif - if (xe_fa_pipeline_dual_phases.first == nullptr || xe_fa_pipeline_dual_phases.second == nullptr) { - xe_fa_opt = false; - fa_copy_qstate = false; - } else { - size_p = neq1 * neq2 * p_dim * neq3 * sizeof(ggml_fp16_t); - size_group_max = neq1 * neq2 * max_dim * neq3 * sizeof(float); - size_t temp_size = ggml_nelements(q) * sizeof(ggml_fp16_t) + size_p + size_group_max; - fa_copy_qstate = true; - if (ctx->prealloc_size_x < temp_size) { - ctx->prealloc_size_x = temp_size; - ggml_vk_preallocate_buffers(ctx, subctx); - } - if (ctx->prealloc_x_need_sync) { - ggml_vk_sync_buffers(ctx, subctx); - } + if (ctx->prealloc_x_need_sync) { + ggml_vk_sync_buffers(ctx, subctx); } } } - if (xe_fa_opt == true) { - use_mask_opt = false; - } - // Reserve space for split_k temporaries. For each split x batch, we need to store the O matrix (D x ne1) // and the per-row m and L values (ne1 rows). We store all the matrices first, followed by the rows. // For matrices, the order is (inner to outer) [HSV, ne1, k, ne2, ne3]. @@ -8697,67 +8943,59 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const mask_n_head_log2, m0, m1, gqa_ratio, split_kv, split_k }; - if (xe_fa_opt && split_k > 1) { - auto upper_power_of_2 = [&](uint32_t in) { - GGML_ASSERT(in != 0); - if (in <= 1) return 1u; - uint32_t ret = in - 1; - ret |= ret >> 1; - ret |= ret >> 2; - ret |= ret >> 4; - ret |= ret >> 8; - ret |= ret >> 16; - return ret + 1; - }; - auto to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, q->type); - const uint32_t out_dim_per_wg = qk_ratio > 16 ? 8 : 16; - size_t x_ne = ggml_nelements(q); - size_t temp_buf_offset = 0; + if (xe_fa_opt) { + uint32_t head_stride_q = uint32_t(nbq2 / ggml_type_size(q->type)); uint32_t head_stride_k = uint32_t(nbk2 / ggml_type_size(k->type)); uint32_t head_stride_v = uint32_t(nbv2 / ggml_type_size(v->type)); uint32_t batch_stride_q = uint32_t(nbq3 / ggml_type_size(q->type)); uint32_t batch_stride_k = uint32_t(nbk3 / ggml_type_size(k->type)); uint32_t batch_stride_v = uint32_t(nbv3 / ggml_type_size(v->type)); - uint32_t batch_stride_m = mask ? uint32_t(mask->nb[3] / ggml_type_size(mask->type)) : 0u; uint32_t batch_stride_o = uint32_t(nb3 / ggml_type_size(dst->type)); - vk_fa_xe_opt_push_constants pc_ph1 = { (uint32_t)nek1, (uint32_t)neq1, (uint32_t)neq2, (uint32_t)nek2, qk_ratio, 1, (sinks != nullptr) ? 1u : 0u, (uint32_t)k_stride, head_stride_k, - batch_stride_q, batch_stride_k, batch_stride_v, batch_stride_m, batch_stride_o, scale }; - vk_fa_xe_opt_push_constants pc_ph2 = pc_ph1; - pc_ph2.nbkv_tok = v_stride; - pc_ph2.nbkv_head = head_stride_v; - vk_subbuffer q_temp_buf = fa_copy_qstate ? ggml_vk_subbuffer(ctx, ctx->prealloc_x, temp_buf_offset) : q_buf; - temp_buf_offset += fa_copy_qstate ? x_ne * sizeof(ggml_fp16_t) : 0; - vk_subbuffer p_temp_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_x, temp_buf_offset); - temp_buf_offset += size_p; - vk_subbuffer max_temp_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_x, temp_buf_offset); - temp_buf_offset += size_group_max; - uint32_t xe_native_sub_group_size = ctx->device.get()->architecture == INTEL_XE1 ? 8 : 16; - uint32_t aligned_gqa_ratio = upper_power_of_2(qk_ratio); - uint32_t out_per_wg_ph1 = std::min(256u / xe_native_sub_group_size, (uint32_t)neq1); - uint32_t out_per_wg_ph2 = std::min(std::max(16u / aligned_gqa_ratio, 1u), (uint32_t)neq1); - uint32_t ph1_wg = ((neq1 + out_per_wg_ph1 - 1) / out_per_wg_ph1) * nek2; - uint32_t ph2_wg = ((neq1 + out_per_wg_ph2 - 1) / out_per_wg_ph2) * ne0 / out_dim_per_wg; - if (fa_copy_qstate) { - const std::vector pc_cpy_fp16 = - { (uint32_t)q->ne[0], (uint32_t)q->ne[1], (uint32_t)q->ne[2], (uint32_t)q->ne[3], (uint32_t)(x_ne) }; - ggml_vk_sync_buffers(ctx, subctx); + + vk_xe_fa_push_constants pc_xe_fa = { (uint32_t)neq1, (uint32_t)neq2, (uint32_t)neq3, + (uint32_t)nek1, (uint32_t)nek2, (uint32_t)nek3, (uint32_t)nev2, (uint32_t)nev3, + (uint32_t)nem1, (uint32_t)nem2, (uint32_t)nem3, + q_stride, head_stride_q, k_stride, head_stride_k, v_stride, head_stride_v, + batch_stride_q, batch_stride_k, batch_stride_v, batch_stride_o, + (sinks != nullptr) ? (1u << 16) : 0u, scale }; + + if (xe_fa_use_2phases) { + auto to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, q, nullptr, GGML_TYPE_F16); + size_t temp_buf_offset = 0; + vk_subbuffer q_temp_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_x, temp_buf_offset); + temp_buf_offset += size_q_staging; + vk_subbuffer p_temp_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_x, temp_buf_offset); + temp_buf_offset += size_p; + vk_subbuffer max_temp_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_x, temp_buf_offset); + temp_buf_offset += size_group_max; + uint32_t ph1_wg = CEIL_DIV(neq1, xe_fa_params.decode_params.out_per_wg_ph1) * nek2; + uint32_t ph2_wg = CEIL_DIV(neq1, xe_fa_params.decode_params.out_row_per_wg_ph2) * ne0 / xe_fa_params.decode_params.out_col_per_wg_ph2; + + pc_xe_fa.nbq1 = uint32_t(neq0); + pc_xe_fa.nbq2 = uint32_t(neq0 * neq1); + pc_xe_fa.nbq3 = uint32_t(neq0 * neq1 * neq2); + ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1); - ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0, { q_buf, q_temp_buf }, pc_cpy_fp16, { (uint32_t)(x_ne), 1, 1 }); - } + ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, q, q_buf, q_temp_buf); - ggml_vk_sync_buffers(ctx, subctx); - ggml_pipeline_request_descriptor_sets(ctx, xe_fa_pipeline_dual_phases.first, 1); - ggml_vk_dispatch_pipeline(ctx, subctx, xe_fa_pipeline_dual_phases.first, - { q_temp_buf, k_buf, mask_buf, p_temp_buf, max_temp_buf }, - pc_ph1, { (uint32_t)ph1_wg, (uint32_t)nek1, (uint32_t)neq3 }); + ggml_pipeline_request_descriptor_sets(ctx, xe_fa_pipeline_dual_phases.first, 1); + ggml_vk_dispatch_pipeline(ctx, subctx, xe_fa_pipeline_dual_phases.first, + { q_temp_buf, k_buf, mask_buf, p_temp_buf, max_temp_buf }, + pc_xe_fa, { (uint32_t)ph1_wg, (uint32_t)nek1, (uint32_t)neq3 }); - ggml_vk_sync_buffers(ctx, subctx); - ggml_pipeline_request_descriptor_sets(ctx, xe_fa_pipeline_dual_phases.second, 1); - ggml_vk_dispatch_pipeline(ctx, subctx, xe_fa_pipeline_dual_phases.second, - { p_temp_buf, v_buf, max_temp_buf, sinks_buf, dst_buf }, - pc_ph2, { (uint32_t)ph2_wg, (uint32_t)nev2, (uint32_t)neq3 }); + ggml_vk_sync_buffers(ctx, subctx); + ggml_pipeline_request_descriptor_sets(ctx, xe_fa_pipeline_dual_phases.second, 1); + ggml_vk_dispatch_pipeline(ctx, subctx, xe_fa_pipeline_dual_phases.second, + { p_temp_buf, v_buf, max_temp_buf, sinks_buf, dst_buf }, + pc_xe_fa, { (uint32_t)ph2_wg, (uint32_t)nev2, (uint32_t)neq3 }); - ctx->prealloc_x_need_sync = true; + ctx->prealloc_x_need_sync = true; + } else { + ggml_pipeline_request_descriptor_sets(ctx, xe_fa_pipeline, 1); + ggml_vk_dispatch_pipeline(ctx, subctx, xe_fa_pipeline, + { q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf }, + pc_xe_fa, { (uint32_t)neq2, (uint32_t)neq1, (uint32_t)neq3 }); + } } else if (split_k > 1) { ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_flash_attn_split_k_reduce, 1); @@ -9233,11 +9471,6 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const break; } return nullptr; - case GGML_OP_DIAG_MASK_INF: - if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { - return ctx->device->pipeline_diag_mask_inf_f32; - } - return nullptr; case GGML_OP_SOFT_MAX: GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); GGML_ASSERT(!src2 || src2->type == GGML_TYPE_F32); @@ -9616,17 +9849,6 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const return pipeline; } return nullptr; - case GGML_OP_ADD1: - if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) { - return ctx->device->pipeline_add1_f16_f16; - } - if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) { - return ctx->device->pipeline_add1_f16_f32; - } - if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { - return ctx->device->pipeline_add1_f32_f32; - } - return nullptr; case GGML_OP_ARANGE: if (dst->type == GGML_TYPE_F32) { return ctx->device->pipeline_arange_f32; @@ -9765,9 +9987,6 @@ static void ggml_vk_op_f32(ggml_backend_vk_context * ctx, vk_context& subctx, co elements = { groups_x, groups_y, uint32_t(CEIL_DIV(uint64_t(total_workgroups), groups_xy)) }; GGML_ASSERT(elements[2] <= ctx->device->properties.limits.maxComputeWorkGroupCount[2]); } break; - case GGML_OP_DIAG_MASK_INF: - elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 }; - break; case GGML_OP_ROPE: case GGML_OP_ROPE_BACK: { @@ -9901,7 +10120,6 @@ static void ggml_vk_op_f32(ggml_backend_vk_context * ctx, vk_context& subctx, co case GGML_OP_SUB: case GGML_OP_DIV: case GGML_OP_MUL: - case GGML_OP_ADD1: case GGML_OP_OUT_PROD: case GGML_OP_ARANGE: case GGML_OP_FILL: @@ -10796,21 +11014,6 @@ void ggml_vk_sqrt(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_ ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQRT, vk_op_unary_push_constants_init(src0, dst)); } -void ggml_vk_add1(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - const uint32_t src0_type_size = ggml_type_size(src0->type); - const uint32_t src1_type_size = ggml_type_size(src1->type); - const uint32_t dst_type_size = ggml_type_size(dst->type); - - ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD1, { - (uint32_t)ggml_nelements(src0), - (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size, - (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size, - (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size, - 0, - 0.0f, 0.0f, 0, - }); -} - void ggml_vk_arange(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { VK_LOG_DEBUG("ggml_vk_arange(dst=" << dst << ", ne=" << ggml_nelements(dst) << ")"); @@ -11325,11 +11528,6 @@ void ggml_vk_glu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_t }); } -void ggml_vk_diag_mask_inf(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { - int32_t * op_params = (int32_t *)dst->op_params; - ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_DIAG_MASK_INF, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0] }); -} - void ggml_vk_soft_max(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst) { float * op_params = (float *)dst->op_params; @@ -12701,10 +12899,6 @@ bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, in case GGML_OP_UPSCALE: ggml_vk_upscale(ctx, compute_ctx, src0, node); - break; - case GGML_OP_ADD1: - ggml_vk_add1(ctx, compute_ctx, src0, src1, node); - break; case GGML_OP_ARANGE: ggml_vk_arange(ctx, compute_ctx, node); @@ -12855,10 +13049,6 @@ bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, in default: return false; } - break; - case GGML_OP_DIAG_MASK_INF: - ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node); - break; case GGML_OP_SOFT_MAX: if (ctx->fused_topk_moe_mode != TOPK_MOE_COUNT) { @@ -13345,6 +13535,54 @@ bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_ UNUSED(buffer); } +static vk_buffer & ggml_vk_tensor_dev_buffer(const ggml_tensor * tensor) { + ggml_backend_buffer_t buffer = tensor->view_src ? tensor->view_src->buffer : tensor->buffer; + return ((ggml_backend_vk_buffer_context *) buffer->context)->dev_buffer; +} + +void ggml_backend_vk_buffer_set_tensor_n(ggml_backend_buffer_t buffer, ggml_tensor * const * tensors, const void * const * data, + const size_t * offsets, const size_t * sizes, size_t n_tensors) { + VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor_n(" << buffer << ", " << n_tensors << ")"); + std::vector regions(n_tensors); + for (size_t i = 0; i < n_tensors; i++) { + regions[i] = { ggml_vk_tensor_dev_buffer(tensors[i]), vk_tensor_offset(tensors[i]) + tensors[i]->view_offs + offsets[i], const_cast(data[i]), sizes[i] }; + } + ggml_vk_buffer_write_n(regions.data(), n_tensors); + + UNUSED(buffer); +} + +void ggml_backend_vk_buffer_get_tensor_n(ggml_backend_buffer_t buffer, const ggml_tensor * const * tensors, void * const * data, + const size_t * offsets, const size_t * sizes, size_t n_tensors) { + VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor_n(" << buffer << ", " << n_tensors << ")"); + std::vector regions(n_tensors); + for (size_t i = 0; i < n_tensors; i++) { + regions[i] = { ggml_vk_tensor_dev_buffer(tensors[i]), vk_tensor_offset(tensors[i]) + tensors[i]->view_offs + offsets[i], data[i], sizes[i] }; + } + ggml_vk_buffer_read_n(regions.data(), n_tensors); + + UNUSED(buffer); +} + +bool ggml_backend_vk_buffer_cpy_tensor_n(ggml_backend_buffer_t buffer, const ggml_tensor * const * srcs, ggml_tensor * const * dsts, size_t n_tensors) { + VK_LOG_DEBUG("ggml_backend_vk_buffer_cpy_tensor_n(" << buffer << ", " << n_tensors << ")"); + for (size_t i = 0; i < n_tensors; i++) { + if (!ggml_backend_buffer_is_vk(srcs[i]->view_src ? srcs[i]->view_src->buffer : srcs[i]->buffer)) { + return false; + } + } + + std::vector regions(n_tensors); + for (size_t i = 0; i < n_tensors; i++) { + regions[i] = { ggml_vk_tensor_dev_buffer(dsts[i]), vk_tensor_offset(dsts[i]) + dsts[i]->view_offs, + ggml_vk_tensor_dev_buffer(srcs[i]), vk_tensor_offset(srcs[i]) + srcs[i]->view_offs, ggml_nbytes(srcs[i]) }; + } + ggml_vk_buffer_copy_n(regions.data(), n_tensors); + return true; + + UNUSED(buffer); +} + void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) { ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context; @@ -16077,10 +16315,6 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm case GGML_OP_CONCAT: { return ggml_vk_concat_supported(op->src[0], op->src[1], op); } - case GGML_OP_ADD1: - return (op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32) - || (op->src[0]->type == GGML_TYPE_F16 && op->src[1]->type == GGML_TYPE_F32) - || (op->src[0]->type == GGML_TYPE_F16 && op->src[1]->type == GGML_TYPE_F16); case GGML_OP_ARANGE: return op->type == GGML_TYPE_F32; case GGML_OP_FILL: @@ -16091,8 +16325,6 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm case GGML_OP_PAD_REFLECT_1D: case GGML_OP_ROLL: return op->src[0]->type == GGML_TYPE_F32; - case GGML_OP_DIAG_MASK_INF: - return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32; case GGML_OP_SOFT_MAX: return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32 && (!op->src[1] || (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)); diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/diag_mask_inf.comp b/ggml/src/ggml-vulkan/vulkan-shaders/diag_mask_inf.comp deleted file mode 100644 index 9cef8a8ec3d2..000000000000 --- a/ggml/src/ggml-vulkan/vulkan-shaders/diag_mask_inf.comp +++ /dev/null @@ -1,34 +0,0 @@ -#version 450 - -#extension GL_EXT_shader_16bit_storage : require -#extension GL_EXT_control_flow_attributes : enable - -layout (push_constant) uniform parameter -{ - uint ncols; - uint rows_per_channel; - uint n_past; -} p; - -#include "types.glsl" - -layout(local_size_x = 1, local_size_y = 512, local_size_z = 1) in; - -layout (binding = 0) readonly buffer X {A_TYPE data_a[];}; -layout (binding = 1) writeonly buffer D {D_TYPE data_d[];}; - -void main() { - const uint col = gl_GlobalInvocationID.y; - const uint row = gl_GlobalInvocationID.x; - - if (col >= p.ncols) { - return; - } - - const uint i = row*p.ncols + col; - if (col > p.n_past + row % p.rows_per_channel) { - data_d[i] = D_TYPE(uintBitsToFloat(0xFF800000)); - } else { - data_d[i] = D_TYPE(data_a[i]); - } -} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_decode_phase_1.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_decode_phase_1.comp index b5f95aaa0d5f..53beab149963 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_decode_phase_1.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_decode_phase_1.comp @@ -3,261 +3,327 @@ #extension GL_EXT_control_flow_attributes : enable #extension GL_EXT_shader_16bit_storage : require #extension GL_EXT_shader_explicit_arithmetic_types_float16 : require -#extension GL_EXT_shader_explicit_arithmetic_types_int16 : require #extension GL_KHR_memory_scope_semantics : enable #extension GL_KHR_shader_subgroup_basic : enable -#extension GL_KHR_shader_subgroup_ballot : enable #extension GL_KHR_shader_subgroup_arithmetic : enable #extension GL_KHR_cooperative_matrix : enable #extension GL_EXT_shared_memory_block : enable -layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in; +layout (local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in; -layout (binding = 0) readonly buffer Q {float16_t qState[];}; -layout (binding = 1) readonly buffer K_VEC4 {f16vec4 kStateVec4[];}; -layout (binding = 2) buffer MASK_F16 {float16_t mState_f16[];}; -layout (binding = 3) buffer P_FP16 {float16_t matP_f16[];}; -layout (binding = 4) buffer OUT_MAX {float out_max_f32[];}; +layout (binding = 0) readonly buffer Q {float16_t data_q[];}; +layout (binding = 1) readonly buffer KV4 {f16vec4 data_kv4[];}; +layout (binding = 2) readonly buffer M {float16_t data_m[];}; +layout (binding = 3) buffer P {float16_t data_p[];}; +layout (binding = 4) buffer MAX {float data_max[];}; layout (push_constant) uniform parameter { - uint kvSeqLen; - uint activationLength; - uint qHead; - uint kvHead; - uint qkRatio; - uint qkSubGroups; - uint flag; - uint kvStride1; - uint kvStride2; - uint batchStrideQ; - uint batchStrideK; - uint batchStrideV; - uint batchStrideM; - uint batchStrideO; - float softMaxScale; + uint neq1; + uint neq2; + uint neq3; + uint nek1; + uint nek2; + uint nek3; + uint nev2; + uint nev3; + uint nem1; + uint nem2; + uint nem3; + uint nbq1; + uint nbq2; + uint nbk1; + uint nbk2; + uint nbv1; + uint nbv2; + uint nbq3; + uint nbk3; + uint nbv3; + uint nb3; + uint flag; + float scale; } p; -layout (constant_id = 0) const uint GROUPSIZE = 128; -layout (constant_id = 1) const uint GQA_RATIO = 8; -layout (constant_id = 2) const uint HEAD_DIM = 128; -layout (constant_id = 3) const uint WARPSIZE = 16; -layout (constant_id = 4) const uint MATP_REDUCE = 32; -layout (constant_id = 5) const uint N_TOK = 1; -layout (constant_id = 6) const uint COOP_MAT_P_PER_LOOP = 4; - -#define MAX_HEADS 8 - -#define TN WARPSIZE -#define TM 8 -#define TK 16 -#define SUBGROUP_COUNT (GROUPSIZE / WARPSIZE) -#define MATP_PER_LOOP (COOP_MAT_P_PER_LOOP * TM) -#define P_LOOP_COUNT (MATP_REDUCE / MATP_PER_LOOP) - -#define COOP_MAT_Q_PER_TOKEN ((GQA_RATIO + TN - 1) / TN) -#define COOP_MAT_P_M COOP_MAT_Q_PER_TOKEN -#define COOP_MAT_P_N (MATP_REDUCE / TM) -#define SLM_PV_SIZE (MATP_REDUCE * COOP_MAT_P_M * TN) -#define SLM_MASK_SIZE (N_TOK * MATP_REDUCE) -#define SLM_POOL_SIZE_K (MATP_PER_LOOP * HEAD_DIM) -#define K_LOAD_PER_LOOP (GROUPSIZE * 4) -#define HEAD_DIM_VEC4 (HEAD_DIM / 4) -#define SLM_CHUNK_SIZE (TK / 4) -#define K_LOAD_LOOPS ((SLM_POOL_SIZE_K + K_LOAD_PER_LOOP - 1) / K_LOAD_PER_LOOP) -#define O_COUNT ((GQA_RATIO + SUBGROUP_COUNT - 1) / SUBGROUP_COUNT) - -shared slm_pool_block { - float slm_pool_pv[SLM_PV_SIZE + SLM_MASK_SIZE]; -} slm_pool_f32; - -shared slm_pool_alias_block { - float16_t slm_pool_k[SLM_POOL_SIZE_K]; -} slm_pool_f16; +layout (constant_id = 0) const uint WorkGroupSize = 128; +layout (constant_id = 1) const uint gqa_ratio = 8; +layout (constant_id = 2) const uint HSK = 128; +layout (constant_id = 3) const uint SubGroupSize = 16; +layout (constant_id = 4) const uint p_reduce = 32; +layout (constant_id = 5) const uint Br = 1; +layout (constant_id = 6) const uint pmat_count = 4; +layout (constant_id = 7) const uint TM = 8; +layout (constant_id = 8) const uint TN = 16; +layout (constant_id = 9) const uint shmem_size = 49152; + +const uint TK = 16; +const uint sg_count = WorkGroupSize / SubGroupSize; +const uint p_per_loop = pmat_count * TM; +const uint p_loops = p_reduce / p_per_loop; + +const uint pmat_row = (gqa_ratio + TN - 1) / TN; +const uint pmat_col = p_reduce / TM; + +const uint k_per_loop = WorkGroupSize * 4; +const uint hsk_v4 = HSK / 4; +const uint slm_col_chunk = TK / 4; +const uint k_loops = (p_per_loop * HSK + k_per_loop - 1) / k_per_loop; +const uint warp_o_row = (gqa_ratio + sg_count - 1) / sg_count; + +#define SLM_PV_SIZE (p_reduce * pmat_row * TN) +#define SLM_MASK_SIZE (Br * p_reduce) + +const bool k_in_shmem = k_loops * k_per_loop <= shmem_size / 2; +const uint ksh_size = k_in_shmem ? (k_loops * k_per_loop) : (sg_count * TM * TK); + +shared sh_block { + float F32sh[SLM_PV_SIZE + SLM_MASK_SIZE]; +} F32Poolsh; + +shared shf16_alias { + float16_t F16sh[ksh_size]; +} F16Poolsh; + +shared shf16v4_alias { + f16vec4 F16V4sh[ksh_size / 4]; +} F16V4Poolsh; void main() { - const uint lane = gl_SubgroupInvocationID; - const uint kHeadIdx = gl_WorkGroupID.x % p.kvHead; - const uint outGroupIdx = gl_WorkGroupID.x / p.kvHead; - const uint v = gl_WorkGroupID.y; - const uint d = gl_WorkGroupID.z; - const uint localLinearId = gl_SubgroupID; - const uint wgLane = localLinearId * WARPSIZE + lane; - const uint qDim = p.qHead * HEAD_DIM; - const uint kvDim = p.kvStride1; - const uint maskDim = p.kvSeqLen; - const uint maxDim = (p.kvSeqLen + MATP_REDUCE - 1) / MATP_REDUCE; - const uint pDim = maxDim * MATP_REDUCE; - const uint tokFlatIdx = localLinearId + outGroupIdx * N_TOK; - uint offsetBaseQ = min(tokFlatIdx, p.activationLength - 1) * qDim; - offsetBaseQ = offsetBaseQ + d * p.batchStrideQ + kHeadIdx * HEAD_DIM * GQA_RATIO; - const uint offsetBaseK = (d * p.batchStrideK + (v * MATP_REDUCE) * kvDim + kHeadIdx * p.kvStride2) / 4; - uint offsetOut = d * p.qHead * p.activationLength * pDim + v * MATP_REDUCE + kHeadIdx * GQA_RATIO * pDim + (localLinearId * O_COUNT + outGroupIdx * N_TOK * p.qHead) * pDim + lane; - uint offsetMax = d * p.qHead * p.activationLength * maxDim + v + kHeadIdx * GQA_RATIO * maxDim + (localLinearId * O_COUNT + outGroupIdx * N_TOK * p.qHead) * maxDim; - const uint offsetSlmLoadPv = (localLinearId * O_COUNT * MATP_REDUCE + lane); - const uint offsetBaseM = v * MATP_REDUCE + lane; - const float fp32Min = uintBitsToFloat(0xFEFFFFFF); - - const uint loopCount = HEAD_DIM / TK; - float maskFp32[MATP_REDUCE / WARPSIZE]; - - if (tokFlatIdx < p.activationLength) { - [[unroll]] for (uint mk = 0; mk < MATP_REDUCE / WARPSIZE; mk++) { - const uint maskOffset = mk * WARPSIZE + offsetBaseM; - if (maskOffset < maskDim) { - maskFp32[mk] = float(mState_f16[d * p.batchStrideM + tokFlatIdx * maskDim + maskOffset]); - } else { - maskFp32[mk] = fp32Min; - } + const uint lane = gl_SubgroupInvocationID; + const uint head_k_idx = gl_WorkGroupID.x % p.nek2; + const uint out_idx = gl_WorkGroupID.x / p.nek2; + const uint p_idx = gl_WorkGroupID.y; + const uint batch_k_ratio = p.neq3 / p.nek3; + const uint batch_idx = gl_WorkGroupID.z; + const uint batch_k_idx = batch_idx / batch_k_ratio; + const uint batch_mask_idx = batch_idx % p.nem3; + const uint batch_mask_stride = p.nek1 * p.nem1 * p.nem2; + const uint sg = gl_SubgroupID; + const uint wg_lane = sg * SubGroupSize + lane; + const uint k_dim = p.nbk1; + const uint max_dim = (p.nek1 + p_reduce - 1) / p_reduce; + const uint p_dim = max_dim * p_reduce; + const uint out_row_idx = sg + out_idx * Br; + const bool single_head_mask = p.nem2 == 1; + uint q_offset = min(out_row_idx, p.neq1 - 1) * p.nbq1; + q_offset = q_offset + batch_idx * p.nbq3 + head_k_idx * p.nbq2 * gqa_ratio; + const uint k_base = (batch_k_idx * p.nbk3 + (p_idx * p_reduce) * k_dim + head_k_idx * p.nbk2) / 4; + uint o_offset = batch_idx * p.neq2 * p.neq1 * p_dim + p_idx * p_reduce + head_k_idx * gqa_ratio * p_dim + + (sg * warp_o_row + out_idx * Br * p.neq2) * p_dim + lane; + uint max_offset = batch_idx * p.neq2 * p.neq1 * max_dim + p_idx + head_k_idx * gqa_ratio * max_dim + + (sg * warp_o_row + out_idx * Br * p.neq2) * max_dim; + const uint pvsh_load_offset = sg * warp_o_row * p_reduce + lane; + const uint mask_base = p_idx * p_reduce + lane; + const uint k_seq_boundary = ((p.nek1 - 1) * k_dim + batch_k_idx * p.nbk3 + head_k_idx * p.nbk2 + HSK) / 4 - 1; + const uint k_head_base = (batch_k_idx * p.nbk3 + head_k_idx * p.nbk2) / 4; + const float NEG_FLT_MAX_OVER_2 = uintBitsToFloat(0xFEFFFFFF); + + float Maskf[p_reduce / SubGroupSize]; + + if (out_row_idx < p.neq1 && single_head_mask) { + if (out_row_idx < p.nem1) { + [[unroll]] for (uint idx = 0; idx < p_reduce / SubGroupSize; ++idx) { + const uint mask_offset = idx * SubGroupSize + mask_base; + if (mask_offset < p.nek1) { + Maskf[idx] = float(data_m[batch_mask_idx * batch_mask_stride + out_row_idx * p.nek1 + mask_offset]); + } else { + Maskf[idx] = NEG_FLT_MAX_OVER_2; + } + } + } else { + [[unroll]] for (uint idx = 0; idx < p_reduce / SubGroupSize; ++idx) { + const uint mask_offset = idx * SubGroupSize + mask_base; + Maskf[idx] = (mask_offset < p.nek1) ? 0.0f : NEG_FLT_MAX_OVER_2; + } + } } - } - coopmat matP[COOP_MAT_P_M][COOP_MAT_P_N]; + coopmat PMat[pmat_row][pmat_col]; - [[unroll]] for (uint mp = 0; mp < COOP_MAT_P_M; mp++) { - [[unroll]] for (uint np = 0; np < COOP_MAT_P_N; np++) { - matP[mp][np] = coopmat(0.0f); + [[unroll]] for (uint r = 0; r < pmat_row; ++r) { + [[unroll]] for (uint c = 0; c < pmat_col; ++c) { + PMat[r][c] = coopmat(0.0f); + } } - } - - [[unroll]] for (uint kLoad = 0; kLoad < K_LOAD_LOOPS; kLoad++) { - const uint flatOffset = kLoad * GROUPSIZE + wgLane; - const uint kRowIdx = flatOffset / HEAD_DIM_VEC4; - const uint kColIdx = flatOffset % HEAD_DIM_VEC4; - const uint slmChunkCol = kColIdx % SLM_CHUNK_SIZE; - const uint slmChunkRow = kColIdx / SLM_CHUNK_SIZE; - const uint offsetK = offsetBaseK + kRowIdx * kvDim / 4 + kColIdx; - const uint offsetSlmK = kRowIdx * TK + slmChunkRow * TK * MATP_PER_LOOP + slmChunkCol * 4; - slm_pool_f16.slm_pool_k[offsetSlmK + 0] = kStateVec4[offsetK].x; - slm_pool_f16.slm_pool_k[offsetSlmK + 1] = kStateVec4[offsetK].y; - slm_pool_f16.slm_pool_k[offsetSlmK + 2] = kStateVec4[offsetK].z; - slm_pool_f16.slm_pool_k[offsetSlmK + 3] = kStateVec4[offsetK].w; - } - - [[unroll]] for (uint pLoop = 0; pLoop < P_LOOP_COUNT; pLoop++) { - f16vec4 kTemp[K_LOAD_LOOPS]; - - if (pLoop + 1 < P_LOOP_COUNT) { - [[unroll]] for (uint kLoad = 0; kLoad < K_LOAD_LOOPS; kLoad++) { - const uint flatOffset = kLoad * GROUPSIZE + wgLane; - const uint kRowIdx = flatOffset / HEAD_DIM_VEC4 + (pLoop + 1) * MATP_PER_LOOP; - const uint kColIdx = flatOffset % HEAD_DIM_VEC4; - const uint offsetK = offsetBaseK + kRowIdx * kvDim / 4 + kColIdx; - kTemp[kLoad] = kStateVec4[offsetK]; - } + + if (k_in_shmem) { + [[unroll]] for (uint idx = 0; idx < k_loops; ++idx) { + const uint flat_offset = idx * WorkGroupSize + wg_lane; + const uint row_idx = flat_offset / hsk_v4; + const uint col_idx = flat_offset % hsk_v4; + const uint sh_chunk_c = col_idx % slm_col_chunk; + const uint sh_chunk_r = col_idx / slm_col_chunk; + uint k_offset = k_base + row_idx * k_dim / 4 + col_idx; + k_offset = min(k_offset, k_seq_boundary); + const uint ksh_offset = (row_idx * TK + sh_chunk_r * TK * p_per_loop) / 4 + sh_chunk_c; + F16V4Poolsh.F16V4sh[ksh_offset] = data_kv4[k_offset]; + } } - barrier(); - if (localLinearId < N_TOK) { - [[unroll]] for (uint loop = 0; loop < loopCount; loop++) { - coopmat matQ[COOP_MAT_P_M]; - coopmat matK[COOP_MAT_P_PER_LOOP]; - - [[unroll]] for (uint mq = 0; mq < COOP_MAT_P_M; mq++) { - coopMatLoad( - matQ[mq], - qState, - offsetBaseQ + mq * TN * HEAD_DIM + loop * TK, - HEAD_DIM, - gl_CooperativeMatrixLayoutColumnMajor); + [[unroll]] for (uint pl = 0; pl < p_loops; ++pl) { + f16vec4 kv4_temp[k_loops]; + + if (k_in_shmem) { + if (pl + 1 < p_loops) { + [[unroll]] for (uint idx = 0; idx < k_loops; ++idx) { + const uint flat_offset = idx * WorkGroupSize + wg_lane; + const uint row_idx = flat_offset / hsk_v4 + (pl + 1) * p_per_loop; + const uint col_idx = flat_offset % hsk_v4; + uint k_offset = k_base + row_idx * k_dim / 4 + col_idx; + k_offset = min(k_offset, k_seq_boundary); + kv4_temp[idx] = data_kv4[k_offset]; + } + } } - [[unroll]] for (uint np = 0; np < COOP_MAT_P_PER_LOOP; np++) { - coopMatLoad( - matK[np], - slm_pool_f16.slm_pool_k, - loop * TK * MATP_PER_LOOP + np * TM * TK, - TK, - gl_CooperativeMatrixLayoutRowMajor); + barrier(); + if (sg < Br) { + [[unroll]] for (uint loop = 0; loop < HSK / TK; ++loop) { + coopmat QMat[pmat_row]; + coopmat KMat[pmat_count]; + + [[unroll]] for (uint r = 0; r < pmat_row; ++r) { + const uint coord = q_offset + r * TN * p.nbq2 + loop * TK; + coopMatLoad(QMat[r], data_q, coord, p.nbq2, gl_CooperativeMatrixLayoutColumnMajor); + } + + [[unroll]] for (uint c = 0; c < pmat_count; ++c) { + if (k_in_shmem) { + const uint coord = loop * TK * p_per_loop + c * TM * TK; + coopMatLoad(KMat[c], F16Poolsh.F16sh, coord, TK, gl_CooperativeMatrixLayoutRowMajor); + } else { + const uint k_base_row = (c * TM + pl * pmat_count * TM + p_idx * p_reduce); + const uint kv4_base_offset = k_head_base + k_base_row * p.nbk1 / 4 + loop * TK / 4; + [[unroll]] for (uint idx = 0; idx < TM * TK / 4 / SubGroupSize; ++idx) { + const uint flat_offset = idx * SubGroupSize + lane; + const uint row_idx = flat_offset / (TK / 4); + const uint col_idx = flat_offset % (TK / 4); + const uint k_temp_offset = kv4_base_offset + row_idx * p.nbk1 / 4 + col_idx; + const uint ksh_temp_offset = sg * TM * TK / 4 + idx * SubGroupSize + lane; + f16vec4 kv4_temp = (k_base_row + row_idx) < p.nek1 ? data_kv4[k_temp_offset] : f16vec4(0.0f, 0.0f, 0.0f, 0.0f); + F16V4Poolsh.F16V4sh[ksh_temp_offset] = kv4_temp; + } + + subgroupBarrier(); + coopMatLoad(KMat[c], F16Poolsh.F16sh, sg * TM * TK, TK, gl_CooperativeMatrixLayoutRowMajor); + subgroupBarrier(); + } + } + + [[unroll]] for (uint r = 0; r < pmat_row; ++r) { + [[unroll]] for (uint c = 0; c < pmat_count; ++c) { + PMat[r][pl * pmat_count + c] = coopMatMulAdd(KMat[c], QMat[r], PMat[r][pl * pmat_count + c]); + } + } + } } - [[unroll]] for (uint mp = 0; mp < COOP_MAT_P_M; mp++) { - [[unroll]] for (uint np = 0; np < COOP_MAT_P_PER_LOOP; np++) { - matP[mp][pLoop * COOP_MAT_P_PER_LOOP + np] = coopMatMulAdd(matK[np], matQ[mp], matP[mp][pLoop * COOP_MAT_P_PER_LOOP + np]); - } + barrier(); + + if (k_in_shmem) { + if (pl + 1 < p_loops) { + [[unroll]] for (uint idx = 0; idx < k_loops; ++idx) { + const uint flat_offset = idx * WorkGroupSize + wg_lane; + const uint row_idx = flat_offset / hsk_v4; + const uint col_idx = flat_offset % hsk_v4; + const uint sh_chunk_c = col_idx % slm_col_chunk; + const uint sh_chunk_r = col_idx / slm_col_chunk; + const uint ksh_offset = (row_idx * TK + sh_chunk_r * TK * p_per_loop) / 4 + sh_chunk_c; + F16V4Poolsh.F16V4sh[ksh_offset] = kv4_temp[idx]; + } + } } - } } barrier(); - if (pLoop + 1 < P_LOOP_COUNT) { - [[unroll]] for (uint kLoad = 0; kLoad < K_LOAD_LOOPS; kLoad++) { - const uint flatOffset = kLoad * GROUPSIZE + wgLane; - const uint kRowIdx = flatOffset / HEAD_DIM_VEC4; - const uint kColIdx = flatOffset % HEAD_DIM_VEC4; - const uint slmChunkCol = kColIdx % SLM_CHUNK_SIZE; - const uint slmChunkRow = kColIdx / SLM_CHUNK_SIZE; - const uint offsetSlmK = kRowIdx * TK + slmChunkRow * TK * MATP_PER_LOOP + slmChunkCol * 4; - slm_pool_f16.slm_pool_k[offsetSlmK + 0] = kTemp[kLoad].x; - slm_pool_f16.slm_pool_k[offsetSlmK + 1] = kTemp[kLoad].y; - slm_pool_f16.slm_pool_k[offsetSlmK + 2] = kTemp[kLoad].z; - slm_pool_f16.slm_pool_k[offsetSlmK + 3] = kTemp[kLoad].w; - } - } - } - - barrier(); - - if (tokFlatIdx < p.activationLength) { - [[unroll]] for (uint mk = 0; mk < MATP_REDUCE / WARPSIZE; mk++) { - slm_pool_f32.slm_pool_pv[SLM_PV_SIZE + localLinearId * MATP_REDUCE + mk * WARPSIZE + lane] = maskFp32[mk]; - } - } - - [[unroll]] for (uint oLoop = 0; oLoop < N_TOK; oLoop++) { - if (oLoop + outGroupIdx * N_TOK < p.activationLength) { - if (localLinearId == oLoop) { - [[unroll]] for (uint mp = 0; mp < COOP_MAT_P_M; mp++) { - [[unroll]] for (uint np = 0; np < COOP_MAT_P_N; np++) { - coopMatStore(matP[mp][np], slm_pool_f32.slm_pool_pv, mp * MATP_REDUCE * TN + np * TM, MATP_REDUCE, gl_CooperativeMatrixLayoutColumnMajor); - } - } - } - - barrier(); - - [[unroll]] for (uint maskIdx = 0; maskIdx < MATP_REDUCE / WARPSIZE; maskIdx++) { - maskFp32[maskIdx] = slm_pool_f32.slm_pool_pv[SLM_PV_SIZE + oLoop * MATP_REDUCE + maskIdx * WARPSIZE + lane]; - } - - float fp32O[O_COUNT][MATP_REDUCE / WARPSIZE]; - float maxOut[O_COUNT]; - - [[unroll]] for (uint oc = 0; oc < O_COUNT; oc++) { - [[unroll]] for (uint os = 0; os < MATP_REDUCE / WARPSIZE; os++) { - fp32O[oc][os] = slm_pool_f32.slm_pool_pv[offsetSlmLoadPv + os * WARPSIZE + oc * MATP_REDUCE] * p.softMaxScale; + if (sg < Br && out_row_idx < p.neq1 && single_head_mask) { + [[unroll]] for (uint idx = 0; idx < p_reduce / SubGroupSize; ++idx) { + F32Poolsh.F32sh[SLM_PV_SIZE + sg * p_reduce + idx * SubGroupSize + lane] = Maskf[idx]; } + } - [[unroll]] for (uint os = 0; os < MATP_REDUCE / WARPSIZE; os++) { - fp32O[oc][os] = fp32O[oc][os] + maskFp32[os]; - } - - float maxTemp = fp32Min; - [[unroll]] for (uint os = 0; os < MATP_REDUCE / WARPSIZE; os++) { - maxTemp = max(maxTemp, fp32O[oc][os]); - } - maxOut[oc] = subgroupMax(maxTemp); - [[unroll]] for (uint os = 0; os < MATP_REDUCE / WARPSIZE; os++) { - fp32O[oc][os] = exp(fp32O[oc][os] - maxOut[oc]); - } - } - - [[unroll]] for (uint oc = 0; oc < O_COUNT; oc++) { - if (localLinearId * O_COUNT + oc < GQA_RATIO) { - [[unroll]] for (uint os = 0; os < MATP_REDUCE / WARPSIZE; os++) { - matP_f16[offsetOut + oc * pDim + os * WARPSIZE] = float16_t(fp32O[oc][os]); - } - - if (lane == 0) { - out_max_f32[offsetMax + oc * maxDim] = maxOut[oc]; - } + [[unroll]] for (uint out_r = 0; out_r < Br; ++out_r) { + if (out_r + out_idx * Br < p.neq1) { + const uint mask_global_base = batch_mask_idx * batch_mask_stride + (out_r + out_idx * Br) * p.nek1; + if (sg == out_r) { + [[unroll]] for (uint r = 0; r < pmat_row; ++r) { + [[unroll]] for (uint c = 0; c < pmat_col; ++c) { + const uint coord = r * p_reduce * TN + c * TM; + coopMatStore(PMat[r][c], F32Poolsh.F32sh, coord, p_reduce, gl_CooperativeMatrixLayoutColumnMajor); + } + } + } + + barrier(); + + if (single_head_mask) { + [[unroll]] for (uint idx = 0; idx < p_reduce / SubGroupSize; ++idx) { + Maskf[idx] = F32Poolsh.F32sh[SLM_PV_SIZE + out_r * p_reduce + idx * SubGroupSize + lane]; + } + } + + float Of[warp_o_row][p_reduce / SubGroupSize]; + float Mf[warp_o_row]; + + [[unroll]] for (uint r = 0; r < warp_o_row; ++r) { + const uint head_q_idx = head_k_idx * gqa_ratio + sg * warp_o_row + r; + const uint mask_head_offset = (head_q_idx % p.nem2) * p.nek1 * p.nem1; + + [[unroll]] for (uint idx = 0; idx < p_reduce / SubGroupSize; ++idx) { + Of[r][idx] = F32Poolsh.F32sh[pvsh_load_offset + idx * SubGroupSize + r * p_reduce] * p.scale; + } + + if (!single_head_mask) { + if (out_r + out_idx * Br < p.nem1) { + [[unroll]] for (uint idx = 0; idx < p_reduce / SubGroupSize; ++idx) { + const uint mask_offset = idx * SubGroupSize + mask_base; + if (mask_offset < p.nek1) { + Maskf[idx] = float(data_m[mask_global_base + mask_head_offset + mask_offset]); + } else { + Maskf[idx] = NEG_FLT_MAX_OVER_2; + } + } + } else { + [[unroll]] for (uint idx = 0; idx < p_reduce / SubGroupSize; ++idx) { + const uint mask_offset = idx * SubGroupSize + mask_base; + Maskf[idx] = (mask_offset < p.nek1) ? 0.0f : NEG_FLT_MAX_OVER_2; + } + } + } + + [[unroll]] for (uint idx = 0; idx < p_reduce / SubGroupSize; ++idx) { + Of[r][idx] = Of[r][idx] + Maskf[idx]; + } + + float Mtempf = NEG_FLT_MAX_OVER_2; + [[unroll]] for (uint idx = 0; idx < p_reduce / SubGroupSize; ++idx) { + const uint p_col_offset = idx * SubGroupSize + mask_base; + if (p_col_offset < p.nek1) { + Mtempf = max(Mtempf, Of[r][idx]); + } + } + Mf[r] = subgroupMax(Mtempf); + [[unroll]] for (uint idx = 0; idx < p_reduce / SubGroupSize; ++idx) { + const uint p_col_offset = idx * SubGroupSize + mask_base; + Of[r][idx] = (p_col_offset < p.nek1) ? exp(Of[r][idx] - Mf[r]) : 0.0f; + } + } + + [[unroll]] for (uint r = 0; r < warp_o_row; ++r) { + if (sg * warp_o_row + r < gqa_ratio) { + [[unroll]] for (uint idx = 0; idx < p_reduce / SubGroupSize; ++idx) { + data_p[o_offset + r * p_dim + idx * SubGroupSize] = float16_t(Of[r][idx]); + } + + if (lane == 0) { + data_max[max_offset + r * max_dim] = Mf[r]; + } + } + } + + o_offset = o_offset + p.neq2 * p_dim; + max_offset = max_offset + p.neq2 * max_dim; + barrier(); } - } - - offsetOut = offsetOut + p.qHead * pDim; - offsetMax = offsetMax + p.qHead * maxDim; - barrier(); } - } } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_decode_phase_2.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_decode_phase_2.comp index 60a1c2ce7362..42a5101d8542 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_decode_phase_2.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_decode_phase_2.comp @@ -3,406 +3,470 @@ #extension GL_EXT_control_flow_attributes : enable #extension GL_EXT_shader_16bit_storage : require #extension GL_EXT_shader_explicit_arithmetic_types_float16 : require -#extension GL_EXT_shader_explicit_arithmetic_types_int16 : require #extension GL_KHR_memory_scope_semantics : enable #extension GL_KHR_shader_subgroup_basic : enable -#extension GL_KHR_shader_subgroup_ballot : enable #extension GL_KHR_shader_subgroup_arithmetic : enable #extension GL_KHR_cooperative_matrix : enable #extension GL_EXT_shared_memory_block : enable -layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in; +layout (local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in; -layout (binding = 0) readonly buffer P {f16vec4 pStateVec4[];}; -layout (binding = 1) readonly buffer V {float16_t vState[];}; -layout (binding = 1) readonly buffer V_VEC4 {f16vec4 vStateVec4[];}; -layout (binding = 2) buffer MAX_FP32 {float max_f32[];}; -layout (binding = 3) buffer SINK_FP32 {float sink_f32[];}; -layout (binding = 4) buffer OUT_FP32 {float out_f32[];}; -layout (binding = 4) buffer OUT_VEC4 {vec4 out_f32_vec4[];}; -layout (binding = 4) buffer OUT_F16 {float16_t out_f16[];}; +layout (binding = 0) readonly buffer PV4 {f16vec4 data_pv4[];}; +layout (binding = 1) readonly buffer V {float16_t data_v[];}; +layout (binding = 1) readonly buffer VV4 {f16vec4 data_vv4[];}; +layout (binding = 2) readonly buffer MAX {float data_max[];}; +layout (binding = 3) readonly buffer S {float data_s[];}; +layout (binding = 4) buffer OV4 {vec4 data_ov4[];}; layout (push_constant) uniform parameter { - uint kvSeqLen; - uint activationLength; - uint qHead; - uint kvHead; - uint qkRatio; - uint qkSubGroups; - uint flag; - uint kvStride1; - uint kvStride2; - uint batchStrideQ; - uint batchStrideK; - uint batchStrideV; - uint batchStrideM; - uint batchStrideO; - float softMaxScale; + uint neq1; + uint neq2; + uint neq3; + uint nek1; + uint nek2; + uint nek3; + uint nev2; + uint nev3; + uint nem1; + uint nem2; + uint nem3; + uint nbq1; + uint nbq2; + uint nbk1; + uint nbk2; + uint nbv1; + uint nbv2; + uint nbq3; + uint nbk3; + uint nbv3; + uint nb3; + uint flag; + float scale; } p; -layout (constant_id = 0) const uint GROUPSIZE = 256; -layout (constant_id = 1) const uint GQA_RATIO = 8; -layout (constant_id = 2) const uint HEAD_DIM = 128; -layout (constant_id = 3) const uint N_TOKS_PER_GROUP = 1; -layout (constant_id = 4) const uint WARPSIZE = 16; -layout (constant_id = 5) const uint MATP_PER_LOOP = 64; -layout (constant_id = 6) const uint MATP_REDUCE = 32; -layout (constant_id = 7) const uint WARP_V_DIM = 16; - -#define TN WARPSIZE -#define TM 8 -#define TK 16 -#define MAT_O_N (WARP_V_DIM / TM) -#define MAT_P_M (GQA_RATIO * N_TOKS_PER_GROUP) -#define ALIGNED_P_M ((MAT_P_M + WARPSIZE - 1) / WARPSIZE) -#define V_HEAD_GROUPS (HEAD_DIM / WARP_V_DIM) - -#define SUBGROUP_COUNT (GROUPSIZE / WARPSIZE) -#define SPLIT_P_GROUPS (MATP_PER_LOOP / TK) - -#define SLM_POOL_SIZE_O (SUBGROUP_COUNT * ALIGNED_P_M * TN * MAT_O_N * TM) - -#define P_LOAD_PER_LOOP (GROUPSIZE * 4) -#define P_LOAD_LOOPS ((MAT_P_M * MATP_PER_LOOP + P_LOAD_PER_LOOP - 1) / P_LOAD_PER_LOOP) -#define SLM_POOL_SIZE_P (P_LOAD_LOOPS * P_LOAD_PER_LOOP) -#define SIZE_LOCAL_MAX (MAT_P_M * MATP_PER_LOOP / MATP_REDUCE) -#define MAX_LOAD_LOOPS ((SIZE_LOCAL_MAX + GROUPSIZE - 1) / GROUPSIZE) -#define SLM_POOL_SIZE_LOCAL_MAX (MAX_LOAD_LOOPS * GROUPSIZE) -#define MAX_REDUCE_COUNT ((MAT_P_M + SUBGROUP_COUNT - 1) / SUBGROUP_COUNT) -#define GLOBAL_MAX_SIZE (MAX_REDUCE_COUNT * SUBGROUP_COUNT) - -#define SLM_POOL_SIZE_SOFTMAX_SUM (SUBGROUP_COUNT * P_LOAD_LOOPS) - -#define SLM_OFFSET_P (GLOBAL_MAX_SIZE * 2 + SLM_POOL_SIZE_SOFTMAX_SUM * 2 + SLM_POOL_SIZE_LOCAL_MAX * 2 * 2) - -#define SLM_OFFSET_GLOBAL_MAX 0 -#define SLM_OFFSET_SOFTMAX_SUM (SLM_OFFSET_GLOBAL_MAX + GLOBAL_MAX_SIZE) -#define SLM_OFFSET_O (SLM_OFFSET_SOFTMAX_SUM + SLM_POOL_SIZE_SOFTMAX_SUM) -#define SLM_OFFSET_LOCAL_MAX (GLOBAL_MAX_SIZE + SLM_POOL_SIZE_SOFTMAX_SUM) - -#define P_REDUCE_VEC4 (MATP_PER_LOOP / 4) -#define MAX_PER_LOOP (MATP_PER_LOOP / MATP_REDUCE) -#define SLM_MAX_STRIDE (MATP_REDUCE / 4) -#define SUB_GROUPS_PER_LINE (MATP_PER_LOOP / WARPSIZE / 4) - -shared slm_pool_block { - float slm_pool_o[GLOBAL_MAX_SIZE + SLM_POOL_SIZE_SOFTMAX_SUM + SLM_POOL_SIZE_O]; -} slm_pool_f32; - -shared slm_pool_alias_block { - float16_t slm_pool_pv[GLOBAL_MAX_SIZE * 2 + SLM_POOL_SIZE_SOFTMAX_SUM * 2 + SLM_POOL_SIZE_LOCAL_MAX * 2 * 2 + SLM_POOL_SIZE_P * 2]; -} slm_pool_alias_f16; +layout (constant_id = 0) const uint WorkGroupSize = 256; +layout (constant_id = 1) const uint gqa_ratio = 8; +layout (constant_id = 2) const uint HSV = 128; +layout (constant_id = 3) const uint Wr = 1; +layout (constant_id = 4) const uint SubGroupSize = 16; +layout (constant_id = 5) const uint p_per_loop = 64; +layout (constant_id = 6) const uint p_reduce = 32; +layout (constant_id = 7) const uint Bc = 16; +layout (constant_id = 8) const uint TM = 8; +layout (constant_id = 9) const uint TN = 16; +layout (constant_id = 10) const uint Flags = 0; + +#define UNALIGNED_SEQ_LEN_BIT (1 << 0) +#define SINK_ENABLE_BIT (1 << 16) + +const uint TK = 16; +const uint o_row = gqa_ratio * Wr; +const uint omat_row = (o_row + TN - 1) / TN; +const uint o_scalar_row = (o_row + SubGroupSize - 1) / SubGroupSize; + +const uint omat_col = Bc / TM; +const uint v_head_wgs = HSV / Bc; + +const uint sg_count = WorkGroupSize / SubGroupSize; +const uint split_p_sg = p_per_loop / TK; +const uint p_loop_col = WorkGroupSize * 4; +const uint p_loops = (o_row * p_per_loop + p_loop_col - 1) / p_loop_col; + +const uint size_max = o_row * p_per_loop / p_reduce; +const uint max_loops = (size_max + WorkGroupSize - 1) / WorkGroupSize; +const uint global_max_loops = (o_row + sg_count - 1) / sg_count; + +#define SLM_POOL_SIZE_GLOBAL_MAX ((global_max_loops * sg_count + SubGroupSize - 1) / SubGroupSize * SubGroupSize) +#define SLM_POOL_SIZE_O (sg_count * omat_row * TN * omat_col * TM) +#define SLM_POOL_SIZE_MAX (max_loops * WorkGroupSize) +#define SLM_POOL_SIZE_SOFTMAX_SUM ((sg_count * p_loops + SubGroupSize - 1) / SubGroupSize * SubGroupSize) +#define SLM_POOL_SIZE_OOB_STAGING (sg_count * TM * TK / 4) + +const uint psh_size = (p_loops * p_loop_col < omat_row * TN * p_per_loop) ? (omat_row * TN * p_per_loop) : (p_loops * p_loop_col); +const uint psh_base = SLM_POOL_SIZE_GLOBAL_MAX * 2 + SLM_POOL_SIZE_SOFTMAX_SUM * 2 + SLM_POOL_SIZE_MAX * 2 * 2; + +const uint global_maxsh_offset = 0; +const uint lfsh_offset = global_maxsh_offset + SLM_POOL_SIZE_GLOBAL_MAX; +const uint osh_offset = lfsh_offset + SLM_POOL_SIZE_SOFTMAX_SUM; +const uint maxsh_offset = SLM_POOL_SIZE_GLOBAL_MAX + SLM_POOL_SIZE_SOFTMAX_SUM; + +const uint p_v4 = p_per_loop / 4; +const uint max_per_loop = p_per_loop / p_reduce; +const uint maxsh_stride = p_reduce / 4; +const uint sg_per_line = p_per_loop / SubGroupSize / 4; +const bool seq_boundary_check = (Flags & UNALIGNED_SEQ_LEN_BIT) != 0; + +shared sh_block { + float F32sh[SLM_POOL_SIZE_GLOBAL_MAX + SLM_POOL_SIZE_SOFTMAX_SUM + SLM_POOL_SIZE_O]; +} F32Poolsh; + +shared shf16_alias { + float16_t F16sh[SLM_POOL_SIZE_GLOBAL_MAX * 2 + SLM_POOL_SIZE_SOFTMAX_SUM * 2 + SLM_POOL_SIZE_MAX * 2 * 2 + psh_size * 2]; +} F16Poolsh; + +shared shf16v4_alias { + f16vec4 F16V4sh[(SLM_POOL_SIZE_GLOBAL_MAX + SLM_POOL_SIZE_SOFTMAX_SUM + SLM_POOL_SIZE_MAX * 2) / 2 + SLM_POOL_SIZE_OOB_STAGING]; +} F16V4Poolsh; void main() { - const uint lane = gl_SubgroupInvocationID; - const uint v = gl_WorkGroupID.y; - const uint d = gl_WorkGroupID.z; - const uint vWarpIdx = gl_WorkGroupID.x % V_HEAD_GROUPS; - const uint outTokIdx = gl_WorkGroupID.x / V_HEAD_GROUPS; - const uint localLinearId = gl_SubgroupID; - const uint wgLane = localLinearId * WARPSIZE + lane; - const uint splitIdx = localLinearId; - const uint maxDim = (p.kvSeqLen + MATP_REDUCE - 1) / MATP_REDUCE; - const uint pDim = maxDim * MATP_REDUCE; - const uint kvDim = p.kvStride1; - const uint oDim = p.qHead * HEAD_DIM; - const uint offsetBaseP = (d * p.activationLength * p.qHead + v * GQA_RATIO + outTokIdx * N_TOKS_PER_GROUP * p.qHead) * pDim / 4; - const uint offsetBaseMax = (d * p.activationLength * p.qHead + v * GQA_RATIO + outTokIdx * N_TOKS_PER_GROUP * p.qHead) * maxDim; - const uint offsetBaseV = (d * p.batchStrideV + v * p.kvStride2 + vWarpIdx * WARP_V_DIM + splitIdx * TK * kvDim); - const uint offsetSlmP = (SLM_OFFSET_P + wgLane * 4); - const float fp32Min = uintBitsToFloat(0xFEFFFFFF); - const float fp32Max = uintBitsToFloat(0x7EFFFFFF); - uint offsetV = offsetBaseV; - - coopmat sums[ALIGNED_P_M][MAT_O_N]; - f16vec4 pStateTemp[P_LOAD_LOOPS]; - - float fp32CompensationP[P_LOAD_LOOPS]; - - uint loadRowBase[P_LOAD_LOOPS]; - uint loadColBase[P_LOAD_LOOPS]; - float fp32SoftMaxSum[P_LOAD_LOOPS]; - float fp32GlobalMaxP[P_LOAD_LOOPS]; - uint maxRowBase[MAX_LOAD_LOOPS]; - uint maxColBase[MAX_LOAD_LOOPS]; - uint outOffsets[ALIGNED_P_M]; - bool outputMask[ALIGNED_P_M]; - float fp32SinkCoeff[ALIGNED_P_M]; - - [[unroll]] for (uint pm = 0; pm < ALIGNED_P_M; pm++) { - const uint flatOffset = pm * WARPSIZE + lane; - const uint inGroupTokIdx = flatOffset / GQA_RATIO; - const uint inGroupHeadIdx = flatOffset % GQA_RATIO; - outputMask[pm] = (N_TOKS_PER_GROUP * outTokIdx + inGroupTokIdx < p.activationLength) && (inGroupHeadIdx < GQA_RATIO) && (inGroupTokIdx < N_TOKS_PER_GROUP); - outOffsets[pm] = (inGroupTokIdx * oDim + inGroupHeadIdx * HEAD_DIM) / 4; - if ((0x1 & p.flag) != 0) { - fp32SinkCoeff[pm] = sink_f32[inGroupHeadIdx + v * GQA_RATIO]; - } - } - - [[unroll]] for (uint maxCount = 0; maxCount < MAX_REDUCE_COUNT; maxCount++) { - const uint flatIdx = maxCount * SUBGROUP_COUNT + localLinearId; - const uint rowIdx = flatIdx % GQA_RATIO; - const uint tokIdx = flatIdx / GQA_RATIO; - - if (tokIdx < N_TOKS_PER_GROUP) { - float fp32MaxReduce = fp32Min; - const uint maxOffset = offsetBaseMax + (tokIdx * p.qHead + rowIdx) * maxDim; - [[unroll]] for (uint maxReduce = 0; maxReduce < (maxDim + WARPSIZE - 1) / WARPSIZE; maxReduce++) { - if (maxReduce * WARPSIZE + lane < maxDim) { - fp32MaxReduce = max(fp32MaxReduce, max_f32[maxOffset + maxReduce * WARPSIZE + lane]); + const uint lane = gl_SubgroupInvocationID; + const uint head_v_idx = gl_WorkGroupID.y; + const uint batch_v_ratio = p.neq3 / p.nev3; + const uint batch_idx = gl_WorkGroupID.z; + const uint batch_v_idx = batch_idx / batch_v_ratio; + const uint v_idx = gl_WorkGroupID.x % v_head_wgs; + const uint out_row_idx = gl_WorkGroupID.x / v_head_wgs; + const uint sg = gl_SubgroupID; + const uint wg_lane = sg * SubGroupSize + lane; + const uint max_dim = (p.nek1 + p_reduce - 1) / p_reduce; + const uint p_dim = max_dim * p_reduce; + const uint v_dim = p.nbv1; + const uint o_dim = p.neq2 * HSV; + const uint p_base = (batch_idx * p.neq1 * p.neq2 + head_v_idx * gqa_ratio + out_row_idx * Wr * p.neq2) * p_dim / 4; + const uint max_base = (batch_idx * p.neq1 * p.neq2 + head_v_idx * gqa_ratio + out_row_idx * Wr * p.neq2) * max_dim; + const uint v_base = batch_v_idx * p.nbv3 + head_v_idx * p.nbv2 + v_idx * Bc + sg * TK * v_dim; + const uint o_base = (batch_idx * p.nb3 + v_idx * Bc + head_v_idx * gqa_ratio * HSV + out_row_idx * o_dim * Wr) / 4; + const uint psh_offset = psh_base + wg_lane * 4; + const float NEG_FLT_MAX_OVER_2 = uintBitsToFloat(0xFEFFFFFF); + const float POS_FLT_MAX_OVER_2 = uintBitsToFloat(0x7EFFFFFF); + uint v_offset = v_base; + + coopmat OMat[omat_row][omat_col]; + f16vec4 pv4_temp[p_loops]; + + float eMf[p_loops]; + + uint p_row_base[p_loops]; + uint p_col_base[p_loops]; + float Lf[p_loops]; + float global_max[p_loops]; + uint max_row_base[max_loops]; + uint max_col_base[max_loops]; + uint o_offset[o_scalar_row]; + bool o_mask[o_scalar_row]; + float sink[o_scalar_row]; + + [[unroll]] for (uint r = 0; r < o_scalar_row; ++r) { + const uint flat_offset = r * SubGroupSize + lane; + const uint row_idx = flat_offset / gqa_ratio; + const uint col_idx = flat_offset % gqa_ratio; + o_mask[r] = (Wr * out_row_idx + row_idx < p.neq1) && (col_idx < gqa_ratio) && (row_idx < Wr); + o_offset[r] = (row_idx * o_dim + col_idx * HSV) / 4; + if ((p.flag & SINK_ENABLE_BIT) != 0) { + sink[r] = data_s[col_idx + head_v_idx * gqa_ratio]; } - } - fp32MaxReduce = subgroupMax(fp32MaxReduce); - if (lane == 0) { - slm_pool_f32.slm_pool_o[SLM_OFFSET_GLOBAL_MAX + maxCount * SUBGROUP_COUNT + localLinearId] = fp32MaxReduce; - } - } else { - if (lane == 0) { - slm_pool_f32.slm_pool_o[SLM_OFFSET_GLOBAL_MAX + maxCount * SUBGROUP_COUNT + localLinearId] = fp32Max; - } - } - } - - barrier(); - - [[unroll]] for (uint pLoad = 0; pLoad < P_LOAD_LOOPS; pLoad++) { - const uint flatOffset = (pLoad * GROUPSIZE + wgLane) / P_REDUCE_VEC4; - const uint rowIdxFlat = flatOffset % GQA_RATIO; - const uint tokenIdxFlat = min(flatOffset / GQA_RATIO, N_TOKS_PER_GROUP - 1); - loadColBase[pLoad] = (pLoad * GROUPSIZE + wgLane) % P_REDUCE_VEC4; - loadRowBase[pLoad] = (tokenIdxFlat * p.qHead + rowIdxFlat); - fp32SoftMaxSum[pLoad] = 0.0f; - fp32GlobalMaxP[pLoad] = slm_pool_f32.slm_pool_o[SLM_OFFSET_GLOBAL_MAX + flatOffset]; - } - - [[unroll]] for (uint maxLoad = 0; maxLoad < MAX_LOAD_LOOPS; maxLoad++) { - const uint flatOffset = (maxLoad * GROUPSIZE + wgLane) / MAX_PER_LOOP; - const uint rowIdxFlat = flatOffset % GQA_RATIO; - const uint tokenIdxFlat = min(flatOffset / GQA_RATIO, N_TOKS_PER_GROUP - 1); - maxColBase[maxLoad] = (maxLoad * GROUPSIZE + wgLane) % MAX_PER_LOOP; - maxRowBase[maxLoad] = (tokenIdxFlat * p.qHead + rowIdxFlat); - } - - [[unroll]] for (uint maxLoad = 0; maxLoad < MAX_LOAD_LOOPS; maxLoad++) { - const uint flatMaxOffset = maxRowBase[maxLoad] * maxDim + maxColBase[maxLoad]; - slm_pool_f32.slm_pool_o[SLM_OFFSET_LOCAL_MAX + maxLoad * GROUPSIZE + wgLane] = max_f32[offsetBaseMax + flatMaxOffset]; - maxColBase[maxLoad] = maxColBase[maxLoad] + MATP_PER_LOOP / MATP_REDUCE; - } - - [[unroll]] for (uint pLoad = 0; pLoad < P_LOAD_LOOPS; pLoad++) { - const uint flatOffset = loadRowBase[pLoad] * pDim / 4 + loadColBase[pLoad]; - pStateTemp[pLoad] = pStateVec4[offsetBaseP + flatOffset]; - } - - [[unroll]] for (uint n = 0; n < ALIGNED_P_M; n++) { - [[unroll]] for (uint i = 0; i < MAT_O_N; i++) { - sums[n][i] = coopmat(0.0f); - } - } - - barrier(); - - [[unroll]] for (uint pLoad = 0; pLoad < P_LOAD_LOOPS; pLoad++) { - const uint maxOffset = (pLoad * GROUPSIZE + wgLane) / SLM_MAX_STRIDE; - if (loadColBase[pLoad] < pDim / 4) { - fp32CompensationP[pLoad] = slm_pool_f32.slm_pool_o[SLM_OFFSET_LOCAL_MAX + maxOffset]; - float pTemp[4] = float[4](pStateTemp[pLoad].x, pStateTemp[pLoad].y, pStateTemp[pLoad].z, pStateTemp[pLoad].w); - float compTemp = exp(fp32CompensationP[pLoad] - fp32GlobalMaxP[pLoad]); - [[unroll]] for (uint kk = 0; kk < 4; kk++) { - pTemp[kk] = pTemp[kk] * compTemp; - fp32SoftMaxSum[pLoad] = fp32SoftMaxSum[pLoad] + pTemp[kk]; - slm_pool_alias_f16.slm_pool_pv[offsetSlmP + pLoad * GROUPSIZE * 4 + kk] = float16_t(pTemp[kk]); - } - } else { - [[unroll]] for (uint kk = 0; kk < 4; kk++) { - slm_pool_alias_f16.slm_pool_pv[offsetSlmP + pLoad * GROUPSIZE * 4 + kk] = float16_t(0.0f); - } } - loadColBase[pLoad] = loadColBase[pLoad] + P_REDUCE_VEC4; - } + if (p.nek1 == 0) { + if (sg == 0) { + [[unroll]] for (uint c = 0; c < Bc / 4; ++c) { + [[unroll]] for (uint r = 0; r < o_scalar_row; ++r) { + if (o_mask[r]) { + data_ov4[o_base + o_offset[r] + c] = vec4(0.0f, 0.0f, 0.0f, 0.0f); + } + } + } + } - const uint loopCount = (p.kvSeqLen + MATP_PER_LOOP - 1) / MATP_PER_LOOP; + return; + } - for (uint loop = 0; loop < loopCount; loop++) { - const uint slmPingPongLoad = (loop & 0x1); - const uint slmPingPongStore = ((loop + 1) & 0x1); + [[unroll]] for (uint idx = 0; idx < global_max_loops; ++idx) { + const uint flat_offset = idx * sg_count + sg; + const uint row_idx = flat_offset % gqa_ratio; + const uint tok_idx = flat_offset / gqa_ratio; + + if (tok_idx < Wr) { + float Maxf = NEG_FLT_MAX_OVER_2; + const uint max_offset = max_base + (tok_idx * p.neq2 + row_idx) * max_dim; + [[unroll]] for (uint max_reduce = 0; max_reduce < (max_dim + SubGroupSize - 1) / SubGroupSize; ++max_reduce) { + if (max_reduce * SubGroupSize + lane < max_dim) { + Maxf = max(Maxf, data_max[max_offset + max_reduce * SubGroupSize + lane]); + } + } + Maxf = subgroupMax(Maxf); + if (lane == 0) { + F32Poolsh.F32sh[global_maxsh_offset + idx * sg_count + sg] = Maxf; + } + } else { + if (lane == 0) { + F32Poolsh.F32sh[global_maxsh_offset + idx * sg_count + sg] = POS_FLT_MAX_OVER_2; + } + } + } - if (loop + 1 < loopCount) { - [[unroll]] for (uint pLoad = 0; pLoad < P_LOAD_LOOPS; pLoad++) { - const uint flatOffset = loadRowBase[pLoad] * pDim / 4 + loadColBase[pLoad]; - pStateTemp[pLoad] = pStateVec4[offsetBaseP + flatOffset]; - } + barrier(); - [[unroll]] for (uint maxLoad = 0; maxLoad < MAX_LOAD_LOOPS; maxLoad++) { - const uint flatMaxOffset = maxRowBase[maxLoad] * maxDim + maxColBase[maxLoad]; - slm_pool_f32.slm_pool_o[SLM_OFFSET_LOCAL_MAX + slmPingPongStore * SLM_POOL_SIZE_LOCAL_MAX + maxLoad * GROUPSIZE + wgLane] = max_f32[offsetBaseMax + flatMaxOffset]; - maxColBase[maxLoad] = maxColBase[maxLoad] + MATP_PER_LOOP / MATP_REDUCE; - } + [[unroll]] for (uint idx = 0; idx < p_loops; ++idx) { + const uint flat_offset = (idx * WorkGroupSize + wg_lane) / p_v4; + const uint row_idx = flat_offset % gqa_ratio; + const uint tok_idx = min(flat_offset / gqa_ratio, Wr - 1); + p_col_base[idx] = (idx * WorkGroupSize + wg_lane) % p_v4; + p_row_base[idx] = (tok_idx * p.neq2 + row_idx); + Lf[idx] = 0.0f; + global_max[idx] = F32Poolsh.F32sh[global_maxsh_offset + flat_offset]; } - barrier(); + [[unroll]] for (uint idx = 0; idx < max_loops; ++idx) { + const uint flat_offset = (idx * WorkGroupSize + wg_lane) / max_per_loop; + const uint row_idx = flat_offset % gqa_ratio; + const uint tok_idx = min(flat_offset / gqa_ratio, Wr - 1); + max_col_base[idx] = (idx * WorkGroupSize + wg_lane) % max_per_loop; + max_row_base[idx] = (tok_idx * p.neq2 + row_idx); + } - { - const uint coopMatOffsetP = SLM_OFFSET_P + slmPingPongLoad * SLM_POOL_SIZE_P + splitIdx * TK; - coopmat matV[MAT_O_N]; - [[unroll]] for (uint cc = 0; cc < MAT_O_N; cc++) { - coopMatLoad( - matV[cc], - vState, - offsetV + TM * cc, - kvDim, - gl_CooperativeMatrixLayoutColumnMajor); - } - [[unroll]] for (uint mo = 0; mo < ALIGNED_P_M; mo++) { - coopmat matP; - coopMatLoad( - matP, - slm_pool_alias_f16.slm_pool_pv, - coopMatOffsetP + mo * TN * MATP_PER_LOOP, - MATP_PER_LOOP, - gl_CooperativeMatrixLayoutColumnMajor); - - [[unroll]] for (uint no = 0; no < MAT_O_N; no++) { - sums[mo][no] = coopMatMulAdd(matV[no], matP, sums[mo][no]); + [[unroll]] for (uint idx = 0; idx < max_loops; ++idx) { + const uint flat_offset = max_row_base[idx] * max_dim + max_col_base[idx]; + if (seq_boundary_check) { + F32Poolsh.F32sh[maxsh_offset + idx * WorkGroupSize + wg_lane] = + (max_col_base[idx] < max_dim) ? data_max[max_base + flat_offset] : NEG_FLT_MAX_OVER_2; + } else { + F32Poolsh.F32sh[maxsh_offset + idx * WorkGroupSize + wg_lane] = data_max[max_base + flat_offset]; } - } + max_col_base[idx] = max_col_base[idx] + p_per_loop / p_reduce; } - offsetV += MATP_PER_LOOP * kvDim; - if (loop * MATP_PER_LOOP + splitIdx * TK >= p.kvSeqLen) { - offsetV = 0; - } - if (loop + 1 < loopCount) { - [[unroll]] for (uint pLoad = 0; pLoad < P_LOAD_LOOPS; pLoad++) { - const uint maxOffset = (pLoad * GROUPSIZE + wgLane) / SLM_MAX_STRIDE; - if (loadColBase[pLoad] < pDim / 4) { - fp32CompensationP[pLoad] = slm_pool_f32.slm_pool_o[SLM_OFFSET_LOCAL_MAX + slmPingPongStore * SLM_POOL_SIZE_LOCAL_MAX + maxOffset]; - float pTemp[4] = float[4](pStateTemp[pLoad].x, pStateTemp[pLoad].y, pStateTemp[pLoad].z, pStateTemp[pLoad].w); - float compTemp = exp(fp32CompensationP[pLoad] - fp32GlobalMaxP[pLoad]); - [[unroll]] for (uint kk = 0; kk < 4; kk++) { - pTemp[kk] = pTemp[kk] * compTemp; - fp32SoftMaxSum[pLoad] = fp32SoftMaxSum[pLoad] + pTemp[kk]; - slm_pool_alias_f16.slm_pool_pv[offsetSlmP + slmPingPongStore * SLM_POOL_SIZE_P + pLoad * GROUPSIZE * 4 + kk] = float16_t(pTemp[kk]); - } + [[unroll]] for (uint idx = 0; idx < p_loops; ++idx) { + const uint flat_offset = p_row_base[idx] * p_dim / 4 + p_col_base[idx]; + if (seq_boundary_check) { + pv4_temp[idx] = (p_col_base[idx] < p_dim / 4) ? data_pv4[p_base + flat_offset] : f16vec4(0.0f, 0.0f, 0.0f, 0.0f); } else { - [[unroll]] for (uint kk = 0; kk < 4; kk++) { - slm_pool_alias_f16.slm_pool_pv[offsetSlmP + slmPingPongStore * SLM_POOL_SIZE_P + pLoad * GROUPSIZE * 4 + kk] = float16_t(0.0f); - } + pv4_temp[idx] = data_pv4[p_base + flat_offset]; } - loadColBase[pLoad] = loadColBase[pLoad] + P_REDUCE_VEC4; - } } - } - - barrier(); - - [[unroll]] for (uint pLoad = 0; pLoad < P_LOAD_LOOPS; pLoad++) { - fp32SoftMaxSum[pLoad] = subgroupAdd(fp32SoftMaxSum[pLoad]); - } - - [[unroll]] for (uint mo = 0; mo < ALIGNED_P_M; mo++) { - [[unroll]] for (uint no = 0; no < MAT_O_N; no++) { - coopMatStore( - sums[mo][no], - slm_pool_f32.slm_pool_o, - SLM_OFFSET_O + mo * TN * WARP_V_DIM + TM * no + localLinearId * ALIGNED_P_M * TN * WARP_V_DIM, - WARP_V_DIM, - gl_CooperativeMatrixLayoutColumnMajor); + + [[unroll]] for (uint r = 0; r < omat_row; ++r) { + [[unroll]] for (uint c = 0; c < omat_col; ++c) { + OMat[r][c] = coopmat(0.0f); + } } - } - [[unroll]] for (uint pLoad = 0; pLoad < P_LOAD_LOOPS; pLoad++) { - slm_pool_f32.slm_pool_o[SLM_OFFSET_SOFTMAX_SUM + pLoad * SUBGROUP_COUNT + localLinearId] = fp32SoftMaxSum[pLoad]; - } + barrier(); - barrier(); + [[unroll]] for (uint idx = 0; idx < p_loops; ++idx) { + const uint max_offset = (idx * WorkGroupSize + wg_lane) / maxsh_stride; + eMf[idx] = F32Poolsh.F32sh[maxsh_offset + max_offset]; + float p_temp[4] = float[4](pv4_temp[idx].x, pv4_temp[idx].y, pv4_temp[idx].z, pv4_temp[idx].w); + float eMf_temp = exp(eMf[idx] - global_max[idx]); + [[unroll]] for (uint i = 0; i < 4; ++i) { + p_temp[i] = p_temp[i] * eMf_temp; + Lf[idx] = Lf[idx] + p_temp[i]; + F16Poolsh.F16sh[psh_offset + idx * WorkGroupSize * 4 + i] = float16_t(p_temp[i]); + } + p_col_base[idx] = p_col_base[idx] + p_v4; + } - if (localLinearId == 1) { - const uint sumBase = SLM_OFFSET_SOFTMAX_SUM + lane * SUB_GROUPS_PER_LINE; - float sumTemp[ALIGNED_P_M][SUB_GROUPS_PER_LINE]; - [[unroll]] for (uint pm = 0; pm < ALIGNED_P_M; pm++) { - [[unroll]] for (uint reduce = 0; reduce < SUB_GROUPS_PER_LINE; reduce++) { - sumTemp[pm][reduce] = slm_pool_f32.slm_pool_o[sumBase + pm * WARPSIZE * SUB_GROUPS_PER_LINE + reduce]; - } + const uint loop_count = seq_boundary_check ? ((p.nek1 + p_per_loop - 1) / p_per_loop - 1) : (p.nek1 / p_per_loop); + uint sh_pingpong_load = 0; + uint sh_pingpong_store = 0; + + for (uint loop = 0; loop < loop_count; ++loop) { + sh_pingpong_load = loop & 0x1; + sh_pingpong_store = (loop + 1) & 0x1; + + if (seq_boundary_check || loop + 1 < loop_count) { + [[unroll]] for (uint idx = 0; idx < p_loops; ++idx) { + const uint flat_offset = p_row_base[idx] * p_dim / 4 + p_col_base[idx]; + if (seq_boundary_check) { + pv4_temp[idx] = (p_col_base[idx] < p_dim / 4) ? data_pv4[p_base + flat_offset] : f16vec4(0.0f, 0.0f, 0.0f, 0.0f); + } else { + pv4_temp[idx] = data_pv4[p_base + flat_offset]; + } + } + + [[unroll]] for (uint idx = 0; idx < max_loops; ++idx) { + const uint flat_offset = max_row_base[idx] * max_dim + max_col_base[idx]; + if (seq_boundary_check) { + F32Poolsh.F32sh[maxsh_offset + sh_pingpong_store * SLM_POOL_SIZE_MAX + idx * WorkGroupSize + wg_lane] = + (max_col_base[idx] < max_dim) ? data_max[max_base + flat_offset] : NEG_FLT_MAX_OVER_2; + } else { + F32Poolsh.F32sh[maxsh_offset + sh_pingpong_store * SLM_POOL_SIZE_MAX + idx * WorkGroupSize + wg_lane] = data_max[max_base + flat_offset]; + } + max_col_base[idx] = max_col_base[idx] + p_per_loop / p_reduce; + } + } + + barrier(); + + { + const uint coord_p = psh_base + sh_pingpong_load * psh_size + sg * TK; + coopmat VMat[omat_col]; + [[unroll]] for (uint c = 0; c < omat_col; ++c) { + coopMatLoad(VMat[c], data_v, v_offset + TM * c, v_dim, gl_CooperativeMatrixLayoutColumnMajor); + } + [[unroll]] for (uint r = 0; r < omat_row; ++r) { + coopmat PMat; + coopMatLoad(PMat, F16Poolsh.F16sh, coord_p + r * TN * p_per_loop, p_per_loop, gl_CooperativeMatrixLayoutColumnMajor); + + [[unroll]] for (uint c = 0; c < omat_col; ++c) { + OMat[r][c] = coopMatMulAdd(VMat[c], PMat, OMat[r][c]); + } + } + } + + v_offset += p_per_loop * v_dim; + + if (seq_boundary_check || loop + 1 < loop_count) { + [[unroll]] for (uint idx = 0; idx < p_loops; ++idx) { + const uint max_offset = (idx * WorkGroupSize + wg_lane) / maxsh_stride; + eMf[idx] = F32Poolsh.F32sh[maxsh_offset + sh_pingpong_store * SLM_POOL_SIZE_MAX + max_offset]; + float p_temp[4] = float[4](pv4_temp[idx].x, pv4_temp[idx].y, pv4_temp[idx].z, pv4_temp[idx].w); + float eMf_temp = exp(eMf[idx] - global_max[idx]); + [[unroll]] for (uint i = 0; i < 4; ++i) { + p_temp[i] = p_temp[i] * eMf_temp; + Lf[idx] = Lf[idx] + p_temp[i]; + F16Poolsh.F16sh[psh_offset + sh_pingpong_store * psh_size + idx * WorkGroupSize * 4 + i] = float16_t(p_temp[i]); + } + p_col_base[idx] = p_col_base[idx] + p_v4; + } + } } - [[unroll]] for (uint pm = 0; pm < ALIGNED_P_M; pm++) { - [[unroll]] for (uint reduce = 1; reduce < SUB_GROUPS_PER_LINE; reduce++) { - sumTemp[pm][0] = sumTemp[pm][0] + sumTemp[pm][reduce]; - } + barrier(); + + // last loop for oob handling + if (seq_boundary_check) { + const uint coord_p = psh_base + sh_pingpong_store * psh_size + sg * TK; + coopmat VMat[omat_col]; + coopmat PMat[omat_row]; + + [[unroll]] for (uint r = 0; r < omat_row; ++r) { + coopMatLoad(PMat[r], F16Poolsh.F16sh, coord_p + r * TN * p_per_loop, p_per_loop, gl_CooperativeMatrixLayoutColumnMajor); + } + + barrier(); + const uint v_global_coord_base = sg * TK + loop_count * p_per_loop; + const uint v_global_offset = (v_base + loop_count * p_per_loop * p.nbv1) / 4; + const uint vv4sh_base = psh_base / 4 + sg * TM * TK / 4; + [[unroll]] for (uint c = 0; c < omat_col; ++c) { + [[unroll]] for (uint idx = 0; idx < TM * TK / SubGroupSize / 4; ++idx) { + const uint vv4_idx = idx * SubGroupSize + lane; + const uint row_idx = vv4_idx / (TM / 4); + const uint col_idx = vv4_idx % (TM / 4); + const uint vv4_offset = v_global_offset + row_idx * p.nbv1 / 4 + c * TM / 4 + col_idx; + + f16vec4 vv4_temp = (v_global_coord_base + row_idx < p.nek1) ? data_vv4[vv4_offset] : f16vec4(0.0f, 0.0f, 0.0f, 0.0f); + F16V4Poolsh.F16V4sh[vv4sh_base + vv4_idx] = vv4_temp; + } + + subgroupBarrier(); + coopMatLoad(VMat[c], F16V4Poolsh.F16V4sh, vv4sh_base, TM / 4, gl_CooperativeMatrixLayoutColumnMajor); + subgroupBarrier(); + } + + [[unroll]] for (uint r = 0; r < omat_row; ++r) { + [[unroll]] for (uint c = 0; c < omat_col; ++c) { + OMat[r][c] = coopMatMulAdd(VMat[c], PMat[r], OMat[r][c]); + } + } } - if ((0x1 & p.flag) != 0) { - [[unroll]] for (uint pm = 0; pm < ALIGNED_P_M; pm++) { - float fp32GlobalMax = slm_pool_f32.slm_pool_o[SLM_OFFSET_GLOBAL_MAX + pm * WARPSIZE + lane]; - float sinkCompensation = fp32GlobalMax - fp32SinkCoeff[pm]; - sinkCompensation = exp(sinkCompensation); - float softmaxSumTemp = sumTemp[pm][0] * sinkCompensation; - sumTemp[pm][0] = sumTemp[pm][0] + 1.0f / sinkCompensation; - sumTemp[pm][0] = 1.0f / sumTemp[pm][0]; - sinkCompensation = sinkCompensation / (1.0f + softmaxSumTemp); - sumTemp[pm][0] = fp32GlobalMax < fp32SinkCoeff[pm] ? sinkCompensation : sumTemp[pm][0]; - slm_pool_f32.slm_pool_o[SLM_OFFSET_SOFTMAX_SUM + pm * WARPSIZE + lane] = sumTemp[pm][0]; - } - } else { - [[unroll]] for (uint pm = 0; pm < ALIGNED_P_M; pm++) { - slm_pool_f32.slm_pool_o[SLM_OFFSET_SOFTMAX_SUM + pm * WARPSIZE + lane] = 1.0f / sumTemp[pm][0]; - } + barrier(); + + [[unroll]] for (uint idx = 0; idx < p_loops; ++idx) { + Lf[idx] = subgroupAdd(Lf[idx]); } - } - - [[unroll]] for (uint reduce = 2; reduce < SPLIT_P_GROUPS; reduce = reduce << 1 ) { - const uint stride = (reduce >> 1) * ALIGNED_P_M * TN * MAT_O_N * TM; - if ((localLinearId % reduce) == 0) { - const uint reduceBase = localLinearId * ALIGNED_P_M * TN * MAT_O_N * TM + SLM_OFFSET_O; - float sumTemp0[4]; - float sumTemp1[4]; - const uint reduceVec4Count = ALIGNED_P_M * TN * MAT_O_N * TM / 4 / WARPSIZE; - [[unroll]] for (uint totalLoads = 0; totalLoads < reduceVec4Count; totalLoads++) { - [[unroll]] for (uint kk = 0; kk < 4; kk++) { - sumTemp0[kk] = slm_pool_f32.slm_pool_o[reduceBase + totalLoads * 4 * WARPSIZE + 4 * lane + kk]; - sumTemp1[kk] = slm_pool_f32.slm_pool_o[reduceBase + stride + totalLoads * 4 * WARPSIZE + 4 * lane + kk]; - } - [[unroll]] for (uint kk = 0; kk < 4; kk++) { - sumTemp0[kk] = sumTemp0[kk] + sumTemp1[kk]; + [[unroll]] for (uint r = 0; r < omat_row; ++r) { + [[unroll]] for (uint c = 0; c < omat_col; ++c) { + const uint coord = osh_offset + r * TN * Bc + TM * c + sg * omat_row * TN * Bc; + coopMatStore(OMat[r][c], F32Poolsh.F32sh, coord, Bc, gl_CooperativeMatrixLayoutColumnMajor); } + } - [[unroll]] for (uint kk = 0; kk < 4; kk++) { - slm_pool_f32.slm_pool_o[reduceBase + totalLoads * 4 * WARPSIZE + 4 * lane + kk] = sumTemp0[kk]; + [[unroll]] for (uint idx = 0; idx < p_loops; ++idx) { + if (lane == 0) { + F32Poolsh.F32sh[lfsh_offset + idx * sg_count + sg] = Lf[idx]; } - } } + barrier(); - } - if (localLinearId == 0) { - const uint slmBase0 = SLM_OFFSET_O + lane * WARP_V_DIM; - const uint slmBase1 = slmBase0 + SPLIT_P_GROUPS / 2 * ALIGNED_P_M * TN * MAT_O_N * TM; + if (sg == 1) { + const uint lf_base = lfsh_offset + lane * sg_per_line; + float Lfrcp_temp[o_scalar_row][sg_per_line]; + [[unroll]] for (uint r = 0; r < o_scalar_row; ++r) { + [[unroll]] for (uint reduce = 0; reduce < sg_per_line; ++reduce) { + Lfrcp_temp[r][reduce] = F32Poolsh.F32sh[lf_base + r * SubGroupSize * sg_per_line + reduce]; + } + } + + [[unroll]] for (uint pm = 0; pm < o_scalar_row; ++pm) { + [[unroll]] for (uint reduce = 1; reduce < sg_per_line; ++reduce) { + Lfrcp_temp[pm][0] = Lfrcp_temp[pm][0] + Lfrcp_temp[pm][reduce]; + } + } - const uint offsetOutBase = (d * p.batchStrideO + vWarpIdx * WARP_V_DIM + v * GQA_RATIO * HEAD_DIM + outTokIdx * oDim * N_TOKS_PER_GROUP) / 4; - float fp32SoftMaxMul[ALIGNED_P_M]; - float fp32Output[ALIGNED_P_M][4]; - [[unroll]] for (uint pm = 0; pm < ALIGNED_P_M; pm++) { - fp32SoftMaxMul[pm] = slm_pool_f32.slm_pool_o[SLM_OFFSET_SOFTMAX_SUM + pm * WARPSIZE + lane]; + subgroupBarrier(); + + if ((p.flag & SINK_ENABLE_BIT) != 0) { + [[unroll]] for (uint r = 0; r < o_scalar_row; ++r) { + float Mf = F32Poolsh.F32sh[global_maxsh_offset + r * SubGroupSize + lane]; + float sink_emf = Mf - sink[r]; + sink_emf = exp(sink_emf); + float Lf_sink = Lfrcp_temp[r][0] * sink_emf; + Lfrcp_temp[r][0] = Lfrcp_temp[r][0] + 1.0f / sink_emf; + Lfrcp_temp[r][0] = 1.0f / Lfrcp_temp[r][0]; + sink_emf = sink_emf / (1.0f + Lf_sink); + Lfrcp_temp[r][0] = (Mf < sink[r]) ? sink_emf : Lfrcp_temp[r][0]; + F32Poolsh.F32sh[lfsh_offset + r * SubGroupSize + lane] = Lfrcp_temp[r][0]; + } + } else { + [[unroll]] for (uint r = 0; r < o_scalar_row; ++r) { + F32Poolsh.F32sh[lfsh_offset + r * SubGroupSize + lane] = (Lfrcp_temp[r][0] == 0.0f) ? 0.0f : (1.0f / Lfrcp_temp[r][0]); + } + } } - [[unroll]] for (uint vg = 0; vg < WARP_V_DIM / 4; vg++) { - [[unroll]] for (uint pm = 0; pm < ALIGNED_P_M; pm++) { - [[unroll]] for (uint vc = 0; vc < 4; vc++) { - fp32Output[pm][vc] = slm_pool_f32.slm_pool_o[slmBase0 + pm * WARPSIZE * WARP_V_DIM + vg * 4 + vc] * fp32SoftMaxMul[pm]; - fp32Output[pm][vc] = fp32Output[pm][vc] + slm_pool_f32.slm_pool_o[slmBase1 + pm * WARPSIZE * WARP_V_DIM + vg * 4 + vc] * fp32SoftMaxMul[pm]; + [[unroll]] for (uint reduce = 2; reduce < split_p_sg; reduce = reduce << 1) { + const uint stride = (reduce >> 1) * omat_row * TN * omat_col * TM; + if ((sg % reduce) == 0) { + const uint reduce_base = sg * omat_row * TN * omat_col * TM + osh_offset; + float sum_temp0[4]; + float sum_temp1[4]; + const uint reduce_count = omat_row * TN * omat_col * TM / 4 / SubGroupSize; + [[unroll]] for (uint idx = 0; idx < reduce_count; ++idx) { + [[unroll]] for (uint i = 0; i < 4; ++i) { + sum_temp0[i] = F32Poolsh.F32sh[reduce_base + idx * 4 * SubGroupSize + 4 * lane + i]; + sum_temp1[i] = F32Poolsh.F32sh[reduce_base + stride + idx * 4 * SubGroupSize + 4 * lane + i]; + } + + [[unroll]] for (uint i = 0; i < 4; ++i) { + sum_temp0[i] = sum_temp0[i] + sum_temp1[i]; + } + + [[unroll]] for (uint i = 0; i < 4; ++i) { + F32Poolsh.F32sh[reduce_base + idx * 4 * SubGroupSize + 4 * lane + i] = sum_temp0[i]; + } + } + } + barrier(); + } + + if (sg == 0) { + const uint sh_base0 = osh_offset + lane * Bc; + const uint sh_base1 = sh_base0 + split_p_sg / 2 * omat_row * TN * omat_col * TM; + + float Lfrcp[o_scalar_row]; + float Of[o_scalar_row][4]; + [[unroll]] for (uint r = 0; r < o_scalar_row; ++r) { + Lfrcp[r] = F32Poolsh.F32sh[lfsh_offset + r * SubGroupSize + lane]; } - } - [[unroll]] for (uint pm = 0; pm < ALIGNED_P_M; pm++) { - if (outputMask[pm] == true) { - out_f32_vec4[offsetOutBase + outOffsets[pm] + vg] = vec4(fp32Output[pm][0], fp32Output[pm][1], fp32Output[pm][2], fp32Output[pm][3]); + [[unroll]] for (uint c = 0; c < Bc / 4; ++c) { + [[unroll]] for (uint r = 0; r < o_scalar_row; ++r) { + [[unroll]] for (uint vc = 0; vc < 4; ++vc) { + Of[r][vc] = F32Poolsh.F32sh[sh_base0 + r * SubGroupSize * Bc + c * 4 + vc] * Lfrcp[r]; + Of[r][vc] = Of[r][vc] + F32Poolsh.F32sh[sh_base1 + r * SubGroupSize * Bc + c * 4 + vc] * Lfrcp[r]; + } + } + + [[unroll]] for (uint r = 0; r < o_scalar_row; ++r) { + if (o_mask[r]) { + data_ov4[o_base + o_offset[r] + c] = vec4(Of[r][0], Of[r][1], Of[r][2], Of[r][3]); + } + } } - } } - } } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_prefill.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_prefill.comp new file mode 100644 index 000000000000..407654ca5c40 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_prefill.comp @@ -0,0 +1,817 @@ +#version 450 + +#extension GL_EXT_control_flow_attributes : enable +#extension GL_EXT_shader_16bit_storage : require +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#extension GL_KHR_cooperative_matrix : enable +#extension GL_KHR_memory_scope_semantics : enable +#extension GL_KHR_shader_subgroup_basic : enable +#extension GL_EXT_shared_memory_block : enable +#extension GL_KHR_shader_subgroup_shuffle : enable +#extension GL_KHR_shader_subgroup_shuffle_relative : enable + +layout (local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in; + +layout (binding = 0) readonly buffer Q {float data_q[];}; +layout (binding = 0) readonly buffer QM2x4 {mat2x4 data_qm2x4[];}; +layout (binding = 1) readonly buffer K {float16_t data_k[];}; +layout (binding = 1) readonly buffer KV4 {f16vec4 data_kv4[];}; +layout (binding = 1) readonly buffer KM2x4 {f16mat2x4 data_km2x4[];}; +layout (binding = 2) readonly buffer V {float16_t data_v[];}; +layout (binding = 2) readonly buffer VV4 {f16vec4 data_vv4[];}; +layout (binding = 3) readonly buffer M {float16_t data_m[];}; +layout (binding = 3) readonly buffer MV2 {f16vec2 data_mv2[];}; +layout (binding = 3) readonly buffer MV4 {f16vec4 data_mv4[];}; +layout (binding = 4) readonly buffer S {float data_s[];}; +layout (binding = 5) buffer OV4 {vec4 data_ov4[];}; + +layout (push_constant) uniform parameter +{ + uint neq1; + uint neq2; + uint neq3; + uint nek1; + uint nek2; + uint nek3; + uint nev2; + uint nev3; + uint nem1; + uint nem2; + uint nem3; + uint nbq1; + uint nbq2; + uint nbk1; + uint nbk2; + uint nbv1; + uint nbv2; + uint nbq3; + uint nbk3; + uint nbv3; + uint nb3; + uint flag; + float scale; +} p; + +layout (constant_id = 0) const uint WorkGroupSize = 256; +layout (constant_id = 1) const uint Wr = 128; +layout (constant_id = 2) const uint Bc = 64; +layout (constant_id = 3) const uint HSK = 128; +layout (constant_id = 4) const uint HSV = 128; +layout (constant_id = 5) const uint qk_ratio = 8; +layout (constant_id = 6) const uint step_p = 32; +layout (constant_id = 7) const uint TM = 8; +layout (constant_id = 8) const uint TN = 16; +layout (constant_id = 9) const uint q_reg = 96; +layout (constant_id = 10) const uint shmem_size = 64; +layout (constant_id = 11) const uint acc_count = 1; +layout (constant_id = 12) const uint Flags = 0; +layout (constant_id = 13) const uint SubGroupSize = 16; +layout (constant_id = 14) const uint gqa_fold = 1; + +#define UNALIGNED_SEQ_LEN_BIT (1 << 0) +#define UNALIGNED_Q_STRIDE_BIT (1 << 1) +#define PARTIAL_ROW_MASK_BIT (1 << 2) +#define INTEL_GPU_BIT (1 << 3) +#define SINK_ENABLE_BIT (1 << 16) + +const bool aligned_q_stride = (Flags & UNALIGNED_Q_STRIDE_BIT) == 0; +const bool seq_boundary_check = (Flags & UNALIGNED_SEQ_LEN_BIT) != 0; +const bool partial_row_mask = (Flags & PARTIAL_ROW_MASK_BIT) != 0; +const uint TK = 16; +const uint sg_count = WorkGroupSize / SubGroupSize; +const uint matp_count = step_p / TM; +const uint mato_count = Bc / TM; +const uint qk_sg = Wr / TN; +const uint folded_row_wg = Wr / gqa_fold; +const uint loadv_sg = (qk_sg == sg_count) ? sg_count : (sg_count - qk_sg); +const uint k_col = (HSK % 64 == 0 && HSK <= 512 && WorkGroupSize <= 256) ? 8 : 4; +const uint k_loop_col = WorkGroupSize * k_col; +const uint k_loops = (step_p * HSK + k_loop_col - 1) / k_loop_col; +const bool k_boundary_check = (step_p * HSK) % k_loop_col != 0; +const uint v_vert_groups = step_p / TK; +const uint v_hori_groups = loadv_sg / v_vert_groups; +const uint v_loops = (HSV / TM + v_hori_groups - 1) / v_hori_groups; +const bool v_boundary_check = HSV % (v_hori_groups * TM) != 0; +const uint m_vert_groups = folded_row_wg / SubGroupSize; +const uint m_hori_groups = sg_count / m_vert_groups; +const uint m_loops = (step_p + m_hori_groups - 1) / m_hori_groups; + +const uint matq_count = q_reg / TK; +const uint q_shmem = HSK - q_reg; +const uint matq_shmem_count = q_shmem / TK; +const uint max_q_reg_staging = shmem_size / 2 / Wr; + +const bool intel_gpu = (Flags & INTEL_GPU_BIT) != 0; +const bool k_in_shmem = HSK <= 576; +const bool v_in_shmem = HSK <= 128 && HSV <= 128; +const bool mask_in_shmem = folded_row_wg <= 64; + +const uint oobsh_staging_size = sg_count * TM * TK; +const uint qsh_size = Wr * q_shmem; +const uint ksh_size = k_in_shmem ? (k_loops * k_loop_col) : oobsh_staging_size; +const uint msh_size = mask_in_shmem ? (folded_row_wg * step_p) : 0; +const uint psh_size = Wr * step_p; +const uint vsh_size = v_in_shmem ? (step_p * HSV) : 0; +const uint emfsh_size = (qk_sg == sg_count) ? 0 : Wr; +const uint pvsh_size = intel_gpu ? 0 : (acc_count * TM * TN * sg_count); + +const uint qsh_base = 0; +const uint emfsh_base = (qsh_base + qsh_size) / 2; +const uint vsh_base = (emfsh_base + emfsh_size) * 2; +const uint psh_base = (vsh_base + vsh_size) / 2; +const uint ksh_base = (psh_base + psh_size) * 2; +const uint pvsh_base = ksh_base / 2; +const uint msh_base = ksh_base + ksh_size; +const uint vsh_oob_staging_base = ksh_base / 4; + +const uint sg_mat_reduce = SubGroupSize / TN; +const uint softmax_loops = step_p / sg_mat_reduce; +const uint acc_loops = acc_count * TM / sg_mat_reduce; +const uint CM1_ELEMS = (TM * TN) / SubGroupSize; +const uint tk_sg_reduce = (TK + SubGroupSize - 1) / SubGroupSize; +const uint o_sg_cols = (sg_count + qk_sg - 1) / qk_sg; +const bool v_row_overshoot_check = o_sg_cols * Bc > HSV; + +shared sh_block { + float F32sh[shmem_size / 4]; +} F32Poolsh; + +shared shf16_alias { + float16_t F16sh[shmem_size / 2]; +} F16Poolsh; + +shared shf16v2_alias { + f16vec2 F16V2sh[shmem_size / 4]; +} F16V2Poolsh; + +shared shf16v4_alias { + f16vec4 F16V4sh[shmem_size / 8]; +} F16V4Poolsh; + +shared shf16m2x4_alias { + f16mat2x4 M2x4sh[shmem_size / 16]; +} F16M2x4Poolsh; + +void main() { + const uint lane = gl_SubgroupInvocationID; + const uint lane_c = lane % TN; + const uint lane_r = lane / TN; + const uint pv_ratio = p.neq2 / p.nev2; + const uint head_q_idx = gl_WorkGroupID.x; + const uint head_k_idx = head_q_idx * gqa_fold / qk_ratio; + const uint head_v_idx = head_q_idx * gqa_fold / pv_ratio; + const uint batch_k_ratio = p.neq3 / p.nek3; + const uint batch_v_ratio = p.neq3 / p.nev3; + const uint head_mask_idx = head_q_idx % p.nem2; + const uint out_r = gl_WorkGroupID.y; + const uint batch_idx = gl_WorkGroupID.z; + const uint batch_k_idx = batch_idx / batch_k_ratio; + const uint batch_v_idx = batch_idx / batch_v_ratio; + const uint batch_mask_idx = batch_idx % p.nem3; + const uint sg = gl_SubgroupID; + const uint batch_mask_stride = p.nek1 * p.nem1 * p.nem2; + uint sg_v_r = sg / v_vert_groups; + const uint sg_v_c = sg % v_vert_groups; + if (qk_sg < sg_count && sg >= qk_sg) { + sg_v_r -= qk_sg / v_vert_groups; + } + const uint sg_m_c = sg % m_hori_groups; + const uint sg_m_r = sg / m_hori_groups; + const uint sg_o_c = sg / qk_sg; + const uint sg_o_r = sg % qk_sg; + const uint sg_o_r_h = sg_o_r % gqa_fold; + const uint sg_o_r_row = sg_o_r / gqa_fold; + const uint o_dim = p.neq2 * HSV; + uint q_offset = out_r * folded_row_wg + sg_o_r_row * TN + lane_c; + q_offset = min(q_offset, p.neq1 - 1); + if (aligned_q_stride) { + q_offset = (q_offset * p.nbq1 + batch_idx * p.nbq3 + (head_q_idx * gqa_fold + sg_o_r_h) * p.nbq2) / 8 + lane_r; + } else { + q_offset = (q_offset * p.nbq1 + batch_idx * p.nbq3 + (head_q_idx * gqa_fold + sg_o_r_h) * p.nbq2) + lane_r; + } + uint k_base; + if (k_in_shmem) { + k_base = (batch_k_idx * p.nbk3 + head_k_idx * p.nbk2) / k_col; + } else { + k_base = batch_k_idx * p.nbk3 + head_k_idx * p.nbk2; + } + uint k_offset[k_loops]; + const uint v_base = batch_v_idx * p.nbv3 + head_v_idx * p.nbv2; + uint v_offset; + if (v_in_shmem) { + v_offset = v_base + sg_v_r * TM + sg_v_c * p.nbv1 * TK; + } else { + v_offset = v_base + sg_o_c * Bc; + } + uint m_offset; + bool mask_in_boundary; + if (mask_in_shmem) { + m_offset = out_r * folded_row_wg + sg_m_r * SubGroupSize + lane; + mask_in_boundary = m_offset < p.nem1; + m_offset = min(m_offset, p.nem1 - 1); + m_offset = m_offset * p.nek1 + batch_mask_idx * batch_mask_stride + head_mask_idx * p.nek1 * p.nem1; + if (seq_boundary_check) { + m_offset += sg_m_c; + } else if (m_loops % 4 == 0) { + m_offset = m_offset / 4 + sg_m_c; + } else if (m_loops % 2 == 0) { + m_offset = m_offset / 2 + sg_m_c; + } else { + m_offset += sg_m_c; + } + } else { + m_offset = out_r * folded_row_wg + sg_o_r_row * TN + lane_c; + mask_in_boundary = m_offset < p.nem1; + m_offset = min(m_offset, p.nem1 - 1); + m_offset = m_offset * p.nek1 + batch_mask_idx * batch_mask_stride + lane_r * softmax_loops + head_mask_idx * p.nek1 * p.nem1; + if (!seq_boundary_check) { + m_offset /= 4; + } + } + const bool mask_row_valid = !partial_row_mask || mask_in_boundary; + const uint o_offset = (batch_idx * p.nb3 + out_r * folded_row_wg * o_dim + (head_q_idx * gqa_fold + sg_o_r_h) * HSV + + sg_o_r_row * TN * o_dim + sg_o_c * Bc + lane_c * o_dim) / 4 + lane_r; + const uint vsh_offset = sg_v_c * TK * HSV + sg_v_r * TM * TK + vsh_base; + const uint msh_store_offset = (sg_m_r * SubGroupSize + lane) * step_p + msh_base; + const uint msh_load_offset = sg_o_r_row * TN * step_p + lane_c * step_p + lane_r * softmax_loops + msh_base; + const uint psh_load_offset = psh_base + sg * TN * step_p + lane_c * step_p + lane_r * softmax_loops; + const uint psh_store_offset = (psh_base + sg * TN * step_p + lane_c * step_p) * 2 + lane_r * softmax_loops; + const float NEG_FLT_MAX_OVER_2 = uintBitsToFloat(0xFEFFFFFF); + const float16_t NEG_F16_MAX_OVER_2 = float16_t(NEG_FLT_MAX_OVER_2); + const float sink = ((p.flag & SINK_ENABLE_BIT) != 0) ? data_s[head_q_idx * gqa_fold + sg_o_r_h] : 0.0f; + coopmat QMat[matq_count]; + uint ksh_offset[k_loops]; + bool mask_load_k[k_loops]; + + if (q_reg <= max_q_reg_staging) { + if (sg < qk_sg) { + if (aligned_q_stride) { + [[dont_unroll]] for (uint i = 0; i < q_reg / sg_mat_reduce / 8; ++i) { + const uint qsh_offset = (qsh_base + sg * q_reg * TN + lane_c * q_reg) / 8 + i * sg_mat_reduce + lane_r; + mat2x4 q_temp = data_qm2x4[q_offset]; + q_temp *= p.scale; + F16M2x4Poolsh.M2x4sh[qsh_offset] = f16mat2x4(q_temp); + q_offset += sg_mat_reduce; + } + } else { + [[dont_unroll]] for (uint i = 0; i < q_reg / sg_mat_reduce; ++i) { + const uint qsh_offset = (qsh_base + sg * q_reg * TN + lane_c * q_reg) + i * sg_mat_reduce + lane_r; + float q_temp = data_q[q_offset]; + q_temp *= p.scale; + F16Poolsh.F16sh[qsh_offset] = float16_t(q_temp); + q_offset += sg_mat_reduce; + } + } + } + + subgroupBarrier(); + + if (sg < qk_sg) { + const uint coord_q = sg * TN * q_reg + qsh_base; + [[unroll]] for (uint i = 0; i < matq_count; ++i) { + coopMatLoad(QMat[i], F16Poolsh.F16sh, coord_q + TK * i, q_reg, gl_CooperativeMatrixLayoutColumnMajor); + } + } + } else { + if (sg < qk_sg) { + const uint coord_q = sg * TN * TK + qsh_base; + [[unroll]] for (uint iq = 0; iq < q_reg / TK; ++iq) { + if (aligned_q_stride) { + [[dont_unroll]] for (uint idx = 0; idx < TK / sg_mat_reduce / 8; ++idx) { + const uint qsh_offset = (qsh_base + sg * TK * TN + lane_c * TK) / 8 + idx * sg_mat_reduce + lane_r; + mat2x4 q_temp = data_qm2x4[q_offset]; + q_temp *= p.scale; + F16M2x4Poolsh.M2x4sh[qsh_offset] = f16mat2x4(q_temp); + q_offset += sg_mat_reduce; + } + } else { + [[dont_unroll]] for (uint idx = 0; idx < TK / sg_mat_reduce; ++idx) { + const uint qsh_offset = (qsh_base + sg * TK * TN + lane_c * TK) + idx * sg_mat_reduce + lane_r; + float q_temp = data_q[q_offset]; + q_temp *= p.scale; + F16Poolsh.F16sh[qsh_offset] = float16_t(q_temp); + q_offset += sg_mat_reduce; + } + } + + subgroupBarrier(); + coopMatLoad(QMat[iq], F16Poolsh.F16sh, coord_q, TK, gl_CooperativeMatrixLayoutColumnMajor); + subgroupBarrier(); + } + } + } + + float Of[Bc / sg_mat_reduce]; + [[unroll]] for (uint i = 0; i < Bc / sg_mat_reduce; ++i) { + Of[i] = 0; + } + + barrier(); + + if (sg < qk_sg) { + if (aligned_q_stride) { + [[dont_unroll]] for (uint i = 0; i < q_shmem / sg_mat_reduce / 8; ++i) { + const uint qsh_offset = (qsh_base + sg * q_shmem * TN + lane_c * q_shmem) / 8 + i * sg_mat_reduce + lane_r; + mat2x4 q_temp = data_qm2x4[q_offset + i * sg_mat_reduce]; + q_temp *= p.scale; + F16M2x4Poolsh.M2x4sh[qsh_offset] = f16mat2x4(q_temp); + } + } else { + [[dont_unroll]] for (uint i = 0; i < q_shmem / sg_mat_reduce; ++i) { + const uint qsh_offset = (qsh_base + sg * q_shmem * TN + lane_c * q_shmem) + i * sg_mat_reduce + lane_r; + float q_temp = data_q[q_offset + i * sg_mat_reduce]; + q_temp *= p.scale; + F16Poolsh.F16sh[qsh_offset] = float16_t(q_temp); + } + } + } + + if (k_in_shmem) { + [[unroll]] for (uint idx = 0; idx < k_loops; ++idx) { + const uint flat_offset = idx * WorkGroupSize + sg * SubGroupSize + lane; + const uint row_idx = flat_offset / (HSK / k_col); + const uint col_idx = flat_offset % (HSK / k_col); + const uint sh_chunk_c = col_idx % (TK / k_col); + const uint sh_chunk_r = col_idx / (TK / k_col); + k_offset[idx] = k_base + row_idx * p.nbk1 / k_col + col_idx; + ksh_offset[idx] = (ksh_base + row_idx * TK + sh_chunk_r * TK * step_p) / k_col + sh_chunk_c; + if (k_boundary_check) { + mask_load_k[idx] = row_idx < step_p; + } + } + } + + const uint loop_count = (p.nek1 + step_p - 1) / step_p; + const uint k_seq_boundary = ((p.nek1 - 1) * p.nbk1 + batch_k_idx * p.nbk3 + head_k_idx * p.nbk2 + HSK) / k_col - 1; + float Mf = NEG_FLT_MAX_OVER_2; + float eMf = 0.0f; + float Lf = 0; + for (uint loop = 0; loop < loop_count; ++loop) { + if (k_in_shmem) { + if (k_boundary_check) { + [[unroll]] for (uint idx = 0; idx < k_loops; ++idx) { + if (seq_boundary_check && loop + 1 == loop_count) { + k_offset[idx] = min(k_offset[idx], k_seq_boundary); + } + + if (mask_load_k[idx]) { + if (k_col == 4) { + F16V4Poolsh.F16V4sh[ksh_offset[idx]] = data_kv4[k_offset[idx]]; + } else { + F16M2x4Poolsh.M2x4sh[ksh_offset[idx]] = data_km2x4[k_offset[idx]]; + } + } + k_offset[idx] += step_p * p.nbk1 / k_col; + } + } else { + [[unroll]] for (uint idx = 0; idx < k_loops; ++idx) { + if (seq_boundary_check && loop + 1 == loop_count) { + k_offset[idx] = min(k_offset[idx], k_seq_boundary); + } + + if (k_col == 4) { + F16V4Poolsh.F16V4sh[ksh_offset[idx]] = data_kv4[k_offset[idx]]; + } else { + F16M2x4Poolsh.M2x4sh[ksh_offset[idx]] = data_km2x4[k_offset[idx]]; + } + k_offset[idx] += step_p * p.nbk1 / k_col; + } + } + } + + if (mask_in_shmem) { + if (seq_boundary_check) { + [[unroll]] for (uint idx = 0; idx < m_loops; ++idx) { + if (idx * m_hori_groups + loop * step_p + sg_m_c < p.nek1) { + F16Poolsh.F16sh[msh_store_offset + sg_m_c + idx * m_hori_groups] = mask_row_valid ? data_m[m_offset] : float16_t(0.0f); + m_offset += m_hori_groups; + } else { + F16Poolsh.F16sh[msh_store_offset + sg_m_c + idx * m_hori_groups] = NEG_F16_MAX_OVER_2; + } + } + } else if (m_loops % 4 == 0) { + [[unroll]] for (uint idx = 0; idx < m_loops / 4; ++idx) { + F16V4Poolsh.F16V4sh[msh_store_offset / 4 + sg_m_c + idx * m_hori_groups] = + mask_row_valid ? data_mv4[m_offset] : f16vec4(0.0f, 0.0f, 0.0f, 0.0f); + m_offset += m_hori_groups; + } + } else if (m_loops % 2 == 0) { + [[unroll]] for (uint idx = 0; idx < m_loops / 2; ++idx) { + F16V2Poolsh.F16V2sh[msh_store_offset / 2 + sg_m_c + idx * m_hori_groups] = mask_row_valid ? data_mv2[m_offset] : f16vec2(0.0f, 0.0f); + m_offset += m_hori_groups; + } + } else { + [[unroll]] for (uint idx = 0; idx < m_loops; ++idx) { + F16Poolsh.F16sh[msh_store_offset + sg_m_c + idx * m_hori_groups] = mask_row_valid ? data_m[m_offset] : float16_t(0.0f); + m_offset += m_hori_groups; + } + } + } + + barrier(); + if (qk_sg == sg_count || sg < qk_sg) { + { + coopmat PMat[matp_count]; + coopmat KMat[matp_count]; + [[unroll]] for (uint pc = 0; pc < matp_count; ++pc) { + PMat[pc] = coopmat(0.0f); + } + + [[unroll]] for (uint d0 = 0; d0 < matq_count; ++d0) { + if (k_in_shmem) { + [[unroll]] for (uint pc = 0; pc < matp_count; ++pc) { + const uint coord = ksh_base + step_p * TK * d0 + TM * TK * pc; + coopMatLoad(KMat[pc], F16Poolsh.F16sh, coord, TK, gl_CooperativeMatrixLayoutRowMajor); + } + } else { + [[unroll]] for (uint pc = 0; pc < matp_count; ++pc) { + const uint k_base_row = loop * step_p + pc * TM; + if (seq_boundary_check && loop + 1 == loop_count) { + const uint k_base_offset = (k_base + k_base_row * p.nbk1 + TK * d0) / 4; + [[unroll]] for (uint idx = 0; idx < TM * TK / 4 / SubGroupSize; ++idx) { + const uint flat_offset = idx * SubGroupSize + lane; + const uint row_idx = flat_offset / (TK / 4); + const uint col_idx = flat_offset % (TK / 4); + const uint k_temp_offset = k_base_offset + row_idx * p.nbk1 / 4 + col_idx; + const uint ksh_temp_offset = ksh_base / 4 + sg * TM * TK / 4 + idx * SubGroupSize + lane; + f16vec4 kv4_temp = (k_base_row + row_idx) < p.nek1 ? data_kv4[k_temp_offset] : f16vec4(0.0f, 0.0f, 0.0f, 0.0f); + F16V4Poolsh.F16V4sh[ksh_temp_offset] = kv4_temp; + } + + subgroupBarrier(); + coopMatLoad(KMat[pc], F16Poolsh.F16sh, ksh_base + sg * TM * TK, TK, gl_CooperativeMatrixLayoutRowMajor); + subgroupBarrier(); + } else { + const uint coord = k_base + k_base_row * p.nbk1 + TK * d0; + coopMatLoad(KMat[pc], data_k, coord, p.nbk1, gl_CooperativeMatrixLayoutRowMajor); + } + } + } + + [[unroll]] for (uint pc = 0; pc < matp_count; ++pc) { + PMat[pc] = coopMatMulAdd(KMat[pc], QMat[d0], PMat[pc]); + } + } + + [[unroll]] for (uint d0 = 0; d0 < matq_shmem_count; ++d0) { + coopmat QMatsh; + if (k_in_shmem) { + [[unroll]] for (uint pc = 0; pc < matp_count; ++pc) { + const uint coord = ksh_base + matq_count * TK * step_p + step_p * TK * d0 + TM * TK * pc; + coopMatLoad(KMat[pc], F16Poolsh.F16sh, coord, TK, gl_CooperativeMatrixLayoutRowMajor); + } + } else { + [[unroll]] for (uint pc = 0; pc < matp_count; ++pc) { + const uint k_base_row = loop * step_p + pc * TM; + if (seq_boundary_check && loop + 1 == loop_count) { + const uint k_base_offset = (k_base + k_base_row * p.nbk1 + TK * d0 + TK * matq_count) / 4; + [[unroll]] for (uint idx = 0; idx < TM * TK / 4 / SubGroupSize; ++idx) { + const uint flat_offset = idx * SubGroupSize + lane; + const uint row_idx = flat_offset / (TK / 4); + const uint col_idx = flat_offset % (TK / 4); + const uint k_temp_offset = k_base_offset + row_idx * p.nbk1 / 4 + col_idx; + const uint ksh_temp_offset = ksh_base / 4 + sg * TM * TK / 4 + idx * SubGroupSize + lane; + f16vec4 kv4_temp = (k_base_row + row_idx) < p.nek1 ? data_kv4[k_temp_offset] : f16vec4(0.0f, 0.0f, 0.0f, 0.0f); + F16V4Poolsh.F16V4sh[ksh_temp_offset] = kv4_temp; + } + + subgroupBarrier(); + coopMatLoad(KMat[pc], F16Poolsh.F16sh, ksh_base + sg * TM * TK, TK, gl_CooperativeMatrixLayoutRowMajor); + subgroupBarrier(); + } else { + const uint coord = k_base + k_base_row * p.nbk1 + TK * d0 + TK * matq_count; + coopMatLoad(KMat[pc], data_k, coord, p.nbk1, gl_CooperativeMatrixLayoutRowMajor); + } + } + } + + const uint coord = qsh_base + sg * TN * q_shmem + TK * d0; + coopMatLoad(QMatsh, F16Poolsh.F16sh, coord, q_shmem, gl_CooperativeMatrixLayoutColumnMajor); + [[unroll]] for (uint pc = 0; pc < matp_count; ++pc) { + PMat[pc] = coopMatMulAdd(KMat[pc], QMatsh, PMat[pc]); + } + } + + [[unroll]] for (uint pc = 0; pc < matp_count; ++pc) { + coopMatStore(PMat[pc], F32Poolsh.F32sh, psh_base + TM * pc + sg * TN * step_p, step_p, gl_CooperativeMatrixLayoutColumnMajor); + } + } + + subgroupBarrier(); + + float Pf[softmax_loops]; + float Mnewf = Mf; + + [[unroll]] for (uint idx = 0; idx < softmax_loops; ++idx) { + Pf[idx] = F32Poolsh.F32sh[psh_load_offset + idx]; + } + + if (mask_in_shmem) { + [[unroll]] for (uint idx = 0; idx < softmax_loops; ++idx) { + Pf[idx] += float(F16Poolsh.F16sh[msh_load_offset + idx]); + } + } else { + if (seq_boundary_check) { + [[unroll]] for (uint idx = 0; idx < softmax_loops; ++idx) { + if (loop * step_p + idx + lane_r * softmax_loops < p.nek1) { + Pf[idx] += mask_row_valid ? float(data_m[m_offset + idx]) : 0.0f; + } else { + Pf[idx] += NEG_FLT_MAX_OVER_2; + } + } + m_offset += step_p; + } else { + [[unroll]] for (uint idx = 0; idx < softmax_loops / 4; ++idx) { + f16vec4 mv4_temp = mask_row_valid ? data_mv4[m_offset + idx] : f16vec4(0.0f, 0.0f, 0.0f, 0.0f); + float mask_f_temp[4] = float[4](float(mv4_temp.x), float(mv4_temp.y), float(mv4_temp.z), float(mv4_temp.w)); + [[unroll]] for (uint vec_idx = 0; vec_idx < 4; ++vec_idx) { + Pf[4 * idx + vec_idx] += mask_f_temp[vec_idx]; + } + } + m_offset += step_p / 4; + } + } + + if (seq_boundary_check && loop + 1 == loop_count) { + [[unroll]] for (uint idx = 0; idx < softmax_loops; ++idx) { + if (loop * step_p + idx + lane_r * softmax_loops < p.nek1) { + Mnewf = max(Mnewf, Pf[idx]); + } + } + } else { + [[unroll]] for (uint idx = 0; idx < softmax_loops; ++idx) { + Mnewf = max(Mnewf, Pf[idx]); + } + } + + [[unroll]] for (uint idx = 1; idx < sg_mat_reduce; ++idx) { + Mnewf = max(Mnewf, subgroupShuffleDown(Mnewf, idx * TN)); + } + + Mnewf = subgroupShuffle(Mnewf, lane & (TN - 1)); + eMf = exp(Mf - Mnewf); + Lf *= eMf; + + if (seq_boundary_check && loop + 1 == loop_count) { + [[unroll]] for (uint idx = 0; idx < softmax_loops; ++idx) { + if (loop * step_p + idx + lane_r * softmax_loops < p.nek1) { + Pf[idx] = exp(Pf[idx] - Mnewf); + } else { + Pf[idx] = 0.0f; + } + Lf += Pf[idx]; + } + } else { + [[unroll]] for (uint idx = 0; idx < softmax_loops; ++idx) { + Pf[idx] = exp(Pf[idx] - Mnewf); + Lf += Pf[idx]; + } + } + + if (qk_sg != sg_count && lane_r == 0) { + F32Poolsh.F32sh[emfsh_base + sg * TN + lane_c] = eMf; + } + + if (SubGroupSize > TN) { + subgroupBarrier(); + } + + [[unroll]] for (uint idx = 0; idx < softmax_loops; ++idx) { + F16Poolsh.F16sh[psh_store_offset + idx] = float16_t(Pf[idx]); + } + Mf = Mnewf; + } + + if (v_in_shmem && (qk_sg == sg_count || sg >= sg_count - loadv_sg)) { + if (seq_boundary_check && loop + 1 == loop_count) { + const uint v_global_coord_base = loop * step_p + sg_v_c * TK + lane_c; + if (v_boundary_check) { + [[dont_unroll]] for (uint c = 0; c < tk_sg_reduce; ++c) { + const uint v_coord_temp = v_global_coord_base + c * SubGroupSize; + uint v_oob_offset = (v_base + v_coord_temp * p.nbv1 + sg_v_r * TM) / 4 + lane_r; + uint vsh_temp_offset = vsh_offset + c * SubGroupSize + lane_c + lane_r * 4 * TK; + [[dont_unroll]] for (uint r = 0; r < v_loops - 1; ++r) { + [[dont_unroll]] for (uint idx = 0; idx < TM / sg_mat_reduce / 4; ++idx) { + f16vec4 vv4_temp = (v_coord_temp < p.nek1) ? data_vv4[v_oob_offset + idx * sg_mat_reduce] : f16vec4(0.0f, 0.0f, 0.0f, 0.0f); + F16Poolsh.F16sh[vsh_temp_offset + idx * sg_mat_reduce * TK * 4 + 0 * TK] = vv4_temp.x; + F16Poolsh.F16sh[vsh_temp_offset + idx * sg_mat_reduce * TK * 4 + 1 * TK] = vv4_temp.y; + F16Poolsh.F16sh[vsh_temp_offset + idx * sg_mat_reduce * TK * 4 + 2 * TK] = vv4_temp.z; + F16Poolsh.F16sh[vsh_temp_offset + idx * sg_mat_reduce * TK * 4 + 3 * TK] = vv4_temp.w; + } + v_oob_offset += TM * v_hori_groups / 4; + vsh_temp_offset += TM * TK * v_hori_groups; + } + } + + if ((sg_v_r + (v_loops - 1) * v_hori_groups) * TM < HSV) { + [[dont_unroll]] for (uint c = 0; c < tk_sg_reduce; ++c) { + const uint v_coord_temp = v_global_coord_base + c * SubGroupSize; + const uint v_oob_offset = (v_base + v_coord_temp * p.nbv1 + sg_v_r * TM + TM * (v_loops - 1) * v_hori_groups) / 4 + lane_r; + const uint vsh_temp_offset = vsh_offset + TM * (v_loops - 1) * TK * v_hori_groups + c * SubGroupSize + lane_c + lane_r * 4 * TK; + [[dont_unroll]] for (uint idx = 0; idx < TM / sg_mat_reduce / 4; ++idx) { + f16vec4 vv4_temp = (v_coord_temp < p.nek1) ? data_vv4[v_oob_offset + idx * sg_mat_reduce] : f16vec4(0.0f, 0.0f, 0.0f, 0.0f); + F16Poolsh.F16sh[vsh_temp_offset + idx * sg_mat_reduce * TK * 4 + 0 * TK] = vv4_temp.x; + F16Poolsh.F16sh[vsh_temp_offset + idx * sg_mat_reduce * TK * 4 + 1 * TK] = vv4_temp.y; + F16Poolsh.F16sh[vsh_temp_offset + idx * sg_mat_reduce * TK * 4 + 2 * TK] = vv4_temp.z; + F16Poolsh.F16sh[vsh_temp_offset + idx * sg_mat_reduce * TK * 4 + 3 * TK] = vv4_temp.w; + } + } + } + } else { + [[dont_unroll]] for (uint c = 0; c < tk_sg_reduce; ++c) { + const uint v_coord_temp = v_global_coord_base + c * SubGroupSize; + uint v_oob_offset = (v_base + v_coord_temp * p.nbv1 + sg_v_r * TM) / 4 + lane_r; + uint vsh_temp_offset = vsh_offset + c * SubGroupSize + lane_c + lane_r * 4 * TK; + [[dont_unroll]] for (uint r = 0; r < v_loops; ++r) { + [[dont_unroll]] for (uint idx = 0; idx < TM / sg_mat_reduce / 4; ++idx) { + f16vec4 vv4_temp = (v_coord_temp < p.nek1) ? data_vv4[v_oob_offset + idx * sg_mat_reduce] : f16vec4(0.0f, 0.0f, 0.0f, 0.0f); + F16Poolsh.F16sh[vsh_temp_offset + idx * sg_mat_reduce * TK * 4 + 0 * TK] = vv4_temp.x; + F16Poolsh.F16sh[vsh_temp_offset + idx * sg_mat_reduce * TK * 4 + 1 * TK] = vv4_temp.y; + F16Poolsh.F16sh[vsh_temp_offset + idx * sg_mat_reduce * TK * 4 + 2 * TK] = vv4_temp.z; + F16Poolsh.F16sh[vsh_temp_offset + idx * sg_mat_reduce * TK * 4 + 3 * TK] = vv4_temp.w; + } + v_oob_offset += TM * v_hori_groups / 4; + vsh_temp_offset += TM * TK * v_hori_groups; + } + } + } + } else { + if (v_boundary_check) { + [[unroll]] for (uint r = 0; r < v_loops - 1; ++r) { + coopmat VMat; + coopMatLoad(VMat, data_v, v_offset + TM * r * v_hori_groups, p.nbv1, gl_CooperativeMatrixLayoutColumnMajor); + coopMatStore(VMat, F16Poolsh.F16sh, vsh_offset + TM * r * TK * v_hori_groups, TK, gl_CooperativeMatrixLayoutRowMajor); + } + + if ((sg_v_r + (v_loops - 1) * v_hori_groups) * TM < HSV) { + coopmat VMat; + coopMatLoad(VMat, data_v, v_offset + TM * (v_loops - 1) * v_hori_groups, p.nbv1, gl_CooperativeMatrixLayoutColumnMajor); + coopMatStore(VMat, F16Poolsh.F16sh, vsh_offset + TM * (v_loops - 1) * TK * v_hori_groups, TK, gl_CooperativeMatrixLayoutRowMajor); + } + } else { + [[unroll]] for (uint r = 0; r < v_loops; ++r) { + coopmat VMat; + coopMatLoad(VMat, data_v, v_offset + TM * r * v_hori_groups, p.nbv1, gl_CooperativeMatrixLayoutColumnMajor); + coopMatStore(VMat, F16Poolsh.F16sh, vsh_offset + TM * r * TK * v_hori_groups, TK, gl_CooperativeMatrixLayoutRowMajor); + } + } + } + } + + barrier(); + { + const uint coord_p = psh_base * 2 + sg_o_r * TN * step_p * 2; + const uint coord_v_base = vsh_base + sg_o_c * mato_count * TM * TK; + const uint coord_pv = pvsh_base + sg * acc_count * TN * TM; + const uint pvsh_offset = pvsh_base + sg * acc_count * TN * TM + lane_c * acc_count * TM + lane_r * 4; + if (qk_sg != sg_count) { + eMf = F32Poolsh.F32sh[emfsh_base + sg_o_r * TN + lane_c]; + } + coopmat PMat[step_p / TK]; + [[unroll]] for (uint d0 = 0; d0 < step_p / TK; ++d0) { + coopMatLoad(PMat[d0], F16Poolsh.F16sh, coord_p + TK * d0, 2 * step_p, gl_CooperativeMatrixLayoutColumnMajor); + } + + [[unroll]] for (uint pv_col = 0; pv_col < mato_count / acc_count; ++pv_col) { + const uint coord_v = coord_v_base + pv_col * acc_count * TM * TK; + coopmat PVMat[acc_count]; + coopmat VMat[acc_count]; + [[unroll]] for (uint idx = 0; idx < acc_count; ++idx) { + PVMat[idx] = coopmat(0.0f); + } + + [[unroll]] for (uint d0 = 0; d0 < step_p / TK; ++d0) { + if (v_in_shmem) { + [[unroll]] for (uint idx = 0; idx < acc_count; ++idx) { + coopMatLoad(VMat[idx], F16Poolsh.F16sh, coord_v + HSV * TK * d0 + TM * TK * idx, TK, gl_CooperativeMatrixLayoutRowMajor); + } + } else { + if (seq_boundary_check && loop + 1 == loop_count) { + const uint v_global_coord_base = d0 * TK + loop * step_p + lane_c; + const uint vsh_staging_store = vsh_oob_staging_base + (sg * TM * TK + lane_c * TM) / 4 + lane_r; + const uint vsh_staging_load = vsh_oob_staging_base * 4 + sg * TM * TK; + [[unroll]] for (uint idx = 0; idx < acc_count; ++idx) { + subgroupBarrier(); + [[dont_unroll]] for (uint c = 0; c < tk_sg_reduce; ++c) { + const uint v_coord_temp = v_global_coord_base + c * SubGroupSize; + const uint v_oob_offset = (v_base + v_coord_temp * p.nbv1 + sg_o_c * Bc + pv_col * acc_count * TM + idx * TM) / 4 + lane_r; + + if (v_row_overshoot_check) { + const uint v_row_temp = sg_o_c * Bc + pv_col * acc_count * TM + idx * TM; + if (v_row_temp < HSV) { + [[dont_unroll]] for (uint r = 0; r < TM / sg_mat_reduce / 4; ++r) { + f16vec4 vv4_temp = (v_coord_temp < p.nek1) ? data_vv4[v_oob_offset + sg_mat_reduce * r] : f16vec4(0.0f, 0.0f, 0.0f, 0.0f); + F16V4Poolsh.F16V4sh[vsh_staging_store + c * SubGroupSize * TM / 4 + sg_mat_reduce * r] = vv4_temp; + } + } else { + [[dont_unroll]] for (uint r = 0; r < TM / sg_mat_reduce / 4; ++r) { + F16V4Poolsh.F16V4sh[vsh_staging_store + c * SubGroupSize * TM / 4 + sg_mat_reduce * r] = f16vec4(0.0f, 0.0f, 0.0f, 0.0f); + } + } + } else { + [[dont_unroll]] for (uint r = 0; r < TM / sg_mat_reduce / 4; ++r) { + f16vec4 vv4_temp = (v_coord_temp < p.nek1) ? data_vv4[v_oob_offset + sg_mat_reduce * r] : f16vec4(0.0f, 0.0f, 0.0f, 0.0f); + F16V4Poolsh.F16V4sh[vsh_staging_store + c * SubGroupSize * TM / 4 + sg_mat_reduce * r] = vv4_temp; + } + } + } + subgroupBarrier(); + coopMatLoad(VMat[idx], F16Poolsh.F16sh, vsh_staging_load, TM, gl_CooperativeMatrixLayoutColumnMajor); + } + } else { + const uint v_coord_global = v_offset + pv_col * acc_count * TM + d0 * TK * p.nbv1; + if (v_row_overshoot_check) { + [[unroll]] for (uint idx = 0; idx < acc_count; ++idx) { + const uint v_row_temp = sg_o_c * Bc + pv_col * acc_count * TM + idx * TM; + if (v_row_temp < HSV) { + coopMatLoad(VMat[idx], data_v, v_coord_global + TM * idx, p.nbv1, gl_CooperativeMatrixLayoutColumnMajor); + } else { + VMat[idx] = coopmat(0.0f); + } + } + } else { + [[unroll]] for (uint idx = 0; idx < acc_count; ++idx) { + coopMatLoad(VMat[idx], data_v, v_coord_global + TM * idx, p.nbv1, gl_CooperativeMatrixLayoutColumnMajor); + } + } + } + } + + [[unroll]] for (uint idx = 0; idx < acc_count; ++idx) { + PVMat[idx] = coopMatMulAdd(VMat[idx], PMat[d0], PVMat[idx]); + } + } + + if (intel_gpu) { + [[unroll]] for (uint idx = 0; idx < acc_count; ++idx) { + [[unroll]] for (uint e = 0; e < CM1_ELEMS; ++e) { + Of[pv_col * acc_loops + idx * CM1_ELEMS + e] = fma(Of[pv_col * acc_loops + idx * CM1_ELEMS + e], + eMf, + PVMat[idx][e]); + } + } + } else { + barrier(); + + [[unroll]] for (uint idx = 0; idx < acc_count; ++idx) { + coopMatStore(PVMat[idx], F32Poolsh.F32sh, coord_pv + TM * idx, acc_count * TM, gl_CooperativeMatrixLayoutColumnMajor); + } + + subgroupBarrier(); + + [[unroll]] for (uint idx = 0; idx < acc_loops / 4; ++idx) { + [[unroll]] for (uint vec_idx = 0; vec_idx < 4; ++vec_idx) { + Of[pv_col * acc_loops + idx * 4 + vec_idx] = fma(Of[pv_col * acc_loops + idx * 4 + vec_idx], + eMf, + F32Poolsh.F32sh[pvsh_offset + idx * sg_mat_reduce * 4 + vec_idx]); + } + } + barrier(); + } + } + } + + v_offset += p.nbv1 * step_p; + barrier(); + } + + if (sg < qk_sg) { + [[unroll]] for (uint idx = 1; idx < sg_mat_reduce; ++idx) { + Lf += subgroupShuffleDown(Lf, idx * TN); + } + if (lane_r == 0) { + F32Poolsh.F32sh[sg * TN + lane_c] = Mf; + F32Poolsh.F32sh[qk_sg * TN + sg * TN + lane_c] = Lf; + } + } + + barrier(); + + Mf = F32Poolsh.F32sh[sg_o_r * TN + lane_c]; + Lf = F32Poolsh.F32sh[qk_sg * TN + sg_o_r * TN + lane_c]; + + float Lfrcp; + if ((p.flag & SINK_ENABLE_BIT) != 0) { + float sink_emf = Mf - sink; + sink_emf = exp(sink_emf); + float Lf_sink = Lf * sink_emf; + Lf += 1.0f / sink_emf; + Lf = 1.0f / Lf; + sink_emf /= (1.0f + Lf_sink); + Lfrcp = (Mf < sink) ? sink_emf : Lf; + } else { + Lfrcp = (Lf == 0.0f) ? 0.0f : (1.0f / Lf); + } + + [[unroll]] for (uint out_c = 0; out_c < Bc / sg_mat_reduce; ++out_c) { + Of[out_c] *= Lfrcp; + } + + const uint sg_out_r = out_r * folded_row_wg + sg_o_r_row * TN + lane_c; + [[unroll]] for (uint o_chunk = 0; o_chunk < Bc / sg_mat_reduce / 4; ++o_chunk) { + const uint out_c = sg_mat_reduce * 4 * o_chunk + sg_o_c * Bc + lane_r; + if (sg_out_r < p.neq1 && out_c < HSV) { + data_ov4[o_offset + o_chunk * sg_mat_reduce] = vec4(Of[4 * o_chunk], Of[4 * o_chunk + 1], Of[4 * o_chunk + 2], Of[4 * o_chunk + 3]); + } + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp index c1696e4cd9cf..7ccccfa1d3cb 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp @@ -939,6 +939,7 @@ void process_shaders() { #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) string_to_spv("fa_decode_ph1", "flash_attn_decode_phase_1.comp", {}, true, true, false, false); string_to_spv("fa_decode_ph2", "flash_attn_decode_phase_2.comp", {}, true, true, false, false); + string_to_spv("fa_prefill", "flash_attn_prefill.comp", {}, true, true, false, false); #endif string_to_spv("fa_sparse_compact", "flash_attn_sparse_compact.comp", {}); @@ -1074,8 +1075,6 @@ void process_shaders() { string_to_spv("silu_back_f32", "silu_back.comp", {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}}); - string_to_spv("diag_mask_inf_f32", "diag_mask_inf.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}}); - string_to_spv("soft_max_f32", "soft_max.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}})); string_to_spv("soft_max_f32_f16", "soft_max.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float16_t"}, {"D_TYPE", "float"}})); string_to_spv("soft_max_back_f32", "soft_max_back.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}})); diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index c6a080d22f3a..1fca258a531d 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -714,13 +714,13 @@ static const struct ggml_type_traits type_traits[GGML_TYPE_COUNT] = { .from_float_ref = (ggml_from_float_t) quantize_row_q4_1_ref, }, [4] = { // GGML_TYPE_Q4_2 - .type_name = "DEPRECATED", + .type_name = "REMOVED", .blck_size = 0, .type_size = 0, .is_quantized = false, }, [5] = { // GGML_TYPE_Q4_3 - .type_name = "DEPRECATED", + .type_name = "REMOVED", .blck_size = 0, .type_size = 0, .is_quantized = false, @@ -1009,7 +1009,6 @@ static const char * GGML_OP_NAME[GGML_OP_COUNT] = { "DUP", "ADD", "ADD_ID", - "ADD1", "ACC", "SUB", "MUL", @@ -1051,8 +1050,6 @@ static const char * GGML_OP_NAME[GGML_OP_COUNT] = { "GET_ROWS_BACK", "SET_ROWS", "DIAG", - "DIAG_MASK_INF", - "DIAG_MASK_ZERO", "SOFT_MAX", "SOFT_MAX_BACK", "ROPE", @@ -1117,7 +1114,7 @@ static const char * GGML_OP_NAME[GGML_OP_COUNT] = { "GLU", }; -static_assert(GGML_OP_COUNT == 102, "GGML_OP_COUNT != 102"); +static_assert(GGML_OP_COUNT == 99, "GGML_OP_COUNT != 99"); static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "none", @@ -1125,7 +1122,6 @@ static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "x", "x+y", "x[i]+y", - "x+y", "view(x,nb,offset)+=y->x", "x-y", "x*y", @@ -1167,8 +1163,6 @@ static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "get_rows_back(x)", "set_rows(x)", "diag(x)", - "diag_mask_inf(x)", - "diag_mask_zero(x)", "soft_max(x)", "soft_max_back(x)", "rope(x)", @@ -1233,7 +1227,7 @@ static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "glu(x)", }; -static_assert(GGML_OP_COUNT == 102, "GGML_OP_COUNT != 102"); +static_assert(GGML_OP_COUNT == 99, "GGML_OP_COUNT != 99"); static_assert(GGML_OP_POOL_COUNT == 2, "GGML_OP_POOL_COUNT != 2"); @@ -1360,12 +1354,6 @@ size_t ggml_row_size(enum ggml_type type, int64_t ne) { return ggml_type_size(type)*ne/ggml_blck_size(type); } -double ggml_type_sizef(enum ggml_type type) { - assert(type >= 0); - assert(type < GGML_TYPE_COUNT); - return ((double)(type_traits[type].type_size))/type_traits[type].blck_size; -} - const char * ggml_type_name(enum ggml_type type) { assert(type >= 0); assert(type < GGML_TYPE_COUNT); @@ -2172,39 +2160,6 @@ struct ggml_tensor * ggml_add_id( return result; } -// ggml_add1 - -static struct ggml_tensor * ggml_add1_impl( - struct ggml_context * ctx, - struct ggml_tensor * a, - struct ggml_tensor * b, - bool inplace) { - GGML_ASSERT(ggml_is_scalar(b)); - GGML_ASSERT(ggml_is_padded_1d(a)); - - struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a); - - result->op = GGML_OP_ADD1; - result->src[0] = a; - result->src[1] = b; - - return result; -} - -struct ggml_tensor * ggml_add1( - struct ggml_context * ctx, - struct ggml_tensor * a, - struct ggml_tensor * b) { - return ggml_add1_impl(ctx, a, b, false); -} - -struct ggml_tensor * ggml_add1_inplace( - struct ggml_context * ctx, - struct ggml_tensor * a, - struct ggml_tensor * b) { - return ggml_add1_impl(ctx, a, b, true); -} - // ggml_acc static struct ggml_tensor * ggml_acc_impl( @@ -3419,16 +3374,6 @@ struct ggml_tensor * ggml_mul_mat( return result; } -void ggml_mul_mat_set_prec( - struct ggml_tensor * a, - enum ggml_prec prec) { - GGML_ASSERT(a->op == GGML_OP_MUL_MAT); - - const int32_t prec_i32 = (int32_t) prec; - - ggml_set_op_params_i32(a, 0, prec_i32); -} - void ggml_mul_mat_set_hint( struct ggml_tensor * a, enum ggml_op_hint hint) { @@ -4102,70 +4047,6 @@ struct ggml_tensor * ggml_diag( return result; } -// ggml_diag_mask_inf - -static struct ggml_tensor * ggml_diag_mask_inf_impl( - struct ggml_context * ctx, - struct ggml_tensor * a, - int n_past, - bool inplace) { - struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a); - - int32_t params[] = { n_past }; - ggml_set_op_params(result, params, sizeof(params)); - - result->op = GGML_OP_DIAG_MASK_INF; - result->src[0] = a; - - return result; -} - -struct ggml_tensor * ggml_diag_mask_inf( - struct ggml_context * ctx, - struct ggml_tensor * a, - int n_past) { - return ggml_diag_mask_inf_impl(ctx, a, n_past, false); -} - -struct ggml_tensor * ggml_diag_mask_inf_inplace( - struct ggml_context * ctx, - struct ggml_tensor * a, - int n_past) { - return ggml_diag_mask_inf_impl(ctx, a, n_past, true); -} - -// ggml_diag_mask_zero - -static struct ggml_tensor * ggml_diag_mask_zero_impl( - struct ggml_context * ctx, - struct ggml_tensor * a, - int n_past, - bool inplace) { - struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a); - - int32_t params[] = { n_past }; - ggml_set_op_params(result, params, sizeof(params)); - - result->op = GGML_OP_DIAG_MASK_ZERO; - result->src[0] = a; - - return result; -} - -struct ggml_tensor * ggml_diag_mask_zero( - struct ggml_context * ctx, - struct ggml_tensor * a, - int n_past) { - return ggml_diag_mask_zero_impl(ctx, a, n_past, false); -} - -struct ggml_tensor * ggml_diag_mask_zero_inplace( - struct ggml_context * ctx, - struct ggml_tensor * a, - int n_past) { - return ggml_diag_mask_zero_impl(ctx, a, n_past, true); -} - // ggml_clamp static struct ggml_tensor * ggml_clamp_impl( @@ -4487,44 +4368,6 @@ struct ggml_tensor * ggml_rope_ext_inplace( ); } -struct ggml_tensor * ggml_rope_custom( - struct ggml_context * ctx, - struct ggml_tensor * a, - struct ggml_tensor * b, - int n_dims, - int mode, - int n_ctx_orig, - float freq_base, - float freq_scale, - float ext_factor, - float attn_factor, - float beta_fast, - float beta_slow) { - return ggml_rope_impl( - ctx, a, b, NULL, n_dims, NULL, mode, n_ctx_orig, freq_base, freq_scale, - ext_factor, attn_factor, beta_fast, beta_slow, false - ); -} - -struct ggml_tensor * ggml_rope_custom_inplace( - struct ggml_context * ctx, - struct ggml_tensor * a, - struct ggml_tensor * b, - int n_dims, - int mode, - int n_ctx_orig, - float freq_base, - float freq_scale, - float ext_factor, - float attn_factor, - float beta_fast, - float beta_slow) { - return ggml_rope_impl( - ctx, a, b, NULL, n_dims, NULL, mode, n_ctx_orig, freq_base, freq_scale, - ext_factor, attn_factor, beta_fast, beta_slow, true - ); -} - // Apparently solving `n_rot = 2pi * x * base^((2 * max_pos_emb) / n_dims)` for x, we get // `corr_dim(n_rot) = n_dims * log(max_pos_emb / (n_rot * 2pi)) / (2 * log(base))` static float ggml_rope_yarn_corr_dim(int n_dims, int n_ctx_orig, float n_rot, float base) { @@ -5264,17 +5107,6 @@ struct ggml_tensor * ggml_upscale( return ggml_interpolate_impl(ctx, a, a->ne[0] * scale_factor, a->ne[1] * scale_factor, a->ne[2], a->ne[3], mode); } -struct ggml_tensor * ggml_upscale_ext( - struct ggml_context * ctx, - struct ggml_tensor * a, - int ne0, - int ne1, - int ne2, - int ne3, - enum ggml_scale_mode mode) { - return ggml_interpolate_impl(ctx, a, ne0, ne1, ne2, ne3, mode); -} - struct ggml_tensor * ggml_interpolate( struct ggml_context * ctx, struct ggml_tensor * a, @@ -5654,16 +5486,6 @@ struct ggml_tensor * ggml_flash_attn_ext_rows( } -void ggml_flash_attn_ext_set_prec( - struct ggml_tensor * a, - enum ggml_prec prec) { - GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT); - - const int32_t prec_i32 = (int32_t) prec; - - ggml_set_op_params_i32(a, 3, prec_i32); // scale is on first pos, max_bias on second -} - enum ggml_prec ggml_flash_attn_ext_get_prec( const struct ggml_tensor * a) { GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT); @@ -6873,22 +6695,6 @@ static void ggml_acc_or_set( ggml_build_forward_expand(cgraph, cgraph->grads[isrc]); } -static void ggml_add1_or_set( - struct ggml_context * ctx, - struct ggml_cgraph * cgraph, - size_t isrc, - struct ggml_tensor * tensor) { - struct ggml_tensor * src = cgraph->visited_hash_set.keys[isrc]; - GGML_ASSERT(src); - if (cgraph->grads[isrc]) { - cgraph->grads[isrc] = ggml_add1_impl(ctx, cgraph->grads[isrc], tensor, cgraph->grad_accs[isrc]); - } else { - cgraph->grads[isrc] = ggml_repeat(ctx, tensor, src); - } - ggml_format_name(cgraph->grads[isrc], "grad for %s", src->name); - ggml_build_forward_expand(cgraph, cgraph->grads[isrc]); -} - static void ggml_sub_or_set( struct ggml_context * ctx, struct ggml_cgraph * cgraph, @@ -6943,14 +6749,6 @@ static void ggml_compute_backward( ggml_add_or_set(ctx, cgraph, isrc1, tmp); } } break; - case GGML_OP_ADD1: { - if (src0_needs_grads) { - ggml_add_or_set(ctx, cgraph, isrc0, grad); - } - if (src1_needs_grads) { - ggml_add_or_set(ctx, cgraph, isrc1, ggml_mean(ctx, grad)); // TODO: should probably be sum instead of mean - } - } break; case GGML_OP_ACC: { if (src0_needs_grads) { ggml_add_or_set(ctx, cgraph, isrc0, grad); @@ -7023,7 +6821,7 @@ static void ggml_compute_backward( } break; case GGML_OP_SUM: { if (src0_needs_grads) { - ggml_add1_or_set(ctx, cgraph, isrc0, grad); + ggml_add_or_set(ctx, cgraph, isrc0, ggml_repeat(ctx, grad, src0)); } } break; case GGML_OP_SUM_ROWS: { @@ -7033,7 +6831,7 @@ static void ggml_compute_backward( } break; case GGML_OP_MEAN: { if (src0_needs_grads) { - ggml_add1_or_set(ctx, cgraph, isrc0, ggml_scale_impl(ctx, grad, 1.0f/src0->ne[0], 0.0, false)); + ggml_add_or_set(ctx, cgraph, isrc0, ggml_repeat(ctx, ggml_scale_impl(ctx, grad, 1.0f/src0->ne[0], 0.0, false), src0)); } } break; case GGML_OP_REPEAT: { @@ -7223,20 +7021,6 @@ static void ggml_compute_backward( // noop } } break; - case GGML_OP_DIAG_MASK_INF: { - if (src0_needs_grads) { - /* ggml_diag_mask_inf_impl() shouldn't be here */ - /* ref: https://github.com/ggml-org/llama.cpp/pull/4203#discussion_r1412377992 */ - const int n_past = ((const int32_t *) tensor->op_params)[0]; - ggml_add_or_set(ctx, cgraph, isrc0, ggml_diag_mask_zero_impl(ctx, grad, n_past, false)); - } - } break; - case GGML_OP_DIAG_MASK_ZERO: { - if (src0_needs_grads) { - const int n_past = ((const int32_t *) tensor->op_params)[0]; - ggml_add_or_set(ctx, cgraph, isrc0, ggml_diag_mask_zero_impl(ctx, grad, n_past, false)); - } - } break; case GGML_OP_TRI: { if (src0_needs_grads) { ggml_add_or_set(ctx, cgraph, isrc0, ggml_tri(ctx, grad, (enum ggml_tri_type) ggml_get_op_params_i32(tensor, 0))); diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py index 30185f02cc20..ad0bd8e67004 100644 --- a/gguf-py/gguf/constants.py +++ b/gguf-py/gguf/constants.py @@ -998,8 +998,8 @@ class MODEL_TENSOR(IntEnum): HC_FFN_INJECT = auto() # qwen4exp HC_ATTN_DOWN_INJECT = auto() # qwen4exp, [hc_attn_down | hc_attn_inject] HC_FFN_DOWN_INJECT = auto() # qwen4exp, [hc_ffn_down | hc_ffn_inject] - ATTN_QKV_GATE = auto() # qwen4exp, [attn_qkv | attn_gate] - SSM_BETA_ALPHA_CAT = auto() # qwen4exp, [ssm_beta | ssm_alpha], unlike the grouped qwen3next ssm_ba + ATTN_QKV_GATE = auto() # qwen35, qwen4exp, [attn_qkv | attn_gate] + SSM_BETA_ALPHA_CAT = auto() # qwen35, qwen4exp, [ssm_beta | ssm_alpha], unlike the grouped qwen3next ssm_ba PLE_KEY = auto() # qwen4exp PLE_VALUE = auto() # qwen4exp PLE_NORM_KEY = auto() # qwen4exp @@ -3409,6 +3409,7 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.ATTN_POST_NORM, MODEL_TENSOR.ATTN_GATE, MODEL_TENSOR.ATTN_QKV, + MODEL_TENSOR.ATTN_QKV_GATE, MODEL_TENSOR.FFN_GATE, MODEL_TENSOR.FFN_DOWN, MODEL_TENSOR.FFN_UP, @@ -3418,6 +3419,7 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.SSM_NORM, MODEL_TENSOR.SSM_BETA, MODEL_TENSOR.SSM_ALPHA, + MODEL_TENSOR.SSM_BETA_ALPHA_CAT, MODEL_TENSOR.SSM_OUT, # NextN/MTP tensors - preserved but unused MODEL_TENSOR.NEXTN_EH_PROJ, diff --git a/include/llama.h b/include/llama.h index 428f51f8df8b..181d840a6c88 100644 --- a/include/llama.h +++ b/include/llama.h @@ -270,7 +270,7 @@ extern "C" { llama_pos * pos; int32_t * n_seq_id; llama_seq_id ** seq_id; - int8_t * logits; // TODO: rename this to "output" + int8_t * logits; } llama_batch; enum llama_model_kv_override_type { @@ -389,7 +389,6 @@ extern "C" { float yarn_beta_fast; // YaRN low correction dim float yarn_beta_slow; // YaRN high correction dim uint32_t yarn_orig_ctx; // YaRN original context size - float defrag_thold; // [DEPRECATED] defragment the KV cache if holes/size > thold, <= 0 disabled (default) ggml_backend_sched_eval_callback cb_eval; void * cb_eval_user_data; @@ -516,11 +515,6 @@ extern "C" { void * set_tensor_data_ud, // userdata for function struct llama_model_params params); - DEPRECATED(LLAMA_API struct llama_model * llama_load_model_from_file( - const char * path_model, - struct llama_model_params params), - "use llama_model_load_from_file instead"); - // Load a model from a file // If the file is split into multiple parts, the file name must follow this pattern: -%05d-of-%05d.gguf // If the split file name does not follow this pattern, use llama_model_load_from_splits @@ -546,20 +540,12 @@ extern "C" { const struct llama_model * model, const char * path_model); - DEPRECATED(LLAMA_API void llama_free_model(struct llama_model * model), - "use llama_model_free instead"); - LLAMA_API void llama_model_free(struct llama_model * model); LLAMA_API struct llama_context * llama_init_from_model( struct llama_model * model, struct llama_context_params params); - DEPRECATED(LLAMA_API struct llama_context * llama_new_context_with_model( - struct llama_model * model, - struct llama_context_params params), - "use llama_init_from_model instead"); - // Frees all allocated memory LLAMA_API void llama_free(struct llama_context * ctx); @@ -584,13 +570,6 @@ extern "C" { LLAMA_API uint32_t llama_n_seq_max (const struct llama_context * ctx); LLAMA_API uint32_t llama_n_rs_seq (const struct llama_context * ctx); - DEPRECATED(LLAMA_API int32_t llama_n_ctx_train(const struct llama_model * model), "use llama_model_n_ctx_train instead"); - DEPRECATED(LLAMA_API int32_t llama_n_embd (const struct llama_model * model), "use llama_model_n_embd instead"); - DEPRECATED(LLAMA_API int32_t llama_n_layer (const struct llama_model * model), "use llama_model_n_layer instead"); - DEPRECATED(LLAMA_API int32_t llama_n_head (const struct llama_model * model), "use llama_model_n_head instead"); - - DEPRECATED(LLAMA_API int32_t llama_n_vocab (const struct llama_vocab * vocab), "use llama_vocab_n_tokens instead"); - LLAMA_API const struct llama_model * llama_get_model (const struct llama_context * ctx); LLAMA_API llama_memory_t llama_get_memory (const struct llama_context * ctx); LLAMA_API enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx); // TODO: rename to llama_get_pooling_type @@ -684,6 +663,19 @@ extern "C" { const char * fname_out, const llama_model_quantize_params * params); + // + // NextN / speculative draft model queries + // + + // DFlash2 selector: number of candidate tokens the draft keeps per block position from its logits + // (the packed lattice also holds the top_k x top_k pairwise transition scores); 0 if the model has no selector head + LLAMA_API int32_t llama_model_dflash_selector_top_k(const struct llama_model * model); + + // returns pointer to the target-model layer indices + LLAMA_API const int32_t * llama_model_target_layer_ids (const struct llama_model * model); + // returns the number of extracted layers from target model + LLAMA_API uint32_t llama_model_target_layer_ids_n(const struct llama_model * model); + // // Adapters // @@ -830,8 +822,6 @@ extern "C" { // (logits, embedding and memory) // Only use when saving the state, not when restoring it, otherwise the size may be too small. LLAMA_API size_t llama_state_get_size(struct llama_context * ctx); - LLAMA_API DEPRECATED(size_t llama_get_state_size(struct llama_context * ctx), - "use llama_state_get_size instead"); // Copies the state to the specified destination address. // Destination needs to have allocated enough memory. @@ -840,10 +830,6 @@ extern "C" { struct llama_context * ctx, uint8_t * dst, size_t size); - LLAMA_API DEPRECATED(size_t llama_copy_state_data( - struct llama_context * ctx, - uint8_t * dst), - "use llama_state_get_data instead"); // Set the state reading from the specified address // Returns the number of bytes read @@ -851,10 +837,6 @@ extern "C" { struct llama_context * ctx, const uint8_t * src, size_t size); - LLAMA_API DEPRECATED(size_t llama_set_state_data( - struct llama_context * ctx, - const uint8_t * src), - "use llama_state_set_data instead"); // Save/load session file LLAMA_API bool llama_state_load_file( @@ -863,25 +845,12 @@ extern "C" { llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out); - LLAMA_API DEPRECATED(bool llama_load_session_file( - struct llama_context * ctx, - const char * path_session, - llama_token * tokens_out, - size_t n_token_capacity, - size_t * n_token_count_out), - "use llama_state_load_file instead"); LLAMA_API bool llama_state_save_file( struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count); - LLAMA_API DEPRECATED(bool llama_save_session_file( - struct llama_context * ctx, - const char * path_session, - const llama_token * tokens, - size_t n_token_count), - "use llama_state_save_file instead"); // Get the exact size needed to copy the state of a single sequence LLAMA_API size_t llama_state_seq_get_size( @@ -1065,6 +1034,15 @@ extern "C" { int32_t idx, struct llama_embd embd); + // Add an entry whose embedding is row `row` of the layer input device buffer of ctx_other. + // All entries of the batch must be of this kind. Positions are set with llama_batch_ext_set_pos(), n_pos_per_embd of them. + // Returns the batch index (>= 0), or the llama_batch_ext_add() error codes. + LLAMA_API int32_t llama_batch_ext_add_embd_row(struct llama_batch_ext * batch, llama_seq_id seq_id, int32_t row); + + // The state of entry idx is row `row` of the h_nextn device buffer of the context set with llama_set_ctx_state_src(). + // All entries of a batch have a state row, or none. + LLAMA_API bool llama_batch_ext_set_embd_state_row(struct llama_batch_ext * batch, int32_t idx, int32_t row); + // Set if output embeddings should be available for the token at index idx in the batch // Note: for now, this is equivalent to setting the output logits LLAMA_API bool llama_batch_ext_set_output_embd( @@ -1118,14 +1096,6 @@ extern "C" { // Returns whether the context is currently using causal attention LLAMA_API bool llama_get_causal_attn(const struct llama_context * ctx); - // Set whether the model is in warmup mode or not - // If true, all model tensors are activated during llama_decode() to load and cache their weights. - // - // note: using this can cause extra graph reallocations because it changes the graph topology with MoE models, - // so it is generally not recommended to use in practice. will be removed in the future - DEPRECATED(LLAMA_API void llama_set_warmup(struct llama_context * ctx, bool warmup), - "user code should do warmup runs manually [TAG_LLAMA_GRAPH_NO_WARMUP]"); - // Set abort callback LLAMA_API void llama_set_abort_callback(struct llama_context * ctx, ggml_abort_callback abort_callback, void * abort_callback_data); @@ -1170,6 +1140,57 @@ extern "C" { // otherwise: float[n_embd] (1-dimensional) LLAMA_API float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id); + // + // NextN / speculative decoding API + // + + // Set whether the context outputs nextn embeddings or not + // If masked == true, output the embeddings only for the tokens with batch.logits != 0 + // If masked == false, output the embeddings for all tokens in the batch regardless of batch.logits + LLAMA_API void llama_set_embeddings_nextn(struct llama_context * ctx, bool value, bool masked); + + // Select which appended NextN block the DECODER_MTP graph runs (offset past + // the trunk: il = n_layer() + offset). Used by the speculative NextN driver to + // chain multiple trained NextN heads. Default 0 (first head). + LLAMA_API void llama_set_nextn_layer_offset(struct llama_context * ctx, int32_t offset); + + // Get all nextn embeddings, mirroring llama_get_embeddings() + LLAMA_API float * llama_get_embeddings_nextn(struct llama_context * ctx); + + // Get the nextn embeddings for the ith token, mirroring llama_get_embeddings_ith() + LLAMA_API float * llama_get_embeddings_nextn_ith(struct llama_context * ctx, int32_t i); + + // Set whether the context outputs the input embeddings of a specific layer + LLAMA_API void llama_set_embeddings_layer_inp(struct llama_context * ctx, uint32_t lid, bool value); + + // Get the input embeddings of a specific layer, mirroring llama_get_embeddings() + LLAMA_API float * llama_get_embeddings_layer_inp(struct llama_context * ctx, uint32_t lid); + + // Write the enabled layer inputs to a device buffer [n_layer_inp*n_embd, n_batch] instead of host memory. + // Row r holds the token at batch index r, layers in ascending layer id order. + LLAMA_API void llama_set_embeddings_layer_inp_dev(struct llama_context * ctx, bool value); + + // Whether decode accepts entries added with llama_batch_ext_add_embd_row() + // (needs a DFlash/DSpark decoder context whose ctx_other has a layer input device buffer). + LLAMA_API bool llama_supports_embd_row(const struct llama_context * ctx); + + // Write the unmasked h_nextn rows (see llama_set_embeddings_nextn) of each decode to a device buffer + // [n_embd_out, n_batch + n_seq_max] instead of host memory: row r < n_batch is the token at batch index r of the last decode, + // row n_batch + s is free for the caller, e.g. for seq s (see llama_set_embeddings_nextn_rows()). + // Returns false if the buffer cannot be used, the rows are then extracted to host memory. + LLAMA_API bool llama_set_embeddings_nextn_dev(struct llama_context * ctx, bool value); + + // Copy rows of the h_nextn device buffer to or from host memory, ordered after the last decode and its readers + LLAMA_API bool llama_get_embeddings_nextn_rows(struct llama_context * ctx, int64_t row0, int64_t n_rows, float * out); + LLAMA_API bool llama_set_embeddings_nextn_rows(struct llama_context * ctx, int64_t row0, int64_t n_rows, const float * data); + + // Read the state rows of batches (see llama_batch_ext_set_embd_state_row()) from the h_nextn device buffer of ctx_src. + // Returns whether decode accepts batches with state rows. + LLAMA_API bool llama_set_ctx_state_src(struct llama_context * ctx, struct llama_context * ctx_src); + + // The paired context (llama_context_params::ctx_other), e.g. the target context of a draft context; may be nullptr + LLAMA_API struct llama_context * llama_get_ctx_other(struct llama_context * ctx); + // // backend sampling API [EXPERIMENTAL] // note: use only if the llama_context was created with at least one llama_sampler_seq_config @@ -1238,31 +1259,6 @@ extern "C" { LLAMA_API llama_token llama_vocab_fim_rep(const struct llama_vocab * vocab); LLAMA_API llama_token llama_vocab_fim_sep(const struct llama_vocab * vocab); - DEPRECATED(LLAMA_API const char * llama_token_get_text(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_get_text instead"); - DEPRECATED(LLAMA_API float llama_token_get_score(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_get_score instead"); - DEPRECATED(LLAMA_API enum llama_token_attr llama_token_get_attr(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_get_attr instead"); - DEPRECATED(LLAMA_API bool llama_token_is_eog(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_is_eog instead"); - DEPRECATED(LLAMA_API bool llama_token_is_control(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_is_control instead"); - DEPRECATED(LLAMA_API llama_token llama_token_bos(const struct llama_vocab * vocab), "use llama_vocab_bos instead"); - DEPRECATED(LLAMA_API llama_token llama_token_eos(const struct llama_vocab * vocab), "use llama_vocab_eos instead"); - DEPRECATED(LLAMA_API llama_token llama_token_eot(const struct llama_vocab * vocab), "use llama_vocab_eot instead"); - DEPRECATED(LLAMA_API llama_token llama_token_cls(const struct llama_vocab * vocab), "use llama_vocab_cls instead"); - DEPRECATED(LLAMA_API llama_token llama_token_sep(const struct llama_vocab * vocab), "use llama_vocab_sep instead"); - DEPRECATED(LLAMA_API llama_token llama_token_nl (const struct llama_vocab * vocab), "use llama_vocab_nl instead"); - DEPRECATED(LLAMA_API llama_token llama_token_pad(const struct llama_vocab * vocab), "use llama_vocab_pad instead"); - DEPRECATED(LLAMA_API bool llama_add_bos_token(const struct llama_vocab * vocab), "use llama_vocab_get_add_bos instead"); - DEPRECATED(LLAMA_API bool llama_add_eos_token(const struct llama_vocab * vocab), "use llama_vocab_get_add_eos instead"); - DEPRECATED(LLAMA_API llama_token llama_token_fim_pre(const struct llama_vocab * vocab), "use llama_vocab_fim_pre instead"); - DEPRECATED(LLAMA_API llama_token llama_token_fim_suf(const struct llama_vocab * vocab), "use llama_vocab_fim_suf instead"); - DEPRECATED(LLAMA_API llama_token llama_token_fim_mid(const struct llama_vocab * vocab), "use llama_vocab_fim_mid instead"); - DEPRECATED(LLAMA_API llama_token llama_token_fim_pad(const struct llama_vocab * vocab), "use llama_vocab_fim_pad instead"); - DEPRECATED(LLAMA_API llama_token llama_token_fim_rep(const struct llama_vocab * vocab), "use llama_vocab_fim_rep instead"); - DEPRECATED(LLAMA_API llama_token llama_token_fim_sep(const struct llama_vocab * vocab), "use llama_vocab_fim_sep instead"); - - // CLS is equivalent to BOS - DEPRECATED(LLAMA_API llama_token llama_vocab_cls(const struct llama_vocab * vocab), // classification - "use llama_vocab_bos instead"); - // // Tokenization // @@ -1534,17 +1530,6 @@ extern "C" { const char * grammar_str, const char * grammar_root); - DEPRECATED(LLAMA_API struct llama_sampler * llama_sampler_init_grammar_lazy( - const struct llama_vocab * vocab, - const char * grammar_str, - const char * grammar_root, - const char ** trigger_words, - size_t num_trigger_words, - const llama_token * trigger_tokens, - size_t num_trigger_tokens), - "use llama_sampler_init_grammar_lazy_patterns instead"); - - /// @details Lazy grammar sampler, introduced in https://github.com/ggml-org/llama.cpp/pull/9639 /// @param trigger_patterns A list of patterns that will trigger the grammar sampler. Pattern will be matched from the start of the generation output, and grammar sampler will be fed content starting from its first match group. /// @param trigger_tokens A list of tokens that will trigger the grammar sampler. Grammar sampler will be fed content starting from the trigger token included. diff --git a/models/templates/google-gemma-4-31B-it-interleaved.jinja b/models/templates/google-gemma-4-31B-it-interleaved.jinja deleted file mode 100644 index 85791c4fe5dc..000000000000 --- a/models/templates/google-gemma-4-31B-it-interleaved.jinja +++ /dev/null @@ -1,282 +0,0 @@ -{%- macro format_parameters(properties, required) -%} - {%- set standard_keys = ['description', 'type', 'properties', 'required', 'nullable'] -%} - {%- set ns = namespace(found_first=false) -%} - {%- for key, value in properties | dictsort -%} - {%- set add_comma = false -%} - {%- if key not in standard_keys -%} - {%- if ns.found_first %},{% endif -%} - {%- set ns.found_first = true -%} - {{ key }}:{ - {%- if value['description'] -%} - description:<|"|>{{ value['description'] }}<|"|> - {%- set add_comma = true -%} - {%- endif -%} - {%- if value['nullable'] %} - {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} - nullable:true - {%- endif -%} - {%- if value['type'] | upper == 'STRING' -%} - {%- if value['enum'] -%} - {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} - enum:{{ format_argument(value['enum']) }} - {%- endif -%} - {%- elif value['type'] | upper == 'OBJECT' -%} - ,properties:{ - {%- if value['properties'] is defined and value['properties'] is mapping -%} - {{- format_parameters(value['properties'], value['required'] | default([])) -}} - {%- elif value is mapping -%} - {{- format_parameters(value, value['required'] | default([])) -}} - {%- endif -%} - } - {%- if value['required'] -%} - ,required:[ - {%- for item in value['required'] | default([]) -%} - <|"|>{{- item -}}<|"|> - {%- if not loop.last %},{% endif -%} - {%- endfor -%} - ] - {%- endif -%} - {%- elif value['type'] | upper == 'ARRAY' -%} - {%- if value['items'] is mapping and value['items'] -%} - ,items:{ - {%- set ns_items = namespace(found_first=false) -%} - {%- for item_key, item_value in value['items'] | dictsort -%} - {%- if item_value is not none -%} - {%- if ns_items.found_first %},{% endif -%} - {%- set ns_items.found_first = true -%} - {%- if item_key == 'properties' -%} - properties:{ - {%- if item_value is mapping -%} - {{- format_parameters(item_value, value['items']['required'] | default([])) -}} - {%- endif -%} - } - {%- elif item_key == 'required' -%} - required:[ - {%- for req_item in item_value -%} - <|"|>{{- req_item -}}<|"|> - {%- if not loop.last %},{% endif -%} - {%- endfor -%} - ] - {%- elif item_key == 'type' -%} - {%- if item_value is string -%} - type:{{ format_argument(item_value | upper) }} - {%- else -%} - type:{{ format_argument(item_value | map('upper') | list) }} - {%- endif -%} - {%- else -%} - {{ item_key }}:{{ format_argument(item_value) }} - {%- endif -%} - {%- endif -%} - {%- endfor -%} - } - {%- endif -%} - {%- endif -%} - {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} - type:<|"|>{{ value['type'] | upper }}<|"|>} - {%- endif -%} - {%- endfor -%} -{%- endmacro -%} -{%- macro format_function_declaration(tool_data) -%} - declaration:{{- tool_data['function']['name'] -}}{description:<|"|>{{- tool_data['function']['description'] -}}<|"|> - {%- set params = tool_data['function']['parameters'] -%} - {%- if params -%} - ,parameters:{ - {%- if params['properties'] -%} - properties:{ {{- format_parameters(params['properties'], params['required']) -}} }, - {%- endif -%} - {%- if params['required'] -%} - required:[ - {%- for item in params['required'] -%} - <|"|>{{- item -}}<|"|> - {{- ',' if not loop.last -}} - {%- endfor -%} - ], - {%- endif -%} - {%- if params['type'] -%} - type:<|"|>{{- params['type'] | upper -}}<|"|>} - {%- endif -%} - {%- endif -%} - {%- if 'response' in tool_data['function'] -%} - {%- set response_declaration = tool_data['function']['response'] -%} - ,response:{ - {%- if response_declaration['description'] -%} - description:<|"|>{{- response_declaration['description'] -}}<|"|>, - {%- endif -%} - {%- if response_declaration['type'] | upper == 'OBJECT' -%} - type:<|"|>{{- response_declaration['type'] | upper -}}<|"|>} - {%- endif -%} - {%- endif -%} - } -{%- endmacro -%} -{%- macro format_argument(argument, escape_keys=True) -%} - {%- if argument is string -%} - {{- '<|"|>' + argument + '<|"|>' -}} - {%- elif argument is boolean -%} - {{- 'true' if argument else 'false' -}} - {%- elif argument is mapping -%} - {{- '{' -}} - {%- set ns = namespace(found_first=false) -%} - {%- for key, value in argument | dictsort -%} - {%- if ns.found_first %},{% endif -%} - {%- set ns.found_first = true -%} - {%- if escape_keys -%} - {{- '<|"|>' + key + '<|"|>' -}} - {%- else -%} - {{- key -}} - {%- endif -%} - :{{- format_argument(value, escape_keys=escape_keys) -}} - {%- endfor -%} - {{- '}' -}} - {%- elif argument is sequence -%} - {{- '[' -}} - {%- for item in argument -%} - {{- format_argument(item, escape_keys=escape_keys) -}} - {%- if not loop.last %},{% endif -%} - {%- endfor -%} - {{- ']' -}} - {%- else -%} - {{- argument -}} - {%- endif -%} -{%- endmacro -%} -{%- macro strip_thinking(text) -%} - {%- set ns = namespace(result='') -%} - {%- for part in text.split('') -%} - {%- if '<|channel>' in part -%} - {%- set ns.result = ns.result + part.split('<|channel>')[0] -%} - {%- else -%} - {%- set ns.result = ns.result + part -%} - {%- endif -%} - {%- endfor -%} - {{- ns.result | trim -}} -{%- endmacro -%} - -{%- set ns = namespace(prev_message_type=None, last_user_message=-1) -%} -{%- set loop_messages = messages -%} -{{- bos_token -}} -{#- Handle System/Tool Definitions Block -#} -{%- if (enable_thinking is defined and enable_thinking) or tools or messages[0]['role'] in ['system', 'developer'] -%} - {{- '<|turn>system\n' -}} - - {#- Inject Thinking token at the very top of the FIRST system turn -#} - {%- if enable_thinking is defined and enable_thinking -%} - {{- '<|think|>\n' -}} - {%- set ns.prev_message_type = 'think' -%} - {%- endif -%} - - {%- if messages[0]['role'] in ['system', 'developer'] -%} - {{- messages[0]['content'] | trim -}} - {%- set loop_messages = messages[1:] -%} - {%- endif -%} - - {%- if tools -%} - {%- for tool in tools %} - {{- '<|tool>' -}} - {{- format_function_declaration(tool) | trim -}} - {{- '' -}} - {%- endfor %} - {%- set ns.prev_message_type = 'tool' -%} - {%- endif -%} - - {{- '\n' -}} -{%- endif %} - -{#- Find last user message -#} -{%- for message in loop_messages -%} - {%- if message['role'] == 'user' -%} - {%- set ns.last_user_message = loop.index0 -%} - {%- endif -%} -{%- endfor -%} - -{#- Loop through messages -#} -{%- for message in loop_messages -%} - {%- set role = 'model' if message['role'] == 'assistant' else message['role'] -%} - {%- if not (ns.prev_message_type == 'tool_response' and message['tool_calls']) -%} - {{- '<|turn>' + role + '\n' }} - {%- endif -%} - - {%- set ns.prev_message_type = None -%} - - {%- if message['tool_calls'] -%} - {#- Preserve reasoning between tool calls for model turns that come after the last user turn -#} - {%- if message['reasoning_content'] and loop.index0 > ns.last_user_message -%} - {{- '<|channel>thought\n' -}} - {{- message['reasoning_content'] -}} - {{- '' -}} - {%- endif -%} - {%- for tool_call in message['tool_calls'] -%} - {%- set function = tool_call['function'] -%} - {{- '<|tool_call>call:' + function['name'] + '{' -}} - {%- if function['arguments'] is mapping -%} - {%- set ns_args = namespace(found_first=false) -%} - {%- for key, value in function['arguments'] | dictsort -%} - {%- if ns_args.found_first %},{% endif -%} - {%- set ns_args.found_first = true -%} - {{- key -}}:{{- format_argument(value, escape_keys=False) -}} - {%- endfor -%} - {%- elif function['arguments'] is string -%} - {{- function['arguments'] -}} - {%- endif -%} - {{- '}' -}} - {%- endfor -%} - {%- set ns.prev_message_type = 'tool_call' -%} - {%- endif -%} - - {%- if message['tool_responses'] -%} - {#- Tool Response handling -#} - {%- for tool_response in message['tool_responses'] -%} - {{- '<|tool_response>' -}} - {%- if tool_response['response'] is mapping -%} - {{- 'response:' + tool_response['name'] | default('unknown') + '{' -}} - {%- for key, value in tool_response['response'] | dictsort -%} - {{- key -}}:{{- format_argument(value, escape_keys=False) -}} - {%- if not loop.last %},{% endif -%} - {%- endfor -%} - {{- '}' -}} - {%- else -%} - {{- 'response:' + tool_response['name'] | default('unknown') + '{value:' + format_argument(tool_response['response'], escape_keys=False) + '}' -}} - {%- endif -%} - {{- '' -}} - {%- endfor -%} - {%- set ns.prev_message_type = 'tool_response' -%} - {%- endif -%} - - {%- if message['content'] is string -%} - {%- if role == 'model' -%} - {{- strip_thinking(message['content']) -}} - {%- else -%} - {{- message['content'] | trim -}} - {%- endif -%} - {%- elif message['content'] is sequence -%} - {%- for item in message['content'] -%} - {%- if item['type'] == 'text' -%} - {%- if role == 'model' -%} - {{- strip_thinking(item['text']) -}} - {%- else -%} - {{- item['text'] | trim -}} - {%- endif -%} - {%- elif item['type'] == 'image' -%} - {{- '<|image|>' -}} - {%- set ns.prev_message_type = 'image' -%} - {%- elif item['type'] == 'audio' -%} - {{- '<|audio|>' -}} - {%- set ns.prev_message_type = 'audio' -%} - {%- elif item['type'] == 'video' -%} - {{- '<|video|>' -}} - {%- set ns.prev_message_type = 'video' -%} - {%- endif -%} - {%- endfor -%} - {%- endif -%} - - {%- if not (message['tool_responses'] and not message['content']) -%} - {{- '\n' -}} - {%- endif -%} -{%- endfor -%} - -{%- if add_generation_prompt -%} - {%- if ns.prev_message_type != 'tool_response' -%} - {{- '<|turn>model\n' -}} - {%- endif -%} - {%- if not enable_thinking | default(false) -%} - {{- '<|channel>thought\n' -}} - {%- endif -%} -{%- endif -%} diff --git a/scripts/chat_tts_norm.py b/scripts/chat_tts_norm.py new file mode 100644 index 000000000000..a5fbd55b68ed --- /dev/null +++ b/scripts/chat_tts_norm.py @@ -0,0 +1,556 @@ +#!/usr/bin/env python3 +"""Reference implementation of TTS normalization patterns, the tts_norm_scan() and tts_norm_sub() template functions. + +The specification is in docs/tts-norm-patterns.md. This file must give the same result as the C++ implementation +(common/chat-tts-norm.cpp) for every input; tests/test-jinja.cpp checks this in python mode (test-jinja -py). + +Usage with jinja2: + + env.globals["tts_norm_scan"] = chat_tts_norm.tts_norm_scan + env.globals["tts_norm_sub"] = chat_tts_norm.tts_norm_sub +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + +# character classes, explicit codepoint ranges (keep in sync with common/chat-tts-norm.cpp) + +TTS_NORM_SPACE = [ + (0x0009, 0x000D), (0x0020, 0x0020), (0x0085, 0x0085), (0x00A0, 0x00A0), (0x1680, 0x1680), + (0x2000, 0x200A), (0x2028, 0x2029), (0x202F, 0x202F), (0x205F, 0x205F), (0x3000, 0x3000), +] + +TTS_NORM_PUNCT = [ + (0x0021, 0x002F), (0x003A, 0x0040), (0x005B, 0x0060), (0x007B, 0x007E), + (0x00A1, 0x00A9), (0x00AB, 0x00B4), (0x00B6, 0x00B9), (0x00BB, 0x00BF), (0x00D7, 0x00D7), (0x00F7, 0x00F7), + (0x2010, 0x2027), (0x2030, 0x205E), (0x20A0, 0x20CF), (0x2100, 0x218F), (0x2190, 0x2BFF), + (0x3001, 0x3003), (0x3008, 0x3020), (0x3030, 0x3030), (0x303D, 0x303D), (0x30FB, 0x30FB), + (0xFE10, 0xFE19), (0xFE30, 0xFE4F), (0xFE50, 0xFE6B), + (0xFF01, 0xFF0F), (0xFF1A, 0xFF20), (0xFF3B, 0xFF40), (0xFF5B, 0xFF65), + (0x1F000, 0x1FAFF), +] + +TTS_NORM_CONTROL = [ + (0x0000, 0x001F), (0x007F, 0x009F), (0x200B, 0x200F), (0x2060, 0x206F), (0xFEFF, 0xFEFF), +] + +TTS_NORM_HAN = [ + (0x2E80, 0x2FDF), (0x3005, 0x3005), (0x3007, 0x3007), (0x3021, 0x3029), (0x3038, 0x303B), + (0x3400, 0x4DBF), (0x4E00, 0x9FFF), (0xF900, 0xFAFF), (0x20000, 0x323AF), +] + +CLASS_LETTERS = "dspawulhc" +INF = 1 << 31 +MAX_REPEAT = 1000 +MAX_PATTERN_LEN = 4096 + + +def _in(ranges: list[tuple[int, int]], c: int) -> bool: + return any(lo <= c <= hi for lo, hi in ranges) + + +def _is_alpha(c: int) -> bool: + if ord("a") <= c <= ord("z") or ord("A") <= c <= ord("Z"): + return True + if c in (0xAA, 0xB5, 0xBA): + return True + return c >= 0xC0 and not _in(TTS_NORM_SPACE, c) and not _in(TTS_NORM_PUNCT, c) and not _in(TTS_NORM_CONTROL, c) + + +def _class_match(kind: str, c: int) -> bool: + if kind == "d": + return ord("0") <= c <= ord("9") + if kind == "s": + return _in(TTS_NORM_SPACE, c) + if kind == "p": + return _in(TTS_NORM_PUNCT, c) + if kind == "a": + return _is_alpha(c) + if kind == "w": + return _is_alpha(c) or ord("0") <= c <= ord("9") + if kind == "u": + return ord("A") <= c <= ord("Z") + if kind == "l": + return ord("a") <= c <= ord("z") + if kind == "h": + return _in(TTS_NORM_HAN, c) + if kind == "c": + return _in(TTS_NORM_CONTROL, c) + return False + + +def _ascii_lower(c: int) -> int: + return c + 32 if ord("A") <= c <= ord("Z") else c + + +def _ascii_swapcase(c: int) -> int: + if ord("A") <= c <= ord("Z"): + return c + 32 + if ord("a") <= c <= ord("z"): + return c - 32 + return c + + +def _is_ascii_alnum(c: int) -> bool: + return ord("0") <= c <= ord("9") or ord("a") <= c <= ord("z") or ord("A") <= c <= ord("Z") + + +# AST + +LITERAL, SET, ANY, START, END, BOUNDARY, GROUP, LOOKAHEAD, LOOKBEHIND = range(9) +ZERO_WIDTH = (START, END, BOUNDARY, LOOKAHEAD, LOOKBEHIND) + + +@dataclass +class _Set: + neg: bool = False + ranges: list[tuple[int, int]] = field(default_factory=list) + classes: list[tuple[str, bool]] = field(default_factory=list) + + +@dataclass +class _Node: + op: int = GROUP + cp: int = 0 + set: _Set = field(default_factory=_Set) + alts: list[list[_Item]] = field(default_factory=list) + capture: int = -1 + neg: bool = False + + +@dataclass +class _Item: + atom: _Node + min: int = 1 + max: int = 1 + + +class PatternError(ValueError): + pass + + +class _Parser: + def __init__(self, s: list[int]): + self.s = s + self.p = 0 + self.n_caps = 0 + + def fail(self, msg: str): + raise PatternError(f"invalid TTS norm pattern: {msg} at position {self.p}") + + def eof(self) -> bool: + return self.p >= len(self.s) + + def peek_is(self, c: str) -> bool: + return not self.eof() and self.s[self.p] == ord(c) + + def expect(self, c: str, what: str): + if not self.peek_is(c): + self.fail(f"expected {what}") + self.p += 1 + + def parse_alts(self) -> list[list[_Item]]: + alts = [self.parse_seq()] + while self.peek_is("|"): + self.p += 1 + alts.append(self.parse_seq()) + return alts + + def parse_seq(self) -> list[_Item]: + seq: list[_Item] = [] + while not self.eof() and self.s[self.p] not in (ord("|"), ord(")")): + item = _Item(self.parse_atom()) + self.parse_quantifier(item) + seq.append(item) + return seq + + def parse_int(self) -> int: + if self.eof() or not (ord("0") <= self.s[self.p] <= ord("9")): + self.fail("expected number in quantifier") + v = 0 + while not self.eof() and ord("0") <= self.s[self.p] <= ord("9"): + v = v * 10 + self.s[self.p] - ord("0") + if v > MAX_REPEAT: + self.fail(f"repetition count exceeds {MAX_REPEAT}") + self.p += 1 + return v + + def parse_quantifier(self, item: _Item): + if self.eof(): + return + c = chr(self.s[self.p]) + if c not in "?*+{": + return + if item.atom.op in ZERO_WIDTH: + self.fail("zero-width assertion cannot be repeated") + self.p += 1 + if c == "?": + item.min, item.max = 0, 1 + elif c == "*": + item.min, item.max = 0, INF + elif c == "+": + item.min, item.max = 1, INF + else: + item.min = self.parse_int() + item.max = item.min + if self.peek_is(","): + self.p += 1 + item.max = INF if self.peek_is("}") else self.parse_int() + self.expect("}", "'}' to close quantifier") + if item.max < item.min: + self.fail("quantifier max is smaller than min") + if not self.eof() and chr(self.s[self.p]) in "?*+{": + self.fail("multiple quantifiers") + + def parse_group(self) -> _Node: + node = _Node(op=GROUP) + if self.peek_is("?"): + self.p += 1 + if self.eof(): + self.fail("unterminated group") + c = chr(self.s[self.p]) + if c == ":": + self.p += 1 + elif c in "=!": + self.p += 1 + node.op = LOOKAHEAD + node.neg = c == "!" + elif c == "<" and self.p + 1 < len(self.s) and self.s[self.p + 1] in (ord("="), ord("!")): + node.op = LOOKBEHIND + node.neg = self.s[self.p + 1] == ord("!") + self.p += 2 + if self.eof() or self.s[self.p] == ord(")"): + self.fail("lookbehind must contain exactly one codepoint matcher") + atom = self.parse_atom() + if atom.op not in (LITERAL, SET, ANY): + self.fail("lookbehind must contain exactly one codepoint matcher") + if not self.peek_is(")"): + self.fail("lookbehind must contain exactly one codepoint matcher") + self.p += 1 + node.alts = [[_Item(atom)]] + return node + elif c == "i": + self.fail("(?i) is only allowed at the start of the pattern") + else: + self.fail("unknown group type") + else: + node.capture = self.n_caps + self.n_caps += 1 + node.alts = self.parse_alts() + self.expect(")", "')' to close group") + return node + + # returns ("class", (kind, neg)) | ("boundary", None) | ("literal", cp) + def parse_escape(self, in_set: bool) -> tuple[str, Any]: + if self.eof(): + self.fail("dangling '%'") + e = self.s[self.p] + self.p += 1 + if e < 0x80 and chr(e).lower() in CLASS_LETTERS: + return "class", (chr(e).lower(), ord("A") <= e <= ord("Z")) + if e == ord("b") and not in_set: + return "boundary", None + if _is_ascii_alnum(e): + self.p -= 1 + self.fail(f"unknown escape '%{chr(e)}'") + return "literal", e + + def parse_set(self) -> _Node: + node = _Node(op=SET) + if self.peek_is("^"): + node.set.neg = True + self.p += 1 + empty = True + while True: + if self.eof(): + self.fail("unterminated set") + if self.s[self.p] == ord("]"): + self.p += 1 + break + empty = False + if self.s[self.p] == ord("%"): + self.p += 1 + kind, val = self.parse_escape(True) + if kind == "class": + node.set.classes.append(val) + continue + lo = val + else: + lo = self.s[self.p] + self.p += 1 + hi = lo + if self.peek_is("-") and self.p + 1 < len(self.s) and self.s[self.p + 1] != ord("]"): + self.p += 1 + if self.s[self.p] == ord("%"): + self.p += 1 + kind, val = self.parse_escape(True) + if kind == "class": + self.fail("character class cannot be used in a range") + hi = val + else: + hi = self.s[self.p] + self.p += 1 + if hi < lo: + self.fail("invalid range in set") + node.set.ranges.append((lo, hi)) + if empty: + self.fail("empty set") + return node + + def parse_atom(self) -> _Node: + c = chr(self.s[self.p]) + self.p += 1 + if c == "(": + return self.parse_group() + if c == "[": + return self.parse_set() + if c == ".": + return _Node(op=ANY) + if c == "^": + return _Node(op=START) + if c == "$": + return _Node(op=END) + if c == "%": + kind, val = self.parse_escape(False) + if kind == "class": + node = _Node(op=SET) + node.set.classes.append(val) + return node + if kind == "boundary": + return _Node(op=BOUNDARY) + return _Node(op=LITERAL, cp=val) + if c in "?*+{": + self.p -= 1 + self.fail("nothing to repeat") + if c in "]}": + self.p -= 1 + self.fail(f"unescaped '{c}', use '%{c}'") + return _Node(op=LITERAL, cp=ord(c)) + + +class _Matcher: + def __init__(self, t: list[int], icase: bool, n_groups: int): + self.t = t + self.icase = icase + self.caps: list[tuple[int, int]] = [(-1, -1)] * n_groups + + def is_w(self, i: int) -> bool: + return i < len(self.t) and _class_match("w", self.t[i]) + + def set_match(self, st: _Set, c: int) -> bool: + def test(x: int) -> bool: + if any(lo <= x <= hi for lo, hi in st.ranges): + return True + return any(_class_match(kind, x) != neg for kind, neg in st.classes) + + m = test(c) + if not m and self.icase: + o = _ascii_swapcase(c) + if o != c: + m = test(o) + return m != st.neg + + def match_alts(self, alts: list[list[_Item]], i: int) -> int: + """returns the end position, or -1 if no alternative matches""" + for seq in alts: + saved = list(self.caps) + end = self.match_seq(seq, i) + if end >= 0: + return end + self.caps = saved + return -1 + + def match_seq(self, seq: list[_Item], i: int) -> int: + pos = i + for it in seq: + count = 0 + while count < it.max: + is_group = it.atom.op == GROUP + saved = list(self.caps) if is_group else None + e = self.match_once(it.atom, pos) + if e < 0: + if saved is not None: + self.caps = saved + break + if e == pos: + # an empty iteration would repeat forever, it satisfies any remaining minimum + count = max(count + 1, it.min) + break + pos = e + count += 1 + if count < it.min: + return -1 + return pos + + def match_once(self, node: _Node, i: int) -> int: + """returns the end position, or -1 on failure""" + n = len(self.t) + op = node.op + if op == LITERAL: + if i < n and (self.t[i] == node.cp or (self.icase and _ascii_lower(self.t[i]) == _ascii_lower(node.cp))): + return i + 1 + return -1 + if op == SET: + return i + 1 if i < n and self.set_match(node.set, self.t[i]) else -1 + if op == ANY: + return i + 1 if i < n else -1 + if op == START: + return i if i == 0 else -1 + if op == END: + return i if i == n else -1 + if op == BOUNDARY: + return i if (i > 0 and self.is_w(i - 1)) != self.is_w(i) else -1 + if op == GROUP: + e = self.match_alts(node.alts, i) + if e < 0: + return -1 + if node.capture >= 0: + self.caps[node.capture] = (i, e) + return e + if op == LOOKAHEAD: + # captures made inside a lookahead are discarded + saved = list(self.caps) + ok = self.match_alts(node.alts, i) >= 0 + self.caps = saved + return i if ok != node.neg else -1 + if op == LOOKBEHIND: + ok = i > 0 and self.match_once(node.alts[0][0].atom, i - 1) == i + return i if ok != node.neg else -1 + return -1 + + +class Pattern: + def __init__(self, src: str): + if len(src.encode("utf-8")) > MAX_PATTERN_LEN: + raise PatternError(f"invalid TTS norm pattern: pattern is longer than {MAX_PATTERN_LEN} bytes") + self.icase = False + parser = _Parser([ord(c) for c in src]) + if src.startswith("(?i)"): + self.icase = True + parser.p = 4 + self.root = _Node(op=GROUP, alts=parser.parse_alts()) + if not parser.eof(): + parser.fail("unbalanced ')'") + self.n_caps = parser.n_caps + + def match_at(self, t: list[int], pos: int) -> tuple[int, list[tuple[int, int]]] | None: + m = _Matcher(t, self.icase, self.n_caps) + end = m.match_alts(self.root.alts, pos) + if end < 0: + return None + return end, m.caps + + +# (rule index or -1, start, end, groups) with codepoint offsets +Segment = tuple[int, int, int, list[tuple[int, int]]] + + +def scan_segments(text: str, rules: list[Pattern]) -> list[Segment]: + t = [ord(c) for c in text] + n = len(t) + out: list[Segment] = [] + i = 0 + pending = 0 + while i < n: + matched = False + for r, rule in enumerate(rules): + res = rule.match_at(t, i) + if res is not None and res[0] > i: + end, groups = res + if pending < i: + out.append((-1, pending, i, [])) + out.append((r, i, end, groups)) + i = end + pending = i + matched = True + break + if not matched: + i += 1 + if pending < n: + out.append((-1, pending, n, [])) + return out + + +def _rules_from_value(rules: Any) -> list[tuple[str, str]]: + if isinstance(rules, str): + return [("match", rules)] + if isinstance(rules, dict): + out = [] + for k, v in rules.items(): + if not isinstance(v, str): + raise TypeError("tts_norm_scan: rule pattern must be a string") + out.append((str(k), v)) + return out + if isinstance(rules, (list, tuple)): + out = [] + for item in rules: + if not isinstance(item, (list, tuple)) or len(item) != 2 or not isinstance(item[0], str) or not isinstance(item[1], str): + raise TypeError("tts_norm_scan: each rule must be a [name, pattern] pair of strings") + out.append((item[0], item[1])) + return out + raise TypeError("tts_norm_scan: rules must be a string, a dict or a list of [name, pattern] pairs") + + +def tts_norm_scan(text: str, rules: Any) -> list[dict[str, Any]]: + rule_srcs = _rules_from_value(rules) + patterns = [Pattern(src) for _, src in rule_srcs] + out: list[dict[str, Any]] = [] + for r, start, end, groups in scan_segments(text, patterns): + # groups that did not participate are empty strings, so they render as nothing and are falsy + vals = ["" if gs < 0 else text[gs:ge] for gs, ge in groups] + out.append({"rule": rule_srcs[r][0] if r >= 0 else None, "text": text[start:end], "groups": vals}) + return out + + +def _parse_repl(repl: str, pattern: Pattern) -> list[str | int]: + pieces: list[str | int] = [] + lit = "" + i = 0 + while i < len(repl): + c = repl[i] + if c != "%": + lit += c + i += 1 + continue + if i + 1 >= len(repl): + raise PatternError("invalid TTS norm replacement: dangling '%'") + i += 1 + c = repl[i] + if c == "%": + lit += "%" + elif "0" <= c <= "9": + g = ord(c) - ord("0") + if g > pattern.n_caps: + raise PatternError(f"invalid TTS norm replacement: group %{c} does not exist") + if lit: + pieces.append(lit) + lit = "" + pieces.append(g) + else: + raise PatternError(f"invalid TTS norm replacement: unknown escape '%{c}'") + i += 1 + if lit: + pieces.append(lit) + return pieces + + +def tts_norm_sub(text: str, pattern: str, repl: str) -> str: + pat = Pattern(pattern) + pieces = _parse_repl(repl, pat) + out = [] + for r, start, end, groups in scan_segments(text, [pat]): + if r < 0: + out.append(text[start:end]) + continue + for piece in pieces: + if isinstance(piece, str): + out.append(piece) + elif piece == 0: + out.append(text[start:end]) + else: + gs, ge = groups[piece - 1] + if gs >= 0: + out.append(text[gs:ge]) + return "".join(out) diff --git a/scripts/sync_vendor.py b/scripts/sync_vendor.py index 0a5271dc1645..fed4914fff9a 100755 --- a/scripts/sync_vendor.py +++ b/scripts/sync_vendor.py @@ -5,7 +5,7 @@ import sys import subprocess -HTTPLIB_VERSION = "refs/tags/v0.65.0" +HTTPLIB_VERSION = "refs/tags/v0.66.0" # used by examples/gguf-hash, these repos have no release tag, so we pin a commit XXHASH_COMMIT = "9f465f1ea932d6ad9a26cd77496311ffa544cd68" diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 387b5820dab6..7527870a1843 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -136,18 +136,6 @@ static const llm_fused_op_probe llm_fused_op_flash_attn_kv_rows_probe = { /*.n_tokens_per_seq =*/ 1, }; -static const llm_fused_op_probe llm_fused_op_gdn_ar_probe = { - /*.op =*/ LLM_FUSED_OP_GDN_AR, - /*.name =*/ "fused Gated Delta Net (autoregressive)", - /*.n_tokens_per_seq =*/ 1, -}; - -static const llm_fused_op_probe llm_fused_op_gdn_ch_probe = { - /*.op =*/ LLM_FUSED_OP_GDN_CH, - /*.name =*/ "fused Gated Delta Net (chunked)", - /*.n_tokens_per_seq =*/ 16, -}; - static const llm_fused_op_probe llm_fused_op_lid_probe = { /*.op =*/ LLM_FUSED_OP_LIGHTNING_INDEXER, /*.name =*/ "Lightning Indexer", @@ -219,7 +207,6 @@ llama_context::llama_context( cparams.embeddings_nextn_masked = false; cparams.offload_kqv = params.offload_kqv; cparams.no_perf = params.no_perf; - cparams.warmup = false; // +1: id n_layer() taps the output of the last layer ("input" of the head) cparams.embeddings_layer_inp.resize(hparams.n_layer() + 1, false); @@ -347,10 +334,6 @@ llama_context::llama_context( cparams.auto_fa = false; } - cparams.fused_gdn_ar = true; - cparams.fused_gdn_ch = true; - cparams.auto_fgdn = false; - cparams.fused_lid = true; cparams.auto_flid = false; @@ -473,6 +456,13 @@ llama_context::llama_context( __func__, cparams.n_ctx_seq, hparams.n_ctx_train); } + { + const int64_t max_nodes = graph_max_nodes(); + + // the results of the decode graphs are created on first use, see get_gf_res_prev + gf_res_reserve = std::make_unique(max_nodes); + } + if (!hparams.vocab_only) { // GPU backends for (const auto & dev : model.devices) { @@ -732,13 +722,6 @@ void llama_context::resolve_fused_ops(const llama_memory_context_i * mctx, uint3 cparams.auto_fkvr = false; } - if (cparams.auto_fgdn) { - LLAMA_LOG_INFO("%s: resolving fused Gated Delta Net support:\n", func); - resolve(llm_fused_op_gdn_ar_probe, cparams.fused_gdn_ar); - resolve(llm_fused_op_gdn_ch_probe, cparams.fused_gdn_ch); - cparams.auto_fgdn = false; - } - if (cparams.auto_flid) { LLAMA_LOG_INFO("%s: resolving fused Lightning Indexer support:\n", func); resolve(llm_fused_op_lid_probe, cparams.fused_lid); @@ -824,16 +807,21 @@ void llama_context::sched_reserve() { const uint32_t n_seqs = cparams.n_seq_max; const uint32_t n_tokens = std::min(cparams.n_ctx, cparams.n_ubatch); - const size_t max_nodes = this->graph_max_nodes(n_tokens); + const size_t max_nodes = this->graph_max_nodes(); LLAMA_LOG_DEBUG("%s: max_nodes = %zu\n", __func__, max_nodes); - gf_res_prev.clear(); - gf_res_reserve.reset(new llm_graph_result(max_nodes)); sched_small.clear(); sched_active = nullptr; gf_res_invalidate(); + gf_res_reserve->set_max_nodes(max_nodes); + gf_res_reserve->reset(); + for (auto & [key, res] : gf_res_prev) { + res->set_max_nodes(max_nodes); + res->reset(); + } + sched_new({ /*.max_nodes =*/ max_nodes, /*.parallel =*/ cparams.pipeline_parallel, @@ -1673,11 +1661,11 @@ bool llama_context::set_h_nextn_rows(int64_t row0, int64_t n_rows, const float * return true; } -bool llama_context::set_state_src(llama_context * src) { - if (cparams.ctx_state_src != src) { +bool llama_context::set_ctx_state_src(llama_context * ctx_src) { + if (cparams.ctx_state_src != ctx_src) { sched_need_reserve = true; } - cparams.ctx_state_src = src; + cparams.ctx_state_src = ctx_src; return supports_state_row(); } @@ -1720,14 +1708,6 @@ bool llama_context::get_causal_attn() const { return cparams.causal_attn; } -void llama_context::set_warmup(bool value) { - LLAMA_LOG_DEBUG("%s: value = %d\n", __func__, value); - - // no scheduler reserve needed because warmups are usually with small batches - - cparams.warmup = value; -} - bool llama_context::set_sampler(llama_seq_id seq_id, llama_sampler * sampler) { if (!sampler && sampling.samplers.count(seq_id) == 0) { return true; @@ -1870,7 +1850,7 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll } if (ss == nullptr) { sched_small.push_back({ key, ggml_backend_sched_ptr(ggml_backend_sched_new( - backend_ptrs.data(), backend_buft.data(), backend_ptrs.size(), graph_max_nodes(n_tokens_per_size), false, cparams.op_offload)), nullptr }); + backend_ptrs.data(), backend_buft.data(), backend_ptrs.size(), graph_max_nodes(), false, cparams.op_offload)), nullptr }); ss = &sched_small.back(); ggml_backend_sched_set_copy_callback(ss->sched.get(), sched_copy_experts, this); ggml_backend_sched_set_realloc_callback(ss->sched.get(), sched_graph_realloc, this); @@ -2976,14 +2956,11 @@ void llama_context::output_reorder() { // graph // -uint32_t llama_context::graph_max_nodes(uint32_t n_tokens) const { +uint32_t llama_context::graph_max_nodes() const { uint32_t res; - if (model.arch == LLM_ARCH_KIMI_K3 || model.arch == LLM_ARCH_KIMI_K31 || model.arch == LLM_ARCH_GLM5_NEXT) { - // the n_tokens*40 budget below is exhausted at ubatch 3840 - res = std::max(n_tokens * 160, 64u * model.n_tensors()); - } else if (model.arch == LLM_ARCH_HRM_TEXT) { - // the 128-slot looped graph needs roughly one stack per token budget - res = std::max(n_tokens * 80, 64u * model.n_tensors()); + if (model.arch == LLM_ARCH_KIMI_K3 || model.arch == LLM_ARCH_KIMI_K31 || model.arch == LLM_ARCH_GLM5_NEXT || + model.arch == LLM_ARCH_HRM_TEXT) { + res = std::max(1024u, 64u * model.n_tensors()); } else if (model.arch == LLM_ARCH_QWEN3NEXT || model.arch == LLM_ARCH_KIMI_LINEAR || model.arch == LLM_ARCH_METIS16 || @@ -3001,7 +2978,7 @@ uint32_t llama_context::graph_max_nodes(uint32_t n_tokens) const { model.arch == LLM_ARCH_MINIMAX_01 || model.arch == LLM_ARCH_MINIMAX_M3 || model.arch == LLM_ARCH_HY_V4) { - res = std::max(n_tokens * 40, 32u * model.n_tensors()); + res = std::max(1024u, 32u * model.n_tensors()); } else if (model.arch == LLM_ARCH_DFLASH && model.hparams.dflash_selector_rank > 0) { // DFlash2's convolutions and selector are shape work rather than matmuls, // so they cost ~8.6 nodes per tensor against ~5.9 for a plain DFlash draft @@ -4541,7 +4518,6 @@ llama_context_params llama_context_default_params() { /*.yarn_beta_fast =*/ -1.0f, /*.yarn_beta_slow =*/ -1.0f, /*.yarn_orig_ctx =*/ 0, - /*.defrag_thold =*/ -1.0f, /*.cb_eval =*/ nullptr, /*.cb_eval_user_data =*/ nullptr, /*.type_k =*/ GGML_TYPE_F16, @@ -4710,13 +4686,6 @@ llama_context * llama_init_from_model( return nullptr; } -// deprecated -llama_context * llama_new_context_with_model( - llama_model * model, - llama_context_params params) { - return llama_init_from_model(model, params); -} - void llama_free(llama_context * ctx) { delete ctx; } @@ -4792,10 +4761,6 @@ bool llama_get_causal_attn(const llama_context * ctx) { return ctx->get_causal_attn(); } -void llama_set_warmup(llama_context * ctx, bool warmup) { - ctx->set_warmup(warmup); -} - void llama_synchronize(llama_context * ctx) { ctx->synchronize(); } @@ -4854,8 +4819,8 @@ bool llama_set_embeddings_nextn_rows(llama_context * ctx, int64_t row0, int64_t return ctx->set_h_nextn_rows(row0, n_rows, data); } -bool llama_set_embd_state_src(llama_context * ctx, llama_context * src) { - return ctx->set_state_src(src); +bool llama_set_ctx_state_src(llama_context * ctx, llama_context * ctx_src) { + return ctx->set_ctx_state_src(ctx_src); } void llama_set_embeddings_layer_inp_dev(llama_context * ctx, bool value) { @@ -5090,31 +5055,6 @@ bool llama_memory_can_shift(llama_memory_t mem) { // llama state API -// deprecated -size_t llama_get_state_size(llama_context * ctx) { - return llama_state_get_size(ctx); -} - -// deprecated -size_t llama_copy_state_data(llama_context * ctx, uint8_t * dst) { - return llama_state_get_data(ctx, dst, -1); -} - -// deprecated -size_t llama_set_state_data(llama_context * ctx, const uint8_t * src) { - return llama_state_set_data(ctx, src, -1); -} - -// deprecated -bool llama_load_session_file(llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) { - return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out); -} - -// deprecated -bool llama_save_session_file(llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) { - return llama_state_save_file(ctx, path_session, tokens, n_token_count); -} - // Returns the *actual* size of the state. // Intended to be used when saving to state to a buffer. size_t llama_state_get_size(llama_context * ctx) { diff --git a/src/llama-context.h b/src/llama-context.h index 61304ce39334..2eeac49512c3 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -133,12 +133,11 @@ struct llama_context { bool get_h_nextn_rows(int64_t row0, int64_t n_rows, float * out); bool set_h_nextn_rows(int64_t row0, int64_t n_rows, const float * data); - // state rows read from the h_nextn device buffer of src, see llama_set_embd_state_src() - bool set_state_src(llama_context * src); + // state rows read from the h_nextn device buffer of ctx_src, see llama_set_ctx_state_src() + bool set_ctx_state_src(llama_context * ctx_src); bool supports_state_row() const; void set_nextn_layer_offset(int32_t offset); void set_causal_attn(bool value); - void set_warmup(bool value); void set_adapters_lora(llama_adapter_lora ** adapters, size_t n_adapters, float * scales); @@ -272,7 +271,7 @@ struct llama_context { // public: - uint32_t graph_max_nodes(uint32_t n_tokens) const; + uint32_t graph_max_nodes() const; // can reuse the llm_graph_result instance of the context (for example to update a memory module) llm_graph_result * get_gf_res_reserve() const; diff --git a/src/llama-cparams.h b/src/llama-cparams.h index 7ac1513efd2a..52c85bdd2bf7 100644 --- a/src/llama-cparams.h +++ b/src/llama-cparams.h @@ -39,9 +39,6 @@ struct llama_cparams { bool offload_kqv; bool flash_attn; bool auto_fa; - bool fused_gdn_ar; // use fused gated delta net (autoregressive) - bool fused_gdn_ch; // use fused gated delta net (chunked) - bool auto_fgdn; bool fused_lid; // use fused lightning indexer bool auto_flid; bool fused_dsv4_hc_pre; @@ -53,7 +50,6 @@ struct llama_cparams { bool fused_kv_rows; // unified cache: attend to the cells of each sequence only (ggml_flash_attn_ext_rows) bool auto_fkvr; bool no_perf; - bool warmup; // TODO: remove [TAG_LLAMA_GRAPH_NO_WARMUP] bool op_offload; bool kv_unified; bool pipeline_parallel; @@ -75,6 +71,6 @@ struct llama_cparams { llama_context * ctx_other; - // context whose h_nextn device buffer holds the state rows of a batch, see llama_set_embd_state_src() + // context whose h_nextn device buffer holds the state rows of a batch, see llama_set_ctx_state_src() llama_context * ctx_state_src; }; diff --git a/src/llama-ext.h b/src/llama-ext.h index a9a08e97e81f..3ac617b0fa03 100644 --- a/src/llama-ext.h +++ b/src/llama-ext.h @@ -123,16 +123,6 @@ 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); -// Set whether the context outputs nextn embeddings or not -// If masked == true, output the embeddings only for the tokens with batch.logits != 0 -// If masked == false, output the embeddings for all tokens in the batch regardless of batch.logits -LLAMA_API void llama_set_embeddings_nextn(struct llama_context * ctx, bool value, bool masked); - -// Select which appended NextN block the DECODER_MTP graph runs (offset past -// the trunk: il = n_layer() + offset). Used by the speculative NextN driver to -// chain multiple trained NextN heads. Default 0 (first head). -LLAMA_API void llama_set_nextn_layer_offset(struct llama_context * ctx, int32_t offset); - // Marks the entries that a decision head (clef, vllm-decision2) reads, the default is 0 // 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 @@ -150,64 +140,10 @@ LLAMA_API bool llama_batch_ext_set_decision_order(struct llama_batch_ext * batch // 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); -// mirrors: -// LLAMA_API float * llama_get_embeddings(struct llama_context * ctx); -LLAMA_API float * llama_get_embeddings_nextn(struct llama_context * ctx); - -// LLAMA_API float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i); -LLAMA_API float * llama_get_embeddings_nextn_ith(struct llama_context * ctx, int32_t i); - -// Set whether the context outputs the input embeddings of a specific layer -LLAMA_API void llama_set_embeddings_layer_inp(struct llama_context * ctx, uint32_t lid, bool value); - -// mirrors: -// LLAMA_API float * llama_get_embeddings(struct llama_context * ctx); -LLAMA_API float * llama_get_embeddings_layer_inp(struct llama_context * ctx, uint32_t lid); - -// Write the enabled layer inputs to a device buffer [n_layer_inp*n_embd, n_batch] instead of host memory. -// Row r holds the token at batch index r, layers in ascending layer id order. -LLAMA_API void llama_set_embeddings_layer_inp_dev(struct llama_context * ctx, bool value); - -// Whether decode accepts entries added with llama_batch_ext_add_embd_row() -// (needs a DFlash/DSpark decoder context whose ctx_other has a layer input device buffer). -LLAMA_API bool llama_supports_embd_row(const struct llama_context * ctx); - -// Add an entry whose embedding is row `row` of the layer input device buffer of ctx_other. -// All entries of the batch must be of this kind. Positions are set with llama_batch_ext_set_pos(), n_pos_per_embd of them. -// Returns the batch index (>= 0), or the llama_batch_ext_add() error codes. -LLAMA_API int32_t llama_batch_ext_add_embd_row(struct llama_batch_ext * batch, llama_seq_id seq_id, int32_t row); - -LLAMA_API llama_context * llama_get_ctx_other(struct llama_context * ctx); - -// Write the unmasked h_nextn rows (see llama_set_embeddings_nextn) of each decode to a device buffer -// [n_embd_out, n_batch + n_seq_max] instead of host memory: row r < n_batch is the token at batch index r of the last decode, -// row n_batch + s is free for the caller, e.g. for seq s (see llama_set_embeddings_nextn_rows()). -// Returns false if the buffer cannot be used, the rows are then extracted to host memory. -LLAMA_API bool llama_set_embeddings_nextn_dev(struct llama_context * ctx, bool value); - -// Copy rows of the h_nextn device buffer to or from host memory, ordered after the last decode and its readers -LLAMA_API bool llama_get_embeddings_nextn_rows(struct llama_context * ctx, int64_t row0, int64_t n_rows, float * out); -LLAMA_API bool llama_set_embeddings_nextn_rows(struct llama_context * ctx, int64_t row0, int64_t n_rows, const float * data); - -// Read the state rows of batches (see llama_batch_ext_set_embd_state_row()) from the h_nextn device buffer of src. -// Returns whether decode accepts batches with state rows. -LLAMA_API bool llama_set_embd_state_src(struct llama_context * ctx, struct llama_context * src); - -// The state of entry idx is row `row` of the h_nextn device buffer of the context set with llama_set_embd_state_src(). -// All entries of a batch have a state row, or none. -LLAMA_API bool llama_batch_ext_set_embd_state_row(struct llama_batch_ext * batch, int32_t idx, int32_t row); - // // model/context data extraction // -LLAMA_API int32_t llama_model_dflash_selector_top_k(const struct llama_model * model); - -// returns pointer to the target-model layer indices -LLAMA_API const int32_t * llama_model_target_layer_ids (const struct llama_model * model); -// returns the number of extracted layers from target model -LLAMA_API uint32_t llama_model_target_layer_ids_n(const struct llama_model * model); - // retrieves the whole token embedding matrix in F32 format (n_embd * n_vocab) // returns total number of elements or 0 on error // if out is nullptr, returns the number of tokens without writing to out diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 415b76a51451..0a0609739ab8 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1420,6 +1420,10 @@ int64_t llm_graph_result::get_max_nodes() const { return max_nodes; } +void llm_graph_result::set_max_nodes(int64_t max_nodes) { + this->max_nodes = max_nodes; +} + void llm_graph_result::reset() { t_inp_tokens = nullptr; t_inp_embd = nullptr; @@ -1443,11 +1447,16 @@ void llm_graph_result::reset() { fused_nodes.clear(); hdmd_inputs.clear(); - buf_compute_meta.resize(ggml_tensor_overhead()*max_nodes + ggml_graph_overhead_custom(max_nodes, false)); + const size_t meta_size = ggml_tensor_overhead()*max_nodes + ggml_graph_overhead_custom(max_nodes, false); + if (meta_size != buf_compute_meta_size) { + // not make_unique: it would zero the whole reserve and make its pages resident + buf_compute_meta.reset(new uint8_t[meta_size]); + buf_compute_meta_size = meta_size; + } ggml_init_params params = { - /*.mem_size =*/ buf_compute_meta.size(), - /*.mem_buffer =*/ buf_compute_meta.data(), + /*.mem_size =*/ buf_compute_meta_size, + /*.mem_buffer =*/ buf_compute_meta.get(), /*.no_alloc =*/ true, }; @@ -1567,7 +1576,7 @@ llm_graph_context::llm_graph_context(const llm_graph_params & params) : n_embd_head_v (hparams.n_embd_head_v()), n_embd_v_gqa (hparams.n_embd_v_gqa()), n_expert (hparams.n_expert), - n_expert_used (cparams.warmup ? hparams.n_expert : hparams.n_expert_used()), + n_expert_used (hparams.n_expert_used()), freq_base (cparams.rope_freq_base), freq_scale (cparams.rope_freq_scale), ext_factor (cparams.yarn_ext_factor), @@ -2685,7 +2694,16 @@ llm_graph_moe_cache_slots llm_graph_context::build_moe_cache_slots( return { nullptr, nullptr }; } for (ggml_tensor * w : { up_exps, gate_exps, down_exps, gate_up_exps }) { - if (w != nullptr && moe_cache->get_experts(w) == nullptr) { + if (w == nullptr) { + continue; + } + ggml_tensor * experts = moe_cache->get_experts(w); + if (experts == nullptr) { + return { nullptr, nullptr }; + } + // the device of the cache must compute the matmul, else the scheduler copies the cache to another backend + ggml_tensor * b = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, experts->ne[0], w == down_exps ? selected_experts->ne[0] : 1, selected_experts->ne[1]); + if (!ggml_backend_supports_op(moe_cache->backend(il), ggml_mul_mat_id(ctx0, experts, b, selected_experts))) { return { nullptr, nullptr }; } } diff --git a/src/llama-graph.h b/src/llama-graph.h index 8a5381073288..4acbc11ffa8e 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -49,8 +49,6 @@ enum llm_graph_type { enum llm_fused_op { LLM_FUSED_OP_FLASH_ATTN, LLM_FUSED_OP_FLASH_ATTN_KV_ROWS, - LLM_FUSED_OP_GDN_AR, - LLM_FUSED_OP_GDN_CH, LLM_FUSED_OP_LIGHTNING_INDEXER, LLM_FUSED_OP_DSV4_HC_PRE, LLM_FUSED_OP_DSV4_HC_COMB, @@ -952,6 +950,8 @@ class llm_graph_result { int64_t get_max_nodes() const; + void set_max_nodes(int64_t max_nodes); + void reset(); void set_inputs(const llama_ubatch * ubatch); @@ -1001,13 +1001,14 @@ class llm_graph_result { ggml_context_ptr ctx_compute; // memory buffers used to evaluate the model - std::vector buf_compute_meta; + std::unique_ptr buf_compute_meta; + size_t buf_compute_meta_size = 0; ggml_cgraph * gf; +private: int64_t max_nodes; -private: // keep a copy of the previous graph parameters // we will use this to determine whether the graph can be reused by comparing them with the new parameters // note: these are updated after constructing the new graph @@ -1276,7 +1277,7 @@ struct llm_graph_context { // tok_scale: applied to token rows only ggml_tensor * build_inp_embd(ggml_tensor * tok_embd, float tok_scale = 1.0f) const; - // the state input of an MTP graph: rows of the h_nextn device buffer of ctx_state_src (see llama_set_embd_state_src()), + // the state input of an MTP graph: rows of the h_nextn device buffer of ctx_state_src (see llama_set_ctx_state_src()), // or uploaded from ubatch.embd_state ggml_tensor * build_inp_embd_state(llm_graph_input_embd_h * inp, int64_t n_embd_state) const; diff --git a/src/llama-model.cpp b/src/llama-model.cpp index cd49ccdd0a86..7c75ab55ef30 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -424,6 +424,7 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str static const std::regex pattern_kv_weight ("blk\\.\\d*\\.attn_(k|v).weight"); static const std::regex pattern_v_exps_weight ("blk\\.\\d*\\.attn_v_exps.weight"); // K2 Horizon MoVA static const std::regex pattern_qkv_weight ("blk\\.\\d*\\.attn_qkv.weight"); + static const std::regex pattern_qkv_gate_weight ("blk\\.\\d*\\.attn_qkv_gate.weight"); static const std::regex pattern_q_bias ("blk\\.\\d*\\.attn_q\\.bias"); static const std::regex pattern_kv_bias ("blk\\.\\d*\\.attn_(k|v)\\.bias"); static const std::regex pattern_qkv_bias ("blk\\.\\d*\\.attn_qkv.bias"); @@ -446,6 +447,7 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str static const std::regex pattern_ssm_alpha ("blk\\.\\d*\\.ssm_alpha.weight"); static const std::regex pattern_ssm_beta ("blk\\.\\d*\\.ssm_beta.weight"); static const std::regex pattern_ssm_beta_alpha ("blk\\.\\d*\\.ssm_ba.weight"); + static const std::regex pattern_ssm_beta_alpha_cat("blk\\.\\d*\\.ssm_beta_alpha.weight"); static const std::regex pattern_r_cache ("cache_r_l\\d*"); static const std::regex pattern_ple_r_cache ("cache_ple_r_l\\d*"); static const std::regex pattern_s_cache ("cache_s_l\\d*"); @@ -593,7 +595,7 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str if (std::regex_match(tensor_name, pattern_q_bias) || std::regex_match(tensor_name, pattern_kv_bias)) { return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_0, "attn_output.weight", "ssm_out.weight"); } - if (std::regex_match(tensor_name, pattern_qkv_weight)) { + if (std::regex_match(tensor_name, pattern_qkv_weight) || std::regex_match(tensor_name, pattern_qkv_gate_weight)) { return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_1, "attn_output.weight", "ssm_out.weight"); } if ( std::regex_match(tensor_name, pattern_qkv_bias)) { @@ -620,7 +622,7 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_0, "ssm_out.weight"); } if (std::regex_match(tensor_name, pattern_ssm_alpha) || std::regex_match(tensor_name, pattern_ssm_beta) || - std::regex_match(tensor_name, pattern_ssm_beta_alpha)) { + std::regex_match(tensor_name, pattern_ssm_beta_alpha) || std::regex_match(tensor_name, pattern_ssm_beta_alpha_cat)) { return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_1, "ssm_out.weight"); } if (std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache)) { @@ -715,6 +717,14 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str } } else { const int64_t head_ratio = n_v_heads / n_k_heads; + if (std::regex_match(tensor_name, pattern_qkv_gate_weight)) { + GGML_ASSERT(tensor->ne[axis] == 2*key_dim + 2*value_dim); + return {{key_dim, 2 + 2*head_ratio}}; + } + if (std::regex_match(tensor_name, pattern_ssm_beta_alpha_cat)) { + GGML_ASSERT(tensor->ne[axis] == 2*n_v_heads); + return {{n_k_heads, 2*head_ratio}}; + } if (std::regex_match(tensor_name, pattern_qkv_weight) || std::regex_match(tensor_name, pattern_ssm_conv1d)) { GGML_ASSERT(tensor->ne[axis] == 2*key_dim + value_dim); return {{key_dim, 2 + head_ratio}}; @@ -811,11 +821,13 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str const int64_t blck_size_perf = std::lcm(blck_size, 128); const int64_t granularity_qkv = std::lcm(blck_size_perf, head_dim); if (std::regex_match(tensor_name, pattern_qkv_weight) || std::regex_match(tensor_name, pattern_attn_gate_weight) || - std::regex_match(tensor_name, pattern_ssm_conv1d) || std::regex_match(tensor_name, pattern_ssm_out_weight)) { + std::regex_match(tensor_name, pattern_ssm_conv1d) || std::regex_match(tensor_name, pattern_ssm_out_weight) || + std::regex_match(tensor_name, pattern_qkv_gate_weight)) { return std::vector(segments.size(), granularity_qkv); } if (std::regex_match(tensor_name, pattern_ssm_dt) || std::regex_match(tensor_name, pattern_ssm_a) || - std::regex_match(tensor_name, pattern_ssm_alpha) || std::regex_match(tensor_name, pattern_ssm_beta)) { + std::regex_match(tensor_name, pattern_ssm_alpha) || std::regex_match(tensor_name, pattern_ssm_beta) || + std::regex_match(tensor_name, pattern_ssm_beta_alpha_cat)) { return std::vector(segments.size(), granularity_qkv / head_dim); } if (std::regex_match(tensor_name, pattern_ssm_beta_alpha)) { @@ -3566,10 +3578,6 @@ const llama_vocab * llama_model_get_vocab(const llama_model * model) { return &model->vocab; } -void llama_free_model(llama_model * model) { - llama_model_free(model); -} - void llama_model_free(llama_model * model) { delete model; } @@ -3640,26 +3648,6 @@ const char * llama_model_decision_label(const struct llama_model * model, uint32 return nullptr; } -// deprecated -int32_t llama_n_ctx_train(const llama_model * model) { - return llama_model_n_ctx_train(model); -} - -// deprecated -int32_t llama_n_embd(const llama_model * model) { - return llama_model_n_embd(model); -} - -// deprecated -int32_t llama_n_layer(const llama_model * model) { - return llama_model_n_layer(model); -} - -// deprecated -int32_t llama_n_head(const llama_model * model) { - return llama_model_n_head(model); -} - llama_rope_type llama_model_rope_type(const llama_model * model) { switch (model->arch) { // these models do not use RoPE diff --git a/src/llama-sampler.cpp b/src/llama-sampler.cpp index c7b395bbc763..24c0316a2965 100644 --- a/src/llama-sampler.cpp +++ b/src/llama-sampler.cpp @@ -2697,8 +2697,6 @@ static struct llama_sampler * llama_sampler_init_grammar_impl( const char * grammar_str, const char * grammar_root, bool lazy, - const char ** trigger_words, - size_t num_trigger_words, const llama_token * trigger_tokens, size_t num_trigger_tokens, const char ** trigger_patterns, @@ -2727,7 +2725,7 @@ static void llama_sampler_grammar_reset(struct llama_sampler * smpl) { static struct llama_sampler * llama_sampler_grammar_clone(const struct llama_sampler * smpl) { const auto * ctx = (const llama_sampler_grammar *) smpl->ctx; - auto * result = llama_sampler_init_grammar_impl(ctx->vocab, nullptr, nullptr, false, nullptr, 0, nullptr, 0, nullptr, 0); + auto * result = llama_sampler_init_grammar_impl(ctx->vocab, nullptr, nullptr, false, nullptr, 0, nullptr, 0); GGML_ASSERT(result); // copy the state @@ -2775,8 +2773,6 @@ static struct llama_sampler * llama_sampler_init_grammar_impl( const char * grammar_str, const char * grammar_root, bool lazy, - const char ** trigger_words, - size_t num_trigger_words, const llama_token * trigger_tokens, size_t num_trigger_tokens, const char ** trigger_patterns, @@ -2784,26 +2780,7 @@ static struct llama_sampler * llama_sampler_init_grammar_impl( auto * ctx = new llama_sampler_grammar; if (grammar_str != nullptr && grammar_str[0] != '\0') { - std::string trigger_pattern; - llama_grammar * grammar = nullptr; - // TODO: remove trigger_words support. - if (trigger_words != nullptr && num_trigger_words > 0) { - GGML_ASSERT(trigger_patterns == nullptr && num_trigger_patterns == 0); - trigger_pattern = "[\\s\\S]*?("; - for (size_t i = 0; i < num_trigger_words; ++i) { - static const std::regex special_chars("[.^$|()*+?\\[\\]{}\\\\]"); - if (i > 0) { - trigger_pattern += "|"; - } - trigger_pattern += std::regex_replace(trigger_words[i], special_chars, "\\$0"); - } - trigger_pattern += ")[\\s\\S]*"; - - std::array tmp_trigger_patterns = { trigger_pattern.c_str() }; - grammar = llama_grammar_init_impl(vocab, grammar_str, grammar_root, lazy, tmp_trigger_patterns.data(), tmp_trigger_patterns.size(), trigger_tokens, num_trigger_tokens); - } else { - grammar = llama_grammar_init_impl(vocab, grammar_str, grammar_root, lazy, trigger_patterns, num_trigger_patterns, trigger_tokens, num_trigger_tokens); - } + llama_grammar * grammar = llama_grammar_init_impl(vocab, grammar_str, grammar_root, lazy, trigger_patterns, num_trigger_patterns, trigger_tokens, num_trigger_tokens); *ctx = { /* .vocab = */ vocab, /* .grammar_str = */ grammar_str, @@ -2833,18 +2810,7 @@ struct llama_sampler * llama_sampler_init_grammar( const struct llama_vocab * vocab, const char * grammar_str, const char * grammar_root) { - return llama_sampler_init_grammar_impl(vocab, grammar_str, grammar_root, /* lazy= */ false, nullptr, 0, nullptr, 0, nullptr, 0); -} - -struct llama_sampler * llama_sampler_init_grammar_lazy( - const struct llama_vocab * vocab, - const char * grammar_str, - const char * grammar_root, - const char ** trigger_words, - size_t num_trigger_words, - const llama_token * trigger_tokens, - size_t num_trigger_tokens) { - return llama_sampler_init_grammar_impl(vocab, grammar_str, grammar_root, /* lazy= */ true, trigger_words, num_trigger_words, trigger_tokens, num_trigger_tokens, nullptr, 0); + return llama_sampler_init_grammar_impl(vocab, grammar_str, grammar_root, /* lazy= */ false, nullptr, 0, nullptr, 0); } struct llama_sampler * llama_sampler_init_grammar_lazy_patterns( @@ -2855,7 +2821,7 @@ struct llama_sampler * llama_sampler_init_grammar_lazy_patterns( size_t num_trigger_patterns, const llama_token * trigger_tokens, size_t num_trigger_tokens) { - return llama_sampler_init_grammar_impl(vocab, grammar_str, grammar_root, /* lazy= */ true, nullptr, 0, trigger_tokens, num_trigger_tokens, trigger_patterns, num_trigger_patterns); + return llama_sampler_init_grammar_impl(vocab, grammar_str, grammar_root, /* lazy= */ true, trigger_tokens, num_trigger_tokens, trigger_patterns, num_trigger_patterns); } // penalties diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp index 229a051e0676..e90f1bd117d4 100644 --- a/src/llama-vocab.cpp +++ b/src/llama-vocab.cpp @@ -4720,11 +4720,6 @@ int32_t llama_vocab_n_tokens(const struct llama_vocab * vocab) { return vocab->n_tokens(); } -// deprecated -int32_t llama_n_vocab(const struct llama_vocab * vocab) { - return llama_vocab_n_tokens(vocab); -} - enum llama_vocab_type llama_vocab_type(const struct llama_vocab * vocab) { return vocab->get_type(); } @@ -4761,11 +4756,6 @@ llama_token llama_vocab_eot(const struct llama_vocab * vocab) { return vocab->token_eot(); } -// deprecated -llama_token llama_vocab_cls(const struct llama_vocab * vocab) { - return vocab->token_bos(); -} - llama_token llama_vocab_sep(const struct llama_vocab * vocab) { return vocab->token_sep(); } @@ -4826,107 +4816,6 @@ llama_token llama_vocab_mask(const struct llama_vocab* vocab) { return vocab->token_mask(); } -// deprecated -const char * llama_token_get_text(const struct llama_vocab * vocab, llama_token token) { - return llama_vocab_get_text(vocab, token); -} - -// deprecated -float llama_token_get_score(const struct llama_vocab * vocab, llama_token token) { - return llama_vocab_get_score(vocab, token); -} - -// deprecated -enum llama_token_attr llama_token_get_attr(const struct llama_vocab * vocab, llama_token token) { - return llama_vocab_get_attr(vocab, token); -} - -// deprecated -bool llama_token_is_eog(const struct llama_vocab * vocab, llama_token token) { - return llama_vocab_is_eog(vocab, token); -} - -// deprecated -bool llama_token_is_control(const struct llama_vocab * vocab, llama_token token) { - return llama_vocab_is_control(vocab, token); -} - -// deprecated -llama_token llama_token_bos(const struct llama_vocab * vocab) { - return llama_vocab_bos(vocab); -} - -// deprecated -llama_token llama_token_eos(const struct llama_vocab * vocab) { - return llama_vocab_eos(vocab); -} - -// deprecated -llama_token llama_token_eot(const struct llama_vocab * vocab) { - return llama_vocab_eot(vocab); -} - -// deprecated -llama_token llama_token_cls(const struct llama_vocab * vocab) { - //return llama_vocab_cls(vocab); - return llama_vocab_bos(vocab); // avoid deprecation warning -} - -// deprecated -llama_token llama_token_sep(const struct llama_vocab * vocab) { - return llama_vocab_sep(vocab); -} - -// deprecated -llama_token llama_token_nl (const struct llama_vocab * vocab) { - return llama_vocab_nl(vocab); -} - -// deprecated -llama_token llama_token_pad(const struct llama_vocab * vocab) { - return llama_vocab_pad(vocab); -} - -// deprecated -bool llama_add_bos_token(const struct llama_vocab * vocab) { - return llama_vocab_get_add_bos(vocab); -} - -// deprecated -bool llama_add_eos_token(const struct llama_vocab * vocab) { - return llama_vocab_get_add_eos(vocab); -} - -// deprecated -llama_token llama_token_fim_pre(const struct llama_vocab * vocab) { - return llama_vocab_fim_pre(vocab); -} - -// deprecated -llama_token llama_token_fim_suf(const struct llama_vocab * vocab) { - return llama_vocab_fim_suf(vocab); -} - -// deprecated -llama_token llama_token_fim_mid(const struct llama_vocab * vocab) { - return llama_vocab_fim_mid(vocab); -} - -// deprecated -llama_token llama_token_fim_pad(const struct llama_vocab * vocab) { - return llama_vocab_fim_pad(vocab); -} - -// deprecated -llama_token llama_token_fim_rep(const struct llama_vocab * vocab) { - return llama_vocab_fim_rep(vocab); -} - -// deprecated -llama_token llama_token_fim_sep(const struct llama_vocab * vocab) { - return llama_vocab_fim_sep(vocab); -} - // // tokenization // diff --git a/src/llama.cpp b/src/llama.cpp index e3699ea1d534..cee6a7dc4428 100644 --- a/src/llama.cpp +++ b/src/llama.cpp @@ -455,12 +455,6 @@ struct llama_model * llama_model_init_from_user( params.use_extra_bufts = false; return llama_model_load_from_file_impl(metadata, set_tensor_data, set_tensor_data_ud, path_model, splits, /*file*/ nullptr, params); } -// deprecated -struct llama_model * llama_load_model_from_file( - const char * path_model, - struct llama_model_params params) { - return llama_model_load_from_file(path_model, params); -} struct llama_model * llama_model_load_from_file( const char * path_model, diff --git a/src/models/clef.cpp b/src/models/clef.cpp index 3ac5782a8e8b..86fed4e874a8 100644 --- a/src/models/clef.cpp +++ b/src/models/clef.cpp @@ -457,16 +457,9 @@ ggml_tensor * llama_model_clef::graph::build_layer_attn_linear( q_conv = build_gdn_l2_norm(ctx0, q_conv, hparams.f_norm_rms_eps); k_conv = build_gdn_l2_norm(ctx0, k_conv, hparams.f_norm_rms_eps); - // note: need explicit repeat only if we are not using the fused GDN - if (num_k_heads != num_v_heads && (!cparams.fused_gdn_ar || !cparams.fused_gdn_ch)) { - GGML_ASSERT(num_v_heads % num_k_heads == 0); - q_conv = ggml_repeat_4d(ctx0, q_conv, head_k_dim, num_v_heads, n_tokens, n_seqs); - k_conv = ggml_repeat_4d(ctx0, k_conv, head_k_dim, num_v_heads, n_tokens, n_seqs); - } - ggml_tensor * state = ggml_fill(ctx0, ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, head_v_dim, head_v_dim, num_v_heads, n_seqs), 0.0f); - ggml_tensor * output = build_delta_net(q_conv, k_conv, v_conv, gate, beta, state, il).first; + ggml_tensor * output = build_delta_net(q_conv, k_conv, v_conv, gate, beta, state).first; cb(output, "attn_output", il); // gated normalization diff --git a/src/models/clover-moe.cpp b/src/models/clover-moe.cpp index cab34cb487a7..e51242616fe8 100644 --- a/src/models/clover-moe.cpp +++ b/src/models/clover-moe.cpp @@ -329,10 +329,8 @@ ggml_tensor * llama_model_clover_moe::graph::build_layer_attn_linear( ggml_tensor * conv_input = build_conv_state(inp, conv_states_all, qkv_mixed, conv_kernel_size, conv_channels, il); - // the chunked path without the fused kernel reads the state after the new state is stored - ggml_tensor * state = (ubatch.n_seq_tokens == 1 || cparams.fused_gdn_ch) ? - build_rs_in_place(inp, ssm_states_all, hparams.n_embd_s(), n_seqs) : - build_rs(inp, ssm_states_all, hparams.n_embd_s(), n_seqs); + // the delta net is always the fused kernel, which reads the state before it stores the new one + ggml_tensor * state = build_rs_in_place(inp, ssm_states_all, hparams.n_embd_s(), n_seqs); state = ggml_reshape_4d(ctx0, state, head_v_dim, head_v_dim, num_v_heads, n_seqs); cb(state, "state_predelta", il); @@ -357,11 +355,6 @@ ggml_tensor * llama_model_clover_moe::graph::build_layer_attn_linear( auto [q_conv, k_conv] = build_gdn_l2_norm_qk(ctx0, conv_qkv_mix, head_k_dim, num_k_heads, n_seq_tokens, n_seqs, 1e-6f); - if (num_k_heads != num_v_heads && (!cparams.fused_gdn_ar || !cparams.fused_gdn_ch)) { - q_conv = ggml_repeat_4d(ctx0, q_conv, head_k_dim, num_v_heads, n_seq_tokens, n_seqs); - k_conv = ggml_repeat_4d(ctx0, k_conv, head_k_dim, num_v_heads, n_seq_tokens, n_seqs); - } - ggml_tensor * output = build_recurrent_attn(inp, ssm_states_all, q_conv, k_conv, v_conv, gate, beta, state, il); ggml_tensor * z_2d = ggml_reshape_4d(ctx0, z, head_v_dim, num_v_heads, n_seq_tokens, n_seqs); diff --git a/src/models/delta-net-base.cpp b/src/models/delta-net-base.cpp index 423f047a79f0..368bb954a9f9 100644 --- a/src/models/delta-net-base.cpp +++ b/src/models/delta-net-base.cpp @@ -3,378 +3,15 @@ #include "llama-impl.h" #include "llama-memory-recurrent.h" -// utility to get one slice from the third dimension -// input dim: [x, y, c, b] -// output dim: [x, y, 1, b] -static ggml_tensor * get_slice_2d(ggml_context * ctx0, ggml_tensor * t, int64_t c) { - return ggml_view_4d(ctx0, t, t->ne[0], t->ne[1], 1, t->ne[3], - t->nb[1], t->nb[2], t->nb[3], t->nb[2] * c); -} - llm_build_delta_net_base::llm_build_delta_net_base(const llm_graph_params & params) : llm_graph_context(params) {} -std::pair llm_build_delta_net_base::build_delta_net_chunking( - ggml_tensor * q, - ggml_tensor * k, - ggml_tensor * v, - ggml_tensor * g, - ggml_tensor * b, - ggml_tensor * s, - int il) { - const int64_t S_k = q->ne[0]; - const int64_t H_k = q->ne[1]; - const int64_t n_tokens = q->ne[2]; - const int64_t n_seqs = q->ne[3]; - - const int64_t S_v = v->ne[0]; - const int64_t H_v = v->ne[1]; - const bool kda = (g->ne[0] == S_k && g->ne[1] == H_k); - - GGML_ASSERT(S_k == S_v); - GGML_ASSERT(H_v % H_k == 0); - - GGML_ASSERT(q->ne[0] == S_k && q->ne[1] == H_k && q->ne[2] == n_tokens && q->ne[3] == n_seqs); - GGML_ASSERT(k->ne[0] == S_k && k->ne[1] == H_k && k->ne[2] == n_tokens && k->ne[3] == n_seqs); - GGML_ASSERT(v->ne[0] == S_v && v->ne[1] == H_v && v->ne[2] == n_tokens && v->ne[3] == n_seqs); - - GGML_ASSERT(g->ne[0] == 1 || g->ne[0] == S_v); - GGML_ASSERT( g->ne[1] == H_v && g->ne[2] == n_tokens && g->ne[3] == n_seqs); - GGML_ASSERT(b->ne[0] == 1 && b->ne[1] == H_v && b->ne[2] == n_tokens && b->ne[3] == n_seqs); - GGML_ASSERT(s->ne[0] == S_v && s->ne[1] == S_v && s->ne[2] == H_v && s->ne[3] == n_seqs); - - const float scale = 1.0f / sqrtf(S_k); - - q = ggml_scale(ctx0, q, scale); - - cb(q, "q_in", il); - cb(k, "k_in", il); - cb(v, "v_in", il); - cb(b, "b_in", il); - cb(g, "g_in", il); - - q = ggml_permute(ctx0, q, 0, 2, 1, 3); // [S_k, n_tokens, H_k, n_seqs] - k = ggml_permute(ctx0, k, 0, 2, 1, 3); // [S_k, n_tokens, H_k, n_seqs] - v = ggml_permute(ctx0, v, 0, 2, 1, 3); // [S_v, n_tokens, H_v, n_seqs] - g = ggml_permute(ctx0, g, 0, 2, 1, 3); // [g_0, n_tokens, H_v, n_seqs] - b = ggml_permute(ctx0, b, 0, 2, 1, 3); // [ 1, n_tokens, H_v, n_seqs] - - const int CS = kda ? 16 : 64; // chunk size - - const int pad = (CS - n_tokens % CS) % CS; - const int n_chunks = (n_tokens + pad) / CS; - - q = ggml_pad(ctx0, q, 0, pad, 0, 0); - k = ggml_pad(ctx0, k, 0, pad, 0, 0); - v = ggml_pad(ctx0, v, 0, pad, 0, 0); - g = ggml_pad(ctx0, g, 0, pad, 0, 0); - b = ggml_pad(ctx0, b, 0, pad, 0, 0); - - ggml_tensor * v_b = ggml_mul(ctx0, v, b); - ggml_tensor * k_b = ggml_mul(ctx0, k, b); - - cb(v_b, "v_b", il); - cb(k_b, "k_b", il); - - q = ggml_reshape_4d(ctx0, q, S_k, CS, n_chunks, H_k * n_seqs); - k = ggml_reshape_4d(ctx0, k, S_k, CS, n_chunks, H_k * n_seqs); - k_b = ggml_reshape_4d(ctx0, k_b, S_k, CS, n_chunks, H_v * n_seqs); - v = ggml_reshape_4d(ctx0, v, S_v, CS, n_chunks, H_v * n_seqs); - v_b = ggml_reshape_4d(ctx0, v_b, S_v, CS, n_chunks, H_v * n_seqs); - - g = ggml_reshape_4d(ctx0, g, g->ne[0], CS, n_chunks, H_v * n_seqs); - b = ggml_reshape_4d(ctx0, b, 1, CS, n_chunks, H_v * n_seqs); - - // [CS, g_0, n_chunks, H_v * n_seqs] - // TODO: extend ggml_cumsum with axis parameter to avoid transpose - ggml_tensor * g_cs = ggml_cumsum(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, g))); - cb(g_cs, "g_cs", il); - - ggml_tensor * kb = nullptr; - ggml_tensor * kq = nullptr; - if (kda) { - const int64_t CHB = n_chunks * H_k * n_seqs; - - ggml_tensor * g_cs_i = ggml_reshape_4d(ctx0, g_cs, CS, 1, S_k, CHB); // [chunk_size, 1, S_k, CHB] - ggml_tensor * g_cs_j = ggml_reshape_4d(ctx0, g_cs, 1, CS, S_k, CHB); // [1, chunk_size, S_k, CHB] - - g_cs_j = ggml_repeat_4d(ctx0, g_cs_j, CS, CS, S_k, CHB); // [1, chunk_size, S_k, CHB] -> [chunk_size, chunk_size, S_k, CHB] - - // decay_mask [chunk_size,chunk_size,S_k,CHB] - ggml_tensor * decay_mask; - decay_mask = ggml_sub(ctx0, g_cs_j, g_cs_i); - decay_mask = ggml_tri(ctx0, decay_mask, GGML_TRI_TYPE_LOWER_DIAG); - decay_mask = ggml_exp(ctx0, decay_mask); - cb(decay_mask, "decay_mask", il); - - // decay_mask [S_k,BT_j,BT_i,CHB] *Note* second and third chunk_sizes are switched - decay_mask = ggml_cont_4d(ctx0, ggml_permute(ctx0, decay_mask, 2, 1, 0, 3), S_k, CS, CS, CHB); - - ggml_tensor * k_b_i = ggml_reshape_4d(ctx0, k_b, S_k, CS, 1, CHB); - ggml_tensor * k_j = ggml_reshape_4d(ctx0, k, S_k, 1, CS, CHB); - ggml_tensor * q_i = ggml_reshape_4d(ctx0, q, S_k, CS, 1, CHB); - - ggml_tensor * decay_k_b_i = ggml_mul(ctx0, decay_mask, k_b_i); - ggml_tensor * decay_q_i = ggml_mul(ctx0, decay_mask, q_i); - - // decay_k_b_i [S,BT,BT,CHB] @ k_j [S,1,BT,CHB] = Akk [BT,1,BT,CHB] - kb = ggml_mul_mat(ctx0, decay_k_b_i, k_j); - kq = ggml_mul_mat(ctx0, decay_q_i, k_j); - - kb = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_4d(ctx0, kb, CS, CS, n_chunks, H_v * n_seqs))); - kq = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_4d(ctx0, kq, CS, CS, n_chunks, H_v * n_seqs))); - } else { - ggml_tensor * g_cs_i = g_cs; - ggml_tensor * g_cs_j = ggml_reshape_4d(ctx0, g_cs, 1, CS, n_chunks, H_v * n_seqs); - - g_cs_j = ggml_repeat_4d(ctx0, g_cs_j, CS, CS, n_chunks, H_v * n_seqs); - - // [CS, CS, n_chunks, H_v * n_seqs] - ggml_tensor * decay_mask; - decay_mask = ggml_sub(ctx0, g_cs_j, g_cs_i); - decay_mask = ggml_tri(ctx0, decay_mask, GGML_TRI_TYPE_LOWER_DIAG); - decay_mask = ggml_exp(ctx0, decay_mask); - cb(decay_mask, "decay_mask", il); - - // [CS, CS, n_chunks, H_k * n_seqs] - kb = ggml_mul_mat(ctx0, k, k_b); - kb = ggml_mul (ctx0, kb, decay_mask); - - // [CS, CS, n_chunks, H_k * n_seqs] - kq = ggml_mul_mat(ctx0, k, q); - kq = ggml_mul(ctx0, kq, decay_mask); - } - - kq = ggml_tri(ctx0, kq, GGML_TRI_TYPE_LOWER_DIAG); - cb(kq, "kq", il); - - // [CS, CS, n_chunks, H_k * n_seqs] - ggml_tensor * attn; - attn = ggml_tri(ctx0, kb, GGML_TRI_TYPE_LOWER); - cb(attn, "attn", il); - - ggml_tensor * identity; - identity = ggml_view_1d(ctx0, attn, CS, 0); - identity = ggml_fill (ctx0, identity, 1.0f); - identity = ggml_diag (ctx0, identity); - - ggml_tensor * lhs = ggml_add(ctx0, attn, identity); - cb(lhs, "dnet_add_ch_lhs", il); - - attn = ggml_neg(ctx0, attn); - cb(attn, "attn_pre_solve", il); - - ggml_tensor * lin_solve = ggml_solve_tri(ctx0, lhs, attn, true, true, false); - attn = ggml_add(ctx0, lin_solve, identity); - cb(attn, "dnet_add_ch_attn_solved", il); // [CS, CS, n_chunks, H_k * n_seqs] - - // [S_v, CS, n_chunks, H_v * n_seqs] - v = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, v_b)), attn); - - // [CS, 1, n_chunks, H_v * n_seqs] KDA: [CS, S_k, n_chunks, H_v * n_seqs] - ggml_tensor * g_exp = ggml_exp(ctx0, g_cs); - - k_b = ggml_cont(ctx0, ggml_transpose(ctx0, k_b)); - - // [CS, S_k, n_chunks, H_k * n_seqs] - ggml_tensor * kbg = ggml_mul(ctx0, k_b, g_exp); - cb(kbg, "k_beta_g_exp", il); - - // [S_k, CS, n_chunks, H_k * n_seqs] - ggml_tensor * k_cd = ggml_mul_mat(ctx0, kbg, attn); - cb(k_cd, "k_cumdecay", il); - - // [1, CS, n_chunks, H_k * n_seqs] KDA: [S_k, CS, n_chunks, H_k * n_seqs] - ggml_tensor * g_exp_t = ggml_cont(ctx0, ggml_transpose(ctx0, g_exp)); - ggml_tensor * q_g_exp = ggml_mul(ctx0, q, g_exp_t); - - // vectorized calculation of key_gdiff - // improved from the chunked version: - // g_last = torch.clamp(g_cum[:, :, -1], max=50.0).exp().unsqueeze(-1).unsqueeze(-1) - // g_diff = torch.clamp(g_cum[:, :, -1:] - g_cum, max=50.0).exp() - // key_gdiff = key * g_diff.unsqueeze(-1) - // kgdmulvnew = (key_gdiff).transpose(-1, -2) @ v_new - // last_recurrent_state = last_recurrent_state * g_last + kgdmulvnew - - // get last element in g_cumsum along CS dimension (ne0) - // example: [[x, y, z, ..., last], ...] -> [[last], ...] - // [1, 1, n_chunks, H_v * n_seqs] KDA: [1, S_k, n_chunks, H_v * n_seqs] - ggml_tensor * g_last = ggml_view_4d(ctx0, g_cs, 1, g_cs->ne[1], g_cs->ne[2], g_cs->ne[3], - g_cs->nb[1], - g_cs->nb[2], - g_cs->nb[3], - ggml_row_size(g_cs->type, g_cs->ne[0] - 1)); - cb(g_last, "g_last", il); - - // [1, 1, n_chunks, H_v * n_seqs] KDA: [S_k, 1, n_chunks, H_v * n_seqs] - ggml_tensor * g_last_exp_t = ggml_transpose(ctx0, ggml_exp(ctx0, g_last)); - cb(g_last_exp_t, "g_last_exp_t", il); - - // [CS, 1, n_chunks, H_v * n_seqs] KDA: [CS, S_k, n_chunks, H_v * n_seqs] - ggml_tensor * g_diff = ggml_neg(ctx0, ggml_sub(ctx0, g_cs, g_last)); - cb(g_diff, "g_diff", il); - - ggml_tensor * g_diff_exp_t = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_exp(ctx0, g_diff))); - - // [S_k, CS, n_chunks, H_v * n_seqs] - ggml_tensor * kg = ggml_mul(ctx0, k, g_diff_exp_t); - cb(kg, "key_gdiff", il); - - // [CS, S_k, n_chunks, H_v * n_seqs] - ggml_tensor * kg_t = ggml_cont(ctx0, ggml_transpose(ctx0, kg)); - cb(kg_t, "key_gdiff_t", il); - - s = ggml_reshape_4d(ctx0, s, S_v, S_v, 1, H_v * n_seqs); - cb(s, "dnet_add_ch_state", il); - - // [CS, S_v, n_chunks, H_v * n_seqs] - ggml_tensor * v_t = ggml_cont(ctx0, ggml_transpose(ctx0, v)); - - for (int64_t chunk = 0; chunk < n_chunks; chunk++) { - ggml_tensor * ch_k_cd = get_slice_2d(ctx0, k_cd, chunk); // [S_k, CS, 1, H_k * n_seqs] - ggml_tensor * ch_v_t = get_slice_2d(ctx0, v_t, chunk); // [ CS, S_v, 1, H_v * n_seqs] - ggml_tensor * ch_kq = get_slice_2d(ctx0, kq, chunk); // [ CS, CS, 1, H_k * n_seqs] - ggml_tensor * ch_q_g_exp = get_slice_2d(ctx0, q_g_exp, chunk); // [S_k, CS, 1, H_k * n_seqs] - ggml_tensor * ch_kg_t = get_slice_2d(ctx0, kg_t, chunk); // [ CS, S_k, 1, H_v * n_seqs] - - // [CS, S_v, 1, H_v * n_seqs] - ggml_tensor * v_t_p = ggml_mul_mat(ctx0, ch_k_cd, s); - cb(v_t_p, "v_prime", il); - - // [CS, S_v, 1, H_v * n_seqs] - ggml_tensor * v_t_new = ggml_sub(ctx0, ch_v_t, v_t_p); - cb(v_t_new, "v_t_new", il); - - // [S_v, CS, 1, H_v * n_seqs] - ggml_tensor * v_attn = ggml_mul_mat(ctx0, v_t_new, ch_kq); - cb(v_attn, "v_attn", il); - - // [S_v, CS, 1, H_v * n_seqs] - ggml_tensor * attn_inter = ggml_mul_mat(ctx0, s, ch_q_g_exp); - cb(attn_inter, "attn_inter", il); - - // [S_v, CS, 1, H_v * n_seqs] - ggml_tensor * o_ch = ggml_add(ctx0, attn_inter, v_attn); - cb(o_ch, "dnet_add_ch_attn_out", il); - - v = ggml_set_inplace(ctx0, v, o_ch, v->nb[1], v->nb[2], v->nb[3], chunk * v->nb[2]); - - // kgdmulvnew = (key_gdiff).transpose(-1, -2) @ v_new - // TODO: head broadcast might not work here - probably will need a transpose - ggml_tensor * kgv = ggml_mul_mat(ctx0, ch_kg_t, v_t_new); // [S_k, S_v, 1, H_k * n_seqs] - - // last_recurrent_state = last_recurrent_state * g_last + kgdmulvnew - ggml_tensor * ch_g_last_exp_t = get_slice_2d(ctx0, g_last_exp_t, chunk); - - s = ggml_mul(ctx0, s, ch_g_last_exp_t); - s = ggml_add(ctx0, s, kgv); - cb(s, "dnet_add_ch_state", il); - } - - // truncate padded tokens - ggml_tensor * o = ggml_view_4d(ctx0, v, - S_v, n_tokens, H_v, n_seqs, - ggml_row_size(v->type, S_v), - ggml_row_size(v->type, S_v * CS * n_chunks), - ggml_row_size(v->type, S_v * CS * n_chunks * H_v), 0); - o = ggml_permute (ctx0, o, 0, 2, 1, 3); // [S_v, H_v, n_tokens, n_seqs] - s = ggml_reshape_4d(ctx0, s, S_v, S_v, H_v, n_seqs); - cb(s, "output_state", il); - - return {o, s}; -} - -std::pair llm_build_delta_net_base::build_delta_net_autoregressive( - ggml_tensor * q, - ggml_tensor * k, - ggml_tensor * v, - ggml_tensor * g, - ggml_tensor * b, // beta - ggml_tensor * s, // state - int il) { - const int64_t S_k = q->ne[0]; - const int64_t H_k = q->ne[1]; - const int64_t n_tokens = q->ne[2]; - const int64_t n_seqs = q->ne[3]; - - const int64_t S_v = v->ne[0]; - const int64_t H_v = v->ne[1]; - - GGML_ASSERT(n_tokens == 1); - - GGML_ASSERT(S_k == S_v); - GGML_ASSERT(H_v % H_k == 0); - - GGML_ASSERT(q->ne[0] == S_k && q->ne[1] == H_k && q->ne[2] == n_tokens && q->ne[3] == n_seqs); - GGML_ASSERT(k->ne[0] == S_k && k->ne[1] == H_k && k->ne[2] == n_tokens && k->ne[3] == n_seqs); - GGML_ASSERT(v->ne[0] == S_v && v->ne[1] == H_v && v->ne[2] == n_tokens && v->ne[3] == n_seqs); - - GGML_ASSERT(g->ne[0] == 1 || g->ne[0] == S_v); - GGML_ASSERT( g->ne[1] == H_v && g->ne[2] == n_tokens && g->ne[3] == n_seqs); - GGML_ASSERT(b->ne[0] == 1 && b->ne[1] == H_v && b->ne[2] == n_tokens && b->ne[3] == n_seqs); - GGML_ASSERT(s->ne[0] == S_v && s->ne[1] == S_v && s->ne[2] == H_v && s->ne[3] == n_seqs); - - const float scale = 1.0f / sqrtf(S_k); - - q = ggml_scale(ctx0, q, scale); - - q = ggml_permute(ctx0, q, 0, 2, 1, 3); // [S_k, n_tokens, H_k, n_seqs] - k = ggml_permute(ctx0, k, 0, 2, 1, 3); // [S_k, n_tokens, H_k, n_seqs] - v = ggml_permute(ctx0, v, 0, 2, 1, 3); // [S_v, n_tokens, H_v, n_seqs] - - cb(q, "q_in", il); - cb(k, "k_in", il); - cb(v, "v_in", il); - cb(b, "b_in", il); - cb(g, "g_in", il); - - // GDA: [1, 1, H_v, n_seqs] - // KDA: [1, S_k, H_v, n_seqs] - g = ggml_reshape_4d(ctx0, g, 1, g->ne[0], H_v, n_seqs); - b = ggml_reshape_4d(ctx0, b, 1, 1, H_v, n_seqs); - - // [S_v, S_v, H_v, n_seqs] - g = ggml_exp(ctx0, g); - s = ggml_mul(ctx0, s, g); - - // [1, S_v, H_v, n_seqs] - ggml_tensor * sk; - sk = ggml_mul (ctx0, s, k); - sk = ggml_sum_rows(ctx0, sk); - - // [S_v, 1, H_v, n_seqs] - ggml_tensor * d; - d = ggml_sub(ctx0, v, ggml_transpose(ctx0, sk)); - d = ggml_mul(ctx0, d, b); - - // [1, S_v, H_v, n_seqs] - ggml_tensor * d_t; - d_t = ggml_transpose(ctx0, d); - - // [S_v, S_v, H_v, n_seqs] - ggml_tensor * kd; - k = ggml_repeat(ctx0, k, s); - kd = ggml_mul (ctx0, k, d_t); - - s = ggml_add(ctx0, s, kd); - - cb(s, "dnet_add_ar_state", il); - - ggml_tensor * s_q = ggml_mul (ctx0, s, q); - ggml_tensor * o = ggml_sum_rows(ctx0, s_q); - - o = ggml_permute (ctx0, o, 2, 0, 1, 3); // [S_v, H_v, n_tokens, n_seqs] - - return {o, s}; -} - -std::pair llm_build_delta_net_base::build_delta_net_fused( +std::pair llm_build_delta_net_base::build_delta_net( ggml_tensor * q, ggml_tensor * k, ggml_tensor * v, ggml_tensor * g, ggml_tensor * b, - ggml_tensor * s, - int il) { + ggml_tensor * s) { const int64_t S_k = q->ne[0]; const int64_t H_k = q->ne[1]; const int64_t n_tokens = q->ne[2]; @@ -397,12 +34,6 @@ std::pair llm_build_delta_net_base::build_delta_ne // K=1: output carries the final state only. state s is 4D [S_v, S_v, H_v, n_seqs]. ggml_tensor * result = ggml_gated_delta_net(ctx0, q, k, v, g, b, s, /*K=*/1); - if (n_tokens == 1) { - res->add_fused_node({LLM_FUSED_OP_GDN_AR, result, il}); - } else { - res->add_fused_node({LLM_FUSED_OP_GDN_CH, result, il}); - } - ggml_tensor * output = ggml_view_4d(ctx0, result, S_v, H_v, n_tokens, n_seqs, ggml_row_size(result->type, S_v), @@ -419,30 +50,6 @@ std::pair llm_build_delta_net_base::build_delta_ne return {output, new_state}; } -std::pair llm_build_delta_net_base::build_delta_net( - ggml_tensor * q, - ggml_tensor * k, - ggml_tensor * v, - ggml_tensor * g, - ggml_tensor * b, - ggml_tensor * s, - int il) { - const int64_t n_seq_tokens = q->ne[2]; - - if (n_seq_tokens == 1) { - if (cparams.fused_gdn_ar) { - return build_delta_net_fused(q, k, v, g, b, s, il); - } - return build_delta_net_autoregressive(q, k, v, g, b, s, il); - } - - if (cparams.fused_gdn_ch) { - return build_delta_net_fused(q, k, v, g, b, s, il); - } - - return build_delta_net_chunking(q, k, v, g, b, s, il); -} - ggml_tensor * llm_build_delta_net_base::build_conv_state( llm_graph_input_rs * inp, ggml_tensor * conv_states_all, @@ -491,7 +98,7 @@ ggml_tensor * llm_build_delta_net_base::build_recurrent_attn( const bool keep = cparams.n_rs_seq > 0; if (!keep) { - auto attn_out = build_delta_net(q, k, v, g, b, s, il); + auto attn_out = build_delta_net(q, k, v, g, b, s); ggml_tensor * output = attn_out.first; ggml_tensor * new_state = attn_out.second; cb(output, "attn_output", il); @@ -510,12 +117,6 @@ ggml_tensor * llm_build_delta_net_base::build_recurrent_attn( // state s is 4D [S_v, S_v, H_v, n_seqs]; K snapshot slots are written into the output. ggml_tensor * gdn_out = ggml_gated_delta_net(ctx0, q, k, v, g, b, s, K); - if (n_seq_tokens > 1) { - res->add_fused_node({LLM_FUSED_OP_GDN_CH, gdn_out, il}); - } else { - res->add_fused_node({LLM_FUSED_OP_GDN_AR, gdn_out, il}); - } - const int64_t attn_score_elems = S_v * H_v * n_seq_tokens * n_seqs; const int64_t state_size_per_snap = S_v * S_v * H_v * n_seqs; diff --git a/src/models/kimi-linear.cpp b/src/models/kimi-linear.cpp index 54d30ad47d2b..2190df8c95ab 100644 --- a/src/models/kimi-linear.cpp +++ b/src/models/kimi-linear.cpp @@ -348,8 +348,7 @@ llama_model_kimi_linear::graph::graph(const llm_graph_params & params) : Qcur = build_gdn_l2_norm(ctx0, Qcur, eps_norm); Kcur = build_gdn_l2_norm(ctx0, Kcur, eps_norm); - // Choose between build_delta_net_chunking and build_delta_net_recurrent based on n_tokens - auto attn_out = build_delta_net(Qcur, Kcur, Vcur, g1, beta, state, il); + auto attn_out = build_delta_net(Qcur, Kcur, Vcur, g1, beta, state); ggml_tensor * output = ggml_cont(ctx0, attn_out.first); ggml_tensor * new_state = attn_out.second; diff --git a/src/models/models.h b/src/models/models.h index 0a3c20278dad..d776fa22203a 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -51,44 +51,13 @@ struct llm_build_delta_net_base : public llm_graph_context { virtual ~llm_build_delta_net_base() = default; // returns pair of output and new state - std::pair build_delta_net_chunking( - ggml_tensor * q, - ggml_tensor * k, - ggml_tensor * v, - ggml_tensor * g, - ggml_tensor * b, - ggml_tensor * s, - int il); - - // returns pair of output and new state - std::pair build_delta_net_autoregressive( - ggml_tensor * q, - ggml_tensor * k, - ggml_tensor * v, - ggml_tensor * g, - ggml_tensor * b, - ggml_tensor * s, - int il); - - // use the ggml_gated_delta_net fused operator (K=1; state has shape [S_v, S_v, H_v, n_seqs]) - std::pair build_delta_net_fused( - ggml_tensor * q, - ggml_tensor * k, - ggml_tensor * v, - ggml_tensor * g, - ggml_tensor * b, - ggml_tensor * s, - int il); - - // choose one of two implementations above based on the number of tokens std::pair build_delta_net( ggml_tensor * q, ggml_tensor * k, ggml_tensor * v, ggml_tensor * g, ggml_tensor * b, - ggml_tensor * s, - int il); + ggml_tensor * s); // read conv state from cache, concat with qkv_mixed, write back (single slot or per-token) // qkv_mixed: (qkv_dim, n_seq_tokens, n_seqs); returns conv_input: (kernel_size + n_seq_tokens - 1, channels, n_seqs) diff --git a/src/models/qwen35.cpp b/src/models/qwen35.cpp index 4e2e8f826e83..f863923ece93 100644 --- a/src/models/qwen35.cpp +++ b/src/models/qwen35.cpp @@ -78,13 +78,20 @@ void llama_model_qwen35::load_arch_tensors(llama_model_loader & ml) { } else { // Linear attention (gated delta net) specific tensors // Create tensors with calculated dimensions - layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", il), { n_embd, key_dim * 2 + value_dim }, TENSOR_NOT_REQUIRED); - layer.wqkv_gate = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "weight", il), { n_embd, value_dim }, TENSOR_NOT_REQUIRED); + const int separate_flags = flags & TENSOR_SKIP ? flags | TENSOR_NOT_REQUIRED : flags; + layer.wqkv_z = create_tensor(tn(LLM_TENSOR_ATTN_QKV_GATE, "weight", il), { n_embd, key_dim * 2 + value_dim * 2 }, flags | TENSOR_NOT_REQUIRED | TENSOR_SKIP_IF_VIRTUAL); + if (!layer.wqkv_z) { + layer.wqkv = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "weight", il), { n_embd, key_dim * 2 + value_dim }, separate_flags); + layer.wqkv_gate = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "weight", il), { n_embd, value_dim }, separate_flags); + } layer.ssm_conv1d = create_tensor(tn(LLM_TENSOR_SSM_CONV1D, "weight", il), { hparams.ssm_d_conv, conv_dim }, flags); layer.ssm_dt = create_tensor(tn(LLM_TENSOR_SSM_DT, "bias", il), { hparams.ssm_dt_rank }, flags); layer.ssm_a = create_tensor(tn(LLM_TENSOR_SSM_A_NOSCAN, il), { hparams.ssm_dt_rank }, flags); - layer.ssm_beta = create_tensor(tn(LLM_TENSOR_SSM_BETA, "weight", il), { n_embd, n_v_heads }, flags); - layer.ssm_alpha = create_tensor(tn(LLM_TENSOR_SSM_ALPHA, "weight", il), { n_embd, n_v_heads }, flags); + layer.ssm_beta_alpha_cat = create_tensor(tn(LLM_TENSOR_SSM_BETA_ALPHA_CAT, "weight", il), { n_embd, n_v_heads * 2 }, flags | TENSOR_NOT_REQUIRED | TENSOR_SKIP_IF_VIRTUAL); + if (!layer.ssm_beta_alpha_cat) { + layer.ssm_beta = create_tensor(tn(LLM_TENSOR_SSM_BETA, "weight", il), { n_embd, n_v_heads }, separate_flags); + layer.ssm_alpha = create_tensor(tn(LLM_TENSOR_SSM_ALPHA, "weight", il), { n_embd, n_v_heads }, separate_flags); + } layer.ssm_norm = create_tensor(tn(LLM_TENSOR_SSM_NORM, "weight", il), { head_v_dim }, flags); layer.ssm_out = create_tensor(tn(LLM_TENSOR_SSM_OUT, "weight", il), { value_dim, n_embd }, flags); } @@ -239,6 +246,22 @@ std::pair llama_model_qwen35::graph::build_qkvz( const int64_t n_seqs = ubatch.n_seqs; const int64_t n_seq_tokens = ubatch.n_seq_tokens; + if (model.layers[il].wqkv_z) { + ggml_tensor * qkvz = build_lora_mm(model.layers[il].wqkv_z, input); + cb(qkvz, "linear_attn_qkvz", il); + + const int64_t n_z = hparams.ssm_d_state * hparams.ssm_dt_rank; + const int64_t n_qkv = qkvz->ne[0] - n_z; + + ggml_tensor * qkv_mixed = ggml_view_3d(ctx0, qkvz, n_qkv, n_seq_tokens, n_seqs, qkvz->nb[1], qkvz->nb[1] * n_seq_tokens, 0); + cb(qkv_mixed, "linear_attn_qkv_mixed", il); + + ggml_tensor * z = ggml_view_2d(ctx0, qkvz, n_z, n_seq_tokens * n_seqs, qkvz->nb[1], ggml_row_size(qkvz->type, n_qkv)); + cb(z, "z", il); + + return { qkv_mixed, z }; + } + ggml_tensor * qkv_mixed = build_lora_mm(model.layers[il].wqkv, input, model.layers[il].wqkv_s); qkv_mixed = ggml_reshape_3d(ctx0, qkv_mixed, qkv_mixed->ne[0], n_seq_tokens, n_seqs); cb(qkv_mixed, "linear_attn_qkv_mixed", il); @@ -354,19 +377,38 @@ ggml_tensor * llama_model_qwen35::graph::build_layer_attn_linear( ggml_tensor * qkv_mixed = qkvz.first; ggml_tensor * z = qkvz.second; - ggml_tensor * beta = build_lora_mm(model.layers[il].ssm_beta, cur, model.layers[il].ssm_beta_s); - cb(beta, "beta", il); + ggml_tensor * beta = nullptr; + ggml_tensor * alpha_biased = nullptr; + if (model.layers[il].ssm_beta_alpha_cat) { + ggml_tensor * ba = build_lora_mm(model.layers[il].ssm_beta_alpha_cat, cur); + cb(ba, "beta_alpha", il); - // reshape after the activation so that mul_mat + unary can be fused - beta = ggml_sigmoid(ctx0, beta); - cb(beta, "beta_sigmoid", il); + beta = ggml_view_4d(ctx0, ba, 1, num_v_heads, n_seq_tokens, n_seqs, + ggml_element_size(ba), ba->nb[1], ba->nb[1] * n_seq_tokens, 0); + ggml_tensor * alpha = ggml_view_3d(ctx0, ba, num_v_heads, n_seq_tokens, n_seqs, + ba->nb[1], ba->nb[1] * n_seq_tokens, ggml_row_size(ba->type, num_v_heads)); + cb(beta, "beta", il); + cb(alpha, "alpha", il); - beta = ggml_reshape_4d(ctx0, beta, 1, num_v_heads, n_seq_tokens, n_seqs); + beta = ggml_sigmoid(ctx0, beta); + cb(beta, "beta_sigmoid", il); - ggml_tensor * alpha = build_lora_mm(model.layers[il].ssm_alpha, cur, model.layers[il].ssm_alpha_s); - cb(alpha, "alpha", il); + alpha_biased = ggml_add(ctx0, alpha, model.layers[il].ssm_dt); + } else { + beta = build_lora_mm(model.layers[il].ssm_beta, cur, model.layers[il].ssm_beta_s); + cb(beta, "beta", il); + + // reshape after the activation so that mul_mat + unary can be fused + beta = ggml_sigmoid(ctx0, beta); + cb(beta, "beta_sigmoid", il); + + beta = ggml_reshape_4d(ctx0, beta, 1, num_v_heads, n_seq_tokens, n_seqs); + + ggml_tensor * alpha = build_lora_mm(model.layers[il].ssm_alpha, cur, model.layers[il].ssm_alpha_s); + cb(alpha, "alpha", il); - ggml_tensor * alpha_biased = ggml_add(ctx0, alpha, model.layers[il].ssm_dt); + alpha_biased = ggml_add(ctx0, alpha, model.layers[il].ssm_dt); + } ggml_tensor * alpha_softplus = ggml_softplus(ctx0, alpha_biased); cb(alpha_softplus, "a_softplus", il); @@ -384,10 +426,8 @@ ggml_tensor * llama_model_qwen35::graph::build_layer_attn_linear( ggml_tensor * conv_input = build_conv_state(inp, conv_states_all, qkv_mixed, conv_kernel_size, conv_channels, il); - // the chunked path without the fused kernel reads the state after the new state is stored - ggml_tensor * state = (ubatch.n_seq_tokens == 1 || cparams.fused_gdn_ch) ? - build_rs_in_place(inp, ssm_states_all, hparams.n_embd_s(), n_seqs) : - build_rs(inp, ssm_states_all, hparams.n_embd_s(), n_seqs); + // the delta net is always the fused kernel, which reads the state before it stores the new one + ggml_tensor * state = build_rs_in_place(inp, ssm_states_all, hparams.n_embd_s(), n_seqs); state = ggml_reshape_4d(ctx0, state, head_v_dim, head_v_dim, num_v_heads, n_seqs); cb(state, "state_predelta", il); @@ -421,14 +461,6 @@ ggml_tensor * llama_model_qwen35::graph::build_layer_attn_linear( //k_conv = ggml_cont_4d(ctx0, k_conv, head_k_dim, num_k_heads, n_seq_tokens, n_seqs); //v_conv = ggml_cont_4d(ctx0, v_conv, head_v_dim, num_v_heads, n_seq_tokens, n_seqs); - // if head keys and value keys are different, repeat to force tensors into matching shapes - // note: need explicit repeat only if we are not using the fused GDN. - if (num_k_heads != num_v_heads && (!cparams.fused_gdn_ar || !cparams.fused_gdn_ch)) { - GGML_ASSERT(num_v_heads % num_k_heads == 0); - q_conv = ggml_repeat_4d(ctx0, q_conv, head_k_dim, num_v_heads, n_seq_tokens, n_seqs); - k_conv = ggml_repeat_4d(ctx0, k_conv, head_k_dim, num_v_heads, n_seq_tokens, n_seqs); - } - cb(q_conv, "q_conv_predelta", il); cb(k_conv, "k_conv_predelta", il); cb(v_conv, "v_conv_predelta", il); @@ -436,7 +468,8 @@ ggml_tensor * llama_model_qwen35::graph::build_layer_attn_linear( ggml_tensor * output = build_recurrent_attn(inp, ssm_states_all, q_conv, k_conv, v_conv, gate, beta, state, il); // z: [head_dim, n_heads, n_tokens, n_seqs] -> [n_heads * n_tokens * n_seqs, head_dim] - ggml_tensor * z_2d = ggml_reshape_4d(ctx0, z, head_v_dim, num_v_heads, n_seq_tokens, n_seqs); + ggml_tensor * z_2d = ggml_view_4d(ctx0, z, head_v_dim, num_v_heads, n_seq_tokens, n_seqs, + ggml_row_size(z->type, head_v_dim), z->nb[1], z->nb[1] * n_seq_tokens, 0); // Apply gated normalization: self.norm(core_attn_out, z) ggml_tensor * attn_out_norm = build_norm_gated(output, model.layers[il].ssm_norm, z_2d, il); diff --git a/src/models/qwen35moe.cpp b/src/models/qwen35moe.cpp index 82abe59bbd42..affe13dc97ed 100644 --- a/src/models/qwen35moe.cpp +++ b/src/models/qwen35moe.cpp @@ -394,10 +394,8 @@ ggml_tensor * llama_model_qwen35moe::graph::build_layer_attn_linear( ggml_tensor * conv_input = build_conv_state(inp, conv_states_all, qkv_mixed, conv_kernel_size, conv_channels, il); - // the chunked path without the fused kernel reads the state after the new state is stored - ggml_tensor * state = (ubatch.n_seq_tokens == 1 || cparams.fused_gdn_ch) ? - build_rs_in_place(inp, ssm_states_all, hparams.n_embd_s(), n_seqs) : - build_rs(inp, ssm_states_all, hparams.n_embd_s(), n_seqs); + // the delta net is always the fused kernel, which reads the state before it stores the new one + ggml_tensor * state = build_rs_in_place(inp, ssm_states_all, hparams.n_embd_s(), n_seqs); state = ggml_reshape_4d(ctx0, state, head_v_dim, head_v_dim, num_v_heads, n_seqs); cb(state, "state_predelta", il); @@ -431,14 +429,6 @@ ggml_tensor * llama_model_qwen35moe::graph::build_layer_attn_linear( //k_conv = ggml_cont_4d(ctx0, k_conv, head_k_dim, num_k_heads, n_seq_tokens, n_seqs); //v_conv = ggml_cont_4d(ctx0, v_conv, head_v_dim, num_v_heads, n_seq_tokens, n_seqs); - // if head keys and value keys are different, repeat to force tensors into matching shapes - // note: need explicit repeat only if we are not using the fused GDN. - if (num_k_heads != num_v_heads && (!cparams.fused_gdn_ar || !cparams.fused_gdn_ch)) { - GGML_ASSERT(num_v_heads % num_k_heads == 0); - q_conv = ggml_repeat_4d(ctx0, q_conv, head_k_dim, num_v_heads, n_seq_tokens, n_seqs); - k_conv = ggml_repeat_4d(ctx0, k_conv, head_k_dim, num_v_heads, n_seq_tokens, n_seqs); - } - cb(q_conv, "q_conv_predelta", il); cb(k_conv, "k_conv_predelta", il); cb(v_conv, "v_conv_predelta", il); diff --git a/src/models/qwen3next.cpp b/src/models/qwen3next.cpp index 613b03e0a594..80993b7f615a 100644 --- a/src/models/qwen3next.cpp +++ b/src/models/qwen3next.cpp @@ -451,10 +451,8 @@ ggml_tensor * llama_model_qwen3next::graph::build_layer_attn_linear( ggml_tensor * conv_input = build_conv_state(inp, conv_states_all, qkv_mixed, conv_kernel_size, conv_channels, il); - // the chunked path without the fused kernel reads the state after the new state is stored - ggml_tensor * state = (ubatch.n_seq_tokens == 1 || cparams.fused_gdn_ch) ? - build_rs_in_place(inp, ssm_states_all, hparams.n_embd_s(), n_seqs) : - build_rs(inp, ssm_states_all, hparams.n_embd_s(), n_seqs); + // the delta net is always the fused kernel, which reads the state before it stores the new one + ggml_tensor * state = build_rs_in_place(inp, ssm_states_all, hparams.n_embd_s(), n_seqs); state = ggml_reshape_4d(ctx0, state, head_v_dim, head_v_dim, num_v_heads, n_seqs); cb(state, "state_predelta", il); diff --git a/src/models/qwen4exp.cpp b/src/models/qwen4exp.cpp index 876640e16a62..181e4dca4047 100644 --- a/src/models/qwen4exp.cpp +++ b/src/models/qwen4exp.cpp @@ -1191,13 +1191,6 @@ ggml_tensor * llama_model_qwen4exp::graph::build_layer_attn_linear( q_conv = build_gdn_l2_norm(ctx0, q_conv, eps_norm); k_conv = build_gdn_l2_norm(ctx0, k_conv, eps_norm); - // repeat to match shapes when head keys != value keys; unneeded with the fused GDN - if (num_k_heads != num_v_heads && (!cparams.fused_gdn_ar || !cparams.fused_gdn_ch)) { - GGML_ASSERT(num_v_heads % num_k_heads == 0); - q_conv = ggml_repeat_4d(ctx0, q_conv, head_k_dim, num_v_heads, n_seq_tokens, n_seqs); - k_conv = ggml_repeat_4d(ctx0, k_conv, head_k_dim, num_v_heads, n_seq_tokens, n_seqs); - } - cb(q_conv, "q_conv_predelta", il); cb(k_conv, "k_conv_predelta", il); cb(v_conv, "v_conv_predelta", il); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index ddb5e27671f7..460b63a1d1bd 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -161,7 +161,7 @@ if (NOT WIN32) NAME test-tokenizers-ggml-vocabs LABEL behavior WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} - ARGS https://huggingface.co/ggml-org/vocabs ${PROJECT_SOURCE_DIR}/models/ggml-vocabs + ARGS https://huggingface.co/ggml-org-dev/vocabs ${PROJECT_SOURCE_DIR}/models/ggml-vocabs ) endif() @@ -326,15 +326,16 @@ llama_build_and_test( ) if (NOT ${CMAKE_SYSTEM_PROCESSOR} MATCHES "s390x") - set(MODEL_NAME "tinyllamas/stories15M-q4_0.gguf") + set(MODEL_NAME "stories15M-q4_0.gguf") set(MODEL_HASH "SHA256=66967fbece6dbe97886593fdbb73589584927e29119ec31f08090732d1861739") else() - set(MODEL_NAME "tinyllamas/stories15M-be.Q4_0.gguf") + set(MODEL_NAME "stories15M-be.Q4_0.gguf") set(MODEL_HASH "SHA256=9aec857937849d976f30397e97eb1cabb53eb9dcb1ce4611ba8247fb5f44c65d") endif() set(MODEL_DEST "${CMAKE_BINARY_DIR}/${MODEL_NAME}") add_test(NAME test-download-model COMMAND ${CMAKE_COMMAND} + -DREPO=ggml-org-dev/stories15M -DDEST=${MODEL_DEST} -DNAME=${MODEL_NAME} -DHASH=${MODEL_HASH} diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 6617a7c0a8bc..98658be2121e 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -5613,9 +5613,14 @@ struct test_mul_mat : public test_case { const int64_t m_v; // rows of a in memory, the batches of a are strided for m_v > m, no view for m_v == 0 const int64_t pad; // bytes after the m_v rows of each batch of a, so nb[2] of a is not a multiple of nb[1] const size_t offset_a; // byte offset of the a view when k_v > k or m_v > m + const bool weights; // a in a weights buffer (CUDA with PDL reads weights early) std::string vars() override { - return VARS_TO_STR14(type_a, type_b, m, n, k, bs, nr, per, k_v, o, src_overlap, m_v, pad, offset_a); + std::string s = VARS_TO_STR14(type_a, type_b, m, n, k, bs, nr, per, k_v, o, src_overlap, m_v, pad, offset_a); + if (weights) { + s += ",weights=1"; + } + return s; } double max_nmse_err() override { @@ -5649,10 +5654,21 @@ struct test_mul_mat : public test_case { std::array bs = {10, 10}, std::array nr = {2, 2}, std::array per = {0, 1, 2, 3}, - int64_t k_v = 0, uint32_t o = 1, bool src_overlap = false, int64_t m_v = 0, int64_t pad = 0, size_t offset_a = 0) - : type_a(type_a), type_b(type_b), m(m), n(n), k(k), bs(bs), nr(nr), per(per), k_v(k_v), o(o), src_overlap(src_overlap), m_v(m_v), pad(pad), offset_a(offset_a) {} + int64_t k_v = 0, uint32_t o = 1, bool src_overlap = false, int64_t m_v = 0, int64_t pad = 0, size_t offset_a = 0, bool weights = false) + : type_a(type_a), type_b(type_b), m(m), n(n), k(k), bs(bs), nr(nr), per(per), k_v(k_v), o(o), src_overlap(src_overlap), m_v(m_v), pad(pad), offset_a(offset_a), weights(weights) {} + + bool use_weight_context() override { + return weights; + } ggml_tensor * build_graph(ggml_context * ctx) override { + return build_graph(ctx, ctx); + } + + ggml_tensor * build_graph(ggml_context * ctx, ggml_context * ctx_weights) override { + ggml_context * ctx_a = weights ? ctx_weights : ctx; + GGML_ASSERT(ctx_a); + // C^T = A * B^T: (k, m) * (k, n) => (m, n) ggml_tensor * a; ggml_tensor * b; @@ -5669,7 +5685,7 @@ struct test_mul_mat : public test_case { const int64_t ne_a[4] = {k, m, bs[0], bs[1]}; const int64_t ne_b[4] = {k, n, bs[0]*nr[0], bs[1]*nr[1]}; - a = ggml_new_tensor_4d(ctx, type_a, ne_a[per[0]], ne_a[per[1]], ne_a[per[2]], ne_a[per[3]]); + a = ggml_new_tensor_4d(ctx_a, type_a, ne_a[per[0]], ne_a[per[1]], ne_a[per[2]], ne_a[per[3]]); b = ggml_new_tensor_4d(ctx, type_b, ne_b[per[0]], ne_b[per[1]], ne_b[per[2]], ne_b[per[3]]); if (!ggml_is_quantized(type_a)) { if (bs[1] == 1 && nr[1] == 1) { @@ -5688,6 +5704,7 @@ struct test_mul_mat : public test_case { GGML_ASSERT(type_a == type_b); GGML_ASSERT(k_v == 0); GGML_ASSERT(m_v == 0); + GGML_ASSERT(ctx_a == ctx); // not handled: b is a view of the same tensor // a and b are interleaved views of the same tensor: (e.g. fused QKV in MiniMax-01) ggml_tensor * base = ggml_new_tensor_4d(ctx, type_a, 2*k, std::max(m, n), bs[0]*nr[0], bs[1]*nr[1]); @@ -5700,7 +5717,7 @@ struct test_mul_mat : public test_case { } else { const int64_t k_physical = k_v == 0 ? k : k_v; const int64_t m_physical = m_v == 0 ? m : m_v + (pad != 0); - a = ggml_new_tensor_4d(ctx, type_a, k_physical, m_physical, bs[0], bs[1]); + a = ggml_new_tensor_4d(ctx_a, type_a, k_physical, m_physical, bs[0], bs[1]); b = ggml_new_tensor_4d(ctx, type_b, k_physical, n, bs[0]*nr[0], bs[1]*nr[1]); if (!ggml_is_quantized(type_a)) { @@ -5755,8 +5772,8 @@ struct test_mul_mat_hadamard : public test_mul_mat { GGML_ASSERT(type_a == GGML_TYPE_F32); } - ggml_tensor * build_graph(ggml_context * ctx) override { - ggml_tensor * out = test_mul_mat::build_graph(ctx); + ggml_tensor * build_graph(ggml_context * ctx, ggml_context * ctx_weights) override { + ggml_tensor * out = test_mul_mat::build_graph(ctx, ctx_weights); // Find the mul_mat op in the graph and set the hint for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { if (t->op == GGML_OP_MUL_MAT) { @@ -5805,8 +5822,8 @@ struct test_mul_mat_w4a8 : public test_mul_mat { std::array bs = {1, 1}, std::array nr = {1, 1}) : test_mul_mat(type_a, type_b, m, n, k, bs, nr) {} - ggml_tensor * build_graph(ggml_context * ctx) override { - ggml_tensor * out = test_mul_mat::build_graph(ctx); + ggml_tensor * build_graph(ggml_context * ctx, ggml_context * ctx_weights) override { + ggml_tensor * out = test_mul_mat::build_graph(ctx, ctx_weights); for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { if (t->op == GGML_OP_MUL_MAT) { ggml_prec_set_src(t, GGML_PREC_Q8, 1); @@ -5827,8 +5844,8 @@ struct test_mul_mat_prec_src1_bf16 : public test_mul_mat { std::array bs = {1, 1}, std::array nr = {1, 1}) : test_mul_mat(type_a, GGML_TYPE_F32, m, n, k, bs, nr) {} - ggml_tensor * build_graph(ggml_context * ctx) override { - ggml_tensor * out = test_mul_mat::build_graph(ctx); + ggml_tensor * build_graph(ggml_context * ctx, ggml_context * ctx_weights) override { + ggml_tensor * out = test_mul_mat::build_graph(ctx, ctx_weights); for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { if (t->op == GGML_OP_MUL_MAT) { ggml_prec_set_src(t, GGML_PREC_BF16, 1); @@ -5860,8 +5877,8 @@ struct test_mul_mat_prec_src1_f32 : public test_mul_mat { double max_nmse_err() override { return 1e-10; } - ggml_tensor * build_graph(ggml_context * ctx) override { - ggml_tensor * out = test_mul_mat::build_graph(ctx); + ggml_tensor * build_graph(ggml_context * ctx, ggml_context * ctx_weights) override { + ggml_tensor * out = test_mul_mat::build_graph(ctx, ctx_weights); for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { if (t->op == GGML_OP_MUL_MAT) { ggml_prec_set_src(t, GGML_PREC_F32, 1); @@ -6649,33 +6666,6 @@ struct test_trunc : public test_case { } }; -// GGML_OP_DIAG_MASK_INF -struct test_diag_mask_inf : public test_case { - const ggml_type type; - const std::array ne; - const int n_past; - - std::string vars() override { - return VARS_TO_STR3(type, ne, n_past); - } - - test_diag_mask_inf(ggml_type type = GGML_TYPE_F32, - std::array ne = {10, 10, 3, 2}, - int n_past = 5) - : type(type), ne(ne), n_past(n_past) {} - - ggml_tensor * build_graph(ggml_context * ctx) override { - ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data()); - ggml_set_param(a); - ggml_set_name(a, "a"); - - ggml_tensor * out = ggml_diag_mask_inf(ctx, a, n_past); - ggml_set_name(out, "out"); - - return out; - } -}; - // GGML_OP_SOFT_MAX struct test_soft_max : public test_case { const ggml_type type; @@ -8497,7 +8487,7 @@ struct test_mul_mat_add : public test_case { } }; -struct test_mul_mat_vec_fusion : public test_case { +struct test_mul_mat_fusion : public test_case { const ggml_type type; const ggml_glu_op glu_op; const int64_t m; @@ -8513,7 +8503,7 @@ struct test_mul_mat_vec_fusion : public test_case { std::array batch_dims; const bool skip; // set some ids to a negative value (only for use_id) - test_mul_mat_vec_fusion(ggml_type type, ggml_glu_op op, int64_t m, int64_t n, int64_t k, + test_mul_mat_fusion(ggml_type type, ggml_glu_op op, int64_t m, int64_t n, int64_t k, bool use_id = false, int n_mats = 1, int n_used = 1, bool b = false, bool with_bias = false, bool with_gate = true, bool with_lane_scale = false, std::array batch_dims = {4, 2}, bool skip = false) : type(type), glu_op(op), m(m), n(n), k(k), use_id(use_id), n_mats(n_mats), n_used(n_used), b(b), with_bias(with_bias), @@ -8529,7 +8519,7 @@ struct test_mul_mat_vec_fusion : public test_case { std::string op_desc(ggml_tensor * t) override { GGML_UNUSED(t); - return "MUL_MAT_VEC_FUSION"; + return "MUL_MAT_FUSION"; } bool run_whole_graph() override { return true; } @@ -8694,12 +8684,12 @@ struct test_mul_mat_vec_fusion : public test_case { }; // Fused gate/up/GLU with GGML_PREC_Q8 on src1, e.g. a W4A16 NVFP4 checkpoint (W4A8, see test_mul_mat_w4a8) -struct test_mul_mat_vec_fusion_w4a8 : public test_mul_mat_vec_fusion { - using test_mul_mat_vec_fusion::test_mul_mat_vec_fusion; - using test_mul_mat_vec_fusion::build_graph; +struct test_mul_mat_fusion_w4a8 : public test_mul_mat_fusion { + using test_mul_mat_fusion::test_mul_mat_fusion; + using test_mul_mat_fusion::build_graph; ggml_tensor * build_graph(ggml_context * ctx, ggml_context * ctx_weights) override { - ggml_tensor * out = test_mul_mat_vec_fusion::build_graph(ctx, ctx_weights); + ggml_tensor * out = test_mul_mat_fusion::build_graph(ctx, ctx_weights); for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { if (t->op == GGML_OP_MUL_MAT || t->op == GGML_OP_MUL_MAT_ID) { ggml_prec_set_src(t, GGML_PREC_Q8, 1); @@ -8710,7 +8700,7 @@ struct test_mul_mat_vec_fusion_w4a8 : public test_mul_mat_vec_fusion { std::string op_desc(ggml_tensor * t) override { GGML_UNUSED(t); - return "MUL_MAT_VEC_FUSION_W4A8"; + return "MUL_MAT_FUSION_W4A8"; } }; @@ -9971,8 +9961,9 @@ struct test_solve_tri : public test_case { const ggml_type type; const std::array ne_lhs; const std::array ne_rhs; + const bool nan_out; // fill the output with NaN before the op runs - std::string vars() override { return VARS_TO_STR3(type, ne_lhs, ne_rhs); } + std::string vars() override { return VARS_TO_STR4(type, ne_lhs, ne_rhs, nan_out); } uint64_t op_flops(ggml_tensor * t) override { GGML_UNUSED(t); @@ -9985,9 +9976,10 @@ struct test_solve_tri : public test_case { test_solve_tri(ggml_type type = GGML_TYPE_F32, std::array ne_lhs = { 10, 10, 4, 3 }, - std::array ne_rhs = { 3, 10, 4, 3 } + std::array ne_rhs = { 3, 10, 4, 3 }, + bool nan_out = false ) - : type(type), ne_lhs(ne_lhs), ne_rhs(ne_rhs) {} + : type(type), ne_lhs(ne_lhs), ne_rhs(ne_rhs), nan_out(nan_out) {} ggml_tensor * build_graph(ggml_context * ctx) override { ggml_tensor * a = ggml_new_tensor_4d(ctx, type, ne_lhs[0], ne_lhs[1], ne_lhs[2], ne_lhs[3]); @@ -10009,6 +10001,9 @@ struct test_solve_tri : public test_case { if (strcmp(t->name, "a") == 0) { // note: avoid zeros in the diagonal init_tensor_tril(t, 0.1, 1.0f); + } else if (nan_out && strcmp(t->name, "out") == 0) { + std::vector data(ggml_nelements(t), NAN); + ggml_backend_tensor_set(t, data.data(), 0, ggml_nbytes(t)); } else { init_tensor_uniform(t, -1.0f, 1.0f); } @@ -12194,6 +12189,7 @@ static std::vector> make_test_cases_eval() { } } } + #if 0 // > 2^31-element dst (8.9 GB), about 45 GB peak memory. Too large to be enabled by default. // kernel_mul_mm dst offset of the last batch is past INT32_MAX: rows 0-31 use full tiles, rows 32-39 use edge tiles. @@ -12404,6 +12400,28 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_mul_mat_pos(type_a, GGML_TYPE_F32, 1000, n, 1024, {1, 1}, {1, 1})); } } + // CUDA few-row MMQ: 1-3 column groups, 32-row tiles (6170 rows), K = 18 units (uneven over the warps) and 9 units (one unit per ring stage) + for (ggml_type type_a : {GGML_TYPE_Q8_0, GGML_TYPE_Q3_K, GGML_TYPE_Q4_K, GGML_TYPE_Q5_K, GGML_TYPE_Q6_K, + GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_NL, GGML_TYPE_IQ4_XS}) { + for (int64_t k : {4608, 2304}) { + test_cases.emplace_back(new test_mul_mat(type_a, GGML_TYPE_F32, 1000, 8, k, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(type_a, GGML_TYPE_F32, 6170, 13, k, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(type_a, GGML_TYPE_F32, 1000, 21, k, {1, 1}, {1, 1})); + } + } + // permuted and broadcast src0/src1 for the 2 byte aligned types + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q6_K, GGML_TYPE_F32, 64, 13, 2304, {2, 3}, {1, 1}, {0, 2, 1, 3})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q6_K, GGML_TYPE_F32, 63, 5, 2304, {3, 2}, {2, 2})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q3_K, GGML_TYPE_F32, 64, 13, 4608, {2, 3}, {1, 1}, {0, 2, 1, 3})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_IQ3_S, GGML_TYPE_F32, 63, 5, 4608, {3, 2}, {2, 2})); + // partial column group, broadcast, padded rows, src1 in [0, 1], src0 in a weights buffer + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_F32, 1000, 5, 4608, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_F32, 64, 13, 4608, {3, 2}, {2, 2})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_F32, 1000, 13, 4608, {1, 1}, {1, 1}, {0, 1, 2, 3}, 5120)); + test_cases.emplace_back(new test_mul_mat_pos(GGML_TYPE_Q4_K, GGML_TYPE_F32, 1000, 13, 4608, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat_pos(GGML_TYPE_Q5_K, GGML_TYPE_F32, 1000, 13, 4608, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_F32, 6170, 13, 4608, {1, 1}, {1, 1}, {0, 1, 2, 3}, 0, 1, false, 0, 0, 0, true)); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q6_K, GGML_TYPE_F32, 1000, 21, 4608, {1, 1}, {1, 1}, {0, 1, 2, 3}, 0, 1, false, 0, 0, 0, true)); #if 0 { @@ -12860,10 +12878,6 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_trunc (type, {1024, 1024, 1, 1})); } - test_cases.emplace_back(new test_diag_mask_inf(GGML_TYPE_F32, {10, 10, 1, 1}, 5)); - test_cases.emplace_back(new test_diag_mask_inf(GGML_TYPE_F32, {10, 10, 3, 1}, 5)); - test_cases.emplace_back(new test_diag_mask_inf(GGML_TYPE_F32, {10, 10, 3, 2}, 5)); - #if 0 std::uniform_int_distribution<> dist_ne1(1, 50); int exponent = 1; @@ -13341,6 +13355,9 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_solve_tri(GGML_TYPE_F32, { 128, 128, 4, 1 }, { 32, 128, 4, 1 })); test_cases.emplace_back(new test_solve_tri(GGML_TYPE_F32, { 64, 64, 4, 4 }, { 200, 64, 4, 4 })); test_cases.emplace_back(new test_solve_tri(GGML_TYPE_F32, { 64, 64, 4, 4 }, { 384, 64, 4, 4 })); + // n % 32 != 0, output prefilled with NaN + test_cases.emplace_back(new test_solve_tri(GGML_TYPE_F32, { 34, 34, 1, 1 }, { 256, 34, 1, 1 }, true)); + test_cases.emplace_back(new test_solve_tri(GGML_TYPE_F32, { 79, 79, 5, 3 }, { 417, 79, 5, 3 }, true)); for (int tfrm : {0, 1, 2}) { for (bool circular : {false, true}) { @@ -13406,7 +13423,7 @@ static std::vector> make_test_cases_eval() { for (int kv : { 113, 512, 1024, }) { if (nr2 != 1 && kv != 512) continue; for (int nb : { 1, 3, 32, 75, }) { - for (ggml_prec prec : {GGML_PREC_F32, GGML_PREC_BF16, GGML_PREC_DEFAULT}) { + for (ggml_prec prec : {GGML_PREC_F32, GGML_PREC_BF16, GGML_PREC_UNDEFINED}) { if (hsk != 128 && prec != GGML_PREC_F32) continue; for (ggml_type type_KV : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q5_1, GGML_TYPE_Q5_0, GGML_TYPE_Q4_1, GGML_TYPE_Q4_0, GGML_TYPE_IQ4_NL}) { if (type_KV != GGML_TYPE_F16 && hsk != 64 && hsk != 72) continue; @@ -13651,12 +13668,12 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_opt_step_sgd(GGML_TYPE_F32, {10, 5, 4, 3})); for (bool with_bias : {false, true}) { - test_cases.emplace_back(new test_mul_mat_vec_fusion(GGML_TYPE_F8_E4M3, GGML_GLU_OP_SWIGLU, 16, 32, 256, + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_F8_E4M3, GGML_GLU_OP_SWIGLU, 16, 32, 256, false, 1, 1, false, with_bias, false, true, {1, 1})); } - test_cases.emplace_back(new test_mul_mat_vec_fusion(GGML_TYPE_F8_E4M3, GGML_GLU_OP_SWIGLU, 16, 32, 256, + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_F8_E4M3, GGML_GLU_OP_SWIGLU, 16, 32, 256, false, 1, 1, false, false, false, true, {2, 1})); - test_cases.emplace_back(new test_mul_mat_vec_fusion(GGML_TYPE_F8_E4M3, GGML_GLU_OP_SWIGLU, 16, 31, 257, + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_F8_E4M3, GGML_GLU_OP_SWIGLU, 16, 31, 257, false, 1, 1, false, false, false, true, {1, 1})); for (ggml_type type : base_types) { @@ -13681,18 +13698,18 @@ static std::vector> make_test_cases_eval() { if (with_lane_scale && type != GGML_TYPE_NVFP4 && type != GGML_TYPE_F8_E4M3) { continue; } - test_cases.emplace_back(new test_mul_mat_vec_fusion(type, glu_op, 1, 32, 256, + test_cases.emplace_back(new test_mul_mat_fusion(type, glu_op, 1, 32, 256, use_id, 16, 8, b, with_bias, with_gate, with_lane_scale)); - test_cases.emplace_back(new test_mul_mat_vec_fusion(type, glu_op, 1, 32, 256, + test_cases.emplace_back(new test_mul_mat_fusion(type, glu_op, 1, 32, 256, use_id, 16, 8, b, with_bias, with_gate, with_lane_scale, {1, 1})); // multi-token batches (spec decoding) for (int64_t m_batch : { 2, 4, 8 }) { - test_cases.emplace_back(new test_mul_mat_vec_fusion(type, glu_op, m_batch, 32, 256, + test_cases.emplace_back(new test_mul_mat_fusion(type, glu_op, m_batch, 32, 256, use_id, 16, 8, b, with_bias, with_gate, with_lane_scale, {1, 1})); } // the lane scale does a GET_ROWS on the ids, which does not accept -1 if (use_id && !with_lane_scale) { - test_cases.emplace_back(new test_mul_mat_vec_fusion(type, glu_op, 8, 32, 256, + test_cases.emplace_back(new test_mul_mat_fusion(type, glu_op, 8, 32, 256, use_id, 16, 8, b, with_bias, with_gate, with_lane_scale, {1, 1}, true)); } } @@ -13704,7 +13721,7 @@ static std::vector> make_test_cases_eval() { } for (bool b : {false, true}) { - test_cases.emplace_back(new test_mul_mat_vec_fusion(GGML_TYPE_IQ2_S, GGML_GLU_OP_SWIGLU_CLAMP, 1, 32, 256, + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_IQ2_S, GGML_GLU_OP_SWIGLU_CLAMP, 1, 32, 256, true, 16, 8, b, false, true, false)); } @@ -13714,7 +13731,7 @@ static std::vector> make_test_cases_eval() { GGML_TYPE_Q8_0}) { for (ggml_glu_op glu_op : {GGML_GLU_OP_SWIGLU, GGML_GLU_OP_GEGLU}) { for (int64_t m_batch : {1, 2, 3, 5, 8, 9, 16, 17}) { - test_cases.emplace_back(new test_mul_mat_vec_fusion(type, glu_op, m_batch, 1000, 1024, + test_cases.emplace_back(new test_mul_mat_fusion(type, glu_op, m_batch, 1000, 1024, false, 16, 8, false, false, true, false, { 1, 1 })); } } @@ -13722,7 +13739,7 @@ static std::vector> make_test_cases_eval() { for (int64_t k : {96, 896, 1024, 2880}) { for (ggml_glu_op glu_op : {GGML_GLU_OP_SWIGLU, GGML_GLU_OP_GEGLU}) { - test_cases.emplace_back(new test_mul_mat_vec_fusion(GGML_TYPE_Q8_0, glu_op, 1, 32, k, + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q8_0, glu_op, 1, 32, k, false, 16, 8, false, false, true, false, {1, 1})); } } @@ -13732,7 +13749,7 @@ static std::vector> make_test_cases_eval() { //for (ggml_glu_op glu_op : { GGML_GLU_OP_SWIGLU, GGML_GLU_OP_GEGLU }) { // for (int64_t m_batch : { 2, 3, 4 }) { // for (int64_t rows : { 1, 2, 3 }) { - // test_cases.emplace_back(new test_mul_mat_vec_fusion(GGML_TYPE_Q4_K, glu_op, m_batch, rows, 256, + // test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, glu_op, m_batch, rows, 256, // false, 16, 8, false, false, true, false, { 1, 1 })); // } // } @@ -13740,27 +13757,42 @@ static std::vector> make_test_cases_eval() { // Both sides of the same row-count boundary as above, on the fused path. for (int64_t rows : {6271, 6272, 6273}) { - test_cases.emplace_back(new test_mul_mat_vec_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 2, rows, 256, + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 2, rows, 256, false, 16, 8, false, false, true, false, { 1, 1 })); } // Fused gate/up + GLU on the MMQ path, only used if its tiling is efficient: ~1280 tiles per case, one case per type and GLU op. - test_cases.emplace_back(new test_mul_mat_vec_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 17, 81920, 256, false, 1, 1, false, false, true, false, { 1, 1 })); - test_cases.emplace_back(new test_mul_mat_vec_fusion(GGML_TYPE_Q5_K, GGML_GLU_OP_GEGLU, 150, 40960, 256, false, 1, 1, false, false, true, false, { 1, 1 })); - test_cases.emplace_back(new test_mul_mat_vec_fusion(GGML_TYPE_Q6_K, GGML_GLU_OP_SWIGLU_OAI, 150, 40960, 256, false, 1, 1, false, false, true, false, { 1, 1 })); - test_cases.emplace_back(new test_mul_mat_vec_fusion(GGML_TYPE_Q8_0, GGML_GLU_OP_SWIGLU_CLAMP, 150, 6912, 256, false, 1, 1, false, false, true, false, { 2, 3 })); - test_cases.emplace_back(new test_mul_mat_vec_fusion(GGML_TYPE_IQ4_XS, GGML_GLU_OP_SWIGLU, 150, 40960, 512, false, 1, 1, false, false, true, false, { 1, 1 })); - test_cases.emplace_back(new test_mul_mat_vec_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 6912, 256, false, 1, 1, false, false, true, true, { 2, 3 })); + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 17, 81920, 256, false, 1, 1, false, false, true, false, { 1, 1 })); + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q5_K, GGML_GLU_OP_GEGLU, 150, 40960, 256, false, 1, 1, false, false, true, false, { 1, 1 })); + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q6_K, GGML_GLU_OP_SWIGLU_OAI, 150, 40960, 256, false, 1, 1, false, false, true, false, { 1, 1 })); + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q8_0, GGML_GLU_OP_SWIGLU_CLAMP, 150, 6912, 256, false, 1, 1, false, false, true, false, { 2, 3 })); + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_IQ4_XS, GGML_GLU_OP_SWIGLU, 150, 40960, 512, false, 1, 1, false, false, true, false, { 1, 1 })); + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 6912, 256, false, 1, 1, false, false, true, true, { 2, 3 })); + // NVFP4 weight scale without gate/up: MMQ applies it in the write-back, the trailing bias add stays a separate node + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 2560, 256, false, 1, 1, false, false, false, true, { 1, 1 })); + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 2560, 256, true, 16, 8, false, false, false, true)); + // Same pattern with broadcast input, 4 of 16 experts used, 8-bit activations (W4A8), and Q4_K, which keeps the scale as a separate node + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 2560, 256, true, 16, 8, true, false, false, true)); + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 2560, 256, true, 16, 4, false, false, false, true)); + test_cases.emplace_back(new test_mul_mat_fusion_w4a8(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 2560, 256, false, 1, 1, false, false, false, true, { 1, 1 })); + test_cases.emplace_back(new test_mul_mat_fusion_w4a8(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 2560, 256, true, 16, 8, false, false, false, true)); + // Few columns and tiles with a long K: split-K through the stream-k fixup, the scale is applied to the partial sums + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 11, 64, 2048, false, 1, 1, false, false, false, true, { 1, 1 })); + test_cases.emplace_back(new test_mul_mat_fusion_w4a8(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 11, 64, 2048, false, 1, 1, false, false, false, true, { 1, 1 })); + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 150, 2560, 256, false, 1, 1, false, false, false, true, { 1, 1 })); + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 150, 2560, 256, true, 16, 8, false, false, false, true)); // The same with experts (~1280 tiles each): 17 tokens with broadcast input (one MMA tile per warp), 2048 tokens without (two, several column tiles per expert). - test_cases.emplace_back(new test_mul_mat_vec_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 17, 5120, 256, true, 16, 8, true)); - test_cases.emplace_back(new test_mul_mat_vec_fusion(GGML_TYPE_Q8_0, GGML_GLU_OP_SWIGLU, 2048, 128, 256, true, 40, 8, false)); + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 17, 5120, 256, true, 16, 8, true)); + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q8_0, GGML_GLU_OP_SWIGLU, 2048, 128, 256, true, 40, 8, false)); // NVFP4 with experts, without and with per-expert weight scales. - test_cases.emplace_back(new test_mul_mat_vec_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 2560, 256, true, 16, 8, false)); - test_cases.emplace_back(new test_mul_mat_vec_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 17, 5120, 256, true, 16, 8, true, false, true, true)); + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 2560, 256, true, 16, 8, false)); + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 17, 5120, 256, true, 16, 8, true, false, true, true)); // NVFP4 with 8-bit activations requested (W4A16 checkpoints), without and with weight scales. - test_cases.emplace_back(new test_mul_mat_vec_fusion_w4a8(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 2560, 256, true, 16, 8, false)); - test_cases.emplace_back(new test_mul_mat_vec_fusion_w4a8(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 40960, 256, false, 1, 1, false, false, true, true, { 1, 1 })); - test_cases.emplace_back(new test_mul_mat_vec_fusion_w4a8(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 2560, 256, true, 16, 8, false, false, true, true)); + test_cases.emplace_back(new test_mul_mat_fusion_w4a8(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 2560, 256, true, 16, 8, false)); + test_cases.emplace_back(new test_mul_mat_fusion_w4a8(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 40960, 256, false, 1, 1, false, false, true, true, { 1, 1 })); + test_cases.emplace_back(new test_mul_mat_fusion_w4a8(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 2560, 256, true, 16, 8, false, false, true, true)); + // K = 2048: few-row MMQ, where enabled, takes the gate and up matmuls instead of the fused MMQ path + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 9, 128, 2048, false, 1, 1, false, false, true, false, { 1, 1 })); for (auto gate : {GATING_FUNC_SOFTMAX, GATING_FUNC_SIGMOID, GATING_FUNC_SOFTMAX_WEIGHT, GATING_FUNC_SQRT_SOFTPLUS}) { for (bool with_norm : {false, true}) { diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp index b565775bf3a5..2c59d1222a52 100644 --- a/tests/test-chat.cpp +++ b/tests/test-chat.cpp @@ -3267,6 +3267,61 @@ static void test_template_output_peg_parsers(bool detailed_debug) { .expect(message_with_tool_calls("amount", R"({"orig": 1.5e10})")) .run(); + // The argument grammar follows the shape of the parameter schema: keys in + // alphabetical order, optional keys skipped in place, nested objects and arrays + // shaped the same way, any other value accepted as written. + common_chat_tool shape_tool{ + /* .name = */ "shape", + /* .description = */ "Schema-shaped arguments", + /* .parameters = */ R"({ + "type": "object", + "properties": { + "path": {"type": "string"}, + "edits": { + "type": "array", + "items": { + "type": "object", + "properties": { + "oldText": {"type": "string"}, + "newText": {"type": "string"} + }, + "required": ["oldText", "newText"] + } + }, + "mode": {"type": "string", "enum": ["fast", "safe"]}, + "count": {"type": "integer"}, + "headers": { + "type": "object", + "properties": { + "content-type": {"type": "string"}, + "accept:lang": {"type": "string"} + } + }, + "options": {"type": "object"} + }, + "required": ["path", "edits"] + })", + }; + + tst.test( + "<|tool_call>call:shape{edits:[{newText:<|\"|>b<|\"|>,oldText:<|\"|>a<|\"|>}],path:<|\"|>f.c<|\"|>}") + .tools({ shape_tool }) + .expect(message_with_tool_calls("shape", R"({"edits":[{"newText":"b","oldText":"a"}],"path":"f.c"})")) + .run(); + + // Optional keys in place, quoted keys that are not identifiers + tst.test( + "<|tool_call>call:shape{count:3,edits:[],headers:{<|\"|>accept:lang<|\"|>:<|\"|>en<|\"|>,'content-type':<|\"|>text<|\"|>},mode:<|\"|>fast<|\"|>,options:{b:1,a:[true]},path:<|\"|>f<|\"|>}") + .tools({ shape_tool }) + .expect(message_with_tool_calls("shape", R"({"count":3,"edits":[],"headers":{"accept:lang":"en","content-type":"text"},"mode":"fast","options":{"b":1,"a":[true]},"path":"f"})")) + .run(); + + tst.test( + "<|tool_call>call:shape{edits:[],headers:{\"content-type\":<|\"|>text<|\"|>},path:<|\"|>f<|\"|>}") + .tools({ shape_tool }) + .expect(message_with_tool_calls("shape", R"({"edits":[],"headers":{"content-type":"text"},"path":"f"})")) + .run(); + // Edge cases tst.test( "<|channel>thought\nHello, world!\nWhat's up?") diff --git a/tests/test-fp8.cpp b/tests/test-fp8.cpp index d66c2140ce07..dfd8ac5419c8 100644 --- a/tests/test-fp8.cpp +++ b/tests/test-fp8.cpp @@ -2,7 +2,6 @@ #include "log.h" #include "ggml.h" #include "ggml-backend.h" -#include "ggml-cpu.h" #include "ggml-cpp.h" #include "gguf.h" #include "llama.h" @@ -465,6 +464,13 @@ static void check_fp8_attention(llama_model * model, bool offload_kqv = true) { } static void check_fp8_context_shift(llama_model * model) { + ggml_backend_ptr backend(ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr)); + GGML_ASSERT(backend); + auto * reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(backend.get())); + auto set_n_threads = (ggml_backend_set_n_threads_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_n_threads"); + GGML_ASSERT(set_n_threads); + set_n_threads(backend.get(), 1); + ggml_context_ptr scale_ctx(ggml_init({ 4096, nullptr, true })); ggml_tensor * scale = ggml_new_tensor_1d(scale_ctx.get(), GGML_TYPE_F32, 1); ggml_backend_buffer_ptr scale_buf(ggml_backend_alloc_ctx_tensors_from_buft(scale_ctx.get(), ggml_backend_cpu_buffer_type())); @@ -501,7 +507,7 @@ static void check_fp8_context_shift(llama_model * model) { ggml_tensor * keys = ggml_new_tensor_3d(ctx.get(), GGML_TYPE_F32, hp.n_embd_head_k(), hp.n_head_kv(), kv->get_size()); ggml_get_type_traits(GGML_TYPE_F8_E4M3)->to_float(before.data(), (float *) keys->data, ggml_nelements(keys)); ggml_tensor * shifts = ggml_new_tensor_1d(ctx.get(), GGML_TYPE_I32, kv->get_size()); - ggml_set_i32(shifts, 0); + std::fill_n(static_cast(shifts->data), ggml_nelements(shifts), 0); for (int i = 1; i < 4; ++i) { ((int32_t *) shifts->data)[i] = -1; } @@ -510,7 +516,7 @@ static void check_fp8_context_shift(llama_model * model) { cp.yarn_ext_factor, cp.yarn_attn_factor, cp.yarn_beta_fast, cp.yarn_beta_slow); ggml_cgraph * gf = ggml_new_graph(ctx.get()); ggml_build_forward_expand(gf, expected_f32); - GGML_ASSERT(ggml_graph_compute_with_ctx(ctx.get(), gf, 1) == GGML_STATUS_SUCCESS); + GGML_ASSERT(ggml_backend_graph_compute(backend.get(), gf) == GGML_STATUS_SUCCESS); std::vector expected(before.size()); ggml_quantize_chunk(GGML_TYPE_F8_E4M3, (float *) expected_f32->data, expected.data(), 0, ggml_nelements(expected_f32)/keys->ne[0], keys->ne[0], nullptr); diff --git a/tests/test-jinja.cpp b/tests/test-jinja.cpp index ce5a9749ba94..c79b0d24b873 100644 --- a/tests/test-jinja.cpp +++ b/tests/test-jinja.cpp @@ -3,6 +3,7 @@ #include #include +#include "chat-tts-norm.h" #include "json.h" #include "subproc.h" @@ -16,8 +17,8 @@ using json = common_json; -static void test_template(testing & t, const std::string & name, const std::string & tmpl, const json & vars, const std::string & expect); -static void test_template_error(testing & t, const std::string & name, const std::string & tmpl, const std::string & expect); +static void test_template(testing & t, const std::string & name, const std::string & tmpl, const json & vars, const std::string & expect, bool tts_norm = false); +static void test_template_error(testing & t, const std::string & name, const std::string & tmpl, const std::string & expect, bool tts_norm = false); static void test_whitespace_control(testing & t); static void test_conditionals(testing & t); @@ -39,6 +40,7 @@ static void test_stats(testing & t); static void test_caps(testing & t); static void test_string_parts(testing & t); static void test_fuzzing(testing & t); +static void test_tts_norm_patterns(testing & t); static bool g_python_mode = false; @@ -75,6 +77,7 @@ int main(int argc, char *argv[]) { t.test("string methods", test_string_methods); t.test("array methods", test_array_methods); t.test("object methods", test_object_methods); + t.test("tts norm patterns", test_tts_norm_patterns); if (!g_python_mode) { t.test("hasher", test_hasher); t.test("stats", test_stats); @@ -169,6 +172,18 @@ static void test_conditionals(testing & t) { "big" ); + test_template(t, "chained comparison", + "{{ 1 <= x <= 100 }},{{ 1 <= y <= 100 }},{{ 1 < 2 < 3 < 2 }},{{ 1 == 1 != 2 }},{{ 'a' in 'apple' == 'apple' }}", + {{"x", 42}, {"y", 500}}, + "True,False,False,True,True" + ); + + test_template(t, "chained comparison short circuit", + "{{ 2 < 1 < y }}", + json::object(), + "False" + ); + test_template(t, "object comparison", "{% if {0: 1, none: 2, 1.0: 3, '0': 4, true: 5} == {false: 1, none: 2, 1: 5, '0': 4} %}equal{% endif %}", json::object(), @@ -1318,6 +1333,18 @@ static void test_macros(testing & t) { "Hello, John Smith,Hi, Jane Doe" ); + test_template(t, "macro with unpacked args", + "{% macro add(a, b, c=0) %}{{ a + b + c }}{% endmacro %}{{ add(*[1, 2]) }},{{ add(1, **{'b': 2, 'c': 3}) }},{{ add(*xs, **kw) }}", + {{"xs", json::array({1, 2})}, {"kw", {{"c", 5}}}}, + "3,6,8" + ); + + test_template(t, "filter with unpacked args", + "{{ 'a-b' | replace(*['-', '+']) }}", + json::object(), + "a+b" + ); + test_template(t, "macro with caller", "\ {%- macro nest_dict(o, i, ff='') %}\n\ @@ -2426,6 +2453,12 @@ static void test_object_methods(testing & t) { {{"obj", {{"a", 3}, {"b", 1}}}}, "{\"a\": 3, \"b\": 1, \"c\": 2}" ); + + test_template(t, "dict from dict and unpacked kwargs", + "{% set o = dict(obj, **{k: 2}) %}{{ o|tojson }}", + {{"obj", {{"a", 3}, {"b", 1}}}, {"k", "c"}}, + "{\"a\": 3, \"b\": 1, \"c\": 2}" + ); } static void test_hasher(testing & t) { @@ -2713,13 +2746,134 @@ static void test_string_parts(testing & t) { } -static void test_template_error(testing & t, const std::string & name, const std::string & tmpl, const std::string & expect) { - t.test(name, [&tmpl, &expect](testing & t) { +// TTS normalization patterns: tts_norm_scan() and tts_norm_sub(), see docs/tts-norm-patterns.md +// these functions are only available to task templates (e.g. "tts"), so every test here passes tts_norm = true +static void test_tts_norm_patterns(testing & t) { + test_template(t, "not available without tts norm builtins", + "{{ tts_norm_scan is defined }}", + json::object(), + "False"); + + test_template(t, "tts_norm_scan splits text into matched and unmatched segments", + "{%- for s in tts_norm_scan(text, [['num', '%d+'], ['word', '%a+']]) -%}[{{ s.rule or '-' }}:{{ s.text }}]{%- endfor -%}", + {{"text", "abc 123, x9"}}, + "[word:abc][-: ][num:123][-:, ][word:x][num:9]", true); + + test_template(t, "tts_norm_scan groups, optional group that did not match is empty", + "{%- for s in tts_norm_scan(text, [['money', '%$(%d+)(?:%.(%d%d))?']]) -%}" + "{%- if s.rule -%}{%- set whole, cents = s.groups -%}{{ whole }}|{{ cents }}|{{ s.groups | length }};{%- endif -%}" + "{%- endfor -%}", + {{"text", "$3.50 and $7"}}, + "3|50|2;7||2;", true); + + test_template(t, "tts_norm_scan rules as dict, the first rule that matches wins", + "{%- for s in tts_norm_scan(text, {'ordinal': '%d+(?:st|nd|rd|th)%b', 'number': '%d+'}) -%}" + "{%- if s.rule -%}<{{ s.rule }}:{{ s.text }}>{%- else -%}{{ s.text }}{%- endif -%}" + "{%- endfor -%}", + {{"text", "the 3rd of 10 or 4three"}}, + "the of or three", true); + + // unlike regex, a failed sequence does not retry the other branches: (?:a|ab)c never matches "abc" + test_template(t, "ordered alternation commits to the first branch that matches", + "{%- for s in tts_norm_scan(text, '(?:a|ab)c') -%}[{{ s.rule or '-' }}:{{ s.text }}]{%- endfor -%}", + {{"text", "abc ac"}}, + "[-:abc ][match:ac]", true); + + // unlike regex, quantifiers never give back what they consumed: %d+0 never matches + test_template(t, "quantifiers are possessive", + "{{ tts_norm_sub(text, '%d+0', 'X') }}|{{ tts_norm_sub(text, '%d+', 'X') }}", + {{"text", "100 20"}}, + "100 20|X X", true); + + test_template(t, "quantifier ranges", + "{{ tts_norm_sub(text, '%d{3}-%d{2,}', '#') }}", + {{"text", "123-4 123-45 123-456789"}}, + "123-4 # #", true); + + test_template(t, "lookbehind: a minus sign is not part of a word", + "{{ tts_norm_sub(text, '(?') }}|{{ tts_norm_sub(text, '[^%w%s]', '') }}", + {{"text", "€ 5 & $6!"}}, + "<5> & <6>!| 5 6", true); + + test_template(t, "remove spaces between Han characters", + "{{ tts_norm_sub(text, '(%h) +(%h)', '%1%2') }}", + {{"text", "你 好 world 世界"}}, + "你好 world 世界", true); + + test_template(t, "mini text normalizer", + "{%- set ones = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'," + " 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] -%}\n" + "{%- set tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] -%}\n" + "{%- macro num(n) -%}{{ ones[n] if n < 20 else tens[(n / 10) | int] ~ ('-' ~ ones[n % 10] if n % 10 else '') }}{%- endmacro -%}\n" + "{%- for s in tts_norm_scan(text, [\n" + " ['money', '%$(%d+)(?:%.(%d%d))?'],\n" + " ['percent', '(%d+)%%'],\n" + " ['time', '(%d%d?):(%d%d)(?!%d)'],\n" + " ['neg', '(?a)') }}", "unknown group type", true); + test_template_error(t, "error: wide lookbehind", "{{ tts_norm_scan('x', '(?<=ab)c') }}", "lookbehind must contain exactly one codepoint matcher", true); + test_template_error(t, "error: missing group in replacement", "{{ tts_norm_sub('x', '(a)', '%2') }}", "group %2 does not exist", true); + test_template_error(t, "error: bad rules", "{{ tts_norm_scan('x', 1) }}", "rules must be a string, a dict or a list", true); + } +} + +static void test_template_error(testing & t, const std::string & name, const std::string & tmpl, const std::string & expect, bool tts_norm) { + t.test(name, [&tmpl, &expect, tts_norm](testing & t) { std::string error; try { jinja::lexer lexer; jinja::program ast = jinja::parse_from_tokens(lexer.tokenize(tmpl)); jinja::context ctx(tmpl); + if (tts_norm) { + common_chat_tts_norm_add_builtins(ctx); + } jinja::runtime runtime(ctx); runtime.gather_string_parts(runtime.execute(ast)); } catch (const std::exception & e) { @@ -2729,14 +2883,17 @@ static void test_template_error(testing & t, const std::string & name, const std }); } -static void test_template_cpp(testing & t, const std::string & name, const std::string & tmpl, const json & vars, const std::string & expect) { - t.test(name, [&tmpl, &vars, &expect](testing & t) { +static void test_template_cpp(testing & t, const std::string & name, const std::string & tmpl, const json & vars, const std::string & expect, bool tts_norm) { + t.test(name, [&tmpl, &vars, &expect, tts_norm](testing & t) { jinja::lexer lexer; auto lexer_res = lexer.tokenize(tmpl); jinja::program ast = jinja::parse_from_tokens(lexer_res); jinja::context ctx(tmpl); + if (tts_norm) { + common_chat_tts_norm_add_builtins(ctx); + } jinja::global_from_json(ctx, vars, true); jinja::runtime runtime(ctx); @@ -2788,17 +2945,36 @@ env.filters["tojson"] = lambda x, ensure_ascii=False, indent=None, separators=No env.globals["strftime_now"] = lambda format: datetime.now().strftime(format) env.globals["raise_exception"] = raise_exception +if merged_input.get("tts_norm_ref"): + import importlib.util + spec = importlib.util.spec_from_file_location("chat_tts_norm", merged_input["tts_norm_ref"]) + chat_tts_norm = importlib.util.module_from_spec(spec) + sys.modules["chat_tts_norm"] = chat_tts_norm # required by dataclasses + spec.loader.exec_module(chat_tts_norm) + env.globals["tts_norm_scan"] = chat_tts_norm.tts_norm_scan + env.globals["tts_norm_sub"] = chat_tts_norm.tts_norm_sub + template = env.from_string(tmpl) result = template.render(**vars_json) sys.stdout.buffer.write(result.encode()) )"; -static void test_template_py(testing & t, const std::string & name, const std::string & tmpl, const json & vars, const std::string & expect) { - t.test(name, [&tmpl, &vars, &expect](testing & t) { +// python reference of the TTS normalization patterns, relative to this file +static std::string tts_norm_ref_path() { + std::string path = __FILE__; + const size_t pos = path.find_last_of("/\\"); + return (pos == std::string::npos ? std::string(".") : path.substr(0, pos)) + "/../scripts/chat_tts_norm.py"; +} + +static void test_template_py(testing & t, const std::string & name, const std::string & tmpl, const json & vars, const std::string & expect, bool tts_norm) { + t.test(name, [&tmpl, &vars, &expect, tts_norm](testing & t) { // Prepare arguments json merged; merged["tmpl"] = json(tmpl); merged["vars"] = vars; + if (tts_norm) { + merged["tts_norm_ref"] = tts_norm_ref_path(); + } #ifdef _WIN32 const char * python_executable = "python.exe"; @@ -2859,11 +3035,11 @@ static void test_template_py(testing & t, const std::string & name, const std::s }); } -static void test_template(testing & t, const std::string & name, const std::string & tmpl, const json & vars, const std::string & expect) { +static void test_template(testing & t, const std::string & name, const std::string & tmpl, const json & vars, const std::string & expect, bool tts_norm) { if (g_python_mode) { - test_template_py(t, name, tmpl, vars, expect); + test_template_py(t, name, tmpl, vars, expect, tts_norm); } else { - test_template_cpp(t, name, tmpl, vars, expect); + test_template_cpp(t, name, tmpl, vars, expect, tts_norm); } } diff --git a/tests/test-quantize-be.sh b/tests/test-quantize-be.sh index ba2d923d2286..2840b79d47f0 100755 --- a/tests/test-quantize-be.sh +++ b/tests/test-quantize-be.sh @@ -34,7 +34,7 @@ if [ "$(uname -m)" != s390x ]; then exit 1 fi -MODEL_URL=https://huggingface.co/ggml-org/models/resolve/499bc8821c6b12b4e53c5bffcb21ec206f212d81/tinyllamas/stories15M.gguf +MODEL_URL=https://huggingface.co/ggml-org-dev/stories15M/resolve/main/stories15M.gguf MODEL_SHA256=61b50d457809a5194818fd22e6724b456cd7bb9a6264c52c8110684c53f3704a F32_SHA256=55174d7a7d46f29fc6be163ccb040330c357aa727b22ec13e2c5d713e5ba5b76 diff --git a/tests/test-tokenizer-random.py b/tests/test-tokenizer-random.py index 8fc476b63c3f..7f5ea3f45684 100644 --- a/tests/test-tokenizer-random.py +++ b/tests/test-tokenizer-random.py @@ -80,7 +80,7 @@ def __init__(self, libllama: LibLlama, path_model: str, mparams={}, cparams={}): raise RuntimeError("error: failed to load model '%s'" % path_model) if isinstance(cparams, dict): cparams = libllama.context_default_params(**cparams) - self.ctx = self.lib.llama_new_context_with_model(self.model, cparams) + self.ctx = self.lib.llama_init_from_model(self.model, cparams) if not self.ctx: raise RuntimeError("error: failed to create context for model '%s'" % path_model) n_tokens_max = self.lib.llama_n_ctx(self.ctx) diff --git a/tools/cli/README.md b/tools/cli/README.md index 8e9f057f8507..475becd2edfc 100644 --- a/tools/cli/README.md +++ b/tools/cli/README.md @@ -50,9 +50,8 @@ | `-kvo, --kv-offload, -nkvo, --no-kv-offload` | whether to enable KV cache offloading (default: enabled)
(env: LLAMA_ARG_KV_OFFLOAD) | | `--repack, -nr, --no-repack` | whether to enable weight repacking (default: enabled)
(env: LLAMA_ARG_REPACK) | | `--no-host` | bypass host buffer allowing extra buffers to be used
(env: LLAMA_ARG_NO_HOST) | -| `-ctk, --cache-type-k TYPE` | KV cache data type for K
allowed values: f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_CACHE_TYPE_K) | -| `-ctv, --cache-type-v TYPE` | KV cache data type for V
allowed values: f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_CACHE_TYPE_V) | -| `-dt, --defrag-thold N` | KV cache defragmentation threshold (DEPRECATED)
(env: LLAMA_ARG_DEFRAG_THOLD) | +| `-ctk, --cache-type-k TYPE` | KV cache data type for K
allowed values: f32, f16, bf16, f8_e4m3, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_CACHE_TYPE_K) | +| `-ctv, --cache-type-v TYPE` | KV cache data type for V
allowed values: f32, f16, bf16, f8_e4m3, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_CACHE_TYPE_V) | | `-np, --parallel N` | number of parallel sequences to decode (default: 1)
(env: LLAMA_ARG_N_PARALLEL) | | `--rpc SERVERS` | comma-separated list of RPC servers (host:port)
(env: LLAMA_ARG_RPC) | | `-lm, --load-mode MODE` | model loading mode (default: auto)
- auto: mmap, unless a device does not support it
- none: no special loading mode
- mmap: memory-map model (if mmap disabled, slower load but may reduce pageouts if not using mlock)
- mlock: force system to keep model in RAM rather than swapping or compressing
- mmap+mlock: mmap + force system to keep model in RAM rather than swapping or compressing
- dio: use DirectIO if available

(env: LLAMA_ARG_LOAD_MODE) | @@ -82,6 +81,7 @@ | `--control-vector-scaled FNAME:SCALE,...` | add a control vector with user defined scaling SCALE
note: use comma-separated values (format: FNAME:SCALE,...) | | `--control-vector-layer-range START END` | layer range to apply the control vector(s) to, start and end inclusive | | `-m, --model FNAME` | model path to load
(env: LLAMA_ARG_MODEL) | +| `--ple, --shard FNAME,...` | extra GGUF shards for the model, comma separated; may be given more than once
paths may live anywhere, including on different drives; --ple is an alias for --shard
(env: LLAMA_ARG_SHARD) | | `-mu, --model-url MODEL_URL` | model download url (default: unused)
(env: LLAMA_ARG_MODEL_URL) | | `-dr, --docker-repo [/][:quant]` | Docker Hub model repository. repo is optional, default to ai/. quant is optional, default to :latest.
example: gemma3
(default: unused)
(env: LLAMA_ARG_DOCKER_REPO) | | `-hf, -hfr, --hf-repo /[:quant]` | Hugging Face model repository; quant is optional, case-insensitive, default to Q4_K_M, or falls back to the first file in the repo if Q4_K_M doesn't exist.
mmproj is also downloaded automatically if available. to disable, add --no-mmproj
example: ggml-org/GLM-4.7-Flash-GGUF:Q4_K_M
(default: unused)
(env: LLAMA_ARG_HF_REPO) | @@ -96,8 +96,8 @@ | `-lv, --verbosity, --log-verbosity N` | Set the verbosity threshold. Messages with a higher verbosity will be ignored. Values:
- 0: generic output
- 1: error
- 2: warning
- 3: info
- 4: trace (more info)
- 5: debug
(default: 3)

(env: LLAMA_ARG_LOG_VERBOSITY) | | `--log-prefix, --no-log-prefix` | Enable prefix in log messages
(env: LLAMA_ARG_LOG_PREFIX) | | `--log-timestamps, --no-log-timestamps` | Enable timestamps in log messages
(env: LLAMA_ARG_LOG_TIMESTAMPS) | -| `--spec-draft-type-k, -ctkd, --cache-type-k-draft TYPE` | KV cache data type for K for the draft model
allowed values: f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K) | -| `--spec-draft-type-v, -ctvd, --cache-type-v-draft TYPE` | KV cache data type for V for the draft model
allowed values: f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_V) | +| `--spec-draft-type-k, -ctkd, --cache-type-k-draft TYPE` | KV cache data type for K for the draft model
allowed values: f32, f16, bf16, f8_e4m3, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K) | +| `--spec-draft-type-v, -ctvd, --cache-type-v-draft TYPE` | KV cache data type for V for the draft model
allowed values: f32, f16, bf16, f8_e4m3, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_V) | ### Sampling params @@ -178,7 +178,7 @@ | `--reasoning-effort LEVEL` | reasoning effort level given to the chat template: 'default' to keep the template default,
or a level such as 'minimal', 'low', 'medium', 'high', 'xhigh' or 'max' (default: default)
(env: LLAMA_ARG_REASONING_EFFORT) | | `--reasoning-budget N` | token budget for thinking: -1 for unrestricted, 0 for immediate end, N>0 for token budget (default: -1)
(env: LLAMA_ARG_THINK_BUDGET) | | `--reasoning-budget-message MESSAGE` | message injected before the end-of-thinking tag when reasoning budget is exhausted (default: none)
(env: LLAMA_ARG_THINK_BUDGET_MESSAGE) | -| `--reasoning-preserve, --no-reasoning-preserve` | preserve reasoning trace in the full history, not just the last assistant message (default: template default)
compatible with certain templates having 'supports_preserve_reasoning' capability
example: https://docs.z.ai/guides/capabilities/thinking-mode#preserved-thinking
(env: LLAMA_ARG_REASONING_PRESERVE) | +| `--reasoning-preserve, --no-reasoning-preserve` | preserve reasoning trace in the full history, not just the last assistant message (default: enabled)
compatible with certain templates having 'supports_preserve_reasoning' capability
example: https://docs.z.ai/guides/capabilities/thinking-mode#preserved-thinking
(env: LLAMA_ARG_REASONING_PRESERVE) | | `--chat-template JINJA_TEMPLATE` | set custom jinja chat template (default: template taken from model's metadata)
if suffix/prefix are specified, template will be disabled
only commonly used templates are accepted (unless --jinja is set before this flag):
list of built-in templates:
bailing, bailing-think, bailing2, chatglm3, chatglm4, chatml, command-r, deepseek, deepseek-ocr, deepseek2, deepseek3, exaone-moe, exaone3, exaone4, falcon3, gemma, gigachat, glmedge, gpt-oss, granite, granite-4.0, granite-4.1, grok-2, hunyuan-dense, hunyuan-moe, hunyuan-vl, kimi-k2, llama2, llama2-sys, llama2-sys-bos, llama2-sys-strip, llama3, llama4, megrez, minicpm, mistral-v1, mistral-v3, mistral-v3-tekken, mistral-v7, mistral-v7-tekken, monarch, openchat, orion, pangu-embedded, phi3, phi4, rwkv-world, seed_oss, smolvlm, solar-open, vicuna, vicuna-orca, yandex, zephyr
(env: LLAMA_ARG_CHAT_TEMPLATE) | | `--chat-template-file JINJA_TEMPLATE_FILE` | set custom jinja chat template file (default: template taken from model's metadata)
if suffix/prefix are specified, template will be disabled
only commonly used templates are accepted (unless --jinja is set before this flag):
list of built-in templates:
bailing, bailing-think, bailing2, chatglm3, chatglm4, chatml, command-r, deepseek, deepseek-ocr, deepseek2, deepseek3, exaone-moe, exaone3, exaone4, falcon3, gemma, gigachat, glmedge, gpt-oss, granite, granite-4.0, granite-4.1, grok-2, hunyuan-dense, hunyuan-moe, hunyuan-vl, kimi-k2, llama2, llama2-sys, llama2-sys-bos, llama2-sys-strip, llama3, llama4, megrez, minicpm, mistral-v1, mistral-v3, mistral-v3-tekken, mistral-v7, mistral-v7-tekken, monarch, openchat, orion, pangu-embedded, phi3, phi4, rwkv-world, seed_oss, smolvlm, solar-open, vicuna, vicuna-orca, yandex, zephyr
(env: LLAMA_ARG_CHAT_TEMPLATE_FILE) | | `--skip-chat-parsing, --no-skip-chat-parsing` | force a pure content parser, even if a Jinja template is specified; model will output everything in the content section, including any reasoning and/or tool calls (default: disabled)
(env: LLAMA_ARG_SKIP_CHAT_PARSING) | diff --git a/tools/completion/README.md b/tools/completion/README.md index 9b824f968ae2..cc6aae3d04d9 100644 --- a/tools/completion/README.md +++ b/tools/completion/README.md @@ -133,9 +133,8 @@ llama-completion.exe -m models\gemma-1.1-7b-it.Q4_K_M.gguf --ignore-eos -n -1 | `-kvo, --kv-offload, -nkvo, --no-kv-offload` | whether to enable KV cache offloading (default: enabled)
(env: LLAMA_ARG_KV_OFFLOAD) | | `--repack, -nr, --no-repack` | whether to enable weight repacking (default: enabled)
(env: LLAMA_ARG_REPACK) | | `--no-host` | bypass host buffer allowing extra buffers to be used
(env: LLAMA_ARG_NO_HOST) | -| `-ctk, --cache-type-k TYPE` | KV cache data type for K
allowed values: f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_CACHE_TYPE_K) | -| `-ctv, --cache-type-v TYPE` | KV cache data type for V
allowed values: f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_CACHE_TYPE_V) | -| `-dt, --defrag-thold N` | KV cache defragmentation threshold (DEPRECATED)
(env: LLAMA_ARG_DEFRAG_THOLD) | +| `-ctk, --cache-type-k TYPE` | KV cache data type for K
allowed values: f32, f16, bf16, f8_e4m3, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_CACHE_TYPE_K) | +| `-ctv, --cache-type-v TYPE` | KV cache data type for V
allowed values: f32, f16, bf16, f8_e4m3, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_CACHE_TYPE_V) | | `-np, --parallel N` | number of parallel sequences to decode (default: 1)
(env: LLAMA_ARG_N_PARALLEL) | | `--rpc SERVERS` | comma-separated list of RPC servers (host:port)
(env: LLAMA_ARG_RPC) | | `-lm, --load-mode MODE` | model loading mode (default: auto)
- auto: mmap, unless a device does not support it
- none: no special loading mode
- mmap: memory-map model (if mmap disabled, slower load but may reduce pageouts if not using mlock)
- mlock: force system to keep model in RAM rather than swapping or compressing
- mmap+mlock: mmap + force system to keep model in RAM rather than swapping or compressing
- dio: use DirectIO if available

(env: LLAMA_ARG_LOAD_MODE) | @@ -165,6 +164,7 @@ llama-completion.exe -m models\gemma-1.1-7b-it.Q4_K_M.gguf --ignore-eos -n -1 | `--control-vector-scaled FNAME:SCALE,...` | add a control vector with user defined scaling SCALE
note: use comma-separated values (format: FNAME:SCALE,...) | | `--control-vector-layer-range START END` | layer range to apply the control vector(s) to, start and end inclusive | | `-m, --model FNAME` | model path to load
(env: LLAMA_ARG_MODEL) | +| `--ple, --shard FNAME,...` | extra GGUF shards for the model, comma separated; may be given more than once
paths may live anywhere, including on different drives; --ple is an alias for --shard
(env: LLAMA_ARG_SHARD) | | `-mu, --model-url MODEL_URL` | model download url (default: unused)
(env: LLAMA_ARG_MODEL_URL) | | `-dr, --docker-repo [/][:quant]` | Docker Hub model repository. repo is optional, default to ai/. quant is optional, default to :latest.
example: gemma3
(default: unused)
(env: LLAMA_ARG_DOCKER_REPO) | | `-hf, -hfr, --hf-repo /[:quant]` | Hugging Face model repository; quant is optional, case-insensitive, default to Q4_K_M, or falls back to the first file in the repo if Q4_K_M doesn't exist.
mmproj is also downloaded automatically if available. to disable, add --no-mmproj
example: ggml-org/GLM-4.7-Flash-GGUF:Q4_K_M
(default: unused)
(env: LLAMA_ARG_HF_REPO) | @@ -179,8 +179,8 @@ llama-completion.exe -m models\gemma-1.1-7b-it.Q4_K_M.gguf --ignore-eos -n -1 | `-lv, --verbosity, --log-verbosity N` | Set the verbosity threshold. Messages with a higher verbosity will be ignored. Values:
- 0: generic output
- 1: error
- 2: warning
- 3: info
- 4: trace (more info)
- 5: debug
(default: 3)

(env: LLAMA_ARG_LOG_VERBOSITY) | | `--log-prefix, --no-log-prefix` | Enable prefix in log messages
(env: LLAMA_ARG_LOG_PREFIX) | | `--log-timestamps, --no-log-timestamps` | Enable timestamps in log messages
(env: LLAMA_ARG_LOG_TIMESTAMPS) | -| `--spec-draft-type-k, -ctkd, --cache-type-k-draft TYPE` | KV cache data type for K for the draft model
allowed values: f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K) | -| `--spec-draft-type-v, -ctvd, --cache-type-v-draft TYPE` | KV cache data type for V for the draft model
allowed values: f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_V) | +| `--spec-draft-type-k, -ctkd, --cache-type-k-draft TYPE` | KV cache data type for K for the draft model
allowed values: f32, f16, bf16, f8_e4m3, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K) | +| `--spec-draft-type-v, -ctvd, --cache-type-v-draft TYPE` | KV cache data type for V for the draft model
allowed values: f32, f16, bf16, f8_e4m3, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_V) | ### Sampling params @@ -256,7 +256,7 @@ llama-completion.exe -m models\gemma-1.1-7b-it.Q4_K_M.gguf --ignore-eos -n -1 | `--reasoning-effort LEVEL` | reasoning effort level given to the chat template: 'default' to keep the template default,
or a level such as 'minimal', 'low', 'medium', 'high', 'xhigh' or 'max' (default: default)
(env: LLAMA_ARG_REASONING_EFFORT) | | `--reasoning-budget N` | token budget for thinking: -1 for unrestricted, 0 for immediate end, N>0 for token budget (default: -1)
(env: LLAMA_ARG_THINK_BUDGET) | | `--reasoning-budget-message MESSAGE` | message injected before the end-of-thinking tag when reasoning budget is exhausted (default: none)
(env: LLAMA_ARG_THINK_BUDGET_MESSAGE) | -| `--reasoning-preserve, --no-reasoning-preserve` | preserve reasoning trace in the full history, not just the last assistant message (default: template default)
compatible with certain templates having 'supports_preserve_reasoning' capability
example: https://docs.z.ai/guides/capabilities/thinking-mode#preserved-thinking
(env: LLAMA_ARG_REASONING_PRESERVE) | +| `--reasoning-preserve, --no-reasoning-preserve` | preserve reasoning trace in the full history, not just the last assistant message (default: enabled)
compatible with certain templates having 'supports_preserve_reasoning' capability
example: https://docs.z.ai/guides/capabilities/thinking-mode#preserved-thinking
(env: LLAMA_ARG_REASONING_PRESERVE) | | `--chat-template JINJA_TEMPLATE` | set custom jinja chat template (default: template taken from model's metadata)
if suffix/prefix are specified, template will be disabled
only commonly used templates are accepted (unless --jinja is set before this flag):
list of built-in templates:
bailing, bailing-think, bailing2, chatglm3, chatglm4, chatml, command-r, deepseek, deepseek-ocr, deepseek2, deepseek3, exaone-moe, exaone3, exaone4, falcon3, gemma, gigachat, glmedge, gpt-oss, granite, granite-4.0, granite-4.1, grok-2, hunyuan-dense, hunyuan-moe, hunyuan-vl, kimi-k2, llama2, llama2-sys, llama2-sys-bos, llama2-sys-strip, llama3, llama4, megrez, minicpm, mistral-v1, mistral-v3, mistral-v3-tekken, mistral-v7, mistral-v7-tekken, monarch, openchat, orion, pangu-embedded, phi3, phi4, rwkv-world, seed_oss, smolvlm, solar-open, vicuna, vicuna-orca, yandex, zephyr
(env: LLAMA_ARG_CHAT_TEMPLATE) | | `--chat-template-file JINJA_TEMPLATE_FILE` | set custom jinja chat template file (default: template taken from model's metadata)
if suffix/prefix are specified, template will be disabled
only commonly used templates are accepted (unless --jinja is set before this flag):
list of built-in templates:
bailing, bailing-think, bailing2, chatglm3, chatglm4, chatml, command-r, deepseek, deepseek-ocr, deepseek2, deepseek3, exaone-moe, exaone3, exaone4, falcon3, gemma, gigachat, glmedge, gpt-oss, granite, granite-4.0, granite-4.1, grok-2, hunyuan-dense, hunyuan-moe, hunyuan-vl, kimi-k2, llama2, llama2-sys, llama2-sys-bos, llama2-sys-strip, llama3, llama4, megrez, minicpm, mistral-v1, mistral-v3, mistral-v3-tekken, mistral-v7, mistral-v7-tekken, monarch, openchat, orion, pangu-embedded, phi3, phi4, rwkv-world, seed_oss, smolvlm, solar-open, vicuna, vicuna-orca, yandex, zephyr
(env: LLAMA_ARG_CHAT_TEMPLATE_FILE) | | `--skip-chat-parsing, --no-skip-chat-parsing` | force a pure content parser, even if a Jinja template is specified; model will output everything in the content section, including any reasoning and/or tool calls (default: disabled)
(env: LLAMA_ARG_SKIP_CHAT_PARSING) | diff --git a/tools/fit-params/fit-params.cpp b/tools/fit-params/fit-params.cpp index 3dc46069ca9a..99082e51bc1a 100644 --- a/tools/fit-params/fit-params.cpp +++ b/tools/fit-params/fit-params.cpp @@ -1,5 +1,4 @@ #include "llama.h" -#include "../src/llama-ext.h" #include "arg.h" #include "common.h" diff --git a/tools/imatrix/imatrix.cpp b/tools/imatrix/imatrix.cpp index 2122bf59467f..7abd83eadcb1 100644 --- a/tools/imatrix/imatrix.cpp +++ b/tools/imatrix/imatrix.cpp @@ -1,5 +1,4 @@ #include "llama.h" -#include "../src/llama-ext.h" #include "arg.h" #include "common.h" diff --git a/tools/mtmd/models/llava.cpp b/tools/mtmd/models/llava.cpp index f4f31ffdbe21..8e8c7638bd84 100644 --- a/tools/mtmd/models/llava.cpp +++ b/tools/mtmd/models/llava.cpp @@ -167,10 +167,8 @@ ggml_cgraph * mtmd_graph_llava::build() { embeddings = ggml_add(ctx0, embeddings, model.mm_0_b); embeddings = ggml_gelu(ctx0, embeddings); - if (model.mm_2_w) { - embeddings = build_mm(model.mm_2_w, embeddings); - embeddings = ggml_add(ctx0, embeddings, model.mm_2_b); - } + embeddings = build_mm(model.mm_2_w, embeddings); + embeddings = ggml_add(ctx0, embeddings, model.mm_2_b); } else if (proj_type == PROJECTOR_TYPE_MLP_NORM) { embeddings = build_mm(model.mm_0_w, embeddings); diff --git a/tools/mtmd/mtmd-model.cpp b/tools/mtmd/mtmd-model.cpp index 8a76e11b5675..da74ed383340 100644 --- a/tools/mtmd/mtmd-model.cpp +++ b/tools/mtmd/mtmd-model.cpp @@ -662,6 +662,10 @@ struct mtmd_model_loader { hparams.image_resize_pad = PAD_NONE; // the HF processor resizes to the smart_resize size, no padding hparams.image_round_half_even = true; // smart_resize uses Python round() get_u32(KEY_SPATIAL_MERGE_SIZE, hparams.n_merge, false); + if (hparams.n_merge != 2) { + // the temporal merge input and the merger use a 2x2 patch grid + throw std::runtime_error(mtmd_format("%s: spatial_merge_size (%d) must be 2\n", __func__, hparams.n_merge)); + } get_u32(KEY_WIN_ATTN_PATTERN, hparams.n_wa_pattern, model.proj_type == PROJECTOR_TYPE_QWEN25VL); // only 2.5 requires it // ref: https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct/blob/main/preprocessor_config.json hparams.set_limit_image_tokens(8, 4096); @@ -1444,8 +1448,15 @@ struct mtmd_model_loader { model.post_ln_w = get_tensor(mtmd_format(TN_LN_POST, prefix, "weight"), false); model.post_ln_b = get_tensor(mtmd_format(TN_LN_POST, prefix, "bias"), false); + // every vision encoder starts with a patch embedding, except the ones with their own stem + const bool has_patch_embd = ( + model.modality == MTMD_MODALITY_VISION && + model.proj_type != PROJECTOR_TYPE_GEMMA3NV && + model.proj_type != PROJECTOR_TYPE_DEEPSEEKOCR && + model.proj_type != PROJECTOR_TYPE_DEEPSEEKOCR2); + model.patch_bias = get_tensor(TN_PATCH_BIAS, false); - model.patch_embeddings_0 = get_tensor(TN_PATCH_EMBD, false); + model.patch_embeddings_0 = get_tensor(TN_PATCH_EMBD, has_patch_embd); model.patch_embeddings_1 = get_tensor(TN_PATCH_EMBD_1, false); model.norm_embd_w = get_tensor(mtmd_format(TN_NORM_EMBD, "weight"), false); @@ -1656,23 +1667,22 @@ struct mtmd_model_loader { case PROJECTOR_TYPE_MLP: case PROJECTOR_TYPE_MLP_NORM: { - // LLaVA projection - model.mm_0_w = get_tensor(mtmd_format(TN_LLAVA_PROJ, 0, "weight"), false); - model.mm_0_b = get_tensor(mtmd_format(TN_LLAVA_PROJ, 0, "bias"), false); - // Yi-type llava - model.mm_1_w = get_tensor(mtmd_format(TN_LLAVA_PROJ, 1, "weight"), false); - model.mm_1_b = get_tensor(mtmd_format(TN_LLAVA_PROJ, 1, "bias"), false); - // missing in Yi-type llava - model.mm_2_w = get_tensor(mtmd_format(TN_LLAVA_PROJ, 2, "weight"), false); - model.mm_2_b = get_tensor(mtmd_format(TN_LLAVA_PROJ, 2, "bias"), false); - // Yi-type llava - model.mm_3_w = get_tensor(mtmd_format(TN_LLAVA_PROJ, 3, "weight"), false); - model.mm_3_b = get_tensor(mtmd_format(TN_LLAVA_PROJ, 3, "bias"), false); - model.mm_4_w = get_tensor(mtmd_format(TN_LLAVA_PROJ, 4, "weight"), false); - model.mm_4_b = get_tensor(mtmd_format(TN_LLAVA_PROJ, 4, "bias"), false); + // LLaVA projection: mm.0 -> gelu -> mm.2 + // Yi-type llava (MLP_NORM): mm.0 -> norm mm.1 -> gelu -> mm.3 -> norm mm.4 + model.mm_0_w = get_tensor(mtmd_format(TN_LLAVA_PROJ, 0, "weight")); + model.mm_0_b = get_tensor(mtmd_format(TN_LLAVA_PROJ, 0, "bias")); + model.mm_3_w = get_tensor(mtmd_format(TN_LLAVA_PROJ, 3, "weight"), model.proj_type == PROJECTOR_TYPE_MLP_NORM); if (model.mm_3_w) { // TODO: this is a hack to support Yi-type llava model.proj_type = PROJECTOR_TYPE_MLP_NORM; + model.mm_1_w = get_tensor(mtmd_format(TN_LLAVA_PROJ, 1, "weight")); + model.mm_1_b = get_tensor(mtmd_format(TN_LLAVA_PROJ, 1, "bias")); + model.mm_3_b = get_tensor(mtmd_format(TN_LLAVA_PROJ, 3, "bias")); + model.mm_4_w = get_tensor(mtmd_format(TN_LLAVA_PROJ, 4, "weight")); + model.mm_4_b = get_tensor(mtmd_format(TN_LLAVA_PROJ, 4, "bias")); + } else { + model.mm_2_w = get_tensor(mtmd_format(TN_LLAVA_PROJ, 2, "weight")); + model.mm_2_b = get_tensor(mtmd_format(TN_LLAVA_PROJ, 2, "bias")); } model.image_newline = get_tensor(TN_IMAGE_NEWLINE, false); } break; @@ -1921,7 +1931,6 @@ struct mtmd_model_loader { { // reuse tensors already loaded by the common section // (TN_PATCH_EMBD and TN_PATCH_BIAS have the same tensor names) - GGML_ASSERT(model.patch_embeddings_0 && "yasa2 requires v.patch_embd.weight"); model.yasa_patch_w = model.patch_embeddings_0; model.yasa_patch_b = model.patch_bias; model.yasa_patch_ln_w = get_tensor(TN_YASA_PATCH_LN_W, false); @@ -2991,6 +3000,10 @@ struct mtmd_model_loader { model.mm_img_end = get_tensor(TN_MM_IMG_END); model.image_newline = get_tensor(TN_IMAGE_NEWLINE); model.view_seperator = get_tensor(TN_IMAGE_SEPERATOR, false); + // the position embedding is resampled on the host as F32 + if (!model.position_embeddings || model.position_embeddings->type != GGML_TYPE_F32) { + throw std::runtime_error(mtmd_format("%s: HunyuanVL requires an F32 %s\n", __func__, mtmd_format(TN_POS_EMBD, prefix).c_str())); + } } break; case PROJECTOR_TYPE_JANUS_PRO: { @@ -4224,7 +4237,7 @@ int mtmd_model::n_mmproj_embd() const { case PROJECTOR_TYPE_MLP_NORM: return mm_3_b->ne[0]; case PROJECTOR_TYPE_MINICPMV: - return mm_model_proj->ne[0]; + return mm_model_proj->ne[1]; case PROJECTOR_TYPE_MINICPMV4_6: case PROJECTOR_TYPE_MINICPMV4_7: case PROJECTOR_TYPE_MINICPM_OCR_1_0: diff --git a/tools/quantize/quantize.cpp b/tools/quantize/quantize.cpp index 38950036cd82..0debcfddaffa 100644 --- a/tools/quantize/quantize.cpp +++ b/tools/quantize/quantize.cpp @@ -510,7 +510,8 @@ int llama_quantize(int argc, char ** argv) { llama_model_kv_override kvo; std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_FILE); kvo.tag = LLAMA_KV_OVERRIDE_TYPE_STR; - strncpy(kvo.val_str, imatrix_file.c_str(), 127); + const std::string fname_imatrix = std::filesystem::path(imatrix_file).filename().string(); + strncpy(kvo.val_str, fname_imatrix.c_str(), 127); kvo.val_str[127] = '\0'; kv_overrides.emplace_back(std::move(kvo)); } @@ -519,7 +520,8 @@ int llama_quantize(int argc, char ** argv) { // TODO: list multiple datasets when there are more than one std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_DATASET); kvo.tag = LLAMA_KV_OVERRIDE_TYPE_STR; - strncpy(kvo.val_str, imatrix_datasets[0].c_str(), 127); + const std::string fname_dataset = std::filesystem::path(imatrix_datasets[0]).filename().string(); + strncpy(kvo.val_str, fname_dataset.c_str(), 127); kvo.val_str[127] = '\0'; kv_overrides.emplace_back(std::move(kvo)); } diff --git a/tools/server/README-dev.md b/tools/server/README-dev.md index 17b39f0aaaba..85fb3f78eae5 100644 --- a/tools/server/README-dev.md +++ b/tools/server/README-dev.md @@ -201,7 +201,7 @@ Invoke a tool call, request body is a JSON object with: Headers: - `x-tool-cwd`: optional; if set, use as the CWD for tool; this is not part of tool's params because it's meant to be set by the runtime, not the LLM itself -- `x-tool-runtime`: optional; if set, run the tool inside this isolate instead of on the host. Either `docker-container:` or `podman-container:`, using an already-running container, or `ssh:`, running the tool on a remote host +- `x-tool-runtime`: optional; if set, run the tool inside this isolate instead of on the host. Either `docker-container:` or `podman-container:`, using an already-running container, or `ssh:`, running the tool on a remote host. Refused with 403 when the server is started with `--tools-runtime`, so clients cannot move tools out of that sandbox Returns JSON object. There are two response formats (MCP tools use the same two formats: their result content is concatenated into `plain_text_response`, and RPC or tool errors are surfaced as the `error` string): @@ -239,6 +239,8 @@ That requires `JSON.stringify` when formatted to message content: } ``` +When the client disconnects during an MCP tool call, or the call exceeds `timeout_ms`, `llama-server` sends `notifications/cancelled` with the request id to the MCP server and returns an error. + Set `stream: true` in the request body to stream a tool's output as it runs, instead of waiting for it to finish. Only certain tools accept this (for ex. `exec_shell_command`); returns 404 if tool doesn't support it. diff --git a/tools/server/README.md b/tools/server/README.md index defc09c6bbbd..27d1417518f4 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -68,9 +68,8 @@ For the full list of features, please refer to [server's changelog](https://gith | `-kvo, --kv-offload, -nkvo, --no-kv-offload` | whether to enable KV cache offloading (default: enabled)
(env: LLAMA_ARG_KV_OFFLOAD) | | `--repack, -nr, --no-repack` | whether to enable weight repacking (default: enabled)
(env: LLAMA_ARG_REPACK) | | `--no-host` | bypass host buffer allowing extra buffers to be used
(env: LLAMA_ARG_NO_HOST) | -| `-ctk, --cache-type-k TYPE` | KV cache data type for K
allowed values: f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_CACHE_TYPE_K) | -| `-ctv, --cache-type-v TYPE` | KV cache data type for V
allowed values: f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_CACHE_TYPE_V) | -| `-dt, --defrag-thold N` | KV cache defragmentation threshold (DEPRECATED)
(env: LLAMA_ARG_DEFRAG_THOLD) | +| `-ctk, --cache-type-k TYPE` | KV cache data type for K
allowed values: f32, f16, bf16, f8_e4m3, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_CACHE_TYPE_K) | +| `-ctv, --cache-type-v TYPE` | KV cache data type for V
allowed values: f32, f16, bf16, f8_e4m3, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_CACHE_TYPE_V) | | `--rpc SERVERS` | comma-separated list of RPC servers (host:port)
(env: LLAMA_ARG_RPC) | | `-lm, --load-mode MODE` | model loading mode (default: auto)
- auto: mmap, unless a device does not support it
- none: no special loading mode
- mmap: memory-map model (if mmap disabled, slower load but may reduce pageouts if not using mlock)
- mlock: force system to keep model in RAM rather than swapping or compressing
- mmap+mlock: mmap + force system to keep model in RAM rather than swapping or compressing
- dio: use DirectIO if available

(env: LLAMA_ARG_LOAD_MODE) | | `-lzm, --lazy-mode MODE` | on-demand reading of certain tensors, for example per-layer embeddings (default: auto)
- on: read the rows of such tensors from disk on demand instead of keeping them resident (requires mmap)
- auto: on, but only for tensors larger than 4 GiB
- off: always keep them resident
(env: LLAMA_ARG_LAZY_MODE) | @@ -99,6 +98,7 @@ For the full list of features, please refer to [server's changelog](https://gith | `--control-vector-scaled FNAME:SCALE,...` | add a control vector with user defined scaling SCALE
note: use comma-separated values (format: FNAME:SCALE,...) | | `--control-vector-layer-range START END` | layer range to apply the control vector(s) to, start and end inclusive | | `-m, --model FNAME` | model path to load
(env: LLAMA_ARG_MODEL) | +| `--ple, --shard FNAME,...` | extra GGUF shards for the model, comma separated; may be given more than once
paths may live anywhere, including on different drives; --ple is an alias for --shard
(env: LLAMA_ARG_SHARD) | | `-mu, --model-url MODEL_URL` | model download url (default: unused)
(env: LLAMA_ARG_MODEL_URL) | | `-dr, --docker-repo [/][:quant]` | Docker Hub model repository. repo is optional, default to ai/. quant is optional, default to :latest.
example: gemma3
(default: unused)
(env: LLAMA_ARG_DOCKER_REPO) | | `-hf, -hfr, --hf-repo /[:quant]` | Hugging Face model repository; quant is optional, case-insensitive, default to Q4_K_M, or falls back to the first file in the repo if Q4_K_M doesn't exist.
mmproj is also downloaded automatically if available. to disable, add --no-mmproj
example: ggml-org/GLM-4.7-Flash-GGUF:Q4_K_M
(default: unused)
(env: LLAMA_ARG_HF_REPO) | @@ -113,8 +113,8 @@ For the full list of features, please refer to [server's changelog](https://gith | `-lv, --verbosity, --log-verbosity N` | Set the verbosity threshold. Messages with a higher verbosity will be ignored. Values:
- 0: generic output
- 1: error
- 2: warning
- 3: info
- 4: trace (more info)
- 5: debug
(default: 3)

(env: LLAMA_ARG_LOG_VERBOSITY) | | `--log-prefix, --no-log-prefix` | Enable prefix in log messages
(env: LLAMA_ARG_LOG_PREFIX) | | `--log-timestamps, --no-log-timestamps` | Enable timestamps in log messages
(env: LLAMA_ARG_LOG_TIMESTAMPS) | -| `--spec-draft-type-k, -ctkd, --cache-type-k-draft TYPE` | KV cache data type for K for the draft model
allowed values: f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K) | -| `--spec-draft-type-v, -ctvd, --cache-type-v-draft TYPE` | KV cache data type for V for the draft model
allowed values: f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_V) | +| `--spec-draft-type-k, -ctkd, --cache-type-k-draft TYPE` | KV cache data type for K for the draft model
allowed values: f32, f16, bf16, f8_e4m3, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K) | +| `--spec-draft-type-v, -ctvd, --cache-type-v-draft TYPE` | KV cache data type for V for the draft model
allowed values: f32, f16, bf16, f8_e4m3, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1
(default: f16)
(env: LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_V) | ### Sampling params @@ -195,16 +195,17 @@ For the full list of features, please refer to [server's changelog](https://gith | `--port PORT` | port to listen (default: 9931)
(env: LLAMA_ARG_PORT) | | `--reuse-port` | allow multiple sockets to bind to the same port (default: disabled)
(env: LLAMA_ARG_REUSE_PORT) | | `--path PATH` | path to serve static files from (default: )
(env: LLAMA_ARG_STATIC_PATH) | -| `--cors-origins ORIGINS` | comma-separated list of allowed origins for CORS (default: *)
if set to special value 'localhost', reflect the Origin header only if it is localhost
(env: LLAMA_ARG_CORS_ORIGINS) | +| `--cors-origins ORIGINS` | comma-separated list of allowed origins for CORS (default: *)
if set to special value 'localhost', only allow same-origin requests (e.g. the built-in UI)
(env: LLAMA_ARG_CORS_ORIGINS) | | `--cors-methods METHODS` | comma-separated list of allowed methods for CORS (default: GET, POST, DELETE, OPTIONS)
(env: LLAMA_ARG_CORS_METHODS) | | `--cors-headers HEADERS` | comma-separated list of allowed headers for CORS (default: *)
(env: LLAMA_ARG_CORS_HEADERS) | | `--cors-credentials, --no-cors-credentials` | whether to allow credentials for CORS (default: enabled)
note: if this is enabled and --cors-origins is set to * (default), the Origin header will be echoed back, and credentials will always be allowed
(env: LLAMA_ARG_CORS_CREDENTIALS) | | `--api-prefix PREFIX` | prefix path the server serves from, without the trailing slash (default: )
(env: LLAMA_ARG_API_PREFIX) | | `--ui-config, --webui-config JSON` | JSON that provides default UI settings (overrides UI defaults)
(env: LLAMA_ARG_UI_CONFIG) | | `--ui-config-file, --webui-config-file PATH` | JSON file that provides default UI settings (overrides UI defaults)
(env: LLAMA_ARG_UI_CONFIG_FILE) | -| `--ui-mcp-proxy, --webui-mcp-proxy, --no-ui-mcp-proxy, --no-webui-mcp-proxy` | experimental: whether to enable MCP CORS proxy - do not enable in untrusted environments (default: disabled)
(env: LLAMA_ARG_UI_MCP_PROXY) | +| `--ui-mcp-proxy, --webui-mcp-proxy, --no-ui-mcp-proxy, --no-webui-mcp-proxy` | experimental: whether to enable MCP CORS proxy, for the Web UI to reach public MCP servers without CORS headers; local and private addresses are refused - do not enable in untrusted environments (default: disabled)
note: for security reasons, this will limit --cors-origins to localhost by default
(env: LLAMA_ARG_UI_MCP_PROXY) | | `--tools TOOL1,TOOL2,...` | experimental: whether to enable built-in tools for AI agents - do not enable in untrusted environments (default: no tools)
specify "all" to enable all tools
available tools: read_file, file_glob_search, grep_search, exec_shell_command, write_file, edit_file, get_info
note: for security reasons, this will limit --cors-origins to localhost by default
(env: LLAMA_ARG_TOOLS) | | `--tools-runtime OPTION` | experimental: run tools in a separate runtime environment (default: none, use host environment)
available options:
'docker:', 'podman:': spin up a new container and reuse it for all invocations, clean up on server exit
'docker-container:', 'podman-container:': use an existing container by ID, won't stop on server exit
'ssh:': run tools on a remote POSIX host over SSH, key-based auth and a trusted host key are required

(env: LLAMA_ARG_TOOLS_RUNTIME) | +| `--allow-unauthenticated-tools` | allow server tools, MCP servers or MCP proxy on a non-loopback address without an API key - only for trusted networks (default: disabled)
(env: LLAMA_ARG_ALLOW_UNAUTHENTICATED_TOOLS) | | `--mcp-servers-config PATH` | experimental: path to JSON file with MCP server definitions (Cursor-compatible format) - do not enable in untrusted environments (default: none)
note: for security reasons, this will limit --cors-origins to localhost by default
(env: LLAMA_ARG_MCP_SERVERS_CONFIG) | | `--mcp-servers-json JSON` | experimental: inline JSON with MCP server definitions (Cursor-compatible format) - do not enable in untrusted environments (default: none)
note: for security reasons, this will limit --cors-origins to localhost by default
(env: LLAMA_ARG_MCP_SERVERS_JSON) | | `-ag, --agent, -no-ag, --no-agent` | whether to enable CORS proxy and all built-in tools - do not enable in untrusted environments (default: disabled)
note: for security reasons, this will limit --cors-origins to localhost by default
(env: LLAMA_ARG_AGENT) | @@ -228,6 +229,7 @@ For the full list of features, please refer to [server's changelog](https://gith | `--slots, --no-slots` | expose slots monitoring endpoint (default: enabled)
(env: LLAMA_ARG_ENDPOINT_SLOTS) | | `--slot-save-path PATH` | path to save slot kv cache (default: disabled)
(env: LLAMA_ARG_SLOT_SAVE_PATH) | | `--media-path PATH` | directory for loading local media files; files can be accessed via file:// URLs using relative paths (default: disabled) | +| `--media-allow-private-urls` | allow http(s) media URLs (e.g. image_url) that point to local or private addresses (default: disabled, only public addresses)
(env: LLAMA_ARG_MEDIA_ALLOW_PRIVATE_URLS) | | `--models-dir PATH` | directory containing models for the router server (default: disabled)
(env: LLAMA_ARG_MODELS_DIR) | | `--models-preset PATH` | path to INI file containing model presets for the router server (default: disabled)
(env: LLAMA_ARG_MODELS_PRESET) | | `--models-max N` | for router server, maximum number of models to load simultaneously (default: 4, 0 = unlimited)
(env: LLAMA_ARG_MODELS_MAX) | @@ -239,7 +241,7 @@ For the full list of features, please refer to [server's changelog](https://gith | `--reasoning-effort LEVEL` | reasoning effort level given to the chat template: 'default' to keep the template default,
or a level such as 'minimal', 'low', 'medium', 'high', 'xhigh' or 'max' (default: default)
(env: LLAMA_ARG_REASONING_EFFORT) | | `--reasoning-budget N` | token budget for thinking: -1 for unrestricted, 0 for immediate end, N>0 for token budget (default: -1)
(env: LLAMA_ARG_THINK_BUDGET) | | `--reasoning-budget-message MESSAGE` | message injected before the end-of-thinking tag when reasoning budget is exhausted (default: none)
(env: LLAMA_ARG_THINK_BUDGET_MESSAGE) | -| `--reasoning-preserve, --no-reasoning-preserve` | preserve reasoning trace in the full history, not just the last assistant message (default: template default)
compatible with certain templates having 'supports_preserve_reasoning' capability
example: https://docs.z.ai/guides/capabilities/thinking-mode#preserved-thinking
(env: LLAMA_ARG_REASONING_PRESERVE) | +| `--reasoning-preserve, --no-reasoning-preserve` | preserve reasoning trace in the full history, not just the last assistant message (default: enabled)
compatible with certain templates having 'supports_preserve_reasoning' capability
example: https://docs.z.ai/guides/capabilities/thinking-mode#preserved-thinking
(env: LLAMA_ARG_REASONING_PRESERVE) | | `--chat-template JINJA_TEMPLATE` | set custom jinja chat template (default: template taken from model's metadata)
if suffix/prefix are specified, template will be disabled
only commonly used templates are accepted (unless --jinja is set before this flag):
list of built-in templates:
bailing, bailing-think, bailing2, chatglm3, chatglm4, chatml, command-r, deepseek, deepseek-ocr, deepseek2, deepseek3, exaone-moe, exaone3, exaone4, falcon3, gemma, gigachat, glmedge, gpt-oss, granite, granite-4.0, granite-4.1, grok-2, hunyuan-dense, hunyuan-moe, hunyuan-vl, kimi-k2, llama2, llama2-sys, llama2-sys-bos, llama2-sys-strip, llama3, llama4, megrez, minicpm, mistral-v1, mistral-v3, mistral-v3-tekken, mistral-v7, mistral-v7-tekken, monarch, openchat, orion, pangu-embedded, phi3, phi4, rwkv-world, seed_oss, smolvlm, solar-open, vicuna, vicuna-orca, yandex, zephyr
(env: LLAMA_ARG_CHAT_TEMPLATE) | | `--chat-template-file JINJA_TEMPLATE_FILE` | set custom jinja chat template file (default: template taken from model's metadata)
if suffix/prefix are specified, template will be disabled
only commonly used templates are accepted (unless --jinja is set before this flag):
list of built-in templates:
bailing, bailing-think, bailing2, chatglm3, chatglm4, chatml, command-r, deepseek, deepseek-ocr, deepseek2, deepseek3, exaone-moe, exaone3, exaone4, falcon3, gemma, gigachat, glmedge, gpt-oss, granite, granite-4.0, granite-4.1, grok-2, hunyuan-dense, hunyuan-moe, hunyuan-vl, kimi-k2, llama2, llama2-sys, llama2-sys-bos, llama2-sys-strip, llama3, llama4, megrez, minicpm, mistral-v1, mistral-v3, mistral-v3-tekken, mistral-v7, mistral-v7-tekken, monarch, openchat, orion, pangu-embedded, phi3, phi4, rwkv-world, seed_oss, smolvlm, solar-open, vicuna, vicuna-orca, yandex, zephyr
(env: LLAMA_ARG_CHAT_TEMPLATE_FILE) | | `--skip-chat-parsing, --no-skip-chat-parsing` | force a pure content parser, even if a Jinja template is specified; model will output everything in the content section, including any reasoning and/or tool calls (default: disabled)
(env: LLAMA_ARG_SKIP_CHAT_PARSING) | @@ -293,6 +295,8 @@ For the full list of features, please refer to [server's changelog](https://gith | `--spec-ngram-size-n N` | the argument has been removed. use the respective --spec-ngram-*-size-n or --spec-ngram-mod-n-match | | `--spec-ngram-size-m N` | the argument has been removed. use the respective --spec-ngram-*-size-m | | `--spec-ngram-min-hits N` | the argument has been removed. use the respective --spec-ngram-*-min-hits | +| `--tts-lang FNAME` | language (ISO 639-1) for audio generation
see tts/README.md for per-model usage notes | +| `--tts-voice VOICE` | voice for audio generation (model-dependent)
see tts/README.md for per-model usage notes | | `--embd-gemma-default` | use default EmbeddingGemma model (note: can download weights from the internet) | | `--fim-qwen-1.5b-default` | use default Qwen 2.5 Coder 1.5B (note: can download weights from the internet) | | `--fim-qwen-3b-default` | use default Qwen 2.5 Coder 3B (note: can download weights from the internet) | @@ -389,7 +393,7 @@ Every server is spawned once at startup to list its tools, then stopped, and res The child process runs with the same privileges as the server, so only declare commands you trust. As with `--tools`, `--cors-origins` then defaults to `localhost`. -Note: `--ui-mcp-proxy` is unrelated, it only lets the Web UI reach remote MCP servers from the browser. +Note: `--ui-mcp-proxy` is unrelated, it only lets the Web UI reach public MCP servers that do not send CORS headers. It refuses local and private addresses (loopback, LAN, link-local); connect to those from the Web UI directly. Any server written against the [MCP specification](https://modelcontextprotocol.io) works as is, whether it uses an official SDK or not: the transport is one JSON-RPC message per line on stdio, so a script wrapping an existing program is a valid server too. @@ -2506,7 +2510,7 @@ To pause a download, send an event to `/models/unload`: it keeps its partial fil Download procedure: - Send POST request to `/models` - Subscribe to `/models/sse` for updates -- On downloading completed, you will receive either `download_finished` or `download_failed` event +- On downloading completed, you will receive either `download_finished` or `download_failed` event. A download that stopped because a client paused or cancelled it fails with `{"stopped": true}` as its data - Call GET `/models` to trigger model list update. If the download success, you should see the new model in the list Payload: diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp index 5bf2ec12a772..0013c09cd0a2 100644 --- a/tools/server/server-common.cpp +++ b/tools/server/server-common.cpp @@ -9,6 +9,8 @@ #include "server-common.h" +#include + #include #include #include @@ -1215,10 +1217,55 @@ json oaicompat_completion_params_parse(const json & body) { // - file:// for local files (only allowed if media_path is set) // - data: for base64 encoded data with uri scheme (e.g. data:image/png;base64,...) // - raw base64 encoded data +static bool ipv4_is_public(const unsigned char * b) { + return !(b[0] == 0 || b[0] == 10 || b[0] == 127 || b[0] >= 224 // this network, private, loopback, multicast, reserved + || (b[0] == 100 && (b[1] & 0xc0) == 64) // 100.64.0.0/10 CGNAT + || (b[0] == 169 && b[1] == 254) // link-local, cloud metadata + || (b[0] == 172 && (b[1] & 0xf0) == 16) // 172.16.0.0/12 + || (b[0] == 192 && b[1] == 168) // 192.168.0.0/16 + || (b[0] == 192 && b[1] == 0 && b[2] == 0) // 192.0.0.0/24 + || (b[0] == 198 && (b[1] & 0xfe) == 18)); // 198.18.0.0/15 +} + +bool server_addr_is_public(const std::string & addr) { + unsigned char b[16]; + if (inet_pton(AF_INET, addr.c_str(), b) == 1) { + return ipv4_is_public(b); + } + if (inet_pton(AF_INET6, addr.c_str(), b) != 1) { + return false; // e.g. scoped address "fe80::1%eth0" + } + static const unsigned char v4_mapped[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}; + static const unsigned char nat64[12] = {0, 0x64, 0xff, 0x9b, 0, 0, 0, 0, 0, 0, 0, 0}; + static const unsigned char zero[12] = {}; + if (memcmp(b, v4_mapped, 12) == 0 || memcmp(b, nat64, 12) == 0) { + return ipv4_is_public(b + 12); + } + return memcmp(b, zero, 12) != 0 // ::/96: unspecified, loopback, IPv4-compatible + && (b[0] & 0xfe) != 0xfc // fc00::/7 unique local + && !(b[0] == 0xfe && (b[1] & 0x80) == 0x80) // fe80::/10 link-local, fec0::/10 site-local + && b[0] != 0xff; // multicast +} + +std::string server_resolve_public_addr(const std::string & host, bool allow_private) { + std::vector addrs; + httplib::hosted_at(host, addrs); + if (addrs.empty()) { + throw std::invalid_argument("cannot resolve host: " + host); + } + for (const auto & addr : addrs) { + if (!allow_private && !server_addr_is_public(addr)) { + throw std::invalid_argument("host is not a public address: " + host); + } + } + return addrs[0]; +} + void handle_media( std::vector & out_files, const std::string & url, - const std::string & media_path) { + const std::string & media_path, + bool allow_private_urls) { if (!media_path.empty()) { // should already be enforced by arg.cpp, but checking just in case GGML_ASSERT(media_path.back() == DIRECTORY_SEPARATOR); @@ -1230,6 +1277,9 @@ void handle_media( common_remote_params params; params.max_size = 1024 * 1024 * 10; // 10MB params.timeout = 10; // seconds + params.resolve_host = [allow_private_urls](const std::string & host) { + return server_resolve_public_addr(host, allow_private_urls); + }; SRV_INF("downloading image from '%s'\n", url.c_str()); auto res = common_remote_get_content(url, params); if (200 <= res.first && res.first < 300) { @@ -1296,7 +1346,7 @@ static void oaicompat_content_load_media(json & content, const server_chat_param json image_url = json_value(p, "image_url", json::object()); std::string url = json_value(image_url, "url", std::string()); - handle_media(out_files, url, opt.media_path); + handle_media(out_files, url, opt.media_path, opt.media_allow_private_urls); p["type"] = "media_marker"; p["text"] = get_media_marker(); @@ -1311,7 +1361,7 @@ static void oaicompat_content_load_media(json & content, const server_chat_param json input_audio = json_value(p, "input_audio", json::object()); std::string url = json_value(input_audio, "data", json_value(input_audio, "url", std::string())); - handle_media(out_files, url, opt.media_path); + handle_media(out_files, url, opt.media_path, opt.media_allow_private_urls); p["type"] = "media_marker"; p["text"] = get_media_marker(); @@ -1326,7 +1376,7 @@ static void oaicompat_content_load_media(json & content, const server_chat_param json input_video = json_value(p, type, json::object()); std::string url = json_value(input_video, "data", json_value(input_video, "url", std::string())); - handle_media(out_files, url, opt.media_path); + handle_media(out_files, url, opt.media_path, opt.media_allow_private_urls); p["type"] = "media_marker"; p["text"] = get_media_marker(); diff --git a/tools/server/server-common.h b/tools/server/server-common.h index ca870465a072..05622849a1e7 100644 --- a/tools/server/server-common.h +++ b/tools/server/server-common.h @@ -299,11 +299,19 @@ llama_tokens tokenize_mixed(const llama_vocab * vocab, const json & json_prompt, // if validate_utf8(text) == text.size(), then the whole text is valid utf8 size_t validate_utf8(const std::string& text); +// true if the address is publicly routable +bool server_addr_is_public(const std::string & addr); + +// resolve host to an address to connect to; throws if not resolvable or not public (unless allow_private) +std::string server_resolve_public_addr(const std::string & host, bool allow_private); + // load a media file from an URL (http, file, data) or from raw base64 data +// http(s) URLs must resolve to public addresses unless allow_private_urls void handle_media( std::vector & out_files, const std::string & url, - const std::string & media_path); + const std::string & media_path, + bool allow_private_urls = false); // process mtmd prompt, return the server_tokens containing both text tokens and media chunks // if is_placeholder is true, the media chunk will be treated as placeholder for counting tokens; the output tokens are not usable for actual inference (e.g. for submitting a task to server_queue) @@ -315,7 +323,7 @@ server_tokens process_mtmd_prompt( bool is_placeholder = false); // decode one media url (http/file/data-uri) into out_files; throws on failure -void handle_media(std::vector & out_files, const std::string & url, const std::string & media_path); +void handle_media(std::vector & out_files, const std::string & url, const std::string & media_path, bool allow_private_urls); /** * break the input "prompt" object into multiple prompt if needed, then tokenize them @@ -365,6 +373,7 @@ struct server_chat_params { int reasoning_budget = -1; std::string reasoning_budget_message; std::string media_path; + bool media_allow_private_urls = false; bool force_pure_content = false; }; diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index ccde2e826020..c0646f9ca71e 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -1739,6 +1739,7 @@ struct server_context_impl { /* reasoning_budget */ params_base.sampling.reasoning_budget_tokens, /* reasoning_budget_msg */ params_base.sampling.reasoning_budget_message, /* media_path */ params_base.media_path, + /* media_allow_private */ params_base.media_allow_private_urls, /* force_pure_content */ params_base.force_pure_content_parser }; @@ -5369,12 +5370,19 @@ server_context_meta server_context::get_meta() const { // may have bypass_sleep = true if the task does not use ctx_server struct server_res_generator : server_res_spipe { server_response_reader rd; + server_queue * queue_awake = nullptr; // set while this response keeps the server awake server_res_generator(server_queue & queue_tasks, server_response & queue_results, int sleep_idle_seconds, bool bypass_sleep = false) : rd(queue_tasks, queue_results, HTTP_POLLING_SECONDS) { // fast path in case sleeping is disabled bypass_sleep |= sleep_idle_seconds < 0; if (!bypass_sleep) { queue_tasks.wait_until_no_sleep(); + queue_awake = &queue_tasks; + } + } + ~server_res_generator() { + if (queue_awake) { + queue_awake->release_inflight(); } } void ok(const json & response_data) { @@ -7011,7 +7019,7 @@ std::unique_ptr server_routes::handle_rerank_impl(const se auto add_image = [&](const std::string & url) { // marker is appended by format_prompt_rerank, one per decoded file try { - handle_media(out_files, url, params.media_path); + handle_media(out_files, url, params.media_path, params.media_allow_private_urls); } catch (const std::runtime_error & e) { throw std::invalid_argument(e.what()); } diff --git a/tools/server/server-cors-proxy.h b/tools/server/server-cors-proxy.h index 3600a33ec647..41d00740416f 100644 --- a/tools/server/server-cors-proxy.h +++ b/tools/server/server-cors-proxy.h @@ -11,6 +11,7 @@ #include #include "server-http.h" +#include "server-common.h" static std::string proxy_header_to_lower(std::string header) { std::transform(header.begin(), header.end(), header.begin(), [](unsigned char c) { @@ -68,9 +69,20 @@ static server_http_res_ptr proxy_request(const server_http_req & req, std::strin req.files, req.should_stop, 600, // timeout_read (default to 10 minutes) - 600 // timeout_write (default to 10 minutes) + 600, // timeout_write (default to 10 minutes) + // test-only escape hatch + server_resolve_public_addr(parsed_url.host, !common_get_env("LLAMA_SERVER_DEBUG_PROXY_ALLOW_PRIVATE").empty()) ); + // route redirects back through the proxy, so each hop is checked + if (proxy->status >= 300 && proxy->status < 400) { + for (auto & [key, value] : proxy->headers) { + if (proxy_header_to_lower(key) == "location") { + value = "?url=" + httplib::encode_uri_component(common_http_resolve_location(target_url, value)); + } + } + } + return proxy; } diff --git a/tools/server/server-http.cpp b/tools/server/server-http.cpp index cf147c7e70f4..5bdece55b6f3 100644 --- a/tools/server/server-http.cpp +++ b/tools/server/server-http.cpp @@ -6,6 +6,9 @@ #include +#include +#include +#include #include #include #include @@ -71,14 +74,97 @@ static void log_server_request(const httplib::Request & req, const httplib::Resp SRV_DBG("response: %s\n", res.body.c_str()); } -// returns true if the Origin header value's host is localhost / 127.0.0.1 / ::1 (any port) -static bool origin_is_localhost(const std::string & origin) { - try { - const std::string host = common_http_parse_url(origin).host; - return host == "localhost" || host == "127.0.0.1" || host == "::1"; - } catch (const std::exception &) { +static std::string ascii_lower(std::string s) { + std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return std::tolower(c); }); + return s; +} + +// true if the text is a dotted IPv4 address in 127.0.0.0/8 +static bool ipv4_is_loopback(const std::string & s) { + unsigned a, b, c, d; + char tail; + return std::sscanf(s.c_str(), "%u.%u.%u.%u%c", &a, &b, &c, &d, &tail) == 4 && a == 127 && b < 256 && c < 256 && d < 256; +} + +// true if the address is loopback: 127.0.0.0/8, ::1 or an IPv4 mapped 127.0.0.0/8 +static bool addr_is_loopback(const std::string & addr) { + static const std::string mapped = "::ffff:"; + if (addr.compare(0, mapped.size(), mapped) == 0) { + return ipv4_is_loopback(addr.substr(mapped.size())); + } + return addr == "::1" || ipv4_is_loopback(addr); +} + +// the name of a Host header value, lowercase, without port and IPv6 brackets +static std::string host_name(const std::string & host) { + if (!host.empty() && host[0] == '[') { + const size_t end = host.find(']'); + return end == std::string::npos ? "" : ascii_lower(host.substr(1, end - 1)); + } + return ascii_lower(host.substr(0, host.find(':'))); +} + +// DNS rebinding guard: a page whose own name resolves to 127.0.0.1 reaches a loopback +// connection with that name in Host, so Host names loopback or the host of an allowed origin +static bool request_host_is_allowed(const std::string & cors_origins, const httplib::Request & req) { + if (!addr_is_loopback(req.local_addr)) { + return true; + } + const std::string host = req.get_header_value("Host"); + const std::string name = host_name(host); + // the unspecified addresses only reach this machine, e.g. curl http://0.0.0.0:8080 + if (name == "localhost" || name == "0.0.0.0" || name == "::" || addr_is_loopback(name)) { + return true; + } + if (cors_origins == "localhost") { return false; } + for (const auto & entry : string_split(cors_origins, ',')) { + const std::string allowed = string_strip(entry); + const size_t sep = allowed.find("://"); + if (sep != std::string::npos && ascii_lower(allowed.substr(sep + 3)) == ascii_lower(host)) { + return true; + } + } + return false; +} + +// CSRF guard when CORS is not "*" +// no ACAO header only hides the response, browsers still send simple requests (text/plain POST, no-cors GET), so reject them here +static bool request_origin_is_allowed(const std::string & cors_origins, const httplib::Request & req, bool is_frontend_path) { + if (cors_origins == "*") { + return true; + } + + if (!request_host_is_allowed(cors_origins, req)) { + return false; + } + + const std::string origin = req.get_header_value("Origin"); + if (!origin.empty()) { + // same-origin, e.g. UI opened via LAN address + const std::string host = req.get_header_value("Host"); + const size_t sep = origin.find("://"); + if (!host.empty() && sep != std::string::npos && ascii_lower(origin.substr(sep + 3)) == ascii_lower(host)) { + return true; + } + if (cors_origins == "localhost") { + return false; // same-origin only, other localhost ports can be untrusted apps + } + for (const auto & allowed : string_split(cors_origins, ',')) { + if (string_strip(allowed) == origin) { + return true; + } + } + return false; + } + + // no Origin: non-browser client or browser no-cors GET; if cross-site, only allow navigation to the UI + const std::string site = req.get_header_value("Sec-Fetch-Site"); + if (site == "cross-site" || site == "same-site") { + return req.method == "GET" && req.get_header_value("Sec-Fetch-Mode") == "navigate" && is_frontend_path; + } + return true; } // For Google Cloud Platform deployment compatibility @@ -328,19 +414,31 @@ bool server_http_context::init_listener(const common_params & params) { return true; }; + // a router child has no API key; the router strips the browser headers, so only a browser sends them here + const bool managed_by_router = std::getenv(SERVER_ENV_ROUTER_PORT) != nullptr; + // register server middlewares - srv->set_pre_routing_handler([¶ms, middleware_validate_api_key, middleware_server_state](const httplib::Request & req, httplib::Response & res) { + srv->set_pre_routing_handler([¶ms, managed_by_router, middleware_validate_api_key, middleware_server_state](const httplib::Request & req, httplib::Response & res) { + if (managed_by_router && (req.has_header("Origin") || req.has_header("Sec-Fetch-Site") || req.has_header("Sec-Fetch-Mode"))) { + SRV_WRN("rejected browser request on router child: %s %s\n", req.method.c_str(), req.path.c_str()); + res.status = 403; + res.set_content( + safe_json_to_str(json { + {"error", { + {"message", "Browser requests must go through the router"}, + {"type", "permission_error"}, + {"code", 403} + }} + }), + "application/json; charset=utf-8" + ); + return httplib::Server::HandlerResponse::Handled; + } if (params.cors_credentials && params.cors_origins == "*") { // special case: echo back the Origin header to allow any origin to access the server with credentials res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin")); } else if (params.cors_origins == "localhost") { - // special case: only reflect the Origin header if it is a localhost origin - std::string origin = req.get_header_value("Origin"); - if (!origin.empty() && origin_is_localhost(origin)) { - res.set_header("Access-Control-Allow-Origin", origin); - } else if (!origin.empty()) { - SRV_WRN("(CORS) skip non-localhost origin: %s\n", origin.c_str()); - } + // special case: same-origin only, no CORS header needed } else { res.set_header("Access-Control-Allow-Origin", params.cors_origins); } @@ -352,6 +450,23 @@ bool server_http_context::init_listener(const common_params & params) { res.set_content("", "text/html"); // blank response, no data return httplib::Server::HandlerResponse::Handled; // skip further processing } + if (!request_origin_is_allowed(params.cors_origins, req, frontend_paths.count(req.path) > 0)) { + SRV_WRN("(CORS) rejected cross-origin request: %s %s, host = '%s', origin = '%s', sec-fetch-site = '%s'\n", + req.method.c_str(), req.path.c_str(), req.get_header_value("Host").c_str(), + req.get_header_value("Origin").c_str(), req.get_header_value("Sec-Fetch-Site").c_str()); + res.status = 403; + res.set_content( + safe_json_to_str(json { + {"error", { + {"message", "Cross-origin request not allowed (see --cors-origins)"}, + {"type", "permission_error"}, + {"code", 403} + }} + }), + "application/json; charset=utf-8" + ); + return httplib::Server::HandlerResponse::Handled; + } if (!middleware_server_state(req, res)) { return httplib::Server::HandlerResponse::Handled; } diff --git a/tools/server/server-mcp.cpp b/tools/server/server-mcp.cpp index 22401e08ab14..08929ba54fe1 100644 --- a/tools/server/server-mcp.cpp +++ b/tools/server/server-mcp.cpp @@ -244,14 +244,30 @@ json server_mcp_transport::send_rpc(const json & request, const std::function= deadline) { + notify_cancelled(request, "request timed out"); return {{"error", {{"code", -32603}, {"message", "request timed out"}}}}; } return {{"error", {{"code", -32603}, {"message", "transport closed"}}}}; } +// MCP cancellation: a notification that lets the server abandon work nobody waits for anymore +// (e.g. a slow tool call after the client dropped the connection). the spec forbids cancelling initialize. +void server_mcp_transport::notify_cancelled(const json & request, const std::string & reason) { + if (!request.contains("id") || request.value("method", "") == "initialize") { + return; + } + json notif = { + {"jsonrpc", "2.0"}, + {"method", "notifications/cancelled"}, + {"params", {{"requestId", request.at("id")}, {"reason", reason}}}, + }; + to_server.write(notif.dump()); +} + bool server_mcp_transport::ensure_init(const std::function & should_stop) { if (initialized) { return true; diff --git a/tools/server/server-mcp.h b/tools/server/server-mcp.h index c7f33a3f797d..2b4eb89201f4 100644 --- a/tools/server/server-mcp.h +++ b/tools/server/server-mcp.h @@ -82,9 +82,10 @@ struct server_mcp_transport { std::string last_error; std::vector tools; - // both assume rpc_mutex is already held by the public caller + // all assume rpc_mutex is already held by the public caller bool ensure_init(const std::function & should_stop); // initialize handshake, once json send_rpc(const json & request, const std::function & should_stop); // returns the reply or an {"error": ...} + void notify_cancelled(const json & request, const std::string & reason); // notifications/cancelled for an abandoned request }; // diff --git a/tools/server/server-models.cpp b/tools/server/server-models.cpp index dc277ead2081..5b7d34501c23 100644 --- a/tools/server/server-models.cpp +++ b/tools/server/server-models.cpp @@ -265,6 +265,23 @@ struct server_monitor { // delete). distinct from params.timeout_read/write which only applies to the generation proxy static constexpr int STREAM_LOOKUP_TIMEOUT_MS = 250; +// router already checked the origin; child sees a loopback Host, so do not forward origin headers +static bool is_browser_origin_header(const std::string & key) { + std::string lower = key; + std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + return lower == "origin" || lower.compare(0, 10, "sec-fetch-") == 0; +} + +static std::map child_request_headers(const std::map & headers) { + std::map out; + for (const auto & [key, value] : headers) { + if (!is_browser_origin_header(key)) { + out.emplace(key, value); + } + } + return out; +} + static void unset_reserved_args(common_preset & preset, bool unset_model_args) { preset.unset_option("LLAMA_ARG_SSL_KEY_FILE"); preset.unset_option("LLAMA_ARG_SSL_CERT_FILE"); @@ -697,6 +714,8 @@ void server_models::unfinished_downloads_remove(const std::string & name) { } bool ok = common_download_remove(name); SRV_INF("removing unfinished download name=%s (%s)\n", name.c_str(), ok ? "succeeded" : "nothing cached"); + // other clients still list it as a paused download + notify_sse("model_remove", name, {}); } bool server_models::remove_sidecar(const std::string & name, const std::string & kind) { @@ -1344,6 +1363,7 @@ void server_models::unload(const std::string & name) { if (it != mapping.end()) { if (it->second.meta.status == SERVER_MODEL_STATUS_DOWNLOADING) { SRV_INF("cancelling download for model name=%s\n", name.c_str()); + it->second.download_stop_requested = true; it->second.request_exit(); // for convenience, we wait the status change here wait(lk, name, [](const server_model_meta & new_meta) { @@ -1371,6 +1391,7 @@ void server_models::unload_all() { for (auto & [name, inst] : mapping) { if (inst.meta.status == SERVER_MODEL_STATUS_DOWNLOADING) { SRV_INF("cancelling download for model name=%s\n", name.c_str()); + inst.download_stop_requested = true; inst.request_exit(); } else if (inst.meta.is_running()) { SRV_INF("stopping model instance name=%s\n", name.c_str()); @@ -1466,6 +1487,7 @@ void server_models::update_status(const std::string & name, const update_status_ void server_models::update_download_progress(const std::string & name, const common_download_progress & progress, bool done, bool ok) { json curr; + bool stopped = false; { std::lock_guard lk(mutex); auto it = mapping.find(name); @@ -1474,6 +1496,7 @@ void server_models::update_download_progress(const std::string & name, const com // mark the instance to be erased on next load_models() call it->second.meta.status = SERVER_MODEL_STATUS_DOWNLOADED; need_reload = true; + stopped = it->second.download_stop_requested; // a download that failed keeps its tag: its partial files are still // there and re-posting the tag resumes them @@ -1495,7 +1518,13 @@ void server_models::update_download_progress(const std::string & name, const com } if (done) { cv.notify_all(); // notify in case unload() is waiting for download to be cancelled - notify_sse(ok ? "download_finished" : "download_failed", name, {}); + // a stop a client asked for (pause or cancel) is no error: say so, so that every + // client, not only the one that asked, can tell it from a failed download + if (ok) { + notify_sse("download_finished", name, {}); + } else { + notify_sse("download_failed", name, stopped ? json{{"stopped", true}} : json{}); + } } else { notify_sse("download_progress", name, curr); } @@ -1518,6 +1547,7 @@ bool server_models::remove(const std::string & name) { if (it->second.meta.status == SERVER_MODEL_STATUS_DOWNLOADING) { // cancel in-flight download SRV_INF("cancelling download for model name=%s\n", name.c_str()); + it->second.download_stop_requested = true; it->second.request_exit(); } else if (it->second.meta.is_running()) { // stop running instance @@ -1714,7 +1744,7 @@ server_http_res_ptr server_models::proxy_request(const server_http_req & req, co CHILD_ADDR, meta->port, proxy_path, - req.headers, + child_request_headers(req.headers), req.body, req.files, // a detached request belongs to a replay session @@ -1769,7 +1799,8 @@ void server_models::proxy_ws(const server_http_req & req, server_http_context::w for (const auto & [key, value] : req.headers) { std::string lower = key; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); - if (lower == "host" || lower == "connection" || lower == "upgrade" || lower.compare(0, 14, "sec-websocket-") == 0) { + if (lower == "host" || lower == "connection" || lower == "upgrade" || lower.compare(0, 14, "sec-websocket-") == 0 + || is_browser_origin_header(key)) { continue; } headers.emplace(key, value); @@ -2410,7 +2441,7 @@ void server_models_routes::init_routes() { CHILD_ADDR, owner->port, child_path, - req.headers, + child_request_headers(req.headers), req.body, req.files, req.should_stop, @@ -2625,7 +2656,8 @@ server_http_proxy::server_http_proxy( const std::map & files, const std::function should_stop, int32_t timeout_read, - int32_t timeout_write + int32_t timeout_write, + const std::string & resolved_addr ) { // shared between reader and writer threads auto cli = std::make_shared(host, port); @@ -2640,7 +2672,11 @@ server_http_proxy::server_http_proxy( } // setup Client - cli->set_follow_location(true); + if (!resolved_addr.empty()) { + // pin the checked address; a redirect could lead to an unchecked one + cli->set_direct_hostname_addr_map({{host, resolved_addr}}); + } + cli->set_follow_location(resolved_addr.empty()); cli->set_connection_timeout(timeout_read, 0); // use --timeout value instead of hardcoded 5 s cli->set_write_timeout(timeout_read, 0); // reversed for cli (client) vs srv (server) cli->set_read_timeout(timeout_write, 0); diff --git a/tools/server/server-models.h b/tools/server/server-models.h index 0db948773c6e..e18ae3a31f43 100644 --- a/tools/server/server-models.h +++ b/tools/server/server-models.h @@ -170,6 +170,7 @@ struct server_models { std::shared_ptr subproc; // shared with the monitor thread server_model_meta meta; int req_count = 0; // number of active proxy requests + bool download_stop_requested = false; // a client asked the download to stop (pause or cancel) // ask the child to exit (it handles the command on its stdin, see server_role::setup) void request_exit() const; @@ -443,7 +444,8 @@ struct server_http_proxy : server_http_res { const std::map & files, const std::function should_stop, int32_t timeout_read, - int32_t timeout_write + int32_t timeout_write, + const std::string & resolved_addr = "" // if set: connect to this address only, do not follow redirects ); ~server_http_proxy() { if (cleanup_pipes) { diff --git a/tools/server/server-queue.cpp b/tools/server/server-queue.cpp index c4ce90721b94..75daebb0d299 100644 --- a/tools/server/server-queue.cpp +++ b/tools/server/server-queue.cpp @@ -114,9 +114,7 @@ void server_queue::pop_deferred_task(int id_slot) { void server_queue::wait_until_no_sleep() { std::unique_lock lock(mutex_tasks); - if (!sleeping) { - return; - } else { + if (sleeping) { if (!req_stop_sleeping) { QUE_DBG("%s", "requesting to stop sleeping\n"); req_stop_sleeping = true; @@ -127,6 +125,13 @@ void server_queue::wait_until_no_sleep() { return !sleeping; }); } + n_inflight++; +} + +void server_queue::release_inflight() { + std::unique_lock lock(mutex_tasks); + GGML_ASSERT(n_inflight > 0); + n_inflight--; } void server_queue::terminate() { @@ -289,7 +294,7 @@ void server_queue::start_loop(int64_t idle_sleep_ms) { constexpr auto max_wait_time = std::chrono::seconds(1); auto should_sleep = [&]() -> bool { // caller must hold mutex_tasks - if (idle_sleep_ms < 0) { + if (idle_sleep_ms < 0 || n_inflight > 0) { return false; } int64_t now = ggml_time_ms(); diff --git a/tools/server/server-queue.h b/tools/server/server-queue.h index 692255e4f6e7..f9d66be64064 100644 --- a/tools/server/server-queue.h +++ b/tools/server/server-queue.h @@ -19,6 +19,7 @@ struct server_queue { bool sleeping = false; bool req_stop_sleeping = false; int64_t time_last_task = 0; + int n_inflight = 0; // requests that keep the server awake, see wait_until_no_sleep() // queues std::deque queue_tasks; @@ -67,8 +68,12 @@ struct server_queue { // if sleeping, request exiting sleep state and wait until it is done // returns immediately if not sleeping + // the server then stays awake until the caller calls release_inflight() void wait_until_no_sleep(); + // let the server sleep again once the caller no longer uses the server state + void release_inflight(); + bool is_sleeping() { std::unique_lock lock(mutex_tasks); return sleeping; diff --git a/tools/server/server-tools.cpp b/tools/server/server-tools.cpp index bde774b37eff..c92f1e9f88bb 100644 --- a/tools/server/server-tools.cpp +++ b/tools/server/server-tools.cpp @@ -896,7 +896,7 @@ struct server_tool_read_file : server_tool { }; } - json invoke(json params, server_tool::stream *) const override { + json invoke(json params, server_tool::stream *, const std::function &) const override { std::string path = params.at("path").get(); int start_line = json_value(params, "start_line", 1); int end_line = json_value(params, "end_line", -1); // -1 = no limit @@ -1013,7 +1013,7 @@ struct server_tool_file_glob_search : server_tool { }; } - json invoke(json params, server_tool::stream *) const override { + json invoke(json params, server_tool::stream *, const std::function &) const override { auto io = make_tools_io(params); const std::string path = params.at("path").get(); @@ -1128,7 +1128,7 @@ struct server_tool_grep_search : server_tool { }; } - json invoke(json params, server_tool::stream *) const override { + json invoke(json params, server_tool::stream *, const std::function &) const override { std::string path = params.at("path").get(); std::string pat_str = params.at("pattern").get(); std::string include = json_value(params, "include", std::string("**")); @@ -1271,7 +1271,7 @@ struct server_tool_exec_shell_command : server_tool { }; } - json invoke(json params, server_tool::stream * st) const override { + json invoke(json params, server_tool::stream * st, const std::function &) const override { std::string command = params.at("command").get(); int timeout = json_value(params, "timeout", 10); size_t max_output = (size_t) json_value(params, "max_output_size", (int) SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_OUTPUT_SIZE); @@ -1348,7 +1348,7 @@ struct server_tool_write_file : server_tool { }; } - json invoke(json params, server_tool::stream *) const override { + json invoke(json params, server_tool::stream *, const std::function &) const override { std::string path = params.at("path").get(); std::string content = params.at("content").get(); @@ -1405,7 +1405,7 @@ struct server_tool_edit_file : server_tool { }; } - json invoke(json params, server_tool::stream *) const override { + json invoke(json params, server_tool::stream *, const std::function &) const override { std::string path = params.at("path").get(); const json & edits_json = params.at("edits"); @@ -1721,7 +1721,7 @@ struct server_tool_get_info : server_tool { }; } - json invoke(json params, server_tool::stream *) const override { + json invoke(json params, server_tool::stream *, const std::function &) const override { auto io = make_tools_io(params); // inside an isolate, we always use the linux command @@ -1835,8 +1835,8 @@ struct server_mcp_tool : server_tool { }; } - json invoke(json params, server_tool::stream *) const override { - return mcp_mgr.call_tool(server_name, tool_name, params); + json invoke(json params, server_tool::stream *, const std::function & should_stop) const override { + return mcp_mgr.call_tool(server_name, tool_name, params, should_stop); } }; @@ -2093,15 +2093,20 @@ void server_tools::setup(const std::vector & enabled_tools, } // accept x-tool-runtime header to route tool I/O through an isolate, e.g. "docker-container:"; - // falls back to the --tools-runtime isolate, if configured + // --tools-runtime wins: it is the sandbox, the client must not move tools out of it if (params.contains("runtime")) { params.erase("runtime"); } auto runtime_header = get_header(req.headers, "x-tool-runtime"); - if (!runtime_header.empty()) { - params["runtime"] = runtime_header; - } else if (runtime) { + if (runtime) { + if (!runtime_header.empty()) { + res->status = 403; + res->data = safe_json_to_str(format_error_response("x-tool-runtime is not allowed when --tools-runtime is set", ERROR_TYPE_PERMISSION)); + return res; + } params["runtime"] = runtime->spec(); + } else if (!runtime_header.empty()) { + params["runtime"] = runtime_header; } // x-resp-type header is only used by read_file for now @@ -2128,7 +2133,7 @@ void server_tools::setup(const std::vector & enabled_tools, auto done = std::make_unique(); try { - tool.invoke(params, &st); + tool.invoke(params, &st, req.should_stop); } catch (const std::exception & e) { done->error_msg = e.what(); } catch (...) { @@ -2153,7 +2158,7 @@ void server_tools::setup(const std::vector & enabled_tools, return true; }; } else { - json result = tool.invoke(params, nullptr); + json result = tool.invoke(params, nullptr, req.should_stop); res->status = 200; res->data = safe_json_to_str(result); } diff --git a/tools/server/server-tools.h b/tools/server/server-tools.h index e7332f2e5743..5a63ee973bef 100644 --- a/tools/server/server-tools.h +++ b/tools/server/server-tools.h @@ -26,7 +26,8 @@ struct server_tool { std::function alive; void push(const std::string & chunk); }; - virtual json invoke(json params, stream * st = nullptr) const = 0; + // should_stop: true once the caller stopped waiting, e.g. the client dropped the connection; a null should_stop means "never stop" + virtual json invoke(json params, stream * st = nullptr, const std::function & should_stop = nullptr) const = 0; json to_json() const; }; diff --git a/tools/server/server.cpp b/tools/server/server.cpp index 4e838cb10626..ca3eb2dbbe0a 100644 --- a/tools/server/server.cpp +++ b/tools/server/server.cpp @@ -13,11 +13,14 @@ #include "llama.h" #include "log.h" +#include #include #include #include +#include #include #include // for std::thread::hardware_concurrency +#include #if defined(_WIN32) #include @@ -256,6 +259,17 @@ static bool server_setup_features( SRV_WRN("%s", "security: no API key is set and CORS allows all origins (see https://github.com/ggml-org/llama.cpp/pull/25655)\n"); } + // tools can run shell commands: do not expose them to the network without auth + const bool tools_enabled = !params.server_tools.empty() || !params.mcp_servers_config.empty() || !params.mcp_servers_json.empty() || params.ui_mcp_proxy; + const bool loopback_only = std::all_of(params.hostnames.begin(), params.hostnames.end(), [](const std::string & h) { + return string_ends_with(h, ".sock") || h == "localhost" || h == "::1" || h == "[::1]" || string_starts_with(h, "127."); + }); + if (tools_enabled && !loopback_only && params.api_keys.empty() && !params.server_tools_allow_unauth) { + SRV_ERR("%s", "security: server tools, MCP servers or MCP proxy are enabled on a non-loopback address without an API key\n"); + SRV_ERR("%s", "set --api-key, bind to 127.0.0.1, or pass --allow-unauthenticated-tools on a trusted network\n"); + return false; + } + std::vector warn_names; if (role_type == SERVER_ROLE_ROUTER) { warn_names.push_back("router mode"); @@ -354,7 +368,10 @@ static bool server_on_listening(server_http_context & ctx_http, const common_par struct server_download_state : public common_download_callback { server_role * role; std::function should_stop; - std::atomic last_progress_time{0}; // multiple files downloading in different threads + // files download in parallel threads: throttle each file on its own, a shared + // timer lets a small, fast file (e.g. a draft) starve the updates of the others + std::mutex progress_mutex; + std::unordered_map last_progress_time; bool is_ok = false; server_download_state(server_role * r) : role(r) {} @@ -384,11 +401,17 @@ struct server_download_state : public common_download_callback { } void on_update(const common_download_progress & p) override { int64_t now = ggml_time_ms(); - // throttle progress updates to avoid flooding logs - if (now - last_progress_time.load(std::memory_order_relaxed) >= 100) { - on_progress(p); - last_progress_time.store(now, std::memory_order_relaxed); + // throttle progress updates to avoid flooding logs; the first update of a file + // always passes, it carries the file's total size + { + std::lock_guard lk(progress_mutex); + auto it = last_progress_time.find(p.url); + if (it != last_progress_time.end() && now - it->second < 100) { + return; + } + last_progress_time[p.url] = now; } + on_progress(p); } void on_done(const common_download_progress & p, bool) override { on_progress(p); diff --git a/tools/server/tests/README.md b/tools/server/tests/README.md index 7ed02d22e6da..d0f8b7938997 100644 --- a/tools/server/tests/README.md +++ b/tools/server/tests/README.md @@ -117,7 +117,7 @@ Example using `gdb`: $ gdb --args ../../../build/bin/llama-server \ --host 127.0.0.1 --port 8080 \ --temp 0.8 --seed 42 \ - --hf-repo ggml-org/models --hf-file tinyllamas/stories260K.gguf \ + --hf-repo ggml-org-dev/stories260K --hf-file stories260K.gguf \ --batch-size 32 --no-slots --alias tinyllama-2 --ctx-size 512 \ --parallel 2 --n-predict 64 ``` diff --git a/tools/server/tests/fixtures/mcp_slow_server.py b/tools/server/tests/fixtures/mcp_slow_server.py index 7f8e67835acc..879d48ffe92b 100644 --- a/tools/server/tests/fixtures/mcp_slow_server.py +++ b/tools/server/tests/fixtures/mcp_slow_server.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 """ MCP server that sleeps before responding, for timeout testing. +With --log, it appends every message it reads from stdin to that file, for cancellation testing. """ import json import sys @@ -70,6 +71,7 @@ def handle_tools_call(params, req_id): def main(): parser = argparse.ArgumentParser() parser.add_argument("--delay", type=float, default=5.0, help="Delay in seconds for sleep tool") + parser.add_argument("--log", help="File to append every message read from stdin to") args = parser.parse_args() # Override the sleep duration @@ -102,6 +104,9 @@ def handle_tools_call(params, req_id): line = line.strip() if not line: continue + if args.log: + with open(args.log, "a") as log: + log.write(line + "\n") try: request = json.loads(line) except json.JSONDecodeError: diff --git a/tools/server/tests/unit/test_basic.py b/tools/server/tests/unit/test_basic.py index b9e9f84f6383..423a7c326cfa 100644 --- a/tools/server/tests/unit/test_basic.py +++ b/tools/server/tests/unit/test_basic.py @@ -98,8 +98,8 @@ def test_server_slots(): def test_load_split_model(): global server server.offline = False - server.model_hf_repo = "ggml-org/models" - server.model_hf_file = "tinyllamas/split/stories15M-q8_0-00001-of-00003.gguf" + server.model_hf_repo = "ggml-org-dev/stories15M" + server.model_hf_file = "split/stories15M-q8_0-00001-of-00003.gguf" server.model_alias = "tinyllama-split" server.start() res = server.make_request("POST", "/completion", data={ diff --git a/tools/server/tests/unit/test_compat_anthropic.py b/tools/server/tests/unit/test_compat_anthropic.py index 13d0774452eb..220417745dab 100644 --- a/tools/server/tests/unit/test_compat_anthropic.py +++ b/tools/server/tests/unit/test_compat_anthropic.py @@ -11,7 +11,7 @@ def get_test_image_base64() -> str: """Get a test image in base64 format""" # Use the same test image as test_vision_api.py - IMG_URL = "https://huggingface.co/ggml-org/tinygemma3-GGUF/resolve/main/test/11_truck.png" + IMG_URL = "https://huggingface.co/ggml-org-dev/tinygemma3-GGUF/resolve/main/test/11_truck.png" response = requests.get(IMG_URL) response.raise_for_status() return base64.b64encode(response.content).decode("utf-8") diff --git a/tools/server/tests/unit/test_lora.py b/tools/server/tests/unit/test_lora.py index 00b2f245f60f..e21d9048bf58 100644 --- a/tools/server/tests/unit/test_lora.py +++ b/tools/server/tests/unit/test_lora.py @@ -3,7 +3,7 @@ server = ServerPreset.stories15m_moe() -LORA_FILE_URL = "https://huggingface.co/ggml-org/stories15M_MOE/resolve/main/moe_shakespeare15M.gguf" +LORA_FILE_URL = "https://huggingface.co/ggml-org-dev/stories15M_MOE/resolve/main/moe_shakespeare15M.gguf" @pytest.fixture(autouse=True) def create_server(): diff --git a/tools/server/tests/unit/test_mcp_servers.py b/tools/server/tests/unit/test_mcp_servers.py index 877b732a5349..7a9f0bea57b3 100644 --- a/tools/server/tests/unit/test_mcp_servers.py +++ b/tools/server/tests/unit/test_mcp_servers.py @@ -9,6 +9,7 @@ 4. Misconfigured MCP servers do not crash the server 5. Multiple MCP servers can be configured simultaneously 6. Warmup populates the tool list at startup +7. The MCP server receives notifications/cancelled when the client drops or the call times out """ import json import os @@ -319,29 +320,60 @@ def call_tool(): server.stop() -def test_mcp_tool_timeout(): - """Tool call should timeout if MCP server is too slow.""" - global server +def _slow_server_config(log_path: str, timeout_ms: int) -> str: MCP_SLOW_SERVER = os.path.join(FIXTURES_DIR, "mcp_slow_server.py") - mcp_json = _mcp_config_json({ + return _mcp_config_json({ "slow": { "command": sys.executable, - "args": [MCP_SLOW_SERVER, "--delay", "5"], - "timeout_ms": 500 + "args": [MCP_SLOW_SERVER, "--log", log_path], + "timeout_ms": timeout_ms, } }) - server = _start_server_with_mcp(mcp_json) + + +def _messages_read_by_mcp_server(log_path: str) -> list: + """Parses the fixture's log, skipping a last line that the fixture is still writing.""" + with open(log_path) as f: + return [json.loads(line) for line in f if line.endswith("\n")] + + +def _wait_for_cancellation(log_path: str, limit_seconds: float) -> dict: + """Returns the notifications/cancelled message once the MCP server has read it.""" + deadline = time.time() + limit_seconds + while time.time() < deadline: + for message in _messages_read_by_mcp_server(log_path): + if message.get("method") == "notifications/cancelled": + return message + time.sleep(0.1) + raise AssertionError(f"the MCP server read no notifications/cancelled: {_messages_read_by_mcp_server(log_path)}") + + +def _tools_call_id(log_path: str): + """Returns the id of the one tools/call request the MCP server has read.""" + ids = [m["id"] for m in _messages_read_by_mcp_server(log_path) if m.get("method") == "tools/call"] + assert len(ids) == 1, ids + return ids[0] + + +def test_mcp_tool_timeout(): + """A tool call that exceeds timeout_ms returns an error and sends notifications/cancelled to the MCP server.""" + global server + with tempfile.NamedTemporaryFile(suffix=".jsonl", delete=False) as f: + log_path = f.name + server = _start_server_with_mcp(_slow_server_config(log_path, timeout_ms=500)) try: res = server.make_request("POST", "/tools", data={ "tool": "slow_sleep", - "params": {"seconds": 5} + "params": {"seconds": 1} }) assert res.status_code == 200, res.body - body = res.body - assert "error" in body, body + assert "error" in res.body, res.body + cancellation = _wait_for_cancellation(log_path, limit_seconds=10) + assert cancellation["params"]["requestId"] == _tools_call_id(log_path) finally: server.stop() + os.unlink(log_path) def test_mcp_warmup_partial_failure(): @@ -711,3 +743,23 @@ def test_mcp_grandchild_holding_pipes_does_not_deadlock(): assert elapsed < 3, f"server shutdown took {elapsed:.1f}s (expected < 3s) — teardown likely deadlocked" finally: server.stop() + + +def test_mcp_dropped_client_sends_cancellation(): + """Dropping the connection during a tool call sends notifications/cancelled for that request to the MCP server.""" + global server + with tempfile.NamedTemporaryFile(suffix=".jsonl", delete=False) as f: + log_path = f.name + server = _start_server_with_mcp(_slow_server_config(log_path, timeout_ms=30000)) + + try: + with pytest.raises(requests.exceptions.ReadTimeout): + server.make_request("POST", "/tools", data={ + "tool": "slow_sleep", + "params": {"seconds": 1.5} + }, timeout=0.5) + cancellation = _wait_for_cancellation(log_path, limit_seconds=10) + assert cancellation["params"]["requestId"] == _tools_call_id(log_path) + finally: + server.stop() + os.unlink(log_path) diff --git a/tools/server/tests/unit/test_proxy.py b/tools/server/tests/unit/test_proxy.py index cb439b7a4560..58fd8c824826 100644 --- a/tools/server/tests/unit/test_proxy.py +++ b/tools/server/tests/unit/test_proxy.py @@ -35,6 +35,7 @@ def test_mcp_proxy(): def test_mcp_proxy_custom_port(): global server server.ui_mcp_proxy = True + server.debug_proxy_allow_private = True server.start() # try getting the server's models API via the proxy @@ -60,6 +61,7 @@ def log_message(self, format, *args): try: global server server.ui_mcp_proxy = True + server.debug_proxy_allow_private = True server.start() res = server.make_request("POST", f"/cors-proxy?url=http://127.0.0.1:{target.server_port}/", data={}) @@ -69,3 +71,62 @@ def log_message(self, format, *args): target.shutdown() target.server_close() + + +@pytest.mark.parametrize("target", [ + "http://127.0.0.1:{port}/models", + "http://localhost:{port}/models", + "http://[::1]:{port}/models", + "http://[::ffff:127.0.0.1]:{port}/models", + "http://10.0.0.1/", + "http://172.16.0.1/", + "http://192.168.1.1/", + "http://100.64.0.1/", + "http://169.254.169.254/latest/meta-data/", # cloud metadata + "http://0.0.0.0:{port}/models", +]) +def test_mcp_proxy_refuses_non_public_targets(target: str): + global server + server.ui_mcp_proxy = True + server.start() + target = target.format(port=server.server_port) + res = server.make_request("GET", f"/cors-proxy?url={target}") + assert res.status_code == 400 + + +def test_mcp_proxy_redirect_goes_through_proxy(): + class RedirectHandler(BaseHTTPRequestHandler): + def do_GET(self): + if self.path == "/start": + self.send_response(302) + self.send_header("Location", "/next") + self.end_headers() + else: + self.send_response(200) + self.end_headers() + self.wfile.write(b"final") + + def log_message(self, format, *args): + pass + + target = ThreadingHTTPServer(("127.0.0.1", 0), RedirectHandler) + target_thread = threading.Thread(target=target.serve_forever, daemon=True) + target_thread.start() + + try: + global server + server.ui_mcp_proxy = True + server.debug_proxy_allow_private = True + server.start() + + url = server.make_url(f"/cors-proxy?url=http://127.0.0.1:{target.server_port}/start") + # redirect points back to the proxy + res = requests.get(url, allow_redirects=False) + assert res.status_code == 302 + assert res.headers["Location"] == f"?url=http%3A%2F%2F127.0.0.1%3A{target.server_port}%2Fnext" + res = requests.get(url) + assert res.status_code == 200 + assert res.text == "final" + finally: + target.shutdown() + target.server_close() diff --git a/tools/server/tests/unit/test_router.py b/tools/server/tests/unit/test_router.py index 98f6aab9e7c5..e4e62086b0ed 100644 --- a/tools/server/tests/unit/test_router.py +++ b/tools/server/tests/unit/test_router.py @@ -27,7 +27,7 @@ def test_router_props(): @pytest.mark.parametrize( "model,success", [ - ("ggml-org/tinygemma3-GGUF:Q8_0", True), + ("ggml-org-dev/tinygemma3-GGUF:Q8_0", True), ("non-existent/model", False), ] ) @@ -109,7 +109,7 @@ def _load_model_and_wait( def test_router_unload_model(): global server server.start() - model_id = "ggml-org/tinygemma3-GGUF:Q8_0" + model_id = "ggml-org-dev/tinygemma3-GGUF:Q8_0" _load_model_and_wait(model_id) @@ -125,9 +125,9 @@ def test_router_models_max_evicts_lru(): server.start() candidate_models = [ - "ggml-org/tinygemma3-GGUF:Q8_0", - "ggml-org/test-model-stories260K:F32", - "ggml-org/test-model-stories260K-infill:F32", + "ggml-org-dev/tinygemma3-GGUF:Q8_0", + "ggml-org-dev/test-model-stories260K:F32", + "ggml-org-dev/test-model-stories260K-infill:F32", ] # Load only the first 2 models to fill the cache @@ -150,9 +150,9 @@ def test_router_models_max_evicts_lru(): # server_lru_sched tests (relying on LLAMA_SERVER_DEBUG_FAKE_TIMING) -MODEL_A = "ggml-org/tinygemma3-GGUF:Q8_0" -MODEL_B = "ggml-org/test-model-stories260K:F32" -MODEL_C = "ggml-org/test-model-stories260K-infill:F32" +MODEL_A = "ggml-org-dev/tinygemma3-GGUF:Q8_0" +MODEL_B = "ggml-org-dev/test-model-stories260K:F32" +MODEL_C = "ggml-org-dev/test-model-stories260K-infill:F32" def _tokenize(model_id: str, timeout: float | None = DEFAULT_REQUEST_TIMEOUT) -> ServerResponse: @@ -388,7 +388,7 @@ def test_router_no_models_autoload(): global server server.no_models_autoload = True server.start() - model_id = "ggml-org/tinygemma3-GGUF:Q8_0" + model_id = "ggml-org-dev/tinygemma3-GGUF:Q8_0" res = server.make_request( "POST", @@ -422,7 +422,7 @@ def test_router_api_key_required(): server.api_key = "sk-router-secret" server.start() - model_id = "ggml-org/tinygemma3-GGUF:Q8_0" + model_id = "ggml-org-dev/tinygemma3-GGUF:Q8_0" auth_headers = {"Authorization": f"Bearer {server.api_key}"} res = server.make_request( @@ -463,10 +463,10 @@ def test_router_reload_models(): with open(preset_path, "w") as f: f.write( "[model-reload-a]\n" - "hf-repo = ggml-org/test-model-stories260K\n" + "hf-repo = ggml-org-dev/test-model-stories260K\n" "\n" "[model-reload-b]\n" - "hf-repo = ggml-org/test-model-stories260K-infill\n" + "hf-repo = ggml-org-dev/test-model-stories260K-infill\n" ) server.models_preset = preset_path @@ -480,10 +480,10 @@ def test_router_reload_models(): with open(preset_path, "w") as f: f.write( "[model-reload-b]\n" - "hf-repo = ggml-org/test-model-stories260K-infill\n" + "hf-repo = ggml-org-dev/test-model-stories260K-infill\n" "\n" "[model-reload-c]\n" - "hf-repo = ggml-org/test-model-stories260K\n" + "hf-repo = ggml-org-dev/test-model-stories260K\n" ) try: @@ -500,14 +500,14 @@ def test_router_dedup_cache_models(): global server preset_path = os.path.join(TMP_DIR, "test_dedup.ini") - main_cache_id = "ggml-org/test-model-stories260K:F32" - draft_cache_id = "ggml-org/test-model-stories260K-infill:F32" + main_cache_id = "ggml-org-dev/test-model-stories260K:F32" + draft_cache_id = "ggml-org-dev/test-model-stories260K-infill:F32" with open(preset_path, "w") as f: f.write( "[model-dedup]\n" - "hf-repo = ggml-org/test-model-stories260K\n" - "spec-draft-hf = ggml-org/test-model-stories260K-infill\n" + "hf-repo = ggml-org-dev/test-model-stories260K\n" + "spec-draft-hf = ggml-org-dev/test-model-stories260K-infill\n" "dedup-cache-models = 1\n" ) @@ -520,7 +520,7 @@ def test_router_dedup_cache_models(): assert main_cache_id not in ids, "main cache model should be hidden by dedup" assert draft_cache_id not in ids, "draft cache model should be hidden by dedup" # other cache models are unaffected - assert "ggml-org/tinygemma3-GGUF:Q8_0" in ids + assert "ggml-org-dev/tinygemma3-GGUF:Q8_0" in ids # the hidden model is only hidden from the listing, it can still be used res = server.make_request("POST", "/tokenize", data={"model": main_cache_id, "content": "hello"}) @@ -530,8 +530,8 @@ def test_router_dedup_cache_models(): with open(preset_path, "w") as f: f.write( "[model-dedup]\n" - "hf-repo = ggml-org/test-model-stories260K\n" - "spec-draft-hf = ggml-org/test-model-stories260K-infill\n" + "hf-repo = ggml-org-dev/test-model-stories260K\n" + "spec-draft-hf = ggml-org-dev/test-model-stories260K-infill\n" ) ids = _get_model_ids(is_reload=True) assert main_cache_id in ids @@ -544,8 +544,8 @@ def test_router_dedup_cache_models(): "dedup-cache-models = 1\n" "\n" "[model-dedup]\n" - "hf-repo = ggml-org/test-model-stories260K\n" - "spec-draft-hf = ggml-org/test-model-stories260K-infill\n" + "hf-repo = ggml-org-dev/test-model-stories260K\n" + "spec-draft-hf = ggml-org-dev/test-model-stories260K-infill\n" ) ids = _get_model_ids(is_reload=True) assert "model-dedup" in ids @@ -557,7 +557,7 @@ def test_router_dedup_cache_models(): def test_router_remote_preset(): global server - server.model_hf_repo = "ggml-org/test-preset-ci" + server.model_hf_repo = "ggml-org-dev/test-preset-ci" server.model_hf_file = None server.offline = False server.start() @@ -574,7 +574,7 @@ def test_router_remote_preset(): _load_model_and_wait(model_id) -MODEL_DOWNLOAD_ID = "ggml-org/test-model-router-download:F16" +MODEL_DOWNLOAD_ID = "ggml-org-dev/test-model-router-download:F16" MODEL_DOWNLOAD_TIMEOUT = 30 @@ -843,7 +843,7 @@ def test_router_preset_model_sidecars(): preset_path = os.path.join(TMP_DIR, "test_preset_sidecars.ini") with open(preset_path, "w") as f: - f.write("[preset-sidecars]\nhf-repo = ggml-org/tinygemma3-GGUF:Q8_0\n") + f.write("[preset-sidecars]\nhf-repo = ggml-org-dev/tinygemma3-GGUF:Q8_0\n") server.models_preset = preset_path server.start() @@ -929,3 +929,66 @@ def test_router_download_drops_stale_partials(): _wait_for_model_status(MODEL_DOWNLOAD_ID, {"downloaded", "unloaded"}, timeout=MODEL_DOWNLOAD_TIMEOUT) server.make_request("DELETE", f"/models?model={MODEL_DOWNLOAD_ID}") + + +def test_router_restricted_cors_same_origin_reaches_child(): + # same-origin request via LAN address must not be refused by the child + global server + lan_ip = get_lan_ip() + if lan_ip is None: + pytest.skip("no non-loopback interface") # ty: ignore[too-many-positional-arguments] + server.cors_origins = "localhost" + server.server_host = "0.0.0.0" + server.start() + body = { + "model": "ggml-org-dev/tinygemma3-GGUF:Q8_0", + "max_tokens": 4, + "messages": [{"role": "user", "content": "hello"}], + } + res = requests.post(server.make_url("/chat/completions", host=lan_ip), json=body, headers={ + "Origin": f"http://{lan_ip}:{server.server_port}", + "Sec-Fetch-Site": "same-origin", + }) + assert res.status_code == 200, res.text + + res = requests.post(server.make_url("/chat/completions", host="127.0.0.1"), json=body, headers={"Origin": "http://evil.com"}) + assert res.status_code == 403 + + +def test_router_child_refuses_browser_requests(tmp_path): + import re + global server + log_path = tmp_path / "router.log" + server.log_path = str(log_path) + server.start() + model_id = "ggml-org-dev/tinygemma3-GGUF:Q8_0" + _load_model_and_wait(model_id) + + pattern = rf"spawning server instance with name={re.escape(model_id)} on port (\d+)" + match = None + for _ in range(50): + match = re.search(pattern, log_path.read_text()) + if match: + break + time.sleep(0.1) + assert match, "child port not found in router log" + child_url = f"http://127.0.0.1:{match.group(1)}" + + # non-browser clients can reach the child directly + assert requests.get(f"{child_url}/health").status_code == 200 + + for headers in [ + {"Origin": "http://evil.com"}, + {"Origin": child_url}, + {"Sec-Fetch-Site": "cross-site", "Sec-Fetch-Mode": "no-cors"}, + {"Sec-Fetch-Site": "same-origin"}, + ]: + assert requests.get(f"{child_url}/health", headers=headers).status_code == 403, headers + + # browser requests through the router still reach the child + res = requests.post(server.make_url("/chat/completions"), json={ + "model": model_id, + "max_tokens": 4, + "messages": [{"role": "user", "content": "hello"}], + }, headers={"Origin": f"http://127.0.0.1:{server.server_port}", "Sec-Fetch-Site": "same-origin"}) + assert res.status_code == 200, res.text diff --git a/tools/server/tests/unit/test_security.py b/tools/server/tests/unit/test_security.py index 36fc439f9b73..ceec582acf0d 100644 --- a/tools/server/tests/unit/test_security.py +++ b/tools/server/tests/unit/test_security.py @@ -110,12 +110,12 @@ def test_cors_options(origin: str, cors_header: str, cors_header_value: str): @pytest.mark.parametrize("origin", [ "http://localhost", "http://localhost:8080", - "http://127.0.0.1", "http://127.0.0.1:3000", - "http://[::1]", "http://[::1]:3000", + "http://evil.com", + "http://localhost.evil.com", ]) -def test_cors_origins_localhost_reflects(origin: str): +def test_cors_origins_localhost_no_cross_origin_header(origin: str): global server server = ServerPreset.router() server.cors_origins = "localhost" @@ -126,49 +126,172 @@ def test_cors_origins_localhost_reflects(origin: str): "Access-Control-Request-Headers": "Authorization", }) assert res.status_code == 200 - assert res.headers["Access-Control-Allow-Origin"] == origin + assert "Access-Control-Allow-Origin" not in res.headers -@pytest.mark.parametrize("origin", [ - "http://web.mydomain.fr", - "http://evil.com", - "http://notlocalhost", - "http://localhost.evil.com", -]) -def test_cors_origins_localhost_rejects(origin: str): +@pytest.mark.parametrize("feature", ["server_tools", "ui_mcp_proxy"]) +def test_cors_origins_defaults_to_localhost(feature: str): global server server = ServerPreset.router() + if feature == "server_tools": + server.server_tools = "all" + else: + server.ui_mcp_proxy = True + server.start() + res = server.make_request("GET", "/props", headers={"Origin": f"http://127.0.0.1:{server.server_port}"}) + assert res.status_code == 200 + res = server.make_request("GET", "/props", headers={"Origin": "http://localhost:5173"}) + assert res.status_code == 403 + + +def _raw_post(path: str, body: str, headers: dict) -> requests.Response: + # text/plain: "simple" request, no CORS preflight + return requests.post(server.make_url(path), data=body, headers={"Content-Type": "text/plain", **headers}) + + +@pytest.mark.parametrize("headers,expected_status", [ + ({}, 200), # non-browser client + ({"Origin": "http://127.0.0.1:{port}"}, 200), # same-origin + ({"Origin": "http://localhost:3000"}, 403), # other localhost app + ({"Origin": "http://evil.com"}, 403), # cross-origin simple request + ({"Origin": "http://localhost.evil.com"}, 403), + ({"Origin": "null"}, 403), # sandboxed iframe / file:// + ({"Sec-Fetch-Site": "cross-site", "Sec-Fetch-Mode": "no-cors"}, 403), +]) +def test_cors_origins_localhost_blocks_simple_requests(headers: dict, expected_status: int): + global server + server.api_key = None server.cors_origins = "localhost" server.start() - res = server.make_request("OPTIONS", "/completions", headers={ - "Origin": origin, - "Access-Control-Request-Method": "POST", - "Access-Control-Request-Headers": "Authorization", + headers = {k: v.format(port=server.server_port) for k, v in headers.items()} + res = _raw_post("/tokenize", '{"content": "hello"}', headers) + assert res.status_code == expected_status + + +def test_cors_origins_localhost_allows_same_origin(): + global server + lan_ip = get_lan_ip() + if lan_ip is None: + pytest.skip("no non-loopback interface") # ty: ignore[too-many-positional-arguments] + server.api_key = None + server.cors_origins = "localhost" + server.server_host = "0.0.0.0" + server.start() + # UI opened via LAN address: Origin matches Host + url = server.make_url("/tokenize", host=lan_ip) + res = requests.post(url, data='{"content": "hello"}', headers={ + "Content-Type": "text/plain", + "Origin": f"http://{lan_ip}:{server.server_port}", }) assert res.status_code == 200 - assert "Access-Control-Allow-Origin" not in res.headers -def test_cors_origins_defaults_to_localhost_with_tools_enabled(): +@pytest.mark.parametrize("host,headers,expected_status", [ + ("localhost", {}, 200), + ("127.0.0.1", {}, 200), + ("127.0.0.2", {}, 200), + ("[::1]", {}, 200), + ("0.0.0.0", {}, 200), + ("evil.com", {"Origin": "http://evil.com:{port}"}, 403), # rebinding, Origin matches Host + ("evil.com", {"Sec-Fetch-Site": "same-origin"}, 403), # rebinding, same-origin GET has no Origin + ("127.0.0.1.evil.com", {}, 403), + ("localhost.evil.com", {}, 403), +]) +def test_cors_origins_localhost_blocks_dns_rebinding(host: str, headers: dict, expected_status: int): global server - server = ServerPreset.router() - server.server_tools = "all" + server.api_key = None + server.cors_origins = "localhost" server.start() - res = server.make_request("OPTIONS", "/completions", headers={ - "Origin": "http://localhost:8080", - "Access-Control-Request-Method": "POST", - "Access-Control-Request-Headers": "Authorization", - }) + port = server.server_port + headers = {k: v.format(port=port) for k, v in headers.items()} + res = _raw_post("/tokenize", '{"content": "hello"}', {"Host": f"{host}:{port}", **headers}) + assert res.status_code == expected_status + + +def test_cors_origins_explicit_list_allows_its_hosts(): + global server + server.api_key = None + server.cors_origins = "https://ia.example.com" + server.start() + # reverse proxy that keeps the Host of the public name + for host, expected_status in [ + ("ia.example.com", 200), + ("evil.com", 403), + ]: + res = _raw_post("/tokenize", '{"content": "hello"}', {"Host": host, "Origin": f"https://{host}"}) + assert res.status_code == expected_status, host + + +def test_cors_origins_explicit_list_blocks_simple_requests(): + global server + server.api_key = None + server.cors_origins = "https://a.example, https://b.example" + server.start() + for origin, expected_status in [ + ("https://a.example", 200), + ("https://b.example", 200), + ("https://c.example", 403), + ]: + res = _raw_post("/tokenize", '{"content": "hello"}', {"Origin": origin}) + assert res.status_code == expected_status, origin + + +def test_cors_origins_wildcard_keeps_allowing_all(): + global server + server.api_key = None + server.cors_origins = "*" + server.start() + res = _raw_post("/tokenize", '{"content": "hello"}', {"Origin": "http://evil.com"}) assert res.status_code == 200 - assert res.headers["Access-Control-Allow-Origin"] == "http://localhost:8080" - res = server.make_request("OPTIONS", "/completions", headers={ - "Origin": "http://evil.com", - "Access-Control-Request-Method": "POST", - "Access-Control-Request-Headers": "Authorization", - }) + +def test_cors_cross_site_navigation_to_ui_allowed(): + global server + server.api_key = None + server.cors_origins = "localhost" + server.start() + nav = {"Sec-Fetch-Site": "cross-site", "Sec-Fetch-Mode": "navigate"} + # UI may not be built in tests, only check it is not refused + assert requests.get(server.make_url("/"), headers=nav).status_code != 403 + assert requests.get(server.make_url("/props"), headers=nav).status_code == 403 + + +def test_tools_drive_by_exec_is_blocked(): + global server + server.api_key = None + server.server_tools = "exec_shell_command" # implies --cors-origins localhost + server.start() + body = '{"tool": "exec_shell_command", "params": {"command": "echo csrf-guard-test"}}' + res = _raw_post("/tools", body, {"Origin": "http://evil.com"}) + assert res.status_code == 403 + assert "csrf-guard-test" not in res.text + + res = _raw_post("/tools", body, {"Origin": "http://localhost:5173"}) + assert res.status_code == 403 + + res = _raw_post("/tools", body, {"Origin": f"http://127.0.0.1:{server.server_port}"}) assert res.status_code == 200 - assert "Access-Control-Allow-Origin" not in res.headers + assert "csrf-guard-test" in res.text + + +@pytest.mark.parametrize("server_host,api_key,allow_unauth,should_start", [ + ("127.0.0.1", None, False, True), + ("0.0.0.0", None, False, False), + ("0.0.0.0", TEST_API_KEY, False, True), + ("0.0.0.0", None, True, True), +]) +def test_tools_refuse_unauthenticated_network_bind(server_host: str, api_key: str | None, allow_unauth: bool, should_start: bool): + global server + server = ServerPreset.router() + server.server_tools = "all" + server.server_host = server_host + server.api_key = api_key + server.allow_unauthenticated_tools = allow_unauth + if should_start: + server.start() + else: + with pytest.raises(RuntimeError): + server.start() def test_cors_proxy_only_forwards_explicit_proxy_headers(): @@ -191,6 +314,7 @@ def log_message(self, format, *args): server = ServerPreset.tinyllama2() server.api_key = TEST_API_KEY server.ui_mcp_proxy = True + server.debug_proxy_allow_private = True server.start() res = server.make_request("GET", f"/cors-proxy?url=http://127.0.0.1:{target.server_port}/capture", headers={ diff --git a/tools/server/tests/unit/test_slot_save.py b/tools/server/tests/unit/test_slot_save.py index 488b63701d1b..70d06c2a98cc 100644 --- a/tools/server/tests/unit/test_slot_save.py +++ b/tools/server/tests/unit/test_slot_save.py @@ -217,8 +217,8 @@ def test_slot_erase(): # Erase remains gated on the slot's content. # -IMG_URL_CAT = "https://huggingface.co/ggml-org/tinygemma3-GGUF/resolve/main/test/91_cat.png" -IMG_URL_TRUCK = "https://huggingface.co/ggml-org/tinygemma3-GGUF/resolve/main/test/11_truck.png" +IMG_URL_CAT = "https://huggingface.co/ggml-org-dev/tinygemma3-GGUF/resolve/main/test/91_cat.png" +IMG_URL_TRUCK = "https://huggingface.co/ggml-org-dev/tinygemma3-GGUF/resolve/main/test/11_truck.png" def _get_img_base64(url: str) -> str: @@ -785,7 +785,7 @@ def test_slot_restore_damaged_checkpoint_appendix(swa_server, damage): @pytest.mark.parametrize("ctkd_restore", ["f16", "q8_0"]) def test_slot_restore_checkpoints_draft_kv_type_change(swa_server, ctkd_restore): server = swa_server - server.model_draft_hf_repo = "ggml-org/tinygemma3-GGUF:Q8_0" # same file as the target, already in the HF cache + server.model_draft_hf_repo = "ggml-org-dev/tinygemma3-GGUF:Q8_0" # same file as the target, already in the HF cache server.spec_type = "draft-simple" server.ctkd = "f16" server.start() diff --git a/tools/server/tests/unit/test_speculative.py b/tools/server/tests/unit/test_speculative.py index 0d41b1173af0..10597fdb0fb7 100644 --- a/tools/server/tests/unit/test_speculative.py +++ b/tools/server/tests/unit/test_speculative.py @@ -5,7 +5,7 @@ server = ServerPreset.stories15m_moe() -MODEL_DRAFT_FILE_URL = "https://huggingface.co/ggml-org/tiny-llamas/resolve/main/stories15M-q4_0.gguf" +MODEL_DRAFT_FILE_URL = "https://huggingface.co/ggml-org-dev/tiny-llamas/resolve/main/stories15M-q4_0.gguf" def create_server(): global server diff --git a/tools/server/tests/unit/test_stream.py b/tools/server/tests/unit/test_stream.py index a1ef55567bc7..741086316133 100644 --- a/tools/server/tests/unit/test_stream.py +++ b/tools/server/tests/unit/test_stream.py @@ -10,7 +10,7 @@ # a model name with slashes exercises the query string routing of the stream routes: the id # cannot travel as a path param because the decoded slash would split it before capture -MODEL = "ggml-org/tinygemma3-GGUF:Q8_0" +MODEL = "ggml-org-dev/tinygemma3-GGUF:Q8_0" STREAM_ID = f"conv-stream-test::{MODEL}" QS = "conv_id=" + quote(STREAM_ID, safe="") diff --git a/tools/server/tests/unit/test_tools_builtin.py b/tools/server/tests/unit/test_tools_builtin.py index d4ebd28d10e5..b3af7360443b 100755 --- a/tools/server/tests/unit/test_tools_builtin.py +++ b/tools/server/tests/unit/test_tools_builtin.py @@ -206,6 +206,21 @@ def test_tools_builtin_runtime_header(container_engine: str, container_id: str): assert "hello container" in exec_res["plain_text_response"] +def test_tools_builtin_runtime_header_refused_with_configured_runtime(container_engine: str, container_id: str): + global server + server.server_tools_runtime = f"{container_engine}-container:{container_id}" + server.start() + + res = call_tool("exec_shell_command", {"command": "echo sandboxed"}) + assert "sandboxed" in res["plain_text_response"] + + for runtime in ["ssh:user@internal-host", f"{container_engine}-container:other", server.server_tools_runtime]: + res = server.make_request("POST", "/tools", + data={"tool": "exec_shell_command", "params": {"command": "echo hi"}}, + headers={"x-tool-runtime": runtime}) + assert res.status_code == 403, res.body + + def test_tools_builtin_runtime_header_unknown_scheme(): global server server.start() diff --git a/tools/server/tests/unit/test_vision_api.py b/tools/server/tests/unit/test_vision_api.py index dd04e2e2b4c2..cad45ee9b5b4 100644 --- a/tools/server/tests/unit/test_vision_api.py +++ b/tools/server/tests/unit/test_vision_api.py @@ -6,8 +6,8 @@ server: ServerProcess def get_img_url(id: str) -> str: - IMG_URL_0 = "https://huggingface.co/ggml-org/tinygemma3-GGUF/resolve/main/test/11_truck.png" - IMG_URL_1 = "https://huggingface.co/ggml-org/tinygemma3-GGUF/resolve/main/test/91_cat.png" + IMG_URL_0 = "https://huggingface.co/ggml-org-dev/tinygemma3-GGUF/resolve/main/test/11_truck.png" + IMG_URL_1 = "https://huggingface.co/ggml-org-dev/tinygemma3-GGUF/resolve/main/test/91_cat.png" if id == "IMG_URL_0": return IMG_URL_0 elif id == "IMG_URL_1": @@ -204,3 +204,41 @@ def test_vision_embeddings_oai_content(): # same prompt and image in both formats assert data[0]["embedding"] == data[1]["embedding"] assert data[0]["embedding"] != data[2]["embedding"] + + +@pytest.mark.parametrize("allow_private", [False, True]) +def test_vision_image_url_private_address(allow_private: bool): + from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + import threading + img = requests.get(get_img_url("IMG_URL_0")).content + + class ImageHandler(BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(200) + self.send_header("Content-Type", "image/png") + self.end_headers() + self.wfile.write(img) + + def log_message(self, format, *args): + pass + + target = ThreadingHTTPServer(("127.0.0.1", 0), ImageHandler) + threading.Thread(target=target.serve_forever, daemon=True).start() + try: + global server + server.media_allow_private_urls = allow_private + server.start() + res = server.make_request("POST", "/chat/completions", data={ + "temperature": 0.0, + "top_k": 1, + "messages": [ + {"role": "user", "content": [ + {"type": "text", "text": "What is this:\n"}, + {"type": "image_url", "image_url": {"url": f"http://127.0.0.1:{target.server_port}/img.png"}}, + ]}, + ], + }) + assert res.status_code == (200 if allow_private else 400) + finally: + target.shutdown() + target.server_close() diff --git a/tools/server/tests/utils.py b/tools/server/tests/utils.py index af69fafe0cf3..71470c2b612e 100644 --- a/tools/server/tests/utils.py +++ b/tools/server/tests/utils.py @@ -52,8 +52,8 @@ class ServerProcess: debug: bool = False server_port: int = 8080 server_host: str = "127.0.0.1" - model_hf_repo: str | None = "ggml-org/models" - model_hf_file: str | None = "tinyllamas/stories260K.gguf" + model_hf_repo: str | None = "ggml-org-dev/stories260K" + model_hf_file: str | None = "stories260K.gguf" model_alias: str = "tinyllama-2" temperature: float = 0.8 seed: int = 42 @@ -122,6 +122,9 @@ class ServerProcess: no_cache_idle_slots: bool = False log_path: str | None = None ui_mcp_proxy: bool = False + debug_proxy_allow_private: bool = False # test-only: lets the CORS proxy reach local servers + media_allow_private_urls: bool = False + allow_unauthenticated_tools: bool = False backend_sampling: bool = False gcp_compat: bool = False server_tools: str | None = None @@ -148,6 +151,8 @@ def start(self, timeout_seconds: int = DEFAULT_HTTP_TIMEOUT) -> None: **os.environ, "LLAMA_SERVER_DEBUG_FAKE_TIMING": "1", } + if self.debug_proxy_allow_private: + env["LLAMA_SERVER_DEBUG_PROXY_ALLOW_PRIVATE"] = "1" if self.llama_cache is not None: env["LLAMA_CACHE"] = self.llama_cache elif "LLAMA_CACHE" not in os.environ: @@ -302,6 +307,10 @@ def start(self, timeout_seconds: int = DEFAULT_HTTP_TIMEOUT) -> None: server_args.append("--no-cache-idle-slots") if self.ui_mcp_proxy: server_args.append("--ui-mcp-proxy") + if self.media_allow_private_urls: + server_args.append("--media-allow-private-urls") + if self.allow_unauthenticated_tools: + server_args.append("--allow-unauthenticated-tools") if self.server_tools: server_args.extend(["--tools", self.server_tools]) if self.server_tools_runtime: @@ -388,6 +397,8 @@ def stop(self) -> None: def make_url(self, path: str, host: str | None = None) -> str: if host is None: host = self.server_host.split(",")[0].strip() + # a wildcard bind cannot be connected to on Windows + host = {"0.0.0.0": "127.0.0.1", "::": "[::1]"}.get(host, host) return f"http://{host}:{self.server_port}{path}" def make_request( @@ -564,7 +575,7 @@ def load_all() -> None: def tinyllama2() -> ServerProcess: server = ServerProcess() server.offline = True # will be downloaded by load_all() - server.model_hf_repo = "ggml-org/test-model-stories260K" + server.model_hf_repo = "ggml-org-dev/test-model-stories260K" server.model_hf_file = None server.model_alias = "tinyllama-2" server.n_ctx = 512 @@ -578,8 +589,8 @@ def tinyllama2() -> ServerProcess: def bert_bge_small() -> ServerProcess: server = ServerProcess() server.offline = True # will be downloaded by load_all() - server.model_hf_repo = "ggml-org/models" - server.model_hf_file = "bert-bge-small/ggml-model-f16.gguf" + server.model_hf_repo = "ggml-org-dev/bert-bge-small-GGUF" + server.model_hf_file = "ggml-model-f16.gguf" server.model_alias = "bert-bge-small" server.n_ctx = 512 server.n_batch = 128 @@ -593,8 +604,8 @@ def bert_bge_small() -> ServerProcess: def bert_bge_small_with_fa() -> ServerProcess: server = ServerProcess() server.offline = True # will be downloaded by load_all() - server.model_hf_repo = "ggml-org/models" - server.model_hf_file = "bert-bge-small/ggml-model-f16.gguf" + server.model_hf_repo = "ggml-org-dev/bert-bge-small-GGUF" + server.model_hf_file = "ggml-model-f16.gguf" server.model_alias = "bert-bge-small" server.n_ctx = 1024 server.n_batch = 300 @@ -609,7 +620,7 @@ def bert_bge_small_with_fa() -> ServerProcess: def tinyllama_infill() -> ServerProcess: server = ServerProcess() server.offline = True # will be downloaded by load_all() - server.model_hf_repo = "ggml-org/test-model-stories260K-infill" + server.model_hf_repo = "ggml-org-dev/test-model-stories260K-infill" server.model_hf_file = None server.model_alias = "tinyllama-infill" server.n_ctx = 2048 @@ -624,7 +635,7 @@ def tinyllama_infill() -> ServerProcess: def stories15m_moe() -> ServerProcess: server = ServerProcess() server.offline = True # will be downloaded by load_all() - server.model_hf_repo = "ggml-org/stories15M_MOE" + server.model_hf_repo = "ggml-org-dev/stories15M_MOE" server.model_hf_file = "stories15M_MOE-F16.gguf" server.model_alias = "stories15m-moe" server.n_ctx = 2048 @@ -639,8 +650,8 @@ def stories15m_moe() -> ServerProcess: def jina_reranker_tiny() -> ServerProcess: server = ServerProcess() server.offline = True # will be downloaded by load_all() - server.model_hf_repo = "ggml-org/models" - server.model_hf_file = "jina-reranker-v1-tiny-en/ggml-model-f16.gguf" + server.model_hf_repo = "ggml-org-dev/jina-reranker-v1-tiny-en-GGUF" + server.model_hf_file = "ggml-model-f16.gguf" server.model_alias = "jina-reranker" server.n_ctx = 512 server.n_batch = 512 @@ -659,7 +670,7 @@ def tinylaya() -> ServerProcess: server.model_file = local_model server.model_hf_repo = None else: - server.model_hf_repo = "ggml-org/tinylaya-for-testing-gguf" + server.model_hf_repo = "ggml-org-dev/tinylaya-for-testing-gguf" server.n_ctx = 1024 server.n_batch = 512 server.n_ubatch = 512 @@ -673,7 +684,7 @@ def tinyopenjev() -> ServerProcess: server.offline = True # will be downloaded by load_all() # mmproj is already provided by HF registry API server.model_hf_file = None - server.model_hf_repo = "ggml-org/tinyopenjev-for-testing-gguf:Q8_0" + server.model_hf_repo = "ggml-org-dev/tinyopenjev-for-testing-gguf:Q8_0" server.n_ctx = 4096 server.n_batch = 512 server.n_slots = 4 @@ -686,7 +697,7 @@ def tinygemma3() -> ServerProcess: server.offline = True # will be downloaded by load_all() # mmproj is already provided by HF registry API server.model_hf_file = None - server.model_hf_repo = "ggml-org/tinygemma3-GGUF:Q8_0" + server.model_hf_repo = "ggml-org-dev/tinygemma3-GGUF:Q8_0" server.model_alias = "tinygemma3" server.n_ctx = 1024 server.n_batch = 512 @@ -701,7 +712,7 @@ def tinylfm3omni() -> ServerProcess: server.offline = True # will be downloaded by load_all() # mmproj is already provided by HF registry API server.model_hf_file = None - server.model_hf_repo = "ggml-org/tinyLFM3-Omni-for-testing-gguf:Q2_K" + server.model_hf_repo = "ggml-org-dev/tinyLFM3-Omni-for-testing-gguf:Q2_K" server.model_alias = "tinylfm3omni" server.n_ctx = 1024 server.n_batch = 512 @@ -794,5 +805,17 @@ def download_file(url: str, output_file_path: str | None = None) -> str: return output_file +def get_lan_ip() -> str | None: + # address of the interface that routes outside, no packet is sent + import socket + try: + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: + s.connect(("192.0.2.1", 9)) + ip = s.getsockname()[0] + except OSError: + return None + return None if ip.startswith("127.") else ip + + def is_slow_test_allowed(): return os.environ.get("SLOW_TESTS") == "1" or os.environ.get("SLOW_TESTS") == "ON" diff --git a/tools/ui/package-lock.json b/tools/ui/package-lock.json index df25e0aa2532..fb2b68eaa822 100644 --- a/tools/ui/package-lock.json +++ b/tools/ui/package-lock.json @@ -53,6 +53,7 @@ "globals": "16.5.0", "highlight.js": "11.11.1", "http-server": "14.1.1", + "llama-brand": "https://codeload.github.com/ggml-org/llama-brand/tar.gz/f05540643c1ca2a18d732ed6491c839686da9a3a", "mdast": "3.0.0", "mdsvex": "0.12.7", "mermaid": "11.17.2", @@ -12326,6 +12327,13 @@ "node": ">=10" } }, + "node_modules/llama-brand": { + "version": "0.1.0", + "resolved": "https://codeload.github.com/ggml-org/llama-brand/tar.gz/f05540643c1ca2a18d732ed6491c839686da9a3a", + "integrity": "sha512-kRDXUIUdfcDt7w4hh3JrFTpqxf2i7R0PHVLGnwUdr4L8EMqE32mEECoXUz1uoUlFaQ+h6QaVHvJWS5y98AoaYA==", + "dev": true, + "license": "CC-BY-NC-4.0" + }, "node_modules/locate-character": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz", diff --git a/tools/ui/package.json b/tools/ui/package.json index 00049071ecb6..cc3785727280 100644 --- a/tools/ui/package.json +++ b/tools/ui/package.json @@ -78,6 +78,7 @@ "globals": "16.5.0", "highlight.js": "11.11.1", "http-server": "14.1.1", + "llama-brand": "https://codeload.github.com/ggml-org/llama-brand/tar.gz/f05540643c1ca2a18d732ed6491c839686da9a3a", "mdast": "3.0.0", "mdsvex": "0.12.7", "mermaid": "11.17.2", diff --git a/tools/ui/pwa-assets-dark.config.ts b/tools/ui/pwa-assets-dark.config.ts index 4d8114ee76df..7a1128f35bb0 100644 --- a/tools/ui/pwa-assets-dark.config.ts +++ b/tools/ui/pwa-assets-dark.config.ts @@ -1,10 +1,8 @@ -import { writeThemeFavicons } from './scripts/favicon-colorize'; -import { FAVICON_COLORS, PWA_ASSET_GENERATOR } from './src/lib/constants/pwa.constants'; +import { writeBrandFavicons } from './scripts/brand-favicons'; +import { PWA_ASSET_GENERATOR } from './src/lib/constants/pwa.constants'; import { defineConfig } from '@vite-pwa/assets-generator/config'; -writeThemeFavicons(FAVICON_COLORS.LIGHT, FAVICON_COLORS.DARK, { - padding: PWA_ASSET_GENERATOR.FAVICON_PADDING -}); +writeBrandFavicons(); export default defineConfig({ headLinkOptions: { diff --git a/tools/ui/pwa-assets.config.ts b/tools/ui/pwa-assets.config.ts index f9f8662a20af..bd0bc0024f5b 100644 --- a/tools/ui/pwa-assets.config.ts +++ b/tools/ui/pwa-assets.config.ts @@ -1,6 +1,5 @@ -import { writeThemeFavicons } from './scripts/favicon-colorize'; +import { writeBrandFavicons } from './scripts/brand-favicons'; import { - FAVICON_COLORS, PWA_ASSET_GENERATOR, PWA_GENERATOR_DEVICES, THEME_COLORS @@ -14,9 +13,7 @@ import { import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; -writeThemeFavicons(FAVICON_COLORS.LIGHT, FAVICON_COLORS.DARK, { - padding: PWA_ASSET_GENERATOR.FAVICON_PADDING -}); +writeBrandFavicons(); export default defineConfig({ headLinkOptions: { @@ -26,7 +23,7 @@ export default defineConfig({ preset: combinePresetAndAppleSplashScreens( { ...minimal2023Preset, - // tiny margin so favicon.ico / pwa-*.png breathe inside the canvas + // llama-brand's favicons carry their own margin transparent: { ...minimal2023Preset.transparent, padding: PWA_ASSET_GENERATOR.FAVICON_PADDING diff --git a/tools/ui/scripts/brand-favicons.ts b/tools/ui/scripts/brand-favicons.ts new file mode 100644 index 000000000000..87a0585161ba --- /dev/null +++ b/tools/ui/scripts/brand-favicons.ts @@ -0,0 +1,27 @@ +import { FAVICON_PATHS } from '../src/lib/constants/pwa.constants'; +import { copyFileSync, mkdirSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const DEFAULT_OUT_DIR = resolve(HERE, '..', 'static'); +const require = createRequire(import.meta.url); + +/** The web favicons llama-brand draws for the UI, optically centred, keyed by the file they become. */ +export const BRAND_FAVICONS = { + [FAVICON_PATHS.SVG_DARK]: 'llama-brand/logo/svg/app/web/favicon-dark.svg', + [FAVICON_PATHS.SVG_LIGHT]: 'llama-brand/logo/svg/app/web/favicon.svg' +} as const; + +/** + * Copy llama-brand's light and dark favicons into the static directory, where + * they are served as they are and feed the PWA asset generator. + */ +export function writeBrandFavicons(outDir: string = DEFAULT_OUT_DIR): void { + mkdirSync(outDir, { recursive: true }); + + for (const [fileName, specifier] of Object.entries(BRAND_FAVICONS)) { + copyFileSync(require.resolve(specifier), resolve(outDir, fileName)); + } +} diff --git a/tools/ui/scripts/favicon-colorize.ts b/tools/ui/scripts/favicon-colorize.ts deleted file mode 100644 index 54a951296a1f..000000000000 --- a/tools/ui/scripts/favicon-colorize.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; -import { dirname, resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const HERE = dirname(fileURLToPath(import.meta.url)); -const PROJECT_ROOT = resolve(HERE, '..'); -const DEFAULT_LOGO = resolve(PROJECT_ROOT, 'src/lib/assets/logo.svg'); -const DEFAULT_OUT_DIR = resolve(PROJECT_ROOT, 'static'); -const DEFAULT_OUT_LIGHT = resolve(DEFAULT_OUT_DIR, 'favicon.svg'); -const DEFAULT_OUT_DARK = resolve(DEFAULT_OUT_DIR, 'favicon-dark.svg'); -const CURRENT_COLOR = 'currentColor'; - -export interface ColorizedFavicon { - light: string; - dark: string; -} - -export interface WriteThemeFaviconsOptions { - sourcePath?: string; - lightOutPath?: string; - darkOutPath?: string; - /** - * Fraction of the icon (0..1) to leave as an even margin on each side. - * Applied by wrapping the inner content in a `` so the - * source `src/lib/assets/logo.svg` is not modified. Pass 0 to disable. - */ - padding?: number; -} - -/** - * Replace every `currentColor` occurrence in the SVG with the given color. - * Pure: no filesystem access, so it is straightforward to unit-test. - */ -export function colorizeFaviconSvg( - svg: string, - lightColor: string, - darkColor: string -): ColorizedFavicon { - return { - dark: svg.replaceAll(CURRENT_COLOR, darkColor), - light: svg.replaceAll(CURRENT_COLOR, lightColor) - }; -} - -/** - * Shrink the inner SVG content uniformly and re-center it so `padding` (a - * 0..1 fraction) is reserved as equal margin on each side. Returns the input - * unchanged for non-positive padding, missing/invalid `viewBox`, or unexpected - * markup so the caller always gets a renderable SVG. - */ -export function padFaviconSvg(svg: string, padding: number): string { - if (!(padding > 0) || padding >= 1) return svg; - - const viewBoxMatch = svg.match(/viewBox\s*=\s*["']([^"']+)["']/i); - - if (!viewBoxMatch) return svg; - - const parts = viewBoxMatch[1] - .trim() - .split(/[\s,]+/) - .map(Number); - - if (parts.length !== 4 || parts.some((n) => !Number.isFinite(n))) return svg; - - const [, , width, height] = parts; - - if (width <= 0 || height <= 0) return svg; - - const scale = 1 - padding; - const translateX = (padding * width) / 2; - const translateY = (padding * height) / 2; - const openTagStart = svg.search(/', openTagStart); - - if (openTagEnd === -1) return svg; - - const closeStart = svg.lastIndexOf('`; - - return `${openTag}${group}${inner}${closeTag}`; -} - -/** - * Read `src/lib/assets/logo.svg`, colorize it for both themes, and write - * the results to the static directory so the PWA asset generator can consume - * them. Paths can be overridden for tests. - */ -export function writeThemeFavicons( - lightColor: string, - darkColor: string, - { - darkOutPath = DEFAULT_OUT_DARK, - lightOutPath = DEFAULT_OUT_LIGHT, - padding = 0, - sourcePath = DEFAULT_LOGO - }: WriteThemeFaviconsOptions = {} -): void { - const source = readFileSync(sourcePath, 'utf-8'); - const { dark, light } = colorizeFaviconSvg(source, lightColor, darkColor); - - mkdirSync(dirname(lightOutPath), { recursive: true }); - writeFileSync(lightOutPath, padFaviconSvg(light, padding)); - writeFileSync(darkOutPath, padFaviconSvg(dark, padding)); -} diff --git a/tools/ui/src/lib/assets/logo.svg b/tools/ui/src/lib/assets/logo.svg deleted file mode 100644 index 05424790afea..000000000000 --- a/tools/ui/src/lib/assets/logo.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/tools/ui/src/lib/components/app/misc/Logo.svelte b/tools/ui/src/lib/components/app/misc/Logo.svelte index ff2b7f2f0723..0dc5bb0bd0c9 100644 --- a/tools/ui/src/lib/components/app/misc/Logo.svelte +++ b/tools/ui/src/lib/components/app/misc/Logo.svelte @@ -1,5 +1,9 @@ diff --git a/tools/ui/src/lib/components/app/models/discover/ModelsDiscover.svelte b/tools/ui/src/lib/components/app/models/discover/ModelsDiscover.svelte index 292938d59c5c..4bc1c38eb531 100644 --- a/tools/ui/src/lib/components/app/models/discover/ModelsDiscover.svelte +++ b/tools/ui/src/lib/components/app/models/discover/ModelsDiscover.svelte @@ -18,12 +18,20 @@ let selectedId = $state(null); let searchQuery = $state(''); - // running and paused downloads both lead the list; a search owns the pane, so the - // section steps aside while a query is active + // running and paused downloads both lead the list, with or without a search query let downloadEntries = $derived(modelsStore.status.getDownloadEntries()); let isSearching = $derived(searchQuery.trim().length > 0); + // a search hit that is downloading already sits under Downloading, so it is listed once + let listedModels = $derived.by(() => { + if (!isSearching) return modelsDiscoverStore.models; + + const downloading = new Set(downloadEntries.map((entry) => repoOf(entry.repoWithTag))); + + return modelsDiscoverStore.models.filter((model) => !downloading.has(model.id)); + }); + /** Hub record for a repo the list does not carry, so its row still renders. */ function hubRecord(id: string): HfModelInfo { return { @@ -119,7 +127,7 @@ (selectedId = id)} showBaseModelAvatar /> @@ -130,7 +138,7 @@ > - {#if downloadEntries.length > 0 && !isSearching} + {#if downloadEntries.length > 0} "] with message_selection "latest" (default) or "earliest". +- Time range: from_timestamp (inclusive) and to_timestamp (exclusive), ISO 8601 like 2026-11-10 or 2026-11-10T14:30, local time. Only messages in the range are searched and shown, and only chats with messages in it are returned. With from_timestamp, message_selection defaults to "earliest". +Example, "what was my last question in the chat about paris?": by_matches=["%paris%"], message_selection="latest", limit_messages=4, then answer from the last user message. +Example, "what did we talk about yesterday?": from_timestamp=, to_timestamp=, limit_messages=2.`; + +export function buildSearchChatsToolDefinition(): OpenAIToolDefinition { + return { + function: { + description: DESCRIPTION, + name: SEARCH_CHATS_TOOL_NAME, + parameters: { + properties: { + by_conv_ids: { + description: 'Only these chats, by conv_id', + items: { type: JsonSchemaType.STRING }, + type: JsonSchemaType.ARRAY + }, + by_matches: { + description: `LIKE patterns matched against titles and message text, any of them, max ${SEARCH_CHATS_PATTERN_MAX_CHARS} chars each`, + items: { type: JsonSchemaType.STRING }, + type: JsonSchemaType.ARRAY + }, + from_timestamp: { + description: + 'Only messages at or after this time, ISO 8601, local time unless an offset is given', + type: JsonSchemaType.STRING + }, + include_current: { + description: 'Also include the current chat, default false', + type: JsonSchemaType.BOOLEAN + }, + limit_chats: { + description: `Max chats, default ${SEARCH_CHATS_LIMIT_CHATS_DEFAULT}, max ${SEARCH_CHATS_LIMIT_CHATS_MAX}`, + type: JsonSchemaType.NUMBER + }, + limit_messages: { + description: `Messages per chat, default ${SEARCH_CHATS_LIMIT_MESSAGES_DEFAULT}, max ${SEARCH_CHATS_LIMIT_MESSAGES_MAX}; 0 lists chats only`, + type: JsonSchemaType.NUMBER + }, + max_message_chars: { + description: `Characters shown per message, default ${SEARCH_CHATS_MESSAGE_CHARS_DEFAULT}, max ${SEARCH_CHATS_MESSAGE_CHARS_MAX}`, + type: JsonSchemaType.NUMBER + }, + message_selection: { + description: `Which messages per chat; default "${SearchChatsMessageSelection.MATCHING}" with by_matches, else "${SearchChatsMessageSelection.EARLIEST}" with from_timestamp, else "${SearchChatsMessageSelection.LATEST}"`, + enum: Object.values(SearchChatsMessageSelection), + type: JsonSchemaType.STRING + }, + offset_chats: { + description: 'Skip this many chats, for paging', + type: JsonSchemaType.NUMBER + }, + order_timestamp: { + description: `Chat order by last activity, default "${SearchChatsOrder.DESC}" (newest first)`, + enum: Object.values(SearchChatsOrder), + type: JsonSchemaType.STRING + }, + to_timestamp: { + description: + 'Only messages before this time (exclusive), same format as from_timestamp', + type: JsonSchemaType.STRING + } + }, + type: JsonSchemaType.OBJECT + } + }, + type: ToolCallType.FUNCTION + }; +} diff --git a/tools/ui/src/lib/constants/settings-keys.constants.ts b/tools/ui/src/lib/constants/settings-keys.constants.ts index 456b7017d098..910f492a386d 100644 --- a/tools/ui/src/lib/constants/settings-keys.constants.ts +++ b/tools/ui/src/lib/constants/settings-keys.constants.ts @@ -33,7 +33,6 @@ export const SETTINGS_KEYS = { FREQUENCY_PENALTY: 'frequency_penalty', FULL_HEIGHT_CODE_BLOCKS: 'fullHeightCodeBlocks', GROUP_MODELS_BY_FAMILY: 'groupModelsByFamily', - JS_SANDBOX_ENABLED: 'jsSandboxEnabled', LIVE_MARKDOWN_PREVIEW: 'liveMarkdownPreview', MAX_IMAGE_RESOLUTION: 'maxImageMPixels', MAX_TOKENS: 'max_tokens', diff --git a/tools/ui/src/lib/constants/settings.constants.ts b/tools/ui/src/lib/constants/settings.constants.ts index 65e192949e65..9fd0832e10a2 100644 --- a/tools/ui/src/lib/constants/settings.constants.ts +++ b/tools/ui/src/lib/constants/settings.constants.ts @@ -678,15 +678,7 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [ }, { defaultValue: false, - help: 'Expose a run_javascript tool to the model. Code runs in a Web Worker inside a sandboxed iframe with an opaque origin, isolated from the WebUI and its API, with a hard timeout.', - key: SETTINGS_KEYS.JS_SANDBOX_ENABLED, - label: 'JavaScript sandbox tool', - type: SettingsFieldType.CHECKBOX - }, - { - defaultValue: false, - dependsOn: SETTINGS_KEYS.JS_SANDBOX_ENABLED, - help: 'Pre-load nerdamer in the sandbox for symbolic computation: simplify, diff, integrate, solve, and more. Requires "JavaScript sandbox tool" to be enabled.', + help: 'Pre-load nerdamer in the run_javascript sandbox for symbolic computation: simplify, diff, integrate, solve, and more.', key: SETTINGS_KEYS.SYMBOLIC_MATH_ENABLED, label: 'Symbolic math (nerdamer)', type: SettingsFieldType.CHECKBOX diff --git a/tools/ui/src/lib/constants/tool-ui.constants.ts b/tools/ui/src/lib/constants/tool-ui.constants.ts index b5c09a653067..1078ebfbee5c 100644 --- a/tools/ui/src/lib/constants/tool-ui.constants.ts +++ b/tools/ui/src/lib/constants/tool-ui.constants.ts @@ -16,6 +16,7 @@ import { FileSearch, FileText, Info, + MessagesSquare, SearchCode, Terminal } from '@lucide/svelte'; @@ -34,6 +35,11 @@ export const TOOL_UI: Readonly> = { label: 'Run JavaScript', source: ToolSource.BROWSER }, + [BuiltInTool.BROWSER_SEARCH_CHATS]: { + icon: MessagesSquare, + label: 'Search chats', + source: ToolSource.BROWSER + }, [BuiltInTool.SERVER_EDIT_FILE]: { icon: FilePen, label: 'Edit file', source: ToolSource.SERVER }, [BuiltInTool.SERVER_EXEC_SHELL_COMMAND]: { icon: Terminal, diff --git a/tools/ui/src/lib/enums/index.ts b/tools/ui/src/lib/enums/index.ts index 3527100b4c8e..134666eb5a62 100644 --- a/tools/ui/src/lib/enums/index.ts +++ b/tools/ui/src/lib/enums/index.ts @@ -112,6 +112,8 @@ export { KeyboardKey } from './keyboard.enums'; export { BuiltInTool, GlobSearchType, + SearchChatsMessageSelection, + SearchChatsOrder, ToolSource, ToolPermissionDecision, ToolResponseField diff --git a/tools/ui/src/lib/enums/mcp.enums.ts b/tools/ui/src/lib/enums/mcp.enums.ts index fc358202bfd8..6be96d8a26eb 100644 --- a/tools/ui/src/lib/enums/mcp.enums.ts +++ b/tools/ui/src/lib/enums/mcp.enums.ts @@ -54,6 +54,8 @@ export enum MCPContentType { * JSON Schema types used in MCP tool definitions */ export enum JsonSchemaType { + ARRAY = 'array', + BOOLEAN = 'boolean', NUMBER = 'number', OBJECT = 'object', STRING = 'string' diff --git a/tools/ui/src/lib/enums/tools.enums.ts b/tools/ui/src/lib/enums/tools.enums.ts index db55837a8378..2bda6872284b 100644 --- a/tools/ui/src/lib/enums/tools.enums.ts +++ b/tools/ui/src/lib/enums/tools.enums.ts @@ -45,6 +45,7 @@ export enum BuiltInTool { BROWSER_GET_DATETIME = 'get_datetime', BROWSER_READ_MEDIA = 'read_media', BROWSER_RUN_JAVASCRIPT = 'run_javascript', + BROWSER_SEARCH_CHATS = 'search_chats', SERVER_EDIT_FILE = 'edit_file', SERVER_EXEC_SHELL_COMMAND = 'exec_shell_command', SERVER_FILE_GLOB_SEARCH = 'file_glob_search', @@ -53,3 +54,16 @@ export enum BuiltInTool { SERVER_READ_FILE = 'read_file', SERVER_WRITE_FILE = 'write_file' } + +/** Wire values of the `search_chats` `message_selection` parameter */ +export enum SearchChatsMessageSelection { + EARLIEST = 'earliest', + LATEST = 'latest', + MATCHING = 'matching' +} + +/** Wire values of the `search_chats` `order_timestamp` parameter */ +export enum SearchChatsOrder { + ASC = 'asc', + DESC = 'desc' +} diff --git a/tools/ui/src/lib/services/database.service.ts b/tools/ui/src/lib/services/database.service.ts index af9fad9a2d48..f11e9860606b 100644 --- a/tools/ui/src/lib/services/database.service.ts +++ b/tools/ui/src/lib/services/database.service.ts @@ -463,6 +463,10 @@ export class DatabaseService { const newConv: DatabaseConversation = { currNode: lastClonedMessage.id, cwd: sourceConv.cwd, + disabledToolCategories: sourceConv.disabledToolCategories + ? [...sourceConv.disabledToolCategories] + : undefined, + disabledTools: sourceConv.disabledTools ? [...sourceConv.disabledTools] : undefined, forkedFromConversationId: sourceConvId, groupId: sourceConv.groupId, id: newConvId, @@ -614,6 +618,15 @@ export class DatabaseService { ); } + /** Run `fn` in a readonly transaction over all tables. `fn` must await only Dexie calls, else the transaction commits early */ + static async readOnly( + fn: (tables: Pick) => Promise + ): Promise { + return db.transaction('r', [db[IDXDB_TABLES.conversations], db[IDXDB_TABLES.messages]], () => + fn(db) + ); + } + /** * Puts conversations into a group, or out of any group when `groupId` is null. * A conversation that joins a group is unpinned. diff --git a/tools/ui/src/lib/services/index.ts b/tools/ui/src/lib/services/index.ts index a8072e55bcda..0e584520d35d 100644 --- a/tools/ui/src/lib/services/index.ts +++ b/tools/ui/src/lib/services/index.ts @@ -300,6 +300,14 @@ export { MCPService } from './mcp.service'; */ export { SandboxService } from './sandbox.service'; +/** + * **SearchChatsService** - Read-only search over saved chats, executor of the search_chats browser tool + * + * @see buildSearchChatsToolDefinition in constants/search-chats - tool schema sent to the LLM + * @see utils/search-chats - parameter parsing, matching and formatting + */ +export { SearchChatsService } from './search-chats.service'; + /** * **RouterService** — Dynamic route URL construction utility * diff --git a/tools/ui/src/lib/services/migration.service.ts b/tools/ui/src/lib/services/migration.service.ts index 6df50f45bf84..21e65b2f70ff 100644 --- a/tools/ui/src/lib/services/migration.service.ts +++ b/tools/ui/src/lib/services/migration.service.ts @@ -19,12 +19,14 @@ import { LEGACY_AGENTIC_REGEX, LEGACY_REASONING_TAGS, NEW_TO_DEPRECATED_MAP, + SEARCH_CHATS_TOOL_KEY, SETTINGS_KEYS, STORAGE_APP_NAME, STORAGE_APP_NAME_DEPRECATED } from '$lib/constants'; import { BooleanString, MessageRole } from '$lib/enums'; import type { McpServerOverride } from '$lib/types/database'; +import { withSearchChatsDisabled } from '$lib/utils/search-chats'; import Dexie from 'dexie'; // Types @@ -829,6 +831,42 @@ const mcpServerOverridesToToolPolicyMigration: Migration = { ); } }; +const SEARCH_CHATS_DEFAULT_DISABLED_MIGRATION_ID = 'search-chats-default-disabled-v1'; +const searchChatsDefaultDisabledMigration: Migration = { + description: 'Disable the search_chats tool by default, globally and in existing conversations', + id: SEARCH_CHATS_DEFAULT_DISABLED_MIGRATION_ID, + + async run(): Promise { + // tool policy is a deny-list, so a new tool is enabled everywhere unless its key is added to the defaults and to each conversation + let defaults: string[] = []; + + try { + const raw = localStorage.getItem(DISABLED_TOOL_KEYS_LOCALSTORAGE_KEY); + const parsed: unknown = raw ? JSON.parse(raw) : []; + + if (Array.isArray(parsed)) + defaults = parsed.filter((k): k is string => typeof k === 'string'); + } catch { + // unreadable defaults are replaced below + } + + localStorage.setItem( + DISABLED_TOOL_KEYS_LOCALSTORAGE_KEY, + JSON.stringify(withSearchChatsDisabled(defaults)) + ); + + const db = await getDatabaseService(); + const conversations = await db.getAllConversations(); + + for (const conv of conversations) { + if (conv.disabledTools?.includes(SEARCH_CHATS_TOOL_KEY)) continue; + + await db.updateConversation(conv.id, { + disabledTools: withSearchChatsDisabled(conv.disabledTools) + }); + } + } +}; const migrations: Migration[] = [ localStorageMigration, idxdbMigration, @@ -840,7 +878,8 @@ const migrations: Migration[] = [ configTypesMigration, renderKeysMigration, modelOrgNameKeyMigration, - mcpServerOverridesToToolPolicyMigration + mcpServerOverridesToToolPolicyMigration, + searchChatsDefaultDisabledMigration ]; export const MigrationService = { diff --git a/tools/ui/src/lib/services/search-chats.service.ts b/tools/ui/src/lib/services/search-chats.service.ts new file mode 100644 index 000000000000..fe2fad1a06bc --- /dev/null +++ b/tools/ui/src/lib/services/search-chats.service.ts @@ -0,0 +1,89 @@ +/** + * SearchChatsService - executor for the search_chats browser tool + * + * Reads conversations and messages in readonly transactions; matching and formatting live in utils/search-chats. + */ + +import { DatabaseService } from './database.service'; +import type { ToolExecutionResult } from '$lib/types'; +import type { DatabaseConversation, DatabaseMessage } from '$lib/types/database'; +import { + parseSearchChatsParams, + searchChats, + SearchChatsError, + type SearchChatsTimeRange +} from '$lib/utils/search-chats'; + +function loadConversations(ids?: string[]): Promise { + return DatabaseService.readOnly(async ({ conversations }) => { + if (!ids) return conversations.toArray(); + + const found = await conversations.bulkGet(ids); + + return found.filter((c): c is DatabaseConversation => !!c); + }); +} + +/** Attachment payloads (base64 media, file text) are dropped as rows stream in, only their names are kept */ +function withoutPayloads({ extra, ...message }: DatabaseMessage): DatabaseMessage { + return { + ...message, + extra: extra?.map(({ name, type }) => ({ name, type })) as DatabaseMessage['extra'] + }; +} + +/** One transaction, so the range lookup and the read see the same data */ +function loadMessages( + convIds: string[] | null, + range?: SearchChatsTimeRange +): Promise { + return DatabaseService.readOnly(async ({ messages }) => { + let ids = convIds; + + if (range) { + const { from, to } = range; + const index = messages.where('timestamp'); + const inRange = + from !== undefined && to !== undefined + ? index.between(from, to, true, false) + : from !== undefined + ? index.aboveOrEqual(from) + : index.below(to); + const active = new Set(); + + await inRange.each((m) => active.add(m.convId)); + ids = ids ? ids.filter((id) => active.has(id)) : [...active]; + } + + const rows: DatabaseMessage[] = []; + + await (ids ? messages.where('convId').anyOf(ids) : messages.toCollection()).each((m) => + rows.push(withoutPayloads(m)) + ); + + return rows; + }); +} + +const loader = { messages: loadMessages }; + +export class SearchChatsService { + /** `currentConversationId` is hidden from results unless the model sets include_current */ + static async executeTool( + args: Record, + currentConversationId?: string + ): Promise { + try { + const params = parseSearchChatsParams(args); + const conversations = await loadConversations(params.byConvIds); + const content = await searchChats(conversations, params, loader, currentConversationId); + + return { content, isError: false }; + } catch (err) { + if (err instanceof SearchChatsError) + return { content: `Error: ${err.message}`, isError: true }; + + throw err; + } + } +} diff --git a/tools/ui/src/lib/stores/agentic/index.svelte.ts b/tools/ui/src/lib/stores/agentic/index.svelte.ts index f22b6b954e9f..bc5d3890322f 100644 --- a/tools/ui/src/lib/stores/agentic/index.svelte.ts +++ b/tools/ui/src/lib/stores/agentic/index.svelte.ts @@ -31,6 +31,7 @@ import { import { ChatService } from '$lib/services'; import { ReadMediaService } from '$lib/services/read-media.service'; import { SandboxService } from '$lib/services/sandbox.service'; +import { SearchChatsService } from '$lib/services/search-chats.service'; import { ToolsService } from '$lib/services/tools.service'; // direct imports between stores, not via the barrel, to avoid circular deps import { AgenticGates } from '$lib/stores/agentic/gates.svelte'; @@ -825,6 +826,8 @@ class AgenticStore { executionResult = executeGetDatetimeTool(); } else if (toolName === BuiltInTool.SERVER_GET_INFO) { executionResult = executeBrowserInfoTool(); + } else if (toolName === BuiltInTool.BROWSER_SEARCH_CHATS) { + executionResult = await SearchChatsService.executeTool(args, conversationId); } else if (toolName === BuiltInTool.BROWSER_READ_MEDIA) { executionResult = await ReadMediaService.executeTool( args, diff --git a/tools/ui/src/lib/stores/conversations/index.svelte.ts b/tools/ui/src/lib/stores/conversations/index.svelte.ts index e338ffcc3f22..f55f74c12208 100644 --- a/tools/ui/src/lib/stores/conversations/index.svelte.ts +++ b/tools/ui/src/lib/stores/conversations/index.svelte.ts @@ -29,6 +29,7 @@ import { findLeafNode, generateConversationTitle } from '$lib/utils'; +import { withSearchChatsDisabled } from '$lib/utils/search-chats'; import { SvelteSet } from 'svelte/reactivity'; import { toast } from 'svelte-sonner'; @@ -529,7 +530,13 @@ class ConversationsStore implements ConversationsPreferencesHost { async importConversationsData( data: ExportedConversations ): Promise<{ imported: DatabaseConversation[]; skipped: DatabaseConversation[] }> { - const result = await DatabaseService.importConversations(data); + // exports can predate search_chats or come from another device, keep it off like for existing chats + const result = await DatabaseService.importConversations( + (Array.isArray(data) ? data : [data]).map(({ conv, messages }) => ({ + conv: { ...conv, disabledTools: withSearchChatsDisabled(conv.disabledTools) }, + messages + })) + ); await this.loadConversations(); diff --git a/tools/ui/src/lib/stores/models-discover/index.svelte.ts b/tools/ui/src/lib/stores/models-discover/index.svelte.ts index c4658485ab16..9742ab6498a7 100644 --- a/tools/ui/src/lib/stores/models-discover/index.svelte.ts +++ b/tools/ui/src/lib/stores/models-discover/index.svelte.ts @@ -14,7 +14,7 @@ import type { HfModelInfo, HfModelSibling } from '$lib/types/huggingface'; -import { isAuxSidecar } from '$lib/utils'; +import { isAuxSidecar, orgOf } from '$lib/utils'; import { SvelteMap } from 'svelte/reactivity'; /** Min/max GGUF file size (bytes) across the quants of one repo. */ @@ -141,7 +141,7 @@ class ModelsDiscoverStore { if (requestId !== this.searchRequestId) return; - this.models = results; + this.models = this.baseOrgFirst(results); this.error = null; } catch (err) { if (requestId !== this.searchRequestId) return; @@ -181,6 +181,23 @@ class ModelsDiscoverStore { return request; } + /** + * Repos published by their base model's own org first (e.g. `Qwen/Qwen3-8B-GGUF` + * ahead of third-party quants of `Qwen/Qwen3-8B`); the hub's order holds otherwise. + */ + private baseOrgFirst(models: HfModelInfo[]): HfModelInfo[] { + // org names are case-insensitive on the hub, and base_model tags are not always canonical + const isBaseOrg = (model: HfModelInfo) => { + const org = orgOf(model.id).toLowerCase(); + + return HuggingFaceService.getBaseModels(model).some( + (base) => orgOf(base).toLowerCase() === org + ); + }; + + return [...models.filter(isBaseOrg), ...models.filter((model) => !isBaseOrg(model))]; + } + /** * Sizes the catalog lists under this repo. Never empty: an entry with no parsable * size contributes the build's own. diff --git a/tools/ui/src/lib/stores/models/status.svelte.ts b/tools/ui/src/lib/stores/models/status.svelte.ts index 3cc0954fbc7f..a2691a1a819b 100644 --- a/tools/ui/src/lib/stores/models/status.svelte.ts +++ b/tools/ui/src/lib/stores/models/status.svelte.ts @@ -26,6 +26,7 @@ import type { ModelPropsManager } from '$lib/stores/models/props.svelte'; import { serverStore } from '$lib/stores/server.svelte'; // explicit type imports: the app.d.ts globals resolve to `any`, so import the real types import type { + ApiModelsSseDownloadFailedData, ApiModelsSseDownloadProgressData, ModelDownloadEntry, ModelDownloadProgress @@ -656,6 +657,12 @@ export class ModelStatusManager { if (event.event === ServerModelsSseEventType.DOWNLOAD_FAILED) { request = this.stopRequests.get(event.model); this.stopRequests.delete(event.model); + + // a stop another client asked for (e.g. the Llama app) reads as a pause: a + // cancel follows with model_remove, which drops the row + if (!request && (event.data as ApiModelsSseDownloadFailedData | undefined)?.stopped) { + request = ModelDownloadStopRequest.PAUSE; + } } const progress = this.downloadProgress.get(event.model) ?? null; @@ -718,6 +725,20 @@ export class ModelStatusManager { total += file?.total ?? 0; } + // a download another client started (e.g. the Llama app) pulls the sidecars the + // list reports for it; the first event of one the list does not know refreshes it + if (!this.downloadSidecars.has(event.model)) { + const listed = this.host.routerModels.find( + (m) => downloadIdKey(m.id) === downloadIdKey(event.model) + ); + + if (listed) { + this.downloadSidecars.set(event.model, listed.sidecars ?? []); + } else if (!this.downloadProgress.has(event.model)) { + void this.host.fetchRouterModels(); + } + } + this.downloadProgress.set(event.model, { downloadedBytes: downloaded, files: progress, @@ -809,14 +830,17 @@ export class ModelStatusManager { private removeRouterModel(modelId: string): void { const idx = this.host.routerModels.findIndex((m) => m.id === modelId); + // download state goes even for a row the list does not carry yet, e.g. a + // download another client started and then cancelled + this.downloadProgress.delete(modelId); + this.failedDownloads.delete(modelId); + this.deletePausedDownload(modelId); + this.downloadSidecars.delete(modelId); + this.stopRequests.delete(modelId); + if (idx !== -1) { this.host.routerModels = this.host.routerModels.filter((m) => m.id !== modelId); this.loadProgress.delete(modelId); - this.downloadProgress.delete(modelId); - this.failedDownloads.delete(modelId); - this.deletePausedDownload(modelId); - this.downloadSidecars.delete(modelId); - this.stopRequests.delete(modelId); this.rejectStatus(modelId, new Error(`Model removed: ${this.host.toDisplayName(modelId)}`)); } diff --git a/tools/ui/src/lib/stores/tools.svelte.ts b/tools/ui/src/lib/stores/tools.svelte.ts index 1d4133408b54..a97dae58a092 100644 --- a/tools/ui/src/lib/stores/tools.svelte.ts +++ b/tools/ui/src/lib/stores/tools.svelte.ts @@ -12,6 +12,7 @@ import { buildBrowserInfoToolDefinition, buildGetDatetimeToolDefinition, buildReadMediaToolDefinition, + buildSearchChatsToolDefinition, DISABLED_TOOL_CATEGORIES_LOCALSTORAGE_KEY, DISABLED_TOOL_KEYS_LOCALSTORAGE_KEY, HOME_TILDE, @@ -112,12 +113,12 @@ class ToolsStore { } get browserTools(): OpenAIToolDefinition[] { - const tools: OpenAIToolDefinition[] = [buildGetDatetimeToolDefinition()]; - - if (settingsStore.config.jsSandboxEnabled) { - tools.push(buildSandboxToolDefinition(!!settingsStore.config.symbolicMathEnabled)); - } - + const tools: OpenAIToolDefinition[] = [ + buildGetDatetimeToolDefinition(), + buildSandboxToolDefinition(!!settingsStore.config.symbolicMathEnabled), + // disabled by default, see searchChatsDefaultDisabledMigration + buildSearchChatsToolDefinition() + ]; const readMedia = this.readMediaTool(); if (readMedia) tools.push(readMedia); diff --git a/tools/ui/src/lib/types/api.d.ts b/tools/ui/src/lib/types/api.d.ts index d3bfbb184369..dbca7ca82b27 100644 --- a/tools/ui/src/lib/types/api.d.ts +++ b/tools/ui/src/lib/types/api.d.ts @@ -156,6 +156,11 @@ export interface ApiModelsSseDownloadProgressData { progress: Record; } +/** download_failed data: `stopped` when a client paused or cancelled the download. */ +export interface ApiModelsSseDownloadFailedData { + stopped?: boolean; +} + /** * Event kind multiplexed on the /models/sse feed. * Only the status_* events carry a status payload, models_reload signals a @@ -168,7 +173,7 @@ export interface ApiModelsSseDownloadProgressData { export interface ApiModelsSseEvent { model: string; event: ServerModelsSseEventType; - data?: ApiModelsSseData | ApiModelsSseDownloadProgressData; + data?: ApiModelsSseData | ApiModelsSseDownloadProgressData | ApiModelsSseDownloadFailedData; } /** diff --git a/tools/ui/src/lib/types/index.ts b/tools/ui/src/lib/types/index.ts index 1a3b18a222c3..5c8c5e8b8b35 100644 --- a/tools/ui/src/lib/types/index.ts +++ b/tools/ui/src/lib/types/index.ts @@ -15,6 +15,7 @@ export type { ApiModelsSseProgress, ApiModelsSseData, ApiModelsSseDownloadProgressData, + ApiModelsSseDownloadFailedData, ApiModelsSseEvent, ApiModelsDownloadRequest, ApiModelsDownloadResponse, diff --git a/tools/ui/src/lib/utils/formatters.ts b/tools/ui/src/lib/utils/formatters.ts index 6a174cd487a7..ab09522772b3 100644 --- a/tools/ui/src/lib/utils/formatters.ts +++ b/tools/ui/src/lib/utils/formatters.ts @@ -132,6 +132,22 @@ export function formatRelativeTime(timestamp: number): string { return new Date(timestamp).toLocaleDateString(); } +function pad2(value: number): string { + return String(value).padStart(2, '0'); +} + +/** ISO 8601 in local time, e.g. `2026-08-17T14:05:09+02:00` */ +export function formatLocalIso(date: Date): string { + // getTimezoneOffset() counts minutes behind UTC, ISO 8601 counts them ahead + const offset = -date.getTimezoneOffset(); + const sign = offset < 0 ? '-' : '+'; + const absOffset = Math.abs(offset); + const day = `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`; + const time = `${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`; + + return `${day}T${time}${sign}${pad2(Math.floor(absOffset / 60))}:${pad2(absOffset % 60)}`; +} + /** * Format time as HH:MM:SS in 24-hour format * diff --git a/tools/ui/src/lib/utils/get-datetime.ts b/tools/ui/src/lib/utils/get-datetime.ts index d971d728edf3..69e41ce0fc0b 100644 --- a/tools/ui/src/lib/utils/get-datetime.ts +++ b/tools/ui/src/lib/utils/get-datetime.ts @@ -6,31 +6,16 @@ * @see buildGetDatetimeToolDefinition in constants/get-datetime.ts - tool schema sent to the LLM */ +import { formatLocalIso } from './formatters'; import type { ToolExecutionResult } from '$lib/types'; -function pad(value: number): string { - return String(value).padStart(2, '0'); -} - -/** ISO 8601 in local time, e.g. `2026-08-17T14:05:09+02:00` */ -function localIsoString(date: Date): string { - // getTimezoneOffset() counts minutes behind UTC, ISO 8601 counts them ahead - const offset = -date.getTimezoneOffset(); - const sign = offset < 0 ? '-' : '+'; - const absOffset = Math.abs(offset); - const day = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`; - const time = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`; - - return `${day}T${time}${sign}${pad(Math.floor(absOffset / 60))}:${pad(absOffset % 60)}`; -} - /** The `result` field keeps the shape the `get_datetime` renderer already reads. */ export function executeGetDatetimeTool(): ToolExecutionResult { const now = new Date(); return { content: JSON.stringify({ - result: localIsoString(now), + result: formatLocalIso(now), timezone: Intl.DateTimeFormat().resolvedOptions().timeZone }), isError: false diff --git a/tools/ui/src/lib/utils/index.ts b/tools/ui/src/lib/utils/index.ts index f8de87fafde3..a7ed91bd8b2a 100644 --- a/tools/ui/src/lib/utils/index.ts +++ b/tools/ui/src/lib/utils/index.ts @@ -99,6 +99,7 @@ export { formatNumber, formatJsonPretty, formatTime, + formatLocalIso, formatPerformanceTime, formatRelativeTime, formatAttachmentText diff --git a/tools/ui/src/lib/utils/search-chats.ts b/tools/ui/src/lib/utils/search-chats.ts new file mode 100644 index 000000000000..b9811bb415ff --- /dev/null +++ b/tools/ui/src/lib/utils/search-chats.ts @@ -0,0 +1,665 @@ +/** + * search_chats core: parameter parsing, matching and formatting. Data comes through a loader, so this has no IndexedDB access. + * Only user and assistant text on the visible branch is searched and shown, so tool output (e.g. older search results) cannot match. + */ + +import { filterByLeafNodeId } from './branching'; +import { formatLocalIso } from './formatters'; +import { + SEARCH_CHATS_CUT_NOTICE, + SEARCH_CHATS_DATE_REGEX, + SEARCH_CHATS_DATE_TIME_REGEX, + SEARCH_CHATS_ELLIPSIS, + SEARCH_CHATS_EXCERPT_LEAD_RATIO, + SEARCH_CHATS_EXCERPT_RECENTER_RATIO, + SEARCH_CHATS_FIELD_SEPARATOR, + SEARCH_CHATS_ID_MAX_CHARS, + SEARCH_CHATS_LIMIT_CHATS_DEFAULT, + SEARCH_CHATS_LIMIT_CHATS_MAX, + SEARCH_CHATS_LIMIT_MESSAGES_DEFAULT, + SEARCH_CHATS_LIMIT_MESSAGES_MAX, + SEARCH_CHATS_MAX_IDS, + SEARCH_CHATS_MAX_PATTERNS, + SEARCH_CHATS_MESSAGE_CHARS_DEFAULT, + SEARCH_CHATS_MESSAGE_CHARS_MAX, + SEARCH_CHATS_MESSAGE_CHARS_MIN, + SEARCH_CHATS_OUTPUT_MAX_CHARS, + SEARCH_CHATS_PATTERN_MAX_CHARS, + SEARCH_CHATS_TOOL_KEY +} from '$lib/constants'; +import { MessageRole, SearchChatsMessageSelection, SearchChatsOrder } from '$lib/enums'; +import type { DatabaseConversation, DatabaseMessage } from '$lib/types/database'; + +export class SearchChatsError extends Error { + constructor(message: string) { + super(message); + this.name = 'SearchChatsError'; + } +} + +export interface SearchChatsParams { + byConvIds?: string[]; + byMatches?: string[]; + /** Inclusive, ms since epoch */ + fromTimestamp?: number; + /** Exclusive, ms since epoch */ + toTimestamp?: number; + order: SearchChatsOrder; + limitChats: number; + offsetChats: number; + limitMessages: number; + messageSelection: SearchChatsMessageSelection; + maxMessageChars: number; + includeCurrent: boolean; +} + +export interface SearchChatsTimeRange { + from?: number; + to?: number; +} + +export interface SearchChatsLoader { + /** Messages of the given conversations (all for `null`); with `range`, only of conversations with a message in [from, to) */ + messages(convIds: string[] | null, range?: SearchChatsTimeRange): Promise; +} + +/** Tool policy with search_chats disabled, for rows that predate the tool */ +export function withSearchChatsDisabled(disabledTools: string[] = []): string[] { + return disabledTools.includes(SEARCH_CHATS_TOOL_KEY) + ? disabledTools + : [...disabledTools, SEARCH_CHATS_TOOL_KEY]; +} + +/** `text.slice(start, end)` without cutting a surrogate pair in half */ +function sliceText(text: string, start: number, end: number = text.length): string { + const isHigh = (i: number) => { + const code = text.charCodeAt(i); + + return code >= 0xd800 && code <= 0xdbff; + }; + + if (start > 0 && isHigh(start - 1)) start++; + + if (end > start && end < text.length && isHigh(end - 1)) end--; + + return text.slice(start, Math.max(start, end)); +} + +function isCalendarDate(year: number, month: number, day: number): boolean { + const date = new Date(Date.UTC(year, month - 1, day)); + + return date.getUTCMonth() === month - 1 && date.getUTCDate() === day; +} + +function stringList( + raw: unknown, + name: string, + maxEntries: number, + maxChars: number +): string[] | undefined { + if (raw === undefined || raw === null) return undefined; + + const list = typeof raw === 'string' ? [raw] : raw; + + if (!Array.isArray(list) || !list.every((v) => typeof v === 'string' && v.trim() !== '')) { + throw new SearchChatsError(`${name} must be an array of non-empty strings`); + } + + if (list.length === 0) return undefined; + + if (list.length > maxEntries) { + throw new SearchChatsError(`${name} takes at most ${maxEntries} entries`); + } + + if (list.some((v) => v.length > maxChars)) { + throw new SearchChatsError(`${name} entries must be at most ${maxChars} characters`); + } + + return list.map((v) => v.trim()); +} + +function integer(raw: unknown, name: string, min: number, max: number, fallback: number): number { + if (raw === undefined || raw === null || raw === '') return fallback; + + const n = Number(raw); + + if (!Number.isInteger(n) || n < min || n > max) { + throw new SearchChatsError(`${name} must be an integer from ${min} to ${max}`); + } + + return n; +} + +function oneOf(raw: unknown, name: string, options: T[], fallback: T): T { + if (raw === undefined || raw === null || raw === '') return fallback; + + const value = String(raw).toLowerCase() as T; + + if (!options.includes(value)) { + throw new SearchChatsError(`${name} must be one of: ${options.join(', ')}`); + } + + return value; +} + +/** ISO 8601 date or date-time; without an offset it is the user's local time */ +function timestamp(raw: unknown, name: string): number | undefined { + if (raw === undefined || raw === null || raw === '') return undefined; + + const error = new SearchChatsError( + `${name} must be an ISO 8601 date or date-time, e.g. 2026-11-10 or 2026-11-10T14:30 (local time unless an offset is given)` + ); + + if (typeof raw !== 'string') throw error; + + const value = raw.trim().replace(' ', 'T'); + const isDate = SEARCH_CHATS_DATE_REGEX.test(value); + + if (!isDate && !SEARCH_CHATS_DATE_TIME_REGEX.test(value)) throw error; + + const [year, month, day] = value.slice(0, 10).split('-').map(Number); + + // Date.parse rolls 2026-02-30T10:00 over to March, it does not reject it + if (!isCalendarDate(year, month, day)) throw error; + + let ms: number; + + if (isDate) { + // Date.parse reads a date-only string as UTC midnight, the user means local midnight + ms = new Date(year, month - 1, day).getTime(); + } else { + const [hours, minutes, seconds = 0] = value + .slice(11, 19) + .split(/[:.Z+-]/) + .map(Number); + + if (hours > 23 || minutes > 59 || seconds > 59) throw error; + + ms = Date.parse(value); + } + + if (Number.isNaN(ms)) throw error; + + return ms; +} + +/** Throws SearchChatsError with a message for the model */ +export function parseSearchChatsParams(raw: Record): SearchChatsParams { + const byConvIds = stringList( + raw.by_conv_ids, + 'by_conv_ids', + SEARCH_CHATS_MAX_IDS, + SEARCH_CHATS_ID_MAX_CHARS + ); + const byMatches = stringList( + raw.by_matches, + 'by_matches', + SEARCH_CHATS_MAX_PATTERNS, + SEARCH_CHATS_PATTERN_MAX_CHARS + ); + const fromTimestamp = timestamp(raw.from_timestamp, 'from_timestamp'); + const toTimestamp = timestamp(raw.to_timestamp, 'to_timestamp'); + + if (fromTimestamp !== undefined && toTimestamp !== undefined && toTimestamp <= fromTimestamp) { + throw new SearchChatsError('to_timestamp must be after from_timestamp'); + } + + const defaultSelection = byMatches + ? SearchChatsMessageSelection.MATCHING + : fromTimestamp !== undefined + ? SearchChatsMessageSelection.EARLIEST + : SearchChatsMessageSelection.LATEST; + const messageSelection = oneOf( + raw.message_selection, + 'message_selection', + Object.values(SearchChatsMessageSelection), + defaultSelection + ); + + if (messageSelection === SearchChatsMessageSelection.MATCHING && !byMatches) { + throw new SearchChatsError( + `message_selection "${SearchChatsMessageSelection.MATCHING}" needs by_matches; use "${SearchChatsMessageSelection.LATEST}" or "${SearchChatsMessageSelection.EARLIEST}"` + ); + } + + return { + byConvIds, + byMatches, + fromTimestamp, + includeCurrent: raw.include_current === true || raw.include_current === 'true', + limitChats: integer( + raw.limit_chats, + 'limit_chats', + 1, + SEARCH_CHATS_LIMIT_CHATS_MAX, + SEARCH_CHATS_LIMIT_CHATS_DEFAULT + ), + limitMessages: integer( + raw.limit_messages, + 'limit_messages', + 0, + SEARCH_CHATS_LIMIT_MESSAGES_MAX, + SEARCH_CHATS_LIMIT_MESSAGES_DEFAULT + ), + maxMessageChars: integer( + raw.max_message_chars, + 'max_message_chars', + SEARCH_CHATS_MESSAGE_CHARS_MIN, + SEARCH_CHATS_MESSAGE_CHARS_MAX, + SEARCH_CHATS_MESSAGE_CHARS_DEFAULT + ), + messageSelection, + offsetChats: integer(raw.offset_chats, 'offset_chats', 0, Number.MAX_SAFE_INTEGER, 0), + order: oneOf( + raw.order_timestamp, + 'order_timestamp', + Object.values(SearchChatsOrder), + SearchChatsOrder.DESC + ), + toTimestamp + }; +} + +/** SQL LIKE (`%` any run, `_` one char) without regex, so a pattern cannot backtrack exponentially */ +function like(text: string, pattern: string): boolean { + let si = 0; + let pi = 0; + let star = -1; + let mark = 0; + + while (si < text.length) { + if ( + pi < pattern.length && + (pattern[pi] === '_' || (pattern[pi] !== '%' && pattern[pi] === text[si])) + ) { + si++; + pi++; + } else if (pi < pattern.length && pattern[pi] === '%') { + star = pi++; + mark = si; + } else if (star !== -1) { + pi = star + 1; + si = ++mark; + } else { + return false; + } + } + + while (pi < pattern.length && pattern[pi] === '%') pi++; + + return pi === pattern.length; +} + +interface Matcher { + test(text: string): boolean; + /** Offset in `text` of the longest literal part of the first matching pattern, -1 if none */ + locate(text: string): number; +} + +function buildMatcher(patterns: string[]): Matcher { + // a pattern without % means "contains" + const compiled = patterns.map((p) => { + const lower = p.toLowerCase(); + const pattern = lower.includes('%') ? lower : `%${lower}%`; + const needle = pattern + .split(/[%_]+/) + .reduce((best, part) => (part.length > best.length ? part : best), ''); + + return { needle, pattern }; + }); + + return { + locate: (text) => { + const lower = text.toLowerCase(); + + // lowercasing can change the length (e.g. U+0130), then offsets do not map back + if (lower.length !== text.length) return -1; + + const hit = compiled.find(({ pattern }) => like(lower, pattern)); + + if (!hit) return -1; + + return hit.needle ? lower.indexOf(hit.needle) : 0; + }, + test: (text) => { + const lower = text.toLowerCase(); + + return compiled.some(({ pattern }) => like(lower, pattern)); + } + }; +} + +/** User and assistant text on the visible branch, in chat order */ +function visibleMessages( + conv: DatabaseConversation, + messages: DatabaseMessage[] +): DatabaseMessage[] { + if (messages.length === 0) return []; + + return filterByLeafNodeId(messages, conv.currNode ?? '').filter( + (m) => + (m.role === MessageRole.USER || m.role === MessageRole.ASSISTANT) && + !m.isSynthetic && + typeof m.content === 'string' && + m.content.trim() !== '' + ); +} + +function formatDate(ms: number): string { + const date = new Date(ms); + + return Number.isNaN(date.getTime()) ? 'unknown' : formatLocalIso(date); +} + +function excerpt(text: string, maxChars: number, matchAt: number): string { + if (text.length <= maxChars) return text; + + if (matchAt > maxChars * SEARCH_CHATS_EXCERPT_RECENTER_RATIO) { + const lead = Math.floor(maxChars * SEARCH_CHATS_EXCERPT_LEAD_RATIO); + const start = Math.max(0, Math.min(matchAt - lead, text.length - maxChars)); + const end = start + maxChars; + const before = start > 0 ? SEARCH_CHATS_ELLIPSIS : ''; + const after = end < text.length ? `${SEARCH_CHATS_ELLIPSIS}[+${text.length - end} chars]` : ''; + + return `${before}${sliceText(text, start, end)}${after}`; + } + + return `${sliceText(text, 0, maxChars)}${SEARCH_CHATS_ELLIPSIS}[+${text.length - maxChars} chars]`; +} + +interface ChatHit { + conv: DatabaseConversation; + /** Visible messages of the whole chat, positions are counted on these */ + messages: DatabaseMessage[]; + /** Visible messages inside the time window (all of them without one) */ + inRange: DatabaseMessage[]; + titleMatched: boolean; + matched: DatabaseMessage[]; +} + +function formatMessage( + message: DatabaseMessage, + position: number, + params: SearchChatsParams, + matcher: Matcher | null +): string { + const text = message.content.trim(); + const matchAt = matcher ? matcher.locate(text) : -1; + const body = excerpt(text, params.maxMessageChars, matchAt).replace(/\n+/g, '\n '); + const files = (message.extra ?? []).map((e) => e.name).filter(Boolean); + // names are user data, quote them so they cannot pass as result structure + const attachments = + files.length > 0 ? ` [attachments: ${files.map((f) => JSON.stringify(f)).join(', ')}]` : ''; + + return `#${position} ${message.role}${SEARCH_CHATS_FIELD_SEPARATOR}${formatDate(message.timestamp)}: ${body}${attachments}`; +} + +interface ChatBlock { + head: string[]; + /** Formatted messages, in chat order */ + messages: string[]; + /** On a cut, keep the last messages (latest / matching) instead of the first */ + keepTail: boolean; +} + +const blockText = ({ head, messages }: ChatBlock) => [...head, ...messages].join('\n'); + +/** Fit a chat block into `room` chars by dropping whole messages from the less wanted end */ +function cutChat(block: ChatBlock, room: number): string { + const ordered = block.keepTail ? [...block.messages].reverse() : block.messages; + const kept: string[] = []; + const head = block.head.join('\n'); + + let size = head.length + 1 + SEARCH_CHATS_CUT_NOTICE.length; + + for (const line of ordered) { + if (size + 1 + line.length > room) break; + + kept.push(line); + size += 1 + line.length; + } + + if (block.keepTail) kept.reverse(); + + const lines = block.keepTail + ? [head, SEARCH_CHATS_CUT_NOTICE, ...kept] + : [head, ...kept, SEARCH_CHATS_CUT_NOTICE]; + const text = lines.join('\n'); + + // even the head does not fit (very long title) + if (text.length > room) { + return `${sliceText(text, 0, Math.max(0, room - SEARCH_CHATS_CUT_NOTICE.length))}${SEARCH_CHATS_CUT_NOTICE}`; + } + + return text; +} + +function formatChat( + hit: ChatHit, + index: number, + params: SearchChatsParams, + matcher: Matcher | null, + timed: boolean +): ChatBlock { + const { conv, inRange, matched, messages, titleMatched } = hit; + const summary = [`conv_id: ${conv.id}`, `updated ${formatDate(conv.lastModified)}`]; + // titles are user data, JSON quoting escapes quotes and newlines + const title = JSON.stringify(conv.name ?? ''); + + if (params.limitMessages === 0) { + return { + head: [ + `- ${title}${SEARCH_CHATS_FIELD_SEPARATOR}${summary.join(SEARCH_CHATS_FIELD_SEPARATOR)}` + ], + keepTail: false, + messages: [] + }; + } + + const counts = timed + ? `${messages.length} messages, ${inRange.length} in the time range` + : `${messages.length} messages`; + const lines = [ + `## Chat ${index}: ${title}`, + [...summary, counts].join(SEARCH_CHATS_FIELD_SEPARATOR) + ]; + const n = params.limitMessages; + + let picked: DatabaseMessage[]; + + if (params.messageSelection === SearchChatsMessageSelection.MATCHING && matched.length > 0) { + const where = [titleMatched ? 'title' : '', `${matched.length} message(s)`] + .filter(Boolean) + .join(', '); + + picked = matched.slice(-n); + lines.push(`matched in: ${where}${matched.length > n ? ` (showing the last ${n})` : ''}`); + } else { + if (params.messageSelection === SearchChatsMessageSelection.MATCHING) { + lines.push('matched in: title only, showing the latest messages'); + } + + picked = + params.messageSelection === SearchChatsMessageSelection.EARLIEST + ? inRange.slice(0, n) + : inRange.slice(-n); + } + + if (messages.length === 0) lines.push('(no messages)'); + + const position = new Map(messages.map((m, i) => [m.id, i + 1])); + + return { + head: lines, + keepTail: params.messageSelection !== SearchChatsMessageSelection.EARLIEST, + messages: picked.map((m) => formatMessage(m, position.get(m.id)!, params, matcher)) + }; +} + +function groupByConversation(messages: DatabaseMessage[]): Map { + const groups = new Map(); + + for (const m of messages) { + const group = groups.get(m.convId); + + if (group) group.push(m); + else groups.set(m.convId, [m]); + } + + return groups; +} + +function describeQuery(params: SearchChatsParams): string { + const parts: string[] = []; + + if (params.byMatches) parts.push(`matching ${JSON.stringify(params.byMatches)}`); + + if (params.byConvIds) parts.push('by conv_id'); + + if (params.fromTimestamp !== undefined) parts.push(`from ${formatDate(params.fromTimestamp)}`); + + if (params.toTimestamp !== undefined) parts.push(`before ${formatDate(params.toTimestamp)}`); + + return parts.join(' '); +} + +/** + * Run a search and render the result as text for the model. + * `conversations` holds the candidates: all conversations, or only those of by_conv_ids. + */ +export async function searchChats( + conversations: DatabaseConversation[], + params: SearchChatsParams, + loader: SearchChatsLoader, + currentConversationId?: string +): Promise { + const { byConvIds, fromTimestamp, toTimestamp } = params; + const timed = fromTimestamp !== undefined || toTimestamp !== undefined; + const notes: string[] = []; + + let candidates = conversations; + + if (byConvIds) { + const found = new Set(candidates.map((c) => c.id)); + const missing = byConvIds.filter((id) => !found.has(id)); + + if (missing.length > 0) notes.push(`not found: ${missing.join(', ')}`); + + candidates = candidates.filter((c) => byConvIds.includes(c.id)); + } + + if (currentConversationId && !params.includeCurrent) { + if (byConvIds?.includes(currentConversationId)) { + notes.push( + 'the current chat is hidden (you already see it); set include_current=true to read it' + ); + } + + candidates = candidates.filter((c) => c.id !== currentConversationId); + } + + const matcher = params.byMatches ? buildMatcher(params.byMatches) : null; + const isInRange = (m: DatabaseMessage) => + (fromTimestamp === undefined || m.timestamp >= fromTimestamp) && + (toTimestamp === undefined || m.timestamp < toTimestamp); + const toHit = (conv: DatabaseConversation, raw: DatabaseMessage[]): ChatHit => { + const messages = visibleMessages(conv, raw); + const inRange = timed ? messages.filter(isInRange) : messages; + const matched = matcher ? inRange.filter((m) => matcher.test(m.content)) : []; + + return { conv, inRange, matched, messages, titleMatched: !!matcher?.test(conv.name ?? '') }; + }; + + let hits: ChatHit[]; + + if (matcher || timed) { + // which chats qualify depends on their messages, so read them before paging + const ids = byConvIds ? candidates.map((c) => c.id) : null; + const range = timed ? { from: fromTimestamp, to: toTimestamp } : undefined; + const byConv = groupByConversation(await loader.messages(ids, range)); + + hits = []; + + for (const conv of candidates) { + const raw = byConv.get(conv.id) ?? []; + + // cheap check on all messages before building the visible branch + if ( + matcher && + !matcher.test(conv.name ?? '') && + !raw.some((m) => typeof m.content === 'string' && matcher.test(m.content)) + ) { + continue; + } + + const hit = toHit(conv, raw); + + // with a time window, a chat needs visible messages inside it, a title match is not enough + if (timed && hit.inRange.length === 0) continue; + + if (matcher && !hit.titleMatched && hit.matched.length === 0) continue; + + hits.push(hit); + } + } else { + hits = candidates.map((conv) => toHit(conv, [])); + } + + const sign = params.order === SearchChatsOrder.ASC ? 1 : -1; + + hits.sort((a, b) => sign * (a.conv.lastModified - b.conv.lastModified)); + + const total = hits.length; + const page = hits.slice(params.offsetChats, params.offsetChats + params.limitChats); + + // plain listing or reading: only the chats on this page need their messages + if (!matcher && !timed && params.limitMessages > 0 && page.length > 0) { + const byConv = groupByConversation(await loader.messages(page.map((h) => h.conv.id))); + + page.forEach((hit, i) => (page[i] = toHit(hit.conv, byConv.get(hit.conv.id) ?? []))); + } + + const orderLabel = params.order === SearchChatsOrder.ASC ? 'oldest first' : 'newest first'; + const range = + page.length === 0 + ? `showing none of ${total}` + : `showing ${params.offsetChats + 1}-${params.offsetChats + page.length} of ${total}`; + const header = [ + `${`${total} chat(s) ${describeQuery(params)}`.trim()} (${orderLabel}, ${range})`, + ...notes + ].join('\n'); + const headerSeparator = '\n\n'; + const separator = params.limitMessages === 0 ? '\n' : '\n\n'; + const moreNote = (hidden: number, nextOffset: number) => + `[${hidden} more chat(s) on this page not shown: use offset_chats=${nextOffset}, or lower limit_messages]`; + // room for the note in its longest form: both numbers at their largest + const noteRoom = + separator.length + moreNote(page.length, params.offsetChats + page.length).length; + const blocks: string[] = []; + + let size = header.length; + + for (const [i, hit] of page.entries()) { + const block = formatChat(hit, params.offsetChats + i + 1, params, matcher, timed); + const text = blockText(block); + const gap = blocks.length === 0 ? headerSeparator.length : separator.length; + const isLast = i === page.length - 1; + const limit = SEARCH_CHATS_OUTPUT_MAX_CHARS - (isLast ? 0 : noteRoom); + + if (size + gap + text.length > limit) { + // always show at least part of the first chat + if (blocks.length === 0) blocks.push(cutChat(block, limit - size - gap)); + + break; + } + + blocks.push(text); + size += gap + text.length; + } + + if (blocks.length < page.length) { + blocks.push(moreNote(page.length - blocks.length, params.offsetChats + blocks.length)); + } + + return blocks.length > 0 ? `${header}${headerSeparator}${blocks.join(separator)}` : header; +} diff --git a/tools/ui/tests/client/search-chats-default-disabled-migration.svelte.test.ts b/tools/ui/tests/client/search-chats-default-disabled-migration.svelte.test.ts new file mode 100644 index 000000000000..802f795db4b2 --- /dev/null +++ b/tools/ui/tests/client/search-chats-default-disabled-migration.svelte.test.ts @@ -0,0 +1,114 @@ +// search_chats starts disabled: tool policy is a deny-list, so the key must be added to the global defaults and to every existing conversation + +import { DISABLED_TOOL_KEYS_LOCALSTORAGE_KEY, SEARCH_CHATS_TOOL_KEY } from '$lib/constants'; +import { DatabaseService } from '$lib/services/database.service'; +import { MigrationService } from '$lib/services/migration.service'; +import type { ExportedConversation } from '$lib/types/database'; +import { withSearchChatsDisabled } from '$lib/utils/search-chats'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +const MIGRATION_ID = 'search-chats-default-disabled-v1'; + +async function runMigration() { + await MigrationService.getMigrations() + .find((m) => m.id === MIGRATION_ID) + ?.run(); +} + +const conversation = (id: string, disabledTools?: string[]) => + ({ + conv: { currNode: null, disabledTools, id, lastModified: 0, name: id }, + messages: [] + }) as unknown as ExportedConversation; + +function storedDefaults(): unknown { + return JSON.parse(localStorage.getItem(DISABLED_TOOL_KEYS_LOCALSTORAGE_KEY) ?? 'null'); +} + +describe('search_chats default-disabled migration', () => { + beforeEach(() => { + localStorage.removeItem(DISABLED_TOOL_KEYS_LOCALSTORAGE_KEY); + }); + + afterEach(async () => { + const conversations = await DatabaseService.getAllConversations(); + + await DatabaseService.bulkDeleteConversations(conversations.map((c) => c.id)); + localStorage.removeItem(DISABLED_TOOL_KEYS_LOCALSTORAGE_KEY); + }); + + it('adds the tool to the global defaults, keeping existing entries', async () => { + localStorage.setItem( + DISABLED_TOOL_KEYS_LOCALSTORAGE_KEY, + JSON.stringify(['server:exec_shell_command']) + ); + await runMigration(); + expect(storedDefaults()).toEqual(['server:exec_shell_command', SEARCH_CHATS_TOOL_KEY]); + }); + + it('creates the defaults on a fresh install', async () => { + await runMigration(); + expect(storedDefaults()).toEqual([SEARCH_CHATS_TOOL_KEY]); + }); + + it('disables the tool in every existing conversation', async () => { + await DatabaseService.importConversations([ + conversation('no-policy'), + conversation('with-policy', ['browser:run_javascript']), + conversation('already', [SEARCH_CHATS_TOOL_KEY]) + ]); + await runMigration(); + + expect((await DatabaseService.getConversation('no-policy'))?.disabledTools).toEqual([ + SEARCH_CHATS_TOOL_KEY + ]); + expect((await DatabaseService.getConversation('with-policy'))?.disabledTools).toEqual([ + 'browser:run_javascript', + SEARCH_CHATS_TOOL_KEY + ]); + expect((await DatabaseService.getConversation('already'))?.disabledTools).toEqual([ + SEARCH_CHATS_TOOL_KEY + ]); + }); + + it('keeps the tool policy of the source chat on fork', async () => { + await DatabaseService.importConversations([ + { + conv: { + currNode: 'm1', + disabledTools: [SEARCH_CHATS_TOOL_KEY], + id: 'source', + lastModified: 0, + name: 'source' + }, + messages: [ + { + children: [], + content: 'hi', + convId: 'source', + id: 'm1', + parent: null, + role: 'user', + timestamp: 0, + type: 'text' + } + ] + } as unknown as ExportedConversation + ]); + + const fork = await DatabaseService.forkConversation('source', 'm1', { + includeAttachments: false, + name: 'fork' + }); + + expect(fork.disabledTools).toEqual([SEARCH_CHATS_TOOL_KEY]); + }); +}); + +describe('withSearchChatsDisabled', () => { + it('adds the key once, for imported rows with or without a policy', () => { + expect(withSearchChatsDisabled(undefined)).toEqual([SEARCH_CHATS_TOOL_KEY]); + expect(withSearchChatsDisabled(['a'])).toEqual(['a', SEARCH_CHATS_TOOL_KEY]); + expect(withSearchChatsDisabled([SEARCH_CHATS_TOOL_KEY])).toEqual([SEARCH_CHATS_TOOL_KEY]); + }); +}); diff --git a/tools/ui/tests/client/search-chats.service.svelte.test.ts b/tools/ui/tests/client/search-chats.service.svelte.test.ts new file mode 100644 index 000000000000..b29aaae3bc4f --- /dev/null +++ b/tools/ui/tests/client/search-chats.service.svelte.test.ts @@ -0,0 +1,113 @@ +// IndexedDB side of search_chats: loading, the current-chat filter and the readonly transaction. +// Matching and formatting are covered by tests/unit/search-chats.test.ts. + +import { MessageRole, MessageType } from '$lib/enums'; +import { DatabaseService } from '$lib/services/database.service'; +import { SearchChatsService } from '$lib/services/search-chats.service'; +import type { ExportedConversation } from '$lib/types/database'; +import { formatLocalIso } from '$lib/utils/formatters'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +function makeConversation( + id: string, + name: string, + turns: [MessageRole, string][], + lastModified: number +): ExportedConversation { + const messages = turns.map(([role, content], i) => ({ + children: i + 1 < turns.length ? [`${id}-m${i + 1}`] : [], + content, + convId: id, + id: `${id}-m${i}`, + parent: i === 0 ? null : `${id}-m${i - 1}`, + role, + timestamp: lastModified + i, + type: MessageType.TEXT + })); + + return { + conv: { currNode: messages.at(-1)!.id, id, lastModified, name }, + messages + } as unknown as ExportedConversation; +} + +beforeEach(async () => { + await DatabaseService.importConversations([ + makeConversation( + 'paris', + "let's think about paris", + [ + [MessageRole.USER, 'plan a weekend in Paris'], + [MessageRole.ASSISTANT, 'Day 1: Louvre'], + [MessageRole.USER, 'how much is a metro ticket?'], + [MessageRole.ASSISTANT, 'About 2 euros.'] + ], + 1000 + ), + makeConversation( + 'search', + 'list my chats', + [ + [MessageRole.USER, 'list my chats'], + [MessageRole.TOOL, `=> [{"name":"let's think about paris"}]`], + [MessageRole.ASSISTANT, 'You have two chats.'] + ], + 2000 + ) + ]); +}); + +afterEach(async () => { + const conversations = await DatabaseService.getAllConversations(); + + await DatabaseService.bulkDeleteConversations(conversations.map((conv) => conv.id)); +}); + +describe('search_chats service', () => { + it('searches every stored message and hides the current chat', async () => { + const reply = await SearchChatsService.executeTool( + { by_matches: ['%paris%'], limit_messages: 1, message_selection: 'latest' }, + 'search' + ); + + expect(reply.isError).toBe(false); + expect(reply.content).toContain('1 chat(s) matching ["%paris%"]'); + expect(reply.content).toContain('#4 assistant'); + expect(reply.content).toContain('About 2 euros.'); + }); + + it('loads chats by id and reports missing ones', async () => { + const reply = await SearchChatsService.executeTool( + { by_conv_ids: ['paris', 'missing'], limit_messages: 1, message_selection: 'earliest' }, + 'search' + ); + + expect(reply.content).toContain('not found: missing'); + expect(reply.content).toContain('plan a weekend in Paris'); + }); + + it('finds chats with messages in a time range through the timestamp index', async () => { + const reply = await SearchChatsService.executeTool( + { from_timestamp: formatLocalIso(new Date(2000)), limit_messages: 1 }, + 'other' + ); + + expect(reply.content).toContain('1 chat(s) from'); + expect(reply.content).toContain('conv_id: search'); + expect(reply.content).toContain('#1 user'); + }); + + it('returns parameter errors to the model', async () => { + const reply = await SearchChatsService.executeTool({ order_timestamp: 'esc' }); + + expect(reply.isError).toBe(true); + expect(reply.content).toBe('Error: order_timestamp must be one of: asc, desc'); + }); + + it('reads through a transaction that refuses writes', async () => { + await expect( + DatabaseService.readOnly(({ messages }) => messages.delete('paris-m0')) + ).rejects.toThrow(); + expect(await DatabaseService.getConversationMessages('paris')).toHaveLength(4); + }); +}); diff --git a/tools/ui/tests/unit/brand-favicons.test.ts b/tools/ui/tests/unit/brand-favicons.test.ts new file mode 100644 index 000000000000..a1fb9e564243 --- /dev/null +++ b/tools/ui/tests/unit/brand-favicons.test.ts @@ -0,0 +1,37 @@ +import { BRAND_FAVICONS, writeBrandFavicons } from '../../scripts/brand-favicons'; +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +const require = createRequire(import.meta.url); + +describe('writeBrandFavicons', () => { + let tmpDir: string; + + beforeEach(() => { + tmpDir = mkdtempSync(join(tmpdir(), 'favicon-')); + }); + + afterEach(() => { + rmSync(tmpDir, { force: true, recursive: true }); + }); + + it("writes llama-brand's light and dark favicons unchanged", () => { + writeBrandFavicons(tmpDir); + + for (const [fileName, specifier] of Object.entries(BRAND_FAVICONS)) { + expect(readFileSync(join(tmpDir, fileName), 'utf-8')).toBe( + readFileSync(require.resolve(specifier), 'utf-8') + ); + } + }); + + it('draws the light favicon in ink and the dark one in light', () => { + writeBrandFavicons(tmpDir); + + expect(readFileSync(join(tmpDir, 'favicon.svg'), 'utf-8')).toContain('fill="#111111"'); + expect(readFileSync(join(tmpDir, 'favicon-dark.svg'), 'utf-8')).toContain('fill="#FAFAFA"'); + }); +}); diff --git a/tools/ui/tests/unit/favicon-colorize.test.ts b/tools/ui/tests/unit/favicon-colorize.test.ts deleted file mode 100644 index b286db37d5f2..000000000000 --- a/tools/ui/tests/unit/favicon-colorize.test.ts +++ /dev/null @@ -1,211 +0,0 @@ -import { - colorizeFaviconSvg, - padFaviconSvg, - writeThemeFavicons -} from '../../scripts/favicon-colorize'; -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; - -const SOURCE_SVG = [ - '', - ' ', - ' ', - ' ', - '' -].join('\n'); - -describe('colorizeFaviconSvg', () => { - it('substitutes every currentColor occurrence for the light variant', () => { - const { light } = colorizeFaviconSvg(SOURCE_SVG, '#111111', '#fafafa'); - - expect(light.match(/currentColor/g)).toBeNull(); - expect(light).toContain('fill="#111111"'); - expect(light).toContain(''); - }); - - it('substitutes every currentColor occurrence for the dark variant', () => { - const { dark } = colorizeFaviconSvg(SOURCE_SVG, '#111111', '#fafafa'); - - expect(dark.match(/currentColor/g)).toBeNull(); - expect(dark).toContain('fill="#fafafa"'); - expect(dark).toContain(''); - }); - - it('leaves non-currentColor colors untouched in both variants', () => { - const { dark, light } = colorizeFaviconSvg(SOURCE_SVG, '#111111', '#fafafa'); - - expect(light).toContain('fill="#ff00aa"'); - expect(dark).toContain('fill="#ff00aa"'); - }); - - it('does not alter any other part of the SVG', () => { - const { dark, light } = colorizeFaviconSvg(SOURCE_SVG, '#111111', '#fafafa'); - const stripColors = (s: string) => - s.replaceAll('#111111', '').replaceAll('#fafafa', '').replaceAll('currentColor', ''); - const expected = stripColors(SOURCE_SVG); - - expect(stripColors(light)).toBe(expected); - expect(stripColors(dark)).toBe(expected); - }); - - it('returns the same SVG for light and dark when called with the same color', () => { - const result = colorizeFaviconSvg(SOURCE_SVG, '#abcdef', '#abcdef'); - - expect(result.light).toBe(result.dark); - }); - - it('returns the source unchanged when given a color that does not appear (no currentColor in source)', () => { - const plain = ''; - const { dark, light } = colorizeFaviconSvg(plain, '#111111', '#fafafa'); - - expect(light).toBe(plain); - expect(dark).toBe(plain); - }); -}); - -describe('padFaviconSvg', () => { - const SIZED_SVG = - '' + - '' + - ''; - - it('wraps inner content in a translate-then-scale group that matches padding', () => { - const padded = padFaviconSvg(SIZED_SVG, 0.05); - - // scale = 1 - 0.05 = 0.95 - // translate = (0.05 * 512) / 2 = 12.8 on each axis - expect(padded).toContain('transform="translate(12.8 12.8) scale(0.95)"'); - expect(padded).toContain(''); - expect(padded).toContain(''); - expect(padded.endsWith('')).toBe(true); - }); - - it('preserves the outer tag attributes', () => { - const padded = padFaviconSvg(SIZED_SVG, 0.1); - - expect(padded.startsWith(' { - expect(padFaviconSvg(SIZED_SVG, 0)).toBe(SIZED_SVG); - expect(padFaviconSvg(SIZED_SVG, -0.1)).toBe(SIZED_SVG); - }); - - it('returns the input unchanged when padding would fully collapse the icon (>= 1)', () => { - expect(padFaviconSvg(SIZED_SVG, 1)).toBe(SIZED_SVG); - expect(padFaviconSvg(SIZED_SVG, 1.5)).toBe(SIZED_SVG); - }); - - it('returns the input unchanged when no viewBox is present', () => { - const noViewBox = ''; - - expect(padFaviconSvg(noViewBox, 0.1)).toBe(noViewBox); - }); - - it('returns the input unchanged when viewBox values are not finite numbers', () => { - const bad = ''; - - expect(padFaviconSvg(bad, 0.1)).toBe(bad); - }); - - it('tolerates a non-square viewBox', () => { - const wide = ''; - const padded = padFaviconSvg(wide, 0.1); - - // scale 0.9, translate (5, 2.5) - expect(padded).toContain('transform="translate(5 2.5) scale(0.9)"'); - }); -}); - -describe('writeThemeFavicons', () => { - const LOGO = - '' + - '' + - ''; - - let tmpDir: string; - - beforeEach(() => { - tmpDir = mkdtempSync(join(tmpdir(), 'favicon-')); - }); - - afterEach(() => { - rmSync(tmpDir, { force: true, recursive: true }); - }); - - function setupSource() { - const sourcePath = join(tmpDir, 'logo.svg'); - - writeFileSync(sourcePath, LOGO); - - return { - darkPath: join(tmpDir, 'favicon-dark.svg'), - lightPath: join(tmpDir, 'favicon.svg'), - sourcePath - }; - } - - it('writes colorized, un-padded favicons without modifying the source', () => { - const { darkPath, lightPath, sourcePath } = setupSource(); - const before = readFileSync(sourcePath, 'utf-8'); - - writeThemeFavicons('#abcdef', '#012345', { - darkOutPath: darkPath, - lightOutPath: lightPath, - sourcePath - }); - - const lightOut = readFileSync(lightPath, 'utf-8'); - const darkOut = readFileSync(darkPath, 'utf-8'); - - // currentColor swapped to the requested palette in both files - expect(lightOut).toContain('fill="#abcdef"'); - expect(lightOut).not.toContain('currentColor'); - expect(darkOut).toContain('fill="#012345"'); - expect(darkOut).not.toContain('currentColor'); - - // default padding (0) keeps the wrapper off the output - expect(lightOut).not.toContain('...', () => { - const { darkPath, lightPath, sourcePath } = setupSource(); - // mirror the production wiring: PWA_ASSET_GENERATOR.FAVICON_PADDING - const padding = 0.04; - // scale = 1 - 0.04 = 0.96; translate = (0.04 * 512) / 2 = 10.24 - const expectedTransform = 'transform="translate(10.24 10.24) scale(0.96)"'; - - writeThemeFavicons('#111111', '#fafafa', { - darkOutPath: darkPath, - lightOutPath: lightPath, - padding, - sourcePath - }); - - const lightOut = readFileSync(lightPath, 'utf-8'); - const darkOut = readFileSync(darkPath, 'utf-8'); - - // both files get the same padding wrapper derived from the viewBox - expect(lightOut).toContain(``); - expect(lightOut.endsWith('')).toBe(true); - expect(darkOut).toContain(``); - expect(darkOut.endsWith('')).toBe(true); - - // colorization still happens inside the wrapped group - expect(lightOut).toContain('fill="#111111"'); - expect(lightOut).not.toContain('currentColor'); - expect(darkOut).toContain('fill="#fafafa"'); - expect(darkOut).not.toContain('currentColor'); - // light palette colour must not leak into dark output - expect(darkOut).not.toContain('#111111'); - - // source file is not modified by the padding step - expect(readFileSync(sourcePath, 'utf-8')).toBe(LOGO); - }); -}); diff --git a/tools/ui/tests/unit/search-chats.test.ts b/tools/ui/tests/unit/search-chats.test.ts new file mode 100644 index 000000000000..9e12c665f7d5 --- /dev/null +++ b/tools/ui/tests/unit/search-chats.test.ts @@ -0,0 +1,383 @@ +import { SEARCH_CHATS_OUTPUT_MAX_CHARS, SEARCH_CHATS_PATTERN_MAX_CHARS } from '$lib/constants'; +import { MessageRole, MessageType } from '$lib/enums'; +import type { DatabaseConversation, DatabaseMessage } from '$lib/types/database'; +import { formatLocalIso } from '$lib/utils/formatters'; +import { parseSearchChatsParams, searchChats, SearchChatsError } from '$lib/utils/search-chats'; +import { describe, expect, it } from 'vitest'; + +type Turn = [role: 'user' | 'assistant' | 'tool', content: string]; + +const conversations: DatabaseConversation[] = []; +const messages: DatabaseMessage[] = []; +// fixture times are in minutes, ISO timestamps only carry seconds +const MINUTE = 60_000; +const at = (minute: number) => formatLocalIso(new Date(minute * MINUTE)); + +/** Add a linear chat whose messages are one minute apart from `startMinute` */ +function addChat(id: string, name: string, startMinute: number, turns: Turn[]): string[] { + const start = startMinute * MINUTE; + const root = `${id}-root`; + const ids = turns.map((_, i) => `${id}-${i + 1}`); + + messages.push({ + children: ids.slice(0, 1), + content: '', + convId: id, + id: root, + parent: null, + role: MessageRole.SYSTEM, + timestamp: start - MINUTE, + type: MessageType.ROOT + } as DatabaseMessage); + + turns.forEach(([role, content], i) => { + messages.push({ + children: ids.slice(i + 1, i + 2), + content, + convId: id, + id: ids[i], + parent: i === 0 ? root : ids[i - 1], + role: role as MessageRole, + timestamp: start + i * MINUTE, + type: MessageType.TEXT + } as DatabaseMessage); + }); + + const lastModified = start + (turns.length - 1) * MINUTE; + + conversations.push({ currNode: ids.at(-1)!, id, lastModified, name } as DatabaseConversation); + + return ids; +} + +const parisIds = addChat('paris', "let's think about paris", 3000, [ + ['user', 'plan a weekend in Paris'], + ['assistant', 'Day 1: Louvre. Day 2: Montmartre.'], + ['user', 'is the eiffel tower worth it?'], + ['assistant', 'Yes, book tickets early.'], + ['user', 'how much is a metro ticket?'], + ['assistant', 'About 2 euros.'] +]); + +// edited-away branch off the first assistant reply, never visible +messages.push({ + children: [], + content: 'old edit about versailles', + convId: 'paris', + id: 'paris-edit', + parent: parisIds[1], + role: MessageRole.USER, + timestamp: 3001 * MINUTE + 30_000, + type: MessageType.TEXT +} as DatabaseMessage); + +// an earlier search session: its tool output names other chats +addChat('search', 'list my chats', 4000, [ + ['user', 'list my chats please'], + ['tool', `=> [{"name":"let's think about paris"},{"name":"what time is it in bulgaria"}]`], + ['assistant', 'You have a few chats.'] +]); + +addChat('bulgaria', 'what time is it in bulgaria', 2000, [ + ['user', 'what time is it in bulgaria'], + ['assistant', 'It is 14:00 in Sofia.'] +]); + +addChat('current', 'this chat', 5000, [['user', 'find the chat where I talk about paris']]); + +const loads: (string[] | null)[] = []; +const loader = { + async messages(ids: string[] | null, range?: { from?: number; to?: number }) { + loads.push(ids); + + const rows = ids ? messages.filter((m) => ids.includes(m.convId)) : messages; + + if (!range) return rows; + + const { from, to } = range; + const active = new Set( + messages + .filter( + (m) => + (from === undefined || m.timestamp >= from) && (to === undefined || m.timestamp < to) + ) + .map((m) => m.convId) + ); + + return rows.filter((m) => active.has(m.convId)); + } +}; + +async function search(args: Record, current = 'current') { + const params = parseSearchChatsParams(args); + const candidates = params.byConvIds + ? conversations.filter((c) => params.byConvIds!.includes(c.id)) + : conversations; + + return searchChats(candidates, params, loader, current); +} + +describe('search_chats: finding chats', () => { + it('answers "last question in the paris chat" in one call', async () => { + const out = await search({ + by_matches: ['%paris%'], + limit_messages: 4, + message_selection: 'latest' + }); + + expect(out).toContain('1 chat(s) matching ["%paris%"] (newest first, showing 1-1 of 1)'); + expect(out).toContain(`## Chat 1: "let's think about paris"`); + expect(out).toContain(`#5 user | ${at(3004)}: how much is a metro ticket?`); + expect(out).toContain('#6 assistant'); + expect(out).not.toContain('#2 assistant'); + }); + + it('ignores tool output and the current chat', async () => { + const out = await search({ by_matches: ['bulgaria'] }); + + // the search session mentions bulgaria in tool output only + expect(out).toContain('1 chat(s) matching'); + expect(out).toContain('conv_id: bulgaria'); + expect(out).not.toContain('conv_id: search'); + }); + + it('shows the matching messages by default', async () => { + const out = await search({ by_matches: ['%eiffel%', 'metro'] }); + + expect(out).toContain('matched in: 2 message(s)'); + expect(out).toContain('#3 user'); + expect(out).toContain('#5 user'); + expect(out).not.toContain('#1 user'); + }); + + it('reports a title-only match and falls back to the latest messages', async () => { + const out = await search({ by_matches: ['%think about%'], limit_messages: 1 }); + + expect(out).toContain('matched in: title only, showing the latest messages'); + expect(out).toContain('#6 assistant'); + }); + + it('does not search edited-away branches', async () => { + expect(await search({ by_matches: ['versailles'] })).toContain('0 chat(s) matching'); + }); + + it('supports _ wildcards and plain words as "contains"', async () => { + expect(await search({ by_matches: ['m_tro'] })).toContain('conv_id: paris'); + expect(await search({ by_matches: 'SOFIA' })).toContain('conv_id: bulgaria'); + }); + + it('moves the excerpt of a long message to the match', async () => { + const long = ` ${'x'.repeat(2000)} the secret word is paris ${'y'.repeat(2000)}`; + + addChat('long', 'long chat', 1000, [['user', long]]); + + const out = await search({ + by_conv_ids: ['long'], + by_matches: ['secret word'], + max_message_chars: 100 + }); + + expect(out).toMatch(/: \.\.\.x+ the secret word is paris y+\.\.\.\[\+\d+ chars\]/); + + conversations.pop(); + messages.splice(-2, 2); + }); +}); + +describe('search_chats: listing and reading', () => { + it('lists chats as one line each without reading messages', async () => { + loads.length = 0; + + const out = await search({ limit_chats: 999, limit_messages: 0 }); + + expect(out.split('\n')).toEqual([ + '3 chat(s) (newest first, showing 1-3 of 3)', + '', + `- "list my chats" | conv_id: search | updated ${at(4002)}`, + `- "let's think about paris" | conv_id: paris | updated ${at(3005)}`, + `- "what time is it in bulgaria" | conv_id: bulgaria | updated ${at(2001)}` + ]); + expect(loads).toEqual([]); + }); + + it('reads messages only for the chats on the page', async () => { + loads.length = 0; + await search({ limit_chats: 2 }); + expect(loads).toEqual([['search', 'paris']]); + }); + + it('pages and orders oldest first', async () => { + const out = await search({ + limit_chats: 1, + limit_messages: 0, + offset_chats: 1, + order_timestamp: 'asc' + }); + + expect(out).toContain('(oldest first, showing 2-2 of 3)'); + expect(out).toContain('conv_id: paris'); + }); + + it('reads a chat by id from the start', async () => { + const out = await search({ + by_conv_ids: ['paris'], + limit_messages: 2, + message_selection: 'earliest' + }); + + expect(out).toContain(`#1 user | ${at(3000)}: plan a weekend in Paris`); + expect(out).toContain('#2 assistant'); + expect(out).not.toContain('#3 user'); + }); + + it('reports unknown ids and hides the current chat unless asked', async () => { + const hidden = await search({ by_conv_ids: ['current', 'nope'] }); + + expect(hidden).toContain('not found: nope'); + expect(hidden).toContain('the current chat is hidden'); + expect(hidden).toContain('0 chat(s) by conv_id'); + + const shown = await search({ by_conv_ids: ['current'], include_current: true }); + + expect(shown).toContain(`#1 user | ${at(5000)}: find the chat where I talk about paris`); + }); + + it('stays within the output budget with a paging hint', async () => { + for (let i = 0; i < 20; i++) { + addChat(`big${i}`, `big ${i}`, 100 + i, [['user', 'z'.repeat(1000)]]); + } + + const out = await search({ by_matches: ['zzz'], limit_chats: 20, max_message_chars: 1000 }); + + expect(out).toMatch(/\[\d+ more chat\(s\) on this page not shown: use offset_chats=\d+/); + expect(out.length).toBeLessThanOrEqual(SEARCH_CHATS_OUTPUT_MAX_CHARS); + + conversations.splice(-20, 20); + messages.splice(-40, 40); + }); + + it('stays within the output budget when listing many long titles', async () => { + for (let i = 0; i < 200; i++) + addChat(`t${i}`, `${'t'.repeat(150)} ${i}`, 10 + i, [['user', 'x']]); + + const out = await search({ limit_chats: 200, limit_messages: 0 }); + + expect(out).toMatch(/more chat\(s\) on this page not shown/); + expect(out.length).toBeLessThanOrEqual(SEARCH_CHATS_OUTPUT_MAX_CHARS); + + conversations.splice(-200, 200); + messages.splice(-400, 400); + }); + + it('keeps the latest messages when a single chat is cut', async () => { + const turns: Turn[] = Array.from({ length: 20 }, (_, i) => [ + 'user', + `msg${i} ${'w'.repeat(900)}` + ]); + + addChat('wide', 'wide chat', 50, turns); + + const out = await search({ + by_conv_ids: ['wide'], + limit_messages: 20, + max_message_chars: 1000 + }); + + expect(out).toContain('[messages cut to fit'); + expect(out).toContain('msg19'); + expect(out).not.toContain('msg0 '); + expect(out.length).toBeLessThanOrEqual(SEARCH_CHATS_OUTPUT_MAX_CHARS); + + conversations.pop(); + messages.splice(-21, 21); + }); + + it('quotes titles so they cannot add result lines', async () => { + addChat('evil', 'x" | conv_id: fake\n## Chat 9: "y', 60, [['user', 'hello evil']]); + + const out = await search({ by_matches: ['hello evil'], limit_messages: 0 }); + + expect(out).toContain(String.raw`- "x\" | conv_id: fake\n## Chat 9: \"y" | conv_id: evil`); + expect(out).not.toContain('\n## Chat 9'); + + conversations.pop(); + messages.splice(-2, 2); + }); +}); + +describe('search_chats: time range', () => { + it('returns the messages from a timestamp, across chats', async () => { + const out = await search({ from_timestamp: at(3004), limit_messages: 2 }); + + expect(out).toContain(`2 chat(s) from ${at(3004)} (newest first, showing 1-2 of 2)`); + expect(out).toContain('6 messages, 2 in the time range'); + expect(out).toContain(`#5 user | ${at(3004)}: how much is a metro ticket?`); + expect(out).not.toContain('#4 assistant'); + expect(out).toContain('conv_id: search'); + expect(out).not.toContain('conv_id: bulgaria'); + }); + + it('excludes the end of the range', async () => { + const out = await search({ from_timestamp: at(3004), to_timestamp: at(4000) }); + + expect(out).toContain('1 chat(s)'); + expect(out).toContain('conv_id: paris'); + }); + + it('limits matches to the range, and a title match needs messages in it', async () => { + const ranged = await search({ by_matches: ['metro', 'eiffel'], from_timestamp: at(3003) }); + + expect(ranged).toContain('matched in: 1 message(s)'); + expect(ranged).not.toContain('#3 user'); + + const titleOnly = await search({ by_matches: ['%think about%'], from_timestamp: at(4000) }); + + expect(titleOnly).toContain('0 chat(s)'); + }); + + it('reads ISO dates as local time', () => { + const parse = (from_timestamp: string) => + parseSearchChatsParams({ from_timestamp }).fromTimestamp; + + expect(parse('2026-11-10')).toBe(new Date(2026, 10, 10).getTime()); + expect(parse('2026-11-10T14:30')).toBe(new Date(2026, 10, 10, 14, 30).getTime()); + expect(parse('2026-11-10T14:30Z')).toBe(Date.UTC(2026, 10, 10, 14, 30)); + }); + + it('defaults to the earliest messages from the timestamp', () => { + const params = parseSearchChatsParams({ from_timestamp: '2026-11-10' }); + + expect(params.messageSelection).toBe('earliest'); + }); +}); + +describe('search_chats: parameters', () => { + it.each([ + [{ message_selection: 'matching' }, 'needs by_matches'], + [{ limit_chats: 0 }, 'limit_chats must be an integer from 1 to 1000'], + [{ limit_messages: 1.5 }, 'limit_messages must be an integer'], + [{ order_timestamp: 'esc' }, 'order_timestamp must be one of: asc, desc'], + [{ by_matches: [1] }, 'by_matches must be an array of non-empty strings'], + [ + { by_matches: ['x'.repeat(SEARCH_CHATS_PATTERN_MAX_CHARS + 1)] }, + `by_matches entries must be at most ${SEARCH_CHATS_PATTERN_MAX_CHARS} characters` + ], + [{ message_selection: 'all' }, 'message_selection must be one of'], + [{ from_timestamp: 'yesterday' }, 'from_timestamp must be an ISO 8601 date'], + [{ from_timestamp: 1786962645195 }, 'from_timestamp must be an ISO 8601 date'], + [{ to_timestamp: '2026-02-30' }, 'to_timestamp must be an ISO 8601 date'], + [{ to_timestamp: '2026-02-30T10:00' }, 'to_timestamp must be an ISO 8601 date'], + [{ from_timestamp: '2026-11-10T24:30' }, 'from_timestamp must be an ISO 8601 date'], + [ + { from_timestamp: '2026-11-10', to_timestamp: '2026-11-09' }, + 'to_timestamp must be after from_timestamp' + ] + ])('rejects %j', (args, message) => { + expect(() => parseSearchChatsParams(args)).toThrow(SearchChatsError); + expect(() => parseSearchChatsParams(args)).toThrow(message); + }); + + it('accepts numbers sent as strings', () => { + expect(parseSearchChatsParams({ limit_chats: '3' }).limitChats).toBe(3); + }); +}); diff --git a/vendor/cpp-httplib/CMakeLists.txt b/vendor/cpp-httplib/CMakeLists.txt index d3b87aeab803..dfe94882d49b 100644 --- a/vendor/cpp-httplib/CMakeLists.txt +++ b/vendor/cpp-httplib/CMakeLists.txt @@ -83,7 +83,7 @@ if (LLAMA_BUILD_BORINGSSL) target_link_libraries(${TARGET} PUBLIC ssl crypto) elseif (LLAMA_BUILD_LIBRESSL) - set(LIBRESSL_VERSION "4.4.0" CACHE STRING "LibreSSL version") + set(LIBRESSL_VERSION "4.4.1" CACHE STRING "LibreSSL version") message(STATUS "Fetching LibreSSL version ${LIBRESSL_VERSION}") diff --git a/vendor/cpp-httplib/httplib.cpp b/vendor/cpp-httplib/httplib.cpp index e67157ad303f..1d883acdbd90 100644 --- a/vendor/cpp-httplib/httplib.cpp +++ b/vendor/cpp-httplib/httplib.cpp @@ -7703,7 +7703,16 @@ bool ThreadPool::enqueue(std::function fn) { if (jobs_.size() > idle_thread_count_ && threads_.size() + dynamic_threads_.size() < max_thread_count_) { cleanup_finished_threads(); - dynamic_threads_.emplace_back(std::thread([this]() { worker(true); })); +#ifndef CPPHTTPLIB_NO_EXCEPTIONS + try { +#endif + dynamic_threads_.emplace_back(std::thread([this]() { worker(true); })); +#ifndef CPPHTTPLIB_NO_EXCEPTIONS + } catch (const std::system_error &) { + // No thread budget left: keep the job queued for an existing worker + // instead of letting the exception escape the accept loop. + } +#endif } } @@ -8158,14 +8167,22 @@ make_host_and_port_string_always_port(const std::string &host, int port) { return prepare_host_string(host) + ":" + std::to_string(port); } -// Request target of a CONNECT for `host`, with `addr_map` applied. +// Where a client connects for `host`, as one string: the mapped address or +// name, or `host` itself. std::string -make_connect_request_target(const std::map &addr_map, - const std::string &host, int port) { +addr_map_target(const std::map &addr_map, + const std::string &host) { std::string connect_host; std::string ip; apply_addr_map(addr_map, host, connect_host, ip); - return make_host_and_port_string_always_port(ip.empty() ? connect_host : ip, + return ip.empty() ? connect_host : ip; +} + +// Request target of a CONNECT for `host`, with `addr_map` applied. +std::string +make_connect_request_target(const std::map &addr_map, + const std::string &host, int port) { + return make_host_and_port_string_always_port(addr_map_target(addr_map, host), port); } @@ -11553,8 +11570,13 @@ bool ClientImpl::redirect(Request &req, Response &res, Error &error) { auto path = std::move(next_path) + next_query; + // A Unix socket client sends "Host: localhost", so a Location naming + // localhost names this client too. + auto is_same_host = next_host == host_ || + (address_family_ == AF_UNIX && next_host == "localhost"); + // Same host redirect - use current client - if (next_scheme == scheme && next_host == host_ && next_port == port_) { + if (next_scheme == scheme && is_same_host && next_port == port_) { return detail::redirect(*this, req, res, path, location, error); } @@ -11705,6 +11727,14 @@ void ClientImpl::setup_redirect_client(ClientType &client) { // Copy network and socket settings client.addr_map_ = addr_map_; client.tunnel_addr_map_ = tunnel_addr_map_; + + // A Unix socket client reaches every host through its own socket, as curl's + // --unix-socket does, unless the caller mapped that host elsewhere. The + // Location's host is never taken as a socket path. + if (address_family_ == AF_UNIX) { + auto &target = client.addr_map_[client.host()]; + if (target.empty()) { target = detail::addr_map_target(addr_map_, host_); } + } client.set_address_family(address_family_); client.set_tcp_nodelay(tcp_nodelay_); client.set_ipv6_v6only(ipv6_v6only_); diff --git a/vendor/cpp-httplib/httplib.h b/vendor/cpp-httplib/httplib.h index 9a7acd71d4dc..489d1ef01d34 100644 --- a/vendor/cpp-httplib/httplib.h +++ b/vendor/cpp-httplib/httplib.h @@ -8,8 +8,8 @@ #ifndef CPPHTTPLIB_HTTPLIB_H #define CPPHTTPLIB_HTTPLIB_H -#define CPPHTTPLIB_VERSION "0.65.0" -#define CPPHTTPLIB_VERSION_NUM "0x004100" +#define CPPHTTPLIB_VERSION "0.66.0" +#define CPPHTTPLIB_VERSION_NUM "0x004200" #ifdef _WIN32 #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00