diff --git a/CMakeLists.txt b/CMakeLists.txt index 763e1d70cf..61abc32a96 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2082,17 +2082,19 @@ if(STRATA_NATIVE_EXPERTS AND (STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) AND NOT S endif() set(_strata_poly_mmq_instances "") foreach(_t q4_0 q4_1 q5_0 q5_1 q8_0 q2_k q3_k q4_k q5_k q6_k iq1_s iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl - iq4_xs) + iq4_xs q2_0) list(APPEND _strata_poly_mmq_instances ${_strata_mmq}/template-instances/mmq-instance-${_t}.cu) endforeach() # MXFP4 and NVFP4: on RTX 50 llama.cpp's tiles use the FP4 MMA with block scales, which exists only in the # arch-specific target, so on CUDA their instances alone are built with 12x -> 12xa, as Strata's W4A4 unit is. A # Blackwell other than 12.0 has no image of them, and Mmq::fits() leaves MXFP4 out there. NVFP4 takes this - # instance only on a 12.0 card with STRATA_PREFILL_NVFP4=w4a4; otherwise its tiles are mmq_nvfp4.cu's int8 ones, - # built for the architectures as given. On HIP there is no NVFP4 prompt product. + # instance only on a 12.0 card with STRATA_PREFILL_NVFP4=w4a4. Its other tiles, mmq_nvfp4.cu's, decode the + # weights to int8 and take Q8_1 rows: that unit is device-generic, so it is built here for HIP as well, under + # STRATA_POLY_NVFP4_INT8 (the int8 tiles alone; STRATA_POLY_NVFP4 is CUDA's, with its FP4 units), where a family + # allows them (Mmq::nvfp4_int8: Inkling 2) or STRATA_PREFILL_NVFP4=w4a8 asks for them. set(_strata_poly_mxfp4 ${_strata_mmq}/template-instances/mmq-instance-mxfp4.cu) if(STRATA_ENABLE_HIP) - list(APPEND _strata_poly_mmq_instances ${_strata_poly_mxfp4}) + list(APPEND _strata_poly_mmq_instances ${_strata_poly_mxfp4} src/poly/mmq_nvfp4.cu) else() list(APPEND _strata_poly_mxfp4 ${_strata_mmq}/template-instances/mmq-instance-nvfp4.cu) list(APPEND _strata_poly_mmq_instances src/poly/mmq_nvfp4.cu) @@ -2107,6 +2109,13 @@ if(STRATA_NATIVE_EXPERTS AND (STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) AND NOT S target_compile_options(strata_poly_mmq_mxfp4 PRIVATE $<$:-Xcompiler=/bigobj>) endif() list(APPEND _strata_poly_mmq_instances $) + # Mmq::mul_tiles() (src/poly/mmq_tiles.cuh, STRATA_POLY_EXPERT_TILES): a kernel for each type of Inkling 2 Mini's + # experts in its GGUFs, each in its own TU + foreach(_t q8_0 iq1_s iq2_xxs iq2_xs iq2_s iq4_nl q2_0) + string(TOUPPER ${_t} _strata_tiles_T) + configure_file(src/poly/mmq_tiles_instance.cu.in ${CMAKE_BINARY_DIR}/poly_mmq_tiles/mmq-tiles-${_t}.cu @ONLY) + list(APPEND _strata_poly_mmq_instances ${CMAKE_BINARY_DIR}/poly_mmq_tiles/mmq-tiles-${_t}.cu) + endforeach() endif() if(STRATA_ENABLE_HIP) # CMake does not infer HIP from the .cu suffixes outside src/ (and drops a .cu source it has no language @@ -2117,19 +2126,26 @@ if(STRATA_NATIVE_EXPERTS AND (STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) AND NOT S add_library(strata_poly_mmq STATIC src/poly/mmq.cu src/poly/fattn.cu src/prefill/ggml_cuda_host.cu ${_strata_mmq}/quantize.cu ${_strata_poly_mmq_instances}) target_include_directories(strata_poly_mmq PRIVATE ${_strata_gg}/include ${_strata_gg}/src ${_strata_mmq} - ${CMAKE_CURRENT_SOURCE_DIR}/include) + ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/src/poly) target_compile_options(strata_poly_mmq PRIVATE $<$:--extended-lambda -use_fast_math>) if(MSVC) target_compile_options(strata_poly_mmq PRIVATE $<$:-Xcompiler=/bigobj>) endif() if(STRATA_ENABLE_HIP) - target_compile_definitions(strata_poly_mmq PRIVATE GGML_USE_HIP=1) + target_compile_definitions(strata_poly_mmq PRIVATE GGML_USE_HIP=1 STRATA_POLY_NVFP4_INT8=1) target_link_libraries(strata_poly_mmq PUBLIC ggml-base hip::host) else() - target_compile_definitions(strata_poly_mmq PRIVATE STRATA_POLY_NVFP4=1) + target_compile_definitions(strata_poly_mmq PRIVATE STRATA_POLY_NVFP4=1 STRATA_POLY_MMQ_TILES=1) target_link_libraries(strata_poly_mmq PUBLIC ggml-base ${_strata_gpu_runtime_target}) endif() + # the routed experts on the CPU (cpu_experts.cpp) and its AVX2 Q2_0 / IQ1_S dot products (cpu_lowbit.cpp, which + # takes ggml-common.h from ggml's src), for every target that runs them + add_library(strata_poly_cpu STATIC src/poly/cpu_experts.cpp src/poly/cpu_lowbit.cpp) + target_include_directories(strata_poly_cpu PUBLIC ${_strata_gg}/include) + set_source_files_properties(src/poly/cpu_lowbit.cpp PROPERTIES INCLUDE_DIRECTORIES ${_strata_gg}/src) + target_link_libraries(strata_poly_cpu PUBLIC ggml-cpu ggml-base Threads::Threads) + if(STRATA_ENABLE_CUDA) target_compile_definitions(strata_poly_mmq PUBLIC STRATA_POLY_GDN_MMA=1) target_link_libraries(strata_poly_mmq PUBLIC strata_gdn_mma) @@ -2142,17 +2158,18 @@ if(STRATA_NATIVE_EXPERTS AND (STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) AND NOT S # Optional model/state check; run by hand with an MTP GGUF and frozen prompt IDs. add_executable(poly_gdn_mma_state_test src/poly/gdn_mma_state_test.cpp src/poly/engine.cpp src/poly/glm5next.cpp src/poly/qwen35.cpp src/poly/gemma4.cpp src/poly/deepseek4.cpp src/poly/lfm2moe.cpp - src/poly/flint.cpp src/poly/kolibri1.cpp src/poly/cpu_experts.cpp src/poly/kernels.cu - src/poly/kernels_dsv4.cu src/core/conversation_memory.cpp) + src/poly/flint.cpp src/poly/kolibri1.cpp src/poly/inkling.cpp src/poly/kernels.cu + src/poly/kernels_dsv4.cu src/poly/kernels_inkling.cu src/core/conversation_memory.cpp) target_include_directories(poly_gdn_mma_state_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) - target_link_libraries(poly_gdn_mma_state_test PRIVATE strata_poly_mmq strata_kernels strata_spec ggml-cpu ggml-base - ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target} CUDA::cuda_driver Threads::Threads) + target_link_libraries(poly_gdn_mma_state_test PRIVATE strata_poly_mmq strata_poly_cpu strata_kernels strata_spec + ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target} CUDA::cuda_driver) endif() add_executable(strata-poly src/poly/main.cpp src/poly/engine.cpp src/poly/glm5next.cpp src/poly/qwen35.cpp src/poly/gemma4.cpp src/poly/deepseek4.cpp src/poly/lfm2moe.cpp src/poly/flint.cpp - src/poly/kolibri1.cpp src/poly/cpu_experts.cpp src/poly/kernels.cu src/poly/kernels_dsv4.cu - src/poly/spill.cpp src/core/conversation_memory.cpp src/core/conversation_file.cpp) + src/poly/kolibri1.cpp src/poly/inkling.cpp src/poly/kernels.cu src/poly/kernels_dsv4.cu + src/poly/kernels_inkling.cu src/poly/spill.cpp src/core/conversation_memory.cpp + src/core/conversation_file.cpp) target_include_directories(strata-poly PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) # the driver's virtual memory calls: the attention caches grow with the conversation; on HIP they are HIP's # memory management calls, which the HIP runtime itself provides (hip_compat/cuda.h) @@ -2161,29 +2178,51 @@ if(STRATA_NATIVE_EXPERTS AND (STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) AND NOT S else() set(_strata_poly_driver CUDA::cuda_driver) endif() - target_link_libraries(strata-poly PRIVATE strata_poly_mmq strata_kernels strata_spec ggml-cpu ggml-base + target_link_libraries(strata-poly PRIVATE strata_poly_mmq strata_poly_cpu strata_kernels strata_spec ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target} - ${_strata_poly_driver} - Threads::Threads) + ${_strata_poly_driver}) # needs the model file, so it is run by hand: poly_expert_parity MODEL.gguf - add_executable(poly_expert_parity src/poly/expert_parity.cpp src/poly/cpu_experts.cpp src/poly/kernels.cu) + add_executable(poly_expert_parity src/poly/expert_parity.cpp src/poly/kernels.cu) target_include_directories(poly_expert_parity PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) - target_link_libraries(poly_expert_parity PRIVATE strata_poly_mmq strata_kernels ggml-cpu ggml-base - ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target} - Threads::Threads) + target_link_libraries(poly_expert_parity PRIVATE strata_poly_mmq strata_poly_cpu strata_kernels + ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target}) # a read with the draft block repeats bit for bit; needs the model file, so it is run by hand: # poly_draft_race_test MODEL.gguf [RUNS] [LAYER_SPLIT] add_executable(poly_draft_race_test src/poly/draft_race_test.cpp src/poly/engine.cpp src/poly/glm5next.cpp src/poly/qwen35.cpp src/poly/gemma4.cpp src/poly/deepseek4.cpp src/poly/lfm2moe.cpp src/poly/flint.cpp src/poly/kolibri1.cpp - src/poly/cpu_experts.cpp src/poly/kernels.cu src/poly/kernels_dsv4.cu - src/core/conversation_memory.cpp) + src/poly/inkling.cpp src/poly/kernels.cu src/poly/kernels_dsv4.cu + src/poly/kernels_inkling.cu src/core/conversation_memory.cpp) target_include_directories(poly_draft_race_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) - target_link_libraries(poly_draft_race_test PRIVATE strata_poly_mmq strata_kernels strata_spec ggml-cpu ggml-base + target_link_libraries(poly_draft_race_test PRIVATE strata_poly_mmq strata_poly_cpu strata_kernels strata_spec ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target} - ${_strata_poly_driver} Threads::Threads) + ${_strata_poly_driver}) + # the engine's logits for a list of tokens as raw floats, to compare with llama.cpp's; needs the model file, so it + # is run by hand: poly_logits_dump MODEL.gguf --tokens ID,ID,... (its usage says the rest) + add_executable(poly_logits_dump src/poly/logits_dump.cpp src/poly/engine.cpp src/poly/glm5next.cpp + src/poly/qwen35.cpp src/poly/gemma4.cpp src/poly/deepseek4.cpp src/poly/lfm2moe.cpp + src/poly/flint.cpp src/poly/kolibri1.cpp src/poly/inkling.cpp src/poly/kernels.cu + src/poly/kernels_dsv4.cu src/poly/kernels_inkling.cu + src/core/conversation_memory.cpp) + target_include_directories(poly_logits_dump PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include + ${_strata_gpu_include_directories}) + target_link_libraries(poly_logits_dump PRIVATE strata_poly_mmq strata_poly_cpu strata_kernels strata_spec + ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target} + ${_strata_poly_driver}) + # Inkling 2 Mini's DSpark drafter against llama.cpp's on llama.cpp's own inputs (a record of its run); needs the + # model files and a card, so it is run by hand: poly_dspark_parity MODEL.gguf DRAFTER.gguf RECORD + add_executable(poly_dspark_parity src/poly/dspark_parity.cpp src/poly/engine.cpp src/poly/glm5next.cpp + src/poly/qwen35.cpp src/poly/gemma4.cpp src/poly/deepseek4.cpp + src/poly/lfm2moe.cpp src/poly/flint.cpp src/poly/kolibri1.cpp src/poly/inkling.cpp + src/poly/kernels.cu src/poly/kernels_dsv4.cu src/poly/kernels_inkling.cu + src/core/conversation_memory.cpp) + target_include_directories(poly_dspark_parity PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include + ${_strata_gpu_include_directories}) + target_link_libraries(poly_dspark_parity PRIVATE strata_poly_mmq strata_poly_cpu strata_kernels strata_spec + ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target} + ${_strata_poly_driver}) # a prompt batch's routing on the card against the hosts' routing; needs a card, so it is run by hand add_executable(poly_route_test src/poly/route_test.cu src/poly/kernels.cu) target_include_directories(poly_route_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include @@ -2224,6 +2263,31 @@ if(STRATA_NATIVE_EXPERTS AND (STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) AND NOT S target_include_directories(poly_sink_attend_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) target_link_libraries(poly_sink_attend_test PRIVATE ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target}) + # Inkling 2 Mini's kernels (inkling_kernels.hpp) against the same arithmetic on the host in double precision; + # needs a card (77 = skipped) + add_executable(poly_inkling_kernels_test src/poly/inkling_kernels_test.cu src/poly/kernels_inkling.cu + src/poly/kernels.cu) + target_include_directories(poly_inkling_kernels_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include + ${_strata_gpu_include_directories}) + target_link_libraries(poly_inkling_kernels_test PRIVATE strata_kernels ${_strata_gpu_blas_target} + ${_strata_gpu_runtime_target}) + add_test(NAME poly_inkling_kernels_test COMMAND poly_inkling_kernels_test) + set_tests_properties(poly_inkling_kernels_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 900) + # cpu_lowbit.cpp's dot products against the dequantized rows, and with `bench` their speed from memory; needs no + # card + add_executable(poly_cpu_lowbit_test src/poly/cpu_lowbit_test.cpp) + target_link_libraries(poly_cpu_lowbit_test PRIVATE strata_poly_cpu) + add_test(NAME poly_cpu_lowbit_test COMMAND poly_cpu_lowbit_test) + set_tests_properties(poly_cpu_lowbit_test PROPERTIES SKIP_RETURN_CODE 77) + # the card's IQ1_S and Q2_0 decode products and Q2_0 prompt tiles against the dequantized rows; needs a card + # (77 = skipped) + add_executable(poly_lowbit_gpu_test src/poly/lowbit_gpu_test.cu) + target_include_directories(poly_lowbit_gpu_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include + ${CMAKE_CURRENT_SOURCE_DIR}/src/poly ${_strata_gg}/include ${_strata_gpu_include_directories}) + target_link_libraries(poly_lowbit_gpu_test PRIVATE strata_poly_mmq strata_kernels ggml-base ${_strata_gpu_blas_target} + ${_strata_gpu_runtime_target}) + add_test(NAME poly_lowbit_gpu_test COMMAND poly_lowbit_gpu_test) + set_tests_properties(poly_lowbit_gpu_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) # STRATA_HIP_PREFILL_FP32 (attend_batch() on FP32 inputs over a q8_0 cache): against an FP64 reference and the default path, and the # fallbacks; needs a card (77 = skipped) add_executable(poly_hip_prefill_fp32_test src/poly/hip_prefill_fp32_test.cu src/poly/kernels.cu) @@ -2238,8 +2302,9 @@ if(STRATA_NATIVE_EXPERTS AND (STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) AND NOT S target_include_directories(poly_fattn_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/src/poly ${_strata_gpu_include_directories}) target_link_libraries(poly_fattn_test PRIVATE strata_poly_mmq ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target}) - # STRATA_POLY_STAGED_TILES: the staged experts in size classes, each a launch of its own tile width, against one - # launch, bit for bit; needs a card + # STRATA_POLY_STAGED_TILES' size classes of the staged experts and Mmq::mul_tiles()'s tables of tiles + # (STRATA_POLY_EXPERT_TILES), each against one launch, bit for bit (within rounding where MMQ uses stream-k); needs a + # card add_executable(poly_mmq_tiles_test src/poly/mmq_tiles_test.cu) target_include_directories(poly_mmq_tiles_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/src/poly ${_strata_gpu_include_directories}) @@ -2257,9 +2322,8 @@ if(STRATA_NATIVE_EXPERTS AND (STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) AND NOT S ${_strata_gpu_include_directories}) target_link_libraries(poly_dsv4_test PRIVATE ${_strata_gpu_runtime_target}) # the pool of the CPU experts, without a model - add_executable(poly_workers_test src/poly/workers_test.cpp src/poly/cpu_experts.cpp) - target_include_directories(poly_workers_test PRIVATE ${_strata_gg}/include) - target_link_libraries(poly_workers_test PRIVATE ggml-cpu ggml-base Threads::Threads) + add_executable(poly_workers_test src/poly/workers_test.cpp) + target_link_libraries(poly_workers_test PRIVATE strata_poly_cpu) add_test(NAME poly_workers_test COMMAND poly_workers_test) # the card's MXFP4 product against ggml's dequantizer on random blocks, without a model; needs a card, run by hand add_executable(poly_mxfp4_test src/poly/mxfp4_test.cu) diff --git a/README.md b/README.md index 6bca7f6b5e..140d872f07 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,8 @@ with an 8 GB card as well. own, made to read pictures: a file of 16 to 29 GB. - **[Kolibri 1](docs/models/kolibri.md)** by Aleph Alpha, which writes German as well as English: a file of 29 to 48 GB, most of which stays in RAM beside a small card. +- **[Inkling 2 Mini](docs/models/inkling.md)** by Thinking Machines, experimental: a file of 9 to 28 GB, on one or + more NVIDIA cards under Linux. The server can change between installed models while it runs ([how](docs/BACKENDS.md#changing-the-model)). diff --git a/docs/AI_SETUP.md b/docs/AI_SETUP.md index 585b0fbcf7..bb28f64217 100644 --- a/docs/AI_SETUP.md +++ b/docs/AI_SETUP.md @@ -121,6 +121,13 @@ one 32 GB V100 wrote 91 tokens/s and read a 32K prompt at 1,017 tokens/s (first layers split wrote 93 and read it at 2,179 (first token 15.3 s); three runs, the medians above. `--model` takes Q4_K_M, Q2_K on a PC with little RAM, or Q3_K_M by name. The support is new, the GGUF independent: ask first. +`--family inkling` (Inkling 2 Mini, by Thinking Machines, in ggml-org's GGUF files) is the newest model on the same +engine, and experimental: Linux, NVIDIA cards (one, or several that split its layers), pictures opt-in, a 17.6 GB +(IQ4_NL), 9.1 GB (`--model UD-Q2_K_XL`, Unsloth's, the fastest) or 27.8 GB (`--model Q8_0`) download, about 22, 14 or +32 GB of RAM beside an 8 GB card by setup's estimate. On an 8 GB RTX 2070 Super it wrote 38.8 to 40.0 tokens/s with +IQ4_NL and 51.1 to 52.3 with UD-Q2_K_XL after a 302-token prompt ([its page](models/inkling.md)). Take it only when +the user asks for it. + ## 4. Run setup without questions From the PolyStrata folder (Windows: in `cmd`, or `cmd /c START-HERE.bat ...` from PowerShell): diff --git a/docs/BACKENDS.md b/docs/BACKENDS.md index 08ac8436c5..bc0f6a093f 100644 --- a/docs/BACKENDS.md +++ b/docs/BACKENDS.md @@ -99,6 +99,9 @@ straight to it. The larger models have pages of their own, | `clover` | Clover-35B-A3B-Preview | maternion Q3_K_M | 16.8 GB | about 20 GB | | | | IsValorum APEX-I-NanoPlus | 12.6 GB | about 16 GB | | | | maternion Q4_K_M | 21.2 GB | about 25 GB | +| `inkling` | Inkling 2 Mini (experimental) | ggml-org IQ4_NL | 17.6 GB | about 22 GB | +| | | Unsloth UD-Q2_K_XL | 9.1 GB | about 14 GB | +| | | ggml-org Q8_0 | 27.8 GB | about 32 GB | Kolibri 1's file is 29 to 48 GB, so its three numbers are the RAM beside an 8 GB card: an 8 GB card holds about a tenth of its 19,200 experts, reads the rest through the OS cache; a 32 GB card fits about two thirds @@ -250,9 +253,12 @@ and, by the tokenizer's `pre` name, how the model writes its reasoning and its t | LFM2.5 | the prompt opens it, `` ends it | `<\|tool_call_start\|>[NAME(K='V', ...), NAME2()]<\|tool_call_end\|>` | | Flint | `` to ``, opened by the model | as GLM's | | Kolibri 1 | the prompt opens it, `` ends it | a JSON object in the wrapper: `{"name": NAME, "arguments": {...}}` | +| Inkling 2 Mini | a `<\|message_model\|><\|content_thinking\|>` block, opened by the model, to `<\|end_message\|>` | `<\|message_model\|>NAME<\|content_invoke_tool_json\|>{"name":NAME,"args":{...}}<\|end_message\|>` | Gemma 4's template thinks only when it is told to, reads a tool in OpenAI's shape and starts with the tokenizer's -``; the server gives it all three. A tool's answers are put in the order of their calls for every model, +``; the server gives it all three. Inkling 2 Mini's template reads only `reasoning_effort` (thinking off is its +`none`) and has no generation prompt: the model writes its reply's first header itself +([its page](models/inkling.md#how-it-talks)). A tool's answers are put in the order of their calls for every model, because a model reads them by position. ## The registry diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 1002191387..cb1622aa26 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -20,8 +20,8 @@ same server): its numbers, what a slot costs and where setup recommends it are i ## The strata-poly models `"parallel": N` in the model's config (`strata-.json`), or `--parallel N` when you run setup, works for -GLM 5.3 Flash, DeepSeek V4 Flash, LFM2.5, Flint, Qwen3.6, Ornith 1.5, Gemma 4, Tiel Coder and MiniCPM-V too, up to -8. The server drives it the way it drives the Strata project's engine (below), with the same lines: +GLM 5.3 Flash, DeepSeek V4 Flash, LFM2.5, Flint, Qwen3.6, Ornith 1.5, Gemma 4, Tiel Coder, MiniCPM-V and Inkling 2 +Mini too, up to 8. The server drives it the way it drives the Strata project's engine (below), with the same lines: - A request alone writes on its own and guesses ahead as always, so one user sees no change. - When a second one comes, the first goes on in a batch slot from where it was, nothing read again, and the two @@ -44,6 +44,19 @@ gains more. On an RTX 5090 with Qwen3.6 UD-Q4_K_M, chats of 300 tokens through t | 3 | 381-389 | | 4 | 428-430 | +Inkling 2 Mini on an RTX 2070 Super 8 GB (Ryzen 5 3600XT, 62 GB DDR4), where most of its experts run on the CPU: chats +of 300 tokens through the server (128K context, q8_0 caches, the expert profile), tokens/s of all chats together, two +runs each, the server started again for each row ([models/inkling.md](models/inkling.md#several-requests-at-once) has +each chat's speed): + +| Chats at once | `"parallel"` | IQ4_NL | UD-Q2_K_XL | +| ---: | ---: | ---: | ---: | +| 1 | 1 | 37.1-37.7 | 46.2-47.8 | +| 1 | 4 | 34.5-35.0 | 44.3-44.9 | +| 2 | 2 | 44.6-45.5 | 57.7-59.7 | +| 3 | 3 | 48.9-49.0 | 63.2-64.5 | +| 4 | 4 | 51.2-51.9 | 64.1-66.5 | + Each slot's attention rows take VRAM from the expert cache as its conversation grows, as the first conversation's do. A model split across cards (`"layer_split"`) runs its slots card after card. @@ -57,8 +70,11 @@ reason alone ([issue 55](https://github.com/VecSzn/PolyStrata/issues/55)). On th laptop every token matched for Qwen3.6, Gemma 4 and LFM2.5 with 2 to 4 sequences and prompts of 19 to 3,000 tokens, and on the RTX 5090 for Qwen3.6, MiniCPM-V, LFM2.5, DeepSeek V4 Flash and GLM 5.3 Flash with 3 sequences after prompts of 64 and 3,000 tokens, and for Flint after prompts of 15 and 3,000 tokens, with every expert on the card -and with the card held to 8 GB. Through the server on the laptop, with the same four options in the run config, -three chats at once gave the text each gave alone, to the character. +and with the card held to 8 GB. On an RTX 2070 Super 8 GB every token matched for Inkling 2 Mini (IQ4_NL and +UD-Q2_K_XL, fp16 and q8_0 caches) with 2, 3 and 4 sequences after a prompt of 302 tokens, 4 after 3,000, and 4 with +`--check-stagger` (prompts of 16 to 3,000 tokens read while the others write, answers of 64 to 16 tokens). +Through the server on the laptop, with the same four options in the run config, three chats at once gave the text +each gave alone, to the character. Without those options the text of a chat answered together can part from the one it gets alone after a few dozen words, and so can two runs of the same chat alone. On the laptop that happened with the run config as setup writes diff --git a/docs/GLM.md b/docs/GLM.md index ee99eb5dd6..e65f5445c0 100644 --- a/docs/GLM.md +++ b/docs/GLM.md @@ -258,7 +258,7 @@ goes on from where it stopped, and an edit goes back to the nearest checkpoint. | `--any-node` | | on a PC with several NUMA nodes, let the CPU threads run on any of them | | `--no-graphs` | | launch a token's kernels one by one, not as the CUDA graph a layer that is recorded at the first token | | `--expert-swaps N` | 64 | while an answer is written, experts on their way into VRAM at a time, each in place of a cached one the answer uses less; 0 = the cache stays as it was loaded | -| `--window N` | 4; 8 for the other models | the most tokens that go through the model together while an answer is written: the known one and guesses after it: the draft block's three at most, and more than three only from a repeat of eight tokens or more; 1 = no guesses | +| `--window N` | 4; for Inkling 2 Mini 1, or 4 with its drafter (`--draft-model`); 8 for the other models | the most tokens that go through the model together while an answer is written: the known one and guesses after it: the draft block's three at most, and more than three only from a repeat of eight tokens or more; 1 = no guesses | | `--lookup N` | 3 | guess what followed an earlier repeat of the last N or more tokens; 0 = never | | `--no-draft` | | do not run the block that guesses ahead | | `--draft-model FILE.gguf` | | a file of the same model to take that block from, when `--model` has none; setup passes the one it downloaded | @@ -281,6 +281,7 @@ goes on from where it stopped, and an edit goes back to the nearest checkpoint. | `--eos-ids ID,ID,...` | from the GGUF | tokens that end a reply | | `--tail-skip N` | 0; setup gives Qwen3.6 6 | an expert outside VRAM that every token of a window ranks at place N+1 or later among its experts is left out: faster, and the answers move a little | | `STRATA_FREEZE_EXPERTS` | not set | hold the split of the routed experts between the card and the CPU still for the engine's whole run, so a greedy answer is a function of the request alone: same request, same answer, bit for bit. With guesses on (`--window` above 1 and a block or `--lookup`) the block's guesses and their windows still take their sizes from the machine's pace, which the freeze does not hold: on the cards measured so far it repeated with them on (RX 9060 XT, several thread counts and loads) and on one RTX 4070 laptop it did not — add `--window 1` for a repeat wherever the guesses are on. Measured cost: nothing measurable on the default path, 4-7% at a short prompt with the freeze set | +| `STRATA_GPU_EXPERTS=N` | not set | a test knob: the card's expert cache holds exactly the first N experts of the order it fills in (the expert profile's), for the engine's whole run, with the split frozen as `STRATA_FREEZE_EXPERTS` does, no uploads into the cache (`--expert-swaps 0`) and no VRAM resize. Two builds leave different VRAM free at load and so cache different numbers of experts, and their sums differ wherever the split does; with the same N and the same profile they hold the same experts, so their logits can be compared byte for byte without `--no-gpu-experts`. An N the VRAM cannot hold stops the load with an error. One card only (not with `STRATA_POLY_CARDS`). With this or `STRATA_FREEZE_EXPERTS` set, the load logs `cache set N experts fnv `: which experts the cache holds, to compare between runs (the same count can be a different set) | | `STRATA_NO_SPILL=1` | not set | keep parked conversations' blobs in heap instead of writing them to temporary files; parking still works but RAM use grows accordingly | `strata-poly` with no arguments prints the list, with the options for running it without the server. diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 359116d643..23510fb55d 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -471,10 +471,10 @@ pipelines them through the cards: see [BATCHING.md](BATCHING.md). ## The strata-poly models -Qwen3.6, Gemma 4, Ornith, Tiel Coder and GLM 5.3 Flash run on the strata-poly engine, which splits a model's layers -across cards too. Each card runs a range of layers and keeps the routed experts of those layers in its VRAM, as many -as fit. The last card also runs the output and the draft block, or Gemma 4's draft model. After its layers a card -copies the rows of the tokens it read into pinned RAM, and the next card reads them from there: one row of the +Qwen3.6, Gemma 4, Ornith, Tiel Coder, GLM 5.3 Flash and Inkling 2 Mini run on the strata-poly engine, which splits a +model's layers across cards too. Each card runs a range of layers and keeps the routed experts of those layers in its +VRAM, as many as fit. The last card also runs the output and the draft block, or Gemma 4's draft model. After its layers +a card copies the rows of the tokens it read into pinned RAM, and the next card reads them from there: one row of the model's width a token, 8 KB for Qwen3.6. No NVLink or peer-to-peer access is needed. A prompt read in several calls keeps the cards busy together when every routed expert is in VRAM, or when the @@ -546,6 +546,10 @@ same container's cache; the engine now asks four times, a quarter of a second ap says at load when the container has less than the model's files and 8 GiB. This pod has less than setup asks for REAP50 beside 6.7 GiB of experts in VRAM, about 82 GB. +Inkling 2 Mini runs its layers 6 to 17 three times, and those stay on one card, so its cards start at layer 1 to 6 or +18 to 22, physical layers as the file numbers them; `"auto"` takes 6 or 18, whichever is nearer its share +([docs/models/inkling.md](models/inkling.md#two-or-more-cards)). + Not done yet: - Only two cards under Linux have run it. Three cards and Windows were not tried. diff --git a/docs/NVFP4.md b/docs/NVFP4.md index 3aa6b3d3b8..0c446ce1d5 100644 --- a/docs/NVFP4.md +++ b/docs/NVFP4.md @@ -130,7 +130,7 @@ FP16's range. | mode | kernel | activations | one product vs FP64 (`mmq_nvfp4_parity`) | |---|---|---|---| -| `w4a8` (default) | llama.cpp MMQ, int8 tensor cores | q8_1, float block scales | 0.53% | +| `w4a8` (CUDA's default; HIP's for Inkling 2, else on request) | llama.cpp MMQ, int8 tensor cores | q8_1, float block scales | 0.53% | | `w4a4` | llama.cpp MMQ, Blackwell FP4 MMA (sm_120a only) | NVFP4 | 8.6% | | `fp16` | dequantize + cuBLAS FP16 GEMM | FP16 | reference | @@ -208,8 +208,9 @@ engine's own q8_1 kernels, which decode UE4M3/E2M1 in software. The engine was b on the RTX 5090 with the host answering as that generation. On those builds `mmq_nvfp4_parity` and `nvfp4_expert_gpu_parity` gave results identical to sm_120. -HIP: the decode kernels use no CUDA-only intrinsics. The NVFP4 MMQ instance and the W4A8 unit are CUDA-only and -guarded (`GGML_USE_HIP`). Neither was built for HIP here. +HIP: the decode kernels use no CUDA-only intrinsics. The NVFP4 MMQ instance (the FP4 MMA) is CUDA-only and guarded +(`GGML_USE_HIP`); the W4A8 unit (`src/poly/mmq_nvfp4.cu`) is device-generic and built for HIP as well +(`STRATA_POLY_NVFP4_INT8`). ## strata-poly: NVFP4 GGUFs @@ -229,8 +230,17 @@ too small for the blocks' E4M3 scales, and llama.cpp multiplies the product by t products before the activation (`ExpertScales`, in each path's SwiGLU), and its down scale on its weight in the token's sum. Down's scale on the hidden instead would leave it near 1e-5 before its 8-bit quantization (see "Where the global scales go"). Only an NVFP4 tensor's `.scale` is read: Gemma 4's `ffn_down_exps.scale` is its own. -- Not built: Metal (no NVFP4 kernels); HIP (no NVFP4 prompt product, the batch goes through the decode kernels; not - run here). +- HIP: the same W4A8 tiles, built for the HIP architectures (`src/poly/mmq_nvfp4.cu` is device-generic; the FP4 + MMA is CUDA's alone). Inkling 2 takes them by default, as on CUDA (`Engine::nvfp4_int8_`, `Mmq::nvfp4_int8`); + another family takes them with `STRATA_PREFILL_NVFP4=w4a8`, read by `nvfp4_int8_on()` in `src/poly/mmq.cu`, and + keeps the decode kernels for its batch, and its previous bits, without it. w4a4 and w4a4x2 leave that choice as it + is, and any other value of the switch keeps the tiles out (Inkling 2's too). Measured on an RX 9060 XT (gfx1200, + ROCm 10.1): + Inkling 2 Mini UD-Q2_K_XL, a 2,048-token prompt 177.3 -> 402.3 tok/s when the nine of its eighteen MoE + layers whose down matrix is NVFP4 stopped going through the decode kernels a token at a time; 286 tokens 174.7 -> + 390.7. Greedy ids identical over 32 tokens at both sizes. On an RX 9070 XT (gfx1201, ROCm 7.2.4), 3,072 of 3,072 + experts in VRAM: 2,048 tokens 372.8 -> 997.7 tok/s, 8,192 tokens 343.9 -> 848.3, writing 85.9 -> 86.8. +- Not built: Metal (no NVFP4 kernels). Measured on lab-pro6000 (RTX PRO 6000 Blackwell Server Edition, sm_120, other users' jobs on the same card), with `WhiskyAKM/LFM2.5-24B-A2B-NVFP4-GGUF` (every matrix NVFP4, no global scales). diff --git a/docs/Q8_KV.md b/docs/Q8_KV.md index 2e7c34b461..c4a931ec21 100644 --- a/docs/Q8_KV.md +++ b/docs/Q8_KV.md @@ -18,6 +18,9 @@ Gemma 4 has its own two, in the same Q8_0 rule but its own layout: `--kv int8` a On `kolibri1`, `STRATA_KV_INT8=1` makes both the decode and the prompt read the q8_0 cache with the int8 reader below (`attend_int8`) instead of the float q8 readers. It is experimental: the queries are quantized too, so the answers change slightly, and it is opt-in. +On `inkling2`, `STRATA_KV_INT8=1` takes a decoded token's attention of a full layer with a room of 32K or more by +`__dp4a` on the q8_0 cache, the queries quantized too; window layers, shorter rooms and the prompt keep the float +readers ([Inkling 2 Mini: long contexts](models/inkling.md#long-contexts)). Opt-in as well. ## What the format is diff --git a/docs/models/inkling.md b/docs/models/inkling.md new file mode 100644 index 0000000000..35ed929310 --- /dev/null +++ b/docs/models/inkling.md @@ -0,0 +1,509 @@ +# Inkling 2 Mini + +Back to [README.md](../../README.md) + +**Inkling 2 Mini** by Thinking Machines, released on 2026-11-20: a mixture of 128 experts, 8 used a token, in 24 +layers. Layers 6 to 17 run three times for each token, so a token goes through 48 layers with the weights of 24. Five +layers in six look back only 1,024 tokens. PolyStrata runs [ggml-org's GGUF files](https://huggingface.co/ggml-org/Inkling-2-Mini-GGUF) +and [Unsloth's UD-Q2_K_XL](https://huggingface.co/unsloth/Inkling-2-Mini-GGUF) on the strata-poly engine. + +**It is experimental and new.** Support was added on 2026-11-21. Its speeds below are from one PC with an RTX 2070 Super +8 GB unless a row names a rented card. Its logits were +checked against llama.cpp's on the same files (below): the same most likely next token after each of the prompts, and +the same at 29 to 32 of 32 steps with llama.cpp's own answer fed in. + +## How fast is it? + +> **Measured on:** RTX 2070 Super 8 GB, Ryzen 5 3600XT, 62 GB DDR4, Ubuntu 22.04, 2026-11-22. `strata-poly --serve` +> with the server's flags (128K context, q8_0 caches), one engine a run, each from a fresh copy of the model's expert +> profile, the prompt read in a fresh conversation (text from the parity prompts repeated). Reading at 2,048, 8,192 and +> 32,768 tokens: prompt only, two runs, with the next layer's experts copied while a layer runs (below). The other +> cells: the same flags, a build before that copy (it changes reading only); 302 and 1,500 tokens two runs each with +> 256 tokens written, the longer prompts one run with 64. 1,042 of IQ4_NL's and 2,022 of UD-Q2_K_XL's 3,072 experts +> were cached in the copy's runs. + +| prompt | IQ4_NL reading | IQ4_NL writing | UD-Q2_K_XL reading | UD-Q2_K_XL writing | +| --- | ---: | ---: | ---: | ---: | +| 302 tokens | 282-290 tokens/s | 38.8-40.0 tokens/s | 557-561 tokens/s | 51.1-52.3 tokens/s | +| 1,500 tokens | 521-523 tokens/s | 38.5-38.7 tokens/s | 881-888 tokens/s | 49.0-49.5 tokens/s | +| 2,048 tokens | 787-789 tokens/s | 34.0 tokens/s | 929-931 tokens/s | | +| 8,192 tokens | 947-948 tokens/s | | 888-896 tokens/s | | +| 32,768 tokens | 911-914 tokens/s | 28.7 tokens/s | 852-854 tokens/s | | +| 131,008 tokens | 659 tokens/s (199 s) | 20.6 tokens/s | | | + +A prompt batch's attention runs on the tensor cores (cards of Turing or newer); writing does not (a token at a time +takes the split path). Single runs differ by up to 4.5% both ways, the means of two runs by at most 1.5%. A prompt's +read copies the next layer's experts that the card does not hold while a layer runs, and hands the card each call's +row tables by a kernel, so that they wait for no copy. + +The results are the same as without those changes. With `STRATA_FREEZE_EXPERTS=1`, the 20 most likely tokens and +their probabilities at 4 steps after prompts of 2,048 and 8,192 tokens (q8_0 caches) and of 2,048 tokens (fp16) +matched for both models, in runs where both builds cached the same number of experts (that number depends on the VRAM +free at load, and runs that differ in it differ in their results with either build). Through `--serve`, also frozen, +at a 40K context with `--kv-whole` (so that a frozen 32K read has its rows), it gave the same tokens after an +8,192-token prompt with a checkpoint inside its read, after that prompt resumed with 1,985 tokens more, and after a +32,765-token prompt read in four reads that followed a read stopped at 3 s. + +`STRATA_POLY_EXPERT_TILES=1` (opt-in) puts a prompt batch's expert products in one launch of tiles of their own +widths. It read prompts 6-17% faster on the RTX 2070 Super 8 GB, a rented RTX 3090 24 GB and a rented A100 40 GB. With +every expert on the card the results were the same to the bit as without it; with some experts in RAM the sums run in +another order, and the chosen token changed only where the top two were nearly tied. + +On an A100 (compute capability 8.0 only) a full-attention layer whose prompt call reaches past 2,048 keys runs on a +FlashAttention-2 kernel that gives the same bits as the tensor-core kernel above. On a rented A100 40 GB (every expert in +VRAM) IQ4_NL read prompts of 8K to 128K tokens 4-6% faster with it. + +On a card that holds every expert, a token written on its own runs as one CUDA graph: its 48 layer runs and their +experts are recorded once (again when the context outgrows the size they were recorded for) and replayed, so the CPU +hands the card 4 launches a token instead of 1,059 (IQ4_NL) or 1,167 (UD-Q2_K_XL). A window of guesses (`--window` +above 1) is recorded the same way, once for each number of tokens it puts through the model, and its guesses are +checked between windows as before. Not recorded: several requests at once (`--parallel`), a picture's tokens and +`--dump-layers`. `--no-graphs` turns it off; the output is the same to the bit either way. A card that holds only +some of the experts, as the 8 GB one above, runs a token launch by launch. + +> **Measured on:** a rented RTX 3090 24 GB, every expert in VRAM, strata-poly alone, a 16K context, q8_0 caches, 256 +> tokens written, two runs each, a build that ran a token launch by launch and this one in turn. + +| writing | launch by launch | one CUDA graph | +| --- | ---: | ---: | +| IQ4_NL, after 302 tokens | 62.5-62.8 tokens/s | 69.8-70.2 tokens/s (+11%) | +| IQ4_NL, after 8,192 tokens | 60.8-61.3 tokens/s | 67.4-67.8 tokens/s | +| UD-Q2_K_XL, after 302 tokens | 71.8-72.6 tokens/s | 82.1-82.6 tokens/s (+14%) | +| UD-Q2_K_XL, after 8,192 tokens | 69.6-70.2 tokens/s | 78.7-79.4 tokens/s | + +A token's launches are fewer on every card: a visit's norms and Q8_1 copies, the cache store and its clip, the +attention's gate and the mixes around it go in fewer kernels that write the same bits as the separate ones (the +kernel test compares them). With UD-Q2_K_XL on the RTX 3090 a token took 890 kernels on the card instead of 1,391 +(nsys, every expert in VRAM). On CUDA a token's mixes are spread over many blocks in a cooperative launch, which the +runtime starts with all of its blocks on the card together, or else they run one block a mix; +`STRATA_INKLING_MIX_SPREAD=0` keeps them one block a mix, with the same bits. + +IQ4_NL's speed depends on its expert profile (`--expert-profile`, which the server keeps up to date): it chooses the +experts the card holds. On 100 questions (50 GSM8K, 50 MMLU-Pro, greedy, medium reasoning) IQ4_NL got 49 and 44 +right, UD-Q2_K_XL 48 and 41; the two gave the same answer to 92 of the 100. + +About 4.6 GiB of experts fit on the 8 GB card. At most 7.5 GiB of VRAM was in use (nvidia-smi, IQ4_NL, a +31,600-token prompt). The engine's RAM was 16.5 GiB with IQ4_NL. + +## What you need + +| | | +| --- | --- | +| **Graphics card** | An **NVIDIA** card, or several that split its layers ([Two or more cards](#two-or-more-cards)). About 3.1 GiB of VRAM before any expert at an 8K context (measured on an 8 GB card), about 4 GiB at 32K. | +| **RAM** | About **22 GB** (IQ4_NL), **14 GB** (UD-Q2_K_XL) or **32 GB** (Q8_0) beside an 8 GB card, setup's estimate (the engine itself used 16.5 GiB with IQ4_NL, 9.1 GiB with UD-Q2_K_XL). The experts the card does not hold stay in RAM. Beside a 24 GB card the IQ4_NL file's experts fit in VRAM by the same estimate. | +| **Disk** | 17.6, 9.1 or 27.8 GB for the model file. | +| **System** | Linux and a current NVIDIA driver. On Windows it ran for one user on an earlier build (MSVC, an RTX 4060 Laptop), but it is not re-checked there, so setup asks before it installs it. | + +Setup does not offer it on AMD or Intel cards or on a Mac. The engine builds and runs it on AMD cards with HIP (an +RX 9070 XT with ROCm 7.2.4, and an RX 9060 XT), but its prompt speed there is not tuned yet. Two or +more NVIDIA cards can split its layers ([Two or more cards](#two-or-more-cards)). It can answer several requests at once +(`--parallel`, see [Several requests at once](#several-requests-at-once)). Its attention caches are fp16, or q8_0 with +`--kv q8_0`, which halves them: a 128K context then takes about 2.3 GiB of VRAM when it is full, in fp16 4.3 GiB. On an +8 GB card, use q8_0 for contexts past 32K. The file allows 1,048,576 tokens and the engine sets no limit of its own, but +the cache stays in VRAM (about 17 KiB a token in q8_0; the engine's KV streaming is not wired up for this model). +Prompts were tried up to 131,008 tokens on the RTX 2070 Super 8 GB (a 128K context, q8_0 caches) and up to 1,048,576 +on a rented A100 40 GB (UD-Q2_K_XL, every expert in VRAM, q8_0 caches, an earlier build: read in 1,782 s, then 17.8 +tokens/s writing, 27.7 GB of VRAM at most). Pictures are optional: see [Images](#images). It writes one token at a +time unless it guesses from the conversation (`--window`, see +[Guesses from the conversation](#guesses-from-the-conversation)) or with its drafter (see +[Guesses from its DSpark drafter](#guesses-from-its-dspark-drafter)). + +## Install + +```bash +./setup.sh --family inkling +``` + +```bash +./setup.sh --family inkling --model UD-Q2_K_XL +``` + +```bash +./setup.sh --family inkling --model Q8_0 +``` + +## Which model should I pick? + +| Size | What it is | Download | RAM beside an 8 GB card (estimate) | +| --- | --- | ---: | ---: | +| **IQ4_NL** | 4-bit experts in layers 0 to 19 (with an importance matrix), 8-bit everywhere else | 17.6 GB | about 22 GB | +| **UD-Q2_K_XL** | Unsloth's: 2-bit experts (Q2_K, IQ1_S and Q2_0), higher where it matters. The fastest, a little less accurate | 9.1 GB | about 14 GB | +| **Q8_0** | 8-bit throughout: the closest to the model as trained | 27.8 GB | about 32 GB | + +Setup takes IQ4_NL unless you name another size. UD-Q2_K_XL comes from Unsloth's repository in the architecture's +native form (`inkling2`, the loop not unrolled); the engine reads that form as it is. Q8_0 was not run. ggml-org's model card gives the KL divergence against the BF16 file on +wikitext-2: 0.0030 for Q8_0 and 0.0095 for IQ4_NL. PolyStrata did not measure that. + +## Several requests at once + +With `"parallel": N` in the run config (or `--parallel N` when you run setup) the engine answers up to N requests +together, as for the other models of strata-poly ([BATCHING.md](../BATCHING.md)). Each request then has its own +attention caches and convolution state. A token of every request goes through the model in one pass, so the dense +weights, and each expert that two requests both use, are read once for all of them. With the expert cache held still +(`--check-batch`, [BATCHING.md](../BATCHING.md)), every sequence got the tokens it gets alone: IQ4_NL and UD-Q2_K_XL, +fp16 and q8_0 caches, 2, 3 and 4 sequences after a 302-token prompt and 4 after a 3,000-token one, and 4 sequences +that start, join and stop at different times (`--check-stagger`: prompts of 16, 46, 375 and 3,000 tokens, read while +the others write, answers of 64 to 16 tokens, so that a step has 1 to 4 of them). + +> **Measured on:** RTX 2070 Super 8 GB, Ryzen 5 3600XT, 62 GB DDR4, Ubuntu 22.04: the server's config (128K context, +> q8_0 caches, the expert profile), chats of 300 tokens started together (greedy, thinking off), two runs each; the +> server was started again for each row, on an earlier build than the speeds at the top of this page. + +| Chats at once | `"parallel"` | IQ4_NL, all together | IQ4_NL, each chat | UD-Q2_K_XL, all together | UD-Q2_K_XL, each chat | Experts in VRAM (IQ4_NL / UD-Q2_K_XL) | +| ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| 1 | 1 | 37.1-37.7 tokens/s | 39.6-40.2 | 46.2-47.8 | 49.6-51.2 | 1,034 / 2,005 | +| 1 | 4 | 34.5-35.0 | 36.9-37.6 | 44.3-44.9 | 46.7-47.4 | 782 / 1,547 | +| 2 | 2 | 44.6-45.5 | 23.5-24.9 | 57.7-59.7 | 30.1-32.1 | 911 / 1,777 | +| 3 | 3 | 48.9-49.0 | 17.0-18.2 | 63.2-64.5 | 21.9-23.2 | 849 / 1,663 | +| 4 | 4 | 51.2-51.9 | 13.3-14.4 | 64.1-66.5 | 16.6-18.0 | 786 / 1,547 | + +"All together" is the tokens of all the chats over the time from the first request to the last answer, prompts +included. "Each chat" is a chat's writing speed as the server reports it (`timings`). On this card most experts run +on the CPU, and requests that route to different experts each need their own, so four chats together wrote 1.34 to +1.44 times as much as one alone. One chat with `"parallel": 4` was 3 to 9% slower than with 1: the slots' VRAM leaves +fewer experts on the card. A card that holds more of the experts may gain more; that was not measured. + +Each slot takes VRAM from the expert cache at load: its 40 window layers' rows and its convolution state. With q8_0 +caches `"parallel": 2` took about 0.5 GiB (it adds two sequences beside the first) and each slot after it about +0.27 GiB (the experts the cache held less, at the average size of a cached expert). Its full-attention rows (17 KiB a +token in q8_0) come out of the cache as its conversation grows, as the first request's do. + +## Guesses from the conversation + +With `--window 4` in the run config's `"args"` (`"--window", "4"`) the engine guesses what comes next where the +answer repeats the conversation: after an earlier repeat of the last three tokens or more (`--lookup N`, default 3) it +takes what followed as up to three guesses, and puts the known token and the guesses through the model together. A +guess counts when the model would have written that token itself, so the answer is the one it writes without +guesses. It is off by default: without `--window` the engine writes one token at a time, identical to `--window 1`. +The model's file has no draft block; its drafter (below) is a file of its own. + +It pays where the answer copies text from the prompt, such as code given back with a change. Elsewhere it guesses +rarely and costs about nothing. On a card that holds few of the experts it gains less: most experts of the guessed +tokens run on the CPU, which takes about as long for a guessed token as for one alone. + +> **Measured on:** RTX 2070 Super 8 GB (Ryzen 5 3600XT, 62 GB DDR4), 128K context, q8_0 caches, the model's expert +> profile. Greedy answers of 300 tokens, two runs each. "Code": a 373-token prompt that asks for a 25-line Python +> file back with a function renamed; "text": a 37-token question on hash tables. + +| | `--window 1` | `--window 4` | Guesses right | +| --- | ---: | ---: | ---: | +| RTX 2070 Super, IQ4_NL, code | 35.1-35.4 tokens/s | 38.8-40.0 | 102 of 119, 115 of 131 | +| RTX 2070 Super, IQ4_NL, text | 36.7-37.8 | 36.7-37.2 | 2 of 12, 4 of 14 | +| RTX 2070 Super, UD-Q2_K_XL, code | 47.1-47.4 | 47.9-48.1 | 40 of 60, 40 of 60 | +| RTX 2070 Super, UD-Q2_K_XL, text | 48.2-48.4 | 48.8-48.8 | 14 of 19, 13 of 19 | + +On a card that holds every expert a window goes through the model as one CUDA graph, as a token alone does (see +above), so the guesses gain on top of the graph's gain. With `--window 4` on a rented RTX 3090 the host handed the card +5.6 launches a window instead of 787 (IQ4_NL) and 24 instead of 921 (UD-Q2_K_XL; nsys, the 128 tokens between a 32- +and a 160-token answer to the 302-token code prompt). + +> **Measured on:** a rented RTX 3090 24 GB, every expert of both sizes in VRAM, strata-poly alone, a 16K context, +> q8_0 caches, 256 tokens written, two runs each. "Code": setup's 302- and 1,500-token code prompts; "prose": a +> 302-token prose prompt. Guesses right: `--window 4`'s. + +| | `--window 1` | `--window 4` | `--window 8` | Guesses right | +| --- | ---: | ---: | ---: | ---: | +| IQ4_NL, code, 302 | 70.8-70.9 tokens/s | 72.8 | 71.5-71.7 | 31 of 50 | +| IQ4_NL, code, 1,500 | 69.8-69.9 | 73.3 | 71.7-71.8 | 54 of 93 | +| IQ4_NL, prose, 302 | 70.7-70.8 | 69.9-70.0 | 69.9-70.0 | 4 of 9 | +| UD-Q2_K_XL, code, 302 | 84.1 | 89.4-89.5 | 88.3-88.7 | 50 of 95 | +| UD-Q2_K_XL, code, 1,500 | 82.8 | 93.8-93.9 | 91.8-92.5 | 70 of 114 | +| UD-Q2_K_XL, prose, 302 | 83.8-84.0 | 120.8-121.3 | 127.8-128.2 | 123 of 128 | + +There `--window 4` and `--window 8` wrote the same 256 tokens as `--window 1`, with the same five likeliest tokens at +every step, and the same with `--no-graphs` (`STRATA_FREEZE_EXPERTS=1`, both sizes, the three prompts). A window of up +to 8 tokens has its experts routed on the card, as a token's are. With the conversation's guesses alone `--window 8` +gains no more than `--window 4` on code. + +With every expert on the CPU (`--no-gpu-experts`), `--window 4` wrote the same 200 tokens as `--window 1`, with the +same five likeliest tokens and their probabilities at every step: IQ4_NL and UD-Q2_K_XL, three prompts each, greedy +(RTX 2070 Super, q8_0 caches). `tools/window_agree.py` runs that check on a model and a prompt of your choice; on +the code prompt (both sizes) and on its own repeated prompt (UD-Q2_K_XL) it found the same 200 tokens and five +likeliest at every step, with 35 to 128 guesses right. With +the card's expert cache holding the same experts (`STRATA_FREEZE_EXPERTS=1`, and for `--window 1` a larger +`--vram-reserve-mib`, because a window's rows take VRAM from the cache), UD-Q2_K_XL's answers were the same too, code +and text. Where the two caches held one expert apart (IQ4_NL: 1,006 and 1,007 of 3,072), they parted at a token the +model rated about as likely as another. + +Without `--window`, 200 greedy tokens were compared with an earlier build's (the same tokens and twenty likeliest +tokens with their probabilities): IQ4_NL and UD-Q2_K_XL, fp16 and q8_0 caches, code and text prompts, every expert on +the CPU and with the cache holding the same experts. 15 of the 16 runs were identical. In the 16th (UD-Q2_K_XL, fp16, +code, experts cached) the two caches never held the same experts (1,864 and 1,869 at load), and the answers first +differ at a token the model rated about as likely as another (ln p1/p2 0.15). + +## Guesses from its DSpark drafter + +Unsloth publishes a small drafter for Inkling 2 Mini, [dspark-Inkling-2-Mini-Q8_0.gguf](https://huggingface.co/unsloth/Inkling-2-Mini-GGUF) +(0.4 GB, three dense layers that read the model's own layers 5, 23, 41 and its output, as llama.cpp's PR 32218 runs +it). With it the engine guesses three tokens a round and puts them through the model with the known one, in one +window. A guess counts only when it is the token the model writes itself. With every expert on the card, or every +expert on the CPU, the greedy answer is the one written without the drafter, token for token. With the experts split +between the card and the CPU (an 8 GB card) it is **not** lossless: the drafter's 0.4 GiB leaves room for fewer +experts in the cache, and the answer can part where the model rates two tokens about equally (see "How it was +checked" below). + +**Turning it on.** Setup asks where the card holds every expert of the size beside the drafter (an RTX 3090 24 GB +with either size, a 16 GB card with UD-Q2_K_XL); the answer's default is no. `--dspark yes` sets it up on any card, +`--dspark no` leaves it out. By hand: `"--draft-model", "/path/to/dspark-Inkling-2-Mini-Q8_0.gguf"` in the run +config's `"args"`. A window is then 4 tokens (`--window N` sets it, `--window 1` turns the drafter off), and +`--lookup` still adds the conversation's repeats. Not with `--parallel` (`--batch`) or several cards. + +**Where it pays.** On a card that holds every expert, and on text it guesses well: code, text that repeats the +prompt. On prose it guesses about half the tokens right and gains little or nothing. On a card that holds few of the +experts it is no faster or slower: the guessed tokens route to experts of their own, and those run on the CPU. The +model's window of guesses is recorded as one CUDA graph (see above); the drafter's own launches go one by one. + +> **Measured on:** a rented RTX 3090 24 GB (every expert of both sizes in VRAM; 256 tokens written, two runs each, +> setup's 302- and 1,500-token code prompts) and a rented RTX 2070 Super 8 GB (31% of IQ4_NL's experts and 68% of +> UD-Q2_K_XL's in VRAM; 200 tokens, one run; "code": the 373-token prompt above, a Python file given back with a +> function renamed; "prose": the 37-token question on hash tables), 2026-11-21/22, strata-poly alone, greedy, q8_0 +> caches, the drafter at its window of 4. + +| | without | with the drafter | guesses right | +| --- | ---: | ---: | ---: | +| RTX 3090, IQ4_NL, code, 302 | 70.8-70.9 tokens/s | 72.3-72.9 tokens/s | 61 of 83, 66 of 84 | +| RTX 3090, IQ4_NL, code, 1,500 | 69.8-69.9 | 78.1-78.4 | 160 of 214 | +| RTX 3090, UD-Q2_K_XL, code, 302 | 84.1 | 103.5-103.9 | 155 of 216 | +| RTX 3090, UD-Q2_K_XL, code, 1,500 | 82.8 | 100.6-100.8 | 151 of 230 | +| RTX 2070 Super, IQ4_NL, code | 17.8 | 17.1 | 109 of 116 | +| RTX 2070 Super, IQ4_NL, prose | 20.4 | 18.2 | 34 of 59 | +| RTX 2070 Super, UD-Q2_K_XL, code | 28.4 | 31.6 | 97 of 112 | +| RTX 2070 Super, UD-Q2_K_XL, prose | 33.8 | 30.3 | 37 of 44 | + +The RTX 2070 Super runs a token launch by launch with or without the drafter (it holds only some of the experts). On +the RTX 3090, prose was measured only while windows still ran launch by launch: there the drafter wrote 2% slower +with IQ4_NL (58.8-59.1 against 60.3 tokens/s, 64 of 120 guesses right) and 9% faster with UD-Q2_K_XL (74.3-74.7 +against 68.3-68.7, 114 of 199). + +Greedy and frozen, the drafter at windows 4 and 8 wrote the same 256 tokens with the same five likeliest at every step +as `--window 1` and as `--no-graphs` (both sizes, those two prompts and a 302-token prose one). + +**VRAM.** The drafter's weights, scratch and window layers' caches took 0.4 GiB at load (the expert cache was that +much smaller with it on the RTX 2070 Super, both sizes), and its full-attention layer keeps 4 KiB a context token in +fp16 whatever `--kv` says (0.5 GiB at 128K). It comes out of the expert cache; setup counts it. + +**How it was checked.** Its guesses against llama.cpp's own drafter (PR 32218, 88025eb) on llama.cpp's inputs +(`poly_dspark_parity`, a record of llama.cpp's run, IQ4_NL, seven guesses a round): 84 of 84, 178 of 179 and 137 of +138 guesses the same on a code, a prose and a 1,523-token prompt (RTX 3090), the largest score difference 0.46. With +every expert on the CPU (`--no-gpu-experts`), its answers were the same 200 tokens with the same five likeliest at +every step as without it (both sizes, code and prose, RTX 2070 Super); with every expert on the card the same 200 +tokens (both sizes, code and prose, RTX 3090). On an RTX 2070 Super 8 GB (961 of IQ4_NL's 3,072 experts in VRAM +without the drafter, 875 with it; UD-Q2_K_XL 2,056 and 1,881), greedy answers with the drafter parted from the ones +without it in 12 of 14 prompts (both sizes, code and prose, 302 to 8,192 tokens, 256 tokens written): each at a step +where the two likeliest tokens were within 0.016-0.18 nats of each other (ln(p1/p2) in the run without the drafter), +as with `--window` above. The cache holds other experts than without the drafter, so a few scores move a little. + +## Long contexts + +A written token's attention reads the whole cache of its 8 full-attention layers, about 17 KiB a token of context in +q8_0, so past 100K it takes most of a token's time. With `--kv q8_0`, `STRATA_KV_INT8=1` (the name Kolibri's opt-in +has) reads a full layer's cache by `__dp4a` once its room is 32K or more (from the 16,385th token), with the queries +quantized to Q8_0 codes too (a 32-value block's delta its largest |value| / 127, about as llama.cpp's flash-attention +kernels do for a quantized cache). Window layers, shorter contexts, the prompt and fp16 caches are left as they are: +there the default kernel was as fast or faster. Unlike Kolibri's, it does not touch the prompt. It is off by default: +it changes the arithmetic, so answers can part from the default's at near-ties. + +> RTX 2070 Super 8 GB (448 GB/s). One token's attention of one full layer, q8_0 cache (`poly_inkling_kernels_test +> decode`); and UD-Q2_K_XL with `--kv q8_0`, a 128K context, one engine per prompt, 64 tokens written + +| | default | `STRATA_KV_INT8=1` | +|---|---|---| +| one layer, room 32K | 268 us | 245 us | +| one layer, room 128K | 1.06 ms | 0.98 ms | +| one layer, room 512K | 4.29 ms | 4.00 ms | +| one layer, room 1M | 8.98 ms (254 GB/s) | 8.32 ms (274 GB/s) | +| writing after a 32,768-token prompt | 39.5 tok/s | 40.9 tok/s | +| writing after a 131,008-token prompt | 29.3 tok/s | 29.9 tok/s | + +On this card most of a token's time at 128K goes to the experts that do not fit in its VRAM, so the gain in writing +speed is small. + +How far it moves the answers, measured on the same card with the experts held fixed at load +(`STRATA_FREEZE_EXPERTS=1`, the same cache both ways), the default against `STRATA_KV_INT8=1`: +- teacher-forced, a 19,500-token prompt then 64 fed tokens: KL 0.0026 a row on average (largest 0.012), the same + most likely token at 65 of 65 rows (IQ4_NL); 0.0091 (largest 0.20), 63 of 65 (UD-Q2_K_XL). After a + 30,000-token prompt and 32 fed tokens: 0.0002 (largest 0.003) and 0.0004 (largest 0.008), 33 of 33 both. +- greedy, 256 tokens written after the 19,500- and the 30,000-token prompts: all 256 the same, both files. +- the checks against llama.cpp (below) are prompts of up to 1,500 tokens, where it does not apply; with it applied + to every layer and room (a build that did, for the test), they stayed in range: 31 or 32 of 32 steps, prompt + cosine 0.99938 to 0.99971. + +## Two or more cards + +Several NVIDIA cards split the model's layers as they do for the other models of strata-poly +([MULTI_GPU.md](../MULTI_GPU.md#the-strata-poly-models)): `--gpus 0,1` at setup, or `"gpu": [0, 1]` and +`"layer_split"` in the run config. Each card keeps the routed experts of its own layers in its VRAM, so two cards hold +more of them than one. The twelve layers that run three times (6 to 17) stay on one card: a later pass runs the +experts the first one has in VRAM. So a card starts at layer 1 to 6 or 18 to 22, which the engine says when it is +given another (`"layer_split": "18"` puts layers 0 to 17 on the first card and 18 to 23 with the output on the second). +`"auto"` shares the layers out by each card's free VRAM and then takes 6 or 18, whichever is nearer. What a card hands +the next one is a token's residual streams, the four blocks' starts and the loop's messages among them: 64.5 KB a token. +A card that holds every expert of its own layers runs a token's layers there as one CUDA graph, as a single card that +holds them all does ([How fast is it?](#how-fast-is-it)); the others run theirs launch by launch. + +Two RTX 3070 8 GB split at 18 wrote 12% to 21% faster than one of them. Split at 6, both models wrote slower than +at 18 (an earlier build on another box). + +> **Measured on:** 2 x RTX 3070 8 GB (rented; PCIe 3.0 x16, no P2P, so the hand-off goes through host memory), a Xeon +> E5-2650 v4 (24 threads), q8_0 caches, the experts each card holds in VRAM, greedy answers of 256 tokens, two runs +> each. The CPU has more cores than a desktop's, so the one-card numbers, and with them what a +> second card adds, are not those of a PC with fewer cores. + +| | One card | Split at 18 | +| --- | ---: | ---: | +| IQ4_NL, after 302 tokens | 44.9-45.1 tokens/s | 52.7-52.8 (+17%) | +| IQ4_NL, after 1,500 tokens | 44.9 | 50.2-50.4 (+12%) | +| UD-Q2_K_XL, after 302 tokens | 56.6-56.9 | 68.0-68.2 (+20%) | +| UD-Q2_K_XL, after 1,500 tokens | 54.3-54.5 | 65.6-65.7 (+21%) | + +At 18 the IQ4_NL cards held 1,175 of layers 0 to 17's 2,304 experts and 694 of layers 18 to 23's 768; UD-Q2_K_XL's +2,194 and all 768. `"auto"` chose 18 too. The prompts read faster split, except UD-Q2_K_XL's of 1,500 tokens: IQ4_NL +221-226 and 640-650 tokens/s on one card, 257-269 and 989-990 split; UD-Q2_K_XL 363-374 and 1,084-1,093 on one card, +493-503 and 1,089-1,096 split. With every expert on the CPU the split gave the same logits as one card to the byte +(both sizes, fp16 and q8_0, split at 18 and `"auto"`; an earlier build at 6 and 3 too), and with the experts in VRAM +held still the split gave the same logits and greedy answers with and without `--no-graphs`. + +## Images + +Setup asks whether you want pictures; the answer is no unless you say yes, so `--yes` installs text only. +`--vision cpu` (or `gpu`, or `yes` for setup's choice by VRAM) adds them: + +```bash +./setup.sh --family inkling --vision cpu +``` + +That downloads ggml-org's image encoder, `mmproj-Inkling-2-Mini-Q8_0.gguf` (0.35 GB), and compiles strata-vision +from llama.cpp 29b52d398b, the commit that added the model and its encoder, into `engine-poly/vision-inkling/`. The +other models' encoder (`engine-poly/strata-vision`, an older llama.cpp) is not changed. The encoder is llama.cpp's +own (its `mtmd` library); PolyStrata places its rows where the template writes the picture +(`<|content_image|>` and one `<|unused_200054|>` for each of the picture's rows after it, in a block of its own, as +llama.cpp does) and does not norm them, as llama.cpp does not. A picture in a tool's message goes in the same way. + +A picture larger than the token limit (setup's 1,024 on the GPU, 300 on the CPU) is made smaller first, as +llama.cpp does with the same limit. A picture costs its rows in the context: 640 x 640 pixels is 256 tokens. + +On an 8 GB card setup puts the encoder on the CPU. Measured on an RTX 2070 Super 8 GB with a Ryzen 5 3600XT +(6 encoder threads), IQ4_NL, flash attention on in the encoder (its default): + +| | 256 rows (640 x 640) | 990 rows (1000 x 2000, at the 1,024 limit) | VRAM | +| --- | ---: | ---: | ---: | +| encoder on the CPU | 2.1 s | 12.3 s | none | +| encoder on the GPU (`--vision gpu`) | 0.06 s | 0.31 s | 576 MiB after its warm-up | + +The photo below (208 rows) took 1.7 s on the CPU (setup's `--vision cpu` build, 6 threads) and 55 ms on the GPU. + +With the encoder on the GPU the engine held 908 routed experts in VRAM instead of 1,038. A prompt with a picture +was read at the speed of a text prompt: 282 tokens with a 256-row picture in 1.2 to 1.35 s (209 to 239 tokens/s in +5 server runs, the encoder on the CPU in 3 of them, on the GPU in 2), 323 tokens of text in 1.4 to 1.5 s (216 and 226 +tokens/s, 2 runs). A whole request (the encode, the prompt and an answer of 90 to 170 tokens) took 6.1 to 8.4 s with +the encoder on the CPU and 3.7 to 6.0 s with it on the GPU. + +**UD-Q2_K_XL** reads pictures too (the same encoder; `--model UD-Q2_K_XL --vision gpu`). With the encoder on the GPU +it read the 282-token prompt at 354 tokens/s and answered at 50 tokens/s; a whole request took 3.3 to 3.8 s. + +**How it was checked.** Against llama.cpp 29b52d398b's `mtmd` on the CPU, for 6 cases (7 drawn pictures from 1 to +990 rows, two of them in one prompt) and a photo (llama.cpp's `tools/mtmd/test-1.jpeg`, a newspaper page, 640 x 488 +pixels, 208 rows), with the Q8_0 encoder and IQ4_NL unless named: + +- **Rows.** strata-vision's were bit-identical to llama.cpp's with flash attention off (the drawn pictures). With + flash attention on (the default) their cosine similarity was 0.98 or more, 0.999 on average (the photo: 0.970 or + more); with the encoder on the GPU 0.965 or more, 0.998 on average, and for the photo 0.957 or more, 0.999 on + average. +- **Logits.** The engine, given llama.cpp's rows, against llama.cpp: cosine similarity of the prompt's logits 0.99986 + or more, and greedy decoding chose the same token in all 33 positions (the prompt's and 32 steps) for every + case and the photo. With `--kv q8_0`: 32 of 33 for the 640 x 640 picture (the miss where llama.cpp's top two were + 0.08 apart; a second run with the fp16 cache missed there too), 33 of 33 for the 990-row picture and the photo + (0.99980). With the photo split across calls (`--prompt-batch 64`): 0.99975, 33 of 33. With the rows normed like + a token's, as the engine did first, it was 0.98485 or more and 29 to 32 of 33. Rows from strata-vision with flash + attention on, from the GPU encoder, or from the BF16 encoder gave the same agreement (0.99989 or more, 33 of 33, + on 2 pictures). +- **UD-Q2_K_XL.** The engine on Unsloth's file against llama.cpp on the same weights (converted to the form + llama.cpp loads, as for the text checks): the photo 0.99990 (33 of 33; `--kv q8_0` 0.99985, 33 of 33), the 640 x + 640 picture 0.99993 (32 of 33, at step 11), the two pictures 0.99984 (33 of 33). +- **Answers.** Asked "Describe the picture in one sentence." at temperature 0 about a 640 x 640 test picture, the + server and `llama-mtmd-cli` both answered: *A light blue background shows a red circle in the upper left, the word + "HELLO" in bold black letters across the middle, and a green square in the lower right.* Two server runs with the + encoder on the CPU gave that answer, one of them installed by setup with `--vision cpu`; two others and two with + it on the GPU worded the same picture a little differently. The engine's runs are not bit-for-bit repeatable, and + the reasoning before the answer has a near tie. About the photo, the `--vision cpu` install answered word for + word as `llama-mtmd-cli`: *A front page of The New York Times from July 20, 1969, with the bold headline "MEN WALK + ON MOON" and a black-and-white photo of the lunar surface and spacecraft.* The `--vision gpu` install read the + same headline, subhead and date and answered *A vintage New York Times front page from July 20, 1969, with the + bold headline "MEN WALK ON MOON" and a black-and-white photo of the lunar surface.* With UD-Q2_K_XL (encoder on + the GPU) the server and `llama-mtmd-cli` both answered *A vintage New York Times front page headlined "MEN WALK ON + MOON" with a black-and-white photo of the lunar surface and spacecraft.*; about the 640 x 640 picture both named + the red circle, "HELLO" and the green square, in other words. + +Why these settings: the Q8_0 encoder is half the BF16 one's download, uses 576 instead of 904 MiB of VRAM and is +faster (256 rows: 2.1 against 3.3 s on the CPU), and the engine's logits were as close to llama.cpp's with either. +Flash attention off made the encoder slower (256 rows 2.8 s, 990 rows 22.7 s on the CPU) and used 1,584 MiB of VRAM +on the GPU, for no change in the logits that could be measured (on the drawn pictures). + +## How it talks + +The server reads these from the tokenizer that setup writes from the GGUF (`pre` = `inkling2`): + +- **Tokens.** Byte-level BPE with 200,058 tokens, llama.cpp's `inkling2` split (its GPT-4o pattern) and, as in the + model's `tokenizer.json`, `ignore_merges`: a piece that is a token as a whole is that token. No token starts a + prompt. A reply ends at `<|content_model_end_sampling|>` (the GGUF's end of text) or at `<|endoftext|>`. +- **Reply.** A reply is a list of blocks. Each starts with `<|message_model|>` and ends with `<|end_message|>`. A + `<|content_thinking|>` block is the reasoning, a `<|content_text|>` block is the answer, and a tool call is + `<|message_model|>NAME<|content_invoke_tool_json|>{"name":"NAME","args":{...}}<|end_message|>`. This is the form + llama.cpp reads (its Inkling parser, ggml-org/llama.cpp PR 32381). The model writes the first header itself. +- **Reasoning effort.** The template writes "Thinking effort level" in a system block. `reasoning_effort` low, medium + and high give 0.2, 0.7 and 0.9. High (0.9) is the default. Thinking turned off gives 0. The model can still think a + little at 0: its model card says the lowest effort does not turn reasoning off. "xhigh" and "max" are 0.9 too, + and "minimal" is thinking off (0), as for every model here: the template's 0.1 and 0.99 are not offered. +- **Sampling.** Setup writes the GGUF's own defaults into the run config: temperature 1.0, top_k 50, top_p 1.0. A + `"sampling"` block you wrote yourself is kept. +- **Forced calls.** `tool_choice` naming one tool is written for the model after its thinking, or at the start of + the reply with thinking off. The reply ends with that call: a block the model opens after it is not sent. + `"required"` with several tools is left to the model. + +## How it was checked + +Token ids against Hugging Face's `tokenizers` library on the model's `tokenizer.json`, the reference. Prompts and +replies against llama.cpp 29b52d398b, the commit that added the model, built on the CPU and run without the model's +weights. 51 of the strings (53 cases), the 14 prompts and the 11 replies are kept in `serve/fixtures/` and checked by +`serve/test_inkling.py`. + +- **Tokens.** 1,006 strings, about 587,000 tokens: English, Japanese, Chinese, Korean, Arabic, Hindi and Russian text, + code, emoji, whitespace runs, control tokens, PolyStrata's docs and source in pieces, and 300 random strings. Every + id was the same as Hugging Face's. llama.cpp's differed in 11 of the strings (see below). +- **Prompts.** 14 requests rendered by llama.cpp's chat code and by the server were the same text: effort levels, a + system prompt, tools, two tool calls and their answers, earlier reasoning, Unicode and quotes. +- **Replies.** 11 replies (llama.cpp's own Inkling tests and a few more) gave the same reasoning, answer and tool calls, + fed whole, in 5-character pieces and one character at a time. + +The engine's output was checked against llama.cpp's on the same files, IQ4_NL and UD-Q2_K_XL, for a short prompt and prompts +of 302 and 1,500 tokens, each run twice: the logits' cosine similarity was 0.9989 to 0.9998, and 16 to 20 of the 20 +most likely tokens were the same. With llama.cpp's own 32-token answer fed in one token at a time, the most likely +token was the same at 29 to 32 of the 32 steps. Where it differed, llama.cpp's two best tokens were within 0.14 of each +other in logit, except at one step (UD-Q2_K_XL, the 1,500-token prompt, in every run), where they were 1.0 apart. Two +runs of the same input do not give identical logits here (cosine 0.9992 between two runs of the 302-token prompt). + +To compare two builds byte for byte with the experts on the card, give both the same `STRATA_GPU_EXPERTS=N` and the +same copy of the expert profile: each build's cache holds the same N experts for the whole run, frozen, whatever VRAM +the build leaves free. Without it the two builds' caches often differ by a few experts (a build that records more +launches leaves less VRAM), and so do their logits. Pick an N a little below what the smaller build caches on its own +(`poly_logits_dump`'s `N of 3072 experts cached` line, `strata-poly`'s `N of 3072 routed experts in VRAM`); one that +does not fit stops the load with an error. With either knob set the load also logs `cache set N experts fnv `, +which experts the cache holds: equal counts are not equal sets (UD-Q2_K_XL's experts come in seven sizes and the cache +takes smaller ones past one that does not fit: 1,640 of them can be any of three sets within 2.5 MiB of cache), so +compare the hash, not the count. + +## Known differences + +- llama.cpp 29b52d398b does not set `ignore_merges` for `inkling2`, so a word that is one token but that no chain of + merges reaches comes out as several there: `kwargs` is one token here and with Hugging Face, three in llama.cpp. + That changed 11 of the 1,006 strings above. PolyStrata follows Hugging Face. `serve/fixtures/inkling2_golden.json` + keeps llama.cpp's ids for one of them (`kwargs`). +- A message whose content is a list of text parts is one block here and one block a part in llama.cpp. The server + joins the parts for every model. +- llama.cpp checks a tool call against the declared tools with a grammar while the model writes it. PolyStrata has no + grammar: it reads the call when its block is closed. A call to a tool that was not declared is shown as text. + +## How does it work? + +The engine side is in `src/poly/inkling.cpp`. The server side is `InklingParser` in `serve/frontend.py`, and the tests +are `serve/test_inkling.py` and `tools/test_setup_inkling.py`. diff --git a/include/strata/hip_compat/cuda.h b/include/strata/hip_compat/cuda.h index 7e28df9aa7..51e585c7da 100644 --- a/include/strata/hip_compat/cuda.h +++ b/include/strata/hip_compat/cuda.h @@ -18,6 +18,12 @@ #define STRATA_VMM_MAP_SETTLES 1 #endif +// ROCm 7.2.4 (WSL2, librocdxg 1.2.2, an RX 9070 XT) refuses hipMemSetAccess (hipErrorInvalidValue) on a piece mapped +// after a larger one in the same reservation - 64 MiB then 1 MiB, 2 then 1, 64 then 4 - while pieces of one size +// always pass (64 + 64, 8 + 8, 1 + 1 MiB): the expert cache lost its odd last piece, and an attention cache grown to +// its reservation's end failed. Engine::vmm_map() maps a reservation in pieces of one size. +#define STRATA_VMM_EQUAL_PIECES 1 + typedef hipError_t CUresult; typedef int CUdevice; // HIP's own CUdeviceptr/handle equivalents are pointer-typed; CUDA's are integers, and strata-poly's Mapped diff --git a/include/strata/hip_compat/cuda_runtime.h b/include/strata/hip_compat/cuda_runtime.h index 72a77a19f3..f60f669cf4 100644 --- a/include/strata/hip_compat/cuda_runtime.h +++ b/include/strata/hip_compat/cuda_runtime.h @@ -18,9 +18,12 @@ #define cudaDevAttrMaxSharedMemoryPerBlockOptin hipDeviceAttributeMaxSharedMemoryPerBlock #define cudaDevAttrMultiProcessorCount hipDeviceAttributeMultiprocessorCount #define cudaDevAttrClockRate hipDeviceAttributeClockRate +#define cudaDevAttrCooperativeLaunch hipDeviceAttributeCooperativeLaunch #define cudaDevAttrComputeCapabilityMajor hipDeviceAttributeComputeCapabilityMajor #define cudaDevAttrComputeCapabilityMinor hipDeviceAttributeComputeCapabilityMinor #define cudaDevAttrIntegrated hipDeviceAttributeIntegrated +#define cudaDevAttrMemoryClockRate hipDeviceAttributeMemoryClockRate +#define cudaDevAttrGlobalMemoryBusWidth hipDeviceAttributeMemoryBusWidth #define cudaDeviceGetAttribute hipDeviceGetAttribute #define cudaDeviceCanAccessPeer hipDeviceCanAccessPeer #define cudaDeviceEnablePeerAccess hipDeviceEnablePeerAccess @@ -56,6 +59,7 @@ #define cudaGetDeviceProperties hipGetDeviceProperties #define cudaGetErrorString hipGetErrorString #define cudaGetLastError hipGetLastError +#define cudaOccupancyMaxActiveBlocksPerMultiprocessor hipOccupancyMaxActiveBlocksPerMultiprocessor #define cudaGraphDestroy hipGraphDestroy #define cudaGraphExecDestroy hipGraphExecDestroy #define cudaGraphExec_t hipGraphExec_t @@ -80,6 +84,7 @@ #define cudaHostRegisterPortable hipHostRegisterPortable #define cudaHostRegisterReadOnly hipHostRegisterReadOnly #define cudaHostUnregister hipHostUnregister +#define cudaLaunchCooperativeKernel hipLaunchCooperativeKernel #define cudaLaunchHostFunc hipLaunchHostFunc #define cudaMalloc hipMalloc #define cudaMallocHost(...) (::strata::hip_compat::malloc_host(__VA_ARGS__)) @@ -153,6 +158,7 @@ inline hipError_t mem_get_info(size_t* free_bytes, size_t* total_bytes) { #define cudaRuntimeGetVersion hipRuntimeGetVersion #define cudaSetDevice hipSetDevice #define cudaStreamBeginCapture hipStreamBeginCapture +#define cudaStreamCaptureModeRelaxed hipStreamCaptureModeRelaxed #define cudaStreamCaptureModeThreadLocal hipStreamCaptureModeThreadLocal #define cudaStreamCaptureStatus hipStreamCaptureStatus #define cudaStreamCaptureStatusNone hipStreamCaptureStatusNone diff --git a/include/strata/kernels/native_mmvq.hpp b/include/strata/kernels/native_mmvq.hpp index be10f97f7a..d533d1d297 100644 --- a/include/strata/kernels/native_mmvq.hpp +++ b/include/strata/kernels/native_mmvq.hpp @@ -51,6 +51,18 @@ void native_quantize_q8_1(const float* x, void* x_q8_1, int n_in, int ncols, /// keeps the sum. n is a multiple of 32. void native_add_rms_norm_q8_1(float* x, const float* add, const float* w, float* y, void* y_q8_1, int n, int rows, float eps, int threads, void* stream); +/// native_add_rms_norm_q8_1() without add of `count` rows that each have their own x, w, y and y_q8_1 (a layer's +/// inputs of Q, K and V, each normed with its own weight), in one launch, a block a row: each row's bits are the +/// call's for it alone. False, with nothing launched, where there is no such kernel (Metal): the caller makes the +/// calls. +constexpr int kNormRowsMax = 4; +struct NormRows { + const float* x[kNormRowsMax]; + const float* w[kNormRowsMax]; + float* y[kNormRowsMax]; + void* y_q8_1[kNormRowsMax]; +}; +bool native_rms_norm_q8_1_rows(const NormRows& rows, int count, int n, float eps, int threads, void* stream); void native_swiglu_quantize_q8_1(const float* gate, const float* up, void* x_q8_1, int n_in, int ncols, void* stream); @@ -146,6 +158,13 @@ struct MmvqSlots { const void* w[kMmvqSlotsMax]; const void* x[kMmvqSlotsMax]; float* y[kMmvqSlotsMax]; + // The same bits through other kernels: native_mmvq.cu's formats a warp a row instead of a block of WARPS warps + // (lane l with the terms of the block's threads l, 32 + l, ..., added in the block's order), where the block's + // threads had uneven work; the IQ formats whose grid iq_kernels.cu stages in shared memory (IQ1_S, IQ1_M, IQ2_XXS, + // IQ2_XS, IQ2_S), 8 rows a warp with the grid staged once. The other IQ formats' launches are as without it. + // Faster for Inkling 2's experts on an RTX 2070 Super; measured on CUDA only. It takes precedence over + // native_mmvq_slots_wide() (on by default on HIP); Metal takes no notice. + bool lanes = false; }; bool native_mmvq_slots(int ggml_type, const MmvqSlots& slots, int count, int n_in, int n_out, void* stream); // Whether the slots launches take a warp per row group where a row's blocks fit one warp (an expert's IQ4_XS down @@ -166,9 +185,25 @@ struct MmvqIds { int x_every; float* y; std::size_t y_stride; + bool lanes = false; // as MmvqSlots::lanes }; bool native_mmvq_ids_supported(int ggml_type); bool native_mmvq_ids(int ggml_type, const MmvqIds& ids, int count, int n_in, int n_out, void* stream); +// Several matrices of one format and input width in one launch (an attention's projections of the same input), each +// with its own rows, Q8_1 columns and output: native_mmvq(type, w[i], x[i], y[i], n_in, n_out[i], ncols, stream) +// for each, bit for bit. Q8_0, Q4_K, Q5_K and Q6_K. False, with nothing launched: another format, a repacked +// matrix, or a layout the switches above chose whose bits these are not; the caller launches them one by one. +constexpr int kMmvqJobsMax = 8; +struct MmvqJobs { + const void* w[kMmvqJobsMax]; + const void* x[kMmvqJobsMax]; + float* y[kMmvqJobsMax]; + int n_out[kMmvqJobsMax]; +}; +bool native_mmvq_jobs(int ggml_type, const MmvqJobs& jobs, int count, int n_in, int ncols, void* stream); +/// native_mmvq_jobs() of one column for matrices of several of its formats, types[i] matrix i's: each its bits. +/// False, with nothing launched, as native_mmvq_jobs() declines. +bool native_mmvq_jobs_mixed(const int* types, const MmvqJobs& jobs, int count, int n_in, void* stream); // Storage/dispatch helpers take stable GGML type IDs, avoiding a ggml runtime // dependency in the engine: Q4_0=2, Q5_0=6, Q8_0=8, Q2_K=10, Q3_K=11, Q4_K=12, Q5_K=13, diff --git a/include/strata/platform/hip_compat/strata_hip.h b/include/strata/platform/hip_compat/strata_hip.h index 180a1f6d68..07db30ee12 100644 --- a/include/strata/platform/hip_compat/strata_hip.h +++ b/include/strata/platform/hip_compat/strata_hip.h @@ -85,6 +85,7 @@ #define cudaSetDevice hipSetDevice #define cudaGetDeviceCount hipGetDeviceCount #define cudaGetDeviceProperties hipGetDeviceProperties +#define cudaOccupancyMaxActiveBlocksPerMultiprocessor hipOccupancyMaxActiveBlocksPerMultiprocessor // The shared-memory opt-in limit: some HIP versions report 0 for it on GCN cards; the real ceiling there is // the plain per-block limit (64 KB of LDS on gfx906). inline hipError_t strata_device_get_attribute(int* v, hipDeviceAttribute_t a, int dev) { diff --git a/include/strata/poly/inkling_kernels.hpp b/include/strata/poly/inkling_kernels.hpp new file mode 100644 index 0000000000..78438ee6be --- /dev/null +++ b/include/strata/poly/inkling_kernels.hpp @@ -0,0 +1,476 @@ +// include/strata/poly/inkling_kernels.hpp - the kernels Inkling 2 Mini (llama.cpp architecture "inkling2_loop", +// ggml-org/llama.cpp 29b52d398b, src/models/inkling2.cpp and inkling2-loop.cpp) needs beyond kernels.hpp's. +// +// Every call enqueues on the given CUDA stream and returns. Pointers are device pointers. A call works on `rows` +// tokens at consecutive positions, a buffer of per-token values holding them row after row (kernels.hpp's rule). +// ggml shapes are written [ne0, ne1, ...]: ne0 is the contiguous one, so ggml [a, b] is b rows of a floats. +// +// ============================================================================================================ +// THE MATH (derived from upstream at 29b52d398b; file:line are that commit's) +// ============================================================================================================ +// +// clip(x, s, c) (inkling2.cpp graph::clip) +// v = x * s (s per channel, optional); n = sqrt(sum v^2) + 1e-6; y = v * clamp(c / n, 0, 1). +// Per head: Q with s = attn_q_clip [128, 24] and c = qk_clip (22.627417), K with no s and c = qk_clip, +// R with s = attn_rel_clip [16, 24] and c = relative_clip (8). V is rms_norm(v, eps = f_norm_rms_eps) per head +// without a weight. +// +// tau (full-attention layers only; inkling2.cpp build_inputs) +// tau(p) = 1 + alpha * log(max(1, (p + 1) * (1 / floor))), floor = log_scale_floor (8192), alpha = 0.1, +// p the token's position. Q and R (after their clips) are multiplied by tau. SWA layers: no tau. +// +// attention (inkling2.cpp build_layer; llama-graph.cpp:4436-4515; llama-kv-cache.cpp:2010-2022) +// For query token i (position p) and head h, against the cached key at position j (group g = h / 3): +// d = p - j (llama-kv-cache.cpp:2017) +// idx = (0 <= d < extent) ? d : extent (llama-kv-cache.cpp:2018; an empty cell is d = -1, +// so idx = extent too, and the mask hides it) +// table = mul_mat(pad(attn_rel_bias, +1 row of zeros), R): bias(i,h,e) = sum_r rel_bias[e][r] * R[i][h][r] +// for e < extent, and 0 for e = extent (the padded row; +// inkling2.cpp "ggml_pad(..., 0, 1, ...)") +// logit(i,h,j) = scale * (Q[i][h] . K[j][g]) + bias(i,h,idx) - sink[i][h] + mask(i,j) +// the softmax has one more logit, 0, with no value (the "zero sink" passed to build_attn) +// scale = 1/sqrt(128). The mask (llama-hparams.h:563-575, LLAMA_SWA_TYPE_STANDARD) hides j > p and, on SWA +// layers, p - j >= n_swa (1024): a SWA token attends the 1024 positions p-1023..p, itself among them. Full +// layers attend 0..p; distances >= extent (1024) get bias 0. extent = relative_extent on full layers and n_swa +// on SWA layers (attn_rel_bias is [16, extent] either way; both are 1024 in the released GGUF). +// Since exp(s - t) / (1 + sum exp(s - t)) = exp(s) / (exp(t) + sum exp(s)), this is the same softmax as +// logit(i,h,j) = scale * Q.K + bias(i,h,idx), with one extra logit t = sink[i][h] that weighs no value, +// which is what inkling_attend() computes (as Flint's sinks, but per query token: sink = attn_sink_proj(x_q), +// [24] a token, no scale). The bias is added after the 1/sqrt(128) scale (ggml_soft_max_ext / flash attn add +// the mask to the scaled product). Upstream with flash attention casts the summed mask (bias - sink) to F16; we +// keep it in float. +// Then out *= sigmoid(attn_gate(x_q)) per value (mul_sigmoid), then wo, then the post-conv. +// +// convolve(x, w, taps) (inkling2.cpp graph::convolve; ggml_ssm_conv = ggml-cpu/ops.cpp:9942-9993) +// n_conv = 4. xx is the channel's inputs, the 3 stored past ones (oldest first) and then the call's. +// y_t = sum_{k=0..3} w[c][k] * xx[t - 3 + k] (ssm_conv: w[c][3] is the current token's tap) +// with taps (full layers' K and V; taps = attn_{k,v}_conv_proj(x_{k,v}) [4 * 8] a token, head-major): +// y_t += sum_{lag=0..3} taps[t][h][lag] * xx[t - lag] (h = c / 128; NOTE the other orientation: lag 0 +// is the current token) +// out_t = (x_t + y_t) * 1/sqrt((taps ? 2 : 1) * 4 + 1) (1/3 with taps, 1/sqrt(5) without) +// The state keeps the last 3 inputs x (before the convolution), per channel, oldest first. Upstream keeps the +// four convolutions of a layer in one state at channel offsets K 0, V 1024, attn-out 2048, ffn-out 2048 + 2304 +// (n_sconv_channels 6656); here each call takes the pointer to its own part (state + offset * 3). +// K conv input: wk(x_k) (1024), V: wv(x_v) (1024), attn-out: wo(gated attention) (2304), ffn-out: the MoE +// output (2304). The clip / rms of K and V come after their convolutions. +// +// mix(blocks, cur, query) (inkling2.cpp graph::mix) +// S = {blocks..., cur}, each rms_norm'ed without weight, eps 1e-6: s_hat = s / sqrt(mean(s^2) + 1e-6). +// score[q][k] = (s_hat_k . query[q]) / sqrt(n_embd); w = softmax over k; out[q] = sum_k w[q][k] * s_hat_k. +// The output mixes the NORMED states. The order of S does not matter (upstream concatenates in reverse). +// Queries: attn_res_query [2304, 1] on SWA layers (one input for Q, K and V), [2304, 3] on full layers (Q, K, V +// inputs), ffn_res_query [2304], output_res_query [2304], loop_msg_query [2304, 4] (Q, K, V, FFN messages). +// +// control(cur, msg) (inkling2.cpp graph::control) +// z = [rms_norm(cur), rms_norm(msg)] (eps 1e-6, no weights, 2 * 2304); r = ctrl_down z (64); +// gain = tanh(ctrl_gain r), forget = tanh(ctrl_forget r) (2304 each); out = (cur - forget * cur) + gain * msg. +// +// SiTU (llama-graph.cpp:2666-2680; the dense build_ffn path aborts, only the MoE path has it) +// gate_up row = [gate (n_ff), up (n_ff)] (the fused ffn_gate_up_exps output, gate first, llama-graph.cpp:2580ff) +// act = beta * tanh(gate * (1 / beta)) * sigmoid(gate); up' = lb > 0 ? lb * tanh(up * (1 / lb)) : up; +// out = act * up'. beta = situ_beta (4), lb = situ_linear_beta (25). +// +// router (llama-graph.cpp:2420-2560): probs = sigmoid(logits) (logits in F32), pick top-8 of probs + exp_probs_b, +// weights = probs of the picked, divided by (sum + 1e-20) (expert_weights_norm_eps), times expert_weights_scale +// (8). kernels.hpp route_rows(gate 1, bias exp_probs_b, norm true, w_scale 8) does this, with a floor of +// 6.1e-5 under the sum instead of + 1e-20: the same for any real sum of 8 sigmoids. +// +// ============================================================================================================ +// WHICH KERNEL DOES WHAT (src/poly/inkling.cpp; "few tokens" is up to Inkling::kFusedRows, 16) +// ============================================================================================================ +// tok_norm, output_norm rms_norm() (kernels.hpp) +// attn_norm, q/k/v_inp_norm, ffn_norm native_add_rms_norm_q8_1 (native_mmvq.hpp), which +// also gives the projections their Q8_1 input +// wq, wk, wv, wo, attn_gate, attn_rel, sink_proj, conv_proj the engine's lin() +// ffn_gate_inp (F32) inkling_gemv() for a few tokens, else the engine's +// router_scores() +// loop ctrl_down / gain / forget (F32) inkling_control_fused() for a few tokens, else +// inkling_control() +// K and V: conv, K clip, V rms norm, into the cache inkling_kv_store() +// (rings as Flint's: row of position p at p % ring) +// Q and R clips, tau inkling_clip_many() +// attention with the relative bias and per-token sinks inkling_attend() +// output gate mul_sigmoid(att, gate, 3072, rows, 3072, false) +// attn-out conv: a block's first layer (the stream afresh) inkling_conv() +// attn-out conv and residual add: the other layers inkling_conv_acc() +// ffn-out conv and residual add inkling_conv_acc() +// depth mix (attn/ffn/output residual queries, messages) inkling_mix() +// router route_rows(gate 1, exp_probs_b, norm, 8.0) +// experts' gate_up -> activation situ_rows() (the engine's act_rows(); the CPU +// experts have their own) +// expert sum the engine's moe_sum(), from zero (no shared expert) +// final softcap (30) softcap() +// step()'s rows (--batch), each of its own sequence: K/V, inkling_kv_store_seqs(), inkling_clip_many_seqs(), +// tau, attention and the post-convolutions with each row's inkling_attend_seqs(), inkling_conv_seqs(), +// caches, state and position; the rest as above, once inkling_conv_acc_seqs() +// for all the rows +#pragma once + +#include "strata/poly/kernels.hpp" + +#include +#include + +namespace strata::poly { + +// ---- clips --------------------------------------------------------------------------------------------------- + +/// The log scale of the full-attention layers: tau(p) = 1 + alpha * log(max(1, (p + 1) * (1 / floor))). A +/// default-constructed one (floor 0) is off: tau = 1. +struct InklingTau { + float alpha = 0.f; + int floor = 0; +}; + +/// clip() for `rows` tokens of `heads` heads of `dim` values: y = v * min(1, threshold / (|v| + 1e-6)), v = x * scale +/// (scale: heads * dim values, head-major as ggml's [dim, heads]; null: none), then times tau(the token's position) +/// when tau.floor > 0. A token's input starts x_stride floats after the one before it (0: heads * dim); y has +/// heads * dim values a token. y may be x when x_stride is 0 or heads * dim. Token t is at position pos + t. +/// dim <= 1024. +void inkling_clip(const float* x, int x_stride, const float* scale, float* y, int dim, int heads, int rows, + float threshold, InklingTau tau, int64_t pos, void* stream); + +// ---- attention ----------------------------------------------------------------------------------------------- + +/// The relative-position bias of a layer: r is the clipped (and on full layers tau-scaled) R, n_head * n_rel +/// floats a token (head-major); table is attn_rel_bias as stored, extent rows of n_rel floats (ggml [n_rel, extent]). +/// n_rel <= 32. +struct InklingRel { + const float* r = nullptr; + const float* table = nullptr; + int n_rel = 16; + int extent = 1024; +}; + +/// The floats inkling_attend()'s `work` needs for its split path: calls of up to kInklingSplitRows tokens of +/// n_head heads. 0 work (null) is allowed: every call then takes the unsplit path. +inline constexpr int kInklingSplitRows = 16; ///< calls of more tokens never split (a prompt batch) +/// a call's keys go in at most this many splits (+1 for a window's offset) +inline constexpr int kInklingMaxSplits = 64; +size_t inkling_attend_work_floats(int n_head, int dim); +/// calls of at least this many tokens take the tensor-core path on cards that have it (Turing or newer, CUDA): every +/// call of more than kInklingSplitRows tokens (on an RTX 2070 Super, 17 tokens at position 8192 took 0.88 ms on the +/// tensor cores against 5.2 ms unsplit in a full layer, 0.15 against 0.74 ms in a window layer) +inline constexpr int kInklingMmaRows = kInklingSplitRows + 1; + +/// Inkling's attention for the `rows` tokens from position `pos`: token t (position p = pos + t) of head h attends +/// the cached rows of positions max(0, p - window + 1) .. p (window 0: 0 .. p) with +/// logit(j) = scale * q[t][h] . k[j][h / (n_head / kv_heads)] + bias(t, h, p - j), +/// bias(t, h, d) = d < rel.extent ? sum_r rel.table[d * n_rel + r] * rel.r[(t * n_head + h) * n_rel + r] : 0, +/// and one more logit, sinks[t * n_head + h], that weighs no value (sinks may be null: none). out: n_head * dim a +/// token. The keys and values must already be in the caches (store them first, as Flint does). +/// Caches: fp16, kv_heads * dim halves a row (kcache / vcache), or Q8_0 where kq8 / vq8 codes are not null (the +/// fp16 pointer is then ignored), in kernels.hpp's Kvq8 layout. With `ring`, position j is row j % ring; ring must +/// hold window + rows - 1 rows (Flint's ring_ = window + rows_ does). +/// dim must be 128 and n_head / kv_heads 3 (Inkling's 24 / 8); else std::invalid_argument. +/// +/// Three paths, the same math; the first two float throughout (the caches' halves are the only rounding): +/// - split (rows <= kInklingSplitRows and work != null): the keys go in splits of S keys counted from position 0, +/// S = max(32, keys / kInklingMaxSplits rounded up to 32), keys = room (a window layer: min(room, window)), +/// one block a split, group and token (each of its warps four keys at a time, no shared-memory tiles), merged by +/// a second launch when there is more than one split (with one, the block writes the output itself). A token's +/// result then does not depend on the tokens beside it in the call (for the same room). `room` is the most +/// positions + 1 a token of the call can have: the launch is sized for it (as attend()'s room); 0 means +/// pos + rows. Calls given the same room split the same way. q and the caches must be 16- and 8-byte aligned +/// (cudaMalloc'd rows of 128 values are). +/// With `int8_dot` (STRATA_KV_INT8), Q8_0 keys and values and a full layer (window 0), the rows whose splits are +/// of 512 keys or more (a room of 32K or more) quantize the queries to Q8_0 codes as well (a 32-value block's +/// delta its largest |value| / 127, about as llama.cpp's flash-attention kernels do for a quantized K) and take +/// each score as __dp4a dots of the codes times the two deltas, a key 8 lanes with 16-byte loads of its codes +/// (the caches must then be 16-byte aligned): other arithmetic, so other bits. A row's kernel depends on its own +/// split only. fp16 caches, window layers, shorter rooms and the other paths ignore it. +/// - unsplit: one block walks all the keys of a tile of up to 8 tokens. +/// - tensor cores (rows >= kInklingMmaRows, rel.n_rel 16, a CUDA card of Turing or newer; else unsplit): a prompt +/// batch. One block walks all the keys of 21 tokens of a group; the queries, R, the softmax's weights and the bias +/// table's rows are rounded to halves, the caches' values too (a Q8_0 code times its scale), and the products sum +/// floats (llama.cpp's flash attention rounds Q, P and V the same way); the bias stays a float. A token's result +/// does not depend on the tokens beside it in the call. On an A100 (sm_80), in a full layer's call that reaches +/// past 2,048 keys, blocks of 85 tokens take each key and value to twice the rows and copy the next keys in +/// while they work, to the same bits; `mma` = InklingMma::turing or ::fa2 asks for one kernel or the other on any +/// card of the path (a test, to compare them; ::fa2 throws std::invalid_argument on a card without the shared +/// memory, 94 KB a block). +/// `at` (null: pos): the first token's position on the card, read when the launch runs, for a launch recorded in a +/// CUDA graph and replayed at later positions (Engine::at_). The same kernels as for pos, so the same bits. It +/// takes the split path, which is then sized by room alone: room > 0 and work enough (else std::invalid_argument). +/// `gate` (null: none): the output gate, out *= sigmoid(gate) (n_head * dim a token), as mul_sigmoid() after the +/// call gives it, the same bits; the split path applies it as it writes the output, the others with mul_sigmoid(). +/// `out_q8_1` (null: none): out's Q8_1 blocks too, as native_quantize_q8_1(out, out_q8_1, rows * n_head * dim, 1) +/// gives them, the same bits (the split path writes them with the output). +/// Throws std::runtime_error on a launch error. +enum class InklingMma { best, turing, fa2 }; +void inkling_attend(const float* q, const uint16_t* kcache, const uint16_t* vcache, Kvq8 kq8, Kvq8 vq8, + InklingRel rel, const float* sinks, int64_t pos, int rows, float* out, int dim, int n_head, + int kv_heads, float scale, int window, int ring, float* work, size_t work_floats, void* stream, + int64_t room = 0, bool int8_dot = false, const long long* at = nullptr, + const float* gate = nullptr, void* out_q8_1 = nullptr, + InklingMma mma = InklingMma::best); + +// ---- short convolutions -------------------------------------------------------------------------------------- + +/// convolve() over `channels` channels with 4 taps: out_t = (x_t + y_t) / sqrt(taps ? 9 : 5), see the top. x and +/// out: channels values a token (out must not be x). w: attn_*_conv / ffn_post_conv, (4, channels) as ggml +/// [4, channels] (w[c * 4 + k], k = 3 the current token). taps: null, or `heads` * 4 values a token (the +/// conv_proj output, taps[t * heads * 4 + h * 4 + lag], lag 0 the current token), channel c in head +/// c / (channels / heads). state: 3 past inputs a channel, oldest first, advanced here by `rows` tokens. +void inkling_conv(const float* x, float* state, const float* w, const float* taps, int heads, float* out, + int channels, int rows, void* stream); + +/// A window's snapshots of a convolution's state (Engine::window()): for the k-th token t of the call whose bit is +/// set in `bits` (t < rows), the state as inkling_conv() leaves it after tokens 0 to t, into snap + k * stride +/// (floats). x and state as inkling_conv()'s, before the call advances the state. +void inkling_conv_snaps(const float* x, const float* state, int channels, int rows, unsigned bits, float* snap, + size_t stride, void* stream); + +// ---- depth mix ----------------------------------------------------------------------------------------------- + +inline constexpr int kInklingMaxStates = 8; +/// mix()'s inputs: up to kInklingMaxStates states (the earlier blocks' outputs, then cur), each rows * n values, +/// and n_query queries (query: n_query rows of n floats, ggml [n, n_query]) each with its own output +/// (rows * n floats). n_query <= 4. +struct InklingMix { + const float* state[kInklingMaxStates] = {}; + int n_state = 0; + const float* query = nullptr; + int n_query = 1; + float* out[4] = {}; +}; +/// out[q][t] = sum_k softmax_k(s_hat_k[t] . query[q] / sqrt(n)) * s_hat_k[t], s_hat = rms_norm(s, eps) without a +/// weight (upstream's eps is 1e-6). An output may be one of the states only when n_query is 1. +void inkling_mix(const InklingMix& m, int n, int rows, float eps, void* stream); + +// ---- loop controller ----------------------------------------------------------------------------------------- + +/// control() whole, for rows tokens: z = [rms_norm(cur), rms_norm(msg)] (eps), r = down z, then +/// out = (cur - tanh(forget r) * cur) + tanh(gain r) * msg. down: rank rows of 2 * n floats (ggml [2n, rank]); +/// gain and forget: n rows of rank floats (ggml [rank, n]); all F32. work: rows * (2 * n + rank + 2 * n) floats. +/// Uses gemv_f32 for fewer than 8 rows, else gemm_f32 on `blas` (blas_create on this stream; may be null below 8 +/// rows). out may be cur. +void inkling_control(void* blas, const float* cur, const float* msg, const float* down, const float* gain, + const float* forget, float* work, float* out, int n, int rank, int rows, float eps, + void* stream); + +// ---- fused decode-path steps --------------------------------------------------------------------------------- +// +// Each of these does what a sequence of the calls above does, in fewer launches, for the few tokens of a decode +// step. The results agree with the sequence's to float rounding (the sums go in another order), except where a +// comment says "the same bits". + +/// inkling_control_fused()'s largest rank (loop.gate_rank): a lane of a warp holds two of its values. +inline constexpr int kInklingMaxRank = 64; + +/// One loop controller of inkling_control()'s: cur and msg (rows * n each), its three F32 matrices, and where out +/// goes (out may be cur). +struct InklingCtrl { + const float* cur = nullptr; + const float* msg = nullptr; + const float* down = nullptr; ///< rank rows of 2n (ggml [2n, rank]) + const float* gain = nullptr; ///< n rows of rank (ggml [rank, n]) + const float* forget = nullptr; ///< n rows of rank + float* out = nullptr; +}; +/// inkling_control() for `count` (1 to 4) controllers at once (a looped visit's Q, K and V, whose inputs are ready +/// together; or one), in two launches whatever the count: the norms and the down projection, then gain, forget +/// and the combine. Sums in float. rank <= kInklingMaxRank, n a multiple of 4; cur, msg and down 16-byte aligned +/// (they are read a float4 at a time; cudaMalloc'd rows of a multiple of 4 floats are). work: count * rows * rank +/// floats. Rows go four at a time (each four re-read the matrices). Throws std::invalid_argument. +void inkling_control_fused(const InklingCtrl* ctrl, int count, int n, int rank, int rows, float eps, float* work, + void* stream); + +/// y[t][o] = w[o] . x[t] for rows (<= 4 at a time; more go four by four) tokens: gemv_f32 / gemm_f32's product +/// (rows_per_x = n_out) for a decode step, a warp an output, the matrix read once for the tokens. w: F32. n_in a +/// multiple of 4, w and x 16-byte aligned. E.g. the router's ffn_gate_inp [2304, 128]. +void inkling_gemv(const float* w, const float* x, float* y, int n_in, int n_out, int rows, void* stream); + +/// Several inkling_clip() calls of the same tokens in one launch (Q and R of a layer; K too when it is not done by +/// inkling_kv_store()). The same bits as the separate calls. +struct InklingClipJob { + const float* x = nullptr; + int x_stride = 0; + const float* scale = nullptr; + float* y = nullptr; + int dim = 0, heads = 0; + float threshold = 0.f; + InklingTau tau; +}; +/// count <= 4. at: as inkling_attend()'s (null: pos). +void inkling_clip_many(const InklingClipJob* jobs, int count, int rows, int64_t pos, void* stream, + const long long* at = nullptr); + +/// Where inkling_kv_store() puts a layer's keys and values: fp16 (k, v) or Q8_0 (kc/ks, vc/vs, kernels.hpp's Kvq8 +/// layout), each row kv_heads * dim; with ring > 0 position p is row p % ring. +struct InklingKvDst { + uint16_t* k = nullptr; + uint16_t* v = nullptr; + int8_t* kc = nullptr; + uint16_t* ks = nullptr; + int8_t* vc = nullptr; + uint16_t* vs = nullptr; + int ring = 0; +}; +/// A layer's K and V from their projections to the cache, in one launch for up to 16 tokens: +/// k = inkling_conv(kraw, k_state, k_w, k_taps) then inkling_clip(k, no scale, k_clip), +/// v = inkling_conv(vraw, v_state, v_w, v_taps) then rms_norm(v, no weight, eps) a head, +/// both into dst at the tokens' positions (from pos) as store_f16 / store_q8 would write them (the same bits), +/// and into k_out / v_out (rows * kv_heads * dim floats each) when they are not null. +/// Taps (null: none) and the states as inkling_conv()'s. dim 128. More than 16 tokens take the separate calls +/// (the same results), which work in k_out and v_out: both must then be given (else std::invalid_argument). +/// at: as inkling_attend()'s (null: pos), for up to 16 tokens (else std::invalid_argument). +void inkling_kv_store(const float* kraw, const float* vraw, float* k_state, float* v_state, const float* k_w, + const float* v_w, const float* k_taps, const float* v_taps, int kv_heads, int dim, int rows, + float k_clip, float eps, const InklingKvDst& dst, int64_t pos, float* k_out, float* v_out, + void* stream, const long long* at = nullptr); +/// inkling_kv_store() and inkling_clip_many(jobs, count) of the same tokens in one launch, the same bits as the two +/// calls (which more than 16 tokens, or no jobs, take). +void inkling_kv_store_clip(const float* kraw, const float* vraw, float* k_state, float* v_state, const float* k_w, + const float* v_w, const float* k_taps, const float* v_taps, int kv_heads, int dim, int rows, + float k_clip, float eps, const InklingKvDst& dst, int64_t pos, float* k_out, float* v_out, + const InklingClipJob* jobs, int count, void* stream, const long long* at = nullptr); + +/// inkling_conv() whose output is added to acc (acc += out) instead of written: the attention's and the FFN's +/// post-convolutions and the residual adds after them (axpy) in one launch. The same bits as inkling_conv() then +/// axpy(out, 1, acc, add). +void inkling_conv_acc(const float* x, float* state, const float* w, const float* taps, int heads, float* acc, + int channels, int rows, void* stream); + +/// A post-convolution of one token (inkling_conv() or inkling_conv_acc(), no taps) into the stream acc, n channels. +/// The input is x, or with `parts` the experts' sum moe_sum() leaves in a zeroed buffer: sum over k < n_parts of +/// weights[k] * parts[k * n + c], in that order. With `save`, acc as it was goes there first (a block's start). +struct InklingConvIn { + const float* x = nullptr; + const float* parts = nullptr; + const float* weights = nullptr; + int n_parts = 0; + float* state = nullptr; ///< 3 past inputs a channel, as inkling_conv()'s + const float* w = nullptr; + float* acc = nullptr; + float* save = nullptr; + bool fresh = false; ///< acc = conv (inkling_conv()), not acc += conv (inkling_conv_acc()) +}; +/// The convolution alone, a thread a channel: the same bits as inkling_conv() / inkling_conv_acc() of the input (after +/// moe_sum() into a zeroed buffer, with parts) and the copy before it. +void inkling_conv_in(const InklingConvIn& c, int n, void* stream); +/// The norms of a mix's outputs, one for each of its queries: native_add_rms_norm_q8_1(out[q], no add, w[q], y[q], +/// y_q8_1[q], n, 1 row, eps, threads). +struct InklingMixNorm { + const float* w[4] = {}; + float* y[4] = {}; + void* y_q8_1[4] = {}; + float eps = 0.f; + int threads = 0; ///< sum_threads(n) +}; +/// One token's inkling_mix() of each of `count` (1 or 2) mixes in one launch, a block each, and `conv` (null: none) +/// done first by the first mix's block, whose threads keep their part of it for the mix, and `norm` (null: none) of +/// the first mix's outputs after it: the same bits as inkling_conv_in(*conv), inkling_mix() of each and the norms. +/// conv->acc and conv->save may be states of the first mix, not of the second. Mixes of more than 5 states or +/// unaligned buffers take those calls one after the other. With `work` (inkling_mix_conv_work_bytes() of device +/// memory, zeroed once and then left to these calls, one at a time) a mix's work is spread over n / 128 blocks that +/// meet in it: each value the same operations in the same order as in the one block, the same bits. The blocks wait +/// for each other, so they must all be on the card at once: the launch is a cooperative one, which the runtime starts +/// with every block or refuses (then one block a mix), and only where the card takes all of them (the occupancy times +/// its multiprocessors), no output is one of the states, and STRATA_INKLING_MIX_SPREAD is not 0; never on HIP, where +/// one block a mix is faster. +void inkling_mix_conv(const InklingMix* mixes, int count, const InklingConvIn* conv, int n, float eps, void* stream, + const InklingMixNorm* norm = nullptr, void* work = nullptr); +size_t inkling_mix_conv_work_bytes(); + +// ---- a token of each of several sequences -------------------------------------------------------------------- +// +// Engine::step()'s rows (--batch): row t of a call is the next token of a sequence of its own, with that sequence's +// caches, convolution state and position. Each call below gives a row the same bits as the call above it gives +// that row alone (rows 1, the row's own state, caches and position), in one launch for all the rows. + +/// The most rows of these calls. +inline constexpr int kInklingSeqRows = 16; + +/// inkling_clip_many() for rows each at its own position: row t's tau is at pos[t] (host array of rows values). +void inkling_clip_many_seqs(const InklingClipJob* jobs, int count, int rows, const int64_t* pos, void* stream); + +/// A row's destination and state in inkling_kv_store_seqs(): its sequence's cache (ring as InklingKvDst's), the K +/// and V convolutions' states, and its position. +struct InklingKvSeq { + InklingKvDst dst; + float* k_state = nullptr; + float* v_state = nullptr; + int64_t pos = 0; +}; +/// inkling_kv_store() of one token for each of `rows` rows (seqs: a host array), into each row's own cache and +/// state. The rest as inkling_kv_store()'s; k_out / v_out may be null. +void inkling_kv_store_seqs(const float* kraw, const float* vraw, const InklingKvSeq* seqs, const float* k_w, + const float* v_w, const float* k_taps, const float* v_taps, int kv_heads, int dim, + int rows, float k_clip, float eps, float* k_out, float* v_out, void* stream); + +/// A row's caches in inkling_attend_seqs(): its sequence's (fp16, or Q8_0 where the codes are not null), its +/// position and the room it is sized for (inkling_attend()'s room; 0: pos + 1). +struct InklingAttnSeq { + const uint16_t* kcache = nullptr; + const uint16_t* vcache = nullptr; + Kvq8 kq8, vq8; + int64_t pos = 0; + int64_t room = 0; +}; +/// inkling_attend()'s split path for one token of each of `rows` rows (seqs: a host array), each against its own +/// caches at its own position, split as inkling_attend() splits that row alone. Every row's caches are fp16, or +/// every row's Q8_0 (the same --kv for all). q, rel.r, sinks and out hold the rows one after the other, as +/// inkling_attend()'s tokens. work: inkling_attend_work_floats() floats (not null). Throws +/// std::invalid_argument for more than kInklingSeqRows rows or caches of mixed kinds. +void inkling_attend_seqs(const float* q, const InklingAttnSeq* seqs, int rows, InklingRel rel, const float* sinks, + float* out, int dim, int n_head, int kv_heads, float scale, int window, int ring, + float* work, size_t work_floats, void* stream, bool int8_dot = false); + +/// inkling_conv() / inkling_conv_acc() of one token for each of `rows` rows, row t with its own state states[t] +/// (a host array of rows pointers), without taps. +void inkling_conv_seqs(const float* x, float* const* states, const float* w, float* out, int channels, int rows, + void* stream); +void inkling_conv_acc_seqs(const float* x, float* const* states, const float* w, float* acc, int channels, int rows, + void* stream); + +// ---- experts' activation ------------------------------------------------------------------------------------- + +/// SiTU for rows that each hold n gate values then n up values (the fused gate_up product); out: n a row, +/// out = beta * tanh(gate / beta) * sigmoid(gate) * (lb > 0 ? lb * tanh(up / lb) : up). +/// `scales` as swiglu_clamp_rows()'s (null: none). +void situ_rows(const float* gate_up, float* out, int n, int rows, float beta, float lb, void* stream, + const ExpertScales* scales = nullptr); +/// situ_rows() into the Q8_1 blocks native_quantize_q8_1(out, q8_1, n * rows, 1) makes of its output, the same bits, +/// in one launch and without the floats. n a multiple of 32. +void situ_rows_q8_1(const float* gate_up, void* q8_1, int n, int rows, float beta, float lb, void* stream, + const ExpertScales* scales = nullptr); + +// ---- the DSpark drafter (--draft-model, a "dflash" file) --------------------------------------------------------- +// +// llama.cpp PR 32218 (88025eb), src/models/dspark.cpp graph_inkling2: three dense layers over a block of eight rows +// that read the model's rows through their own caches. The model's rows go in as inkling_dspark_fuse() makes them: +// what the drafter's layers' caches take, and the context its recurrent head reads. + +/// For each of `rows` rows of the model: four inputs (the streams entering visits 5, 23 and 41, and the normed +/// output), input k's row r at x[k] + r * stride[k], and four outputs of n_embd floats a row, +/// out[j] = rms_norm(sum_k w[j][k] * x[k]) * norm[j] (ggml: soft_max(dspark_fuse row j), mul, sum_rows, +/// build_norm RMS) +/// j = 0..2 the drafter's layers' contexts (dflare_norm), 3 the head's (dspark_norm). w is softmax(dspark_fuse)'s. +struct InklingFuse { + const float* x[4] = {}; + int64_t stride[4] = {}; + float w[4][4] = {}; + const float* norm[4] = {}; + float* out[4] = {}; +}; +void inkling_dspark_fuse(const InklingFuse& f, int n_embd, int rows, float eps, void* stream); + +/// Attention of `rows` tokens that all see the same cached rows, positions lo .. hi, each other's among them (the +/// drafter's block: non-causal, every row with the first one's window). q: n_head * dim a token; the caches fp16, +/// kv_heads * dim a row, position p at row p % ring (ring 0: p); out: n_head * dim a token. The keys go in up to +/// kInklingBlockSplits pieces a key head, and work holds inkling_block_attend_work_floats() floats for their sums. +/// Heads of 128 values, and rows * n_head / kv_heads <= 32; else std::invalid_argument. +inline constexpr int kInklingBlockSplits = 32; +size_t inkling_block_attend_work_floats(int rows, int n_head, int dim); +void inkling_block_attend(const float* q, const uint16_t* kcache, const uint16_t* vcache, int64_t lo, int64_t hi, + int ring, int rows, float* out, int dim, int n_head, int kv_heads, float scale, float* work, + void* stream); + +/// The recurrent head's step (build_inkling2_head): from joint = joint_proj . [state, markov_w1[prev], hidden, +/// context] + b (3 * rank floats), +/// gate = sigmoid(joint[0, rank)), cand = tanh(joint[rank, 2 rank)), +/// state = cand + gate * (state - cand), latent = tanh(joint[2 rank, 3 rank)). +void inkling_dspark_gru(const float* joint, float* state, float* latent, int rank, void* stream); + +} // namespace strata::poly diff --git a/include/strata/poly/kernels.hpp b/include/strata/poly/kernels.hpp index 584b9de69c..850834216a 100644 --- a/include/strata/poly/kernels.hpp +++ b/include/strata/poly/kernels.hpp @@ -20,8 +20,9 @@ void gemv_f32(const float* w, const float* x, float* y, int n_in, int n_out, int void gemv_bf16(const uint16_t* w, const float* x, float* y, int n_in, int n_out, int rows_per_x, int rows, void* stream); /// The same for the many rows of a prompt batch, as a cuBLAS product on the stream of `blas` (blas_create), one -/// for each group of rows_per_x outputs. It sums in another order than gemv_f32, so a row does not come out -/// to the last bit as it does there. Throws std::runtime_error. +/// for each group of rows_per_x outputs; one group of up to 256 outputs in kernels of its own on that stream, each +/// output one fmaf after the other in the inputs' order. It sums in another order than gemv_f32, so a row does not +/// come out to the last bit as it does there. Throws std::runtime_error. void gemm_f32(void* blas, const float* w, const float* x, float* y, int n_in, int n_out, int rows_per_x, int rows); /// n BF16 values as floats, for gemm_f32. void bf16_to_f32(const uint16_t* w, float* out, size_t n, void* stream); diff --git a/metal/CMakeLists.txt b/metal/CMakeLists.txt index 915d4bd024..34792e2562 100644 --- a/metal/CMakeLists.txt +++ b/metal/CMakeLists.txt @@ -207,7 +207,7 @@ if(STRATA_METAL_POLY) target_link_libraries(strata_poly_metal_kernels PUBLIC ggml-base) add_executable(strata-poly ${S}/poly/main.cpp ${S}/poly/engine.cpp ${S}/poly/qwen35.cpp ${S}/poly/gemma4.cpp ${S}/poly/lfm2moe.cpp ${S}/poly/glm5next.cpp ${S}/poly/deepseek4.cpp ${S}/poly/flint.cpp - ${S}/poly/kolibri1.cpp ${S}/poly/cpu_experts.cpp ${S}/poly/spill.cpp ${S}/platform/memory.cpp + ${S}/poly/kolibri1.cpp ${S}/poly/cpu_experts.cpp ${S}/poly/cpu_lowbit.cpp ${S}/poly/spill.cpp ${S}/platform/memory.cpp ${S}/core/conversation_memory.cpp ${S}/core/conversation_file.cpp ${S}/spec/draft_policy.cpp ${S}/spec/suffix_drafter.cpp) target_include_directories(strata-poly PRIVATE ${STRATA_GGML_DIR}/ggml/include ${STRATA_GGML_DIR}/ggml/src) diff --git a/metal/setup_mac.py b/metal/setup_mac.py index 2ee8352a85..b313a4bd79 100644 --- a/metal/setup_mac.py +++ b/metal/setup_mac.py @@ -47,7 +47,8 @@ # Smaller architectures use strata-poly, not the fixed Qwen3.8 Metal window. # Keep their files, revisions, sizes and checksums in setup.py's single catalog. # The native port is opt-in through --family; the existing Qwen3.8 defaults stay unchanged. -MAC_POLY_FAMILIES = tuple(f for f, d in S.FAMILIES.items() if d.get("engine") == "poly") +# (a family marked "cuda_only", Inkling 2 Mini, has no Metal code) +MAC_POLY_FAMILIES = tuple(f for f, d in S.FAMILIES.items() if d.get("engine") == "poly" and not d.get("cuda_only")) def smaller_model_catalog() -> dict: diff --git a/metal/src/poly/quantized.cpp b/metal/src/poly/quantized.cpp index 0f566393f1..177c4d0f2b 100644 --- a/metal/src/poly/quantized.cpp +++ b/metal/src/poly/quantized.cpp @@ -144,7 +144,7 @@ namespace strata::poly { using namespace metal_detail; Mmq::Mmq() = default; Mmq::~Mmq() = default; -bool Mmq::fits(int t,int64_t rows,int64_t cols) { +bool Mmq::fits(int t,int64_t rows,int64_t cols,Allow) { return kernels::native_mmvq_supported(t) && rows>0 && rows<=INT32_MAX && cols>0 && cols<=INT32_MAX && cols%ggml_blck_size(ggml_type(t))==0; } // room for either form of the rows: q8_1, or fp16 on the matrix-unit path (mm_rows()) diff --git a/metal/src/poly/unported.cpp b/metal/src/poly/unported.cpp index 20d4dda010..dd488b8f5b 100644 --- a/metal/src/poly/unported.cpp +++ b/metal/src/poly/unported.cpp @@ -1,11 +1,13 @@ // metal/src/poly/unported.cpp - the entry points of the shared strata-poly host code that have no Metal kernel yet. // None of them is on a Mac family's default path: llama.cpp's flash attention (which falls back to attend() and // attend_batch() by its own contract), Gemma 4's opt-in int8 attention caches, Clover's block guesses and coreset -// routing, and the half-sum guard of Flint's MMQ. A call that would need a kernel says what is missing instead of -// computing something else. +// routing, the half-sum guard of Flint's MMQ, and Inkling 2's SiTU and tables of MMQ tiles (the engine does not run +// Inkling 2 on Metal). +// A call that would need a kernel says what is missing instead of computing something else. #include "fattn.hpp" #include "mmq.hpp" #include "strata/kernels/native_mmvq.hpp" +#include "strata/poly/inkling_kernels.hpp" #include "strata/poly/kernels.hpp" #include @@ -70,6 +72,21 @@ void scale_rows(float*, int64_t, int, int, const int32_t*, const float*, bool, v unported("half-sum guard (Flint)"); } +// Metal's tiles take no stream-k scratch: nothing to take ahead (Inkling 2's, which Metal does not run) +void Mmq::reserve_fixup() {} +// the tables of tiles of Inkling 2's prompt experts (Engine::expert_tiles_): false keeps the engine on mul() +bool Mmq::tiles_fit(int, int64_t, int64_t, bool) { return false; } +void Mmq::plan_tiles(int, const int32_t*, const int32_t*, const int32_t*, int, std::vector&) { + unported("tables of MMQ tiles (Inkling 2)"); +} +void Mmq::mul_tiles(const void*, const int64_t*, int, int64_t, int64_t, const void*, int64_t, int64_t, const Tile*, + const Tile*, int, const int32_t*, float*, int64_t, void*) { + unported("tables of MMQ tiles (Inkling 2)"); +} +void situ_rows(const float*, float*, int, int, float, float, void*, const ExpertScales*) { + unported("SiTU (Inkling 2)"); +} + } // namespace strata::poly namespace strata::kernels { @@ -77,4 +94,9 @@ namespace strata::kernels { // the 32-expert launches of STRATA_SLOTS_WARP: Metal's slots kernel takes 8 cached experts a launch bool native_mmvq_slots_wide() { return false; } +// several matrices of one input a launch (Inkling 2's projections, which Metal does not run): lin() one by one +bool native_mmvq_jobs(int, const MmvqJobs&, int, int, int, void*) { return false; } +bool native_rms_norm_q8_1_rows(const NormRows&, int, int, float, int, void*) { return false; } +bool native_mmvq_jobs_mixed(const int*, const MmvqJobs&, int, int, void*) { return false; } + } // namespace strata::kernels diff --git a/serve/fixtures/inkling2_chat_template.jinja b/serve/fixtures/inkling2_chat_template.jinja new file mode 100644 index 0000000000..cae99e0891 --- /dev/null +++ b/serve/fixtures/inkling2_chat_template.jinja @@ -0,0 +1,137 @@ +{%- set effort_map = {"none": 0.0, "minimal": 0.1, "low": 0.2, "medium": 0.7, "high": 0.9, "xhigh": 0.99, "max": 0.99} -%} +{%- set role_token = {"user": "<|message_user|>", "assistant": "<|message_model|>", "system": "<|message_system|>", "tool": "<|message_tool|>"} -%} + +{%- macro emit_thinking_effort() -%} + {%- set eff = reasoning_effort if reasoning_effort is defined and reasoning_effort is not none else 0.9 -%} + {%- if eff is string -%} + {%- set key = eff | trim -%} + {%- if key not in effort_map -%} + {{- raise_exception("Unknown reasoning_effort: " ~ eff) -}} + {%- endif -%} + {%- set num = effort_map[key] -%} + {%- else -%} + {%- set num = eff | float -%} + {%- endif -%} + {%- if num < 0.0 or num > 0.99 -%} + {{- raise_exception("reasoning_effort must be in [0.0, 0.99]") -}} + {%- endif -%} + {{- "<|message_system|><|content_text|>Thinking effort level: " -}} + {%- if num == 0.0 -%}0{%- else -%}{{ num }}{%- endif -%} + {{- "<|end_message|>" -}} +{%- endmacro -%} + +{%- if tools -%} + {%- set tool_state = namespace(specs=[]) -%} + {%- for tool in tools -%} + {%- set fn = tool.function if tool.function is defined else tool -%} + {%- set spec = { + "description": (fn.description if fn.description is defined and fn.description else ""), + "name": fn.name, + "parameters": (fn.parameters if fn.parameters is defined and fn.parameters else {}), + "type": (tool.type if tool.type is defined and tool.type else "function"), + } -%} + {%- set tool_state.specs = tool_state.specs + [spec] -%} + {%- endfor -%} + {{- "<|message_system|>tool_declare<|content_xml|>" -}} + {{- tool_state.specs | tojson(sort_keys=true, separators=(",", ":")) -}} + {{- "<|end_message|>" -}} +{%- endif -%} + +{%- set state = namespace(effort_emitted=false) -%} +{%- for message in messages -%} + {%- if message.role not in role_token -%} + {{- raise_exception("Unknown message role: " ~ message.role) -}} + {%- endif -%} + {%- if not state.effort_emitted and message.role != "system" -%} + {{- emit_thinking_effort() -}} + {%- set state.effort_emitted = true -%} + {%- endif -%} + + {%- set header = namespace(text=role_token[message.role]) -%} + {%- if message.role == "tool" -%} + {%- if message.name is defined and message.name -%} + {%- set header.text = header.text ~ message.name -%} + {%- elif message.tool_call_id is defined and message.tool_call_id -%} + {%- for prev in messages -%} + {%- if prev.role == "assistant" and prev.tool_calls -%} + {%- for tc in prev.tool_calls -%} + {%- if tc.id is defined and tc.id == message.tool_call_id and tc.function.name is defined -%} + {%- set header.text = header.text ~ tc.function.name -%} + {%- endif -%} + {%- endfor -%} + {%- endif -%} + {%- endfor -%} + {%- endif -%} + {%- elif message.role == "assistant" and message.name is defined and message.name -%} + {%- set header.text = header.text ~ message.name -%} + {%- endif -%} + {%- set rtok = header.text -%} + {%- set rendered -%} + + {%- if message.role == "assistant" and message.reasoning_content is defined and message.reasoning_content -%} + {{- rtok ~ "<|content_thinking|>" ~ message.reasoning_content ~ "<|end_message|>" -}} + {%- endif -%} + + {%- if message.content is string and (message.content or not (message.role == "assistant" and (message.tool_calls or message.reasoning_content))) -%} + {{- rtok ~ "<|content_text|>" ~ message.content ~ "<|end_message|>" -}} + {%- elif message.content -%} + {%- for part in message.content -%} + {%- if part is string -%} + {{- rtok ~ "<|content_text|>" ~ part ~ "<|end_message|>" -}} + {%- elif part.type is not defined or part.type in ("text", "input_text") -%} + {%- set text_part = (part.text if part.text is defined and part.text is string else "") -%} + {{- rtok ~ "<|content_text|>" ~ text_part ~ "<|end_message|>" -}} + {%- elif part.type in ("image", "input_image", "image_url") -%} + {%- if message.role not in ("user", "tool") -%} + {{- raise_exception("Image content is only supported for user and tool messages") -}} + {%- endif -%} + {{- rtok ~ "<|content_image|><|unused_200054|><|end_message|>" -}} + {%- elif part.type in ("audio", "input_audio", "audio_url") -%} + {{- raise_exception("Inkling 2 does not accept audio input") -}} + {%- else -%} + {{- raise_exception("Unsupported content part type: " ~ part.type) -}} + {%- endif -%} + {%- endfor -%} + {%- endif -%} + + {%- if message.role == "assistant" and message.tool_calls -%} + {%- for tc in message.tool_calls -%} + {%- set fn = tc.function -%} + {%- if fn.name is not defined or fn.name is not string -%} + {{- raise_exception("tool call function name must be a string") -}} + {%- endif -%} + {%- if message.name is defined and message.name and message.name != fn.name -%} + {{- raise_exception("assistant name " ~ message.name ~ " does not match its tool call " ~ fn.name) -}} + {%- endif -%} + {%- set args = fn.arguments if fn.arguments is defined and fn.arguments else {} -%} + {%- if args is string -%} + {{- raise_exception("tool call arguments must be a parsed object, not a JSON string; canonicalize upstream") -}} + {%- endif -%} + {%- if args is not mapping -%} + {{- raise_exception("tool call arguments must be an object") -}} + {%- endif -%} + {{- "<|message_model|>" ~ fn.name ~ "<|content_invoke_tool_json|>" -}} + {{- '{"name":' ~ (fn.name | tojson(sort_keys=true, separators=(",", ":"))) ~ ',"args":' -}} + {{- "{" -}} + {%- for key, value in args | dictsort(case_sensitive=true) -%} + {{- (key | tojson) ~ ":" ~ (value | tojson(separators=(",", ":"))) -}} + {%- if not loop.last -%},{%- endif -%} + {%- endfor -%} + {{- "}}<|end_message|>" -}} + {%- endfor -%} + {%- endif -%} + + {%- if message.role == "assistant" -%} + {{- "<|content_model_end_sampling|>" -}} + {%- endif -%} + {%- endset -%} + {%- if message.role == "assistant" -%} + {%- generation -%}{{- rendered -}}{%- endgeneration -%} + {%- else -%} + {{- rendered -}} + {%- endif -%} +{%- endfor -%} + +{%- if not state.effort_emitted -%} + {{- emit_thinking_effort() -}} +{%- endif -%} diff --git a/serve/fixtures/inkling2_golden.json b/serve/fixtures/inkling2_golden.json new file mode 100644 index 0000000000..6f20c85753 --- /dev/null +++ b/serve/fixtures/inkling2_golden.json @@ -0,0 +1,85 @@ +{"source": "token ids: Hugging Face tokenizers on thinkingmachines/Inkling-2-Mini's tokenizer.json (BPE, ignore_merges, add_special_tokens=false), the reference; \"llama_cpp_ids\" where llama.cpp 29b52d398b's llama_tokenize differs (it does not set ignore_merges for inkling2, so a word that is one token but that no chain of merges reaches, \"kwargs\", is three there); the parse_special=false cases (control tokens as text, which HF cannot do) are llama.cpp's ids (\"ids_from\"). \"templates\": llama.cpp's common_chat_templates_apply() with the model's template (OpenAI messages and tools, chat_template_kwargs), the prompt it renders; \"replies\": common_chat_session's parse of a reply (reasoning_format auto, parallel tool calls)", + "tokens": [ + {"name": "simple_en", "text": "Hello, world!", "parse_special": true, "ids": [32269, 11, 150770, 0]}, + {"name": "sentence_en", "text": "The quick brown fox jumps over the lazy dog.", "parse_special": true, "ids": [371, 157021, 161319, 220, 32329, 160581, 82, 150053, 149876, 161703, 153350, 13]}, + {"name": "leading_space", "text": " Hello", "parse_special": true, "ids": [188766]}, + {"name": "leading_spaces_multi", "text": " three leading spaces", "parse_special": true, "ids": [149859, 150396, 154384, 156465]}, + {"name": "trailing_space", "text": "trailing space ", "parse_special": true, "ids": [31229, 279, 150785, 220]}, + {"name": "japanese", "text": "こんにちは、世界!今日はいい天気ですね。東京タワーは333メートルです。", "parse_special": true, "ids": [116200, 2369, 144765, 6433, 110174, 6622, 124784, 6085, 117386, 24596, 10282, 77122, 6126, 6434, 118229, 5916, 5947, 5959, 6085, 73886, 5938, 85381, 5944, 77122, 6434]}, + {"name": "chinese_korean", "text": "你好,世界。안녕하세요 세계", "parse_special": true, "ids": [11739, 23643, 6633, 110174, 6434, 128458, 220, 102467]}, + {"name": "numbers", "text": "1234567 and 3.14159 and -42 and 1,000,000 and 0.0001 and 2026-11-21", "parse_special": true, "ids": [70904, 81554, 22, 149880, 220, 18, 13, 73388, 69022, 149880, 196973, 68872, 149880, 220, 16, 11, 68128, 11, 68128, 149880, 220, 15, 13, 68128, 16, 149880, 220, 68111, 21, 12, 68052, 12, 68251]}, + {"name": "digits_long", "text": "12345678901234567890", "parse_special": true, "ids": [70904, 81554, 91927, 77863, 81999, 97293, 68410]}, + {"name": "code_python_spaces", "text": "def foo(x):\n if x > 0:\n return x * 2\n return None\n", "parse_special": true, "ids": [1719, 173339, 7, 87, 8, 25, 198, 149862, 150003, 149924, 196995, 220, 15, 25, 198, 149860, 149862, 150583, 149924, 196987, 220, 17, 198, 149862, 150583, 150830, 198]}, + {"name": "code_tabs", "text": "int main() {\n\tfor (int i = 0; i < 10; i++) {\n\t\tprintf(\"%d\\n\", i);\n\t}\n}\n", "parse_special": true, "ids": [407, 150520, 68078, 196983, 198, 197, 307, 196976, 407, 149900, 196977, 220, 15, 26, 149900, 196982, 220, 68026, 26, 149900, 145040, 8, 196983, 198, 197, 197, 70806, 7, 1, 4, 67, 59, 77, 1, 11, 149900, 8, 26, 198, 197, 92, 198, 92, 198]}, + {"name": "multiple_newlines", "text": "line one\n\n\nline four\n\n\n\n\nline nine", "parse_special": true, "ids": [909, 150011, 68019, 909, 150792, 68017, 198, 909, 154109]}, + {"name": "crlf_and_mixed_ws", "text": "a\r\nb \t c d e", "parse_special": true, "ids": [64, 68247, 65, 220, 197, 149972, 1377, 67, 68911, 68]}, + {"name": "emoji", "text": "I love 🦙 and 🚀! 👨‍👩‍👧‍👦 family, flags 🇯🇵🇺🇸, skin tone 👍🏽", "parse_special": true, "ids": [40, 152467, 220, 109184, 149880, 220, 108185, 0, 220, 75157, 70363, 74269, 70363, 87292, 70363, 87862, 151177, 11, 170593, 220, 83184, 73275, 72569, 71511, 11, 155956, 164969, 220, 76858, 69389]}, + {"name": "accents_and_symbols", "text": "Café naïve résumé — “quotes” ‘single’ … € £ ¥ © ™ ½ ∑ ∞ ≠ √", "parse_special": true, "ids": [120967, 149946, 5169, 290, 150182, 118188, 150220, 150060, 31000, 82, 23068, 150817, 2706, 23064, 151105, 151091, 157841, 193252, 154437, 220, 25627, 220, 5153, 190207, 163900, 178755, 158507]}, + {"name": "special_tokens_text", "text": "<|message_user|><|content_text|>Hi there<|end_message|><|message_model|>", "parse_special": true, "ids": [200000, 200004, 4896, 150102, 200010, 200001]}, + {"name": "special_tokens_text_plain", "text": "<|message_user|><|content_text|>Hi there<|end_message|><|message_model|>", "parse_special": false, "ids": [27, 91, 65752, 62, 2986, 91, 29, 27, 91, 48038, 62, 911, 91, 29, 4896, 150102, 27, 91, 406, 62, 65752, 91, 29, 27, 91, 65752, 62, 1119, 91, 29], "ids_from": "llama.cpp"}, + {"name": "special_tokens_mixed", "text": "text before <|endoftext|> text after <|content_model_end_sampling|><|begin_of_text|>", "parse_special": true, "ids": [911, 150463, 220, 199999, 150311, 150273, 220, 200006, 200028]}, + {"name": "special_tokens_mixed_plain", "text": "text before <|endoftext|> text after <|content_model_end_sampling|><|begin_of_text|>", "parse_special": false, "ids": [911, 150463, 196982, 91, 406, 277, 911, 91, 29, 150311, 150273, 196982, 91, 48038, 62, 1119, 62, 406, 62, 76130, 91, 29, 27, 91, 1582, 62, 277, 62, 911, 91, 29], "ids_from": "llama.cpp"}, + {"name": "fake_special", "text": "<|not_a_token|> <|message_user |> < |end_message| >", "parse_special": true, "ids": [27, 91, 799, 62, 64, 62, 2906, 91, 29, 196982, 91, 65752, 62, 2986, 196975, 29, 196982, 196975, 406, 62, 65752, 91, 196995]}, + {"name": "url_and_email", "text": "Visit https://example.com/path?a=1&b=two#frag or mail me@example.org", "parse_special": true, "ids": [33974, 150491, 25, 145055, 1805, 13, 376, 14, 1448, 30, 64, 28, 16, 5, 65, 28, 1286, 2, 31193, 149918, 154695, 149991, 31, 1805, 13, 1061]}, + {"name": "json_snippet", "text": "{\"name\": \"get_weather\", \"args\": {\"city\": \"Tokyo\", \"days\": 3}}", "parse_special": true, "ids": [90, 1, 930, 1, 25, 196980, 832, 62, 30847, 1, 11, 196980, 70747, 1, 25, 196983, 1, 2958, 1, 25, 196980, 34664, 1, 11, 196980, 70095, 1, 25, 220, 18, 92, 92]}, + {"name": "contractions_caps", "text": "I'm sure they'll say it's DON'T-STOP, wasn't it? HELLO hello HeLLo", "parse_special": true, "ids": [40, 6, 76, 151456, 150051, 6, 359, 150657, 149921, 6, 82, 199445, 6, 51, 12, 148033, 11, 157354, 6, 83, 149921, 30, 198431, 148284, 171551, 150266, 43, 1211]}, + {"name": "empty", "text": "", "parse_special": true, "ids": []}, + {"name": "single_space", "text": " ", "parse_special": true, "ids": [220]}, + {"name": "only_newlines", "text": "\n\n\n", "parse_special": true, "ids": [68019]}, + {"name": "long_whitespace_run", "text": "a b\t\t\t\t\tc", "parse_special": true, "ids": [64, 149861, 149861, 149963, 68550, 197, 66]}, + {"name": "arabic_hindi_russian", "text": "مرحبا بالعالم नमस्ते दुनिया Привет, мир", "parse_special": true, "ids": [80401, 150701, 72897, 163574, 164865, 152570, 68399, 11, 158322]}, + {"name": "extra_0", "text": "helloПривет мир", "parse_special": true, "ids": [32205, 71168, 68399, 158322]}, + {"name": "extra_1", "text": "HTTPServer and McDonald's", "parse_special": true, "ids": [146005, 52861, 149880, 152065, 31091, 6, 82]}, + {"name": "extra_2", "text": "kwargs **kwargs", "parse_special": true, "ids": [87550, 197033, 87550], "llama_cpp_ids": [86226, 70, 82, 197033, 86226, 70, 82]}, + {"name": "extra_3", "text": "é́ combining", "parse_special": true, "ids": [108114, 69195, 172469]}, + {"name": "extra_4", "text": "\u0000\u0001 control", "parse_special": true, "ids": [188, 189, 221, 150389]}, + {"name": "extra_5", "text": " non-breaking space", "parse_special": true, "ids": [1377, 3932, 12, 105763, 1377, 1626]}, + {"name": "extra_6", "text": "

", "parse_special": true, "ids": [718, 101, 111833]}, + {"name": "extra_7", "text": "àb́Ĉ", "parse_special": true, "ids": [64, 73561, 65, 69195, 34, 91336]}, + {"name": "extra_8", "text": "Džungla Lj LJ", "parse_special": true, "ids": [131, 227, 1873, 891, 220, 131, 230, 220, 131, 229]}, + {"name": "extra_9", "text": "fi ligature Ⅻ ⅻ", "parse_special": true, "ids": [76606, 152850, 1483, 220, 149826, 220, 149842]}, + {"name": "extra_10", "text": "ΣΊΣΥΦΟΣ σίσυφος", "parse_special": true, "ids": [5348, 138, 232, 5348, 5350, 5351, 101790, 220, 119820, 71145, 75600, 5388]}, + {"name": "extra_11", "text": "İstanbul ıi", "parse_special": true, "ids": [5234, 121115, 158821, 72]}, + {"name": "extra_12", "text": "ß ẞ", "parse_special": true, "ids": [5217, 220, 6335]}, + {"name": "extra_13", "text": "​‌‍ zero width", "parse_special": true, "ids": [68619, 68051, 70363, 151712, 152077]}, + {"name": "extra_14", "text": "x =//\ny", "parse_special": true, "ids": [87, 196977, 145055, 198, 88]}, + {"name": "extra_15", "text": "path/to/file.py\n/usr/bin", "parse_special": true, "ids": [1448, 14, 278, 14, 1082, 13, 1746, 198, 14, 4460, 14, 2285]}, + {"name": "extra_16", "text": "abc中文def 你好abc 東京タワーtower", "parse_special": true, "ids": [33782, 114903, 1719, 220, 11739, 23643, 33782, 220, 118229, 5916, 5947, 5959, 32999]}, + {"name": "extra_17", "text": "end.)/\n/next", "parse_special": true, "ids": [406, 13, 8, 14, 198, 14, 2157]}, + {"name": "extra_18", "text": "helloWORLD camelCaseWord XMLHttpRequest", "parse_special": true, "ids": [32205, 146508, 146001, 220, 39907, 4474, 4164, 198420, 31126, 43683]}, + {"name": "extra_19", "text": "ПРИВЕТworld", "parse_special": true, "ids": [5454, 82007, 103419, 5397, 1966]}, + {"name": "extra_20", "text": "don't DON'T Don'T", "parse_special": true, "ids": [1630, 6, 83, 199445, 6, 51, 152875, 6, 51]}, + {"name": "extra_21", "text": "a b  c", "parse_special": true, "ids": [64, 68911, 65, 1377, 1377, 66]}, + {"name": "extra_22", "text": "x\r\n\r\ny", "parse_special": true, "ids": [87, 70392, 88]}, + {"name": "extra_23", "text": "**bold**/[link](u)/\n", "parse_special": true, "ids": [145054, 4832, 145054, 14, 58, 1915, 60, 7, 84, 8, 14, 198]}, + {"name": "extra_24", "text": "١٢٣٤ ४५६ 12345", "parse_special": true, "ids": [90460, 95893, 119077, 121933, 220, 25486, 25487, 25488, 220, 70904, 68358]} + ], + "templates": [ + {"name": "user_only", "request": {"messages": [{"role": "user", "content": "Hi"}]}, "kwargs": {}, "prompt": "<|message_system|><|content_text|>Thinking effort level: 0.9<|end_message|><|message_user|><|content_text|>Hi<|end_message|>"}, + {"name": "system_user", "request": {"messages": [{"role": "system", "content": "You are terse."}, {"role": "user", "content": "Hi"}]}, "kwargs": {}, "prompt": "<|message_system|><|content_text|>You are terse.<|end_message|><|message_system|><|content_text|>Thinking effort level: 0.9<|end_message|><|message_user|><|content_text|>Hi<|end_message|>"}, + {"name": "effort_low", "request": {"messages": [{"role": "user", "content": "Hi"}]}, "kwargs": {"reasoning_effort": "low"}, "prompt": "<|message_system|><|content_text|>Thinking effort level: 0.2<|end_message|><|message_user|><|content_text|>Hi<|end_message|>"}, + {"name": "effort_none", "request": {"messages": [{"role": "user", "content": "Hi"}]}, "kwargs": {"reasoning_effort": "none"}, "prompt": "<|message_system|><|content_text|>Thinking effort level: 0<|end_message|><|message_user|><|content_text|>Hi<|end_message|>"}, + {"name": "effort_medium", "request": {"messages": [{"role": "user", "content": "Hi"}]}, "kwargs": {"reasoning_effort": "medium"}, "prompt": "<|message_system|><|content_text|>Thinking effort level: 0.7<|end_message|><|message_user|><|content_text|>Hi<|end_message|>"}, + {"name": "effort_high", "request": {"messages": [{"role": "user", "content": "Hi"}]}, "kwargs": {"reasoning_effort": "high"}, "prompt": "<|message_system|><|content_text|>Thinking effort level: 0.9<|end_message|><|message_user|><|content_text|>Hi<|end_message|>"}, + {"name": "effort_number", "request": {"messages": [{"role": "user", "content": "Hi"}]}, "kwargs": {"reasoning_effort": 0.5}, "prompt": "<|message_system|><|content_text|>Thinking effort level: 0.5<|end_message|><|message_user|><|content_text|>Hi<|end_message|>"}, + {"name": "multi_turn", "request": {"messages": [{"role": "user", "content": "Hi"}, {"role": "assistant", "content": "Hello! How can I help?"}, {"role": "user", "content": "Tell me a joke"}]}, "kwargs": {}, "prompt": "<|message_system|><|content_text|>Thinking effort level: 0.9<|end_message|><|message_user|><|content_text|>Hi<|end_message|><|message_model|><|content_text|>Hello! How can I help?<|end_message|><|content_model_end_sampling|><|message_user|><|content_text|>Tell me a joke<|end_message|>"}, + {"name": "reasoning_history", "request": {"messages": [{"role": "user", "content": "2+2?"}, {"role": "assistant", "content": "4", "reasoning_content": "simple math"}, {"role": "user", "content": "and 3+3?"}]}, "kwargs": {}, "prompt": "<|message_system|><|content_text|>Thinking effort level: 0.9<|end_message|><|message_user|><|content_text|>2+2?<|end_message|><|message_model|><|content_thinking|>simple math<|end_message|><|message_model|><|content_text|>4<|end_message|><|content_model_end_sampling|><|message_user|><|content_text|>and 3+3?<|end_message|>"}, + {"name": "tools_decl", "request": {"messages": [{"role": "user", "content": "Weather in Paris?"}], "tools": [{"type": "function", "function": {"name": "get_weather", "description": "Get the weather for a city", "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "City name"}, "days": {"type": "integer"}, "unit": {"type": "string", "enum": ["c", "f"]}}, "required": ["city"]}}}, {"type": "function", "function": {"name": "now", "description": "", "parameters": {"type": "object", "properties": {}}}}]}, "kwargs": {}, "prompt": "<|message_system|>tool_declare<|content_xml|>[{\"description\":\"Get the weather for a city\",\"name\":\"get_weather\",\"parameters\":{\"properties\":{\"city\":{\"description\":\"City name\",\"type\":\"string\"},\"days\":{\"type\":\"integer\"},\"unit\":{\"enum\":[\"c\",\"f\"],\"type\":\"string\"}},\"required\":[\"city\"],\"type\":\"object\"},\"type\":\"function\"},{\"description\":\"\",\"name\":\"now\",\"parameters\":{\"properties\":{},\"type\":\"object\"},\"type\":\"function\"}]<|end_message|><|message_system|><|content_text|>Thinking effort level: 0.9<|end_message|><|message_user|><|content_text|>Weather in Paris?<|end_message|>"}, + {"name": "tool_round", "request": {"messages": [{"role": "user", "content": "Weather in Paris and Tokyo?"}, {"role": "assistant", "content": "", "reasoning_content": "two calls", "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "get_weather", "arguments": "{\"city\": \"Paris\", \"unit\": \"c\"}"}}, {"id": "c2", "type": "function", "function": {"name": "get_weather", "arguments": "{\"days\": 2, \"city\": \"東京\"}"}}]}, {"role": "tool", "tool_call_id": "c1", "content": "18 C, sunny"}, {"role": "tool", "tool_call_id": "c2", "content": "{\"temp\": 21}"}, {"role": "assistant", "content": "Paris 18 C, Tokyo 21 C."}, {"role": "user", "content": "thanks"}], "tools": [{"type": "function", "function": {"name": "get_weather", "description": "Get the weather for a city", "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "City name"}, "days": {"type": "integer"}, "unit": {"type": "string", "enum": ["c", "f"]}}, "required": ["city"]}}}]}, "kwargs": {}, "prompt": "<|message_system|>tool_declare<|content_xml|>[{\"description\":\"Get the weather for a city\",\"name\":\"get_weather\",\"parameters\":{\"properties\":{\"city\":{\"description\":\"City name\",\"type\":\"string\"},\"days\":{\"type\":\"integer\"},\"unit\":{\"enum\":[\"c\",\"f\"],\"type\":\"string\"}},\"required\":[\"city\"],\"type\":\"object\"},\"type\":\"function\"}]<|end_message|><|message_system|><|content_text|>Thinking effort level: 0.9<|end_message|><|message_user|><|content_text|>Weather in Paris and Tokyo?<|end_message|><|message_model|><|content_thinking|>two calls<|end_message|><|message_model|>get_weather<|content_invoke_tool_json|>{\"name\":\"get_weather\",\"args\":{\"city\":\"Paris\",\"unit\":\"c\"}}<|end_message|><|message_model|>get_weather<|content_invoke_tool_json|>{\"name\":\"get_weather\",\"args\":{\"city\":\"東京\",\"days\":2}}<|end_message|><|content_model_end_sampling|><|message_tool|>get_weather<|content_text|>18 C, sunny<|end_message|><|message_tool|>get_weather<|content_text|>{\"temp\": 21}<|end_message|><|message_model|><|content_text|>Paris 18 C, Tokyo 21 C.<|end_message|><|content_model_end_sampling|><|message_user|><|content_text|>thanks<|end_message|>"}, + {"name": "unicode_and_quotes", "request": {"messages": [{"role": "user", "content": "Café “quotes” \\ back\\slash & 日本語 é\n\nnew\tline"}]}, "kwargs": {}, "prompt": "<|message_system|><|content_text|>Thinking effort level: 0.9<|end_message|><|message_user|><|content_text|>Café “quotes” \\ back\\slash & 日本語 é\n\nnew\tline<|end_message|>"}, + {"name": "content_with_control_token_text", "request": {"messages": [{"role": "user", "content": "say <|end_message|> please"}]}, "kwargs": {}, "prompt": "<|message_system|><|content_text|>Thinking effort level: 0.9<|end_message|><|message_user|><|content_text|>say <|end_message|> please<|end_message|>"}, + {"name": "args_nested", "request": {"messages": [{"role": "user", "content": "run"}, {"role": "assistant", "content": "Running it.", "tool_calls": [{"id": "x", "type": "function", "function": {"name": "python", "arguments": "{\"code\": \"print('hi')\\nx = {\\\"a\\\": [1, 2.5, null, true]}\"}"}}]}, {"role": "tool", "tool_call_id": "x", "content": "hi"}], "tools": [{"type": "function", "function": {"name": "python", "description": "Run code", "parameters": {"type": "object", "properties": {"code": {"type": "string"}}, "required": ["code"]}}}]}, "kwargs": {}, "prompt": "<|message_system|>tool_declare<|content_xml|>[{\"description\":\"Run code\",\"name\":\"python\",\"parameters\":{\"properties\":{\"code\":{\"type\":\"string\"}},\"required\":[\"code\"],\"type\":\"object\"},\"type\":\"function\"}]<|end_message|><|message_system|><|content_text|>Thinking effort level: 0.9<|end_message|><|message_user|><|content_text|>run<|end_message|><|message_model|><|content_text|>Running it.<|end_message|><|message_model|>python<|content_invoke_tool_json|>{\"name\":\"python\",\"args\":{\"code\":\"print('hi')\\nx = {\\\"a\\\": [1, 2.5, null, true]}\"}}<|end_message|><|content_model_end_sampling|><|message_tool|>python<|content_text|>hi<|end_message|>"} + ], + "replies": [ + {"name": "content_only", "tools": [], "text": "<|message_model|><|content_text|>Hello, world!\nWhat's up?<|end_message|>", "content": "Hello, world!\nWhat's up?", "reasoning": "", "calls": []}, + {"name": "think_then_content", "tools": [], "text": "<|message_model|><|content_thinking|>I'm thinking<|end_message|><|message_model|><|content_text|>Hello!<|end_message|>", "content": "Hello!", "reasoning": "I'm thinking", "calls": []}, + {"name": "cut_in_thinking", "tools": [], "text": "<|message_model|><|content_thinking|>I was still thinking", "content": "", "reasoning": "I was still thinking", "calls": []}, + {"name": "cut_in_content", "tools": [], "text": "<|message_model|><|content_thinking|>t<|end_message|><|message_model|><|content_text|>Hello, wor", "content": "Hello, wor", "reasoning": "t", "calls": []}, + {"name": "single_call", "tools": [{"name": "get_weather", "description": "Get the weather for a city", "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "City name"}, "days": {"type": "integer"}, "unit": {"type": "string", "enum": ["c", "f"]}}, "required": ["city"]}}], "text": "<|message_model|>get_weather<|content_invoke_tool_json|>{\"name\":\"get_weather\",\"args\":{\"city\":\"Paris\"}}<|end_message|>", "content": "", "reasoning": "", "calls": [{"name": "get_weather", "arguments": {"city": "Paris"}}]}, + {"name": "think_content_call", "tools": [{"name": "get_weather", "description": "Get the weather for a city", "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "City name"}, "days": {"type": "integer"}, "unit": {"type": "string", "enum": ["c", "f"]}}, "required": ["city"]}}], "text": "<|message_model|><|content_thinking|>I should call it<|end_message|><|message_model|><|content_text|>On it.<|end_message|><|message_model|>get_weather<|content_invoke_tool_json|>{\"name\":\"get_weather\",\"args\":{\"city\":\"Paris\"}}<|end_message|>", "content": "On it.", "reasoning": "I should call it", "calls": [{"name": "get_weather", "arguments": {"city": "Paris"}}]}, + {"name": "tools_but_content", "tools": [{"name": "get_weather", "description": "Get the weather for a city", "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "City name"}, "days": {"type": "integer"}, "unit": {"type": "string", "enum": ["c", "f"]}}, "required": ["city"]}}], "text": "<|message_model|><|content_thinking|>No tool needed<|end_message|><|message_model|><|content_text|>Hi<|end_message|>", "content": "Hi", "reasoning": "No tool needed", "calls": []}, + {"name": "parallel", "tools": [{"name": "get_weather", "description": "Get the weather for a city", "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "City name"}, "days": {"type": "integer"}, "unit": {"type": "string", "enum": ["c", "f"]}}, "required": ["city"]}}, {"name": "now", "description": "", "parameters": {"type": "object", "properties": {}}}], "text": "<|message_model|>get_weather<|content_invoke_tool_json|>{\"name\":\"get_weather\",\"args\":{\"city\":\"Paris\"}}<|end_message|><|message_model|>now<|content_invoke_tool_json|>{\"name\":\"now\",\"args\":{}}<|end_message|>", "content": "", "reasoning": "", "calls": [{"name": "get_weather", "arguments": {"city": "Paris"}}, {"name": "now", "arguments": {}}]}, + {"name": "end_inside_string", "tools": [{"name": "python", "description": "Run code", "parameters": {"type": "object", "properties": {"code": {"type": "string"}}, "required": ["code"]}}], "text": "<|message_model|>python<|content_invoke_tool_json|>{\"name\":\"python\",\"args\":{\"code\":\"print('<|end_message|>')\"}}<|end_message|>", "content": "", "reasoning": "", "calls": [{"name": "python", "arguments": {"code": "print('<|end_message|>')"}}]}, + {"name": "two_text_blocks", "tools": [], "text": "<|message_model|><|content_text|>One.<|end_message|><|message_model|><|content_text|> Two.<|end_message|>", "content": "One. Two.", "reasoning": "", "calls": []}, + {"name": "nested_args", "tools": [{"name": "python", "description": "Run code", "parameters": {"type": "object", "properties": {"code": {"type": "string"}}, "required": ["code"]}}], "text": "<|message_model|>python<|content_invoke_tool_json|>{\"name\":\"python\",\"args\":{\"code\":\"x = {\\\"a\\\": [1, 2]}\\nprint(x)\"}}<|end_message|>", "content": "", "reasoning": "", "calls": [{"name": "python", "arguments": {"code": "x = {\"a\": [1, 2]}\nprint(x)"}}]} + ]} diff --git a/serve/fixtures/inkling2_vocab_subset.json b/serve/fixtures/inkling2_vocab_subset.json new file mode 100644 index 0000000000..9b6f54c925 --- /dev/null +++ b/serve/fixtures/inkling2_vocab_subset.json @@ -0,0 +1 @@ +{"about":"the tokens and merges of Inkling 2 Mini's vocabulary (ggml-org/Inkling-2-Mini-GGUF) that the golden strings use, at their own ids, with the merges in their order: with ignore_merges (a piece that is a token is that token) and BPE over the rest, they give the full vocabulary's ids for these strings (a merge that never applies cannot change which one applies first)","n_tokens":200058,"pre":"inkling2","special_ids":{"tokenizer.ggml.eos_token_id":200006,"tokenizer.ggml.padding_token_id":199999,"tokenizer.ggml.eot_token_id":200006},"tokens":{"0":"!","1":"\"","2":"#","3":"$","4":"%","5":"&","6":"'","7":"(","8":")","9":"*","10":"+","11":",","12":"-","13":".","14":"/","15":"0","16":"1","17":"2","18":"3","19":"4","20":"5","21":"6","22":"7","23":"8","24":"9","25":":","26":";","27":"<","28":"=","29":">","30":"?","31":"@","32":"A","33":"B","34":"C","35":"D","36":"E","37":"F","38":"G","39":"H","40":"I","41":"J","42":"K","43":"L","44":"M","45":"N","46":"O","47":"P","48":"Q","49":"R","50":"S","51":"T","52":"U","53":"V","54":"W","55":"X","56":"Y","57":"Z","58":"[","59":"\\","60":"]","61":"^","62":"_","63":"`","64":"a","65":"b","66":"c","67":"d","68":"e","69":"f","70":"g","71":"h","72":"i","73":"j","74":"k","75":"l","76":"m","77":"n","78":"o","79":"p","80":"q","81":"r","82":"s","83":"t","84":"u","85":"v","86":"w","87":"x","88":"y","89":"z","90":"{","91":"|","92":"}","93":"~","94":"¡","95":"¢","96":"£","97":"¤","98":"¥","99":"¦","100":"§","101":"¨","102":"©","103":"ª","104":"«","105":"¬","106":"®","107":"¯","108":"°","109":"±","110":"²","111":"³","112":"´","113":"µ","114":"¶","115":"·","116":"¸","117":"¹","118":"º","119":"»","120":"¼","121":"½","122":"¾","123":"¿","124":"À","125":"Á","126":"Â","127":"Ã","128":"Ä","129":"Å","130":"Æ","131":"Ç","132":"È","133":"É","134":"Ê","135":"Ë","136":"Ì","137":"Í","138":"Î","139":"Ï","140":"Ð","141":"Ñ","142":"Ò","143":"Ó","144":"Ô","145":"Õ","146":"Ö","147":"×","148":"Ø","149":"Ù","150":"Ú","151":"Û","152":"Ü","153":"Ý","154":"Þ","155":"ß","156":"à","157":"á","158":"â","159":"ã","160":"ä","161":"å","162":"æ","163":"ç","164":"è","165":"é","166":"ê","167":"ë","168":"ì","169":"í","170":"î","171":"ï","172":"ð","173":"ñ","174":"ò","175":"ó","176":"ô","177":"õ","178":"ö","179":"÷","180":"ø","181":"ù","182":"ú","183":"û","184":"ü","185":"ý","186":"þ","187":"ÿ","188":"Ā","189":"ā","190":"Ă","191":"ă","192":"Ą","193":"ą","194":"Ć","195":"ć","196":"Ĉ","197":"ĉ","198":"Ċ","199":"ċ","200":"Č","201":"č","202":"Ď","203":"ď","204":"Đ","205":"đ","206":"Ē","207":"ē","208":"Ĕ","209":"ĕ","210":"Ė","211":"ė","212":"Ę","213":"ę","214":"Ě","215":"ě","216":"Ĝ","217":"ĝ","218":"Ğ","219":"ğ","220":"Ġ","221":"ġ","222":"Ģ","223":"ģ","224":"Ĥ","225":"ĥ","226":"Ħ","227":"ħ","228":"Ĩ","229":"ĩ","230":"Ī","231":"ī","232":"Ĭ","233":"ĭ","234":"Į","235":"į","236":"İ","237":"ı","238":"IJ","239":"ij","240":"Ĵ","241":"ĵ","242":"Ķ","243":"ķ","244":"ĸ","245":"Ĺ","246":"ĺ","247":"Ļ","248":"ļ","249":"Ľ","250":"ľ","251":"Ŀ","252":"ŀ","253":"Ł","254":"ł","255":"Ń","256":"in","257":"er","258":"th","259":"an","260":"on","261":"re","262":"en","263":"at","264":"or","265":"st","266":"al","268":"the","269":"le","271":"it","277":"of","278":"to","279":"ing","280":"me","281":"de","282":"ac","283":"as","290":"ve","291":"il","295":"co","296":"lo","297":"ge","300":"te","301":"ig","303":"ãĤ","304":"su","305":"ra","306":"he","307":"for","311":"un","312":"ãĥ","314":"ss","320":"am","331":"ul","332":"ab","334":"ver","335":"mo","337":"pl","343":"ãģ","344":"ex","350":"us","354":"um","359":"ll","363":"we","369":"qu","371":"The","375":"age","376":"com","382":"áº","385":"ure","387":"ãĢ","390":"ï¼","406":"end","407":"int","458":"æ°","483":"ld","486":"ä½","523":"æĿ","542":"ple","545":"ä¸","608":"æĸ","631":"äº","666":"ame","694":"sp","718":"âĢ","719":"ä»","723":"æĹ","733":"å¥","740":"çķ","757":"å¤","762":"ther","781":"ile","786":"wor","794":"ace","799":"not","801":"pr","810":"à¥","819":"was","832":"get","833":"âĦ","840":"fo","845":"xt","847":"ìķ","874":"tra","891":"la","909":"line","911":"text","917":"del","919":"pa","930":"name","940":"íķ","999":"ak","1036":"ê³","1038":"ìĦ","1044":"tp","1052":"wo","1061":"org","1082":"file","1093":"wer","1119":"model","1122":"ample","1137":"ìļ","1160":"print","1175":"sum","1177":"they","1187":"ëħ","1207":"hel","1211":"Lo","1286":"two","1364":"na","1377":"Âł","1428":"Ser","1434":"bre","1448":"path","1483":"ature","1582":"begin","1626":"space","1630":"don","1719":"def","1740":"mess","1746":"py","1805":"example","1873":"ung","1915":"link","1966":"world","2108":"ken","2157":"next","2160":"break","2185":"ump","2285":"bin","2368":"ãģ¡","2369":"ãģ«","2467":"lig","2706":"single","2891":"ather","2906":"token","2958":"city","2986":"user","3092":"came","3136":"fra","3158":"Don","3254":"bul","3415":"ald","3529":"ãĥĪ","3843":"ote","3932":"non","4018":"sam","4164":"Word","4460":"usr","4474":"Case","4832":"bold","4835":"Ht","4896":"Hi","5153":"½","5164":"é","5169":"ï","5217":"ÃŁ","5234":"İ","5235":"ı","5348":"Σ","5350":"Î¥","5351":"Φ","5369":"ο","5384":"ÎŁ","5388":"ÏĤ","5389":"Ïĥ","5391":"Ïħ","5392":"ÏĨ","5397":"Т","5412":"в","5415":"е","5418":"и","5441":"ÐĴ","5444":"Ðķ","5447":"Ðĺ","5454":"ÐŁ","5455":"Ðł","5457":"ÑĢ","5459":"ÑĤ","5627":"ا","5628":"ب","5644":"ع","5651":"ÙĦ","5652":"Ùħ","5916":"ãĤ¿","5932":"ãĤĵ","5938":"ãĥ¡","5944":"ãĥ«","5947":"ãĥ¯","5959":"ãĥ¼","6079":"ãģ§","6085":"ãģ¯","6101":"ãģĦ","6114":"ãģĵ","6118":"ãģĻ","6126":"ãģŃ","6335":"áºŀ","6433":"ãĢģ","6434":"ãĢĤ","6622":"ï¼ģ","6633":"ï¼Į","10282":"æ°Ĺ","11739":"ä½ł","13693":"æĿ±","14789":"ä¸ĸ","14798":"ä¸Ń","18004":"æĸĩ","19060":"京","23064":"âĢĻ","23068":"âĢĿ","23104":"ä»Ĭ","23275":"æĹ¥","23643":"好","23996":"çķĮ","24596":"天","25486":"४","25487":"५","25488":"६","25627":"âĦ¢","25767":"ìķĪ","26524":"íķĺ","26968":"ê³Ħ","26996":"ìĦ¸","27470":"ìļĶ","27616":"ëħķ","30847":"weather","30911":"stan","31000":"quote","31091":"Donald","31126":"Http","31193":"frag","31229":"trail","31478":"jump","31810":"sampl","32205":"hello","32269":"Hello","32329":"fox","32999":"tower","33782":"abc","33974":"Visit","34664":"Tokyo","39907":"camel","43683":"Request","48038":"content","52861":"Server","65722":"еÑĤ","65752":"message","66498":"اÙĦ","67972":"ÐŁÑĢ","68014":"ĊĊ","68015":"ðŁ","68017":"ĊĊĊĊ","68019":"ĊĊĊ","68026":"10","68051":"âĢĮ","68052":"11","68078":"()","68099":"ðŁĩ","68100":"ðŁı","68103":"ré","68111":"202","68128":"000","68191":"ðŁij","68224":"ί","68227":"اÙĦÙħ","68247":"čĊ","68251":"21","68358":"45","68399":"веÑĤ","68410":"90","68550":"ĉĉĉĉ","68619":"âĢĭ","68642":"ð٦","68666":"ðŁļ","68745":"باÙĦ","68872":"42","68911":"ãĢĢ","69022":"59","69195":"Ìģ","69389":"ðŁı½","70095":"days","70363":"âĢį","70392":"čĊčĊ","70747":"args","70806":"printf","70904":"123","71145":"ÏĥÏħ","71168":"ÐŁÑĢи","71511":"ðŁĩ¸","72569":"ðŁĩº","72897":"عاÙĦÙħ","73275":"ðŁĩµ","73388":"141","73561":"ÌĢ","73886":"333","74269":"ðŁij©","75157":"ðŁij¨","75600":"ÏĨο","76130":"sampling","76606":"ï¬ģ","76858":"ðŁijį","77122":"ãģ§ãģĻ","77863":"012","80401":"ÙħرØŃبا","81554":"456","81999":"345","82007":"ÐłÐĺ","83184":"ðŁĩ¯","84572":"wasn","85381":"ãĥ¼ãĥĪ","86414":"ìĦ¸ìļĶ","87292":"ðŁij§","87550":"kwargs","87862":"ðŁij¦","90460":"Ù¡","91336":"ÌĤ","91927":"789","95893":"Ù¢","97293":"678","101790":"ÎŁÎ£","102467":"ìĦ¸ê³Ħ","103419":"ÐĴÐķ","105763":"breaking","108114":"eÌģ","108185":"ðŁļĢ","109184":"ð٦Ļ","110174":"ä¸ĸçķĮ","111563":"íķĺìĦ¸ìļĶ","111833":"âĢ©","114903":"ä¸Ńæĸĩ","116200":"ãģĵãĤĵ","117177":"ìķĪëħķ","117386":"ãģĦãģĦ","118188":"sumé","118229":"æĿ±äº¬","119077":"Ù£","119820":"Ïĥί","120967":"Café","121115":"stanbul","121933":"Ù¤","124784":"ä»ĬæĹ¥","128458":"ìķĪëħķíķĺìĦ¸ìļĶ","144765":"ãģ¡ãģ¯","145040":"++","145054":"**","145055":"//","145862":"ON","145866":"ST","145879":"OR","145883":"ML","145887":"HT","145896":"LL","145922":"TP","145992":"XML","146001":"LD","146005":"HTTP","146066":"HE","146080":"OP","146508":"WOR","148033":"STOP","148122":"DON","148284":"LLO","149826":"âħ«","149842":"âħ»","149859":"ĠĠ","149860":"ĠĠĠĠ","149861":"ĠĠĠĠĠĠĠĠ","149862":"ĠĠĠ","149876":"Ġthe","149880":"Ġand","149900":"Ġi","149918":"Ġor","149921":"Ġit","149924":"Ġx","149946":"Ġna","149963":"Ġb","149972":"Ġc","149991":"Ġme","150003":"Ġif","150011":"Ġone","150051":"Ġthey","150053":"Ġover","150060":"ĠâĢľ","150102":"Ġthere","150182":"Ġré","150220":"ĠâĢĶ","150266":"ĠHe","150273":"Ġafter","150311":"Ġtext","150389":"Ġcontrol","150396":"Ġthree","150463":"Ġbefore","150491":"Ġhttps","150520":"Ġmain","150583":"Ġreturn","150657":"Ġsay","150701":"ĠباÙĦ","150770":"Ġworld","150785":"Ġspace","150792":"Ġfour","150817":"ĠâĢĺ","150830":"ĠNone","151091":"ĠâĤ¬","151105":"Ġâ̦","151177":"Ġfamily","151456":"Ġsure","151712":"Ġzero","152065":"ĠMc","152077":"Ġwidth","152467":"Ġlove","152570":"ĠÐŁÑĢи","152850":"Ġlig","152875":"ĠDon","153350":"Ġdog","154109":"Ġnine","154384":"Ġleading","154437":"Ġ©","154695":"Ġmail","155956":"Ġskin","156465":"Ġspaces","157021":"Ġquick","157354":"Ġwasn","157841":"Ġ£","158322":"ĠмиÑĢ","158507":"ĠâĪļ","158821":"Ġı","160581":"Ġjump","161319":"Ġbrown","161703":"Ġlazy","163574":"Ġनमसà¥įतà¥ĩ","163900":"ĠâĪŀ","164865":"Ġदà¥ģनिया","164969":"Ġtone","170593":"Ġflags","171551":"Ġhello","172469":"Ġcombining","173339":"Ġfoo","178755":"Ġâīł","188766":"ĠHello","190207":"ĠâĪij","193252":"ĠÂ¥","196973":"Ġ-","196975":"Ġ|","196976":"Ġ(","196977":"Ġ=","196980":"Ġ\"","196982":"Ġ<","196983":"Ġ{","196987":"Ġ*","196995":"Ġ>","197033":"Ġ**","198420":"ĠXML","198431":"ĠHE","199445":"ĠDON","199998":"<|unused|>","199999":"<|endoftext|>","200000":"<|message_user|>","200001":"<|message_model|>","200002":"<|message_system|>","200003":"<|message_tool|>","200004":"<|content_text|>","200005":"<|content_image|>","200006":"<|content_model_end_sampling|>","200007":"<|unused_200007|>","200008":"<|content_thinking|>","200009":"<|unused_200009|>","200010":"<|end_message|>","200011":"<|unused_200011|>","200012":"<|unused_200012|>","200013":"<|unused_200013|>","200014":"<|unused_200014|>","200015":"<|unused_200015|>","200016":"<|unused_200016|>","200017":"<|unused_200017|>","200018":"<|unused_200018|>","200019":"<|unused_200019|>","200020":"<|unused_200020|>","200021":"<|unused_200021|>","200022":"<|content_tool_error|>","200023":"<|unused_200023|>","200024":"<|content_xml|>","200025":"<|unused_200025|>","200026":"<|unused_200026|>","200027":"<|unused_200027|>","200028":"<|begin_of_text|>","200029":"<|unused_200029|>","200030":"<|unused_200030|>","200031":"<|unused_200031|>","200032":"<|unused_200032|>","200033":"<|unused_200033|>","200034":"<|unused_200034|>","200035":"<|unused_200035|>","200036":"<|unused_200036|>","200037":"<|unused_200037|>","200038":"<|unused_200038|>","200039":"<|unused_200039|>","200040":"<|unused_200040|>","200041":"<|unused_200041|>","200042":"<|unused_200042|>","200043":"<|unused_200043|>","200044":"<|unused_200044|>","200045":"<|unused_200045|>","200046":"<|unused_200046|>","200047":"<|unused_200047|>","200048":"<|unused_200048|>","200049":"<|content_invoke_tool_json|>","200050":"<|unused_200050|>","200051":"<|unused_200051|>","200052":"<|unused_200052|>","200053":"<|unused_200053|>","200054":"<|unused_200054|>","200055":"<|unused_200055|>","200056":"<|unused_200056|>","200057":"<|content_invoke_tool_text|>"},"control":[199998,199999,200000,200001,200002,200003,200004,200005,200006,200007,200008,200009,200010,200011,200012,200013,200014,200015,200016,200017,200018,200019,200020,200021,200022,200023,200024,200025,200026,200027,200028,200029,200030,200031,200032,200033,200034,200035,200036,200037,200038,200039,200040,200041,200042,200043,200044,200045,200046,200047,200048,200049,200050,200051,200052,200053,200054,200055,200056,200057],"merges":["i n","e r","t h","a n","o n","r e","e n","a t","o r","s t","a l","th e","l e","i t","o f","t o","in g","m e","d e","a c","a s","v e","i l","c o","l o","g e","t e","i g","ã Ĥ","s u","r a","h e","f or","u n","ã ĥ","s s","a m","u l","a b","v er","m o","p l","ã ģ","e x","u s","u m","l l","w e","q u","a ge","co m","á º","u re","ã Ģ","ï ¼","en d","in t","æ °","l d","ä ½","æ Ŀ","p le","ä ¸","æ ĸ","ä º","a me","s p","â Ģ","ä »","æ Ĺ","å ¥","ç ķ","å ¤","th er","i le","w or","ac e","p r","à ¥","w as","â Ħ","f o","x t","ì ķ","t ra","l a","te xt","de l","p a","í ķ","a k","ê ³","ì Ħ","t p","w o","or g","f ile","w er","mo del","am ple","ì ļ","pr int","su m","the y","ë ħ","he l","L o","t wo","n a"," ł","S er","b re","pa th","at ure","sp ace","d on","de f","me ss","p y","ex ample","un g","wor ld","k en","bre ak","um p","b in","ãģ ¡","ãģ «","l ig","a ther","to ken","us er","c ame","f ra","D on","b ul","al d","ãĥ Ī","o te","n on","s am","us r","H t","à ©","à ¯","Ä °","Ä ±","Î £","Î ¥","Î ¦","Î ¿","Î Ł","Ï Ĥ","Ï ĥ","Ï ħ","Ï Ĩ","Ð ¢","Ð ²","Ð µ","Ð ¸","Ð Ĵ","Ð ķ","Ð ĺ","Ð Ł","Ð ł","Ñ Ģ","Ñ Ĥ","Ø §","Ø ¨","Ø ¹","Ù Ħ","Ù ħ","ãĤ ¿","ãĤ ĵ","ãĥ ¡","ãĥ «","ãĥ ¯","ãĥ ¼","ãģ §","ãģ ¯","ãģ Ħ","ãģ ĵ","ãģ Ļ","ãģ Ń","Ạŀ","ãĢ ģ","ãĢ Ĥ","ï¼ ģ","ï¼ Į","æ° Ĺ","ä½ ł","æĿ ±","ä¸ ĸ","ä¸ Ń","æĸ ĩ","äº ¬","ä» Ĭ","æĹ ¥","å¥ ½","çķ Į","å¤ ©","ॠª","ॠ«","ॠ¬","âĦ ¢","ìķ Ī","íķ ĺ","ê³ Ħ","ìĦ ¸","ìļ Ķ","ëħ ķ","we ather","st an","qu ote","Don ald","Ht tp","fra g","tra il","j ump","sam pl","hel lo","fo x","to wer","ab c","came l","Ser ver","е ÑĤ","mess age","ا ÙĦ","ÐŁ ÑĢ","Ċ Ċ","ð Ł","ĊĊ ĊĊ","âĢ Į","ðŁ ĩ","ðŁ ı","r é","ðŁ ij","Î ¯","اÙĦ Ùħ","в еÑĤ","âĢ ĭ","ðŁ ¦","ðŁ ļ","ب اÙĦ","ãĢ Ģ","Ì ģ","ðŁı ½","âĢ į","print f","Ïĥ Ïħ","ÐŁÑĢ Ð¸","ðŁĩ ¸","ðŁĩ º","ع اÙĦÙħ","ðŁĩ µ","Ì Ģ","ðŁij ©","ðŁij ¨","ÏĨ ο","sampl ing","ðŁij į","ãģ§ ãģĻ","Ðł Ðĺ","ðŁĩ ¯","was n","ãĥ¼ ãĥĪ","ìĦ¸ ìļĶ","ðŁij §","ðŁij ¦","Ù ¡","Ì Ĥ","Ù ¢","ÎŁ Σ","ìĦ¸ ê³Ħ","ÐĴ Ðķ","break ing","e Ìģ","ðŁļ Ģ","ðŁ¦ Ļ","ä¸ĸ çķĮ","íķĺ ìĦ¸ìļĶ","âĢ ©","ä¸Ń æĸĩ","ãģĵ ãĤĵ","ìķĪ ëħķ","ãģĦ ãģĦ","sum é","æĿ± 京","Ù £","Ïĥ ί","stan bul","ä»Ĭ æĹ¥","ìķĪëħķ íķĺìĦ¸ìļĶ","ãģ¡ ãģ¯","+ +","* *","/ /","O N","S T","O R","M L","H T","L L","T P","X ML","L D","HT TP","H E","O P","W OR","ST OP","D ON","LL O","Ġ Ġ","ĠĠ ĠĠ","ĠĠĠĠ ĠĠĠĠ","ĠĠ Ġ","Ġ it","Ġ na","Ġ they","Ġ ré","Ġ باÙĦ","Ġ ÐŁÑĢи","Ġ lig","Ġ Don","Ġ wasn","Ġ ı","Ġ jump","Ġ |","Ġ =","Ġ <","Ġ {","Ġ XML","Ġ HE","Ġ DON"]} diff --git a/serve/frontend.py b/serve/frontend.py index 553ca86f04..9a8545e087 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -83,6 +83,7 @@ def render(messages, tools=None): return "" user = {"role": "user", "content": "strata_caps_user"} + inkling = is_inkling_template(self.source) # Inkling's own blocks, not the XML tools = [{"name": f"strata_caps_call_{i}", "description": "strata_caps_description", "parameters": {"type": "object", "properties": {"arg": {"type": "string"}}}} for i in range(2)] @@ -98,19 +99,27 @@ def calls_supported(count): prompt = render(messages, tools) # Instructions include example XML and literal tag names, which are not model output. Parse only # complete calls to our probe functions, using the same body parser as OutputParser. - bodies = re.findall(r"\s*(.*?)\s*", - prompt, re.S) - try: - parsed = [parse_tool_call(body) for body in bodies] - except ValueError: - return False + if inkling: # <|message_model|>NAME<|content_invoke_tool_json|>{...} + parsed = [parse_inkling_tool_call(name, body) for name, body in re.findall( + re.escape(INK_HEADER) + r"(strata_caps_call_\d+)" + re.escape(INK_TOOL_JSON) + "(.*?)" + + re.escape(INK_END), prompt, re.S)] + if None in parsed: + return False + else: + bodies = re.findall(r"\s*(.*?)\s*", + prompt, re.S) + try: + parsed = [parse_tool_call(body) for body in bodies] + except ValueError: + return False return [{"name": call.name, "arguments": call.arguments} for call in parsed] == calls \ and all(reply in prompt for reply in replies) history = [user, {"role": "assistant", "content": "strata_caps_answer", "reasoning_content": "strata_caps_reasoning"}, user] + marks = (INK_TOOL_DECLARE,) if inkling else ("", "", " tuple[str, str | None]: return "unknown", None -def forced_call(tool_choice, tools: list[dict] | None) -> str | None: +def forced_call(tool_choice, tools: list[dict] | None, call_format: str = "function") -> str | None: """`tool_choice` -> the text that opens the call the reply must make, or None (the model decides). There is no grammar here: the server writes this opening itself, so the model can only go on with a call. "required" / Anthropic "any": any of the tools; a named function: that one. A value it cannot honour (an @@ -807,6 +816,15 @@ def forced_call(tool_choice, tools: list[dict] | None) -> str | None: return None if kind == "required" and len(names) == 1: # one tool to call: name it, the model cannot invent another kind, name = "named", next(iter(names)) + if call_format == "inkling": + # Inkling's call opens with the tool's name: a named one is written up to its arguments; "required" among + # several cannot be opened without choosing the name, so the model decides + if kind == "named" and name in names: + return INK_HEADER + name + INK_TOOL_JSON + '{"name":' + json.dumps(name) + ',"args":' + if kind == "required" and names: + print("[strata] tool_choice \"required\" with several tools is not supported for this model: the model " + "decides, as with \"auto\"", flush=True) + return None if kind == "required" and names: return CALL_START + "\n list[Event]: self._reset_scan() self.state, self.lead = "content", True return [Event("tool_call", call=call)] + + +# ------------------------------------------------------------------------------------------------ Inkling 2 +# Inkling's reply is a list of blocks, each opened by <|message_model|> and closed by <|end_message|> (llama.cpp +# 29b52d398b common/parsers/inkling.cpp, PR 32381): +# <|message_model|><|content_thinking|>...<|end_message|> its reasoning +# <|message_model|><|content_text|>...<|end_message|> its answer +# <|message_model|>NAME<|content_invoke_tool_json|>{"name":"NAME","args":{...}}<|end_message|> a tool call +# and the turn ends with <|content_model_end_sampling|>, the GGUF's eos. The model writes the first header itself: +# the template's prompt ends on a closed block, with no generation prompt. +INK_HEADER = "<|message_model|>" +INK_THINK = "<|content_thinking|>" +INK_TEXT = "<|content_text|>" +INK_TOOL_JSON = "<|content_invoke_tool_json|>" +INK_END = "<|end_message|>" +INK_SAMPLING_END = "<|content_model_end_sampling|>" +INK_TOOL_DECLARE = "<|message_system|>tool_declare" # the system block that declares the request's tools +INK_NAME_MAX = 256 # a header followed by more than this without <|content_...|> is not a call + + +def is_inkling_template(source: str) -> bool: + """llama.cpp's test for an Inkling 1 or 2 template.""" + return "<|message_user|>" in source and "<|content_image|>" in source + + +def inkling_call_end(text: str) -> int: + """Where the <|end_message|> that closes a call block's JSON is in `text`, or -1. One inside a JSON string (code + that prints the tag) is the string's: llama.cpp's grammar reads the JSON first. Text that is not JSON ends at + the first one, and so does JSON followed by the next block's header.""" + i = text.find(INK_END) + if i < 0 or not text.lstrip().startswith("{"): + return i + depth, in_str, esc, j = 0, False, False, 0 + while i >= 0: + for c in text[j:i]: # the JSON up to this candidate + if in_str: + if esc: + esc = False + elif c == "\\": + esc = True + elif c == '"': + in_str = False + elif c == '"': + in_str = True + elif c in "{[": + depth += 1 + elif c in "}]": + depth -= 1 + if (not in_str and depth <= 0) or text.startswith(INK_HEADER, i + len(INK_END)): + return i # (JSON that never closes ends where the next block opens) + j = i + i = text.find(INK_END, i + 1) + return -1 + + +def inkling_json_end(text: str) -> int: + """Where the JSON object `text` starts with closes (the index past its last brace), or -1: not JSON, or not closed + yet. Braces and brackets inside strings are the strings'.""" + if not text.lstrip().startswith("{"): + return -1 + depth, in_str, esc = 0, False, False + for k, c in enumerate(text): + if in_str: + if esc: + esc = False + elif c == "\\": + esc = True + elif c == '"': + in_str = False + elif c == '"': + in_str = True + elif c in "{[": + depth += 1 + elif c in "}]": + depth -= 1 + if depth == 0: + return k + 1 + return -1 + + +def parse_inkling_tool_call(name: str, body: str) -> ToolCall | None: + """A call block's body, `{"name":NAME,"args":{...}}`, -> its call; None when it is not one. The name is the + header's (llama.cpp's grammar makes the two the same). A body with no "args" is the arguments alone, less the + tool's own "name" if it has one: `{"name":"get_time"}` is a call with no arguments.""" + try: + obj = json.loads(body) + except ValueError: + return None + if not isinstance(obj, dict) or not name: + return None + key = "args" if "args" in obj else "arguments" if "arguments" in obj else None + if key: + args = obj[key] + else: + args = {k: v for k, v in obj.items() if not (k == "name" and v == name)} + if args is None: + args = {} + if isinstance(args, str): # arguments written as a JSON string + try: + args = json.loads(args) + except ValueError: + return None + if not isinstance(args, dict): + return None + return ToolCall(name=name, arguments=args) + + +class InklingParser: + """OutputParser for Inkling's blocks (call_format "inkling"): the same events and the attributes Service.run reads + (state, buf, think_end, pending, rescued, refused). A class of its own rather than one of OutputParser's formats: + those mark the reasoning with tags, and Inkling's reply is a list of blocks, reasoning one kind of them. A + thinking block is reasoning whatever the request asked: the template has no switch that keeps the model from + writing one (reasoning_effort "none" asks for little). A call is announced when its name is complete and its + arguments follow whole when its block ends, as for GLM's and Gemma's. A call to a tool the request did not declare + is the text it is. + + `state`: "reasoning" in a thinking block, "call" in a call block, "text" in a text block and "content" between + blocks: a forced tool call (Service.run) is written there, never inside a block.""" + + think_open = INK_HEADER + INK_THINK + think_end = INK_END + + def __init__(self, tools: list[dict] | None = None, stream_tools: bool = False, **_): + # (OutputParser's other options - thinking, recover, call_format, opened - change nothing for these blocks) + self.schemas = {t.get("name"): t for t in tools or []} + self.stream_tools = stream_tools + self.buf = "" + self.mode = "between" # between | head | thinking | text | call + self.name = None # the call block's tool name + self.scall = None # the call announced by tool_start + self.pending: list = [] # (OutputParser's calls from the reasoning: none here) + self.seen = 0 # how much of a call block's text has no <|end_message|> + self.rescued = self.refused = 0 + + @property + def state(self) -> str: + return {"thinking": "reasoning", "call": "call", "text": "text"}.get(self.mode, "content") + + _hold = OutputParser._hold + + @staticmethod + def _clean(text: str) -> str: + return text.replace(INK_SAMPLING_END, "") + + def _emit(self, out: list, kind: str, text: str): + text = self._clean(text) + if text: + out.append(Event(kind, text)) + + def feed(self, delta: str) -> list[Event]: + self.buf += delta + out: list[Event] = [] + while True: + if self.mode == "between": + i = self.buf.find(INK_HEADER) + if i < 0: + # text outside a block (a model that leaves the format): content, without stray closers + keep = self._hold(self.buf, (INK_HEADER, INK_END, INK_SAMPLING_END)) + stray = self.buf[:len(self.buf) - keep].replace(INK_END, "") + if stray.strip(): + self._emit(out, "content", stray) + self.buf = self.buf[len(self.buf) - keep:] + return out + stray = self.buf[:i].replace(INK_END, "") + if stray.strip(): + self._emit(out, "content", stray) + self.buf = self.buf[i:] # the header stays held until what it opens is known + self.mode = "head" + elif self.mode == "head": + rest = self.buf[len(INK_HEADER):] + if rest.startswith(INK_THINK): + self.buf, self.mode = rest[len(INK_THINK):], "thinking" + continue + if rest.startswith(INK_TEXT): + self.buf, self.mode = rest[len(INK_TEXT):], "text" + continue + j = rest.find(INK_TOOL_JSON) + name = rest[:j] if j >= 0 else rest[:len(rest) - self._hold(rest, (INK_TOOL_JSON,))] + if "<|" in name or "\n" in name or len(name) > INK_NAME_MAX: + # not a call's name: a block without its content token, read as text + if not (INK_THINK.startswith(rest) or INK_TEXT.startswith(rest)): + self.buf, self.mode = rest, "text" + continue + return out + if j < 0: + return out + self.name, self.buf, self.mode = name.strip(), rest[j + len(INK_TOOL_JSON):], "call" + if self.stream_tools and self.name in self.schemas: + self.scall = ToolCall(name=self.name, arguments={}) + out.append(Event("tool_start", call=self.scall)) + elif self.mode in ("thinking", "text"): + kind = "reasoning" if self.mode == "thinking" else "content" + i = self.buf.find(INK_END) + h = self.buf.find(INK_HEADER) + if h >= 0 and (i < 0 or h < i): # a new block before this one was closed: this one ends there + self._emit(out, kind, self.buf[:h]) + self.buf, self.mode = self.buf[h:], "between" + continue + if i < 0: + keep = self._hold(self.buf, (INK_END, INK_HEADER, INK_SAMPLING_END)) + self._emit(out, kind, self.buf[:len(self.buf) - keep]) + self.buf = self.buf[len(self.buf) - keep:] + return out + self._emit(out, kind, self.buf[:i]) + self.buf, self.mode = self.buf[i + len(INK_END):], "between" + else: # call + if INK_HEADER in self.buf: + # whole JSON and then the next block's header, with no <|end_message|> between: the call ends there + e = inkling_json_end(self.buf) + if e >= 0 and self.buf[e:].lstrip().startswith(INK_HEADER): + body, self.buf = self.buf[:e], self.buf[e:].lstrip() + self.seen = 0 + out += self._finish_call(body) + self.mode = "between" + continue + # a long call is searched only where text came since the last look, until an <|end_message|> came + i = inkling_call_end(self.buf) if self.buf.find(INK_END, self.seen) >= 0 else -1 + if i < 0: + self.seen = max(0, len(self.buf) - len(INK_END) + 1) + return out + self.seen = 0 + body, self.buf = self.buf[:i], self.buf[i + len(INK_END):] + out += self._finish_call(body) + self.mode = "between" + + def _finish_call(self, body: str) -> list[Event]: + out = [] + call = parse_inkling_tool_call(self.name, body) if self.name in self.schemas else None + if call is None: + self._emit(out, "content", INK_HEADER + (self.name or "") + INK_TOOL_JSON + body) + else: + if self.scall is not None: + call.id = self.scall.id + out.append(Event("tool_args", json.dumps(call.arguments, ensure_ascii=False), call=self.scall)) + out.append(Event("tool_call", call=call)) + self.name, self.scall = None, None + return out + + def finish(self, reason: str | None = None) -> list[Event]: + """End of generation: what is held goes out. A call block whose JSON is whole but whose <|end_message|> did + not come is the call; an unfinished one is text, or, when it was announced already, stays unfinished (no + "tool_call", as OutputParser does, #211).""" + out: list[Event] = [] + buf, self.buf = self.buf, "" + if self.mode in ("thinking", "text"): + if not any(tag.startswith(buf) for tag in (INK_END, INK_HEADER, INK_SAMPLING_END)): + self._emit(out, "reasoning" if self.mode == "thinking" else "content", buf) + elif self.mode == "call": + if parse_inkling_tool_call(self.name, buf) is not None or self.scall is None: + out += self._finish_call(buf) + self.name, self.scall = None, None + elif self.mode == "head": + rest = buf[len(INK_HEADER):] + if rest and not (INK_THINK.startswith(rest) or INK_TEXT.startswith(rest) + or INK_TOOL_JSON.startswith(rest)) and "<|" not in rest: + self._emit(out, "content", rest) + elif buf.strip() and not any(tag.startswith(buf) for tag in (INK_HEADER, INK_END, INK_SAMPLING_END)): + self._emit(out, "content", buf.replace(INK_END, "")) + self.mode = "between" + return out diff --git a/serve/models.py b/serve/models.py index a8421234d0..89f3ae5310 100644 --- a/serve/models.py +++ b/serve/models.py @@ -29,6 +29,7 @@ "lfm2moe": "lfm2moe", "flint": "flint", "kolibri1": "kolibri1", + "inkling2_loop": "inkling2_loop", } # a routed expert's tensors: they stay in the file and are held in VRAM as far as it has room EXPERT = re.compile(r"\.ffn_(gate|up|down|gate_up)_exps\.weight$") diff --git a/serve/server.py b/serve/server.py index fc3d435b9f..f1b480f922 100644 --- a/serve/server.py +++ b/serve/server.py @@ -59,9 +59,9 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tools")) sys.path.insert(0, str(ROOT)) # run as a script (run-.bat) as well as a module -from serve.frontend import (THINK_END, ChatTemplate, Event, OutputParser, anthropic_to_messages, # noqa: E402 - forced_call, gemma_model_turn, images_of, literal_tags, mark_think_literals, - openai_to_messages, tool_choice_of, unmark_think_literals) +from serve.frontend import (THINK_END, ChatTemplate, Event, InklingParser, OutputParser, # noqa: E402 + anthropic_to_messages, forced_call, gemma_model_turn, images_of, literal_tags, + mark_think_literals, openai_to_messages, tool_choice_of, unmark_think_literals) from serve.mcp import McpCancelled, hub_from_config # noqa: E402 from serve import runconfig # noqa: E402 from serve import models as registry # noqa: E402 @@ -152,7 +152,25 @@ def write_temporary(path: Path, parts: list) -> None: # ends the first turn: the system prompt with the tools, which "warm_start" keeps. TURN_OPENERS = {"function": ("<|im_start|>",), "gemma": ("<|turn>",), "glm": ("<|system|>", "<|developer|>", "<|user|>", "<|assistant|>", "<|observation|>"), - "dsml": ("<|User|>", "<|Assistant|>"), "lfm2": ("<|im_start|>",)} + "dsml": ("<|User|>", "<|Assistant|>"), "lfm2": ("<|im_start|>",), + # Inkling: every block of a message opens with its role's token + "inkling": ("<|message_system|>", "<|message_user|>", "<|message_model|>", "<|message_tool|>")} +# Inkling's reasoning_effort (its template: none, minimal, low, medium, high (the default, 0.9), xhigh, max or a +# number from 0 to 0.99) for the levels effort_kwargs() makes. A client's "high" arrives as "xhigh" there +# (frontend.EFFORT), which is Inkling's "high"; thinking off is its "none". +INKLING_EFFORT = {"xhigh": "high"} + + +def inkling_kwargs(kwargs: dict) -> dict: + """The template arguments of an Inkling prompt (render_prompt(), and resolve_prefix()'s head of it): its template + reads only reasoning_effort, so thinking off is its "none" and a level its own name (INKLING_EFFORT).""" + out = {k: v for k, v in kwargs.items() if k != "enable_thinking"} + effort = kwargs.get("reasoning_effort") + if kwargs.get("enable_thinking") is False: + out["reasoning_effort"] = "none" + elif effort not in (None, ""): + out["reasoning_effort"] = INKLING_EFFORT.get(effort, effort) + return out WARM_MIN_TOKENS = 2048 # a shorter prompt start is quick to read again: not kept # #606: a reply that repeats one token this many times in a row is ended there ("length"): a model in a loop, or a # broken state that answers one token forever (an issue saw 36,689 tokens of "!"). The config's "repeat_stop_tokens" @@ -3406,7 +3424,8 @@ def _read_tokenizer(self, tokenizer) -> None: # how the model writes a tool call (serve/frontend.py's OutputParser) pre = getattr(tokenizer, "pre", "") self.call_format = "glm" if pre in ("glm4", "glm5", "flint") else "gemma" if pre == "gemma4" else \ - "dsml" if pre in ("joyai-llm", "deepseek-v3") else "lfm2" if pre == "lfm2" else "function" + "dsml" if pre in ("joyai-llm", "deepseek-v3") else "lfm2" if pre == "lfm2" else \ + "inkling" if pre == "inkling2" else "function" self.turn_ids = frozenset(t[0] for t in (tokenizer.encode(s, parse_special=True) for s in TURN_OPENERS[self.call_format]) if len(t) == 1) self.engine.turn_ids = self.turn_ids # the GEN line's turn_at (StrataEngine.turn_key) @@ -3429,12 +3448,20 @@ def _read_tokenizer(self, tokenizer) -> None: for end in ("<|user|>", "<|observation|>", "<|developer|>"): ids = tokenizer.encode(end, parse_special=True) self.stop_ids |= set(ids if len(ids) == 1 else []) + elif self.call_format == "inkling": + # llama.cpp ends Inkling's reply at its eos, <|content_model_end_sampling|>, and at <|endoftext|> (the + # GGUF's pad), a token it ends every model at by its text + ids = tokenizer.encode("<|endoftext|>", parse_special=True) + self.stop_ids |= set(ids if len(ids) == 1 else []) # an image in a prompt (prepare()): the token the template writes for it, which stands for each of its rows; # the token the template writes before that one, if it writes one; the tokens to put around the rows, if # the template leaves that to the program # A template that writes the marker alone (MiniCPM-V 4.7's, like Gemma 4's) has no token before it to tell # an image's marker from the same text in a message: the first ones are the images (prepare()). + # Inkling 2's template writes <|content_image|><|unused_200054|> in a block of its own, and llama.cpp's mtmd + # puts the rows in place of the second (its img_beg is <|content_image|>, it writes no end). self.image_marks = ("<|image|>", None, ("<|image>", "")) if self.call_format == "gemma" else \ + ("<|unused_200054|>", "<|content_image|>", None) if self.call_format == "inkling" else \ (IMAGE_PAD, VISION_START if VISION_START in getattr(self.template, "source", VISION_START) else None, None) # #567: a prompt re-encodes only what follows the last special token it shares with a recent prompt (the # same ids as a full encode: tools/strata_tokenizer.py PromptEncoder). Tokenizers without resume points @@ -4499,6 +4526,11 @@ def render_prompt(self, messages, tools, kwargs) -> str: "enable_thinking": not off} if self.call_format in ("gemma", "dsml") and tools: # their templates read a tool as OpenAI sends it tools = [{"type": "function", "function": t} for t in tools] + if self.call_format == "inkling": + # Inkling's template reads only reasoning_effort, and writes it in a system block before the first + # message that is not a system one: effort_end's turn at the end is not its form. Its prompt ends on a + # closed block; the model writes the header of its reply itself, as with llama.cpp. + return self.template.render(messages, tools=tools, **inkling_kwargs(kwargs)) if not self.effort_end or (not off and effort in (None, "", "xhigh", "high")): prompt = self.template.render(messages, tools=tools, **kwargs) if self.call_format == "gemma": @@ -4780,8 +4812,11 @@ def head_ids(msgs): marked, marked_tools, changed = mark_think_literals(msgs, tools, self.literals) effort = kwargs.get("reasoning_effort") off = kwargs.get("enable_thinking") is False # render_prompt's rule for #458's effort_end - kw = ({k: v for k, v in kwargs.items() if k not in ("reasoning_effort", "enable_thinking")} - if self.effort_end and (off or effort not in (None, "", "xhigh", "high")) else dict(kwargs)) + if self.call_format == "inkling": # render_prompt's arguments for its template + kw = inkling_kwargs(kwargs) + else: + kw = ({k: v for k, v in kwargs.items() if k not in ("reasoning_effort", "enable_thinking")} + if self.effort_end and (off or effort not in (None, "", "xhigh", "high")) else dict(kwargs)) kw["add_generation_prompt"] = False text = self.template.render(marked, tools=marked_tools, **kw) cut = text.find(self.PREFIX_END) @@ -4942,8 +4977,9 @@ def _run(self, ids, thinking, tools, max_new, sampling, cancel, force=None) -> I f"the answer (budget {budget})", flush=True) budget = max(1, max_new - reserve) opened = bool(self.think_open_ids) and ids[-len(self.think_open_ids):] == self.think_open_ids - parser = OutputParser(thinking=thinking, tools=tools, stream_tools=True, recover=self.tool_call_recovery, - call_format=self.call_format, opened=opened) + parser = (InklingParser if self.call_format == "inkling" else OutputParser)( + thinking=thinking, tools=tools, stream_tools=True, recover=self.tool_call_recovery, + call_format=self.call_format, opened=opened) detok, n, finish = Detokenizer(self.tok), 0, "length" run_tok, run_len, repeated = None, 0, False # #606: the current run of one repeated token thinking_n = 0 # tokens written while thinking (Responses' reasoning_tokens) @@ -4968,6 +5004,10 @@ def cut(evs): out.append(Event("content", held)) out.append(ev) return out + # Inkling goes on writing after a call it did not choose itself (a thinking block and an answer): once the + # forced call is whole, a block that opens after it ends the reply, as tool_choice asks + after_forced = force is not None and self.call_format == "inkling" + forced_done = False opening = [] # without thinking the prompt ends with the forced opening: if force and not thinking: # the parser reads it as if the model had written it opening, force = parser.feed(force), None @@ -5111,6 +5151,13 @@ def cut(evs): piece = detok.push(t) tail = (tail + piece)[-2:] evs = cut(parser.feed(piece)) + if forced_done and parser.state in ("reasoning", "text"): + evs = [ev for ev in evs if ev.kind not in ("reasoning", "content")] + for ev in evs: + yield "event", ev + finish = "stop" + break + forced_done = forced_done or after_forced and any(ev.kind == "tool_call" for ev in evs) self._note(n, evs, st, rate) last_print = self._progress(last_print, st=st) for ev in evs: @@ -5253,7 +5300,9 @@ def cut(evs): budget = st["thinking_budget"] = None text = closed_with(REASONING_WRAP_UP, parser.think_end) + (force or "") else: - text = "\n" * (2 - (len(tail) - len(tail.rstrip("\n")))) + force + # (Inkling's blocks follow each other with nothing between them) + text = force if self.call_format == "inkling" else \ + "\n" * (2 - (len(tail) - len(tail.rstrip("\n")))) + force force = None extra = self.tok.encode(text, parse_special=True) if max_new - n - len(extra) < 1: @@ -6740,7 +6789,8 @@ def _openai(self, req): self._no_local_images(messages) if tool_choice_of(req.get("tool_choice"))[0] == "none": # as the Responses route: no tools are offered tools = None - force = forced_call(req.get("tool_choice"), tools) # a bad value is a 400 before anything is sent + # a bad value is a 400 before anything is sent + force = forced_call(req.get("tool_choice"), tools, getattr(svc, "call_format", "function")) messages, validator = prepare_format(req.get("response_format"), messages) if validator is not None and (tools or req.get("strata_mcp")): raise ValueError("structured response_format with tools/MCP is not supported") @@ -6984,7 +7034,8 @@ def _anthropic(self, req): self._no_local_images(messages) if tool_choice_of(req.get("tool_choice"))[0] == "none": # Anthropic's {"type": "none"}: no tools offered tools = None - force = forced_call(req.get("tool_choice"), tools) # "any" / {"type": "tool", "name": N} + # "any" / {"type": "tool", "name": N} + force = forced_call(req.get("tool_choice"), tools, getattr(svc, "call_format", "function")) max_new = int(req.get("max_tokens") or 0) # 0/-1: the rest of the context svc.reasoning_budget(req) # a bad value is a 400 before anything is sent stop_strings(req) # ... and so is a bad stop / stop_sequences diff --git a/serve/test_inkling.py b/serve/test_inkling.py new file mode 100644 index 0000000000..a83d9ec986 --- /dev/null +++ b/serve/test_inkling.py @@ -0,0 +1,558 @@ +"""Inkling 2 Mini behind the server: its pre-tokenizer, its chat template, its blocks of reasoning, text and tool calls, +and its stops, effort and forced calls. + + python -m unittest serve.test_inkling + +The template is the model's own (serve/fixtures/inkling2_chat_template.jinja, the GGUF's tokenizer.chat_template and +thinkingmachines/Inkling-2-Mini's chat_template.jinja, SHA-256 53a9035f...). serve/fixtures/inkling2_golden.json +holds the token ids of 51 strings (53 cases) from Hugging Face's tokenizers on the model's tokenizer.json (the reference; +llama.cpp's where they differ are kept as "llama_cpp_ids", and the cases with control tokens read as text are +llama.cpp's), checked with the part of the vocabulary they use (serve/fixtures/inkling2_vocab_subset.json) and again +with the whole vocabulary from $STRATA_INKLING_TOKENIZER (a pack's tokenizer/ directory) when it is set; and llama.cpp +29b52d398b's rendered prompts and its parse of replies. +""" +import json +import os +import sys +import tempfile +import threading +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT)) + +import strata_tokenizer as ST # noqa: E402 +from serve.frontend import (ChatTemplate, InklingParser, anthropic_to_messages, forced_call, # noqa: E402 + openai_to_messages, parse_inkling_tool_call) +from serve.server import ByteTokenizer, MockEngine, Service, StrataEngine # noqa: E402 + +FIXTURES = Path(__file__).resolve().parent / "fixtures" +TEMPLATE = FIXTURES / "inkling2_chat_template.jinja" +GOLDEN = FIXTURES / "inkling2_golden.json" + + +class PreTokenizer(unittest.TestCase): + def pieces(self, text): + return ST.Tokenizer(["a"], [], pre="inkling2")._pieces(text) + + def test_words_are_cut_where_their_capitals_end(self): + self.assertEqual(self.pieces("HTTPServer and McDonald's"), ["HTTPServer", " and", " Mc", "Donald's"]) + self.assertEqual(self.pieces("HELLO hello HeLLo"), ["HELLO", " hello", " He", "LLo"]) + + def test_contractions_stay_on_the_word_in_either_case(self): + self.assertEqual(self.pieces("I'm sure they'LL"), ["I'm", " sure", " they'LL"]) + + def test_digits_go_in_threes_and_punctuation_keeps_line_breaks_and_slashes(self): + self.assertEqual(self.pieces("1234567"), ["123", "456", "7"]) + self.assertEqual(self.pieces("a.\n\nb"), ["a", ".\n\n", "b"]) + self.assertEqual(self.pieces("x =//\ny"), ["x", " =//\n", "y"]) + self.assertEqual(self.pieces("end.)/\n/next"), ["end", ".)/\n/", "next"]) # Flint's: ".)/\n", "/next" + self.assertEqual(self.pieces("a b\n\n c"), ["a", " ", " b", "\n\n", " ", " c"]) + + def test_a_letter_past_ascii_is_both_cases(self): + # llama.cpp matches the pattern on text where every such letter is one placeholder: "helloПривет" is one piece + self.assertEqual(self.pieces("helloПривет мир"), ["helloПривет", " мир"]) + self.assertEqual(self.pieces("naïve Café"), ["naïve", " Café"]) + self.assertEqual(self.pieces("abc中文def"), ["abc中文def"]) # no run of ideographs of its own + + def test_a_piece_that_is_a_token_is_that_token(self): + # tokenizer.json's ignore_merges (Hugging Face is the reference; llama.cpp 29b52d398b does not set it) + tok = ST.Tokenizer(["a", "b", "ab"], [], pre="inkling2") + self.assertTrue(tok.ignore_merges) + self.assertEqual(tok.encode("ab"), [2]) # "ab" is a token, though no merge makes it + + +def subset_tokenizer(): + """The vocabulary's tokens and merges that the golden strings use (serve/fixtures/inkling2_vocab_subset.json), at + their own ids; the other ids hold placeholders.""" + sub = json.loads((FIXTURES / "inkling2_vocab_subset.json").read_text(encoding="utf-8")) + tokens = [f"" for i in range(sub["n_tokens"])] + types = [1] * sub["n_tokens"] + for i, t in sub["tokens"].items(): + tokens[int(i)] = t + for i in sub["control"]: + types[i] = 3 + return ST.Tokenizer(tokens, sub["merges"], types, pre=sub["pre"], special_ids=sub["special_ids"]) + + +class ReferenceIds(unittest.TestCase): + """The reference ids of the golden strings, with and without parse_special (no download needed).""" + + def test_the_golden_strings(self): + tok = subset_tokenizer() + golden = json.loads(GOLDEN.read_text(encoding="utf-8")) + self.assertGreater(len(golden["tokens"]), 40) + for case in golden["tokens"]: + with self.subTest(case["name"]): + ids = tok.encode(case["text"], parse_special=case["parse_special"]) + self.assertEqual(ids, case["ids"]) + self.assertEqual(tok.decode(ids), case["text"]) + + def test_a_prompt_is_cut_at_the_control_tokens(self): + tok = subset_tokenizer() + ids = tok.encode("<|message_user|><|content_text|>Hi there<|end_message|><|message_model|>", parse_special=True) + self.assertEqual((ids[:2], ids[-2:]), ([200000, 200004], [200010, 200001])) + self.assertNotIn(200010, tok.encode("<|end_message|>")) # text unless parse_special + + def test_where_llama_cpp_differs(self): + # "kwargs" is one token that no chain of merges reaches: Hugging Face gives it whole, llama.cpp as three + tok = subset_tokenizer() + case = next(c for c in json.loads(GOLDEN.read_text(encoding="utf-8"))["tokens"] if "llama_cpp_ids" in c) + self.assertEqual(case["text"], "kwargs **kwargs") + self.assertEqual(tok.encode(case["text"]), [87550, 197033, 87550]) + self.assertEqual(case["llama_cpp_ids"], [86226, 70, 82, 197033, 86226, 70, 82]) + + +def real_tokenizer(): + path = os.environ.get("STRATA_INKLING_TOKENIZER") + return ST.Tokenizer.from_dir(path) if path and (Path(path) / "vocab.json").is_file() else None + + +@unittest.skipIf(real_tokenizer() is None, "no Inkling tokenizer here ($STRATA_INKLING_TOKENIZER)") +class RealVocabulary(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tok = real_tokenizer() + + def test_the_vocabulary_and_its_specials(self): + self.assertEqual(len(self.tok.tokens), 200058) + self.assertEqual(self.tok.pre, "inkling2") + self.assertEqual(self.tok.special_ids["tokenizer.ggml.eos_token_id"], 200006) + self.assertEqual(self.tok.special_ids["tokenizer.ggml.padding_token_id"], 199999) + self.assertNotIn("tokenizer.ggml.bos_token_id", self.tok.special_ids) + for text, i in (("<|message_model|>", 200001), ("<|content_model_end_sampling|>", 200006), + ("<|end_message|>", 200010), ("<|content_invoke_tool_json|>", 200049)): + self.assertEqual(self.tok.encode(text, parse_special=True), [i]) + self.assertNotEqual(self.tok.encode(text), [i]) # a control token: text unless parse_special + + def test_round_trips(self): + for text in ("", "Hello, world!", " leading and trailing ", "def f(x):\n\treturn x\n", "你好,世界", + "مرحبا", "\U0001f600\U0001f680\U0001f1fa\U0001f1f8", "é́", "\x00\x01\x7f", + " nbsp", "1234567890", "\r\n\r\n", "x" * 3000, "<|message_user|> as text"): + with self.subTest(text=text[:20]): + self.assertEqual(self.tok.decode(self.tok.encode(text)), text) + + def test_reference_token_ids(self): + golden = json.loads(GOLDEN.read_text(encoding="utf-8")) + for case in golden["tokens"]: + with self.subTest(case["name"]): + self.assertEqual(self.tok.encode(case["text"], parse_special=case.get("parse_special", True)), + case["ids"]) + + +class Template(unittest.TestCase): + TOOLS = [{"name": "get_weather", "description": "Get the weather", + "parameters": {"type": "object", "properties": {"city": {"type": "string"}, "days": {"type": "integer"}}, + "required": ["city"]}}] + + @classmethod + def setUpClass(cls): + cls.t = ChatTemplate(TEMPLATE) + + def test_a_user_message_and_the_default_effort(self): + self.assertEqual(self.t.render([{"role": "user", "content": "Hi"}]), + "<|message_system|><|content_text|>Thinking effort level: 0.9<|end_message|>" + "<|message_user|><|content_text|>Hi<|end_message|>") + + def test_the_effort_comes_after_the_system_prompt_and_reads_names_and_numbers(self): + msgs = [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "Hi"}] + for effort, shown in (("none", "0"), ("minimal", "0.1"), ("low", "0.2"), ("medium", "0.7"), ("high", "0.9"), + ("xhigh", "0.99"), ("max", "0.99"), (0.5, "0.5")): + with self.subTest(effort=effort): + self.assertEqual(self.t.render(msgs, reasoning_effort=effort), + "<|message_system|><|content_text|>Be brief.<|end_message|>" + f"<|message_system|><|content_text|>Thinking effort level: {shown}<|end_message|>" + "<|message_user|><|content_text|>Hi<|end_message|>") + + def test_tools_calls_and_answers(self): + msgs = [{"role": "user", "content": "Weather in Paris?"}, + {"role": "assistant", "content": "", "reasoning_content": "I need the tool.", + "tool_calls": [{"id": "c1", "function": {"name": "get_weather", "arguments": {"days": 2, "city": "Paris"}}}]}, + {"role": "tool", "tool_call_id": "c1", "content": "18 C"}, + {"role": "assistant", "content": "It is 18 C."}] + self.assertEqual(self.t.render(msgs, tools=self.TOOLS), + '<|message_system|>tool_declare<|content_xml|>[{"description":"Get the weather",' + '"name":"get_weather","parameters":{"properties":{"city":{"type":"string"},' + '"days":{"type":"integer"}},"required":["city"],"type":"object"},"type":"function"}]' + "<|end_message|>" + "<|message_system|><|content_text|>Thinking effort level: 0.9<|end_message|>" + "<|message_user|><|content_text|>Weather in Paris?<|end_message|>" + "<|message_model|><|content_thinking|>I need the tool.<|end_message|>" + '<|message_model|>get_weather<|content_invoke_tool_json|>{"name":"get_weather",' + '"args":{"city":"Paris","days":2}}<|end_message|><|content_model_end_sampling|>' + "<|message_tool|>get_weather<|content_text|>18 C<|end_message|>" + "<|message_model|><|content_text|>It is 18 C.<|end_message|><|content_model_end_sampling|>") + + def test_a_tool_in_openai_shape_renders_the_same(self): + flat = self.t.render([{"role": "user", "content": "x"}], tools=self.TOOLS) + wrapped = self.t.render([{"role": "user", "content": "x"}], + tools=[{"type": "function", "function": self.TOOLS[0]}]) + self.assertEqual(flat, wrapped) + + def test_the_server_reads_what_the_template_can_do(self): + self.assertEqual(self.t.caps, {"supports_tools": True, "supports_tool_calls": True, + "supports_system_role": True, "supports_parallel_tool_calls": True, + "supports_preserve_reasoning": True}) + + def test_llama_cpp_renders_the_same(self): + # llama.cpp's prompts for OpenAI requests, read the way the server reads them + golden = json.loads(GOLDEN.read_text(encoding="utf-8")) + self.assertGreater(len(golden["templates"]), 10) + for case in golden["templates"]: + with self.subTest(case["name"]): + messages, tools, _ = openai_to_messages(case["request"]) + self.assertEqual(self.t.render(messages, tools=tools, **case["kwargs"]), case["prompt"]) + + +H, THINK, TEXT, JSON_, END = ("<|message_model|>", "<|content_thinking|>", "<|content_text|>", + "<|content_invoke_tool_json|>", "<|end_message|>") + + +def events(text, step, tools=None, stream_tools=True, thinking=True): + p = InklingParser(thinking=thinking, tools=tools, stream_tools=stream_tools) + evs = [] + for i in range(0, len(text), step): + evs += p.feed(text[i:i + step]) + return evs + p.finish() + + +def joined(evs, kind): + return "".join(e.text for e in evs if e.kind == kind) + + +class Blocks(unittest.TestCase): + TOOLS = [{"name": "get_weather", "parameters": {"properties": {"city": {"type": "string"}}}}, + {"name": "now", "parameters": {"properties": {}}}] + STEPS = (1, 3, 7, 10_000) + + def test_reasoning_then_the_answer(self): + text = f"{H}{THINK}The user greets me.{END}{H}{TEXT}Hello! x{END}" + for step in self.STEPS: + with self.subTest(step=step): + evs = events(text, step) + self.assertEqual(joined(evs, "reasoning"), "The user greets me.") + self.assertEqual(joined(evs, "content"), "Hello! x") + + def test_an_answer_without_reasoning_and_blocks_one_after_another(self): + text = f"{H}{TEXT}One.{END}{H}{THINK}more{END}{H}{TEXT} Two.{END}" + for step in self.STEPS: + with self.subTest(step=step): + evs = events(text, step) + self.assertEqual(joined(evs, "content"), "One. Two.") + self.assertEqual(joined(evs, "reasoning"), "more") + + def test_thinking_off_still_reads_a_thinking_block_as_reasoning(self): + evs = events(f"{H}{THINK}brief{END}{H}{TEXT}ok{END}", 2, thinking=False) + self.assertEqual((joined(evs, "reasoning"), joined(evs, "content")), ("brief", "ok")) + + def test_tool_calls_however_they_arrive(self): + text = (f"{H}{THINK}Need weather.{END}{H}get_weather{JSON_}" + '{"name":"get_weather","args":{"city":"Paris <|x|>"}}' f"{END}{H}now{JSON_}" '{"name":"now","args":{}}' + f"{END}") + for stream_tools in (False, True): + for step in self.STEPS: + with self.subTest(stream_tools=stream_tools, step=step): + evs = events(text, step, self.TOOLS, stream_tools) + calls = [(e.call.name, e.call.arguments) for e in evs if e.kind == "tool_call"] + self.assertEqual(calls, [("get_weather", {"city": "Paris <|x|>"}), ("now", {})]) + self.assertEqual(joined(evs, "reasoning"), "Need weather.") + self.assertEqual(joined(evs, "content"), "") + + def test_a_streamed_call_is_announced_and_keeps_its_id(self): + text = f"{H}get_weather{JSON_}" '{"name":"get_weather","args":{"city":"Oslo"}}' f"{END}" + evs = [e for e in events(text, 1, self.TOOLS) if e.kind.startswith("tool_")] + self.assertEqual([e.kind for e in evs], ["tool_start", "tool_args", "tool_call"]) + self.assertEqual(evs[0].call.id, evs[2].call.id) + self.assertEqual(json.loads(evs[1].text), {"city": "Oslo"}) + + def test_a_call_to_a_tool_not_declared_is_text(self): + text = f"{H}rm_rf{JSON_}" '{"name":"rm_rf","args":{}}' f"{END}" + for tools in (None, self.TOOLS): + with self.subTest(tools=bool(tools)): + evs = events(text, 4, tools) + self.assertFalse([e for e in evs if e.kind.startswith("tool_")]) + self.assertIn("rm_rf", joined(evs, "content")) + + def test_a_call_whose_end_did_not_come(self): + whole = f"{H}now{JSON_}" '{"name":"now","args":{}}' + evs = events(whole, 5, self.TOOLS) # its JSON is whole: the call + self.assertEqual([(e.call.name, e.call.arguments) for e in evs if e.kind == "tool_call"], [("now", {})]) + cut = f"{H}get_weather{JSON_}" '{"name":"get_weather","args":{"ci' + evs = events(cut, 5, self.TOOLS) # announced and cut: no call (as OutputParser, #211) + self.assertEqual([e.kind for e in evs if e.kind.startswith("tool_")], ["tool_start"]) + evs = events(cut, 5, self.TOOLS, stream_tools=False) # not announced: the text it is + self.assertFalse([e for e in evs if e.kind.startswith("tool_")]) + self.assertIn('"args":{"ci', joined(evs, "content")) + + def test_a_call_whose_end_tag_did_not_come_before_the_next_block(self): + # the JSON is whole and the next block's header follows it: the call ends there, the block after it is read + for step in (1, 4, 1000): + with self.subTest(step=step): + evs = events(f"{H}now{JSON_}" '{"name":"now","args":{}}' f"{H}{TEXT}Done.{END}", step, self.TOOLS) + self.assertEqual([(e.call.name, e.call.arguments) for e in evs if e.kind == "tool_call"], + [("now", {})]) + self.assertEqual(joined(evs, "content"), "Done.") + + def test_stray_markers_are_not_shown(self): + evs = events(f"{H}{TEXT}Hi{END}<|content_model_end_sampling|>", 1) + self.assertEqual(joined(evs, "content"), "Hi") + evs = events(f"{H}{TEXT}Hi", 1) # cut before its end: what came + self.assertEqual(joined(evs, "content"), "Hi") + + def test_a_block_without_its_content_token_is_text(self): + evs = events(f"{H}Plain answer.\nSecond line{END}", 3) + self.assertEqual(joined(evs, "content"), "Plain answer.\nSecond line") + + def test_the_parser_states_the_server_reads(self): + p = InklingParser(tools=self.TOOLS) + self.assertEqual((p.state, p.buf), ("content", "")) + p.feed(H) + self.assertNotEqual(p.buf, "") # the header is held: no forced call written here + p.feed(THINK + "x") + self.assertEqual(p.state, "reasoning") + p.feed(END) + self.assertEqual((p.state, p.buf), ("content", "")) # between blocks: a forced call goes here + p.feed(H + TEXT + "y") + self.assertEqual(p.state, "text") # not inside a text block + self.assertEqual(p.think_end, END) + + def test_llama_cpp_reads_the_same(self): + # llama.cpp's parse of the replies in its own test-chat.cpp cases for Inkling 2, and a few more + golden = json.loads(GOLDEN.read_text(encoding="utf-8")) + self.assertGreater(len(golden["replies"]), 10) + for case in golden["replies"]: + for step in (1, 5, 10_000): + with self.subTest(case["name"], step=step): + evs = events(case["text"], step, case["tools"] or None) + self.assertEqual(joined(evs, "content"), case["content"]) + self.assertEqual(joined(evs, "reasoning"), case["reasoning"]) + self.assertEqual([{"name": e.call.name, "arguments": e.call.arguments} + for e in evs if e.kind == "tool_call"], case["calls"]) + + def test_the_block_closer_inside_a_string_argument_does_not_end_the_call(self): + text = f"{H}python{JSON_}" '{"name":"python","args":{"code":"print(\'<|end_message|>\')"}}' f"{END}{H}{TEXT}ok{END}" + tools = [{"name": "python", "parameters": {"properties": {"code": {"type": "string"}}}}] + for step in (1, 4, 10_000): + with self.subTest(step=step): + evs = events(text, step, tools) + self.assertEqual([e.call.arguments for e in evs if e.kind == "tool_call"], + [{"code": "print('<|end_message|>')"}]) + self.assertEqual(joined(evs, "content"), "ok") + # JSON that never closes ends where the next block opens + evs = events(f'{H}python{JSON_}{{"name":"python","args":{{"code":"x{END}{H}{TEXT}after{END}', 3, tools) + self.assertEqual(joined(evs, "content").count("after"), 1) + self.assertFalse([e for e in evs if e.kind == "tool_call"]) + + def test_parse_inkling_tool_call(self): + self.assertEqual(parse_inkling_tool_call("f", '{"name":"f","args":{"a":1}}').arguments, {"a": 1}) + self.assertEqual(parse_inkling_tool_call("f", '{"name": "f", "arguments": "{\\"a\\": 1}"}').arguments, {"a": 1}) + self.assertEqual(parse_inkling_tool_call("f", '{"a": 1}').arguments, {"a": 1}) + self.assertEqual(parse_inkling_tool_call("f", '{"name":"f"}').arguments, {}) # no arguments + self.assertEqual(parse_inkling_tool_call("f", '{"name":"f","a":1}').arguments, {"a": 1}) + self.assertEqual(parse_inkling_tool_call("f", '{"name":"x"}').arguments, {"name": "x"}) # a "name" argument + for body in ('{"name":"f","args":[1]}', "{", "[]"): + self.assertIsNone(parse_inkling_tool_call("f", body)) + + +class InklingTokens(ByteTokenizer): + SPECIALS = ["<|endoftext|>", "<|message_user|>", "<|message_model|>", "<|message_system|>", "<|message_tool|>", + "<|content_text|>", "<|content_image|>", "<|content_model_end_sampling|>", "<|content_thinking|>", + "<|end_message|>", "<|content_xml|>", "<|content_invoke_tool_json|>"] + pre = "inkling2" + special_ids = {"tokenizer.ggml.eos_token_id": 263, "tokenizer.ggml.eot_token_id": 263, + "tokenizer.ggml.padding_token_id": 256} + + +class ServiceForInkling(unittest.TestCase): + TOOLS = [{"type": "function", "function": {"name": "get_weather", + "parameters": {"properties": {"city": {"type": "string"}}}}}] + + def setUp(self): + self.tok = InklingTokens() + self.svc = Service(MockEngine(self.tok, "hi"), self.tok, ChatTemplate(TEMPLATE)) + + def prompt(self, req): + return self.svc.render_prompt(*openai_to_messages(req)) + + def test_call_format_stops_and_turns(self): + self.assertEqual(self.svc.call_format, "inkling") + # llama.cpp's end of generation: the eos <|content_model_end_sampling|> and <|endoftext|> + self.assertEqual(self.svc.stop_ids, {263, 256}) + self.assertEqual(self.svc.engine.eos_ids, frozenset({263})) # the engine's own: the GGUF's eos and eot + self.assertEqual(self.svc.turn_ids, frozenset({257, 258, 259, 260})) + + def test_the_effort_a_client_asks_for(self): + user = [{"role": "user", "content": "Hi"}] + for req, shown in (({}, "0.9"), ({"reasoning_effort": "low"}, "0.2"), ({"reasoning_effort": "medium"}, "0.7"), + ({"reasoning_effort": "high"}, "0.9"), ({"reasoning_effort": "none"}, "0"), + ({"chat_template_kwargs": {"enable_thinking": False}}, "0")): + with self.subTest(req=req): + self.assertEqual(self.prompt({"messages": user, **req}), + f"<|message_system|><|content_text|>Thinking effort level: {shown}<|end_message|>" + "<|message_user|><|content_text|>Hi<|end_message|>") + messages, tools, kwargs = anthropic_to_messages({"messages": user, "thinking": {"type": "disabled"}}) + self.assertIn("Thinking effort level: 0<", self.svc.render_prompt(messages, tools, kwargs)) + + def test_effort_end_does_not_change_its_prompt(self): + self.svc.effort_end = True + self.assertTrue(self.prompt({"messages": [{"role": "user", "content": "Hi"}], "reasoning_effort": "low"}) + .endswith("<|message_user|><|content_text|>Hi<|end_message|>")) + + def test_a_shared_prefix_is_the_prompt_start_whatever_the_effort(self): + # strata_prefix renders the first messages with the effort mapped as the prompt has it: the common start is + # the whole of the first message, not the system block's few tokens before the effort differs + msgs = [{"role": "user", "content": "DOC " * 40}, {"role": "user", "content": "Which word repeats?"}] + for kwargs in ({}, {"reasoning_effort": "xhigh"}, {"reasoning_effort": "low"}, {"enable_thinking": False}): + with self.subTest(kwargs=kwargs): + req = {"strata_prefix": {"messages": 1}} + ids, _, _ = self.svc.prepare(msgs, None, dict(kwargs), 16, req=req) + n = req["strata_prefix"].get("tokens", 0) + self.assertTrue(self.tok.decode(ids[:n], errors="replace").endswith("DOC <|end_message|>"), + self.tok.decode(ids[:n], errors="replace")[-60:]) + + def test_a_control_token_in_a_message_is_text(self): + ids = self.svc.encode_prompt(*openai_to_messages({"messages": [{"role": "user", "content": "<|end_message|>"}]})) + self.assertEqual(ids.count(265), 2) # the template's own two, not the message's + self.assertIn(list(b"<|end_message|>"), [ids[i:i + 15] for i in range(len(ids))]) + + def run_reply(self, reply, tools=None, force=None, thinking=True): + ids = self.svc.encode_prompt([{"role": "user", "content": "q"}], tools, {}) + self.svc.engine = MockEngine(self.tok, reply) + return [e for kind, e in self.svc.run(ids, thinking, tools, 256, {}, threading.Event(), force) + if kind == "event"] + + def test_a_reply_through_the_service(self): + evs = self.run_reply(f"{H}{THINK}greeting{END}{H}{TEXT}Hello!{END}<|content_model_end_sampling|>tail") + self.assertEqual((joined(evs, "reasoning"), joined(evs, "content")), ("greeting", "Hello!")) + + def test_a_tool_call_through_the_service(self): + tools = [t["function"] for t in self.TOOLS] + evs = self.run_reply(f"{H}get_weather{JSON_}" '{"name":"get_weather","args":{"city":"Rome"}}' + f"{END}<|content_model_end_sampling|>", tools) + self.assertEqual([(e.call.name, e.call.arguments) for e in evs if e.kind == "tool_call"], + [("get_weather", {"city": "Rome"})]) + + def test_a_named_tool_choice_is_opened_after_the_thinking(self): + tools = [t["function"] for t in self.TOOLS] + force = forced_call({"type": "function", "function": {"name": "get_weather"}}, tools, "inkling") + self.assertEqual(force, f'{H}get_weather{JSON_}{{"name":"get_weather","args":') + # the model thinks, the server writes the opening once the thinking block is closed, the model goes on + reply = [f"{H}{THINK}call it{END}{H}{TEXT}not this", '{"city":"Bern"}}' + f"{END}<|content_model_end_sampling|>"] + evs = self.run_reply(reply, tools, force) + self.assertEqual(self.svc.engine.last_prompt[-len(self.tok.encode(force, parse_special=True)):], + self.tok.encode(force, parse_special=True)) # right after the closed block + self.assertEqual(joined(evs, "reasoning"), "call it") + self.assertEqual([(e.call.name, e.call.arguments) for e in evs if e.kind == "tool_call"], + [("get_weather", {"city": "Bern"})]) + + def test_the_reply_ends_after_a_forced_call(self): + # without thinking the prompt ends with the opening; the model finishes the call, then writes blocks of its + # own (a thinking block, an answer): the reply ends where the first of them opens + tools = [t["function"] for t in self.TOOLS] + force = forced_call({"type": "function", "function": {"name": "get_weather"}}, tools, "inkling") + evs = self.run_reply('{"city":"Bern"}}' f"{END}{H}{THINK}why{END}{H}{TEXT}a joke{END}", tools, force, + thinking=False) + self.assertEqual([(e.call.name, e.call.arguments) for e in evs if e.kind == "tool_call"], + [("get_weather", {"city": "Bern"})]) + self.assertEqual((joined(evs, "reasoning"), joined(evs, "content")), ("", "")) + + def test_required_among_several_tools_is_left_to_the_model(self): + tools = [{"name": "a"}, {"name": "b"}] + self.assertIsNone(forced_call("required", tools, "inkling")) + self.assertTrue(forced_call("required", [{"name": "a"}], "inkling").startswith(H + "a" + JSON_)) + self.assertEqual(forced_call("required", tools), "\n<|unused_200054|> in a block of its own, and + the server puts one <|unused_200054|> a row of the picture there, as llama.cpp 29b52d398b's mtmd feeds it + (<|message_user|><|content_image|>[rows]<|end_message|>; its img_beg is <|content_image|>, it writes no end).""" + + class FakeVision: + def __init__(self, d, n=(3, 2)): + self.n, self.seen = list(n), {} + self.dir = Path(d) + self.rows = self.dir / "img.sve" + self.rows.write_bytes(b"rows") + + def encode(self, source): # a picture encoded once is the cache's (a tool's is encoded before) + if source not in self.seen: + self.seen[source] = self.n.pop(0) + return self.rows, self.seen[source] + + def service(self, d, n=(3, 2)): + class Asked(MockEngine): + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.asked = (StrataEngine.sampling_keys(sampling), embeddings) + yield from super().generate(ids, max_new, sampling, cancel, embeddings) + + tok = subset_tokenizer() + return Service(Asked(tok, "a cat"), tok, ChatTemplate(TEMPLATE), vision=self.FakeVision(d, n)) + + def test_the_rows_go_where_the_template_put_the_picture(self): + with tempfile.TemporaryDirectory() as d: + svc = self.service(d) + self.assertEqual(svc.image_marks, ("<|unused_200054|>", "<|content_image|>", None)) + msgs = [{"role": "user", "content": [{"type": "image", "source": "a.png"}, + {"type": "text", "text": "Hi there"}, + {"type": "image", "source": "b.png"}]}] + ids, _, _ = svc.prepare(msgs, None, {}) + at = ids.index(200005) + self.assertEqual(ids[at - 1:at + 7], [200000, 200005, 200054, 200054, 200054, 200010, 200000, 200004]) + at = ids.index(200005, at + 1) + self.assertEqual(ids[at - 1:at + 4], [200000, 200005, 200054, 200054, 200010]) + self.assertEqual((ids.count(200054), svc.embeddings.pad), (5, 200054)) + # the engine is told which token stands for a picture's rows + rows = svc.embeddings.path + list(svc.run(ids, False, None, 8, {}, threading.Event())) + self.assertEqual(svc.engine.asked, (" image_pad=200054", rows)) + + def test_two_pictures_back_to_back(self): + with tempfile.TemporaryDirectory() as d: + svc = self.service(d, (2, 3)) + msgs = [{"role": "user", "content": [{"type": "image", "source": "a.png"}, + {"type": "image", "source": "b.png"}]}] + ids, _, _ = svc.prepare(msgs, None, {}) + at = ids.index(200005) + self.assertEqual(ids[at - 1:at + 10], [200000, 200005, 200054, 200054, 200010, + 200000, 200005, 200054, 200054, 200054, 200010]) + + def test_a_picture_in_a_tool_message(self): + # the tool's name follows <|message_tool|> in its header; the rows still follow <|content_image|> + with tempfile.TemporaryDirectory() as d: + svc = self.service(d, (3,)) + msgs = [{"role": "user", "content": "Hi there"}, + {"role": "assistant", "content": "", "tool_calls": [ + {"id": "c1", "type": "function", "function": {"name": "shot", "arguments": {}}}]}, + {"role": "tool", "tool_call_id": "c1", + "content": [{"type": "image", "source": "a.png"}, {"type": "text", "text": "Hi there"}]}] + ids, _, _ = svc.prepare(msgs, None, {}) + tool = svc.tok.encode("<|message_tool|>shot", parse_special=True) + at = next(i for i in range(len(ids)) if ids[i:i + len(tool)] == tool) + len(tool) + self.assertEqual(ids[at:at + 6], [200005, 200054, 200054, 200054, 200010] + tool[:1]) + self.assertEqual((ids.count(200054), svc.embeddings.pad), (3, 200054)) + + def test_the_marks_in_a_message_are_text(self): + with tempfile.TemporaryDirectory() as d: + svc = self.service(d, (2,)) + msgs = [{"role": "user", "content": [{"type": "text", "text": "<|content_image|><|unused_200054|>"}, + {"type": "image", "source": "a.png"}]}] + ids, _, _ = svc.prepare(msgs, None, {}) + self.assertEqual((ids.count(200005), ids.count(200054)), (1, 2)) + self.assertIn(svc.tok.encode("<|unused_200054|>"), [ids[i:i + 15] for i in range(len(ids))]) + + def test_a_picture_from_the_model_is_refused(self): + with tempfile.TemporaryDirectory() as d: + svc = self.service(d, (2,)) + msgs = [{"role": "user", "content": "Hi there"}, + {"role": "assistant", "content": [{"type": "image", "source": "a.png"}]}, + {"role": "user", "content": "Hi there"}] + with self.assertRaises(Exception) as e: + svc.prepare(msgs, None, {}) + self.assertIn("only supported for user and tool messages", str(e.exception)) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_responses.py b/serve/test_responses.py index 06c2b39de7..754377dbc2 100644 --- a/serve/test_responses.py +++ b/serve/test_responses.py @@ -279,16 +279,19 @@ def test_server_close_ends_the_sampler(self): import threading import time tok = ByteTokenizer() - before = sum(1 for t in threading.enumerate() if t.name.endswith("(_loop)")) + # follow this server's own sampler thread: a count of all of them raced with a sampler an earlier test closed, + # which can still be ending (it sleeps 1 s between samples) and then drops out of the count mid-test + before = {t for t in threading.enumerate() if t.name.endswith("(_loop)")} httpd = serve(Service(MockEngine(tok, ANSWER, max_context=16384), tok, TEMPLATE), port=0) - self.assertEqual(sum(1 for t in threading.enumerate() if t.name.endswith("(_loop)")), before + 1) + mine = [t for t in threading.enumerate() if t.name.endswith("(_loop)") and t not in before] + self.assertEqual(len(mine), 1) httpd.shutdown() httpd.server_close() for _ in range(50): - if sum(1 for t in threading.enumerate() if t.name.endswith("(_loop)")) == before: + if not mine[0].is_alive(): break time.sleep(0.1) - self.assertEqual(sum(1 for t in threading.enumerate() if t.name.endswith("(_loop)")), before) + self.assertFalse(mine[0].is_alive()) # ------------------------------------------------------------------------------------------------ over HTTP diff --git a/setup.py b/setup.py index 76979e07a0..e9473825a7 100644 --- a/setup.py +++ b/setup.py @@ -94,6 +94,8 @@ "IsValorum/Clover-35B-A3B-Preview-APEX-I-NanoPlus-V2.1-GGUF": "d22b8db8efc6dfe15df84264e2fae26fafe530bb", # 2026-10-28 "Diffuspace/Clover-35B-A3B-Preview": "4b0402b65e523d0183a14c431955438714cb16ff", # 2026-10-28 "unsloth/Ornith-1.5-122B-GGUF": "3842d003341507c216295c6f28dfcd30349925c6", # 2026-10-20 + "ggml-org/Inkling-2-Mini-GGUF": "db61c5b492a6a034d986328d28274af0a439aa6c", # 2026-11-20 + "unsloth/Inkling-2-Mini-GGUF": "ae9327c5fbc7333116ba32eee78bb5d2bbefae4f", # 2026-11-21 "ornith-ai/Ornith-1.5-122B": "dfa07bab90e90746ffbfc0b0cba3126eb9265de2", # 2026-10-20 } @@ -196,6 +198,10 @@ def ms_meta(repo: str, path: str): # the Strata project's pin until it moves; only strata-vision builds from this one (a second checkout, like #14 suggests). VISION_LLAMA_CPP_COMMIT = "69f201a2051ea9b9e9b50c3cc56afd9e2ae64414" VISION_LLAMA_CPP_ZIP = f"https://github.com/ggml-org/llama.cpp/archive/{VISION_LLAMA_CPP_COMMIT}.zip" +# Inkling 2 Mini's image encoder (mtmd's inkling2v projector, and the inkling2 tokenizer strata-vision opens the text +# file with) is newer than VISION_LLAMA_CPP_COMMIT: a third checkout, for that family's encoder only ("vision_llama"), +# built into a folder of its own (build_vision_own), so the other families' encoder stays on its pin. +INKLING_VISION_LLAMA_CPP_COMMIT = "29b52d398b294509746ec0a3f28948a3107c0213" # The ready-made engine: , a zip with strata(.exe), strata-vision(.exe) and BUILD.json, built # by tools/make_release.py. Set this to the GitHub release download folder when publishing, e.g. @@ -863,6 +869,70 @@ def ms_meta(repo: str, path: str): (32785752352, "43bdc1b0cb764b5531d320816fb6004245256a414bfd55f1fdb69e3db42eaa57"), "mmproj-F16.gguf": (908724544, "39db176176a904b101f5173a4f03e785990f9279f94ab373c4fd629ae7011817")}}, + # Inkling 2 Mini (llama.cpp's inkling2_loop, ggml-org/llama.cpp 29b52d398b): Thinking Machines' looped mixture of + # experts, 24 layers whose layers 6 to 17 run three times a token, 128 experts with 8 used. ggml-org's GGUFs. + # Images are opt-in ("vision"; the question's default is no): ggml-org's Q8_0 mmproj, read by strata-vision built + # from llama.cpp 29b52d398b ("vision_llama", build_vision_own) into engine-poly/vision-inkling/, apart from the + # other families' encoder. "vision_vram_gb": 576 MiB for the encoder's process after its warm-up at 1,024 tokens + # (RTX 2070 Super, flash attention on; 904 MiB with the BF16 mmproj, 1,584 MiB with flash attention off); the + # engine held 908 instead of 1,038 routed experts in VRAM beside it there. Q8_0 rather than BF16: half the + # download, less VRAM, faster (256 rows: 2.1 s against 3.3 s on 6 CPU threads, 63 against 131 ms on the GPU), and + # the engine's prompt logits with either one's rows were as close to llama.cpp's (cosine 0.99989 or more, the same + # greedy tokens, 2 pictures). + # Offered on NVIDIA cards only ("cuda_only"; "cuda_only_why" is the reason setup gives): the engine builds and runs + # it on AMD cards with HIP too (an RX 9070 XT with ROCm 7.2.4, an RX 9060 XT), but its prompt speed there is not + # tuned yet, so setup does not offer it there. + # On Windows it ran for one user (an earlier build, MSVC, an RTX 4060 Laptop) but is not re-checked there each + # round, so setup still asks first (docs/models/inkling.md, "What you need"). Several cards split its + # layers as the other families' (the loop's twelve on one card); "parallel" (--batch) as for them too; its attention + # caches are fp16 or q8_0 (POLY_KV). Measured on an RTX 2070 Super 8 GB with 62 GB of RAM (IQ4_NL): about 3.1 GiB + # of VRAM beside the experts at 8K in fp16, so "vram_beside_gb" 4.0 at 32K (the rows of the 8 full-attention passes: + # "row_bytes", 32 KiB a token in fp16, 17 KiB in q8_0; the 40 window passes' rings are fixed, ~0.3 GiB fp16, ~0.17 + # GiB q8_0); the engine's resident memory was 16.5 GiB. "laptop_tps": 28 tokens/s after a 34.8K-token prompt, + # measured with q8_0 caches in a 128K context. "arena_gb" is the files' expert tensors (IQ4_NL: layers 0-19 IQ4_NL, + # 20-23 Q8_0). The experts the card does not hold stay in RAM, as for the others. "sampling": the GGUF's + # general.sampling.* (temperature 1.0, top_k 50, top_p 1.0, min_p 0), written into a run config that has no sampling + # block of its own. "dspark": the model's own drafter (Unsloth's DSpark file, --draft-model), opt-in, offered only + # where the card holds every expert of the size beside it (poly_dspark_offer()), and not with several cards or + # "parallel". It guesses up to three tokens a round and the model checks them in one window: measured on a rented + # RTX 3090 24 GB (every expert in VRAM) it wrote code faster and prose about as fast (docs/models/inkling.md); on + # a rented RTX 2070 Super 8 GB (31% of IQ4_NL's experts in VRAM, 68% of UD-Q2_K_XL's) it was slower or no faster, + # as a window's tokens route to experts of their own on the CPU. "vram_gb": the expert cache was 0.4 GiB smaller + # with it at load there (both sizes, a 1,024-token prompt batch: its weights, scratch and window layers' rings); + # "row_bytes": its full-attention layer's fp16 keys and values, 4 KiB a context token. + "inkling": {"title": "Inkling 2 Mini", "by": "Thinking Machines; GGUF by ggml-org", + "about": "on the strata-poly engine: NVIDIA, Linux; an 18 GB file, ~22 GB of RAM beside an " + "8 GB card (16.5 GiB measured for the engine); a 2-bit and an 8-bit size too, images optional", + "hf": hf("ggml-org/Inkling-2-Mini-GGUF"), "file": "Inkling-2-Mini-{q}.gguf", "shards": 1, + "tag": "inkling2-", "name": "inkling-2-mini", "engine": "poly", "vision": True, + "vision_llama": INKLING_VISION_LLAMA_CPP_COMMIT, "mmproj_hf": hf("ggml-org/Inkling-2-Mini-GGUF"), + "mmproj": "mmproj-Inkling-2-Mini-Q8_0.gguf", "vision_gb": 0.35, "vision_vram_gb": 0.6, + "experimental": True, "windows": False, "cuda_only": True, "ran_on_gb": 8, "row_bytes": 32768, + "cuda_only_why": "its prompt speed on AMD cards is not tuned yet", + "laptop_tps": {32768: "28"}, + "windows_risk": "Inkling 2 Mini ran on Windows for one user on an earlier build, but it is not re-checked there", + "sampling": {"temperature": 1.0, "top_k": 50, "top_p": 1.0}, + "dspark": {"hf": hf("unsloth/Inkling-2-Mini-GGUF"), "file": "dspark-Inkling-2-Mini-Q8_0.gguf", + "gb": 0.4, "vram_gb": 0.4, "row_bytes": 4096}, + "models": {"IQ4_NL": {"about": "4-bit experts in layers 0-19 (imatrix), 8-bit everywhere else", + "download_gb": 17.6, "ram_gb": 22, "arena_gb": 15.8, "vram_beside_gb": 4.0}, + "UD-Q2_K_XL": {"about": "Unsloth's 2-bit experts, higher where it matters: the fastest and " + "the least RAM (9 GB measured), a little less accurate", + "download_gb": 9.1, "ram_gb": 14, "arena_gb": 8.4, "vram_beside_gb": 4.0, + "hf": hf("unsloth/Inkling-2-Mini-GGUF"), + "mmproj_hf": hf("ggml-org/Inkling-2-Mini-GGUF")}, + "Q8_0": {"about": "8-bit throughout: the closest to the model as trained", + "download_gb": 27.8, "ram_gb": 32, "arena_gb": 26.0, "vram_beside_gb": 4.0}}, + "sha256": {"Inkling-2-Mini-IQ4_NL.gguf": + (17627940768, "cbdf3fa9dc50a4124977980f37da4f1fa764b0cfe800d275cd43d26ce2a81af4"), + "Inkling-2-Mini-UD-Q2_K_XL.gguf": + (9138715328, "20292e8142b69535ca88a5d04439d0fdeb4dc698d44c002dca706dcf92901441"), + "Inkling-2-Mini-Q8_0.gguf": + (27820099264, "d57542f8aea5d7639beba5fc4ae7f584754916f63ac5d5a69328c27f652f45da"), + "mmproj-Inkling-2-Mini-Q8_0.gguf": + (345910944, "233287272ec5ac39b4168677aba54a4c024f202410f5629fac1830e1059f8abb"), + "dspark-Inkling-2-Mini-Q8_0.gguf": + (402278560, "2ec78510da837e8fc3be54a14757a0c5fbd2d8d9e85a0d92853fafdf674f3773")}}, } MMPROJ = "mmproj-Qwen3.8-Flash-Next-BF16.gguf" # Qwen3.6-35B-A3B (GGUF architecture qwen35moe), Unsloth's GGUFs with the MTP block: a family with an engine path of its @@ -2390,7 +2460,8 @@ def verify_sha256(s: Path, size: int, sha: str, own: bool = False) -> None: # general.architecture of each strata-poly family's GGUFs, the name Engine::open() (src/poly/engine.cpp) picks its # code by; the families not listed are qwen35moe POLY_GGUF_ARCHS = {"glm": ("glm5-next", "glm5next"), "deepseek": ("deepseek4",), "lfm25": ("lfm2moe",), - "gemma4": ("gemma4",), "flint": ("flint",), "kolibri": ("kolibri1",), "clover": ("clover_moe",)} + "gemma4": ("gemma4",), "flint": ("flint",), "kolibri": ("kolibri1",), "clover": ("clover_moe",), + "inkling": ("inkling2_loop", "inkling2")} def gguf_arch(s: Path) -> str: @@ -2635,17 +2706,23 @@ def check_shards(shards): f"delete {s.name} and its .done mark and run setup again") -def get_llama_cpp(vision=False): +def get_llama_cpp(vision=False, commit: str | None = None): """llama.cpp at the pinned commit (ggml for the build, gguf-py for the tools, mtmd for images), as a zip: no git. - `vision`: the image encoder's own newer checkout (VISION_LLAMA_CPP_COMMIT); the engines never use it.""" - if vision and VISION_LLAMA_CPP_COMMIT == LLAMA_CPP_COMMIT: - vision = False - commit = VISION_LLAMA_CPP_COMMIT if vision else LLAMA_CPP_COMMIT + `vision`: the image encoder's own newer checkout (VISION_LLAMA_CPP_COMMIT); the engines never use it. + `commit`: that checkout instead, for a family's own encoder ("vision_llama", build_vision_own).""" + if commit is not None: + vision = commit != LLAMA_CPP_COMMIT + url = f"https://github.com/ggml-org/llama.cpp/archive/{commit}.zip" if vision else LLAMA_CPP_ZIP + else: + if vision and VISION_LLAMA_CPP_COMMIT == LLAMA_CPP_COMMIT: + vision = False + commit = VISION_LLAMA_CPP_COMMIT if vision else LLAMA_CPP_COMMIT + url = VISION_LLAMA_CPP_ZIP if vision else LLAMA_CPP_ZIP llama = ROOT / "third_party" / (f"llama.cpp-{commit[:7]}" if vision else "llama.cpp") if (llama / "ggml" / "CMakeLists.txt").exists() and (llama / "gguf-py").is_dir(): return llama z = ROOT / "third_party" / f"llama.cpp-{commit[:7]}.zip" - download(VISION_LLAMA_CPP_ZIP if vision else LLAMA_CPP_ZIP, z, "llama.cpp source") + download(url, z, "llama.cpp source") tmp = ROOT / "third_party" / "_unpack" shutil.rmtree(tmp, ignore_errors=True) try: @@ -3026,8 +3103,9 @@ def unsloth_default_env(family: str, model: str, hip: bool, in_budget: bool) -> def menu_families(hip: bool) -> list: """The families the model menu lists, in menu order. The NVFP4 packs run on NVIDIA cards only (the AMD and Intel - engines have no NVFP4 kernels), so on those the menu does not offer them; `--family nvfp4` still says why not.""" - return [f for f in FAMILIES if not (hip and FAMILIES[f].get("ready"))] + engines have no NVFP4 kernels), so on those the menu does not offer them; `--family nvfp4` still says why not. + A family marked "cuda_only" (Inkling 2 Mini) is left out there too.""" + return [f for f in FAMILIES if not (hip and (FAMILIES[f].get("ready") or FAMILIES[f].get("cuda_only")))] def nvfp4_card_note(gpu) -> str: @@ -5496,6 +5574,15 @@ def write_setup_config(cfg_path: Path, cfg: dict, source: Path | None = None) -> if dropped else "")) +def config_has(path, key: str) -> bool: + """Whether the run config at `path` (None: none) is a JSON object with `key`.""" + try: + cfg = json.loads(Path(path).read_text(encoding="utf-8-sig")) if path is not None else None + except (OSError, ValueError): + return False + return isinstance(cfg, dict) and key in cfg + + def readable_config(path: Path) -> bool: """#459: a config that parses as a JSON object; any other gets a one-line warning naming it.""" text = None @@ -6456,6 +6543,17 @@ def poly_held_gb(d, vram_gb) -> float: return min(d["arena_gb"], max(0.0, vram_gb - poly_beside_gb(d)) * 1.073741824) +def poly_dspark_gb(spark, ctx=32768) -> float: + """The GiB of VRAM the DSpark drafter takes at a context of ctx tokens (FAMILIES["inkling"]["dspark"]).""" + return spark["vram_gb"] + ctx * spark["row_bytes"] / 2**30 + + +def poly_dspark_offer(fam, d, vram_gb) -> bool: + """Whether setup offers a size's DSpark drafter: where the card holds every expert of the size beside it at a 32K + context, which is where it was measured to pay (FAMILIES["inkling"]).""" + return poly_held_gb(d, vram_gb - poly_dspark_gb(fam["dspark"])) >= d["arena_gb"] + + def poly_parallel_note(asked: int | None, d, vram_gb) -> list[str]: """What setup says of "parallel" for a strata-poly size: answers written together pay where the card holds every expert of the size. Where most of them run on the CPU, different requests route to different experts and the @@ -6526,7 +6624,7 @@ def poly_verdict(d, ram, vram_gb, hip, windows=False) -> str: # --kv for a model of strata-poly (docs/Q8_KV.md): the formats its architecture's attention caches have beside # fp16, the default. The other engine's own are STRATA_KV. -POLY_KV = {"q8_0": ("qwen36", "ornith", "ornith122", "tiel", "minicpmv", "kolibri", "flint", "lfm25"), +POLY_KV = {"q8_0": ("qwen36", "ornith", "ornith122", "tiel", "minicpmv", "kolibri", "flint", "lfm25", "inkling"), "int8": ("gemma4",), "int8k": ("gemma4",)} STRATA_KV = ("int8", "q4_0", "k8v4") @@ -6697,6 +6795,63 @@ def build_engine_poly(gpu, yes, llama, vision="none", toolkit=13, portable=False return eng +def vision_own_dir(family: str) -> Path: + """The folder of a family's own image encoder (a family with "vision_llama"): beside strata-poly, apart from the + encoder the other families share (engine-poly/strata-vision), with a BUILD.json of its own.""" + return ROOT / ENGINE_POLY_DIR / f"vision-{family}" + + +def vision_own_ok(family, cards, vision, toolkit=13, portable=False) -> bool: + """Whether the family's own encoder there is of this source, commit and portability, and on the device asked: one + built with CUDA (for these cards, with this toolkit) also runs on the CPU; one built without it, with any.""" + out = vision_own_dir(family) + try: + meta = json.loads((out / "BUILD.json").read_text()) + except (OSError, ValueError): + return False + was = meta.get("vision") or "none" + return (out / VEXE).exists() and meta.get("vision_src") == source_hash(VISION_SOURCES) and \ + meta.get("llama") == FAMILIES[family]["vision_llama"] and bool(meta.get("portable")) == bool(portable) and \ + (was == "gpu" and int(meta.get("toolkit", 13)) == toolkit and set(cards) <= set(meta.get("archs", [])) or + was == "cpu" and vision == "cpu") + + +def build_vision_own(family, gpu, yes, vision, toolkit=13, portable=False) -> Path: + """Compile strata-vision from the family's own llama.cpp checkout (FAMILIES[family]["vision_llama"]) into + vision_own_dir(family) ("gpu": with CUDA, "cpu": without), and again when tools/vision or that commit changed, the + toolkit of a CUDA one is another, or the GPU is asked of a CPU one. engine-poly/strata-vision and + engine-poly/BUILD.json are not touched. Its BUILD.json has the toolkit's library folders ("cuda_dirs"), for the + config's lib_dirs. Returns the folder.""" + # build_engine_poly's encoder block, copied rather than shared: a change there would touch every family's encoder + commit = FAMILIES[family]["vision_llama"] + out = vision_own_dir(family) + cards = sorted({int(x) for x in gpu.get("archs", [gpu["arch"]])}) + if vision_own_ok(family, cards, vision, toolkit, portable): + ok(f"{FAMILIES[family]['title']}'s image encoder already built") + return out + out.mkdir(parents=True, exist_ok=True) + stamp = out / "BUILD.json" + vsrc = source_hash(VISION_SOURCES) + nvcc, vcvars = install_build_tools({**gpu, "archs": cards, "toolkit": toolkit, + "need_cuda": (12, 8) if max(cards) >= 120 else (12, 0)}, yes) + say(f" Compiling {FAMILIES[family]['title']}'s image encoder (llama.cpp {commit[:7]})" + + (" with CUDA (10-20 minutes, once) ..." if vision == "gpu" else " ...")) + defs = [f"-DLLAMA_DIR={get_llama_cpp(commit=commit)}", f"-DSTRATA_VISION_CUDA={'ON' if vision == 'gpu' else 'OFF'}", + f"-DSTRATA_PORTABLE={'ON' if portable else 'OFF'}"] + if vision == "gpu": + defs += [f"-DCMAKE_CUDA_ARCHITECTURES={';'.join(str(x) for x in cards)}", f"-DCMAKE_CUDA_COMPILER={nvcc}"] + vdir = ROOT / (f"build-vision-{family}" + ("" if toolkit == 13 else "-cuda12")) + cmake_build(ROOT / "tools" / "vision", vdir, "strata-vision", defs, vcvars, f"build-vision-{family}.bat") + shutil.copy2(vdir / "bin" / VEXE, out / VEXE) + bindir = Path(nvcc).parent # the toolkit's own libraries, as build_engine_poly's + dirs = [str(x) for x in (bindir, bindir / "x64", bindir.parent / "lib64") if x.is_dir()] if vision == "gpu" else [] + stamp.write_text(json.dumps({"source": "local", "llama": commit, "vision": vision, "vision_src": vsrc, + "archs": cards if vision == "gpu" else [], "toolkit": toolkit, "cuda_dirs": dirs, + **({"portable": True} if portable else {})}, indent=1)) + ok(f"image encoder: {out / VEXE}") + return out + + def build_engine_poly_hip(gpu, llama, portable=False) -> Path: """Compile strata-poly for this AMD GPU into engine-poly/ (again only when its source changed: a `git pull`). Windows: AMD's TheRock Windows wheels in .rocm-win (build_engine_poly_hip_win; portable: see that function). @@ -6835,9 +6990,11 @@ def update_poly_engine(cfg: dict, yes=False, cfg_path: Path | None = None) -> No if gpu is None: raise RuntimeError("no NVIDIA GPU found") gpu["archs"] = sorted({int(gpu_info(i)["arch"]) for i in picks}) # a layer split's cards - # the encoder too, when this model has one: on the device it was built for + # the encoder too, when this model has one: on the device it was built for. A family's own encoder + # (build_vision_own) has its own stamp and is updated after this (update_vision_own), not the shared one. vis = cfg.get("vision") - vision = ("gpu" if meta.get("vision") == "gpu" or vis.get("gpu") else "cpu") if isinstance(vis, dict) else "none" + vision = ("gpu" if meta.get("vision") == "gpu" or vis.get("gpu") else "cpu") \ + if isinstance(vis, dict) and vision_own_family(cfg) is None else "none" changed = renamed fits = set(gpu["archs"]) <= {int(x) for x in meta.get("archs", [])} if not (meta.get("src") == source_hash(ENGINE_SOURCES) and (eng / POLY_EXE).exists() and fits @@ -6859,6 +7016,44 @@ def update_poly_engine(cfg: dict, yes=False, cfg_path: Path | None = None) -> No ok(f"this install's engine is {POLY_EXE} now (it was {OLD_POLY_EXE}); {OLD_ENGINE_POLY_DIR}/ can be deleted") except (Exception, SystemExit) as e: warn(f"could not update strata-poly{'' if isinstance(e, SystemExit) else f' ({e})'}: starting the installed one") + finally: + update_vision_own(cfg, yes, cfg_path) + + +def vision_own_family(cfg: dict) -> str | None: + """The family whose own image encoder (build_vision_own) this config's images use, or None.""" + vis = cfg.get("vision") + return next((f for f in FAMILIES if FAMILIES[f].get("vision_llama") and isinstance(vis, dict) and + Path(str(vis.get("exe", ""))).parent == vision_own_dir(f)), None) + + +def update_vision_own(cfg: dict, yes=False, cfg_path: Path | None = None) -> None: + """Before a start, after the engine's update (update_poly_engine): a family's own image encoder is compiled again + when its stamp says so (build_vision_own), on the device and with the toolkit it was built for, and the config + gets its toolkit's library folders. A failure must not stop the start: the installed one runs.""" + own = vision_own_family(cfg) + if own is None: + return + try: + stamp = vision_own_dir(own) / "BUILD.json" + meta = json.loads(stamp.read_text()) if stamp.exists() else {} + g = cfg.get("gpu") + picks = g if isinstance(g, list) else [g if isinstance(g, int) else None] + gpu = gpu_info(picks[0]) + if gpu is None: + raise RuntimeError("no NVIDIA GPU found") + gpu["archs"] = sorted({int(gpu_info(i)["arch"]) for i in picks}) + want = "gpu" if meta.get("vision") == "gpu" or cfg["vision"].get("gpu") else "cpu" + build_vision_own(own, gpu, yes, want, int(meta.get("toolkit", config_toolkit(cfg))), bool(meta.get("portable"))) + dirs = json.loads(stamp.read_text()).get("cuda_dirs") or [] + new = [d for d in dirs if d not in (cfg.get("lib_dirs") or [])] + if new: + cfg["lib_dirs"] = (cfg.get("lib_dirs") or []) + new + if cfg_path is not None: + cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8") + except (Exception, SystemExit) as e: + warn(f"could not update the image encoder{'' if isinstance(e, SystemExit) else f' ({e})'}: starting the " + "installed one") def poly_tail_skip(cfg: dict, cfg_path: Path | None = None) -> None: @@ -6913,8 +7108,9 @@ def poly_setup(a, family, gpu, hip, cuda_tk, multi, ram, data, elsewhere, port, warn(f"{title}'s engine with CUDA 12 is compiled here (the ready-made one is CUDA 13)" + (": on Pascal / Volta it is untested" if int(gpu["arch"]) < CUDA13_MIN_ARCH else "")) if WIN and not fam.get("windows"): - confirm_risk(f"{title} has been run on Linux only: its engine compiles on Windows, the model was not tried " - "there", bool(a.family), a.yes, f"{title} has not been tried on Windows", + confirm_risk(fam.get("windows_risk") or f"{title} has been run on Linux only: its engine compiles on " + "Windows, the model was not tried there", bool(a.family), a.yes, + f"{title} has not been tried on Windows", f"use Linux, or --family {family} --yes to try it here") sees = fam.get("vision") is True if sees and hip: # the image encoder is a CUDA program: no HIP build of it yet (as for the main engine) @@ -6969,6 +7165,32 @@ def poly_setup(a, family, gpu, hip, cuda_tk, multi, ram, data, elsewhere, port, vision = auto if ask("Do you want images?", ["y", "n"], "n", a.yes) == "y" else "none" ok("images: " + {"none": "off", "gpu": "on", "cpu": "on (encoder on the CPU)"}[vision]) room = max(0.0, vram - (fam["vision_vram_gb"] if vision == "gpu" else 0)) # the VRAM left for the model + # the model's own drafter: opt-in, asked only where it was measured to pay, never with requests at once (--batch) + # or on several cards; its VRAM comes out of the room for the experts and the context's rows + spark = None + if fam.get("dspark"): + offer = poly_dspark_offer(fam, d, room) and not (a.parallel or 0) > 1 and not multi + want = a.dspark + if want is None and offer: + say() + say(f" Speculative decoding: {title}'s own drafter ({fam['dspark']['gb']} GB download, " + f"~{poly_dspark_gb(fam['dspark']):.1f} GB of VRAM) guesses") + say(" a few tokens ahead and the model checks them together: faster code and text that repeats, prose") + say(" about as fast. With every expert on the card a greedy answer is the one written without it.") + want = "yes" if ask("Use the DSpark drafter?", ["y", "n"], "n", a.yes) == "y" else "no" + if want == "yes" and (a.parallel or 0) > 1: + fail("--dspark yes does not go with --parallel", "leave one of them out") + if want == "yes" and multi: + fail("--dspark yes does not go with several cards", "leave it out, or choose one card") + if want == "yes": + if not offer: + warn("the DSpark drafter on a card that does not hold every expert: expect it to be no faster or " + "slower (measured on an RTX 2070 Super 8 GB)") + spark = fam["dspark"] + room = max(0.0, room - poly_dspark_gb(spark)) + ok("DSpark drafter: " + ("on" if spark else "off")) + elif a.dspark == "yes": + warn(f"--dspark: {title} has no DSpark drafter (Inkling 2 Mini has); left out") beside = poly_beside_gb(d) held, need_ram = poly_held_gb(d, room), poly_ram_need(d, room) say() @@ -7016,7 +7238,7 @@ def poly_setup(a, family, gpu, hip, cuda_tk, multi, ram, data, elsewhere, port, say() say(" Context length = how much text the model can see at once (your chat, files, tool output).") say(" Longer takes VRAM from the expert cache:") - row = fam.get("row_bytes", GLM_ROW_BYTES) + row = fam.get("row_bytes", GLM_ROW_BYTES) + (spark["row_bytes"] if spark else 0) # writing after a prompt that fills the context, tokens/s, on the 8 GB laptop (docs/BACKENDS.md, docs/LFM.md) laptop = fam.get("laptop_tps") or ({32768: "52-58", 65536: "42-46", 131072: "28-30"} if fam.get("ran_on_gb") == 8 else {}) @@ -7073,7 +7295,8 @@ def poly_setup(a, family, gpu, hip, cuda_tk, multi, ram, data, elsewhere, port, gguf = shards[0] have_model = all(s.exists() and (done(s) or bool(a.gguf_dir)) for s in shards) # the size's draft model: beside the model's file, or, when --gguf-dir has none, where setup keeps its own - guesser = models_dir / Path(d["draft_model"]).name if d.get("draft_model") else None + guesser = models_dir / Path(d["draft_model"]).name if d.get("draft_model") else \ + models_dir / spark["file"] if spark else None if guesser is not None and a.gguf_dir and not guesser.exists(): guesser = Path(a.models_dir) / tag / guesser.name have_guesser = guesser is None or guesser.exists() and (done(guesser) or bool(a.gguf_dir) or whole_shard(guesser)) @@ -7113,9 +7336,15 @@ def poly_setup(a, family, gpu, hip, cuda_tk, multi, ram, data, elsewhere, port, prev_meta = json.loads(prev.read_text(encoding="utf-8")) if prev.exists() else {} portable = bool(WIN and (getattr(a, "max_compatibility", False) or (not a.build and prev_meta.get("portable")))) + # a family with an encoder of its own ("vision_llama") builds it apart: the shared one is left as it is + own_vision = bool(fam.get("vision_llama")) and vision != "none" eng = build_engine_poly_hip(gpu, llama, portable) if hip else \ - build_engine_poly(gpu, a.yes, llama, vision, cuda_tk, portable) + build_engine_poly(gpu, a.yes, llama, "none" if fam.get("vision_llama") else vision, cuda_tk, portable) + veng = build_vision_own(family, gpu, a.yes, vision, cuda_tk, portable) if own_vision else eng lib_dirs = engine_lib_dirs(eng) + if own_vision: # the own encoder's toolkit libraries too (a CUDA one) + own_dirs = json.loads((veng / "BUILD.json").read_text()).get("cuda_dirs") or [] + lib_dirs = lib_dirs + [d for d in own_dirs if d not in lib_dirs] ok(f"engine: {eng / POLY_EXE}") step(5, f"downloading {title} {model}") @@ -7151,7 +7380,7 @@ def _skip_or_verify(path, sha_key): if guesser is not None: if not have_guesser: say(" Its draft model lets it guess a few words ahead and check them at once (faster answers).") - download(d.get("hf", fam["hf"]) + d["draft_model"], guesser) + download(spark["hf"] + spark["file"] if spark else d.get("hf", fam["hf"]) + d["draft_model"], guesser) _skip_or_verify(guesser, guesser.name) if mmproj is not None: if not have_mmproj: @@ -7259,15 +7488,25 @@ def _skip_or_verify(path, sha_key): if vt > fam.get("vision_most", vt): warn(f"--vision-tokens {vt}: {title} reads a picture in one prompt batch, {fam['vision_most']} tokens " "unless the engine is started with a larger --prompt-batch; a picture with more is refused") - cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), "model": str(gguf), "gpu": vision == "gpu", + cfg["vision"] = {"exe": str(veng / VEXE), "mmproj": str(mmproj), "model": str(gguf), "gpu": vision == "gpu", "max_tokens": vt} if vision == "cpu": cfg["vision"]["threads"] = max(1, (os.cpu_count() or 8) // 2) # requests at once: written only when given, else an earlier "parallel" is carried over (write_setup_config) if a.parallel is not None: cfg["parallel"] = a.parallel if a.parallel >= 2 else 1 + elif spark: # the drafter guesses for one request at a time + if config_has(cfg_path if cfg_path.is_file() else earlier, "parallel"): + say(" requests at once: 1 in place of the earlier config's \"parallel\" (the DSpark drafter guesses for " + "one request at a time; --dspark no keeps several)") + cfg["parallel"] = 1 for line in poly_parallel_note(a.parallel, d, vram): (ok if a.parallel is not None else say)(line if a.parallel is not None else " " + line) + if fam.get("sampling") and not config_has(cfg_path if cfg_path.is_file() else earlier, "sampling"): + # the model's own defaults (its GGUF's general.sampling.*): a "sampling" block of the user's is kept instead + cfg["sampling"] = dict(fam["sampling"]) + ok("sampling defaults: " + ", ".join(f"{k} {v}" for k, v in cfg["sampling"].items()) + + " (the model's own; \"sampling\" in the config)") poly_kv_whole(cfg) warm_start_into(cfg, a) write_setup_config(cfg_path, cfg, earlier) @@ -7850,7 +8089,8 @@ def main() -> int: "DeepSeek V4 Flash, lfm25 = LFM2.5-24B-A2B, flint = Flint 40B-A2.5B, qwen36 = " "Qwen3.6-35B-A3B on strata-poly, clover = Clover-35B-A3B-Preview, ornith = " "Ornith 1.5, gemma4 = Gemma 4 26B-A4B, tiel = Tiel Coder 35B-A3B, minicpmv = MiniCPM-V 4.7 " - "35B-A3B, ornith122 = Ornith 1.5 122B (docs/BACKENDS.md), qwen36-strata = Qwen3.6-35B-A3B on the Strata project's " + "35B-A3B, ornith122 = Ornith 1.5 122B (docs/BACKENDS.md), inkling = Inkling 2 Mini " + "(experimental, NVIDIA only, docs/models/inkling.md), qwen36-strata = Qwen3.6-35B-A3B on the Strata project's " "own engine (UD-Q4_K_XL and up, 32 GB of RAM or more; pictures with --vision, several " "requests at once with --parallel; docs/QWEN36.md)") ap.add_argument("--model", choices=list(dict.fromkeys( @@ -7871,6 +8111,9 @@ def main() -> int: "Kolibri, Flint, LFM2.5), int8 or int8k (Gemma 4), fp16 (the default)") ap.add_argument("--vision", choices=["yes", "no", "none", "gpu", "cpu"], help="let the model read images (yes = the encoder on the GPU)") + ap.add_argument("--dspark", choices=["yes", "no"], + help="Inkling 2 Mini: speculative decoding with its own DSpark drafter (a 0.4 GB download; " + "offered by default only where the card holds every expert)") ap.add_argument("--vision-tokens", type=int, metavar="N", help="the most image tokens a picture becomes (default 1024 with the encoder on the GPU, 300 on " "the CPU): more reads small text and charts better, and takes longer to encode; remembered " @@ -8305,6 +8548,9 @@ def main() -> int: say(f" {m:8s} needs ~{d['ram_gb']} GB RAM: {verdict}") for f, fd in FAMILIES.items(): # the families with sizes of their own for m, d in fd.get("models", {}).items(): + if hip and fd.get("cuda_only"): + say(f" {fd['title']} {m}: NVIDIA only (setup does not offer it on AMD cards yet)") + continue any_fits = any_fits or poly_fits(d, ram, gpu["vram_gb"], hip) say(f" {fd['title']} {m}: {poly_verdict(d, ram, gpu['vram_gb'], hip, bool(fd.get('windows')))}") if not any_fits: @@ -8339,6 +8585,10 @@ def main() -> int: if family in OWN_PATH_FAMILIES: # Qwen3.6: its own engine path, its own steps 2-7 return install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted) fam = FAMILIES[family] + if fam.get("cuda_only") and hip: + why = fam.get("cuda_only_why") + fail(f"setup offers {fam['title']} on NVIDIA cards only for now" + (f": {why}" if why else ""), + "use an NVIDIA card, or choose another model") if fam.get("ready") and hip: # not a risk the user could take: the HIP engine has no NVFP4 expert kernels at all, so it would not start fail(f"{fam['title']} runs on NVIDIA cards only: the AMD engine has no NVFP4 kernels", diff --git a/src/kernels/cuda/dequant_bf16.cu b/src/kernels/cuda/dequant_bf16.cu index f0aaa92500..1889b24649 100644 --- a/src/kernels/cuda/dequant_bf16.cu +++ b/src/kernels/cuda/dequant_bf16.cu @@ -417,7 +417,7 @@ bool dequant_bf16_supported(int ggml_type) noexcept { namespace { // plan v0.3 P6: the i-quant formats (llama.cpp's dequantizers, iq_kernels.cu) -bool iq_only(int t) { return t == 16 || t == 17 || t == 18 || t == 21 || t == 22 || t == 29; } +bool iq_only(int t) { return t == 16 || t == 17 || t == 18 || t == 21 || t == 22 || t == 29 || t == 19; } } // namespace void dequant_bf16(int ggml_type, const void* blocks, int64_t row0, int64_t rows, int64_t cols, uint16_t* out, diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 6872ca4b8b..5ed192696a 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -241,6 +241,29 @@ __device__ __forceinline__ float vec_dot_iq3_s_q8_1(const void* __restrict__ vbq return d * sumi; } +__device__ __forceinline__ float vec_dot_iq1_s_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, + const int& kbx, const int& iqs) { + const block_iq1_s* bq1 = (const block_iq1_s*) vbq + kbx; + const int qs_packed = get_int_b2(bq1->qs, iqs); + const uint8_t* qs = (const uint8_t*) &qs_packed; + const int qh = bq1->qh[iqs]; + int sumi = 0; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int grid = iq1s_grid_gpu[qs[l0 / 2] | (((qh >> 3 * (l0 / 2)) & 0x07) << 8)]; + const int grid0 = (grid >> 0) & 0x0F0F0F0F; + const int grid1 = (grid >> 4) & 0x0F0F0F0F; + const int u0 = get_int_b4(bq8_1[iqs].qs, l0 + 0); + const int u1 = get_int_b4(bq8_1[iqs].qs, l0 + 1); + sumi = ggml_cuda_dp4a(grid0, u0, sumi); + sumi = ggml_cuda_dp4a(grid1, u1, sumi); + } + const float d1q = __half2float(bq1->d) * (((qh >> 11) & 0x0E) + 1); + const float delta = -1.0f + IQ1S_DELTA - (qh & 0x8000) * (2.0f * IQ1S_DELTA / 0x8000); + const float2 ds = __half22float2(bq8_1[iqs].ds); + return d1q * (ds.x * sumi + ds.y * delta); +} + __device__ __forceinline__ float vec_dot_iq1_m_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1, const int& kbx, const int& iqs) { const block_iq1_m* bq1 = (const block_iq1_m*) vbq + kbx; @@ -620,6 +643,8 @@ template<> struct Fmt<23> { static constexpr int qk = 256, ipb = 8, step = 4; __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq4_xs_q8_1(v, y, kbx, iqs); } }; template<> struct Fmt<22> { static constexpr int qk = 256, ipb = 8, step = 2; __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq2_s_q8_1(v, y, kbx, iqs); } }; +template<> struct Fmt<19> { static constexpr int qk = 256, ipb = 8, step = 1; + __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq1_s_q8_1(v, y, kbx, iqs); } }; template<> struct Fmt<29> { static constexpr int qk = 256, ipb = 8, step = 1; __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq1_m_q8_1(v, y, kbx, iqs); } }; template<> struct Fmt<42> { static constexpr int qk = 64, ipb = 2, step = 1; @@ -644,17 +669,17 @@ template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0, // The formats of each role, one list each so a type cannot be in one switch and missing from another. Every // entry is a kernel template for each CUDA architecture of the build, hence two lists rather than one. #ifdef STRATA_Q6K_EXPERTS // opt-in build (-DSTRATA_Q6K_EXPERTS=ON): one more instance per kernel, loaded at start -#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(14) X(6) X(2) X(3) X(8) X(40) +#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(19) X(42) X(12) X(13) X(14) X(6) X(2) X(3) X(8) X(40) #else -#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(2) X(3) X(8) X(40) +#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(19) X(42) X(12) X(13) X(6) X(2) X(3) X(8) X(40) #endif // Q5_K / Q6_K downs: Qwen3.6-35B-A3B (FF 512, whole 256-blocks per row); Flash-Next's FF 640 never selects them #ifdef STRATA_Q6K_EXPERTS -#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8) X(13) X(14) X(40) +#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(19) X(7) X(6) X(2) X(3) X(8) X(13) X(14) X(40) #else -#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8) X(13) X(40) +#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(19) X(7) X(6) X(2) X(3) X(8) X(13) X(40) #endif -#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(2) X(3) X(8) X(40) +#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(19) X(42) X(12) X(13) X(7) X(6) X(2) X(3) X(8) X(40) template<> struct Fmt<40> { static constexpr int qk = 64, ipb = 2, step = 4; // NVFP4: 2 calls of 32 values __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_nvfp4_q8_1(v, y, kbx, iqs); } }; @@ -704,7 +729,7 @@ template struct Split; // per-entry ones, which call Fmt::dot per column exactly as before #242 (the launchers test kSplit at compile // time, so the multi kernels are never instantiated for a type without a Split). template inline constexpr bool kSplit = false; -template inline constexpr bool kStageIqGrid = (TY == 16 || TY == 17 || TY == 22 || TY == 29); +template inline constexpr bool kStageIqGrid = (TY == 16 || TY == 17 || TY == 22 || TY == 29 || TY == 19); template<> inline constexpr bool kSplit<16> = true; template<> struct Split<16> { // IQ2_XXS @@ -917,6 +942,42 @@ template<> struct Split<21> { // IQ3_S return d * sumi; } }; +template<> inline constexpr bool kSplit<19> = true; +template<> struct Split<19> { // IQ1_S: vec_dot_iq1_s_q8_1, split + struct W { int g[8]; float d1q, delta; }; + template + __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) { + const block_iq1_s* bq1 = (const block_iq1_s*) vbq + kbx; + const int qs_packed = get_int_b2(bq1->qs, iqs); + const uint8_t* qs = (const uint8_t*) &qs_packed; + const int qh = bq1->qh[iqs]; + const uint32_t* grid_lut; + if constexpr (STAGE_GRID) grid_lut = s_grid; + else grid_lut = iq1s_grid_gpu; + W r; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int grid = grid_lut[qs[l0 / 2] | (((qh >> 3 * (l0 / 2)) & 0x07) << 8)]; + r.g[l0 + 0] = (grid >> 0) & 0x0F0F0F0F; + r.g[l0 + 1] = (grid >> 4) & 0x0F0F0F0F; + } + r.d1q = __half2float(bq1->d) * (((qh >> 11) & 0x0E) + 1); + r.delta = -1.0f + IQ1S_DELTA - (qh & 0x8000) * (2.0f * IQ1S_DELTA / 0x8000); + return r; + } + __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { + int sumi = 0; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int u0 = get_int_b4(bq8_1[iqs].qs, l0 + 0); + const int u1 = get_int_b4(bq8_1[iqs].qs, l0 + 1); + sumi = ggml_cuda_dp4a(r.g[l0 + 0], u0, sumi); + sumi = ggml_cuda_dp4a(r.g[l0 + 1], u1, sumi); + } + const float2 ds = __half22float2(bq8_1[iqs].ds); + return r.d1q * (ds.x * sumi + ds.y * r.delta); + } +}; template<> inline constexpr bool kSplit<29> = true; template<> struct Split<29> { // IQ1_M struct W { int g[8]; float delta[4]; int sc0, sc1; float dw; }; @@ -1323,7 +1384,7 @@ __device__ __forceinline__ const uint32_t* stage_iq_grid(uint32_t* s_buf, int ti for (int i = tid; i < 1024; i += nthreads) dst[i] = src[i]; __syncthreads(); return s_buf; - } else if constexpr (TY == 29) { + } else if constexpr (TY == 29 || TY == 19) { uint2* dst = (uint2*) s_buf; const uint2* src = (const uint2*) iq1s_grid_gpu; for (int i = tid; i < 1024; i += nthreads) dst[i] = src[i]; @@ -1336,7 +1397,7 @@ __device__ __forceinline__ const uint32_t* stage_iq_grid(uint32_t* s_buf, int ti template> struct IqGridWords { - static constexpr int value = !STAGE_GRID ? 4 : (TY == 22 || TY == 29) ? 2048 : (TY == 17) ? 1024 : (TY == 16) ? 512 : 4; + static constexpr int value = !STAGE_GRID ? 4 : (TY == 22 || TY == 29 || TY == 19) ? 2048 : (TY == 17) ? 1024 : (TY == 16) ? 512 : 4; }; // mmvq_kernel with the columns taken NC at a time. After warp_sum every lane holds the same sum, so lane c stores @@ -2208,6 +2269,20 @@ __device__ void dq_iq3_s(const void* vx, int64_t ibs, dst_t* yy, int tid) { } } template +__device__ void dq_iq1_s(const void* vx, int64_t ibs, dst_t* yy, int tid) { + const block_iq1_s* x = (const block_iq1_s*) vx; + const int64_t il = tid / 8, ib = tid % 8; + dst_t* y = yy + 32 * ib + 8 * il; + const float delta = x[ibs].qh[ib] & 0x8000 ? -1 - IQ1S_DELTA : -1 + IQ1S_DELTA; + const float d = (float) x[ibs].d * (2 * ((x[ibs].qh[ib] >> 12) & 7) + 1); + uint32_t grid32[2]; + const int8_t* q = (const int8_t*) grid32; + grid32[0] = iq1s_grid_gpu[x[ibs].qs[4 * ib + il] | (((x[ibs].qh[ib] >> 3 * il) & 7) << 8)]; + grid32[1] = (grid32[0] >> 4) & 0x0f0f0f0f; + grid32[0] &= 0x0f0f0f0f; + for (int j = 0; j < 8; ++j) y[j] = cvt(d * (q[j] + delta)); +} +template __device__ void dq_iq1_m(const void* vx, int64_t ibs, dst_t* yy, int tid) { const block_iq1_m* x = (const block_iq1_m*) vx; const int64_t il = tid / 8, ib = tid % 8; @@ -2466,6 +2541,7 @@ __device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs, case 21: dq_iq3_s(vx, ibs, y, tid); break; case 22: dq_iq2_s(vx, ibs, y, tid); break; case 29: dq_iq1_m(vx, ibs, y, tid); break; + case 19: dq_iq1_s(vx, ibs, y, tid); break; case 23: dq_iq4_xs(vx, ibs, y, tid); break; case 11: dq_q3_k(vx, ibs, y, tid); break; case 42: dq_q2_0(vx, ibs, y, tid); break; @@ -2520,7 +2596,7 @@ __global__ void dequant_gu_kernel(int ty, const void* __restrict__ gate, const v // the types dq_dispatch dequantizes bool is_iq(int t) { - return t == 16 || t == 17 || t == 18 || t == 20 || t == 21 || t == 22 || t == 23 || t == 29 || t == 42 || t == 11 || + return t == 16 || t == 17 || t == 18 || t == 20 || t == 21 || t == 22 || t == 23 || t == 29 || t == 19 || t == 42 || t == 11 || #ifdef STRATA_Q6K_EXPERTS t == 12 || t == 13 || t == 14 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8 || t == 40; #else @@ -3453,6 +3529,7 @@ size_t iq_row_bytes(int t, int64_t n) noexcept { case 21: return (size_t) (n / 256) * sizeof(block_iq3_s); case 22: return (size_t) (n / 256) * sizeof(block_iq2_s); case 29: return (size_t) (n / 256) * sizeof(block_iq1_m); + case 19: return (size_t) (n / 256) * sizeof(block_iq1_s); case 23: return (size_t) (n / 256) * sizeof(block_iq4_xs); case 11: return (size_t) (n / 256) * sizeof(block_q3_K); case 42: return (size_t) (n / 64) * sizeof(block_q2_0); @@ -3504,12 +3581,43 @@ __global__ void __launch_bounds__(128) mmvq_slots_kernel(S slots, size_t row_byt if (lane == 0) at.y[row] = s; } +// mmvq_slots_kernel for MmvqSlots::lanes, the formats whose grid mmvq_multi_kernel stages in shared memory: the grid +// staged once for a block of LANE_ROWS rows a warp, each row row_dot_multi's for one column, which is row_dot's +// arithmetic in its order - the same bits. STRATA_OLD_IQ_MMVQ and STRATA_IQ_STAGE_GRID=0 keep mmvq_slots_kernel. +constexpr int LANE_ROWS = 8; +template +__global__ void __launch_bounds__(128) mmvq_slots_staged_kernel(S slots, size_t row_bytes, int n_in, int n_out) { + STRATA_SHARED_ALIGN16_U32(s_grid_buf, IqGridWords::value); + const uint32_t* s_grid = stage_iq_grid(s_grid_buf, threadIdx.y * 32 + threadIdx.x, 128); + const SlotPtrs at = slot_ptrs(slots, int(blockIdx.y)); + const int lane = threadIdx.x, nb = n_in / Fmt::qk; + const int off[1] = {0}; + for (int r = 0; r < LANE_ROWS; ++r) { + const int row = (blockIdx.x * 4 + threadIdx.y) * LANE_ROWS + r; + if (row >= n_out) return; + float s[1]; + row_dot_multi((const uint8_t*) at.w + (size_t) row * row_bytes, (const block_q8_1*) at.x, + off, 1, nb, lane, s, s_grid); + if (lane == 0) at.y[row] = s[0]; + } +} + template void slots_of(int t, const S& slots, int count, int n_in, int n_out, void* stream) { const size_t rb = iq_row_bytes(t, n_in); const dim3 grid((unsigned) ((n_out + 3) / 4), (unsigned) count), block(32, 4); + const dim3 staged((unsigned) ((n_out + 4 * LANE_ROWS - 1) / (4 * LANE_ROWS)), (unsigned) count); switch (t) { -#define STRATA_MMVQ(T) case T: mmvq_slots_kernel<<>>(slots, rb, n_in, n_out); break; +#define STRATA_MMVQ(T) \ + case T: \ + if constexpr (kStageIqGrid) { \ + if (slots.lanes && !g_old_kernels && g_stage_grid) { \ + mmvq_slots_staged_kernel<<>>(slots, rb, n_in, n_out); \ + break; \ + } \ + } \ + mmvq_slots_kernel<<>>(slots, rb, n_in, n_out); \ + break; STRATA_MMVQ_FMTS(STRATA_MMVQ) #undef STRATA_MMVQ default: std::fprintf(stderr, "iq_mmvq_slots: type %d is not supported\n", t); std::exit(1); diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index b1d71efb4e..c54740cd5b 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -203,16 +203,12 @@ __global__ void native_swiglu_quantize_q8_1_kernel(const float* __restrict__ gat // with its block size (SUM threads of the block) and its IEEE operations written out (this file is built with // --use_fast_math). Then every thread of the block takes values, a warp 32 of one Q8_1 block, and quantizes them as // native_quantize_q8_1_kernel does: more threads than the sum's make the row's quantization fewer steps. +// The block's row: xr, ar (or null), yr and qr at the row's place. template -__launch_bounds__(1024, 1) -__global__ void native_add_rms_norm_q8_1_kernel(float* __restrict__ x, const float* __restrict__ add, - const float* __restrict__ w, float* __restrict__ y, - Q81Block* __restrict__ yq, int n, float eps) { +__device__ __forceinline__ void add_rms_norm_q8_1_row(float* __restrict__ xr, const float* __restrict__ ar, + const float* __restrict__ w, float* __restrict__ yr, + Q81Block* __restrict__ qr, int n, float eps) { __shared__ float part[SUM / WARP]; - float* xr = x + std::size_t(blockIdx.x) * n; - const float* ar = add ? add + std::size_t(blockIdx.x) * n : nullptr; - float* yr = y + std::size_t(blockIdx.x) * n; - Q81Block* qr = yq + std::size_t(blockIdx.x) * (n / Q8K); if (threadIdx.x < SUM) { float ss = 0.0f; for (int i = threadIdx.x; i < n; i += SUM) { @@ -239,6 +235,24 @@ __global__ void native_add_rms_norm_q8_1_kernel(float* __restrict__ x, const flo } } +template +__launch_bounds__(1024, 1) +__global__ void native_add_rms_norm_q8_1_kernel(float* __restrict__ x, const float* __restrict__ add, + const float* __restrict__ w, float* __restrict__ y, + Q81Block* __restrict__ yq, int n, float eps) { + add_rms_norm_q8_1_row(x + std::size_t(blockIdx.x) * n, add ? add + std::size_t(blockIdx.x) * n : nullptr, w, + y + std::size_t(blockIdx.x) * n, yq + std::size_t(blockIdx.x) * (n / Q8K), n, eps); +} + +// native_add_rms_norm_q8_1_kernel's row of its own for each block, without add. +template +__launch_bounds__(1024, 1) +__global__ void native_rms_norm_q8_1_rows_kernel(NormRows r, int n, float eps) { + const int k = blockIdx.x; + add_rms_norm_q8_1_row(const_cast(r.x[k]), nullptr, r.w[k], r.y[k], + static_cast(r.y_q8_1[k]), n, eps); +} + // Exact pinned vec_dot_q5_K_q8_1_impl_vmmq expression and integer dot order. __device__ __forceinline__ float q5_q8_dot_impl( const int* __restrict__ vl, const int* __restrict__ vh, const int* __restrict__ u, @@ -1794,9 +1808,42 @@ __global__ void native_mmvq_slots_warp_kernel(S slots, int n_in, int n_out) { } } +// native_mmvq_slots_kernel with a warp a row (MmvqSlots::lanes): lane l does the work of the block's threads l, +// 32 + l, 64 + l and 96 + l, each into its own sum, and adds them in the order the block adds its warps' partials - +// the same terms in the same order, so the same bits, with no shared memory or barrier and no thread idle for a K +// the block's threads do not divide evenly (an expert's 2304 and 1152 IQ4_NL values: 72 and 36 blocks for the +// block's 64 pairs of threads). +template +__launch_bounds__(WARPS * WARP) +__global__ void native_mmvq_slots_lanes_kernel(S slots, int n_in, int n_out) { + const SlotPtrs at = slot_ptrs(slots, int(blockIdx.y)); + const int row = int(blockIdx.x) * WARPS + int(threadIdx.y); + if (row >= n_out) return; // whole warps: no barrier below + const auto* w = static_cast(at.w) + std::size_t(row) * (n_in / F::DIV); + const auto* x = static_cast(at.x); + const int lane = int(threadIdx.x), blocks_per_row = n_in / F::DIV; + float tmp[WARPS] = {}; + for (int base = 0; base < blocks_per_row; base += F::BPI) { +#pragma unroll + for (int v = 0; v < WARPS; ++v) { + const int tid = WARP * v + lane, kbx = base + tid / F::T, kqs = F::kqs(tid); + if (kbx < blocks_per_row) tmp[v] += F::apply(F::load(w + kbx, kqs), x + kbx * F::KBY, kqs); + } + } +#pragma unroll + for (int v = 1; v < WARPS; ++v) tmp[0] += tmp[v]; + tmp[0] = warp_sum(tmp[0]); + if (lane == 0) at.y[row] = tmp[0]; +} + template void launch_slots(const S& slots, int count, int n_in, int n_out, cudaStream_t s) { const dim3 threads(WARP, WARPS); + if (slots.lanes) { + const dim3 blocks(unsigned((std::size_t(n_out) + WARPS - 1) / WARPS), unsigned(count)); + native_mmvq_slots_lanes_kernel<<>>(slots, n_in, n_out); + return; + } if (native_mmvq_slots_wide() && n_in / F::DIV * F::T <= WARP && n_in % F::DIV == 0) { constexpr int ROWS = 2; if (n_in / F::DIV * F::T <= WARP / 2) { // a row in half a warp: two rows' groups a warp @@ -2705,6 +2752,29 @@ void native_add_rms_norm_q8_1(float* x, const float* add, const float* w, float* launch_check(); } +bool native_rms_norm_q8_1_rows(const NormRows& r, int count, int n, float eps, int threads, void* stream) { + validate_shape(n, 1); + validate_stream(stream); + if (count < 1 || count > kNormRowsMax) throw std::invalid_argument("native_rms_norm_q8_1_rows: 1 to 4 rows"); + for (int k = 0; k < count; ++k) { + validate_pointer(r.x[k]); + validate_pointer(r.w[k]); + validate_pointer(r.y[k]); + validate_pointer(r.y_q8_1[k]); + } + const auto s = static_cast(stream); + const int block = std::max(threads, std::min(1024, n)); // native_add_rms_norm_q8_1()'s + switch (threads) { + case 128: native_rms_norm_q8_1_rows_kernel<128><<>>(r, n, eps); break; + case 256: native_rms_norm_q8_1_rows_kernel<256><<>>(r, n, eps); break; + case 512: native_rms_norm_q8_1_rows_kernel<512><<>>(r, n, eps); break; + case 1024: native_rms_norm_q8_1_rows_kernel<1024><<>>(r, n, eps); break; + default: throw std::invalid_argument("native_rms_norm_q8_1_rows: 128, 256, 512 or 1024 threads"); + } + launch_check(); + return true; +} + void native_q5_k_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) { validate_shape(n_in, ncols, QK); @@ -3139,7 +3209,7 @@ bool native_mmvq_supported(int ggml_type) noexcept { return ggml_type == 2 || ggml_type == 6 || ggml_type == 7 || ggml_type == 8 || ggml_type == 10 || ggml_type == 11 || ggml_type == 12 || ggml_type == 13 || ggml_type == 14 || ggml_type == 20 || ggml_type == 23 || ggml_type == 42 || ggml_type == 16 || ggml_type == 17 || ggml_type == 18 || - ggml_type == 21 || ggml_type == 22 || ggml_type == 29 || ggml_type == 39 || ggml_type == 40; + ggml_type == 21 || ggml_type == 22 || ggml_type == 29 || ggml_type == 19 || ggml_type == 39 || ggml_type == 40; } std::size_t native_mmvq_weight_bytes(int ggml_type, int n_in, int n_out) { @@ -3159,7 +3229,7 @@ std::size_t native_mmvq_weight_bytes(int ggml_type, int n_in, int n_out) { case 23: block_elems = 256; block_bytes = 136; break; case 42: block_elems = 64; block_bytes = 18; break; case 40: block_elems = 64; block_bytes = 36; break; - case 16: case 17: case 18: case 21: case 22: case 29: + case 16: case 17: case 18: case 21: case 22: case 29: case 19: block_elems = 256; block_bytes = (int) iq_row_bytes(ggml_type, 256); break; default: throw std::invalid_argument("unsupported native MMVQ GGML type"); } @@ -3188,7 +3258,7 @@ void native_mmvq(int ggml_type, const void* weights, const void* x_q8_1, float* case 14: native_q6_k_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; case 23: native_iq4_xs_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; case 42: native_q2_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break; - case 16: case 17: case 18: case 21: case 22: case 29: + case 16: case 17: case 18: case 21: case 22: case 29: case 19: iq_mmvq(ggml_type, weights, x_q8_1, y, n_in, n_out, ncols, stream); break; default: throw std::invalid_argument("unsupported native MMVQ GGML type"); } @@ -3204,7 +3274,7 @@ int slots_kind(int ggml_type) { #else switch (ggml_type) { case 2: case 6: case 8: case 20: case 39: case 10: case 11: case 12: case 13: case 14: case 23: case 42: return 1; - case 7: case 16: case 17: case 18: case 21: case 22: case 29: case 40: return 2; // the ones native_mmvq() hands to iq_mmvq() + case 7: case 16: case 17: case 18: case 21: case 22: case 29: case 19: case 40: return 2; // the ones native_mmvq() hands to iq_mmvq() default: return 0; } #endif @@ -3265,6 +3335,204 @@ bool native_mmvq_slots(int ggml_type, const MmvqSlots& slots, int count, int n_i return true; } +namespace { + +// native_mmvq_jobs: blockIdx.x counts the row blocks of all the matrices, matrix after matrix, and a block is +// native_mmvq_multi_kernel's EXACT layout for its matrix (one row, or ROWS for a K too small for every thread). A +// kernel of its own rather than a matrix table in native_mmvq_multi_kernel, which every family's products run: that +// kernel stays byte-identical. An ordinary launch: it has no pdl_wait() for launch_pdl(). +struct JobsArgs { + MmvqJobs j; + int first[kMmvqJobsMax + 1]; // each matrix's first row block, and the end + int count; +}; + +// The job of block b: the last whose first row block is at most b. +__device__ __forceinline__ int job_of(const int* first, int count, int b) { + int k = 0; +#pragma unroll + for (int i = 1; i < kMmvqJobsMax; ++i) + if (i < count && b >= first[i]) k = i; + return k; +} + +// Job k's row block b - first[k]. +template +__device__ __forceinline__ void mmvq_job_block(const JobsArgs& a, int k, int b, int n_in) { + const auto* w = static_cast(a.j.w[k]); + const auto* x = static_cast(a.j.x[k]); + float* y = a.j.y[k]; + const int n_out = a.j.n_out[k]; + const int tid = WARP * int(threadIdx.y) + int(threadIdx.x); + const int row0 = ROWS * (b - a.first[k]); + const int blocks_per_row = n_in / F::DIV; + const int x_stride = n_in / Q8K; + float tmp[NCOLS][ROWS] = {}; + for (int kbx = tid / F::T; kbx < blocks_per_row; kbx += F::BPI) { + const int kby = kbx * F::KBY; + const int kqs = F::kqs(tid); +#pragma unroll + for (int i = 0; i < ROWS; ++i) { + if (row0 + i < n_out) { + const typename F::W wv = F::load(w + std::size_t(row0 + i) * blocks_per_row + kbx, kqs); +#pragma unroll + for (int j = 0; j < NCOLS; ++j) tmp[j][i] += F::apply(wv, x + std::size_t(j) * x_stride + kby, kqs); + } + } + } + __shared__ float partial[WARPS - 1][NCOLS][ROWS][WARP]; + if (threadIdx.y > 0) { +#pragma unroll + for (int j = 0; j < NCOLS; ++j) +#pragma unroll + for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][j][i][threadIdx.x] = tmp[j][i]; + } + __syncthreads(); + if (threadIdx.y > 0) return; +#pragma unroll + for (int j = 0; j < NCOLS; ++j) { +#pragma unroll + for (int i = 0; i < ROWS; ++i) { +#pragma unroll + for (int l = 0; l < WARPS - 1; ++l) tmp[j][i] += partial[l][j][i][threadIdx.x]; + tmp[j][i] = warp_sum(tmp[j][i]); + if (threadIdx.x == i && row0 + i < n_out) y[std::size_t(j) * n_out + row0 + i] = tmp[j][i]; + } + } +} + +template +__launch_bounds__(WARPS * WARP, 1) +__global__ void native_mmvq_jobs_kernel(JobsArgs a, int n_in) { + const int b = int(blockIdx.x); + mmvq_job_block(a, job_of(a.first, a.count, b), b, n_in); +} + +// native_mmvq_jobs_kernel's blocks for matrices of several formats, one column: each block the one-format kernel's +// for its matrix's format and rows a block (kind: 2 * format index + rows - 1). +struct MixedArgs { + JobsArgs a; + int kind[kMmvqJobsMax]; +}; +__launch_bounds__(WARPS * WARP, 1) +__global__ void native_mmvq_jobs_mixed_kernel(MixedArgs m, int n_in) { + const int b = int(blockIdx.x), k = job_of(m.a.first, m.a.count, b); + switch (m.kind[k]) { + case 0: mmvq_job_block, 1, 1>(m.a, k, b, n_in); break; + case 1: mmvq_job_block, 1, 2>(m.a, k, b, n_in); break; + case 2: mmvq_job_block(m.a, k, b, n_in); break; + case 3: mmvq_job_block(m.a, k, b, n_in); break; + case 4: mmvq_job_block(m.a, k, b, n_in); break; + case 5: mmvq_job_block(m.a, k, b, n_in); break; + case 6: mmvq_job_block(m.a, k, b, n_in); break; + default: mmvq_job_block(m.a, k, b, n_in); break; + } +} + +// launch_jobs_n()'s rows a block for format F and n_in. +template +int job_rows(int n_in) { return n_in / F::DIV >= F::BPI ? 1 : 2; } + +template +void launch_jobs_n(JobsArgs a, int n_in, cudaStream_t s) { + const auto go = [&](auto rows) { + constexpr int ROWS = decltype(rows)::value; + a.first[0] = 0; + for (int i = 0; i < a.count; ++i) a.first[i + 1] = a.first[i] + (a.j.n_out[i] + ROWS - 1) / ROWS; + native_mmvq_jobs_kernel<<>>(a, n_in); + }; + if (n_in / F::DIV >= F::BPI) go(std::integral_constant{}); + else go(std::integral_constant{}); +} + +template +void launch_jobs(const JobsArgs& a, int n_in, int ncols, cudaStream_t s) { + switch (ncols) { + case 1: launch_jobs_n(a, n_in, s); break; + case 2: launch_jobs_n(a, n_in, s); break; + case 3: launch_jobs_n(a, n_in, s); break; + case 4: launch_jobs_n(a, n_in, s); break; + case 5: launch_jobs_n(a, n_in, s); break; + case 6: launch_jobs_n(a, n_in, s); break; + case 7: launch_jobs_n(a, n_in, s); break; + default: launch_jobs_n(a, n_in, s); break; + } +} + +} // namespace + +bool native_mmvq_jobs(int ggml_type, const MmvqJobs& jobs, int count, int n_in, int ncols, void* stream) { +#if defined(STRATA_HIP_GFX906) + (void) ggml_type, (void) jobs, (void) count, (void) n_in, (void) ncols, (void) stream; + return false; // the wave layout's bits are other +#else + // the formats whose single products are this layout's bits; several columns only in the exact layout + if (ggml_type != 8 && ggml_type != 12 && ggml_type != 13 && ggml_type != 14) return false; + if (ncols > 1 && (!g_multi_exact || g_b6_rows > 0 || s26_tsum_on())) return false; + if (count < 1 || count > kMmvqJobsMax || ncols < 1 || ncols > MAX_NCOLS) + throw std::invalid_argument("native_mmvq_jobs requires 1 to 8 matrices and 1 to 8 columns"); + validate_shape(n_in, ncols, ggml_type == 8 ? 32 : 256); + validate_stream(stream); + JobsArgs a{}; + a.j = jobs; + a.count = count; + for (int i = 0; i < count; ++i) { + if (jobs.n_out[i] <= 0) throw std::invalid_argument("native_mmvq_jobs requires n_out > 0"); + validate_pointer(jobs.w[i]); + validate_pointer(jobs.x[i]); + validate_pointer(jobs.y[i]); + // a repacked matrix (STRATA_Q8_PACKED, STRATA_Q6_PACKED) goes through its own kernel + if (q8_packed_registry().count(jobs.w[i]) || q6_packed_registry().count(jobs.w[i])) return false; + } + const auto s = static_cast(stream); + switch (ggml_type) { + case 8: launch_jobs>(a, n_in, ncols, s); break; + case 12: launch_jobs(a, n_in, ncols, s); break; + case 13: launch_jobs(a, n_in, ncols, s); break; + default: launch_jobs(a, n_in, ncols, s); break; + } + launch_check(); + return true; +#endif +} + +bool native_mmvq_jobs_mixed(const int* types, const MmvqJobs& jobs, int count, int n_in, void* stream) { +#if defined(STRATA_HIP_GFX906) + (void) types, (void) jobs, (void) count, (void) n_in, (void) stream; + return false; // the wave layout's bits are other +#else + if (count < 1 || count > kMmvqJobsMax || n_in <= 0) + throw std::invalid_argument("native_mmvq_jobs_mixed requires 1 to 8 matrices and n_in > 0"); + validate_stream(stream); + MixedArgs m{}; + m.a.j = jobs; + m.a.count = count; + m.a.first[0] = 0; + for (int i = 0; i < count; ++i) { + int index, rows; + switch (types[i]) { + case 8: index = 0, rows = job_rows>(n_in); break; + case 12: index = 1, rows = job_rows(n_in); break; + case 13: index = 2, rows = job_rows(n_in); break; + case 14: index = 3, rows = job_rows(n_in); break; + default: return false; + } + if (n_in % (types[i] == 8 ? 32 : 256)) return false; + if (jobs.n_out[i] <= 0) throw std::invalid_argument("native_mmvq_jobs_mixed requires n_out > 0"); + validate_pointer(jobs.w[i]); + validate_pointer(jobs.x[i]); + validate_pointer(jobs.y[i]); + if (q8_packed_registry().count(jobs.w[i]) || q6_packed_registry().count(jobs.w[i])) return false; + m.kind[i] = 2 * index + rows - 1; + m.a.first[i + 1] = m.a.first[i] + (jobs.n_out[i] + rows - 1) / rows; + } + native_mmvq_jobs_mixed_kernel<<(stream)>>>( + m, n_in); + launch_check(); + return true; +#endif +} + bool native_mmvq_ids_supported(int ggml_type) { return slots_kind(ggml_type) != 0; } bool native_mmvq_ids(int ggml_type, const MmvqIds& ids, int count, int n_in, int n_out, void* stream) { diff --git a/src/kernels/iq_multi_parity.cpp b/src/kernels/iq_multi_parity.cpp index 27b06d1e4e..351dec4036 100644 --- a/src/kernels/iq_multi_parity.cpp +++ b/src/kernels/iq_multi_parity.cpp @@ -61,6 +61,7 @@ const char* name_of(int t) { case 22: return "IQ2_S"; case 23: return "IQ4_XS"; case 29: return "IQ1_M"; + case 19: return "IQ1_S"; case 42: return "Q2_0"; default: return "?"; } @@ -157,7 +158,10 @@ void check_mmvq(int t, int n_in, int n_out, cudaStream_t s, std::mt19937& rng) { } const double rel = num / (den + 1e-30); worst = std::max(worst, rel); - if (diff != 0 || !finite || !(rel < 1e-2)) { + // IQ1_S takes its delta term from the q8_1 block's float sum (ds.y, as llama.cpp does), not from the int8 + // values this reference is built from, so on 5 x 1024 it sits at ~1.07e-2: its guard is 2e-2 + const double tol = t == 19 ? 2e-2 : 1e-2; + if (diff != 0 || !finite || !(rel < tol)) { std::printf(" %-8s %5d x %5d ncols %2d: %zu outputs differ from the old kernel, ref rel %.2e%s FAIL\n", name_of(t), n_out, n_in, nc, diff, rel, finite ? "" : ", non-finite"); ++bad; @@ -289,7 +293,7 @@ float time_ms(cudaStream_t s, int it, const auto& fn) { void bench(cudaStream_t s, std::mt19937& rng) { std::printf("\n--bench: microseconds per call, old (per-column decode) / new (decode once), idle GPU assumed\n"); const int n_in = 2560, n_out = 8192, it = 200; - for (int t : {16, 17, 18, 21, 22, 29}) { + for (int t : {16, 17, 18, 21, 22, 29, 19}) { const auto w = random_rows(t, n_out, n_in, rng); uint8_t* dw = dalloc(w.size()); ck(cudaMemcpy(dw, w.data(), w.size(), cudaMemcpyHostToDevice), "w"); @@ -313,7 +317,7 @@ void bench(cudaStream_t s, std::mt19937& rng) { cudaFree(dw); cudaFree(dx); cudaFree(dxq); cudaFree(dy); } // the verify window's shape: 2560 x 640 experts, 16 groups of m entries each - for (int gu : {16, 17, 18, 21, 22, 29}) { + for (int gu : {16, 17, 18, 21, 22, 29, 19}) { std::printf("%-8s/Q2_0 grouped, 16 groups of m entries:", name_of(gu)); for (int m : {1, 2, 3, 4, 8}) { Grouped G(gu, 42, 2560, 640, std::vector(16, m), 8, rng); @@ -409,11 +413,11 @@ int main(int argc, char** argv) { cudaStream_t s; ck(cudaStreamCreate(&s), "stream"); std::mt19937 rng(18); - for (int t : {16, 17, 18, 20, 21, 22, 23, 29, 42}) { + for (int t : {16, 17, 18, 20, 21, 22, 23, 29, 19, 42}) { check_mmvq(t, 2560, 67, s, rng); // the model's n_embd; 67 rows: a partial block of 4 rows check_mmvq(t, 1024, 5, s, rng); } - for (int gu : {16, 17, 18, 21, 22, 23, 29, 42}) { + for (int gu : {16, 17, 18, 21, 22, 23, 29, 19, 42}) { for (int dt : {20, 42}) check_grouped(gu, dt, 2560, 640, s, rng); // the model's shape check_grouped(gu, 23, 1024, 512, s, rng); // IQ4_XS down needs n_ff % 256 == 0 } diff --git a/src/kernels/iq_parity.cpp b/src/kernels/iq_parity.cpp index 4bc74f64de..a55dd17e6a 100644 --- a/src/kernels/iq_parity.cpp +++ b/src/kernels/iq_parity.cpp @@ -26,7 +26,7 @@ int main(int argc, char** argv) { const std::string dir = argc > 1 ? argv[1] : "logs/iq_fixture"; - const char* names[] = {"IQ2_XXS", "IQ2_XS", "IQ2_S", "IQ3_XXS", "IQ3_S", "IQ1_M", "IQ4_NL", "IQ4_XS", "Q2_0", "Q3_K"}; + const char* names[] = {"IQ2_XXS", "IQ2_XS", "IQ2_S", "IQ3_XXS", "IQ3_S", "IQ1_M", "IQ1_S", "IQ4_NL", "IQ4_XS", "Q2_0", "Q3_K"}; int failures = 0, missing = 0; cudaStream_t s; cudaStreamCreate(&s); diff --git a/src/poly/cpu_experts.cpp b/src/poly/cpu_experts.cpp index 345a3e3323..d386e29d91 100644 --- a/src/poly/cpu_experts.cpp +++ b/src/poly/cpu_experts.cpp @@ -1,5 +1,6 @@ // src/poly/cpu_experts.cpp - see the header. #include "cpu_experts.hpp" +#include "cpu_lowbit.hpp" #include "ggml.h" #include "ggml-cpu.h" @@ -141,7 +142,8 @@ bool cpu_expert_types_ok(int gu_type, int d_type, int n_embd, int n_ff, std::str void cpu_experts(Workers& workers, const CpuExpert* experts, int n, int rows, int gu_type, int u_type, int d_type, int n_embd, int n_ff, const float* x, float limit, bool gelu, float* out, - const std::function* meanwhile, const uint8_t* late, const std::function* wait) { + const std::function* meanwhile, const uint8_t* late, const std::function* wait, + const Situ* situ, bool lowbit) { init_once(); const ggml_type_traits_cpu* tg = traits(gu_type); const ggml_type_traits_cpu* tu = traits(u_type); @@ -153,6 +155,12 @@ void cpu_experts(Workers& workers, const CpuExpert* experts, int n, int rows, in const size_t au_bytes = ggml_row_size(tu->vec_dot_type, n_embd); const size_t h_bytes = ggml_row_size(td->vec_dot_type, n_ff); const bool own_act = tu->vec_dot_type != tg->vec_dot_type; // up's dot product takes another quantization + // the dot products: with `lowbit` cpu_lowbit.cpp's for Q2_0 and IQ1_S (on the same activations), else ggml's + const auto dot_of = [lowbit](int type, const ggml_type_traits_cpu* t) { + const ggml_vec_dot_t f = lowbit ? lowbit_vec_dot(type) : nullptr; + return f ? f : t->vec_dot; + }; + const ggml_vec_dot_t gdot = dot_of(gu_type, tg), udot = dot_of(u_type, tu), ddot = dot_of(d_type, td); // The workers get these through the pointers below: a thread_local named in their code would be their own. static thread_local std::vector act, act_u, hq; @@ -212,10 +220,16 @@ void cpu_experts(Workers& workers, const CpuExpert* experts, int n, int rows, in const uint8_t* a = actp + (size_t) experts[j].row * a_bytes; const uint8_t* au = actup + (size_t) experts[j].row * au_step; float g = 0.f, u = 0.f; - tg->vec_dot(n_embd, &g, 0, gate, 0, a, 0, 1); - tu->vec_dot(n_embd, &u, 0, up, 0, au, 0, 1); + gdot(n_embd, &g, 0, gate, 0, a, 0, 1); + udot(n_embd, &u, 0, up, 0, au, 0, 1); g *= e.gate_scale; u *= e.up_scale; + if (situ) { + const float gated = situ->beta * std::tanh(g / situ->beta) / (1.f + std::exp(-g)); + const float lin = situ->lin_beta > 0.f ? situ->lin_beta * std::tanh(u / situ->lin_beta) : u; + hp[(size_t) j * n_ff + r] = gated * lin; + continue; + } if (gelu) { hp[(size_t) j * n_ff + r] = 0.5f * g * (1.f + std::tanh(0.7978845608f * g * (1.f + 0.044715f * g * g))) * u; @@ -241,7 +255,7 @@ void cpu_experts(Workers& workers, const CpuExpert* experts, int n, int rows, in for (int u = 0; u < n_run; ++u) { const uint8_t* down = experts[byp[runp[u]]].down + (size_t) r * d_row; for (int i = runp[u]; i < runp[u + 1]; ++i) - td->vec_dot(n_ff, s + byp[i], 0, down, 0, hqp + (size_t) byp[i] * h_bytes, 0, 1); + ddot(n_ff, s + byp[i], 0, down, 0, hqp + (size_t) byp[i] * h_bytes, 0, 1); } // a token's sum in the order its experts were given: the order it has in a call of its own int j = 0; diff --git a/src/poly/cpu_experts.hpp b/src/poly/cpu_experts.hpp index 2a23e52660..520e95dc71 100644 --- a/src/poly/cpu_experts.hpp +++ b/src/poly/cpu_experts.hpp @@ -60,6 +60,10 @@ struct CpuExpert { /// Checks that ggml-cpu has a dot product for both types. Call once per layer format at load. bool cpu_expert_types_ok(int gu_type, int d_type, int n_embd, int n_ff, std::string& err); +/// cpu_experts()'s SiTU activation (llama.cpp's LLM_FFN_SITU, Inkling 2's): its beta and linear beta. +struct Situ { + float beta = 0, lin_beta = 0; +}; /// For each of `rows` tokens, with n_embd values of x and of out each: /// out = sum over the token's experts of weight * down(silu(min(gate x, limit)) * clamp(up x, -limit, limit)), @@ -70,9 +74,12 @@ bool cpu_expert_types_ok(int gu_type, int d_type, int n_embd, int n_ff, std::str /// u_type is up's type: gate's in every file but the few that quantize the two apart. /// `late`, when given, marks the experts whose weights are still being read: their products come after the others', /// and `wait(j)` is called before experts[j]'s are read. The sums are as without them. +/// `situ`, when given, is the activation in place of both (llama.cpp's LLM_FFN_SITU, Inkling 2's): +/// beta * tanh(g / beta) * sigmoid(g) * lin_beta * tanh(u / lin_beta), with u as it is when lin_beta <= 0. +/// `lowbit`: Q2_0's and IQ1_S's dot products are cpu_lowbit.hpp's where the CPU has them, else ggml's. void cpu_experts(Workers& workers, const CpuExpert* experts, int n, int rows, int gu_type, int u_type, int d_type, int n_embd, int n_ff, const float* x, float limit, bool gelu, float* out, const std::function* meanwhile = nullptr, const uint8_t* late = nullptr, - const std::function* wait = nullptr); + const std::function* wait = nullptr, const Situ* situ = nullptr, bool lowbit = false); } // namespace strata::poly diff --git a/src/poly/cpu_lowbit.cpp b/src/poly/cpu_lowbit.cpp new file mode 100644 index 0000000000..ce0f268428 --- /dev/null +++ b/src/poly/cpu_lowbit.cpp @@ -0,0 +1,197 @@ +// src/poly/cpu_lowbit.cpp - see the header. The kernels are compiled for AVX2 + FMA + F16C by target attribute +// and chosen at run time, so a build for older CPUs never runs them; a build for another architecture has none. +// +// IQ1_S: ggml-cpu's AVX2 vec_dot_iq1_s_q8_K (ggml/src/ggml-cpu/arch/x86/quants.c, MIT) with the same integer sums +// and float steps, but without BMI2's pdep, which Zen 1 and 2 run in microcode (~250 cycles each, two per 64 +// values). Q2_0: ggml's generic vec_dot_q2_0_q8_0 (ggml-cpu/quants.c) in AVX2. +#include "cpu_lowbit.hpp" + +#if defined(__x86_64__) || defined(_M_X64) +#define STRATA_LOWBIT_X86 1 +#endif + +#if STRATA_LOWBIT_X86 +#include + +#include +#include +#include + +#define GGML_COMMON_DECL_CPP +#define GGML_COMMON_IMPL_CPP +#include "ggml-common.h" + +#if defined(__GNUC__) || defined(__clang__) +#define LOWBIT_FN __attribute__((target("avx2,fma,f16c"))) +#else +#define LOWBIT_FN +#endif +#endif + +namespace strata::poly { +#if STRATA_LOWBIT_X86 +namespace { + +#if defined(_MSC_VER) && !defined(__clang__) +// MSVC has no _cvtsh_ss: the same F16C conversion through the vector intrinsic. +inline float h2f(uint16_t h) { return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128(h))); } +#else +LOWBIT_FN inline float h2f(uint16_t h) { return _cvtsh_ss(h); } +#endif + +LOWBIT_FN inline float hsum_float_8(const __m256 x) { // ggml's + __m128 res = _mm256_extractf128_ps(x, 1); + res = _mm_add_ps(res, _mm256_castps256_ps128(x)); + res = _mm_add_ps(res, _mm_movehl_ps(res, res)); + res = _mm_add_ss(res, _mm_movehdup_ps(res)); + return _mm_cvtss_f32(res); +} + +LOWBIT_FN inline __m256i mul_add_epi8(const __m256i x, const __m256i y) { // ggml's: pairs of x * y in int16 + const __m256i ax = _mm256_sign_epi8(x, x); + const __m256i sy = _mm256_sign_epi8(y, x); + return _mm256_maddubs_epi16(ax, sy); +} + +// ---- Q2_0 x Q8_0 ------------------------------------------------------------------------------------------------- + +// One Q8_0 block's 8 partial sums of (code - 1) * q, the block's 32 codes in the 8 bytes at `codes` (value +// 4i + m in byte i, bits 2m). The activation's bytes go to "plane" order inside each 128-bit half (dword m holds +// values 4i + m, i = 0..3: one pshufb), where the codes of a plane are a byte shifted by 2m and masked: no +// interleave. sum (c - 1) q = sum c q - sum q, both in int16 pairs (|pair| <= 6 * 127), then madd. +LOWBIT_FN inline __m256i q8_block_sums(const uint8_t* codes, const int8_t* q) { + const __m256i plane = _mm256_setr_epi8(0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, + 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15); + const __m256i qp = _mm256_shuffle_epi8(_mm256_loadu_si256((const __m256i*) q), plane); + uint64_t c8; + std::memcpy(&c8, codes, 8); + const __m256i cb = _mm256_permutevar8x32_epi32(_mm256_castsi128_si256(_mm_cvtsi64_si128((long long) c8)), + _mm256_setr_epi32(0, 0, 0, 0, 1, 1, 1, 1)); + const __m256i c = _mm256_and_si256(_mm256_srlv_epi32(cb, _mm256_setr_epi32(0, 2, 4, 6, 0, 2, 4, 6)), + _mm256_set1_epi8(3)); + const __m256i cq = _mm256_maddubs_epi16(c, qp); + const __m256i sq = _mm256_maddubs_epi16(_mm256_set1_epi8(1), qp); + return _mm256_madd_epi16(_mm256_sub_epi16(cq, sq), _mm256_set1_epi16(1)); +} + +// As ggml's AVX2 dot products of the other types do it: each Q8_0 block's 8 partial sums go into an 8-lane float +// accumulator with the block's two scales, fma(d_x * d_y, float(sums), acc), and the lanes are added once at the +// end. The last bits differ from ggml's generic C (the sums go in another order). +LOWBIT_FN void vec_dot_q2_0_q8_0(int n, float* s, size_t, const void* vx, size_t, const void* vy, size_t, int) { + const int nb = n / QK2_0; + const block_q2_0* x = (const block_q2_0*) vx; + const block_q8_0* y = (const block_q8_0*) vy; + __m256 acc0 = _mm256_setzero_ps(), acc1 = _mm256_setzero_ps(); + for (int i = 0; i < nb; ++i) { + const float d0 = h2f(x[i].d); + const __m256 s0 = _mm256_cvtepi32_ps(q8_block_sums(x[i].qs, y[2 * i].qs)); + const __m256 s1 = _mm256_cvtepi32_ps(q8_block_sums(x[i].qs + 8, y[2 * i + 1].qs)); + acc0 = _mm256_fmadd_ps(_mm256_set1_ps(d0 * h2f(y[2 * i].d)), s0, acc0); + acc1 = _mm256_fmadd_ps(_mm256_set1_ps(d0 * h2f(y[2 * i + 1].d)), s1, acc1); + } + *s = hsum_float_8(_mm256_add_ps(acc0, acc1)); +} + +// ---- IQ1_S x Q8_K ------------------------------------------------------------------------------------------------ + +// ggml's AVX2 kernel with its scalar parts done in vectors, the same integers and the same float steps: +// * the 32 grid indices of a block, qs[k] | ((qh[k / 4] >> 3 (k % 4)) & 7) << 8, as 16-bit lanes at once (left +// shifts by multiplies: qh << 8, << 5, << 2 by mullo, qh >> 1 by mulhi), then read out for the table loads (scalar +// loads: AVX2's gathers took 1.25x as long on Zen 2); +// * sumi1, the delta term: sum over the 8 groups of (bsums[2g] + bsums[2g + 1]) * (+-1) * ls, one madd of the +// bsums, one product with the signed scales and a sum, an exact integer as ggml's scalar loop's. +LOWBIT_FN void vec_dot_iq1_s_q8_K(int n, float* s, size_t, const void* vx, size_t, const void* vy, size_t, int) { + const block_iq1_s* x = (const block_iq1_s*) vx; + const block_q8_K* y = (const block_q8_K*) vy; + const int nb = n / QK_K; + __m256 accum = _mm256_setzero_ps(); + float accum1 = 0; + // a group's qh four times: 16-bit lane k of the 16 holds qh[k / 4] (one half of the block's 8 groups) + const __m256i rep4 = _mm256_setr_epi8(0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 2, 3, 2, 3, 2, 3, + 4, 5, 4, 5, 4, 5, 4, 5, 6, 7, 6, 7, 6, 7, 6, 7); + const __m256i mul_lo = _mm256_setr_epi16(256, 32, 4, 0, 256, 32, 4, 0, 256, 32, 4, 0, 256, 32, 4, 0); + const __m256i mul_hi = _mm256_setr_epi16(0, 0, 0, -32768, 0, 0, 0, -32768, 0, 0, 0, -32768, 0, 0, 0, -32768); + const __m256i m700 = _mm256_set1_epi16(0x700); + for (int i = 0; i < nb; ++i) { + const int8_t* q8 = y[i].qs; + const uint16_t* qh = x[i].qh; + alignas(32) uint16_t idx[32]; + { + const __m128i qh8 = _mm_loadu_si128((const __m128i*) qh); // the 8 groups' qh + const __m256i h0 = _mm256_shuffle_epi8(_mm256_broadcastsi128_si256(qh8), rep4); // groups 0..3 + const __m256i h1 = _mm256_shuffle_epi8(_mm256_broadcastsi128_si256(_mm_srli_si128(qh8, 8)), rep4); + const __m256i q0 = _mm256_cvtepu8_epi16(_mm_loadu_si128((const __m128i*) x[i].qs)); + const __m256i q1 = _mm256_cvtepu8_epi16(_mm_loadu_si128((const __m128i*) (x[i].qs + 16))); + const __m256i i0 = _mm256_or_si256( + q0, _mm256_and_si256(_mm256_or_si256(_mm256_mullo_epi16(h0, mul_lo), _mm256_mulhi_epu16(h0, mul_hi)), + m700)); + const __m256i i1 = _mm256_or_si256( + q1, _mm256_and_si256(_mm256_or_si256(_mm256_mullo_epi16(h1, mul_lo), _mm256_mulhi_epu16(h1, mul_hi)), + m700)); + _mm256_store_si256((__m256i*) idx, i0); + _mm256_store_si256((__m256i*) (idx + 16), i1); + } + __m256i sumi = _mm256_setzero_si256(); +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC unroll 4 +#endif + for (int ib = 0; ib < QK_K / 32; ib += 2) { + const uint16_t* id = idx + 4 * ib; + const __m256i q1b_1 = + _mm256_set_epi64x(iq1s_grid[id[3]], iq1s_grid[id[2]], iq1s_grid[id[1]], iq1s_grid[id[0]]); + const __m256i q1b_2 = + _mm256_set_epi64x(iq1s_grid[id[7]], iq1s_grid[id[6]], iq1s_grid[id[5]], iq1s_grid[id[4]]); + const __m256i q8b_1 = _mm256_loadu_si256((const __m256i*) (q8 + 32 * ib)); + const __m256i q8b_2 = _mm256_loadu_si256((const __m256i*) (q8 + 32 * ib + 32)); + const __m256i dot1 = mul_add_epi8(q1b_1, q8b_1); + const __m256i dot2 = mul_add_epi8(q1b_2, q8b_2); + const int16_t ls1 = 2 * ((qh[ib + 0] >> 12) & 7) + 1; + const int16_t ls2 = 2 * ((qh[ib + 1] >> 12) & 7) + 1; + const __m256i p1 = _mm256_madd_epi16(dot1, _mm256_set1_epi16(ls1)); + const __m256i p2 = _mm256_madd_epi16(dot2, _mm256_set1_epi16(ls2)); + sumi = _mm256_add_epi32(sumi, _mm256_add_epi32(p1, p2)); + } + int sumi1; + { + const __m256i gs = _mm256_madd_epi16(_mm256_loadu_si256((const __m256i*) y[i].bsums), _mm256_set1_epi16(1)); + const __m256i h = _mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i*) qh)); + const __m256i ls = _mm256_add_epi32(_mm256_slli_epi32(_mm256_and_si256(_mm256_srli_epi32(h, 12), + _mm256_set1_epi32(7)), 1), + _mm256_set1_epi32(1)); + const __m256i sl = _mm256_sign_epi32(ls, _mm256_sub_epi32(_mm256_set1_epi32(1), + _mm256_slli_epi32(_mm256_srli_epi32(h, 15), 1))); + const __m256i pr = _mm256_mullo_epi32(gs, sl); + const __m128i t = _mm_add_epi32(_mm256_castsi256_si128(pr), _mm256_extracti128_si256(pr, 1)); + const __m128i u = _mm_add_epi32(t, _mm_unpackhi_epi64(t, t)); + sumi1 = _mm_cvtsi128_si32(_mm_add_epi32(u, _mm_shuffle_epi32(u, 1))); + } + const float d = y[i].d * h2f(x[i].d); + accum = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(sumi), accum); + accum1 = std::fmaf(d, (float) sumi1, accum1); + } + *s = std::fmaf(IQ1S_DELTA, accum1, hsum_float_8(accum)); +} + +bool cpu_ok() { +#if defined(__GNUC__) || defined(__clang__) + static const bool ok = __builtin_cpu_supports("avx2") && __builtin_cpu_supports("fma") && + __builtin_cpu_supports("f16c"); + return ok; +#else + return false; +#endif +} + +} // namespace + +ggml_vec_dot_t lowbit_vec_dot(int type) { + if (!cpu_ok()) return nullptr; + if (type == GGML_TYPE_Q2_0) return &vec_dot_q2_0_q8_0; + if (type == GGML_TYPE_IQ1_S) return &vec_dot_iq1_s_q8_K; + return nullptr; +} +#else +ggml_vec_dot_t lowbit_vec_dot(int) { return nullptr; } +#endif + +} // namespace strata::poly diff --git a/src/poly/cpu_lowbit.hpp b/src/poly/cpu_lowbit.hpp new file mode 100644 index 0000000000..f9f62c06fd --- /dev/null +++ b/src/poly/cpu_lowbit.hpp @@ -0,0 +1,16 @@ +// src/poly/cpu_lowbit.hpp - AVX2 dot products for two expert types whose ggml-cpu ones are slow on x86: +// Q2_0 x Q8_0: ggml-cpu has only the generic C one; +// IQ1_S x Q8_K: ggml-cpu's AVX2 one takes BMI2's pdep, which Zen 1 and 2 run in microcode. +// Both take ggml's own blocks and its activation formats (vec_dot_type Q8_0 / Q8_K, quantized by ggml), and have +// ggml's vec_dot signature, so cpu_experts.cpp calls them where it called ggml's. +#pragma once + +#include "ggml-cpu.h" + +namespace strata::poly { + +/// This file's dot product for ggml type `type` (GGML_TYPE_Q2_0 or GGML_TYPE_IQ1_S), or null: for any other type, +/// and on a CPU without AVX2, FMA and F16C (or not x86). +ggml_vec_dot_t lowbit_vec_dot(int type); + +} // namespace strata::poly diff --git a/src/poly/cpu_lowbit_test.cpp b/src/poly/cpu_lowbit_test.cpp new file mode 100644 index 0000000000..8f2b95ee9d --- /dev/null +++ b/src/poly/cpu_lowbit_test.cpp @@ -0,0 +1,172 @@ +// src/poly/cpu_lowbit_test.cpp - cpu_lowbit.cpp's Q2_0 and IQ1_S dot products against the dequantized rows in +// double precision; and, with `bench`, their speed against ggml-cpu's from memory (a buffer much larger than the +// caches), one thread and all of them, one token and four. +// +// usage: poly_cpu_lowbit_test [bench [threads...]] (exit 0: every check passes; 77: no AVX2/FMA/F16C) +#include "cpu_lowbit.hpp" + +#include "ggml.h" +#include "ggml-cpu.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace strata::poly; + +int failures = 0; +std::mt19937 rng(7); + +const ggml_type_traits_cpu* cpu(ggml_type t) { return ggml_get_type_traits_cpu(t); } + +// random rows of a type: random code bytes, and block scales of a realistic size +std::vector random_rows(ggml_type t, int n, int rows) { + const size_t rb = ggml_row_size(t, n); + std::vector w(rb * rows); + std::uniform_int_distribution byte(0, 255); + for (auto& b : w) b = (uint8_t) byte(rng); + const size_t bb = ggml_type_size(t); + std::uniform_real_distribution sc(0.002f, 0.05f); + for (size_t off = 0; off + bb <= w.size(); off += bb) { + const ggml_fp16_t d = ggml_fp32_to_fp16(sc(rng)); + std::memcpy(&w[off], &d, 2); // d is the first field of q2_0, iq1_s, q4_0 and q5_0 + } + return w; +} + +std::vector activation(ggml_type wt, const std::vector& x) { + const ggml_type at = cpu(wt)->vec_dot_type; + std::vector a(ggml_row_size(at, (int64_t) x.size())); + cpu(at)->from_float(x.data(), a.data(), (int64_t) x.size()); + return a; +} + +void parity(ggml_type t, int n, int rows) { + const ggml_vec_dot_t mine = lowbit_vec_dot(t); + const auto w = random_rows(t, n, rows); + std::normal_distribution nd(0.f, 1.f); + std::vector x(n); + for (float& v : x) v = nd(rng); + const auto a = activation(t, x); + // the activation as the dot products see it + std::vector ax(n), wx(n); + if (cpu(t)->vec_dot_type == GGML_TYPE_Q8_K) { // ggml-base has no to_float for Q8_K: d (float), 256 codes, sums + const size_t bb = ggml_type_size(GGML_TYPE_Q8_K); + for (int b = 0; b < n / 256; ++b) { + float d; + std::memcpy(&d, a.data() + b * bb, 4); + for (int i = 0; i < 256; ++i) ax[b * 256 + i] = d * (float) (int8_t) a[b * bb + 4 + i]; + } + } else { + ggml_get_type_traits(cpu(t)->vec_dot_type)->to_float(a.data(), ax.data(), n); + } + const size_t rb = ggml_row_size(t, n); + double max_rel = 0; + for (int r = 0; r < rows; ++r) { + float got = 0; + mine(n, &got, 0, w.data() + r * rb, 0, a.data(), 0, 1); + ggml_get_type_traits(t)->to_float(w.data() + r * rb, wx.data(), n); + double d = 0, mag = 0; + for (int i = 0; i < n; ++i) d += double(wx[i]) * ax[i], mag += std::fabs(double(wx[i]) * ax[i]); + max_rel = std::max(max_rel, std::fabs(got - d) / std::max(mag, 1e-30)); + } + const bool ok = max_rel < 1e-5; + if (!ok) ++failures; + std::printf("%-8s n=%-5d %5d rows: max |dot - dequantized dot| / sum|terms| %.2e %s\n", ggml_type_name(t), n, + rows, max_rel, ok ? "ok" : "FAIL"); +} + +// GB/s of the weights' bytes: `threads` threads each walking its share of rows of a buffer of `bytes`, `tokens` +// activations a row (the rows a pool task takes, as cpu_experts does: a row, then every token of it) +double bench(ggml_type t, ggml_vec_dot_t dot, int n, size_t bytes, int threads, int tokens) { + const size_t rb = ggml_row_size(t, n); + const int rows = int(bytes / rb); + static std::vector w; + w.assign(rb * rows, 0); + { + std::mt19937 g(3); + for (size_t i = 0; i < w.size(); i += 4096) w[i] = (uint8_t) g(); + const size_t bb = ggml_type_size(t); + const ggml_fp16_t d = ggml_fp32_to_fp16(0.01f); + for (size_t off = 0; off + bb <= w.size(); off += bb) std::memcpy(&w[off], &d, 2); + } + std::vector x(n, 0.5f); + const auto a = activation(t, x); + std::vector> acts(tokens, a); + auto run = [&](int th) { + float sink = 0; + // tasks of 32 rows, dealt out in turn (cpu_experts' kRowsPerTask): a row, then every token of it + for (int r0 = 32 * th; r0 < rows; r0 += 32 * threads) + for (int r = r0; r < std::min(rows, r0 + 32); ++r) + for (int k = 0; k < tokens; ++k) { + float s; + dot(n, &s, 0, w.data() + (size_t) r * rb, 0, acts[k].data(), 0, 1); + sink += s; + } + volatile float keep = sink; + (void) keep; + }; + double best = 1e30; + for (int rep = 0; rep < 3; ++rep) { + const auto t0 = std::chrono::steady_clock::now(); + std::vector ts; + for (int i = 1; i < threads; ++i) ts.emplace_back(run, i); + run(0); + for (auto& th : ts) th.join(); + best = std::min(best, std::chrono::duration(std::chrono::steady_clock::now() - t0).count()); + } + return double(rb) * rows / best / 1e9; +} + +} // namespace + +int main(int argc, char** argv) { + ggml_cpu_init(); + if (!lowbit_vec_dot(GGML_TYPE_Q2_0) || !lowbit_vec_dot(GGML_TYPE_IQ1_S)) { + std::printf("this CPU has no AVX2/FMA/F16C: skipped\n"); + return 77; + } + parity(GGML_TYPE_Q2_0, 1152, 4000); // Inkling's down rows + parity(GGML_TYPE_Q2_0, 64, 2000); + parity(GGML_TYPE_Q2_0, 4096, 500); + parity(GGML_TYPE_IQ1_S, 2304, 4000); // Inkling's gate|up rows + parity(GGML_TYPE_IQ1_S, 256, 2000); + parity(GGML_TYPE_IQ1_S, 4096, 500); + + if (argc > 1 && std::string(argv[1]) == "bench") { + std::vector threads; + for (int i = 2; i < argc; ++i) threads.push_back(std::atoi(argv[i])); + if (threads.empty()) threads = {1, (int) std::thread::hardware_concurrency()}; + const size_t bytes = size_t(256) << 20; // 256 MiB of rows, 8 times the L3: from memory, as the experts are + struct Case { + const char* name; + ggml_type t; + ggml_vec_dot_t dot; + int n; + }; + const Case cases[] = { + {"Q2_0 ggml", GGML_TYPE_Q2_0, cpu(GGML_TYPE_Q2_0)->vec_dot, 1152}, + {"Q2_0 this AVX2", GGML_TYPE_Q2_0, lowbit_vec_dot(GGML_TYPE_Q2_0), 1152}, + {"IQ1_S ggml", GGML_TYPE_IQ1_S, cpu(GGML_TYPE_IQ1_S)->vec_dot, 2304}, + {"IQ1_S this AVX2", GGML_TYPE_IQ1_S, lowbit_vec_dot(GGML_TYPE_IQ1_S), 2304}, + {"IQ4_NL ggml (for comparison)", GGML_TYPE_IQ4_NL, cpu(GGML_TYPE_IQ4_NL)->vec_dot, 2304}, + }; + std::printf("\nGB/s of each type's own bytes\n"); + for (int tokens : {1, 4}) + for (int th : threads) + for (const Case& c : cases) + std::printf("%-32s threads %2d tokens %d: %7.2f GB/s\n", c.name, th, tokens, + bench(c.t, c.dot, c.n, bytes, th, tokens)); + } + std::printf("%s: %d failure%s\n", failures ? "FAILED" : "PASSED", failures, failures == 1 ? "" : "s"); + return failures ? 1 : 0; +} diff --git a/src/poly/dspark_parity.cpp b/src/poly/dspark_parity.cpp new file mode 100644 index 0000000000..7c76bb3bc9 --- /dev/null +++ b/src/poly/dspark_parity.cpp @@ -0,0 +1,120 @@ +// src/poly/dspark_parity.cpp - Inkling 2 Mini's DSpark drafter against llama.cpp's on the same inputs. Run by hand: +// poly_dspark_parity MODEL.gguf DRAFTER.gguf RECORD [--max-context N] [--expert-profile FILE] [--reload] +// RECORD is what llama.cpp's drafter got and gave in a run of speculative decoding: after a header of four int32 +// ('DSPK', n_embd, 4, 0), a 'B' for each of the model's calls (int32 n, n positions, n tokens, then n rows of the +// drafter's four inputs, 4 * n_embd floats a row) and a 'D' for each round of guesses (int32 pos0, the token at +// pos0, the guesses' count and the guesses, then seven rows of scores, one a slot of the block after the first). +// The calls' rows go into this engine's drafter as they are, and each round's block is guessed again: its slots' +// tokens (each the likeliest of its scores, from the guesses before) and scores are compared with llama.cpp's. +// --reload: before each round the conversation's state and rows are saved, the drafter's caches zeroed and the two +// loaded back (Inkling::spark_reload_for_test()); its lines are then the same as without it. +#include "engine.hpp" +#include "inkling.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +int32_t first_max(const float* l, int n) { return (int32_t) (std::max_element(l, l + n) - l); } + +template +void get(std::FILE* f, T* p, size_t n) { + if (std::fread(p, sizeof(T), n, f) != n) throw std::runtime_error("the record ends early"); +} + +} // namespace + +int main(int argc, char** argv) { + using namespace strata::poly; + if (argc < 4) { + std::fprintf(stderr, "usage: poly_dspark_parity MODEL.gguf DRAFTER.gguf RECORD [--max-context N] " + "[--expert-profile FILE] [--reload]\n"); + return 2; + } + try { + Options o; + o.model = argv[1]; + o.draft_model = argv[2]; + o.max_context = 4096; + bool reload = false; + for (int i = 4; i < argc; ++i) { + const std::string a = argv[i]; + if (a == "--reload") reload = true; + else if (a == "--max-context" && i + 1 < argc) o.max_context = std::atoi(argv[++i]); + else if (a == "--expert-profile" && i + 1 < argc) o.profile = argv[++i]; + else throw std::runtime_error("unknown option " + a); + } + std::unique_ptr e = Engine::open(o); + Inkling* ink = dynamic_cast(e.get()); + if (!ink) throw std::runtime_error("not an Inkling 2 model"); + const int nv = ink->n_vocab_real(); + std::FILE* f = std::fopen(argv[3], "rb"); + if (!f) throw std::runtime_error(std::string("cannot read ") + argv[3]); + int32_t hdr[4]; + get(f, hdr, 4); + const int E = hdr[1]; + if (hdr[0] != 0x4b505344 || E != e->n_embd()) throw std::runtime_error("not a record of this model"); + std::vector feats, ref((size_t) 7 * nv), mine((size_t) 7 * nv); + int rounds = 0, slots = 0, same = 0, chains = 0; + double worst = 0.0; + for (int c; (c = std::fgetc(f)) != EOF;) { + if (c == 'B') { + int32_t n; + get(f, &n, 1); + std::vector pos((size_t) n), tok((size_t) n); + get(f, pos.data(), (size_t) n); + get(f, tok.data(), (size_t) n); + feats.resize((size_t) n * 4 * E); + get(f, feats.data(), feats.size()); + for (int i = 1; i < n; ++i) + if (pos[(size_t) i] != pos[0] + i) throw std::runtime_error("a call's positions do not follow"); + ink->spark_rows_for_test(pos[0], n, feats.data()); + continue; + } + if (c != 'D') throw std::runtime_error("a bad record"); + int32_t head[3]; + get(f, head, 3); + std::vector draft((size_t) head[2]); + get(f, draft.data(), draft.size()); + get(f, ref.data(), ref.size()); + int32_t toks[8]; + if (reload) ink->spark_reload_for_test(head[0]); + const int n = ink->spark_block_for_test(head[1], head[0], 7, toks, mine.data()); + // the slots compare while the guesses before them are the same: a slot's input is the guess before it + int agree = 0; + double d = 0.0; + std::string line; + for (int i = 0; i < n; ++i) { + const float* r = ref.data() + (size_t) i * nv; + const float* m = mine.data() + (size_t) i * nv; + const int32_t rt = first_max(r, nv); + for (int j = 0; j < nv; ++j) d = std::max(d, (double) std::fabs(r[j] - m[j])); + ++slots; + line += " " + std::to_string(rt) + (rt == toks[i] ? "=" : "/" + std::to_string(toks[i])); + if (rt != toks[i]) break; + ++agree; + } + same += agree; + chains += agree == n; + worst = std::max(worst, d); + ++rounds; + std::printf("pos %d anchor %d: %d of %d slots, max |d logit| %.4f:%s\n", head[0], head[1], agree, n, d, + line.c_str()); + } + std::fclose(f); + std::printf("%d rounds: %d of %d slots compared gave llama.cpp's token, %d rounds all 7; worst |d logit| " + "%.4f\n", + rounds, same, slots, chains, worst); + return 0; + } catch (const std::exception& ex) { + std::fprintf(stderr, "poly_dspark_parity: %s\n", ex.what()); + return 1; + } +} diff --git a/src/poly/engine.cpp b/src/poly/engine.cpp index 92da58f019..1064879849 100644 --- a/src/poly/engine.cpp +++ b/src/poly/engine.cpp @@ -9,9 +9,13 @@ #include "kolibri1.hpp" #include "lfm2moe.hpp" #include "flint.hpp" +#if !defined(STRATA_GPU_METAL) +#include "inkling.hpp" +#endif #include "mmq.hpp" #include "qwen35.hpp" #include "runtime.hpp" +#include "strata/poly/inkling_kernels.hpp" #include "strata/poly/kernels.hpp" #if defined(STRATA_GPU_METAL) #include "strata/core/conversation_memory.hpp" @@ -118,15 +122,46 @@ int usable_cpus(bool* quota_set = nullptr) { return (int) std::max(n, 1LL); } +// The physical cores of the CPUs this process may use, or 0 when the topology cannot be read: a core's CPUs are +// counted once, by the first CPU of its list. +int physical_cores() { +#ifdef __linux__ + cpu_set_t may, cores; + if (sched_getaffinity(0, sizeof(may), &may) != 0) return 0; + CPU_ZERO(&cores); + for (int c = 0; c < CPU_SETSIZE; ++c) { + if (!CPU_ISSET(c, &may)) continue; + char path[96]; + std::snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%d/topology/core_cpus_list", c); + FILE* f = std::fopen(path, "r"); + if (!f) { + std::snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", c); + f = std::fopen(path, "r"); + } + if (!f) return 0; + int first = -1; + const bool read = std::fscanf(f, "%d", &first) == 1; + std::fclose(f); + if (!read || first < 0 || first >= CPU_SETSIZE) return 0; + CPU_SET(first, &cores); + } + return CPU_COUNT(&cores); +#else + return 0; +#endif +} + // The CPU threads when --threads names none: 70% of the usable CPUs, so that the PC's other programs keep the // rest. With a thread for every CPU the CPU was 90 to 94% busy while an answer was written, on 16 cores of a // Xeon beside a card held to 8 GB; 22 threads of 32 left it 66% busy, wrote as fast, and 19 to 23% faster // beside another program's load on 8 CPUs, since a layer waits for its slowest thread and a thread that has to // share its CPU is the slowest. A container with a CPU quota keeps them all: that is a server with no desktop // to leave CPU to, and GLM 5.3 Flash's CPU experts there take 15 ms a token with 18 threads where 12.8 with 24. -int default_threads() { +// With `by_cores` (Engine::thread_a_core()), one a physical core of them, or that rule when the cores are unknown. +int default_threads(bool by_cores) { bool quota = false; const int n = usable_cpus("a); + if (const int cores = by_cores ? physical_cores() : 0; cores > 0) return std::min(cores, n); return quota ? n : std::max(1, (n * 7 + 5) / 10); } @@ -422,6 +457,12 @@ float largest(const float* x, int n) { // The CUDA calls of a card's engine go to its card: a split's engines share the caller's thread (but in read()), // and the card is the thread's. Back to the caller's card at the end. One engine alone changes nothing. +// A flag that holds for part of a call, false again when the call ends, also when it is cut short. +struct Until { + bool& on; + ~Until() { on = false; } +}; + class OnCard { public: OnCard(int device, bool split) : split_(split) { @@ -471,9 +512,13 @@ class Behind { // The first layer of each card's share of n_layer layers, for Options::layer_split on `cards` cards; empty: no // split. "auto" shares the layers' bytes out by each card's free VRAM, less what every card's engine takes beside // its layers and, on the last card, the output and the draft block. Then every card caches about the same share -// of its layers' experts, which is where a byte of VRAM on one is worth as much as on another. -std::vector layer_starts(const std::string& split, const Shards& file, int n_layer, int cards) { +// of its layers' experts, which is where a byte of VRAM on one is worth as much as on another. No card starts +// inside [keep_lo, keep_hi) but at keep_lo: those layers run on one card (Inkling's loop); "auto" takes the +// nearer of keep_lo and keep_hi by the layers' bytes. +std::vector layer_starts(const std::string& split, const Shards& file, int n_layer, int cards, int keep_lo = 0, + int keep_hi = 0) { if (split.empty() || cards < 2) return {}; + const auto inside = [&](int il) { return il > keep_lo && il < keep_hi; }; std::vector starts{0}; if (split != "auto") { for (size_t at = 0; at < split.size();) { @@ -486,6 +531,11 @@ std::vector layer_starts(const std::string& split, const Shards& file, int throw std::runtime_error("--layer-split " + split + ": the first layer of each later card, rising, " "between 1 and " + std::to_string(n_layer - 2) + " (\"auto\" shares them " "out by each card's free VRAM)"); + if (inside((int) v)) + throw std::runtime_error("--layer-split " + split + ": layers " + std::to_string(keep_lo) + " to " + + std::to_string(keep_hi - 1) + " run on one card, so a card starts at layer " + + std::to_string(keep_lo) + " or " + std::to_string(keep_hi) + + ", or outside them"); starts.push_back((int) v); at = comma + 1; } @@ -521,7 +571,18 @@ std::vector layer_starts(const std::string& split, const Shards& file, int for (int d = 1; d < cards; ++d) { share += room[(size_t) d - 1] / all_room; int il = starts.back() + 1; // card d starts where the layers before it pass the cards before it's share - while (il < n_layer - 2 * (cards - d) && before[(size_t) il] < share * before[(size_t) n_layer]) ++il; + const int most = n_layer - 2 * (cards - d); + while (il < most && before[(size_t) il] < share * before[(size_t) n_layer]) ++il; + if (inside(il)) { + const double want = share * before[(size_t) n_layer]; + const bool lo_ok = keep_lo > starts.back(), hi_ok = keep_hi <= most; + if (!lo_ok && !hi_ok) + throw std::runtime_error("layers " + std::to_string(keep_lo) + " to " + std::to_string(keep_hi - 1) + + " run on one card: there is no place for card " + std::to_string(d) + + " to start"); + il = !hi_ok || (lo_ok && want - before[(size_t) keep_lo] <= before[(size_t) keep_hi] - want) ? keep_lo + : keep_hi; + } starts.push_back(il); } return starts; @@ -652,6 +713,7 @@ Engine::~Engine() { swap_cv_.notify_all(); follower_.join(); } + if (pre_th_.joinable()) pre_th_.join(); if (swap_st_) cudaStreamSynchronize(cs(swap_st_)); if (up_) cudaStreamSynchronize(cs(up_)); if (rs_) cudaStreamSynchronize(cs(rs_)); @@ -676,7 +738,8 @@ Engine::~Engine() { for (unsigned long long h : vpool_) cuMemRelease(h); // the pool goes back to the card with the engine vpool_.clear(); for (void* p : host_allocs_) cudaFreeHost(p); - for (void* e : {ev_stage_[0], ev_stage_[1], ev_ahead_, ev_free_, ev_in_[0], ev_in_[1], ev_out_[0], ev_out_[1], ev_hr_}) + for (void* e : {ev_stage_[0], ev_stage_[1], ev_ahead_, ev_free_, ev_pre_[0], ev_pre_[1], ev_in_[0], ev_in_[1], + ev_out_[0], ev_out_[1], ev_hr_}) if (e) cudaEventDestroy((cudaEvent_t) e); for (void* e : swap_pin_ev_) if (e) cudaEventDestroy((cudaEvent_t) e); @@ -774,9 +837,35 @@ void Engine::mind_memory() { #endif } -void Engine::vmm_reserve(Mapped& m, size_t bytes) { +#ifdef STRATA_VMM_EQUAL_PIECES +// Where a reservation's pieces must all be of one size (hip_compat/cuda.h): the unit they are made of, 2 MiB like +// the pool's handles, of which vmm_reserve() reserves a whole number. +static size_t vmm_unit(size_t grain) { return up_to(size_t(2) << 20, grain); } + +// The size of every piece of a reservation of `reserved` bytes: `first`, the size of the piece it has, or for its +// first map the most units that divide the reservation and are no more than the piece asked for and the map's bytes. +// A map then covers a whole number of pieces, and the last one is no shorter than the others. +static size_t vmm_piece(size_t reserved, size_t first, size_t bytes, size_t piece, size_t unit) { + if (first) return first; + const size_t most = std::min(up_to(std::min(piece, reserved), unit), up_to(bytes, unit)) / unit; + size_t k = std::max(most, 1); + while (k > 1 && (reserved / unit) % k != 0) --k; + return k * unit; +} +#endif + +void Engine::vmm_reserve(Mapped& m, size_t bytes, size_t piece) { CUdeviceptr p = 0; +#ifdef STRATA_VMM_EQUAL_PIECES + // without the pool, a whole number of the pieces vmm_map() will be asked for (vmm_piece() takes the most units + // that divide the reservation: of another size it could leave every piece one unit, a descriptor each on ROCm) + const size_t unit = pool_on_ ? pg_ : vmm_unit(grain_); + bytes = std::max(bytes, 1); + m.reserved = up_to(bytes, pool_on_ ? unit : up_to(std::min(piece, up_to(bytes, unit)), unit)); +#else + (void) piece; m.reserved = up_to(std::max(bytes, 1), pool_on_ ? pg_ : grain_); // a whole number of pool handles +#endif cu_ck(cuMemAddressReserve(&p, m.reserved, 0, 0, 0), "reserving addresses for VRAM"); m.base = p; } @@ -874,7 +963,13 @@ void Engine::vmm_map(Mapped& m, size_t bytes, size_t piece, const char* what) { // With the pool a piece is one of its handles and comes from it, never from the card; a map it cannot serve // throws as a card that has no more VRAM does if (pool_on_) piece = pg_; +#ifdef STRATA_VMM_EQUAL_PIECES + if (!pool_on_) + piece = vmm_piece(m.reserved, m.pieces.empty() ? 0 : m.pieces.front().second, bytes, piece, vmm_unit(grain_)); + bytes = std::min(up_to(bytes, piece), m.reserved); +#else bytes = std::min(up_to(bytes, pool_on_ ? pg_ : grain_), m.reserved); +#endif CUmemAllocationProp prop = {}; prop.type = CU_MEM_ALLOCATION_TYPE_PINNED; prop.location.type = CU_MEM_LOCATION_TYPE_DEVICE; @@ -1197,7 +1292,7 @@ void* Engine::kv_alloc(size_t bytes, int per) { Kv k; k.bytes = bytes; k.per = per; - vmm_reserve(k, all); + vmm_reserve(k, all, (size_t) ((kKvGrow + per - 1) / per) * bytes); // cover()'s pieces kv_.push_back(std::move(k)); p = (void*) kv_.back().base; } @@ -1329,7 +1424,15 @@ void Engine::cover(int64_t end) { const auto size = [rows](const Kv& k) { return (size_t) ((rows + k.per - 1) / k.per) * k.bytes; }; size_t more = 0, held = arena_.mapped + other_rows(); for (const Kv& k : kv_) { +#ifdef STRATA_VMM_EQUAL_PIECES + // what vmm_map() below maps: whole pieces + const size_t piece = pool_on_ ? pg_ + : vmm_piece(k.reserved, k.pieces.empty() ? 0 : k.pieces.front().second, size(k), + (size_t) ((kKvGrow + k.per - 1) / k.per) * k.bytes, vmm_unit(grain_)); + const size_t want = std::min(up_to(size(k), piece), k.reserved); +#else const size_t want = std::min(up_to(size(k), pool_on_ ? pg_ : grain_), k.reserved); +#endif if (want > k.mapped) more += want - k.mapped; // trim_card_kv() leaves a piece it cuts through held += k.mapped; } @@ -1561,9 +1664,10 @@ void Engine::load_shape() { // A MoE layer: its router and shared expert to VRAM, and its routed experts' places in the file, where they // stay; fill_expert_cache() copies the ones VRAM has room for. A file may keep an expert's gate and up in one // tensor, the gate's rows first. -void Engine::load_moe(int il, bool shared) { +void Engine::load_moe(int il, bool shared, int from, bool any_type_scales) { Layer& L = layers_[(size_t) il]; - auto mat = [&](const char* n, int64_t a, int64_t b) { return upload(tensor(il, n), blk(il, n), a, b, kAnyMat); }; + const int src = from < 0 ? il : from; + auto mat = [&](const char* n, int64_t a, int64_t b) { return upload(tensor(src, n), blk(src, n), a, b, kAnyMat); }; L.moe = true; L.gate_inp = mat("ffn_gate_inp.weight", n_embd_, n_expert_); if (shared) { @@ -1573,8 +1677,8 @@ void Engine::load_moe(int il, bool shared) { } auto exps = [&](const char* n, int64_t n_in, int64_t rows) -> const TensorInfo& { - const TensorInfo* t = tensor(il, n); - if (!t) throw std::runtime_error("the GGUF has no tensor " + blk(il, n)); + const TensorInfo* t = tensor(src, n); + if (!t) throw std::runtime_error("the GGUF has no tensor " + blk(src, n)); if (t->shape.size() != 3 || (int64_t) t->shape[0] != n_in || (int64_t) t->shape[1] != rows || (int64_t) t->shape[2] != n_expert_) throw std::runtime_error(t->name + " is " + shape_of(*t) + ", expected [" + std::to_string(n_in) + ", " + @@ -1585,7 +1689,7 @@ void Engine::load_moe(int il, bool shared) { L.d_type = td.type; L.d_bytes = home(td).payload(td) / (size_t) n_expert_; L.exp_down = home(td).data(td); - if (tensor(il, "ffn_gate_up_exps.weight")) { + if (tensor(src, "ffn_gate_up_exps.weight")) { const TensorInfo& gu = exps("ffn_gate_up_exps.weight", n_embd_, 2 * n_ff_exp_); L.gu_type = gu.type; L.gu_stride = home(gu).payload(gu) / (size_t) n_expert_; @@ -1615,29 +1719,36 @@ void Engine::load_moe(int il, bool shared) { size_t(8)); L.gu_step = (L.gu_step + unit - 1) / unit * unit; } - // NVFP4 experts converted from NVIDIA's checkpoints carry each expert's global scale of gate, up and down - // (llama.cpp's ffn_*_exps_s). Gate's and up's go on their products ahead of the activation (ExpertScales), - // down's on the expert's weight in its token's sum. Only NVFP4's: Gemma 4's ffn_down_exps.scale is its own. + // Each expert's scale of its gate, up and down (llama.cpp's ffn_*_exps_s): gate's and up's go on their products + // ahead of the activation (ExpertScales), down's on the expert's weight in its token's sum. NVFP4 experts + // converted from NVIDIA's checkpoints carry them for their NVFP4 projections; a projection of another type in the + // same layer has none (Qwen3.6 NVFP4-MTP-HQ: some ups are Q4_K), and Gemma 4's ffn_down_exps.scale is its own. + // any_type_scales: every projection's, whatever its type, a joined gate and up's one scale on both (Inkling 2's). const bool nv = L.gu_type == GGML_TYPE_NVFP4 || L.u_type == GGML_TYPE_NVFP4 || L.d_type == GGML_TYPE_NVFP4; - if (nv && tensor(il, "ffn_gate_up_exps.scale")) - throw std::runtime_error(blk(il, "ffn_gate_up_exps.scale: NVFP4 scales of a joined gate and up are not supported")); - // A projection of another type in the same layer has none (Qwen3.6 NVFP4-MTP-HQ: some ups are Q4_K). + if (nv && !any_type_scales && tensor(src, "ffn_gate_up_exps.scale")) + throw std::runtime_error(blk(src, "ffn_gate_up_exps.scale: NVFP4 scales of a joined gate and up are not supported")); const auto one = [&](const char* n, uint32_t type, Dev& d, std::vector& h) { - const TensorInfo* t = tensor(il, n); + const TensorInfo* t = tensor(src, n); h.clear(); - if (type != GGML_TYPE_NVFP4 || !t) return; + if (!t || (!any_type_scales && type != GGML_TYPE_NVFP4)) return false; if (t->type != kTypeF32) throw std::runtime_error(t->name + " is not F32"); - d = upload(t, blk(il, n), n_expert_, 1, kF32); + d = upload(t, blk(src, n), n_expert_, 1, kF32); h.resize((size_t) n_expert_); std::memcpy(h.data(), home(*t).data(*t), h.size() * sizeof(float)); + return true; }; - one("ffn_gate_exps.scale", L.gu_type, L.s_gate, L.h_s_gate); - one("ffn_up_exps.scale", L.u_type, L.s_up, L.h_s_up); + if (any_type_scales && one("ffn_gate_up_exps.scale", L.gu_type, L.s_gate, L.h_s_gate)) { + L.s_up = L.s_gate; + L.h_s_up = L.h_s_gate; + } else { + one("ffn_gate_exps.scale", L.gu_type, L.s_gate, L.h_s_gate); + one("ffn_up_exps.scale", L.u_type, L.s_up, L.h_s_up); + } one("ffn_down_exps.scale", L.d_type, L.s_down, L.h_s_down); std::string err; if (!cpu_expert_types_ok((int) L.gu_type, (int) L.d_type, n_embd_, n_ff_exp_, err) || !cpu_expert_types_ok((int) L.u_type, (int) L.d_type, n_embd_, n_ff_exp_, err)) - throw std::runtime_error(blk(il, "ffn_*_exps.weight: ") + err); + throw std::runtime_error(blk(src, "ffn_*_exps.weight: ") + err); L.slot.assign((size_t) n_expert_, nullptr); ++n_moe_; } @@ -1647,11 +1758,24 @@ std::unique_ptr Engine::open(const Options& o) { const Shards file(o.model); const MetaValue* arch = file.get("general.architecture"); const std::string name = arch ? arch->s : std::string(); + // Inkling 2 (inkling2_loop; Unsloth's files: inkling2 with the loop in its metadata): the card's kernels loaded + // at once (CUDA_MODULE_LOADING=EAGER), before the expert cache takes the VRAM: loaded lazily, a kernel's code goes + // to VRAM at its first launch, which can then find none left. Set before any CUDA call (the driver reads it + // once); a value the user set is kept. + const bool inkling = name == "inkling2_loop" || (name == "inkling2" && file.get("inkling2.num_loops")); + if (inkling && !std::getenv("CUDA_MODULE_LOADING")) { +#if defined(_WIN32) + _putenv_s("CUDA_MODULE_LOADING", "EAGER"); +#else + setenv("CUDA_MODULE_LOADING", "EAGER", 0); +#endif + } // Clover is a qwen35moe model trained to also guess a block of tokens at once (Qwen35) const bool qwen35 = name == "qwen35moe" || name == "clover_moe"; - if (o.kv_format == KvFmt::kQ8_0 && !qwen35 && name != "kolibri1" && name != "flint" && name != "lfm2moe") - throw std::runtime_error("--kv q8_0 is supported for qwen35moe, kolibri1, flint and lfm2moe models in v1; " - "this is a '" + name + "' model"); + if (o.kv_format == KvFmt::kQ8_0 && !qwen35 && name != "kolibri1" && name != "flint" && name != "lfm2moe" && + !inkling) + throw std::runtime_error("--kv q8_0 is supported for qwen35moe, kolibri1, flint, lfm2moe and Inkling 2 " + "(inkling2_loop, inkling2) models in v1; this is a '" + name + "' model"); // int8 and int8k are Gemma 4's: their readers are not the arithmetic q8_0's are, so a model takes one // family or the other rather than a choice between them. if (name != "gemma4" && (o.kv_format == KvFmt::kInt8 || o.kv_format == KvFmt::kInt8K)) @@ -1668,6 +1792,14 @@ std::unique_ptr Engine::open(const Options& o) { if (name == "lfm2moe") return std::make_unique(); if (name == "flint") return std::make_unique(); if (name == "kolibri1") return std::make_unique(); +#if defined(STRATA_GPU_METAL) + if (inkling) throw std::runtime_error(o.model + " is an Inkling 2 model, which the Metal engine does not run yet"); +#elif defined(STRATA_USE_HIP) + // HIP runs it as CUDA does (an RX 9060 XT loaded UD-Q2_K_XL with all 3,072 experts in VRAM in 1.8 s) + if (inkling) return std::make_unique(); +#else + if (inkling) return std::make_unique(); +#endif throw std::runtime_error(o.model + " is a '" + name + "' model, which this engine does not run"); }; int cards = 1, devices = 1; @@ -1680,9 +1812,16 @@ std::unique_ptr Engine::open(const Options& o) { const MetaValue* blocks = file.get(name + ".block_count"); const MetaValue* nextn = file.get(name + ".nextn_predict_layers"); if (!blocks) throw std::runtime_error("the GGUF has no " + name + ".block_count"); + int n_layer = (int) blocks->u - (nextn ? (int) nextn->u : 0), keep_lo = 0, keep_hi = 0; +#if !defined(STRATA_GPU_METAL) + if (inkling) Inkling::split_layers(file, n_layer, keep_lo, keep_hi); +#endif + // its drafter reads visits of every card's (Inkling::drafter_rows()) + if (inkling && !o.draft_model.empty() && o.draft && o.window != 1) + throw std::runtime_error("Inkling 2: the DSpark drafter (--draft-model) is not for --layer-split"); int was = 0; ck(cudaGetDevice(&was), "cudaGetDevice"); - starts = layer_starts(o.layer_split, file, (int) blocks->u - (nextn ? (int) nextn->u : 0), cards); + starts = layer_starts(o.layer_split, file, n_layer, cards, keep_lo, keep_hi); ck(cudaSetDevice(was), "cudaSetDevice"); } if (starts.empty()) { @@ -1692,8 +1831,7 @@ std::unique_ptr Engine::open(const Options& o) { } // a card after another, each with the next run of layers; the last one has the output and the draft block - std::unique_ptr first; - Engine* prev = nullptr; + std::vector> parts; for (size_t k = 0; k < starts.size(); ++k) { std::unique_ptr e = make(); const bool last = k + 1 == starts.size(); @@ -1702,29 +1840,49 @@ std::unique_ptr Engine::open(const Options& o) { so.draft = false; so.draft_model.clear(); } - if (first) { - so.window = first->opt_.window; // every card's windows are the first one's - e->workers_ = first->workers_; - } + if (k > 0) so.window = parts[0]->opt_.window; // every card's windows are the first one's e->lo_ = starts[k]; e->end_ = last ? -1 : starts[k + 1]; e->split_ = true; ck(cudaSetDevice((int) k % devices), "cudaSetDevice"); try { - e->load(so); + e->load_layers(so); + } catch (const std::runtime_error& err) { + // on a card with several parts every part's layers, staging buffer and caches come before any expert + const std::string shared = k < (size_t) devices ? "" : + " (it shares a card with part " + std::to_string(k - (size_t) devices) + ", and the layers, " + "staging buffers and attention caches of both are in VRAM before any expert: give the card fewer " + "layers, a smaller --stage-mib or a shorter context)"; + throw std::runtime_error("card " + std::to_string(k) + ": " + err.what() + shared); + } + parts.push_back(std::move(e)); + } + // Then the expert caches, each of what its card has left. A card with several parts leaves the later ones + // what they need beside their layers (mates_need()). + for (size_t k = 0; k < parts.size(); ++k) { + Engine& e = *parts[k]; + for (size_t j = 0; j < parts.size(); ++j) + if (j != k && (int) j % devices == (int) k % devices) e.mates_.push_back(parts[j].get()); + if (k > 0) e.workers_ = parts[0]->workers_; + ck(cudaSetDevice((int) k % devices), "cudaSetDevice"); + try { + e.load_experts(); } catch (const std::runtime_error& err) { throw std::runtime_error("card " + std::to_string(k) + ": " + err.what()); } - Engine* at = e.get(); - if (prev) prev->next_ = std::move(e); - else first = std::move(e); - prev = at; + } + std::unique_ptr first = std::move(parts[0]); + Engine* prev = first.get(); + for (size_t k = 1; k < parts.size(); ++k) { + prev->next_ = std::move(parts[k]); + prev = prev->next_.get(); } ck(cudaSetDevice(0), "cudaSetDevice"); int k = 0; for (const Engine* e = first.get(); e; e = e->next_.get(), ++k) std::fprintf(stderr, "strata-poly: layers %d to %d on card %d: %d of %d routed experts in VRAM (%.1f GiB)\n", - e->lo_, e->hi_ - 1, k, e->cached_, e->n_moe_ * e->n_expert_, double(e->exp_at_) / double(1ull << 30)); + e->physical(e->lo_), e->physical(e->hi_ - 1), k, e->cached_, e->n_moe_ * e->n_expert_, + double(e->exp_at_) / double(1ull << 30)); return first; } @@ -1843,6 +2001,38 @@ int64_t Engine::vram_free_mib() const { return next_ ? std::min(mib, next_->vram_free_mib()) : mib; } +bool Engine::ram_is_tight() const { + const size_t ram = ram_available(), files = gg_->bytes() + (dg_ ? dg_->bytes() : 0); + return ram > 0 && files + (5ULL << 30) > ram; +} + +int Engine::reserve_for(size_t total_b, bool ram_tight) const { + // 256 MiB at least, whatever was asked: the launches recorded later take theirs out of the reserve (mind_vram()) + return opt_.vram_reserve_mib >= 0 ? std::max(opt_.vram_reserve_mib, 256) : +#if defined(STRATA_GPU_METAL) + opt_.metal_balanced ? 256 : +#endif + default_reserve_mib(total_b, ram_tight); +} + +// Several engines of a split on one card (STRATA_POLY_CARDS) share its VRAM. Each keeps its reserve free for the +// launches it records, and one without an expert cache maps its attention caches' later rows from what is free +// (cover() takes them out of a cache where there is one). Their layers, staging buffers and caches are in VRAM +// before any expert cache is filled (open()). +size_t Engine::mates_need() const { + size_t need = 0, free_b = 0, total_b = 0; + if (!mates_.empty()) ck(cudaMemGetInfo(&free_b, &total_b), "cudaMemGetInfo"); + for (const Engine* m : mates_) { + const int mib = m->reserve_mib_ > 0 ? m->reserve_mib_ : m->reserve_for(total_b, m->ram_is_tight()); + need += size_t(mib) << 20; + if (m->exp_) continue; + for (const Kv& k : m->kv_) need += k.reserved - k.mapped; + for (const Seq& q : m->seqs_) + for (const Kv& k : q.kv) need += k.reserved - k.mapped; + } + return need; +} + // Experts go to VRAM by use per byte when there are counts, the profile's and this run's, and otherwise the same // number from every layer. // @@ -1859,15 +2049,11 @@ void Engine::fill_expert_cache() { if (!opt_.gpu_experts || n_moe_ == 0) return; size_t free_b = 0, total_b = 0; ck(cudaMemGetInfo(&free_b, &total_b), "cudaMemGetInfo"); - const size_t ram = ram_available(), files = gg_->bytes() + (dg_ ? dg_->bytes() : 0); - ram_tight_ = ram > 0 && files + (5ULL << 30) > ram; - // 256 MiB at least, whatever was asked: the launches recorded later take theirs out of the reserve (mind_vram()) - reserve_mib_ = opt_.vram_reserve_mib >= 0 ? std::max(opt_.vram_reserve_mib, 256) : -#if defined(STRATA_GPU_METAL) - opt_.metal_balanced ? 256 : -#endif - default_reserve_mib(total_b, ram_tight_); - size_t reserve = size_t(reserve_mib_) << 20; + ram_tight_ = ram_is_tight(); + reserve_mib_ = reserve_for(total_b, ram_tight_); + // the other engines of a split on this card have their layers here already, and what they need beside them is + // left with the reserve + size_t reserve = (size_t(reserve_mib_) << 20) + mates_need(); // The first time the pool claims what the card has but the margin (the reserve), for the whole run, and no more // than the model can use (below, where the experts' bytes are known): from then on the cache and the rows share it. // A later call (resize_cache()) divides what the pool holds again. @@ -1878,7 +2064,16 @@ void Engine::fill_expert_cache() { free_b = vpool_bytes(); reserve = stage_map_.base ? 0 : stage_slack; } - if (!claim_later && free_b <= reserve) return; + // STRATA_GPU_EXPERTS: an N the VRAM cannot hold is refused rather than cached in part + const auto short_of = [&](size_t room, size_t need) { + if (expert_cap_ <= 0) return; + throw std::runtime_error("STRATA_GPU_EXPERTS=" + std::to_string(expert_cap_) + ": the card has " + + std::to_string(room >> 20) + " MiB for the expert cache" + + (need ? ", the first " + std::to_string(expert_cap_) + " experts take " + + std::to_string(need >> 20) + " MiB" : std::string()) + + ": lower N or --vram-reserve-mib"); + }; + if (!claim_later && free_b <= reserve) return short_of(0, 0); struct Cand { int il, e; @@ -1914,6 +2109,14 @@ void Engine::fill_expert_cache() { } std::stable_sort(cands.begin(), cands.end(), [](const Cand& a, const Cand& b) { return a.value != b.value ? a.value > b.value : a.e < b.e; }); + if (expert_cap_ >= 0) { // the first N, each in turn, and nothing but them: the cache is sized to hold them + if ((size_t) expert_cap_ > cands.size()) + throw std::runtime_error("STRATA_GPU_EXPERTS=" + std::to_string(expert_cap_) + ": the model has " + + std::to_string(cands.size()) + " experts the card can hold"); + cands.resize((size_t) expert_cap_); + all = 0; + for (const Cand& c : cands) all += c.bytes; + } n_trade_ = (int) sizes.size(); if (claim_later) { @@ -1934,7 +2137,7 @@ void Engine::fill_expert_cache() { budgeted ? "under the OS's budget for this process" : "of the card's free VRAM", limit >> 20); free_b = vpool_bytes(); reserve = stage_map_.base ? 0 : stage_slack; - if (free_b <= reserve) return; + if (free_b <= reserve) return short_of(0, 0); } // sized again (resize_cache()), it is no larger than load() made it, or than its addresses with VMM const size_t most = vmm_ ? std::min(all, total_b) : @@ -1965,13 +2168,20 @@ void Engine::fill_expert_cache() { } } #endif + if (arena < all) short_of(arena, all); if (arena == 0) return; if (vmm_) { // in pieces, so that it can give some up to the attention caches (shrink_cache()) and grow +#ifdef STRATA_VMM_EQUAL_PIECES + // a whole number of kArenaPiece, so that its pieces can all be of that size (vmm_map()) + if (!arena_.base) vmm_reserve(arena_, up_to(most + 256, kArenaPiece)); +#else if (!arena_.base) vmm_reserve(arena_, most + 256); // addresses only: grow_cache() maps more of them +#endif try { vmm_map(arena_, arena + 256, kArenaPiece, "the expert cache"); } catch (const std::runtime_error&) { // the card may not have it all (grow_cache() is just as tolerant) arena = arena_.mapped > 256 ? arena_.mapped - 256 : 0; + if (arena < all) short_of(arena, all); if (arena == 0) return; } exp_ = (uint8_t*) arena_.base; @@ -2021,6 +2231,20 @@ void Engine::fill_expert_cache() { L.slot[e] = s; ++cached_; } + // With the split held still for a comparison (STRATA_FREEZE_EXPERTS, STRATA_GPU_EXPERTS): which experts the cache + // holds, an FNV-1a hash of its (layer, expert) pairs. Experts of several sizes are taken past one that does not + // fit, so two runs can cache the same number of experts but not the same ones, and their sums then differ. + if (freeze_experts_asked_) { + uint64_t h = 14695981039346656037ULL; + int n = 0; + for (size_t il = 0; il < layers_.size(); ++il) + for (size_t e = 0; e < layers_[il].slot.size(); ++e) + if (layers_[il].slot[e]) { + for (const size_t v : {il, e}) h = (h ^ (uint32_t) v) * 1099511628211ULL; + ++n; + } + std::fprintf(stderr, "strata-poly: cache set %d experts fnv %016llx\n", n, (unsigned long long) h); + } #if defined(STRATA_GPU_METAL) if (opt_.metal_balanced) { if (arena + 256 > exp_at_) { @@ -2095,8 +2319,8 @@ void Engine::resize_cache(int mib) { void Engine::resize_card_cache(int mib) { if (!opt_.gpu_experts || n_moe_ == 0) return; // As shrink_cache(): a frozen answer's cache does not change under it (the vram API resizes between - // requests; unfreeze_experts() ends the freeze before one begins). - if (freeze_experts_) return; + // requests; unfreeze_experts() ends the freeze before one begins). STRATA_GPU_EXPERTS holds it for the run. + if (freeze_experts_ || expert_cap_ >= 0) return; OnCard here(device_, split_); #if defined(STRATA_GPU_METAL) // Every Metal graph retains its indirect resources, including in the legacy memory mode. @@ -2175,7 +2399,8 @@ bool Engine::mind_card_vram() { return true; } if (minds_++ == 0) return false; // nothing is recorded before the first request - const int64_t keep = opt_.vram_reserve_mib >= 0 || ram_tight_ ? reserve_mib_ : std::max(reserve_mib_ / 2, 128); + const int64_t keep = (opt_.vram_reserve_mib >= 0 || ram_tight_ ? reserve_mib_ : std::max(reserve_mib_ / 2, 128)) + + (int64_t) (mates_need() >> 20); if (free < keep / 2) { shrink_cache(size_t(keep - free) << 20); held_is_budget(); @@ -2367,6 +2592,57 @@ void Engine::plan_ahead(Layer& L, int il) { L.ahead.resize(std::min(L.ahead.size(), stage_bytes_ / (L.gu_step + L.d_bytes))); } +int Engine::uncached(const Layer& L) const { + return (int) std::count(L.slot.begin(), L.slot.end(), nullptr); +} + +// In a read, the experts of the next turn's layer (next_home_) that are not cached go to the staging buffer while +// the m of layer L are read there by the turn's calls: before the buffer's start if they fit there, else after +// L's. The part they take was the layer's before L, whose last call the copy waits for (ev_free_ has its mark +// until L's first call is done). Where they do not fit, the next layer copies them when it starts, as without +// this. The experts and the launches are the same either way, so the results are too. +// +// On an RTX 2070 Super (PCIe 3.0 x16), with 1,042 of Inkling 2 Mini IQ4_NL's 3,072 experts cached, a read copies +// 18.7 GB, 1.4 s at 13.1 GB/s. In a 2,048-token prompt read in 2.5 s the card still waits 0.54 s for those +// copies: the layers outside the loop have about 500 MB each not cached, and two of them together do not fit the +// 627 MB buffer. +void Engine::prestage(const Layer& L, int m, int n) { + Layer& N = layers_[(size_t) next_home_]; + if (!batched(N, n)) return; + plan_ahead(N, next_home_); + const int m2 = (int) N.ahead.size(); + if (m2 == 0 || m2 != uncached(N)) return; + const size_t span = pad((size_t) m * L.gu_step) + (size_t) m * L.d_bytes + kTail; + const size_t span2 = pad((size_t) m2 * N.gu_step) + (size_t) m2 * N.d_bytes + kTail; + const size_t room = stage_bytes_ + 256 + kTail, after = pad(stage_at_ + span); + size_t at = 0; + if (span2 > stage_at_) { + if (after + span2 > room) return; + at = after; + } + pre_.il = next_home_; + pre_.at = at; + pre_.experts = N.ahead; + pre_.ev ^= 1; + ck(cudaStreamWaitEvent(cs(up_), (cudaEvent_t) ev_free_, 0), "expert staging"); + if (!stagers_) stagers_ = std::make_unique(4); + pre_th_ = std::thread([this, &N, at, ev = ev_pre_[pre_.ev]] { + try { + cudaSetDevice(device_); // a thread starts on card 0 + stage(N, pre_.experts.data(), (int) pre_.experts.size(), up_, true, stage_ + at); + ck(cudaEventRecord((cudaEvent_t) ev, cs(up_)), "expert staging"); + } catch (...) { + pre_err_ = std::current_exception(); + } + }); +} + +// The copy prestage() started is on its way: what is left of it is the card's. +void Engine::settle_prestage() { + if (pre_th_.joinable()) pre_th_.join(); + if (pre_err_) std::rethrow_exception(std::exchange(pre_err_, nullptr)); +} + // The follower: an asked-for expert goes from the mapped file to a pinned buffer, and from there to its slot. // The file may have to be read for it, which is why this is not the engine's thread. Two buffers take turns: an // expert is copied into one while the other uploads, and the upload is the quicker of the two. (A buffer for @@ -2621,6 +2897,12 @@ void Engine::follow(int written) { } void Engine::load(const Options& o) { + load_layers(o); + load_experts(); +} + +// load() up to the expert cache: the weights in VRAM, and the caches, the scratch and the staging buffer. +void Engine::load_layers(const Options& o) { #if defined(STRATA_GPU_METAL) gpu::metal::set_optimize(o.metal_optimize); gpu::metal::set_scoped_residency(o.metal_balanced); @@ -2707,7 +2989,26 @@ void Engine::load(const Options& o) { // CPU instead (the cache holds it, but the split is the first token's). What it buys: greedy answers that // repeat bit for bit, which is what a test, a benchmark of quality or a comparison with another engine needs. freeze_experts_ = freeze_experts_asked_ = std::getenv("STRATA_FREEZE_EXPERTS") != nullptr; - if (freeze_experts_) + // STRATA_GPU_EXPERTS=N, a test knob: the expert cache holds exactly the first N experts of the order it fills + // in (the profile's), held still for the whole run - frozen, no uploads, no resize. Two builds that leave + // different VRAM free (one records more launches) would cache different numbers of experts, and their sums + // differ wherever the split does; with the same N and the same profile they hold the same set, so their + // logits can be compared byte for byte with the experts on the card. An N the card cannot hold is an error. + if (const char* v = std::getenv("STRATA_GPU_EXPERTS"); v && *v) { + char* end = nullptr; + const long n = std::strtol(v, &end, 10); + if (*end || n < 0 || n > (1L << 24)) + throw std::runtime_error(std::string("STRATA_GPU_EXPERTS=") + v + " is not a number of experts"); + if (split_) throw std::runtime_error("STRATA_GPU_EXPERTS is for one card's engine, not a split"); + expert_cap_ = (int) n; + freeze_experts_ = freeze_experts_asked_ = true; + opt_.expert_swaps = 0; + if (opt_.gpu_experts) + std::fprintf(stderr, "strata-poly: STRATA_GPU_EXPERTS=%d: the expert cache holds the first %d experts " + "in the profile's order, frozen, with no uploads and no resize, for the whole run\n", + expert_cap_, expert_cap_); + } + if (freeze_experts_ && expert_cap_ < 0) std::fprintf(stderr, "strata-poly: the experts' split is frozen for the engine's whole run " "(STRATA_FREEZE_EXPERTS): greedy answers are a function of the request alone, " "and the only cache change after load is the serve VRAM resize\n"); @@ -2726,6 +3027,16 @@ void Engine::load(const Options& o) { // allocation each (kv_alloc()) and the expert cache still gives VRAM to other programs and takes it back // (mind_vram()): refilled in one allocation instead, it only ever got smaller. ck(cudaGetDevice(&device_), "cudaGetDevice"); +#if defined(STRATA_USE_HIP) && defined(__linux__) + // ROCm keeps a file descriptor open for each VMM handle (its dmabuf, librocdxg on WSL2): with --vram-pool's + // 2 MiB handles the usual soft limit of 1,024 descriptors held an RX 9070 XT's pool to 2 GiB ("fail to import fd", + // and the map fails as a card without VRAM does). The soft limit goes up to the hard one (at most 2^20), as a + // process may, and never down. + if (rlimit r{}; getrlimit(RLIMIT_NOFILE, &r) == 0 && r.rlim_cur < r.rlim_max) { + r.rlim_cur = std::max(r.rlim_cur, std::min(r.rlim_max, rlim_t(1) << 20)); + (void) setrlimit(RLIMIT_NOFILE, &r); + } +#endif CUdevice dev = 0; int vmm = 0; if (cuDeviceGet(&dev, device_) == CUDA_SUCCESS && @@ -2798,6 +3109,11 @@ void Engine::load(const Options& o) { !split_; if (block_guess_) std::fprintf(stderr, "strata-poly: STRATA_BLOCK_GUESS: the model guesses its own blocks\n"); alloc(); +} + +// The rest of load(), from the expert cache on: it takes what the card has free once the layers, the staging +// buffer and the caches of every engine on the card are in VRAM (open()). +void Engine::load_experts() { if (!opt_.profile.empty()) read_profile(opt_.profile, (int) layers_.size(), n_expert_, prior_); fill_expert_cache(); ensure_stage(); @@ -2830,7 +3146,7 @@ void Engine::load(const Options& o) { for (const Kv& k : kv_) more += k.reserved - k.mapped; for (const Seq& q : seqs_) for (const Kv& k : q.kv) more += k.reserved - k.mapped; - if ((int64_t) ((more + kArenaPiece) >> 20) + reserve_mib_ <= vram_free_mib()) { + if ((int64_t) ((more + kArenaPiece + mates_need()) >> 20) + reserve_mib_ <= vram_free_mib()) { for (int s = sequences() - 1; s >= 0; --s) { // ends with the first one bound if (s != bound_) { park_bound(); @@ -2840,7 +3156,7 @@ void Engine::load(const Options& o) { } } } - const int threads = opt_.threads > 0 ? opt_.threads : default_threads(); + const int threads = opt_.threads > 0 ? opt_.threads : default_threads(thread_a_core()); mind_memory(); // the routed experts in the mapped files, and of them the ones the CPU reads through the mapping: those the // card does not have, as many as Options::ram_experts_mib keeps @@ -3069,7 +3385,8 @@ void Engine::alloc() { hn_ = state_ + rec_n_; h_guess_ = (Likeliest*) hmalloc(sizeof(Likeliest), "pinned memory"); // likeliest() writes it } - if (block_guess_) h_block_ = (Likeliest*) hmalloc((size_t) opt_.window * sizeof(Likeliest), "pinned memory"); + if (block_guess_ || block_drafter_) + h_block_ = (Likeliest*) hmalloc((size_t) std::max(opt_.window, 1) * sizeof(Likeliest), "pinned memory"); // window(): the state after tokens of it, for keep(), and every token's logits snap_places_ = snaps_spread() ? std::min(opt_.window - 1, kSnapPlaces) : opt_.window - 1; if (snap_places_ > 0) @@ -3108,21 +3425,33 @@ void Engine::alloc() { // A prompt batch runs a layer's routed experts through MMQ when the card has a tile for each of their types // (batched()). The model's layers: the draft block's experts never run a batch at a time. const size_t n = (size_t) rows_; - bool tiles = false, mixed_tiles = false; + bool tiles = false, mixed_tiles = false, any_tiles = false; + int n_tiled = 0, n_products = 0; size_t one_expert = 0; for (int il = 0; il < n_layer_; ++il) { Layer& L = layers_[(size_t) il]; if (!L.moe) continue; // a mixed layer multiplies gate and up apart (moe_rows()), each a matrix of n_ff rows - const bool gu_fits = L.mixed() ? Mmq::fits((int) L.gu_type, n_ff_exp_, n_embd_) && - Mmq::fits((int) L.u_type, n_ff_exp_, n_embd_) - : Mmq::fits((int) L.gu_type, 2 * n_ff_exp_, n_embd_); - L.mmq = opt_.gpu_experts && rows_ >= kStageRows && gu_fits && Mmq::fits((int) L.d_type, n_embd_, n_ff_exp_); + const Mmq::Allow ea = expert_mmq(); + const bool lb = lowbit_experts_; + const bool gu_fits = L.mixed() ? Mmq::fits((int) L.gu_type, n_ff_exp_, n_embd_, ea) && + Mmq::fits((int) L.u_type, n_ff_exp_, n_embd_, ea) + : Mmq::fits((int) L.gu_type, 2 * n_ff_exp_, n_embd_, ea); + L.mmq = opt_.gpu_experts && rows_ >= kStageRows && gu_fits && Mmq::fits((int) L.d_type, n_embd_, n_ff_exp_, ea); + L.tiles_gu = expert_tiles_ && L.mmq && !L.mixed() && Mmq::tiles_fit((int) L.gu_type, 2 * n_ff_exp_, n_embd_, lb); + L.tiles_d = expert_tiles_ && L.mmq && Mmq::tiles_fit((int) L.d_type, n_embd_, n_ff_exp_, lb); + any_tiles = any_tiles || L.tiles_gu || L.tiles_d; + n_tiled += L.tiles_gu + L.tiles_d; + n_products += L.mmq ? 2 : 0; tiles = tiles || L.mmq; mixed_tiles = mixed_tiles || (L.mmq && L.mixed()); one_expert = std::max(one_expert, L.gu_step + L.d_bytes); } if (tiles) mmq_ = std::make_unique(); + if (expert_tiles_) + std::fprintf(stderr, "strata-poly: STRATA_POLY_EXPERT_TILES: %d of the layers' %d expert products in tiles of " + "their own widths\n", n_tiled, n_products); + if (mmq_ && reserve_mmq_) mmq_->reserve_fixup(); shared_scratch(); // the first pass only counts assign_scratch(); @@ -3164,6 +3493,14 @@ void Engine::alloc() { std::vector ramp(rr); std::iota(ramp.begin(), ramp.end(), 0); ck(cudaMemcpy(iota_, ramp.data(), rr * sizeof(int32_t), cudaMemcpyHostToDevice), "scratch"); + if (any_tiles) { // the cached experts' offsets, a round's gate|up and down ones; both products' tiles + const size_t mats = (3 * (size_t) n_expert_ + 1) / 2 * 2, n_tiles = 2 * ((size_t) n_expert_ + rr / 128 + 1); + const size_t bytes = mats * sizeof(int64_t) + n_tiles * sizeof(Mmq::Tile); + mat_at_ = (int64_t*) dmalloc(bytes, "scratch"); + h_mat_at_ = (int64_t*) hmalloc(bytes, "pinned memory"); + d_tiles_ = (Mmq::Tile*) (mat_at_ + mats); + tiles_.reserve(n_tiles); + } // One layer's experts pass through it at a time, so it never holds more than a layer has. A model of // small experts has a few hundred MiB a layer, and the rest of the default would be VRAM that the @@ -3193,7 +3530,7 @@ void Engine::alloc() { if (!opt_.metal_balanced) #endif ensure_stage(); - for (void** e : {&ev_stage_[0], &ev_stage_[1], &ev_ahead_, &ev_free_}) { + for (void** e : {&ev_stage_[0], &ev_stage_[1], &ev_ahead_, &ev_free_, &ev_pre_[0], &ev_pre_[1]}) { cudaEvent_t ev = nullptr; ck(cudaEventCreateWithFlags(&ev, cudaEventDisableTiming), "cudaEventCreate"); *e = ev; @@ -3270,13 +3607,13 @@ void Engine::save_state(uint8_t* dst) { ck(cudaStreamSynchronize(cs(st_)), "save state"); for (int il = 0; il < (int) layers_.size(); ++il) if (runs(il)) save_layer(il, pos_, dst); - save_last(dst); + save_last(dst, pos_); if (next_) next_->save_state(dst + card_state_bytes()); } // What the state has that is no layer's: the model's output for the last token, which the draft block pairs the // next one with. It lies behind the layers' state. -void Engine::save_last(uint8_t* dst) { +void Engine::save_last(uint8_t* dst, int64_t) { if (!draft_) return; ck(cudaMemcpy(dst + rec_n_ * sizeof(float), hn_, (size_t) n_embd_ * sizeof(float), cudaMemcpyDeviceToHost), "save state"); @@ -3561,6 +3898,59 @@ void Engine::lin(const Dev& w, const float* x, float* y, int n, const void* xq, if (w.scale != 1.0f) axpy(y, w.scale, y, n * w.n_out, false, st_); } +void Engine::lin_jobs(const LinJob* jobs, int count, int n) { + if (count > kernels::kMmvqJobsMax) throw std::logic_error("lin_jobs takes up to 8 matrices"); + // lin() takes the float types, inputs not in Q8_1, and more than a launch's 8 tokens (a prompt batch: MMQ) + const auto alone = [&](const LinJob& j) { + return !j.xq || n > 8 || j.w->type == kTypeF32 || j.w->type == kTypeBF16; + }; + // grouped: in a group already, launched or declined (then lin() takes it); done: launched + bool grouped[kernels::kMmvqJobsMax] = {}, done[kernels::kMmvqJobsMax] = {}; + const auto launched = [&](int j) { + const LinJob& g = jobs[j]; + if (g.w->scale != 1.0f) axpy(g.y, g.w->scale, g.y, n * g.w->n_out, false, st_); + done[j] = grouped[j] = true; + }; + // a token's matrices of several formats and one input width (a file of mixed quantizations): one launch + if (n == 1) { + kernels::MmvqJobs m{}; + int types[kernels::kMmvqJobsMax], idx[kernels::kMmvqJobsMax], k = 0; + bool mixed = false; + for (int j = 0; j < count; ++j) { + const int t = (int) jobs[j].w->type; + if (alone(jobs[j]) || (t != 8 && t != 12 && t != 13 && t != 14) || // native_mmvq_jobs()'s formats + (k > 0 && jobs[j].w->n_in != jobs[idx[0]].w->n_in)) + continue; + m.w[k] = jobs[j].w->p, m.x[k] = jobs[j].xq, m.y[k] = jobs[j].y, m.n_out[k] = jobs[j].w->n_out; + types[k] = t; + mixed = mixed || t != types[0]; + idx[k++] = j; + } + if (mixed && kernels::native_mmvq_jobs_mixed(types, m, k, jobs[idx[0]].w->n_in, st_)) + for (int j = 0; j < k; ++j) launched(idx[j]); + } + for (int i = 0; i < count; ++i) { + if (grouped[i] || alone(jobs[i])) continue; + kernels::MmvqJobs m{}; + int idx[kernels::kMmvqJobsMax], k = 0; + for (int j = i; j < count; ++j) { + if (grouped[j] || alone(jobs[j]) || jobs[j].w->type != jobs[i].w->type || + jobs[j].w->n_in != jobs[i].w->n_in) + continue; + m.w[k] = jobs[j].w->p; + m.x[k] = jobs[j].xq; + m.y[k] = jobs[j].y; + m.n_out[k] = jobs[j].w->n_out; + grouped[j] = true; + idx[k++] = j; + } + if (k < 2 || !kernels::native_mmvq_jobs((int) jobs[i].w->type, m, k, jobs[i].w->n_in, n, st_)) continue; + for (int j = 0; j < k; ++j) launched(idx[j]); + } + for (int i = 0; i < count; ++i) + if (!done[i]) lin(*jobs[i].w, jobs[i].x, jobs[i].y, n, jobs[i].xq); +} + ExpertScales Engine::expert_scales(const Layer& L, const int32_t* ids) const { ExpertScales s; if (L.h_s_gate.empty() && L.h_s_up.empty()) return s; @@ -3588,7 +3978,7 @@ void Engine::lin_raw(const Dev& w, const float* x, float* y, int n, const void* return gemv_bf16((const uint16_t*) w.p, x, y, w.n_in, w.n_out, per, n, st_); } // a prompt batch: llama.cpp's matrix-matrix kernels read the weights once for all the tokens - if (mmq_ && n >= kStageRows && Mmq::fits((int) w.type, w.n_out, w.n_in)) { + if (mmq_ && n >= kStageRows && Mmq::fits((int) w.type, w.n_out, w.n_in, dense_mmq())) { // A row too large for the halves its blocks keep their sums in goes in divided by a power of two, and x is // left as it was for whatever reads it next (both exact): its product comes out divided by the same. const bool guard = half_sum_guard_ && Mmq::half_sums((int) w.type); @@ -3616,7 +4006,9 @@ void Engine::router_scores(const Layer& L, int n) { lin(L.gate_inp, xn_, rl_, n, bool Engine::batched(const Layer& L, int n) const { return mmq_ && L.mmq && n >= kStageRows; } -int Engine::card_rows() const { return block_guess_ ? std::max(kSumRows, opt_.window * n_used_) : kSumRows; } +int Engine::card_rows() const { + return block_guess_ || windows_on_card() ? std::max(kSumRows, opt_.window * n_used_) : kSumRows; +} // The router's scores, and the copies of them and of the experts' input to the host. void Engine::moe_router(const Layer& L, int n) { @@ -3627,12 +4019,13 @@ void Engine::moe_router(const Layer& L, int n) { for (size_t q = 0; q < 8; ++q) if (ev_ == ev_row_[q]) part = q; const size_t ne = (size_t) n_expert_; - // the next MoE layer's router on this layer's input, for pool_ahead() + // the router of the next layer with routed experts (in the order the layers run: Layer::alias) on this layer's + // input, for pool_ahead() int j = (int) (&L - layers_.data()) + 1; - while (j < n_layer_ && !layers_[(size_t) j].moe) ++j; + while (j < n_layer_ && !routed(layers_[(size_t) j])) ++j; if (j >= n_layer_) return; float* d = ahead_dev_ + part * 16 * ne; - lin(layers_[(size_t) j].gate_inp, xn_, d, n, xq_); + lin(layers_[(size_t) home_of(j)].gate_inp, xn_, d, n, xq_); ck(cudaMemcpyAsync(h_ahead_ + part * 16 * ne, d, (size_t) n * ne * sizeof(float), cudaMemcpyDeviceToHost, cs(st_)), "read ahead"); } @@ -4034,7 +4427,9 @@ void Engine::pool_read(const Layer& L, PoolRead& r) { // The routed experts of tokens that come a few at a time. moe_router() is on its way, with ev_ behind it. True // when experts were computed on the CPU: their sum waits in h_cpu_ for moe_add(). `first` is run once, by the // thread that hands the cached experts to the card and ahead of them. -bool Engine::moe(Layer& L, int il, int n, const std::function* first) { +bool Engine::moe(int visit, int n, const std::function* first) { + const int il = home_of(visit); + Layer& L = layers_[(size_t) il]; const size_t e_row = (size_t) n_embd_; Clock::time_point t0 = Clock::now(); ck(cudaEventSynchronize((cudaEvent_t) ev_), "router"); @@ -4048,9 +4443,9 @@ bool Engine::moe(Layer& L, int il, int n, const std::function* first) { size_t part = 0; for (size_t q = 0; q < 8; ++q) if (ev_ == ev_row_[q]) part = q; - int j = il + 1; - while (j < n_layer_ && !layers_[(size_t) j].moe) ++j; - if (j < n_layer_) pool_ahead(j, n, part, prefetch_k_); + int j = visit + 1; + while (j < n_layer_ && !routed(layers_[(size_t) j])) ++j; + if (j < n_layer_) pool_ahead(home_of(j), n, part, prefetch_k_); } const float limit = clamp_exp_[(size_t) il]; @@ -4152,6 +4547,7 @@ bool Engine::moe(Layer& L, int il, int n, const std::function* first) { for (int i0 = 0; i0 < n_cached; i0 += per) { const int m = std::min(per, n_cached - i0); kernels::MmvqSlots gate_up{}, up{}, down{}; + gate_up.lanes = up.lanes = down.lanes = lane_slots_; for (int j = 0; j < m; ++j) { const Cached& c = cached[i0 + j]; gate_up.w[j] = c.slot; @@ -4166,21 +4562,25 @@ bool Engine::moe(Layer& L, int il, int n, const std::function* first) { } // a mixed layer's gate and up are each a matrix of n_ff rows of its own type, up's into the second half const int gu_rows = L.mixed() ? n_ff_exp_ : 2 * n_ff_exp_; - const bool one = m > 1 && kernels::native_mmvq_slots((int) L.gu_type, gate_up, m, n_embd_, gu_rows, st_); + // one matrix too where its launch is a warp a row (MmvqSlots::lanes): the same bits, and faster where + // the format has a lanes kernel (measured for Inkling 2's on CUDA) + const bool slots = m > 1 || lane_slots_; + const bool one = slots && kernels::native_mmvq_slots((int) L.gu_type, gate_up, m, n_embd_, gu_rows, st_); for (int j = 0; j < m && !one; ++j) kernels::native_mmvq((int) L.gu_type, gate_up.w[j], gate_up.x[j], gate_up.y[j], n_embd_, gu_rows, 1, st_); if (L.mixed()) { - const bool one_u = m > 1 && kernels::native_mmvq_slots((int) L.u_type, up, m, n_embd_, n_ff_exp_, st_); + const bool one_u = slots && kernels::native_mmvq_slots((int) L.u_type, up, m, n_embd_, n_ff_exp_, st_); for (int j = 0; j < m && !one_u; ++j) kernels::native_mmvq((int) L.u_type, up.w[j], up.x[j], up.y[j], n_embd_, n_ff_exp_, 1, st_); } ExpertScales es = expert_scales(L); for (int j = 0; j < m && (es.gate || es.up); ++j) es.e[j] = cached[i0 + j].e; - if (gelu_) geglu_rows(g_, h_, n_ff_exp_, m, st_, &es); - else swiglu_clamp_rows(g_, h_, n_ff_exp_, m, limit, st_, &es); - kernels::native_quantize_q8_1(h_, q8_, n_ff_exp_, m, st_); - if (!(m > 1 && kernels::native_mmvq_slots((int) L.d_type, down, m, n_ff_exp_, n_embd_, st_))) + if (!act_rows_q8_1(g_, q8_, m, &es)) { + act_rows(g_, h_, m, limit, &es); + kernels::native_quantize_q8_1(h_, q8_, n_ff_exp_, m, st_); + } + if (!(slots && kernels::native_mmvq_slots((int) L.d_type, down, m, n_ff_exp_, n_embd_, st_))) for (int j = 0; j < m; ++j) kernels::native_mmvq((int) L.d_type, down.w[j], down.x[j], down.y[j], n_ff_exp_, n_embd_, 1, st_); @@ -4241,7 +4641,8 @@ bool Engine::moe(Layer& L, int il, int n, const std::function* first) { } }; cpu_experts(*workers_, host, n_host, m, (int) L.gu_type, (int) L.u_type, (int) L.d_type, n_embd_, n_ff_exp_, - h_x_ + (size_t) at * e_row, limit, gelu_, cpu, meanwhile, any_late ? late : nullptr, &wait); + h_x_ + (size_t) at * e_row, limit, gelu_, cpu, meanwhile, any_late ? late : nullptr, &wait, + situ_ ? &*situ_ : nullptr, lowbit_experts_); pool_reads_.clear(); stats_.cpu_ms += ms_since(t0); } @@ -4251,6 +4652,12 @@ bool Engine::moe(Layer& L, int il, int n, const std::function* first) { // The CPU's experts of n tokens into the routed experts' sum. void Engine::moe_add(int n) { axpy(h_cpu_, 1.f, fo_, n * n_embd_, true, st_); } +void Engine::act_rows(const float* gate_up, float* h, int rows, float limit, const ExpertScales* es) { + if (situ_) situ_rows(gate_up, h, n_ff_exp_, rows, situ_->beta, situ_->lin_beta, st_, es); + else if (gelu_) geglu_rows(gate_up, h, n_ff_exp_, rows, st_, es); + else swiglu_clamp_rows(gate_up, h, n_ff_exp_, rows, limit, st_, es); +} + // With every routed expert in VRAM, a few tokens' experts are routed on the card and found there by its picks // (moe_card()), so a layer never waits for the host. The cache's slots go to the card again when they changed. bool Engine::card_moe(int n) { @@ -4291,29 +4698,34 @@ bool Engine::moe_card(Layer& L, int il, int n) { const void* const* table = d_slots_ + (size_t) il * n_expert_; const size_t xq_row = kernels::native_q8_1_bytes(n_embd_), ff = (size_t) n_ff_exp_; // a mixed layer's gate and up are each a matrix of n_ff rows of its own type, up's into the second half - const kernels::MmvqIds gate_up{table, d_ids_, 0, xq_, xq_row, n_used_, g_, 2 * ff}; + const kernels::MmvqIds gate_up{table, d_ids_, 0, xq_, xq_row, n_used_, g_, 2 * ff, lane_slots_}; kernels::native_mmvq_ids((int) L.gu_type, gate_up, rr, n_embd_, L.mixed() ? n_ff_exp_ : 2 * n_ff_exp_, st_); if (L.mixed()) { - const kernels::MmvqIds up{table, d_ids_, L.gu_bytes, xq_, xq_row, n_used_, g_ + ff, 2 * ff}; + const kernels::MmvqIds up{table, d_ids_, L.gu_bytes, xq_, xq_row, n_used_, g_ + ff, 2 * ff, lane_slots_}; kernels::native_mmvq_ids((int) L.u_type, up, rr, n_embd_, n_ff_exp_, st_); } const ExpertScales es = expert_scales(L, d_ids_); - if (gelu_) geglu_rows(g_, h_, n_ff_exp_, rr, st_, &es); - else swiglu_clamp_rows(g_, h_, n_ff_exp_, rr, clamp_exp_[(size_t) il], st_, &es); + const bool act_q8 = act_rows_q8_1(g_, q8_, rr, &es); + if (!act_q8) act_rows(g_, h_, rr, clamp_exp_[(size_t) il], &es); if (!L.h_s_down.empty()) expert_weights(d_wts_, fp(L.s_down), d_ids_, rr, st_); - kernels::native_quantize_q8_1(h_, q8_, n_ff_exp_ * rr, 1, st_); // the rows back to back, as one vector + if (!act_q8) kernels::native_quantize_q8_1(h_, q8_, n_ff_exp_ * rr, 1, st_); // the rows back to back, as one vector const kernels::MmvqIds down{table, d_ids_, L.gu2(), q8_, kernels::native_q8_1_bytes(n_ff_exp_), 1, d_, - (size_t) n_embd_}; + (size_t) n_embd_, lane_slots_}; kernels::native_mmvq_ids((int) L.d_type, down, rr, n_ff_exp_, n_embd_, st_); - moe_sum(d_, d_wts_, fo_, n_embd_, n_used_, n, st_); + if (!card_sum_in_tail(n)) moe_sum(d_, d_wts_, fo_, n_embd_, n_used_, n, st_); return true; } // m experts from the mapped file into the staging buffer: gate and up of each back to back from the start, the // downs after them. The two pinned buffers take turns, so the workers fill one while the other uploads. `alone`: -// stagers_ fill them, while the workers compute experts. -void Engine::stage(const Layer& L, const int32_t* experts, int m, void* stream, bool alone) { - staged_il_ = -1; // whatever the buffer held +// stagers_ fill them, while the workers compute experts. `to`: a place in the buffer for the next layer's +// experts, copied while this one's are read (prestage()). +void Engine::stage(const Layer& L, const int32_t* experts, int m, void* stream, bool alone, uint8_t* to) { + if (!to) { + staged_il_ = -1; // whatever the buffer held + stage_at_ = 0; + to = stage_; + } const size_t step = L.gu_step, down_at = pad((size_t) m * step); const int per = (int) (chunk_bytes_ / (step + L.d_bytes)); for (int j0 = 0; j0 < m; j0 += per) { @@ -4342,14 +4754,13 @@ void Engine::stage(const Layer& L, const int32_t* experts, int m, void* stream, else get(h + c * step + j * L.d_bytes, L.exp_down + e * L.d_bytes, L.d_bytes, L.gu2()); }; (alone ? *stagers_ : *workers_).run((int) (3 * c), copy); - ck(cudaMemcpyAsync(stage_ + (size_t) j0 * step, h, c * step, cudaMemcpyHostToDevice, cs(stream)), - "expert staging"); - ck(cudaMemcpyAsync(stage_ + down_at + (size_t) j0 * L.d_bytes, h + c * step, c * L.d_bytes, - cudaMemcpyHostToDevice, cs(stream)), + ck(cudaMemcpyAsync(to + (size_t) j0 * step, h, c * step, cudaMemcpyHostToDevice, cs(stream)), "expert staging"); + ck(cudaMemcpyAsync(to + down_at + (size_t) j0 * L.d_bytes, h + c * step, c * L.d_bytes, cudaMemcpyHostToDevice, + cs(stream)), "expert staging"); ck(cudaEventRecord(left, cs(stream)), "expert staging"); } - ck(cudaMemsetAsync(stage_ + down_at + (size_t) m * L.d_bytes, 0, kTail, cs(stream)), "expert staging"); + ck(cudaMemsetAsync(to + down_at + (size_t) m * L.d_bytes, 0, kTail, cs(stream)), "expert staging"); } // A MoE layer for a prompt batch: the experts on the GPU, by llama.cpp's MMQ. A row is a token and one @@ -4407,7 +4818,13 @@ void Engine::moe_rows(Layer& L, int il, int n) { // request's: a frozen answer takes the staging as it finds it, which is what the first token saw. const bool mine = ahead && staged_il_ == il && (staged_ == L.ahead || (freeze_experts_ ? true : 2 * route_ms_ < ahead_ms_)); - const bool early = n_ahead > 0 && !mine; + // The layer before may have copied them (prestage()), where the buffer had room beside its own. + if (pre_.il >= 0 && !mine) settle_prestage(); + const bool pre = n_ahead > 0 && !mine && pre_.il == il && pre_.experts == L.ahead; + if (pre) stage_at_ = pre_.at; + void* const pre_done = ev_pre_[pre_.ev]; // before prestage() below starts the next one's + pre_.il = mine ? pre_.il : -1; + const bool early = n_ahead > 0 && !mine && !pre; if (early) { const Clock::time_point t = Clock::now(); // the buffer is free once the layer before has read it @@ -4421,9 +4838,13 @@ void Engine::moe_rows(Layer& L, int il, int n) { } } + // The next layer's copy runs while this one's calls are read, if every expert of both that is not cached + // goes in the buffer, and nothing of this layer's is copied after it (its later calls find theirs there). + if ((early || pre) && prestage_ && next_home_ >= 0 && n_ahead == uncached(L)) prestage(L, n_ahead, n); + const Clock::time_point t0 = Clock::now(); ck(cudaEventSynchronize((cudaEvent_t) ev_), "router"); - if (ahead && !early && !freeze_experts_) route_ms_ = ms_since(t0); + if (ahead && !early && !pre && !freeze_experts_) route_ms_ = ms_since(t0); stats_.route_wait_ms += ms_since(t0); const size_t cb_row = (size_t) n_expert_ + 1; @@ -4502,7 +4923,8 @@ void Engine::moe_rows(Layer& L, int il, int n) { if (n_ahead > 0) round_.push_back(n_cached + n_ahead); while (round_.back() < n_group) round_.push_back(std::min(round_.back() + per_round, n_group)); const int n_round = (int) round_.size() - 1; - const int n_tile = (int) staged_tiles_.size() + 1; // the size classes of a round's experts + // the size classes of a round's experts; none where the layer's products take tiles of their own widths + const int n_tile = L.tiles_gu || L.tiles_d ? 1 : (int) staged_tiles_.size() + 1; const size_t tile_row = (size_t) 2 * n_expert_ + 2; const auto tile_of = [&](int rows) { int t = 0; @@ -4586,15 +5008,69 @@ void Engine::moe_rows(Layer& L, int il, int n) { } b[n_chan] = at; } - ck(cudaMemcpyAsync(tab_, h_tab_, - (3 * cap + 3 * (size_t) n_expert_ + 3 + kClasses * cb_row + 2 * n_tile * tile_row * (n_tile > 1)) * - sizeof(int32_t), - cudaMemcpyHostToDevice, cs(st_)), - "expert rows"); - if ((es.gate || es.up) && rg > 0) - ck(cudaMemcpyAsync(d_ex_, h_ex_, (size_t) rg * sizeof(int32_t), cudaMemcpyHostToDevice, cs(st_)), "expert rows"); + const size_t n_tab = + 3 * cap + 3 * (size_t) n_expert_ + 3 + kClasses * cb_row + 2 * n_tile * tile_row * (n_tile > 1); + const int n_ex = (es.gate || es.up) && rg > 0 ? rg : 0; + if (kernel_tables_) { + copy2(h_tab_, tab_, (int) n_tab, h_ex_, d_ex_, n_ex, st_); + } else { + ck(cudaMemcpyAsync(tab_, h_tab_, n_tab * sizeof(int32_t), cudaMemcpyHostToDevice, cs(st_)), "expert rows"); + if (n_ex > 0) + ck(cudaMemcpyAsync(d_ex_, h_ex_, (size_t) n_ex * sizeof(int32_t), cudaMemcpyHostToDevice, cs(st_)), + "expert rows"); + } const int rc = bounds[n_cached]; // the rows of the cached experts + + // expert_tiles_: the tiles of each product - the cached experts', each round's - and where their matrices are. The + // cached experts' slots count from the lowest one; a round's experts from the buffer. The two products may take + // other widths, so each has tiles of its own: for part p (0 the cached experts, 1 + r round r), gate|up's from + // tile_at_[2p], down's from tile_at_[2p + 1]. + const size_t n_mats = (3 * (size_t) n_expert_ + 1) / 2 * 2; + const uint8_t* slot0 = nullptr; + if (L.tiles_gu || L.tiles_d) { + int64_t* at = h_mat_at_; // the cached experts' slots, a round's gate|up, a round's down + for (int g = 0; g < n_cached; ++g) + if (!slot0 || L.slot[(size_t) group_[(size_t) g]] < slot0) slot0 = L.slot[(size_t) group_[(size_t) g]]; + for (int g = 0; g < n_cached; ++g) at[g] = L.slot[(size_t) group_[(size_t) g]] - slot0; + for (int j = 0; j < n_expert_; ++j) { + at[n_expert_ + j] = (int64_t) j * (int64_t) step; + at[2 * n_expert_ + j] = (int64_t) j * (int64_t) L.d_bytes; + } + tiles_.clear(); + tile_at_.assign(1, 0); + const auto part = [&](int g0, int m) { + tile_first_.resize((size_t) m); + tile_rows_.resize((size_t) m); + tile_mat_.resize((size_t) m); + for (int j = 0; j < m; ++j) { + tile_first_[(size_t) j] = bounds[g0 + j]; + tile_rows_[(size_t) j] = rows_of(g0 + j); + tile_mat_[(size_t) j] = j; + } + for (const int t : {(int) L.gu_type, (int) L.d_type}) { + Mmq::plan_tiles(t, tile_first_.data(), tile_rows_.data(), tile_mat_.data(), m, tiles_); + tile_at_.push_back((int) tiles_.size()); + } + }; + part(0, n_cached); + for (int r = 0; r < n_round; ++r) part(round_[(size_t) r], round_[(size_t) r + 1] - round_[(size_t) r]); + std::copy(tiles_.begin(), tiles_.end(), (Mmq::Tile*) (at + n_mats)); + const size_t words = (n_mats * sizeof(int64_t) + tiles_.size() * sizeof(Mmq::Tile)) / sizeof(int32_t); + if (kernel_tables_) + copy2(h_mat_at_, mat_at_, (int) words, nullptr, nullptr, 0, st_); + else + ck(cudaMemcpyAsync(mat_at_, h_mat_at_, words * sizeof(int32_t), cudaMemcpyHostToDevice, cs(st_)), + "expert tiles"); + } + // product t (0 gate|up, 1 down) of part p over its tiles: rows of xq from row0, matrices from w at `at` + const auto tile_mul = [&](int p, int t, const uint8_t* w, const int64_t* at, const void* xq, int64_t row0, + int64_t xq_rows, const int32_t* ids, float* dst, int64_t ld) { + const int a = tile_at_[(size_t) (2 * p + t)], b = tile_at_[(size_t) (2 * p + t + 1)]; + mmq_->mul_tiles(w, at, (int) (t == 0 ? L.gu_type : L.d_type), t == 0 ? 2 * n_ff_exp_ : n_embd_, + t == 0 ? n_embd_ : n_ff_exp_, xq, row0, xq_rows, d_tiles_ + a, tiles_.data() + a, b - a, ids, + dst, ld, st_); + }; stats_.batch_cached += rc; stats_.batch_staged += rg - rc; @@ -4647,20 +5123,27 @@ void Engine::moe_rows(Layer& L, int il, int n) { } j += m; } - for (const Run& r : runs_) { - mmq_->mul(slot_of(r.j), gt, gu_rows, n_embd_, L.slot_bytes, r.m, mq_, d_cb + (size_t) r.c * cb_row + r.j, - iota_, rg, r.most, gu_, ff2, st_); - up_mul(slot_of(r.j), L.slot_bytes, r.m, d_cb + (size_t) r.c * cb_row + r.j, r.most); + if (L.tiles_gu) { + if (rc > 0) tile_mul(0, 0, slot0, mat_at_, mq_, 0, rg, iota_, gu_, ff2); + } else { + for (const Run& r : runs_) { + mmq_->mul(slot_of(r.j), gt, gu_rows, n_embd_, L.slot_bytes, r.m, mq_, + d_cb + (size_t) r.c * cb_row + r.j, iota_, rg, r.most, gu_, ff2, st_); + up_mul(slot_of(r.j), L.slot_bytes, r.m, d_cb + (size_t) r.c * cb_row + r.j, r.most); + } } if (rc > 0) { - if (gelu_) geglu_rows(gu_, hx_, n_ff_exp_, rc, st_, &es); - else swiglu_clamp_rows(gu_, hx_, n_ff_exp_, rc, limit, st_, &es); + act_rows(gu_, hx_, rc, limit, &es); if (guard) guard_half_sums(hx_, ff, n_ff_exp_, rc, hf_, st_); Mmq::quantize(hx_, nullptr, mq2_, dt, ff, ff, rc, st_); } - for (const Run& r : runs_) - mmq_->mul(slot_of(r.j) + gu2, dt, n_embd_, ff, L.slot_bytes, r.m, mq2_, d_cb + (size_t) r.c * cb_row + r.j, - d_place, rc, r.most, dx_, n_embd_, st_); + if (L.tiles_d) { + if (rc > 0) tile_mul(0, 1, slot0 + gu2, mat_at_, mq2_, 0, rc, d_place, dx_, n_embd_); + } else { + for (const Run& r : runs_) + mmq_->mul(slot_of(r.j) + gu2, dt, n_embd_, ff, L.slot_bytes, r.m, mq2_, + d_cb + (size_t) r.c * cb_row + r.j, d_place, rc, r.most, dx_, n_embd_, st_); + } if (guard && rc > 0) scale_rows(dx_, n_embd_, n_embd_, rc, d_place, hf_, false, st_); // The round the buffer holds goes first and is not copied. If it holds none of this call's, the experts @@ -4671,7 +5154,7 @@ void Engine::moe_rows(Layer& L, int il, int n) { if ((size_t) (last - first) == staged_.size() && std::equal(first, last, staged_.begin())) kept = r; } const int from = mine && kept < 0 ? 1 : 0; - holds = early ? 0 : kept; + holds = early || pre ? 0 : kept; for (int turn = 0; turn < n_round; ++turn) { const int r = kept < 0 ? (turn + from) % n_round : turn == 0 ? kept : turn - (turn <= kept ? 1 : 0); const int g0 = round_[(size_t) r], m = round_[(size_t) r + 1] - g0; @@ -4679,9 +5162,10 @@ void Engine::moe_rows(Layer& L, int il, int n) { const int r0 = round_row_[(size_t) r], rows = round_row_[(size_t) r + 1] - r0; if (r == kept) { // the buffer has it - } else if (r == 0 && early) { - ck(cudaStreamWaitEvent(cs(st_), (cudaEvent_t) ev_ahead_, 0), "expert staging"); + } else if (r == 0 && (early || pre)) { + ck(cudaStreamWaitEvent(cs(st_), (cudaEvent_t) (pre ? pre_done : ev_ahead_), 0), "expert staging"); } else if (rows > 0) { + if (pre_th_.joinable()) settle_prestage(); // the pinned buffers are the copy's stage(L, group_.data() + g0, m, st_, n_cpu > 0); holds = r; } @@ -4698,23 +5182,33 @@ void Engine::moe_rows(Layer& L, int il, int n) { if (top > 0) launch(k, top); } }; - each_class([&](int k, int top) { - const int32_t* b = n_tile == 1 ? d_bounds + g0 : d_tb + (size_t) k * tile_row + (size_t) (g0 - n_cached + r); - mmq_->mul(stage_, gt, gu_rows, n_embd_, step, m, mq_, b, iota_, rg, top, gu_, ff2, st_); - up_mul(stage_, step, m, b, top); - }); + uint8_t* const sb = stage_ + stage_at_; + if (L.tiles_gu) { + tile_mul(1 + r, 0, sb, mat_at_ + n_expert_, mq_, 0, rg, iota_, gu_, ff2); + } else { + each_class([&](int k, int top) { + const int32_t* b = n_tile == 1 ? d_bounds + g0 + : d_tb + (size_t) k * tile_row + (size_t) (g0 - n_cached + r); + mmq_->mul(sb, gt, gu_rows, n_embd_, step, m, mq_, b, iota_, rg, top, gu_, ff2, st_); + up_mul(sb, step, m, b, top); + }); + } ExpertScales er = es; if (er.ids) er.ids += r0; - if (gelu_) geglu_rows(gu_ + (size_t) r0 * ff2, hx_ + (size_t) r0 * ff, n_ff_exp_, rows, st_, &er); - else swiglu_clamp_rows(gu_ + (size_t) r0 * ff2, hx_ + (size_t) r0 * ff, n_ff_exp_, rows, limit, st_, &er); + act_rows(gu_ + (size_t) r0 * ff2, hx_ + (size_t) r0 * ff, rows, limit, &er); if (guard) guard_half_sums(hx_ + (size_t) r0 * ff, ff, n_ff_exp_, rows, hf_ + r0, st_); Mmq::quantize(hx_ + (size_t) r0 * ff, nullptr, mq2_, dt, ff, ff, rows, st_); - each_class([&](int k, int top) { - const int32_t* b = (n_tile == 1 ? d_rel + (g0 - n_cached + r) - : d_tb + (size_t) (n_tile + k) * tile_row + (size_t) (g0 - n_cached + r)); - mmq_->mul(stage_ + down_at, dt, n_embd_, ff, L.d_bytes, m, mq2_, b, d_place + r0, rows, top, dx_, n_embd_, - st_); - }); + if (L.tiles_d) { + tile_mul(1 + r, 1, sb + down_at, mat_at_ + 2 * n_expert_, mq2_, r0, rows, d_place + r0, dx_, n_embd_); + } else { + each_class([&](int k, int top) { + const int32_t* b = (n_tile == 1 ? d_rel + (g0 - n_cached + r) + : d_tb + (size_t) (n_tile + k) * tile_row + + (size_t) (g0 - n_cached + r)); + mmq_->mul(sb + down_at, dt, n_embd_, ff, L.d_bytes, m, mq2_, b, d_place + r0, rows, top, dx_, + n_embd_, st_); + }); + } if (guard) scale_rows(dx_, n_embd_, n_embd_, rows, d_place + r0, hf_ + r0, false, st_); } ck(cudaEventRecord((cudaEvent_t) ev_free_, cs(st_)), "expert staging"); @@ -4733,7 +5227,7 @@ void Engine::moe_rows(Layer& L, int il, int n) { done = Clock::now(); }); cpu_experts(*workers_, host_.data(), (int) host_.size(), n, gt, ut, dt, n_embd_, n_ff_exp_, h_x_, limit, gelu_, - h_cpu_, nullptr); + h_cpu_, nullptr, nullptr, nullptr, situ_ ? &*situ_ : nullptr, lowbit_experts_); const double cpu = ms_since(start); behind.wait(); const double gpu = std::chrono::duration(done - start).count(); @@ -4793,6 +5287,7 @@ void Engine::run(const int32_t* tokens, int n) { if (pos_ + n > opt_.max_context) throw std::runtime_error("the context is full (" + std::to_string(opt_.max_context) + " tokens)"); cover(pos_ + n); + const Until parts{card_parts_}; // from a moe_card() to the layer_tail() after it // h_r_ and h_cpu_ may still be the source of the previous call's copies ck(cudaStreamSynchronize(cs(st_)), "eval"); @@ -4852,17 +5347,19 @@ void Engine::run(const int32_t* tokens, int n) { const auto up = [&](int il, int m, size_t rec) { Layer& L = layers_[(size_t) il]; const size_t head = (size_t) head_key(il, m) * recs + rec; - if (replay && L.fixed) replayed(L.heads, head, [&] { layer_head(L, il, m); }); + if (replay && L.fixed && layer_graphs()) replayed(L.heads, head, [&] { layer_head(L, il, m); }); else layer_head(L, il, m); - if (!L.moe || batched(L, m)) return; + if (!routed(L) || batched(layers_[(size_t) home_of(il)], m)) return; ck(cudaEventRecord((cudaEvent_t) ev_, cs(st_)), "router"); - if (replay) replayed(L.shared, rec, [&] { moe_shared(L, il, m); }); + // a model whose heads are not recorded apart (layer_graphs()) has its shared expert launched as it is too: a + // graph launch for a launch or two (Inkling's is one memset) costs the host more than the launches + if (replay && layer_graphs()) replayed(L.shared, rec, [&] { moe_shared(L, il, m); }); else moe_shared(L, il, m); }; const auto tail = [&](int il, int m, size_t rec) { Layer& L = layers_[(size_t) il]; dbg("ffn", il, fo_, n_embd_); - if (replay && L.fixed) replayed(L.tail, rec, [&] { layer_tail(L, il, m); }); + if (replay && L.fixed && layer_graphs()) replayed(L.tail, rec, [&] { layer_tail(L, il, m); }); else layer_tail(L, il, m); }; @@ -4904,7 +5401,7 @@ void Engine::run(const int32_t* tokens, int n) { } for (int j = il < 0 ? lo_ : il + 1; j < hi_; ++j) { up(j, m, rec); - if (layers_[(size_t) j].moe) break; + if (routed(layers_[(size_t) j])) break; } }; const auto back = [&] { @@ -4922,8 +5419,7 @@ void Engine::run(const int32_t* tokens, int n) { try { for (int k = 0; k < 2; ++k) go_on(k, -1, false); for (int il = lo_; il < hi_; ++il) { - Layer& L = layers_[(size_t) il]; - if (!L.moe) continue; + if (!routed(layers_[(size_t) il])) continue; for (int k = 0; k < 2; ++k) { // by another thread while this one computes: it must leave the rows as it found them const std::function other = [&] { @@ -4936,7 +5432,7 @@ void Engine::run(const int32_t* tokens, int n) { } }; const int m = half(k); - const bool add = moe(L, il, m, late.k >= 0 ? &other : nullptr); + const bool add = moe(il, m, late.k >= 0 ? &other : nullptr); if (failed) std::rethrow_exception(failed); late = {k, il, add}; } @@ -4952,11 +5448,16 @@ void Engine::run(const int32_t* tokens, int n) { // The routed experts on the card alone, when every one of them is in VRAM: recorded too, once a layer has // shown it routes there (Layer::card). const bool card = n < kStageRows && card_moe(n); + layers_in_order_ = true; + const Until in_order{layers_in_order_}; const auto on_card = [&](int il, int m, size_t rec) { - Layer& L = layers_[(size_t) il]; + const int home = home_of(il); + Layer& L = layers_[(size_t) home]; + card_parts_ = false; if (!card) return false; - if (replay && L.card == 1) replayed(L.card_moe, rec, [&] { moe_card(L, il, m); }); - else if (!moe_card(L, il, m)) return false; + if (replay && L.card == 1) replayed(L.card_moe, rec, [&] { moe_card(L, home, m); }); + else if (!moe_card(L, home, m)) return false; + card_parts_ = card_sum_in_tail(m); stats_.gpu_experts += m * n_used_; return true; }; @@ -4965,7 +5466,7 @@ void Engine::run(const int32_t* tokens, int n) { bool whole = card && replay; for (int il = lo_; il < hi_ && whole; ++il) { const Layer& L = layers_[(size_t) il]; - whole = L.fixed && (!L.moe || L.card == 1); + whole = L.fixed && (!routed(L) || layers_[(size_t) home_of(il)].card == 1); } // A block of guesses is recorded whole or not at all: a layer's own recordings are a window's, of other kernels. if (block_pass_ && !whole) replay = false; @@ -4978,22 +5479,25 @@ void Engine::run(const int32_t* tokens, int n) { for (int il = lo_; il < hi_; ++il) { Layer& L = layers_[(size_t) il]; layer_head(L, il, n); - if (!L.moe) continue; + if (!routed(L)) continue; moe_shared(L, il, n); - moe_card(L, il, n); + moe_card(layers_[(size_t) home_of(il)], home_of(il), n); + card_parts_ = card_sum_in_tail(n); layer_tail(L, il, n); } }); ck(cudaGraphLaunch((cudaGraphExec_t) pass, cs(st_)), "layer graph"); - for (int il = lo_; il < hi_; ++il) stats_.gpu_experts += layers_[(size_t) il].moe ? n * n_used_ : 0; + for (int il = lo_; il < hi_; ++il) stats_.gpu_experts += routed(layers_[(size_t) il]) ? n * n_used_ : 0; return; } for (int il = lo_; il < hi_; ++il) { Layer& L = layers_[(size_t) il]; up(il, n, (size_t) n - 1); - if (!L.moe) continue; - if (batched(L, n)) moe_rows(L, il, n); - else if (!on_card(il, n, (size_t) n - 1) && moe(L, il, n)) moe_add(n); + if (!routed(L)) continue; + const int home = home_of(il); + Layer& M = layers_[(size_t) home]; // the layer whose experts L runs: L, or its Layer::alias + if (batched(M, n)) moe_rows(M, home, n); + else if (!on_card(il, n, (size_t) n - 1) && moe(il, n)) moe_add(n); tail(il, n, (size_t) n - 1); } } @@ -5017,6 +5521,7 @@ void Engine::step(const int* seqs, const int32_t* tokens, int n, const int32_t* if (guesses && !steps_guesses()) throw std::logic_error("step: guesses need --batch-mtp, a draft block and one card"); if (!step_seqs_.empty()) throw std::logic_error("step: the rows of the step before are not kept yet (keep_step())"); OnCard here(device_, split_); + const Until parts{card_parts_}; // from a moe_card() to the layer_tail() after it end_read(); const int home = bound_; const auto use = [&](int s) { hold(s); }; @@ -5116,19 +5621,24 @@ void Engine::step(const int* seqs, const int32_t* tokens, int n, const int32_t* pos_ = at[(size_t) i]; } } - if (!L.moe) continue; - if (batched(L, R)) { - moe_rows(L, il, R); + if (!routed(L)) continue; + const int home = home_of(il); + Layer& M = layers_[(size_t) home]; // the layer whose experts L runs: L, or its Layer::alias + if (batched(M, R)) { + moe_rows(M, home, R); } else { ck(cudaEventRecord((cudaEvent_t) ev_, cs(st_)), "router"); if (replay) replayed(L.shared, rec, [&] { moe_shared(L, il, R); }); else moe_shared(L, il, R); - if (card && L.card == 1 && replay) { - replayed(L.card_moe, rec, [&] { moe_card(L, il, R); }); + card_parts_ = false; + if (card && M.card == 1 && replay) { + replayed(M.card_moe, rec, [&] { moe_card(M, home, R); }); + card_parts_ = card_sum_in_tail(R); stats_.gpu_experts += R * n_used_; - } else if (card && moe_card(L, il, R)) { + } else if (card && moe_card(M, home, R)) { + card_parts_ = card_sum_in_tail(R); stats_.gpu_experts += R * n_used_; - } else if (moe(L, il, R)) { + } else if (moe(il, R)) { moe_add(R); } } @@ -5272,7 +5782,7 @@ void Engine::draft_rows_of(const Row* rows, const int32_t* tokens, int n, Likeli ck(cudaEventRecord((cudaEvent_t) ev_, cs(st_)), "router"); moe_shared(L, n_layer_, n); tok_ = nullptr; // a guess's row has no token of the sequence - if (moe(L, n_layer_, n)) moe_add(n); + if (moe(n_layer_, n)) moe_add(n); axpy(fo_, 1.f, x, n * n_embd_, true, st_); rms_norm(x, fp(d_head_), step_h_, n_embd_, n, rms_eps_, st_); Dev head = output_; // the matrix's first rows are the common tokens' @@ -5387,7 +5897,10 @@ void Engine::eval(const int32_t* tokens, int n, bool want_logits) { if (want_logits) ck(cudaStreamSynchronize(cs(st_)), "eval"); } // behind the logits: the caller has them while the card does this - if (draft_) draft_rows(tokens, ahead_pos_ == pos_ && tokens[0] == ahead_tok_ ? 1 : 0, n); + if (draft_) { + drafter_rows(pos_, n, hn_ + n_embd_); + draft_rows(tokens, ahead_pos_ == pos_ && tokens[0] == ahead_tok_ ? 1 : 0, n); + } pos_ += n; stats_.tokens += n; } @@ -5396,13 +5909,15 @@ void Engine::eval(const int32_t* tokens, int n, bool want_logits) { void Engine::layer(int il, int n) { Layer& L = layers_[(size_t) il]; layer_head(L, il, n); - if (!L.moe) return; - if (batched(L, n)) { - moe_rows(L, il, n); + if (!routed(L)) return; + const int home = home_of(il); + Layer& M = layers_[(size_t) home]; // the layer whose experts L runs: L, or its Layer::alias + if (batched(M, n)) { + moe_rows(M, home, n); } else { ck(cudaEventRecord((cudaEvent_t) ev_, cs(st_)), "router"); moe_shared(L, il, n); - if (moe(L, il, n)) moe_add(n); + if (moe(il, n)) moe_add(n); } layer_tail(L, il, n); } @@ -5539,6 +6054,9 @@ bool Engine::read(const int32_t* tokens, int n, const Mark* marks, int n_marks, // Between two turns the caller may give the read up. The layers so far have the read's tokens in // their state and the others have not: the sequence cannot go on from here, nor from where it was. if (turn && k > 0 && !(*turn)(k, turns)) { + settle_prestage(); + pre_.il = next_home_ = -1; + if (up_) ck(cudaStreamSynchronize(cs(up_)), "read"); // the copy no turn takes ends before another if (host) ck(cudaStreamSynchronize(cs(rs_)), "read"); ck(cudaStreamSynchronize(cs(st_)), "read"); shared_ahead_ = false; @@ -5553,9 +6071,13 @@ bool Engine::read(const int32_t* tokens, int n, const Mark* marks, int n_marks, tok_ = tokens + call.at; if (host) ck(cudaStreamWaitEvent(cs(st_), (cudaEvent_t) ev_in_[c % 2], 0), "read"); if (il < n_layer_) { + const int on = il + 1; // the layer of the next turn, whose experts may come meanwhile + next_home_ = + prestage_ && on < hi_ && on < n_layer_ && routed(layers_[(size_t) on]) ? home_of(on) : -1; layer(il, call.m); } else { output_rows(0, call.m, hn_ + n_embd_); + drafter_rows(pos_, call.m, hn_ + n_embd_); draft_rows(tokens + call.at, ahead_pos_ == pos_ && tokens[call.at] == ahead_tok_ ? 1 : 0, call.m); ++read_draft_calls_; } @@ -5565,7 +6087,7 @@ bool Engine::read(const int32_t* tokens, int n, const Mark* marks, int n_marks, if (il < n_layer_) save_layer(il, pos, state); if (k == turns - 1) { // what no turn is for: a layer behind the model's, the last output for (int j = n_layer_; j < (int) layers_.size(); ++j) save_layer(j, pos, state); - save_last(state); + save_last(state, pos); } } // The card's work on the next call starts now. This call's rows leave beside it, unless this was @@ -5592,12 +6114,18 @@ bool Engine::read(const int32_t* tokens, int n, const Mark* marks, int n_marks, ck(cudaStreamSynchronize(cs(st_)), "the next card"); } } catch (...) { + if (pre_th_.joinable()) pre_th_.join(); + pre_err_ = nullptr; + pre_.il = next_home_ = -1; + if (up_) cudaStreamSynchronize(cs(up_)); if (host) cudaStreamSynchronize(cs(rs_)); shared_ahead_ = false; r_ = r0; pos_ = pos0; throw; } + settle_prestage(); + pre_.il = next_home_ = -1; shared_ahead_ = false; r_ = r0; pos_ = pos0; @@ -5663,6 +6191,7 @@ void Engine::window(const int32_t* tokens, int t) { } float* h = draft_ ? hn_ + n_embd_ : xn_; output_rows(0, t, h); + if (draft_) drafter_rows(pos_, t, h); lin(output_, h, wlogits_, t); finish_logits(wlogits_, t); ck(cudaMemcpyAsync(h_wlogits_, wlogits_, (size_t) t * n_vocab_ * sizeof(float), cudaMemcpyDeviceToHost, cs(st_)), @@ -5787,7 +6316,7 @@ void Engine::draft_step(int32_t token, int i) { ck(cudaEventRecord((cudaEvent_t) ev_, cs(st_)), "router"); moe_shared(L, n_layer_, 1); tok_ = nullptr; // a guess's row has no token of the sequence - if (moe(L, n_layer_, 1)) moe_add(1); + if (moe(n_layer_, 1)) moe_add(1); axpy(fo_, 1.f, x, n_embd_, true, st_); rms_norm(x, fp(d_head_), own, n_embd_, 1, rms_eps_, st_); Dev head = output_; // the matrix's first rows are the common tokens' @@ -5831,6 +6360,11 @@ int32_t Engine::draft(int32_t token, int i, float* prob) { if (!draft_ && !block_guess_) throw std::logic_error("draft: this model has no block that guesses ahead"); if (token < 0 || token >= n_vocab_) throw std::runtime_error("a token id is outside the vocabulary"); if (i < 0 || pos_ + i >= opt_.max_context) throw std::logic_error("draft: the position is outside the context"); + if (block_drafter_) { + if (i == 0) block_n_ = draft_block(token, opt_.window - 1, h_block_); + *prob = i < block_n_ ? h_block_[i].prob : 0.f; + return i < block_n_ ? h_block_[i].token : 0; + } if (block_guess_) { if (i == 0) guess_block(token); *prob = i < block_n_ ? h_block_[i].prob : 0.f; diff --git a/src/poly/engine.hpp b/src/poly/engine.hpp index 7220509b54..86561727a4 100644 --- a/src/poly/engine.hpp +++ b/src/poly/engine.hpp @@ -15,6 +15,7 @@ #pragma once #include "cpu_experts.hpp" +#include "mmq.hpp" #include "strata/poly/kernels.hpp" #include @@ -22,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -143,6 +145,11 @@ struct Dev { struct Layer { bool moe = false; bool mmq = false; ///< the card has MMQ tiles for its routed experts' types (Engine::batched()) + bool tiles_gu = false, tiles_d = false; ///< gate|up's, down's products through Mmq::mul_tiles() (expert_tiles_) + /// A layer that runs another layer's routed experts (Inkling's later visits of a looped layer): that layer's + /// index, whose router, cache slots, staging, use counts and CPU pool it uses. Its own moe is false, so the + /// expert cache and every loop over the MoE layers leave it out. -1 (every other model): none. + int alias = -1; bool fixed = false; ///< one token's launches can be recorded and replayed for the next ones (eval()): they ///< are the same for every token, or read the position on the card (Engine::at_) Dev attn_norm, ffn_norm; ///< the norms ahead of the attention and of the FFN @@ -195,8 +202,6 @@ struct Stats { /// The most likely token of n logits: the first of the largest. int most_likely(const float* logits, int n); -class Mmq; - /// A picture in a sequence: n rows that stand where n tokens would, each the vision encoder's output for a patch, /// as wide as a token's embedding. The patches come line after line, nx to a line. struct Image { @@ -312,7 +317,9 @@ class Engine { /// saved (Clover on an 8 GB laptop wrote 57.7 tokens/s after a 32K prompt with its guesses, 61.6 without). bool drafts() const { return next_ ? next_->drafts() : draft_ || (block_guess_ && all_cached()); } /// The guesses of a window come out of draft(token, 0, &p) together: asking for one more costs nothing. - bool guesses_at_once() const { return next_ ? next_->guesses_at_once() : block_guess_; } + bool guesses_at_once() const { + return next_ ? next_->guesses_at_once() : block_guess_ || block_drafter_; + } /// Test only: the calls read()'s layer-major path gave the draft block's rows (draft_rows()) on the card that has /// the block, since load. Two or more in one read are back-to-back refills of its pinned input rows. int64_t read_draft_calls_for_test() const { return next_ ? next_->read_draft_calls_for_test() : read_draft_calls_; } @@ -416,6 +423,15 @@ class Engine { /// model's output for the token before pos(); the second is this step's to leave and the next step's to read. /// The engine's own runs the draft block. virtual void draft_step(int32_t token, int i); + /// A drafter that guesses a window's tokens in one pass (block_drafter_): up to `most` guesses after `token` at + /// pos() into out, and how many it made. + virtual int draft_block(int32_t token, int most, Likeliest* out) { + (void) token, (void) most, (void) out; + return 0; + } + /// After a call of the model: its n rows from position pos are in r_, and h holds their outputs, normed. A + /// drafter that reads the model's rows takes them here. + virtual void drafter_rows(int64_t pos, int n, const float* h) { (void) pos, (void) n, (void) h; } /// The floats of every recurrent layer's state together. They are state_'s first. virtual size_t recurrent_floats() const = 0; /// Whether the recurrent layers leave their state after any tokens of a call, and not only after its first @@ -461,6 +477,20 @@ class Engine { } /// The shared expert, into fo_. It runs on the GPU while the host routes. virtual void moe_shared(const Layer& L, int il, int n) = 0; + /// moe_card() of n tokens leaves the experts' sum to the layer's tail: d_ holds each picked expert's output and + /// d_wts_ its weight, and run() sets card_parts_ for the tail that follows. + virtual bool card_sum_in_tail(int n) const { (void) n; return false; } + /// A window's tokens are routed on the card together, as a block of the model's own guesses is, when every expert + /// is in VRAM: card_rows() holds a whole window's rows. false (the default): a window of more than kSumRows rows + /// is routed on the host. + virtual bool windows_on_card() const { return false; } + /// The routed experts' activation of `rows` rows of gate_up straight into q8, the Q8_1 blocks of the down + /// products' input: what act_rows() into h_ and native_quantize_q8_1() of the rows give, in fewer launches. + /// true: done (h_ is not written); false (the default): those two run. + virtual bool act_rows_q8_1(const float* gate_up, void* q8, int rows, const ExpertScales* es) { + (void) gate_up, (void) q8, (void) rows, (void) es; + return false; + } /// The scores of a layer's router for n tokens, into rl_. The engine's own: the router's matrix times the /// experts' input (xn_). virtual void router_scores(const Layer& L, int n); @@ -484,6 +514,12 @@ class Engine { /// Which recording of a layer's head fits n tokens from pos(). Launches that are sized by the rows they read /// are recorded once for each size (room()), and the architecture numbers the sizes from 0. virtual int head_key(int il, int n) const { (void) il, (void) n; return 0; } + /// The CPU threads when Options::threads is 0. false (the default): 70% of the usable CPUs (all of them under a + /// container's CPU quota); true: one a physical core of them. + virtual bool thread_a_core() const { return false; } + /// run() records a fixed layer's head and tail apart when a call's layers are not one recording (its routed + /// experts are not all on the card). false: only the one recording of every layer. + virtual bool layer_graphs() const { return true; } /// layer_head() takes step()'s rows in one call: the products for every row at once, and each row's recurrent /// state and attention rows from its own sequence (rows_of_, seq_state(), seq_buf()), its position from at_. /// Otherwise step() runs the head a row at a time, with the row's sequence bound. @@ -516,10 +552,19 @@ class Engine { /// The other names of a tensor or a metadata key in the files of this architecture, or null. virtual const Names* tensor_alias(const char* name) const { (void) name; return nullptr; } virtual const Names* meta_alias(const char* key) const { (void) key; return nullptr; } + /// The file's layer that layer il runs (Inkling's visits: their physical layer), for the log. + virtual int physical(int il) const { return il; } // ---- what it builds on ---- /// Whether layer il is this engine's: one of [lo_, hi_), or the draft block on the card that ends the model. bool runs(int il) const { return il >= lo_ && (il < hi_ || hi_ == n_layer_); } + /// The layer whose routed experts layer il runs: il itself, or its Layer::alias. + int home_of(int il) const { + const int a = layers_[(size_t) il].alias; + return a < 0 ? il : a; + } + /// A layer with routed experts of its own or another's. + static bool routed(const Layer& L) { return L.moe || L.alias >= 0; } size_t card_state_bytes() const { return state_n_ * sizeof(float) + extra_bytes(); } /// Every expert of this engine's layers is in its cache. bool all_cached() const { return cached_ == n_moe_ * n_expert_; } @@ -541,7 +586,9 @@ class Engine { int shape_i(const char* key) const; float shape_f(const char* key) const; void load_shape(); - void load_moe(int il, bool shared = true); + /// `from`: the layer whose tensors these are, when not il (Inkling's later visits of a layer); -1: il. + /// any_type_scales: the experts' scales (ffn_*_exps.scale) of every type, not only NVFP4's. + void load_moe(int il, bool shared = true, int from = -1, bool any_type_scales = false); void alloc(); void shared_scratch(); float* draft_input(const int32_t* tokens, int64_t row, const float* h, int n); @@ -551,9 +598,28 @@ class Engine { bool input(int32_t token, int64_t row, float* dst) const; void lin(const Dev& w, const float* x, float* y, int n, const void* xq = nullptr, int rows_per_x = 0); void lin_raw(const Dev& w, const float* x, float* y, int n, const void* xq, int rows_per_x); + /// y = w x of several matrices for n tokens, each as lin(w, x, y, n, xq) gives it: those of one quantized format + /// and input width, with their inputs in Q8_1 (xq), in one launch (native_mmvq_jobs()) where it takes them. + struct LinJob { + const Dev* w; + const float* x; + float* y; + const void* xq; + }; + void lin_jobs(const LinJob* jobs, int count, int n); /// The layer's ExpertScales for rows of the experts ids[r] (on the card), or none. ExpertScales expert_scales(const Layer& L, const int32_t* ids = nullptr) const; + /// load() in two: the layers, caches, scratch and staging buffer; then the expert cache and what follows it. + void load_layers(const Options& o); + void load_experts(); void fill_expert_cache(); + /// The reserve fill_expert_cache() keeps free on a card of total_b bytes, and whether the machine's RAM is within + /// 5 GiB of the model's files. + int reserve_for(size_t total_b, bool ram_tight) const; + bool ram_is_tight() const; + /// What the other engines on this card (mates_) need free beside what they hold, which this one's expert cache + /// leaves them. + size_t mates_need() const; void ensure_stage(); void start_swaps(); void plan_ahead(Layer& L, int il); @@ -561,9 +627,13 @@ class Engine { bool pick_way(int t); void took_way(int t, double ms); void layer(int il, int n); - void save_last(uint8_t* dst); + /// After the layers' state at position pos: what is no layer's (the model's output for the last token, with a + /// draft block). + virtual void save_last(uint8_t* dst, int64_t pos); + /// L: the layer as it runs (for a layer with Layer::alias its own, not its experts' layer). void moe_router(const Layer& L, int n); - bool moe(Layer& L, int il, int n, const std::function* first = nullptr); + /// The routed experts of layer il as it runs: its Layer::alias's when it has one. + bool moe(int il, int n, const std::function* first = nullptr); bool card_moe(int n); bool moe_card(Layer& L, int il, int n); const float* biased(const Layer& L, const float* scores); @@ -571,13 +641,17 @@ class Engine { /// a time (moe()). bool batched(const Layer& L, int n) const; /// The routed experts' rows a call routed on the card has room for (d_): a window of a model that guesses its - /// own block, or kSumRows. The others keep kSumRows, whose windows past it are routed on the host as before. + /// own block or routes its windows on the card (windows_on_card()), or kSumRows. The others keep kSumRows, whose + /// windows past it are routed on the host as before. int card_rows() const; void moe_add(int n); template void* record(F&& work); void moe_rows(Layer& L, int il, int n); - void stage(const Layer& L, const int32_t* experts, int m, void* stream, bool alone = false); + void stage(const Layer& L, const int32_t* experts, int m, void* stream, bool alone = false, uint8_t* to = nullptr); + void prestage(const Layer& L, int m, int n); + void settle_prestage(); + int uncached(const Layer& L) const; void mind_memory(); void follow(int written); void follow_loop(); @@ -614,7 +688,7 @@ class Engine { size_t bytes = 0; ///< for every `per` rows int per = 1; }; - void vmm_reserve(Mapped& m, size_t bytes); + void vmm_reserve(Mapped& m, size_t bytes, size_t piece = SIZE_MAX); void vmm_map(Mapped& m, size_t bytes, size_t piece, const char* what); void vmm_unmap(Mapped& m, size_t bytes); void vmm_settle(); @@ -663,6 +737,8 @@ class Engine { int end_ = -1; ///< what open() asked for hi_; -1: the model's end bool split_ = false; ///< one of several engines: a call sets its card first std::unique_ptr next_; + /// The engines of the split on the same card as this one (STRATA_POLY_CARDS above the cards there are) + std::vector mates_; int64_t read_draft_calls_ = 0; ///< read_draft_calls_for_test() const float* pass_ = nullptr; int64_t pass_at_ = 0; @@ -683,6 +759,8 @@ class Engine { ///< for the engine's whole run (see Engine::load()) bool freeze_experts_asked_ = false; ///< the env was set: refreeze_experts() puts it back after the ///< serve VRAM resize lifted it (unfreeze_experts()) + int expert_cap_ = -1; ///< STRATA_GPU_EXPERTS: the cache holds exactly this many experts, + ///< frozen for the run (see Engine::load_layers()); below 0: unset void* blas_ = nullptr; ///< cuBLAS on st_ void* ev_ = nullptr; ///< marks the router's copy to the host: ev_row_'s first, or a window's row's own void* ev_row_[8] = {}; ///< one for each token a window can have @@ -717,16 +795,55 @@ class Engine { void* ev_out_[2] = {}; ///< marks the card done with a call in each half float rms_eps_ = 0; bool gelu_ = false; ///< the routed experts' activation: GELU of the gate, else SiLU within the layer's limits + std::optional situ_; ///< in place of both, Inkling 2's SiTU (cpu_experts.hpp) + /// The routed experts' activation of `rows` rows of n_ff_exp_ gate values then n_ff_exp_ up values, into h. + void act_rows(const float* gate_up, float* h, int rows, float limit, const ExpertScales* es); + /// alloc(): MMQ's scratch taken before the expert cache is filled (Mmq::reserve_fixup()); Inkling 2's, else off + bool reserve_mmq_ = false; + /// A read copies the next layer's experts that are not cached while a layer's calls run (prestage()); Inkling + /// 2's, else off: each layer's copy starts with the layer. + bool prestage_ = false; + /// moe_rows() hands the card a call's row tables by a kernel that reads them from pinned memory (copy2()), not + /// by a copy: the copies to the card went one after the other, and a read's tables (100 KB) waited behind its + /// rows of the residual (63 MiB a call of Inkling 2 Mini's at 1,024 tokens) and the next layer's experts + /// (prestage()). Inkling 2's, else off. + bool kernel_tables_ = false; + /// Q2_0 and IQ1_S experts on this project's kernels: the CPU's AVX2 dot products (cpu_lowbit.hpp) and Q2_0's MMQ + /// tiles (Mmq::fits()). Inkling 2's; off, those types take ggml-cpu's dot products and no tiles. + bool lowbit_experts_ = false; + /// the cached experts' launches through kernels::MmvqSlots::lanes' kernels (the same bits): Inkling 2's, measured + /// there; off, the other families' launches as they were + bool lane_slots_ = false; +#if defined(STRATA_USE_HIP) + /// NVFP4 matrices' prompt products on HIP take the int8 tiles (Mmq::nvfp4_int8) unless STRATA_PREFILL_NVFP4 keeps + /// them out: Inkling 2's, as on CUDA, where every family takes them. Off, a family's NVFP4 matrices go through + /// the decode kernels a token at a time unless STRATA_PREFILL_NVFP4=w4a8 asks for the tiles. + bool nvfp4_int8_ = false; +#endif + /// What MMQ may take for the routed experts and for the dense matrices. + Mmq::Allow expert_mmq() const { +#if defined(STRATA_USE_HIP) + return Mmq::Allow((lowbit_experts_ ? Mmq::q2_0 : Mmq::none) | (nvfp4_int8_ ? Mmq::nvfp4_int8 : Mmq::none)); +#else + return lowbit_experts_ ? Mmq::q2_0 : Mmq::none; +#endif + } + Mmq::Allow dense_mmq() const { return expert_mmq(); } std::vector clamp_exp_, clamp_shexp_; ///< a layer's SwiGLU limits: the routed experts', the shared one's /// a prompt batch's products go through guard_half_sums(): the model's activations can sum past a half's range /// in a block. Off for the models whose sums stay in range: it cost LFM2.5 4% of a 30K prompt's read on a 5090. bool half_sum_guard_ = false; + /// a prompt batch's routed experts through Mmq::mul_tiles(): one launch a product over every cached expert, and + /// one over a staging round's, each expert's rows cut into tiles of their own width (moe_rows()). No tile's sum + /// is split, where llama.cpp's stream-k splits some, so other bits: opt-in (Inkling 2's STRATA_POLY_EXPERT_TILES) + bool expert_tiles_ = false; std::vector layers_; ///< the model's, and after them the draft block Dev out_norm_, output_; bool draft_ = false; bool block_layer_ = false; ///< what guesses ahead is a block after the model's layers (layers_' last) bool block_guess_ = false; ///< the model guesses a window's tokens itself, in a block (block_mask()) + bool block_drafter_ = false; ///< the architecture's drafter guesses a window's tokens in one pass (draft_block()) bool block_pass_ = false; ///< the call under way is that block: its tokens see each other, no state changes Likeliest* h_block_ = nullptr; ///< the block's guesses and their probabilities, pinned int block_n_ = 0; ///< how many it holds @@ -810,6 +927,8 @@ class Engine { int snap_places_ = 0; ///< how many states it holds float* snap_at_ = nullptr; ///< where the call under way leaves the first of its states unsigned snap_bits_ = 0; ///< the tokens of the call under way that leave their state, a bit a token + bool card_parts_ = false; ///< the next layer_tail()'s experts went through moe_card() with their sum left to it + bool layers_in_order_ = false; ///< run()'s layers are under way: a layer's tail is followed by the next one's head bool windowed_ = false; ///< the call under way is a window's // step() with guesses: a place for every sequence's state after its first row, and what keep_step() settles float* step_snap_ = nullptr; @@ -868,6 +987,18 @@ class Engine { void* ev_hr_ = nullptr; ///< marks the card's last read of h_r_ by draft_input() int staged_il_ = -1; ///< the layer whose experts the buffer holds for its next call, or -1 std::vector staged_; ///< those experts, in the buffer's order: one round of the layer's + size_t stage_at_ = 0; ///< where in stage_ that round starts + struct Prestaged { + int il = -1; ///< the layer whose experts the copy is of, or -1 + size_t at = 0; ///< where in stage_ + std::vector experts; ///< the layer's L.ahead when it was planned + int ev = 0; ///< which of ev_pre_ marks its end + } pre_; ///< prestage()'s copy + std::thread pre_th_; ///< fills the pinned buffers for it + std::exception_ptr pre_err_; + /// mark the ends of those copies in turn: the next layer's copy starts before this one's calls wait for theirs + void* ev_pre_[2] = {}; + int next_home_ = -1; ///< read(): the layer whose experts the next turn runs, or -1 double ahead_ms_ = 0, route_ms_ = 0; ///< what that layer's copy ahead took, and the card to its routing bool shared_ahead_ = false; ///< read() runs several calls: each copies ahead, whatever its size size_t stage_bytes_ = 0, chunk_bytes_ = 0; @@ -877,6 +1008,14 @@ class Engine { size_t stage_cut_ = 0; ///< what the cache gave up for it, which it takes back int stage_turn_ = 0; std::vector ids_, count_, first_, group_, round_, round_row_; + // expert_tiles_: a call's tiles (the cached experts', then each staging round's from tile_at_[r]) and the + // matrices' offsets (the cached experts' slots from the lowest, a round's gate|up and down from the buffer's), + // here and on the card + std::vector tiles_; + std::vector tile_at_; + std::vector tile_first_, tile_rows_, tile_mat_; + int64_t *h_mat_at_ = nullptr, *mat_at_ = nullptr; + Mmq::Tile* d_tiles_ = nullptr; std::vector staged_tiles_; ///< STRATA_POLY_STAGED_TILES: the rows that end a size class of staged experts std::vector route_tmp_; ///< route()'s scratch, a share for each host thread std::vector bias_rl_; ///< one token's scores with Options::cache_bias added (moe()) diff --git a/src/poly/gemm_small_test.cu b/src/poly/gemm_small_test.cu index ca97897ab3..dccc991d25 100644 --- a/src/poly/gemm_small_test.cu +++ b/src/poly/gemm_small_test.cu @@ -1,14 +1,17 @@ -// src/poly/gemm_small_test.cu - gemm_f32() for one group of up to 256 outputs (gemm_small_kernel, gemm_tile_kernel past -// 64 of them) against the same products on the host: each output's sum of fmaf in the inputs' order, so the bits -// must be the same. +// src/poly/gemm_small_test.cu - gemm_f32() for one group of up to 256 outputs (gemm_small_kernel up to 32 of them, +// gemm_tile_kernel past that) against the same products on the host: each output's sum of fmaf in the inputs' order, +// so the bits must be the same. --bench also times the calls of Inkling 2 Mini's prompt batches (its router, 2,304 +// inputs to 128 outputs, and its controllers' down products, 4,608 to 64) and prints a hash of each one's outputs, +// to compare two builds by. // -// usage: poly_gemm_small_test (exit 0: every output the same) +// usage: poly_gemm_small_test [--bench] (exit 0: every output the same) #include "strata/poly/kernels.hpp" #include #include #include +#include #include #include #include @@ -18,35 +21,69 @@ namespace { using namespace strata::poly; +struct Product { + std::vector w, x, y; + float *dw = nullptr, *dx = nullptr, *dy = nullptr; + Product(int n_in, int n_out, int rows, std::mt19937& rng) + : w(size_t(n_in) * n_out), x(size_t(n_in) * rows), y(size_t(n_out) * rows) { + std::normal_distribution nd(0.f, 1.f); + for (float& v : w) v = 0.05f * nd(rng); + for (float& v : x) v = nd(rng); + cudaMalloc(&dw, w.size() * sizeof(float)); + cudaMalloc(&dx, x.size() * sizeof(float)); + cudaMalloc(&dy, y.size() * sizeof(float)); + cudaMemcpy(dw, w.data(), w.size() * sizeof(float), cudaMemcpyHostToDevice); + cudaMemcpy(dx, x.data(), x.size() * sizeof(float), cudaMemcpyHostToDevice); + } + ~Product() { cudaFree(dw), cudaFree(dx), cudaFree(dy); } + void get() { cudaMemcpy(y.data(), dy, y.size() * sizeof(float), cudaMemcpyDeviceToHost); } +}; + int check(cublasHandle_t h, int n_in, int n_out, int rows, std::mt19937& rng) { - std::normal_distribution nd(0.f, 1.f); - std::vector w(size_t(n_in) * n_out), x(size_t(n_in) * rows), want(size_t(n_out) * rows), - got(want.size()); - for (float& v : w) v = 0.05f * nd(rng); - for (float& v : x) v = nd(rng); + Product p(n_in, n_out, rows, rng); + std::vector want(p.y.size()); for (int t = 0; t < rows; ++t) for (int o = 0; o < n_out; ++o) { float acc = 0.f; - for (int k = 0; k < n_in; ++k) acc = std::fma(x[size_t(t) * n_in + k], w[size_t(o) * n_in + k], acc); + for (int k = 0; k < n_in; ++k) + acc = std::fma(p.x[size_t(t) * n_in + k], p.w[size_t(o) * n_in + k], acc); want[size_t(t) * n_out + o] = acc; } - float *dw = nullptr, *dx = nullptr, *dy = nullptr; - cudaMalloc(&dw, w.size() * sizeof(float)); - cudaMalloc(&dx, x.size() * sizeof(float)); - cudaMalloc(&dy, got.size() * sizeof(float)); - cudaMemcpy(dw, w.data(), w.size() * sizeof(float), cudaMemcpyHostToDevice); - cudaMemcpy(dx, x.data(), x.size() * sizeof(float), cudaMemcpyHostToDevice); - gemm_f32(h, dw, dx, dy, n_in, n_out, n_out, rows); - cudaMemcpy(got.data(), dy, got.size() * sizeof(float), cudaMemcpyDeviceToHost); - cudaFree(dw), cudaFree(dx), cudaFree(dy); - const bool ok = !std::memcmp(want.data(), got.data(), want.size() * sizeof(float)); + cudaMemset(p.dy, 0xff, p.y.size() * sizeof(float)); + gemm_f32(h, p.dw, p.dx, p.dy, n_in, n_out, n_out, rows); + p.get(); + const bool ok = !std::memcmp(want.data(), p.y.data(), want.size() * sizeof(float)); std::printf("%s n_in %4d n_out %3d rows %4d\n", ok ? "ok " : "FAIL", n_in, n_out, rows); return ok ? 0 : 1; } +void bench(cublasHandle_t h, int n_in, int n_out, int rows, std::mt19937& rng) { + Product p(n_in, n_out, rows, rng); + cudaStream_t stream = nullptr; + cublasGetStream(h, &stream); + cudaEvent_t e0, e1; + cudaEventCreate(&e0), cudaEventCreate(&e1); + for (int i = 0; i < 5; ++i) gemm_f32(h, p.dw, p.dx, p.dy, n_in, n_out, n_out, rows); + constexpr int reps = 50; + cudaEventRecord(e0, stream); + for (int i = 0; i < reps; ++i) gemm_f32(h, p.dw, p.dx, p.dy, n_in, n_out, n_out, rows); + cudaEventRecord(e1, stream); + cudaEventSynchronize(e1); + float ms = 0.f; + cudaEventElapsedTime(&ms, e0, e1); + p.get(); + uint64_t hash = 14695981039346656037ull; // FNV-1a of the outputs' bytes + const unsigned char* const bytes = reinterpret_cast(p.y.data()); + for (size_t i = 0; i < p.y.size() * sizeof(float); ++i) hash = (hash ^ bytes[i]) * 1099511628211ull; + const double us = 1000.0 * ms / reps; + std::printf("bench n_in %4d n_out %3d rows %4d %8.1f us %5.2f TFLOPS fnv %016llx\n", n_in, n_out, rows, us, + 2.0 * n_in * n_out * rows / us * 1e-6, (unsigned long long) hash); + cudaEventDestroy(e0), cudaEventDestroy(e1); +} + } // namespace -int main() { +int main(int argc, char** argv) { cublasHandle_t h = nullptr; if (cublasCreate(&h) != CUBLAS_STATUS_SUCCESS) { std::printf("no cuBLAS\n"); @@ -57,7 +94,19 @@ int main() { for (int n_out : {32, 64, 100, 128, 256}) for (int rows : {32, 37, 1024, 2048}) bad += check(h, 2048, n_out, rows, rng); bad += check(h, 2000, 64, 45, rng); // inputs that end inside a step - bad += check(h, 2000, 256, 45, rng); // and of gemm_tile_kernel's + bad += check(h, 2000, 256, 45, rng); + bad += check(h, 2000, 33, 45, rng); // the fewest outputs that take gemm_tile_kernel + for (int rows : {16, 333, 1024}) { // Inkling 2 Mini's router and controllers + bad += check(h, 2304, 128, rows, rng); + bad += check(h, 4608, 64, rows, rng); + } + if (argc > 1 && !std::strcmp(argv[1], "--bench")) { + std::mt19937 brng(11); + for (int rows : {333, 1024, 4096}) { + bench(h, 2304, 128, rows, brng); + bench(h, 4608, 64, rows, brng); + } + } cublasDestroy(h); if (const cudaError_t e = cudaGetLastError(); e != cudaSuccess) { std::printf("CUDA: %s\n", cudaGetErrorString(e)); diff --git a/src/poly/inkling.cpp b/src/poly/inkling.cpp new file mode 100644 index 0000000000..6caf316b29 --- /dev/null +++ b/src/poly/inkling.cpp @@ -0,0 +1,1431 @@ +// src/poly/inkling.cpp - the layers of Inkling 2 Mini. The reference for the math is llama.cpp's +// src/models/inkling2.cpp and inkling2-loop.cpp (29b52d398b); the kernels' header has it written out +// (include/strata/poly/inkling_kernels.hpp). +#include "inkling.hpp" + +#include "runtime.hpp" +#include "strata/poly/inkling_kernels.hpp" +#include "strata/poly/kernels.hpp" +#include "strata/kernels/native_mmvq.hpp" + +#include +#include +#include +#include +#include +#include + +namespace strata::poly { +namespace { + +int64_t of_layer(const MetaValue& v, int il) { + if (v.type != MetaType::ARRAY) return (int64_t) v.u; + if ((size_t) il >= v.items.size()) throw std::runtime_error("a per-layer value of the GGUF ends before its layers"); + return (int64_t) v.items[(size_t) il].u; +} + +const char* const kCtrl[4] = {"q", "k", "v", "ffn"}; + +constexpr int kSparkRows = 256; // the model's rows the DSpark drafter takes in a launch + +// Unsloth's files (architecture "inkling2", the loop in its metadata) name the loop's parts otherwise; byte for byte +// they are the ggml-org file's: attn = q, mlp = ffn. +const Names kTensorNames[] = { + {"loop_q_ctrl_down.weight", {"loop_attn_down.weight", nullptr}}, + {"loop_q_ctrl_gain.weight", {"loop_attn_gain.weight", nullptr}}, + {"loop_q_ctrl_forget.weight", {"loop_attn_forget.weight", nullptr}}, + {"loop_k_ctrl_down.weight", {"loop_k_down.weight", nullptr}}, + {"loop_k_ctrl_gain.weight", {"loop_k_gain.weight", nullptr}}, + {"loop_k_ctrl_forget.weight", {"loop_k_forget.weight", nullptr}}, + {"loop_v_ctrl_down.weight", {"loop_v_down.weight", nullptr}}, + {"loop_v_ctrl_gain.weight", {"loop_v_gain.weight", nullptr}}, + {"loop_v_ctrl_forget.weight", {"loop_v_forget.weight", nullptr}}, + {"loop_ffn_ctrl_down.weight", {"loop_mlp_down.weight", nullptr}}, + {"loop_ffn_ctrl_gain.weight", {"loop_mlp_gain.weight", nullptr}}, + {"loop_ffn_ctrl_forget.weight", {"loop_mlp_forget.weight", nullptr}}, +}; +const Names kMetaNames[] = { + {"loop.start", {"loop.core_start", nullptr}}, + {"loop.end", {"loop.core_end", nullptr}}, + {"loop.count", {"num_loops", nullptr}}, +}; + +// Where a visit's keys and values go, in its planes pl: fp16 keys and values, or q8_0 codes and scales. +InklingKvDst kv_dst(bool q8, uint8_t* const* pl, int ring) { + InklingKvDst dst; + if (q8) { + dst.kc = (int8_t*) pl[0], dst.ks = (uint16_t*) pl[1]; + dst.vc = (int8_t*) pl[2], dst.vs = (uint16_t*) pl[3]; + } else { + dst.k = (uint16_t*) pl[0], dst.v = (uint16_t*) pl[1]; + } + dst.ring = ring; + return dst; +} + +// The caches the attention of a token at `pos` reads, in the planes pl. +InklingAttnSeq attn_seq(bool q8, uint8_t* const* pl, int64_t pos, int64_t room) { + InklingAttnSeq c; + if (q8) { + c.kq8 = Kvq8{(const int8_t*) pl[0], (const uint16_t*) pl[1]}; + c.vq8 = Kvq8{(const int8_t*) pl[2], (const uint16_t*) pl[3]}; + } else { + c.kcache = (const uint16_t*) pl[0]; + c.vcache = (const uint16_t*) pl[1]; + } + c.pos = pos; + c.room = room; + return c; +} + +} // namespace + +// ---- visits ---------------------------------------------------------------------------------------------------- + +int Inkling::phys_of(int v) const { + const int core = core_end_ - core_start_, end = core_start_ + n_passes_ * core; + if (v < core_start_) return v; + if (v < end) return core_start_ + (v - core_start_) % core; + return v - (n_passes_ - 1) * core; +} + +int Inkling::pass_of(int v) const { + const int core = core_end_ - core_start_, end = core_start_ + n_passes_ * core; + return v < core_start_ || v >= end ? 0 : (v - core_start_) / core; +} + +// llama.cpp's cache slot of a visit: the physical layer for the first pass, then n_phys + the later passes' runs. +int Inkling::slot_of(int v) const { + const int p = phys_of(v), q = pass_of(v); + return q == 0 ? p : n_phys_ + (q - 1) * (core_end_ - core_start_) + (p - core_start_); +} + +void Inkling::begin_pass() { blocks_.assign(layers_.size(), Block{}); } + +const Names* Inkling::tensor_alias(const char* name) const { + for (const Names& n : kTensorNames) + if (std::strcmp(n.name, name) == 0) return &n; + return nullptr; +} + +const Names* Inkling::meta_alias(const char* key) const { + for (const Names& n : kMetaNames) + if (std::strcmp(n.name, key) == 0) return &n; + return nullptr; +} + +void Inkling::split_layers(const Shards& file, int& n_layer, int& keep_lo, int& keep_hi) { + const std::string pre = file.get("general.architecture")->s + "."; + const auto num = [&](const char* key) { + const MetaValue* v = file.get(pre + key); + for (const Names& n : kMetaNames) + if (!v && std::strcmp(n.name, key) == 0) + for (const char* other : n.other) + if (other && !v) v = file.get(pre + other); + if (!v) throw std::runtime_error(std::string("unsupported model: no ") + pre + key); + return (int) v->u; + }; + keep_lo = num("loop.start"); + keep_hi = num("loop.end"); + if (pre == "inkling2.") n_layer -= (num("loop.count") - 1) * (keep_hi - keep_lo); // Unsloth's: every visit +} + +void Inkling::load_geometry() { + // --draft-model is the DSpark drafter here, a model of its own, not a file of this one with a block in it, + // which is what load_shape() would look for + std::unique_ptr spark = std::move(dg_); + load_shape(); + auto find = [&](const char* key) { return meta_in(*gg_, key); }; + auto need = [](bool ok, const char* what) { + if (!ok) throw std::runtime_error(std::string("unsupported model: ") + what); + }; + auto must = [&](const char* key) -> const MetaValue& { + const MetaValue* v = find(key); + need(v != nullptr, key); + return *v; + }; + unsloth_ = gg_->get("general.architecture")->s == "inkling2"; + core_start_ = shape_i("loop.start"); + core_end_ = shape_i("loop.end"); + n_passes_ = shape_i("loop.count"); + // ggml-org's block_count is the physical layers, unsloth's every visit + n_phys_ = unsloth_ ? n_layer_ - (n_passes_ - 1) * (core_end_ - core_start_) : n_layer_; + rank_ = shape_i("loop.gate_rank"); + const MetaValue* varying = find("loop.varying"); + need(!varying || varying->u == 0, "a loop whose passes vary (inkling2_loop.loop.varying)"); + need(shape_i("attn_res.block_size") == kBlockSize, "attn_res.block_size is not 6"); + // the streams in r_ hold four blocks and one block of the pass before: Inkling 2 Mini's shape + need(n_phys_ == 24 && core_start_ == 6 && core_end_ == 18 && n_passes_ >= 2 && n_passes_ <= kMaxPasses, + "a loop other than layers 6 to 17 of 24, or a bad loop.count"); + // the controllers' decode kernel holds the rank's values in a warp's registers (inkling_control_fused()) + if (rank_ <= 0 || rank_ > kInklingMaxRank) + throw std::runtime_error("unsupported model: loop.gate_rank is " + std::to_string(rank_) + ", 1 to " + + std::to_string(kInklingMaxRank) + " is supported"); + n_layer_ = n_phys_ + (n_passes_ - 1) * (core_end_ - core_start_); + + const MetaValue& heads = must("attention.head_count"); + const MetaValue& kv = must("attention.head_count_kv"); + n_head_ = (int) of_layer(heads, 0); + n_kv_ = (int) of_layer(kv, 0); + for (int il = 0; il < n_phys_; ++il) + need(of_layer(heads, il) == n_head_ && of_layer(kv, il) == n_kv_, "layers with different head counts"); + head_dim_ = shape_i("attention.key_length"); + need(shape_i("attention.value_length") == head_dim_, "the keys and values have different widths"); + need(head_dim_ == 128 && n_kv_ > 0 && n_head_ == 3 * n_kv_, "attention other than 3 query heads of 128 a key"); + n_rel_ = shape_i("attention.relative_length"); + extent_ = shape_i("attention.relative_extent"); + window_ = shape_i("attention.sliding_window"); + need(n_rel_ > 0 && n_rel_ <= 32 && extent_ > 0 && window_ > 0, "bad relative-position or window sizes"); + n_conv_ = shape_i("shortconv.l_cache"); + need(n_conv_ == 4, "shortconv.l_cache is not 4"); + const MetaValue& swa = must("attention.sliding_window_pattern"); + for (int il = 0; il < n_phys_; ++il) of_layer(swa, il); + qk_clip_ = shape_f("attention.qk_clip"); + rel_clip_ = shape_f("attention.relative_clip"); + tau_floor_ = shape_i("attention.log_scale_floor"); + tau_alpha_ = shape_f("attention.log_scale_alpha"); + need(tau_floor_ > 0 && qk_clip_ > 0.f && rel_clip_ > 0.f, "bad clips or log scale"); + const MetaValue* cap = find("final_logit_softcapping"); + softcap_ = cap ? (float) cap->f : 0.f; + const MetaValue* scale = find("expert_weights_scale"); + w_scale_ = scale ? (float) scale->num() : 0.f; +#if defined(STRATA_USE_HIP) + nvfp4_int8_ = true; // NVFP4 matrices' prompt products on the int8 tiles, as on CUDA +#endif + reserve_mmq_ = true; // MMQ's scratch before the expert cache takes the VRAM + prestage_ = true; // a read's next layer's experts come while a layer runs + kernel_tables_ = true; // and a call's tables do not wait behind the copies to the card + lowbit_experts_ = true; // Unsloth's files: IQ1_S gate_up and Q2_0 down experts + // STRATA_POLY_EXPERT_TILES=1: a prompt batch's experts in tiles of their own widths (Engine::expert_tiles_). + // Opt-in: no tile's sum is split over K where llama.cpp's stream-k splits some, so the sums differ in rounding. + if (const char* e = std::getenv("STRATA_POLY_EXPERT_TILES"); e && std::atoi(e) != 0) expert_tiles_ = true; +#if !defined(STRATA_USE_HIP) + lane_slots_ = true; // the cached experts' launches through MmvqSlots::lanes' kernels (measured on CUDA) +#endif + situ_ = Situ{shape_f("activation.situ_beta"), shape_f("activation.situ_linear_beta")}; + need(situ_->beta > 0.f, "bad activation.situ_beta"); + const MetaValue* real = find("vocab_size_unpadded"); + n_vocab_real_ = real ? (int) real->u : n_vocab_; + need(n_vocab_real_ > 0 && n_vocab_real_ <= n_vocab_, "bad vocab_size_unpadded"); + conv_floats_ = (size_t) (n_conv_ - 1) * (2 * (size_t) n_kv_ * head_dim_ + 2 * (size_t) n_embd_); + + clamp_exp_.assign((size_t) n_layer_ + 1, INFINITY); + clamp_shexp_ = clamp_exp_; + + // step()'s rows are a sequence's each, and the _seqs kernels take kInklingSeqRows of them a launch + if (opt_.batch + 1 > kInklingSeqRows) + throw std::runtime_error("Inkling 2: --batch takes at most " + std::to_string(kInklingSeqRows - 1)); + if (opt_.kv_format != KvFmt::kFp16 && opt_.kv_format != KvFmt::kQ8_0) + throw std::runtime_error("Inkling 2: the attention cache is fp16 or q8_0"); + // A card of a split has a run of physical layers (split_layers()), here its visits: the core's on one card. + const auto visit = [&](int p) { + if (p > core_start_ && p < core_end_) throw std::logic_error("Inkling 2: a card starts inside the loop"); + return p <= core_start_ ? p : p + (n_passes_ - 1) * (core_end_ - core_start_); + }; + lo_ = visit(lo_); + if (end_ >= 0) end_ = visit(end_); + // The file has no block that guesses ahead. With the DSpark drafter (--draft-model) a window is the token and three + // of its guesses; without, the guesses come from the conversation's repeats (--lookup) only: opt-in with --window, + // a token at a time by default. + if (opt_.window == 0) opt_.window = spark ? 4 : 1; + opt_.draft = false; + if (spark) { + if (opt_.batch > 0) throw std::runtime_error("Inkling 2: the DSpark drafter (--draft-model) is not for --batch"); + dg_ = std::move(spark); + block_ = dg_.get(); // the file its tensors are read from (home()) + load_spark_shape(); + spark_ = draft_ = block_drafter_ = true; + } + std::fprintf(stderr, "strata-poly: %s: %d layers, %d to %d run %d times: %d visits\n", + unsloth_ ? "inkling2 (looped)" : "inkling2_loop", n_phys_, core_start_, core_end_ - 1, n_passes_, + n_layer_); +} + +void Inkling::load_layer(int v) { + Layer& L = layers_[(size_t) v]; + Block& B = blocks_[(size_t) v]; + const int p = phys_of(v); + const int first = p < core_end_ ? p : p + (n_passes_ - 1) * (core_end_ - core_start_); + if (v != first) { // a later visit: the first one's weights, and caches of its own + const Block& F = blocks_[(size_t) first]; + B = F; + B.pass = pass_of(v); + B.conv = nullptr; + for (uint8_t*& q : B.plane) q = nullptr; + L = layers_[(size_t) first]; + L.moe = false; // the first visit's experts: one copy of each in the cache (Layer::alias) + L.alias = first; + L.slot.clear(); + return; + } + auto f32 = [&](const char* n, int64_t a, int64_t b = 1) { return upload(tensor(p, n), blk(p, n), a, b, kF32); }; + auto mat = [&](const char* n, int64_t a, int64_t b) { return upload(tensor(p, n), blk(p, n), a, b, kAnyMat); }; + const int64_t E = n_embd_, hq = (int64_t) n_head_ * head_dim_, hk = (int64_t) n_kv_ * head_dim_; + + if (v == lo_) { // the model's own small tensors, beside the card's first layer: the input's and the output's + if (lo_ == 0) tok_norm_ = upload(gg_->find("token_embd_norm.weight"), "token_embd_norm.weight", E, 1, kF32); + if (hi_ == n_layer_) + out_query_ = upload(gg_->find("output_res_query.weight"), "output_res_query.weight", E, 1, kF32); + } + B.phys = p; + B.pass = 0; + // a token alone and a window's tokens are recorded (Engine::run()), a recording for each number of tokens; + // pictures and step()'s rows take the kernels' positions by value. step() replays a fixed layer's head without + // asking layer_graphs(), and its recordings are keyed by row, not position: fixed must stay off with --batch. + L.fixed = opt_.batch == 0; + B.swa = of_layer(*meta_in(*gg_, "attention.sliding_window_pattern"), p) != 0; + B.wq = mat("attn_q.weight", E, hq); + B.wk = mat("attn_k.weight", E, hk); + B.wv = mat("attn_v.weight", E, hk); + B.wo = mat("attn_output.weight", hq, E); + B.wgate = mat("attn_gate.weight", E, hq); + B.wrel = mat("attn_rel.weight", E, (int64_t) n_rel_ * n_head_); + B.wsink = mat("attn_sink_proj.weight", E, n_head_); + const TensorInfo* rb = tensor(p, "attn_rel_bias.weight"); + if (!rb || rb->shape.size() != 2 || (int) rb->shape[0] != n_rel_) + throw std::runtime_error(blk(p, "attn_rel_bias.weight") + " is missing or not [" + std::to_string(n_rel_) + + ", extent]"); + B.extent = (int) rb->shape[1]; + if (B.extent != (B.swa ? window_ : extent_)) + throw std::runtime_error(blk(p, "attn_rel_bias.weight") + " has " + std::to_string(B.extent) + + " distances, expected " + std::to_string(B.swa ? window_ : extent_)); + B.rel_bias = f32("attn_rel_bias.weight", n_rel_, B.extent); + B.q_clip = f32("attn_q_clip.weight", head_dim_, n_head_); + B.rel_clip = f32("attn_rel_clip.weight", n_rel_, n_head_); + B.k_conv = f32("attn_k_conv.weight", n_conv_, hk); + B.v_conv = f32("attn_v_conv.weight", n_conv_, hk); + B.post_conv = f32("attn_post_conv.weight", n_conv_, E); + B.ffn_post_conv = f32("ffn_post_conv.weight", n_conv_, E); + if (B.swa) { + L.attn_norm = f32("attn_norm.weight", E); + } else { + B.q_norm = f32("attn_q_inp_norm.weight", E); + B.k_norm = f32("attn_k_inp_norm.weight", E); + B.v_norm = f32("attn_v_inp_norm.weight", E); + B.k_conv_proj = mat("attn_k_conv_proj.weight", E, (int64_t) n_conv_ * n_kv_); + B.v_conv_proj = mat("attn_v_conv_proj.weight", E, (int64_t) n_conv_ * n_kv_); + } + if (p > 0) B.attn_query = f32("attn_res_query.weight", E, B.swa ? 1 : 3); + B.ffn_query = f32("ffn_res_query.weight", E); + L.ffn_norm = f32("ffn_norm.weight", E); + if (p >= core_start_ && p < core_end_) { + if (unsloth_ && !tensor(p, "loop_msg_query.weight")) { + // unsloth's queries are two tensors of the model, [2304, 24] each: row 2i and 2i + 1 of loop_res_query are + // core layer start + i's q and ffn queries, of loop_kv_res_query its k and v ones + const TensorInfo* rq = gg_->find("loop_res_query.weight"); + const TensorInfo* kq = gg_->find("loop_kv_res_query.weight"); + const int nc = core_end_ - core_start_; + for (const TensorInfo* t : {rq, kq}) + if (!t || t->type != kTypeF32 || (int64_t) t->elements() != 2 * nc * E) + throw std::runtime_error("inkling2: loop_res_query / loop_kv_res_query missing or not F32 [2304, " + + std::to_string(2 * nc) + "]"); + if (dense_) { // the second pass of the load: VRAM of its own beside the arena + if (!msg_mem_) msg_mem_ = dmalloc((size_t) nc * 4 * E * sizeof(float), "the loop's queries"); + const int i = p - core_start_; + const float* r = (const float*) home(*rq).data(*rq); + const float* k = (const float*) home(*kq).data(*kq); + std::vector q((size_t) 4 * E); + std::memcpy(q.data(), r + (size_t) (2 * i) * E, E * sizeof(float)); + std::memcpy(q.data() + E, k + (size_t) (2 * i) * E, E * sizeof(float)); + std::memcpy(q.data() + 2 * E, k + (size_t) (2 * i + 1) * E, E * sizeof(float)); + std::memcpy(q.data() + 3 * E, r + (size_t) (2 * i + 1) * E, E * sizeof(float)); + float* d = (float*) msg_mem_ + (size_t) i * 4 * E; + h2d(d, q.data(), q.size() * sizeof(float)); + B.msg_query = Dev{d, kTypeF32, (int) E, 4}; + } + } else { + B.msg_query = f32("loop_msg_query.weight", E, 4); + } + for (int c = 0; c < 4; ++c) { + const std::string pre = std::string("loop_") + kCtrl[c] + "_ctrl_"; + B.ctrl_down[c] = f32((pre + "down.weight").c_str(), 2 * E, rank_); + B.ctrl_gain[c] = f32((pre + "gain.weight").c_str(), rank_, E); + B.ctrl_forget[c] = f32((pre + "forget.weight").c_str(), rank_, E); + } + } + load_moe(v, false, p, true); // Unsloth's files scale every expert's gate_up and down, whatever their type + if (L.gate_inp.type != kTypeF32) // router_scores() takes it as floats + throw std::runtime_error(blk(p, "ffn_gate_inp.weight") + " is not F32"); + B.probs_b.assign((size_t) n_expert_, 0.f); + if (const TensorInfo* b = tensor(p, "exp_probs_b.bias")) { + if (b->type != kTypeF32 || (int64_t) b->elements() != n_expert_) + throw std::runtime_error(blk(p, "exp_probs_b.bias") + " is " + shape_of(*b) + ", expected F32 [" + + std::to_string(n_expert_) + "]"); + std::memcpy(B.probs_b.data(), home(*b).data(*b), (size_t) n_expert_ * sizeof(float)); + B.probs_b_dev = upload(b, blk(p, "exp_probs_b.bias"), n_expert_, 1, kF32); + } +} + +size_t Inkling::recurrent_floats() const { return (size_t) n_layer_ * conv_floats_; } + +// Each visit's convolution state in state_; a window visit's caches are a ring of the rows a call can read, a full +// one's a row a position. +void Inkling::alloc_caches() { + ring_ = std::min(opt_.max_context, window_ + rows_); + keep_ = std::min(window_, ring_); + size_t one = 0; // a position's bytes in a visit's planes together + for (int i = 0; i < planes(); ++i) one += plane_row(i); + if (q8()) std::fprintf(stderr, "strata-poly: q8_0 KV cache: %zu bytes a row\n", one / 2); + // STRATA_KV_INT8=1 reads the q8_0 cache of a decoded token with __dp4a, the queries quantized too (as Kolibri's + // does). Opt-in: other arithmetic, so other bits; fp16 caches and prompt batches are unchanged. + if (const char* e = std::getenv("STRATA_KV_INT8"); e && std::atoi(e) != 0 && !int8_dot_) { + int8_dot_ = q8(); + std::fprintf(stderr, "strata-poly: STRATA_KV_INT8: decode attention %s\n", + int8_dot_ ? "through __dp4a on the q8_0 cache" : "unchanged (the cache is not q8_0)"); + } + size_t rings = 0; + for (int v = 0; v < (int) blocks_.size(); ++v) + if (runs(v) && blocks_[(size_t) v].swa) rings += (size_t) ring_ * one; + uint8_t* kv = rings ? (uint8_t*) seq_alloc(rings, "the attention cache") : nullptr; + float* st = state_; + for (int v = 0; v < (int) blocks_.size(); ++v) { + Block& B = blocks_[(size_t) v]; + if (!runs(v)) continue; + B.conv = st; + st += conv_floats_; + for (int i = 0; i < planes(); ++i) { + if (B.swa) { + B.plane[i] = kv; + kv += (size_t) ring_ * plane_row(i); + } else { + B.plane[i] = (uint8_t*) kv_alloc(plane_row(i), 1); + } + } + } + if (!mix_work_) { // inkling_mix_conv()'s meeting place + mix_work_ = dmalloc(inkling_mix_conv_work_bytes(), "scratch"); + ck(cudaMemset(mix_work_, 0, inkling_mix_conv_work_bytes()), "scratch"); + } + // the drafter's: its window layers' rings, its other layer's rows, and the head's context of the last positions + if (spark_) { + const size_t row = (size_t) s_kv_ * s_dim_ * sizeof(uint16_t); + for (SparkLayer& D : spark_layers_) { + if (D.swa) { + D.k = (uint16_t*) seq_alloc((size_t) s_ring_ * row, "the drafter's cache"); + D.v = (uint16_t*) seq_alloc((size_t) s_ring_ * row, "the drafter's cache"); + } else { + D.k = (uint16_t*) kv_alloc(row, 1); + D.v = (uint16_t*) kv_alloc(row, 1); + } + } + s_rnn_ = (float*) seq_alloc((size_t) (s_block_ + 1) * n_embd_ * sizeof(float), "the drafter's cache"); + } + // the padded vocabulary's scores, which finish_logits() puts out of reach + if (!neg_inf_ && n_vocab_ > n_vocab_real_) { + const size_t pad_n = (size_t) (n_vocab_ - n_vocab_real_); + neg_inf_ = (float*) dmalloc(pad_n * sizeof(float), "scratch"); + std::vector h(pad_n, -INFINITY); + ck(cudaMemcpy(neg_inf_, h.data(), pad_n * sizeof(float), cudaMemcpyHostToDevice), "scratch"); + } +} + +// Per-token buffers hold rows_ tokens, row after row. +void Inkling::assign_scratch() { + const size_t n = (size_t) rows_, e = n * n_embd_, hq = n * n_head_ * head_dim_, hk = n * n_kv_ * head_dim_; + res_ = fbuf(e); + for (float*& b : blk_) b = fbuf(e); + bank_ = fbuf(e); + bank_out_ = fbuf(e); + for (float*& m : msg_) m = fbuf(e); + for (float*& m : mix_) m = fbuf(e); + for (float*& m : in_) m = fbuf(e); + for (float*& m : ctl_) m = fbuf(e); + const size_t q8 = (n * kernels::native_q8_1_bytes(n_embd_) + sizeof(float) - 1) / sizeof(float); + for (void*& m : inq_) m = fbuf(q8); + attq_ = fbuf((n * kernels::native_q8_1_bytes(n_head_ * head_dim_) + sizeof(float) - 1) / sizeof(float)); + ctl_work_ = fbuf(n * (4 * (size_t) n_embd_ + rank_)); + q_ = fbuf(hq); + gate_ = fbuf(hq); + att_ = fbuf(hq); + kraw_ = fbuf(hk); + k_ = fbuf(hk); + vraw_ = fbuf(hk); + v_ = fbuf(hk); + rel_ = fbuf(n * n_head_ * n_rel_); + sink_ = fbuf(n * n_head_); + ktap_ = fbuf(n * n_kv_ * n_conv_); + vtap_ = fbuf(n * n_kv_ * n_conv_); + o_ = fbuf(e); + awork_n_ = inkling_attend_work_floats(n_head_, head_dim_); + awork_ = awork_n_ ? fbuf(awork_n_) : nullptr; + if (!spark_) return; + if (rows_ < s_block_) + throw std::runtime_error("Inkling 2: the DSpark drafter takes a block of " + std::to_string(s_block_) + + " rows: a prompt batch of fewer cannot hold it"); + const size_t c = (size_t) std::min(rows_, kSparkRows), b = (size_t) s_block_, E = (size_t) n_embd_; + const size_t sq = (size_t) s_head_ * s_dim_, sk = std::max(b, c) * s_kv_ * s_dim_, r = (size_t) s_rank_; + for (float*& x : s_ctx_) x = fbuf(c * E); + s_x_ = fbuf(b * E); + s_xn_ = fbuf(b * E); + s_q_ = fbuf(b * sq); + s_qr_ = fbuf(b * sq); + s_k_ = fbuf(sk); + s_kr_ = fbuf(sk); + s_v_ = fbuf(sk); + s_att_ = fbuf(b * sq); + s_g_ = fbuf(b * s_ff_); + s_u_ = fbuf(b * s_ff_); + s_cur_ = fbuf(b * E); + s_base_ = fbuf((b - 1) * n_vocab_); + s_bias_ = fbuf((size_t) n_vocab_); + s_in_ = fbuf(2 * r + 2 * E); + s_jo_ = fbuf(3 * r); + s_state_ = fbuf(r); + s_latent_ = fbuf(r); + s_corr_ = fbuf(E); + s_work_ = fbuf(inkling_block_attend_work_floats(s_block_, s_head_, s_dim_)); +} + +// ---- the streams in r_ ----------------------------------------------------------------------------------------- + +void Inkling::gather(int k, float* dst, int n, int first) { + const size_t e = (size_t) n_embd_ * sizeof(float), rs = e * streams(); + ck(cudaMemcpy2DAsync(dst, e, r_ + (size_t) first * streams() * n_embd_ + (size_t) k * n_embd_, rs, e, (size_t) n, + cudaMemcpyDeviceToDevice, cs(st_)), + "streams"); +} + +void Inkling::scatter(int k, const float* src, int n) { + const size_t e = (size_t) n_embd_ * sizeof(float), rs = e * streams(); + ck(cudaMemcpy2DAsync(stream(k), rs, src, e, e, (size_t) n, cudaMemcpyDeviceToDevice, cs(st_)), "streams"); +} + +void Inkling::copy_stream(int from, int to, int n) { + const size_t e = (size_t) n_embd_ * sizeof(float), rs = e * streams(); + ck(cudaMemcpy2DAsync(stream(to), rs, stream(from), rs, e, (size_t) n, cudaMemcpyDeviceToDevice, cs(st_)), + "streams"); +} + +// --dump-layers (Engine::dbg()): a stage of n tokens, by llama.cpp's index of the visit (its cache slot) +void Inkling::dump(const char* name, int v, const float* dev, int width, int n) { + dbg(name, v >= 0 ? slot_of(v) : -1, dev, width * n); +} + +// ---- a layer --------------------------------------------------------------------------------------------------- + +// The rows the attention of n tokens from pos_ is sized for: a full visit's in room()'s steps rather than pos + n, +// so that its splits, and so a token's bits, do not change with every position. A window visit's serves every +// position: sized for the context, it gets the window's splits and the one more a window not starting on a split's +// edge spans (window + n - 1 rows would leave that one out). +int64_t Inkling::attn_room(const Block& B, int n) const { + return B.swa ? (int64_t) opt_.max_context : Engine::room(n); +} + +int Inkling::head_key(int il, int n) const { return blocks_[(size_t) il].swa ? 0 : room_key(n); } + +// A post-convolution of n rows into acc (written when `fresh`, else added), its state at `state` in the bound +// sequence's state_, or with step()'s rows at the same place in each row's own sequence's. +void Inkling::post_conv(const float* x, float* state, const Dev& w, float* acc, int n, bool fresh, const Row* rows) { + if (rows) { + float* states[kInklingSeqRows]; + for (int i = 0; i < n; ++i) states[i] = seq_state(rows[i].seq, state); + if (fresh) inkling_conv_seqs(x, states, fp(w), acc, n_embd_, n, st_); + else inkling_conv_acc_seqs(x, states, fp(w), acc, n_embd_, n, st_); + } else { + conv_snaps(x, state, n_embd_, n); + if (fresh) inkling_conv(x, state, fp(w), nullptr, 0, acc, n_embd_, n, st_); + else inkling_conv_acc(x, state, fp(w), nullptr, 0, acc, n_embd_, n, st_); + } +} + +// A window's snapshots of a convolution's state (Engine::window()), before the call's n rows of x advance it. +void Inkling::conv_snaps(const float* x, const float* state, int channels, int n) { + if (snap_bits_) inkling_conv_snaps(x, state, channels, n, snap_bits_, snap_at_ + (state - state_), rec_n_, st_); +} + +// The attention from its three normed inputs (and their Q8_1 copies) to ao_, through the output's convolution. +void Inkling::attn(Block& B, int v, const float* xq, const float* xk, const float* xv, const void* const* xq8, int n, + bool fuse) { + const int hk = n_kv_ * head_dim_, hq = n_head_ * head_dim_; + // the projections of the three inputs, those of one format in one launch + const LinJob proj[8] = {{&B.wq, xq, q_, xq8[0]}, {&B.wgate, xq, gate_, xq8[0]}, + {&B.wrel, xq, rel_, xq8[0]}, {&B.wsink, xq, sink_, xq8[0]}, + {&B.wk, xk, kraw_, xq8[1]}, {&B.wv, xv, vraw_, xq8[2]}, + {&B.k_conv_proj, xk, ktap_, xq8[1]}, {&B.v_conv_proj, xv, vtap_, xq8[2]}}; + lin_jobs(proj, B.swa ? 6 : 8, n); + const size_t v_at = (size_t) (n_conv_ - 1) * hk; // the V convolution's state, after K's + const InklingTau tau = B.swa ? InklingTau{} : InklingTau{tau_alpha_, tau_floor_}; + InklingClipJob jobs[2]; + jobs[0] = {q_, 0, fp(B.q_clip), q_, head_dim_, n_head_, qk_clip_, tau}; + jobs[1] = {rel_, 0, fp(B.rel_clip), rel_, n_rel_, n_head_, rel_clip_, tau}; + InklingRel rel; + rel.r = rel_; + rel.table = fp(B.rel_bias); + rel.n_rel = n_rel_; + rel.extent = B.extent; + const float scale = 1.f / std::sqrt((float) head_dim_); + const int window = B.swa ? window_ : 0, ring = B.swa ? ring_ : 0; + // K and V from their projections into the cache in one launch, Q's and R's clips in another, then the attention + if (rows_of_) { // step(): each row a token of its own sequence, with its caches, convolution state and position + InklingKvSeq kv[kInklingSeqRows]; + InklingAttnSeq at[kInklingSeqRows]; + int64_t pos[kInklingSeqRows]; + for (int i = 0; i < n; ++i) { + const Row& r = rows_of_[i]; + uint8_t* pl[4] = {}; + for (int j = 0; j < planes(); ++j) pl[j] = (uint8_t*) seq_buf(r.seq, B.plane[j]); + float* const conv = seq_state(r.seq, B.conv); + kv[i].dst = kv_dst(q8(), pl, ring); + kv[i].k_state = conv; + kv[i].v_state = conv + v_at; + kv[i].pos = pos[i] = r.pos; + const int64_t keep = pos_; // its room as alone (room() reads pos_) + pos_ = r.pos; + at[i] = attn_seq(q8(), pl, r.pos, attn_room(B, 1)); + pos_ = keep; + } + inkling_kv_store_seqs(kraw_, vraw_, kv, fp(B.k_conv), fp(B.v_conv), B.swa ? nullptr : ktap_, + B.swa ? nullptr : vtap_, n_kv_, head_dim_, n, qk_clip_, rms_eps_, k_, v_, st_); + inkling_clip_many_seqs(jobs, 2, n, pos, st_); + inkling_attend_seqs(q_, at, n, rel, sink_, att_, head_dim_, n_head_, n_kv_, scale, window, ring, awork_, + awork_n_, st_, int8_dot_); + } else { + const long long* at = recording_ ? at_ : nullptr; // a recorded launch: the position from what at_ holds + conv_snaps(kraw_, B.conv, hk, n); + conv_snaps(vraw_, B.conv + v_at, hk, n); + if (fuse) { + inkling_kv_store_clip(kraw_, vraw_, B.conv, B.conv + v_at, fp(B.k_conv), fp(B.v_conv), + B.swa ? nullptr : ktap_, B.swa ? nullptr : vtap_, n_kv_, head_dim_, n, qk_clip_, + rms_eps_, kv_dst(q8(), B.plane, ring), pos_, k_, v_, jobs, 2, st_, at); + } else { + inkling_kv_store(kraw_, vraw_, B.conv, B.conv + v_at, fp(B.k_conv), fp(B.v_conv), + B.swa ? nullptr : ktap_, B.swa ? nullptr : vtap_, n_kv_, head_dim_, n, qk_clip_, rms_eps_, + kv_dst(q8(), B.plane, ring), pos_, k_, v_, st_, at); + inkling_clip_many(jobs, 2, n, pos_, st_, at); + } + dump("Qcur", v, q_, hq, n); + dump("Kcur", v, k_, hk, n); + dump("Vcur", v, v_, hk, n); + dump("Rcur", v, rel_, n_head_ * n_rel_, n); + const InklingAttnSeq c = attn_seq(q8(), B.plane, pos_, attn_room(B, n)); + inkling_attend(q_, c.kcache, c.vcache, c.kq8, c.vq8, rel, sink_, pos_, n, att_, head_dim_, n_head_, n_kv_, + scale, window, ring, awork_, awork_n_, st_, c.room, int8_dot_, at, fuse ? gate_ : nullptr, + fuse ? attq_ : nullptr); + } + dump("kqv_out", v, att_, hq, n); + if (!fuse) mul_sigmoid(att_, gate_, hq, n, hq, false, st_); + lin(B.wo, att_, o_, n, fuse ? attq_ : nullptr); // the post-convolution: layer_head(), with the residual +} + +// A visit from its input to its router's copy. The streams: see inkling.hpp. +void Inkling::layer_head(Layer& L, int v, int n) { + Block& B = blocks_[(size_t) v]; + const int ip = B.phys; + const size_t e = (size_t) n * n_embd_; + // One token's streams lie one after the other in r_, as a buffer of one row each: the mixes read them there and + // the stream is worked on in place. More tokens' are gathered, a buffer a stream, and the stream goes back in the + // tail. + const bool direct = n == 1; + float* const cres = work_stream(n); + tail_rows_ = rows_of_; // step()'s rows, for the tail's convolution + // A token alone has its launches fused (fused()): the visit before's tail convolution goes in with the first + // mix here, the attention's with the FFN's mix. + const bool fuse = fused(n); + // the visit before's, still to do (none before the card's first: a call cut short leaves its own behind) + const InklingConvIn* last = tail_wait_ && v != lo_ ? &tail_conv_ : nullptr; + tail_wait_ = false; + const auto flush = [&] { + if (last) inkling_conv_in(*last, n_embd_, st_); + last = nullptr; + }; + if (v == 0) { // the embedding, normed, is the first block's start + gather(kCur, o_, n); + rms_norm(o_, fp(tok_norm_), res_, n_embd_, n, rms_eps_, st_); + // a picture's rows go in as the encoder made them: llama.cpp norms token embeddings only (inkling2.cpp, + // `if (ubatch.token)`). A call can hold text and picture rows, so the raw rows are put back row by row. + // step()'s rows have none (Engine::step()). + if (!rows_of_) + for (const Image& im : images_) { + const int64_t a = std::max(im.at, pos_), b = std::min(im.at + im.n, pos_ + n); + if (a < b) + ck(cudaMemcpyAsync(res_ + (size_t) (a - pos_) * n_embd_, o_ + (size_t) (a - pos_) * n_embd_, + (size_t) (b - a) * n_embd_ * sizeof(float), cudaMemcpyDeviceToDevice, cs(st_)), + "picture rows"); + } + if (direct) ck(cudaMemcpyAsync(cres, res_, e * sizeof(float), cudaMemcpyDeviceToDevice, cs(st_)), "streams"); + else scatter(kCur, res_, n); + } else { + // a later pass of the core starts from layer 5's output, with what the pass before left for its messages: + // the start of the block in the core's middle (its layer 11's output) and the stream (its layer 17's) + if (B.pass > 0 && ip == core_start_) { + flush(); + const int core_in = kBlock0 + core_start_ / kBlockSize; + copy_stream(core_in + 1, kBank, n); + copy_stream(kCur, kBankOut, n); + copy_stream(core_in, kCur, n); + } + if (!direct) gather(kCur, res_, n); + } + dump("l_in", v, cres, n_embd_, n); + if (spark_) // the drafter reads the stream entering this visit (drafter_rows()), the visit before's tail in it + for (int k = 0; k < kTaps; ++k) { + if (taps_[k] != v) continue; + flush(); + if (direct) ck(cudaMemcpyAsync(stream(kTap0 + k), cres, e * sizeof(float), cudaMemcpyDeviceToDevice, + cs(st_)), + "streams"); + else scatter(kTap0 + k, res_, n); + } + const int nb = blocks_before(ip); + const float* bp[4]; // the blocks' starts + for (int k = 0; k < nb; ++k) { + if (direct) { + bp[k] = stream(kBlock0 + k); + } else { + gather(kBlock0 + k, blk_[k], n); + bp[k] = blk_[k]; + } + } + + // the attention's inputs: the stream, or its mix with the blocks (one for a window layer, Q, K and V apart + // for a full one) + const float* in[3] = {cres, cres, cres}; + // the mixes: the attention's inputs, and a later pass's messages (the pass before's mix, gated into each input) + InklingMix mixes[2]; + int n_mix = 0; + if (B.attn_query.p) { + InklingMix& m = mixes[n_mix++]; + for (int k = 0; k < nb; ++k) m.state[k] = bp[k]; + m.state[nb] = cres; + m.n_state = nb + 1; + m.query = fp(B.attn_query); + m.n_query = B.swa ? 1 : 3; + for (int j = 0; j < m.n_query; ++j) m.out[j] = mix_[j]; + for (int j = 0; j < 3; ++j) in[j] = mix_[B.swa ? 0 : j]; + } + if (B.pass > 0) { + if (!direct) { + gather(kBank, bank_, n); + gather(kBankOut, bank_out_, n); + } + InklingMix& m = mixes[n_mix++]; + m.state[0] = direct ? stream(kBank) : bank_; + m.state[1] = direct ? stream(kBankOut) : bank_out_; + m.n_state = 2; + m.query = fp(B.msg_query); + m.n_query = 4; + for (int j = 0; j < 4; ++j) m.out[j] = msg_[j]; + } + const int threads = sum_threads(n_embd_); + // the first pass's visits norm the mix's outputs in its launch (later passes' controllers come in between) + const bool normed = fuse && n_mix > 0 && B.attn_query.p && B.pass == 0; + if (fuse && n_mix > 0 && B.attn_query.p) { + InklingMixNorm nm; + for (int j = 0; j < mixes[0].n_query; ++j) { + nm.w[j] = fp(B.swa ? L.attn_norm : j == 0 ? B.q_norm : j == 1 ? B.k_norm : B.v_norm); + nm.y[j] = in_[j], nm.y_q8_1[j] = inq_[j]; + } + nm.eps = rms_eps_, nm.threads = threads; + inkling_mix_conv(mixes, n_mix, last, n_embd_, norm_eps_, st_, normed ? &nm : nullptr, mix_work_); + last = nullptr; + } else { + flush(); + for (int k = 0; k < n_mix; ++k) inkling_mix(mixes[k], n_embd_, n, norm_eps_, st_); + } + if (B.pass > 0) { + if (n <= kFusedRows) { // the three controllers in two launches; each out its own buffer + InklingCtrl c[3]; + for (int j = 0; j < 3; ++j) + c[j] = {in[j], msg_[j], fp(B.ctrl_down[j]), fp(B.ctrl_gain[j]), fp(B.ctrl_forget[j]), ctl_[j]}; + inkling_control_fused(c, 3, n_embd_, rank_, n, norm_eps_, ctl_work_, st_); + for (int j = 0; j < 3; ++j) in[j] = ctl_[j]; + } else { + for (int j = 0; j < 3; ++j) { + inkling_control(blas_, in[j], msg_[j], fp(B.ctrl_down[j]), fp(B.ctrl_gain[j]), fp(B.ctrl_forget[j]), + ctl_work_, ctl_[j], n_embd_, rank_, n, norm_eps_, st_); + in[j] = ctl_[j]; + } + } + } + const void* q8[3]; + const auto norm = [&](int j, const float* x, const Dev& w) { + if (!normed) + kernels::native_add_rms_norm_q8_1(const_cast(x), nullptr, fp(w), in_[j], inq_[j], n_embd_, n, + rms_eps_, threads, st_); + q8[j] = inq_[j]; + }; + const float* x[3]; + if (B.swa && B.pass == 0) { + norm(0, in[0], L.attn_norm); + x[0] = x[1] = x[2] = in_[0]; + q8[1] = q8[2] = q8[0]; + } else { + const Dev* w[3] = {&L.attn_norm, &L.attn_norm, &L.attn_norm}; + if (!B.swa) w[0] = &B.q_norm, w[1] = &B.k_norm, w[2] = &B.v_norm; + kernels::NormRows rows{}; + for (int j = 0; j < 3; ++j) { + rows.x[j] = in[j], rows.w[j] = fp(*w[j]), rows.y[j] = in_[j], rows.y_q8_1[j] = inq_[j]; + x[j] = in_[j]; + q8[j] = inq_[j]; + } + if (!normed && (!fuse || !kernels::native_rms_norm_q8_1_rows(rows, 3, n_embd_, rms_eps_, threads, st_))) + for (int j = 0; j < 3; ++j) norm(j, in[j], *w[j]); + } + attn(B, v, x[0], x[1], x[2], q8, n, fuse); + + // the first layer of a block starts the stream afresh, and what it started from is the block's + float* const post = B.conv + (size_t) 2 * (n_conv_ - 1) * n_kv_ * head_dim_; // the attention-out's state + InklingConvIn conv; // a token alone's, done by the FFN's mix + if (fuse) { + conv_snaps(o_, post, n_embd_, n); + conv.x = o_; + conv.state = post; + conv.w = fp(B.post_conv); + conv.acc = cres; + conv.fresh = ip % kBlockSize == 0; + if (conv.fresh) { + const int k = ip / kBlockSize; + conv.save = stream(kBlock0 + k); + bp[k] = conv.save; + } + } else if (ip % kBlockSize == 0) { + const int k = ip / kBlockSize; + if (direct) { + ck(cudaMemcpyAsync(stream(kBlock0 + k), cres, e * sizeof(float), cudaMemcpyDeviceToDevice, cs(st_)), + "streams"); + bp[k] = stream(kBlock0 + k); + } else { + scatter(kBlock0 + k, res_, n); + ck(cudaMemcpyAsync(blk_[k], res_, e * sizeof(float), cudaMemcpyDeviceToDevice, cs(st_)), "streams"); + bp[k] = blk_[k]; + } + post_conv(o_, post, B.post_conv, cres, n, true, rows_of_); + } else { + post_conv(o_, post, B.post_conv, cres, n, false, rows_of_); + } + dump("ffn_inp", v, cres, n_embd_, n); + + // the FFN's input: the stream mixed with the blocks, gated with its message in a later pass + const int nf = blocks_at(ip); + InklingMix m; + for (int k = 0; k < nf; ++k) m.state[k] = bp[k]; + m.state[nf] = cres; + m.n_state = nf + 1; + m.query = fp(B.ffn_query); + m.n_query = 1; + m.out[0] = mix_[0]; + InklingMixNorm nm; // the first pass's FFN input, normed in the mix's launch + nm.w[0] = fp(L.ffn_norm), nm.y[0] = xn_, nm.y_q8_1[0] = xq_, nm.eps = rms_eps_, nm.threads = threads; + if (fuse) inkling_mix_conv(&m, 1, &conv, n_embd_, norm_eps_, st_, B.pass == 0 ? &nm : nullptr, mix_work_); + else inkling_mix(m, n_embd_, n, norm_eps_, st_); + float* f = mix_[0]; + if (B.pass > 0) { + if (n <= kFusedRows) { + const InklingCtrl c{f, msg_[3], fp(B.ctrl_down[3]), fp(B.ctrl_gain[3]), fp(B.ctrl_forget[3]), ctl_[0]}; + inkling_control_fused(&c, 1, n_embd_, rank_, n, norm_eps_, ctl_work_, st_); + } else { + inkling_control(blas_, f, msg_[3], fp(B.ctrl_down[3]), fp(B.ctrl_gain[3]), fp(B.ctrl_forget[3]), + ctl_work_, ctl_[0], n_embd_, rank_, n, norm_eps_, st_); + } + f = ctl_[0]; + } + if (!fuse || B.pass > 0) + kernels::native_add_rms_norm_q8_1(f, nullptr, fp(L.ffn_norm), xn_, xq_, n_embd_, n, rms_eps_, threads, st_); + dump("ffn_in", v, xn_, n_embd_, n); + if (!batched(layers_[(size_t) home_of(v)], n)) moe_router(L, n); // the experts' layer decides (Layer::alias) +} + +// The routed experts' sum through its convolution, into the stream. +void Inkling::layer_tail(Layer&, int v, int n) { + Block& B = blocks_[(size_t) v]; + const size_t hk = (size_t) n_kv_ * head_dim_; + const bool parts = card_parts_; // moe_card() left the experts' sum to this + card_parts_ = false; + dump("ffn_moe_out", v, fo_, n_embd_, n); + float* const state = B.conv + (size_t) (n_conv_ - 1) * (2 * hk + n_embd_); + // the stream at this half's rows: a window's halves (shift_rows()) run the other half's head in between + float* const cres = work_stream(n); + if (fused(n) && !tail_rows_) { // a token alone: the next visit's first mix does the convolution + InklingConvIn& c = tail_conv_; + c = InklingConvIn{}; + if (parts) { + c.parts = d_, c.weights = d_wts_, c.n_parts = n_used_; + } else { + conv_snaps(fo_, state, n_embd_, n); + c.x = fo_; + } + c.state = state; + c.w = fp(B.ffn_post_conv); + c.acc = cres; + if (layers_in_order_ && v + 1 < hi_) tail_wait_ = true; + else inkling_conv_in(c, n_embd_, st_); + return; + } + if (parts) moe_sum(d_, d_wts_, fo_, n_embd_, n_used_, n, st_); // step()'s row of one sequence + post_conv(fo_, state, B.ffn_post_conv, cres, n, false, tail_rows_); + tail_rows_ = nullptr; + if (cres == res_) scatter(kCur, res_, n); // several tokens' stream back to r_ (one token's is worked on there) + dump("l_out", v, cres, n_embd_, n); +} + +// A half of a window at its rows: the engine's buffers and the stream a layer's head leaves for its tail. +void Inkling::shift_rows(ptrdiff_t by) { + Engine::shift_rows(by); + res_ += by * n_embd_; +} + +// The output's input: the stream mixed with the four blocks, normed. +void Inkling::output_rows(int first, int rows, float* h) { + const int nb = blocks_at(n_phys_ - 1); + InklingMix m; + for (int k = 0; k < nb; ++k) { + gather(kBlock0 + k, blk_[k], rows, first); + m.state[k] = blk_[k]; + } + gather(kCur, mix_[1], rows, first); + m.state[nb] = mix_[1]; + m.n_state = nb + 1; + m.query = fp(out_query_); + m.n_query = 1; + m.out[0] = mix_[0]; + inkling_mix(m, n_embd_, rows, norm_eps_, st_); + rms_norm(mix_[0], fp(out_norm_), h, n_embd_, rows, rms_eps_, st_); + dump("result_norm", -1, h, n_embd_, rows); +} + +// The final softcap, and the padded vocabulary's rows out of reach. +void Inkling::finish_logits(float* logits, int rows) { + if (softcap_ > 0.f) softcap(logits, (size_t) rows * n_vocab_, softcap_, st_); + if (!neg_inf_) return; + const size_t pad_n = (size_t) (n_vocab_ - n_vocab_real_); + for (int r = 0; r < rows; ++r) + ck(cudaMemcpyAsync(logits + (size_t) r * n_vocab_ + n_vocab_real_, neg_inf_, pad_n * sizeof(float), + cudaMemcpyDeviceToDevice, cs(st_)), + "logits"); +} + +// What ggml's MoE graph does for this model: sigmoid gates, the n_used largest of gate + bias, weights from the +// bare gates divided by their sum (+ 1e-20, expert_weights_norm_eps) and times expert_weights_scale. +void Inkling::route(int il, const float* logits, int32_t, int* ids, float* w, float* probs) const { + const std::vector& bias = blocks_[(size_t) il].probs_b; + float* pick = probs + n_expert_; + for (int e = 0; e < n_expert_; ++e) { + probs[e] = 1.f / (1.f + std::exp(-logits[e])); + pick[e] = probs[e] + bias[(size_t) e]; + } + float sum = 0.f; + for (int k = 0; k < n_used_; ++k) { + int best = 0; + for (int e = 1; e < n_expert_; ++e) + if (pick[e] > pick[best]) best = e; + pick[best] = -INFINITY; + ids[k] = best; + w[k] = probs[best]; + sum += w[k]; + } + sum += 1e-20f; + for (int k = 0; k < n_used_; ++k) { + w[k] /= sum; + if (w_scale_ != 0.f) w[k] *= w_scale_; + } +} + +// The router's F32 product: a decode step's few tokens with inkling_gemv(), a prompt batch as the engine does it. +void Inkling::router_scores(const Layer& L, int n) { + if (n <= kFusedRows) inkling_gemv(fp(L.gate_inp), xn_, rl_, n_embd_, n_expert_, n, st_); + else Engine::router_scores(L, n); +} + +bool Inkling::route_card(int il, int n, int32_t* ids, float* w) { + const Block& B = blocks_[(size_t) il]; + route_rows(rl_, n_expert_, n_used_, n, 1, 1.f, B.probs_b_dev.p ? fp(B.probs_b_dev) : nullptr, nullptr, true, + w_scale_, ids, w, st_); + return true; +} + +// SiTU straight into the down products' Q8_1 input (situ_rows_q8_1()): the same bits as situ_rows() then the +// quantization. +bool Inkling::act_rows_q8_1(const float* gate_up, void* q8, int rows, const ExpertScales* es) { + situ_rows_q8_1(gate_up, q8, n_ff_exp_, rows, situ_->beta, situ_->lin_beta, st_, es); + return true; +} + +// No shared expert: the routed experts' sum starts from zero. +void Inkling::moe_shared(const Layer&, int, int n) { + ck(cudaMemsetAsync(fo_, 0, (size_t) n * n_embd_ * sizeof(float), cs(st_)), "experts"); +} + +// ---- a sequence's state and rows ------------------------------------------------------------------------------- + +// The last keep_ positions before `pos` as runs of a ring's rows: f(the run's place among the keep_, its first +// ring row, its rows). +template +void Inkling::window_runs(int64_t pos, F&& f) const { + for (int64_t p = std::max(0, pos - keep_); p < pos;) { + const int64_t at = p % ring_, m = std::min(pos - p, ring_ - at); + f((size_t) (p - (pos - keep_)), (size_t) at, (size_t) m); + p += m; + } +} + +size_t Inkling::plane_row(int i) const { + const size_t width = (size_t) n_kv_ * head_dim_; + if (!q8()) return width * sizeof(uint16_t); + return i % 2 == 0 ? width : width / 32 * sizeof(uint16_t); +} + +// A sequence's rows are the full visits'; a window visit's are part of its state (save_layer()). A visit's part of +// a row is its planes one after the other (fp16 keys, values; or q8_0 key codes, key scales, value codes, value +// scales, as Flint's), each plane's rows together. +size_t Inkling::card_row_bytes() const { + size_t one = 0; + for (int i = 0; i < planes(); ++i) one += plane_row(i); + size_t layers = 0; + for (const Block& B : blocks_) + if (B.plane[0] && !B.swa) ++layers; + size_t spark = 0; // the drafter's: its full layers' keys and values + for (const SparkLayer& D : spark_layers_) + if (!D.swa) spark += 2 * spark_row(); + return layers * one + spark; +} + +void Inkling::save_card_rows(int64_t first, int64_t n, uint8_t* dst) { + if (first < 0 || n < 0 || first + n > opt_.max_context) + throw std::logic_error("save_rows: the rows are outside the context"); + ck(cudaStreamSynchronize(cs(st_)), "save rows"); + for (const Block& B : blocks_) { + if (B.swa || n == 0 || !B.plane[0]) continue; + for (int i = 0; i < planes(); ++i) { + const size_t row = plane_row(i); + ck(cudaMemcpy(dst, B.plane[i] + (size_t) first * row, (size_t) n * row, cudaMemcpyDeviceToHost), + "save rows"); + dst += (size_t) n * row; + } + } + // on st_: the drafter writes its rows of a call behind the call's logits (Engine::eval()) + for (const SparkLayer& D : spark_layers_) { + if (D.swa || n == 0) continue; + for (const uint16_t* plane : {D.k, D.v}) { + ck(cudaMemcpyAsync(dst, (const uint8_t*) plane + (size_t) first * spark_row(), (size_t) n * spark_row(), + cudaMemcpyDeviceToHost, cs(st_)), + "save rows"); + dst += (size_t) n * spark_row(); + } + } + if (spark_) ck(cudaStreamSynchronize(cs(st_)), "save rows"); +} + +void Inkling::load_card_rows(const uint8_t* src, int64_t from, int64_t count, int64_t first, int64_t n) { + if (from < 0 || first < from || n < 0 || first + n > from + count || first + n > opt_.max_context) + throw std::logic_error("load_rows: the rows are outside what was saved"); + cover(first + n); + ck(cudaStreamSynchronize(cs(st_)), "load rows"); + for (const Block& B : blocks_) { + if (B.swa || n == 0 || !B.plane[0]) continue; + for (int i = 0; i < planes(); ++i) { + const size_t row = plane_row(i); + h2d(B.plane[i] + (size_t) first * row, src + (size_t) (first - from) * row, (size_t) n * row); + src += (size_t) count * row; + } + } + for (const SparkLayer& D : spark_layers_) { + if (D.swa || n == 0) continue; + for (uint16_t* plane : {D.k, D.v}) { + h2d((uint8_t*) plane + (size_t) first * spark_row(), src + (size_t) (first - from) * spark_row(), + (size_t) n * spark_row()); + src += (size_t) count * spark_row(); + } + } +} + +// What a window visit has of the sequence: the rows the next token attends, its planes one after the other. +size_t Inkling::extra_bytes() const { + size_t one = 0; + for (int i = 0; i < planes(); ++i) one += plane_row(i); + size_t layers = 0; + for (const Block& B : blocks_) + if (B.swa) ++layers; + return layers * (size_t) keep_ * one + spark_extra(); +} + +// A visit's convolution state at its place in state_, and a window visit's rows behind the window visits before it. +void Inkling::save_layer(int v, int64_t pos, uint8_t* dst) { + const Block& B = blocks_[(size_t) v]; + if (B.conv) + ck(cudaMemcpy(dst + (size_t) (B.conv - state_) * sizeof(float), B.conv, conv_floats_ * sizeof(float), + cudaMemcpyDeviceToHost), + "save state"); + if (!B.swa) return; + size_t whole = 0; + for (int i = 0; i < planes(); ++i) whole += (size_t) keep_ * plane_row(i); + dst += state_n_ * sizeof(float); + for (int j = 0; j < v; ++j) + if (blocks_[(size_t) j].swa) dst += whole; + for (int i = 0; i < planes(); ++i) { + const size_t one_row = plane_row(i); + std::memset(dst, 0, (size_t) keep_ * one_row); // the places of positions before the sequence's start + window_runs(pos, [&](size_t slot, size_t at, size_t m) { + ck(cudaMemcpy(dst + slot * one_row, B.plane[i] + at * one_row, m * one_row, cudaMemcpyDeviceToHost), + "save state"); + }); + dst += (size_t) keep_ * one_row; + } +} + +void Inkling::load_extra(const uint8_t* src, int64_t pos) { + for (const Block& B : blocks_) { + if (!B.swa) continue; + for (int i = 0; i < planes(); ++i) { + const size_t one_row = plane_row(i); + window_runs(pos, [&](size_t slot, size_t at, size_t m) { + h2d(B.plane[i] + at * one_row, src + slot * one_row, m * one_row); + }); + src += (size_t) keep_ * one_row; + } + } + // the drafter's, behind the model's (save_last()) + for (const SparkLayer& D : spark_layers_) { + if (!D.swa) continue; + for (uint16_t* plane : {D.k, D.v}) { + spark_window(pos, [&](size_t slot, size_t at, size_t m) { + h2d((uint8_t*) plane + at * spark_row(), src + slot * spark_row(), m * spark_row()); + }); + src += (size_t) s_window_ * spark_row(); + } + } + if (spark_) h2d(s_rnn_, src, (size_t) (s_block_ + 1) * n_embd_ * sizeof(float)); +} + +// The drafter's part of the state: its window layers' rows of the window before pos, and the head's last contexts. +size_t Inkling::spark_extra() const { + if (!spark_) return 0; + size_t rings = 0; + for (const SparkLayer& D : spark_layers_) + if (D.swa) rings += 2 * (size_t) s_window_ * spark_row(); + return rings + (size_t) (s_block_ + 1) * n_embd_ * sizeof(float); +} + +// The window before pos in a drafter's ring: f(place in the saved rows, row of the ring, rows) for each run. +template +void Inkling::spark_window(int64_t pos, F&& f) const { + for (int64_t p = std::max(0, pos - s_window_); p < pos;) { + const int64_t at = p % s_ring_, m = std::min(pos - p, s_ring_ - at); + f((size_t) (p - (pos - s_window_)), (size_t) at, (size_t) m); + p += m; + } +} + +void Inkling::save_last(uint8_t* dst, int64_t pos) { + Engine::save_last(dst, pos); + if (!spark_) return; + dst += card_state_bytes() - spark_extra(); + for (const SparkLayer& D : spark_layers_) { + if (!D.swa) continue; + for (const uint16_t* plane : {D.k, D.v}) { + std::memset(dst, 0, (size_t) s_window_ * spark_row()); // the places before the sequence's start + spark_window(pos, [&](size_t slot, size_t at, size_t m) { + ck(cudaMemcpyAsync(dst + slot * spark_row(), (const uint8_t*) plane + at * spark_row(), + m * spark_row(), cudaMemcpyDeviceToHost, cs(st_)), + "save state"); + }); + dst += (size_t) s_window_ * spark_row(); + } + } + ck(cudaMemcpyAsync(dst, s_rnn_, (size_t) (s_block_ + 1) * n_embd_ * sizeof(float), cudaMemcpyDeviceToHost, + cs(st_)), + "save state"); + ck(cudaStreamSynchronize(cs(st_)), "save state"); +} + + +// ---- the DSpark drafter ---------------------------------------------------------------------------------------- +// +// Inkling 2 Mini's own block drafter (unsloth/Inkling-2-Mini-GGUF's dspark-Inkling-2-Mini-*.gguf, architecture +// "dflash"), as llama.cpp runs it in PR 32218 (88025eb): src/models/dspark.cpp graph_inkling2 and +// common/speculative.cpp's draft-dspark. +// +// Every row the model computes - a prompt's, a token's, a window's with its wrong guesses - goes in at its position: +// the streams entering visits 5, 23 and 41 and the normed output are mixed, a mix for each of the drafter's three +// layers and one for its head (inkling_dspark_fuse()), and each layer keeps its mix's keys and values in its cache +// at the row's position. A wrong guess's row is written again when its position gets its real token, or by the +// block, before anything reads it: the block reads its own positions and the ones before them. +// +// To guess, a block of eight rows at pos() .. pos() + 7 goes through the three layers: the token at pos() (picked +// and not fed yet) as the model norms its embeddings, then seven copies of mask_embd. Every row sees every row of +// the block and the cached rows before it, a window layer's from pos() - 1024 on (the first row's window, for all). +// The rows' outputs take the model's output matrix. The guesses are rows 1, 2, ... in turn (row 0's is none): a +// small recurrent state takes the guess before (its markov_w1 row), the row's output and the head's mix of the row +// before pos(), and its correction goes through the output matrix again and onto the row's scores, which are capped +// as the model's. Each guess costs a product with the output matrix, and the block one more. + +void Inkling::load_spark_shape() { + const Shards& g = *dg_; + auto need = [&](bool ok, const std::string& what) { + if (!ok) throw std::runtime_error(opt_.draft_model + " is not a DSpark drafter of this model: " + what); + }; + const MetaValue* arch = g.get("general.architecture"); + need(arch && arch->s == "dflash" && g.find("dspark_hidden_out.weight"), + "not a dflash file with dspark_hidden_out.weight"); + auto get = [&](const char* key) -> const MetaValue& { + const MetaValue* v = meta_in(g, key); + need(v != nullptr, std::string("no dflash.") + key); + return *v; + }; + const int n = (int) get("block_count").u; + need(n > 0 && n <= 8 && (int) get("embedding_length").u == n_embd_, "its layers or width"); + s_head_ = (int) get("attention.head_count").u; + s_kv_ = (int) get("attention.head_count_kv").u; + s_dim_ = (int) get("attention.key_length").u; + s_ff_ = (int) get("feed_forward_length").u; + need(s_dim_ == 128 && (int) get("attention.value_length").u == s_dim_ && + (int) get("rope.dimension_count").u == s_dim_ && s_kv_ > 0 && s_head_ % s_kv_ == 0 && s_ff_ > 0, + "attention other than heads of 128 values, rotated whole"); + s_block_ = (int) get("block_size").u; + // a block's queries of a key head go to inkling_block_attend() together + need(s_block_ >= 2 && s_block_ * (s_head_ / s_kv_) <= 32, + "a block of " + std::to_string(s_block_) + " rows"); + // a block guesses s_block_ - 1 tokens: a window holds the token and at most those + if (opt_.window > s_block_) + throw std::runtime_error("Inkling 2: --window " + std::to_string(opt_.window) + " is more than the DSpark " + "drafter's block of " + std::to_string(s_block_) + " (the token and its guesses)"); + need(get("attention.causal").u == 0 && get("sample_from_anchor").u == 0, + "a causal block, or one whose first row is a guess"); + need((int) get("vocab_size").u == n_vocab_ && (int) get("vocab_size_unpadded").u == n_vocab_real_, + "another vocabulary"); + s_eps_ = (float) get("attention.layer_norm_rms_epsilon").f; + s_cap_ = (float) get("final_logit_softcapping").f; + s_window_ = (int) get("attention.sliding_window").u; + s_theta_ = std::pow((float) get("rope.freq_base").f, -2.f / (float) s_dim_); + need(s_eps_ > 0.f && s_cap_ > 0.f && s_window_ > 0, "its norms' epsilon, softcap or window"); + const MetaValue& targets = get("target_layers"); + need(targets.items.size() == kTaps + 1 && (int) targets.items[kTaps].u == n_layer_, + "it reads other layers than three visits and the output"); + for (int k = 0; k < kTaps; ++k) { + taps_[k] = (int) targets.items[(size_t) k].u; + need(taps_[k] > 0 && taps_[k] < n_layer_ && (k == 0 || taps_[k] > taps_[k - 1]), "its target layers"); + } + const MetaValue& pattern = get("attention.sliding_window_pattern"); + spark_layers_.assign((size_t) n, SparkLayer{}); + for (int il = 0; il < n; ++il) spark_layers_[(size_t) il].swa = of_layer(pattern, il) != 0; + const TensorInfo* w1 = g.find("markov_w1.weight"); + need(w1 && w1->type == kTypeBF16 && w1->shape.size() == 2 && (int64_t) w1->shape[1] == n_vocab_, + "markov_w1.weight is not BF16 [rank, vocabulary]"); + s_rank_ = (int) w1->shape[0]; + need(s_rank_ > 0 && s_rank_ <= n_embd_, "its recurrent rank"); + markov_ = (const uint16_t*) g.data(*w1); + // softmax(dspark_fuse): a row of the four inputs' weights for each layer's mix and one for the head's + const TensorInfo* fuse = g.find("dspark_fuse.weight"); + need(fuse && fuse->type == kTypeF32 && fuse->elements() == (uint64_t) (kTaps + 1) * (n + 1) && n + 1 == 4, + "dspark_fuse.weight is not F32 [4, 4]"); + const float* f = (const float*) g.data(*fuse); + for (int j = 0; j < 4; ++j) { + const float* row = f + (size_t) j * (kTaps + 1); + const float mx = *std::max_element(row, row + kTaps + 1); + double sum = 0.0; + for (int k = 0; k <= kTaps; ++k) sum += fuse_[j][k] = std::exp(row[k] - mx); + for (int k = 0; k <= kTaps; ++k) fuse_[j][k] = (float) (fuse_[j][k] / sum); + } + s_ring_ = s_window_ + s_block_; + std::fprintf(stderr, "strata-poly: DSpark drafter: %d layers, a block of %d, reads visits %d, %d, %d\n", n, + s_block_, taps_[0], taps_[1], taps_[2]); +} + +// Twice, like the model's weights: the first time adds up the arena. +void Inkling::load_drafter() { + const Shards& g = *dg_; + auto up = [&](const std::string& name, int64_t a, int64_t b, Want w) { return upload(g.find(name), name, a, b, w); }; + const int64_t E = n_embd_, hq = (int64_t) s_head_ * s_dim_, hk = (int64_t) s_kv_ * s_dim_, r = s_rank_; + s_out_norm_ = up("output_norm.weight", E, 1, kF32); + s_mask_ = up("mask_embd.weight", E, 1, kF32); + s_ctx_norm_ = up("dspark_norm.weight", E, 1, kF32); + // the head's two products take one token: as floats, so that no BF16 matrix asks for lin()'s scratch + s_joint_ = up("joint_proj.weight", 2 * r + 2 * E, 3 * r, kF32); + s_joint_b_ = up("joint_proj.bias", 3 * r, 1, kF32); + s_hout_ = up("dspark_hidden_out.weight", r, E, kF32); + s_hout_b_ = up("dspark_hidden_out.bias", E, 1, kF32); + for (int il = 0; il < (int) spark_layers_.size(); ++il) { + SparkLayer& D = spark_layers_[(size_t) il]; + auto f32 = [&](const char* n, int64_t a) { return up(blk(il, n), a, 1, kF32); }; + auto mat = [&](const char* n, int64_t a, int64_t b) { return up(blk(il, n), a, b, kAnyMat); }; + D.attn_norm = f32("attn_norm.weight", E); + D.ffn_norm = f32("ffn_norm.weight", E); + D.ctx_norm = f32("dflare_norm.weight", E); + D.q_norm = f32("attn_q_norm.weight", s_dim_); + D.k_norm = f32("attn_k_norm.weight", s_dim_); + D.k_ctx_norm = f32("attn_k_ctx_norm.weight", s_dim_); + D.wq = mat("attn_q.weight", E, hq); + D.wk = mat("attn_k.weight", E, hk); + D.wv = mat("attn_v.weight", E, hk); + D.wo = mat("attn_output.weight", hq, E); + D.k_ctx = mat("attn_k_ctx.weight", E, hk); + D.v_ctx = mat("attn_v_ctx.weight", E, hk); + D.gate = mat("ffn_gate.weight", E, s_ff_); + D.up = mat("ffn_up.weight", E, s_ff_); + D.down = mat("ffn_down.weight", s_ff_, E); + } +} + +// n rows of keys and values from position pos into a layer's cache, around its ring in a window layer. +void Inkling::spark_store(const SparkLayer& D, const float* k, const float* v, int64_t pos, int n) { + const int hk = s_kv_ * s_dim_; + for (int at = 0; at < n;) { + const int64_t row = D.swa ? (pos + at) % s_ring_ : pos + at; + const int m = D.swa ? (int) std::min(n - at, s_ring_ - row) : n - at; + store_f16(k + (size_t) at * hk, D.k, hk, row, m, st_); + store_f16(v + (size_t) at * hk, D.v, hk, row, m, st_); + at += m; + } +} + +// The model's n rows from position pos into the drafter: input k's row r at x[k] + r * stride[k]. +void Inkling::spark_rows(int64_t pos, int n, const float* const* x, const int64_t* stride) { + const int E = n_embd_; + const int64_t last = pos + n - 1, ring = s_block_ + 1; + const int chunk = std::min(rows_, kSparkRows); // the rows s_ctx_ holds (alloc()) + for (int c0 = 0; c0 < n; c0 += chunk) { + const int m = std::min(chunk, n - c0); + InklingFuse f; + for (int k = 0; k < 4; ++k) { + f.x[k] = x[k] + (size_t) c0 * stride[k]; + f.stride[k] = stride[k]; + for (int j = 0; j < 4; ++j) f.w[j][k] = fuse_[j][k]; + } + for (int j = 0; j < 4; ++j) { + f.norm[j] = fp(j < 3 ? spark_layers_[(size_t) j].ctx_norm : s_ctx_norm_); + f.out[j] = s_ctx_[j]; + } + inkling_dspark_fuse(f, E, m, s_eps_, st_); + for (int il = 0; il < (int) spark_layers_.size(); ++il) { + const SparkLayer& D = spark_layers_[(size_t) il]; + lin(D.k_ctx, s_ctx_[il], s_k_, m); + lin(D.v_ctx, s_ctx_[il], s_v_, m); + head_norm_rope(s_k_, s_dim_, fp(D.k_ctx_norm), s_kr_, s_dim_, s_kv_, s_dim_, s_theta_, pos + c0, m, s_eps_, + st_); + spark_store(D, s_kr_, s_v_, pos + c0, m); + } + // the head reads the mix of the row before a block's first: the last positions' are kept + for (int t = std::max(0, (int) (last - s_block_ - pos) - c0); t < m; ++t) + ck(cudaMemcpyAsync(s_rnn_ + (size_t) ((pos + c0 + t) % ring) * E, s_ctx_[3] + (size_t) t * E, + (size_t) E * sizeof(float), cudaMemcpyDeviceToDevice, cs(st_)), + "drafter"); + } +} + +void Inkling::drafter_rows(int64_t pos, int n, const float* h) { + const int64_t rs = (int64_t) streams() * n_embd_; + const float* x[4] = {r_ + (size_t) kTap0 * n_embd_, r_ + (size_t) (kTap0 + 1) * n_embd_, + r_ + (size_t) (kTap0 + 2) * n_embd_, h}; + const int64_t stride[4] = {rs, rs, rs, n_embd_}; + spark_rows(pos, n, x, stride); +} + +int Inkling::draft_block(int32_t token, int most, Likeliest* out) { return spark_block(token, pos_, most, out); } + +// Up to `most` guesses after `token` at pos0 (see above), into out. +int Inkling::spark_block(int32_t token, int64_t pos0, int most, Likeliest* out) { + const int B = s_block_, E = n_embd_, r = s_rank_; + most = std::min(most, B - 1); + if (most <= 0 || pos0 < 1 || pos0 + B > opt_.max_context) return 0; + cover(pos0 + B); + if (!h_w1_) { + h_w1_ = (float*) hmalloc((size_t) (r + E) * sizeof(float), "pinned memory"); + h_pick_ = (Likeliest*) hmalloc(sizeof(Likeliest), "pinned memory"); + } + ck(cudaStreamSynchronize(cs(st_)), "drafter"); // h_w1_ is free + // the block's rows: the token as the model norms its embeddings, then the masks. The embedding goes behind the + // markov_w1 row, which the head's first guess writes while the card may not have copied the embedding yet. + float* const h_embd = h_w1_ + r; + embed(token, h_embd); + h2d(s_xn_, h_embd, (size_t) E * sizeof(float)); + rms_norm(s_xn_, fp(tok_norm_), s_x_, E, 1, rms_eps_, st_); + for (int i = 1; i < B; ++i) + ck(cudaMemcpyAsync(s_x_ + (size_t) i * E, fp(s_mask_), (size_t) E * sizeof(float), cudaMemcpyDeviceToDevice, + cs(st_)), + "drafter"); + const float scale = 1.f / std::sqrt((float) s_dim_); + for (const SparkLayer& D : spark_layers_) { + rms_norm(s_x_, fp(D.attn_norm), s_xn_, E, B, s_eps_, st_); + lin(D.wq, s_xn_, s_q_, B); + lin(D.wk, s_xn_, s_k_, B); + lin(D.wv, s_xn_, s_v_, B); + head_norm_rope(s_q_, s_dim_, fp(D.q_norm), s_qr_, s_dim_, s_head_, s_dim_, s_theta_, pos0, B, s_eps_, st_); + head_norm_rope(s_k_, s_dim_, fp(D.k_norm), s_kr_, s_dim_, s_kv_, s_dim_, s_theta_, pos0, B, s_eps_, st_); + spark_store(D, s_kr_, s_v_, pos0, B); + const int64_t lo = D.swa ? std::max(0, pos0 - s_window_) : 0; + inkling_block_attend(s_qr_, D.k, D.v, lo, pos0 + B - 1, D.swa ? s_ring_ : 0, B, s_att_, s_dim_, s_head_, + s_kv_, scale, s_work_, st_); + lin(D.wo, s_att_, s_xn_, B); + axpy(s_xn_, 1.f, s_x_, B * E, true, st_); + rms_norm(s_x_, fp(D.ffn_norm), s_xn_, E, B, s_eps_, st_); + lin(D.gate, s_xn_, s_g_, B); + lin(D.up, s_xn_, s_u_, B); + swiglu_clamp(s_g_, s_u_, s_g_, B * s_ff_, INFINITY, st_); + lin(D.down, s_g_, s_xn_, B); + axpy(s_xn_, 1.f, s_x_, B * E, true, st_); + } + rms_norm(s_x_, fp(s_out_norm_), s_cur_, E, B, s_eps_, st_); + lin(output_, s_cur_ + E, s_base_, most); // the guesses' rows' scores + // the head, a guess at a time from the one before + ck(cudaMemsetAsync(s_state_, 0, (size_t) r * sizeof(float), cs(st_)), "drafter"); + const float* context = s_rnn_ + (size_t) ((pos0 - 1) % (B + 1)) * E; + int32_t prev = token; + for (int i = 1; i <= most; ++i) { + const uint16_t* w1 = markov_ + (size_t) prev * r; + for (int j = 0; j < r; ++j) { + const uint32_t bits = (uint32_t) w1[j] << 16; + std::memcpy(h_w1_ + j, &bits, sizeof(float)); + } + copy2(s_state_, s_in_, r, s_cur_ + (size_t) i * E, s_in_ + 2 * r, E, st_); + h2d(s_in_ + r, h_w1_, (size_t) r * sizeof(float)); + ck(cudaMemcpyAsync(s_in_ + 2 * r + E, context, (size_t) E * sizeof(float), cudaMemcpyDeviceToDevice, cs(st_)), + "drafter"); + lin(s_joint_, s_in_, s_jo_, 1); + add_bias(fp(s_joint_b_), s_jo_, 3 * r, 1, st_); + inkling_dspark_gru(s_jo_, s_state_, s_latent_, r, st_); + lin(s_hout_, s_latent_, s_corr_, 1); + add_bias(fp(s_hout_b_), s_corr_, E, 1, st_); + lin(output_, s_corr_, s_bias_, 1); + float* logits = s_base_ + (size_t) (i - 1) * n_vocab_; + axpy(s_bias_, 1.f, logits, n_vocab_, true, st_); + softcap(logits, (size_t) n_vocab_, s_cap_, st_); + likeliest(logits, n_vocab_real_, h_pick_, st_); + ck(cudaStreamSynchronize(cs(st_)), "drafter"); + out[i - 1] = *h_pick_; + prev = h_pick_->token; + } + return most; +} + +void Inkling::spark_rows_for_test(int64_t pos, int n, const float* features) { + if (!spark_) throw std::logic_error("spark_rows_for_test: no drafter"); + cover(pos + n); + const size_t row = (size_t) 4 * n_embd_; + float* d = nullptr; + ck(cudaMalloc(&d, (size_t) n * row * sizeof(float)), "test"); + // on st_: a cudaMemcpy() from pageable memory can return before its copy lands, and st_ does not wait for it + h2d(d, features, (size_t) n * row * sizeof(float)); + const float* x[4] = {d, d + n_embd_, d + 2 * (size_t) n_embd_, d + 3 * (size_t) n_embd_}; + const int64_t stride[4] = {(int64_t) row, (int64_t) row, (int64_t) row, (int64_t) row}; + spark_rows(pos, n, x, stride); + ck(cudaStreamSynchronize(cs(st_)), "test"); + cudaFree(d); +} + +void Inkling::spark_reload_for_test(int64_t pos) { + if (!spark_) throw std::logic_error("spark_reload_for_test: no drafter"); + pos_ = pos; + std::vector state(state_bytes()), rows((size_t) pos * row_bytes()); + save_state(state.data()); + save_rows(0, pos, rows.data()); + for (const SparkLayer& D : spark_layers_) + for (uint16_t* plane : {D.k, D.v}) zero_vram(plane, (size_t) (D.swa ? s_ring_ : pos) * spark_row()); + zero_vram(s_rnn_, (size_t) (s_block_ + 1) * n_embd_ * sizeof(float)); + load_rows(rows.data(), 0, pos, 0, pos); + load_state(state.data(), pos); + ck(cudaStreamSynchronize(cs(st_)), "test"); + pos_ = 0; +} + +int Inkling::spark_block_for_test(int32_t token, int64_t pos0, int most, int32_t* tokens, float* logits) { + if (!spark_) throw std::logic_error("spark_block_for_test: no drafter"); + std::vector out((size_t) s_block_); + const int n = spark_block(token, pos0, most, out.data()); + for (int i = 0; i < n; ++i) tokens[i] = out[(size_t) i].token; + ck(cudaMemcpy2DAsync(logits, (size_t) n_vocab_real_ * sizeof(float), s_base_, (size_t) n_vocab_ * sizeof(float), + (size_t) n_vocab_real_ * sizeof(float), (size_t) n, cudaMemcpyDeviceToHost, cs(st_)), + "test"); + ck(cudaStreamSynchronize(cs(st_)), "test"); + return n; +} + +} // namespace strata::poly diff --git a/src/poly/inkling.hpp b/src/poly/inkling.hpp new file mode 100644 index 0000000000..3d664ab821 --- /dev/null +++ b/src/poly/inkling.hpp @@ -0,0 +1,242 @@ +// src/poly/inkling.hpp - Thinking Machines' Inkling 2 Mini (llama.cpp architecture "inkling2_loop"): 128 experts, +// 8 a token, 24 layers of which the middle twelve run three times. +// +// No rotary embedding: a layer's attention adds a bias by the distance between query and key, a learned table of +// 16 per distance that the query's own 16 coefficients a head weigh, and each query has a sink logit of its own. +// Five layers in six attend a window of 1,024 positions; every sixth attends everything, with its queries scaled up +// slowly past 8,192 positions. Keys, values, the attention's output and the experts' sum each go through a short +// causal convolution of four taps. +// +// The residual stream starts afresh every six layers ("attention residuals"): what a block of six started from is +// kept, and the input of an attention, an FFN or the output is a learned mix of those and of the stream. +// +// Layers 6 to 17 are the core, run three times in a row ("passes"). Each pass starts from what layer 5 gave; from +// the second on, every core layer also gets a message from the pass before (a mix of what that pass left), which +// a small gate of its own blends into the attention's and the FFN's inputs. Every run of a layer has its own +// attention cache and convolution state. +// +// In the engine a run of a layer is a "visit": 48 of them in the order they run (layers_, n_layer_), each with the +// weights of its physical layer. On several cards a card has a run of physical layers, and the loop's are on one +// card: a card starts at layer 1 to 6 or 18 to 22. The reference for the math is llama.cpp's +// src/models/inkling2.cpp and inkling2-loop.cpp (29b52d398b). +#pragma once + +#include "engine.hpp" +#include "strata/poly/inkling_kernels.hpp" + +#include + +namespace strata::poly { + +class Inkling final : public Engine { +public: + /// For a layer split (Engine::open()): the file's layers (n_layer: its block_count, which in Unsloth's files + /// counts every visit) as physical ones, and the loop's [keep_lo, keep_hi), which runs on one card: a later visit + /// runs the first one's experts (Layer::alias) and weights. + static void split_layers(const Shards& file, int& n_layer, int& keep_lo, int& keep_hi); + size_t card_row_bytes() const override; + void save_card_rows(int64_t first, int64_t n, uint8_t* dst) override; + void load_card_rows(const uint8_t* src, int64_t from, int64_t count, int64_t first, int64_t n) override; + +protected: + void load_geometry() override; + void load_layer(int il) override; + void begin_pass() override; + size_t recurrent_floats() const override; + void alloc_caches() override; + void assign_scratch() override; + bool sees() const override { return true; } // pictures (strata-vision's rows) in place of tokens + /// step()'s rows in one head: the products, mixes and controllers for all of them, and each row's caches, + /// convolution states and position from its own sequence (attn(), post_conv()). The rows' positions go to the + /// kernels by value, so a step is not recorded: with --batch Inkling sets no Layer::fixed, and step() records + /// only those. + bool batch_heads() const override { return true; } + /// A call's launches that take the position read its first one from at_ when recorded (attn()), a token's and a + /// window's alike; a full visit's attention is recorded once for each room() it is sized for, a window visit's + /// for the context. + int head_key(int il, int n) const override; + /// A call's visits are recorded only as one, when its routed experts are all on the card (Engine::run()). + bool layer_graphs() const override { return false; } + /// A thread a core: on a Ryzen 7 7800X3D (8 cores, 16 CPUs) beside an RX 9070 XT, IQ4_NL wrote 45.5 to 47.2 + /// tokens/s with 8 threads and 42.1 to 44.7 with the 11 of 70%; on a Ryzen 5 3600XT beside an RTX 2070 Super, + /// 6, 8, 11 and 12 threads were the same. + bool thread_a_core() const override { return true; } + /// A window of guesses is routed on the card (Engine::moe_card()) with every expert in VRAM, so that it is + /// recorded as one too: --window 5 to 8 have more rows than kSumRows. + bool windows_on_card() const override { return true; } + int widest() const override { return std::max({n_head_ * head_dim_, 2 * n_embd_, s_ff_}); } + int streams() const override { return kStreams + (spark_ ? kTaps : 0); } + void layer_head(Layer& L, int il, int n) override; + void layer_tail(Layer& L, int il, int n) override; + void output_rows(int first, int rows, float* h) override; + void route(int il, const float* logits, int32_t token, int* ids, float* w, float* tmp) const override; + bool route_card(int il, int n, int32_t* ids, float* w) override; + void router_scores(const Layer& L, int n) override; + void moe_shared(const Layer& L, int il, int n) override; + /// A token's (fused()), outside a window of guesses: the same for every call of one token, so that a recording + /// of moe_card() serves run() and step() alike. + bool card_sum_in_tail(int n) const override { return n == 1 && !opt_.dump && opt_.window == 1; } + bool act_rows_q8_1(const float* gate_up, void* q8, int rows, const ExpertScales* es) override; + void finish_logits(float* logits, int rows) override; + void shift_rows(ptrdiff_t by) override; + size_t extra_bytes() const override; + void load_drafter() override; + void drafter_rows(int64_t pos, int n, const float* h) override; + int draft_block(int32_t token, int most, Likeliest* out) override; + void save_layer(int il, int64_t pos, uint8_t* dst) override; + void load_extra(const uint8_t* src, int64_t pos) override; + void save_last(uint8_t* dst, int64_t pos) override; + const Names* tensor_alias(const char* name) const override; + const Names* meta_alias(const char* key) const override; + int physical(int v) const override { return phys_of(v); } + +private: + /// The residual streams of a token in r_, n_embd_ floats each: the stream itself, the four blocks' starts + /// (the normed embedding, layer 5's output, layer 11's of this pass, layer 17's of the last pass), and what + /// the pass before left for the messages (its layer 11's and 17's outputs). + /// With the drafter, three more: the streams entering the visits it reads (kTap0 on). + enum Stream { kCur = 0, kBlock0 = 1, kBank = 5, kBankOut = 6, kStreams = 7, kTap0 = 7, kTaps = 3 }; + + /// A visit's weights (its physical layer's: a later visit has the first one's pointers) and its caches. + struct Block { + int phys = 0; ///< the physical layer + int pass = 0; ///< 0: the prelude, the epilogue and the core's first pass; 1, 2: the core's later passes + bool swa = false; + int extent = 0; ///< the distances its bias table has + Dev wq, wk, wv, wo, wgate, wrel, wsink, rel_bias, q_clip, rel_clip; + Dev k_conv, v_conv, post_conv, ffn_post_conv; + Dev q_norm, k_norm, v_norm; ///< a full layer's three input norms (a window layer's is Layer::attn_norm) + Dev k_conv_proj, v_conv_proj; ///< a full layer's input-dependent taps + Dev attn_query, ffn_query; ///< the depth mix's queries: 1 (window) or 3 (full) for the attention + Dev msg_query; ///< a core layer's: the messages' 4 queries + Dev ctrl_down[4], ctrl_gain[4], ctrl_forget[4]; ///< a core layer's gates: q, k, v, ffn + std::vector probs_b; ///< the bias the routed experts' pick adds to the gates + Dev probs_b_dev; + float* conv = nullptr; ///< in state_: K, V, attention-out, FFN-out convolutions' 3 past inputs + /// The caches, a row a position (max_context of them, or ring_ in a window visit): fp16 keys and values + /// (planes 0, 1), or under --kv q8_0 the keys' codes and scales and the values' codes and scales (0 to 3), a + /// Q8_0 block's fp16 scale for every 32 codes (store_q8()). + uint8_t* plane[4] = {}; + }; + + bool q8() const { return opt_.kv_format == KvFmt::kQ8_0; } + int planes() const { return q8() ? 4 : 2; } + size_t plane_row(int i) const; ///< a row's bytes in plane i + int phys_of(int v) const; + int pass_of(int v) const; + /// The blocks a layer's mix has before its attention (before) or its FFN (after its block is pushed). + static int blocks_before(int ip) { return ip == 0 ? 0 : (ip - 1) / kBlockSize + 1; } + static int blocks_at(int ip) { return ip / kBlockSize + 1; } + static constexpr int kBlockSize = 6; + /// loop.count's bound: the released model runs 3 passes. Nothing else limits it (each pass more is 12 visits' + /// caches and state); a larger value is taken for a bad file. + static constexpr int kMaxPasses = 8; + + float* stream(int k) const { return r_ + (size_t) k * n_embd_; } + /// Where a layer works on the stream of a call of n tokens: r_ itself for one, else res_ (gathered by the head, + /// scattered back by the tail). + float* work_stream(int n) const { return n == 1 ? stream(kCur) : res_; } + void gather(int k, float* dst, int n, int first = 0); + void scatter(int k, const float* src, int n); + void copy_stream(int from, int to, int n); + void attn(Block& B, int il, const float* xq, const float* xk, const float* xv, const void* const* q8, int n, + bool fuse); + /// A token alone (not step()'s rows, no --dump-layers) goes in fewer launches, the same bits: the visit before's + /// tail convolution with the first mix, K and V's store with the clips, the attention's gate with its output, + /// three input norms in one launch, the attention's convolution with the FFN's mix and, with the experts on the + /// card, their sum with the tail's convolution. + bool fused(int n) const { return n == 1 && !rows_of_ && !opt_.dump; } + int64_t attn_room(const Block& B, int n) const; + void post_conv(const float* x, float* state, const Dev& w, float* acc, int n, bool fresh, const Row* rows); + void conv_snaps(const float* x, const float* state, int channels, int n); + void dump(const char* name, int il, const float* dev, int width, int n); + int slot_of(int v) const; ///< llama.cpp's layer index of visit v (its cache slot), for the dumps + template + void window_runs(int64_t pos, F&& f) const; + + std::vector blocks_; ///< one a visit, as layers_ + int n_phys_ = 0, core_start_ = 0, core_end_ = 0, n_passes_ = 0, rank_ = 0; + int n_head_ = 0, n_kv_ = 0, head_dim_ = 0, n_rel_ = 0, extent_ = 0, n_conv_ = 4; + int n_vocab_real_ = 0; + float qk_clip_ = 0, rel_clip_ = 0, softcap_ = 0, w_scale_ = 0; + float norm_eps_ = 1e-6f; ///< the depth mix's and the controls' (the weighted norms take rms_eps_) + float tau_alpha_ = 0; + int tau_floor_ = 0; + int window_ = 0; ///< the tokens a window layer attends, the token itself among them + int ring_ = 0; ///< rows of a window layer's caches: the window and a call's tokens + int keep_ = 0; ///< rows of a window layer a sequence's state keeps + Dev tok_norm_, out_query_; + size_t conv_floats_ = 0; ///< one visit's convolution state + + // device scratch, rows_ tokens each + float *res_ = nullptr; ///< the stream (kCur) from a layer's head to its tail + const Row* tail_rows_ = nullptr; ///< step()'s rows (rows_of_) from a layer's head to its tail + InklingConvIn tail_conv_; ///< a token's tail convolution, left to the next visit's head (fused()) + bool tail_wait_ = false; ///< tail_conv_ is still to be done + float *blk_[4] = {}; ///< the blocks, gathered from r_ + float *bank_ = nullptr, *bank_out_ = nullptr; + float *msg_[4] = {}; ///< a core layer's messages: q, k, v, ffn + float *mix_[3] = {}; ///< the attention's inputs out of the depth mix + float *in_[3] = {}; ///< the normed (and controlled) q, k, v inputs + float *ctl_[3] = {}, *ctl_work_ = nullptr; + void* inq_[3] = {}; ///< in_'s Q8_1 copies + void* attq_ = nullptr; ///< a token's gated attention output's Q8_1 copy (fused()) + float* neg_inf_ = nullptr; ///< -inf for the padded vocabulary's scores + void* mix_work_ = nullptr; ///< inkling_mix_conv()'s blocks' meeting place + float *q_ = nullptr, *kraw_ = nullptr, *k_ = nullptr, *vraw_ = nullptr, *v_ = nullptr, *rel_ = nullptr, + *sink_ = nullptr, *gate_ = nullptr, *ktap_ = nullptr, *vtap_ = nullptr, *att_ = nullptr, *o_ = nullptr; + float* awork_ = nullptr; + size_t awork_n_ = 0; + bool int8_dot_ = false; ///< STRATA_KV_INT8: decode attention by __dp4a on the q8_0 cache + /// unsloth's layout: architecture "inkling2", block_count the visits, loop_{attn,k,v,mlp}_* + bool unsloth_ = false; + void* msg_mem_ = nullptr; ///< that layout's message queries, a core layer's [2304, 4] each + static constexpr int kFusedRows = 16; ///< the most tokens the controllers' and the router's fused kernels take + + // ---- the DSpark drafter: --draft-model, a "dflash" file (inkling.cpp) ---- + /// A layer of the drafter: dense, pre-norm, its attention's keys and values of the model's rows (k_ctx, v_ctx) + /// and of the block's own in one cache, a row a position (a ring of d_ring_ rows in a window layer). + struct SparkLayer { + bool swa = false; + Dev attn_norm, wq, wk, wv, wo, q_norm, k_norm, k_ctx, v_ctx, k_ctx_norm, ctx_norm, ffn_norm, gate, up, down; + uint16_t* k = nullptr; + uint16_t* v = nullptr; + }; + void load_spark_shape(); + size_t spark_row() const { return (size_t) s_kv_ * s_dim_ * sizeof(uint16_t); } ///< a key's or a value's row + size_t spark_extra() const; + template + void spark_window(int64_t pos, F&& f) const; + void spark_store(const SparkLayer& D, const float* k, const float* v, int64_t pos, int n); + void spark_rows(int64_t pos, int n, const float* const* x, const int64_t* stride); + int spark_block(int32_t token, int64_t pos0, int most, Likeliest* out); + bool spark_ = false; + std::vector spark_layers_; + int taps_[kTaps] = {}; ///< the visits whose input streams it reads; the model's output is its fourth input + int s_head_ = 0, s_kv_ = 0, s_dim_ = 0, s_ff_ = 0, s_rank_ = 0, s_block_ = 0, s_window_ = 0, s_ring_ = 0; + float s_eps_ = 0, s_theta_ = 0, s_cap_ = 0; + float fuse_[4][4] = {}; ///< softmax(dspark_fuse): a row for each layer's context and one for the head's + Dev s_out_norm_, s_mask_, s_ctx_norm_, s_joint_, s_joint_b_, s_hout_, s_hout_b_; + const uint16_t* markov_ = nullptr; ///< markov_w1 (BF16, rank a token), read in the file + float* s_ctx_[4] = {}; ///< a call's rows fused: each layer's context and the head's + float* s_rnn_ = nullptr; ///< the head's context of the last s_block_ + 1 positions, a ring (seq_alloc) + float *s_x_ = nullptr, *s_xn_ = nullptr, *s_q_ = nullptr, *s_k_ = nullptr, *s_v_ = nullptr, *s_qr_ = nullptr, + *s_kr_ = nullptr, *s_att_ = nullptr, *s_g_ = nullptr, *s_u_ = nullptr, *s_cur_ = nullptr, + *s_base_ = nullptr, *s_bias_ = nullptr, *s_in_ = nullptr, *s_jo_ = nullptr, *s_state_ = nullptr, + *s_latent_ = nullptr, *s_corr_ = nullptr, *s_work_ = nullptr; + float* h_w1_ = nullptr; ///< pinned: a markov_w1 row as floats, then a token's embedding + Likeliest* h_pick_ = nullptr; ///< pinned: a slot's guess + +public: + /// Test only (poly_dspark_parity): the drafter takes n rows of the model from position pos as features (host, + /// a row the four inputs of inkling_dspark_fuse() one after the other), then guesses `most` tokens after + /// `token` at pos0 into tokens; logits gets each guess's scores (most rows of n_vocab_real() floats, host). + void spark_rows_for_test(int64_t pos, int n, const float* features); + int spark_block_for_test(int32_t token, int64_t pos0, int most, int32_t* tokens, float* logits); + /// Test only: a conversation's state at pos and its rows before pos saved (save_state(), save_rows()), the + /// drafter's caches zeroed, and the two loaded back, as a conversation cache's turn does. + void spark_reload_for_test(int64_t pos); + int n_vocab_real() const { return n_vocab_real_; } +}; + +} // namespace strata::poly diff --git a/src/poly/inkling_kernels_test.cu b/src/poly/inkling_kernels_test.cu new file mode 100644 index 0000000000..ffb74aab89 --- /dev/null +++ b/src/poly/inkling_kernels_test.cu @@ -0,0 +1,2587 @@ +// src/poly/inkling_kernels_test.cu - Inkling 2 Mini's kernels (inkling_kernels.hpp) against the same arithmetic on +// the host in double precision, on random inputs of the model's shapes: the clips and tau, the short convolutions +// (with and without the input-dependent taps, walked and parallel, and their state), the depth mix, the loop +// controller, SiTU, and the attention over fp16 and Q8_0 caches, full and sliding-window (a ring), split, unsplit +// and on the tensor cores (Turing's kernel and, where it runs, attn_fa2_kernel, to the bit), with and without a +// room past the call, for 1, 7 and more than 1,024 tokens; the calls +// for a token of each of several sequences (Engine::step()'s rows) against a call for each row alone, to the bit; +// the launches that take the position, for a token and for a window's 2 to 8, recorded in a CUDA graph that reads it +// from the card and replayed, against the same calls given it by value, to the bit; +// a visit's projections in one launch (native_mmvq_jobs()) and the cached experts' launches a warp a row +// (MmvqSlots::lanes) against each matrix alone, to the bit; and a token's fused launches (K and V's store with the +// clips, the attention with its gate, the input norms in one launch, the mixes with a post-convolution before them) +// against the calls they stand for, to the bit; and the DSpark drafter's fuse, block attention and recurrent step. +// +// usage: poly_inkling_kernels_test [bench | decode] (exit 0: every check within its tolerance; 77: no usable card; +// bench: also time the attention and the decode shapes; decode: only the decode-shape timings, with a +// token's attention over a q8_0 cache of up to 1M rows and the rate it reads it at) +#include "strata/poly/inkling_kernels.hpp" +#include "strata/poly/kernels.hpp" +#include "strata/kernels/native_mmvq.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace strata::poly; + +int failures = 0; +std::mt19937 rng(1234); + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::printf("CUDA error at %s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +std::vector randv(size_t n, float sd, float mean = 0.f) { + std::normal_distribution d(mean, sd); + std::vector v(n); + for (float& x : v) x = d(rng); + return v; +} + +template T* up(const std::vector& v) { + T* d = nullptr; + ck(cudaMalloc(&d, std::max(1, v.size()) * sizeof(T)), "malloc"); + if (!v.empty()) ck(cudaMemcpy(d, v.data(), v.size() * sizeof(T), cudaMemcpyHostToDevice), "upload"); + return d; +} + +template std::vector down(const T* d, size_t n) { + std::vector v(n); + ck(cudaDeviceSynchronize(), "sync"); + ck(cudaMemcpy(v.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost), "download"); + return v; +} + +// A case that throws is a failure of its own, and the cases after it still run. +template +void guarded(const char* what, F&& f) { + try { + f(); + } catch (const std::exception& e) { + std::printf("%-58s threw: %s FAIL\n", what, e.what()); + ++failures; + } +} + +// A stream of the tests' own: native_mmvq.cu's calls refuse the legacy one. +cudaStream_t test_stream() { + static cudaStream_t st = [] { + cudaStream_t s; + ck(cudaStreamCreate(&s), "stream"); + return s; + }(); + return st; +} + +// max |a - b| and max |a - b| / max(|b|, floor); reports and counts a failure past tol (on the absolute error) +void compare(const char* what, const std::vector& got, const std::vector& ref, double tol, + double floor_ = 1e-3) { + double abs_e = 0, rel_e = 0; + bool nan = false; + size_t worst = 0; + for (size_t i = 0; i < ref.size(); ++i) { + if (!std::isfinite(got[i])) nan = true; + const double e = std::fabs(double(got[i]) - ref[i]); + if (e > abs_e) abs_e = e, worst = i; + rel_e = std::max(rel_e, e / std::max(std::fabs(ref[i]), floor_)); + } + const bool ok = !nan && abs_e <= tol; + if (!ok) ++failures; + std::printf("%-58s n=%-9zu max abs %.3e max rel %.3e %s", what, ref.size(), abs_e, rel_e, ok ? "ok" : "FAIL"); + if (!ok) std::printf(" (at %zu: got %.6g ref %.6g%s)", worst, got[worst], ref[worst], nan ? ", NaN" : ""); + std::printf("\n"); +} + +// ---- clip ------------------------------------------------------------------------------------------------------- + +double host_tau(InklingTau t, long long p) { + if (t.floor <= 0) return 1.0; + float v = (float) p + 1.0f; + v = v * (1.0f / (float) t.floor); + v = std::max(v, 1.0f); + return 1.0 + double(t.alpha) * std::log((double) v); +} + +void test_clip(const char* what, int dim, int heads, int rows, bool scaled, float threshold, InklingTau tau, + long long pos, bool wide) { + const int stride = heads * dim + (wide ? 64 : 0); // wide: a token's input starts past the one before's end + std::vector x(size_t(rows) * stride); + for (int t = 0; t < rows; ++t) { // some rows far inside the threshold, some far outside + const float sd = (t % 3 == 0 ? 0.2f : 3.0f) * threshold / std::sqrt((float) dim); + auto r = randv(stride, sd); + std::copy(r.begin(), r.end(), x.begin() + size_t(t) * stride); + } + std::vector s = scaled ? randv(size_t(heads) * dim, 0.3f, 1.0f) : std::vector{}; + float *dx = up(x), *ds = scaled ? up(s) : nullptr, *dy = nullptr; + ck(cudaMalloc(&dy, size_t(rows) * heads * dim * sizeof(float)), "malloc"); + inkling_clip(dx, stride, ds, dy, dim, heads, rows, threshold, tau, pos, nullptr); + std::vector ref(size_t(rows) * heads * dim); + for (int t = 0; t < rows; ++t) + for (int h = 0; h < heads; ++h) { + std::vector v(dim); + double ss = 0; + for (int i = 0; i < dim; ++i) { + v[i] = double(x[size_t(t) * stride + h * dim + i]) * (scaled ? s[h * dim + i] : 1.0); + ss += v[i] * v[i]; + } + const double f = std::min(1.0, std::max(0.0, threshold / (std::sqrt(ss) + 1e-6))); + const double ta = host_tau(tau, pos + t); + for (int i = 0; i < dim; ++i) ref[(size_t(t) * heads + h) * dim + i] = v[i] * f * ta; + } + compare(what, down(dy, ref.size()), ref, 2e-5 * threshold); + cudaFree(dx), cudaFree(ds), cudaFree(dy); +} + +// ---- conv ------------------------------------------------------------------------------------------------------- + +void host_conv(const std::vector& x, std::vector& state, const std::vector& w, + const std::vector* taps, int heads, std::vector& out, int channels, int rows) { + const double scale = 1.0 / std::sqrt(double((taps ? 2 : 1) * 4 + 1)); + for (int t = 0; t < rows; ++t) { + for (int c = 0; c < channels; ++c) { + double* st = state.data() + size_t(c) * 3; + const double v = x[size_t(t) * channels + c]; + double y = st[0] * w[4 * c] + st[1] * w[4 * c + 1] + st[2] * w[4 * c + 2] + v * w[4 * c + 3]; + if (taps) { + const int h = c / (channels / heads); + const float* tp = taps->data() + (size_t(t) * heads + h) * 4; + y += tp[0] * v + tp[1] * st[2] + tp[2] * st[1] + tp[3] * st[0]; + } + out[size_t(t) * channels + c] = (v + y) * scale; + st[0] = st[1], st[1] = st[2], st[2] = v; + } + } +} + +void test_conv(const char* what, int channels, int heads, bool dynamic, std::vector calls) { + std::vector w = randv(size_t(channels) * 4, 0.4f); + std::vector st0 = randv(size_t(channels) * 3, 1.0f); + std::vector hstate(st0.begin(), st0.end()); + float *dw = up(w), *dst = up(st0); + int total = 0; + for (int rows : calls) { + std::vector x = randv(size_t(rows) * channels, 1.0f); + std::vector taps = randv(size_t(rows) * heads * 4, 0.3f); + float *dx = up(x), *dt = dynamic ? up(taps) : nullptr, *dout = nullptr; + ck(cudaMalloc(&dout, x.size() * sizeof(float)), "malloc"); + inkling_conv(dx, dst, dw, dt, heads, dout, channels, rows, nullptr); + std::vector ref(x.size()); + host_conv(x, hstate, w, dynamic ? &taps : nullptr, heads, ref, channels, rows); + const std::string name = std::string(what) + " rows " + std::to_string(rows) + " out"; + compare(name.c_str(), down(dout, ref.size()), ref, 1e-5); + cudaFree(dx), cudaFree(dt), cudaFree(dout); + total += rows; + } + compare((std::string(what) + " state after " + std::to_string(total)).c_str(), down(dst, hstate.size()), hstate, + 0.0); + cudaFree(dw), cudaFree(dst); +} + +// ---- mix -------------------------------------------------------------------------------------------------------- + +// offset: the states start that many floats into their buffers (1: not 16-byte aligned, the scalar kernel) +void test_mix(int n_state, int n_query, int rows, int n = 2304, int offset = 0) { + InklingMix m; + m.n_state = n_state; + m.n_query = n_query; + std::vector> s; + std::vector bufs; + for (int k = 0; k < n_state; ++k) { + s.push_back(randv(size_t(rows) * n, 0.5f + k, 0.1f * k)); + std::vector padded(offset, 0.f); + padded.insert(padded.end(), s.back().begin(), s.back().end()); + bufs.push_back(up(padded)); + m.state[k] = bufs.back() + offset; + } + std::vector q = randv(size_t(n_query) * n, 1.0f); + m.query = up(q); + for (int i = 0; i < n_query; ++i) ck(cudaMalloc(&m.out[i], size_t(rows) * n * sizeof(float)), "malloc"); + inkling_mix(m, n, rows, 1e-6f, nullptr); + std::vector ref(size_t(n_query) * rows * n); + for (int t = 0; t < rows; ++t) { + std::vector> hat(n_state, std::vector(n)); + for (int k = 0; k < n_state; ++k) { + double ss = 0; + for (int i = 0; i < n; ++i) ss += double(s[k][size_t(t) * n + i]) * s[k][size_t(t) * n + i]; + const double inv = 1.0 / std::sqrt(ss / n + 1e-6); + for (int i = 0; i < n; ++i) hat[k][i] = s[k][size_t(t) * n + i] * inv; + } + for (int j = 0; j < n_query; ++j) { + std::vector sc(n_state); + double mx = -1e300; + for (int k = 0; k < n_state; ++k) { + double d = 0; + for (int i = 0; i < n; ++i) d += hat[k][i] * q[size_t(j) * n + i]; + sc[k] = d / std::sqrt((double) n); + mx = std::max(mx, sc[k]); + } + double sum = 0; + for (double& v : sc) sum += (v = std::exp(v - mx)); + for (int i = 0; i < n; ++i) { + double y = 0; + for (int k = 0; k < n_state; ++k) y += sc[k] / sum * hat[k][i]; + ref[(size_t(j) * rows + t) * n + i] = y; + } + } + } + std::vector got; + for (int j = 0; j < n_query; ++j) { + auto o = down(m.out[j], size_t(rows) * n); + got.insert(got.end(), o.begin(), o.end()); + } + const std::string name = "mix states " + std::to_string(n_state) + " queries " + std::to_string(n_query) + + " rows " + std::to_string(rows) + " n " + std::to_string(n) + + (offset ? " (unaligned)" : ""); + compare(name.c_str(), got, ref, 2e-4); + for (float* b : bufs) cudaFree(b); + for (int j = 0; j < n_query; ++j) cudaFree(m.out[j]); + cudaFree((void*) m.query); +} + +// ---- controller ------------------------------------------------------------------------------------------------- + +// the reference of one controller +void host_control(const std::vector& cur, const std::vector& msg, const std::vector& wd, + const std::vector& wg, const std::vector& wf, int n, int rank, int rows, double* ref) { + for (int t = 0; t < rows; ++t) { + std::vector z(2 * n), r(rank); + for (int half = 0; half < 2; ++half) { + const float* x = (half ? msg.data() : cur.data()) + size_t(t) * n; + double ss = 0; + for (int i = 0; i < n; ++i) ss += double(x[i]) * x[i]; + const double inv = 1.0 / std::sqrt(ss / n + 1e-6); + for (int i = 0; i < n; ++i) z[half * n + i] = x[i] * inv; + } + for (int o = 0; o < rank; ++o) { + double a = 0; + for (int i = 0; i < 2 * n; ++i) a += double(wd[size_t(o) * 2 * n + i]) * z[i]; + r[o] = a; + } + for (int o = 0; o < n; ++o) { + double g = 0, f = 0; + for (int i = 0; i < rank; ++i) { + g += double(wg[size_t(o) * rank + i]) * r[i]; + f += double(wf[size_t(o) * rank + i]) * r[i]; + } + const double c = cur[size_t(t) * n + o], m = msg[size_t(t) * n + o]; + ref[size_t(t) * n + o] = (c - std::tanh(f) * c) + std::tanh(g) * m; + } + } +} + +void test_control(void* blas, int rows) { + const int n = 2304, rank = 64; + std::vector cur = randv(size_t(rows) * n, 1.0f), msg = randv(size_t(rows) * n, 2.0f); + std::vector wd = randv(size_t(rank) * 2 * n, 0.02f), wg = randv(size_t(n) * rank, 0.2f), + wf = randv(size_t(n) * rank, 0.2f); + float *dc = up(cur), *dm = up(msg), *dd = up(wd), *dg = up(wg), *df = up(wf), *work = nullptr, *out = nullptr; + ck(cudaMalloc(&work, size_t(rows) * (4 * n + rank) * sizeof(float)), "malloc"); + ck(cudaMalloc(&out, size_t(rows) * n * sizeof(float)), "malloc"); + inkling_control(blas, dc, dm, dd, dg, df, work, out, n, rank, rows, 1e-6f, nullptr); + std::vector ref(size_t(rows) * n); + host_control(cur, msg, wd, wg, wf, n, rank, rows, ref.data()); + compare(("control rows " + std::to_string(rows)).c_str(), down(out, ref.size()), ref, 1e-4); + cudaFree(dc), cudaFree(dm), cudaFree(dd), cudaFree(dg), cudaFree(df), cudaFree(work), cudaFree(out); +} + +// ---- SiTU ------------------------------------------------------------------------------------------------------- + +void test_situ() { + const int n = 1152, rows = 9; + const float beta = 4.0f, lb = 25.0f; + std::vector gu = randv(size_t(rows) * 2 * n, 6.0f); + for (int i = 0; i < 32; ++i) gu[i] = 60.f * (i - 16), gu[n + i] = 90.f * (i - 16); // the saturated ends + float *dgu = up(gu), *dout = nullptr; + ck(cudaMalloc(&dout, size_t(rows) * n * sizeof(float)), "malloc"); + situ_rows(dgu, dout, n, rows, beta, lb, nullptr); + std::vector ref(size_t(rows) * n); + for (int t = 0; t < rows; ++t) + for (int i = 0; i < n; ++i) { + const double g = gu[size_t(t) * 2 * n + i], u = gu[size_t(t) * 2 * n + n + i]; + ref[size_t(t) * n + i] = beta * std::tanh(g / beta) / (1 + std::exp(-g)) * lb * std::tanh(u / lb); + } + compare("situ_rows (n 1152, rows 9, beta 4, linear beta 25)", down(dout, ref.size()), ref, 2e-4); + // lb <= 0: the up values as they are + situ_rows(dgu, dout, n, 1, beta, 0.f, nullptr); + std::vector ref0(n); + for (int i = 0; i < n; ++i) ref0[i] = beta * std::tanh(gu[i] / beta) / (1 + std::exp(-gu[i])) * gu[n + i]; + compare("situ_rows (no linear beta, 1 row)", down(dout, n), ref0, 2e-3); + cudaFree(dgu), cudaFree(dout); +} + +size_t bytes_differ(const void* a, const void* b, size_t bytes); + +// situ_rows_q8_1() against situ_rows() and native_quantize_q8_1(), to the byte: with the experts' scales by their +// picks, and blocks of zeros, of denormal values and of values past a half's range (the linear beta off). +void test_situ_q8(int rows, float lb, bool scaled) { + const cudaStream_t st = test_stream(); + namespace kk = strata::kernels; + const int n = 1152, n_exp = 16; + const float beta = 4.0f; + std::vector gu = randv(size_t(rows) * 2 * n, 3.0f); + for (int i = 0; i < 32; ++i) gu[i] = 0.f; // a block of zeros + for (int i = 32; i < 64; ++i) gu[i] = 1e-38f * (i - 47); // denormal products + for (int i = 64; i < 96; ++i) gu[i] = 30.f, gu[n + i] = 1e6f * (i - 70); // past 65504 (no linear beta) + std::vector ids(rows); + for (int r = 0; r < rows; ++r) ids[r] = (r * 5) % n_exp; + float *dgu = up(gu), *dh, *gs = up(randv(n_exp, 0.2f, 1.f)), *us = up(randv(n_exp, 0.2f, 1.f)); + int32_t* dids = up(ids); + ck(cudaMalloc(&dh, size_t(rows) * n * 4), "malloc"); + const size_t qb = kk::native_q8_1_bytes(n) * rows; + void *q0, *q1; + ck(cudaMalloc(&q0, qb), "malloc"), ck(cudaMalloc(&q1, qb), "malloc"); + ExpertScales es; + if (scaled) es.gate = gs, es.up = us, es.ids = dids; + situ_rows(dgu, dh, n, rows, beta, lb, st, &es); + kk::native_quantize_q8_1(dh, q0, n * rows, 1, st); + situ_rows_q8_1(dgu, q1, n, rows, beta, lb, st, &es); + const size_t diff = bytes_differ(q0, q1, qb); + char name[120]; + std::snprintf(name, sizeof name, "situ_rows_q8_1 rows %d%s%s", rows, lb > 0 ? "" : " no linear beta", + scaled ? " scaled" : ""); + std::printf("%-58s %zu bytes differ %s\n", name, diff, diff ? "FAIL" : "ok"); + if (diff) ++failures; + for (void* p : {(void*) dgu, (void*) dh, (void*) gs, (void*) us, (void*) dids, q0, q1}) cudaFree(p); +} + +// ---- attention -------------------------------------------------------------------------------------------------- + +constexpr int kDim = 128, kHeads = 24, kKv = 8, kRel = 16, kExtent = 1024; + +struct Cache { + int rows_cap = 0; // rows the cache holds (max context, or the ring) + bool q8 = false; + uint16_t *k = nullptr, *v = nullptr; + int8_t *kc = nullptr, *vc = nullptr; + uint16_t *ks = nullptr, *vs = nullptr; + std::vector hk, hv; // what the cache holds, as the kernels read it, by cache row + void alloc(int cap, bool quant) { + rows_cap = cap, q8 = quant; + const size_t n = size_t(cap) * kKv * kDim; + if (q8) { + ck(cudaMalloc(&kc, n), "malloc"), ck(cudaMalloc(&vc, n), "malloc"); + ck(cudaMalloc(&ks, n / 32 * 2), "malloc"), ck(cudaMalloc(&vs, n / 32 * 2), "malloc"); + // garbage where nothing was stored: the kernels must not read it + ck(cudaMemset(kc, 0x7f, n), "memset"), ck(cudaMemset(vc, 0x7f, n), "memset"); + ck(cudaMemset(ks, 0x7c, n / 16), "memset"), ck(cudaMemset(vs, 0x7c, n / 16), "memset"); + } else { + ck(cudaMalloc(&k, n * 2), "malloc"), ck(cudaMalloc(&v, n * 2), "malloc"); + ck(cudaMemset(k, 0xff, n * 2), "memset"), ck(cudaMemset(v, 0xff, n * 2), "memset"); // NaN halves + } + hk.assign(n, NAN), hv.assign(n, NAN); + } + void free_() { cudaFree(k), cudaFree(v), cudaFree(kc), cudaFree(vc), cudaFree(ks), cudaFree(vs); } + // the rows of positions pos.. into cache rows p % ring (ring 0: p), then the host copy refreshed + void store(const float* dkx, const float* dvx, long long pos, int rows, int ring) { + const int width = kKv * kDim; + for (int done = 0; done < rows;) { + const long long p = pos + done; + const int at = ring ? int(p % ring) : int(p); + const int m = ring ? std::min(rows - done, ring - at) : rows - done; + if (q8) { + store_q8(dkx + size_t(done) * width, kc, ks, width, at, m, nullptr); + store_q8(dvx + size_t(done) * width, vc, vs, width, at, m, nullptr); + } else { + store_f16(dkx + size_t(done) * width, k, width, at, m, nullptr); + store_f16(dvx + size_t(done) * width, v, width, at, m, nullptr); + } + done += m; + } + refresh(); + } + void refresh() { + const size_t n = size_t(rows_cap) * kKv * kDim; + if (q8) { + auto c1 = down(kc, n), c2 = down(vc, n); + auto s1 = down(ks, n / 32), s2 = down(vs, n / 32); + for (size_t i = 0; i < n; ++i) { + hk[i] = float(c1[i]) * __half2float(__ushort_as_half(s1[i / 32])); + hv[i] = float(c2[i]) * __half2float(__ushort_as_half(s2[i / 32])); + } + } else { + auto a = down(k, n), b = down(v, n); + for (size_t i = 0; i < n; ++i) { + hk[i] = __half2float(__ushort_as_half(a[i])); + hv[i] = __half2float(__ushort_as_half(b[i])); + } + } + } +}; + +// the reference for token t (position p) of the call +void host_attend(const Cache& c, const std::vector& q, const std::vector& r, + const std::vector& table, const std::vector* sinks, long long pos, int t, int window, + int ring, double* out) { + const long long p = pos + t; + const long long lo = window > 0 ? std::max(0, p - window + 1) : 0; + const double scale = 1.0 / std::sqrt((double) kDim); + for (int h = 0; h < kHeads; ++h) { + const int g = h / (kHeads / kKv); + const float* qh = q.data() + (size_t(t) * kHeads + h) * kDim; + const float* rh = r.data() + (size_t(t) * kHeads + h) * kRel; + std::vector lg; + double mx = sinks ? (*sinks)[size_t(t) * kHeads + h] : -1e300; + for (long long j = lo; j <= p; ++j) { + const long long row = ring ? j % ring : j; + const float* kj = c.hk.data() + (size_t(row) * kKv + g) * kDim; + double d = 0; + for (int i = 0; i < kDim; ++i) d += double(qh[i]) * kj[i]; + const long long dist = p - j; + double b = 0; + if (dist < kExtent) + for (int i = 0; i < kRel; ++i) b += double(table[size_t(dist) * kRel + i]) * rh[i]; + lg.push_back(d * scale + b); + mx = std::max(mx, lg.back()); + } + double sum = sinks ? std::exp((*sinks)[size_t(t) * kHeads + h] - mx) : 0.0; + for (double& v : lg) sum += (v = std::exp(v - mx)); + double* o = out + size_t(h) * kDim; + std::fill(o, o + kDim, 0.0); + for (long long j = lo; j <= p; ++j) { + const long long row = ring ? j % ring : j; + const float* vj = c.hv.data() + (size_t(row) * kKv + g) * kDim; + const double w = lg[size_t(j - lo)] / sum; + for (int i = 0; i < kDim; ++i) o[i] += w * vj[i]; + } + } +} + +// The tensor-core path rounds the queries, R, the bias table's rows, the softmax's weights and the values to halves +// for its products (inkling_attend(); llama.cpp's flash attention rounds Q, P and V the same way), so it is held to +// fattn_test.cu's bound for the other families' tensor-core attention against the doubles: 7.5e-3 of the largest +// result (at least 1). On an RTX 2070 Super (sm_75) the most is 3.8e-3 of 1. A wrong mask or bias distance could +// hide inside that bound, so the probes (Probe) make the weights exact and hold every path to 1e-5. The other paths +// keep 2e-5. +constexpr double kMmaRoom = 7.5e-3; +bool mma_card = false; // a card of Turing or newer: calls of kInklingMmaRows or more take the tensor cores +bool fa2_card = true; // attn_fa2_kernel runs here (InklingMma::fa2; until a call says not): held to Turing's bits + +// Inputs that make every path's weights exact (no sinks): mean, q = 0 and R = 0, so each visible key weighs 1 and a +// token's result is the mean of their values; edge, q = 0, a table of zeros but for a column of row extent - 1 that +// is 8 and R that picks it with ln 2 (whose half in log2 units is 1), so the key at distance extent - 1 weighs 256 +// and the others 1. Every token is held to 1e-5. +enum class Probe { none, mean, edge }; +constexpr int kProbeCol = 5; + +struct AttnCase { + const char* name; + int window, ring; // 0 0: a full layer + bool q8; + std::vector calls; // tokens of each call, one after the other from position 0 + bool split; // give inkling_attend its work buffer + bool room; // size the launch for a room past the call's positions (a full visit's) + bool sinks; + int check_every; // check every n-th token of a long call (and its last, and the window's edge) + Probe probe = Probe::none; + bool int8_dot = false; // STRATA_KV_INT8's split path (inkling_attend()'s int8_dot) +}; + +void test_attend(const AttnCase& tc, const std::vector& rand_table, float* rand_dtable) { + const bool probe = tc.probe != Probe::none; + std::vector table = rand_table; + float* dtable = rand_dtable; + if (tc.probe == Probe::edge) { + table.assign(size_t(kExtent) * kRel, 0.0f); + table[size_t(kExtent - 1) * kRel + kProbeCol] = 8.0f; + dtable = up(table); + } + int total = 0; + for (int n : tc.calls) total += n; + Cache c; + c.alloc(tc.ring ? tc.ring : total, tc.q8); + float* work = nullptr; + const size_t work_n = inkling_attend_work_floats(kHeads, kDim); + if (tc.split) ck(cudaMalloc(&work, work_n * sizeof(float)), "malloc"); + long long pos = 0; + for (int rows : tc.calls) { + // queries clipped to the model's range (|q| <= 22.6), keys too, values rms-normed: sizes as the model's + std::vector q = randv(size_t(rows) * kHeads * kDim, 1.2f), k = randv(size_t(rows) * kKv * kDim, 1.2f), + v = randv(size_t(rows) * kKv * kDim, 1.0f), r = randv(size_t(rows) * kHeads * kRel, 1.5f), + s = randv(size_t(rows) * kHeads, 2.0f, 1.0f); + if (probe) { + std::fill(q.begin(), q.end(), 0.0f); + std::fill(r.begin(), r.end(), 0.0f); + if (tc.probe == Probe::edge) + for (size_t i = kProbeCol; i < r.size(); i += kRel) r[i] = 0.693147182f; + } + float *dq = up(q), *dk = up(k), *dv = up(v), *dr = up(r), *ds = up(s), *dout = nullptr; + ck(cudaMalloc(&dout, q.size() * sizeof(float)), "malloc"); + c.store(dk, dv, pos, rows, tc.ring); + InklingRel rel{dr, dtable, kRel, kExtent}; + const Kvq8 kq = tc.q8 ? Kvq8{c.kc, c.ks} : Kvq8{}, vq = tc.q8 ? Kvq8{c.vc, c.vs} : Kvq8{}; + const float scale = 1.f / std::sqrt((float) kDim); + const auto attend = [&](float* out, InklingMma mma) { + inkling_attend(dq, c.k, c.v, kq, vq, rel, tc.sinks ? ds : nullptr, pos, rows, out, kDim, kHeads, kKv, + scale, tc.window, tc.ring, work, work_n, nullptr, tc.room ? pos + rows + 517 : 0, + tc.int8_dot, nullptr, nullptr, nullptr, mma); + ck(cudaGetLastError(), "attend"); + }; + attend(dout, InklingMma::best); + auto got = down(dout, q.size()); + std::string tiers; // the tensor-core path: both kernels, to the bit + if (mma_card && fa2_card && rows >= kInklingMmaRows) try { + attend(dout, InklingMma::fa2); + const auto b = down(dout, q.size()); + attend(dout, InklingMma::turing); + const auto a = down(dout, q.size()); + size_t diff = 0; + for (size_t i = 0; i < a.size(); ++i) diff += std::memcmp(&a[i], &b[i], sizeof(float)) != 0; + if (diff) ++failures; + tiers = ", fa2 vs Turing's kernel " + std::to_string(diff) + " values differ" + (diff ? " FAIL" : ""); + } catch (const std::invalid_argument&) { + std::printf("attn_fa2_kernel does not run on this card: Turing's kernel only\n"); + fa2_card = false; + } + std::vector toks; + for (int t = 0; t < rows; ++t) { + const long long p = pos + t; + const bool edge = (p >= 1020 && p <= 1030) || (p >= 2045 && p <= 2050); + if (t % tc.check_every == 0 || t == rows - 1 || edge) toks.push_back(t); + } + std::vector ref(toks.size() * kHeads * kDim); + std::vector sel(ref.size()); + for (size_t i = 0; i < toks.size(); ++i) { + host_attend(c, q, r, table, tc.sinks ? &s : nullptr, pos, toks[i], tc.window, tc.ring, + ref.data() + i * kHeads * kDim); + std::copy(got.begin() + size_t(toks[i]) * kHeads * kDim, got.begin() + size_t(toks[i] + 1) * kHeads * kDim, + sel.begin() + i * kHeads * kDim); + } + const std::string name = std::string(tc.name) + ": pos " + std::to_string(pos) + " rows " + + std::to_string(rows) + " (" + std::to_string(toks.size()) + " checked)" + tiers; + double top = 1.0; + for (double x : ref) top = std::max(top, std::fabs(x)); + const double tol = + tc.int8_dot ? 2e-2 : probe ? 1e-5 : mma_card && rows >= kInklingMmaRows ? kMmaRoom * top : 2e-5; + compare(name.c_str(), sel, ref, tol); + cudaFree(dq), cudaFree(dk), cudaFree(dv), cudaFree(dr), cudaFree(ds), cudaFree(dout); + pos += rows; + } + c.free_(); + cudaFree(work); + if (dtable != rand_dtable) cudaFree(dtable); +} + +// A token's result the same, to the bit, alone and beside others (the split path). +void test_attend_alone(const std::vector& table, float* dtable) { + const int ctx = 3000, rows = 7, window = 1024, ring = window + 2048; + for (int w : {0, window}) { + Cache c; + c.alloc(w ? ring : ctx + rows, false); + auto k = randv(size_t(ctx + rows) * kKv * kDim, 1.2f), v = randv(size_t(ctx + rows) * kKv * kDim, 1.0f); + float *dk = up(k), *dv = up(v); + for (int p = 0; p < ctx + rows; p += 1000) { + const int m = std::min(1000, ctx + rows - p); + c.store(dk + size_t(p) * kKv * kDim, dv + size_t(p) * kKv * kDim, p, m, w ? ring : 0); + } + auto q = randv(size_t(rows) * kHeads * kDim, 1.2f), r = randv(size_t(rows) * kHeads * kRel, 1.5f), + s = randv(size_t(rows) * kHeads, 2.0f); + float *dq = up(q), *dr = up(r), *ds = up(s), *o1 = nullptr, *o2 = nullptr, *work = nullptr; + ck(cudaMalloc(&o1, q.size() * 4), "malloc"), ck(cudaMalloc(&o2, q.size() * 4), "malloc"); + const size_t wn = inkling_attend_work_floats(kHeads, kDim); + ck(cudaMalloc(&work, wn * 4), "malloc"); + const float scale = 1.f / std::sqrt((float) kDim); + inkling_attend(dq, c.k, c.v, {}, {}, {dr, dtable, kRel, kExtent}, ds, ctx, rows, o1, kDim, kHeads, kKv, scale, + w, w ? ring : 0, work, wn, nullptr, ctx + 64); + for (int t = 0; t < rows; ++t) { + inkling_attend(dq + size_t(t) * kHeads * kDim, c.k, c.v, {}, {}, + {dr + size_t(t) * kHeads * kRel, dtable, kRel, kExtent}, ds + size_t(t) * kHeads, ctx + t, + 1, o2 + size_t(t) * kHeads * kDim, kDim, kHeads, kKv, scale, w, w ? ring : 0, work, wn, + nullptr, ctx + 64); + ck(cudaDeviceSynchronize(), "sync"); + } + auto a = down(o1, q.size()), b = down(o2, q.size()); + size_t diff = 0; + for (size_t i = 0; i < a.size(); ++i) diff += a[i] != b[i]; + std::printf("%-58s %zu of %zu values differ %s\n", + w ? "attend split, 7 tokens vs one at a time (window)" + : "attend split, 7 tokens vs one at a time (full)", + diff, a.size(), diff ? "FAIL" : "ok"); + if (diff) ++failures; + cudaFree(dk), cudaFree(dv), cudaFree(dq), cudaFree(dr), cudaFree(ds), cudaFree(o1), cudaFree(o2), + cudaFree(work); + c.free_(); + } +} + +// The tensor-core path: a token's result the same, to the bit, in calls that start at other tokens (other blocks +// and other rows of a block). +void test_attend_mma_alone(const std::vector& table, float* dtable, bool q8, InklingMma mma) { + const int ctx = 3000, rows = 130, shift = 23, window = 1024, ring = window + 2048; + for (int w : {0, window}) { + Cache c; + c.alloc(w ? ring : ctx + rows, q8); + auto k = randv(size_t(ctx + rows) * kKv * kDim, 1.2f), v = randv(size_t(ctx + rows) * kKv * kDim, 1.0f); + float *dk = up(k), *dv = up(v); + for (int p = 0; p < ctx + rows; p += 1000) { + const int m = std::min(1000, ctx + rows - p); + c.store(dk + size_t(p) * kKv * kDim, dv + size_t(p) * kKv * kDim, p, m, w ? ring : 0); + } + auto q = randv(size_t(rows) * kHeads * kDim, 1.2f), r = randv(size_t(rows) * kHeads * kRel, 1.5f), + s = randv(size_t(rows) * kHeads, 2.0f); + float *dq = up(q), *dr = up(r), *ds = up(s), *o1 = nullptr, *o2 = nullptr; + ck(cudaMalloc(&o1, q.size() * 4), "malloc"), ck(cudaMalloc(&o2, q.size() * 4), "malloc"); + const Kvq8 kq = q8 ? Kvq8{c.kc, c.ks} : Kvq8{}, vq = q8 ? Kvq8{c.vc, c.vs} : Kvq8{}; + const float scale = 1.f / std::sqrt((float) kDim); + inkling_attend(dq, c.k, c.v, kq, vq, {dr, dtable, kRel, kExtent}, ds, ctx, rows, o1, kDim, kHeads, kKv, scale, + w, w ? ring : 0, nullptr, 0, nullptr, 0, false, nullptr, nullptr, nullptr, mma); + const size_t off = size_t(shift) * kHeads; + inkling_attend(dq + off * kDim, c.k, c.v, kq, vq, {dr + off * kRel, dtable, kRel, kExtent}, ds + off, + ctx + shift, rows - shift, o2, kDim, kHeads, kKv, scale, w, w ? ring : 0, nullptr, 0, nullptr, 0, + false, nullptr, nullptr, nullptr, mma); + auto a = down(o1, q.size()), b = down(o2, q.size() - off * kDim); + size_t diff = 0; + for (size_t i = 0; i < b.size(); ++i) diff += a[off * kDim + i] != b[i]; + const std::string name = std::string("attend tensor cores") + (mma == InklingMma::fa2 ? " (fa2), " : ", ") + + (q8 ? "q8_0" : "fp16") + ", " + std::to_string(rows - shift) + " tokens in 2 calls (" + + (w ? "window" : "full") + ")"; + std::printf("%-58s %zu of %zu values differ %s\n", name.c_str(), diff, b.size(), diff ? "FAIL" : "ok"); + if (diff) ++failures; + cudaFree(dk), cudaFree(dv), cudaFree(dq), cudaFree(dr), cudaFree(ds), cudaFree(o1), cudaFree(o2); + c.free_(); + } +} + +// Timings (with `bench`): a prompt batch's attention and a token's, full and window layers, fp16 caches. +void bench_attend(const std::vector& table, float* dtable) { + const int ctx = 32768, window = 1024; + auto k = randv(size_t(ctx) * kKv * kDim, 1.0f); + float* dk = up(k); // the same numbers for keys and values: only the time is looked at + uint16_t *kc = nullptr, *vc = nullptr; + ck(cudaMalloc(&kc, k.size() * 2), "malloc"), ck(cudaMalloc(&vc, k.size() * 2), "malloc"); + store_f16(dk, kc, kKv * kDim, 0, ctx, nullptr); + store_f16(dk, vc, kKv * kDim, 0, ctx, nullptr); + const int rows = 4096; + auto q = randv(size_t(rows) * kHeads * kDim, 1.0f), r = randv(size_t(rows) * kHeads * kRel, 1.0f), + s = randv(size_t(rows) * kHeads, 1.0f); + float *dq = up(q), *dr = up(r), *ds = up(s), *out = nullptr, *work = nullptr; + ck(cudaMalloc(&out, q.size() * 4), "malloc"); + const size_t wn = inkling_attend_work_floats(kHeads, kDim); + ck(cudaMalloc(&work, wn * 4), "malloc"); + cudaEvent_t e0, e1; + cudaEventCreate(&e0), cudaEventCreate(&e1); + auto time = [&](const char* what, auto&& f) { + f(); + cudaEventRecord(e0); + const int reps = 5; + for (int i = 0; i < reps; ++i) f(); + cudaEventRecord(e1); + cudaEventSynchronize(e1); + float ms = 0; + cudaEventElapsedTime(&ms, e0, e1); + std::printf("bench %-52s %9.3f ms\n", what, ms / reps); + }; + const float sc = 1.f / std::sqrt((float) kDim); + InklingRel rel{dr, dtable, kRel, kExtent}; + time("prompt 4096 tokens from 0, full layer", [&] { + inkling_attend(dq, kc, vc, {}, {}, rel, ds, 0, rows, out, kDim, kHeads, kKv, sc, 0, 0, work, wn, nullptr); + }); + time("prompt 4096 tokens from 0, window 1024", [&] { + inkling_attend(dq, kc, vc, {}, {}, rel, ds, 0, rows, out, kDim, kHeads, kKv, sc, window, 0, work, wn, nullptr); + }); + for (int n : {17, 32, 48, 64, 128}) { // a prompt's last call: about the tensor-core path's smallest + const std::string a = std::to_string(n) + " tokens at 8192, full layer"; + time(a.c_str(), [&] { + inkling_attend(dq, kc, vc, {}, {}, rel, ds, 8192, n, out, kDim, kHeads, kKv, sc, 0, 0, work, wn, nullptr); + }); + const std::string b = std::to_string(n) + " tokens at 8192, window 1024"; + time(b.c_str(), [&] { + inkling_attend(dq, kc, vc, {}, {}, rel, ds, 8192, n, out, kDim, kHeads, kKv, sc, window, 0, work, wn, + nullptr); + }); + } + for (int p : {1024, 4096, 32767}) { + const std::string a = "1 token at " + std::to_string(p) + ", full layer"; + time(a.c_str(), [&] { + inkling_attend(dq, kc, vc, {}, {}, rel, ds, p, 1, out, kDim, kHeads, kKv, sc, 0, 0, work, wn, nullptr); + }); + } + time("1 token at 32767, window 1024", [&] { + inkling_attend(dq, kc, vc, {}, {}, rel, ds, 32767, 1, out, kDim, kHeads, kKv, sc, window, 0, work, wn, + nullptr); + }); + time("7 tokens at 32760, window 1024", [&] { + inkling_attend(dq, kc, vc, {}, {}, rel, ds, 32760, 7, out, kDim, kHeads, kKv, sc, window, 0, work, wn, + nullptr); + }); + ck(cudaDeviceSynchronize(), "bench"); + cudaFree(dk), cudaFree(kc), cudaFree(vc), cudaFree(dq), cudaFree(dr), cudaFree(ds), cudaFree(out), cudaFree(work); +} + +// Timings (with `bench`): a prompt batch's attention on the tensor cores, each kernel, in a 32K cache: the engine's +// calls of 1,024 tokens at its end and at the start of a prompt (the calls of a 2K or 8K prompt), 4,096 for a longer +// batch; in TFLOPS of the products the keys a token sees take. +void bench_attend_tiers(const std::vector& table, float* dtable) { + const int ctx = 32768, window = 1024; + auto k = randv(size_t(ctx) * kKv * kDim, 1.0f); + float* dk = up(k); + Cache f16, q8; + f16.alloc(ctx, false), q8.alloc(ctx, true); + for (int p = 0; p < ctx; p += 4096) f16.store(dk + size_t(p) * kKv * kDim, dk + size_t(p) * kKv * kDim, p, 4096, 0); + for (int p = 0; p < ctx; p += 4096) q8.store(dk + size_t(p) * kKv * kDim, dk + size_t(p) * kKv * kDim, p, 4096, 0); + const int most = 4096; + auto q = randv(size_t(most) * kHeads * kDim, 1.0f), r = randv(size_t(most) * kHeads * kRel, 1.0f), + s = randv(size_t(most) * kHeads, 1.0f); + float *dq = up(q), *dr = up(r), *ds = up(s), *out = nullptr; + ck(cudaMalloc(&out, q.size() * 4), "malloc"); + cudaEvent_t e0, e1; + cudaEventCreate(&e0), cudaEventCreate(&e1); + const float sc = 1.f / std::sqrt((float) kDim); + const InklingRel rel{dr, dtable, kRel, kExtent}; + for (bool quant : {true, false}) + for (int w : {0, window}) + for (const std::pair call : {std::pair{4096, ctx - 4096}, + {1024, ctx - 1024}, {1024, 0}, {1024, 1024}, {1024, 2048}, + {1024, 3072}, {1024, 7168}}) { + const int rows = call.first; + const long long pos = call.second; + double flop = 0; + for (int t = 0; t < rows; ++t) + flop += 4.0 * kDim * kHeads * (w ? std::min(w, pos + t + 1) : pos + t + 1); + const Cache& c = quant ? q8 : f16; + const Kvq8 kq = quant ? Kvq8{c.kc, c.ks} : Kvq8{}, vq = quant ? Kvq8{c.vc, c.vs} : Kvq8{}; + for (InklingMma mma : {InklingMma::turing, InklingMma::fa2, InklingMma::best}) { + if (mma == InklingMma::fa2 && !fa2_card) continue; + const auto f = [&] { + inkling_attend(dq, c.k, c.v, kq, vq, rel, ds, pos, rows, out, kDim, kHeads, kKv, sc, w, 0, + nullptr, 0, nullptr, 0, false, nullptr, nullptr, nullptr, mma); + }; + f(); + const int reps = rows == 4096 ? 5 : pos < 4096 ? 100 : 20; + cudaEventRecord(e0); + for (int i = 0; i < reps; ++i) f(); + cudaEventRecord(e1); + cudaEventSynchronize(e1); + float ms = 0; + cudaEventElapsedTime(&ms, e0, e1); + ms /= reps; + const std::string what = std::string("prompt ") + std::to_string(rows) + " tokens at " + + std::to_string(pos) + ", " + (w ? "window 1024" : "full layer") + ", " + + (quant ? "q8_0" : "fp16") + ", " + + (mma == InklingMma::turing ? "Turing's kernel" + : mma == InklingMma::fa2 ? "fa2" + : "the path's choice"); + std::printf("bench %-74s %9.3f ms %6.1f TFLOPS\n", what.c_str(), ms, flop / ms * 1e-9); + } + } + ck(cudaDeviceSynchronize(), "bench"); + f16.free_(), q8.free_(); + cudaFree(dk), cudaFree(dq), cudaFree(dr), cudaFree(ds), cudaFree(out); +} + +// ---- the fused decode steps --------------------------------------------------------------------------------------- + +void test_control_fused(int count, int rows) { + const int n = 2304, rank = 64; + std::vector c(count); + std::vector ref(size_t(count) * rows * n); + std::vector frees; + for (int k = 0; k < count; ++k) { + auto cur = randv(size_t(rows) * n, 1.0f), msg = randv(size_t(rows) * n, 2.0f); + auto wd = randv(size_t(rank) * 2 * n, 0.02f), wg = randv(size_t(n) * rank, 0.2f), + wf = randv(size_t(n) * rank, 0.2f); + host_control(cur, msg, wd, wg, wf, n, rank, rows, ref.data() + size_t(k) * rows * n); + float *dc = up(cur), *dm = up(msg), *dd = up(wd), *dg = up(wg), *df = up(wf), *out = nullptr; + ck(cudaMalloc(&out, cur.size() * 4), "malloc"); + c[k].cur = dc, c[k].msg = dm, c[k].out = k % 2 ? dc : out; // in place for every other one + c[k].down = dd, c[k].gain = dg, c[k].forget = df; + frees.insert(frees.end(), {dc, dm, dd, dg, df, out}); + } + float* work = nullptr; + ck(cudaMalloc(&work, size_t(count) * rows * rank * 4), "malloc"); + inkling_control_fused(c.data(), count, n, rank, rows, 1e-6f, work, nullptr); + std::vector got; + for (int k = 0; k < count; ++k) { + auto o = down(c[k].out, size_t(rows) * n); + got.insert(got.end(), o.begin(), o.end()); + } + const std::string name = std::string("control fused ") + std::to_string(count) + " ctrl, rows " + + std::to_string(rows); + compare(name.c_str(), got, ref, 1e-4); + for (void* p : frees) cudaFree(p); + cudaFree(work); +} + +void test_gemv(int n_in, int n_out, int rows) { + auto w = randv(size_t(n_in) * n_out, 0.05f), x = randv(size_t(rows) * n_in, 1.0f); + float *dw = up(w), *dx = up(x), *dy = nullptr; + ck(cudaMalloc(&dy, size_t(rows) * n_out * 4), "malloc"); + inkling_gemv(dw, dx, dy, n_in, n_out, rows, nullptr); + std::vector ref(size_t(rows) * n_out); + for (int t = 0; t < rows; ++t) + for (int o = 0; o < n_out; ++o) { + double a = 0; + for (int i = 0; i < n_in; ++i) a += double(w[size_t(o) * n_in + i]) * x[size_t(t) * n_in + i]; + ref[size_t(t) * n_out + o] = a; + } + const std::string name = "gemv " + std::to_string(n_in) + " -> " + std::to_string(n_out) + ", rows " + + std::to_string(rows); + compare(name.c_str(), down(dy, ref.size()), ref, 1e-4); + cudaFree(dw), cudaFree(dx), cudaFree(dy); +} + +// the bits of two device buffers of floats +void same_bits(const char* what, const float* a, const float* b, size_t n) { + auto x = down(a, n), y = down(b, n); + size_t diff = 0; + for (size_t i = 0; i < n; ++i) diff += std::memcmp(&x[i], &y[i], 4) != 0; + std::printf("%-58s %zu of %zu values differ %s\n", what, diff, n, diff ? "FAIL" : "ok"); + if (diff) ++failures; +} + +// STRATA_KV_INT8 where it does not apply: the same bits as without it (fp16 caches, window layers, rooms under 32K). +void test_int8_unchanged(const std::vector& table, float* dtable) { + const int ctx = 20000, window = 1024, rows = 7; + auto kv = randv(size_t(ctx) * kKv * kDim, 1.2f); + float* dkv = up(kv); + Cache cf, c8; + cf.alloc(ctx, false), c8.alloc(ctx, true); + store_f16(dkv, cf.k, kKv * kDim, 0, ctx, nullptr), store_f16(dkv, cf.v, kKv * kDim, 0, ctx, nullptr); + store_q8(dkv, c8.kc, c8.ks, kKv * kDim, 0, ctx, nullptr), store_q8(dkv, c8.vc, c8.vs, kKv * kDim, 0, ctx, nullptr); + float *q = up(randv(size_t(rows) * kHeads * kDim, 1.2f)), *r = up(randv(size_t(rows) * kHeads * kRel, 1.5f)), + *sk = up(randv(size_t(rows) * kHeads, 2.0f, 1.0f)), *o1, *o2, *work; + const size_t n = size_t(rows) * kHeads * kDim, wn = inkling_attend_work_floats(kHeads, kDim); + ck(cudaMalloc(&o1, n * 4), "malloc"), ck(cudaMalloc(&o2, n * 4), "malloc"), ck(cudaMalloc(&work, wn * 4), "malloc"); + const InklingRel rel{r, dtable, kRel, kExtent}; + struct Case { + const char* name; + bool q8; + int window; + long long pos, room; + }; + const Case cases[] = { + {"int8 dot unchanged: q8_0 full, room 16384", true, 0, 12000, 16384}, + {"int8 dot unchanged: q8_0 window (ring)", true, window, ctx - rows, 0}, + {"int8 dot unchanged: fp16 full, room 32768", false, 0, ctx - rows, 32768}, + }; + for (const Case& k : cases) { + const Cache& c = k.q8 ? c8 : cf; + const Kvq8 kq = k.q8 ? Kvq8{c.kc, c.ks} : Kvq8{}, vq = k.q8 ? Kvq8{c.vc, c.vs} : Kvq8{}; + const float sc = 1.f / std::sqrt((float) kDim); + for (int i8 = 0; i8 < 2; ++i8) + inkling_attend(q, c.k, c.v, kq, vq, rel, sk, k.pos, rows, i8 ? o2 : o1, kDim, kHeads, kKv, sc, k.window, + k.window ? ctx : 0, work, wn, nullptr, k.room, i8 != 0); + same_bits(k.name, o1, o2, n); + } + cf.free_(), c8.free_(); + cudaFree(dkv), cudaFree(q), cudaFree(r), cudaFree(sk), cudaFree(o1), cudaFree(o2), cudaFree(work); +} + +// Random blocks of a format, n_in x n_out, on the card: random bytes with sane scales (fp16 d, and dmin where the +// format has one; MXFP4's power of two; IQ1_M's d in the top nibbles of its scales) so that the products stay finite. +void* random_weights(int type, int n_in, int n_out) { + namespace k = strata::kernels; + const bool small = type == 2 || type == 6 || type == 8 || type == 20 || type == 39; + const int sub = small ? 32 : type == 42 ? 64 : 256; // values a block + const size_t blk = k::native_mmvq_weight_bytes(type, sub, 1); + std::uniform_int_distribution byte(0, 255); + std::uniform_real_distribution scale(1e-3f, 1e-2f); + std::vector h(k::native_mmvq_weight_bytes(type, n_in, n_out)); + for (uint8_t& c : h) c = (uint8_t) byte(rng); + for (size_t b = 0; b < h.size() / blk; ++b) { + const __half d = __float2half(scale(rng)); + uint8_t* p = h.data() + b * blk; + if (type == 39) { + p[0] = (uint8_t) (118 + byte(rng) % 5); // 2^-10 to 2^-6 + } else if (type == 29) { + uint16_t bits; + std::memcpy(&bits, &d, 2); + for (int i = 0; i < 4; ++i) { // blk - 8: the four 16-bit scales + uint8_t& hi = p[blk - 8 + 2 * i + 1]; + hi = (uint8_t) ((hi & 0x0f) | (((bits >> (4 * i)) & 0xf) << 4)); + } + } else if (type == 10) { + std::memcpy(p + blk - 4, &d, 2), std::memcpy(p + blk - 2, &d, 2); // d and dmin at the end + } else if (type == 11 || type == 14) { + std::memcpy(p + blk - 2, &d, 2); + } else { + std::memcpy(p, &d, 2); + if (type == 12 || type == 13) std::memcpy(p + 2, &d, 2); + } + } + return up(h); +} + +// n_in values of each of `rows` tokens in Q8_1 on the card +void* random_q8_1(int n_in, int rows, cudaStream_t st) { + namespace k = strata::kernels; + float* x = up(randv(size_t(n_in) * rows, 1.f)); + void* q; + ck(cudaMalloc(&q, k::native_q8_1_bytes(n_in, rows)), "malloc"); + k::native_quantize_q8_1(x, q, n_in, rows, st); + ck(cudaStreamSynchronize(st), "quantize"); + cudaFree(x); + return q; +} + +// A visit's projections of its three inputs in one launch (native_mmvq_jobs(), Engine::lin_jobs()) against each +// alone (native_mmvq()), to the bit: the first `count` of 8 matrices, 1 to 8 tokens. Inkling 2's 2304 values a row +// take a row a block; a row shorter than a block's threads take in one pass (512 values here) takes 2 rows a block, +// the last of them a single row in a matrix of odd rows (37 and 31). +void test_mmvq_jobs(int type, const char* name, int n_in, int count, int rows) { + namespace k = strata::kernels; + const int outs[8] = {3072, 3072, 384, 24, 1024, 37, 1024, 31}; + void* w[8]; + for (int i = 0; i < count; ++i) w[i] = random_weights(type, n_in, outs[i]); + cudaStream_t st; + ck(cudaStreamCreate(&st), "stream"); + void* xq[3]; + for (void*& q : xq) q = random_q8_1(n_in, rows, st); + size_t total = 0; + for (int i = 0; i < count; ++i) total += size_t(outs[i]) * rows; + float *ya, *yb; + ck(cudaMalloc(&ya, total * sizeof(float)), "malloc"); + ck(cudaMalloc(&yb, total * sizeof(float)), "malloc"); + k::MmvqJobs jobs{}; + size_t at = 0; + for (int i = 0; i < count; ++i) { + const void* x = xq[i < 4 ? 0 : i % 2 ? 2 : 1]; + k::native_mmvq(type, w[i], x, ya + at, n_in, outs[i], rows, st); + jobs.w[i] = w[i], jobs.x[i] = x, jobs.y[i] = yb + at, jobs.n_out[i] = outs[i]; + at += size_t(outs[i]) * rows; + } + const bool took = k::native_mmvq_jobs(type, jobs, count, n_in, rows, st); + const std::string what = std::string("mmvq jobs ") + name + " " + std::to_string(n_in) + ", " + + std::to_string(count) + " matrices, " + std::to_string(rows) + " rows"; + if (!took) { + std::printf("%-58s not taken FAIL\n", what.c_str()); + ++failures; + } else { + same_bits(what.c_str(), ya, yb, total); + } + for (int i = 0; i < count; ++i) cudaFree(w[i]); + for (void* p : xq) cudaFree(p); + cudaFree(ya), cudaFree(yb); + cudaStreamDestroy(st); +} + +// A visit's projections of several formats in one launch (native_mmvq_jobs_mixed(), UD-Q2_K_XL's attention) against +// each alone, to the bit. +void test_mmvq_jobs_mixed(int n_in, int count) { + namespace k = strata::kernels; + const int outs[8] = {3072, 3072, 384, 24, 1024, 37, 1024, 31}, types[8] = {14, 12, 8, 13, 8, 14, 13, 12}; + void* w[8]; + for (int i = 0; i < count; ++i) w[i] = random_weights(types[i], n_in, outs[i]); + cudaStream_t st; + ck(cudaStreamCreate(&st), "stream"); + void* xq[3]; + for (void*& q : xq) q = random_q8_1(n_in, 1, st); + size_t total = 0; + for (int i = 0; i < count; ++i) total += size_t(outs[i]); + float *ya, *yb; + ck(cudaMalloc(&ya, total * sizeof(float)), "malloc"); + ck(cudaMalloc(&yb, total * sizeof(float)), "malloc"); + k::MmvqJobs jobs{}; + size_t at = 0; + for (int i = 0; i < count; ++i) { + const void* x = xq[i < 4 ? 0 : i % 2 ? 2 : 1]; + k::native_mmvq(types[i], w[i], x, ya + at, n_in, outs[i], 1, st); + jobs.w[i] = w[i], jobs.x[i] = x, jobs.y[i] = yb + at, jobs.n_out[i] = outs[i]; + at += size_t(outs[i]); + } + const bool took = k::native_mmvq_jobs_mixed(types, jobs, count, n_in, st); + const std::string what = "mmvq jobs mixed " + std::to_string(n_in) + ", " + std::to_string(count) + " matrices"; + if (!took) { + std::printf("%-58s not taken FAIL\n", what.c_str()); + ++failures; + } else { + same_bits(what.c_str(), ya, yb, total); + } + for (int i = 0; i < count; ++i) cudaFree(w[i]); + for (void* p : xq) cudaFree(p); + cudaFree(ya), cudaFree(yb); + cudaStreamDestroy(st); +} + +// The cached experts' launch a warp a row (MmvqSlots::lanes, MmvqIds::lanes) against each matrix alone +// (native_mmvq()) and against the same launch without lanes, to the bit: an expert's gate and up (n_in -> n_out) of +// `count` experts, each its own column. +void test_slots_lanes(int type, const char* name, int n_in, int n_out, int count) { + namespace k = strata::kernels; + cudaStream_t st; + ck(cudaStreamCreate(&st), "stream"); + std::vector w((size_t) count); + for (void*& p : w) p = random_weights(type, n_in, n_out); + void* xq = random_q8_1(n_in, count, st); + const size_t xr = k::native_q8_1_bytes(n_in), total = size_t(n_out) * count; + float *ya, *yb, *yc, *yd; + ck(cudaMalloc(&ya, total * sizeof(float)), "malloc"); + ck(cudaMalloc(&yb, total * sizeof(float)), "malloc"); + ck(cudaMalloc(&yc, total * sizeof(float)), "malloc"); + ck(cudaMalloc(&yd, total * sizeof(float)), "malloc"); + k::MmvqSlots slots{}, plain{}; + slots.lanes = true; + for (int i = 0; i < count; ++i) { + const void* x = (const uint8_t*) xq + i * xr; + k::native_mmvq(type, w[(size_t) i], x, ya + size_t(i) * n_out, n_in, n_out, 1, st); + slots.w[i] = plain.w[i] = w[(size_t) i], slots.x[i] = plain.x[i] = x; + slots.y[i] = yb + size_t(i) * n_out, plain.y[i] = yd + size_t(i) * n_out; + } + // the same through the card's picks: expert i is table[ids[i]], the table backwards + std::vector table(w.rbegin(), w.rend()); + std::vector ids((size_t) count); + for (int i = 0; i < count; ++i) ids[(size_t) i] = count - 1 - i; + void* dtable; + ck(cudaMalloc(&dtable, table.size() * sizeof(void*)), "malloc"); + ck(cudaMemcpy(dtable, table.data(), table.size() * sizeof(void*), cudaMemcpyHostToDevice), "table"); + int32_t* dids = up(ids); + const k::MmvqIds picks{(const void* const*) dtable, dids, 0, xq, xr, 1, yc, size_t(n_out), true}; + const std::string what = std::string("slots lanes ") + name + " " + std::to_string(n_in) + " -> " + + std::to_string(n_out) + " x" + std::to_string(count); + if (!k::native_mmvq_slots(type, slots, count, n_in, n_out, st) || + !k::native_mmvq_ids(type, picks, count, n_in, n_out, st) || + !k::native_mmvq_slots(type, plain, count, n_in, n_out, st)) { + std::printf("%-58s not taken FAIL\n", what.c_str()); + ++failures; + } else { + same_bits(what.c_str(), ya, yb, total); + same_bits((what + ", picks").c_str(), ya, yc, total); + same_bits((what + ", without lanes").c_str(), yd, yb, total); + } + for (void* p : w) cudaFree(p); + cudaFree(xq), cudaFree(dtable), cudaFree(dids); + cudaFree(ya), cudaFree(yb), cudaFree(yc), cudaFree(yd); + cudaStreamDestroy(st); +} + +void test_clip_many(int rows) { + const InklingTau tau{0.1f, 8192}; + auto q = randv(size_t(rows) * 3072, 2.0f), r = randv(size_t(rows) * 384, 2.0f), qs = randv(3072, 0.3f, 1.f), + rs = randv(384, 0.3f, 1.f); + float *dq = up(q), *dr = up(r), *dqs = up(qs), *drs = up(rs), *y1, *y2; + ck(cudaMalloc(&y1, (q.size() + r.size()) * 4), "malloc"), ck(cudaMalloc(&y2, (q.size() + r.size()) * 4), "malloc"); + inkling_clip(dq, 0, dqs, y1, 128, 24, rows, 22.6f, tau, 20000, nullptr); + inkling_clip(dr, 0, drs, y1 + q.size(), 16, 24, rows, 8.f, tau, 20000, nullptr); + InklingClipJob j[2]; + j[0].x = dq, j[0].scale = dqs, j[0].y = y2, j[0].dim = 128, j[0].heads = 24, j[0].threshold = 22.6f, j[0].tau = tau; + j[1].x = dr, j[1].scale = drs, j[1].y = y2 + q.size(), j[1].dim = 16, j[1].heads = 24, j[1].threshold = 8.f, + j[1].tau = tau; + inkling_clip_many(j, 2, rows, 20000, nullptr); + same_bits(("clip_many Q + R vs two inkling_clip, rows " + std::to_string(rows)).c_str(), y1, y2, + q.size() + r.size()); + cudaFree(dq), cudaFree(dr), cudaFree(dqs), cudaFree(drs), cudaFree(y1), cudaFree(y2); +} + +void test_conv_acc(int channels, int rows) { + auto x = randv(size_t(rows) * channels, 1.f), w = randv(size_t(channels) * 4, 0.4f), + st = randv(size_t(channels) * 3, 1.f), acc = randv(size_t(rows) * channels, 1.f); + float *dx = up(x), *dw = up(w), *s1 = up(st), *s2 = up(st), *a1 = up(acc), *a2 = up(acc), *tmp; + ck(cudaMalloc(&tmp, x.size() * 4), "malloc"); + inkling_conv(dx, s1, dw, nullptr, 0, tmp, channels, rows, nullptr); + axpy(tmp, 1.f, a1, rows * channels, true, nullptr); + inkling_conv_acc(dx, s2, dw, nullptr, 0, a2, channels, rows, nullptr); + same_bits(("conv_acc vs conv + axpy, rows " + std::to_string(rows)).c_str(), a1, a2, acc.size()); + same_bits(("conv_acc state, rows " + std::to_string(rows)).c_str(), s1, s2, st.size()); + cudaFree(dx), cudaFree(dw), cudaFree(s1), cudaFree(s2), cudaFree(a1), cudaFree(a2), cudaFree(tmp); +} + +// inkling_kv_store() against the separate calls: its K and V floats against the host's double reference, the +// state to the bit, and its cache rows to the bit against store_f16 / store_q8 of its own floats. +void test_kv_store(int rows, bool q8, bool taps, int ring, long long pos) { + const int kvh = 8, dim = 128, width = kvh * dim, cap = ring ? ring : int(pos) + rows; + auto kraw = randv(size_t(rows) * width, 1.f), vraw = randv(size_t(rows) * width, 1.f), + kw = randv(size_t(width) * 4, 0.4f), vw = randv(size_t(width) * 4, 0.4f), + kt = randv(size_t(rows) * kvh * 4, 0.3f), vt = randv(size_t(rows) * kvh * 4, 0.3f), + st = randv(size_t(width) * 6, 1.f); + for (size_t i = 0; i < kraw.size(); i += 7) kraw[i] *= 8.f; // some heads past the clip + float *dk = up(kraw), *dv = up(vraw), *dkw = up(kw), *dvw = up(vw), *dkt = up(kt), *dvt = up(vt), *dst = up(st); + float *ko, *vo; + ck(cudaMalloc(&ko, kraw.size() * 4), "malloc"), ck(cudaMalloc(&vo, vraw.size() * 4), "malloc"); + Cache c; + c.alloc(cap, q8); + InklingKvDst d; + d.k = c.k, d.v = c.v, d.kc = c.kc, d.ks = c.ks, d.vc = c.vc, d.vs = c.vs, d.ring = ring; + inkling_kv_store(dk, dv, dst, dst + size_t(width) * 3, dkw, dvw, taps ? dkt : nullptr, taps ? dvt : nullptr, kvh, + dim, rows, 22.6f, 1e-6f, d, pos, ko, vo, nullptr); + // the host's reference of the floats and the state + std::vector hst(st.begin(), st.end()), kref(kraw.size()), vref(vraw.size()); + std::vector ks(hst.begin(), hst.begin() + width * 3), vs(hst.begin() + width * 3, hst.end()); + host_conv(kraw, ks, kw, taps ? &kt : nullptr, kvh, kref, width, rows); + host_conv(vraw, vs, vw, taps ? &vt : nullptr, kvh, vref, width, rows); + for (int t = 0; t < rows; ++t) + for (int h = 0; h < kvh; ++h) { + double* kk = kref.data() + (size_t(t) * kvh + h) * dim; + double* vv = vref.data() + (size_t(t) * kvh + h) * dim; + double sk = 0, sv = 0; + for (int i = 0; i < dim; ++i) sk += kk[i] * kk[i], sv += vv[i] * vv[i]; + const double f = std::min(1.0, 22.6 / (std::sqrt(sk) + 1e-6)), r = 1.0 / std::sqrt(sv / dim + 1e-6); + for (int i = 0; i < dim; ++i) kk[i] *= f, vv[i] *= r; + } + const std::string name = std::string("kv_store rows ") + std::to_string(rows) + (q8 ? " q8_0" : " fp16") + + (taps ? " taps" : "") + (ring ? " ring" : ""); + compare((name + ": K").c_str(), down(ko, kraw.size()), kref, 2e-5); + compare((name + ": V").c_str(), down(vo, vraw.size()), vref, 2e-5); + std::vector hst2(ks.begin(), ks.end()); + hst2.insert(hst2.end(), vs.begin(), vs.end()); + compare((name + ": state").c_str(), down(dst, st.size()), hst2, 0.0); + // the cache rows against the stores of its own floats + Cache c2; + c2.alloc(cap, q8); + for (int side = 0; side < 2; ++side) { + const float* x = side ? vo : ko; + for (int done = 0; done < rows;) { + const long long p = pos + done, r = ring ? p % ring : p; + const int m = ring ? int(std::min(rows - done, ring - r)) : rows - done; + if (q8) + store_q8(x + size_t(done) * width, side ? c2.vc : c2.kc, side ? c2.vs : c2.ks, width, r, m, nullptr); + else store_f16(x + size_t(done) * width, side ? c2.v : c2.k, width, r, m, nullptr); + done += m; + } + } + size_t diff = 0, n = 0; + auto cmp = [&](const void* a, const void* b, size_t bytes) { + std::vector x(bytes), y(bytes); + ck(cudaDeviceSynchronize(), "sync"); + cudaMemcpy(x.data(), a, bytes, cudaMemcpyDeviceToHost), cudaMemcpy(y.data(), b, bytes, cudaMemcpyDeviceToHost); + for (size_t i = 0; i < bytes; ++i) diff += x[i] != y[i]; + n += bytes; + }; + const size_t vals = size_t(cap) * width; + if (q8) cmp(c.kc, c2.kc, vals), cmp(c.vc, c2.vc, vals), cmp(c.ks, c2.ks, vals / 16), cmp(c.vs, c2.vs, vals / 16); + else cmp(c.k, c2.k, vals * 2), cmp(c.v, c2.v, vals * 2); + std::printf("%-58s %zu of %zu bytes differ %s\n", (name + ": cache vs store of its floats").c_str(), diff, n, + diff ? "FAIL" : "ok"); + if (diff) ++failures; + c.free_(), c2.free_(); + cudaFree(dk), cudaFree(dv), cudaFree(dkw), cudaFree(dvw), cudaFree(dkt), cudaFree(dvt), cudaFree(dst), cudaFree(ko), + cudaFree(vo); +} + +// ---- a token of each of several sequences (Engine::step()'s rows) ------------------------------------------------- +// +// Each _seqs call against the single-sequence call of each row alone, to the bit: a sequence's token is then the +// same in a batch as alone. The rows' positions are spread over the window's edge, the ring's wrap and the full +// visits' room steps. + +const std::vector kSeqPos = {0, 5, 1023, 1024, 1500, 2047, 2049, 4100, 70}; + +void test_clip_many_seqs(int rows) { + const InklingTau tau{0.1f, 8192}; + auto q = randv(size_t(rows) * 3072, 2.0f), r = randv(size_t(rows) * 384, 2.0f), qs = randv(3072, 0.3f, 1.f), + rs = randv(384, 0.3f, 1.f); + float *dq = up(q), *dr = up(r), *dqs = up(qs), *drs = up(rs), *y1, *y2; + ck(cudaMalloc(&y1, (q.size() + r.size()) * 4), "malloc"), ck(cudaMalloc(&y2, (q.size() + r.size()) * 4), "malloc"); + std::vector pos(rows); + for (int t = 0; t < rows; ++t) pos[t] = kSeqPos[t % kSeqPos.size()] * 7 + t; // past tau's floor too + auto jobs = [&](float* y, size_t t) { + static InklingClipJob j[2]; + j[0] = {}, j[1] = {}; + j[0].x = dq + t * 3072, j[0].scale = dqs, j[0].y = y + t * 3072, j[0].dim = 128, j[0].heads = 24; + j[0].threshold = 22.6f, j[0].tau = tau; + j[1].x = dr + t * 384, j[1].scale = drs, j[1].y = y + q.size() + t * 384, j[1].dim = 16, j[1].heads = 24; + j[1].threshold = 8.f, j[1].tau = tau; + return j; + }; + for (int t = 0; t < rows; ++t) inkling_clip_many(jobs(y1, size_t(t)), 2, 1, pos[t], nullptr); + inkling_clip_many_seqs(jobs(y2, 0), 2, rows, pos.data(), nullptr); + same_bits(("clip_many_seqs vs a row at a time, rows " + std::to_string(rows)).c_str(), y1, y2, + q.size() + r.size()); + cudaFree(dq), cudaFree(dr), cudaFree(dqs), cudaFree(drs), cudaFree(y1), cudaFree(y2); +} + +void test_conv_seqs(bool acc, int rows) { + const int channels = 2304; + auto x = randv(size_t(rows) * channels, 1.f), w = randv(size_t(channels) * 4, 0.4f), + st = randv(size_t(rows) * channels * 3, 1.f), o = randv(size_t(rows) * channels, 1.f); + float *dx = up(x), *dw = up(w), *s1 = up(st), *s2 = up(st), *o1 = up(o), *o2 = up(o); + std::vector states(rows); + for (int t = 0; t < rows; ++t) { + const size_t xo = size_t(t) * channels, so = size_t(t) * channels * 3; + if (acc) inkling_conv_acc(dx + xo, s1 + so, dw, nullptr, 0, o1 + xo, channels, 1, nullptr); + else inkling_conv(dx + xo, s1 + so, dw, nullptr, 0, o1 + xo, channels, 1, nullptr); + states[t] = s2 + so; + } + if (acc) inkling_conv_acc_seqs(dx, states.data(), dw, o2, channels, rows, nullptr); + else inkling_conv_seqs(dx, states.data(), dw, o2, channels, rows, nullptr); + const std::string name = std::string(acc ? "conv_acc_seqs" : "conv_seqs") + " vs a row at a time, rows " + + std::to_string(rows); + same_bits((name + ": out").c_str(), o1, o2, o.size()); + same_bits((name + ": state").c_str(), s1, s2, st.size()); + cudaFree(dx), cudaFree(dw), cudaFree(s1), cudaFree(s2), cudaFree(o1), cudaFree(o2); +} + +// the bytes of two device buffers +size_t bytes_differ(const void* a, const void* b, size_t bytes) { + std::vector x(bytes), y(bytes); + ck(cudaDeviceSynchronize(), "sync"); + ck(cudaMemcpy(x.data(), a, bytes, cudaMemcpyDeviceToHost), "download"); + ck(cudaMemcpy(y.data(), b, bytes, cudaMemcpyDeviceToHost), "download"); + size_t diff = 0; + for (size_t i = 0; i < bytes; ++i) diff += x[i] != y[i]; + return diff; +} + +// A window's snapshots (Engine::window()): each against the state inkling_conv() leaves after that many tokens. +// Bits at or past rows, and past the kernel's 32 tokens, leave no snapshot: the places after the last stay as set. +void test_conv_snaps(int rows, unsigned bits) { + const int channels = 1024, places = 33; + const size_t sn = size_t(channels) * 3, stride = sn + 64; // a snapshot's place, apart as in the engine + auto x = randv(size_t(rows) * channels, 1.f), w = randv(size_t(channels) * 4, 0.4f), st = randv(sn, 1.f); + float *dx = up(x), *dw = up(w), *ds = up(st), *snap, *o; + ck(cudaMalloc(&snap, places * stride * 4), "malloc"), ck(cudaMalloc(&o, x.size() * 4), "malloc"); + ck(cudaMemset(snap, 0xff, places * stride * 4), "memset"); + inkling_conv_snaps(dx, ds, channels, rows, bits, snap, stride, nullptr); + const std::string name = "conv_snaps rows " + std::to_string(rows); + int k = 0; + for (int t = 0; t < rows && t < 32; ++t) { + if (!(bits >> t & 1u)) continue; + float* s1 = up(st); + inkling_conv(dx, s1, dw, nullptr, 0, o, channels, t + 1, nullptr); + same_bits((name + " after token " + std::to_string(t)).c_str(), s1, snap + size_t(k++) * stride, sn); + cudaFree(s1); + } + const size_t rest = (places - k) * stride * 4; + std::vector unset(rest, 0xff); + uint8_t* du = up(unset); + const size_t diff = bytes_differ(du, snap + size_t(k) * stride, rest); + std::printf("%-58s %zu bytes written %s\n", (name + " past its " + std::to_string(k) + " snapshots").c_str(), + diff, diff ? "FAIL" : "ok"); + if (diff) ++failures; + cudaFree(du), cudaFree(dx), cudaFree(dw), cudaFree(ds), cudaFree(snap), cudaFree(o); +} + +size_t caches_differ(const Cache& a, const Cache& b) { + const size_t vals = size_t(a.rows_cap) * kKv * kDim; + if (a.q8) + return bytes_differ(a.kc, b.kc, vals) + bytes_differ(a.vc, b.vc, vals) + bytes_differ(a.ks, b.ks, vals / 16) + + bytes_differ(a.vs, b.vs, vals / 16); + return bytes_differ(a.k, b.k, vals * 2) + bytes_differ(a.v, b.v, vals * 2); +} + +void test_kv_store_seqs(int rows, bool q8, bool taps, int ring) { + const int width = kKv * kDim; + auto kraw = randv(size_t(rows) * width, 1.f), vraw = randv(size_t(rows) * width, 1.f), + kw = randv(size_t(width) * 4, 0.4f), vw = randv(size_t(width) * 4, 0.4f), + kt = randv(size_t(rows) * kKv * 4, 0.3f), vt = randv(size_t(rows) * kKv * 4, 0.3f), + st = randv(size_t(rows) * width * 6, 1.f); + for (size_t i = 0; i < kraw.size(); i += 7) kraw[i] *= 8.f; + float *dk = up(kraw), *dv = up(vraw), *dkw = up(kw), *dvw = up(vw), *dkt = up(kt), *dvt = up(vt); + float *s1 = up(st), *s2 = up(st), *ko1, *vo1, *ko2, *vo2; + for (float** p : {&ko1, &vo1, &ko2, &vo2}) ck(cudaMalloc(p, kraw.size() * 4), "malloc"); + std::vector c1(rows), c2(rows); + std::vector seqs(rows); + for (int t = 0; t < rows; ++t) { + const long long pos = kSeqPos[t % kSeqPos.size()]; + const int cap = ring ? ring : int(pos) + 1; + c1[t].alloc(cap, q8), c2[t].alloc(cap, q8); + InklingKvDst d1, d2; + d1.k = c1[t].k, d1.v = c1[t].v, d1.kc = c1[t].kc, d1.ks = c1[t].ks, d1.vc = c1[t].vc, d1.vs = c1[t].vs; + d2.k = c2[t].k, d2.v = c2[t].v, d2.kc = c2[t].kc, d2.ks = c2[t].ks, d2.vc = c2[t].vc, d2.vs = c2[t].vs; + d1.ring = d2.ring = ring; + const size_t xo = size_t(t) * width, so = size_t(t) * width * 6, to = size_t(t) * kKv * 4; + inkling_kv_store(dk + xo, dv + xo, s1 + so, s1 + so + width * 3, dkw, dvw, taps ? dkt + to : nullptr, + taps ? dvt + to : nullptr, kKv, kDim, 1, 22.6f, 1e-6f, d1, pos, ko1 + xo, vo1 + xo, nullptr); + seqs[t].dst = d2, seqs[t].k_state = s2 + so, seqs[t].v_state = s2 + so + width * 3, seqs[t].pos = pos; + } + inkling_kv_store_seqs(dk, dv, seqs.data(), dkw, dvw, taps ? dkt : nullptr, taps ? dvt : nullptr, kKv, kDim, rows, + 22.6f, 1e-6f, ko2, vo2, nullptr); + const std::string name = std::string("kv_store_seqs vs a row at a time, rows ") + std::to_string(rows) + + (q8 ? " q8_0" : " fp16") + (taps ? " taps" : "") + (ring ? " ring" : ""); + same_bits((name + ": K").c_str(), ko1, ko2, kraw.size()); + same_bits((name + ": V").c_str(), vo1, vo2, vraw.size()); + same_bits((name + ": state").c_str(), s1, s2, st.size()); + size_t diff = 0; + for (int t = 0; t < rows; ++t) diff += caches_differ(c1[t], c2[t]); + std::printf("%-58s %zu bytes differ %s\n", (name + ": caches").c_str(), diff, diff ? "FAIL" : "ok"); + if (diff) ++failures; + for (int t = 0; t < rows; ++t) c1[t].free_(), c2[t].free_(); + for (float* p : {dk, dv, dkw, dvw, dkt, dvt, s1, s2, ko1, vo1, ko2, vo2}) cudaFree(p); +} + +// Each row its own cache of pos + 1 rows; full rows sized as Engine::room(1) sizes them, window rows for the +// context, as Inkling::attn() does. `alone`: rows before position 32 get no room (pos + 1, one split), so that a +// call has rows of one split beside rows of several. +void test_attend_seqs(int rows, bool q8, int window, const std::vector& table, float* dtable, + const std::vector& at = kSeqPos, long long context = 8192, bool alone = false, + bool int8_dot = false) { + const int ring = window ? window + 1024 : 0; + std::vector c(rows); + std::vector seqs(rows); + for (int t = 0; t < rows; ++t) { + const long long pos = at[t % at.size()]; + c[t].alloc(ring ? ring : int(pos) + 1, q8); + auto k = randv(size_t(pos + 1) * kKv * kDim, 1.2f), v = randv(size_t(pos + 1) * kKv * kDim, 1.0f); + float *dk = up(k), *dv = up(v); + c[t].store(dk, dv, 0, int(pos) + 1, ring); + cudaFree(dk), cudaFree(dv); + InklingAttnSeq& s = seqs[t]; + s.kcache = c[t].k, s.vcache = c[t].v; + if (q8) s.kq8 = {c[t].kc, c[t].ks}, s.vq8 = {c[t].vc, c[t].vs}; + s.pos = pos; + long long room = 1024; + while (room < pos + 1) room *= 2; + s.room = alone && pos < 32 ? 0 : window ? context : std::min(room, context); + } + auto q = randv(size_t(rows) * kHeads * kDim, 1.2f), r = randv(size_t(rows) * kHeads * kRel, 1.5f), + sk = randv(size_t(rows) * kHeads, 2.0f, 1.0f); + float *dq = up(q), *dr = up(r), *ds = up(sk), *o1, *o2, *work; + ck(cudaMalloc(&o1, q.size() * 4), "malloc"), ck(cudaMalloc(&o2, q.size() * 4), "malloc"); + const size_t wn = inkling_attend_work_floats(kHeads, kDim); + ck(cudaMalloc(&work, wn * 4), "malloc"); + const float scale = 1.f / std::sqrt((float) kDim); + for (int t = 0; t < rows; ++t) { + const InklingAttnSeq& s = seqs[t]; + inkling_attend(dq + size_t(t) * kHeads * kDim, s.kcache, s.vcache, s.kq8, s.vq8, + {dr + size_t(t) * kHeads * kRel, dtable, kRel, kExtent}, ds + size_t(t) * kHeads, s.pos, 1, + o1 + size_t(t) * kHeads * kDim, kDim, kHeads, kKv, scale, window, ring, work, wn, nullptr, + s.room, int8_dot); + } + inkling_attend_seqs(dq, seqs.data(), rows, {dr, dtable, kRel, kExtent}, ds, o2, kDim, kHeads, kKv, scale, window, + ring, work, wn, nullptr, int8_dot); + const std::string name = std::string("attend_seqs vs a row at a time, rows ") + std::to_string(rows) + + (q8 ? " q8_0" : " fp16") + (window ? " window" : " full") + + (alone ? ", 1 split and more" : "") + (context > 8192 ? ", 128K" : "") + + (int8_dot ? ", int8 dot" : ""); + same_bits(name.c_str(), o1, o2, q.size()); + for (Cache& x : c) x.free_(); + cudaFree(dq), cudaFree(dr), cudaFree(ds), cudaFree(o1), cudaFree(o2), cudaFree(work); +} + +// ---- the position on the card (Engine::at_) ------------------------------------------------------------------------ +// +// A visit's launches that take the position, for a call of `rows` tokens as Inkling::attn() makes them +// (inkling_kv_store(), inkling_clip_many(), inkling_attend()): a decode token's, or a window's of the known token and +// its guesses. Recorded once in a CUDA graph that reads the first position from the card and replayed call after +// call with the position written there first (Engine::run()), against the same calls given the position by value, to +// the bit: K and V, the caches, the convolutions' state, Q and R after their clips (and tau) and the attention's +// output. A recording a room: a full visit's in Engine::room(rows)'s steps, recorded again when the rows outgrow it, +// a window visit's the context's. `calls` calls go across a room's step, the window's edge or the ring's wrap; a +// window's call starts where the one before kept its tokens, 1 to rows of them in turn, as keep() leaves pos(). +void test_at(bool q8, int window, bool taps, long long first, int calls, long long context, bool int8_dot = false, + int rows = 1) { + const int width = kKv * kDim, hq = kHeads * kDim, hr = kHeads * kRel; + const int ring = window ? window + 16 : 0, cap = ring ? ring : int(context); + Cache c[2]; + { // the rows before the first token, the same in both + auto k = randv(size_t(first) * width, 1.2f), v = randv(size_t(first) * width, 1.0f); + float *dk = up(k), *dv = up(v); + for (Cache& x : c) x.alloc(cap, q8), x.store(dk, dv, 0, int(first), ring); + cudaFree(dk), cudaFree(dv); + } + auto kw = randv(size_t(width) * 4, 0.4f), vw = randv(size_t(width) * 4, 0.4f), st0 = randv(size_t(width) * 6, 1.f), + qs = randv(hq, 0.3f, 1.f), rs = randv(hr, 0.3f, 1.f); + float *dkw = up(kw), *dvw = up(vw), *dqs = up(qs), *drs = up(rs); + const size_t wn = inkling_attend_work_floats(kHeads, kDim); + float *state[2], *ko[2], *vo[2], *yq[2], *yr[2], *out[2], *work[2]; + for (int i = 0; i < 2; ++i) { + state[i] = up(st0); + for (auto [p, n] : {std::pair{&ko[i], width}, {&vo[i], width}, {&yq[i], hq}, {&yr[i], hr}, {&out[i], hq}}) + ck(cudaMalloc(p, size_t(n) * rows * 4), "malloc"); + ck(cudaMalloc(&work[i], wn * 4), "malloc"); + } + float *dk, *dv, *dkt, *dvt, *dq, *dr, *dsk; + for (auto [p, n] : {std::pair{&dk, width}, {&dv, width}, {&dkt, kKv * 4}, {&dvt, kKv * 4}, {&dq, hq}, {&dr, hr}, + {&dsk, kHeads}}) + ck(cudaMalloc(p, size_t(n) * rows * 4), "malloc"); + long long* dat; + ck(cudaMalloc(&dat, sizeof(long long)), "malloc"); + float* dtable = up(randv(size_t(kExtent) * kRel, 0.3f)); + cudaStream_t st; + ck(cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking), "stream"); + const float scale = 1.f / std::sqrt((float) kDim); + // the launches of side i (0: the position by value, 1: from the card, `pos` unused) + const auto visit = [&](int i, long long pos, long long room) { + const long long* at = i ? dat : nullptr; + InklingKvDst d; + d.k = c[i].k, d.v = c[i].v, d.kc = c[i].kc, d.ks = c[i].ks, d.vc = c[i].vc, d.vs = c[i].vs, d.ring = ring; + inkling_kv_store(dk, dv, state[i], state[i] + size_t(width) * 3, dkw, dvw, taps ? dkt : nullptr, + taps ? dvt : nullptr, kKv, kDim, rows, 22.6f, 1e-6f, d, pos, ko[i], vo[i], st, at); + const InklingTau tau = window ? InklingTau{} : InklingTau{0.1f, 8192}; + InklingClipJob j[2]; + j[0] = {dq, 0, dqs, yq[i], kDim, kHeads, 22.6f, tau}; + j[1] = {dr, 0, drs, yr[i], kRel, kHeads, 8.f, tau}; + inkling_clip_many(j, 2, rows, pos, st, at); + const Kvq8 kq = q8 ? Kvq8{c[i].kc, c[i].ks} : Kvq8{}, vq = q8 ? Kvq8{c[i].vc, c[i].vs} : Kvq8{}; + inkling_attend(yq[i], c[i].k, c[i].v, kq, vq, {yr[i], dtable, kRel, window ? window : kExtent}, dsk, pos, rows, + out[i], kDim, kHeads, kKv, scale, window, ring, work[i], wn, st, room, int8_dot, at); + }; + std::vector> graphs; // by room + size_t diff = 0; + long long pos = first; + for (int call = 0; call < calls; pos += 1 + call++ % rows) { + // the call's inputs, on the stream the launches go on + const size_t n = size_t(rows); + const std::pair> in[] = { + {dk, randv(n * width, 1.f)}, {dv, randv(n * width, 1.f)}, {dkt, randv(n * kKv * 4, 0.3f)}, + {dvt, randv(n * kKv * 4, 0.3f)}, {dq, randv(n * hq, 2.f)}, {dr, randv(n * hr, 2.f)}, + {dsk, randv(n * kHeads, 2.f, 1.f)}}; + for (const auto& [d, h] : in) + ck(cudaMemcpyAsync(d, h.data(), h.size() * 4, cudaMemcpyHostToDevice, st), "upload"); + long long room = 1024; + while (room < pos + rows) room *= 2; + room = window ? context : std::min(room, context); + visit(0, pos, room); + auto g = std::find_if(graphs.begin(), graphs.end(), [&](const auto& x) { return x.first == room; }); + if (g == graphs.end()) { + cudaGraph_t made; + ck(cudaStreamBeginCapture(st, cudaStreamCaptureModeThreadLocal), "capture"); + visit(1, 0, room); + ck(cudaStreamEndCapture(st, &made), "capture"); + cudaGraphExec_t exec; + ck(cudaGraphInstantiateWithFlags(&exec, made, 0), "instantiate"); + cudaGraphDestroy(made); + g = graphs.insert(graphs.end(), {room, exec}); + } + ck(cudaMemcpyAsync(dat, &pos, sizeof(long long), cudaMemcpyHostToDevice, st), "position"); + ck(cudaGraphLaunch(g->second, st), "replay"); + ck(cudaStreamSynchronize(st), "replay"); + const size_t b = size_t(rows) * 4; + diff += bytes_differ(ko[0], ko[1], width * b) + bytes_differ(vo[0], vo[1], width * b) + + bytes_differ(state[0], state[1], size_t(width) * 24) + bytes_differ(yq[0], yq[1], hq * b) + + bytes_differ(yr[0], yr[1], hr * b) + bytes_differ(out[0], out[1], hq * b) + caches_differ(c[0], c[1]); + } + char name[160]; + const char *kind = q8 ? "q8_0" : "fp16", *visit_kind = window ? "window" : "full", *tap = taps ? " taps" : ""; + if (rows == 1) + std::snprintf(name, sizeof name, "at vs pos, %s %s%s%s, %d tokens from %lld, %zu recordings", kind, visit_kind, + tap, int8_dot ? " int8 dot" : "", calls, first, graphs.size()); + else + std::snprintf(name, sizeof name, "at vs pos, %s %s%s%s, %d calls of %d from %lld, %zu rec.", kind, visit_kind, + tap, int8_dot ? " int8" : "", calls, rows, first, graphs.size()); + std::printf("%-58s %zu bytes differ %s\n", name, diff, diff ? "FAIL" : "ok"); + if (diff) ++failures; + for (auto& g : graphs) cudaGraphExecDestroy(g.second); + cudaStreamDestroy(st); + for (Cache& x : c) x.free_(); + for (float* p : {dkw, dvw, dqs, drs, dk, dv, dkt, dvt, dq, dr, dsk, dtable}) cudaFree(p); + for (int i = 0; i < 2; ++i) + for (float* p : {state[i], ko[i], vo[i], yq[i], yr[i], out[i], work[i]}) cudaFree(p); + cudaFree(dat); +} + +// ---- a token's fused launches (Inkling::fused()) against the calls they stand for, to the bit ----------------- + +// K and V's store with the clips (inkling_kv_store_clip()) and the attention with its gate (inkling_attend()'s gate) +// against inkling_kv_store(), inkling_clip_many(), inkling_attend() and mul_sigmoid(): the fused side recorded in a +// CUDA graph that reads the position from the card, as a decode token's whole-token graph has them. +void test_fused_attn(bool q8, int window, bool taps, long long first, int tokens, long long context, + bool int8_dot = false) { + const int width = kKv * kDim, hq = kHeads * kDim, hr = kHeads * kRel; + const int ring = window ? window + 16 : 0, cap = ring ? ring : int(context); + Cache c[2]; + { + auto k = randv(size_t(first) * width, 1.2f), v = randv(size_t(first) * width, 1.0f); + float *dk = up(k), *dv = up(v); + for (Cache& x : c) x.alloc(cap, q8), x.store(dk, dv, 0, int(first), ring); + cudaFree(dk), cudaFree(dv); + } + auto kw = randv(size_t(width) * 4, 0.4f), vw = randv(size_t(width) * 4, 0.4f), st0 = randv(size_t(width) * 6, 1.f), + qs = randv(hq, 0.3f, 1.f), rs = randv(hr, 0.3f, 1.f); + float *dkw = up(kw), *dvw = up(vw), *dqs = up(qs), *drs = up(rs); + const size_t wn = inkling_attend_work_floats(kHeads, kDim); + float *state[2], *ko[2], *vo[2], *yq[2], *yr[2], *out[2], *work[2]; + void* oq[2]; + const size_t oqb = strata::kernels::native_q8_1_bytes(hq); + for (int i = 0; i < 2; ++i) { + state[i] = up(st0); + for (auto [p, n] : {std::pair{&ko[i], width}, {&vo[i], width}, {&yq[i], hq}, {&yr[i], hr}, {&out[i], hq}}) + ck(cudaMalloc(p, size_t(n) * 4), "malloc"); + ck(cudaMalloc(&work[i], wn * 4), "malloc"); + ck(cudaMalloc(&oq[i], oqb), "malloc"); + } + float *dk, *dv, *dkt, *dvt, *dq, *dr, *dsk, *dg; + for (auto [p, n] : {std::pair{&dk, width}, {&dv, width}, {&dkt, kKv * 4}, {&dvt, kKv * 4}, {&dq, hq}, {&dr, hr}, + {&dsk, kHeads}, {&dg, hq}}) + ck(cudaMalloc(p, size_t(n) * 4), "malloc"); + long long* dat; + ck(cudaMalloc(&dat, sizeof(long long)), "malloc"); + float* dtable = up(randv(size_t(kExtent) * kRel, 0.3f)); + cudaStream_t st; + ck(cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking), "stream"); + const float scale = 1.f / std::sqrt((float) kDim); + // side 0: the calls one by one, the position by value; side 1: fused, from the card + const auto visit = [&](int i, long long pos, long long room) { + const long long* at = i ? dat : nullptr; + InklingKvDst d; + d.k = c[i].k, d.v = c[i].v, d.kc = c[i].kc, d.ks = c[i].ks, d.vc = c[i].vc, d.vs = c[i].vs, d.ring = ring; + const InklingTau tau = window ? InklingTau{} : InklingTau{0.1f, 8192}; + InklingClipJob j[2]; + j[0] = {dq, 0, dqs, yq[i], kDim, kHeads, 22.6f, tau}; + j[1] = {dr, 0, drs, yr[i], kRel, kHeads, 8.f, tau}; + if (i) { + inkling_kv_store_clip(dk, dv, state[i], state[i] + size_t(width) * 3, dkw, dvw, taps ? dkt : nullptr, + taps ? dvt : nullptr, kKv, kDim, 1, 22.6f, 1e-6f, d, pos, ko[i], vo[i], j, 2, st, at); + } else { + inkling_kv_store(dk, dv, state[i], state[i] + size_t(width) * 3, dkw, dvw, taps ? dkt : nullptr, + taps ? dvt : nullptr, kKv, kDim, 1, 22.6f, 1e-6f, d, pos, ko[i], vo[i], st, at); + inkling_clip_many(j, 2, 1, pos, st, at); + } + const Kvq8 kq = q8 ? Kvq8{c[i].kc, c[i].ks} : Kvq8{}, vq = q8 ? Kvq8{c[i].vc, c[i].vs} : Kvq8{}; + inkling_attend(yq[i], c[i].k, c[i].v, kq, vq, {yr[i], dtable, kRel, window ? window : kExtent}, dsk, pos, 1, + out[i], kDim, kHeads, kKv, scale, window, ring, work[i], wn, st, room, int8_dot, at, + i ? dg : nullptr, i ? oq[i] : nullptr); + if (!i) { + mul_sigmoid(out[i], dg, hq, 1, hq, false, st); + strata::kernels::native_quantize_q8_1(out[i], oq[i], hq, 1, st); + } + }; + std::vector> graphs; // by room + size_t diff = 0; + for (long long pos = first; pos < first + tokens; ++pos) { + const std::pair> in[] = { + {dk, randv(width, 1.f)}, {dv, randv(width, 1.f)}, {dkt, randv(kKv * 4, 0.3f)}, + {dvt, randv(kKv * 4, 0.3f)}, {dq, randv(hq, 2.f)}, {dr, randv(hr, 2.f)}, + {dsk, randv(kHeads, 2.f, 1.f)}, {dg, randv(hq, 2.f)}}; + for (const auto& [d, h] : in) + ck(cudaMemcpyAsync(d, h.data(), h.size() * 4, cudaMemcpyHostToDevice, st), "upload"); + long long room = 1024; + while (room < pos + 1) room *= 2; + room = window ? context : std::min(room, context); + visit(0, pos, room); + auto g = std::find_if(graphs.begin(), graphs.end(), [&](const auto& x) { return x.first == room; }); + if (g == graphs.end()) { + cudaGraph_t made; + ck(cudaStreamBeginCapture(st, cudaStreamCaptureModeThreadLocal), "capture"); + visit(1, 0, room); + ck(cudaStreamEndCapture(st, &made), "capture"); + cudaGraphExec_t exec; + ck(cudaGraphInstantiateWithFlags(&exec, made, 0), "instantiate"); + cudaGraphDestroy(made); + g = graphs.insert(graphs.end(), {room, exec}); + } + ck(cudaMemcpyAsync(dat, &pos, sizeof(long long), cudaMemcpyHostToDevice, st), "position"); + ck(cudaGraphLaunch(g->second, st), "replay"); + ck(cudaStreamSynchronize(st), "replay"); + diff += bytes_differ(ko[0], ko[1], size_t(width) * 4) + bytes_differ(vo[0], vo[1], size_t(width) * 4) + + bytes_differ(state[0], state[1], size_t(width) * 24) + bytes_differ(yq[0], yq[1], size_t(hq) * 4) + + bytes_differ(yr[0], yr[1], size_t(hr) * 4) + bytes_differ(out[0], out[1], size_t(hq) * 4) + + bytes_differ(oq[0], oq[1], oqb) + caches_differ(c[0], c[1]); + } + char name[160]; + std::snprintf(name, sizeof name, "fused vs calls, %s %s%s%s, %d tokens from %lld", q8 ? "q8_0" : "fp16", + window ? "window" : "full", taps ? " taps" : "", int8_dot ? " int8" : "", tokens, first); + std::printf("%-58s %zu bytes differ %s\n", name, diff, diff ? "FAIL" : "ok"); + if (diff) ++failures; + for (auto& g : graphs) cudaGraphExecDestroy(g.second); + cudaStreamDestroy(st); + for (Cache& x : c) x.free_(); + for (float* p : {dkw, dvw, dqs, drs, dk, dv, dkt, dvt, dq, dr, dsk, dg, dtable}) cudaFree(p); + for (int i = 0; i < 2; ++i) + for (float* p : {state[i], ko[i], vo[i], yq[i], yr[i], out[i], work[i]}) cudaFree(p); + for (void* p : oq) cudaFree(p); + cudaFree(dat); +} + +// The gate on the paths that do not split (no work; a prompt's rows) is mul_sigmoid() after them: the same bits. +void test_gate_unsplit(int rows) { + const cudaStream_t st = test_stream(); + const int width = kKv * kDim, hq = kHeads * kDim; + Cache c; + c.alloc(rows + 40, false); + float *dk = up(randv(size_t(rows + 40) * width, 1.2f)), *dv = up(randv(size_t(rows + 40) * width, 1.f)); + c.store(dk, dv, 0, rows + 40, 0); + float *dq = up(randv(size_t(rows) * hq, 1.2f)), *dr = up(randv(size_t(rows) * kHeads * kRel, 1.5f)), + *ds = up(randv(size_t(rows) * kHeads, 2.f, 1.f)), *dg = up(randv(size_t(rows) * hq, 2.f)); + float* dtable = up(randv(size_t(kExtent) * kRel, 0.3f)); + float *o0, *o1; + ck(cudaMalloc(&o0, size_t(rows) * hq * 4), "malloc"), ck(cudaMalloc(&o1, size_t(rows) * hq * 4), "malloc"); + const InklingRel rel{dr, dtable, kRel, kExtent}; + const float scale = 1.f / std::sqrt((float) kDim); + inkling_attend(dq, c.k, c.v, {}, {}, rel, ds, 40, rows, o0, kDim, kHeads, kKv, scale, 0, 0, nullptr, 0, st); + mul_sigmoid(o0, dg, hq, rows, hq, false, st); + const size_t qb = strata::kernels::native_q8_1_bytes(hq) * rows; + void *q0, *q1; + ck(cudaMalloc(&q0, qb), "malloc"), ck(cudaMalloc(&q1, qb), "malloc"); + strata::kernels::native_quantize_q8_1(o0, q0, hq * rows, 1, st); + inkling_attend(dq, c.k, c.v, {}, {}, rel, ds, 40, rows, o1, kDim, kHeads, kKv, scale, 0, 0, nullptr, 0, st, 0, + false, nullptr, dg, q1); + same_bits(("attend's gate unsplit, rows " + std::to_string(rows)).c_str(), o0, o1, size_t(rows) * hq); + const size_t qd = bytes_differ(q0, q1, qb); + std::printf("%-58s %zu bytes differ %s\n", ("attend's Q8_1 unsplit, rows " + std::to_string(rows)).c_str(), qd, + qd ? "FAIL" : "ok"); + if (qd) ++failures; + cudaFree(q0), cudaFree(q1); + c.free_(); + for (float* p : {dk, dv, dq, dr, ds, dg, dtable, o0, o1}) cudaFree(p); +} + +// A visit's three input norms in one launch (native_rms_norm_q8_1_rows()) against a call each. +void test_norm_rows(int count) { + const cudaStream_t st = test_stream(); + namespace k = strata::kernels; + const int n = 2304, threads = sum_threads(n); + const size_t qb = k::native_q8_1_bytes(n); + k::NormRows rows{}; + float *y0[4], *x[4]; + void* q0[4]; + for (int j = 0; j < count; ++j) { + auto h = randv(n, 1.f + j); + for (int i = j; i < n; i += 97) h[i] *= 40.f; // a few large values, as the model's streams have + x[j] = up(h); + rows.x[j] = x[j]; + rows.w[j] = up(randv(n, 0.2f, 1.f)); + ck(cudaMalloc(&rows.y[j], n * 4), "malloc"), ck(cudaMalloc(&y0[j], n * 4), "malloc"); + ck(cudaMalloc(&rows.y_q8_1[j], qb), "malloc"), ck(cudaMalloc(&q0[j], qb), "malloc"); + k::native_add_rms_norm_q8_1(x[j], nullptr, rows.w[j], y0[j], q0[j], n, 1, 1e-6f, threads, st); + } + const bool ran = k::native_rms_norm_q8_1_rows(rows, count, n, 1e-6f, threads, st); + size_t diff = ran ? 0 : 1; + for (int j = 0; j < count && ran; ++j) + diff += bytes_differ(y0[j], rows.y[j], size_t(n) * 4) + bytes_differ(q0[j], rows.y_q8_1[j], qb); + std::printf("%-58s %zu bytes differ %s\n", ("norm rows " + std::to_string(count)).c_str(), diff, + diff ? "FAIL" : "ok"); + if (diff) ++failures; + for (int j = 0; j < count; ++j) + cudaFree(x[j]), cudaFree((void*) rows.w[j]), cudaFree(rows.y[j]), cudaFree(y0[j]), cudaFree(rows.y_q8_1[j]), + cudaFree(q0[j]); +} + +// One token's mixes with a post-convolution before them (inkling_mix_conv(), inkling_conv_in()) against +// moe_sum() into a zeroed buffer, the copy, inkling_conv() / inkling_conv_acc() and inkling_mix() of each; and the +// launch with its work spread over many blocks against the one block a mix, and the spread launch recorded in a graph +// as the engine's whole-token graph records it. Each runs `reps` tokens in a row (the convolution's state and the +// stream carried on, the spread launches' meeting place reused). +// nb: the blocks before the stream in the first mix; the stream (acc) is its last state. +struct MixConvCase { + const char* name; + int nb, nq; // the first mix's blocks and queries + bool msg; // a second mix (a later pass's messages: 2 states, 4 queries) + int conv; // 0: none, 1: x, 2: parts (8 experts) + bool fresh; // written, with the stream's old value saved into block save_k + int save_k; + bool alone; // inkling_conv_in() only, no mix + bool norm = false; // the first mix's outputs normed in the launch (native_add_rms_norm_q8_1()) + int n = 2304; + int reps = 3; +}; +void* mix_work = nullptr; // inkling_mix_conv()'s meeting place, shared by every case as an engine's is +void test_mix_conv(const MixConvCase& tc) { + const cudaStream_t st = test_stream(); + const int n = tc.n, parts = 8; + if (!mix_work) { + ck(cudaMalloc(&mix_work, inkling_mix_conv_work_bytes()), "malloc"); + ck(cudaMemset(mix_work, 0, inkling_mix_conv_work_bytes()), "memset"); + } + std::vector> hs; // the first mix's states (the stream last), then the second's + for (int k = 0; k <= tc.nb; ++k) hs.push_back(randv(n, 0.5f + k, 0.1f * k)); + for (int k = 0; k < 2; ++k) hs.push_back(randv(n, 1.f + k)); + const auto q1 = randv(size_t(tc.nq) * n, 1.f), q2 = randv(size_t(4) * n, 1.f), hx = randv(n, 1.f), + hp = randv(size_t(parts) * n, 1.f), hw = randv(parts, 0.3f, 0.2f), hst = randv(size_t(n) * 3, 1.f), + hcw = randv(size_t(n) * 4, 0.4f); + float *dq1 = up(q1), *dq2 = up(q2), *dx = up(hx), *dp = up(hp), *dw = up(hw), *dcw = up(hcw); + namespace kk = strata::kernels; + const size_t qb = tc.norm ? kk::native_q8_1_bytes(n) : 36; // native_q8_1_bytes() takes multiples of 256 + const int threads = sum_threads(n); + std::vector nw; + for (int j = 0; j < tc.nq; ++j) { + auto h = randv(n, 0.2f, 1.f); + if (j == 1) std::fill(h.begin(), h.begin() + 64, 1e-39f); // denormal products: a block flushed to zero + nw.push_back(up(h)); + } + struct Side { + std::vector s; + float *state, *fo, *out[8], *ny[4]; + void* nq[4]; + } side[4]; // the calls, the one-block launch, the spread one, the spread one recorded + for (Side& d : side) { + for (const auto& h : hs) d.s.push_back(up(h)); + d.state = up(hst); + ck(cudaMalloc(&d.fo, n * 4), "malloc"); + for (float*& o : d.out) ck(cudaMalloc(&o, n * 4), "malloc"); + for (int j = 0; j < 4; ++j) ck(cudaMalloc(&d.ny[j], n * 4), "malloc"), ck(cudaMalloc(&d.nq[j], qb), "malloc"); + } + const auto mixes = [&](Side& d, InklingMix* m) { + m[0] = InklingMix{}; + for (int k = 0; k <= tc.nb; ++k) m[0].state[k] = d.s[k]; + m[0].n_state = tc.nb + 1, m[0].query = dq1, m[0].n_query = tc.nq; + for (int j = 0; j < tc.nq; ++j) m[0].out[j] = d.out[j]; + m[1] = InklingMix{}; + m[1].state[0] = d.s[tc.nb + 1], m[1].state[1] = d.s[tc.nb + 2]; + m[1].n_state = 2, m[1].query = dq2, m[1].n_query = 4; + for (int j = 0; j < 4; ++j) m[1].out[j] = d.out[4 + j]; + return tc.msg ? 2 : 1; + }; + const auto conv_of = [&](Side& d) { + InklingConvIn c; + if (tc.conv == 2) c.parts = dp, c.weights = dw, c.n_parts = parts; + else c.x = dx; + c.state = d.state, c.w = dcw, c.acc = d.s[tc.nb], c.fresh = tc.fresh; + if (tc.fresh) c.save = d.s[tc.save_k]; + return c; + }; + const auto calls = [&](Side& d) { + if (tc.conv) { + const float* x = dx; + if (tc.conv == 2) { + ck(cudaMemsetAsync(d.fo, 0, n * 4, st), "memset"); + moe_sum(dp, dw, d.fo, n, parts, 1, st); + x = d.fo; + } + if (tc.fresh) { + ck(cudaMemcpyAsync(d.s[tc.save_k], d.s[tc.nb], n * 4, cudaMemcpyDeviceToDevice, st), "copy"); + inkling_conv(x, d.state, dcw, nullptr, 0, d.s[tc.nb], n, 1, st); + } else { + inkling_conv_acc(x, d.state, dcw, nullptr, 0, d.s[tc.nb], n, 1, st); + } + } + if (!tc.alone) { + InklingMix m[2]; + const int count = mixes(d, m); + for (int k = 0; k < count; ++k) inkling_mix(m[k], n, 1, 1e-6f, st); + for (int j = 0; j < tc.nq && tc.norm; ++j) + kk::native_add_rms_norm_q8_1(d.out[j], nullptr, nw[j], d.ny[j], d.nq[j], n, 1, 1e-5f, threads, st); + } + }; + const auto fused = [&](Side& d, void* work) { + const InklingConvIn c = conv_of(d); + if (tc.alone) { + inkling_conv_in(c, n, st); + } else { + InklingMix m[2]; + const int count = mixes(d, m); + InklingMixNorm nm; + for (int j = 0; j < tc.nq; ++j) nm.w[j] = nw[j], nm.y[j] = d.ny[j], nm.y_q8_1[j] = d.nq[j]; + nm.eps = 1e-5f, nm.threads = threads; + inkling_mix_conv(m, count, tc.conv ? &c : nullptr, n, 1e-6f, st, tc.norm ? &nm : nullptr, work); + } + }; + cudaGraphExec_t rec = nullptr; + const char* recorded = ""; + { + cudaGraph_t made; + ck(cudaStreamBeginCapture(st, cudaStreamCaptureModeThreadLocal), "capture"); + fused(side[3], mix_work); + ck(cudaStreamEndCapture(st, &made), "capture"); +#if !defined(__HIPCC__) + // whether the recording holds the spread launch (MIX_SPREAD threads a block, more blocks than mixes) + size_t count = 0; + ck(cudaGraphGetNodes(made, nullptr, &count), "nodes"); + std::vector nodes(count); + ck(cudaGraphGetNodes(made, nodes.data(), &count), "nodes"); + recorded = ", recorded one block a mix"; + for (cudaGraphNode_t node : nodes) { + cudaGraphNodeType type; + cudaKernelNodeParams kp{}; + if (cudaGraphNodeGetType(node, &type) == cudaSuccess && type == cudaGraphNodeTypeKernel && + cudaGraphKernelNodeGetParams(node, &kp) == cudaSuccess && kp.blockDim.x == 32 && kp.gridDim.x > 2) + recorded = ", recorded spread"; + } +#endif + ck(cudaGraphInstantiateWithFlags(&rec, made, 0), "instantiate"); + cudaGraphDestroy(made); + } + for (int r = 0; r < tc.reps; ++r) { + calls(side[0]); + fused(side[1], nullptr); + fused(side[2], mix_work); + ck(cudaGraphLaunch(rec, st), "replay"); + } + ck(cudaStreamSynchronize(st), "mix conv"); + cudaGraphExecDestroy(rec); + const auto differ = [&](const Side& a, const Side& b) { + size_t diff = bytes_differ(a.state, b.state, size_t(n) * 12); + for (size_t k = 0; k < hs.size(); ++k) diff += bytes_differ(a.s[k], b.s[k], size_t(n) * 4); + if (!tc.alone) { + for (int j = 0; j < tc.nq; ++j) diff += bytes_differ(a.out[j], b.out[j], size_t(n) * 4); + for (int j = 0; j < 4 && tc.msg; ++j) diff += bytes_differ(a.out[4 + j], b.out[4 + j], size_t(n) * 4); + for (int j = 0; j < tc.nq && tc.norm; ++j) + diff += bytes_differ(a.ny[j], b.ny[j], size_t(n) * 4) + bytes_differ(a.nq[j], b.nq[j], qb); + } + return diff; + }; + const size_t one = differ(side[0], side[1]), spread = differ(side[1], side[2]), rd = differ(side[2], side[3]); + std::printf("%-58s %zu | %zu | %zu bytes differ %s%s\n", + (std::string("mix conv ") + tc.name + ", n " + std::to_string(n)).c_str(), one, spread, rd, + one + spread + rd ? "FAIL" : "ok", tc.alone ? "" : recorded); + if (one + spread + rd) ++failures; + for (Side& d : side) { + for (float* p : d.s) cudaFree(p); + cudaFree(d.state), cudaFree(d.fo); + for (float* o : d.out) cudaFree(o); + for (int j = 0; j < 4; ++j) cudaFree(d.ny[j]), cudaFree(d.nq[j]); + } + for (float* p : nw) cudaFree(p); + for (float* p : {dq1, dq2, dx, dp, dw, dcw}) cudaFree(p); +} + +// The position on the card wants the split path, sized by the room: a call that would leave it is refused. +void test_at_refuses() { + long long* dat; + ck(cudaMalloc(&dat, sizeof(long long)), "malloc"); + int refused = 0; + float* dtable = up(randv(size_t(kExtent) * kRel, 0.3f)); + for (long long room : {0, 1024}) { // no room; a room, but no work for the split path + try { + inkling_attend(nullptr, nullptr, nullptr, {}, {}, {dtable, dtable, kRel, kExtent}, nullptr, 0, 1, nullptr, + kDim, kHeads, kKv, 1.f, 0, 0, nullptr, 0, nullptr, room, false, dat); + } catch (const std::invalid_argument&) { + ++refused; + } + } + try { // more tokens than one launch of the store takes + inkling_kv_store(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, kKv, kDim, 17, 1.f, + 1e-6f, InklingKvDst{}, 0, nullptr, nullptr, nullptr, dat); + } catch (const std::invalid_argument&) { + ++refused; + } + std::printf("%-58s %d of 3 refused %s\n", "at: no room, off the split path, past 16 tokens", refused, + refused == 3 ? "ok" : "FAIL"); + if (refused != 3) ++failures; + cudaFree(dtable), cudaFree(dat); +} + +// More rows than kInklingSeqRows: each _seqs call refuses them. +void test_seqs_refuse_rows() { + const int rows = kInklingSeqRows + 1; + std::vector pos(rows, 0); + std::vector states(rows, nullptr); + std::vector kv(rows); + std::vector at(rows); + InklingClipJob job; + job.dim = 128, job.heads = 1; + float* work = nullptr; + ck(cudaMalloc(&work, 4), "malloc"); + int refused = 0; + const auto count = [&](auto&& f) { + try { + f(); + } catch (const std::invalid_argument&) { + ++refused; + } + }; + count([&] { inkling_clip_many_seqs(&job, 1, rows, pos.data(), nullptr); }); + count([&] { inkling_conv_seqs(nullptr, states.data(), nullptr, nullptr, 2304, rows, nullptr); }); + count([&] { inkling_conv_acc_seqs(nullptr, states.data(), nullptr, nullptr, 2304, rows, nullptr); }); + count([&] { + inkling_kv_store_seqs(nullptr, nullptr, kv.data(), nullptr, nullptr, nullptr, nullptr, kKv, kDim, rows, 1.f, + 1e-6f, nullptr, nullptr, nullptr); + }); + count([&] { + inkling_attend_seqs(nullptr, at.data(), rows, {nullptr, work, 0, kExtent}, nullptr, nullptr, kDim, kHeads, kKv, + 1.f, 0, 0, work, 1, nullptr); + }); + ck(cudaGetLastError(), "refuse"); + std::printf("%-58s %d of 5 refused %s\n", "the _seqs calls refuse 17 rows", refused, refused == 5 ? "ok" : "FAIL"); + if (refused != 5) ++failures; + cudaFree(work); +} + +// Timings at decode shapes (with `bench`): the per-token kernels as the engine calls them for one token. Each +// case runs `reps` times as one CUDA graph (no host launch cost between the calls), replayed 5 times; the fastest +// replay is reported. The functions take the stream the graph is captured on. +cudaStream_t bs = nullptr; +template float time_us(const char* what, F&& f, int reps = 200) { + if (!bs) cudaStreamCreateWithFlags(&bs, cudaStreamNonBlocking); + ck(cudaDeviceSynchronize(), "before the timing"); // the setup ran on the legacy stream + f(); // warm-up + ck(cudaStreamSynchronize(bs), "warm-up"); + cudaGraph_t gr; + cudaGraphExec_t ex; + ck(cudaStreamBeginCapture(bs, cudaStreamCaptureModeRelaxed), "capture"); + for (int i = 0; i < reps; ++i) f(); + ck(cudaStreamEndCapture(bs, &gr), "end capture"); + ck(cudaGraphInstantiate(&ex, gr, 0), "instantiate"); + cudaEvent_t e0, e1; + cudaEventCreate(&e0), cudaEventCreate(&e1); + float best = 1e30f; + for (int k = 0; k < 6; ++k) { + cudaEventRecord(e0, bs); + cudaGraphLaunch(ex, bs); + cudaEventRecord(e1, bs); + cudaEventSynchronize(e1); + float ms = 0; + cudaEventElapsedTime(&ms, e0, e1); + if (k) best = std::min(best, ms); // the first replay uploads the graph + } + std::printf("bench %-58s %9.2f us\n", what, 1000.f * best / reps); + cudaEventDestroy(e0), cudaEventDestroy(e1); + cudaGraphExecDestroy(ex), cudaGraphDestroy(gr); + return 1000.f * best / reps; +} + +// A token's attention of a full layer at long contexts over a q8_0 cache (as large as the card holds, up to 1M +// rows), sized as Engine::room(1) sizes it: the time, and the cache's bytes it reads over the time against the +// card's memory bandwidth. Each case runs again and again, so a cache that fits in the card's L2 (a 32K room's is +// 71 MB, 20480 tokens' 45 MB) can read faster than the memory +// on a card with an L2 that large (an RTX 4090's is 72 MB; an RTX 2070 Super's 4 MB): such a rate says nothing of +// the memory's. +__global__ void fill_q8_kernel(int8_t* codes, uint16_t* scales, size_t n) { + for (size_t i = blockIdx.x * size_t(blockDim.x) + threadIdx.x; i < n; i += size_t(gridDim.x) * blockDim.x) { + uint32_t h = uint32_t(i) * 2654435761u ^ uint32_t(i >> 32) * 40503u; + h ^= h >> 15, h *= 2246822519u, h ^= h >> 13; + codes[i] = (int8_t) (h & 0xff); + if (i % 32 == 0) scales[i / 32] = __half_as_ushort(__float2half(0.002f + (h >> 20) * 1e-5f)); + } +} + +void bench_long_decode(float* dtable) { + int clock_khz = 0, bus_bits = 0; + cudaDeviceGetAttribute(&clock_khz, cudaDevAttrMemoryClockRate, 0); + cudaDeviceGetAttribute(&bus_bits, cudaDevAttrGlobalMemoryBusWidth, 0); + const double peak = 2.0 * clock_khz * 1e3 * bus_bits / 8; // bytes a second + size_t free_b = 0, total_b = 0; + cudaMemGetInfo(&free_b, &total_b); + const size_t row_bytes = size_t(kKv) * kDim * 2 * 34 / 32; // K and V codes and scales a position + long long cap = 0; + for (long long c : {32768LL, 131072LL, 262144LL, 524288LL, 1048576LL}) + if (size_t(c) * row_bytes + (size_t(256) << 20) < free_b) cap = c; + if (!cap) return; + const size_t n = size_t(cap) * kKv * kDim; + int8_t *kc = nullptr, *vc = nullptr; + uint16_t *ks = nullptr, *vs = nullptr; + ck(cudaMalloc(&kc, n), "malloc"), ck(cudaMalloc(&vc, n), "malloc"); + ck(cudaMalloc(&ks, n / 16), "malloc"), ck(cudaMalloc(&vs, n / 16), "malloc"); + fill_q8_kernel<<<1024, 256>>>(kc, ks, n); + fill_q8_kernel<<<1024, 256>>>(vc, vs, n); + const int rows = 1; + float *q = up(randv(size_t(rows) * kHeads * kDim, 1.0f)), *r = up(randv(size_t(rows) * kHeads * kRel, 1.0f)), + *s = up(randv(size_t(rows) * kHeads, 1.0f)), *out = nullptr, *work = nullptr; + ck(cudaMalloc(&out, size_t(rows) * kHeads * kDim * 4), "malloc"); + const size_t wn = inkling_attend_work_floats(kHeads, kDim); + ck(cudaMalloc(&work, wn * 4), "malloc"); + const InklingRel rel{r, dtable, kRel, kExtent}; + const float sc = 1.f / std::sqrt((float) kDim); + std::printf("bench long decode: memory %.0f GB/s (%d kHz x %d bits)\n", peak / 1e9, clock_khz, bus_bits); + for (long long room = 32768; room <= cap; room *= 2) { + for (long long pos : {room - 1, room / 2 + room / 8}) { + const std::string w = "attend q8_0 full, 1 token at " + std::to_string(pos) + ", room " + + std::to_string(room); + for (bool i8 : {false, true}) { + const float us = time_us((w + (i8 ? ", int8 dot" : "")).c_str(), [&] { + inkling_attend(q, nullptr, nullptr, {kc, ks}, {vc, vs}, rel, s, pos, rows, out, kDim, kHeads, + kKv, sc, 0, 0, work, wn, bs, room, i8); + }, room >= 262144 ? 20 : 100); + const double rate = double(pos + 1) * row_bytes / (us * 1e-6); + std::printf("bench %-58s %9.1f GB/s, %.1f%% of the memory's\n", " the cache read at", rate / 1e9, + 100.0 * rate / peak); + } + } + } + ck(cudaDeviceSynchronize(), "long decode bench"); + cudaFree(kc), cudaFree(vc), cudaFree(ks), cudaFree(vs); + cudaFree(q), cudaFree(r), cudaFree(s), cudaFree(out), cudaFree(work); +} + +void bench_decode(const std::vector& table, float* dtable) { + const int n = 2304; + // mix: 5 states, 1 / 3 / 4 queries, one token; 5 states with 4 queries for 7 tokens + { + std::vector st; + for (int k = 0; k < 5; ++k) st.push_back(up(randv(size_t(7) * n, 1.0f))); + float* qd = up(randv(size_t(4) * n, 1.0f)); + float* out[4]; + for (auto& o : out) ck(cudaMalloc(&o, size_t(7) * n * 4), "malloc"); + for (int nq : {1, 3, 4}) + for (int rows : {1, 7}) { + InklingMix m; + m.n_state = 5, m.n_query = nq, m.query = qd; + for (int k = 0; k < 5; ++k) m.state[k] = st[k]; + for (int q = 0; q < nq; ++q) m.out[q] = out[q]; + const std::string w = "mix 5 states, " + std::to_string(nq) + " queries, " + std::to_string(rows) + + " token(s)"; + time_us(w.c_str(), [&] { inkling_mix(m, n, rows, 1e-6f, bs); }); + } + for (float* p : st) cudaFree(p); + for (float* o : out) cudaFree(o); + cudaFree(qd); + } + // clip and conv, one token + { + float *x = up(randv(size_t(n) * 8, 1.0f)), *y = nullptr, *sc = up(randv(3072, 1.0f)), + *state = up(randv(size_t(n) * 3, 1.0f)), *w = up(randv(size_t(n) * 4, 0.3f)), + *taps = up(randv(64, 0.3f)); + ck(cudaMalloc(&y, size_t(n) * 8 * 4), "malloc"); + time_us("clip Q 128 x 24, scale, tau, 1 token", [&] { + inkling_clip(x, 0, sc, y, 128, 24, 1, 22.6f, InklingTau{0.1f, 8192}, 100, bs); + }); + time_us("clip K 128 x 8, 1 token", [&] { inkling_clip(x, 0, nullptr, y, 128, 8, 1, 22.6f, {}, 100, bs); }); + time_us("clip R 16 x 24, 1 token", [&] { inkling_clip(x, 0, sc, y, 16, 24, 1, 8.f, {}, 100, bs); }); + time_us("conv 1024, taps 8 heads, 1 token", [&] { inkling_conv(x, state, w, taps, 8, y, 1024, 1, bs); }); + time_us("conv 2304, 1 token", [&] { inkling_conv(x, state, w, nullptr, 0, y, 2304, 1, bs); }); + cudaFree(x), cudaFree(y), cudaFree(sc), cudaFree(state), cudaFree(w), cudaFree(taps); + } + // inkling_mix_conv() at the engine's shapes: one block a mix against the spread launch + { + std::vector fr; + auto mk = [&](size_t count, float sd) { float* p = up(randv(count, sd)); fr.push_back(p); return p; }; + float *qd = mk(size_t(4) * n, 1.f), *parts = mk(size_t(8) * n, 1.f), *pw = mk(8, 0.3f), + *state = mk(size_t(3) * n, 1.f), *cw = mk(size_t(4) * n, 0.3f), *x = mk(n, 1.f); + float* s[7]; + float *out[8], *ny[4]; + void* yq[4]; + for (float*& p : s) p = mk(n, 1.f); + for (float*& p : out) p = mk(n, 0.f); + for (float*& p : ny) p = mk(n, 0.f); + for (void*& p : yq) p = mk(strata::kernels::native_q8_1_bytes(n) / 4 + 1, 0.f); + float* nw[3] = {mk(n, 1.f), mk(n, 1.f), mk(n, 1.f)}; + void* work = nullptr; + ck(cudaMalloc(&work, inkling_mix_conv_work_bytes()), "malloc"); + ck(cudaMemset(work, 0, inkling_mix_conv_work_bytes()), "memset"); + struct Shape { + const char* name; + int states, nq; + bool msg, sum, norm; + }; + for (const Shape& sh : {Shape{"window, tail sum, norm", 3, 1, false, true, true}, + Shape{"full, tail sum, 3 norms", 4, 3, false, true, true}, + Shape{"full, tail sum, messages", 4, 3, true, true, false}, + Shape{"ffn 5 states, conv, norm", 5, 1, false, false, true}, + Shape{"ffn 5 states, conv", 5, 1, false, false, false}}) { + InklingMix m[2]; + for (int k = 0; k < sh.states; ++k) m[0].state[k] = s[k]; + m[0].n_state = sh.states, m[0].query = qd, m[0].n_query = sh.nq; + for (int q = 0; q < sh.nq; ++q) m[0].out[q] = out[q]; + m[1].state[0] = s[5], m[1].state[1] = s[6], m[1].n_state = 2, m[1].query = qd, m[1].n_query = 4; + for (int q = 0; q < 4; ++q) m[1].out[q] = out[4 + q]; + InklingConvIn c; + if (sh.sum) c.parts = parts, c.weights = pw, c.n_parts = 8; + else c.x = x; + c.state = state, c.w = cw, c.acc = s[sh.states - 1]; + InklingMixNorm nm; + for (int q = 0; q < sh.nq; ++q) nm.w[q] = nw[q], nm.y[q] = ny[q], nm.y_q8_1[q] = yq[q]; + nm.eps = 1e-5f, nm.threads = sum_threads(n); + for (void* wk : {(void*) nullptr, work}) { + const std::string w = std::string("mix conv ") + sh.name + (wk ? ": spread" : ": one block a mix"); + time_us(w.c_str(), [&] { + inkling_mix_conv(m, sh.msg ? 2 : 1, &c, n, 1e-6f, bs, sh.norm ? &nm : nullptr, wk); + }); + } + } + ck(cudaDeviceSynchronize(), "mix conv bench"); + cudaFree(work); + for (float* p : fr) cudaFree(p); + } + // the fused steps against the launches they replace, one token + { + const int rank = 64; + std::vector fr; + auto mk = [&](size_t count, float sd) { float* p = up(randv(count, sd)); fr.push_back(p); return p; }; + InklingCtrl c[4]; + float* work = mk(size_t(4) * 4 * (4 * n + rank), 0.f); + for (int k = 0; k < 4; ++k) { + c[k].cur = mk(n, 1.f), c[k].msg = mk(n, 1.f), c[k].out = mk(n, 0.f); + c[k].down = mk(size_t(rank) * 2 * n, 0.02f), c[k].gain = mk(size_t(n) * rank, 0.2f); + c[k].forget = mk(size_t(n) * rank, 0.2f); + } + auto separate_ctrl = [&](int count) { + for (int k = 0; k < count; ++k) + inkling_control(nullptr, c[k].cur, c[k].msg, c[k].down, c[k].gain, c[k].forget, work, c[k].out, n, + rank, 1, 1e-6f, bs); + }; + time_us("control x1: inkling_control (6 launches)", [&] { separate_ctrl(1); }); + time_us("control x1: inkling_control_fused", [&] { inkling_control_fused(c, 1, n, rank, 1, 1e-6f, work, bs); }); + time_us("control x3: 3 x inkling_control", [&] { separate_ctrl(3); }); + time_us("control x3: one inkling_control_fused", [&] { + inkling_control_fused(c, 3, n, rank, 1, 1e-6f, work, bs); + }); + // the router's product + float *rw = mk(size_t(n) * 128, 0.05f), *x = mk(n * 4, 1.f), *y = mk(128 * 4, 0.f); + time_us("router 2304 -> 128: gemv_f32", [&] { gemv_f32(rw, x, y, n, 128, 128, 1, bs); }); + time_us("router 2304 -> 128: inkling_gemv", [&] { inkling_gemv(rw, x, y, n, 128, 1, bs); }); + // Q and R clips + float *q = mk(3072, 2.f), *qs = mk(3072, 0.3f), *r = mk(384, 2.f), *rs = mk(384, 0.3f); + const InklingTau tau{0.1f, 8192}; + time_us("clip Q + R: 2 x inkling_clip", [&] { + inkling_clip(q, 0, qs, q, 128, 24, 1, 22.6f, tau, 100, bs); + inkling_clip(r, 0, rs, r, 16, 24, 1, 8.f, tau, 100, bs); + }); + InklingClipJob j[2]; + j[0].x = q, j[0].scale = qs, j[0].y = q, j[0].dim = 128, j[0].heads = 24, j[0].threshold = 22.6f; + j[0].tau = tau; + j[1].x = r, j[1].scale = rs, j[1].y = r, j[1].dim = 16, j[1].heads = 24, j[1].threshold = 8.f; + j[1].tau = tau; + time_us("clip Q + R: inkling_clip_many", [&] { inkling_clip_many(j, 2, 1, 100, bs); }); + // K and V to the cache + const int width = 1024, cap = 2048; + float *kraw = mk(width, 1.f), *vraw = mk(width, 1.f), *kst = mk(width * 3, 1.f), *vst = mk(width * 3, 1.f), + *kw = mk(width * 4, 0.3f), *vw = mk(width * 4, 0.3f), *kt = mk(32, 0.3f), *vt = mk(32, 0.3f), + *ko = mk(width, 0.f), *vo = mk(width, 0.f); + int8_t *kc, *vc; + uint16_t *ks, *vs; + ck(cudaMalloc(&kc, size_t(cap) * width), "malloc"), ck(cudaMalloc(&vc, size_t(cap) * width), "malloc"); + ck(cudaMalloc(&ks, size_t(cap) * width / 16), "malloc"); + ck(cudaMalloc(&vs, size_t(cap) * width / 16), "malloc"); + fr.insert(fr.end(), {(float*) kc, (float*) vc, (float*) ks, (float*) vs}); + time_us("K, V to the q8_0 cache: the separate calls (6 launches)", [&] { + inkling_conv(kraw, kst, kw, kt, 8, ko, width, 1, bs); + inkling_conv(vraw, vst, vw, vt, 8, vo, width, 1, bs); + inkling_clip(ko, 0, nullptr, ko, 128, 8, 1, 22.6f, {}, 100, bs); + rms_norm(vo, nullptr, vo, 128, 8, 1e-6f, bs); + store_q8(ko, kc, ks, width, 100, 1, bs); + store_q8(vo, vc, vs, width, 100, 1, bs); + }); + InklingKvDst d; + d.kc = kc, d.ks = ks, d.vc = vc, d.vs = vs; + time_us("K, V to the q8_0 cache: inkling_kv_store", [&] { + inkling_kv_store(kraw, vraw, kst, vst, kw, vw, kt, vt, 8, 128, 1, 22.6f, 1e-6f, d, 100, ko, vo, bs); + }); + // a post-convolution and its residual add + float *xo = mk(n, 1.f), *pst = mk(n * 3, 1.f), *pw = mk(n * 4, 0.3f), *tmp = mk(n, 0.f), *res = mk(n, 1.f); + time_us("post-conv + residual: inkling_conv + axpy", [&] { + inkling_conv(xo, pst, pw, nullptr, 0, tmp, n, 1, bs); + axpy(tmp, 1.f, res, n, true, bs); + }); + time_us("post-conv + residual: inkling_conv_acc", [&] { + inkling_conv_acc(xo, pst, pw, nullptr, 0, res, n, 1, bs); + }); + ck(cudaDeviceSynchronize(), "fused bench"); + for (float* p : fr) cudaFree(p); + } + // attention, one token (and 7), over q8_0 and fp16 caches + { + const int ctx = 32768, window = 1024; + auto kv = randv(size_t(ctx) * kKv * kDim, 1.0f); + float* dkv = up(kv); + Cache cf, c8; + cf.alloc(ctx, false), c8.alloc(ctx, true); + for (Cache* c : {&cf, &c8}) { + const int width = kKv * kDim; + if (c->q8) { + store_q8(dkv, c->kc, c->ks, width, 0, ctx, nullptr); + store_q8(dkv, c->vc, c->vs, width, 0, ctx, nullptr); + } else { + store_f16(dkv, c->k, width, 0, ctx, nullptr); + store_f16(dkv, c->v, width, 0, ctx, nullptr); + } + } + const int rows = 7; + float *q = up(randv(size_t(rows) * kHeads * kDim, 1.0f)), *r = up(randv(size_t(rows) * kHeads * kRel, 1.0f)), + *s = up(randv(size_t(rows) * kHeads, 1.0f)), *out = nullptr, *work = nullptr; + ck(cudaMalloc(&out, size_t(rows) * kHeads * kDim * 4), "malloc"); + const size_t wn = inkling_attend_work_floats(kHeads, kDim); + ck(cudaMalloc(&work, wn * 4), "malloc"); + const float sc = 1.f / std::sqrt((float) kDim); + const InklingRel rel{r, dtable, kRel, kExtent}; + struct Case { + const char* name; + bool q8; + int pos, rows, window; + long long room; // 0: pos + rows + bool int8_dot = false; + }; + const Case cases[] = { + {"q8_0 full, 1 token at 25", true, 25, 1, 0, 0}, + {"q8_0 full, 1 token at 150", true, 150, 1, 0, 0}, + {"q8_0 swa, 1 token at 150", true, 150, 1, window, 0}, + {"q8_0 full, 1 token at 150, room 1024", true, 150, 1, 0, 1024}, + {"q8_0 swa, 1 token at 150, room 1024", true, 150, 1, window, 1024}, + {"q8_0 full, 1 token at 150, room 131072", true, 150, 1, 0, 131072}, + {"q8_0 full, 1 token at 1024", true, 1024, 1, 0, 0}, + {"q8_0 full, 1 token at 4096", true, 4096, 1, 0, 0}, + {"q8_0 full, 1 token at 32767", true, 32767, 1, 0, 0}, + {"q8_0 swa, 1 token at 32767 (ring)", true, 32767, 1, window, 0}, + {"q8_0 swa, 7 tokens at 32760 (ring)", true, 32760, 7, window, 0}, + {"q8_0 full, 1 token at 32767, int8 dot", true, 32767, 1, 0, 0, true}, + {"fp16 full, 1 token at 150", false, 150, 1, 0, 0}, + {"fp16 full, 1 token at 1024", false, 1024, 1, 0, 0}, + {"fp16 full, 1 token at 32767", false, 32767, 1, 0, 0}, + {"fp16 swa, 1 token at 32767 (ring)", false, 32767, 1, window, 0}, + }; + for (const Case& k : cases) { + const Cache& c = k.q8 ? c8 : cf; + const Kvq8 kq = k.q8 ? Kvq8{c.kc, c.ks} : Kvq8{}, vq = k.q8 ? Kvq8{c.vc, c.vs} : Kvq8{}; + // a window layer reads the full cache as its ring (any ring >= window + rows is the same work) + const int rg = k.window ? ctx : 0; + const std::string w = std::string("attend ") + k.name; + time_us(w.c_str(), [&] { + inkling_attend(q, c.k, c.v, kq, vq, rel, s, k.pos, k.rows, out, kDim, kHeads, kKv, sc, k.window, rg, + work, wn, bs, k.room, k.int8_dot); + }, 50); + } + cf.free_(), c8.free_(); + cudaFree(dkv), cudaFree(q), cudaFree(r), cudaFree(s), cudaFree(out), cudaFree(work); + } + bench_long_decode(dtable); +} + +// ---- the DSpark drafter ------------------------------------------------------------------------------------------ + +void test_dspark_fuse(int rows) { + const int n = 2304; + const int64_t stride[4] = {3 * n, 3 * n, 3 * n, n}; + std::vector x[4], norm[4]; + for (int k = 0; k < 4; ++k) x[k] = randv((size_t) rows * stride[k], 1.f); + InklingFuse f; + std::vector wts = randv(16, 1.f); + float* dx[4]; + float* dn[4]; + float* dout[4]; + for (int k = 0; k < 4; ++k) { + norm[k] = randv(n, 0.2f, 1.f); + dx[k] = up(x[k]); + dn[k] = up(norm[k]); + ck(cudaMalloc(&dout[k], (size_t) rows * n * sizeof(float)), "malloc"); + f.x[k] = dx[k] + k % 3; // the streams of a row at their offsets + f.stride[k] = stride[k]; + f.norm[k] = dn[k]; + f.out[k] = dout[k]; + for (int j = 0; j < 4; ++j) f.w[k][j] = wts[(size_t) k * 4 + j]; + } + inkling_dspark_fuse(f, n, rows, 1e-6f, nullptr); + for (int j = 0; j < 4; ++j) { + std::vector ref((size_t) rows * n); + for (int r = 0; r < rows; ++r) { + double ss = 0; + for (int i = 0; i < n; ++i) { + double v = 0; + for (int k = 0; k < 4; ++k) v += (double) f.w[j][k] * x[k][(size_t) r * stride[k] + k % 3 + i]; + ref[(size_t) r * n + i] = v; + ss += v * v; + } + const double sc = 1.0 / std::sqrt(ss / n + 1e-6); + for (int i = 0; i < n; ++i) ref[(size_t) r * n + i] *= sc * norm[j][i]; + } + const std::string what = "dspark fuse, output " + std::to_string(j) + ", " + std::to_string(rows) + " rows"; + compare(what.c_str(), down(dout[j], ref.size()), ref, 2e-5); + } + for (int k = 0; k < 4; ++k) cudaFree(dx[k]), cudaFree(dn[k]), cudaFree(dout[k]); +} + +// rows queries that all see positions lo..hi of an fp16 cache (a ring when ring > 0) +void test_block_attend(int rows, long long lo, long long hi, int ring) { + const int dim = 128, nh = 24, kv = 8, per = nh / kv; + const long long slots = ring > 0 ? ring : hi + 1; + std::vector q = randv((size_t) rows * nh * dim, 1.f); + std::vector kf = randv((size_t) slots * kv * dim, 1.f), vf = randv((size_t) slots * kv * dim, 1.f); + std::vector kh(kf.size()), vh(vf.size()); + for (size_t i = 0; i < kf.size(); ++i) { + const __half a = __float2half(kf[i]), b = __float2half(vf[i]); + std::memcpy(&kh[i], &a, 2), std::memcpy(&vh[i], &b, 2); + kf[i] = __half2float(a), vf[i] = __half2float(b); + } + float *dq = up(q), *dout = nullptr, *dwork = nullptr; + uint16_t *dk = up(kh), *dv = up(vh); + ck(cudaMalloc(&dout, q.size() * sizeof(float)), "malloc"); + ck(cudaMalloc(&dwork, inkling_block_attend_work_floats(rows, nh, dim) * sizeof(float)), "malloc"); + const float scale = 1.f / std::sqrt((float) dim); + inkling_block_attend(dq, dk, dv, lo, hi, ring, rows, dout, dim, nh, kv, scale, dwork, nullptr); + std::vector ref(q.size()); + for (int r = 0; r < rows; ++r) + for (int h = 0; h < nh; ++h) { + const int g = h / per; + std::vector s((size_t) (hi - lo + 1)); + double mx = -1e300; + for (long long p = lo; p <= hi; ++p) { + const long long row = ring > 0 ? p % ring : p; + double d = 0; + for (int i = 0; i < dim; ++i) + d += (double) q[((size_t) r * nh + h) * dim + i] * kf[((size_t) row * kv + g) * dim + i]; + s[(size_t) (p - lo)] = d * scale; + mx = std::max(mx, d * scale); + } + double sum = 0; + for (double& e : s) sum += e = std::exp(e - mx); + for (int i = 0; i < dim; ++i) { + double v = 0; + for (long long p = lo; p <= hi; ++p) { + const long long row = ring > 0 ? p % ring : p; + v += s[(size_t) (p - lo)] * vf[((size_t) row * kv + g) * dim + i]; + } + ref[((size_t) r * nh + h) * dim + i] = v / sum; + } + } + const std::string what = "block attend, " + std::to_string(rows) + " rows, keys " + std::to_string(lo) + ".." + + std::to_string(hi) + (ring ? ", ring " + std::to_string(ring) : ""); + compare(what.c_str(), down(dout, ref.size()), ref, 2e-5); + cudaFree(dq), cudaFree(dk), cudaFree(dv), cudaFree(dout), cudaFree(dwork); +} + +void test_dspark_gru() { + const int rank = 256; + std::vector j = randv(3 * rank, 2.f), st = randv(rank, 0.5f); + float *dj = up(j), *ds = up(st), *dl = nullptr; + ck(cudaMalloc(&dl, rank * sizeof(float)), "malloc"); + inkling_dspark_gru(dj, ds, dl, rank, nullptr); + std::vector rs(rank), rl(rank); + for (int i = 0; i < rank; ++i) { + const double gate = 1.0 / (1.0 + std::exp(-(double) j[i])), cand = std::tanh((double) j[rank + i]); + rs[i] = cand + gate * (st[i] - cand); + rl[i] = std::tanh((double) j[2 * rank + i]); + } + compare("dspark recurrent head state", down(ds, rank), rs, 1e-6); + compare("dspark recurrent head latent", down(dl, rank), rl, 1e-6); + cudaFree(dj), cudaFree(ds), cudaFree(dl); +} + +} // namespace + +// f(), a group of checks: an exception out of it is its failure, not the end of the run. +template void guarded(F&& f) { + try { + f(); + } catch (const std::exception& e) { + std::printf("%-58s %s FAIL\n", "(a check threw)", e.what()); + ++failures; + } +} + +int main(int argc, char** argv) { + const bool bench = argc > 1 && std::string(argv[1]) == "bench"; + const bool only_bench = argc > 1 && std::string(argv[1]) == "decode"; + int devices = 0; + if (const cudaError_t e = cudaGetDeviceCount(&devices); e != cudaSuccess || devices == 0) { + std::printf("no usable CUDA device (%s): skipped\n", e != cudaSuccess ? cudaGetErrorString(e) : "none"); + return 77; + } + cudaDeviceProp prop{}; + cudaGetDeviceProperties(&prop, 0); + std::printf("device: %s (sm_%d%d)\n", prop.name, prop.major, prop.minor); + mma_card = prop.major * 10 + prop.minor >= 75; + + if (only_bench) { // decode: only the decode-shape timings + std::vector table = randv(size_t(kExtent) * kRel, 0.3f); + float* dtable = up(table); + bench_decode(table, dtable); + cudaFree(dtable); + return 0; + } + const InklingTau tau{0.1f, 8192}; + test_clip("clip Q (128 x 24, scale, tau, pos 30000, 7 rows)", 128, 24, 7, true, 22.627417f, tau, 30000, true); + test_clip("clip Q (128 x 24, scale, tau, pos 123456, 1 row)", 128, 24, 1, true, 22.627417f, tau, 123456, false); + test_clip("clip K (128 x 8, no scale, 1500 rows)", 128, 8, 1500, false, 22.627417f, {}, 0, true); + test_clip("clip R (16 x 24, scale, tau, pos 8000, 1100 rows)", 16, 24, 1100, true, 8.0f, tau, 8000, true); + test_clip("clip R (16 x 24, scale, no tau, 1 row)", 16, 24, 1, true, 8.0f, {}, 5, true); + + test_conv("conv K (1024, taps 8 heads)", 1024, 8, true, {1, 7, 1, 40, 3}); + test_conv("conv V (1024, taps 8 heads)", 1024, 8, true, {5, 7}); + test_conv("conv attn-out (2304, no taps)", 2304, 1, false, {1, 7, 1100, 1}); + test_conv("conv ffn-out (2304, no taps)", 2304, 1, false, {3, 4}); + + test_mix(1, 1, 3); + test_mix(2, 1, 1); + test_mix(5, 3, 7); + test_mix(4, 4, 33); + test_mix(8, 1, 2); + test_mix(8, 4, 3, 128); // one warp a token: fewer threads than the 40 sums + test_mix(3, 2, 2, 100); + test_mix(4, 3, 5, 2303); // n not a multiple of 4: the scalar kernel + test_mix(5, 4, 3, 2304, 1); // states not 16-byte aligned: the scalar kernel + + void* blas = blas_create(nullptr); + test_control(blas, 1); + test_control(blas, 7); + test_control(blas, 20); + blas_destroy(blas); + + test_situ(); + + for (int count : {1, 3, 4}) + for (int rows : {1, 3, 7}) test_control_fused(count, rows); + test_control_fused(1, 5); + for (int rows : {1, 4, 7}) test_gemv(2304, 128, rows); + test_gemv(4608, 64, 2); + for (int rows : {1, 7, 40}) test_clip_many(rows); + for (int rows : {1, 7, 40}) test_conv_acc(2304, rows); + test_kv_store(1, true, true, 0, 150); + test_kv_store(1, true, false, 1030, 2047); + test_kv_store(7, true, true, 1030, 1026); // wraps the ring + test_kv_store(7, false, false, 1030, 1026); + test_kv_store(3, false, true, 0, 5); + test_kv_store(16, false, true, 0, 40); // the most tokens of the one launch + test_kv_store(17, false, true, 0, 40); // the fewest of the separate calls + test_kv_store(20, true, true, 1030, 1020); + test_kv_store(20, false, false, 0, 0); + + std::vector table = randv(size_t(kExtent) * kRel, 0.3f); + float* dtable = up(table); + const std::vector cases = { + {"attend full fp16 split", 0, 0, false, {7, 1, 1}, true, false, true, 1}, + {"attend full fp16 split, 1 token at 0", 0, 0, false, {1, 1, 16, 17}, true, false, true, 1}, + {"attend full fp16 split, room, 1 token at 0", 0, 0, true, {1, 16, 17}, true, true, true, 1}, + {"attend full fp16 unsplit", 0, 0, false, {7, 1}, false, false, true, 1}, + {"attend full fp16 unsplit, 1 token at 0", 0, 0, false, {1, 3, 2, 17}, false, false, true, 1}, + // 2 and 3 tokens unsplit: attn_kernel's TQ 2, whose 6 rows of weights a key are not a whole float4 + {"attend full q8_0 unsplit, 2 and 3 tokens", 0, 0, true, {40, 3, 2, 3}, false, false, true, 1}, + {"attend swa fp16 ring unsplit, 2 and 3 tokens", 1024, 1024 + 1100, false, {1100, 3, 2}, false, false, true, + 37}, + {"attend full fp16 prompt >1024", 0, 0, false, {1100, 7, 1}, true, false, true, 23}, + {"attend full fp16 prompt, room", 0, 0, false, {1300, 1, 7}, true, true, true, 41}, + {"attend full q8_0", 0, 0, true, {1050, 1, 7}, true, false, true, 37}, + {"attend full fp16 no sinks", 0, 0, false, {33, 2}, true, false, false, 1}, + {"attend swa fp16 ring", 1024, 1024 + 2048, false, {2048, 1, 7, 2048, 1}, true, false, true, 29}, + {"attend swa fp16 ring, room", 1024, 1024 + 1100, false, {1100, 1, 7, 1100, 1}, true, true, true, 31}, + {"attend swa q8_0 ring unsplit", 1024, 1024 + 1500, true, {1500, 1, 7, 1500}, false, false, true, 43}, + {"attend swa q8_0 ring", 1024, 1024 + 1500, true, {1030, 7, 1}, true, true, true, 43}, + // the tensor-core path: calls about its smallest, a block's 21 tokens, past the extent, the ring's wrap + {"attend full fp16 mma, rows about the switch", 0, 0, false, + {kInklingMmaRows - 1, kInklingMmaRows, kInklingMmaRows + 1, 21 * 5, 22}, false, false, true, 1}, + {"attend full q8_0 mma, rows about the switch", 0, 0, true, + {kInklingMmaRows, 1, kInklingMmaRows + 20, 63, 85}, true, false, true, 1}, + {"attend full fp16 mma, past the extent", 0, 0, false, {990, 100, 2000, 64}, true, false, true, 7}, + {"attend full q8_0 mma, no sinks", 0, 0, true, {1500, 200}, false, false, false, 11}, + {"attend swa fp16 mma ring wrap", 1024, 1024 + 300, false, {900, 300, 301, 64, 299}, true, false, true, 5}, + {"attend swa q8_0 mma ring wrap", 1024, 1024 + 512, true, {1000, 512, 100, 512, 77}, true, false, true, 5}, + {"attend swa q8_0 mma, no sinks", 1024, 1024 + 2048, true, {2048, 70}, false, false, false, 9}, + // and about the edges of attn_fa2_kernel's blocks of 85 tokens (42 with 4 warps) + {"attend full fp16 mma, blocks of 42 and 85", 0, 0, false, {41, 42, 43, 84, 85, 86, 170, 171}, false, false, + true, 1}, + {"attend swa q8_0 mma ring, blocks of 42 and 85", 1024, 1024 + 400, true, {900, 85, 86, 170, 341}, false, + false, true, 3}, + {"attend full fp16 mma probe, mean", 0, 0, false, {1000, 100}, false, false, false, 3, Probe::mean}, + {"attend swa fp16 mma probe, mean, ring wrap", 1024, 1024 + 300, false, {1200, 300}, false, false, false, 3, + Probe::mean}, + {"attend full fp16 mma probe, extent's edge", 0, 0, false, {1000, 100}, false, false, false, 3, Probe::edge}, + {"attend swa fp16 mma probe, extent's edge, ring wrap", 1024, 1024 + 300, false, {1200, 300}, false, false, + false, 3, Probe::edge}, + // STRATA_KV_INT8: a full layer's rows of 512-key splits or more (a room of 32K or more), alone and 7 or 16 a + // call, to a looser bound (the queries are rounded to Q8_0 codes) + {"attend full q8_0 int8 dot, 33K", 0, 0, true, {33000, 1, 7, 16, 1}, true, true, true, 4999, Probe::none, + true}, + }; + for (const AttnCase& tc : cases) test_attend(tc, table, dtable); + test_attend_alone(table, dtable); + for (InklingMma mma : {InklingMma::best, InklingMma::fa2}) + if (mma == InklingMma::best || fa2_card) + for (bool q8 : {false, true}) test_attend_mma_alone(table, dtable, q8, mma); + + for (int rows : {1, 4, 9, kInklingSeqRows}) test_clip_many_seqs(rows); + for (bool acc : {false, true}) + for (int rows : {1, 9, kInklingSeqRows}) test_conv_seqs(acc, rows); + test_conv_snaps(4, 0x7u); + test_conv_snaps(8, 0x55u); + test_conv_snaps(2, 0x1u); + test_conv_snaps(4, 0xf0u); // every bit past the rows + test_conv_snaps(3, 0xffffffffu); // bits at and past the rows + test_conv_snaps(40, 0x80000005u); // rows past 32: the last snapshot after token 31 + test_kv_store_seqs(1, false, true, 0); + test_kv_store_seqs(9, false, true, 0); + test_kv_store_seqs(9, true, true, 0); + test_kv_store_seqs(9, false, false, 2048); + test_kv_store_seqs(9, true, false, 2048); + test_kv_store_seqs(kInklingSeqRows, true, true, 0); + for (bool q8 : {false, true}) + for (int window : {0, 1024}) + for (int rows : {1, 3, 9, kInklingSeqRows}) test_attend_seqs(rows, q8, window, table, dtable); + for (int window : {0, 1024}) test_attend_seqs(9, false, window, table, dtable, kSeqPos, 8192, true); + test_attend_seqs(2, true, 0, table, dtable, {131000, 70}, 131072); // the largest split of a 128K context + // the int8 dot's rows alone and together: all of them past 16K (its kernel), and one beside a short one (both) + test_attend_seqs(4, true, 0, table, dtable, {20000, 40000, 70000, 131000}, 131072, false, true); + test_attend_seqs(2, true, 0, table, dtable, {131000, 70}, 131072, false, true); + test_int8_unchanged(table, dtable); + test_seqs_refuse_rows(); + test_at(false, 0, true, 1020, 8, 8192); // a full visit across room 1024's edge + test_at(true, 0, true, 2044, 8, 8192); + test_at(true, 0, false, 2045, 6, 3000); // a room past the context's: the context + test_at(false, 0, true, 8190, 4, 16384); // tau past its floor + test_at(false, 1024, false, 1036, 8, 8192); // a window visit across the ring's wrap + test_at(true, 1024, false, 1020, 8, 8192); // across the window's edge + test_at(true, 0, false, 32765, 6, 65536, true); // STRATA_KV_INT8: its kernel from room 32768 on + // a window's calls of 2 to 8 tokens (--window 8), each case on its own so that one that throws leaves the others + for (int rows = 2; rows <= 8; ++rows) { + guarded("at vs pos, full, a window across room 1024's edge", + [&] { test_at(rows % 2 == 0, 0, true, 1020 - rows, 8, 8192, false, rows); }); + guarded("at vs pos, window visit, a window across the ring's wrap", + [&] { test_at(rows % 2 != 0, 1024, false, 1030 - rows, 8, 8192, false, rows); }); + } + guarded("at vs pos, window visit, across the window's edge", + [] { test_at(true, 1024, false, 1018, 6, 8192, false, 4); }); + guarded("at vs pos, tau past its floor, room 8192's edge", + [] { test_at(false, 0, true, 8186, 6, 16384, false, 8); }); + guarded("at vs pos, a room past the context's", [] { test_at(true, 0, false, 2040, 6, 3000, false, 4); }); + guarded("at vs pos, STRATA_KV_INT8 from room 32768 on", [] { test_at(true, 0, false, 32760, 6, 65536, true, 8); }); + test_at_refuses(); + test_fused_attn(false, 0, true, 1020, 8, 8192); // full: a room's edge, one split and more + test_fused_attn(true, 0, true, 8190, 4, 16384); // tau past its floor + test_fused_attn(false, 1024, false, 1036, 8, 8192); // window: the ring's wrap + test_fused_attn(true, 1024, false, 20, 6, 8192); // a few keys: one split, the block writes the output + test_fused_attn(false, 0, false, 3, 4, 4096); + test_fused_attn(true, 0, false, 32765, 6, 65536, true); // STRATA_KV_INT8's kernel from room 32768 on + for (int rows : {1, 5, 40}) test_gate_unsplit(rows); + for (int count : {1, 3}) test_norm_rows(count); + test_situ_q8(8, 25.f, true); + test_situ_q8(8, 0.f, false); + test_situ_q8(1, 25.f, false); + for (const MixConvCase& tc : std::vector{ + {"window, tail sum, messages", 2, 1, true, 2, false, 0, false}, + {"full, tail x", 3, 3, false, 1, false, 0, false}, + {"full, tail sum, messages", 4, 3, true, 2, false, 0, false}, + {"ffn, attention conv", 3, 1, false, 1, false, 0, false}, + {"ffn, block start", 2, 1, false, 1, true, 1, false}, + {"ffn, block start, first block", 1, 1, false, 1, true, 0, false}, + {"no conv, messages", 1, 1, true, 0, false, 0, false}, + {"conv alone, sum", 1, 1, false, 2, false, 0, true}, + {"conv alone, block start", 3, 1, false, 1, true, 1, true}, + {"window, tail sum, norm", 2, 1, false, 2, false, 0, false, true}, + {"full, tail x, 3 norms", 3, 3, false, 1, false, 0, false, true}, + {"ffn, block start, norm", 2, 1, false, 1, true, 1, false, true}, + {"first visit, norm", 0, 1, false, 0, false, 0, false, true}, + {"full, tail sum, 3 norms", 3, 3, false, 2, false, 0, false, true}, + {"window, 1 state, tail sum, messages", 0, 1, true, 2, false, 0, false}, + {"ffn, 5 states, block start", 4, 1, false, 1, true, 3, false}, + {"ffn, 5 states, norm", 4, 1, false, 1, false, 0, false, true}, + {"window, tail sum, norm", 2, 1, false, 2, false, 0, false, true, 512}, + {"full, tail x, 3 norms", 3, 3, false, 1, false, 0, false, true, 1024}, + {"window, tail x, norm", 1, 1, false, 1, false, 0, false, true, 2048}, + {"full, tail sum, a part block", 3, 3, false, 2, false, 0, false, false, 2336}, + {"full, tail sum, messages, a part warp", 4, 3, true, 2, false, 0, false, false, 2312}, + {"ffn, block start, norm, widest", 2, 1, false, 1, true, 1, false, true, 3072}, + {"full, tail sum, 3 norms, 40 tokens", 3, 3, false, 2, false, 0, false, true, 2304, 40}}) { + guarded([&] { test_mix_conv(tc); }); + } + for (int rows : {1, 2, 4, 8}) { + guarded([&] { test_mmvq_jobs(8, "Q8_0", 2304, 8, rows); }); + guarded([&] { test_mmvq_jobs(12, "Q4_K", 2304, 8, rows); }); + guarded([&] { test_mmvq_jobs(13, "Q5_K", 2304, 8, rows); }); + guarded([&] { test_mmvq_jobs(14, "Q6_K", 2304, 8, rows); }); + } + for (int rows : {1, 3}) { // 2 rows a block; fewer matrices + for (int count : {3, 8}) { + guarded([&] { test_mmvq_jobs(8, "Q8_0", 512, count, rows); }); + guarded([&] { test_mmvq_jobs(12, "Q4_K", 512, count, rows); }); + guarded([&] { test_mmvq_jobs(13, "Q5_K", 512, count, rows); }); + guarded([&] { test_mmvq_jobs(14, "Q6_K", 512, count, rows); }); + } + } + guarded([&] { test_mmvq_jobs(8, "Q8_0", 2304, 2, 1); }); + for (int count : {2, 5, 8}) guarded([&] { test_mmvq_jobs_mixed(2304, count); }); + guarded([&] { test_mmvq_jobs_mixed(512, 8); }); // 2 rows a block for every format + // Inkling 2's experts: IQ4_NL and Q8_0 (IQ4_NL's file), Q2_0 (UD-Q2_K_XL's downs); a tail of rows + for (int count : {1, 8}) { + guarded([&] { test_slots_lanes(20, "IQ4_NL", 2304, 2304, count); }); + guarded([&] { test_slots_lanes(20, "IQ4_NL", 1152, 2304, count); }); + guarded([&] { test_slots_lanes(8, "Q8_0", 2304, 2304, count); }); + guarded([&] { test_slots_lanes(8, "Q8_0", 1152, 2304, count); }); + guarded([&] { test_slots_lanes(42, "Q2_0", 1152, 2304, count); }); + } + guarded([&] { test_slots_lanes(20, "IQ4_NL", 2304, 2301, 8); }); + guarded([&] { test_slots_lanes(8, "Q8_0", 1152, 37, 3); }); + // UD-Q2_K_XL's gate and up, and IQ1_M: iq_kernels.cu's, the grid staged; 8 rows a warp and its tails + for (int count : {1, 8}) { + guarded([&] { test_slots_lanes(19, "IQ1_S", 2304, 2304, count); }); + guarded([&] { test_slots_lanes(16, "IQ2_XXS", 2304, 2304, count); }); + guarded([&] { test_slots_lanes(17, "IQ2_XS", 2304, 2304, count); }); + guarded([&] { test_slots_lanes(22, "IQ2_S", 2304, 2304, count); }); + guarded([&] { test_slots_lanes(29, "IQ1_M", 2304, 2304, count); }); + } + guarded([&] { test_slots_lanes(19, "IQ1_S", 2304, 2301, 8); }); + guarded([&] { test_slots_lanes(29, "IQ1_M", 1024, 37, 3); }); + guarded([&] { test_slots_lanes(22, "IQ2_S", 1024, 37, 3); }); + // the other formats of native_mmvq.cu's lanes kernel + guarded([&] { test_slots_lanes(2, "Q4_0", 2304, 1152, 3); }); + guarded([&] { test_slots_lanes(6, "Q5_0", 1152, 37, 3); }); + guarded([&] { test_slots_lanes(39, "MXFP4", 2880, 2880, 3); }); + guarded([&] { test_slots_lanes(10, "Q2_K", 2304, 1152, 3); }); + guarded([&] { test_slots_lanes(11, "Q3_K", 2304, 37, 3); }); + guarded([&] { test_slots_lanes(12, "Q4_K", 2304, 1152, 3); }); + guarded([&] { test_slots_lanes(13, "Q5_K", 1280, 512, 3); }); + guarded([&] { test_slots_lanes(14, "Q6_K", 2304, 1152, 3); }); + guarded([&] { test_slots_lanes(23, "IQ4_XS", 1536, 2301, 8); }); + for (int rows : {1, 8, 300}) guarded([&] { test_dspark_fuse(rows); }); + guarded([&] { test_block_attend(8, 0, 7, 0); }); + guarded([&] { test_block_attend(8, 0, 1500, 0); }); + guarded([&] { test_block_attend(8, 2000 - 1024, 2007, 1032); }); // the window wraps the ring + guarded([&] { test_block_attend(8, 0, 9000, 0); }); // the most pieces + guarded([&] { test_block_attend(1, 3, 40, 0); }); + guarded([&] { test_dspark_gru(); }); + if (bench) bench_attend(table, dtable), bench_attend_tiers(table, dtable), bench_decode(table, dtable); + cudaFree(dtable); + + ck(cudaDeviceSynchronize(), "final"); + std::printf("%s: %d failure%s\n", failures ? "FAILED" : "PASSED", failures, failures == 1 ? "" : "s"); + return failures ? 1 : 0; +} diff --git a/src/poly/kernels.cu b/src/poly/kernels.cu index 4f312c61c6..e860b5d07b 100644 --- a/src/poly/kernels.cu +++ b/src/poly/kernels.cu @@ -162,56 +162,138 @@ gemm_small_kernel(const float* __restrict__ w, const float* __restrict__ x, floa if (t < rows && o < n_out) y[size_t(t) * n_out + o] = acc; } -// gemm_small_kernel for more outputs (a router's 128 or 256): a block TILE_TOK tokens and TILE_OUT outputs, a thread -// 4 of each, so a value read from shared memory serves 4 products where it served one. For 2,048 tokens of 2,048 -// values and 256 outputs gemm_small_kernel took 0.34 ms on an RTX 5090, 241 ms of the 3.7 s Flint read a prompt of -// 29,816 tokens in. Each output is still one fmaf after the other in the inputs' order: the same bits. -constexpr int TILE_TOK = 32, TILE_OUT = 64, TILE_K = 32; - -__global__ void __launch_bounds__(TILE_TOK * TILE_OUT / 16) +// gemm_small_kernel for more outputs (a router's 128 or 256, the controllers' 64): a block TOK tokens and OUT +// outputs, a thread TT tokens and TO outputs of them, so a value read from shared memory serves TT or TO products +// where it served one. The block takes the inputs K at a time, and reads the inputs and weights of a step two steps +// ahead into registers. Each output is still one fmaf after the other in the inputs' order: the same bits whatever +// the tile. +template +__global__ void __launch_bounds__((TOK / TT) * (OUT / TO)) gemm_tile_kernel(const float* __restrict__ w, const float* __restrict__ x, float* __restrict__ y, int n_in, int n_out, int rows) { - constexpr int THREADS = TILE_TOK * TILE_OUT / 16; - // a step's inputs and weights by input, so a thread reads its 4 tokens' and 4 outputs' values as one float4 - __shared__ __align__(16) float sx[TILE_K][TILE_TOK + 4], sw[TILE_K][TILE_OUT + 4]; - const int t0 = blockIdx.x * TILE_TOK, o0 = blockIdx.y * TILE_OUT; - const int to = 4 * (threadIdx.x / (TILE_OUT / 4)), oo = 4 * (threadIdx.x % (TILE_OUT / 4)); - float acc[4][4]; + constexpr int THREADS = (TOK / TT) * (OUT / TO), XS = TOK * K / THREADS, WS = OUT * K / THREADS; + static_assert(XS * THREADS == TOK * K && WS * THREADS == OUT * K, "a step's values spread over the threads"); + static_assert(TOK % 8 == 0 && OUT % 8 == 0 && (TT == 2 || TT == 4 || TT == 8) && (TO == 2 || TO == 4 || TO == 8), + "rows of a multiple of 4 floats, an odd one of them past a multiple of 32 banks"); + // a step's inputs and weights by input (a row TOK + 4 floats, so a warp's 4 tokens of 8 inputs fill 32 banks), + // twice over + __shared__ __align__(16) float sx[2][K][TOK + 4], sw[2][K][OUT + 4]; + const int t0 = blockIdx.x * TOK, o0 = blockIdx.y * OUT; + // a thread's tokens and outputs: TT (TO) in a row, or two runs of 4 half a tile apart, so that a quarter of a + // warp reads its float4s from 128 bytes in a row + const int tr = threadIdx.x / (OUT / TO), orr = threadIdx.x % (OUT / TO); + const int tb = TT == 8 ? 4 * tr : TT * tr, ob = TO == 8 ? 4 * orr : TO * orr; + constexpr int TH = TT == 8 ? TOK / 2 : 0, OH = TO == 8 ? OUT / 2 : 0; + // what a thread reads of a step: one input of a token (an output) and of every RS-th one on, so that a warp + // reads 4 tokens' (outputs') runs of 8 inputs + static_assert(THREADS % (4 * K) == 0, "a thread's input the same at every place of its step"); + constexpr int RS = THREADS / K; + const int kq = threadIdx.x / 4 % K, rq = threadIdx.x % 4 + 4 * (threadIdx.x / (4 * K)); + const float* const xb = x + size_t(t0) * n_in; + const float* const wb = w + size_t(o0) * n_in; + const int xn = rows - t0, wn = n_out - o0; + // a step's values in registers: two steps' worth, so that what a thread reads has a whole step to arrive + struct Regs { + float x[XS], w[WS]; + } ra, rb; + const auto fetch = [&](Regs& r, int k0) { + const int k = k0 + kq; + const bool in = k < n_in; #pragma unroll - for (int i = 0; i < 4; ++i) + for (int j = 0; j < XS; ++j) { + const int t = rq + j * RS; + r.x[j] = in && t < xn ? xb[t * n_in + k] : 0.0f; + } #pragma unroll - for (int j = 0; j < 4; ++j) acc[i][j] = 0.0f; - for (int k0 = 0; k0 < n_in; k0 += TILE_K) { - for (int i = threadIdx.x; i < TILE_TOK * TILE_K; i += THREADS) { - const int t = t0 + i / TILE_K, k = k0 + i % TILE_K; - sx[i % TILE_K][i / TILE_K] = t < rows && k < n_in ? x[size_t(t) * n_in + k] : 0.0f; + for (int j = 0; j < WS; ++j) { + const int o = rq + j * RS; + r.w[j] = in && o < wn ? wb[o * n_in + k] : 0.0f; } - for (int i = threadIdx.x; i < TILE_OUT * TILE_K; i += THREADS) { - const int o = o0 + i / TILE_K, k = k0 + i % TILE_K; - sw[i % TILE_K][i / TILE_K] = o < n_out && k < n_in ? w[size_t(o) * n_in + k] : 0.0f; + }; + const auto store = [&](const Regs& r, int b) { +#pragma unroll + for (int j = 0; j < XS; ++j) sx[b][kq][rq + j * RS] = r.x[j]; +#pragma unroll + for (int j = 0; j < WS; ++j) sw[b][kq][rq + j * RS] = r.w[j]; + }; + // n floats from 16 (n = 2: 8) bytes on: 4 of them and 4 more `half` floats on for n = 8 + const auto read = [](const float* p, int half, float* v, int n) { + if (n == 2) { + const float2 a = *reinterpret_cast(p); + v[0] = a.x, v[1] = a.y; + return; } - __syncthreads(); + const float4 a = *reinterpret_cast(p); + v[0] = a.x, v[1] = a.y, v[2] = a.z, v[3] = a.w; + if (n == 8) { + const float4 b = *reinterpret_cast(p + half); + v[4] = b.x, v[5] = b.y, v[6] = b.z, v[7] = b.w; + } + }; + float acc[TT][TO]; +#pragma unroll + for (int i = 0; i < TT; ++i) +#pragma unroll + for (int j = 0; j < TO; ++j) acc[i][j] = 0.0f; + // step s works on shared half s % 2, stores step s + 1's values into the other one (read during step s - 1) + // and reads step s + 2's into the registers that held them + const auto step = [&](Regs& next, Regs& later, int k0, int b) { + fetch(next, k0 + 2 * K); #pragma unroll 8 - for (int c = 0; c < TILE_K; ++c) { - const float4 a = *reinterpret_cast(&sx[c][to]); - const float4 b = *reinterpret_cast(&sw[c][oo]); - const float av[4] = {a.x, a.y, a.z, a.w}, bv[4] = {b.x, b.y, b.z, b.w}; + for (int c = 0; c < K; ++c) { + float av[TT], bv[TO]; + read(&sx[b][c][tb], TH, av, TT); + read(&sw[b][c][ob], OH, bv, TO); #pragma unroll - for (int i = 0; i < 4; ++i) + for (int i = 0; i < TT; ++i) #pragma unroll - for (int j = 0; j < 4; ++j) acc[i][j] = fmaf(av[i], bv[j], acc[i][j]); + for (int j = 0; j < TO; ++j) acc[i][j] = fmaf(av[i], bv[j], acc[i][j]); } + store(later, b ^ 1); __syncthreads(); + }; + fetch(ra, 0); + fetch(rb, K); + store(ra, 0); + __syncthreads(); + for (int k0 = 0; k0 < n_in; k0 += 2 * K) { + step(ra, rb, k0, 0); + if (k0 + K < n_in) step(rb, ra, k0 + K, 1); } #pragma unroll - for (int i = 0; i < 4; ++i) + for (int i = 0; i < TT; ++i) #pragma unroll - for (int j = 0; j < 4; ++j) { - const int t = t0 + to + i, o = o0 + oo + j; + for (int j = 0; j < TO; ++j) { + const int t = t0 + tb + (TT == 8 ? i / 4 * TH + i % 4 : i), o = o0 + ob + (TO == 8 ? j / 4 * OH + j % 4 : j); if (t < rows && o < n_out) y[size_t(t) * n_out + o] = acc[i][j]; } } +template +void gemm_tile(const float* w, const float* x, float* y, int n_in, int n_out, int rows, cudaStream_t stream) { + gemm_tile_kernel<<>>(w, x, y, n_in, n_out, rows); +} + +// The largest tile that still gives half the card's SMs a block: more work a block reads its inputs fewer times +// and keeps more threads at work, and a tile half as large is faster where it gives twice the SMs one. On an RTX +// 2070 Super (40 SMs), us a call, against gemm_small_kernel for 64 outputs and the one 32 x 64 tile for 128: +// 4,608 inputs -> 64 (the controllers): 333 rows 360 -> 196, 1,024 rows 826 -> 261, 4,096 rows 3,062 -> 713 +// 2,304 inputs -> 128 (the router): 333 rows 214 -> 131, 1,024 rows 261 -> 202, 4,096 rows 848 -> 579 +// each the fastest of the 19 (64 outputs) and 27 (128) tiles measured there, every one with the same bits. +void gemm_tiles(const float* w, const float* x, float* y, int n_in, int n_out, int rows, cudaStream_t stream) { + int dev = 0, sms = 0; + cudaGetDevice(&dev); + cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev); + const auto blocks = [&](int tok, int out) { + return 2 * ((rows + tok - 1) / tok) * ((n_out + out - 1) / out) >= sms; + }; + if (n_out > 64 && blocks(64, 128)) return gemm_tile<64, 128, 8, 8, 16>(w, x, y, n_in, n_out, rows, stream); + if (blocks(64, 64)) return gemm_tile<64, 64, 8, 4, 16>(w, x, y, n_in, n_out, rows, stream); + if (blocks(32, 64)) return gemm_tile<32, 64, 4, 4, 32>(w, x, y, n_in, n_out, rows, stream); + gemm_tile<32, 32, 2, 4, 32>(w, x, y, n_in, n_out, rows, stream); +} + // Where a row's Q8_1 blocks would keep a sum past the halves' range: a power of two to divide the row by, 1 for // most. The test is on runs of 16 (Q2_K's blocks keep sums of 16, the others of 32) against a quarter of 65504, // so a block of 32 stays under half of it, and on the largest value, whose block delta is a half too. @@ -2689,9 +2771,8 @@ void gemm_f32(void* blas, const float* w, const float* x, float* y, int n_in, in if (groups == 1 && n_out <= 8 * SMALL_OUT) { cudaStream_t stream = nullptr; blas_ck(cublasGetStream(h, &stream), "cublasGetStream"); - if (n_out > 2 * SMALL_OUT) - gemm_tile_kernel<<>>(w, x, y, n_in, n_out, rows); + if (n_out > SMALL_OUT) + gemm_tiles(w, x, y, n_in, n_out, rows, stream); else gemm_small_kernel<<>>(w, x, y, n_in, n_out, rows); diff --git a/src/poly/kernels_inkling.cu b/src/poly/kernels_inkling.cu new file mode 100644 index 0000000000..9210a8c664 --- /dev/null +++ b/src/poly/kernels_inkling.cu @@ -0,0 +1,3576 @@ +// src/poly/kernels_inkling.cu - Inkling 2 Mini's kernels; see include/strata/poly/inkling_kernels.hpp for the math +// and where it comes from. Plain float arithmetic throughout, the caches' halves (or Q8_0 codes) the only rounding, +// but for the prompt batches' attention on the tensor cores (attn_mma_kernel, attn_fa2_kernel), whose products take +// halves. +#include "strata/poly/inkling_kernels.hpp" +#include "strata/kernels/dp4a.hpp" +#include "strata/kernels/native_mmvq.hpp" +#if defined(__HIPCC__) +#include "strata/kernels/gfx_arch.hpp" +#endif + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::poly { +namespace { + +constexpr int WARP = 32; +constexpr int kDevices = 64; // the devices a setting or answer of the card's is kept for + +inline cudaStream_t cs(void* stream) { return (cudaStream_t) stream; } +inline int grid(size_t n, int block) { return int((n + block - 1) / block); } + +void check_launch(const char* what) { + if (const cudaError_t e = cudaGetLastError(); e != cudaSuccess) + throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e)); +} + +__device__ __forceinline__ float warp_sum(float x) { +#pragma unroll + for (int o = WARP / 2; o > 0; o >>= 1) x += __shfl_xor_sync(0xffffffffu, x, o, WARP); + return x; +} + +__device__ __forceinline__ float warp_max(float x) { +#pragma unroll + for (int o = WARP / 2; o > 0; o >>= 1) x = fmaxf(x, __shfl_xor_sync(0xffffffffu, x, o, WARP)); + return x; +} + +__device__ __forceinline__ float sigmoidf(float x) { return 1.0f / (1.0f + expf(-x)); } + +// ---- native_mmvq.cu's arithmetic ------------------------------------------------------------------------------- +// +// native_mmvq.cu is built with --use_fast_math: its float operations flush denormals to zero and its divisions are +// approximate. The launches here that do its Q8_1 quantization or its RMS norm write those operations out as the +// instructions it compiles them to, so that their bits are its bits (this file is built without fast math). A HIP +// build has no PTX and compiles native_mmvq.cu without fast math, so there they are the plain IEEE operations. +namespace fm { +#if defined(__HIPCC__) +__device__ __forceinline__ float add(float a, float b) { return a + b; } +__device__ __forceinline__ float add_rn(float a, float b) { return __fadd_rn(a, b); } +__device__ __forceinline__ float mul_rn(float a, float b) { return __fmul_rn(a, b); } +__device__ __forceinline__ float div_rn(float a, float b) { return __fdiv_rn(a, b); } +__device__ __forceinline__ float div(float a, float b) { return a / b; } +__device__ __forceinline__ float max(float a, float b) { return fmaxf(a, b); } +__device__ __forceinline__ float fma_rn(float a, float b, float c) { return __fmaf_rn(a, b, c); } +__device__ __forceinline__ float sqrt_rn(float a) { return __fsqrt_rn(a); } +__device__ __forceinline__ float abs(float a) { return fabsf(a); } +#else +#define FM_BINARY(name, op) \ + __device__ __forceinline__ float name(float a, float b) { \ + float r; \ + asm(op " %0, %1, %2;" : "=f"(r) : "f"(a), "f"(b)); \ + return r; \ + } +FM_BINARY(add, "add.ftz.f32") // a + b +FM_BINARY(add_rn, "add.rn.ftz.f32") // __fadd_rn +FM_BINARY(mul_rn, "mul.rn.ftz.f32") // __fmul_rn +FM_BINARY(div_rn, "div.rn.ftz.f32") // __fdiv_rn +FM_BINARY(div, "div.approx.ftz.f32") // a / b +FM_BINARY(max, "max.ftz.f32") // fmaxf +#undef FM_BINARY +__device__ __forceinline__ float fma_rn(float a, float b, float c) { // __fmaf_rn + float r; + asm("fma.rn.ftz.f32 %0, %1, %2, %3;" : "=f"(r) : "f"(a), "f"(b), "f"(c)); + return r; +} +__device__ __forceinline__ float sqrt_rn(float a) { // __fsqrt_rn + float r; + asm("sqrt.rn.ftz.f32 %0, %1;" : "=f"(r) : "f"(a)); + return r; +} +__device__ __forceinline__ float abs(float a) { // fabsf + float r; + asm("abs.ftz.f32 %0, %1;" : "=f"(r) : "f"(a)); + return r; +} +#endif +__device__ __forceinline__ float warp_sum(float x) { +#pragma unroll + for (int o = WARP / 2; o > 0; o >>= 1) x = add(x, __shfl_xor_sync(0xffffffffu, x, o, WARP)); + return x; +} +__device__ __forceinline__ float warp_max(float x) { +#pragma unroll + for (int o = WARP / 2; o > 0; o >>= 1) x = max(x, __shfl_xor_sync(0xffffffffu, x, o, WARP)); + return x; +} +constexpr float kHalfMax = 65504.0f; +__device__ __forceinline__ float finite(float v) { return abs(v) > kHalfMax ? copysignf(kHalfMax, v) : v; } + +// A Q8_1 block: native_mmvq.cu's Q81Block. +struct Q81 { + __half2 ds; + int8_t qs[32]; +}; +static_assert(sizeof(Q81) == 36, "a Q8_1 block"); + +// A warp's 32 values, lane i value i of the block, as native_quantize_q8_1_kernel quantizes them (q8_1_finite.hpp's +// scale, value and sums). +__device__ __forceinline__ void q8_1(float xi, Q81* blk) { + const int lane = threadIdx.x % WARP; + const float amax = warp_max(abs(xi)); + const float sum = warp_sum(xi); + const float d = finite(div(amax, 127.0f)); + int8_t q = 0; + if (amax != 0.0f) { + const float r = roundf(div(xi, d)); + q = (int8_t) (r > 127.0f ? 127.0f : r < -127.0f ? -127.0f : r); + } + blk->qs[lane] = q; + if (lane == 0) blk->ds = make_half2(__float2half(finite(d)), __float2half(finite(sum))); +} + +// native_add_rms_norm_q8_1_kernel's row without add: y = x / rms(x) * w and its Q8_1 blocks. The block's +// threads (a multiple of 32, fewer than SUM or not) take the kernel's SUM threads' sums in turn, a warp one of its +// warps; part: SUM / WARP floats of shared memory. +template +__device__ __forceinline__ void rms_norm_q8_1(const float* x, const float* w, float* y, Q81* yq, int n, float eps, + float* part) { + for (int t0 = 0; t0 < SUM; t0 += blockDim.x) { + const int t = t0 + threadIdx.x; + if (t >= SUM) break; + float ss = 0.0f; + for (int i = t; i < n; i += SUM) { + const float v = x[i]; + ss = fma_rn(v, v, ss); + } + ss = warp_sum(ss); + if ((t & 31) == 0) part[t >> 5] = ss; + } + __syncthreads(); + float sum = 0.0f; + for (int k = 0; k < SUM / WARP; ++k) sum = add_rn(sum, part[k]); + const float scale = div_rn(1.0f, sqrt_rn(add_rn(div_rn(sum, float(n)), eps))); + for (int i = threadIdx.x; i < n; i += blockDim.x) { + const float xi = mul_rn(mul_rn(x[i], scale), w[i]); + y[i] = xi; + q8_1(xi, yq + i / 32); + } + __syncthreads(); // part, for a row after this one +} +} // namespace fm + +// upstream: cast(pos) -> scale_bias(1, 1) -> scale(1 / floor) -> clamp(1, inf) -> log -> scale_bias(alpha, 1) +__device__ __forceinline__ float tau_of(float alpha, int floor_, long long p) { + float v = (float) p * 1.0f + 1.0f; + v = v * (1.0f / (float) floor_); + v = v < 1.0f ? 1.0f : v; + return logf(v) * alpha + 1.0f; +} + +// ---- clip ------------------------------------------------------------------------------------------------------ + +// A warp a head of a token. x may be y (a clip in place): it is not __restrict__. +__device__ __forceinline__ void clip_group(const float* x, int x_stride, const float* __restrict__ scale, float* y, + int dim, int heads, int gi, float threshold, float alpha, int floor_, + long long pos) { + const int lane = threadIdx.x % WARP; + const int t = gi / heads, h = gi % heads; + const float* xr = x + size_t(t) * x_stride + size_t(h) * dim; + float* yr = y + (size_t(t) * heads + h) * dim; + const float* sr = scale ? scale + size_t(h) * dim : nullptr; + constexpr int MAXV = 1024 / WARP; + float v[MAXV]; + float ss = 0.0f; +#pragma unroll + for (int k = 0; k < MAXV; ++k) { + const int i = lane + k * WARP; + v[k] = 0.0f; + if (i < dim) { + v[k] = sr ? xr[i] * sr[i] : xr[i]; + ss += v[k] * v[k]; + } + } + ss = warp_sum(ss); + const float norm = sqrtf(ss) + 1e-6f; + const float factor = fminf(fmaxf(threshold / norm, 0.0f), 1.0f); + const float tau = floor_ > 0 ? tau_of(alpha, floor_, pos + t) : 1.0f; +#pragma unroll + for (int k = 0; k < MAXV; ++k) { + const int i = lane + k * WARP; + if (i < dim) yr[i] = floor_ > 0 ? v[k] * factor * tau : v[k] * factor; + } +} + +__global__ void clip_kernel(const float* x, int x_stride, const float* __restrict__ scale, float* y, int dim, + int heads, int groups, float threshold, float alpha, int floor_, long long pos) { + const int gi = blockIdx.x * (blockDim.x / WARP) + threadIdx.x / WARP; + if (gi >= groups) return; + clip_group(x, x_stride, scale, y, dim, heads, gi, threshold, alpha, floor_, pos); +} + +struct ClipJobs { + InklingClipJob j[4]; + int first[5]; // the jobs' first groups, and the end +}; + +// Where a call's tokens are: one sequence's, from a position on (inkling_clip_many()) given by value or read on the +// card when the launch runs, or each row a sequence's of its own at a position of its own (inkling_clip_many_seqs()). +// pos(t) - t is handed to clip_group(), which adds t. +struct ClipFrom { + long long pos; + __device__ long long first(int) const { return pos; } +}; +struct ClipAt { + const long long* at; + __device__ long long first(int) const { return *at; } +}; +struct ClipSeqs { + long long pos[kInklingSeqRows]; + __device__ long long first(int t) const { return pos[t] - t; } +}; + +template +__device__ __forceinline__ void clip_many_group(const ClipJobs& c, int count, const From& from, int gi) { +#pragma unroll + for (int k = 0; k < 4; ++k) { + if (k >= count) return; + if (gi < c.first[k + 1]) { + const InklingClipJob& j = c.j[k]; + const int g = gi - c.first[k]; + clip_group(j.x, j.x_stride ? j.x_stride : j.heads * j.dim, j.scale, j.y, j.dim, j.heads, g, j.threshold, + j.tau.alpha, j.tau.floor, from.first(g / j.heads)); + return; + } + } +} + +template +__global__ void clip_many_kernel(ClipJobs c, int count, From from) { + clip_many_group(c, count, from, blockIdx.x * (blockDim.x / WARP) + threadIdx.x / WARP); +} + +// ---- attention ------------------------------------------------------------------------------------------------- + +constexpr int AT_DIM = 128, AT_PER = 3, AT_KEYS = 32, AT_THREADS = 128, AT_MAX_REL = 32; +constexpr int AT_KPAD = AT_DIM + 1; // a key row in shared memory, padded so that 32 keys are 32 banks +constexpr int AT_MIN_SPLIT = 32; // the split path's smallest split: short contexts still fill the card + +struct AttnArgs { + const float* q; + const half* kc; + const half* vc; + Kvq8 kq; + Kvq8 vq; + InklingRel rel; + const float* sinks; + long long pos; + int rows, n_head, kv_heads, window, ring; + float scale; + int split; // the split path's keys a split (counted from position 0) + int nslot; // the split path's splits a token's partials have room for + int i8_from; // the split path's rows of splits of this many keys or more take attn_dec_i8_kernel (0: none) + float* out; + const float* gate; // the split path's output gate: out = o * sigmoid(gate) (null: none) + void* out_q8_1; // the split path's output's Q8_1 blocks too (null: none) + float* work; +}; + +template +__device__ __forceinline__ float cache_value(const half* c, const Kvq8& q8, size_t i) { + if constexpr (Q8) return (float) q8.codes[i] * __half2float(__ushort_as_half(q8.scales[i / 32])); + else return __half2float(c[i]); +} + +// Ks holds the tile's keys in 4-value blocks, key-major ((d/4) * AT_KEYS + key) * 4 + d % 4, so a thread's four +// consecutive dims of its own key are one 16-byte read and the warp's 32 keys are 32 neighbouring ones; Ps holds the +// tile's scores key-major ([KEYS][R]) so the values' pass reads a row of them at a time. The values are not staged: +// each is used once, and a block reads them coalesced. +constexpr size_t attn_smem(int tq) { + const int r = tq * AT_PER; + return sizeof(float) * (size_t(r) * AT_DIM + AT_KEYS * AT_DIM + size_t(r) * AT_KEYS + size_t(r) * AT_MAX_REL + + 3 * r); +} + +// The unsplit path: a block takes TQ tokens from blockIdx.z * TQ, the PER heads of group blockIdx.y, and all of +// the tokens' keys. The keys go in tiles of AT_KEYS counted from position 0; a row's online softmax only takes +// the keys the row attends, so a key the row does not see changes nothing (its weight is exactly 0 and the row's +// max stays). +template +__global__ void __launch_bounds__(AT_THREADS) attn_kernel(AttnArgs a) { + constexpr int R = TQ * AT_PER; + constexpr int RPT = (R * AT_KEYS + AT_THREADS - 1) / AT_THREADS; // scores a thread per tile + extern __shared__ __align__(16) float smem[]; + float* Qs = smem; // [R][DIM] + float* Ks = Qs + R * AT_DIM; // [DIM / 4][KEYS][4] + float* Ps = Ks + AT_KEYS * AT_DIM; // [KEYS][R] + float* Rs = Ps + R * AT_KEYS; // [R][MAX_REL] + float* Ms = Rs + R * AT_MAX_REL; // [R] + float* Ls = Ms + R; // [R] + float* As = Ls + R; // [R] + + const int tid = threadIdx.x, lane = tid % WARP, warp = tid / WARP; + const int g = blockIdx.y, t0 = blockIdx.z * TQ; + const int nt = min(TQ, a.rows - t0); + const int n_rel = a.rel.n_rel; + const long long p0 = a.pos + t0, plast = p0 + nt - 1; + const long long kb = a.window > 0 && p0 >= a.window ? p0 - a.window + 1 : 0, ke = plast + 1; + + // the queries, their relative-position projections; the rows' running max, sum and output + for (int i = tid; i < R * AT_DIM; i += AT_THREADS) { + const int r = i / AT_DIM, d = i % AT_DIM, t = r / AT_PER, h = g * AT_PER + r % AT_PER; + Qs[i] = t < nt ? a.q[((size_t(t0) + t) * a.n_head + h) * AT_DIM + d] : 0.0f; + } + for (int i = tid; i < R * AT_MAX_REL; i += AT_THREADS) { + const int r = i / AT_MAX_REL, j = i % AT_MAX_REL, t = r / AT_PER, h = g * AT_PER + r % AT_PER; + Rs[i] = t < nt && j < n_rel ? a.rel.r[((size_t(t0) + t) * a.n_head + h) * n_rel + j] : 0.0f; + } + if (tid < R) { + Ms[tid] = -INFINITY; + Ls[tid] = 0.0f; + } + float acc[R]; +#pragma unroll + for (int r = 0; r < R; ++r) acc[r] = 0.0f; + __syncthreads(); + + for (long long kt = kb < ke ? kb / AT_KEYS * AT_KEYS : ke; kt < ke; kt += AT_KEYS) { + // the tile's keys; a key outside [kb, ke) is zeros (its cache row may be anything) + for (int j = 0; j < AT_KEYS; ++j) { + const long long kp = kt + j; + const bool live = kp >= kb && kp < ke; + const long long row = a.ring > 0 ? kp % a.ring : kp; + const size_t base = (size_t(row) * a.kv_heads + g) * AT_DIM + tid; + Ks[(size_t(tid / 4) * AT_KEYS + j) * 4 + tid % 4] = live ? cache_value(a.kc, a.kq, base) : 0.0f; + } + __syncthreads(); + + // scores: a thread has key `lane` of the tile and the rows warp, warp + 4, ...; four dims a read on both + // sides (Qs' row is contiguous, Ks' key is), which is a quarter of the shared-memory reads of one + float s[RPT]; +#pragma unroll + for (int i = 0; i < RPT; ++i) s[i] = 0.0f; +#pragma unroll 1 + for (int d4 = 0; d4 < AT_DIM / 4; ++d4) { + const float4 kv = *reinterpret_cast(Ks + (size_t(d4) * AT_KEYS + lane) * 4); +#pragma unroll + for (int i = 0; i < RPT; ++i) { + const int r = warp + i * (AT_THREADS / WARP); + if (r < R) { + const float4 q = *reinterpret_cast(Qs + r * AT_DIM + 4 * d4); + s[i] += q.x * kv.x; + s[i] += q.y * kv.y; + s[i] += q.z * kv.z; + s[i] += q.w * kv.w; + } + } + } + const long long kp = kt + lane; +#pragma unroll + for (int i = 0; i < RPT; ++i) { + const int r = warp + i * (AT_THREADS / WARP); + if (r >= R) continue; + const int t = r / AT_PER; + const long long p = p0 + t; + const long long dist = p - kp; + const bool seen = t < nt && kp >= kb && kp < ke && dist >= 0 && (a.window <= 0 || dist < a.window); + float v = -INFINITY; + if (seen) { + float bias = 0.0f; + if (dist < a.rel.extent) { + const float* tb = a.rel.table + size_t(dist) * n_rel; + const float* rr = Rs + r * AT_MAX_REL; + for (int j = 0; j < n_rel; ++j) bias += tb[j] * rr[j]; + } + v = s[i] * a.scale + bias; + } + Ps[lane * R + r] = v; + } + __syncthreads(); + + // the online softmax: a warp a row + for (int r = warp; r < R; r += AT_THREADS / WARP) { + const float s = Ps[lane * R + r]; + const float m_old = Ms[r]; + const float m_new = fmaxf(m_old, warp_max(s)); + const float p = s == -INFINITY ? 0.0f : expf(s - m_new); + const float sum = warp_sum(p); + Ps[lane * R + r] = p; + if (lane == 0) { + const float alpha = m_old == -INFINITY ? 0.0f : expf(m_old - m_new); + As[r] = alpha; + Ms[r] = m_new; + Ls[r] = Ls[r] * alpha + sum; + } + } + __syncthreads(); + + // the values: a thread a dimension, every row; the tile's weights are read four rows a time when a key's R + // of them stay 16-byte aligned (TQ 4 and 8; TQ 2's 6 put every other key's 8 bytes off), else one at a time +#pragma unroll + for (int r = 0; r < R; ++r) acc[r] *= As[r]; + for (int j = 0; j < AT_KEYS; ++j) { + const long long kp = kt + j; + const bool live = kp >= kb && kp < ke; + const long long row = a.ring > 0 ? kp % a.ring : kp; + const size_t base = (size_t(row) * a.kv_heads + g) * AT_DIM + tid; + const float v = live ? cache_value(a.vc, a.vq, base) : 0.0f; + const float* pr = Ps + j * R; + int r = 0; + if constexpr (R % 4 == 0) + for (; r < R; r += 4) { + const float4 w = *reinterpret_cast(pr + r); + acc[r] += w.x * v; + acc[r + 1] += w.y * v; + acc[r + 2] += w.z * v; + acc[r + 3] += w.w * v; + } + for (; r < R; ++r) acc[r] += pr[r] * v; + } + __syncthreads(); + } + +#pragma unroll + for (int r = 0; r < R; ++r) { + const int t = r / AT_PER, h = g * AT_PER + r % AT_PER; + if (t >= nt) continue; + const size_t tok = size_t(t0) + t; + const float m = Ms[r], l = Ls[r]; + const float sink = a.sinks ? a.sinks[tok * a.n_head + h] : -INFINITY; + const float mx = fmaxf(m, sink); + const float f = m == -INFINITY ? 0.0f : expf(m - mx); + const float denom = l * f + (sink == -INFINITY ? 0.0f : expf(sink - mx)); + a.out[(tok * a.n_head + h) * AT_DIM + tid] = acc[r] * f / denom; + } +} + +// ---- the same prompt attention on RDNA4's matrix cores (opt-in: STRATA_INKLING_WMMA=1, gfx12, halves' caches) ---- +// +// attn_kernel's block and softmax, with S = Q K^T and O += P V as v_wmma_f32_16x16x16_f16 (wave32) steps: a block is +// WMMA_ROWS rows (21 tokens of the 3-head group blockIdx.y) and a warp owns 16 of them; its key tile of 32 is done as +// two 16-key tiles. gfx12's fragment layout (checked on gfx1201, src/kernels/cuda/qsa_prompt_attn.cu): a lane l holds +// A[l % 16][(l / 16) * 8 + i] and B[(l / 16) * 8 + i][l % 16], and its C/D is D[(l / 16) * 8 + i][l % 16]. +#if defined(__HIPCC__) && (defined(__gfx1200__) || defined(__gfx1201__)) +#define INKLING_WMMA 1 +#else +#define INKLING_WMMA 0 +#endif + +#if INKLING_WMMA +typedef _Float16 wh8 __attribute__((ext_vector_type(8))); +typedef float wf8 __attribute__((ext_vector_type(8))); + +__device__ __forceinline__ wf8 wmma16(wh8 a, wh8 b, wf8 c) { + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c); +} + +__device__ __forceinline__ wf8 wf8_zero() { return wf8{0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; } +#endif + +constexpr int WMMA_WARPS = AT_THREADS / WARP; // 4 +constexpr int WMMA_ROWS = 16 * WMMA_WARPS; // rows (token, head) pairs a block +constexpr int WMMA_TOKENS = WMMA_ROWS / AT_PER; // 21 tokens, the last row unused +constexpr int WMMA_KR = AT_DIM + 8; // a key or value row of shared memory, halves + +constexpr int WMMA_VS = AT_KEYS + 8; // a dim's row of a value tile, halves (16-byte aligned, banks spread) +constexpr std::size_t WMMA_DMAX = 64; // distances a tile's rows can span, at most + +constexpr size_t attn_wmma_smem() { + return sizeof(half) * (size_t(WMMA_ROWS) * AT_DIM + size_t(AT_KEYS) * WMMA_KR + size_t(AT_DIM) * WMMA_VS) + + sizeof(float) * (size_t(WMMA_ROWS) * AT_KEYS + size_t(WMMA_ROWS) * AT_MAX_REL + WMMA_DMAX * AT_MAX_REL + + 3 * WMMA_ROWS); +} + +__global__ void __launch_bounds__(AT_THREADS) attn_wmma_kernel(AttnArgs a) { +#if INKLING_WMMA + extern __shared__ __align__(16) char wsm[]; + half* Qh = reinterpret_cast(wsm); // [ROWS][DIM] + half* ks = Qh + size_t(WMMA_ROWS) * AT_DIM; // [KEYS][KR] + half* vs = ks + size_t(AT_KEYS) * WMMA_KR; // [DIM][VS]: a dim's 32 keys, for B fragments + float* Ps = reinterpret_cast(vs + size_t(AT_DIM) * WMMA_VS); // [ROWS][KEYS] + float* Rh = Ps + size_t(WMMA_ROWS) * AT_KEYS; // [ROWS][MAX_REL] + float* bt = Rh + size_t(WMMA_ROWS) * AT_MAX_REL; // [DIST][MAX_REL], this tile's table rows + float* Ms = bt + WMMA_DMAX * AT_MAX_REL; // [ROWS] + float* Ls = Ms + WMMA_ROWS; + float* As = Ls + WMMA_ROWS; + + const int tid = threadIdx.x, lane = tid % WARP, warp = tid / WARP; + const int col = lane % 16, kh = lane / 16; // a fragment's row (A) or column (B and C), and its k half + const int g = blockIdx.y, t0 = blockIdx.x * WMMA_TOKENS; + const int nt = min(WMMA_TOKENS, a.rows - t0); + const int n_rel = a.rel.n_rel; + const long long p0 = a.pos + t0, plast = p0 + nt - 1; + const long long kb = a.window > 0 && p0 >= a.window ? p0 - a.window + 1 : 0, ke = plast + 1; + const int r0 = 16 * warp + 8 * kh; // this lane's C rows, r0 .. r0 + 7 + + for (int i = tid; i < WMMA_ROWS * AT_DIM; i += AT_THREADS) { + const int r = i / AT_DIM, d = i % AT_DIM, t = r / AT_PER, h = g * AT_PER + r % AT_PER; + Qh[i] = t < nt ? (half) a.q[((size_t(t0) + t) * a.n_head + h) * AT_DIM + d] : (half) 0.0f; + } + for (int i = tid; i < WMMA_ROWS * AT_MAX_REL; i += AT_THREADS) { + const int r = i / AT_MAX_REL, j = i % AT_MAX_REL, t = r / AT_PER, h = g * AT_PER + r % AT_PER; + Rh[i] = t < nt && j < n_rel ? a.rel.r[((size_t(t0) + t) * a.n_head + h) * n_rel + j] : 0.0f; + } + if (tid < WMMA_ROWS) { + Ms[tid] = -INFINITY; + Ls[tid] = 0.0f; + } + wf8 acc[AT_DIM / 16]; +#pragma unroll + for (int j = 0; j < AT_DIM / 16; ++j) acc[j] = wf8_zero(); + __syncthreads(); + + for (long long kt = kb < ke ? kb / AT_KEYS * AT_KEYS : ke; kt < ke; kt += AT_KEYS) { + // the tile's keys and values, halves a row (a key outside [kb, ke) is zeros); the values go by dim, which + // is how a B fragment reads them + for (int j = 0; j < AT_KEYS; ++j) { + const long long kp = kt + j; + const bool live = kp >= kb && kp < ke; + const long long row = a.ring > 0 ? kp % a.ring : kp; + const size_t base = (size_t(row) * a.kv_heads + g) * AT_DIM + tid; + vs[size_t(tid) * WMMA_VS + j] = live ? a.vc[base] : (half) 0.0f; + } + // the keys, eight halves a thread a copy: a key row is contiguous, and a 16-byte copy is one instruction + constexpr int KCH = AT_DIM / 8; + for (int i = tid; i < AT_KEYS * KCH; i += AT_THREADS) { + const int j = i / KCH, c = i % KCH; + const long long kp = kt + j; + const bool live = kp >= kb && kp < ke; + const long long row = a.ring > 0 ? kp % a.ring : kp; + const size_t base = (size_t(row) * a.kv_heads + g) * AT_DIM + size_t(c) * 8; + uint4* dst = reinterpret_cast(ks + j * WMMA_KR + c * 8); + *dst = live ? *reinterpret_cast(a.kc + base) : make_uint4(0, 0, 0, 0); + } + // the table rows the tile's rows and keys can reach: dist = position - key, so [p0 - kt - 31, plast - kt] + const long long dlo = std::max(0, p0 - kt - (AT_KEYS - 1)); + const long long dhi = std::min(a.rel.extent - 1, plast - kt); + const int nd = dhi >= dlo ? int(dhi - dlo + 1) : 0; + for (int i = tid; i < nd * n_rel; i += AT_THREADS) bt[i] = a.rel.table[size_t(dlo + i / n_rel) * n_rel + i % n_rel]; + __syncthreads(); + + // S = Q K^T, a 16-key tile a step: this lane's scores are rows r0..r0+7 at key col +#pragma unroll + for (int t16 = 0; t16 < AT_KEYS / 16; ++t16) { + wf8 s = wf8_zero(); +#pragma unroll + for (int kk = 0; kk < AT_DIM / 16; ++kk) { + const int kd = kk * 16 + 8 * kh; + wh8 q, k; +#pragma unroll + for (int i = 0; i < 8; ++i) { + q[i] = Qh[size_t(16 * warp + col) * AT_DIM + kd + i]; + k[i] = ks[(t16 * 16 + col) * WMMA_KR + kd + i]; + } + s = wmma16(q, k, s); + } + const long long kp = kt + t16 * 16 + col; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int r = r0 + i, t = r / AT_PER; + const long long p = p0 + t, dist = p - kp; + const bool seen = t < nt && kp >= kb && kp < ke && dist >= 0 && (a.window <= 0 || dist < a.window); + float v = -INFINITY; + if (seen) { + float bias = 0.0f; + if (dist < a.rel.extent && dist >= dlo && dist <= dhi) { + const float* tb = bt + size_t(dist - dlo) * n_rel; + const float* rr = Rh + size_t(r) * AT_MAX_REL; + int j = 0; + for (; j + 4 <= n_rel; j += 4) { + const float4 t4 = *reinterpret_cast(tb + j); + const float4 r4 = *reinterpret_cast(rr + j); + bias += t4.x * r4.x; + bias += t4.y * r4.y; + bias += t4.z * r4.z; + bias += t4.w * r4.w; + } + for (; j < n_rel; ++j) bias += tb[j] * rr[j]; + } + v = s[i] * a.scale + bias; + } + Ps[size_t(r) * AT_KEYS + t16 * 16 + col] = v; + } + } + __syncthreads(); + + // the online softmax: a warp a row, a lane a key (attn_kernel's) + for (int r = warp; r < WMMA_ROWS; r += WMMA_WARPS) { + const float s = Ps[size_t(r) * AT_KEYS + lane]; + const float m_old = Ms[r]; + const float m_new = fmaxf(m_old, warp_max(s)); + const float p = s == -INFINITY ? 0.0f : expf(s - m_new); + const float sum = warp_sum(p); + Ps[size_t(r) * AT_KEYS + lane] = p; + if (lane == 0) { + const float alpha = m_old == -INFINITY ? 0.0f : expf(m_old - m_new); + As[r] = alpha; + Ms[r] = m_new; + Ls[r] = Ls[r] * alpha + sum; + } + } + __syncthreads(); + + // O += P V: this lane's rows scaled by their alphas, then two 16-key groups of A fragments and the 16-dim + // slices of the values that go with them +#pragma unroll + for (int i = 0; i < 8; ++i) { + const float al = As[r0 + i]; +#pragma unroll + for (int j = 0; j < AT_DIM / 16; ++j) acc[j][i] *= al; + } +#pragma unroll + for (int kg = 0; kg < AT_KEYS / 16; ++kg) { + wh8 ph; +#pragma unroll + for (int i = 0; i < 8; ++i) ph[i] = (half) Ps[size_t(16 * warp + col) * AT_KEYS + kg * 16 + 8 * kh + i]; +#pragma unroll + for (int j = 0; j < AT_DIM / 16; ++j) { + wh8 v; +#pragma unroll + for (int i = 0; i < 8; ++i) v[i] = vs[size_t(j * 16 + col) * WMMA_VS + kg * 16 + 8 * kh + i]; + acc[j] = wmma16(ph, v, acc[j]); + } + } + __syncthreads(); + } + +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int r = r0 + i, t = r / AT_PER, h = g * AT_PER + r % AT_PER; + if (t >= nt) continue; + const size_t tok = size_t(t0) + t; + const float m = Ms[r], l = Ls[r]; + const float sink = a.sinks ? a.sinks[tok * a.n_head + h] : -INFINITY; + const float mx = fmaxf(m, sink); + const float f = m == -INFINITY ? 0.0f : expf(m - mx); + const float denom = l * f + (sink == -INFINITY ? 0.0f : expf(sink - mx)); +#pragma unroll + for (int j = 0; j < AT_DIM / 16; ++j) + a.out[(tok * a.n_head + h) * AT_DIM + j * 16 + col] = acc[j][i] * f / denom; + } +#else + (void) a; +#if defined(__HIPCC__) + __builtin_trap(); +#else + __trap(); +#endif +#endif +} + +// Whether attn_wmma_kernel runs here: asked for (STRATA_INKLING_WMMA=1), on a card the kernel has its instructions +// for (INKLING_WMMA's archs; the macros are the device pass's alone, so the host asks the card's name), elsewhere +// the kernel being a trap. +bool wmma_attention() { +#if defined(__HIPCC__) + static const bool asked = [] { + const char* v = std::getenv("STRATA_INKLING_WMMA"); + return v != nullptr && *v != '\0' && std::string(v) != "0"; + }(); + if (!asked) return false; + static std::atomic cards[kDevices] = {}; // a device's: 1 gfx12, 2 not, 0 not yet asked + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= kDevices) { + cudaGetLastError(); + return false; + } + int card = cards[dev].load(std::memory_order_relaxed); + if (!card) { + cudaDeviceProp p{}; + const bool gfx12 = cudaGetDeviceProperties(&p, dev) == cudaSuccess && + kernels::gfx_arch_is_gfx12_wmma(p.gcnArchName); + card = gfx12 ? 1 : 2; + cudaGetLastError(); + cards[dev].store(card, std::memory_order_relaxed); + } + return card == 1; +#else + return false; +#endif +} + +void launch_attn_wmma(const AttnArgs& a, int kv_heads, int rows, cudaStream_t st) { + constexpr size_t smem = attn_wmma_smem(); + if constexpr (smem > 48 * 1024) { + static std::atomic set[kDevices] = {}; // the device's own setting: once on each card the calls are for + int dev = 0; + const bool known = cudaGetDevice(&dev) == cudaSuccess && dev >= 0 && dev < kDevices; + if (!known || !set[dev].load(std::memory_order_relaxed)) { + const cudaError_t e = + cudaFuncSetAttribute(attn_wmma_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem); + if (e != cudaSuccess) + throw std::runtime_error(std::string("inkling_attend: shared memory: ") + cudaGetErrorString(e)); + if (known) set[dev].store(true, std::memory_order_relaxed); + } + } + const dim3 g(grid(rows, WMMA_TOKENS), kv_heads); + attn_wmma_kernel<<>>(a); + check_launch("inkling_attend"); +} + +// The split path's rows: a call's tokens one after the other in one sequence (inkling_attend()), or each row a +// sequence's of its own with its own caches, position and splits (inkling_attend_seqs()). AttnArgs::nslot is then +// the most splits of a row, and what a token's partials are strided by. +struct AttnRow { + const half* kc; + const half* vc; + Kvq8 kq, vq; + long long pos; + int split, nslot; +}; +struct AttnOne { + __device__ AttnRow row(const AttnArgs& a, int t) const { + return {a.kc, a.vc, a.kq, a.vq, a.pos + t, a.split, a.nslot}; + } +}; +struct AttnAt { // AttnOne's from the position on the card + const long long* at; + __device__ AttnRow row(const AttnArgs& a, int t) const { + return {a.kc, a.vc, a.kq, a.vq, *at + t, a.split, a.nslot}; + } +}; +struct AttnSeqs { + AttnRow r[kInklingSeqRows]; + __device__ AttnRow row(const AttnArgs&, int t) const { return r[t]; } +}; +// the rows of a call whose splits are of `from` keys or more +inline int rows_from(const AttnOne&, const AttnArgs& a, int ntok, int from) { return a.split >= from ? ntok : 0; } +inline int rows_from(const AttnAt&, const AttnArgs& a, int ntok, int from) { return a.split >= from ? ntok : 0; } +inline int rows_from(const AttnSeqs& s, const AttnArgs&, int ntok, int from) { + int n = 0; + for (int t = 0; t < ntok; ++t) n += s.r[t].split >= from; + return n; +} + +// The splits of a token's head merged, in the splits' order, with its sink. A block a head of a token, a thread a +// value dimension. A row of one split has its output from attn_dec_kernel. +template +__global__ void attn_join_kernel(AttnArgs a, Rows rows) { + const int th = blockIdx.x, d = threadIdx.x; + const int nslot = rows.row(a, th / a.n_head).nslot; + if (nslot <= 1) return; + const float* sinks = a.sinks; + const float* w = a.work + size_t(th) * a.nslot * (AT_DIM + 2); + float mx = sinks ? sinks[th] : -INFINITY; + for (int s = 0; s < nslot; ++s) mx = fmaxf(mx, w[size_t(s) * (AT_DIM + 2)]); + float denom = sinks ? expf(sinks[th] - mx) : 0.0f, sum = 0.0f; + for (int s = 0; s < nslot; ++s) { + const float* ws = w + size_t(s) * (AT_DIM + 2); + if (ws[0] == -INFINITY) continue; + const float f = expf(ws[0] - mx); + denom += ws[1] * f; + sum += ws[2 + d] * f; + } + const size_t i = size_t(th) * AT_DIM + d; + const float o = sum / denom, y = a.gate ? o * sigmoidf(a.gate[i]) : o; + a.out[i] = y; + if (a.out_q8_1) fm::q8_1(y, static_cast(a.out_q8_1) + i / 32); +} + +// The split path's kernel: one token of one group, the keys of one split. No tiles in shared memory and no +// barriers while it walks: each warp takes DEC_KEYS keys at a time (the block's keys go to the warps in turn, +// counted from the split's first key). A key's score is the sum of 32 shares, a share four of its values' dot with +// a head's query (values 4j .. 4j + 3) and bias weight j, added up pairwise as a butterfly over 32 lanes would (j +// with j + 16, then 8 apart, 4, 2, 1). A lane takes the four shares of one key that sum first (j, j + 8, j + 16, +// j + 24), so the four keys' scores are made at once by 8 lanes each with three shuffles a head. Its values: a +// lane four of each key's, as the output is kept. Each warp keeps its own running max, sum and output for the +// group's heads; the warps are merged in their order at the end, and the block's result is the token's output when +// its call has one split, else a partial for attn_join_kernel. Nothing depends on the other tokens of the call. +constexpr int DEC_WARPS = 4, DEC_KEYS = 4, DEC_LANES = WARP / DEC_KEYS; // DEC_LANES: a key's lanes for its score +constexpr int DEC_SHARES = WARP / DEC_LANES; // a lane's shares of a score +static_assert(DEC_WARPS * WARP == AT_DIM, "attn_dec_kernel's merge takes a thread a value dimension"); +static_assert(AT_MAX_REL <= WARP, "a share has one bias weight at most"); + +// Four values of a cache from value i: Q8_0 codes times their block's scale, or halves. +template +__device__ __forceinline__ void load4(const half* c, const Kvq8& q8, size_t i, float* x) { + if constexpr (Q8) { + const int codes = *reinterpret_cast(q8.codes + i); + const float d = __half2float(__ushort_as_half(q8.scales[i / 32])); +#pragma unroll + for (int j = 0; j < 4; ++j) x[j] = (float) (signed char) (codes >> (8 * j)) * d; + } else { + const uint2 bits = *reinterpret_cast(c + i); + const __half2 a = *reinterpret_cast(&bits.x), b = *reinterpret_cast(&bits.y); + x[0] = __low2float(a), x[1] = __high2float(a), x[2] = __low2float(b), x[3] = __high2float(b); + } +} + +template +__global__ void __launch_bounds__(DEC_WARPS * WARP, 5) attn_dec_kernel(AttnArgs a, Rows rows) { + __shared__ float sm_m[DEC_WARPS][AT_PER], sm_l[DEC_WARPS][AT_PER]; + __shared__ float sm_o[DEC_WARPS][AT_PER][AT_DIM]; + __shared__ __align__(16) float sm_q[AT_PER][AT_DIM]; + const int lane = threadIdx.x % WARP, warp = threadIdx.x / WARP; + const int sub = lane % DEC_LANES, mine = lane / DEC_LANES; // the score's lanes: key `mine` of a step + const int g = blockIdx.y, t = blockIdx.z, n_rel = a.rel.n_rel; + const AttnRow r = rows.row(a, t); + if ((int) blockIdx.x >= r.nslot) return; // a row with fewer splits than the call's most + if (a.i8_from > 0 && r.split >= a.i8_from) return; // attn_dec_i8_kernel's row + const int p = int(r.pos); + const int lo = a.window > 0 && p >= a.window ? p - a.window + 1 : 0; + const int s = lo / r.split + blockIdx.x; + const int kb = max(lo, s * r.split), ke = min(p + 1, (s + 1) * r.split); + // the queries in shared memory; share j = sub + DEC_LANES * k of each head's bias weight + float rr[AT_PER][DEC_SHARES], m[AT_PER], l[AT_PER], acc[AT_PER][4]; +#pragma unroll + for (int h = 0; h < AT_PER; ++h) { + const size_t th = size_t(t) * a.n_head + g * AT_PER + h; + sm_q[h][threadIdx.x] = a.q[th * AT_DIM + threadIdx.x]; +#pragma unroll + for (int k = 0; k < DEC_SHARES; ++k) { + const int j = sub + DEC_LANES * k; + rr[h][k] = j < n_rel ? a.rel.r[th * n_rel + j] : 0.0f; + } + m[h] = -INFINITY, l[h] = 0.0f; +#pragma unroll + for (int i = 0; i < 4; ++i) acc[h][i] = 0.0f; + } + // A step of the warp's DEC_KEYS keys from k0, at cache rows from row0. A full step (its keys all live and not + // across a ring's end: all but a split's last) goes without those checks, and a far one (its keys all past the + // bias's extent: most of a long context) loads no bias weights (theirs are 0, as the general step finds). + const size_t key_stride = size_t(a.kv_heads) * AT_DIM; + auto step = [&](int k0, int row0, auto full, auto far) { + constexpr bool FULL = decltype(full)::value, FAR = decltype(far)::value; + size_t at[DEC_KEYS]; // each key's row + bool live[DEC_KEYS]; +#pragma unroll + for (int c = 0; c < DEC_KEYS; ++c) { + if constexpr (FULL) { + at[c] = (size_t(row0) * a.kv_heads + g) * AT_DIM + c * key_stride; + live[c] = true; + } else { + int row = row0 + c; + if (a.ring > 0 && row >= a.ring) row -= a.ring; + at[c] = (size_t(row) * a.kv_heads + g) * AT_DIM; + live[c] = k0 + c < ke; + } + } + // the values: a lane four of each key + float vx[DEC_KEYS][4]; +#pragma unroll + for (int c = 0; c < DEC_KEYS; ++c) { + if (live[c]) { + load4(r.vc, r.vq, at[c] + 4 * lane, vx[c]); + } else { +#pragma unroll + for (int i = 0; i < 4; ++i) vx[c][i] = 0.0f; + } + } + // the score of key `mine`: this lane's four shares of it, as the butterfly's first two rounds add them + float sc[AT_PER]; + { + const int kp = k0 + mine, dist = p - kp; + const bool here = FULL || kp < ke; + const bool near = !FAR && here && dist < a.rel.extent; + size_t base = at[0]; +#pragma unroll + for (int c = 1; c < DEC_KEYS; ++c) + if (mine == c) base = at[c]; + float sh[AT_PER][DEC_SHARES]; +#pragma unroll + for (int k = 0; k < DEC_SHARES; ++k) { + const int j = sub + DEC_LANES * k; + float kx[4]; + if (here) { + load4(r.kc, r.kq, base + 4 * j, kx); + } else { +#pragma unroll + for (int i = 0; i < 4; ++i) kx[i] = 0.0f; + } + const float tb = near && j < n_rel ? a.rel.table[size_t(dist) * n_rel + j] : 0.0f; +#pragma unroll + for (int h = 0; h < AT_PER; ++h) { + const float4 qv = *reinterpret_cast(&sm_q[h][4 * j]); + float d = __fmul_rn(qv.y, kx[1]); // (the first two products: the old kernel's contraction) + d = __fmaf_rn(qv.x, kx[0], d); + d = __fmaf_rn(qv.z, kx[2], d); + d = __fmaf_rn(qv.w, kx[3], d); + sh[h][k] = __fmaf_rn(d, a.scale, __fmul_rn(tb, rr[h][k])); + } + } +#pragma unroll + for (int h = 0; h < AT_PER; ++h) { + // shares j and j + 16, j + 8 and j + 24, then those two + float v = __fadd_rn(__fadd_rn(sh[h][0], sh[h][2]), __fadd_rn(sh[h][1], sh[h][3])); +#pragma unroll + for (int o = DEC_LANES / 2; o > 0; o >>= 1) v = __fadd_rn(v, __shfl_xor_sync(0xffffffffu, v, o, WARP)); + sc[h] = v; + } + } + float s[AT_PER][DEC_KEYS]; +#pragma unroll + for (int h = 0; h < AT_PER; ++h) +#pragma unroll + for (int c = 0; c < DEC_KEYS; ++c) s[h][c] = __shfl_sync(0xffffffffu, sc[h], c * DEC_LANES, WARP); +#pragma unroll + for (int h = 0; h < AT_PER; ++h) { + float mx = -INFINITY; +#pragma unroll + for (int c = 0; c < DEC_KEYS; ++c) + if (live[c]) mx = fmaxf(mx, s[h][c]); + const float m_new = fmaxf(m[h], mx); + if (m_new == -INFINITY) continue; // no live key yet + const float alpha = m[h] == -INFINITY ? 0.0f : expf(m[h] - m_new); + float pc[DEC_KEYS], sum = 0.0f; +#pragma unroll + for (int c = 0; c < DEC_KEYS; ++c) { + pc[c] = live[c] ? expf(s[h][c] - m_new) : 0.0f; + sum = __fadd_rn(sum, pc[c]); + } + m[h] = m_new; + l[h] = __fmaf_rn(l[h], alpha, sum); +#pragma unroll + for (int i = 0; i < 4; ++i) { + float y = __fmaf_rn(acc[h][i], alpha, __fmul_rn(pc[0], vx[0][i])); +#pragma unroll + for (int c = 1; c < DEC_KEYS; ++c) y = __fmaf_rn(pc[c], vx[c][i], y); + acc[h][i] = y; + } + } + }; + __syncthreads(); // the queries + // a ring's wraps are found by comparing, not dividing, as the keys go on + int row0 = kb + warp * DEC_KEYS; + if (a.ring > 0) row0 %= a.ring; + for (int k0 = kb + warp * DEC_KEYS; k0 < ke; k0 += DEC_WARPS * DEC_KEYS) { + const bool full = k0 + DEC_KEYS <= ke && (a.ring <= 0 || row0 + DEC_KEYS <= a.ring); + if (full && p - (k0 + DEC_KEYS - 1) >= a.rel.extent) step(k0, row0, std::true_type{}, std::true_type{}); + else if (full) step(k0, row0, std::true_type{}, std::false_type{}); + else step(k0, row0, std::false_type{}, std::false_type{}); + row0 += DEC_WARPS * DEC_KEYS; + if (a.ring > 0 && row0 >= a.ring) row0 %= a.ring; + } +#pragma unroll + for (int h = 0; h < AT_PER; ++h) { + if (lane == 0) sm_m[warp][h] = m[h], sm_l[warp][h] = l[h]; +#pragma unroll + for (int i = 0; i < 4; ++i) sm_o[warp][h][4 * lane + i] = acc[h][i]; + } + __syncthreads(); + const int d = threadIdx.x; // a thread a value dimension +#pragma unroll + for (int h = 0; h < AT_PER; ++h) { + float M = -INFINITY; +#pragma unroll + for (int w = 0; w < DEC_WARPS; ++w) M = fmaxf(M, sm_m[w][h]); + float L = 0.0f, O = 0.0f; +#pragma unroll + for (int w = 0; w < DEC_WARPS; ++w) { + const float f = sm_m[w][h] == -INFINITY ? 0.0f : expf(sm_m[w][h] - M); + L += sm_l[w][h] * f; + O += sm_o[w][h][d] * f; + } + const size_t th = size_t(t) * a.n_head + g * AT_PER + h; + if (r.nslot > 1) { + float* wp = a.work + (th * a.nslot + blockIdx.x) * (AT_DIM + 2); + if (d == 0) wp[0] = M, wp[1] = L; + wp[2 + d] = O; + } else { + const float sink = a.sinks ? a.sinks[th] : -INFINITY; + const float mx = fmaxf(M, sink); + const float f = M == -INFINITY ? 0.0f : expf(M - mx); + const float denom = L * f + (sink == -INFINITY ? 0.0f : expf(sink - mx)); + const size_t i = th * AT_DIM + d; + const float o = O * f / denom, y = a.gate ? o * sigmoidf(a.gate[i]) : o; + a.out[i] = y; + if (a.out_q8_1) fm::q8_1(y, static_cast(a.out_q8_1) + i / 32); + } + } +} + +// The split path over Q8_0 keys and values with the queries quantized too (inkling_attend()'s int8_dot) for a +// full layer's rows of splits of I8_MIN_SPLIT keys or more: the same splits, partials and join as attn_dec_kernel, +// other arithmetic. A window layer's splits are 32 keys (its window's), so it never comes here: no window, no +// ring. A key's 128 values go to 8 lanes, 16 each (one 16-byte load of its codes), so a warp reads 4 keys at once; +// each 8-lane group takes I8_KEYS keys a step (the block's keys go to the warps in turn, counted from the split's +// first key, and a warp's to its groups in turn) and keeps its own running max, sum and output for the group's +// heads. A score is the sum over the key's 32-value blocks of (its query's codes . the key's codes) * the query +// block's delta * the key block's, the dot of 16 values four __dp4a; the query is quantized here about as +// llama.cpp's flash-attention kernels quantize theirs for a quantized K (delta = the block's largest |value| / 127, +// codes the values times 1 / delta rounded to the nearest, where llama.cpp divides). The groups of a warp are +// merged in their order at the end (lanes 8 and 16 apart), then the warps in theirs through shared memory. +constexpr int I8_WARPS = 4, I8_LANES = 8, I8_KEYS = 2; +// the shortest split it takes (a full layer's room of 32K): attn_dec_kernel was the faster on an RTX 2070 Super for +// window layers (a token at 32767: 19.3 us against 26.3 here) and short rooms (at 4096: 52.3 against 55.0), this +// one from 32K (at 32767: 254 us against 286) +constexpr int I8_MIN_SPLIT = 512; +constexpr int I8_DIMS = AT_DIM / I8_LANES; // a lane's values of a key: half a block +constexpr int I8_WARP_KEYS = WARP / I8_LANES * I8_KEYS; // a warp's keys a step +constexpr int I8_STEP = I8_WARPS * I8_WARP_KEYS; // the block's +constexpr int I8_RELS = (AT_MAX_REL + I8_LANES - 1) / I8_LANES; // a lane's relative-position weights a head +static_assert(I8_WARPS * WARP == AT_DIM, "attn_dec_i8_kernel's merge takes a thread a value dimension"); +static_assert(I8_DIMS * 2 == 32, "a lane's values are half of a Q8_0 block"); + +// Four codes, unscaled, as floats: a code's byte offset by 128 under the bits of 2^23, less 2^23 + 128 (exact). +__device__ __forceinline__ void codes4(int w, float* x) { + const unsigned u = unsigned(w) ^ 0x80808080u; +#pragma unroll + for (int j = 0; j < 4; ++j) x[j] = __uint_as_float(__byte_perm(u, 0x4b000000u, 0x7540 + j)) - 8388736.0f; +} + +template +__global__ void __launch_bounds__(I8_WARPS * WARP) attn_dec_i8_kernel(AttnArgs a, Rows rows) { + __shared__ float sm_m[I8_WARPS][AT_PER], sm_l[I8_WARPS][AT_PER]; + __shared__ float sm_o[I8_WARPS][AT_PER][AT_DIM]; + const int lane = threadIdx.x % WARP, warp = threadIdx.x / WARP, sub = lane % I8_LANES; + const int g = blockIdx.y, t = blockIdx.z, n_rel = a.rel.n_rel; + const AttnRow r = rows.row(a, t); + if ((int) blockIdx.x >= r.nslot || r.split < a.i8_from) return; // fewer splits, or attn_dec_kernel's row + const int p = int(r.pos); + const int kb = blockIdx.x * r.split, ke = min(p + 1, kb + r.split); + // this lane's 16 query values of each head as codes, their block's delta times the score's scale + int qc[AT_PER][I8_DIMS / 4]; + float qd[AT_PER], rr[AT_PER][I8_RELS], m[AT_PER], l[AT_PER], acc[AT_PER][I8_DIMS]; +#pragma unroll + for (int h = 0; h < AT_PER; ++h) { + const size_t th = size_t(t) * a.n_head + g * AT_PER + h; + float x[I8_DIMS], amax = 0.0f; +#pragma unroll + for (int i = 0; i < I8_DIMS / 4; ++i) { + const float4 v = *reinterpret_cast(a.q + th * AT_DIM + I8_DIMS * sub + 4 * i); + x[4 * i] = v.x, x[4 * i + 1] = v.y, x[4 * i + 2] = v.z, x[4 * i + 3] = v.w; + } +#pragma unroll + for (int i = 0; i < I8_DIMS; ++i) amax = fmaxf(amax, fabsf(x[i])); + amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, 1, WARP)); // the block's other half + const float d = amax / 127.0f, id = d > 0.0f ? 1.0f / d : 0.0f; +#pragma unroll + for (int i = 0; i < I8_DIMS / 4; ++i) { + int w = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) w |= (int(roundf(x[4 * i + j] * id)) & 0xff) << (8 * j); + qc[h][i] = w; + } + qd[h] = d * a.scale; +#pragma unroll + for (int i = 0; i < I8_RELS; ++i) { + const int j = sub + I8_LANES * i; + rr[h][i] = j < n_rel ? a.rel.r[th * n_rel + j] : 0.0f; + } + m[h] = -INFINITY, l[h] = 0.0f; +#pragma unroll + for (int i = 0; i < I8_DIMS; ++i) acc[h][i] = 0.0f; + } + int k0 = kb + warp * I8_WARP_KEYS + lane / I8_LANES * I8_KEYS; // this lane's first key + for (int w0 = kb + warp * I8_WARP_KEYS; w0 < ke; w0 += I8_STEP) { + int4 kc[I8_KEYS], vc[I8_KEYS]; + float kd[I8_KEYS], vd[I8_KEYS]; + bool live[I8_KEYS]; +#pragma unroll + for (int c = 0; c < I8_KEYS; ++c) { + live[c] = k0 + c < ke; + const size_t base = (size_t(k0 + c) * a.kv_heads + g) * AT_DIM + I8_DIMS * sub; + if (live[c]) { + kc[c] = *reinterpret_cast(r.kq.codes + base); + vc[c] = *reinterpret_cast(r.vq.codes + base); + kd[c] = __half2float(__ushort_as_half(r.kq.scales[base / 32])); + vd[c] = __half2float(__ushort_as_half(r.vq.scales[base / 32])); + } else { + kc[c] = vc[c] = make_int4(0, 0, 0, 0); + kd[c] = vd[c] = 0.0f; + } + } + // a lane's share of each score: its 16 values' dot, scaled, and its share of the bias for keys near enough + float sc[AT_PER][I8_KEYS]; +#pragma unroll + for (int c = 0; c < I8_KEYS; ++c) +#pragma unroll + for (int h = 0; h < AT_PER; ++h) { + int dot = STRATA_DP4A(qc[h][0], kc[c].x, 0); + dot = STRATA_DP4A(qc[h][1], kc[c].y, dot); + dot = STRATA_DP4A(qc[h][2], kc[c].z, dot); + dot = STRATA_DP4A(qc[h][3], kc[c].w, dot); + sc[h][c] = (float) dot * (qd[h] * kd[c]); + } + if (p - (k0 + I8_KEYS - 1) < a.rel.extent) { // no shuffles in here: the groups may differ +#pragma unroll + for (int c = 0; c < I8_KEYS; ++c) { + const int dist = p - (k0 + c); + if (!live[c] || dist >= a.rel.extent) continue; + const float* tb = a.rel.table + size_t(dist) * n_rel; +#pragma unroll + for (int i = 0; i < I8_RELS; ++i) { + const int j = sub + I8_LANES * i; + if (j < n_rel) { + const float w = tb[j]; +#pragma unroll + for (int h = 0; h < AT_PER; ++h) sc[h][c] += w * rr[h][i]; + } + } + } + } +#pragma unroll + for (int o = I8_LANES / 2; o > 0; o >>= 1) +#pragma unroll + for (int h = 0; h < AT_PER; ++h) +#pragma unroll + for (int c = 0; c < I8_KEYS; ++c) sc[h][c] += __shfl_xor_sync(0xffffffffu, sc[h][c], o, WARP); + // the online softmax, then the values: each key's 16 values converted once for the three heads + float alpha[AT_PER], pv[AT_PER][I8_KEYS]; +#pragma unroll + for (int h = 0; h < AT_PER; ++h) { + float mx = -INFINITY; +#pragma unroll + for (int c = 0; c < I8_KEYS; ++c) + if (live[c]) mx = fmaxf(mx, sc[h][c]); + const float m_new = fmaxf(m[h], mx); + alpha[h] = m[h] == -INFINITY ? 0.0f : expf(m[h] - m_new); + float sum = 0.0f; +#pragma unroll + for (int c = 0; c < I8_KEYS; ++c) { + const float pc = live[c] ? expf(sc[h][c] - m_new) : 0.0f; // m_new is finite with a live key + sum += pc; + pv[h][c] = pc * vd[c]; + } + m[h] = m_new; + l[h] = l[h] * alpha[h] + sum; + } +#pragma unroll + for (int h = 0; h < AT_PER; ++h) +#pragma unroll + for (int i = 0; i < I8_DIMS; ++i) acc[h][i] *= alpha[h]; +#pragma unroll + for (int c = 0; c < I8_KEYS; ++c) { + float x[I8_DIMS]; + codes4(vc[c].x, x), codes4(vc[c].y, x + 4), codes4(vc[c].z, x + 8), codes4(vc[c].w, x + 12); +#pragma unroll + for (int h = 0; h < AT_PER; ++h) +#pragma unroll + for (int i = 0; i < I8_DIMS; ++i) acc[h][i] += pv[h][c] * x[i]; + } + k0 += I8_STEP; + } + // the warp's groups merged: group 0 with 1 and 2 with 3, then the pairs (the earlier group's terms first) +#pragma unroll + for (int o = I8_LANES; o < WARP; o <<= 1) +#pragma unroll + for (int h = 0; h < AT_PER; ++h) { + const float mo = __shfl_xor_sync(0xffffffffu, m[h], o, WARP); + const float lo_ = __shfl_xor_sync(0xffffffffu, l[h], o, WARP); + const bool first = (lane & o) == 0; + const float M = fmaxf(m[h], mo); + const float fa = m[h] == -INFINITY ? 0.0f : expf(m[h] - M); + const float fb = mo == -INFINITY ? 0.0f : expf(mo - M); + const float f0 = first ? fa : fb, f1 = first ? fb : fa; + const float l0 = first ? l[h] : lo_, l1 = first ? lo_ : l[h]; + l[h] = l0 * f0 + l1 * f1; +#pragma unroll + for (int i = 0; i < I8_DIMS; ++i) { + const float ao = __shfl_xor_sync(0xffffffffu, acc[h][i], o, WARP); + const float a0 = first ? acc[h][i] : ao, a1 = first ? ao : acc[h][i]; + acc[h][i] = a0 * f0 + a1 * f1; + } + m[h] = M; + } + if (lane < I8_LANES) { +#pragma unroll + for (int h = 0; h < AT_PER; ++h) { + if (lane == 0) sm_m[warp][h] = m[h], sm_l[warp][h] = l[h]; +#pragma unroll + for (int i = 0; i < I8_DIMS; ++i) sm_o[warp][h][I8_DIMS * sub + i] = acc[h][i]; + } + } + __syncthreads(); + const int d = threadIdx.x; // a thread a value dimension +#pragma unroll + for (int h = 0; h < AT_PER; ++h) { + float M = -INFINITY; +#pragma unroll + for (int w = 0; w < I8_WARPS; ++w) M = fmaxf(M, sm_m[w][h]); + float L = 0.0f, O = 0.0f; +#pragma unroll + for (int w = 0; w < I8_WARPS; ++w) { + const float f = sm_m[w][h] == -INFINITY ? 0.0f : expf(sm_m[w][h] - M); + L += sm_l[w][h] * f; + O += sm_o[w][h][d] * f; + } + const size_t th = size_t(t) * a.n_head + g * AT_PER + h; + if (r.nslot > 1) { + float* wp = a.work + (th * a.nslot + blockIdx.x) * (AT_DIM + 2); + if (d == 0) wp[0] = M, wp[1] = L; + wp[2 + d] = O; + } else { + const float sink = a.sinks ? a.sinks[th] : -INFINITY; + const float mx = fmaxf(M, sink); + const float f = M == -INFINITY ? 0.0f : expf(M - mx); + const float denom = L * f + (sink == -INFINITY ? 0.0f : expf(sink - mx)); + const size_t i = th * AT_DIM + d; + const float o = O * f / denom, y = a.gate ? o * sigmoidf(a.gate[i]) : o; + a.out[i] = y; + if (a.out_q8_1) fm::q8_1(y, static_cast(a.out_q8_1) + i / 32); + } + } +} + +// ---- attention on the tensor cores (a prompt batch) ------------------------------------------------------------- + +// The tensor cores' m16n8k16 step and ldmatrix (kernels.cu's): Turing runs the step as two of k = 8 on the same +// registers. AMD builds and cards before Turing have neither; there the host never launches attn_mma_kernel +// (mma_attention()). +#if defined(__HIPCC__) || (defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 750) +#define INKLING_MMA 0 +#else +#define INKLING_MMA 1 +#endif + +#if INKLING_MMA +__device__ __forceinline__ void mma16816(float* c, const uint32_t* a, const uint32_t* b) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 800 + asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n" + : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) + : "r"(a[0]), "r"(a[1]), "r"(b[0])); + asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n" + : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) + : "r"(a[2]), "r"(a[3]), "r"(b[1])); +#else + asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, " + "{%0,%1,%2,%3};\n" + : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) + : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1])); +#endif +} + +__device__ __forceinline__ void ldmatrix_x4(uint32_t* r, const half* p, bool trans) { + const unsigned a = (unsigned) __cvta_generic_to_shared(p); + if (trans) + asm volatile("ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 {%0,%1,%2,%3}, [%4];\n" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) : "r"(a)); + else + asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) : "r"(a)); +} + +__device__ __forceinline__ uint32_t half2_bits(float lo, float hi) { + const __half2 h = __floats2half2_rn(lo, hi); + return *reinterpret_cast(&h); +} +#endif + +// attn_mma_kernel's shape: MMA_WARPS warps of 16 query rows, row r of the block token r / 3 and head r % 3 of the +// group (MMA_TOKENS tokens; the last row of the last warp is unused), keys MMA_KEYS at a time. +constexpr int MMA_WARPS = 4, MMA_KEYS = 32, MMA_TOKENS = 16 * MMA_WARPS / AT_PER; +constexpr int MMA_KROW = AT_DIM + 8; // a key or value row in shared memory, halves +constexpr int MMA_BIAS = MMA_KEYS + 8; // a warp's distances a tile (5 tokens + keys) +constexpr int MMA_TROW = 16 + 8; // a row of the bias table, halves +constexpr int MMA_SLICE = 16 * (MMA_WARPS - 1) / AT_PER + MMA_BIAS; // the block's distances a tile +static_assert(16 * MMA_WARPS / AT_PER * AT_PER >= 16 * MMA_WARPS - 2, "attn_mma_kernel: at most 2 unused rows"); + +// The unsplit path on the tensor cores, the way kernels.cu's attn_flash128_kernel goes: the queries (scaled to log2 +// units and rounded to halves) stay in registers, a tile's keys and values go to shared memory as halves (a Q8_0 +// cache's codes times their scales, rounded), S = Q K^T and O += P V are m16n8k16 steps that sum floats, and each +// row keeps its online softmax in floats. The relative-position bias is a product too: the warp's rows' R (16 +// values, rounded to halves) times the table's rows of the distances the tile spans (halves), a warp's 16 rows by +// MMA_BIAS distances, put in shared memory as floats and read back at each score's distance. Only the tiles +// that hold a distance below the extent compute it. The tiles are counted from position 0, so a row's sums do +// not depend on the other rows of the block. The sink is added at the end, as one more weight of no value. +template +__global__ void __launch_bounds__(MMA_WARPS * WARP) attn_mma_kernel(AttnArgs a) { +#if INKLING_MMA + __shared__ __align__(16) half ks[MMA_KEYS][MMA_KROW], vs[MMA_KEYS][MMA_KROW]; + __shared__ __align__(16) half slice[MMA_SLICE][MMA_TROW]; + __shared__ __align__(16) float bias[MMA_WARPS][16][MMA_BIAS]; + constexpr float LOG2E = 1.44269504f; + const int lane = threadIdx.x % WARP, w = threadIdx.x / WARP, gid = lane / 4, tig = lane % 4; + const int g = blockIdx.y, t0 = (gridDim.x - 1 - blockIdx.x) * MMA_TOKENS; // the longest blocks first + const int nt = min(MMA_TOKENS, a.rows - t0), wt0 = 16 * w / AT_PER; + const long long p0 = a.pos + t0; + int tok[2], head[2]; // the thread's rows gid and gid + 8 of the warp's, as tokens of the block + bool row_ok[2]; + for (int i = 0; i < 2; ++i) { + const int r = 16 * w + gid + 8 * i; + tok[i] = r / AT_PER; + head[i] = g * AT_PER + r % AT_PER; + row_ok[i] = tok[i] < nt; + } + uint32_t qa[8][4], ra[4]; // a block of 16 values a step, in log2 units; R the same + for (int i = 0; i < 2; ++i) { + const size_t th = (size_t(t0) + tok[i]) * a.n_head + head[i]; + for (int u = 0; u < 2; ++u) { // values 2 tig.. and 8 + 2 tig.. of each block of 16 + for (int k = 0; k < 8; ++k) { + float2 x = make_float2(0.0f, 0.0f); + if (row_ok[i]) x = *reinterpret_cast(a.q + th * AT_DIM + 16 * k + 8 * u + 2 * tig); + qa[k][i + 2 * u] = half2_bits(x.x * a.scale * LOG2E, x.y * a.scale * LOG2E); + } + const float* rr = a.rel.r + th * 16 + 8 * u + 2 * tig; + ra[i + 2 * u] = row_ok[i] ? half2_bits(rr[0] * LOG2E, rr[1] * LOG2E) : 0u; + } + } + float o[16][4], m[2] = {-INFINITY, -INFINITY}, l[2] = {0.0f, 0.0f}; + for (int n = 0; n < 16; ++n) o[n][0] = o[n][1] = o[n][2] = o[n][3] = 0.0f; + // the block's tokens attend positions [lo, hi): from the first one's window to the last one + const long long hi = p0 + nt, lo = a.window > 0 ? max(0LL, p0 - a.window + 1) : 0; + for (long long k0 = lo / MMA_KEYS * MMA_KEYS; k0 < hi; k0 += MMA_KEYS) { + __syncthreads(); // the last tile's keys, values and bias are read + // the tile's keys and values, 8 values a thread at a time; positions outside [lo, hi) are zeros (their + // cache rows may be anything), which no weight reads + for (int i = threadIdx.x; i < MMA_KEYS * AT_DIM / 8; i += MMA_WARPS * WARP) { + const int r = i / (AT_DIM / 8), c = 8 * (i % (AT_DIM / 8)); + const long long key = k0 + r; + uint4 kx = make_uint4(0, 0, 0, 0), vx = kx; + if (key >= lo && key < hi) { + const size_t at = (size_t(a.ring > 0 ? key % a.ring : key) * a.kv_heads + g) * AT_DIM + c; + const auto load = [&](const half* f16, const Kvq8& q8, bool quant) { + if (!quant) return *reinterpret_cast(f16 + at); + const uint2 codes = *reinterpret_cast(q8.codes + at); + const float d = __half2float(__ushort_as_half(q8.scales[at / 32])); + uint32_t h[4]; + for (int j = 0; j < 4; ++j) { + const uint32_t word = j < 2 ? codes.x : codes.y, sh = 16 * (j % 2); + h[j] = half2_bits((float) (signed char) (word >> sh) * d, + (float) (signed char) (word >> (sh + 8)) * d); + } + return make_uint4(h[0], h[1], h[2], h[3]); + }; + kx = load(a.kc, a.kq, KQ8); + vx = load(a.vc, a.vq, VQ8); + } + *reinterpret_cast(&ks[r][c]) = kx; + *reinterpret_cast(&vs[r][c]) = vx; + } + // the table's rows of the block's distances d = p0 - (k0 + MMA_KEYS - 1) + e, zeros past the extent and + // before 0 (the padded row, and keys after the token, which the mask removes) + const long long d0 = p0 - (k0 + MMA_KEYS - 1); + const bool near = d0 < a.rel.extent; + if (near) + for (int i = threadIdx.x; i < MMA_SLICE * 8; i += MMA_WARPS * WARP) { + const int e = i / 8, j = 2 * (i % 8); + const long long d = d0 + e; + float2 x = make_float2(0.0f, 0.0f); + if (d >= 0 && d < a.rel.extent) x = *reinterpret_cast(a.rel.table + d * 16 + j); + *reinterpret_cast(&slice[e][j]) = half2_bits(x.x, x.y); + } + __syncthreads(); + float s[MMA_KEYS / 8][4]; + for (int n = 0; n < MMA_KEYS / 8; ++n) { + s[n][0] = s[n][1] = s[n][2] = s[n][3] = 0.0f; + for (int k = 0; k < 8; k += 2) { + uint32_t b[4]; // keys 8 n.., values 16 k.. and 16 (k + 1).. + ldmatrix_x4(b, &ks[8 * n + lane % 8][16 * k + 8 * (lane / 8)], false); + mma16816(s[n], qa[k], b); + mma16816(s[n], qa[k + 1], b + 2); + } + } + if (near) { + // the warp's rows times its distances: column e is distance p0 + wt0 - (k0 + MMA_KEYS - 1) + e + for (int n = 0; n < MMA_BIAS / 8; ++n) { + const half* tr = &slice[wt0 + 8 * n + gid][2 * tig]; + const uint32_t b[2] = {*reinterpret_cast(tr), + *reinterpret_cast(tr + 8)}; + float c[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + mma16816(c, ra, b); + *reinterpret_cast(&bias[w][gid][8 * n + 2 * tig]) = make_float2(c[0], c[1]); + *reinterpret_cast(&bias[w][gid + 8][8 * n + 2 * tig]) = make_float2(c[2], c[3]); + } + __syncwarp(); + } + for (int i = 0; i < 2; ++i) { + const long long own = p0 + tok[i]; // the row's token attends positions (own - window, own] + const int e0 = tok[i] - wt0 + MMA_KEYS - 1; + float mx = -INFINITY; + for (int n = 0; n < MMA_KEYS / 8; ++n) + for (int j = 2 * i; j < 2 * i + 2; ++j) { + const int c = 8 * n + 2 * tig + j % 2; + const long long key = k0 + c; + if (!row_ok[i] || key > own || (a.window > 0 && key <= own - a.window)) + s[n][j] = -INFINITY; + else if (near) + s[n][j] += bias[w][gid + 8 * i][e0 - c]; + mx = fmaxf(mx, s[n][j]); + } + mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, 1)); + mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, 2)); + const float now = fmaxf(m[i], mx), base = now == -INFINITY ? 0.0f : now; + const float f = exp2f(m[i] - base); + m[i] = now; + l[i] *= f; + for (int n = 0; n < 16; ++n) { + o[n][2 * i] *= f; + o[n][2 * i + 1] *= f; + } + for (int n = 0; n < MMA_KEYS / 8; ++n) + for (int j = 2 * i; j < 2 * i + 2; ++j) { + s[n][j] = exp2f(s[n][j] - base); + l[i] += s[n][j]; + } + } + for (int k = 0; k < MMA_KEYS / 16; ++k) { // keys 16 k..: the weights as an A fragment + const uint32_t pa[4] = {half2_bits(s[2 * k][0], s[2 * k][1]), half2_bits(s[2 * k][2], s[2 * k][3]), + half2_bits(s[2 * k + 1][0], s[2 * k + 1][1]), + half2_bits(s[2 * k + 1][2], s[2 * k + 1][3])}; + for (int n = 0; n < 16; n += 2) { + uint32_t b[4]; // keys 16 k.., values 8 n.. and 8 (n + 1).. + ldmatrix_x4(b, &vs[16 * k + lane % 8 + 8 * (lane / 8 % 2)][8 * n + 8 * (lane / 16)], true); + mma16816(o[n], pa, b); + mma16816(o[n + 1], pa, b + 2); + } + } + } + for (int i = 0; i < 2; ++i) { + l[i] += __shfl_xor_sync(0xffffffffu, l[i], 1); + l[i] += __shfl_xor_sync(0xffffffffu, l[i], 2); + if (!row_ok[i]) continue; + const size_t th = (size_t(t0) + tok[i]) * a.n_head + head[i]; + float f = 1.0f; + if (a.sinks) { // the sink, in log2 units like the scores + const float sink = a.sinks[th] * LOG2E, now = fmaxf(m[i], sink); + f = exp2f(m[i] - now); + l[i] = l[i] * f + exp2f(sink - now); + } + float* y = a.out + th * AT_DIM + 2 * tig; + for (int n = 0; n < 16; ++n) + *reinterpret_cast(y + 8 * n) = make_float2(o[n][2 * i] * f / l[i], o[n][2 * i + 1] * f / l[i]); + } +#else + (void) a; // never launched without the tensor cores (mma_attention()) +#endif +} + +// Whether attn_mma_kernel runs as such here: built for Turing or newer, and not from an older card's PTX compiled +// for this one (whose instructions are that card's). +bool mma_attention() { +#if defined(__HIPCC__) + return false; +#else + static std::atomic cards[kDevices] = {}; // a device's: 1 yes, 2 no, 0 not yet asked + int dev = 0; + const bool known = cudaGetDevice(&dev) == cudaSuccess && dev >= 0 && dev < kDevices; + if (known) + if (const int card = cards[dev].load(std::memory_order_relaxed)) return card == 1; + cudaFuncAttributes fa{}; + const cudaError_t e = cudaFuncGetAttributes(&fa, attn_mma_kernel); + if (e != cudaSuccess) cudaGetLastError(); + const bool on = e == cudaSuccess && fa.ptxVersion >= 75; + if (known) cards[dev].store(on ? 1 : 2, std::memory_order_relaxed); + return on; +#endif +} + +// ---- attention on the tensor cores, cards that sum fp16 products into floats at full rate ----------------------- + +// attn_fa2_kernel's shape: W warps of 32 query rows (two m16 tiles that share each key and value fragment), row r +// of the block token r / 3 and head r % 3 of the group (fa_tokens(W) tokens; the last row or two unused), keys +// MMA_KEYS at a time, the next tile copied in while the warps work on this one. +__host__ __device__ constexpr int fa_tokens(int w) { return 32 * w / AT_PER; } +// the block's distances a tile +__host__ __device__ constexpr int fa_slice(int w) { return 16 * (2 * w - 1) / AT_PER + MMA_BIAS; } +constexpr int FA_QROW = AT_DIM + 8; // a query row, halves + +// A tile's keys or values in shared memory: S stages of halves (2: the next tile comes in while the warps work on +// this one), or for a Q8_0 cache S stages of codes and scales and the halves of the one being read. +template +struct FaTile { + half h[S][MMA_KEYS][MMA_KROW]; +}; +template +struct FaTile { + half h[1][MMA_KEYS][MMA_KROW]; + int8_t c[S][MMA_KEYS][AT_DIM]; + uint16_t d[S][MMA_KEYS][AT_DIM / 32]; +}; +template +struct __align__(16) FaSmem { + FaTile k; + FaTile v; + half q[32 * W][FA_QROW]; // the rows' queries, in log2 units + half r[32 * W][MMA_TROW]; // the rows' R, in log2 units + float slice[S][fa_slice(W)][16]; // the table's rows of the tile's distances, as stored + float bias[W][16][MMA_BIAS]; // an m16 tile's rows times its distances +}; + +#if INKLING_MMA +// cp.async from Ampere on, zeros where !fill; a plain copy before (a test's only: the host takes attn_fa2_kernel +// only on the cards fa2_attention() names) +__device__ __forceinline__ void copy16(void* dst, const void* src, bool fill) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 + asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;\n" + ::"r"((unsigned) __cvta_generic_to_shared(dst)), "l"(src), "r"(fill ? 16 : 0) : "memory"); +#else + *reinterpret_cast(dst) = fill ? *reinterpret_cast(src) : make_uint4(0, 0, 0, 0); +#endif +} + +__device__ __forceinline__ void copy8(void* dst, const void* src, bool fill) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 + asm volatile("cp.async.ca.shared.global [%0], [%1], 8, %2;\n" + ::"r"((unsigned) __cvta_generic_to_shared(dst)), "l"(src), "r"(fill ? 8 : 0) : "memory"); +#else + *reinterpret_cast(dst) = fill ? *reinterpret_cast(src) : make_uint2(0, 0); +#endif +} + +__device__ __forceinline__ void copy_wait() { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 + asm volatile("cp.async.wait_all;\n" ::: "memory"); +#endif +} + +// The keys or values of positions k0.. into stage st, zeros outside [lo, hi) (their cache rows may be anything) +template +__device__ __forceinline__ void fa_load(FaTile& t, int st, const half* f16, const Kvq8& q8, const AttnArgs& a, + int g, long long k0, long long lo, long long hi) { + constexpr int PER = Q8 ? 16 : 8; // values a copy + for (int i = threadIdx.x; i < MMA_KEYS * AT_DIM / PER; i += W * WARP) { + const int r = i / (AT_DIM / PER), c = PER * (i % (AT_DIM / PER)); + const long long key = k0 + r; + const bool in = key >= lo && key < hi; + const size_t at = (size_t(in ? (a.ring > 0 ? key % a.ring : key) : 0) * a.kv_heads + g) * AT_DIM; + if constexpr (Q8) { + copy16(&t.c[st][r][c], q8.codes + at + c, in); + if (c == 0) copy8(&t.d[st][r][0], q8.scales + at / 32, in); + } else { + copy16(&t.h[st][r][c], f16 + at + c, in); + } + } +} + +// A Q8_0 stage's codes times their scales, as halves: half(c) * d rounds the exact product once, as attn_mma_kernel's +// float(c) * d -> half does +template +__device__ __forceinline__ void fa_convert(FaTile& t, int st) { + for (int i = threadIdx.x; i < MMA_KEYS * AT_DIM / 8; i += W * WARP) { + const int r = i / (AT_DIM / 8), c = 8 * (i % (AT_DIM / 8)); + const uint2 codes = *reinterpret_cast(&t.c[st][r][c]); + const __half2 d = __half2half2(__ushort_as_half(t.d[st][r][c / 32])); + uint32_t h[4]; + for (int j = 0; j < 4; ++j) { // 0x64xx is the half 1024 + xx; xx = c + 128 + const uint32_t x = __byte_perm((j < 2 ? codes.x : codes.y) ^ 0x80808080u, 0x64646464u, + j % 2 ? 0x4342 : 0x4140); + const __half2 c1 = __hsub2_rn(*reinterpret_cast(&x), __float2half2_rn(1152.0f)); + const __half2 v = __hmul2_rn(c1, d); + h[j] = *reinterpret_cast(&v); + } + *reinterpret_cast(&t.h[0][r][c]) = make_uint4(h[0], h[1], h[2], h[3]); + } +} +#endif + +// attn_mma_kernel's arithmetic, row for row, for blocks of 32 rows a warp (256 with 8 warps): each key and value +// fragment feeds two m16 tiles, the tiles come in by cp.async while the last one is worked on, a Q8_0 tile becomes +// halves once for the block, and only the m16 tiles a tile's diagonal, window edge or unused rows cross test each +// score. Every row takes the same 32-key tiles from position 0, the same steps in the same order and the same +// roundings as attn_mma_kernel's (the online softmax's sums written out as that kernel's compile to), so the two give +// the same bits: the tiles one kernel walks and the other skips hold no key of the row, and change nothing in it; a +// bias of the table's zero rows (past the extent) would only add zeros. +// Whether code built for `arch` (a __CUDA_ARCH__) has attn_fa2_kernel's body: the tensor cores' (Turing on), and +// for 8 warps the shared memory (fa_smem) of the cards of that architecture, which sm_80, sm_87, sm_90 and sm_100 +// have and Turing and the cards of up to 99 KB a block (sm_86, sm_89, sm_120) do not. The host asks it of the code +// the card runs (fa2_card()), which can be another architecture's: sm_86's on an sm_87 card, sm_75's PTX on an A100. +__host__ __device__ constexpr bool fa_fits(int arch, int w) { + return arch >= 750 && (w < 8 || (arch >= 800 && arch != 860 && arch != 890 && arch < 1200)); +} + +template +__device__ __forceinline__ void attn_fa2(const AttnArgs& a) { +#if INKLING_MMA + constexpr int FA_TOKENS = fa_tokens(W), FA_SLICE = fa_slice(W); + extern __shared__ __align__(16) unsigned char fa_raw[]; + FaSmem& sm = *reinterpret_cast*>(fa_raw); + constexpr float LOG2E = 1.44269504f; + const int lane = threadIdx.x % WARP, w = threadIdx.x / WARP, gid = lane / 4, tig = lane % 4; + const int g = blockIdx.y, t0 = (gridDim.x - 1 - blockIdx.x) * FA_TOKENS; // the longest blocks first + const int nt = min(FA_TOKENS, a.rows - t0); + const long long p0 = a.pos + t0; + int tok[2][2], wt0[2], wt1[2]; // the thread's rows gid and gid + 8 of each m16 tile; a tile's first and last + bool row_ok[2][2]; + #pragma unroll + for (int mt = 0; mt < 2; ++mt) { + const int r0 = 16 * (2 * w + mt); + wt0[mt] = r0 / AT_PER; + wt1[mt] = (r0 + 15) / AT_PER; + #pragma unroll + for (int i = 0; i < 2; ++i) { + const int r = r0 + gid + 8 * i; + tok[mt][i] = r / AT_PER; + row_ok[mt][i] = tok[mt][i] < nt; + const size_t th = (size_t(t0) + tok[mt][i]) * a.n_head + g * AT_PER + r % AT_PER; + #pragma unroll + for (int u = 0; u < 2; ++u) { + #pragma unroll + for (int k = 0; k < 8; ++k) { + float2 x = make_float2(0.0f, 0.0f); + if (row_ok[mt][i]) + x = *reinterpret_cast(a.q + th * AT_DIM + 16 * k + 8 * u + 2 * tig); + *reinterpret_cast(&sm.q[r][16 * k + 8 * u + 2 * tig]) = + half2_bits(x.x * a.scale * LOG2E, x.y * a.scale * LOG2E); + } + const float* rr = a.rel.r + th * 16 + 8 * u + 2 * tig; + *reinterpret_cast(&sm.r[r][8 * u + 2 * tig]) = + row_ok[mt][i] ? half2_bits(rr[0] * LOG2E, rr[1] * LOG2E) : 0u; + } + } + } + float o[2][16][4], m[2][2], l[2][2]; + #pragma unroll + for (int mt = 0; mt < 2; ++mt) { + m[mt][0] = m[mt][1] = -INFINITY; + l[mt][0] = l[mt][1] = 0.0f; + #pragma unroll + for (int n = 0; n < 16; ++n) o[mt][n][0] = o[mt][n][1] = o[mt][n][2] = o[mt][n][3] = 0.0f; + } + const long long hi = p0 + nt, lo = a.window > 0 ? max(0LL, p0 - a.window + 1) : 0; + const long long first = lo / MMA_KEYS * MMA_KEYS; + const int tiles = (int) ((hi - first + MMA_KEYS - 1) / MMA_KEYS); + const auto load = [&](int it) { + const long long k0 = first + (long long) it * MMA_KEYS, d0 = p0 - (k0 + MMA_KEYS - 1); + const int st = it % S; + fa_load(sm.k, st, a.kc, a.kq, a, g, k0, lo, hi); + fa_load(sm.v, st, a.vc, a.vq, a, g, k0, lo, hi); + if (d0 < a.rel.extent) // the table's rows of distances d0 + e, zeros past the extent and before 0 + for (int i = threadIdx.x; i < FA_SLICE * 4; i += W * WARP) { + const long long d = d0 + i / 4; + const bool in = d >= 0 && d < a.rel.extent; + copy16(&sm.slice[st][i / 4][4 * (i % 4)], a.rel.table + (in ? d : 0) * 16 + 4 * (i % 4), in); + } + }; + if constexpr (S > 1) load(0); + for (int it = 0; it < tiles; ++it) { + const long long k0 = first + (long long) it * MMA_KEYS, d0 = p0 - (k0 + MMA_KEYS - 1); + const int st = it % S; + if constexpr (S == 1) { // one stage: the last tile is read, then this one comes in + if (it > 0) __syncthreads(); + load(it); + } + copy_wait(); + __syncthreads(); // this tile is in; the last one is read, so its stage takes the next + if (S > 1 && it + 1 < tiles) load(it + 1); + if constexpr (KQ8) fa_convert(sm.k, st); + if constexpr (VQ8) fa_convert(sm.v, st); + if constexpr (KQ8 || VQ8) __syncthreads(); + const half(*kt)[MMA_KROW] = sm.k.h[KQ8 ? 0 : st]; + const half(*vt)[MMA_KROW] = sm.v.h[VQ8 ? 0 : st]; + // per m16 tile: whether a row of it sees a key of the tile, whether some do not see some (a score test + // each), whether a distance is below the extent + bool act[2], edge[2], near[2]; + #pragma unroll + for (int mt = 0; mt < 2; ++mt) { + const long long own0 = p0 + wt0[mt], own1 = p0 + wt1[mt]; + act[mt] = wt0[mt] < nt && k0 <= own1 && (a.window <= 0 || k0 + MMA_KEYS - 1 > own0 - a.window); + edge[mt] = wt1[mt] >= nt || k0 + MMA_KEYS - 1 > own0 || (a.window > 0 && k0 <= own1 - a.window); + near[mt] = d0 + wt0[mt] < a.rel.extent; + } + if (!act[0] && !act[1]) continue; + float s[2][MMA_KEYS / 8][4]; +#pragma unroll + for (int mt = 0; mt < 2; ++mt) +#pragma unroll + for (int n = 0; n < MMA_KEYS / 8; ++n) s[mt][n][0] = s[mt][n][1] = s[mt][n][2] = s[mt][n][3] = 0.0f; +#pragma unroll + for (int k = 0; k < 8; k += 2) { + uint32_t qf[2][2][4]; // the rows' values 16 k.. and 16 (k + 1).. +#pragma unroll + for (int mt = 0; mt < 2; ++mt) +#pragma unroll + for (int h = 0; h < 2; ++h) + if (act[mt]) + ldmatrix_x4(qf[mt][h], &sm.q[16 * (2 * w + mt) + lane % 16][16 * (k + h) + 8 * (lane / 16)], + false); +#pragma unroll + for (int n = 0; n < MMA_KEYS / 8; ++n) { + uint32_t b[4]; // keys 8 n.., values 16 k.. and 16 (k + 1).. + ldmatrix_x4(b, &kt[8 * n + lane % 8][16 * k + 8 * (lane / 8)], false); +#pragma unroll + for (int mt = 0; mt < 2; ++mt) + if (act[mt]) { + mma16816(s[mt][n], qf[mt][0], b); + mma16816(s[mt][n], qf[mt][1], b + 2); + } + } + } +#pragma unroll + for (int mt = 0; mt < 2; ++mt) { + if (!act[mt]) continue; + if (near[mt]) { // column e is distance p0 + wt0 - (k0 + MMA_KEYS - 1) + e + uint32_t ra[4]; + ldmatrix_x4(ra, &sm.r[16 * (2 * w + mt) + lane % 16][8 * (lane / 16)], false); + #pragma unroll + for (int n = 0; n < MMA_BIAS / 8; ++n) { + const float* tr = &sm.slice[st][wt0[mt] + 8 * n + gid][2 * tig]; + const uint32_t b[2] = {half2_bits(tr[0], tr[1]), half2_bits(tr[8], tr[9])}; + float c[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + mma16816(c, ra, b); + *reinterpret_cast(&sm.bias[w][gid][8 * n + 2 * tig]) = make_float2(c[0], c[1]); + *reinterpret_cast(&sm.bias[w][gid + 8][8 * n + 2 * tig]) = make_float2(c[2], c[3]); + } + __syncwarp(); + } + #pragma unroll + for (int i = 0; i < 2; ++i) { + const int own = (int) (p0 + tok[mt][i] - k0); // the row's position, from the tile's first key + const int e0 = tok[mt][i] - wt0[mt] + MMA_KEYS - 1; + const float* bias = sm.bias[w][gid + 8 * i]; + float mx = -INFINITY; + #pragma unroll + for (int n = 0; n < MMA_KEYS / 8; ++n) + #pragma unroll + for (int j = 2 * i; j < 2 * i + 2; ++j) { + const int c = 8 * n + 2 * tig + j % 2; + if (edge[mt] && (!row_ok[mt][i] || c > own || (a.window > 0 && c <= own - a.window))) + s[mt][n][j] = -INFINITY; + else if (near[mt]) + s[mt][n][j] = __fadd_rn(s[mt][n][j], bias[e0 - c]); + mx = fmaxf(mx, s[mt][n][j]); + } + mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, 1)); + mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, 2)); + const float now = fmaxf(m[mt][i], mx), base = now == -INFINITY ? 0.0f : now; + const float f = exp2f(__fsub_rn(m[mt][i], base)); + m[mt][i] = now; + #pragma unroll + for (int n = 0; n < 16; ++n) { + o[mt][n][2 * i] = __fmul_rn(o[mt][n][2 * i], f); + o[mt][n][2 * i + 1] = __fmul_rn(o[mt][n][2 * i + 1], f); + } + #pragma unroll + for (int n = 0; n < MMA_KEYS / 8; ++n) + #pragma unroll + for (int j = 2 * i; j < 2 * i + 2; ++j) { + s[mt][n][j] = exp2f(__fsub_rn(s[mt][n][j], base)); + l[mt][i] = n == 0 && j == 2 * i ? __fmaf_rn(l[mt][i], f, s[mt][n][j]) + : __fadd_rn(l[mt][i], s[mt][n][j]); + } + } + if (near[mt]) __syncwarp(); // the buffer is read before the other m16 tile writes it + } + #pragma unroll + for (int k = 0; k < MMA_KEYS / 16; ++k) { // keys 16 k..: the weights as an A fragment + uint32_t pa[2][4]; + #pragma unroll + for (int mt = 0; mt < 2; ++mt) { + pa[mt][0] = half2_bits(s[mt][2 * k][0], s[mt][2 * k][1]); + pa[mt][1] = half2_bits(s[mt][2 * k][2], s[mt][2 * k][3]); + pa[mt][2] = half2_bits(s[mt][2 * k + 1][0], s[mt][2 * k + 1][1]); + pa[mt][3] = half2_bits(s[mt][2 * k + 1][2], s[mt][2 * k + 1][3]); + } + #pragma unroll + for (int n = 0; n < 16; n += 2) { + uint32_t b[4]; // keys 16 k.., values 8 n.. and 8 (n + 1).. + ldmatrix_x4(b, &vt[16 * k + lane % 8 + 8 * (lane / 8 % 2)][8 * n + 8 * (lane / 16)], true); + #pragma unroll + for (int mt = 0; mt < 2; ++mt) + if (act[mt]) { + mma16816(o[mt][n], pa[mt], b); + mma16816(o[mt][n + 1], pa[mt], b + 2); + } + } + } + } + #pragma unroll + for (int mt = 0; mt < 2; ++mt) + #pragma unroll + for (int i = 0; i < 2; ++i) { + l[mt][i] = __fadd_rn(l[mt][i], __shfl_xor_sync(0xffffffffu, l[mt][i], 1)); + l[mt][i] = __fadd_rn(l[mt][i], __shfl_xor_sync(0xffffffffu, l[mt][i], 2)); + if (!row_ok[mt][i]) continue; + const int r = 16 * (2 * w + mt) + gid + 8 * i; + const size_t th = (size_t(t0) + tok[mt][i]) * a.n_head + g * AT_PER + r % AT_PER; + float f = 1.0f; + if (a.sinks) { // the sink, in log2 units like the scores + const float sink = a.sinks[th] * LOG2E, now = fmaxf(m[mt][i], sink); + f = exp2f(__fsub_rn(m[mt][i], now)); + l[mt][i] = __fmaf_rn(l[mt][i], f, exp2f(__fsub_rn(sink, now))); + } + float* y = a.out + th * AT_DIM + 2 * tig; + #pragma unroll + for (int n = 0; n < 16; ++n) + *reinterpret_cast(y + 8 * n) = make_float2(__fmul_rn(o[mt][n][2 * i], f) / l[mt][i], + __fmul_rn(o[mt][n][2 * i + 1], f) / l[mt][i]); + } +#else + (void) a; // never launched without the tensor cores (mma_attention()) +#endif +} + +template +__global__ void __launch_bounds__(W * WARP, 1) attn_fa2_kernel(AttnArgs a) { + static_assert(fa_tokens(W) * AT_PER >= 32 * W - 2, "attn_fa2_kernel: at most 2 unused rows"); +#if defined(__CUDA_ARCH__) + constexpr int arch = __CUDA_ARCH__; +#else + constexpr int arch = 0; // AMD builds: never launched (mma_attention()) +#endif + if constexpr (fa_fits(arch, W)) attn_fa2(a); + else __trap(); // fa2_card() takes it only where fa_fits(); a stray launch must not return garbage +} + +// The shared memory attn_fa2_kernel needs: 149 KB for 8 warps (A100: up to 163 KB a block, H100 227 KB), 94 KB +// for 4 (the cards of up to 99 KB: sm_86, sm_89, sm_120). +template +constexpr size_t fa_smem(bool kq, bool vq) { + return kq ? (vq ? sizeof(FaSmem) : sizeof(FaSmem)) + : (vq ? sizeof(FaSmem) : sizeof(FaSmem)); +} + +// What attn_fa2_kernel does on the current card, asked once a card (a layer split can mix cards), as bits: 1 asked, +// 2 it takes the prompt batches (fa2_attention()), and from bit 2 + 2 * (2 * kq + vq) the most warps its block can +// have there for those caches, over 4 (fa2_warps(): 8, 4 or 0). +// +// It takes them when the card runs code built for Ampere or newer and its tensor cores sum fp16 products into floats +// at full rate, where it was measured faster (an A100-PCIE-40GB; A30 and A800 not measured). sm_80 is GA100 only: +// A100 and A800, 312 dense TFLOPS with fp32 accumulation as with fp16 in NVIDIA's A100 whitepaper, A30 165. +// GeForce cards of sm_86, sm_89 and sm_120 sum into floats at half rate (the GA102, Ada and RTX Blackwell +// whitepapers: RTX 3090 71 of 142, RTX 4090 165.2 of 330.3, RTX 5090 209.5 of 419 TFLOPS), where attn_mma_kernel is +// already near that limit; the same chips' professional cards (RTX A6000, A40, L40, ...) and Hopper are not measured. +int fa2_card() { +#if defined(__HIPCC__) + return 1; +#else + static std::atomic cards[kDevices] = {}; + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= kDevices) { + cudaGetLastError(); + return 1; + } + int bits = cards[dev].load(std::memory_order_relaxed); + if (bits) return bits; + bits = 1; + cudaFuncAttributes fa{}; + int optin = 0, major = 0, minor = 0; + if (cudaFuncGetAttributes(&fa, attn_fa2_kernel<8, 2, false, false>) == cudaSuccess && + cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev) == cudaSuccess && + cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess && + cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess) { + const int arch = 10 * fa.ptxVersion; // the __CUDA_ARCH__ of the code the card runs + if (arch >= 800 && major == 8 && minor == 0) bits |= 2; + for (int c = 0; c < 4; ++c) { + const bool kq = c & 2, vq = c & 1; + const int w = fa_fits(arch, 8) && (size_t) optin >= fa_smem<8>(kq, vq) ? 8 + : fa_fits(arch, 4) && (size_t) optin >= fa_smem<4>(kq, vq) ? 4 + : 0; + bits |= w / 4 << (2 + 2 * c); + } + } else { + cudaGetLastError(); + } + cards[dev].store(bits, std::memory_order_relaxed); + return bits; +#endif +} + +bool fa2_attention() { return fa2_card() & 2; } +int fa2_warps(bool kq, bool vq) { return 4 * (fa2_card() >> (2 + 2 * (2 * kq + vq)) & 3); } + +template +void launch_fa2(const AttnArgs& a, cudaStream_t st) { + constexpr size_t smem = sizeof(FaSmem); + static std::atomic set[kDevices] = {}; // the device's own setting: once on each card the calls are for + int dev = 0; + const bool known = cudaGetDevice(&dev) == cudaSuccess && dev >= 0 && dev < kDevices; + if (!known || !set[dev].load(std::memory_order_relaxed)) { + const cudaError_t e = cudaFuncSetAttribute(attn_fa2_kernel, + cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem); + if (e != cudaSuccess) + throw std::runtime_error(std::string("inkling_attend: shared memory: ") + cudaGetErrorString(e)); + if (known) set[dev].store(true, std::memory_order_relaxed); + } + attn_fa2_kernel<<>>(a); +} + +template +void launch_fa2_q(const AttnArgs& a, cudaStream_t st, bool kq, bool vq) { + if (kq && vq) launch_fa2(a, st); + else if (kq) launch_fa2(a, st); + else if (vq) launch_fa2(a, st); + else launch_fa2(a, st); +} + +template +void launch_attn(const AttnArgs& a, dim3 g, cudaStream_t st) { + constexpr size_t smem = attn_smem(TQ); + if constexpr (smem > 48 * 1024) { + // the device's own setting: asked on whichever card the call is for + const cudaError_t e = + cudaFuncSetAttribute(attn_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem); + if (e != cudaSuccess) + throw std::runtime_error(std::string("inkling_attend: shared memory: ") + cudaGetErrorString(e)); + } + attn_kernel<<>>(a); +} + +template +void launch_attn_q(const AttnArgs& a, dim3 g, cudaStream_t st, bool kq8, bool vq8) { + if (kq8 && vq8) launch_attn(a, g, st); + else if (kq8) launch_attn(a, g, st); + else if (vq8) launch_attn(a, g, st); + else launch_attn(a, g, st); +} + +int split_keys(long long room) { + const long long s = (room + kInklingMaxSplits - 1) / kInklingMaxSplits; + return (int) std::max(AT_MIN_SPLIT, (s + AT_KEYS - 1) / AT_KEYS * AT_KEYS); +} + +// The split path's keys a split and splits of a token whose positions + 1 are at most span_room. +void splits_of(long long span_room, int window, int& split, int& nslot) { + // a window layer's tokens see `window` keys whatever the room: its splits are sized for those + split = split_keys(window > 0 ? std::min(span_room, window) : span_room); + long long n = (span_room + split - 1) / split; + if (window > 0) n = std::min(n, (window + split - 1) / split + 1); + nslot = (int) std::max(n, 1); +} + +template +void launch_dec(const AttnArgs& a, const Rows& rows, int ntok, bool kq, bool vq, bool int8_dot, cudaStream_t st) { + const dim3 gd((unsigned) a.nslot, a.kv_heads, ntok); + if (int8_dot && kq && vq && a.window <= 0) { // a full layer's rows of long splits by __dp4a, the others not + AttnArgs b = a; + b.i8_from = I8_MIN_SPLIT; + const int big = rows_from(rows, a, ntok, I8_MIN_SPLIT); + if (big > 0) attn_dec_i8_kernel<<>>(b, rows); + if (big < ntok) attn_dec_kernel<<>>(b, rows); + } else if (kq && vq) attn_dec_kernel<<>>(a, rows); + else if (kq) attn_dec_kernel<<>>(a, rows); + else if (vq) attn_dec_kernel<<>>(a, rows); + else attn_dec_kernel<<>>(a, rows); + check_launch("inkling_attend"); + if (a.nslot > 1) { // a row of one split: the block wrote the token's output itself + attn_join_kernel<<>>(a, rows); + check_launch("inkling_attend (join)"); + } +} + +// ---- convolution ----------------------------------------------------------------------------------------------- + +// The convolution of one token of one channel from its inputs s0 (oldest) .. s2 and v (the token's), in +// upstream's order: ssm_conv's sum, then the four input-dependent taps lag 0..3, then the residual and the scale. +__device__ __forceinline__ float conv_one(float s0, float s1, float s2, float v, const float* wc, + const float* tp, float scale) { + float y = 0.0f; + y += s0 * wc[0]; + y += s1 * wc[1]; + y += s2 * wc[2]; + y += v * wc[3]; + if (tp) { + y += v * tp[0]; + y += s2 * tp[1]; + y += s1 * tp[2]; + y += s0 * tp[3]; + } + return (v + y) * scale; +} + +// The convolution's scale: 1/3 with taps, 1/sqrt(5) without. +inline float conv_scale(const float* taps) { return 1.0f / sqrtf(float((taps ? 2 : 1) * 4 + 1)); } + +// Where conv_walk_kernel's tokens are: the call's tokens one after the other in one sequence, with one state (a +// thread walks them all), or each row a sequence's of its own with its own state (row blockIdx.y). +struct ConvOne { + float* state; + int rows; + __device__ int first() const { return 0; } + __device__ int end() const { return rows; } + __device__ float* at(int) const { return state; } +}; +struct ConvSeqs { + float* state[kInklingSeqRows]; + __device__ int first() const { return blockIdx.y; } + __device__ int end() const { return blockIdx.y + 1; } + __device__ float* at(int t) const { return state[t]; } +}; + +template +__global__ void conv_walk_kernel(const float* __restrict__ x, Rows rows, const float* __restrict__ w, + const float* __restrict__ taps, int heads, float* __restrict__ out, int channels, + float scale) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= channels) return; + const float* wc = w + 4 * size_t(c); + const int h = taps ? c / (channels / heads) : 0; + const int r0 = rows.first(), r1 = rows.end(); + float* st = rows.at(r0) + size_t(c) * 3; + float s0 = st[0], s1 = st[1], s2 = st[2]; + for (int row = r0; row < r1; ++row) { + const size_t i = size_t(row) * channels + c; + const float v = x[i]; + const float y = conv_one(s0, s1, s2, v, wc, taps ? taps + (size_t(row) * heads + h) * 4 : nullptr, scale); + out[i] = ACC ? __fadd_rn(out[i], y) : y; // no fma with the scale: axpy's bits + s0 = s1; + s1 = s2; + s2 = v; + } + st[0] = s0; + st[1] = s1; + st[2] = s2; +} + +template +__global__ void conv_rows_kernel(const float* __restrict__ x, const float* __restrict__ state, + const float* __restrict__ w, const float* __restrict__ taps, int heads, + float* __restrict__ out, int channels, int row0, float scale) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= channels) return; + const int row = row0 + blockIdx.y; + const float* st = state + size_t(c) * 3; + auto in = [&](int r) { return r >= 0 ? x[size_t(r) * channels + c] : st[3 + r]; }; + const int h = taps ? c / (channels / heads) : 0; + const float y = conv_one(in(row - 3), in(row - 2), in(row - 1), in(row), w + 4 * size_t(c), + taps ? taps + (size_t(row) * heads + h) * 4 : nullptr, scale); + float* o = out + size_t(row) * channels + c; + *o = ACC ? __fadd_rn(*o, y) : y; +} + +__global__ void conv_state_kernel(const float* __restrict__ x, float* __restrict__ state, int channels, int rows) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= channels) return; + float* st = state + size_t(c) * 3; + auto in = [&](int r) { return r >= 0 ? x[size_t(r) * channels + c] : st[3 + r]; }; + const float a = in(rows - 3), b = in(rows - 2), d = in(rows - 1); + st[0] = a; + st[1] = b; + st[2] = d; +} + +// The state as it is after token t of x (t < rows) for each of the call's snapshot tokens (Snaps), row blockIdx.y +// of them into snap + blockIdx.y * stride: what conv_state_kernel leaves after t + 1 tokens. Before the call +// advances the state. +constexpr int SNAPS_MAX = 32; +struct Snaps { + int t[SNAPS_MAX]; +}; +__global__ void conv_snaps_kernel(const float* __restrict__ x, const float* __restrict__ state, int channels, + Snaps snaps, float* __restrict__ snap, size_t stride) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= channels) return; + const int t = snaps.t[blockIdx.y]; + const float* st = state + size_t(c) * 3; + auto in = [&](int r) { return r >= 0 ? x[size_t(r) * channels + c] : st[3 + r]; }; + float* to = snap + blockIdx.y * stride + size_t(c) * 3; + to[0] = in(t - 2); + to[1] = in(t - 1); + to[2] = in(t); +} + +constexpr int CONV_ROWS = 16; + +// ---- mix ------------------------------------------------------------------------------------------------------- + +constexpr int MIX_THREADS = 512; +constexpr int MIX_SUMS = kInklingMaxStates * 5; // a state's sum of squares and its dot with each of 4 queries + +// A block a token, in one pass over the states: every state's sum of squares and its dots with the raw queries +// together (s_hat . q = inv * (s . q)), the block's sums of all of them at once, the softmaxes, then the outputs. +__global__ void __launch_bounds__(MIX_THREADS) mix_kernel(InklingMix m, int n, float eps) { + __shared__ float part[MIX_THREADS / WARP][MIX_SUMS]; + __shared__ float tot[MIX_SUMS]; + __shared__ float wts[4][kInklingMaxStates]; + const size_t t = blockIdx.x; + const int ns = m.n_state, nq = m.n_query, lane = threadIdx.x % WARP, warp = threadIdx.x / WARP; + float acc[MIX_SUMS]; +#pragma unroll + for (int j = 0; j < MIX_SUMS; ++j) acc[j] = 0.0f; + for (int i = threadIdx.x; i < n; i += MIX_THREADS) { + float qv[4]; +#pragma unroll + for (int q = 0; q < 4; ++q) qv[q] = q < nq ? m.query[size_t(q) * n + i] : 0.0f; +#pragma unroll + for (int k = 0; k < kInklingMaxStates; ++k) { + if (k >= ns) break; + const float x = m.state[k][t * n + i]; + acc[k * 5] += x * x; +#pragma unroll + for (int q = 0; q < 4; ++q) acc[k * 5 + 1 + q] += x * qv[q]; + } + } +#pragma unroll + for (int j = 0; j < MIX_SUMS; ++j) { + const float v = warp_sum(acc[j]); + if (lane == 0) part[warp][j] = v; + } + __syncthreads(); + if (threadIdx.x < MIX_SUMS) { + float v = 0.0f; + for (int w = 0; w < MIX_THREADS / WARP; ++w) v += part[w][threadIdx.x]; + tot[threadIdx.x] = v; + } + __syncthreads(); + if (threadIdx.x < nq) { + const int q = threadIdx.x; + const float scale = 1.0f / sqrtf((float) n); + float sc[kInklingMaxStates], mx = -INFINITY; + for (int k = 0; k < ns; ++k) { + const float inv = 1.0f / sqrtf(tot[k * 5] / float(n) + eps); + sc[k] = tot[k * 5 + 1 + q] * inv * scale; + mx = fmaxf(mx, sc[k]); + } + float sum = 0.0f; + for (int k = 0; k < ns; ++k) sum += (sc[k] = expf(sc[k] - mx)); + // the weights times the states' norms, so that the sum below reads the raw states + for (int k = 0; k < ns; ++k) wts[q][k] = sc[k] / sum / sqrtf(tot[k * 5] / float(n) + eps); + } + __syncthreads(); + for (int i = threadIdx.x; i < n; i += MIX_THREADS) { + float xs[kInklingMaxStates]; +#pragma unroll + for (int k = 0; k < kInklingMaxStates; ++k) xs[k] = k < ns ? m.state[k][t * n + i] : 0.0f; + for (int q = 0; q < nq; ++q) { + float y = 0.0f; +#pragma unroll + for (int k = 0; k < kInklingMaxStates; ++k) + if (k < ns) y += wts[q][k] * xs[k]; + m.out[q][t * n + i] = y; + } + } +} + +constexpr int MIX4_MAX = 768; // threads: a float4 each, so n <= 3072 +// mix_kernel for n a multiple of 4 up to 4 * MIX4_MAX, NS states: a thread a float4 of every state, read once into +// registers and kept for the output, so that a token's whole read is on its way at once. The same sums otherwise. +// States a thread of mix4_body() has in registers already (a convolution's output before it): their values at +// the thread's float4. +struct Given { + const float* p[2] = {}; + float4 v[2]; + __device__ float4 at(const float* s, int i) const { + return s == p[0] ? v[0] : s == p[1] ? v[1] : reinterpret_cast(s)[i]; + } +}; + +constexpr int MIX4_SUMS = kInklingMaxStates * 5; +struct Mix4Smem { + float part[MIX4_MAX / WARP][MIX4_SUMS]; + float tot[MIX4_SUMS]; + float wts[4][kInklingMaxStates]; +}; + +// mix4_body()'s sums of a thread's float4 of each state: its square, then its products with the queries'. +template +__device__ __forceinline__ void mix4_sums(const float4* xs, const float4* qv, float* acc) { +#pragma unroll + for (int k = 0; k < NS; ++k) { + const float4 x = xs[k]; + acc[k * 5] = x.x * x.x + x.y * x.y + x.z * x.z + x.w * x.w; +#pragma unroll + for (int q = 0; q < 4; ++q) + acc[k * 5 + 1 + q] = x.x * qv[q].x + x.y * qv[q].y + x.z * qv[q].z + x.w * qv[q].w; + } +} + +// Query q's weights w[NS] from the block's sums tot: the softmax of the normed states' scores, times their norms, so +// that the output's sum reads the raw states. +template +__device__ __forceinline__ void mix4_weights(const float* tot, int q, int n, float eps, float* w) { + const float scale = 1.0f / sqrtf((float) n); + float sc[NS], inv[NS], mx = -INFINITY; +#pragma unroll + for (int k = 0; k < NS; ++k) { + inv[k] = 1.0f / sqrtf(tot[k * 5] / float(n) + eps); + sc[k] = tot[k * 5 + 1 + q] * inv[k] * scale; + mx = fmaxf(mx, sc[k]); + } + float sum = 0.0f; +#pragma unroll + for (int k = 0; k < NS; ++k) sum += (sc[k] = expf(sc[k] - mx)); +#pragma unroll + for (int k = 0; k < NS; ++k) w[k] = sc[k] / sum * inv[k]; +} + +// An output value from the states' values x there. +template +__device__ __forceinline__ float mix4_one(const float* w, const float* x) { + float y = 0.0f; +#pragma unroll + for (int k = 0; k < NS; ++k) y += w[k] * x[k]; + return y; +} + +template +__device__ __forceinline__ float4 mix4_out(const float* w, const float4* xs) { + float x[NS], y[NS], z[NS], v[NS]; +#pragma unroll + for (int k = 0; k < NS; ++k) x[k] = xs[k].x, y[k] = xs[k].y, z[k] = xs[k].z, v[k] = xs[k].w; + return make_float4(mix4_one(w, x), mix4_one(w, y), mix4_one(w, z), mix4_one(w, v)); +} + +// mix4_kernel's token t; `given` only for one token (t 0). +template +__device__ __forceinline__ void mix4_body(const InklingMix& m, int n, float eps, size_t t, const Given& given, + Mix4Smem& sm) { + constexpr int SUMS = NS * 5; + auto& part = sm.part; + auto& tot = sm.tot; + auto& wts = sm.wts; + const int nq = m.n_query, lane = threadIdx.x % WARP, warp = threadIdx.x / WARP; + const int i = threadIdx.x, n4 = n / 4; + const bool own = i < n4; + float4 xs[NS]; + float acc[SUMS]; +#pragma unroll + for (int j = 0; j < SUMS; ++j) acc[j] = 0.0f; + if (own) { + float4 qv[4]; +#pragma unroll + for (int q = 0; q < 4; ++q) + qv[q] = q < nq ? reinterpret_cast(m.query + size_t(q) * n)[i] : make_float4(0, 0, 0, 0); +#pragma unroll + for (int k = 0; k < NS; ++k) xs[k] = given.at(m.state[k] + t * n, i); + mix4_sums(xs, qv, acc); + } +#pragma unroll + for (int j = 0; j < SUMS; ++j) { + const float v = warp_sum(acc[j]); + if (lane == 0) part[warp][j] = v; + } + __syncthreads(); + const int warps = blockDim.x / WARP; + for (int j = threadIdx.x; j < SUMS; j += blockDim.x) { // a block of n <= 128 has fewer threads than sums + float v = 0.0f; + for (int w = 0; w < warps; ++w) v += part[w][j]; + tot[j] = v; + } + __syncthreads(); + if (threadIdx.x < nq) mix4_weights(tot, threadIdx.x, n, eps, wts[threadIdx.x]); + __syncthreads(); + if (!own) return; +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q >= nq) break; + reinterpret_cast(m.out[q] + t * n)[i] = mix4_out(wts[q], xs); + } +} + +template +__global__ void __launch_bounds__(MIX4_MAX) mix4_kernel(InklingMix m, int n, float eps) { + __shared__ Mix4Smem sm; + mix4_body(m, n, eps, blockIdx.x, Given{}, sm); +} + +void launch_mix4(const InklingMix& m, int n, int rows, float eps, cudaStream_t st) { + const int threads = (n / 4 + WARP - 1) / WARP * WARP; + switch (m.n_state) { + case 1: mix4_kernel<1><<>>(m, n, eps); break; + case 2: mix4_kernel<2><<>>(m, n, eps); break; + case 3: mix4_kernel<3><<>>(m, n, eps); break; + case 4: mix4_kernel<4><<>>(m, n, eps); break; + case 5: mix4_kernel<5><<>>(m, n, eps); break; + case 6: mix4_kernel<6><<>>(m, n, eps); break; + case 7: mix4_kernel<7><<>>(m, n, eps); break; + default: mix4_kernel<8><<>>(m, n, eps); break; + } +} + +// ---- a token's post-convolution in the launch that reads it ----------------------------------------------------- + +struct ConvIn { + const float* x; + const float* parts; + const float* wts; + int n_parts; + float* state; + const float* w; + float* acc; + float* save; + bool fresh; + float scale; +}; + +// Channel ch of InklingConvIn's convolution for one token, given acc's value there: the input (with parts, the sum +// moe_sum() leaves in a zeroed buffer), conv_walk_kernel's convolution and state, and acc's new value. +__device__ __forceinline__ float conv_in_one(const ConvIn& c, int n, int ch, float old) { + float v; + if (c.parts) { + float s = 0.0f; + for (int k = 0; k < c.n_parts; ++k) s += c.wts[k] * c.parts[size_t(k) * n + ch]; + v = __fadd_rn(0.0f, s); + } else { + v = c.x[ch]; + } + float* st = c.state + size_t(ch) * 3; + const float s0 = st[0], s1 = st[1], s2 = st[2]; + const float y = conv_one(s0, s1, s2, v, c.w + 4 * size_t(ch), nullptr, c.scale); + st[0] = s1, st[1] = s2, st[2] = v; + return c.fresh ? y : __fadd_rn(old, y); +} + +__global__ void conv_in_kernel(ConvIn c, int n) { + const int ch = blockIdx.x * blockDim.x + threadIdx.x; + if (ch >= n) return; + const float old = c.acc[ch]; + if (c.save) c.save[ch] = old; + c.acc[ch] = conv_in_one(c, n, ch, old); +} + +constexpr int MIX_CONV_STATES = 5; // inkling_mix_conv()'s most states a mix +struct MixPair { + InklingMix m[2]; +}; + +struct MixNorms { + const float* w[4]; + float* y[4]; + fm::Q81* yq[4]; + float eps; +}; + +// One token's mixes, a block each, mix4_kernel's work; the first block's threads first do the convolution of +// their float4 of c.acc, which its mix then reads from their registers. With SUM, the first mix's outputs are then +// normed as native_add_rms_norm_q8_1_kernel norms them, each with its own weight. +template +__global__ void __launch_bounds__(MIX4_MAX) mix_conv_kernel(MixPair mp, ConvIn c, MixNorms nr, int n, float eps) { + __shared__ Mix4Smem sm; + __shared__ float part[SUM > 0 ? SUM / WARP : 1]; + const InklingMix& m = mp.m[blockIdx.x]; + const int i = threadIdx.x; + Given g; + if (blockIdx.x == 0 && c.acc && i < n / 4) { + float4* a4 = reinterpret_cast(c.acc) + i; + const float4 old = *a4; + if (c.save) reinterpret_cast(c.save)[i] = old; + float4 y; + y.x = conv_in_one(c, n, 4 * i, old.x); + y.y = conv_in_one(c, n, 4 * i + 1, old.y); + y.z = conv_in_one(c, n, 4 * i + 2, old.z); + y.w = conv_in_one(c, n, 4 * i + 3, old.w); + *a4 = y; + g.p[0] = c.acc, g.v[0] = y; + g.p[1] = c.save, g.v[1] = old; + } + switch (m.n_state) { + case 1: mix4_body<1>(m, n, eps, 0, g, sm); break; + case 2: mix4_body<2>(m, n, eps, 0, g, sm); break; + case 3: mix4_body<3>(m, n, eps, 0, g, sm); break; + case 4: mix4_body<4>(m, n, eps, 0, g, sm); break; + default: mix4_body<5>(m, n, eps, 0, g, sm); break; + } + if constexpr (SUM > 0) { + if (blockIdx.x != 0) return; + __syncthreads(); // the mix's outputs + for (int q = 0; q < m.n_query; ++q) fm::rms_norm_q8_1(m.out[q], nr.w[q], nr.y[q], nr.yq[q], n, nr.eps, part); + } +} +static_assert(MIX_CONV_STATES == 5, "mix_conv_kernel's cases"); + +// ---- one token's mixes over many blocks ------------------------------------------------------------------------ +// +// mix_conv_kernel's work in blocks of MIX_SPREAD threads, thread g of a mix's blocks doing what thread g of its block +// does there (the same float4 of the same states and the same warp's sums), so that every value is the same +// operations in the same order. A mix's blocks meet in device memory (grid_meet()) after their warps' sums, which +// each block then adds up as mix4_body() does for the weights; with norms, the first mix's blocks meet again after +// the norms' warps' sums, a norm's warp recomputing the outputs it reads from the states. + +constexpr int MIX_SPREAD = 32; + +struct MixSpreadWork { + unsigned meet[8]; // a counter a mix (grid_meet()) + float part[2][MIX4_MAX / WARP][MIX_CONV_STATES * 5]; + float norm[4][1024 / WARP]; +}; + +struct MixSpreadSmem { + float tot[MIX_CONV_STATES * 5]; + float wts[4][MIX_CONV_STATES]; + __align__(16) float outs[4][4 * MIX_SPREAD]; // the norms' inputs, the block's part of them +}; + +// A load past the SM's cache, of what other blocks of the launch wrote before a grid_meet(). +__device__ __forceinline__ float load_peer(const float* p) { return *(volatile const float*) p; } + +// The `blocks` blocks of a group past this point together, their stores before it seen by their load_peer()s after +// it. The arrivals add 2^31 to the counter in all, which flips its top bit with the last one: from 0, it is 0 or +// 2^31 between meetings. +__device__ __forceinline__ void grid_meet(unsigned* count, int blocks, bool first) { + __syncthreads(); + if (threadIdx.x == 0) { + __threadfence(); + const unsigned old = atomicAdd(count, first ? 0x80000000u - unsigned(blocks - 1) : 1u); + while (((old ^ *(volatile unsigned*) count) & 0x80000000u) == 0) { + } + __threadfence(); + } + __syncthreads(); +} + +// conv_in_one() of channels 4i .. 4i + 3, all their loads before their stores; g gets acc's and save's float4. +__device__ __forceinline__ void conv_in4(const ConvIn& c, int n, int i, Given& g) { + float4* a4 = reinterpret_cast(c.acc) + i; + const float4 old = *a4; + const float o[4] = {old.x, old.y, old.z, old.w}; + float v[4]; + if (c.parts) { + float s[4] = {0.0f, 0.0f, 0.0f, 0.0f}; +#pragma unroll 4 + for (int k = 0; k < c.n_parts; ++k) { + const float wk = c.wts[k]; + const float* p = c.parts + size_t(k) * n + 4 * size_t(i); +#pragma unroll + for (int j = 0; j < 4; ++j) s[j] += wk * p[j]; + } +#pragma unroll + for (int j = 0; j < 4; ++j) v[j] = __fadd_rn(0.0f, s[j]); + } else { +#pragma unroll + for (int j = 0; j < 4; ++j) v[j] = c.x[4 * i + j]; + } + float* st = c.state + size_t(i) * 12; + float s0[4], s1[4], s2[4], y[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) s0[j] = st[3 * j], s1[j] = st[3 * j + 1], s2[j] = st[3 * j + 2]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + y[j] = conv_one(s0[j], s1[j], s2[j], v[j], c.w + 16 * size_t(i) + 4 * j, nullptr, c.scale); + y[j] = c.fresh ? y[j] : __fadd_rn(o[j], y[j]); + } + if (c.save) reinterpret_cast(c.save)[i] = old; +#pragma unroll + for (int j = 0; j < 4; ++j) st[3 * j] = s1[j], st[3 * j + 1] = s2[j], st[3 * j + 2] = v[j]; + const float4 y4 = make_float4(y[0], y[1], y[2], y[3]); + *a4 = y4; + g.p[0] = c.acc, g.v[0] = y4; + g.p[1] = c.save, g.v[1] = old; +} + +// Block b of a mix's nb; with SUM, the first mix's norms after it (fm::rms_norm_q8_1()'s sums). +template +__device__ __forceinline__ void mix_spread_body(const InklingMix& m, const MixNorms& nr, int n, float eps, + const Given& given, int mi, int b, int nb, MixSpreadWork* wk, + MixSpreadSmem& sm) { + constexpr int SUMS = NS * 5; + auto& tot = sm.tot; + auto& wts = sm.wts; + auto& outs = sm.outs; + const int nq = m.n_query, lane = threadIdx.x % WARP, n4 = n / 4; + const int i = b * MIX_SPREAD + threadIdx.x, warp = i / WARP; // mix4_body()'s thread and warp + const bool own = i < n4; + float4 xs[NS]; + float acc[SUMS]; +#pragma unroll + for (int j = 0; j < SUMS; ++j) acc[j] = 0.0f; + if (own) { + float4 qv[4]; +#pragma unroll + for (int q = 0; q < 4; ++q) + qv[q] = q < nq ? reinterpret_cast(m.query + size_t(q) * n)[i] : make_float4(0, 0, 0, 0); +#pragma unroll + for (int k = 0; k < NS; ++k) xs[k] = given.at(m.state[k], i); + mix4_sums(xs, qv, acc); + } +#pragma unroll + for (int j = 0; j < SUMS; ++j) { + const float v = warp_sum(acc[j]); + if (lane == 0) wk->part[mi][warp][j] = v; + } + grid_meet(&wk->meet[mi], nb, b == 0); + const int warps = (n4 + WARP - 1) / WARP; + for (int j = threadIdx.x; j < SUMS; j += blockDim.x) { + float v = 0.0f; + for (int w = 0; w < warps; ++w) v += load_peer(&wk->part[mi][w][j]); + tot[j] = v; + } + __syncthreads(); + if (threadIdx.x < nq) mix4_weights(tot, threadIdx.x, n, eps, wts[threadIdx.x]); + __syncthreads(); + if (own) { +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q >= nq) break; + const float4 y = mix4_out(wts[q], xs); + reinterpret_cast(m.out[q])[i] = y; + if constexpr (SUM > 0) reinterpret_cast(outs[q])[threadIdx.x] = y; + } + } + if constexpr (SUM > 0) { + if (mi != 0) return; + // the norms' sums: their thread t (warp t / 32) of each output's values t, t + SUM, ... + const int nw = nb * MIX_SPREAD / WARP; + for (int k = warp; k < SUM / WARP; k += nw) { + const int t = k * WARP + lane; + float ss[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + for (int e = t; e < n; e += SUM) { + float x[NS]; +#pragma unroll + for (int s = 0; s < NS; ++s) x[s] = load_peer(m.state[s] + e); +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q >= nq) break; + const float v = mix4_one(wts[q], x); + ss[q] = fm::fma_rn(v, v, ss[q]); + } + } +#pragma unroll + for (int q = 0; q < 4; ++q) { + if (q >= nq) break; + const float v = fm::warp_sum(ss[q]); + if (lane == 0) wk->norm[q][k] = v; + } + } + grid_meet(&wk->meet[0], nb, b == 0); + const int base = 4 * MIX_SPREAD * b, count = min(4 * MIX_SPREAD, n - base); // a multiple of 32 + for (int q = 0; q < nq; ++q) { + float sum = 0.0f; + for (int k = 0; k < SUM / WARP; ++k) sum = fm::add_rn(sum, load_peer(&wk->norm[q][k])); + const float scale = fm::div_rn(1.0f, fm::sqrt_rn(fm::add_rn(fm::div_rn(sum, float(n)), nr.eps))); + for (int e = threadIdx.x; e < count; e += blockDim.x) { + const int j = base + e; + const float xi = fm::mul_rn(fm::mul_rn(outs[q][e], scale), nr.w[q][j]); + nr.y[q][j] = xi; + fm::q8_1(xi, nr.yq[q] + j / 32); + } + } + } +} + +// grid: the first mix's blocks (blocks0), then the second's. +template +__global__ void __launch_bounds__(MIX_SPREAD) mix_spread_kernel(MixPair mp, ConvIn c, MixNorms nr, int n, float eps, + int blocks0, MixSpreadWork* wk) { + const int mi = blockIdx.x < blocks0 ? 0 : 1; + const int b = blockIdx.x - mi * blocks0, nb = mi ? gridDim.x - blocks0 : blocks0; + const InklingMix& m = mp.m[mi]; + const int i = b * MIX_SPREAD + threadIdx.x; + __shared__ MixSpreadSmem sm; + Given g; + if (mi == 0 && c.acc && i < n / 4) conv_in4(c, n, i, g); + switch (m.n_state) { + case 1: mix_spread_body<1, SUM>(m, nr, n, eps, g, mi, b, nb, wk, sm); break; + case 2: mix_spread_body<2, SUM>(m, nr, n, eps, g, mi, b, nb, wk, sm); break; + case 3: mix_spread_body<3, SUM>(m, nr, n, eps, g, mi, b, nb, wk, sm); break; + case 4: mix_spread_body<4, SUM>(m, nr, n, eps, g, mi, b, nb, wk, sm); break; + default: mix_spread_body<5, SUM>(m, nr, n, eps, g, mi, b, nb, wk, sm); break; + } +} + +// ---- controller, SiTU ------------------------------------------------------------------------------------------ + +__global__ void ctrl_mix_kernel(const float* cur, const float* __restrict__ msg, const float* __restrict__ gain, + const float* __restrict__ forget, float* out, size_t n) { + const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i >= n) return; + const float c = cur[i]; + out[i] = (c - tanhf(forget[i]) * c) + tanhf(gain[i]) * msg[i]; +} + +__device__ __forceinline__ float situ_one(float g, float u, float beta, float lb) { + const float act = tanhf(g * (1.0f / beta)) * beta * sigmoidf(g); + const float up = lb > 0.0f ? tanhf(u * (1.0f / lb)) * lb : u; + return act * up; +} + +__device__ __forceinline__ float2 row_scales(const ExpertScales& s, int row) { + if (!s.gate && !s.up) return make_float2(1.0f, 1.0f); + const int e = s.ids ? s.ids[row] : s.e[row]; + return make_float2(s.gate ? s.gate[e] : 1.0f, s.up ? s.up[e] : 1.0f); +} + +__global__ void situ_rows_kernel(const float* __restrict__ gate_up, float* __restrict__ out, int n, float beta, + float lb, ExpertScales s) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + const float* row = gate_up + size_t(blockIdx.y) * 2 * n; + const float2 sc = row_scales(s, blockIdx.y); + out[size_t(blockIdx.y) * n + i] = situ_one(row[i] * sc.x, row[n + i] * sc.y, beta, lb); +} + +// situ_rows_kernel's values, not stored, into their Q8_1 blocks (n a multiple of 32: a warp is a block). +__global__ void situ_q8_1_kernel(const float* __restrict__ gate_up, fm::Q81* __restrict__ q, int n, float beta, + float lb, ExpertScales s) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + const float* row = gate_up + size_t(blockIdx.y) * 2 * n; + const float2 sc = row_scales(s, blockIdx.y); + const size_t at = size_t(blockIdx.y) * n + i; + fm::q8_1(situ_one(row[i] * sc.x, row[n + i] * sc.y, beta, lb), q + at / 32); +} + +// ---- fused decode steps ------------------------------------------------------------------------------------------ + +__device__ __forceinline__ float4 ld4(const float* p, size_t i) { return *reinterpret_cast(p + i); } +__device__ __forceinline__ float dot4(float4 a, float4 b) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } + +constexpr int CTRL_ROWS = 4, CTRL_THREADS = 256, CTRL_OUT = 32; // a block's outputs in the second launch +static_assert(kInklingMaxRank == 2 * WARP, "ctrl_up_kernel: a lane two of the rank's values"); + +struct CtrlArgs { + const float* cur[4]; + const float* msg[4]; + const float* down[4]; + const float* gain[4]; + const float* forget[4]; + float* out[4]; + int n, rank, rows; + float eps; + float* work; +}; + +// The norms of cur and msg and output o of the down projection, for every row: down[o] . [cur / rms, msg / rms] is +// (down_left[o] . cur) / rms(cur) + (down_right[o] . msg) / rms(msg). A block an output of a controller. +__global__ void __launch_bounds__(CTRL_THREADS) ctrl_down_kernel(CtrlArgs a) { + __shared__ float part[CTRL_THREADS / WARP][4 * CTRL_ROWS]; + const int o = blockIdx.x, k = blockIdx.y, n = a.n, rows = a.rows; + const float* cur = a.cur[k]; + const float* msg = a.msg[k]; + const float* wr = a.down[k] + size_t(o) * 2 * n; + float acc[4 * CTRL_ROWS]; // per row: down_left . cur, down_right . msg, cur . cur, msg . msg +#pragma unroll + for (int j = 0; j < 4 * CTRL_ROWS; ++j) acc[j] = 0.0f; + for (int i = 4 * threadIdx.x; i < n; i += 4 * CTRL_THREADS) { + const float4 wl = ld4(wr, i), wm = ld4(wr, size_t(n) + i); +#pragma unroll + for (int t = 0; t < CTRL_ROWS; ++t) { + if (t >= rows) break; + const float4 c = ld4(cur, size_t(t) * n + i), m = ld4(msg, size_t(t) * n + i); + acc[4 * t] += dot4(wl, c); + acc[4 * t + 1] += dot4(wm, m); + acc[4 * t + 2] += dot4(c, c); + acc[4 * t + 3] += dot4(m, m); + } + } + const int lane = threadIdx.x % WARP, warp = threadIdx.x / WARP; +#pragma unroll + for (int j = 0; j < 4 * CTRL_ROWS; ++j) { + const float v = warp_sum(acc[j]); + if (lane == 0) part[warp][j] = v; + } + __syncthreads(); + if (threadIdx.x < rows) { + const int t = threadIdx.x; + float v[4] = {0, 0, 0, 0}; + for (int w = 0; w < CTRL_THREADS / WARP; ++w) +#pragma unroll + for (int j = 0; j < 4; ++j) v[j] += part[w][4 * t + j]; + const float ic = 1.0f / sqrtf(v[2] / float(n) + a.eps), im = 1.0f / sqrtf(v[3] / float(n) + a.eps); + a.work[(size_t(k) * rows + t) * a.rank + o] = v[0] * ic + v[1] * im; + } +} + +// gain and forget of CTRL_OUT outputs of a controller (a warp four of them, a lane two of the rank's values), and +// the combine: out = (cur - tanh(forget) * cur) + tanh(gain) * msg. +__global__ void __launch_bounds__(CTRL_THREADS) ctrl_up_kernel(CtrlArgs a) { + __shared__ float r[CTRL_ROWS][kInklingMaxRank]; + const int k = blockIdx.y, n = a.n, rows = a.rows, rank = a.rank; + for (int i = threadIdx.x; i < rows * rank; i += CTRL_THREADS) + r[i / rank][i % rank] = a.work[size_t(k) * rows * rank + i]; + __syncthreads(); + const float* gw = a.gain[k]; + const float* fw = a.forget[k]; + const int lane = threadIdx.x % WARP, warp = threadIdx.x / WARP; + constexpr int PER = CTRL_OUT / (CTRL_THREADS / WARP); +#pragma unroll + for (int j = 0; j < PER; ++j) { + const int o = blockIdx.x * CTRL_OUT + warp * PER + j; + if (o >= n) break; + const bool l0 = lane < rank, l1 = lane + WARP < rank; + const float g0 = l0 ? gw[size_t(o) * rank + lane] : 0.0f; + const float g1 = l1 ? gw[size_t(o) * rank + lane + WARP] : 0.0f; + const float f0 = l0 ? fw[size_t(o) * rank + lane] : 0.0f; + const float f1 = l1 ? fw[size_t(o) * rank + lane + WARP] : 0.0f; + float gs[CTRL_ROWS], fs[CTRL_ROWS]; +#pragma unroll + for (int t = 0; t < CTRL_ROWS; ++t) { + const float r0 = t < rows && l0 ? r[t][lane] : 0.0f, r1 = t < rows && l1 ? r[t][lane + WARP] : 0.0f; + gs[t] = warp_sum(g0 * r0 + g1 * r1); + fs[t] = warp_sum(f0 * r0 + f1 * r1); + } +#pragma unroll + for (int t = 0; t < CTRL_ROWS; ++t) + if (lane == t && t < rows) { + const size_t i = size_t(t) * n + o; + const float c = a.cur[k][i]; + a.out[k][i] = (c - tanhf(fs[t]) * c) + tanhf(gs[t]) * a.msg[k][i]; + } + } +} + +// y[t][o] = w[o] . x[t], a warp an output, for up to CTRL_ROWS tokens. +constexpr int GEMV_WARPS = 4; +__global__ void __launch_bounds__(GEMV_WARPS * WARP) gemv_rows_kernel(const float* __restrict__ w, + const float* __restrict__ x, + float* __restrict__ y, int n_in, int n_out, + int rows) { + const int lane = threadIdx.x % WARP, o = blockIdx.x * GEMV_WARPS + threadIdx.x / WARP; + if (o >= n_out) return; + const float* wr = w + size_t(o) * n_in; + float acc[CTRL_ROWS] = {0, 0, 0, 0}; +#pragma unroll 4 + for (int i = 4 * lane; i < n_in; i += 4 * WARP) { + const float4 wv = ld4(wr, i); +#pragma unroll + for (int t = 0; t < CTRL_ROWS; ++t) + if (t < rows) acc[t] += dot4(wv, ld4(x, size_t(t) * n_in + i)); + } +#pragma unroll + for (int t = 0; t < CTRL_ROWS; ++t) { + const float v = warp_sum(acc[t]); + if (lane == 0 && t < rows) y[size_t(t) * n_out + o] = v; + } +} + +// inkling_kv_store(): a block a head of K (blockIdx.y 0) or of V (1), a thread a value of it; the tokens in turn. +constexpr int KV_ROWS = 16; +struct KvArgs { + const float* raw[2]; + float* state[2]; + const float* w[2]; + const float* taps[2]; + float* out[2]; + InklingKvDst dst; + int kv_heads, rows; + float k_clip, eps; + long long pos; +}; + +// Where kv_store_kernel's tokens go: the call's tokens one after the other in one sequence (a block takes them all), +// from a position given by value or read on the card when the launch runs, or each row a sequence's of its own (a +// block a row, blockIdx.z). +struct KvOne { + __device__ int first(const KvArgs&) const { return 0; } + __device__ int end(const KvArgs& a) const { return a.rows; } + __device__ float* state(const KvArgs& a, int which, int) const { return a.state[which]; } + __device__ const InklingKvDst& dst(const KvArgs& a, int) const { return a.dst; } + __device__ long long pos(const KvArgs& a, int t) const { return a.pos + t; } +}; +struct KvAt : KvOne { + const long long* at; + __device__ long long pos(const KvArgs&, int t) const { return *at + t; } +}; +struct KvSeqs { + InklingKvSeq row[kInklingSeqRows]; + __device__ int first(const KvArgs&) const { return blockIdx.z; } + __device__ int end(const KvArgs&) const { return blockIdx.z + 1; } + __device__ float* state(const KvArgs&, int which, int t) const { return which ? row[t].v_state : row[t].k_state; } + __device__ const InklingKvDst& dst(const KvArgs&, int t) const { return row[t].dst; } + __device__ long long pos(const KvArgs&, int t) const { return (long long) row[t].pos; } +}; + +// A block's head g of K (which 0) or of V (1); part: AT_DIM / WARP floats of shared memory. +template +__device__ __forceinline__ void kv_store_head(const KvArgs& a, const Rows& rows, int g, int which, float* part) { + const int d = threadIdx.x, lane = d % WARP; + const int channels = a.kv_heads * AT_DIM, c = g * AT_DIM + d; + const float* x = a.raw[which]; + const float* taps = a.taps[which]; + const float* wc = a.w[which] + 4 * size_t(c); + const int t0 = rows.first(a), t1 = rows.end(a); + float* st = rows.state(a, which, t0) + size_t(c) * 3; + const float scale = 1.0f / sqrtf(float((taps ? 2 : 1) * 4 + 1)); + float s0 = st[0], s1 = st[1], s2 = st[2]; + for (int t = t0; t < t1; ++t) { + const InklingKvDst& dst = rows.dst(a, t); + const bool q8 = which ? dst.vc != nullptr : dst.kc != nullptr; + const float v = x[size_t(t) * channels + c]; + const float y = conv_one(s0, s1, s2, v, wc, taps ? taps + (size_t(t) * a.kv_heads + g) * 4 : nullptr, scale); + s0 = s1, s1 = s2, s2 = v; + // the head's sum of squares: the warps' sums, then the four in order + float ss = warp_sum(y * y); + if (lane == 0) part[d / WARP] = ss; + __syncthreads(); + ss = part[0] + part[1] + part[2] + part[3]; + __syncthreads(); + float val; + if (which == 0) { + const float factor = fminf(fmaxf(a.k_clip / (sqrtf(ss) + 1e-6f), 0.0f), 1.0f); + val = y * factor; + } else { + val = y * (1.0f / sqrtf(ss / float(AT_DIM) + a.eps)); + } + if (a.out[which]) a.out[which][size_t(t) * channels + c] = val; + const long long p = rows.pos(a, t); + const long long row = dst.ring > 0 ? p % dst.ring : p; + if (!q8) { + half* cache = reinterpret_cast(which ? dst.v : dst.k); + cache[size_t(row) * channels + c] = __float2half(val); + } else { + // a warp is a Q8_0 block of 32 values: store_q8's rule + float amax = fabsf(val); +#pragma unroll + for (int o = WARP / 2; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o, WARP)); + const float dl = amax / 127.0f; + const float id = dl > 0.f ? 1.0f / dl : 0.0f; + int8_t* codes = which ? dst.vc : dst.kc; + half* scales = reinterpret_cast(which ? dst.vs : dst.ks); + const size_t at = size_t(row) * channels + c; + if (lane == 0) scales[at / 32] = __float2half(dl); + const float q = fminf(fmaxf(rintf(val * id), -127.0f), 127.0f); + codes[at] = (int8_t) q; + } + } + st[0] = s0, st[1] = s1, st[2] = s2; +} + +template +__global__ void __launch_bounds__(AT_DIM) kv_store_kernel(KvArgs a, Rows rows) { + __shared__ float part[AT_DIM / WARP]; + kv_store_head(a, rows, blockIdx.x, blockIdx.y, part); +} + +// kv_store_kernel's blocks (a head of K, then of V, by blockIdx.x) and then clip_many_kernel's warps, AT_DIM / WARP +// a block, in one launch: the same work, a block or a warp as each of the two would give it. +template +__global__ void __launch_bounds__(AT_DIM) kv_clip_kernel(KvArgs a, Rows rows, ClipJobs c, int count, From from) { + __shared__ float part[AT_DIM / WARP]; + const int b = blockIdx.x, kv = 2 * a.kv_heads; + if (b < kv) { + kv_store_head(a, rows, b % a.kv_heads, b / a.kv_heads, part); + return; + } + clip_many_group(c, count, from, (b - kv) * (AT_DIM / WARP) + int(threadIdx.x) / WARP); +} + +} // namespace + +// ================================================================================================================ + +void inkling_clip(const float* x, int x_stride, const float* scale, float* y, int dim, int heads, int rows, + float threshold, InklingTau tau, int64_t pos, void* stream) { + if (rows <= 0) return; + if (dim <= 0 || dim > 1024) throw std::invalid_argument("inkling_clip: dim must be 1 to 1024"); + const int groups = rows * heads, per_block = 256 / WARP; + clip_kernel<<>>(x, x_stride ? x_stride : heads * dim, scale, y, dim, + heads, groups, threshold, tau.alpha, tau.floor, + (long long) pos); + check_launch("inkling_clip"); +} + +size_t inkling_attend_work_floats(int n_head, int dim) { + return size_t(kInklingSplitRows) * n_head * (kInklingMaxSplits + 2) * (dim + 2); +} + +namespace { +// inkling_attend()'s and inkling_attend_seqs()'s checks, and the arguments every row shares +AttnArgs attn_args(const char* who, const float* q, const InklingRel& rel, const float* sinks, int rows, float* out, + int dim, int n_head, int kv_heads, float scale, int window, int ring, float* work) { + if (dim != AT_DIM || kv_heads <= 0 || n_head != AT_PER * kv_heads) + throw std::invalid_argument(std::string(who) + ": heads of 128 values in groups of 3 only"); + if (rel.n_rel < 0 || rel.n_rel > AT_MAX_REL || (rel.n_rel > 0 && !rel.r) || !rel.table) + throw std::invalid_argument(std::string(who) + ": bad relative-position bias"); + AttnArgs a{}; + a.q = q; + a.rel = rel; + a.sinks = sinks; + a.rows = rows; + a.n_head = n_head; + a.kv_heads = kv_heads; + a.window = window; + a.ring = ring; + a.scale = scale; + a.out = out; + a.work = work; + return a; +} +} // namespace + +void inkling_attend(const float* q, const uint16_t* kcache, const uint16_t* vcache, Kvq8 kq8, Kvq8 vq8, + InklingRel rel, const float* sinks, int64_t pos, int rows, float* out, int dim, int n_head, + int kv_heads, float scale, int window, int ring, float* work, size_t work_floats, void* stream, + int64_t room, bool int8_dot, const long long* at, const float* gate, void* out_q8_1, + InklingMma mma) { + if (rows <= 0) return; + if (at && room <= 0) throw std::invalid_argument("inkling_attend: the position on the card needs a room"); + AttnArgs a = + attn_args("inkling_attend", q, rel, sinks, rows, out, dim, n_head, kv_heads, scale, window, ring, work); + a.kc = (const half*) kcache; + a.vc = (const half*) vcache; + a.kq = kq8; + a.vq = vq8; + a.pos = (long long) pos; + const bool kq = kq8.codes != nullptr, vq = vq8.codes != nullptr; + const cudaStream_t st = cs(stream); + // positions + 1, at most: the caller's room when it gives one, else pos + rows + const long long span_room = room > 0 ? (long long) room : (long long) pos + rows; + + if (work && rows <= kInklingSplitRows && span_room > 0) { + splits_of(span_room, window, a.split, a.nslot); + const size_t need = size_t(rows) * n_head * a.nslot * (AT_DIM + 2); + if (need <= work_floats) { + a.gate = gate; + a.out_q8_1 = out_q8_1; + if (at) launch_dec(a, AttnAt{at}, rows, kq, vq, int8_dot, st); + else launch_dec(a, AttnOne{}, rows, kq, vq, int8_dot, st); + return; + } + } + if (at) throw std::invalid_argument("inkling_attend: the position on the card takes the split path and a room"); + // a block is WMMA_TOKENS tokens of a visit: below that the decode and split paths are the ones to use; its bias + // reads the table and R four values at a time + if (!kq && !vq && rows >= WMMA_TOKENS && rel.n_rel % 4 == 0 && wmma_attention()) { + launch_attn_wmma(a, kv_heads, rows, st); + if (gate) mul_sigmoid(out, gate, n_head * dim, rows, n_head * dim, false, stream); + if (out_q8_1) kernels::native_quantize_q8_1(out, out_q8_1, n_head * dim * rows, 1, stream); + return; + } + if (rows >= kInklingMmaRows && rel.n_rel == 16 && mma_attention()) { + // attn_fa2_kernel for full layers whose call reaches past kFa2Keys positions only: in a window layer, and for + // the first 2,048 keys of a full one, attn_mma_kernel was the faster (A100, q8_0, 1,024 tokens: 0.21 against + // 0.30 ms at position 0, 0.52 against 0.53 at 1,024; 4,096 tokens at 28,672 in a window layer: 0.98 against + // 1.32), and both give the same bits + constexpr long long kFa2Keys = 2048; + const bool fa2 = mma == InklingMma::fa2 || + (mma == InklingMma::best && window <= 0 && pos + rows > kFa2Keys && fa2_attention()); + const int fw = fa2 ? fa2_warps(kq, vq) : 0; + if (mma == InklingMma::fa2 && !fw) + throw std::invalid_argument("inkling_attend: no shared memory for attn_fa2_kernel on this card"); + const dim3 gm(grid(rows, MMA_TOKENS), kv_heads); + if (fw == 8) launch_fa2_q<8>(a, st, kq, vq); + else if (fw) launch_fa2_q<4>(a, st, kq, vq); + else if (kq && vq) attn_mma_kernel<<>>(a); + else if (kq) attn_mma_kernel<<>>(a); + else if (vq) attn_mma_kernel<<>>(a); + else attn_mma_kernel<<>>(a); + check_launch("inkling_attend"); + if (gate) mul_sigmoid(out, gate, n_head * dim, rows, n_head * dim, false, stream); + if (out_q8_1) kernels::native_quantize_q8_1(out, out_q8_1, n_head * dim * rows, 1, stream); + return; + } + const int tq = rows >= 8 ? 8 : rows >= 4 ? 4 : rows >= 2 ? 2 : 1; + const dim3 g(1, kv_heads, (rows + tq - 1) / tq); + switch (tq) { + case 8: launch_attn_q<8>(a, g, st, kq, vq); break; + case 4: launch_attn_q<4>(a, g, st, kq, vq); break; + case 2: launch_attn_q<2>(a, g, st, kq, vq); break; + default: launch_attn_q<1>(a, g, st, kq, vq); break; + } + check_launch("inkling_attend"); + if (gate) mul_sigmoid(out, gate, n_head * dim, rows, n_head * dim, false, stream); + if (out_q8_1) kernels::native_quantize_q8_1(out, out_q8_1, n_head * dim * rows, 1, stream); +} + +void inkling_attend_seqs(const float* q, const InklingAttnSeq* seqs, int rows, InklingRel rel, const float* sinks, + float* out, int dim, int n_head, int kv_heads, float scale, int window, int ring, + float* work, size_t work_floats, void* stream, bool int8_dot) { + if (rows <= 0) return; + if (rows > kInklingSeqRows || !work) + throw std::invalid_argument("inkling_attend_seqs: 1 to " + std::to_string(kInklingSeqRows) + + " rows, and work"); + AttnArgs a = attn_args("inkling_attend_seqs", q, rel, sinks, rows, out, dim, n_head, kv_heads, scale, window, ring, + work); + a.nslot = 1; + const bool kq = seqs[0].kq8.codes != nullptr, vq = seqs[0].vq8.codes != nullptr; + AttnSeqs r{}; + for (int t = 0; t < rows; ++t) { + const InklingAttnSeq& c = seqs[t]; + if ((c.kq8.codes != nullptr) != kq || (c.vq8.codes != nullptr) != vq) + throw std::invalid_argument("inkling_attend_seqs: every row's caches of one kind"); + AttnRow& w = r.r[t]; + w.kc = (const half*) c.kcache, w.vc = (const half*) c.vcache, w.kq = c.kq8, w.vq = c.vq8; + w.pos = (long long) c.pos; + splits_of(c.room > 0 ? (long long) c.room : w.pos + 1, window, w.split, w.nslot); + a.nslot = std::max(a.nslot, w.nslot); + } + if (size_t(rows) * n_head * a.nslot * (AT_DIM + 2) > work_floats) + throw std::invalid_argument("inkling_attend_seqs: work too small"); + launch_dec(a, r, rows, kq, vq, int8_dot, cs(stream)); +} + +namespace { +template +void conv_any(const float* x, float* state, const float* w, const float* taps, int heads, float* out, int channels, + int rows, void* stream) { + if (rows <= 0) return; + if (taps && (heads <= 0 || channels % heads)) + throw std::invalid_argument("inkling_conv: channels must split evenly into the taps' heads"); + const float scale = conv_scale(taps); + if (rows >= CONV_ROWS) { + for (int r = 0; r < rows; r += 65535) // a grid has at most 65535 rows + conv_rows_kernel<<>>( + x, state, w, taps, heads, out, channels, r, scale); + conv_state_kernel<<>>(x, state, channels, rows); + } else { + conv_walk_kernel<<>>(x, ConvOne{state, rows}, w, taps, heads, + out, channels, scale); + } + check_launch("inkling_conv"); +} +} // namespace + +void inkling_conv(const float* x, float* state, const float* w, const float* taps, int heads, float* out, + int channels, int rows, void* stream) { + conv_any(x, state, w, taps, heads, out, channels, rows, stream); +} + +void inkling_conv_acc(const float* x, float* state, const float* w, const float* taps, int heads, float* acc, + int channels, int rows, void* stream) { + conv_any(x, state, w, taps, heads, acc, channels, rows, stream); +} + +void inkling_conv_snaps(const float* x, const float* state, int channels, int rows, unsigned bits, float* snap, + size_t stride, void* stream) { + Snaps snaps{}; + int n = 0; + for (int t = 0; t < rows && t < SNAPS_MAX; ++t) + if (bits >> t & 1u) snaps.t[n++] = t; + if (n == 0) return; + conv_snaps_kernel<<>>(x, state, channels, snaps, snap, stride); + check_launch("inkling_conv_snaps"); +} + +namespace { +template +void conv_seqs(const float* x, float* const* states, const float* w, float* out, int channels, int rows, + void* stream) { + if (rows <= 0) return; + if (rows > kInklingSeqRows) + throw std::invalid_argument("inkling_conv_seqs: at most " + std::to_string(kInklingSeqRows) + " rows"); + ConvSeqs s{}; + for (int t = 0; t < rows; ++t) s.state[t] = states[t]; + conv_walk_kernel<<>>(x, s, w, nullptr, 0, out, channels, + conv_scale(nullptr)); + check_launch("inkling_conv_seqs"); +} +} // namespace + +void inkling_conv_seqs(const float* x, float* const* states, const float* w, float* out, int channels, int rows, + void* stream) { + conv_seqs(x, states, w, out, channels, rows, stream); +} + +void inkling_conv_acc_seqs(const float* x, float* const* states, const float* w, float* acc, int channels, int rows, + void* stream) { + conv_seqs(x, states, w, acc, channels, rows, stream); +} + +void inkling_mix(const InklingMix& m, int n, int rows, float eps, void* stream) { + if (rows <= 0) return; + if (m.n_state < 1 || m.n_state > kInklingMaxStates || m.n_query < 1 || m.n_query > 4) + throw std::invalid_argument("inkling_mix: 1 to 8 states and 1 to 4 queries"); + bool aligned = n % 4 == 0 && n / 4 <= MIX4_MAX && (uintptr_t(m.query) & 15) == 0; + for (int k = 0; k < m.n_state; ++k) aligned = aligned && (uintptr_t(m.state[k]) & 15) == 0; + for (int q = 0; q < m.n_query; ++q) aligned = aligned && (uintptr_t(m.out[q]) & 15) == 0; + if (aligned) + launch_mix4(m, n, rows, eps, cs(stream)); + else + mix_kernel<<>>(m, n, eps); + check_launch("inkling_mix"); +} + +namespace { +ConvIn conv_in(const InklingConvIn& c) { + if (!c.acc || !c.state || !c.w || (!c.x && !(c.parts && c.weights && c.n_parts > 0))) + throw std::invalid_argument("inkling_conv_in: acc, state, w and an input"); + return ConvIn{c.x, c.parts, c.weights, c.n_parts, c.state, c.w, c.acc, c.save, c.fresh, conv_scale(nullptr)}; +} +bool aligned16(const void* p) { return (uintptr_t(p) & 15) == 0; } +} // namespace + +void inkling_conv_in(const InklingConvIn& c, int n, void* stream) { + if (n <= 0) return; + conv_in_kernel<<>>(conv_in(c), n); + check_launch("inkling_conv_in"); +} + +size_t inkling_mix_conv_work_bytes() { return sizeof(MixSpreadWork); } + +namespace { +// The blocks of mix_spread_kernel a launch on the current card can take (the least over its SUMs, times the card's +// multiprocessors), or -1 where it has no cooperative launch. A launch's blocks wait for each other in grid_meet(), +// so it goes out as a cooperative one, which the runtime starts with all of its blocks on the card together (beside +// other streams' kernels, in an MPS client's or a green context's share of the card) or refuses; refused, it is the +// one block a mix. None on HIP: there the blocks' meetings cost more than the one block a mix did (an RX 9070 XT +// wrote Inkling 2 Mini UD-Q2_K_XL at 74.1 tok/s spread, 80.1 in one block, after a 286-token prompt; the same bits). +// STRATA_INKLING_MIX_SPREAD=0: none anywhere (the same bits). +int spread_room() { +#if defined(__HIPCC__) + return -1; +#else + static const bool off = [] { + const char* v = std::getenv("STRATA_INKLING_MIX_SPREAD"); + return v != nullptr && std::string(v) == "0"; + }(); + if (off) return -1; + static std::atomic rooms[kDevices] = {}; // a device's, 0: not yet asked + int dev = 0; + if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= kDevices) { + cudaGetLastError(); + return -1; + } + int room = rooms[dev].load(std::memory_order_relaxed); + if (room) return room; + int sms = 0, coop = 0, least = INT_MAX; + for (const void* k : {(const void*) mix_spread_kernel<0>, (const void*) mix_spread_kernel<128>, + (const void*) mix_spread_kernel<256>, (const void*) mix_spread_kernel<512>, + (const void*) mix_spread_kernel<1024>}) { + int per_sm = 0; + if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm, k, MIX_SPREAD, 0) != cudaSuccess) per_sm = 0; + least = std::min(least, per_sm); + } + if (cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev) != cudaSuccess) sms = 0; + if (cudaDeviceGetAttribute(&coop, cudaDevAttrCooperativeLaunch, dev) != cudaSuccess) coop = 0; + cudaGetLastError(); + room = coop && least * sms > 0 ? least * sms : -1; + rooms[dev].store(room, std::memory_order_relaxed); + return room; +#endif +} +} // namespace + +void inkling_mix_conv(const InklingMix* mixes, int count, const InklingConvIn* conv, int n, float eps, void* stream, + const InklingMixNorm* norm, void* work) { + if (count < 1 || count > 2) throw std::invalid_argument("inkling_mix_conv: 1 or 2 mixes"); + bool fits = n % 4 == 0 && n / 4 <= MIX4_MAX; + MixPair mp{}; + for (int k = 0; k < count; ++k) { + const InklingMix& m = mixes[k]; + if (m.n_state < 1 || m.n_state > kInklingMaxStates || m.n_query < 1 || m.n_query > 4) + throw std::invalid_argument("inkling_mix_conv: 1 to 8 states and 1 to 4 queries"); + fits = fits && m.n_state <= MIX_CONV_STATES && aligned16(m.query); + for (int j = 0; j < m.n_state; ++j) fits = fits && aligned16(m.state[j]); + for (int q = 0; q < m.n_query; ++q) fits = fits && aligned16(m.out[q]); + mp.m[k] = m; + } + if (conv) fits = fits && aligned16(conv->acc) && aligned16(conv->save); + if (norm && n % WARP) throw std::invalid_argument("inkling_mix_conv: the norms take n a multiple of 32"); + if (!fits) { // the calls one after the other + if (conv) inkling_conv_in(*conv, n, stream); + for (int k = 0; k < count; ++k) inkling_mix(mixes[k], n, 1, eps, stream); + for (int q = 0; norm && q < mixes[0].n_query; ++q) + kernels::native_add_rms_norm_q8_1(mixes[0].out[q], nullptr, norm->w[q], norm->y[q], norm->y_q8_1[q], n, 1, + norm->eps, norm->threads, stream); + return; + } + const int threads = (n / 4 + WARP - 1) / WARP * WARP; // launch_mix4()'s + const ConvIn c = conv ? conv_in(*conv) : ConvIn{}; + MixNorms nr{}; + if (norm) { + for (int q = 0; q < mixes[0].n_query; ++q) + nr.w[q] = norm->w[q], nr.y[q] = norm->y[q], nr.yq[q] = static_cast(norm->y_q8_1[q]); + nr.eps = norm->eps; + } + const cudaStream_t st = cs(stream); + const int blocks = (threads + MIX_SPREAD - 1) / MIX_SPREAD; // a mix's, spread + // the norms' sums read every block's states after the outputs are written: spread only where no output is a state + bool apart = true; + for (int k = 0; k < count; ++k) + for (int q = 0; q < mixes[k].n_query; ++q) + for (int j = 0; j < count; ++j) + for (int i = 0; i < mixes[j].n_state; ++i) apart = apart && mixes[k].out[q] != mixes[j].state[i]; + if (work && apart && count * blocks <= spread_room()) { + auto* wk = static_cast(work); + const void* kernel = nullptr; + switch (norm ? norm->threads : 0) { + case 0: kernel = (const void*) mix_spread_kernel<0>; break; + case 128: kernel = (const void*) mix_spread_kernel<128>; break; + case 256: kernel = (const void*) mix_spread_kernel<256>; break; + case 512: kernel = (const void*) mix_spread_kernel<512>; break; + case 1024: kernel = (const void*) mix_spread_kernel<1024>; break; + default: throw std::invalid_argument("inkling_mix_conv: norms of 128, 256, 512 or 1024 threads"); + } + int blocks0 = blocks; + void* args[] = {&mp, (void*) &c, &nr, &n, &eps, &blocks0, &wk}; + if (cudaLaunchCooperativeKernel(kernel, dim3(count * blocks), dim3(MIX_SPREAD), args, 0, st) == cudaSuccess) + return; + cudaGetLastError(); // not all of its blocks at once: the one block a mix + } + switch (norm ? norm->threads : 0) { + case 0: mix_conv_kernel<0><<>>(mp, c, nr, n, eps); break; + case 128: mix_conv_kernel<128><<>>(mp, c, nr, n, eps); break; + case 256: mix_conv_kernel<256><<>>(mp, c, nr, n, eps); break; + case 512: mix_conv_kernel<512><<>>(mp, c, nr, n, eps); break; + case 1024: mix_conv_kernel<1024><<>>(mp, c, nr, n, eps); break; + default: throw std::invalid_argument("inkling_mix_conv: norms of 128, 256, 512 or 1024 threads"); + } + check_launch("inkling_mix_conv"); +} + +void inkling_control(void* blas, const float* cur, const float* msg, const float* down, const float* gain, + const float* forget, float* work, float* out, int n, int rank, int rows, float eps, + void* stream) { + if (rows <= 0) return; + float* z = work; + float* r = z + size_t(rows) * 2 * n; + float* g = r + size_t(rows) * rank; + float* f = g + size_t(rows) * n; + rms_norm(cur, nullptr, z, n, rows, eps, stream, 2 * n); + rms_norm(msg, nullptr, z + n, n, rows, eps, stream, 2 * n); + if (rows < 8 || !blas) { + gemv_f32(down, z, r, 2 * n, rank, rank, rows, stream); + gemv_f32(gain, r, g, rank, n, n, rows, stream); + gemv_f32(forget, r, f, rank, n, n, rows, stream); + } else { + gemm_f32(blas, down, z, r, 2 * n, rank, rank, rows); + gemm_f32(blas, gain, r, g, rank, n, n, rows); + gemm_f32(blas, forget, r, f, rank, n, n, rows); + } + const size_t count = size_t(rows) * n; + ctrl_mix_kernel<<>>(cur, msg, g, f, out, count); + check_launch("inkling_control"); +} + +void situ_rows(const float* gate_up, float* out, int n, int rows, float beta, float lb, void* stream, + const ExpertScales* scales) { + if (n <= 0 || rows <= 0) return; + for (int r = 0; r < rows; r += 65535) { // a grid has at most 65535 rows + ExpertScales s = scales ? *scales : ExpertScales{}; + if (s.ids) s.ids += r; + situ_rows_kernel<<>>( + gate_up + size_t(r) * 2 * n, out + size_t(r) * n, n, beta, lb, s); + } + check_launch("situ_rows"); +} + +void situ_rows_q8_1(const float* gate_up, void* q8_1, int n, int rows, float beta, float lb, void* stream, + const ExpertScales* scales) { + if (n <= 0 || rows <= 0) return; + if (n % WARP) throw std::invalid_argument("situ_rows_q8_1: n must be a multiple of 32"); + for (int r = 0; r < rows; r += 65535) { + ExpertScales s = scales ? *scales : ExpertScales{}; + if (s.ids) s.ids += r; + situ_q8_1_kernel<<>>( + gate_up + size_t(r) * 2 * n, static_cast(q8_1) + size_t(r) * n / 32, n, beta, lb, s); + } + check_launch("situ_rows_q8_1"); +} + +void inkling_control_fused(const InklingCtrl* ctrl, int count, int n, int rank, int rows, float eps, float* work, + void* stream) { + if (rows <= 0 || count <= 0) return; + if (count > 4 || rank <= 0 || rank > kInklingMaxRank || n % 4) + throw std::invalid_argument("inkling_control_fused: 1 to 4 controllers, rank 1 to " + + std::to_string(kInklingMaxRank) + ", n a multiple of 4"); + const cudaStream_t st = cs(stream); + for (int r0 = 0; r0 < rows; r0 += CTRL_ROWS) { + CtrlArgs a{}; + a.n = n, a.rank = rank, a.rows = std::min(CTRL_ROWS, rows - r0), a.eps = eps, a.work = work; + for (int k = 0; k < count; ++k) { + const size_t off = size_t(r0) * n; + a.cur[k] = ctrl[k].cur + off; + a.msg[k] = ctrl[k].msg + off; + a.out[k] = ctrl[k].out + off; + a.down[k] = ctrl[k].down, a.gain[k] = ctrl[k].gain, a.forget[k] = ctrl[k].forget; + } + const dim3 g1(rank, count), g2((n + CTRL_OUT - 1) / CTRL_OUT, count); + ctrl_down_kernel<<>>(a); + ctrl_up_kernel<<>>(a); + check_launch("inkling_control_fused"); + } +} + +void inkling_gemv(const float* w, const float* x, float* y, int n_in, int n_out, int rows, void* stream) { + if (rows <= 0 || n_out <= 0) return; + if (n_in % 4) throw std::invalid_argument("inkling_gemv: n_in must be a multiple of 4"); + for (int r0 = 0; r0 < rows; r0 += CTRL_ROWS) { + const int m = std::min(CTRL_ROWS, rows - r0); + const float* xr = x + size_t(r0) * n_in; + float* yr = y + size_t(r0) * n_out; + gemv_rows_kernel<<>>(w, xr, yr, n_in, n_out, m); + } + check_launch("inkling_gemv"); +} + +namespace { +ClipJobs clip_jobs(const InklingClipJob* jobs, int count, int rows) { + if (count > 4) throw std::invalid_argument("inkling_clip_many: at most 4 jobs"); + ClipJobs c{}; + c.first[0] = 0; + for (int k = 0; k < count; ++k) { + if (jobs[k].dim <= 0 || jobs[k].dim > 1024) throw std::invalid_argument("inkling_clip_many: dim 1 to 1024"); + c.j[k] = jobs[k]; + c.first[k + 1] = c.first[k] + rows * jobs[k].heads; + } + return c; +} + +template +void clip_many(const InklingClipJob* jobs, int count, int rows, const From& from, void* stream) { + if (rows <= 0 || count <= 0) return; + const ClipJobs c = clip_jobs(jobs, count, rows); + const int per_block = 256 / WARP; + clip_many_kernel<<>>(c, count, from); + check_launch("inkling_clip_many"); +} +} // namespace + +void inkling_clip_many(const InklingClipJob* jobs, int count, int rows, int64_t pos, void* stream, + const long long* at) { + if (at) clip_many(jobs, count, rows, ClipAt{at}, stream); + else clip_many(jobs, count, rows, ClipFrom{(long long) pos}, stream); +} + +void inkling_clip_many_seqs(const InklingClipJob* jobs, int count, int rows, const int64_t* pos, void* stream) { + if (rows > kInklingSeqRows) + throw std::invalid_argument("inkling_clip_many_seqs: at most " + std::to_string(kInklingSeqRows) + " rows"); + ClipSeqs from{}; + for (int t = 0; t < rows; ++t) from.pos[t] = (long long) pos[t]; + clip_many(jobs, count, rows, from, stream); +} + +namespace { +KvArgs kv_args(const float* kraw, const float* vraw, float* k_state, float* v_state, const float* k_w, const float* v_w, + const float* k_taps, const float* v_taps, int kv_heads, int rows, float k_clip, float eps, + const InklingKvDst& dst, int64_t pos, float* k_out, float* v_out) { + KvArgs a{}; + a.raw[0] = kraw, a.raw[1] = vraw; + a.state[0] = k_state, a.state[1] = v_state; + a.w[0] = k_w, a.w[1] = v_w; + a.taps[0] = k_taps, a.taps[1] = v_taps; + a.out[0] = k_out, a.out[1] = v_out; + a.dst = dst; + a.kv_heads = kv_heads, a.rows = rows, a.k_clip = k_clip, a.eps = eps; + a.pos = (long long) pos; + return a; +} +} // namespace + +void inkling_kv_store(const float* kraw, const float* vraw, float* k_state, float* v_state, const float* k_w, + const float* v_w, const float* k_taps, const float* v_taps, int kv_heads, int dim, int rows, + float k_clip, float eps, const InklingKvDst& dst, int64_t pos, float* k_out, float* v_out, + void* stream, const long long* at) { + if (rows <= 0) return; + if (dim != AT_DIM) throw std::invalid_argument("inkling_kv_store: heads of 128 values only"); + const int width = kv_heads * dim; + if (rows > KV_ROWS) { // a prompt batch: the separate calls + if (at) throw std::invalid_argument("inkling_kv_store: the position on the card takes at most 16 tokens"); + if (!k_out || !v_out) throw std::invalid_argument("inkling_kv_store: more than 16 tokens need k_out and v_out"); + inkling_conv(kraw, k_state, k_w, k_taps, kv_heads, k_out, width, rows, stream); + inkling_conv(vraw, v_state, v_w, v_taps, kv_heads, v_out, width, rows, stream); + inkling_clip(k_out, 0, nullptr, k_out, dim, kv_heads, rows, k_clip, InklingTau{}, pos, stream); + rms_norm(v_out, nullptr, v_out, dim, rows * kv_heads, eps, stream); + for (int side = 0; side < 2; ++side) { + const float* x = side ? v_out : k_out; + int8_t* codes = side ? dst.vc : dst.kc; + uint16_t* scales = side ? dst.vs : dst.ks; + uint16_t* cache = side ? dst.v : dst.k; + for (int done = 0; done < rows;) { + const int64_t p = pos + done; + const int64_t r = dst.ring > 0 ? p % dst.ring : p; + const int m = dst.ring > 0 ? (int) std::min(rows - done, dst.ring - r) : rows - done; + if (codes) store_q8(x + size_t(done) * width, codes, scales, width, r, m, stream); + else store_f16(x + size_t(done) * width, cache, width, r, m, stream); + done += m; + } + } + check_launch("inkling_kv_store"); + return; + } + const KvArgs a = kv_args(kraw, vraw, k_state, v_state, k_w, v_w, k_taps, v_taps, kv_heads, rows, k_clip, eps, dst, + pos, k_out, v_out); + if (at) kv_store_kernel<<>>(a, KvAt{{}, at}); + else kv_store_kernel<<>>(a, KvOne{}); + check_launch("inkling_kv_store"); +} + +void inkling_kv_store_clip(const float* kraw, const float* vraw, float* k_state, float* v_state, const float* k_w, + const float* v_w, const float* k_taps, const float* v_taps, int kv_heads, int dim, int rows, + float k_clip, float eps, const InklingKvDst& dst, int64_t pos, float* k_out, float* v_out, + const InklingClipJob* jobs, int count, void* stream, const long long* at) { + if (rows <= 0) return; + if (rows > KV_ROWS || count <= 0) { + inkling_kv_store(kraw, vraw, k_state, v_state, k_w, v_w, k_taps, v_taps, kv_heads, dim, rows, k_clip, eps, dst, + pos, k_out, v_out, stream, at); + inkling_clip_many(jobs, count, rows, pos, stream, at); + return; + } + if (dim != AT_DIM) throw std::invalid_argument("inkling_kv_store_clip: heads of 128 values only"); + const KvArgs a = kv_args(kraw, vraw, k_state, v_state, k_w, v_w, k_taps, v_taps, kv_heads, rows, k_clip, eps, dst, + pos, k_out, v_out); + const ClipJobs c = clip_jobs(jobs, count, rows); + const int blocks = 2 * kv_heads + grid(c.first[count], AT_DIM / WARP); + if (at) kv_clip_kernel<<>>(a, KvAt{{}, at}, c, count, ClipAt{at}); + else kv_clip_kernel<<>>(a, KvOne{}, c, count, ClipFrom{(long long) pos}); + check_launch("inkling_kv_store_clip"); +} + +void inkling_kv_store_seqs(const float* kraw, const float* vraw, const InklingKvSeq* seqs, const float* k_w, + const float* v_w, const float* k_taps, const float* v_taps, int kv_heads, int dim, + int rows, float k_clip, float eps, float* k_out, float* v_out, void* stream) { + if (rows <= 0) return; + if (dim != AT_DIM) throw std::invalid_argument("inkling_kv_store_seqs: heads of 128 values only"); + if (rows > kInklingSeqRows) + throw std::invalid_argument("inkling_kv_store_seqs: at most " + std::to_string(kInklingSeqRows) + " rows"); + KvArgs a{}; + a.raw[0] = kraw, a.raw[1] = vraw; + a.w[0] = k_w, a.w[1] = v_w; + a.taps[0] = k_taps, a.taps[1] = v_taps; + a.out[0] = k_out, a.out[1] = v_out; + a.kv_heads = kv_heads, a.rows = rows, a.k_clip = k_clip, a.eps = eps; + KvSeqs r{}; + for (int t = 0; t < rows; ++t) r.row[t] = seqs[t]; + kv_store_kernel<<>>(a, r); + check_launch("inkling_kv_store_seqs"); +} + +// ---- the DSpark drafter -------------------------------------------------------------------------------------- + +namespace { + +constexpr int FUSE_THREADS = 256; + +// A block a row and an output: the weighted sum to out, then its root mean square, then out scaled in place. +__global__ void dspark_fuse_kernel(InklingFuse f, int n_embd, float eps) { + const int r = blockIdx.x, j = blockIdx.y; + float* out = f.out[j] + (size_t) r * n_embd; + float ss = 0.f; + for (int i = threadIdx.x; i < n_embd; i += FUSE_THREADS) { + float v = 0.f; +#pragma unroll + for (int k = 0; k < 4; ++k) v += f.w[j][k] * f.x[k][(size_t) r * f.stride[k] + i]; + out[i] = v; + ss += v * v; + } + __shared__ float part[FUSE_THREADS / WARP]; + ss = warp_sum(ss); + if (threadIdx.x % WARP == 0) part[threadIdx.x / WARP] = ss; + __syncthreads(); + if (threadIdx.x < WARP) { + float t = threadIdx.x < FUSE_THREADS / WARP ? part[threadIdx.x] : 0.f; + t = warp_sum(t); + if (threadIdx.x == 0) part[0] = t; + } + __syncthreads(); + const float scale = rsqrtf(part[0] / (float) n_embd + eps); + const float* norm = f.norm[j]; + for (int i = threadIdx.x; i < n_embd; i += FUSE_THREADS) out[i] = out[i] * scale * norm[i]; +} + +// Block attention: a block a key head and a piece of the keys, which it takes BA_KEYS at a time with a running +// softmax. Its queries are the rows' heads of that key head, row-major: qi = row * per + head % per. +constexpr int BA_DIM = 128, BA_KEYS = 32, BA_THREADS = 256, BA_QUERIES = 32; +constexpr int BA_KROW = BA_DIM + 2; // halves a key row in shared memory: rows fall on different banks + +__global__ void block_attend_kernel(const float* __restrict__ q, const half* __restrict__ kc, + const half* __restrict__ vc, long long lo, long long n_keys, int ring, int rows, + int n_head, int kv_heads, float scale, int per_split, float* __restrict__ work) { + const int g = blockIdx.x, split = blockIdx.y, per = n_head / kv_heads, nq = rows * per; + const long long a = (long long) split * per_split, b = min(n_keys, a + per_split); + __shared__ float qs[BA_QUERIES][BA_DIM]; + __shared__ half ks[BA_KEYS][BA_KROW]; + __shared__ half vs[BA_KEYS][BA_DIM]; + __shared__ float ps[BA_QUERIES][BA_KEYS]; + __shared__ float m[BA_QUERIES], l[BA_QUERIES], corr[BA_QUERIES]; + for (int i = threadIdx.x; i < nq * BA_DIM; i += BA_THREADS) { + const int qi = i / BA_DIM, d = i % BA_DIM, r = qi / per, h = g * per + qi % per; + qs[qi][d] = q[((size_t) r * n_head + h) * BA_DIM + d]; + } + if (threadIdx.x < BA_QUERIES) m[threadIdx.x] = -INFINITY, l[threadIdx.x] = 0.f; + constexpr int ACC = BA_QUERIES * BA_DIM / BA_THREADS; + float acc[ACC]; +#pragma unroll + for (int i = 0; i < ACC; ++i) acc[i] = 0.f; + const int warp = threadIdx.x / WARP, lane = threadIdx.x % WARP; + for (long long k0 = a; k0 < b; k0 += BA_KEYS) { + const int nk = (int) min((long long) BA_KEYS, b - k0); + __syncthreads(); // the last tile's keys, values and weights are read + for (int i = threadIdx.x; i < BA_KEYS * BA_DIM / 2; i += BA_THREADS) { + const int kj = i / (BA_DIM / 2), d = 2 * (i % (BA_DIM / 2)); + half2 kv = __floats2half2_rn(0.f, 0.f), vv = kv; + if (kj < nk) { + const long long p = lo + k0 + kj, row = ring > 0 ? p % ring : p; + const size_t at = ((size_t) row * kv_heads + g) * BA_DIM + d; + kv = *reinterpret_cast(kc + at); + vv = *reinterpret_cast(vc + at); + } + *reinterpret_cast(&ks[kj][d]) = kv; + *reinterpret_cast(&vs[kj][d]) = vv; + } + __syncthreads(); + for (int i = threadIdx.x; i < nq * BA_KEYS; i += BA_THREADS) { + const int qi = i / BA_KEYS, kj = i % BA_KEYS; + float s = -INFINITY; + if (kj < nk) { + s = 0.f; +#pragma unroll 8 + for (int d = 0; d < BA_DIM; d += 2) { + const float2 k2 = __half22float2(*reinterpret_cast(&ks[kj][d])); + s += qs[qi][d] * k2.x + qs[qi][d + 1] * k2.y; + } + s *= scale; + } + ps[qi][kj] = s; + } + __syncthreads(); + for (int qi = warp; qi < nq; qi += BA_THREADS / WARP) { + const float s = ps[qi][lane]; // BA_KEYS == WARP + const float mt = warp_max(s), mo = m[qi], mn = fmaxf(mo, mt); + const float p = s == -INFINITY ? 0.f : expf(s - mn); + const float sum = warp_sum(p); + ps[qi][lane] = p; + if (lane == 0) { + const float c = mo == -INFINITY ? 0.f : expf(mo - mn); + corr[qi] = c; + l[qi] = l[qi] * c + sum; + m[qi] = mn; + } + } + __syncthreads(); +#pragma unroll + for (int i = 0; i < ACC; ++i) { + const int o = threadIdx.x + i * BA_THREADS, qi = o / BA_DIM, d = o % BA_DIM; + if (qi >= nq) continue; + float v = acc[i] * corr[qi]; + for (int kj = 0; kj < nk; ++kj) v += ps[qi][kj] * __half2float(vs[kj][d]); + acc[i] = v; + } + } + __syncthreads(); + // the piece's sums: per query its largest logit, its weights' sum and its weighted values + float* w = work + ((size_t) g * gridDim.y + split) * nq * (BA_DIM + 2); +#pragma unroll + for (int i = 0; i < ACC; ++i) { + const int o = threadIdx.x + i * BA_THREADS, qi = o / BA_DIM, d = o % BA_DIM; + if (qi < nq) w[(size_t) qi * (BA_DIM + 2) + 2 + d] = acc[i]; + } + if (threadIdx.x < nq) { + w[(size_t) threadIdx.x * (BA_DIM + 2)] = m[threadIdx.x]; + w[(size_t) threadIdx.x * (BA_DIM + 2) + 1] = l[threadIdx.x]; + } +} + +// A block a row's head: the pieces' sums together. +__global__ void block_join_kernel(const float* __restrict__ work, float* __restrict__ out, int splits, int rows, + int n_head, int kv_heads) { + const int r = blockIdx.x / n_head, h = blockIdx.x % n_head, d = threadIdx.x; + const int per = n_head / kv_heads, g = h / per, nq = rows * per, qi = r * per + h % per; + const float* w = work + (size_t) g * splits * nq * (BA_DIM + 2) + (size_t) qi * (BA_DIM + 2); + const size_t step = (size_t) nq * (BA_DIM + 2); + float mx = -INFINITY; + for (int s = 0; s < splits; ++s) mx = fmaxf(mx, w[s * step]); + float sum = 0.f, v = 0.f; + for (int s = 0; s < splits; ++s) { + const float ms = w[s * step]; + if (ms == -INFINITY) continue; + const float c = expf(ms - mx); + sum += w[s * step + 1] * c; + v += w[s * step + 2 + d] * c; + } + out[((size_t) r * n_head + h) * BA_DIM + d] = v / sum; +} + +__global__ void dspark_gru_kernel(const float* __restrict__ joint, float* __restrict__ state, + float* __restrict__ latent, int rank) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= rank) return; + const float gate = sigmoidf(joint[i]), cand = tanhf(joint[rank + i]); + state[i] = cand + gate * (state[i] - cand); + latent[i] = tanhf(joint[2 * rank + i]); +} + +int block_splits(long long n_keys) { + return (int) std::min(kInklingBlockSplits, std::max(1, (n_keys + 255) / 256)); +} + +} // namespace + +void inkling_dspark_fuse(const InklingFuse& f, int n_embd, int rows, float eps, void* stream) { + if (rows <= 0) return; + dspark_fuse_kernel<<>>(f, n_embd, eps); + check_launch("inkling_dspark_fuse"); +} + +size_t inkling_block_attend_work_floats(int rows, int n_head, int dim) { + return (size_t) kInklingBlockSplits * rows * n_head * (dim + 2); +} + +void inkling_block_attend(const float* q, const uint16_t* kcache, const uint16_t* vcache, int64_t lo, int64_t hi, + int ring, int rows, float* out, int dim, int n_head, int kv_heads, float scale, float* work, + void* stream) { + if (rows <= 0) return; + if (dim != BA_DIM || kv_heads <= 0 || n_head % kv_heads || rows * (n_head / kv_heads) > BA_QUERIES || hi < lo) + throw std::invalid_argument("inkling_block_attend: heads of 128 values, at most 32 queries a key head"); + const long long n_keys = hi - lo + 1; + const int splits = block_splits(n_keys); + const int per_split = (int) ((n_keys + splits - 1) / splits); + block_attend_kernel<<>>( + q, (const half*) kcache, (const half*) vcache, (long long) lo, n_keys, ring, rows, n_head, kv_heads, scale, + per_split, work); + check_launch("inkling_block_attend"); + block_join_kernel<<>>(work, out, splits, rows, n_head, kv_heads); + check_launch("inkling_block_attend"); +} + +void inkling_dspark_gru(const float* joint, float* state, float* latent, int rank, void* stream) { + if (rank <= 0) return; + dspark_gru_kernel<<>>(joint, state, latent, rank); + check_launch("inkling_dspark_gru"); +} + +} // namespace strata::poly diff --git a/src/poly/logits_dump.cpp b/src/poly/logits_dump.cpp new file mode 100644 index 0000000000..829cb2c512 --- /dev/null +++ b/src/poly/logits_dump.cpp @@ -0,0 +1,208 @@ +// src/poly/logits_dump.cpp - the engine's logits for a list of token ids, as raw floats, to compare with +// llama.cpp's (any architecture the engine runs). Run by hand; see usage() for the options. +// +// The prompt goes in calls of max_rows() tokens (eval(), the last one with logits); then each --decode token goes +// in alone. DIR/prompt_logits.f32 gets the prompt's last logits, DIR/decode_logits.f32 one row a decode token +// (n_vocab() floats a row, or --vocab N's first N). The five likeliest of each row go to stdout. With --images, +// pictures (strata-vision's SVE1 records) take the places of --image-pad's runs in the prompt, as GENI's do. +#include "engine.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +const char* const kUsage = + "usage: poly_logits_dump MODEL.gguf (--tokens ID,ID,... | --tokens-file FILE) [options]\n" + " --tokens ID,ID,... the prompt's token ids\n" + " --tokens-file FILE the prompt's ids from a file, apart by commas, white space or brackets (a JSON list)\n" + " --decode ID,ID,... tokens fed one at a time after the prompt, each with its logits\n" + " --out DIR where the .f32 files go (default .)\n" + " --vocab N write a row's first N scores (llama.cpp's unpadded vocabulary)\n" + " --max-context N the engine's context (default 4096)\n" + " --prompt-batch N the prompt's tokens a call\n" + " --kv fp16|q8_0 the attention cache's format (default fp16)\n" + " --expert-profile FILE the expert cache's profile, as strata-poly's\n" + " --threads N the CPU experts' threads\n" + " --no-graphs no recorded launches\n" + " --no-gpu-experts every routed expert on the CPU\n" + " --vram-reserve-mib N VRAM left free after the expert cache is filled, as strata-poly's\n" + " --layer-split auto|N[,N...] the layers across the cards, as strata-poly's (STRATA_POLY_CARDS=2: two on one)\n" + " --reload after the prompt, save the state and rows, reset, feed other tokens, load them back\n" + " --images FILE pictures: strata-vision's records (SVE1), one a run of --image-pad in the prompt\n" + " --image-pad ID the token that stands for a picture's rows (Inkling 2: 200054)\n"; + +std::vector ids(const std::string& s) { + std::vector out; + for (const char* p = s.c_str(); *p;) { + char* end = nullptr; + out.push_back((int32_t) std::strtol(p, &end, 10)); + if (end == p) throw std::runtime_error("not a list of token ids: " + s); + p = *end == ',' ? end + 1 : end; + } + return out; +} + +// ids apart by commas, white space or brackets +std::vector ids_in_file(const std::string& path) { + std::ifstream in(path); + if (!in) throw std::runtime_error("cannot read " + path); + std::stringstream ss; + ss << in.rdbuf(); + std::string t = ss.str(), u; + for (char& c : t) + if (c == ' ' || c == '\n' || c == '\t' || c == '\r' || c == '[' || c == ']') c = ','; + for (char c : t) + if (!(c == ',' && (u.empty() || u.back() == ','))) u += c; + while (!u.empty() && u.back() == ',') u.pop_back(); + return ids(u); +} + +void top(const std::string& what, const float* l, int n) { + std::vector o((size_t) n); + std::iota(o.begin(), o.end(), 0); + const int k = std::min(5, n); + std::partial_sort(o.begin(), o.begin() + k, o.end(), [l](int a, int b) { return l[a] > l[b]; }); + std::printf("%s:", what.c_str()); + for (int i = 0; i < k; ++i) std::printf(" %d(%.4f)", o[(size_t) i], l[o[(size_t) i]]); + std::printf("\n"); +} + +// The pictures of an SVE1 file ('SVE1', rows, rows of a line, lines, a row's floats; then the floats), each at the +// next run of `pad` in ids, as strata-poly's GENI places them (main.cpp, take_pictures). The ids stay as they are. +std::vector pictures(const std::string& path, int32_t pad, int n_embd, + const std::vector& ids, std::vector>& rows) { + std::FILE* f = std::fopen(path.c_str(), "rb"); + if (!f) throw std::runtime_error("cannot read " + path); + std::vector out; + size_t i = 0; + for (int32_t hdr[5]; std::fread(hdr, sizeof(int32_t), 5, f) == 5;) { + if (hdr[0] != 0x31455653 || hdr[1] < 1 || hdr[2] < 1 || (int64_t) hdr[2] * hdr[3] != hdr[1] || hdr[4] != n_embd) + throw std::runtime_error("bad embeddings file (expected SVE1 records of width " + std::to_string(n_embd) + ")"); + rows.emplace_back((size_t) hdr[1] * (size_t) n_embd); + if (std::fread(rows.back().data(), sizeof(float), rows.back().size(), f) != rows.back().size()) + throw std::runtime_error("short embeddings file"); + while (i < ids.size() && ids[i] != pad) ++i; + for (int j = 0; j < hdr[1]; ++j) + if (i + (size_t) j >= ids.size() || ids[i + (size_t) j] != pad) + throw std::runtime_error("picture " + std::to_string(rows.size()) + " has " + std::to_string(hdr[1]) + + " rows and the prompt fewer places for it"); + out.push_back({(int64_t) i, hdr[1], hdr[2], nullptr}); + i += (size_t) hdr[1]; + } + std::fclose(f); + if (std::find(ids.begin() + (std::ptrdiff_t) i, ids.end(), pad) != ids.end()) + throw std::runtime_error("the prompt has more places for pictures than the embeddings file"); + for (size_t k = 0; k < out.size(); ++k) out[k].rows = rows[k].data(); + return out; +} + +FILE* create(const std::string& path) { + FILE* f = std::fopen(path.c_str(), "wb"); + if (!f) throw std::runtime_error("cannot write " + path); + return f; +} + +} // namespace + +int main(int argc, char** argv) { + try { + if (argc < 2) throw std::runtime_error(kUsage); + strata::poly::Options o; + o.model = argv[1]; + o.max_context = 4096; + o.window = 1; + std::vector prompt, decode; + std::string out = ".", images; + int32_t image_pad = -1; + bool reload = false; + int vocab = 0; + for (int i = 2; i < argc; ++i) { + const std::string a = argv[i]; + auto val = [&]() -> const char* { + if (i + 1 >= argc) throw std::runtime_error(a + " needs a value"); + return argv[++i]; + }; + if (a == "--tokens") prompt = ids(val()); + else if (a == "--tokens-file") prompt = ids_in_file(val()); + else if (a == "--decode") decode = ids(val()); + else if (a == "--out") out = val(); + else if (a == "--vocab") vocab = std::atoi(val()); + else if (a == "--max-context") o.max_context = std::atoi(val()); + else if (a == "--prompt-batch") o.prompt_batch = std::atoi(val()); + else if (a == "--kv") { + const std::string f = val(); + if (f == "q8_0") o.kv_format = strata::poly::KvFmt::kQ8_0; + else if (f != "fp16") throw std::runtime_error("--kv is fp16 or q8_0"); + } else if (a == "--expert-profile") o.profile = val(); + else if (a == "--threads") o.threads = std::atoi(val()); + else if (a == "--no-graphs") o.graphs = false; + else if (a == "--no-gpu-experts") o.gpu_experts = false; + else if (a == "--vram-reserve-mib") o.vram_reserve_mib = std::atoi(val()); + else if (a == "--layer-split") o.layer_split = val(); + else if (a == "--reload") reload = true; + else if (a == "--images") images = val(); + else if (a == "--image-pad") image_pad = (int32_t) std::atoi(val()); + else throw std::runtime_error("unknown option " + a + "\n" + kUsage); + } + if (prompt.empty()) throw std::runtime_error(std::string("no prompt tokens\n") + kUsage); + if (!images.empty() && image_pad < 0) throw std::runtime_error("--images needs --image-pad"); + + auto e = strata::poly::Engine::open(o); + std::fprintf(stderr, "loaded: %lld MiB VRAM free, %d of %d experts cached (%.2f GiB)\n", + (long long) e->vram_free_mib(), e->cached_experts(), e->total_experts(), e->cached_gib()); + const int nv = e->n_vocab(), nw = vocab > 0 ? std::min(vocab, nv) : nv; + std::vector> rows; + if (!images.empty()) { + if (!e->sees()) throw std::runtime_error("this model does not read pictures"); + const std::vector at = pictures(images, image_pad, e->n_embd(), prompt, rows); + e->images(at.data(), (int) at.size()); + for (const auto& im : at) std::fprintf(stderr, "picture: %d rows at %lld\n", im.n, (long long) im.at); + } + for (size_t i = 0; i < prompt.size();) { + const int m = (int) e->whole((int64_t) i, (int64_t) std::min(prompt.size() - i, (size_t) e->max_rows())); + e->eval(prompt.data() + i, m, i + (size_t) m == prompt.size()); + i += (size_t) m; + } + FILE* f = create(out + "/prompt_logits.f32"); + std::fwrite(e->logits(), sizeof(float), (size_t) nw, f); + std::fclose(f); + top("prompt", e->logits(), nv); + if (reload) { // what a conversation checkpoint does (save_state, save_rows), and back + const int64_t pos = e->pos(); + std::vector state(e->state_bytes()), rows((size_t) pos * e->row_bytes()); + e->save_state(state.data()); + e->save_rows(0, pos, rows.data()); + e->reset(); + const int32_t other[4] = {11, 12, 13, 14}; // something else in the caches and state meanwhile + e->eval(other, 4, false); + e->load_rows(rows.data(), 0, pos, 0, pos); + e->load_state(state.data(), pos); + std::fprintf(stderr, "reload: %zu bytes of state, %zu of rows for %lld positions\n", state.size(), + rows.size(), (long long) pos); + } + f = create(out + "/decode_logits.f32"); + for (size_t k = 0; k < decode.size(); ++k) { + e->eval(&decode[k], 1, true); + std::fwrite(e->logits(), sizeof(float), (size_t) nw, f); + top("decode " + std::to_string(k), e->logits(), nv); + } + std::fclose(f); + const strata::poly::Stats& st = e->stats(); + std::fprintf(stderr, "experts from VRAM %lld (%.1f%%), CPU %lld; %d of %d experts cached (%.2f GiB)\n", + (long long) st.gpu_experts, + 100.0 * (double) st.gpu_experts / (double) std::max(1, st.gpu_experts + st.cpu_experts), + (long long) st.cpu_experts, e->cached_experts(), e->total_experts(), e->cached_gib()); + return 0; + } catch (const std::exception& x) { + std::fprintf(stderr, "poly_logits_dump: %s\n", x.what()); + return 1; + } +} diff --git a/src/poly/lowbit_gpu_test.cu b/src/poly/lowbit_gpu_test.cu new file mode 100644 index 0000000000..45a081ef9f --- /dev/null +++ b/src/poly/lowbit_gpu_test.cu @@ -0,0 +1,426 @@ +// src/poly/lowbit_gpu_test.cu - the card's products of Inkling 2's low-bit expert types: +// * IQ1_S and Q2_0 in the decode products (native_mmvq, native_mmvq_slots) against ggml's dequantized rows times +// the Q8_1 activation on the host; +// * Q2_0 in the prompt products (poly::Mmq, llama.cpp's MMQ tiles) against the dequantized rows times the floats, +// and against the same matrix written exactly as Q4_0 through Q4_0's tiles; +// and with `bench` the products' times. +// +// usage: poly_lowbit_gpu_test [bench] (exit 0: every check passes; 77: no card) +#include "mmq.hpp" +#include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/native_mmvq.hpp" + +#include "ggml.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace strata; + +int failures = 0; +std::mt19937 rng(11); +cudaStream_t ts; // the checks' stream (native_mmvq takes no null stream) + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::printf("CUDA error at %s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +void check(bool ok, const std::string& what) { + std::printf("%-78s %s\n", what.c_str(), ok ? "ok" : "FAIL"); + if (!ok) ++failures; +} + +std::vector random_rows(ggml_type t, int n, int rows) { + const size_t rb = ggml_row_size(t, n); + std::vector w(rb * rows); + std::uniform_int_distribution byte(0, 255); + for (auto& b : w) b = (uint8_t) byte(rng); + const size_t bb = ggml_type_size(t); + std::uniform_real_distribution sc(0.002f, 0.05f); + for (size_t off = 0; off + bb <= w.size(); off += bb) { + const ggml_fp16_t d = ggml_fp32_to_fp16(sc(rng)); + std::memcpy(&w[off], &d, 2); + } + return w; +} + +// the card's copy, with zero bytes behind it (the MMQ tiles read past a matrix's last row) +void* upload(const void* p, size_t n) { + void* d = nullptr; + ck(cudaMalloc(&d, n + (1 << 20)), "malloc"); + ck(cudaMemset(d, 0, n + (1 << 20)), "memset"); + ck(cudaMemcpy(d, p, n, cudaMemcpyHostToDevice), "upload"); + return d; +} + +std::vector dequant(ggml_type t, const std::vector& w, int n, int rows) { + std::vector f((size_t) n * rows); + ggml_get_type_traits(t)->to_float(w.data(), f.data(), (int64_t) n * rows); + return f; +} + +// Q2_0 as Q4_0, exactly: a block of 64 is (q - 1) * d with q in 0..3, two Q4_0 blocks of (q4 - 8) * d, q4 = q + 7 +void q2_0_to_q4_0(const uint8_t* src, uint8_t* dst, int64_t n) { + for (int64_t b = 0; b < n / 64; ++b, src += 18) + for (int h = 0; h < 2; ++h, dst += 18) { + std::memcpy(dst, src, 2); + uint8_t* qs = dst + 2; + for (int j = 0; j < 16; ++j) { + const auto q = [&](int e) { return (src[2 + (32 * h + e) / 4] >> (2 * ((32 * h + e) % 4))) & 3; }; + qs[j] = (uint8_t) ((q(j) + 7) | ((q(j + 16) + 7) << 4)); + } + } +} + +// the Q8_1 activation as the decode products read it: 32 values a block, half2 (d, s) then 32 codes +std::vector q8_1_values(const void* dq, int n) { + std::vector b((size_t) n / 32 * 36); + ck(cudaMemcpy(b.data(), dq, b.size(), cudaMemcpyDeviceToHost), "download"); + std::vector v(n); + for (int k = 0; k < n / 32; ++k) { + __half d; + std::memcpy(&d, &b[(size_t) k * 36], 2); + for (int i = 0; i < 32; ++i) v[k * 32 + i] = __half2float(d) * (float) (int8_t) b[(size_t) k * 36 + 4 + i]; + } + return v; +} + +// max over the rows of |got - ref| / sum |terms| +double row_err(const std::vector& got, const std::vector& wf, const std::vector& xv, int n, + int rows, size_t got_stride = 1, size_t got_off = 0) { + double worst = 0; + for (int r = 0; r < rows; ++r) { + double d = 0, mag = 0; + for (int i = 0; i < n; ++i) { + const double t = double(wf[(size_t) r * n + i]) * xv[i]; + d += t, mag += std::fabs(t); + } + worst = std::max(worst, std::fabs(got[got_off + (size_t) r * got_stride] - d) / std::max(mag, 1e-30)); + } + return worst; +} + +// The IQ1_S row dot as ggml-cuda's vec_dot_iq1_s_q8_1 defines it: a group of 32 is dl * (grid + delta), taken as +// dl * ((g + 1) . q * d + (delta - 1) * s), s the activation block's sum as Q8_1 keeps it (a half of the sum of the +// values before they were quantized). In double otherwise. qx: the Q8_1 bytes of the activation (36 a block of 32). +std::vector iq1_s_ref(const std::vector& w, const std::vector& qx, int n_in, int n_out) { + std::vector wf = dequant(GGML_TYPE_IQ1_S, w, n_in, n_out); + std::vector y(n_out); + const size_t rb = ggml_row_size(GGML_TYPE_IQ1_S, n_in); + for (int r = 0; r < n_out; ++r) { + double acc = 0; + for (int b = 0; b < n_in / 256; ++b) { + const uint8_t* blk = w.data() + r * rb + b * 50; + ggml_fp16_t dh; + std::memcpy(&dh, blk, 2); + const double d = ggml_fp16_to_fp32(dh); + for (int g = 0; g < 8; ++g) { + uint16_t qh; + std::memcpy(&qh, blk + 34 + 2 * g, 2); + const double dl = d * (2 * ((qh >> 12) & 7) + 1), delta = qh & 0x8000 ? -0.125 : 0.125; + const uint8_t* xb = qx.data() + (size_t) (b * 8 + g) * 36; + __half hd, hs; + std::memcpy(&hd, xb, 2), std::memcpy(&hs, xb + 2, 2); + const double xd = __half2float(hd), xs = __half2float(hs); + // the kernel's form: the grid as g + 1 (0..2) against the codes, and delta - 1 against the block's + // sum s, which Q8_1 keeps as the sum of the unquantized values (llama.cpp's quantizer too): the two + // agree with dl * (g + delta) . x only as far as d * sum q is s + for (int i = 0; i < 32; ++i) { + const double g1 = (wf[(size_t) r * n_in + b * 256 + g * 32 + i] - dl * delta) + dl; // dl (g + 1) + acc += g1 * xd * (int8_t) xb[4 + i]; + } + acc += dl * (delta - 1.0) * xs; + } + } + y[r] = acc; + } + return y; +} + +std::vector q8_1_bytes(const void* dq, int n) { + std::vector b((size_t) n / 32 * 36); + ck(cudaMemcpy(b.data(), dq, b.size(), cudaMemcpyDeviceToHost), "download"); + return b; +} + +// max over the rows of |got - ref| / sum |w * x| +double ref_err(const std::vector& got, size_t off, const std::vector& ref, const std::vector& wf, + const std::vector& xv, int n, int rows) { + double worst = 0; + for (int r = 0; r < rows; ++r) { + double mag = 0; + for (int i = 0; i < n; ++i) mag += std::fabs(double(wf[(size_t) r * n + i]) * xv[i]); + worst = std::max(worst, std::fabs(got[off + r] - ref[r]) / std::max(mag, 1e-30)); + } + return worst; +} + +void test_iq1_s_decode() { + const int n_in = 2304, n_out = 2304, count = 8; // Inkling's gate|up rows, a token's 8 experts + std::vector> w; + std::vector dw; + std::vector> xs; + void* dx = nullptr; + float* dy = nullptr; + ck(cudaMalloc(&dx, (size_t) count * n_in / 32 * 36), "malloc"); + ck(cudaMalloc(&dy, (size_t) count * n_out * 4), "malloc"); + float* dxf = nullptr; + ck(cudaMalloc(&dxf, (size_t) count * n_in * 4), "malloc"); + std::normal_distribution nd(0.f, 1.f); + std::vector xf((size_t) count * n_in); + for (float& v : xf) v = nd(rng); + ck(cudaMemcpy(dxf, xf.data(), xf.size() * 4, cudaMemcpyHostToDevice), "upload"); + kernels::quantize_q8_1_rows(dxf, count, n_in, dx, ts); + kernels::MmvqSlots slots{}; + for (int e = 0; e < count; ++e) { + w.push_back(random_rows(GGML_TYPE_IQ1_S, n_in, n_out)); + dw.push_back(upload(w.back().data(), w.back().size())); + slots.w[e] = dw.back(); + slots.x[e] = (const uint8_t*) dx + (size_t) e * n_in / 32 * 36; + slots.y[e] = dy + (size_t) e * n_out; + } + check(kernels::native_mmvq_supported(GGML_TYPE_IQ1_S), "IQ1_S is a native MMVQ type"); + check(kernels::native_mmvq_slots(GGML_TYPE_IQ1_S, slots, count, n_in, n_out, ts), "native_mmvq_slots takes IQ1_S"); + ck(cudaStreamSynchronize(ts), "slots"); + std::vector got((size_t) count * n_out); + ck(cudaMemcpy(got.data(), dy, got.size() * 4, cudaMemcpyDeviceToHost), "download"); + double worst = 0; + for (int e = 0; e < count; ++e) { + const auto wf = dequant(GGML_TYPE_IQ1_S, w[e], n_in, n_out); + const auto xv = q8_1_values(slots.x[e], n_in); + const auto ref = iq1_s_ref(w[e], q8_1_bytes(slots.x[e], n_in), n_in, n_out); + worst = std::max(worst, ref_err(got, (size_t) e * n_out, ref, wf, xv, n_in, n_out)); + } + char buf[160]; + std::snprintf(buf, sizeof buf, "IQ1_S slots, 8 x [2304 x 2304]: vs ggml-cuda's dot in double %.2e", + worst); + check(worst < 1e-5, buf); + // native_mmvq with 1 to 3 columns of the first matrix + for (int nc = 1; nc <= 3; ++nc) { + kernels::native_mmvq(GGML_TYPE_IQ1_S, dw[0], dx, dy, n_in, n_out, nc, ts); + ck(cudaStreamSynchronize(ts), "mmvq"); + std::vector g((size_t) nc * n_out); + ck(cudaMemcpy(g.data(), dy, g.size() * 4, cudaMemcpyDeviceToHost), "download"); + const auto wf = dequant(GGML_TYPE_IQ1_S, w[0], n_in, n_out); + double wc = 0; + for (int c = 0; c < nc; ++c) { + const void* xc = (const uint8_t*) dx + (size_t) c * n_in / 32 * 36; + wc = std::max(wc, ref_err(g, (size_t) c * n_out, iq1_s_ref(w[0], q8_1_bytes(xc, n_in), n_in, n_out), wf, + q8_1_values(xc, n_in), n_in, n_out)); + } + std::snprintf(buf, sizeof buf, "IQ1_S native_mmvq, %d column(s): max rel error %.2e", nc, wc); + check(wc < 1e-5, buf); + } + for (void* p : dw) cudaFree(p); + cudaFree(dx), cudaFree(dy), cudaFree(dxf); +} + +// Q2_0 down in the decode products: a token's 8 experts +void test_q2_0_decode() { + const int n_in = 1152, n_out = 2304, count = 8; + void* dx = nullptr; + float *dy = nullptr, *dxf = nullptr; + ck(cudaMalloc(&dx, (size_t) count * n_in / 32 * 36), "malloc"); + ck(cudaMalloc(&dy, (size_t) count * n_out * 4), "malloc"); + ck(cudaMalloc(&dxf, (size_t) count * n_in * 4), "malloc"); + std::normal_distribution nd(0.f, 1.f); + std::vector xf((size_t) count * n_in); + for (float& v : xf) v = nd(rng); + ck(cudaMemcpy(dxf, xf.data(), xf.size() * 4, cudaMemcpyHostToDevice), "upload"); + kernels::quantize_q8_1_rows(dxf, count, n_in, dx, ts); + kernels::MmvqSlots slots{}; + std::vector> w; + std::vector dw; + for (int e = 0; e < count; ++e) { + w.push_back(random_rows(GGML_TYPE_Q2_0, n_in, n_out)); + dw.push_back(upload(w.back().data(), w.back().size())); + slots.w[e] = dw.back(); + slots.x[e] = (const uint8_t*) dx + (size_t) e * n_in / 32 * 36; + slots.y[e] = dy + (size_t) e * n_out; + } + const bool took = kernels::native_mmvq_slots(GGML_TYPE_Q2_0, slots, count, n_in, n_out, ts); + ck(cudaStreamSynchronize(ts), "slots"); + std::vector got((size_t) count * n_out); + ck(cudaMemcpy(got.data(), dy, got.size() * 4, cudaMemcpyDeviceToHost), "download"); + double worst = 0; + for (int e = 0; e < count; ++e) + worst = std::max(worst, row_err(got, dequant(GGML_TYPE_Q2_0, w[e], n_in, n_out), q8_1_values(slots.x[e], n_in), + n_in, n_out, 1, (size_t) e * n_out)); + char buf[160]; + std::snprintf(buf, sizeof buf, "Q2_0 slots, 8 x [2304 x 1152]: max |y - dequantized dot| / sum|terms| %.2e", worst); + check(took && worst < 1e-5, buf); + for (void* p : dw) cudaFree(p); + cudaFree(dx), cudaFree(dy), cudaFree(dxf); +} + +void test_q2_0_mmq(int rows) { + const int n_in = 1152, n_out = 2304; // Inkling's down matrix + check(poly::Mmq::fits(GGML_TYPE_Q2_0, n_out, n_in, poly::Mmq::q2_0) && + !poly::Mmq::fits(GGML_TYPE_Q2_0, n_out, n_in), + "Mmq::fits(Q2_0) only when asked for"); + const auto w = random_rows(GGML_TYPE_Q2_0, n_in, n_out); + std::vector w4(ggml_row_size(GGML_TYPE_Q4_0, n_in) * n_out); + q2_0_to_q4_0(w.data(), w4.data(), (int64_t) n_in * n_out); + void *dw = upload(w.data(), w.size()), *dw4 = upload(w4.data(), w4.size()); + std::normal_distribution nd(0.f, 1.f); + std::vector x((size_t) rows * n_in); + for (float& v : x) v = nd(rng); + float *dxf, *d2, *d4; + void* xq; + ck(cudaMalloc(&dxf, x.size() * 4), "malloc"); + ck(cudaMemcpy(dxf, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "upload"); + ck(cudaMalloc(&xq, poly::Mmq::q8_bytes(rows, n_in)), "malloc"); + ck(cudaMalloc(&d2, (size_t) rows * n_out * 4), "malloc"); + ck(cudaMalloc(&d4, (size_t) rows * n_out * 4), "malloc"); + poly::Mmq mmq; + poly::Mmq::quantize(dxf, nullptr, xq, GGML_TYPE_Q2_0, n_in, n_in, rows, ts); + mmq.mul(dw, GGML_TYPE_Q2_0, n_out, n_in, 0, 1, xq, nullptr, nullptr, rows, rows, d2, n_out, ts); + poly::Mmq::quantize(dxf, nullptr, xq, GGML_TYPE_Q4_0, n_in, n_in, rows, ts); + mmq.mul(dw4, GGML_TYPE_Q4_0, n_out, n_in, 0, 1, xq, nullptr, nullptr, rows, rows, d4, n_out, ts); + ck(cudaStreamSynchronize(ts), "mmq"); + std::vector g2((size_t) rows * n_out), g4(g2.size()); + ck(cudaMemcpy(g2.data(), d2, g2.size() * 4, cudaMemcpyDeviceToHost), "download"); + ck(cudaMemcpy(g4.data(), d4, g4.size() * 4, cudaMemcpyDeviceToHost), "download"); + const auto wf = dequant(GGML_TYPE_Q2_0, w, n_in, n_out); + double vs_ref = 0, vs_q4 = 0; + for (int t = 0; t < rows; ++t) { + std::vector xt(x.begin() + (size_t) t * n_in, x.begin() + (size_t) (t + 1) * n_in); + vs_ref = std::max(vs_ref, row_err(g2, wf, xt, n_in, n_out, 1, (size_t) t * n_out)); + for (int r = 0; r < n_out; ++r) { + double mag = 0; + for (int i = 0; i < n_in; ++i) mag += std::fabs(double(wf[(size_t) r * n_in + i]) * xt[i]); + vs_q4 = std::max(vs_q4, std::fabs(double(g2[(size_t) t * n_out + r]) - g4[(size_t) t * n_out + r]) / mag); + } + } + char buf[200]; + std::snprintf(buf, sizeof buf, + "Q2_0 MMQ, %d rows x [2304 x 1152]: vs float dot %.2e (activation's Q8_1), vs the same as Q4_0 %.2e", + rows, vs_ref, vs_q4); + // Q2_0's tiles take the -1 offset from the activation's block sums, which the Q8_1 rows keep in halves (as + // Q4_0's take its -8): the two differ by those roundings, a few 1e-5 of sum |terms| + check(vs_ref < 2e-2 && vs_q4 < 2e-4, buf); + cudaFree(dw), cudaFree(dw4), cudaFree(dxf), cudaFree(xq), cudaFree(d2), cudaFree(d4); +} + +// ---- timings ------------------------------------------------------------------------------------------------------ + +cudaStream_t bs; +template float time_us(F&& f, int reps = 200) { + f(); + ck(cudaStreamSynchronize(bs), "warm-up"); + cudaGraph_t g; + cudaGraphExec_t ex; + ck(cudaStreamBeginCapture(bs, cudaStreamCaptureModeRelaxed), "capture"); + for (int i = 0; i < reps; ++i) f(); + ck(cudaStreamEndCapture(bs, &g), "end capture"); + ck(cudaGraphInstantiate(&ex, g, 0), "instantiate"); + cudaEvent_t e0, e1; + cudaEventCreate(&e0), cudaEventCreate(&e1); + float best = 1e30f; + for (int k = 0; k < 6; ++k) { + cudaEventRecord(e0, bs); + cudaGraphLaunch(ex, bs); + cudaEventRecord(e1, bs); + cudaEventSynchronize(e1); + float ms; + cudaEventElapsedTime(&ms, e0, e1); + if (k) best = std::min(best, ms); + } + cudaGraphExecDestroy(ex), cudaGraphDestroy(g); + return 1000.f * best / reps; +} + +void bench() { + cudaStreamCreateWithFlags(&bs, cudaStreamNonBlocking); + const int count = 8; + std::normal_distribution nd(0.f, 1.f); + struct Mat { + const char* name; + ggml_type t; + int n_in, n_out; + }; + // a token's 8 routed experts: gate|up (IQ1_S) and down (Q2_0), and other types of the same shapes beside them + const Mat mats[] = {{"gate|up IQ1_S", GGML_TYPE_IQ1_S, 2304, 2304}, {"gate|up Q5_0", GGML_TYPE_Q5_0, 2304, 2304}, + {"gate|up IQ2_S", GGML_TYPE_IQ2_S, 2304, 2304}, {"down Q2_0", GGML_TYPE_Q2_0, 1152, 2304}, + {"down Q4_0", GGML_TYPE_Q4_0, 1152, 2304}}; + void* dx; + ck(cudaMalloc(&dx, (size_t) count * 2304 / 32 * 36), "malloc"); + float* dy; + ck(cudaMalloc(&dy, (size_t) count * 2304 * 4), "malloc"); + std::printf("\ndecode: native_mmvq_slots, 8 experts' matrices in one launch (us a launch; GB/s of the weights)\n"); + for (const Mat& m : mats) { + std::vector dw; + kernels::MmvqSlots s{}; + size_t bytes = 0; + for (int e = 0; e < count; ++e) { + const auto w = random_rows(m.t, m.n_in, m.n_out); + bytes += w.size(); + dw.push_back(upload(w.data(), w.size())); + s.w[e] = dw.back(); + s.x[e] = (const uint8_t*) dx + (size_t) e * m.n_in / 32 * 36; + s.y[e] = dy + (size_t) e * m.n_out; + } + const float us = time_us([&] { kernels::native_mmvq_slots(m.t, s, count, m.n_in, m.n_out, bs); }); + std::printf("bench %-32s %8.2f us %7.1f GB/s (%.2f MB)\n", m.name, us, bytes / (us * 1e3), bytes / 1e6); + for (void* p : dw) cudaFree(p); + } + std::printf("\nprompt: Mmq::mul, one matrix, 512 rows (us a call)\n"); + const int rows = 512; + float* dxf; + ck(cudaMalloc(&dxf, (size_t) rows * 2304 * 4), "malloc"); + std::vector xf((size_t) rows * 2304); + for (float& v : xf) v = nd(rng); + ck(cudaMemcpy(dxf, xf.data(), xf.size() * 4, cudaMemcpyHostToDevice), "upload"); + void* xq; + ck(cudaMalloc(&xq, poly::Mmq::q8_bytes(rows, 2304)), "malloc"); + float* dd; + ck(cudaMalloc(&dd, (size_t) rows * 2304 * 4), "malloc"); + poly::Mmq mmq; + const Mat pm[] = {{"down Q2_0 [2304 x 1152]", GGML_TYPE_Q2_0, 1152, 2304}, + {"down Q4_0 [2304 x 1152]", GGML_TYPE_Q4_0, 1152, 2304}, + {"gate|up IQ1_S [2304 x 2304]", GGML_TYPE_IQ1_S, 2304, 2304}, + {"gate|up Q5_0 [2304 x 2304]", GGML_TYPE_Q5_0, 2304, 2304}}; + for (const Mat& m : pm) { + const auto w = random_rows(m.t, m.n_in, m.n_out); + void* dw = upload(w.data(), w.size()); + poly::Mmq::quantize(dxf, nullptr, xq, m.t, m.n_in, m.n_in, rows, bs); + const float us = time_us([&] { + mmq.mul(dw, m.t, m.n_out, m.n_in, 0, 1, xq, nullptr, nullptr, rows, rows, dd, m.n_out, bs); + }, 50); + std::printf("bench %-32s %8.2f us\n", m.name, us); + cudaFree(dw); + } + cudaFree(dx), cudaFree(dy), cudaFree(dxf), cudaFree(xq), cudaFree(dd); +} + +} // namespace + +int main(int argc, char** argv) { + int devices = 0; + if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) { + std::printf("no usable CUDA device: skipped\n"); + return 77; + } + cudaStreamCreateWithFlags(&ts, cudaStreamNonBlocking); + test_iq1_s_decode(); + test_q2_0_decode(); + test_q2_0_mmq(16); + test_q2_0_mmq(300); + if (argc > 1 && std::string(argv[1]) == "bench") bench(); + std::printf("%s: %d failure%s\n", failures ? "FAILED" : "PASSED", failures, failures == 1 ? "" : "s"); + return failures ? 1 : 0; +} diff --git a/src/poly/main.cpp b/src/poly/main.cpp index 0cff329cc5..969e024586 100644 --- a/src/poly/main.cpp +++ b/src/poly/main.cpp @@ -1295,8 +1295,11 @@ int once(Session& ss, const std::vector& ids, const Pictures& pictures, } // --check-batch K: K prompts, the --tokens one without its first 0, 1, ... K-1 tokens, each answered greedily on -// its own and then all of them together in their own sequences (Engine::step()). Returns 1 when a token differs. -int check_batch(Engine& engine, const std::vector& ids, int k, long long max_new) { +// its own and then all of them together in their own sequences (Engine::step()). With --check-stagger the +// sequences differ in all but the model: sequence j's prompt is the first n >> 3 (K - 1 - j) tokens of --tokens' n +// (at least 16), it is read once the others have taken j * max_new / (2K) steps, and it writes max_new - j * max_new +// / K tokens, so that the last steps are the first sequence's alone. Returns 1 when a token differs. +int check_batch(Engine& engine, const std::vector& ids, int k, long long max_new, bool stagger) { const auto read = [&](const std::vector& p) { engine.reset(); for (size_t i = 0; i < p.size(); i += (size_t) engine.max_rows()) { @@ -1305,27 +1308,45 @@ int check_batch(Engine& engine, const std::vector& ids, int k, long lon } return (int32_t) strata::poly::most_likely(engine.logits(), engine.n_vocab()); }; - std::vector> want((size_t) k), got((size_t) k); - std::vector seqs((size_t) k); + std::vector> want((size_t) k), got((size_t) k), prompt((size_t) k); + std::vector wants((size_t) k, max_new), joins((size_t) k, 0); + for (int j = 0; j < k; ++j) { + if (!stagger) { + prompt[(size_t) j].assign(ids.begin() + j, ids.end()); + continue; + } + const int shift = 3 * (k - 1 - j); // a size_t shifted by 64 or more is undefined (k of 23 or more) + const size_t n = std::min(ids.size(), std::max(16, shift < 64 ? ids.size() >> shift : 0)); + prompt[(size_t) j].assign(ids.begin(), ids.begin() + (std::ptrdiff_t) n); + wants[(size_t) j] = max_new - j * max_new / k; + joins[(size_t) j] = j * max_new / (2 * k); + } std::vector next((size_t) k); for (int j = 0; j < k; ++j) { - const std::vector p(ids.begin() + j, ids.end()); engine.bind(0); - int32_t t = read(p); - for (long long n = 0; n < max_new; ++n) { + int32_t t = read(prompt[(size_t) j]); + for (long long n = 0; n < wants[(size_t) j]; ++n) { want[(size_t) j].push_back(t); engine.eval(&t, 1, true); t = (int32_t) strata::poly::most_likely(engine.logits(), engine.n_vocab()); } } - const Clock::time_point t0 = Clock::now(); - for (int j = 0; j < k; ++j) { - seqs[(size_t) j] = j + 1; - engine.bind(j + 1); - next[(size_t) j] = read(std::vector(ids.begin() + j, ids.end())); - } - engine.bind(0); - const double read_ms = ms_since(t0); + // a sequence's prompt is read on its own sequence when it joins: before the first step, or between two steps of + // the others + double read_ms = 0; + std::vector joined((size_t) k, false); + const auto join = [&](long long step) { + const Clock::time_point t0 = Clock::now(); + for (int j = 0; j < k; ++j) + if (!joined[(size_t) j] && joins[(size_t) j] <= step) { + engine.bind(j + 1); + next[(size_t) j] = read(prompt[(size_t) j]); + joined[(size_t) j] = true; + } + engine.bind(0); + read_ms += ms_since(t0); + }; + join(0); const Clock::time_point t1 = Clock::now(); // --batch-mtp: each sequence guesses the token after its next one, a step checks the guesses, and a sequence // that has its max_new tokens leaves the steps @@ -1333,12 +1354,14 @@ int check_batch(Engine& engine, const std::vector& ids, int k, long lon long long steps = 0, offered = 0, right = 0; std::vector live, kept; std::vector feed, guess; + long long tokens = 0; while (true) { + if (stagger) join(steps); live.clear(); feed.clear(); guess.clear(); for (int j = 0; j < k; ++j) - if ((long long) got[(size_t) j].size() < max_new) { + if (joined[(size_t) j] && (long long) got[(size_t) j].size() < wants[(size_t) j]) { got[(size_t) j].push_back(next[(size_t) j]); live.push_back(j + 1); feed.push_back(next[(size_t) j]); @@ -1348,7 +1371,8 @@ int check_batch(Engine& engine, const std::vector& ids, int k, long lon guess.resize(live.size()); engine.draft_many(live.data(), feed.data(), (int) live.size(), guess.data()); for (size_t i = 0; i < live.size(); ++i) { - if ((long long) got[(size_t) live[i] - 1].size() >= max_new) guess[i] = -1; // no token wanted after + if ((long long) got[(size_t) live[i] - 1].size() >= wants[(size_t) live[i] - 1]) + guess[i] = -1; // no token wanted after offered += guess[i] >= 0; } engine.step(live.data(), feed.data(), (int) live.size(), guess.data()); @@ -1356,6 +1380,7 @@ int check_batch(Engine& engine, const std::vector& ids, int k, long lon engine.step(live.data(), feed.data(), (int) live.size()); } ++steps; + tokens += (long long) live.size(); kept.assign(live.size(), 1); for (size_t i = 0, row = 0; i < live.size(); ++i) { const size_t j = (size_t) live[i] - 1; @@ -1372,7 +1397,7 @@ int check_batch(Engine& engine, const std::vector& ids, int k, long lon } if (guessing) engine.keep_step(kept.data()); } - for (int j = 0; j < k; ++j) got[(size_t) j].resize((size_t) max_new); + for (int j = 0; j < k; ++j) got[(size_t) j].resize((size_t) wants[(size_t) j]); const double step_ms = ms_since(t1); if (guessing) std::fprintf(stderr, "check-batch: --batch-mtp: %lld steps, %lld of %lld guesses right\n", steps, right, @@ -1382,12 +1407,16 @@ int check_batch(Engine& engine, const std::vector& ids, int k, long lon size_t same = 0; while (same < want[(size_t) j].size() && want[(size_t) j][same] == got[(size_t) j][same]) ++same; std::fprintf(stderr, "check-batch: sequence %d: the first %zu of %lld tokens as on its own\n", j + 1, same, - max_new); + wants[(size_t) j]); if (same < want[(size_t) j].size()) rc = 1; } - std::fprintf(stderr, "check-batch: %d prompts read in %.0f ms, %lld steps of %d tokens in %.0f ms (%.1f tok/s " - "together)\n", - k, read_ms, max_new, k, step_ms, step_ms > 0 ? 1000.0 * (double) (max_new * k) / step_ms : 0.0); + if (stagger) // the steps' time with the prompts read between them + std::fprintf(stderr, "check-batch: %d prompts read in %.0f ms, %lld steps of %lld tokens in all in %.0f ms\n", + k, read_ms, steps, tokens, step_ms); + else + std::fprintf(stderr, "check-batch: %d prompts read in %.0f ms, %lld steps of %d tokens in %.0f ms (%.1f tok/s " + "together)\n", + k, read_ms, max_new, k, step_ms, step_ms > 0 ? 1000.0 * (double) (max_new * k) / step_ms : 0.0); return rc; } @@ -1400,7 +1429,8 @@ void usage() { "usage: strata-poly --model FILE.gguf (--serve | --tokens ID,ID,... [--max-new N])\n" " --max-context N tokens the attention caches hold (default 8192)\n" " --threads N CPU threads for the experts that are not in VRAM (default: 70%% of the usable\n" - " CPUs; all of them in a container with a CPU quota)\n" + " CPUs; all of them in a container with a CPU quota; one a physical core for\n" + " Inkling 2 Mini)\n" " --vram-reserve-mib N VRAM left free beside the expert cache, 256 at least (default: a\n" " thirty-second of the card, 256 to 768, or a sixteenth, 512 to 1024,\n" " when the PC's free RAM is within 4 GiB of the model's files, and then\n" @@ -1420,12 +1450,14 @@ void usage() { " --window N the most tokens that go through the model at once while an answer is\n" " written: the one that is known and guesses at the ones after it, which\n" " count when they turn out right (1 = no guesses; default 8, of which\n" - " the block guesses 3, and 4 for GLM 5.3 Flash)\n" + " the block guesses 3, 4 for GLM 5.3 Flash, and for Inkling 2 Mini 4\n" + " with its DSpark drafter, else 1: its guesses come from --lookup alone)\n" " --lookup N guess what followed an earlier repeat of the last N or more tokens\n" " (default 3, 0 = never)\n" " --no-draft do not run the block that guesses ahead\n" " --draft-model FILE a file of the same model to take that block from, when --model has none;\n" - " for Gemma 4, its draft model (a gemma4-assistant file)\n" + " for Gemma 4, its draft model (a gemma4-assistant file); for\n" + " Inkling 2 Mini, its DSpark drafter (a dflash file)\n" " --draft-vocab N the block guesses among the vocabulary's first N tokens (default:\n" " 131072 for Qwen3.6, Ornith and Tiel, all of it for the others; 0 = all)\n" " --no-graphs launch a token's kernels one by one (default: a layer's are recorded once\n" @@ -1485,6 +1517,8 @@ void usage() { " --check-batch K with --tokens and --batch K or more: K prompts answered on their own and\n" " then together, compared token by token (takes --kv-whole, so the expert\n" " cache stays as it is)\n" + " --check-stagger with --check-batch: prompts of different lengths (the first n >> 3 (K-1-j)\n" + " tokens), read while the others write, and answers of different lengths\n" " --eos-ids ID,ID,... tokens that end a reply (default: the GGUF's eos, eot and eom)\n" " --temperature F --top-k N --top-p F --min-p F --seed N sampling for --tokens (default greedy)\n" " --images FILE with --tokens: the prompt's pictures, as strata-vision writes them\n" @@ -1505,7 +1539,10 @@ void usage() { "environment: STRATA_ROUTE_TAIL_SKIP=N in place of --tail-skip (0 turns it off)\n" "environment: STRATA_FREEZE_EXPERTS=1 hold the split of the routed experts between the card\n" " and the CPU still, so the same request gives the same greedy answer\n" - " bit for bit; with guesses on, add --window 1 for a repeat everywhere\n"); + " bit for bit; with guesses on, add --window 1 for a repeat everywhere\n" + "environment: STRATA_GPU_EXPERTS=N a test knob: the expert cache holds exactly the first N experts\n" + " (the profile's order), frozen, for the whole run, so that two builds hold\n" + " the same ones; an N the card cannot hold is an error\n"); } } // namespace @@ -1530,6 +1567,7 @@ int main(int argc, char** argv) { bool want_serve = false; long long max_new = 32; int top_probs = 0, lookup = 3, image_pad = -1, check = 0; + bool stagger = false; // --check-stagger std::string images, pinned; std::vector ids, eos, follow; for (int i = 1; i < argc; ++i) { @@ -1591,6 +1629,7 @@ int main(int argc, char** argv) { else if (a == "--batch" || a == "--slots") o.batch = std::atoi(val()); else if (a == "--batch-mtp") o.batch_mtp = true; else if (a == "--check-batch") check = std::atoi(val()); + else if (a == "--check-stagger") stagger = true; else if (a == "--draft-vocab") o.draft_vocab = std::atoi(val()); else if (a == "--prompt-batch") o.prompt_batch = std::atoi(val()); else if (a == "--stage-mib") o.stage_mib = std::atoi(val()); @@ -1713,7 +1752,7 @@ int main(int argc, char** argv) { } else if ((long long) ids.size() + max_new > engine.max_context()) { throw std::runtime_error("the prompt and --max-new together exceed --max-context"); } else if (check > 0) { - rc = check_batch(engine, ids, check, max_new); + rc = check_batch(engine, ids, check, max_new, stagger); } else { Pictures pictures; if (!images.empty()) { diff --git a/src/poly/mmq.cu b/src/poly/mmq.cu index 6149f9d2c7..eaf69b9db5 100644 --- a/src/poly/mmq.cu +++ b/src/poly/mmq.cu @@ -6,13 +6,28 @@ #include "mmq.cuh" #include "quantize.cuh" +#if STRATA_POLY_MMQ_TILES +#include "mmq_tiles.cuh" +#endif + +#include #include +#include #include #include namespace strata::poly { -#if STRATA_POLY_NVFP4 +#if STRATA_POLY_MMQ_TILES +// The types with mul_tiles() kernels: Inkling 2 Mini's experts in its GGUFs (one instance TU each in CMakeLists.txt, +// mmq_tiles_instance.cu.in) +#define STRATA_POLY_MMQ_TILE_TYPES(X) X(Q8_0) X(IQ1_S) X(IQ2_XXS) X(IQ2_XS) X(IQ2_S) X(IQ4_NL) X(Q2_0) +#define X(T) extern template void mul_mat_q_tiles_case(const MmqTilesArgs&, int, size_t, cudaStream_t); +STRATA_POLY_MMQ_TILE_TYPES(X) +#undef X +#endif + +#if STRATA_POLY_NVFP4 || STRATA_POLY_NVFP4_INT8 // mmq_nvfp4.cu void nvfp4_w4a8(ggml_backend_cuda_context& ctx, const mmq_args& a, cudaStream_t s); bool nvfp4_w4a8_fits(int64_t w_rows, int cc, size_t smpbo); @@ -24,21 +39,34 @@ namespace { // The types with kernels in this build: one template instance each in CMakeLists.txt. #define STRATA_POLY_MMQ_TYPES(X) \ X(Q4_0) X(Q4_1) X(Q5_0) X(Q5_1) X(Q8_0) X(Q2_K) X(Q3_K) X(Q4_K) X(Q5_K) X(Q6_K) \ - X(IQ1_S) X(IQ2_XXS) X(IQ2_XS) X(IQ2_S) X(IQ3_XXS) X(IQ3_S) X(IQ4_NL) X(IQ4_XS) X(MXFP4) + X(IQ1_S) X(IQ2_XXS) X(IQ2_XS) X(IQ2_S) X(IQ3_XXS) X(IQ3_S) X(IQ4_NL) X(IQ4_XS) X(MXFP4) X(Q2_0) int64_t pad512(int64_t n) { return (n + 511) / 512 * 512; } // NVFP4's prompt products: on RTX 50, with STRATA_PREFILL_NVFP4=w4a4, FP4 x FP4 on its FP4 tensor cores (the // instance built for 12.0a, as MXFP4's); otherwise, as on every other card, the weights decoded to int8 times Q8_1 // rows (mmq_nvfp4.cu). -bool nvfp4_fp4(int cc) { - static const bool asked = [] { +const std::string& nvfp4_mode() { + static const std::string mode = [] { const char* v = std::getenv("STRATA_PREFILL_NVFP4"); - return v != nullptr && std::string(v) == "w4a4"; + return std::string(v ? v : ""); }(); - return asked && cc == GGML_CUDA_CC_BLACKWELL; + return mode; } +bool nvfp4_fp4(int cc) { return nvfp4_mode() == "w4a4" && cc == GGML_CUDA_CC_BLACKWELL; } + +#if STRATA_POLY_NVFP4_INT8 +// HIP builds mmq_nvfp4.cu's int8 tiles and none of CUDA's FP4 ones. An NVFP4 matrix takes them where the caller +// allows them (Engine::nvfp4_int8_: Inkling 2) or STRATA_PREFILL_NVFP4=w4a8 asks for them; w4a4 and w4a4x2 ask for +// products HIP does not have and leave the choice as it was, and any other value keeps them out. +bool nvfp4_int8_on(Mmq::Allow allow) { + const std::string& m = nvfp4_mode(); + if (m == "w4a8") return true; + return (m.empty() || m == "w4a4" || m == "w4a4x2") && (allow & Mmq::nvfp4_int8); +} +#endif + // The float each row of NVFP4's FP4 rows carries (quantize_mmq_fp4_cuda's scale) goes behind the blocks and the // tiles' tail, in the room q8_bytes() leaves: FP4 blocks take half the bytes of Q8_1's. float* fp4_scales(void* xq, int64_t rows, int64_t cols) { @@ -57,6 +85,12 @@ Mmq::Mmq() { ctx_ = new ggml_backend_cuda_context(ggml_cuda_get_device()); } Mmq::~Mmq() { delete (ggml_backend_cuda_context*) ctx_; } +void Mmq::reserve_fixup() { + auto& ctx = *(ggml_backend_cuda_context*) ctx_; + const int nsm = ggml_cuda_info().devices[ggml_cuda_get_device()].nsm; + ggml_cuda_pool_alloc tmp(ctx.pool(), (size_t) nsm * 128 * 128); // the largest tile is 128 x 128 +} + // mul_mat_q_case's own choice: a tile size whose configuration exists for this card and fits its shared memory. // It aborts the process when there is none. // @@ -64,9 +98,10 @@ Mmq::~Mmq() { delete (ggml_backend_cuda_context*) ctx_; } // step they read on into what lies behind it, and multiply that by the zeros quantize() pads the rows of x with. // So what lies behind a matrix must be readable and must not be read as an infinite block scale: the engine keeps // zero bytes there (kTail in runtime.hpp), as ggml-cuda does behind its tensors. -bool Mmq::fits(int type, int64_t w_rows, int64_t w_cols) { +bool Mmq::fits(int type, int64_t w_rows, int64_t w_cols, Allow allow) { const ggml_type t = (ggml_type) type; const auto& dev = ggml_cuda_info().devices[ggml_cuda_get_device()]; + if (t == GGML_TYPE_Q2_0 && !(allow & q2_0)) return false; switch (t) { #define X(T) case GGML_TYPE_##T: STRATA_POLY_MMQ_TYPES(X) @@ -77,6 +112,10 @@ bool Mmq::fits(int type, int64_t w_rows, int64_t w_cols) { if (w_cols % QK_NVFP4 != 0) return false; if (!nvfp4_fp4(dev.cc)) return nvfp4_w4a8_fits(w_rows, dev.cc, dev.smpbo); break; +#elif STRATA_POLY_NVFP4_INT8 + case GGML_TYPE_NVFP4: + if (w_cols % QK_NVFP4 != 0 || !nvfp4_int8_on(allow)) return false; + return nvfp4_w4a8_fits(w_rows, dev.cc, dev.smpbo); #endif default: return false; } @@ -109,6 +148,8 @@ bool Mmq::split_exact(int type, int64_t w_rows) { const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; #if STRATA_POLY_NVFP4 if (t == GGML_TYPE_NVFP4 && !nvfp4_fp4(cc)) return !nvfp4_w4a8_stream_k(w_rows, cc); +#elif STRATA_POLY_NVFP4_INT8 + if (t == GGML_TYPE_NVFP4) return !nvfp4_w4a8_stream_k(w_rows, cc); #endif for (int J = 8; J <= 128; J += 8) { const ggml_cuda_mmq_config c = ggml_cuda_mmq_get_config(t, J, fallback, cc); @@ -178,10 +219,122 @@ void Mmq::mul(const void* w, int type, int64_t w_rows, int64_t w_cols, size_t st nvfp4_w4a8(ctx, a, s); } break; +#elif STRATA_POLY_NVFP4_INT8 + case GGML_TYPE_NVFP4: nvfp4_w4a8(ctx, a, s); break; #endif default: throw std::runtime_error("mmq: tensor type " + std::to_string(type) + " is not built"); } ck("mmq product"); } +bool Mmq::tiles_fit(int type, int64_t w_rows, int64_t w_cols, bool q2_0) { +#if STRATA_POLY_MMQ_TILES + const ggml_type t = (ggml_type) type; + if (t == GGML_TYPE_Q2_0 && !q2_0) return false; + switch (t) { +#define X(T) case GGML_TYPE_##T: + STRATA_POLY_MMQ_TILE_TYPES(X) +#undef X + break; + default: return false; + } + const auto& dev = ggml_cuda_info().devices[ggml_cuda_get_device()]; + int anchor_of[mmq_tiles::kNWidths]; + size_t shared_of[mmq_tiles::kNWidths]; + if (mmq_tiles::widths(t, dev.cc, dev.smpbo, anchor_of, shared_of) == 0 || anchor_of[mmq_tiles::kNWidths - 1] == 0) + return false; + for (int k = 0; k < mmq_tiles::kNWidths; ++k) // every launch's row tiles cover the matrix + if (anchor_of[k] && w_rows % ggml_cuda_mmq_get_config(t, anchor_of[k], false, dev.cc).I != 0) return false; + return w_cols % ggml_blck_size(t) == 0; +#else + (void) type; + (void) w_rows; + (void) w_cols; + (void) q2_0; + return false; +#endif +} + +void Mmq::plan_tiles(int type, const int32_t* first, const int32_t* rows, const int32_t* mat, int n, + std::vector& out) { +#if STRATA_POLY_MMQ_TILES + const auto& dev = ggml_cuda_info().devices[ggml_cuda_get_device()]; + int anchor_of[mmq_tiles::kNWidths]; + size_t shared_of[mmq_tiles::kNWidths]; + mmq_tiles::widths((ggml_type) type, dev.cc, dev.smpbo, anchor_of, shared_of); + constexpr int widest = mmq_tiles::kWidths[mmq_tiles::kNWidths - 1]; + if (anchor_of[mmq_tiles::kNWidths - 1] == 0) + throw std::runtime_error("mmq: no tiles for tensor type " + std::to_string(type)); + std::vector order((size_t) n); + std::iota(order.begin(), order.end(), 0); + std::stable_sort(order.begin(), order.end(), [&](int a, int b) { return rows[a] > rows[b]; }); + // the tiles of each anchor's launch, the widest anchor's first + std::vector other; + for (const int i : order) { + int at = first[i]; + const int end = first[i] + rows[i]; + for (; end - at >= widest; at += widest) out.push_back({at, widest, mat[i], widest}); + if (at < end) { + int k = 0; + while (anchor_of[k] == 0 || mmq_tiles::kWidths[k] < end - at) ++k; + const Tile t = {at, end - at, mat[i], mmq_tiles::kWidths[k]}; + (anchor_of[k] == widest ? out : other).push_back(t); + } + } + std::stable_sort(other.begin(), other.end(), [&](const Tile& a, const Tile& b) { + const auto anc = [&](const Tile& t) { // t.width is one of kWidths: the loop above took it from there + const int* w = std::find(mmq_tiles::kWidths, mmq_tiles::kWidths + mmq_tiles::kNWidths, t.width); + if (w == mmq_tiles::kWidths + mmq_tiles::kNWidths) throw std::logic_error("mmq: a tile of no width"); + return anchor_of[w - mmq_tiles::kWidths]; + }; + return anc(a) > anc(b); + }); + out.insert(out.end(), other.begin(), other.end()); +#else + (void) type; + (void) first; + (void) rows; + (void) mat; + (void) n; + (void) out; + throw std::runtime_error("mmq: this build has no tiles"); +#endif +} + +void Mmq::mul_tiles(const void* w, const int64_t* at, int type, int64_t w_rows, int64_t w_cols, const void* xq, + int64_t row0, int64_t xq_rows, const Tile* tiles, const Tile* host_tiles, int n_tiles, + const int32_t* ids, float* dst, int64_t ld_dst, void* stream) { + if (n_tiles <= 0) return; +#if STRATA_POLY_MMQ_TILES + const ggml_type t = (ggml_type) type; + const auto& dev = ggml_cuda_info().devices[ggml_cuda_get_device()]; + const MmqTilesArgs a = {(const char*) w, at, (const int*) xq, ids, tiles, host_tiles, dst, n_tiles, (int) w_rows, + (int) w_cols, (int) xq_rows, (int) ld_dst, (int) row0}; + const cudaStream_t s = (cudaStream_t) stream; + switch (t) { +#define X(T) case GGML_TYPE_##T: mul_mat_q_tiles_case(a, dev.cc, dev.smpbo, s); break; + STRATA_POLY_MMQ_TILE_TYPES(X) +#undef X + default: throw std::runtime_error("mmq: tensor type " + std::to_string(type) + " has no tiles"); + } + ck("mmq tiles"); +#else + (void) w; + (void) at; + (void) type; + (void) w_rows; + (void) w_cols; + (void) xq; + (void) row0; + (void) xq_rows; + (void) tiles; + (void) host_tiles; + (void) ids; + (void) dst; + (void) ld_dst; + (void) stream; + throw std::runtime_error("mmq: this build has no tiles"); +#endif +} + } // namespace strata::poly diff --git a/src/poly/mmq.hpp b/src/poly/mmq.hpp index 98c5802d2d..72790b1b6b 100644 --- a/src/poly/mmq.hpp +++ b/src/poly/mmq.hpp @@ -7,6 +7,7 @@ #include #include +#include namespace strata::poly { @@ -17,8 +18,14 @@ class Mmq { Mmq(const Mmq&) = delete; Mmq& operator=(const Mmq&) = delete; + /// The products a caller lets a matrix take besides the default ones. + /// q2_0: Q2_0's tiles (Engine::lowbit_experts_). + /// nvfp4_int8: on HIP, NVFP4's int8 tiles (mmq_nvfp4.cu) unless STRATA_PREFILL_NVFP4 keeps them out + /// (Engine::nvfp4_int8_); CUDA takes them for NVFP4 always. + enum Allow : unsigned { none = 0, q2_0 = 1u << 0, nvfp4_int8 = 1u << 2 }; + /// This build multiplies ggml_type, and the card has a tile for a matrix of [w_rows, w_cols] of it. - static bool fits(int ggml_type, int64_t w_rows, int64_t w_cols); + static bool fits(int ggml_type, int64_t w_rows, int64_t w_cols, Allow allow = none); /// Bytes of `rows` rows of `cols` values as quantize() writes them. static size_t q8_bytes(int64_t rows, int64_t cols); /// quantize() keeps the rows' block sums in halves for a matrix of ggml_type (guard_half_sums()). @@ -33,6 +40,10 @@ class Mmq { /// call whole. static void quantize(const float* x, const int32_t* ids, void* xq, int ggml_type, int64_t cols, int64_t ld, int64_t rows, void* stream); + /// The scratch the products take at their first launch with a split of tiles (llama.cpp's stream-k fixup, at + /// most a tile of floats a multiprocessor), taken now: it is VRAM a card that later has none to spare would + /// fail to get (Inkling 2 at a long prompt after short ones). + void reserve_fixup(); /// One launch over n matrices of [w_rows, w_cols], `stride` bytes apart from w: matrix e times the rows /// [bounds[e], bounds[e + 1]) of xq, which quantize() wrote with total_rows rows. Row i's product goes to row @@ -43,6 +54,30 @@ class Mmq { const int32_t* bounds, const int32_t* ids, int64_t total_rows, int64_t max_rows, float* dst, int64_t ld_dst, void* stream); + /// A tile of mul_tiles(): rows [row, row + rows) of the call's rows times matrix `mat`, in a tile `width` + /// columns wide (a width plan_tiles() chose, rows <= width). + struct alignas(16) Tile { + int32_t row, rows, mat, width; + }; + /// mul_tiles() has kernels for ggml_type on this card, and a matrix of [w_rows, w_cols] of it takes them. Q2_0 + /// only when `q2_0`, as fits(). CUDA builds only. + static bool tiles_fit(int ggml_type, int64_t w_rows, int64_t w_cols, bool q2_0 = false); + /// Appends to `out` the tiles of matrix mat[i] times the rows [first[i], first[i] + rows[i]), for each i < n with + /// rows: as many 128 rows wide as it fills, then one of the narrowest width that holds the rest; the matrices + /// with the most rows first, a matrix's tiles one after the other (they read the same weights). On a card whose + /// narrow tiles take another block shape (RDNA4), those come after the others, a launch of their own. + static void plan_tiles(int ggml_type, const int32_t* first, const int32_t* rows, const int32_t* mat, int n, + std::vector& out); + /// The product over a table of n_tiles tiles, on the device and here (one launch, or one for each block shape + /// the table has: see plan_tiles()): matrix m is [w_rows, w_cols] at w + at[m] bytes (at + /// on the device); a tile's rows are rows of xq counted from row0, which quantize() wrote with xq_rows rows, and + /// row i's product goes to row ids[i - row0] of dst, ld_dst floats a row. Each output is one block's sum over + /// the whole of K, in the order llama.cpp's MMQ adds a tile it does not split (stream-k): the same to the bit + /// whatever the tiles' widths and however the tiles are shared out between launches. Throws std::runtime_error. + void mul_tiles(const void* w, const int64_t* at, int ggml_type, int64_t w_rows, int64_t w_cols, const void* xq, + int64_t row0, int64_t xq_rows, const Tile* tiles, const Tile* host_tiles, int n_tiles, + const int32_t* ids, float* dst, int64_t ld_dst, void* stream); + private: void* ctx_ = nullptr; ///< llama.cpp's launch context: a small scratch pool }; diff --git a/src/poly/mmq_tiles.cuh b/src/poly/mmq_tiles.cuh new file mode 100644 index 0000000000..724fdd6718 --- /dev/null +++ b/src/poly/mmq_tiles.cuh @@ -0,0 +1,187 @@ +// src/poly/mmq_tiles.cuh - Mmq::mul_tiles(): llama.cpp's MMQ tiles (ggml-cuda mmq.cuh, MIT) launched over a table of +// tiles instead of a grid of every matrix's column tiles. Included only by the per-type instance TUs (CMake: +// mmq_tiles_instance.cu.in); mmq.cu sees the declaration below. +// +// The kernel is the branch of llama.cpp's mul_mat_q that gives each block one whole tile (the one it takes where a +// launch does not use stream-k), with three changes: a block's tile - its matrix, first row, rows and width - comes +// from the table; a matrix is found by its byte offset from one base pointer; and the tile's width is the table's, +// one of kWidths, so one launch has tiles of several widths. Each width runs llama.cpp's own +// mul_mat_q_process_tile, loaders, vec_dot and write_back for that width. A block sums its tile over the whole of K +// in K's order, as llama.cpp does every tile it does not split, and an output's sum does not depend on the width of +// its tile: the results are the same to the bit however the rows are cut into tiles and the tiles into launches +// (poly_mmq_tiles_test checks them against llama.cpp's MMQ run so that it splits nothing). +#pragma once + +#include "common.cuh" +#include "mmq.cuh" +#include "mmq.hpp" + +#include + +namespace strata::poly { + +struct MmqTilesArgs { + const char* x; // the base the matrices' offsets count from + const int64_t* at; // per matrix: bytes from x + const int* y; // the rows, as Mmq::quantize() wrote them + const int32_t* ids; // row i - row0 of y goes to row ids[i - row0] of dst + const Mmq::Tile* tiles; // on the device + const Mmq::Tile* host_tiles; // the same, here: where a launch's anchor changes + float* dst; + int n_tiles, nrows_x, ncols_x, ncols_y, nrows_dst, row0; +}; + +template void mul_mat_q_tiles_case(const MmqTilesArgs& a, int cc, size_t smpbo, cudaStream_t s); + +namespace mmq_tiles { + +constexpr int kWidths[] = {16, 32, 48, 64, 96, 128}; +constexpr int kNWidths = (int) (sizeof(kWidths) / sizeof(kWidths[0])); + +// A launch has one block shape - threads and rows of the weights a block - and takes the tiles of every width that +// llama.cpp configures with the shape of its anchor, the widest such width in kWidths. One anchor (128) on NVIDIA, +// where every width has 256 threads and 128 rows; two on RDNA4 (up to 64 columns: 128 threads, 64 rows). +constexpr __device__ bool same_shape(ggml_type type, int J, int A) { + const ggml_cuda_mmq_config c = ggml_cuda_mmq_get_config(type, J, false); + const ggml_cuda_mmq_config w = ggml_cuda_mmq_get_config(type, A, false); + return c.type != GGML_TYPE_COUNT && w.type != GGML_TYPE_COUNT && c.nthreads == w.nthreads && c.I == w.I; +} + +constexpr __device__ bool anchor(ggml_type type, int A) { + if (!same_shape(type, A, A)) return false; + for (const int W : kWidths) + if (W > A && same_shape(type, W, A)) return false; + return true; +} + +template +static __device__ __forceinline__ void tile(const char* __restrict__ x, const int* __restrict__ y, + const int32_t* __restrict__ ids, float* __restrict__ dst, + const Mmq::Tile t, const int it, const int blocks_per_ne00, + const int nrows_x, const int stride_row_x, const int ncols_y, + const int stride_col_dst, const int row0) { + if constexpr (!same_shape(type, J, A)) { + NO_DEVICE_CODE; + } else { + constexpr int warp_size = ggml_cuda_get_physical_warp_size(); + constexpr int nwarps = ggml_cuda_mmq_get_nthreads(type, J, false) / warp_size; + constexpr int I = ggml_cuda_mmq_get_I(type, J, false); + extern __shared__ int ids_dst_shared[]; // the first J ints of mul_mat_q_process_tile's shared memory + const int r = t.row - row0; +#pragma unroll + for (int j0 = 0; j0 < J; j0 += nwarps * warp_size) { + const int j = j0 + threadIdx.y * warp_size + threadIdx.x; + if (j0 + nwarps * warp_size > J && j >= J) break; + ids_dst_shared[j] = j < t.rows ? ids[r + j] : 0; + } + __syncthreads(); + const int offset_y = r * (int) (sizeof(block_q8_1_mmq) / sizeof(int)); + mul_mat_q_process_tile(x, it * I * stride_row_x, y + offset_y, ids_dst_shared, + dst + it * I, nullptr, nullptr, stride_row_x, ncols_y, + stride_col_dst, nrows_x - it * I - 1, t.rows - 1, 0, + blocks_per_ne00); + } +} + +// grid: (row tiles of the matrices, tiles of the table); a block reads its tile from the table. Compiled only for an +// anchor of the architecture it is built for (a stub elsewhere). +template +__launch_bounds__(ggml_cuda_mmq_get_nthreads(type, A, false), ggml_cuda_mmq_get_occupancy(type, A, false)) +static __global__ void mul_mat_q_tiles(const char* __restrict__ x, const int64_t* __restrict__ at, + const int* __restrict__ y, const int32_t* __restrict__ ids, + const Mmq::Tile* __restrict__ tiles, float* __restrict__ dst, + const int blocks_per_ne00, const int nrows_x, const int stride_row_x, + const int ncols_y, const int stride_col_dst, const int row0) { + if constexpr (!anchor(type, A)) { + NO_DEVICE_CODE; + } else { + const Mmq::Tile t = tiles[blockIdx.y]; + const char* xm = x + at[t.mat]; + const int it = blockIdx.x; +#define STRATA_TILE(J) \ + case J: \ + tile(xm, y, ids, dst, t, it, blocks_per_ne00, nrows_x, stride_row_x, ncols_y, stride_col_dst, \ + row0); \ + break; + switch (t.width) { + STRATA_TILE(16) + STRATA_TILE(32) + STRATA_TILE(48) + STRATA_TILE(64) + STRATA_TILE(96) + STRATA_TILE(128) + default: break; + } +#undef STRATA_TILE + } +} + +// The widths of the type on a card (host side): for each of kWidths, out[k] = its anchor, or 0 where llama.cpp has no +// configuration for it or the card has not its shared memory. The shared memory of an anchor's launch: the most of +// its widths'. Returns how many widths there are. +inline int widths(ggml_type type, int cc, size_t smpbo, int* anchor_of, size_t* shared_of) { + int n = 0; + for (int k = 0; k < kNWidths; ++k) { + anchor_of[k] = 0; + shared_of[k] = 0; + } + for (int k = 0; k < kNWidths; ++k) { + const ggml_cuda_mmq_config c = ggml_cuda_mmq_get_config(type, kWidths[k], false, cc); + if (c.type == GGML_TYPE_COUNT || mmq_get_nbytes_shared(c, cc) > smpbo) continue; + int a = k; // the widest width of the same shape + for (int m = k + 1; m < kNWidths; ++m) { + const ggml_cuda_mmq_config d = ggml_cuda_mmq_get_config(type, kWidths[m], false, cc); + if (d.type != GGML_TYPE_COUNT && d.nthreads == c.nthreads && d.I == c.I) a = m; + } + anchor_of[k] = kWidths[a]; + shared_of[a] = std::max(shared_of[a], mmq_get_nbytes_shared(c, cc)); + ++n; + } + return n; +} + +template +void launch(const MmqTilesArgs& a, int first, int count, size_t shared, int cc, cudaStream_t s) { + CUDA_SET_SHARED_MEMORY_LIMIT((mul_mat_q_tiles), shared); + const ggml_cuda_mmq_config w = ggml_cuda_mmq_get_config(type, A, false, cc); + const int warp_size = ggml_cuda_info().devices[ggml_cuda_get_device()].warp_size; + const dim3 blocks((unsigned) (a.nrows_x / w.I), (unsigned) count, 1); + const dim3 threads((unsigned) warp_size, (unsigned) (w.nthreads / warp_size), 1); + const int bpr = a.ncols_x / ggml_cuda_type_traits::qk; + mul_mat_q_tiles<<>>(a.x, a.at, a.y, a.ids, a.tiles + first, a.dst, bpr, + a.nrows_x, bpr, a.ncols_y, a.nrows_dst, a.row0); +} + +} // namespace mmq_tiles + +// A launch for each run of tiles of one anchor in the table (plan_tiles() puts them one anchor after the other). +template void mul_mat_q_tiles_case(const MmqTilesArgs& a, int cc, size_t smpbo, cudaStream_t s) { + int anchor_of[mmq_tiles::kNWidths]; + size_t shared_of[mmq_tiles::kNWidths]; + GGML_ASSERT(mmq_tiles::widths(type, cc, smpbo, anchor_of, shared_of) > 0); + for (int i = 0; i < a.n_tiles;) { + const int A = anchor_of[std::find(mmq_tiles::kWidths, mmq_tiles::kWidths + mmq_tiles::kNWidths, + a.host_tiles[i].width) - mmq_tiles::kWidths]; + int j = i + 1; + while (j < a.n_tiles && + anchor_of[std::find(mmq_tiles::kWidths, mmq_tiles::kWidths + mmq_tiles::kNWidths, + a.host_tiles[j].width) - mmq_tiles::kWidths] == A) + ++j; + const size_t shared = + shared_of[std::find(mmq_tiles::kWidths, mmq_tiles::kWidths + mmq_tiles::kNWidths, A) - mmq_tiles::kWidths]; + switch (A) { +#define STRATA_ANCHOR(W) case W: mmq_tiles::launch(a, i, j - i, shared, cc, s); break; + STRATA_ANCHOR(16) + STRATA_ANCHOR(32) + STRATA_ANCHOR(48) + STRATA_ANCHOR(64) + STRATA_ANCHOR(96) + STRATA_ANCHOR(128) +#undef STRATA_ANCHOR + default: GGML_ABORT("mmq tiles: width %d", a.host_tiles[i].width); + } + i = j; + } +} + +} // namespace strata::poly diff --git a/src/poly/mmq_tiles_instance.cu.in b/src/poly/mmq_tiles_instance.cu.in new file mode 100644 index 0000000000..3fc50d81f2 --- /dev/null +++ b/src/poly/mmq_tiles_instance.cu.in @@ -0,0 +1,7 @@ +// Generated by CMake from src/poly/mmq_tiles_instance.cu.in: Mmq::mul_tiles()'s kernel for one type, in its own TU so +// nvcc builds the types in parallel. +#include "mmq_tiles.cuh" + +namespace strata::poly { +template void mul_mat_q_tiles_case(const MmqTilesArgs&, int, size_t, cudaStream_t); +} // namespace strata::poly diff --git a/src/poly/mmq_tiles_test.cu b/src/poly/mmq_tiles_test.cu index 9fbbe8953a..6432f8f242 100644 --- a/src/poly/mmq_tiles_test.cu +++ b/src/poly/mmq_tiles_test.cu @@ -1,23 +1,37 @@ -// src/poly/mmq_tiles_test.cu - the size-class launches of STRATA_POLY_STAGED_TILES (engine.cpp, moe_rows) give the same -// results as one launch: to the bit, except on a card whose MMQ uses stream-k (Mmq::split_exact()), where they are -// the same products added in another order and must agree within rounding. llama.cpp's MMQ takes a launch's tile -// width from the largest expert in it, so the engine launches the experts of up to N rows apart from the larger -// ones, each class with bounds in which the other classes' experts have no rows, over rows laid out class after -// class. That layout is built here the way the engine builds it, for row counts with many small experts, a few -// large, empty ones and equal ones. +// src/poly/mmq_tiles_test.cu - two ways of cutting a prompt batch's expert products into launches, against one launch: // -// usage: poly_mmq_tiles_test (exit 0: every case agrees; 77: no card) +// 1. The size-class launches of STRATA_POLY_STAGED_TILES (engine.cpp, moe_rows) give the same results as one launch: +// to the bit, except on a card whose MMQ uses stream-k (Mmq::split_exact()), where they are the same products added +// in another order and must agree within rounding. llama.cpp's MMQ takes a launch's tile width from the largest +// expert in it, so the engine launches the experts of up to N rows apart from the larger ones, each class with +// bounds in which the other classes' experts have no rows, over rows laid out class after class. That layout is +// built here the way the engine builds it, for row counts with many small experts, a few large, empty ones and +// equal ones. +// 2. Mmq::mul_tiles() (STRATA_POLY_EXPERT_TILES), for each type it has kernels for, against llama.cpp's MMQ launched +// so that it splits no tile (a grid of exactly the card's multiprocessors times the row tiles, every tile its own +// block): to the bit on every card, with the tiles in one launch and in several, from row 0 and from a later row. +// How many rows differ from llama.cpp's own launch (stream-k on most cards) is printed, not checked. +// +// usage: poly_mmq_tiles_test (exit 0: every case agrees; 77: no card) +// poly_mmq_tiles_test bench FILE Inkling 2 Mini's expert shapes, rows per expert from FILE (a line of counts +// a layer call), llama.cpp's launches against mul_tiles(): microseconds, TOPS #include "mmq.hpp" #include +#include "ggml.h" + #include #include #include #include #include #include +#include +#include #include +#include +#include #include #include @@ -131,14 +145,296 @@ int run_case(const Quant& q, const std::vector& rows, const std::vector random_matrices(int type, int64_t w_rows, int64_t w_cols, int n, size_t* per, std::mt19937& rng) { + const size_t bs = ggml_type_size((ggml_type) type); + const int64_t bk = ggml_blck_size((ggml_type) type); + *per = (size_t) w_rows * (size_t) (w_cols / bk) * bs; + std::vector w(*per * n + 4096, 0); + for (size_t i = 0; i < *per * n; ++i) w[i] = (uint8_t) rng(); + for (size_t b = 0; b < *per * n / bs; ++b) w[b * bs + 1] = (uint8_t) (0x30 | (rng() & 3)); + return w; +} + +struct Buffers { // cudaFree on the way out + std::vector p; + template T* add(T* q) { if (q) p.push_back((void*) q); return q; } + void* alloc(size_t bytes) { void* q = nullptr; return cudaMalloc(&q, bytes) == cudaSuccess ? add(q) : nullptr; } + ~Buffers() { for (void* q : p) cudaFree(q); } +}; + +// One case: matrix e times rows[e] rows. Returns the rows that differ from the reference in any of the three ways of +// launching the tiles (-1: a CUDA error); *vs_launch gets the rows in which llama.cpp's own launch differs from it. +int run_tiles(const TileType& q, const std::vector& rows, int nsm, std::mt19937& rng, int* vs_launch) { + constexpr int64_t kR = 256, kC = 768; // three of MMQ's K steps + const int n = (int) rows.size(); + size_t per = 0; + const std::vector w = random_matrices(q.type, kR, kC, n, &per, rng); + std::vector start(n + 1, 0), mat(n); + for (int e = 0; e < n; ++e) start[(size_t) e + 1] = start[(size_t) e] + rows[(size_t) e]; + std::iota(mat.begin(), mat.end(), 0); + const int total = start[(size_t) n]; + std::vector x((size_t) total * kC); + for (auto& v : x) v = (float) ((rng() & 0xffff) / 32768.0 - 1.0); + std::vector iota(total); + std::iota(iota.begin(), iota.end(), 0); + std::vector at(n); + for (int e = 0; e < n; ++e) at[(size_t) e] = (int64_t) e * (int64_t) per; + // the tiles of every matrix, and of the second half's from a later row (as a staging round's down product) + const int h = n / 2, row0 = start[(size_t) h]; + std::vector all, late; + Mmq::plan_tiles(q.type, start.data(), rows.data(), mat.data(), n, all); + Mmq::plan_tiles(q.type, start.data() + h, rows.data() + h, mat.data() + h, n - h, late); + std::vector tiles(all); + tiles.insert(tiles.end(), late.begin(), late.end()); + + Buffers b; + Mmq mmq; + const size_t out = (size_t) total * kR * sizeof(float); + uint8_t* dw = b.add(upload(w)); + float* dx = b.add(upload(x)); + int32_t *d_iota = b.add(upload(iota)), *d_start = b.add(upload(start)); + int64_t* d_at = b.add(upload(at)); + Mmq::Tile* d_tiles = b.add(upload(tiles)); + void *xq = b.alloc(Mmq::q8_bytes(total, kC)), *xq2 = b.alloc(Mmq::q8_bytes(total, kC)); + float *ref = (float*) b.alloc(out), *own = (float*) b.alloc(out), *one = (float*) b.alloc(out), + *three = (float*) b.alloc(out), *from = (float*) b.alloc(out); + if (!dw || !dx || !d_iota || !d_start || !d_at || !d_tiles || !xq || !xq2 || !ref || !own || !one || !three || !from) + return -1; + for (float* d : {ref, own, one, three, from}) cudaMemset(d, 0, out); + const int most = *std::max_element(rows.begin(), rows.end()); + Mmq::quantize(dx, nullptr, xq, q.type, kC, kC, total, nullptr); + Mmq::quantize(dx + (size_t) row0 * kC, nullptr, xq2, q.type, kC, kC, total - row0, nullptr); + // the reference: as many column tiles as the card has multiprocessors, so llama.cpp's grid is every tile a block + mmq.mul(dw, q.type, kR, kC, per, n, xq, d_start, d_iota, total, 128 * (int64_t) nsm, ref, kR, nullptr); + mmq.mul(dw, q.type, kR, kC, per, n, xq, d_start, d_iota, total, most, own, kR, nullptr); + const int nt = (int) all.size(); + mmq.mul_tiles(dw, d_at, q.type, kR, kC, xq, 0, total, d_tiles, tiles.data(), nt, d_iota, one, kR, nullptr); + for (int k = 0; k < 3; ++k) { // the same tiles in three launches + const int a = nt * k / 3, z = nt * (k + 1) / 3; + mmq.mul_tiles(dw, d_at, q.type, kR, kC, xq, 0, total, d_tiles + a, tiles.data() + a, z - a, d_iota, three, kR, + nullptr); + } + mmq.mul_tiles(dw, d_at, q.type, kR, kC, xq2, row0, total - row0, d_tiles + nt, tiles.data() + nt, (int) late.size(), + d_iota + row0, from, kR, nullptr); + if (!ok(cudaDeviceSynchronize(), "run")) return -1; + std::vector r((size_t) total * kR), o(r.size()), u(r.size()), t(r.size()), f(r.size()); + cudaMemcpy(r.data(), ref, out, cudaMemcpyDeviceToHost); + cudaMemcpy(o.data(), own, out, cudaMemcpyDeviceToHost); + cudaMemcpy(u.data(), one, out, cudaMemcpyDeviceToHost); + cudaMemcpy(t.data(), three, out, cudaMemcpyDeviceToHost); + cudaMemcpy(f.data(), from, out, cudaMemcpyDeviceToHost); + int bad = 0; + *vs_launch = 0; + for (int i = 0; i < total; ++i) { + const size_t a = (size_t) i * kR, bytes = kR * sizeof(float); + const bool same = std::memcmp(&u[a], &r[a], bytes) == 0 && std::memcmp(&t[a], &r[a], bytes) == 0 && + (i < row0 || std::memcmp(&f[a], &r[a], bytes) == 0); + bad += !same; + *vs_launch += std::memcmp(&o[a], &r[a], bytes) != 0; + } + return bad; +} + +int test_tiles(std::mt19937& rng) { + int nsm = 0; + cudaDeviceGetAttribute(&nsm, cudaDevAttrMultiProcessorCount, 0); + struct Dist { const char* name; std::vector rows; }; + std::vector dists; + dists.push_back({"widths' edges", {1, 15, 16, 17, 31, 32, 33, 47, 48, 49, 63, 64, 65, 95, 96, 97, 127, 128, 129, 0, + 255, 256, 257, 383}}); + { // a layer of a prompt batch: 1,024 tokens of 8 experts in 128, a few popular + std::vector r(128); + for (int i = 0; i < 1024 * 8; ++i) { + const double u = (double) (rng() % 1000000) / 1000000.0; + ++r[(size_t) std::min(127, (int) (128 * u * u))]; + } + dists.push_back({"skewed layer", r}); + } + { + std::vector r; + for (int e = 0; e < 40; ++e) r.push_back(rng() % 3 == 0 ? 0 : 1 + (int) (rng() % 200)); + dists.push_back({"random", r}); + } + int failures = 0, cases = 0; + for (const TileType& q : kTileTypes) { + if (!Mmq::tiles_fit(q.type, 256, 768, true)) { + std::printf("tiles %s: no kernel in this build or on this card: skipped\n", q.name); + continue; + } + for (const Dist& d : dists) { + int vs = 0; + const int bad = run_tiles(q, d.rows, nsm, rng, &vs); + ++cases; + const int total = std::accumulate(d.rows.begin(), d.rows.end(), 0); + if (bad != 0) ++failures; + std::printf("%s tiles %s %s: %d of %d rows differ from llama.cpp's unsplit tiles; llama.cpp's own launch " + "differs from them in %d\n", bad == 0 ? "ok " : "FAIL", q.name, d.name, bad, total, vs); + } + } + if (failures) std::printf("FAIL: %d of %d tile cases\n", failures, cases); + return failures; +} + +// ---- bench ---- + +struct Product { const char* name; int type; int64_t w_rows, w_cols; }; + +double time_ms(const std::function& f) { + cudaEvent_t a, z; + cudaEventCreate(&a); + cudaEventCreate(&z); + f(); // warm + std::vector t; + for (int k = 0; k < 5; ++k) { + cudaEventRecord(a); + f(); + cudaEventRecord(z); + cudaEventSynchronize(z); + float ms = 0; + cudaEventElapsedTime(&ms, a, z); + t.push_back(ms); + } + cudaEventDestroy(a); + cudaEventDestroy(z); + std::sort(t.begin(), t.end()); + return t[t.size() / 2]; +} + +// Inkling 2 Mini's expert products (n_embd 2304, n_ff_exp 1152, 128 experts) for each line of counts: the engine's +// default launches - a launch for each class of rows (up to 32, up to 128, more; the rows laid out class after class) +// over all the matrices, and over runs of 1 to 3 matrices as scattered cache slots make them - against one launch +// of mul_tiles(). +int bench(const char* file) { + std::ifstream in(file); + std::vector> calls; + for (std::string line; std::getline(in, line);) { + std::istringstream ss(line); + std::vector r; + for (int v; ss >> v;) r.push_back(v); + if (r.size() == 128) calls.push_back(r); + } + if (calls.empty()) { std::printf("bench: no lines of 128 counts in %s\n", file); return 2; } + const Product products[] = {{"IQ4_NL gate_up", 20, 2304, 2304}, {"IQ4_NL down", 20, 2304, 1152}, + {"Q8_0 gate_up", 8, 2304, 2304}, {"Q8_0 down", 8, 2304, 1152}, + {"IQ2_S gate_up", 22, 2304, 2304}, {"IQ2_XXS gate_up", 16, 2304, 2304}, + {"IQ1_S gate_up", 19, 2304, 2304}, {"Q2_0 down", 42, 2304, 1152}}; + std::mt19937 rng(11); + constexpr int n = 128, kLimits[] = {32, 128}; + for (const Product& p : products) { + if (!Mmq::tiles_fit(p.type, p.w_rows, p.w_cols, true)) continue; + size_t per = 0; + Buffers b; + Mmq mmq; + const std::vector w = random_matrices(p.type, p.w_rows, p.w_cols, n, &per, rng); + uint8_t* dw = b.add(upload(w)); + const int most_total = 1024 * 8; + std::vector x((size_t) most_total * p.w_cols); + for (auto& v : x) v = (float) ((rng() & 0xffff) / 32768.0 - 1.0); + float* dx = b.add(upload(x)); + std::vector iota(most_total); + std::iota(iota.begin(), iota.end(), 0); + int32_t* d_iota = b.add(upload(iota)); + std::vector at(n); + for (int e = 0; e < n; ++e) at[(size_t) e] = (int64_t) e * (int64_t) per; + int64_t* d_at = b.add(upload(at)); + void* xq = b.alloc(Mmq::q8_bytes(most_total, p.w_cols)); + float* dst = (float*) b.alloc((size_t) most_total * p.w_rows * sizeof(float)); + Mmq::Tile* d_tiles = (Mmq::Tile*) b.alloc((size_t) (n + most_total / 128 + 1) * sizeof(Mmq::Tile)); + int32_t* d_cb = (int32_t*) b.alloc(3 * (n + 1) * sizeof(int32_t)); + if (!dw || !dx || !d_iota || !d_at || !xq || !dst || !d_tiles || !d_cb) { std::printf("bench: no VRAM\n"); return 1; } + double sa = 0, sb = 0, sc = 0, ops = 0; + int la = 0, lb = 0; + for (const auto& rows : calls) { + int total = 0; + for (int r : rows) total += r; + if (total > most_total) continue; + const auto cls = [&](int r) { return r <= kLimits[0] ? 0 : r <= kLimits[1] ? 1 : 2; }; + // the engine's layout: class after class, an expert's rows together; per class its bounds + std::vector cb(3 * (n + 1)), first(n), mat(n); + int most[3] = {}; + for (int c = 0, a = 0; c < 3; ++c) { + for (int e = 0; e < n; ++e) { + cb[(size_t) c * (n + 1) + e] = a; + if (rows[(size_t) e] > 0 && cls(rows[(size_t) e]) == c) { + first[(size_t) e] = a; + a += rows[(size_t) e]; + most[c] = std::max(most[c], rows[(size_t) e]); + } + } + cb[(size_t) c * (n + 1) + n] = a; + } + std::iota(mat.begin(), mat.end(), 0); + std::vector tiles; + Mmq::plan_tiles(p.type, first.data(), rows.data(), mat.data(), n, tiles); + cudaMemcpy(d_tiles, tiles.data(), tiles.size() * sizeof(Mmq::Tile), cudaMemcpyHostToDevice); + cudaMemcpy(d_cb, cb.data(), cb.size() * sizeof(int32_t), cudaMemcpyHostToDevice); + Mmq::quantize(dx, nullptr, xq, p.type, p.w_cols, p.w_cols, total, nullptr); + // runs of 1 to 3 matrices + std::vector> runs; + for (int j = 0; j < n;) { + const int m = std::min(n - j, 1 + (int) (rng() % 3)); + runs.push_back({j, m}); + j += m; + } + int n_a = 0, n_b = 0; + const double ta = time_ms([&] { + n_a = 0; + for (int c = 0; c < 3; ++c) + if (most[c] > 0) { + mmq.mul(dw, p.type, p.w_rows, p.w_cols, per, n, xq, d_cb + (size_t) c * (n + 1), d_iota, total, + most[c], dst, p.w_rows, nullptr); + ++n_a; + } + }); + const double tb = time_ms([&] { + n_b = 0; + for (const auto& [j, m] : runs) { + int top[3] = {}; + for (int e = j; e < j + m; ++e) + if (rows[(size_t) e] > 0) top[cls(rows[(size_t) e])] = std::max(top[cls(rows[(size_t) e])], rows[(size_t) e]); + for (int c = 0; c < 3; ++c) + if (top[c] > 0) { + mmq.mul(dw + (size_t) j * per, p.type, p.w_rows, p.w_cols, per, m, xq, + d_cb + (size_t) c * (n + 1) + j, d_iota, total, top[c], dst, p.w_rows, nullptr); + ++n_b; + } + } + }); + const double tc = time_ms([&] { + mmq.mul_tiles(dw, d_at, p.type, p.w_rows, p.w_cols, xq, 0, total, d_tiles, tiles.data(), (int) tiles.size(), + d_iota, dst, p.w_rows, nullptr); + }); + sa += ta; sb += tb; sc += tc; la += n_a; lb += n_b; + ops += 2.0 * total * (double) p.w_rows * (double) p.w_cols; + } + if (!ok(cudaDeviceSynchronize(), "bench")) return 1; + const auto tops = [&](double ms) { return ops / (ms * 1e-3) / 1e12; }; + const double nc = (double) calls.size(); + std::printf("bench %-16s %zu calls: classes %.1f us (%.1f launches) %.1f TOPS | runs %.1f us (%.1f launches) " + "%.1f TOPS | tiles %.1f us (1 launch) %.1f TOPS\n", p.name, calls.size(), 1000 * sa / nc, la / nc, + tops(sa), 1000 * sb / nc, lb / nc, tops(sb), 1000 * sc / nc, tops(sc)); + } + return 0; +} + } // namespace -int main() { +int main(int argc, char** argv) { int devices = 0; if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) { std::printf("no card: skipped\n"); return 77; } + if (argc == 3 && std::strcmp(argv[1], "bench") == 0) return bench(argv[2]); std::mt19937 rng(7); struct Dist { const char* name; std::vector rows; }; std::vector dists; @@ -172,8 +468,9 @@ int main() { } } } - if (failures) { - std::printf("FAIL: %d of %d cases\n", failures, cases); + const int tile_failures = test_tiles(rng); + if (failures || tile_failures) { + std::printf("FAIL: %d of %d class cases, %d tile cases\n", failures, cases, tile_failures); return 1; } std::printf("PASS cases=%d\n", cases); diff --git a/tools/iq_fixture.py b/tools/iq_fixture.py index 8cfcf92198..58d9b6d1d8 100644 --- a/tools/iq_fixture.py +++ b/tools/iq_fixture.py @@ -58,6 +58,7 @@ "IQ3_XXS": (256, 98), "IQ3_S": (256, 110), "IQ1_M": (256, 56), + "IQ1_S": (256, 50), "IQ4_NL": (32, 18), "IQ4_XS": (256, 136), "Q3_K": (256, 110), @@ -83,7 +84,7 @@ def repair_scales(name: str, raw: np.ndarray) -> None: raw[:, 0:2] = np.frombuffer(HALF_ONE, dtype=np.uint8) # name -> (the KERNEL type id written into the .bin header, identical to the gguf-py enum id) KERNEL_IDS = {"IQ2_XXS": 16, "IQ2_XS": 17, "IQ2_S": 22, "IQ3_XXS": 18, "IQ3_S": 21, - "IQ1_M": 29, "IQ4_NL": 20, "IQ4_XS": 23, "Q2_0": 42, "Q3_K": 11} + "IQ1_M": 29, "IQ1_S": 19, "IQ4_NL": 20, "IQ4_XS": 23, "Q2_0": 42, "Q3_K": 11} def build(name: str, rows: int, cols: int, seed: int): diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index 308e0e51a8..50e7ad96da 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -221,6 +221,17 @@ "download_gb": 79.7, "ram_gb": 66, "arena_gb": 73.0}, "Q8_0": {"about": "8-bit throughout: the closest to the model as trained", "download_gb": 132.6, "ram_gb": 119, "arena_gb": 125.8}}}, + "inkling": {"title": "Inkling 2 Mini", + "about": "on the strata-poly engine: NVIDIA, Linux; an 18 GB file, ~22 GB of RAM beside an " + "8 GB card (16.5 GiB measured for the engine); a 2-bit and an 8-bit size too, images optional", + "tag": "inkling2-", "engine": "poly", "vision": True, "experimental": True, + "models": {"IQ4_NL": {"about": "4-bit experts in layers 0-19 (imatrix), 8-bit everywhere else", + "download_gb": 17.6, "ram_gb": 22, "arena_gb": 15.8}, + "UD-Q2_K_XL": {"about": "Unsloth's 2-bit experts, higher where it matters: the fastest and " + "the least RAM (9 GB measured), a little less accurate", + "download_gb": 9.1, "ram_gb": 14, "arena_gb": 8.4}, + "Q8_0": {"about": "8-bit throughout: the closest to the model as trained", + "download_gb": 27.8, "ram_gb": 32, "arena_gb": 26.0}}}, } FALLBACK_CONTEXTS = [8192, 32768, 65536, 131072, 204800, 262144, 393216, 524288] BENCH_PROMPT = ("Write a short story (about 300 words) about a lighthouse keeper who finds a message in a bottle. " @@ -1136,7 +1147,8 @@ def tool_defs(models: dict, families: dict, contexts: list) -> list: "Qwen3.6-35B-A3B, ornith = Ornith 1.5, gemma4 = Gemma 4 26B-A4B, tiel = " "Tiel Coder 35B-A3B (GLM's engine: one NVIDIA card, an 11-25 GB download, " "15-31 GB of RAM beside an 8 GB card by setup's estimate; images with " - "vision except LFM2.5 and Flint)"}, + "vision except LFM2.5 and Flint), inkling = Inkling 2 Mini (experimental: " + "NVIDIA, Linux, a 9, 18 or 28 GB download, images optional)"}, "model": {"type": "string", "enum": list(dict.fromkeys( [*models, *(m for f in families.values() for m in f.get("models", ()))])), "description": "the size (quantization): see strata_models"}, diff --git a/tools/strata_tokenizer.py b/tools/strata_tokenizer.py index 4417d7595d..161e2fd657 100644 --- a/tools/strata_tokenizer.py +++ b/tools/strata_tokenizer.py @@ -130,10 +130,33 @@ def bytes_to_unicode() -> dict[int, str]: r"|\s+" ) +# The `inkling2` pre-tokenizer (Inkling 2 Mini), llama.cpp's LLAMA_VOCAB_PRE_TYPE_GPT4O (llama.cpp 29b52d398b +# src/llama-vocab.cpp): o200k's split. A word is cut where its capitals end, as in Flint's, contractions stay on the +# word, digits go in runs of up to three, and punctuation keeps the line breaks and slashes after it. This is +# llama.cpp's own spelling of the pattern, not tokenizer.json's: `(?=[\p{L}\p{M}])[^a-z]` for "an upper-case letter" +# (its groups made non-capturing, for findall). +# llama.cpp runs it on text where every letter past ASCII is one placeholder, so such a letter is upper and lower case +# at once; Python's [^a-z] / [^A-Z] give it the same both ways, so a word like "helloПривет" stays one piece as it does +# there (tokenizer.json's \p{Lu}/\p{Ll} would cut it). ignore_merges, as Hugging Face's tokenizer.json for the model +# sets it (the reference): a piece that is a token as a whole is that token. llama.cpp 29b52d398b does not set it for +# this name, and gives "kwargs" (one token, which no chain of merges reaches) as three. +GPT4O_PATTERN = ( + r"[^\r\n\p{L}\p{N}]?(?:(?=[\p{L}\p{M}])[^a-z])*(?:(?=[\p{L}\p{M}])[^A-Z])+" + r"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?" + r"|[^\r\n\p{L}\p{N}]?(?:(?=[\p{L}\p{M}])[^a-z])+(?:(?=[\p{L}\p{M}])[^A-Z])*" + r"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?" + r"|\p{N}{1,3}" + r"| ?[^\s\p{L}\p{N}]+[\r\n/]*" + r"|\s*[\r\n]+" + r"|\s+(?!\S)" + r"|\s+" +) + PRE_PATTERNS = {"glm4": GLM4_PATTERN, "glm5": GLM4_PATTERN, # every other name: QWEN35_PATTERN, as before - "gemma4": GEMMA4_PATTERN, "lfm2": GLM4_PATTERN, "kolibri1": QWEN2_PATTERN} + "gemma4": GEMMA4_PATTERN, "lfm2": GLM4_PATTERN, "kolibri1": QWEN2_PATTERN, + "inkling2": GPT4O_PATTERN} PRE_SEQUENCES = {"joyai-llm": DEEPSEEK3_SEQUENCE, "deepseek-v3": DEEPSEEK3_SEQUENCE, "flint": FLINT_SEQUENCE} -IGNORE_MERGES = ("glm4", "glm5", "lfm2") +IGNORE_MERGES = ("glm4", "glm5", "lfm2", "inkling2") RAW = ("gemma4",) # vocabularies of UTF-8 pieces MODELS = {"gpt2": None, "gemma4": "gemma4"} # tokenizer.ggml.model -> the pre-tokenizer it implies, if any @@ -595,6 +618,8 @@ def extract(gguf_path, out_dir) -> dict: "pre_pattern": tk.pre_pattern, "pre_sequence": list(tk.pre_sequence) if tk.pre_sequence else None, "pre_pattern_source": "llama.cpp src/llama-vocab.cpp (LLAMA_VOCAB_PRE_TYPE_GEMMA4)" if tk.raw + else "llama.cpp 29b52d398b src/llama-vocab.cpp (LLAMA_VOCAB_PRE_TYPE_GPT4O), with " + "tokenizer.json's ignore_merges" if tk.pre_pattern == GPT4O_PATTERN else "llama.cpp src/llama-vocab.cpp (LLAMA_VOCAB_PRE_TYPE_DEEPSEEK3_LLM)" if tk.pre_sequence else "llama.cpp src/llama-vocab.cpp (LLAMA_VOCAB_PRE_TYPE_CHATGLM4)" if tk.ignore_merges diff --git a/tools/test_setup_glm.py b/tools/test_setup_glm.py index 1698094882..0f8fd8db3c 100644 --- a/tools/test_setup_glm.py +++ b/tools/test_setup_glm.py @@ -282,7 +282,8 @@ def fake_build(gpu, yes, llama, vision="none", toolkit=13, portable=False): mock.patch.object(setup, "page_file_gb", lambda: 16.0), mock.patch.object(setup, "free_gb", lambda p: 500.0), mock.patch.object(setup, "pip_install", lambda *a, **k: None), - mock.patch.object(setup, "get_llama_cpp", lambda: self.t / "llama.cpp"), + mock.patch.object(setup, "get_llama_cpp", # a family's own encoder's checkout: its own folder + lambda commit=None: self.t / (f"llama.cpp-{commit[:7]}" if commit else "llama.cpp")), mock.patch.object(setup, "get_prebuilt", mock.Mock(side_effect=AssertionError("the Qwen engine"))), mock.patch.object(setup, "build_engine_poly", fake_build), mock.patch.object(setup, "download", fake_download), diff --git a/tools/test_setup_inkling.py b/tools/test_setup_inkling.py new file mode 100644 index 0000000000..f597989f1d --- /dev/null +++ b/tools/test_setup_inkling.py @@ -0,0 +1,425 @@ +"""Tests for setup.py's Inkling 2 Mini (docs/models/inkling.md): its pinned files, the estimates for an 8 GB card, the +install by GLM's steps with no draft model unless its DSpark drafter is asked for (offered only where the card holds +every expert), the model's sampling defaults in the run config, NVIDIA only, and its image encoder: opt-in, built from +its own llama.cpp pin into a folder of its own (the other families' encoder and its stamp are left alone). Mocked +like tools/test_setup_glm.py, whose harness this uses. + + python -m unittest tools.test_setup_inkling +""" +from __future__ import annotations + +import json +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import setup # noqa: E402 +from tools import test_setup_glm as glm_tests # noqa: E402 + +FAM = setup.FAMILIES["inkling"] +# setup's order: the size taken with the RAM for it, then Unsloth's 2-bit file (the least RAM), then 8-bit +SIZES = [("IQ4_NL", 17627940768), ("UD-Q2_K_XL", 9138715328), ("Q8_0", 27820099264)] +MMPROJ = "mmproj-Inkling-2-Mini-Q8_0.gguf" +DSPARK = "dspark-Inkling-2-Mini-Q8_0.gguf" + + +class Pins(unittest.TestCase): + def test_the_files(self): + self.assertEqual(list(setup.family_models("inkling")), [m for m, _ in SIZES]) + self.assertEqual(FAM["hf"], "https://huggingface.co/ggml-org/Inkling-2-Mini-GGUF/resolve/" + "db61c5b492a6a034d986328d28274af0a439aa6c/") + self.assertEqual(list(FAM["sha256"]), [f"Inkling-2-Mini-{m}.gguf" for m, _ in SIZES] + [MMPROJ, DSPARK]) + # the DSpark drafter: Unsloth's Q8_0 file at setup's pinned revision (its LFS sha256) + self.assertEqual(FAM["dspark"]["hf"], "https://huggingface.co/unsloth/Inkling-2-Mini-GGUF/resolve/" + "ae9327c5fbc7333116ba32eee78bb5d2bbefae4f/") + self.assertEqual(FAM["dspark"]["file"], DSPARK) + self.assertEqual(FAM["sha256"][DSPARK], + (402278560, "2ec78510da837e8fc3be54a14757a0c5fbd2d8d9e85a0d92853fafdf674f3773")) + for size, n in SIZES: + file = f"Inkling-2-Mini-{size}.gguf" + d = FAM["models"][size] + self.assertEqual((setup.model_file(FAM, size, 1), setup.model_shards(FAM, size)), (file, 1)) + self.assertEqual(FAM["sha256"][file][0], n) + self.assertRegex(FAM["sha256"][file][1], r"^[0-9a-f]{64}$") + self.assertAlmostEqual(n / 1e9, d["download_gb"], delta=0.05) + self.assertLess(d["arena_gb"], d["download_gb"]) + self.assertEqual(d["ram_gb"], round(setup.poly_ram_need(d, 8.0)), size) + if size == "UD-Q2_K_XL": # Unsloth's repository, in the architecture's native form (inkling2) + self.assertEqual(d["hf"], "https://huggingface.co/unsloth/Inkling-2-Mini-GGUF/resolve/" + "ae9327c5fbc7333116ba32eee78bb5d2bbefae4f/") + self.assertEqual(d["mmproj_hf"], FAM["mmproj_hf"]) # ggml-org's image encoder for it too + else: + self.assertNotIn("hf", d) + self.assertNotIn("mmproj_hf", d) + self.assertEqual(setup.POLY_GGUF_ARCHS["inkling"], ("inkling2_loop", "inkling2")) + self.assertFalse(setup.poly_batch(FAM, FAM["models"]["IQ4_NL"], 31.8, 32768)) # the engine's prompt batch + + def test_the_about_line_and_what_is_not_claimed(self): + n = setup.poly_ram_need(FAM["models"]["IQ4_NL"], 8.0) + self.assertIn(f"~{n:.0f} GB of RAM beside an 8 GB card (16.5 GiB measured for the engine)", FAM["about"]) + self.assertIs(FAM["experimental"], True) + self.assertNotIn("unmeasured", FAM) # measured on an RTX 2070 Super 8 GB (the comment above FAMILIES) + self.assertIs(FAM["windows"], False) + self.assertIs(FAM["vision"], True) + self.assertIn("images optional", FAM["about"]) + self.assertEqual(FAM["ran_on_gb"], 8) # run on an RTX 2070 Super 8 GB + + def test_the_image_encoder(self): + self.assertEqual(FAM["mmproj"], MMPROJ) + self.assertEqual(FAM["mmproj_hf"], FAM["hf"]) # the same pinned revision of ggml-org's + self.assertEqual(FAM["sha256"][MMPROJ], + (345910944, "233287272ec5ac39b4168677aba54a4c024f202410f5629fac1830e1059f8abb")) + self.assertAlmostEqual(FAM["sha256"][MMPROJ][0] / 1e9, FAM["vision_gb"], delta=0.01) + # its own llama.cpp (mtmd's inkling2v): a full commit, not the other families' encoder's or the engines' + self.assertRegex(FAM["vision_llama"], r"^[0-9a-f]{40}$") + self.assertEqual(FAM["vision_llama"], setup.INKLING_VISION_LLAMA_CPP_COMMIT) + self.assertNotIn(FAM["vision_llama"], (setup.VISION_LLAMA_CPP_COMMIT, setup.LLAMA_CPP_COMMIT)) + self.assertEqual([f for f in setup.FAMILIES if setup.FAMILIES[f].get("vision_llama")], ["inkling"]) + + def test_which_llama_cpp_checkout(self): + with tempfile.TemporaryDirectory() as t: + root = Path(t) + for name in ("llama.cpp", f"llama.cpp-{setup.VISION_LLAMA_CPP_COMMIT[:7]}", + f"llama.cpp-{FAM['vision_llama'][:7]}"): + (root / "third_party" / name / "ggml").mkdir(parents=True) + (root / "third_party" / name / "ggml" / "CMakeLists.txt").write_text("") + (root / "third_party" / name / "gguf-py").mkdir() + with mock.patch.object(setup, "ROOT", root), \ + mock.patch.object(setup, "download", mock.Mock(side_effect=AssertionError("downloaded"))): + self.assertEqual(setup.get_llama_cpp().name, "llama.cpp") + self.assertEqual(setup.get_llama_cpp(vision=True).name, # the others' encoder: as before + f"llama.cpp-{setup.VISION_LLAMA_CPP_COMMIT[:7]}") + self.assertEqual(setup.get_llama_cpp(commit=FAM["vision_llama"]).name, "llama.cpp-29b52d3") + self.assertEqual(setup.get_llama_cpp(commit=setup.LLAMA_CPP_COMMIT).name, "llama.cpp") + urls = [] + with mock.patch.object(setup, "ROOT", root / "empty"), \ + mock.patch.object(setup, "download", mock.Mock(side_effect=lambda url, *a: urls.append(url) or + (_ for _ in ()).throw(OSError()))): + with self.assertRaises(OSError): + setup.get_llama_cpp(commit=FAM["vision_llama"]) + self.assertEqual(urls, [f"https://github.com/ggml-org/llama.cpp/archive/{FAM['vision_llama']}.zip"]) + + def test_nvidia_only(self): + self.assertIn("inkling", setup.menu_families(False)) + self.assertNotIn("inkling", setup.menu_families(True)) + self.assertIn("inkling", setup.POLY_KV["q8_0"]) # fp16 or q8_0 caches + sys.path.insert(0, str(ROOT / "metal")) + import setup_mac + self.assertNotIn("inkling", setup_mac.MAC_POLY_FAMILIES) + + +class Main(unittest.TestCase): + setUp, tearDown = glm_tests.Main.setUp, glm_tests.Main.tearDown + + def main(self, *args, **kw): + """glm's harness (its get_llama_cpp gives a commit its own folder), with the own encoder's compile mocked: + what it was given in self.vbuilt.""" + self.vbuilt = [] + self.nvcc = self.t / "cuda" / "bin" / "nvcc" # the toolkit's bin and lib64: the encoder's cuda_dirs + + def fake_cmake(src, bdir, target, defs, vcvars, bat): + self.vbuilt.append((src, bdir, target, defs)) + (bdir / "bin").mkdir(parents=True, exist_ok=True) + (bdir / "bin" / setup.VEXE).write_text("") + + with mock.patch.object(setup, "cmake_build", fake_cmake), \ + mock.patch.object(setup, "install_build_tools", lambda gpu, yes: (str(self.nvcc), None)): + (self.t / "cuda" / "bin").mkdir(parents=True, exist_ok=True) + (self.t / "cuda" / "lib64").mkdir(exist_ok=True) + return glm_tests.Main.main(self, *args, **kw) + + def test_install_each_size(self): + for size, _n in SIZES: + with self.subTest(size): + self.downloads, self.runs, self.verified = [], [], [] + code, out, _ = self.main(family="inkling", model=size, ram=64.0, vram=8188 / 1024) + self.assertEqual(code, 0, out) + cfg = json.loads((self.t / f"strata-inkling2-{size.lower()}.json").read_text()) + file = f"Inkling-2-Mini-{size}.gguf" + self.assertEqual(self.downloads, [FAM["models"][size].get("hf", FAM["hf"]) + file]) + self.assertEqual(self.verified, [(file, *FAM["sha256"][file])]) + tag = "inkling2-" + size + pack = self.t / "data" / "packs" / tag.lower() + self.assertEqual([Path(r[1]).name for r in self.runs], ["strata_tokenizer.py"]) + args = cfg["args"] + self.assertEqual(Path(args[args.index("--model") + 1]), self.t / "models" / tag / file) + self.assertEqual(Path(args[args.index("--expert-profile") + 1]), pack / "expert-profile.txt") + for flag in ("--draft-model", "--tail-skip", "--prompt-batch", "--kv"): + self.assertNotIn(flag, args) + self.assertEqual(cfg["model_name"], f"inkling-2-mini-{size.lower()}") + self.assertEqual(cfg["display_name"], f"Inkling 2 Mini {size}") + self.assertNotIn("vision", cfg) + self.assertNotIn("tool_call_recovery", cfg) + self.assertEqual(cfg["sampling"], {"temperature": 1.0, "top_k": 50, "top_p": 1.0}) + self.assertNotIn("EXPERIMENTAL and new", out) # measured: no "not measured yet" warning + + def test_a_sampling_block_of_the_users_is_kept(self): + code, out, cfg = self.main(family="inkling", ram=64.0, vram=31.84) + self.assertEqual(code, 0, out) + path = self.t / "strata-inkling2-iq4_nl.json" + path.write_text(json.dumps({**cfg, "sampling": {"temperature": 0.6}})) + code, out, cfg = self.main(family="inkling", ram=64.0, vram=31.84) + self.assertEqual(code, 0, out) + self.assertEqual(json.loads(path.read_text())["sampling"], {"temperature": 0.6}) + + def test_the_size_taken_without_a_name(self): + for ram in (64.0, 20.0): # IQ4_NL wants the least RAM too + with self.subTest(ram=ram): + code, out, _ = self.main(family="inkling", ram=ram, vram=8.0) + self.assertEqual(code, 0, out) + self.assertTrue((self.t / "strata-inkling2-iq4_nl.json").is_file(), out) + + def test_windows_is_asked(self): + code, out, _ = self.main(win=True, family="inkling", ram=64.0, vram=31.84) + self.assertEqual(code, 0, out) # --yes takes the risk + self.assertIn("Inkling 2 Mini ran on Windows for one user on an earlier build", out) + self.assertNotIn("has been run on Linux only", out) + + def test_cards(self): + # a layer split as for the other families (the engine keeps the loop's layers on one card) + code, out, cfg = self.main(["--gpus", "0,1"], family="inkling", ram=64.0, n_gpus=2) + self.assertEqual(code, 0, out) + self.assertEqual((cfg["gpu"], cfg["layer_split"]), ([0, 1], "auto")) + code, out, cfg = self.main(["--gpus", "0,1", "--layer-split", "18"], family="inkling", ram=64.0, n_gpus=2) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["layer_split"], "18") + code, out, cfg = self.main(["--gpu", "1"], family="inkling", ram=64.0, n_gpus=2) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["gpu"], 1) + code, out, cfg = self.main(["--kv", "q8_0"], family="inkling", ram=64.0) + self.assertEqual(code, 0, out) + self.assertIn("--kv", cfg["args"]) + self.assertEqual(cfg["args"][cfg["args"].index("--kv") + 1], "q8_0") + + def test_requests_at_once(self): + # "parallel" as for the other families of strata-poly: written when asked, suggested where it pays + self.assertNotIn("one_request", FAM) + code, out, cfg = self.main(["--parallel", "3"], family="inkling", ram=64.0) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["parallel"], 3) + self.assertIn("parallel requests: 3 at once", out) + code, out, cfg = self.main(family="inkling", ram=64.0, vram=8188 / 1024) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["parallel"], 3) # the earlier config's, carried over + self.assertIn("Several requests at once (opt-in, --parallel N)", out) # an 8 GB card: most experts on the CPU + code, out, cfg = self.main(["--parallel", "1"], family="inkling", ram=64.0) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["parallel"], 1) + code, out, cfg = self.main(family="inkling", ram=64.0) + self.assertEqual(code, 0, out) + self.assertEqual(cfg["parallel"], 1) # an earlier "parallel": 1 is kept too + + def test_the_drafter_is_opt_in_and_offered_where_it_can_pay(self): + d, q2 = FAM["models"]["IQ4_NL"], FAM["models"]["UD-Q2_K_XL"] + self.assertFalse(setup.poly_dspark_offer(FAM, d, 8188 / 1024)) # an 8 GB card: most experts on the CPU + self.assertFalse(setup.poly_dspark_offer(FAM, q2, 8188 / 1024)) + self.assertTrue(setup.poly_dspark_offer(FAM, d, 24.0)) # an RTX 3090: every expert in VRAM + self.assertTrue(setup.poly_dspark_offer(FAM, d, 31.84)) + self.assertFalse(setup.poly_dspark_offer(FAM, d, 16.0)) # 16 GB: IQ4_NL's do not all fit + self.assertTrue(setup.poly_dspark_offer(FAM, q2, 16.0)) # UD-Q2_K_XL's do + # where every expert fits only without the drafter's VRAM, it is not offered + edge = setup.poly_beside_gb(d) + d["arena_gb"] / 1.073741824 + 0.1 + self.assertEqual(setup.poly_held_gb(d, edge), d["arena_gb"]) + self.assertFalse(setup.poly_dspark_offer(FAM, d, edge)) + self.assertAlmostEqual(setup.poly_dspark_gb(FAM["dspark"]), 0.4 + 0.125) # at 32K: its rows' 128 MiB + for vram, asked in ((8188 / 1024, False), (31.84, True)): + with self.subTest(vram=vram): + self.downloads = [] + code, out, cfg = self.main(family="inkling", ram=64.0, vram=vram, answers={}) # Enter: no + self.assertEqual(code, 0, out) + self.assertEqual(any("DSpark drafter?" in q for q in self.asked), asked, self.asked) + self.assertNotIn("--draft-model", cfg["args"]) + self.assertNotIn(DSPARK, " ".join(self.downloads)) + self.assertIn("64K tokens (1.1 GB more VRAM", out) # the model's rows alone + + def test_the_drafter_when_asked(self): + for vram in (31.84, 8188 / 1024): # where it is not offered, it is still set up, with a warning + with self.subTest(vram=vram): + self.downloads, self.verified = [], [] + code, out, cfg = self.main(["--dspark", "yes"], family="inkling", ram=64.0, vram=vram) + self.assertEqual(code, 0, out) + args = cfg["args"] + self.assertEqual(Path(args[args.index("--draft-model") + 1]), + self.t / "models" / "inkling2-IQ4_NL" / DSPARK) + if vram > 9: # the second run finds the file there + self.assertIn(FAM["dspark"]["hf"] + DSPARK, self.downloads) + self.assertIn((DSPARK, *FAM["sha256"][DSPARK]), self.verified) + self.assertEqual(cfg["parallel"], 1) + self.assertEqual("expect it to be no faster or slower" in out, vram < 9, out) + self.assertIn("64K tokens (1.2 GB more VRAM", out) # and the drafter's, 4 KiB a token + code, out, _ = self.main(["--dspark", "yes", "--parallel", "3"], family="inkling", ram=64.0, vram=31.84) + self.assertNotEqual(code, 0) + self.assertIn("--dspark yes does not go with --parallel", out) + + def test_no_images_unless_asked(self): + code, out, cfg = self.main(family="inkling", ram=64.0, vram=8188 / 1024) # --yes: the default, no + self.assertEqual(code, 0, out) + self.assertNotIn("vision", cfg) + self.assertEqual((self.encoder, self.vbuilt), ("none", [])) + self.assertFalse((self.t / setup.ENGINE_POLY_DIR / "vision-inkling").exists()) + self.assertNotIn(MMPROJ, " ".join(self.downloads)) + self.downloads = [] + code, out, cfg = self.main(family="inkling", ram=64.0, vram=8188 / 1024, answers={}) # Enter: no + self.assertEqual(code, 0, out) + self.assertTrue(any("Do you want images?" in q for q in self.asked), self.asked) + self.assertNotIn("vision", cfg) + self.assertEqual(self.vbuilt, []) + + def test_images_on_the_cpu_of_an_8_gb_card(self): + code, out, cfg = self.main(["--vision", "yes"], family="inkling", ram=64.0, vram=8188 / 1024) + self.assertEqual(code, 0, out) + self.assertNotIn("not used with Inkling 2 Mini", out) + own = self.t / setup.ENGINE_POLY_DIR / "vision-inkling" + models = self.t / "models" / "inkling2-IQ4_NL" + self.assertEqual(cfg["vision"], {"exe": str(own / setup.VEXE), "mmproj": str(models / MMPROJ), + "model": str(models / "Inkling-2-Mini-IQ4_NL.gguf"), "gpu": False, + "max_tokens": setup.VISION["cpu"]["max_tokens"], + "threads": cfg["vision"]["threads"]}) + self.assertIn(FAM["mmproj_hf"] + MMPROJ, self.downloads) + self.assertIn((MMPROJ, *FAM["sha256"][MMPROJ]), self.verified) + # the shared engine is built without an encoder; its folder gets no strata-vision and its stamp no change + self.assertEqual(self.encoder, "none") + self.assertFalse((self.t / setup.ENGINE_POLY_DIR / setup.VEXE).exists()) + self.assertNotIn("vision", json.loads((self.t / setup.ENGINE_POLY_DIR / "BUILD.json").read_text())) + [(src, bdir, target, defs)] = self.vbuilt + self.assertEqual((src, bdir.name, target), + (self.t / "tools" / "vision", "build-vision-inkling", "strata-vision")) + self.assertIn(f"-DLLAMA_DIR={self.t / 'llama.cpp-29b52d3'}", defs) + self.assertIn("-DSTRATA_VISION_CUDA=OFF", defs) + stamp = json.loads((own / "BUILD.json").read_text()) + with mock.patch.object(setup, "ROOT", self.t): + vsrc = setup.source_hash(setup.VISION_SOURCES) + self.assertEqual((stamp["llama"], stamp["vision"], stamp["vision_src"]), (FAM["vision_llama"], "cpu", vsrc)) + self.assertEqual(stamp["cuda_dirs"], []) # no CUDA in a CPU one + # again: nothing to compile + code, out, cfg = self.main(["--vision", "cpu"], family="inkling", ram=64.0, vram=8188 / 1024) + self.assertEqual((code, self.vbuilt), (0, []), out) + self.assertIn("image encoder already built", out) + + def test_images_on_the_gpu(self): + code, out, cfg = self.main(["--vision", "gpu"], family="inkling", ram=64.0, vram=8188 / 1024) + self.assertEqual(code, 0, out) + self.assertIs(cfg["vision"]["gpu"], True) + self.assertEqual(cfg["vision"]["max_tokens"], setup.VISION["gpu"]["max_tokens"]) + [(_src, _bdir, _target, defs)] = self.vbuilt + self.assertIn("-DSTRATA_VISION_CUDA=ON", defs) + self.assertIn("-DCMAKE_CUDA_ARCHITECTURES=120", defs) + self.assertIn(f"-DCMAKE_CUDA_COMPILER={self.nvcc}", defs) + # the toolkit's libraries: in the encoder's stamp and the config's lib_dirs, as the shared build's are + dirs = [str(self.t / "cuda" / "bin"), str(self.t / "cuda" / "lib64")] + stamp = json.loads((self.t / setup.ENGINE_POLY_DIR / "vision-inkling" / "BUILD.json").read_text()) + self.assertEqual(stamp["cuda_dirs"], dirs) + self.assertEqual([d for d in cfg["lib_dirs"] if d in dirs], dirs) + # a CPU encoder asked of one built with CUDA: kept + code, out, cfg = self.main(["--vision", "cpu"], family="inkling", ram=64.0, vram=8188 / 1024) + self.assertEqual((code, self.vbuilt, cfg["vision"]["gpu"]), (0, [], False), out) + + def test_the_unsloth_size_takes_ggml_orgs_encoder(self): + code, out, cfg = self.main(["--vision", "cpu"], family="inkling", model="UD-Q2_K_XL", ram=64.0, + vram=8188 / 1024) + self.assertEqual(code, 0, out) + self.assertIn(FAM["mmproj_hf"] + MMPROJ, self.downloads) + self.assertEqual(Path(cfg["vision"]["mmproj"]).name, MMPROJ) + + +class Update(unittest.TestCase): + """update_poly_engine before a start: the engine first, then the own encoder (update_vision_own), compiled again + when its stamp is stale; the shared one is not asked for, and another family's encoder is updated as before.""" + + @staticmethod + def hashes(root): + with mock.patch.object(setup, "ROOT", root): + return setup.source_hash(setup.ENGINE_SOURCES), setup.source_hash(setup.VISION_SOURCES) + + def run_update(self, root, vis_exe, own_stamp=None, engine_src=None, fails=None): + """update_poly_engine on an install in root: (the shared build's mock, the own encoder's compiles, the + output). `fails`: what install_build_tools raises (the encoder's compile).""" + eng = root / setup.ENGINE_POLY_DIR + (eng / "vision-inkling").mkdir(parents=True, exist_ok=True) + (eng / setup.POLY_EXE).write_text("") + (eng / "BUILD.json").write_text(json.dumps({"src": engine_src or self.hashes(root)[0], "archs": [75], + "toolkit": 12, "vision": "cpu", "vision_src": "old"})) + if own_stamp is not None: + (eng / "vision-inkling" / setup.VEXE).write_text("") + (eng / "vision-inkling" / "BUILD.json").write_text(json.dumps(own_stamp)) + cfg = {"exe": str(eng / setup.POLY_EXE), "args": [], "gpu": 0, "cuda": 12, "lib_dirs": ["/cuda12/lib64"], + "vision": {"exe": str(vis_exe), "gpu": False}} + compiles = [] + + def fake_cmake(src, bdir, target, defs, vcvars, bat): + compiles.append(defs) + (bdir / "bin").mkdir(parents=True, exist_ok=True) + (bdir / "bin" / setup.VEXE).write_text("") + + def tools(gpu, yes): + if fails is not None: + raise fails + return str(root / "cuda12" / "bin" / "nvcc"), None + + engine = mock.Mock(return_value=eng) + with mock.patch.object(setup, "ROOT", root), \ + mock.patch.object(setup, "get_llama_cpp", lambda *a, **k: root / "llama.cpp"), \ + mock.patch.object(setup, "gpu_info", lambda i=None: {"arch": "75"}), \ + mock.patch.object(setup, "build_engine_poly", engine), \ + mock.patch.object(setup, "cmake_build", fake_cmake), \ + mock.patch.object(setup, "install_build_tools", tools), \ + mock.patch.object(setup, "engine_lib_dirs", lambda e: ["/cuda12/lib64"]): + out = glm_tests.quiet(setup.update_poly_engine, cfg) + self.cfg = cfg + return engine, compiles, out + + def test_the_own_encoder(self): + with tempfile.TemporaryDirectory() as t: + root = Path(t) + exe = root / setup.ENGINE_POLY_DIR / "vision-inkling" / setup.VEXE + engine, compiles, _ = self.run_update(root, exe) # no stamp: compiled, for the CPU + engine.assert_not_called() # the shared one's stale vision_src: not ours + self.assertEqual(len(compiles), 1) + self.assertIn("-DSTRATA_VISION_CUDA=OFF", compiles[0]) + self.assertIn(f"-DLLAMA_DIR={root / 'llama.cpp'}", compiles[0]) + fresh = {"llama": FAM["vision_llama"], "vision": "cpu", "toolkit": 12, + "vision_src": self.hashes(root)[1]} + engine, compiles, _ = self.run_update(root, exe, fresh) + self.assertEqual((engine.call_count, compiles), (0, [])) + # another toolkit: a CPU one is kept (as the shared check), a CUDA one is not + with mock.patch.object(setup, "ROOT", root): + self.assertTrue(setup.vision_own_ok("inkling", [75], "cpu", 13)) + gpu = {**fresh, "vision": "gpu", "archs": [75]} + (exe.parent / "BUILD.json").write_text(json.dumps(gpu)) + self.assertTrue(setup.vision_own_ok("inkling", [75], "gpu", 12)) + self.assertFalse(setup.vision_own_ok("inkling", [75], "gpu", 13)) + self.assertFalse(setup.vision_own_ok("inkling", [86], "gpu", 12)) # another card + # a CUDA one compiled again: on the GPU, and its toolkit's libraries reach the config's lib_dirs + (root / "cuda12" / "bin").mkdir(parents=True) + engine, compiles, _ = self.run_update(root, exe, {**gpu, "vision_src": "old"}) + self.assertEqual(len(compiles), 1) + self.assertIn("-DSTRATA_VISION_CUDA=ON", compiles[0]) + self.assertEqual(self.cfg["lib_dirs"], ["/cuda12/lib64", str(root / "cuda12" / "bin")]) + engine, compiles, _ = self.run_update(root, exe, {**fresh, "llama": setup.VISION_LLAMA_CPP_COMMIT}) + self.assertEqual(len(compiles), 1) + + def test_a_failed_encoder_build_leaves_the_engine_update(self): + with tempfile.TemporaryDirectory() as t: + root = Path(t) + exe = root / setup.ENGINE_POLY_DIR / "vision-inkling" / setup.VEXE + for e in (SystemExit(1), OSError("no compiler")): + engine, compiles, out = self.run_update(root, exe, engine_src="old", fails=e) + engine.assert_called_once() # the engine is still updated + self.assertEqual(engine.call_args[0][3], "none") # without the shared encoder + self.assertIn("could not update the image encoder", out[1]) + self.assertNotIn("could not update strata-poly", out[1]) + + def test_another_familys_encoder_as_before(self): + with tempfile.TemporaryDirectory() as t: + root = Path(t) + engine, compiles, _ = self.run_update(root, root / setup.ENGINE_POLY_DIR / setup.VEXE) + self.assertEqual(compiles, []) + self.assertEqual(engine.call_args[0][3], "cpu") # the shared encoder, stale: rebuilt + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_setup_mac.py b/tools/test_setup_mac.py index ad7e240d83..b13e71a34c 100644 --- a/tools/test_setup_mac.py +++ b/tools/test_setup_mac.py @@ -280,7 +280,8 @@ def test_the_source_flag_reaches_strata_source(self): class SmallerModelCatalog(unittest.TestCase): def test_uses_shared_family_sizes_and_filenames(self): catalog = M.smaller_model_catalog() - self.assertEqual(set(catalog), {f for f,d in setup.FAMILIES.items() if d.get("engine")=="poly"}) + self.assertEqual(set(catalog), {f for f,d in setup.FAMILIES.items() if d.get("engine")=="poly" + and not d.get("cuda_only")}) # Inkling 2 Mini: NVIDIA only for family, entry in catalog.items(): self.assertTrue(entry["metal_ready"]) self.assertFalse(entry["model_validated"]) diff --git a/tools/test_setup_menu.py b/tools/test_setup_menu.py index 0817a7ff29..d5622a505d 100644 --- a/tools/test_setup_menu.py +++ b/tools/test_setup_menu.py @@ -22,7 +22,7 @@ def test_the_menu_order_on_nvidia(self): fams = setup.menu_families(False) + list(setup.OWN_PATH_FAMILIES) self.assertEqual(fams, ["qwen", "swift", "coder", "unsloth", "nvfp4", "glm", "deepseek", "lfm25", "flint", "kolibri", "qwen36", "clover", "ornith", "gemma4", "tiel", "minicpmv", "ornith122", - "qwen36-strata"]) + "inkling", "qwen36-strata"]) def test_the_default_stays_the_first_family(self): self.assertEqual(setup.menu_families(False)[0], "qwen") @@ -31,6 +31,7 @@ def test_the_default_stays_the_first_family(self): def test_nvfp4_is_not_listed_on_amd_and_intel(self): fams = setup.menu_families(True) self.assertNotIn("nvfp4", fams) + self.assertNotIn("inkling", fams) # NVIDIA only too ("cuda_only") self.assertEqual(fams, ["qwen", "swift", "coder", "unsloth", "glm", "deepseek", "lfm25", "flint", "kolibri", "qwen36", "clover", "ornith", "gemma4", "tiel", "minicpmv", "ornith122"]) self.assertIn("nvfp4", setup.FAMILIES) # --family nvfp4 still exists, and says why not diff --git a/tools/test_window_agree.py b/tools/test_window_agree.py new file mode 100644 index 0000000000..364999d578 --- /dev/null +++ b/tools/test_window_agree.py @@ -0,0 +1,73 @@ +"""Tests for tools/window_agree.py against a stand-in engine (a script that prints what strata-poly prints): the +verdict on tokens, top probabilities and guesses. No model, no GPU. + + python -m unittest tools.test_window_agree +""" +from __future__ import annotations + +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +TOOL = Path(__file__).resolve().parent / "window_agree.py" + +# The stand-in: tokens on stdout, a top line a step and the summary on stderr. FAKE_DIFFER=tokens|top makes the +# window run part from --window 1; FAKE_GUESSES the guesses it reports. +ENGINE = r''' +import os, sys +a = sys.argv +w = int(a[a.index("--window") + 1]) +toks = [5, 6, 7, 8] +tops = ["top 5:0.9 6:0.1", "top 6:0.8 7:0.2", "top 7:0.7 8:0.3", "top 8:0.6 9:0.4"] +d = os.environ.get("FAKE_DIFFER", "") +if w > 1 and d == "tokens": + toks[2] = 9 +if w > 1 and d == "top": + tops[1] = "top 6:0.8 7:0.19" +print(",".join(map(str, toks))) +for t in tops: + print(t, file=sys.stderr) +g = os.environ.get("FAKE_GUESSES", "3") if w > 1 else "0" +print(f"prompt 9 tokens 1.0 tok/s, generated 4 tokens 1.0 tok/s (length); 1 of {g} guessed tokens right", + file=sys.stderr) +''' + + +class Verdict(unittest.TestCase): + def run_tool(self, **env): + with tempfile.TemporaryDirectory() as d: + engine = Path(d) / "engine.py" + engine.write_text(ENGINE) + wrapper = Path(d) / "strata-poly" + wrapper.write_text(f"#!/bin/sh\nexec {sys.executable} {engine} \"$@\"\n") + wrapper.chmod(0o755) + p = subprocess.run([sys.executable, str(TOOL), "--model", "m.gguf", "--bin", str(wrapper)], + capture_output=True, text=True, env={**os.environ, **env}) + return p.returncode, p.stdout + + def test_the_same_answer_passes(self): + rc, out = self.run_tool() + self.assertEqual(rc, 0, out) + self.assertIn("tokens: the same 4", out) + + def test_a_different_token_fails(self): + rc, out = self.run_tool(FAKE_DIFFER="tokens") + self.assertEqual(rc, 1) + self.assertIn("first differ at step 2", out) + + def test_a_different_probability_fails(self): + rc, out = self.run_tool(FAKE_DIFFER="top") + self.assertEqual(rc, 1) + self.assertIn("top 5: first differ at step 1", out) + + def test_no_guesses_checks_nothing(self): + rc, out = self.run_tool(FAKE_GUESSES="0") + self.assertEqual(rc, 1) + self.assertIn("no guess was offered", out) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/window_agree.py b/tools/window_agree.py new file mode 100644 index 0000000000..9546515a9c --- /dev/null +++ b/tools/window_agree.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Whether guessed windows change an answer: --window N against --window 1, token for token. + + python tools/window_agree.py --model M.gguf [--window 4] [--tokens-file P.ids] [-- extra engine options] + +Both runs write --max-new tokens greedily from the same prompt (no prompt or conversation cache, no EOS stop, +no draft block, so a window's guesses come from the conversation's repeats, --lookup 3) with --top-probs, and +every expert on the CPU (--no-gpu-experts): the card's expert cache holds different experts when a window's rows +take VRAM from it, and different experts give different answers whatever the window does. The check passes when +both runs wrote the same tokens and printed the same likeliest tokens and probabilities at every step, and the +window run took guesses (it fails when none was offered, since it then checked nothing). + +The prompt is --tokens-file (comma-separated ids, as --tokens takes them), or by default a run of random ids +(--lo..--hi, a fixed seed) after BOS, repeated so that the model repeats it and lookup guesses from it. Options +after -- go to both runs. Exit status 0 when they agree, 1 when not. +""" +import argparse +import random +import re +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent + + +def run(a, ids, window): + cmd = [a.bin, "--model", a.model, "--tokens", ",".join(map(str, ids)), "--max-new", str(a.max_new), + "--max-context", str(a.max_context), "--window", str(window), "--lookup", "3", "--no-draft", + "--no-gpu-experts", "--prompt-cache", "0", "--conversation-cache-mib", "0", "--eos-ids", "0", + "--top-probs", str(a.top)] + a.passthrough + p = subprocess.run(cmd, capture_output=True, text=True, timeout=a.timeout) + if p.returncode != 0: + sys.stderr.write(p.stderr[-3000:]) + raise SystemExit(f"exit {p.returncode} for --window {window}") + tokens = [int(x) for x in re.findall(r"-?\d+", p.stdout)] + tops = [line for line in p.stderr.splitlines() if line.startswith("top ")] + m = re.search(r"(\d+) of (\d+) guessed tokens right", p.stderr) + return tokens, tops, (int(m.group(1)), int(m.group(2))) if m else (0, 0) + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--model", required=True) + ap.add_argument("--bin", default=str(ROOT / "build" / "strata-poly")) + ap.add_argument("--window", type=int, default=4) + ap.add_argument("--tokens-file", help="the prompt's ids, comma-separated (default: a repeated random run)") + ap.add_argument("--length", type=int, default=48, help="ids in the random run") + ap.add_argument("--repeats", type=int, default=3, help="times the random run is in the prompt") + ap.add_argument("--seed", type=int, default=20261122) + ap.add_argument("--lo", type=int, default=1000) + ap.add_argument("--hi", type=int, default=60000) + ap.add_argument("--max-new", type=int, default=200) + ap.add_argument("--max-context", type=int, default=4096) + ap.add_argument("--top", type=int, default=5, help="the likeliest tokens compared at every step") + ap.add_argument("--timeout", type=float, default=3600) + ap.add_argument("passthrough", nargs="*", help="extra engine options, after --") + a = ap.parse_args() + + if a.tokens_file: + ids = [int(x) for x in re.findall(r"-?\d+", Path(a.tokens_file).read_text())] + else: + rng = random.Random(a.seed) + run_ids = [rng.randrange(a.lo, a.hi) for _ in range(a.length)] + ids = [1] + run_ids * a.repeats + ref, ref_tops, _ = run(a, ids, 1) + got, got_tops, (right, guessed) = run(a, ids, a.window) + if not ref: + raise SystemExit("--window 1 wrote no token ids") + n = min(len(ref), len(got)) + first = next((k for k in range(n) if ref[k] != got[k]), None) + if first is None and len(ref) != len(got): + first = n + top_first = next((k for k in range(min(len(ref_tops), len(got_tops))) if ref_tops[k] != got_tops[k]), None) + if top_first is None and len(ref_tops) != len(got_tops): + top_first = min(len(ref_tops), len(got_tops)) + print(f"prompt {len(ids)} ids; --window {a.window}: {right} of {guessed} guessed tokens right") + print(f"tokens: {'the same ' + str(len(ref)) if first is None else 'first differ at step ' + str(first)}; " + f"top {a.top}: {'the same at ' + str(len(ref_tops)) + ' steps' if top_first is None else 'first differ at step ' + str(top_first)}") + if guessed == 0: + print("no guess was offered, so the window was not checked") + return 1 + return 0 if first is None and top_first is None else 1 + + +if __name__ == "__main__": + sys.exit(main())