diff --git a/.devops/nix/python-scripts.nix b/.devops/nix/python-scripts.nix index 56ea18278876..873b2ebe503a 100644 --- a/.devops/nix/python-scripts.nix +++ b/.devops/nix/python-scripts.nix @@ -22,10 +22,6 @@ let gitpython tabulate - # for examples/pydantic-models-to-grammar-examples.py - docstring-parser - pydantic - ]; llama-python-test-deps = with python3Packages; [ diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 867dcaf49420..4777f613ee7b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1239,6 +1239,7 @@ jobs: with: key: release-windows-2022-${{ matrix.arch }}-cuda-${{ matrix.cuda }} evict-old-files: 1d + max-size: "1G" - name: Build id: cmake_build diff --git a/CMakeLists.txt b/CMakeLists.txt index b8b40e75f68f..30aed5c914a9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,8 +3,8 @@ project("llama.cpp" C CXX) include(CheckIncludeFileCXX) ### llama.cpp version -set(LLAMA_VERSION_MAJOR 0) -set(LLAMA_VERSION_MINOR 9) +set(LLAMA_VERSION_MAJOR 1) +set(LLAMA_VERSION_MINOR 0) set(LLAMA_VERSION_PATCH 0) set(LLAMA_VERSION_BASE "${LLAMA_VERSION_MAJOR}.${LLAMA_VERSION_MINOR}.${LLAMA_VERSION_PATCH}") diff --git a/README.md b/README.md index 84e9eb5d9295..80b73cc528fa 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ LLM inference in C/C++ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT) -[![Release](https://img.shields.io/github/v/release/ggml-org/llama.cpp?filter=v*&color=brightgreen)](https://github.com/ggml-org/llama.cpp/releases?q=tag:v0) +[![Release](https://img.shields.io/github/v/release/ggml-org/llama.cpp?filter=v*&color=brightgreen)](https://github.com/ggml-org/llama.cpp/releases?q=tag:v1) [![Nightly](https://img.shields.io/github/v/release/ggml-org/llama.cpp?label=nightly&filter=b*&color=orange)](https://github.com/ggml-org/llama.cpp/releases?q=b) [![Server](https://img.shields.io/github/actions/workflow/status/ggml-org/llama.cpp/server.yml?label=Server)](https://github.com/ggml-org/llama.cpp/actions/workflows/server.yml) [![Docker](https://img.shields.io/github/actions/workflow/status/ggml-org/llama.cpp/docker.yml?label=Docker)](https://github.com/ggml-org/llama.cpp/actions/workflows/docker.yml) diff --git a/common/parsers/k2-horizon.cpp b/common/parsers/k2-horizon.cpp index 1afd578c83eb..e688cd919382 100644 --- a/common/parsers/k2-horizon.cpp +++ b/common/parsers/k2-horizon.cpp @@ -48,6 +48,11 @@ common_chat_params common_chat_params_init_k2_horizon(const common_chat_template data.thinking_start_tag = THINK_START; data.thinking_end_tags = { THINK_END }; + // The models sometimes close medium/low reasoning with the generic + if (think != "ifm|think") { + data.thinking_end_tags.push_back(""); + } + data.preserved_tokens = data.thinking_end_tags; data.preserved_tokens.insert(data.preserved_tokens.end(), { THINK_START, SECTION_START, SECTION_END, CALL_START, CALL_END, diff --git a/common/speculative.cpp b/common/speculative.cpp index aa37d8bb8228..dbdadb1ea056 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -3050,6 +3050,26 @@ common_speculative * common_speculative_init(common_params_speculative & params, return nullptr; } + // the n-gram drafters ignore p_min, and DSpark uses it as the cutoff of its confidence head + const bool uses_p_min = std::any_of(configs.begin(), configs.end(), [](const common_speculative_config & c) { + switch (c.type) { + case COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK: + case COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE: + case COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K: + case COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V: + case COMMON_SPECULATIVE_TYPE_NGRAM_MOD: + case COMMON_SPECULATIVE_TYPE_NGRAM_CACHE: + return false; + default: + return true; + } + }); + + if (params.draft.probabilistic && params.draft.p_min > 0.0f && uses_p_min) { + LOG_WRN("%s: --spec-draft-p-min %.2f stops sampled drafts early, consider setting it to 0 with --spec-draft-sampling probabilistic\n", + __func__, (double) params.draft.p_min); + } + common_speculative_ptr result(new common_speculative { /* .dparams = */ common_speculative_draft_params_vec(n_seq), /* .impls = */ std::move(impls), diff --git a/docs/ops.md b/docs/ops.md index 3c2bcd239bb1..c2ae5cbfb15f 100644 --- a/docs/ops.md +++ b/docs/ops.md @@ -126,7 +126,7 @@ Legend: | TANH | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | TIMESTEP_EMBEDDING | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | | TOP_K | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | 🟡 | ✅ | ❌ | ❌ | -| TOP_K_MASK | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | +| TOP_K_MASK | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | | TRI | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | | TRUNC | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | UPSCALE | ❌ | 🟡 | ✅ | ✅ | ❌ | ❌ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | diff --git a/docs/ops/Vulkan.csv b/docs/ops/Vulkan.csv index 65ac8bf33984..dbd6412efb39 100644 --- a/docs/ops/Vulkan.csv +++ b/docs/ops/Vulkan.csv @@ -19439,3 +19439,31 @@ "Vulkan0","LIGHTNING_INDEXER","hsk=128,nh=64,kv=256,nb=512,ns=4,nm=1,type_K=q4_1","support","0","no","Vulkan" "Vulkan0","LIGHTNING_INDEXER","hsk=128,nh=64,kv=256,nb=512,ns=4,nm=1,type_K=q4_0","support","0","no","Vulkan" "Vulkan0","LIGHTNING_INDEXER","hsk=128,nh=64,kv=256,nb=512,ns=4,nm=1,type_K=iq4_nl","support","0","no","Vulkan" +"Vulkan0","TOP_K_MASK","type=f16,n_kv=256,n_blk=4,n_pick=64,n_top=16,n_extra=3,score=1,nb=32,nh=1,ns=1,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f16,n_kv=1001,n_blk=4,n_pick=70,n_top=16,n_extra=3,score=1,nb=7,nh=1,ns=1,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f16,n_kv=256,n_blk=4,n_pick=64,n_top=64,n_extra=0,score=1,nb=33,nh=1,ns=1,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f16,n_kv=512,n_blk=8,n_pick=16,n_top=32,n_extra=7,score=1,nb=5,nh=1,ns=4,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f16,n_kv=4096,n_blk=4,n_pick=1024,n_top=512,n_extra=3,score=1,nb=1,nh=1,ns=1,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f16,n_kv=4096,n_blk=4,n_pick=1024,n_top=512,n_extra=3,score=1,nb=64,nh=1,ns=2,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f16,n_kv=256,n_blk=0,n_pick=256,n_top=16,n_extra=0,score=0,nb=32,nh=1,ns=1,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f16,n_kv=1001,n_blk=0,n_pick=1001,n_top=64,n_extra=0,score=0,nb=7,nh=1,ns=3,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f16,n_kv=4096,n_blk=0,n_pick=4096,n_top=2048,n_extra=0,score=0,nb=5,nh=1,ns=1,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f16,n_kv=512,n_blk=0,n_pick=512,n_top=32,n_extra=5,score=1,nb=9,nh=1,ns=1,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f16,n_kv=512,n_blk=16,n_pick=32,n_top=4,n_extra=0,score=1,nb=6,nh=4,ns=1,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f16,n_kv=1024,n_blk=8,n_pick=128,n_top=16,n_extra=8,score=0,nb=3,nh=2,ns=2,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f16,n_kv=1001,n_blk=4,n_pick=70,n_top=16,n_extra=3,score=1,nb=7,nh=1,ns=1,real=0,bcast=1","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f16,n_kv=512,n_blk=8,n_pick=16,n_top=32,n_extra=7,score=1,nb=5,nh=1,ns=4,real=0,bcast=1","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f32,n_kv=256,n_blk=4,n_pick=64,n_top=16,n_extra=3,score=1,nb=32,nh=1,ns=1,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f32,n_kv=1001,n_blk=4,n_pick=70,n_top=16,n_extra=3,score=1,nb=7,nh=1,ns=1,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f32,n_kv=256,n_blk=4,n_pick=64,n_top=64,n_extra=0,score=1,nb=33,nh=1,ns=1,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f32,n_kv=512,n_blk=8,n_pick=16,n_top=32,n_extra=7,score=1,nb=5,nh=1,ns=4,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f32,n_kv=4096,n_blk=4,n_pick=1024,n_top=512,n_extra=3,score=1,nb=1,nh=1,ns=1,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f32,n_kv=4096,n_blk=4,n_pick=1024,n_top=512,n_extra=3,score=1,nb=64,nh=1,ns=2,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f32,n_kv=256,n_blk=0,n_pick=256,n_top=16,n_extra=0,score=0,nb=32,nh=1,ns=1,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f32,n_kv=1001,n_blk=0,n_pick=1001,n_top=64,n_extra=0,score=0,nb=7,nh=1,ns=3,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f32,n_kv=4096,n_blk=0,n_pick=4096,n_top=2048,n_extra=0,score=0,nb=5,nh=1,ns=1,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f32,n_kv=512,n_blk=0,n_pick=512,n_top=32,n_extra=5,score=1,nb=9,nh=1,ns=1,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f32,n_kv=512,n_blk=16,n_pick=32,n_top=4,n_extra=0,score=1,nb=6,nh=4,ns=1,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f32,n_kv=1024,n_blk=8,n_pick=128,n_top=16,n_extra=8,score=0,nb=3,nh=2,ns=2,real=0,bcast=0","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f32,n_kv=1001,n_blk=4,n_pick=70,n_top=16,n_extra=3,score=1,nb=7,nh=1,ns=1,real=0,bcast=1","support","1","yes","Vulkan" +"Vulkan0","TOP_K_MASK","type=f32,n_kv=512,n_blk=8,n_pick=16,n_top=32,n_extra=7,score=1,nb=5,nh=1,ns=4,real=0,bcast=1","support","1","yes","Vulkan" diff --git a/docs/speculative.md b/docs/speculative.md index d8f3bcb3922a..9072eedd34ac 100644 --- a/docs/speculative.md +++ b/docs/speculative.md @@ -189,7 +189,7 @@ llama-server ... --spec-type ngram-mod --spec-ngram-mod-n-match 24 --spec-ngram- Applications: -- Iterating over a block of text/code (e.g. in llama.vim) +- Iterating over a block of text/code (e.g. in [llama.vim](https://github.com/ggml-org/llama.vim)) - Reasoning models (when they have to repeat their thinking in the final answer) - Summarization diff --git a/examples/json_schema_pydantic_example.py b/examples/json_schema_pydantic_example.py deleted file mode 100644 index dae2a9b8a2a4..000000000000 --- a/examples/json_schema_pydantic_example.py +++ /dev/null @@ -1,82 +0,0 @@ -# Usage: -#! ./llama-server -m some-model.gguf & -#! pip install pydantic -#! python json_schema_pydantic_example.py - -from pydantic import BaseModel, Field, TypeAdapter -from annotated_types import MinLen -from typing import Annotated, List, Optional -import json, requests - -if True: - - def create_completion(*, response_model=None, endpoint="http://localhost:9931/v1/chat/completions", messages, **kwargs): - ''' - Creates a chat completion using an OpenAI-compatible endpoint w/ JSON schema support - (llama.cpp server, llama-cpp-python, Anyscale / Together...) - - The response_model param takes a type (+ supports Pydantic) and behaves just as w/ Instructor (see below) - ''' - response_format = None - type_adapter = None - - if response_model: - type_adapter = TypeAdapter(response_model) - schema = type_adapter.json_schema() - messages = [{ - "role": "system", - "content": f"You respond in JSON format with the following schema: {json.dumps(schema, indent=2)}" - }] + messages - response_format={"type": "json_object", "schema": schema} - - data = requests.post(endpoint, headers={"Content-Type": "application/json"}, - json=dict(messages=messages, response_format=response_format, **kwargs)).json() - if 'error' in data: - raise Exception(data['error']['message']) - - content = data["choices"][0]["message"]["content"] - return type_adapter.validate_json(content) if type_adapter else content - -else: - - # This alternative branch uses Instructor + OpenAI client lib. - # Instructor support streamed iterable responses, retry & more. - # (see https://python.useinstructor.com/) - #! pip install instructor openai - import instructor, openai - client = instructor.patch( - openai.OpenAI(api_key="123", base_url="http://localhost:9931"), - mode=instructor.Mode.JSON_SCHEMA) - create_completion = client.chat.completions.create - - -if __name__ == '__main__': - - class QAPair(BaseModel): - class Config: - extra = 'forbid' # triggers additionalProperties: false in the JSON schema - question: str - concise_answer: str - justification: str - stars: Annotated[int, Field(ge=1, le=5)] - - class PyramidalSummary(BaseModel): - class Config: - extra = 'forbid' # triggers additionalProperties: false in the JSON schema - title: str - summary: str - question_answers: Annotated[List[QAPair], MinLen(2)] - sub_sections: Optional[Annotated[List['PyramidalSummary'], MinLen(2)]] - - print("# Summary\n", create_completion( - model="...", - response_model=PyramidalSummary, - messages=[{ - "role": "user", - "content": f""" - You are a highly efficient corporate document summarizer. - Create a pyramidal summary of an imaginary internal document about our company processes - (starting high-level, going down to each sub sections). - Keep questions short, and answers even shorter (trivia / quizz style). - """ - }])) diff --git a/examples/llama.vim b/examples/llama.vim deleted file mode 100644 index 23a281fc3332..000000000000 --- a/examples/llama.vim +++ /dev/null @@ -1,783 +0,0 @@ -" LLM-based text completion using llama.cpp -" -" requires: -" -" - neovim or vim -" - curl -" - llama.cpp server instance -" - FIM-compatible model -" -" sample config: -" -" - Tab - accept the current suggestion -" - Shift+Tab - accept just the first line of the suggestion -" - Ctrl+F - toggle FIM completion manually -" -" make symlink or copy this file to ~/.config/nvim/autoload/llama.vim -" -" start the llama.cpp server with a FIM-compatible model. for example: -" -" $ llama-server -m {model.gguf} --port 8012 -ngl 99 -fa --ubatch-size 512 --batch-size 1024 --cache-reuse 256 -" -" --batch-size [512, model max context] -" -" adjust the batch size to control how much of the provided local context will be used during the inference -" lower values will use smaller part of the context around the cursor, which will result in faster processing -" -" --ubatch-size [64, 2048] -" -" chunks the batch into smaller chunks for faster processing -" depends on the specific hardware. use llama-bench to profile and determine the best size -" -" --cache-reuse (ge:llama_config.n_predict, 1024] -" -" this should be either 0 (disabled) or strictly larger than g:llama_config.n_predict -" using non-zero value enables context reuse on the server side which dramatically improves the performance at -" large contexts. a value of 256 should be good for all cases -" -" run this once to initialise llama.vim: -" -" :call llama#init() -" -" more info: https://github.com/ggml-org/llama.cpp/pull/9787 -" - -" colors (adjust to your liking) -highlight llama_hl_hint guifg=#ff772f ctermfg=202 -highlight llama_hl_info guifg=#77ff2f ctermfg=119 - -" general parameters: -" -" endpoint: llama.cpp server endpoint -" n_prefix: number of lines before the cursor location to include in the local prefix -" n_suffix: number of lines after the cursor location to include in the local suffix -" n_predict: max number of tokens to predict -" t_max_prompt_ms: max allotted time for the prompt processing (TODO: not yet supported) -" t_max_predict_ms: max allotted time for the prediction -" show_info: show extra info about the inference (0 - disabled, 1 - statusline, 2 - inline) -" auto_fim: trigger FIM completion automatically on cursor movement -" max_line_suffix: do not auto-trigger FIM completion if there are more than this number of characters to the right of the cursor -" -" ring buffer of chunks, accumulated with time upon: -" -" - completion request -" - yank -" - entering a buffer -" - leaving a buffer -" - writing a file -" -" parameters for the ring-buffer with extra context: -" -" ring_n_chunks: max number of chunks to pass as extra context to the server (0 to disable) -" ring_chunk_size: max size of the chunks (in number of lines) -" note: adjust these numbers so that you don't overrun your context -" at ring_n_chunks = 64 and ring_chunk_size = 64 you need ~32k context -" ring_scope: the range around the cursor position (in number of lines) for gathering chunks after FIM -" ring_update_ms: how often to process queued chunks in normal mode -" -let s:default_config = { - \ 'endpoint': 'http://127.0.0.1:8012/infill', - \ 'n_prefix': 256, - \ 'n_suffix': 64, - \ 'n_predict': 128, - \ 't_max_prompt_ms': 500, - \ 't_max_predict_ms': 3000, - \ 'show_info': 2, - \ 'auto_fim': v:true, - \ 'max_line_suffix': 8, - \ 'ring_n_chunks': 64, - \ 'ring_chunk_size': 64, - \ 'ring_scope': 1024, - \ 'ring_update_ms': 1000, - \ } - -let g:llama_config = get(g:, 'llama_config', s:default_config) - -function! s:get_indent(str) - let l:count = 0 - for i in range(len(a:str)) - if a:str[i] == "\t" - let l:count += &tabstop - 1 - else - break - endif - endfor - return l:count -endfunction - -function! s:rand(i0, i1) abort - return a:i0 + rand() % (a:i1 - a:i0 + 1) -endfunction - -function! llama#init() - if !executable('curl') - echohl WarningMsg - echo 'llama.vim requires the "curl" command to be available' - echohl None - return - endif - - let s:pos_x = 0 " cursor position upon start of completion - let s:pos_y = 0 - - let s:line_cur = '' - - let s:line_cur_prefix = '' - let s:line_cur_suffix = '' - - let s:ring_chunks = [] " current set of chunks used as extra context - let s:ring_queued = [] " chunks that are queued to be sent for processing - let s:ring_n_evict = 0 - - let s:hint_shown = v:false - let s:pos_y_pick = -9999 " last y where we picked a chunk - let s:pos_dx = 0 - let s:content = [] - let s:can_accept = v:false - - let s:timer_fim = -1 - let s:t_fim_start = reltime() " used to measure total FIM time - let s:t_last_move = reltime() " last time the cursor moved - - let s:current_job = v:null - - let s:ghost_text_nvim = exists('*nvim_buf_get_mark') - let s:ghost_text_vim = has('textprop') - - if s:ghost_text_vim - let s:hlgroup_hint = 'llama_hl_hint' - let s:hlgroup_info = 'llama_hl_info' - - if empty(prop_type_get(s:hlgroup_hint)) - call prop_type_add(s:hlgroup_hint, {'highlight': s:hlgroup_hint}) - endif - if empty(prop_type_get(s:hlgroup_info)) - call prop_type_add(s:hlgroup_info, {'highlight': s:hlgroup_info}) - endif - endif - - augroup llama - autocmd! - autocmd InsertEnter * inoremap llama#fim_inline(v:false) - autocmd InsertLeavePre * call llama#fim_cancel() - - autocmd CursorMoved * call s:on_move() - autocmd CursorMovedI * call s:on_move() - autocmd CompleteChanged * call llama#fim_cancel() - - if g:llama_config.auto_fim - autocmd CursorMovedI * call llama#fim(v:true) - endif - - " gather chunks upon yanking - autocmd TextYankPost * if v:event.operator ==# 'y' | call s:pick_chunk(v:event.regcontents, v:false, v:true) | endif - - " gather chunks upon entering/leaving a buffer - autocmd BufEnter * call timer_start(100, {-> s:pick_chunk(getline(max([1, line('.') - g:llama_config.ring_chunk_size/2]), min([line('.') + g:llama_config.ring_chunk_size/2, line('$')])), v:true, v:true)}) - autocmd BufLeave * call s:pick_chunk(getline(max([1, line('.') - g:llama_config.ring_chunk_size/2]), min([line('.') + g:llama_config.ring_chunk_size/2, line('$')])), v:true, v:true) - - " gather chunk upon saving the file - autocmd BufWritePost * call s:pick_chunk(getline(max([1, line('.') - g:llama_config.ring_chunk_size/2]), min([line('.') + g:llama_config.ring_chunk_size/2, line('$')])), v:true, v:true) - augroup END - - silent! call llama#fim_cancel() - - " init background update of the ring buffer - if g:llama_config.ring_n_chunks > 0 - call s:ring_update() - endif -endfunction - -" compute how similar two chunks of text are -" 0 - no similarity, 1 - high similarity -" TODO: figure out something better -function! s:chunk_sim(c0, c1) - let l:lines0 = len(a:c0) - let l:lines1 = len(a:c1) - - let l:common = 0 - - for l:line0 in a:c0 - for l:line1 in a:c1 - if l:line0 == l:line1 - let l:common += 1 - break - endif - endfor - endfor - - return 2.0 * l:common / (l:lines0 + l:lines1) -endfunction - -" pick a random chunk of size g:llama_config.ring_chunk_size from the provided text and queue it for processing -" -" no_mod - do not pick chunks from buffers with pending changes -" do_evict - evict chunks that are very similar to the new one -" -function! s:pick_chunk(text, no_mod, do_evict) - " do not pick chunks from buffers with pending changes or buffers that are not files - if a:no_mod && (getbufvar(bufnr('%'), '&modified') || !buflisted(bufnr('%')) || !filereadable(expand('%'))) - return - endif - - " if the extra context option is disabled - do nothing - if g:llama_config.ring_n_chunks <= 0 - return - endif - - " don't pick very small chunks - if len(a:text) < 3 - return - endif - - if len(a:text) + 1 < g:llama_config.ring_chunk_size - let l:chunk = a:text - else - let l:l0 = s:rand(0, max([0, len(a:text) - g:llama_config.ring_chunk_size/2])) - let l:l1 = min([l:l0 + g:llama_config.ring_chunk_size/2, len(a:text)]) - - let l:chunk = a:text[l:l0:l:l1] - endif - - let l:chunk_str = join(l:chunk, "\n") . "\n" - - " check if this chunk is already added - let l:exist = v:false - - for i in range(len(s:ring_chunks)) - if s:ring_chunks[i].data == l:chunk - let l:exist = v:true - break - endif - endfor - - for i in range(len(s:ring_queued)) - if s:ring_queued[i].data == l:chunk - let l:exist = v:true - break - endif - endfor - - if l:exist - return - endif - - " evict queued chunks that are very similar to the new one - for i in range(len(s:ring_queued) - 1, 0, -1) - if s:chunk_sim(s:ring_queued[i].data, l:chunk) > 0.9 - if a:do_evict - call remove(s:ring_queued, i) - let s:ring_n_evict += 1 - else - return - endif - endif - endfor - - " also from s:ring_chunks - for i in range(len(s:ring_chunks) - 1, 0, -1) - if s:chunk_sim(s:ring_chunks[i].data, l:chunk) > 0.9 - if a:do_evict - call remove(s:ring_chunks, i) - let s:ring_n_evict += 1 - else - return - endif - endif - endfor - - " TODO: become parameter ? - if len(s:ring_queued) == 16 - call remove(s:ring_queued, 0) - endif - - call add(s:ring_queued, {'data': l:chunk, 'str': l:chunk_str, 'time': reltime(), 'filename': expand('%')}) - - "let &statusline = 'extra context: ' . len(s:ring_chunks) . ' / ' . len(s:ring_queued) -endfunction - -" picks a queued chunk, sends it for processing and adds it to s:ring_chunks -" called every g:llama_config.ring_update_ms -function! s:ring_update() - call timer_start(g:llama_config.ring_update_ms, {-> s:ring_update()}) - - " update only if in normal mode or if the cursor hasn't moved for a while - if mode() !=# 'n' && reltimefloat(reltime(s:t_last_move)) < 3.0 - return - endif - - if len(s:ring_queued) == 0 - return - endif - - " move the first queued chunk to the ring buffer - if len(s:ring_chunks) == g:llama_config.ring_n_chunks - call remove(s:ring_chunks, 0) - endif - - call add(s:ring_chunks, remove(s:ring_queued, 0)) - - "let &statusline = 'updated context: ' . len(s:ring_chunks) . ' / ' . len(s:ring_queued) - - " send asynchronous job with the new extra context so that it is ready for the next FIM - let l:extra_context = [] - for l:chunk in s:ring_chunks - call add(l:extra_context, { - \ 'text': l:chunk.str, - \ 'time': l:chunk.time, - \ 'filename': l:chunk.filename - \ }) - endfor - - " no samplers needed here - let l:request = json_encode({ - \ 'input_prefix': "", - \ 'input_suffix': "", - \ 'input_extra': l:extra_context, - \ 'prompt': "", - \ 'n_predict': 1, - \ 'temperature': 0.0, - \ 'stream': v:false, - \ 'samplers': ["temperature"], - \ 'cache_prompt': v:true, - \ 't_max_prompt_ms': 1, - \ 't_max_predict_ms': 1 - \ }) - - let l:curl_command = [ - \ "curl", - \ "--silent", - \ "--no-buffer", - \ "--request", "POST", - \ "--url", g:llama_config.endpoint, - \ "--header", "Content-Type: application/json", - \ "--data", l:request - \ ] - - " no callbacks because we don't need to process the response - if s:ghost_text_nvim - call jobstart(l:curl_command, {}) - elseif s:ghost_text_vim - call job_start(l:curl_command, {}) - endif -endfunction - -" necessary for 'inoremap ' -function! llama#fim_inline(is_auto) abort - call llama#fim(a:is_auto) - return '' -endfunction - -" the main FIM call -" takes local context around the cursor and sends it together with the extra context to the server for completion -function! llama#fim(is_auto) abort - " we already have a suggestion for the current cursor position - if s:hint_shown && !a:is_auto - call llama#fim_cancel() - return - endif - - call llama#fim_cancel() - - " avoid sending repeated requests too fast - if reltimefloat(reltime(s:t_fim_start)) < 0.6 - if s:timer_fim != -1 - call timer_stop(s:timer_fim) - let s:timer_fim = -1 - endif - - let s:t_fim_start = reltime() - let s:timer_fim = timer_start(600, {-> llama#fim(v:true)}) - return - endif - - let s:t_fim_start = reltime() - - let s:content = [] - let s:can_accept = v:false - - let s:pos_x = col('.') - 1 - let s:pos_y = line('.') - let l:max_y = line('$') - - let l:lines_prefix = getline(max([1, s:pos_y - g:llama_config.n_prefix]), s:pos_y - 1) - let l:lines_suffix = getline(s:pos_y + 1, min([l:max_y, s:pos_y + g:llama_config.n_suffix])) - - let s:line_cur = getline('.') - - let s:line_cur_prefix = strpart(s:line_cur, 0, s:pos_x) - let s:line_cur_suffix = strpart(s:line_cur, s:pos_x) - - if a:is_auto && len(s:line_cur_suffix) > g:llama_config.max_line_suffix - return - endif - - let l:prefix = "" - \ . join(l:lines_prefix, "\n") - \ . "\n" - - let l:prompt = "" - \ . s:line_cur_prefix - - let l:suffix = "" - \ . s:line_cur_suffix - \ . "\n" - \ . join(l:lines_suffix, "\n") - \ . "\n" - - " prepare the extra context data - let l:extra_context = [] - for l:chunk in s:ring_chunks - call add(l:extra_context, { - \ 'text': l:chunk.str, - \ 'time': l:chunk.time, - \ 'filename': l:chunk.filename - \ }) - endfor - - " the indentation of the current line - let l:indent = strlen(matchstr(s:line_cur_prefix, '^\s*')) - - let l:request = json_encode({ - \ 'input_prefix': l:prefix, - \ 'input_suffix': l:suffix, - \ 'input_extra': l:extra_context, - \ 'prompt': l:prompt, - \ 'n_predict': g:llama_config.n_predict, - \ 'n_indent': l:indent, - \ 'top_k': 40, - \ 'top_p': 0.99, - \ 'stream': v:false, - \ 'samplers': ["top_k", "top_p", "infill"], - \ 'cache_prompt': v:true, - \ 't_max_prompt_ms': g:llama_config.t_max_prompt_ms, - \ 't_max_predict_ms': g:llama_config.t_max_predict_ms - \ }) - - let l:curl_command = [ - \ "curl", - \ "--silent", - \ "--no-buffer", - \ "--request", "POST", - \ "--url", g:llama_config.endpoint, - \ "--header", "Content-Type: application/json", - \ "--data", l:request - \ ] - - if s:current_job != v:null - if s:ghost_text_nvim - call jobstop(s:current_job) - elseif s:ghost_text_vim - call job_stop(s:current_job) - endif - endif - - " send the request asynchronously - if s:ghost_text_nvim - let s:current_job = jobstart(l:curl_command, { - \ 'on_stdout': function('s:fim_on_stdout', [s:pos_x, s:pos_y, a:is_auto]), - \ 'on_exit': function('s:fim_on_exit'), - \ 'stdout_buffered': v:true - \ }) - elseif s:ghost_text_vim - let s:current_job = job_start(l:curl_command, { - \ 'out_cb': function('s:fim_on_stdout', [s:pos_x, s:pos_y, a:is_auto]), - \ 'exit_cb': function('s:fim_on_exit') - \ }) - endif - - " TODO: per-file location - let l:delta_y = abs(s:pos_y - s:pos_y_pick) - - " gather some extra context nearby and process it in the background - " only gather chunks if the cursor has moved a lot - " TODO: something more clever? reranking? - if a:is_auto && l:delta_y > 32 - " expand the prefix even further - call s:pick_chunk(getline(max([1, s:pos_y - g:llama_config.ring_scope]), max([1, s:pos_y - g:llama_config.n_prefix])), v:false, v:false) - - " pick a suffix chunk - call s:pick_chunk(getline(min([l:max_y, s:pos_y + g:llama_config.n_suffix]), min([l:max_y, s:pos_y + g:llama_config.n_suffix + g:llama_config.ring_chunk_size])), v:false, v:false) - - let s:pos_y_pick = s:pos_y - endif -endfunction - -" if first_line == v:true accept only the first line of the response -function! llama#fim_accept(first_line) - " insert the suggestion at the cursor location - if s:can_accept && len(s:content) > 0 - call setline(s:pos_y, s:line_cur[:(s:pos_x - 1)] . s:content[0]) - if len(s:content) > 1 - if !a:first_line - call append(s:pos_y, s:content[1:-1]) - endif - endif - - " move the cursor to the end of the accepted text - if !a:first_line && len(s:content) > 1 - call cursor(s:pos_y + len(s:content) - 1, s:pos_x + s:pos_dx + 1) - else - call cursor(s:pos_y, s:pos_x + len(s:content[0])) - endif - endif - - call llama#fim_cancel() -endfunction - -function! llama#fim_cancel() - let s:hint_shown = v:false - - " clear the virtual text - let l:bufnr = bufnr('%') - - if s:ghost_text_nvim - let l:id_vt_fim = nvim_create_namespace('vt_fim') - call nvim_buf_clear_namespace(l:bufnr, l:id_vt_fim, 0, -1) - elseif s:ghost_text_vim - call prop_remove({'type': s:hlgroup_hint, 'all': v:true}) - call prop_remove({'type': s:hlgroup_info, 'all': v:true}) - endif - - " remove the mappings - silent! iunmap - silent! iunmap - silent! iunmap -endfunction - -function! s:on_move() - let s:t_last_move = reltime() - - call llama#fim_cancel() -endfunction - -" callback that processes the FIM result from the server and displays the suggestion -function! s:fim_on_stdout(pos_x, pos_y, is_auto, job_id, data, event = v:null) - if s:ghost_text_nvim - let l:raw = join(a:data, "\n") - elseif s:ghost_text_vim - let l:raw = a:data - endif - - if len(l:raw) == 0 - return - endif - - if a:pos_x != col('.') - 1 || a:pos_y != line('.') - return - endif - - " show the suggestion only in insert mode - if mode() !=# 'i' - return - endif - - let s:pos_x = a:pos_x - let s:pos_y = a:pos_y - - let s:can_accept = v:true - let l:has_info = v:false - - if s:can_accept && v:shell_error - if !a:is_auto - call add(s:content, "<| curl error: is the server on? |>") - endif - let s:can_accept = v:false - endif - - let l:n_prompt = 0 - let l:t_prompt_ms = 1.0 - let l:s_prompt = 0 - - let l:n_predict = 0 - let l:t_predict_ms = 1.0 - let l:s_predict = 0 - - " get the generated suggestion - if s:can_accept - let l:response = json_decode(l:raw) - - for l:part in split(get(l:response, 'content', ''), "\n", 1) - call add(s:content, l:part) - endfor - - " remove trailing new lines - while len(s:content) > 0 && s:content[-1] == "" - call remove(s:content, -1) - endwhile - - let l:generation_settings = get(l:response, 'generation_settings', {}) - let l:n_ctx = get(l:generation_settings, 'n_ctx', 0) - - let l:n_cached = get(l:response, 'tokens_cached', 0) - let l:truncated = get(l:response, 'truncated', v:false) - - " if response.timings is available - if len(get(l:response, 'timings', {})) > 0 - let l:has_info = v:true - let l:timings = get(l:response, 'timings', {}) - - let l:n_prompt = get(l:timings, 'prompt_n', 0) - let l:t_prompt_ms = get(l:timings, 'prompt_ms', 1) - let l:s_prompt = get(l:timings, 'prompt_per_second', 0) - - let l:n_predict = get(l:timings, 'predicted_n', 0) - let l:t_predict_ms = get(l:timings, 'predicted_ms', 1) - let l:s_predict = get(l:timings, 'predicted_per_second', 0) - endif - endif - - if len(s:content) == 0 - call add(s:content, "") - let s:can_accept = v:false - endif - - if len(s:content) == 0 - return - endif - - " NOTE: the following is logic for discarding predictions that repeat existing text - " the code is quite ugly and there is very likely a simpler and more canonical way to implement this - " - " still, I wonder if there is some better way that avoids having to do these special hacks? - " on one hand, the LLM 'sees' the contents of the file before we start editing, so it is normal that it would - " start generating whatever we have given it via the extra context. but on the other hand, it's not very - " helpful to re-generate the same code that is already there - - " truncate the suggestion if the first line is empty - if len(s:content) == 1 && s:content[0] == "" - let s:content = [""] - endif - - " ... and the next lines are repeated - if len(s:content) > 1 && s:content[0] == "" && s:content[1:] == getline(s:pos_y + 1, s:pos_y + len(s:content) - 1) - let s:content = [""] - endif - - " truncate the suggestion if it repeats the suffix - if len(s:content) == 1 && s:content[0] == s:line_cur_suffix - let s:content = [""] - endif - - " find the first non-empty line (strip whitespace) - let l:cmp_y = s:pos_y + 1 - while l:cmp_y < line('$') && getline(l:cmp_y) =~? '^\s*$' - let l:cmp_y += 1 - endwhile - - if (s:line_cur_prefix . s:content[0]) == getline(l:cmp_y) - " truncate the suggestion if it repeats the next line - if len(s:content) == 1 - let s:content = [""] - endif - - " ... or if the second line of the suggestion is the prefix of line l:cmp_y + 1 - if len(s:content) == 2 && s:content[-1] == getline(l:cmp_y + 1)[:len(s:content[-1]) - 1] - let s:content = [""] - endif - - " ... or if the middle chunk of lines of the suggestion is the same as [l:cmp_y + 1, l:cmp_y + len(s:content) - 1) - if len(s:content) > 2 && join(s:content[1:-1], "\n") == join(getline(l:cmp_y + 1, l:cmp_y + len(s:content) - 1), "\n") - let s:content = [""] - endif - endif - - " keep only lines that have the same or larger whitespace prefix as s:line_cur_prefix - "let l:indent = strlen(matchstr(s:line_cur_prefix, '^\s*')) - "for i in range(1, len(s:content) - 1) - " if strlen(matchstr(s:content[i], '^\s*')) < l:indent - " let s:content = s:content[:i - 1] - " break - " endif - "endfor - - let s:pos_dx = len(s:content[-1]) - - let s:content[-1] .= s:line_cur_suffix - - call llama#fim_cancel() - - " display virtual text with the suggestion - let l:bufnr = bufnr('%') - - if s:ghost_text_nvim - let l:id_vt_fim = nvim_create_namespace('vt_fim') - endif - - " construct the info message - if g:llama_config.show_info > 0 && l:has_info - let l:prefix = ' ' - - if l:truncated - let l:info = printf("%s | WARNING: the context is full: %d / %d, increase the server context size or reduce g:llama_config.ring_n_chunks", - \ g:llama_config.show_info == 2 ? l:prefix : 'llama.vim', - \ l:n_cached, l:n_ctx - \ ) - else - let l:info = printf("%s | c: %d / %d, r: %d / %d, e: %d, q: %d / 16 | p: %d (%.2f ms, %.2f t/s) | g: %d (%.2f ms, %.2f t/s) | t: %.2f ms", - \ g:llama_config.show_info == 2 ? l:prefix : 'llama.vim', - \ l:n_cached, l:n_ctx, len(s:ring_chunks), g:llama_config.ring_n_chunks, s:ring_n_evict, len(s:ring_queued), - \ l:n_prompt, l:t_prompt_ms, l:s_prompt, - \ l:n_predict, l:t_predict_ms, l:s_predict, - \ 1000.0 * reltimefloat(reltime(s:t_fim_start)) - \ ) - endif - - if g:llama_config.show_info == 1 - " display the info in the statusline - let &statusline = l:info - let l:info = '' - endif - endif - - " display the suggestion and append the info to the end of the first line - if s:ghost_text_nvim - call nvim_buf_set_extmark(l:bufnr, l:id_vt_fim, s:pos_y - 1, s:pos_x - 1, { - \ 'virt_text': [[s:content[0], 'llama_hl_hint'], [l:info, 'llama_hl_info']], - \ 'virt_text_win_col': virtcol('.') - 1 - \ }) - - call nvim_buf_set_extmark(l:bufnr, l:id_vt_fim, s:pos_y - 1, 0, { - \ 'virt_lines': map(s:content[1:], {idx, val -> [[val, 'llama_hl_hint']]}), - \ 'virt_text_win_col': virtcol('.') - \ }) - elseif s:ghost_text_vim - let l:new_suffix = s:content[0] - if !empty(l:new_suffix) - call prop_add(s:pos_y, s:pos_x + 1, { - \ 'type': s:hlgroup_hint, - \ 'text': l:new_suffix - \ }) - endif - for line in s:content[1:] - call prop_add(s:pos_y, 0, { - \ 'type': s:hlgroup_hint, - \ 'text': line, - \ 'text_padding_left': s:get_indent(line), - \ 'text_align': 'below' - \ }) - endfor - if !empty(l:info) - call prop_add(s:pos_y, 0, { - \ 'type': s:hlgroup_info, - \ 'text': l:info, - \ 'text_padding_left': col('$'), - \ 'text_wrap': 'truncate' - \ }) - endif - endif - - " setup accept shortcuts - inoremap :call llama#fim_accept(v:false) - inoremap :call llama#fim_accept(v:true) - - let s:hint_shown = v:true -endfunction - -function! s:fim_on_exit(job_id, exit_code, event = v:null) - if a:exit_code != 0 - echom "Job failed with exit code: " . a:exit_code - endif - - let s:current_job = v:null -endfunction diff --git a/examples/pydantic_models_to_grammar.py b/examples/pydantic_models_to_grammar.py deleted file mode 100644 index ff6e120e45bb..000000000000 --- a/examples/pydantic_models_to_grammar.py +++ /dev/null @@ -1,1322 +0,0 @@ -from __future__ import annotations - -import inspect -import json -import re -from copy import copy -from enum import Enum -from inspect import getdoc, isclass -from typing import TYPE_CHECKING, Any, Callable, Optional, Union, get_args, get_origin, get_type_hints - -from docstring_parser import parse -from pydantic import BaseModel, create_model - -if TYPE_CHECKING: - from types import GenericAlias -else: - # python 3.8 compat - from typing import _GenericAlias as GenericAlias - -# TODO: fix this -# pyright: reportAttributeAccessIssue=information - - -class PydanticDataType(Enum): - """ - Defines the data types supported by the grammar_generator. - - Attributes: - STRING (str): Represents a string data type. - BOOLEAN (str): Represents a boolean data type. - INTEGER (str): Represents an integer data type. - FLOAT (str): Represents a float data type. - OBJECT (str): Represents an object data type. - ARRAY (str): Represents an array data type. - ENUM (str): Represents an enum data type. - CUSTOM_CLASS (str): Represents a custom class data type. - """ - - STRING = "string" - TRIPLE_QUOTED_STRING = "triple_quoted_string" - MARKDOWN_CODE_BLOCK = "markdown_code_block" - BOOLEAN = "boolean" - INTEGER = "integer" - FLOAT = "float" - OBJECT = "object" - ARRAY = "array" - ENUM = "enum" - ANY = "any" - NULL = "null" - CUSTOM_CLASS = "custom-class" - CUSTOM_DICT = "custom-dict" - SET = "set" - - -def map_pydantic_type_to_gbnf(pydantic_type: type[Any]) -> str: - origin_type = get_origin(pydantic_type) - origin_type = pydantic_type if origin_type is None else origin_type - - if isclass(origin_type) and issubclass(origin_type, str): - return PydanticDataType.STRING.value - elif isclass(origin_type) and issubclass(origin_type, bool): - return PydanticDataType.BOOLEAN.value - elif isclass(origin_type) and issubclass(origin_type, int): - return PydanticDataType.INTEGER.value - elif isclass(origin_type) and issubclass(origin_type, float): - return PydanticDataType.FLOAT.value - elif isclass(origin_type) and issubclass(origin_type, Enum): - return PydanticDataType.ENUM.value - - elif isclass(origin_type) and issubclass(origin_type, BaseModel): - return format_model_and_field_name(origin_type.__name__) - elif origin_type is list: - element_type = get_args(pydantic_type)[0] - return f"{map_pydantic_type_to_gbnf(element_type)}-list" - elif origin_type is set: - element_type = get_args(pydantic_type)[0] - return f"{map_pydantic_type_to_gbnf(element_type)}-set" - elif origin_type is Union: - union_types = get_args(pydantic_type) - union_rules = [map_pydantic_type_to_gbnf(ut) for ut in union_types] - return f"union-{'-or-'.join(union_rules)}" - elif origin_type is Optional: - element_type = get_args(pydantic_type)[0] - return f"optional-{map_pydantic_type_to_gbnf(element_type)}" - elif isclass(origin_type): - return f"{PydanticDataType.CUSTOM_CLASS.value}-{format_model_and_field_name(origin_type.__name__)}" - elif origin_type is dict: - key_type, value_type = get_args(pydantic_type) - return f"custom-dict-key-type-{format_model_and_field_name(map_pydantic_type_to_gbnf(key_type))}-value-type-{format_model_and_field_name(map_pydantic_type_to_gbnf(value_type))}" - else: - return "unknown" - - -def format_model_and_field_name(model_name: str) -> str: - parts = re.findall("[A-Z][^A-Z]*", model_name) - if not parts: # Check if the list is empty - return model_name.lower().replace("_", "-") - return "-".join(part.lower().replace("_", "-") for part in parts) - - -def generate_list_rule(element_type): - """ - Generate a GBNF rule for a list of a given element type. - - :param element_type: The type of the elements in the list (e.g., 'string'). - :return: A string representing the GBNF rule for a list of the given type. - """ - rule_name = f"{map_pydantic_type_to_gbnf(element_type)}-list" - element_rule = map_pydantic_type_to_gbnf(element_type) - list_rule = rf'{rule_name} ::= "[" {element_rule} ("," {element_rule})* "]"' - return list_rule - - -def get_members_structure(cls, rule_name): - if issubclass(cls, Enum): - # Handle Enum types - members = [f'"\\"{member.value}\\""' for name, member in cls.__members__.items()] - return f"{cls.__name__.lower()} ::= " + " | ".join(members) - if cls.__annotations__ and cls.__annotations__ != {}: - result = f'{rule_name} ::= "{{"' - # Modify this comprehension - members = [ - f' "\\"{name}\\"" ":" {map_pydantic_type_to_gbnf(param_type)}' - for name, param_type in get_type_hints(cls).items() - if name != "self" - ] - - result += '"," '.join(members) - result += ' "}"' - return result - if rule_name == "custom-class-any": - result = f"{rule_name} ::= " - result += "value" - return result - - init_signature = inspect.signature(cls.__init__) - parameters = init_signature.parameters - result = f'{rule_name} ::= "{{"' - # Modify this comprehension too - members = [ - f' "\\"{name}\\"" ":" {map_pydantic_type_to_gbnf(param.annotation)}' - for name, param in parameters.items() - if name != "self" and param.annotation != inspect.Parameter.empty - ] - - result += '", "'.join(members) - result += ' "}"' - return result - - -def regex_to_gbnf(regex_pattern: str) -> str: - """ - Translate a basic regex pattern to a GBNF rule. - Note: This function handles only a subset of simple regex patterns. - """ - gbnf_rule = regex_pattern - - # Translate common regex components to GBNF - gbnf_rule = gbnf_rule.replace("\\d", "[0-9]") - gbnf_rule = gbnf_rule.replace("\\s", "[ \t\n]") - - # Handle quantifiers and other regex syntax that is similar in GBNF - # (e.g., '*', '+', '?', character classes) - - return gbnf_rule - - -def generate_gbnf_integer_rules(max_digit=None, min_digit=None): - """ - - Generate GBNF Integer Rules - - Generates GBNF (Generalized Backus-Naur Form) rules for integers based on the given maximum and minimum digits. - - Parameters: - max_digit (int): The maximum number of digits for the integer. Default is None. - min_digit (int): The minimum number of digits for the integer. Default is None. - - Returns: - integer_rule (str): The identifier for the integer rule generated. - additional_rules (list): A list of additional rules generated based on the given maximum and minimum digits. - - """ - additional_rules = [] - - # Define the rule identifier based on max_digit and min_digit - integer_rule = "integer-part" - if max_digit is not None: - integer_rule += f"-max{max_digit}" - if min_digit is not None: - integer_rule += f"-min{min_digit}" - - # Handling Integer Rules - if max_digit is not None or min_digit is not None: - # Start with an empty rule part - integer_rule_part = "" - - # Add mandatory digits as per min_digit - if min_digit is not None: - integer_rule_part += "[0-9] " * min_digit - - # Add optional digits up to max_digit - if max_digit is not None: - optional_digits = max_digit - (min_digit if min_digit is not None else 0) - integer_rule_part += "".join(["[0-9]? " for _ in range(optional_digits)]) - - # Trim the rule part and append it to additional rules - integer_rule_part = integer_rule_part.strip() - if integer_rule_part: - additional_rules.append(f"{integer_rule} ::= {integer_rule_part}") - - return integer_rule, additional_rules - - -def generate_gbnf_float_rules(max_digit=None, min_digit=None, max_precision=None, min_precision=None): - """ - Generate GBNF float rules based on the given constraints. - - :param max_digit: Maximum number of digits in the integer part (default: None) - :param min_digit: Minimum number of digits in the integer part (default: None) - :param max_precision: Maximum number of digits in the fractional part (default: None) - :param min_precision: Minimum number of digits in the fractional part (default: None) - :return: A tuple containing the float rule and additional rules as a list - - Example Usage: - max_digit = 3 - min_digit = 1 - max_precision = 2 - min_precision = 1 - generate_gbnf_float_rules(max_digit, min_digit, max_precision, min_precision) - - Output: - ('float-3-1-2-1', ['integer-part-max3-min1 ::= [0-9] [0-9] [0-9]?', 'fractional-part-max2-min1 ::= [0-9] [0-9]?', 'float-3-1-2-1 ::= integer-part-max3-min1 "." fractional-part-max2-min - *1']) - - Note: - GBNF stands for Generalized Backus-Naur Form, which is a notation technique to specify the syntax of programming languages or other formal grammars. - """ - additional_rules = [] - - # Define the integer part rule - integer_part_rule = ( - "integer-part" - + (f"-max{max_digit}" if max_digit is not None else "") - + (f"-min{min_digit}" if min_digit is not None else "") - ) - - # Define the fractional part rule based on precision constraints - fractional_part_rule = "fractional-part" - fractional_rule_part = "" - if max_precision is not None or min_precision is not None: - fractional_part_rule += (f"-max{max_precision}" if max_precision is not None else "") + ( - f"-min{min_precision}" if min_precision is not None else "" - ) - # Minimum number of digits - fractional_rule_part = "[0-9]" * (min_precision if min_precision is not None else 1) - # Optional additional digits - fractional_rule_part += "".join( - [" [0-9]?"] * ((max_precision - ( - min_precision if min_precision is not None else 1)) if max_precision is not None else 0) - ) - additional_rules.append(f"{fractional_part_rule} ::= {fractional_rule_part}") - - # Define the float rule - float_rule = f"float-{max_digit if max_digit is not None else 'X'}-{min_digit if min_digit is not None else 'X'}-{max_precision if max_precision is not None else 'X'}-{min_precision if min_precision is not None else 'X'}" - additional_rules.append(f'{float_rule} ::= {integer_part_rule} "." {fractional_part_rule}') - - # Generating the integer part rule definition, if necessary - if max_digit is not None or min_digit is not None: - integer_rule_part = "[0-9]" - if min_digit is not None and min_digit > 1: - integer_rule_part += " [0-9]" * (min_digit - 1) - if max_digit is not None: - integer_rule_part += "".join([" [0-9]?"] * (max_digit - (min_digit if min_digit is not None else 1))) - additional_rules.append(f"{integer_part_rule} ::= {integer_rule_part.strip()}") - - return float_rule, additional_rules - - -def generate_gbnf_rule_for_type( - model_name, field_name, field_type, is_optional, processed_models, created_rules, field_info=None -) -> tuple[str, list[str]]: - """ - Generate GBNF rule for a given field type. - - :param model_name: Name of the model. - - :param field_name: Name of the field. - :param field_type: Type of the field. - :param is_optional: Whether the field is optional. - :param processed_models: List of processed models. - :param created_rules: List of created rules. - :param field_info: Additional information about the field (optional). - - :return: Tuple containing the GBNF type and a list of additional rules. - :rtype: tuple[str, list] - """ - rules = [] - - field_name = format_model_and_field_name(field_name) - gbnf_type = map_pydantic_type_to_gbnf(field_type) - - origin_type = get_origin(field_type) - origin_type = field_type if origin_type is None else origin_type - - if isclass(origin_type) and issubclass(origin_type, BaseModel): - nested_model_name = format_model_and_field_name(field_type.__name__) - nested_model_rules, _ = generate_gbnf_grammar(field_type, processed_models, created_rules) - rules.extend(nested_model_rules) - gbnf_type, rules = nested_model_name, rules - elif isclass(origin_type) and issubclass(origin_type, Enum): - enum_values = [f'"\\"{e.value}\\""' for e in field_type] # Adding escaped quotes - enum_rule = f"{model_name}-{field_name} ::= {' | '.join(enum_values)}" - rules.append(enum_rule) - gbnf_type, rules = model_name + "-" + field_name, rules - elif origin_type is list: # Array - element_type = get_args(field_type)[0] - element_rule_name, additional_rules = generate_gbnf_rule_for_type( - model_name, f"{field_name}-element", element_type, is_optional, processed_models, created_rules - ) - rules.extend(additional_rules) - array_rule = f"""{model_name}-{field_name} ::= "[" ws {element_rule_name} ("," ws {element_rule_name})* "]" """ - rules.append(array_rule) - gbnf_type, rules = model_name + "-" + field_name, rules - - elif origin_type is set: # Array - element_type = get_args(field_type)[0] - element_rule_name, additional_rules = generate_gbnf_rule_for_type( - model_name, f"{field_name}-element", element_type, is_optional, processed_models, created_rules - ) - rules.extend(additional_rules) - array_rule = f"""{model_name}-{field_name} ::= "[" ws {element_rule_name} ("," ws {element_rule_name})* "]" """ - rules.append(array_rule) - gbnf_type, rules = model_name + "-" + field_name, rules - - elif gbnf_type.startswith("custom-class-"): - rules.append(get_members_structure(field_type, gbnf_type)) - elif gbnf_type.startswith("custom-dict-"): - key_type, value_type = get_args(field_type) - - additional_key_type, additional_key_rules = generate_gbnf_rule_for_type( - model_name, f"{field_name}-key-type", key_type, is_optional, processed_models, created_rules - ) - additional_value_type, additional_value_rules = generate_gbnf_rule_for_type( - model_name, f"{field_name}-value-type", value_type, is_optional, processed_models, created_rules - ) - gbnf_type = rf'{gbnf_type} ::= "{{" ( {additional_key_type} ": " {additional_value_type} ("," "\n" ws {additional_key_type} ":" {additional_value_type})* )? "}}" ' - - rules.extend(additional_key_rules) - rules.extend(additional_value_rules) - elif gbnf_type.startswith("union-"): - union_types = get_args(field_type) - union_rules = [] - - for union_type in union_types: - if isinstance(union_type, GenericAlias): - union_gbnf_type, union_rules_list = generate_gbnf_rule_for_type( - model_name, field_name, union_type, False, processed_models, created_rules - ) - union_rules.append(union_gbnf_type) - rules.extend(union_rules_list) - - elif not issubclass(union_type, type(None)): - union_gbnf_type, union_rules_list = generate_gbnf_rule_for_type( - model_name, field_name, union_type, False, processed_models, created_rules - ) - union_rules.append(union_gbnf_type) - rules.extend(union_rules_list) - - # Defining the union grammar rule separately - if len(union_rules) == 1: - union_grammar_rule = f"{model_name}-{field_name}-optional ::= {' | '.join(union_rules)} | null" - else: - union_grammar_rule = f"{model_name}-{field_name}-union ::= {' | '.join(union_rules)}" - rules.append(union_grammar_rule) - if len(union_rules) == 1: - gbnf_type = f"{model_name}-{field_name}-optional" - else: - gbnf_type = f"{model_name}-{field_name}-union" - elif isclass(origin_type) and issubclass(origin_type, str): - if field_info and hasattr(field_info, "json_schema_extra") and field_info.json_schema_extra is not None: - triple_quoted_string = field_info.json_schema_extra.get("triple_quoted_string", False) - markdown_string = field_info.json_schema_extra.get("markdown_code_block", False) - - gbnf_type = PydanticDataType.TRIPLE_QUOTED_STRING.value if triple_quoted_string else PydanticDataType.STRING.value - gbnf_type = PydanticDataType.MARKDOWN_CODE_BLOCK.value if markdown_string else gbnf_type - - elif field_info and hasattr(field_info, "pattern"): - # Convert regex pattern to grammar rule - regex_pattern = field_info.regex.pattern - gbnf_type = f"pattern-{field_name} ::= {regex_to_gbnf(regex_pattern)}" - else: - gbnf_type = PydanticDataType.STRING.value - - elif ( - isclass(origin_type) - and issubclass(origin_type, float) - and field_info - and hasattr(field_info, "json_schema_extra") - and field_info.json_schema_extra is not None - ): - # Retrieve precision attributes for floats - max_precision = ( - field_info.json_schema_extra.get("max_precision") if field_info and hasattr(field_info, - "json_schema_extra") else None - ) - min_precision = ( - field_info.json_schema_extra.get("min_precision") if field_info and hasattr(field_info, - "json_schema_extra") else None - ) - max_digits = field_info.json_schema_extra.get("max_digit") if field_info and hasattr(field_info, - "json_schema_extra") else None - min_digits = field_info.json_schema_extra.get("min_digit") if field_info and hasattr(field_info, - "json_schema_extra") else None - - # Generate GBNF rule for float with given attributes - gbnf_type, rules = generate_gbnf_float_rules( - max_digit=max_digits, min_digit=min_digits, max_precision=max_precision, min_precision=min_precision - ) - - elif ( - isclass(origin_type) - and issubclass(origin_type, int) - and field_info - and hasattr(field_info, "json_schema_extra") - and field_info.json_schema_extra is not None - ): - # Retrieve digit attributes for integers - max_digits = field_info.json_schema_extra.get("max_digit") if field_info and hasattr(field_info, - "json_schema_extra") else None - min_digits = field_info.json_schema_extra.get("min_digit") if field_info and hasattr(field_info, - "json_schema_extra") else None - - # Generate GBNF rule for integer with given attributes - gbnf_type, rules = generate_gbnf_integer_rules(max_digit=max_digits, min_digit=min_digits) - else: - gbnf_type, rules = gbnf_type, [] - - return gbnf_type, rules - - -def generate_gbnf_grammar(model: type[BaseModel], processed_models: set[type[BaseModel]], created_rules: dict[str, list[str]]) -> tuple[list[str], bool]: - """ - - Generate GBnF Grammar - - Generates a GBnF grammar for a given model. - - :param model: A Pydantic model class to generate the grammar for. Must be a subclass of BaseModel. - :param processed_models: A set of already processed models to prevent infinite recursion. - :param created_rules: A dict containing already created rules to prevent duplicates. - :return: A list of GBnF grammar rules in string format. And two booleans indicating if an extra markdown or triple quoted string is in the grammar. - Example Usage: - ``` - model = MyModel - processed_models = set() - created_rules = dict() - - gbnf_grammar = generate_gbnf_grammar(model, processed_models, created_rules) - ``` - """ - if model in processed_models: - return [], False - - processed_models.add(model) - model_name = format_model_and_field_name(model.__name__) - - if not issubclass(model, BaseModel): - # For non-Pydantic classes, generate model_fields from __annotations__ or __init__ - if hasattr(model, "__annotations__") and model.__annotations__: - model_fields = {name: (typ, ...) for name, typ in get_type_hints(model).items()} - else: - init_signature = inspect.signature(model.__init__) - parameters = init_signature.parameters - model_fields = {name: (param.annotation, param.default) for name, param in parameters.items() if - name != "self"} - else: - # For Pydantic models, use model_fields and check for ellipsis (required fields) - model_fields = get_type_hints(model) - - model_rule_parts = [] - nested_rules = [] - has_markdown_code_block = False - has_triple_quoted_string = False - look_for_markdown_code_block = False - look_for_triple_quoted_string = False - for field_name, field_info in model_fields.items(): - if not issubclass(model, BaseModel): - field_type, default_value = field_info - # Check if the field is optional (not required) - is_optional = (default_value is not inspect.Parameter.empty) and (default_value is not Ellipsis) - else: - field_type = field_info - field_info = model.model_fields[field_name] - is_optional = field_info.is_required is False and get_origin(field_type) is Optional - rule_name, additional_rules = generate_gbnf_rule_for_type( - model_name, format_model_and_field_name(field_name), field_type, is_optional, processed_models, - created_rules, field_info - ) - look_for_markdown_code_block = True if rule_name == "markdown_code_block" else False - look_for_triple_quoted_string = True if rule_name == "triple_quoted_string" else False - if not look_for_markdown_code_block and not look_for_triple_quoted_string: - if rule_name not in created_rules: - created_rules[rule_name] = additional_rules - model_rule_parts.append(f' ws "\\"{field_name}\\"" ":" ws {rule_name}') # Adding escaped quotes - nested_rules.extend(additional_rules) - else: - has_triple_quoted_string = look_for_triple_quoted_string - has_markdown_code_block = look_for_markdown_code_block - - fields_joined = r' "," "\n" '.join(model_rule_parts) - model_rule = rf'{model_name} ::= "{{" "\n" {fields_joined} "\n" ws "}}"' - - has_special_string = False - if has_triple_quoted_string: - model_rule += '"\\n" ws "}"' - model_rule += '"\\n" triple-quoted-string' - has_special_string = True - if has_markdown_code_block: - model_rule += '"\\n" ws "}"' - model_rule += '"\\n" markdown-code-block' - has_special_string = True - all_rules = [model_rule] + nested_rules - - return all_rules, has_special_string - - -def generate_gbnf_grammar_from_pydantic_models( - models: list[type[BaseModel]], outer_object_name: str | None = None, outer_object_content: str | None = None, - list_of_outputs: bool = False -) -> str: - """ - Generate GBNF Grammar from Pydantic Models. - - This method takes a list of Pydantic models and uses them to generate a GBNF grammar string. The generated grammar string can be used for parsing and validating data using the generated - * grammar. - - Args: - models (list[type[BaseModel]]): A list of Pydantic models to generate the grammar from. - outer_object_name (str): Outer object name for the GBNF grammar. If None, no outer object will be generated. Eg. "function" for function calling. - outer_object_content (str): Content for the outer rule in the GBNF grammar. Eg. "function_parameters" or "params" for function calling. - list_of_outputs (str, optional): Allows a list of output objects - Returns: - str: The generated GBNF grammar string. - - Examples: - models = [UserModel, PostModel] - grammar = generate_gbnf_grammar_from_pydantic(models) - print(grammar) - # Output: - # root ::= UserModel | PostModel - # ... - """ - processed_models: set[type[BaseModel]] = set() - all_rules = [] - created_rules: dict[str, list[str]] = {} - if outer_object_name is None: - for model in models: - model_rules, _ = generate_gbnf_grammar(model, processed_models, created_rules) - all_rules.extend(model_rules) - - if list_of_outputs: - root_rule = r'root ::= (" "| "\n") "[" ws grammar-models ("," ws grammar-models)* ws "]"' + "\n" - else: - root_rule = r'root ::= (" "| "\n") grammar-models' + "\n" - root_rule += "grammar-models ::= " + " | ".join( - [format_model_and_field_name(model.__name__) for model in models]) - all_rules.insert(0, root_rule) - return "\n".join(all_rules) - elif outer_object_name is not None: - if list_of_outputs: - root_rule = ( - rf'root ::= (" "| "\n") "[" ws {format_model_and_field_name(outer_object_name)} ("," ws {format_model_and_field_name(outer_object_name)})* ws "]"' - + "\n" - ) - else: - root_rule = f"root ::= {format_model_and_field_name(outer_object_name)}\n" - - model_rule = ( - rf'{format_model_and_field_name(outer_object_name)} ::= (" "| "\n") "{{" ws "\"{outer_object_name}\"" ":" ws grammar-models' - ) - - fields_joined = " | ".join( - [rf"{format_model_and_field_name(model.__name__)}-grammar-model" for model in models]) - - grammar_model_rules = f"\ngrammar-models ::= {fields_joined}" - mod_rules = [] - for model in models: - mod_rule = rf"{format_model_and_field_name(model.__name__)}-grammar-model ::= " - mod_rule += ( - rf'"\"{model.__name__}\"" "," ws "\"{outer_object_content}\"" ":" ws {format_model_and_field_name(model.__name__)}' + "\n" - ) - mod_rules.append(mod_rule) - grammar_model_rules += "\n" + "\n".join(mod_rules) - - for model in models: - model_rules, has_special_string = generate_gbnf_grammar(model, processed_models, - created_rules) - - if not has_special_string: - model_rules[0] += r'"\n" ws "}"' - - all_rules.extend(model_rules) - - all_rules.insert(0, root_rule + model_rule + grammar_model_rules) - return "\n".join(all_rules) - - -def get_primitive_grammar(grammar): - """ - Returns the needed GBNF primitive grammar for a given GBNF grammar string. - - Args: - grammar (str): The string containing the GBNF grammar. - - Returns: - str: GBNF primitive grammar string. - """ - type_list: list[type[object]] = [] - if "string-list" in grammar: - type_list.append(str) - if "boolean-list" in grammar: - type_list.append(bool) - if "integer-list" in grammar: - type_list.append(int) - if "float-list" in grammar: - type_list.append(float) - additional_grammar = [generate_list_rule(t) for t in type_list] - primitive_grammar = r""" -boolean ::= "true" | "false" -null ::= "null" -string ::= "\"" ( - [^"\\] | - "\\" (["\\/bfnrt] | "u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]) - )* "\"" ws -ws ::= ([ \t\n] ws)? -float ::= ("-"? ([0] | [1-9] [0-9]*)) ("." [0-9]+)? ([eE] [-+]? [0-9]+)? ws - -integer ::= [0-9]+""" - - any_block = "" - if "custom-class-any" in grammar: - any_block = """ -value ::= object | array | string | number | boolean | null - -object ::= - "{" ws ( - string ":" ws value - ("," ws string ":" ws value)* - )? "}" ws - -array ::= - "[" ws ( - value - ("," ws value)* - )? "]" ws - -number ::= integer | float""" - - markdown_code_block_grammar = "" - if "markdown-code-block" in grammar: - markdown_code_block_grammar = r''' -markdown-code-block ::= opening-triple-ticks markdown-code-block-content closing-triple-ticks -markdown-code-block-content ::= ( [^`] | "`" [^`] | "`" "`" [^`] )* -opening-triple-ticks ::= "```" "python" "\n" | "```" "c" "\n" | "```" "cpp" "\n" | "```" "txt" "\n" | "```" "text" "\n" | "```" "json" "\n" | "```" "javascript" "\n" | "```" "css" "\n" | "```" "html" "\n" | "```" "markdown" "\n" -closing-triple-ticks ::= "```" "\n"''' - - if "triple-quoted-string" in grammar: - markdown_code_block_grammar = r""" -triple-quoted-string ::= triple-quotes triple-quoted-string-content triple-quotes -triple-quoted-string-content ::= ( [^'] | "'" [^'] | "'" "'" [^'] )* -triple-quotes ::= "'''" """ - return "\n" + "\n".join(additional_grammar) + any_block + primitive_grammar + markdown_code_block_grammar - - -def generate_markdown_documentation( - pydantic_models: list[type[BaseModel]], model_prefix="Model", fields_prefix="Fields", - documentation_with_field_description=True -) -> str: - """ - Generate markdown documentation for a list of Pydantic models. - - Args: - pydantic_models (list[type[BaseModel]]): list of Pydantic model classes. - model_prefix (str): Prefix for the model section. - fields_prefix (str): Prefix for the fields section. - documentation_with_field_description (bool): Include field descriptions in the documentation. - - Returns: - str: Generated text documentation. - """ - documentation = "" - pyd_models: list[tuple[type[BaseModel], bool]] = [(model, True) for model in pydantic_models] - for model, add_prefix in pyd_models: - if add_prefix: - documentation += f"{model_prefix}: {model.__name__}\n" - else: - documentation += f"Model: {model.__name__}\n" - - # Handling multi-line model description with proper indentation - - class_doc = getdoc(model) - base_class_doc = getdoc(BaseModel) - class_description = class_doc if class_doc and class_doc != base_class_doc else "" - if class_description != "": - documentation += " Description: " - documentation += format_multiline_description(class_description, 0) + "\n" - - if add_prefix: - # Indenting the fields section - documentation += f" {fields_prefix}:\n" - else: - documentation += f" Fields:\n" # noqa: F541 - if isclass(model) and issubclass(model, BaseModel): - for name, field_type in get_type_hints(model).items(): - # if name == "markdown_code_block": - # continue - if get_origin(field_type) == list: - element_type = get_args(field_type)[0] - if isclass(element_type) and issubclass(element_type, BaseModel): - pyd_models.append((element_type, False)) - if get_origin(field_type) == Union: - element_types = get_args(field_type) - for element_type in element_types: - if isclass(element_type) and issubclass(element_type, BaseModel): - pyd_models.append((element_type, False)) - documentation += generate_field_markdown( - name, field_type, model, documentation_with_field_description=documentation_with_field_description - ) - documentation += "\n" - - if hasattr(model, "Config") and hasattr(model.Config, - "json_schema_extra") and "example" in model.Config.json_schema_extra: - documentation += f" Expected Example Output for {format_model_and_field_name(model.__name__)}:\n" - json_example = json.dumps(model.Config.json_schema_extra["example"]) - documentation += format_multiline_description(json_example, 2) + "\n" - - return documentation - - -def generate_field_markdown( - field_name: str, field_type: type[Any], model: type[BaseModel], depth=1, - documentation_with_field_description=True -) -> str: - """ - Generate markdown documentation for a Pydantic model field. - - Args: - field_name (str): Name of the field. - field_type (type[Any]): Type of the field. - model (type[BaseModel]): Pydantic model class. - depth (int): Indentation depth in the documentation. - documentation_with_field_description (bool): Include field descriptions in the documentation. - - Returns: - str: Generated text documentation for the field. - """ - indent = " " * depth - - field_info = model.model_fields.get(field_name) - field_description = field_info.description if field_info and field_info.description else "" - - origin_type = get_origin(field_type) - origin_type = field_type if origin_type is None else origin_type - - if origin_type == list: - element_type = get_args(field_type)[0] - field_text = f"{indent}{field_name} ({format_model_and_field_name(field_type.__name__)} of {format_model_and_field_name(element_type.__name__)})" - if field_description != "": - field_text += ":\n" - else: - field_text += "\n" - elif origin_type == Union: - element_types = get_args(field_type) - types = [] - for element_type in element_types: - types.append(format_model_and_field_name(element_type.__name__)) - field_text = f"{indent}{field_name} ({' or '.join(types)})" - if field_description != "": - field_text += ":\n" - else: - field_text += "\n" - else: - field_text = f"{indent}{field_name} ({format_model_and_field_name(field_type.__name__)})" - if field_description != "": - field_text += ":\n" - else: - field_text += "\n" - - if not documentation_with_field_description: - return field_text - - if field_description != "": - field_text += f" Description: {field_description}\n" - - # Check for and include field-specific examples if available - if hasattr(model, "Config") and hasattr(model.Config, - "json_schema_extra") and "example" in model.Config.json_schema_extra: - field_example = model.Config.json_schema_extra["example"].get(field_name) - if field_example is not None: - example_text = f"'{field_example}'" if isinstance(field_example, str) else field_example - field_text += f"{indent} Example: {example_text}\n" - - if isclass(origin_type) and issubclass(origin_type, BaseModel): - field_text += f"{indent} Details:\n" - for name, type_ in get_type_hints(field_type).items(): - field_text += generate_field_markdown(name, type_, field_type, depth + 2) - - return field_text - - -def format_json_example(example: dict[str, Any], depth: int) -> str: - """ - Format a JSON example into a readable string with indentation. - - Args: - example (dict): JSON example to be formatted. - depth (int): Indentation depth. - - Returns: - str: Formatted JSON example string. - """ - indent = " " * depth - formatted_example = "{\n" - for key, value in example.items(): - value_text = f"'{value}'" if isinstance(value, str) else value - formatted_example += f"{indent}{key}: {value_text},\n" - formatted_example = formatted_example.rstrip(",\n") + "\n" + indent + "}" - return formatted_example - - -def generate_text_documentation( - pydantic_models: list[type[BaseModel]], model_prefix="Model", fields_prefix="Fields", - documentation_with_field_description=True -) -> str: - """ - Generate text documentation for a list of Pydantic models. - - Args: - pydantic_models (list[type[BaseModel]]): List of Pydantic model classes. - model_prefix (str): Prefix for the model section. - fields_prefix (str): Prefix for the fields section. - documentation_with_field_description (bool): Include field descriptions in the documentation. - - Returns: - str: Generated text documentation. - """ - documentation = "" - pyd_models: list[tuple[type[BaseModel], bool]] = [(model, True) for model in pydantic_models] - for model, add_prefix in pyd_models: - if add_prefix: - documentation += f"{model_prefix}: {model.__name__}\n" - else: - documentation += f"Model: {model.__name__}\n" - - # Handling multi-line model description with proper indentation - - class_doc = getdoc(model) - base_class_doc = getdoc(BaseModel) - class_description = class_doc if class_doc and class_doc != base_class_doc else "" - if class_description != "": - documentation += " Description: " - documentation += "\n" + format_multiline_description(class_description, 2) + "\n" - - if isclass(model) and issubclass(model, BaseModel): - documentation_fields = "" - for name, field_type in get_type_hints(model).items(): - # if name == "markdown_code_block": - # continue - if get_origin(field_type) == list: - element_type = get_args(field_type)[0] - if isclass(element_type) and issubclass(element_type, BaseModel): - pyd_models.append((element_type, False)) - if get_origin(field_type) == Union: - element_types = get_args(field_type) - for element_type in element_types: - if isclass(element_type) and issubclass(element_type, BaseModel): - pyd_models.append((element_type, False)) - documentation_fields += generate_field_text( - name, field_type, model, documentation_with_field_description=documentation_with_field_description - ) - if documentation_fields != "": - if add_prefix: - documentation += f" {fields_prefix}:\n{documentation_fields}" - else: - documentation += f" Fields:\n{documentation_fields}" - documentation += "\n" - - if hasattr(model, "Config") and hasattr(model.Config, - "json_schema_extra") and "example" in model.Config.json_schema_extra: - documentation += f" Expected Example Output for {format_model_and_field_name(model.__name__)}:\n" - json_example = json.dumps(model.Config.json_schema_extra["example"]) - documentation += format_multiline_description(json_example, 2) + "\n" - - return documentation - - -def generate_field_text( - field_name: str, field_type: type[Any], model: type[BaseModel], depth=1, - documentation_with_field_description=True -) -> str: - """ - Generate text documentation for a Pydantic model field. - - Args: - field_name (str): Name of the field. - field_type (type[Any]): Type of the field. - model (type[BaseModel]): Pydantic model class. - depth (int): Indentation depth in the documentation. - documentation_with_field_description (bool): Include field descriptions in the documentation. - - Returns: - str: Generated text documentation for the field. - """ - indent = " " * depth - - field_info = model.model_fields.get(field_name) - field_description = field_info.description if field_info and field_info.description else "" - - if get_origin(field_type) == list: - element_type = get_args(field_type)[0] - field_text = f"{indent}{field_name} ({format_model_and_field_name(field_type.__name__)} of {format_model_and_field_name(element_type.__name__)})" - if field_description != "": - field_text += ":\n" - else: - field_text += "\n" - elif get_origin(field_type) == Union: - element_types = get_args(field_type) - types = [] - for element_type in element_types: - types.append(format_model_and_field_name(element_type.__name__)) - field_text = f"{indent}{field_name} ({' or '.join(types)})" - if field_description != "": - field_text += ":\n" - else: - field_text += "\n" - else: - field_text = f"{indent}{field_name} ({format_model_and_field_name(field_type.__name__)})" - if field_description != "": - field_text += ":\n" - else: - field_text += "\n" - - if not documentation_with_field_description: - return field_text - - if field_description != "": - field_text += f"{indent} Description: " + field_description + "\n" - - # Check for and include field-specific examples if available - if hasattr(model, "Config") and hasattr(model.Config, - "json_schema_extra") and "example" in model.Config.json_schema_extra: - field_example = model.Config.json_schema_extra["example"].get(field_name) - if field_example is not None: - example_text = f"'{field_example}'" if isinstance(field_example, str) else field_example - field_text += f"{indent} Example: {example_text}\n" - - if isclass(field_type) and issubclass(field_type, BaseModel): - field_text += f"{indent} Details:\n" - for name, type_ in get_type_hints(field_type).items(): - field_text += generate_field_text(name, type_, field_type, depth + 2) - - return field_text - - -def format_multiline_description(description: str, indent_level: int) -> str: - """ - Format a multiline description with proper indentation. - - Args: - description (str): Multiline description. - indent_level (int): Indentation level. - - Returns: - str: Formatted multiline description. - """ - indent = " " * indent_level - return indent + description.replace("\n", "\n" + indent) - - -def save_gbnf_grammar_and_documentation( - grammar, documentation, grammar_file_path="./grammar.gbnf", documentation_file_path="./grammar_documentation.md" -): - """ - Save GBNF grammar and documentation to specified files. - - Args: - grammar (str): GBNF grammar string. - documentation (str): Documentation string. - grammar_file_path (str): File path to save the GBNF grammar. - documentation_file_path (str): File path to save the documentation. - - Returns: - None - """ - try: - with open(grammar_file_path, "w") as file: - file.write(grammar + get_primitive_grammar(grammar)) - print(f"Grammar successfully saved to {grammar_file_path}") - except IOError as e: - print(f"An error occurred while saving the grammar file: {e}") - - try: - with open(documentation_file_path, "w") as file: - file.write(documentation) - print(f"Documentation successfully saved to {documentation_file_path}") - except IOError as e: - print(f"An error occurred while saving the documentation file: {e}") - - -def remove_empty_lines(string): - """ - Remove empty lines from a string. - - Args: - string (str): Input string. - - Returns: - str: String with empty lines removed. - """ - lines = string.splitlines() - non_empty_lines = [line for line in lines if line.strip() != ""] - string_no_empty_lines = "\n".join(non_empty_lines) - return string_no_empty_lines - - -def generate_and_save_gbnf_grammar_and_documentation( - pydantic_model_list, - grammar_file_path="./generated_grammar.gbnf", - documentation_file_path="./generated_grammar_documentation.md", - outer_object_name: str | None = None, - outer_object_content: str | None = None, - model_prefix: str = "Output Model", - fields_prefix: str = "Output Fields", - list_of_outputs: bool = False, - documentation_with_field_description=True, -): - """ - Generate GBNF grammar and documentation, and save them to specified files. - - Args: - pydantic_model_list: List of Pydantic model classes. - grammar_file_path (str): File path to save the generated GBNF grammar. - documentation_file_path (str): File path to save the generated documentation. - outer_object_name (str): Outer object name for the GBNF grammar. If None, no outer object will be generated. Eg. "function" for function calling. - outer_object_content (str): Content for the outer rule in the GBNF grammar. Eg. "function_parameters" or "params" for function calling. - model_prefix (str): Prefix for the model section in the documentation. - fields_prefix (str): Prefix for the fields section in the documentation. - list_of_outputs (bool): Whether the output is a list of items. - documentation_with_field_description (bool): Include field descriptions in the documentation. - - Returns: - None - """ - documentation = generate_markdown_documentation( - pydantic_model_list, model_prefix, fields_prefix, - documentation_with_field_description=documentation_with_field_description - ) - grammar = generate_gbnf_grammar_from_pydantic_models(pydantic_model_list, outer_object_name, outer_object_content, - list_of_outputs) - grammar = remove_empty_lines(grammar) - save_gbnf_grammar_and_documentation(grammar, documentation, grammar_file_path, documentation_file_path) - - -def generate_gbnf_grammar_and_documentation( - pydantic_model_list, - outer_object_name: str | None = None, - outer_object_content: str | None = None, - model_prefix: str = "Output Model", - fields_prefix: str = "Output Fields", - list_of_outputs: bool = False, - documentation_with_field_description=True, -): - """ - Generate GBNF grammar and documentation for a list of Pydantic models. - - Args: - pydantic_model_list: List of Pydantic model classes. - outer_object_name (str): Outer object name for the GBNF grammar. If None, no outer object will be generated. Eg. "function" for function calling. - outer_object_content (str): Content for the outer rule in the GBNF grammar. Eg. "function_parameters" or "params" for function calling. - model_prefix (str): Prefix for the model section in the documentation. - fields_prefix (str): Prefix for the fields section in the documentation. - list_of_outputs (bool): Whether the output is a list of items. - documentation_with_field_description (bool): Include field descriptions in the documentation. - - Returns: - tuple: GBNF grammar string, documentation string. - """ - documentation = generate_markdown_documentation( - copy(pydantic_model_list), model_prefix, fields_prefix, - documentation_with_field_description=documentation_with_field_description - ) - grammar = generate_gbnf_grammar_from_pydantic_models(pydantic_model_list, outer_object_name, outer_object_content, - list_of_outputs) - grammar = remove_empty_lines(grammar + get_primitive_grammar(grammar)) - return grammar, documentation - - -def generate_gbnf_grammar_and_documentation_from_dictionaries( - dictionaries: list[dict[str, Any]], - outer_object_name: str | None = None, - outer_object_content: str | None = None, - model_prefix: str = "Output Model", - fields_prefix: str = "Output Fields", - list_of_outputs: bool = False, - documentation_with_field_description=True, -): - """ - Generate GBNF grammar and documentation from a list of dictionaries. - - Args: - dictionaries (list[dict]): List of dictionaries representing Pydantic models. - outer_object_name (str): Outer object name for the GBNF grammar. If None, no outer object will be generated. Eg. "function" for function calling. - outer_object_content (str): Content for the outer rule in the GBNF grammar. Eg. "function_parameters" or "params" for function calling. - model_prefix (str): Prefix for the model section in the documentation. - fields_prefix (str): Prefix for the fields section in the documentation. - list_of_outputs (bool): Whether the output is a list of items. - documentation_with_field_description (bool): Include field descriptions in the documentation. - - Returns: - tuple: GBNF grammar string, documentation string. - """ - pydantic_model_list = create_dynamic_models_from_dictionaries(dictionaries) - documentation = generate_markdown_documentation( - copy(pydantic_model_list), model_prefix, fields_prefix, - documentation_with_field_description=documentation_with_field_description - ) - grammar = generate_gbnf_grammar_from_pydantic_models(pydantic_model_list, outer_object_name, outer_object_content, - list_of_outputs) - grammar = remove_empty_lines(grammar + get_primitive_grammar(grammar)) - return grammar, documentation - - -def create_dynamic_model_from_function(func: Callable[..., Any]): - """ - Creates a dynamic Pydantic model from a given function's type hints and adds the function as a 'run' method. - - Args: - func (Callable): A function with type hints from which to create the model. - - Returns: - A dynamic Pydantic model class with the provided function as a 'run' method. - """ - - # Get the signature of the function - sig = inspect.signature(func) - - # Parse the docstring - assert func.__doc__ is not None - docstring = parse(func.__doc__) - - dynamic_fields = {} - param_docs = [] - for param in sig.parameters.values(): - # Exclude 'self' parameter - if param.name == "self": - continue - - # Assert that the parameter has a type annotation - if param.annotation == inspect.Parameter.empty: - raise TypeError(f"""Parameter '{param.name}' in function '{getattr(func, "__name__", "")}' lacks a type annotation""") - - # Find the parameter's description in the docstring - param_doc = next((d for d in docstring.params if d.arg_name == param.name), None) - - # Assert that the parameter has a description - if not param_doc or not param_doc.description: - raise ValueError( - f"""Parameter '{param.name}' in function '{getattr(func, "__name__", "")}' lacks a description in the docstring""") - - # Add parameter details to the schema - param_docs.append((param.name, param_doc)) - if param.default == inspect.Parameter.empty: - default_value = ... - else: - default_value = param.default - dynamic_fields[param.name] = ( - param.annotation if param.annotation != inspect.Parameter.empty else str, default_value) - # Creating the dynamic model - dynamic_model = create_model(f"{getattr(func, '__name__')}", **dynamic_fields) # ty: ignore[no-matching-overload] - - for name, param_doc in param_docs: - dynamic_model.model_fields[name].description = param_doc.description - - dynamic_model.__doc__ = docstring.short_description - - def run_method_wrapper(self): - func_args = {name: getattr(self, name) for name, _ in dynamic_fields.items()} - return func(**func_args) - - # Adding the wrapped function as a 'run' method - setattr(dynamic_model, "run", run_method_wrapper) - return dynamic_model - - -def add_run_method_to_dynamic_model(model: type[BaseModel], func: Callable[..., Any]): - """ - Add a 'run' method to a dynamic Pydantic model, using the provided function. - - Args: - model (type[BaseModel]): Dynamic Pydantic model class. - func (Callable): Function to be added as a 'run' method to the model. - - Returns: - type[BaseModel]: Pydantic model class with the added 'run' method. - """ - - def run_method_wrapper(self): - func_args = {name: getattr(self, name) for name in model.model_fields} - return func(**func_args) - - # Adding the wrapped function as a 'run' method - setattr(model, "run", run_method_wrapper) - - return model - - -def create_dynamic_models_from_dictionaries(dictionaries: list[dict[str, Any]]): - """ - Create a list of dynamic Pydantic model classes from a list of dictionaries. - - Args: - dictionaries (list[dict]): List of dictionaries representing model structures. - - Returns: - list[type[BaseModel]]: List of generated dynamic Pydantic model classes. - """ - dynamic_models = [] - for func in dictionaries: - model_name = format_model_and_field_name(func.get("name", "")) - dyn_model = convert_dictionary_to_pydantic_model(func, model_name) - dynamic_models.append(dyn_model) - return dynamic_models - - -def map_grammar_names_to_pydantic_model_class(pydantic_model_list): - output = {} - for model in pydantic_model_list: - output[format_model_and_field_name(model.__name__)] = model - - return output - - -def json_schema_to_python_types(schema): - type_map = { - "any": Any, - "string": str, - "number": float, - "integer": int, - "boolean": bool, - "array": list, - } - return type_map[schema] - - -def list_to_enum(enum_name, values): - return Enum(enum_name, {value: value for value in values}) - - -def convert_dictionary_to_pydantic_model(dictionary: dict[str, Any], model_name: str = "CustomModel") -> type[Any]: - """ - Convert a dictionary to a Pydantic model class. - - Args: - dictionary (dict): Dictionary representing the model structure. - model_name (str): Name of the generated Pydantic model. - - Returns: - type[BaseModel]: Generated Pydantic model class. - """ - fields: dict[str, Any] = {} - - if "properties" in dictionary: - for field_name, field_data in dictionary.get("properties", {}).items(): - if field_data == "object": - submodel = convert_dictionary_to_pydantic_model(dictionary, f"{model_name}_{field_name}") - fields[field_name] = (submodel, ...) - else: - field_type = field_data.get("type", "str") - - if field_data.get("enum", []): - fields[field_name] = (list_to_enum(field_name, field_data.get("enum", [])), ...) - elif field_type == "array": - items = field_data.get("items", {}) - if items != {}: - array = {"properties": items} - array_type = convert_dictionary_to_pydantic_model(array, f"{model_name}_{field_name}_items") - fields[field_name] = (list[array_type], ...) - else: - fields[field_name] = (list, ...) - elif field_type == "object": - submodel = convert_dictionary_to_pydantic_model(field_data, f"{model_name}_{field_name}") - fields[field_name] = (submodel, ...) - elif field_type == "required": - required = field_data.get("enum", []) - for key, field in fields.items(): - if key not in required: - optional_type = fields[key][0] - fields[key] = (Optional[optional_type], ...) - else: - field_type = json_schema_to_python_types(field_type) - fields[field_name] = (field_type, ...) - if "function" in dictionary: - for field_name, field_data in dictionary.get("function", {}).items(): - if field_name == "name": - model_name = field_data - elif field_name == "description": - fields["__doc__"] = field_data - elif field_name == "parameters": - return convert_dictionary_to_pydantic_model(field_data, f"{model_name}") - - if "parameters" in dictionary: - field_data = {"function": dictionary} - return convert_dictionary_to_pydantic_model(field_data, f"{model_name}") - if "required" in dictionary: - required = dictionary.get("required", []) - for key, field in fields.items(): - if key not in required: - optional_type = fields[key][0] - fields[key] = (Optional[optional_type], ...) - custom_model = create_model(model_name, **fields) - return custom_model diff --git a/examples/pydantic_models_to_grammar_examples.py b/examples/pydantic_models_to_grammar_examples.py deleted file mode 100755 index 35905fb97262..000000000000 --- a/examples/pydantic_models_to_grammar_examples.py +++ /dev/null @@ -1,312 +0,0 @@ -#!/usr/bin/env python3 - -"""Function calling example using pydantic models.""" - -from __future__ import annotations - -import argparse -import datetime -import json -import logging -import textwrap -import sys -from enum import Enum -from typing import Optional, Union - -import requests -from pydantic import BaseModel, Field -from pydantic_models_to_grammar import (add_run_method_to_dynamic_model, convert_dictionary_to_pydantic_model, - create_dynamic_model_from_function, generate_gbnf_grammar_and_documentation) - - -def create_completion(host, prompt, gbnf_grammar): - """Calls the /completion API on llama-server. - - See - https://github.com/ggml-org/llama.cpp/tree/HEAD/tools/server#api-endpoints - """ - print(f" Request:\n Grammar:\n{textwrap.indent(gbnf_grammar, ' ')}\n Prompt:\n{textwrap.indent(prompt.rstrip(), ' ')}") - headers = {"Content-Type": "application/json"} - data = {"prompt": prompt, "grammar": gbnf_grammar} - result = requests.post(f"http://{host}/completion", headers=headers, json=data).json() - assert data.get("error") is None, data - logging.info("Result: %s", result) - content = result["content"] - print(f" Model: {result['model']}") - print(f" Result:\n{textwrap.indent(json.dumps(json.loads(content), indent=2), ' ')}") - return content - - -# A function for the agent to send a message to the user. -class SendMessageToUser(BaseModel): - """Send a message to the User.""" - chain_of_thought: str = Field(..., description="Your chain of thought while sending the message.") - message: str = Field(..., description="Message you want to send to the user.") - - def run(self): - print(f"SendMessageToUser: {self.message}") - - -def example_rce(host): - """Minimal test case where the LLM call an arbitrary python function.""" - print("- example_rce") - tools = [SendMessageToUser] - gbnf_grammar, documentation = generate_gbnf_grammar_and_documentation( - pydantic_model_list=tools, outer_object_name="function", - outer_object_content="function_parameters", model_prefix="Function", fields_prefix="Parameters") - system_message = "You are an advanced AI, tasked to assist the user by calling functions in JSON format. The following are the available functions and their parameters and types:\n\n" + documentation - user_message = "What is 42 * 42?" - prompt = f"<|im_start|>system\n{system_message}<|im_end|>\n<|im_start|>user\n{user_message}<|im_end|>\n<|im_start|>assistant" - text = create_completion(host, prompt, gbnf_grammar) - json_data = json.loads(text) - tools_map = {tool.__name__:tool for tool in tools} - # This finds "SendMessageToUser": - tool = tools_map.get(json_data["function"]) - if not tool: - print(f"Error: unknown tool {json_data['function']}") - return 1 - tool(**json_data["function_parameters"]).run() - return 0 - - -# Enum for the calculator tool. -class MathOperation(Enum): - ADD = "add" - SUBTRACT = "subtract" - MULTIPLY = "multiply" - DIVIDE = "divide" - - -# Simple pydantic calculator tool for the agent that can add, subtract, -# multiply, and divide. Docstring and description of fields will be used in -# system prompt. -class Calculator(BaseModel): - """Perform a math operation on two numbers.""" - number_one: Union[int, float] = Field(..., description="First number.") - operation: MathOperation = Field(..., description="Math operation to perform.") - number_two: Union[int, float] = Field(..., description="Second number.") - - def run(self): - if self.operation == MathOperation.ADD: - return self.number_one + self.number_two - elif self.operation == MathOperation.SUBTRACT: - return self.number_one - self.number_two - elif self.operation == MathOperation.MULTIPLY: - return self.number_one * self.number_two - elif self.operation == MathOperation.DIVIDE: - return self.number_one / self.number_two - else: - raise ValueError("Unknown operation.") - - -def example_calculator(host): - """Have the LLM ask to get a calculation done. - - Here the grammar gets generated by passing the available function models to - generate_gbnf_grammar_and_documentation function. This also generates a - documentation usable by the LLM. - - pydantic_model_list is the list of pydantic models outer_object_name is an - optional name for an outer object around the actual model object. Like a - "function" object with "function_parameters" which contains the actual model - object. If None, no outer object will be generated outer_object_content is - the name of outer object content. - - model_prefix is the optional prefix for models in the documentation. (Default="Output Model") - fields_prefix is the prefix for the model fields in the documentation. (Default="Output Fields") - """ - print("- example_calculator") - tools = [SendMessageToUser, Calculator] - gbnf_grammar, documentation = generate_gbnf_grammar_and_documentation( - pydantic_model_list=tools, outer_object_name="function", - outer_object_content="function_parameters", model_prefix="Function", fields_prefix="Parameters") - system_message = "You are an advanced AI, tasked to assist the user by calling functions in JSON format. The following are the available functions and their parameters and types:\n\n" + documentation - user_message1 = "What is 42 * 42?" - prompt = f"<|im_start|>system\n{system_message}<|im_end|>\n<|im_start|>user\n{user_message1}<|im_end|>\n<|im_start|>assistant" - text = create_completion(host, prompt, gbnf_grammar) - json_data = json.loads(text) - expected = { - "function": "Calculator", - "function_parameters": { - "number_one": 42, - "operation": "multiply", - "number_two": 42 - } - } - if json_data != expected: - print(" Result is not as expected!") - tools_map = {tool.__name__:tool for tool in tools} - # This finds "Calculator": - tool = tools_map.get(json_data["function"]) - if not tool: - print(f"Error: unknown tool {json_data['function']}") - return 1 - result = tool(**json_data["function_parameters"]).run() - print(f" Call {json_data['function']} gave result {result}") - return 0 - - -class Category(Enum): - """The category of the book.""" - Fiction = "Fiction" - NonFiction = "Non-Fiction" - - -class Book(BaseModel): - """Represents an entry about a book.""" - title: str = Field(..., description="Title of the book.") - author: str = Field(..., description="Author of the book.") - published_year: Optional[int] = Field(..., description="Publishing year of the book.") - keywords: list[str] = Field(..., description="A list of keywords.") - category: Category = Field(..., description="Category of the book.") - summary: str = Field(..., description="Summary of the book.") - - -def example_struct(host): - """A example structured output based on pydantic models. - - The LLM will create an entry for a Book database out of an unstructured - text. We need no additional parameters other than our list of pydantic - models. - """ - print("- example_struct") - tools = [Book] - gbnf_grammar, documentation = generate_gbnf_grammar_and_documentation(pydantic_model_list=tools) - system_message = "You are an advanced AI, tasked to create a dataset entry in JSON for a Book. The following is the expected output model:\n\n" + documentation - text = """The Feynman Lectures on Physics is a physics textbook based on some lectures by Richard Feynman, a Nobel laureate who has sometimes been called "The Great Explainer". The lectures were presented before undergraduate students at the California Institute of Technology (Caltech), during 1961–1963. The book's co-authors are Feynman, Robert B. Leighton, and Matthew Sands.""" - prompt = f"<|im_start|>system\n{system_message}<|im_end|>\n<|im_start|>user\n{text}<|im_end|>\n<|im_start|>assistant" - text = create_completion(host, prompt, gbnf_grammar) - json_data = json.loads(text) - # In this case, there's no function nor function_parameters. - # Here the result will vary based on the LLM used. - keys = sorted(["title", "author", "published_year", "keywords", "category", "summary"]) - if keys != sorted(json_data.keys()): - print(f"Unexpected result: {sorted(json_data.keys())}") - return 1 - book = Book(**json_data) - print(f" As a Book object: %s" % book) - return 0 - - -def get_current_datetime(output_format: Optional[str] = None): - """Get the current date and time in the given format. - - Args: - output_format: formatting string for the date and time, defaults to '%Y-%m-%d %H:%M:%S' - """ - return datetime.datetime.now().strftime(output_format or "%Y-%m-%d %H:%M:%S") - - -# Example function to get the weather. -def get_current_weather(location, unit): - """Get the current weather in a given location""" - if "London" in location: - return json.dumps({"location": "London", "temperature": "42", "unit": unit.value}) - elif "New York" in location: - return json.dumps({"location": "New York", "temperature": "24", "unit": unit.value}) - elif "North Pole" in location: - return json.dumps({"location": "North Pole", "temperature": "-42", "unit": unit.value}) - return json.dumps({"location": location, "temperature": "unknown"}) - - -def example_concurrent(host): - """An example for parallel function calling with a Python function, a pydantic - function model and an OpenAI like function definition. - """ - print("- example_concurrent") - # Function definition in OpenAI style. - current_weather_tool = { - "type": "function", - "function": { - "name": "get_current_weather", - "description": "Get the current weather in a given location", - "parameters": { - "type": "object", - "properties": { - "location": { - "type": "string", - "description": "The city and state, e.g. San Francisco, CA", - }, - "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, - }, - "required": ["location"], - }, - }, - } - # Convert OpenAI function definition into pydantic model. - current_weather_tool_model = convert_dictionary_to_pydantic_model(current_weather_tool) - # Add the actual function to a pydantic model. - current_weather_tool_model = add_run_method_to_dynamic_model(current_weather_tool_model, get_current_weather) - - # Convert normal Python function to a pydantic model. - current_datetime_model = create_dynamic_model_from_function(get_current_datetime) - - tools = [SendMessageToUser, Calculator, current_datetime_model, current_weather_tool_model] - gbnf_grammar, documentation = generate_gbnf_grammar_and_documentation( - pydantic_model_list=tools, outer_object_name="function", - outer_object_content="params", model_prefix="Function", fields_prefix="Parameters", list_of_outputs=True) - system_message = "You are an advanced AI assistant. You are interacting with the user and with your environment by calling functions. You call functions by writing JSON objects, which represent specific function calls.\nBelow is a list of your available function calls:\n\n" + documentation - text = """Get the date and time, get the current weather in celsius in London and solve the following calculation: 42 * 42""" - prompt = f"<|im_start|>system\n{system_message}<|im_end|>\n<|im_start|>user\n{text}<|im_end|>\n<|im_start|>assistant" - text = create_completion(host, prompt, gbnf_grammar) - json_data = json.loads(text) - expected = [ - { - "function": "get_current_datetime", - "params": { - "output_format": "%Y-%m-%d %H:%M:%S" - } - }, - { - "function": "get_current_weather", - "params": { - "location": "London", - "unit": "celsius" - } - }, - { - "function": "Calculator", - "params": { - "number_one": 42, - "operation": "multiply", - "number_two": 42 - } - } - ] - res = 0 - if json_data != expected: - print(" Result is not as expected!") - print(" This can happen on highly quantized models") - res = 1 - tools_map = {tool.__name__:tool for tool in tools} - for call in json_data: - tool = tools_map.get(call["function"]) - if not tool: - print(f"Error: unknown tool {call['function']}") - return 1 - result = tool(**call["params"]).run() - print(f" Call {call['function']} returned {result}") - # Should output something like this: - # Call get_current_datetime returned 2024-07-15 09:50:38 - # Call get_current_weather returned {"location": "London", "temperature": "42", "unit": "celsius"} - # Call Calculator returned 1764 - return res - - -def main(): - parser = argparse.ArgumentParser(description=sys.modules[__name__].__doc__) - parser.add_argument("--host", default="localhost:9931", help="llama.cpp server") - parser.add_argument("-v", "--verbose", action="store_true", help="enables logging") - args = parser.parse_args() - logging.basicConfig(level=logging.INFO if args.verbose else logging.ERROR) - ret = 0 - # Comment out below to only run the example you want. - ret = ret or example_rce(args.host) - ret = ret or example_calculator(args.host) - ret = ret or example_struct(args.host) - ret = ret or example_concurrent(args.host) - return ret - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/examples/realtime_client.py b/examples/realtime_client.py deleted file mode 100644 index 3b806fab3d0e..000000000000 --- a/examples/realtime_client.py +++ /dev/null @@ -1,211 +0,0 @@ -#!/usr/bin/env python3 -"""Example client for the llama-server /v1/realtime websocket, with the openai SDK. - -Start a server with an audio model, e.g. LFM3-Audio: - - llama-server -hf LiquidAI/LFM3-Audio-2B-GGUF - -Spoken conversation, the audio of each wav file is one user turn. It is sent in chunks as it would come from a -microphone, the server prefills it as it arrives so the response starts right after the last chunk: - - python examples/realtime_client.py --instructions "Respond with interleaved text and audio." question.wav - -Output modalities: left out, the model picks; "text", "audio" or "text,audio" (interleaved) force the response. -Without --instructions, a forced mode comes with the system prompt of the LFM3-Audio or LFM3-Omni model card: - - python examples/realtime_client.py --output-modalities text,audio --out answer.wav question.wav - -Tool calls: --tools gives the conversation a demo tool, the client runs its calls and sends the results back: - - python examples/realtime_client.py --tools --text "Set the volume to 30." - -Text turns go in with --text, transcription sessions transcribe each file: - - python examples/realtime_client.py --text "What is the capital of France?" - python examples/realtime_client.py --type transcription --language en speech.wav - -Live transcription models (Voxtral Realtime, LFM3-Audio live ASR) transcribe while the audio is sent, a transcription -session opens with ?intent=transcription: - - python examples/realtime_client.py --type transcription speech.wav - -Requirements: pip install "openai[realtime]" numpy -""" - -import argparse -import asyncio -import base64 -import json -import time -import wave - -import numpy as np -from openai import AsyncOpenAI - - -# system prompts of the LiquidAI/LFM3-Audio-2B and LiquidAI/LFM3-Omni-2B model cards for a forced output mode -MODE_INSTRUCTIONS = { - "audio": {"text,audio": "Respond with interleaved text and audio."}, - "omni": {"text": "Respond in text.", "text,audio": "Respond in interleaved text and audio."}, -} -# and with tools: calls, or an answer in interleaved text and speech -TOOLS_INSTRUCTIONS = "Respond with function calls, and interleaved text and audio.\n\nList of tools:" - -# the demo tool of --tools -DEMO_TOOLS = [{ - "type": "function", - "name": "set_volume", - "description": "Set the device speaker volume.", - "parameters": { - "type": "object", - "properties": {"volume": {"type": "integer", "description": "Volume from 0 to 100."}}, - "required": ["volume"], - }, -}] - - -def run_tool(name, arguments): - if name == "set_volume": - return {"volume": json.loads(arguments)["volume"]} - return {"error": f"unknown tool {name}"} - - -def read_wav(path, rate): - # PCM16 wav -> mono int16 at the given rate - with wave.open(path, "rb") as f: - assert f.getsampwidth() == 2, "the example reads PCM16 wav files" - x = np.frombuffer(f.readframes(f.getnframes()), dtype=np.int16).astype(np.float32) - x = x.reshape(-1, f.getnchannels()).mean(axis=1) - sr = f.getframerate() - if sr != rate: - n = int(round(len(x) * rate / sr)) - x = np.interp(np.arange(n) * sr / rate, np.arange(len(x)), x) - return np.clip(x, -32768, 32767).astype(np.int16) - - -def write_wav(path, pcm, rate): - with wave.open(path, "wb") as f: - f.setnchannels(1) - f.setsampwidth(2) - f.setframerate(rate) - f.writeframes(pcm.tobytes()) - - -async def main(args): - # the SDK derives a wss:// URL from base_url, a plain http server needs ws:// - client = AsyncOpenAI(base_url=args.url, api_key=args.api_key, websocket_base_url=args.url.replace("http", "ws", 1)) - query = {"intent": "transcription"} if args.type == "transcription" else {} - async with client.realtime.connect(model=args.model, extra_query=query) as conn: - ev = await conn.recv() - if ev.type == "error": - print("error:", ev.error.message) - return - # the audio goes in at the rate of the model, PCM16 mono - session_info = ev.model_dump(warnings=False)["session"] - audio_fmt = session_info["audio"] - card = "omni" if "omni" in str(session_info.get("model", "")).lower() else "audio" - in_rate = audio_fmt["input"]["format"]["rate"] - out_rate = (audio_fmt.get("output") or {}).get("format", {}).get("rate", 24000) - - session = {"type": args.type} - if args.type == "realtime": - instructions = args.instructions - if instructions is None: - instructions = TOOLS_INSTRUCTIONS if args.tools else MODE_INSTRUCTIONS[card].get(args.output_modalities) - if args.tools: - session["tools"] = DEMO_TOOLS - if instructions is not None: - session["instructions"] = instructions - if args.output_modalities: - session["output_modalities"] = args.output_modalities.split(",") - elif args.language: - session["audio"] = {"input": {"transcription": {"language": args.language}}} - await conn.session.update(session=session) # ty: ignore[invalid-argument-type] - ev = await conn.recv() - if ev.type == "error": - print("error:", ev.error.message) - return - - turns = [("audio", path) for path in args.wav] + [("text", text) for text in args.text] - for i, (kind, src) in enumerate(turns): - t_last = 0.0 - - # the input is sent while the events are read: live transcription arrives while the audio is sent - async def send_turn(): - nonlocal t_last - if kind == "audio": - pcm = read_wav(src, in_rate) - step = in_rate * args.chunk_ms // 1000 - for j in range(0, len(pcm), step): - chunk = pcm[j:j + step] - await conn.input_audio_buffer.append(audio=base64.b64encode(chunk.tobytes()).decode()) - if args.realtime: - await asyncio.sleep(len(chunk) / in_rate) - if args.type == "transcription": - # "final" ends the input, models that transcribe with a delay then complete the last item - await conn.send({"type": "input_audio_buffer.commit", "final": i == len(args.wav) - 1}) # ty: ignore[invalid-argument-type] - else: - await conn.conversation.item.create(item={ - "type": "message", "role": "user", "content": [{"type": "input_text", "text": src}]}) - if args.type == "realtime": - # the audio not committed yet ends the user turn - await conn.response.create() - t_last = time.perf_counter() - - print(f"--- turn {i} ({kind}: {src})") - sender = asyncio.create_task(send_turn()) - t_first = None - audio = [] - async for ev in conn: - if ev.type == "response.output_text.delta" or ev.type == "conversation.item.input_audio_transcription.delta": - t_first = t_first or time.perf_counter() - print(ev.delta, end="", flush=True) - elif ev.type == "response.output_audio.delta": - t_first = t_first or time.perf_counter() - audio.append(np.frombuffer(base64.b64decode(ev.delta), dtype=np.int16)) - elif ev.type == "response.done": - # the calls of the response are run, their results go back and the model answers them - calls = [o for o in ev.model_dump()["response"]["output"] if o["type"] == "function_call"] - for call in calls: - result = json.dumps(run_tool(call["name"], call["arguments"])) - print(f"\n[call {call['name']}({call['arguments']}) -> {result}]", flush=True) - await conn.conversation.item.create(item={ - "type": "function_call_output", "call_id": call["call_id"], "output": result}) - if not calls: - break - await conn.response.create() - elif ev.type == "conversation.item.input_audio_transcription.completed": - break - elif ev.type == "error": - print("\nerror:", ev.error.message) - return - await sender - print() - if t_first is not None and t_first > t_last: - print(f"first output {1000 * (t_first - t_last):.0f} ms after the end of the input") - elif t_first is not None: - print(f"output started {1000 * (t_last - t_first):.0f} ms before the end of the input, " - f"done {1000 * (time.perf_counter() - t_last):.0f} ms after it") - if audio: - pcm_out = np.concatenate(audio) - path = f"{args.out.removesuffix('.wav')}_{i}.wav" if len(turns) > 1 else args.out - write_wav(path, pcm_out, out_rate) - print(f"audio: {len(pcm_out) / out_rate:.2f} s -> {path}") - - -if __name__ == "__main__": - p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - p.add_argument("wav", nargs="*", help="PCM16 wav files, one user turn each") - p.add_argument("--text", action="append", default=[], help="a user turn as text, after the audio turns, repeatable") - p.add_argument("--type", choices=["realtime", "transcription"], default="realtime", help="session type") - p.add_argument("--instructions", help="system prompt of the conversation") - p.add_argument("--tools", action="store_true", help="give the conversation a demo tool (set_volume), its calls are run") - p.add_argument("--output-modalities", choices=["text", "audio", "text,audio"], help="default: the model picks") - p.add_argument("--language", help="transcription language, e.g. en") - p.add_argument("--chunk-ms", type=int, default=100, help="audio chunk size") - p.add_argument("--realtime", action=argparse.BooleanOptionalAction, default=True, help="send the audio in real time") - p.add_argument("--out", default="response.wav", help="where the audio of the responses goes") - p.add_argument("--url", default="http://127.0.0.1:9931/v1") - p.add_argument("--api-key", default="none") - p.add_argument("--model", default="default", help="model name, used by the router") - asyncio.run(main(p.parse_args())) diff --git a/examples/reason-act.sh b/examples/reason-act.sh deleted file mode 100755 index 3c801920d019..000000000000 --- a/examples/reason-act.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env bash - -cd `dirname $0` -cd .. - -# get -m model parameter otherwise defer to default -if [ "$1" == "-m" ]; then - MODEL="-m $2 " -fi - -./llama-cli $MODEL --color \ - -f ./prompts/reason-act.txt \ - -i --interactive-first \ - --top_k 10000 --temp 0.2 --repeat_penalty 1 -t 7 -c 2048 \ - -r "Question:" -r "Observation:" --in-prefix " " \ - -n -1 diff --git a/examples/server-llama2-13B.sh b/examples/server-llama2-13B.sh deleted file mode 100755 index fd5a575886f0..000000000000 --- a/examples/server-llama2-13B.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env bash - -set -e - -cd "$(dirname "$0")/.." || exit - -# Specify the model you want to use here: -MODEL="${MODEL:-./models/llama-2-13b-chat.ggmlv3.q5_K_M.bin}" -PROMPT_TEMPLATE=${PROMPT_TEMPLATE:-./prompts/chat-system.txt} - -# Adjust to the number of CPU cores you want to use. -N_THREAD="${N_THREAD:-12}" - -# Note: you can also override the generation options by specifying them on the command line: -GEN_OPTIONS="${GEN_OPTIONS:---ctx_size 4096 --batch-size 1024}" - - -# shellcheck disable=SC2086 # Intended splitting of GEN_OPTIONS -./llama-server $GEN_OPTIONS \ - --model "$MODEL" \ - --threads "$N_THREAD" \ - --rope-freq-scale 1.0 \ - "$@" - -# I used this to test the model with mps, but omitted it from the general purpose. If you want to use it, just specify it on the command line. -# -ngl 1 \ diff --git a/examples/server_embd.py b/examples/server_embd.py deleted file mode 100644 index f8b0ffecd8f4..000000000000 --- a/examples/server_embd.py +++ /dev/null @@ -1,35 +0,0 @@ -import asyncio -import asyncio.threads -import requests -import numpy as np - - -n = 8 - -result = [] - -async def requests_post_async(*args, **kwargs): - return await asyncio.threads.to_thread(requests.post, *args, **kwargs) - -async def main(): - model_url = "http://127.0.0.1:6900" - responses: list[requests.Response] = await asyncio.gather(*[requests_post_async( - url= f"{model_url}/embedding", - json= {"content": "a "*1022} - ) for i in range(n)]) - - for response in responses: - embedding = response.json()["embedding"] - print(embedding[-8:]) - result.append(embedding) - -asyncio.run(main()) - -# compute cosine similarity - -for i in range(n-1): - for j in range(i+1, n): - embedding1 = np.array(result[i]) - embedding2 = np.array(result[j]) - similarity = np.dot(embedding1, embedding2) / (np.linalg.norm(embedding1) * np.linalg.norm(embedding2)) - print(f"Similarity between {i} and {j}: {similarity:.2f}") diff --git a/examples/test-cmake/CMakeLists.txt b/examples/test-cmake/CMakeLists.txt index 6ceb3359e526..340707ee7064 100644 --- a/examples/test-cmake/CMakeLists.txt +++ b/examples/test-cmake/CMakeLists.txt @@ -8,7 +8,7 @@ option(LLAMA_TEST_USE_SUBDIR "Use add_subdirectory instead of find_package" OFF) if(LLAMA_TEST_USE_SUBDIR) add_subdirectory(../../ llama.cpp) else() - find_package(llama 0.1.0 REQUIRED) + find_package(llama CONFIG REQUIRED PATHS ${CMAKE_PREFIX_PATH} NO_DEFAULT_PATH) endif() add_executable(test-cmake test-cmake.cpp) diff --git a/ggml/CMakeLists.txt b/ggml/CMakeLists.txt index 9b6b8b6baf43..b1018cbbb56e 100644 --- a/ggml/CMakeLists.txt +++ b/ggml/CMakeLists.txt @@ -3,8 +3,8 @@ cmake_minimum_required(VERSION 3.14...3.28) # for add_link_options and implicit project("ggml" C CXX ASM) ### GGML Version -set(GGML_VERSION_MAJOR 0) -set(GGML_VERSION_MINOR 29) +set(GGML_VERSION_MAJOR 1) +set(GGML_VERSION_MINOR 0) set(GGML_VERSION_PATCH 0) set(GGML_VERSION_BASE "${GGML_VERSION_MAJOR}.${GGML_VERSION_MINOR}.${GGML_VERSION_PATCH}") diff --git a/ggml/src/ggml-cann/ggml-cann.cpp b/ggml/src/ggml-cann/ggml-cann.cpp index 0bfb960095c5..7e692f1b545f 100644 --- a/ggml/src/ggml-cann/ggml-cann.cpp +++ b/ggml/src/ggml-cann/ggml-cann.cpp @@ -2601,6 +2601,9 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten } case GGML_OP_SUM: return ggml_is_contiguous_rows(op->src[0]); + case GGML_OP_RMS_NORM: + // the cached gamma of ones does not track its type, so F32 and BF16 can not share it + return op->src[0]->type != GGML_TYPE_BF16; case GGML_OP_L2_NORM: case GGML_OP_CROSS_ENTROPY_LOSS: case GGML_OP_DUP: @@ -2617,7 +2620,6 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten case GGML_OP_SUB: case GGML_OP_MUL: case GGML_OP_DIV: - case GGML_OP_RMS_NORM: case GGML_OP_SQR: case GGML_OP_SQRT: case GGML_OP_CLAMP: diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index eed5d69e3c19..7c2542741fb3 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -4144,6 +4144,50 @@ static void ggml_compute_forward_rms_norm_f32( } } +static void ggml_compute_forward_rms_norm_bf16( + const ggml_compute_params * params, + ggml_tensor * dst) { + + const ggml_tensor * src0 = dst->src[0]; + + GGML_ASSERT(ggml_are_same_shape(src0, dst)); + GGML_ASSERT(src0->nb[0] == sizeof(ggml_bf16_t)); + + const int ith = params->ith; + const int nth = params->nth; + + GGML_TENSOR_UNARY_OP_LOCALS + + float eps; + memcpy(&eps, dst->op_params, sizeof(float)); + GGML_ASSERT(eps >= 0.0f); + + for (int64_t i03 = 0; i03 < ne03; i03++) { + for (int64_t i02 = 0; i02 < ne02; i02++) { + for (int64_t i01 = ith; i01 < ne01; i01 += nth) { + const ggml_bf16_t * x = (ggml_bf16_t *) ((char *) src0->data + i01*nb01 + i02*nb02 + i03*nb03); + ggml_bf16_t * y = (ggml_bf16_t *) ((char *) dst->data + i01*nb1 + i02*nb2 + i03*nb3); + + ggml_float sum = 0.0; + for (int64_t i00 = 0; i00 < ne00; i00++) { + const float v = GGML_BF16_TO_FP32(x[i00]); + sum += (ggml_float)(v*v); + } + + const float mean = sum/ne00; + const float scale = 1.0f/sqrtf(mean + eps); + + // if you hit this, likely you got an inf somewhere earlier + assert(scale > 0.0f); + + for (int64_t i00 = 0; i00 < ne00; i00++) { + y[i00] = GGML_FP32_TO_BF16(GGML_BF16_TO_FP32(x[i00])*scale); + } + } + } + } +} + void ggml_compute_forward_rms_norm( const ggml_compute_params * params, ggml_tensor * dst) { @@ -4155,6 +4199,10 @@ void ggml_compute_forward_rms_norm( { ggml_compute_forward_rms_norm_f32(params, dst); } break; + case GGML_TYPE_BF16: + { + ggml_compute_forward_rms_norm_bf16(params, dst); + } break; default: { GGML_ABORT("fatal error"); diff --git a/ggml/src/ggml-cpu/spacemit/ime.cpp b/ggml/src/ggml-cpu/spacemit/ime.cpp index dc51ad0aa4dd..0794c115de47 100644 --- a/ggml/src/ggml-cpu/spacemit/ime.cpp +++ b/ggml/src/ggml-cpu/spacemit/ime.cpp @@ -995,7 +995,8 @@ class tensor_traits_common : public tensor_traits_base { spacemit_kernels::rvv::forward_rms_norm_f32(params, op); return true; default: - GGML_ABORT("fatal error"); + ggml_compute_forward_rms_norm(params, op); + return true; } case GGML_OP_ADD: switch (op->src[0]->type) { diff --git a/ggml/src/ggml-cuda/CMakeLists.txt b/ggml/src/ggml-cuda/CMakeLists.txt index dce8827ae8f1..211a8dac7ac5 100644 --- a/ggml/src/ggml-cuda/CMakeLists.txt +++ b/ggml/src/ggml-cuda/CMakeLists.txt @@ -29,6 +29,7 @@ if (CUDAToolkit_FOUND) # 86 == RTX 3000, needs CUDA v11.1 # 89 == RTX 4000, needs CUDA v11.8 # 90 == Hopper H100/200, needs CUDA v11.8 + # 103 == Blackwell GB300, needs CUDA v12.9 # 120 == Blackwell, needs CUDA v12.8, FP4 tensor cores # # XX-virtual == compile CUDA code as PTX, do JIT compilation to binary code on first run @@ -64,7 +65,7 @@ if (CUDAToolkit_FOUND) list(APPEND CMAKE_CUDA_ARCHITECTURES 120a-real) endif() if (CUDAToolkit_VERSION VERSION_GREATER_EQUAL "12.9") - list(APPEND CMAKE_CUDA_ARCHITECTURES 121a-real) + list(APPEND CMAKE_CUDA_ARCHITECTURES 103-real 121a-real) endif() endif() endif() diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index 0374b5b743fc..e26de2d16dfe 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -4241,22 +4241,25 @@ static bool ggml_cuda_can_fuse(const struct ggml_cgraph * cgraph, add = cgraph->nodes[node_idx+2]; } - GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32); - GGML_ASSERT(rms_norm->type == GGML_TYPE_F32); - - //rms norm only supports F32 - if (mul->src[0]->type != GGML_TYPE_F32 || - mul->src[1]->type != GGML_TYPE_F32 || - mul->type != GGML_TYPE_F32) { + // the mul operand is a norm weight, which model files store as F32; + // the add operand is an F32 bias or a residual with the type of x + const ggml_type type = rms_norm->type; + if ((type != GGML_TYPE_F32 && type != GGML_TYPE_BF16) || rms_norm->src[0]->type != type) { return false; } - if (add && (add->src[0]->type != GGML_TYPE_F32 || - add->src[1]->type != GGML_TYPE_F32 || - add->type != GGML_TYPE_F32) ) { + const ggml_tensor * mul_src = mul->src[0] == rms_norm ? mul->src[1] : mul->src[0]; + if (mul_src->type != GGML_TYPE_F32 || mul->type != type) { return false; } + if (add) { + const ggml_tensor * add_src = add->src[0] == mul ? add->src[1] : add->src[0]; + if ((add_src->type != GGML_TYPE_F32 && add_src->type != type) || add->type != type) { + return false; + } + } + //if rms norm is the B operand, then we don't handle broadcast if (rms_norm == mul->src[1] && !ggml_are_same_shape(mul->src[0], rms_norm)) { return false; @@ -4278,8 +4281,9 @@ static bool ggml_cuda_can_fuse(const struct ggml_cgraph * cgraph, const ggml_tensor * rms_norm = cgraph->nodes[node_idx]; const ggml_tensor * scale = cgraph->nodes[node_idx+1]; - GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32); - GGML_ASSERT(rms_norm->type == GGML_TYPE_F32); + if (rms_norm->src[0]->type != GGML_TYPE_F32 || rms_norm->type != GGML_TYPE_F32) { + return false; + } float bias; memcpy(&bias, (const float *) scale->op_params + 1, sizeof(float)); @@ -6904,9 +6908,11 @@ static bool ggml_backend_cuda_device_supports_op(ggml_backend_dev_t dev, const g case GGML_OP_SILU_BACK: return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32; case GGML_OP_NORM: - case GGML_OP_RMS_NORM: case GGML_OP_L2_NORM: return ggml_is_contiguous_rows(op->src[0]); + case GGML_OP_RMS_NORM: + return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_BF16) && op->type == op->src[0]->type && + ggml_is_contiguous_rows(op->src[0]); case GGML_OP_RMS_NORM_BACK: return ggml_is_contiguous(op->src[0]); case GGML_OP_NONE: diff --git a/ggml/src/ggml-cuda/mmq-config-gcn.cuh b/ggml/src/ggml-cuda/mmq-config-gcn.cuh index 24af2ef2b05b..2aea107f5272 100644 --- a/ggml/src/ggml-cuda/mmq-config-gcn.cuh +++ b/ggml/src/ggml-cuda/mmq-config-gcn.cuh @@ -1,31 +1,36 @@ static constexpr __host__ __device__ ggml_cuda_mmq_config ggml_cuda_mmq_get_config_gcn(ggml_type type, int J, bool fallback) { CASE(GGML_TYPE_Q1_0, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_Q1_0, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_Q1_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_Q1_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q1_0, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q1_0, 512, 2, 128, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q1_0, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q1_0, 512, 2, 128, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q1_0, 512, 2, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q1_0, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q1_0, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q1_0, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q1_0, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q1_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q1_0, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q1_0, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q1_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_Q1_0, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_Q1_0, 512, 2, 128, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_Q1_0, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_Q1_0, 512, 2, 128, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_Q1_0, 512, 2, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_Q1_0, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q2_0, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_Q2_0, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_Q2_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_Q2_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q2_0, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q2_0, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q2_0, 512, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q2_0, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q2_0, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q2_0, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_Q2_0, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q2_0, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q2_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q2_0, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q2_0, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q2_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_Q2_0, 512, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_Q2_0, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q4_0, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q4_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q4_0, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q4_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q4_0, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q4_0, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q4_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q4_0, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q4_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); @@ -37,8 +42,11 @@ static constexpr __host__ __device__ ggml_cuda_mmq_config ggml_cuda_mmq_get_conf CASE(GGML_TYPE_Q4_1, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q4_1, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q4_1, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q4_1, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_Q4_1, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q4_1, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q4_1, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q4_1, 512, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q4_1, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q4_1, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q4_1, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); @@ -50,43 +58,45 @@ static constexpr __host__ __device__ ggml_cuda_mmq_config ggml_cuda_mmq_get_conf CASE(GGML_TYPE_Q5_0, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q5_0, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q5_0, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q5_0, 512, 2, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q5_0, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q5_0, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q5_0, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q5_0, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_Q5_0, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q5_0, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q5_0, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q5_0, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_Q5_0, 512, 2, 128, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_Q5_0, 512, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q5_0, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q5_1, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_Q5_1, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q5_1, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q5_1, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q5_1, 512, 2, 128, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q5_1, 512, 2, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q5_1, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q5_1, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q5_1, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q5_1, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_Q5_1, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q5_1, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q5_1, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q5_1, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_Q5_1, 512, 2, 128, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_Q5_1, 512, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q5_1, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q8_0, 512, 2, 128, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_Q8_0, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_Q8_0, 256, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q8_0, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q8_0, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q8_0, 512, 2, 128, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q8_0, 512, 2, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q8_0, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q8_0, 512, 2, 64, 80, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q8_0, 512, 2, 128, 96, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q8_0, 512, 2, 128, 112, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q8_0, 512, 2, 128, 128, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q8_0, 512, 2, 128, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q8_0, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_Q8_0, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q8_0, 512, 2, 128, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q8_0, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q8_0, 512, 2, 128, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q8_0, 512, 2, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q8_0, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q8_0, 512, 2, 128, 80, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q8_0, 512, 2, 128, 96, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q8_0, 512, 2, 128, 112, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q8_0, 512, 2, 128, 128, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); @@ -95,7 +105,10 @@ static constexpr __host__ __device__ ggml_cuda_mmq_config ggml_cuda_mmq_get_conf CASE(GGML_TYPE_Q2_K, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q2_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q2_K, 512, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q2_K, 512, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q2_K, 512, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q2_K, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q2_K, 512, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q2_K, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q2_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, false, false); @@ -108,18 +121,20 @@ static constexpr __host__ __device__ ggml_cuda_mmq_config ggml_cuda_mmq_get_conf CASE(GGML_TYPE_Q3_K, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q3_K, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q3_K, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q3_K, 512, 2, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q3_K, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q3_K, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q3_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q3_K, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_Q3_K, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_Q3_K, 256, 2, 128, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q3_K, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q3_K, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_Q3_K, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_Q3_K, 512, 2, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q3_K, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q4_K, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q4_K, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_Q4_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q4_K, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q4_K, 512, 2, 128, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q4_K, 256, 2, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q4_K, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q4_K, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q4_K, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); @@ -131,6 +146,7 @@ static constexpr __host__ __device__ ggml_cuda_mmq_config ggml_cuda_mmq_get_conf CASE(GGML_TYPE_Q5_K, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q5_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q5_K, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q5_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q5_K, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q5_K, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); @@ -143,7 +159,11 @@ static constexpr __host__ __device__ ggml_cuda_mmq_config ggml_cuda_mmq_get_conf CASE(GGML_TYPE_Q6_K, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q6_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q6_K, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q6_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q6_K, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q6_K, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_Q6_K, 256, 2, 64, 56, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q6_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, false, true); CASE(GGML_TYPE_Q6_K, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q6_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, false, false); @@ -151,126 +171,151 @@ static constexpr __host__ __device__ ggml_cuda_mmq_config ggml_cuda_mmq_get_conf CASE(GGML_TYPE_Q6_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q6_K, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q6_K, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_Q6_K, 256, 2, 64, 56, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, false, false); CASE(GGML_TYPE_Q6_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, false, false); // --------------------------------------------------------------------------------------------- CASE(GGML_TYPE_IQ1_S, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_IQ1_S, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ1_S, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ1_S, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ1_S, 512, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ1_S, 512, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ1_S, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + // CASE(GGML_TYPE_IQ1_S, 512, 2, 128, 128, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ1_S, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ1_S, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ1_S, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ1_S, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ1_S, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ1_S, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ1_S, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ1_S, 512, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ1_S, 512, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ1_S, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + // CASE(GGML_TYPE_IQ1_S, 512, 2, 128, 128, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_IQ2_XXS, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ2_XXS, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ2_XXS, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ2_XXS, 512, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ2_XXS, 512, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ2_XXS, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + // CASE(GGML_TYPE_IQ2_XXS, 512, 2, 128, 128, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ2_XXS, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ2_XXS, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ2_XXS, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ2_XXS, 512, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ2_XXS, 512, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ2_XXS, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + // CASE(GGML_TYPE_IQ2_XXS, 512, 2, 128, 128, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_IQ2_XS, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ2_XS, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ2_XS, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ2_XS, 512, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ2_XS, 512, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ2_XS, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); + // CASE(GGML_TYPE_IQ2_XS, 512, 2, 128, 128, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ2_XS, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ2_XS, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ2_XS, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ2_XS, 512, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ2_XS, 512, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ2_XS, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); + // CASE(GGML_TYPE_IQ2_XS, 512, 2, 128, 128, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ2_S, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_IQ2_S, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ2_S, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ2_S, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ2_S, 512, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ2_S, 512, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ2_S, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); + // CASE(GGML_TYPE_IQ2_S, 512, 2, 128, 128, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ2_S, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ2_S, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ2_S, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ2_S, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ2_S, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ2_S, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ2_S, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ2_S, 512, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ2_S, 512, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ2_S, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); + // CASE(GGML_TYPE_IQ2_S, 512, 2, 128, 128, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_IQ3_XXS, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ3_XXS, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ3_XXS, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ3_XXS, 512, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ3_XXS, 512, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ3_XXS, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + // CASE(GGML_TYPE_IQ3_XXS, 512, 2, 128, 128, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ3_XXS, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ3_XXS, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ3_XXS, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ3_XXS, 512, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ3_XXS, 512, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ3_XXS, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + // CASE(GGML_TYPE_IQ3_XXS, 512, 2, 128, 128, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_IQ3_S, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ3_S, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ3_S, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ3_S, 512, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ3_S, 512, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ3_S, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + // CASE(GGML_TYPE_IQ3_S, 512, 2, 128, 128, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ3_S, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ3_S, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ3_S, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ3_S, 512, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ3_S, 512, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ3_S, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + // CASE(GGML_TYPE_IQ3_S, 512, 2, 128, 128, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_IQ4_XS, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ4_XS, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ4_XS, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ4_XS, 512, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ4_XS, 512, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ4_XS, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ4_XS, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ4_XS, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ4_XS, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ4_XS, 512, 2, 128, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ4_XS, 512, 2, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ4_XS, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_IQ4_NL, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ4_NL, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ4_NL, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ4_NL, 512, 2, 128, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_IQ4_NL, 512, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ4_NL, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true); CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ4_NL, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ4_NL, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ4_NL, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ4_NL, 512, 2, 128, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_IQ4_NL, 512, 2, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); CASE(GGML_TYPE_IQ4_NL, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false); // --------------------------------------------------------------------------------------------- CASE(GGML_TYPE_MXFP4, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_MXFP4, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_MXFP4, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); CASE(GGML_TYPE_MXFP4, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_MXFP4, 512, 2, 128, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_MXFP4, 512, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); CASE(GGML_TYPE_MXFP4, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true); CASE(GGML_TYPE_MXFP4, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_MXFP4, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_MXFP4, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_MXFP4, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); CASE(GGML_TYPE_MXFP4, 512, 2, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_MXFP4, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_MXFP4, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_MXFP4, 512, 2, 128, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_MXFP4, 512, 2, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); CASE(GGML_TYPE_MXFP4, 512, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false); CASE(GGML_TYPE_NVFP4, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, false, true); - CASE(GGML_TYPE_NVFP4, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_NVFP4, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_NVFP4, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, false, true); CASE(GGML_TYPE_NVFP4, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_NVFP4, 256, 2, 128, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, false, true); + CASE(GGML_TYPE_NVFP4, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, false, true); CASE(GGML_TYPE_NVFP4, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, false, true); CASE(GGML_TYPE_NVFP4, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, false, false); - CASE(GGML_TYPE_NVFP4, 256, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, false, false); + CASE(GGML_TYPE_NVFP4, 512, 2, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, false, false); CASE(GGML_TYPE_NVFP4, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, false, false); CASE(GGML_TYPE_NVFP4, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, false, false); CASE(GGML_TYPE_NVFP4, 256, 2, 128, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, false, false); diff --git a/ggml/src/ggml-cuda/norm.cu b/ggml/src/ggml-cuda/norm.cu index 69730dba870f..b01e18c5c86c 100644 --- a/ggml/src/ggml-cuda/norm.cu +++ b/ggml/src/ggml-cuda/norm.cu @@ -1,4 +1,5 @@ #include "norm.cuh" +#include "convert.cuh" #include "mmvq.cuh" #include @@ -92,11 +93,38 @@ static __global__ void group_norm_f32(const float * x, float * dst, const int gr } } -// do_quantize: also write the result as q8_1 blocks, as quantize_q8_1 would for the mat-vec that reads it (do_vec only, +// 4 consecutive values of x as float4, x + 4*i is aligned to 4 values +template +static __device__ __forceinline__ float4 rms_norm_load4(const T * x, const int i) { + if constexpr (std::is_same_v) { + __align__(8) nv_bfloat162 v[2]; + ggml_cuda_memcpy_1(v, x + 4*i); + const float2 lo = ggml_cuda_cast(v[0]); + const float2 hi = ggml_cuda_cast(v[1]); + return make_float4(lo.x, lo.y, hi.x, hi.y); + } else { + return ((const float4 *) x)[i]; + } +} + +template +static __device__ __forceinline__ void rms_norm_store4(T * dst, const int i, const float4 r) { + if constexpr (std::is_same_v) { + const __align__(8) nv_bfloat16 v[4] = { + ggml_cuda_cast(r.x), ggml_cuda_cast(r.y), ggml_cuda_cast(r.z), ggml_cuda_cast(r.w) }; + ggml_cuda_memcpy_1(dst + 4*i, v); + } else { + ((float4 *) dst)[i] = r; + } +} + +// x and dst are float or nv_bfloat16, mul is float, add is float or the type of x +// do_quantize: also write the result as q8_1 blocks, as quantize_q8_1 would for the mat-vec that reads it (do_vec and float only, // rows of whole blocks). A thread holds 4 values, so 8 consecutive lanes hold one block. -template -static __global__ void rms_norm_f32(const float * x, - float * dst, +template +static __global__ void rms_norm_f32(const T * x, + T * dst, const int ncols, const int nchannels, const int nsamples, @@ -112,7 +140,7 @@ static __global__ void rms_norm_f32(const float * x, const uint3 mul_nrows_packed = make_uint3(0, 0, 0), const uint3 mul_nchannels_packed = make_uint3(0, 0, 0), const uint3 mul_nsamples_packed = make_uint3(0, 0, 0), - const float * add = nullptr, + const T_add * add = nullptr, const int64_t add_stride_row = 0, const int64_t add_stride_channel = 0, const int64_t add_stride_sample = 0, @@ -129,6 +157,7 @@ static __global__ void rms_norm_f32(const float * x, static_assert(!do_add || do_multiply, "fusing add is not supported without multiplying"); static_assert(!do_scale || !do_multiply, "fusing scale is not supported with multiplying"); + static_assert(!do_quantize || (do_vec && std::is_same_v), "the q8_1 copy is made from F32 by the vector kernel"); extern __shared__ float s_sum[]; @@ -137,8 +166,8 @@ static __global__ void rms_norm_f32(const float * x, // grid.y and grid.z are clamped to the CUDA limit, iterate over the excess channels/samples for (int sample = blockIdx.z; sample < nsamples; sample += gridDim.z) { for (int channel = blockIdx.y; channel < nchannels; channel += gridDim.y) { - const float * xc = x + sample*stride_sample + channel*stride_channel + row*stride_row; - float * dstc = dst + ((sample*nchannels + channel)*nrows + row)*ncols; + const T * xc = x + sample*stride_sample + channel*stride_channel + row*stride_row; + T * dstc = dst + ((sample*nchannels + channel)*nrows + row)*ncols; [[maybe_unused]] const float * mulc = nullptr; if constexpr (do_multiply) { @@ -148,7 +177,7 @@ static __global__ void rms_norm_f32(const float * x, mulc = mul + mul_sample * mul_stride_sample + mul_channel * mul_stride_channel + mul_row * mul_stride_row; } - [[maybe_unused]] const float * addc = nullptr; + [[maybe_unused]] const T_add * addc = nullptr; if constexpr (do_add) { const int add_row = fastmodulo(row, add_nrows_packed); const int add_channel = fastmodulo(channel, add_nchannels_packed); @@ -158,10 +187,7 @@ static __global__ void rms_norm_f32(const float * x, if constexpr (do_vec) { const int ncols4 = ncols / 4; - const float4 * x4 = (const float4 *) xc; const float4 * mul4 = (const float4 *) mulc; - const float4 * add4 = (const float4 *) addc; - float4 * dst4 = (float4 *) dstc; float4 xs[vpt]; float tmp = 0.0f; @@ -170,7 +196,7 @@ static __global__ void rms_norm_f32(const float * x, for (int k = 0; k < vpt; k++) { const int i = tid + k*block_size; if (i < ncols4) { - xs[k] = x4[i]; + xs[k] = rms_norm_load4(xc, i); tmp += xs[k].x*xs[k].x + xs[k].y*xs[k].y + xs[k].z*xs[k].z + xs[k].w*xs[k].w; } } @@ -190,7 +216,7 @@ static __global__ void rms_norm_f32(const float * x, r.w *= m.w; } if constexpr (do_add) { - const float4 a = add4[i]; + const float4 a = rms_norm_load4(addc, i); r.x += a.x; r.y += a.y; r.z += a.z; @@ -202,7 +228,7 @@ static __global__ void rms_norm_f32(const float * x, r.z *= scale_out; r.w *= scale_out; } - dst4[i] = r; + rms_norm_store4(dstc, i, r); if constexpr (do_quantize) { // same arithmetic as quantize_q8_1 @@ -220,7 +246,7 @@ static __global__ void rms_norm_f32(const float * x, // the rows of the copy are padded as for quantize_q8_1, the mat-vec does not read the padding const int64_t row_cont = (int64_t) (sample*nchannels + channel)*nrows + row; block_q8_1 * y = (block_q8_1 *) q8_1 + row_cont*(GGML_PAD(ncols, MATRIX_ROW_PADDING)/QK8_1) + i / (QK8_1/4); - const int iqs = 4*(i % (QK8_1/4)); + const int iqs = 4*(i % (QK8_1/4)); y->qs[iqs + 0] = q0; y->qs[iqs + 1] = q1; @@ -236,7 +262,7 @@ static __global__ void rms_norm_f32(const float * x, float tmp = 0.0f; // partial sum for thread in warp for (int col = tid; col < ncols; col += block_size) { - const float xi = xc[col]; + const float xi = ggml_cuda_cast(xc[col]); tmp += xi * xi; } @@ -247,17 +273,18 @@ static __global__ void rms_norm_f32(const float * x, const float scale = rsqrtf(mean + eps); for (int col = tid; col < ncols; col += block_size) { + const float xi = ggml_cuda_cast(xc[col]); if constexpr (do_multiply && do_add) { const int mul_col = fastmodulo(col, mul_ncols_packed); const int add_col = fastmodulo(col, add_ncols_packed); - dstc[col] = scale * xc[col] * mulc[mul_col] + addc[add_col]; + dstc[col] = ggml_cuda_cast(scale * xi * mulc[mul_col] + ggml_cuda_cast(addc[add_col])); } else if constexpr (do_multiply) { const int mul_col = fastmodulo(col, mul_ncols_packed); - dstc[col] = scale * xc[col] * mulc[mul_col]; + dstc[col] = ggml_cuda_cast(scale * xi * mulc[mul_col]); } else if constexpr (do_scale) { - dstc[col] = scale_out * (scale * xc[col]); + dstc[col] = ggml_cuda_cast(scale_out * (scale * xi)); } else { - dstc[col] = scale * xc[col]; + dstc[col] = ggml_cuda_cast(scale * xi); } } } @@ -428,7 +455,7 @@ static void group_norm_f32_cuda( do { \ const dim3 block_dims(BLOCK_SIZE, 1, 1); \ const ggml_cuda_kernel_launch_params launch_params{ blocks_num, block_dims, block_dims.x > WARP_SIZE ? 32 * sizeof(float) : 0, stream }; \ - ggml_cuda_kernel_launch(rms_norm_f32, launch_params, \ + ggml_cuda_kernel_launch(rms_norm_f32, launch_params, \ x, dst, ncols, nchannels, nsamples, stride_row, stride_channel, stride_sample, eps, \ mul, mul_stride_row, mul_stride_channel, mul_stride_sample, \ mul_ncols_packed, mul_nrows_packed, mul_nchannels_packed, mul_nsamples_packed, \ @@ -437,10 +464,10 @@ static void group_norm_f32_cuda( } while (0) // returns whether the q8_1 copy was written (do_quantize) -template +template static bool rms_norm_f32_dispatch( const dim3 blocks_num, - const ggml_tensor * x_t, float * dst, const int ncols, const int nchannels, const int nsamples, + const ggml_tensor * x_t, T * dst, const int ncols, const int nchannels, const int nsamples, const int64_t stride_row, const int64_t stride_channel, const int64_t stride_sample, const float eps, const ggml_tensor * mul_t, const int64_t mul_stride_row, const int64_t mul_stride_channel, const int64_t mul_stride_sample, const uint3 mul_ncols_packed, const uint3 mul_nrows_packed, const uint3 mul_nchannels_packed, const uint3 mul_nsamples_packed, @@ -450,27 +477,27 @@ static bool rms_norm_f32_dispatch( static_assert(!do_add || do_multiply, "fusing add is not supported without multiplying"); static_assert(!do_scale || !do_multiply, "fusing scale is not supported with multiplying"); - const float * x = (const float *) x_t->data; + const T * x = (const T *) x_t->data; const float * mul = mul_t ? (const float *) mul_t->data : nullptr; - const float * add = add_t ? (const float *) add_t->data : nullptr; + const T_add * add = add_t ? (const T_add *) add_t->data : nullptr; // dst is written at row * ncols, i.e. always at a multiple of ncols, so only its base needs checking here - bool vec = ncols % 4 == 0 && ncols > 0 && ((uintptr_t) dst & 15) == 0; - vec = vec && ggml_cuda_is_aligned(x_t, 16); + bool vec = ncols % 4 == 0 && ncols > 0 && ((uintptr_t) dst % (4*sizeof(T))) == 0; + vec = vec && ggml_cuda_is_aligned(x_t, 4*sizeof(T)); if constexpr (do_multiply) { vec = vec && mul_ncols_packed.z == (uint32_t) ncols && ggml_cuda_is_aligned(mul_t, 16); } if constexpr (do_add) { vec = vec && add_ncols_packed.z == (uint32_t) ncols - && ggml_cuda_is_aligned(add_t, 16); + && ggml_cuda_is_aligned(add_t, 4*sizeof(T_add)); } const int n4 = ncols / 4; if constexpr (do_quantize) { // the q8_1 copy needs the vector kernel and rows of whole blocks if (!vec || n4 > 4096 || ncols % QK8_1 != 0) { - rms_norm_f32_dispatch( + rms_norm_f32_dispatch( blocks_num, x_t, dst, ncols, nchannels, nsamples, stride_row, stride_channel, stride_sample, eps, mul_t, mul_stride_row, mul_stride_channel, mul_stride_sample, mul_ncols_packed, mul_nrows_packed, mul_nchannels_packed, mul_nsamples_packed, @@ -504,9 +531,9 @@ static bool rms_norm_f32_dispatch( } #undef RMS_NORM_LAUNCH -template +template static void rms_norm_f32_cuda( - const ggml_tensor * x_t, float * dst, const int ncols, const int nrows, const int nchannels, const int nsamples, + const ggml_tensor * x_t, T * dst, const int ncols, const int nrows, const int nchannels, const int nsamples, const int64_t stride_row, const int64_t stride_channel, const int64_t stride_sample, const float eps, cudaStream_t stream, const float scale_out = 1.0f) { const dim3 blocks_num(nrows, MIN(nchannels, UINT16_MAX), MIN(nsamples, UINT16_MAX)); @@ -518,10 +545,11 @@ static void rms_norm_f32_cuda( } // returns whether the q8_1 copy of the result was written +template static bool rms_norm_mul_f32_cuda(const ggml_tensor * x_t, const ggml_tensor * mul_t, const ggml_tensor * add_t, - float * dst, + T * dst, const int ncols, const int nrows, const int nchannels, @@ -558,12 +586,14 @@ static bool rms_norm_mul_f32_cuda(const ggml_tensor * x_t, const uint3 zero_packed = make_uint3(0, 0, 0); if (add_t == nullptr) { - if (q8_1 != nullptr) { - return rms_norm_f32_dispatch( - blocks_num, x_t, dst, ncols, nchannels, nsamples, stride_row, stride_channel, stride_sample, eps, - mul_t, mul_stride_row, mul_stride_channel, mul_stride_sample, - mul_ncols_packed, mul_nrows_packed, mul_nchannels_packed, mul_nsamples_packed, - nullptr, 0, 0, 0, zero_packed, zero_packed, zero_packed, zero_packed, stream, 1.0f, q8_1); + if constexpr (std::is_same_v) { + if (q8_1 != nullptr) { + return rms_norm_f32_dispatch( + blocks_num, x_t, dst, ncols, nchannels, nsamples, stride_row, stride_channel, stride_sample, eps, + mul_t, mul_stride_row, mul_stride_channel, mul_stride_sample, + mul_ncols_packed, mul_nrows_packed, mul_nchannels_packed, mul_nsamples_packed, + nullptr, 0, 0, 0, zero_packed, zero_packed, zero_packed, zero_packed, stream, 1.0f, q8_1); + } } rms_norm_f32_dispatch( blocks_num, x_t, dst, ncols, nchannels, nsamples, stride_row, stride_channel, stride_sample, eps, @@ -575,24 +605,46 @@ static bool rms_norm_mul_f32_cuda(const ggml_tensor * x_t, const uint3 add_nrows_packed = init_fastdiv_values(add_nrows); const uint3 add_nchannels_packed = init_fastdiv_values(add_nchannels); const uint3 add_nsamples_packed = init_fastdiv_values(add_nsamples); - if (q8_1 != nullptr) { - return rms_norm_f32_dispatch( + // the add operand is F32 or has the type of x (e.g. a BF16 residual) + if (add_t->type == GGML_TYPE_F32) { + if constexpr (std::is_same_v) { + if (q8_1 != nullptr) { + return rms_norm_f32_dispatch( + blocks_num, x_t, dst, ncols, nchannels, nsamples, stride_row, stride_channel, stride_sample, eps, + mul_t, mul_stride_row, mul_stride_channel, mul_stride_sample, + mul_ncols_packed, mul_nrows_packed, mul_nchannels_packed, mul_nsamples_packed, + add_t, add_stride_row, add_stride_channel, add_stride_sample, + add_ncols_packed, add_nrows_packed, add_nchannels_packed, add_nsamples_packed, stream, 1.0f, q8_1); + } + } + rms_norm_f32_dispatch( blocks_num, x_t, dst, ncols, nchannels, nsamples, stride_row, stride_channel, stride_sample, eps, mul_t, mul_stride_row, mul_stride_channel, mul_stride_sample, mul_ncols_packed, mul_nrows_packed, mul_nchannels_packed, mul_nsamples_packed, add_t, add_stride_row, add_stride_channel, add_stride_sample, - add_ncols_packed, add_nrows_packed, add_nchannels_packed, add_nsamples_packed, stream, 1.0f, q8_1); + add_ncols_packed, add_nrows_packed, add_nchannels_packed, add_nsamples_packed, stream); + } else { + rms_norm_f32_dispatch( + blocks_num, x_t, dst, ncols, nchannels, nsamples, stride_row, stride_channel, stride_sample, eps, + mul_t, mul_stride_row, mul_stride_channel, mul_stride_sample, + mul_ncols_packed, mul_nrows_packed, mul_nchannels_packed, mul_nsamples_packed, + add_t, add_stride_row, add_stride_channel, add_stride_sample, + add_ncols_packed, add_nrows_packed, add_nchannels_packed, add_nsamples_packed, stream); } - rms_norm_f32_dispatch( - blocks_num, x_t, dst, ncols, nchannels, nsamples, stride_row, stride_channel, stride_sample, eps, - mul_t, mul_stride_row, mul_stride_channel, mul_stride_sample, - mul_ncols_packed, mul_nrows_packed, mul_nchannels_packed, mul_nsamples_packed, - add_t, add_stride_row, add_stride_channel, add_stride_sample, - add_ncols_packed, add_nrows_packed, add_nchannels_packed, add_nsamples_packed, stream); } return false; } +// calls launch with the data of dst as float * or nv_bfloat16 *, the output types of the RMS_NORM kernels +template +static void rms_norm_launch_typed(ggml_tensor * dst, const F & launch) { + if (dst->type == GGML_TYPE_BF16) { + launch((nv_bfloat16 *) dst->data); + } else { + launch((float *) dst->data); + } +} + static void rms_norm_back_f32_cuda(const float * grad, const float * xf, float * dst, const int ncols, const int nrows, const float eps, cudaStream_t stream) { if (ncols < 1024) { const dim3 block_dims(WARP_SIZE, 1, 1); @@ -663,11 +715,10 @@ void ggml_cuda_op_group_norm(ggml_backend_cuda_context & ctx, ggml_tensor * dst) void ggml_cuda_op_rms_norm(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { const ggml_tensor * src0 = dst->src[0]; - 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); + GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_BF16); + GGML_ASSERT( dst->type == src0->type); GGML_TENSOR_UNARY_OP_LOCALS; @@ -681,7 +732,9 @@ void ggml_cuda_op_rms_norm(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { const int64_t s02 = nb02 / ts0; const int64_t s03 = nb03 / ts0; - rms_norm_f32_cuda(src0, dst_d, ne00, ne01, ne02, ne03, s01, s02, s03, eps, stream); + rms_norm_launch_typed(dst, [&](auto * dst_d) { + rms_norm_f32_cuda(src0, dst_d, ne00, ne01, ne02, ne03, s01, s02, s03, eps, stream); + }); } void ggml_cuda_op_rms_norm_scale_fused(ggml_backend_cuda_context & ctx, ggml_tensor * dst, ggml_tensor * scale_tensor) { @@ -727,12 +780,12 @@ void ggml_cuda_op_rms_norm_fused(ggml_backend_cuda_context & ctx, ggml_tensor * GGML_ASSERT(false); } - float * dst_d = (float *) mul_tensor->data; cudaStream_t stream = ctx.stream(); - GGML_ASSERT(rms_norm_src->type == GGML_TYPE_F32); - GGML_ASSERT(dst->type == GGML_TYPE_F32); - GGML_ASSERT(mul_tensor->type == GGML_TYPE_F32); + GGML_ASSERT(rms_norm_src->type == GGML_TYPE_F32 || rms_norm_src->type == GGML_TYPE_BF16); + GGML_ASSERT(dst->type == rms_norm_src->type); + GGML_ASSERT(mul_tensor->type == rms_norm_src->type); + GGML_ASSERT(mul_src->type == GGML_TYPE_F32); GGML_ASSERT(eps >= 0.0f); const int64_t ne00 = rms_norm_src->ne[0]; @@ -769,14 +822,17 @@ void ggml_cuda_op_rms_norm_fused(ggml_backend_cuda_context & ctx, ggml_tensor * q8_1 = ctx.q8_1_cache.buf->get(); } - const bool quantized = rms_norm_mul_f32_cuda(rms_norm_src, mul_src, nullptr, dst_d, - ne00, ne01, ne02, ne03, - /*s00*/ s01, s02, s03, - /*mul_s00*/ mul_s01, mul_s02, mul_s03, - mul_ncols, mul_nrows, mul_nchannels, mul_nsamples, - /*add_s00*/ 0, 0, 0, - 0, 0, 0, 0, - eps, stream, q8_1); + bool quantized = false; + rms_norm_launch_typed(mul_tensor, [&](auto * dst_d) { + quantized = rms_norm_mul_f32_cuda(rms_norm_src, mul_src, nullptr, dst_d, + ne00, ne01, ne02, ne03, + /*s00*/ s01, s02, s03, + /*mul_s00*/ mul_s01, mul_s02, mul_s03, + mul_ncols, mul_nrows, mul_nchannels, mul_nsamples, + /*add_s00*/ 0, 0, 0, + 0, 0, 0, 0, + eps, stream, q8_1); + }); if (q8_1_src1 != nullptr) { if (quantized) { @@ -817,13 +873,14 @@ void ggml_cuda_op_rms_norm_fused_add(ggml_backend_cuda_context & ctx, GGML_ASSERT(false); } - float * dst_d = (float *) add_tensor->data; cudaStream_t stream = ctx.stream(); - GGML_ASSERT(rms_norm_src->type == GGML_TYPE_F32); - GGML_ASSERT(dst->type == GGML_TYPE_F32); - GGML_ASSERT(mul_tensor->type == GGML_TYPE_F32); - GGML_ASSERT(add_tensor->type == GGML_TYPE_F32); + GGML_ASSERT(rms_norm_src->type == GGML_TYPE_F32 || rms_norm_src->type == GGML_TYPE_BF16); + GGML_ASSERT(dst->type == rms_norm_src->type); + GGML_ASSERT(mul_tensor->type == rms_norm_src->type); + GGML_ASSERT(add_tensor->type == rms_norm_src->type); + GGML_ASSERT(mul_src->type == GGML_TYPE_F32); + GGML_ASSERT(add_src->type == GGML_TYPE_F32 || add_src->type == rms_norm_src->type); GGML_ASSERT(eps >= 0.0f); const int64_t ne00 = rms_norm_src->ne[0]; @@ -871,14 +928,17 @@ void ggml_cuda_op_rms_norm_fused_add(ggml_backend_cuda_context & ctx, q8_1 = ctx.q8_1_cache.buf->get(); } - const bool quantized = rms_norm_mul_f32_cuda(rms_norm_src, mul_src,add_src,dst_d, - ne00,ne01, ne02, ne03, - /*s00*/ s01, s02, s03, - /*mul_s00*/ mul_s01, mul_s02, mul_s03, - mul_ncols, mul_nrows, mul_nchannels, mul_nsamples, - /*add_s00*/ add_s01, add_s02, add_s03, - add_ncols, add_nrows, add_nchannels, add_nsamples, - eps, stream, q8_1); + bool quantized = false; + rms_norm_launch_typed(add_tensor, [&](auto * dst_d) { + quantized = rms_norm_mul_f32_cuda(rms_norm_src, mul_src, add_src, dst_d, + ne00, ne01, ne02, ne03, + /*s00*/ s01, s02, s03, + /*mul_s00*/ mul_s01, mul_s02, mul_s03, + mul_ncols, mul_nrows, mul_nchannels, mul_nsamples, + /*add_s00*/ add_s01, add_s02, add_s03, + add_ncols, add_nrows, add_nchannels, add_nsamples, + eps, stream, q8_1); + }); if (q8_1_src1 != nullptr) { if (quantized) { diff --git a/ggml/src/ggml-cuda/pad_reflect_1d.cu b/ggml/src/ggml-cuda/pad_reflect_1d.cu index a41e72c3709c..6bad7d379af3 100644 --- a/ggml/src/ggml-cuda/pad_reflect_1d.cu +++ b/ggml/src/ggml-cuda/pad_reflect_1d.cu @@ -18,11 +18,12 @@ static __global__ __launch_bounds__(CUDA_PAD_REFLECT_1D_BLOCK_SIZE, 1) void const int64_t nb2, const int64_t nb3, const int p0, - const int p1) { + const int p1, + const uint32_t block_offset) { const int64_t i3 = blockIdx.z; const int64_t i2 = blockIdx.y; - const uint2 div_mod_packed = fast_div_modulo(blockIdx.x, ne01); + const uint2 div_mod_packed = fast_div_modulo(blockIdx.x + block_offset, ne01); const int64_t tile1 = div_mod_packed.y; // i1 const int64_t tile0 = div_mod_packed.x; // nth i0 tile const int64_t i1 = tile1; @@ -77,17 +78,21 @@ void ggml_cuda_op_pad_reflect_1d(ggml_backend_cuda_context & ctx, ggml_tensor * // sanity: padded length matches GGML_ASSERT(ne0 == ne00 + p0 + p1); - // threads per block (x): not more than a row has elements. A tensor with many short rows would otherwise launch - // mostly idle threads, and grid size * block size has to stay below 2^32 on HIP. - const int64_t bx = std::min(CUDA_PAD_REFLECT_1D_BLOCK_SIZE, ne0); - const int64_t tiles0 = (ne0 + bx - 1) / bx; // number of tiles along i0 - // grid.x covers i1 and all tiles of i0: [ne01 * tiles0] + constexpr int64_t bx = CUDA_PAD_REFLECT_1D_BLOCK_SIZE; // threads per block (x) + constexpr int64_t max_blocks = UINT32_MAX / bx; // HIP refuses more than 2^32 threads per grid dimension + const int64_t tiles0 = (ne0 + bx - 1) / bx; // number of tiles along i0 + const int64_t nblocks = ne01 * tiles0; // blocks covering i1 and all tiles of i0 + GGML_ASSERT(nblocks <= UINT32_MAX); + const dim3 block_dims((unsigned) bx, 1, 1); + + // grid.x covers a chunk of at most max_blocks of the nblocks // grid.y covers i2: [ne02] // grid.z covers i3: [ne03] - const dim3 grid_dims((unsigned) (ne01 * tiles0), (unsigned) ne02, (unsigned) ne03); - const dim3 block_dims((unsigned) bx, 1, 1); + for (int64_t offset = 0; offset < nblocks; offset += max_blocks) { + const dim3 grid_dims((unsigned) std::min(nblocks - offset, max_blocks), (unsigned) ne02, (unsigned) ne03); - pad_reflect_1d_kernel_f32<<>>( - src0->data, dst->data, ne0, ne00, ne01_packed, ne02, ne03, src0->nb[0], src0->nb[1], src0->nb[2], src0->nb[3], - dst->nb[0], dst->nb[1], dst->nb[2], dst->nb[3], p0, p1); + pad_reflect_1d_kernel_f32<<>>( + src0->data, dst->data, ne0, ne00, ne01_packed, ne02, ne03, src0->nb[0], src0->nb[1], src0->nb[2], src0->nb[3], + dst->nb[0], dst->nb[1], dst->nb[2], dst->nb[3], p0, p1, (uint32_t) offset); + } } diff --git a/ggml/src/ggml-hexagon/CMakeLists.txt b/ggml/src/ggml-hexagon/CMakeLists.txt index 9444f732132d..fea5770c197f 100644 --- a/ggml/src/ggml-hexagon/CMakeLists.txt +++ b/ggml/src/ggml-hexagon/CMakeLists.txt @@ -33,10 +33,11 @@ add_library(htp_iface OBJECT set_target_properties(htp_iface PROPERTIES POSITION_INDEPENDENT_CODE ON) target_include_directories(htp_iface PUBLIC ${HEXAGON_SDK_ROOT}/incs - ${HEXAGON_SDK_ROOT}/incs/stddef ${HEXAGON_SDK_ROOT}/utils/examples ${CMAKE_CURRENT_SOURCE_DIR}/htp ${CMAKE_CURRENT_BINARY_DIR}) +target_include_directories(htp_iface PRIVATE + ${HEXAGON_SDK_ROOT}/incs/stddef) build_idl(htp/htp_iface.idl htp_iface) @@ -65,8 +66,14 @@ ggml_add_backend_library(${TARGET_NAME} libdl.h ../../include/ggml-hexagon.h) +if (WIN32) + # some clang-cl drivers do not predefine ARM64 macros for winnt.h + target_compile_definitions(${TARGET_NAME} PRIVATE _M_ARM64=1 _ARM64_=1) +endif() + target_link_libraries(${TARGET_NAME} PRIVATE htp_iface) target_include_directories(${TARGET_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/htp ${CMAKE_CURRENT_BINARY_DIR}) +target_include_directories(${TARGET_NAME} SYSTEM PRIVATE ${HEXAGON_SDK_ROOT}/incs/stddef) # Build HTP skels set(HTP_SKELS) diff --git a/ggml/src/ggml-hexagon/ggml-hexagon.cpp b/ggml/src/ggml-hexagon/ggml-hexagon.cpp index 03da443c8318..89c9d9a61139 100644 --- a/ggml/src/ggml-hexagon/ggml-hexagon.cpp +++ b/ggml/src/ggml-hexagon/ggml-hexagon.cpp @@ -316,6 +316,7 @@ struct ggml_hexagon_session { ggml_hexagon_opbatch* op_batch; ggml_hexagon_opqueue* op_queue; + std::unordered_set buffers; std::unordered_map> cloned_buffers; std::unordered_set virt_peers; std::unordered_set phys_peers; @@ -337,6 +338,7 @@ struct ggml_hexagon_session { ggml_hexagon_mdev_group mdev; ggml_backend_dev_t dev = nullptr; ggml_backend_hexagon_device_context * dev_ctx = nullptr; + ggml_hexagon_shared_buffer * shm_buf = nullptr; ggml_hexagon_fence_buffer * fence_buf = nullptr; ggml_hexagon_session(const ggml_hexagon_device_config & config, ggml_backend_dev_t dev = nullptr, uint32_t mdev_idx = 0, uint32_t mdev_count = 0) noexcept(false); @@ -373,8 +375,8 @@ struct ggml_hexagon_session { void flush_peers(); void flush_pending(bool all = true); - ggml_hexagon_shared_buffer * mmap_tensor(const ggml_tensor * t); - bool clone_buffer(const ggml_hexagon_shared_buffer*); + void mmap_buffers(); + void clone_buffer(const ggml_hexagon_shared_buffer*); void release_buffer(const ggml_hexagon_shared_buffer*); void unclone_buffer(const ggml_hexagon_shared_buffer*); @@ -434,7 +436,7 @@ struct ggml_hexagon_rpcmem_block { int fd = -1; size_t size = 0; - std::unordered_set mapped_clones; + std::unordered_set clones; ggml_hexagon_rpcmem_block(size_t size) { base = (uint8_t *) rpcmem_alloc2(RPCMEM_HEAP_ID_SYSTEM, RPCMEM_DEFAULT_FLAGS, size); @@ -468,16 +470,24 @@ struct ggml_hexagon_shared_buffer { size_t size() const { return mem ? mem->size : 0; } int fd() const { return mem ? mem->fd : -1; } - void mmap(bool extended = false) { + void mmap() { if (!this->mem) return; if (this->mapped) return; - GGML_ASSERT(!this->pinned || !extended); + GGML_ASSERT(!this->pinned || !this->extended); - this->extended = extended; - fastrpc_map_flags flags = this->pinned ? FASTRPC_MAP_FD : (extended ? FASTRPC_MAP_FD_DELAYED_EXTENDED : FASTRPC_MAP_FD_DELAYED); + fastrpc_map_flags flags = this->pinned ? FASTRPC_MAP_FD : (this->extended ? FASTRPC_MAP_FD_DELAYED_EXTENDED : FASTRPC_MAP_FD_DELAYED); int err = fastrpc_mmap(sess->domain_id, fd(), (void *) base(), 0, size(), flags); + if (err != 0) { + if (this->extended) { + flags = FASTRPC_MAP_FD_EXTENDED; + } + HEX_VERBOSE("ggml-hex: %s mmap failed (err 0x%08x), retrying in 100ms...\n", sess->c_name(), (unsigned) err); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + err = fastrpc_mmap(sess->domain_id, fd(), (void *) base(), 0, size(), flags); + } + if (err != 0) { GGML_LOG_ERROR("ggml-hex: %s buffer mapping failed : domain_id %d size %zu fd %d error 0x%08x\n", sess->c_name(), sess->domain_id, size(), fd(), (unsigned) err); @@ -550,10 +560,10 @@ struct ggml_hexagon_shared_buffer { // Clone constructor for cross-session mapping ggml_hexagon_shared_buffer(ggml_hexagon_session * sess, const ggml_hexagon_shared_buffer & other) { - this->sess = sess; - this->mem = other.mem; - this->mapped = false; - this->pinned = other.pinned; + this->sess = sess; + this->mem = other.mem; + this->mapped = false; + this->pinned = false; this->extended = other.extended; } @@ -563,19 +573,30 @@ struct ggml_hexagon_shared_buffer { }; struct ggml_hexagon_fence_buffer : public ggml_hexagon_shared_buffer { + uint8_t * data = nullptr; uint32_t slot_count = 0; uint32_t slot_head = 0; std::vector free_slots; ggml_backend_buffer backend_buffer{}; - ggml_hexagon_fence_buffer(ggml_hexagon_session * sess, ggml_backend_buffer_type_t buft, size_t size) - : ggml_hexagon_shared_buffer(sess, size, false /* pinned */), - slot_count(size / HTP_FENCE_SLOT_SIZE), + static size_t size_of(size_t n_slots) { + return n_slots * HTP_FENCE_SLOT_SIZE; + } + + ggml_hexagon_fence_buffer(ggml_hexagon_shared_buffer * shm_buf, ggml_backend_buffer_type_t buft, size_t offset, size_t n_slots) + : ggml_hexagon_shared_buffer(shm_buf->sess, *shm_buf), + data(shm_buf->base() + offset), + slot_count(n_slots), slot_head(0) { + GGML_ASSERT((uintptr_t) data % HEX_L2_LINE_SIZE == 0); + this->mapped = shm_buf->mapped; backend_buffer.buft = buft; backend_buffer.context = static_cast(this); - backend_buffer.size = size; - mmap(false); + backend_buffer.size = size_of(n_slots); + } + + ~ggml_hexagon_fence_buffer() { + this->mapped = false; } uint8_t * alloc_slot(uint32_t n_slots = 1) { @@ -583,11 +604,11 @@ struct ggml_hexagon_fence_buffer : public ggml_hexagon_shared_buffer { if (n_slots == 1 && !free_slots.empty()) { uint32_t slot = free_slots.back(); free_slots.pop_back(); - ptr = base() + (size_t) slot * HTP_FENCE_SLOT_SIZE; + ptr = data + (size_t) slot * HTP_FENCE_SLOT_SIZE; } else if (slot_head + n_slots <= slot_count) { uint32_t slot = slot_head; slot_head += n_slots; - ptr = base() + (size_t) slot * HTP_FENCE_SLOT_SIZE; + ptr = data + (size_t) slot * HTP_FENCE_SLOT_SIZE; } if (ptr) { memset(ptr, 0, (size_t) n_slots * HTP_FENCE_SLOT_SIZE); @@ -597,7 +618,7 @@ struct ggml_hexagon_fence_buffer : public ggml_hexagon_shared_buffer { void free_slot(void * ptr, uint32_t n_slots = 1) { if (!ptr) return; - uint32_t slot = ((uint8_t *) ptr - base()) / HTP_FENCE_SLOT_SIZE; + uint32_t slot = ((uint8_t *) ptr - data) / HTP_FENCE_SLOT_SIZE; for (uint32_t i = 0; i < n_slots; i++) { free_slots.push_back(slot + i); } @@ -636,6 +657,7 @@ inline ggml_tensor ggml_hexagon_session::make_fence_tensor(const volatile void * static void ggml_backend_hexagon_buffer_free_buffer(ggml_backend_buffer_t buffer) { auto sbuf = static_cast(buffer->context); + sbuf->sess->buffers.erase(sbuf); sbuf->sess->unclone_buffer(sbuf); delete sbuf; } @@ -975,31 +997,44 @@ static bool ggml_backend_hexagon_host_buffer_type_is_host(ggml_backend_buffer_ty GGML_UNUSED(buft); } -struct ggml_backend_hexagon_alloc_buffer_n_plan_item { +struct ggml_backend_hexagon_alloc_unit { size_t size; int first; int last; }; +struct ggml_backend_hexagon_alloc_buffer_n_plan_item { + size_t size; + std::vector units; +}; + using ggml_backend_hexagon_alloc_buffer_n_plan_t = std::vector; -static const char * ggml_hexagon_kv_layer_suffix(const struct ggml_tensor * t) { - if (strncmp(t->name, "cache_", 6) != 0) { - return NULL; - } - const char * p = strstr(t->name, "_l"); - if (!p || !isdigit((unsigned char)p[2])) { - return NULL; +static bool ggml_hexagon_tensor_layer(const struct ggml_tensor * t, int & kind, int & layer) { + if (strncmp(t->name, "blk.", 4) == 0 && isdigit((unsigned char) t->name[4])) { + char * end = NULL; + long l = strtol(t->name + 4, &end, 10); + if (end && *end == '.') { + kind = 0; + layer = (int) l; + return true; + } + } + if (strncmp(t->name, "cache_", 6) == 0) { + const char * p = strstr(t->name, "_l"); + if (p && isdigit((unsigned char) p[2])) { + char * end = NULL; + long l = strtol(p + 2, &end, 10); + if (end && *end == '\0') { + kind = 1; + layer = (int) l; + return true; + } + } } - return p; + return false; } -struct ggml_backend_hexagon_alloc_unit { - size_t size; - int first; - int last; -}; - static ggml_backend_hexagon_alloc_buffer_n_plan_t ggml_backend_hexagon_alloc_buffer_n_plan( ggml_backend_buffer_type_t buft, struct ggml_tensor ** tensors, int n_tensors) { ggml_backend_hexagon_alloc_buffer_n_plan_t plan; @@ -1012,61 +1047,72 @@ static ggml_backend_hexagon_alloc_buffer_n_plan_t ggml_backend_hexagon_alloc_buf int i = 0; while (i < n_tensors) { struct ggml_tensor * t = tensors[i]; - size_t unit_size = 0; - int unit_first = i; - int unit_last = i + 1; - - if (t->data == NULL && t->view_src == NULL) { - unit_size += GGML_PAD(ggml_backend_buft_get_alloc_size(buft, t), alignment); + if (t->data != NULL || t->view_src != NULL) { + i++; + continue; } - const char * layer_suffix = ggml_hexagon_kv_layer_suffix(t); + size_t unit_size = GGML_PAD(ggml_backend_buft_get_alloc_size(buft, t), alignment); + int unit_first = i; + int unit_last = i + 1; + + int kind = -1, layer = -1; + const bool has_layer = ggml_hexagon_tensor_layer(t, kind, layer); - while (unit_last < n_tensors) { + while (has_layer && unit_last < n_tensors) { struct ggml_tensor * next = tensors[unit_last]; - - if (next->view_src != NULL) { + if (next->data != NULL || next->view_src != NULL) { unit_last++; continue; } - if (layer_suffix != NULL) { - const char * next_suffix = ggml_hexagon_kv_layer_suffix(next); - if (next_suffix != NULL && strcmp(layer_suffix, next_suffix) == 0) { - if (next->data == NULL) { - unit_size += GGML_PAD(ggml_backend_buft_get_alloc_size(buft, next), alignment); - } - unit_last++; - continue; - } + int next_kind = -1, next_layer = -1; + if (!ggml_hexagon_tensor_layer(next, next_kind, next_layer) || + next_kind != kind || next_layer != layer) { + break; } - break; + size_t next_size = GGML_PAD(ggml_backend_buft_get_alloc_size(buft, next), alignment); + if (unit_size + next_size > max_size) { + break; + } + + unit_size += next_size; + unit_last++; } units.push_back({ unit_size, unit_first, unit_last }); i = unit_last; } - size_t cur_buf_size = 0; - int cur_buf_first = 0; - for (const auto & unit : units) { if (unit.size == 0) { continue; } - - if (cur_buf_size > 0 && (cur_buf_size + unit.size) > max_size) { - plan.push_back({ cur_buf_size, cur_buf_first, unit.first }); - cur_buf_size = 0; - cur_buf_first = unit.first; + bool placed = false; + for (auto & item : plan) { + if (item.size + unit.size <= max_size) { + item.size += unit.size; + item.units.push_back(unit); + placed = true; + break; + } + } + if (!placed) { + plan.push_back({ unit.size, { unit } }); } - - cur_buf_size += unit.size; } - if (cur_buf_size > 0) { - plan.push_back({ cur_buf_size, cur_buf_first, n_tensors }); + std::stable_sort(plan.begin(), plan.end(), [](const auto & a, const auto & b) { + return a.size > b.size; + }); + + if (!plan.empty()) { + for (const auto & unit : units) { + if (unit.size == 0) { + plan[0].units.push_back(unit); + } + } } return plan; @@ -1092,28 +1138,19 @@ static ggml_backend_buffer_t ggml_backend_hexagon_buffer_type_alloc_buffer_n( struct ggml_tallocr tallocr = ggml_tallocr_new(buffer); struct ggml_tensor * t_failed = NULL; - for (int j = item.first; j < item.last; j++) { - struct ggml_tensor * t = tensors[j]; - if (t->data == NULL) { - if (t->view_src == NULL) { + for (const auto & unit : item.units) { + for (int j = unit.first; j < unit.last; j++) { + struct ggml_tensor * t = tensors[j]; + if (t->data == NULL && t->view_src == NULL) { if (ggml_tallocr_alloc(&tallocr, t) != GGML_STATUS_SUCCESS) { t_failed = t; break; } - } else if (t->buffer == NULL) { - if (ggml_backend_view_init(t) != GGML_STATUS_SUCCESS) { - t_failed = t; - break; - } - } - } else { - if (t->view_src != NULL && t->buffer == NULL) { - if (ggml_backend_view_init(t) != GGML_STATUS_SUCCESS) { - t_failed = t; - break; - } } } + if (t_failed != NULL) { + break; + } } if (t_failed != NULL) { GGML_LOG_ERROR("%s: failed to initialize tensor %s\n", __func__, t_failed->name); @@ -1131,6 +1168,19 @@ static ggml_backend_buffer_t ggml_backend_hexagon_buffer_type_alloc_buffer_n( return NULL; } + for (int j = 0; j < n_tensors; j++) { + struct ggml_tensor * t = tensors[j]; + if (t->view_src != NULL && t->buffer == NULL) { + if (ggml_backend_view_init(t) != GGML_STATUS_SUCCESS) { + GGML_LOG_ERROR("%s: failed to initialize tensor %s\n", __func__, t->name); + for (ggml_backend_buffer_t b : buffers) { + ggml_backend_buffer_free(b); + } + return NULL; + } + } + } + if (buffers.size() == 1) { return buffers[0]; } @@ -1200,7 +1250,6 @@ struct ggml_hexagon_opbatch { ggml_hexagon_session* sess; std::vector ops; // htp_opnode of ops - std::vector h_bufs; // htp buffer descriptors std::vector h_tens; // htp tensor descriptors std::vector h_ops; // htp op descriptors @@ -1529,45 +1578,45 @@ struct ggml_hexagon_registry { struct ggml_hexagon_opqueue { // Shared buffer for storing batches ggml_hexagon_shared_buffer *shm_buf; - size_t shm_blk_size; + uint8_t * data; + size_t slot_size; size_t depth; using opvec = std::vector; std::vector op_cache; // per batch op cache - ggml_hexagon_opqueue(ggml_hexagon_session *sess, size_t batch_size, size_t depth) : depth(depth) { + static size_t size_of(size_t batch_size, size_t n_threads, size_t depth = 1) { size_t n_bufs = HTP_OP_MAX_BUFS; size_t n_ops = batch_size; size_t n_tensors = std::min(n_ops * 4 + HTP_OP_MAX_INPUTS + HTP_OP_MAX_OUTPUTS, HTP_OP_MAX_TENSORS); size_t tr_size = 0; if (opt_profile == 3) { - tr_size = sess->n_threads * opt_optrace * sizeof(htp_trace_desc); + tr_size = n_threads * opt_optrace * sizeof(htp_trace_desc); } - shm_blk_size = sizeof(htp_buf_desc) * n_bufs + - sizeof(htp_tensor) * n_tensors + - sizeof(htp_op_desc) * n_ops + - sizeof(htp_prof_desc) * n_ops + - tr_size; - - shm_buf = new ggml_hexagon_shared_buffer(sess, shm_blk_size * depth, true /* pinned */); + size_t slot_size = sizeof(htp_buf_desc) * n_bufs + + sizeof(htp_tensor) * n_tensors + + sizeof(htp_op_desc) * n_ops + + sizeof(htp_prof_desc) * n_ops + + tr_size; + return slot_size * depth; + } + ggml_hexagon_opqueue(ggml_hexagon_shared_buffer *shm_buf, size_t offset, size_t batch_size, size_t depth) + : shm_buf(shm_buf), + data(shm_buf->base() + offset), + slot_size(size_of(batch_size, shm_buf->sess->n_threads)), + depth(depth) { op_cache.resize(depth); if (opt_verbose) { - GGML_LOG_INFO("ggml-hex: %s allocated opqueue : batch-size %zu depth %zu shm-size %zu shm-block-size %zu\n", - sess->c_name(), batch_size, depth, shm_buf->size(), shm_blk_size); + GGML_LOG_INFO("ggml-hex: %s allocated opqueue : batch-size %zu depth %zu shm-size %zu slot-size %zu\n", + shm_buf->c_name(), batch_size, depth, size_of(batch_size, shm_buf->sess->n_threads, depth), slot_size); } } - ~ggml_hexagon_opqueue() { - delete shm_buf; - } - - size_t shm_size() const { return shm_buf ? shm_buf->size() : 0; } - // push new batch bool push(htp_opbatch_req& req, dspqueue_buffer& dbuf, const ggml_hexagon_opbatch* op_batch, uint64_t seq) { static_assert(sizeof(htp_opbatch_req) % 8 == 0, "sizeof(htp_opbatch_req) must be multiple of 8"); @@ -1603,13 +1652,13 @@ struct ggml_hexagon_opqueue { req.n_traces = 0; } - dbuf.ptr = shm_buf->base() + ((size_t) slot * shm_blk_size); + dbuf.ptr = data + ((size_t) slot * slot_size); dbuf.fd = shm_buf->fd(); dbuf.flags = DSPQUEUE_BUFFER_FLAG_FLUSH_SENDER | DSPQUEUE_BUFFER_FLAG_INVALIDATE_RECIPIENT; dbuf.offset = (uint8_t*) dbuf.ptr - (uint8_t*) shm_buf->base(); dbuf.size = b_size + t_size + o_size + p_size + tr_size; - GGML_ASSERT(dbuf.size <= shm_blk_size); + GGML_ASSERT(dbuf.size <= slot_size); uint8_t * m_ptr = (uint8_t*) dbuf.ptr; uint8_t * b_ptr = m_ptr; m_ptr += b_size; @@ -1657,7 +1706,7 @@ struct ggml_hexagon_opqueue { } const size_t m_size = b_size + t_size + o_size + p_size + tr_size; - GGML_ASSERT(m_size <= shm_blk_size); + GGML_ASSERT(m_size <= slot_size); HEX_VERBOSE("ggml-hex: %s opqueue-pop batch #%llu : n-bufs %u n-tensors %u n-ops %u : m-size %zu b-size %zu t-size %zu o-size %zu\n", shm_buf->sess->c_name(), (unsigned long long) rsp.seq, rsp.n_bufs, rsp.n_tensors, rsp.n_ops, @@ -1775,6 +1824,7 @@ void ggml_hexagon_session::flush_batch(size_t min_ops) { if (op_batch->n_ops < min_ops) { return; } op_batch->sort_buffers(); + this->mmap_buffers(); htp_opbatch_req req {}; dspqueue_buffer dbuf{}; @@ -1819,10 +1869,17 @@ void ggml_hexagon_session::flush_batch(size_t min_ops) { } void ggml_hexagon_session::enqueue_op(const htp_opnode & node) { - auto clone_tensor_buffer = [this](const ggml_tensor * t) { - auto sbuf = this->mmap_tensor(t); - if (!sbuf) return; - if (sbuf->sess != this) { + auto register_tensor = [&](const ggml_tensor * t) { + if (!t) return; + auto * sbuf = static_cast(t->buffer->context); + if (ggml_backend_buffer_get_usage(t->buffer) == GGML_BACKEND_BUFFER_USAGE_WEIGHTS) { + sbuf->extended = opt_dma64; + } + if (sbuf->sess == this) { + if (!sbuf->mapped) { + this->buffers.insert(sbuf); + } + } else { this->clone_buffer(sbuf); } for (auto & sub : this->mdev.sessions) { @@ -1830,11 +1887,11 @@ void ggml_hexagon_session::enqueue_op(const htp_opnode & node) { } }; - for (auto t : node.get_inputs()) { - clone_tensor_buffer(t); + for (const auto * src : node.get_inputs()) { + register_tensor(src); } - for (auto t : node.get_outputs()) { - clone_tensor_buffer(t); + for (const auto * dst : node.get_outputs()) { + register_tensor(dst); } const bool fits_tensors = op_batch->fit_tensors(node); @@ -1945,46 +2002,61 @@ void ggml_hexagon_session::enqueue_allreduce( this->enqueue_op(ar_node); } -ggml_hexagon_shared_buffer * ggml_hexagon_session::mmap_tensor(const ggml_tensor * t) { - if (!t) return nullptr; +void ggml_hexagon_session::mmap_buffers() { + auto collect_session = [](ggml_hexagon_session * sess, std::unordered_set & unmapped) { + for (auto * sbuf : sess->buffers) { + if (!sbuf->mapped) { + unmapped.insert(sbuf); + } + } + for (auto & [fd, clone] : sess->cloned_buffers) { + if (!clone->mapped) { + unmapped.insert(clone.get()); + } + } + }; + + std::unordered_set unmapped; + collect_session(this, unmapped); + for (auto & sub : this->mdev.sessions) { + collect_session(sub.get(), unmapped); + } - auto sbuf = static_cast(t->buffer->context); - if (!sbuf->mapped) { - const bool is_weight = ggml_backend_buffer_get_usage(t->buffer) == GGML_BACKEND_BUFFER_USAGE_WEIGHTS; - const bool extended = opt_dma64 && is_weight; - sbuf->mmap(extended); + if (!unmapped.empty()) { + std::vector sorted(unmapped.begin(), unmapped.end()); + std::sort(sorted.begin(), sorted.end(), [](const auto * a, const auto * b) { + if (a->size() != b->size()) { + return a->size() > b->size(); + } + if (a->fd() != b->fd()) { + return a->fd() < b->fd(); + } + return a->sess->domain_id < b->sess->domain_id; + }); + for (auto * sbuf : sorted) { + sbuf->mmap(); + } } - return sbuf; } -bool ggml_hexagon_session::clone_buffer(const ggml_hexagon_shared_buffer * sbuf) +void ggml_hexagon_session::clone_buffer(const ggml_hexagon_shared_buffer * sbuf) { GGML_ASSERT(sbuf && sbuf->mem); - if (sbuf->sess == this) return true; + if (sbuf->sess == this) return; auto mem = sbuf->mem; int fd = mem->fd; GGML_ASSERT(fd >= 0); - if (this->cloned_buffers.find(fd) != this->cloned_buffers.end()) return true; - - GGML_ASSERT(sbuf->mapped); + if (this->cloned_buffers.find(fd) != this->cloned_buffers.end()) return; HEX_VERBOSE("ggml-hex: %s clone-buffer: %s base %p size %zu fd %d\n", this->name.c_str(), sbuf->c_name(), sbuf->base(), sbuf->size(), fd); auto clone = std::make_unique(this, *sbuf); - try { - clone->mmap(sbuf->extended); - } catch (const std::exception & exc) { - GGML_LOG_ERROR("ggml-hex: %s lazy mapping of buffer context failed: %s\n", this->c_name(), exc.what()); - return false; - } - this->cloned_buffers[fd] = std::move(clone); - mem->mapped_clones.insert(this); - return true; + mem->clones.insert(this); } void ggml_hexagon_session::release_buffer(const ggml_hexagon_shared_buffer * sbuf) { @@ -2000,14 +2072,14 @@ void ggml_hexagon_session::release_buffer(const ggml_hexagon_shared_buffer * sbu auto clone = std::move(it->second); this->cloned_buffers.erase(it); } - mem->mapped_clones.erase(this); + mem->clones.erase(this); } void ggml_hexagon_session::unclone_buffer(const ggml_hexagon_shared_buffer * sbuf) { GGML_ASSERT(sbuf && sbuf->mem); auto mem = sbuf->mem; - std::vector sessions(mem->mapped_clones.begin(), mem->mapped_clones.end()); + std::vector sessions(mem->clones.begin(), mem->clones.end()); for (auto * sess : sessions) { sess->release_buffer(sbuf); @@ -2276,9 +2348,14 @@ void ggml_hexagon_session::allocate(const ggml_hexagon_device_config & config) n } // Allocate buffers and state for op batching - this->op_queue = new ggml_hexagon_opqueue(this, opt_opbatch, opt_opqueue); - - this->fence_buf = new ggml_hexagon_fence_buffer(this, &dev_ctx->fence_buffer_type, 64 * 1024); + const size_t n_fences = 512; + const size_t opq_size = ggml_hexagon_opqueue::size_of(opt_opbatch, this->n_threads, opt_opqueue); + const size_t fence_offset = GGML_PAD(opq_size, HEX_L2_LINE_SIZE); + const size_t fence_size = ggml_hexagon_fence_buffer::size_of(n_fences); + + this->shm_buf = new ggml_hexagon_shared_buffer(this, fence_offset + fence_size, true /* pinned */); + this->op_queue = new ggml_hexagon_opqueue(this->shm_buf, 0, opt_opbatch, opt_opqueue); + this->fence_buf = new ggml_hexagon_fence_buffer(this->shm_buf, &dev_ctx->fence_buffer_type, fence_offset, n_fences); if (this->mdev.count > 1) { this->mdev_fence_slot = this->alloc_fence(this->mdev.count); } @@ -2287,7 +2364,7 @@ void ggml_hexagon_session::allocate(const ggml_hexagon_device_config & config) n opt_vmem = ggml_hexagon_measure_max_vmem(this); GGML_LOG_INFO("ggml-hex: %s measured max vmem %zu\n", this->c_name(), opt_vmem); } - const size_t shm_size = this->op_queue->shm_size(); + const size_t shm_size = this->shm_buf->size(); this->max_vmem = (opt_vmem > shm_size) ? (opt_vmem - shm_size) : opt_vmem; this->op_batch = new ggml_hexagon_opbatch(this, opt_opbatch, this->max_vmem); @@ -2328,8 +2405,6 @@ void ggml_hexagon_session::release() noexcept(true) { } } - delete this->op_batch; - delete this->op_queue; for (auto & it : this->cpy_fence_slots) { free_fence((void *) it.second, 1); } @@ -2340,6 +2415,14 @@ void ggml_hexagon_session::release() noexcept(true) { delete this->fence_buf; this->fence_buf = nullptr; } + + delete this->op_batch; + delete this->op_queue; + delete this->shm_buf; + this->op_batch = nullptr; + this->op_queue = nullptr; + this->shm_buf = nullptr; + while (!this->cloned_buffers.empty()) { release_buffer(this->cloned_buffers.begin()->second.get()); } @@ -2734,19 +2817,12 @@ static bool ggml_hexagon_cpy_tensor_async_phys(ggml_backend_t backend_src, ggml_ auto sess_src = static_cast(backend_src->context); auto sess_dst = static_cast(backend_dst->context); - sess_src->mmap_tensor(src); - auto sbuf_dst = sess_dst->mmap_tensor(dst); - - if (!sess_src->clone_buffer(sbuf_dst)) { return false; } - const uint64_t src_key = ggml_hexagon_session_key(sess_src); auto & fence_slot = sess_dst->cpy_fence_slots[src_key]; if (!fence_slot) { fence_slot = (volatile uint32_t *) sess_dst->alloc_fence(1); } - if (!sess_src->clone_buffer(sess_dst->fence_buf)) { return false; } - uint32_t fence_seq = sess_dst->next_fence_seq(); HEX_VERBOSE("ggml-hex: %s cpy-tensor-async %s -> %s size %zu : seq 0x%x\n", @@ -2766,11 +2842,6 @@ static bool ggml_hexagon_cpy_tensor_async_virt(ggml_backend_t backend_src, ggml_ auto sess_src = static_cast(backend_src->context); auto sess_dst = static_cast(backend_dst->context); - auto sbuf_src = sess_src->mmap_tensor(src); - sess_dst->mmap_tensor(dst); - - if (!sess_dst->clone_buffer(sbuf_src)) { return false; } - HEX_VERBOSE("ggml-hex: %s cpy-tensor-async %s -> %s size %zu\n", sess_dst->name.c_str(), src->name, dst->name, ggml_nbytes(src)); @@ -2893,7 +2964,6 @@ static void ggml_backend_hexagon_event_wait(ggml_backend_t backend, ggml_backend return; } - sess->clone_buffer(hex_event->fence_sess->fence_buf); sess->add_peer(hex_event->sess); sess->enqueue_fence(&hex_event->fence_tensor, hex_event->seq, /* wait = */ true); } diff --git a/ggml/src/ggml-hexagon/htp/htp-ctx.h b/ggml/src/ggml-hexagon/htp/htp-ctx.h index 721fa2162d20..b6b608631c60 100644 --- a/ggml/src/ggml-hexagon/htp/htp-ctx.h +++ b/ggml/src/ggml-hexagon/htp/htp-ctx.h @@ -82,6 +82,7 @@ struct htp_ops_context { struct htp_context { dspqueue_t dsp_queue; + struct htp_mmap shm; struct htp_mmap mmap[HTP_MAX_MMAPS]; dma_queue_t dma[HTP_MAX_NTHREADS]; struct htp_thread_trace trace[HTP_MAX_NTHREADS]; diff --git a/ggml/src/ggml-hexagon/htp/main.c b/ggml/src/ggml-hexagon/htp/main.c index ad457d1a6b3e..c1df5a164433 100644 --- a/ggml/src/ggml-hexagon/htp/main.c +++ b/ggml/src/ggml-hexagon/htp/main.c @@ -1089,7 +1089,12 @@ static int execute_op(struct htp_ops_context * octx) { } static inline bool reuse_buf(struct htp_context *ctx, uint32_t *m_reuse, struct htp_buf_desc *b) { - b->base = NULL; + if (b->fd == ctx->shm.fd) { + b->base = ctx->shm.base; + return true; + } + + b->base = 0; for (uint32_t i=0; immap + i; @@ -1203,7 +1208,7 @@ static void prep_op_bufs(struct htp_context *ctx, struct htp_buf_desc *bufs, uin for (uint32_t i=0; i < n_bufs; i++) { struct htp_buf_desc *b = bufs + i; - if (!(b->flags & HTP_BUF_EXTENDED)) { + if (!(b->flags & HTP_BUF_EXTENDED) && b->fd != ctx->shm.fd) { b->base = 0; } if (!mmap_buf(ctx, b)) { @@ -1316,6 +1321,9 @@ static void process_opbatch(struct htp_context * ctx, const struct htp_opbatch_r n_bufs, n_tens, n_ops, req->n_traces, dbuf->size, b_size, t_size, o_size); // Setup descriptor pointers + ctx->shm.fd = dbuf->fd; + ctx->shm.base = (uintptr_t) dbuf->ptr - dbuf->offset; + uint8_t * m_ptr = dbuf->ptr; struct htp_buf_desc* bufs = (struct htp_buf_desc*) m_ptr; m_ptr += b_size; struct htp_tensor* tens = (struct htp_tensor*) m_ptr; m_ptr += t_size; diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index 0a07a76bf112..0ea4a821a670 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1708,8 +1708,9 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te case GGML_OP_ARGMAX: return has_simdgroup_reduction; case GGML_OP_NORM: - case GGML_OP_RMS_NORM: return has_simdgroup_reduction && (ggml_is_contiguous_rows(op->src[0])); + case GGML_OP_RMS_NORM: + return has_simdgroup_reduction && op->src[0]->type == GGML_TYPE_F32 && (ggml_is_contiguous_rows(op->src[0])); case GGML_OP_ROPE: case GGML_OP_ROPE_BACK: return ggml_rope_get_truncate(op); diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index 7fa1a8e35b6b..a60929abc20b 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -11966,7 +11966,7 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te case GGML_OP_NORM: return true; case GGML_OP_RMS_NORM: - return op->ne[0] % 4 == 0 && ggml_is_contiguous_rows(op->src[0]); + return op->src[0]->type == GGML_TYPE_F32 && op->ne[0] % 4 == 0 && ggml_is_contiguous_rows(op->src[0]); case GGML_OP_L2_NORM: return ggml_is_contiguous_rows(op->src[0]); case GGML_OP_REPEAT: diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 3aff66724711..810a30a2e2ec 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -1455,6 +1455,12 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { } break; } + case GGML_OP_RMS_NORM: { + if (op->type == GGML_TYPE_BF16) { + return {false, "RMS_NORM with BF16 type is not supported"}; + } + break; + } case GGML_OP_ADD_ID: { // Keep support aligned with the CPU backend implementation, which only handles f32 inputs/output and i32 ids. if (op->type != GGML_TYPE_F32 || op->src[0]->type != GGML_TYPE_F32 || op->src[1]->type != GGML_TYPE_F32 || diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp index fdd526425c40..3bcbad6f8524 100644 --- a/ggml/src/ggml-sycl/ggml-sycl.cpp +++ b/ggml/src/ggml-sycl/ggml-sycl.cpp @@ -7598,8 +7598,9 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons case GGML_OP_NORM: case GGML_OP_L2_NORM: case GGML_OP_GROUP_NORM: - case GGML_OP_RMS_NORM: return true; + case GGML_OP_RMS_NORM: + return op->src[0]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32; case GGML_OP_RMS_NORM_BACK: return ggml_is_contiguous(op->src[0]); case GGML_OP_SCALE: diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-common.h b/ggml/src/ggml-vulkan/ggml-vulkan-common.h index 4e05fb81839b..b74062931404 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-common.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-common.h @@ -109,6 +109,7 @@ void ggml_vk_quantize_q8_1(ggml_backend_vk_context * ctx, vk_context& subctx, co void ggml_vk_dsv4_hc_comb(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * mixes, const ggml_tensor * scale, const ggml_tensor * base, ggml_tensor * dst); void ggml_vk_dsv4_hc_pre(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * x, const ggml_tensor * weights, ggml_tensor * dst); void ggml_vk_dsv4_hc_post(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * x, const ggml_tensor * residual, const ggml_tensor * post, const ggml_tensor * comb, ggml_tensor * dst, const ggml_tensor * gate_scale_in = nullptr); +void ggml_vk_top_k_mask(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst); void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx); bool ggml_vk_use_mul_mat_vec_id(const struct ggml_cgraph * cgraph, int node_idx); void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx); diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h index 1ef00477bfef..caa852e28bf7 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h @@ -219,6 +219,29 @@ struct vk_op_dsv4_hc_post_push_constants { float gate_scale_out; }; +struct vk_op_top_k_mask_push_constants { + uint32_t n_kv; + uint32_t n_top; + uint32_t n_pick; + uint32_t n_blk; + uint32_t n_extra; + uint32_t has_score; + uint32_t ninf; + + uint32_t ne1; uint32_t ne2; + + uint32_t m1; uint32_t m2; uint32_t m3; + uint32_t nbm1; uint32_t nbm2; uint32_t nbm3; + uint32_t nbd1; uint32_t nbd2; uint32_t nbd3; + + uint32_t m_offset; + uint32_t k_offset; + uint32_t s_offset; + uint32_t b_offset; + uint32_t e_offset; + uint32_t d_offset; +}; + struct vk_op_count_experts_push_constants { uint32_t ne00; uint32_t ne01; @@ -972,6 +995,18 @@ template <> inline void init_pushconst_tensor_offsets(ggml_backend_vk_context * p.d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type); } +// the fifth source, extra, comes from dst +template <> inline void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_top_k_mask_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) { + const ggml_tensor * extra = dst->src[4]; + + p.m_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type); + p.k_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type); + p.s_offset = src2 ? get_misalign_bytes(ctx, src2) / ggml_type_size(src2->type) : 0; + p.b_offset = src3 ? get_misalign_bytes(ctx, src3) / ggml_type_size(src3->type) : 0; + p.e_offset = extra ? get_misalign_bytes(ctx, extra) / ggml_type_size(extra->type) : 0; + p.d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type); +} + template size_t push_constant_size(const T &t) { static_assert(std::is_class::value, "T must be a struct/class"); GGML_UNUSED(t); diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-types.h b/ggml/src/ggml-vulkan/ggml-vulkan-types.h index 81fd5b8a84ba..e72afc6ae447 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-types.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-types.h @@ -977,6 +977,8 @@ struct vk_device_struct { vk_pipeline pipeline_dsv4_hc_pre_gated_f32; vk_pipeline pipeline_dsv4_hc_post_f32; vk_pipeline pipeline_dsv4_hc_post_nocomb_f32; + vk_pipeline pipeline_top_k_mask_f16; + vk_pipeline pipeline_top_k_mask_f32; std::map pipeline_solve_tri_f32; vk_pipeline pipeline_im2col_f32, pipeline_im2col_f32_f16; vk_pipeline pipeline_im2col_3d_f32, pipeline_im2col_3d_f32_f16; @@ -1279,6 +1281,10 @@ struct ggml_backend_vk_context { vk_device device; + // Workaround for drivers moving VRAM contents off the GPU when idle + std::promise keepalive_stop; + std::thread keepalive_thread; + size_t semaphore_idx, binary_semaphore_idx, event_idx; ggml_vk_garbage_collector gc; size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k, prealloc_size_add_rms_partials, prealloc_size_add_rms_partials_offset; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index 22641f5fbdb4..bb5aec3657eb 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -3823,6 +3823,10 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { ggml_vk_create_pipeline(device, device->pipeline_dsv4_hc_post_f32, "dsv4_hc_post_f32", dsv4_hc_post_f32_len, dsv4_hc_post_f32_data, "main", 5, sizeof(vk_op_dsv4_hc_post_push_constants), {256, 1, 1}, { 256, 1 }, 1); ggml_vk_create_pipeline(device, device->pipeline_dsv4_hc_post_nocomb_f32,"dsv4_hc_post_nocomb_f32",dsv4_hc_post_f32_len, dsv4_hc_post_f32_data, "main", 5, sizeof(vk_op_dsv4_hc_post_push_constants), {256, 1, 1}, { 256, 0 }, 1); + const uint32_t top_k_mask_wg = std::min({256u, device->properties.limits.maxComputeWorkGroupInvocations, device->properties.limits.maxComputeWorkGroupSize[0]}); + ggml_vk_create_pipeline(device, device->pipeline_top_k_mask_f16, "top_k_mask_f16", top_k_mask_f16_len, top_k_mask_f16_data, "main", 6, sizeof(vk_op_top_k_mask_push_constants), {1, 1, 1}, {top_k_mask_wg}, 1); + ggml_vk_create_pipeline(device, device->pipeline_top_k_mask_f32, "top_k_mask_f32", top_k_mask_f32_len, top_k_mask_f32_data, "main", 6, sizeof(vk_op_top_k_mask_push_constants), {1, 1, 1}, {top_k_mask_wg}, 1); + for (auto &s : device->pipeline_solve_tri_f32) { const vk_solve_tri_pipeline_state &state = s.first; @@ -4237,6 +4241,8 @@ static bool ggml_vk_has_rebar(const vk::PhysicalDevice & physical_device) { return false; } +static void ggml_vk_device_start_keepalive(vk_device& device); + vk_device ggml_vk_get_device(size_t idx) { VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")"); @@ -7623,6 +7629,46 @@ void ggml_vk_dsv4_hc_post(ggml_backend_vk_context * ctx, vk_context& subctx, con ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { x_buf, r_buf, p_buf, c_buf, d_buf }, pc, { n_embd, n_tokens, 1 }); } +void ggml_vk_top_k_mask(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { + const ggml_tensor * mask = dst->src[0]; + const ggml_tensor * top_k = dst->src[1]; + const ggml_tensor * score = dst->src[2]; + const ggml_tensor * blocks = dst->src[3]; + const ggml_tensor * extra = dst->src[4]; + VK_LOG_DEBUG("ggml_vk_top_k_mask(" << mask << ", " << top_k << ", " << score << ", " << blocks << ", " << extra << ", " << dst << ")"); + + vk_pipeline pipeline = dst->type == GGML_TYPE_F16 ? ctx->device->pipeline_top_k_mask_f16 : ctx->device->pipeline_top_k_mask_f32; + GGML_ASSERT(pipeline != nullptr); + + ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); + + const vk_subbuffer m_buf = ggml_vk_tensor_subbuffer(ctx, mask, true); + const vk_subbuffer k_buf = ggml_vk_tensor_subbuffer(ctx, top_k, true); + const vk_subbuffer s_buf = score ? ggml_vk_tensor_subbuffer(ctx, score, true) : k_buf; + const vk_subbuffer b_buf = blocks ? ggml_vk_tensor_subbuffer(ctx, blocks, true) : k_buf; + const vk_subbuffer e_buf = extra ? ggml_vk_tensor_subbuffer(ctx, extra, true) : k_buf; + const vk_subbuffer d_buf = ggml_vk_tensor_subbuffer(ctx, dst, true); + + vk_op_top_k_mask_push_constants pc = { + (uint32_t)mask->ne[0], + (uint32_t)top_k->ne[0], + (uint32_t)(blocks ? blocks->ne[1] : score ? score->ne[0] : mask->ne[0]), + blocks ? (uint32_t)blocks->ne[0] : 0, + extra ? (uint32_t)extra->ne[0] : 0, + score ? 1u : 0u, + dst->type == GGML_TYPE_F16 ? 0xFC00u : 0xFF800000u, + (uint32_t)dst->ne[1], (uint32_t)dst->ne[2], + (uint32_t)mask->ne[1], (uint32_t)mask->ne[2], (uint32_t)mask->ne[3], + ggml_vk_nb_elem(mask, 1), ggml_vk_nb_elem(mask, 2), ggml_vk_nb_elem(mask, 3), + ggml_vk_nb_elem(dst, 1), ggml_vk_nb_elem(dst, 2), ggml_vk_nb_elem(dst, 3), + 0, 0, 0, 0, 0, 0, + }; + init_pushconst_tensor_offsets(ctx, pc, mask, top_k, score, blocks, dst); + + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { m_buf, k_buf, s_buf, b_buf, e_buf, d_buf }, pc, + { (uint32_t)dst->ne[1], (uint32_t)dst->ne[2], (uint32_t)dst->ne[3] }); +} + void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) { ggml_tensor * dst = cgraph->nodes[node_idx]; ggml_tensor * src0 = dst->src[0]; @@ -13209,6 +13255,11 @@ bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, in break; + case GGML_OP_TOP_K_MASK: + ggml_vk_top_k_mask(ctx, compute_ctx, node); + + break; + case GGML_OP_GATED_DELTA_NET: ggml_vk_gated_delta_net(ctx, compute_ctx, node); @@ -13353,6 +13404,10 @@ void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) { void ggml_vk_cleanup(ggml_backend_vk_context * ctx) { VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")"); + if (ctx->keepalive_thread.joinable()) { + ctx->keepalive_stop.set_value(); + ctx->keepalive_thread.join(); + } // discard any unsubmitted command buffers ctx->compute_ctx.reset(); // wait for any pending command buffers to finish @@ -15719,11 +15774,34 @@ static ggml_guid_t ggml_backend_vk_guid() { return &guid; } +static void ggml_vk_start_keepalive(ggml_backend_vk_context * ctx) { + const char * env = getenv("GGML_VK_KEEPALIVE"); + const int s = env ? atoi(env) : 0; + if (s <= 0) { + return; + } + + GGML_LOG_INFO("ggml_vulkan: GGML_VK_KEEPALIVE=%ds on %s\n", s, ctx->device->name.c_str()); + + vk_buffer buf = ggml_vk_create_buffer_check(ctx->device, 4, vk::MemoryPropertyFlagBits::eDeviceLocal); + ctx->keepalive_thread = std::thread([buf, stop = ctx->keepalive_stop.get_future(), s]() mutable { + while (stop.wait_for(std::chrono::seconds(s)) == std::future_status::timeout) { + try { + ggml_vk_buffer_memset(buf, 0, 0, 4); + } catch (const std::exception & e) { + GGML_LOG_WARN("ggml_vulkan: keepalive stopped: %s\n", e.what()); + return; + } + } + }); +} + ggml_backend_t ggml_backend_vk_init(size_t dev_num) { VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")"); ggml_backend_vk_context * ctx = new ggml_backend_vk_context; ggml_vk_init(ctx, dev_num); + ggml_vk_start_keepalive(ctx); ggml_backend_t vk_backend = new ggml_backend { /* .guid = */ ggml_backend_vk_guid(), @@ -16235,11 +16313,11 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm case GGML_OP_VIEW: case GGML_OP_PERMUTE: case GGML_OP_TRANSPOSE: - case GGML_OP_RMS_NORM: return true; case GGML_OP_GROUP_NORM: return ggml_is_contiguous(op->src[0]); case GGML_OP_NORM: + case GGML_OP_RMS_NORM: case GGML_OP_L2_NORM: return op->src[0]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32; case GGML_OP_ADD: @@ -16459,6 +16537,30 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm } return true; } + case GGML_OP_TOP_K_MASK: + { + const ggml_tensor * mask = op->src[0]; + if ((op->type != GGML_TYPE_F16 && op->type != GGML_TYPE_F32) || mask->type != op->type) { + return false; + } + + // one workgroup per row + const auto & max_wg = device->properties.limits.maxComputeWorkGroupCount; + if (op->ne[1] > max_wg[0] || op->ne[2] > max_wg[1] || op->ne[3] > max_wg[2]) { + return false; + } + + // the shader expects contiguous rows in mask and dst, and contiguous tensors in the other inputs + if (!ggml_is_contiguous_rows(op) || !ggml_is_contiguous_rows(mask)) { + return false; + } + for (int i = 1; i <= 4; ++i) { + if (op->src[i] && !ggml_is_contiguous(op->src[i])) { + return false; + } + } + return true; + } case GGML_OP_GATED_DELTA_NET: { const uint32_t S_v = op->src[2]->ne[0]; diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/top_k_mask.comp b/ggml/src/ggml-vulkan/vulkan-shaders/top_k_mask.comp new file mode 100644 index 000000000000..0e2c5b1605a1 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/top_k_mask.comp @@ -0,0 +1,95 @@ +#version 450 + +#extension GL_EXT_shader_16bit_storage : require +#extension GL_KHR_memory_scope_semantics : enable + +// One workgroup per row: fill the row with -inf, then copy the mask cells of the live picks and the extra cells. +// The op only moves bits, so f16 needs no float16 arithmetic and the score check does not depend on float controls. + +layout(constant_id = 0) const uint BLOCK_SIZE = 256; + +layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in; + +layout(push_constant) uniform parameter +{ + uint n_kv; + uint n_top; + uint n_pick; + uint n_blk; // 0: a pick is a cell + uint n_extra; + uint has_score; + uint ninf; // bits of -inf: a 16-bit literal would need shaderInt16 + + uint ne1; uint ne2; + + uint m1; uint m2; uint m3; + uint nbm1; uint nbm2; uint nbm3; + uint nbd1; uint nbd2; uint nbd3; + + uint m_offset; + uint k_offset; + uint s_offset; + uint b_offset; + uint e_offset; + uint d_offset; +}; + +layout(binding = 0, std430) readonly buffer M { MASK_TYPE data_m[]; }; +layout(binding = 1, std430) readonly buffer K { int data_k[]; }; +layout(binding = 2, std430) readonly buffer S { uint data_s[]; }; +layout(binding = 3, std430) readonly buffer B { int data_b[]; }; +layout(binding = 4, std430) readonly buffer E { int data_e[]; }; +// coherent: the fill and the copy of a cell can come from different invocations +layout(binding = 5, std430) coherent writeonly buffer D { MASK_TYPE data_d[]; }; + +void keep(const int c, const uint m_row, const uint d_row) { + if (c >= 0 && uint(c) < n_kv) { + data_d[d_row + uint(c)] = data_m[m_row + uint(c)]; + } +} + +// score > -inf +bool is_live(const uint s) { + return s != 0xFF800000u && (s & 0x7FFFFFFFu) <= 0x7F800000u; +} + +void main() { + const uint tid = gl_LocalInvocationIndex; + + const uint i1 = gl_WorkGroupID.x; + const uint i2 = gl_WorkGroupID.y; + const uint i3 = gl_WorkGroupID.z; + + const uint row = i1 + ne1*(i2 + ne2*i3); + const uint m_row = m_offset + (i1 % m1)*nbm1 + (i2 % m2)*nbm2 + (i3 % m3)*nbm3; + const uint d_row = d_offset + i1*nbd1 + i2*nbd2 + i3*nbd3; + + for (uint i = tid; i < n_kv; i += BLOCK_SIZE) { + data_d[d_row + i] = MASK_TYPE(ninf); + } + + controlBarrier(gl_ScopeWorkgroup, gl_ScopeWorkgroup, gl_StorageSemanticsBuffer, gl_SemanticsAcquireRelease); + + // one invocation per pick or extra cell; cells kept twice get the same value + for (uint i = tid; i < n_top + n_extra; i += BLOCK_SIZE) { + if (i >= n_top) { + keep(data_e[e_offset + row*n_extra + (i - n_top)], m_row, d_row); + continue; + } + + const int p = data_k[k_offset + row*n_top + i]; + if (p < 0 || uint(p) >= n_pick) { + continue; + } + if (has_score != 0 && !is_live(data_s[s_offset + row*n_pick + uint(p)])) { + continue; + } + if (n_blk == 0) { + keep(p, m_row, d_row); + continue; + } + for (uint k = 0; k < n_blk; ++k) { + keep(data_b[b_offset + uint(p)*n_blk + k], m_row, d_row); + } + } +} 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 7ccccfa1d3cb..d26357498240 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp @@ -1120,6 +1120,8 @@ void process_shaders() { string_to_spv("dsv4_hc_comb_f32", "dsv4_hc_comb.comp", {}); string_to_spv("dsv4_hc_pre_f32", "dsv4_hc_pre.comp", {}); string_to_spv("dsv4_hc_post_f32", "dsv4_hc_post.comp", {}); + string_to_spv("top_k_mask_f16", "top_k_mask.comp", {{"MASK_TYPE", "uint16_t"}}); + string_to_spv("top_k_mask_f32", "top_k_mask.comp", {{"MASK_TYPE", "uint"}}); string_to_spv("cumsum_f32", "cumsum.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}})); string_to_spv("cumsum_multipass1_f32", "cumsum_multipass1.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}})); string_to_spv("cumsum_multipass2_f32", "cumsum_multipass2.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}})); diff --git a/pyproject.toml b/pyproject.toml index 996529753e45..9a066770c0aa 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ version = "0.0.0" dynamic = ["classifiers"] readme = "README.md" authors = [{name = "GGML", email = "ggml@ggml.ai"}] -requires-python = '>=3.10,<3.15' +requires-python = '>=3.10,<3.16' dependencies = [ 'numpy (>=2.2.6,<3.0.0); python_version < "3.14"', 'numpy (>=2.3.0,<3.0.0); python_version >= "3.14"', @@ -40,9 +40,12 @@ packages = [ [tool.poetry.dependencies] torch = [ - { version = "==2.11.0", source = "pypi", markers = "sys_platform == 'darwin'" }, - { version = "==2.11.0+cpu", source = "pytorch", markers = "sys_platform == 'linux'" }, - { version = "==2.11.0", source = "pypi", markers = "sys_platform == 'win32'" }, + { version = "==2.11.0", source = "pypi", markers = "sys_platform == 'darwin' and python_version < '3.15'" }, + { version = "==2.11.0+cpu", source = "pytorch", markers = "sys_platform == 'linux' and python_version < '3.15'" }, + { version = "==2.11.0", source = "pypi", markers = "sys_platform == 'win32' and python_version < '3.15'" }, + { version = "==2.15.0", source = "pypi", markers = "sys_platform == 'darwin' and python_version >= '3.15'" }, + { version = "==2.15.0+cpu", source = "pytorch", markers = "sys_platform == 'linux' and python_version >= '3.15'" }, + { version = "==2.15.0", source = "pypi", markers = "sys_platform == 'win32' and python_version >= '3.15'" }, ] [tool.poetry.group.dev.dependencies] diff --git a/requirements/requirements-all.txt b/requirements/requirements-all.txt index 6c6bea9490b4..b18db3859656 100644 --- a/requirements/requirements-all.txt +++ b/requirements/requirements-all.txt @@ -4,7 +4,6 @@ -r ./requirements-compare-llama-bench.txt -r ./requirements-server-bench.txt --r ./requirements-pydantic.txt -r ./requirements-test-tokenizer-random.txt -r ./requirements-convert_hf_to_gguf.txt diff --git a/requirements/requirements-compare-llama-bench.txt b/requirements/requirements-compare-llama-bench.txt index d87e897e1719..22ed7fc8b5c9 100644 --- a/requirements/requirements-compare-llama-bench.txt +++ b/requirements/requirements-compare-llama-bench.txt @@ -1,3 +1,4 @@ tabulate~=0.9.0 GitPython~=3.1.43 -matplotlib~=3.10.0 +matplotlib~=3.10.0; python_version < "3.11" +matplotlib~=3.11.2; python_version >= "3.11" diff --git a/requirements/requirements-convert_hf_to_gguf.txt b/requirements/requirements-convert_hf_to_gguf.txt index b1f7c863e27e..77df026c9a9c 100644 --- a/requirements/requirements-convert_hf_to_gguf.txt +++ b/requirements/requirements-convert_hf_to_gguf.txt @@ -2,4 +2,5 @@ --extra-index-url https://download.pytorch.org/whl/cpu ## Embedding Gemma requires PyTorch 2.6.0 or later, bumped to 2.11.0 for compatibility -torch==2.11.0 +torch==2.11.0; python_version < "3.15" +torch==2.15.0; python_version >= "3.15" diff --git a/requirements/requirements-convert_legacy_llama.txt b/requirements/requirements-convert_legacy_llama.txt index 9186f361eb5d..5f62ffee0462 100644 --- a/requirements/requirements-convert_legacy_llama.txt +++ b/requirements/requirements-convert_legacy_llama.txt @@ -1,5 +1,5 @@ numpy~=2.2.6; python_version < "3.14" -numpy~=2.4.6; python_version >= "3.14" +numpy~=2.5.4; python_version >= "3.14" sentencepiece>=0.1.98,<0.3.0 transformers==4.57.6 diff --git a/requirements/requirements-gguf_editor_gui.txt b/requirements/requirements-gguf_editor_gui.txt index 0618acf09919..a12e6e527e69 100644 --- a/requirements/requirements-gguf_editor_gui.txt +++ b/requirements/requirements-gguf_editor_gui.txt @@ -1,4 +1,4 @@ numpy~=2.2.6; python_version < "3.14" -numpy~=2.4.6; python_version >= "3.14" +numpy~=2.5.4; python_version >= "3.14" PySide6~=6.9.0 gguf>=0.17.0 diff --git a/requirements/requirements-pydantic.txt b/requirements/requirements-pydantic.txt deleted file mode 100644 index 1738494edb47..000000000000 --- a/requirements/requirements-pydantic.txt +++ /dev/null @@ -1,3 +0,0 @@ -docstring_parser~=0.15 -pydantic~=2.11.7 -requests~=2.32.3 diff --git a/requirements/requirements-server-bench.txt b/requirements/requirements-server-bench.txt index 88a9cb2dc067..21e181e03a2d 100644 --- a/requirements/requirements-server-bench.txt +++ b/requirements/requirements-server-bench.txt @@ -1,6 +1,7 @@ datasets~=4.8.0 -matplotlib~=3.10.0 +matplotlib~=3.10.0; python_version < "3.11" +matplotlib~=3.11.2; python_version >= "3.11" numpy~=2.2.6; python_version < "3.14" -numpy~=2.4.6; python_version >= "3.14" +numpy~=2.5.4; python_version >= "3.14" requests~=2.32.3 tqdm~=4.67.1 diff --git a/requirements/requirements-test-tokenizer-random.txt b/requirements/requirements-test-tokenizer-random.txt index 2785e71a2571..f54bc8ddf57c 100644 --- a/requirements/requirements-test-tokenizer-random.txt +++ b/requirements/requirements-test-tokenizer-random.txt @@ -1 +1 @@ -cffi~=1.16.0 +cffi~=2.1.1 diff --git a/requirements/requirements-tool_bench.txt b/requirements/requirements-tool_bench.txt index 471f13fd55c1..26f46bb4d8ee 100644 --- a/requirements/requirements-tool_bench.txt +++ b/requirements/requirements-tool_bench.txt @@ -1,9 +1,11 @@ pytest~=8.3.3 -matplotlib~=3.10.0 +matplotlib~=3.10.0; python_version < "3.11" +matplotlib~=3.11.2; python_version >= "3.11" numpy~=2.2.6; python_version < "3.14" -numpy~=2.4.6; python_version >= "3.14" +numpy~=2.5.4; python_version >= "3.14" openai~=2.14.0 -pandas~=2.3.3 +pandas~=2.3.3; python_version < "3.11" +pandas~=3.0.6; python_version >= "3.11" prometheus-client~=0.20.0 requests~=2.32.3 wget~=3.2 diff --git a/scripts/hip/gcn-cdna-vgpr-check.py b/scripts/hip/gcn-cdna-vgpr-check.py index a09891fdc3a5..894104524809 100644 --- a/scripts/hip/gcn-cdna-vgpr-check.py +++ b/scripts/hip/gcn-cdna-vgpr-check.py @@ -83,6 +83,8 @@ def main(): '_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi16ELb0ELb1ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiiil', '_ZL18flash_attn_ext_f16ILi576ELi512ELi8ELi4ELb0ELb1ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiiil', '_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type2ELS0_2ELb0EEvPKcS2_S2_S2_S2_PKiS4_PfP15HIP_vector_typeIfLj2EEffffjfiS6_IjLj3EEiiiiiiiiiiiliiliiiiil', + '_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb0EEvPKcS2_S2_S2_S2_PKiS4_PfP15HIP_vector_typeIfLj2EEffffjfiS6_IjLj3EEiiiiiiiiiiiliiliiiiil', + '_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb1EEvPKcS2_S2_S2_S2_PKiS4_PfP15HIP_vector_typeIfLj2EEffffjfiS6_IjLj3EEiiiiiiiiiiiliiliiiiil', '_ZL18flash_attn_ext_f16ILi320ELi256ELi2ELi32ELb0ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiiil', '_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi16ELb0ELb1ELb1EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiiil', } diff --git a/scripts/snapdragon/qdc/run_qdc_jobs.py b/scripts/snapdragon/qdc/run_qdc_jobs.py index 1ba640fca5af..f1c3d87deb3a 100644 --- a/scripts/snapdragon/qdc/run_qdc_jobs.py +++ b/scripts/snapdragon/qdc/run_qdc_jobs.py @@ -68,8 +68,9 @@ POLL_INTERVAL = 30 JOB_TIMEOUT = 3600 +RUNNER_TIMEOUT = 300 LOG_UPLOAD_TIMEOUT = 600 -CAPACITY_TIMEOUT = 1800 +CAPACITY_TIMEOUT = 300 CAPACITY_POLL = 60 MAX_CONCURRENT_JOBS = 5 DEFAULT_RETRIES = 0 @@ -82,6 +83,10 @@ class DeviceUnavailableError(Exception): """Raised when the QDC device resource is not available (retryable).""" +class RunnerUnavailableError(Exception): + """Raised when QDC runner or capacity is not available within timeout (non-retryable).""" + + _SCRIPTS_DIR = Path(__file__).parent _TESTS_DIR = _SCRIPTS_DIR / "tests" @@ -253,8 +258,9 @@ class PlatformSpec: # ============================================================================= -def wait_for_job(client, job_id: str, timeout: int) -> str: +def wait_for_job(client, job_id: str, timeout: int, runner_timeout: int = RUNNER_TIMEOUT) -> str: elapsed = 0 + submitted_elapsed = 0 last_state = None consecutive_errors = 0 max_consecutive_errors = 5 @@ -285,6 +291,26 @@ def wait_for_job(client, job_id: str, timeout: int) -> str: if raw != last_state: log.info("Job %s: %s", job_id, raw) last_state = raw + + is_submitted = (status == JobState.SUBMITTED) or ( + isinstance(raw, str) and raw.lower() == "submitted" + ) + if is_submitted: + submitted_elapsed += POLL_INTERVAL + if submitted_elapsed >= runner_timeout: + try: + qdc_api.abort_job(client, job_id) + log.warning( + "Aborted job %s: runner did not pick up job within %ds", + job_id, + runner_timeout, + ) + except Exception as e: + log.warning("Failed to abort job %s: %s", job_id, e) + raise RunnerUnavailableError( + f"Runner did not pick up job {job_id} within {runner_timeout}s" + ) + time.sleep(POLL_INTERVAL) elapsed += POLL_INTERVAL # Abort to free the QDC concurrency slot instead of leaking it. @@ -312,10 +338,10 @@ def wait_for_log_upload(client, job_id: str) -> None: log.warning("Timed out waiting for log upload after %ds", LOG_UPLOAD_TIMEOUT) -def wait_for_capacity(client, max_jobs: int = MAX_CONCURRENT_JOBS) -> None: +def wait_for_capacity(client, timeout: int = CAPACITY_TIMEOUT, max_jobs: int = MAX_CONCURRENT_JOBS) -> None: """Block until the user's active (non-terminal) QDC job count is below max_jobs.""" elapsed = 0 - while elapsed < CAPACITY_TIMEOUT: + while elapsed < timeout: jobs_page = qdc_api.get_jobs_list(client, page_number=0, page_size=50) if jobs_page is None: log.warning( @@ -338,7 +364,7 @@ def wait_for_capacity(client, max_jobs: int = MAX_CONCURRENT_JOBS) -> None: time.sleep(CAPACITY_POLL) elapsed += CAPACITY_POLL raise TimeoutError( - f"Capacity wait timed out after {CAPACITY_TIMEOUT}s" + f"Capacity wait timed out after {timeout}s" ) @@ -445,7 +471,11 @@ def fetch_logs_and_parse_tests( ) -def write_summary(result: JobResult, title: str = "QDC Test Results") -> None: +def write_summary( + result: JobResult, + title: str = "QDC Test Results", + note: str | None = None, +) -> None: summary_path = os.environ.get("GITHUB_STEP_SUMMARY") if not summary_path: return @@ -454,8 +484,12 @@ def write_summary(result: JobResult, title: str = "QDC Test Results") -> None: lines = [ f"## {title}\n", - f"Overall: {icon} {'PASSED' if result.passed else 'FAILED'}\n", ] + if note: + lines.append(f"{note}\n") + else: + lines.append(f"Overall: {icon} {'PASSED' if result.passed else 'FAILED'}\n") + reportable = {n: ok for n, ok in result.tests.items() if "test_install" not in n} if reportable: lines += ["| Test | Result |", "| ---- | ------ |"] @@ -464,7 +498,7 @@ def write_summary(result: JobResult, title: str = "QDC Test Results") -> None: passed_n = sum(1 for v in reportable.values() if v) failed_n = sum(1 for v in reportable.values() if not v) lines += ["", f"**{passed_n} passed, {failed_n} failed**"] - else: + elif not note: lines.append("_No per-test data available._") failed_names = [n for n, ok in reportable.items() if not ok] @@ -519,6 +553,8 @@ def parse_args() -> argparse.Namespace: help="Test suite to run (default: bench)") p.add_argument("--job-timeout", type=int, default=JOB_TIMEOUT, metavar="SECONDS", help=f"Max seconds to wait for job completion (default: {JOB_TIMEOUT})") + p.add_argument("--runner-timeout", type=int, default=RUNNER_TIMEOUT, metavar="SECONDS", + help=f"Max seconds to wait for runner to pick up job (default: {RUNNER_TIMEOUT})") p.add_argument("--retries", type=int, default=DEFAULT_RETRIES, metavar="N", help="Number of retries when device is unavailable (default: 0)") p.add_argument("--retry-delay", type=int, default=RETRY_DELAY, metavar="SECONDS", @@ -537,9 +573,11 @@ def _submit_and_run_job(client, args, spec, target_id, artifact_id) -> JobResult test failure). """ try: - wait_for_capacity(client) + wait_for_capacity(client, timeout=args.runner_timeout) except TimeoutError: - raise DeviceUnavailableError("Capacity wait timed out — device busy") + raise RunnerUnavailableError( + f"Capacity wait timed out after {args.runner_timeout}s - device busy" + ) job_name = spec.job_name_fmt.format(base="llama.cpp Hexagon tests") @@ -559,11 +597,16 @@ def _submit_and_run_job(client, args, spec, target_id, artifact_id) -> JobResult job_parameters=[JobSubmissionParameter.WIFIENABLED], ) if job_id is None: - raise DeviceUnavailableError("Job submission failed — device may be unavailable") + raise DeviceUnavailableError("Job submission failed - device may be unavailable") log.info("Job submitted: %s (device=%s)", job_id, args.device) try: - job_status = wait_for_job(client, job_id, timeout=args.job_timeout) + job_status = wait_for_job( + client, + job_id, + timeout=args.job_timeout, + runner_timeout=args.runner_timeout, + ) except TimeoutError as e: raise DeviceUnavailableError(str(e)) log.info("Job %s finished: %s", job_id, job_status) @@ -637,6 +680,14 @@ def main() -> int: try: result = _submit_and_run_job(client, args, spec, target_id, artifact_id) break + except RunnerUnavailableError as e: + log.warning("QDC runner unavailable for %s after %ds - job skipped: %s", args.device, args.runner_timeout, e) + write_summary( + JobResult(passed=True, tests={}), + title=f"QDC Tests ({args.device})", + note=f"SKIPPED: Runner did not pick up job within {args.runner_timeout}s. Skipped to avoid stalling CI.", + ) + return 0 except DeviceUnavailableError as e: if attempt < max_attempts: log.warning( diff --git a/scripts/sync-ggml.last b/scripts/sync-ggml.last index 43167cdceab2..6322fbe69f6c 100644 --- a/scripts/sync-ggml.last +++ b/scripts/sync-ggml.last @@ -1 +1 @@ -57e2c2ca2a7cae756b1c4dfafa0cdfef9051d234 +417a024b4fb6bc3116d41af7c067166a039bdf12 diff --git a/src/llama-grammar.cpp b/src/llama-grammar.cpp index 4e096a3684c6..0ef01dbcaff9 100644 --- a/src/llama-grammar.cpp +++ b/src/llama-grammar.cpp @@ -948,6 +948,160 @@ static void llama_grammar_advance_stack( } } +// Left-factor grammar rules to reduce redundant parallel stacks. +// +// When a rule has many alternates (e.g. tool-choice ::= tc0 | tc1 | ... | tc119) +// and the referenced rules share a common element-content prefix, extract that +// prefix so the parser processes it once instead of N times. +// +// Handles two cases: +// 1. Inline common prefix: rule = "ab1" | "ab2" -> rule = "ab" rule', rule' = "1" | "2" +// 2. Cross-rule prefix: rule = A | B | C where A,B,C start with same elements +// -> rule = common_prefix rule', rule' = A_suffix | B_suffix | C_suffix +static void llama_grammar_left_factor(llama_grammar_rules & rules) { + auto elem_eq = [](const llama_grammar_element & a, const llama_grammar_element & b) { + return a.type == b.type && a.value == b.value; + }; + + // Keep the prefix boundary outside character classes. + auto trim_prefix = [](const llama_grammar_rule & rule, size_t start, size_t length) { + while (length > 0) { + const auto type = rule[start + length].type; + if (type != LLAMA_GRETYPE_CHAR_ALT && type != LLAMA_GRETYPE_CHAR_RNG_UPPER) { + break; + } + length--; + } + return length; + }; + + struct alt_info { + size_t rule_idx; + size_t start; + size_t end; + }; + + const size_t n_rules_original = rules.size(); + // Original rules factor at most once; generated rules do not resolve references. + // Each new suffix removes a non-empty prefix. + bool changed = true; + while (changed) { + changed = false; + const size_t n_rules = rules.size(); + + for (size_t ri = 0; ri < n_rules; ri++) { + const auto & rule = rules[ri]; + + // Split rule into alternates + std::vector> alt_ranges; + size_t alt_start = 0; + for (size_t j = 0; j < rule.size(); j++) { + if (rule[j].type == LLAMA_GRETYPE_ALT || rule[j].type == LLAMA_GRETYPE_END) { + alt_ranges.push_back({alt_start, j}); + alt_start = j + 1; + } + } + + if (alt_ranges.size() < 4) { + continue; + } + + // Resolve each alternate: if it's a single RULE_REF, follow it to get the + // actual element sequence from the referenced rule. + std::vector resolved; + resolved.reserve(alt_ranges.size()); + bool all_single_refs = true; + + for (const auto & [astart, aend] : alt_ranges) { + size_t len = aend - astart; + // Resolving references in generated suffixes can expand recursive rules forever. + if (ri < n_rules_original && len == 1 && rule[astart].type == LLAMA_GRETYPE_RULE_REF) { + size_t ref_id = static_cast(rule[astart].value); + if (ref_id < rules.size()) { + size_t ref_end = 0; + for (size_t k = 0; k < rules[ref_id].size(); k++) { + if (rules[ref_id][k].type == LLAMA_GRETYPE_ALT || + rules[ref_id][k].type == LLAMA_GRETYPE_END) { + ref_end = k; + break; + } + } + bool single_alt = (rules[ref_id][ref_end].type == LLAMA_GRETYPE_END); + if (single_alt) { + resolved.push_back({ref_id, 0, ref_end}); + continue; + } + } + } + all_single_refs = false; + resolved.push_back({ri, astart, aend}); + } + + if (!all_single_refs) { + resolved.clear(); + for (const auto & [astart, aend] : alt_ranges) { + resolved.push_back({ri, astart, aend}); + } + } + + size_t prefix_len = 0; + bool prefix_match = true; + while (prefix_match) { + const auto & first = resolved[0]; + if (first.start + prefix_len >= first.end) { + break; + } + const auto & ref_elem = rules[first.rule_idx][first.start + prefix_len]; + + for (size_t ai = 1; ai < resolved.size(); ai++) { + const auto & alt = resolved[ai]; + if (alt.start + prefix_len >= alt.end || + !elem_eq(rules[alt.rule_idx][alt.start + prefix_len], ref_elem)) { + prefix_match = false; + break; + } + } + if (prefix_match) { + prefix_len++; + } + } + + for (const auto & alt : resolved) { + prefix_len = trim_prefix(rules[alt.rule_idx], alt.start, prefix_len); + } + if (prefix_len == 0) { + continue; + } + + uint32_t suffix_choice_id = static_cast(rules.size()); + llama_grammar_rule suffix_choice; + + for (size_t ai = 0; ai < resolved.size(); ai++) { + if (ai > 0) { + suffix_choice.push_back({LLAMA_GRETYPE_ALT, 0}); + } + const auto & alt = resolved[ai]; + for (size_t j = alt.start + prefix_len; j < alt.end; j++) { + suffix_choice.push_back(rules[alt.rule_idx][j]); + } + } + suffix_choice.push_back({LLAMA_GRETYPE_END, 0}); + + llama_grammar_rule new_rule; + const auto & first = resolved[0]; + for (size_t j = 0; j < prefix_len; j++) { + new_rule.push_back(rules[first.rule_idx][first.start + j]); + } + new_rule.push_back({LLAMA_GRETYPE_RULE_REF, suffix_choice_id}); + new_rule.push_back({LLAMA_GRETYPE_END, 0}); + + rules.push_back(std::move(suffix_choice)); + rules[ri] = std::move(new_rule); + changed = true; + } + } +} + static bool llama_grammar_detect_left_recursion( const llama_grammar_rules & rules, size_t rule_index, @@ -1006,7 +1160,7 @@ static bool llama_grammar_detect_left_recursion( } const llama_grammar_rules & llama_grammar_get_rules(const struct llama_grammar * grammar) { - return grammar->rules; + return *grammar->rules; } llama_grammar_stacks & llama_grammar_get_stacks(struct llama_grammar * grammar) { @@ -1035,7 +1189,7 @@ static void llama_grammar_accept_chr( if (!llama_grammar_is_end_of_sequence(match.second)) { new_stack.push_back(match.second); } - llama_grammar_advance_stack(grammar.rules, new_stack, new_stacks); + llama_grammar_advance_stack(*grammar.rules, new_stack, new_stacks); } } @@ -1221,12 +1375,16 @@ struct llama_grammar * llama_grammar_init_impl( } } - // Check for left recursion - std::vector rules_visited(n_rules); - std::vector rules_in_progress(n_rules); - std::vector rules_may_be_empty(n_rules); + // Left-factor rules to reduce redundant parallel stacks + llama_grammar_left_factor(vec_rules); + + // Check for left recursion (use post-factoring rule count) + const size_t n_rules_total = vec_rules.size(); + std::vector rules_visited(n_rules_total); + std::vector rules_in_progress(n_rules_total); + std::vector rules_may_be_empty(n_rules_total); try { - for (size_t i = 0; i < n_rules; i++) { + for (size_t i = 0; i < n_rules_total; i++) { if (rules_visited[i]) { continue; } @@ -1267,7 +1425,7 @@ struct llama_grammar * llama_grammar_init_impl( // then the pointers would be invalidated when the local vec_rules goes out of scope. return new llama_grammar { vocab, - std::move(vec_rules), + std::make_shared(std::move(vec_rules)), std::move(stacks), /* .partial_utf8 = */ {}, /* .lazy = */ false, @@ -1319,12 +1477,16 @@ struct llama_grammar * llama_grammar_init_impl( vec_rules[i].push_back({LLAMA_GRETYPE_END, 0}); } - // Check for left recursion - std::vector rules_visited(n_rules); - std::vector rules_in_progress(n_rules); - std::vector rules_may_be_empty(n_rules); + // Left-factor rules to reduce redundant parallel stacks + llama_grammar_left_factor(vec_rules); + + // Check for left recursion (use post-factoring rule count) + const size_t n_rules_total = vec_rules.size(); + std::vector rules_visited(n_rules_total); + std::vector rules_in_progress(n_rules_total); + std::vector rules_may_be_empty(n_rules_total); try { - for (size_t i = 0; i < n_rules; i++) { + for (size_t i = 0; i < n_rules_total; i++) { if (rules_visited[i]) { continue; } @@ -1378,7 +1540,7 @@ struct llama_grammar * llama_grammar_init_impl( // then the pointers would be invalidated when the local vec_rules goes out of scope. return new llama_grammar { vocab, - std::move(vec_rules), + std::make_shared(std::move(vec_rules)), std::move(stacks), /* .partial_utf8 = */ {}, /* .lazy = */ lazy, @@ -1399,33 +1561,7 @@ void llama_grammar_free_impl(struct llama_grammar * grammar) { } struct llama_grammar * llama_grammar_clone_impl(const struct llama_grammar & grammar) { - auto * result = new llama_grammar { - grammar.vocab, - grammar.rules, - grammar.stacks, - grammar.partial_utf8, - grammar.lazy, - grammar.awaiting_trigger, - grammar.trigger_buffer, - grammar.trigger_buffer_positions, - grammar.trigger_tokens, - grammar.trigger_patterns, - }; - - // redirect elements in stacks to point to new rules - for (size_t is = 0; is < result->stacks.size(); is++) { - for (size_t ie = 0; ie < result->stacks[is].size(); ie++) { - for (size_t ir0 = 0; ir0 < grammar.rules.size(); ir0++) { - for (size_t ir1 = 0; ir1 < grammar.rules[ir0].size(); ir1++) { - if (grammar.stacks[is][ie] == &grammar.rules[ir0][ir1]) { - result->stacks[is][ie] = &result->rules[ir0][ir1]; - } - } - } - } - } - - return result; + return new llama_grammar(grammar); } void llama_grammar_apply_impl(const struct llama_grammar & grammar, llama_token_data_array * cur_p) { @@ -1465,7 +1601,7 @@ void llama_grammar_apply_impl(const struct llama_grammar & grammar, llama_token_ } } - const auto rejects = llama_grammar_reject_candidates(grammar.rules, grammar.stacks, candidates_grammar); + const auto rejects = llama_grammar_reject_candidates(*grammar.rules, grammar.stacks, candidates_grammar); for (const auto & reject : rejects) { cur_p->data[reject.index].logit = -INFINITY; } @@ -1566,7 +1702,7 @@ void llama_grammar_accept_token(struct llama_grammar & grammar, llama_token toke if (!llama_grammar_is_end_of_sequence(pos + 1)) { new_stack.push_back(pos + 1); } - llama_grammar_advance_stack(grammar.rules, new_stack, stacks_new); + llama_grammar_advance_stack(*grammar.rules, new_stack, stacks_new); } } else { llama_grammar_stacks current_stacks = {stack}; diff --git a/src/llama-grammar.h b/src/llama-grammar.h index 2885f770597f..5829d8edc467 100644 --- a/src/llama-grammar.h +++ b/src/llama-grammar.h @@ -3,6 +3,7 @@ #include "llama.h" #include +#include #include #include #include @@ -132,8 +133,8 @@ struct llama_grammar { // note: allow null vocab for testing (not great) const llama_vocab * vocab; - const llama_grammar_rules rules; // TODO: shared ptr - llama_grammar_stacks stacks; + const std::shared_ptr rules; + llama_grammar_stacks stacks; // buffer for partially generated UTF-8 sequence from accepted tokens llama_partial_utf8 partial_utf8; diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 0a0609739ab8..1c6ec1263abc 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -2432,12 +2432,9 @@ ggml_tensor * llm_graph_context::build_moe_ffn( // compute the expert input before the slot lookup, so that the scheduler prefetches it for the CPU part (the router can read a different tensor) ggml_build_forward_expand(gf, cur); - // the experts of host-resident layers may be read from the MoE cache, and part of the misses computed from the host experts - // the CPU part does not support weights before the FFN, LoRAs or rotated experts - const std::array exps = { up_exps, gate_exps, down_exps, gate_up_exps }; - const bool can_cpu_share = !weight_before_ffn && loras->empty() && - std::none_of(exps.begin(), exps.end(), [&](ggml_tensor * w) { return w != nullptr && hdmd != nullptr && hdmd->rot.count(w) > 0; }); - const llm_graph_moe_cache_slots cache = build_moe_cache_slots(selected_experts, up_exps, gate_exps, down_exps, gate_up_exps, can_cpu_share, il); + // the experts of host-resident layers may be read from the MoE cache (see llama_moe_cache::build_lookup) + const llama_moe_cache_lookup cache = moe_cache == nullptr ? llama_moe_cache_lookup{} : + moe_cache->build_lookup(*this, { il, up_exps, gate_exps, down_exps, gate_up_exps, weight_before_ffn }, selected_experts); cur = ggml_reshape_3d(ctx0, cur, n_embd, 1, n_tokens); @@ -2610,14 +2607,12 @@ ggml_tensor * llm_graph_context::build_moe_ffn( return experts; }; - ggml_tensor * experts = build_experts(cur, selected_experts, cache.slots, true); - if (cache.cpu_ids != nullptr) { - // the cached experts and the misses computed from the host experts, each reads the others as zero - // the cached experts come first in the graph, so that they are computed while the misses are - ggml_build_forward_expand(gf, experts); - experts = ggml_add(ctx0, experts, build_experts(cur, selected_experts, cache.cpu_ids, false)); - cb(experts, "ffn_moe_down_merged", il); - } + ggml_tensor * experts = cache.slots == nullptr ? + build_experts(cur, selected_experts, nullptr, true) : + moe_cache->build_experts(*this, cache, cur, selected_experts, + [](ggml_tensor * cur, ggml_tensor * ids, ggml_tensor * mm_ids, bool cached, void * user_data) { + return (*static_cast(user_data))(cur, ids, mm_ids, cached); + }, &build_experts); if (down_exps_s) { cb(experts, "ffn_moe_down_scaled", il); @@ -2676,66 +2671,6 @@ ggml_tensor * llm_graph_context::build_moe_ffn( return moe_out; } -llm_graph_moe_cache_slots llm_graph_context::build_moe_cache_slots( - ggml_tensor * selected_experts, - ggml_tensor * up_exps, - ggml_tensor * gate_exps, - ggml_tensor * down_exps, - ggml_tensor * gate_up_exps, - bool cpu_part, - int il) const { - if (moe_cache == nullptr) { - return { nullptr, nullptr }; - } - - ggml_tensor * cpu_map = cpu_part ? moe_cache->get_cpu_map(il, selected_experts->ne[1]) : nullptr; - ggml_tensor * slot_map = moe_cache->get_slot_map(il, selected_experts->ne[1], selected_experts->ne[0], cpu_map != nullptr); - if (slot_map == nullptr) { - return { nullptr, nullptr }; - } - for (ggml_tensor * w : { up_exps, gate_exps, down_exps, gate_up_exps }) { - 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 }; - } - } - - ggml_tensor * ids = selected_experts; - if (!ggml_is_contiguous(ids)) { - ids = ggml_cont(ctx0, ids); - } - ids = ggml_reshape_1d(ctx0, ids, ggml_nelements(ids)); - - // the slot map is a host weight, so the scheduler starts a new split here and copies it with the copy callback - // the callback reads the selected experts, uploads the missing ones and updates the slot map - ggml_tensor * slots = ggml_get_rows(ctx0, slot_map, ids); // [1, n_expert_used*n_tokens] - if (!ggml_backend_supports_op(moe_cache->backend(il), slots)) { - return { nullptr, nullptr }; - } - ggml_backend_sched_set_tensor_backend(sched, slots, moe_cache->backend(il)); - cb(slots, "ffn_moe_slots", il); - - // add the lookup now: the transform of a Hadamard-folded expert reads host weights and would start its split first - ggml_build_forward_expand(gf, slots); - - // the misses computed from the host experts, read after the lookup has picked them - ggml_tensor * cpu_ids = nullptr; - if (cpu_map != nullptr) { - cpu_ids = ggml_get_rows(ctx0, cpu_map, ids); // [1, n_expert_used*n_tokens] - cpu_ids = ggml_reshape_2d(ctx0, cpu_ids, selected_experts->ne[0], selected_experts->ne[1]); - } - - return { ggml_reshape_2d(ctx0, slots, selected_experts->ne[0], selected_experts->ne[1]), cpu_ids }; -} - // input embeddings with optional lora ggml_tensor * llm_graph_context::build_inp_embd(ggml_tensor * tok_embd, float tok_scale) const { const int64_t n_embd_inp = hparams.n_embd_inp(); diff --git a/src/llama-graph.h b/src/llama-graph.h index 4acbc11ffa8e..8d5cabc8bd87 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -1038,11 +1038,6 @@ struct llm_graph_amax_src1 { ggml_tensor * scale_s; // scale to undo on the matmul result, or nullptr }; -struct llm_graph_moe_cache_slots { - ggml_tensor * slots; // [n_expert_used, n_tokens] slots of the selected experts in the MoE cache, or nullptr - ggml_tensor * cpu_ids; // [n_expert_used, n_tokens] misses computed from the host experts, -1 for the other experts, or nullptr -}; - struct llm_graph_context { const llama_model & model; @@ -1146,7 +1141,7 @@ struct llm_graph_context { ggml_tensor * w_s = nullptr) const; // do mat_mul_id, while optionally apply lora and per-expert scale - // if slots is set, the experts are selected by slots instead of ids, from the MoE cache if cached (see build_moe_cache_slots) + // if slots is set, the experts are selected by slots instead of ids, from the MoE cache if cached (see llama_moe_cache::build_lookup) ggml_tensor * build_lora_mm_id( ggml_tensor * w, // ggml_tensor * as ggml_tensor * cur, // ggml_tensor * b @@ -1259,17 +1254,6 @@ struct llm_graph_context { ggml_tensor * post_exp_norm = nullptr, float post_exp_norm_eps = 1e-5f) const; - // the slots of the selected experts in the MoE cache, nullptr if the experts of the layer are not read from the cache - // with cpu_part, also the misses computed from the host experts, if the cache leaves any to the CPU - llm_graph_moe_cache_slots build_moe_cache_slots( - ggml_tensor * selected_experts, - ggml_tensor * up_exps, - ggml_tensor * gate_exps, - ggml_tensor * down_exps, - ggml_tensor * gate_up_exps, - bool cpu_part, - int il) const; - // // inputs // diff --git a/src/llama-moe-cache.cpp b/src/llama-moe-cache.cpp index 965f6a177612..1070b92b8a13 100644 --- a/src/llama-moe-cache.cpp +++ b/src/llama-moe-cache.cpp @@ -1,5 +1,6 @@ #include "llama-moe-cache.h" +#include "llama-graph.h" #include "llama-impl.h" #include "llama-memory.h" #include "llama-model.h" @@ -635,6 +636,7 @@ struct llama_moe_cache::impl { } } + // the device that caches layer il ggml_backend_t backend(int32_t il) const { return devices[groups[layers[il].ig].id].backend; } @@ -684,6 +686,8 @@ struct llama_moe_cache::impl { } } + // the slot map of layer il, if its experts can be read from the cache for n_tokens tokens, nullptr otherwise + // cpu_part: the graph computes the misses in the CPU map of the layer (see get_cpu_map) ggml_tensor * get_slot_map(int32_t il, int64_t n_tokens, int64_t n_expert_used, bool cpu_part) const { if (il < 0 || il >= (int32_t) layers.size() || layers[il].ig < 0) { return nullptr; @@ -698,6 +702,8 @@ struct llama_moe_cache::impl { return cpu_part ? l.slot_map_cpu : l.slot_map; } + // the experts of layer il computed on the CPU: I32 [1, n_expert] in host memory, e for these experts, -1 for the others + // nullptr if no misses of layer il are computed on the CPU for ubatches of n_tokens tokens ggml_tensor * get_cpu_map(int32_t il, int64_t n_tokens) const { if (il < 0 || il >= (int32_t) layers.size() || layers[il].cpu_map == nullptr) { return nullptr; @@ -791,7 +797,7 @@ struct llama_moe_cache::impl { } } GGML_ASSERT(ggml_is_contiguous(sel)); - GGML_ASSERT(sel->op == GGML_OP_RESHAPE); // of the [n_expert_used, n_tokens] ids, see build_moe_cache_slots + GGML_ASSERT(sel->op == GGML_OP_RESHAPE); // of the [n_expert_used, n_tokens] ids, see build_lookup const int32_t n_used = (int32_t) sel->src[0]->ne[0]; @@ -878,20 +884,82 @@ llama_moe_cache::llama_moe_cache(const llama_model & model, bool no_alloc, const llama_moe_cache::~llama_moe_cache() = default; -ggml_backend_t llama_moe_cache::backend(int32_t il) const { - return pimpl->backend(il); +ggml_tensor * llama_moe_cache::get_experts(const ggml_tensor * w) const { + return pimpl->get_experts(w); } -ggml_tensor * llama_moe_cache::get_slot_map(int32_t il, int64_t n_tokens, int64_t n_expert_used, bool cpu_part) const { - return pimpl->get_slot_map(il, n_tokens, n_expert_used, cpu_part); -} +llama_moe_cache_lookup llama_moe_cache::build_lookup(const llm_graph_context & g, const llama_moe_cache_layer & layer, ggml_tensor * selected_experts) const { + const int32_t il = layer.il; + ggml_context * ctx0 = g.ctx0; -ggml_tensor * llama_moe_cache::get_experts(const ggml_tensor * w) const { - return pimpl->get_experts(w); + // part of the misses may be computed from the host experts, but not with weights before the FFN, LoRAs or rotated experts + bool cpu_part = !layer.weight_before_ffn && g.loras->empty(); + for (ggml_tensor * w : { layer.up_exps, layer.gate_exps, layer.down_exps, layer.gate_up_exps }) { + cpu_part = cpu_part && !(w != nullptr && g.hdmd != nullptr && g.hdmd->rot.count(w) > 0); + } + + ggml_tensor * cpu_map = cpu_part ? pimpl->get_cpu_map(il, selected_experts->ne[1]) : nullptr; + ggml_tensor * slot_map = pimpl->get_slot_map(il, selected_experts->ne[1], selected_experts->ne[0], cpu_map != nullptr); + if (slot_map == nullptr) { + return {}; + } + for (ggml_tensor * w : { layer.up_exps, layer.gate_exps, layer.down_exps, layer.gate_up_exps }) { + if (w == nullptr) { + continue; + } + ggml_tensor * experts = pimpl->get_experts(w); + if (experts == nullptr) { + return {}; + } + // 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 == layer.down_exps ? selected_experts->ne[0] : 1, selected_experts->ne[1]); + if (!ggml_backend_supports_op(pimpl->backend(il), ggml_mul_mat_id(ctx0, experts, b, selected_experts))) { + return {}; + } + } + + ggml_tensor * ids = selected_experts; + if (!ggml_is_contiguous(ids)) { + ids = ggml_cont(ctx0, ids); + } + ids = ggml_reshape_1d(ctx0, ids, ggml_nelements(ids)); + + // the slot map is a host weight, so the scheduler starts a new split here and copies it with the copy callback + // the callback reads the selected experts, uploads the missing ones and updates the slot map + ggml_tensor * slots = ggml_get_rows(ctx0, slot_map, ids); // [1, n_expert_used*n_tokens] + if (!ggml_backend_supports_op(pimpl->backend(il), slots)) { + return {}; + } + ggml_backend_sched_set_tensor_backend(g.sched, slots, pimpl->backend(il)); + g.cb(slots, "ffn_moe_slots", il); + + // add the lookup now: the transform of a Hadamard-folded expert reads host weights and would start its split first + ggml_build_forward_expand(g.gf, slots); + + // the misses computed from the host experts, read after the lookup has picked them + ggml_tensor * cpu_ids = nullptr; + if (cpu_map != nullptr) { + cpu_ids = ggml_get_rows(ctx0, cpu_map, ids); // [1, n_expert_used*n_tokens] + cpu_ids = ggml_reshape_2d(ctx0, cpu_ids, selected_experts->ne[0], selected_experts->ne[1]); + } + + return { il, ggml_reshape_2d(ctx0, slots, selected_experts->ne[0], selected_experts->ne[1]), cpu_ids }; } -ggml_tensor * llama_moe_cache::get_cpu_map(int32_t il, int64_t n_tokens) const { - return pimpl->get_cpu_map(il, n_tokens); +ggml_tensor * llama_moe_cache::build_experts(const llm_graph_context & g, const llama_moe_cache_lookup & lookup, + ggml_tensor * cur, ggml_tensor * selected_experts, llama_moe_cache_build_experts_t build, void * user_data) const { + GGML_ASSERT(lookup.slots != nullptr); + + ggml_tensor * experts = build(cur, selected_experts, lookup.slots, true, user_data); + if (lookup.cpu_ids != nullptr) { + // the cached experts and the misses computed from the host experts, each reads the others as zero + // the cached experts come first in the graph, so that they are computed while the misses are + ggml_build_forward_expand(g.gf, experts); + experts = ggml_add(g.ctx0, experts, build(cur, selected_experts, lookup.cpu_ids, false, user_data)); + g.cb(experts, "ffn_moe_down_merged", lookup.il); + } + + return experts; } bool llama_moe_cache::copy(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst, ggml_cgraph * graph) { diff --git a/src/llama-moe-cache.h b/src/llama-moe-cache.h index 636bc4559c19..833eac360f63 100644 --- a/src/llama-moe-cache.h +++ b/src/llama-moe-cache.h @@ -7,6 +7,28 @@ #include struct llama_model; +struct llm_graph_context; + +// the experts of a MoE layer, as llm_graph_context::build_moe_ffn passes them to the MoE cache +struct llama_moe_cache_layer { + int32_t il; + ggml_tensor * up_exps; + ggml_tensor * gate_exps; + ggml_tensor * down_exps; + ggml_tensor * gate_up_exps; + bool weight_before_ffn; // the router weights scale the expert input +}; + +// the lookup of the selected experts of a layer in the MoE cache, see llama_moe_cache::build_lookup +struct llama_moe_cache_lookup { + int32_t il = -1; + ggml_tensor * slots = nullptr; // [n_expert_used, n_tokens] slots of the selected experts in the MoE cache, nullptr if the layer does not read the cache + ggml_tensor * cpu_ids = nullptr; // [n_expert_used, n_tokens] misses computed from the host experts, -1 for the other experts, or nullptr +}; + +// builds the experts selected by mm_ids up to the down projection, from the MoE cache if cached: [n_embd, n_expert_used, n_tokens] +// cur is the expert input and ids are the selected experts, for the biases and scales (see llm_graph_context::build_moe_ffn) +using llama_moe_cache_build_experts_t = ggml_tensor * (*)(ggml_tensor * cur, ggml_tensor * ids, ggml_tensor * mm_ids, bool cached, void * user_data); // keeps recently and repeatedly used experts of host-resident MoE layers in a device buffer // each layer has a slot map in host memory: when the scheduler copies it to the device, the copy callback uploads the missing experts @@ -17,19 +39,19 @@ class llama_moe_cache { llama_moe_cache(const llama_model & model, bool no_alloc, const std::vector & backends, const std::vector & bufts, size_t size, float cpu_share); ~llama_moe_cache(); - // the device that caches layer il - ggml_backend_t backend(int32_t il) const; - - // the slot map of layer il, if its experts can be read from the cache for n_tokens tokens, nullptr otherwise - // cpu_part: the graph computes the misses in the CPU map of the layer (see get_cpu_map) - ggml_tensor * get_slot_map(int32_t il, int64_t n_tokens, int64_t n_expert_used, bool cpu_part) const; - // the experts of w in the cache, nullptr if w is not cached ggml_tensor * get_experts(const ggml_tensor * w) const; - // the experts of layer il computed on the CPU: I32 [1, n_expert] in host memory, e for these experts, -1 for the others - // nullptr if no misses of layer il are computed on the CPU for ubatches of n_tokens tokens - ggml_tensor * get_cpu_map(int32_t il, int64_t n_tokens) const; + // the graph of a MoE layer, built by llm_graph_context::build_moe_ffn in two steps: + + // 1. the lookup of the selected experts in the cache, built after the expert input and before the expert matmuls + // returns no slots if the layer does not read its experts from the cache for this ubatch + llama_moe_cache_lookup build_lookup(const llm_graph_context & g, const llama_moe_cache_layer & layer, ggml_tensor * selected_experts) const; + + // 2. the experts of a layer with slots, from the cache and from the host experts: [n_embd, n_expert_used, n_tokens] + // calls build synchronously; does not retain user_data + ggml_tensor * build_experts(const llm_graph_context & g, const llama_moe_cache_lookup & lookup, + ggml_tensor * cur, ggml_tensor * selected_experts, llama_moe_cache_build_experts_t build, void * user_data) const; // ggml_backend_sched copy callback, returns false if src is not a slot map bool copy(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst, ggml_cgraph * graph); diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index e19ba45bbb94..177bcedb2ff6 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -2975,6 +2975,7 @@ struct test_rms_norm_mul_rope : public test_case { int mode; const bool yarn; const bool truncate; + const ggml_type type; // type of a, the weights are F32 std::string op_desc(ggml_tensor * t) override { GGML_UNUSED(t); @@ -2984,18 +2985,22 @@ struct test_rms_norm_mul_rope : public test_case { bool run_whole_graph() override { return true; } std::string vars() override { - return VARS_TO_STR11(ne, eps, multi_add, mul, rope, set_rows, broadcast, mode, set_rows_type, yarn, truncate); + std::string s = VARS_TO_STR11(ne, eps, multi_add, mul, rope, set_rows, broadcast, mode, set_rows_type, yarn, truncate); + if (type != GGML_TYPE_F32) { + s += "," + VAR_TO_STR(type); + } + return s; } test_rms_norm_mul_rope(std::array ne, float eps = 1e-6f, bool multi_add = false, bool set_rows = false, bool broadcast = false, int mode = GGML_ROPE_TYPE_NORMAL, bool mul = true, bool rope = true, ggml_type set_rows_type = GGML_TYPE_F16, - bool yarn = false, bool truncate = true) + bool yarn = false, bool truncate = true, ggml_type type = GGML_TYPE_F32) : ne(ne), eps(eps), multi_add(multi_add), mul(mul), rope(rope), set_rows(set_rows), broadcast(broadcast), - set_rows_type(set_rows_type), mode(mode), yarn(yarn), truncate(truncate) {} + set_rows_type(set_rows_type), mode(mode), yarn(yarn), truncate(truncate), type(type) {} ggml_tensor * build_graph(ggml_context * ctx) override { - ggml_tensor * a = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, ne[0], ne[1], ne[2], ne[3]); + ggml_tensor * a = ggml_new_tensor_4d(ctx, type, ne[0], ne[1], ne[2], ne[3]); ggml_tensor * b = nullptr; ggml_tensor * c = nullptr; @@ -3074,6 +3079,10 @@ struct test_rms_norm_mul_rope : public test_case { } double max_nmse_err() override { + if (type == GGML_TYPE_BF16) { + // the fused kernel rounds to BF16 once, the CPU rounds after each op + return 1e-4; + } if (ne[0] == 8192) { return 5e-6; } @@ -4036,6 +4045,11 @@ struct test_rms_norm : public test_case { } } + double max_nmse_err() override { + // the row scale can differ by a few F32 ulps between backends, so a few outputs round to the neighbouring BF16 value + return type == GGML_TYPE_BF16 ? 1e-5 : test_case::max_nmse_err(); + } + float grad_eps() override { return 1.0f; } @@ -4090,6 +4104,8 @@ struct test_rms_norm_mul_add : public test_case { const bool post_mul; const bool alias_rms_input; const bool weight_broadcast; + const ggml_type type_w; // type of b and d, GGML_TYPE_COUNT -> same as a + const ggml_type type_add; // type of c, GGML_TYPE_COUNT -> same as b std::string op_desc(ggml_tensor * t) override { GGML_UNUSED(t); @@ -4099,22 +4115,33 @@ struct test_rms_norm_mul_add : public test_case { bool run_whole_graph() override { return true; } std::string vars() override { - return VARS_TO_STR8(type, ne, eps, broadcast, multi_add, post_mul, alias_rms_input, weight_broadcast); + std::string s = VARS_TO_STR8(type, ne, eps, broadcast, multi_add, post_mul, alias_rms_input, weight_broadcast); + if (type_w != GGML_TYPE_COUNT) { + s += "," + VAR_TO_STR(type_w); + } + if (type_add != GGML_TYPE_COUNT) { + s += "," + VAR_TO_STR(type_add); + } + return s; } test_rms_norm_mul_add(ggml_type type = GGML_TYPE_F32, std::array ne = {64, 5, 4, 3}, float eps = 1e-6f, bool broadcast = false, bool multi_add = false, bool post_mul = false, - bool alias_rms_input = false, bool weight_broadcast = false) + bool alias_rms_input = false, bool weight_broadcast = false, ggml_type type_w = GGML_TYPE_COUNT, + ggml_type type_add = GGML_TYPE_COUNT) : type(type), ne(ne), eps(eps), broadcast(broadcast), multi_add(multi_add), post_mul(post_mul), - alias_rms_input(alias_rms_input), weight_broadcast(weight_broadcast) {} + alias_rms_input(alias_rms_input), weight_broadcast(weight_broadcast), type_w(type_w), type_add(type_add) {} ggml_tensor * build_graph(ggml_context * ctx) override { std::array broadcast_dims = {ne[0]*2, ne[1]*3, ne[2]*3, ne[3]*4}; + const ggml_type tw = type_w == GGML_TYPE_COUNT ? type : type_w; + const ggml_type ta = type_add == GGML_TYPE_COUNT ? tw : type_add; + ggml_tensor * a = ggml_new_tensor(ctx, type, 4, broadcast ? broadcast_dims.data() : ne.data()); - ggml_tensor * b = weight_broadcast ? ggml_new_tensor_1d(ctx, type, ne[0]) : ggml_new_tensor(ctx, type, 4, ne.data()); - ggml_tensor * c = ggml_new_tensor(ctx, type, 4, ne.data()); + ggml_tensor * b = weight_broadcast ? ggml_new_tensor_1d(ctx, tw, ne[0]) : ggml_new_tensor(ctx, tw, 4, ne.data()); + ggml_tensor * c = ggml_new_tensor(ctx, ta, 4, ne.data()); ggml_tensor * d = nullptr; ggml_set_param(a); @@ -4127,7 +4154,7 @@ struct test_rms_norm_mul_add : public test_case { // Use a, b and c early, so we don't end up with an OP_NONE between rms_norm and mul a = ggml_add(ctx, ggml_add(ctx, a, b), c); if (post_mul) { - d = ggml_new_tensor_1d(ctx, type, 1); + d = ggml_new_tensor_1d(ctx, tw, 1); ggml_set_param(d); ggml_set_name(d, "d"); a = ggml_add(ctx, a, d); @@ -4151,6 +4178,11 @@ struct test_rms_norm_mul_add : public test_case { } } + double max_nmse_err() override { + // fused ops round to BF16 once, the CPU rounds after each op + return type == GGML_TYPE_BF16 ? 1e-4 : test_case::max_nmse_err(); + } + float grad_eps() override { return 1.0f; } @@ -12012,6 +12044,7 @@ static std::vector> make_test_cases_eval() { for (bool v : { false, true }) { test_cases.emplace_back(new test_norm(GGML_TYPE_F32, { n, 5, 4, 3 }, v, eps)); test_cases.emplace_back(new test_rms_norm(GGML_TYPE_F32, { n, 5, 4, 3 }, v, eps)); + test_cases.emplace_back(new test_rms_norm(GGML_TYPE_BF16, { n, 5, 4, 3 }, v, eps)); } test_cases.emplace_back(new test_norm(GGML_TYPE_F32, { n, 5, 4, 3 }, false, eps, true)); test_cases.emplace_back(new test_norm_scale(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, false, 1.5f)); @@ -12030,12 +12063,14 @@ static std::vector> make_test_cases_eval() { for (bool v : { false, true }) { test_cases.emplace_back(new test_norm(GGML_TYPE_F32, { n, 5, 4, 3 }, v, eps)); test_cases.emplace_back(new test_rms_norm(GGML_TYPE_F32, { n, 5, 4, 3 }, v, eps)); + test_cases.emplace_back(new test_rms_norm(GGML_TYPE_BF16, { n, 5, 4, 3 }, v, eps)); } } } // in-place tests test_cases.emplace_back(new test_rms_norm(GGML_TYPE_F32, {64, 5, 4, 3}, false, 1e-6f, true)); + test_cases.emplace_back(new test_rms_norm(GGML_TYPE_BF16, {64, 5, 4, 3}, false, 1e-6f, true)); // shapes below exceed the CUDA gridDim.y/gridDim.z limit of 65535 (#27901) test_cases.emplace_back(new test_norm (GGML_TYPE_F32, {4, 1, 65536, 1}, false, 1e-6f)); test_cases.emplace_back(new test_rms_norm (GGML_TYPE_F32, {4, 1, 65536, 1}, false, 1e-6f, false)); @@ -12049,6 +12084,19 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, {n, 3, 2, 1}, 1e-6f, false, false, false, false, true)); } + // BF16 x with F32 weights, n > 1 because the NMSE of a single BF16 output is too noisy + // the widths cover every CUDA block size, with and without 4-value loads + for (uint32_t n : {127, 128, 512, 1024, 2048, 2816, 4096, 8192, 16385}) { + test_cases.emplace_back(new test_rms_norm(GGML_TYPE_BF16, {n, 3, 2, 1})); + test_cases.emplace_back(new test_rms_norm_mul_rope({n, 3, 2, 1}, 1e-6f, false, false, true, GGML_ROPE_TYPE_NORMAL, true, false, GGML_TYPE_F16, false, true, GGML_TYPE_BF16)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, {n, 3, 2, 1}, 1e-6f, false, false, false, false, true, GGML_TYPE_F32)); + // BF16 residual added after the norm (post-norm models, e.g. Gemma) + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, {n, 3, 2, 1}, 1e-6f, false, false, false, false, true, GGML_TYPE_F32, GGML_TYPE_BF16)); + for (bool multi_add : {false, true}) { + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, {n, 1, 1, 1}, 1e-6f, false, multi_add, false, false, false, GGML_TYPE_F32)); + } + } + for (ggml_type set_rows_type : { GGML_TYPE_F32, GGML_TYPE_F16 }) { test_cases.emplace_back(new test_rms_norm_mul_rope({ 256, 1, 1, 1 }, 1e-6f, false, true, false, GGML_ROPE_TYPE_NORMAL, false, false, set_rows_type)); test_cases.emplace_back(new test_rms_norm_mul_rope({ 128, 4, 3, 1 }, 1e-6f, false, true, false, GGML_ROPE_TYPE_NORMAL, false, false, set_rows_type)); @@ -12074,6 +12122,9 @@ static std::vector> make_test_cases_eval() { for (uint32_t n : { 64, 1025 }) { test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, false)); test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, true)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { n, 5, 4, 3 }, eps, false, false, false, false, false, GGML_TYPE_F32)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { n, 5, 4, 3 }, eps, true, false, false, false, false, GGML_TYPE_F32)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { n, 5, 4, 3 }, eps, true, false, false, false, false, GGML_TYPE_F32, GGML_TYPE_BF16)); test_cases.emplace_back(new test_norm_mul_add(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, false)); test_cases.emplace_back(new test_norm_mul_add(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, true)); test_cases.emplace_back(new test_add_rms_norm(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, false)); @@ -12101,6 +12152,9 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 256, 4, 3, 2 }, 1e-6f, false, false, true, false, true)); test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 1536, 1, 1, 1 }, 1e-6f, false, false, false, true)); test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 256, 4, 1, 1 }, 1e-6f, false, false, false, true)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 1536, 1, 1, 1 }, 1e-6f, false, false, true, false, false, GGML_TYPE_F32)); + // the ADD operand is the BF16 input itself, added in place + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 1536, 1, 1, 1 }, 1e-6f, false, false, false, true, false, GGML_TYPE_F32)); test_cases.emplace_back(new test_rms_norm_mul_rope({128, 4, 7, 2})); test_cases.emplace_back(new test_rms_norm_mul_rope({128, 4, 7, 2}, 1e-6f, false, true)); @@ -14164,8 +14218,10 @@ static std::vector> make_test_cases_perf() { // RMS_NORM and fused variants at decode and prefill shapes for (int64_t n_tokens : {1, 512}) { - test_cases.emplace_back(new test_rms_norm(GGML_TYPE_F32, {4096, n_tokens, 1, 1})); - test_cases.emplace_back(new test_rms_norm(GGML_TYPE_F32, {128, 32*n_tokens, 1, 1})); + for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_BF16}) { + test_cases.emplace_back(new test_rms_norm(type, {4096, n_tokens, 1, 1})); + test_cases.emplace_back(new test_rms_norm(type, {128, 32*n_tokens, 1, 1})); + } test_cases.emplace_back(new test_rms_norm_mul_rope({4096, n_tokens, 1, 1}, 1e-6f, false, false, true, GGML_ROPE_TYPE_NORMAL, true, false)); test_cases.emplace_back(new test_rms_norm_mul_rope({128, 32, n_tokens, 1}, 1e-6f, false, false, true, GGML_ROPE_TYPE_NEOX)); test_cases.emplace_back(new test_rms_norm_mul_rope({128, 8, n_tokens, 1}, 1e-6f, false, true, true, GGML_ROPE_TYPE_NEOX)); diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp index 2c59d1222a52..7752015c8830 100644 --- a/tests/test-chat.cpp +++ b/tests/test-chat.cpp @@ -5206,6 +5206,25 @@ static void test_template_output_peg_parsers(bool detailed_debug) { .expect_reconstruction() .run(); + tst.test("I'm\nthinkingHello, world!\nWhat's up?") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .chat_template_kwargs({ { "reasoning_effort", R"("low")" } }) + .expect(message_assist_thoughts) + .run(); + + tst.test( + "I'm\nthinking\n" + "special_function\n" + "arg1\n" + "1\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .tools({ special_function_tool }) + .chat_template_kwargs({ { "reasoning_effort", R"("medium")" } }) + .expect(message_assist_call_thoughts) + .run(); + tst.test( "I'm\nthinking\n" "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n" diff --git a/tests/test-grammar-integration.cpp b/tests/test-grammar-integration.cpp index 75bfca645f00..a7a7e968ef42 100644 --- a/tests/test-grammar-integration.cpp +++ b/tests/test-grammar-integration.cpp @@ -193,6 +193,19 @@ static void test_schema(const std::string & test_desc, const std::string & schem } static void test_simple_grammar() { + test_grammar( + "left factor leading empty suffix", + "root ::= \"ab\" | \"abc\" | \"abd\" | \"abe\"", + {"ab", "abc", "abd", "abe"}, {"", "a", "abb", "abcc"}); + test_grammar( + "left factor middle empty suffix", + "root ::= \"abc\" | \"ab\" | \"abd\" | \"abe\"", + {"ab", "abc", "abd", "abe"}, {"", "a", "abb", "abcc"}); + test_grammar( + "left factor recursive references", + "root ::= \"ok\" | choice\nchoice ::= a | b | c | d\na ::= \"x\" a\nb ::= \"x\" b\nc ::= \"x\" c\nd ::= \"x\" d", + {"ok"}, {"", "x", "xx", "okx"}); + test_schema( "min 0", R"""({ @@ -623,6 +636,19 @@ static void test_special_chars() { "🔵🟠abc🟠🔵" } ); + + test_grammar( + "skip left factoring inside character classes", + "root ::= [ab] \"x\" | [ac] \"x\" | [ad] \"x\" | [ae] \"x\"", + {"ax", "bx", "cx", "dx", "ex"}, {"", "a", "fx", "axx"}); + test_grammar( + "skip left factoring inside character ranges", + "root ::= [a-b] \"x\" | [a-c] \"x\" | [a-d] \"x\" | [a-e] \"x\"", + {"ax", "bx", "cx", "dx", "ex"}, {"", "a", "fx", "axx"}); + test_grammar( + "left factor referenced character alternatives", + "root ::= a | b | c | d\na ::= \"p\" [a] \"x\"\nb ::= \"p\" [ab] \"x\"\nc ::= \"p\" [ac] \"x\"\nd ::= \"p\" [ad] \"x\"", + {"pax", "pbx", "pcx", "pdx"}, {"", "px", "pex", "paxx"}); } static void test_quantifiers() { diff --git a/tools/mtmd/requirements.txt b/tools/mtmd/requirements.txt index d646ca7b02f2..5da6f3de3988 100644 --- a/tools/mtmd/requirements.txt +++ b/tools/mtmd/requirements.txt @@ -1,6 +1,8 @@ -r ../../requirements/requirements-convert_legacy_llama.txt --extra-index-url https://download.pytorch.org/whl/cpu -pillow~=11.3.0 +pillow~=12.3.0 -torch==2.11.0 # check_requirements: ignore "==" -torchvision==0.26.0; platform_machine != "s390x" # check_requirements: ignore "==" +torch==2.11.0; python_version < "3.15" # check_requirements: ignore "==" +torch==2.15.0; python_version >= "3.15" # check_requirements: ignore "==" +torchvision==0.26.0; platform_machine != "s390x" and python_version < "3.15" # check_requirements: ignore "==" +torchvision==0.29.2; platform_machine != "s390x" and python_version >= "3.15" # check_requirements: ignore "==" diff --git a/tools/server/README.md b/tools/server/README.md index 27d1417518f4..066ecb4ddade 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -1654,8 +1654,6 @@ LFM3-Omni is not trained to reason, run it with `--reasoning off` so that its tu Tools go into the system prompt with the chat template, and the tool calls are parsed as in `/v1/chat/completions`. The client runs the calls of a response, sends their results as `function_call_output` items, then asks for the next response. -See [examples/realtime_client.py](../../examples/realtime_client.py) for a client with the `openai` library. - ### POST `/v1/audio/speech`: OpenAI-compatible Speech API Generates speech from text, for models that can generate audio. The request is converted to a [`/tts`](#post-tts-generate-speech-audio-from-text) request, so the `/tts` options such as `lang`, `seed` or `speaker_ref_b64` can also be used. diff --git a/tools/server/tests/requirements.txt b/tools/server/tests/requirements.txt index 3cea52523740..1a490b5cc236 100644 --- a/tools/server/tests/requirements.txt +++ b/tools/server/tests/requirements.txt @@ -2,7 +2,7 @@ pytest~=8.3.3 pytest-xdist~=3.6 filelock~=3.16 numpy~=2.2.6; python_version < "3.14" -numpy~=2.4.6; python_version >= "3.14" +numpy~=2.5.4; python_version >= "3.14" openai~=2.14.0 prometheus-client~=0.20.0 requests~=2.32.3 diff --git a/tools/server/tests/unit/test_router.py b/tools/server/tests/unit/test_router.py index e4e62086b0ed..b5c6fcdae70a 100644 --- a/tools/server/tests/unit/test_router.py +++ b/tools/server/tests/unit/test_router.py @@ -934,24 +934,24 @@ def test_router_download_drops_stale_partials(): 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() + lan_ip = get_lan_ip(server) + if lan_ip is None: + pytest.skip("no LAN address reachable from this host") # ty: ignore[too-many-positional-arguments] 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={ + res = server.make_request("POST", "/chat/completions", data=body, host=lan_ip, headers={ "Origin": f"http://{lan_ip}:{server.server_port}", "Sec-Fetch-Site": "same-origin", }) - assert res.status_code == 200, res.text + assert res.status_code == 200, res.body - res = requests.post(server.make_url("/chat/completions", host="127.0.0.1"), json=body, headers={"Origin": "http://evil.com"}) + res = server.make_request("POST", "/chat/completions", data=body, host="127.0.0.1", headers={"Origin": "http://evil.com"}) assert res.status_code == 403 diff --git a/tools/server/tests/unit/test_security.py b/tools/server/tests/unit/test_security.py index ceec582acf0d..ef4e48fa8cbd 100644 --- a/tools/server/tests/unit/test_security.py +++ b/tools/server/tests/unit/test_security.py @@ -170,16 +170,16 @@ def test_cors_origins_localhost_blocks_simple_requests(headers: dict, expected_s 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() + lan_ip = get_lan_ip(server) + if lan_ip is None: + pytest.skip("no LAN address reachable from this host") # ty: ignore[too-many-positional-arguments] # UI opened via LAN address: Origin matches Host url = server.make_url("/tokenize", host=lan_ip) - res = requests.post(url, data='{"content": "hello"}', headers={ + res = requests.post(url, data='{"content": "hello"}', timeout=DEFAULT_REQUEST_TIMEOUT, headers={ "Content-Type": "text/plain", "Origin": f"http://{lan_ip}:{server.server_port}", }) diff --git a/tools/server/tests/unit/test_tools_builtin.py b/tools/server/tests/unit/test_tools_builtin.py index b3af7360443b..b6673a089b09 100755 --- a/tools/server/tests/unit/test_tools_builtin.py +++ b/tools/server/tests/unit/test_tools_builtin.py @@ -53,15 +53,16 @@ def test_tools_builtin_grep_search(): assert "Total matches: 1" in text -def test_tools_builtin_read_file(): +def test_tools_builtin_read_file(tmp_path): global server server.start() - this_file = os.path.join(PROJECT_ROOT, "tools", "server", "tests", "unit", "test_tools_builtin.py") - res = call_tool("read_file", {"path": this_file}) - text = res["plain_text_response"] - assert GREP_MARKER in text - assert "def test_tools_builtin_read_file" in text + # a file of its own keeps the test below the read limit, unlike this file which grows with every test + path = str(tmp_path / "read.txt") + with open(path, "w", newline="\n") as f: + f.write("line1\nline2\nline3\n") + res = call_tool("read_file", {"path": path}) + assert res["plain_text_response"] == "line1\nline2\nline3\n" def test_tools_builtin_write_then_edit_file(tmp_path): @@ -128,27 +129,21 @@ def test_tools_builtin_exec_shell_command_stream(): assert "[exit code: 0]" in chunks -def test_tools_builtin_cwd_header(): +def test_tools_builtin_cwd_header(tmp_path): global server server.start() - cwd_dir = os.path.join(PROJECT_ROOT, "tools", "server", "tests", "unit") - headers = {"x-tool-cwd": cwd_dir} + headers = {"x-tool-cwd": str(tmp_path)} - res = call_tool("read_file", {"path": "test_tools_builtin.py"}, headers=headers) - assert GREP_MARKER in res["plain_text_response"] + (tmp_path / "cwd.txt").write_text("cwd-content") + res = call_tool("read_file", {"path": "cwd.txt"}, headers=headers) + assert "cwd-content" in res["plain_text_response"] # exec_shell_command should also run with that directory as its working directory: - # writing to a relative filename must land inside cwd_dir + # writing to a relative filename must land inside it marker_name = "llama_cpp_test_tools_builtin_cwd_marker.txt" - marker_path = os.path.join(cwd_dir, marker_name) - try: - command = f"echo hello > {marker_name}" - call_tool("exec_shell_command", {"command": command}, headers=headers) - assert os.path.exists(marker_path) - finally: - if os.path.exists(marker_path): - os.remove(marker_path) + call_tool("exec_shell_command", {"command": f"echo hello > {marker_name}"}, headers=headers) + assert (tmp_path / marker_name).exists() def _container_engine_unavailable_reason(engine: str) -> str | None: diff --git a/tools/server/tests/unit/test_vision_api.py b/tools/server/tests/unit/test_vision_api.py index cad45ee9b5b4..3c835fd6d2d3 100644 --- a/tools/server/tests/unit/test_vision_api.py +++ b/tools/server/tests/unit/test_vision_api.py @@ -39,6 +39,9 @@ def create_server(): global server os.environ['LLAMA_MEDIA_MARKER'] = '<__media__>' server = ServerPreset.tinygemma3() + # the test images are on huggingface.co, which resolves to a private address on runners inside the HF network + # test_vision_image_url_private_address covers the private address check + server.media_allow_private_urls = True def test_models_supports_multimodal_capability(): global server diff --git a/tools/server/tests/utils.py b/tools/server/tests/utils.py index 71470c2b612e..56c88b354007 100644 --- a/tools/server/tests/utils.py +++ b/tools/server/tests/utils.py @@ -34,6 +34,9 @@ # per-request timeout, a hung server fails the test instead of stalling the CI for hours DEFAULT_REQUEST_TIMEOUT = 600 +# timeout of the reachability probe of the LAN address +LAN_PROBE_TIMEOUT = 5 + class ServerResponse: headers: dict @@ -805,7 +808,7 @@ def download_file(url: str, output_file_path: str | None = None) -> str: return output_file -def get_lan_ip() -> str | None: +def get_lan_ip(server: ServerProcess) -> str | None: # address of the interface that routes outside, no packet is sent import socket try: @@ -814,7 +817,14 @@ def get_lan_ip() -> str | None: ip = s.getsockname()[0] except OSError: return None - return None if ip.startswith("127.") else ip + if ip.startswith("127."): + return None + # a host can fail to reach its own LAN address (firewall, VPN, system proxy) + try: + requests.get(server.make_url("/health", host=ip), timeout=LAN_PROBE_TIMEOUT) + except requests.exceptions.RequestException: + return None + return ip def is_slow_test_allowed(): diff --git a/tools/ui/.npmrc b/tools/ui/.npmrc index fd58f2418d44..5e0a8e82addf 100644 --- a/tools/ui/.npmrc +++ b/tools/ui/.npmrc @@ -1,6 +1,8 @@ engine-strict=true ignore-scripts=true min-release-age=7 +# Allow root-declared remote tarball dependencies (llama-brand) on npm 12+ +allow-remote=root # The single-bundle production build needs more than the default heap on CI runners; # npm passes this to every script it runs, on every platform node-options=--max-old-space-size=6144 diff --git a/ty.toml b/ty.toml index 1a11151e67d9..2774cdbb8ed5 100644 --- a/ty.toml +++ b/ty.toml @@ -22,13 +22,3 @@ unresolved-reference = "ignore" import-not-found = "ignore" missing-attribute = "ignore" missing-union-attribute = "ignore" - -[[overrides]] -include = [ - "./examples/pydantic_models_to_grammar.py", -] - -[overrides.rules] -unsupported-operator = "ignore" -not-subscriptable = "ignore" -invalid-type-form = "ignore"