diff --git a/docs/INKLING2.md b/docs/INKLING2.md new file mode 100644 index 00000000000..d68da6382b2 --- /dev/null +++ b/docs/INKLING2.md @@ -0,0 +1,134 @@ +# Inkling-2-Mini (`strata-ink2`) + +`strata-ink2` is Strata's engine program for [Inkling-2-Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini) +(Thinking Machines Lab, Apache 2.0): a 128-expert, top-8 mixture of experts whose layers 6-17 run three times, so a +token goes through 48 layer applications. The engine reads the published checkpoint as it is: NVFP4 experts in layers +0-19, MXFP8 experts in layers 20-23, BF16 for everything else, and the ViT that reads pictures. Nothing is requantized. + +To install and start it, see [MODELS.md](MODELS.md#inkling-2-mini): `./setup.sh --family inkling2` (the official +checkpoint, one of the two sources of setup's Inkling family; the `.strata` SQ builds run `strata-inkling` instead) +picks the flags below for your card. This page is for reading what setup chose, or for running the engine by hand. + +NVIDIA (RTX 20 series or newer) or AMD RDNA (wave32, gfx10 to gfx12) through ROCm, one GPU, Linux. The AMD port is +jingx8885's, measured on a gfx1151 (Radeon 8060S); the speeds below are NVIDIA ones. + +## What setup chooses + +Measured on an RTX 3090 with its VRAM limited to the card size (the expert pools only see that much), 2x Xeon Gold +6252, 257-token chat prompt, 512 greedy tokens; prompt speed on a 16K-token prompt. + +| Card | Engine flags (besides `--model`, `--chunk 1024 --tc 1`) | Decode | Prompt | +| --- | --- | --- | --- | +| 24 GB | `--max-context 65536 --kv f16 --spec 1` (every expert on the card) | 88-90 tok/s (108 on short prompts with `--spec`) | 2,380 tok/s | +| 16 GB | `--max-context 131072 --kv f16`, offload as below | not measured | not measured | +| 24 GB, longer contexts | `--max-context 131072 --kv f16 --kv-grow 1 --vram-reserve-mib R --cpu-threads N --spec 1` | 84-86 tok/s (103 on short prompts) | not measured | +| 12 GB, with a desktop | `--max-context 65536 --kv f16 --kv-grow 1 --vram-reserve-mib R --cpu-threads N` | 73-75 tok/s | 717 tok/s | +| 8 GB, nothing else on it | `--max-context 32768 --kv f16 --kv-grow 1 --vram-reserve-mib R --cpu-threads N` | 66 tok/s | 568 tok/s | +| 8 GB, with a desktop | the same with `--kv i8r` | 60-61 tok/s | 560 tok/s | + +Every config also gets `--conversation-cache-mib 4096` (2048, or off, when RAM is short). In offload the engine pins +about 17 GiB of RAM for the experts that are not on the card; setup asks for 32 GB of RAM. + +With the offload, setup adds `--spec 1` only where the card still holds 70% of the experts beside the drafter at the +full context. The drafter takes about 2 GiB from the expert pools (its weights, its K/V, and the prompt buffers, which +stay mapped with it), and a check computes eight tokens' experts to keep three to five, so the experts that are not on +the card cost more per token than in plain decoding. Decode in tok/s, plain and with `--spec 1` (same box, 512 greedy +tokens, mean of two runs; 16 GB: one run): + +| Card and context | Experts on the card with the drafter | Chat prompt (257 tokens) | Short prompt (24 tokens) | +| --- | --- | --- | --- | +| 8 GB, 32K | 19% | 66.9, with `--spec 1` 51.8 | 64.6, with `--spec 1` 59.9 | +| 12 GB, 64K | 45% | 80.6, with `--spec 1` 72.3 | 81.5, with `--spec 1` 87.9 | +| 16 GB, 128K | 70% | 84.1, with `--spec 1` 84.4 | 85.7, with `--spec 1` 100.2 | +| 24 GB, 128K | 98% | 85.9, with `--spec 1` 83.9 | 86.7, with `--spec 1` 103.1 | +| 24 GB, 256K, `--kv i8r`, no `--kv-grow` | 92% | 82.9, with `--spec 1` 84.7 | 83.3, with `--spec 1` 100.0 | + +These are speeds at the start of a conversation: with `--kv-grow` the K/V of a long conversation takes expert slots, +which is why the 16 GB card at 128K stays without the drafter. + +## Flags + +**Model and context** + +- `--model DIR` the checkpoint folder (or a GGUF file, below). +- `--max-context N` (alias `--ctx`) the longest conversation, prompt plus answer. +- `--chunk N` prompt tokens read per step (`--serve` needs one; setup uses 1024). With `--kv-grow` a chunk shrinks by + itself when the card is short of room. +- `--tc 0|1` tensor cores for the prompt (1, the default in setup). `--tc 0` is the exact fp32 path, slower, used to + check the other one. +- `--serve` the line protocol the Strata server speaks. + +**Memory** + +- `--vram-reserve-mib N` leaves N MiB of VRAM free and turns on the expert offload: the experts that do not fit stay + in pinned RAM, and the card keeps the most used ones (decayed use counts, promotions in the background). +- `--cpu-threads N` computes the experts that are not on the card on the CPU instead of copying them over PCIe: one + pool of N threads per NUMA node (at most two), each expert's memory bound to its node. Needs `--vram-reserve-mib`, + AVX2 + FMA + F16C, and Linux. `STRATA_NUMA_POOL=0` turns the NUMA placement off. +- `--kv-grow 1` the K/V cache starts small and grows into the expert pools as the conversation grows, so a long + context costs expert slots only when it is used. Each pool keeps at least 64 slots: a prompt that would need more + ends with a "context is full" error, and the engine keeps serving. `--kv-grow-step N` sets the growth step. +- `--kv FORMAT` the K/V format. Mean KL against fp32 K/V (expert routing fixed, 23K-token mixed text): + + | `--kv` | Bytes per token and layer pass | KL mean | Top-1 | + | --- | --- | --- | --- | + | `f16` (default) | 4,096 | 0 | 100% | + | `i8r` (int8, rotated) | 2,112 | 3.5e-5 | 99.80% | + | `k8v8` | 2,112 | 5.3e-5 | 99.73% | + | `i8` | 2,112 | 1.3e-4 | 99.61% | + | `k8v4` | 1,632 | 1.5e-3 (1.6K-token text) | 98.75% | + + `f32` exists for checks. + +**Speed** + +- `--spec 1` speculative decoding with the model's own drafter (`mtp.safetensors`): a draft token is kept only when it + is the model's own choice (greedy) or passes the usual acceptance test (sampled). It falls back to plain decoding + while that is faster. The check reads the drafts through other kernels than plain decoding, so a near-tie can go the + other way: a 512-token greedy answer matched plain decoding for 273 tokens, then parted where the top two logits were + 0.2 apart. With `--cpu-threads` the CPU also computes a check's experts that are not on the card (same answer as + with every expert on the card over those 512 tokens); it pays only where most experts are on the card (the table + under [What setup chooses](#what-setup-chooses)). +- `--verify-tc 1` (off by default) runs the dense products of a `--spec` check and of the drafter (up to 8 vectors, + matrices of more than 256 rows) on tensor cores: fp16 weights and inputs, fp32 accumulation, the numbers of the + prompt path's products. Without it, those products follow plain decoding's order. CUDA cards of compute capability + 8.0 or later. RTX 3090, every expert on the card, `--kv i8r`, a check at every step, three runs each: 36.0 ms per + check without, 32.6 with. With the expert routing fixed, the 8-token prompt lane is at mean KL 3.0e-7 against the + fp32 token path, against 8.7e-8 without the flag, top-1 100%. + +**Conversations and pictures** + +- `--conversation-cache-mib N` (0, off, by default) keeps conversations in pinned RAM so that a request never reads + again a prompt the engine already read: a checkpoint at the end of each prompt lets the next turn continue from + there even when the client sends the history back without the model's reasoning, conversations set aside (an + agent and its subagents taking turns) are taken up again, and conversations sharing a long beginning (a system + prompt and tools) read it once. `--conversation-cache-min-tokens N` (512): shorter conversations are not kept. +- Pictures need no flag. The ViT is read into RAM at the first picture and streamed to the card for each one, so + text-only use costs no VRAM; with offload it borrows a few hundred MiB of expert slots while it runs. A picture + over `--image-max-tokens N` (4096; one token is a 40x40 pixel tile) is scaled down. + +**Checks and debugging**: `--tokens IDS` / `--tokens-file F` with `--n N` run one prompt without the server, +`--dump-logits F`, `--record-routing F` / `--force-routing F`, `--image F`, `--dump-image-emb F`, `--vis-pixels F`. +`terminal/tools/inkling2/README.md` describes the comparison against the transformers implementation. + +## GGUF files + +`--model FILE.gguf` reads llama.cpp's merged `inkling2_loop` layout with IQ3_S, IQ4_NL and Q8_0 experts (work by +merbanan). GGUF models run without `--cpu-threads` and `--spec` for now, and setup does not install them. +Layers 20-23 may use a different expert type than layers 0-19, as in ggml-org's `Inkling-2-Mini-IQ4_NL.gguf` (IQ4_NL, +Q8_0 in layers 20-23): on the 1,600-token text its mean KL against the fp32 reference is 5.9e-3 (llama.cpp on the same +file: 5.4e-3). Any other mix, or an expert type outside these three (NVFP4, for example), stops the load with an error +that names the layers and types. + +## Quality + +Against the transformers implementation in fp32 on a 1,600-token text: the token-by-token path with fp32 K/V is at +mean KL 1.4e-12 (top-1 100%), and the tensor-core prompt path at 2.1e-7 with the expert routing fixed. Pictures: mean +KL 1e-7 or less in fp32, with the same greedy answers. + +## Limits + +- One GPU. `--cpu-threads` on Linux only, at most two NUMA nodes. +- `--spec` with the expert offload and no `--cpu-threads` copies a check's missing experts over PCIe: 16 tok/s on an + 8 GB card. Setup does not write that pair. +- Not offered in `strata launch` or the desktop app yet. diff --git a/docs/MODELS.md b/docs/MODELS.md index 10122bcdd59..9b744505eb0 100644 --- a/docs/MODELS.md +++ b/docs/MODELS.md @@ -284,6 +284,59 @@ drafting and picture reading (`Inkling-2-Mini-Vision.strata`, 0.64 GB). strata launch --family inkling-2-mini --model SQ-15 ``` +### The official checkpoint (`strata-ink2`) + +Setup's Inkling family also takes the official checkpoint (`./setup.sh --family inkling-2-mini --model official`, +or `--family inkling2` for short), which runs its own engine, `strata-ink2`; the rest of this section is about it. + +[Inkling-2-Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini) by Thinking Machines Lab (Apache 2.0): a +mixture of experts with 128 experts per layer, 8 active, NVFP4 and MXFP8 experts. Strata reads the published +checkpoint as it is (a 20.2 GB download at a pinned revision, every file checked against its size and SHA-256) with +its own engine program, `strata-ink2`, which setup compiles for your card. NVIDIA cards (RTX 20 series or newer) and AMD RDNA cards (ROCm) on +Linux only so far; it is not in the app or in `strata launch` yet. It reads pictures itself (send them in the chat +page or as `image_url`; nothing is loaded for them until the first one, then about 0.65 GB of RAM). A request's +`reasoning_effort` is the template's thinking level: a word (none 0.0, minimal 0.1, low 0.2, medium 0.7, high 0.9, +xhigh 0.99) or the level itself, 0.0 to 0.99; 0.9 when the request gives none. The model still thinks briefly at +none. Setup also +gives it a conversation cache in RAM (`--conversation-cache-mib`, 4096 or 2048 MiB depending on the RAM left, off +with a note below that): an agent's next turn then reads only what is new, even when the agent drops the model's +reasoning from its history. + +```sh +./setup.sh --family inkling2 +``` + +Setup picks how it runs from the card: + +- **Every expert fits on the card** (24 GB cards up to a 64K context): they stay there, with the checkpoint's draft + layer (`mtp.safetensors`) for faster answers. Measured on an RTX 3090: 19.3 GiB of graphics memory at an 8K context, + 21.2 GiB at 64K; the conversation memory takes 36,864 bytes a token. +- **Otherwise** (8 to 16 GB cards, or a longer context): the card keeps the most used experts and the others stay in + RAM (about 32 GB of RAM; the engine's peak was 16.8 GiB); the CPU computes the experts a token needs that the card + does not hold, one thread per physical core of each CPU socket (`--cpu-threads`, AVX2 needed). The conversation + memory grows into the card as it is used (`--kv-grow 1`) and gives the room back to the experts afterwards. + `--vram-reserve-mib N` keeps N MiB of the card free for other programs (1500 by default on a card that drives a + display, less where the card has no room for it). + + The engine keeps at least 64 expert slots of each kind (about 2.5 GB) at every point of a conversation: a long + prompt is read in smaller pieces near that limit, and a prompt that does not fit even then gets a plain error ("the + context is full") while the model keeps running. Setup picks the longest context that never reaches that point, + counting what a desktop already holds on the card, with 16-bit conversation memory where it reaches 32K and 8-bit + (`--kv i8r`, the closest 8-bit format to full precision) where it does not: + + | Card | Context | Conversation memory | + | --- | ---: | --- | + | 8 GB, nothing else on it | 32K | 16-bit | + | 8 GB driving a desktop | 32K | 8-bit (`i8r`) | + | 12 GB driving a desktop | 64K | 16-bit | + | 16 GB driving a desktop | 128K | 16-bit | + + Measured on an RTX 3090 set up as an 8 GB card with a 500 MiB desktop and 8-bit memory: a 30K-token prompt read + and answered (83 s to the end of the answer's 1,450 tokens), a 55K-token prompt refused with "the context is full" + after 41K tokens, and the next request answered by the same engine. + +The run config (`strata-inkling-2-mini-official.json`) holds the engine's arguments; they can be edited there. Every flag and its measured effect: [INKLING2.md](INKLING2.md). + ## Adding or switching models - **In the app:** the Models page lists every model with its size and whether it fits your computer. Pick one and press the install button. diff --git a/engine/cmake/strata_gpu_engine.cmake b/engine/cmake/strata_gpu_engine.cmake index e8c487297c6..d360497ff52 100644 --- a/engine/cmake/strata_gpu_engine.cmake +++ b/engine/cmake/strata_gpu_engine.cmake @@ -562,6 +562,28 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_executable(strata-q36ref src/qwen35/q36ref.cu) target_include_directories(strata-q36ref PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) target_link_libraries(strata-q36ref PRIVATE strata_kernels strata_warnings ${_strata_gpu_runtime_target}) + # NEW-MODELS-PLAN.md T1: Inkling-2-Mini's reference path (the thinkingmachines safetensors as shipped: BF16, NVFP4 and + # MXFP8 experts; one GPU, the model resident, plain kernels), checked against transformers by terminal/tools/inkling2/ + # HIP: Linux only (the engine uses POSIX calls) and out of the default target, so a plain HIP build of the other + # engines does not compile it; setup builds it by name + if(STRATA_ENABLE_CUDA OR (STRATA_ENABLE_HIP AND NOT WIN32)) + add_executable(strata-ink2ref src/inkling2/ink2ref.cu) + target_include_directories(strata-ink2ref PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) + target_link_libraries(strata-ink2ref PRIVATE strata_warnings ${_strata_gpu_runtime_target}) + # T2 engine path for the same family: --serve (engine protocol), chunked prefill (cuBLAS), decode graph captured on + # the per-thread default stream + # ink2_cpu.cpp: cold experts on the CPU (--cpu-threads), Linux x86 (a stub elsewhere) + find_package(Threads REQUIRED) + add_executable(strata-ink2 src/inkling2/ink2_engine.cu src/inkling2/ink2_cpu.cpp src/inkling2/ink2_image.cpp) + target_include_directories(strata-ink2 PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) + target_link_libraries(strata-ink2 PRIVATE strata_warnings ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target} Threads::Threads) + target_compile_options(strata-ink2 PRIVATE + $<$:--default-stream=per-thread> + $<$:-fgpu-default-stream=per-thread>) + if(STRATA_ENABLE_HIP) + set_target_properties(strata-ink2ref strata-ink2 PROPERTIES EXCLUDE_FROM_ALL ON) + endif() + endif() # the engine path for the same family (serve protocol, prompt chunks, decode graph): src/qwen35/q36_engine.cu, a # library that `strata` switches to for a qwen35moe model (the family switch at the top of its main) and that # strata-q36 wraps on its own. Not on gfx906 (#3172, #3271): it calls cuBLAS entry points the wave64 compat layer does diff --git a/engine/include/strata/hip_compat/cublas_v2.h b/engine/include/strata/hip_compat/cublas_v2.h index b6170078910..a0254c00c4c 100644 --- a/engine/include/strata/hip_compat/cublas_v2.h +++ b/engine/include/strata/hip_compat/cublas_v2.h @@ -9,6 +9,7 @@ #include #define CUBLAS_COMPUTE_32F rocblas_datatype_f32_r #define CUBLAS_DEFAULT_MATH 0 +#define CUBLAS_PEDANTIC_MATH CUBLAS_DEFAULT_MATH #define CUBLAS_GEMM_DEFAULT rocblas_gemm_algo_standard #define CUBLAS_OP_N rocblas_operation_none #define CUBLAS_OP_T rocblas_operation_transpose @@ -21,6 +22,7 @@ #define cublasHandle_t rocblas_handle #define cublasSetStream rocblas_set_stream #define cublasSetWorkspace rocblas_set_workspace +#define cublasSgemm rocblas_sgemm #define cublasStatus_t rocblas_status inline rocblas_status cublasSetMathMode(rocblas_handle h, int mode) { @@ -42,6 +44,8 @@ inline rocblas_status cublasGemmEx(rocblas_handle h, rocblas_operation trans_a, #else #define CUBLAS_COMPUTE_32F HIPBLAS_COMPUTE_32F #define CUBLAS_DEFAULT_MATH HIPBLAS_DEFAULT_MATH +// rocBLAS returns HIPBLAS_STATUS_NOT_SUPPORTED for HIPBLAS_PEDANTIC_MATH and already runs SGEMM in full FP32. +#define CUBLAS_PEDANTIC_MATH HIPBLAS_DEFAULT_MATH #define CUBLAS_GEMM_DEFAULT HIPBLAS_GEMM_DEFAULT #define CUBLAS_OP_N HIPBLAS_OP_N #define CUBLAS_OP_T HIPBLAS_OP_T diff --git a/engine/include/strata/hip_compat/cuda_runtime.h b/engine/include/strata/hip_compat/cuda_runtime.h index 805020cda3e..88aaea46bab 100644 --- a/engine/include/strata/hip_compat/cuda_runtime.h +++ b/engine/include/strata/hip_compat/cuda_runtime.h @@ -25,6 +25,7 @@ #define cudaDevAttrComputeCapabilityMinor hipDeviceAttributeComputeCapabilityMinor #define cudaDevAttrIntegrated hipDeviceAttributeIntegrated #define cudaDeviceGetAttribute hipDeviceGetAttribute +#define cudaDeviceGetPCIBusId hipDeviceGetPCIBusId #define cudaDeviceCanAccessPeer hipDeviceCanAccessPeer #define cudaDeviceEnablePeerAccess hipDeviceEnablePeerAccess #define cudaDeviceDisablePeerAccess hipDeviceDisablePeerAccess @@ -35,6 +36,7 @@ #define cudaErrorMemoryAllocation hipErrorOutOfMemory #define cudaErrorPeerAccessAlreadyEnabled hipErrorPeerAccessAlreadyEnabled #define cudaErrorStreamCaptureUnsupported hipErrorStreamCaptureUnsupported +#define cudaErrorUnknown hipErrorUnknown #define cudaError_t hipError_t #define cudaEventCreate hipEventCreate #define cudaEventCreateWithFlags hipEventCreateWithFlags @@ -112,6 +114,7 @@ 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 @@ -121,6 +124,7 @@ hipError_t mem_get_info(size_t* free_bytes, size_t* total_bytes); #define cudaStreamEndCapture hipStreamEndCapture #define cudaStreamIsCapturing hipStreamIsCapturing #define cudaStreamNonBlocking hipStreamNonBlocking +#define cudaStreamPerThread hipStreamPerThread #define cudaStreamQuery hipStreamQuery #define cudaStreamSynchronize hipStreamSynchronize #define cudaStreamWaitEvent hipStreamWaitEvent @@ -165,7 +169,14 @@ inline hipError_t cudaGraphInstantiate(hipGraphExec_t* exec, hipGraph_t graph, return hipGraphInstantiate(exec, graph, error, log, size); } #define __trap() __builtin_trap() // the compiled-out sm_80 paths (never selected on AMD) +#if defined(__HIP_STREAM_PER_THREAD) +#define cudaMemcpyToSymbol(symbol, ...) hipMemcpyToSymbol(static_cast(&(symbol)), __VA_ARGS__) +#define cudaMemcpyToSymbolAsync(symbol, ...) hipMemcpyToSymbolAsync(static_cast(&(symbol)), __VA_ARGS__) +#define cudaMemcpyFromSymbol(dst, symbol, ...) hipMemcpyFromSymbol(dst, static_cast(&(symbol)), __VA_ARGS__) +#else #define cudaMemcpyToSymbol(symbol, ...) hipMemcpyToSymbol(HIP_SYMBOL(symbol), __VA_ARGS__) +#define cudaMemcpyToSymbolAsync(symbol, ...) hipMemcpyToSymbolAsync(HIP_SYMBOL(symbol), __VA_ARGS__) #define cudaMemcpyFromSymbol(dst, symbol, ...) hipMemcpyFromSymbol(dst, HIP_SYMBOL(symbol), __VA_ARGS__) +#endif #include "intrinsics.hpp" diff --git a/engine/include/strata/hip_compat/intrinsics.hpp b/engine/include/strata/hip_compat/intrinsics.hpp index 49558dcc853..5a4b7fba419 100644 --- a/engine/include/strata/hip_compat/intrinsics.hpp +++ b/engine/include/strata/hip_compat/intrinsics.hpp @@ -144,6 +144,34 @@ __device__ __forceinline__ unsigned ballot_sync(uint32_t mask, int predicate) { return static_cast(__ballot(predicate)); } +// CUDA's __ldcv: load bypassing L1/L2 cache (system-scope coherent load for mapped host memory). +template +__device__ __forceinline__ T ldcv(const T* p) { + static_assert(sizeof(T) == 4 || sizeof(T) == 8 || sizeof(T) == 16, "__ldcv: 4, 8, or 16 bytes"); + if constexpr (sizeof(T) == 4) { + const unsigned u = + __hip_atomic_load(reinterpret_cast(p), __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); + T r; + __builtin_memcpy(&r, &u, 4); + return r; + } else if constexpr (sizeof(T) == 8) { + const unsigned long long u = __hip_atomic_load(reinterpret_cast(p), + __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); + T r; + __builtin_memcpy(&r, &u, 8); + return r; + } else { + const unsigned long long* q = reinterpret_cast(p); + const unsigned long long u[2] = { + __hip_atomic_load(q + 0, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM), + __hip_atomic_load(q + 1, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM), + }; + T r; + __builtin_memcpy(&r, u, 16); + return r; + } +} + } // namespace strata::hip_compat #define __dp4a(a, b, c) (::strata::hip_compat::dp4a((a), (b), (c))) @@ -156,6 +184,7 @@ __device__ __forceinline__ unsigned ballot_sync(uint32_t mask, int predicate) { #define __shfl_up_sync(...) (::strata::hip_compat::shfl_up_sync(__VA_ARGS__)) #define __shfl_sync(...) (::strata::hip_compat::shfl_sync(__VA_ARGS__)) #define __ballot_sync(mask, predicate) (::strata::hip_compat::ballot_sync((mask), (predicate))) +#define __ldcv(p) (::strata::hip_compat::ldcv((p))) #if HIP_VERSION_MAJOR < 7 #define __syncwarp(...) (::strata::hip_compat::syncwarp(__VA_ARGS__)) #endif diff --git a/engine/src/inkling2/ink2_cpu.cpp b/engine/src/inkling2/ink2_cpu.cpp new file mode 100644 index 00000000000..5243dd3bca2 --- /dev/null +++ b/engine/src/inkling2/ink2_cpu.cpp @@ -0,0 +1,852 @@ +// src/inkling2/ink2_cpu.cpp - see ink2_cpu.hpp. +// +// Expert slot layout (ink2_engine.cu): [w13 | s13 | w2 | s2]. NVFP4 (layers < mx_first): rows of K/2 bytes, value 2j +// in the low nibble of byte j, then one e4m3 scale per 16 columns per row; the dot product times a per-expert factor. +// MXFP8: rows of K e4m3 bytes, then one ue8m0 exponent per 32 columns per row. w13 rows: 2j gate j, 2j + 1 up j. +// +// Kernels: AVX2 + FMA + F16C (any x86-64 since Haswell / Zen) and AVX-512 variants, chosen at run time. +// +// int8 activations (NVFP4 layers, opt-in: INK2_CPU_ACT=int8): the activations (x, then the SwiGLU output) quantized +// to int8 per 16 values (scale amax / 127), stored per chunk of C values (64 with AVX-512 VNNI, 32 otherwise) as +// [even values | odd values], so a row's low nibbles meet the first half and its high nibbles the second with no +// interleave. The codes go through pshufb as doubled int8 + 12 (0..24: unsigned, for vpdpbusd / vpmaddubsw); each +// int32 lane (4 products) starts at -12 * (its 4 activations), which takes the +12 back; then per lane float(sum) * +// weight block scale (the e4m3 byte placed into an fp16, value * 2^-8) * activation block scale (* 128: the codes' 0.5 +// and the 2^8) into fp32 accumulators. KL 6e-4 against the resident run (fp32: 1e-4), and since the fp32 kernel's +// prefetch and vpermps decode no faster (one 1-job visit 65-67 us either way, fable/nh.cpp): not the default. +// +// fp32 path (default; MXFP8 layers always): NVFP4 codes through pshufb as doubled int8 (the 0.5 folded into the +// scale), MXFP8 bytes through fp16 (the GPU kernels' placement: the bits shifted into an fp16, exact, value * 2^-8, +// folded into the scale). The element values are the GPU's exactly; only the order of the fp32 sums differs. +#include "ink2_cpu.hpp" + +#if !defined(__linux__) || !(defined(__x86_64__) || defined(__i386__)) +// CBA: Linux x86 only (thread pinning, NUMA placement through sysfs, GCC target attributes); elsewhere --cpu-threads +// is refused (isa() == nullptr) and the experts' host memory is plain memory +#include +namespace ink2cpu { +int nodes() { return 1; } +void* node_alloc(size_t bytes, int) { return std::malloc(bytes); } +void node_free(void* p, size_t) { std::free(p); } +const char* isa() { return nullptr; } +void start(const Setup&) {} +void stop() {} +} // namespace ink2cpu +#else + +#if defined(__GNUC__) && !defined(__clang__) +#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" // GCC 12's avx512fintrin.h (_mm512_undefined_*) +#pragma GCC diagnostic ignored "-Wuninitialized" +#endif +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ink2cpu { +namespace { + +// ------------------------------------------------------------------------------------------------ topology +std::vector parse_list(const std::string& s) { // "0-23,48-71" + std::vector out; + std::stringstream ss(s); + std::string part; + while (std::getline(ss, part, ',')) { + if (part.empty()) continue; + const size_t d = part.find('-'); + const int a = std::atoi(part.c_str()), b = d == std::string::npos ? a : std::atoi(part.c_str() + d + 1); + for (int i = a; i <= b; ++i) out.push_back(i); + } + return out; +} +std::string read_line(const std::string& path) { + std::ifstream f(path); + std::string s; + std::getline(f, s); + return s; +} +// STRATA_NUMA_POOL=0 (Strata's switch for its own NUMA split): NUMA placement off, one pool over every node's cores, +// one doorbell, expert memory wherever the kernel puts it +bool numa_off() { + const char* e = std::getenv("STRATA_NUMA_POOL"); + return e && std::string(e) == "0"; +} +// physical cores of a node (the first thread of each core), in order; NUMA off: of the whole machine +std::vector node_cores(int node) { + std::vector cpus = parse_list(read_line(numa_off() ? std::string("/sys/devices/system/cpu/online") + : "/sys/devices/system/node/node" + std::to_string(node) + "/cpulist")); + if (cpus.empty() && node == 0) { + const int n = (int) std::thread::hardware_concurrency(); + for (int i = 0; i < n; ++i) cpus.push_back(i); + } + std::vector cores; + for (int c : cpus) { + const std::vector sib = parse_list(read_line("/sys/devices/system/cpu/cpu" + std::to_string(c) + + "/topology/thread_siblings_list")); + if (sib.empty() || sib[0] == c) cores.push_back(c); + } + return cores; +} +void pin(int cpu) { + cpu_set_t s; + CPU_ZERO(&s); + CPU_SET(cpu, &s); + pthread_setaffinity_np(pthread_self(), sizeof s, &s); +} +void nap_us(long us) { + timespec t{0, us * 1000}; + nanosleep(&t, nullptr); +} + +// ------------------------------------------------------------------------------------------------ tables +float E4H[256]; // e4m3 scale * 0.5 (the doubled NVFP4 codes) +float MXS[256]; // 2^(s - 127) * 2^8 (the fp16 placement's 2^-8) +alignas(16) const int8_t E2M1X2[16] = {0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12}; +alignas(64) const float E2M1X2F[16] = {0, 1, 2, 3, 4, 6, 8, 12, -0.0f, -1, -2, -3, -4, -6, -8, -12}; // as fp32 +alignas(16) const uint8_t E2M1X2U[16] = {12, 13, 14, 15, 16, 18, 20, 24, 12, 11, 10, 9, 8, 6, 4, 0}; // + 12 +float e4m3_decode(unsigned v) { // as the GPU's (NaN for 0x7F / 0xFF) + const int e = (v >> 3) & 15, m = v & 7; + float r = e == 0 ? (float) m * 0.001953125f : std::ldexp(1.0f + (float) m * 0.125f, e - 7); + if (e == 15 && m == 7) r = NAN; + return (v & 0x80) ? -r : r; +} + +// ------------------------------------------------------------------------------------------------ fp32 kernels +#define T2 __attribute__((target("avx2,fma,f16c"))) +#define T5 __attribute__((target("avx512f,avx512bw,avx512vl,avx2,fma,f16c"))) +#define T5V __attribute__((target("avx512f,avx512bw,avx512vl,avx512vnni,avx2,fma,f16c"))) + +T2 inline float hsum256(__m256 a) { + const __m128 h = _mm_add_ps(_mm256_castps256_ps128(a), _mm256_extractf128_ps(a, 1)); + const __m128 q = _mm_add_ps(h, _mm_movehl_ps(h, h)); + return _mm_cvtss_f32(_mm_add_ss(q, _mm_movehdup_ps(q))); +} +// 16 bytes = 32 NVFP4 values -> their doubled codes in element order: a = values 0-15, b = 16-31 +T2 inline void nv_codes(const uint8_t* p, __m128i lut, __m128i& a, __m128i& b) { + const __m128i q = _mm_loadu_si128((const __m128i*) p), m = _mm_set1_epi8(0x0F); + const __m128i lo = _mm_and_si128(q, m), hi = _mm_and_si128(_mm_srli_epi16(q, 4), m); + a = _mm_shuffle_epi8(lut, _mm_unpacklo_epi8(lo, hi)); + b = _mm_shuffle_epi8(lut, _mm_unpackhi_epi8(lo, hi)); +} +// e4m3 bytes (zero-extended in 16-bit lanes) -> the fp16 bits of value * 2^-8 +T2 inline __m128i e4m3_h8(__m128i w) { + return _mm_or_si128(_mm_slli_epi16(_mm_and_si128(w, _mm_set1_epi16(0x80)), 8), + _mm_slli_epi16(_mm_and_si128(w, _mm_set1_epi16(0x7F)), 7)); +} +T5 inline __m256i e4m3_h16(__m256i w) { + return _mm256_or_si256(_mm256_slli_epi16(_mm256_and_si256(w, _mm256_set1_epi16(0x80)), 8), + _mm256_slli_epi16(_mm256_and_si256(w, _mm256_set1_epi16(0x7F)), 7)); +} + +constexpr int R = 4; // rows per step (the activation loads shared) +// INK2_CPU_OPT (bit mask, default all): 1 vpermps NVFP4 kernel, 2 software prefetch, 4 SwiGLU fused into gate_up with h +// written by non-temporal stores, 8 the waiting threads keep AVX-512 warm, 16 start() pins its caller +int g_opt = 31; +// Software prefetch of the next step's rows (R rows ahead: codes, and the scale bytes). A thread's share of an expert +// is ~100 rows read once: the hardware prefetchers restart at every row group (4 streams + 4 scale streams, 18 lines +// each). One Cascade Lake core, cold slices (k1.cpp): 3.5 -> 3.9 GB/s (= the L2-resident rate); Zen 3 AVX2: 6.2 -> 7.5. +#define PF_ROWS(w, s, sdiv, step) \ + if (pf && (b & (step - 1)) == 0) { \ + _mm_prefetch((const char*) (w) + pf, _MM_HINT_T0); \ + if ((b & (8 * step - 1)) == 0) _mm_prefetch((const char*) (s) + pf / sdiv, _MM_HINT_T0); \ + } + +// y[r] = factor * W[r] . x for r in [r0, r1) +T2 void nv_rows_avx2(const uint8_t* W, int N, int K, const float* x, float factor, float* y, int r0, int r1) { + const uint8_t* S = W + (size_t) N * (K / 2); + const size_t pf = g_opt & 2 ? (size_t) R * (K / 2) : 0; + const __m128i lut = _mm_load_si128((const __m128i*) E2M1X2); + for (int r = r0; r < r1; r += R) { + const int nr = r1 - r < R ? r1 - r : R; + __m256 acc[R]; + for (int i = 0; i < R; ++i) acc[i] = _mm256_setzero_ps(); + for (int b = 0; b < K / 32; ++b) { + const __m256 x0 = _mm256_loadu_ps(x + 32 * b), x1 = _mm256_loadu_ps(x + 32 * b + 8), + x2 = _mm256_loadu_ps(x + 32 * b + 16), x3 = _mm256_loadu_ps(x + 32 * b + 24); + for (int i = 0; i < nr; ++i) { + const uint8_t* w = W + (size_t) (r + i) * (K / 2) + 16 * b; + const uint8_t* s = S + (size_t) (r + i) * (K / 16) + 2 * b; + PF_ROWS(w, s, 8, 4) + __m128i a, c; + nv_codes(w, lut, a, c); + const __m256 v0 = _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(a)), + v1 = _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(a, 8))), + v2 = _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(c)), + v3 = _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(c, 8))); + const __m256 p0 = _mm256_fmadd_ps(v1, x1, _mm256_mul_ps(v0, x0)); + const __m256 p1 = _mm256_fmadd_ps(v3, x3, _mm256_mul_ps(v2, x2)); + acc[i] = _mm256_fmadd_ps(p0, _mm256_set1_ps(E4H[s[0]]), acc[i]); + acc[i] = _mm256_fmadd_ps(p1, _mm256_set1_ps(E4H[s[1]]), acc[i]); + } + } + for (int i = 0; i < nr; ++i) y[r + i] = factor * hsum256(acc[i]); + } +} +T5 void nv_rows_512(const uint8_t* W, int N, int K, const float* x, float factor, float* y, int r0, int r1) { + const uint8_t* S = W + (size_t) N * (K / 2); + const size_t pf = g_opt & 2 ? (size_t) R * (K / 2) : 0; + const __m128i lut = _mm_load_si128((const __m128i*) E2M1X2); + for (int r = r0; r < r1; r += R) { + const int nr = r1 - r < R ? r1 - r : R; + __m512 acc[R]; + for (int i = 0; i < R; ++i) acc[i] = _mm512_setzero_ps(); + for (int b = 0; b < K / 32; ++b) { + const __m512 x0 = _mm512_loadu_ps(x + 32 * b), x1 = _mm512_loadu_ps(x + 32 * b + 16); + for (int i = 0; i < nr; ++i) { + const uint8_t* w = W + (size_t) (r + i) * (K / 2) + 16 * b; + const uint8_t* s = S + (size_t) (r + i) * (K / 16) + 2 * b; + PF_ROWS(w, s, 8, 4) + __m128i a, c; + nv_codes(w, lut, a, c); + const __m512 v0 = _mm512_cvtepi32_ps(_mm512_cvtepi8_epi32(a)), v1 = _mm512_cvtepi32_ps(_mm512_cvtepi8_epi32(c)); + acc[i] = _mm512_fmadd_ps(_mm512_mul_ps(v0, x0), _mm512_set1_ps(E4H[s[0]]), acc[i]); + acc[i] = _mm512_fmadd_ps(_mm512_mul_ps(v1, x1), _mm512_set1_ps(E4H[s[1]]), acc[i]); + } + } + for (int i = 0; i < nr; ++i) y[r + i] = factor * _mm512_reduce_add_ps(acc[i]); + } +} +// The sums of nv_rows_512 (same element values, same order: bit-identical results) with the codes decoded by one +// vpermps: 8 bytes zero-extended to 8 qwords, q | q << 28 puts the low nibble in the low 4 bits of the even dword and +// the high nibble in those of the odd one, and vpermps reads only those 4 bits of an index. Cascade Lake, one core, +// L2-resident (k1.cpp): 690 uops per KB on ports 0 + 5 against 862, and the core stays in the AVX-512 "light" licence +// (2.39 GHz all-core bin against 1.99): 6.05 GB/s against 4.03. +T5 void nv_rows_perm(const uint8_t* W, int N, int K, const float* x, float factor, float* y, int r0, int r1) { + const uint8_t* S = W + (size_t) N * (K / 2); + const size_t pf = g_opt & 2 ? (size_t) R * (K / 2) : 0; + const __m512 tab = _mm512_load_ps(E2M1X2F); + for (int r = r0; r < r1; r += R) { + const int nr = r1 - r < R ? r1 - r : R; + __m512 acc[R]; + for (int i = 0; i < R; ++i) acc[i] = _mm512_setzero_ps(); + for (int b = 0; b < K / 32; ++b) { + const __m512 x0 = _mm512_loadu_ps(x + 32 * b), x1 = _mm512_loadu_ps(x + 32 * b + 16); + for (int i = 0; i < nr; ++i) { + const uint8_t* w = W + (size_t) (r + i) * (K / 2) + 16 * b; + const uint8_t* s = S + (size_t) (r + i) * (K / 16) + 2 * b; + PF_ROWS(w, s, 8, 4) + const __m512i q0 = _mm512_cvtepu8_epi64(_mm_loadl_epi64((const __m128i*) w)), + q1 = _mm512_cvtepu8_epi64(_mm_loadl_epi64((const __m128i*) (w + 8))); + const __m512 v0 = _mm512_permutexvar_ps(_mm512_or_si512(q0, _mm512_slli_epi64(q0, 28)), tab), + v1 = _mm512_permutexvar_ps(_mm512_or_si512(q1, _mm512_slli_epi64(q1, 28)), tab); + acc[i] = _mm512_fmadd_ps(_mm512_mul_ps(v0, x0), _mm512_set1_ps(E4H[s[0]]), acc[i]); + acc[i] = _mm512_fmadd_ps(_mm512_mul_ps(v1, x1), _mm512_set1_ps(E4H[s[1]]), acc[i]); + } + } + for (int i = 0; i < nr; ++i) y[r + i] = factor * _mm512_reduce_add_ps(acc[i]); + } +} +T2 void mx_rows_avx2(const uint8_t* W, int N, int K, const float* x, float* y, int r0, int r1) { + const uint8_t* S = W + (size_t) N * K; + for (int r = r0; r < r1; r += R) { + const int nr = r1 - r < R ? r1 - r : R; + __m256 acc[R]; + for (int i = 0; i < R; ++i) acc[i] = _mm256_setzero_ps(); + for (int b = 0; b < K / 32; ++b) { + const __m256 x0 = _mm256_loadu_ps(x + 32 * b), x1 = _mm256_loadu_ps(x + 32 * b + 8), + x2 = _mm256_loadu_ps(x + 32 * b + 16), x3 = _mm256_loadu_ps(x + 32 * b + 24); + for (int i = 0; i < nr; ++i) { + const uint8_t* w = W + (size_t) (r + i) * K + 32 * b; + const __m128i q0 = _mm_loadu_si128((const __m128i*) w), q1 = _mm_loadu_si128((const __m128i*) (w + 16)); + const __m256 v0 = _mm256_cvtph_ps(e4m3_h8(_mm_cvtepu8_epi16(q0))), + v1 = _mm256_cvtph_ps(e4m3_h8(_mm_cvtepu8_epi16(_mm_srli_si128(q0, 8)))), + v2 = _mm256_cvtph_ps(e4m3_h8(_mm_cvtepu8_epi16(q1))), + v3 = _mm256_cvtph_ps(e4m3_h8(_mm_cvtepu8_epi16(_mm_srli_si128(q1, 8)))); + const __m256 p = _mm256_fmadd_ps(v3, x3, _mm256_fmadd_ps(v2, x2, _mm256_fmadd_ps(v1, x1, _mm256_mul_ps(v0, x0)))); + acc[i] = _mm256_fmadd_ps(p, _mm256_set1_ps(MXS[S[(size_t) (r + i) * (K / 32) + b]]), acc[i]); + } + } + for (int i = 0; i < nr; ++i) y[r + i] = hsum256(acc[i]); + } +} +T5 void mx_rows_512(const uint8_t* W, int N, int K, const float* x, float* y, int r0, int r1) { + const uint8_t* S = W + (size_t) N * K; + const size_t pf = g_opt & 2 ? (size_t) R * K : 0; + for (int r = r0; r < r1; r += R) { + const int nr = r1 - r < R ? r1 - r : R; + __m512 acc[R]; + for (int i = 0; i < R; ++i) acc[i] = _mm512_setzero_ps(); + for (int b = 0; b < K / 32; ++b) { + const __m512 x0 = _mm512_loadu_ps(x + 32 * b), x1 = _mm512_loadu_ps(x + 32 * b + 16); + for (int i = 0; i < nr; ++i) { + const uint8_t* w = W + (size_t) (r + i) * K + 32 * b; + PF_ROWS(w, S + (size_t) (r + i) * (K / 32) + b, 32, 2) + const __m256i q = _mm256_cvtepu8_epi16(_mm_loadu_si128((const __m128i*) w)), + q2 = _mm256_cvtepu8_epi16(_mm_loadu_si128((const __m128i*) (w + 16))); + const __m512 v0 = _mm512_cvtph_ps(e4m3_h16(q)), v1 = _mm512_cvtph_ps(e4m3_h16(q2)); + const __m512 p = _mm512_fmadd_ps(v1, x1, _mm512_mul_ps(v0, x0)); + acc[i] = _mm512_fmadd_ps(p, _mm512_set1_ps(MXS[S[(size_t) (r + i) * (K / 32) + b]]), acc[i]); + } + } + for (int i = 0; i < nr; ++i) y[r + i] = _mm512_reduce_add_ps(acc[i]); + } +} + +// ------------------------------------------------------------------------------------------------ int8 activations +struct QAct { // K activations in the q8 kernels' form (see the top) + const int8_t* q; // [K] per chunk of C: even values, then odd values + const int32_t* init; // [K/4] per lane (4 q): -12 * their sum + const float* xs; // [K/4] per lane: its block's scale * 128 +}; + +// 16 activations (block b of the vector) -> int8 at their places in the chunk layout, and the block's scale d[b] +T2 void q8_block(const float* x, int b, int C, int8_t* q, float* d) { + const __m256 a = _mm256_loadu_ps(x), c = _mm256_loadu_ps(x + 8), sgn = _mm256_set1_ps(-0.0f); + const __m256 m = _mm256_max_ps(_mm256_andnot_ps(sgn, a), _mm256_andnot_ps(sgn, c)); + __m128 h = _mm_max_ps(_mm256_castps256_ps128(m), _mm256_extractf128_ps(m, 1)); + h = _mm_max_ps(h, _mm_movehl_ps(h, h)); + h = _mm_max_ss(h, _mm_movehdup_ps(h)); + const float am = _mm_cvtss_f32(h); + d[b] = am / 127.0f; + const __m256 id = _mm256_set1_ps(am > 0 ? 127.0f / am : 0.0f); + const __m256i ia = _mm256_cvtps_epi32(_mm256_mul_ps(a, id)), ic = _mm256_cvtps_epi32(_mm256_mul_ps(c, id)); + // packs work per 128-bit half: [a0-3 c0-3 | a4-7 c4-7] -> [a0-3 a4-7 c0-3 c4-7] -> 16 int8 in order + const __m256i p16 = _mm256_permute4x64_epi64(_mm256_packs_epi32(ia, ic), 0xD8); + const __m128i p8 = _mm_packs_epi16(_mm256_castsi256_si128(p16), _mm256_extracti128_si256(p16, 1)); + const __m128i eo = _mm_shuffle_epi8(p8, _mm_setr_epi8(0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15)); + int8_t* base = q + (size_t) (b / (C / 16)) * C + (b % (C / 16)) * 8; + _mm_storel_epi64((__m128i*) base, eo); + _mm_storel_epi64((__m128i*) (base + C / 2), _mm_unpackhi_epi64(eo, eo)); +} +// the lanes' starts and scales of K quantized activations (q, block scales d) +T2 void q8_lanes(const int8_t* q, const float* d, int K, int C, int32_t* init, float* xs) { + const __m256i one8 = _mm256_set1_epi8(1), m12 = _mm256_set1_epi16(-12); + for (int i = 0; i < K; i += 32) + _mm256_storeu_si256((__m256i*) (init + i / 4), + _mm256_madd_epi16(_mm256_maddubs_epi16(one8, _mm256_loadu_si256((const __m256i*) (q + i))), m12)); + // a chunk's lanes: its even half then its odd half, each two lanes per block + for (int c = 0, i = 0; c < K / C; ++c) + for (int half = 0; half < 2; ++half) + for (int b = 0; b < C / 16; ++b, i += 2) xs[i] = xs[i + 1] = 128.0f * d[c * (C / 16) + b]; +} + +// CBA: the e4m3 block scales' sign bit is dropped (NVFP4 block scales are amax / 6 / global: non-negative) +T2 void q8_rows_avx2(const uint8_t* W, int N, int K, QAct X, float factor, float* y, int r0, int r1) { + const uint8_t* S = W + (size_t) N * (K / 2); + const __m256i lut = _mm256_broadcastsi128_si256(_mm_load_si128((const __m128i*) E2M1X2U)); + const __m128i m4 = _mm_set1_epi8(0x0F), sm = _mm_set1_epi16(0x7F00); + const __m256i ones = _mm256_set1_epi16(1); + // word w of the 8 lane scales: high byte = scale byte (w & 3) >> 1, low byte zero + const __m128i sctl = _mm_setr_epi8(-1, 0, -1, 0, -1, 1, -1, 1, -1, 0, -1, 0, -1, 1, -1, 1); + for (int r = r0; r < r1; r += R) { + const int nr = r1 - r < R ? r1 - r : R; + __m256 acc[R]; + for (int i = 0; i < R; ++i) acc[i] = _mm256_setzero_ps(); + for (int c = 0; c < K / 32; ++c) { + const __m256i xq = _mm256_loadu_si256((const __m256i*) (X.q + 32 * c)); + const __m256i in = _mm256_loadu_si256((const __m256i*) (X.init + 8 * c)); + const __m256 xs = _mm256_loadu_ps(X.xs + 8 * c); + for (int i = 0; i < nr; ++i) { + const uint8_t* w = W + (size_t) (r + i) * (K / 2) + 16 * c; + uint16_t s2; + std::memcpy(&s2, S + (size_t) (r + i) * (K / 16) + 2 * c, 2); + const __m128i q = _mm_loadu_si128((const __m128i*) w); + const __m128i lo = _mm_and_si128(q, m4), hi = _mm_and_si128(_mm_srli_epi16(q, 4), m4); + const __m256i wq = _mm256_shuffle_epi8(lut, _mm256_set_m128i(hi, lo)); + const __m256i isum = _mm256_add_epi32(_mm256_madd_epi16(_mm256_maddubs_epi16(wq, xq), ones), in); + const __m128i sh = _mm_srli_epi16(_mm_and_si128(_mm_shuffle_epi8(_mm_set1_epi16((short) s2), sctl), sm), 1); + const __m256 sc = _mm256_mul_ps(_mm256_cvtph_ps(sh), xs); + acc[i] = _mm256_fmadd_ps(_mm256_cvtepi32_ps(isum), sc, acc[i]); + } + } + for (int i = 0; i < nr; ++i) y[r + i] = factor * hsum256(acc[i]); + } +} +T5V void q8_rows_vnni(const uint8_t* W, int N, int K, QAct X, float factor, float* y, int r0, int r1) { + const uint8_t* S = W + (size_t) N * (K / 2); + const __m512i lut = _mm512_broadcast_i32x4(_mm_load_si128((const __m128i*) E2M1X2U)); + const size_t pf = g_opt & 2 ? (size_t) R * (K / 2) : 0; + const __m256i m4 = _mm256_set1_epi8(0x0F), sm = _mm256_set1_epi16(0x7F00); + // word w of the 16 lane scales (per 128-bit half, words 0-7 / 8-15): high byte = scale byte (w & 7) >> 1 + const __m256i sctl = _mm256_setr_epi8(-1, 0, -1, 0, -1, 1, -1, 1, -1, 2, -1, 2, -1, 3, -1, 3, + -1, 0, -1, 0, -1, 1, -1, 1, -1, 2, -1, 2, -1, 3, -1, 3); + for (int r = r0; r < r1; r += R) { + const int nr = r1 - r < R ? r1 - r : R; + __m512 acc[R]; + for (int i = 0; i < R; ++i) acc[i] = _mm512_setzero_ps(); + for (int b = 0; b < K / 64; ++b) { + const int c = b; + const __m512i xq = _mm512_loadu_si512(X.q + 64 * c); + const __m512i in = _mm512_loadu_si512(X.init + 16 * c); + const __m512 xs = _mm512_loadu_ps(X.xs + 16 * c); + for (int i = 0; i < nr; ++i) { + const uint8_t* w = W + (size_t) (r + i) * (K / 2) + 32 * c; + PF_ROWS(w, S + (size_t) (r + i) * (K / 16) + 4 * c, 8, 2) + int s4; + std::memcpy(&s4, S + (size_t) (r + i) * (K / 16) + 4 * c, 4); + const __m256i q = _mm256_loadu_si256((const __m256i*) w); + const __m256i lo = _mm256_and_si256(q, m4), hi = _mm256_and_si256(_mm256_srli_epi16(q, 4), m4); + const __m512i wq = _mm512_shuffle_epi8(lut, _mm512_inserti64x4(_mm512_castsi256_si512(lo), hi, 1)); + const __m512i isum = _mm512_dpbusd_epi32(in, wq, xq); + const __m256i sh = _mm256_srli_epi16(_mm256_and_si256(_mm256_shuffle_epi8(_mm256_set1_epi32(s4), sctl), sm), 1); + const __m512 sc = _mm512_mul_ps(_mm512_cvtph_ps(sh), xs); + acc[i] = _mm512_fmadd_ps(_mm512_cvtepi32_ps(isum), sc, acc[i]); + } + } + for (int i = 0; i < nr; ++i) y[r + i] = factor * _mm512_reduce_add_ps(acc[i]); + } +} + +int g_isa = 0; // fp32 kernels: 2 avx2, 5 avx512 +bool g_vnni = false; // q8 kernels: AVX-512 VNNI (chunks of 64), else AVX2 (chunks of 32) +bool g_q8 = false; // NVFP4 layers with int8 activations (INK2_CPU_ACT=int8) +int g_C = 32; +void rows(bool nv, const uint8_t* W, int N, int K, const float* x, float factor, float* y, int r0, int r1) { + if (r0 >= r1) return; + if (nv) (g_isa == 5 ? (g_opt & 1 ? nv_rows_perm : nv_rows_512) : nv_rows_avx2)(W, N, K, x, factor, y, r0, r1); + else (g_isa == 5 ? mx_rows_512 : mx_rows_avx2)(W, N, K, x, y, r0, r1); +} +void q8_rows(const uint8_t* W, int N, int K, QAct X, float factor, float* y, int r0, int r1) { + if (r0 < r1) (g_vnni ? q8_rows_vnni : q8_rows_avx2)(W, N, K, X, factor, y, r0, r1); +} + +// ------------------------------------------------------------------------------------------------ pools +Setup S; +inline float swiglu1(float g, float u) { // as the GPU's + return (std::tanh(g / S.gate_cap) * S.gate_cap) * (1.0f / (1.0f + std::exp(-g))) * (std::tanh(u / S.up_cap) * S.up_cap); +} + +struct Barrier { // spinning, sense-reversing + alignas(64) std::atomic count{0}; + alignas(64) std::atomic sense{0}; + int n = 1; + void wait(int& local) { + local ^= 1; + if (count.fetch_add(1, std::memory_order_acq_rel) == n - 1) { + count.store(0, std::memory_order_relaxed); + sense.store(local, std::memory_order_release); + } else { + while (sense.load(std::memory_order_acquire) != local) _mm_pause(); + } + } +}; + +constexpr int K8 = BELL_K, FFX = 1152; // FFX: FF bound of the buffers (start() checks) +struct alignas(64) Node { + int id = 0; + std::vector cpus; + alignas(64) std::atomic gen{0}; // the sequence number the workers are to run + Barrier bar; + // the node's jobs (published by its master before gen) + int nj = 0, layer = 0; + int ex[K8]; // expert + float* y[K8]; // its output row (in the node's doorbell) + // node-local; written by one thread (x) or by slices (the rest), read by all + float* x = nullptr; // [H] fp32 path + int8_t* xq = nullptr; // [H] q8 path: x quantized, and its block scales + float* xd = nullptr; // [H/16] + float* gu = nullptr; // [K8][2 FF] + float* hh = nullptr; // [K8][FF] fp32 path + int8_t* hq = nullptr; // [K8][FF] q8 path + float* hd = nullptr; // [K8][FF/16] + alignas(64) double ph[7] = {}; // trace: the master's ms at its phase ends + std::vector th; +}; +struct Priv { // a pool thread's copies of the visit's inputs in the kernels' forms (heap, first touched by the thread) + alignas(64) float x[BELL_H]; + alignas(64) float h[K8 * FFX]; + alignas(64) int8_t qx[BELL_H]; + alignas(64) int32_t ix[BELL_H / 4]; + alignas(64) float sx[BELL_H / 4]; + alignas(64) int8_t qh[K8 * FFX]; + alignas(64) int32_t ih[K8 * FFX / 4]; + alignas(64) float sh[K8 * FFX / 4]; + alignas(64) float warm[16] = {}; // warm512's scratch +}; +std::vector g_nodes; +std::atomic g_stop{false}; +std::atomic g_ready{0}; // threads started (start() returns once all are: a ring before a thread read its + // starting point was taken for that starting point, never acked: the GPU's wait trapped) +bool g_trace = false; +constexpr double IDLE_MS = 20.0; // spinning this long without work, then naps of NAP_US +constexpr long NAP_US = 100; + +double now_ms() { + timespec t; + clock_gettime(CLOCK_MONOTONIC, &t); + return t.tv_sec * 1e3 + t.tv_nsec / 1e6; +} +// a share of n items in units of `align` +void share(int n, int t, int T, int align, int& a, int& b) { + const int units = (n + align - 1) / align; + a = std::min(n, (int) ((long) units * t / T) * align); + b = std::min(n, (int) ((long) units * (t + 1) / T) * align); +} +// a copy of bytes the node's other threads wrote, each thread starting at its own place: the whole pool reading the +// same lines in the same order crawled (8.8 KB in 22 threads: 17 us; staggered: 7.6) +T2 void copy_rot(void* dst, const void* src, size_t bytes, int t, int T) { + const size_t n = bytes / 32, o = n * t / T; + __m256i* d = (__m256i*) dst; + const __m256i* s = (const __m256i*) src; + for (size_t i = o; i < n; ++i) _mm256_storeu_si256(d + i, _mm256_loadu_si256(s + i)); + for (size_t i = 0; i < o; ++i) _mm256_storeu_si256(d + i, _mm256_loadu_si256(s + i)); + std::memcpy((char*) dst + n * 32, (const char*) src + n * 32, bytes % 32); +} +inline void mark(Node& N, int t, int i) { if (!t && g_trace) N.ph[i] = now_ms(); } + +void node_work(Node& N, Priv& P, int t, int& sense) { + const int T = (int) N.cpus.size(), l = N.layer, H = S.h, FF = S.ff, nj = N.nj, C = g_C; + const bool nv = l < S.mx_first, q8 = nv && g_q8, fuse = (g_opt & 4) && !q8; + const size_t partA = nv ? S.nv_partA : S.mx_partA; + int a, b; + // private copies of the input: threads reading a buffer others write near hit an 8x slowdown (cpunv.cpp) + if (q8) { + copy_rot(P.qx, N.xq, H, t, T); + q8_lanes(P.qx, N.xd, H, C, P.ix, P.sx); + } else { + copy_rot(P.x, N.x, (size_t) H * 4, t, T); + } + mark(N, t, 0); + share(2 * FF, t, T, R, a, b); + for (int j = 0; j < nj; ++j) { + const int key = l * S.ne + N.ex[j]; + float* gu = N.gu + (size_t) j * 2 * FF; + if (q8) q8_rows(S.ex[key], 2 * FF, H, {P.qx, P.ix, P.sx}, S.f13[key], gu, a, b); + else rows(nv, S.ex[key], 2 * FF, H, P.x, nv ? S.f13[key] : 1.0f, gu, a, b); + if (fuse) { + // SwiGLU of the thread's own outputs right away (rows 2i and 2i + 1 are both in its share: R is even), one + // barrier less. h by non-temporal stores: every thread of the node reads all of it next, and lines left + // modified in 22 cores' caches made those 22 copies of 4.6 KB cost ~8 us (bcast2.cpp: 12 us against + // 0.5 us when the writers bypass their caches) + float* hh = N.hh + (size_t) j * FF; + for (int i = a / 2; i < b / 2; ++i) { + const float v = swiglu1(gu[2 * i], gu[2 * i + 1]); + int bits; + std::memcpy(&bits, &v, 4); + _mm_stream_si32((int*) (hh + i), bits); + } + } + } + mark(N, t, 1); + if (fuse) { + _mm_sfence(); + mark(N, t, 2); + } else { + N.bar.wait(sense); + mark(N, t, 2); + share(nj * FF / 16, t, T, 1, a, b); // SwiGLU per block of 16 outputs (q8: quantized as a block) + for (int blk = a; blk < b; ++blk) { + alignas(32) float h[16]; + const float* gu = N.gu + 32 * (size_t) blk; + for (int i = 0; i < 16; ++i) h[i] = swiglu1(gu[2 * i], gu[2 * i + 1]); + if (q8) q8_block(h, blk, C, N.hq, N.hd); + else std::memcpy(N.hh + 16 * (size_t) blk, h, sizeof h); + } + } + N.bar.wait(sense); + mark(N, t, 3); + if (q8) { + copy_rot(P.qh, N.hq, (size_t) nj * FF, t, T); + q8_lanes(P.qh, N.hd, nj * FF, C, P.ih, P.sh); + } else { + copy_rot(P.h, N.hh, (size_t) nj * FF * 4, t, T); + } + mark(N, t, 4); + share(H, t, T, R, a, b); + for (int j = 0; j < nj; ++j) { + const int key = l * S.ne + N.ex[j]; + float* y = N.y[j]; + if (q8) q8_rows(S.ex[key] + partA, H, FF, {P.qh + (size_t) j * FF, P.ih + (size_t) j * FF / 4, P.sh + (size_t) j * FF / 4}, + S.f2[key], y, a, b); + else rows(nv, S.ex[key] + partA, H, FF, P.h + (size_t) j * FF, nv ? S.f2[key] : 1.0f, y, a, b); + } + mark(N, t, 5); + N.bar.wait(sense); + mark(N, t, 6); +} + +// A core that has run no 512-bit code for ~1 ms powers its upper vector lanes down and drops its AVX-512 licence; the +// next visit then starts slowly (nh.cpp: a 1-job visit after a gap of 1 ms or more takes +50 us, 58 -> 110). The +// waiting threads run a few 512-bit FMAs every WARM_SPINS pauses (~0.1 ms) so that a visit always starts warm. +constexpr unsigned WARM_SPINS = 1024; +T5 __attribute__((noinline)) void warm512(float* p) { + __m512 a = _mm512_loadu_ps(p), b = _mm512_set1_ps(0.999f); + for (int i = 0; i < 8; ++i) a = _mm512_fmadd_ps(a, b, b); + _mm512_storeu_ps(p, a); +} +inline void spin(Priv* P, unsigned& n) { + _mm_pause(); + if ((g_opt & 8) && g_isa == 5 && ++n % WARM_SPINS == 0) warm512(P->warm); +} + +void worker(Node* N, int t) { + pin(N->cpus[t]); + Priv* P = new Priv; + int sense = 0; + unsigned seen = 0, spins = 0; // gen starts at 0 + g_ready.fetch_add(1); + double last = now_ms(); + while (!g_stop.load(std::memory_order_relaxed)) { + const unsigned g = N->gen.load(std::memory_order_acquire); + if (g == seen) { + if (now_ms() - last > IDLE_MS) nap_us(NAP_US); + else spin(P, spins); + continue; + } + seen = g; + node_work(*N, *P, t, sense); + last = now_ms(); + } + delete P; +} + +void master(Node* N) { + pin(N->cpus[0]); + Priv* P = new Priv; + InkBell* B = S.bell[N->id]; // the node's own doorbell (local memory) + int sense = 0; + unsigned seen = 0, vseen = 0, spins = 0, gen = 0; // the bell is zeroed before start(): ring 0 = nothing yet + // nj jobs (N->ex, N->y) of layer l on the input x (in the node's doorbell): published to the workers, run with them + auto pass = [&](int l, int nj, const float* x) { + N->nj = nj; + N->layer = l; + if (l < S.mx_first && g_q8) + for (int b = 0; b < S.h / 16; ++b) q8_block(x + 16 * b, b, g_C, N->xq, N->xd); + else + std::memcpy(N->x, x, (size_t) S.h * 4); + N->gen.store(++gen, std::memory_order_release); + node_work(*N, *P, 0, sense); + }; + g_ready.fetch_add(1); + double last = now_ms(); + while (!g_stop.load(std::memory_order_relaxed)) { + const unsigned seq = B->ring, vseq = B->vring; + if (seq == seen && vseq == vseen) { + if (now_ms() - last > IDLE_MS) nap_us(NAP_US); + else spin(P, spins); + continue; + } + if (vseq != vseen) { // a verify block's visit: its tokens one after the other, each as a decode visit + vseen = vseq; + const double t_ring = g_trace ? now_ms() : 0.0; + int jobs = 0; + std::atomic_thread_fence(std::memory_order_acquire); + const int n = std::min((int) B->vn, BELL_J), l = B->vlayer; + // CBA: one pass over an expert's weights per token that routes to it; a row kernel taking several inputs + // per expert (as the GPU's k_moe_gemv_grp) would read them once + for (int j = 0; j < n;) { + const int tok = B->vt[j]; + int nj = 0; + for (; j < n && B->vt[j] == tok; ++j) { + const int e = B->ve[j]; + if (S.home[l * S.ne + e] != N->id || nj == K8) continue; + N->ex[nj] = e; + N->y[nj] = B->vy[j]; + ++nj; + } + if (nj) pass(l, nj, B->vx[tok]); + jobs += nj; + } + std::atomic_thread_fence(std::memory_order_seq_cst); + B->ack[N->id] = vseq; + last = now_ms(); + if (g_trace && jobs) { // per node, every 1000 busy verify visits: jobs, experts with jobs, us per visit + static thread_local double v = 0, sj = 0, se = 0, su = 0; + bool ex[256] = {}; + for (int j = 0; j < n; ++j) + if (S.home[l * S.ne + B->ve[j]] == N->id && !ex[B->ve[j] & 255]) { ex[B->ve[j] & 255] = true; se += 1; } + sj += jobs; + su += last - t_ring; + if (++v == 1000) { + std::fprintf(stderr, "[cpu] node %d verify: per busy visit %.1f jobs on %.1f experts, %.0f us\n", N->id, + sj / v, se / v, 1e3 * su / v); + v = sj = se = su = 0; + } + } + continue; + } + seen = seq; + const double t_ring = now_ms(); + std::atomic_thread_fence(std::memory_order_acquire); + const int n = B->n, l = B->layer; + int nj = 0; + for (int j = 0; j < n && j < K8; ++j) { + const int e = B->e[j]; + if (S.home[l * S.ne + e] != N->id) continue; + N->ex[nj] = e; + N->y[nj] = B->y[j]; + ++nj; + } + if (nj) pass(l, nj, (const float*) B->x); + std::atomic_thread_fence(std::memory_order_seq_cst); + B->ack[N->id] = seq; + last = now_ms(); + if (nj) { // the node's time per job for the GPU's PCIe share (the ring seen -> the ack, over 16 visits) + const float us = (float) (1e3 * (last - t_ring) / nj); + B->us_job = B->us_job > 0.0f ? B->us_job + (us - B->us_job) / 16.0f : us; + } + if (g_trace) { // per node, every 2000 rings: busy visits, us from the ring seen to the ack by jobs per visit, + // and the master's phases per busy visit + static thread_local double cnt[K8 + 1], sum[K8 + 1], ph[7], rings = 0, worst = 0; + const double d = last - t_ring; + ++rings; + if (nj) { + cnt[nj] += 1; + sum[nj] += d; + worst = d > worst ? d : worst; + for (int i = 0; i < 7; ++i) ph[i] += N->ph[i] - (i ? N->ph[i - 1] : t_ring); + } + if (rings == 2000) { + double busy = 0; + for (int i = 1; i <= K8; ++i) busy += cnt[i]; + busy = std::max(busy, 1.0); + char line[512]; + int len = std::snprintf(line, sizeof line, "[cpu] node %d: %.0f busy of 2000, max %.0f us; us by jobs:", N->id, + busy, 1e3 * worst); + for (int i = 1; i <= K8; ++i) + if (cnt[i]) len += std::snprintf(line + len, sizeof line - len, " %d:%.0f(%.0f)", i, 1e3 * sum[i] / cnt[i], cnt[i]); + len += std::snprintf(line + len, sizeof line - len, "; phases (in, gate_up, wait, swiglu, h, down, wait)"); + for (double v : ph) len += std::snprintf(line + len, sizeof line - len, " %.1f", 1e3 * v / busy); + std::fprintf(stderr, "%s\n", line); + for (int i = 0; i <= K8; ++i) cnt[i] = sum[i] = 0; + for (double& v : ph) v = 0; + rings = worst = 0; + } + } + } + delete P; +} + +} // namespace + +// ------------------------------------------------------------------------------------------------ API +int nodes() { + int n = 0; + while (!read_line("/sys/devices/system/node/node" + std::to_string(n) + "/cpulist").empty()) ++n; + if (numa_off()) return 1; + if (const char* e = std::getenv("INK2_CPU_NODES")) n = std::min(n, std::max(1, std::atoi(e))); // 1: node 0 only + return std::min(n ? n : 1, 2); // CBA: two nodes at most (InkBell::ack, Setup::bell); more = widen those arrays +} + +void* node_alloc(size_t bytes, int node) { + void* p = mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (p == MAP_FAILED) return nullptr; + madvise(p, bytes, MADV_HUGEPAGE); + if (numa_off()) return p; // first touched by whoever writes it first + // MPOL_BIND before the first touch: with the default policy a node short of free pages (page cache: the box had 3.7 + // of 95 GB free on node 0) silently takes the other node's pages (measured 2.2 GB local / 12.7 GB remote, the pool + // then reads across UPI); bound, the kernel reclaims the node's own cache instead + unsigned long mask[2] = {0, 0}; + mask[node / 64] = 1UL << (node % 64); + if (syscall(SYS_mbind, p, bytes, 2 /* MPOL_BIND */, mask, 128, 0) != 0) { + static bool said = false; + if (!said) std::fprintf(stderr, "cpu experts: mbind to node %d failed (%s), placement by first touch only\n", node, + std::strerror(errno)); + said = true; + } + const std::vector cores = node_cores(node); + // first touch from threads pinned on the node: the kernel places each page (2 MiB with THP) there + const int nt = std::max(1, std::min(8, (int) cores.size())); + std::vector th; + for (int t = 0; t < nt; ++t) + th.emplace_back([&, t] { + if (!cores.empty()) pin(cores[t % cores.size()]); + const size_t a = bytes / nt * t, b = t == nt - 1 ? bytes : bytes / nt * (t + 1); + for (size_t i = a & ~(size_t) 4095; i < b; i += 4096) static_cast(p)[i] = 0; + }); + for (auto& x : th) x.join(); + return p; +} +void node_free(void* p, size_t bytes) { if (p) munmap(p, bytes); } + +const char* isa() { + __builtin_cpu_init(); + if (__builtin_cpu_supports("avx512f") && __builtin_cpu_supports("avx512bw") && __builtin_cpu_supports("avx512vl")) + return "avx512"; + if (__builtin_cpu_supports("avx2") && __builtin_cpu_supports("fma") && __builtin_cpu_supports("f16c")) return "avx2"; + return nullptr; +} + +void start(const Setup& s) { + S = s; + for (int i = 0; i < 256; ++i) { + E4H[i] = 0.5f * e4m3_decode(i); + MXS[i] = std::exp2f((float) i - 119.0f); + } + const char* k = isa(); + const bool avx2_only = std::getenv("INK2_CPU_AVX2") != nullptr; + g_isa = k && std::string(k) == "avx512" && !avx2_only ? 5 : 2; + g_vnni = g_isa == 5 && __builtin_cpu_supports("avx512vnni"); + g_C = g_vnni ? 64 : 32; + const char* act = std::getenv("INK2_CPU_ACT"); + g_q8 = act && std::string(act) == "int8" && S.h % 64 == 0 && S.ff % 64 == 0 && S.h <= BELL_H && S.ff <= FFX; + g_trace = std::getenv("INK2_CPU_TRACE") != nullptr; + if (const char* e = std::getenv("INK2_CPU_OPT")) g_opt = std::atoi(e); + const int nn = nodes(); + g_stop = false; + for (int n = 0; n < nn; ++n) { + // the node's control block (gen, barrier, job list: polled by all its threads) on its own node: from the main + // thread's heap it could sit across the inter-socket link, every barrier then a remote round trip + Node* N = new (node_alloc(sizeof(Node), n)) Node; + N->id = n; + std::vector cores = node_cores(n); + // node 0 keeps its first core for the engine's own thread (graph launches, the serve loop) + if (n == 0 && cores.size() > 1) { + if (g_opt & 16) { + // ... and the caller is put there (both hyperthreads): left to the scheduler it sat on the second + // hyperthread of a pool core (seen: cpu 78, pool thread 6 of node 1), whose thread then ran at half + // speed and held every barrier of its node ~30 us + cpu_set_t set; + CPU_ZERO(&set); + for (int c : parse_list(read_line("/sys/devices/system/cpu/cpu" + std::to_string(cores[0]) + "/topology/thread_siblings_list"))) + CPU_SET(c, &set); + sched_setaffinity(0, sizeof set, &set); // CBA: for good: threads the caller starts later inherit it + } + cores.erase(cores.begin()); + } + if ((int) cores.size() > S.threads) cores.resize(S.threads); + N->cpus = cores; + N->bar.n = (int) cores.size(); + auto alloc = [&](size_t bytes) { return node_alloc(bytes, n); }; + N->x = (float*) alloc((size_t) BELL_H * 4); + N->xq = (int8_t*) alloc(BELL_H); + N->xd = (float*) alloc((size_t) BELL_H / 16 * 4); + N->gu = (float*) alloc((size_t) K8 * 2 * FFX * 4); + N->hh = (float*) alloc((size_t) K8 * FFX * 4); + N->hq = (int8_t*) alloc((size_t) K8 * FFX); + N->hd = (float*) alloc((size_t) K8 * FFX / 16 * 4); + g_nodes.push_back(N); + } + g_ready = 0; + int total = 0; + for (Node* N : g_nodes) { + N->th.emplace_back(master, N); + for (int t = 1; t < (int) N->cpus.size(); ++t) N->th.emplace_back(worker, N, t); + total += (int) N->cpus.size(); + } + while (g_ready.load() < total) std::this_thread::yield(); + std::fprintf(stderr, "cpu experts: %s, NVFP4 activations %s, %d node(s)%s, threads per node:", + g_isa == 5 ? "avx512" : "avx2", g_q8 ? (g_vnni ? "int8 (VNNI)" : "int8") : "fp32", nn, + numa_off() ? " (NUMA placement off: STRATA_NUMA_POOL=0)" : ""); + for (Node* N : g_nodes) std::fprintf(stderr, " %zu", N->cpus.size()); + std::fprintf(stderr, "\n"); +} + +void stop() { + g_stop = true; + for (Node* N : g_nodes) { + for (auto& t : N->th) t.join(); + N->~Node(); // CBA: the node buffers stay mapped until exit + node_free(N, sizeof(Node)); + } + g_nodes.clear(); +} + +} // namespace ink2cpu +#endif diff --git a/engine/src/inkling2/ink2_cpu.hpp b/engine/src/inkling2/ink2_cpu.hpp new file mode 100644 index 00000000000..55040aa7b56 --- /dev/null +++ b/engine/src/inkling2/ink2_cpu.hpp @@ -0,0 +1,66 @@ +// src/inkling2/ink2_cpu.hpp - Inkling-2's cold experts on the CPU (strata-ink2 --cpu-threads N). +// +// The decode graph hands the experts of a layer visit that are not in VRAM to the CPU through one doorbell per node +// (InkBell, in that node's memory, registered mapped): the GPU writes the visit's input x, the jobs and a sequence +// number into each; one pool of pinned threads per NUMA node computes the jobs whose expert lives on that node +// (gate_up, softcapped SwiGLU, down: the same math as the GPU kernels; fp32 activations, int8 opt-in) and writes each +// expert's output row and its ack into its own doorbell; the graph waits for both acks, then the MoE tail weights all +// eight outputs as usual. +// A --spec verify block (8 tokens per layer visit) rings the same doorbells through `vring`: the block's inputs vx, one +// job per (token, expert) not in VRAM, in token order, outputs vy per job. The pools run it one token at a time, a +// decode visit each (the same kernels, so the same numbers as a decode visit of that token). +// +// Experts live in host memory placed per node (ink2cpu::node_alloc), each expert whole on one node, and so do the +// doorbells and the pools' buffers: a node's threads only touch local memory. On a two-socket box the inter-socket +// link is the slow path; only the GPU's traffic (doorbells, expert copies) crosses it. STRATA_NUMA_POOL=0 turns the +// placement off: one pool over all cores, one doorbell, expert memory unplaced (--cpu-threads is then the total). +#pragma once +#include +#include + +namespace ink2cpu { + +constexpr int BELL_H = 2304, BELL_K = 8, BELL_M = 8, BELL_J = BELL_M * BELL_K; // M: tokens of a verify block +struct InkBell { // one per node in its memory, registered mapped; GPU writes ring/job/x, the node's pool y/ack + volatile unsigned ring; // sequence number of the last visit with CPU jobs + volatile unsigned vring; // the same for verify block visits (one sequence for both; the fields after y) + unsigned pad0[14]; + volatile unsigned ack[2]; // [node]: the last sequence number done (written in that node's bell) + volatile float us_job; // the pool's time per job, us (moving average; the GPU's PCIe share reads it) + unsigned pad1[13]; + int layer, n; // the visit's layer, number of jobs + int k[BELL_K], e[BELL_K]; // job j: top-k slot k[j], expert e[j] + unsigned pad2[14]; + float x[BELL_H]; // the visit's MoE input + float y[BELL_K][BELL_H]; // job j's expert output (factor applied, not the router weight), in the bell + // of its expert's node + // a verify block's visit (vring): jobs in token order + int vlayer, vn; // the visit's layer, number of jobs + int vt[BELL_J], ve[BELL_J]; // job j: token (row of vx) vt[j], expert ve[j] + unsigned pad3[14]; + float vx[BELL_M][BELL_H]; // the block's MoE inputs + float vy[BELL_J][BELL_H]; // job j's expert output, in the bell of its expert's node +}; + +struct Setup { + int nl = 0, ne = 0, mx_first = 0, h = 0, ff = 0; + const uint8_t* const* ex = nullptr; // [nl * ne] host address of expert (l, e)'s slot + const uint8_t* home = nullptr; // [nl * ne] its node + const float* f13 = nullptr; // [nl * ne] NVFP4 per-expert factors (layers < mx_first) + const float* f2 = nullptr; + size_t nv_partA = 0, mx_partA = 0; // offset of part B (w2 | s2) in a slot + float gate_cap = 0, up_cap = 0; + InkBell* bell[2] = {}; // [node] + int threads = 0; // per node +}; + +int nodes(); // NUMA nodes with CPUs (1 when there is no NUMA information) +// bytes of anonymous memory on `node`, its pages touched by a thread pinned there (so they are placed there) +void* node_alloc(size_t bytes, int node); +void node_free(void* p, size_t bytes); +const char* isa(); // "avx512" | "avx2" | nullptr (no usable kernel: AVX2 + FMA + F16C needed) + +void start(const Setup& s); // starts the pools; they spin on the bell (and nap when it is idle) +void stop(); + +} // namespace ink2cpu diff --git a/engine/src/inkling2/ink2_engine.cu b/engine/src/inkling2/ink2_engine.cu new file mode 100644 index 00000000000..8265c0b4f2c --- /dev/null +++ b/engine/src/inkling2/ink2_engine.cu @@ -0,0 +1,5981 @@ +// src/inkling2/ink2_engine.cu - strata-ink2: Inkling-2-Mini's engine path (NEW-MODELS-PLAN.md T2), step 1: the whole +// forward pass on the GPU, one token at a time (the prompt too), checked against strata-ink2ref (T1) and the fp32 +// transformers oracle (terminal/tools/inkling2/). +// +// * weights resident in their checkpoint form, as in strata-ink2ref: BF16 dense matrices, NVFP4 experts (layers 0-19: +// e2m1 pairs, an e4m3 scale per 16, an fp32 factor amax/denominator per expert), MXFP8 experts (layers 20-23: e4m3, +// a ue8m0 exponent per 32). Every matrix-vector product reads them as they are, fp32 activations, fp32 sums +// ("W exact, A16"): nothing is requantized; +// * the embedding table stays in host RAM (one row per token); +// * attention: split over 256-position chunks per head with a log-sum-exp merge that adds the per-token sink logit; +// the relative bias table [24][1024] built per token; KV in fp32 (CBA: fp32 KV, --ctx 8192 by default - int8 KV is +// T2 step 3); sliding layers keep a 1024-position ring, full layers the whole context; +// * convolutions with a 3-row history per layer application (48 applications: each loop pass has its own state). +// +// * one CUDA graph per token (--graph 1, the default): positions on the device, built at the first token. Build with +// --default-stream per-thread (the graph is captured on cudaStreamPerThread). +// +// * the prompt in chunks of --chunk tokens (default 512; 0 = one token at a time through the decode graph): cuBLAS +// SGEMM in full FP32 for the dense products (fp32 copy of each BF16 matrix made per use), a grouped expert product +// decoding NVFP4 / MXFP8 on the fly, tiled fp32 attention. Link -lcublas. +// +// Modes: --tokens IDS | --tokens-file F [--n N] [--dump-logits F] [--ctx N] [--graph 0|1] [--chunk N]; prints prompt / +// decode speed. +#include "../image/vae/safetensors_lite.hpp" +#include "ink2_cpu.hpp" +#include "ink2_iq_tables.h" +#include "ink2_image.hpp" + +#if !defined(STRATA_USE_HIP) +#include +#endif +#include +#include +#if defined(STRATA_USE_HIP) +#include "ink2_wmma_hip.cuh" +#else +#include +#endif +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using vec = std::vector; +#if defined(STRATA_USE_HIP) +namespace wmma = ink2_wmma; +#else +namespace wmma = nvcuda::wmma; +#endif +using strata::image::StFile; +using strata::image::StTensor; + +constexpr int H = 2304, NL = 24, NQ = 24, NKV = 8, HD = 128, NREP = NQ / NKV, DREL = 16, EXTENT = 1024, WINDOW = 1024; +constexpr int QD = NQ * HD, KVD = NKV * HD; // 3072, 1024 +constexpr int NE = 128, TOPK = 8, FF = 1152, KC = 4, GATE_RANK = 64, VOCAB = 200058, VOCAB_ROWS = 201024; +constexpr int LOOP_BEGIN = 6, LOOP_END = 18, NLOOP = LOOP_END - LOOP_BEGIN, PASSES = 3, BLOCK = 6; +constexpr int NCALLS = NL + (PASSES - 1) * NLOOP; +constexpr int MXFP8_FIRST = 20; +constexpr float EPS = 1e-6f, QK_CLIP = 22.627416997969522f, REL_CLIP = 8.0f, LOG_ALPHA = 0.1f, LOG_FLOOR = 8192.0f; +constexpr float GATE_CAP = 4.0f, UP_CAP = 25.0f, ROUTE_SCALE = 8.0f, LOGIT_CAP = 30.0f; +constexpr int CHUNK = 256; // attention positions per block +int PF_RING_EXTRA = 512; // = the prefill chunk: a chunk's keys must not evict the window of its first query +constexpr int OFF_GATE = QD, OFF_REL = 2 * QD, OFF_SINK = OFF_REL + NQ * DREL, OFF_K = OFF_SINK + NQ; // in proj + +bool full_layer(int L) { return L % BLOCK == BLOCK - 1; } + +#define CK(x) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { \ + std::fprintf(stderr, "CUDA %s at %s:%d\n", cudaGetErrorString(e_), __FILE__, __LINE__); std::exit(1); } } while (0) + +// --------------------------------------------------------------------------------------------------------------------- +// Kernels + +__device__ __forceinline__ float bf16lo(uint32_t u) { return __uint_as_float(u << 16); } +__device__ __forceinline__ float bf16hi(uint32_t u) { return __uint_as_float(u & 0xffff0000u); } + +__device__ __forceinline__ float e4m3_decode(uint32_t v) { + const int e = (v >> 3) & 15, m = v & 7; + float r = e == 0 ? (float) m * 0.001953125f : ldexpf(1.0f + (float) m * 0.125f, e - 7); + if (e == 15 && m == 7) r = __int_as_float(0x7fc00000); + return (v & 0x80) ? -r : r; +} + +__device__ __forceinline__ float warp_sum(float a) { + for (int o = 16; o; o >>= 1) a += __shfl_xor_sync(0xffffffffu, a, o); + return a; +} +__device__ __forceinline__ float warp_max(float a) { + for (int o = 16; o; o >>= 1) a = fmaxf(a, __shfl_xor_sync(0xffffffffu, a, o)); + return a; +} + +// sum over the block (blockDim.x a multiple of 32, <= 1024); every thread gets the result +__device__ float block_sum(float v) { + __shared__ float red[32]; + v = warp_sum(v); + const int w = threadIdx.x / 32, l = threadIdx.x & 31, nw = blockDim.x / 32; + __syncthreads(); + if (!l) red[w] = v; + __syncthreads(); + float t = l < nw ? red[l] : 0.0f; + return warp_sum(t); +} +__device__ float block_max(float v) { + __shared__ float red[32]; + v = warp_max(v); + const int w = threadIdx.x / 32, l = threadIdx.x & 31, nw = blockDim.x / 32; + __syncthreads(); + if (!l) red[w] = v; + __syncthreads(); + float t = l < nw ? red[l] : -INFINITY; + return warp_max(t); +} + +// y[row] = W[row] . x (BF16 W [N, K], K % 8 == 0), one warp per row, x staged in shared memory and read as float4 +// (lane stride 32 B: 2-way bank conflicts at most) +// R rows per warp: the staged x serves 8R rows per block, R independent loads in flight per lane. Each row's sum is +// the same sequence of operations whatever R (bit-identical results). +template +__device__ __forceinline__ void gemv_bf16_dot(const uint16_t* __restrict__ W, const float* xs, float* __restrict__ y, + int N, int K, int row0) { + const int lane = threadIdx.x & 31; + const uint4* w[R]; +#pragma unroll + for (int r = 0; r < R; ++r) w[r] = reinterpret_cast(W + (size_t) min(row0 + r, N - 1) * K); + const float4* x4 = reinterpret_cast(xs); + float acc[R]; +#pragma unroll + for (int r = 0; r < R; ++r) acc[r] = 0.0f; +#pragma unroll 2 + for (int i = lane; i < K / 8; i += 32) { + uint4 v[R]; +#pragma unroll + for (int r = 0; r < R; ++r) v[r] = __ldg(w[r] + i); + const float4 a = x4[2 * i], b = x4[2 * i + 1]; +#pragma unroll + for (int r = 0; r < R; ++r) + acc[r] += bf16lo(v[r].x) * a.x + bf16hi(v[r].x) * a.y + bf16lo(v[r].y) * a.z + bf16hi(v[r].y) * a.w + + bf16lo(v[r].z) * b.x + bf16hi(v[r].z) * b.y + bf16lo(v[r].w) * b.z + bf16hi(v[r].w) * b.w; + } +#pragma unroll + for (int r = 0; r < R; ++r) { + const float t = warp_sum(acc[r]); + if (!lane && row0 + r < N) y[row0 + r] = t; + } +} +template +__device__ __forceinline__ void gemv_bf16_rows(const uint16_t* __restrict__ W, const float* __restrict__ x, + float* __restrict__ y, int N, int K) { + extern __shared__ float xs[]; + for (int i = threadIdx.x; i < K; i += blockDim.x) xs[i] = x[i]; + __syncthreads(); + const int row0 = (blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32) * R; + if (row0 >= N) return; + gemv_bf16_dot(W, xs, y, N, K, row0); +} +template +__global__ void k_gemv_bf16(const uint16_t* __restrict__ W, const float* __restrict__ x, float* __restrict__ y, int N, + int K) { + gemv_bf16_rows(W, x, y, N, K); +} +// q / k / v projections with three inputs in one launch: rows [0, b1) . xq, [b1, b2) . xk, [b2, N) . xv (R divides b1 and +// b2: a warp's rows share an input). A block stages only the inputs its rows touch (smem 3K). +template +__global__ void k_gemv_bf16_qkv(const uint16_t* __restrict__ W, const float* __restrict__ xq, const float* __restrict__ xk, + const float* __restrict__ xv, int b1, int b2, float* __restrict__ y, int N, int K) { + extern __shared__ float xs[]; + const int rb = blockIdx.x * (blockDim.x / 32) * R, re = min(rb + (int) (blockDim.x / 32) * R, N); + if (rb < b1) for (int i = threadIdx.x; i < K; i += blockDim.x) xs[i] = xq[i]; + if (rb < b2 && re > b1) for (int i = threadIdx.x; i < K; i += blockDim.x) xs[K + i] = xk[i]; + if (re > b2) for (int i = threadIdx.x; i < K; i += blockDim.x) xs[2 * K + i] = xv[i]; + __syncthreads(); + const int row0 = (blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32) * R; + if (row0 >= N) return; + gemv_bf16_dot(W, xs + (row0 < b1 ? 0 : row0 < b2 ? K : 2 * K), y, N, K, row0); +} + +// Up to 3 independent message gates per launch (gate j = blockIdx.y, or blockIdx.x for the one-block kernels): the +// q / k / v gates of a layer application are independent, 4 launches instead of 12; same arithmetic per gate. +struct GateArgs { + const uint16_t* down[3]; + const uint16_t* fg[3]; + const float* x[3]; + const float* m[3]; + float* y[3]; + const float* nw[3]; + float* yn[3]; +}; +// fg GEMV of gate j: gfg[j] [2H] = fg_j [2H, GATE_RANK] . gdown[j] +template +__global__ void k_gemv_bf16_gate(GateArgs a, const float* __restrict__ gdown, float* __restrict__ gfg, int N, int K) { + const int j = blockIdx.y; + gemv_bf16_rows(a.fg[j], gdown + (size_t) j * GATE_RANK, gfg + (size_t) j * N, N, K); +} + +// e2m1 pair (one byte: low nibble first) -> fp32 values * 2^-14: the nibble's sign/exponent/mantissa bits placed +// in an fp16 (exact, subnormal 0.5 included); the 2^14 goes into the block scale +__device__ __forceinline__ float2 e2m1x2(uint32_t byte) { + const uint32_t a = (byte & 0xFu) | ((byte & 0xF0u) << 12); + const uint32_t h = ((a & 0x00080008u) << 12) | ((a & 0x00070007u) << 9); + return __half22float2(*reinterpret_cast(&h)); +} +// two e4m3 bytes (in bits 0-7 and 16-23) -> fp32 values * 2^-8 (fp16 placement, exact incl. subnormals) +__device__ __forceinline__ float2 e4m3x2(uint32_t a) { + const uint32_t h = ((a & 0x00800080u) << 8) | ((a & 0x007F007Fu) << 7); + return __half22float2(*reinterpret_cast(&h)); +} + +// SoftcappedSwiGLU of one (gate, up) pair (row 2j gate j, 2j+1 up j of the gu buffer) +__device__ __forceinline__ float swiglu1(float g, float u) { + return (tanhf(g / GATE_CAP) * GATE_CAP) * (1.0f / (1.0f + expf(-g))) * (tanhf(u / UP_CAP) * UP_CAP); +} +// The TOPK selected experts at once (blockIdx.y = k): y[k][row] = W_e[row] . x_k, e = ids[k]. +// NVFP4: lane reads 4 bytes = 8 columns (half a 16-column block, its e4m3 scale s[i/2]); the sum times factors[e]. +// x is read from global memory through L1 (K x 4 B per expert, shared by the SM's warps): no staging copy, only the +// scale table in shared memory. Memory-latency bound (ncu: DRAM 67 %, SM 55 %, long-scoreboard stalls); 3090 bench of +// the staged version vs this one: gate_up 41 -> 38 us, down 33 -> 22 us (with ACT below). +// ACT (gate_up, R even): a warp holds rows 2j (gate j) and 2j + 1 (up j) and also writes act[k][j], their SwiGLU, the +// down GEMV's input: computed once per expert instead of once per down block. Same values, same operations as before. +template +__global__ void k_gemv_nvfp4_sel(const uint8_t* const* __restrict__ tab, + const float* __restrict__ factors, const int* __restrict__ ids, + const float* __restrict__ x, int x_stride, float* __restrict__ y, int N, int K, + float* __restrict__ act = nullptr) { + static_assert(!ACT || R % 2 == 0, "ACT needs the gate / up pair in one warp"); + __shared__ float e4[256]; // scale table, * 2^14 + for (int i = threadIdx.x; i < 256; i += blockDim.x) e4[i] = e4m3_decode(i) * 16384.0f; + __syncthreads(); + const int row0 = (blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32) * R, lane = threadIdx.x & 31; + if (row0 >= N) return; + const int e = ids[blockIdx.y]; + const uint8_t* W = tab[e]; + if (!W) return; // computed on the CPU (--cpu-threads): k_cpu_wait writes its output + const uint8_t* S = W + (size_t) N * (K / 2); + const uint32_t* w[R]; + const uint8_t* s[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { + const size_t row = min(row0 + r, N - 1); + w[r] = reinterpret_cast(W + row * (K / 2)); + s[r] = S + row * (K / 16); + } + const float4* x4 = reinterpret_cast(x + (size_t) blockIdx.y * x_stride); + float acc[R]; +#pragma unroll + for (int r = 0; r < R; ++r) acc[r] = 0.0f; +#pragma unroll 2 + for (int i = lane; i < K / 8; i += 32) { + uint32_t v[R]; + uint8_t sc[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { v[r] = __ldg(w[r] + i); sc[r] = __ldg(s[r] + (i >> 1)); } + const float4 a = __ldg(x4 + 2 * i), b = __ldg(x4 + 2 * i + 1); +#pragma unroll + for (int r = 0; r < R; ++r) { + const float2 p0 = e2m1x2(v[r] & 0xff), p1 = e2m1x2((v[r] >> 8) & 0xff), p2 = e2m1x2((v[r] >> 16) & 0xff), + p3 = e2m1x2(v[r] >> 24); + const float part = p0.x * a.x + p0.y * a.y + p1.x * a.z + p1.y * a.w + p2.x * b.x + p2.y * b.y + + p3.x * b.z + p3.y * b.w; + acc[r] += part * e4[sc[r]]; + } + } + float t[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { + t[r] = warp_sum(acc[r]) * factors[e]; + if (!lane && row0 + r < N) y[(size_t) blockIdx.y * N + row0 + r] = t[r]; + } + if (ACT && !lane) +#pragma unroll + for (int r = 0; r < R; r += 2) + if (row0 + r + 1 < N) act[(size_t) blockIdx.y * (N / 2) + (row0 + r) / 2] = swiglu1(t[r], t[r + 1]); +} + +// MXFP8: lane reads 4 bytes = 4 columns; the ue8m0 exponent per 32 columns (8 words): 2^(s - 127) * 2^8 +template +__global__ void k_gemv_mxfp8_sel(const uint8_t* const* __restrict__ tab, const int* __restrict__ ids, const float* __restrict__ x, int x_stride, + float* __restrict__ y, int N, int K) { + extern __shared__ float sm[]; + float* xs = sm; + const float* xk = x + (size_t) blockIdx.y * x_stride; + for (int i = threadIdx.x; i < K; i += blockDim.x) xs[i] = SWI ? swiglu1(xk[2 * i], xk[2 * i + 1]) : xk[i]; + __syncthreads(); + const int row0 = (blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32) * R, lane = threadIdx.x & 31; + if (row0 >= N) return; + const int e = ids[blockIdx.y]; + const uint8_t* W = tab[e]; + if (!W) return; // computed on the CPU (--cpu-threads) + const uint8_t* S = W + (size_t) N * K; + const uint32_t* w[R]; + const uint8_t* s[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { + const size_t row = min(row0 + r, N - 1); + w[r] = reinterpret_cast(W + row * K); + s[r] = S + row * (K / 32); + } + const float4* x4 = reinterpret_cast(xs); + float acc[R]; +#pragma unroll + for (int r = 0; r < R; ++r) acc[r] = 0.0f; +#pragma unroll 2 + for (int i = lane; i < K / 4; i += 32) { + uint32_t v[R]; + uint8_t sc[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { v[r] = __ldg(w[r] + i); sc[r] = __ldg(s[r] + (i >> 3)); } + const float4 a = x4[i]; +#pragma unroll + for (int r = 0; r < R; ++r) { + const float2 p01 = e4m3x2((v[r] & 0xffu) | ((v[r] & 0xff00u) << 8)); + const float2 p23 = e4m3x2(((v[r] >> 16) & 0xffu) | ((v[r] & 0xff000000u) >> 8)); + const float part = p01.x * a.x + p01.y * a.y + p23.x * a.z + p23.y * a.w; + acc[r] += part * exp2f((float) sc[r] - 119.0f); // 2^(s-127) * 2^8 + } + } +#pragma unroll + for (int r = 0; r < R; ++r) { + const float t = warp_sum(acc[r]); + if (!lane && row0 + r < N) y[(size_t) blockIdx.y * N + row0 + r] = t; + } +} + +// --------------------------------------------------------------------------------------------------------------------- +// GGUF weights (--model FILE.gguf, llama.cpp's merged inkling2_loop layout): experts gate_up IQ3_S / down IQ4_NL (or +// Q8_0), dense matrices Q8_0 repacked at load into int8 codes [N][K] + fp16 scales [N][K / 32] (lossless). +enum GgType : int { GG_F32 = 0, GG_F16 = 1, GG_Q8_0 = 8, GG_IQ4_NL = 20, GG_IQ3_S = 21, GG_BF16 = 30 }; +__device__ uint32_t d_iq3s_grid[512]; +__constant__ int8_t c_iq4nl[16]; + +// 8 weights of one row (row pointer rp, ggml blocks) at columns [kc, kc + 8), kc % 8 == 0; the tables in shared memory +template +__device__ __forceinline__ void gg_ld8(const uint8_t* __restrict__ rp, int kc, float* w, const uint32_t* grid, + const int8_t* kv) { + if constexpr (T == GG_IQ3_S) { // 110 B per 256: d, qs[64], qh[8], signs[32], scales[4] + const uint8_t* b = rp + (size_t) (kc >> 8) * 110; + const int ib = (kc & 255) >> 5, il = (kc & 31) >> 3; + const float d = __half2float(*reinterpret_cast(b)); + const float db = d * (float) (1 + 2 * ((b[106 + (ib >> 1)] >> (4 * (ib & 1))) & 15)); + const uint32_t qh = b[66 + ib], sg = b[74 + 4 * ib + il]; + const uint32_t g1 = grid[b[2 + 8 * ib + 2 * il] | ((qh << (8 - 2 * il)) & 256)]; + const uint32_t g2 = grid[b[3 + 8 * ib + 2 * il] | ((qh << (7 - 2 * il)) & 256)]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + w[j] = db * (float) ((g1 >> (8 * j)) & 255) * (((sg >> j) & 1) ? -1.0f : 1.0f); + w[4 + j] = db * (float) ((g2 >> (8 * j)) & 255) * (((sg >> (4 + j)) & 1) ? -1.0f : 1.0f); + } + } else if constexpr (T == GG_IQ4_NL) { // 18 B per 32: d, qs[16] (low nibbles values 0..15, high 16..31) + const uint8_t* b = rp + (size_t) (kc >> 5) * 18; + const int o = kc & 31; + const float d = __half2float(*reinterpret_cast(b)); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const uint32_t by = b[2 + ((o + j) & 15)]; + w[j] = d * (float) kv[o < 16 ? by & 15u : by >> 4]; + } + } else { // Q8_0: 34 B per 32: d, qs[32] + const uint8_t* b = rp + (size_t) (kc >> 5) * 34; + const int o = kc & 31; + const float d = __half2float(*reinterpret_cast(b)); +#pragma unroll + for (int j = 0; j < 8; ++j) w[j] = d * (float) (int8_t) b[2 + o + j]; + } +} +__device__ __forceinline__ void gg_tables(uint32_t* grid, int8_t* kv) { + for (int i = threadIdx.x; i < 512; i += blockDim.x) grid[i] = d_iq3s_grid[i]; + if (threadIdx.x < 16) kv[threadIdx.x] = c_iq4nl[threadIdx.x]; +} +// w13 rows of the GGUF are [gate 0..FF) [up FF..2FF); the engine's gu rows interleave them (2j gate j, 2j+1 up j) +__device__ __forceinline__ int gg_perm(int n, int N) { return (n & 1) ? N / 2 + (n >> 1) : n >> 1; } + +// selected experts, GGUF formats: y[k][o] = W_e[row(o)] . x_k (row(o) = gg_perm(o) for PERM); W_e = tab[e] (part A: +// the gate_up rows, part B: the down rows of the expert's slot); rb = bytes per row +template +__global__ void k_gemv_gg_sel(const uint8_t* const* __restrict__ tab, size_t rb, const int* __restrict__ ids, + const float* __restrict__ x, int x_stride, float* __restrict__ y, int N, int K) { + extern __shared__ float sm[]; + float* xs = sm; + uint32_t* grid = reinterpret_cast(sm + K); + int8_t* kv = reinterpret_cast(grid + 512); + const float* xk = x + (size_t) blockIdx.y * x_stride; + for (int i = threadIdx.x; i < K; i += blockDim.x) xs[i] = SWI ? swiglu1(xk[2 * i], xk[2 * i + 1]) : xk[i]; + gg_tables(grid, kv); + __syncthreads(); + const int row0 = (blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32) * R, lane = threadIdx.x & 31; + if (row0 >= N) return; + const uint8_t* W = tab[ids[blockIdx.y]]; + const uint8_t* rp[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { + const int o = min(row0 + r, N - 1); + rp[r] = W + (size_t) (PERM ? gg_perm(o, N) : o) * rb; + } + float acc[R]; +#pragma unroll + for (int r = 0; r < R; ++r) acc[r] = 0.0f; + for (int kc = lane * 8; kc < K; kc += 256) { + const float4 a = *reinterpret_cast(xs + kc), b = *reinterpret_cast(xs + kc + 4); +#pragma unroll + for (int r = 0; r < R; ++r) { + float w[8]; + gg_ld8(rp[r], kc, w, grid, kv); + acc[r] += w[0] * a.x + w[1] * a.y + w[2] * a.z + w[3] * a.w + w[4] * b.x + w[5] * b.y + w[6] * b.z + w[7] * b.w; + } + } +#pragma unroll + for (int r = 0; r < R; ++r) { + const float t = warp_sum(acc[r]); + if (!lane && row0 + r < N) y[(size_t) blockIdx.y * N + row0 + r] = t; + } +} + +__constant__ int c_q8w; // INK2_Q8_WIDE (default: 1 before sm_80): 16-byte loads in the dense Q8 GEMV (0: 8-byte) +#define g_q8_wide (c_q8w) +// dense Q8_0 (repacked): y[row] = W[row] . x, as gemv_bf16_dot (one warp per R rows, x staged) +template +__device__ __forceinline__ void gemv_q8_dot(const int8_t* __restrict__ Wq, const __half* __restrict__ Ws, const float* xs, + float* __restrict__ y, int N, int K, int row0) { + const int lane = threadIdx.x & 31; + const uint2* w[R]; + const __half* sc[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { + const size_t row = (size_t) min(row0 + r, N - 1); + w[r] = reinterpret_cast(Wq + row * K); + sc[r] = Ws + row * (K / 32); + } + const float4* x4 = reinterpret_cast(xs); + float acc[R]; +#pragma unroll + for (int r = 0; r < R; ++r) acc[r] = 0.0f; + if (g_q8_wide) { // 16 codes (one 16-byte load) per lane step, inside one 32-value scale block + const uint4* w16[R]; +#pragma unroll + for (int r = 0; r < R; ++r) w16[r] = reinterpret_cast(w[r]); +#pragma unroll 2 + for (int i = lane; i < K / 16; i += 32) { + uint4 v[R]; + float f[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { v[r] = __ldg(w16[r] + i); f[r] = __half2float(sc[r][i >> 1]); } + const float4 a = x4[4 * i], b = x4[4 * i + 1], c = x4[4 * i + 2], d = x4[4 * i + 3]; +#pragma unroll + for (int r = 0; r < R; ++r) { + const char4 c0 = *reinterpret_cast(&v[r].x), c1 = *reinterpret_cast(&v[r].y); + const char4 c2 = *reinterpret_cast(&v[r].z), c3 = *reinterpret_cast(&v[r].w); + acc[r] += f[r] * (c0.x * a.x + c0.y * a.y + c0.z * a.z + c0.w * a.w + c1.x * b.x + c1.y * b.y + c1.z * b.z + + c1.w * b.w + c2.x * c.x + c2.y * c.y + c2.z * c.z + c2.w * c.w + c3.x * d.x + c3.y * d.y + + c3.z * d.z + c3.w * d.w); + } + } + } else +#pragma unroll 2 + for (int i = lane; i < K / 8; i += 32) { + uint2 v[R]; + float f[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { v[r] = __ldg(w[r] + i); f[r] = __half2float(sc[r][i >> 2]); } + const float4 a = x4[2 * i], b = x4[2 * i + 1]; +#pragma unroll + for (int r = 0; r < R; ++r) { + const char4 c0 = *reinterpret_cast(&v[r].x), c1 = *reinterpret_cast(&v[r].y); + acc[r] += f[r] * (c0.x * a.x + c0.y * a.y + c0.z * a.z + c0.w * a.w + c1.x * b.x + c1.y * b.y + c1.z * b.z + + c1.w * b.w); + } + } +#pragma unroll + for (int r = 0; r < R; ++r) { + const float t = warp_sum(acc[r]); + if (!lane && row0 + r < N) y[row0 + r] = t; + } +} +template +__global__ void k_gemv_q8(const int8_t* __restrict__ Wq, const __half* __restrict__ Ws, const float* __restrict__ x, + float* __restrict__ y, int N, int K) { + extern __shared__ float xs[]; + for (int i = threadIdx.x; i < K; i += blockDim.x) xs[i] = x[i]; + __syncthreads(); + const int row0 = (blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32) * R; + if (row0 >= N) return; + gemv_q8_dot(Wq, Ws, xs, y, N, K, row0); +} +template +__global__ void k_gemv_q8_qkv(const int8_t* __restrict__ Wq, const __half* __restrict__ Ws, const float* __restrict__ xq, + const float* __restrict__ xk, const float* __restrict__ xv, int b1, int b2, + float* __restrict__ y, int N, int K) { + extern __shared__ float xs[]; + const int rb = blockIdx.x * (blockDim.x / 32) * R, re = min(rb + (int) (blockDim.x / 32) * R, N); + if (rb < b1) for (int i = threadIdx.x; i < K; i += blockDim.x) xs[i] = xq[i]; + if (rb < b2 && re > b1) for (int i = threadIdx.x; i < K; i += blockDim.x) xs[K + i] = xk[i]; + if (re > b2) for (int i = threadIdx.x; i < K; i += blockDim.x) xs[2 * K + i] = xv[i]; + __syncthreads(); + const int row0 = (blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32) * R; + if (row0 >= N) return; + gemv_q8_dot(Wq, Ws, xs + (row0 < b1 ? 0 : row0 < b2 ? K : 2 * K), y, N, K, row0); +} +// Q8 rows -> fp32 / fp16 (prompt products through cuBLAS); n8 = elements / 8 +__global__ void kb_q8_to_f32(const int8_t* __restrict__ q, const __half* __restrict__ sc, float* __restrict__ dst, size_t n8) { + const size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n8) return; + const uint2 v = reinterpret_cast(q)[i]; + const float f = __half2float(sc[i >> 2]); + const char4 c0 = *reinterpret_cast(&v.x), c1 = *reinterpret_cast(&v.y); + float4* d = reinterpret_cast(dst + 8 * i); + d[0] = make_float4(c0.x * f, c0.y * f, c0.z * f, c0.w * f); + d[1] = make_float4(c1.x * f, c1.y * f, c1.z * f, c1.w * f); +} +__global__ void kb_q8_to_f16(const int8_t* __restrict__ q, const __half* __restrict__ sc, __half* __restrict__ dst, size_t n8) { + const size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n8) return; + const uint2 v = reinterpret_cast(q)[i]; + const float f = __half2float(sc[i >> 2]); + const char4 c0 = *reinterpret_cast(&v.x), c1 = *reinterpret_cast(&v.y); + __half2* d = reinterpret_cast<__half2*>(dst + 8 * i); + d[0] = __floats2half2_rn(c0.x * f, c0.y * f); d[1] = __floats2half2_rn(c0.z * f, c0.w * f); + d[2] = __floats2half2_rn(c1.x * f, c1.y * f); d[3] = __floats2half2_rn(c1.z * f, c1.w * f); +} + +// y = rms(x) (* w if w): one block +__global__ void k_rms(const float* __restrict__ x, const float* __restrict__ w, float* __restrict__ y, int n) { + x += (size_t) blockIdx.x * n; + y += (size_t) blockIdx.x * n; + float ss = 0.0f; + for (int i = threadIdx.x; i < n; i += blockDim.x) ss += x[i] * x[i]; + ss = block_sum(ss); + const float r = rsqrtf(ss / n + EPS); + for (int i = threadIdx.x; i < n; i += blockDim.x) y[i] = w ? w[i] * (x[i] * r) : x[i] * r; +} + +// attention residual: stack [S][H] (contiguous), NQ queries [NQ][H] -> out [NQ][H] = sum_j softmax_j(q . n_j / sqrt H) +// n_j, n_j = rms(stack_j) (unweighted); q . n_j = rinv_j * (q . stack_j). One block of 256 threads (9 columns each), +// S and NQ compile-time (registers only). With `outn`, also outn[k] = rms(out[k]) * nw[k] (nw[k] null: unweighted); +// `out` may then be null. +constexpr int AR_T = 256, AR_C = H / AR_T; +template +__global__ void k_attnres(const float* __restrict__ stack, size_t sstride, const float* __restrict__ queries, + float* __restrict__ out, const float* nw0, const float* nw1, const float* nw2, + float* __restrict__ outn) { + stack += (size_t) blockIdx.x * H; // a grid of T tokens: stack entry j of token t at stack + j * sstride + t * H + if (out) out += (size_t) blockIdx.x * NQ * H; + if (outn) outn += (size_t) blockIdx.x * NQ * H; + constexpr int NV = S + NQ * S; + __shared__ float red[AR_T / 32][NV + NQ]; + __shared__ float p[NQ][S], rinv[S], onorm[NQ]; + const int t = threadIdx.x, w = t / 32, l = t & 31; + float v[S][AR_C]; + float acc[NV]; +#pragma unroll + for (int i = 0; i < NV; ++i) acc[i] = 0.0f; +#pragma unroll + for (int c = 0; c < AR_C; ++c) { + const int i = c * AR_T + t; + float q[NQ]; +#pragma unroll + for (int k = 0; k < NQ; ++k) q[k] = queries[(size_t) k * H + i]; +#pragma unroll + for (int j = 0; j < S; ++j) { + v[j][c] = stack[j * sstride + i]; + acc[j] += v[j][c] * v[j][c]; +#pragma unroll + for (int k = 0; k < NQ; ++k) acc[S + k * S + j] += q[k] * v[j][c]; + } + } +#pragma unroll + for (int i = 0; i < NV; ++i) { + const float r = warp_sum(acc[i]); + if (!l) red[w][i] = r; + } + __syncthreads(); + if (t < NV) { + float r = 0.0f; +#pragma unroll + for (int k = 0; k < AR_T / 32; ++k) r += red[k][t]; + red[0][t] = r; + } + __syncthreads(); + if (t < S) rinv[t] = rsqrtf(red[0][t] / H + EPS); + __syncthreads(); + if (t < NQ) { + float lg[S], mx = -INFINITY, z = 0.0f; +#pragma unroll + for (int j = 0; j < S; ++j) { lg[j] = red[0][S + t * S + j] * rinv[j] * rsqrtf((float) H); mx = fmaxf(mx, lg[j]); } +#pragma unroll + for (int j = 0; j < S; ++j) { lg[j] = expf(lg[j] - mx); z += lg[j]; } +#pragma unroll + for (int j = 0; j < S; ++j) p[t][j] = lg[j] / z * rinv[j]; + } + __syncthreads(); + float o[NQ][AR_C], ss[NQ]; +#pragma unroll + for (int k = 0; k < NQ; ++k) { + ss[k] = 0.0f; +#pragma unroll + for (int c = 0; c < AR_C; ++c) { + float a = 0.0f; +#pragma unroll + for (int j = 0; j < S; ++j) a += p[k][j] * v[j][c]; + o[k][c] = a; + ss[k] += a * a; + if (out) out[(size_t) k * H + c * AR_T + t] = a; + } + } + if (!outn) return; +#pragma unroll + for (int k = 0; k < NQ; ++k) { + const float r = warp_sum(ss[k]); + if (!l) red[w][NV + k] = r; + } + __syncthreads(); + if (t < NQ) { + float r = 0.0f; +#pragma unroll + for (int k = 0; k < AR_T / 32; ++k) r += red[k][NV + t]; + onorm[t] = rsqrtf(r / H + EPS); + } + __syncthreads(); + const float* nw[3] = {nw0, nw1, nw2}; +#pragma unroll + for (int k = 0; k < NQ; ++k) { + const float* wk = k < 3 ? nw[k] : nullptr; +#pragma unroll + for (int c = 0; c < AR_C; ++c) { + const int i = c * AR_T + t; + outn[(size_t) k * H + i] = wk ? wk[i] * (o[k][c] * onorm[k]) : o[k][c] * onorm[k]; + } + } +} + +// rms of two vectors at once (blockIdx.x 0: x, 1: m), unweighted: gate j's [rms(x), rms(m)] into cat[j] [2H] +__global__ void k_rms2(GateArgs g, float* __restrict__ cat) { + const int j = blockIdx.y; + const float* a = blockIdx.x ? g.m[j] : g.x[j]; + float* b = cat + (size_t) (2 * j + blockIdx.x) * H; + float ss = 0.0f; + for (int i = threadIdx.x; i < H; i += blockDim.x) ss += a[i] * a[i]; + ss = block_sum(ss); + const float r = rsqrtf(ss / H + EPS); + for (int i = threadIdx.x; i < H; i += blockDim.x) b[i] = a[i] * r; +} + +// small-N matrix-vector product: one block per row (BF16 W [N, K]), for N too small to fill the GPU warp-per-row +__device__ __forceinline__ float rowblock_dot(const uint16_t* __restrict__ W, const float* __restrict__ x, int K) { + const uint4* w = reinterpret_cast(W + (size_t) blockIdx.x * K); + const float4* x4 = reinterpret_cast(x); + float acc = 0.0f; + for (int i = threadIdx.x; i < K / 8; i += blockDim.x) { + const uint4 v = __ldg(w + i); + const float4 a = __ldg(x4 + 2 * i), b = __ldg(x4 + 2 * i + 1); + acc += bf16lo(v.x) * a.x + bf16hi(v.x) * a.y + bf16lo(v.y) * a.z + bf16hi(v.y) * a.w + + bf16lo(v.z) * b.x + bf16hi(v.z) * b.y + bf16lo(v.w) * b.z + bf16hi(v.w) * b.w; + } + return block_sum(acc); +} +__global__ void k_gemv_bf16_rowblock(const uint16_t* __restrict__ W, const float* __restrict__ x, float* __restrict__ y, + int K) { + const float acc = rowblock_dot(W, x, K); + if (!threadIdx.x) y[blockIdx.x] = acc; +} +// gate j's down projection: gdown[j] [GATE_RANK] = down_j . cat[j]; grid (GATE_RANK, gates) +__global__ void k_gate_down(GateArgs g, const float* __restrict__ cat, float* __restrict__ gdown, int K) { + const int j = blockIdx.y; + const float acc = rowblock_dot(g.down[j], cat + (size_t) j * 2 * H, K); + if (!threadIdx.x) gdown[(size_t) j * GATE_RANK + blockIdx.x] = acc; +} + +// message gate tail + the following norm: y = (1 - tanh f) * x + tanh g * m; yn = rms(y) * w. One block per gate. +__global__ void k_gate_mix_rms(GateArgs ga, const float* gfg) { + const int j = blockIdx.x; + const float *x = ga.x[j], *m = ga.m[j], *f = gfg + (size_t) j * 2 * H, *g = f + H, *w = ga.nw[j]; + float *y = ga.y[j], *yn = ga.yn[j]; + float ss = 0.0f; + for (int i = threadIdx.x; i < H; i += blockDim.x) { + const float a = (1.0f - tanhf(f[i])) * x[i] + tanhf(g[i]) * m[i]; + y[i] = a; + ss += a * a; + } + ss = block_sum(ss); + const float r = rsqrtf(ss / H + EPS); + for (int i = threadIdx.x; i < H; i += blockDim.x) yn[i] = w[i] * (y[i] * r); +} + + +__device__ __forceinline__ float log_scale_at(int pos) { + return 1.0f + LOG_ALPHA * logf(fmaxf((float) (pos + 1) / LOG_FLOOR, 1.0f)); +} + +// head hd of v: v *= scale; L2 clip to thr; (log scale on full layers). block = 128 threads, dim <= 128 +__device__ __forceinline__ void head_clip1(float* v, const float* scale, int dim, float thr, int log_scaled, int pos, + int hd) { + float* x = v + (size_t) hd * dim; + const int i = threadIdx.x; + float a = i < dim ? x[i] * (scale ? scale[(size_t) hd * dim + i] : 1.0f) : 0.0f; + const float norm = sqrtf(block_sum(a * a)); + a *= fminf(thr / (norm + 1e-6f), 1.0f); + if (log_scaled) a *= log_scale_at(pos); + if (i < dim) x[i] = a; +} + +// Inkling2LoopShortConvolution: hist = HR rows, row p % HR holds position p's input. HR > 3 + the longest verify block +// (8): positions written by a rejected draft never overwrite a row an accepted position still reads, so a rollback is +// only the position going back. +constexpr int HR = 16; +__device__ __forceinline__ float short_conv1(float xc, float* __restrict__ hist, const float* __restrict__ w, int C, int c, + int p) { + float acc = w[(size_t) c * KC + KC - 1] * xc; + for (int j = 1; j < KC; ++j) + if (p - j >= 0) acc += w[(size_t) c * KC + KC - 1 - j] * hist[(size_t) ((p - j) % HR) * C + c]; + hist[(size_t) (p % HR) * C + c] = xc; + return __fmul_rn(acc + xc, rsqrtf((float) (KC + 1))); // _rn: no FMA contraction with the caller's residual add +} +// attention tail: conv of the attention output, then either (block boundary) r = y also stored as the next block state, +// or r = h + y also stored over the layer's stack entry +__global__ void k_attn_tail(const float* __restrict__ x, float* __restrict__ hist, const float* __restrict__ w, + const float* __restrict__ h, float* __restrict__ r, float* __restrict__ r_copy, int boundary, + const int* d_pos) { + const int c = blockIdx.x * blockDim.x + threadIdx.x; + if (c >= H) return; + const float y = short_conv1(x[c], hist, w, H, c, *d_pos); + const float v = boundary ? y : h[c] + y; + r[c] = v; + r_copy[c] = v; +} +// MoE tail: combine the TOPK expert outputs, conv, residual: out = r + conv(sum_k y_k w_k) +__global__ void k_moe_tail(const float* __restrict__ ey, const float* __restrict__ wts, float* __restrict__ hist, + const float* __restrict__ w, const float* __restrict__ r, float* __restrict__ out, + const int* d_pos) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= H) return; + float a = 0.0f; + for (int k = 0; k < TOPK; ++k) a += ey[(size_t) k * H + i] * wts[k]; + out[i] = r[i] + short_conv1(a, hist, w, H, i, *d_pos); +} + +// Inkling2LoopDynamicShortConvolution: taps static_w[lag][c] + dw[(c / 128) * 4 + lag] +__device__ __forceinline__ float dyn_conv1(float xc, const float* __restrict__ dw, float* __restrict__ hist, + const float* __restrict__ static_w, int C, int c, int p) { + const int head = c / (C / NKV); + float acc = 0.0f; + for (int lag = 0; lag < KC; ++lag) { + const float tap = static_w[(size_t) lag * C + c] + dw[head * KC + lag]; + if (lag == 0) acc += tap * xc; + else if (p - lag >= 0) acc += tap * hist[(size_t) ((p - lag) % HR) * C + c]; + } + hist[(size_t) (p % HR) * C + c] = xc; + return __fmul_rn(acc + xc, rsqrtf((float) (2 * KC + 1))); +} + +// KV cache cells [cap][KVD], format c_kvm (--kv): 0 fp32; 1 fp16 (round to nearest); 2 Strata's int8 layout +// (kv_q8.hpp): codes + one fp16 scale per 64 values [cap][KVD / 64] (ksc / vsc); scale = fp16(max|x| / 127), +// code = clamp(rint(x / scale), -127, 127). K is L2-clipped and V RMS-normalized per head before the store. +constexpr int KVG = 64; +constexpr int V4G = 32; // --kv k8v4: V values per fp16 scale +__constant__ int c_kvm; // 3 = int8 with Walsh-Hadamard rotation (Strata's kv_int8_rotate): K, V, q rotated per head, + // the attention output rotated back (H orthonormal and symmetric: scores unchanged); + // 4 = k8v4: K as in 2, V rotated as in 3 and stored as 4-bit codes [cap][KVD / 2] (low nibble + // first) with one fp16 scale per 32 values [cap][KVD / 32]; q is not rotated (K is not) + // 5 = k8v8: K as in 2, V rotated as in 3 and stored int8 as in 2; q not rotated +__host__ __device__ constexpr bool kv_rot_v(int kvm) { return kvm >= 3; } // the output is rotated back +// orthonormal Walsh-Hadamard transform of one 128-vector held one value per thread by a 128-thread block +__device__ __forceinline__ float wht128(float x) { + __shared__ float r[128]; + const int t = threadIdx.x; + __syncthreads(); // r reused across calls + r[t] = x; +#pragma unroll + for (int st = 1; st < 128; st <<= 1) { + __syncthreads(); + const float a = r[t], b = r[t ^ st]; + __syncthreads(); + r[t] = (t & st) ? b - a : a + b; + } + __syncthreads(); + return r[t] * 0.08838834764831845f; // 1 / sqrt(128) +} +// VV: the V cache (k8v4 differs between K and V) +template +__device__ __forceinline__ float4 kv_ld4(const void* B, const __half* sc, size_t row, int e) { + if (VV && c_kvm == 4) { // 4 nibbles (e % 4 == 0): 2 bytes, low nibble first + const uint32_t u = *reinterpret_cast(static_cast(B) + row * (KVD / 2) + e / 2); + const float f = __half2float(sc[row * (KVD / V4G) + e / V4G]); + return make_float4((float) ((int) (u & 15u) - 8) * f, (float) ((int) ((u >> 4) & 15u) - 8) * f, + (float) ((int) ((u >> 8) & 15u) - 8) * f, (float) ((int) (u >> 12) - 8) * f); + } + if (c_kvm == 0) return *reinterpret_cast(static_cast(B) + row * KVD + e); + if (c_kvm == 1) { + const uint2 u = *reinterpret_cast(static_cast(B) + row * KVD + e); + const float2 a = __half22float2(*reinterpret_cast(&u.x)); + const float2 b = __half22float2(*reinterpret_cast(&u.y)); + return make_float4(a.x, a.y, b.x, b.y); + } + const char4 c = *reinterpret_cast(static_cast(B) + row * KVD + e); + const float f = __half2float(sc[row * (KVD / KVG) + e / KVG]); + return make_float4(c.x * f, c.y * f, c.z * f, c.w * f); +} +template +__device__ __forceinline__ float kv_ld1(const void* B, const __half* sc, size_t row, int e) { + if (VV && c_kvm == 4) { + const uint32_t b = static_cast(B)[row * (KVD / 2) + e / 2]; + return (float) ((int) ((e & 1) ? b >> 4 : b & 15u) - 8) * __half2float(sc[row * (KVD / V4G) + e / V4G]); + } + if (c_kvm == 0) return static_cast(B)[row * KVD + e]; + if (c_kvm == 1) return __half2float(static_cast(B)[row * KVD + e]); + return static_cast(B)[row * KVD + e] * __half2float(sc[row * (KVD / KVG) + e / KVG]); +} +// one cell value, called by every thread of a 128-thread block, thread i holding element e = g * HD + i (warps 0-1: +// first group of 64, warps 2-3: second) +template +__device__ __forceinline__ void kv_st(void* B, __half* sc, size_t row, int e, float x) { + if (c_kvm == 0) { static_cast(B)[row * KVD + e] = x; return; } + if (c_kvm == 1) { static_cast<__half*>(B)[row * KVD + e] = __float2half_rn(x); return; } + if (c_kvm == 3 || (VV && c_kvm >= 4)) x = wht128(x); + if (VV && c_kvm == 4) { // a warp holds one group of 32: scale = fp16(max|x| / 7), code = clamp(rint(x / s), -7, 7) + 8 + const float m = warp_max(fabsf(x)); + const __half sh = __float2half_rn(m / 7.0f); + const float f = __half2float(sh); + const int q = f > 0.0f ? max(-7, min(7, __float2int_rn(x / f))) : 0; + const int qn = __shfl_down_sync(0xffffffffu, q, 1); + if (!(threadIdx.x & 1)) static_cast(B)[row * (KVD / 2) + e / 2] = (uint8_t) ((q + 8) | ((qn + 8) << 4)); + if (!(threadIdx.x & (V4G - 1))) sc[row * (KVD / V4G) + e / V4G] = sh; + return; + } + __shared__ float gm[4]; + const float m = warp_max(fabsf(x)); + __syncthreads(); // gm is reused by the next call + if (!(threadIdx.x & 31)) gm[threadIdx.x >> 5] = m; + __syncthreads(); + const int w = threadIdx.x >> 5; + const __half sh = __float2half_rn(fmaxf(gm[w & ~1], gm[w | 1]) / 127.0f); + const float f = __half2float(sh); + const int q = f > 0.0f ? max(-127, min(127, __float2int_rn(x / f))) : 0; + static_cast(B)[row * KVD + e] = (int8_t) q; + if (!(threadIdx.x & (KVG - 1))) sc[row * (KVD / KVG) + e / KVG] = sh; +} + +// keys: L2 clip per KV head; values: unweighted RMS per head; stored at position pos (ring: pos % cap) +// k / v convolutions (static or dynamic taps) fused with the store; grid NKV, block HD +template +__device__ __forceinline__ void conv_kv_store1(const float* k, const float* v, float* khist, float* vhist, const float* kw, + const float* vw, void* K, void* V, __half* ksc, __half* vsc, int cap, + const int* d_pos, int g) { + const int i = threadIdx.x, c = g * HD + i, p = *d_pos; + const float kv = DYN ? dyn_conv1(k[c], k + KVD, khist, kw, KVD, c, p) : short_conv1(k[c], khist, kw, KVD, c, p); + const float vv = DYN ? dyn_conv1(v[c], v + KVD, vhist, vw, KVD, c, p) : short_conv1(v[c], vhist, vw, KVD, c, p); + const float kn = sqrtf(block_sum(kv * kv)); + const float vr = rsqrtf(block_sum(vv * vv) / HD + EPS); + const size_t row = (size_t) ((*d_pos) % cap); + kv_st(K, ksc, row, c, kv * fminf(QK_CLIP / (kn + 1e-6f), 1.0f)); + kv_st(V, vsc, row, c, vv * vr); +} + +// Attention prep, one launch (block = 128): blocks [0, NQ) clip q head b; [NQ, 2 NQ) clip rs head h then +// rel[h][d] = sum_r rs[h][r] proj[r][d]; [2 NQ, 2 NQ + NKV) conv + clip/rms + store of k / v group g. Same arithmetic as +// the former four kernels (k_head_clip x2, k_rel_logits, k_conv_kv_store). +template +__global__ void k_attn_prep(float* q, const float* q_scale, float* rs, const float* rel_scale, const float* rel_proj, + float* rel, int log_scaled, const float* k, const float* v, float* khist, float* vhist, + const float* kw, const float* vw, void* K, void* V, __half* ksc, __half* vsc, int cap, + const int* d_pos) { + const int b = blockIdx.x; + if (b < NQ) { + head_clip1(q, q_scale, HD, QK_CLIP, log_scaled, *d_pos, b); + if (c_kvm == 3) q[b * HD + threadIdx.x] = wht128(q[b * HD + threadIdx.x]); + } else if (b < 2 * NQ) { + const int h = b - NQ; + head_clip1(rs, rel_scale, DREL, REL_CLIP, log_scaled, *d_pos, h); + __syncthreads(); // the clipped rs of head h, written by this block + for (int d = threadIdx.x; d < EXTENT; d += blockDim.x) { + float a = 0.0f; +#pragma unroll + for (int r = 0; r < DREL; ++r) a += rs[h * DREL + r] * rel_proj[r * EXTENT + d]; + rel[h * EXTENT + d] = a; + } + } else { + conv_kv_store1(k, v, khist, vhist, kw, vw, K, V, ksc, vsc, cap, d_pos, b - 2 * NQ); + } +} + +// partial attention: block (head h, chunk c) covers distances [c*CHUNK, c*CHUNK + CHUNK) back from pos; window 0 = full. +// writes m, l (sum of exp) and o[HD] (unnormalized) for the merge. block = 128 threads (4 warps). +__global__ void k_attn_partial(const float* __restrict__ q, const void* __restrict__ K, const void* __restrict__ V, + const __half* __restrict__ ksc, const __half* __restrict__ vsc, const float* __restrict__ rel, int cap, int window, const int* d_pos, + float* __restrict__ pm, float* __restrict__ pl, float* __restrict__ po) { + __shared__ __align__(16) float qs[HD]; + __shared__ float lg[CHUNK]; + const int h = blockIdx.x, c = blockIdx.y, g = h / NREP, tid = threadIdx.x, lane = tid & 31, wp = tid / 32; + const int pos = *d_pos; + const int span = window > 0 ? min(pos + 1, window) : pos + 1; // distances 0 .. span-1 + const int d0 = c * CHUNK, n = min(CHUNK, span - d0); + const size_t part = (size_t) h * gridDim.y + c; + if (n <= 0) { + if (!tid) { pm[part] = -INFINITY; pl[part] = 0.0f; } + po[part * HD + tid] = 0.0f; + return; + } + qs[tid] = q[h * HD + tid]; + __syncthreads(); + const float scale = rsqrtf((float) HD); + // ring slot of distance d0 + k: r0 - k, wrapped once (k < CHUNK <= cap) + const int r0 = (pos - d0) % cap; + // q.k: 8 lanes per position (4 positions per warp, 16 per block step), each lane 4 float4 of the row + { + const int sub = lane & 7; + const float4* q4 = reinterpret_cast(qs); + for (int k0 = wp * 4; k0 < n; k0 += 16) { + const int k = k0 + (lane >> 3); + float a = 0.0f; + if (k < n) { + const int r = r0 - k < 0 ? r0 - k + cap : r0 - k; + float4 kv[4]; +#pragma unroll + for (int u = 0; u < 4; ++u) kv[u] = kv_ld4(K, ksc, (size_t) r, g * HD + 4 * (sub + 8 * u)); +#pragma unroll + for (int u = 0; u < 4; ++u) { + const float4 qv = q4[sub + 8 * u]; + a += qv.x * kv[u].x + qv.y * kv[u].y + qv.z * kv[u].z + qv.w * kv[u].w; + } + } + a += __shfl_xor_sync(0xffffffffu, a, 4); + a += __shfl_xor_sync(0xffffffffu, a, 2); + a += __shfl_xor_sync(0xffffffffu, a, 1); + const int dist = d0 + k; + if (!sub && k < n) lg[k] = a * scale + (dist < EXTENT ? rel[h * EXTENT + dist] : 0.0f); + } + } + __syncthreads(); + float mx = -INFINITY; + for (int k = tid; k < n; k += blockDim.x) mx = fmaxf(mx, lg[k]); + mx = block_max(mx); + float s = 0.0f; + for (int k = tid; k < n; k += blockDim.x) { lg[k] = expf(lg[k] - mx); s += lg[k]; } + s = block_sum(s); // block_sum syncs, lg visible after + __syncthreads(); + // p.V: warp wp takes positions wp, wp + 4, ...; lane holds dims 4 lane .. 4 lane + 3; the 4 partial rows summed + // through smem (positions spread over the warps: 4x more loads in flight than one position per block step) + __shared__ float4 red[4][HD / 4]; + float4 o4 = make_float4(0.0f, 0.0f, 0.0f, 0.0f); + const int ve = g * HD + 4 * lane; + // k8v4's V loads in a loop of their own: its format test inside the loop slowed this kernel 13.6 -> 23.8 us (f16) + if (c_kvm == 4) { +#pragma unroll 4 + for (int k = wp; k < n; k += 4) { + const int r = r0 - k < 0 ? r0 - k + cap : r0 - k; + const float4 v = kv_ld4(V, vsc, (size_t) r, ve); + const float pk = lg[k]; + o4.x += pk * v.x; o4.y += pk * v.y; o4.z += pk * v.z; o4.w += pk * v.w; + } + } else { // V as K in the other formats +#pragma unroll 4 + for (int k = wp; k < n; k += 4) { + const int r = r0 - k < 0 ? r0 - k + cap : r0 - k; + const float4 v = kv_ld4(V, vsc, (size_t) r, ve); + const float pk = lg[k]; + o4.x += pk * v.x; o4.y += pk * v.y; o4.z += pk * v.z; o4.w += pk * v.w; + } + } + red[wp][lane] = o4; + __syncthreads(); + const float* rf = reinterpret_cast(red); + const float o = rf[tid] + rf[HD + tid] + rf[2 * HD + tid] + rf[3 * HD + tid]; + if (!tid) { pm[part] = mx; pl[part] = s; } + po[part * HD + tid] = o; +} + +// merge the chunks of each head with its sink logit (zero value); out[h][HD] +__global__ void k_attn_merge(const float* pm, const float* pl, const float* po, int nchunk, const float* sink, + const float* gate, float* out) { + const int h = blockIdx.x, tid = threadIdx.x; + float M = sink[h]; + for (int c = 0; c < nchunk; ++c) M = fmaxf(M, pm[h * nchunk + c]); + float L = expf(sink[h] - M), o = 0.0f; + for (int c = 0; c < nchunk; ++c) { + const float m = pm[h * nchunk + c]; + if (m == -INFINITY) continue; + const float f = expf(m - M); + L += f * pl[h * nchunk + c]; + o += f * po[((size_t) h * nchunk + c) * HD + tid]; + } + float a = o / L; // then the output gate: a * sigmoid(g) + if (kv_rot_v(c_kvm)) a = wht128(a); // rotated V: the output comes back with the same transform + out[h * HD + tid] = a * (1.0f / (1.0f + expf(-gate[h * HD + tid]))); +} + + +// rotate head blockIdx.x of row blockIdx.y in place (--kv i8r): prefill q before attention, output after; block 128 +__global__ void kb_wht(float* x, int stride) { + float* v = x + (size_t) blockIdx.y * stride + blockIdx.x * HD; + v[threadIdx.x] = wht128(v[threadIdx.x]); +} + +// router: sigmoid scores, top-8 on score + bias, weights score / sum * 8. one block of NE threads +__global__ void k_router(const float* logits, const float* bias, int* ids, float* wts) { + logits += (size_t) blockIdx.x * NE; + ids += blockIdx.x * TOPK; + wts += blockIdx.x * TOPK; + __shared__ float sel[NE], sc[NE]; + __shared__ int pick[TOPK]; + const int e = threadIdx.x; + sc[e] = 1.0f / (1.0f + expf(-logits[e])); + sel[e] = sc[e] + bias[e]; + if (e < TOPK) pick[e] = e; // only NaN scores leave a rank unfilled: keep the ids in range then + __syncthreads(); + // rank of e = number of experts ahead of it (higher score, ties: lower index); ranks 0..TOPK-1 are the picks in + // the order successive argmaxes (ties to the lowest index) would give them + const float me = sel[e]; + int rank = 0; + for (int i = 0; i < NE; ++i) { + const float o = sel[i]; + rank += (o > me) || (o == me && i < e); + } + if (rank < TOPK) pick[rank] = e; + __syncthreads(); + if (e == 0) { + float sum = 0.0f; + for (int k = 0; k < TOPK; ++k) sum += sc[pick[k]]; + for (int k = 0; k < TOPK; ++k) { ids[k] = pick[k]; wts[k] = sc[pick[k]] / (sum + 1e-20f) * ROUTE_SCALE; } + } +} + + + +__global__ void k_softcap(float* x, int n, float cap) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) x[i] = tanhf(x[i] / cap) * cap; +} + +// --------------------------------------------------------------------------------------------------------------------- +// Prefill kernels: T tokens at once (positions pos0 .. pos0 + T - 1), activations row-major [T][dim] with a row stride. +// Same fp32 arithmetic as the one-token kernels; only the summation order of the matrix products differs (cuBLAS SGEMM, +// full FP32, no TF32). + +__global__ void kb_bf16_to_f32(const uint16_t* __restrict__ src, float* __restrict__ dst, size_t n8) { + const size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n8) return; + const uint4 v = __ldg(reinterpret_cast(src) + i); + float4* d = reinterpret_cast(dst) + 2 * i; + d[0] = make_float4(bf16lo(v.x), bf16hi(v.x), bf16lo(v.y), bf16hi(v.y)); + d[1] = make_float4(bf16lo(v.z), bf16hi(v.z), bf16lo(v.w), bf16hi(v.w)); +} + +// [rms(x_t), rms(m_t)] -> cat[t][2H]; grid (2, T) +__global__ void kb_rms2(const float* __restrict__ x, int sx, const float* __restrict__ m, int sm, float* __restrict__ cat) { + const int t = blockIdx.y; + const float* a = blockIdx.x ? m + (size_t) t * sm : x + (size_t) t * sx; + float* b = cat + (size_t) t * 2 * H + (size_t) blockIdx.x * H; + float ss = 0.0f; + for (int i = threadIdx.x; i < H; i += blockDim.x) ss += a[i] * a[i]; + ss = block_sum(ss); + const float r = rsqrtf(ss / H + EPS); + for (int i = threadIdx.x; i < H; i += blockDim.x) b[i] = a[i] * r; +} + +// yn_t = rms((1 - tanh f) * x + tanh g * m) * w; fg [T][2H]; grid T +__global__ void kb_gate_mix_rms(const float* x, int sx, const float* m, int sm, const float* fg, const float* w, + float* yn) { + const int t = blockIdx.x; + x += (size_t) t * sx; + m += (size_t) t * sm; + const float* f = fg + (size_t) t * 2 * H; + const float* g = f + H; + yn += (size_t) t * H; + float ss = 0.0f; + for (int i = threadIdx.x; i < H; i += blockDim.x) { + const float a = (1.0f - tanhf(f[i])) * x[i] + tanhf(g[i]) * m[i]; + ss += a * a; + } + ss = block_sum(ss); + const float r = rsqrtf(ss / H + EPS); + for (int i = threadIdx.x; i < H; i += blockDim.x) { + const float a = (1.0f - tanhf(f[i])) * x[i] + tanhf(g[i]) * m[i]; + yn[i] = w[i] * (a * r); + } +} + +// per head and token: v *= scale; L2 clip; (log scale). grid (heads, T), block 128 +// Graph-captured verify / draft blocks: the launches carry pos0 = -1 and the kernels read the block's first position +// from d_vpos (set before each replay); the chunked prefill passes it by value as before. +__device__ int d_vpos; +#define VPOS(p) ((p) < 0 ? d_vpos : (p)) +__global__ void kb_head_clip(float* v, int sv, const float* scale, int dim, float thr, int log_scaled, int pos0) { + pos0 = VPOS(pos0); + float* x = v + (size_t) blockIdx.y * sv + (size_t) blockIdx.x * dim; + const int i = threadIdx.x; + float a = i < dim ? x[i] * (scale ? scale[(size_t) blockIdx.x * dim + i] : 1.0f) : 0.0f; + const float norm = sqrtf(block_sum(a * a)); + a *= fminf(thr / (norm + 1e-6f), 1.0f); + if (log_scaled) a *= log_scale_at(pos0 + blockIdx.y); + if (i < dim) x[i] = a; +} + +// causal depthwise conv over the chunk; inputs before the chunk come from hist (row p % HR). grid (C / 256, T). +// dw (dynamic taps, full layers): per token at dw + t * sx, [NKV][KC]; static_w then [KC][C]; else w [C][KC] +__global__ void kb_conv(const float* __restrict__ x, int sx, const float* __restrict__ hist, const float* __restrict__ w, + const float* __restrict__ dw, float* __restrict__ y, int sy, int C, int pos0) { + pos0 = VPOS(pos0); + const int c = blockIdx.x * blockDim.x + threadIdx.x, t = blockIdx.y, p = pos0 + t; + if (c >= C) return; + const float xc = x[(size_t) t * sx + c]; + float acc; + if (dw) { + const float* d = dw + (size_t) t * sx + (c / (C / NKV)) * KC; + acc = (w[c] + d[0]) * xc; + for (int lag = 1; lag < KC; ++lag) { + if (p - lag < 0) break; + const float v = t - lag >= 0 ? x[(size_t) (t - lag) * sx + c] : hist[(size_t) ((p - lag) % HR) * C + c]; + acc += (w[(size_t) lag * C + c] + d[lag]) * v; + } + y[(size_t) t * sy + c] = (acc + xc) * rsqrtf((float) (2 * KC + 1)); + } else { + acc = w[(size_t) c * KC + KC - 1] * xc; + for (int j = 1; j < KC; ++j) { + if (p - j < 0) break; + const float v = t - j >= 0 ? x[(size_t) (t - j) * sx + c] : hist[(size_t) ((p - j) % HR) * C + c]; + acc += w[(size_t) c * KC + KC - 1 - j] * v; + } + y[(size_t) t * sy + c] = (acc + xc) * rsqrtf((float) (KC + 1)); + } +} +// after kb_conv: the chunk's last (up to HR) inputs into hist. grid (C / 256, min(HR, T)) +__global__ void kb_hist_store(const float* __restrict__ x, int sx, float* __restrict__ hist, int C, int T, int pos0) { + pos0 = VPOS(pos0); + const int c = blockIdx.x * blockDim.x + threadIdx.x, t = T - 1 - blockIdx.y; + if (c < C) hist[(size_t) ((pos0 + t) % HR) * C + c] = x[(size_t) t * sx + c]; +} + +// grid (NKV, T), block HD +__global__ void kb_kv_store(const float* kc, const float* vc, void* K, void* V, __half* ksc, __half* vsc, int cap, + int pos0) { + pos0 = VPOS(pos0); + const int g = blockIdx.x, t = blockIdx.y, i = threadIdx.x; + const float kv = kc[(size_t) t * KVD + g * HD + i], vv = vc[(size_t) t * KVD + g * HD + i]; + const float kn = sqrtf(block_sum(kv * kv)); + const float vr = rsqrtf(block_sum(vv * vv) / HD + EPS); + const size_t row = (size_t) ((pos0 + t) % cap); + kv_st(K, ksc, row, g * HD + i, kv * fminf(QK_CLIP / (kn + 1e-6f), 1.0f)); + kv_st(V, vsc, row, g * HD + i, vv * vr); +} + +// rel[t][h][d] = sum_r rs_t[h][r] proj[r][d]; grid (NQ, T) +__global__ void kb_rel_logits(const float* rs, int sr, const float* proj, float* rel) { + const int h = blockIdx.x, t = blockIdx.y; + const float* r0 = rs + (size_t) t * sr + h * DREL; + float* o = rel + ((size_t) t * NQ + h) * EXTENT; + for (int d = threadIdx.x; d < EXTENT; d += blockDim.x) { + float a = 0.0f; +#pragma unroll + for (int r = 0; r < DREL; ++r) a += r0[r] * proj[r * EXTENT + d]; + o[d] = a; + } +} + +// Tiled causal attention, fp32: block = (64 queries, one q head), 256 threads; key tiles of 64 from the cache (ring +// index j % cap). Online softmax started from the sink (m = sink, l = 1, o = 0: its value is zero). +// Thread (ty = tid / 16, tx = tid % 16): queries ty*4 .. +3; scores for keys tx + 16 m; outputs dims tx + 16 m. +constexpr int FQ = 64, FK = 64, FQ_LD = HD + 4, FK_LD = HD + 1, FP_LD = FK + 1; +constexpr size_t FA_SMEM = (size_t) (FQ * FQ_LD + FK * FK_LD + FQ * FP_LD) * 4; +__global__ void __launch_bounds__(256) kb_attn(const float* __restrict__ P, int sp, const void* __restrict__ K, + const void* __restrict__ V, const __half* __restrict__ ksc, + const __half* __restrict__ vsc, const float* __restrict__ rel, int cap, + int window, int pos0, int T, float* __restrict__ out) { + pos0 = VPOS(pos0); + extern __shared__ float fsm[]; + float* Qs = fsm; // [FQ][FQ_LD] + float* KVs = Qs + FQ * FQ_LD; // keys [FK][FK_LD], then values [FK][HD] + float* Ps = KVs + FK * FK_LD; // [FQ][FP_LD] + const int h = blockIdx.y, g = h / NREP, t0 = blockIdx.x * FQ, tid = threadIdx.x, ty = tid / 16, tx = tid % 16; + const int nq = min(FQ, T - t0); + for (int i = tid; i < FQ * HD; i += 256) { + const int r = i / HD, d = i % HD; + Qs[r * FQ_LD + d] = r < nq ? P[(size_t) (t0 + r) * sp + h * HD + d] : 0.0f; + } + float m[4], l[4], o[4][8]; + const float scale = rsqrtf((float) HD); +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int r = ty * 4 + i; + m[i] = r < nq ? P[(size_t) (t0 + r) * sp + OFF_SINK + h] : 0.0f; + l[i] = 1.0f; +#pragma unroll + for (int j = 0; j < 8; ++j) o[i][j] = 0.0f; + } + const int pa = pos0 + t0, pb = pos0 + t0 + nq - 1; // first / last query position + const int lo = window > 0 ? max(0, pa - window + 1) : 0; + for (int k0 = lo; k0 <= pb; k0 += FK) { + __syncthreads(); + for (int i = tid; i < FK * HD; i += 256) { + const int r = i / HD, d = i % HD, j = k0 + r; + KVs[r * FK_LD + d] = j <= pb ? kv_ld1(K, ksc, (size_t) (j % cap), g * HD + d) : 0.0f; + } + __syncthreads(); + float s[4][4]; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int c = 0; c < 4; ++c) s[i][c] = 0.0f; +#pragma unroll 4 + for (int d = 0; d < HD; ++d) { + float q[4], k[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) q[i] = Qs[(ty * 4 + i) * FQ_LD + d]; +#pragma unroll + for (int c = 0; c < 4; ++c) k[c] = KVs[(tx + 16 * c) * FK_LD + d]; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int c = 0; c < 4; ++c) s[i][c] += q[i] * k[c]; + } + // bias, mask, online softmax (a query row lives in the 16 threads of a half warp) +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int r = ty * 4 + i, p = pos0 + t0 + r; + float mx = -INFINITY; +#pragma unroll + for (int c = 0; c < 4; ++c) { + const int j = k0 + tx + 16 * c, dist = p - j; + const bool ok = r < nq && j <= p && (window == 0 || dist < window); + s[i][c] = ok ? s[i][c] * scale + (dist < EXTENT ? rel[((size_t) (t0 + r) * NQ + h) * EXTENT + dist] : 0.0f) + : -INFINITY; + mx = fmaxf(mx, s[i][c]); + } + for (int w = 8; w; w >>= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, w)); + const float mn = fmaxf(m[i], mx), f = expf(m[i] - mn); + float sum = 0.0f; +#pragma unroll + for (int c = 0; c < 4; ++c) { + const float e = expf(s[i][c] - mn); + Ps[r * FP_LD + tx + 16 * c] = e; + sum += e; + } + for (int w = 8; w; w >>= 1) sum += __shfl_xor_sync(0xffffffffu, sum, w); + l[i] = l[i] * f + sum; + m[i] = mn; +#pragma unroll + for (int j = 0; j < 8; ++j) o[i][j] *= f; + } + __syncthreads(); + for (int i = tid; i < FK * HD; i += 256) { + const int r = i / HD, d = i % HD, j = k0 + r; + KVs[r * HD + d] = j <= pb ? kv_ld1(V, vsc, (size_t) (j % cap), g * HD + d) : 0.0f; + } + __syncthreads(); + const int kn = min(FK, pb - k0 + 1); + for (int k = 0; k < kn; ++k) { + float pv[4], v[8]; +#pragma unroll + for (int i = 0; i < 4; ++i) pv[i] = Ps[(ty * 4 + i) * FP_LD + k]; +#pragma unroll + for (int j = 0; j < 8; ++j) v[j] = KVs[k * HD + tx + 16 * j]; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < 8; ++j) o[i][j] += pv[i] * v[j]; + } + } +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int r = ty * 4 + i; + if (r >= nq) continue; +#pragma unroll + for (int j = 0; j < 8; ++j) out[(size_t) (t0 + r) * QD + h * HD + tx + 16 * j] = o[i][j] / l[i]; + } +} + +// att[t][i] *= sigmoid(gate_t[i]); grid (QD / 256, T) +__global__ void kb_mul_sigmoid(float* att, const float* gate, int sg) { + const int i = blockIdx.x * blockDim.x + threadIdx.x, t = blockIdx.y; + att[(size_t) t * QD + i] *= 1.0f / (1.0f + expf(-gate[(size_t) t * sg + i])); +} + +// MoE plan (one block, thread = expert): rows of the grouped products sorted by expert then (token, k); +// rows[r] = token, slot[t * TOPK + k] = r; tiles of FM rows within one expert. +constexpr int FM = 64, FN = 64, FKK = 32; +// (one block of 1024 threads; the order of the rows within an expert is not deterministic and does not matter: each +// output row depends only on its own input row) +__global__ void kb_moe_plan(const int* __restrict__ ids, int T, int* rows, int* slot, int* tile_e, int* tile_r0, + int* ntiles, int* eoff, int* ecnt) { + __shared__ int cnt[NE], off[NE], cur[NE]; + const int n = T * TOPK; + for (int e = threadIdx.x; e < NE; e += blockDim.x) { cnt[e] = 0; cur[e] = 0; } + __syncthreads(); + for (int i = threadIdx.x; i < n; i += blockDim.x) atomicAdd(&cnt[ids[i]], 1); + __syncthreads(); + if (threadIdx.x == 0) { + int o = 0, nt = 0; + for (int j = 0; j < NE; ++j) { + off[j] = o; + for (int r = 0; r < cnt[j]; r += FM) { tile_e[nt] = j; tile_r0[nt] = o + r; ++nt; } + o += cnt[j]; + } + *ntiles = nt; + } + __syncthreads(); + for (int e = threadIdx.x; e < NE; e += blockDim.x) { eoff[e] = off[e]; ecnt[e] = cnt[e]; } + for (int i = threadIdx.x; i < n; i += blockDim.x) { + const int e = ids[i], r = off[e] + atomicAdd(&cur[e], 1); + rows[r] = i / TOPK; + slot[i] = r; + } +} + +// Grouped expert product with the weights decoded on the fly (exact: e2m1 * e4m3 and e4m3 * 2^k are exact in fp32): +// C[r][n] = (factor_e) * sum_k A[arow(r)][k] W_e[n][k] for the rows r of a tile (expert e). grid (max tiles, N / FN), +// 256 threads, 4x4 outputs per thread. arow = rows[r] (gather) or r. +template +__global__ void __launch_bounds__(256) kb_moe_gemm(const float* __restrict__ A, int lda, const int* __restrict__ rows, + const uint8_t* const* __restrict__ tab, + const float* __restrict__ factors, const int* __restrict__ tile_e, + const int* __restrict__ tile_r0, const int* __restrict__ ntiles, + const int* __restrict__ eoff, const int* __restrict__ ecnt, + float* __restrict__ C, int N, int K) { + __shared__ __align__(16) float As[FKK][FM + 4], Ws[FKK][FN + 4]; + if ((int) blockIdx.x >= *ntiles) return; + const int e = tile_e[blockIdx.x], r0 = tile_r0[blockIdx.x], rend = eoff[e] + ecnt[e], n0 = blockIdx.y * FN; + const uint8_t* W = tab[e]; + if (!W) return; + const uint8_t* S = W + (size_t) N * (NV ? K / 2 : K); + const int tid = threadIdx.x, ty = tid / 16, tx = tid % 16; + // A loads: 2 float4 per thread (row idx / 8, float4 idx % 8) + const float* asrc[2]; + int arow_l[2], akq[2]; +#pragma unroll + for (int u = 0; u < 2; ++u) { + const int idx = tid + 256 * u, row = idx / 8, r = r0 + row; + arow_l[u] = row; + akq[u] = idx % 8; + asrc[u] = r < rend ? A + (size_t) (rows ? rows[r] : r) * lda + akq[u] * 4 : nullptr; + } + const int wn = tid / 4, wq = tid % 4; // W loads: row n0 + wn, 8 columns from wq * 8 + const size_t wrow = (size_t) n0 + wn; + float acc[4][4] = {}; + for (int k0 = 0; k0 < K; k0 += FKK) { +#pragma unroll + for (int u = 0; u < 2; ++u) { + const float4 v = asrc[u] ? *reinterpret_cast(asrc[u] + k0) : make_float4(0, 0, 0, 0); + const int kk = akq[u] * 4, row = arow_l[u]; + As[kk][row] = v.x; As[kk + 1][row] = v.y; As[kk + 2][row] = v.z; As[kk + 3][row] = v.w; + } + const int kc = k0 + wq * 8; + if (NV) { + const uint32_t v = __ldg(reinterpret_cast(W + wrow * (K / 2) + kc / 2)); + const float sc = e4m3_decode(__ldg(S + wrow * (K / 16) + kc / 16)) * 16384.0f; +#pragma unroll + for (int b = 0; b < 4; ++b) { + const float2 p = e2m1x2((v >> (8 * b)) & 0xff); + Ws[wq * 8 + 2 * b][wn] = p.x * sc; + Ws[wq * 8 + 2 * b + 1][wn] = p.y * sc; + } + } else { + const uint2 v = __ldg(reinterpret_cast(W + wrow * K + kc)); + const float sc = exp2f((float) __ldg(S + wrow * (K / 32) + k0 / 32) - 119.0f); + const uint32_t wd[2] = {v.x, v.y}; +#pragma unroll + for (int b = 0; b < 2; ++b) { + const float2 p01 = e4m3x2((wd[b] & 0xffu) | ((wd[b] & 0xff00u) << 8)); + const float2 p23 = e4m3x2(((wd[b] >> 16) & 0xffu) | ((wd[b] & 0xff000000u) >> 8)); + Ws[wq * 8 + 4 * b][wn] = p01.x * sc; + Ws[wq * 8 + 4 * b + 1][wn] = p01.y * sc; + Ws[wq * 8 + 4 * b + 2][wn] = p23.x * sc; + Ws[wq * 8 + 4 * b + 3][wn] = p23.y * sc; + } + } + __syncthreads(); +#pragma unroll 8 + for (int kk = 0; kk < FKK; ++kk) { + const float4 a = *reinterpret_cast(&As[kk][ty * 4]); + const float4 b = *reinterpret_cast(&Ws[kk][tx * 4]); + const float av[4] = {a.x, a.y, a.z, a.w}, bv[4] = {b.x, b.y, b.z, b.w}; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < 4; ++j) acc[i][j] += av[i] * bv[j]; + } + __syncthreads(); + } + const float f = NV ? factors[e] : 1.0f; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int r = r0 + ty * 4 + i; + if (r < rend) + *reinterpret_cast(C + (size_t) r * N + n0 + tx * 4) = + make_float4(acc[i][0] * f, acc[i][1] * f, acc[i][2] * f, acc[i][3] * f); + } +} + +// --- small T (speculative verification, T <= SMALL_T tokens): weights read once for all T vectors. Per (row, token) +// the same operations in the same order as the decode GEMVs (gemv_bf16_dot, k_gemv_nvfp4_sel, k_gemv_mxfp8_sel: a +// lane walks words lane, lane + 32, ...). The verified token as a whole does not match decode bit for bit: its +// attention runs kb_attn_tc / kb_attn, decode's k_attn_partial + k_attn_merge, another summation order, so greedy +// --spec can part from plain decoding at a near-tie. +constexpr int SMALL_T = 8; +// dense: Y[t][row] (row stride ldy) = W[row] . X[t] (row stride ldx), t < T <= SMALL_T; R rows per warp. The T input +// rows are read straight from global memory (L1 / L2: T x K x 4 B <= 147 KB, reused by every warp of an SM): no +// shared-memory staging, no barrier, the weight loads of consecutive words pipelined (unroll 2). +template +__global__ void __launch_bounds__(256) k_gemv_bf16_multi(const uint16_t* __restrict__ W, const float* __restrict__ X, + int ldx, float* __restrict__ Y, int ldy, int N, int K, int T) { + constexpr int TV = SMALL_T; + const int lane = threadIdx.x & 31, row0 = (blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32) * R; + if (row0 >= N) return; + const uint4* w[R]; +#pragma unroll + for (int r = 0; r < R; ++r) w[r] = reinterpret_cast(W + (size_t) min(row0 + r, N - 1) * K); + float acc[R][TV]; +#pragma unroll + for (int r = 0; r < R; ++r) +#pragma unroll + for (int t = 0; t < TV; ++t) acc[r][t] = 0.0f; +#pragma unroll 2 + for (int i = lane; i < K / 8; i += 32) { + uint4 v[R]; +#pragma unroll + for (int r = 0; r < R; ++r) v[r] = __ldg(w[r] + i); +#pragma unroll + for (int t = 0; t < TV; ++t) { + if (t >= T) break; + const float4* x4 = reinterpret_cast(X + (size_t) t * ldx); + const float4 a = __ldg(x4 + 2 * i), b = __ldg(x4 + 2 * i + 1); +#pragma unroll + for (int r = 0; r < R; ++r) + acc[r][t] += bf16lo(v[r].x) * a.x + bf16hi(v[r].x) * a.y + bf16lo(v[r].y) * a.z + bf16hi(v[r].y) * a.w + + bf16lo(v[r].z) * b.x + bf16hi(v[r].z) * b.y + bf16lo(v[r].w) * b.z + bf16hi(v[r].w) * b.w; + } + } +#pragma unroll + for (int t = 0; t < TV; ++t) { + if (t >= T) break; +#pragma unroll + for (int r = 0; r < R; ++r) { + const float x = warp_sum(acc[r][t]); + if (!lane && row0 + r < N) Y[(size_t) t * ldy + row0 + r] = x; + } + } +} +// short matrices (N <= 256: router, gate down): one block per row, the K words split over 256 threads, block +// reduction per vector (latency-bound otherwise: a warp per row walks K alone) +__global__ void __launch_bounds__(256) k_gemv_bf16_multi_rows(const uint16_t* __restrict__ W, const float* __restrict__ X, + int ldx, float* __restrict__ Y, int ldy, int K, int T) { + constexpr int TV = SMALL_T; + __shared__ float red[8][TV]; + const uint4* w = reinterpret_cast(W + (size_t) blockIdx.x * K); + float acc[TV]; +#pragma unroll + for (int t = 0; t < TV; ++t) acc[t] = 0.0f; + for (int i = threadIdx.x; i < K / 8; i += 256) { + const uint4 v = __ldg(w + i); +#pragma unroll + for (int t = 0; t < TV; ++t) { + if (t >= T) break; + const float4* x4 = reinterpret_cast(X + (size_t) t * ldx); + const float4 a = __ldg(x4 + 2 * i), b = __ldg(x4 + 2 * i + 1); + acc[t] += bf16lo(v.x) * a.x + bf16hi(v.x) * a.y + bf16lo(v.y) * a.z + bf16hi(v.y) * a.w + bf16lo(v.z) * b.x + + bf16hi(v.z) * b.y + bf16lo(v.w) * b.z + bf16hi(v.w) * b.w; + } + } + const int lane = threadIdx.x & 31, wp = threadIdx.x >> 5; +#pragma unroll + for (int t = 0; t < TV; ++t) { + const float x = warp_sum(acc[t]); + if (!lane) red[wp][t] = x; + } + __syncthreads(); + if (threadIdx.x < T) { + float x = 0.0f; + for (int u = 0; u < 8; ++u) x += red[u][threadIdx.x]; + Y[(size_t) threadIdx.x * ldy + blockIdx.x] = x; + } +} +// K = 64 (the gates' fg): 8 lanes per row (one word each), 4 rows per warp; the 8-lane butterfly is the decode's +// 32-lane warp_sum minus its zero steps (bit-identical) +__global__ void __launch_bounds__(256) k_gemv_bf16_multi_k64(const uint16_t* __restrict__ W, const float* __restrict__ X, + int ldx, float* __restrict__ Y, int ldy, int N, int T) { + constexpr int TV = SMALL_T; + __shared__ __align__(16) float xs[TV][64]; + for (int i = threadIdx.x; i < T * 64; i += 256) xs[i / 64][i % 64] = X[(size_t) (i / 64) * ldx + i % 64]; + __syncthreads(); + const int lane = threadIdx.x & 31, j = lane & 7, row = (blockIdx.x * 8 + (threadIdx.x >> 5)) * 4 + (lane >> 3); + const uint4 v = row < N ? __ldg(reinterpret_cast(W + (size_t) row * 64) + j) : make_uint4(0, 0, 0, 0); +#pragma unroll + for (int t = 0; t < TV; ++t) { + if (t >= T) break; + const float4 a = *reinterpret_cast(&xs[t][8 * j]), b = *reinterpret_cast(&xs[t][8 * j + 4]); + float x = bf16lo(v.x) * a.x + bf16hi(v.x) * a.y + bf16lo(v.y) * a.z + bf16hi(v.y) * a.w + bf16lo(v.z) * b.x + + bf16hi(v.z) * b.y + bf16lo(v.w) * b.z + bf16hi(v.w) * b.w; + x += __shfl_xor_sync(0xffffffffu, x, 4); + x += __shfl_xor_sync(0xffffffffu, x, 2); + x += __shfl_xor_sync(0xffffffffu, x, 1); + if (j == 0 && row < N) Y[(size_t) t * ldy + row] = x; + } +} +// opt-in (--verify-tc 1): the same products on tensor cores, mma m16n8k16 with the prefill's hgemm numbers (fp16 +// weights and inputs, fp32 accumulation). A warp takes 16 rows x the 8 vectors over a K slice (64-column chunks, +// strided over the block's 8 warps); the warps' partial tiles are added in warp order (deterministic). Within a +// chunk the 16 columns a lane loads (2 x 16 B per row: whole 32 B sectors) are spread over the 4 mma steps; the +// vectors' columns follow the same permutation, so the dot products are the same sums in another order. Not decode's +// GEMV order: greedy --spec output can differ from the default path, hence opt-in. K % 64 == 0, CUDA sm_80+. +__device__ __forceinline__ uint32_t h2bits(float a, float b) { + const __half2 h = __floats2half2_rn(a, b); + return *reinterpret_cast(&h); +} +__global__ void __launch_bounds__(256) k_gemv_bf16_tc(const uint16_t* __restrict__ W, const float* __restrict__ X, int ldx, + float* __restrict__ Y, int ldy, int N, int K, int T) { +#if !defined(STRATA_USE_HIP) && defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 + __shared__ float4 red[8][32]; + const int lane = threadIdx.x & 31, wp = threadIdx.x >> 5, g = lane >> 2, c = lane & 3, row0 = blockIdx.x * 16; + const uint4* wa = reinterpret_cast(W + (size_t) min(row0 + g, N - 1) * K); + const uint4* wb = reinterpret_cast(W + (size_t) min(row0 + g + 8, N - 1) * K); + const float4* x = reinterpret_cast(X + (size_t) min(g, T - 1) * ldx); + const bool xv = g < T; + float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f}; +#pragma unroll 2 + for (int ch = wp; ch < K / 64; ch += 8) { + const int o = ch * 8 + c * 2; // this lane's columns of the chunk: 16c .. 16c + 15 (uint4 2c, 2c + 1) + const uint4 a0 = __ldg(wa + o), a1 = __ldg(wa + o + 1), b0 = __ldg(wb + o), b1 = __ldg(wb + o + 1); + float4 xq[4]; +#pragma unroll + for (int q = 0; q < 4; ++q) xq[q] = xv ? __ldg(x + ch * 16 + c * 4 + q) : make_float4(0.0f, 0.0f, 0.0f, 0.0f); + const uint32_t ra[8] = {a0.x, a0.y, a0.z, a0.w, a1.x, a1.y, a1.z, a1.w}; + const uint32_t rb[8] = {b0.x, b0.y, b0.z, b0.w, b1.x, b1.y, b1.z, b1.w}; +#pragma unroll + for (int s = 0; s < 4; ++s) { // step s: the lane's columns 4s .. 4s + 3 (logical k 2c, 2c+1 and 2c+8, 2c+9) + const uint32_t A0 = h2bits(bf16lo(ra[2 * s]), bf16hi(ra[2 * s])), A1 = h2bits(bf16lo(rb[2 * s]), bf16hi(rb[2 * s])); + const uint32_t A2 = h2bits(bf16lo(ra[2 * s + 1]), bf16hi(ra[2 * s + 1])); + const uint32_t A3 = h2bits(bf16lo(rb[2 * s + 1]), bf16hi(rb[2 * s + 1])); + const uint32_t B0 = h2bits(xq[s].x, xq[s].y), B1 = h2bits(xq[s].z, xq[s].w); + 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"(acc[0]), "+f"(acc[1]), "+f"(acc[2]), "+f"(acc[3]) + : "r"(A0), "r"(A1), "r"(A2), "r"(A3), "r"(B0), "r"(B1)); + } + } + red[wp][lane] = make_float4(acc[0], acc[1], acc[2], acc[3]); + __syncthreads(); + if (threadIdx.x < 128) { // (lane l, element q): row g or g + 8 (q / 2), vector 2c + q % 2 + const int l = threadIdx.x >> 2, q = threadIdx.x & 3; + float v = 0.0f; +#pragma unroll + for (int u = 0; u < 8; ++u) v += reinterpret_cast(&red[u][l])[q]; + const int row = row0 + (l >> 2) + (q >> 1) * 8, t = (l & 3) * 2 + (q & 1); + if (t < T && row < N) Y[(size_t) t * ldy + row] = v; + } +#else + __trap(); +#endif +} +// grouped experts: the rows of one expert (blockIdx.y = tile of kb_moe_plan; with T <= SMALL_T an expert has at most +// SMALL_T rows, one tile) times its weights, read once. C[r][n] = factor_e * W_e[n] . A[arow(r)], arow = rows[r] or r. +// R rows per warp; each word's weights decoded once for all the tile's rows; inputs read from L1 / L2. +#ifndef GRP_UNROLL +#define GRP_UNROLL 2 +#endif +#ifndef GRP_MINB +#define GRP_MINB 2 +#endif +constexpr int GRP_UNR = GRP_UNROLL; // (a pragma argument is not macro-expanded) +template +__global__ void __launch_bounds__(256, GRP_MINB) k_moe_gemv_grp(const float* __restrict__ A, int lda, const int* __restrict__ rows, + const uint8_t* const* __restrict__ tab, + const float* __restrict__ factors, const int* __restrict__ tile_e, + const int* __restrict__ tile_r0, const int* __restrict__ ntiles, + const int* __restrict__ eoff, const int* __restrict__ ecnt, + float* __restrict__ C, int N, int K) { + constexpr int TV = SMALL_T, CPW = NV ? 8 : 4; + __shared__ float e4[256]; + if ((int) blockIdx.y >= *ntiles) return; + const int e = tile_e[blockIdx.y], r0 = tile_r0[blockIdx.y], nr = min(eoff[e] + ecnt[e] - r0, TV); + const uint8_t* W = tab[e]; + if (!W) return; + const uint8_t* S = W + (size_t) N * (NV ? K / 2 : K); + if (NV) { + for (int i = threadIdx.x; i < 256; i += blockDim.x) e4[i] = e4m3_decode(i) * 16384.0f; + __syncthreads(); + } + const int lane = threadIdx.x & 31, row0 = (blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32) * R; + if (row0 >= N) return; + const float* xr[TV]; +#pragma unroll + for (int t = 0; t < TV; ++t) xr[t] = A + (size_t) (t < nr ? (rows ? rows[r0 + t] : r0 + t) : 0) * lda; + const int kw = K / CPW; // words per row + float acc[R][TV]; +#pragma unroll + for (int r = 0; r < R; ++r) +#pragma unroll + for (int t = 0; t < TV; ++t) acc[r][t] = 0.0f; +#pragma unroll GRP_UNR + for (int i = lane; i < kw; i += 32) { + uint32_t v[R]; + uint8_t sc[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { + const size_t row = row0 + r; + v[r] = __ldg(reinterpret_cast(W + row * kw * 4) + i); + sc[r] = NV ? __ldg(S + row * (K / 16) + (i >> 1)) : __ldg(S + row * (K / 32) + (i >> 3)); + } + if (NV) { // weights decoded once per word, then every row of the tile + float wd[R][8], ws[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { + const uint32_t vv = v[r]; + const float2 p0 = e2m1x2(vv & 0xff), p1 = e2m1x2((vv >> 8) & 0xff), p2 = e2m1x2((vv >> 16) & 0xff), + p3 = e2m1x2(vv >> 24); + wd[r][0] = p0.x; wd[r][1] = p0.y; wd[r][2] = p1.x; wd[r][3] = p1.y; + wd[r][4] = p2.x; wd[r][5] = p2.y; wd[r][6] = p3.x; wd[r][7] = p3.y; + ws[r] = e4[sc[r]]; + } +#pragma unroll + for (int t = 0; t < TV; ++t) { + if (t >= nr) break; + const float4 a = __ldg(reinterpret_cast(xr[t]) + 2 * i), + b = __ldg(reinterpret_cast(xr[t]) + 2 * i + 1); +#pragma unroll + for (int r = 0; r < R; ++r) { + const float part = wd[r][0] * a.x + wd[r][1] * a.y + wd[r][2] * a.z + wd[r][3] * a.w + wd[r][4] * b.x + + wd[r][5] * b.y + wd[r][6] * b.z + wd[r][7] * b.w; + acc[r][t] += part * ws[r]; + } + } + } else { + float wd[R][4], ws[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { + const uint32_t vv = v[r]; + const float2 p01 = e4m3x2((vv & 0xffu) | ((vv & 0xff00u) << 8)); + const float2 p23 = e4m3x2(((vv >> 16) & 0xffu) | ((vv & 0xff000000u) >> 8)); + wd[r][0] = p01.x; wd[r][1] = p01.y; wd[r][2] = p23.x; wd[r][3] = p23.y; + ws[r] = exp2f((float) sc[r] - 119.0f); + } +#pragma unroll + for (int t = 0; t < TV; ++t) { + if (t >= nr) break; + const float4 a = __ldg(reinterpret_cast(xr[t]) + i); +#pragma unroll + for (int r = 0; r < R; ++r) { + const float part = wd[r][0] * a.x + wd[r][1] * a.y + wd[r][2] * a.z + wd[r][3] * a.w; + acc[r][t] += part * ws[r]; + } + } + } + } + const float f = NV ? factors[e] : 1.0f; +#pragma unroll + for (int t = 0; t < TV; ++t) { + if (t >= nr) break; +#pragma unroll + for (int r = 0; r < R; ++r) { + const float x = warp_sum(acc[r][t]); + if (!lane) C[(size_t) (r0 + t) * N + row0 + r] = NV ? x * f : x; + } + } +} + +// --- tensor-core variant (--tc 1): FP16 inputs, FP32 accumulation. NVFP4 expert weights are exact in fp16 +// (e2m1 * e4m3 <= 2688, >= 2^-10, <= 6 significant bits; the per-expert factor stays an fp32 multiplier); the +// activations are rounded to fp16 (2^-11 relative). Residual stream, norms, router, gates, attention stay fp32. +// MXFP8 (layers 20-23): e4m3 * 2^(s-127) with s in [113, 118] in this checkpoint (measured, mx_range.py): multiples of +// 2^-23 below 1, exact in fp16; stored * 2^10 (clear of the subnormals), the 2^-10 back as the output factor. +constexpr int TM = 64, TN = 128, TK = 32, TLD = TK + 8, TCLD = TN + 4; +template +__global__ void __launch_bounds__(256) kb_moe_gemm_tc(const half* __restrict__ A, int lda, + const uint8_t* const* __restrict__ tab, + const float* __restrict__ factors, const int* __restrict__ tile_e, + const int* __restrict__ tile_r0, const int* __restrict__ ntiles, + const int* __restrict__ eoff, const int* __restrict__ ecnt, + float* __restrict__ C, int N, int K) { + __shared__ __align__(32) unsigned char smraw[TM * TCLD * 4]; // As + Bs during the loop, C staging after + half* As = reinterpret_cast(smraw); + half* Bs = As + TM * TLD; + float* Cs = reinterpret_cast(smraw); + if ((int) blockIdx.x >= *ntiles) return; + const int e = tile_e[blockIdx.x], r0 = tile_r0[blockIdx.x], rend = eoff[e] + ecnt[e], n0 = blockIdx.y * TN; + const uint8_t* W = tab[e]; + if (!W) return; + const uint8_t* S = W + (size_t) N * (NV ? K / 2 : K); + const int tid = threadIdx.x, warp = tid / 32, wm = warp / 4, wn = warp % 4; + // A: fp16 rows in expert order (gathered / converted once per layer, not once per N block): 16 B per thread + const int arow = tid / 4, akq = tid % 4; + const half* asrc = r0 + arow < rend ? A + (size_t) (r0 + arow) * lda + akq * 8 : nullptr; + int wn_[2], wq_[2]; +#pragma unroll + for (int u = 0; u < 2; ++u) { + const int idx = tid + 256 * u; + wn_[u] = idx / 4; + wq_[u] = idx % 4; + } + wmma::fragment c[2][2]; +#pragma unroll + for (int i = 0; i < 2; ++i) +#pragma unroll + for (int j = 0; j < 2; ++j) wmma::fill_fragment(c[i][j], 0.0f); + // register prefetch: tile k0 + TK is loaded from global while tile k0 (in smem) goes through the MMAs. The + // conversions and the MMA order are unchanged (bit-identical to the single-buffered loop). + uint4 av; + uint2 wv[2]; + uint8_t sv[2]; + auto gload = [&](int k0) { + av = asrc ? *reinterpret_cast(asrc + k0) : make_uint4(0, 0, 0, 0); +#pragma unroll + for (int u = 0; u < 2; ++u) { + const size_t wrow = (size_t) n0 + wn_[u]; + const int kc = k0 + wq_[u] * 8; + if (NV) { + wv[u].x = __ldg(reinterpret_cast(W + wrow * (K / 2) + kc / 2)); + sv[u] = __ldg(S + wrow * (K / 16) + kc / 16); + } else { + wv[u] = __ldg(reinterpret_cast(W + wrow * K + kc)); + sv[u] = __ldg(S + wrow * (K / 32) + k0 / 32); + } + } + }; + gload(0); + for (int k0 = 0; k0 < K; k0 += TK) { + *reinterpret_cast(As + arow * TLD + akq * 8) = av; +#pragma unroll + for (int u = 0; u < 2; ++u) { + half2 h[4]; + if (NV) { + const uint32_t v = wv[u].x; + const float sc = e4m3_decode(sv[u]) * 16384.0f; +#pragma unroll + for (int b = 0; b < 4; ++b) { + const float2 p = e2m1x2((v >> (8 * b)) & 0xff); + h[b] = __floats2half2_rn(p.x * sc, p.y * sc); + } + } else { + const float sc = exp2f((float) sv[u] - 109.0f); // 2^(s-127) 2^8 2^10 + const uint32_t wd[2] = {wv[u].x, wv[u].y}; +#pragma unroll + for (int b = 0; b < 2; ++b) { + const float2 p01 = e4m3x2((wd[b] & 0xffu) | ((wd[b] & 0xff00u) << 8)); + const float2 p23 = e4m3x2(((wd[b] >> 16) & 0xffu) | ((wd[b] & 0xff000000u) >> 8)); + h[2 * b] = __floats2half2_rn(p01.x * sc, p01.y * sc); + h[2 * b + 1] = __floats2half2_rn(p23.x * sc, p23.y * sc); + } + } + *reinterpret_cast(Bs + wn_[u] * TLD + wq_[u] * 8) = *reinterpret_cast(h); + } + __syncthreads(); + if (k0 + TK < K) gload(k0 + TK); +#pragma unroll + for (int kk = 0; kk < TK; kk += 16) { + wmma::fragment a[2]; + wmma::fragment b[2]; +#pragma unroll + for (int i = 0; i < 2; ++i) wmma::load_matrix_sync(a[i], As + (wm * 32 + i * 16) * TLD + kk, TLD); +#pragma unroll + for (int j = 0; j < 2; ++j) wmma::load_matrix_sync(b[j], Bs + (wn * 32 + j * 16) * TLD + kk, TLD); +#pragma unroll + for (int i = 0; i < 2; ++i) +#pragma unroll + for (int j = 0; j < 2; ++j) wmma::mma_sync(c[i][j], a[i], b[j], c[i][j]); + } + __syncthreads(); + } +#pragma unroll + for (int i = 0; i < 2; ++i) +#pragma unroll + for (int j = 0; j < 2; ++j) + wmma::store_matrix_sync(Cs + (wm * 32 + i * 16) * TCLD + wn * 32 + j * 16, c[i][j], TCLD, wmma::mem_row_major); + __syncthreads(); + const float f = NV ? factors[e] : 1.0f / 1024.0f; +#pragma unroll + for (int u = 0; u < 8; ++u) { + const int idx = tid + 256 * u, row = idx / 32, c4 = idx % 32, r = r0 + row; + if (r >= rend) continue; + const float4 v = *reinterpret_cast(Cs + row * TCLD + c4 * 4); + *reinterpret_cast(C + (size_t) r * N + n0 + c4 * 4) = make_float4(v.x * f, v.y * f, v.z * f, v.w * f); + } +} + +// Grouped expert products for GGUF experts (prompt): as kb_moe_gemm / kb_moe_gemm_tc, the weights decoded by gg_ld8 +// (no per-expert factor), output column n of w13 read from row gg_perm(n) (PERM) +template +__global__ void __launch_bounds__(256) kb_moe_gemm_gg(const float* __restrict__ A, int lda, const int* __restrict__ rows, + const uint8_t* const* __restrict__ tab, size_t rb, + const int* __restrict__ tile_e, const int* __restrict__ tile_r0, + const int* __restrict__ ntiles, const int* __restrict__ eoff, + const int* __restrict__ ecnt, float* __restrict__ C, int N, int K) { + __shared__ __align__(16) float As[FKK][FM + 4], Ws[FKK][FN + 4]; + __shared__ uint32_t grid[512]; + __shared__ int8_t kv[16]; + if ((int) blockIdx.x >= *ntiles) return; + const int e = tile_e[blockIdx.x], r0 = tile_r0[blockIdx.x], rend = eoff[e] + ecnt[e], n0 = blockIdx.y * FN; + const uint8_t* W = tab[e]; + if (!W) return; // not in this batch (offload): another launch has it + gg_tables(grid, kv); + const int tid = threadIdx.x, ty = tid / 16, tx = tid % 16; + const float* asrc[2]; + int arow_l[2], akq[2]; +#pragma unroll + for (int u = 0; u < 2; ++u) { + const int idx = tid + 256 * u, row = idx / 8, r = r0 + row; + arow_l[u] = row; + akq[u] = idx % 8; + asrc[u] = r < rend ? A + (size_t) (rows ? rows[r] : r) * lda + akq[u] * 4 : nullptr; + } + const int wn = tid / 4, wq = tid % 4, nrow = n0 + wn; + const uint8_t* wp = W + (size_t) (PERM ? gg_perm(nrow, N) : nrow) * rb; + float acc[4][4] = {}; + __syncthreads(); // the tables + for (int k0 = 0; k0 < K; k0 += FKK) { +#pragma unroll + for (int u = 0; u < 2; ++u) { + const float4 v = asrc[u] ? *reinterpret_cast(asrc[u] + k0) : make_float4(0, 0, 0, 0); + const int kk = akq[u] * 4, row = arow_l[u]; + As[kk][row] = v.x; As[kk + 1][row] = v.y; As[kk + 2][row] = v.z; As[kk + 3][row] = v.w; + } + float w[8]; + gg_ld8(wp, k0 + wq * 8, w, grid, kv); +#pragma unroll + for (int j = 0; j < 8; ++j) Ws[wq * 8 + j][wn] = w[j]; + __syncthreads(); +#pragma unroll 8 + for (int kk = 0; kk < FKK; ++kk) { + const float4 a = *reinterpret_cast(&As[kk][ty * 4]); + const float4 b = *reinterpret_cast(&Ws[kk][tx * 4]); + const float av[4] = {a.x, a.y, a.z, a.w}, bv[4] = {b.x, b.y, b.z, b.w}; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < 4; ++j) acc[i][j] += av[i] * bv[j]; + } + __syncthreads(); + } +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int r = r0 + ty * 4 + i; + if (r < rend) + *reinterpret_cast(C + (size_t) r * N + n0 + tx * 4) = make_float4(acc[i][0], acc[i][1], acc[i][2], acc[i][3]); + } +} + +template +__global__ void __launch_bounds__(256) kb_moe_gemm_tc_gg(const half* __restrict__ A, int lda, + const uint8_t* const* __restrict__ tab, size_t rb, + const int* __restrict__ tile_e, const int* __restrict__ tile_r0, + const int* __restrict__ ntiles, const int* __restrict__ eoff, + const int* __restrict__ ecnt, float* __restrict__ C, int N, int K) { + __shared__ __align__(32) unsigned char smraw[TM * TCLD * 4]; + __shared__ uint32_t grid[512]; + __shared__ int8_t kv[16]; + half* As = reinterpret_cast(smraw); + half* Bs = As + TM * TLD; + float* Cs = reinterpret_cast(smraw); + if ((int) blockIdx.x >= *ntiles) return; + const int e = tile_e[blockIdx.x], r0 = tile_r0[blockIdx.x], rend = eoff[e] + ecnt[e], n0 = blockIdx.y * TN; + const uint8_t* W = tab[e]; + if (!W) return; // not in this batch (offload): another launch has it + gg_tables(grid, kv); + const int tid = threadIdx.x, warp = tid / 32, wm = warp / 4, wn = warp % 4; + const int arow = tid / 4, akq = tid % 4; + const half* asrc = r0 + arow < rend ? A + (size_t) (r0 + arow) * lda + akq * 8 : nullptr; + int wn_[2], wq_[2]; + const uint8_t* wp[2]; +#pragma unroll + for (int u = 0; u < 2; ++u) { + const int idx = tid + 256 * u; + wn_[u] = idx / 4; + wq_[u] = idx % 4; + const int nrow = n0 + wn_[u]; + wp[u] = W + (size_t) (PERM ? gg_perm(nrow, N) : nrow) * rb; + } + wmma::fragment c[2][2]; +#pragma unroll + for (int i = 0; i < 2; ++i) +#pragma unroll + for (int j = 0; j < 2; ++j) wmma::fill_fragment(c[i][j], 0.0f); + __syncthreads(); // the tables + uint4 av; + float wv[2][8]; + auto gload = [&](int k0) { + av = asrc ? *reinterpret_cast(asrc + k0) : make_uint4(0, 0, 0, 0); +#pragma unroll + for (int u = 0; u < 2; ++u) gg_ld8(wp[u], k0 + wq_[u] * 8, wv[u], grid, kv); + }; + gload(0); + for (int k0 = 0; k0 < K; k0 += TK) { + *reinterpret_cast(As + arow * TLD + akq * 8) = av; +#pragma unroll + for (int u = 0; u < 2; ++u) { + half2 h[4]; +#pragma unroll + for (int b = 0; b < 4; ++b) h[b] = __floats2half2_rn(wv[u][2 * b], wv[u][2 * b + 1]); + *reinterpret_cast(Bs + wn_[u] * TLD + wq_[u] * 8) = *reinterpret_cast(h); + } + __syncthreads(); + if (k0 + TK < K) gload(k0 + TK); +#pragma unroll + for (int kk = 0; kk < TK; kk += 16) { + wmma::fragment a[2]; + wmma::fragment b[2]; +#pragma unroll + for (int i = 0; i < 2; ++i) wmma::load_matrix_sync(a[i], As + (wm * 32 + i * 16) * TLD + kk, TLD); +#pragma unroll + for (int j = 0; j < 2; ++j) wmma::load_matrix_sync(b[j], Bs + (wn * 32 + j * 16) * TLD + kk, TLD); +#pragma unroll + for (int i = 0; i < 2; ++i) +#pragma unroll + for (int j = 0; j < 2; ++j) wmma::mma_sync(c[i][j], a[i], b[j], c[i][j]); + } + __syncthreads(); + } +#pragma unroll + for (int i = 0; i < 2; ++i) +#pragma unroll + for (int j = 0; j < 2; ++j) + wmma::store_matrix_sync(Cs + (wm * 32 + i * 16) * TCLD + wn * 32 + j * 16, c[i][j], TCLD, wmma::mem_row_major); + __syncthreads(); +#pragma unroll + for (int u = 0; u < 8; ++u) { + const int idx = tid + 256 * u, row = idx / 32, c4 = idx % 32, r = r0 + row; + if (r >= rend) continue; + *reinterpret_cast(C + (size_t) r * N + n0 + c4 * 4) = *reinterpret_cast(Cs + row * TCLD + c4 * 4); + } +} + +// big prompt chunks (INK2_DQ_MIN tokens, --tc): an expert's weights decoded once to fp16 [N][K] (row gg_perm(n) for +// PERM), then a cuBLAS tensor-core GEMM per expert over its rows (the tile GEMMs decode the weights per 64-row tile) +template +__global__ void kb_dequant_gg(const uint8_t* const* __restrict__ tab, int e, size_t rb, half* __restrict__ out, int N, int K) { + __shared__ uint32_t grid[512]; + __shared__ int8_t kv[16]; + gg_tables(grid, kv); + __syncthreads(); + const uint8_t* W = tab[e]; + const size_t n8 = (size_t) N * (K / 8); + for (size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; i < n8; i += (size_t) gridDim.x * blockDim.x) { + const int n = (int) (i / (K / 8)), kc = (int) (i % (K / 8)) * 8; + float w[8]; + gg_ld8(W + (size_t) (PERM ? gg_perm(n, N) : n) * rb, kc, w, grid, kv); + half2 h[4]; +#pragma unroll + for (int b = 0; b < 4; ++b) h[b] = __floats2half2_rn(w[2 * b], w[2 * b + 1]); + *reinterpret_cast(out + (size_t) n * K + kc) = *reinterpret_cast(h); + } +} +// fp32 [T][K] (row stride ld) -> fp16 [T][K]; bf16 -> fp16 (dense weights: exact for |w| >= 2^-14, the rare smaller +// ones lose low bits as fp16 subnormals) +__global__ void kb_f32_to_f16(const float* __restrict__ x, int ld, int K, half* __restrict__ y, size_t n) { + const size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + const size_t t = i / K, k = i % K; + y[i] = __float2half_rn(x[t * ld + k]); +} +__global__ void kb_bf16_to_f16(const uint16_t* __restrict__ src, half* __restrict__ dst, size_t n) { + const size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) dst[i] = __float2half_rn(__uint_as_float((uint32_t) src[i] << 16)); +} + +// Tensor-core attention (--tc 1): block = 64 queries x one q head, 4 warps (16 query rows each), key tiles of 32. +// Q (fp16, prepared in qh [T][QD]) stays in matrix_a fragments; K / V tiles converted fp32 -> fp16 into smem; +// S = Q K^T (fp32 accumulation) goes through smem for scale + bias + mask + online softmax (fp32), P in fp16; +// O stays in accumulator fragments, rescaled per row with a row map of the fragment elements found at start +// (store_matrix_sync of known values: the element -> row mapping is not specified by the API, so it is measured). +constexpr int AQ = 64, AK = 32, ALD = HD + 8, SLD = AK + 4, PLD = AK + 8, AW = 4 * NREP; +static_assert(16 * PLD * 2 <= 16 * SLD * 4, "P aliases S"); +__global__ void __launch_bounds__(128 * NREP, 1) kb_attn_tc(const half* __restrict__ qh, const float* __restrict__ P, int sp, + const void* __restrict__ K, const void* __restrict__ V, + const __half* __restrict__ ksc, const __half* __restrict__ vsc, + const float* __restrict__ rel, int cap, int window, int pos0, int T, + float* __restrict__ out, int nsplit, float* __restrict__ spm, + float* __restrict__ spl, float* __restrict__ spo) { + // nsplit > 1 (verify blocks, T <= AQ): blockIdx.z = key split, partial (max, sum, unnormalized out) per split into + // spm / spl / spo, merged by kb_attn_merge_split; the sink counts in split 0 only. + pos0 = VPOS(pos0); + // GQA group per block: the NREP q heads of kv head g share each K / V tile (loaded and converted once); + // warp w: head g * NREP + w / 4, query rows t0 + (w % 4) * 16. Per warp the computation is unchanged. + // P (fp16) overwrites the warp's own S rows once read; the row map lives in the K / V tile before the loop. + __shared__ __align__(32) half KVs[2 * AK * ALD]; + __shared__ __align__(32) float Ss[AW][16 * SLD]; + __shared__ float ms[AW][16], ls[AW][16], fs[AW][16]; + static_assert(AW * 256 * 4 <= 2 * AK * ALD * 2, "row map fits in the K / V tile"); + half* Ks = KVs; + half* Vs = KVs + AK * ALD; + const int g = blockIdx.y, t0 = blockIdx.x * AQ, tid = threadIdx.x, w = tid / 32, lane = tid % 32; + const int h = g * NREP + w / 4; + const int tw = t0 + (w % 4) * 16; // this warp's first query row + half* Pw = reinterpret_cast(Ss[w]); + int* rmw = reinterpret_cast(KVs) + w * 256; + using FA = wmma::fragment; + using FBc = wmma::fragment; + using FBr = wmma::fragment; + using FC = wmma::fragment; + // row map of accumulator elements + FC probe; + const int ne = probe.num_elements; + for (int i = 0; i < ne; ++i) probe.x[i] = (float) (lane * ne + i); + wmma::store_matrix_sync(Ss[w], probe, SLD, wmma::mem_row_major); + __syncwarp(); + for (int cell = lane; cell < 256; cell += 32) { + const int v = (int) Ss[w][(cell / 16) * SLD + cell % 16]; + rmw[v] = cell / 16; + } + __syncwarp(); + int rowof[8]; + for (int i = 0; i < ne && i < 8; ++i) rowof[i] = rmw[lane * ne + i]; + FA qa[HD / 16]; +#pragma unroll + for (int kd = 0; kd < HD / 16; ++kd) wmma::load_matrix_sync(qa[kd], qh + (size_t) tw * QD + h * HD + kd * 16, QD); + FC o[HD / 16]; +#pragma unroll + for (int n = 0; n < HD / 16; ++n) wmma::fill_fragment(o[n], 0.0f); + const int split = blockIdx.z; + if (lane < 16) { + const int r = tw + lane; + ms[w][lane] = split > 0 ? -INFINITY : r < T ? P[(size_t) r * sp + OFF_SINK + h] : 0.0f; + ls[w][lane] = split > 0 ? 0.0f : 1.0f; + } + const float scale = rsqrtf((float) HD); + const int nq = min(AQ, T - t0); + const int pa = pos0 + t0, pb = pos0 + t0 + nq - 1; + const int lo = window > 0 ? max(0, pa - window + 1) : 0; + const int per = nsplit > 1 ? ((pb - lo + 1 + nsplit - 1) / nsplit + AK - 1) / AK * AK : pb - lo + 1; + const int kb = lo + split * per, ke = min(pb, kb + per - 1); + for (int k0 = kb; k0 <= ke; k0 += AK) { + __syncthreads(); + for (int i = tid; i < AK * HD / 4; i += 128 * NREP) { // float4 units + const int r = i / (HD / 4), d = (i % (HD / 4)) * 4, j = k0 + r; + float4 kv = make_float4(0, 0, 0, 0), vv = kv; + if (j <= pb) { + kv = kv_ld4(K, ksc, (size_t) (j % cap), g * HD + d); + vv = kv_ld4(V, vsc, (size_t) (j % cap), g * HD + d); + } + half2 a[2] = {__floats2half2_rn(kv.x, kv.y), __floats2half2_rn(kv.z, kv.w)}; + half2 b[2] = {__floats2half2_rn(vv.x, vv.y), __floats2half2_rn(vv.z, vv.w)}; + *reinterpret_cast(Ks + r * ALD + d) = *reinterpret_cast(a); + *reinterpret_cast(Vs + r * ALD + d) = *reinterpret_cast(b); + } + __syncthreads(); + if (tw >= T) continue; // whole warp past the chunk (still joins the block barriers) + FC s[AK / 16]; +#pragma unroll + for (int n = 0; n < AK / 16; ++n) { + wmma::fill_fragment(s[n], 0.0f); +#pragma unroll + for (int kd = 0; kd < HD / 16; ++kd) { + FBc kb; + wmma::load_matrix_sync(kb, Ks + n * 16 * ALD + kd * 16, ALD); + wmma::mma_sync(s[n], qa[kd], kb, s[n]); + } + wmma::store_matrix_sync(Ss[w] + n * 16, s[n], SLD, wmma::mem_row_major); + } + __syncwarp(); + { + const int r = lane / 2, c0 = (lane % 2) * 16, t = tw + r, p = pos0 + t; + float sv[16], mx = -INFINITY; +#pragma unroll + for (int c = 0; c < 16; ++c) { + const int j = k0 + c0 + c, dist = p - j; + const bool ok = t < T && j <= p && (window == 0 || dist < window); + sv[c] = ok ? Ss[w][r * SLD + c0 + c] * scale + + (dist < EXTENT ? rel[((size_t) t * NQ + h) * EXTENT + dist] : 0.0f) + : -INFINITY; + mx = fmaxf(mx, sv[c]); + } + mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, 1)); + // (-inf only in a split > 0 with every key so far masked for this row: nothing to rescale, e = 0) + const float mo = ms[w][r], mn = fmaxf(mo, mx), f = mn == -INFINITY ? 1.0f : expf(mo - mn); + float sum = 0.0f; + __syncwarp(); // every S value of the warp read before P overwrites them +#pragma unroll + for (int c = 0; c < 16; ++c) { + const float e = mn == -INFINITY ? 0.0f : expf(sv[c] - mn); + sum += e; + Pw[r * PLD + c0 + c] = __float2half_rn(e); + } + sum += __shfl_xor_sync(0xffffffffu, sum, 1); + __syncwarp(); + if (!(lane % 2)) { ms[w][r] = mn; ls[w][r] = ls[w][r] * f + sum; fs[w][r] = f; } + } + __syncwarp(); + float fr[8]; + for (int i = 0; i < ne && i < 8; ++i) fr[i] = fs[w][rowof[i]]; +#pragma unroll + for (int n = 0; n < HD / 16; ++n) + for (int i = 0; i < ne && i < 8; ++i) o[n].x[i] *= fr[i]; +#pragma unroll + for (int ks = 0; ks < AK / 16; ++ks) { + FA pa_; + wmma::load_matrix_sync(pa_, Pw + ks * 16, PLD); +#pragma unroll + for (int n = 0; n < HD / 16; ++n) { + FBr vb; + wmma::load_matrix_sync(vb, Vs + ks * 16 * ALD + n * 16, ALD); + wmma::mma_sync(o[n], pa_, vb, o[n]); + } + } + } + if (tw >= T) return; + __syncwarp(); + if (nsplit > 1) { // T <= AQ: rows tw.. of split `split`, [nsplit][AQ][...] + if (lane < 16 && tw + lane < T) { + const size_t i = ((size_t) split * AQ + tw + lane) * NQ + h; + spm[i] = ms[w][lane]; + spl[i] = ls[w][lane]; + } +#pragma unroll + for (int n = 0; n < HD / 16; ++n) + wmma::store_matrix_sync(spo + ((size_t) split * AQ + tw) * QD + h * HD + n * 16, o[n], QD, wmma::mem_row_major); + return; + } + float il[8]; + for (int i = 0; i < ne && i < 8; ++i) il[i] = 1.0f / ls[w][rowof[i]]; +#pragma unroll + for (int n = 0; n < HD / 16; ++n) { + for (int i = 0; i < ne && i < 8; ++i) o[n].x[i] *= il[i]; + wmma::store_matrix_sync(out + (size_t) tw * QD + h * HD + n * 16, o[n], QD, wmma::mem_row_major); + } +} + +// merge of kb_attn_tc's key splits: grid (NQ, T), block HD +__global__ void kb_attn_merge_split(const float* __restrict__ spm, const float* __restrict__ spl, + const float* __restrict__ spo, int nsplit, float* __restrict__ out) { + const int h = blockIdx.x, t = blockIdx.y, d = threadIdx.x; + float M = -INFINITY; + for (int s = 0; s < nsplit; ++s) M = fmaxf(M, spm[((size_t) s * AQ + t) * NQ + h]); + float L = 0.0f, O = 0.0f; + for (int s = 0; s < nsplit; ++s) { + const size_t i = ((size_t) s * AQ + t) * NQ + h; + if (spm[i] == -INFINITY) continue; + const float f = expf(spm[i] - M); + L += spl[i] * f; + O += spo[((size_t) s * AQ + t) * QD + h * HD + d] * f; + } + out[(size_t) t * QD + h * HD + d] = O / L; +} + +// SoftcappedSwiGLU on nr rows: gu [nr][2FF] -> act [nr][FF] +__global__ void kb_swiglu(const float* gu, float* act, int nr) { + const size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= (size_t) nr * FF) return; + const size_t k = i / FF, j = i % FF; + const float g = gu[k * 2 * FF + 2 * j], u = gu[k * 2 * FF + 2 * j + 1]; + act[i] = (tanhf(g / GATE_CAP) * GATE_CAP) * (1.0f / (1.0f + expf(-g))) * (tanhf(u / UP_CAP) * UP_CAP); +} + +// expert-ordered fp16 copy of the MoE input: ah[r][k] = fp16(x[rows[r]][k]) (the rounding the TC GEMM applied per tile) +__global__ void kb_gather_h(const float* __restrict__ x, const int* __restrict__ rows, half* __restrict__ ah) { + const int r = blockIdx.x, src = rows[r]; + for (int k = threadIdx.x * 2; k < H; k += blockDim.x * 2) + *reinterpret_cast(ah + (size_t) r * H + k) = + __floats2half2_rn(x[(size_t) src * H + k], x[(size_t) src * H + k + 1]); +} +// kb_swiglu with an fp16 output (the down GEMM's A, same values as converting the fp32 act per tile) +__global__ void kb_swiglu_h(const float* gu, half* act, int nr) { + const size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= (size_t) nr * FF) return; + const size_t k = i / FF, j = i % FF; + const float g = gu[k * 2 * FF + 2 * j], u = gu[k * 2 * FF + 2 * j + 1]; + act[i] = __float2half_rn((tanhf(g / GATE_CAP) * GATE_CAP) * (1.0f / (1.0f + expf(-g))) * (tanhf(u / UP_CAP) * UP_CAP)); +} + +// out[t][i] = sum_k wts[t][k] ey[slot[t][k]][i] (k in routing order, as k_moe_tail); grid (H / 256, T) +__global__ void kb_combine(const float* ey, const int* slot, const float* wts, float* out) { + const int i = blockIdx.x * blockDim.x + threadIdx.x, t = blockIdx.y; + float a = 0.0f; + for (int k = 0; k < TOPK; ++k) a += ey[(size_t) slot[t * TOPK + k] * H + i] * wts[t * TOPK + k]; + out[(size_t) t * H + i] = a; +} + +// routing record (one-token path): rec[pos][k] = ids[k] +__global__ void k_rec_ids(const int* ids, int* rec, const int* d_pos) { + rec[(size_t) (*d_pos) * TOPK + threadIdx.x] = ids[threadIdx.x]; +} +// Expert cache (offload, --vram-reserve-mib). Per pool: owner[slot] = l * NE + e or -1, stamp[slot] = last use (one +// clock for both pools); slot_of[l * NE + e] = slot or -1. k_cache_plan (one block) stamps every id of the call +// first, then gives each miss the least recently used slot (ties: lowest index), so a call never evicts its own +// experts; it points the tables at the slot and queues the copy, which k_fetch does from mapped pinned host memory. +// n ids, duplicates allowed (n = TOPK in decode; T x TOPK for a multi-token verify). +// CBA: 32-bit clock, wraps after ~10M decoded tokens (LRU order then wrong for one pass, results still exact). +struct CacheArgs { + int *slot_of, *owner; + unsigned *stamp, *clock; + int nslot; + const uint8_t **tabA, **tabB; + uint8_t* pool; + size_t eb, partA; + const uint8_t* const* host; // device views of layer l's experts in mapped host memory ([NE]) + const uint8_t** fsrc; + uint8_t** fdst; + int* nfetch; + unsigned long long* fbytes; +}; +constexpr int FETCH_MAX = 64, FETCH_BLOCKS = 96; +__global__ void k_cache_plan(int l, const int* __restrict__ ids, int n, CacheArgs c) { + __shared__ int miss[FETCH_MAX], nm; + __shared__ unsigned clk; + __shared__ unsigned long long wmin[32]; + if (threadIdx.x == 0) { + unsigned t = *c.clock; + int m = 0; + for (int i = 0; i < n; ++i) { + const int e = ids[i]; + bool dup = false; + for (int j = 0; j < i; ++j) dup |= ids[j] == e; + if (dup) continue; + const int sl = c.slot_of[l * NE + e]; + if (sl >= 0) c.stamp[sl] = ++t; + else miss[m++] = e; + } + nm = m; + clk = t; + } + __syncthreads(); + for (int m = 0; m < nm; ++m) { + unsigned long long best = ~0ull; + for (int i = threadIdx.x; i < c.nslot; i += blockDim.x) + best = min(best, ((unsigned long long) c.stamp[i] << 32) | (unsigned) i); +#pragma unroll + for (int o = 16; o; o >>= 1) best = min(best, __shfl_xor_sync(0xffffffffu, best, o)); + if ((threadIdx.x & 31) == 0) wmin[threadIdx.x / 32] = best; + __syncthreads(); + if (threadIdx.x == 0) { + for (int w = 1; w < (int) (blockDim.x / 32); ++w) best = min(best, wmin[w]); + const int v = (int) (best & 0xffffffffu), e = miss[m], key = l * NE + e, old = c.owner[v]; + if (old >= 0) { c.slot_of[old] = -1; c.tabA[old] = nullptr; c.tabB[old] = nullptr; } + uint8_t* d = c.pool + (size_t) v * c.eb; + c.owner[v] = key; + c.slot_of[key] = v; + c.stamp[v] = ++clk; + c.tabA[key] = d; + c.tabB[key] = d + c.partA; + c.fsrc[m] = c.host[e]; + c.fdst[m] = d; + } + __syncthreads(); + } + if (threadIdx.x == 0) { + *c.clock = clk; + *c.nfetch = nm; + *c.fbytes += (unsigned long long) nm * c.eb; + } +} +// queued copies, host -> slot: grid (FETCH_BLOCKS, max copies), 16 B per thread and step, 4 loads in flight +__global__ void k_fetch(const uint8_t* const* __restrict__ fsrc, uint8_t* const* __restrict__ fdst, + const int* __restrict__ nfetch, size_t bytes) { + if ((int) blockIdx.y >= *nfetch) return; + const uint4* src = reinterpret_cast(fsrc[blockIdx.y]); + uint4* dst = reinterpret_cast(fdst[blockIdx.y]); + const size_t n = bytes / 16, st = (size_t) gridDim.x * blockDim.x; + size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; + for (; i + 3 * st < n; i += 4 * st) { + const uint4 a = src[i], b = src[i + st], cc = src[i + 2 * st], d = src[i + 3 * st]; + dst[i] = a; dst[i + st] = b; dst[i + 2 * st] = cc; dst[i + 3 * st] = d; + } + for (; i < n; i += st) dst[i] = src[i]; +} + +// --kv-grow: slots [from, to) leave a pool: their experts out of the tables (the next use fetches them again) +__global__ void k_pool_evict(int* owner, int* slot_of, const uint8_t** tabA, const uint8_t** tabB, unsigned* stamp, + int from, int to) { + const int s = from + (int) (blockIdx.x * blockDim.x + threadIdx.x); + if (s >= to) return; + const int o = owner[s]; + if (o >= 0) { slot_of[o] = -1; tabA[o] = nullptr; tabB[o] = nullptr; owner[s] = -1; } + stamp[s] = 0; +} + +// teacher-forced routing (verification): the recorded experts, weights from this pass' own scores; grid T, block 32 +__global__ void kb_router_forced(const float* logits, const int* forced, int* ids, float* wts) { + const int t = blockIdx.x, k = threadIdx.x; + if (k) return; + float sc[TOPK], sum = 0.0f; + for (int j = 0; j < TOPK; ++j) { + sc[j] = 1.0f / (1.0f + expf(-logits[(size_t) t * NE + forced[t * TOPK + j]])); + sum += sc[j]; + } + for (int j = 0; j < TOPK; ++j) { ids[t * TOPK + j] = forced[t * TOPK + j]; wts[t * TOPK + j] = sc[j] / (sum + 1e-20f) * ROUTE_SCALE; } +} + +__global__ void kb_add(const float* a, const float* b, float* y, size_t n) { + const size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) y[i] = a[i] + b[i]; +} + +// --------------------------------------------------------------------------------------------------------------------- +// Checkpoint and weights + +struct Ckpt { + std::string path; + StFile st; + const StTensor& t(const std::string& name) const { + auto it = st.tensors.find(name); + if (it == st.tensors.end()) { std::fprintf(stderr, "missing tensor %s\n", name.c_str()); std::exit(1); } + return it->second; + } + std::vector bytes(const std::string& name) const { + std::vector b; + const std::string e = strata::image::st_read_tensor(path, st, t(name), b); + if (!e.empty()) { std::fprintf(stderr, "%s\n", e.c_str()); std::exit(1); } + return b; + } + vec f32(const std::string& name) const { + const StTensor& d = t(name); + auto b = bytes(name); + vec out; + if (d.dtype == "F32") { + out.resize(b.size() / 4); + std::memcpy(out.data(), b.data(), b.size()); + } else if (d.dtype == "BF16") { + out.resize(b.size() / 2); + for (size_t i = 0; i < out.size(); ++i) { + uint32_t u = (uint32_t) (b[2 * i] | (b[2 * i + 1] << 8)) << 16; + std::memcpy(&out[i], &u, 4); + } + } else { std::fprintf(stderr, "%s: dtype %s\n", name.c_str(), d.dtype.c_str()); std::exit(1); } + return out; + } +}; + +size_t g_vram = 0; + +void* dalloc(size_t bytes) { + if (!bytes) return nullptr; // an empty pool (GGUF: no MXFP8 slots) + void* d = nullptr; + CK(cudaMalloc(&d, bytes)); + CK(cudaMemset(d, 0, bytes)); + g_vram += bytes; + return d; +} +float* dfloats(size_t n) { return (float*) dalloc(n * 4); } +void* upload(const void* p, size_t bytes) { + void* d = dalloc(bytes); + if (!d) return nullptr; + CK(cudaMemcpy(d, p, bytes, cudaMemcpyHostToDevice)); + return d; +} +float* dvec(const vec& v) { return (float*) upload(v.data(), v.size() * 4); } +// --------------------------------------------------------------------------------------------------------------------- +// Growable device ranges (CUDA virtual memory): an address range reserved once, physical chunks of the allocation +// granularity mapped and unmapped at its end. The addresses never move. Driver entry points resolved at run time +// (no link to libcuda), as in src/core/vmm.cpp. +#if defined(STRATA_USE_HIP) +struct Vmm { + bool ok = false; + size_t gran = 0; + int dev = 0; +}; +Vmm g_vmm; +void vmm_init() { +#if defined(HIP_VERSION_MAJOR) && HIP_VERSION_MAJOR >= 6 + Vmm& a = g_vmm; + CK(cudaGetDevice(&a.dev)); + int vmm = 0; + if (hipDeviceGetAttribute(&vmm, hipDeviceAttributeVirtualMemoryManagementSupported, a.dev) != hipSuccess || !vmm) { + std::fprintf(stderr, "--kv-grow: HIP virtual memory management is not supported on this device\n"); + std::exit(1); + } + hipMemAllocationProp prop{}; + prop.type = hipMemAllocationTypePinned; + prop.requestedHandleType = hipMemHandleTypeNone; + prop.location.type = hipMemLocationTypeDevice; + prop.location.id = a.dev; + size_t g = 0; + if (hipMemGetAllocationGranularity(&g, &prop, hipMemAllocationGranularityMinimum) != hipSuccess || !g) { + std::fprintf(stderr, "--kv-grow: no allocation granularity\n"); + std::exit(1); + } + const size_t want = 2ull << 20; + a.gran = g >= want ? g : (want + g - 1) / g * g; + a.ok = true; +#else + std::fprintf(stderr, "--kv-grow: HIP virtual memory management requires ROCm 6+\n"); + std::exit(1); +#endif +} +struct VRange { + void* base = nullptr; + size_t reserved = 0, mapped = 0; +#if defined(HIP_VERSION_MAJOR) && HIP_VERSION_MAJOR >= 6 + std::vector h; +#endif + void* ptr() const { return base; } + static size_t up(size_t b) { return (b + g_vmm.gran - 1) / g_vmm.gran * g_vmm.gran; } + void init(size_t bytes) { +#if defined(HIP_VERSION_MAJOR) && HIP_VERSION_MAJOR >= 6 + reserved = up(std::max(bytes, 1)); + if (hipMemAddressReserve(&base, reserved, 0, nullptr, 0) != hipSuccess) { + std::fprintf(stderr, "hipMemAddressReserve of %zu bytes failed\n", reserved); + std::exit(1); + } +#else + (void) bytes; +#endif + } + size_t need(size_t bytes) const { return std::min(up(bytes), reserved); } + bool map_to(size_t bytes) { +#if defined(HIP_VERSION_MAJOR) && HIP_VERSION_MAJOR >= 6 + const size_t want = need(bytes); + hipMemAllocationProp prop{}; + prop.type = hipMemAllocationTypePinned; + prop.requestedHandleType = hipMemHandleTypeNone; + prop.location.type = hipMemLocationTypeDevice; + prop.location.id = g_vmm.dev; + hipMemAccessDesc acc{}; + acc.location = prop.location; + acc.flags = hipMemAccessFlagsProtReadWrite; + while (mapped < want) { + hipMemGenericAllocationHandle_t hd = nullptr; + if (hipMemCreate(&hd, g_vmm.gran, &prop, 0) != hipSuccess) { + (void) hipGetLastError(); + return false; + } + void* addr = static_cast(base) + mapped; + if (hipMemMap(addr, g_vmm.gran, 0, hd, 0) != hipSuccess || + hipMemSetAccess(addr, g_vmm.gran, &acc, 1) != hipSuccess) { + std::fprintf(stderr, "hipMemMap failed\n"); + std::exit(1); + } + h.push_back(hd); + mapped += g_vmm.gran; + g_vram += g_vmm.gran; + } + return true; +#else + (void) bytes; + return false; +#endif + } + void unmap_to(size_t bytes) { +#if defined(HIP_VERSION_MAJOR) && HIP_VERSION_MAJOR >= 6 + const size_t want = need(bytes); + while (mapped > want) { + mapped -= g_vmm.gran; + (void) hipMemUnmap(static_cast(base) + mapped, g_vmm.gran); + (void) hipMemRelease(h.back()); + h.pop_back(); + g_vram -= g_vmm.gran; + } +#else + (void) bytes; +#endif + } +}; +#else +struct Vmm { + bool ok = false; + size_t gran = 0; + int dev = 0; + decltype(&cuMemAddressReserve) reserve = nullptr; + decltype(&cuMemCreate) create = nullptr; + decltype(&cuMemRelease) release = nullptr; + decltype(&cuMemMap) map = nullptr; + decltype(&cuMemUnmap) unmap = nullptr; + decltype(&cuMemSetAccess) access = nullptr; +}; +Vmm g_vmm; +template bool vmm_resolve(const char* name, F& f) { + cudaDriverEntryPointQueryResult q{}; + void* p = nullptr; +#if CUDART_VERSION >= 12050 + const cudaError_t e = cudaGetDriverEntryPointByVersion(name, &p, 12000, cudaEnableDefault, &q); +#else + const cudaError_t e = cudaGetDriverEntryPoint(name, &p, cudaEnableDefault, &q); +#endif + if (e != cudaSuccess || q != cudaDriverEntryPointSuccess || !p) { (void) cudaGetLastError(); return false; } + f = (F) p; + return true; +} +void vmm_init() { + Vmm& a = g_vmm; + decltype(&cuMemGetAllocationGranularity) granularity = nullptr; + CK(cudaGetDevice(&a.dev)); + if (!vmm_resolve("cuMemGetAllocationGranularity", granularity) || !vmm_resolve("cuMemAddressReserve", a.reserve) || + !vmm_resolve("cuMemCreate", a.create) || !vmm_resolve("cuMemRelease", a.release) || !vmm_resolve("cuMemMap", a.map) || + !vmm_resolve("cuMemUnmap", a.unmap) || !vmm_resolve("cuMemSetAccess", a.access)) { + std::fprintf(stderr, "--kv-grow: the driver's virtual memory entry points are missing\n"); + std::exit(1); + } + CUmemAllocationProp prop{}; + prop.type = CU_MEM_ALLOCATION_TYPE_PINNED; + prop.location.type = CU_MEM_LOCATION_TYPE_DEVICE; + prop.location.id = a.dev; + if (granularity(&a.gran, &prop, CU_MEM_ALLOC_GRANULARITY_MINIMUM) != CUDA_SUCCESS || !a.gran) { + std::fprintf(stderr, "--kv-grow: no allocation granularity\n"); + std::exit(1); + } + a.ok = true; +} +struct VRange { + CUdeviceptr base = 0; + size_t reserved = 0, mapped = 0; + std::vector h; + void* ptr() const { return (void*) base; } + static size_t up(size_t b) { return (b + g_vmm.gran - 1) / g_vmm.gran * g_vmm.gran; } + void init(size_t bytes) { + reserved = up(std::max(bytes, 1)); + if (g_vmm.reserve(&base, reserved, 0, 0, 0) != CUDA_SUCCESS) { + std::fprintf(stderr, "cuMemAddressReserve of %zu bytes failed\n", reserved); + std::exit(1); + } + } + size_t need(size_t bytes) const { return std::min(up(bytes), reserved); } // mapped bytes for `bytes` + bool map_to(size_t bytes) { // false: out of memory (what was mapped stays) + const size_t want = need(bytes); + CUmemAllocationProp prop{}; + prop.type = CU_MEM_ALLOCATION_TYPE_PINNED; + prop.location.type = CU_MEM_LOCATION_TYPE_DEVICE; + prop.location.id = g_vmm.dev; + CUmemAccessDesc acc{}; + acc.location = prop.location; + acc.flags = CU_MEM_ACCESS_FLAGS_PROT_READWRITE; + while (mapped < want) { + CUmemGenericAllocationHandle hd = 0; + if (g_vmm.create(&hd, g_vmm.gran, &prop, 0) != CUDA_SUCCESS) return false; + if (g_vmm.map(base + mapped, g_vmm.gran, 0, hd, 0) != CUDA_SUCCESS || + g_vmm.access(base + mapped, g_vmm.gran, &acc, 1) != CUDA_SUCCESS) { + std::fprintf(stderr, "cuMemMap failed\n"); + std::exit(1); + } + h.push_back(hd); + mapped += g_vmm.gran; + g_vram += g_vmm.gran; + } + return true; + } + void unmap_to(size_t bytes) { + const size_t want = need(bytes); + while (mapped > want) { + mapped -= g_vmm.gran; + g_vmm.unmap(base + mapped, g_vmm.gran); + g_vmm.release(h.back()); + h.pop_back(); + g_vram -= g_vmm.gran; + } + } +}; +#endif + +struct DMat { + const uint16_t* d = nullptr; // BF16 [n][k] + int n = 0, k = 0; + const int8_t* q = nullptr; // or Q8_0 (GGUF): codes [n][k], fp16 scales [n][k / 32] + const __half* qs = nullptr; +}; + +// Experts live in fixed-size slots of a device pool (one pool per format), each slot one expert as +// [w13 | w13 scales | w2 | w2 scales] (part A = w13 + scales, part B = w2 + scales). The kernels address an expert +// through tA / tB (device tables, NE part pointers per layer, slices of E.tabA / E.tabB). +struct Experts { + bool nvfp4 = true; + const uint8_t* const* tA = nullptr; + const uint8_t* const* tB = nullptr; + const float *f13 = nullptr, *f2 = nullptr; + int gg13 = 0, gg2 = 0; // GGUF: ggml types of gate_up (part A) and down (part B), 0 = the checkpoint formats + size_t rb13 = 0, rb2 = 0; // bytes per row +}; +constexpr size_t NV_A = (size_t) 2 * FF * H / 2 + (size_t) 2 * FF * H / 16, NV_B = (size_t) H * FF / 2 + (size_t) H * FF / 16; +constexpr size_t MX_A = (size_t) 2 * FF * H + (size_t) 2 * FF * H / 32, MX_B = (size_t) H * FF + (size_t) H * FF / 32; +constexpr size_t NV_BYTES = NV_A + NV_B, MX_BYTES = MX_A + MX_B; // 4478976 / 8211456 +static_assert(NV_A % 256 == 0 && NV_BYTES % 256 == 0 && MX_A % 256 == 0 && MX_BYTES % 256 == 0, "slot alignment"); + +struct Gate { DMat down, fg; }; // fg: [forget; gain] stacked [2H, GATE_RANK] + +struct Layer { + bool full = false, loop = false; + // proj: [wq 3072; gate_attn 3072; wr 384; sink 24; wk 1024; (k_wproj 32); wv 1024; (v_wproj 32)] stacked, K = H: + // one launch when the query, key and value inputs are the same vector, three otherwise + DMat proj, wo, router; + int off_k = 0, off_v = 0, n_k = 0, n_v = 0; + const float *q_scale, *rel_scale, *rel_proj, *k_conv = nullptr, *v_conv = nullptr, *k_static = nullptr, + *v_static = nullptr, *attn_conv, *mlp_conv, *attn_norm = nullptr, *q_norm = nullptr, + *k_norm = nullptr, *v_norm = nullptr, *mlp_norm, *attn_query = nullptr, *mlp_query, *router_bias; + Experts ex; + Gate gates[4]; +}; + +struct Slot { + void *K, *V; // [cap][KVD] fp32 / fp16 / int8 codes with ksc / vsc (--kv, see kv_st) + __half *ksc = nullptr, *vsc = nullptr; // [cap][KVD / KVG] + int cap = 0; + bool full = false; + float *khist, *vhist, *ahist, *mhist; // [HR][C] +}; + +struct Bells { ink2cpu::InkBell* b[2]; }; // device views of the per-node doorbells +constexpr int SYNC_MAX = 2; // misses of a visit computed on the GPU over PCIe (the PCIe share), at most +struct SyncArgs { // the PCIe share's state, for k_cache_cpu and k_cpu_wait + const uint8_t* const* xsrc; // [NL * NE] device views of the experts in host memory + const uint8_t** tabA; + const uint8_t** tabB; + uint8_t* stage; // [SYNC_MAX] staging slots of MX_BYTES + const uint8_t** fsrc; + uint8_t** fdst; + int* nfetch; + int* keys; // [SYNC_MAX] the visit's PCIe experts (their table entries point at the staging) + unsigned long long* fbytes; + const uint8_t* home; // [NL * NE] node of each expert + float us_nv, us_mx; // one expert over PCIe, us (0: the share off) + float margin; // us the GPU side adds to the copies (its GEMVs, the background copies' PCIe) +}; + +struct Engine { + const Ckpt* ck = nullptr; + int ctx = 8192, nchunk_full = 0, nchunk_slide = WINDOW / CHUNK; + std::vector embed; // host BF16 + std::vector embed_q8; // or (GGUF) host Q8_0 rows of H / 32 blocks + const float *embed_norm, *norm, *final_query, *msg_queries; + DMat unembed; + Layer L[NL]; + Slot S[NCALLS]; + int* d_pos; + // activations + float *h, *out, *Bbuf, *preB, *pre_h, *prev_stack, *msgs; + float *a, *t[4], *xq, *xk, *xv, *q, *k, *v, *kc, *vc, *dw, *rs, *rel, *sink, *gate, *att, *attn_out, *att2, *r; + float *m, *mn, *cat, *gdown, *gf, *gg, *rl, *wts, *gu, *act, *ey, *moe, *y2, *logits; + float *pm, *pl, *po, *emb_in, *pout, *gfg; + int* ids; + bool graph = true; + cudaGraphExec_t exec = nullptr; + int* rec = nullptr; // routing record / forcing [NCALLS][ctx][TOPK] (verification only) + int rec_mode = 0; // 1 record (one-token path), 2 force (prefill) + bool grow = false; // --kv-grow 1: the full-attention slots' K/V mapped as the context grows (VRange), the expert + int grow_step = 8192; // pools (offload) give memory up and take it back (--kv-grow-step cells) + int kv_cells = 0; // cells mapped now + int kvm = 1; // --kv f32 (0) | f16 (1, default) | i8 (2: int8 cells + fp16 scale per 64, Strata's kv_q8 + // layout) | i8r (3: i8 + Walsh-Hadamard rotation) + // experts: every expert in layout order (NVFP4 layers 0-19 then MXFP8 layers 20-23, NE per layer, one slot + // each); resident = the device pool holds them all, in that order + uint8_t *pool_nv = nullptr, *pool_mx = nullptr; + const uint8_t **tabA = nullptr, **tabB = nullptr; // device [NL * NE]: part A / part B of expert (l, e) + std::vector htabA, htabB; // host mirrors + // offload (--vram-reserve-mib N: leave N MiB of the card free, the expert pools take what remains): every expert + // in mapped host memory (xh), the pools hold nslot_nv / nslot_mx of them, LRU (k_cache_plan) + int reserve_mib = -1; // < 0: everything resident + bool offload = false; + std::vector xh; // [NL * NE] host address of expert (l, e) (regions placed per NUMA node) + std::vector home; // [NL * NE] its node + const uint8_t** xsrc_d = nullptr; // device [NL * NE]: its device view (mapped) + std::vector> regions; + int nslot_nv = 0, nslot_mx = 0; + // CPU experts (--cpu-threads N, with offload): misses of a decode visit computed on the CPU (ink2_cpu), wanted + // experts promoted into the pools in the background (copied during the next token, committed at its end) + int cpu_threads = 0; + bool cpu = false; + int cpu_nodes = 1; + // one doorbell per node, in that node's memory: its pool reads and writes local memory only, the GPU crosses + ink2cpu::InkBell* bell[2] = {}; + Bells bell_d = {}; + const uint8_t* home_d = nullptr; // [NL * NE] the node holding expert (l, e) (E.home) + unsigned *d_seq = nullptr, *d_cur = nullptr; + int *vjob = nullptr, *nvjob = nullptr; // a --spec verify visit's CPU jobs: [BELL_J] row of PF.ey | node << 16 + float* cnt = nullptr; // [NL * NE] decayed use counts (placement) + SyncArgs sync = {}; // the PCIe share + int *want_nv = nullptr, *want_mx = nullptr, *nwant_nv = nullptr, *nwant_mx = nullptr; + int *pend_nv = nullptr, *pend_mx = nullptr, *npend_nv = nullptr, *npend_mx = nullptr; // [i] = key, [PMAX + i] = slot + const uint8_t **psrc_nv = nullptr, **psrc_mx = nullptr; // promotion copies (k_fetch lists of their own) + uint8_t **pdst_nv = nullptr, **pdst_mx = nullptr; + int *pnf_nv = nullptr, *pnf_mx = nullptr; + std::vector hf13, hf2; // [NL * NE] host copies of the NVFP4 factors (1 for MXFP8) + cudaStream_t side = nullptr; + cudaEvent_t ev_fork = nullptr, ev_join = nullptr; + VRange vpool_nv, vpool_mx; // --kv-grow: the pools as growable ranges (owner / stamp sized for every expert) + int *slot_of = nullptr, *owner_nv = nullptr, *owner_mx = nullptr, *nfetch = nullptr; + unsigned *stamp_nv = nullptr, *stamp_mx = nullptr, *clock = nullptr; + const uint8_t** fsrc = nullptr; + uint8_t** fdst = nullptr; + unsigned long long* fbytes = nullptr; +}; +// GGUF (--model FILE.gguf): slots [gate_up rows | down rows]; one format for every layer, every slot in pool_nv; or one +// for layers < MXFP8_FIRST and another after (g_gg_two, ink2_gguf_experts.cuh): offload uses both pools as the checkpoint +bool g_is_gguf = false, g_gg_two = false; +size_t g_gg_a[2] = {}, g_gg_b[2] = {}; // GGUF part A / part B bytes of an expert: layers < MXFP8_FIRST [0], after [1] +bool ex_nv(int l) { return (g_is_gguf && !g_gg_two) || l < MXFP8_FIRST; } // the layer's experts live in pool_nv (offload) +size_t ex_bytes(int l) { const int r = l >= MXFP8_FIRST; return g_is_gguf ? g_gg_a[r] + g_gg_b[r] : r ? MX_BYTES : NV_BYTES; } +size_t ex_partA(int l) { const int r = l >= MXFP8_FIRST; return g_is_gguf ? g_gg_a[r] : r ? MX_A : NV_A; } +size_t ex_layer_off(int l) { // offset of layer l's first expert in the resident / host layout + return l < MXFP8_FIRST ? (size_t) l * NE * ex_bytes(0) + : (size_t) MXFP8_FIRST * NE * ex_bytes(0) + (size_t) (l - MXFP8_FIRST) * NE * ex_bytes(NL - 1); +} +size_t pool_slot(bool nv) { return ex_bytes(nv ? 0 : NL - 1); } // bytes of a pool_nv / pool_mx slot (offload) +int g_slot = 0; // the layer application being built (host side, baked into the launches) +bool g_verify_tc = false; // --verify-tc 1: small-T dense products on tensor cores (k_gemv_bf16_tc) +int g_rpw = 4; // decode GEMV rows per warp, upper bound (INK2_RPW: 1, 2, 4, 8) +int g_sel_rpw = 2; // expert (selected) GEMV rows per warp (INK2_SEL_RPW: 1, 2, 4, 8) +int g_grp_r = 4; // small-T grouped expert GEMV rows per warp (INK2_GRP_R: 1, 2, 4) +int g_gemv_min_blocks = 164; // bf16 GEMV: R halved until the grid has this many blocks (2 per SM; INK2_GEMV_MINB) + +Engine E; + +DMat dmat(const std::string& name) { + const StTensor& t = E.ck->t(name); + DMat m; + m.n = (int) t.shape[0]; + m.k = 1; + for (size_t i = 1; i < t.shape.size(); ++i) m.k *= (int) t.shape[i]; + auto b = E.ck->bytes(name); + m.d = (const uint16_t*) upload(b.data(), b.size()); + return m; +} +const float* fvec(const std::string& name) { return dvec(E.ck->f32(name)); } + +DMat dmat_stack(const std::vector& names) { // BF16 matrices with the same K, rows concatenated + std::vector all; + DMat m; + for (const auto& n : names) { + const StTensor& t = E.ck->t(n); + int k = 1; + for (size_t i = 1; i < t.shape.size(); ++i) k *= (int) t.shape[i]; + if (m.k && k != m.k) { std::fprintf(stderr, "%s: K %d != %d\n", n.c_str(), k, m.k); std::exit(1); } + m.k = k; + m.n += (int) t.shape[0]; + auto b = E.ck->bytes(n); + all.insert(all.end(), b.begin(), b.end()); + } + m.d = (const uint16_t*) upload(all.data(), all.size()); + return m; +} + +// the NUMA node of the GPU (sysfs), -1 when unknown +int gpu_node() { + char bus[32] = {0}; + if (cudaDeviceGetPCIBusId(bus, sizeof bus, 0) != cudaSuccess) return -1; + std::string id(bus); + for (char& c : id) c = (char) std::tolower((unsigned char) c); + FILE* f = std::fopen(("/sys/bus/pci/devices/" + id + "/numa_node").c_str(), "r"); + if (!f) return -1; + int n = -1; + if (std::fscanf(f, "%d", &n) != 1) n = -1; + std::fclose(f); + return n; +} + +// the experts' memory (load / load_gguf, once ex_bytes is known): resident, the device pools; offload, host regions +// per NUMA node (E.xh / E.home / E.xsrc_d); the part tables +void expert_memory() { + if (E.reserve_mib < 0 && g_is_gguf) { // GGUF resident: every layer in pool_nv (one or two formats) + E.pool_nv = (uint8_t*) dalloc(ex_layer_off(NL)); + } else if (E.reserve_mib < 0) { + E.pool_nv = (uint8_t*) dalloc((size_t) MXFP8_FIRST * NE * NV_BYTES); + E.pool_mx = (uint8_t*) dalloc((size_t) (NL - MXFP8_FIRST) * NE * MX_BYTES); + } else { + // every expert in host memory, registered (mapped) for the copies. CPU experts on several nodes: each expert + // whole on one node, alternating (a node's threads read local memory only); else all on the GPU's node. + E.offload = true; + E.cpu_nodes = E.cpu ? ink2cpu::nodes() : 1; + const int gnode = gpu_node(); + E.xh.assign((size_t) NL * NE, nullptr); + E.home.assign((size_t) NL * NE, 0); + std::vector dev((size_t) NL * NE, nullptr); + for (int n = 0; n < E.cpu_nodes; ++n) { + size_t bytes = 0; + for (int k = 0; k < NL * NE; ++k) { + E.home[k] = E.cpu_nodes > 1 ? (uint8_t) (k % E.cpu_nodes) : 0; + if (E.home[k] == n) bytes += ex_bytes(k / NE); + } + const int place = E.cpu_nodes > 1 ? n : std::max(gnode, 0); + uint8_t* reg = (uint8_t*) ink2cpu::node_alloc(bytes, place); + if (!reg) { std::fprintf(stderr, "cannot map %.2f GiB of host memory for the experts\n", bytes / 1073741824.0); std::exit(1); } + CK(cudaHostRegister(reg, bytes, cudaHostRegisterMapped | cudaHostRegisterPortable)); + void* dv = nullptr; + CK(cudaHostGetDevicePointer(&dv, reg, 0)); + E.regions.push_back({reg, bytes}); + size_t off = 0; + for (int k = 0; k < NL * NE; ++k) + if (E.home[k] == n) { + E.xh[k] = reg + off; + dev[k] = (const uint8_t*) dv + off; + off += ex_bytes(k / NE); + } + } + E.xsrc_d = (const uint8_t**) upload(dev.data(), dev.size() * sizeof(void*)); + } + E.hf13.assign((size_t) NL * NE, 1.0f); + E.hf2.assign((size_t) NL * NE, 1.0f); + E.tabA = (const uint8_t**) dalloc((size_t) NL * NE * sizeof(void*)); + E.tabB = (const uint8_t**) dalloc((size_t) NL * NE * sizeof(void*)); + E.htabA.assign((size_t) NL * NE, nullptr); + E.htabB.assign((size_t) NL * NE, nullptr); +} + +void load() { + const Ckpt& ck = *E.ck; + const std::string p = "model.llm."; + E.embed_norm = fvec(p + "embed_norm.weight"); + E.norm = fvec(p + "norm.weight"); + E.final_query = fvec(p + "attn_res.output_query"); + { + auto b = ck.bytes(p + "embed.weight"); + E.embed.resize(b.size() / 2); + std::memcpy(E.embed.data(), b.data(), b.size()); + } + E.unembed = dmat(p + "unembed.weight"); + { + const vec q = ck.f32(p + "middle_cycle_cross_pass_queries"), kv = ck.f32(p + "middle_cycle_cross_pass_kv_queries"); + vec mq((size_t) NLOOP * 4 * H); + for (int i = 0; i < NLOOP; ++i) { + const float* src[4] = {&q[(size_t) (2 * i) * H], &kv[(size_t) (2 * i) * H], &kv[(size_t) (2 * i + 1) * H], + &q[(size_t) (2 * i + 1) * H]}; + for (int j = 0; j < 4; ++j) std::memcpy(&mq[((size_t) i * 4 + j) * H], src[j], H * 4); + } + E.msg_queries = dvec(mq); + } + expert_memory(); + for (int l = 0; l < NL; ++l) { + Layer& Y = E.L[l]; + const std::string q = p + "layers." + std::to_string(l) + "."; + Y.full = full_layer(l); + Y.loop = l >= LOOP_BEGIN && l < LOOP_END; + { + std::vector parts = {q + "attn.wq_du.weight", q + "attn.gate_attn.weight", q + "attn.wr_du.weight", + q + "attn.attn_sink_proj.weight", q + "attn.wk_dv.weight"}; + if (Y.full) parts.push_back(q + "attn.k_sconv.weight_proj"); + parts.push_back(q + "attn.wv_dv.weight"); + if (Y.full) parts.push_back(q + "attn.v_sconv.weight_proj"); + Y.proj = dmat_stack(parts); + Y.off_k = OFF_K; + Y.n_k = KVD + (Y.full ? NKV * KC : 0); + Y.off_v = Y.off_k + Y.n_k; + Y.n_v = Y.n_k; + if (Y.proj.n != Y.off_v + Y.n_v) { std::fprintf(stderr, "layer %d: stacked rows %d\n", l, Y.proj.n); std::exit(1); } + } + Y.wo = dmat(q + "attn.wo_ud.weight"); + Y.router = dmat(q + "mlp.gate.weight"); + Y.router_bias = fvec(q + "mlp.gate.bias"); + Y.q_scale = fvec(q + "attn.q_l2_clip.scale"); + Y.rel_scale = fvec(q + "attn.rel_l2_clip.scale"); + Y.rel_proj = fvec(q + "attn.rel_logits_proj.proj"); + Y.attn_conv = fvec(q + "attn_sconv.weight"); + Y.mlp_conv = fvec(q + "mlp_sconv.weight"); + Y.mlp_norm = fvec(q + "mlp_norm.weight"); + if (Y.full) { + Y.k_static = fvec(q + "attn.k_sconv.static_w"); + Y.v_static = fvec(q + "attn.v_sconv.static_w"); + Y.q_norm = fvec(q + "q_input_norm.weight"); + Y.k_norm = fvec(q + "k_input_norm.weight"); + Y.v_norm = fvec(q + "v_input_norm.weight"); + } else { + Y.k_conv = fvec(q + "attn.k_sconv.weight"); + Y.v_conv = fvec(q + "attn.v_sconv.weight"); + Y.attn_norm = fvec(q + "attn_norm.weight"); + } + if (l > 0) Y.attn_query = fvec(p + "attn_res.attn_queries." + std::to_string(l - 1)); + Y.mlp_query = fvec(p + "attn_res.mlp_queries." + std::to_string(l)); + if (Y.loop) { + const char* names[4] = {"attn", "k", "v", "mlp"}; + for (int g = 0; g < 4; ++g) { + const std::string c = q + "controllers." + names[g] + "."; + Y.gates[g] = {dmat(c + "down_weight"), dmat_stack({c + "forget_weight", c + "gain_weight"})}; + } + } + Experts& X = Y.ex; + X.nvfp4 = l < MXFP8_FIRST; + { // the four expert tensors interleaved into one slot per expert, then the layer into its pool range + const auto w13 = ck.bytes(q + "mlp.experts.w13_weight"), s13 = ck.bytes(q + "mlp.experts.w13_weight_scale"); + const auto w2 = ck.bytes(q + "mlp.experts.w2_weight"), s2 = ck.bytes(q + "mlp.experts.w2_weight_scale"); + const size_t a = w13.size() / NE, b = s13.size() / NE, c = w2.size() / NE, d = s2.size() / NE, eb = ex_bytes(l); + if (a + b + c + d != eb || a + b != ex_partA(l)) { std::fprintf(stderr, "layer %d: expert bytes %zu\n", l, a + b + c + d); std::exit(1); } + std::vector lay(E.offload ? 0 : (size_t) NE * eb); + for (int e = 0; e < NE; ++e) { + uint8_t* o = E.offload ? E.xh[(size_t) l * NE + e] : lay.data() + (size_t) e * eb; + std::memcpy(o, w13.data() + e * a, a); + std::memcpy(o + a, s13.data() + e * b, b); + std::memcpy(o + a + b, w2.data() + e * c, c); + std::memcpy(o + a + b + c, s2.data() + e * d, d); + } + if (!E.offload) { // resident: the layer's range of its pool (offload: setup_offload fills the pools) + uint8_t* dst = (X.nvfp4 ? E.pool_nv : E.pool_mx) + ex_layer_off(l) - (X.nvfp4 ? 0 : ex_layer_off(MXFP8_FIRST)); + CK(cudaMemcpy(dst, lay.data(), lay.size(), cudaMemcpyHostToDevice)); + for (int e = 0; e < NE; ++e) { + E.htabA[l * NE + e] = dst + (size_t) e * eb; + E.htabB[l * NE + e] = dst + (size_t) e * eb + ex_partA(l); + } + } + X.tA = E.tabA + (size_t) l * NE; + X.tB = E.tabB + (size_t) l * NE; + } + if (X.nvfp4) { + const vec a13 = ck.f32(q + "mlp.experts.w13_weight_amax"), d13 = ck.f32(q + "mlp.experts.w13_weight_outer_scale_denominator"); + const vec a2 = ck.f32(q + "mlp.experts.w2_weight_amax"), d2 = ck.f32(q + "mlp.experts.w2_weight_outer_scale_denominator"); + vec f13(NE), f2(NE); + for (int e = 0; e < NE; ++e) { + f13[e] = a13[e] / d13[0]; + f2[e] = a2[e] / d2[0]; + E.hf13[(size_t) l * NE + e] = f13[e]; + E.hf2[(size_t) l * NE + e] = f2[e]; + } + X.f13 = dvec(f13); + X.f2 = dvec(f2); + } + std::fprintf(stderr, "\rloaded layer %d/%d, %.1f GiB in VRAM", l + 1, NL, g_vram / 1073741824.0); + } + std::fprintf(stderr, "\n"); + if (!E.offload) { + CK(cudaMemcpy(E.tabA, E.htabA.data(), E.htabA.size() * sizeof(void*), cudaMemcpyHostToDevice)); + CK(cudaMemcpy(E.tabB, E.htabB.data(), E.htabB.size() * sizeof(void*), cudaMemcpyHostToDevice)); + } +} + +// --------------------------------------------------------------------------------------------------------------------- +// GGUF reader (one file, mapped read-only) and the loader for llama.cpp's merged inkling2_loop layout +struct GgTensor { uint32_t type = 0; int64_t ne[4] = {1, 1, 1, 1}; int nd = 0; const uint8_t* data = nullptr; size_t bytes = 0; }; +struct Gguf { + const uint8_t* base = nullptr; + size_t size = 0; + std::map t; + std::map ints; + std::string arch; + const GgTensor& get(const std::string& n) const { + auto it = t.find(n); + if (it == t.end()) { std::fprintf(stderr, "GGUF: missing tensor %s\n", n.c_str()); std::exit(1); } + return it->second; + } + bool has(const std::string& n) const { return t.count(n) != 0; } +}; +size_t gg_row_bytes(uint32_t type, int64_t ne0) { + switch (type) { + case GG_F32: return (size_t) ne0 * 4; + case GG_F16: case GG_BF16: return (size_t) ne0 * 2; + case GG_Q8_0: return (size_t) ne0 / 32 * 34; + case GG_IQ4_NL: return (size_t) ne0 / 32 * 18; + case GG_IQ3_S: return (size_t) ne0 / 256 * 110; + default: return 0; + } +} +#include "ink2_gguf_experts.cuh" +std::string gg_open(const std::string& path, Gguf& g) { + const int fd = ::open(path.c_str(), O_RDONLY); + if (fd < 0) return "cannot open " + path; + struct stat st{}; + fstat(fd, &st); + g.size = (size_t) st.st_size; + void* m = mmap(nullptr, g.size, PROT_READ, MAP_PRIVATE, fd, 0); + ::close(fd); + if (m == MAP_FAILED) return "cannot map " + path; + g.base = (const uint8_t*) m; + size_t p = 0; + auto rd = [&](void* dst, size_t n) { if (p + n > g.size) { std::fprintf(stderr, "GGUF: truncated\n"); std::exit(1); } std::memcpy(dst, g.base + p, n); p += n; }; + auto u32 = [&] { uint32_t v; rd(&v, 4); return v; }; + auto u64 = [&] { uint64_t v; rd(&v, 8); return v; }; + auto str = [&] { const uint64_t n = u64(); std::string r((const char*) g.base + p, n); p += n; return r; }; + if (u32() != 0x46554747u) return path + ": not a GGUF file"; + const uint32_t ver = u32(); + if (ver < 2) return path + ": GGUF version 1"; + const uint64_t nt = u64(), nkv = u64(); + const size_t sz[13] = {1, 1, 2, 2, 4, 4, 4, 1, 0, 0, 8, 8, 8}; + uint64_t align = 32; + std::function skip = [&](uint32_t ty, const std::string& key) { + if (ty == 8) { (void) str(); return; } + if (ty == 9) { + const uint32_t et = u32(); + const uint64_t n = u64(); + for (uint64_t i = 0; i < n; ++i) skip(et, ""); + return; + } + if (ty > 12) { std::fprintf(stderr, "GGUF: value type %u\n", ty); std::exit(1); } + int64_t v = 0; + if (ty == 4 || ty == 5) { uint32_t x; rd(&x, 4); v = ty == 5 ? (int32_t) x : x; } + else if (ty == 10 || ty == 11) { uint64_t x; rd(&x, 8); v = (int64_t) x; } + else p += sz[ty]; + if (!key.empty() && (ty == 4 || ty == 5 || ty == 10 || ty == 11)) g.ints[key] = v; + }; + for (uint64_t i = 0; i < nkv; ++i) { + const std::string key = str(); + const uint32_t ty = u32(); + if (key == "general.architecture" && ty == 8) { g.arch = str(); continue; } + skip(ty, key); + if (key == "general.alignment") align = (uint64_t) g.ints[key]; + } + std::vector> offs; + for (uint64_t i = 0; i < nt; ++i) { + const std::string name = str(); + GgTensor x; + x.nd = (int) u32(); + for (int d = 0; d < x.nd; ++d) x.ne[d] = (int64_t) u64(); + x.type = u32(); + const uint64_t off = u64(); + const size_t rb = gg_row_bytes(x.type, x.ne[0]); + if (!rb) return name + ": ggml type " + std::to_string(x.type) + " (" + gg_type_name(x.type) + ") is not supported"; + x.bytes = rb * (size_t) (x.ne[1] * x.ne[2] * x.ne[3]); + g.t[name] = x; + offs.push_back({name, off}); + } + const size_t data = (p + align - 1) / align * align; + for (auto& o : offs) { + GgTensor& x = g.t[o.first]; + if (data + o.second + x.bytes > g.size) return o.first + ": data past the end of the file"; + x.data = g.base + data + o.second; + } + return ""; +} + +const Gguf* g_gg = nullptr; + +uint16_t f32_to_bf16(float f) { // round to nearest even + uint32_t u; + std::memcpy(&u, &f, 4); + u += 0x7FFFu + ((u >> 16) & 1u); + return (uint16_t) (u >> 16); +} +// any supported 1-D / 2-D GGUF tensor as fp32 (row-major, ne0 fastest) +vec gg_f32(const std::string& n) { + const GgTensor& x = g_gg->get(n); + const size_t ne = (size_t) (x.ne[0] * x.ne[1] * x.ne[2] * x.ne[3]); + vec out(ne); + const uint8_t* b = x.data; + switch (x.type) { + case GG_F32: std::memcpy(out.data(), b, ne * 4); break; + case GG_F16: for (size_t i = 0; i < ne; ++i) { uint16_t h; std::memcpy(&h, b + 2 * i, 2); out[i] = __half2float(*reinterpret_cast<__half*>(&h)); } break; + case GG_BF16: for (size_t i = 0; i < ne; ++i) { uint16_t h; std::memcpy(&h, b + 2 * i, 2); uint32_t u = (uint32_t) h << 16; std::memcpy(&out[i], &u, 4); } break; + case GG_Q8_0: + for (size_t j = 0; j < ne / 32; ++j) { + const uint8_t* q = b + j * 34; + uint16_t h; + std::memcpy(&h, q, 2); + const float d = __half2float(*reinterpret_cast<__half*>(&h)); + for (int i = 0; i < 32; ++i) out[32 * j + i] = d * (float) (int8_t) q[2 + i]; + } + break; + default: std::fprintf(stderr, "%s: type %u where a dense tensor was expected\n", n.c_str(), x.type); std::exit(1); + } + return out; +} +// BF16 matrix from F32 / BF16 (exact) or another type (rounded; the loop gates, the router if not exact) +DMat gg_bf16_stack(const std::vector& names) { + DMat m; + std::vector all; + size_t inexact = 0; + for (const auto& n : names) { + const GgTensor& x = g_gg->get(n); + if (m.k && x.ne[0] != m.k) { std::fprintf(stderr, "%s: K %lld != %d\n", n.c_str(), (long long) x.ne[0], m.k); std::exit(1); } + m.k = (int) x.ne[0]; + m.n += (int) (x.ne[1] * x.ne[2]); + for (float f : gg_f32(n)) { + const uint16_t h = f32_to_bf16(f); + uint32_t u = (uint32_t) h << 16; + float back; + std::memcpy(&back, &u, 4); + inexact += back != f; + all.push_back(h); + } + } + if (inexact && std::getenv("INK2_VERBOSE")) std::fprintf(stderr, "%s: %zu values rounded to BF16\n", names[0].c_str(), inexact); + m.d = (const uint16_t*) upload(all.data(), all.size() * 2); + return m; +} +// Q8_0 matrix (rows of the named tensors concatenated) repacked into codes [n][k] + scales [n][k / 32] +DMat gg_q8_stack(const std::vector& names) { + DMat m; + std::vector q; + std::vector<__half> sc; + for (const auto& n : names) { + const GgTensor& x = g_gg->get(n); + if (x.type != GG_Q8_0) return gg_bf16_stack(names); // a part in another type: the whole stack as BF16 + if (m.k && x.ne[0] != m.k) { std::fprintf(stderr, "%s: K differs\n", n.c_str()); std::exit(1); } + m.k = (int) x.ne[0]; + const int64_t rows = x.ne[1] * x.ne[2]; + m.n += (int) rows; + const size_t nb = (size_t) rows * (m.k / 32); + for (size_t j = 0; j < nb; ++j) { + const uint8_t* b = x.data + j * 34; + __half h; + std::memcpy(&h, b, 2); + sc.push_back(h); + for (int i = 0; i < 32; ++i) q.push_back((int8_t) b[2 + i]); + } + } + m.q = (const int8_t*) upload(q.data(), q.size()); + m.qs = (const __half*) upload(sc.data(), sc.size() * 2); + return m; +} +const float* gg_fvec(const std::string& n) { return dvec(gg_f32(n)); } +// a [rows][cols] tensor (ne0 = cols) transposed +vec gg_transpose(const std::string& n) { + const GgTensor& x = g_gg->get(n); + const vec a = gg_f32(n); + const int64_t c = x.ne[0], r = x.ne[1]; + vec o(a.size()); + for (int64_t i = 0; i < r; ++i) + for (int64_t j = 0; j < c; ++j) o[(size_t) j * r + i] = a[(size_t) i * c + j]; + return o; +} + +void load_gguf() { + const Gguf& g = *g_gg; + if (g.arch != "inkling2_loop") { std::fprintf(stderr, "GGUF architecture %s, expected inkling2_loop\n", g.arch.c_str()); std::exit(1); } + auto need = [&](const char* k, int64_t v) { + auto it = g.ints.find(std::string("inkling2_loop.") + k); + if (it == g.ints.end() || it->second != v) { std::fprintf(stderr, "GGUF: %s is not %lld\n", k, (long long) v); std::exit(1); } + }; + need("block_count", NL); need("embedding_length", H); need("expert_count", NE); need("expert_used_count", TOPK); + need("loop.start", LOOP_BEGIN); need("loop.end", LOOP_END); need("loop.count", PASSES); need("loop.gate_rank", GATE_RANK); + need("attention.sliding_window", WINDOW); need("expert_feed_forward_length", FF); + gg_expert_formats(g); // one expert type pair for every layer, or one for 0..19 and one for 20..23; slot = [gate_up | down] + E.embed_norm = gg_fvec("token_embd_norm.weight"); + E.norm = gg_fvec("output_norm.weight"); + E.final_query = gg_fvec("output_res_query.weight"); + { + const GgTensor& x = g.get("token_embd.weight"); + if (x.type != GG_Q8_0 || x.ne[0] != H) { std::fprintf(stderr, "token_embd: Q8_0 [%d] expected\n", H); std::exit(1); } + E.embed_q8.assign(x.data, x.data + x.bytes); + } + E.unembed = gg_q8_stack({"output.weight"}); + { + vec mq((size_t) NLOOP * 4 * H); + for (int i = 0; i < NLOOP; ++i) { + const vec q = gg_f32("blk." + std::to_string(LOOP_BEGIN + i) + ".loop_msg_query.weight"); + if (q.size() != (size_t) 4 * H) { std::fprintf(stderr, "loop_msg_query: size\n"); std::exit(1); } + std::memcpy(&mq[(size_t) i * 4 * H], q.data(), q.size() * 4); + } + E.msg_queries = dvec(mq); + } + expert_memory(); + for (int l = 0; l < NL; ++l) { + Layer& Y = E.L[l]; + const std::string b = "blk." + std::to_string(l) + "."; + Y.full = full_layer(l); + Y.loop = l >= LOOP_BEGIN && l < LOOP_END; + { + std::vector parts = {b + "attn_q.weight", b + "attn_gate.weight", b + "attn_rel.weight", + b + "attn_sink_proj.weight", b + "attn_k.weight"}; + if (Y.full) parts.push_back(b + "attn_k_conv_proj.weight"); + parts.push_back(b + "attn_v.weight"); + if (Y.full) parts.push_back(b + "attn_v_conv_proj.weight"); + Y.proj = gg_q8_stack(parts); + Y.off_k = OFF_K; + Y.n_k = KVD + (Y.full ? NKV * KC : 0); + Y.off_v = Y.off_k + Y.n_k; + Y.n_v = Y.n_k; + if (Y.proj.n != Y.off_v + Y.n_v) { std::fprintf(stderr, "layer %d: stacked rows %d\n", l, Y.proj.n); std::exit(1); } + } + Y.wo = gg_q8_stack({b + "attn_output.weight"}); + Y.router = gg_bf16_stack({b + "ffn_gate_inp.weight"}); + Y.router_bias = gg_fvec(b + "exp_probs_b.bias"); + Y.q_scale = gg_fvec(b + "attn_q_clip.weight"); + Y.rel_scale = gg_fvec(b + "attn_rel_clip.weight"); + Y.rel_proj = dvec(gg_transpose(b + "attn_rel_bias.weight")); // the converter stored proj^T + Y.attn_conv = gg_fvec(b + "attn_post_conv.weight"); + Y.mlp_conv = gg_fvec(b + "ffn_post_conv.weight"); + Y.mlp_norm = gg_fvec(b + "ffn_norm.weight"); + if (Y.full) { // static_w was stored as flip(0).T: transpose back, then flip the taps + for (int kv = 0; kv < 2; ++kv) { + vec t = gg_transpose(b + (kv ? "attn_v_conv.weight" : "attn_k_conv.weight")); + const size_t taps = t.size() / KVD; + vec f(t.size()); + for (size_t r = 0; r < taps; ++r) std::memcpy(&f[r * KVD], &t[(taps - 1 - r) * KVD], KVD * 4); + (kv ? Y.v_static : Y.k_static) = dvec(f); + } + Y.q_norm = gg_fvec(b + "attn_q_inp_norm.weight"); + Y.k_norm = gg_fvec(b + "attn_k_inp_norm.weight"); + Y.v_norm = gg_fvec(b + "attn_v_inp_norm.weight"); + } else { + Y.k_conv = gg_fvec(b + "attn_k_conv.weight"); + Y.v_conv = gg_fvec(b + "attn_v_conv.weight"); + Y.attn_norm = gg_fvec(b + "attn_norm.weight"); + } + if (l > 0) Y.attn_query = gg_fvec(b + "attn_res_query.weight"); + Y.mlp_query = gg_fvec(b + "ffn_res_query.weight"); + if (Y.loop) { + const char* names[4] = {"q", "k", "v", "ffn"}; + for (int k = 0; k < 4; ++k) { + const std::string c = b + "loop_" + names[k] + "_ctrl_"; + Y.gates[k] = {gg_bf16_stack({c + "down.weight"}), gg_bf16_stack({c + "forget.weight", c + "gain.weight"})}; + } + } + Experts& X = Y.ex; + const GgTensor& gu = g.get(b + "ffn_gate_up_exps.weight"); + const GgTensor& dn = g.get(b + "ffn_down_exps.weight"); + if (gu.ne[0] != H || gu.ne[1] != 2 * FF || gu.ne[2] != NE || dn.ne[0] != FF || dn.ne[1] != H || dn.ne[2] != NE) { + std::fprintf(stderr, "layer %d: expert shapes\n", l); + std::exit(1); + } + X.nvfp4 = false; + X.gg13 = (int) gu.type; + X.gg2 = (int) dn.type; + X.rb13 = gg_row_bytes(gu.type, gu.ne[0]); + X.rb2 = gg_row_bytes(dn.type, dn.ne[0]); + const size_t ga = ex_partA(l), gb = ex_bytes(l) - ga; // gg_expert_formats checked the types per layer range + if (gu.bytes / NE != ga || dn.bytes / NE != gb) { std::fprintf(stderr, "layer %d: expert sizes differ\n", l); std::exit(1); } + { // one slot per expert: [gate_up rows | down rows], then the layer into its pool range (offload: E.xh) + const size_t eb = ex_bytes(l); + std::vector lay(E.offload ? 0 : (size_t) NE * eb); + for (int e = 0; e < NE; ++e) { + uint8_t* o = E.offload ? E.xh[(size_t) l * NE + e] : lay.data() + (size_t) e * eb; + std::memcpy(o, gu.data + (size_t) e * ga, ga); + std::memcpy(o + ga, dn.data + (size_t) e * gb, gb); + } + if (!E.offload) { + uint8_t* dst = E.pool_nv + ex_layer_off(l); + CK(cudaMemcpy(dst, lay.data(), lay.size(), cudaMemcpyHostToDevice)); + for (int e = 0; e < NE; ++e) { + E.htabA[l * NE + e] = dst + (size_t) e * eb; + E.htabB[l * NE + e] = dst + (size_t) e * eb + ga; + } + } + X.tA = E.tabA + (size_t) l * NE; + X.tB = E.tabB + (size_t) l * NE; + } + std::fprintf(stderr, "\rloaded layer %d/%d, %.1f GiB in VRAM", l + 1, NL, g_vram / 1073741824.0); + } + std::fprintf(stderr, "\n"); + if (!E.offload) { + CK(cudaMemcpy(E.tabA, E.htabA.data(), E.htabA.size() * sizeof(void*), cudaMemcpyHostToDevice)); + CK(cudaMemcpy(E.tabB, E.htabB.data(), E.htabB.size() * sizeof(void*), cudaMemcpyHostToDevice)); + } + CK(cudaMemcpyToSymbol(d_iq3s_grid, k_iq3s_grid, sizeof(k_iq3s_grid))); + CK(cudaMemcpyToSymbol(c_iq4nl, k_iq4nl_values, sizeof(k_iq4nl_values))); +} + +// offload: once everything else is allocated, the pools take the free VRAM minus --vram-reserve-mib and a margin +// (decode graph, cuBLAS workspaces), split 80 / 20 between NVFP4 and MXFP8 bytes (two-pool LRU replay of corpus12k, +// lru2.py: 0.20 best at 6, 7 and 8 GiB). Initial content: looped layers first, then the others, expert order. +// CBA: fixed margin and 0.20 split; per-card measurement / a routing profile if the first tokens matter. +// INK2_OFF_MARGIN_MIB: VRAM kept beside --vram-reserve-mib for what is allocated after the pools (decode graph, cuBLAS, +// CPU-expert staging). Measured on the 3090 at 8 GiB (reserve 15946, nvidia-smi peak): 17-31 MiB used after the pools +// with --tc 0 / 1, --cpu-threads 22, --spec 1, a 6000-token prompt at chunk 1024; 128 leaves ~100 MiB to spare. +int g_off_margin_mib = 128; +void setup_offload() { + size_t fr = 0, tot = 0; + CK(cudaMemGetInfo(&fr, &tot)); + const size_t keep = ((size_t) E.reserve_mib << 20) + ((size_t) g_off_margin_mib << 20); + const size_t budget = fr > keep ? fr - keep : 0; + // GGUF with one expert format: one pool; else (checkpoint, GGUF g_gg_two) layers >= MXFP8_FIRST in pool_mx. + // CBA: a two-format GGUF (IQ4_NL / Q8_0) reuses the checkpoint's 0.20 split, not replayed for its slot sizes + const bool one = g_is_gguf && !g_gg_two; + if (one) { + E.nslot_mx = 0; + E.nslot_nv = (int) std::min(budget / ex_bytes(0), (size_t) NL * NE); + } else { + E.nslot_mx = (int) std::min((size_t) (budget * 0.2) / pool_slot(false), (size_t) (NL - MXFP8_FIRST) * NE); + E.nslot_nv = (int) std::min((budget - (size_t) E.nslot_mx * pool_slot(false)) / pool_slot(true), (size_t) MXFP8_FIRST * NE); + } + if (E.nslot_nv < FETCH_MAX || (!one && E.nslot_mx < FETCH_MAX)) { + std::fprintf(stderr, "offload: %.2f GiB free, reserve %d MiB: room for %d + %d expert slots (need >= %d each)\n", + fr / 1073741824.0, E.reserve_mib, E.nslot_nv, E.nslot_mx, FETCH_MAX); + std::exit(1); + } + const int cap_nv = one ? NL * NE : MXFP8_FIRST * NE, cap_mx = one ? 0 : (NL - MXFP8_FIRST) * NE; + if (E.grow) { // growable: --kv-grow takes slots back as the context grows (pool_resize) + E.vpool_nv.init((size_t) cap_nv * ex_bytes(0)); + if (!E.vpool_nv.map_to((size_t) E.nslot_nv * ex_bytes(0))) { std::fprintf(stderr, "offload: pool mapping failed\n"); std::exit(1); } + E.pool_nv = (uint8_t*) E.vpool_nv.ptr(); + if (cap_mx) { + E.vpool_mx.init((size_t) cap_mx * pool_slot(false)); + if (!E.vpool_mx.map_to((size_t) E.nslot_mx * pool_slot(false))) { std::fprintf(stderr, "offload: pool mapping failed\n"); std::exit(1); } + E.pool_mx = (uint8_t*) E.vpool_mx.ptr(); + } + } else { + E.pool_nv = (uint8_t*) dalloc((size_t) E.nslot_nv * ex_bytes(0)); + if (E.nslot_mx) E.pool_mx = (uint8_t*) dalloc((size_t) E.nslot_mx * pool_slot(false)); + } + std::vector slot_of((size_t) NL * NE, -1), own_nv(E.grow ? cap_nv : E.nslot_nv, -1), + own_mx(E.grow ? cap_mx : E.nslot_mx, -1); + std::vector order; + for (int l = LOOP_BEGIN; l < LOOP_END; ++l) order.push_back(l); + for (int l = 0; l < NL; ++l) if (l < LOOP_BEGIN || l >= LOOP_END) order.push_back(l); + int used_nv = 0, used_mx = 0; + for (int l : order) + for (int e = 0; e < NE; ++e) { + const bool nv = ex_nv(l); + int& used = nv ? used_nv : used_mx; + if (used >= (nv ? E.nslot_nv : E.nslot_mx)) continue; + const size_t eb = ex_bytes(l); + uint8_t* d = (nv ? E.pool_nv : E.pool_mx) + (size_t) used * eb; + CK(cudaMemcpy(d, E.xh[(size_t) l * NE + e], eb, cudaMemcpyHostToDevice)); + slot_of[l * NE + e] = used; + (nv ? own_nv : own_mx)[used] = l * NE + e; + E.htabA[l * NE + e] = d; + E.htabB[l * NE + e] = d + ex_partA(l); + ++used; + } + CK(cudaMemcpy(E.tabA, E.htabA.data(), E.htabA.size() * sizeof(void*), cudaMemcpyHostToDevice)); + CK(cudaMemcpy(E.tabB, E.htabB.data(), E.htabB.size() * sizeof(void*), cudaMemcpyHostToDevice)); + auto ints = [](const std::vector& v) { return (int*) upload(v.data(), v.size() * 4); }; + E.slot_of = ints(slot_of); + E.owner_nv = ints(own_nv); + E.owner_mx = ints(own_mx); + E.stamp_nv = (unsigned*) dalloc(own_nv.size() * 4); + E.stamp_mx = (unsigned*) dalloc(own_mx.size() * 4); + E.clock = (unsigned*) dalloc(4); + E.nfetch = (int*) dalloc(4); + E.fsrc = (const uint8_t**) dalloc(FETCH_MAX * sizeof(void*)); + E.fdst = (uint8_t**) dalloc(FETCH_MAX * sizeof(void*)); + E.fbytes = (unsigned long long*) dalloc(8); + std::fprintf(stderr, "offload: %.2f GiB free after the rest, reserve %d MiB -> %d NVFP4 + %d MXFP8 expert slots " + "(%.2f GiB, %.0f %% of the experts)\n", fr / 1073741824.0, E.reserve_mib, E.nslot_nv, E.nslot_mx, + ((size_t) E.nslot_nv * ex_bytes(0) + (size_t) E.nslot_mx * pool_slot(false)) / 1073741824.0, + 100.0 * ((size_t) E.nslot_nv * ex_bytes(0) + (size_t) E.nslot_mx * pool_slot(false)) / ex_layer_off(NL)); +} + +// bytes per cell of a slot's K (0), V (1), K scales (2), V scales (3) in format E.kvm +size_t kv_cell_bytes(int a) { + const int m = E.kvm; + switch (a) { + case 0: return (size_t) KVD * (m == 0 ? 4 : m == 1 ? 2 : 1); + case 1: return m == 4 ? KVD / 2 : (size_t) KVD * (m == 0 ? 4 : m == 1 ? 2 : 1); + case 2: return m >= 2 ? (KVD / KVG) * 2 : 0; + default: return m >= 2 ? (KVD / (m == 4 ? V4G : KVG)) * 2 : 0; + } +} +std::vector g_kvr; // --kv-grow: the full slots' arrays +std::vector g_kvr_bpc; // their bytes per cell +size_t kv_mapped_for(int cells) { + size_t t = 0; + for (size_t i = 0; i < g_kvr.size(); ++i) t += g_kvr[i].need((size_t) cells * g_kvr_bpc[i]); + return t; +} + +// --kv-grow with offload: a pool's slot count changes. Nothing may be running on the device; the decode graph (the +// slot count is one of its launch arguments) is rebuilt at the next token. +size_t vram_free() { size_t fr = 0, tot = 0; CK(cudaMemGetInfo(&fr, &tot)); return fr; } +size_t vram_keep() { return ((size_t) std::max(E.reserve_mib, 0) << 20) + ((size_t) g_off_margin_mib << 20); } // as setup_offload +void promote_cancel(); // (CPU experts) +cudaGraphExec_t g_vexec[2] = {}; // the --spec verify graphs (forward_prefill): the slot counts baked in too +void pool_resize(bool nv, int n) { + int& ns = nv ? E.nslot_nv : E.nslot_mx; + VRange& r = nv ? E.vpool_nv : E.vpool_mx; + const size_t eb = pool_slot(nv); + n = std::max(0, std::min(n, (int) (r.reserved / eb))); + if (n < ns) { + if (E.cpu) promote_cancel(); // planned promotions may hold slots past n + k_pool_evict<<<(ns - n + 255) / 256, 256>>>(nv ? E.owner_nv : E.owner_mx, E.slot_of, E.tabA, E.tabB, + nv ? E.stamp_nv : E.stamp_mx, n, ns); + CK(cudaDeviceSynchronize()); + r.unmap_to((size_t) n * eb); + } else if (n > ns) { + if (!r.map_to((size_t) n * eb)) n = std::max(ns, (int) (r.mapped / eb)); + } + ns = n; + if (E.exec) { CK(cudaGraphExecDestroy(E.exec)); E.exec = nullptr; } + for (auto& x : g_vexec) if (x) { CK(cudaGraphExecDestroy(x)); x = nullptr; } +} +double pool_bytes(bool nv) { return (double) (nv ? E.nslot_nv : E.nslot_mx) * pool_slot(nv); } +// the pools give up `bytes`, in proportion to their sizes +void pools_release(double bytes, const char* what) { + const double deficit = bytes + 4.0 * g_vmm.gran, used = pool_bytes(true) + pool_bytes(false); + for (bool nv : {true, false}) { + const int ns = nv ? E.nslot_nv : E.nslot_mx; + if (!ns) continue; + const int drop = (int) std::ceil(deficit * pool_bytes(nv) / used / pool_slot(nv)); + if (ns - drop < FETCH_MAX) { std::fprintf(stderr, "%s would leave the expert pool %d slots\n", what, ns - drop); std::exit(1); } + pool_resize(nv, ns - drop); + } +} +// the pools take what is free beyond the margin, in proportion to their sizes +void pools_fill() { + if (!E.offload || !E.grow) return; + const size_t fr = vram_free(), keep = vram_keep() + 4 * g_vmm.gran; + if (fr <= keep) return; + const double spare = (double) (fr - keep), used = pool_bytes(true) + pool_bytes(false); + for (bool nv : {true, false}) { + const int ns = nv ? E.nslot_nv : E.nslot_mx; + if (!ns) continue; + pool_resize(nv, ns + (int) (spare * pool_bytes(nv) / used / pool_slot(nv))); + } +} +// the full slots hold `need` cells (grown in --kv-grow-step steps, from the expert pools when VRAM is short) +void kv_fit(int need) { + if (!E.grow || need <= E.kv_cells) return; + const int nc = std::min(E.ctx, (need + E.grow_step - 1) / E.grow_step * E.grow_step); + CK(cudaDeviceSynchronize()); + const size_t add = kv_mapped_for(nc) - kv_mapped_for(E.kv_cells), keep = vram_keep(), fr = vram_free(); + if (fr < add + keep && E.offload) pools_release((double) (add + keep - fr), "the K/V"); + for (size_t i = 0; i < g_kvr.size(); ++i) + if (!g_kvr[i].map_to((size_t) nc * g_kvr_bpc[i])) { std::fprintf(stderr, "--kv-grow: out of VRAM at %d cells\n", nc); std::exit(1); } + E.kv_cells = nc; + std::fprintf(stderr, "kv-grow: %d cells (%.2f GiB K/V), expert slots %d + %d\n", nc, kv_mapped_for(nc) / 1073741824.0, + E.nslot_nv, E.nslot_mx); +} +// a request that needs only `need` cells: the rest of the mapped K/V back to the pools +void kv_trim(int need) { + if (!E.grow) return; + const int nc = std::min(E.ctx, std::max(E.grow_step, (need + E.grow_step - 1) / E.grow_step * E.grow_step)); + if (E.kv_cells <= nc + E.grow_step) return; + CK(cudaDeviceSynchronize()); + for (size_t i = 0; i < g_kvr.size(); ++i) g_kvr[i].unmap_to((size_t) nc * g_kvr_bpc[i]); + E.kv_cells = nc; + pools_fill(); + std::fprintf(stderr, "kv-grow: back to %d cells, expert slots %d + %d\n", nc, E.nslot_nv, E.nslot_mx); +} + +void alloc_state() { + if (E.grow) g_kvr.reserve(4 * NCALLS); // VRange addresses are handed out: no reallocation + CK(cudaMemcpyToSymbol(c_kvm, &E.kvm, sizeof(int))); + E.nchunk_full = (E.ctx + CHUNK - 1) / CHUNK; + for (int s = 0; s < NCALLS; ++s) { + const int l = s < NL ? s : LOOP_BEGIN + (s - NL) % NLOOP; + Slot& S = E.S[s]; + S.full = full_layer(l); + S.cap = S.full ? E.ctx : WINDOW + PF_RING_EXTRA; + void** arr[4] = {&S.K, &S.V, (void**) &S.ksc, (void**) &S.vsc}; + for (int a = 0; a < 4; ++a) { + const size_t b = kv_cell_bytes(a); + if (!b) continue; + if (E.grow && S.full) { + g_kvr.emplace_back(); + VRange& r = g_kvr.back(); + r.init((size_t) S.cap * b); + g_kvr_bpc.push_back(b); + *arr[a] = r.ptr(); + } else { + *arr[a] = dalloc((size_t) S.cap * b); + } + } + S.khist = dfloats(HR * KVD); + S.vhist = dfloats(HR * KVD); + S.ahist = dfloats(HR * H); + S.mhist = dfloats(HR * H); + } + if (E.grow) { + E.kv_cells = std::min(E.ctx, E.grow_step); + for (size_t i = 0; i < g_kvr.size(); ++i) + if (!g_kvr[i].map_to((size_t) E.kv_cells * g_kvr_bpc[i])) { std::fprintf(stderr, "--kv-grow: no VRAM for %d cells\n", E.kv_cells); std::exit(1); } + } + E.d_pos = (int*) dalloc(4); + E.h = dfloats(H); E.out = dfloats(H); E.Bbuf = dfloats(8 * H); E.preB = dfloats(8 * H); E.pre_h = dfloats(H); + E.prev_stack = dfloats(8 * H); E.msgs = dfloats(4 * H); E.a = dfloats(3 * H); + for (auto& t : E.t) t = dfloats(H); + E.xq = dfloats(H); E.xk = dfloats(H); E.xv = dfloats(H); + E.q = dfloats(QD); E.k = dfloats(KVD); E.v = dfloats(KVD); E.kc = dfloats(KVD); E.vc = dfloats(KVD); E.dw = dfloats(64); + E.rs = dfloats(NQ * DREL); E.rel = dfloats(NQ * EXTENT); E.sink = dfloats(NQ); E.gate = dfloats(QD); + E.att = dfloats(QD); E.attn_out = dfloats(H); E.att2 = dfloats(H); E.r = dfloats(H); + E.m = dfloats(H); E.mn = dfloats(H); E.cat = dfloats(3 * 2 * H); E.gdown = dfloats(3 * GATE_RANK); E.gf = dfloats(H); + E.gg = dfloats(H); E.rl = dfloats(NE); E.wts = dfloats(TOPK); E.ids = (int*) dalloc(TOPK * 4); + E.gu = dfloats((size_t) TOPK * 2 * FF); E.act = dfloats((size_t) TOPK * FF); E.ey = dfloats((size_t) TOPK * H); + E.moe = dfloats(H); E.y2 = dfloats(H); E.logits = dfloats(VOCAB_ROWS); E.emb_in = dfloats(H); E.pout = dfloats(OFF_K + 2 * (KVD + NKV * KC)); E.gfg = dfloats(3 * 2 * H); + const int nc = std::max(E.nchunk_full, E.nchunk_slide); + E.pm = dfloats((size_t) NQ * nc); E.pl = dfloats((size_t) NQ * nc); E.po = dfloats((size_t) NQ * nc * HD); +} + +// --------------------------------------------------------------------------------------------------------------------- +// The forward pass (device pointers; the block-state count is static per call, kept on the host) + +void gemv(const DMat& W, const float* x, float* y, int rows = -1, int first = 0) { // rows [first, first + rows) + const int n = rows < 0 ? W.n - first : rows; + // small N (k / v projections: 1024 rows, wo: 2304) gave 32-72 blocks for 82 SMs at R = 4 (420-670 GB/s): fewer rows + // per warp there, more blocks; per-row arithmetic is the same whatever R (bit-identical) + int R = g_rpw; + while (R > 1 && (n + 8 * R - 1) / (8 * R) < g_gemv_min_blocks) R /= 2; + const unsigned g = (unsigned) ((n + 8 * R - 1) / (8 * R)); + const size_t sm = (size_t) W.k * 4; + if (W.q) { + const int8_t* wq = W.q + (size_t) first * W.k; + const __half* ws = W.qs + (size_t) first * (W.k / 32); + switch (R) { + case 1: k_gemv_q8<1><<>>(wq, ws, x, y, n, W.k); break; + case 2: k_gemv_q8<2><<>>(wq, ws, x, y, n, W.k); break; + case 8: k_gemv_q8<8><<>>(wq, ws, x, y, n, W.k); break; + default: k_gemv_q8<4><<>>(wq, ws, x, y, n, W.k); + } + return; + } + const uint16_t* w = W.d + (size_t) first * W.k; + switch (R) { + case 1: k_gemv_bf16<1><<>>(w, x, y, n, W.k); break; + case 2: k_gemv_bf16<2><<>>(w, x, y, n, W.k); break; + case 8: k_gemv_bf16<8><<>>(w, x, y, n, W.k); break; + default: k_gemv_bf16<4><<>>(w, x, y, n, W.k); + } +} +void rms(const float* x, const float* w, float* y, int n = H) { k_rms<<<1, 512>>>(x, w, y, n); } +void copy(float* dst, const float* src, size_t n) { CK(cudaMemcpyAsync(dst, src, n * 4, cudaMemcpyDeviceToDevice)); } + +// Inkling2LoopMessageGate, then rms(.) * nw into yn (every gated stream is normalized next) +// n (<= 3) independent gates in one launch per stage +void message_gates(int n, const Gate* const g[], const float* const x[], const float* const m[], float* const y[], + const float* const nw[], float* const yn[]) { + GateArgs a{}; + for (int j = 0; j < n; ++j) { + a.down[j] = g[j]->down.d; a.fg[j] = g[j]->fg.d; a.x[j] = x[j]; a.m[j] = m[j]; a.y[j] = y[j]; a.nw[j] = nw[j]; + a.yn[j] = yn[j]; + } + k_rms2<<>>(a, E.cat); + k_gate_down<<>>(a, E.cat, E.gdown, g[0]->down.k); + const int N = g[0]->fg.n, K = g[0]->fg.k; // as gemv(): R halved while the grid is short + int R = g_rpw; + while (R > 1 && (N + 8 * R - 1) / (8 * R) < g_gemv_min_blocks) R /= 2; + const dim3 grid((unsigned) ((N + 8 * R - 1) / (8 * R)), n); + const size_t sm = (size_t) K * 4; + switch (R) { + case 1: k_gemv_bf16_gate<1><<>>(a, E.gdown, E.gfg, N, K); break; + case 2: k_gemv_bf16_gate<2><<>>(a, E.gdown, E.gfg, N, K); break; + case 8: k_gemv_bf16_gate<8><<>>(a, E.gdown, E.gfg, N, K); break; + default: k_gemv_bf16_gate<4><<>>(a, E.gdown, E.gfg, N, K); + } + k_gate_mix_rms<<>>(a, E.gfg); +} + +// attnres dispatch on (S, NQ) +void attnres(const float* stack, int S, const float* queries, int nq, float* out, const float* nw0 = nullptr, + const float* nw1 = nullptr, const float* nw2 = nullptr, float* outn = nullptr, int T = 1) { + const size_t ss = (size_t) T * H; // T tokens: entries [S][T][H] +#define AR_CASE(SS, QQ) if (S == SS && nq == QQ) { k_attnres<<>>(stack, ss, queries, out, nw0, nw1, nw2, outn); return; } + AR_CASE(1, 1) AR_CASE(2, 1) AR_CASE(3, 1) AR_CASE(4, 1) AR_CASE(5, 1) AR_CASE(6, 1) + AR_CASE(2, 3) AR_CASE(3, 3) AR_CASE(4, 3) AR_CASE(5, 3) + AR_CASE(2, 4) AR_CASE(3, 4) +#undef AR_CASE + std::fprintf(stderr, "attnres: no kernel for S=%d nq=%d\n", S, nq); + std::exit(1); +} + +void attention(const Layer& Y, Slot& S, const float* xq, const float* xk, const float* xv) { + float* P = E.pout; + if (xq == xk && xk == xv) { + gemv(Y.proj, xq, P); + } else { + const int N = Y.off_v + Y.n_v, K = Y.proj.k; // one launch, three inputs (rows: q.. | k | v) + int R = g_rpw; + while (R > 1 && ((N + 8 * R - 1) / (8 * R) < g_gemv_min_blocks || Y.off_k % R || Y.off_v % R)) R /= 2; + const unsigned g = (unsigned) ((N + 8 * R - 1) / (8 * R)); + const size_t sm = (size_t) 3 * K * 4; + if (Y.proj.q) { + switch (R) { + case 1: k_gemv_q8_qkv<1><<>>(Y.proj.q, Y.proj.qs, xq, xk, xv, Y.off_k, Y.off_v, P, N, K); break; + case 2: k_gemv_q8_qkv<2><<>>(Y.proj.q, Y.proj.qs, xq, xk, xv, Y.off_k, Y.off_v, P, N, K); break; + case 8: k_gemv_q8_qkv<8><<>>(Y.proj.q, Y.proj.qs, xq, xk, xv, Y.off_k, Y.off_v, P, N, K); break; + default: k_gemv_q8_qkv<4><<>>(Y.proj.q, Y.proj.qs, xq, xk, xv, Y.off_k, Y.off_v, P, N, K); + } + } else switch (R) { + case 1: k_gemv_bf16_qkv<1><<>>(Y.proj.d, xq, xk, xv, Y.off_k, Y.off_v, P, N, K); break; + case 2: k_gemv_bf16_qkv<2><<>>(Y.proj.d, xq, xk, xv, Y.off_k, Y.off_v, P, N, K); break; + case 8: k_gemv_bf16_qkv<8><<>>(Y.proj.d, xq, xk, xv, Y.off_k, Y.off_v, P, N, K); break; + default: k_gemv_bf16_qkv<4><<>>(Y.proj.d, xq, xk, xv, Y.off_k, Y.off_v, P, N, K); + } + } + float *q = P, *k = P + Y.off_k, *v = P + Y.off_v; + float *rs = P + OFF_REL, *sink = P + OFF_SINK, *gate = P + OFF_GATE; + static_assert(HD == 128, "k_attn_prep: 128-thread blocks for q heads, rs heads and k / v groups"); + if (Y.full) + k_attn_prep<<<2 * NQ + NKV, 128>>>(q, Y.q_scale, rs, Y.rel_scale, Y.rel_proj, E.rel, 1, k, v, S.khist, S.vhist, + Y.k_static, Y.v_static, S.K, S.V, S.ksc, S.vsc, S.cap, E.d_pos); + else + k_attn_prep<<<2 * NQ + NKV, 128>>>(q, Y.q_scale, rs, Y.rel_scale, Y.rel_proj, E.rel, 0, k, v, S.khist, + S.vhist, Y.k_conv, Y.v_conv, S.K, S.V, S.ksc, S.vsc, S.cap, E.d_pos); + const int nch = S.full ? E.nchunk_full : E.nchunk_slide; + k_attn_partial<<>>(q, S.K, S.V, S.ksc, S.vsc, E.rel, S.cap, S.full ? 0 : WINDOW, E.d_pos, E.pm, E.pl, E.po); + k_attn_merge<<>>(E.pm, E.pl, E.po, nch, sink, gate, E.att); + gemv(Y.wo, E.att, E.attn_out); +} + +// offload: make layer l's experts ids[0..n) resident (plan + fetch, device side, graph-capturable) +void expert_cache(int l, const int* ids, int n) { + const bool nv = ex_nv(l); + CacheArgs c{E.slot_of, nv ? E.owner_nv : E.owner_mx, nv ? E.stamp_nv : E.stamp_mx, E.clock, + nv ? E.nslot_nv : E.nslot_mx, E.tabA, E.tabB, nv ? E.pool_nv : E.pool_mx, ex_bytes(l), ex_partA(l), + E.xsrc_d + (size_t) l * NE, E.fsrc, E.fdst, E.nfetch, E.fbytes}; + k_cache_plan<<<1, 1024>>>(l, ids, n, c); + k_fetch<<>>(E.fsrc, E.fdst, E.nfetch, ex_bytes(l)); +} + +// ---- CPU experts (--cpu-threads). A decode visit: k_cache_cpu stamps the resident experts, hands the others to the +// CPU (one bell per node: jobs, x, ring = sequence number) and notes them as wanted; the GEMVs skip them (null table entries); +// k_cpu_wait waits for every node's ack and copies the CPU outputs into ey. At the end of a token k_promote_commit +// makes the experts copied during this token resident, then k_promote_plan promotes up to PROMOTE_NV / PROMOTE_MX +// wanted experts (victims unmapped at once, so nothing reads them while the next token copies into them). +// Placement (INK2_PLACE=freq, default): a count per (layer, expert), +1 per routed use (each loop pass counts), times +// INK2_DECAY (0.97) per token; the token's misses are taken most counted first, each against the resident expert of +// the pool with the lowest count, and only if it beats it by INK2_GAIN (1.0). Replay of the corpus routing at 8 GiB +// (place/simeng.py): 2.25 -> 1.42 CPU experts per visit, 14.7 -> 8.6 promotions per token; Strata's adaptive cache with +// a per-token decay, its victims from the whole pool (experts of a pool are all one size). INK2_PLACE=lru: the +// least recently used slot, misses in visit order (the previous policy). +// PCIe share (INK2_PCIE=0: off): k_cache_cpu moves a visit's misses one by one, the busiest node's lowest-ranked +// first, from the CPU to a GPU staging slot over PCIe while that shortens the visit (each node's us per job measured +// by its pool, one copy's us measured at start, plus INK2_PCIE_MARGIN us for the GPU side: 120, from a sweep of +// 0 / 60 / 120 / 200); k_cpu_wait takes them out of the tables. q1 chat at 8 GiB, one node: 4 threads 37.2 -> 40.6 +// tok/s, 8 threads 52.4 -> 52.8; the 2 x 22-thread box 66.4 -> 65-66 (it rarely fires there). +constexpr int WANT_MAX = 64, PMAX = 32; +bool g_place_freq = true; +float g_decay = 0.97f, g_gain = 1.0f; +int g_bg_blocks = 4; // INK2_BG_BLOCKS (12 GiB, q1 chat: 4 and 8 blocks 69.8 / 68.9 tok/s, 16: 65.8) +int g_promote_nv = 12, g_promote_mx = 3; // per token (INK2_PROMOTE=nv,mx): ~54 + 25 MB of PCIe in the background +__global__ void k_cache_cpu(int l, const int* __restrict__ ids, const float* __restrict__ x, int* slot_of, unsigned* stamp, + unsigned* clock, int* want, int* nwant, Bells bells, int nodes, unsigned* seq, unsigned* cur, + float* cnt, SyncArgs sa) { + __shared__ int nj; + if (threadIdx.x == 0) { + unsigned t = *clock; + int n = 0, nw = *nwant, jk[TOPK], je[TOPK]; + for (int k = 0; k < TOPK; ++k) { + const int e = ids[k], key = l * NE + e, sl = slot_of[key]; + cnt[key] += 1.0f; + if (sl >= 0) { stamp[sl] = ++t; continue; } + jk[n] = k; + je[n] = e; + ++n; + bool have = false; + for (int i = 0; i < nw; ++i) have |= want[i] == key; + if (!have && nw < WANT_MAX) want[nw++] = key; + } + *clock = t; + *nwant = nw; + // PCIe share: while it shortens the visit, the busiest node's lowest-ranked miss is copied to a staging slot + // and computed on the GPU instead: visit ~ max(node jobs x the node's us per job, copies x one copy's us) + const bool nv = l < MXFP8_FIRST; + const float tp = nv ? sa.us_nv : sa.us_mx; + int ns = 0; + if (tp > 0.0f && n) { + const float u[2] = {bells.b[0]->us_job, nodes > 1 ? bells.b[1]->us_job : 0.0f}; + int c[2] = {0, 0}; + for (int j = 0; j < n; ++j) ++c[nodes > 1 ? sa.home[l * NE + je[j]] : 0]; + while (ns < SYNC_MAX) { + const float t0 = c[0] * u[0], t1 = c[1] * u[1]; + const int m = t1 > t0 ? 1 : 0; + if (!c[m]) break; + const float now = fmaxf(fmaxf(t0, t1), ns ? ns * tp + sa.margin : 0.0f); + const float after = fmaxf(fmaxf((c[m] - 1) * u[m], m ? t0 : t1), (ns + 1) * tp + sa.margin); + if (after >= now) break; + int j = n - 1; + while ((nodes > 1 ? sa.home[l * NE + je[j]] : 0) != m) --j; + const int key = l * NE + je[j]; + uint8_t* st = sa.stage + (size_t) ns * MX_BYTES; + sa.fsrc[ns] = sa.xsrc[key]; + sa.fdst[ns] = st; + sa.tabA[key] = st; + sa.tabB[key] = st + (nv ? NV_A : MX_A); + sa.keys[ns] = key; + for (int i = j; i + 1 < n; ++i) { jk[i] = jk[i + 1]; je[i] = je[i + 1]; } + --n; + --c[m]; + ++ns; + } + *sa.fbytes += (unsigned long long) ns * (nv ? NV_BYTES : MX_BYTES); + } + *sa.nfetch = ns; + for (int j = 0; j < n; ++j) + for (int b = 0; b < nodes; ++b) { + bells.b[b]->k[j] = jk[j]; + bells.b[b]->e[j] = je[j]; + } + nj = n; + } + __syncthreads(); + if (!nj) { + if (threadIdx.x == 0) *cur = 0; + return; + } + for (int b = 0; b < nodes; ++b) + for (int i = threadIdx.x; i < H; i += blockDim.x) bells.b[b]->x[i] = x[i]; + __threadfence_system(); + __syncthreads(); + if (threadIdx.x == 0) { + for (int b = 0; b < nodes; ++b) { + bells.b[b]->layer = l; + bells.b[b]->n = nj; + } + __threadfence_system(); + const unsigned s = ++*seq; + for (int b = 0; b < nodes; ++b) bells.b[b]->ring = s; + __threadfence_system(); + *cur = s; + } +} +// grid TOPK: block j copies job j's output, from the doorbell of the node holding its expert, once every node has acked +// (a stuck pool traps after ~4 s: an error, not a hang) +__global__ void k_cpu_wait(Bells bells, const uint8_t* __restrict__ home, const unsigned* cur, int nodes, float* ey, + SyncArgs sa) { + const volatile ink2cpu::InkBell* b0 = bells.b[0]; + const volatile ink2cpu::InkBell* b1 = bells.b[nodes > 1 ? 1 : 0]; + if (blockIdx.x == 0 && threadIdx.x == 0) // the GEMVs are done: the PCIe share's experts leave the tables + for (int i = 0; i < *sa.nfetch; ++i) sa.tabA[sa.keys[i]] = sa.tabB[sa.keys[i]] = nullptr; + const unsigned s = *cur; + if (!s) return; + __shared__ int ok; + if (threadIdx.x == 0) { + const long long t0 = clock64(); + while (b0->ack[0] != s || (nodes > 1 && b1->ack[1] != s)) + if (clock64() - t0 > 8000000000ll) __trap(); + ok = (int) blockIdx.x < b0->n; + } + __syncthreads(); + if (!ok) return; + const int j = blockIdx.x, k = b0->k[j]; + const int node = nodes > 1 ? home[b0->layer * NE + b0->e[j]] : 0; + const float4* src = reinterpret_cast(bells.b[node]->y[j]); + float4* dst = reinterpret_cast(ey + (size_t) k * H); + for (int i = threadIdx.x; i < H / 4; i += blockDim.x) dst[i] = __ldcv(src + i); // not through the caches +} +// ---- A --spec verify block's visit (T <= BELL_M tokens, moe_b's small-T path) with the CPU experts: k_cache_cpu_b is +// k_cache_cpu over the block's T x TOPK ids: the resident ones stamped and counted, one CPU job per (token, expert) +// that is not (jobs in token order, the pools run a token at a time; its row of PF.ey in vjob), the experts wanted; +// the grouped GEMVs skip them (null table entries); k_cpu_wait_b copies the CPU outputs into their rows of PF.ey. +// CBA: no PCIe share here. Measured (INK2_CPU_TRACE, q1 chat, 2 x 22 threads, a copy 370 us + margin): at 16 GiB a +// node's busy visit is 3.2 jobs on 2.2 experts, 301 us, shorter than one copy; at 8 GiB 15-16 jobs on 7-8 experts, +// 1.1 ms, where a copy per node would save ~2 jobs (~140 us), and --spec loses to plain decoding there anyway. A slower +// CPU could want a share that takes the experts with the most rows of the block. +__global__ void k_cache_cpu_b(int l, const int* __restrict__ ids, const int* __restrict__ slot, int T, + const float* __restrict__ x, const int* slot_of, unsigned* stamp, unsigned* clock, + int* want, int* nwant, Bells bells, int nodes, const uint8_t* __restrict__ home, + unsigned* seq, unsigned* cur, float* cnt, int* vjob, int* nvjob) { + __shared__ int nj, jt[ink2cpu::BELL_J], je[ink2cpu::BELL_J], busy[2]; + if (threadIdx.x == 0) { + unsigned t = *clock; + int n = 0, nw = *nwant; + busy[0] = busy[1] = 0; + for (int i = 0; i < T * TOPK; ++i) { + const int e = ids[i], key = l * NE + e, sl = slot_of[key]; + cnt[key] += 1.0f; + if (sl >= 0) { stamp[sl] = ++t; continue; } + const int node = nodes > 1 ? home[key] : 0; + jt[n] = i / TOPK; + je[n] = e; + vjob[n] = slot[i] | node << 16; + busy[node] = 1; + ++n; + bool have = false; + for (int j = 0; j < nw; ++j) have |= want[j] == key; + if (!have && nw < WANT_MAX) want[nw++] = key; + } + *clock = t; + *nwant = nw; + *nvjob = n; + nj = n; + } + __syncthreads(); + if (!nj) { + if (threadIdx.x == 0) *cur = 0; + return; + } + for (int b = 0; b < nodes; ++b) { + if ((int) threadIdx.x < nj) { + bells.b[b]->vt[threadIdx.x] = jt[threadIdx.x]; + bells.b[b]->ve[threadIdx.x] = je[threadIdx.x]; + } + if (!busy[b]) continue; // a node without jobs only acks + float* dst = &bells.b[b]->vx[0][0]; + for (int i = threadIdx.x; i < T * H; i += blockDim.x) dst[i] = x[i]; + } + __threadfence_system(); + __syncthreads(); + if (threadIdx.x == 0) { + for (int b = 0; b < nodes; ++b) { + bells.b[b]->vlayer = l; + bells.b[b]->vn = nj; + } + __threadfence_system(); + const unsigned s = ++*seq; + for (int b = 0; b < nodes; ++b) bells.b[b]->vring = s; + __threadfence_system(); + *cur = s; + } +} +// grid BELL_J: block j copies job j's output into its row of ey once every node has acked (a stuck pool traps) +__global__ void k_cpu_wait_b(Bells bells, const unsigned* cur, int nodes, const int* __restrict__ vjob, + const int* __restrict__ nvjob, float* ey) { + const unsigned s = *cur; + if (!s || (int) blockIdx.x >= *nvjob) return; + const volatile ink2cpu::InkBell* b0 = bells.b[0]; + const volatile ink2cpu::InkBell* b1 = bells.b[nodes > 1 ? 1 : 0]; + if (threadIdx.x == 0) { + const long long t0 = clock64(); + while (b0->ack[0] != s || (nodes > 1 && b1->ack[1] != s)) + if (clock64() - t0 > 8000000000ll) __trap(); + } + __syncthreads(); + const int j = blockIdx.x, r = vjob[j] & 0xffff; + const float4* src = reinterpret_cast(bells.b[vjob[j] >> 16]->vy[j]); + float4* dst = reinterpret_cast(ey + (size_t) r * H); + for (int i = threadIdx.x; i < H / 4; i += blockDim.x) dst[i] = __ldcv(src + i); // not through the caches +} +struct PromoteArgs { + int *slot_of, *owner; + unsigned *stamp, *clock; + int nslot; + const uint8_t **tabA, **tabB; + uint8_t* pool; + size_t eb, partA; + const uint8_t* const* xsrc; // [NL * NE] device views + int *want, *nwant, *pend, *npend; + const uint8_t** fsrc; + uint8_t** fdst; + int* nfetch; + unsigned long long* fbytes; + int maxn; + const float* cnt; // [NL * NE] decayed use counts + int freq; // 1: victims by count, candidates by count, admission margin; 0: LRU, visit order + float gain; +}; +__global__ void k_promote_commit(PromoteArgs c) { + if (threadIdx.x) return; + unsigned t = *c.clock; + for (int i = 0; i < *c.npend; ++i) { + const int key = c.pend[i], v = c.pend[PMAX + i]; + c.owner[v] = key; + c.slot_of[key] = v; + c.stamp[v] = ++t; + c.tabA[key] = c.pool + (size_t) v * c.eb; + c.tabB[key] = c.pool + (size_t) v * c.eb + c.partA; + } + *c.clock = t; + *c.npend = 0; + *c.nfetch = 0; +} +__global__ void k_promote_plan(PromoteArgs c) { + __shared__ unsigned long long wmin[32]; + __shared__ int n, np, stop; + if (threadIdx.x == 0) { + n = *c.nwant; + np = 0; + stop = c.maxn <= 0; + if (c.freq) // candidates most counted first (n <= WANT_MAX: insertion sort) + for (int i = 1; i < n; ++i) { + const int k = c.want[i]; + int j = i; + for (; j > 0 && c.cnt[c.want[j - 1]] < c.cnt[k]; --j) c.want[j] = c.want[j - 1]; + c.want[j] = k; + } + else + n = min(n, c.maxn); + } + __syncthreads(); + for (int m = 0; m < n && !stop; ++m) { + // victim: the lowest (count or stamp, slot); an empty slot first, a slot in flight never + unsigned long long best = ~0ull; + for (int i = threadIdx.x; i < c.nslot; i += blockDim.x) { + const int o = c.owner[i]; + const unsigned key = c.stamp[i] == 0xffffffffu ? 0xffffffffu + : !c.freq ? c.stamp[i] + : o < 0 ? 0u + : __float_as_uint(c.cnt[o]); // counts >= 0: ordered as uints + best = min(best, ((unsigned long long) key << 32) | (unsigned) i); + } +#pragma unroll + for (int o = 16; o; o >>= 1) best = min(best, __shfl_xor_sync(0xffffffffu, best, o)); + if ((threadIdx.x & 31) == 0) wmin[threadIdx.x / 32] = best; + __syncthreads(); + if (threadIdx.x == 0) { + for (int w = 1; w < (int) (blockDim.x / 32); ++w) best = min(best, wmin[w]); + const int v = (int) (best & 0xffffffffu), key = c.want[m], old = c.owner[v]; + const bool admit = !c.freq || old < 0 || c.cnt[key] >= c.cnt[old] + c.gain; + if (c.slot_of[key] < 0 && c.stamp[v] != 0xffffffffu && admit) { // (resident meanwhile: a prefill's cache) + if (old >= 0) { c.slot_of[old] = -1; c.tabA[old] = nullptr; c.tabB[old] = nullptr; } + c.owner[v] = -1; + c.stamp[v] = 0xffffffffu; // in flight: never a victim before its commit + c.pend[np] = key; + c.pend[PMAX + np] = v; + c.fsrc[np] = c.xsrc[key]; + c.fdst[np] = c.pool + (size_t) v * c.eb; + ++np; + stop = np >= c.maxn; + } else if (!admit) { + stop = 1; // the next candidates are counted less: none beats this victim either + } + } + __syncthreads(); + } + if (threadIdx.x == 0) { + *c.npend = np; + *c.nfetch = np; + *c.fbytes += (unsigned long long) np * c.eb; + *c.nwant = 0; + } +} +__global__ void k_decay(float* cnt, int n, float f) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) cnt[i] *= f; +} +PromoteArgs promote_args(bool nv) { + return {E.slot_of, nv ? E.owner_nv : E.owner_mx, nv ? E.stamp_nv : E.stamp_mx, E.clock, nv ? E.nslot_nv : E.nslot_mx, + E.tabA, E.tabB, nv ? E.pool_nv : E.pool_mx, nv ? NV_BYTES : MX_BYTES, nv ? NV_A : MX_A, E.xsrc_d, + nv ? E.want_nv : E.want_mx, nv ? E.nwant_nv : E.nwant_mx, nv ? E.pend_nv : E.pend_mx, nv ? E.npend_nv : E.npend_mx, + nv ? E.psrc_nv : E.psrc_mx, nv ? E.pdst_nv : E.pdst_mx, nv ? E.pnf_nv : E.pnf_mx, E.fbytes, + nv ? g_promote_nv : g_promote_mx, E.cnt, g_place_freq ? 1 : 0, g_gain}; +} +// start of a decode token: the copies planned at the end of the previous one, on a side stream (few blocks: the +// token's own kernels keep the SMs) +// BG_BLOCKS blocks in all, one expert after the other: blocks waiting on PCIe reads hold SM slots, so few of them +__global__ void k_fetch_bg(const uint8_t* const* __restrict__ src_nv, uint8_t* const* __restrict__ dst_nv, const int* nnv, + const uint8_t* const* __restrict__ src_mx, uint8_t* const* __restrict__ dst_mx, const int* nmx) { + const int a = *nnv, b = *nmx; + for (int m = 0; m < a + b; ++m) { + const bool nv = m < a; + const uint4* src = reinterpret_cast(nv ? src_nv[m] : src_mx[m - a]); + uint4* dst = reinterpret_cast(nv ? dst_nv[m] : dst_mx[m - a]); + const size_t n = (nv ? NV_BYTES : MX_BYTES) / 16, st = (size_t) gridDim.x * blockDim.x; + size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; + for (; i + 3 * st < n; i += 4 * st) { + const uint4 x0 = src[i], x1 = src[i + st], x2 = src[i + 2 * st], x3 = src[i + 3 * st]; + dst[i] = x0; dst[i + st] = x1; dst[i + 2 * st] = x2; dst[i + 3 * st] = x3; + } + for (; i < n; i += st) dst[i] = src[i]; + } +} +void promote_fork() { + CK(cudaEventRecord(E.ev_fork, cudaStreamPerThread)); + CK(cudaStreamWaitEvent(E.side, E.ev_fork, 0)); + k_fetch_bg<<>>(E.psrc_nv, E.pdst_nv, E.pnf_nv, E.psrc_mx, E.pdst_mx, E.pnf_mx); + CK(cudaEventRecord(E.ev_join, E.side)); +} +// --kv-grow shrinking a pool: the promotions planned at the end of the last token are dropped (resizes run between +// tokens with the device idle: their copies have not started), their slots empty again; later misses want them again +__global__ void k_promote_cancel(const int* pend, int* npend, int* pnf, unsigned* stamp) { + if (threadIdx.x) return; + for (int i = 0; i < *npend; ++i) stamp[pend[PMAX + i]] = 0; + *npend = 0; + *pnf = 0; +} +void promote_cancel() { + k_promote_cancel<<<1, 32>>>(E.pend_nv, E.npend_nv, E.pnf_nv, E.stamp_nv); + k_promote_cancel<<<1, 32>>>(E.pend_mx, E.npend_mx, E.pnf_mx, E.stamp_mx); +} +// end of a decode token: join the copies, commit them, plan the next ones +void promote_join() { + CK(cudaStreamWaitEvent(cudaStreamPerThread, E.ev_join, 0)); + if (g_place_freq) k_decay<<<(NL * NE + 255) / 256, 256>>>(E.cnt, NL * NE, g_decay); + for (int nv = 1; nv >= 0; --nv) { + k_promote_commit<<<1, 32>>>(promote_args(nv)); + k_promote_plan<<<1, 1024>>>(promote_args(nv)); + } +} +void expert_cpu_ring(int l, const float* x) { + const bool nv = l < MXFP8_FIRST; + k_cache_cpu<<<1, 256>>>(l, E.ids, x, E.slot_of, nv ? E.stamp_nv : E.stamp_mx, E.clock, nv ? E.want_nv : E.want_mx, + nv ? E.nwant_nv : E.nwant_mx, E.bell_d, E.cpu_nodes, E.d_seq, E.d_cur, E.cnt, E.sync); + if (E.sync.us_nv > 0.0f) k_fetch<<>>(E.fsrc, E.fdst, E.nfetch, ex_bytes(l)); +} +void setup_cpu() { + if (const char* p = std::getenv("INK2_PROMOTE")) std::sscanf(p, "%d,%d", &g_promote_nv, &g_promote_mx); + if (const char* p = std::getenv("INK2_BG_BLOCKS")) g_bg_blocks = std::max(1, std::atoi(p)); + if (const char* p = std::getenv("INK2_PLACE")) g_place_freq = std::string(p) != "lru"; + if (const char* p = std::getenv("INK2_DECAY")) g_decay = (float) std::atof(p); + if (const char* p = std::getenv("INK2_GAIN")) g_gain = (float) std::atof(p); + E.cnt = (float*) dalloc((size_t) NL * NE * 4); + CK(cudaMemset(E.cnt, 0, (size_t) NL * NE * 4)); + g_promote_nv = std::min(g_promote_nv, PMAX); + g_promote_mx = std::min(g_promote_mx, PMAX); + const size_t bell_bytes = (sizeof(ink2cpu::InkBell) + 4095) & ~(size_t) 4095; + for (int n = 0; n < E.cpu_nodes; ++n) { // placed like the experts: node n, or the GPU's node with one node + const int place = E.cpu_nodes > 1 ? n : std::max(gpu_node(), 0); + E.bell[n] = (ink2cpu::InkBell*) ink2cpu::node_alloc(bell_bytes, place); + if (!E.bell[n]) { std::fprintf(stderr, "cannot map the CPU doorbell\n"); std::exit(1); } + std::memset((void*) E.bell[n], 0, sizeof(ink2cpu::InkBell)); + CK(cudaHostRegister((void*) E.bell[n], bell_bytes, cudaHostRegisterMapped | cudaHostRegisterPortable)); + void* dv = nullptr; + CK(cudaHostGetDevicePointer(&dv, (void*) E.bell[n], 0)); + E.bell_d.b[n] = (ink2cpu::InkBell*) dv; + } + if (E.cpu_nodes < 2) E.bell_d.b[1] = E.bell_d.b[0]; + E.home_d = (const uint8_t*) upload(E.home.data(), E.home.size()); + // PCIe share (INK2_PCIE=0: off): staging slots, and one expert's copy timed with the kernel that will do it + // (best of 5; INK2_PCIE_US: an NVFP4 expert's us instead, e.g. to play a faster link) + SyncArgs& a = E.sync; // (off: us_nv 0, k_cache_cpu still writes nfetch = 0) + a.xsrc = E.xsrc_d; a.tabA = E.tabA; a.tabB = E.tabB; a.fsrc = E.fsrc; a.fdst = E.fdst; a.nfetch = E.nfetch; + a.fbytes = E.fbytes; a.home = E.home_d; + a.keys = (int*) dalloc(SYNC_MAX * 4); + if (!(std::getenv("INK2_PCIE") && std::string(std::getenv("INK2_PCIE")) == "0")) { + a.stage = (uint8_t*) dalloc((size_t) SYNC_MAX * MX_BYTES); + const uint8_t* srcd = nullptr; // layer 0's expert 0 (an NVFP4 one), its device view + CK(cudaMemcpy(&srcd, E.xsrc_d, sizeof srcd, cudaMemcpyDeviceToHost)); + const int one = 1; + CK(cudaMemcpy(E.fsrc, &srcd, sizeof srcd, cudaMemcpyHostToDevice)); + CK(cudaMemcpy(E.fdst, &a.stage, sizeof a.stage, cudaMemcpyHostToDevice)); + CK(cudaMemcpy(E.nfetch, &one, 4, cudaMemcpyHostToDevice)); + cudaEvent_t e0, e1; + CK(cudaEventCreate(&e0)); + CK(cudaEventCreate(&e1)); + float best = 1e9f; + for (int i = 0; i < 5; ++i) { + CK(cudaEventRecord(e0)); + k_fetch<<>>(E.fsrc, E.fdst, E.nfetch, NV_BYTES); + CK(cudaEventRecord(e1)); + CK(cudaEventSynchronize(e1)); + float ms = 0; + CK(cudaEventElapsedTime(&ms, e0, e1)); + best = std::min(best, ms); + } + CK(cudaEventDestroy(e0)); + CK(cudaEventDestroy(e1)); + const int zero = 0; + CK(cudaMemcpy(E.nfetch, &zero, 4, cudaMemcpyHostToDevice)); + a.us_nv = std::getenv("INK2_PCIE_US") ? (float) std::atof(std::getenv("INK2_PCIE_US")) : 1e3f * best; + a.us_mx = a.us_nv * (float) MX_BYTES / (float) NV_BYTES; + a.margin = std::getenv("INK2_PCIE_MARGIN") ? (float) std::atof(std::getenv("INK2_PCIE_MARGIN")) : 120.0f; + std::fprintf(stderr, "cpu experts: PCIe share on, an NVFP4 expert over PCIe %.0f us (%.1f GB/s)\n", a.us_nv, + NV_BYTES / (a.us_nv * 1e3)); + } + auto zi = [](size_t n) { int* p = (int*) dalloc(n * 4); CK(cudaMemset(p, 0, n * 4)); return p; }; + E.d_seq = (unsigned*) zi(1); + E.d_cur = (unsigned*) zi(1); + E.vjob = zi(ink2cpu::BELL_J); + E.nvjob = zi(1); + E.want_nv = zi(WANT_MAX); E.want_mx = zi(WANT_MAX); E.nwant_nv = zi(1); E.nwant_mx = zi(1); + E.pend_nv = zi(2 * PMAX); E.pend_mx = zi(2 * PMAX); E.npend_nv = zi(1); E.npend_mx = zi(1); + E.psrc_nv = (const uint8_t**) dalloc(PMAX * sizeof(void*)); + E.psrc_mx = (const uint8_t**) dalloc(PMAX * sizeof(void*)); + E.pdst_nv = (uint8_t**) dalloc(PMAX * sizeof(void*)); + E.pdst_mx = (uint8_t**) dalloc(PMAX * sizeof(void*)); + E.pnf_nv = zi(1); + E.pnf_mx = zi(1); + CK(cudaStreamCreateWithFlags(&E.side, cudaStreamNonBlocking)); + CK(cudaEventCreateWithFlags(&E.ev_fork, cudaEventDisableTiming)); + CK(cudaEventCreateWithFlags(&E.ev_join, cudaEventDisableTiming)); + ink2cpu::Setup s; + s.nl = NL; s.ne = NE; s.mx_first = MXFP8_FIRST; s.h = H; s.ff = FF; + s.ex = E.xh.data(); + s.home = E.home.data(); + s.f13 = E.hf13.data(); + s.f2 = E.hf2.data(); + s.nv_partA = NV_A; s.mx_partA = MX_A; + s.gate_cap = GATE_CAP; s.up_cap = UP_CAP; + s.bell[0] = E.bell[0]; + s.bell[1] = E.bell[1]; + s.threads = E.cpu_threads; + ink2cpu::start(s); +} + +// GGUF expert GEMV launches (runtime ggml type -> kernel), INK2_GG_RPW rows per warp (2, 4, 8; default 4) +int g_gg_rpw = 4; +template +void gg_sel_r(int t, const uint8_t* const* tab, size_t rb, const float* x, int xs, float* y, int N, int K) { + const dim3 g((unsigned) (N / (8 * R)), TOPK); + const size_t sm = (size_t) (K + 512 + 4) * 4; + switch (t) { + case GG_IQ3_S: k_gemv_gg_sel<<>>(tab, rb, E.ids, x, xs, y, N, K); break; + case GG_IQ4_NL: k_gemv_gg_sel<<>>(tab, rb, E.ids, x, xs, y, N, K); break; + default: k_gemv_gg_sel<<>>(tab, rb, E.ids, x, xs, y, N, K); + } +} +template +void gg_sel(int t, const uint8_t* const* tab, size_t rb, const float* x, int xs, float* y, int N, int K) { + switch (g_gg_rpw) { + case 2: gg_sel_r(t, tab, rb, x, xs, y, N, K); break; + case 8: gg_sel_r(t, tab, rb, x, xs, y, N, K); break; + default: gg_sel_r(t, tab, rb, x, xs, y, N, K); + } +} + +void moe(const Layer& Y, const float* x, const float* r, float* mhist, const float* mlp_conv, float* out) { + k_gemv_bf16_rowblock<<>>(Y.router.d, x, E.rl, H); + k_router<<<1, NE>>>(E.rl, Y.router_bias, E.ids, E.wts); + if (E.rec_mode == 1) k_rec_ids<<<1, TOPK>>>(E.ids, E.rec + (size_t) g_slot * E.ctx * TOPK, E.d_pos); + if (E.cpu) expert_cpu_ring(int(&Y - E.L), x); + else if (E.offload) expert_cache(int(&Y - E.L), E.ids, TOPK); + const Experts& X = Y.ex; + if (X.gg13) { + gg_sel(X.gg13, X.tA, X.rb13, x, 0, E.gu, 2 * FF, H); + gg_sel(X.gg2, X.tB, X.rb2, E.gu, 2 * FF, E.ey, H, FF); + } else if (X.nvfp4) { +#define SEL(R) \ + k_gemv_nvfp4_sel<((R) < 2 ? 2 : (R)), true><<>>( \ + X.tA, X.f13, E.ids, x, 0, E.gu, 2 * FF, H, E.act); \ + k_gemv_nvfp4_sel<<>>(X.tB, X.f2, E.ids, E.act, FF, E.ey, H, FF); + switch (g_sel_rpw) { case 1: SEL(1) break; case 2: SEL(2) break; case 8: SEL(8) break; default: SEL(4) } +#undef SEL + } else { +#define SEL(R) \ + k_gemv_mxfp8_sel<<>>(X.tA, E.ids, x, 0, E.gu, 2 * FF, H); \ + k_gemv_mxfp8_sel<<>>(X.tB, E.ids, E.gu, 2 * FF, E.ey, H, FF); + switch (g_sel_rpw) { case 1: SEL(1) break; case 2: SEL(2) break; case 8: SEL(8) break; default: SEL(4) } +#undef SEL + } + if (E.cpu) k_cpu_wait<<>>(E.bell_d, E.home_d, E.d_cur, E.cpu_nodes, E.ey, E.sync); + k_moe_tail<<<(H + 255) / 256, 256>>>(E.ey, E.wts, mhist, mlp_conv, r, out, E.d_pos); +} + +// one layer application: input E.h, block states Bbuf[0..nB), output E.out; msgs = 4 x H or nullptr +void layer_forward(int l, Slot& S, int nB, const float* msgs) { + const Layer& Y = E.L[l]; + float* stack_h = E.Bbuf + (size_t) nB * H; + copy(stack_h, E.h, H); // stack [B..., h] + const float *xq, *xk, *xv; + if (Y.full) { + if (!msgs) { // l > 0 always (full layers are 5, 11, 17, 23) + attnres(E.Bbuf, nB + 1, Y.attn_query, 3, nullptr, Y.q_norm, Y.k_norm, Y.v_norm, E.a); + xq = E.a; xk = E.a + H; xv = E.a + 2 * H; + } else { + attnres(E.Bbuf, nB + 1, Y.attn_query, 3, E.a); + const Gate* g3[3] = {&Y.gates[0], &Y.gates[1], &Y.gates[2]}; + const float* x3[3] = {E.a, E.a + H, E.a + 2 * H}; + const float* m3[3] = {msgs, msgs + H, msgs + 2 * H}; + float* y3[3] = {E.t[0], E.t[1], E.t[2]}; + const float* nw3[3] = {Y.q_norm, Y.k_norm, Y.v_norm}; + float* yn3[3] = {E.xq, E.xk, E.xv}; + message_gates(3, g3, x3, m3, y3, nw3, yn3); + xq = E.xq; xk = E.xk; xv = E.xv; + } + } else if (!msgs) { + if (l > 0) attnres(E.Bbuf, nB + 1, Y.attn_query, 1, nullptr, Y.attn_norm, nullptr, nullptr, E.xq); + else rms(E.h, Y.attn_norm, E.xq); + xq = xk = xv = E.xq; + } else { + attnres(E.Bbuf, nB + 1, Y.attn_query, 1, E.a); + const Gate* g3[3] = {&Y.gates[0], &Y.gates[1], &Y.gates[2]}; + const float* x3[3] = {E.a, E.a, E.a}; + const float* m3[3] = {msgs, msgs + H, msgs + 2 * H}; + float* y3[3] = {E.t[0], E.t[1], E.t[2]}; + const float* nw3[3] = {Y.attn_norm, Y.attn_norm, Y.attn_norm}; + float* yn3[3] = {E.xq, E.xk, E.xv}; + message_gates(3, g3, x3, m3, y3, nw3, yn3); + xq = E.xq; xk = E.xk; xv = E.xv; + } + attention(Y, S, xq, xk, xv); + int ns; + const float* r; + if (l % BLOCK == 0) { // block boundary: the residual restarts, B gains h (already at Bbuf[nB]) + k_attn_tail<<>>(E.attn_out, S.ahist, Y.attn_conv, E.h, E.att2, E.Bbuf + (size_t) (nB + 1) * H, 1, E.d_pos); + r = E.att2; + ns = nB + 2; + } else { + k_attn_tail<<>>(E.attn_out, S.ahist, Y.attn_conv, E.h, E.r, stack_h, 0, E.d_pos); + r = E.r; + ns = nB + 1; + } + if (!msgs) { + attnres(E.Bbuf, ns, Y.mlp_query, 1, nullptr, Y.mlp_norm, nullptr, nullptr, E.mn); + } else { + attnres(E.Bbuf, ns, Y.mlp_query, 1, E.m); + const Gate* g1[1] = {&Y.gates[3]}; + const float* x1[1] = {E.m}; + const float* m1[1] = {msgs + 3 * H}; + float* y1[1] = {E.t[3]}; + const float* nw1[1] = {Y.mlp_norm}; + float* yn1[1] = {E.mn}; + message_gates(1, g1, x1, m1, y1, nw1, yn1); + } + moe(Y, E.mn, r, S.mhist, Y.mlp_conv, E.out); + if (l % BLOCK == 0) copy(stack_h, E.h, H); // B gets the layer's input (the caller counts it) +} + +// token tok's embedding row (host table, BF16 or Q8_0) as fp32 +void embed_row(int tok, float* out) { + if (!E.embed_q8.empty()) { + const uint8_t* b = E.embed_q8.data() + (size_t) tok * (H / 32) * 34; + for (int j = 0; j < H / 32; ++j, b += 34) { + uint16_t hb; + std::memcpy(&hb, b, 2); + const float d = __half2float(*reinterpret_cast(&hb)); + for (int i = 0; i < 32; ++i) out[32 * j + i] = d * (float) (int8_t) b[2 + i]; + } + return; + } + for (int i = 0; i < H; ++i) { + uint32_t u = (uint32_t) E.embed[(size_t) tok * H + i] << 16; + std::memcpy(&out[i], &u, 4); + } +} + +// the token's embedding row (host table) into E.emb_in +void upload_embed(int tok) { + vec e(H); + embed_row(tok, e.data()); + CK(cudaMemcpyAsync(E.emb_in, e.data(), H * 4, cudaMemcpyHostToDevice)); +} + +// one token: embedding in E.emb_in, position in E.d_pos; writes E.logits. Device work only (captured in a graph): +// the host-side pointer swaps are the same on every call (an even number), so a replay sees the same buffers. +// --spec: the one-token path also keeps the drafter's features of its position, ring row pos % FRING +constexpr int FRING = 16; +float* g_fring = nullptr; // [FRING][4][H] +__global__ void k_feat_store(const float* __restrict__ x, float* __restrict__ ring, const int* __restrict__ d_pos, int tap) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < H) ring[((size_t) (*d_pos % FRING) * 4 + tap) * H + i] = x[i]; +} +void forward_device() { + if (E.cpu) promote_fork(); + rms(E.emb_in, E.embed_norm, E.h); + int nB = 0, visit = 0; + auto run = [&](int l, int slot, const float* msgs) { + g_slot = slot; + if (g_fring && (visit == 5 || visit == 23 || visit == 41)) + k_feat_store<<>>(E.h, g_fring, E.d_pos, visit == 5 ? 0 : visit == 23 ? 1 : 2); + ++visit; + layer_forward(l, E.S[slot], nB, msgs); + if (l % BLOCK == 0) ++nB; + std::swap(E.h, E.out); + }; + for (int l = 0; l < LOOP_BEGIN; ++l) run(l, l, nullptr); + const int npre = nB; + copy(E.pre_h, E.h, H); + copy(E.preB, E.Bbuf, (size_t) npre * H); + for (int l = LOOP_BEGIN; l < LOOP_END; ++l) run(l, l, nullptr); + for (int p = 1; p < PASSES; ++p) { + const int nprev = nB - (npre + 1); // previous pass' block states after its first one, then its output h + copy(E.prev_stack, E.Bbuf + (size_t) (npre + 1) * H, (size_t) nprev * H); + copy(E.prev_stack + (size_t) nprev * H, E.h, H); + copy(E.h, E.pre_h, H); + copy(E.Bbuf, E.preB, (size_t) npre * H); + nB = npre; + for (int i = 0; i < NLOOP; ++i) { + attnres(E.prev_stack, nprev + 1, E.msg_queries + (size_t) i * 4 * H, 4, E.msgs); + run(LOOP_BEGIN + i, NL + (p - 1) * NLOOP + i, E.msgs); + } + } + for (int l = LOOP_END; l < NL; ++l) run(l, l, nullptr); + copy(E.Bbuf + (size_t) nB * H, E.h, H); + attnres(E.Bbuf, nB + 1, E.final_query, 1, nullptr, E.norm, nullptr, nullptr, E.mn); + if (g_fring) k_feat_store<<>>(E.mn, g_fring, E.d_pos, 3); + gemv(E.unembed, E.mn, E.logits, VOCAB); + k_softcap<<<(VOCAB + 255) / 256, 256>>>(E.logits, VOCAB, LOGIT_CAP); + if (E.cpu) promote_join(); +} + +// --------------------------------------------------------------------------------------------------------------------- +// Prefill: the prompt in chunks of up to TP tokens. Same math as forward_device, row-batched: dense products as +// cuBLAS SGEMM (full FP32) on an fp32 copy of the BF16 matrix made per use, experts as kb_moe_gemm (weights decoded on +// the fly), attention tiled (kb_attn). It fills the same KV / conv state as the one-token path, which then decodes. + +struct Prefill { + int TP = 512; // chunk capacity + bool tc = false; // --tc 1: fp16 tensor-core products (NVFP4 experts, attention proj / wo) + cublasHandle_t cb = nullptr, cbh = nullptr; // fp32 (pedantic) / fp16 tensor-op handles + half *wh = nullptr, *xh = nullptr, *qh = nullptr; // fp16 weight / activation / query scratch + float* wf = nullptr; // fp32 copy of one dense matrix (or a slice of the unembedding) + size_t wf_cap = 0; + float *x0, *h, *out, *B, *preB, *pre_h, *prev, *msgs, *a, *xq, *xk, *xv, *P, *kc, *vc, *rel, *att, *attn_out, *att2, + *r, *m, *mn, *moe, *y2, *cat, *gdown, *gfg, *rl, *wts, *gu, *act, *ey, *lg; + int *ids, *rows, *slot, *tile_e, *tile_r0, *ntiles, *eoff, *ecnt; + int np_max = 0; + // offload (expert_parts): copy stream, two staging halves with their batch tables (pinned host / device) + cudaStream_t cs = nullptr; + cudaEvent_t ev_free[2], ev_ready[2]; + uint8_t* stg[2]; + size_t stg_half = 192ull << 20; + unsigned stg_turn = 0; + const uint8_t** ptab[2]; + const uint8_t** dtab[2]; + std::vector nonres[NL]; // per layer, the experts not in the pools (refreshed at each prefill call) + size_t fbytes = 0; + // speculative decoding (--spec): per chunk row, the drafter's target features [T][4][H] (h entering layer visits + // 5, 23, 41, final normed output); verify mode: per-row greedy token into am[T] instead of the last row's logits + float* feat = nullptr; + int* am = nullptr; + bool rows_argmax = false; + float* rows_host = nullptr; // rows_argmax + rows_copy (sampling): the rows' softcapped logits [T][VOCAB] (pinned) + bool rows_copy = false; + float *spm = nullptr, *spl = nullptr, *spo = nullptr; // kb_attn_tc key splits (verify) +}; +constexpr int SPLIT_MAX = 64; +#ifndef SPLIT_KEYS +#define SPLIT_KEYS 32 +#endif +Prefill PF; + +// Elastic prompt buffers (--kv-grow with offload): the chunk-sized buffers over 8 MiB and the staging halves live in +// growable ranges, mapped while a prompt is read (memory taken from the expert pools) and unmapped after. +half* g_dq[2] = {nullptr, nullptr}; // decoded expert weights (fp16), two in turn +int g_dq_min = 4096; // INK2_DQ_MIN: prompt chunks from this size take the decode-once path (0: never); 3090 at 1024: 2154 -> 1769 tok/s, at 4096: 2652 -> 2941 +bool g_pf_routed = false; // this chunk runs through the decode cache (short chunks): no streaming +int g_pf_routed_max = 64; // INK2_ROUTED_MAX: chunks of up to this many tokens fetch only the experts they route to +bool g_pf_elastic = false; +std::vector g_pfr; +std::vector g_pfr_whole; // 1: parts at offsets of the full --chunk (the region, the fp16 input thirds), mapped + // whole; 2: the staging halves (whole, and not at all for a routed short prompt) +int g_pf_mapped_T = 0; +void* pf_alloc(size_t bytes, int whole = 0) { + if (!g_pf_elastic || bytes < ((size_t) 8 << 20)) return dalloc(bytes); + g_pfr.emplace_back(); + g_pfr.back().init(bytes); + g_pfr_whole.push_back(whole); + return g_pfr.back().ptr(); +} +float* pf_floats(size_t n) { return (float*) pf_alloc(n * 4); } + +// the shared region's phases laid out for a chunk of T tokens (P / rel, gu / ey / act, lg) +float* g_region = nullptr; +int g_cur_T = 0; +void pf_layout(int T) { + g_cur_T = T; + PF.P = g_region; PF.rel = g_region + (size_t) T * PF.np_max; + PF.gu = g_region; PF.ey = g_region; PF.act = g_region + (size_t) T * TOPK * 2 * FF; + PF.lg = g_region; +} + +void alloc_prefill() { + g_pfr.reserve(64); + const size_t T = PF.TP, TH = T * H; + CK(cublasCreate(&PF.cb) == CUBLAS_STATUS_SUCCESS ? cudaSuccess : cudaErrorUnknown); + cublasSetStream(PF.cb, cudaStreamPerThread); + cublasSetMathMode(PF.cb, CUBLAS_PEDANTIC_MATH); // full FP32, no TF32 / reduced-precision shortcuts + for (int l = 0; l < NL; ++l) PF.np_max = std::max(PF.np_max, E.L[l].proj.n); + PF.wf_cap = std::max((size_t) PF.np_max * H, (size_t) 8192 * H); + PF.wf = dfloats(PF.wf_cap); + PF.x0 = pf_floats(TH); PF.h = pf_floats(TH); PF.out = pf_floats(TH); PF.B = pf_floats(8 * TH); PF.preB = pf_floats(8 * TH); + PF.pre_h = pf_floats(TH); PF.prev = pf_floats(8 * TH); PF.msgs = pf_floats(4 * TH); PF.a = pf_floats(3 * TH); + PF.xq = pf_floats(TH); PF.xk = pf_floats(TH); PF.xv = pf_floats(TH); + PF.kc = pf_floats(T * KVD); PF.vc = pf_floats(T * KVD); PF.att = pf_floats(((T + 63) / 64 * 64) * QD); + PF.attn_out = pf_floats(TH); PF.att2 = pf_floats(TH); PF.r = pf_floats(TH); PF.m = pf_floats(TH); PF.mn = pf_floats(TH); + PF.moe = pf_floats(TH); PF.y2 = pf_floats(TH); PF.cat = pf_floats(2 * TH); PF.gdown = pf_floats(T * GATE_RANK); + PF.gfg = pf_floats(2 * TH); PF.rl = pf_floats(T * NE); PF.wts = pf_floats(T * TOPK); + // One region, phases with disjoint lifetimes (saves ~217 KB per chunk token, 445 MB at chunk 2048): + // attention: P [T][np_max], rel [T][NQ][EXTENT]; MoE: gu [T*TOPK][2FF] then ey (same rows, H = 2FF) after the + // SwiGLU has read gu, act [T*TOPK][FF] after gu; after the last layer: lg [T][8192] (all-logits dumps only) + static_assert(2 * FF == H, "ey aliases gu"); + const size_t att_n = T * ((size_t) PF.np_max + NQ * EXTENT), moe_n = T * TOPK * (size_t) 3 * FF; + // (sub-buffers at offsets of the chunk being read, pf_layout: the region maps in proportion to the chunk) + g_region = (float*) pf_alloc(std::max(std::max(att_n, moe_n), T * (size_t) 8192) * 4); + pf_layout((int) T); + auto ints = [](size_t n) { return (int*) dalloc(n * 4); }; + PF.ids = ints(T * TOPK); PF.rows = ints(T * TOPK); PF.slot = ints(T * TOPK); + PF.tile_e = ints(T * TOPK / FM + NE); PF.tile_r0 = ints(T * TOPK / FM + NE); PF.ntiles = ints(1); + PF.eoff = ints(NE); PF.ecnt = ints(NE); + // the fp32 prompt attention needs 83 KB of shared memory: more than Turing's 64 KB (--tc 1 does not use it) +#if defined(STRATA_USE_HIP) + if (!PF.tc) { + int max_smem = 0; + if (cudaDeviceGetAttribute(&max_smem, cudaDevAttrMaxSharedMemoryPerBlockOptin, 0) != cudaSuccess || + (size_t) max_smem < FA_SMEM) { + std::fprintf(stderr, "the fp32 prompt attention needs %zu bytes of shared memory, more than this card has: use --tc 1\n", FA_SMEM); + std::exit(1); + } + } +#endif + if (!PF.tc && cudaFuncSetAttribute(kb_attn, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) FA_SMEM) != cudaSuccess) { + std::fprintf(stderr, "the fp32 prompt attention needs %zu bytes of shared memory, more than this card has: use --tc 1\n", FA_SMEM); + std::exit(1); + } + if (E.offload) { + CK(cudaStreamCreateWithFlags(&PF.cs, cudaStreamNonBlocking)); + for (int h = 0; h < 2; ++h) { + CK(cudaEventCreateWithFlags(&PF.ev_free[h], cudaEventDisableTiming)); + CK(cudaEventCreateWithFlags(&PF.ev_ready[h], cudaEventDisableTiming)); + PF.stg[h] = (uint8_t*) pf_alloc(PF.stg_half, 2); + CK(cudaHostAlloc((void**) &PF.ptab[h], NE * sizeof(void*), cudaHostAllocDefault)); + PF.dtab[h] = (const uint8_t**) dalloc(NE * sizeof(void*)); + } + } + if (PF.tc) { + CK(cublasCreate(&PF.cbh) == CUBLAS_STATUS_SUCCESS ? cudaSuccess : cudaErrorUnknown); + cublasSetStream(PF.cbh, cudaStreamPerThread); + PF.wh = (half*) dalloc((size_t) PF.np_max * H * 2); + if (g_is_gguf) for (auto& d : g_dq) d = (half*) dalloc((size_t) 2 * FF * H * 2); // one expert part (w13: 2FF x H) + PF.xh = (half*) pf_alloc(3 * T * QD * 2); + PF.qh = (half*) pf_alloc(((T + 63) / 64 * 64) * QD * 2); + } + // cuBLAS loads its kernels and workspace at the first call of each shape class: run them once now, before the + // expert pools take the free memory (a first prompt after that would find only the reserve) + { + const int Tw[3] = {16, 256, PF.TP}, Nw[3] = {NE, H, QD}; // the buffers hold QD x QD and TP x QD + const size_t big = (size_t) PF.TP * QD; + float *a = nullptr, *w = nullptr, *c = nullptr; + CK(cudaMalloc(&a, big * 4)); CK(cudaMalloc(&w, (size_t) QD * QD * 4)); CK(cudaMalloc(&c, big * 4)); + const float one = 1.0f, zero = 0.0f; + for (int ti : Tw) + for (int nw : Nw) { + cublasSgemm(PF.cb, CUBLAS_OP_T, CUBLAS_OP_N, nw, ti, H, &one, w, H, a, H, &zero, c, nw); + if (PF.tc) + cublasGemmEx(PF.cbh, CUBLAS_OP_T, CUBLAS_OP_N, nw, ti, H, &one, w, CUDA_R_16F, H, a, CUDA_R_16F, H, &zero, c, + CUDA_R_32F, nw, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT); + } + CK(cudaDeviceSynchronize()); + CK(cudaFree(a)); CK(cudaFree(w)); CK(cudaFree(c)); + } +} + +// A chunk is read routed only if its pools can hold all its ids at once, so that no group's plan evicts an expert an +// earlier group of the chunk fetched (its tiles would be skipped): T x TOPK, plus the promotions in flight with the +// CPU experts, within the smaller pool. CBA: counts ids, not distinct experts (a device count would cost a sync). +bool pf_routed_ok(int T) { + if (!E.offload || T > g_pf_routed_max) return false; + const int need = T * TOPK + (E.cpu ? PMAX : 0); + return need <= E.nslot_nv && (!E.nslot_mx || need <= E.nslot_mx); +} +// a chunk that streams after all (pf_map left the staging out, then a K/V growth shrank the pools): the staging halves +// mapped now, before forward_prefill reads what the pools hold +void pf_map_staging() { + size_t add = 0; + for (size_t i = 0; i < g_pfr.size(); ++i) if (g_pfr_whole[i] == 2) add += g_pfr[i].reserved - g_pfr[i].mapped; + if (!add) return; + CK(cudaDeviceSynchronize()); + const size_t keep = vram_keep(), fr = vram_free(); + if (fr < add + keep) pools_release((double) (add + keep - fr), "the staging"); + for (size_t i = 0; i < g_pfr.size(); ++i) + if (g_pfr_whole[i] == 2 && !g_pfr[i].map_to(g_pfr[i].reserved)) { std::fprintf(stderr, "staging: out of VRAM\n"); std::exit(1); } +} +// the prompt buffers for chunks of T tokens (T <= --chunk): mapped, from the pools if VRAM is short +void pf_map(int T) { + if (g_pfr.empty() || T <= g_pf_mapped_T) return; + CK(cudaDeviceSynchronize()); + size_t add = 0; + std::vector want(g_pfr.size()); + for (size_t i = 0; i < g_pfr.size(); ++i) { + const VRange& r = g_pfr[i]; + want[i] = g_pfr_whole[i] == 2 ? (pf_routed_ok(T) ? 0 : r.reserved) + : g_pfr_whole[i] ? r.reserved : r.need(std::min(r.reserved, (size_t) ((double) r.reserved * (T + 64) / PF.TP))); + if (want[i] > r.mapped) add += want[i] - r.mapped; + } + const size_t keep = vram_keep(), fr = vram_free(); + if (fr < add + keep) pools_release((double) (add + keep - fr), "the prompt buffers"); + for (size_t i = 0; i < g_pfr.size(); ++i) + if (!g_pfr[i].map_to(want[i])) { std::fprintf(stderr, "prompt buffers: out of VRAM\n"); std::exit(1); } + g_pf_mapped_T = T; +} +#include "ink2_grow_guard.cuh" +// the largest chunk (<= T, halving down to 256) whose prompt buffers and K/V growth leave each pool its FETCH_MAX +// slots: long contexts on a small card read the prompt in smaller chunks instead of stopping (g_pf_full: not even 256) +int pf_fit(int T, int pos0) { + if (g_pfr.empty() || !E.offload) return T; + for (;; T /= 2) { + size_t want = 0, have = 0; + for (size_t i = 0; i < g_pfr.size(); ++i) { + const VRange& r = g_pfr[i]; + want += g_pfr_whole[i] == 2 ? (pf_routed_ok(T) ? 0 : r.reserved) + : g_pfr_whole[i] ? r.reserved : r.need(std::min(r.reserved, (size_t) ((double) r.reserved * (T + 64) / PF.TP))); + have += r.mapped; + } + const int nc = std::min(E.ctx, (pos0 + T + E.grow_step - 1) / E.grow_step * E.grow_step); + const double kv_add = E.grow && nc > E.kv_cells ? (double) (kv_mapped_for(nc) - kv_mapped_for(E.kv_cells)) : 0.0; + const double deficit = kv_add + (double) want - (double) have + (double) vram_keep() - (double) vram_free() + 8.0 * g_vmm.gran; + const bool fits = pools_keep_min(deficit); + if (fits || T <= 256) { g_pf_full = !fits; return T; } + } +} +// after a prompt: the buffers' memory back to the pools +void pf_unmap() { + if (g_pfr.empty() || !g_pf_mapped_T) return; + CK(cudaDeviceSynchronize()); + for (auto& r : g_pfr) r.unmap_to(0); + g_pf_mapped_T = 0; + pools_fill(); +} + +// tensor-core dense product: Y[t][0..n) = fp16(X[t]) . fp16(W rows [first, first + n))^T, fp32 accumulation. +// wcvt: convert W (whole matrix) into PF.wh first; xslot: which third of PF.xh holds X's fp16 copy +void gemv_multi(const DMat& W, int first, int n, const float* X, int ldx, float* Y, int ldy, int T); +void hgemm(const DMat& W, bool wcvt, int first, int n, const float* X, int ldx, int K, int xslot, float* Y, int ldy, int T) { + if (T <= SMALL_T) { gemv_multi(W, first, n, X, ldx, Y, ldy, T); return; } + if (wcvt) { + const size_t nw = (size_t) W.n * W.k; + if (W.q) kb_q8_to_f16<<<(unsigned) ((nw / 8 + 255) / 256), 256>>>(W.q, W.qs, PF.wh, nw / 8); + else kb_bf16_to_f16<<<(unsigned) ((nw + 255) / 256), 256>>>(W.d, PF.wh, nw); + } + half* xh = PF.xh + (size_t) xslot * g_cur_T * QD; // (thirds of the chunk being read) + const size_t nx = (size_t) T * K; + kb_f32_to_f16<<<(unsigned) ((nx + 255) / 256), 256>>>(X, ldx, K, xh, nx); + const float one = 1.0f, zero = 0.0f; + if (cublasGemmEx(PF.cbh, CUBLAS_OP_T, CUBLAS_OP_N, n, T, K, &one, PF.wh + (size_t) first * K, CUDA_R_16F, K, xh, + CUDA_R_16F, K, &zero, Y, CUDA_R_32F, ldy, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT) != CUBLAS_STATUS_SUCCESS) { + std::fprintf(stderr, "cublasGemmEx failed (%d x %d x %d)\n", n, T, K); + std::exit(1); + } +} + +// rows [first, first + n) of W (BF16) into PF.wf as fp32 +const float* wf32(const DMat& W, int first = 0, int n = -1) { + if (n < 0) n = W.n - first; + const size_t n8 = (size_t) n * W.k / 8; + if ((size_t) n * W.k > PF.wf_cap) { std::fprintf(stderr, "wf32: %d x %d over the scratch\n", n, W.k); std::exit(1); } + if (W.q) kb_q8_to_f32<<<(unsigned) ((n8 + 255) / 256), 256>>>(W.q + (size_t) first * W.k, W.qs + (size_t) first * (W.k / 32), PF.wf, n8); + else kb_bf16_to_f32<<<(unsigned) ((n8 + 255) / 256), 256>>>(W.d + (size_t) first * W.k, PF.wf, n8); + return PF.wf; +} +// Y[t][0..n) (row stride ldy) = X[t] (row stride ldx) . Wf[0..n)^T, Wf fp32 [n][K] +void sgemm(const float* Wf, int n, int K, const float* X, int ldx, float* Y, int ldy, int T) { + const float one = 1.0f, zero = 0.0f; + if (cublasSgemm(PF.cb, CUBLAS_OP_T, CUBLAS_OP_N, n, T, K, &one, Wf, K, X, ldx, &zero, Y, ldy) != CUBLAS_STATUS_SUCCESS) { + std::fprintf(stderr, "cublasSgemm failed (%d x %d x %d)\n", n, T, K); + std::exit(1); + } +} +// rows [first, first + n) of W, T <= SMALL_T vectors +void gemv_multi(const DMat& W, int first, int n, const float* X, int ldx, float* Y, int ldy, int T) { + if (W.q) { // CBA: Q8 (GGUF) rows read once per vector; a multi-vector Q8 GEMV if short GGUF chunks matter + for (int t = 0; t < T; ++t) gemv(W, X + (size_t) t * ldx, Y + (size_t) t * ldy, n, first); + return; + } + if (W.k == 64) { + k_gemv_bf16_multi_k64<<<(unsigned) ((n + 31) / 32), 256>>>(W.d + (size_t) first * 64, X, ldx, Y, ldy, n, T); + return; + } + if (n <= 256) { + k_gemv_bf16_multi_rows<<<(unsigned) n, 256>>>(W.d + (size_t) first * W.k, X, ldx, Y, ldy, W.k, T); + return; + } + if (g_verify_tc && W.k % 64 == 0) { + k_gemv_bf16_tc<<<(unsigned) ((n + 15) / 16), 256>>>(W.d + (size_t) first * W.k, X, ldx, Y, ldy, n, W.k, T); + return; + } + int R = 4; // as gemv(): fewer rows per warp while the grid is short + while (R > 1 && (n + 8 * R - 1) / (8 * R) < g_gemv_min_blocks) R /= 2; + const unsigned g = (unsigned) ((n + 8 * R - 1) / (8 * R)); + const uint16_t* w = W.d + (size_t) first * W.k; + switch (R) { + case 1: k_gemv_bf16_multi<1><<>>(w, X, ldx, Y, ldy, n, W.k, T); break; + case 2: k_gemv_bf16_multi<2><<>>(w, X, ldx, Y, ldy, n, W.k, T); break; + default: k_gemv_bf16_multi<4><<>>(w, X, ldx, Y, ldy, n, W.k, T); + } +} +void gemm(const DMat& W, const float* X, int ldx, float* Y, int ldy, int T) { + if (T <= SMALL_T) { gemv_multi(W, 0, W.n, X, ldx, Y, ldy, T); return; } + sgemm(wf32(W), W.n, W.k, X, ldx, Y, ldy, T); +} + +void message_gate_b(const Gate& g, const float* x, int sx, const float* m, int sm, const float* nw, float* yn, int T) { + kb_rms2<<>>(x, sx, m, sm, PF.cat); + gemm(g.down, PF.cat, 2 * H, PF.gdown, GATE_RANK, T); + gemm(g.fg, PF.gdown, GATE_RANK, PF.gfg, 2 * H, T); + kb_gate_mix_rms<<>>(x, sx, m, sm, PF.gfg, nw, yn); +} + +void conv_b(const float* x, int sx, float* hist, const float* w, const float* dw, float* y, int sy, int C, int T, int pos0) { + kb_conv<<>>(x, sx, hist, w, dw, y, sy, C, pos0); + kb_hist_store<<>>(x, sx, hist, C, T, pos0); +} + +void attention_b(const Layer& Y, Slot& S, const float* xq, int sq, const float* xk, int sk, const float* xv, int sv, + int T, int pos0) { + const int np = Y.proj.n; + float* P = PF.P; + if (PF.tc) { + if (xq == xk && xk == xv && sq == sk && sk == sv) { + hgemm(Y.proj, true, 0, np, xq, sq, H, 0, P, np, T); + } else { + hgemm(Y.proj, true, 0, OFF_K, xq, sq, H, 0, P, np, T); + hgemm(Y.proj, false, Y.off_k, Y.n_k, xk, sk, H, 1, P + Y.off_k, np, T); + hgemm(Y.proj, false, Y.off_v, Y.n_v, xv, sv, H, 2, P + Y.off_v, np, T); + } + } + const float* W = PF.tc || T <= SMALL_T ? nullptr : wf32(Y.proj); + if (PF.tc) { + } else if (T <= SMALL_T) { + if (xq == xk && xk == xv && sq == sk && sk == sv) { + gemv_multi(Y.proj, 0, np, xq, sq, P, np, T); + } else { + gemv_multi(Y.proj, 0, OFF_K, xq, sq, P, np, T); + gemv_multi(Y.proj, Y.off_k, Y.n_k, xk, sk, P + Y.off_k, np, T); + gemv_multi(Y.proj, Y.off_v, Y.n_v, xv, sv, P + Y.off_v, np, T); + } + } else if (xq == xk && xk == xv && sq == sk && sk == sv) { + sgemm(W, np, H, xq, sq, P, np, T); + } else { + sgemm(W, OFF_K, H, xq, sq, P, np, T); + sgemm(W + (size_t) Y.off_k * H, Y.n_k, H, xk, sk, P + Y.off_k, np, T); + sgemm(W + (size_t) Y.off_v * H, Y.n_v, H, xv, sv, P + Y.off_v, np, T); + } + kb_head_clip<<>>(P, np, Y.q_scale, HD, QK_CLIP, Y.full, pos0); + if (E.kvm == 3) kb_wht<<>>(P, np); + float *k = P + Y.off_k, *v = P + Y.off_v; + if (Y.full) { + conv_b(k, np, S.khist, Y.k_static, k + KVD, PF.kc, KVD, KVD, T, pos0); + conv_b(v, np, S.vhist, Y.v_static, v + KVD, PF.vc, KVD, KVD, T, pos0); + } else { + conv_b(k, np, S.khist, Y.k_conv, nullptr, PF.kc, KVD, KVD, T, pos0); + conv_b(v, np, S.vhist, Y.v_conv, nullptr, PF.vc, KVD, KVD, T, pos0); + } + kb_kv_store<<>>(PF.kc, PF.vc, S.K, S.V, S.ksc, S.vsc, S.cap, pos0); + kb_head_clip<<>>(P + OFF_REL, np, Y.rel_scale, DREL, REL_CLIP, Y.full, pos0); + kb_rel_logits<<>>(P + OFF_REL, np, Y.rel_proj, PF.rel); + if (PF.tc) { + const size_t nqh = (size_t) T * QD; + kb_f32_to_f16<<<(unsigned) ((nqh + 255) / 256), 256>>>(P, np, QD, PF.qh, nqh); + // verify blocks: the keys split over blocks (8 blocks would walk the whole context otherwise) + int ns = 1; + if (T <= SMALL_T && PF.spo) { // graph (pos0 < 0): a fixed count, the kernel spreads the keys it finds + const int nk = pos0 < 0 ? (S.full ? E.ctx : WINDOW + T) : pos0 + T - (S.full ? 0 : std::max(0, pos0 - WINDOW + 1)); + ns = std::min(SPLIT_MAX, std::max(1, nk / SPLIT_KEYS)); + } + kb_attn_tc<<>>(PF.qh, P, np, S.K, S.V, S.ksc, S.vsc, PF.rel, S.cap, + S.full ? 0 : WINDOW, pos0, T, PF.att, ns, PF.spm, + PF.spl, PF.spo); + if (ns > 1) kb_attn_merge_split<<>>(PF.spm, PF.spl, PF.spo, ns, PF.att); + } else { + kb_attn<<>>(P, np, S.K, S.V, S.ksc, S.vsc, PF.rel, S.cap, S.full ? 0 : WINDOW, pos0, + T, PF.att); + } + if (kv_rot_v(E.kvm)) kb_wht<<>>(PF.att, QD); + kb_mul_sigmoid<<>>(PF.att, P + OFF_GATE, np); + if (PF.tc) hgemm(Y.wo, true, 0, H, PF.att, QD, QD, 0, PF.attn_out, H, T); + else gemm(Y.wo, PF.att, QD, PF.attn_out, H, T); +} + +// Offloaded prefill: the expert cache is frozen during a prefill (a chunk touches nearly every expert, an LRU would +// only thrash). A grouped product runs once over the resident experts (the decode tables, null = not resident: +// tiles skipped), then over the others in batches streamed into two staging halves on PF.cs (copy of batch b + 1 +// overlapping the product of batch b). Each row still sees exactly its expert's weights: bit-identical. +// part B (w2) is streamed after the SwiGLU, separately from part A (w13): each byte crosses PCIe once per layer call. +// CBA: streams every non-resident expert of the layer, used by the chunk or not (a 1024-token chunk uses 119-127 of 128). +template void expert_parts(int l, bool partB, F launch) { + const Experts& X = E.L[l].ex; + launch(partB ? X.tB : X.tA); + if (!E.offload || g_pf_routed) return; + const auto& nonres = PF.nonres[l]; + const size_t eb = ex_bytes(l), part = partB ? eb - ex_partA(l) : ex_partA(l), off = partB ? ex_partA(l) : 0; + const int per = (int) (PF.stg_half / part); + for (int b0 = 0, bi = 0; b0 < (int) nonres.size(); b0 += per, ++bi) { + const int h = PF.stg_turn++ & 1, n = std::min(per, (int) nonres.size() - b0); + CK(cudaStreamWaitEvent(PF.cs, PF.ev_free[h], 0)); + CK(cudaEventSynchronize(PF.ev_ready[h])); // the previous table copy out of ptab[h] is done + const uint8_t** tab = PF.ptab[h]; + std::fill(tab, tab + NE, nullptr); + for (int j = 0; j < n; ++j) { + const int e = nonres[b0 + j]; + uint8_t* d = PF.stg[h] + (size_t) j * part; + CK(cudaMemcpyAsync(d, E.xh[(size_t) l * NE + e] + off, part, cudaMemcpyHostToDevice, PF.cs)); + tab[e] = d; + } + // the batch table rides on the copy stream too (pinned slot per half, reused once ev_free[h] has fired) + CK(cudaMemcpyAsync(PF.dtab[h], PF.ptab[h], NE * sizeof(void*), cudaMemcpyHostToDevice, PF.cs)); + CK(cudaEventRecord(PF.ev_ready[h], PF.cs)); + CK(cudaStreamWaitEvent(cudaStreamPerThread, PF.ev_ready[h], 0)); + launch(PF.dtab[h]); + CK(cudaEventRecord(PF.ev_free[h], cudaStreamPerThread)); + PF.fbytes += (size_t) n * part; + } +} + +// GGUF grouped products (prompt), runtime type -> kernel +template +void gg_gemm(int t, bool tc, int maxt, const void* A, int lda, const int* rows, const uint8_t* const* tab, size_t rb, + float* C, int N, int K) { +#define GGA PF.tile_e, PF.tile_r0, PF.ntiles, PF.eoff, PF.ecnt, C, N, K + if (tc) { + const dim3 g((unsigned) maxt, (unsigned) (N / TN)); + const half* a = (const half*) A; + switch (t) { + case GG_IQ3_S: kb_moe_gemm_tc_gg<<>>(a, lda, tab, rb, GGA); break; + case GG_IQ4_NL: kb_moe_gemm_tc_gg<<>>(a, lda, tab, rb, GGA); break; + default: kb_moe_gemm_tc_gg<<>>(a, lda, tab, rb, GGA); + } + } else { + const dim3 g((unsigned) maxt, (unsigned) (N / FN)); + const float* a = (const float*) A; + switch (t) { + case GG_IQ3_S: kb_moe_gemm_gg<<>>(a, lda, rows, tab, rb, GGA); break; + case GG_IQ4_NL: kb_moe_gemm_gg<<>>(a, lda, rows, tab, rb, GGA); break; + default: kb_moe_gemm_gg<<>>(a, lda, rows, tab, rb, GGA); + } + } +#undef GGA +} + +void moe_b(const Layer& Y, const float* x, float* out, int T, int pos0) { + gemm(Y.router, x, H, PF.rl, NE, T); + if (E.rec_mode == 2) + kb_router_forced<<>>(PF.rl, E.rec + ((size_t) g_slot * E.ctx + pos0) * TOPK, PF.ids, PF.wts); + else + k_router<<>>(PF.rl, Y.router_bias, PF.ids, PF.wts); + kb_moe_plan<<<1, 1024>>>(PF.ids, T, PF.rows, PF.slot, PF.tile_e, PF.tile_r0, PF.ntiles, PF.eoff, PF.ecnt); + const Experts& X = Y.ex; + const int l = int(&Y - E.L), nr = T * TOPK, maxt = nr / FM + NE; + // A short chunk uses few experts: it makes the ones it routes to resident through the decode cache (groups of 8 + // tokens: at most 64 misses per plan) instead of streaming every expert the pools do not hold. + // (g_pf_routed: set per chunk by forward_prefill; the small-T path below caches its own experts) + if (g_pf_routed && !(T <= SMALL_T && !X.gg13)) + for (int t0 = 0; t0 < T; t0 += 8) expert_cache(l, PF.ids + (size_t) t0 * TOPK, std::min(8, T - t0) * TOPK); + if (T <= SMALL_T && !X.gg13) { // offload: the verify's experts through the decode cache (T x TOPK ids), not the staging + // a verify block with the CPU experts: its misses on the CPU (other short chunks: fetched, as before) + const bool vcpu = E.cpu && PF.rows_argmax && T <= ink2cpu::BELL_M; + if (vcpu) { + const bool nv = l < MXFP8_FIRST; + k_cache_cpu_b<<<1, 1024>>>(l, PF.ids, PF.slot, T, x, E.slot_of, nv ? E.stamp_nv : E.stamp_mx, E.clock, + nv ? E.want_nv : E.want_mx, nv ? E.nwant_nv : E.nwant_mx, E.bell_d, E.cpu_nodes, + E.home_d, E.d_seq, E.d_cur, E.cnt, E.vjob, E.nvjob); + } else if (E.offload) expert_cache(l, PF.ids, T * TOPK); + const int RR = g_grp_r; + auto g = RR == 2 ? (X.nvfp4 ? k_moe_gemv_grp : k_moe_gemv_grp) + : RR == 1 ? (X.nvfp4 ? k_moe_gemv_grp : k_moe_gemv_grp) + : (X.nvfp4 ? k_moe_gemv_grp : k_moe_gemv_grp); + auto parts = [&](bool partB, auto launch) { if (E.offload) launch(partB ? X.tB : X.tA); else expert_parts(l, partB, launch); }; + parts(false, [&](const uint8_t* const* t) { + g<<>>(x, H, PF.rows, t, X.f13, PF.tile_e, PF.tile_r0, PF.ntiles, PF.eoff, + PF.ecnt, PF.gu, 2 * FF, H); + }); + kb_swiglu<<<(unsigned) (((size_t) nr * FF + 255) / 256), 256>>>(PF.gu, PF.act, nr); + parts(true, [&](const uint8_t* const* t) { + g<<>>(PF.act, FF, nullptr, t, X.f2, PF.tile_e, PF.tile_r0, PF.ntiles, PF.eoff, + PF.ecnt, PF.ey, H, FF); + }); + if (vcpu) k_cpu_wait_b<<>>(E.bell_d, E.d_cur, E.cpu_nodes, E.vjob, E.nvjob, PF.ey); + } else if (X.gg13 && PF.tc && g_dq_min > 0 && T >= g_dq_min) { + // decode-once: per expert with rows, its part decoded to fp16 and one cuBLAS GEMM over its rows (the row + // counts are read back). The non-resident experts' copies into the two staging halves are queued before the + // read-back (they do not depend on it), so they overlap the layer's attention. + half* ah = reinterpret_cast(PF.act); + kb_gather_h<<>>(x, PF.rows, ah); + const auto& nr_list = PF.nonres[l]; + const bool stream = E.offload && !g_pf_routed && !nr_list.empty(); + const size_t eb = ex_bytes(l), partA = ex_partA(l), partB = eb - partA; + const int perA = (int) (PF.stg_half / partA), perB = (int) (PF.stg_half / partB); + const bool early = stream && (int) nr_list.size() <= perA && (int) nr_list.size() <= perB; + int hA = -1, hB = -1; + auto stage = [&](bool pb, int b0, int n) { // queue the copies of nr_list[b0 .. b0 + n) into a half + const int h = PF.stg_turn++ & 1; + const size_t part = pb ? partB : partA, poff = pb ? partA : 0; + CK(cudaStreamWaitEvent(PF.cs, PF.ev_free[h], 0)); + CK(cudaEventSynchronize(PF.ev_ready[h])); + const uint8_t** tab = PF.ptab[h]; + std::fill(tab, tab + NE, nullptr); + for (int j = 0; j < n; ++j) { + const int e = nr_list[b0 + j]; + uint8_t* d = PF.stg[h] + (size_t) j * part; + CK(cudaMemcpyAsync(d, E.xh[(size_t) l * NE + e] + poff, part, cudaMemcpyHostToDevice, PF.cs)); + tab[e] = d; + } + CK(cudaMemcpyAsync(PF.dtab[h], PF.ptab[h], NE * sizeof(void*), cudaMemcpyHostToDevice, PF.cs)); + CK(cudaEventRecord(PF.ev_ready[h], PF.cs)); + PF.fbytes += (size_t) n * part; + return h; + }; + if (early) { hA = stage(false, 0, (int) nr_list.size()); hB = stage(true, 0, (int) nr_list.size()); } + std::vector cnt(NE), off(NE); + CK(cudaMemcpyAsync(cnt.data(), PF.ecnt, NE * 4, cudaMemcpyDeviceToHost)); + CK(cudaMemcpyAsync(off.data(), PF.eoff, NE * 4, cudaMemcpyDeviceToHost)); + CK(cudaStreamSynchronize(cudaStreamPerThread)); + std::vector nonres(NE, false); + if (E.offload) for (int e : nr_list) nonres[e] = true; + int turn = 0; + auto run_parts = [&](bool pb, int hpre) { + const int t = pb ? X.gg2 : X.gg13, N = pb ? H : 2 * FF, K = pb ? FF : H; + const size_t rb = pb ? X.rb2 : X.rb13; + float* C = pb ? PF.ey : PF.gu; + auto one = [&](const uint8_t* const* tab, int e) { + if (!cnt[e]) return; + half* wbuf = g_dq[turn++ & 1]; + const unsigned gb = 2 * 34 * 4; + if (!pb) { + if (t == GG_IQ3_S) kb_dequant_gg<<>>(tab, e, rb, wbuf, N, K); + else if (t == GG_IQ4_NL) kb_dequant_gg<<>>(tab, e, rb, wbuf, N, K); + else kb_dequant_gg<<>>(tab, e, rb, wbuf, N, K); + } else { + if (t == GG_IQ3_S) kb_dequant_gg<<>>(tab, e, rb, wbuf, N, K); + else if (t == GG_IQ4_NL) kb_dequant_gg<<>>(tab, e, rb, wbuf, N, K); + else kb_dequant_gg<<>>(tab, e, rb, wbuf, N, K); + } + const float one_f = 1.0f, zero = 0.0f; + if (cublasGemmEx(PF.cbh, CUBLAS_OP_T, CUBLAS_OP_N, N, cnt[e], K, &one_f, wbuf, CUDA_R_16F, K, + ah + (size_t) off[e] * K, CUDA_R_16F, K, &zero, C + (size_t) off[e] * N, CUDA_R_32F, N, + CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT) != CUBLAS_STATUS_SUCCESS) { + std::fprintf(stderr, "cublasGemmEx (expert) failed\n"); + std::exit(1); + } + }; + const auto& tabd = pb ? X.tB : X.tA; + for (int e = 0; e < NE; ++e) if (!nonres[e]) one(tabd, e); + if (!stream) return; + auto use = [&](int h, int b0, int n) { + CK(cudaStreamWaitEvent(cudaStreamPerThread, PF.ev_ready[h], 0)); + for (int j = 0; j < n; ++j) one(PF.dtab[h], nr_list[b0 + j]); + CK(cudaEventRecord(PF.ev_free[h], cudaStreamPerThread)); + }; + if (hpre >= 0) { use(hpre, 0, (int) nr_list.size()); return; } + const int per = pb ? perB : perA; + for (int b0 = 0; b0 < (int) nr_list.size(); b0 += per) { + const int n = std::min(per, (int) nr_list.size() - b0); + use(stage(pb, b0, n), b0, n); + } + }; + run_parts(false, hA); + kb_swiglu_h<<<(unsigned) (((size_t) nr * FF + 255) / 256), 256>>>(PF.gu, ah, nr); + run_parts(true, hB); + } else if (X.gg13) { // GGUF experts: the same streaming of part A (gate_up) then part B (down) + half* ah = reinterpret_cast(PF.act); + const int mt = PF.tc ? nr / TM + NE : maxt; + if (PF.tc) kb_gather_h<<>>(x, PF.rows, ah); + expert_parts(l, false, [&](const uint8_t* const* t) { + if (PF.tc) gg_gemm(X.gg13, true, mt, ah, H, nullptr, t, X.rb13, PF.gu, 2 * FF, H); + else gg_gemm(X.gg13, false, mt, x, H, PF.rows, t, X.rb13, PF.gu, 2 * FF, H); + }); + if (PF.tc) kb_swiglu_h<<<(unsigned) (((size_t) nr * FF + 255) / 256), 256>>>(PF.gu, ah, nr); + else kb_swiglu<<<(unsigned) (((size_t) nr * FF + 255) / 256), 256>>>(PF.gu, PF.act, nr); + expert_parts(l, true, [&](const uint8_t* const* t) { + if (PF.tc) gg_gemm(X.gg2, true, mt, ah, FF, nullptr, t, X.rb2, PF.ey, H, FF); + else gg_gemm(X.gg2, false, mt, PF.act, FF, nullptr, t, X.rb2, PF.ey, H, FF); + }); + } else if (PF.tc) { + const int maxt_tc = nr / TM + NE; + auto g = X.nvfp4 ? kb_moe_gemm_tc : kb_moe_gemm_tc; + // fp16 A copies live in the act region: the gathered input [nr][H] halves (same bytes as act [nr][FF] floats) + // until the SwiGLU, then the fp16 act [nr][FF] + half* ah = reinterpret_cast(PF.act); + kb_gather_h<<>>(x, PF.rows, ah); + expert_parts(l, false, [&](const uint8_t* const* t) { + g<<>>(ah, H, t, X.f13, PF.tile_e, PF.tile_r0, PF.ntiles, PF.eoff, PF.ecnt, + PF.gu, 2 * FF, H); + }); + kb_swiglu_h<<<(unsigned) (((size_t) nr * FF + 255) / 256), 256>>>(PF.gu, ah, nr); + expert_parts(l, true, [&](const uint8_t* const* t) { + g<<>>(ah, FF, t, X.f2, PF.tile_e, PF.tile_r0, PF.ntiles, PF.eoff, PF.ecnt, PF.ey, + H, FF); + }); + } else { + auto g = X.nvfp4 ? kb_moe_gemm : kb_moe_gemm; + expert_parts(l, false, [&](const uint8_t* const* t) { + g<<>>(x, H, PF.rows, t, X.f13, PF.tile_e, PF.tile_r0, PF.ntiles, PF.eoff, + PF.ecnt, PF.gu, 2 * FF, H); + }); + kb_swiglu<<<(unsigned) (((size_t) nr * FF + 255) / 256), 256>>>(PF.gu, PF.act, nr); + expert_parts(l, true, [&](const uint8_t* const* t) { + g<<>>(PF.act, FF, nullptr, t, X.f2, PF.tile_e, PF.tile_r0, PF.ntiles, PF.eoff, + PF.ecnt, PF.ey, H, FF); + }); + } + kb_combine<<>>(PF.ey, PF.slot, PF.wts, out); +} + +void copy_b(float* dst, const float* src, size_t n) { copy(dst, src, n); } +void add_b(const float* a, const float* b, float* y, size_t n) { kb_add<<<(unsigned) ((n + 255) / 256), 256>>>(a, b, y, n); } + +// layer_forward for T tokens: input PF.h, block states PF.B[0..nB) ([S][T][H]), output PF.out; msgs [T][4][H] or null +void layer_forward_b(int l, Slot& S, int nB, const float* msgs, int T, int pos0) { + const Layer& Y = E.L[l]; + const size_t ES = (size_t) T * H; + float* stack_h = PF.B + nB * ES; + copy_b(stack_h, PF.h, ES); + const float *xq, *xk, *xv; + int sq = H, sk = H, sv = H; + if (Y.full) { + if (!msgs) { + attnres(PF.B, nB + 1, Y.attn_query, 3, nullptr, Y.q_norm, Y.k_norm, Y.v_norm, PF.a, T); + xq = PF.a; xk = PF.a + H; xv = PF.a + 2 * H; + sq = sk = sv = 3 * H; + } else { + attnres(PF.B, nB + 1, Y.attn_query, 3, PF.a, nullptr, nullptr, nullptr, nullptr, T); + message_gate_b(Y.gates[0], PF.a, 3 * H, msgs, 4 * H, Y.q_norm, PF.xq, T); + message_gate_b(Y.gates[1], PF.a + H, 3 * H, msgs + H, 4 * H, Y.k_norm, PF.xk, T); + message_gate_b(Y.gates[2], PF.a + 2 * H, 3 * H, msgs + 2 * H, 4 * H, Y.v_norm, PF.xv, T); + xq = PF.xq; xk = PF.xk; xv = PF.xv; + } + } else if (!msgs) { + if (l > 0) attnres(PF.B, nB + 1, Y.attn_query, 1, nullptr, Y.attn_norm, nullptr, nullptr, PF.xq, T); + else k_rms<<>>(PF.h, Y.attn_norm, PF.xq, H); + xq = xk = xv = PF.xq; + } else { + attnres(PF.B, nB + 1, Y.attn_query, 1, PF.a, nullptr, nullptr, nullptr, nullptr, T); + message_gate_b(Y.gates[0], PF.a, H, msgs, 4 * H, Y.attn_norm, PF.xq, T); + message_gate_b(Y.gates[1], PF.a, H, msgs + H, 4 * H, Y.attn_norm, PF.xk, T); + message_gate_b(Y.gates[2], PF.a, H, msgs + 2 * H, 4 * H, Y.attn_norm, PF.xv, T); + xq = PF.xq; xk = PF.xk; xv = PF.xv; + } + attention_b(Y, S, xq, sq, xk, sk, xv, sv, T, pos0); + conv_b(PF.attn_out, H, S.ahist, Y.attn_conv, nullptr, PF.att2, H, H, T, pos0); + int ns; + const float* r; + if (l % BLOCK == 0) { + r = PF.att2; + copy_b(PF.B + (nB + 1) * ES, PF.att2, ES); + ns = nB + 2; + } else { + add_b(PF.h, PF.att2, PF.r, ES); + r = PF.r; + copy_b(stack_h, PF.r, ES); + ns = nB + 1; + } + if (!msgs) { + attnres(PF.B, ns, Y.mlp_query, 1, nullptr, Y.mlp_norm, nullptr, nullptr, PF.mn, T); + } else { + attnres(PF.B, ns, Y.mlp_query, 1, PF.m, nullptr, nullptr, nullptr, nullptr, T); + message_gate_b(Y.gates[3], PF.m, H, msgs + 3 * H, 4 * H, Y.mlp_norm, PF.mn, T); + } + moe_b(Y, PF.mn, PF.moe, T, pos0); + conv_b(PF.moe, H, S.mhist, Y.mlp_conv, nullptr, PF.y2, H, H, T, pos0); + add_b(r, PF.y2, PF.out, ES); + if (l % BLOCK == 0) copy_b(stack_h, PF.h, ES); +} + +// tokens ids[pos0 .. pos0 + T) -> logits of the last one in E.logits (all of them into `all` [T][VOCAB] if non-null) +// ===================================================================================================================== +// DSpark drafter (mtp.safetensors; reference: vLLM PR #69028, vllm/models/inkling2/nvidia/dspark.py). 3 dense layers +// over a block of DBLK rows at positions p..p+7: the anchor (last committed token, target embedding + embed norm) and +// 7 mask rows. Attention: the block (bidirectional) and the context K/V of the committed positions < p, computed from +// the target's features (h entering layer visits 5, 23, 41 + the final normed output, per position) mixed per layer +// (softmax(fuse_weight) row, rms, dflare_norm). Drafts: rows 1..7 through the target's LM head, corrected by a +// recurrent Markov head (folded into the LM head once), greedy. The drafter only proposes: its rounding changes the +// acceptance rate, never the output (the target verifies every token). Everything here is fp32 with bf16 weights; +// the reference rounds to bf16 after each op. +constexpr int DL = 3, DFF = 9216, DBLK = 8, MR = 256, DQKV = QD + 2 * KVD, DSPLIT_KEYS = 256, DSPLIT_MAX = 256; +constexpr int DLOCAL_CAP = WINDOW + 64; // local layers keep [p - 1024, p + 8) +constexpr float DTHETA = 1e6f, MCAP = 30.0f; + +// out[r] = rms(sum_t alpha[t] f[r][t]) * w; f rows [4][H] (stride 4H) +__global__ void kd_mix_rms(const float* __restrict__ f, const float* __restrict__ alpha, const float* __restrict__ w, + float* __restrict__ out) { + const float* x = f + (size_t) blockIdx.x * 4 * H; + float* y = out + (size_t) blockIdx.x * H; + const float a0 = alpha[0], a1 = alpha[1], a2 = alpha[2], a3 = alpha[3]; + float ss = 0.0f; + for (int i = threadIdx.x; i < H; i += blockDim.x) { + const float m = a0 * x[i] + a1 * x[H + i] + a2 * x[2 * H + i] + a3 * x[3 * H + i]; + ss += m * m; + } + ss = block_sum(ss); + const float r = rsqrtf(ss / H + EPS); + for (int i = threadIdx.x; i < H; i += blockDim.x) { + const float m = a0 * x[i] + a1 * x[H + i] + a2 * x[2 * H + i] + a3 * x[3 * H + i]; + y[i] = m * r * w[i]; + } +} +// res (= x when first, else += x when x), xn = rms(res) * w; one block per row +__global__ void kd_add_rms(const float* __restrict__ x, float* __restrict__ res, const float* __restrict__ w, + float* __restrict__ xn, int first) { + const size_t o = (size_t) blockIdx.x * H; + float ss = 0.0f; + for (int i = threadIdx.x; i < H; i += blockDim.x) { + const float v = first ? x[o + i] : res[o + i] + (x ? x[o + i] : 0.0f); + res[o + i] = v; + ss += v * v; + } + ss = block_sum(ss); + const float r = rsqrtf(ss / H + EPS); + for (int i = threadIdx.x; i < H; i += blockDim.x) xn[o + i] = res[o + i] * r * w[i]; +} +// per-head rms * w then neox RoPE at pos (fp32 inv_freq = theta^(-2i / HD), as the reference's cos/sin table); one +// 128-thread block per head row +__device__ __forceinline__ float head_norm_rope(float v, const float* __restrict__ w, int pos) { + __shared__ float red[4], sm[HD]; + const int d = threadIdx.x; + float ss = warp_sum(v * v); + __syncthreads(); + if ((d & 31) == 0) red[d >> 5] = ss; + __syncthreads(); + ss = red[0] + red[1] + red[2] + red[3]; + sm[d] = v * rsqrtf(ss / HD + EPS) * w[d]; + __syncthreads(); + const int i = d & 63; + const float inv = 1.0f / powf(DTHETA, (float) (2 * i) / HD), ang = (float) pos * inv; + float s, c; + sincosf(ang, &s, &c); + const float x1 = sm[i], x2 = sm[i + 64]; + return d < 64 ? x1 * c - x2 * s : x2 * c + x1 * s; +} +// block rows: q heads (q_norm) and k heads (k_norm) normed + roped in place at pos0 + row; k / v into the cache +__global__ void kd_qk_rope_store(float* qkv, const float* __restrict__ qn, const float* __restrict__ kn, int pos0, + __half* K, __half* V, int cap) { + pos0 = VPOS(pos0); + const int h = blockIdx.x, r = blockIdx.y, d = threadIdx.x; + float* x = qkv + (size_t) r * DQKV + (h < NQ ? h * HD : QD + (h - NQ) * HD); + const float o = head_norm_rope(x[d], h < NQ ? qn : kn, pos0 + r); + x[d] = o; + if (h >= NQ) { + const size_t c = (size_t) ((pos0 + r) % cap) * KVD + (h - NQ) * HD + d; + K[c] = __float2half(o); + V[c] = __float2half(qkv[(size_t) r * DQKV + QD + KVD + (h - NQ) * HD + d]); + } +} +// context K / V of committed positions pos0 + r: kv rows [k (KVD) | v (KVD)]; k normed (k_norm_ctx) + roped +__global__ void kd_ctx_store(const float* __restrict__ kv, const float* __restrict__ kn, int pos0, __half* K, __half* V, + int cap) { + const int g = blockIdx.x, r = blockIdx.y, d = threadIdx.x; + const float* x = kv + (size_t) r * 2 * KVD; + const float o = head_norm_rope(x[g * HD + d], kn, pos0 + r); + const size_t c = (size_t) ((pos0 + r) % cap) * KVD + g * HD + d; + K[c] = __float2half(o); + V[c] = __float2half(x[KVD + g * HD + d]); +} +// attention of the DBLK block rows of q head h (blockIdx.x) over keys [k0, k1) of split blockIdx.y; 4 warps over +// keys, a lane holds 4 dims; partial (max, sum, out) per (head, split, row) +__device__ __forceinline__ float4 ld4h(const __half* p) { + const uint2 u = *reinterpret_cast(p); + const float2 a = __half22float2(*reinterpret_cast(&u.x)), b = __half22float2(*reinterpret_cast(&u.y)); + return make_float4(a.x, a.y, b.x, b.y); +} +// keys [lo, p + DBLK), lo = 0 or (local) p + DBLK - (WINDOW + DBLK), spread over gridDim.y splits +__global__ void kd_attn_partial(const float* __restrict__ qkv, const __half* __restrict__ K, const __half* __restrict__ V, + int cap, int p, int local, float* pm, float* pl, float* po) { + p = VPOS(p); + // (local == 2: ablation, the block only, no context) + const int hi = p + DBLK, lo = local == 2 ? p : local ? max(0, hi - (WINDOW + DBLK)) : 0, per = (hi - lo + gridDim.y - 1) / gridDim.y; + const int h = blockIdx.x, s = blockIdx.y, g = h / NREP, w = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int k0 = lo + s * per, k1 = min(hi, k0 + per); + const float scale = rsqrtf((float) HD); + float4 q[DBLK], acc[DBLK]; + float m[DBLK], l[DBLK]; +#pragma unroll + for (int r = 0; r < DBLK; ++r) { + const float4 t = *reinterpret_cast(qkv + (size_t) r * DQKV + h * HD + 4 * lane); + q[r] = make_float4(t.x * scale, t.y * scale, t.z * scale, t.w * scale); + acc[r] = make_float4(0, 0, 0, 0); + m[r] = -INFINITY; + l[r] = 0.0f; + } + for (int j = k0 + w; j < k1; j += 4) { + const size_t c = (size_t) (j % cap) * KVD + g * HD + 4 * lane; + const float4 kk = ld4h(K + c), vv = ld4h(V + c); +#pragma unroll + for (int r = 0; r < DBLK; ++r) { + const float sc = warp_sum(q[r].x * kk.x + q[r].y * kk.y + q[r].z * kk.z + q[r].w * kk.w); + const float mn = fmaxf(m[r], sc), cf = __expf(m[r] - mn), p = __expf(sc - mn); + l[r] = l[r] * cf + p; + acc[r] = make_float4(acc[r].x * cf + p * vv.x, acc[r].y * cf + p * vv.y, acc[r].z * cf + p * vv.z, + acc[r].w * cf + p * vv.w); + m[r] = mn; + } + } + __shared__ float sm_m[4][DBLK], sm_l[4][DBLK]; + __shared__ float4 sm_o[4][DBLK][32]; +#pragma unroll + for (int r = 0; r < DBLK; ++r) { + if (!lane) { sm_m[w][r] = m[r]; sm_l[w][r] = l[r]; } + sm_o[w][r][lane] = acc[r]; + } + __syncthreads(); + for (int r = w; r < DBLK; r += 4) { + float M = -INFINITY, L = 0.0f; + float4 O = make_float4(0, 0, 0, 0); + for (int u = 0; u < 4; ++u) M = fmaxf(M, sm_m[u][r]); + for (int u = 0; u < 4; ++u) { + if (sm_m[u][r] == -INFINITY) continue; + const float cf = __expf(sm_m[u][r] - M); + const float4 t = sm_o[u][r][lane]; + L += sm_l[u][r] * cf; + O = make_float4(O.x + t.x * cf, O.y + t.y * cf, O.z + t.z * cf, O.w + t.w * cf); + } + const size_t idx = ((size_t) h * DSPLIT_MAX + s) * DBLK + r; + if (!lane) { pm[idx] = M; pl[idx] = L; } + reinterpret_cast(po + idx * HD)[lane] = O; + } +} +__global__ void kd_attn_merge(const float* __restrict__ pm, const float* __restrict__ pl, const float* __restrict__ po, + int ns, float* __restrict__ att) { + const int h = blockIdx.x, r = blockIdx.y, d = threadIdx.x; + float M = -INFINITY; + for (int s = 0; s < ns; ++s) M = fmaxf(M, pm[((size_t) h * DSPLIT_MAX + s) * DBLK + r]); + float L = 0.0f, O = 0.0f; + for (int s = 0; s < ns; ++s) { + const size_t idx = ((size_t) h * DSPLIT_MAX + s) * DBLK + r; + if (pm[idx] == -INFINITY) continue; + const float cf = __expf(pm[idx] - M); + L += pl[idx] * cf; + O += po[idx * HD + d] * cf; + } + att[(size_t) r * QD + h * HD + d] = O / L; +} +__global__ void kd_silu_mul(const float* __restrict__ gu, float* __restrict__ act) { + const int r = blockIdx.y, j = blockIdx.x * blockDim.x + threadIdx.x; + if (j >= DFF) return; + const float g = gu[(size_t) r * 2 * DFF + j], u = gu[(size_t) r * 2 * DFF + DFF + j]; + act[(size_t) r * DFF + j] = g / (1.0f + expf(-g)) * u; +} +// Markov step input [state | w1[prev]] +__global__ void kd_markov_in(const float* __restrict__ state, const uint16_t* __restrict__ w1, const int* __restrict__ prev, + float* __restrict__ in) { + const int j = threadIdx.x; + in[j] = state[j]; + const uint32_t u = (uint32_t) w1[(size_t) *prev * MR + j] << 16; + in[MR + j] = __uint_as_float(u); +} +// raw = Wsp [state, w1[prev]] + Wout out_i + (Wf f_rnn + bias); gate / cand / out split; state, latent +__global__ void kd_markov_gate(const float* __restrict__ raw, const float* __restrict__ ctx_i, const float* __restrict__ cf, + float* __restrict__ state, float* __restrict__ latent) { + const int j = threadIdx.x; + const float g = raw[j] + ctx_i[j] + cf[j], c = raw[MR + j] + ctx_i[MR + j] + cf[MR + j]; + const float o = raw[2 * MR + j] + ctx_i[2 * MR + j] + cf[2 * MR + j]; + const float gate = 1.0f / (1.0f + expf(-g)); + state[j] = gate * state[j] + (1.0f - gate) * tanhf(c); + latent[j] = tanhf(o); +} +// argmax over n of cap * tanh((a + b + c) / cap) (b, c optional): blocks -> (value, index) partials, then one block +// (ties: the lowest index) +constexpr int AM_BLOCKS = 160; +__device__ __forceinline__ void am_better(float& v, int& i, float v2, int i2) { + if (v2 > v || (v2 == v && i2 < i)) { v = v2; i = i2; } +} +__device__ __forceinline__ void am_block(float& v, int& i) { + __shared__ float sv[32]; + __shared__ int si[32]; + for (int o = 16; o; o >>= 1) am_better(v, i, __shfl_xor_sync(0xffffffffu, v, o), __shfl_xor_sync(0xffffffffu, i, o)); + __syncthreads(); + if ((threadIdx.x & 31) == 0) { sv[threadIdx.x >> 5] = v; si[threadIdx.x >> 5] = i; } + __syncthreads(); + if (threadIdx.x < 32) { + v = threadIdx.x < blockDim.x / 32 ? sv[threadIdx.x] : -INFINITY; + i = threadIdx.x < blockDim.x / 32 ? si[threadIdx.x] : 0x7fffffff; + for (int o = 16; o; o >>= 1) am_better(v, i, __shfl_xor_sync(0xffffffffu, v, o), __shfl_xor_sync(0xffffffffu, i, o)); + } +} +__global__ void kd_argmax_partial(const float* __restrict__ a, const float* __restrict__ b, const float* __restrict__ c, + int n, float* pv, int* pi) { + float v = -INFINITY; + int idx = 0x7fffffff; + for (int k = blockIdx.x * blockDim.x + threadIdx.x; k < n; k += gridDim.x * blockDim.x) { + float x = a[k] + (b ? b[k] : 0.0f) + (c ? c[k] : 0.0f); + x = MCAP * tanhf(x / MCAP); + if (x != x) x = -INFINITY; + am_better(v, idx, x, k); + } + am_block(v, idx); + if (threadIdx.x == 0) { pv[blockIdx.x] = v; pi[blockIdx.x] = idx; } +} +__global__ void kd_argmax_final(const float* __restrict__ pv, const int* __restrict__ pi, int nb, int* out) { + float v = -INFINITY; + int idx = 0x7fffffff; + for (int k = threadIdx.x; k < nb; k += blockDim.x) am_better(v, idx, pv[k], pi[k]); + am_block(v, idx); + if (threadIdx.x == 0) *out = idx; +} +// per-row argmax of the target's logits [T][VOCAB] (one block per row) +__global__ void k_rows_argmax(const float* __restrict__ lg, int n, int* out) { + const float* x = lg + (size_t) blockIdx.x * n; + float v = -INFINITY; + int idx = 0x7fffffff; + for (int k = threadIdx.x; k < n; k += blockDim.x) am_better(v, idx, x[k] != x[k] ? -INFINITY : x[k], k); + am_block(v, idx); + if (threadIdx.x == 0) out[blockIdx.x] = idx; +} +// fold of the Markov head's output projection into the LM head: fold[v] = U[v] . Wh (Wh [H][MR] fp32), fold_b[v] = +// U[v] . bh; one block of MR threads per vocabulary row +__global__ void kd_fold(const uint16_t* __restrict__ U, const float* __restrict__ Wh, const float* __restrict__ bh, + uint16_t* __restrict__ fold, float* __restrict__ fold_b) { + __shared__ float u[H]; + const size_t v = blockIdx.x; + for (int i = threadIdx.x; i < H; i += blockDim.x) u[i] = __uint_as_float((uint32_t) U[v * H + i] << 16); + __syncthreads(); + float acc = 0.0f, ab = 0.0f; + for (int i = 0; i < H; ++i) acc += u[i] * Wh[(size_t) i * MR + threadIdx.x]; + for (int i = threadIdx.x; i < H; i += blockDim.x) ab += u[i] * bh[i]; + ab = block_sum(ab); + const uint32_t bits = __float_as_uint(acc); // round to nearest even + fold[v * MR + threadIdx.x] = (uint16_t) ((bits + 0x7FFFu + ((bits >> 16) & 1u)) >> 16); + if (threadIdx.x == 0) fold_b[v] = ab; +} + +struct DLayer { + DMat qkv, kvc, o, gu, down; + const float *in_ln, *post_ln, *dflare, *q_norm, *k_norm, *k_norm_ctx; + bool local = false; + __half *K = nullptr, *V = nullptr; + int cap = 0; +}; +struct Drafter { + bool on = false; + DLayer L[DL]; + const float *norm, *mask_embed, *alpha, *mk_dflare, *rnn_bias, *fold_b; + DMat rsp, rout, rf, w1, fold; // rnn_proj columns [state | w1] / [out_i] / [f_rnn]; markov_w1; folded LM head + float *x, *res, *xn, *qkv, *att, *gu, *act, *out, *base, *ctxc, *ctxkv, *frnn, *cf, *mctx, *state, *in1, *raw, + *latent, *bias, *pm, *pl, *po, *pv; + int *drafts, *pi; + // stats + long verifies = 0, accepted = 0, hk[DBLK] = {}, plain = 0, switches = 0; +}; +Drafter D; +int g_draft_abl = 0; // INK2_DRAFT_ABL (tests): 1 = no Markov bias, 2 = no context K/V + +void draft_load(const std::string& dir) { + Ckpt mk; + mk.path = dir + "/mtp.safetensors"; + const std::string e = strata::image::st_read_header(mk.path, mk.st); + if (!e.empty()) { std::fprintf(stderr, "--spec: %s\n", e.c_str()); std::exit(1); } + const Ckpt* main_ck = E.ck; + E.ck = &mk; + for (int i = 0; i < DL; ++i) { + DLayer& Y = D.L[i]; + const std::string q = "layers." + std::to_string(i) + "."; + Y.local = i == 0 || i == 2; // mtp_config.local_layer_ids + Y.qkv = dmat_stack({q + "self_attn.q_proj.weight", q + "self_attn.k_proj.weight", q + "self_attn.v_proj.weight"}); + Y.kvc = dmat_stack({q + "self_attn.k_proj_ctx.weight", q + "self_attn.v_proj_ctx.weight"}); + Y.o = dmat(q + "self_attn.o_proj.weight"); + Y.gu = dmat_stack({q + "mlp.gate_proj.weight", q + "mlp.up_proj.weight"}); + Y.down = dmat(q + "mlp.down_proj.weight"); + Y.in_ln = fvec(q + "input_layernorm.weight"); + Y.post_ln = fvec(q + "post_attention_layernorm.weight"); + Y.dflare = fvec(q + "dflare_norm.weight"); + Y.q_norm = fvec(q + "self_attn.q_norm.weight"); + Y.k_norm = fvec(q + "self_attn.k_norm.weight"); + Y.k_norm_ctx = fvec(q + "self_attn.k_norm_ctx.weight"); + Y.cap = Y.local ? DLOCAL_CAP : E.ctx; + Y.K = (__half*) dalloc((size_t) Y.cap * KVD * 2); + Y.V = (__half*) dalloc((size_t) Y.cap * KVD * 2); + } + D.norm = fvec("norm.weight"); + D.mask_embed = fvec("mask_embed"); + D.mk_dflare = fvec("markov_head.dflare_norm.weight"); + D.rnn_bias = fvec("markov_head.rnn_proj.bias"); + { // fuse_alpha = softmax(fuse_weight) per row (rows: 3 layers + Markov head; columns: the 4 target taps) + const vec fw = mk.f32("fuse_weight"); + vec a(16); + for (int r = 0; r < 4; ++r) { + float mx = -INFINITY, s = 0.0f; + for (int t = 0; t < 4; ++t) mx = std::max(mx, fw[r * 4 + t]); + for (int t = 0; t < 4; ++t) s += std::exp(fw[r * 4 + t] - mx); + for (int t = 0; t < 4; ++t) a[r * 4 + t] = std::exp(fw[r * 4 + t] - mx) / s; + } + D.alpha = dvec(a); + } + { // rnn_proj [3 MR][2 MR + 2 H] split by columns + const StTensor& t = mk.t("markov_head.rnn_proj.weight"); + const int rows = (int) t.shape[0], cols = (int) t.shape[1]; + if (rows != 3 * MR || cols != 2 * MR + 2 * H) { std::fprintf(stderr, "rnn_proj %d x %d\n", rows, cols); std::exit(1); } + auto b = mk.bytes("markov_head.rnn_proj.weight"); + const uint16_t* w = (const uint16_t*) b.data(); + auto part = [&](int c0, int n) { + std::vector m((size_t) rows * n); + for (int r = 0; r < rows; ++r) std::memcpy(&m[(size_t) r * n], w + (size_t) r * cols + c0, (size_t) n * 2); + DMat d; + d.n = rows; + d.k = n; + d.d = (const uint16_t*) upload(m.data(), m.size() * 2); + return d; + }; + D.rsp = part(0, 2 * MR); + D.rout = part(2 * MR, H); + D.rf = part(2 * MR + H, H); + } + D.w1 = dmat("markov_head.markov_w1.weight"); + { // fold hidden_out into the LM head + const float* Wh = fvec("markov_head.hidden_out.weight"); // [H][MR] + const float* bh = fvec("markov_head.hidden_out.bias"); + D.fold.n = VOCAB_ROWS; + D.fold.k = MR; + D.fold.d = (const uint16_t*) dalloc((size_t) VOCAB_ROWS * MR * 2); + D.fold_b = dfloats(VOCAB_ROWS); + kd_fold<<>>(E.unembed.d, Wh, bh, (uint16_t*) D.fold.d, (float*) D.fold_b); + CK(cudaDeviceSynchronize()); + } + E.ck = main_ck; + const int TP = std::max(PF.TP, DBLK); + D.x = dfloats(DBLK * H); D.res = dfloats(DBLK * H); D.xn = dfloats(DBLK * H); D.qkv = dfloats(DBLK * DQKV); + D.att = dfloats(DBLK * QD); D.gu = dfloats((size_t) DBLK * 2 * DFF); D.act = dfloats((size_t) DBLK * DFF); + D.out = dfloats(DBLK * H); D.base = dfloats((size_t) (DBLK - 1) * VOCAB); + D.ctxc = dfloats((size_t) DBLK * H); D.ctxkv = dfloats((size_t) DBLK * 2 * KVD); + D.frnn = dfloats(H); D.cf = dfloats(3 * MR); D.mctx = dfloats((DBLK - 1) * 3 * MR); D.state = dfloats(MR); + D.in1 = dfloats(2 * MR); D.raw = dfloats(3 * MR); D.latent = dfloats(MR); D.bias = dfloats(VOCAB_ROWS); + D.pm = dfloats((size_t) NQ * DSPLIT_MAX * DBLK); D.pl = dfloats((size_t) NQ * DSPLIT_MAX * DBLK); + D.po = dfloats((size_t) NQ * DSPLIT_MAX * DBLK * HD); + D.pv = dfloats(AM_BLOCKS); D.pi = (int*) dalloc(AM_BLOCKS * 4); D.drafts = (int*) dalloc(DBLK * 4); + (void) TP; + D.on = true; +} + +// context K / V of the committed positions pos0 .. pos0 + n - 1 from their target features (rows of feat, [4][H] each) +void draft_context(const float* feat, int pos0, int n) { + for (int r0 = 0; r0 < n; r0 += DBLK) { + const int m = std::min(DBLK, n - r0); + for (int i = 0; i < DL; ++i) { + DLayer& Y = D.L[i]; + kd_mix_rms<<>>(feat + (size_t) r0 * 4 * H, D.alpha + 4 * i, Y.dflare, D.ctxc); + gemv_multi(Y.kvc, 0, 2 * KVD, D.ctxc, H, D.ctxkv, 2 * KVD, m); + kd_ctx_store<<>>(D.ctxkv, Y.k_norm_ctx, pos0 + r0, Y.K, Y.V, Y.cap); + } + } +} +// Markov context from the last committed position's features (one row [4][H]) +void draft_frnn(const float* feat_row) { + kd_mix_rms<<<1, 256>>>(feat_row, D.alpha + 12, D.mk_dflare, D.frnn); + gemv(D.rf, D.frnn, D.cf); + add_b(D.cf, D.rnn_bias, D.cf, 3 * MR); +} +// the block for anchor `tok` at position p: drafts for p + 1 .. p + 7 into D.drafts[1..7] (D.drafts[0] = tok) +void draft_device(int p); +cudaGraphExec_t g_draft_exec = nullptr; +void draft_run(int tok, int p) { + upload_embed(tok); + CK(cudaMemcpyAsync(D.drafts, &tok, 4, cudaMemcpyHostToDevice)); + if (!E.graph) { draft_device(p); return; } + CK(cudaMemcpyToSymbolAsync(d_vpos, &p, 4, 0, cudaMemcpyHostToDevice, cudaStreamPerThread)); + if (!g_draft_exec) { + cudaGraph_t g; + CK(cudaStreamBeginCapture(cudaStreamPerThread, cudaStreamCaptureModeRelaxed)); + draft_device(-1); + CK(cudaStreamEndCapture(cudaStreamPerThread, &g)); + CK(cudaGraphInstantiate(&g_draft_exec, g, 0)); + } + CK(cudaGraphLaunch(g_draft_exec, cudaStreamPerThread)); +} +// the block's device work, p < 0: read from d_vpos +void draft_device(int p) { + rms(E.emb_in, E.embed_norm, D.x); + for (int r = 1; r < DBLK; ++r) copy(D.x + (size_t) r * H, D.mask_embed, H); + const float* mlp_out = D.x; + for (int i = 0; i < DL; ++i) { + DLayer& Y = D.L[i]; + kd_add_rms<<>>(mlp_out, D.res, Y.in_ln, D.xn, i == 0); + gemv_multi(Y.qkv, 0, DQKV, D.xn, H, D.qkv, DQKV, DBLK); + kd_qk_rope_store<<>>(D.qkv, Y.q_norm, Y.k_norm, p, Y.K, Y.V, Y.cap); + // split count fixed by the layer's reach (graph-capturable); empty splits write max = -inf, skipped by the merge + const int reach = Y.local ? WINDOW + DBLK : E.ctx; + const int ns = std::min(DSPLIT_MAX, std::max(1, (reach + DSPLIT_KEYS - 1) / DSPLIT_KEYS)); + kd_attn_partial<<>>(D.qkv, Y.K, Y.V, Y.cap, p, g_draft_abl == 2 ? 2 : Y.local, D.pm, D.pl, D.po); + kd_attn_merge<<>>(D.pm, D.pl, D.po, ns, D.att); + gemv_multi(Y.o, 0, H, D.att, QD, D.out, H, DBLK); + kd_add_rms<<>>(D.out, D.res, Y.post_ln, D.xn, 0); + gemv_multi(Y.gu, 0, 2 * DFF, D.xn, H, D.gu, 2 * DFF, DBLK); + kd_silu_mul<<>>(D.gu, D.act); + gemv_multi(Y.down, 0, H, D.act, DFF, D.x, H, DBLK); + mlp_out = D.x; + } + kd_add_rms<<>>(D.x, D.res, D.norm, D.out, 0); + const float* rows = D.out + H; // the 7 mask rows + gemv_multi(E.unembed, 0, VOCAB, rows, H, D.base, VOCAB, DBLK - 1); + gemv_multi(D.rout, 0, 3 * MR, rows, H, D.mctx, 3 * MR, DBLK - 1); + CK(cudaMemsetAsync(D.state, 0, MR * 4)); + for (int i = 0; i < DBLK - 1; ++i) { + kd_markov_in<<<1, MR>>>(D.state, D.w1.d, D.drafts + i, D.in1); + gemv(D.rsp, D.in1, D.raw); + kd_markov_gate<<<1, MR>>>(D.raw, D.mctx + (size_t) i * 3 * MR, D.cf, D.state, D.latent); + gemv(D.fold, D.latent, D.bias, VOCAB); + const bool nomk = g_draft_abl == 1; // ablation: base logits only + kd_argmax_partial<<>>(D.base + (size_t) i * VOCAB, nomk ? nullptr : D.bias, nomk ? nullptr : D.fold_b, + VOCAB, D.pv, D.pi); + kd_argmax_final<<<1, 256>>>(D.pv, D.pi, AM_BLOCKS, D.drafts + i + 1); + } +} + +#include "ink2_vision.cuh" // pictures: the ViT + projector, the image rows of a prompt + +void forward_prefill_device(int T, int pos0, float* all); +void forward_prefill(const int* toks, int T, int pos0, float* all) { + kv_fit(pos0 + T); + pf_layout(T); // (before the pools are read below: a growth can take slots) + g_pf_routed = pf_routed_ok(T); + if (!g_pf_routed) pf_map_staging(); + const size_t ES = (size_t) T * H; + if (E.offload) { // what decode left in the pools + std::vector t((size_t) NL * NE); + CK(cudaMemcpy(t.data(), E.tabA, t.size() * sizeof(void*), cudaMemcpyDeviceToHost)); + for (int l = 0; l < NL; ++l) { + PF.nonres[l].clear(); + for (int e = 0; e < NE; ++e) if (!t[(size_t) l * NE + e]) PF.nonres[l].push_back(e); + } + } + { + vec e(ES); + for (int t = 0; t < T; ++t) embed_row(toks[t] < 0 ? IMAGE_TOKEN : toks[t], &e[(size_t) t * H]); // (vis_id) + CK(cudaMemcpyAsync(PF.x0, e.data(), ES * 4, cudaMemcpyHostToDevice, cudaStreamPerThread)); + CK(cudaStreamSynchronize(cudaStreamPerThread)); + } + if (PF.rows_argmax && E.graph && T == DBLK) { // verify block (offload: through the decode cache): one graph per output variant + cudaGraphExec_t& x = g_vexec[PF.rows_copy ? 1 : 0]; + CK(cudaMemcpyToSymbolAsync(d_vpos, &pos0, 4, 0, cudaMemcpyHostToDevice, cudaStreamPerThread)); + if (!x) { + cudaGraph_t g; + CK(cudaStreamBeginCapture(cudaStreamPerThread, cudaStreamCaptureModeRelaxed)); + forward_prefill_device(T, -1, nullptr); + CK(cudaStreamEndCapture(cudaStreamPerThread, &g)); + CK(cudaGraphInstantiate(&x, g, 0)); + } + CK(cudaGraphLaunch(x, cudaStreamPerThread)); + CK(cudaStreamSynchronize(cudaStreamPerThread)); + return; + } + forward_prefill_device(T, pos0, all); + CK(cudaStreamSynchronize(cudaStreamPerThread)); +} +// forward_prefill's device work (pos0 < 0: from d_vpos; `all` only outside a graph) +void forward_prefill_device(int T, int pos0, float* all) { + const size_t ES = (size_t) T * H; + // a verify block with the CPU experts promotes as a decode token does (copies during the block, committed at its + // end). CBA: the per-token budget and decay once per block of 1-8 tokens (INK2_PROMOTE) + const bool vcpu = E.cpu && PF.rows_argmax && T <= ink2cpu::BELL_M; + if (vcpu) promote_fork(); + k_rms<<>>(PF.x0, E.embed_norm, PF.h, H); + vis_inject(T, pos0); // a picture's rows replace its placeholders' normed embeddings + int nB = 0, visit = 0; + auto run = [&](int l, int slot, const float* msgs) { + g_slot = slot; + if (PF.feat) { + const int tap = visit == 5 ? 0 : visit == 23 ? 1 : visit == 41 ? 2 : -1; + if (tap >= 0) + CK(cudaMemcpy2DAsync(PF.feat + (size_t) tap * H, (size_t) 4 * H * 4, PF.h, (size_t) H * 4, (size_t) H * 4, + T, cudaMemcpyDeviceToDevice, cudaStreamPerThread)); + } + ++visit; + layer_forward_b(l, E.S[slot], nB, msgs, T, pos0); + if (l % BLOCK == 0) ++nB; + std::swap(PF.h, PF.out); + }; + for (int l = 0; l < LOOP_BEGIN; ++l) run(l, l, nullptr); + const int npre = nB; + copy_b(PF.pre_h, PF.h, ES); + copy_b(PF.preB, PF.B, npre * ES); + for (int l = LOOP_BEGIN; l < LOOP_END; ++l) run(l, l, nullptr); + for (int p = 1; p < PASSES; ++p) { + const int nprev = nB - (npre + 1); + copy_b(PF.prev, PF.B + (npre + 1) * ES, nprev * ES); + copy_b(PF.prev + nprev * ES, PF.h, ES); + copy_b(PF.h, PF.pre_h, ES); + copy_b(PF.B, PF.preB, npre * ES); + nB = npre; + for (int i = 0; i < NLOOP; ++i) { + attnres(PF.prev, nprev + 1, E.msg_queries + (size_t) i * 4 * H, 4, PF.msgs, nullptr, nullptr, nullptr, + nullptr, T); + run(LOOP_BEGIN + i, NL + (p - 1) * NLOOP + i, PF.msgs); + } + } + for (int l = LOOP_END; l < NL; ++l) run(l, l, nullptr); + copy_b(PF.B + nB * ES, PF.h, ES); + attnres(PF.B, nB + 1, E.final_query, 1, nullptr, E.norm, nullptr, nullptr, PF.mn, T); + if (PF.feat) + CK(cudaMemcpy2DAsync(PF.feat + (size_t) 3 * H, (size_t) 4 * H * 4, PF.mn, (size_t) H * 4, (size_t) H * 4, T, + cudaMemcpyDeviceToDevice, cudaStreamPerThread)); + if (PF.rows_argmax) { // softcap is monotonic: argmax of the raw logits + gemv_multi(E.unembed, 0, VOCAB, PF.mn, H, PF.lg, VOCAB, T); + k_rows_argmax<<>>(PF.lg, VOCAB, PF.am); + if (PF.rows_copy) { // sampling: every row's softcapped logits + k_softcap<<<(unsigned) (((size_t) T * VOCAB + 255) / 256), 256>>>(PF.lg, T * VOCAB, LOGIT_CAP); + CK(cudaMemcpyAsync(PF.rows_host, PF.lg, (size_t) T * VOCAB * 4, cudaMemcpyDeviceToHost, cudaStreamPerThread)); + } + if (vcpu) promote_join(); + return; + } + gemv(E.unembed, PF.mn + (size_t) (T - 1) * H, E.logits, VOCAB); + k_softcap<<<(VOCAB + 255) / 256, 256>>>(E.logits, VOCAB, LOGIT_CAP); + if (all) { // every position (verification): the unembedding in slices of 8192 rows + for (int r0 = 0; r0 < VOCAB; r0 += 8192) { + const int n = std::min(8192, VOCAB - r0); + sgemm(wf32(E.unembed, r0, n), n, H, PF.mn, H, PF.lg, n, T); + k_softcap<<<(unsigned) (((size_t) T * n + 255) / 256), 256>>>(PF.lg, T * n, LOGIT_CAP); + CK(cudaMemcpy2DAsync(all + r0, (size_t) VOCAB * 4, PF.lg, (size_t) n * 4, (size_t) n * 4, T, + cudaMemcpyDeviceToHost, cudaStreamPerThread)); + } + } +} + +std::vector parse_ids(const char* s) { + std::vector v; + for (const char* p = s; *p;) { + char* end = nullptr; + const long x = std::strtol(p, &end, 10); + if (end == p) break; // trailing whitespace / newline: no number, nothing pushed + v.push_back((int) x); + p = *end == ',' ? end + 1 : end; + } + return v; +} + +double now_ms() { + return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); +} + +// sampling on the host (the engine samples; Strata's server only forwards the keys): greedy without a temperature +struct Sampler { + float temp = 0.0f, top_p = 1.0f, min_p = 0.0f; + int top_k = 0; + std::mt19937_64 rng{std::random_device{}()}; +}; +// the sampler's distribution over the logits lg (temp > 0): candidates within 20.8 temp of the max, sorted, top_k, +// min_p, top_p; unnormalized weights p (total = their sum) +struct Dist { + std::vector> c; + std::vector p; + size_t keep = 0; + double total = 0.0; +}; +Dist make_dist(const float* lg, const Sampler& s) { + Dist d; + const int best = (int) (std::max_element(lg, lg + VOCAB) - lg); + const float mx = lg[best], thr = mx - 20.8f * s.temp; // exp(-20.8) ~ 1e-9 of the top probability: never matters + for (int i = 0; i < VOCAB; ++i) + if (lg[i] >= thr) d.c.push_back({lg[i], i}); + std::sort(d.c.begin(), d.c.end(), [](const auto& a, const auto& b) { return a.first > b.first || (a.first == b.first && a.second < b.second); }); + if (s.top_k > 0 && (int) d.c.size() > s.top_k) d.c.resize(s.top_k); + d.p.resize(d.c.size()); + for (size_t i = 0; i < d.c.size(); ++i) d.p[i] = std::exp((double) (d.c[i].first - mx) / s.temp); + d.keep = d.c.size(); + if (s.min_p > 0.0f) + for (size_t i = 0; i < d.keep; ++i) if (d.p[i] < s.min_p * d.p[0]) { d.keep = i; break; } + double acc = 0.0, total = 0.0; + for (size_t i = 0; i < d.keep; ++i) total += d.p[i]; + if (s.top_p < 1.0f) { + for (size_t i = 0; i < d.keep; ++i) { acc += d.p[i]; if (acc >= s.top_p * total) { d.keep = i + 1; break; } } + total = 0.0; + for (size_t i = 0; i < d.keep; ++i) total += d.p[i]; + } + d.total = total; + return d; +} +// a draw from d, optionally with one token removed (the residual of a rejected greedy draft) +int draw(const Dist& d, std::mt19937_64& rng, int exclude = -1) { + double total = d.total; + for (size_t i = 0; i < d.keep; ++i) if (d.c[i].second == exclude) total -= d.p[i]; + double u = std::uniform_real_distribution(0.0, total)(rng); + int last = -1; + for (size_t i = 0; i < d.keep; ++i) { + if (d.c[i].second == exclude) continue; + last = d.c[i].second; + u -= d.p[i]; + if (u <= 0.0) return last; + } + return last; +} +double prob(const Dist& d, int tok) { + for (size_t i = 0; i < d.keep; ++i) if (d.c[i].second == tok) return d.p[i] / d.total; + return 0.0; +} +int sample(const float* lg, Sampler& s) { + if (s.temp <= 0.0f) return (int) (std::max_element(lg, lg + VOCAB) - lg); + return draw(make_dist(lg, s), s.rng); +} +int sample(const vec& lg, Sampler& s) { return sample(lg.data(), s); } + +constexpr int EOS_ID = 200006; // <|content_model_end_sampling|> (generation_config.json) + +#include "ink2_session.cuh" + +} // namespace + +int main(int argc, char** argv) { + if (const char* r = std::getenv("INK2_RPW")) g_rpw = std::atoi(r); + if (const char* r = std::getenv("INK2_SEL_RPW")) g_sel_rpw = std::atoi(r); + if (const char* r = std::getenv("INK2_GEMV_MINB")) g_gemv_min_blocks = std::atoi(r); + if (const char* r = std::getenv("INK2_OFF_MARGIN_MIB")) g_off_margin_mib = std::atoi(r); + if (const char* r = std::getenv("INK2_GRP_R")) g_grp_r = std::atoi(r); + if (const char* r = std::getenv("INK2_DRAFT_ABL")) g_draft_abl = std::atoi(r); + if (const char* r = std::getenv("INK2_GG_RPW")) g_gg_rpw = std::atoi(r); + if (const char* r = std::getenv("INK2_ROUTED_MAX")) g_pf_routed_max = std::atoi(r); + if (const char* r = std::getenv("INK2_DQ_MIN")) g_dq_min = std::atoi(r); + { +#if defined(STRATA_USE_HIP) + const int w = std::getenv("INK2_Q8_WIDE") ? std::atoi(std::getenv("INK2_Q8_WIDE")) : 0; +#else + int major = 0; // default on before Ampere only: Turing gains, 3090 decode 91.7 -> 90.5 tok/s with it + CK(cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, 0)); + const int w = std::getenv("INK2_Q8_WIDE") ? std::atoi(std::getenv("INK2_Q8_WIDE")) : (major < 8); +#endif + CK(cudaMemcpyToSymbol(c_q8w, &w, sizeof(int))); + } + std::string dir, dump_logits, rec_path; + std::vector vis_paths; // --image (one per placeholder of --tokens, in order) + std::string vis_pixels; // --vis-pixels: the ViT alone on a processor pixel tensor + std::vector ids; + int n_gen = 32; + bool serve = false, spec = false; + int cc_mib = 0, cc_min = 512; // --conversation-cache-mib / -min-tokens (ink2_session.cuh) + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + if (a == "--serve") { serve = true; continue; } + if (i + 1 >= argc) { std::fprintf(stderr, "option %s needs a value\n", a.c_str()); return 2; } + const char* v = argv[++i]; + if (a == "--model") dir = v; + else if (a == "--tokens") ids = parse_ids(v); + else if (a == "--tokens-file") { + FILE* f = std::fopen(v, "r"); + if (!f) { std::fprintf(stderr, "cannot open %s\n", v); return 2; } + std::string text; + for (int c; (c = std::fgetc(f)) != EOF;) text += (char) c; + std::fclose(f); + ids = parse_ids(text.c_str()); + } + else if (a == "--n") n_gen = std::atoi(v); + else if (a == "--ctx" || a == "--max-context") E.ctx = std::atoi(v); + else if (a == "--dump-logits") dump_logits = v; + else if (a == "--graph") E.graph = std::atoi(v) != 0; + else if (a == "--chunk") PF.TP = std::atoi(v); + else if (a == "--tc") PF.tc = std::atoi(v) != 0; + else if (a == "--verify-tc") g_verify_tc = std::atoi(v) != 0; + else if (a == "--vram-reserve-mib") E.reserve_mib = std::atoi(v); + else if (a == "--spec") spec = std::atoi(v) != 0; + else if (a == "--cpu-threads") E.cpu_threads = std::atoi(v); + else if (a == "--kv-grow") E.grow = std::atoi(v) != 0; + else if (a == "--conversation-cache-mib") cc_mib = std::atoi(v); + else if (a == "--conversation-cache-min-tokens") cc_min = std::atoi(v); + else if (a == "--kv-grow-step") E.grow_step = std::max(CHUNK, std::atoi(v) / CHUNK * CHUNK); + else if (a == "--kv") { // Strata's names too (strata_control/tuning.py: fp16, int8) + const std::string k = v; + if (k == "f16" || k == "fp16") E.kvm = 1; + else if (k == "f32" || k == "fp32") E.kvm = 0; + else if (k == "i8" || k == "int8") E.kvm = 2; + else if (k == "i8r") E.kvm = 3; + else if (k == "k8v4") E.kvm = 4; + else if (k == "k8v8") E.kvm = 5; + else { std::fprintf(stderr, "--kv %s: this engine has f16 (fp16), f32, i8 (int8), i8r, k8v4 and k8v8\n", v); return 2; } + } + // Strata's server and tuner may add these: the KV cache is always resident here and prefill has one form + else if (a == "--kv-resident" || a == "--prefill" || a == "--conversation-cache-slots") std::fprintf(stderr, "[ink2] %s %s ignored\n", a.c_str(), v); + else if (a == "--record-routing") { rec_path = v; E.rec_mode = 1; } + else if (a == "--force-routing") { rec_path = v; E.rec_mode = 2; } + else if (a == "--image") vis_paths.push_back(v); + else if (a == "--vis-pixels") vis_pixels = v; + else if (a == "--dump-image-emb") g_vis.dump = v; + else if (a == "--image-max-tokens") g_vis.max_tokens = std::atoi(v); + else { std::fprintf(stderr, "unknown option %s\n", a.c_str()); return 2; } + } + if (E.grow) vmm_init(); + if (dir.empty() || (ids.empty() && !serve && vis_pixels.empty())) { + std::fprintf(stderr, "usage: strata-ink2 --model DIR (--serve | --tokens IDS | --tokens-file F) [--n N] [--ctx N] " + "[--chunk N] [--tc 0|1] [--verify-tc 0|1] [--kv f16|fp16|f32|i8|int8|i8r|k8v4|k8v8] [--kv-grow 1 [--kv-grow-step N]] [--vram-reserve-mib N [--cpu-threads N]] [--spec 0|1] [--dump-logits F] [--conversation-cache-mib N [--conversation-cache-min-tokens N]] [--image FILE ... [--image-max-tokens N] [--dump-image-emb F]] [--vis-pixels F]\n"); + return 2; + } + if (serve && PF.TP <= 0) { std::fprintf(stderr, "--serve needs --chunk > 0\n"); return 2; } + if (E.cpu_threads > 0) { // CPU experts: decode and --spec verify misses on the CPU (needs the offload) + if (E.reserve_mib < 0) { std::fprintf(stderr, "--cpu-threads needs --vram-reserve-mib (expert offload)\n"); return 2; } + if (!ink2cpu::isa()) { std::fprintf(stderr, "--cpu-threads: this CPU has no AVX2 + FMA + F16C\n"); return 2; } + E.cpu = true; + } + if (!serve && (int) ids.size() + n_gen > E.ctx) { std::fprintf(stderr, "prompt + n exceeds --ctx %d\n", E.ctx); return 2; } + Ckpt ck; + Gguf gg; + g_is_gguf = dir.size() > 5 && dir.compare(dir.size() - 5, 5, ".gguf") == 0; + // CBA: no GGUF CPU expert kernels (ink2_cpu decodes NVFP4 / MXFP8 only) and no drafter tensors in a GGUF: refused + // until IQ3_S / IQ4_NL / Q8_0 CPU dots and a GGUF drafter exist + if (g_is_gguf && E.cpu) { std::fprintf(stderr, "--cpu-threads: not with a GGUF model (no GGUF CPU expert kernels yet)\n"); return 2; } + if (g_is_gguf && spec) { std::fprintf(stderr, "--spec: not with a GGUF model (no drafter for it yet)\n"); return 2; } + if (g_verify_tc) { // mma m16n8k16 f16: CUDA sm_80+ + int cc = 0; +#if !defined(STRATA_USE_HIP) + cudaDeviceGetAttribute(&cc, cudaDevAttrComputeCapabilityMajor, 0); +#endif + if (cc < 8) { std::fprintf(stderr, "[ink2] --verify-tc 1 ignored: it needs a CUDA card of compute capability 8.0 or later\n"); g_verify_tc = false; } + } + if (g_is_gguf) { // --model FILE.gguf: llama.cpp's merged inkling2_loop layout + const std::string e = gg_open(dir, gg); + if (!e.empty()) { std::fprintf(stderr, "%s\n", e.c_str()); return 1; } + g_gg = ≫ + } else { + ck.path = dir + "/model-00001-of-00001.safetensors"; + const std::string e = strata::image::st_read_header(ck.path, ck.st); + if (!e.empty()) { std::fprintf(stderr, "%s\n", e.c_str()); return 1; } + E.ck = &ck; + } + if (!vis_pixels.empty()) return vis_cli_pixels(vis_pixels); + const double t_load = now_ms(); + if (g_is_gguf) load_gguf(); + else load(); + if (PF.TP > 0) PF_RING_EXTRA = PF.TP; + alloc_state(); + // CBA: not with --spec: its verify blocks read the prompt buffers between prompts; they stay mapped (fixed) there, + // a per-verify map / unmap would cost two device syncs per block + g_pf_elastic = E.grow && E.offload && !spec; + if (PF.TP > 0) alloc_prefill(); + const size_t rec_n = (size_t) NCALLS * E.ctx * TOPK; + if (E.rec_mode) E.rec = (int*) dalloc(rec_n * 4); + if (E.rec_mode == 2) { + std::vector r(rec_n); + FILE* f = std::fopen(rec_path.c_str(), "rb"); + if (!f || std::fread(r.data(), 4, rec_n, f) != rec_n) { std::fprintf(stderr, "cannot read %s (same --ctx?)\n", rec_path.c_str()); return 1; } + std::fclose(f); + CK(cudaMemcpy(E.rec, r.data(), rec_n * 4, cudaMemcpyHostToDevice)); + } + if (spec) { + if (PF.TP < 256) { std::fprintf(stderr, "--spec needs --chunk >= 256\n"); return 2; } + draft_load(dir); + PF.feat = dfloats((size_t) PF.TP * 4 * H); + PF.spm = dfloats((size_t) SPLIT_MAX * AQ * NQ); + PF.spl = dfloats((size_t) SPLIT_MAX * AQ * NQ); + PF.spo = dfloats((size_t) SPLIT_MAX * AQ * QD); + PF.am = (int*) dalloc(DBLK * 4); + CK(cudaHostAlloc((void**) &PF.rows_host, (size_t) DBLK * VOCAB * 4, cudaHostAllocDefault)); + g_fring = dfloats((size_t) FRING * 4 * H); + } + if (E.offload) setup_offload(); + if (E.cpu) setup_cpu(); + if (serve) sess_init(cc_mib, cc_min); + + vec logits(VOCAB); + auto step = [&](int tok, int pos, bool want_logits) { + kv_fit(pos + 1); + CK(cudaMemcpyAsync(E.d_pos, &pos, 4, cudaMemcpyHostToDevice)); + upload_embed(tok); + if (!E.graph) { + forward_device(); + } else { + if (!E.exec) { // built once: every launch reads the position from E.d_pos + cudaGraph_t g; + CK(cudaStreamBeginCapture(cudaStreamPerThread, cudaStreamCaptureModeRelaxed)); + forward_device(); + CK(cudaStreamEndCapture(cudaStreamPerThread, &g)); + CK(cudaGraphInstantiate(&E.exec, g, 0)); + } + CK(cudaGraphLaunch(E.exec, cudaStreamPerThread)); + } + if (want_logits) CK(cudaMemcpy(logits.data(), E.logits, (size_t) VOCAB * 4, cudaMemcpyDeviceToHost)); + }; + // warm-up at position 0 (builds the decode graph outside any timing; position 0 is rewritten by the first prompt) + step(0, 0, false); + CK(cudaDeviceSynchronize()); + std::fprintf(stderr, "load %.1f s, %.2f GiB in VRAM (ctx %d)\n", (now_ms() - t_load) / 1000, g_vram / 1073741824.0, E.ctx); + + // Speculative continuation (--spec): `first` was sampled for position p (not fed yet; already emitted by the + // caller). Draft 7 / verify 8 until emit() returns false, max_new tokens in all, or stop; the target's per-row + // distributions decide (greedy: the draft is the row's argmax; sampling: accept the greedy draft d with + // probability P(d), else draw from P without d, which leaves the output distribution exactly the target's). + // Near the context end: the one-token path. Returns the number of tokens emitted (first included). + // Adaptive: the loop keeps an estimate of the wall time per emitted token of both modes (EMA) and decodes one + // token at a time through the decode graph for PLAIN_RUN tokens whenever the speculative estimate is the slower + // (low acceptance: sampling at high temperature, unpredictable text); the drafter's context follows the plain + // tokens through the decode graph's feature ring. The first PLAIN_PROBE tokens measure the plain mode. + constexpr int PLAIN_PROBE = 4, PLAIN_RUN = 32, SPEC_MIN = 3; + const bool spec_force = std::getenv("INK2_SPEC_FORCE") != nullptr; // tests: never fall back + // tests: INK2_VDUMP=FILE keeps the first INK2_VDUMP_N (16) verify blocks: position, 8 input tokens, 8 rows of logits + FILE* vdump = std::getenv("INK2_VDUMP") ? std::fopen(std::getenv("INK2_VDUMP"), "wb") : nullptr; + int vdump_left = std::getenv("INK2_VDUMP_N") ? std::atoi(std::getenv("INK2_VDUMP_N")) : 16; + auto spec_continue = [&](int first, int p, int max_new, Sampler& s, const std::function& emit, + const std::atomic* stop) { + int n = 1, anchor = first, plain_left = spec_force ? 0 : PLAIN_PROBE, spec_iters = 0; + double ms_plain = 0.0, ms_spec = 0.0; // EMA, ms per emitted token (0: not measured yet) + bool go = true; + while (go && n < max_new && !(stop && stop->load())) { + if (plain_left > 0 || p + DBLK > E.ctx) { // one token: decode graph, drafter context from its features + const double t0 = now_ms(); + step(anchor, p, true); + draft_context(g_fring + (size_t) (p % FRING) * 4 * H, p, 1); + ++p; + anchor = sample(logits, s); + ++n; + go = emit(anchor); + CK(cudaDeviceSynchronize()); + const double dt = now_ms() - t0; + ms_plain = ms_plain > 0.0 ? 0.9 * ms_plain + 0.1 * dt : dt; + if (plain_left > 0 && --plain_left == 0) draft_frnn(g_fring + (size_t) ((p - 1) % FRING) * 4 * H); + ++D.plain; + continue; + } + const double t0 = now_ms(); + draft_run(anchor, p); + int d[DBLK], g[DBLK]; + CK(cudaMemcpy(d, D.drafts, DBLK * 4, cudaMemcpyDeviceToHost)); + PF.rows_argmax = true; + const float* rows = s.temp > 0.0f ? PF.rows_host : nullptr; + PF.rows_copy = rows != nullptr || (vdump && vdump_left > 0); + forward_prefill(d, DBLK, p, nullptr); + if (vdump && vdump_left-- > 0) { + std::fwrite(&p, 4, 1, vdump); + std::fwrite(d, 4, DBLK, vdump); + std::fwrite(PF.rows_host, 4, (size_t) DBLK * VOCAB, vdump); + std::fflush(vdump); + } + PF.rows_argmax = PF.rows_copy = false; + CK(cudaMemcpy(g, PF.am, DBLK * 4, cudaMemcpyDeviceToHost)); + int k = 0, next = -1; + for (; k < DBLK - 1; ++k) { // row k predicts position p + k + 1; the draft for it is d[k + 1] + if (!rows) { + if (d[k + 1] != g[k]) { next = g[k]; break; } + } else { + const Dist dist = make_dist(rows + (size_t) k * VOCAB, s); + const double u = std::uniform_real_distribution(0.0, 1.0)(s.rng); + if (u >= prob(dist, d[k + 1])) { next = draw(dist, s.rng, d[k + 1]); break; } + } + } + if (next < 0) next = rows ? sample(rows + (size_t) (DBLK - 1) * VOCAB, s) : g[DBLK - 1]; + for (int j = 1; j <= k && go; ++j) { ++n; go = emit(d[j]) && n < max_new; } + if (go) { ++n; go = emit(next); } + draft_context(PF.feat, p, k + 1); + draft_frnn(PF.feat + (size_t) k * 4 * H); + p += k + 1; + anchor = next; + ++D.verifies; + D.accepted += k; + ++D.hk[k]; + CK(cudaDeviceSynchronize()); + const double dt = (now_ms() - t0) / (k + 1); + ms_spec = ms_spec > 0.0 ? 0.8 * ms_spec + 0.2 * dt : dt; + if (++spec_iters >= SPEC_MIN && ms_plain > 0.0 && ms_spec > ms_plain && !spec_force) { + plain_left = PLAIN_RUN; + ms_spec = 0.0; + spec_iters = 0; + ++D.switches; + } + } + return n; + }; + + if (serve) { + // Strata engine protocol (terminal/serve/server.py): READY stop; GEN [ k=v ...] ; + // T per token; DONE ; PP ; + // STOP (read by its own thread; cleared when the next GEN starts); EOF / QUIT ends. + std::atomic stop{false}; + std::mutex mu; + std::condition_variable cv; + std::deque q; + bool eof = false; + std::thread reader([&] { + std::string line; + while (std::getline(std::cin, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line == "STOP") { stop.store(true); continue; } + { std::lock_guard lk(mu); q.push_back(line); } + cv.notify_one(); + } + { std::lock_guard lk(mu); eof = true; } + cv.notify_one(); + }); + reader.detach(); + std::printf("INFO images=%d\n", vis_available() ? 1 : 0); // GEN takes image= keys + std::printf("READY %d stop\n", E.ctx); + std::fflush(stdout); + std::vector hist; // tokens whose KV / conv state is in the slots; last_logits follow hist.back() + vec last_logits; + Sampler smp; + for (;;) { + std::string line; + { + std::unique_lock lk(mu); + cv.wait(lk, [&] { return eof || !q.empty(); }); + if (q.empty()) break; + line = q.front(); + q.pop_front(); + } + if (line == "QUIT") break; + if (line.rfind("GEN ", 0) != 0) { std::printf("ERR unsupported command\n"); std::fflush(stdout); continue; } + stop.store(false); + std::vector f; + for (size_t p = 0; p < line.size();) { + const size_t s2 = line.find(' ', p); + f.push_back(line.substr(p, s2 == std::string::npos ? std::string::npos : s2 - p)); + if (s2 == std::string::npos) break; + p = s2 + 1; + } + if (f.size() < 3) { std::printf("ERR malformed GEN\n"); std::fflush(stdout); continue; } + int max_new = std::atoi(f[1].c_str()); + std::vector pr = parse_ids(f.back().c_str()); + Sampler s; + s.rng = std::move(smp.rng); + std::vector imgs; // image= keys, one per placeholder (ink2_vision.cuh) + for (size_t k = 2; k + 1 < f.size(); ++k) { // unknown keys are ignored + const size_t eq = f[k].find('='); + if (eq == std::string::npos) continue; + const std::string key = f[k].substr(0, eq), val = f[k].substr(eq + 1); + if (key == "temperature") s.temp = std::strtof(val.c_str(), nullptr); + else if (key == "top_p") s.top_p = std::strtof(val.c_str(), nullptr); + else if (key == "top_k") s.top_k = std::atoi(val.c_str()); + else if (key == "min_p") s.min_p = std::strtof(val.c_str(), nullptr); + else if (key == "seed") s.rng.seed(std::strtoull(val.c_str(), nullptr, 10)); + else if (key == "image") imgs.push_back(ink2img::pct_decode(val)); + } + if (pr.empty()) { std::printf("ERR empty prompt\n"); std::fflush(stdout); smp.rng = std::move(s.rng); continue; } + if (const std::string ve = vis_prepare(pr, imgs); !ve.empty()) { // placeholders -> image tokens + std::printf("ERR image: %s\n", ve.c_str()); + std::fflush(stdout); + smp.rng = std::move(s.rng); + continue; + } + if ((int) pr.size() >= E.ctx) { + std::printf("ERR prompt of %zu tokens exceeds the context %d\n", pr.size(), E.ctx); + std::fflush(stdout); + smp.rng = std::move(s.rng); + continue; + } + max_new = std::max(0, std::min(max_new, E.ctx - (int) pr.size())); + const bool reuse = !hist.empty() && pr.size() >= hist.size() && std::equal(hist.begin(), hist.end(), pr.begin()); + size_t start = reuse ? hist.size() : 0; + if (g_sess.on) start = sess_begin(pr, hist, last_logits, start); // conversation cache (ink2_session.cuh) + kv_trim((int) pr.size() + 1); + if (spec && start == pr.size()) start = pr.size() - 1; // re-fed: the drafter needs its features + const double t0 = now_ms(); + const long acc0 = D.accepted, ver0 = D.verifies; + if (const std::string ve = vis_encode(start); !ve.empty()) { + std::printf("ERR image: %s\n", ve.c_str()); + std::fflush(stdout); + smp.rng = std::move(s.rng); + continue; + } + if (start == pr.size()) { + logits = last_logits; + } else { + for (size_t p0 = start, Tz = 0; p0 < pr.size(); p0 += Tz) { + const int T = sess_chunk((int) p0, pf_fit((int) std::min((size_t) PF.TP, pr.size() - p0), (int) p0)); + if (g_pf_full) { context_full(hist, p0, pr.size()); break; } // ink2_grow_guard.cuh + Tz = (size_t) T; + if (T < g_pf_mapped_T) pf_unmap(); + pf_map(T); + forward_prefill(&pr[p0], T, (int) p0, nullptr); + if (spec) { + draft_context(PF.feat, (int) p0, T); + if (p0 + T == pr.size()) draft_frnn(PF.feat + (size_t) (T - 1) * 4 * H); + } + sess_after_chunk((int) (p0 + T)); + const double ms = now_ms() - t0; + std::printf("PP %zu %zu %.0f %.1f\n", p0 + T, pr.size(), ms, 1000.0 * (p0 + T - start) / std::max(ms, 1.0)); + std::fflush(stdout); + } + if (g_ctx_full) { g_ctx_full = false; g_vis.pending = false; smp.rng = std::move(s.rng); continue; } + CK(cudaMemcpy(logits.data(), E.logits, (size_t) VOCAB * 4, cudaMemcpyDeviceToHost)); + pf_unmap(); + } + sess_prompt_end(pr, logits); + const double t1 = now_ms(); + std::vector gen; + const char* finish = "length"; + int pos = (int) pr.size(); + if (spec && max_new > 0 && !stop.load()) { + const int first = sample(logits, s); + gen.push_back(first); + std::printf("T %d\n", first); + std::fflush(stdout); + if (first == EOS_ID) finish = "stop"; + else spec_continue(first, pos, max_new, s, [&](int t) { + gen.push_back(t); + std::printf("T %d\n", t); + std::fflush(stdout); + if (t == EOS_ID) { finish = "stop"; return false; } + return true; + }, &stop); + if (stop.load() && std::strcmp(finish, "stop") != 0) finish = "cancel"; + } + for (int k = 0; k < (spec ? 0 : max_new); ++k) { + if (stop.load()) { finish = "cancel"; break; } + const int next = sample(logits, s); + gen.push_back(next); + std::printf("T %d\n", next); + std::fflush(stdout); + if (next == EOS_ID) { finish = "stop"; break; } + if (k + 1 < max_new) { + if (!kv_room(pos + 1)) { std::fprintf(stderr, "kv-grow: the answer ends at %d tokens: the K/V cannot grow\n", pos); break; } + step(next, pos++, true); + } + } + const double t2 = now_ms(); + hist = pr; + g_vis.pending = false; + if (!gen.empty()) hist.insert(hist.end(), gen.begin(), gen.end() - 1); // the last token was never fed + last_logits = logits; + smp.rng = std::move(s.rng); + // + drafts accepted / offered, prompt tokens not read (Strata's DONE fields 6-8: usage.cached_tokens) + std::printf("DONE %zu %zu %.0f %.0f %s %ld %ld %zu\n", gen.size(), pr.size(), t1 - t0, t2 - t1, finish, + D.accepted - acc0, (D.verifies - ver0) * (DBLK - 1), start); + std::fflush(stdout); + } + return 0; + } + + if (!vis_paths.empty() || std::count(ids.begin(), ids.end(), IMAGE_TOKEN)) { // pictures (ink2_vision.cuh) + std::string ve = PF.TP > 0 ? vis_prepare(ids, vis_paths) : "pictures need --chunk > 0"; + if (ve.empty() && (int) ids.size() + n_gen > E.ctx) ve = "prompt + n exceeds --ctx " + std::to_string(E.ctx); + if (ve.empty()) ve = vis_encode(0); + if (!ve.empty()) { std::fprintf(stderr, "%s\n", ve.c_str()); return 1; } + } + if (spec) { // greedy speculative decoding: prompt in chunks, then draft 7 / verify 8 + const double s0 = now_ms(); + for (size_t p0 = 0; p0 < ids.size(); p0 += PF.TP) { + const int T = (int) std::min((size_t) PF.TP, ids.size() - p0); + forward_prefill(&ids[p0], T, (int) p0, nullptr); + draft_context(PF.feat, (int) p0, T); + if (p0 + T == ids.size()) draft_frnn(PF.feat + (size_t) (T - 1) * 4 * H); + } + CK(cudaMemcpy(logits.data(), E.logits, (size_t) VOCAB * 4, cudaMemcpyDeviceToHost)); + const double s1 = now_ms(); + Sampler smp; // INK2_TEMP / INK2_SEED (tests): sampled speculative decoding + if (const char* t = std::getenv("INK2_TEMP")) smp.temp = std::strtof(t, nullptr); + if (const char* t = std::getenv("INK2_SEED")) smp.rng.seed(std::strtoull(t, nullptr, 10)); + std::vector out = {sample(logits, smp)}; + spec_continue(out[0], (int) ids.size(), n_gen, smp, [&](int t) { out.push_back(t); return true; }, nullptr); + CK(cudaDeviceSynchronize()); + const double s2 = now_ms(); + out.resize(std::min((size_t) n_gen, out.size())); + std::printf("gen:"); + for (int t : out) std::printf(" %d", t); + std::printf("\nprompt %zu tokens %.0f ms (%.1f tok/s), decode %zu tokens %.0f ms (%.1f tok/s)\n", ids.size(), + s1 - s0, 1000.0 * ids.size() / (s1 - s0), out.size(), s2 - s1, 1000.0 * out.size() / (s2 - s1)); + std::printf("spec: %ld verifies, %.2f drafts accepted per verify (%.2f tokens per verify); accepted-count histogram:", + D.verifies, (double) D.accepted / std::max(1L, D.verifies), 1.0 + (double) D.accepted / std::max(1L, D.verifies)); + for (int k = 0; k < DBLK; ++k) std::printf(" %ld", D.hk[k]); + std::printf("; %ld plain tokens, %ld switches to plain\n", D.plain, D.switches); + return 0; + } + FILE* fg = dump_logits.empty() ? nullptr : std::fopen(dump_logits.c_str(), "wb"); + const double t0 = now_ms(); + if (PF.TP > 0) { // chunked prefill + std::vector all(fg ? (size_t) PF.TP * VOCAB : 0); + for (size_t p0 = 0, T = 0; p0 < ids.size(); p0 += T) { + T = (size_t) pf_fit((int) std::min((size_t) PF.TP, ids.size() - p0), (int) p0); + if ((int) T < g_pf_mapped_T) pf_unmap(); + pf_map((int) T); + forward_prefill(&ids[p0], T, (int) p0, fg ? all.data() : nullptr); + if (fg) std::fwrite(all.data(), 4, (size_t) T * VOCAB, fg); + } + CK(cudaMemcpy(logits.data(), E.logits, (size_t) VOCAB * 4, cudaMemcpyDeviceToHost)); + pf_unmap(); + } else { + for (size_t t = 0; t < ids.size(); ++t) { + step(ids[t], (int) t, fg != nullptr || t + 1 == ids.size()); + if (fg) std::fwrite(logits.data(), 4, logits.size(), fg); + } + } + CK(cudaDeviceSynchronize()); + const double t1 = now_ms(); + if (fg) std::fclose(fg); + unsigned long long fb1 = 0, fb2 = 0; + if (E.offload) CK(cudaMemcpy(&fb1, E.fbytes, 8, cudaMemcpyDeviceToHost)); + std::printf("gen:"); + int pos = (int) ids.size(); + for (int k = 0; k < n_gen; ++k) { + const int next = (int) (std::max_element(logits.begin(), logits.end()) - logits.begin()); + std::printf(" %d", next); + step(next, pos++, true); + } + CK(cudaDeviceSynchronize()); + const double t2 = now_ms(); + if (E.offload) { + CK(cudaMemcpy(&fb2, E.fbytes, 8, cudaMemcpyDeviceToHost)); + size_t fr = 0, tot = 0; + CK(cudaMemGetInfo(&fr, &tot)); + std::printf("\nexpert fetch: prompt %.1f MB/token, decode %.1f MB/token; VRAM used %.2f GiB of %.2f\n", + (fb1 + PF.fbytes) / 1e6 / std::max(1, ids.size()), (fb2 - fb1) / 1e6 / std::max(1, n_gen), + (tot - fr) / 1073741824.0, tot / 1073741824.0); + } + if (E.rec_mode == 1) { + std::vector r(rec_n); + CK(cudaMemcpy(r.data(), E.rec, rec_n * 4, cudaMemcpyDeviceToHost)); + FILE* f = std::fopen(rec_path.c_str(), "wb"); + std::fwrite(r.data(), 4, rec_n, f); + std::fclose(f); + } + std::printf("\nprompt %zu tokens %.0f ms (%.1f tok/s), decode %d tokens %.0f ms (%.1f tok/s)\n", ids.size(), t1 - t0, + 1000.0 * ids.size() / (t1 - t0), n_gen, t2 - t1, n_gen > 0 ? 1000.0 * n_gen / (t2 - t1) : 0.0); + return 0; +} diff --git a/engine/src/inkling2/ink2_gguf_experts.cuh b/engine/src/inkling2/ink2_gguf_experts.cuh new file mode 100644 index 00000000000..38ad393310e --- /dev/null +++ b/engine/src/inkling2/ink2_gguf_experts.cuh @@ -0,0 +1,66 @@ +// Expert formats of a GGUF model (included by ink2_engine.cu after the GGUF reader's Gguf / gg_row_bytes). +// A GGUF may give layers 0..MXFP8_FIRST-1 one ggml type pair (gate_up, down) and layers MXFP8_FIRST..NL-1 another, as the +// checkpoint does with NVFP4 / MXFP8 (ggml-org's IQ4_NL file keeps Q8_0 experts in layers 20-23). One pair for every +// layer: one expert pool, as before; two pairs: the later layers in pool_mx with their own slot size. +// CBA: one type pair per layer range, the ranges fixed at MXFP8_FIRST; arbitrary per-layer types would need a pool per +// slot size (and its share of the offload budget) +#pragma once + +const char* gg_type_name(uint32_t t) { // ggml.h's enum ggml_type + static const char* const n[] = {"F32", "F16", "Q4_0", "Q4_1", "type 4", "type 5", "Q5_0", "Q5_1", "Q8_0", "Q8_1", + "Q2_K", "Q3_K", "Q4_K", "Q5_K", "Q6_K", "Q8_K", "IQ2_XXS", "IQ2_XS", "IQ3_XXS", + "IQ1_S", "IQ4_NL", "IQ3_S", "IQ2_S", "IQ4_XS", "I8", "I16", "I32", "I64", "F64", + "IQ1_M", "BF16", "type 31", "type 32", "type 33", "TQ1_0", "TQ2_0", "type 36", + "type 37", "type 38", "MXFP4", "NVFP4", "Q1_0", "Q2_0", "F8_E4M3"}; + return t < sizeof n / sizeof n[0] ? n[t] : "unknown type"; +} +bool gg_expert_type_ok(uint32_t t) { return t == GG_IQ3_S || t == GG_IQ4_NL || t == GG_Q8_0; } + +// ty[l] = {gate_up type, down type} of layer l (nl layers, the second range from split): "" or why they are refused +std::string gg_expert_mix_error(const uint32_t (*ty)[2], int nl, int split) { + char m[320]; + for (int l = 0; l < nl; ++l) + for (int p = 0; p < 2; ++p) + if (!gg_expert_type_ok(ty[l][p])) { + std::snprintf(m, sizeof m, "GGUF experts: layer %d %s is %s (supported: IQ3_S, IQ4_NL, Q8_0)", l, + p ? "down" : "gate_up", gg_type_name(ty[l][p])); + return m; + } + for (int r0 : {0, split}) { + const int r1 = r0 ? nl : split; + for (int l = r0 + 1; l < r1; ++l) + if (ty[l][0] != ty[r0][0] || ty[l][1] != ty[r0][1]) { + std::snprintf(m, sizeof m, "GGUF experts: layer %d is %s / %s (gate_up / down), layer %d %s / %s; " + "supported: one type pair for layers 0-%d and one for layers %d-%d", l, + gg_type_name(ty[l][0]), gg_type_name(ty[l][1]), r0, gg_type_name(ty[r0][0]), + gg_type_name(ty[r0][1]), split - 1, split, nl - 1); + return m; + } + } + return ""; +} + +// g_gg_a / g_gg_b (part bytes per expert, both ranges) and g_gg_two, or exit naming the layers and types +void gg_expert_formats(const Gguf& g) { + uint32_t ty[NL][2]; + for (int l = 0; l < NL; ++l) { + ty[l][0] = g.get("blk." + std::to_string(l) + ".ffn_gate_up_exps.weight").type; + ty[l][1] = g.get("blk." + std::to_string(l) + ".ffn_down_exps.weight").type; + } + const std::string err = gg_expert_mix_error(ty, NL, MXFP8_FIRST); + if (!err.empty()) { std::fprintf(stderr, "%s\n", err.c_str()); std::exit(1); } + for (int r = 0; r < 2; ++r) { + const int l = r ? MXFP8_FIRST : 0; + g_gg_a[r] = g.get("blk." + std::to_string(l) + ".ffn_gate_up_exps.weight").bytes / NE; + g_gg_b[r] = g.get("blk." + std::to_string(l) + ".ffn_down_exps.weight").bytes / NE; + if (g_gg_a[r] % 16 || g_gg_b[r] % 16) { + std::fprintf(stderr, "GGUF experts of layer %d: %zu / %zu bytes, not 16-byte multiples\n", l, g_gg_a[r], g_gg_b[r]); + std::exit(1); + } + } + g_gg_two = ty[0][0] != ty[MXFP8_FIRST][0] || ty[0][1] != ty[MXFP8_FIRST][1]; + if (g_gg_two) + std::fprintf(stderr, "GGUF experts: layers 0-%d %s / %s, layers %d-%d %s / %s (two expert pools)\n", MXFP8_FIRST - 1, + gg_type_name(ty[0][0]), gg_type_name(ty[0][1]), MXFP8_FIRST, NL - 1, + gg_type_name(ty[MXFP8_FIRST][0]), gg_type_name(ty[MXFP8_FIRST][1])); +} diff --git a/engine/src/inkling2/ink2_grow_guard.cuh b/engine/src/inkling2/ink2_grow_guard.cuh new file mode 100644 index 00000000000..81bc13104d7 --- /dev/null +++ b/engine/src/inkling2/ink2_grow_guard.cuh @@ -0,0 +1,46 @@ +// --kv-grow with the expert offload: the K/V and the prompt buffers take their memory from the expert pools, and pools_release stops the +// process when a pool would fall under FETCH_MAX slots. These checks answer beforehand whether a growth fits: pf_fit reads a prompt in smaller +// chunks while one does not, and the serve loop ends a request the card cannot hold with an error (a prompt) or "length" (an answer) instead of +// the process stopping. Nothing here runs without --kv-grow. +// CBA: --spec with --kv-grow (resident only in setup) still grows through kv_fit unchecked; its verify reads the prompt path + +bool g_pf_full = false; // pf_fit: even a 256-token chunk would leave a pool under its minimum +bool g_ctx_full = false; // context_full ended the request (the serve loop goes on to the next one) +void pf_unmap(); + +// would pools_release(bytes) leave every pool FETCH_MAX slots? The same arithmetic, nothing released +bool pools_keep_min(double bytes) { + if (bytes <= 0) return true; + if (!E.offload) return false; + const double deficit = bytes + 4.0 * g_vmm.gran, used = pool_bytes(true) + pool_bytes(false); + for (bool nv : {true, false}) { + const int ns = nv ? E.nslot_nv : E.nslot_mx; + if (!ns) continue; + const int drop = (int) std::ceil(deficit * pool_bytes(nv) / used / pool_slot(nv)); + if (ns - drop < FETCH_MAX) return false; + } + return true; +} + +// can the K/V grow to `need` cells (kv_fit's step) without a pool falling under its minimum? +bool kv_room(int need) { + if (!E.grow || need <= E.kv_cells) return true; + const int nc = std::min(E.ctx, (need + E.grow_step - 1) / E.grow_step * E.grow_step); + const size_t add = kv_mapped_for(nc) - kv_mapped_for(E.kv_cells), keep = vram_keep(), fr = vram_free(); + return fr >= add + keep || pools_keep_min((double) (add + keep - fr)); +} + +// the serve loop's end of a prompt the card cannot hold: the buffers and the K/V beyond the default step back to the pools, nothing of this +// prompt kept as conversation (the K/V holds part of it), an ERR line for the server (no DONE follows) +void context_full(std::vector& hist, size_t read, size_t prompt) { + pf_unmap(); + kv_trim(1); + hist.clear(); + g_pf_full = false; + g_ctx_full = true; + std::fprintf(stderr, "kv-grow: the prompt does not fit, %zu of %zu tokens read; expert slots %d + %d\n", read, prompt, E.nslot_nv, + E.nslot_mx); + std::printf("ERR the context is full: the K/V of this %zu-token prompt does not fit beside the expert pools on this card (%zu tokens read); " + "a shorter conversation fits\n", prompt, read); + std::fflush(stdout); +} diff --git a/engine/src/inkling2/ink2_image.cpp b/engine/src/inkling2/ink2_image.cpp new file mode 100644 index 00000000000..ea469535671 --- /dev/null +++ b/engine/src/inkling2/ink2_image.cpp @@ -0,0 +1,158 @@ +// src/inkling2/ink2_image.cpp - see ink2_image.hpp. +#include "ink2_image.hpp" + +#include +#include +#include +#include +#include + +#define STB_IMAGE_IMPLEMENTATION +#define STBI_ONLY_JPEG +#define STBI_ONLY_PNG +#define STBI_ONLY_BMP +#define STBI_ONLY_GIF +#define STBI_NO_LINEAR +#define STBI_NO_HDR +#include "../../third_party/stb/stb_image.h" + +namespace ink2img { +namespace { + +int tokens_for(int w, int h) { return ((h + TILE - 1) / TILE) * ((w + TILE - 1) / TILE); } + +// area average (each output pixel the mean of the source area it covers, partial pixels weighted) +// CBA: the engine's own downscale for pictures over the token cap (the reference processor never resizes, so there is +// nothing to match); a PIL-style antialiased bicubic would only matter if the cap is hit often +void area_resize(const std::vector& src, int sw, int sh, std::vector& dst, int dw, int dh) { + dst.assign((size_t) dw * dh * 3, 0); + const double fx = (double) sw / dw, fy = (double) sh / dh; + for (int oy = 0; oy < dh; ++oy) { + const double y0 = oy * fy, y1 = (oy + 1) * fy; + for (int ox = 0; ox < dw; ++ox) { + const double x0 = ox * fx, x1 = (ox + 1) * fx; + double acc[3] = {0, 0, 0}, area = 0; + for (int iy = (int) y0; iy < std::min(sh, (int) std::ceil(y1)); ++iy) { + const double wy = std::min(y1, iy + 1.0) - std::max(y0, (double) iy); + for (int ix = (int) x0; ix < std::min(sw, (int) std::ceil(x1)); ++ix) { + const double wgt = wy * (std::min(x1, ix + 1.0) - std::max(x0, (double) ix)); + const uint8_t* s = &src[((size_t) iy * sw + ix) * 3]; + for (int c = 0; c < 3; ++c) acc[c] += wgt * s[c]; + area += wgt; + } + } + for (int c = 0; c < 3; ++c) + dst[((size_t) oy * dw + ox) * 3 + c] = (uint8_t) std::min(255.0, std::max(0.0, std::round(acc[c] / area))); + } + } +} + +// patches from a tile accessor px(tile, y, x, c) (y, x within the 40 x 40 tile) +template +void cut(Picture& p, F px) { + const int nt = p.rows * p.cols; + p.patches.assign((size_t) nt * 4 * PIN, 0.0f); + for (int t = 0; t < nt; ++t) + for (int ir = 0; ir < 2; ++ir) + for (int ic = 0; ic < 2; ++ic) { + float* o = &p.patches[((size_t) t * 4 + ir * 2 + ic) * PIN]; + for (int y = 0; y < PATCH; ++y) + for (int x = 0; x < PATCH; ++x) + for (int c = 0; c < 3; ++c) *o++ = px(t, ir * PATCH + y, ic * PATCH + x, c); + } +} + +} // namespace + +std::string load_picture(const std::string& path, int max_tokens, Picture& p) { + int w = 0, h = 0, comp = 0; + if (!stbi_info(path.c_str(), &w, &h, &comp)) return "cannot decode " + path + ": " + stbi_failure_reason(); + if ((int64_t) w * h > ((int64_t) 1 << 27)) // 134 MP (16 bytes a pixel while it is read: ~2 GB of RAM) + return "picture of " + std::to_string(w) + "x" + std::to_string(h) + " px: more than 134 million pixels"; + unsigned char* px = stbi_load(path.c_str(), &w, &h, &comp, 4); + if (!px) return "cannot decode " + path + ": " + stbi_failure_reason(); + if (w < 1 || h < 1) { stbi_image_free(px); return "empty picture " + path; } + // the processor's convert_to_rgb: alpha over a checkerboard of 8 px squares, 204 where (row/8 + col/8) is even, else + // 153, integer rounding as (rgb * a + bg * (255 - a) + 127) / 255 (an opaque pixel stays as it is) + std::vector rgb((size_t) w * h * 3); + for (int y = 0; y < h; ++y) + for (int x = 0; x < w; ++x) { + const unsigned char* s = px + ((size_t) y * w + x) * 4; + const int a = s[3], bg = ((y / 8 + x / 8) % 2 == 0) ? 204 : 153; + for (int c = 0; c < 3; ++c) rgb[((size_t) y * w + x) * 3 + c] = (uint8_t) ((s[c] * a + bg * (255 - a) + 127) / 255); + } + stbi_image_free(px); + p.src_w = w; + p.src_h = h; + if (max_tokens > 0 && tokens_for(w, h) > max_tokens) { + double s = std::sqrt((double) max_tokens * TILE * TILE / ((double) w * h)); + int nw, nh; + for (;; s *= 0.995) { + nw = std::max(1, (int) (w * s)); + nh = std::max(1, (int) (h * s)); + if (tokens_for(nw, nh) <= max_tokens) break; + } + std::vector small; + area_resize(rgb, w, h, small, nw, nh); + rgb.swap(small); + w = nw; + h = nh; + } + p.w = w; + p.h = h; + p.rows = (h + TILE - 1) / TILE; + p.cols = (w + TILE - 1) / TILE; + uint64_t k = 1469598103934665603ull; + auto mix = [&k](const void* d, size_t n) { + for (size_t i = 0; i < n; ++i) { k ^= ((const uint8_t*) d)[i]; k *= 1099511628211ull; } + }; + mix(&w, sizeof w); + mix(&h, sizeof h); + mix(rgb.data(), rgb.size()); + p.key = k; + const float pad = (-1.0f - 127.5f) / 127.5f; // the processor pads with -1 on the 0-255 scale, then normalizes + cut(p, [&](int t, int y, int x, int c) { + const int gy = (t / p.cols) * TILE + y, gx = (t % p.cols) * TILE + x; + if (gy >= h || gx >= w) return pad; + return ((float) rgb[((size_t) gy * w + gx) * 3 + c] - 127.5f) / 127.5f; + }); + return ""; +} + +std::string load_pixels(const std::string& path, Picture& p) { + FILE* f = std::fopen(path.c_str(), "rb"); + if (!f) return "cannot open " + path; + int32_t rc[2] = {0, 0}; + std::vector t; + std::string err; + if (std::fread(rc, 4, 2, f) != 2 || rc[0] < 1 || rc[1] < 1) err = "bad pixel file " + path; + else { + t.resize((size_t) rc[0] * rc[1] * TILE * TILE * 3); + if (std::fread(t.data(), 4, t.size(), f) != t.size()) err = "short pixel file " + path; + } + std::fclose(f); + if (!err.empty()) return err; + p.rows = rc[0]; + p.cols = rc[1]; + p.w = p.src_w = p.cols * TILE; + p.h = p.src_h = p.rows * TILE; + p.key = 0; + cut(p, [&](int tile, int y, int x, int c) { return t[(((size_t) tile * TILE + y) * TILE + x) * 3 + c]; }); + return ""; +} + +std::string pct_decode(const std::string& s) { + std::string o; + for (size_t i = 0; i < s.size(); ++i) { + if (s[i] == '%' && i + 2 < s.size()) { + const std::string hx = s.substr(i + 1, 2); + char* e = nullptr; + const long v = std::strtol(hx.c_str(), &e, 16); + if (e && *e == '\0') { o += (char) v; i += 2; continue; } + } + o += s[i]; + } + return o; +} + +} // namespace ink2img diff --git a/engine/src/inkling2/ink2_image.hpp b/engine/src/inkling2/ink2_image.hpp new file mode 100644 index 00000000000..393cb702c87 --- /dev/null +++ b/engine/src/inkling2/ink2_image.hpp @@ -0,0 +1,37 @@ +// src/inkling2/ink2_image.hpp - Inkling-2's pictures on the host (plain C++, no GPU): decode, the processor's +// preprocessing, and the ViT's input patches. The ViT itself is ink2_vision.cuh. +// +// transformers' Inkling2ImageProcessor (huggingface/transformers#51050) never resizes: the picture is padded at the +// right and the bottom to whole 40 x 40 tiles with -1 on the 0-255 scale, scaled to [-1, 1] ((p - 127.5) / 127.5), +// and each tile is one image token (rows x cols tokens, raster order). The ViT cuts a tile into 2 x 2 native patches +// of 20 x 20 pixels, each a 1200-vector in (y, x, channel) order. A picture with an alpha channel is composited onto +// the processor's checkerboard (8 px squares of 204 / 153) first. +#pragma once +#include +#include +#include + +namespace ink2img { + +constexpr int TILE = 40, PATCH = 20, PIN = 3 * PATCH * PATCH; // 1200 inputs per native patch + +struct Picture { + int w = 0, h = 0; // the size the ViT reads (after the token cap) + int src_w = 0, src_h = 0; // as decoded + int rows = 0, cols = 0; // image tokens: ceil(h / 40) x ceil(w / 40) + uint64_t key = 0; // FNV-1a of the pixels the ViT reads and their size (what prefix reuse compares) + std::vector patches; // [rows * cols * 4][1200]: per tile (raster order) its 2 x 2 patches, row-major +}; + +// Decodes a JPEG / PNG / BMP / GIF (first frame) file and prepares it. A picture over `max_tokens` image tokens is +// scaled down to fit first (the reference never resizes: this is the engine's own cap). "" or the error. +std::string load_picture(const std::string& path, int max_tokens, Picture& p); + +// The processor's own pixel tensor (terminal/tools/inkling2/vision_oracle.py .pix: int32 rows, int32 cols, then +// float32 [rows * cols][40][40][3]), cut into the ViT's patches. "" or the error. +std::string load_pixels(const std::string& path, Picture& p); + +// %20 -> space, %25 -> % (the protocol's image= keys, as serve/hy4_kind.py encode_path writes them) +std::string pct_decode(const std::string& s); + +} // namespace ink2img diff --git a/engine/src/inkling2/ink2_iq_tables.h b/engine/src/inkling2/ink2_iq_tables.h new file mode 100644 index 00000000000..ee4f3b71fed --- /dev/null +++ b/engine/src/inkling2/ink2_iq_tables.h @@ -0,0 +1,72 @@ +// ink2_iq_tables.h - the IQ3_S grid and the IQ4_NL code book, copied from llama.cpp ggml/src/ggml-common.h (MIT), +// used by the GGUF expert kernels of ink2_engine.cu (--model FILE.gguf). +#pragma once +#include + +static const uint32_t k_iq3s_grid[512] = { + 0x01010101, 0x01010103, 0x01010105, 0x0101010b, 0x0101010f, 0x01010301, 0x01010303, 0x01010305, + 0x01010309, 0x0101030d, 0x01010501, 0x01010503, 0x0101050b, 0x01010707, 0x01010901, 0x01010905, + 0x0101090b, 0x0101090f, 0x01010b03, 0x01010b07, 0x01010d01, 0x01010d05, 0x01010f03, 0x01010f09, + 0x01010f0f, 0x01030101, 0x01030103, 0x01030105, 0x01030109, 0x01030301, 0x01030303, 0x0103030b, + 0x01030501, 0x01030507, 0x0103050f, 0x01030703, 0x0103070b, 0x01030909, 0x01030d03, 0x01030d0b, + 0x01030f05, 0x01050101, 0x01050103, 0x0105010b, 0x0105010f, 0x01050301, 0x01050307, 0x0105030d, + 0x01050503, 0x0105050b, 0x01050701, 0x01050709, 0x01050905, 0x0105090b, 0x0105090f, 0x01050b03, + 0x01050b07, 0x01050f01, 0x01050f07, 0x01070107, 0x01070303, 0x0107030b, 0x01070501, 0x01070505, + 0x01070703, 0x01070707, 0x0107070d, 0x01070909, 0x01070b01, 0x01070b05, 0x01070d0f, 0x01070f03, + 0x01070f0b, 0x01090101, 0x01090307, 0x0109030f, 0x01090503, 0x01090509, 0x01090705, 0x01090901, + 0x01090907, 0x01090b03, 0x01090f01, 0x010b0105, 0x010b0109, 0x010b0501, 0x010b0505, 0x010b050d, + 0x010b0707, 0x010b0903, 0x010b090b, 0x010b090f, 0x010b0d0d, 0x010b0f07, 0x010d010d, 0x010d0303, + 0x010d0307, 0x010d0703, 0x010d0b05, 0x010d0f03, 0x010f0101, 0x010f0105, 0x010f0109, 0x010f0501, + 0x010f0505, 0x010f050d, 0x010f0707, 0x010f0b01, 0x010f0b09, 0x03010101, 0x03010103, 0x03010105, + 0x03010109, 0x03010301, 0x03010303, 0x03010307, 0x0301030b, 0x0301030f, 0x03010501, 0x03010505, + 0x03010703, 0x03010709, 0x0301070d, 0x03010b09, 0x03010b0d, 0x03010d03, 0x03010f05, 0x03030101, + 0x03030103, 0x03030107, 0x0303010d, 0x03030301, 0x03030309, 0x03030503, 0x03030701, 0x03030707, + 0x03030903, 0x03030b01, 0x03030b05, 0x03030f01, 0x03030f0d, 0x03050101, 0x03050305, 0x0305030b, + 0x0305030f, 0x03050501, 0x03050509, 0x03050705, 0x03050901, 0x03050907, 0x03050b0b, 0x03050d01, + 0x03050f05, 0x03070103, 0x03070109, 0x0307010f, 0x03070301, 0x03070307, 0x03070503, 0x0307050f, + 0x03070701, 0x03070709, 0x03070903, 0x03070d05, 0x03070f01, 0x03090107, 0x0309010b, 0x03090305, + 0x03090309, 0x03090703, 0x03090707, 0x03090905, 0x0309090d, 0x03090b01, 0x03090b09, 0x030b0103, + 0x030b0301, 0x030b0307, 0x030b0503, 0x030b0701, 0x030b0705, 0x030b0b03, 0x030d0501, 0x030d0509, + 0x030d050f, 0x030d0909, 0x030d090d, 0x030f0103, 0x030f0107, 0x030f0301, 0x030f0305, 0x030f0503, + 0x030f070b, 0x030f0903, 0x030f0d05, 0x030f0f01, 0x05010101, 0x05010103, 0x05010107, 0x0501010b, + 0x0501010f, 0x05010301, 0x05010305, 0x05010309, 0x0501030d, 0x05010503, 0x05010507, 0x0501050f, + 0x05010701, 0x05010705, 0x05010903, 0x05010907, 0x0501090b, 0x05010b01, 0x05010b05, 0x05010d0f, + 0x05010f01, 0x05010f07, 0x05010f0b, 0x05030101, 0x05030105, 0x05030301, 0x05030307, 0x0503030f, + 0x05030505, 0x0503050b, 0x05030703, 0x05030709, 0x05030905, 0x05030b03, 0x05050103, 0x05050109, + 0x0505010f, 0x05050503, 0x05050507, 0x05050701, 0x0505070f, 0x05050903, 0x05050b07, 0x05050b0f, + 0x05050f03, 0x05050f09, 0x05070101, 0x05070105, 0x0507010b, 0x05070303, 0x05070505, 0x05070509, + 0x05070703, 0x05070707, 0x05070905, 0x05070b01, 0x05070d0d, 0x05090103, 0x0509010f, 0x05090501, + 0x05090507, 0x05090705, 0x0509070b, 0x05090903, 0x05090f05, 0x05090f0b, 0x050b0109, 0x050b0303, + 0x050b0505, 0x050b070f, 0x050b0901, 0x050b0b07, 0x050b0f01, 0x050d0101, 0x050d0105, 0x050d010f, + 0x050d0503, 0x050d0b0b, 0x050d0d03, 0x050f010b, 0x050f0303, 0x050f050d, 0x050f0701, 0x050f0907, + 0x050f0b01, 0x07010105, 0x07010303, 0x07010307, 0x0701030b, 0x0701030f, 0x07010505, 0x07010703, + 0x07010707, 0x0701070b, 0x07010905, 0x07010909, 0x0701090f, 0x07010b03, 0x07010d07, 0x07010f03, + 0x07030103, 0x07030107, 0x0703010b, 0x07030309, 0x07030503, 0x07030507, 0x07030901, 0x07030d01, + 0x07030f05, 0x07030f0d, 0x07050101, 0x07050305, 0x07050501, 0x07050705, 0x07050709, 0x07050b01, + 0x07070103, 0x07070301, 0x07070309, 0x07070503, 0x07070507, 0x0707050f, 0x07070701, 0x07070903, + 0x07070907, 0x0707090f, 0x07070b0b, 0x07070f07, 0x07090107, 0x07090303, 0x0709030d, 0x07090505, + 0x07090703, 0x07090b05, 0x07090d01, 0x07090d09, 0x070b0103, 0x070b0301, 0x070b0305, 0x070b050b, + 0x070b0705, 0x070b0909, 0x070b0b0d, 0x070b0f07, 0x070d030d, 0x070d0903, 0x070f0103, 0x070f0107, + 0x070f0501, 0x070f0505, 0x070f070b, 0x09010101, 0x09010109, 0x09010305, 0x09010501, 0x09010509, + 0x0901050f, 0x09010705, 0x09010903, 0x09010b01, 0x09010f01, 0x09030105, 0x0903010f, 0x09030303, + 0x09030307, 0x09030505, 0x09030701, 0x0903070b, 0x09030907, 0x09030b03, 0x09030b0b, 0x09050103, + 0x09050107, 0x09050301, 0x0905030b, 0x09050503, 0x09050707, 0x09050901, 0x09050b0f, 0x09050d05, + 0x09050f01, 0x09070109, 0x09070303, 0x09070307, 0x09070501, 0x09070505, 0x09070703, 0x0907070b, + 0x09090101, 0x09090105, 0x09090509, 0x0909070f, 0x09090901, 0x09090f03, 0x090b010b, 0x090b010f, + 0x090b0503, 0x090b0d05, 0x090d0307, 0x090d0709, 0x090d0d01, 0x090f0301, 0x090f030b, 0x090f0701, + 0x090f0907, 0x090f0b03, 0x0b010105, 0x0b010301, 0x0b010309, 0x0b010505, 0x0b010901, 0x0b010909, + 0x0b01090f, 0x0b010b05, 0x0b010d0d, 0x0b010f09, 0x0b030103, 0x0b030107, 0x0b03010b, 0x0b030305, + 0x0b030503, 0x0b030705, 0x0b030f05, 0x0b050101, 0x0b050303, 0x0b050507, 0x0b050701, 0x0b05070d, + 0x0b050b07, 0x0b070105, 0x0b07010f, 0x0b070301, 0x0b07050f, 0x0b070909, 0x0b070b03, 0x0b070d0b, + 0x0b070f07, 0x0b090103, 0x0b090109, 0x0b090501, 0x0b090705, 0x0b09090d, 0x0b0b0305, 0x0b0b050d, + 0x0b0b0b03, 0x0b0b0b07, 0x0b0d0905, 0x0b0f0105, 0x0b0f0109, 0x0b0f0505, 0x0d010303, 0x0d010307, + 0x0d01030b, 0x0d010703, 0x0d010707, 0x0d010d01, 0x0d030101, 0x0d030501, 0x0d03050f, 0x0d030d09, + 0x0d050305, 0x0d050709, 0x0d050905, 0x0d050b0b, 0x0d050d05, 0x0d050f01, 0x0d070101, 0x0d070309, + 0x0d070503, 0x0d070901, 0x0d09050b, 0x0d090907, 0x0d090d05, 0x0d0b0101, 0x0d0b0107, 0x0d0b0709, + 0x0d0b0d01, 0x0d0d010b, 0x0d0d0901, 0x0d0f0303, 0x0d0f0307, 0x0f010101, 0x0f010109, 0x0f01010f, + 0x0f010501, 0x0f010505, 0x0f01070d, 0x0f010901, 0x0f010b09, 0x0f010d05, 0x0f030105, 0x0f030303, + 0x0f030509, 0x0f030907, 0x0f03090b, 0x0f050103, 0x0f050109, 0x0f050301, 0x0f05030d, 0x0f050503, + 0x0f050701, 0x0f050b03, 0x0f070105, 0x0f070705, 0x0f07070b, 0x0f070b07, 0x0f090103, 0x0f09010b, + 0x0f090307, 0x0f090501, 0x0f090b01, 0x0f0b0505, 0x0f0b0905, 0x0f0d0105, 0x0f0d0703, 0x0f0f0101, +}; +static const int8_t k_iq4nl_values[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113}; diff --git a/engine/src/inkling2/ink2_session.cuh b/engine/src/inkling2/ink2_session.cuh new file mode 100644 index 00000000000..ddec41966e6 --- /dev/null +++ b/engine/src/inkling2/ink2_session.cuh @@ -0,0 +1,336 @@ +// The conversation cache of --serve (--conversation-cache-mib N, off by default): agentic use (one agent over many +// turns, an agent and its sub-agents taking turns) does not read again a prompt it has already read. +// +// The slots hold one conversation (the live one, `hist` of the serve loop). Its state after n tokens is, per layer +// visit: the full-attention K / V rows [0, n) (8 visits), the sliding-window rows of positions [n - WINDOW, n) in +// their ring (40 visits), the four causal-conv rings (khist / vhist / ahist / mhist, HR rows each, 48 visits); with +// --spec the drafter's K / V (its global layer: rows [0, n), its two local layers: their ring's window); and the +// logits after token n - 1. Every --kv format is bytes per row here (codes and scales alike, kv_cell_bytes). Not +// per conversation, not saved: the expert pools and the CPU experts' placement, the drafter's Markov context (the +// serve loop always reads at least the prompt's last token with --spec, which recomputes it), the sampler. +// +// A checkpoint (Ck) is the "tail" of a state at n: everything above except the full-attention rows, ~190 MiB at f16, +// in page-locked host memory. The full rows [0, n) are free to keep: a later position never writes them. So: +// - at each prompt's end (before the first sampled token) a checkpoint of the live conversation: a client that +// sends the history back re-rendered (its reasoning dropped, its tool call re-serialized) diverges from the +// generated tokens after the prompt, and the next request restores that point instead of reading from 0; +// - a request that does not extend the live conversation's last prompt parks it (its full rows, its checkpoints +// and one at its history end) and restores the parked conversation, live checkpoint or branch point that covers +// the longest prefix of the request; +// - a request sharing a long prefix with a known conversation without a checkpoint there (sub-agents sharing a +// system prompt and tools) stops its prefill at the branch point once and takes a checkpoint there. +// LRU over whole parked conversations under the budget. Off: none of this runs (the serve loop is the base one). + +constexpr int SPLIT_MIN = 512; // a branch point is taken when it covers this many tokens more than the best state + +struct Pinned { // page-locked host memory (DMA only: any NUMA node) + uint8_t* p = nullptr; + size_t n = 0; + explicit Pinned(size_t bytes) { + if (bytes && cudaHostAlloc((void**) &p, bytes, cudaHostAllocDefault) == cudaSuccess) n = bytes; + else { p = nullptr; (void) cudaGetLastError(); } + } + ~Pinned() { if (p) cudaFreeHost(p); } + Pinned(const Pinned&) = delete; + Pinned& operator=(const Pinned&) = delete; +}; +using PinnedP = std::shared_ptr; + +struct Ck { // the tail of the state after the first n tokens + int n = 0; + PinnedP tail; + vec logits; + int kind = 0; // CK_PROMPT a prompt's end, CK_BRANCH a branch point, CK_END a parked history's end +}; +constexpr int CK_PROMPT = 0, CK_BRANCH = 1, CK_END = 2; +struct Conv { // a parked conversation: its tokens, its full rows [0, ids.size()), its checkpoints + std::vector ids; + PinnedP full; + std::vector cks; + int prompt_n = 0; // its last prompt's length: a request extending it continues this conversation + uint64_t used = 0; + bool hold = false; // the one sess_begin restores: not evicted meanwhile +}; + +struct SessArr { uint8_t* d; size_t b; int cap; }; // device rows of b bytes, position q in row q % cap + +struct Sess { + bool on = false; + size_t budget = 0; // bytes + int min_tokens = 512; // --conversation-cache-min-tokens: shorter conversations are not parked + std::vector full, ring; + std::vector> conv; + size_t tail_bytes = 0, row_bytes = 0; + std::vector live; // checkpoints of the live conversation (its full rows are the slots') + int live_prompt = 0; // the live conversation's last prompt length (0: none) + std::vector parked; + std::vector spare; // tails no longer used (cudaHostAlloc is slow): taken again first + uint64_t clock = 0; + int split = -1; // this request: the prefill stops here for a branch checkpoint + std::string note; // this request's log line +} g_sess; + +void sess_init(int mib, int min_tokens) { + if (mib <= 0) return; + g_sess.min_tokens = min_tokens; + for (int s = 0; s < NCALLS; ++s) { + Slot& S = E.S[s]; + void* arr[4] = {S.K, S.V, S.ksc, S.vsc}; + for (int a = 0; a < 4; ++a) { + const size_t b = kv_cell_bytes(a); + if (!b) continue; + (S.full ? g_sess.full : g_sess.ring).push_back({(uint8_t*) arr[a], b, S.cap}); + } + g_sess.conv.push_back({S.khist, (size_t) HR * KVD * 4}); + g_sess.conv.push_back({S.vhist, (size_t) HR * KVD * 4}); + g_sess.conv.push_back({S.ahist, (size_t) HR * H * 4}); + g_sess.conv.push_back({S.mhist, (size_t) HR * H * 4}); + } + if (D.on) + for (int i = 0; i < DL; ++i) + for (__half* x : {D.L[i].K, D.L[i].V}) (D.L[i].local ? g_sess.ring : g_sess.full).push_back({(uint8_t*) x, (size_t) KVD * 2, D.L[i].cap}); + for (auto& a : g_sess.ring) g_sess.tail_bytes += (size_t) WINDOW * a.b; + for (auto& c : g_sess.conv) g_sess.tail_bytes += c.second; + for (auto& a : g_sess.full) g_sess.row_bytes += a.b; + g_sess.budget = (size_t) mib << 20; + if (g_sess.budget < 3 * g_sess.tail_bytes) { + std::fprintf(stderr, "--conversation-cache-mib %d: below %zu MiB (three checkpoints of %zu MiB): cache off\n", mib, + (3 * g_sess.tail_bytes) >> 20, g_sess.tail_bytes >> 20); + return; + } + g_sess.on = true; + std::fprintf(stderr, "conversation cache: %d MiB of host memory, checkpoints of %.0f MiB, %.1f KiB per parked token, " + "conversations of %d+ tokens parked\n", mib, g_sess.tail_bytes / 1048576.0, g_sess.row_bytes / 1024.0, min_tokens); +} + +size_t sess_lcp(const std::vector& a, const std::vector& b) { + size_t l = 0; + while (l < a.size() && l < b.size() && a[l] == b[l]) ++l; + return l; +} +// positions [lo, hi) of an array <-> host bytes h (position order) +void sess_rows(const SessArr& a, int lo, int hi, uint8_t* h, bool d2h) { + for (int q = lo; q < hi;) { + const int r = q % a.cap, m = std::min(hi - q, a.cap - r); + uint8_t* dv = a.d + (size_t) r * a.b; + uint8_t* hv = h + (size_t) (q - lo) * a.b; + CK(cudaMemcpyAsync(d2h ? (void*) hv : (void*) dv, d2h ? (const void*) dv : (const void*) hv, (size_t) m * a.b, + d2h ? cudaMemcpyDeviceToHost : cudaMemcpyHostToDevice, cudaStreamPerThread)); + q += m; + } +} +void sess_tail(int n, uint8_t* h, bool d2h) { // the ring windows and conv rings of the state at n + CK(cudaDeviceSynchronize()); + const int lo = std::max(0, n - WINDOW); + for (auto& a : g_sess.ring) { sess_rows(a, lo, n, h, d2h); h += (size_t) WINDOW * a.b; } + for (auto& c : g_sess.conv) { + CK(cudaMemcpyAsync(d2h ? (void*) h : c.first, d2h ? (const void*) c.first : (const void*) h, c.second, + d2h ? cudaMemcpyDeviceToHost : cudaMemcpyHostToDevice, cudaStreamPerThread)); + h += c.second; + } + CK(cudaDeviceSynchronize()); +} +void sess_full(int n, uint8_t* h, bool d2h) { // the full rows [0, n), array after array + CK(cudaDeviceSynchronize()); + for (auto& a : g_sess.full) { sess_rows(a, 0, n, h, d2h); h += (size_t) n * a.b; } + CK(cudaDeviceSynchronize()); +} + +// host bytes held: each tail once (branch checkpoints are shared between conversations) +size_t sess_used() { + std::vector seen; + size_t t = 0; + auto tail = [&](const PinnedP& p) { + if (p && std::find(seen.begin(), seen.end(), p.get()) == seen.end()) { seen.push_back(p.get()); t += p->n; } + }; + for (auto& c : g_sess.live) tail(c.tail); + for (auto& v : g_sess.parked) { t += v.full ? v.full->n : 0; for (auto& c : v.cks) tail(c.tail); } + for (auto& p : g_sess.spare) tail(p); + return t; +} +// room for `bytes` more: spare buffers freed first, then the least recently used parked conversations (not one held) +bool sess_room(size_t bytes) { + while (sess_used() + bytes > g_sess.budget) { + if (!g_sess.spare.empty()) { g_sess.spare.pop_back(); continue; } + auto lru = g_sess.parked.end(); + for (auto it = g_sess.parked.begin(); it != g_sess.parked.end(); ++it) + if (!it->hold && (lru == g_sess.parked.end() || it->used < lru->used)) lru = it; + if (lru == g_sess.parked.end()) return false; + g_sess.note += " evicted " + std::to_string(lru->ids.size()); + g_sess.parked.erase(lru); + } + return true; +} +// CBA: page-locked buffers are kept for reuse (cudaHostAlloc pins ~0.45 ms per MiB on a PCIe 3 host: 80 ms per +// checkpoint), a spare taken for anything up to half its size; checkpoints in PIN_UNIT steps, a parked conversation's +// rows in PIN_UNIT << k (a conversation that grew a turn finds its last buffer again). Up to half a row buffer is +// slack; a sub-allocator in one pinned arena would waste less +constexpr size_t PIN_UNIT = (size_t) 32 << 20; +PinnedP sess_alloc(size_t bytes, bool geo = false) { + bytes = (bytes + PIN_UNIT - 1) / PIN_UNIT * PIN_UNIT; + if (geo) { size_t g = PIN_UNIT; while (g < bytes) g *= 2; bytes = g; } + auto& sp = g_sess.spare; + size_t bi = sp.size(); + for (size_t i = 0; i < sp.size(); ++i) + if (sp[i]->n >= bytes && sp[i]->n <= 2 * bytes && (bi == sp.size() || sp[i]->n < sp[bi]->n)) bi = i; + if (bi < sp.size()) { PinnedP p = sp[bi]; sp.erase(sp.begin() + bi); return p; } + if (!sess_room(bytes)) return nullptr; + PinnedP p = std::make_shared(bytes); + return p->p ? p : nullptr; +} +void sess_drop(PinnedP&& p) { // a buffer nothing uses any more goes to the spares + if (p && p.use_count() == 1) g_sess.spare.push_back(std::move(p)); + p.reset(); +} +// a checkpoint of the live state at n (its logits: lg) +bool sess_take(int n, const vec& lg, int kind) { + PinnedP t = sess_alloc(g_sess.tail_bytes); + if (!t) { g_sess.note += " no-room"; return false; } + sess_tail(n, t->p, true); + g_sess.live.push_back({n, t, lg, kind}); + return true; +} + +// The live conversation (hist, last_logits) to the parked set, when worth it: its full rows, its checkpoints and its +// history end. The live checkpoints stay valid for the slots (a later restore may use them). +void sess_park(const std::vector& hist, const vec& last_logits) { + if ((int) hist.size() < g_sess.min_tokens) return; + Conv v; + v.ids = hist; + v.prompt_n = g_sess.live_prompt; + v.cks = g_sess.live; + const bool end = std::none_of(v.cks.begin(), v.cks.end(), [&](const Ck& c) { return c.n == (int) hist.size(); }); + const size_t need = hist.size() * g_sess.row_bytes + (end ? g_sess.tail_bytes : 0); + if (!sess_room(need)) { g_sess.note += " park-no-room"; return; } + // in the parked set (held) while its buffers are taken, so that the budget counts them + v.used = ++g_sess.clock; + v.hold = true; + const uint64_t id = v.used; + g_sess.parked.push_back(std::move(v)); + auto me = [&]() -> Conv& { for (auto& c : g_sess.parked) if (c.used == id) return c; return g_sess.parked.back(); }; + PinnedP full = sess_alloc(hist.size() * g_sess.row_bytes, true); + if (!full) { + for (size_t j = 0; j < g_sess.parked.size(); ++j) if (g_sess.parked[j].used == id) g_sess.parked.erase(g_sess.parked.begin() + j); + g_sess.note += " park-no-room"; + return; + } + me().full = full; + sess_full((int) hist.size(), full->p, true); + if (end) { + PinnedP t = sess_alloc(g_sess.tail_bytes); + if (t) { sess_tail((int) hist.size(), t->p, true); me().cks.push_back({(int) hist.size(), t, last_logits, CK_END}); } + } + me().hold = false; + g_sess.note += " parked " + std::to_string(hist.size()); +} + +// Before the request's kv_trim (a parked conversation's rows are still mapped): picks the longest prefix of pr with a +// state, parks the live conversation if pr does not continue it, restores that state. `start` = the base loop's +// choice (hist.size() when pr extends hist, else 0); returns the position to read from. hist / last_logits follow. +size_t sess_begin(const std::vector& pr, std::vector& hist, vec& last_logits, size_t start) { + g_sess.split = -1; + g_sess.note.clear(); + const double t0 = now_ms(); + // (a picture's image tokens are ids made from its pixels' hash, ink2_vision.cuh vis_id: every comparison below + // tells two pictures of the same size apart) + const size_t l_live = sess_lcp(hist, pr); + // the best state: the live history end (start), a live checkpoint, a parked conversation's checkpoint + size_t best = start, share = l_live; + int src = start > 0 ? 0 : -1, ck = -1, pv = -1; // src: 0 live end, 1 live checkpoint, 2 parked, -1 none + for (size_t i = 0; i < g_sess.live.size(); ++i) + if (g_sess.live[i].n <= (int) l_live && g_sess.live[i].n > (int) best) { best = g_sess.live[i].n; src = 1; ck = (int) i; } + for (size_t j = 0; j < g_sess.parked.size(); ++j) { + const size_t l = sess_lcp(g_sess.parked[j].ids, pr); + share = std::max(share, l); + for (size_t i = 0; i < g_sess.parked[j].cks.size(); ++i) + if (g_sess.parked[j].cks[i].n <= (int) l && g_sess.parked[j].cks[i].n > (int) best) { best = g_sess.parked[j].cks[i].n; src = 2; ck = (int) i; pv = (int) j; } + } + // the live conversation is parked unless the request extends its last prompt (the same conversation, re-rendered + // or continued) + const bool same = (!hist.empty() && l_live == hist.size()) || (g_sess.live_prompt > 0 && (int) l_live >= g_sess.live_prompt); + // a branch point between conversations only (a re-render diverging deep in the generated tail is not one) + if (!same && share >= best + SPLIT_MIN && share < pr.size()) g_sess.split = (int) share; + if (pv >= 0) g_sess.parked[pv].hold = true; + if (!same && !hist.empty()) sess_park(hist, last_logits); // (may evict parked conversations, not the held one) + for (size_t j = 0; j < g_sess.parked.size(); ++j) if (g_sess.parked[j].hold) { pv = (int) j; g_sess.parked[j].hold = false; } + const char* how = "live"; + if (src == 1) { // the slots' own rows [0, n): the tail only + const Ck c = g_sess.live[ck]; + sess_tail(c.n, c.tail->p, false); + last_logits = c.logits; + how = "rewind"; + } else if (src == 2) { + Conv& v = g_sess.parked[pv]; + const Ck c = v.cks[ck]; + kv_fit(c.n + 1); // --kv-grow: a conversation longer than the K/V mapped now + if ((int) sess_lcp(hist, v.ids) < c.n || same) { // (same: the slots' rows past the live prompt may differ) + // the parked rows array after array: n rows of each, from an image of ids.size() rows each + CK(cudaDeviceSynchronize()); + const uint8_t* h = v.full->p; + for (auto& a : g_sess.full) { sess_rows(a, 0, c.n, const_cast(h), false); h += v.ids.size() * a.b; } + CK(cudaDeviceSynchronize()); + } + sess_tail(c.n, c.tail->p, false); + last_logits = c.logits; + how = "parked"; + v.used = ++g_sess.clock; + // the request continues that conversation (extends its last prompt): it leaves the parked set, its checkpoints + // up to n become the live ones; else (a sibling from a shared branch point) it stays parked, its branch + // checkpoints shared + std::vector keep; + for (auto& x : v.cks) if (x.n <= c.n && (x.n == c.n || x.kind == CK_BRANCH)) keep.push_back(x); + g_sess.live = keep; + if (v.prompt_n > 0 && (int) best >= v.prompt_n) { // its buffers to the spares (unless shared with the live) + Conv dead = std::move(v); + g_sess.parked.erase(g_sess.parked.begin() + pv); + sess_drop(std::move(dead.full)); + for (auto& x : dead.cks) sess_drop(std::move(x.tail)); + } + } else if (src < 0) { + how = "none"; + } + for (size_t i = g_sess.live.size(); i-- > 0;) // checkpoints past the read start are no longer the slots' state + if (g_sess.live[i].n > (int) best) { PinnedP t = g_sess.live[i].tail; g_sess.live.erase(g_sess.live.begin() + i); sess_drop(std::move(t)); } + g_sess.live_prompt = 0; // (sess_prompt_end sets it) + hist.assign(pr.begin(), pr.begin() + best); + std::fprintf(stderr, "[ink2] conversation cache: prompt %zu, read from %zu (%s)%s%s, %zu parked, %.0f of %zu MiB, %.0f ms\n", + pr.size(), best, how, g_sess.split > 0 ? (", branch point " + std::to_string(g_sess.split)).c_str() : "", + g_sess.note.c_str(), g_sess.parked.size(), sess_used() / 1048576.0, g_sess.budget >> 20, now_ms() - t0); + return best; +} + +// the prefill chunk at p0 of T tokens: ends at the branch point when it crosses it +int sess_chunk(int p0, int T) { return g_sess.on && g_sess.split > p0 && g_sess.split < p0 + T ? g_sess.split - p0 : T; } +// after the chunk ending at p: the branch checkpoint. CBA: the live conversation's checkpoints are never evicted +// (only parked conversations are); one branch point per request at most, they leave with it when it is parked +void sess_after_chunk(int p) { + if (!g_sess.on || p != g_sess.split) return; + vec lg(VOCAB); + CK(cudaMemcpy(lg.data(), E.logits, (size_t) VOCAB * 4, cudaMemcpyDeviceToHost)); + const double t0 = now_ms(); + if (sess_take(p, lg, CK_BRANCH)) std::fprintf(stderr, "[ink2] conversation cache: branch checkpoint at %d, %.0f ms\n", p, now_ms() - t0); +} +// FNV-1a of the logits: identity checks (serve mode has no logits dump) +unsigned long long sess_hash(const vec& lg) { + uint64_t h = 1469598103934665603ull; + for (float f : lg) { uint32_t u; std::memcpy(&u, &f, 4); h = (h ^ u) * 1099511628211ull; } + return (unsigned long long) h; +} +// the prompt read (lg: its last logits), before the first sampled token: the live prompt-end checkpoint +void sess_prompt_end(const std::vector& pr, const vec& lg) { + if (!g_sess.on) { // INK2_LOGITS_HASH=1: the hash without the cache too (the reference runs) + static const bool h = std::getenv("INK2_LOGITS_HASH") != nullptr; + if (h) std::fprintf(stderr, "[ink2] conversation cache: off, prompt end %zu, logits %016llx\n", pr.size(), sess_hash(lg)); + return; + } + const double t0 = now_ms(); + bool have = false; // a checkpoint at this very point already (the same prompt again, a restored one) + for (size_t i = g_sess.live.size(); i-- > 0;) { // earlier prompt ends / a restored end (prefixes of this) give way + if (g_sess.live[i].n == (int) pr.size()) { have = true; continue; } + if (g_sess.live[i].kind != CK_BRANCH) { PinnedP t = g_sess.live[i].tail; g_sess.live.erase(g_sess.live.begin() + i); sess_drop(std::move(t)); } + } + g_sess.note.clear(); + g_sess.live_prompt = have || sess_take((int) pr.size(), lg, CK_PROMPT) ? (int) pr.size() : 0; + std::fprintf(stderr, "[ink2] conversation cache: prompt end %zu checkpoint %.0f ms%s, %.0f MiB, logits %016llx\n", pr.size(), + now_ms() - t0, g_sess.note.c_str(), sess_used() / 1048576.0, sess_hash(lg)); +} diff --git a/engine/src/inkling2/ink2_vision.cuh b/engine/src/inkling2/ink2_vision.cuh new file mode 100644 index 00000000000..d128ba73822 --- /dev/null +++ b/engine/src/inkling2/ink2_vision.cuh @@ -0,0 +1,477 @@ +// src/inkling2/ink2_vision.cuh - Inkling-2's image input in strata-ink2: the ViT + projector, and the image rows of a +// prompt. Included by ink2_engine.cu inside its anonymous namespace, after the prompt path (Prefill, the expert pools). +// +// Model (checkpoint model.visual.*, transformers#51050 Inkling2VisionModel; checked in fp32 against it, see +// terminal/tools/inkling2/vision_oracle.py): +// * input: the picture's 2 x 2 native patches of 20 x 20 px per image token (ink2_image.hpp), a 1200-vector each; +// patch_embedding 1200 -> 1024 (no bias) + a learned 32 x 32 position table resampled bilinearly (align_corners +// False, edge-clamped) to the native patch grid; a class token (class + its position embedding) in front; +// LayerNorm (ln_pre). temporal_patch_size is unused for a still picture. +// * 23 pre-LayerNorm blocks, hidden 1024, 16 heads of 64, biased q/k/v/out, full attention within the picture, +// 2D axial RoPE (theta 1e4, 16 frequencies): channel pair j < 16 turns by (column + 1) * f_j, pair j >= 16 by +// (row + 1) * f_{j-16}, interleaved pairs; the class token sits at (0, 0). Layer scale on both branches +// (x + ls_1 * attn, x + ls_2 * mlp), MLP 1024 -> 4096 -> 1024 with the exact (erf) GELU. No final norm. +// * projector: the 4 patch states of a token concatenated (4096) -> proj_in 4096 -> GELU -> proj_out 2304, no bias. +// * the language model reads these rows in place of the image placeholders' rows AFTER its embedding norm (the +// reference masked_scatter's them into inputs_embeds = embed_norm(embed(ids))); positions stay plain token indices. +// +// Numerics: fp32 throughout (cuBLAS SGEMM, pedantic math, on fp32 copies of the BF16 weights made per use). +// CBA: attention as SGEMM over query chunks with the scores in VRAM, fine to a few thousand ViT tokens (a 1000-token +// picture: ~0.2 s) but 7 s at the cap (16k ViT tokens, 4096 image tokens); a flash-style TF32 / fp16 kernel if big +// pictures matter. One picture at a time, no batching across a prompt's pictures. +// +// Memory: nothing at load. At the first picture the weights are read into pinned host memory (634 MB BF16 + 6 MB +// fp32) and a cuBLAS handle is made (a few MiB of VRAM: 7.90 GiB used at 8 GiB text-only, 7.91 GiB after a picture). +// The weights are streamed to the GPU matrix by matrix during each encode. An encode's working VRAM (weight staging +// 100 MB + 20 KB per ViT token + 32 MB) comes from the tail of the NVFP4 expert pool when the experts are offloaded +// (those slots are evicted, then handed back empty: the pool refills them on demand), else from free VRAM beyond the +// margin, and goes back as the encode ends. +// CBA: the weights cross PCIe at every encode (~650 MB, about 90 ms on this box: most of a small picture's cost); a +// resident copy when VRAM is free (no offload) is the upgrade. +// +// Protocol (Hy4-Flash's 1.6b): GEN ... image= ... , one image= key per <|unused_200054|> of the ids in +// prompt order; the engine decodes the files, expands each placeholder to its rows x cols image tokens and encodes +// them before the prompt is read. INFO images=1 at the start says it can. +// +// Picture identity: an expanded image token is not 200054 in the prompt the engine keeps but a negative id made from +// the picture's key (its pixels' hash) and its offset in the picture (vis_id). Every prefix comparison of the serve +// loop and of the conversation cache (hist, live checkpoints, parked conversations, branch points) therefore sees two +// different pictures of the same size as different tokens: a state is reused only with the same pictures at the same +// places. Only the embedding lookup (forward_prefill) maps a negative id back to the placeholder's row, which the +// picture's row then replaces. +#pragma once + +constexpr int VH = 1024, VHEADS = 16, VHD = 64, VFF = 4096, VLAYERS = 23, VGRID = 32, VMERGE_IN = 4 * VH, VPROJ = 4096; +constexpr float VEPS = 1e-5f; +constexpr int IMAGE_TOKEN = 200054; // <|unused_200054|> (processor_config.json image_token) +constexpr size_t VSC = (size_t) 8 << 20; // scores / MLP scratch, floats (32 MB): attention in query chunks of VSC / S +// small fp32 tensors of one layer, offsets +constexpr int SM_BQ = 0, SM_BK = 1024, SM_BV = 2048, SM_BO = 3072, SM_B1 = 4096, SM_B2 = 8192, SM_LN1W = 9216, + SM_LN1B = 10240, SM_LN2W = 11264, SM_LN2B = 12288, SM_LS1 = 13312, SM_LS2 = 14336, SM_N = 15360; + +struct Vis { + int max_tokens = 4096; // --image-max-tokens: per picture (bigger ones are scaled down first) + std::string dump; // --dump-image-emb: the image rows of the last encode, float32 [n][2304] + // weights (pinned host, loaded at the first picture) + bool loaded = false; + uint16_t* wb = nullptr; // the BF16 matrices back to back + float* ws = nullptr; // the small fp32 tensors + size_t nb = 0, ns = 0; + size_t m_patch = 0, m_in = 0, m_out = 0, m_l[VLAYERS][6] = {}; // matrices (q k v o fc1 fc2) in wb + size_t s_pos = 0, s_cls = 0, s_lnw = 0, s_lnb = 0, s_l[VLAYERS] = {}; + cublasHandle_t cb = nullptr; + // the request + struct Span { int pos, n; uint64_t key; size_t row; }; + std::vector pics; + std::vector spans; // this prompt's pictures + float* emb = nullptr; // pinned [rows][H]: the image rows of this prompt + size_t emb_cap = 0; + bool pending = false; // the prompt being read has image rows to put in +} g_vis; + +double vis_ms() { + return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); +} + +bool vis_available() { return !g_is_gguf && E.ck && E.ck->st.tensors.count("model.visual.proj_out.weight"); } + +void vis_load() { + if (g_vis.loaded) return; + const double t0 = vis_ms(); + const std::string P = "model.visual.", B = P + "backbone."; + std::vector> mats = {{B + "embeddings.patch_embedding.weight", &g_vis.m_patch}, + {P + "proj_in.weight", &g_vis.m_in}, {P + "proj_out.weight", &g_vis.m_out}}; + const char* lm[6] = {"self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.out_proj", "mlp.c_fc", "mlp.c_proj"}; + for (int l = 0; l < VLAYERS; ++l) + for (int j = 0; j < 6; ++j) mats.push_back({B + "layers." + std::to_string(l) + "." + lm[j] + ".weight", &g_vis.m_l[l][j]}); + size_t nb = 0; + for (auto& m : mats) { + const StTensor& t = E.ck->t(m.first); + if (t.dtype != "BF16") { std::fprintf(stderr, "%s: %s, expected BF16\n", m.first.c_str(), t.dtype.c_str()); std::exit(1); } + *m.second = nb; + nb += (t.end - t.begin) / 2; + } + g_vis.ns = (size_t) VGRID * VGRID * VH + 3 * VH + (size_t) VLAYERS * SM_N; + CK(cudaHostAlloc((void**) &g_vis.wb, nb * 2, cudaHostAllocDefault)); + CK(cudaHostAlloc((void**) &g_vis.ws, g_vis.ns * 4, cudaHostAllocDefault)); + g_vis.nb = nb; + for (auto& m : mats) { + const auto b = E.ck->bytes(m.first); + std::memcpy(g_vis.wb + *m.second, b.data(), b.size()); + } + size_t o = 0; + auto put = [&](const std::string& name, size_t want) { + const vec v = E.ck->f32(name); + if (v.size() != want) { std::fprintf(stderr, "%s: %zu values, expected %zu\n", name.c_str(), v.size(), want); std::exit(1); } + std::memcpy(g_vis.ws + o, v.data(), want * 4); + o += want; + }; + g_vis.s_pos = o; put(B + "embeddings.position_embedding", (size_t) VGRID * VGRID * VH); + g_vis.s_cls = o; put(B + "embeddings.class_embedding", VH); + { // the class token's input: class_embedding + cls_position_embedding + const vec c = E.ck->f32(B + "embeddings.cls_position_embedding"); + for (int i = 0; i < VH; ++i) g_vis.ws[g_vis.s_cls + i] += c[i]; + } + g_vis.s_lnw = o; put(B + "ln_pre.weight", VH); + g_vis.s_lnb = o; put(B + "ln_pre.bias", VH); + const char* sm[12] = {"self_attn.q_proj.bias", "self_attn.k_proj.bias", "self_attn.v_proj.bias", "self_attn.out_proj.bias", + "mlp.c_fc.bias", "mlp.c_proj.bias", "ln_1.weight", "ln_1.bias", "ln_2.weight", "ln_2.bias", + "ls_1.gamma", "ls_2.gamma"}; + for (int l = 0; l < VLAYERS; ++l) { + g_vis.s_l[l] = o; + for (int j = 0; j < 12; ++j) put(B + "layers." + std::to_string(l) + "." + sm[j], j == 4 ? VFF : VH); + } + CK(cublasCreate(&g_vis.cb) == CUBLAS_STATUS_SUCCESS ? cudaSuccess : cudaErrorUnknown); + cublasSetStream(g_vis.cb, cudaStreamPerThread); + cublasSetMathMode(g_vis.cb, CUBLAS_PEDANTIC_MATH); + g_vis.loaded = true; + std::fprintf(stderr, "[vision] weights read: %.0f MB BF16 + %.1f MB fp32 in pinned host memory, %.2f s\n", nb * 2 / 1e6, + g_vis.ns * 4 / 1e6, (vis_ms() - t0) / 1000); +} + +// ---------------------------------------------------------------------------------------------------------------- kernels +__global__ void kv_bf16_f32(const uint16_t* __restrict__ s, float* __restrict__ d, size_t n) { + for (size_t i = blockIdx.x * (size_t) blockDim.x + threadIdx.x; i < n; i += (size_t) gridDim.x * blockDim.x) + d[i] = __uint_as_float((uint32_t) s[i] << 16); +} +__device__ __forceinline__ float kv_block_sum(float v, float* sh) { // blockDim 256 + v = warp_sum(v); + if ((threadIdx.x & 31) == 0) sh[threadIdx.x >> 5] = v; + __syncthreads(); + float t = threadIdx.x < 8 ? sh[threadIdx.x] : 0.0f; + if (threadIdx.x < 32) t = warp_sum(t); + if (threadIdx.x == 0) sh[8] = t; + __syncthreads(); + const float r = sh[8]; + __syncthreads(); + return r; +} +// LayerNorm over rows of 1024, block 256 +__global__ void kv_ln(const float* __restrict__ x, const float* __restrict__ w, const float* __restrict__ b, float* __restrict__ y) { + __shared__ float sh[9]; + const float* r = x + (size_t) blockIdx.x * VH; + float v[4], s = 0.0f; + for (int j = 0; j < 4; ++j) { v[j] = r[threadIdx.x + 256 * j]; s += v[j]; } + const float mean = kv_block_sum(s, sh) / VH; + float q = 0.0f; + for (int j = 0; j < 4; ++j) { v[j] -= mean; q += v[j] * v[j]; } + const float inv = rsqrtf(kv_block_sum(q, sh) / VH + VEPS); + float* o = y + (size_t) blockIdx.x * VH; + for (int j = 0; j < 4; ++j) { const int i = threadIdx.x + 256 * j; o[i] = v[j] * inv * w[i] + b[i]; } +} +// softmax of rows of n, block 256 +__global__ void kv_softmax(float* __restrict__ s, int n) { + __shared__ float sh[9]; + float* r = s + (size_t) blockIdx.x * n; + float m = -INFINITY; + for (int i = threadIdx.x; i < n; i += 256) m = fmaxf(m, r[i]); + m = warp_max(m); + if ((threadIdx.x & 31) == 0) sh[threadIdx.x >> 5] = m; + __syncthreads(); + if (threadIdx.x == 0) { float t = sh[0]; for (int k = 1; k < 8; ++k) t = fmaxf(t, sh[k]); sh[8] = t; } + __syncthreads(); + m = sh[8]; + __syncthreads(); + float z = 0.0f; + for (int i = threadIdx.x; i < n; i += 256) { const float e = expf(r[i] - m); r[i] = e; z += e; } + const float inv = 1.0f / kv_block_sum(z, sh); + for (int i = threadIdx.x; i < n; i += 256) r[i] *= inv; +} +// (row, col) of native patch i (block order: 2 x 2 per token, tokens in raster order over `cols` tokens a row) +__device__ __forceinline__ void kv_patch_rc(int i, int cols, int& row, int& col) { + const int t = i >> 2; + row = (t / cols) * 2 + ((i >> 1) & 1); + col = (t % cols) * 2 + (i & 1); +} +// one axis of the position table's bilinear resampling (align_corners False, edge clamp), as transformers' +// _interpolation_axis_taps_weights +__device__ __forceinline__ void kv_taps(int idx, int size, int& t0, int& t1, float& w0, float& w1) { + const float src = ((float) idx + 0.5f) * (float) VGRID / (float) size - 0.5f, f = floorf(src); + t0 = min(max((int) f, 0), VGRID - 1); + t1 = min(max((int) f + 1, 0), VGRID - 1); + w0 = fmaxf(1.0f - fabsf(src - f), 0.0f); + w1 = fmaxf(1.0f - fabsf(src - f - 1.0f), 0.0f); +} +// x[0] = class token; x[1 + i] += position embedding of patch i. grid N + 1, block 256 +__global__ void kv_embed(float* __restrict__ x, const float* __restrict__ pos, const float* __restrict__ cls, int rows, int cols) { + if (blockIdx.x == 0) { + for (int d = threadIdx.x; d < VH; d += 256) x[d] = cls[d]; + return; + } + int r, c, h0, h1, w0i, w1i; + float hw0, hw1, ww0, ww1; + kv_patch_rc(blockIdx.x - 1, cols, r, c); + kv_taps(r, 2 * rows, h0, h1, hw0, hw1); + kv_taps(c, 2 * cols, w0i, w1i, ww0, ww1); + const float* p00 = pos + (size_t) (h0 * VGRID + w0i) * VH; + const float* p01 = pos + (size_t) (h0 * VGRID + w1i) * VH; + const float* p10 = pos + (size_t) (h1 * VGRID + w0i) * VH; + const float* p11 = pos + (size_t) (h1 * VGRID + w1i) * VH; + float* o = x + (size_t) blockIdx.x * VH; + for (int d = threadIdx.x; d < VH; d += 256) + o[d] += p00[d] * (hw0 * ww0) + p01[d] * (hw0 * ww1) + p10[d] * (hw1 * ww0) + p11[d] * (hw1 * ww1); +} +// q, k += bias, then the 2D RoPE (interleaved pairs; pair j < 16: column, j >= 16: row; class token at (0, 0)). +// grid S, block 512 (16 heads x 32 pairs) +__global__ void kv_qk_rope(float* __restrict__ q, float* __restrict__ k, float* __restrict__ v, const float* __restrict__ bq, + const float* __restrict__ bk, const float* __restrict__ bv, int cols) { + const int s = blockIdx.x, hd = threadIdx.x >> 5, j = threadIdx.x & 31; + int r = -1, c = -1; + if (s > 0) kv_patch_rc(s - 1, cols, r, c); + const float p = (float) (j < 16 ? c + 1 : r + 1); + const int jj = j & 15; + const float inv = 1.0f / powf(10000.0f, (float) (2 * jj) / 32.0f); + const float a = p * inv, cs = cosf(a), sn = sinf(a); + const size_t i = (size_t) s * VH + hd * VHD + 2 * j; + float x0 = q[i] + bq[hd * VHD + 2 * j], x1 = q[i + 1] + bq[hd * VHD + 2 * j + 1]; + q[i] = x0 * cs - x1 * sn; + q[i + 1] = x1 * cs + x0 * sn; + x0 = k[i] + bk[hd * VHD + 2 * j]; + x1 = k[i + 1] + bk[hd * VHD + 2 * j + 1]; + k[i] = x0 * cs - x1 * sn; + k[i + 1] = x1 * cs + x0 * sn; + v[i] += bv[hd * VHD + 2 * j]; + v[i + 1] += bv[hd * VHD + 2 * j + 1]; +} +// x += ls * (y + b), rows of 1024 +__global__ void kv_resid(float* __restrict__ x, const float* __restrict__ y, const float* __restrict__ b, + const float* __restrict__ ls, size_t n) { + for (size_t i = blockIdx.x * (size_t) blockDim.x + threadIdx.x; i < n; i += (size_t) gridDim.x * blockDim.x) { + const int d = (int) (i % VH); + x[i] += ls[d] * (y[i] + b[d]); + } +} +// y = gelu(y + b) (exact erf form), rows of `w` (b may be null) +__global__ void kv_gelu(float* __restrict__ y, const float* __restrict__ b, int w, size_t n) { + for (size_t i = blockIdx.x * (size_t) blockDim.x + threadIdx.x; i < n; i += (size_t) gridDim.x * blockDim.x) { + const float v = y[i] + (b ? b[i % w] : 0.0f); + y[i] = 0.5f * v * (1.0f + erff(v * 0.70710678118654752f)); + } +} +unsigned kv_grid(size_t n) { return (unsigned) std::min((n + 255) / 256, 8192); } + +// -------------------------------------------------------------------------------------------------- the encode's VRAM +struct VisArena { uint8_t* p = nullptr; size_t bytes = 0; int pool_saved = -1; }; +void vis_graphs_drop() { // the decode graph and the verify graphs bake the slot counts in (as pool_resize) + if (E.exec) { CK(cudaGraphExecDestroy(E.exec)); E.exec = nullptr; } + for (auto& x : g_vexec) if (x) { CK(cudaGraphExecDestroy(x)); x = nullptr; } +} +std::string vis_arena_get(VisArena& a, size_t bytes) { + CK(cudaDeviceSynchronize()); + a.bytes = bytes; + if (E.offload) { // the NVFP4 pool's last slots, evicted (as pool_resize shrinking, without giving the memory up) + const size_t eb = ex_bytes(0); + const int k = (int) ((bytes + eb - 1) / eb), ns = E.nslot_nv, n = ns - k; + if (n < 2 * FETCH_MAX) + return "the picture needs " + std::to_string(bytes >> 20) + " MiB of VRAM for its encoder, more than the expert pool can lend"; + if (E.cpu) promote_cancel(); + k_pool_evict<<<(k + 255) / 256, 256>>>(E.owner_nv, E.slot_of, E.tabA, E.tabB, E.stamp_nv, n, ns); + CK(cudaDeviceSynchronize()); + a.pool_saved = ns; + E.nslot_nv = n; + vis_graphs_drop(); + a.p = E.pool_nv + (size_t) n * eb; + std::fprintf(stderr, "[vision] %zu MiB lent by the expert pool (%d NVFP4 slots)\n", bytes >> 20, k); + return ""; + } + const size_t fr = vram_free(), keep = vram_keep(); + if (fr < bytes + keep || cudaMalloc((void**) &a.p, bytes) != cudaSuccess) { + (void) cudaGetLastError(); + a.p = nullptr; + return "the picture needs " + std::to_string(bytes >> 20) + " MiB of VRAM for its encoder, " + + std::to_string(fr > keep ? (fr - keep) >> 20 : 0) + " MiB are free"; + } + return ""; +} +void vis_arena_put(VisArena& a) { + CK(cudaDeviceSynchronize()); + if (a.pool_saved >= 0) { // the slots come back empty (owner -1, stamp 0): the pool fills them on demand + E.nslot_nv = a.pool_saved; + vis_graphs_drop(); + } else if (a.p) { + CK(cudaFree(a.p)); + } + a = VisArena(); +} + +// -------------------------------------------------------------------------------------------------------- the ViT +// one picture -> its rows x cols image rows [n][H] (host) +std::string vis_run(const ink2img::Picture& pic, float* out) { + vis_load(); + const int NT = pic.rows * pic.cols, N = 4 * NT, S = N + 1; + const size_t SH = (size_t) S * VH, WMAX = (size_t) VPROJ * VMERGE_IN, WS_BYTES = (size_t) 4 << 20; + auto al = [](size_t b) { return (b + 255) / 256 * 256; }; + const size_t b_small = al(g_vis.ns * 4), b_stage = al(WMAX * 2), b_wf = al(WMAX * 4), b_act = al((5 * SH + VSC) * 4); + VisArena A; + const size_t free0 = vram_free(); + std::string err = vis_arena_get(A, b_small + b_stage + b_wf + WS_BYTES + b_act); + if (!err.empty()) return err; + const double t0 = vis_ms(); + uint8_t* p = A.p; + float* sm = (float*) p; p += b_small; + uint16_t* stg = (uint16_t*) p; p += b_stage; + float* wf = (float*) p; p += b_wf; + void* cws = p; p += WS_BYTES; + float* x = (float*) p; + float *y = x + SH, *q = y + SH, *k = q + SH, *v = k + SH, *sc = v + SH; + cublasSetWorkspace(g_vis.cb, cws, WS_BYTES); + const cudaStream_t st = cudaStreamPerThread; + CK(cudaMemcpyAsync(sm, g_vis.ws, g_vis.ns * 4, cudaMemcpyHostToDevice, st)); + size_t h2d = g_vis.ns * 4; + auto wmat = [&](size_t off, size_t n, float* dst) { // a BF16 matrix -> fp32 at dst + CK(cudaMemcpyAsync(stg, g_vis.wb + off, n * 2, cudaMemcpyHostToDevice, st)); + kv_bf16_f32<<>>(stg, dst, n); + h2d += n * 2; + }; + const float one = 1.0f, zero = 0.0f; + bool ok = true; + // Y[T][n] = X[T][K] . W[n][K]^T (row-major; ldw: W's row stride) + auto gemm = [&](int T, int n, int K, const float* X, int ldx, const float* W, int ldw, float* Y, int ldy, float alpha) { + if (cublasSgemm(g_vis.cb, CUBLAS_OP_T, CUBLAS_OP_N, n, T, K, &alpha, W, ldw, X, ldx, &zero, Y, ldy) != CUBLAS_STATUS_SUCCESS) + ok = false; + }; + // the patches -> x[1..N], the class token at x[0], the position table, ln_pre + CK(cudaMemcpyAsync(k, pic.patches.data(), (size_t) N * ink2img::PIN * 4, cudaMemcpyHostToDevice, st)); + h2d += (size_t) N * ink2img::PIN * 4; + wmat(g_vis.m_patch, (size_t) VH * ink2img::PIN, wf); + gemm(N, VH, ink2img::PIN, k, ink2img::PIN, wf, ink2img::PIN, x + VH, VH, one); + kv_embed<<>>(x, sm + g_vis.s_pos, sm + g_vis.s_cls, pic.rows, pic.cols); + kv_ln<<>>(x, sm + g_vis.s_lnw, sm + g_vis.s_lnb, y); + std::swap(x, y); + const int qc_max = (int) std::max(1, std::min(S, VSC / S)), mc = (int) (VSC / VFF); + const size_t M1 = (size_t) VH * VH, M4 = (size_t) VFF * VH; + for (int l = 0; l < VLAYERS; ++l) { + const float* s = sm + g_vis.s_l[l]; + float *wq = wf, *wk = wf + M1, *wv = wf + 2 * M1, *wo = wf + 3 * M1, *w1 = wf + 4 * M1, *w2 = w1 + M4; + wmat(g_vis.m_l[l][0], M1, wq); wmat(g_vis.m_l[l][1], M1, wk); wmat(g_vis.m_l[l][2], M1, wv); + wmat(g_vis.m_l[l][3], M1, wo); wmat(g_vis.m_l[l][4], M4, w1); wmat(g_vis.m_l[l][5], M4, w2); + kv_ln<<>>(x, s + SM_LN1W, s + SM_LN1B, y); + gemm(S, VH, VH, y, VH, wq, VH, q, VH, one); + gemm(S, VH, VH, y, VH, wk, VH, k, VH, one); + gemm(S, VH, VH, y, VH, wv, VH, v, VH, one); + kv_qk_rope<<>>(q, k, v, s + SM_BQ, s + SM_BK, s + SM_BV, pic.cols); + for (int h = 0; h < VHEADS; ++h) // attention -> y (the heads' outputs side by side) + for (int q0 = 0; q0 < S; q0 += qc_max) { + const int qc = std::min(qc_max, S - q0); + gemm(qc, S, VHD, q + (size_t) q0 * VH + h * VHD, VH, k + h * VHD, VH, sc, S, 0.125f); // 1 / sqrt(64) + kv_softmax<<>>(sc, S); + if (cublasSgemm(g_vis.cb, CUBLAS_OP_N, CUBLAS_OP_N, VHD, qc, S, &one, v + h * VHD, VH, sc, S, &zero, + y + (size_t) q0 * VH + h * VHD, VH) != CUBLAS_STATUS_SUCCESS) ok = false; + } + gemm(S, VH, VH, y, VH, wo, VH, q, VH, one); + kv_resid<<>>(x, q, s + SM_BO, s + SM_LS1, SH); + kv_ln<<>>(x, s + SM_LN2W, s + SM_LN2B, y); + for (int r0 = 0; r0 < S; r0 += mc) { + const int m = std::min(mc, S - r0); + gemm(m, VFF, VH, y + (size_t) r0 * VH, VH, w1, VH, sc, VFF, one); + kv_gelu<<>>(sc, s + SM_B1, VFF, (size_t) m * VFF); + gemm(m, VH, VFF, sc, VFF, w2, VFF, q + (size_t) r0 * VH, VH, one); + } + kv_resid<<>>(x, q, s + SM_B2, s + SM_LS2, SH); + } + // projector: the 4 patch rows of a token side by side are x[1 + 4t .. 1 + 4t + 3] (block order), already contiguous + wmat(g_vis.m_in, (size_t) VPROJ * VMERGE_IN, wf); + gemm(NT, VPROJ, VMERGE_IN, x + VH, VMERGE_IN, wf, VMERGE_IN, q, VPROJ, one); + kv_gelu<<>>(q, nullptr, VPROJ, (size_t) NT * VPROJ); + wmat(g_vis.m_out, (size_t) H * VPROJ, wf); + gemm(NT, H, VPROJ, q, VPROJ, wf, VPROJ, k, H, one); + CK(cudaMemcpyAsync(out, k, (size_t) NT * H * 4, cudaMemcpyDeviceToHost, st)); + CK(cudaStreamSynchronize(st)); + const double t1 = vis_ms(); + const size_t arena = A.bytes; + vis_arena_put(A); + if (!ok) return "cuBLAS failed in the picture encoder"; + const size_t free1 = vram_free(); + std::fprintf(stderr, "[vision] %dx%d px (decoded %dx%d) -> %d x %d image tokens, ViT %d tokens: %.0f ms, %.0f MiB VRAM, " + "%.0f MB weights over PCIe; VRAM free %.0f MiB before, %.0f after\n", pic.w, pic.h, pic.src_w, pic.src_h, + pic.rows, pic.cols, S, t1 - t0, arena / 1048576.0, h2d / 1e6, free0 / 1048576.0, free1 / 1048576.0); + return ""; +} + +// ------------------------------------------------------------------------------------------------------- the prompt +// the prompt id of image token j of the picture with key k: negative (never a vocabulary id), 31 bits of a mix of both +// CBA: two different pictures match only if all 31-bit ids of the shared span collide (~2^-31 per token) +int vis_id(uint64_t k, int j) { + uint64_t x = k ^ (0x9e3779b97f4a7c15ull * (uint64_t) (j + 1)); + x ^= x >> 33; x *= 0xff51afd7ed558ccdull; x ^= x >> 33; x *= 0xc4ceb9fe1a85ec53ull; x ^= x >> 33; + return -1 - (int) (x & 0x3fffffff); +} +// This prompt's pictures: each IMAGE_TOKEN of `ids` (one per picture, prompt order) becomes its rows x cols image +// tokens. `paths` empty and no placeholder: a text prompt (nothing to do). "" or the error. +std::string vis_prepare(std::vector& ids, const std::vector& paths, bool pixels = false) { + g_vis.spans.clear(); + g_vis.pics.clear(); + g_vis.pending = false; + const size_t nph = (size_t) std::count(ids.begin(), ids.end(), IMAGE_TOKEN); + if (paths.empty() && nph == 0) return ""; + if (!vis_available()) return "this model has no image encoder (model.visual.*; a GGUF file is text only here)"; + if (nph != paths.size()) + return std::to_string(paths.size()) + " picture(s) for " + std::to_string(nph) + " image placeholder(s) in the prompt"; + g_vis.pics.resize(paths.size()); + for (size_t i = 0; i < paths.size(); ++i) { + const std::string e = pixels ? ink2img::load_pixels(paths[i], g_vis.pics[i]) + : ink2img::load_picture(paths[i], g_vis.max_tokens, g_vis.pics[i]); + if (!e.empty()) return e; + } + std::vector out; + out.reserve(ids.size()); + size_t k = 0, row = 0; + for (int t : ids) { + if (t != IMAGE_TOKEN) { out.push_back(t); continue; } + const ink2img::Picture& p = g_vis.pics[k++]; + const int n = p.rows * p.cols; + g_vis.spans.push_back({(int) out.size(), n, p.key, row}); + row += (size_t) n; + for (int j = 0; j < n; ++j) out.push_back(vis_id(p.key, j)); + } + ids.swap(out); + return ""; +} + +// Encodes the pictures whose rows are read from `start` on (the others are in the reused prefix). "" or the error. +std::string vis_encode(size_t start) { + if (g_vis.spans.empty()) return ""; + size_t rows = 0; + for (const auto& s : g_vis.spans) rows += (size_t) s.n; + if (rows > g_vis.emb_cap) { + if (g_vis.emb) CK(cudaFreeHost(g_vis.emb)); + CK(cudaHostAlloc((void**) &g_vis.emb, rows * H * 4, cudaHostAllocDefault)); + g_vis.emb_cap = rows; + } + for (size_t i = 0; i < g_vis.spans.size(); ++i) { + const Vis::Span& s = g_vis.spans[i]; + if ((size_t) (s.pos + s.n) <= start) continue; + const std::string e = vis_run(g_vis.pics[i], g_vis.emb + s.row * H); + if (!e.empty()) return e; + } + g_vis.pics.clear(); // (the patches: up to tens of MB a picture) + if (!g_vis.dump.empty()) { + if (FILE* f = std::fopen(g_vis.dump.c_str(), "wb")) { + std::fwrite(g_vis.emb, 4, rows * H, f); + std::fclose(f); + } + } + g_vis.pending = true; + return ""; +} + +// forward_prefill_device: the chunk [pos0, pos0 + T)'s image rows over its normed embeddings (PF.h) +void vis_inject(int T, int pos0) { + if (!g_vis.pending || pos0 < 0) return; + for (const auto& s : g_vis.spans) { + const int a = std::max(pos0, s.pos), b = std::min(pos0 + T, s.pos + s.n); + if (a >= b) continue; + CK(cudaMemcpyAsync(PF.h + (size_t) (a - pos0) * H, g_vis.emb + (s.row + (size_t) (a - s.pos)) * H, + (size_t) (b - a) * H * 4, cudaMemcpyHostToDevice, cudaStreamPerThread)); + } +} + +// --vis-pixels FILE: the ViT alone on the processor's pixel tensor (no language model loaded), rows to --dump-image-emb +int vis_cli_pixels(const std::string& path) { + std::vector ids = {IMAGE_TOKEN}; + std::string e = vis_prepare(ids, {path}, true); + if (e.empty()) e = vis_encode(0); + if (!e.empty()) { std::fprintf(stderr, "%s\n", e.c_str()); return 1; } + std::printf("vision: %zu image rows%s%s\n", ids.size(), g_vis.dump.empty() ? "" : " written to ", g_vis.dump.c_str()); + return 0; +} diff --git a/engine/src/inkling2/ink2_wmma_hip.cuh b/engine/src/inkling2/ink2_wmma_hip.cuh new file mode 100644 index 00000000000..ff38d66008e --- /dev/null +++ b/engine/src/inkling2/ink2_wmma_hip.cuh @@ -0,0 +1,180 @@ +#pragma once + +#include +#include +#include + +#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || \ + defined(__gfx1150__) || defined(__gfx1151__) || defined(__gfx1152__) +#define INK2_WMMA_GFX11 1 +#define INK2_WMMA_GFX12 0 +#elif defined(__gfx1200__) || defined(__gfx1201__) +#define INK2_WMMA_GFX11 0 +#define INK2_WMMA_GFX12 1 +#else +#define INK2_WMMA_GFX11 0 +#define INK2_WMMA_GFX12 0 +#endif + +namespace ink2_wmma { + +struct matrix_a {}; +struct matrix_b {}; +struct accumulator {}; +struct row_major {}; +struct col_major {}; +enum layout_t { mem_row_major, mem_col_major }; + +static_assert(sizeof(__half) == sizeof(_Float16), "expected 16-bit __half"); +static_assert(sizeof(unsigned short) == sizeof(_Float16), "expected 16-bit _Float16"); + +using v16h = _Float16 __attribute__((ext_vector_type(16))); +using v8h = _Float16 __attribute__((ext_vector_type(8))); +using v8f = float __attribute__((ext_vector_type(8))); + +__device__ __forceinline__ _Float16 to_f16(__half h) { + return __builtin_bit_cast(_Float16, __half_as_ushort(h)); +} + +template +struct fragment; + +#if INK2_WMMA_GFX11 +template +struct fragment { + v16h v; +}; + +template +struct fragment { + v16h v; +}; +#elif INK2_WMMA_GFX12 +template +struct fragment { + v8h v; +}; + +template +struct fragment { + v8h v; +}; +#else +template +struct fragment { + float v[16]; +}; + +template +struct fragment { + float v[16]; +}; +#endif + +template <> +struct fragment { + static constexpr int num_elements = 8; + float x[num_elements]; +}; + +__device__ __forceinline__ void fill_fragment(fragment& f, float val) { +#pragma unroll + for (int i = 0; i < 8; ++i) f.x[i] = val; +} + +__device__ __forceinline__ void load_matrix_sync(fragment& f, + const __half* src, unsigned ldm) { + const int lane = threadIdx.x & 31; + const int sub = lane & 15; +#if INK2_WMMA_GFX11 + __builtin_memcpy(&f.v, src + (size_t) sub * ldm, sizeof(v16h)); +#elif INK2_WMMA_GFX12 + const int hi = lane >> 4; + __builtin_memcpy(&f.v, src + (size_t) sub * ldm + 8 * hi, sizeof(v8h)); +#else + const __half* row = src + (size_t) sub * ldm; +#pragma unroll + for (int k = 0; k < 16; ++k) f.v[k] = __half2float(row[k]); +#endif +} + +__device__ __forceinline__ void load_matrix_sync(fragment& f, + const __half* src, unsigned ldm) { + const int lane = threadIdx.x & 31; + const int sub = lane & 15; +#if INK2_WMMA_GFX11 + __builtin_memcpy(&f.v, src + (size_t) sub * ldm, sizeof(v16h)); +#elif INK2_WMMA_GFX12 + const int hi = lane >> 4; + __builtin_memcpy(&f.v, src + (size_t) sub * ldm + 8 * hi, sizeof(v8h)); +#else + const __half* col = src + (size_t) sub * ldm; +#pragma unroll + for (int k = 0; k < 16; ++k) f.v[k] = __half2float(col[k]); +#endif +} + +__device__ __forceinline__ void load_matrix_sync(fragment& f, + const __half* src, unsigned ldm) { + const int lane = threadIdx.x & 31; + const int sub = lane & 15; +#if INK2_WMMA_GFX11 +#pragma unroll + for (int k = 0; k < 16; ++k) f.v[k] = to_f16(src[(size_t) k * ldm + sub]); +#elif INK2_WMMA_GFX12 + const int k0 = (lane >> 4) * 8; +#pragma unroll + for (int k = 0; k < 8; ++k) f.v[k] = to_f16(src[(size_t) (k0 + k) * ldm + sub]); +#else +#pragma unroll + for (int k = 0; k < 16; ++k) f.v[k] = __half2float(src[(size_t) k * ldm + sub]); +#endif +} + +template +__device__ __forceinline__ void mma_sync(fragment& d, + const fragment& a, + const fragment& b, + const fragment& c) { +#if INK2_WMMA_GFX11 + v8f cv; + __builtin_memcpy(&cv, c.x, sizeof(cv)); + cv = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a.v, b.v, cv); + __builtin_memcpy(d.x, &cv, sizeof(cv)); +#elif INK2_WMMA_GFX12 + v8f cv; + __builtin_memcpy(&cv, c.x, sizeof(cv)); + cv = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a.v, b.v, cv); + __builtin_memcpy(d.x, &cv, sizeof(cv)); +#else + const int hi = (threadIdx.x & 31) >> 4; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const int row = 2 * i + hi; + float sum = c.x[i]; +#pragma unroll + for (int k = 0; k < 16; ++k) sum = fmaf(__shfl(a.v[k], row), b.v[k], sum); + d.x[i] = sum; + } +#endif +} + +__device__ __forceinline__ void store_matrix_sync(float* dst, + const fragment& f, + unsigned ldm, layout_t layout) { + const int lane = threadIdx.x & 31; + const int sub = lane & 15; + const int hi = lane >> 4; +#pragma unroll + for (int i = 0; i < 8; ++i) { +#if INK2_WMMA_GFX12 + const int row = 8 * hi + i; +#else + const int row = 2 * i + hi; +#endif + if (layout == mem_row_major) dst[(size_t) row * ldm + sub] = f.x[i]; + else dst[(size_t) sub * ldm + row] = f.x[i]; + } +} + +} diff --git a/engine/src/inkling2/ink2ref.cu b/engine/src/inkling2/ink2ref.cu new file mode 100644 index 00000000000..9293798df2e --- /dev/null +++ b/engine/src/inkling2/ink2ref.cu @@ -0,0 +1,693 @@ +// src/inkling2/ink2ref.cu - NEW-MODELS-PLAN.md phase T1 for Inkling-2-Mini (thinkingmachines/Inkling-2-Mini, +// model_type inkling2_loop): the reference path, exactness first. One GPU, every weight resident in VRAM in its +// checkpoint form (BF16 dense, NVFP4 experts on layers 0-19, MXFP8 experts on layers 20-23: ~18 GiB), one token at a +// time (the prompt too), fp32 activations. The GPU only runs the matrix-vector products (plain kernels of this file); +// everything else is host fp32, written to mirror the transformers reference (PR #51050, +// models/inkling2_loop/modeling_inkling2_loop.py) line for line, so a mismatch points at one operation. +// No expert cache, no batching, no MTP, no vision. Checked against that reference by tools/inkling2/ (per layer +// application outputs, logits, greedy tokens). +// +// CBA: host-side attention and convolutions, one cudaMemcpy pair per GEMV - a reference, ~0.1-0.3 s per token; the +// engine path (T2) moves all of it onto the GPU. +// +// The forward pass (per token): +// h = rms(embed[tok]) * embed_norm; B = [] (B: "block states", snapshots of h) +// layers 0-5, then the loop layers 6-17 (pass 0), then passes 1 and 2 of 6-17 restarted from the pre-loop (h, B) and +// fed "messages" from the previous pass, then layers 18-23; a layer whose index is a multiple of 6 appends its +// INPUT to B. Each pass of a loop layer has its own KV cache and convolution states (48 slots in all). +// h = attnres(final_query, B, h); logits = softcap30(unembed (rms(h) * norm)) +// One layer L (full attention when L % 6 == 5, else sliding window 1024): +// a = attnres(attention_input[L], B, h) (absent for L 0; three queries q/k/v on full layers) +// [loop passes 1-2: a = message_gate(a, message)] x = rms(a) * norm (q/k/v norms on full layers) +// att = attention(xq, xk, xv); att = shortconv(att) +// r = (L % 6 == 0) ? att : h + att (on a block boundary the residual restarts; B gets h) +// m = attnres(mlp_input[L], B, r) [loop passes 1-2: message_gate(m, message)] +// out = r + shortconv(MoE(rms(m) * mlp_norm)) +// +// Usage: strata-ink2ref --model DIR (--tokens 1,2,3 | --tokens-file F) [--n 16] [--dump-layers FILE] [--dump-logits FILE] +// [--pos-offset N] +// --dump-layers writes every position's 48 layer-application outputs (f32, [pos][48][2304]); --dump-logits every +// position's logits (f32, [pos][200058]); prints the greedy continuation ("gen: id id ..."). +#include "../image/vae/safetensors_lite.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using vec = std::vector; +using strata::image::StFile; +using strata::image::StTensor; + +// config.json (text_config) of Inkling-2-Mini. CBA: fixed geometry, read from config.json if a second size ships. +constexpr int H = 2304, NL = 24, NQ = 24, NKV = 8, HD = 128, NREP = NQ / NKV, DREL = 16, EXTENT = 1024, WINDOW = 1024; +constexpr int NE = 128, TOPK = 8, FF = 1152, KC = 4, VOCAB = 200058; +constexpr int LOOP_BEGIN = 6, LOOP_END = 18, NLOOP = LOOP_END - LOOP_BEGIN, PASSES = 3, BLOCK = 6; +constexpr int NCALLS = NL + (PASSES - 1) * NLOOP; // 48 layer applications +constexpr int MXFP8_FIRST = 20; // hf_quant_config.json: experts of layers 20-23 are MXFP8 +constexpr float EPS = 1e-6f, QK_CLIP = 22.627416997969522f, REL_CLIP = 8.0f, LOG_ALPHA = 0.1f, LOG_FLOOR = 8192.0f; +constexpr float GATE_CAP = 4.0f, UP_CAP = 25.0f, ROUTE_SCALE = 8.0f, LOGIT_CAP = 30.0f; + +bool full_layer(int L) { return L % BLOCK == BLOCK - 1; } // local_layer_ids omit 5, 11, 17, 23 + +#define CK(x) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { \ + std::fprintf(stderr, "CUDA %s at %s:%d\n", cudaGetErrorString(e_), __FILE__, __LINE__); std::exit(1); } } while (0) + +// --------------------------------------------------------------------------------------------------------------------- +// GPU: the matrix-vector products, one warp per output row, fp32 accumulation. + +__device__ __forceinline__ float bf16f(uint16_t b) { return __uint_as_float(((uint32_t) b) << 16); } + +__device__ __forceinline__ float e4m3f(uint8_t v) { // float8_e4m3fn: bias 7, no infinities, S.1111.111 = NaN + const int e = (v >> 3) & 15, m = v & 7; + float r = e == 0 ? (float) m * 0.001953125f /* m/8 * 2^-6 */ : ldexpf(1.0f + (float) m * 0.125f, e - 7); + if (e == 15 && m == 7) r = __int_as_float(0x7fc00000); + return (v & 0x80) ? -r : r; +} + +__constant__ float kE2M1[16] = {0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f, + -0.0f, -0.5f, -1.0f, -1.5f, -2.0f, -3.0f, -4.0f, -6.0f}; + +__device__ __forceinline__ float warp_sum(float a) { + for (int o = 16; o; o >>= 1) a += __shfl_xor_sync(0xffffffffu, a, o); + return a; +} + +__global__ void gemv_bf16(const uint16_t* W, const float* x, float* y, int N, int K) { + const int row = blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32, lane = threadIdx.x & 31; + if (row >= N) return; + const uint16_t* w = W + (size_t) row * K; + float acc = 0.0f; + for (int k = lane; k < K; k += 32) acc += bf16f(w[k]) * x[k]; + acc = warp_sum(acc); + if (!lane) y[row] = acc; +} + +// NVFP4 (ModelOpt layout of this checkpoint): byte b of a row holds columns 2b (low nibble) and 2b+1 (high nibble); +// one e4m3 scale per 16 columns; one fp32 factor per expert (amax / outer_scale_denominator), applied to the sum. +__global__ void gemv_nvfp4(const uint8_t* W, const uint8_t* S, float factor, const float* x, float* y, int N, int K) { + const int row = blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32, lane = threadIdx.x & 31; + if (row >= N) return; + const uint8_t* w = W + (size_t) row * (K / 2); + const uint8_t* s = S + (size_t) row * (K / 16); + float acc = 0.0f; + for (int b = lane; b < K / 2; b += 32) { + const uint8_t v = w[b]; + const float sc = e4m3f(s[b / 8]); + acc += (kE2M1[v & 15] * sc) * x[2 * b] + (kE2M1[v >> 4] * sc) * x[2 * b + 1]; + } + acc = warp_sum(acc); + if (!lane) y[row] = acc * factor; +} + +// MXFP8: e4m3 values, one ue8m0 exponent per 32 columns (2^(s - 127)). +__global__ void gemv_mxfp8(const uint8_t* W, const uint8_t* S, const float* x, float* y, int N, int K) { + const int row = blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32, lane = threadIdx.x & 31; + if (row >= N) return; + const uint8_t* w = W + (size_t) row * K; + const uint8_t* s = S + (size_t) row * (K / 32); + float acc = 0.0f; + for (int k = lane; k < K; k += 32) acc += (e4m3f(w[k]) * exp2f((float) s[k / 32] - 127.0f)) * x[k]; + acc = warp_sum(acc); + if (!lane) y[row] = acc; +} + +// --------------------------------------------------------------------------------------------------------------------- +// Checkpoint access + +struct Ckpt { + std::string path; + StFile st; + const StTensor& t(const std::string& name) const { + auto it = st.tensors.find(name); + if (it == st.tensors.end()) { std::fprintf(stderr, "missing tensor %s\n", name.c_str()); std::exit(1); } + return it->second; + } + bool has(const std::string& name) const { return st.tensors.count(name) != 0; } + std::vector bytes(const std::string& name) const { + std::vector b; + const std::string e = strata::image::st_read_tensor(path, st, t(name), b); + if (!e.empty()) { std::fprintf(stderr, "%s\n", e.c_str()); std::exit(1); } + return b; + } + vec f32(const std::string& name) const { // BF16 or F32 -> fp32 (exact) + const StTensor& d = t(name); + auto b = bytes(name); + vec out; + if (d.dtype == "F32") { + out.resize(b.size() / 4); + std::memcpy(out.data(), b.data(), b.size()); + } else if (d.dtype == "BF16") { + out.resize(b.size() / 2); + for (size_t i = 0; i < out.size(); ++i) { + uint32_t u = (uint32_t) (b[2 * i] | (b[2 * i + 1] << 8)) << 16; + std::memcpy(&out[i], &u, 4); + } + } else { std::fprintf(stderr, "%s: dtype %s not handled\n", name.c_str(), d.dtype.c_str()); std::exit(1); } + return out; + } +}; + +const Ckpt* g_ck = nullptr; +size_t g_vram = 0; + +void* upload(const std::vector& b) { + void* d = nullptr; + CK(cudaMalloc(&d, b.size())); + CK(cudaMemcpy(d, b.data(), b.size(), cudaMemcpyHostToDevice)); + g_vram += b.size(); + return d; +} + +struct DMat { // a BF16 matrix [n, k] in VRAM + const uint16_t* d = nullptr; + int n = 0, k = 0; +}; + +DMat dmat(const std::string& name) { + const StTensor& t = g_ck->t(name); + if (t.dtype != "BF16") { std::fprintf(stderr, "%s: expected BF16, got %s\n", name.c_str(), t.dtype.c_str()); std::exit(1); } + DMat m; + m.n = (int) t.shape[0]; + m.k = 1; + for (size_t i = 1; i < t.shape.size(); ++i) m.k *= (int) t.shape[i]; + m.d = (const uint16_t*) upload(g_ck->bytes(name)); + return m; +} + +float* g_dx = nullptr; +float* g_dy = nullptr; + + +vec mv(const DMat& W, const vec& x, int rows = -1) { // W x, the first `rows` rows (all by default) + const int n = rows < 0 ? W.n : rows; + if ((int) x.size() != W.k) { std::fprintf(stderr, "mv: %zu != %d\n", x.size(), W.k); std::exit(1); } + CK(cudaMemcpy(g_dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice)); + gemv_bf16<<<(n + 7) / 8, 256>>>(W.d, g_dx, g_dy, n, W.k); + vec y((size_t) n); + CK(cudaMemcpy(y.data(), g_dy, y.size() * 4, cudaMemcpyDeviceToHost)); + return y; +} + +struct Experts { + bool nvfp4 = true; + const uint8_t *w13 = nullptr, *s13 = nullptr, *w2 = nullptr, *s2 = nullptr; + vec f13, f2; // NVFP4: amax / denominator per expert +}; + +// gate_up rows of expert e: [2*FF rows (gate/up interleaved: row 2j gate j, 2j+1 up j), H columns]; down: [H, FF] +vec expert_mv(const Experts& X, int e, bool up_proj, const vec& x) { + const int N = up_proj ? 2 * FF : H, K = up_proj ? H : FF; + CK(cudaMemcpy(g_dx, x.data(), (size_t) K * 4, cudaMemcpyHostToDevice)); + if (X.nvfp4) { + const uint8_t* w = (up_proj ? X.w13 : X.w2) + (size_t) e * N * (K / 2); + const uint8_t* s = (up_proj ? X.s13 : X.s2) + (size_t) e * N * (K / 16); + gemv_nvfp4<<<(N + 7) / 8, 256>>>(w, s, (up_proj ? X.f13 : X.f2)[e], g_dx, g_dy, N, K); + } else { + const uint8_t* w = (up_proj ? X.w13 : X.w2) + (size_t) e * N * K; + const uint8_t* s = (up_proj ? X.s13 : X.s2) + (size_t) e * N * (K / 32); + gemv_mxfp8<<<(N + 7) / 8, 256>>>(w, s, g_dx, g_dy, N, K); + } + vec y((size_t) N); + CK(cudaMemcpy(y.data(), g_dy, y.size() * 4, cudaMemcpyDeviceToHost)); + return y; +} + +// --------------------------------------------------------------------------------------------------------------------- +// Host fp32 operations (each one named after its transformers module) + +float dot(const float* a, const float* b, int n) { + float s = 0.0f; + for (int i = 0; i < n; ++i) s += a[i] * b[i]; + return s; +} + +vec rms(const vec& x, const vec* w) { // Inkling2LoopRMSNorm (w) / Inkling2LoopUnweightedRMSNorm (nullptr) + double ss = 0.0; // CBA: double for the mean; torch reduces fp32 pairwise, the difference is ~1e-7 relative + for (float v : x) ss += (double) v * v; + const float r = 1.0f / std::sqrt((float) (ss / x.size()) + EPS); + vec y(x.size()); + for (size_t i = 0; i < x.size(); ++i) y[i] = w ? (*w)[i] * (x[i] * r) : x[i] * r; + return y; +} + +float sigmoidf(float v) { return 1.0f / (1.0f + std::exp(-v)); } + +int g_pos_offset = 0; // --pos-offset: shifts the positions Inkling2LoopLogScale sees (only), to test it past 8191 + +float log_scale(int pos) { // Inkling2LoopLogScale + pos += g_pos_offset; + return 1.0f + LOG_ALPHA * std::log(std::max((float) (pos + 1) / LOG_FLOOR, 1.0f)); +} + +void l2_clip(float* v, int n, float thr) { // Inkling2LoopL2Clip + const float norm = std::sqrt(dot(v, v, n)); + const float s = std::min(thr / (norm + 1e-6f), 1.0f); + for (int i = 0; i < n; ++i) v[i] *= s; +} + +// Inkling2LoopBlockAttentionResidual / MessageAttentionResidual: softmax over the normalized stack [B..., h] of +// (q . s_j) / sqrt(H), returns sum_j p_j s_j (the NORMALIZED states), one output per query. +std::vector attnres(const float* queries, int nq, const std::vector& B, const vec& h) { + std::vector s; + for (const vec& b : B) s.push_back(rms(b, nullptr)); + s.push_back(rms(h, nullptr)); + std::vector out; + const float scale = 1.0f / std::sqrt((float) H); + for (int q = 0; q < nq; ++q) { + vec lg(s.size()); + for (size_t j = 0; j < s.size(); ++j) lg[j] = dot(queries + (size_t) q * H, s[j].data(), H) * scale; + const float mx = *std::max_element(lg.begin(), lg.end()); + float z = 0.0f; + for (float& v : lg) { v = std::exp(v - mx); z += v; } + vec o(H, 0.0f); + for (size_t j = 0; j < s.size(); ++j) + for (int i = 0; i < H; ++i) o[i] += (lg[j] / z) * s[j][i]; + out.push_back(o); + } + return out; +} + +struct MsgGate { // Inkling2LoopMessageGate (checkpoint: controllers.{attn,k,v,mlp}.{down,forget,gain}_weight) + DMat down, forget, gain; +}; + +vec message_gate(const MsgGate& g, const vec& x, const vec& m) { // (1 - tanh(F d)) * x + tanh(G d) * m + vec cat = rms(x, nullptr); + vec mn = rms(m, nullptr); + cat.insert(cat.end(), mn.begin(), mn.end()); + const vec d = mv(g.down, cat); + const vec f = mv(g.forget, d), gn = mv(g.gain, d); + vec y(H); + for (int i = 0; i < H; ++i) y[i] = (1.0f - std::tanh(f[i])) * x[i] + std::tanh(gn[i]) * m[i]; + return y; +} + +// Inkling2LoopShortConvolution: depthwise causal conv over the sequence (taps w[c][0..3], w[c][3] on the current +// token), out = (conv + x) / sqrt(5). `hist` holds this slot's previous inputs, oldest first. +vec short_conv(const vec& x, std::vector& hist, const vec& w) { + const int C = (int) x.size(); + vec y(C); + for (int c = 0; c < C; ++c) { + float acc = w[(size_t) c * KC + KC - 1] * x[c]; + for (int j = 1; j < KC; ++j) { + const int back = (int) hist.size() - j; + if (back >= 0) acc += w[(size_t) c * KC + KC - 1 - j] * hist[back][c]; + } + y[c] = (acc + x[c]) / std::sqrt((float) (KC + 1)); + } + hist.push_back(x); + return y; +} + +// Inkling2LoopDynamicShortConvolution (full layers' keys and values): taps = static_w[lag][c] + (Wp xin)[head*4+lag], +// out = (sum_lag taps * x[t - lag] + x) / sqrt(9). +vec dyn_conv(const vec& x, const vec& xin, std::vector& hist, const vec& static_w, const DMat& wproj) { + const vec dw = mv(wproj, xin); // [NKV * KC] + const int C = (int) x.size(), per_head = C / NKV; + vec y(C); + for (int c = 0; c < C; ++c) { + float acc = 0.0f; + for (int lag = 0; lag < KC; ++lag) { + const float tap = static_w[(size_t) lag * C + c] + dw[(c / per_head) * KC + lag]; + const float* past = lag == 0 ? x.data() : ((int) hist.size() - lag >= 0 ? hist[hist.size() - lag].data() : nullptr); + if (past) acc += tap * past[c]; + } + y[c] = (acc + x[c]) / std::sqrt((float) (2 * KC + 1)); + } + hist.push_back(x); + return y; +} + +// --------------------------------------------------------------------------------------------------------------------- +// The model + +struct Layer { + bool full = false, loop = false; + DMat wq, wk, wv, wo, gate_attn, wr, sink, router; + DMat k_wproj, v_wproj; // full layers + vec q_scale, rel_scale, rel_proj; // [24*128], [24*16], [16*1024] + vec k_conv, v_conv, k_static, v_static, attn_conv, mlp_conv; + vec attn_norm, q_norm, k_norm, v_norm, mlp_norm; + vec attn_query, mlp_query; // attention_input (1 or 3 queries; empty on layer 0), mlp_input + vec router_bias; + Experts ex; + MsgGate gates[4]; // q, k, v, mlp (loop layers) +}; + +struct Slot { // one layer application's state across positions + std::vector K, V; // [pos][NKV*HD] after the clip / norm + std::vector khist, vhist, ahist, mhist; +}; + +struct Model { + vec embed_norm, norm, final_query, msg_queries; // msg_queries: [NLOOP][4 (q,k,v,mlp)][H] + std::vector embed; // host BF16 [201024 * H] + DMat unembed; + Layer L[NL]; + Slot slots[NCALLS]; +}; + +Model* M = nullptr; + +void load(const Ckpt& ck) { + M = new Model(); + const std::string p = "model.llm."; + M->embed_norm = ck.f32(p + "embed_norm.weight"); + M->norm = ck.f32(p + "norm.weight"); + M->final_query = ck.f32(p + "attn_res.output_query"); + { + auto b = ck.bytes(p + "embed.weight"); + M->embed.resize(b.size() / 2); + std::memcpy(M->embed.data(), b.data(), b.size()); + } + M->unembed = dmat(p + "unembed.weight"); + { // Inkling2LoopMergeMessageQueries: queries rows (2i, 2i+1) = (q, mlp), kv_queries rows (2i, 2i+1) = (k, v) + const vec q = ck.f32(p + "middle_cycle_cross_pass_queries"), kv = ck.f32(p + "middle_cycle_cross_pass_kv_queries"); + M->msg_queries.resize((size_t) NLOOP * 4 * H); + for (int i = 0; i < NLOOP; ++i) { + const float* src[4] = {&q[(size_t) (2 * i) * H], &kv[(size_t) (2 * i) * H], &kv[(size_t) (2 * i + 1) * H], + &q[(size_t) (2 * i + 1) * H]}; + for (int j = 0; j < 4; ++j) std::memcpy(&M->msg_queries[((size_t) i * 4 + j) * H], src[j], H * 4); + } + } + for (int l = 0; l < NL; ++l) { + Layer& Y = M->L[l]; + const std::string q = p + "layers." + std::to_string(l) + "."; + Y.full = full_layer(l); + Y.loop = l >= LOOP_BEGIN && l < LOOP_END; + Y.wq = dmat(q + "attn.wq_du.weight"); + Y.wk = dmat(q + "attn.wk_dv.weight"); + Y.wv = dmat(q + "attn.wv_dv.weight"); + Y.wo = dmat(q + "attn.wo_ud.weight"); + Y.gate_attn = dmat(q + "attn.gate_attn.weight"); + Y.wr = dmat(q + "attn.wr_du.weight"); + Y.sink = dmat(q + "attn.attn_sink_proj.weight"); + Y.router = dmat(q + "mlp.gate.weight"); + Y.router_bias = ck.f32(q + "mlp.gate.bias"); + Y.q_scale = ck.f32(q + "attn.q_l2_clip.scale"); + Y.rel_scale = ck.f32(q + "attn.rel_l2_clip.scale"); + Y.rel_proj = ck.f32(q + "attn.rel_logits_proj.proj"); + Y.attn_conv = ck.f32(q + "attn_sconv.weight"); + Y.mlp_conv = ck.f32(q + "mlp_sconv.weight"); + Y.mlp_norm = ck.f32(q + "mlp_norm.weight"); + if (Y.full) { + Y.k_static = ck.f32(q + "attn.k_sconv.static_w"); + Y.v_static = ck.f32(q + "attn.v_sconv.static_w"); + Y.k_wproj = dmat(q + "attn.k_sconv.weight_proj"); + Y.v_wproj = dmat(q + "attn.v_sconv.weight_proj"); + Y.q_norm = ck.f32(q + "q_input_norm.weight"); + Y.k_norm = ck.f32(q + "k_input_norm.weight"); + Y.v_norm = ck.f32(q + "v_input_norm.weight"); + } else { + Y.k_conv = ck.f32(q + "attn.k_sconv.weight"); + Y.v_conv = ck.f32(q + "attn.v_sconv.weight"); + Y.attn_norm = ck.f32(q + "attn_norm.weight"); + } + if (l > 0) Y.attn_query = ck.f32(p + "attn_res.attn_queries." + std::to_string(l - 1)); // offset 1 + Y.mlp_query = ck.f32(p + "attn_res.mlp_queries." + std::to_string(l)); + if ((int) Y.attn_query.size() != (l == 0 ? 0 : (Y.full ? 3 : 1)) * H) { + std::fprintf(stderr, "layer %d: attention_input query size %zu\n", l, Y.attn_query.size()); + std::exit(1); + } + if (Y.loop) { + const char* names[4] = {"attn", "k", "v", "mlp"}; + for (int g = 0; g < 4; ++g) { + const std::string c = q + "controllers." + names[g] + "."; + Y.gates[g] = {dmat(c + "down_weight"), dmat(c + "forget_weight"), dmat(c + "gain_weight")}; + } + } + Experts& X = Y.ex; + X.nvfp4 = l < MXFP8_FIRST; + X.w13 = (const uint8_t*) upload(ck.bytes(q + "mlp.experts.w13_weight")); + X.s13 = (const uint8_t*) upload(ck.bytes(q + "mlp.experts.w13_weight_scale")); + X.w2 = (const uint8_t*) upload(ck.bytes(q + "mlp.experts.w2_weight")); + X.s2 = (const uint8_t*) upload(ck.bytes(q + "mlp.experts.w2_weight_scale")); + if (X.nvfp4) { + const vec a13 = ck.f32(q + "mlp.experts.w13_weight_amax"), d13 = ck.f32(q + "mlp.experts.w13_weight_outer_scale_denominator"); + const vec a2 = ck.f32(q + "mlp.experts.w2_weight_amax"), d2 = ck.f32(q + "mlp.experts.w2_weight_outer_scale_denominator"); + X.f13.resize(NE); + X.f2.resize(NE); + for (int e = 0; e < NE; ++e) { X.f13[e] = a13[e] / d13[0]; X.f2[e] = a2[e] / d2[0]; } + } else if (ck.has(q + "mlp.experts.w13_weight_amax")) { + std::fprintf(stderr, "layer %d: MXFP8 expected but the experts carry an amax\n", l); + std::exit(1); + } + std::fprintf(stderr, "\rloaded layer %d/%d, %.1f GiB in VRAM", l + 1, NL, g_vram / 1073741824.0); + } + std::fprintf(stderr, "\n"); +} + +// Inkling2LoopSlidingAttention / Inkling2LoopFullAttention for one token at `pos` +vec attention(const Layer& Y, Slot& S, int pos, const vec& xq, const vec& xk, const vec& xv) { + const float tau = log_scale(pos); + vec q = mv(Y.wq, xq); + for (int h = 0; h < NQ; ++h) { // (Log)ScaledL2Clip + float* v = &q[(size_t) h * HD]; + for (int d = 0; d < HD; ++d) v[d] *= Y.q_scale[(size_t) h * HD + d]; + l2_clip(v, HD, QK_CLIP); + if (Y.full) for (int d = 0; d < HD; ++d) v[d] *= tau; + } + vec k = mv(Y.wk, xk), v = mv(Y.wv, xv); + if (Y.full) { + k = dyn_conv(k, xk, S.khist, Y.k_static, Y.k_wproj); + v = dyn_conv(v, xv, S.vhist, Y.v_static, Y.v_wproj); + } else { + k = short_conv(k, S.khist, Y.k_conv); + v = short_conv(v, S.vhist, Y.v_conv); + } + for (int g = 0; g < NKV; ++g) { + l2_clip(&k[(size_t) g * HD], HD, QK_CLIP); // keys: L2Clip, no scale + vec vh(v.begin() + (size_t) g * HD, v.begin() + (size_t) (g + 1) * HD); + vh = rms(vh, nullptr); // values: UnweightedRMSNorm per head + std::copy(vh.begin(), vh.end(), v.begin() + (size_t) g * HD); + } + S.K.push_back(k); + S.V.push_back(v); + + vec rs = mv(Y.wr, xq); // relative position bias states [24][16] + for (int h = 0; h < NQ; ++h) { + float* r = &rs[(size_t) h * DREL]; + for (int d = 0; d < DREL; ++d) r[d] *= Y.rel_scale[(size_t) h * DREL + d]; + l2_clip(r, DREL, REL_CLIP); + if (Y.full) for (int d = 0; d < DREL; ++d) r[d] *= tau; + } + const vec sink = mv(Y.sink, xq); + const vec gate = mv(Y.gate_attn, xq); + + const int T = (int) S.K.size(); // == pos + 1 + const float scale = 1.0f / std::sqrt((float) HD); + vec att((size_t) NQ * HD, 0.0f); + for (int h = 0; h < NQ; ++h) { + const int g = h / NREP; + vec lg((size_t) T, -INFINITY); + float mx = sink[h]; + for (int j = 0; j < T; ++j) { + const int dist = (T - 1) - j; + if (!Y.full && dist >= WINDOW) continue; + float bias = 0.0f; + if (dist < EXTENT) { + for (int r = 0; r < DREL; ++r) bias += rs[(size_t) h * DREL + r] * Y.rel_proj[(size_t) r * EXTENT + dist]; + } + lg[j] = dot(&q[(size_t) h * HD], &S.K[j][(size_t) g * HD], HD) * scale + bias; + mx = std::max(mx, lg[j]); + } + float z = std::exp(sink[h] - mx); // the sink: one more logit with a zero value + for (int j = 0; j < T; ++j) { lg[j] = std::exp(lg[j] - mx); z += lg[j]; } + float* o = &att[(size_t) h * HD]; + for (int j = 0; j < T; ++j) + for (int d = 0; d < HD; ++d) o[d] += (lg[j] / z) * S.V[j][(size_t) g * HD + d]; + } + for (size_t i = 0; i < att.size(); ++i) att[i] *= sigmoidf(gate[i]); // GatedOutputProjection + return mv(Y.wo, att); +} + +vec moe(const Layer& Y, const vec& x) { // Inkling2LoopSparseMoeBlock (router in fp32, sigmoid scores) + const vec lg = mv(Y.router, x); + vec s(NE), sel(NE); + for (int e = 0; e < NE; ++e) { s[e] = sigmoidf(lg[e]); sel[e] = s[e] + Y.router_bias[e]; } + std::vector idx(NE); + std::iota(idx.begin(), idx.end(), 0); + std::partial_sort(idx.begin(), idx.begin() + TOPK, idx.end(), [&](int a, int b) { return sel[a] > sel[b]; }); + float sum = 0.0f; + for (int k = 0; k < TOPK; ++k) sum += s[idx[k]]; + vec out(H, 0.0f); + for (int k = 0; k < TOPK; ++k) { + const int e = idx[k]; + const float w = s[e] / (sum + 1e-20f) * ROUTE_SCALE; + const vec gu = expert_mv(Y.ex, e, true, x); + vec act(FF); + for (int j = 0; j < FF; ++j) { // SoftcappedSwiGLU + const float g = gu[2 * j], u = gu[2 * j + 1]; + act[j] = (std::tanh(g / GATE_CAP) * GATE_CAP) * sigmoidf(g) * (std::tanh(u / UP_CAP) * UP_CAP); + } + const vec y = expert_mv(Y.ex, e, false, act); + for (int i = 0; i < H; ++i) out[i] += y[i] * w; + } + return out; +} + +// One decoder layer application; `msgs` = the 4 messages (q, k, v, mlp) on loop passes 1-2, else nullptr. +vec layer_forward(int l, Slot& S, int pos, const vec& h, const std::vector& B, const std::vector* msgs) { + const Layer& Y = M->L[l]; + vec xq, xk, xv; + if (Y.full) { + vec qi = h, ki = h, vi = h; + if (l > 0) { + auto r = attnres(Y.attn_query.data(), 3, B, h); + qi = r[0]; ki = r[1]; vi = r[2]; + } + if (msgs) { + qi = message_gate(Y.gates[0], qi, (*msgs)[0]); + ki = message_gate(Y.gates[1], ki, (*msgs)[1]); + vi = message_gate(Y.gates[2], vi, (*msgs)[2]); + } + xq = rms(qi, &Y.q_norm); xk = rms(ki, &Y.k_norm); xv = rms(vi, &Y.v_norm); + } else { + const vec a = l > 0 ? attnres(Y.attn_query.data(), 1, B, h)[0] : h; + if (msgs) { + xq = rms(message_gate(Y.gates[0], a, (*msgs)[0]), &Y.attn_norm); + xk = rms(message_gate(Y.gates[1], a, (*msgs)[1]), &Y.attn_norm); + xv = rms(message_gate(Y.gates[2], a, (*msgs)[2]), &Y.attn_norm); + } else { + xq = xk = xv = rms(a, &Y.attn_norm); + } + } + vec att = attention(Y, S, pos, xq, xk, xv); + att = short_conv(att, S.ahist, Y.attn_conv); + std::vector B2 = B; + vec r(H); + if (l % BLOCK == 0) { r = att; B2.push_back(h); } + else for (int i = 0; i < H; ++i) r[i] = h[i] + att[i]; + vec m = attnres(Y.mlp_query.data(), 1, B2, r)[0]; + if (msgs) m = message_gate(Y.gates[3], m, (*msgs)[3]); + vec y = moe(Y, rms(m, &Y.mlp_norm)); + y = short_conv(y, S.mhist, Y.mlp_conv); + for (int i = 0; i < H; ++i) y[i] += r[i]; + return y; +} + +vec forward_token(int tok, int pos, std::vector* calls) { + vec e(H); + for (int i = 0; i < H; ++i) { + uint32_t u = (uint32_t) M->embed[(size_t) tok * H + i] << 16; + std::memcpy(&e[i], &u, 4); + } + vec h = rms(e, &M->embed_norm); + std::vector B; + auto run = [&](int l, int slot, const std::vector* msgs) { + vec out = layer_forward(l, M->slots[slot], pos, h, B, msgs); + if (l % BLOCK == 0) B.push_back(h); + h = out; + if (calls) calls->push_back(h); + }; + for (int l = 0; l < LOOP_BEGIN; ++l) run(l, l, nullptr); + const vec pre_h = h; + const std::vector pre_B = B; + for (int l = LOOP_BEGIN; l < LOOP_END; ++l) run(l, l, nullptr); + for (int p = 1; p < PASSES; ++p) { + const std::vector prevB(B.begin() + pre_B.size() + 1, B.end()); // +1: skip the first loop block + const vec prev_h = h; + h = pre_h; + B = pre_B; + for (int i = 0; i < NLOOP; ++i) { + const std::vector msgs = attnres(&M->msg_queries[(size_t) i * 4 * H], 4, prevB, prev_h); + run(LOOP_BEGIN + i, NL + (p - 1) * NLOOP + i, &msgs); + } + } + for (int l = LOOP_END; l < NL; ++l) run(l, l, nullptr); + h = attnres(M->final_query.data(), 1, B, h)[0]; + vec logits = mv(M->unembed, rms(h, &M->norm), VOCAB); + for (float& v : logits) v = std::tanh(v / LOGIT_CAP) * LOGIT_CAP; + return logits; +} + +std::vector parse_ids(const char* s) { + std::vector v; + for (const char* p = s; *p;) { + char* end = nullptr; + v.push_back((int) std::strtol(p, &end, 10)); + if (end == p) break; + p = *end == ',' ? end + 1 : end; + } + return v; +} + +} // namespace + +int main(int argc, char** argv) { + std::string dir, dump_layers, dump_logits; + std::vector ids; + int n_gen = 16; + for (int i = 1; i + 1 < argc; i += 2) { + const std::string a = argv[i]; + if (a == "--model") dir = argv[i + 1]; + else if (a == "--tokens") ids = parse_ids(argv[i + 1]); + else if (a == "--n") n_gen = std::atoi(argv[i + 1]); + else if (a == "--pos-offset") g_pos_offset = std::atoi(argv[i + 1]); + else if (a == "--tokens-file") { + FILE* f = std::fopen(argv[i + 1], "r"); + if (!f) { std::fprintf(stderr, "cannot open %s\n", argv[i + 1]); return 2; } + std::string text; + for (int c; (c = std::fgetc(f)) != EOF;) text += (char) c; + std::fclose(f); + ids = parse_ids(text.c_str()); + } + else if (a == "--dump-layers") dump_layers = argv[i + 1]; + else if (a == "--dump-logits") dump_logits = argv[i + 1]; + else { std::fprintf(stderr, "unknown option %s\n", a.c_str()); return 2; } + } + if (dir.empty() || ids.empty()) { + std::fprintf(stderr, "usage: strata-ink2ref --model DIR --tokens 1,2,3 [--n 16] [--dump-layers F] [--dump-logits F]\n"); + return 2; + } + Ckpt ck; + ck.path = dir + "/model-00001-of-00001.safetensors"; + const std::string e = strata::image::st_read_header(ck.path, ck.st); + if (!e.empty()) { std::fprintf(stderr, "%s\n", e.c_str()); return 1; } + g_ck = &ck; + CK(cudaMalloc(&g_dx, (size_t) 2 * H * 4)); + CK(cudaMalloc(&g_dy, (size_t) 201024 * 4)); + load(ck); + + FILE* fl = dump_layers.empty() ? nullptr : std::fopen(dump_layers.c_str(), "wb"); + FILE* fg = dump_logits.empty() ? nullptr : std::fopen(dump_logits.c_str(), "wb"); + vec logits; + for (size_t t = 0; t < ids.size(); ++t) { + std::vector calls; + logits = forward_token(ids[t], (int) t, &calls); + if ((int) calls.size() != NCALLS) { std::fprintf(stderr, "%zu layer calls\n", calls.size()); return 1; } + if (fl) for (const vec& c : calls) std::fwrite(c.data(), 4, H, fl); + if (fg) std::fwrite(logits.data(), 4, logits.size(), fg); + std::fprintf(stderr, "\rprompt %zu/%zu", t + 1, ids.size()); + } + std::fprintf(stderr, "\n"); + if (fl) std::fclose(fl); + if (fg) std::fclose(fg); + std::printf("top:"); + { + std::vector o(logits.size()); + std::iota(o.begin(), o.end(), 0); + std::partial_sort(o.begin(), o.begin() + 5, o.end(), [&](int a, int b) { return logits[a] > logits[b]; }); + for (int k = 0; k < 5; ++k) std::printf(" %d:%.4f", o[k], logits[o[k]]); + } + std::printf("\ngen:"); + int pos = (int) ids.size(); + for (int k = 0; k < n_gen; ++k) { + const int next = (int) (std::max_element(logits.begin(), logits.end()) - logits.begin()); + std::printf(" %d", next); + std::fflush(stdout); + logits = forward_token(next, pos++, nullptr); + } + std::printf("\n"); + return 0; +} diff --git a/terminal/serve/frontend.py b/terminal/serve/frontend.py index 694349b6407..f80654f8d74 100644 --- a/terminal/serve/frontend.py +++ b/terminal/serve/frontend.py @@ -82,7 +82,8 @@ def render(self, messages: list[dict], tools: list[dict] | None = None, add_gene elif self._is_inkling2: from serve import inkling_dialect messages = inkling_dialect.prepare_messages(messages) - kwargs = inkling_dialect.template_kwargs(kwargs) + if not _INK_THINKS: # strata-inkling runs thinking off; strata-ink2 takes the effort words + kwargs = inkling_dialect.template_kwargs(kwargs) return self.template.render(messages=messages, tools=tools, add_generation_prompt=add_generation_prompt, **kwargs) @@ -183,23 +184,54 @@ def _text_of(content) -> str: _EFFORT_QWEN = dict(EFFORT) -_FAMILY: str | None = None +# Inkling 2's template takes the words themselves (none 0.0, minimal 0.1, low 0.2, medium 0.7, high 0.9, xhigh/max 0.99) +_EFFORT_INKLING = {"none": "none", "off": "none", "minimal": "minimal", "disabled": "none", "false": "none", + "low": "low", "medium": "medium", "high": "high", "xhigh": "xhigh", "max": "max", "maximum": "max"} +_FAMILY: str | None = None # the model family this server runs (None: the Qwen form) +# Inkling 2 has two engines on the same official template: strata-inkling runs it thinking off (serve/inkling_dialect.py, the default +# here), strata-ink2 takes the template's effort words (Service.set_family turns this on for it) +_INK_THINKS = False -def use_family(family: str | None) -> None: - """The reasoning-effort words of the model family this server runs (module state, like ENV_TO_USER): Qwen, Hy4-Flash, or Inkling-2-Mini.""" - global _FAMILY - _FAMILY = family +def is_inkling(source: str | None) -> bool: + """Inkling 2's chat template: messages are <|message_model|><|content_KIND|>...<|end_message|>.""" + return INK_THINK in (source or "") + + +def use_family(family: str | None, thinks: bool = False) -> None: + """The reasoning-effort words of the model family this server runs (module state, like ENV_TO_USER): the Qwen table, + Hy4-Flash's (its template knows no_think, high and max: serve/hy4_dialect.py) or Inkling 2's.""" + global _FAMILY, _INK_THINKS + _FAMILY, _INK_THINKS = family, family == "inkling2" and thinks EFFORT.clear() if family == "hy4": from serve import hy4_dialect EFFORT.update(hy4_dialect.EFFORT) return - if family == "inkling2": + if family == "inkling2" and not _INK_THINKS: from serve import inkling_dialect EFFORT.update(inkling_dialect.EFFORT) return - EFFORT.update(_EFFORT_QWEN) + EFFORT.update(_EFFORT_INKLING if family == "inkling2" else _EFFORT_QWEN) + + +def family_text(text: str) -> str: + """Text the server writes into the reply itself (the thinking's close, a wrap-up) in this family's spelling: for Inkling 2, + and the blank line after it are the end of the thinking message and the start of the text one.""" + if _FAMILY != "inkling2": + return text + return re.sub(r"\n?\n*", INK_CLOSE, text) + + +def inkling_force(force: str | None) -> str | None: + """forced_call's opening (`\\n\\n`) in Inkling 2's form: the call message's header and the start + of its JSON body, so the model can only write the arguments.""" + if not force: + return force + m = re.search(r"\n]*)>", force) + if m is None: # CBA: "required" among several tools opens a model message only; the model may still write text + return INK_HEAD + return f'{INK_HEAD}{m.group(1)}{INK_CALL}{{"name":{json.dumps(m.group(1), ensure_ascii=False)},"args":' def effort_kwargs(value) -> dict: @@ -207,14 +239,25 @@ def effort_kwargs(value) -> dict: if value is None or value == "": return {} if value is False: - return {"reasoning_effort": "none"} if _FAMILY == "inkling2" else {"enable_thinking": False} + if _FAMILY != "inkling2": + return {"enable_thinking": False} + value = "false" # Inkling 2's template takes the words: "false" is its "none" if _FAMILY == "hy4": from serve import hy4_dialect mode = hy4_dialect.normalize_effort(value) return {"enable_thinking": False} if mode == "no_think" else {"reasoning_effort": mode} - if _FAMILY == "inkling2": + if _FAMILY == "inkling2" and not _INK_THINKS: from serve import inkling_dialect return {"reasoning_effort": inkling_dialect.normalize_effort(value)} + if _FAMILY == "inkling2" and not isinstance(value, bool): # its template also takes the level itself, 0.0 to 0.99 + try: + level = float(value) + except (TypeError, ValueError): + level = None + if level is not None: + if not 0.0 <= level <= 0.99: + raise ValueError(f"reasoning effort {value!r}: Inkling 2 takes a level from 0.0 to 0.99, or none, minimal, low, medium, high, xhigh") + return {"reasoning_effort": level} key = str(value).strip().lower() if key not in EFFORT: raise ValueError(f"unknown reasoning effort {value!r}: use none, low, medium or high") @@ -660,10 +703,16 @@ def _order_chat_tool_results(messages: list[dict]) -> None: rank = {cid: n for n, cid in enumerate(calls)} messages[i:j] = sorted(messages[i:j], key=lambda m: rank[m["_call_id"]]) i = j + names = {} # Inkling 2 heads a result with its tool's name (<|message_tool|>NAME) for message in messages: - message.pop("_call_id", None) + cid = message.pop("_call_id", None) + if (_FAMILY == "inkling2" and message["role"] == "tool" and not message.get("name") and isinstance(cid, str) + and cid in names): + message["name"] = names[cid] for call in message.get("tool_calls") or []: - call.pop("_call_id", None) + cid = call.pop("_call_id", None) + if isinstance(cid, str): # a client's id may be anything (a list, a number) + names[cid] = call["function"].get("name") def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: @@ -680,6 +729,8 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: out = {"role": role, "content": _parts_of(content) if images else _text_of(content)} if role == "tool": out["_call_id"] = m.get("tool_call_id") + if _FAMILY == "inkling2" and isinstance(m.get("name"), str) and m["name"]: + out["name"] = m["name"] if m.get("reasoning_content"): out["reasoning_content"] = m["reasoning_content"] if m.get("tool_calls"): @@ -710,7 +761,7 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: raise ValueError("chat_template_kwargs must be an object") for k, v in ctk.items(): if k == "enable_thinking" and not v: - kwargs = {"enable_thinking": False} + kwargs = effort_kwargs(False) # Inkling 2: its template reads no enable_thinking, only the effort "none" elif k in ("reasoning_effort", "thinking_mode") and "enable_thinking" not in kwargs: kwargs.update(effort_kwargs(v)) return _env_to_user(_late_system_to_user(messages)), tools, kwargs @@ -911,7 +962,7 @@ def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[d if isinstance(bt, int) and not isinstance(bt, bool) and bt > 0 and req.get("reasoning_budget_tokens") is None: req["reasoning_budget_tokens"] = bt if isinstance(thinking, dict) and thinking.get("type") == "disabled": - kwargs["enable_thinking"] = False + kwargs.update(effort_kwargs(False)) elif effort: kwargs.update(effort_kwargs(effort)) elif isinstance(thinking, dict) and thinking.get("budget_tokens"): @@ -923,7 +974,7 @@ def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[d # and allow a few dozen tokens, which the model otherwise spent thinking and answered with no text at all. # A config's reasoning_effort still applies: Service.with_shared sets output_config before this runs. A # request that gives its own reasoning_budget_tokens (#123) asks for thinking, so it thinks as before. - kwargs["enable_thinking"] = False + kwargs.update(effort_kwargs(False)) return _env_to_user(_late_system_to_user(messages)), tools, kwargs @@ -943,6 +994,10 @@ class Event: THINK_END = "" +# Inkling 2's message markers (Ink2OutputParser): a header, three content kinds, a message's end, the reply's end +INK_HEAD, INK_THINK, INK_TEXT = "<|message_model|>", "<|content_thinking|>", "<|content_text|>" +INK_CALL, INK_END, INK_STOP = "<|content_invoke_tool_json|>", "<|end_message|>", "<|content_model_end_sampling|>" +INK_CLOSE = INK_END + INK_HEAD + INK_TEXT # the thinking's end as the model writes it CALL_START = "" CALL_END = "" FUNCTION_CALLS_START = "" # #6022: Claude's dialect's wrapper around its `` calls (recover) @@ -3034,6 +3089,93 @@ def __init__(self, thinking: bool = True, tools: list[dict] | None = None, strea declared_only=declared_only, deferred=deferred) +class Ink2OutputParser(JsonOutputParser): + """strata-ink2's parser (Service.set_family picks it; strata-inkling keeps InklingOutputParser, which drops the thinking). + Inkling 2 writes its reply as messages, <|message_model|>[NAME]<|content_KIND|>BODY<|end_message|>, KIND thinking, text + or invoke_tool_json (BODY {"name": NAME, "args": {...}}), and ends with <|content_model_end_sampling|>. The markers become the + form JsonOutputParser reads (the thinking closed by , each call a JSON) and the rest is its own.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._raw, self._sec, self._closed, self._call = "", None, False, "" + + def feed(self, delta: str) -> list[Event]: + if not delta and not self._raw: + return super().feed("") + self._raw += delta + out = [] + while self._raw: + i = self._raw.find("<|") + if i != 0: + text = self._raw[:i] if i > 0 else self._raw[:-1] if self._raw.endswith("<") else self._raw + if not text: # a lone "<" that may start a marker: held back + break + self._raw = self._raw[len(text):] + out += self._body(text) + continue + j = self._raw.find("|>") + if j < 0: + if len(self._raw) < 48: # a marker split across deltas: held back until it is whole + break + out += self._body(self._raw[:2]) + self._raw = self._raw[2:] + continue + tag, self._raw = self._raw[:j + 2], self._raw[j + 2:] + out += self._marker(tag) + return out + + def _body(self, text: str) -> list[Event]: + if self._sec in ("think", "text"): + return super().feed(text) + if self._sec == "call": + self._call += text + return [] # the header's NAME (it is in the call's JSON too) + + def _close(self) -> list[Event]: + if self._closed: + return [] + self._closed = True + return super().feed(THINK_END) if self.state == "reasoning" else [] + + def _marker(self, tag: str) -> list[Event]: + if tag == INK_HEAD or tag == INK_STOP: + self._sec = None + elif tag == INK_THINK: + self._sec = "think" + elif tag == INK_TEXT: + out, self._sec = self._close(), "text" + return out + elif tag == INK_CALL: + out, self._sec, self._call = self._close(), "call", "" + return out + elif tag == INK_END: + sec, self._sec = self._sec, None + if sec == "think": + return self._close() + if sec == "call": + return super().feed(self._wrap(self._call)) + elif self._sec in ("think", "text"): + return super().feed(tag) # not a marker of the reply's form: text + return [] + + @staticmethod + def _wrap(body: str) -> str: + try: + call = json.loads(body) + body = json.dumps({"name": call["name"], "arguments": call.get("args", {})}, ensure_ascii=False) + except (ValueError, TypeError, KeyError): + pass # not the form: JsonOutputParser's recovery reads it, or it stays text + return f"{CALL_START}\n{body}\n{CALL_END}" + + def finish(self, reason: str | None = None) -> list[Event]: + raw, self._raw = self._raw, "" + out = self._body(raw) if raw else [] + if self._sec == "call" and self._call: # cut inside a call: its opening and body, unclosed, as JsonOutputParser has them + out += super().feed(f"{CALL_START}\n{self._call}") + self._sec, self._call = None, "" + return out + super().finish(reason) + + class Hy4OutputParser(OutputParser): """The parser for Hy4-Flash: the model writes its reasoning and its calls with tagged tokens (``, ``, `` ...); serve/hy4_dialect.py turns them into the form OutputParser reads as the text arrives, and everything else (reasoning, content, declared-tool rules, recovery) is diff --git a/terminal/serve/server.py b/terminal/serve/server.py index 814f03455e1..4a4ba0dcc15 100644 --- a/terminal/serve/server.py +++ b/terminal/serve/server.py @@ -314,7 +314,7 @@ openai_collect, ) from serve.frontend import (CALL_END, CALL_START, FUNC_END, FUNC_START, THINK_END, ChatTemplate, Event, OutputParser, # noqa: E402 - parser_for_template, anthropic_to_messages, anthropic_tools, + INK_STOP, Ink2OutputParser, family_text, inkling_force, is_inkling, parser_for_template, anthropic_to_messages, anthropic_tools, forced_call, images_of, literal_tags, mark_think_literals, openai_to_messages, require_messages, tool_choice_of, unmark_think_literals) from serve.mcp import McpCancelled, hub_from_config, resolve_image_results # noqa: E402 @@ -425,6 +425,31 @@ def combined_embeddings_path(vision_dir: Path, nbytes: int) -> Path: # it blocked once the socket buffers are full - and that thread holds the engine's turn. A write that makes no progress # for this long ends the request as a disconnect (the engine is stopped, the turn given back). 0: no limit, as before. STREAM_WRITE_TIMEOUT_S = float(os.environ.get("STRATA_STREAM_WRITE_TIMEOUT_S", "60") or 0) +INKLING_NO_IMAGES = ("this Inkling 2 engine does not read images (a GGUF model is text only here, or the engine predates " + "images: one that reads them says images=1 at its start); send the text of the picture instead") + +def inkling_picture(data: bytes) -> bytes: + """A picture for strata-ink2: Vision.normalize, then a JPEG decoded by Pillow and handed over as an uncompressed BMP. + The reference (transformers' processor) decodes with libjpeg-turbo; the engine's stb_image decodes ~3 % of a photo's + pixels a few levels off, and that alone moves the ViT's output by ~2 % (measured on a 960x686 JPEG: rel-L2 2.4e-2 + against 2.7e-5 for the same pixels as a PNG). Pillow is the same libjpeg-turbo, so the pixels are the reference's.""" + data = Vision.normalize(data) + if data[:3] != b"\xff\xd8\xff": + return data + try: + import io + from PIL import Image + im = Image.open(io.BytesIO(data), formats=["JPEG"]) + im = im.convert("RGB") + out = io.BytesIO() + im.save(out, format="BMP") + return out.getvalue() + except ImportError: # CBA: without Pillow the engine decodes the JPEG itself (stb_image: close, not the reference's pixels) + return data + except Exception as e: # noqa: BLE001 - Pillow could not read what normalize passed through + raise ValueError(f"the image could not be read ({e})") from None + + # Reads that had no timeout (#1317). A blocking read of the image encoder's pipe or of the engine's READY line that # never returned held the request turn for good: the engine then sat idle in its command loop, so no watchdog could # fire and every later request queued behind it (the "lost step" class of #481). Generous on purpose: a cold model @@ -4161,10 +4186,26 @@ def __init__(self, engine: Engine, tokenizer, template: ChatTemplate, model_name else PromptEncoder(tokenizer) def set_family(self, family: str | None) -> None: - """The model family (None: the Qwen form this server was written for).""" + """The model family (None: the Qwen form this server was written for). Inkling 2 has two engines on the same template: + strata-inkling (Service.inkling, by its program's name: upstream's dialect, thinking off) and strata-ink2, any other + engine on Inkling 2's template (its effort words, Ink2OutputParser and the settings below).""" + ink2 = family in (None, "inkling2") and not getattr(self, "inkling", False) and is_inkling(getattr(self.template, "source", None)) + if ink2: + family = "inkling2" + self.parser_cls = Ink2OutputParser + # CBA: the tool-markup retry writes a Qwen user turn into the reply; off until it has an Inkling spelling + self.tool_markup_retry = False + # its reply ends with <|content_model_end_sampling|> (generation_config.json's eos); <|endoftext|> is one token + # in its o200k vocabulary too, but it is the pad, so end_token_ids' Qwen rule would miss the end + self.stop_ids = set(self.tok.encode(INK_STOP, parse_special=True)) + self._force_text = inkling_force self.family = family import serve.frontend as _frontend - _frontend.use_family(family) + _frontend.use_family(family, thinks=ink2) + if ink2: # /props: upstream sets False for strata-inkling (it drops the thinking); strata-ink2 keeps it, as the template does + hist = [{"role": "user", "content": "q"}, {"role": "assistant", "content": "a", "reasoning_content": "strata_caps_reasoning"}, + {"role": "user", "content": "q"}] + self.template.caps = {**self.template.caps, "supports_preserve_reasoning": "strata_caps_reasoning" in self.template.render(hist)} _force_text = None @@ -4424,10 +4465,16 @@ def reported_ctx(self) -> int: def has_vision(self) -> bool: """Whether this server can read images: either a separate vision encoder (Flash-Next) - or an in-process Hy4-Flash / Inkling-2-Mini engine that reported `images=1`.""" + or an engine that reads them itself (engine_reads_images) and reported `images=1`.""" if self.vision is not None: return True - return bool((self.hy4 or self.inkling) and (getattr(self.engine, "info", None) or {}).get("images") == 1) + return self.engine_reads_images() and (getattr(self.engine, "info", None) or {}).get("images") == 1 + + def engine_reads_images(self) -> bool: + """The engine decodes and encodes the pictures itself, from the files named by `image=` keys on its GEN + line (protocol 1.6b), never through the separate picture reader: Hy4-Flash, and both Inkling 2 engines (strata-ink2's + ViT runs in the engine; the template's one <|unused_200054|> per picture becomes rows x cols image tokens there).""" + return bool(self.hy4 or self.inkling or self.family == "inkling2") def reasoning_budget(self, req) -> int | None: """#123: the most tokens this request may think, or None: the request's `reasoning_budget_tokens` (or, as @@ -5293,14 +5340,16 @@ def prepare(self, messages, tools, kwargs, max_new=None, force=None, req=None, c images = images_of(messages) self.embeddings.hy4 = self._drop_hy4_images(getattr(self.embeddings, "hy4", None)) self.embeddings.inkling = self._drop_hy4_images(getattr(self.embeddings, "inkling", None)) # an earlier pass of this request left its files: gone first - if images and (self.hy4 or self.inkling): # Hy4-Flash / Inkling-2-Mini: in-process engine reads pictures directly (INFO images=1) + if images and self.engine_reads_images(): # Hy4-Flash, Inkling 2: the engine reads the pictures itself (INFO images=1); never the separate picture reader kind_mod = inkling_kind if self.inkling else hy4_kind if (getattr(self.engine, "info", None) or {}).get("images") != 1: - raise ValueError(kind_mod.NO_IMAGES_REPLY) + raise ValueError(INKLING_NO_IMAGES if self.family == "inkling2" and not self.inkling else kind_mod.NO_IMAGES_REPLY) if self.offline and any(src.startswith(("http://", "https://")) for src in images): raise ValueError("offline mode cannot download an image URL; send a data: image instead") + # strata-ink2: Pillow's JPEG pixels (inkling_picture), its files named like Hy4-Flash's (the image= keys of the GEN line) written = kind_mod.write_images( - images, lambda s: fetched[s] if s in fetched else Vision.load(s), Vision.normalize, cancel) + images, lambda s: fetched[s] if s in fetched else Vision.load(s), + inkling_picture if self.family == "inkling2" and not self.inkling else Vision.normalize, cancel) if self.inkling: self.embeddings.inkling = written else: @@ -5945,7 +5994,7 @@ def replica_selected(index: int) -> None: # #1053: the model wrote its reasoning and stopped before : the client would get # an empty answer. Close the thinking once and let it answer. close_retried = True - extra = self.tok.encode(REASONING_CLOSE, parse_special=True) + extra = self.tok.encode(family_text(REASONING_CLOSE), parse_special=True) if max_new - n - len(extra) >= 1: print("[strata] the reply ended inside its thinking with no answer: closing the " "thinking once and continuing (reasoning_close_retry)", flush=True) @@ -6022,9 +6071,10 @@ def replica_selected(index: int) -> None: budget = st["thinking_budget"] = None text = REASONING_WRAP_UP + (force or "") else: - text = "\n" * (2 - (len(tail) - len(tail.rstrip("\n")))) + force + text = force if self.family == "inkling2" else \ + "\n" * (2 - (len(tail) - len(tail.rstrip("\n")))) + force # (Inkling: no blank line between messages) force = None - extra = self.tok.encode(text, parse_special=True) + extra = self.tok.encode(family_text(text), parse_special=True) if max_new - n - len(extra) < 1: break # no room left to answer: "length", as without a budget if wrap: @@ -8825,7 +8875,8 @@ def request_stop(reason: str): except (OSError, ValueError): pass try: - tok = ST.Tokenizer(tokens, merges, types, tcfg.get("pre") or "qwen35", tcfg.get("special_ids") or None) + tok = ST.Tokenizer(tokens, merges, types, tcfg.get("pre") or "qwen35", tcfg.get("special_ids") or None, + bool(tcfg.get("ignore_merges"))) except ST.UnknownPreTokenizer as e: # a model with its own splitting rule: stop here, never split with another's ap.error(f"the model's tokenizer ({tpath}): {e}") hub = hub_from_config(cfg, a.mcp_config) # before the minutes of loading: a bad entry stops here diff --git a/terminal/serve/server_parts/engines.py b/terminal/serve/server_parts/engines.py index dace875f46d..b261e018d44 100644 --- a/terminal/serve/server_parts/engines.py +++ b/terminal/serve/server_parts/engines.py @@ -823,6 +823,12 @@ def parallel_args(cfg: dict, args: list[str]) -> list[str]: if isinstance(n, int) and not isinstance(n, bool) and n >= 1: args[args.index("--batch") + 1] = str(min(n, SPLIT_MAX_LANES)) return [] + if os.path.basename(str(cfg.get("exe") or "").replace("\\", "/")).lower().startswith("strata-ink2"): + # strata-ink2 (the official Inkling checkpoint) runs one request at a time: it takes no batch flag + n = cfg.get("parallel") + if isinstance(n, int) and not isinstance(n, bool) and n > 1: + print(f'[strata] "parallel": {n} is ignored: strata-ink2 answers one request at a time', flush=True) + return [] if cfg.get("arch") in ("inkling2_loop", "inkling2", "inkling2_loop_text"): # Inkling-2-Mini supports native 1..64 continuous batching (`--parallel 1|4|8|32|64`)! if "--parallel" in args or "--batch" in args or "--slots" in args: diff --git a/terminal/serve/server_parts/http_api.py b/terminal/serve/server_parts/http_api.py index 709e285697d..2097dbeed8a 100644 --- a/terminal/serve/server_parts/http_api.py +++ b/terminal/serve/server_parts/http_api.py @@ -614,6 +614,8 @@ def check_request_sampling(req) -> None: # Qwen3.6-35B-A3B: the general-task sets (the card's precise-coding set is temperature 0.6, presence_penalty 0) "qwen35moe": {"thinking": {"temperature": 1.0, "top_p": 0.95, "top_k": 20, "presence_penalty": 1.5}, "instruct": {"temperature": 0.7, "top_p": 0.8, "top_k": 20, "presence_penalty": 1.5}}, + # Inkling-2-Mini: generation_config.json (temperature 1.0, nothing else; the thinking level is in the prompt) + "inkling2": {"thinking": {"temperature": 1.0}, "instruct": {"temperature": 1.0}}, # Hy4-Flash (HY-4-Flash-200B): HuggingFace model card defaults when request/config omits sampling "hy4flash": {"thinking": {"temperature": 0.9, "top_p": 1.0}, "instruct": {"temperature": 0.9, "top_p": 1.0}}, diff --git a/terminal/serve/test_inkling_frontend.py b/terminal/serve/test_inkling_frontend.py new file mode 100644 index 00000000000..85f9e91c002 --- /dev/null +++ b/terminal/serve/test_inkling_frontend.py @@ -0,0 +1,140 @@ +"""strata-ink2's side of Inkling 2: its reply form through Ink2OutputParser, its effort words, its thinking close and the {% generation %} +tag. strata-inkling (upstream) keeps InklingOutputParser and thinking off: serve/test_inkling_dialect.py.""" +import random + +import pytest + +from serve import frontend +from serve.frontend import (INK_CALL, INK_END, INK_HEAD, INK_STOP, INK_TEXT, INK_THINK, ChatTemplate, Ink2OutputParser, InklingOutputParser, + effort_kwargs, family_text, openai_to_messages, parser_for_template, use_family) + +TOOLS = [{"name": n, "description": "", "parameters": {"type": "object", "properties": {}}} for n in ("get_weather", "a", "b")] +CASES = { + "think+text": (INK_HEAD + INK_THINK + "17*23 = 391." + INK_END + INK_HEAD + INK_TEXT + "391" + INK_END + INK_STOP, + ("17*23 = 391.", "391", [])), + "text only": (INK_HEAD + INK_TEXT + "a c d<|weird|>e" + INK_END + INK_STOP, ("", "a c d<|weird|>e", [])), + "think+call": (INK_HEAD + INK_THINK + "Need it." + INK_END + INK_HEAD + "get_weather" + INK_CALL + + '{"name":"get_weather","args":{"city":"Paris"}}' + INK_END + INK_STOP, + ("Need it.", "", [("get_weather", {"city": "Paris"})])), + "two calls": (INK_HEAD + INK_THINK + "x" + INK_END + INK_HEAD + "a" + INK_CALL + '{"name":"a","args":{}}' + INK_END + + INK_HEAD + "b" + INK_CALL + '{"name":"b","args":{"k":1}}' + INK_END + INK_STOP, + ("x", "", [("a", {}), ("b", {"k": 1})])), +} + + +@pytest.fixture +def inkling(): + use_family("inkling2", thinks=True) + yield + use_family(None) + + +def _run(stream: str, rng: random.Random): + p = Ink2OutputParser(thinking=True, tools=TOOLS, stream_tools=True) + evs, i = [], 0 + while i < len(stream): + k = rng.randint(1, 7) + evs += p.feed(stream[i:i + k]) + i += k + evs += p.finish("stop") + return ("".join(e.text for e in evs if e.kind == "reasoning"), "".join(e.text for e in evs if e.kind == "content"), + [(e.call.name, e.call.arguments) for e in evs if e.kind == "tool_call"]) + + +@pytest.mark.parametrize("name", CASES) +def test_reply_form_any_split(name): + stream, want = CASES[name] + rng = random.Random(name) + for _ in range(100): # markers split anywhere across deltas + assert _run(stream, rng) == want + + +def test_parser_chosen_by_engine(tmp_path): + """The same template for both engines: strata-inkling (known by its program's name) gets upstream's parser and thinking off, + any other engine on Inkling 2's template is strata-ink2.""" + from serve.server import ByteTokenizer, Service + from serve.test_vram import VramEngine + t = tmp_path / "t.jinja" + t.write_text("{#- <|content_thinking|> <|content_invoke_tool_json|> -#}{{ reasoning_effort }}") + assert parser_for_template(t.read_text()) is InklingOutputParser + tok = ByteTokenizer() + try: + svc = Service(VramEngine(tok), tok, ChatTemplate(t)) + svc.set_family(None) + assert (svc.family, svc.parser_cls, frontend._INK_THINKS) == ("inkling2", Ink2OutputParser, True) + assert svc.template.render([], **effort_kwargs("high")) == "high" + assert svc.template.caps["supports_preserve_reasoning"] is False # (this template drops it; the official one keeps it) + eng = VramEngine(tok) + eng.inkling_engine = True + svc = Service(eng, tok, ChatTemplate(t)) + svc.set_family("inkling2") + assert (svc.family, svc.parser_cls, frontend._INK_THINKS) == ("inkling2", InklingOutputParser, False) + assert svc.template.render([], **effort_kwargs("high")) == "none" + finally: + use_family(None) + + +def test_family_text_and_effort(inkling): + assert family_text("\n\nDone thinking.\n\n\n") == "\n\nDone thinking." + INK_END + INK_HEAD + INK_TEXT + assert effort_kwargs(False) == {"reasoning_effort": "none"} + assert effort_kwargs("high") == {"reasoning_effort": "high"} + assert effort_kwargs(0.5) == {"reasoning_effort": 0.5} + assert effort_kwargs("0.3") == {"reasoning_effort": 0.3} + assert effort_kwargs(0) == {"reasoning_effort": 0.0} + for bad in (1.5, -0.1, "nan"): + with pytest.raises(ValueError): + effort_kwargs(bad) + + +def test_qwen_unchanged(): + use_family(None) + assert family_text("a\n\n\n") == "a\n\n\n" + assert effort_kwargs(False) == {"enable_thinking": False} + assert effort_kwargs("high") == {"reasoning_effort": "xhigh"} + + +def test_thinking_off_is_the_effort_none(inkling): + """Inkling 2's template reads no enable_thinking: "thinking off" from any client is its effort "none" (the model still writes a short + thinking message, which the parser keeps out of the answer).""" + from serve.frontend import anthropic_to_messages + q = [{"role": "user", "content": "hi"}] + assert openai_to_messages({"messages": q, "chat_template_kwargs": {"enable_thinking": False}})[2] == {"reasoning_effort": "none"} + assert anthropic_to_messages({"messages": q, "thinking": {"type": "disabled"}})[2] == {"reasoning_effort": "none"} + use_family(None) + assert openai_to_messages({"messages": q, "chat_template_kwargs": {"enable_thinking": False}})[2] == {"enable_thinking": False} + assert anthropic_to_messages({"messages": q, "thinking": {"type": "disabled"}})[2] == {"enable_thinking": False} + + +def test_tool_result_named_from_its_call(inkling): + msgs, _, _ = openai_to_messages({"messages": [ + {"role": "user", "content": "w?"}, + {"role": "assistant", "content": "", "tool_calls": [{"id": "c1", "type": "function", + "function": {"name": "get_weather", "arguments": "{}"}}]}, + {"role": "tool", "tool_call_id": "c1", "content": "12"}]}) + assert msgs[-1]["name"] == "get_weather" + use_family(None) + msgs, _, _ = openai_to_messages({"messages": [ + {"role": "assistant", "content": "", "tool_calls": [{"id": "c1", "type": "function", + "function": {"name": "f", "arguments": "{}"}}]}, + {"role": "tool", "tool_call_id": "c1", "content": "12"}]}) + assert "name" not in msgs[-1] + + +def test_forced_call_opening(): + from serve.frontend import forced_call, inkling_force + tools = [{"name": "get_weather"}, {"name": "other"}] + named = inkling_force(forced_call({"type": "function", "function": {"name": "get_weather"}}, tools)) + assert named == INK_HEAD + "get_weather" + INK_CALL + '{"name":"get_weather","args":' + assert inkling_force(forced_call("required", tools)) == INK_HEAD + assert inkling_force(None) is None + p = Ink2OutputParser(thinking=True, tools=TOOLS, stream_tools=True) # the opening, then the model's arguments + evs = p.feed(INK_HEAD + INK_THINK + "t" + INK_END) + p.feed(named) + p.feed('{"city":"Lyon"}}' + INK_END + INK_STOP) + evs += p.finish("stop") + assert [(e.call.name, e.call.arguments) for e in evs if e.kind == "tool_call"] == [("get_weather", {"city": "Lyon"})] + + +def test_generation_tag(tmp_path): + t = tmp_path / "t.jinja" + t.write_text("{% for m in messages %}{% generation %}[{{ m.content }}]{% endgeneration %}{% endfor %}") + assert ChatTemplate(t).render([{"role": "user", "content": "hi"}]) == "[hi]" + assert frontend._FAMILY is None diff --git a/terminal/serve/test_inkling_images.py b/terminal/serve/test_inkling_images.py new file mode 100644 index 00000000000..b5dd68d145b --- /dev/null +++ b/terminal/serve/test_inkling_images.py @@ -0,0 +1,114 @@ +"""Inkling 2's pictures: strata-ink2 reads them itself (its ViT runs in the engine), as Hy4-Flash does. The server writes +each picture to a file and names it with an image= key on the GEN line; the template's one <|unused_200054|> per +picture is expanded to its image tokens by the engine. Never the separate picture reader. + + python -m pytest serve/test_inkling_images.py +""" +import base64 +import tempfile +import unittest +from pathlib import Path + +from serve.frontend import ChatTemplate, openai_to_messages, use_family +from serve.server import ByteTokenizer, Service, StrataEngine +from serve.test_vram import VramEngine + +PNG = (b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00" + b"\x00\rIDATx\x9cc\xf8\xff\xff?\x00\x05\xfe\x02\xfe\xa7\x9a\xa0\xa0\x00\x00\x00\x00IEND\xaeB`\x82") +# the image branch of Inkling 2's chat_template.jinja (the model's own file is not in this repository) +TEMPLATE = ('{#- Inkling 2: <|content_thinking|> -#}{%- for m in messages -%}{%- if m.content is string -%}<|message_user|><|content_text|>{{ m.content }}<|end_message|>' + '{%- else -%}{%- for part in m.content -%}{%- if part.type in ("image", "input_image", "image_url") -%}' + '<|message_user|><|content_image|><|unused_200054|><|end_message|>{%- else -%}' + '<|message_user|><|content_text|>{{ part.text }}<|end_message|>{%- endif -%}{%- endfor -%}{%- endif -%}{%- endfor -%}') + + +def request(): + url = "data:image/png;base64," + base64.b64encode(PNG).decode() + msgs, _, _ = openai_to_messages({"messages": [{"role": "user", "content": [ + {"type": "image_url", "image_url": {"url": url}}, {"type": "text", "text": "What is this?"}]}]}) + return msgs + + +class InklingImages(unittest.TestCase): + def service(self, images): + tmp = Path(tempfile.mkdtemp()) + (tmp / "t.jinja").write_text(TEMPLATE) + tok = ByteTokenizer() + engine = VramEngine(tok) + engine.loaded = True + if images is not None: + engine.info["images"] = images + svc = Service(engine, tok, ChatTemplate(tmp / "t.jinja")) + svc.set_family("inkling2") + self.addCleanup(use_family, None) + self.addCleanup(svc.drop_embeddings) + return svc + + def test_the_template_is_known_as_inkling(self): + tmp = Path(tempfile.mkdtemp()) + (tmp / "t.jinja").write_text(TEMPLATE) + tok = ByteTokenizer() + svc = Service(VramEngine(tok), tok, ChatTemplate(tmp / "t.jinja")) + svc.set_family(None) + self.addCleanup(use_family, None) + self.assertEqual(svc.family, "inkling2") + self.assertTrue(svc.engine_reads_images()) + + def test_images_need_an_engine_that_says_images_1(self): + self.assertTrue(self.service(1).has_vision()) + self.assertFalse(self.service(0).has_vision()) + self.assertFalse(self.service(None).has_vision()) + + def test_a_picture_goes_to_the_engine_as_a_file(self): + svc = self.service(1) + svc.prepare(request(), None, {}) + paths = svc.embeddings.hy4 + self.assertEqual(len(paths), 1) + self.assertEqual(Path(paths[0]).read_bytes(), PNG) # a PNG goes as it came (the engine decodes it) + self.assertIsNone(svc.embeddings.path) # no embeddings file: the separate reader is not used + self.assertEqual(svc.render_prompt(request(), None, {}).count("<|unused_200054|>"), 1) # one placeholder a picture + svc.drop_embeddings() + self.assertFalse(Path(paths[0]).exists()) + + def test_a_jpeg_goes_as_pillows_pixels(self): + try: + import io + from PIL import Image + except ImportError: + self.skipTest("no Pillow") + im = Image.new("RGB", (45, 30)) + im.putdata([((x * 37) % 256, (y * 91) % 256, (x * y) % 256) for y in range(30) for x in range(45)]) + buf = io.BytesIO() + im.save(buf, format="JPEG", quality=80) + url = "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode() + msgs, _, _ = openai_to_messages({"messages": [{"role": "user", "content": [ + {"type": "image_url", "image_url": {"url": url}}, {"type": "text", "text": "?"}]}]}) + svc = self.service(1) + svc.prepare(msgs, None, {}) + sent = Path(svc.embeddings.hy4[0]).read_bytes() + self.assertEqual(sent[:2], b"BM") # decoded by Pillow (libjpeg-turbo, as the reference) + want = Image.open(io.BytesIO(buf.getvalue())).convert("RGB") + self.assertEqual(list(Image.open(io.BytesIO(sent)).convert("RGB").getdata()), list(want.getdata())) + + def test_the_gen_line_names_the_picture(self): + keys = StrataEngine.sampling_keys({"strata_hy4_images": ["/tmp/a b%.png"]}) + self.assertIn(" image=/tmp/a%20b%25.png", keys) + + def test_an_engine_without_images_is_a_clear_400(self): + svc = self.service(0) + with self.assertRaises(ValueError) as cm: + svc.prepare(request(), None, {}) + self.assertIn("Inkling 2 engine does not read images", str(cm.exception)) + + def test_qwen_without_a_reader_is_unchanged(self): + tok = ByteTokenizer() + svc = Service(VramEngine(tok), tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja")) + svc.set_family(None) + self.assertFalse(svc.engine_reads_images()) + with self.assertRaises(ValueError) as cm: + svc.prepare(request(), None, {}) + self.assertIn("started without the vision encoder", str(cm.exception)) + + +if __name__ == "__main__": + unittest.main() diff --git a/terminal/setup.py b/terminal/setup.py index 6b2a020ef0e..6ba42fc57d5 100644 --- a/terminal/setup.py +++ b/terminal/setup.py @@ -831,6 +831,16 @@ def ms_meta(repo: str, path: str): "models": {b: {"about": inkling_family.BUILD_ABOUT[b], "ram_gb": int(-(-inkling_fit.BUILDS[b]["footprint_gb"] // 1)), "format": inkling_fit.BUILDS[b].get("format", "strata")} for b in inkling_fit.ORDER}, } } +# The family's other source: Thinking Machines' checkpoint as published (safetensors, pinned revision), run by its own engine program strata-ink2 +# (compiled here for the card; NVIDIA and AMD cards on Linux, ink2_offered) and installed by install_ink2: `--family inkling-2-mini --model official` +# or `--family inkling2`, or the last line of install_inkling2's menu. Not one of INKLING_FAMILIES' "models": that table also feeds the catalog +# (tools/strata_mcp.py, strata launch), which sizes every entry as an SQ build (inkling_fit.BUILDS). +# The files, sizes, memory figures and the rule for the engine's arguments are strata_control/ink2_family.py. +# CBA: strata launch (strata_cli/launch) and its agent harness still take every inkling-2-mini model for strata-inkling (thinking off, +# --parallel, the Vision shard); the official source is set up with ./setup.sh. Upgrade path: route those by the config's exe/arch. +from strata_control import ink2_family # noqa: E402 +INK2_ABOUT = f"the official checkpoint as published (safetensors, a {ink2_family.DOWNLOAD_GB:.1f} GB download), run by strata-ink2" +HF_REVISIONS[ink2_family.REPO] = ink2_family.REVISION # Inkling-2-Mini custom/community local-file & Hugging Face import sources (official HF safetensors + Unsloth GGUFs). # Native `.strata` v1.1 (SQ-20, SQ-15, SQ-10 + Vision) remains the flagship recommended default; `strata-inkling` also @@ -843,8 +853,9 @@ def ms_meta(repo: str, path: str): "files": ("model-00001-of-00001.safetensors", "model.safetensors.index.json", "config.json", "tokenizer.json", "chat_template.jinja"), "dspark": "mtp.safetensors", - "arch": "inkling2_loop", - "exe": "component:strata-inkling", + "arch": ink2_family.ARCH, # this source runs strata-ink2 (install_ink2), not strata-inkling + "exe": ink2_family.EXE, + "model": ink2_family.MODEL, # setup.sh --family inkling-2-mini --model official "recommended_default": False, }, "gguf": { @@ -939,6 +950,7 @@ def build_inkling_import_args( UNSLOTH_REPO: {**UNSLOTH_V31_SHARDS, **UNSLOTH_SHARDS, **UNSLOTH_IQ4_XS_SHARDS, **UNSLOTH_BIG_SHARDS}, "unsloth/Qwen3.6-35B-A3B-MTP-GGUF": QWEN36_FILES, "agentionai/Qwen3.8-Flash-Next-Gyro-GGUF": GYRO_FILES, + ink2_family.REPO: ink2_family.FILES, } # the files of a repository at a commit other than HF_REVISIONS' (UNSLOTH_V31_REVISION): (repository, commit) -> name -> (bytes, sha256); file_pin looks here first REV_PINS = {(UNSLOTH_REPO, UNSLOTH_V31_REVISION): {**UNSLOTH_V31_SHARDS, **UNSLOTH_Q4_V31_SHARDS}} @@ -2629,7 +2641,8 @@ def find_vcvars(cuda_v=None): return v if v and v.exists() else None -CMAKE_MIN = (3, 24) # CMakeLists.txt: cmake_minimum_required(VERSION 3.24) +CMAKE_MIN = (3, 25, 2) # CMakeLists.txt says 3.24, but the engine's CUDA20 targets configure with nvcc 13 from CMake 3.25.2 on + # (3.24.3 and Debian 12's 3.25.1: "does not support the language dialect CUDA20") def _tool_version(path, name): @@ -2661,7 +2674,7 @@ def find_tool(name): runs, version = _tool_version(c, name) if not runs: continue - if name == "cmake" and version and version[:2] < CMAKE_MIN: + if name == "cmake" and version and version[:3] < CMAKE_MIN: older = older or c continue return c @@ -6585,7 +6598,7 @@ def tool_usable(name): return False if name == "cmake": runs, version = _tool_version(found, name) - return runs and (not version or version[:2] >= CMAKE_MIN) + return runs and (not version or version[:3] >= CMAKE_MIN) return True @@ -7690,6 +7703,8 @@ def choices_from_config(cfg_path: Path) -> dict: if own is not None: # Qwen3.6 / Hy4-Flash / Inkling-2-Mini: own sizes; no Flash-Next KV / projection settings d = special_fams[own] size = next((m for m in d["models"] if m.lower() == tag[len(d["tag"]):].lower()), None) + if own == inkling_family.FAMILY and tag[len(d["tag"]):].lower() == ink2_family.MODEL: + size = ink2_family.MODEL # the official checkpoint's config (install_ink2) a = cfg.get("args", []) ctx = a[a.index("--max-context") + 1] if "--max-context" in a and a.index("--max-context") + 1 < len(a) else None vis = cfg.get("vision") @@ -8568,7 +8583,13 @@ def _start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open say(" " + "-" * 100) size = f'about {gb:.0f} GB' if gb >= 1 else '34-55 GB' a_ = cfg["args"] - if "--mmap-experts" in a_ and "--resident-budget-gib" not in a_ and "--resident-experts" not in a_: + if cfg.get("arch") == ink2_family.ARCH: # Inkling-2-Mini: its own figures (strata_control/ink2_family.py) + say(f" Starting {cfg.get('model_name', 'the model')}: " + ( + f"it keeps the experts the card does not hold in RAM (about {ink2_family.OFFLOAD_RAM_GIB:.1f} GiB, locked for the GPU)" + + (f", and {a_[a_.index('--conversation-cache-mib') + 1]} MiB for its conversation cache." if "--conversation-cache-mib" in a_[:-1] else ".") + if "--vram-reserve-mib" in a_ else + f"it loads its {ink2_family.FILES['model-00001-of-00001.safetensors'][0] / 1e9:.0f} GB onto the graphics card.")) + elif "--mmap-experts" in a_ and "--resident-budget-gib" not in a_ and "--resident-experts" not in a_: # #505: the mapped low-RAM mode loads nothing into RAM up front (the server's narrator says the same) say(f" Starting {cfg.get('model_name', 'the model')}: it maps {size} of experts from the model files (the OS " "file cache reads them).") @@ -10286,6 +10307,261 @@ def install_hy4_flash(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopt return start(cfg_path, port) +INK2_SOURCES = ("CMakeLists.txt", "cmake", "include", "src/inkling2", "src/image/vae") +INK2_HIP_ARCHS = tuple(a for a in AMD_ARCHS if a.startswith(("gfx10", "gfx11", "gfx12"))) + + +def gpu_used_mib(g) -> float: + """The VRAM in use on this NVIDIA card now (nvidia-smi memory.used, MiB); 0 when it does not say.""" + text = out(["nvidia-smi", "-i", str(g.get("index", 0)), "--query-gpu=memory.used", "--format=csv,noheader,nounits"]).strip() + try: + return float(text.splitlines()[0]) + except (ValueError, IndexError): + return 0.0 + + +def ink2_offered(hip: bool) -> bool: + """Is Inkling-2-Mini offered: an NVIDIA (CUDA) or AMD (ROCm/HIP) card on Linux (strata-ink2 uses POSIX calls), outside the app (which compiles + nothing: no ready-made engine carries strata-ink2).""" + return sys.platform.startswith("linux") and not CONTROL + + +def ink2_cpu_threads() -> int: + """strata-ink2's --cpu-threads: threads PER NUMA node. The engine pins them to that node's physical cores (node 0 less the engine's own + thread) and keeps each expert's RAM on one node, so a thread reads only its own node's memory. The count follows the Strata engine's rule for + its CPU expert pool (plan_pool_workers): one socket's physical cores less the engine's thread, one fewer on a big CPU (22 of 24 per socket was + measured on a 2 x 24-core Xeon), the performance cores and half the efficiency cores on a hybrid CPU. CBA: per socket, not per NUMA node; the + engine caps it at each node's cores, so a CPU with several nodes per socket gets fewer threads than it could use""" + logical, cores = cpu_core_layout() + return plan_pool_workers(logical, cores, hybrid=cpu_cores()) + + +def ink2_build(gpu, yes, hip=False, amd=None) -> tuple[Path, list]: + """strata-ink2 compiled for this card, in its own build folder (build-ink2 for CUDA, build-ink2-hip for ROCm/HIP) and copied into engine/ with + its own stamp: the ready-made engines do not carry it. Compiled again when its sources, backend or the card's generation change. Returns + (the program, the GPU runtime library folders it runs with).""" + eng = engine_dir(13) + eng.mkdir(exist_ok=True) + exe = eng / ink2_family.EXE + stamp = eng / (ink2_family.EXE + ".json") + try: + meta = json.loads(stamp.read_text(encoding="utf-8")) + except (OSError, ValueError): + meta = {} + src = source_hash(INK2_SOURCES) + if hip: + raw_archs = gpu.get("archs") or ( + [gpu["arch"]] if gpu.get("arch") else + [amd["arch"]] if isinstance(amd, dict) and amd.get("arch") else + [g["arch"] for g in (amd or []) if isinstance(g, dict) and g.get("arch")] + ) + archs = sorted({a.split(":")[0] for a in arch_names(raw_archs)}) + if exe.is_file() and meta.get("backend") == "hip" and meta.get("src") == src and set(archs) <= set(arch_names(meta.get("archs"))): + ok(f"engine: {exe} (already compiled for this PC)") + return exe, meta.get("lib_dirs") or [] + if not (shutil.which("c++") or shutil.which("g++")) or not shutil.which("git"): + fail("a C++ compiler and git are needed to compile the AMD engine", + "Ubuntu/Debian: sudo apt install build-essential git Fedora: sudo dnf install gcc-c++ git") + root, dirs = rocm_root(archs) + libs = [str(Path(d).parent) for d in dirs[1:]] + bitcode = next((p for p in (root / "lib" / "llvm" / "amdgcn" / "bitcode", root / "amdgcn" / "bitcode") if p.is_dir()), + root / "amdgcn" / "bitcode") + os.environ.update({"HIP_PLATFORM": "amd", "HIP_COMPILER": "clang", "HIP_RUNTIME": "rocclr", "ROCM_PATH": str(root), + "HIP_PATH": str(root)}) + os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(dirs + [os.environ.get("LD_LIBRARY_PATH", "")]).rstrip(os.pathsep) + os.environ["PATH"] = os.pathsep.join([str(root / "bin"), str(rocm_clang(root).parent), os.environ.get("PATH", "")]) + bdir = ROOT / "build-ink2-hip" + say(" Compiling the Inkling-2-Mini engine (strata-ink2) for " + ", ".join(archs) + " (a few minutes, once) ...") + cmake_build(engine_src(), bdir, ink2_family.EXE, + ["-DSTRATA_ENABLE_HIP=ON", "-DSTRATA_ENABLE_CUDA=OFF", "-DSTRATA_BUILD_TESTS=OFF", + "-DCMAKE_HIP_ARCHITECTURES=" + ";".join(archs), + f"-DCMAKE_HIP_COMPILER={rocm_clang(root)}", f"-DCMAKE_HIP_COMPILER_ROCM_ROOT={root}", + "-DCMAKE_PREFIX_PATH=" + ";".join([str(root), *libs]), + f"-DCMAKE_HIP_FLAGS=-isystem {root}/include --rocm-path={root} --rocm-device-lib-path={bitcode}"], + None, "") + shutil.copy2(bdir / ink2_family.EXE, exe) + stamp.write_text(json.dumps({"backend": "hip", "archs": archs, "src": src, "lib_dirs": dirs}, indent=1), encoding="utf-8") + ok(f"engine compiled: {exe}") + return exe, dirs + archs = sorted({int(x) for x in gpu.get("archs", [gpu["arch"]])}) + prev_archs = meta.get("archs") or [] if meta.get("backend", "cuda") == "cuda" else [] + if exe.is_file() and meta.get("backend", "cuda") == "cuda" and meta.get("src") == src and set(archs) <= set(prev_archs): + ok(f"engine: {exe} (already compiled for this PC)") + return exe, meta.get("cuda_dirs") or [] + archs = sorted(set(archs) | set(prev_archs)) + nvcc, vcvars = install_build_tools({**gpu, "archs": archs, "toolkit": 13}, yes) + bdir = ROOT / "build-ink2" + say(" Compiling the Inkling-2-Mini engine (strata-ink2) for " + ", ".join(f"sm_{x}" for x in archs) + " (a few minutes, once) ...") + cmake_build(engine_src(), bdir, ink2_family.EXE, + ["-DSTRATA_ENABLE_CUDA=ON", "-DSTRATA_BUILD_TESTS=OFF", f"-DCMAKE_CUDA_ARCHITECTURES={';'.join(str(x) for x in archs)}", + f"-DCMAKE_CUDA_COMPILER={nvcc}", *toolkit_root_defs(nvcc), *host_compiler_defs(True)], + vcvars, "build-ink2.bat") + shutil.copy2(bdir / ink2_family.EXE, exe) + bindir = Path(nvcc).parent # the toolkit's own libraries (cuBLAS, the runtime), as build_engine keeps them + dirs = [str(d) for d in (bindir, bindir.parent / "lib64") if d.is_dir()] + stamp.write_text(json.dumps({"backend": "cuda", "src": src, "archs": archs, "cuda_dirs": dirs}, indent=1), encoding="utf-8") + ok(f"engine compiled: {exe}") + return exe, dirs + + +def ink2_tokenizer(model_dir: Path, pack: Path) -> Path: + """The tokenizer directory serve reads, from the checkpoint's tokenizer.json and chat_template.jinja (the o200k split rule; the end of a + reply is generation_config.json's eos_token_id).""" + tok = pack / "tokenizer" + if (tok / "vocab.json").is_file() and (tok / "chat_template.jinja").is_file(): + return tok + sys.path.insert(0, str(ROOT / "tools")) + import strata_tokenizer + eos = json.loads((model_dir / "generation_config.json").read_text(encoding="utf-8"))["eos_token_id"] + strata_tokenizer.extract_hf(model_dir, pack, ink2_family.PRE_TOKENIZER, {"eos": int(eos)}) + return tok + + +def install_ink2(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted): + """Steps 2-7 for the official checkpoint of Inkling-2-Mini (--model ink2_family.MODEL of the Inkling family; install_inkling2 hands it + over): the context, the engine program strata-ink2 (compiled here), the checkpoint's files (pinned revision, size and SHA-256), the + tokenizer from its tokenizer.json, the config and the start script. The engine's arguments come from the card (strata_control/ink2_family.py + engine_args): every expert on it with the draft layer when they fit, else the expert offload, the card holding the most used experts and the + CPU computing the others.""" + F = ink2_family + fam = INKLING_FAMILIES[family] + if not ink2_offered(hip): + fail(f"{fam['title']} runs on NVIDIA or AMD cards on Linux only so far: its engine (strata-ink2) is compiled on this PC" + + (" (the app compiles no engine)" if CONTROL else ""), + "choose another model, or set it up from a Linux checkout (./setup.sh) with an NVIDIA or AMD card") + if hip: + arch = str(gpu.get("arch") or "") + if not any(gfx_arch_is(arch, a) for a in INK2_HIP_ARCHS): + fail(f"{fam['title']} on AMD needs a wave32 RDNA GPU ({', '.join(INK2_HIP_ARCHS)}); this one is {arch or 'unknown'}", + "choose another model for this card") + elif cuda_tk == 12 or int(gpu.get("arch") or 0) < CUDA13_MIN_ARCH: + fail(f"{fam['title']} needs an NVIDIA card from the RTX 20 series (sm_75) or newer; this one is sm_{gpu.get('arch')}", + "choose another model for this card") + if multi: + warn(f"{fam['title']} runs on one GPU: using GPU {gpu.get('index', 0)} ({gpu_name(gpu)}) only") + model = F.MODEL + ok(f"the published checkpoint ({F.DOWNLOAD_GB:.1f} GB), run by strata-ink2") + tag = fam["tag"] + model + vram_mib = float(gpu.get("vram_gb", 0.0)) * 1024 + display = False if hip else gpu_drives_display(gpu) + # the VRAM kept free for other programs: the person's own number, else what a card that drives the screen needs (#779), else none (the engine + # keeps its own margin for what it allocates after the experts) + reserve = a.vram_reserve_mib if a.vram_reserve_mib is not None else (DISPLAY_RESERVE_MIB if display else 0) + used = 0.0 if hip else gpu_used_mib(gpu) # a desktop's VRAM now: the offload's pools are sized from what is free at start + rec_ctx = F.recommended_context(vram_mib, reserve, used) + if a.context: + ctx = a.context + else: + say() + say(" Context length = how much text the model can see at once. Its cache takes " + f"{F.kv_bytes_per_token(True) * 32768 / 2**30:.1f} GB of VRAM per 32K tokens:") + for i, c in enumerate(F.CONTEXTS, 1): + say(f" {i}) {c // 1024}K tokens" + (" (every expert fits on your GPU)" if F.resident_fits(vram_mib, c, reserve) else "") + + (" (recommended for your GPU)" if c == rec_ctx else "")) + ctx = F.CONTEXTS[int(ask("Context?", [str(i) for i in range(1, len(F.CONTEXTS) + 1)], str(F.CONTEXTS.index(rec_ctx) + 1), a.yes)) - 1] + ok(f"context: {ctx} tokens") + _, avx2, _ = cpu_info() + threads = ink2_cpu_threads() if avx2 and not is_arm64() else None # the engine's CPU experts need AVX2 + FMA + F16C on x86 + if F.resident_fits(vram_mib, ctx, reserve): + ok("every expert fits on the card: they stay there, with the draft layer (mtp.safetensors) for faster answers") + else: + kv = F.offload_kv(vram_mib, reserve, used, ctx) # the conversation memory's format + room = F.offload_room_mib(vram_mib, ctx, used, kv) # what a reserve can take with the expert pools at the engine's minimum + if room < 0: + confirm_risk(f"a {vram_mib / 1024:.0f} GB card ({used:.0f} MiB of it in use now) is too small for {fam['title']} at a {ctx // 1024}K " + f"context: the engine needs about {-room} MiB more VRAM for its expert pools and may stop at start", bool(a.family), a.yes, + f"the card is too small for {fam['title']} at a {ctx // 1024}K context", + "choose a smaller context (--context 8192), or another model", " Install it anyway?") + warn(f"installing {fam['title']} on a {vram_mib / 1024:.0f} GB card, as you chose") + elif reserve > room and a.vram_reserve_mib is None: + warn(f"only {room} MiB of VRAM can be kept free for other programs on this card at a {ctx // 1024}K context (not {reserve}): " + "the engine's expert pools need the rest") + reserve = room + elif reserve > room: + warn(f"--vram-reserve-mib {reserve} leaves the engine's expert pools less than they need at a {ctx // 1024}K context (at most " + f"{room} MiB can be kept free): it would stop at start. Kept as you chose") + ok(f"the card holds the most used experts and the others stay in RAM ({reserve} MiB of VRAM kept free for other programs); the " + f"conversation memory grows into the card as it is used" + (f" (8-bit, {kv}, to leave the experts room)" if kv != "f16" else "")) + if threads: + ok(f"CPU experts: {threads} threads per CPU socket compute the experts the card does not hold") + else: + warn("this CPU cannot run the engine's CPU experts (they need AVX2 on an x86 CPU): the experts the card does not hold are copied to it " + "as they are needed, which is slower") + if ram < F.RAM_GB: + confirm_risk(f"the experts the card does not hold stay in RAM: {fam['title']} needs about {F.RAM_GB} GB of RAM here, this PC has " + f"{ram:.0f} GB, so it may not start", bool(a.family), a.yes, f"{fam['title']} needs about {F.RAM_GB} GB of RAM on this card", + f"--family {family} --model {model} --yes installs it anyway", " Install it anyway?") + warn(f"installing {fam['title']} with {ram:.0f} GB of RAM, as you chose") + if display and a.vram_reserve_mib is None: + say(" This card drives a display, so VRAM is kept free for it (--vram-reserve-mib N to change how much)") + ok("images: on (the engine reads pictures itself; nothing is loaded for them until the first one)") + if a.vision in ("no", "none"): + warn(f"--vision {a.vision}: {fam['title']}'s engine reads pictures itself, there is nothing to turn off (no download, no memory until a picture)") + cache_mib, spare = F.conversation_cache_mib(ram, not F.resident_fits(vram_mib, ctx, reserve)) + if cache_mib: + ok(f"conversation cache: {cache_mib} MiB of RAM (an agent's next turn reads only what is new)") + else: + warn(f"conversation cache: off - {spare:.1f} GB of RAM are left beside the model and the system, less than the " + f"{F.CACHE_MIB[-1] // 1024 + F.CACHE_SPARE_MIN_GIB:.1f} GB it needs; every turn of an agent re-reads its whole conversation") + if a.rope_scaling or a.rope_scale or a.kv or a.resident_budget_gib is not None or a.low_ram not in (None, "auto") or getattr(a, "parallel", None): + warn(f"--rope-scaling / --kv / --resident-budget-gib / --low-ram / --parallel are other models' settings: {fam['title']} does not use them") + own = bool(a.gguf_dir) # --gguf-dir: a folder that already holds the checkpoint (checked, never changed) + folder = Path(a.gguf_dir) if own else Path(a.models_dir) / tag + left = sum(size for n, (size, _) in F.FILES.items() if not ((folder / n).is_file() and done(folder / n))) / 1e9 + if not own and left and free_gb(folder) < left: + fail(f"not enough free disk space in {folder}: need ~{left:.0f} GB, {free_gb(folder):.0f} GB free", "use --models-dir on a bigger drive") + + step(3, "Python packages") + pip_install(runtime_packages(), "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil, textual (the screens)") + + step(4, "the Inkling-2-Mini engine") + exe, lib_dirs = ink2_build(gpu, a.yes, hip=hip, amd=amd) + + step(5, f"downloading {fam['title']}") + for name, (size, sha) in F.FILES.items(): + dst = folder / name + if own: + if not dst.is_file(): + fail(f"{dst} is missing", f"put the published {name} in {folder}, or drop --gguf-dir to download it") + else: + download(hf(F.REPO) + name, dst) + verify_sha256(dst, size, sha, own=own) + ok(f"model files: {folder}") + + step(6, "preparing the model for Strata") + data, _ = data_folder_for(a) + tok = ink2_tokenizer(folder, data / "packs" / tag.lower()) + ok(f"tokenizer: {tok}") + + step(7, "writing the start script") + args = F.engine_args(str(folder), ctx, vram_mib, reserve, threads, used, cache_mib) + cfg = {"exe": str(exe), "args": args, "cwd": str(ROOT), "tokenizer": str(tok), "model_name": F.NAME, "arch": F.ARCH, + "log": str(home() / f"strata-{tag.lower()}.log"), "lib_dirs": lib_dirs, "port": port} + if hip: + cfg["backend"] = "hip" + if gpu.get("count", 1) > 1 or a.gpu is not None: + cfg["gpu"] = gpu["index"] + cfg["gpus_asked"] = True + if a.host: + cfg["host"] = a.host + if a.api_key: + cfg["api_key"] = a.api_key + if a.browser is not None: + cfg["open_browser"] = a.browser + cfg_path = home() / f"strata-{tag.lower()}.json" + write_setup_config(cfg_path, cfg, adopted if adopted is not None and adopted.name == cfg_path.name else None, explicit_args(a)) + script = write_run_script(tag, cfg_path, port, cfg.get("open_browser") is not False) + ok(f"start script: {script.name}") + say() + say("All set.") + say(f" API (OpenAI): http://127.0.0.1:{port}/v1 (any API key; model name: anything)") + say(f" API (Anthropic): http://127.0.0.1:{port}/v1/messages") + say(f" Next time: just run ./setup.sh (or {script.name}) - it starts right away") + if a.no_start: + return 0 + return start(cfg_path, port) + + def inkling_folder(a) -> Path: if getattr(a, "gguf_dir", None): p = Path(a.gguf_dir) @@ -10522,6 +10798,8 @@ def install_inkling2(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte say(f" {fam['title']} - {fam['by']}: {fam['about']}") ok(f"model: {fam['title']}") say(f" Its license: {fam['license']}") + if a.model == ink2_family.MODEL: # the official checkpoint: strata-ink2, its own installer + return install_ink2(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted) names = list(fam["models"]) if a.model and a.model not in names: fail(f"{fam['title']} has no {a.model} model file", "choose one of: " + ", ".join(names)) @@ -10538,6 +10816,8 @@ def install_inkling2(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte vision = a.vision not in ("no", "none") want_ctx = a.context or inkling_family.DEFAULT_CONTEXT lines = inkling_menu_lines(vram_gib, ram_gib, unified, want_ctx, vision, igpu=igpu, arch=arch) + if ink2_offered(hip): # the official checkpoint: strata-ink2, its own installer (install_ink2) + lines.append((ink2_family.MODEL, f"{ink2_family.MODEL:7s} {INK2_ABOUT} (NVIDIA or AMD, Linux)")) rec = inkling_fit.recommend(vram_gib, ram_gib, unified, want_ctx, vision, igpu=igpu, arch=arch) say() order = [b for b, _ in lines] @@ -10545,6 +10825,8 @@ def install_inkling2(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte say(f" {i}) {text}") model = a.model or order[int(ask("Which size?", [str(i) for i in range(1, len(order) + 1)], str(order.index(rec["build"]) + 1), a.yes)) - 1] ok(f"size: {model}") + if model == ink2_family.MODEL: + return install_ink2(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted) tag = fam["tag"] + model ctx = a.context or inkling_family.DEFAULT_CONTEXT if not a.context: @@ -11169,23 +11451,24 @@ def main() -> int: say(" " + retired.NOT_OFFERED) # DeepSeek: no longer offered (strata_control/retired.py) return 2 _hy4_ask = _peek("--family") in HY4_FAMILIES or bool(_peek("--model") and model_alias(_peek("--model")) in HY4_FAMILIES["hy4-flash"]["models"]) - _ink_ask = _peek("--family") in INKLING_FAMILIES or bool(_peek("--model") and model_alias(_peek("--model")) in INKLING_FAMILIES["inkling-2-mini"]["models"]) + _ink_ask = _peek("--family") in (*INKLING_FAMILIES, ink2_family.FAMILY) or bool(_peek("--model") and model_alias(_peek("--model")) in INKLING_FAMILIES["inkling-2-mini"]["models"]) if sys.platform == "darwin" and not CONTROL and not _hy4_ask and not _ink_ask: # a Mac: metal/setup_mac.py (the Metal engine); the app (Control mode), Hy4-Flash and Inkling-2-Mini go on below. return mac_setup(sys.argv[1:]) # (after the retired names above, so a Mac gets the same sentence and exit 2, M1 11-16) - if (_peek("--family") and _peek("--family") not in {**FAMILIES, **OWN_PATH_FAMILIES, **HY4_FAMILIES, **INKLING_FAMILIES}) \ + if (_peek("--family") and _peek("--family") not in {**FAMILIES, **OWN_PATH_FAMILIES, **HY4_FAMILIES, **INKLING_FAMILIES, ink2_family.FAMILY: None}) \ or (_peek("--model") and not _peek("--family") and model_alias(_peek("--model")) not in MODELS and not any(model_alias(_peek("--model")) in f["models"] for f in {**OWN_PATH_FAMILIES, **HY4_FAMILIES, **INKLING_FAMILIES}.values())): feed_models_setup(_peek("--feed")) # a name the built-in tables do not know may be a model of the signed feed if _peek("--family") in FEED_UNAVAILABLE: fail(f"{FEED_UNAVAILABLE[_peek('--family')]['title']} is {FEED_UNAVAILABLE[_peek('--family')]['reason']}") ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--family", choices=list(FAMILIES) + list(PREVIEW_FAMILIES) + list(HY4_FAMILIES) + list(INKLING_FAMILIES), + ap.add_argument("--family", choices=list(FAMILIES) + list(PREVIEW_FAMILIES) + list(HY4_FAMILIES) + list(INKLING_FAMILIES) + [ink2_family.FAMILY], help="qwen = Qwen3.8-Flash-Next, swift = Swift 1.5, qwen36 = Qwen3.6-35B-A3B (pictures with --vision, " "several requests at once with --parallel; docs/QWEN36.md), hy4-flash = Tencent Hy4-Flash (SQ-64 / SQ-96 / SQ-128), " - "inkling-2-mini = Thinking Machines Inkling-2-Mini (SQ-20 / SQ-15 / SQ-10)") + "inkling-2-mini = Thinking Machines Inkling-2-Mini (SQ-20 / SQ-15 / SQ-10; official = the published checkpoint, " + "NVIDIA or AMD cards on Linux, docs/MODELS.md), inkling2 = inkling-2-mini --model official") ap.add_argument("--model", type=model_alias, choices=list(dict.fromkeys([*MODELS, *(m for f in PREVIEW_FAMILIES.values() for m in f["models"]), *(m for f in HY4_FAMILIES.values() for m in f["models"]), - *(m for f in INKLING_FAMILIES.values() for m in f["models"])]))) + *(m for f in INKLING_FAMILIES.values() for m in f["models"]), ink2_family.MODEL]))) ap.add_argument("--context", type=int) ap.add_argument("--rope-scaling", choices=["none", "linear", "yarn"], help="the RoPE extension for a context past the model's trained 262144: linear (position " @@ -11350,6 +11633,10 @@ def main() -> int: if getattr(a, "dsv41_package", None): # DeepSeek's engine package: no longer offered (strata_control/retired.py) say(" " + retired.NOT_OFFERED) return 2 + if a.family == ink2_family.FAMILY: # --family inkling2: the official checkpoint's source of the Inkling family + if a.model and a.model != ink2_family.MODEL: + ap.error(f"--family {ink2_family.FAMILY} is the official checkpoint (--model {ink2_family.MODEL}); the SQ builds are --family {inkling_family.FAMILY}") + a.family, a.model = inkling_family.FAMILY, ink2_family.MODEL if a.model and a.model not in MODELS and a.family not in PREVIEW_FAMILIES and a.family not in HY4_FAMILIES and a.family not in INKLING_FAMILIES: ap.error(f"--model {a.model} is a size of " + ", ".join(f"--family {f}" for f, d in {**PREVIEW_FAMILIES, **HY4_FAMILIES, **INKLING_FAMILIES}.items() if a.model in d["models"])) @@ -11738,7 +12025,7 @@ def main() -> int: rest = [*(f for f in OWN_PATH_FAMILIES if not OWN_PATH_FAMILIES[f].get("feed")), *(f for f in OWN_PATH_FAMILIES if OWN_PATH_FAMILIES[f].get("feed")), *feed_late, *(f for f in HY4_FAMILIES if hy4_offered(a)), - *(f for f in INKLING_FAMILIES if inkling_offered(a))] + *(f for f in INKLING_FAMILIES if inkling_offered(a) or ink2_offered(hip))] for j, f in enumerate(rest, len(fams) + 1): # families with an engine path of their own d = {**FAMILIES, **OWN_PATH_FAMILIES, **HY4_FAMILIES, **INKLING_FAMILIES}[f] say(f" {j}) {cyan}{d['title']:20s}{reset} {d['by']} - {d['about']} [new]" + (f" ({FEED_UNAVAILABLE[f]['reason']})" if f in FEED_UNAVAILABLE else "")) diff --git a/terminal/strata_cli/launch/harness.py b/terminal/strata_cli/launch/harness.py index 4a7005cd440..b2d1083cc9d 100644 --- a/terminal/strata_cli/launch/harness.py +++ b/terminal/strata_cli/launch/harness.py @@ -109,7 +109,7 @@ def _display_name(t: Target) -> str: m = (t.model or "").lower() if m.startswith("hy4-flash"): return "Tencent Hy4-Flash (Strata, local)" - if m.startswith("inkling-2-mini"): + if m.startswith(("inkling-2-mini", "inkling2")): # (inkling2-mini: strata-ink2, which thinks: the default reasoning entry) return "Inkling-2-Mini (Strata, local)" if m.startswith("qwen3.6") or m.startswith("qwen36"): return "Qwen3.6-35B-A3B (Strata, local)" diff --git a/terminal/strata_control/ink2_family.py b/terminal/strata_control/ink2_family.py new file mode 100644 index 00000000000..65f3b973356 --- /dev/null +++ b/terminal/strata_control/ink2_family.py @@ -0,0 +1,210 @@ +"""Inkling-2-Mini (Thinking Machines' checkpoint as published on Hugging Face): its files (exact sizes and SHA-256 at a pinned revision), its engine +program (strata-ink2, built from engine/src/inkling2) and the rule that turns this PC's card, RAM and CPU into the engine's arguments. Pure data and +small functions; setup.py's install_ink2 does the downloads, the build and the questions. In setup it is one source ("model") of the +Inkling family (setup.py INKLING_FAMILIES, whose SQ builds run upstream's strata-inkling). + +The pins: the four LFS files' SHA-256 are Hugging Face's own (the repository tree's `lfs.oid`); the small files' SHA-256 were computed from copies whose +git blob id matched the tree's `oid` at REVISION, so they are that revision's bytes. README.md, .gitattributes and tiktoken/tokenizer.model are not +downloaded: neither the engine nor the tokenizer pack reads them. +""" + +from __future__ import annotations + +FAMILY = "inkling2" # setup.sh --family inkling2: --family inkling-2-mini --model official +ARCH = "inkling2" # the run config's "arch" (serve: the family's sampling defaults); never strata-inkling's inkling2_loop +MODEL = "official" # its "model" in the Inkling family; run config file: strata-inkling-2-mini-official.json +# the run config's model_name (the API's model id): not upstream's "inkling-2-mini" prefix, which strata launch's agent harness, tune and pictures +# take for strata-inkling (thinking off, --parallel, the Vision shard) +NAME = "inkling2-mini" +EXE = "strata-ink2" # Linux only: the engine includes sys/mman.h and unistd.h +ABOUT = ("a 128-expert mixture of experts with NVFP4 / MXFP8 experts, read as published (19.5 GB); " + "NVIDIA (CUDA) and AMD (ROCm/HIP) cards on Linux, the experts that do not fit the card stay in RAM") +REPO = "thinkingmachines/Inkling-2-Mini" +REVISION = "ed40e7da625f594fc9c4990f5f66be24873c22d7" # 2026-11-20 ("Declare the dtype at the top level of config.json") +#: Pictures: strata-ink2 reads them itself (its ViT, ink2_vision.cuh) and says INFO images=1 at its start, which is what the server enables image +#: input from (Service.engine_reads_images): nothing to write in the run config. The engine takes no file for it beyond the checkpoint (its +#: preprocessing constants are processor_config.json's, built in); the file stays in the download set as part of the published checkpoint +VISION = True +#: the ViT weights, pinned in host memory at the first picture (634 MB BF16 + 6 MB fp32) +VISION_RAM_GIB = 0.65 + +#: file name -> (bytes, sha256), in download order (the big ones first: a disk that fills up says so early) +FILES = { + "model-00001-of-00001.safetensors": (19_526_019_168, "65e60f51aa1284d4fb022584908c315270334d991828bb774af60584523539d1"), + "mtp.safetensors": (635_801_416, "7c3b651317f01f73bcf4e1dceba66ef8b7e1a1eac6bc171e882e690a4b10a1d2"), + "tokenizer.json": (26_178_678, "7f332727f9a3f093dd452a39cc978e6757627e5dad1b0673aa4e75174f236dd6"), + "model.safetensors.index.json": (109_300, "c1631065b7b00787993522dddc66a68b3abee869192977fb3dcb796e63bc5838"), + "hf_quant_config.json": (67_924, "7c656207d3ce37879c7be209a036b0dde43bf01f78159bff06880b868ed57143"), + "tokenizer_config.json": (13_235, "bf09342d285139fd37ce10c70878af1d52cb390e9901e10248654293a80ee636"), + "chat_template.jinja": (6_868, "53a9035f3255945704b5857657cfb00c1165090c0641c4f782a0cbf268cc16dc"), + "config.json": (2_722, "a7a349601f0984c4abf999c480ef775d8567d21f5f84b4e8a3e035b44f288dc2"), + "special_tokens_map.json": (529, "c16f44b3594563d82743ddb0417a2be1bfe3e2000dfad2da4b8f32554593e1a0"), + "processor_config.json": (461, "d7350adce18c8be4b607f261c8f0f7eabbf720bb7aaf648a43d4f8372bbacc2d"), + "generation_config.json": (98, "a08737c07a65a8fdf69f7cf086576210e5aad4b241437090b26d7b0c4f7905f7"), +} +DOWNLOAD_GB = sum(s for s, _ in FILES.values()) / 1e9 +#: the tokenizer pack (tools/strata_tokenizer.py extract_hf): the o200k split rule +PRE_TOKENIZER = "gpt-4o" + +# ---- the engine's memory (engine/src/inkling2/ink2_engine.cu) +#: K/V per context token, fp16 (--kv f16): a full-attention layer (L % 6 == 5: 5, 11, 17, 23) keeps the whole context, the others a 1024-token +#: window whose size does not grow with it. Layers 6-17 run three times, each pass with its own K/V, so the full-attention visits are 5, 11, 17, 23 +#: + 11, 17 twice more = 8; each holds K and V of 8 heads x 128 at 2 bytes. --spec 1 adds the drafter's one global layer (mtp.safetensors: 3 layers, +#: 0 and 2 local). Measured on an RTX 3090 (nvidia-smi, --spec 1, --chunk 1024): 8K -> 32K context +864 MiB = 36864 bytes a token. +KV_HEADS, HEAD_DIM, KV_FULL_VISITS, DRAFT_FULL_LAYERS = 8, 128, 8, 1 +#: bytes of one full-attention visit's K and V per token in each --kv format (the engine's kv_cell_bytes): f16 2 x 1024 x 2; i8r, i8 and k8v8 all +#: int8 K and V with an fp16 scale per 64 values, 2 x (1024 + 32). Of those three, i8r is the closest to f32 K/V (KL_VS_F32 below) +KV_CELL_BYTES = {"f16": 4096, "i8r": 2112} +#: KL(f32 K/V || format) per position, the routing forced to one f32 recording, served flags (--tc 1 --chunk 1024): (mean, p99, top-1 %). +#: p1600: 1600 tokens of prose; c23k: 23,265 tokens of mixed prose, French, C++ and Python. f16 matched f32 bit for bit on both +KL_VS_F32 = {"p1600": {"i8": (1.00e-4, 1.59e-3, 99.50), "i8r": (2.04e-5, 2.41e-4, 99.88), "k8v8": (3.39e-5, 4.66e-4, 99.94)}, + "c23k": {"i8": (1.32e-4, 1.69e-3, 99.61), "i8r": (3.52e-5, 4.09e-4, 99.80), "k8v8": (5.34e-5, 6.41e-4, 99.73)}} + + +def kv_bytes_per_token(spec: bool, kv: str = "f16") -> int: + return (KV_FULL_VISITS + (DRAFT_FULL_LAYERS if spec else 0)) * KV_CELL_BYTES[kv] if kv != "f16" else \ + (KV_FULL_VISITS + (DRAFT_FULL_LAYERS if spec else 0)) * 2 * KV_HEADS * HEAD_DIM * 2 + + +#: VRAM with every expert on the card (nvidia-smi memory.used, CUDA context included) less the K/V: --spec 1, --chunk 1024, --kv f16, after a +#: 1.5K-token request (RTX 3090: 19720 MiB at 8K, 20584 at 32K, 21740 at 64K context). +RESIDENT_FIXED_MIB = 19436 +#: kept free beside it so a longer prompt or the driver does not end the load in an out-of-memory error. CBA: one card measured (RTX 3090); a +#: card with another CUDA context size moves this by ~100 MiB, the margin covers it +RESIDENT_MARGIN_MIB = 1024 +#: --chunk: prompt tokens per step (the measured default of the hand-tuned config) +CHUNK = 1024 +#: the contexts offered (the model was trained to 1M; past 256K is untested here) +CONTEXTS = [8192, 16384, 32768, 49152, 65536, 131072, 262144] +DEFAULT_CONTEXT = 32768 # where nothing larger fits on the card with every expert +#: the RAM of the offload mode: every expert is kept in RAM (pinned, placed on the NUMA nodes) while the card holds the most used. Measured: the +#: engine's peak resident memory (VmHWM) 16.8 GiB on an RTX 3090 set up as an 8 GB card; 32 GB leaves the OS, the server and the browser room +OFFLOAD_RAM_GIB = 16.8 +RESIDENT_RAM_GIB = 3.2 # the same peak with every expert on the card (24 GB, 64K context) +#: the OS, the server and a browser beside the engine. CBA: one figure for every PC, not measured per system +OS_RAM_GIB = 6.0 +RAM_GB = 32 + +#: The conversation cache (--conversation-cache-mib, the engine's default 0 = off): prompt-end checkpoints and parked conversations in pinned +#: host memory. Without it a client that drops the reasoning from its history (every agent client does) re-reads its whole prompt every turn: the +#: rewind point it needs lives in that cache. The largest of CACHE_MIB that leaves CACHE_SPARE_MIN_GIB of RAM beside the engine, the pictures' +#: weights and the OS; off below that. +CACHE_MIB = (4096, 2048) +CACHE_SPARE_MIN_GIB = 1.5 + + +def conversation_cache_mib(ram_gib: float, offload: bool) -> tuple: + """(MiB for --conversation-cache-mib or 0, the RAM left beside the engine, the pictures and the OS in GiB).""" + spare = ram_gib - (OFFLOAD_RAM_GIB if offload else RESIDENT_RAM_GIB) - VISION_RAM_GIB - OS_RAM_GIB + return next((m for m in CACHE_MIB if spare - m / 1024 >= CACHE_SPARE_MIN_GIB), 0), spare + +#: The expert offload (--vram-reserve-mib) runs with --kv-grow 1: the full-attention K/V is mapped in 8192-cell steps as a conversation grows and +#: the prompt buffers only while a prompt is read, both taken from the expert pools and given back after. The engine keeps each pool at its +#: 64-slot minimum: a prompt reads in smaller chunks (down to 256 tokens) when the buffers would not fit, and a prompt that does not fit even then +#: ends with "the context is full" (a 400 to the client, the engine keeps running). So the context setup writes is the one whose deepest point - +#: the whole K/V and a 256-token chunk's buffers - still leaves the pools their minimum. Measured on an RTX 3090 set up as an 8 GB card with a +#: 500 MiB desktop (the engine's "offload:" and "kv-grow: N cells, expert slots a + b" lines): at rest it holds GROW_BASE_MIB beside the pools +#: and the K/V (--chunk 1024); a prompt maps up to 1000 MiB more for 1024-token chunks, and PROMPT_BUF_MIN_MIB where pf_fit has shrunk the +#: chunk (the parts laid out for a full chunk stay mapped whole: the largest drop beside the K/V seen at the floor was 728 MiB). Checked there +#: with i8r: a 30K-token prompt read in 83 s (chunks shrinking near the end; --chunk 256 throughout took 240 s), a 55K one refused at 40,960 +#: tokens with the engine still up. CBA: one card measured; another card's CUDA context moves it by ~100 MiB +GROW_BASE_MIB = 3451 +PROMPT_BUF_MIN_MIB = 730 +#: the offload's K/V formats, in order: the first that reaches TARGET_CONTEXT is used (f16 first: the reference) +OFFLOAD_KV = ["f16", "i8r"] +TARGET_CONTEXT = 32768 # agentic coding needs 30-60K +OFFLOAD_MARGIN_MIB = 128 # the engine's INK2_OFF_MARGIN_MIB, kept beside the reserve +#: the least room the pools may have: the engine refuses to start with fewer than 64 slots in either pool (FETCH_MAX), the MXFP8 pool gets 20% of +#: the room and an MXFP8 expert is 8211456 bytes: 64 x 8211456 / 0.2 bytes = 2506 MiB, rounded up for the 2-decimal GiB of the measurement +MIN_POOLS_MIB = 2560 +#: kept beside the pools' minimum when setup sizes the offload: the measurement is one card's (another card's CUDA context differs by ~100 MiB) and +#: a desktop's VRAM grows after setup looked at it; with less the engine can stop at start ("need >= 64" slots) +OFFLOAD_SLACK_MIB = 256 + + +#: --spec 1 beside the expert offload (with CPU experts: a verify block's missing experts run on the CPU pools). The drafter takes VRAM from the +#: expert pools: its weights (SPEC_DRAFTER_MIB), the prompt buffers, which stay mapped with it (SPEC_PROMPT_BUF_MIB), and its K/V layer for the whole +#: context, 4096 bytes a token in every --kv format, not grown. Measured on the RTX 3090 (the engine's "offload:" line with and without --spec 1): +#: 1884 MiB at 256K without --kv-grow (the buffers mapped either way), 2120 MiB at 64K and 2376 MiB at 128K with it. +#: A verify block computes 8 tokens' experts and keeps 3 to 5 of them, so every missing expert costs more CPU time a token than in plain +#: decoding, and the smaller pools miss more. SPEC_OFFLOAD_SPEEDS: per card shape, the share of the experts the pools hold with the drafter (%), +#: then decode tok/s plain and with --spec 1 on the 257-token chat prompt, plain and with --spec 1 on a 24-token prompt (the 3090 limited to the +#: card size, 2 x 22 threads, 512 greedy tokens at the start of the context, the mean of two runs; 16 GB: one run). With most experts on the +#: card it does what it does with all of them (88.6 against 90.9 on the chat prompt, whose drafts are rarely kept, and well ahead where they +#: are); at 45% and less the chat prompt loses 10% and more. So the drafter is on where the pools still hold SPEC_OFFLOAD_POOLS_MIB (70% of +#: the experts) beside it and the whole context's K/V. CBA: one box measured (fewer or slower CPU threads move the break-even up); nothing +#: between 45% and 70% +SPEC_DRAFTER_MIB = 860 +SPEC_PROMPT_BUF_MIB = 1004 +SPEC_OFFLOAD_POOLS_MIB = 10500 +SPEC_OFFLOAD_SPEEDS = {"8 GB, 32K": (19, 66.9, 51.8, 64.6, 59.9), "12 GB, 64K": (45, 80.6, 72.3, 81.5, 87.9), + "16 GB, 128K": (70, 84.1, 84.4, 85.7, 100.2), "24 GB, 128K": (98, 85.9, 83.9, 86.7, 103.1), + "24 GB, 256K, i8r, no --kv-grow": (92, 82.9, 84.7, 83.3, 100.0)} + + +def offload_spec(vram_mib: float, ctx: int, reserve_mib: int = 0, used_mib: float = 0, kv: str = "f16") -> bool: + """The offload mode runs the drafter (--spec 1) too: the expert pools keep SPEC_OFFLOAD_POOLS_MIB beside it at the deepest point (the whole + K/V of `ctx`).""" + spec_mib = SPEC_DRAFTER_MIB + SPEC_PROMPT_BUF_MIB + -(-ctx * DRAFT_FULL_LAYERS * KV_CELL_BYTES["f16"] // 2**20) + pools = int(vram_mib - used_mib) - reserve_mib - GROW_BASE_MIB - -(-ctx * kv_bytes_per_token(False, kv) // 2**20) - spec_mib + return pools >= SPEC_OFFLOAD_POOLS_MIB + + +def resident_need_mib(ctx: int) -> int: + """VRAM (MiB) the resident mode (every expert on the card, the drafter on) takes at this context.""" + return RESIDENT_FIXED_MIB + -(-ctx * kv_bytes_per_token(True) // 2**20) + + +def resident_fits(vram_mib: float, ctx: int, reserve_mib: int = 0) -> bool: + """Every expert, the drafter and the K/V of `ctx` fit on a card of `vram_mib` with `reserve_mib` kept free for other programs.""" + return resident_need_mib(ctx) + RESIDENT_MARGIN_MIB + reserve_mib <= vram_mib + + +def offload_room_mib(vram_mib: float, ctx: int, used_mib: float = 0, kv: str = "f16") -> int: + """The VRAM a reserve can take in the offload mode at its deepest point (the whole K/V of `ctx` in format `kv` and a 256-token chunk's + buffers), with the expert pools at their minimum and the slack kept; below 0 a prompt that long ends with "the context is full". + `used_mib`: what other programs (a desktop) hold on the card now: the engine sizes its pools from the FREE VRAM and keeps the reserve on top + of that.""" + return (int(vram_mib - used_mib) - GROW_BASE_MIB - -(-ctx * kv_bytes_per_token(False, kv) // 2**20) - PROMPT_BUF_MIN_MIB + - OFFLOAD_MARGIN_MIB - MIN_POOLS_MIB - OFFLOAD_SLACK_MIB) + + +def offload_kv(vram_mib: float, reserve_mib: int = 0, used_mib: float = 0, ctx: int = TARGET_CONTEXT) -> str: + """The offload's K/V format at this context: the first that leaves the reserve its room; else the first that fits at all (setup then cuts + the reserve to its room); else the last (the smallest).""" + return (next((k for k in OFFLOAD_KV if offload_room_mib(vram_mib, ctx, used_mib, k) >= reserve_mib), None) + or next((k for k in OFFLOAD_KV if offload_room_mib(vram_mib, ctx, used_mib, k) >= 0), OFFLOAD_KV[-1])) + + +def recommended_context(vram_mib: float, reserve_mib: int = 0, used_mib: float = 0) -> int: + """The largest context up to 128K that runs with every expert on the card (the reserve covers what a desktop holds there). When none does, + the experts share the card: the largest context up to 128K whose deepest point leaves the pools their room beside the reserve (offload_kv's + format). A reserve that would hold the context under TARGET_CONTEXT gives way: TARGET_CONTEXT (or the largest that fits) with whatever room + is left for the reserve (setup cuts it and says so); 8K at the least.""" + fits = [c for c in CONTEXTS if DEFAULT_CONTEXT <= c <= 131072 and resident_fits(vram_mib, c, reserve_mib)] + if fits: + return max(fits) + def best(reserve): + kv = offload_kv(vram_mib, reserve, used_mib) + return max([c for c in CONTEXTS if c <= 131072 and offload_room_mib(vram_mib, c, used_mib, kv) >= reserve], default=8192) + ctx = best(reserve_mib) + return ctx if ctx >= TARGET_CONTEXT or not reserve_mib else max(ctx, min(best(0), TARGET_CONTEXT)) + + +def engine_args(model_dir: str, ctx: int, vram_mib: float, reserve_mib: int, cpu_threads: int | None, used_mib: float = 0, + cache_mib: int = 0) -> list[str]: + """The engine's arguments. Every expert fits on the card: resident, with the drafter (--spec 1). Otherwise the expert offload with --kv-grow 1: + the card keeps `reserve_mib` free and fills the rest with the most used experts, the others stay in RAM; `cpu_threads` (per NUMA node; None: no + CPU experts) computes a token's missing experts on the CPU instead of copying them over PCIe; the K/V format is offload_kv's. With CPU + experts the drafter stays on where the pools keep most of the experts beside it (offload_spec). CBA: offload without CPU experts (no AVX2) + goes without the drafter: its verify blocks would copy their missing experts over PCIe (measured at 8 GB: 16 tok/s)""" + cache = ["--conversation-cache-mib", str(int(cache_mib))] if cache_mib else [] # (conversation_cache_mib) + if resident_fits(vram_mib, ctx, reserve_mib): + return ["--model", model_dir, "--max-context", str(ctx), "--chunk", str(CHUNK), "--kv", "f16", "--tc", "1", "--spec", "1", *cache] + args = ["--model", model_dir, "--max-context", str(ctx), "--chunk", str(CHUNK), "--kv", offload_kv(vram_mib, reserve_mib, used_mib, ctx), + "--tc", "1", "--kv-grow", "1", "--vram-reserve-mib", str(int(reserve_mib))] + if cpu_threads: + args += ["--cpu-threads", str(int(cpu_threads))] + if offload_spec(vram_mib, ctx, reserve_mib, used_mib, args[args.index("--kv") + 1]): + args += ["--spec", "1"] + return args + cache diff --git a/terminal/strata_control/pictures.py b/terminal/strata_control/pictures.py index 47cc7f9add4..68c1a0e9e44 100644 --- a/terminal/strata_control/pictures.py +++ b/terminal/strata_control/pictures.py @@ -100,7 +100,10 @@ def url(self, endpoint: str | None = None) -> str: def family_of(cfg: dict, gguf: Path | None, asked: str | None = None) -> str | None: """The family whose picture file this model uses; None for one this step does not handle. ``asked`` is the catalog's family (the app knows it); - without it the model's own file name and name decide (Swift's files are called Swift-..., Qwen3.6's start with Qwen3.6).""" + without it the model's own file name and name decide (Swift's files are called Swift-..., Qwen3.6's start with Qwen3.6). + strata-ink2 (the official Inkling checkpoint): "inkling2", whatever was asked - it reads the ViT from the checkpoint folder itself.""" + if Path(str(cfg.get("exe") or "").replace("\\", "/")).name.lower().startswith("strata-ink2"): + return "inkling2" if asked: low = asked.lower() if low in ("hy4-flash", "inkling-2-mini"): @@ -448,6 +451,9 @@ def fetch(config_path: str | Path, *, engine_dir: str | Path, asked: str = "yes" foot = discovery.footprint(cfg, config) gguf = foot.weights[0] if foot.weights else None name = family_of(cfg, gguf, family) + if name == "inkling2": # strata-ink2: nothing to fetch, no --vision file (never Inkling-2-Mini-Vision.strata) + return {"mmproj": None, "vision": None, "fetched": False, "family": name, "data_dir": None, + "note": "strata-ink2 reads pictures with the ViT of its checkpoint folder: nothing to download"} if name == "hy4-flash": return _fetch_hy4(config, cfg, foot, data_dir=data_dir, progress=progress, cancel=cancel, endpoint=endpoint, online=online) if name == "inkling-2-mini": diff --git a/terminal/tests/terminal/test_gh_0217_hipflags.py b/terminal/tests/terminal/test_gh_0217_hipflags.py index 1fbe7d96b75..ece90c393e4 100644 --- a/terminal/tests/terminal/test_gh_0217_hipflags.py +++ b/terminal/tests/terminal/test_gh_0217_hipflags.py @@ -18,7 +18,7 @@ def flags(self, relative: str) -> list[str]: def test_setup_py_has_the_engine_and_the_picture_reader_builds(self): found = self.flags("setup.py") - self.assertEqual(len(found), 2, found) + self.assertEqual(len(found), 3, found) for flags in found: self.assertTrue(flags.startswith("-isystem {root}/include --rocm-path={root}"), flags) diff --git a/terminal/tests/terminal/test_inkling2_setup.py b/terminal/tests/terminal/test_inkling2_setup.py new file mode 100644 index 00000000000..90f960ec4ac --- /dev/null +++ b/terminal/tests/terminal/test_inkling2_setup.py @@ -0,0 +1,400 @@ +"""Inkling-2-Mini's official checkpoint in setup (install_ink2, strata_control/ink2_family.py): its pinned files, the engine arguments it writes for a card, the K/V +figure against the engine's own layout, and the places a family is registered.""" + +from __future__ import annotations + +import json +import os +import re +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +import setup +from strata_control import ink2_family as F + +ROOT = Path(__file__).resolve().parents[2] +ENGINE = ROOT.parent / "engine" / "src" / "inkling2" / "ink2_engine.cu" + + +def engine_flags() -> set: + """The options strata-ink2's main() parses (`a == "--x"`).""" + return set(re.findall(r'a == "(--[a-z0-9-]+)"', ENGINE.read_text(encoding="utf-8"))) + + +class Files(unittest.TestCase): + def test_every_file_is_pinned_at_the_revision(self): + self.assertRegex(F.REVISION, r"^[0-9a-f]{40}$") + self.assertEqual(setup.HF_REVISIONS[F.REPO], F.REVISION) + self.assertIs(setup.REPO_PINS[F.REPO], F.FILES) + for name, (size, sha) in F.FILES.items(): + self.assertGreater(size, 0, name) + self.assertRegex(sha, r"^[0-9a-f]{64}$", name) + self.assertNotEqual(set(sha), {"0"}, name) + self.assertEqual(setup.file_pin(setup.hf(F.REPO) + name), (size, sha)) + + def test_what_the_engine_and_the_pack_read_is_downloaded(self): + for name in ("model-00001-of-00001.safetensors", "mtp.safetensors", "tokenizer.json", "chat_template.jinja", "generation_config.json", + "processor_config.json"): + self.assertIn(name, F.FILES) + src = ENGINE.read_text(encoding="utf-8") + self.assertIn('"/model-00001-of-00001.safetensors"', src) + self.assertIn('"/mtp.safetensors"', src) + + +class KV(unittest.TestCase): + def test_the_figure_follows_the_engines_layout(self): + src = ENGINE.read_text(encoding="utf-8") + c = {k: int(v) for k, v in re.findall(r"\b(NL|NKV|HD|LOOP_BEGIN|LOOP_END|PASSES|BLOCK|DL) = (\d+)", src)} + self.assertIn("bool full_layer(int L) { return L % BLOCK == BLOCK - 1; }", src) + self.assertIn("S.cap = S.full ? E.ctx : WINDOW + PF_RING_EXTRA;", src) # only the full-attention visits grow with the context + visits = list(range(c["NL"])) + [l for _ in range(c["PASSES"] - 1) for l in range(c["LOOP_BEGIN"], c["LOOP_END"])] + full = sum(1 for l in visits if l % c["BLOCK"] == c["BLOCK"] - 1) + self.assertEqual(full, F.KV_FULL_VISITS) + self.assertIn("Y.local = i == 0 || i == 2;", src) # the drafter: one global layer of DL + self.assertEqual(c["DL"] - 2, F.DRAFT_FULL_LAYERS) + self.assertEqual((c["NKV"], c["HD"]), (F.KV_HEADS, F.HEAD_DIM)) + self.assertEqual(F.kv_bytes_per_token(False), 32768) + self.assertEqual(F.kv_bytes_per_token(True), 36864) # measured: 864 MiB from 8K to 32K context + self.assertEqual(F.kv_bytes_per_token(True), 36864) + + +class Args(unittest.TestCase): + def test_resident_on_a_24_gb_card(self): + ctx = F.recommended_context(24576) + self.assertEqual(ctx, 65536) + args = F.engine_args("/m", ctx, 24576, 0, 22) + self.assertEqual(args[args.index("--spec") + 1], "1") + self.assertNotIn("--vram-reserve-mib", args) + self.assertNotIn("--cpu-threads", args) + + def test_offload_on_an_8_gb_card(self): + ctx = F.recommended_context(8192) # no desktop on the card: f16 reaches 32K + self.assertEqual(ctx, 32768) + args = F.engine_args("/m", ctx, 8192, 0, 22) + self.assertEqual(args[args.index("--vram-reserve-mib") + 1], "0") + self.assertEqual(args[args.index("--cpu-threads") + 1], "22") + self.assertEqual(args[args.index("--kv-grow") + 1], "1") + self.assertEqual((args[args.index("--kv") + 1], args[args.index("--chunk") + 1]), ("f16", "1024")) + self.assertNotIn("--spec", args) + # a desktop holding 500 MiB (measured on the 3090 as an 8 GB card: i8r reads a 30K prompt, refuses a 55K one cleanly): 32K in i8r + self.assertEqual(F.recommended_context(8192, 1500, 500), 32768) + self.assertEqual(F.offload_kv(8192, 1500, 500, 32768), "i8r") + no_cpu = F.engine_args("/m", 32768, 8192, 39, None, 500) + self.assertEqual((no_cpu[no_cpu.index("--kv") + 1], no_cpu[no_cpu.index("--chunk") + 1]), ("i8r", "1024")) + self.assertNotIn("--cpu-threads", no_cpu) + + def test_the_offload_keeps_the_drafter_where_the_pools_stay_large(self): + src = ENGINE.read_text(encoding="utf-8") + self.assertNotIn("not with --spec 1 yet", src) # the engine takes --spec 1 with --cpu-threads + self.assertIn("k_cache_cpu_b", src) + for vram, ctx in ((8192, 32768), (12288, 65536), (16384, 131072)): # the pools keep under 70% of the experts + self.assertFalse(F.offload_spec(vram, ctx), vram) + self.assertNotIn("--spec", F.engine_args("/m", ctx, vram, 0, 22)) + self.assertFalse(F.resident_fits(24576, 131072)) # a 24 GB card at 128K: offload, most experts on it + args = F.engine_args("/m", 131072, 24576, 0, 22) + self.assertEqual((args[args.index("--spec") + 1], args[args.index("--cpu-threads") + 1], args[args.index("--kv-grow") + 1]), + ("1", "22", "1")) + self.assertNotIn("--spec", F.engine_args("/m", 131072, 24576, 0, None)) # no CPU experts: no drafter in offload + self.assertTrue(F.offload_spec(24576, 65536, 3072)) # a 3 GB desktop reserve at 64K + self.assertFalse(F.offload_spec(24576, 262144)) # 256K of fp16 K/V leaves the pools 67% ... + self.assertTrue(F.offload_spec(24576, 262144, kv="i8r")) # ... of int8 K/V 93% + for shape, (share, chat, chat_spec, short, short_spec) in F.SPEC_OFFLOAD_SPEEDS.items(): + on = share >= 70 # SPEC_OFFLOAD_POOLS_MIB of the experts' 15013 MiB + self.assertEqual(chat_spec >= 0.95 * chat and short_spec > 1.1 * short, on, shape) # on: the chat prompt holds, the short one gains + + def test_offload_contexts_by_card(self): + self.assertEqual(F.recommended_context(12288, 1500, 600), 65536) + self.assertEqual(F.offload_kv(12288, 1500, 600, 65536), "f16") + self.assertEqual(F.recommended_context(16384, 1500, 800), 131072) + self.assertEqual(F.recommended_context(7168, 0, 300), 8192) # too small for anything better + + def test_the_offload_floor_follows_the_engines_pools(self): + src = ENGINE.read_text(encoding="utf-8") + guard = (ENGINE.parent / "ink2_grow_guard.cuh").read_text(encoding="utf-8") + self.assertIn("constexpr int FETCH_MAX = 64", src) + self.assertIn("(size_t) (budget * 0.2) / pool_slot(false)", src) # the MXFP8 pool's share of the room ... + self.assertIn("size_t pool_slot(bool nv) { return ex_bytes(nv ? 0 : NL - 1); }", src) + self.assertIn("g_is_gguf ? g_gg_a[r] + g_gg_b[r] : r ? MX_BYTES : NV_BYTES;", src) # ... MX_BYTES a slot for the checkpoint + self.assertIn("int g_off_margin_mib = 128;", src) + self.assertIn("int grow_step = 8192;", src) # the K/V grows in 8192-cell steps + self.assertIn("for (;; T /= 2) {", src) # pf_fit halves the chunk ... + self.assertIn("if (fits || T <= 256) { g_pf_full = !fits; return T; }", src) # ... down to 256, then the request ends + self.assertIn("if (ns - drop < FETCH_MAX) return false;", guard) # each pool keeps its minimum + self.assertIn("ERR the context is full", guard) + self.assertEqual(F.OFFLOAD_MARGIN_MIB, 128) + self.assertGreaterEqual(F.MIN_POOLS_MIB * 2**20, 64 * 8211456 / 0.2) # 64 MXFP8 slots at the least (MX_BYTES) + self.assertIn("// 4478976 / 8211456", src) + self.assertEqual(F.offload_room_mib(8192, 8192, 500), F.offload_room_mib(8192, 8192) - 500) # a desktop's VRAM comes out of the room + self.assertLess(F.offload_room_mib(8192, 49152, 500, "i8r"), 0) # measured: the 55K prompt stopped at 40,960 + self.assertLess(F.offload_room_mib(6144, 8192, 0, "i8r"), 0) # a 6 GB card is too small + + def test_the_8_bit_cell_follows_the_engine(self): + src = ENGINE.read_text(encoding="utf-8") + self.assertIn('else if (k == "i8r") E.kvm = 3;', src) + self.assertIn("case 2: return m >= 2 ? (KVD / KVG) * 2 : 0;", src) # K scales: fp16 per 64 + self.assertIn("default: return m >= 2 ? (KVD / (m == 4 ? V4G : KVG)) * 2 : 0;", src) # V scales: per 64 but for k8v4 + self.assertEqual(F.KV_CELL_BYTES["i8r"], 1024 + 1024 + 2 * (1024 // 64) * 2) + for text, kl in F.KL_VS_F32.items(): # the closest 8-bit format to f32 K/V + self.assertEqual(min(kl, key=lambda k: kl[k][0]), "i8r", text) + self.assertEqual(min(kl, key=lambda k: kl[k][1]), "i8r", text) + + def test_a_reserve_or_a_long_context_moves_a_card_to_offload(self): + self.assertTrue(F.resident_fits(24576, 65536)) + self.assertFalse(F.resident_fits(24576, 131072)) + self.assertFalse(F.resident_fits(24576, 65536, 3072)) + + def test_every_flag_is_one_the_engine_parses(self): + known = engine_flags() + self.assertIn("--vram-reserve-mib", known) + for vram in (8192, 12288, 16384, 24576, 49152): + for threads in (None, 7, 22): + args = F.engine_args("/m", F.recommended_context(vram), vram, 0, threads, 0, 4096) + flags = [x for x in args if x.startswith("--")] + self.assertEqual(set(flags) - known, set(), (vram, threads)) + if "--vram-reserve-mib" in flags: # offload: the drafter only with the CPU experts + self.assertLessEqual("--spec" in flags, "--cpu-threads" in flags) + self.assertFalse("--cpu-threads" in flags and "--vram-reserve-mib" not in flags) + + def test_conversation_cache_from_the_ram(self): + self.assertEqual(F.conversation_cache_mib(187, True)[0], 4096) + self.assertEqual(F.conversation_cache_mib(29.8, True)[0], 4096) # a 32 GB PC, experts in RAM: 6.4 GiB spare + self.assertEqual(F.conversation_cache_mib(27.0, True)[0], 2048) + self.assertEqual(F.conversation_cache_mib(25.0, True), (0, 25.0 - 16.8 - 0.65 - 6.0)) # off below 1.5 GiB left + self.assertEqual(F.conversation_cache_mib(16, False)[0], 4096) # resident: the experts are not in RAM + args = F.engine_args("/m", 32768, 8192, 0, 22, 0, 2048) + self.assertEqual(args[args.index("--conversation-cache-mib") + 1], "2048") + self.assertNotIn("--conversation-cache-mib", F.engine_args("/m", 32768, 8192, 0, 22)) + # the RAM setup asks of an offload PC holds the engine, the pictures' weights, the OS and the largest cache + self.assertGreaterEqual(F.RAM_GB * 1e9 / 2**30, F.OFFLOAD_RAM_GIB + F.VISION_RAM_GIB + F.OS_RAM_GIB + F.CACHE_MIB[0] / 1024) + self.assertTrue(F.VISION) + self.assertIn("processor_config.json", F.FILES) + + def test_cpu_threads_per_socket(self): + with mock.patch.object(setup, "cpu_core_layout", return_value=(96, [24, 24])), mock.patch.object(setup, "cpu_cores", return_value=None): + self.assertEqual(setup.ink2_cpu_threads(), 22) # measured best on 2 x 24 cores + with mock.patch.object(setup, "cpu_core_layout", return_value=(16, [8])), mock.patch.object(setup, "cpu_cores", return_value=None): + self.assertEqual(setup.ink2_cpu_threads(), 7) + + +class Registered(unittest.TestCase): + def test_offered_on_linux_for_cuda_and_hip(self): + with mock.patch.object(setup, "CONTROL", False): + with mock.patch.object(setup.sys, "platform", "linux"): + self.assertTrue(setup.ink2_offered(False)) + self.assertTrue(setup.ink2_offered(True)) + with mock.patch.object(setup.sys, "platform", "win32"): + self.assertFalse(setup.ink2_offered(False)) + self.assertFalse(setup.ink2_offered(True)) + with mock.patch.object(setup.sys, "platform", "darwin"): + self.assertFalse(setup.ink2_offered(False)) + self.assertFalse(setup.ink2_offered(True)) + with mock.patch.object(setup, "CONTROL", True), mock.patch.object(setup.sys, "platform", "linux"): + self.assertFalse(setup.ink2_offered(False)) + self.assertFalse(setup.ink2_offered(True)) + self.assertNotIn("inkling2", setup.OWN_PATH_FAMILIES) # that table's installer is the single-GGUF one + + def test_hip_arch_set_allows_wave32_and_refuses_gfx906(self): + self.assertIn("gfx1151", setup.INK2_HIP_ARCHS) + self.assertIn("gfx1201", setup.INK2_HIP_ARCHS) + self.assertIn("gfx1100", setup.INK2_HIP_ARCHS) + self.assertNotIn("gfx906", setup.INK2_HIP_ARCHS) + self.assertIn("AMD", F.ABOUT) + self.assertIn("NVIDIA", F.ABOUT) + args = mock.MagicMock() + with mock.patch.object(setup, "CONTROL", False), mock.patch.object(setup.sys, "platform", "linux"), \ + mock.patch.object(setup, "say"), mock.patch.object(setup, "ok"), \ + mock.patch.object(setup, "fail", side_effect=RuntimeError("refused")) as fail_mock: + with self.assertRaises(RuntimeError): + setup.install_ink2(args, "inkling-2-mini", {"arch": "gfx906", "vram_gb": 32.0}, True, + [{"arch": "gfx906"}], 13, [], 8080, 64.0, None) + self.assertIn("gfx906", fail_mock.call_args[0][0]) + + def test_its_config_is_read_back_and_not_tuned(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d) / "strata-inkling-2-mini-official.json" + p.write_text(json.dumps({"exe": "x/strata-ink2", "arch": "inkling2", "model_name": "inkling-2-mini", + "args": F.engine_args("/m", 65536, 24576, 0, None)}), encoding="utf-8") + ch = setup.choices_from_config(p) + self.assertEqual((ch["family"], ch["model"], ch["context"], ch["vision"]), ("inkling-2-mini", "official", 65536, "none")) + self.assertEqual(setup.calibration_targets([p], None, None), []) + + def test_the_start_leaves_its_arguments_alone(self): + cfg = {"exe": "x/strata-ink2", "arch": "inkling2", "args": F.engine_args("/m", 32768, 8192, 0, 22)} + before = list(cfg["args"]) + with mock.patch.object(setup, "write_config") as w: + out = setup.upgrade_config(Path("strata-inkling-2-mini-official.json"), cfg) + self.assertEqual(out["args"], before) + w.assert_not_called() + + +class OneFamily(unittest.TestCase): + """The official checkpoint is a source ("model") of upstream's Inkling family: install_inkling2 hands it to install_ink2 (strata-ink2), the + SQ builds stay on strata-inkling.""" + + def test_the_family_lists_it_and_routes_it_to_strata_ink2(self): + fam = setup.INKLING_FAMILIES["inkling-2-mini"] + self.assertNotIn(F.MODEL, fam["models"]) # the catalog sizes every entry as an SQ build + self.assertTrue({"SQ-20", "SQ-15", "SQ-10"} <= set(fam["models"])) + self.assertNotIn("INK2_FAMILIES", vars(setup)) + src = setup.INKLING_COMMUNITY_SOURCES["safetensors"] + self.assertEqual((src["exe"], src["arch"], src["model"]), (F.EXE, F.ARCH, F.MODEL)) + from serve import inkling_kind + cfg = {"exe": "/x/engine/strata-ink2", "arch": F.ARCH, "args": F.engine_args("/m", 32768, 24576, 0, None)} + self.assertFalse(inkling_kind.is_inkling(cfg)) # never strata-inkling's start rules + + def test_install_inkling2_hands_the_official_source_over(self): + args = mock.MagicMock(model=F.MODEL, context=None, vision=None) + with mock.patch.object(setup, "install_ink2", return_value=7) as ink2, mock.patch.object(setup, "say"), \ + mock.patch.object(setup, "ok"), mock.patch.object(setup, "ink2_offered", return_value=True): + got = setup.install_inkling2(args, "inkling-2-mini", {"vram_gb": 24.0, "arch": 86}, False, None, 13, [], 8080, 64.0, None) + self.assertEqual(got, 7) + self.assertEqual(ink2.call_args[0][1], "inkling-2-mini") + + +class Routing(unittest.TestCase): + """A strata-ink2 config is never routed as strata-inkling's: no batch flag, no Vision shard, a model id the harness leaves thinking.""" + + CFG = {"exe": "/x/engine/strata-ink2", "arch": F.ARCH, "model_name": F.NAME, "parallel": 8, "args": ["--model", "/m"]} + + def test_no_parallel_flag(self): + from serve.server_parts import engines + self.assertEqual(engines.parallel_args(dict(self.CFG), list(self.CFG["args"])), []) + up = {"exe": "component:strata-inkling", "arch": "inkling2_loop", "parallel": 8, "args": ["--native", "m.strata"]} + self.assertEqual(engines.parallel_args(up, list(up["args"])), ["--parallel", "8"]) + + def test_no_vision_shard(self): + from strata_control import pictures + self.assertEqual(pictures.family_of(self.CFG, None, "inkling-2-mini"), "inkling2") + with tempfile.TemporaryDirectory() as d: + p = Path(d) / "strata-inkling-2-mini-official.json" + p.write_text(json.dumps(self.CFG), encoding="utf-8") + got = pictures.fetch(p, engine_dir=d) + self.assertEqual((got["mmproj"], got["vision"], got["fetched"]), (None, None, False)) + + def test_the_harness_keeps_its_thinking(self): + from strata_cli.launch import harness + t = harness.target("http://127.0.0.1:8080", None, F.NAME) + self.assertFalse(harness._is_inkling(t)) + self.assertEqual(harness._display_name(t), "Inkling-2-Mini (Strata, local)") + + +class Build(unittest.TestCase): + def test_hip_build_cmake_args_and_stamp_reuse(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d) + rocm = root / "rocm" + clang = rocm / "llvm" / "bin" / "clang++" + clang.parent.mkdir(parents=True) + clang.write_text("", encoding="utf-8") + bitcode = rocm / "lib" / "llvm" / "amdgcn" / "bitcode" + bitcode.mkdir(parents=True) + extra_pkg = root / "rocm_libs" + dirs = [str(rocm / "lib"), str(extra_pkg / "lib")] + builds = [] + + def fake_cmake(src, bdir, target, defs, vcvars, bat): + builds.append((bdir, target, list(defs))) + bdir.mkdir(parents=True, exist_ok=True) + (bdir / F.EXE).write_text("hip-bin", encoding="utf-8") + + src_hash = ["h1"] + with mock.patch.object(setup, "ROOT", root), \ + mock.patch.object(setup, "engine_src", return_value=root / "engine-src"), \ + mock.patch.object(setup, "rocm_root", return_value=(rocm, dirs)) as rocm_mock, \ + mock.patch.object(setup, "cmake_build", side_effect=fake_cmake), \ + mock.patch.object(setup, "source_hash", side_effect=lambda _parts: src_hash[0]), \ + mock.patch.object(setup.shutil, "which", side_effect=lambda name: f"/usr/bin/{name}"), \ + mock.patch.object(setup, "say"), mock.patch.object(setup, "ok"), \ + mock.patch.dict(os.environ, {}, clear=False): + gpu = {"arch": "gfx1151", "archs": ["gfx1151"]} + exe, got_dirs = setup.ink2_build(gpu, True, hip=True, amd=[gpu]) + self.assertEqual(exe, root / "engine" / F.EXE) + self.assertEqual(got_dirs, dirs) + self.assertEqual(len(builds), 1) + bdir, target, defs = builds[0] + self.assertEqual(bdir, root / "build-ink2-hip") + self.assertEqual(target, F.EXE) + self.assertIn("-DSTRATA_ENABLE_HIP=ON", defs) + self.assertIn("-DSTRATA_ENABLE_CUDA=OFF", defs) + self.assertIn("-DSTRATA_BUILD_TESTS=OFF", defs) + self.assertIn("-DCMAKE_HIP_ARCHITECTURES=gfx1151", defs) + self.assertIn(f"-DCMAKE_HIP_COMPILER={clang}", defs) + self.assertIn(f"-DCMAKE_HIP_COMPILER_ROCM_ROOT={rocm}", defs) + self.assertIn(f"-DCMAKE_PREFIX_PATH={rocm};{extra_pkg}", defs) + self.assertIn(f"-DCMAKE_HIP_FLAGS=-isystem {rocm}/include --rocm-path={rocm} --rocm-device-lib-path={bitcode}", defs) + rocm_mock.assert_called_once_with(["gfx1151"]) + + stamp = json.loads((root / "engine" / (F.EXE + ".json")).read_text(encoding="utf-8")) + self.assertEqual(stamp, {"backend": "hip", "archs": ["gfx1151"], "src": "h1", "lib_dirs": dirs}) + + exe2, got_dirs2 = setup.ink2_build({"arch": "gfx1151"}, True, hip=True, amd=[gpu]) + self.assertEqual((exe2, got_dirs2), (exe, dirs)) + self.assertEqual(len(builds), 1) + + src_hash[0] = "h2" + setup.ink2_build({"arch": "gfx1151"}, True, hip=True, amd=[gpu]) + self.assertEqual(len(builds), 2) + + setup.ink2_build({"arch": "gfx1201"}, True, hip=True) + self.assertEqual(len(builds), 3) + self.assertIn("-DCMAKE_HIP_ARCHITECTURES=gfx1201", builds[2][2]) + + def test_cuda_build_rebuilds_cleanly_over_a_hip_stamp(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d) + eng = root / "engine" + eng.mkdir() + (eng / F.EXE).write_text("hip-bin", encoding="utf-8") + (eng / (F.EXE + ".json")).write_text( + json.dumps({"backend": "hip", "archs": ["gfx1151"], "src": "h1", "lib_dirs": ["/rocm/lib"]}), + encoding="utf-8", + ) + nvcc = root / "cuda" / "bin" / "nvcc" + nvcc.parent.mkdir(parents=True) + nvcc.write_text("", encoding="utf-8") + builds = [] + + def fake_cmake(src, bdir, target, defs, vcvars, bat): + builds.append((bdir, target, list(defs))) + bdir.mkdir(parents=True, exist_ok=True) + (bdir / F.EXE).write_text("cuda-bin", encoding="utf-8") + + with mock.patch.object(setup, "ROOT", root), \ + mock.patch.object(setup, "engine_src", return_value=root / "engine-src"), \ + mock.patch.object(setup, "install_build_tools", return_value=(str(nvcc), None)), \ + mock.patch.object(setup, "toolkit_root_defs", return_value=[]), \ + mock.patch.object(setup, "host_compiler_defs", return_value=[]), \ + mock.patch.object(setup, "cmake_build", side_effect=fake_cmake), \ + mock.patch.object(setup, "source_hash", return_value="h1"), \ + mock.patch.object(setup, "say"), mock.patch.object(setup, "ok"): + exe, _ = setup.ink2_build({"arch": 86}, True, hip=False) + self.assertEqual(exe, eng / F.EXE) + self.assertEqual(len(builds), 1) + self.assertEqual(builds[0][0], root / "build-ink2") + self.assertIn("-DSTRATA_ENABLE_CUDA=ON", builds[0][2]) + self.assertIn("-DCMAKE_CUDA_ARCHITECTURES=86", builds[0][2]) + + def test_source_hash_tracks_hip_wmma_and_hip_compat(self): + with tempfile.TemporaryDirectory() as d: + eng = Path(d) + (eng / "CMakeLists.txt").write_text("cmake", encoding="utf-8") + (eng / "src" / "inkling2").mkdir(parents=True) + (eng / "include" / "strata" / "hip_compat").mkdir(parents=True) + wmma = eng / "src" / "inkling2" / "ink2_wmma_hip.cuh" + compat = eng / "include" / "strata" / "hip_compat" / "hip_compat.h" + wmma.write_text("v1", encoding="utf-8") + compat.write_text("c1", encoding="utf-8") + with mock.patch.object(setup, "engine_src", return_value=eng): + h0 = setup.source_hash(setup.INK2_SOURCES) + wmma.write_text("v2", encoding="utf-8") + h1 = setup.source_hash(setup.INK2_SOURCES) + compat.write_text("c2", encoding="utf-8") + h2 = setup.source_hash(setup.INK2_SOURCES) + self.assertNotEqual(h0, h1) + self.assertNotEqual(h1, h2) + + +if __name__ == "__main__": + unittest.main() diff --git a/terminal/tools/inkling2/README.md b/terminal/tools/inkling2/README.md new file mode 100644 index 00000000000..786b9e60eb6 --- /dev/null +++ b/terminal/tools/inkling2/README.md @@ -0,0 +1,20 @@ +# Inkling-2-Mini validation tools + +How `strata-ink2ref` and `strata-ink2` were checked against the model's reference implementation, the transformers +pull request huggingface/transformers#51050, run in fp32 on the CPU. + +1. `setup-venv.sh DIR`: a venv with that pull request and CPU torch. +2. `oracle.py --model CKPT --out DIR`: per-layer-application outputs and logits of a few prompts, plus their greedy + continuations; `ref_run.sh PROMPT` compares `strata-ink2ref --dump-layers --dump-logits` with them layer by layer. +3. `kl_run.py --model CKPT --text FILE --out X.pt`: all-position logits of a long text (`--mode w4a4` reproduces vLLM's + quantized expert activations); `cmp_logits.py` and `kl_cmp.py` give KL, max logit difference and top-1 agreement + against an engine's `--dump-logits`; `long_check.sh` runs the long-context and position-offset cases. +4. `tok_check.py CKPT REPO [TEXT...]`: Strata's tokenizer against the Hugging Face one on a corpus and chat prompts; + `pack_check.py` loads the extracted tokenizer pack the way the server does. +5. Pictures: `vision_oracle.py --model CKPT --image FILE --out P` writes the processor's pixel tensor (`P.pix`) and the + vision tower's rows (`P.emb`); `strata-ink2 --vis-pixels P.pix --dump-image-emb X` runs the engine's ViT on the same + pixels and `emb_cmp.py P.emb X` compares them (max |d|, cosine per token). `vision_kl.py --model CKPT --image FILE + --out P` gives the full multimodal prompt's logits and greedy answer (`P.0.pt`, the prompt with one placeholder per + picture in `P.0.ids1`); `strata-ink2 --tokens-file P.0.ids1 --image FILE --dump-logits L` then `vis_cmp.py P.0.pt L` + give KL and top-1 before, inside and after the picture. Use PNG (or BMP) for strict comparisons: the reference + decodes JPEG with libjpeg-turbo, the engine with stb_image (the server hands strata-ink2 Pillow-decoded JPEGs). diff --git a/terminal/tools/inkling2/cmp_logits.py b/terminal/tools/inkling2/cmp_logits.py new file mode 100644 index 00000000000..932b83b6778 --- /dev/null +++ b/terminal/tools/inkling2/cmp_logits.py @@ -0,0 +1,14 @@ +"""Per-position comparison of strata-ink2ref --dump-logits with a kl_run.py logits file. usage: cmp_logits.py ORACLE.pt REF.logits""" +import sys, numpy as np, torch +o = torch.load(sys.argv[1]); ol = o["logits"].double(); T, V = ol.shape +gl = torch.from_numpy(np.fromfile(sys.argv[2], dtype=np.float32).reshape(T, V)).double() +lp, lq = torch.log_softmax(ol, -1), torch.log_softmax(gl, -1) +kl = (lp.exp() * (lp - lq)).sum(-1); d = (ol - gl).abs().amax(-1) +agree = (ol.argmax(-1) == gl.argmax(-1)) +print(f"T={T} KL max {kl.max().item():.2e} (pos {kl.argmax().item()}) max|dlogit| {d.max().item():.2e} (pos {d.argmax().item()}) top1 agree {agree.float().mean().item()*100:.2f}%") +for lo, hi in ((0, 1000), (1000, 1030), (1030, T)): + if lo < T: print(f" pos {lo}-{min(hi, T)-1}: max|dlogit| {d[lo:hi].max().item():.2e} KL max {kl[lo:hi].max().item():.2e}") +bad = (~agree).nonzero().flatten().tolist() +for p in bad[:10]: + top = torch.topk(ol[p], 2).values + print(f" top1 differs at {p}: oracle margin top1-top2 {(top[0]-top[1]).item():.2e}") diff --git a/terminal/tools/inkling2/emb_cmp.py b/terminal/tools/inkling2/emb_cmp.py new file mode 100644 index 00000000000..6119e9e75e5 --- /dev/null +++ b/terminal/tools/inkling2/emb_cmp.py @@ -0,0 +1,12 @@ +"""Image rows of strata-ink2 (--dump-image-emb) against vision_oracle.py's .emb. usage: emb_cmp.py ORACLE.emb OURS.emb""" +import sys +import numpy as np + +a = np.fromfile(sys.argv[1], dtype=np.float32).reshape(-1, 2304).astype(np.float64) +b = np.fromfile(sys.argv[2], dtype=np.float32).reshape(-1, 2304).astype(np.float64) +assert a.shape == b.shape, (a.shape, b.shape) +d = np.abs(a - b) +cos = (a * b).sum(1) / (np.linalg.norm(a, axis=1) * np.linalg.norm(b, axis=1)) +rel = np.linalg.norm(a - b, axis=1) / np.linalg.norm(a, axis=1) +print(f"rows {a.shape[0]} max|d| {d.max():.3e} (row {d.max(1).argmax()}) max|ref| {np.abs(a).max():.3e} " + f"cos min {cos.min():.8f} mean {cos.mean():.8f} rel-L2 max {rel.max():.3e} mean {rel.mean():.3e}") diff --git a/terminal/tools/inkling2/kl_cmp.py b/terminal/tools/inkling2/kl_cmp.py new file mode 100644 index 00000000000..2dbc6f36c2f --- /dev/null +++ b/terminal/tools/inkling2/kl_cmp.py @@ -0,0 +1,11 @@ +"""KL(ref || other) per position, top-1 agreement, from kl_run.py outputs. usage: kl_cmp.py REF.pt OTHER.pt...""" +import sys, torch +ref = torch.load(sys.argv[1]) +lp = torch.log_softmax(ref["logits"].double(), -1) +for path in sys.argv[2:]: + o = torch.load(path) + assert torch.equal(o["ids"], ref["ids"]) + lq = torch.log_softmax(o["logits"].double(), -1) + kl = (lp.exp() * (lp - lq)).sum(-1) + top1 = (lp.argmax(-1) == lq.argmax(-1)).float().mean().item() + print(f"{path.split(chr(47))[-1]:16s} KL mean {kl.mean().item():.5f} median {kl.median().item():.5f} p99 {kl.quantile(0.99).item():.4f} max {kl.max().item():.4f} top1-agree {top1*100:.1f}% (T={kl.numel()})") diff --git a/terminal/tools/inkling2/kl_run.py b/terminal/tools/inkling2/kl_run.py new file mode 100644 index 00000000000..f88967f7ae9 --- /dev/null +++ b/terminal/tools/inkling2/kl_run.py @@ -0,0 +1,116 @@ +"""Inkling-2-Mini numerics probe: logits of one long text under a given weight dtype / expert activation mode. + +usage: kl_run.py --model DIR --dtype float32|bfloat16 --mode a16|w4a4 --text FILE --out FILE.pt [--max-tokens N] + +mode a16 : the transformers PR reference as is (experts dequantized, activations at the model dtype) +mode w4a4 : expert GEMM inputs quantized as vLLM does on Hopper/Blackwell (vllm PR #69028, ops/nvfp4.py, + ops/mxfp8.py, ops/activation.py swiglu_quantize): NVFP4 per-row amax/1536 + per-16 e4m3 block + scale chosen by the 6-vs-4 "fouroversix_mae" rule (layers 0-19), MXFP8 per-32 ue8m0 (layers 20-23). + The SwiGLU output is multiplied by the routing weight BEFORE its quantization, as swiglu_quantize does. +""" +import argparse, time +import torch +import torch.nn.functional as F +from transformers import AutoTokenizer, Inkling2LoopForConditionalGeneration +from transformers.models.inkling2_loop import modeling_inkling2_loop as M + +FP32_MAX = 3.4028234663852886e38 +MXFP8_FIRST_LAYER = 20 # hf_quant_config.json: layers 20-23 experts are MXFP8, 0-19 NVFP4 + + +def e2m1_round(x): + """fp32 -> nearest e2m1 value, ties as cvt.rn.satfinite (vllm ops/nvfp4.py _e2m1 thresholds).""" + a = x.abs() + v = torch.where(a <= 0.25, 0.0, torch.where(a < 0.75, 0.5, torch.where(a <= 1.25, 1.0, torch.where( + a < 1.75, 1.5, torch.where(a <= 2.5, 2.0, torch.where(a < 3.5, 3.0, torch.where(a <= 5.0, 4.0, 6.0))))))) + return torch.where(torch.signbit(x), -v, v) + + +def nvfp4_qdq(x): + """Quantize-dequantize rows of x [M, K] (fp32 math) as vllm nvfp4_quantize; returns fp32.""" + x = x.float() + m, k = x.shape + amax = x.abs().amax(1, keepdim=True) + enc = torch.clamp(1536.0 / amax, max=FP32_MAX) + dec = 1.0 / enc + outer = amax * (1.0 / 1536.0) + xb = x.view(m, k // 16, 16) + bmax = xb.abs().amax(-1, keepdim=True) + best, best_err = None, None + for div in (6.0, 4.0): # order matters: 4 wins only if strictly better + s = torch.clamp(bmax * (enc.unsqueeze(-1) * (1.0 / div if div == 6.0 else 0.25)), max=448.0) + s = s.to(torch.float8_e4m3fn).float() + inv = torch.clamp(1.0 / (s * dec.unsqueeze(-1)), max=FP32_MAX) + r = e2m1_round(xb * inv) + rec = (r * s) * outer.unsqueeze(-1) + err = (rec - xb).abs().sum(-1, keepdim=True) + if best is None: + best, best_err = rec, err + else: + best = torch.where(err < best_err, rec, best) + return best.view(m, k) + + +def mxfp8_qdq(x): + x = x.float() + m, n = x.shape + g = x.view(m, n // 32, 32) + raw = g.abs().amax(-1, keepdim=True) / 448.0 + e = ((raw.view(torch.int32) + 0x007FFFFF) & 0x7F800000) >> 23 + e = torch.where(raw <= 2.0 ** -127, torch.zeros_like(e), torch.clamp(e, max=254)) + scale = torch.clamp((e << 23).view(torch.float32), min=2.0 ** -127) + inv = torch.where(e == 0, torch.full_like(scale, 2.0 ** 127), 1.0 / scale) + v = torch.clamp(g * inv, -448.0, 448.0).to(torch.float8_e4m3fn).float() + return (v * scale).view(m, n) + + +def w4a4_forward(self, hidden_states, top_k_index, top_k_weights): + qdq = mxfp8_qdq if self.layer_idx >= MXFP8_FIRST_LAYER else nvfp4_qdq + out = torch.zeros_like(hidden_states, dtype=torch.float32) + for e in torch.unique(top_k_index).tolist(): + if e == self.num_experts: + continue + pos, tok = torch.where((top_k_index == e).T) + x = qdq(hidden_states[tok]) + gu = F.linear(x, self.gate_up_proj[e].float()) + gate, up = gu.chunk(2, dim=-1) + act = (torch.tanh(gate / self.act_fn.gate_softcap.softcap) * self.act_fn.gate_softcap.softcap + * torch.sigmoid(gate) * torch.tanh(up / self.act_fn.up_softcap.softcap) * self.act_fn.up_softcap.softcap) + act = act * top_k_weights[tok, pos, None].float() # gamma before quantization (swiglu_quantize) + y = F.linear(qdq(act), self.down_proj[e].float()) + out.index_add_(0, tok, y) + return out.to(hidden_states.dtype) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--model", required=True, help="the Inkling-2-Mini checkpoint directory") + ap.add_argument("--dtype", default="float32") + ap.add_argument("--mode", default="a16") + ap.add_argument("--text", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--max-tokens", type=int, default=1024) + ap.add_argument("--threads", type=int, default=48) + ap.add_argument("--pos-offset", type=int, default=0, help="position_ids = arange + N (only LogScale reads them)") + ap.add_argument("--ids-out", help="also write the token ids, comma-separated, for strata-ink2ref --tokens-file") + a = ap.parse_args() + torch.set_num_threads(a.threads) + tok = AutoTokenizer.from_pretrained(a.model) + model = Inkling2LoopForConditionalGeneration.from_pretrained(a.model, dtype=getattr(torch, a.dtype), device_map="cpu").eval() + for i, layer in enumerate(model.model.language_model.layers): + layer.mlp.experts.layer_idx = i + if a.mode == "w4a4": + layer.mlp.experts.forward = w4a4_forward.__get__(layer.mlp.experts) + ids = tok(open(a.text).read(), return_tensors="pt").input_ids[:, : a.max_tokens] + if a.ids_out: + open(a.ids_out, "w").write(",".join(map(str, ids[0].tolist()))) + pos = (torch.arange(ids.shape[1]) + a.pos_offset).unsqueeze(0) + t = time.time() + with torch.no_grad(): + logits = model(input_ids=ids, position_ids=pos, use_cache=False).logits[0].float() + torch.save({"ids": ids[0], "logits": logits}, a.out) + print(f"KLRUN-DONE dtype={a.dtype} mode={a.mode} pos_offset={a.pos_offset} tokens={ids.shape[1]} fwd={time.time() - t:.0f}s", flush=True) + + +if __name__ == "__main__": + main() diff --git a/terminal/tools/inkling2/long_check.sh b/terminal/tools/inkling2/long_check.sh new file mode 100755 index 00000000000..39e020b186f --- /dev/null +++ b/terminal/tools/inkling2/long_check.sh @@ -0,0 +1,16 @@ +#!/bin/bash +# long_check.sh: long-context and LogScale checks of strata-ink2ref against the fp32 transformers oracle. +# Environment: PY (the oracle venv's python, see setup-venv.sh), WORK (a directory holding long.txt and text.txt, the +# outputs land there), REF (the strata-ink2ref binary), MODEL (the Inkling-2-Mini checkpoint directory) +set -x +: "${PY:?}" "${WORK:?}" "${REF:?}" "${MODEL:?}" +T=$(dirname "$0"); P="$PY -I"; D=$WORK +$P $T/kl_run.py --model $MODEL --dtype float32 --mode a16 --text $D/long.txt --max-tokens 1600 --out $D/long_fp32.pt --ids-out $D/long.ids +$P $T/kl_run.py --model $MODEL --dtype float32 --mode a16 --text $D/text.txt --max-tokens 48 --pos-offset 20000 --out $D/off_fp32.pt --ids-out $D/off.ids +$REF --model $MODEL --tokens-file $D/off.ids --n 0 --pos-offset 20000 --dump-logits $D/off.ref.logits +$P $T/cmp_logits.py $D/off_fp32.pt $D/off.ref.logits +$REF --model $MODEL --tokens-file $D/off.ids --n 0 --dump-logits $D/off0.ref.logits +$P $T/cmp_logits.py $D/off_fp32.pt $D/off0.ref.logits +$REF --model $MODEL --tokens-file $D/long.ids --n 0 --dump-logits $D/long.ref.logits +$P $T/cmp_logits.py $D/long_fp32.pt $D/long.ref.logits +echo LONG-CHECK-DONE diff --git a/terminal/tools/inkling2/oracle.py b/terminal/tools/inkling2/oracle.py new file mode 100644 index 00000000000..4d8479b5b09 --- /dev/null +++ b/terminal/tools/inkling2/oracle.py @@ -0,0 +1,98 @@ +"""Inkling-2-Mini oracle: run the transformers PR #51050 reference on CPU and dump per-layer-application tensors. + +usage: oracle.py --model DIR --dtype float32|bfloat16 --out DIR [--prompts prompts.json] [--gen N] + +Dumps (safetensors, one file per prompt): + ids, logits (last position + all positions), and for each decoder-layer call k (0..47, in call order): + call{k}.layer, call{k}.in_h, call{k}.in_B, call{k}.msgs (loop passes 1-2 only), call{k}.out +Also the greedy continuation (--gen tokens) as text + ids in summary.json. +""" +import argparse, json, os, time +import torch +from safetensors.torch import save_file +from transformers import AutoTokenizer, Inkling2LoopForConditionalGeneration + +DEFAULT_PROMPTS = [ + {"name": "raw_en", "text": "The capital of France is"}, + {"name": "raw_fr", "text": "Le petit chat est monté sur le toit parce que"}, + {"name": "raw_code", "text": "def fibonacci(n):\n \"\"\"Return the n-th Fibonacci number.\"\"\"\n"}, + {"name": "chat_sky", "chat": [{"role": "user", "content": "Explain in one sentence why the sky is usually blue."}]}, +] + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--model", required=True, help="the Inkling-2-Mini checkpoint directory") + ap.add_argument("--dtype", default="float32") + ap.add_argument("--out", required=True) + ap.add_argument("--prompts") + ap.add_argument("--gen", type=int, default=16) + ap.add_argument("--threads", type=int, default=48) + a = ap.parse_args() + torch.set_num_threads(a.threads) + os.makedirs(a.out, exist_ok=True) + dtype = getattr(torch, a.dtype) + prompts = json.load(open(a.prompts)) if a.prompts else DEFAULT_PROMPTS + + t0 = time.time() + tok = AutoTokenizer.from_pretrained(a.model) + model = Inkling2LoopForConditionalGeneration.from_pretrained(a.model, dtype=dtype, device_map="cpu") + model.eval() + print(f"loaded in {time.time() - t0:.0f}s", flush=True) + + text_model = model.model.language_model if hasattr(model.model, "language_model") else model.model + layers = list(text_model.layers) + calls = [] + + def hook(mod, args, kwargs, out): + if not calls_enabled[0]: + return + h = args[0] if args else kwargs["hidden_states"] + B = args[1] if len(args) > 1 else kwargs["block_states"] + msgs = args[2] if len(args) > 2 else kwargs.get("messages") + calls.append({"layer": layers.index(mod), "in_h": h, "in_B": B, "msgs": msgs, "out": out}) + + calls_enabled = [True] + for L in layers: + L.register_forward_hook(hook, with_kwargs=True) + + summary = {"dtype": a.dtype, "prompts": []} + for p in prompts: + if "chat" in p: + ids = tok.apply_chat_template(p["chat"], tokenize=True, add_generation_prompt=True, return_tensors="pt") + ids = ids["input_ids"] if isinstance(ids, dict) or hasattr(ids, "keys") else ids + else: + ids = tok(p["text"], return_tensors="pt").input_ids + calls.clear() + calls_enabled[0] = True + t = time.time() + with torch.no_grad(): + out = model(input_ids=ids, use_cache=False) + fwd_s = time.time() - t + assert len(calls) == 48, len(calls) + tensors = {"ids": ids[0].to(torch.int64).contiguous(), "logits": out.logits[0].float().contiguous().clone()} + for k, c in enumerate(calls): + tensors[f"call{k}.layer"] = torch.tensor([c["layer"]], dtype=torch.int64) + tensors[f"call{k}.in_h"] = c["in_h"][0].float().contiguous().clone() + tensors[f"call{k}.in_B"] = c["in_B"][0].float().contiguous().clone() + tensors[f"call{k}.out"] = c["out"][0].float().contiguous().clone() + if c["msgs"] is not None: + tensors[f"call{k}.msgs"] = c["msgs"][0].float().contiguous().clone() + save_file(tensors, os.path.join(a.out, f"{p['name']}.safetensors")) + + calls_enabled[0] = False + with torch.no_grad(): + g = model.generate(input_ids=ids, max_new_tokens=a.gen, do_sample=False) + new = g[0, ids.shape[1]:].tolist() + top5 = torch.topk(out.logits[0, -1].float(), 5) + rec = {"name": p["name"], "n_tokens": ids.shape[1], "fwd_s": round(fwd_s, 1), + "top5_ids": top5.indices.tolist(), "top5_logits": [round(x, 4) for x in top5.values.tolist()], + "gen_ids": new, "gen_text": tok.decode(new)} + summary["prompts"].append(rec) + print(json.dumps(rec, ensure_ascii=False), flush=True) + json.dump(summary, open(os.path.join(a.out, "summary.json"), "w"), ensure_ascii=False, indent=1) + print("ORACLE-DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/terminal/tools/inkling2/pack_check.py b/terminal/tools/inkling2/pack_check.py new file mode 100644 index 00000000000..9323da1fe63 --- /dev/null +++ b/terminal/tools/inkling2/pack_check.py @@ -0,0 +1,25 @@ +"""pack_check.py REPO PACK MODEL [TEXT...]: load the extracted pack exactly as server.py does, compare to HF on the +text files given and on terminal/serve/frontend.py.""" +import json, pathlib, sys +repo, pack, model = sys.argv[1:4] +sys.path.insert(0, f"{repo}/terminal/tools") +import strata_tokenizer as ST +from transformers import AutoTokenizer +tpath = pathlib.Path(pack, "tokenizer") +vocab = json.loads((tpath / "vocab.json").read_text(encoding="utf-8")) +tokens = [None] * len(vocab) +for t, i in vocab.items(): + tokens[i] = t +merges = (tpath / "merges.txt").read_text(encoding="utf-8").split("\n") +types = json.loads((tpath / "token_type.json").read_text()) +tcfg = json.loads((tpath / "tokenizer.json").read_text(encoding="utf-8")) +tok = ST.Tokenizer(tokens, merges, types, tcfg.get("pre") or "qwen35", tcfg.get("special_ids") or None, + bool(tcfg.get("ignore_merges"))) +hf = AutoTokenizer.from_pretrained(model) +bad = 0 +for f in sys.argv[4:] + [f"{repo}/terminal/serve/frontend.py"]: + s = open(f).read() + a, b = tok.encode(s), hf(s, add_special_tokens=False, split_special_tokens=True).input_ids + bad += a != b + print(f, len(a), "OK" if a == b else "MISMATCH") +print("PACK-CHECK", "OK" if bad == 0 else "FAIL") diff --git a/terminal/tools/inkling2/ref_cmp.py b/terminal/tools/inkling2/ref_cmp.py new file mode 100644 index 00000000000..3ecb0cb7810 --- /dev/null +++ b/terminal/tools/inkling2/ref_cmp.py @@ -0,0 +1,19 @@ +"""Compare strata-ink2ref dumps with the transformers oracle. usage: ref_cmp.py ORACLE.safetensors LAYERS.bin LOGITS.bin""" +import sys, numpy as np, torch +from safetensors.torch import load_file +o = load_file(sys.argv[1]); T = o["ids"].numel(); H = 2304 +lay = np.fromfile(sys.argv[2], dtype=np.float32).reshape(T, 48, H) +lg = np.fromfile(sys.argv[3], dtype=np.float32).reshape(T, -1) +names = [f"L{l}" for l in range(6)] + [f"L{l}p{p}" for p in range(3) for l in range(6, 18)] + [f"L{l}" for l in range(18, 24)] +first_bad = None +for k in range(48): + ref = o[f"call{k}.out"].numpy(); got = lay[:, k] + rel = np.linalg.norm(got - ref, axis=1) / np.maximum(np.linalg.norm(ref, axis=1), 1e-30) + if rel.max() > 1e-3 and first_bad is None: first_bad = k + print(f"call{k:2d} {names[k]:7s} rel_err max {rel.max():.2e} (pos {rel.argmax()}) |ref| {np.linalg.norm(ref[-1]):.3f}") +ol = o["logits"].double(); gl = torch.from_numpy(lg).double() +lp, lq = torch.log_softmax(ol, -1), torch.log_softmax(gl, -1) +kl = (lp.exp() * (lp - lq)).sum(-1) +print("logits max|d|", (ol - gl).abs().max().item(), " KL per pos", [round(x, 6) for x in kl.tolist()], + " top1 agree", (ol.argmax(-1) == gl.argmax(-1)).float().mean().item()) +print("FIRST-DIVERGING-CALL", first_bad) diff --git a/terminal/tools/inkling2/ref_run.sh b/terminal/tools/inkling2/ref_run.sh new file mode 100755 index 00000000000..bc887ce1be7 --- /dev/null +++ b/terminal/tools/inkling2/ref_run.sh @@ -0,0 +1,10 @@ +#!/bin/bash +# ref_run.sh PROMPT: run strata-ink2ref on an oracle.py prompt's ids and compare its per-layer outputs and logits. +# Environment: PY (the oracle venv's python), ORACLE (oracle.py --out directory), WORK (dump directory), REF (the +# strata-ink2ref binary), MODEL (the Inkling-2-Mini checkpoint directory); N generated tokens (16) +: "${PY:?}" "${ORACLE:?}" "${WORK:?}" "${REF:?}" "${MODEL:?}" +T=$(dirname "$0"); O=$ORACLE/$1.safetensors; D=$WORK; mkdir -p $D +ids=$($PY -I -c "from safetensors.torch import load_file; print(\",\".join(map(str, load_file(\"$O\")[\"ids\"].tolist())))") +$REF --model $MODEL --tokens $ids --n ${N:-16} --dump-layers $D/$1.layers --dump-logits $D/$1.logits +$PY -I $T/ref_cmp.py $O $D/$1.layers $D/$1.logits +grep -o "\"name\": \"$1\".*\"gen_ids\": \[[0-9, ]*\]" $ORACLE/summary.json | grep -o "gen_ids.*" diff --git a/terminal/tools/inkling2/setup-venv.sh b/terminal/tools/inkling2/setup-venv.sh new file mode 100755 index 00000000000..eb909fccc51 --- /dev/null +++ b/terminal/tools/inkling2/setup-venv.sh @@ -0,0 +1,13 @@ +#!/bin/bash +# setup-venv.sh DIR: a venv in DIR for the transformers PR #51050 oracle (CPU torch); needs git and uv on PATH +set -ex +cd "${1:?usage: setup-venv.sh DIR}" +[ -d transformers ] || git clone -q --filter=blob:none https://github.com/huggingface/transformers.git +cd transformers && git fetch -q origin pull/51050/head:pr-51050 && git checkout -q pr-51050 && git log -1 --format="%h %ad %s" --date=iso && cd .. +uv venv -p 3.12 .venv +. .venv/bin/activate +uv pip install --index-url https://download.pytorch.org/whl/cpu torch +uv pip install -e ./transformers safetensors tiktoken numpy accelerate pillow +uv pip install --index-url https://download.pytorch.org/whl/cpu torchvision # the image processor (vision_oracle.py, vision_kl.py) +python -c "import torch, transformers; print(torch.__version__, transformers.__version__); from transformers import Inkling2LoopForConditionalGeneration; print(\"OK\")" +echo SETUP-DONE diff --git a/terminal/tools/inkling2/tok_check.py b/terminal/tools/inkling2/tok_check.py new file mode 100644 index 00000000000..0ab73d07e1d --- /dev/null +++ b/terminal/tools/inkling2/tok_check.py @@ -0,0 +1,73 @@ +"""tok_check.py: Strata's tokenizer (tools/strata_tokenizer.py, pre "gpt-4o") vs the HF tokenizer of Inkling-2-Mini. + +1. GPT4O_PATTERN must equal the regex in the model's tokenizer.json (copied, not re-typed); +2. ids must match HF on a corpus: per paragraph and per whole file (EN/FR prose, the bench prompts, Strata docs, C++ and + Python sources, unicode edge cases), and on rendered chat prompts with parse_special; +3. decode(encode(s)) == s. +usage: tok_check.py MODEL_DIR STRATA_REPO [TEXT...] [--extract OUT_DIR] (TEXT: extra corpus files) +""" +import glob, json, pathlib, sys, time + +model, repo = sys.argv[1], sys.argv[2] +sys.path.insert(0, f"{repo}/terminal/tools") +import strata_tokenizer as st +from transformers import AutoTokenizer + +tj = json.loads(pathlib.Path(model, "tokenizer.json").read_text()) +hf_pat = tj["pre_tokenizer"]["pretokenizers"][0]["pattern"]["Regex"] +assert hf_pat == st.GPT4O_PATTERN, "GPT4O_PATTERN differs from tokenizer.json" +print("pattern: identical to tokenizer.json") + +hf = AutoTokenizer.from_pretrained(model) +t0 = time.time() +tk = st.Tokenizer.from_hf(pathlib.Path(model, "tokenizer.json"), "gpt-4o", {"eos": 200006}) +print(f"strata tokenizer: {len(tk.tokens)} tokens, {len(tk.ranks)} merges, {len(tk.special_tokens)} special, {time.time() - t0:.1f}s") + +files = sys.argv[3:] # extra corpus files, minus "--extract OUT_DIR" +if "--extract" in files: + i = files.index("--extract") + files = files[:i] + files[i + 2:] +files += sorted(glob.glob(f"{repo}/docs/*.md"))[:12] +files += [f"{repo}/engine/src/inkling2/ink2_engine.cu", f"{repo}/terminal/serve/frontend.py"] +edge = ["Hello, world! It's 2026; they'll've done it.", "L'été où j'ai vu l'œuf — «déjà» ?", "ÉCOLE École école ÉCOLE's", + "naïve café́ é́ कि", "😀👍🏽 🇫🇷 a‍b", "你好,世界 こんにちは 안녕하세요", "مرحبا بالعالم", + " leading\t\ttabs\n\n\n trailing ", "x = 1234567 + 89.01e-5; // 0x1F", "path/to/file.py:42 http://a.b/c?d=e&f", + "\x00\x01\x1f\x7f ctrl", "CamelCaseIdentifierHTTPServer getHTTPResponseCode", "a\r\nb\rc\n\r\nd", "I'M SHOUTING'S"] +docs = [(f, open(f, errors="replace").read()) for f in files if pathlib.Path(f).is_file()] +pieces = [("edge", s) for s in edge] +for f, txt in docs: + pieces.append((f, txt)) + pieces += [(f + "#p", p) for p in txt.split("\n\n") if p.strip()] +chats = [[{"role": "user", "content": "Explique en une phrase pourquoi le ciel est bleu."}], + [{"role": "system", "content": "Tu es concis."}, {"role": "user", "content": open(f"{repo}/README.md").read()}], + [{"role": "user", "content": "2+2?"}, {"role": "assistant", "content": "4", "reasoning_content": "easy"}, + {"role": "user", "content": "et 3+3 ?"}]] +bad, n, nchar = 0, 0, 0 +t0 = time.time() +for name, s in pieces: + a = tk.encode(s) # raw text: markers are text (Strata's parse_special=False); HF matches them unless told not to + b = hf(s, add_special_tokens=False, split_special_tokens=True).input_ids + n += 1 + nchar += len(s) + if a != b: + bad += 1 + if bad <= 5: + k = next(i for i in range(min(len(a), len(b)) + 1) if i >= min(len(a), len(b)) or a[i] != b[i]) + print(f"MISMATCH {name}: at token {k}: strata {a[k:k + 6]} hf {b[k:k + 6]} | " + f"{tk.decode(a[max(0, k - 3):k + 4])!r} vs {hf.decode(b[max(0, k - 3):k + 4])!r}") + if tk.decode(a) != s: + print(f"ROUNDTRIP {name}: decode(encode(s)) != s") + bad += 1 +for c in chats: + s = hf.apply_chat_template(c, tokenize=False, add_generation_prompt=True) + a = tk.encode(s, parse_special=True) + b = hf(s, add_special_tokens=False).input_ids + n += 1 + if a != b: + bad += 1 + print(f"MISMATCH chat ({len(a)} vs {len(b)} ids)") +print(f"{n} strings, {nchar} chars, {bad} mismatches, encode {time.time() - t0:.1f}s") +if "--extract" in sys.argv and bad == 0: + out = sys.argv[sys.argv.index("--extract") + 1] + print("pack:", st.extract_hf(model, out, "gpt-4o", {"eos": 200006})) +print("TOK-CHECK-DONE", "OK" if bad == 0 else "FAIL") diff --git a/terminal/tools/inkling2/vis_cmp.py b/terminal/tools/inkling2/vis_cmp.py new file mode 100644 index 00000000000..79b03e6d3d1 --- /dev/null +++ b/terminal/tools/inkling2/vis_cmp.py @@ -0,0 +1,28 @@ +"""strata-ink2 --dump-logits of a prompt with a picture against vision_kl.py's .pt (or a text kl_run.py .pt). +usage: vis_cmp.py ORACLE.pt OURS.logits [IMAGE_TOKEN]""" +import sys +import numpy as np +import torch + +o = torch.load(sys.argv[1]) +ref = o["logits"].double() +T, V = ref.shape +ours = torch.from_numpy(np.fromfile(sys.argv[2], dtype=np.float32).reshape(-1, V)).double() +assert ours.shape[0] == T, (ours.shape, T) +img = int(sys.argv[3]) if len(sys.argv) > 3 else 200054 +ids = o["ids"] +lp, lq = torch.log_softmax(ref, -1), torch.log_softmax(ours, -1) +kl = (lp.exp() * (lp - lq)).sum(-1) +top1 = ref.argmax(-1) == ours.argmax(-1) +d = (ref - ours).abs().amax(-1) +isimg = ids == img +first = int(isimg.nonzero()[0]) if isimg.any() else T +last = int(isimg.nonzero()[-1]) if isimg.any() else -1 +parts = {"all": torch.ones(T, dtype=torch.bool), "before picture": torch.arange(T) < first, "picture": isimg, + "after picture": torch.arange(T) > last} +for name, m in parts.items(): + if m.sum() == 0: + continue + k = kl[m] + print(f"{name:15s} T={int(m.sum()):5d} KL mean {k.mean():.2e} median {k.median():.2e} max {k.max():.2e} " + f"top1 {top1[m].float().mean() * 100:.1f}% max|dlogit| {d[m].max():.2e}") diff --git a/terminal/tools/inkling2/vision_kl.py b/terminal/tools/inkling2/vision_kl.py new file mode 100644 index 00000000000..67111d0be21 --- /dev/null +++ b/terminal/tools/inkling2/vision_kl.py @@ -0,0 +1,58 @@ +"""Inkling-2-Mini with a picture, end to end (transformers PR #51050 on the CPU): all-position logits of a chat prompt +with one picture, and its greedy continuation, for strata-ink2 --image --dump-logits (compare with kl_cmp-style KL). + +usage: vision_kl.py --model DIR --out PREFIX --image FILE [--image FILE ...] [--together] [--dtype float32] [--gen N] + +Per picture k (PREFIX.k.*): .pt {"ids": the processor-expanded prompt, "logits": [T][V] fp32, "gen": greedy ids}, +.ids1 (the prompt with one <|unused_200054|> per picture: what strata-ink2 --tokens-file takes with --image). +One model load for all pictures. +""" +import argparse, json, time +import torch +from transformers import AutoProcessor, Inkling2LoopForConditionalGeneration + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--model", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--image", action="append", required=True) + ap.add_argument("--prompt", default="Describe this picture in one sentence.") + ap.add_argument("--effort", default="none") + ap.add_argument("--dtype", default="float32") + ap.add_argument("--gen", type=int, default=24) + ap.add_argument("--threads", type=int, default=48) + ap.add_argument("--together", action="store_true", help="all pictures in one message (one prompt, PREFIX.0.*)") + a = ap.parse_args() + torch.set_num_threads(a.threads) + proc = AutoProcessor.from_pretrained(a.model) + t = time.time() + model = Inkling2LoopForConditionalGeneration.from_pretrained(a.model, dtype=getattr(torch, a.dtype), device_map="cpu").eval() + print(f"loaded in {time.time() - t:.0f}s", flush=True) + groups = [a.image] if a.together else [[img] for img in a.image] + for k, imgs in enumerate(groups): + img = ",".join(imgs) + msgs = [{"role": "user", "content": [{"type": "image", "image": i} for i in imgs] + [{"type": "text", "text": a.prompt}]}] + inp = proc.apply_chat_template(msgs, tokenize=True, add_generation_prompt=True, return_dict=True, + return_tensors="pt", reasoning_effort=a.effort) + ids = inp["input_ids"][0].tolist() + one, prev = [], None + for x in ids: + if not (x == proc.image_token_id and prev == proc.image_token_id): + one.append(x) + prev = x + open(f"{a.out}.{k}.ids1", "w").write(",".join(map(str, one))) + t = time.time() + with torch.no_grad(): + logits = model(**inp, use_cache=False).logits[0].float() + fwd = time.time() - t + g = model.generate(**inp, max_new_tokens=a.gen, do_sample=False) + gen = g[0, len(ids):].tolist() + torch.save({"ids": inp["input_ids"][0], "logits": logits, "gen": gen}, f"{a.out}.{k}.pt") + print(json.dumps({"image": img, "grid": inp["image_grid_thw"].tolist(), "tokens": len(ids), "fwd_s": round(fwd, 1), + "gen_ids": gen, "gen_text": proc.tokenizer.decode(gen)}, ensure_ascii=False), flush=True) + print("VISION-KL-DONE", flush=True) + + +if __name__ == "__main__": + main() diff --git a/terminal/tools/inkling2/vision_oracle.py b/terminal/tools/inkling2/vision_oracle.py new file mode 100644 index 00000000000..fe34194fffc --- /dev/null +++ b/terminal/tools/inkling2/vision_oracle.py @@ -0,0 +1,87 @@ +"""Inkling-2-Mini image path reference (transformers PR #51050, fp32 on the CPU), for strata-ink2's ViT + projector. + +usage: vision_oracle.py --model DIR --image FILE --out PREFIX [--prompt TEXT] [--layers] + +Writes, for one picture through the model's own processor: + PREFIX.pix the processor's pixel tensor: int32 rows, int32 cols, then float32 [rows*cols][40][40][3] + (strata-ink2 --vis-pixels reads it: the ViT on exactly these numbers) + PREFIX.emb the vision tower's output (one row per image token): float32 [rows*cols][2304] + PREFIX.ids the chat prompt with the picture (processor-expanded placeholders), comma-separated token ids + PREFIX.ids1 the same prompt with one placeholder per picture (what Strata's server sends the engine) + PREFIX.layers (--layers) the ViT hidden states after embeddings+ln_pre and after each layer: float32 [24][1+4n][1024] +Only the vision tower is loaded (its 422 tensors), so this runs in seconds; kl_run.py-style full-model logits of the +multimodal prompt are vision_kl.py's job. +""" +import argparse, json, re +import numpy as np +import torch +from safetensors import safe_open +from transformers import AutoConfig, AutoProcessor +from transformers.models.inkling2.modeling_inkling2 import Inkling2VisionModel + +RENAMES = [(r"^backbone\.embeddings\.position_embedding$", "embeddings.position_embedding.weight"), + (r"^backbone\.embeddings\.", "embeddings."), (r"^backbone\.ln_pre\.", "pre_layernorm."), + (r"^backbone\.layers\.", "layers."), (r"^proj_in\.", "merger.linear_1."), (r"^proj_out\.", "merger.linear_2."), + (r"\.ln_1\.", ".layernorm_before."), (r"\.ln_2\.", ".layernorm_after."), (r"\.mlp\.c_fc\.", ".mlp.fc1."), + (r"\.mlp\.c_proj\.", ".mlp.fc2."), (r"\.ls_1\.gamma$", ".lambda_1"), (r"\.ls_2\.gamma$", ".lambda_2")] + + +def load_vision(model_dir): + cfg = AutoConfig.from_pretrained(model_dir) + vm = Inkling2VisionModel(cfg.vision_config).float().eval() + sd = {} + with safe_open(f"{model_dir}/model-00001-of-00001.safetensors", "pt") as f: + for k in f.keys(): + if not k.startswith("model.visual."): + continue + n = k[len("model.visual."):] + for a, b in RENAMES: + n = re.sub(a, b, n) + sd[n] = f.get_tensor(k).float() + missing, unexpected = vm.load_state_dict(sd, strict=False) + missing = [m for m in missing if "inv_freq" not in m] + assert not missing and not unexpected, (missing, unexpected) + return vm + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--model", required=True) + ap.add_argument("--image", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--prompt", default="Describe this picture in one sentence.") + ap.add_argument("--effort", default="none") + ap.add_argument("--layers", action="store_true") + a = ap.parse_args() + torch.set_num_threads(16) + proc = AutoProcessor.from_pretrained(a.model) + msgs = [{"role": "user", "content": [{"type": "image", "image": a.image}, {"type": "text", "text": a.prompt}]}] + inp = proc.apply_chat_template(msgs, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt", + reasoning_effort=a.effort) + pix, grid = inp["pixel_values"].float(), inp["image_grid_thw"] + t, rows, cols = grid[0].tolist() + ids = inp["input_ids"][0].tolist() + img = proc.image_token_id + one, prev = [], None + for x in ids: # one placeholder per picture, as the template renders it before expansion + if not (x == img and prev == img): + one.append(x) + prev = x + with open(a.out + ".pix", "wb") as f: + np.array([rows, cols], dtype=np.int32).tofile(f) + pix.numpy().astype(np.float32).tofile(f) + open(a.out + ".ids", "w").write(",".join(map(str, ids))) + open(a.out + ".ids1", "w").write(",".join(map(str, one))) + vm = load_vision(a.model) + with torch.no_grad(): + out = vm(pixel_values=pix, image_grid_thw=grid, output_hidden_states=a.layers) + out.pooler_output.float().numpy().tofile(a.out + ".emb") + if a.layers: + torch.stack([h.float() for h in out.hidden_states]).numpy().tofile(a.out + ".layers") + print(json.dumps({"image": a.image, "grid": [t, rows, cols], "pix_shape": list(pix.shape), "tokens": len(ids), + "image_tokens": ids.count(img), "pix_min": pix.min().item(), "pix_max": pix.max().item(), + "hidden_states": len(out.hidden_states) if a.layers else 0})) + + +if __name__ == "__main__": + main() diff --git a/terminal/tools/strata_tokenizer.py b/terminal/tools/strata_tokenizer.py index 872d9c72693..441ec09ced6 100644 --- a/terminal/tools/strata_tokenizer.py +++ b/terminal/tools/strata_tokenizer.py @@ -94,6 +94,7 @@ def bytes_to_unicode() -> dict[int, str]: r"|\s+" ) O200K_PRES = ("o200k", "o200k_base", "gpt-4o", "inkling", "inkling2") +GPT4O_PATTERN = O200K_PATTERN # the name tools/inkling2/tok_check.py checks against the model's tokenizer.json # The `qwen2` pre-tokenizer (Qwen2 / Qwen3-Next; llama.cpp LLAMA_VOCAB_PRE_TYPE_QWEN2, @@ -154,10 +155,12 @@ def pre_tokenizer_kind(pre) -> str | None: class Tokenizer: def __init__(self, tokens: list[str], merges: list[str], token_types: list[int] | None = None, - pre: str = "qwen35", special_ids: dict[str, int] | None = None): + pre: str = "qwen35", special_ids: dict[str, int] | None = None, ignore_merges: bool = False): self.tokens = tokens self.pre = pre - self.ignore_merges = pre in O200K_PRES + # HF BPE `ignore_merges` (a pack's tokenizer.json says it; the o200k rule implies it): a pre-token piece that is + # itself a vocab entry is that one token, whatever the merges would make of it + self.ignore_merges = bool(ignore_merges) or pre in O200K_PRES if pre_tokenizer_kind(pre) is None: # Not a fallback: another model's pre-tokenizer splits text differently, so encoding with the qwen35 rule would # change every prompt without any error (llama.cpp has one rule per `tokenizer.ggml.pre` type for the same reason). @@ -286,7 +289,7 @@ def from_hf(cls, tokenizer_json, pre: str = "gpt-4o", special_ids: dict[str, int sp["tokenizer.ggml.eos_token_id"] = int(ids[eos]) except Exception: pass - return cls([str(x) for x in tokens], merges, [types.get(i, 1) for i in range(n)], pre, sp) + return cls([str(x) for x in tokens], merges, [types.get(i, 1) for i in range(n)], pre, sp, bool(m.get("ignore_merges"))) # -------------------------------------------------------------- the algorithm def _bpe(self, word: str) -> list[str]: diff --git a/terminal/tools/test_setup_model_pins.py b/terminal/tools/test_setup_model_pins.py index dac4bc99a0f..c1df14a913b 100644 --- a/terminal/tools/test_setup_model_pins.py +++ b/terminal/tools/test_setup_model_pins.py @@ -95,7 +95,7 @@ def test_every_pin_is_well_formed_and_every_repository_is_pinned(self): for name, (size, sha) in files.items(): with self.subTest(repo=repo, file=name): self.assertIsInstance(size, int) - self.assertGreater(size, 1000) + self.assertGreater(size, 50 if name.endswith((".json", ".jinja")) else 1000) # (a checkpoint's small config files) self.assertRegex(sha, HEX) def test_known_values(self):