diff --git a/docs/MAC.md b/docs/MAC.md new file mode 100644 index 00000000..17cd931f --- /dev/null +++ b/docs/MAC.md @@ -0,0 +1,209 @@ +# Strata on a Mac (Apple Silicon, Metal) + +Strata runs on Apple Silicon Macs through its own engine on Metal. This is the same engine as on a PC. The NVIDIA +kernels are replaced by Metal ones (`metal/`), and the host code and the server are the PC's. `./setup.sh` sets it up the way +`START-HERE.bat` does on Windows. There is no ready-made Mac engine: setup builds it from source on your Mac +(about 1-15 minutes). The NVIDIA, AMD and Intel engines are unchanged. + +**Status:** new. It is measured on two Macs: an M5 Max with 128 GB, where the model stays in memory, and an M4 Mac mini +with 32 GB, where the experts stream from the SSD. Other chips and memory sizes are untested, and reports help +([COMMUNITY_BENCHMARKS.md](COMMUNITY_BENCHMARKS.md)). + +## What you need + +- **An Apple Silicon Mac (M1 or newer).** Intel Macs cannot run it. +- **macOS 15 or newer.** The engine keeps its buffers resident through a residency set, which macOS 15 introduced. +- **The Command Line Tools:** `xcode-select --install`. That is the compiler. Xcode itself is not needed. +- **Enough unified memory for the pack.** The GPU maps the model's main file and keeps it in memory while the model runs. Metal lets one + program keep about 3/4 of the memory resident (107.5 GB of 128 GB, measured on the M5 Max). + +| Pack | The file the GPU maps | Needs about (with the prompt buffers, KV cache, draft layer) | Recommended from | +|---|---|---|---| +| Q2_0 | 37.6 GB | 46 GB | 64 GB | +| IQ3_XXS | 47.0 GB | 55 GB | 74 GB (where IQ3_S does not fit) | +| IQ3_S (recommended; the default from 96 GB) | 54.8 GB | 63 GB | 96 GB | +| UD-Q4_K_XL (Unsloth, recommended: higher quality) | 82.6 GB | 91 GB | 128 GB | +| UD-Q5_K_XL, UD-Q6_K_XL (Unsloth) | 103.9 / 114.8 GB | stream from the SSD on 128 GB | 128 GB, streamed | + +- **The n-gram table:** each pack also has a 28.8 GB n-gram table (the model's second file). It is read from the SSD a few rows at a time and does not count against the memory above. +- **Disk:** the download is 66-84 GB, plus about 7 GB for the pack and the draft layer. A Mac that streams also needs room for the experts' copy (below): 34-40 GB. +- **A Mac whose memory cannot hold the pack (32-48 GB):** the engine streams the experts from the SSD instead. It decides this by itself when the experts are more than 60% of Metal's share. + - It keeps the most-used experts in an arena: Metal's share, or the memory macOS reports as available less what it keeps for macOS, whichever is smaller. It keeps 7 GB, or 15% of the RAM when that is more, and it also keeps the n-gram table's share. It counts as free only what macOS can give without swapping (free and purgeable memory and the clean file cache, not other programs' idle memory). It checks again just before it takes the arena, and fills the arena in 1.5 GB steps, checking again before each one; it stops early rather than push macOS below what it keeps. + - It reads the rest as each token needs them, and reads ahead the experts the next layer will probably use. + - Setup writes a second copy of the experts for such a Mac (`.experts`, 40 GB for IQ3_XXS). In it each expert's three matrices sit together, so the SSD reads an expert with one request instead of three. On the 32 GB M4 that is about 17% faster decoding and 30% faster prompts, with the same tokens. Setup writes it only when the disk has room for it plus 10 GB; otherwise it warns, and the engine reads the model file as before. + - Setup configures such a Mac without the MTP draft layer: one token per step is faster there. + - Measured at 32 GB (below). Smaller Macs are untested. +- **Setup recommends, and never forces.** It recommends the pack by memory; a bigger pack chosen with `--model` is kept, with a warning about what it risks. + +## Install + +``` +git clone https://github.com/Niko1221/Strata && cd Strata +./setup.sh # asks the size; --yes takes the recommended answers +``` + +What the first run does (each step is skipped when it is already done): + +1. **Python.** It needs Python 3.10 or newer, but macOS ships 3.9. If that is all your Mac has, `setup.sh` downloads a standalone Python 3.12 (25 MB, pinned by SHA-256) into `.python`. No sudo, no Homebrew. +2. **Checks your Mac:** the chip, the memory, the macOS version, the Command Line Tools and the free disk. +3. **Python packages** into `.venv`. CMake and Ninja come from pip. +4. **Builds the engine** (`build-metal/strata`). It uses Apple's metal-cpp headers (pinned by SHA-256) and llama.cpp's ggml at the commit the PC build pins. +5. **Downloads the model.** The download resumes if interrupted. `--gguf-dir` uses files you already have. +6. **Prepares the model:** the pack (seconds), and the MTP draft layer (about 5 GB of the original checkpoint). On a Mac that streams: the experts' copy instead of the draft layer (about 3 minutes on the M4, checked byte for byte against the model file). +7. **Writes `strata-.json` and `run-.sh`, then starts the server.** + +The config uses the Mac defaults: `--spec 2` and the Q8_0 hyper-connection read (below). After that, `./setup.sh` or `./run-q2_0.sh` starts the model directly. The server is the same as on a PC: +- the OpenAI-compatible API on `http://127.0.0.1:8080/v1`; +- the Anthropic API on `/v1/messages`; +- the chat page on `http://127.0.0.1:8080/`. + +Options: `--model Q2_0|IQ3_XXS|IQ3_S|UD-Q4_K_XL|UD-Q5_K_XL|UD-Q6_K_XL` (the UD files are Unsloth's), `--vision yes|no`, `--context N`, `--port`, `--host` / `--api-key`, `--draft-vocab`, `--no-browser`, +`--data-dir`, `--models-dir`, `--gguf-dir`, `--setup` (another model or new settings), `--no-start`, `--check` (only +check the Mac), `--build` (build the engine again). + +## Measured (M5 Max, 128 GB, macOS 27.2) + +**Decode**, in tokens per second over 200 generated tokens, with greedy answers. The table gives two prompts: a short question +("prompt1") and a story. + +| | Q2_0 | IQ3_XXS | IQ3_S | +|---|---|---|---| +| Setup's defaults (`--spec 2` with MTP, the suffix drafter on) | **119.5 / 108.2** | **108.9 / 97.0** | - | +| `--spec 2` with MTP, suffix drafter off | 114.0 / 107.9 | 103.5 / 96.9 | 98.2 / 94.1 | +| No MTP (one token per step) | 87.4 / 87.3 | 78.7 / 78.6 | 74.5 / 74.3 | + +The output with MTP is the same as without it, token for token, in every run. MTP only proposes tokens, and the +full model checks every one of them. + +**Prompt reading** (time to the first token), on the needle-test prompts below: + +| | 4K tokens | 32K tokens | +|---|---|---| +| Q2_0 | ~1,430 tok/s | ~1,460 tok/s | +| IQ3_XXS | ~1,260 tok/s | ~1,240 tok/s | +| IQ3_S | ~1,320 tok/s | ~1,140-1,190 tok/s | + +The first prompt after the Mac starts is slower, while macOS reads the model file (IQ3_S: 413 tok/s on the first 4K +prompt, cold). + +**For comparison**, llama.cpp on the same Mac with Q2_0: 56.6 tok/s decode on the story, and 887 / 809 tok/s on 4K / 32K prompts. + +### Unsloth's UD-Q4/Q5/Q6_K_XL on the M5 Max + +IQ3_S and UD-Q4_K_XL are the recommended sizes. Setup offers IQ3_S as the default and names UD-Q4_K_XL as the +higher-quality choice where it fits. Decode is tokens per second over 200 tokens (greedy, MTP); prompts are the warm rate +of the second request on (the first request after the start pays a few seconds of first-use cost). + +| | IQ3_S | UD-Q4_K_XL | UD-Q5_K_XL (streamed) | UD-Q6_K_XL (streamed) | +|---|---|---|---|---| +| Quality against Q8_0 (top-1 / KL) | 87.9% / 0.142 | 92.8% / 0.055 | not measured | not measured | +| Decode, short question, no MTP / MTP | 75.4 / 101.9 | 60.7 / 94.0 | - | - | +| Decode, story, no MTP / MTP | 74.8 / 94.7 | 59.7 / 73.7 | 28 / 46-51 (`--spec 3`) | not measured / 47-51 (`--spec 3`) | +| Prompt 4K / 32K | ~1,180 / ~1,290 | ~1,150 / ~1,290 | ~1,070 / ~1,110 | ~1,020 / ~1,020 | +| llama.cpp Metal, decode (story / code) | 51.1 / 44.1 | 48.4 / 47.3 | 45.1 / 43.2 | does not run (Insufficient Memory) | +| llama.cpp Metal, prompt 4K / 32K | 791 / 730 | 821 / 739 | 729 / 693 | - | + +- **UD-Q5 and UD-Q6 cannot stay resident:** their repacked file (103.9 and 114.8 GB) is bigger than the largest buffer Metal gives (86.6 GB), so the experts stream from the SSD into an arena of about 80-86 GB (80% of Q5's experts, 74% of Q6's). 98% of the lookups hit it. +- **The cost is a fixed hand-shake per layer** (the engine reads the router's choice and makes sure the experts are in the arena), not the SSD. A window of 2 tokens costs 38 ms against ~17 resident, so a longer window pays: Q5 story 28 tok/s without MTP, 41.8 with `--spec 2`, 50.6 with `--spec 3`, 46 with `--spec 4`. Setup writes `--spec 3` and keeps the MTP draft layer for a streaming Mac with 96 GB or more. +- **The arena is limited to 67% of the RAM together with the engine's other buffers.** Wired memory above that made macOS swap: with UD-Q6, a 90 GB arena swapped 29,000 pages in 8 seconds and the Mac later froze, an 84 GB arena ran clean. The "keep 15% free" rule alone did not catch it, because macOS counts file cache as available. +- **The experts' copy** (`.experts`, 98 GB for Q5) did not pay on the M5 Max: decode 50.3 against 50.2 tok/s without it, 4K prompt 741 against 685 (noisy). Setup does not write it on a Mac with 96 GB or more. +- **Prompts stream in chunks of 4096** on a streaming Mac with 96 GB or more (the engine's own default there; 1024 on a smaller one): every chunk makes one pass over the experts that are not in the arena, so a longer chunk reads them fewer times. UD-Q5, warm, 2 interleaved rounds: chunks of 1024 gave 700 tok/s on the 4K prompt, 2048 gave 920 and 4096 gave 1,100 (32K: 710, 970, 1,100); the decode did not change. `STRATA_METAL_PROMPT_CHUNK=N` sets it. On a resident model 4096 instead of 2048 gained only 2-4% (Q2_0), so that default stays. + +### M4 Mac mini, 32 GB, experts streamed from the SSD + +The arena was 11.5-14.7 GB. Tokens per second, one token per step (no MTP), medians of 5 interleaved runs: + +| | Q2_0 | IQ3_XXS | llama.cpp, CPU only (Q2_0 / IQ3_XXS) | +|---|---|---|---| +| Decode, short question (200 tokens) | **14.1** | **10.0** | 6.3 / 4.1 | +| Decode, story (200 tokens) | **13.5** | **9.2** | 6.3 / 4.1 | +| Decode after a 6K-token document | **13.1** | **7.7** | 5.1 / 2.8 | +| Prompt, 4K tokens | **93.6** | **65.8** | 21.2 / 8.7 | + +- The greedy answers equal the M5 Max's (model in memory) on 10 of 10 test prompts, for both packs. +- No memory was swapped out during the runs; the least memory left to macOS was 7.1 GB. +- MTP was slower here (Q2_0 story 12.1-12.3 with it against 12.3-12.8 without). The draft layer's 1.2 GB do more as expert cache. + +**The experts' copy** (`.experts`, one SSD request per expert): IQ3_XXS after the 6K-token document, the arena held at 12 GB, medians of 5 interleaved runs each: + +| | Decode | The 6K prompt | SSD wait per token | +|---|---|---|---| +| The model file (three reads per expert) | 7.37 tok/s | 64.7 tok/s | 46.6 ms | +| The experts' copy (one read per expert) | **8.62 tok/s** | **84.1 tok/s** | 31.5 ms | + +- The tokens are identical in all 10 runs. +- The 4K-token prompt (3 interleaved runs each, default arena): 72.9 tok/s with the copy against 62.5 with the model file (+17%), the same tokens. +- 32K-token prompts through the server, with the copy: 29,768 tokens at 89.2 tok/s (5.6 minutes to the first token), 33,803 tokens at 84.4 tok/s. The code word was found both times. +- A 34-minute server run with the copy (47 requests: 32K and 6K needles, short questions, a story, code; context 34,816) got every answer right and did not slow down over time. Decode was 7.2-7.7 tok/s on short answers and 9.9-10.4 on the story; the 6K prompts ran at 80-90 tok/s. macOS's memory pressure was never critical: one 2-second "warn" sample while the arena filled at the start. About 90 MB were swapped out in those same 2 seconds and nothing after; three restarts afterwards (smaller arenas, less memory free) swapped nothing. +- The SSD alone measures the same: 2.97 GB/s for one 1.75 MB read per expert against 2.30 GB/s for three 0.58 MB reads (6 threads, uncached). +- The arena's size matters most. With the model file, a 7.5 GB arena gave 5.5 tok/s, 10.5 GB gave 6.7 and 12 GB gave 7.5. The read-ahead depth, the I/O threads and the eviction order each moved decode by less than 3%. +- The Q2_0 copy is not measured yet. The numbers in the table above are with the model file. +- **Measured again on the release build, with less memory free:** the M4 had 13-17 GB available when the engine started (another user's programs held the rest), so the arena was 5.7 GB (Q2_0) and 9.3 GB (IQ3_XXS, with the experts' copy). One token per step, medians of 3: Q2_0 story 8.3 tok/s, 4K prompt 80; IQ3_XXS story 8.3, 4K prompt 89. That is the arena's size effect above, not a regression: with a 6.6 GB arena the engine used to stop at the first prompt ("no free slot"); a small arena now gives the prompt's 1.6 GB of buffers their own allocation, and a 26-minute server run with a 5.4 GB arena (29 requests, 6K and 31K needles found) was clean. +- With the default arena (12.1-12.2 GB here), the experts' copy gives 8.35-8.48 tok/s decode and 82.5-82.8 tok/s on the prompt. Nothing was swapped out. macOS's memory pressure stayed "normal", except for one 2-second "warn" sample while the arena fills; keeping 7 GB for macOS shows the same sample. +- Those runs and the server run below kept 5 GB for macOS. The default is now 7 GB with the stepped fill: after the 6K document, 7.3 and 6.7 tok/s decode (arenas 9.3 and 7.6 GB, as much as was free), the same tokens, the memory pressure "normal" throughout and nothing swapped out. + +**Why `--spec 2`:** measured with MTP on the same two prompts. + +| Window | Q2_0 (prompt1 / story) | IQ3_XXS (prompt1 / story) | +|---|---|---| +| `--spec 2` | 111 / 106 | 102 / 95 | +| `--spec 3` | 116 / 92 | 108 / 95 | +| `--spec 4` | 111 / 81 | 108 / 83 | +| `--spec 5-6` | slower | slower | + +`--spec 2` is the best default on mixed text. An explicit `--spec N` in the config's `args` is kept. + +### Quality + +- **The Q8_0 hyper-connection read is the default on Mac.** It keeps a Q8_0 copy of the hyper-connection matrices instead of BF16. `STRATA_HC_Q8=0` in the config's `env` gives the exact BF16 read. +- **How the KL was measured:** teacher-forced over 28 prompts (code, reasoning, chat, six languages, documents), about 6,000 positions per set. The reference is BF16. + - On the model's own text: mean KL 0.0007, top-1 agreement 98.9%. + - On another model's text: mean KL 0.0007, top-1 agreement 99.1%. + - Perplexity of the text is unchanged (×0.9995 and ×1.0006). + - For scale, IQ3_XXS against Q2_0 is a KL of 0.094. + - The Mac engine is deterministic: two runs give identical numbers. +- **The fast prompt path** (the prompt kernels) against reading the prompt through decode windows: mean KL 0.0004, top-1 99.4-99.6%. +- **Needles:** a code word hidden in 8K, 16K and 32K tokens of text, at 10/50/90% depth. Found 9 of 9 with Q2_0 and with IQ3_XXS, both with Q8_0 and with BF16. With the fast prompt path (4K-32K) the answers are the same. +- **Same answers as on a PC:** + - against the CUDA engine on a Tesla P100 (IQ3_XXS and IQ3_S), the first 200 tokens of a reply are identical on the short question; + - on the story, the first IQ3_S tokens differ at token 1, a near-tie (margin 0.12). Following the CUDA engine's tokens, 4 of 200 picks differ, all at margins 0.06-0.21; + - against the HIP engine on a Radeon AI PRO R9700 (Q2_0), 36 of 39 first tokens are identical. + - The differences are near-ties between the two best tokens, from a different floating-point order. + +## Limits (this version) + +- **Images (vision):** `--vision yes` in setup. Checked on one test picture with Q2_0 and UD-Q4_K_XL: the answers equal the HIP engine's, and text output is unchanged with vision on. No other tests yet. +- **Context:** measured up to 32K (needles, KL). Setup recommends 32K below 96 GB and 64K from 96 GB. Up to the model's 262K can be set, but it is not measured. +- **One request at a time.** `--parallel` (batch slots) is not ported. Several clients queue. +- **Not ported:** the control vector (`--control-vector-scaled`) and the PC tuning (`--calibrate`). +- **Streaming:** measured at 32 GB only. The model's file must be on the internal SSD; an external disk is untested and likely much slower. +- **Families:** the original Qwen3.8-Flash-Next and Unsloth's UD-Q4/Q5/Q6_K_XL are measured (above). Setup repacks Unsloth's shards into one file for the GPU. The Swift and Coder releases are not set up on Mac yet, and Qwen3.6 does not run on the Mac engine. +- **Engine only from source.** There is no ready-made Mac engine in the release zips. + +## Switches (for testing; all off unless set, the defaults are above) + +| Variable | Effect | +|---|---| +| `STRATA_HC_Q8=0` | The BF16 hyper-connection read (exact) instead of Q8_0 | +| `STRATA_METAL_PROMPT=window` | Read the prompt through decode windows (the slow, exact fallback; ~190 tok/s) | +| `STRATA_METAL_PROMPT_CHUNK=N` | Prompt chunk size (default 2048) | +| `STRATA_METAL_MTP_Q8=0` | The draft layer's matrices in BF16 instead of Q8_0 | +| `STRATA_METAL_MTP_CHAIN=0` | One GPU submission per draft step instead of one per round | +| `STRATA_METAL_FUSE=0`, `STRATA_METAL_LAZY_FOLD=0` | Turn off two decode fusions (same tokens, slower) | +| `STRATA_METAL_PARTIAL=1`, `STRATA_METAL_ROUTE=1` | Two decode variants that measured no faster here (same tokens) | +| `STRATA_METAL_STREAM=1` / `=0` | Stream the experts from the SSD even when the pack fits / never (the default decides by size) | +| `STRATA_METAL_CONTIG=0` | Streaming: read the model file even when the experts' copy is there | +| `STRATA_METAL_ARENA_GB=N`, `STRATA_METAL_KEEP_FREE_GB=N` | Streaming: the arena's size, or the memory left to macOS when the arena is sized | +| `STRATA_METAL_KEEP_HOST_WEIGHTS=1` | Streaming: keep the host code's own copies of the weights (2-3 GB) instead of giving them back to macOS | +| `STRATA_METAL_TRACE=1`, `STRATA_METAL_PROFILE=1`, `STRATA_METAL_KPROF=T` | Per-window traces, a time breakdown, per-kernel GPU times | + +## How it works + +The code is in `metal/` (the engine's side in `metal/src/engine`, the kernels in `metal/kernels`). In short: +- **Host code:** the PC host code compiles unchanged for macOS. `metal/include/metal_compat` maps the CUDA runtime calls it makes onto a small Metal runtime (`metal/src/gpu`). +- **The decode and prompt work** run in Metal kernels (`metal/kernels`, `metal/src/engine`): + - one command buffer per verify window; + - the experts are read in place from the mapped model file; + - the hyper-connections, the GDN state and the QSA attention stay on the GPU; + - a whole MTP draft round runs in one command buffer. +- **The PC builds are byte-identical** with this code present. Every shared file's change is behind `STRATA_GPU_METAL` or `__APPLE__`, and the CUDA and HIP objects are compared after each change. diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index ffaea059..a9dc19db 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -389,6 +389,9 @@ private: int32_t* d_spec_ = nullptr; ///< device: kVerifyMaxT draft ids, then kVerifyMaxT q rows int hist_len_ = 0; bool head_sampling_ = true; ///< set_head_sampling +#if defined(STRATA_GPU_METAL) + void* metal_ = nullptr; ///< the Metal decode window (metal/src/engine/window.cpp): init/run/commit go there +#endif std::vector logit_bias_host_; float* logit_bias_device_ = nullptr; int device_ = -1; ///< the device `init` ran on: run/commit switch to it (layer split) diff --git a/metal/CMakeLists.txt b/metal/CMakeLists.txt new file mode 100644 index 00000000..42978519 --- /dev/null +++ b/metal/CMakeLists.txt @@ -0,0 +1,123 @@ +# metal/ - Strata on Apple Silicon (Metal), MAC-PLAN.md. Its own CMake project like sycl/, macOS only, never part of +# the CUDA / HIP / SYCL builds. +# +# Two parts: +# * the kernel tree (mac-kern): the runtime face src/mtl_rt.*, the MSL kernels kernels/*.metal (compiled at run time), +# CPU references src/ref_*.cpp and the parity / bench programs tests/*.cpp; +# * the engine (mac-design): the shared host sources from ../src, UNCHANGED - include/metal_compat goes first on the +# include path and gives them the CUDA runtime names on Metal, as include/strata/hip_compat does on HIP - over +# the Metal device runtime src/gpu/runtime.cpp (metal-cpp) and the kernel library src/engine/*. +# +# cmake -S metal -B build-metal -G Ninja -DCMAKE_BUILD_TYPE=Release -DMETAL_CPP_DIR=... [-DSTRATA_GGML_DIR=...] +# ninja -C build-metal +cmake_minimum_required(VERSION 3.24) +project(strata_metal LANGUAGES C CXX OBJCXX) + +if(NOT APPLE) + message(FATAL_ERROR "metal/ builds on macOS only") +endif() + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_OBJCXX_STANDARD 20) +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE Release) +endif() +set(CMAKE_CXX_FLAGS_RELEASE "-O2") +set(CMAKE_OBJCXX_FLAGS_RELEASE "-O2") + +get_filename_component(STRATA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/.." ABSOLUTE) +set(GGML_COMMON "${STRATA_ROOT}/third_party/ggml/ggml-common.h") + +# ---- the kernel tree (mac-kern) ------------------------------------------------------------------------------------ +add_library(mtl_rt STATIC src/mtl_rt.mm src/ref_quant.cpp src/gguf_lite.cpp) +target_include_directories(mtl_rt PUBLIC src ${STRATA_ROOT}/third_party/ggml) +target_compile_options(mtl_rt PRIVATE $<$:-fobjc-arc>) +target_compile_definitions(mtl_rt PRIVATE + STRATA_GGML_COMMON_DEFAULT="${GGML_COMMON}" + STRATA_METAL_KERNELS_DEFAULT="${CMAKE_CURRENT_SOURCE_DIR}/kernels") +target_link_libraries(mtl_rt PUBLIC "-framework Metal" "-framework Foundation") + +file(GLOB STRATA_METAL_TESTS CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/tests/*.cpp) +list(REMOVE_ITEM STRATA_METAL_TESTS ${CMAKE_CURRENT_SOURCE_DIR}/tests/runtime_hello.cpp) +foreach(src ${STRATA_METAL_TESTS}) + get_filename_component(t ${src} NAME_WE) + add_executable(${t} ${src}) + target_link_libraries(${t} PRIVATE mtl_rt) +endforeach() + +# ---- the device runtime and the engine (mac-design) --------------------------------------------------------------- +set(METAL_CPP_DIR "" CACHE PATH "metal-cpp headers (https://developer.apple.com/metal/cpp/), e.g. metal-cpp_26") +if(NOT EXISTS "${METAL_CPP_DIR}/Metal/Metal.hpp") + message(STATUS "strata metal: METAL_CPP_DIR is not set: the device runtime and the engine are not built") + return() +endif() + +add_library(strata_gpu_metal STATIC src/gpu/runtime.cpp) +target_include_directories(strata_gpu_metal BEFORE PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include/metal_compat + ${CMAKE_CURRENT_SOURCE_DIR}/include ${STRATA_ROOT}/include) +target_include_directories(strata_gpu_metal SYSTEM PUBLIC ${METAL_CPP_DIR}) +target_compile_definitions(strata_gpu_metal PUBLIC STRATA_GPU_METAL=1) +target_link_libraries(strata_gpu_metal PUBLIC "-framework Metal" "-framework Foundation" "-framework QuartzCore") + +add_library(strata_core_metal STATIC ${STRATA_ROOT}/src/core/graph.cpp) +target_link_libraries(strata_core_metal PUBLIC strata_gpu_metal) +add_executable(runtime_hello tests/runtime_hello.cpp) +target_link_libraries(runtime_hello PRIVATE strata_core_metal) +enable_testing() +add_test(NAME runtime_hello COMMAND runtime_hello) + +# The engine: ggml (the native expert formats' type traits and ggml-cpu) from a llama.cpp checkout at the commit the +# PC build pins (CMakeLists.txt: 3cf03257). +option(STRATA_METAL_ENGINE "Build the engine (strata) for Metal" ON) +set(STRATA_GGML_DIR "" CACHE PATH "llama.cpp checkout at the pinned commit") +if(NOT STRATA_METAL_ENGINE) + return() +endif() +if(NOT EXISTS "${STRATA_GGML_DIR}/ggml/CMakeLists.txt") + message(FATAL_ERROR "STRATA_GGML_DIR='${STRATA_GGML_DIR}' is not a llama.cpp checkout") +endif() +set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) +set(GGML_STATIC ON CACHE BOOL "" FORCE) +set(GGML_METAL OFF CACHE BOOL "" FORCE) +set(GGML_BLAS OFF CACHE BOOL "" FORCE) +set(GGML_OPENMP OFF CACHE BOOL "" FORCE) +set(GGML_BACKEND_DL OFF CACHE BOOL "" FORCE) +set(GGML_BUILD_TESTS OFF CACHE BOOL "" FORCE) +set(GGML_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) +add_subdirectory(${STRATA_GGML_DIR}/ggml ${CMAKE_BINARY_DIR}/ggml EXCLUDE_FROM_ALL) + +set(S ${STRATA_ROOT}/src) +set(STRATA_METAL_HOST_SOURCES + ${S}/core/device.cu ${S}/core/pinned.cu ${S}/platform/memory.cpp ${S}/core/graph.cpp ${S}/core/weights.cpp ${S}/core/layout.cpp + ${S}/core/layer.cpp ${S}/core/session.cpp ${S}/core/expert_source.cpp ${S}/core/remote_experts.cpp ${S}/core/expert_cache.cpp + ${S}/core/native_head.cpp ${S}/core/native_dense.cpp ${S}/core/verify.cpp ${S}/core/mtp.cpp + ${S}/core/conversation_snapshot.cpp ${S}/core/conversation_state.cpp ${S}/core/conversation_memory.cpp + ${S}/core/peer_experts.cpp ${S}/core/arch_defaults.cpp ${S}/core/vmm.cpp ${S}/core/conversation_file.cpp + ${S}/kernels/ngram.cpp ${S}/ngram/ple_reader.cpp ${S}/platform/direct_file.cpp + ${S}/prefill/prefill.cpp + ${S}/spec/suffix_drafter.cpp ${S}/spec/controller.cpp ${S}/spec/draft_policy.cpp ${S}/spec/draft_source.cpp + ${S}/kernels/cpu/pool.cpp ${S}/kernels/cpu/expert_layout.cpp ${S}/kernels/cpu/native_expert.cpp) +set_source_files_properties(${S}/core/device.cu ${S}/core/pinned.cu PROPERTIES LANGUAGE CXX) + +# The kernel library: Metal implementations (src/engine/*.cpp) and, for every entry point not ported yet, a stub +# that stops the engine with the entry point's name (src/engine/stubs.cpp, generated by tools/gen_stubs.py). +file(GLOB STRATA_METAL_ENGINE_SOURCES CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/engine/*.cpp) + +add_library(strata_metal_host STATIC ${STRATA_METAL_HOST_SOURCES}) +target_include_directories(strata_metal_host PUBLIC ${STRATA_ROOT}/include ${S}/core ${STRATA_ROOT}/third_party/ggml + ${STRATA_GGML_DIR}/ggml/include ${STRATA_GGML_DIR}/ggml/src ${STRATA_GGML_DIR}/ggml/src/ggml-cpu) +target_compile_definitions(strata_metal_host PUBLIC STRATA_NATIVE_EXPERTS=1 STRATA_VERSION="0.1.43.1-metal") +target_compile_options(strata_metal_host PRIVATE -Wno-unused-parameter -Wno-deprecated-declarations) +target_link_libraries(strata_metal_host PUBLIC strata_gpu_metal ggml-cpu ggml-base) + +add_library(strata_metal_kernels STATIC ${STRATA_METAL_ENGINE_SOURCES}) +target_include_directories(strata_metal_kernels PRIVATE src ${STRATA_ROOT}/third_party/ggml) +target_compile_definitions(strata_metal_kernels PRIVATE + STRATA_GGML_COMMON_DEFAULT="${GGML_COMMON}" STRATA_METAL_KERNELS_DEFAULT="${CMAKE_CURRENT_SOURCE_DIR}/kernels" + STRATA_METAL_ENGINE_KERNELS_DEFAULT="${CMAKE_CURRENT_SOURCE_DIR}/src/engine/msl" + STRATA_METAL_DATA_DEFAULT="${STRATA_ROOT}/data") +target_link_libraries(strata_metal_kernels PUBLIC strata_metal_host mtl_rt) + +add_executable(strata ${S}/program/generate.cpp) +target_link_libraries(strata PRIVATE strata_metal_kernels strata_metal_host strata_metal_kernels) diff --git a/metal/include/metal_compat/cpuid.h b/metal/include/metal_compat/cpuid.h new file mode 100644 index 00000000..8fd3eb52 --- /dev/null +++ b/metal/include/metal_compat/cpuid.h @@ -0,0 +1,6 @@ +// metal/include/metal_compat/cpuid.h - GCC's on arm64: every leaf reads as zero, so the x86 feature +// probes (src/kernels/cpu/expert_layout.cpp) report no AVX / AVX-512 / VNNI and the engine never picks an x86 kernel. +#pragma once +#define __cpuid(leaf, a, b, c, d) ((void) (leaf), (a) = 0, (b) = 0, (c) = 0, (d) = 0) +#define __cpuid_count(leaf, sub, a, b, c, d) ((void) (leaf), (void) (sub), (a) = 0, (b) = 0, (c) = 0, (d) = 0) +static inline unsigned __get_cpuid_max(unsigned, unsigned* sig) { if (sig) *sig = 0; return 0; } diff --git a/metal/include/metal_compat/cuda_runtime.h b/metal/include/metal_compat/cuda_runtime.h new file mode 100644 index 00000000..eb64243e --- /dev/null +++ b/metal/include/metal_compat/cuda_runtime.h @@ -0,0 +1,130 @@ +// metal/include/metal_compat/cuda_runtime.h - the CUDA runtime names the host files use, on Metal. +// +// The HIP build's approach (include/strata/hip_compat/cuda_runtime.h maps every cudaX the host code calls to hipX), +// applied to Metal: this directory goes first on the Metal build's include path, so the shared host files compile for +// Metal UNCHANGED, and the CUDA / HIP builds never see this file (their objects stay byte-identical by construction). +// Every name forwards to strata::gpu's Metal implementation (metal/src/gpu/runtime.cpp), whose semantics are the +// CUDA ones. Only the names in the Phase 1 inventory (phaseA-tests/mac-design.md §1.3) are provided; a host file that +// uses another one fails to compile on Metal, which is the point. +#pragma once + +#include +#include + +#include // metal_compat/immintrin.h: CUDA's headers bring the x86 one in on a PC +#include "strata/gpu/runtime.hpp" // metal/include/strata/gpu: the Metal runtime + +namespace strata::gpu::compat_detail { inline Error bad() { return kErrorUnsupported; } } + +// ---- types and constants +using cudaError_t = strata::gpu::Error; +using cudaStream_t = strata::gpu::Stream; +using cudaEvent_t = strata::gpu::Event; +using cudaGraph_t = strata::gpu::Graph; +using cudaGraphExec_t = strata::gpu::GraphExec; +using cudaGraphNode_t = void*; +using cudaDeviceProp = strata::gpu::DeviceProp; +using cudaMemcpyKind = strata::gpu::CopyKind; +using cudaHostFn_t = strata::gpu::HostFn; +inline constexpr cudaError_t cudaSuccess = strata::gpu::kSuccess; +inline constexpr cudaError_t cudaErrorNotReady = strata::gpu::kNotReady; +inline constexpr cudaError_t cudaErrorMemoryAllocation = strata::gpu::kErrorMemoryAllocation; +inline constexpr cudaError_t cudaErrorPeerAccessAlreadyEnabled = strata::gpu::kErrorPeerAccessAlreadyEnabled; +inline constexpr cudaError_t cudaErrorStreamCaptureUnsupported = strata::gpu::kErrorUnsupported; +inline constexpr cudaMemcpyKind cudaMemcpyHostToDevice = strata::gpu::kHostToDevice; +inline constexpr cudaMemcpyKind cudaMemcpyDeviceToHost = strata::gpu::kDeviceToHost; +inline constexpr cudaMemcpyKind cudaMemcpyDeviceToDevice = strata::gpu::kDeviceToDevice; +inline constexpr cudaMemcpyKind cudaMemcpyDefault = strata::gpu::kCopyDefault; +inline constexpr unsigned cudaHostAllocDefault = strata::gpu::kHostAllocDefault; +inline constexpr unsigned cudaHostAllocPortable = strata::gpu::kHostAllocPortable; +inline constexpr unsigned cudaHostAllocMapped = strata::gpu::kHostAllocMapped; +inline constexpr unsigned cudaHostRegisterPortable = strata::gpu::kHostRegisterPortable; +inline constexpr unsigned cudaHostRegisterMapped = strata::gpu::kHostRegisterMapped; +inline constexpr unsigned cudaHostRegisterReadOnly = strata::gpu::kHostRegisterReadOnly; +inline constexpr unsigned cudaEventDefault = strata::gpu::kEventDefault; +inline constexpr unsigned cudaEventDisableTiming = strata::gpu::kEventDisableTiming; +inline constexpr unsigned cudaEventBlockingSync = strata::gpu::kEventBlockingSync; +inline constexpr unsigned cudaStreamNonBlocking = strata::gpu::kStreamNonBlocking; +enum cudaStreamCaptureMode { cudaStreamCaptureModeGlobal = 0, cudaStreamCaptureModeThreadLocal = 1, cudaStreamCaptureModeRelaxed = 2 }; +enum cudaDeviceAttr { cudaDevAttrClockRate = 13, cudaDevAttrMultiProcessorCount = 16, cudaDevAttrIntegrated = 18 }; + +// ---- errors, devices +inline cudaError_t cudaGetLastError() { return strata::gpu::get_last_error(); } +inline cudaError_t cudaPeekAtLastError() { return strata::gpu::peek_last_error(); } +inline const char* cudaGetErrorString(cudaError_t e) { return strata::gpu::error_string(e); } +inline cudaError_t cudaGetDevice(int* d) { return strata::gpu::get_device(d); } +inline cudaError_t cudaSetDevice(int d) { return strata::gpu::set_device(d); } +inline cudaError_t cudaGetDeviceCount(int* n) { return strata::gpu::device_count(n); } +inline cudaError_t cudaDeviceSynchronize() { return strata::gpu::device_synchronize(); } +inline cudaError_t cudaMemGetInfo(size_t* f, size_t* t) { return strata::gpu::mem_get_info(f, t); } +inline cudaError_t cudaGetDeviceProperties(cudaDeviceProp* p, int d) { return strata::gpu::get_device_properties(p, d); } +inline cudaError_t cudaRuntimeGetVersion(int* v) { return strata::gpu::runtime_version(v); } +inline cudaError_t cudaDriverGetVersion(int* v) { return strata::gpu::runtime_version(v); } +inline cudaError_t cudaDeviceGetAttribute(int* v, cudaDeviceAttr a, int d) { + switch (a) { + case cudaDevAttrIntegrated: return strata::gpu::device_integrated(v, d); + case cudaDevAttrMultiProcessorCount: return strata::gpu::device_sm_count(v, d); + case cudaDevAttrClockRate: return strata::gpu::device_clock_khz(v, d); + } + return strata::gpu::compat_detail::bad(); +} +inline cudaError_t cudaDeviceCanAccessPeer(int* v, int d, int p) { return strata::gpu::device_can_access_peer(v, d, p); } +inline cudaError_t cudaDeviceEnablePeerAccess(int p, unsigned f) { return strata::gpu::device_enable_peer_access(p, f); } + +// ---- memory and copies +template inline cudaError_t cudaMalloc(T** p, size_t n) { return strata::gpu::malloc_device(p, n); } +inline cudaError_t cudaFree(void* p) { return strata::gpu::free_device(p); } +template inline cudaError_t cudaHostAlloc(T** p, size_t n, unsigned f) { return strata::gpu::host_alloc(p, n, f); } +template inline cudaError_t cudaMallocHost(T** p, size_t n) { return strata::gpu::malloc_host(p, n); } +inline cudaError_t cudaFreeHost(void* p) { return strata::gpu::free_host(p); } +template inline cudaError_t cudaHostGetDevicePointer(T** d, void* h, unsigned f) { return strata::gpu::host_device_pointer(d, h, f); } +inline cudaError_t cudaHostRegister(void* p, size_t n, unsigned f) { return strata::gpu::host_register(p, n, f); } +inline cudaError_t cudaHostUnregister(void* p) { return strata::gpu::host_unregister(p); } +inline cudaError_t cudaMemset(void* p, int v, size_t n) { return strata::gpu::memset_device(p, v, n); } +inline cudaError_t cudaMemsetAsync(void* p, int v, size_t n, cudaStream_t s = nullptr) { return strata::gpu::memset_async(p, v, n, s); } +inline cudaError_t cudaMemcpy(void* d, const void* s, size_t n, cudaMemcpyKind k) { return strata::gpu::memcpy_sync(d, s, n, k); } +inline cudaError_t cudaMemcpyAsync(void* d, const void* s, size_t n, cudaMemcpyKind k, cudaStream_t st = nullptr) { + return strata::gpu::memcpy_async(d, s, n, k, st); +} +inline cudaError_t cudaMemcpy2DAsync(void* d, size_t dp, const void* s, size_t sp, size_t w, size_t h, cudaMemcpyKind k, + cudaStream_t st = nullptr) { + return strata::gpu::memcpy_2d_async(d, dp, s, sp, w, h, k, st); +} +inline cudaError_t cudaMemcpyPeerAsync(void* d, int dd, const void* s, int sd, size_t n, cudaStream_t st = nullptr) { + return strata::gpu::memcpy_peer_async(d, dd, s, sd, n, st); +} + +// ---- streams, events, host functions +inline cudaError_t cudaStreamCreate(cudaStream_t* s) { return strata::gpu::stream_create(s); } +inline cudaError_t cudaStreamCreateWithFlags(cudaStream_t* s, unsigned f) { return strata::gpu::stream_create(s, f); } +inline cudaError_t cudaStreamDestroy(cudaStream_t s) { return strata::gpu::stream_destroy(s); } +inline cudaError_t cudaStreamSynchronize(cudaStream_t s) { return strata::gpu::stream_synchronize(s); } +inline cudaError_t cudaStreamQuery(cudaStream_t s) { return strata::gpu::stream_query(s); } +inline cudaError_t cudaStreamWaitEvent(cudaStream_t s, cudaEvent_t e, unsigned f = 0) { return strata::gpu::stream_wait_event(s, e, f); } +inline cudaError_t cudaLaunchHostFunc(cudaStream_t s, cudaHostFn_t fn, void* a) { return strata::gpu::launch_host_func(s, fn, a); } +inline cudaError_t cudaEventCreate(cudaEvent_t* e) { return strata::gpu::event_create(e); } +inline cudaError_t cudaEventCreateWithFlags(cudaEvent_t* e, unsigned f) { return strata::gpu::event_create(e, f); } +inline cudaError_t cudaEventDestroy(cudaEvent_t e) { return strata::gpu::event_destroy(e); } +inline cudaError_t cudaEventRecord(cudaEvent_t e, cudaStream_t s = nullptr) { return strata::gpu::event_record(e, s); } +inline cudaError_t cudaEventQuery(cudaEvent_t e) { return strata::gpu::event_query(e); } +inline cudaError_t cudaEventSynchronize(cudaEvent_t e) { return strata::gpu::event_synchronize(e); } +inline cudaError_t cudaEventElapsedTime(float* ms, cudaEvent_t a, cudaEvent_t b) { return strata::gpu::event_elapsed_ms(ms, a, b); } + +// ---- graphs +inline cudaError_t cudaStreamBeginCapture(cudaStream_t s, cudaStreamCaptureMode m) { + return m == cudaStreamCaptureModeThreadLocal ? strata::gpu::begin_capture(s) : strata::gpu::compat_detail::bad(); +} +inline cudaError_t cudaStreamEndCapture(cudaStream_t s, cudaGraph_t* g) { return strata::gpu::end_capture(s, g); } +inline cudaError_t cudaGraphGetNodes(cudaGraph_t g, cudaGraphNode_t* nodes, size_t* n) { + return nodes == nullptr ? strata::gpu::graph_node_count(g, n) : strata::gpu::compat_detail::bad(); +} +inline cudaError_t cudaGraphInstantiate(cudaGraphExec_t* x, cudaGraph_t g, cudaGraphNode_t*, char*, size_t) { + return strata::gpu::graph_instantiate(x, g); +} +inline cudaError_t cudaGraphInstantiate(cudaGraphExec_t* x, cudaGraph_t g, unsigned long long f = 0) { + return strata::gpu::graph_instantiate(x, g, f); +} +inline cudaError_t cudaGraphLaunch(cudaGraphExec_t x, cudaStream_t s) { return strata::gpu::graph_launch(x, s); } +inline cudaError_t cudaGraphUpload(cudaGraphExec_t x, cudaStream_t s) { return strata::gpu::graph_upload(x, s); } +inline cudaError_t cudaGraphDestroy(cudaGraph_t g) { return strata::gpu::graph_destroy(g); } +inline cudaError_t cudaGraphExecDestroy(cudaGraphExec_t x) { return strata::gpu::graph_exec_destroy(x); } diff --git a/metal/include/metal_compat/immintrin.h b/metal/include/metal_compat/immintrin.h new file mode 100644 index 00000000..1f39eddd --- /dev/null +++ b/metal/include/metal_compat/immintrin.h @@ -0,0 +1,5 @@ +// metal/include/metal_compat/immintrin.h - the x86 intrinsics the host loops use, on arm64: the spin-wait hint and +// the store fence before a host flag is raised (verify.cpp, session.cpp, mtp.cpp, graph.cpp). +#pragma once +static inline void _mm_pause() { __asm__ __volatile__("yield"); } +static inline void _mm_sfence() { __asm__ __volatile__("dmb ishst" ::: "memory"); } diff --git a/metal/include/metal_compat/linux/mman.h b/metal/include/metal_compat/linux/mman.h new file mode 100644 index 00000000..5b90ec33 --- /dev/null +++ b/metal/include/metal_compat/linux/mman.h @@ -0,0 +1,12 @@ +// metal/include/metal_compat/linux/mman.h - the Linux mmap flags src/core/pinned.cu asks for, on macOS. There are no +// hugetlb pages and no transparent huge pages: MAP_HUGETLB is spelled as MAP_FIXED at address 0, which macOS refuses +// (the 4 GiB __PAGEZERO), and MADV_HUGEPAGE as an advice madvise refuses, so pinned.cu takes its 4 KB-page fallback +// and reports it, exactly as on a Linux box without a hugetlb pool. +#pragma once +#include +#ifndef MAP_HUGETLB +#define MAP_HUGETLB MAP_FIXED +#endif +#ifndef MADV_HUGEPAGE +#define MADV_HUGEPAGE (-1) +#endif diff --git a/metal/include/strata/gpu/metal.hpp b/metal/include/strata/gpu/metal.hpp new file mode 100644 index 00000000..4880bdc8 --- /dev/null +++ b/metal/include/strata/gpu/metal.hpp @@ -0,0 +1,44 @@ +// metal/include/strata/gpu/metal.hpp - what the Metal kernel library needs beyond include/strata/gpu/runtime.hpp. +// +// The host code never includes this: it sees only runtime.hpp and the strata::kernels::* headers. The Metal +// implementations of those kernel headers (metal/src/kernels/*) turn their `void* stream` into a gpu::Stream and call +// dispatch(): encoded now, or recorded when the stream is being captured (the Metal "graph"). +#pragma once + +#include +#include +#include + +#include "strata/gpu/runtime.hpp" + +namespace MTL { +class Device; +class ComputePipelineState; +} // namespace MTL + +namespace strata::gpu::metal { + +MTL::Device* device(); + +/// Compile MSL source at run time (the Command Line Tools have no offline `metal` compiler) and return the pipeline +/// of `function`. Cached by (source name, function name); nullptr and `err` on failure. +MTL::ComputePipelineState* pipeline(const char* source_name, const char* source, const char* function, std::string& err); + +struct Grid { + uint32_t x = 1, y = 1, z = 1; +}; + +/// One compute dispatch: `args` (<= 4 KiB, copied now, as a CUDA kernel's arguments are at launch/capture) is bound at +/// buffer index 0; the kernel reads its device pointers (gpuAddress values) from it. `threadgroups` x `threads` +/// like a CUDA <<>>. Dispatches on one stream are ordered (each one sees the previous one's +/// writes), as kernels on one CUDA stream are. +Error dispatch(Stream s, MTL::ComputePipelineState* p, const void* args, size_t arg_bytes, Grid threadgroups, Grid threads, + size_t threadgroup_bytes = 0); + +/// Counters for tests and the dispatch-cost budget. +struct Stats { + uint64_t dispatches = 0, command_buffers = 0, blits = 0, host_syncs = 0; +}; +Stats stats(); + +} // namespace strata::gpu::metal diff --git a/metal/include/strata/gpu/runtime.hpp b/metal/include/strata/gpu/runtime.hpp new file mode 100644 index 00000000..7791dc4a --- /dev/null +++ b/metal/include/strata/gpu/runtime.hpp @@ -0,0 +1,126 @@ +// metal/include/strata/gpu/runtime.hpp - the device runtime of the Metal build (MAC-PLAN Phase 1, compat design). +// +// The shared host files keep calling the CUDA runtime names; on Metal those names come from +// metal/include/metal_compat/cuda_runtime.h (first on the include path, as include/strata/hip_compat is on HIP), which +// forwards every one to the functions declared here. metal/src/gpu/runtime.cpp implements them on metal-cpp: +// - a device pointer is the MTLBuffer's gpuAddress (the host never dereferences it; kernels take it from their +// argument struct); host_alloc returns contents() and host_device_pointer maps it to its gpuAddress; every buffer is +// in one residency set; +// - a Stream is a command queue + the open command buffer / compute encoder + a shared-event timeline; an Event is a +// (shared event, value) pair; +// - begin_capture / end_capture / graph_launch record the stream's dispatches and re-encode them per launch (the CUDA +// graph rule "per-step values live in device buffers, not in arguments" holds here too); +// - caps().unified_memory is true and host_view(device_pointer) is the CPU address of a device allocation. +// The CUDA and HIP builds never include this directory. +#pragma once + +#include +#include + +// The signatures and the meaning of each call are those of the CUDA runtime call of the same purpose. + +namespace strata::gpu { + +enum Error : int { kSuccess = 0, kNotReady = 600, kErrorInvalidValue = 1, kErrorMemoryAllocation = 2, kErrorUnsupported = 801, + kErrorLaunchFailure = 719 }; +struct StreamImpl; +struct EventImpl; +struct GraphImpl; +struct GraphExecImpl; +using Stream = StreamImpl*; // nullptr = the default (legacy) stream, as on CUDA +using Event = EventImpl*; +using Graph = GraphImpl*; +using GraphExec = GraphExecImpl*; +enum CopyKind : int { kHostToHost = 0, kHostToDevice = 1, kDeviceToHost = 2, kDeviceToDevice = 3, kCopyDefault = 4 }; +using HostFn = void (*)(void*); +struct DeviceProp { // the fields the host code reads + char name[256] = {}; + char gcnArchName[256] = {}; + int major = 0, minor = 0, warpSize = 32, multiProcessorCount = 0; + size_t totalGlobalMem = 0; +}; + +inline constexpr unsigned kHostAllocDefault = 0; +inline constexpr unsigned kHostAllocPortable = 1; +inline constexpr unsigned kHostAllocMapped = 2; +inline constexpr unsigned kHostRegisterPortable = 1; +inline constexpr unsigned kHostRegisterMapped = 2; +inline constexpr unsigned kHostRegisterReadOnly = 8; +inline constexpr unsigned kEventDefault = 0; +inline constexpr unsigned kEventBlockingSync = 1; +inline constexpr unsigned kEventDisableTiming = 2; +inline constexpr unsigned kStreamNonBlocking = 1; + +struct Caps { + bool unified_memory = true; +}; +inline Caps caps() { return Caps{}; } +void* host_view(const void* device_pointer); + +Error get_last_error(); +Error peek_last_error(); +const char* error_string(Error e); + +Error get_device(int* dev); +Error set_device(int dev); +Error device_count(int* n); +Error device_synchronize(); +Error mem_get_info(size_t* free_b, size_t* total_b); +Error get_device_properties(DeviceProp* p, int dev); +Error device_integrated(int* v, int dev); +Error device_sm_count(int* v, int dev); +Error device_clock_khz(int* v, int dev); +Error runtime_version(int* v); +Error device_can_access_peer(int* v, int dev, int peer); +Error device_enable_peer_access(int peer, unsigned flags); +inline constexpr Error kErrorPeerAccessAlreadyEnabled = Error(704); + +Error malloc_device_raw(void** p, size_t bytes); +template inline Error malloc_device(T** p, size_t bytes) { return malloc_device_raw((void**) (void*) p, bytes); } +Error free_device(void* p); +Error host_alloc_raw(void** p, size_t bytes, unsigned flags); +template inline Error host_alloc(T** p, size_t bytes, unsigned flags) { return host_alloc_raw((void**) (void*) p, bytes, flags); } +Error free_host(void* p); +template inline Error malloc_host(T** p, size_t bytes) { return host_alloc_raw((void**) (void*) p, bytes, 0); } +Error host_device_pointer_raw(void** dev, void* host); +template inline Error host_device_pointer(T** dev, void* host, unsigned = 0) { + return host_device_pointer_raw((void**) (void*) dev, host); +} +Error host_register(void* p, size_t bytes, unsigned flags); +Error host_unregister(void* p); +Error memset_device(void* p, int value, size_t bytes); +Error memset_async(void* p, int value, size_t bytes, Stream s = nullptr); + +Error memcpy_sync(void* dst, const void* src, size_t bytes, CopyKind k); +Error memcpy_async(void* dst, const void* src, size_t bytes, CopyKind k, Stream s = nullptr); +Error memcpy_2d_async(void* dst, size_t dpitch, const void* src, size_t spitch, size_t width, size_t height, CopyKind k, + Stream s = nullptr); +Error memcpy_peer_async(void* dst, int dst_dev, const void* src, int src_dev, size_t bytes, Stream s = nullptr); + +Error stream_create(Stream* s, unsigned flags); +inline Error stream_create(Stream* s) { return stream_create(s, 0); } +Error stream_destroy(Stream s); +Error stream_synchronize(Stream s); +Error stream_query(Stream s); +Error stream_wait_event(Stream s, Event e, unsigned flags = 0); +Error launch_host_func(Stream s, HostFn fn, void* arg); + +Error event_create(Event* e, unsigned flags); +inline Error event_create(Event* e) { return event_create(e, 0); } +Error event_destroy(Event e); +Error event_record(Event e, Stream s = nullptr); +Error event_query(Event e); +Error event_synchronize(Event e); +Error event_elapsed_ms(float* ms, Event a, Event b); + +Error begin_capture(Stream s); +Error end_capture(Stream s, Graph* g); +Error graph_node_count(Graph g, size_t* n); +Error graph_instantiate(GraphExec* x, Graph g); +inline Error graph_instantiate(GraphExec* x, Graph g, unsigned long long) { return graph_instantiate(x, g); } +Error graph_launch(GraphExec x, Stream s); +Error graph_upload(GraphExec x, Stream s); +Error graph_destroy(Graph g); +Error graph_exec_destroy(GraphExec x); + +} // namespace strata::gpu diff --git a/metal/kernels/alu_bench.metal b/metal/kernels/alu_bench.metal new file mode 100644 index 00000000..e34890a0 --- /dev/null +++ b/metal/kernels/alu_bench.metal @@ -0,0 +1,181 @@ +// metal/kernels/alu_bench.metal - instruction-rate probes (alu_bench.cpp): each thread runs ITER iterations of 8 +// independent chains of one operation; the result is written so nothing is eliminated. +#define ITER 1024 + +kernel void a_fma32(device float* out [[buffer(0)]], constant float& k [[buffer(1)]], uint gid [[thread_position_in_grid]]) { + float a0 = gid, a1 = gid + 1, a2 = gid + 2, a3 = gid + 3, a4 = gid + 4, a5 = gid + 5, a6 = gid + 6, a7 = gid + 7; + for (int i = 0; i < ITER; ++i) { + a0 = fma(a0, k, 0.5f); a1 = fma(a1, k, 0.5f); a2 = fma(a2, k, 0.5f); a3 = fma(a3, k, 0.5f); + a4 = fma(a4, k, 0.5f); a5 = fma(a5, k, 0.5f); a6 = fma(a6, k, 0.5f); a7 = fma(a7, k, 0.5f); + } + out[gid] = a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7; +} + +kernel void a_fma16(device float* out [[buffer(0)]], constant float& kf [[buffer(1)]], uint gid [[thread_position_in_grid]]) { + const half k = half(kf); + half a0 = gid & 7, a1 = 1, a2 = 2, a3 = 3, a4 = 4, a5 = 5, a6 = 6, a7 = 7; + for (int i = 0; i < ITER; ++i) { + a0 = fma(a0, k, half(0.5)); a1 = fma(a1, k, half(0.5)); a2 = fma(a2, k, half(0.5)); a3 = fma(a3, k, half(0.5)); + a4 = fma(a4, k, half(0.5)); a5 = fma(a5, k, half(0.5)); a6 = fma(a6, k, half(0.5)); a7 = fma(a7, k, half(0.5)); + } + out[gid] = float(a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7); +} + +// float accumulator, half operands (does the conversion come free?) +kernel void a_fmamix(device float* out [[buffer(0)]], constant float& kf [[buffer(1)]], uint gid [[thread_position_in_grid]]) { + half h0 = half(gid & 7), h1 = h0 + half(1); + float a0 = gid, a1 = 1, a2 = 2, a3 = 3, a4 = 4, a5 = 5, a6 = 6, a7 = 7; + for (int i = 0; i < ITER; ++i) { + a0 = fma(float(h0), kf, a0); a1 = fma(float(h1), kf, a1); a2 = fma(float(h0), kf, a2); a3 = fma(float(h1), kf, a3); + a4 = fma(float(h0), kf, a4); a5 = fma(float(h1), kf, a5); a6 = fma(float(h0), kf, a6); a7 = fma(float(h1), kf, a7); + h0 = h0 * half(0.999); h1 = h1 * half(0.999); + } + out[gid] = a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7; +} + +kernel void a_iand(device float* out [[buffer(0)]], constant uint& k [[buffer(1)]], uint gid [[thread_position_in_grid]]) { + uint a0 = gid, a1 = gid + 1, a2 = gid + 2, a3 = gid + 3, a4 = gid + 4, a5 = gid + 5, a6 = gid + 6, a7 = gid + 7; + for (int i = 0; i < ITER; ++i) { + a0 = (a0 ^ k) + 1; a1 = (a1 ^ k) + 1; a2 = (a2 ^ k) + 1; a3 = (a3 ^ k) + 1; + a4 = (a4 ^ k) + 1; a5 = (a5 ^ k) + 1; a6 = (a6 ^ k) + 1; a7 = (a7 ^ k) + 1; + } + out[gid] = float(a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7); +} + +kernel void a_shift(device float* out [[buffer(0)]], constant uint& k [[buffer(1)]], uint gid [[thread_position_in_grid]]) { + uint a0 = gid, a1 = gid + 1, a2 = gid + 2, a3 = gid + 3, a4 = gid + 4, a5 = gid + 5, a6 = gid + 6, a7 = gid + 7; + for (int i = 0; i < ITER; ++i) { + a0 = (a0 >> k) | k; a1 = (a1 >> k) | k; a2 = (a2 >> k) | k; a3 = (a3 >> k) | k; + a4 = (a4 >> k) | k; a5 = (a5 >> k) | k; a6 = (a6 >> k) | k; a7 = (a7 >> k) | k; + } + out[gid] = float(a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7); +} + +// int -> float conversion + fma +kernel void a_cvt(device float* out [[buffer(0)]], constant uint& k [[buffer(1)]], uint gid [[thread_position_in_grid]]) { + uint u = gid; + float a0 = 0, a1 = 0, a2 = 0, a3 = 0, a4 = 0, a5 = 0, a6 = 0, a7 = 0; + for (int i = 0; i < ITER; ++i) { + u += k; + a0 += float(u & 3); a1 += float(u & 12); a2 += float(u & 48); a3 += float(u & 192); + a4 += float(u & 768); a5 += float(u & 3072); a6 += float(u & 12288); a7 += float(u & 49152); + } + out[gid] = a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7; +} + +// threadgroup memory loads: random-ish 8-byte reads from a 4 KB table +kernel void a_tgload(device float* out [[buffer(0)]], constant uint& k [[buffer(1)]], uint gid [[thread_position_in_grid]], + ushort tid [[thread_index_in_threadgroup]]) { + threadgroup uint2 tab[512]; + for (int i = tid; i < 512; i += 256) tab[i] = uint2(i, i * 3); + threadgroup_barrier(mem_flags::mem_threadgroup); + uint u = gid * 2654435761u; + uint2 s0 = 0, s1 = 0, s2 = 0, s3 = 0; + for (int i = 0; i < ITER; ++i) { + s0 += tab[(u >> 3) & 511]; s1 += tab[(u >> 7) & 511]; s2 += tab[(u >> 11) & 511]; s3 += tab[(u >> 15) & 511]; + u += k; + } + out[gid] = float(s0.x + s1.x + s2.x + s3.x + s0.y + s1.y + s2.y + s3.y); +} + +// select (sign application) +kernel void a_sel(device float* out [[buffer(0)]], constant uint& k [[buffer(1)]], uint gid [[thread_position_in_grid]]) { + uint u = gid; + float a0 = 1, a1 = 2, a2 = 3, a3 = 4, a4 = 5, a5 = 6, a6 = 7, a7 = 8; + for (int i = 0; i < ITER; ++i) { + u ^= k; + a0 = (u & 1) ? -a0 : a0; a1 = (u & 2) ? -a1 : a1; a2 = (u & 4) ? -a2 : a2; a3 = (u & 8) ? -a3 : a3; + a4 = (u & 16) ? -a4 : a4; a5 = (u & 32) ? -a5 : a5; a6 = (u & 64) ? -a6 : a6; a7 = (u & 128) ? -a7 : a7; + } + out[gid] = a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7; +} + +// dot-shaped: acc_i += q_i * x_i with loop-carried accumulators only (q, x vary slowly) +kernel void a_dot32(device float* out [[buffer(0)]], constant float& k [[buffer(1)]], uint gid [[thread_position_in_grid]]) { + float q[8], x[8], a[8]; + for (int j = 0; j < 8; ++j) { q[j] = float(gid + j); x[j] = k * j; a[j] = 0; } + for (int i = 0; i < ITER; ++i) { + for (int j = 0; j < 8; ++j) a[j] = fma(q[j], x[j], a[j]); + q[0] += 1.0f; + } + float s = 0; + for (int j = 0; j < 8; ++j) s += a[j]; + out[gid] = s; +} +kernel void a_dot16(device float* out [[buffer(0)]], constant float& k [[buffer(1)]], uint gid [[thread_position_in_grid]]) { + half q[8], x[8], a[8]; + for (int j = 0; j < 8; ++j) { q[j] = half(gid + j); x[j] = half(k * j); a[j] = 0; } + for (int i = 0; i < ITER; ++i) { + for (int j = 0; j < 8; ++j) a[j] = fma(q[j], x[j], a[j]); + q[0] += half(1.0f); + } + float s = 0; + for (int j = 0; j < 8; ++j) s += float(a[j]); + out[gid] = s; +} +kernel void a_dotmix(device float* out [[buffer(0)]], constant float& k [[buffer(1)]], uint gid [[thread_position_in_grid]]) { + half q[8]; + float x[8], a[8]; + for (int j = 0; j < 8; ++j) { q[j] = half(gid + j); x[j] = k * j; a[j] = 0; } + for (int i = 0; i < ITER; ++i) { + for (int j = 0; j < 8; ++j) a[j] = fma(float(q[j]), x[j], a[j]); + q[0] += half(1.0f); + } + float s = 0; + for (int j = 0; j < 8; ++j) s += a[j]; + out[gid] = s; +} +kernel void a_fma32x16(device float* out [[buffer(0)]], constant float& k [[buffer(1)]], uint gid [[thread_position_in_grid]]) { + float a[16]; + for (int j = 0; j < 16; ++j) a[j] = gid + j; + for (int i = 0; i < ITER / 2; ++i) + for (int j = 0; j < 16; ++j) a[j] = fma(a[j], k, 0.5f); + float s = 0; + for (int j = 0; j < 16; ++j) s += a[j]; + out[gid] = s; +} + +// 8-byte gathers from a 4 KB table in device memory (L1-resident) and in the constant address space +kernel void a_devload(device float* out [[buffer(0)]], constant uint& k [[buffer(1)]], device const uint2* tab [[buffer(2)]], + uint gid [[thread_position_in_grid]]) { + uint u = gid * 2654435761u; + uint2 s0 = 0, s1 = 0, s2 = 0, s3 = 0; + for (int i = 0; i < ITER; ++i) { + s0 += tab[(u >> 3) & 511]; s1 += tab[(u >> 7) & 511]; s2 += tab[(u >> 11) & 511]; s3 += tab[(u >> 15) & 511]; + u += k; + } + out[gid] = float(s0.x + s1.x + s2.x + s3.x + s0.y + s1.y + s2.y + s3.y); +} +kernel void a_cstload(device float* out [[buffer(0)]], constant uint& k [[buffer(1)]], constant uint2* tab [[buffer(2)]], + uint gid [[thread_position_in_grid]]) { + uint u = gid * 2654435761u; + uint2 s0 = 0, s1 = 0, s2 = 0, s3 = 0; + for (int i = 0; i < ITER; ++i) { + s0 += tab[(u >> 3) & 511]; s1 += tab[(u >> 7) & 511]; s2 += tab[(u >> 11) & 511]; s3 += tab[(u >> 15) & 511]; + u += k; + } + out[gid] = float(s0.x + s1.x + s2.x + s3.x + s0.y + s1.y + s2.y + s3.y); +} +// 4-byte gathers from a 1 KB threadgroup table (IQ3_XXS's grid) +kernel void a_tgload4(device float* out [[buffer(0)]], constant uint& k [[buffer(1)]], uint gid [[thread_position_in_grid]], + ushort tid [[thread_index_in_threadgroup]]) { + threadgroup uint tab[256]; + for (int i = tid; i < 256; i += 256) tab[i] = i * 3; + threadgroup_barrier(mem_flags::mem_threadgroup); + uint u = gid * 2654435761u; + uint s0 = 0, s1 = 0, s2 = 0, s3 = 0; + for (int i = 0; i < ITER; ++i) { + s0 += tab[(u >> 3) & 255]; s1 += tab[(u >> 7) & 255]; s2 += tab[(u >> 11) & 255]; s3 += tab[(u >> 15) & 255]; + u += k; + } + out[gid] = float(s0 + s1 + s2 + s3); +} +// popcount parity (computed ksigns) +kernel void a_popc(device float* out [[buffer(0)]], constant uint& k [[buffer(1)]], uint gid [[thread_position_in_grid]]) { + uint u = gid, s0 = 0, s1 = 0, s2 = 0, s3 = 0; + for (int i = 0; i < ITER; ++i) { + s0 += popcount(u & 127); s1 += popcount((u >> 7) & 127); s2 += popcount((u >> 14) & 127); s3 += popcount((u >> 21) & 127); + u += k; + } + out[gid] = float(s0 + s1 + s2 + s3); +} diff --git a/metal/kernels/dense_mm.metal b/metal/kernels/dense_mm.metal new file mode 100644 index 00000000..45e29ace --- /dev/null +++ b/metal/kernels/dense_mm.metal @@ -0,0 +1,69 @@ +// metal/kernels/dense_mm.metal - dense projections for a PROMPT chunk (after quant/units/mma.metal): +// act_f16 X[t][k] -> half (the matrix units' operand) +// dq_f16 a quantized matrix -> half rows (ref_quant's values rounded to fp16), once per chunk +// gemm_f16 Y[t][n] = Xh[t] . Wh[n] (fp32) by MetalPerformancePrimitives matmul2d, TM x TN tiles, K dynamic; +// rows of Y past n_out / t past n_tok are not written (the tensors carry the extents) +#include +using namespace mpp::tensor_ops; + +kernel void act_f16(device const float* x [[buffer(0)]], device half* xh [[buffer(1)]], constant uint& n [[buffer(2)]], + uint gid [[thread_position_in_grid]]) { + if (gid < n) xh[gid] = half(x[gid]); +} + +struct DqArgs { + uint n_in; // values per row + uint n_out; // rows + uint row_bytes; + uint perm; // 0: row r -> r; p > 0: row r = c * (n_out / p) + d -> d * p + c (the HC up matrix with the p + // streams of an output interleaved, for gemm_hc_up's epilogue) +}; + +// one thread per unit: grid (units per row / 64, n_out), 64 threads +template +kernel void dq_f16(device const uchar* W [[buffer(0)]], device half* Wh [[buffer(1)]], constant DqArgs& a [[buffer(2)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int UNIT = fmt::UNIT, H = UNIT / 2; + threadgroup uint tab[fmt::TAB]; + load_tab(tab, tid, 64); + threadgroup_barrier(mem_flags::mem_threadgroup); + const int u = int(tg.x) * 64 + tid, r = int(tg.y); + if (u * UNIT >= int(a.n_in)) return; + // the unit's chunk origin: a 128-wide chunk holds whole units of every format + const int k0 = (u * UNIT) / 128 * 128; + float w[UNIT]; + int p0, p1; + DW::run(W + ulong(r) * a.row_bytes, u, k0, w, p0, p1, tab); + const int q = a.perm ? int(a.n_out / a.perm) : 1; + const int ro = a.perm ? (r % q) * int(a.perm) + r / q : r; + device half* o = Wh + ulong(ro) * a.n_in + k0; + for (int j = 0; j < H; ++j) { + o[p0 + j] = half(w[j]); + o[p1 + j] = half(w[H + j]); + } +} + +struct GemmArgs { int M, N, K; int pad; }; // Y is M rows of N floats + +template +kernel void gemm_f16(device half* A [[buffer(0)]], device half* B [[buffer(1)]], device float* Y [[buffer(2)]], + constant GemmArgs& a [[buffer(3)]], uint3 tg [[threadgroup_position_in_grid]]) { + tensor, tensor_inline> tA(A, dextents(a.K, a.M)); + tensor, tensor_inline> tB(B, dextents(a.K, a.N)); + tensor, tensor_inline> tY(Y, dextents(a.N, a.M)); + constexpr auto desc = matmul2d_descriptor(TM, TN, dynamic_length_v, false, true, false); + matmul2d> op; + auto mA = tA.slice(0, int(tg.y) * TM); + auto mB = tB.slice(0, int(tg.x) * TN); + auto mY = tY.slice(int(tg.x) * TN, int(tg.y) * TM); + op.run(mA, mB, mY); +} + +#define DQ(F) template [[host_name("dq_f16_" #F)]] kernel decltype(dq_f16) dq_f16; +#define DQ_(F) DQ(F) +DQ_(T_F32) DQ_(T_BF16) DQ_(T_Q8_0) DQ_(T_Q4_0) DQ_(T_Q5_0) DQ_(T_IQ4_NL) DQ_(T_IQ4_XS) DQ_(T_Q2_0) DQ_(T_IQ3_S) DQ_(T_Q3_K) +DQ_(T_Q4_K) DQ_(T_Q5_K) DQ_(T_Q6_K) +template [[host_name("gemm_f16_64_64_4")]] kernel decltype(gemm_f16<64, 64, 4>) gemm_f16<64, 64, 4>; +template [[host_name("gemm_f16_128_64_4")]] kernel decltype(gemm_f16<128, 64, 4>) gemm_f16<128, 64, 4>; +template [[host_name("gemm_f16_64_128_4")]] kernel decltype(gemm_f16<64, 128, 4>) gemm_f16<64, 128, 4>; +template [[host_name("gemm_f16_64_32_4")]] kernel decltype(gemm_f16<64, 32, 4>) gemm_f16<64, 32, 4>; diff --git a/metal/kernels/gdn.metal b/metal/kernels/gdn.metal new file mode 100644 index 00000000..c7954dfb --- /dev/null +++ b/metal/kernels/gdn.metal @@ -0,0 +1,165 @@ +// metal/kernels/gdn.metal - one GDN (gated delta-net) layer's recurrence for a window of tokens, fused end to end: +// +// conv (4 taps, history [channels][3] oldest first) -> SiLU, on q (16 heads), k (16), v (48 heads) of 128 +// q, k: L2 norm as native_gdn_l2_norm (rsqrt(sum/128 + eps/128), then x 1/sqrt(128), two roundings) +// gate = exp(softplus(alpha + dt) * a) (softplus = v > 20 ? v : log1p(exp(v))), beta = sigmoid(beta) +// kv_j = sum_i S[i][j] k[i]; delta_j = (v_j - gate * kv_j) * beta; S = gate * S + k[i] delta_j +// o_j = (sum_i S[i][j] q[i]) / sqrt(128); y_j = o_j * rsqrt(mean(o^2) + eps) * gamma_j * sigmoid(z_j) +// +// State layout as Strata's: S[(i * h_v + h) * 128 + j]. Value head h reads q/k head h % h_k. +// One threadgroup per value head, 512 threads = 16 simdgroups: simdgroup s holds columns j = 32 (s % 4) + lane and +// rows i = 32 (s / 4) .. + 32 of the head's 128 x 128 state in registers. GDN_NTOK tokens run in order; with +// `commit` the state and the conv history are written back after the last one (a verify window runs without commit, +// the fold of m accepted tokens is the same kernel with GDN_NTOK = m and commit). The conv history is read from +// `hist` and the committed one written to `hist_out` (ping-pong: the q/k channels are shared by three threadgroups). + +constant int GDN_NTOK [[function_constant(2)]]; + +struct GdnArgs { + uint h_k; // 16 + uint h_v; // 48 + uint channels; // 10240 = (2 h_k + h_v) * 128 + uint commit; // 0: verify (no write); 1: commit after the last token; 0x100 | k (1 <= k <= GDN_NTOK): commit + // the state and the conv history after the first k tokens, in place, while every token's y is + // still computed (a window whose first k rows are kept) - bitwise the commit of a k-token step + float eps; // 1e-6 + uint plane; // 0: y only; else y is the raw plane of prepared activations (xprep layout, n = h_v * 128, + // `plane` floats between planes) and the other planes and the per-16 sums are written too +}; + +template +kernel void gdn_step_t(device float* state [[buffer(0)]], device float* hist [[buffer(1)]], + device const float* qkv [[buffer(2)]], device const float* alpha [[buffer(3)]], + device const float* beta [[buffer(4)]], device const float* z [[buffer(5)]], + device const float* conv_w [[buffer(6)]], device const float* dt [[buffer(7)]], + device const float* ssm_a [[buffer(8)]], device const float* gamma [[buffer(9)]], + device float* y [[buffer(10)]], constant GdnArgs& a [[buffer(11)]], + device float* hist_out [[buffer(12)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + constexpr int S = 128; + threadgroup float qs[S], ks[S], vs[S]; + constexpr int RPT = S / IB; // state rows per thread + threadgroup float red[IB][S]; + threadgroup float part[32]; + threadgroup float gb[2]; + threadgroup float ys[S]; + const int h = int(tg.x), hk = h % int(a.h_k), hv = int(a.h_v); + const int cb = sg & 3, ib = sg >> 2; + const int j = 32 * cb + lane, i0 = RPT * ib; + const float scale = 1.0f / sqrt(float(S)); + + // the channel this thread convolves: 0..127 q of head hk, 128..255 k of head hk, 256..383 v of head h + int ch = -1; + if (tid < 128) ch = hk * S + tid; + else if (tid < 256) ch = int(a.h_k) * S + hk * S + (tid - 128); + else if (tid < 384) ch = 2 * int(a.h_k) * S + h * S + (tid - 256); + float hst[3] = {0.0f, 0.0f, 0.0f}, cw[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + if (ch >= 0) { + for (int k = 0; k < 3; ++k) hst[k] = hist[ch * 3 + k]; + for (int k = 0; k < 4; ++k) cw[k] = conv_w[ch * 4 + k]; + } + float st[RPT]; + for (int r = 0; r < RPT; ++r) st[r] = state[((i0 + r) * hv + h) * S + j]; + + const int commit_at = a.commit == 1u ? GDN_NTOK : (a.commit >> 8) ? int(a.commit & 0xFFu) : 0; + for (int t = 0; t < GDN_NTOK; ++t) { + // conv + SiLU + float cv = 0.0f; + if (ch >= 0) { + const float in = qkv[t * int(a.channels) + ch]; + const float vals[4] = {hst[0], hst[1], hst[2], in}; + float s = 0.0f; + for (int k = 0; k < 4; ++k) s = fma(vals[k], cw[k], s); + s = s + 0.0f; + cv = s / (1.0f + exp(-s)); + hst[0] = hst[1]; + hst[1] = hst[2]; + hst[2] = in; + } + // L2 norms of q (threads 0..127 = simdgroups 0..3) and k (128..255 = 4..7) + const float ssq = simd_sum(cv * cv); + if (lane == 0) part[sg] = ssq; + if (tid == 0) { + const float v = alpha[t * hv + h] + dt[h]; + // log1p(e^v) (Kahan: log(u) * e / (u - 1), u = 1 + e; exact where 1 + e rounds to 1) + const float e = exp(v), u = 1.0f + e; + const float sp = v > 20.0f ? v : (u == 1.0f ? e : log(u) * e / (u - 1.0f)); + gb[0] = exp(sp * ssm_a[h]); + gb[1] = 1.0f / (1.0f + exp(-beta[t * hv + h])); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid < 256) { + const int base = tid < 128 ? 0 : 4; + const float tot = (part[base] + part[base + 1]) + (part[base + 2] + part[base + 3]); + const float rs = rsqrt(tot / float(S) + a.eps / float(S)); + const float nv = (rs * cv) * scale; + if (tid < 128) qs[tid] = nv; + else ks[tid - 128] = nv; + } else if (tid < 384) { + vs[tid - 256] = cv; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const float g = gb[0], be = gb[1]; + // kv_j + float kv = 0.0f; + for (int r = 0; r < RPT; ++r) kv = fma(st[r], ks[i0 + r], kv); + red[ib][j] = kv; + threadgroup_barrier(mem_flags::mem_threadgroup); + kv = 0.0f; + for (int k = 0; k < IB; ++k) kv += red[k][j]; + const float delta = (vs[j] - g * kv) * be; + float o = 0.0f; + for (int r = 0; r < RPT; ++r) { + st[r] = fma(g, st[r], ks[i0 + r] * delta); + o = fma(st[r], qs[i0 + r], o); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + red[ib][j] = o; + threadgroup_barrier(mem_flags::mem_threadgroup); + // the readout and the output norm: column j's o (every i-block thread of the column holds the same value) + o = 0.0f; + for (int k = 0; k < IB; ++k) o += red[k][j]; + o = o * scale; + const float osq = ib == 0 ? simd_sum(o * o) : 0.0f; + if (ib == 0 && lane == 0) part[cb] = osq; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (ib == 0) { + const float tot = (part[0] + part[1]) + (part[2] + part[3]); + const float rs = rsqrt(tot / float(S) + a.eps); + const float zz = z[t * hv * S + h * S + j]; + const float yv = ((rs * o) * gamma[j]) * (1.0f / (1.0f + exp(-zz))); + y[t * hv * S + h * S + j] = yv; + if (a.plane) { + const float q2s[8] = {1.0f, 0.25f, 0.0625f, 0.015625f, 0.00390625f, 0.0009765625f, 0.000244140625f, + 0.00006103515625f}; + const float p4s[4] = {1.0f, 0.00390625f, 1.52587890625e-05f, 5.9604644775390625e-08f}; + device float* raw = y + t * hv * S + h * S + j; + const int jj = j & 15; + raw[a.plane] = yv * q2s[jj & 7]; + raw[2 * a.plane] = yv * p4s[jj & 3]; + raw[3 * a.plane] = (jj & 1) ? yv * 0.00390625f : yv; + ys[j] = yv; + } + } + if (t + 1 == commit_at) { + // the state and the conv history after token t (registers: st after this token's update, hst after its + // shift); the state is read only before the loop, so in place is safe. q/k history: the threadgroups + // h < h_k own their q/k head (h == hk); v history: every head its own - to hist_out, NOT in place: a q/k + // channel is read by the three threadgroups h % h_k at their start, and a threadgroup may start after its + // owner has finished (seen on the 10-core M4); the caller swaps the two + for (int r = 0; r < RPT; ++r) state[((i0 + r) * hv + h) * S + j] = st[r]; + if (ch >= 0 && (tid >= 256 || h < int(a.h_k))) + for (int k = 0; k < 3; ++k) hist_out[ch * 3 + k] = hst[k]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (a.plane && ib == 0 && (j & 15) == 0) { + float s0 = 0.0f, s1 = 0.0f; + for (int k = 0; k < 16; k += 2) { s0 += ys[j + k]; s1 += ys[j + k + 1]; } + y[4 * a.plane + t * (hv * S / 16) + (h * S + j) / 16] = s0 + s1; + } + } +} + +template [[host_name("gdn_step")]] kernel decltype(gdn_step_t<4>) gdn_step_t<4>; +template [[host_name("gdn_step8")]] kernel decltype(gdn_step_t<8>) gdn_step_t<8>; diff --git a/metal/kernels/gdn_prompt.metal b/metal/kernels/gdn_prompt.metal new file mode 100644 index 00000000..b2d530b1 --- /dev/null +++ b/metal/kernels/gdn_prompt.metal @@ -0,0 +1,485 @@ +// metal/kernels/gdn_prompt.metal - a GDN layer's recurrence for a PROMPT chunk of T tokens, in three passes: the work +// that does not touch the state runs parallel over the tokens; only the state update is a scan, and the columns of a +// head's state are independent in it (column j needs k, q, v_j, the gate and beta), so a lane owns one column. +// +// gdn_pre per (token, head): conv (4 taps; history oldest first) -> SiLU; q, k L2 norm * 1/sqrt(128) (the decode +// step's arithmetic); kq = k . q per key head; gate = exp(softplus(alpha + dt) * a), beta = sigmoid(beta); +// the chunk's last 3 conv inputs -> hist_out +// gdn_scan per (value head, 32 columns x CB simdgroups): the state column in registers (128 floats a lane); +// per token a = S^T k, b = S^T q (old state), delta = (v - g a) beta, o = (g b + delta kq) / sqrt(128) +// (= S_new^T q / sqrt(128)), S = g S + k delta^T; q and k staged per TB tokens in threadgroup memory +// gdn_post per (token, head): y = o * rsqrt(mean(o^2) + eps) * gamma * sigmoid(z) -> fp16 (the out GEMM's operand) +// and, with `f32`, fp32 +// +// State layout as Strata's: S[(i * h_v + h) * 128 + j]. Value head h reads q/k head h % h_k. +// The kernels are new entries (nothing of gdn.metal changes). + +struct GdnPArgs { + uint n_tok; + uint h_k; // 16 + uint h_v; // 48 + uint channels; // 10240 + float eps; // 1e-6 + uint f32; // gdn_post: also write fp32 y +}; + +static inline float gp_conv(device const float* qkv, device const float* hist, device const float* cw, int ch, int t, + int channels) { + float s = 0.0f; + for (int k = 0; k < 4; ++k) { + const int src = t - 3 + k; + const float x = src >= 0 ? qkv[src * channels + ch] : hist[ch * 3 + (src + 3)]; + s = fma(x, cw[ch * 4 + k], s); + } + s = s + 0.0f; + return s / (1.0f + exp(-s)); +} + +// grid (h_k + h_v / 2, T), 256 threads. x < h_k: q (threads 0..127) and k (128..255) of key head x; else value heads +// 2 (x - h_k) and + 1. +kernel void gdn_pre(device const float* qkv [[buffer(0)]], device const float* hist [[buffer(1)]], + device const float* conv_w [[buffer(2)]], device const float* alpha [[buffer(3)]], + device const float* beta [[buffer(4)]], device const float* dt [[buffer(5)]], + device const float* ssm_a [[buffer(6)]], device float* qn [[buffer(7)]], device float* kn [[buffer(8)]], + device float* vc [[buffer(9)]], device float2* gb [[buffer(10)]], device float* kq [[buffer(11)]], + device float* hist_out [[buffer(12)]], constant GdnPArgs& a [[buffer(13)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + constexpr int S = 128; + threadgroup float part[8]; + threadgroup float prod[S]; + const int x = int(tg.x), t = int(tg.y), hk_n = int(a.h_k), hv = int(a.h_v), C = int(a.channels), T = int(a.n_tok); + int ch; + if (x < hk_n) ch = tid < 128 ? x * S + tid : hk_n * S + x * S + (tid - 128); + else ch = 2 * hk_n * S + (2 * (x - hk_n) + (tid >> 7)) * S + (tid & 127); + const float cv = gp_conv(qkv, hist, conv_w, ch, t, C); + if (t == T - 1) + for (int k = 0; k < 3; ++k) { + const int src = T - 3 + k; + hist_out[ch * 3 + k] = src >= 0 ? qkv[src * C + ch] : hist[ch * 3 + (src + 3)]; + } + if (x < hk_n) { + const float ssq = simd_sum(cv * cv); + if (lane == 0) part[sg] = ssq; + threadgroup_barrier(mem_flags::mem_threadgroup); + const int base = tid < 128 ? 0 : 4; + const float tot = (part[base] + part[base + 1]) + (part[base + 2] + part[base + 3]); + const float rs = rsqrt(tot / float(S) + a.eps / float(S)); + const float nv = (rs * cv) * (1.0f / sqrt(float(S))); + if (tid < 128) { + qn[(t * hk_n + x) * S + tid] = nv; + prod[tid] = nv; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid >= 128) { + kn[(t * hk_n + x) * S + tid - 128] = nv; + const float p = simd_sum(nv * prod[tid - 128]); + if (lane == 0) part[sg] = p; // simdgroups 4..7 (q's slots 0..3 are read already) + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid == 0) kq[t * hk_n + x] = (part[4] + part[5]) + (part[6] + part[7]); + } else { + const int h = 2 * (x - hk_n) + (tid >> 7); + vc[(t * hv + h) * S + (tid & 127)] = cv; + if ((tid & 127) == 0) { + const float v = alpha[t * hv + h] + dt[h]; + const float e = exp(v), u = 1.0f + e; + const float sp = v > 20.0f ? v : (u == 1.0f ? e : log(u) * e / (u - 1.0f)); + gb[t * hv + h] = float2(exp(sp * ssm_a[h]), 1.0f / (1.0f + exp(-beta[t * hv + h]))); + } + } +} + +// grid (h_v * 4 / CB), CB * 32 threads; TB tokens of q and k staged at a time +template +kernel void gdn_scan_t(device float* state [[buffer(0)]], device const float4* qn [[buffer(1)]], + device const float4* kn [[buffer(2)]], device const float* vc [[buffer(3)]], + device const float2* gb [[buffer(4)]], device const float* kq [[buffer(5)]], + device float* o [[buffer(6)]], constant GdnPArgs& a [[buffer(7)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + constexpr int S = 128, NB = 4 / CB; + threadgroup float4 qs[TB][32], ks[TB][32]; + const int h = int(tg.x) / NB, hk = h % int(a.h_k), hv = int(a.h_v), hkn = int(a.h_k); + const int j = ((int(tg.x) % NB) * CB + sg) * 32 + lane; + const int T = int(a.n_tok); + const float scale = 1.0f / sqrt(float(S)); + float st[S]; +#pragma clang loop unroll(full) + for (int i = 0; i < S; ++i) st[i] = state[(i * hv + h) * S + j]; + for (int t0 = 0; t0 < T; t0 += TB) { + const int nb = min(TB, T - t0); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int idx = tid; idx < nb * 32; idx += CB * 32) { + const int tt = idx >> 5, w = idx & 31; + qs[tt][w] = qn[((t0 + tt) * hkn + hk) * 32 + w]; + ks[tt][w] = kn[((t0 + tt) * hkn + hk) * 32 + w]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int tt = 0; tt < nb; ++tt) { + const int t = t0 + tt; + const float2 g_b = gb[t * hv + h]; + const float kqv = kq[t * hkn + hk]; + const float v = vc[(t * hv + h) * S + j]; + float ka = 0.0f, kb = 0.0f, qa = 0.0f, qb = 0.0f; +#pragma clang loop unroll(full) + for (int w = 0; w < 32; w += 2) { + const float4 k0 = ks[tt][w], k1 = ks[tt][w + 1], q0 = qs[tt][w], q1 = qs[tt][w + 1]; + ka = fma(st[4 * w], k0.x, ka); ka = fma(st[4 * w + 1], k0.y, ka); + ka = fma(st[4 * w + 2], k0.z, ka); ka = fma(st[4 * w + 3], k0.w, ka); + kb = fma(st[4 * w + 4], k1.x, kb); kb = fma(st[4 * w + 5], k1.y, kb); + kb = fma(st[4 * w + 6], k1.z, kb); kb = fma(st[4 * w + 7], k1.w, kb); + qa = fma(st[4 * w], q0.x, qa); qa = fma(st[4 * w + 1], q0.y, qa); + qa = fma(st[4 * w + 2], q0.z, qa); qa = fma(st[4 * w + 3], q0.w, qa); + qb = fma(st[4 * w + 4], q1.x, qb); qb = fma(st[4 * w + 5], q1.y, qb); + qb = fma(st[4 * w + 6], q1.z, qb); qb = fma(st[4 * w + 7], q1.w, qb); + } + const float g = g_b.x, kv = ka + kb, qv = qa + qb; + const float delta = (v - g * kv) * g_b.y; + o[(t * hv + h) * S + j] = fma(g, qv, delta * kqv) * scale; +#pragma clang loop unroll(full) + for (int w = 0; w < 32; ++w) { + const float4 k4 = ks[tt][w]; + st[4 * w] = fma(g, st[4 * w], k4.x * delta); + st[4 * w + 1] = fma(g, st[4 * w + 1], k4.y * delta); + st[4 * w + 2] = fma(g, st[4 * w + 2], k4.z * delta); + st[4 * w + 3] = fma(g, st[4 * w + 3], k4.w * delta); + } + } + } +#pragma clang loop unroll(full) + for (int i = 0; i < S; ++i) state[(i * hv + h) * S + j] = st[i]; +} + +// a probe for the bench (function constant 6): 1 = no per-token exchange (wrong results), 2 = no state update +constant int GDN_PROBE [[function_constant(6)]]; +constant int gdn_probe = is_function_constant_defined(GDN_PROBE) ? GDN_PROBE : 0; + +// the rows of a column split over IB simdgroups (128 / IB rows a lane, fewer registers): grid (h_v * 4), IB * 32 +// threads; lane = column (32 columns a threadgroup); per token the IB partial dots are exchanged through threadgroup +// memory (double-buffered: one barrier a token) +template +kernel void gdn_scan_r(device float* state [[buffer(0)]], device const float4* qn [[buffer(1)]], + device const float4* kn [[buffer(2)]], device const float* vc [[buffer(3)]], + device const float2* gb [[buffer(4)]], device const float* kq [[buffer(5)]], + device float* o [[buffer(6)]], constant GdnPArgs& a [[buffer(7)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + constexpr int S = 128, R = S / IB, R4 = R / 4; + threadgroup float4 qs[TB][32], ks[TB][32]; + threadgroup float2 red[2][IB][32]; + threadgroup float vs[TB][32]; + threadgroup float4 gk[TB]; // gate, beta, kq + const int h = int(tg.x) / 4, hk = h % int(a.h_k), hv = int(a.h_v), hkn = int(a.h_k); + const int j = (int(tg.x) % 4) * 32 + lane, i0 = sg * R; + const int T = int(a.n_tok); + const float scale = 1.0f / sqrt(float(S)); + float st[R]; +#pragma clang loop unroll(full) + for (int i = 0; i < R; ++i) st[i] = state[((i0 + i) * hv + h) * S + j]; + for (int t0 = 0; t0 < T; t0 += TB) { + const int nb = min(TB, T - t0); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int idx = tid; idx < nb * 32; idx += IB * 32) { + const int tt = idx >> 5, w = idx & 31; + qs[tt][w] = qn[((t0 + tt) * hkn + hk) * 32 + w]; + ks[tt][w] = kn[((t0 + tt) * hkn + hk) * 32 + w]; + vs[tt][w] = vc[((t0 + tt) * hv + h) * S + (j - lane) + w]; + if (w == 0) { + const float2 g_b = gb[(t0 + tt) * hv + h]; + gk[tt] = float4(g_b.x, g_b.y, kq[(t0 + tt) * hkn + hk], 0.0f); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int tt = 0; tt < nb; ++tt) { + const int t = t0 + tt, slot = t & 1; + float ka = 0.0f, qa = 0.0f; +#pragma clang loop unroll(full) + for (int w = 0; w < R4; ++w) { + const float4 k4 = ks[tt][i0 / 4 + w], q4 = qs[tt][i0 / 4 + w]; + ka = fma(st[4 * w], k4.x, ka); ka = fma(st[4 * w + 1], k4.y, ka); + ka = fma(st[4 * w + 2], k4.z, ka); ka = fma(st[4 * w + 3], k4.w, ka); + qa = fma(st[4 * w], q4.x, qa); qa = fma(st[4 * w + 1], q4.y, qa); + qa = fma(st[4 * w + 2], q4.z, qa); qa = fma(st[4 * w + 3], q4.w, qa); + } + const float4 g_b = gk[tt]; + const float kqv = g_b.z; + const float v = vs[tt][lane]; + float2 s = float2(ka, qa); + if (gdn_probe != 1) { + red[slot][sg][lane] = s; + threadgroup_barrier(mem_flags::mem_threadgroup); + s = red[slot][0][lane]; +#pragma clang loop unroll(full) + for (int b = 1; b < IB; ++b) s += red[slot][b][lane]; + } + const float g = g_b.x; + const float delta = (v - g * s.x) * g_b.y; + if (sg == 0) o[(t * hv + h) * S + j] = fma(g, s.y, delta * kqv) * scale; + if (gdn_probe != 2) +#pragma clang loop unroll(full) + for (int w = 0; w < R4; ++w) { + const float4 k4 = ks[tt][i0 / 4 + w]; + st[4 * w] = fma(g, st[4 * w], k4.x * delta); + st[4 * w + 1] = fma(g, st[4 * w + 1], k4.y * delta); + st[4 * w + 2] = fma(g, st[4 * w + 2], k4.z * delta); + st[4 * w + 3] = fma(g, st[4 * w + 3], k4.w * delta); + } + } + } +#pragma clang loop unroll(full) + for (int i = 0; i < R; ++i) state[((i0 + i) * hv + h) * S + j] = st[i]; +} + +// gdn_scan_r<8, 16> with the 16 state rows of a lane in four float4 variables (no array): a register-allocation check +kernel void gdn_scan_v(device float* state [[buffer(0)]], device const float4* qn [[buffer(1)]], + device const float4* kn [[buffer(2)]], device const float* vc [[buffer(3)]], + device const float2* gb [[buffer(4)]], device const float* kq [[buffer(5)]], + device float* o [[buffer(6)]], constant GdnPArgs& a [[buffer(7)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + constexpr int S = 128, IB = 8, TB = 16; + threadgroup float4 qs[TB][32], ks[TB][32]; + threadgroup float2 red[2][IB][32]; + threadgroup float vs[TB][32]; + threadgroup float4 gk[TB]; + const int h = int(tg.x) / 4, hk = h % int(a.h_k), hv = int(a.h_v), hkn = int(a.h_k); + const int j = (int(tg.x) % 4) * 32 + lane, i0 = sg * 16, w0 = sg * 4; + const int T = int(a.n_tok); + const float scale = 1.0f / sqrt(float(S)); + device float* sp = state + (i0 * hv + h) * S + j; + const int rs = hv * S; + float4 s0 = float4(sp[0], sp[rs], sp[2 * rs], sp[3 * rs]); + float4 s1 = float4(sp[4 * rs], sp[5 * rs], sp[6 * rs], sp[7 * rs]); + float4 s2 = float4(sp[8 * rs], sp[9 * rs], sp[10 * rs], sp[11 * rs]); + float4 s3 = float4(sp[12 * rs], sp[13 * rs], sp[14 * rs], sp[15 * rs]); + for (int t0 = 0; t0 < T; t0 += TB) { + const int nb = min(TB, T - t0); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int idx = tid; idx < nb * 32; idx += IB * 32) { + const int tt = idx >> 5, w = idx & 31; + qs[tt][w] = qn[((t0 + tt) * hkn + hk) * 32 + w]; + ks[tt][w] = kn[((t0 + tt) * hkn + hk) * 32 + w]; + vs[tt][w] = vc[((t0 + tt) * hv + h) * S + (j - lane) + w]; + if (w == 0) { + const float2 g_b = gb[(t0 + tt) * hv + h]; + gk[tt] = float4(g_b.x, g_b.y, kq[(t0 + tt) * hkn + hk], 0.0f); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int tt = 0; tt < nb; ++tt) { + const int t = t0 + tt, slot = t & 1; + const float4 k0 = ks[tt][w0], k1 = ks[tt][w0 + 1], k2 = ks[tt][w0 + 2], k3 = ks[tt][w0 + 3]; + const float4 q0 = qs[tt][w0], q1 = qs[tt][w0 + 1], q2 = qs[tt][w0 + 2], q3 = qs[tt][w0 + 3]; + const float ka = (dot(s0, k0) + dot(s1, k1)) + (dot(s2, k2) + dot(s3, k3)); + const float qa = (dot(s0, q0) + dot(s1, q1)) + (dot(s2, q2) + dot(s3, q3)); + red[slot][sg][lane] = float2(ka, qa); + const float4 g_b = gk[tt]; + const float v = vs[tt][lane]; + threadgroup_barrier(mem_flags::mem_threadgroup); + float2 r = red[slot][0][lane]; + for (int b = 1; b < IB; ++b) r += red[slot][b][lane]; + const float g = g_b.x; + const float delta = (v - g * r.x) * g_b.y; + if (sg == 0) o[(t * hv + h) * S + j] = fma(g, r.y, delta * g_b.z) * scale; + s0 = fma(float4(g), s0, k0 * delta); + s1 = fma(float4(g), s1, k1 * delta); + s2 = fma(float4(g), s2, k2 * delta); + s3 = fma(float4(g), s3, k3 * delta); + } + } + sp[0] = s0.x; sp[rs] = s0.y; sp[2 * rs] = s0.z; sp[3 * rs] = s0.w; + sp[4 * rs] = s1.x; sp[5 * rs] = s1.y; sp[6 * rs] = s1.z; sp[7 * rs] = s1.w; + sp[8 * rs] = s2.x; sp[9 * rs] = s2.y; sp[10 * rs] = s2.z; sp[11 * rs] = s2.w; + sp[12 * rs] = s3.x; sp[13 * rs] = s3.y; sp[14 * rs] = s3.z; sp[15 * rs] = s3.w; +} + +// grid (h_v, T), 128 threads +kernel void gdn_post(device const float* o [[buffer(0)]], device const float* z [[buffer(1)]], + device const float* gamma [[buffer(2)]], device half* yh [[buffer(3)]], device float* y [[buffer(4)]], + constant GdnPArgs& a [[buffer(5)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + threadgroup float part[4]; + const int h = int(tg.x), t = int(tg.y), hv = int(a.h_v); + const uint i = uint(t * hv + h) * 128 + tid; + const float ov = o[i]; + const float ss = simd_sum(ov * ov); + if (lane == 0) part[sg] = ss; + threadgroup_barrier(mem_flags::mem_threadgroup); + const float tot = (part[0] + part[1]) + (part[2] + part[3]); + const float rs = rsqrt(tot / 128.0f + a.eps); + const float yv = ((rs * ov) * gamma[tid]) * (1.0f / (1.0f + exp(-z[i]))); + yh[i] = half(yv); + if (a.f32) y[i] = yv; +} + +template [[host_name("gdn_scan_1")]] kernel decltype(gdn_scan_t<1, 16>) gdn_scan_t<1, 16>; +template [[host_name("gdn_scan_2")]] kernel decltype(gdn_scan_t<2, 16>) gdn_scan_t<2, 16>; +template [[host_name("gdn_scan_4")]] kernel decltype(gdn_scan_t<4, 16>) gdn_scan_t<4, 16>; +template [[host_name("gdn_scanr_2")]] kernel decltype(gdn_scan_r<2, 16>) gdn_scan_r<2, 16>; +template [[host_name("gdn_scanr_4")]] kernel decltype(gdn_scan_r<4, 16>) gdn_scan_r<4, 16>; +template [[host_name("gdn_scanr_8")]] kernel decltype(gdn_scan_r<8, 16>) gdn_scan_r<8, 16>; +template [[host_name("gdn_scanr_4_8")]] kernel decltype(gdn_scan_r<4, 8>) gdn_scan_r<4, 8>; + +// ---- the chunked form (chunks of GC = 32 tokens), the WY / UT form of the gated delta rule. With G_t the product +// of the chunk's gates up to t (log space: lg_t) and S0 the state entering the chunk: +// (I + A) D = B, A_ts = beta_t (k_t . k_s) G_t / G_s (s < t), B = [beta v | beta G k] -> D = [U | W] +// delta = U - W S0, o_t = G_t S0^T q_t + sum_{s <= t} (q_t . k_s) G_t / G_s delta_s, +// S_L = G_L S0 + sum_s G_L / G_s k_s delta_s^T +// (the sequential recurrence's algebra; the rounding differs). Three kernels: +// gdn_cprep per (head, chunk): lg, A, the forward substitution for U and W (a thread per column of B) +// gdn_cstate per (head, 32 state columns): the chunks in order - delta, the inter-chunk output, the state update +// gdn_cout per (head, chunk): o += the intra-chunk part, times 1/sqrt(128) +constant constexpr int GC = 32; + +// grid (h_v, chunks), 256 threads. U, W: [h][chunk][GC][128]; lgo: [h][chunk][GC] +kernel void gdn_cprep(device const float* qn [[buffer(0)]], device const float* kn [[buffer(1)]], + device const float* vc [[buffer(2)]], device const float2* gb [[buffer(3)]], + device float* U [[buffer(4)]], device float* W [[buffer(5)]], device float* lgo [[buffer(6)]], + constant GdnPArgs& a [[buffer(7)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int S = 128; + threadgroup float A[GC][GC]; + threadgroup float lg[GC], bt[GC]; + const int h = int(tg.x), c = int(tg.y), hv = int(a.h_v), hkn = int(a.h_k), hk = h % hkn, T = int(a.n_tok); + const int NC = (T + GC - 1) / GC, t0 = c * GC, nb = min(GC, T - t0); + if (tid == 0) { + float s = 0.0f; + for (int t = 0; t < GC; ++t) { + if (t < nb) s += max(log(gb[(t0 + t) * hv + h].x), -80.0f); + lg[t] = s; + bt[t] = t < nb ? gb[(t0 + t) * hv + h].y : 0.0f; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int idx = tid; idx < GC * GC; idx += 256) { + const int t = idx / GC, s = idx % GC; + float v = 0.0f; + if (s < t && t < nb) { + device const float4* kt = (device const float4*)(kn + ((t0 + t) * hkn + hk) * S); + device const float4* ks = (device const float4*)(kn + ((t0 + s) * hkn + hk) * S); + float d = 0.0f; + for (int i = 0; i < S / 4; ++i) d += dot(kt[i], ks[i]); + v = bt[t] * d * exp(lg[t] - lg[s]); + } + A[t][s] = v; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // forward substitution, column j of B a thread (threads 0..127: beta v; 128..255: beta G k) + const int j = tid & 127; + const bool isw = tid >= 128; + float x[GC]; + for (int t = 0; t < GC; ++t) { + float b = 0.0f; + if (t < nb) b = isw ? bt[t] * exp(lg[t]) * kn[((t0 + t) * hkn + hk) * S + j] : bt[t] * vc[((t0 + t) * hv + h) * S + j]; + for (int s = 0; s < t; ++s) b = fma(-A[t][s], x[s], b); + x[t] = b; + } + device float* o = (isw ? W : U) + (ulong(h) * NC + c) * GC * S + j; + for (int t = 0; t < GC; ++t) o[t * S] = x[t]; + if (tid < GC) lgo[(h * NC + c) * GC + tid] = lg[tid]; +} + +// grid (h_v * 4), 256 threads = 8 row blocks of 16 x 32 columns; the state's 128 x 32 block in registers (16 a thread) +kernel void gdn_cstate(device float* state [[buffer(0)]], device const float* qn [[buffer(1)]], + device const float* kn [[buffer(2)]], device const float* U [[buffer(3)]], + device const float* W [[buffer(4)]], device const float* lgo [[buffer(5)]], + device float* delta [[buffer(6)]], device float* o [[buffer(7)]], constant GdnPArgs& a [[buffer(8)]], + uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]]) { + constexpr int S = 128, RB = 16; + threadgroup float red[8][16][32]; + threadgroup float dl[GC][32]; + const int h = int(tg.x) / 4, hv = int(a.h_v), hkn = int(a.h_k), hk = h % hkn, T = int(a.n_tok); + const int NC = (T + GC - 1) / GC; + const int j = (int(tg.x) % 4) * 32 + lane, i0 = sg * RB; + float st[RB]; + for (int r = 0; r < RB; ++r) st[r] = state[((i0 + r) * hv + h) * S + j]; + for (int c = 0; c < NC; ++c) { + const int t0 = c * GC, nb = min(GC, T - t0); + device const float* Uc = U + (ulong(h) * NC + c) * GC * S; + device const float* Wc = W + (ulong(h) * NC + c) * GC * S; + device const float* lg = lgo + (h * NC + c) * GC; + // pass 0: delta = U - W S0; pass 1: o_inter = G_t S0^T q_t; 16 tokens at a time + for (int pass = 0; pass < 2; ++pass) { + for (int hf = 0; hf < 2; ++hf) { + float p[16]; + for (int u = 0; u < 16; ++u) { + const int t = hf * 16 + u; + float s = 0.0f; + if (t < nb) { + device const float* v = pass == 0 ? Wc + t * S + i0 : qn + ((t0 + t) * hkn + hk) * S + i0; + for (int r = 0; r < RB; ++r) s = fma(v[r], st[r], s); + } + p[u] = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int u = 0; u < 16; ++u) red[sg][u][lane] = p[u]; + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int u = sg * 2; u < sg * 2 + 2; ++u) { + const int t = hf * 16 + u; + float s = 0.0f; + for (int b = 0; b < 8; ++b) s += red[b][u][lane]; + if (t < nb) { + if (pass == 0) { + const float d = Uc[t * S + j] - s; + dl[t][lane] = d; + delta[((ulong(h) * NC + c) * GC + t) * S + j] = d; + } else { + o[((t0 + t) * hv + h) * S + j] = exp(lg[t]) * s; + } + } else if (pass == 0) { + dl[t][lane] = 0.0f; + } + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // S = G_L S0 + sum_s G_L / G_s k_s delta_s^T + const float lgl = lg[nb - 1], gl = exp(lgl); + for (int r = 0; r < RB; ++r) st[r] *= gl; + for (int s = 0; s < nb; ++s) { + const float f = exp(lgl - lg[s]) * dl[s][lane]; + device const float* ks = kn + ((t0 + s) * hkn + hk) * S + i0; + for (int r = 0; r < RB; ++r) st[r] = fma(ks[r], f, st[r]); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + for (int r = 0; r < RB; ++r) state[((i0 + r) * hv + h) * S + j] = st[r]; +} + +// grid (h_v, chunks), 128 threads (column j): o_t = (o_inter_t + sum_{s <= t} (q_t . k_s) G_t / G_s delta_s) / sqrt(128) +kernel void gdn_cout(device const float* qn [[buffer(0)]], device const float* kn [[buffer(1)]], + device const float* delta [[buffer(2)]], device const float* lgo [[buffer(3)]], + device float* o [[buffer(4)]], constant GdnPArgs& a [[buffer(5)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int S = 128; + threadgroup float M[GC][GC]; + const int h = int(tg.x), c = int(tg.y), hv = int(a.h_v), hkn = int(a.h_k), hk = h % hkn, T = int(a.n_tok); + const int NC = (T + GC - 1) / GC, t0 = c * GC, nb = min(GC, T - t0); + device const float* lg = lgo + (h * NC + c) * GC; + for (int idx = tid; idx < GC * GC; idx += 128) { + const int t = idx / GC, s = idx % GC; + float v = 0.0f; + if (s <= t && t < nb) { + device const float4* qt = (device const float4*)(qn + ((t0 + t) * hkn + hk) * S); + device const float4* ks = (device const float4*)(kn + ((t0 + s) * hkn + hk) * S); + float d = 0.0f; + for (int i = 0; i < S / 4; ++i) d += dot(qt[i], ks[i]); + v = d * exp(lg[t] - lg[s]); + } + M[t][s] = v; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const int j = tid; + device const float* dc = delta + (ulong(h) * NC + c) * GC * S + j; + float dv[GC]; + for (int s = 0; s < GC; ++s) dv[s] = s < nb ? dc[s * S] : 0.0f; + const float scale = 1.0f / sqrt(float(S)); + for (int t = 0; t < nb; ++t) { + float s = o[((t0 + t) * hv + h) * S + j]; + for (int u = 0; u <= t; ++u) s = fma(M[t][u], dv[u], s); + o[((t0 + t) * hv + h) * S + j] = s * scale; + } +} diff --git a/metal/kernels/gemv.metal b/metal/kernels/gemv.metal new file mode 100644 index 00000000..6d4ed3a5 --- /dev/null +++ b/metal/kernels/gemv.metal @@ -0,0 +1,264 @@ +// metal/kernels/gemv.metal - y[t][r] = W[r] . x[t] for a window of 1..8 tokens (dense projections, the shared +// expert, the LM head), any format of quant.metal/units.metal. +// +// Shape of a threadgroup: SG simdgroups; KS of them split the row's units (KS = 1: no split), the other SG/KS cover +// different rows. In a simdgroup, LPR lanes share a row and 32/LPR rows run side by side; each lane holds NR rows. +// The weights of a unit are decoded once and applied to every token. Partial sums of a K split are added in a +// fixed order (deterministic). + +struct GemvArgs { + uint n_in; + uint n_out; + uint n_tok; + uint row_bytes; + uint x_stride; // floats between tokens' x rows + uint y_stride; // floats between tokens' y rows +}; + +constant int NTOK [[function_constant(0)]]; // tokens of the window (1..8): the token loops are specialised +// a bench probe (function constant 9): 1 = tokens past the first reuse token 0's x (no load; wrong values), +// 2 = tokens past the first skip the combine (wrong values) +constant int GEMV_PROBE [[function_constant(9)]]; +constant int gemv_probe = is_function_constant_defined(GEMV_PROBE) ? GEMV_PROBE : 0; + +template +kernel void gemv(device const uchar* W [[buffer(0)]], device const float* xp [[buffer(1)]], + device const float* s16 [[buffer(2)]], device float* y [[buffer(3)]], constant GemvArgs& a [[buffer(4)]], + uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int UNIT = fmt::UNIT, RS = SG / KS, RG = 32 / LPR; + threadgroup uint tab[fmt::TAB]; + threadgroup float red[KS > 1 ? KS * RS * RG * NR * 8 : 1]; + load_tab(tab, tid, SG * 32); + threadgroup_barrier(mem_flags::mem_threadgroup); + const int ks = sg / RS, rs = sg % RS; + const int li = lane % LPR; + const int lrow0 = (rs * RG + lane / LPR) * NR; + const int row0 = int(tg.x) * RS * RG * NR + lrow0; + const int U = int(a.n_in) / UNIT; + const int u0 = ks * U / KS, u1 = (ks + 1) * U / KS; + float acc[NR][8]; + for (int r = 0; r < NR; ++r) + for (int t = 0; t < NTOK; ++t) acc[r][t] = 0.0f; + device const uchar* rp[NR]; + for (int r = 0; r < NR; ++r) rp[r] = W + (ulong)min(row0 + r, int(a.n_out) - 1) * a.row_bytes; + const int s16n = int(a.n_in) / 16; + if (gemv_probe == 3) { + // rows outer, tokens inner: one row's decoded unit in registers at a time (x re-read per row from L1) + for (int u = u0 + li; u < u1; u += LPR) + for (int r = 0; r < NR; ++r) { + float q[UNIT]; + float4 sc; + Dec::run(rp[r], u, q, sc, tab); + for (int t = 0; t < NTOK; ++t) { + float xs[UNIT], xsum[2]; + X::load(xp + t * int(a.x_stride), s16 + t * s16n, u, xs, xsum); + acc[r][t] += unit_combine(q, sc, xs, xsum); + } + } + } else + for (int u = u0 + li; u < u1; u += LPR) { + float q[NR][UNIT]; + float4 sc[NR]; + for (int r = 0; r < NR; ++r) Dec::run(rp[r], u, q[r], sc[r], tab); + float xs[UNIT], xsum[2]; + for (int t = 0; t < NTOK; ++t) { + if (gemv_probe != 1 || t == 0) X::load(xp + t * int(a.x_stride), s16 + t * s16n, u, xs, xsum); + if (gemv_probe != 2 || t == 0) + for (int r = 0; r < NR; ++r) acc[r][t] += unit_combine(q[r], sc[r], xs, xsum); + } + } + constexpr int RPT = RS * RG * NR; + for (int r = 0; r < NR; ++r) + for (int t = 0; t < NTOK; ++t) { + const float v = lane_sum(acc[r][t]); + if (KS == 1) { + if (li == 0 && row0 + r < int(a.n_out)) y[t * int(a.y_stride) + row0 + r] = v; + } else if (li == 0) { + red[(ks * RPT + lrow0 + r) * 8 + t] = v; + } + } + if (KS > 1) { + threadgroup_barrier(mem_flags::mem_threadgroup); + if (ks == 0 && li == 0) + for (int r = 0; r < NR; ++r) + for (int t = 0; t < NTOK; ++t) { + float v = 0.0f; + for (int k = 0; k < KS; ++k) v += red[(k * RPT + lrow0 + r) * 8 + t]; + if (row0 + r < int(a.n_out)) y[t * int(a.y_stride) + row0 + r] = v; + } + } +} + +#define GV(F, L, R, S, K) template [[host_name("gemv_" #F "_" #L "_" #R "_" #S "_" #K)]] kernel decltype(gemv) gemv; +#define GV_SET(F) GV(F, 32, 1, 4, 1) GV(F, 32, 2, 4, 1) GV(F, 16, 1, 4, 1) GV(F, 16, 2, 4, 1) GV(F, 8, 1, 4, 1) \ + GV(F, 8, 2, 4, 1) GV(F, 4, 2, 4, 1) GV(F, 4, 1, 4, 1) GV(F, 32, 1, 4, 4) GV(F, 32, 2, 4, 2) \ + GV(F, 32, 1, 8, 8) GV(F, 16, 1, 8, 4) GV(F, 32, 1, 8, 2) GV(F, 8, 1, 8, 1) GV(F, 1, 1, 4, 1) GV(F, 1, 2, 4, 1) GV(F, 2, 1, 4, 1) GV(F, 2, 2, 4, 1) GV(F, 1, 1, 2, 1) GV(F, 4, 4, 4, 1) +#ifndef GEMV_TYPES +#define GEMV_TYPES GV_SET(T_F32) GV_SET(T_BF16) GV_SET(T_Q8_0) GV_SET(T_Q4_0) GV_SET(T_Q5_0) GV_SET(T_IQ4_NL) GV_SET(T_IQ4_XS) \ + GV_SET(T_Q2_0) GV_SET(T_IQ3_S) GV_SET(T_Q3_K) GV_SET(T_Q4_K) GV_SET(T_Q5_K) GV_SET(T_Q6_K) +#endif +GEMV_TYPES + +// The shared expert's gate and up in one dispatch: h[t][r] = silu(Wg[r] . x[t]) * (Wu[r] . x[t]), each with its own +// format (and so its own prepared activation kind); h is written raw (its consumer reads raw activations). +// KS = 1; tiles as gemv. Buffers: Wg, xg (Wg's kind), Wu, xu (Wu's kind), s16, h, args (row_bytes = Wg's), rb_up. +template +kernel void gemv_pair(device const uchar* Wg [[buffer(0)]], device const float* xg [[buffer(1)]], + device const uchar* Wu [[buffer(2)]], device const float* xu [[buffer(3)]], + device const float* s16 [[buffer(4)]], device float* h [[buffer(5)]], + constant GemvArgs& a [[buffer(6)]], constant uint& rb_up [[buffer(7)]], + uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int U1 = fmt::UNIT, U2 = fmt::UNIT, RG = 32 / LPR; + constexpr int TB = fmt::TAB > fmt::TAB ? fmt::TAB : fmt::TAB; + threadgroup uint tab1[fmt::TAB]; + threadgroup uint tab2[fmt::TAB]; + (void)TB; + load_tab(tab1, tid, SG * 32); + load_tab(tab2, tid, SG * 32); + threadgroup_barrier(mem_flags::mem_threadgroup); + const int li = lane % LPR; + const int row = (int(tg.x) * SG + sg) * RG + lane / LPR; + const int rr = min(row, int(a.n_out) - 1); + device const uchar* rg = Wg + ulong(rr) * a.row_bytes; + device const uchar* ru = Wu + ulong(rr) * rb_up; + const int s16n = int(a.n_in) / 16; + float ag[8], au[8]; + for (int t = 0; t < 8; ++t) ag[t] = au[t] = 0.0f; + for (int u = li; u < int(a.n_in) / U1; u += LPR) { + float q[U1]; + float4 sc; + Dec::run(rg, u, q, sc, tab1); + for (int t = 0; t < NTOK; ++t) { + float xs[U1], xsum[2]; + X::load(xg + t * int(a.x_stride), s16 + t * s16n, u, xs, xsum); + ag[t] += unit_combine(q, sc, xs, xsum); + } + } + for (int u = li; u < int(a.n_in) / U2; u += LPR) { + float q[U2]; + float4 sc; + Dec::run(ru, u, q, sc, tab2); + for (int t = 0; t < NTOK; ++t) { + float xs[U2], xsum[2]; + X::load(xu + t * int(a.x_stride), s16 + t * s16n, u, xs, xsum); + au[t] += unit_combine(q, sc, xs, xsum); + } + } + for (int t = 0; t < NTOK; ++t) { + const float gv = lane_sum(ag[t]), uv = lane_sum(au[t]); + if (li == 0 && row < int(a.n_out)) h[t * int(a.y_stride) + row] = gv / (1.0f + exp(-gv)) * uv; + } +} + +#define GP_(F1, F2) template [[host_name("gemv_pair_" #F1 "_" #F2)]] kernel decltype(gemv_pair) gemv_pair; +#define GP(F1, F2) GP_(F1, F2) +#define GP_ROW(F1) GP(F1, T_IQ3_S) GP(F1, T_IQ4_XS) GP(F1, T_Q2_0) GP(F1, T_Q3_K) GP(F1, T_Q4_K) GP(F1, T_Q5_K) GP(F1, T_Q6_K) +GP_ROW(T_IQ3_S) GP_ROW(T_IQ4_XS) GP_ROW(T_Q2_0) GP_ROW(T_Q3_K) GP_ROW(T_Q4_K) GP_ROW(T_Q5_K) GP_ROW(T_Q6_K) +// Q2_0 with raw activations (the shared expert's down reading the pair's raw h) +GV_SET(T_Q2_0R) + +// gemv_cat: two matrices of the same format and n_in over the same x in one dispatch - rows [0, n_split) are W's +// (into y), rows [n_split, n_out) are W2's (into y2, from its row 0). Each row's arithmetic is gemv's (KS = 1), so the +// outputs are bitwise the two separate GEMVs'. (GDN's ssm_alpha + ssm_beta: 48 + 48 rows.) +// Buffers: W, xp, s16, y, args (n_out = both), W2, y2, n_split. +template +kernel void gemv_cat(device const uchar* W [[buffer(0)]], device const float* xp [[buffer(1)]], + device const float* s16 [[buffer(2)]], device float* y [[buffer(3)]], constant GemvArgs& a [[buffer(4)]], + device const uchar* W2 [[buffer(5)]], device float* y2 [[buffer(6)]], constant uint& n_split [[buffer(7)]], + uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int UNIT = fmt::UNIT, RG = 32 / LPR; + threadgroup uint tab[fmt::TAB]; + load_tab(tab, tid, SG * 32); + threadgroup_barrier(mem_flags::mem_threadgroup); + const int li = lane % LPR; + const int row0 = int(tg.x) * SG * RG * NR + (sg * RG + lane / LPR) * NR; + const int U = int(a.n_in) / UNIT, sp = int(n_split); + float acc[NR][8]; + for (int r = 0; r < NR; ++r) + for (int t = 0; t < NTOK; ++t) acc[r][t] = 0.0f; + device const uchar* rp[NR]; + for (int r = 0; r < NR; ++r) { + const int row = min(row0 + r, int(a.n_out) - 1); + rp[r] = row < sp ? W + (ulong)row * a.row_bytes : W2 + (ulong)(row - sp) * a.row_bytes; + } + const int s16n = int(a.n_in) / 16; + for (int u = li; u < U; u += LPR) { + float q[NR][UNIT]; + float4 sc[NR]; + for (int r = 0; r < NR; ++r) Dec::run(rp[r], u, q[r], sc[r], tab); + for (int t = 0; t < NTOK; ++t) { + float xs[UNIT], xsum[2]; + X::load(xp + t * int(a.x_stride), s16 + t * s16n, u, xs, xsum); + for (int r = 0; r < NR; ++r) acc[r][t] += unit_combine(q[r], sc[r], xs, xsum); + } + } + for (int r = 0; r < NR; ++r) + for (int t = 0; t < NTOK; ++t) { + const float v = lane_sum(acc[r][t]); + const int row = row0 + r; + if (li == 0 && row < int(a.n_out)) { + if (row < sp) y[t * int(a.y_stride) + row] = v; + else y2[t * int(a.y_stride) + row - sp] = v; + } + } +} +#define GVC_(F, L, R, S) template [[host_name("gemvc_" #F "_" #L "_" #R "_" #S)]] kernel decltype(gemv_cat) gemv_cat; +#define GVC(F, L, R, S) GVC_(F, L, R, S) +GVC(T_BF16, 32, 1, 4) GVC(T_BF16, 32, 1, 8) GVC(T_BF16, 16, 1, 4) GVC(T_BF16, 32, 2, 4) +GVC(T_F32, 32, 1, 4) GVC(T_F32, 32, 1, 8) GVC(T_F32, 16, 1, 4) GVC(T_F32, 32, 2, 4) + +// gemv_x: gemv (KS = 1) with the window's prepared x (the format's plane, NTOK rows, and its per-16 sums) staged in +// threadgroup memory once per threadgroup, so the per-unit x reads of every token come from threadgroup memory +// instead of L1 (on the M4 the x traffic through L1 - 4 B a weight a token, shared by the rows in a simdgroup - is +// what a window token costs). Same tile meaning and the same arithmetic as gemv_____1: bitwise. +// Dynamic threadgroup memory 0: 4 * NTOK * (n_in + n_in / 16) bytes. +template +kernel void gemv_x(device const uchar* W [[buffer(0)]], device const float* xp [[buffer(1)]], + device const float* s16 [[buffer(2)]], device float* y [[buffer(3)]], constant GemvArgs& a [[buffer(4)]], + threadgroup float* xt [[threadgroup(0)]], + uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int UNIT = fmt::UNIT, RG = 32 / LPR; + threadgroup uint tab[fmt::TAB]; + load_tab(tab, tid, SG * 32); + const int n = int(a.n_in), s16n = n / 16; + threadgroup float* st = xt + NTOK * n; + for (int t = 0; t < NTOK; ++t) { + device const float4* src = (device const float4*)(xp + t * int(a.x_stride)); + threadgroup float4* dst = (threadgroup float4*)(xt + t * n); + for (int i = tid; i < n / 4; i += SG * 32) dst[i] = src[i]; + for (int i = tid; i < s16n; i += SG * 32) st[t * s16n + i] = s16[t * s16n + i]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const int li = lane % LPR; + const int row0 = int(tg.x) * SG * RG * NR + (sg * RG + lane / LPR) * NR; + const int U = n / UNIT; + float acc[NR][8]; + for (int r = 0; r < NR; ++r) + for (int t = 0; t < NTOK; ++t) acc[r][t] = 0.0f; + device const uchar* rp[NR]; + for (int r = 0; r < NR; ++r) rp[r] = W + (ulong)min(row0 + r, int(a.n_out) - 1) * a.row_bytes; + for (int u = li; u < U; u += LPR) { + float q[NR][UNIT]; + float4 sc[NR]; + for (int r = 0; r < NR; ++r) Dec::run(rp[r], u, q[r], sc[r], tab); + for (int t = 0; t < NTOK; ++t) { + float xs[UNIT], xsum[2]; + X::load((threadgroup const float*)(xt + t * n), (threadgroup const float*)(st + t * s16n), u, xs, xsum); + for (int r = 0; r < NR; ++r) acc[r][t] += unit_combine(q[r], sc[r], xs, xsum); + } + } + for (int r = 0; r < NR; ++r) + for (int t = 0; t < NTOK; ++t) { + const float v = lane_sum(acc[r][t]); + if (li == 0 && row0 + r < int(a.n_out)) y[t * int(a.y_stride) + row0 + r] = v; + } +} +#define GVX(F, L, R, S) template [[host_name("gemvx_" #F "_" #L "_" #R "_" #S)]] kernel decltype(gemv_x) gemv_x; +#define GVX_SET(F) GVX(F, 32, 1, 4) GVX(F, 32, 2, 4) GVX(F, 16, 1, 4) GVX(F, 16, 2, 4) GVX(F, 8, 1, 4) GVX(F, 8, 2, 4) \ + GVX(F, 4, 2, 4) GVX(F, 16, 2, 8) GVX(F, 8, 2, 8) GVX(F, 16, 4, 4) GVX(F, 32, 2, 8) GVX(F, 2, 2, 4) +GVX_SET(T_BF16) GVX_SET(T_Q8_0) GVX_SET(T_Q4_0) GVX_SET(T_Q5_0) GVX_SET(T_IQ4_NL) GVX_SET(T_IQ4_XS) GVX_SET(T_Q2_0) +GVX_SET(T_IQ3_S) GVX_SET(T_Q3_K) GVX_SET(T_Q4_K) GVX_SET(T_Q5_K) GVX_SET(T_Q6_K) diff --git a/metal/kernels/glue.metal b/metal/kernels/glue.metal new file mode 100644 index 00000000..b7bc8bcc --- /dev/null +++ b/metal/kernels/glue.metal @@ -0,0 +1,63 @@ +// metal/kernels/glue.metal - small elementwise steps between the big kernels (after quant/units/moe.metal). +// +// swiglu_prep h = silu(g) * u for the shared expert, written as prepared activations (xprep layout) +// moe_combine_sh bo[t] = sum_k ye[entry(t, k)] + sigmoid(sg[t]) * ysh[t] (k in order) + +struct GlueArgs { + uint n; // vector width + uint n_tok; + uint n_embd; + uint topk; +}; + +// grid (n / 16, n_tok), 16 threads: one group of 16 values +kernel void swiglu_prep(device const float* g [[buffer(0)]], device const float* u [[buffer(1)]], + device float* xp [[buffer(2)]], constant GlueArgs& a [[buffer(3)]], + uint3 tg [[threadgroup_position_in_grid]], ushort j [[thread_index_in_threadgroup]]) { + threadgroup float v[16]; + const uint t = tg.y, d = tg.x * 16 + j, plane = a.n_tok * a.n; + const float gv = g[t * a.n + d]; + const float h = gv / (1.0f + exp(-gv)) * u[t * a.n + d]; + const float q2s[8] = {1.0f, 0.25f, 0.0625f, 0.015625f, 0.00390625f, 0.0009765625f, 0.000244140625f, 0.00006103515625f}; + const float p4s[4] = {1.0f, 0.00390625f, 1.52587890625e-05f, 5.9604644775390625e-08f}; + device float* raw = xp + t * a.n + d; + raw[0] = h; + raw[plane] = h * q2s[j & 7]; + raw[2 * plane] = h * p4s[j & 3]; + raw[3 * plane] = (j & 1) ? h * 0.00390625f : h; + v[j] = h; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (j == 0) { + float s0 = 0.0f, s1 = 0.0f; + for (int k = 0; k < 16; k += 2) { s0 += v[k]; s1 += v[k + 1]; } + xp[4 * plane + t * (a.n / 16) + tg.x] = s0 + s1; + } +} + +kernel void moe_combine_sh(device const float* ye [[buffer(0)]], device const int* plan [[buffer(1)]], + device const float* ysh [[buffer(2)]], device const float* sg [[buffer(3)]], + device float* bo [[buffer(4)]], constant GlueArgs& a [[buffer(5)]], + uint gid [[thread_position_in_grid]]) { + const uint t = gid / a.n_embd, k = gid % a.n_embd; + if (t >= a.n_tok) return; + float s = 0.0f; + for (uint j = 0; j < a.topk; ++j) s += ye[plan[P_TOKENT + t * a.topk + j] * int(a.n_embd) + k]; + const float gs = 1.0f / (1.0f + exp(-sg[t])); + bo[gid] = fma(gs, ysh[gid], s); +} + +// slc_touch: reads n16 16-byte words (a weight range the next kernels will need) so they sit in the SLC; the xor is +// written only if it equals a value it never takes (keeps the loads alive). grid (ceil(n16 / 1024)), 256 threads, +// 4 words a thread. +kernel void slc_touch(device const uint4* src [[buffer(0)]], device uint* sink [[buffer(1)]], constant uint& n16 [[buffer(2)]], + uint gid [[thread_position_in_grid]]) { + uint s = 0; + for (uint k = 0; k < 4; ++k) { + const uint j = (gid >> 8) * 1024 + k * 256 + (gid & 255); + if (j < n16) { + const uint4 v = src[j]; + s ^= v.x ^ v.y ^ v.z ^ v.w; + } + } + if (s == 0x9e3779b9u) sink[0] = s; +} diff --git a/metal/kernels/gr.metal b/metal/kernels/gr.metal new file mode 100644 index 00000000..c1960fd5 --- /dev/null +++ b/metal/kernels/gr.metal @@ -0,0 +1,179 @@ +// metal/kernels/gr.metal - the hyper-connection (gated residual) read for a window of tokens, with the previous +// sublayer's write folded in. The math is fused_gr.hpp's (native contract: FP32 activations, BF16 weights): +// +// gr_norm R'[c] = R[c] + bo * 2 sigmoid(inj_prev[c] / hc) (when apply; written back in place) +// xn[c] = R'[c] * w_norm[c] * rsqrt(mean(R'[c]^2) + eps) +// gr_down lo[k] = silu((w_down[k] . xn) / hc) k < hc_lr; inject[c] = w_inject[c] . xn +// gr_up mixed[d] = mean_c xn[c][d] * sigmoid(w_up[c n + d] . lo), written as prepared activations (xprep's +// planes and per-16 sums) for the GEMVs that read it +// +// Shapes: n_embd 2560, hc 4, hc_lr 320. Per token t: R[t] (hc * n), bo[t] (n), inj_prev[t] (hc), xn[t] (hc * n), +// lo[t] (hc_lr), inject[t] (hc), XP planes of n_tok rows. + +constant int GR_NTOK [[function_constant(1)]]; + +struct GrArgs { + uint n_embd; + uint hc; + uint hc_lr; + uint n_tok; + uint apply; + float eps; +}; + +// one threadgroup per (stream c, token t), 256 threads +kernel void gr_norm(device float* R [[buffer(0)]], device const float* bo [[buffer(1)]], + device const float* inj [[buffer(2)]], device const float* w_norm [[buffer(3)]], + device float* xn [[buffer(4)]], constant GrArgs& a [[buffer(5)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + threadgroup float part[8]; + const uint c = tg.x, t = tg.y, n = a.n_embd; + device float* r = R + (t * a.hc + c) * n; + const float g = a.apply ? 2.0f / (1.0f + exp(-inj[t * a.hc + c] / float(a.hc))) : 0.0f; + float ss = 0.0f; + for (uint d = tid; d < n; d += 256) { + float v = r[d]; + if (a.apply) { + v = fma(bo[t * n + d], g, v); + r[d] = v; + } + ss = fma(v, v, ss); + } + ss = simd_sum(ss); + if (lane == 0) part[sg] = ss; + threadgroup_barrier(mem_flags::mem_threadgroup); + float tot = 0.0f; + for (int i = 0; i < 8; ++i) tot += part[i]; + const float rs = rsqrt(tot / float(n) + a.eps); + device float* o = xn + (t * a.hc + c) * n; + device const float* w = w_norm + c * n; + for (uint d = tid; d < n; d += 256) o[d] = r[d] * w[d] * rs; +} + +// rows: 0 .. hc_lr - 1 = w_down, hc_lr .. hc_lr + hc - 1 = w_inject (both bf16 rows of hc * n_embd). +// SG simdgroups split the row's units KS ways; LPR = 32 (a simdgroup per row); RS = SG / KS rows per threadgroup. +// one row's K-split partial over xn (units of format F) +template +static inline void grd_acc(device const uchar* w, int nin, int ks, int KS, ushort lane, device const float* xn, + thread float* acc, threadgroup const uint* notab) { + constexpr int UNIT = fmt::UNIT; + const int U = nin / UNIT, u0 = ks * U / KS, u1 = (ks + 1) * U / KS; + for (int u = u0 + lane; u < u1; u += 32) { + float q[UNIT]; + float4 sc; + Dec::run(w, u, q, sc, notab); + for (int t = 0; t < GR_NTOK; ++t) { + float xs[UNIT], xsum[2] = {0.0f, 0.0f}; + for (int k = 0; k < UNIT; k += 16) load16(xn + t * nin + UNIT * u + k, xs + k); + acc[t] += unit_combine(q, sc, xs, xsum); + } + } +} + +// FI: the inject rows' format (the Unsloth files: Q8_0 down, F32 inject); FI = F is the original kernel +template +kernel void gr_down_f(device const uchar* w_down [[buffer(0)]], device const uchar* w_inject [[buffer(1)]], + device const float* xn [[buffer(2)]], device float* lo [[buffer(3)]], + device float* inject [[buffer(4)]], constant GrArgs& a [[buffer(5)]], + uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]]) { + constexpr int RS = SG / KS; + threadgroup float red[KS * RS * 8]; + threadgroup uint notab[1]; + const int ks = sg / RS, rs = sg % RS; + const int row = int(tg.x) * RS + rs; + const int nrows = int(a.hc_lr + a.hc); + const int rr = min(row, nrows - 1); + const int nin = int(a.hc * a.n_embd); + const uint rb = uint(nin / fmt::QK * fmt::BB), rbi = uint(nin / fmt::QK * fmt::BB); + float acc[8]; + for (int t = 0; t < 8; ++t) acc[t] = 0.0f; + if (rr < int(a.hc_lr)) grd_acc(w_down + ulong(rr) * rb, nin, ks, KS, lane, xn, acc, notab); + else grd_acc(w_inject + ulong(rr - int(a.hc_lr)) * rbi, nin, ks, KS, lane, xn, acc, notab); + for (int t = 0; t < GR_NTOK; ++t) { + const float v = simd_sum(acc[t]); + if (lane == 0) red[(ks * RS + rs) * 8 + t] = v; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (ks == 0 && lane < GR_NTOK && row < nrows) { + const int t = lane; + float v = 0.0f; + for (int k = 0; k < KS; ++k) v += red[(k * RS + rs) * 8 + t]; + if (row < int(a.hc_lr)) { + const float z = v / float(a.hc); + lo[t * int(a.hc_lr) + row] = z / (1.0f + exp(-z)); + } else { + inject[t * int(a.hc) + row - int(a.hc_lr)] = v; + } + } +} + +// A threadgroup owns 16 consecutive d for all hc = 4 streams: 8 simdgroups, simdgroup s -> stream s / 2 and +// d0 + 8 (s % 2) .. + 8; LPR = 4 lanes per row (320 = 20 units of 16, 5 per lane). +// XP: [4 kinds][n_tok][n] then S16 [n_tok][n / 16] (units.metal's xprep layout). +template +kernel void gr_up_f(device const uchar* w_up [[buffer(0)]], device const float* lo [[buffer(1)]], + device const float* xn [[buffer(2)]], device float* xp [[buffer(3)]], + constant GrArgs& a [[buffer(4)]], + uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) { + threadgroup float gate[8][4][16]; + threadgroup float msum[8][16]; + threadgroup uint notab[1]; + const int n = int(a.n_embd), c = sg >> 1, dl = 8 * (sg & 1) + lane / 4, li = lane & 3; + const int d = int(tg.x) * 16 + dl; + constexpr int UNIT = fmt::UNIT; + device const uchar* w = w_up + ulong(c * n + d) * (a.hc_lr / fmt::QK * fmt::BB); + const int U = int(a.hc_lr) / UNIT; + float acc[8]; + for (int t = 0; t < 8; ++t) acc[t] = 0.0f; + for (int u = li; u < U; u += 4) { + float q[UNIT]; + float4 sc; + Dec::run(w, u, q, sc, notab); + for (int t = 0; t < GR_NTOK; ++t) { + float xs[UNIT], xsum[2] = {0.0f, 0.0f}; + for (int k = 0; k < UNIT; k += 16) load16(lo + t * int(a.hc_lr) + UNIT * u + k, xs + k); + acc[t] += unit_combine(q, sc, xs, xsum); + } + } + for (int t = 0; t < GR_NTOK; ++t) { + const float v = lane_sum<4>(acc[t]); + if (li == 0) gate[t][c][dl] = 1.0f / (1.0f + exp(-v)); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // 16 threads per token: thread j -> d0 + j + const int t = tid / 16, j = tid & 15; + if (t < GR_NTOK) { + const int dd = int(tg.x) * 16 + j; + const int hc = int(a.hc); + float m = 0.0f; + for (int cc = 0; cc < hc; ++cc) m = fma(xn[(t * hc + cc) * n + dd], gate[t][cc][j], m); + m = m / float(hc); + const uint plane = a.n_tok * uint(n); + device float* raw = xp + t * n + dd; + const float q2s[8] = {1.0f, 0.25f, 0.0625f, 0.015625f, 0.00390625f, 0.0009765625f, 0.000244140625f, + 0.00006103515625f}; + const float p4s[4] = {1.0f, 0.00390625f, 1.52587890625e-05f, 5.9604644775390625e-08f}; + raw[0] = m; + raw[plane] = m * q2s[j & 7]; + raw[2 * plane] = m * p4s[j & 3]; + raw[3 * plane] = (j & 1) ? m * 0.00390625f : m; + msum[t][j] = m; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t < GR_NTOK && j == 0) { + // the per-16 sum in xprep's order (even and odd partial sums, then added) + float s0 = 0.0f, s1 = 0.0f; + for (int k = 0; k < 16; k += 2) { s0 += msum[t][k]; s1 += msum[t][k + 1]; } + xp[4 * a.n_tok * uint(n) + t * (n / 16) + tg.x] = s0 + s1; + } +} + +#define GRD(S, K) template [[host_name("gr_down_" #S "_" #K)]] kernel decltype(gr_down_f) gr_down_f; \ + template [[host_name("gr_down_q8_" #S "_" #K)]] kernel decltype(gr_down_f) gr_down_f; \ + template [[host_name("gr_down_q8f_" #S "_" #K)]] kernel decltype(gr_down_f) gr_down_f; +GRD(8, 8) GRD(8, 4) GRD(4, 4) GRD(4, 2) GRD(16, 16) GRD(16, 8) +template [[host_name("gr_up")]] kernel decltype(gr_up_f) gr_up_f; +template [[host_name("gr_up_q8")]] kernel decltype(gr_up_f) gr_up_f; diff --git a/metal/kernels/gr2.metal b/metal/kernels/gr2.metal new file mode 100644 index 00000000..1253a11d --- /dev/null +++ b/metal/kernels/gr2.metal @@ -0,0 +1,341 @@ +// metal/kernels/gr2.metal - the hyper-connection read in TWO dispatches (after quant/units/gr.metal), for BF16 HC +// weights (the exact path) or a Q8_0 copy of them (the STRATA_HC_Q8 option): +// +// gr_down3 grid (row blocks, hc streams). The RMSNorm is per stream, so a threadgroup owns one stream c: it forms +// R'_c = R_c + bo * 2 sigmoid(inj_prev_c / hc) (10 KB a token), its sum of squares and rs_c itself, +// stages xn_c = (R'_c * w_norm_c) * rs_c in threadgroup memory once, and every simdgroup dots its rows' +// stream-c quarter with it: D[t][row][c]. Row block 0 also writes R'_c to R_out (ping-pong, never in +// place) and rs_c. Rows 0..hc_lr-1 are w_down, hc_lr.. the inject rows. +// gr_up3 lo[k] = silu(sum_c D[t][k][c] / hc) formed in threadgroup memory, then as gr_up with xn = R' * w_norm +// * rs on the fly, writing the prepared activations. +// inj_prev of the NEXT read = sum_c D[t][hc_lr + c'][c] of this one (gr_down3 sums it, in c order). +// +// Per element the arithmetic is gr_norm's (fma(bo, g, R), then (R' * w) * rs); the K order differs (per stream, then +// the 4 streams in order). + +#ifndef P_TOKENT +#define P_TOKENT 532 // moe.metal's plan layout +#endif + +struct GrArgs3 { + uint n_embd; + uint hc; + uint hc_lr; + uint n_tok; // the prepared planes' row count (the plane stride) + uint apply; + float eps; + uint rb_down; // bytes per row of w_down / w_inject + uint rb_up; // bytes per row of w_up + uint comb; // 1: bo is not given; it is the MoE combine (moe_combine_sh's arithmetic) of buffers 10..13 + uint topk; +}; + +// bo[t][d], given or the MoE combine: sum_k ye[entry(t, k)][d] (k in order) + sigmoid(sg[t]) * ysh[t][d] +static inline float bo_at(device const float* bo, device const int* plan, device const float* ye, + device const float* ysh, device const float* sg, constant GrArgs3& a, int t, int d) { + const int n = int(a.n_embd); + if (!a.comb) return bo[t * n + d]; + float s = 0.0f; + for (uint j = 0; j < a.topk; ++j) s += ye[plan[P_TOKENT + t * int(a.topk) + j] * n + d]; + const float gs = 1.0f / (1.0f + exp(-sg[t])); + return fma(gs, ysh[t * n + d], s); +} + +template +kernel void gr_down3(device const uchar* w_down [[buffer(0)]], device const uchar* w_inject [[buffer(1)]], + device const float* Rin [[buffer(2)]], device float* Rout [[buffer(3)]], + device const float* bo [[buffer(4)]], device const float* Dprev [[buffer(5)]], + device const float* wn [[buffer(6)]], device float* D [[buffer(7)]], + device float* rs_out [[buffer(8)]], constant GrArgs3& a [[buffer(9)]], + device const int* plan [[buffer(10)]], device const float* ye [[buffer(11)]], + device const float* ysh [[buffer(12)]], device const float* sgv [[buffer(13)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + constexpr int UNIT = fmt::UNIT; + threadgroup float xs_tg[TT][2560]; + threadgroup float part[8][TT]; + threadgroup float g_tg[TT], rs_tg[TT]; + threadgroup uint tab[fmt::TAB]; + load_tab(tab, tid, 256); + const int n = int(a.n_embd), hc = int(a.hc), NIN = hc * n, c = int(tg.y); + const int nrows = int(a.hc_lr) + hc; + for (int t0 = 0; t0 < GR_NTOK; t0 += TT) { + const int T = min(TT, GR_NTOK - t0); + if (tid < T) { + float g = 0.0f; + if (a.apply) { + device const float* dp = Dprev + ((t0 + tid) * nrows + int(a.hc_lr) + c) * hc; + const float ip = ((dp[0] + dp[1]) + dp[2]) + dp[3]; + g = 2.0f / (1.0f + exp(-ip / float(hc))); + } + g_tg[tid] = g; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int t = 0; t < T; ++t) { + device const float* rt = Rin + (t0 + t) * NIN + c * n; + float ss = 0.0f; + for (int d = tid; d < n; d += 256) { + float v = rt[d]; + if (a.apply) v = fma(bo_at(bo, plan, ye, ysh, sgv, a, t0 + t, d), g_tg[t], v); + xs_tg[t][d] = v; + ss = fma(v, v, ss); + if (tg.x == 0) Rout[(t0 + t) * NIN + c * n + d] = v; + } + ss = simd_sum(ss); + if (lane == 0) part[sg][t] = ss; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid < T) { + float tot = 0.0f; + for (int k = 0; k < 8; ++k) tot += part[k][tid]; + const float rsv = rsqrt(tot / float(n) + a.eps); + rs_tg[tid] = rsv; + if (tg.x == 0) rs_out[(t0 + tid) * hc + c] = rsv; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int t = 0; t < T; ++t) + for (int d = tid; d < n; d += 256) xs_tg[t][d] = xs_tg[t][d] * wn[c * n + d] * rs_tg[t]; + threadgroup_barrier(mem_flags::mem_threadgroup); + // the rows: simdgroup sg holds RPS rows; lanes split the stream's units + int rows[RPS]; + device const uchar* wr[RPS]; + for (int k = 0; k < RPS; ++k) { + rows[k] = (int(tg.x) * 8 + sg) * RPS + k; + const int rr = min(rows[k], nrows - 1); + wr[k] = rr < int(a.hc_lr) ? w_down + ulong(rr) * a.rb_down : w_inject + ulong(rr - int(a.hc_lr)) * a.rb_down; + } + float acc[RPS][TT]; + for (int k = 0; k < RPS; ++k) + for (int t = 0; t < TT; ++t) acc[k][t] = 0.0f; + const int U = n / UNIT, u0 = c * U; + for (int u = lane; u < U; u += 32) { + float q[RPS][UNIT]; + float4 sc[RPS]; + for (int k = 0; k < RPS; ++k) Dec::run(wr[k], u0 + u, q[k], sc[k], tab); + for (int t = 0; t < T; ++t) { + float xs[UNIT], xsum[2] = {0.0f, 0.0f}; + for (int e = 0; e < UNIT; ++e) xs[e] = xs_tg[t][u * UNIT + e]; + for (int k = 0; k < RPS; ++k) acc[k][t] += unit_combine(q[k], sc[k], xs, xsum); + } + } + for (int k = 0; k < RPS; ++k) + for (int t = 0; t < T; ++t) { + const float v = simd_sum(acc[k][t]); + if (lane == 0 && rows[k] < nrows) D[((t0 + t) * nrows + rows[k]) * hc + c] = v; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } +} + +// grid (n_embd / 16), 256 threads. +template +kernel void gr_up3(device const uchar* w_up [[buffer(0)]], device const float* D [[buffer(1)]], + device const float* Rn [[buffer(2)]], device float* xp [[buffer(3)]], + constant GrArgs3& a [[buffer(4)]], device const float* wn [[buffer(5)]], + device const float* rs [[buffer(6)]], + uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int UNIT = fmt::UNIT; + threadgroup float lo_tg[8][320]; + threadgroup float gate[8][4][16]; + threadgroup float msum[8][16]; + threadgroup uint tab[fmt::TAB]; + load_tab(tab, tid, 256); + const int n = int(a.n_embd), hc = int(a.hc), lr = int(a.hc_lr), nrows = lr + hc; + for (int e = tid; e < GR_NTOK * lr; e += 256) { + const int t = e / lr, k = e - t * lr; + device const float* dp = D + (t * nrows + k) * hc; + const float z = (((dp[0] + dp[1]) + dp[2]) + dp[3]) / float(hc); + lo_tg[t][k] = z / (1.0f + exp(-z)); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const int c = sg >> 1, dl = 8 * (sg & 1) + lane / 4, li = lane & 3; + const int d = int(tg.x) * 16 + dl; + device const uchar* w = w_up + ulong(c * n + d) * a.rb_up; + const int U = lr / UNIT; + float acc[8]; + for (int t = 0; t < 8; ++t) acc[t] = 0.0f; + for (int u = li; u < U; u += 4) { + float q[UNIT]; + float4 sc; + Dec::run(w, u, q, sc, tab); + for (int t = 0; t < GR_NTOK; ++t) { + float xs[UNIT], xsum[2] = {0.0f, 0.0f}; + for (int e = 0; e < UNIT; ++e) xs[e] = lo_tg[t][UNIT * u + e]; + acc[t] += unit_combine(q, sc, xs, xsum); + } + } + for (int t = 0; t < GR_NTOK; ++t) { + const float v = lane_sum<4>(acc[t]); + if (li == 0) gate[t][c][dl] = 1.0f / (1.0f + exp(-v)); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const int t = tid / 16, j = tid & 15; + if (t < GR_NTOK) { + const int dd = int(tg.x) * 16 + j; + float m = 0.0f; + for (int cc = 0; cc < hc; ++cc) { + const float xn = Rn[(t * hc + cc) * n + dd] * wn[cc * n + dd] * rs[t * hc + cc]; + m = fma(xn, gate[t][cc][j], m); + } + m = m / float(hc); + const uint plane = a.n_tok * uint(n); + device float* raw = xp + t * n + dd; + const float q2s[8] = {1.0f, 0.25f, 0.0625f, 0.015625f, 0.00390625f, 0.0009765625f, 0.000244140625f, + 0.00006103515625f}; + const float p4s[4] = {1.0f, 0.00390625f, 1.52587890625e-05f, 5.9604644775390625e-08f}; + raw[0] = m; + raw[plane] = m * q2s[j & 7]; + raw[2 * plane] = m * p4s[j & 3]; + raw[3 * plane] = (j & 1) ? m * 0.00390625f : m; + msum[t][j] = m; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (t < GR_NTOK && j == 0) { + float s0 = 0.0f, s1 = 0.0f; + for (int k = 0; k < 16; k += 2) { s0 += msum[t][k]; s1 += msum[t][k + 1]; } + xp[4 * a.n_tok * uint(n) + t * (n / 16) + tg.x] = s0 + s1; + } +} + +#define GD3(F, T, R) template [[host_name("gr_down3_" #F "_" #T "_" #R)]] kernel decltype(gr_down3) gr_down3; +GD3(30, 1, 1) GD3(30, 2, 1) GD3(30, 3, 1) GD3(30, 1, 2) GD3(30, 2, 2) GD3(30, 3, 2) +GD3(8, 1, 1) GD3(8, 2, 1) GD3(8, 3, 1) GD3(8, 1, 2) GD3(8, 2, 2) GD3(8, 3, 2) +template [[host_name("gr_up3_30")]] kernel decltype(gr_up3) gr_up3; +template [[host_name("gr_up3_8")]] kernel decltype(gr_up3) gr_up3; + +// BF16 only: as gr_down3, but each lane loads its rows' weights (5 units of 16 per row and lane: 2560 = 160 units) +// into registers before the norm phase, so the weight stream is in flight while the threadgroup forms xn. +template +kernel void gr_down3b(device const uchar* w_down [[buffer(0)]], device const uchar* w_inject [[buffer(1)]], + device const float* Rin [[buffer(2)]], device float* Rout [[buffer(3)]], + device const float* bo [[buffer(4)]], device const float* Dprev [[buffer(5)]], + device const float* wn [[buffer(6)]], device float* D [[buffer(7)]], + device float* rs_out [[buffer(8)]], constant GrArgs3& a [[buffer(9)]], + device const int* plan [[buffer(10)]], device const float* ye [[buffer(11)]], + device const float* ysh [[buffer(12)]], device const float* sgv [[buffer(13)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + threadgroup float xs_tg[TT][2560]; + threadgroup float part[8][TT]; + threadgroup float g_tg[TT], rs_tg[TT]; + const int n = int(a.n_embd), hc = int(a.hc), NIN = hc * n, c = int(tg.y); + const int nrows = int(a.hc_lr) + hc; + int rows[RPS]; + uint4 wr[RPS][5][2]; + for (int k = 0; k < RPS; ++k) { + rows[k] = (int(tg.x) * 8 + sg) * RPS + k; + const int rr = min(rows[k], nrows - 1); + device const uchar* w = rr < int(a.hc_lr) ? w_down + ulong(rr) * a.rb_down : w_inject + ulong(rr - int(a.hc_lr)) * a.rb_down; + device const uint4* p = (device const uint4*)(w + 2 * (c * n)); + for (int i = 0; i < 5; ++i) { + wr[k][i][0] = p[2 * (lane + 32 * i)]; + wr[k][i][1] = p[2 * (lane + 32 * i) + 1]; + } + } + for (int t0 = 0; t0 < GR_NTOK; t0 += TT) { + const int T = min(TT, GR_NTOK - t0); + if (tid < T) { + float g = 0.0f; + if (a.apply) { + device const float* dp = Dprev + ((t0 + tid) * nrows + int(a.hc_lr) + c) * hc; + const float ip = ((dp[0] + dp[1]) + dp[2]) + dp[3]; + g = 2.0f / (1.0f + exp(-ip / float(hc))); + } + g_tg[tid] = g; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int t = 0; t < T; ++t) { + device const float* rt = Rin + (t0 + t) * NIN + c * n; + float ss = 0.0f; + for (int d = tid; d < n; d += 256) { + float v = rt[d]; + if (a.apply) v = fma(bo_at(bo, plan, ye, ysh, sgv, a, t0 + t, d), g_tg[t], v); + xs_tg[t][d] = v; + ss = fma(v, v, ss); + if (tg.x == 0) Rout[(t0 + t) * NIN + c * n + d] = v; + } + ss = simd_sum(ss); + if (lane == 0) part[sg][t] = ss; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid < T) { + float tot = 0.0f; + for (int k = 0; k < 8; ++k) tot += part[k][tid]; + const float rsv = rsqrt(tot / float(n) + a.eps); + rs_tg[tid] = rsv; + if (tg.x == 0) rs_out[(t0 + tid) * hc + c] = rsv; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int t = 0; t < T; ++t) + for (int d = tid; d < n; d += 256) xs_tg[t][d] = xs_tg[t][d] * wn[c * n + d] * rs_tg[t]; + threadgroup_barrier(mem_flags::mem_threadgroup); + float acc[RPS][TT]; + for (int k = 0; k < RPS; ++k) + for (int t = 0; t < TT; ++t) acc[k][t] = 0.0f; + for (int i = 0; i < 5; ++i) { + const int u = lane + 32 * i; + for (int k = 0; k < RPS; ++k) { + const uint v[8] = {wr[k][i][0].x, wr[k][i][0].y, wr[k][i][0].z, wr[k][i][0].w, + wr[k][i][1].x, wr[k][i][1].y, wr[k][i][1].z, wr[k][i][1].w}; + float q[16]; + for (int e = 0; e < 8; ++e) { + q[2 * e] = as_type(v[e] << 16); + q[2 * e + 1] = as_type(v[e] & 0xFFFF0000u); + } + const float4 sc = float4(1.0f, 1.0f, 0.0f, 0.0f); + for (int t = 0; t < T; ++t) { + float xs[16], xsum[2] = {0.0f, 0.0f}; + for (int e = 0; e < 16; ++e) xs[e] = xs_tg[t][u * 16 + e]; + acc[k][t] += unit_combine<16>(q, sc, xs, xsum); + } + } + } + for (int k = 0; k < RPS; ++k) + for (int t = 0; t < T; ++t) { + const float v = simd_sum(acc[k][t]); + if (lane == 0 && rows[k] < nrows) D[((t0 + t) * nrows + rows[k]) * hc + c] = v; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } +} +#define GD3B(T, R) template [[host_name("gr_down3b_" #T "_" #R)]] kernel decltype(gr_down3b) gr_down3b; +GD3B(1, 1) GD3B(2, 1) GD3B(3, 1) GD3B(1, 2) GD3B(2, 2) GD3B(3, 2) + +// gr_norm_comb: gr_norm (gr.metal) with the sublayer output bo formed on the fly as the MoE combine - bo[t][d] = +// sum_k ye[entry(t, k)][d] (k in order) + sigmoid(sg[t]) * ysh[t][d], moe_combine_sh's arithmetic - so the combine's +// dispatch goes away; R', xn bitwise gr_norm's after moe_combine_sh. One threadgroup per (stream c, token t). +kernel void gr_norm_comb(device float* R [[buffer(0)]], device const float* ye [[buffer(1)]], + device const float* inj [[buffer(2)]], device const float* w_norm [[buffer(3)]], + device float* xn [[buffer(4)]], constant GrArgs& a [[buffer(5)]], + device const int* plan [[buffer(6)]], device const float* ysh [[buffer(7)]], + device const float* sgv [[buffer(8)]], constant uint& topk [[buffer(9)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + threadgroup float part[8]; + const uint c = tg.x, t = tg.y, n = a.n_embd; + device float* r = R + (t * a.hc + c) * n; + const float g = a.apply ? 2.0f / (1.0f + exp(-inj[t * a.hc + c] / float(a.hc))) : 0.0f; + const float gs = 1.0f / (1.0f + exp(-sgv[t])); + float ss = 0.0f; + for (uint d = tid; d < n; d += 256) { + float v = r[d]; + if (a.apply) { + float s = 0.0f; + for (uint j = 0; j < topk; ++j) s += ye[plan[P_TOKENT + t * topk + j] * int(n) + d]; + const float bo = fma(gs, ysh[t * n + d], s); + v = fma(bo, g, v); + r[d] = v; + } + ss = fma(v, v, ss); + } + ss = simd_sum(ss); + if (lane == 0) part[sg] = ss; + threadgroup_barrier(mem_flags::mem_threadgroup); + float tot = 0.0f; + for (int i = 0; i < 8; ++i) tot += part[i]; + const float rs = rsqrt(tot / float(n) + a.eps); + device float* o = xn + (t * a.hc + c) * n; + device const float* w = w_norm + c * n; + for (uint d = tid; d < n; d += 256) o[d] = r[d] * w[d] * rs; +} diff --git a/metal/kernels/gridbar.metal b/metal/kernels/gridbar.metal new file mode 100644 index 00000000..5cd9a0fa --- /dev/null +++ b/metal/kernels/gridbar.metal @@ -0,0 +1,54 @@ +// metal/kernels/gridbar.metal - feasibility probe for a persistent kernel: phases separated by an in-kernel grid +// barrier (a device atomic counter) instead of dispatch boundaries. Metal does not promise that all threadgroups of +// a grid are resident at once; the probe launches at most one threadgroup per GPU core. +// +// Each phase p: every thread streams its share of chunk p (n uint4), and threadgroup g writes a token value +// (p * 1000 + g) to flag[p][g]; after the barrier, phase p + 1 checks every flag of phase p (written by the OTHER +// threadgroups) and counts mismatches into bad[0]. + +static inline void grid_barrier(device atomic_uint* bar, uint target, ushort tid) { + threadgroup_barrier(mem_flags::mem_device); +#ifdef GB_FENCE + atomic_thread_fence(mem_flags::mem_device, memory_order_seq_cst, thread_scope_device); +#endif + if (tid == 0) { + atomic_fetch_add_explicit(bar, 1u, memory_order_relaxed); + while (atomic_load_explicit(bar, memory_order_relaxed) < target) {} + } + threadgroup_barrier(mem_flags::mem_device); +#ifdef GB_FENCE + atomic_thread_fence(mem_flags::mem_device, memory_order_seq_cst, thread_scope_device); +#endif +} + +kernel void k_phases(device const uint4* src [[buffer(0)]], device uint* out [[buffer(1)]], + device atomic_uint* bar [[buffer(2)]], device volatile uint* flag [[buffer(3)]], + device atomic_uint* bad [[buffer(4)]], constant uint& n [[buffer(5)]], + constant uint& phases [[buffer(6)]], + uint tgpx [[threadgroup_position_in_grid]], uint ntgx [[threadgroups_per_grid]], + ushort tid [[thread_index_in_threadgroup]], uint gid [[thread_position_in_grid]], + uint nt [[threads_per_grid]]) { + const uint g = tgpx, ntg = ntgx; + uint4 acc = 0; + for (uint p = 0; p < phases; ++p) { + if (p > 0 && tid < ntg) { + const uint v = flag[(p - 1) * ntg + tid]; + if (v != (p - 1) * 1000 + tid) atomic_fetch_add_explicit(bad, 1u, memory_order_relaxed); + } + device const uint4* s = src + ulong(p) * n; + for (uint i = gid; i < n; i += nt) acc += s[i]; + if (tid == 0) flag[p * ntg + g] = p * 1000 + g; + grid_barrier(bar, (p + 1) * ntg, tid); + } + out[gid] = acc.x ^ acc.y ^ acc.z ^ acc.w; +} + +// one phase per dispatch, for comparison +kernel void k_phase1(device const uint4* src [[buffer(0)]], device uint* out [[buffer(1)]], + constant uint& n [[buffer(2)]], constant uint& p [[buffer(3)]], + uint gid [[thread_position_in_grid]], uint nt [[threads_per_grid]]) { + uint4 acc = 0; + device const uint4* s = src + ulong(p) * n; + for (uint i = gid; i < n; i += nt) acc += s[i]; + out[gid] = acc.x ^ acc.y ^ acc.z ^ acc.w; +} diff --git a/metal/kernels/mm_bench.metal b/metal/kernels/mm_bench.metal new file mode 100644 index 00000000..c04659fc --- /dev/null +++ b/metal/kernels/mm_bench.metal @@ -0,0 +1,85 @@ +// metal/kernels/mm_bench.metal - matrix throughput probes (mm_bench.cpp): C[M][N] = A[M][K] . B[N][K]^T, fp32 out. +// mpp_mm Metal 4 MetalPerformancePrimitives matmul2d (the M5's neural accelerators), a TM x TN +// tile of C per threadgroup, K dynamic, A and B straight from device memory +// sg_mm simdgroup_matrix 8x8, a 32 x 32 tile per simdgroup (4 x 4 accumulators), 4 simdgroups +#include +using namespace mpp::tensor_ops; + +struct MmArgs { int M, N, K; }; + +template +kernel void mpp_mm(device T* A [[buffer(0)]], device T* B [[buffer(1)]], device float* C [[buffer(2)]], + constant MmArgs& a [[buffer(3)]], uint3 tg [[threadgroup_position_in_grid]]) { + // extents are (inner, outer): A is M rows of K, B is N rows of K, C is M rows of N + tensor, tensor_inline> tA(A, dextents(a.K, a.M)); + tensor, tensor_inline> tB(B, dextents(a.K, a.N)); + tensor, tensor_inline> tC(C, dextents(a.N, a.M)); + constexpr auto desc = matmul2d_descriptor(TM, TN, dynamic_length_v, false, true, false); + matmul2d> op; + auto mA = tA.slice(0, int(tg.y) * TM); + auto mB = tB.slice(0, int(tg.x) * TN); + auto mC = tC.slice(int(tg.x) * TN, int(tg.y) * TM); + op.run(mA, mB, mC); +} + +#define MPP(T, M, N, S) template [[host_name("mpp_mm_" #T "_" #M "_" #N "_" #S)]] kernel decltype(mpp_mm) mpp_mm; +MPP(half, 64, 32, 4) MPP(half, 64, 64, 4) MPP(half, 128, 64, 4) MPP(half, 32, 64, 4) MPP(half, 64, 128, 4) +MPP(half, 16, 64, 2) MPP(half, 128, 128, 4) +MPP(half, 64, 16, 2) MPP(half, 64, 16, 4) MPP(half, 128, 16, 4) MPP(half, 128, 32, 4) MPP(half, 64, 32, 2) MPP(half, 32, 16, 2) +MPP(half, 32, 32, 2) MPP(half, 16, 32, 1) MPP(half, 16, 16, 1) MPP(half, 128, 48, 4) MPP(half, 64, 48, 4) +MPP(float, 64, 32, 4) MPP(float, 64, 64, 4) MPP(float, 128, 64, 4) +MPP(bfloat, 64, 64, 4) MPP(bfloat, 128, 64, 4) + +// simdgroup_matrix: threadgroup tile 64 x 64 (4 simdgroups x 32 x 32), K in steps of 8, operands from device memory +template +kernel void sg_mm(device const T* A [[buffer(0)]], device const T* B [[buffer(1)]], device float* C [[buffer(2)]], + constant MmArgs& a [[buffer(3)]], uint3 tg [[threadgroup_position_in_grid]], + ushort sg [[simdgroup_index_in_threadgroup]]) { + const int m0 = int(tg.y) * 64 + (sg >> 1) * 32, n0 = int(tg.x) * 64 + (sg & 1) * 32; + simdgroup_matrix acc[4][4]; + for (int i = 0; i < 4; ++i) + for (int j = 0; j < 4; ++j) acc[i][j] = make_filled_simdgroup_matrix(0.0f); + for (int k = 0; k < a.K; k += 8) { + simdgroup_matrix ma[4], mb[4]; + for (int i = 0; i < 4; ++i) simdgroup_load(ma[i], A + (m0 + 8 * i) * a.K + k, a.K); + for (int j = 0; j < 4; ++j) simdgroup_load(mb[j], B + (n0 + 8 * j) * a.K + k, a.K, ulong2(0, 0), true); + for (int i = 0; i < 4; ++i) + for (int j = 0; j < 4; ++j) simdgroup_multiply_accumulate(acc[i][j], ma[i], mb[j], acc[i][j]); + } + for (int i = 0; i < 4; ++i) + for (int j = 0; j < 4; ++j) simdgroup_store(acc[i][j], C + (m0 + 8 * i) * a.N + n0 + 8 * j, a.N); +} +template [[host_name("sg_mm_half")]] kernel decltype(sg_mm) sg_mm; +template [[host_name("sg_mm_float")]] kernel decltype(sg_mm) sg_mm; + + +// the element layout of single-simdgroup matmul2d cooperative tensors (right input, left input, destination) for a +// TM x TN x TK descriptor: out[((which * 32 + lane) * 128 + i) * 4 + (0, 1)] = the two indices, [2] = capacity +template +kernel void coop_layout(device int* out [[buffer(0)]], ushort lane [[thread_index_in_simdgroup]]) { + constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false, matmul2d_descriptor::mode::multiply_accumulate); + matmul2d op; + auto r = op.template get_right_input_cooperative_tensor(); + auto l = op.template get_left_input_cooperative_tensor(); + auto dd = op.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t, + __tensor_ops_detail::__remove_addrspace_t, float>(); + for (uint16_t i = 0; i < dd.get_capacity() && i < 128; ++i) { + auto ix = dd.get_multidimensional_index(i); + device int* o = out + ((2 * 32 + lane) * 128 + i) * 4; + o[0] = ix[0]; o[1] = ix[1]; o[2] = dd.get_capacity(); + } + for (uint16_t i = 0; i < r.get_capacity() && i < 128; ++i) { + auto ix = r.get_multidimensional_index(i); + device int* o = out + ((0 * 32 + lane) * 128 + i) * 4; + o[0] = ix[0]; o[1] = ix[1]; o[2] = r.get_capacity(); + } + for (uint16_t i = 0; i < l.get_capacity() && i < 128; ++i) { + auto ix = l.get_multidimensional_index(i); + device int* o = out + ((1 * 32 + lane) * 128 + i) * 4; + o[0] = ix[0]; o[1] = ix[1]; o[2] = l.get_capacity(); + } +} +template [[host_name("coop_layout_16_32_16")]] kernel decltype(coop_layout<16, 32, 16>) coop_layout<16, 32, 16>; +template [[host_name("coop_layout_32_32_16")]] kernel decltype(coop_layout<32, 32, 16>) coop_layout<32, 32, 16>; +template [[host_name("coop_layout_16_64_32")]] kernel decltype(coop_layout<16, 64, 32>) coop_layout<16, 64, 32>; +template [[host_name("coop_layout_16_32_32")]] kernel decltype(coop_layout<16, 32, 32>) coop_layout<16, 32, 32>; diff --git a/metal/kernels/mma.metal b/metal/kernels/mma.metal new file mode 100644 index 00000000..9bbb27e2 --- /dev/null +++ b/metal/kernels/mma.metal @@ -0,0 +1,216 @@ +// metal/kernels/mma.metal - a GEMV for windows of tokens on the simdgroup matrix units (after quant/units.metal). +// +// y[t][r] = W[r] . x[t] for NTOK (1..8) tokens: each simdgroup owns 8 rows; the K axis runs in chunks of 128. Per +// chunk the simdgroup decodes its 8 x 128 weights - with ref_quant's arithmetic, so a tile element is exactly the +// dequantized weight - into threadgroup memory, then 16 simdgroup_multiply_accumulate steps take A = the 8 x 8 weight +// tile and B = the 8 (k) x 8 (token) slice of x, loaded transposed straight from device memory (x has 8 rows: the +// tokens past the window are padding, and an output column depends only on its own token). +// +// Activations are the raw plane (no pre-scaling); n_in must be a multiple of 128. Every format's units sit inside +// one 128-wide chunk: Q4_K/Q5_K units span 64 positions, Q6_K units 128, the others are contiguous. + +// ---- decoders to actual weights: w[UNIT] and the chunk offsets of its two halves (p0: w[0..H), p1: w[H..UNIT)) ---- +template struct DW { + // generic: w = s * q (quant.metal's deq is ref_quant's order: the scale times the code), contiguous + static inline void run(device const uchar* row, int u, int k0, thread float* w, thread int& p0, thread int& p1, + threadgroup const uint* tab) { + constexpr int UNIT = fmt::UNIT, UPB = fmt::QK / UNIT; + float q[UNIT]; + const float s = deq(row + (u / UPB) * fmt::BB, u % UPB, q, tab); + for (int j = 0; j < UNIT; ++j) w[j] = q[j] * s; + p0 = u * UNIT - k0; + p1 = p0 + UNIT / 2; + } +}; +// Q2_0: (code - 1) * d +template <> struct DW { + static inline void run(device const uchar* row, int u, int k0, thread float* w, thread int& p0, thread int& p1, + threadgroup const uint*) { + device const uchar* b = row + (u >> 2) * 18; + device const ushort* p = (device const ushort*)(b + 2 + 4 * (u & 3)); + const ushort a = p[0], c = p[1]; + const float d = rdh(b); + for (int j = 0; j < 8; ++j) { + w[j] = float(int((a >> (2 * j)) & 3) - 1) * d; + w[8 + j] = float(int((c >> (2 * j)) & 3) - 1) * d; + } + p0 = 16 * u - k0; + p1 = p0 + 8; + } +}; +template <> struct DW { + static inline void run(device const uchar* row, int u, int k0, thread float* w, thread int& p0, thread int& p1, + threadgroup const uint* tab) { + device const uchar* b = row + u * 24; + float q[32]; + const float d = deq(b, 0, q, tab), m = rdh(b + 2); + for (int j = 0; j < 32; ++j) w[j] = q[j] * d + m; + p0 = 32 * u - k0; + p1 = p0 + 16; + } +}; +template <> struct DW { + static inline void run(device const uchar* row, int u, int k0, thread float* w, thread int& p0, thread int& p1, + threadgroup const uint*) { + device const float* p = (device const float*)(row + 64 * u); + for (int j = 0; j < 16; ++j) w[j] = p[j]; + p0 = 16 * u - k0; + p1 = p0 + 8; + } +}; +template <> struct DW { + static inline void run(device const uchar* row, int u, int k0, thread float* w, thread int& p0, thread int& p1, + threadgroup const uint*) { + device const uint4* p = (device const uint4*)(row + 32 * u); + const uint4 a = p[0], c = p[1]; + const uint v[8] = {a.x, a.y, a.z, a.w, c.x, c.y, c.z, c.w}; + for (int k = 0; k < 8; ++k) { + w[2 * k] = as_type(v[k] << 16); + w[2 * k + 1] = as_type(v[k] & 0xFFFF0000u); + } + p0 = 16 * u - k0; + p1 = p0 + 8; + } +}; +// Q4_K / Q5_K: d1 * code - m1 (ref: d * sc, dmin * m), runs at 256b + 64c + 16m and + 32 +template <> struct DW { + static inline void run(device const uchar* row, int u, int k0, thread float* w, thread int& p0, thread int& p1, + threadgroup const uint*) { + device const uchar* b = row + (u >> 3) * 144; + const int c = (u >> 1) & 3, m = u & 1; + const float d = rdh(b), dm = rdh(b + 2); + float s1, m1, s2, m2; + scale_min_k4(2 * c, b + 4, s1, m1); + scale_min_k4(2 * c + 1, b + 4, s2, m2); + const float d1 = d * s1, mm1 = dm * m1, d2 = d * s2, mm2 = dm * m2; + device const uchar* q = b + 16 + 32 * c + 16 * m; + for (int j = 0; j < 16; ++j) { + w[j] = d1 * float(q[j] & 15) - mm1; + w[16 + j] = d2 * float(q[j] >> 4) - mm2; + } + p0 = 256 * (u >> 3) + 64 * c + 16 * m - k0; + p1 = p0 + 32; + } +}; +template <> struct DW { + static inline void run(device const uchar* row, int u, int k0, thread float* w, thread int& p0, thread int& p1, + threadgroup const uint*) { + device const uchar* b = row + (u >> 3) * 176; + const int c = (u >> 1) & 3, m = u & 1; + const float d = rdh(b), dm = rdh(b + 2); + float s1, m1, s2, m2; + scale_min_k4(2 * c, b + 4, s1, m1); + scale_min_k4(2 * c + 1, b + 4, s2, m2); + const float d1 = d * s1, mm1 = dm * m1, d2 = d * s2, mm2 = dm * m2; + device const uchar* ql = b + 48 + 32 * c + 16 * m; + device const uchar* qh = b + 16 + 16 * m; + const uchar u1 = uchar(1 << (2 * c)), u2 = uchar(2 << (2 * c)); + for (int j = 0; j < 16; ++j) { + w[j] = d1 * float((ql[j] & 15) + ((qh[j] & u1) ? 16 : 0)) - mm1; + w[16 + j] = d2 * float((ql[j] >> 4) + ((qh[j] & u2) ? 16 : 0)) - mm2; + } + p0 = 256 * (u >> 3) + 64 * c + 16 * m - k0; + p1 = p0 + 32; + } +}; +// Q6_K: d * sc * (code - 32), runs at 256b + 128n + 32p + 16m and + 64 +template <> struct DW { + static inline void run(device const uchar* row, int u, int k0, thread float* w, thread int& p0, thread int& p1, + threadgroup const uint*) { + device const uchar* b = row + (u >> 3) * 210; + const int n = (u >> 2) & 1, m = (u >> 1) & 1, p = u & 1; + device const uchar* ql = b + 64 * n + 32 * p + 16 * m; + device const uchar* qh = b + 128 + 32 * n + 16 * m; + device const char* sc = (device const char*)(b + 192); + const float d = rdh(b + 208); + const float ds1 = d * float(sc[8 * n + m + 2 * p]), ds2 = d * float(sc[8 * n + m + 2 * p + 4]); + for (int j = 0; j < 16; ++j) { + const int c1 = int((ql[j] & 15) | (((qh[j] >> (2 * p)) & 3) << 4)) - 32; + const int c2 = int((ql[j] >> 4) | (((qh[j] >> (2 * p + 4)) & 3) << 4)) - 32; + w[j] = ds1 * float(c1); + w[16 + j] = ds2 * float(c2); + } + p0 = 256 * (u >> 3) + 128 * n + 32 * p + 16 * m - k0; + p1 = p0 + 64; + } +}; +// Q3_K: d_all * (sc - 32) * (code - (hbit ? 0 : 4)), contiguous 32 +template <> struct DW { + static inline void run(device const uchar* row, int u, int k0, thread float* w, thread int& p0, thread int& p1, + threadgroup const uint*) { + device const uchar* b = row + (u >> 3) * 110; + const int n = (u >> 2) & 1, j = u & 3; + device const uchar* q = b + 32 + 32 * n; + device const uchar* hm = b; + device const uchar* s = b + 96; + const int i1 = 8 * n + 2 * j, i2 = i1 + 1; + const int l1 = (i1 < 8 ? s[i1] & 0xF : s[i1 - 8] >> 4) | (((s[8 + (i1 & 3)] >> (2 * (i1 >> 2))) & 3) << 4); + const int l2 = (i2 < 8 ? s[i2] & 0xF : s[i2 - 8] >> 4) | (((s[8 + (i2 & 3)] >> (2 * (i2 >> 2))) & 3) << 4); + const float d = rdh(b + 108); + const float dl1 = d * float(l1 - 32), dl2 = d * float(l2 - 32); + const uchar hb = uchar(1 << (4 * n + j)); + for (int l = 0; l < 16; ++l) { + w[l] = dl1 * float(int((q[l] >> (2 * j)) & 3) - ((hm[l] & hb) ? 0 : 4)); + w[16 + l] = dl2 * float(int((q[l + 16] >> (2 * j)) & 3) - ((hm[l + 16] & hb) ? 0 : 4)); + } + p0 = 32 * u - k0; + p1 = p0 + 16; + } +}; + +struct MmaArgs { + uint n_in; + uint n_out; + uint row_bytes; + uint x_stride; // floats between the 8 token rows of x + uint y_stride; +}; +constant int MMA_NTOK [[function_constant(4)]]; + +template +kernel void gemv_mma(device const uchar* W [[buffer(0)]], device const float* x [[buffer(1)]], + device float* y [[buffer(2)]], constant MmaArgs& a [[buffer(3)]], + uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int UNIT = fmt::UNIT, UPC = 128 / UNIT, H = UNIT / 2; + threadgroup float wt[SG][8 * 128]; + threadgroup float ct[SG][64]; + threadgroup uint tab[fmt::TAB]; + load_tab(tab, tid, SG * 32); + threadgroup_barrier(mem_flags::mem_threadgroup); + const int row0 = (int(tg.x) * SG + sg) * 8; + simdgroup_float8x8 C = make_filled_simdgroup_matrix(0.0f); + threadgroup float* w8 = wt[sg]; + for (int k0 = 0; k0 < int(a.n_in); k0 += 128) { + for (int it = lane; it < 8 * UPC; it += 32) { + const int r = it / UPC, uu = it - r * UPC; + const int rr = min(row0 + r, int(a.n_out) - 1); + float w[UNIT]; + int p0, p1; + DW::run(W + ulong(rr) * a.row_bytes, k0 / UNIT + uu, k0, w, p0, p1, tab); + for (int j = 0; j < H; ++j) { + w8[r * 128 + p0 + j] = w[j]; + w8[r * 128 + p1 + j] = w[H + j]; + } + } + simdgroup_barrier(mem_flags::mem_threadgroup); + for (int k8 = 0; k8 < 128; k8 += 8) { + simdgroup_float8x8 A, B; + simdgroup_load(A, w8 + k8, 128); + simdgroup_load(B, x + k0 + k8, a.x_stride, ulong2(0, 0), true); + simdgroup_multiply_accumulate(C, A, B, C); + } + simdgroup_barrier(mem_flags::mem_threadgroup); + } + simdgroup_store(C, ct[sg], 8); + simdgroup_barrier(mem_flags::mem_threadgroup); + for (int e = lane; e < 64; e += 32) { + const int r = e >> 3, t = e & 7; + if (t < MMA_NTOK && row0 + r < int(a.n_out)) y[t * int(a.y_stride) + row0 + r] = ct[sg][e]; + } +} + +#define MM(F, S) template [[host_name("gemv_mma_" #F "_" #S)]] kernel decltype(gemv_mma) gemv_mma; +#define MM_SET(F) MM(F, 1) MM(F, 2) MM(F, 4) +MM_SET(T_BF16) MM_SET(T_Q8_0) MM_SET(T_Q4_0) MM_SET(T_Q5_0) MM_SET(T_IQ4_NL) MM_SET(T_IQ4_XS) MM_SET(T_Q2_0) +MM_SET(T_IQ3_S) MM_SET(T_Q3_K) MM_SET(T_Q4_K) MM_SET(T_Q5_K) MM_SET(T_Q6_K) diff --git a/metal/kernels/moe.metal b/metal/kernels/moe.metal new file mode 100644 index 00000000..bb8fdbbc --- /dev/null +++ b/metal/kernels/moe.metal @@ -0,0 +1,336 @@ +// metal/kernels/moe.metal - routed experts of one layer for a verify window of 1..8 tokens, grouped by expert: +// +// moe_plan one threadgroup: the window's top-k ids -> groups (distinct experts, by id) with their entries +// (token, weight), each (token, k)'s entry index, and the indirect grid sizes of the next two kernels. +// Deterministic (no atomics). +// moe_gu per group, a block of FFN rows: gate and up rows read once, applied to every entry of the group +// (the shared input x is read from cache), h = silu(gate) * up per entry. +// moe_down per group, a block of output rows: ye[entry] = weight * (down . h[entry]). +// moe_combine y[token] = sum over k of ye[entry(token, k)], in k order. +// +// The plan is one int buffer (see P_* below). Expert addressing: MoeArgs (a pack blob or the GGUF tensors): +// [gate rows | up rows | down rows] in GGUF blocks (tools/iq_pack.py's experts.bin layout). + +#define P_NG 0 +#define P_IGU 4 +#define P_IDN 8 +#define P_MAXE 128 +#define P_GEXP 16 +#define P_GSTART (P_GEXP + P_MAXE) +#define P_ETOK (P_GSTART + P_MAXE + 4) +#define P_EW (P_ETOK + P_MAXE) +#define P_TOKENT (P_EW + P_MAXE) +#define P_INTS (P_TOKENT + P_MAXE) + +// Expert e's matrices: gate at W + gate_off + e * gu_stride, up at W + up_off + e * gu_stride, down at +// W + down_off + e * d_stride (a pack's blobs: gate_off 0, strides = the blob; a GGUF: the three tensors). +struct MoeArgs { + ulong gate_off; + ulong up_off; + ulong down_off; + ulong gu_stride; + ulong d_stride; + uint gu_row; // bytes per gate/up row + uint d_row; // bytes per down row + uint n_embd; + uint n_ff; + uint n_tok; + uint topk; + uint n_expert; + uint gx_gu; // threadgroups along the rows for moe_gu (n_ff / rows per threadgroup) + uint gx_dn; // ... for moe_down (n_embd / rows per threadgroup) + uint pad; +}; + +// The SSD-streaming arena (metal/src/engine/stream.cpp): with function constant 20 set, expert e of the layer lies in +// an arena slot, smap[e] = (chunk << 28) | its 16 KiB page in that chunk; the chunks are W (buffer 0) and buffers 7..9 +// (gate_off / up_off / down_off are then offsets inside the slot). The same block is in moe_mm.metal. +#ifndef STRATA_ARENA_METAL +#define STRATA_ARENA_METAL +constant bool kArenaFc [[function_constant(20)]]; +constant bool kArena = is_function_constant_defined(kArenaFc) && kArenaFc; +static inline device const uchar* arena_slot(uint v, device const uchar* W, device const uchar* W1, device const uchar* W2, + device const uchar* W3) { + const uint c = v >> 28; + device const uchar* b = c == 0 ? W : (c == 1 ? W1 : (c == 2 ? W2 : W3)); + return b + (ulong)(v & 0x0FFFFFFFu) * 16384ul; +} +#endif + +static inline void plan_body(device const int* ids, device const float* w, device int* plan, constant MoeArgs& a, + ushort tid, ushort nth, ushort sg, ushort lane, threadgroup int* s_grp, + threadgroup int* s_ent) { + const int ne = int(a.n_tok * a.topk); + // one thread per expert id (nth == n_expert, at most 1024) + const int e = tid; + int cnt = 0; + if (e < int(a.n_expert)) + for (int i = 0; i < ne; ++i) cnt += ids[i] == e; + const int has = cnt > 0; + const int pg = simd_prefix_exclusive_sum(has), pe = simd_prefix_exclusive_sum(cnt); + if (lane == 31) { s_grp[sg] = pg + has; s_ent[sg] = pe + cnt; } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid == 0) { + int og = 0, oe = 0; + const int nsg = (nth + 31) / 32; + for (int i = 0; i < nsg; ++i) { + const int g = s_grp[i], n = s_ent[i]; + s_grp[i] = og; + s_ent[i] = oe; + og += g; + oe += n; + } + plan[P_NG] = og; + plan[P_IGU] = int(a.gx_gu); plan[P_IGU + 1] = og; plan[P_IGU + 2] = 1; + plan[P_IDN] = int(a.gx_dn); plan[P_IDN + 1] = og; plan[P_IDN + 2] = 1; + plan[P_GSTART + og] = oe; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (has) { + const int gi = s_grp[sg] + pg, off = s_ent[sg] + pe; + plan[P_GEXP + gi] = e; + plan[P_GSTART + gi] = off; + int j = 0; + for (int i = 0; i < ne; ++i) + if (ids[i] == e) { + plan[P_ETOK + off + j] = i / int(a.topk); + plan[P_EW + off + j] = as_type(w[i]); + plan[P_TOKENT + i] = off + j; + ++j; + } + } +} + +kernel void moe_plan(device const int* ids [[buffer(0)]], device const float* w [[buffer(1)]], + device int* plan [[buffer(2)]], constant MoeArgs& a [[buffer(3)]], + ushort tid [[thread_position_in_threadgroup]], ushort nth [[threads_per_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + threadgroup int s_grp[32], s_ent[32]; + plan_body(ids, w, plan, a, tid, nth, sg, lane, s_grp, s_ent); +} + +// The router's tail for the window, then the plan, in one threadgroup of n_expert (512) threads: simdgroup t routes +// token t exactly as native_router.cu (pinned llama.cpp topk-moe): softmax over the 512 logits, top 10 by +// probability (equal values: the lower expert index), weights = p / max(sum of the selected, 2^-14), the sum taken +// by winning lane in selection order and reduced with the same xor tree. +kernel void moe_route(device const float* logits [[buffer(0)]], device int* ids [[buffer(1)]], + device float* w [[buffer(2)]], device int* plan [[buffer(3)]], constant MoeArgs& a [[buffer(4)]], + ushort tid [[thread_position_in_threadgroup]], ushort nth [[threads_per_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + threadgroup int s_grp[32], s_ent[32]; + if (sg < a.n_tok) { + device const float* l = logits + sg * 512; + float v[16]; + for (int i = 0; i < 16; ++i) v[i] = l[lane + 32 * i]; + float mx = -INFINITY; + for (int i = 0; i < 16; ++i) mx = max(mx, v[i]); + for (ushort m = 16; m > 0; m >>= 1) mx = max(mx, simd_shuffle_xor(mx, m)); + float sum = 0.0f; + for (int i = 0; i < 16; ++i) { + v[i] = exp(v[i] - mx); + sum += v[i]; + } + for (ushort m = 16; m > 0; m >>= 1) sum += simd_shuffle_xor(sum, m); + const float rcp = 1.0f / sum; + for (int i = 0; i < 16; ++i) { + v[i] *= rcp; + if (isnan(v[i])) v[i] = -FLT_MAX; + } + float selected = 0.0f, ssum = 0.0f; + for (int rank = 0; rank < 10; ++rank) { + float best = v[0]; + int ex = lane; + for (int i = 1; i < 16; ++i) + if (v[i] > best) { best = v[i]; ex = lane + 32 * i; } + for (ushort m = 16; m > 0; m >>= 1) { + const float ob = simd_shuffle_xor(best, m); + const int oe = simd_shuffle_xor(ex, m); + if (ob > best || (ob == best && oe < ex)) { best = ob; ex = oe; } + } + if ((ex & 31) == lane) { + v[ex / 32] = -INFINITY; + ids[sg * 10 + rank] = ex; + ssum += best; + } + if (rank == lane) selected = best; + } + for (ushort m = 16; m > 0; m >>= 1) ssum += simd_shuffle_xor(ssum, m); + ssum = max(ssum, 6.103515625e-5f); + const float inv = 1.0f / ssum; + if (lane < 10) w[sg * 10 + lane] = selected * inv; + } + threadgroup_barrier(mem_flags::mem_device); + plan_body(ids, w, plan, a, tid, nth, sg, lane, s_grp, s_ent); +} + +// ---- gate + up + SwiGLU ------------------------------------------------------------------------------------------- +// One pass over a group's rows for all its NE entries (1..8: an expert appears once per token); NE is uniform per +// threadgroup, so the kernel switches once into a body specialised for it. +template +static inline void gu_body(device const uchar* g0, device const uchar* u0, device const float* x, + device const float* xs16, device float* h, device const int* etok, int c, int row0, int li, + constant MoeArgs& a, threadgroup const uint* tab) { + constexpr int UNIT = fmt::UNIT; + float ag[NR][NE], au[NR][NE]; + for (int r = 0; r < NR; ++r) + for (int t = 0; t < NE; ++t) ag[r][t] = au[r][t] = 0.0f; + const int U = int(a.n_embd) / UNIT; + for (int u = li; u < U; u += LPR) { + float qg[NR][UNIT], qu[NR][UNIT]; + float4 cg[NR], cu[NR]; + for (int r = 0; r < NR; ++r) { + Dec::run(g0 + r * a.gu_row, u, qg[r], cg[r], tab); + Dec::run(u0 + r * a.gu_row, u, qu[r], cu[r], tab); + } + for (int t = 0; t < NE; ++t) { + const int tok = etok[t]; + float xs[UNIT], xsum[2]; + X::load(x + tok * int(a.n_embd), xs16 + tok * int(a.n_embd / 16), u, xs, xsum); + for (int r = 0; r < NR; ++r) { + ag[r][t] += unit_combine(qg[r], cg[r], xs, xsum); + au[r][t] += unit_combine(qu[r], cu[r], xs, xsum); + } + } + } + for (int r = 0; r < NR; ++r) + for (int t = 0; t < NE; ++t) { + const float gv = lane_sum(ag[r][t]), uv = lane_sum(au[r][t]); + if (li == 0) h[(c + t) * int(a.n_ff) + row0 + r] = gv / (1.0f + exp(-gv)) * uv; + } +} + +// bench probe (function constant 22): 1 = no table load (wrong values for the i-quants) +constant int MOE_PROBE [[function_constant(22)]]; +constant int moe_probe = is_function_constant_defined(MOE_PROBE) ? MOE_PROBE : 0; + +template +kernel void moe_gu(device const uchar* W [[buffer(0)]], device const float* x [[buffer(1)]], + device float* h [[buffer(2)]], device const int* plan [[buffer(3)]], + constant MoeArgs& a [[buffer(4)]], device const float* xs16 [[buffer(5)]], + device const uint* smap [[buffer(6)]], device const uchar* W1 [[buffer(7)]], + device const uchar* W2 [[buffer(8)]], device const uchar* W3 [[buffer(9)]], + uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int RG = 32 / LPR; + threadgroup uint tab[fmt::TAB]; + if (moe_probe != 1) { + load_tab(tab, tid, SG * 32); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + const int g = int(tg.y); + if (g >= plan[P_NG]) return; + const int li = lane % LPR; + const int row0 = ((int(tg.x) * SG + sg) * RG + lane / LPR) * NR; + const ulong ex = (ulong)plan[P_GEXP + g]; + const int c = plan[P_GSTART + g], ne = plan[P_GSTART + g + 1] - c; + device const int* etok = plan + P_ETOK + c; + device const uchar* E = kArena ? arena_slot(smap[ex], W, W1, W2, W3) : W + ex * a.gu_stride; + device const uchar* g0 = E + a.gate_off + (ulong)row0 * a.gu_row; + device const uchar* u0 = E + a.up_off + (ulong)row0 * a.gu_row; + switch (ne) { + case 1: gu_body(g0, u0, x, xs16, h, etok, c, row0, li, a, tab); break; + case 2: gu_body(g0, u0, x, xs16, h, etok, c, row0, li, a, tab); break; + case 3: gu_body(g0, u0, x, xs16, h, etok, c, row0, li, a, tab); break; + case 4: gu_body(g0, u0, x, xs16, h, etok, c, row0, li, a, tab); break; + default: + for (int k = 0; k < ne; k += 4) { + const int m = min(4, ne - k); + if (m == 4) gu_body(g0, u0, x, xs16, h, etok + k, c + k, row0, li, a, tab); + else if (m == 3) gu_body(g0, u0, x, xs16, h, etok + k, c + k, row0, li, a, tab); + else if (m == 2) gu_body(g0, u0, x, xs16, h, etok + k, c + k, row0, li, a, tab); + else gu_body(g0, u0, x, xs16, h, etok + k, c + k, row0, li, a, tab); + } + } +} + +// ---- down --------------------------------------------------------------------------------------------------------- +template +static inline void dn_body(device const uchar* d0, device const float* h, device const float* hs16, device float* ye, + device const int* plan, int c, int row0, int li, constant MoeArgs& a, + threadgroup const uint* tab) { + constexpr int UNIT = fmt::UNIT; + float ac[NR][NE]; + for (int r = 0; r < NR; ++r) + for (int t = 0; t < NE; ++t) ac[r][t] = 0.0f; + const int U = int(a.n_ff) / UNIT; + for (int u = li; u < U; u += LPR) { + float q[NR][UNIT]; + float4 sc[NR]; + for (int r = 0; r < NR; ++r) Dec::run(d0 + r * a.d_row, u, q[r], sc[r], tab); + for (int t = 0; t < NE; ++t) { + float xs[UNIT], xsum[2]; + X::load(h + (c + t) * int(a.n_ff), hs16 + (c + t) * int(a.n_ff / 16), u, xs, xsum); + for (int r = 0; r < NR; ++r) ac[r][t] += unit_combine(q[r], sc[r], xs, xsum); + } + } + for (int r = 0; r < NR; ++r) + for (int t = 0; t < NE; ++t) { + const float v = lane_sum(ac[r][t]); + if (li == 0) ye[(c + t) * int(a.n_embd) + row0 + r] = as_type(plan[P_EW + c + t]) * v; + } +} + +template +kernel void moe_down(device const uchar* W [[buffer(0)]], device const float* h [[buffer(1)]], + device float* ye [[buffer(2)]], device const int* plan [[buffer(3)]], + constant MoeArgs& a [[buffer(4)]], device const float* hs16 [[buffer(5)]], + device const uint* smap [[buffer(6)]], device const uchar* W1 [[buffer(7)]], + device const uchar* W2 [[buffer(8)]], device const uchar* W3 [[buffer(9)]], + uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int RG = 32 / LPR; + threadgroup uint tab[fmt::TAB]; + load_tab(tab, tid, SG * 32); + threadgroup_barrier(mem_flags::mem_threadgroup); + const int g = int(tg.y); + if (g >= plan[P_NG]) return; + const int li = lane % LPR; + const int row0 = ((int(tg.x) * SG + sg) * RG + lane / LPR) * NR; + const ulong ex = (ulong)plan[P_GEXP + g]; + const int c = plan[P_GSTART + g], ne = plan[P_GSTART + g + 1] - c; + device const uchar* d0 = (kArena ? arena_slot(smap[ex], W, W1, W2, W3) : W + ex * a.d_stride) + a.down_off + (ulong)row0 * a.d_row; + switch (ne) { + case 1: dn_body(d0, h, hs16, ye, plan, c, row0, li, a, tab); break; + case 2: dn_body(d0, h, hs16, ye, plan, c, row0, li, a, tab); break; + case 3: dn_body(d0, h, hs16, ye, plan, c, row0, li, a, tab); break; + case 4: dn_body(d0, h, hs16, ye, plan, c, row0, li, a, tab); break; + default: + for (int k = 0; k < ne; k += 4) { + const int m = min(4, ne - k); + if (m == 4) dn_body(d0, h, hs16, ye, plan, c + k, row0, li, a, tab); + else if (m == 3) dn_body(d0, h, hs16, ye, plan, c + k, row0, li, a, tab); + else if (m == 2) dn_body(d0, h, hs16, ye, plan, c + k, row0, li, a, tab); + else dn_body(d0, h, hs16, ye, plan, c + k, row0, li, a, tab); + } + } +} + +kernel void moe_combine(device const float* ye [[buffer(0)]], device float* y [[buffer(1)]], + device const int* plan [[buffer(2)]], constant MoeArgs& a [[buffer(3)]], + uint gid [[thread_position_in_grid]]) { + const uint t = gid / a.n_embd, k = gid % a.n_embd; + if (t >= a.n_tok) return; + float s = 0.0f; + for (uint j = 0; j < a.topk; ++j) s += ye[plan[P_TOKENT + t * a.topk + j] * int(a.n_embd) + k]; + y[gid] = s; +} + +// ---- instantiations: moe_gu____, moe_down____ ------------------------------- +#define GU(F, L, R, S) template [[host_name("moe_gu_" #F "_" #L "_" #R "_" #S)]] kernel decltype(moe_gu) moe_gu; +#define DN(F, L, R, S) template [[host_name("moe_down_" #F "_" #L "_" #R "_" #S)]] kernel decltype(moe_down) moe_down; +#define GU_SET(F) GU(F, 32, 1, 4) GU(F, 32, 2, 4) GU(F, 32, 4, 4) GU(F, 32, 2, 2) GU(F, 32, 2, 8) GU(F, 32, 1, 8) \ + GU(F, 16, 1, 4) GU(F, 16, 2, 4) GU(F, 8, 1, 4) GU(F, 8, 2, 4) GU(F, 8, 1, 2) +#define DN_SET(F) DN(F, 8, 1, 4) DN(F, 8, 2, 4) DN(F, 8, 4, 4) DN(F, 8, 1, 8) DN(F, 8, 2, 8) DN(F, 4, 1, 4) DN(F, 4, 2, 4) \ + DN(F, 4, 4, 4) DN(F, 16, 1, 4) DN(F, 16, 2, 4) DN(F, 32, 1, 4) DN(F, 2, 2, 4) +GU_SET(T_Q2_0) +GU_SET(T_IQ3_XXS) +GU_SET(T_IQ2_XXS) +GU_SET(T_IQ2_XS) +GU_SET(T_IQ2_S) +GU_SET(T_IQ3_S) +GU_SET(T_IQ4_XS) // the IQ3_S pack's gate/up in one layer +GU_SET(T_Q4_K) GU_SET(T_Q5_K) GU_SET(T_Q6_K) GU_SET(T_Q8_0) // the UD-Q4/5/6_K_XL packs +DN_SET(T_Q5_1) DN_SET(T_Q8_0) +DN_SET(T_Q2_0) +DN_SET(T_Q2_0R) +DN_SET(T_IQ4_NL) diff --git a/metal/kernels/moe_mm.metal b/metal/kernels/moe_mm.metal new file mode 100644 index 00000000..ff28897a --- /dev/null +++ b/metal/kernels/moe_mm.metal @@ -0,0 +1,1089 @@ +// metal/kernels/moe_mm.metal - routed experts for a PROMPT chunk (after quant/units/mma.metal): a grouped GEMM on +// the matrix units through Metal 4's MetalPerformancePrimitives matmul2d (on the M5 its neural accelerators). +// +// Plan (deterministic, three passes): the chunk's T x topk (token, expert) entries are sorted by expert, then by +// entry index; each expert's run is padded to a multiple of TM rows; tile i = (expert, first padded row). +// mm_hist per block of 1024 entries: a histogram of experts -> bcnt[block][expert] +// mm_scan one threadgroup (thread = expert): block offsets, the padded expert offsets, the tile list +// mm_place per block: an entry's padded row = expert offset + earlier blocks' count + rank in its block; +// srt_tok[row] = token (-1 on padding), srt_w[row] = weight, pos[entry] = row +// GEMMs: a threadgroup takes a tile (TM rows of one expert) and TN output rows; per K chunk of TK it converts the +// tile's activations to fp16 and dequantizes TN x TK weights (ref_quant's arithmetic, then rounded to fp16) into +// threadgroup memory, and matmul2d multiplies them, fp32 accumulation. +// mm_gu H[row][f] = silu(x . gate_f) * (x . up_f), fp32, for the n_ff rows +// mm_down YE[row][d] = h . down_d, fp32 +// mm_combine y[t][d] = sum_k w(t, k) * YE[pos(t, k)][d], k in order +// +// The idea of feeding matmul2d tiles of dequantized weights from threadgroup memory follows yibie/strata-mlx's +// tile_matmul (MIT); the code is our own. +#include +using namespace mpp::tensor_ops; + +struct MmPlanArgs { + uint n_ent; // T * topk + uint topk; + uint n_expert; + uint tm; // the tile height (rows of one expert) + uint n_blocks; // ceil(n_ent / 1024) +}; + +// counts per block: bcnt[block * n_expert + e] +kernel void mm_hist(device const int* ids [[buffer(0)]], device uint* bcnt [[buffer(1)]], + constant MmPlanArgs& a [[buffer(2)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + threadgroup atomic_uint h[1024]; + for (uint e = tid; e < a.n_expert; e += 1024) atomic_store_explicit(&h[e], 0u, memory_order_relaxed); + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint i = tg.x * 1024 + tid; + if (i < a.n_ent) atomic_fetch_add_explicit(&h[ids[i]], 1u, memory_order_relaxed); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint e = tid; e < a.n_expert; e += 1024) + bcnt[tg.x * a.n_expert + e] = atomic_load_explicit(&h[e], memory_order_relaxed); +} + +// one threadgroup of n_expert (<= 1024) threads. boff[block][e] = expert e's rows before this block (within e); +// eoff[e] = expert e's first padded row; tiles[i] = (expert, row0); meta[0] = n_tiles, meta[1] = padded rows; +// indirect grids: meta[2..4] = (gx_gu, n_tiles, 1) for the gate/up GEMM, meta[5..7] = (gx_down, n_tiles, 1) for the +// down GEMM (gx_gu in meta[2], gx_down in meta[5] written by the host once), meta[8..10] = (rows, 1, 1) for mm_gather. +kernel void mm_scan(device const uint* bcnt [[buffer(0)]], device uint* boff [[buffer(1)]], + device uint* eoff [[buffer(2)]], device int2* tiles [[buffer(3)]], device uint* meta [[buffer(4)]], + constant MmPlanArgs& a [[buffer(5)]], + ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]]) { + threadgroup uint s_rows[32], s_tiles[32]; + // simdgroups past the launched ones must count 0 (512 threads fill only 16 of the 32 slots) + if (tid < 32) { s_rows[tid] = 0; s_tiles[tid] = 0; } + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint e = tid; + uint tot = 0; + if (e < a.n_expert) + for (uint b = 0; b < a.n_blocks; ++b) { + boff[b * a.n_expert + e] = tot; + tot += bcnt[b * a.n_expert + e]; + } + const uint nt = (tot + a.tm - 1) / a.tm, rows = nt * a.tm; + const uint pr = simd_prefix_exclusive_sum(rows), pt = simd_prefix_exclusive_sum(nt); + if (lane == 31) { s_rows[sg] = pr + rows; s_tiles[sg] = pt + nt; } + threadgroup_barrier(mem_flags::mem_threadgroup); + uint orow = 0, otile = 0, all_rows = 0, all_tiles = 0; + for (int i = 0; i < 32; ++i) { + if (i < int(sg)) { orow += s_rows[i]; otile += s_tiles[i]; } + all_rows += s_rows[i]; + all_tiles += s_tiles[i]; + } + if (e < a.n_expert) { + const uint r0 = orow + pr, t0 = otile + pt; + eoff[e] = r0; + for (uint k = 0; k < nt; ++k) tiles[t0 + k] = int2(int(e), int(r0 + k * a.tm)); + } + if (tid == 0) { + meta[0] = all_tiles; + meta[1] = all_rows; + meta[3] = all_tiles; // indirect grid of the gate/up GEMM: (meta[2] given, tiles, 1) + meta[4] = 1; + meta[6] = all_tiles; // of the down GEMM: (meta[5] given, tiles, 1) + meta[7] = 1; + meta[8] = all_rows; // of the gather: (rows, 1, 1) + meta[9] = 1; + meta[10] = 1; + } +} + +// grid (n_blocks), 1024 threads. srt_* must be cleared to the padding value (-1 / 0) beforehand by mm_clear. +kernel void mm_place(device const int* ids [[buffer(0)]], device const float* w [[buffer(1)]], + device const uint* boff [[buffer(2)]], device const uint* eoff [[buffer(3)]], + device int* srt_tok [[buffer(4)]], device float* srt_w [[buffer(5)]], device int* pos [[buffer(6)]], + constant MmPlanArgs& a [[buffer(7)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + threadgroup int s_id[1024]; + const uint i = tg.x * 1024 + tid; + const int e = i < a.n_ent ? ids[i] : -1; + s_id[tid] = e; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (i >= a.n_ent) return; + uint rank = 0; + for (uint j = 0; j < tid; ++j) rank += s_id[j] == e; + const uint row = eoff[e] + boff[tg.x * a.n_expert + e] + rank; + srt_tok[row] = int(i / a.topk); + srt_w[row] = w[i]; + pos[i] = int(row); +} + +kernel void mm_clear(device int* srt_tok [[buffer(0)]], constant uint& n [[buffer(1)]], uint gid [[thread_position_in_grid]]) { + if (gid < n) srt_tok[gid] = -1; +} + +// ---- the GEMMs ----------------------------------------------------------------------------------------------------- +// weights of one expert: gate at W + gate_off + e * gu_stride (+ up_off for up), down at W + down_off + e * d_stride +struct MmArgs { + ulong gate_off; + ulong up_off; + ulong down_off; + ulong gu_stride; + ulong d_stride; + uint gu_row; // bytes per gate/up row (n_embd values) + uint d_row; // bytes per down row (n_ff values) + uint n_embd; + uint n_ff; +}; + +// TN x TK weights of `nrow`-strided rows into threadgroup half: thread-strided units of the format +template +static inline void stage_w(device const uchar* w0, uint row_bytes, int k0, threadgroup half* dst, + threadgroup const uint* tab, ushort tid, ushort nth) { + constexpr int UNIT = fmt::UNIT, UPC = TK / UNIT, H = UNIT / 2; + static_assert(TK % UNIT == 0, "the K chunk must hold whole units of the format"); + for (int it = tid; it < TN * UPC; it += nth) { + const int r = it / UPC, uu = it - r * UPC; + float wv[UNIT]; + int p0, p1; + DW::run(w0 + ulong(r) * row_bytes, k0 / UNIT + uu, k0, wv, p0, p1, tab); + for (int j = 0; j < H; ++j) { + dst[r * TK + p0 + j] = half(wv[j]); + dst[r * TK + p1 + j] = half(wv[H + j]); + } + } +} + +template +kernel void mm_gu(device const uchar* W [[buffer(0)]], device const float* x [[buffer(1)]], + device float* H [[buffer(2)]], device const int* srt_tok [[buffer(3)]], + device const int2* tiles [[buffer(4)]], constant MmArgs& a [[buffer(5)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int NTH = SG * 32; + threadgroup half xa[TM * TK]; + threadgroup half wg[TN * TK]; + threadgroup half wu[TN * TK]; + threadgroup uint tab[fmt::TAB]; + threadgroup int tok[TM]; + load_tab(tab, tid, NTH); + const int2 tl = tiles[tg.y]; + const int e = tl.x, row0 = tl.y, f0 = int(tg.x) * TN; + for (int m = tid; m < TM; m += NTH) tok[m] = srt_tok[row0 + m]; + device const uchar* g0 = W + a.gate_off + ulong(e) * a.gu_stride + ulong(f0) * a.gu_row; + device const uchar* u0 = W + a.up_off + ulong(e) * a.gu_stride + ulong(f0) * a.gu_row; + constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false); + matmul2d> op; + tensor, tensor_inline> tA(xa, dextents(TK, TM)); + tensor, tensor_inline> tG(wg, dextents(TK, TN)); + tensor, tensor_inline> tU(wu, dextents(TK, TN)); + auto accg = op.template get_destination_cooperative_tensor(); + auto accu = op.template get_destination_cooperative_tensor(); + for (uint16_t i = 0; i < accg.get_capacity(); ++i) + if (accg.is_valid_element(i)) { accg[i] = 0.0f; accu[i] = 0.0f; } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int k0 = 0; k0 < int(a.n_embd); k0 += TK) { + for (int it = tid; it < TM * TK; it += NTH) { + const int m = it / TK, k = it - m * TK; + xa[it] = tok[m] >= 0 ? half(x[ulong(tok[m]) * a.n_embd + k0 + k]) : half(0.0f); + } + stage_w(g0, a.gu_row, k0, wg, tab, tid, NTH); + stage_w(u0, a.gu_row, k0, wu, tab, tid, NTH); + threadgroup_barrier(mem_flags::mem_threadgroup); + auto pg = op.template get_destination_cooperative_tensor(); + auto pu = op.template get_destination_cooperative_tensor(); + op.run(tA, tG, pg); + op.run(tA, tU, pu); + for (uint16_t i = 0; i < pg.get_capacity(); ++i) + if (pg.is_valid_element(i)) { accg[i] += pg[i]; accu[i] += pu[i]; } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + for (uint16_t i = 0; i < accg.get_capacity(); ++i) + if (accg.is_valid_element(i)) { + const float g = accg[i]; + accg[i] = g / (1.0f + exp(-g)) * accu[i]; + } + tensor, tensor_inline> tH(H, dextents(a.n_ff, 1 << 30)); + accg.store(tH.slice(f0, row0)); +} + +template +kernel void mm_down(device const uchar* W [[buffer(0)]], device const float* H [[buffer(1)]], + device float* YE [[buffer(2)]], device const int2* tiles [[buffer(3)]], + constant MmArgs& a [[buffer(4)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int NTH = SG * 32; + threadgroup half ha[TM * TK]; + threadgroup half wd[TN * TK]; + threadgroup uint tab[fmt::TAB]; + load_tab(tab, tid, NTH); + const int2 tl = tiles[tg.y]; + const int e = tl.x, row0 = tl.y, d0 = int(tg.x) * TN; + device const uchar* w0 = W + a.down_off + ulong(e) * a.d_stride + ulong(d0) * a.d_row; + constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false); + matmul2d> op; + tensor, tensor_inline> tA(ha, dextents(TK, TM)); + tensor, tensor_inline> tW(wd, dextents(TK, TN)); + auto acc = op.template get_destination_cooperative_tensor(); + for (uint16_t i = 0; i < acc.get_capacity(); ++i) + if (acc.is_valid_element(i)) acc[i] = 0.0f; + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int k0 = 0; k0 < int(a.n_ff); k0 += TK) { + for (int it = tid; it < TM * TK; it += NTH) { + const int m = it / TK, k = it - m * TK; + ha[it] = half(H[ulong(row0 + m) * a.n_ff + k0 + k]); + } + stage_w(w0, a.d_row, k0, wd, tab, tid, NTH); + threadgroup_barrier(mem_flags::mem_threadgroup); + auto p = op.template get_destination_cooperative_tensor(); + op.run(tA, tW, p); + for (uint16_t i = 0; i < p.get_capacity(); ++i) + if (p.is_valid_element(i)) acc[i] += p[i]; + threadgroup_barrier(mem_flags::mem_threadgroup); + } + tensor, tensor_inline> tY(YE, dextents(a.n_embd, 1 << 30)); + acc.store(tY.slice(d0, row0)); +} + +// grid (T * n_embd / 256), 256 threads +kernel void mm_combine(device const float* YE [[buffer(0)]], device const int* pos [[buffer(1)]], + device const float* srt_w [[buffer(2)]], device float* y [[buffer(3)]], + constant uint4& a [[buffer(4)]], // (T, n_embd, topk, -) + uint gid [[thread_position_in_grid]]) { + const uint t = gid / a.y, d = gid % a.y; + if (t >= a.x) return; + float s = 0.0f; + for (uint k = 0; k < a.z; ++k) { + const int r = pos[t * a.z + k]; + s = fma(srt_w[r], YE[ulong(r) * a.y + d], s); + } + y[gid] = s; +} + +#define MMGU_(F, M, N, K, S) template [[host_name("mm_gu_" #F "_" #M "_" #N "_" #K "_" #S)]] kernel decltype(mm_gu) mm_gu; +#define MMDN_(F, M, N, K, S) template [[host_name("mm_down_" #F "_" #M "_" #N "_" #K "_" #S)]] kernel decltype(mm_down) mm_down; +#define MMGU(F, M, N, K, S) MMGU_(F, M, N, K, S) +#define MMDN(F, M, N, K, S) MMDN_(F, M, N, K, S) +#define MM_GU_SET(F) MMGU(F, 32, 64, 64, 4) MMGU(F, 64, 64, 64, 4) MMGU(F, 16, 64, 64, 2) MMGU(F, 32, 32, 64, 2) +#define MM_DN_SET(F) MMDN(F, 32, 64, 64, 4) MMDN(F, 64, 64, 64, 4) MMDN(F, 16, 64, 64, 2) MMDN(F, 32, 32, 64, 2) +MM_GU_SET(T_Q2_0) MM_GU_SET(T_IQ3_XXS) MM_GU_SET(T_IQ2_XXS) MM_GU_SET(T_IQ2_XS) MM_GU_SET(T_IQ2_S) MM_GU_SET(T_IQ3_S) +MM_DN_SET(T_Q2_0) MM_DN_SET(T_IQ4_NL) + +// ---- v2: activations gathered once per layer as fp16 rows, read by matmul2d from device memory --------------------- +// mm_gather: XS[row][k] = half(x[srt_tok[row]][k]) (0 on padding rows). grid (rows), 256 threads. +kernel void mm_gather(device const float* x [[buffer(0)]], device const int* srt_tok [[buffer(1)]], + device half* XS [[buffer(2)]], constant uint& n [[buffer(3)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + const int t = srt_tok[tg.x]; + device half* o = XS + ulong(tg.x) * n; + for (uint k = tid; k < n; k += 256) o[k] = t >= 0 ? half(x[ulong(t) * n + k]) : half(0.0f); +} + +// The SSD-streaming arena (as in moe.metal): with function constant 20, expert e's slot is smap[e] in the chunks W, +// W1..W3 (buffers 5..8 of mm_gu2 / mm_down2 / mm_gu3 / mm_down3); gate_off / up_off / down_off are offsets in the slot. +#ifndef STRATA_ARENA_METAL +#define STRATA_ARENA_METAL +constant bool kArenaFc [[function_constant(20)]]; +constant bool kArena = is_function_constant_defined(kArenaFc) && kArenaFc; +static inline device const uchar* arena_slot(uint v, device const uchar* W, device const uchar* W1, device const uchar* W2, + device const uchar* W3) { + const uint c = v >> 28; + device const uchar* b = c == 0 ? W : (c == 1 ? W1 : (c == 2 ? W2 : W3)); + return b + (ulong)(v & 0x0FFFFFFFu) * 16384ul; +} +#endif + +// a probe for the bench (function constant 5): 1 = the weights not decoded (a cheap fill), 2 = no matrix multiply +constant int MM_PROBE [[function_constant(5)]]; +constant int mm_probe = is_function_constant_defined(MM_PROBE) ? MM_PROBE : 0; + +template +kernel void mm_gu2(device const uchar* W [[buffer(0)]], device const half* XS [[buffer(1)]], + device half* HS [[buffer(2)]], device const int2* tiles [[buffer(3)]], constant MmArgs& a [[buffer(4)]], device const uint* smap [[buffer(5)]], + device const uchar* W1 [[buffer(6)]], device const uchar* W2 [[buffer(7)]], device const uchar* W3 [[buffer(8)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int NTH = SG * 32; + threadgroup half wg[TN * TK]; + threadgroup half wu[TN * TK]; + threadgroup float ot[TM * TN]; + threadgroup uint tab[fmt::TAB]; + load_tab(tab, tid, NTH); + const int2 tl = tiles[tg.y]; + const int e = tl.x, row0 = tl.y, f0 = int(tg.x) * TN; + device const uchar* E = kArena ? arena_slot(smap[e], W, W1, W2, W3) : W + ulong(e) * a.gu_stride; + device const uchar* g0 = E + a.gate_off + ulong(f0) * a.gu_row; + device const uchar* u0 = E + a.up_off + ulong(f0) * a.gu_row; + constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false, matmul2d_descriptor::mode::multiply_accumulate); + matmul2d> op; + tensor, tensor_inline> tX((device half*)XS, dextents(a.n_embd, 1 << 30)); + tensor, tensor_inline> tG(wg, dextents(TK, TN)); + tensor, tensor_inline> tU(wu, dextents(TK, TN)); + auto tA = tX.template slice(0, row0); + auto accg = op.template get_destination_cooperative_tensor(); + auto accu = op.template get_destination_cooperative_tensor(); + for (uint16_t i = 0; i < accg.get_capacity(); ++i) + if (accg.is_valid_element(i)) { accg[i] = 0.0f; accu[i] = 0.0f; } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int k0 = 0; k0 < int(a.n_embd); k0 += TK) { + if (mm_probe == 1) { + for (int it = tid; it < TN * TK; it += NTH) { wg[it] = half(k0 & 7); wu[it] = half(it & 7); } + } else { + stage_w(g0, a.gu_row, k0, wg, tab, tid, NTH); + stage_w(u0, a.gu_row, k0, wu, tab, tid, NTH); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + tA = tX.template slice(k0, row0); + if (mm_probe != 2) { + op.run(tA, tG, accg); + op.run(tA, tU, accu); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + for (uint16_t i = 0; i < accg.get_capacity(); ++i) + if (accg.is_valid_element(i)) { + const float g = accg[i]; + accg[i] = g / (1.0f + exp(-g)) * accu[i]; + } + tensor, tensor_inline> tO(ot, dextents(TN, TM)); + accg.store(tO); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int it = tid; it < TM * TN; it += NTH) { + const int m = it / TN, f = it - m * TN; + HS[ulong(row0 + m) * a.n_ff + f0 + f] = half(ot[it]); + } +} + +template +kernel void mm_down2(device const uchar* W [[buffer(0)]], device const half* HS [[buffer(1)]], + device float* YE [[buffer(2)]], device const int2* tiles [[buffer(3)]], + constant MmArgs& a [[buffer(4)]], device const uint* smap [[buffer(5)]], + device const uchar* W1 [[buffer(6)]], device const uchar* W2 [[buffer(7)]], device const uchar* W3 [[buffer(8)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int NTH = SG * 32; + threadgroup half wd[TN * TK]; + threadgroup uint tab[fmt::TAB]; + load_tab(tab, tid, NTH); + const int2 tl = tiles[tg.y]; + const int e = tl.x, row0 = tl.y, d0 = int(tg.x) * TN; + device const uchar* w0 = (kArena ? arena_slot(smap[e], W, W1, W2, W3) : W + ulong(e) * a.d_stride) + a.down_off + ulong(d0) * a.d_row; + constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false, matmul2d_descriptor::mode::multiply_accumulate); + matmul2d> op; + tensor, tensor_inline> tH((device half*)HS, dextents(a.n_ff, 1 << 30)); + tensor, tensor_inline> tW(wd, dextents(TK, TN)); + auto tA = tH.template slice(0, row0); + auto acc = op.template get_destination_cooperative_tensor(); + for (uint16_t i = 0; i < acc.get_capacity(); ++i) + if (acc.is_valid_element(i)) acc[i] = 0.0f; + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int k0 = 0; k0 < int(a.n_ff); k0 += TK) { + stage_w(w0, a.d_row, k0, wd, tab, tid, NTH); + threadgroup_barrier(mem_flags::mem_threadgroup); + tA = tH.template slice(k0, row0); + op.run(tA, tW, acc); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + tensor, tensor_inline> tY(YE, dextents(a.n_embd, 1 << 30)); + acc.store(tY.slice(d0, row0)); +} + +#define MMGU2_(F, M, N, K, S) template [[host_name("mm_gu2_" #F "_" #M "_" #N "_" #K "_" #S)]] kernel decltype(mm_gu2) mm_gu2; +#define MMDN2_(F, M, N, K, S) template [[host_name("mm_down2_" #F "_" #M "_" #N "_" #K "_" #S)]] kernel decltype(mm_down2) mm_down2; +#define MMGU2(F, M, N, K, S) MMGU2_(F, M, N, K, S) +#define MMDN2(F, M, N, K, S) MMDN2_(F, M, N, K, S) +#define MM_GU2_SET(F) MMGU2(F, 32, 64, 32, 2) MMGU2(F, 32, 32, 32, 2) MMGU2(F, 32, 64, 16, 2) MMGU2(F, 64, 32, 16, 2) MMGU2(F, 16, 32, 32, 2) MMGU2(F, 16, 64, 16, 2) MMGU2(F, 16, 128, 32, 4) MMGU2(F, 32, 64, 16, 4) MMGU2(F, 16, 32, 32, 1) MMGU2(F, 16, 64, 32, 4) MMGU2(F, 16, 64, 64, 2) MMGU2(F, 32, 64, 64, 4) MMGU2(F, 64, 64, 64, 4) MMGU2(F, 16, 32, 64, 2) MMGU2(F, 32, 64, 32, 4) MMGU2(F, 64, 64, 32, 4) MMGU2(F, 16, 64, 32, 2) +#define MM_DN2_SET(F) MMDN2(F, 32, 64, 32, 2) MMDN2(F, 32, 32, 32, 2) MMDN2(F, 32, 64, 16, 2) MMDN2(F, 64, 32, 16, 2) MMDN2(F, 16, 32, 32, 2) MMDN2(F, 16, 64, 16, 2) MMDN2(F, 16, 128, 32, 4) MMDN2(F, 32, 64, 16, 4) MMDN2(F, 16, 32, 32, 1) MMDN2(F, 16, 64, 32, 4) MMDN2(F, 16, 64, 64, 2) MMDN2(F, 32, 64, 64, 4) MMDN2(F, 64, 64, 64, 4) MMDN2(F, 16, 32, 64, 2) MMDN2(F, 32, 64, 32, 4) MMDN2(F, 64, 64, 32, 4) MMDN2(F, 16, 64, 32, 2) +#define MM_GU2_U32(F) MMGU2(F, 16, 64, 32, 2) MMGU2(F, 16, 64, 64, 2) MMGU2(F, 32, 64, 32, 2) MMGU2(F, 16, 32, 32, 2) \ + MMGU2(F, 64, 64, 32, 4) +#define MM_DN2_U32(F) MMDN2(F, 16, 64, 32, 2) MMDN2(F, 16, 64, 64, 2) MMDN2(F, 16, 32, 32, 2) MMDN2(F, 32, 32, 32, 2) \ + MMDN2(F, 16, 128, 32, 4) MMDN2(F, 32, 64, 32, 2) MMDN2(F, 64, 64, 32, 4) +// K-quants: the staged K chunk must hold whole units as DW places them (128 wide): TK 128 +#define MM_GU2_KQ(F) MMGU2(F, 16, 32, 128, 2) MMGU2(F, 16, 16, 128, 2) MMGU2(F, 32, 32, 128, 2) MMGU2(F, 16, 32, 128, 4) +MM_GU2_KQ(T_Q4_K) MM_GU2_KQ(T_Q5_K) MM_GU2_KQ(T_Q6_K) MM_GU2_U32(T_Q8_0) MM_DN2_U32(T_Q5_1) MM_DN2_U32(T_Q8_0) +// IQ4_XS (UNIT 32): the K chunk must be >= 32 +MMGU2(T_IQ4_XS, 16, 64, 32, 2) MMGU2(T_IQ4_XS, 16, 64, 64, 2) MMGU2(T_IQ4_XS, 32, 64, 32, 2) MMGU2(T_IQ4_XS, 16, 32, 32, 2) +MMGU2(T_IQ4_XS, 64, 64, 32, 4) +MM_GU2_SET(T_Q2_0) MM_GU2_SET(T_IQ3_XXS) MM_GU2_SET(T_IQ2_XXS) MM_GU2_SET(T_IQ2_XS) MM_GU2_SET(T_IQ2_S) MM_GU2_SET(T_IQ3_S) +MM_DN2_SET(T_Q2_0) +MMDN2(T_IQ4_NL, 16, 64, 32, 2) MMDN2(T_IQ4_NL, 16, 64, 64, 2) MMDN2(T_IQ4_NL, 16, 32, 32, 2) MMDN2(T_IQ4_NL, 32, 32, 32, 2) MMDN2(T_IQ4_NL, 16, 128, 32, 4) + +// ---- v3: the weights decoded straight into matmul2d's right-input cooperative tensor (single-simdgroup scope), +// no threadgroup staging and no barriers in the K loop. Each simdgroup owns TN output rows; a threadgroup SG * TN. +// The right input's element layout (tests/coop_layout): runs of 4 consecutive k at one n, so a lane decodes 4 values +// at a time (W4). Activations: the gathered fp16 rows from device memory. +#ifndef STRATA_COOP_K4 +#define STRATA_COOP_K4 +// function constant 7: the right-input cooperative tensor holds runs of 4 consecutive k at one n per lane (the M5's +// layout; tests/coop_layout). false (the M4: runs of 2 n at one k): every element decoded on its own. +constant bool COOP_K4 [[function_constant(7)]]; +constant bool coop_k4 = is_function_constant_defined(COOP_K4) ? COOP_K4 : true; +#endif +template struct W4; +// the four weights k .. k + 3 (k % 4 == 0) of a row, in quant.metal's deq arithmetic (code * scale in fp32), as fp16 +// the threadgroup forms of quant.metal's field readers (blocks staged in threadgroup memory) +static inline uint rd32(threadgroup const uchar* p) { + threadgroup const ushort* s = (threadgroup const ushort*)p; + return uint(s[0]) | (uint(s[1]) << 16); +} +static inline float rdh(threadgroup const uchar* p) { return float(*(threadgroup const half*)p); } + +static inline half4 w4_signed(uint g, uint s, float sc) { + const uchar4 v = as_type(g); + const float4 q = float4((s & 1) ? -float(v[0]) : float(v[0]), (s & 2) ? -float(v[1]) : float(v[1]), + (s & 4) ? -float(v[2]) : float(v[2]), (s & 8) ? -float(v[3]) : float(v[3])); + return half4(q * sc); +} +template <> struct W4 { // 64 values a block: fp16 d, 16 bytes of 2-bit codes (value v at byte v / 4) + // fp32 math then fp16 (an fp16-math decode was measured slower: 4.2 vs 3.5 ms a layer) + static inline half4 run(device const uchar* row, int k, threadgroup const uint*) { + device const uchar* b = row + (k >> 6) * 18; + const float d = float(*(device const half*)b); + const uint q = b[2 + ((k & 63) >> 2)]; + return half4(float4(float(int(q & 3) - 1), float(int((q >> 2) & 3) - 1), float(int((q >> 4) & 3) - 1), + float(int(q >> 6) - 1)) * d); + } +}; +template <> struct W4 { + static inline half4 run(device const uchar* row, int k, threadgroup const uint* tab) { + device const uchar* b = row + (k >> 8) * 98; + const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2; + const uint aux = rd32(b + 2 + 64 + 4 * ib); + threadgroup const uchar* ks = (threadgroup const uchar*)(tab + 256); + const uint s = ks[(aux >> (7 * l)) & 127]; + const float sc = rdh(b) * (0.5f + float(aux >> 28)) * 0.5f; + return w4_signed(tab[b[2 + 8 * ib + 2 * l + hh]], hh ? s >> 4 : s, sc); + } +}; +template <> struct W4 { + static inline half4 run(device const uchar* row, int k, threadgroup const uint* tab) { + device const uchar* b = row + (k >> 8) * 66; + const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2; + const uint a0 = rd32(b + 2 + 8 * ib), a1 = rd32(b + 2 + 8 * ib + 4); + threadgroup const uchar* ks = (threadgroup const uchar*)(tab + 512); + const uint idx = (a0 >> (8 * l)) & 255, s = ks[(a1 >> (7 * l)) & 127]; + const float sc = rdh(b) * (0.5f + float(a1 >> 28)) * 0.25f; + return w4_signed(tab[2 * idx + hh], hh ? s >> 4 : s, sc); + } +}; +template <> struct W4 { + static inline half4 run(device const uchar* row, int k, threadgroup const uint* tab) { + device const uchar* b = row + (k >> 8) * 74; + const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2; + const uint v = ((device const ushort*)(b + 2))[4 * ib + l]; + threadgroup const uchar* ks = (threadgroup const uchar*)(tab + 1024); + const uint idx = v & 511, s = ks[v >> 9]; + const uint scb = b[66 + ib]; + const float sc = rdh(b) * (0.5f + float((scb >> (4 * (l >> 1))) & 15)) * 0.25f; + return w4_signed(tab[2 * idx + hh], hh ? s >> 4 : s, sc); + } +}; +template <> struct W4 { + static inline half4 run(device const uchar* row, int k, threadgroup const uint* tab) { + device const uchar* b = row + (k >> 8) * 82; + const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2; + const uint qh = b[66 + ib]; + const uint idx = uint(b[2 + 4 * ib + l]) | ((qh << (8 - 2 * l)) & 0x300); + const uint s = b[2 + 32 + 4 * ib + l]; + const uint scb = b[74 + ib]; + const float sc = rdh(b) * (0.5f + float((scb >> (4 * (l >> 1))) & 15)) * 0.25f; + return w4_signed(tab[2 * idx + hh], hh ? s >> 4 : s, sc); + } +}; +template <> struct W4 { + static inline half4 run(device const uchar* row, int k, threadgroup const uint* tab) { + device const uchar* b = row + (k >> 8) * 110; + const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2; + const uint qh = b[66 + ib]; + const uint i = hh ? (uint(b[2 + 8 * ib + 2 * l + 1]) | ((qh << (7 - 2 * l)) & 256)) + : (uint(b[2 + 8 * ib + 2 * l]) | ((qh << (8 - 2 * l)) & 256)); + const uint s = b[74 + 4 * ib + l]; + const uint scb = b[106 + (ib >> 1)]; + const float sc = rdh(b) * float(1 + 2 * ((scb >> (4 * (ib & 1))) & 15)); + return w4_signed(tab[i], hh ? s >> 4 : s, sc); + } +}; +template <> struct W4 { // 256 a block: d, scales_h, scales_l[4], qs[128]; 32-groups as IQ4_NL's + static inline half4 run(device const uchar* row, int k, threadgroup const uint* tab) { + device const uchar* b = row + (k >> 8) * 136; + const int j = k & 255, ib = j >> 5, o = j & 15, hi = (j >> 4) & 1; + const uint sh = *(device const ushort*)(b + 2); + const int ls = int((b[4 + (ib >> 1)] >> (4 * (ib & 1))) & 15) | int(((sh >> (2 * ib)) & 3) << 4); + const float s = rdh(b) * float(ls - 32); + device const uchar* qs = b + 8 + 16 * ib; + float4 q; + for (int c = 0; c < 4; ++c) { + const half2 w = as_type(tab[qs[o + c]]); + q[c] = float(hi ? w.y : w.x); + } + return half4(q * s); + } +}; +template <> struct W4 { // 32 a block: d, 16 bytes; low nibbles are elements 0..15, high 16..31 + static inline half4 run(device const uchar* row, int k, threadgroup const uint* tab) { + device const uchar* b = row + (k >> 5) * 18; + const int j = k & 31, hi = j >> 4, o = j & 15; + const float d = rdh(b); + float4 q; + for (int c = 0; c < 4; ++c) { + const half2 w = as_type(tab[b[2 + o + c]]); + q[c] = float(hi ? w.y : w.x); + } + return half4(q * d); + } +}; + +// W8: the runs k .. k + 3 and k + 16 .. k + 19 of a row (k % 32 < 16): one 32-group, so the per-group fields (scale, +// sign word) are read once. The generic one is two W4. +// ---- the K-quant / legacy-quant W4 decoders (the UD-Q4/5/6_K_XL packs' experts): values k .. k + 3 (k % 4 == 0) +// of a row in ref_quant's arithmetic (float), then fp16 +template <> struct W4 { // 32 a block: d, int8 qs[32] + static inline half4 run(device const uchar* row, int k, threadgroup const uint*) { + device const uchar* b = row + (k >> 5) * 34; + const float d = rdh(b); + device const char* q = (device const char*)(b + 2 + (k & 31)); + return half4(float4(float(q[0]), float(q[1]), float(q[2]), float(q[3])) * d); + } +}; +template <> struct W4 { // 32 a block: d, m, qh (32 bits), qs[16] (low nibbles 0..15, high 16..31) + static inline half4 run(device const uchar* row, int k, threadgroup const uint*) { + device const uchar* b = row + (k >> 5) * 24; + const float d = rdh(b), m = rdh(b + 2); + const uint hb = rd32(b + 4); + const int j = k & 31, o = j & 15, hi = j >> 4; + float4 w; + for (int c = 0; c < 4; ++c) { + const uint qv = b[8 + o + c]; + const int x = int(hi ? (qv >> 4) : (qv & 15)) | int(((hb >> (j + c)) & 1) << 4); + w[c] = float(x) * d + m; + } + return half4(w); + } +}; +template <> struct W4 { // 256 a block: d, dmin, scales[12], qs[128] (64-chunks: low nibbles then high) + static inline half4 run(device const uchar* row, int k, threadgroup const uint*) { + device const uchar* b = row + (k >> 8) * 144; + const int j = k & 255, c = j >> 6, hi = (j >> 5) & 1, l = j & 31; + float s, mm; + scale_min_k4(2 * c + hi, b + 4, s, mm); + const float d1 = rdh(b) * s, m1 = rdh(b + 2) * mm; + device const uchar* q = b + 16 + 32 * c + l; + float4 w; + for (int i = 0; i < 4; ++i) w[i] = d1 * float(hi ? (q[i] >> 4) : (q[i] & 15)) - m1; + return half4(w); + } +}; +template <> struct W4 { // 256 a block: d, dmin, scales[12], qh[32], qs[128] + static inline half4 run(device const uchar* row, int k, threadgroup const uint*) { + device const uchar* b = row + (k >> 8) * 176; + const int j = k & 255, c = j >> 6, hi = (j >> 5) & 1, l = j & 31; + float s, mm; + scale_min_k4(2 * c + hi, b + 4, s, mm); + const float d1 = rdh(b) * s, m1 = rdh(b + 2) * mm; + device const uchar* qh = b + 16 + l; + device const uchar* ql = b + 48 + 32 * c + l; + const uint bit = 1u << (2 * c + hi); + float4 w; + for (int i = 0; i < 4; ++i) + w[i] = d1 * float(int(hi ? (ql[i] >> 4) : (ql[i] & 15)) + ((qh[i] & bit) ? 16 : 0)) - m1; + return half4(w); + } +}; +template <> struct W4 { // 256 a block: ql[128], qh[64], int8 scales[16], d; halves of 128 + static inline half4 run(device const uchar* row, int k, threadgroup const uint*) { + device const uchar* b = row + (k >> 8) * 210; + const int j = k & 255, n = j >> 7, jj = j & 127, qd = jj >> 5, l = jj & 31; + device const uchar* ql = b + 64 * n + l + ((qd & 1) ? 32 : 0); + device const uchar* qh = b + 128 + 32 * n + l; + const float d = rdh(b + 208); + const float ds = d * float(((device const char*)(b + 192 + 8 * n))[l / 16 + 2 * qd]); + float4 w; + for (int i = 0; i < 4; ++i) { + const int q = int(((qd >> 1) ? (ql[i] >> 4) : (ql[i] & 15)) | (((qh[i] >> (2 * qd)) & 3) << 4)) - 32; + w[i] = ds * float(q); + } + return half4(w); + } +}; + +template struct W8 { + static inline void run(device const uchar* row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) { + a = W4::run(row, k, tab); + b = W4::run(row, k + 16, tab); + } +}; +// (a W8 sharing the block scale was measured slower than the two W4 of the generic one: 5.5 vs 3.5-4.2 ms) +template <> struct W8 { + template + static inline void run(P row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) { + const P bl = row + (k >> 8) * 98; + const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2; + const uint aux = rd32(bl + 2 + 64 + 4 * ib); + threadgroup const uchar* ks = (threadgroup const uchar*)(tab + 256); + const float sc = rdh(bl) * (0.5f + float(aux >> 28)) * 0.5f; + const P qs = bl + 2 + 8 * ib + hh; + if (mm_probe == 3) { // bench probe: no threadgroup-table lookups (wrong values) + a = w4_signed(qs[2 * l] * 0x01010101u, aux, sc); + b = w4_signed(qs[2 * l + 4] * 0x01010101u, aux >> 7, sc); + return; + } + uint s0, s1; + if (mm_probe == 4) { // the signs computed (ksigns_iq2xs[i] = i | parity(i) << 7) instead of looked up + const uint i0 = (aux >> (7 * l)) & 127, i1 = (aux >> (7 * (l + 2))) & 127; + s0 = i0 | ((popcount(i0) & 1u) << 7); + s1 = i1 | ((popcount(i1) & 1u) << 7); + } else { + s0 = ksg(tab, 256, (aux >> (7 * l)) & 127); + s1 = ksg(tab, 256, (aux >> (7 * (l + 2))) & 127); + } + a = w4_signed(g_iq3xxs(tab, qs[2 * l]), hh ? s0 >> 4 : s0, sc); + b = w4_signed(g_iq3xxs(tab, qs[2 * l + 4]), hh ? s1 >> 4 : s1, sc); + } +}; +template <> struct W8 { + static inline void run(device const uchar* row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) { + device const uchar* bl = row + (k >> 8) * 66; + const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2; + const uint a0 = rd32(bl + 2 + 8 * ib), a1 = rd32(bl + 2 + 8 * ib + 4); + threadgroup const uchar* ks = (threadgroup const uchar*)(tab + 512); + const float sc = rdh(bl) * (0.5f + float(a1 >> 28)) * 0.25f; + const uint i0 = (a0 >> (8 * l)) & 255, i1 = (a0 >> (8 * (l + 2))) & 255; + const uint s0 = ks[(a1 >> (7 * l)) & 127], s1 = ks[(a1 >> (7 * (l + 2))) & 127]; + a = w4_signed(tab[2 * i0 + hh], hh ? s0 >> 4 : s0, sc); + b = w4_signed(tab[2 * i1 + hh], hh ? s1 >> 4 : s1, sc); + } +}; +template <> struct W8 { + static inline void run(device const uchar* row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) { + device const uchar* bl = row + (k >> 8) * 74; + const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2; + device const ushort* q = (device const ushort*)(bl + 2) + 4 * ib; + const uint v0 = q[l], v1 = q[l + 2]; + threadgroup const uchar* ks = (threadgroup const uchar*)(tab + 1024); + const uint scb = bl[66 + ib]; + const float d = rdh(bl); + const float sc0 = d * (0.5f + float((scb >> (4 * (l >> 1))) & 15)) * 0.25f; + const float sc1 = d * (0.5f + float((scb >> (4 * ((l + 2) >> 1))) & 15)) * 0.25f; + const uint s0 = ks[v0 >> 9], s1 = ks[v1 >> 9]; + a = w4_signed(tab[2 * (v0 & 511) + hh], hh ? s0 >> 4 : s0, sc0); + b = w4_signed(tab[2 * (v1 & 511) + hh], hh ? s1 >> 4 : s1, sc1); + } +}; +template <> struct W8 { + template + static inline void run(P row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) { + const P bl = row + (k >> 8) * 82; + const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2; + const uint qh = bl[66 + ib], scb = bl[74 + ib]; + const float d = rdh(bl); + const uint i0 = uint(bl[2 + 4 * ib + l]) | ((qh << (8 - 2 * l)) & 0x300); + const uint i1 = uint(bl[2 + 4 * ib + l + 2]) | ((qh << (8 - 2 * (l + 2))) & 0x300); + const uint s0 = bl[2 + 32 + 4 * ib + l], s1 = bl[2 + 32 + 4 * ib + l + 2]; + const float sc0 = d * (0.5f + float((scb >> (4 * (l >> 1))) & 15)) * 0.25f; + const float sc1 = d * (0.5f + float((scb >> (4 * ((l + 2) >> 1))) & 15)) * 0.25f; + a = w4_signed(g_iq2s(tab, i0, hh), hh ? s0 >> 4 : s0, sc0); + b = w4_signed(g_iq2s(tab, i1, hh), hh ? s1 >> 4 : s1, sc1); + } +}; +template <> struct W8 { + template + static inline void run(P row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) { + const P bl = row + (k >> 8) * 110; + const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2; + const uint qh = bl[66 + ib], scb = bl[106 + (ib >> 1)]; + const float sc = rdh(bl) * float(1 + 2 * ((scb >> (4 * (ib & 1))) & 15)); + const int l1 = l + 2; + const uint i0 = hh ? (uint(bl[2 + 8 * ib + 2 * l + 1]) | ((qh << (7 - 2 * l)) & 256)) + : (uint(bl[2 + 8 * ib + 2 * l]) | ((qh << (8 - 2 * l)) & 256)); + const uint i1 = hh ? (uint(bl[2 + 8 * ib + 2 * l1 + 1]) | ((qh << (7 - 2 * l1)) & 256)) + : (uint(bl[2 + 8 * ib + 2 * l1]) | ((qh << (8 - 2 * l1)) & 256)); + const uint s0 = bl[74 + 4 * ib + l], s1 = bl[74 + 4 * ib + l1]; + if (mm_probe == 7) { + // bench probe: a repacked layout's cost - one aligned 16-byte load a lane a row a 32-group holding every + // field the lane needs (wrong values: the bytes come from an arbitrary aligned spot of the row) + const uint4 r = *(device const uint4*)((ulong(row) + ulong(k >> 5) * 16) & ~ulong(15)); + const uint qhv = r.z & 0xFF, scv = (r.z >> 8) & 0xFF; + const float scr = float(as_type(ushort(r.w & 0xFFFF))) * float(1 + 2 * ((scv >> (4 * (ib & 1))) & 15)); + const uint j0 = ((r.x >> (8 * (l & 1))) & 0xFF) | ((qhv << (8 - 2 * l)) & 256); + const uint j1 = ((r.x >> (16 + 8 * (l & 1))) & 0xFF) | ((qhv << (7 - 2 * l)) & 256); + a = w4_signed(tab[j0], (r.y >> (8 * hh)) & 0xFF, scr); + b = w4_signed(tab[j1], (r.y >> (16 + 8 * hh)) & 0xFF, scr); + return; + } + if (mm_probe == 5) { // bench probe: the loads and the scale, no grid lookup / sign math (wrong values) + a = half4(half(float(i0 ^ s0) * sc)); + b = half4(half(float(i1 ^ s1) * sc)); + return; + } + a = w4_signed(g_iq3s(tab, i0), hh ? s0 >> 4 : s0, sc); + b = w4_signed(g_iq3s(tab, i1), hh ? s1 >> 4 : s1, sc); + } +}; + +// W8 for the K-quants and Q5_1: the lane's runs k and k + 16 (k % 32 < 16) share the block's scales / mins / high +// bits; the 4-byte code runs read as one uint where the block layout keeps them 4-aligned (Q4_K 144-, Q5_K 176-, +// Q5_1 24-byte blocks: rows of whole blocks start 4-aligned). The same per-value arithmetic as W4. +static inline float4 nib4(uint v, int hi) { const uint s = hi ? (v >> 4) : v; return float4(as_type(s & 0x0F0F0F0Fu)); } +template <> struct W8 { + static inline void run(device const uchar* row, int k, threadgroup const uint*, thread half4& a, thread half4& b) { + device const uchar* bl = row + (k >> 8) * 144; + const int j = k & 255, c = j >> 6, hi = (j >> 5) & 1, l = j & 31; + float s, mm; + scale_min_k4(2 * c + hi, bl + 4, s, mm); + const float d1 = rdh(bl) * s, m1 = rdh(bl + 2) * mm; + device const uint* q = (device const uint*)(bl + 16 + 32 * c + l); + const float4 qa = nib4(q[0], hi), qb = nib4(q[4], hi); + a = half4(d1 * qa - m1); + b = half4(d1 * qb - m1); + } +}; +template <> struct W8 { + static inline void run(device const uchar* row, int k, threadgroup const uint*, thread half4& a, thread half4& b) { + device const uchar* bl = row + (k >> 8) * 176; + const int j = k & 255, c = j >> 6, hi = (j >> 5) & 1, l = j & 31; + float s, mm; + scale_min_k4(2 * c + hi, bl + 4, s, mm); + const float d1 = rdh(bl) * s, m1 = rdh(bl + 2) * mm; + device const uint* qh = (device const uint*)(bl + 16 + l); + device const uint* ql = (device const uint*)(bl + 48 + 32 * c + l); + const uint sh = uint(2 * c + hi); + const float4 ha = float4(as_type((qh[0] >> sh) & 0x01010101u)) * 16.0f; + const float4 hb = float4(as_type((qh[4] >> sh) & 0x01010101u)) * 16.0f; + a = half4(d1 * (nib4(ql[0], hi) + ha) - m1); + b = half4(d1 * (nib4(ql[4], hi) + hb) - m1); + } +}; +template <> struct W8 { + static inline void run(device const uchar* row, int k, threadgroup const uint*, thread half4& a, thread half4& b) { + device const uchar* bl = row + (k >> 5) * 24; + const float d = rdh(bl), m = rdh(bl + 2); + const uint hb = rd32(bl + 4); + const int j = k & 15; // runs at j and j + 16: the low nibbles of qs[j..j+3], then the high ones + const uint v = *(device const uint*)(bl + 8 + j); + float4 wa, wb; + for (int c = 0; c < 4; ++c) { + const uint qv = (v >> (8 * c)) & 0xFFu; + wa[c] = float(int(qv & 15) | int(((hb >> (j + c)) & 1) << 4)) * d + m; + wb[c] = float(int(qv >> 4) | int(((hb >> (j + 16 + c)) & 1) << 4)) * d + m; + } + a = half4(wa); + b = half4(wb); + } +}; +template <> struct W8 { + static inline void run(device const uchar* row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) { + device const uchar* bl = row + (k >> 8) * 210; + const int j = k & 255, n = j >> 7, jj = j & 127, qd = jj >> 5, l = jj & 31; // l < 16; the pair at l + 16 + device const uchar* ql = bl + 64 * n + l + ((qd & 1) ? 32 : 0); + device const uchar* qh = bl + 128 + 32 * n + l; + const float d = rdh(bl + 208); + device const char* sc = (device const char*)(bl + 192 + 8 * n); + const float dsa = d * float(sc[2 * qd]), dsb = d * float(sc[1 + 2 * qd]); + // the 4-byte runs as two ushorts each (210-byte blocks: 2-aligned) + device const ushort* l2 = (device const ushort*)ql; + device const ushort* h2 = (device const ushort*)qh; + const uint la = uint(l2[0]) | (uint(l2[1]) << 16), lb = uint(l2[8]) | (uint(l2[9]) << 16); + const uint ha = uint(h2[0]) | (uint(h2[1]) << 16), hb = uint(h2[8]) | (uint(h2[9]) << 16); + const uint sl = (qd >> 1) ? 4u : 0u, shh = uint(2 * qd); + const uint4 qa = (uint4(as_type((la >> sl) & 0x0F0F0F0Fu)) | (uint4(as_type((ha >> shh) & 0x03030303u)) << 4)); + const uint4 qb = (uint4(as_type((lb >> sl) & 0x0F0F0F0Fu)) | (uint4(as_type((hb >> shh) & 0x03030303u)) << 4)); + a = half4(dsa * (float4(qa) - 32.0f)); + b = half4(dsb * (float4(qb) - 32.0f)); + } +}; + +template +kernel void mm_gu3(device const uchar* W [[buffer(0)]], device const half* XS [[buffer(1)]], + device half* HS [[buffer(2)]], device const int2* tiles [[buffer(3)]], constant MmArgs& a [[buffer(4)]], device const uint* smap [[buffer(5)]], + device const uchar* W1 [[buffer(6)]], device const uchar* W2 [[buffer(7)]], device const uchar* W3 [[buffer(8)]], + uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) { + threadgroup float ot[SG][TM * TN]; + threadgroup uint tab[fmt::TAB]; + load_tab(tab, tid, SG * 32); + threadgroup_barrier(mem_flags::mem_threadgroup); + const int2 tl = tiles[tg.y]; + const int e = tl.x, row0 = tl.y, n0 = (int(tg.x) * SG + sg) * TN; + device const uchar* E = kArena ? arena_slot(smap[e], W, W1, W2, W3) : W + ulong(e) * a.gu_stride; + device const uchar* g0 = E + a.gate_off + ulong(n0) * a.gu_row; + device const uchar* u0 = E + a.up_off + ulong(n0) * a.gu_row; + constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false, matmul2d_descriptor::mode::multiply_accumulate); + matmul2d op; + tensor, tensor_inline> tX((device half*)XS, dextents(a.n_embd, 1 << 30)); + auto rg = op.template get_right_input_cooperative_tensor(); + auto ru = op.template get_right_input_cooperative_tensor(); + auto tA = tX.template slice(0, row0); + auto accg = op.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t, __tensor_ops_detail::__remove_addrspace_t, float>(); + auto accu = op.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t, __tensor_ops_detail::__remove_addrspace_t, float>(); + for (uint16_t i = 0; i < accg.get_capacity(); ++i) + if (accg.is_valid_element(i)) { accg[i] = 0.0f; accu[i] = 0.0f; } + for (int k0 = 0; k0 < int(a.n_embd); k0 += TK) { + const uint16_t cap = rg.get_capacity(), half_cap = cap / 2; + if (!coop_k4) { + for (uint16_t i = 0; i < cap; ++i) { + const auto ix = rg.get_multidimensional_index(i); + const int k = k0 + ix[0], n = ix[1]; + rg[i] = W4::run(g0 + ulong(n) * a.gu_row, k & ~3, tab)[k & 3]; + ru[i] = W4::run(u0 + ulong(n) * a.gu_row, k & ~3, tab)[k & 3]; + } + } else +#pragma clang loop unroll(full) + for (uint16_t i = 0; i < half_cap; i += 4) { + const auto ix = rg.get_multidimensional_index(i); + const auto iy = rg.get_multidimensional_index(i + half_cap); + const int k = k0 + ix[0], n = ix[1]; + device const uchar* rgw = g0 + ulong(n) * a.gu_row; + device const uchar* ruw = u0 + ulong(n) * a.gu_row; + half4 wg, wu, wg2, wu2; + if (mm_probe == 1) { // the bench probe: no decode (constant weights) + wg = half4(half(n & 7)); wu = wg; wg2 = half4(half(k & 7)); wu2 = wg2; + } else if (TK == 32) { + // the lane's two runs of this row sit in one 32-group: element i + cap / 2 is (k + 16, n) - part of + // the COOP_K4 layout (coop_probe checks it); a runtime check of it here cost 30% + W8::run(rgw, k, tab, wg, wg2); + W8::run(ruw, k, tab, wu, wu2); + } else { + const int k2 = k0 + iy[0]; + device const uchar* rgw2 = g0 + ulong(iy[1]) * a.gu_row; + device const uchar* ruw2 = u0 + ulong(iy[1]) * a.gu_row; + wg = W4::run(rgw, k, tab); wu = W4::run(ruw, k, tab); + wg2 = W4::run(rgw2, k2, tab); wu2 = W4::run(ruw2, k2, tab); + } + rg[i] = wg.x; rg[i + 1] = wg.y; rg[i + 2] = wg.z; rg[i + 3] = wg.w; + ru[i] = wu.x; ru[i + 1] = wu.y; ru[i + 2] = wu.z; ru[i + 3] = wu.w; + const uint16_t j = i + half_cap; + rg[j] = wg2.x; rg[j + 1] = wg2.y; rg[j + 2] = wg2.z; rg[j + 3] = wg2.w; + ru[j] = wu2.x; ru[j + 1] = wu2.y; ru[j + 2] = wu2.z; ru[j + 3] = wu2.w; + } + tA = tX.template slice(k0, row0); + op.run(tA, rg, accg); + op.run(tA, ru, accu); + } + for (uint16_t i = 0; i < accg.get_capacity(); ++i) + if (accg.is_valid_element(i)) { + const float g = accg[i]; + accg[i] = g / (1.0f + exp(-g)) * accu[i]; + } + tensor, tensor_inline> tO(ot[sg], dextents(TN, TM)); + accg.store(tO); + simdgroup_barrier(mem_flags::mem_threadgroup); + for (int it = lane; it < TM * TN; it += 32) { + const int m = it / TN, f = it - m * TN; + HS[ulong(row0 + m) * a.n_ff + n0 + f] = half(ot[sg][it]); + } +} + +template +kernel void mm_down3(device const uchar* W [[buffer(0)]], device const half* HS [[buffer(1)]], + device float* YE [[buffer(2)]], device const int2* tiles [[buffer(3)]], constant MmArgs& a [[buffer(4)]], device const uint* smap [[buffer(5)]], + device const uchar* W1 [[buffer(6)]], device const uchar* W2 [[buffer(7)]], device const uchar* W3 [[buffer(8)]], + uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort tid [[thread_index_in_threadgroup]]) { + threadgroup uint tab[fmt::TAB]; + load_tab(tab, tid, SG * 32); + threadgroup_barrier(mem_flags::mem_threadgroup); + const int2 tl = tiles[tg.y]; + const int e = tl.x, row0 = tl.y, n0 = (int(tg.x) * SG + sg) * TN; + device const uchar* w0 = (kArena ? arena_slot(smap[e], W, W1, W2, W3) : W + ulong(e) * a.d_stride) + a.down_off + ulong(n0) * a.d_row; + constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false, matmul2d_descriptor::mode::multiply_accumulate); + matmul2d op; + tensor, tensor_inline> tH((device half*)HS, dextents(a.n_ff, 1 << 30)); + auto rw = op.template get_right_input_cooperative_tensor(); + auto tA = tH.template slice(0, row0); + auto acc = op.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t, __tensor_ops_detail::__remove_addrspace_t, float>(); + for (uint16_t i = 0; i < acc.get_capacity(); ++i) + if (acc.is_valid_element(i)) acc[i] = 0.0f; + for (int k0 = 0; k0 < int(a.n_ff); k0 += TK) { + if (!coop_k4) { + for (uint16_t i = 0; i < rw.get_capacity(); ++i) { + const auto ix = rw.get_multidimensional_index(i); + const int k = k0 + ix[0]; + rw[i] = W4::run(w0 + ulong(ix[1]) * a.d_row, k & ~3, tab)[k & 3]; + } + } else if (TK == 32) { + // the paired runs (element i + cap / 2 is (k + 16, n), the COOP_K4 layout): one W8 a pair + const uint16_t half_cap = rw.get_capacity() / 2; +#pragma clang loop unroll(full) + for (uint16_t i = 0; i < half_cap; i += 4) { + const auto ix = rw.get_multidimensional_index(i); + half4 w, w2; + W8::run(w0 + ulong(ix[1]) * a.d_row, k0 + ix[0], tab, w, w2); + rw[i] = w.x; rw[i + 1] = w.y; rw[i + 2] = w.z; rw[i + 3] = w.w; + const uint16_t j = i + half_cap; + rw[j] = w2.x; rw[j + 1] = w2.y; rw[j + 2] = w2.z; rw[j + 3] = w2.w; + } + } else +#pragma clang loop unroll(full) + for (uint16_t i = 0; i < rw.get_capacity(); i += 4) { + const auto ix = rw.get_multidimensional_index(i); + const half4 w = W4::run(w0 + ulong(ix[1]) * a.d_row, k0 + ix[0], tab); + rw[i] = w.x; rw[i + 1] = w.y; rw[i + 2] = w.z; rw[i + 3] = w.w; + } + tA = tH.template slice(k0, row0); + op.run(tA, rw, acc); + } + tensor, tensor_inline> tY(YE, dextents(a.n_embd, 1 << 30)); + acc.store(tY.slice(n0, row0)); +} + +#define MMGU3_(F, M, N, K, S) template [[host_name("mm_gu3_" #F "_" #M "_" #N "_" #K "_" #S)]] kernel decltype(mm_gu3) mm_gu3; +#define MMDN3_(F, M, N, K, S) template [[host_name("mm_down3_" #F "_" #M "_" #N "_" #K "_" #S)]] kernel decltype(mm_down3) mm_down3; +#define MMGU3(F, M, N, K, S) MMGU3_(F, M, N, K, S) +#define MMDN3(F, M, N, K, S) MMDN3_(F, M, N, K, S) +#define MM3_ONE(F, M, N, K, S) MMGU3(F, M, N, K, S) MMDN3(F, M, N, K, S) +#define MM3_GU(F) MMGU3(F, 16, 64, 32, 2) MMGU3(F, 16, 32, 32, 4) MMGU3(F, 32, 64, 32, 2) MMGU3(F, 16, 64, 64, 2) \ + MMGU3(F, 16, 32, 16, 2) MMGU3(F, 32, 32, 32, 2) MMGU3(F, 16, 64, 32, 1) MMGU3(F, 16, 64, 32, 4) MMGU3(F, 16, 32, 16, 4) MMGU3(F, 16, 32, 32, 5) MMGU3(F, 16, 32, 16, 5) MMGU3(F, 16, 16, 32, 4) MMGU3(F, 16, 16, 32, 8) MMGU3(F, 16, 16, 16, 8) +#define MM3_DN(F) MMDN3(F, 16, 64, 32, 2) MMDN3(F, 16, 32, 32, 4) MMDN3(F, 32, 64, 32, 2) MMDN3(F, 16, 64, 64, 2) \ + MMDN3(F, 16, 32, 16, 2) MMDN3(F, 32, 32, 32, 2) MMDN3(F, 16, 64, 32, 1) MMDN3(F, 16, 64, 32, 4) MMDN3(F, 16, 64, 16, 2) MMDN3(F, 16, 32, 16, 4) MMDN3(F, 16, 64, 32, 5) MMDN3(F, 16, 64, 16, 4) +MM3_GU(T_Q4_K) MM3_GU(T_Q5_K) MM3_GU(T_Q6_K) MM3_GU(T_Q8_0) MM3_GU(T_IQ4_XS) MM3_GU(T_Q2_0) MM3_GU(T_IQ3_XXS) MM3_GU(T_IQ2_XXS) MM3_GU(T_IQ2_XS) MM3_GU(T_IQ2_S) MM3_GU(T_IQ3_S) +MM3_DN(T_Q2_0) MM3_DN(T_IQ4_NL) MM3_DN(T_Q5_1) MM3_DN(T_Q8_0) + +// mm_gu4: mm_gu3 with each decoded right operand (TN x TK weights of gate and of up) applied to MS 16-row token +// tiles (a tile of 16 * MS rows from the plan, tm = 16 * MS): the decode, which bounds mm_gu3, is shared by MS times +// as many token rows (more padding rows per expert, but the matrix ops are cheap next to the decode). The same +// per-row arithmetic as mm_gu3 (each 16-row op is mm_gu3's): bitwise for the rows both compute. COOP_K4 layout only. +template +kernel void mm_gu4(device const uchar* W [[buffer(0)]], device const half* XS [[buffer(1)]], + device half* HS [[buffer(2)]], device const int2* tiles [[buffer(3)]], constant MmArgs& a [[buffer(4)]], + uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int TM = 16; + threadgroup float ot[SG][TM * TN]; + threadgroup uint tab[fmt::TAB]; + load_tab(tab, tid, SG * 32); + threadgroup_barrier(mem_flags::mem_threadgroup); + const int2 tl = tiles[tg.y]; + const int e = tl.x, row0 = tl.y, n0 = (int(tg.x) * SG + sg) * TN; + device const uchar* g0 = W + a.gate_off + ulong(e) * a.gu_stride + ulong(n0) * a.gu_row; + device const uchar* u0 = W + a.up_off + ulong(e) * a.gu_stride + ulong(n0) * a.gu_row; + constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false, matmul2d_descriptor::mode::multiply_accumulate); + matmul2d op; + tensor, tensor_inline> tX((device half*)XS, dextents(a.n_embd, 1 << 30)); + auto rg = op.template get_right_input_cooperative_tensor(); + auto ru = op.template get_right_input_cooperative_tensor(); + auto tA0 = tX.template slice(0, row0); + auto tA1 = tX.template slice(0, row0 + TM); +#define MM4_DST op.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t, __tensor_ops_detail::__remove_addrspace_t, float>() + auto accg0 = MM4_DST; + auto accu0 = MM4_DST; + auto accg1 = MM4_DST; + auto accu1 = MM4_DST; +#undef MM4_DST + using DT = decltype(accg0); + for (uint16_t i = 0; i < accg0.get_capacity(); ++i) + if (accg0.is_valid_element(i)) { accg0[i] = 0.0f; accu0[i] = 0.0f; accg1[i] = 0.0f; accu1[i] = 0.0f; } + for (int k0 = 0; k0 < int(a.n_embd); k0 += TK) { + const uint16_t cap = rg.get_capacity(), half_cap = cap / 2; +#pragma clang loop unroll(full) + for (uint16_t i = 0; i < half_cap; i += 4) { + const auto ix = rg.get_multidimensional_index(i); + const int k = k0 + ix[0], n = ix[1]; + device const uchar* rgw = g0 + ulong(n) * a.gu_row; + device const uchar* ruw = u0 + ulong(n) * a.gu_row; + half4 wg, wu, wg2, wu2; + W8::run(rgw, k, tab, wg, wg2); + W8::run(ruw, k, tab, wu, wu2); + rg[i] = wg.x; rg[i + 1] = wg.y; rg[i + 2] = wg.z; rg[i + 3] = wg.w; + ru[i] = wu.x; ru[i + 1] = wu.y; ru[i + 2] = wu.z; ru[i + 3] = wu.w; + const uint16_t j = i + half_cap; + rg[j] = wg2.x; rg[j + 1] = wg2.y; rg[j + 2] = wg2.z; rg[j + 3] = wg2.w; + ru[j] = wu2.x; ru[j + 1] = wu2.y; ru[j + 2] = wu2.z; ru[j + 3] = wu2.w; + } + tA0 = tX.template slice(k0, row0); + op.run(tA0, rg, accg0); + op.run(tA0, ru, accu0); + if (MS > 1) { + tA1 = tX.template slice(k0, row0 + TM); + op.run(tA1, rg, accg1); + op.run(tA1, ru, accu1); + } + } + for (int s = 0; s < MS; ++s) { + thread DT& ag = s == 0 ? accg0 : accg1; + thread DT& au = s == 0 ? accu0 : accu1; + for (uint16_t i = 0; i < ag.get_capacity(); ++i) + if (ag.is_valid_element(i)) { + const float g = ag[i]; + ag[i] = g / (1.0f + exp(-g)) * au[i]; + } + tensor, tensor_inline> tO(ot[sg], dextents(TN, TM)); + simdgroup_barrier(mem_flags::mem_threadgroup); + ag.store(tO); + simdgroup_barrier(mem_flags::mem_threadgroup); + for (int it = lane; it < TM * TN; it += 32) { + const int m = it / TN, f = it - m * TN; + HS[ulong(row0 + s * TM + m) * a.n_ff + n0 + f] = half(ot[sg][it]); + } + } +} +#define MMGU4_(F, M, N, K, S) template [[host_name("mm_gu4_" #F "_" #M "_" #N "_" #K "_" #S)]] kernel decltype(mm_gu4) mm_gu4; +#define MMGU4(F, M, N, K, S) MMGU4_(F, M, N, K, S) +#define MM4_GU(F) MMGU4(F, 2, 32, 32, 4) MMGU4(F, 2, 32, 32, 2) MMGU4(F, 2, 16, 32, 4) MMGU4(F, 1, 32, 32, 4) +MM4_GU(T_Q2_0) MM4_GU(T_IQ3_XXS) MM4_GU(T_IQ2_XXS) MM4_GU(T_IQ2_XS) MM4_GU(T_IQ2_S) MM4_GU(T_IQ3_S) MM4_GU(T_IQ4_XS) + +// mm_gu5: mm_gu3 (COOP_K4 layout, TK 32) with the threadgroup's weight rows staged block by block (QK = 256 values a +// row, gate and up) into threadgroup memory by coalesced ushort loads, the lanes decoding from there: the decode's +// many small scattered device loads (2-6 a run) become threadgroup reads. Same decoded values and the same matrix +// ops as mm_gu3: bitwise. Formats with 256-value blocks and a templated W8 (IQ3_S, IQ3_XXS, IQ2_S). +template +kernel void mm_gu5(device const uchar* W [[buffer(0)]], device const half* XS [[buffer(1)]], + device half* HS [[buffer(2)]], device const int2* tiles [[buffer(3)]], constant MmArgs& a [[buffer(4)]], + uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int TM = 16, TK = 32, BB = fmt::BB, ROWS = SG * TN, RU = BB / 2; + threadgroup float ot[SG][TM * TN]; + threadgroup uint tab[fmt::TAB]; + threadgroup ushort stg[2][ROWS * RU]; + load_tab(tab, tid, SG * 32); + const int2 tl = tiles[tg.y]; + const int e = tl.x, row0 = tl.y, nt0 = int(tg.x) * ROWS, n0 = nt0 + sg * TN; + device const uchar* gt = W + a.gate_off + ulong(e) * a.gu_stride + ulong(nt0) * a.gu_row; + device const uchar* ut = W + a.up_off + ulong(e) * a.gu_stride + ulong(nt0) * a.gu_row; + constexpr auto desc = matmul2d_descriptor(TM, TN, TK, false, true, false, matmul2d_descriptor::mode::multiply_accumulate); + matmul2d op; + tensor, tensor_inline> tX((device half*)XS, dextents(a.n_embd, 1 << 30)); + auto rg = op.template get_right_input_cooperative_tensor(); + auto ru = op.template get_right_input_cooperative_tensor(); + auto tA = tX.template slice(0, row0); + auto accg = op.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t, __tensor_ops_detail::__remove_addrspace_t, float>(); + auto accu = op.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t, __tensor_ops_detail::__remove_addrspace_t, float>(); + for (uint16_t i = 0; i < accg.get_capacity(); ++i) + if (accg.is_valid_element(i)) { accg[i] = 0.0f; accu[i] = 0.0f; } + const int NB = int(a.n_embd) / 256; + for (int kb = 0; kb < NB; ++kb) { + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int idx = tid; idx < ROWS * RU; idx += SG * 32) { + const int r = idx / RU, w = idx - r * RU; + stg[0][idx] = ((device const ushort*)(gt + ulong(r) * a.gu_row + kb * BB))[w]; + stg[1][idx] = ((device const ushort*)(ut + ulong(r) * a.gu_row + kb * BB))[w]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int ks = 0; ks < 8; ++ks) { + const int k0 = kb * 256 + ks * TK; + const uint16_t half_cap = rg.get_capacity() / 2; +#pragma clang loop unroll(full) + for (uint16_t i = 0; i < half_cap; i += 4) { + const auto ix = rg.get_multidimensional_index(i); + const int kl = ks * TK + ix[0], n = sg * TN + ix[1]; + // the block's row in the stage; W8 indexes block (k >> 8) = 0 of it with k = kl + threadgroup const uchar* rgw = (threadgroup const uchar*)(stg[0] + n * RU); + threadgroup const uchar* ruw = (threadgroup const uchar*)(stg[1] + n * RU); + half4 wg, wu, wg2, wu2; + W8::run(rgw, kl, tab, wg, wg2); + W8::run(ruw, kl, tab, wu, wu2); + rg[i] = wg.x; rg[i + 1] = wg.y; rg[i + 2] = wg.z; rg[i + 3] = wg.w; + ru[i] = wu.x; ru[i + 1] = wu.y; ru[i + 2] = wu.z; ru[i + 3] = wu.w; + const uint16_t j = i + half_cap; + rg[j] = wg2.x; rg[j + 1] = wg2.y; rg[j + 2] = wg2.z; rg[j + 3] = wg2.w; + ru[j] = wu2.x; ru[j + 1] = wu2.y; ru[j + 2] = wu2.z; ru[j + 3] = wu2.w; + } + tA = tX.template slice(k0, row0); + op.run(tA, rg, accg); + op.run(tA, ru, accu); + } + } + for (uint16_t i = 0; i < accg.get_capacity(); ++i) + if (accg.is_valid_element(i)) { + const float g = accg[i]; + accg[i] = g / (1.0f + exp(-g)) * accu[i]; + } + tensor, tensor_inline> tO(ot[sg], dextents(TN, TM)); + accg.store(tO); + simdgroup_barrier(mem_flags::mem_threadgroup); + for (int it = lane; it < TM * TN; it += 32) { + const int m = it / TN, f = it - m * TN; + HS[ulong(row0 + m) * a.n_ff + n0 + f] = half(ot[sg][it]); + } +} +#define MMGU5_(F, N, S) template [[host_name("mm_gu5_" #F "_" #N "_" #S)]] kernel decltype(mm_gu5) mm_gu5; +#define MMGU5(F, N, S) MMGU5_(F, N, S) +MMGU5(T_IQ3_S, 32, 2) MMGU5(T_IQ3_S, 32, 1) MMGU5(T_IQ3_S, 16, 4) MMGU5(T_IQ3_XXS, 32, 2) MMGU5(T_IQ3_XXS, 32, 1) +MMGU5(T_IQ3_XXS, 16, 4) MMGU5(T_IQ2_S, 32, 2) MMGU5(T_IQ2_S, 32, 1) MMGU5(T_IQ2_S, 16, 4) diff --git a/metal/kernels/prompt.metal b/metal/kernels/prompt.metal new file mode 100644 index 00000000..64833b0a --- /dev/null +++ b/metal/kernels/prompt.metal @@ -0,0 +1,177 @@ +// metal/kernels/prompt.metal - the elementwise steps of a prompt chunk around the GEMMs (after quant/units.metal): +// +// route_topk per token: softmax over the 512 logits, top 10 (ties: the lower expert), weights renormalised +// over the selected with a 2^-14 floor - moe_route's rule; one simdgroup a token +// gr_epi_down after the HC down GEMM (V = xn . [w_down; w_inject], T x (hc_lr + hc)): lo_h = half(silu(v / hc)), +// inject = v +// gr_epi_up after the HC up GEMM (G = lo . w_up, T x hc*n): mixed = mean_c xn[c] * sigmoid(G[c]) -> float and +// half (the next GEMMs' operand) +// swiglu_h h = half(silu(g) * u) +// moe_out bo = y_routed + sigmoid(sg) * y_shared + +kernel void route_topk(device const float* logits [[buffer(0)]], device int* ids [[buffer(1)]], + device float* w [[buffer(2)]], constant uint& n_tok [[buffer(3)]], + uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]]) { + const uint t = tg.x * 8 + sg; + if (t >= n_tok) return; + device const float* l = logits + ulong(t) * 512; + float v[16]; + for (int i = 0; i < 16; ++i) v[i] = l[lane + 32 * i]; + float mx = -INFINITY; + for (int i = 0; i < 16; ++i) mx = max(mx, v[i]); + for (ushort m = 16; m > 0; m >>= 1) mx = max(mx, simd_shuffle_xor(mx, m)); + float sum = 0.0f; + for (int i = 0; i < 16; ++i) { + v[i] = exp(v[i] - mx); + sum += v[i]; + } + for (ushort m = 16; m > 0; m >>= 1) sum += simd_shuffle_xor(sum, m); + const float rcp = 1.0f / sum; + for (int i = 0; i < 16; ++i) { + v[i] *= rcp; + if (isnan(v[i])) v[i] = -FLT_MAX; + } + float selected = 0.0f, ssum = 0.0f; + for (int rank = 0; rank < 10; ++rank) { + float best = v[0]; + int ex = lane; + for (int i = 1; i < 16; ++i) + if (v[i] > best) { best = v[i]; ex = lane + 32 * i; } + for (ushort m = 16; m > 0; m >>= 1) { + const float ob = simd_shuffle_xor(best, m); + const int oe = simd_shuffle_xor(ex, m); + if (ob > best || (ob == best && oe < ex)) { best = ob; ex = oe; } + } + if ((ex & 31) == lane) { + v[ex / 32] = -INFINITY; + ids[t * 10 + rank] = ex; + ssum += best; + } + if (rank == lane) selected = best; + } + for (ushort m = 16; m > 0; m >>= 1) ssum += simd_shuffle_xor(ssum, m); + ssum = max(ssum, 6.103515625e-5f); + if (lane < 10) w[t * 10 + lane] = selected * (1.0f / ssum); +} + +struct EpiArgs { + uint n_tok; + uint n_embd; // 2560 + uint hc; // 4 + uint hc_lr; // 320 +}; + +// grid (T * (hc_lr + hc) / 256) +kernel void gr_epi_down(device const float* V [[buffer(0)]], device half* lo_h [[buffer(1)]], + device float* inject [[buffer(2)]], constant EpiArgs& a [[buffer(3)]], + uint gid [[thread_position_in_grid]]) { + const uint nr = a.hc_lr + a.hc, t = gid / nr, r = gid % nr; + if (t >= a.n_tok) return; + const float v = V[gid]; + if (r < a.hc_lr) { + const float z = v / float(a.hc); + lo_h[t * a.hc_lr + r] = half(z / (1.0f + exp(-z))); + } else { + inject[t * a.hc + r - a.hc_lr] = v; + } +} + +// grid (T * n_embd / 256) +kernel void gr_epi_up(device const float* G [[buffer(0)]], device const float* xn [[buffer(1)]], + device float* mixed [[buffer(2)]], device half* mixed_h [[buffer(3)]], + constant EpiArgs& a [[buffer(4)]], uint gid [[thread_position_in_grid]]) { + const uint n = a.n_embd, t = gid / n, d = gid % n; + if (t >= a.n_tok) return; + float m = 0.0f; + for (uint c = 0; c < a.hc; ++c) { + const float g = G[ulong(t) * a.hc * n + c * n + d]; + m = fma(xn[ulong(t) * a.hc * n + c * n + d], 1.0f / (1.0f + exp(-g)), m); + } + m = m / float(a.hc); + mixed[gid] = m; + mixed_h[gid] = half(m); +} + +kernel void swiglu_h(device const float* g [[buffer(0)]], device const float* u [[buffer(1)]], device half* h [[buffer(2)]], + constant uint& n [[buffer(3)]], uint gid [[thread_position_in_grid]]) { + if (gid >= n) return; + const float gv = g[gid]; + h[gid] = half(gv / (1.0f + exp(-gv)) * u[gid]); +} + +// grid (T * n_embd / 256); sg: T values +kernel void moe_out(device const float* yr [[buffer(0)]], device const float* ys [[buffer(1)]], + device const float* sg [[buffer(2)]], device float* bo [[buffer(3)]], constant uint2& a [[buffer(4)]], + uint gid [[thread_position_in_grid]]) { + const uint t = gid / a.y; + if (t >= a.x) return; + bo[gid] = fma(1.0f / (1.0f + exp(-sg[t])), ys[gid], yr[gid]); +} + +// ---- the HC read with fewer passes (after dense_mm.metal: GemmArgs, MetalPerformancePrimitives) --------------------- +// gr_norm_h: gr_norm with xn written as fp16 only (the GEMM operand; gemm_hc_up's epilogue reads it too). +// one threadgroup per (stream c, token t), 256 threads; args as gr_norm's (GrArgs, gr.metal) +kernel void gr_norm_h(device float* R [[buffer(0)]], device const float* bo [[buffer(1)]], + device const float* inj [[buffer(2)]], device const float* w_norm [[buffer(3)]], + device half* xnh [[buffer(4)]], constant GrArgs& a [[buffer(5)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + threadgroup float part[8]; + const uint c = tg.x, t = tg.y, n = a.n_embd; + device float* r = R + (t * a.hc + c) * n; + const float g = a.apply ? 2.0f / (1.0f + exp(-inj[t * a.hc + c] / float(a.hc))) : 0.0f; + float ss = 0.0f; + for (uint d = tid; d < n; d += 256) { + float v = r[d]; + if (a.apply) { + v = fma(bo[t * n + d], g, v); + r[d] = v; + } + ss = fma(v, v, ss); + } + ss = simd_sum(ss); + if (lane == 0) part[sg] = ss; + threadgroup_barrier(mem_flags::mem_threadgroup); + float tot = 0.0f; + for (int i = 0; i < 8; ++i) tot += part[i]; + const float rs = rsqrt(tot / float(n) + a.eps); + device half* o = xnh + (t * a.hc + c) * n; + device const float* w = w_norm + c * n; + for (uint d = tid; d < n; d += 256) o[d] = half(r[d] * w[d] * rs); +} + +// gemm_hc_up: G = lo . w_up^T with w_up's rows interleaved by dq_f16 (perm = hc: row d * hc + c), so a TN-column +// tile holds TN / hc outputs d with all their streams; the epilogue mixed[t][d] = mean_c xn[t][c][d] * +// sigmoid(G[t][d * hc + c]) -> fp32 and fp16. G is never written. grid (hc * n / TN, ceil(T / TM)), 32 * SG threads. +template +kernel void gemm_hc_up(device half* A [[buffer(0)]], device half* B [[buffer(1)]], device const half* xnh [[buffer(2)]], + device float* mixed [[buffer(3)]], device half* mixh [[buffer(4)]], constant GemmArgs& g [[buffer(5)]], + constant EpiArgs& e [[buffer(6)]], uint3 tg [[threadgroup_position_in_grid]], + ushort tid [[thread_index_in_threadgroup]]) { + threadgroup float ot[TM * TN]; + tensor, tensor_inline> tA(A, dextents(g.K, g.M)); + tensor, tensor_inline> tB(B, dextents(g.K, g.N)); + tensor, tensor_inline> tO(ot, dextents(TN, TM)); + constexpr auto desc = matmul2d_descriptor(TM, TN, dynamic_length_v, false, true, false); + matmul2d> op; + auto mA = tA.slice(0, int(tg.y) * TM); + auto mB = tB.slice(0, int(tg.x) * TN); + op.run(mA, mB, tO); + threadgroup_barrier(mem_flags::mem_threadgroup); + const int hc = int(e.hc), n = int(e.n_embd), DPT = TN / hc; + const int t0 = int(tg.y) * TM, d0 = int(tg.x) * DPT; + for (int idx = tid; idx < TM * DPT; idx += SG * 32) { + const int m = idx / DPT, dd = idx - m * DPT, t = t0 + m; + if (t >= int(e.n_tok)) continue; + float s = 0.0f; + for (int c = 0; c < hc; ++c) + s = fma(float(xnh[ulong(t) * hc * n + c * n + d0 + dd]), 1.0f / (1.0f + exp(-ot[m * TN + dd * hc + c])), s); + s = s / float(hc); + mixed[ulong(t) * n + d0 + dd] = s; + mixh[ulong(t) * n + d0 + dd] = half(s); + } +} +template [[host_name("gemm_hc_up_64_64_4")]] kernel decltype(gemm_hc_up<64, 64, 4>) gemm_hc_up<64, 64, 4>; +template [[host_name("gemm_hc_up_64_32_4")]] kernel decltype(gemm_hc_up<64, 32, 4>) gemm_hc_up<64, 32, 4>; +template [[host_name("gemm_hc_up_32_64_4")]] kernel decltype(gemm_hc_up<32, 64, 4>) gemm_hc_up<32, 64, 4>; diff --git a/metal/kernels/qsa.metal b/metal/kernels/qsa.metal new file mode 100644 index 00000000..9642e58e --- /dev/null +++ b/metal/kernels/qsa.metal @@ -0,0 +1,384 @@ +// metal/kernels/qsa.metal - QSA (sparse full attention) decode for a window of tokens, between the projections. +// Contract of include/strata/kernels/qsa.hpp / qsa_select.hpp / qsa_decode_attn.hpp / kv_q8.hpp (the engine's +// native path), in a Metal layout (no paging: unified memory): +// +// qsa_prep per token t (cell pos0 + t): q heads rms_norm * q_norm, NEOX RoPE on 64 dims -> qcur; +// k rms_norm * k_norm, RoPE -> int8 KV append (fp16 scale per 64 = fp16(amax/127), rint, clamp); +// v -> int8 append; indexer q rms_norm * iq_norm, RoPE -> qidx. The indexer KEYS (last +// threadgroup, all window tokens in order): raw tail [cell % 4]; on a block completion +// pooled[b] = rope(rms_norm(mean of the block's 4 raw keys) * ik_norm, pos of the block's first cell); +// cell 0 also sets dead = rms_norm(raw) * ik_norm (the tail block's key). +// qsa_score per token, block b <= n_bid: sum over the 4 indexer heads of relu(qidx . key_b); key_b = pooled[b], +// the tail block n_bid scores `dead` and gets +1e9 when it has cells. +// qsa_topk per token: width = min(n_kv, 2051) cells; n_kv <= 2051: all; else the width cells of largest +// score (a cell inherits its block's), ties to the lowest cell, emitted ascending (radix select). +// qsa_attn split-K: (chunk of CH cells, kv head, token): 12 query heads; s = q.k / 16, chunk max m, sum l, +// acc = p . v -> partials +// qsa_merge per (head, token): log-sum-exp merge, * sigmoid(gate), written as prepared activations (xprep +// planes) for attn_output. +// +// RoPE: cos/sin from a host table [pos][32] (double precision, as build_rope_table). + +#define QH 24 +#define QKV 2 +#define QD 256 +#define QROT 64 +#define IH 4 +#define ID 128 +#define QBUDGET 2051 +#define QCH 64 + +constant int QSA_NTOK [[function_constant(3)]]; +// QSA_MROPE (function constant 24): interleaved M-RoPE (the vision path; strata/kernels/mrope.hpp, ggml IMROPE, +// sections 11/11/10): buffer 20 of qsa_prep is a table int32 [cells][3] (t, h, w), and rotary pair i (0..31) of the row +// at (pos_base + cell) rotates by the cos/sin table's row tab[(pos_base + cell) * 3 + i % 3] instead of its own - +// the pooled indexer keys too (position pos_base + 4 b of a block). Off: exactly the plain RoPE. +constant bool QSA_MROPE [[function_constant(24)]]; +constant bool qsa_mrope = is_function_constant_defined(QSA_MROPE) && QSA_MROPE; + +struct QsaArgs { + uint pos0; // the window's first cell (relative to the sequence) + uint pos_base; // absolute position of cell 0 (RoPE) + uint max_cells; + uint n_tok; + float eps; +}; + +// cache layout per layer +// kq/vq [cell][kv head][256] int8, ks/vs [cell][kv head][4] half +// tail [4][128] f32 (slot = cell % 4), dead [128], pooled [max_cells / 4 + 1][128] + +static inline float tg_sum256(float v, threadgroup float* part, ushort sg, ushort lane, ushort nsg) { + v = simd_sum(v); + if (lane == 0) part[sg] = v; + threadgroup_barrier(mem_flags::mem_threadgroup); + float t = 0.0f; + for (int i = 0; i < nsg; ++i) t += part[i]; + threadgroup_barrier(mem_flags::mem_threadgroup); + return t; +} + +// one row (width w <= 256 = threads) : out = rope((rs * x) * g) (RoPE on the first 64 dims, NEOX pairs i, i+32) +static inline float norm_rope(float x, float xhi_unused, device const float* g, threadgroup float* row, + threadgroup float* part, ushort tid, ushort sg, ushort lane, int w, float eps, + device const float2* cs, uint absp, bool rope, device const int* mtab) { + const float ss = tg_sum256(tid < w ? x * x : 0.0f, part, sg, lane, 8); + const float rs = rsqrt(ss / float(w) + eps); + const float y = tid < w ? (rs * x) * g[tid] : 0.0f; + row[tid] = y; + threadgroup_barrier(mem_flags::mem_threadgroup); + float o = y; + if (rope && tid < QROT) { + const int p = tid & 31; + const uint pp = qsa_mrope ? uint(mtab[absp * 3 + uint(p % 3)]) : absp; + const float2 c = cs[pp * 32 + p]; + const float a = row[p], b = row[p + 32]; + o = tid < 32 ? a * c.x - b * c.y : a * c.y + b * c.x; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + (void)xhi_unused; + return o; +} + +// grid (32 rows + 1, n_tok): rows 0..23 q heads, 24..25 k heads, 26..27 v heads, 28..31 indexer q heads; +// threadgroup 32 (x = 32, y = 0) is the indexer-key threadgroup. 256 threads. +kernel void qsa_prep(device const float* qfull [[buffer(0)]], device const float* kcur [[buffer(1)]], + device const float* vcur [[buffer(2)]], device const float* iqraw [[buffer(3)]], + device const float* ikraw [[buffer(4)]], device const float* qn [[buffer(5)]], + device const float* kn [[buffer(6)]], device const float* iqn [[buffer(7)]], + device const float* ikn [[buffer(8)]], device const float2* cs [[buffer(9)]], + device float* qcur [[buffer(10)]], device float* qidx [[buffer(11)]], + device char* kq [[buffer(12)]], device char* vq [[buffer(13)]], device half* ksc [[buffer(14)]], + device half* vsc [[buffer(15)]], device float* tail [[buffer(16)]], device float* dead [[buffer(17)]], + device float* pooled [[buffer(18)]], constant QsaArgs& a [[buffer(19)]], + device const int* mtab [[buffer(20)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + threadgroup float part[8]; + threadgroup float row[256]; + threadgroup float amax[8]; + const int r = int(tg.x); + if (r == 32) { + // the indexer keys, every window token in order (only threadgroup (32, 0) works) + if (tg.y != 0) return; + for (int t = 0; t < int(a.n_tok); ++t) { + const uint cell = a.pos0 + uint(t); + const float x = tid < ID ? ikraw[t * ID + tid] : 0.0f; + if (tid < ID) tail[(cell & 3) * ID + tid] = x; + threadgroup_barrier(mem_flags::mem_device); + if (cell == 0) { + const float o = norm_rope(x, 0.0f, ikn, row, part, tid, sg, lane, ID, a.eps, cs, 0, false, mtab); + if (tid < ID) dead[tid] = o; + } + if ((cell & 3) == 3) { + float m = 0.0f; + if (tid < ID) m = (((tail[tid] + tail[ID + tid]) + tail[2 * ID + tid]) + tail[3 * ID + tid]) * 0.25f; + const uint b = cell >> 2; + const float o = norm_rope(m, 0.0f, ikn, row, part, tid, sg, lane, ID, a.eps, cs, a.pos_base + 4 * b, true, mtab); + if (tid < ID) pooled[b * ID + tid] = o; + } + threadgroup_barrier(mem_flags::mem_device); + } + return; + } + const int t = int(tg.y); + const uint cell = a.pos0 + uint(t), absp = a.pos_base + cell; + if (r < QH) { + const float x = qfull[(t * QH + r) * 2 * QD + tid]; + const float o = norm_rope(x, 0.0f, qn, row, part, tid, sg, lane, QD, a.eps, cs, absp, true, mtab); + qcur[(t * QH + r) * QD + tid] = o; + } else if (r < QH + 2 * QKV) { + const bool isv = r >= QH + QKV; + const int h = r - QH - (isv ? QKV : 0); + float x = (isv ? vcur : kcur)[(t * QKV + h) * QD + tid]; + if (!isv) x = norm_rope(x, 0.0f, kn, row, part, tid, sg, lane, QD, a.eps, cs, absp, true, mtab); + // int8 with an fp16 scale per 64 values: groups = simdgroup pairs (64 threads) + float m = simd_max(fabs(x)); + if (lane == 0) amax[sg] = m; + threadgroup_barrier(mem_flags::mem_threadgroup); + const int g = tid >> 6; + m = max(amax[2 * g], amax[2 * g + 1]); + const half sh = half(m / 127.0f); + const float sf = float(sh); + int q = 0; + if (sf > 0.0f) q = clamp(int(rint(x / sf)), -127, 127); + const uint rowi = cell * QKV + uint(h); + (isv ? vq : kq)[rowi * QD + tid] = char(q); + if ((tid & 63) == 0) (isv ? vsc : ksc)[rowi * 4 + g] = sh; + } else { + const int h = r - QH - 2 * QKV; + const float x = tid < ID ? iqraw[(t * IH + h) * ID + tid] : 0.0f; + const float o = norm_rope(x, 0.0f, iqn, row, part, tid, sg, lane, ID, a.eps, cs, absp, true, mtab); + if (tid < ID) qidx[(t * IH + h) * ID + tid] = o; + } +} + +// scores [n_tok][max_blocks]; grid (ceil(max_blocks / 8), n_tok), 256 threads: a simdgroup per block. +kernel void qsa_score(device const float* qidx [[buffer(0)]], device const float* pooled [[buffer(1)]], + device const float* dead [[buffer(2)]], device float* scores [[buffer(3)]], + constant QsaArgs& a [[buffer(4)]], + uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]]) { + const int t = int(tg.y); + const uint n_kv = a.pos0 + uint(t) + 1, n_bid = n_kv >> 2; + const uint b = tg.x * 8 + sg; + if (b > n_bid) return; + device const float* key = b == n_bid ? dead : pooled + b * ID; + float k[4]; + for (int i = 0; i < 4; ++i) k[i] = key[lane + 32 * i]; + float s = 0.0f; + for (int h = 0; h < IH; ++h) { + float d = 0.0f; + for (int i = 0; i < 4; ++i) d = fma(qidx[(t * IH + h) * ID + lane + 32 * i], k[i], d); + d = simd_sum(d); + s += max(d, 0.0f); + } + if (b == n_bid && (n_kv & 3) != 0) s += 1e9f; + if (lane == 0) scores[uint(t) * (a.max_cells / 4 + 2) + b] = s; +} + +// ids [n_tok][QBUDGET], ascending. One threadgroup of 1024 threads per token. Order key of a float: larger score = +// larger key; a radix select (4 passes of 8 bits) over the blocks with weights = their cell counts finds the +// threshold key T and how many cells with key == T to take (the lowest cells first). +static inline uint okey(float f) { + const uint u = as_type(f); + return (u & 0x80000000u) ? ~u : (u | 0x80000000u); +} +kernel void qsa_topk(device const float* scores [[buffer(0)]], device int* ids [[buffer(1)]], + constant QsaArgs& a [[buffer(2)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + threadgroup atomic_uint hist[256]; + threadgroup uint sel[4]; + threadgroup uint pref[32]; + const int t = int(tg.x); + const uint n_kv = a.pos0 + uint(t) + 1, n_bid = n_kv >> 2, nb = n_bid + 1; + device int* out = ids + t * QBUDGET; + device const float* sc = scores + uint(t) * (a.max_cells / 4 + 2); + if (n_kv <= QBUDGET) { + for (uint c = tid; c < n_kv; c += 1024) out[c] = int(c); + return; + } + // radix select of the `need`-th largest cell key + uint prefix = 0, pmask = 0, need = QBUDGET; + for (int pass = 0; pass < 4; ++pass) { + const int shift = 24 - 8 * pass; + if (tid < 256) atomic_store_explicit(&hist[tid], 0u, memory_order_relaxed); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint b = tid; b < nb; b += 1024) { + const uint k = okey(sc[b]); + if ((k & pmask) == prefix) { + const uint w = b < n_bid ? 4u : (n_kv & 3u); + if (w) atomic_fetch_add_explicit(&hist[(k >> shift) & 255u], w, memory_order_relaxed); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid == 0) { + uint acc = 0, d = 0; + for (int v = 255; v >= 0; --v) { + const uint h = atomic_load_explicit(&hist[v], memory_order_relaxed); + if (acc + h >= need) { d = uint(v); break; } + acc += h; + } + sel[0] = d; + sel[1] = need - acc; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + prefix |= sel[0] << shift; + pmask |= 255u << shift; + need = sel[1]; + threadgroup_barrier(mem_flags::mem_threadgroup); + } + // T = prefix; take every cell with key > T and the first `need` cells (lowest index) with key == T, ascending. + // Pass over blocks in order of index with a prefix scan of each block's selected cell count. + const uint T = prefix; + uint base = 0, eq_taken = 0; + for (uint b0 = 0; b0 < nb; b0 += 1024) { + const uint b = b0 + tid; + uint w = 0, weq = 0; + if (b < nb) { + const uint k = okey(sc[b]); + const uint cells = b < n_bid ? 4u : (n_kv & 3u); + if (k > T) w = cells; + else if (k == T) weq = cells; + } + // equal-key cells: the lowest first, `need` of them in total + const uint eq_before = simd_prefix_exclusive_sum(weq); + if (lane == 31) pref[sg] = eq_before + weq; + threadgroup_barrier(mem_flags::mem_threadgroup); + uint eq_sg = 0; + for (int i = 0; i < int(sg); ++i) eq_sg += pref[i]; + uint eq_tot = 0; + for (int i = 0; i < 32; ++i) eq_tot += pref[i]; + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint eq0 = eq_taken + eq_sg + eq_before; + uint take_eq = 0; + if (weq && eq0 < need) take_eq = min(weq, need - eq0); + const uint mine = w + take_eq; + const uint before = simd_prefix_exclusive_sum(mine); + if (lane == 31) pref[sg] = before + mine; + threadgroup_barrier(mem_flags::mem_threadgroup); + uint off = base; + for (int i = 0; i < int(sg); ++i) off += pref[i]; + uint tot = 0; + for (int i = 0; i < 32; ++i) tot += pref[i]; + threadgroup_barrier(mem_flags::mem_threadgroup); + off += before; + for (uint c = 0; c < mine; ++c) out[off + c] = int(4 * b + c); + base += tot; + eq_taken += eq_tot; + } +} + +// partials: [n_tok][chunks][QH][QD + 2] (acc, then m, l). grid (chunks, QKV, n_tok), 256 threads. +kernel void qsa_attn(device const float* qcur [[buffer(0)]], device const char* kq [[buffer(1)]], + device const char* vq [[buffer(2)]], device const half* ksc [[buffer(3)]], + device const half* vsc [[buffer(4)]], device const int* ids [[buffer(5)]], + device float* part [[buffer(6)]], constant QsaArgs& a [[buffer(7)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + constexpr int HPG = QH / QKV; // 12 query heads per kv head + threadgroup float qs[HPG][QD]; + threadgroup float s[HPG][QCH]; + threadgroup int cid[QCH]; + const int chunk = int(tg.x), g = int(tg.y), t = int(tg.z); + const uint n_kv = a.pos0 + uint(t) + 1, width = min(n_kv, uint(QBUDGET)); + const int c0 = chunk * QCH; + const int nchunks = (QBUDGET + QCH - 1) / QCH; + device float* pp = part + ((uint(t) * nchunks + chunk) * QH) * (QD + 2); + if (uint(c0) >= width) { + // an empty chunk: m = -inf, l = 0 (the merge skips it) + for (int h = 0; h < HPG; ++h) + if (tid == 0) { pp[(g * HPG + h) * (QD + 2) + QD] = -INFINITY; pp[(g * HPG + h) * (QD + 2) + QD + 1] = 0.0f; } + return; + } + const int nc = min(QCH, int(width) - c0); + for (int h = 0; h < HPG; ++h) qs[h][tid] = qcur[(t * QH + g * HPG + h) * QD + tid]; + if (tid < QCH) cid[tid] = tid < nc ? ids[t * QBUDGET + c0 + tid] : 0; + threadgroup_barrier(mem_flags::mem_threadgroup); + // scores: 12 x 64 dots of 256; simdgroup sg takes cells sg, sg + 8, ...; lanes split the 256 dims (8 each) + for (int c = sg; c < nc; c += 8) { + const uint rowi = uint(cid[c]) * QKV + uint(g); + device const char* kr = kq + rowi * QD; + float kv[8]; + const float scl = float(ksc[rowi * 4 + (lane >> 3)]); + for (int i = 0; i < 8; ++i) kv[i] = float(kr[lane * 8 + i]) * scl; + for (int h = 0; h < HPG; ++h) { + float d = 0.0f; + for (int i = 0; i < 8; ++i) d = fma(qs[h][lane * 8 + i], kv[i], d); + d = simd_sum(d); + if (lane == 0) s[h][c] = d * 0.0625f; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // per head: max, exp, sum (simdgroup h % 8 handles heads h, h + 8) + threadgroup float mh[HPG], lh[HPG]; + for (int h = sg; h < HPG; h += 8) { + float m = -INFINITY; + for (int c = lane; c < nc; c += 32) m = max(m, s[h][c]); + m = simd_max(m); + float l = 0.0f; + for (int c = lane; c < nc; c += 32) { + const float p = exp(s[h][c] - m); + s[h][c] = p; + l += p; + } + l = simd_sum(l); + if (lane == 0) { mh[h] = m; lh[h] = l; } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // acc[h][j] = sum_c p[h][c] v[c][j]: thread = dim j + float acc[HPG]; + for (int h = 0; h < HPG; ++h) acc[h] = 0.0f; + for (int c = 0; c < nc; ++c) { + const uint rowi = uint(cid[c]) * QKV + uint(g); + const float v = float(vq[rowi * QD + tid]) * float(vsc[rowi * 4 + (tid >> 6)]); + for (int h = 0; h < HPG; ++h) acc[h] = fma(s[h][c], v, acc[h]); + } + for (int h = 0; h < HPG; ++h) { + device float* o = pp + (g * HPG + h) * (QD + 2); + o[tid] = acc[h]; + if (tid == 0) { o[QD] = mh[h]; o[QD + 1] = lh[h]; } + } +} + +// grid (QH, n_tok), 256 threads: out = merge * sigmoid(gate), as prepared activations of n = QH * QD per token +kernel void qsa_merge(device const float* part [[buffer(0)]], device const float* qfull [[buffer(1)]], + device float* xp [[buffer(2)]], constant QsaArgs& a [[buffer(3)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + threadgroup float msum[256]; + const int h = int(tg.x), t = int(tg.y); + const int nchunks = (QBUDGET + QCH - 1) / QCH; + const uint n_kv = a.pos0 + uint(t) + 1, width = min(n_kv, uint(QBUDGET)); + const int nc = int((width + QCH - 1) / QCH); + device const float* pp = part + (uint(t) * nchunks * QH + uint(h)) * (QD + 2); + float M = -INFINITY; + for (int k = 0; k < nc; ++k) M = max(M, pp[k * QH * (QD + 2) + QD]); + float L = 0.0f, o = 0.0f; + for (int k = 0; k < nc; ++k) { + device const float* q = pp + k * QH * (QD + 2); + const float e = exp(q[QD] - M); + L = fma(q[QD + 1], e, L); + o = fma(q[tid], e, o); + } + o = o / L; + const float gate = qfull[(t * QH + h) * 2 * QD + QD + tid]; + const float y = o * (1.0f / (1.0f + exp(-gate))); + // prepared planes (xprep layout) of the n = QH * QD vector + const uint n = QH * QD, plane = a.n_tok * n, d = uint(h) * QD + tid; + const int j = tid & 15; + const float q2s[8] = {1.0f, 0.25f, 0.0625f, 0.015625f, 0.00390625f, 0.0009765625f, 0.000244140625f, 0.00006103515625f}; + const float p4s[4] = {1.0f, 0.00390625f, 1.52587890625e-05f, 5.9604644775390625e-08f}; + device float* raw = xp + uint(t) * n + d; + raw[0] = y; + raw[plane] = y * q2s[j & 7]; + raw[2 * plane] = y * p4s[j & 3]; + raw[3 * plane] = (j & 1) ? y * 0.00390625f : y; + msum[tid] = y; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (j == 0) { + float s0 = 0.0f, s1 = 0.0f; + for (int k = 0; k < 16; k += 2) { s0 += msum[tid + k]; s1 += msum[tid + k + 1]; } + xp[4 * plane + uint(t) * (n / 16) + d / 16] = s0 + s1; + } +} diff --git a/metal/kernels/qsa2.metal b/metal/kernels/qsa2.metal new file mode 100644 index 00000000..8ae189b6 --- /dev/null +++ b/metal/kernels/qsa2.metal @@ -0,0 +1,289 @@ +// metal/kernels/qsa2.metal - QSA decode v2 (after qsa.metal): the same selection and attention math, more parallel. +// +// qsa_attn2 chunks of 32 cells, the 12 query heads of a kv head in 2 groups of 6: 4x the threadgroups of +// qsa_attn (at a 1K context 128 instead of 32); V loads 8 cells at a time. +// qsa_merge2 qsa_merge for that chunking. +// qsa_topk2 the digit of each radix pass found by a parallel suffix scan of the 256 bins (simdgroup prefix +// sums) instead of one thread; cells emitted from contiguous block ranges per thread after one scan. + +#define QCH2 32 +#define QHG 2 + +// partials: [n_tok][chunks2][QH][QD + 2]. grid (chunks2, QKV * QHG, n_tok), 256 threads. +kernel void qsa_attn2(device const float* qcur [[buffer(0)]], device const char* kq [[buffer(1)]], + device const char* vq [[buffer(2)]], device const half* ksc [[buffer(3)]], + device const half* vsc [[buffer(4)]], device const int* ids [[buffer(5)]], + device float* part [[buffer(6)]], constant QsaArgs& a [[buffer(7)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + constexpr int HPG = QH / QKV / QHG; // 6 + threadgroup float qs[HPG][QD]; + threadgroup float s[HPG][QCH2]; + threadgroup float mh[HPG], lh[HPG]; + threadgroup int cid[QCH2]; + const int chunk = int(tg.x), g = int(tg.y) / QHG, hg = int(tg.y) % QHG, t = int(tg.z); + const int h0 = g * (QH / QKV) + hg * HPG; + const uint n_kv = a.pos0 + uint(t) + 1, width = min(n_kv, uint(QBUDGET)); + const int c0 = chunk * QCH2; + const int nchunks = (QBUDGET + QCH2 - 1) / QCH2; + if (uint(c0) >= width) return; + device float* pp = part + ((uint(t) * nchunks + chunk) * QH) * (QD + 2); + const int nc = min(QCH2, int(width) - c0); + for (int h = 0; h < HPG; ++h) qs[h][tid] = qcur[(t * QH + h0 + h) * QD + tid]; + if (tid < QCH2) cid[tid] = tid < nc ? ids[t * QBUDGET + c0 + tid] : 0; + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int c = sg; c < nc; c += 8) { + const uint rowi = uint(cid[c]) * QKV + uint(g); + device const char4* kr = (device const char4*)(kq + rowi * QD + lane * 8); + const char4 k0 = kr[0], k1 = kr[1]; + const float scl = float(ksc[rowi * 4 + (lane >> 3)]); + const float kv[8] = {float(k0.x) * scl, float(k0.y) * scl, float(k0.z) * scl, float(k0.w) * scl, + float(k1.x) * scl, float(k1.y) * scl, float(k1.z) * scl, float(k1.w) * scl}; + for (int h = 0; h < HPG; ++h) { + float d = 0.0f; + for (int i = 0; i < 8; ++i) d = fma(qs[h][lane * 8 + i], kv[i], d); + d = simd_sum(d); + if (lane == 0) s[h][c] = d * 0.0625f; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg < HPG) { + const int h = sg; + const float sv = lane < nc ? s[h][lane] : -INFINITY; + const float m = simd_max(sv); + const float p = lane < nc ? exp(sv - m) : 0.0f; + const float l = simd_sum(p); + if (lane < nc) s[h][lane] = p; + if (lane == 0) { mh[h] = m; lh[h] = l; } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float acc[HPG]; + for (int h = 0; h < HPG; ++h) acc[h] = 0.0f; + for (int cb = 0; cb < nc; cb += 8) { + float v[8]; + const int m = min(8, nc - cb); + for (int c = 0; c < 8; ++c) { + v[c] = 0.0f; + if (c < m) { + const uint rowi = uint(cid[cb + c]) * QKV + uint(g); + v[c] = float(vq[rowi * QD + tid]) * float(vsc[rowi * 4 + (tid >> 6)]); + } + } + for (int c = 0; c < m; ++c) + for (int h = 0; h < HPG; ++h) acc[h] = fma(s[h][cb + c], v[c], acc[h]); + } + for (int h = 0; h < HPG; ++h) { + device float* o = pp + (h0 + h) * (QD + 2); + o[tid] = acc[h]; + if (tid == 0) { o[QD] = mh[h]; o[QD + 1] = lh[h]; } + } +} + +kernel void qsa_merge2(device const float* part [[buffer(0)]], device const float* qfull [[buffer(1)]], + device float* xp [[buffer(2)]], constant QsaArgs& a [[buffer(3)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + threadgroup float msum[256]; + const int h = int(tg.x), t = int(tg.y); + const int nchunks = (QBUDGET + QCH2 - 1) / QCH2; + const uint n_kv = a.pos0 + uint(t) + 1, width = min(n_kv, uint(QBUDGET)); + const int nc = int((width + QCH2 - 1) / QCH2); + device const float* pp = part + (uint(t) * nchunks * QH + uint(h)) * (QD + 2); + float M = -INFINITY; + for (int k = 0; k < nc; ++k) M = max(M, pp[k * QH * (QD + 2) + QD]); + float L = 0.0f, o = 0.0f; + for (int k = 0; k < nc; ++k) { + device const float* q = pp + k * QH * (QD + 2); + const float e = exp(q[QD] - M); + L = fma(q[QD + 1], e, L); + o = fma(q[tid], e, o); + } + o = o / L; + const float gate = qfull[(t * QH + h) * 2 * QD + QD + tid]; + const float y = o * (1.0f / (1.0f + exp(-gate))); + const uint n = QH * QD, plane = a.n_tok * n, d = uint(h) * QD + tid; + const int j = tid & 15; + const float q2s[8] = {1.0f, 0.25f, 0.0625f, 0.015625f, 0.00390625f, 0.0009765625f, 0.000244140625f, 0.00006103515625f}; + const float p4s[4] = {1.0f, 0.00390625f, 1.52587890625e-05f, 5.9604644775390625e-08f}; + device float* raw = xp + uint(t) * n + d; + raw[0] = y; + raw[plane] = y * q2s[j & 7]; + raw[2 * plane] = y * p4s[j & 3]; + raw[3 * plane] = (j & 1) ? y * 0.00390625f : y; + msum[tid] = y; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (j == 0) { + float s0 = 0.0f, s1 = 0.0f; + for (int k = 0; k < 16; k += 2) { s0 += msum[tid + k]; s1 += msum[tid + k + 1]; } + xp[4 * plane + uint(t) * (n / 16) + d / 16] = s0 + s1; + } +} + +kernel void qsa_topk2(device const float* scores [[buffer(0)]], device int* ids [[buffer(1)]], + constant QsaArgs& a [[buffer(2)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + threadgroup atomic_uint hist[256]; + threadgroup uint sgs[32], sgs2[32]; + threadgroup uint sel[2]; + const int t = int(tg.x); + const uint n_kv = a.pos0 + uint(t) + 1, n_bid = n_kv >> 2, nb = n_bid + 1; + device int* out = ids + t * QBUDGET; + device const float* sc = scores + uint(t) * (a.max_cells / 4 + 2); + if (n_kv <= QBUDGET) { + for (uint c = tid; c < n_kv; c += 1024) out[c] = int(c); + return; + } + uint prefix = 0, pmask = 0, need = QBUDGET; + for (int pass = 0; pass < 4; ++pass) { + const int shift = 24 - 8 * pass; + if (tid < 256) atomic_store_explicit(&hist[tid], 0u, memory_order_relaxed); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint b = tid; b < nb; b += 1024) { + const uint k = okey(sc[b]); + if ((k & pmask) == prefix) { + const uint w = b < n_bid ? 4u : (n_kv & 3u); + if (w) atomic_fetch_add_explicit(&hist[(k >> shift) & 255u], w, memory_order_relaxed); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // thread i < 256 holds bin 255 - i: an exclusive prefix over i = the cells of the higher digits + uint cnt = 0, ex = 0; + if (tid < 256) { + cnt = atomic_load_explicit(&hist[255 - tid], memory_order_relaxed); + ex = simd_prefix_exclusive_sum(cnt); + if (lane == 31) sgs[sg] = ex + cnt; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid < 256) { + uint above = ex; + for (int i = 0; i < int(sg); ++i) above += sgs[i]; + if (above < need && above + cnt >= need) { sel[0] = 255u - tid; sel[1] = need - above; } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + prefix |= sel[0] << shift; + pmask |= 255u << shift; + need = sel[1]; + threadgroup_barrier(mem_flags::mem_threadgroup); + } + const uint T = prefix; + const uint per = (nb + 1023) / 1024, b0 = min(nb, uint(tid) * per), b1 = min(nb, b0 + per); + uint gt = 0, eq = 0; + for (uint b = b0; b < b1; ++b) { + const uint k = okey(sc[b]); + const uint cells = b < n_bid ? 4u : (n_kv & 3u); + if (k > T) gt += cells; + else if (k == T) eq += cells; + } + const uint eqb = simd_prefix_exclusive_sum(eq); + if (lane == 31) sgs2[sg] = eqb + eq; + threadgroup_barrier(mem_flags::mem_threadgroup); + uint eq_before = eqb; + for (int i = 0; i < int(sg); ++i) eq_before += sgs2[i]; + const uint eq_take = eq_before >= need ? 0u : min(eq, need - eq_before); + const uint mine = gt + eq_take; + const uint mb = simd_prefix_exclusive_sum(mine); + if (lane == 31) sgs[sg] = mb + mine; + threadgroup_barrier(mem_flags::mem_threadgroup); + uint off = mb; + for (int i = 0; i < int(sg); ++i) off += sgs[i]; + uint left = eq_take; + for (uint b = b0; b < b1; ++b) { + const uint k = okey(sc[b]); + const uint cells = b < n_bid ? 4u : (n_kv & 3u); + uint take = 0; + if (k > T) take = cells; + else if (k == T) { take = min(cells, left); left -= take; } + for (uint c = 0; c < take; ++c) out[off + c] = int(4 * b + c); + off += take; + } +} + +// qsa_attn3: qsa_attn's chunking and partial layout (qsa_merge reads it), without a reduction per (cell, head): +// for q.k a lane owns a cell (8 simdgroups = 2 halves of the 64 cells x 4 groups of 3 heads; q from threadgroup +// memory, read by every lane alike), for p.v a thread owns a dimension. grid (33, QKV, n_tok), 256 threads. +kernel void qsa_attn3(device const float* qcur [[buffer(0)]], device const char* kq [[buffer(1)]], + device const char* vq [[buffer(2)]], device const half* ksc [[buffer(3)]], + device const half* vsc [[buffer(4)]], device const int* ids [[buffer(5)]], + device float* part [[buffer(6)]], constant QsaArgs& a [[buffer(7)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + constexpr int HPG = QH / QKV; // 12 + threadgroup float qs[HPG][QD]; + threadgroup float s[HPG][QCH]; + threadgroup float mh[HPG], lh[HPG]; + threadgroup int cid[QCH]; + const int chunk = int(tg.x), g = int(tg.y), t = int(tg.z); + const uint n_kv = a.pos0 + uint(t) + 1, width = min(n_kv, uint(QBUDGET)); + const int c0 = chunk * QCH; + const int nchunks = (QBUDGET + QCH - 1) / QCH; + device float* pp = part + ((uint(t) * nchunks + chunk) * QH) * (QD + 2); + if (uint(c0) >= width) return; + const int nc = min(QCH, int(width) - c0); + for (int h = 0; h < HPG; ++h) qs[h][tid] = qcur[(t * QH + g * HPG + h) * QD + tid]; + if (tid < QCH) cid[tid] = tid < nc ? ids[t * QBUDGET + c0 + tid] : 0; + threadgroup_barrier(mem_flags::mem_threadgroup); + { + const int half_ = sg & 1, hgrp = sg >> 1; // cells 32 * half_ + lane, heads 3 * hgrp .. + 3 + const int c = 32 * half_ + lane; + if (c < nc) { + const uint rowi = uint(cid[c]) * QKV + uint(g); + device const char4* kr = (device const char4*)(kq + rowi * QD); + float d0 = 0.0f, d1 = 0.0f, d2 = 0.0f; + for (int gq = 0; gq < 4; ++gq) { + const float scl = float(ksc[rowi * 4 + gq]); + float e0 = 0.0f, e1 = 0.0f, e2 = 0.0f; + for (int i = 0; i < 16; ++i) { + const char4 k4 = kr[gq * 16 + i]; + const int base = gq * 64 + 4 * i; + const float kv[4] = {float(k4.x), float(k4.y), float(k4.z), float(k4.w)}; + for (int e = 0; e < 4; ++e) { + e0 = fma(qs[3 * hgrp][base + e], kv[e], e0); + e1 = fma(qs[3 * hgrp + 1][base + e], kv[e], e1); + e2 = fma(qs[3 * hgrp + 2][base + e], kv[e], e2); + } + } + d0 = fma(e0, scl, d0); + d1 = fma(e1, scl, d1); + d2 = fma(e2, scl, d2); + } + s[3 * hgrp][c] = d0 * 0.0625f; + s[3 * hgrp + 1][c] = d1 * 0.0625f; + s[3 * hgrp + 2][c] = d2 * 0.0625f; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int h = sg; h < HPG; h += 8) { + float m = -INFINITY; + for (int c = lane; c < nc; c += 32) m = max(m, s[h][c]); + m = simd_max(m); + float l = 0.0f; + for (int c = lane; c < nc; c += 32) { + const float p = exp(s[h][c] - m); + s[h][c] = p; + l += p; + } + l = simd_sum(l); + if (lane == 0) { mh[h] = m; lh[h] = l; } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float acc[HPG]; + for (int h = 0; h < HPG; ++h) acc[h] = 0.0f; + for (int cb = 0; cb < nc; cb += 8) { + float v[8]; + const int m = min(8, nc - cb); + for (int c = 0; c < 8; ++c) { + v[c] = 0.0f; + if (c < m) { + const uint rowi = uint(cid[cb + c]) * QKV + uint(g); + v[c] = float(vq[rowi * QD + tid]) * float(vsc[rowi * 4 + (tid >> 6)]); + } + } + for (int c = 0; c < m; ++c) + for (int h = 0; h < HPG; ++h) acc[h] = fma(s[h][cb + c], v[c], acc[h]); + } + for (int h = 0; h < HPG; ++h) { + device float* o = pp + (g * HPG + h) * (QD + 2); + o[tid] = acc[h]; + if (tid == 0) { o[QD] = mh[h]; o[QD + 1] = lh[h]; } + } +} diff --git a/metal/kernels/qsa_prompt.metal b/metal/kernels/qsa_prompt.metal new file mode 100644 index 00000000..5b0b55d8 --- /dev/null +++ b/metal/kernels/qsa_prompt.metal @@ -0,0 +1,336 @@ +// metal/kernels/qsa_prompt.metal - QSA attention for a PROMPT chunk on the matrix units (after qsa.metal: QH, QKV, QD, +// QBUDGET, QCH, QsaArgs). The same split-K partials as qsa_attn (part [t][chunk][QH][QD + 2]: acc, then m, l), so +// qsa_merge is unchanged; per (chunk of QCH = 64 selected cells, kv head g, token t) one simdgroup: +// S[12 x 64] = Qh[12 x 256] . K^T / 16 single-simdgroup matmul2d, K (int8 * fp16 scale per 64) decoded into +// the right-input cooperative tensor, 32 dims a step +// per head: m = max, p = exp(s - m), l = sum p (fp32, through threadgroup memory), P -> fp16 +// acc[12 x 256] = P[12 x 64] . V[64 x 256] four 64-dim matmuls, V decoded into the right input +// The operands are fp16 (q rounded from fp32; k, v = int8 * scale rounded): to rounding of qsa_attn's fp32. +#include +using namespace mpp::tensor_ops; +#ifndef STRATA_COOP_K4 +#define STRATA_COOP_K4 +// function constant 7: the right-input cooperative tensor holds runs of 4 consecutive k at one n per lane (the M5's +// layout; tests/coop_layout). false (the M4: runs of 2 n at one k): every element decoded on its own. +constant bool COOP_K4 [[function_constant(7)]]; +constant bool coop_k4 = is_function_constant_defined(COOP_K4) ? COOP_K4 : true; +#endif + +// a bisection probe (function constant 8): stop at stage n and write m = n (1: after the ids, 2: after S, 3: after +// the softmax); 0 = normal +constant int QSA_STOP [[function_constant(8)]]; +constant int qsa_stop = is_function_constant_defined(QSA_STOP) ? QSA_STOP : 0; + +// grid (chunks, QKV, n_tok), 32 threads. qh: the q heads as fp16 [t][QH][QD] (qcur rounded). +kernel void qsa_attn_mm(device const half* qh [[buffer(0)]], device const char* kq [[buffer(1)]], + device const char* vq [[buffer(2)]], device const half* ksc [[buffer(3)]], + device const half* vsc [[buffer(4)]], device const int* ids [[buffer(5)]], + device float* part [[buffer(6)]], constant QsaArgs& a [[buffer(7)]], + uint3 tg [[threadgroup_position_in_grid]], ushort lane [[thread_index_in_simdgroup]]) { + constexpr int HPG = QH / QKV, NCH = (QBUDGET + QCH - 1) / QCH; + threadgroup float s[16 * QCH]; + threadgroup half p[16 * QCH]; + threadgroup int cid[QCH]; + threadgroup half vs[QCH][4]; + const int chunk = int(tg.x), g = int(tg.y), t = int(tg.z); + const uint n_kv = a.pos0 + uint(t) + 1, width = min(n_kv, uint(QBUDGET)); + const int c0 = chunk * QCH; + device float* pp = part + ((uint(t) * NCH + chunk) * QH + g * HPG) * (QD + 2); + if (uint(c0) >= width) { + if (lane < HPG) { pp[lane * (QD + 2) + QD] = -INFINITY; pp[lane * (QD + 2) + QD + 1] = 0.0f; } + return; + } + const int nc = min(QCH, int(width) - c0); + for (int c = lane; c < QCH; c += 32) { + const int id = c < nc ? ids[t * QBUDGET + c0 + c] : -1; + cid[c] = id; + for (int j = 0; j < 4; ++j) vs[c][j] = id >= 0 ? vsc[(uint(id) * QKV + g) * 4 + j] : half(0.0f); + } + simdgroup_barrier(mem_flags::mem_threadgroup); + if (qsa_stop == 1) { if (lane < HPG) { pp[lane * (QD + 2) + QD] = 1.0f; pp[lane * (QD + 2) + QD + 1] = 1.0f; } return; } + // ---- S = Q K^T + { + constexpr auto desc = matmul2d_descriptor(16, QCH, 32, false, true, false, matmul2d_descriptor::mode::multiply_accumulate); + matmul2d op; + tensor, tensor_inline> tQ((device half*)qh + (uint(t) * QH + g * HPG) * QD, + dextents(QD, HPG)); + auto rk = op.template get_right_input_cooperative_tensor(); + auto tA = tQ.template slice<32, 16>(0, 0); + auto acc = op.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t, __tensor_ops_detail::__remove_addrspace_t, float>(); + for (uint16_t i = 0; i < acc.get_capacity(); ++i) + if (acc.is_valid_element(i)) acc[i] = 0.0f; + for (int k0 = 0; k0 < QD; k0 += 32) { + if (!coop_k4) { + for (uint16_t i = 0; i < rk.get_capacity(); ++i) { + const auto ix = rk.get_multidimensional_index(i); + const int k = k0 + ix[0], id = cid[ix[1]]; + const uint row = uint(id) * QKV + g; + rk[i] = id >= 0 ? half(float(kq[row * QD + k]) * float(ksc[row * 4 + (k >> 6)])) : half(0.0f); + } + } else +#pragma clang loop unroll(full) + for (uint16_t i = 0; i < rk.get_capacity(); i += 4) { + const auto ix = rk.get_multidimensional_index(i); + const int k = k0 + ix[0], c = ix[1], id = cid[c]; + half4 w = half4(0.0h); + if (id >= 0) { + const uint row = uint(id) * QKV + g; + const char4 q4 = *(device const char4*)(kq + row * QD + k); + w = half4(float4(q4) * float(ksc[row * 4 + (k >> 6)])); + } + rk[i] = w.x; rk[i + 1] = w.y; rk[i + 2] = w.z; rk[i + 3] = w.w; + } + tA = tQ.template slice<32, 16>(k0, 0); + op.run(tA, rk, acc); + } + tensor, tensor_inline> tS(s, dextents(QCH, 16)); + acc.store(tS); + } + simdgroup_barrier(mem_flags::mem_threadgroup); + if (qsa_stop == 2) { if (lane < HPG) { pp[lane * (QD + 2) + QD] = 2.0f; pp[lane * (QD + 2) + QD + 1] = 1.0f; } return; } + // ---- softmax pieces per head (lane = head for the reductions; 12 heads) + float mh = -INFINITY, lh = 0.0f; + if (lane < HPG) { + for (int c = 0; c < nc; ++c) mh = max(mh, s[lane * QCH + c] * 0.0625f); + for (int c = 0; c < QCH; ++c) { + const float e = c < nc ? exp(s[lane * QCH + c] * 0.0625f - mh) : 0.0f; + lh += e; + p[lane * QCH + c] = half(e); + } + } else if (lane < 16) { + for (int c = 0; c < QCH; ++c) p[lane * QCH + c] = half(0.0f); + } + simdgroup_barrier(mem_flags::mem_threadgroup); + if (qsa_stop == 3) { if (lane < HPG) { pp[lane * (QD + 2) + QD] = 3.0f; pp[lane * (QD + 2) + QD + 1] = 1.0f; } return; } + // ---- acc = P V, 64 dims at a time + { + // K = 32 cells a run (two runs a 64-cell chunk): K = 64 runs compute garbage on the M4 + constexpr auto desc = matmul2d_descriptor(16, 64, 32, false, true, false, matmul2d_descriptor::mode::multiply_accumulate); + matmul2d op; + tensor, tensor_inline> tP(p, dextents(QCH, 16)); + tensor, tensor_inline> tO(pp, dextents(QD + 2, HPG)); + for (int d0 = 0; d0 < QD; d0 += 64) { + auto rv = op.template get_right_input_cooperative_tensor(); + auto tPh = tP.template slice<32, 16>(0, 0); + auto acc = op.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t, __tensor_ops_detail::__remove_addrspace_t, float>(); + for (uint16_t i = 0; i < acc.get_capacity(); ++i) + if (acc.is_valid_element(i)) acc[i] = 0.0f; + for (int c0 = 0; c0 < QCH; c0 += 32) { +#pragma clang loop unroll(full) + for (uint16_t i = 0; i < rv.get_capacity(); ++i) { + const auto ix = rv.get_multidimensional_index(i); // (cell, dim) + const int c = c0 + ix[0], d = d0 + ix[1], id = cid[c]; + rv[i] = id >= 0 ? half(float(vq[(uint(id) * QKV + g) * QD + d]) * float(vs[c][d >> 6])) : half(0.0f); + } + tPh = tP.template slice<32, 16>(c0, 0); + op.run(tPh, rv, acc); + } + if (qsa_stop == 4) { // the bisection: the old direct store into the 258-float rows + auto mO = tO.slice(d0, 0); + acc.store(mO); + continue; + } + // through threadgroup memory (s is free now): a matmul2d store into rows of QD + 2 floats loses the + // whole threadgroup on the M4 + tensor, tensor_inline> tT(s, dextents(64, 16)); + simdgroup_barrier(mem_flags::mem_threadgroup); + acc.store(tT); + simdgroup_barrier(mem_flags::mem_threadgroup); + for (int it = lane; it < HPG * 64; it += 32) pp[(it >> 6) * (QD + 2) + d0 + (it & 63)] = s[it]; + } + } + if (lane < HPG) { pp[lane * (QD + 2) + QD] = mh; pp[lane * (QD + 2) + QD + 1] = lh; } +} + +// qcur (fp32) -> fp16 for qsa_attn_mm +kernel void qsa_q_f16(device const float* q [[buffer(0)]], device half* qh [[buffer(1)]], constant uint& n [[buffer(2)]], + uint gid [[thread_position_in_grid]]) { + if (gid < n) qh[gid] = half(q[gid]); +} + +// qsa_score as a GEMM (fp32 operands, so the selection sees qsa_score's values to fp32 rounding): S[(t, h)][b] = +// qidx[t][h] . pooled[b] for 16 tokens x IH heads (64 rows) by 64 blocks a threadgroup; the epilogue sums relu over +// the heads. The tail block n_bid (the `dead` key, + 1e9 when it has cells) and blocks past it are left to the +// scalar path: the tail is scored here by one simdgroup a token; blocks > n_bid are not written (qsa_topk reads +// b <= n_bid). grid (ceil(max blocks / 64), ceil(T / 16)), 128 threads. +kernel void qsa_score_mm(device const float* qidx [[buffer(0)]], device const float* pooled [[buffer(1)]], + device const float* dead [[buffer(2)]], device float* scores [[buffer(3)]], + constant QsaArgs& a [[buffer(4)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + threadgroup float ot[64 * 64]; + const int b0 = int(tg.x) * 64, t0 = int(tg.y) * 16; + const uint nb_all = (a.pos0 + a.n_tok) / 4 + 1; // blocks any token of the chunk can score + tensor, tensor_inline> tQ((device float*)qidx, dextents(ID, int(a.n_tok) * IH)); + tensor, tensor_inline> tK((device float*)pooled, dextents(ID, int(nb_all))); + tensor, tensor_inline> tO(ot, dextents(64, 64)); + constexpr auto desc = matmul2d_descriptor(64, 64, dynamic_length_v, false, true, false); + matmul2d> op; + auto mA = tQ.slice(0, t0 * IH); + auto mB = tK.slice(0, b0); + op.run(mA, mB, tO); + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint stride = a.max_cells / 4 + 2; + for (int idx = tid; idx < 16 * 64; idx += 128) { + const int tt = idx >> 6, j = idx & 63, t = t0 + tt, b = b0 + j; + if (t >= int(a.n_tok)) continue; + const uint n_kv = a.pos0 + uint(t) + 1, n_bid = n_kv >> 2; + if (uint(b) >= n_bid) continue; + float s = 0.0f; + for (int h = 0; h < IH; ++h) s += max(ot[(tt * IH + h) * 64 + j], 0.0f); + scores[uint(t) * stride + b] = s; + } + // the tail block of each token in this threadgroup's block range (the first column threadgroup does it) + if (tg.x == 0) + for (int tt = sg; tt < 16; tt += 4) { + const int t = t0 + tt; + if (t >= int(a.n_tok)) break; + const uint n_kv = a.pos0 + uint(t) + 1, n_bid = n_kv >> 2; + float k[4]; + for (int i = 0; i < 4; ++i) k[i] = dead[lane + 32 * i]; + float s = 0.0f; + for (int h = 0; h < IH; ++h) { + float d = 0.0f; + for (int i = 0; i < 4; ++i) d = fma(qidx[(t * IH + h) * ID + lane + 32 * i], k[i], d); + d = simd_sum(d); + s += max(d, 0.0f); + } + if ((n_kv & 3) != 0) s += 1e9f; + if (lane == 0) scores[uint(t) * stride + n_bid] = s; + } +} + +// qsa_flash: the whole attention of a (kv head g, token t) in one threadgroup (no split-K partials, no merge): the +// width selected cells in chunks of 64 with an online softmax; 4 simdgroups, simdgroup s owns dims 64 s .. 64 s + 63 +// (its slice of S's K sum and its 64 output dims). Out: xq = (acc / l) * sigmoid(gate) as fp16 (attn_output's GEMM +// operand). grid (QKV, n_tok), 128 threads. +kernel void qsa_flash(device const half* qh [[buffer(0)]], device const char* kq [[buffer(1)]], + device const char* vq [[buffer(2)]], device const half* ksc [[buffer(3)]], + device const half* vsc [[buffer(4)]], device const int* ids [[buffer(5)]], + device const float* qfull [[buffer(6)]], device half* xqh [[buffer(7)]], constant QsaArgs& a [[buffer(8)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + constexpr int HPG = QH / QKV; + threadgroup float sp[4][16 * QCH]; + threadgroup half p[16 * QCH]; + threadgroup int cid[QCH]; + threadgroup float vs[QCH]; + threadgroup float fac[16], lsum[16], mrun[16]; + const int g = int(tg.x), t = int(tg.y); + const uint n_kv = a.pos0 + uint(t) + 1, width = min(n_kv, uint(QBUDGET)); + const int nch = int((width + QCH - 1) / QCH); + if (tid < 16) { mrun[tid] = -INFINITY; lsum[tid] = 0.0f; } + constexpr auto dS = matmul2d_descriptor(16, QCH, 32, false, true, false, matmul2d_descriptor::mode::multiply_accumulate); + constexpr auto dO = matmul2d_descriptor(16, 64, 32, false, true, false, matmul2d_descriptor::mode::multiply_accumulate); + matmul2d opS; + matmul2d opO; + tensor, tensor_inline> tQ((device half*)qh + (uint(t) * QH + g * HPG) * QD, + dextents(QD, HPG)); + tensor, tensor_inline> tP(p, dextents(QCH, 16)); + auto rv = opO.template get_right_input_cooperative_tensor(); + auto tPh = tP.template slice<32, 16>(0, 0); + auto acc = opO.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t, + __tensor_ops_detail::__remove_addrspace_t, float>(); + auto tot = acc; // the running output; acc takes one chunk (fresh each chunk: on the M4 a run does not accumulate + // into elements rescaled in place) + for (uint16_t i = 0; i < acc.get_capacity(); ++i) + if (acc.is_valid_element(i)) tot[i] = 0.0f; + const int d0 = sg * 64; + for (int ch = 0; ch < nch; ++ch) { + const int c0 = ch * QCH, nc = min(QCH, int(width) - c0); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid < QCH) { + const int id = tid < nc ? ids[t * QBUDGET + c0 + tid] : -1; + cid[tid] = id; + vs[tid] = id >= 0 ? float(vsc[(uint(id) * QKV + g) * 4 + sg * 0]) : 0.0f; // (per-simdgroup scale below) + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // S partial over this simdgroup's 64 dims + { + auto rk = opS.template get_right_input_cooperative_tensor(); + auto tA = tQ.template slice<32, 16>(d0, 0); + auto s = opS.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t, + __tensor_ops_detail::__remove_addrspace_t, float>(); + for (uint16_t i = 0; i < s.get_capacity(); ++i) + if (s.is_valid_element(i)) s[i] = 0.0f; + for (int k0 = d0; k0 < d0 + 64; k0 += 32) { + if (!coop_k4) { + for (uint16_t i = 0; i < rk.get_capacity(); ++i) { + const auto ix = rk.get_multidimensional_index(i); + const int k = k0 + ix[0], id = cid[ix[1]]; + const uint row = uint(id) * QKV + g; + rk[i] = id >= 0 ? half(float(kq[row * QD + k]) * float(ksc[row * 4 + (k >> 6)])) : half(0.0f); + } + } else +#pragma clang loop unroll(full) + for (uint16_t i = 0; i < rk.get_capacity(); i += 4) { + const auto ix = rk.get_multidimensional_index(i); + const int k = k0 + ix[0], c = ix[1], id = cid[c]; + half4 w = half4(0.0h); + if (id >= 0) { + const uint row = uint(id) * QKV + g; + const char4 q4 = *(device const char4*)(kq + row * QD + k); + w = half4(float4(q4) * float(ksc[row * 4 + (k >> 6)])); + } + rk[i] = w.x; rk[i + 1] = w.y; rk[i + 2] = w.z; rk[i + 3] = w.w; + } + tA = tQ.template slice<32, 16>(k0, 0); + opS.run(tA, rk, s); + } + tensor, tensor_inline> tS(sp[sg], dextents(QCH, 16)); + s.store(tS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // online softmax per head row: simdgroup 0, lane = row + if (sg == 0 && lane < 16) { + if (lane < HPG) { + float m = mrun[lane]; + for (int c = 0; c < nc; ++c) { + const int q = lane * QCH + c; + m = max(m, (((sp[0][q] + sp[1][q]) + (sp[2][q] + sp[3][q])) * 0.0625f)); + } + const float f = exp(mrun[lane] - m); + float l = lsum[lane] * f; + for (int c = 0; c < QCH; ++c) { + const int q = lane * QCH + c; + const float e = c < nc ? exp(((sp[0][q] + sp[1][q]) + (sp[2][q] + sp[3][q])) * 0.0625f - m) : 0.0f; + l += e; + p[q] = half(e); + } + mrun[lane] = m; + lsum[lane] = l; + fac[lane] = f; + } else { + for (int c = 0; c < QCH; ++c) p[lane * QCH + c] = half(0.0f); + fac[lane] = 0.0f; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // rescale this simdgroup's accumulator rows, then acc += P V over its 64 dims + for (uint16_t i = 0; i < acc.get_capacity(); ++i) + if (acc.is_valid_element(i)) acc[i] = 0.0f; + for (int c0 = 0; c0 < QCH; c0 += 32) { // K = 32 cells a run (K = 64 is wrong on the M4) +#pragma clang loop unroll(full) + for (uint16_t i = 0; i < rv.get_capacity(); ++i) { + const auto ix = rv.get_multidimensional_index(i); // (cell, dim) + const int c = c0 + ix[0], d = d0 + ix[1], id = cid[c]; + rv[i] = id >= 0 ? half(float(vq[(uint(id) * QKV + g) * QD + d]) * float(vsc[(uint(id) * QKV + g) * 4 + sg])) : half(0.0f); + } + tPh = tP.template slice<32, 16>(c0, 0); + opO.run(tPh, rv, acc); + } + for (uint16_t i = 0; i < acc.get_capacity(); ++i) + if (acc.is_valid_element(i)) tot[i] = fma(tot[i], fac[acc.get_multidimensional_index(i)[1]], acc[i]); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint16_t i = 0; i < acc.get_capacity(); ++i) + if (acc.is_valid_element(i)) { + const auto ix = acc.get_multidimensional_index(i); // (dim, row) + const int h = ix[1], d = d0 + ix[0]; + if (h < HPG) { + const int hh = g * HPG + h; + const float gate = qfull[(uint(t) * QH + hh) * 2 * QD + QD + d]; + xqh[(uint(t) * QH + hh) * QD + d] = half(tot[i] / lsum[h] * (1.0f / (1.0f + exp(-gate)))); + } + } +} diff --git a/metal/kernels/quant.metal b/metal/kernels/quant.metal new file mode 100644 index 00000000..51fecca7 --- /dev/null +++ b/metal/kernels/quant.metal @@ -0,0 +1,313 @@ +// metal/kernels/quant.metal - the weight formats as "units": a unit is UNIT consecutive weights of one row that one +// SIMD lane decodes at a time into raw values q[0..UNIT) and one scale s, so that the unit's dot with x is +// s * sum(q[j] * x[j]). Every GEMV kernel (moe.metal, gemv.metal) is written once over these. +// +// Decode rules transcribed from ggml-quants.c dequantize_row_* (3cf03257) and Strata's Q2_0 contract +// (docs/q2_0-contract.md); the grids and sign tables are ggml-common.h's (prepended by the runtime). The tables a +// format needs are copied to threadgroup memory once per threadgroup (constant-memory lookups with divergent indices +// serialise on Apple GPUs). +// +// Blocks start at 2-byte aligned addresses (18, 66, 74, 82, 98, 110 bytes), so every multi-byte field is read as +// ushorts. + +#define T_Q4_0 2 +#define T_Q3_K 11 +#define T_BF16 30 +#define T_F32 0 +#define T_Q5_0 6 +#define T_Q5_1 7 +#define T_Q8_0 8 +#define T_Q4_K 12 +#define T_Q5_K 13 +#define T_Q6_K 14 +#define T_IQ2_XXS 16 +#define T_IQ2_XS 17 +#define T_IQ3_XXS 18 +#define T_IQ4_NL 20 +#define T_IQ3_S 21 +#define T_IQ2_S 22 +#define T_IQ4_XS 23 +#define T_Q2_0 42 +#define T_Q2_0R 142 // Q2_0 read with raw activations (codes - 1 in the decoder; no prepared x needed) + +template struct fmt; +// QK block elements, BB block bytes, UNIT weights per unit, TAB words of threadgroup table +template <> struct fmt { enum { QK = 64, BB = 18, UNIT = 16, TAB = 1 }; }; +template <> struct fmt { enum { QK = 64, BB = 18, UNIT = 16, TAB = 1 }; }; +template <> struct fmt { enum { QK = 256, BB = 98, UNIT = 16, TAB = 256 + 32 }; }; +template <> struct fmt { enum { QK = 256, BB = 66, UNIT = 16, TAB = 512 + 32 }; }; +template <> struct fmt { enum { QK = 256, BB = 74, UNIT = 16, TAB = 1024 + 32 }; }; +template <> struct fmt { enum { QK = 256, BB = 82, UNIT = 16, TAB = 2048 + 32 }; }; +template <> struct fmt { enum { QK = 256, BB = 110, UNIT = 16, TAB = 512 + 32 }; }; +template <> struct fmt { enum { QK = 32, BB = 18, UNIT = 32, TAB = 256 }; }; +template <> struct fmt { enum { QK = 256, BB = 136, UNIT = 32, TAB = 256 }; }; +template <> struct fmt { enum { QK = 256, BB = 110, UNIT = 32, TAB = 1 }; }; +template <> struct fmt { enum { QK = 256, BB = 144, UNIT = 32, TAB = 1 }; }; +template <> struct fmt { enum { QK = 256, BB = 176, UNIT = 32, TAB = 1 }; }; +template <> struct fmt { enum { QK = 256, BB = 210, UNIT = 32, TAB = 1 }; }; +template <> struct fmt { enum { QK = 16, BB = 32, UNIT = 16, TAB = 1 }; }; +template <> struct fmt { enum { QK = 16, BB = 64, UNIT = 16, TAB = 1 }; }; +template <> struct fmt { enum { QK = 32, BB = 34, UNIT = 32, TAB = 1 }; }; +template <> struct fmt { enum { QK = 32, BB = 18, UNIT = 32, TAB = 1 }; }; +template <> struct fmt { enum { QK = 32, BB = 22, UNIT = 32, TAB = 1 }; }; +template <> struct fmt { enum { QK = 32, BB = 24, UNIT = 32, TAB = 1 }; }; + +static inline uint rd32(device const uchar* p) { + device const ushort* s = (device const ushort*)p; + return uint(s[0]) | (uint(s[1]) << 16); +} +static inline float rdh(device const uchar* p) { return float(*(device const half*)p); } + +// ---- threadgroup tables ------------------------------------------------------------------------------------------- +// layout in `tab` (uint words): [0, G) the grid, [G, G + 32) ksigns_iq2xs as bytes; IQ4_NL/XS: 16 floats. +template static inline void load_tab(threadgroup uint* tab, ushort tid, ushort nth); + +// QUANT_CTAB (function constant 23): the i-quant grids and the sign table read from ggml-common's constant arrays +// instead of a threadgroup copy (no table load and no barrier wait at the threadgroup's start); the same values. +constant bool QUANT_CTAB [[function_constant(23)]]; +constant bool ctab = is_function_constant_defined(QUANT_CTAB) && QUANT_CTAB; +static inline uint ksg(threadgroup const uint* tab, int at, uint i) { + return ctab ? uint(ksigns_iq2xs[i]) : uint(((threadgroup const uchar*)(tab + at))[i]); +} +static inline uint g_iq3xxs(threadgroup const uint* tab, uint i) { return ctab ? iq3xxs_grid[i] : tab[i]; } +static inline uint g_iq3s(threadgroup const uint* tab, uint i) { return ctab ? iq3s_grid[i] : tab[i]; } +static inline uint g_iq2xxs(threadgroup const uint* tab, uint i, int w) { return ctab ? uint(iq2xxs_grid[i] >> (32 * w)) : tab[2 * i + w]; } +static inline uint g_iq2xs(threadgroup const uint* tab, uint i, int w) { return ctab ? uint(iq2xs_grid[i] >> (32 * w)) : tab[2 * i + w]; } +static inline uint g_iq2s(threadgroup const uint* tab, uint i, int w) { return ctab ? uint(iq2s_grid[i] >> (32 * w)) : tab[2 * i + w]; } + +template <> inline void load_tab(threadgroup uint*, ushort, ushort) {} +template <> inline void load_tab(threadgroup uint*, ushort, ushort) {} +template <> inline void load_tab(threadgroup uint*, ushort, ushort) {} +template <> inline void load_tab(threadgroup uint*, ushort, ushort) {} +template <> inline void load_tab(threadgroup uint*, ushort, ushort) {} +template <> inline void load_tab(threadgroup uint*, ushort, ushort) {} +template <> inline void load_tab(threadgroup uint*, ushort, ushort) {} +template <> inline void load_tab(threadgroup uint*, ushort, ushort) {} +template <> inline void load_tab(threadgroup uint*, ushort, ushort) {} +template <> inline void load_tab(threadgroup uint*, ushort, ushort) {} +template <> inline void load_tab(threadgroup uint*, ushort, ushort) {} +template <> inline void load_tab(threadgroup uint*, ushort, ushort) {} + +static inline void load_signs(threadgroup uint* tab, int at, ushort tid, ushort nth) { + threadgroup uchar* s = (threadgroup uchar*)(tab + at); + for (int i = tid; i < 128; i += nth) s[i] = ksigns_iq2xs[i]; +} +template <> inline void load_tab(threadgroup uint* tab, ushort tid, ushort nth) { + if (ctab) return; + for (int i = tid; i < 256; i += nth) tab[i] = iq3xxs_grid[i]; + load_signs(tab, 256, tid, nth); +} +template <> inline void load_tab(threadgroup uint* tab, ushort tid, ushort nth) { + if (ctab) return; + for (int i = tid; i < 512; i += nth) tab[i] = iq3s_grid[i]; + load_signs(tab, 512, tid, nth); +} +template <> inline void load_tab(threadgroup uint* tab, ushort tid, ushort nth) { + if (ctab) return; + for (int i = tid; i < 256; i += nth) { tab[2 * i] = uint(iq2xxs_grid[i]); tab[2 * i + 1] = uint(iq2xxs_grid[i] >> 32); } + load_signs(tab, 512, tid, nth); +} +template <> inline void load_tab(threadgroup uint* tab, ushort tid, ushort nth) { + if (ctab) return; + for (int i = tid; i < 512; i += nth) { tab[2 * i] = uint(iq2xs_grid[i]); tab[2 * i + 1] = uint(iq2xs_grid[i] >> 32); } + load_signs(tab, 1024, tid, nth); +} +template <> inline void load_tab(threadgroup uint* tab, ushort tid, ushort nth) { + if (ctab) return; + for (int i = tid; i < 1024; i += nth) { tab[2 * i] = uint(iq2s_grid[i]); tab[2 * i + 1] = uint(iq2s_grid[i] >> 32); } + load_signs(tab, 2048, tid, nth); +} +// IQ4: a byte -> (codebook[low nibble], codebook[high nibble]) as half2, so one lookup gives two weights +template <> inline void load_tab(threadgroup uint* tab, ushort tid, ushort nth) { + for (int i = tid; i < 256; i += nth) + tab[i] = as_type(half2(half(kvalues_iq4nl[i & 15]), half(kvalues_iq4nl[i >> 4]))); +} +template <> inline void load_tab(threadgroup uint* tab, ushort tid, ushort nth) { + load_tab(tab, tid, nth); +} + +// ---- unit decoders: return s, fill q[UNIT] ------------------------------------------------------------------------ +// ui = unit index inside the block (0 .. QK/UNIT - 1). +template static inline float deq(device const uchar* b, int ui, thread float* q, threadgroup const uint* tab); + +// Q2_0: 64 = 4 units of 16; code c (2 bits, LSB first) -> c - 1; scale d. +template <> inline float deq(device const uchar* b, int ui, thread float* q, threadgroup const uint*) { + device const ushort* p = (device const ushort*)(b + 2 + 4 * ui); + const ushort a = p[0], c = p[1]; + for (int j = 0; j < 8; ++j) { + q[j] = float((a >> (2 * j)) & 3) - 1.0f; + q[8 + j] = float((c >> (2 * j)) & 3) - 1.0f; + } + return rdh(b); +} + +// 8 signed grid bytes from a 4-byte grid word pair helper +static inline void put_signed4(thread float* q, uint g, uint s) { + const uchar4 v = as_type(g); + q[0] = (s & 1) ? -float(v[0]) : float(v[0]); + q[1] = (s & 2) ? -float(v[1]) : float(v[1]); + q[2] = (s & 4) ? -float(v[2]) : float(v[2]); + q[3] = (s & 8) ? -float(v[3]) : float(v[3]); +} + +// IQ3_XXS: 256 = 8 x 32; unit = half of a 32 (two grid pairs). +template <> inline float deq(device const uchar* b, int ui, thread float* q, threadgroup const uint* tab) { + const int ib = ui >> 1, h = ui & 1; + const uint aux = rd32(b + 2 + 64 + 4 * ib); + device const uchar* qs = b + 2 + 8 * ib + 4 * h; + for (int l2 = 0; l2 < 2; ++l2) { + const int l = 2 * h + l2; + const uint s = ksg(tab, 256, (aux >> (7 * l)) & 127); + put_signed4(q + 8 * l2, g_iq3xxs(tab, qs[2 * l2]), s); + put_signed4(q + 8 * l2 + 4, g_iq3xxs(tab, qs[2 * l2 + 1]), s >> 4); + } + return rdh(b) * (0.5f + float(aux >> 28)) * 0.5f; +} + +// IQ2_XXS: per 32: two u32 (4 grid indices, then 4 x 7 sign bits + 4-bit scale). +template <> inline float deq(device const uchar* b, int ui, thread float* q, threadgroup const uint* tab) { + const int ib = ui >> 1, h = ui & 1; + const uint a0 = rd32(b + 2 + 8 * ib), a1 = rd32(b + 2 + 8 * ib + 4); + for (int l2 = 0; l2 < 2; ++l2) { + const int l = 2 * h + l2; + const uint idx = (a0 >> (8 * l)) & 255; + const uint s = ksg(tab, 512, (a1 >> (7 * l)) & 127); + put_signed4(q + 8 * l2, g_iq2xxs(tab, idx, 0), s); + put_signed4(q + 8 * l2 + 4, g_iq2xxs(tab, idx, 1), s >> 4); + } + return rdh(b) * (0.5f + float(a1 >> 28)) * 0.25f; +} + +// IQ2_XS: uint16 qs[32] (9-bit grid index + 7-bit sign index), scales[8] nibbles. +template <> inline float deq(device const uchar* b, int ui, thread float* q, threadgroup const uint* tab) { + const int ib = ui >> 1, h = ui & 1; + device const ushort* qs = (device const ushort*)(b + 2); + for (int l2 = 0; l2 < 2; ++l2) { + const uint v = qs[4 * ib + 2 * h + l2]; + const uint idx = v & 511, s = ksg(tab, 1024, v >> 9); + put_signed4(q + 8 * l2, g_iq2xs(tab, idx, 0), s); + put_signed4(q + 8 * l2 + 4, g_iq2xs(tab, idx, 1), s >> 4); + } + const uint sc = b[66 + ib]; + return rdh(b) * (0.5f + float((sc >> (4 * h)) & 15)) * 0.25f; +} + +// IQ2_S: qs[32] low 8 bits of the 10-bit index, signs[32], qh[8] (2 high bits per group of 8), scales[8]. +template <> inline float deq(device const uchar* b, int ui, thread float* q, threadgroup const uint* tab) { + const int ib = ui >> 1, h = ui & 1; + const uint qh = b[66 + ib]; + for (int l2 = 0; l2 < 2; ++l2) { + const int l = 2 * h + l2; + const uint idx = uint(b[2 + 4 * ib + l]) | ((qh << (8 - 2 * l)) & 0x300); + const uint s = b[2 + 32 + 4 * ib + l]; + put_signed4(q + 8 * l2, g_iq2s(tab, idx, 0), s); + put_signed4(q + 8 * l2 + 4, g_iq2s(tab, idx, 1), s >> 4); + } + const uint sc = b[74 + ib]; + return rdh(b) * (0.5f + float((sc >> (4 * h)) & 15)) * 0.25f; +} + +// IQ3_S: qs[64] low 8 bits of 9-bit indices, qh[8], signs[32], scales[4] (nibble per 32). +template <> inline float deq(device const uchar* b, int ui, thread float* q, threadgroup const uint* tab) { + const int ib = ui >> 1, h = ui & 1; + const uint qh = b[66 + ib]; + for (int l2 = 0; l2 < 2; ++l2) { + const int l = 2 * h + l2; + const uint i1 = uint(b[2 + 8 * ib + 2 * l]) | ((qh << (8 - 2 * l)) & 256); + const uint i2 = uint(b[2 + 8 * ib + 2 * l + 1]) | ((qh << (7 - 2 * l)) & 256); + const uint s = b[74 + 4 * ib + l]; + put_signed4(q + 8 * l2, g_iq3s(tab, i1), s); + put_signed4(q + 8 * l2 + 4, g_iq3s(tab, i2), s >> 4); + } + const uint sc = b[106 + (ib >> 1)]; + return rdh(b) * float(1 + 2 * ((sc >> (4 * (ib & 1))) & 15)); +} + +// IQ4_NL: 32 = 1 unit; low nibbles are elements 0..15, high 16..31 (one half2 lookup per byte). +template <> inline float deq(device const uchar* b, int, thread float* q, threadgroup const uint* tab) { + device const ushort* p = (device const ushort*)(b + 2); + for (int j = 0; j < 8; ++j) { + const ushort v = p[j]; + const half2 w0 = as_type(tab[v & 255]), w1 = as_type(tab[v >> 8]); + q[2 * j] = float(w0.x); + q[2 * j + 16] = float(w0.y); + q[2 * j + 1] = float(w1.x); + q[2 * j + 17] = float(w1.y); + } + return rdh(b); +} + +// IQ4_XS: 256 = 8 units of 32; 6-bit scale from scales_l nibble + 2 bits of scales_h, minus 32. +template <> inline float deq(device const uchar* b, int ui, thread float* q, threadgroup const uint* tab) { + device const ushort* p = (device const ushort*)(b + 8 + 16 * ui); + for (int j = 0; j < 8; ++j) { + const ushort v = p[j]; + const half2 w0 = as_type(tab[v & 255]), w1 = as_type(tab[v >> 8]); + q[2 * j] = float(w0.x); + q[2 * j + 16] = float(w0.y); + q[2 * j + 1] = float(w1.x); + q[2 * j + 17] = float(w1.y); + } + const uint sh = *(device const ushort*)(b + 2); + const int ls = int((b[4 + (ui >> 1)] >> (4 * (ui & 1))) & 15) | int(((sh >> (2 * ui)) & 3) << 4); + return rdh(b) * float(ls - 32); +} + +template <> inline float deq(device const uchar* b, int, thread float* q, threadgroup const uint*) { + device const ushort* p = (device const ushort*)(b + 2); + for (int j = 0; j < 16; ++j) { + const ushort v = p[j]; + q[2 * j] = float(as_type(uchar(v & 255))); + q[2 * j + 1] = float(as_type(uchar(v >> 8))); + } + return rdh(b); +} + +template <> inline float deq(device const uchar* b, int, thread float* q, threadgroup const uint*) { + device const ushort* p = (device const ushort*)(b + 2); + for (int j = 0; j < 8; ++j) { + const ushort v = p[j]; + q[2 * j] = float(v & 15) - 8.0f; + q[2 * j + 16] = float((v >> 4) & 15) - 8.0f; + q[2 * j + 1] = float((v >> 8) & 15) - 8.0f; + q[2 * j + 17] = float(v >> 12) - 8.0f; + } + return rdh(b); +} + +template <> inline float deq(device const uchar* b, int, thread float* q, threadgroup const uint*) { + const uint hb = rd32(b + 2); + device const ushort* p = (device const ushort*)(b + 6); + for (int j = 0; j < 8; ++j) { + const ushort v = p[j]; + const int j0 = 2 * j, j1 = 2 * j + 1; + q[j0] = float(int(v & 15) | int(((hb >> j0) & 1) << 4)) - 16.0f; + q[j0 + 16] = float(int((v >> 4) & 15) | int(((hb >> (j0 + 16)) & 1) << 4)) - 16.0f; + q[j1] = float(int((v >> 8) & 15) | int(((hb >> j1) & 1) << 4)) - 16.0f; + q[j1 + 16] = float(int(v >> 12) | int(((hb >> (j1 + 16)) & 1) << 4)) - 16.0f; + } + return rdh(b); +} + +// Q5_1: 32 = 1 unit; q = the 5-bit code (no offset; the min m is applied through the x sums), returns d +template <> inline float deq(device const uchar* b, int, thread float* q, threadgroup const uint*) { + const uint hb = rd32(b + 4); + device const ushort* p = (device const ushort*)(b + 8); + for (int j = 0; j < 8; ++j) { + const ushort v = p[j]; + const int j0 = 2 * j, j1 = 2 * j + 1; + q[j0] = float(int(v & 15) | int(((hb >> j0) & 1) << 4)); + q[j0 + 16] = float(int((v >> 4) & 15) | int(((hb >> (j0 + 16)) & 1) << 4)); + q[j1] = float(int((v >> 8) & 15) | int(((hb >> j1) & 1) << 4)); + q[j1 + 16] = float(int(v >> 12) | int(((hb >> (j1 + 16)) & 1) << 4)); + } + return rdh(b); +} + +// sum over groups of LPR consecutive lanes (LPR = 1, 2, 4, 8, 16 or 32); the result is valid in every lane +template +static inline float lane_sum(float v) { + if (LPR == 32) return simd_sum(v); + for (ushort o = LPR / 2; o > 0; o >>= 1) v += simd_shuffle_xor(v, o); + return v; +} diff --git a/metal/kernels/router.metal b/metal/kernels/router.metal new file mode 100644 index 00000000..e5c75274 --- /dev/null +++ b/metal/kernels/router.metal @@ -0,0 +1,104 @@ +// metal/kernels/router.metal - the router GEMV and moe_route in ONE dispatch (after quant/units/moe/gemv.metal): the +// logits rows as gemv's (LPR = 32 lanes a row, KS = 1: bitwise gemv__32_1_*_1's), 16 rows a threadgroup of 512 +// threads; every threadgroup bumps a device counter after its rows (device-scope fences around it), and the LAST one +// runs moe_route's body (the softmax / top-10 / weights, then the plan) with its 512 threads (= n_expert) and resets +// the counter. No threadgroup waits for another. ids / w / plan are bitwise moe_route's. +// Buffers: W, xp, s16, logits, args (GemvArgs: n_out = n_expert), ids, w, plan, MoeArgs, counter (one uint, zero). + +static inline void route_body(device const float* logits, device int* ids, device float* w, device int* plan, + constant MoeArgs& a, ushort tid, ushort nth, ushort sg, ushort lane, threadgroup int* s_grp, + threadgroup int* s_ent) { + if (sg < a.n_tok) { + device const float* l = logits + sg * 512; + float v[16]; + for (int i = 0; i < 16; ++i) v[i] = l[lane + 32 * i]; + float mx = -INFINITY; + for (int i = 0; i < 16; ++i) mx = max(mx, v[i]); + for (ushort m = 16; m > 0; m >>= 1) mx = max(mx, simd_shuffle_xor(mx, m)); + float sum = 0.0f; + for (int i = 0; i < 16; ++i) { + v[i] = exp(v[i] - mx); + sum += v[i]; + } + for (ushort m = 16; m > 0; m >>= 1) sum += simd_shuffle_xor(sum, m); + const float rcp = 1.0f / sum; + for (int i = 0; i < 16; ++i) { + v[i] *= rcp; + if (isnan(v[i])) v[i] = -FLT_MAX; + } + float selected = 0.0f, ssum = 0.0f; + for (int rank = 0; rank < 10; ++rank) { + float best = v[0]; + int ex = lane; + for (int i = 1; i < 16; ++i) + if (v[i] > best) { best = v[i]; ex = lane + 32 * i; } + for (ushort m = 16; m > 0; m >>= 1) { + const float ob = simd_shuffle_xor(best, m); + const int oe = simd_shuffle_xor(ex, m); + if (ob > best || (ob == best && oe < ex)) { best = ob; ex = oe; } + } + if ((ex & 31) == lane) { + v[ex / 32] = -INFINITY; + ids[sg * 10 + rank] = ex; + ssum += best; + } + if (rank == lane) selected = best; + } + for (ushort m = 16; m > 0; m >>= 1) ssum += simd_shuffle_xor(ssum, m); + ssum = max(ssum, 6.103515625e-5f); + const float inv = 1.0f / ssum; + if (lane < 10) w[sg * 10 + lane] = selected * inv; + } + threadgroup_barrier(mem_flags::mem_device); + plan_body(ids, w, plan, a, tid, nth, sg, lane, s_grp, s_ent); +} + +template +kernel void router_route(device const uchar* W [[buffer(0)]], device const float* xp [[buffer(1)]], + device const float* s16 [[buffer(2)]], device float* logits [[buffer(3)]], + constant GemvArgs& ga [[buffer(4)]], device int* ids [[buffer(5)]], device float* w [[buffer(6)]], + device int* plan [[buffer(7)]], constant MoeArgs& a [[buffer(8)]], + device atomic_uint* counter [[buffer(9)]], + uint tgx [[threadgroup_position_in_grid]], uint ngx [[threadgroups_per_grid]], + ushort tid [[thread_index_in_threadgroup]], ushort nth [[threads_per_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + constexpr int UNIT = fmt::UNIT; + threadgroup uint tab[fmt::TAB]; + threadgroup int s_grp[32], s_ent[32]; + threadgroup uint last; + load_tab(tab, tid, nth); + threadgroup_barrier(mem_flags::mem_threadgroup); + // the GEMV: simdgroup sg -> row tg.x * 16 + sg, 32 lanes over its units + const int row = int(tgx) * 16 + sg; + const int rr = min(row, int(ga.n_out) - 1); + device const uchar* rp = W + (ulong)rr * ga.row_bytes; + const int U = int(ga.n_in) / UNIT, s16n = int(ga.n_in) / 16; + float acc[8]; + for (int t = 0; t < NTOK; ++t) acc[t] = 0.0f; + for (int u = lane; u < U; u += 32) { + float q[UNIT]; + float4 sc; + Dec::run(rp, u, q, sc, tab); + for (int t = 0; t < NTOK; ++t) { + float xs[UNIT], xsum[2]; + X::load(xp + t * int(ga.x_stride), s16 + t * s16n, u, xs, xsum); + acc[t] += unit_combine(q, sc, xs, xsum); + } + } + for (int t = 0; t < NTOK; ++t) { + const float v = lane_sum<32>(acc[t]); + if (lane == 0 && row < int(ga.n_out)) logits[t * int(ga.y_stride) + row] = v; + } + // the last threadgroup to finish routes + atomic_thread_fence(mem_flags::mem_device, memory_order_seq_cst, thread_scope_device); + threadgroup_barrier(mem_flags::mem_device); + if (tid == 0) last = atomic_fetch_add_explicit(counter, 1u, memory_order_relaxed) == ngx - 1 ? 1u : 0u; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (!last) return; + atomic_thread_fence(mem_flags::mem_device, memory_order_seq_cst, thread_scope_device); + route_body(logits, ids, w, plan, a, tid, nth, sg, lane, s_grp, s_ent); + if (tid == 0) atomic_store_explicit(counter, 0u, memory_order_relaxed); +} + +template [[host_name("router_route_30")]] kernel decltype(router_route) router_route; +template [[host_name("router_route_0")]] kernel decltype(router_route) router_route; diff --git a/metal/kernels/rt_bench.metal b/metal/kernels/rt_bench.metal new file mode 100644 index 00000000..bdce780a --- /dev/null +++ b/metal/kernels/rt_bench.metal @@ -0,0 +1,67 @@ +// metal/kernels/rt_bench.metal - bandwidth and dispatch-cost probes (rt_bench.cpp). + +// Grid-stride streaming read: thread i reads src[i], src[i + nt], ... (coalesced across the grid). +kernel void k_read(device const uint4* src [[buffer(0)]], device uint* out [[buffer(1)]], + constant uint& n [[buffer(2)]], + uint gid [[thread_position_in_grid]], uint nt [[threads_per_grid]]) { + uint4 a = 0; + for (uint i = gid; i < n; i += nt) a += src[i]; + out[gid] = a.x ^ a.y ^ a.z ^ a.w; +} + +// The same, 4 independent loads in flight per iteration. +kernel void k_read_u4(device const uint4* src [[buffer(0)]], device uint* out [[buffer(1)]], + constant uint& n [[buffer(2)]], + uint gid [[thread_position_in_grid]], uint nt [[threads_per_grid]]) { + uint4 a = 0, b = 0, c = 0, d = 0; + uint i = gid; + for (; i + 3 * nt < n; i += 4 * nt) { + a += src[i]; + b += src[i + nt]; + c += src[i + 2 * nt]; + d += src[i + 3 * nt]; + } + for (; i < n; i += nt) a += src[i]; + a += b + c + d; + out[gid] = a.x ^ a.y ^ a.z ^ a.w; +} + +// Contiguous chunk per threadgroup (how a GEMV row block reads): threadgroup g reads [g*chunk, (g+1)*chunk). +kernel void k_read_chunk(device const uint4* src [[buffer(0)]], device uint* out [[buffer(1)]], + constant uint& n [[buffer(2)]], constant uint& chunk [[buffer(3)]], + uint tid [[thread_position_in_threadgroup]], uint tgs [[threads_per_threadgroup]], + uint g [[threadgroup_position_in_grid]], uint gid [[thread_position_in_grid]]) { + uint4 a = 0, b = 0; + const uint base = g * chunk, end = min(base + chunk, n); + uint i = base + tid; + for (; i + tgs < end; i += 2 * tgs) { + a += src[i]; + b += src[i + tgs]; + } + for (; i < end; i += tgs) a += src[i]; + a += b; + out[gid] = a.x ^ a.y ^ a.z ^ a.w; +} + +// Read + write (a state update): dst[i] = src[i] * 1.0001 for float4. +kernel void k_copy(device const float4* src [[buffer(0)]], device float4* dst [[buffer(1)]], + constant uint& n [[buffer(2)]], + uint gid [[thread_position_in_grid]], uint nt [[threads_per_grid]]) { + for (uint i = gid; i < n; i += nt) dst[i] = src[i] * 1.0001f; +} + +// Dispatch-cost probes. +kernel void k_empty(device uint* out [[buffer(0)]], uint gid [[thread_position_in_grid]]) { + if (gid == 0xFFFFFFFFu) out[0] = 1; +} + +// A dependent chain: each dispatch reads what the previous one wrote. +kernel void k_chain(device uint* buf [[buffer(0)]], uint gid [[thread_position_in_grid]]) { + if (gid == 0) buf[0] = buf[0] + 1; +} + +// A small but real kernel: 2560 floats read, 2560 written (an elementwise op on one token). +kernel void k_small(device const float* x [[buffer(0)]], device float* y [[buffer(1)]], + uint gid [[thread_position_in_grid]]) { + if (gid < 2560) y[gid] = x[gid] * 0.5f + y[gid]; +} diff --git a/metal/kernels/sample.metal b/metal/kernels/sample.metal new file mode 100644 index 00000000..8443d360 --- /dev/null +++ b/metal/kernels/sample.metal @@ -0,0 +1,59 @@ +// metal/kernels/sample.metal - greedy sampling over the LM head's logits: the largest logit, ties to the lowest +// token id (NaN never wins). Two stages: argmax_part (grid (parts, n_tok), 256 threads) writes one (value, id) +// pair per threadgroup; argmax_final (grid (n_tok), 256 threads) reduces them in order. + +struct ArgArgs { + uint n_vocab; + uint parts; +}; + +static inline void better(thread float& bv, thread int& bi, float v, int i) { + if (v > bv || (v == bv && i < bi)) { bv = v; bi = i; } +} + +static inline void tg_argmax(thread float& bv, thread int& bi, threadgroup float* sv, threadgroup int* si, ushort sg, + ushort lane) { + for (ushort m = 16; m > 0; m >>= 1) { + const float ov = simd_shuffle_xor(bv, m); + const int oi = simd_shuffle_xor(bi, m); + better(bv, bi, ov, oi); + } + if (lane == 0) { sv[sg] = bv; si[sg] = bi; } + threadgroup_barrier(mem_flags::mem_threadgroup); + bv = -INFINITY; + bi = 0x7fffffff; + for (int k = 0; k < 8; ++k) better(bv, bi, sv[k], si[k]); +} + +kernel void argmax_part(device const float* logits [[buffer(0)]], device float* pv [[buffer(1)]], + device int* pi [[buffer(2)]], constant ArgArgs& a [[buffer(3)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + threadgroup float sv[8]; + threadgroup int si[8]; + const uint t = tg.y, per = (a.n_vocab + a.parts - 1) / a.parts; + const uint b0 = tg.x * per, b1 = min(b0 + per, a.n_vocab); + device const float* l = logits + t * a.n_vocab; + float bv = -INFINITY; + int bi = 0x7fffffff; + for (uint i = b0 + tid; i < b1; i += 256) { + const float v = l[i]; + if (!isnan(v)) better(bv, bi, v, int(i)); + } + tg_argmax(bv, bi, sv, si, sg, lane); + if (tid == 0) { pv[t * a.parts + tg.x] = bv; pi[t * a.parts + tg.x] = bi; } +} + +kernel void argmax_final(device const float* pv [[buffer(0)]], device const int* pi [[buffer(1)]], + device int* out [[buffer(2)]], constant ArgArgs& a [[buffer(3)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + threadgroup float sv[8]; + threadgroup int si[8]; + const uint t = tg.x; + float bv = -INFINITY; + int bi = 0x7fffffff; + for (uint k = tid; k < a.parts; k += 256) better(bv, bi, pv[t * a.parts + k], pi[t * a.parts + k]); + tg_argmax(bv, bi, sv, si, sg, lane); + if (tid == 0) out[t] = bi; +} diff --git a/metal/kernels/units.metal b/metal/kernels/units.metal new file mode 100644 index 00000000..15f584cb --- /dev/null +++ b/metal/kernels/units.metal @@ -0,0 +1,321 @@ +// metal/kernels/units.metal - the dot of one unit with the window's tokens (after quant.metal). +// +// X::load(xrow, u, xs, xsum) prepares unit u's x slice of one token (xrow = the token's row start), once per unit +// and shared by every weight row the lane reads: the UNIT x values in the order the decoder produces weights, and +// up to two partial sums (for the formats with an offset or a min). Where the codes are read with the mask trick +// (an AND keeps a field in place, so the code arrives multiplied by 2^k), the x values are pre-scaled by 2^-k here: +// exact in float. + +// the threadgroup-memory form (x staged once per threadgroup; the same values) +static inline void load16(threadgroup const float* p, thread float* xs) { + threadgroup const float4* v = (threadgroup const float4*)p; + for (int j = 0; j < 4; ++j) { + const float4 a = v[j]; + xs[4 * j] = a.x; + xs[4 * j + 1] = a.y; + xs[4 * j + 2] = a.z; + xs[4 * j + 3] = a.w; + } +} +static inline void load16(device const float* p, thread float* xs) { + device const float4* v = (device const float4*)p; + for (int j = 0; j < 4; ++j) { + const float4 a = v[j]; + xs[4 * j] = a.x; + xs[4 * j + 1] = a.y; + xs[4 * j + 2] = a.z; + xs[4 * j + 3] = a.w; + } +} + +// ---- prepared x (xprep): XP holds, per token row of n floats, the kinds +// XK_RAW x (every format without the mask trick) +// XK_Q2 x * 4^-(i % 8) (Q2_0: 2-bit fields in place in a 16-bit word) +// XK_P4 x * 2^-(8 (i % 4)) (Q4_K, Q5_K: byte fields in place in a 32-bit word) +// XK_P2 x * 2^-(8 (i % 2)) (Q6_K, Q3_K: byte fields in place in a 16-bit word) +// and S16 = the sum of every 16 consecutive raw x (the formats with an offset or a min). +#define XK_RAW 0 +#define XK_Q2 1 +#define XK_P4 2 +#define XK_P2 3 +template struct XKind { enum { K = XK_RAW }; }; +template <> struct XKind { enum { K = XK_Q2 }; }; +template <> struct XKind { enum { K = XK_P4 }; }; +template <> struct XKind { enum { K = XK_P4 }; }; +template <> struct XKind { enum { K = XK_P2 }; }; +template <> struct XKind { enum { K = XK_P2 }; }; + +// X::load(xp, s16, u, xs, xsum): unit u's prepared x (xp = the token's row of the format's kind, s16 = its sums) +template struct X { + template static inline void load(P xp, P, int u, thread float* xs, thread float* xsum) { + constexpr int UNIT = fmt::UNIT; + for (int k = 0; k < UNIT; k += 16) load16(xp + u * UNIT + k, xs + k); + xsum[0] = xsum[1] = 0.0f; + } +}; +template <> struct X { + template static inline void load(P xp, P s16, int u, thread float* xs, thread float* xsum) { + load16(xp + 16 * u, xs); + xsum[0] = s16[u]; + xsum[1] = 0.0f; + } +}; +// Q4_K / Q5_K: unit (block b, chunk c, half m): run0 at 256b + 64c + 16m, run1 = run0 + 32 +template <> struct X { + template static inline void load(P xp, P s16, int u, thread float* xs, thread float* xsum) { + const int p0 = 256 * (u >> 3) + 64 * ((u >> 1) & 3) + 16 * (u & 1); + load16(xp + p0, xs); + load16(xp + p0 + 32, xs + 16); + xsum[0] = s16[p0 >> 4]; + xsum[1] = s16[(p0 >> 4) + 2]; + } +}; +template <> struct X { + template static inline void load(P xp, P s16, int u, thread float* xs, thread float* xsum) { + X::load(xp, s16, u, xs, xsum); + } +}; +// Q6_K: unit (block b, half n, m, p): run0 at 256b + 128n + 32p + 16m, run1 = run0 + 64 +template <> struct X { + template static inline void load(P xp, P s16, int u, thread float* xs, thread float* xsum) { + const int p0 = 256 * (u >> 3) + 128 * ((u >> 2) & 1) + 32 * (u & 1) + 16 * ((u >> 1) & 1); + load16(xp + p0, xs); + load16(xp + p0 + 64, xs + 16); + xsum[0] = s16[p0 >> 4]; + xsum[1] = s16[(p0 >> 4) + 4]; + } +}; +// Q5_1: 32 contiguous raw x, the two per-16 sums formed from them (the GEMVs that read Q5_1 - the routed down - get +// h without prepared sums) +template <> struct X { + template static inline void load(P xp, P, int u, thread float* xs, thread float* xsum) { + load16(xp + 32 * u, xs); + load16(xp + 32 * u + 16, xs + 16); + float a = 0.0f, b = 0.0f; + for (int j = 0; j < 16; ++j) { a += xs[j]; b += xs[16 + j]; } + xsum[0] = a; + xsum[1] = b; + } +}; +// Q3_K: 32 contiguous, sums per 16 +template <> struct X { + template static inline void load(P xp, P s16, int u, thread float* xs, thread float* xsum) { + load16(xp + 32 * u, xs); + load16(xp + 32 * u + 16, xs + 16); + xsum[0] = s16[2 * u]; + xsum[1] = s16[2 * u + 1]; + } +}; + +// xprep: one thread per 16 consecutive values of one token row; XP = [4 kinds][n_tok][n] then S16 [n_tok][n / 16] +kernel void xprep(device const float* x [[buffer(0)]], device float* xp [[buffer(1)]], constant uint& n [[buffer(2)]], + constant uint& n_tok [[buffer(3)]], uint gid [[thread_position_in_grid]]) { + const uint per = n / 16; + if (gid >= per * n_tok) return; + const uint t = gid / per, i = gid % per; + device const float* src = x + t * n + 16 * i; + const uint plane = n_tok * n; + device float* raw = xp + t * n + 16 * i; + float v[16]; + load16(src, v); + float s0 = 0, s1 = 0; + for (int j = 0; j < 16; j += 2) { s0 += v[j]; s1 += v[j + 1]; } + const float q2s[8] = {1.0f, 0.25f, 0.0625f, 0.015625f, 0.00390625f, 0.0009765625f, 0.000244140625f, 0.00006103515625f}; + const float p4s[4] = {1.0f, 0.00390625f, 1.52587890625e-05f, 5.9604644775390625e-08f}; + for (int j = 0; j < 16; ++j) { + raw[j] = v[j]; + raw[plane + j] = v[j] * q2s[j & 7]; + raw[2 * plane + j] = v[j] * p4s[j & 3]; + raw[3 * plane + j] = (j & 1) ? v[j] * 0.00390625f : v[j]; + } + xp[4 * plane + t * per + i] = s0 + s1; +} + +// ---- decoders: Dec::run(row, u, q, sc) decodes unit u of a row into q[UNIT] and sc = (d1, d2, m1, m2), so that +// for any token: dot = d1 * sum_{j < UNIT/2} q[j] xs[j] + d2 * sum_{j >= UNIT/2} q[j] xs[j] - (m1 xsum0 + m2 xsum1) +// with xs, xsum from X::load. A unit's weights are decoded once per row and applied to every token. +template struct Dec { + static inline void run(device const uchar* row, int u, thread float* q, thread float4& sc, threadgroup const uint* tab) { + constexpr int UNIT = fmt::UNIT, UPB = fmt::QK / UNIT; + const float s = deq(row + (u / UPB) * fmt::BB, u % UPB, q, tab); + sc = float4(s, s, 0.0f, 0.0f); + } +}; + +template <> struct Dec { + static inline void run(device const uchar* row, int u, thread float* q, thread float4& sc, threadgroup const uint*) { + device const uchar* b = row + (u >> 2) * 18; + device const ushort* p = (device const ushort*)(b + 2 + 4 * (u & 3)); + const ushort a = p[0], c = p[1]; + for (int j = 0; j < 8; ++j) { + q[j] = float(a & ushort(3u << (2 * j))); + q[8 + j] = float(c & ushort(3u << (2 * j))); + } + const float d = rdh(b); + sc = float4(d, d, d, 0.0f); + } +}; + +// Q2_0 with raw x: q = c - 1 (shift, and, convert, subtract), one scale +template <> struct Dec { + static inline void run(device const uchar* row, int u, thread float* q, thread float4& sc, threadgroup const uint*) { + device const uchar* b = row + (u >> 2) * 18; + device const ushort* p = (device const ushort*)(b + 2 + 4 * (u & 3)); + const ushort a = p[0], c = p[1]; + for (int j = 0; j < 8; ++j) { + q[j] = float((a >> (2 * j)) & 3) - 1.0f; + q[8 + j] = float((c >> (2 * j)) & 3) - 1.0f; + } + const float d = rdh(b); + sc = float4(d, d, 0.0f, 0.0f); + } +}; + +static inline void scale_min_k4(int j, device const uchar* q, thread float& d, thread float& m) { + if (j < 4) { + d = float(q[j] & 63); + m = float(q[j + 4] & 63); + } else { + d = float((q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4)); + m = float((q[j + 4] >> 4) | ((q[j] >> 6) << 4)); + } +} +static inline void bytes4(uint w, thread float* q) { + q[0] = float(w & 0xFFu); + q[1] = float(w & 0xFF00u); + q[2] = float(w & 0xFF0000u); + q[3] = float(w & 0xFF000000u); +} +static inline void bytes2(ushort w, thread float* q) { + q[0] = float(w & 0xFF); + q[1] = float(w & 0xFF00); +} + +template <> struct Dec { // w = d q + m: sum = d (q . x) + m (sum x) + static inline void run(device const uchar* row, int u, thread float* q, thread float4& sc, threadgroup const uint* tab) { + device const uchar* b = row + u * 24; + const float d = deq(b, 0, q, tab), m = rdh(b + 2); + sc = float4(d, d, -m, -m); + } +}; + +template <> struct Dec { + static inline void run(device const uchar* row, int u, thread float* q, thread float4& sc, threadgroup const uint*) { + device const uchar* b = row + (u >> 3) * 144; + const int c = (u >> 1) & 3, m = u & 1; + const float d = rdh(b), dm = rdh(b + 2); + float s1, m1, s2, m2; + scale_min_k4(2 * c, b + 4, s1, m1); + scale_min_k4(2 * c + 1, b + 4, s2, m2); + device const uint* qp = (device const uint*)(b + 16 + 32 * c + 16 * m); + for (int w = 0; w < 4; ++w) { + const uint v = qp[w]; + bytes4(v & 0x0F0F0F0Fu, q + 4 * w); + bytes4((v >> 4) & 0x0F0F0F0Fu, q + 16 + 4 * w); + } + sc = float4(d * s1, d * s2, dm * m1, dm * m2); + } +}; + +template <> struct Dec { + static inline void run(device const uchar* row, int u, thread float* q, thread float4& sc, threadgroup const uint*) { + device const uchar* b = row + (u >> 3) * 176; + const int c = (u >> 1) & 3, m = u & 1; + const float d = rdh(b), dm = rdh(b + 2); + float s1, m1, s2, m2; + scale_min_k4(2 * c, b + 4, s1, m1); + scale_min_k4(2 * c + 1, b + 4, s2, m2); + device const uint* qp = (device const uint*)(b + 48 + 32 * c + 16 * m); + device const uint* hp = (device const uint*)(b + 16 + 16 * m); + for (int w = 0; w < 4; ++w) { + const uint v = qp[w], h = hp[w]; + bytes4((v & 0x0F0F0F0Fu) | (((h >> (2 * c)) & 0x01010101u) << 4), q + 4 * w); + bytes4(((v >> 4) & 0x0F0F0F0Fu) | (((h >> (2 * c + 1)) & 0x01010101u) << 4), q + 16 + 4 * w); + } + sc = float4(d * s1, d * s2, dm * m1, dm * m2); + } +}; + +template <> struct Dec { + static inline void run(device const uchar* row, int u, thread float* q, thread float4& sc, threadgroup const uint*) { + device const uchar* b = row + (u >> 3) * 210; + const int n = (u >> 2) & 1, m = (u >> 1) & 1, p = u & 1; + device const ushort* ql = (device const ushort*)(b + 64 * n + 32 * p + 16 * m); + device const ushort* qh = (device const ushort*)(b + 128 + 32 * n + 16 * m); + device const char* scs = (device const char*)(b + 192); + const float d = rdh(b + 208); + for (int w = 0; w < 8; ++w) { + const ushort l = ql[w], h = qh[w]; + bytes2((l & 0x0F0F) | (((h >> (2 * p)) & 0x0303) << 4), q + 2 * w); + bytes2(((l >> 4) & 0x0F0F) | (((h >> (2 * p + 4)) & 0x0303) << 4), q + 16 + 2 * w); + } + const float d1 = d * float(scs[8 * n + m + 2 * p]), d2 = d * float(scs[8 * n + m + 2 * p + 4]); + sc = float4(d1, d2, 32.0f * d1, 32.0f * d2); + } +}; + +template <> struct Dec { + static inline void run(device const uchar* row, int u, thread float* q, thread float4& sc, threadgroup const uint*) { + device const uchar* b = row + (u >> 3) * 110; + const int n = (u >> 2) & 1, j = u & 3; + // qs and hmask as packed (2-byte aligned) vectors: blocks are 110 bytes, so odd blocks are only 2-aligned + device const packed_ushort4* qv = (device const packed_ushort4*)(b + 32 + 32 * n); + device const packed_ushort4* hv = (device const packed_ushort4*)b; + ushort qq[16], hm[16]; + for (int v = 0; v < 4; ++v) { + const ushort4 a4 = ushort4(qv[v]), h4 = ushort4(hv[v]); + qq[4 * v] = a4.x; qq[4 * v + 1] = a4.y; qq[4 * v + 2] = a4.z; qq[4 * v + 3] = a4.w; + hm[4 * v] = h4.x; hm[4 * v + 1] = h4.y; hm[4 * v + 2] = h4.z; hm[4 * v + 3] = h4.w; + } + device const uchar* s = b + 96; + const int i1 = 8 * n + 2 * j, i2 = i1 + 1; + const int l1 = (i1 < 8 ? s[i1] & 0xF : s[i1 - 8] >> 4) | (((s[8 + (i1 & 3)] >> (2 * (i1 >> 2))) & 3) << 4); + const int l2 = (i2 < 8 ? s[i2] & 0xF : s[i2 - 8] >> 4) | (((s[8 + (i2 & 3)] >> (2 * (i2 >> 2))) & 3) << 4); + const float d = rdh(b + 108); + const int hs = 4 * n + j; + for (int w = 0; w < 8; ++w) { + bytes2(((qq[w] >> (2 * j)) & 0x0303) | (((hm[w] >> hs) & 0x0101) << 2), q + 2 * w); + bytes2(((qq[w + 8] >> (2 * j)) & 0x0303) | (((hm[w + 8] >> hs) & 0x0101) << 2), q + 16 + 2 * w); + } + const float d1 = d * float(l1 - 32), d2 = d * float(l2 - 32); + sc = float4(d1, d2, 4.0f * d1, 4.0f * d2); + } +}; + +template <> struct Dec { // 16 floats a unit (the Unsloth files' router / alpha / beta / inject rows) + static inline void run(device const uchar* row, int u, thread float* q, thread float4& sc, threadgroup const uint*) { + device const float4* p = (device const float4*)(row + 64 * u); + for (int k = 0; k < 4; ++k) { + const float4 v = p[k]; + q[4 * k] = v.x; q[4 * k + 1] = v.y; q[4 * k + 2] = v.z; q[4 * k + 3] = v.w; + } + sc = float4(1.0f, 1.0f, 0.0f, 0.0f); + } +}; + +template <> struct Dec { + static inline void run(device const uchar* row, int u, thread float* q, thread float4& sc, threadgroup const uint*) { + device const uint4* p = (device const uint4*)(row + 32 * u); + const uint4 a = p[0], c = p[1]; + const uint v[8] = {a.x, a.y, a.z, a.w, c.x, c.y, c.z, c.w}; + for (int k = 0; k < 8; ++k) { + q[2 * k] = as_type(v[k] << 16); + q[2 * k + 1] = as_type(v[k] & 0xFFFF0000u); + } + sc = float4(1.0f, 1.0f, 0.0f, 0.0f); + } +}; + +// acc += unit dot of decoded q / sc with one token's prepared slice +template +static inline float unit_combine(thread const float* q, float4 sc, thread const float* xs, thread const float* xsum) { + constexpr int H = UNIT / 2; + float s0 = 0, s1 = 0, s2 = 0, s3 = 0; + for (int j = 0; j < H; j += 2) { + s0 = fma(q[j], xs[j], s0); + s1 = fma(q[j + 1], xs[j + 1], s1); + s2 = fma(q[H + j], xs[H + j], s2); + s3 = fma(q[H + j + 1], xs[H + j + 1], s3); + } + return sc.x * (s0 + s1) + sc.y * (s2 + s3) - (sc.z * xsum[0] + sc.w * xsum[1]); +} diff --git a/metal/probe/mkfile.c b/metal/probe/mkfile.c new file mode 100644 index 00000000..068aadbd --- /dev/null +++ b/metal/probe/mkfile.c @@ -0,0 +1,23 @@ +// mkfile.c - write a dense test file of N GiB with F_NOCACHE (so it is not left in the page cache): +// the first uint32 of every 4 KiB is (offset >> 12) ^ 0x5a5a5a5a, the rest is a cheap pattern. +#include +#include +#include +#include +#include +int main(int argc, char** argv) { + if (argc < 3) return 1; + const uint64_t gib = strtoull(argv[2], 0, 10); + int fd = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0644); + if (fd < 0) return 2; + fcntl(fd, F_NOCACHE, 1); + const size_t B = 64u << 20; + uint32_t* buf = aligned_alloc(16384, B); + for (uint64_t off = 0; off < (gib << 30); off += B) { + for (size_t i = 0; i < B / 4; ++i) buf[i] = (uint32_t) (i * 2654435761u); + for (size_t p = 0; p < B; p += 4096) buf[p / 4] = (uint32_t) ((off + p) >> 12) ^ 0x5a5a5a5au; + if (write(fd, buf, B) != (ssize_t) B) return 3; + } + close(fd); + return 0; +} diff --git a/metal/probe/mtl_doorbell.cpp b/metal/probe/mtl_doorbell.cpp new file mode 100644 index 00000000..20baf0d8 --- /dev/null +++ b/metal/probe/mtl_doorbell.cpp @@ -0,0 +1,115 @@ +// mtl_doorbell.cpp - can Strata's doorbell protocol run on Metal? +// A. in-kernel spin: a running kernel polls a shared-memory word that the CPU writes later (the CUDA doorbell model) +// B. MTLSharedEvent ping-pong: the GPU signals "routing ready" (value 2l+1), the host sees it, does its part, sets +// 2l+2 from the CPU, and the GPU (encodeWait inside the same, already committed command buffer) goes on. +// Measures the round trip per "layer". +#define NS_PRIVATE_IMPLEMENTATION +#define MTL_PRIVATE_IMPLEMENTATION +#include +#include + +#include +#include +#include +#include +#include +#include + +static double now_us() { + return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); +} +static const char* kSrc = R"MSL( +#include +using namespace metal; +struct SpinArgs { device atomic_uint* flag; device uint* out; uint want; uint max_iter; }; +kernel void spin(constant SpinArgs& p [[buffer(0)]], uint i [[thread_position_in_grid]]) { + if (i != 0) return; + uint it = 0; + while (atomic_load_explicit(p.flag, memory_order_relaxed) != p.want && it < p.max_iter) ++it; + p.out[0] = it; + p.out[1] = atomic_load_explicit(p.flag, memory_order_relaxed); +} +struct TickArgs { device uint* x; }; +kernel void tick(constant TickArgs& p [[buffer(0)]], uint i [[thread_position_in_grid]]) { if (i == 0) p.x[0] += 1; } +)MSL"; +struct SpinArgs { uint64_t flag, out; uint32_t want, max_iter; }; +struct TickArgs { uint64_t x; }; + +int main() { + NS::AutoreleasePool* pool = NS::AutoreleasePool::alloc()->init(); + MTL::Device* dev = MTL::CreateSystemDefaultDevice(); + NS::Error* e = nullptr; + MTL::Library* lib = dev->newLibrary(NS::String::string(kSrc, NS::UTF8StringEncoding), nullptr, &e); + if (!lib) { std::printf("compile failed\n"); return 1; } + auto pipe = [&](const char* n) { return dev->newComputePipelineState(lib->newFunction(NS::String::string(n, NS::UTF8StringEncoding)), &e); }; + MTL::ComputePipelineState* p_spin = pipe("spin"); + MTL::ComputePipelineState* p_tick = pipe("tick"); + MTL::CommandQueue* q = dev->newCommandQueue(); + MTL::Buffer* bf = dev->newBuffer(16384, MTL::ResourceStorageModeShared); + MTL::Buffer* bo = dev->newBuffer(16384, MTL::ResourceStorageModeShared); + MTL::ResidencySet* rs = dev->newResidencySet(MTL::ResidencySetDescriptor::alloc()->init(), &e); + rs->addAllocation(bf); rs->addAllocation(bo); rs->commit(); q->addResidencySet(rs); + volatile uint32_t* flag = (volatile uint32_t*) bf->contents(); + uint32_t* out = (uint32_t*) bo->contents(); + + // ---- A: in-kernel spin on a word the CPU writes 5 ms after commit + for (int rep = 0; rep < 3; ++rep) { + *flag = 0; out[0] = out[1] = 0; + SpinArgs a{bf->gpuAddress(), bo->gpuAddress(), 7, 200000000u}; + MTL::CommandBuffer* cb = q->commandBuffer(); + MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder(); + enc->setComputePipelineState(p_spin); + enc->setBytes(&a, sizeof a, 0); + enc->dispatchThreads(MTL::Size(1, 1, 1), MTL::Size(1, 1, 1)); + enc->endEncoding(); + const double t0 = now_us(); + cb->commit(); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + std::atomic_thread_fence(std::memory_order_seq_cst); + *flag = 7; + const double tw = now_us(); + cb->waitUntilCompleted(); + std::printf("A in-kernel spin: GPU saw the CPU store: %s (iterations %u, flag %u), done %.0f us after the store, status %d\n", + out[1] == 7 ? "YES" : "NO (timed out)", out[0], out[1], now_us() - tw, (int) cb->status()); + (void) t0; + } + + // ---- B: shared-event ping-pong, L "layers" in ONE committed command buffer + for (int rep = 0; rep < 3; ++rep) { + const int L = 48; + MTL::SharedEvent* ev = dev->newSharedEvent(); + ev->setSignaledValue(0); + out[0] = 0; + MTL::CommandBuffer* cb = q->commandBuffer(); + TickArgs ta{bo->gpuAddress()}; + for (int l = 0; l < L; ++l) { + MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder(); + enc->setComputePipelineState(p_tick); + enc->setBytes(&ta, sizeof ta, 0); + enc->dispatchThreads(MTL::Size(1, 1, 1), MTL::Size(1, 1, 1)); + enc->endEncoding(); + cb->encodeSignalEvent(ev, 2 * l + 1); // "the miss list of layer l is ready" + cb->encodeWait(ev, 2 * l + 2); // "the host has answered layer l" + } + std::vector rt; + const double t0 = now_us(); + cb->commit(); + for (int l = 0; l < L; ++l) { + while (ev->signaledValue() < (uint64_t) (2 * l + 1)) {} + const double ts = now_us(); + if (out[0] != (uint32_t) (l + 1)) std::printf(" layer %d: host read %u (stale?)\n", l, out[0]); + ev->setSignaledValue(2 * l + 2); + rt.push_back(ts); + } + cb->waitUntilCompleted(); + const double total = now_us() - t0; + std::vector gaps; + for (int l = 1; l < L; ++l) gaps.push_back(rt[l] - rt[l - 1]); + std::sort(gaps.begin(), gaps.end()); + std::printf("B shared-event round trip: %d layers in %.0f us, per layer median %.1f us (min %.1f, max %.1f), ticks %u, status %d\n", + L, total, gaps[gaps.size() / 2], gaps.front(), gaps.back(), out[0], (int) cb->status()); + ev->release(); + } + pool->release(); + return 0; +} diff --git a/metal/probe/mtl_probe.cpp b/metal/probe/mtl_probe.cpp new file mode 100644 index 00000000..d1e0a335 --- /dev/null +++ b/metal/probe/mtl_probe.cpp @@ -0,0 +1,268 @@ +// mtl_probe.cpp - M5 Max checks for the Metal device-interface design (mac-design stream). +// 1. device facts: unified memory, maxBufferLength, recommendedMaxWorkingSetSize, GPU families +// 2. MSL compiled at run time (no offline `metal` tool in the Command Line Tools) +// 3. a hello kernel that takes RAW GPU ADDRESSES in a setBytes struct (the CUDA "void* device pointer" model) +// 4. gpuAddress vs contents(): are they equal? +// 5. newBufferWithBytesNoCopy over an mmapped file > 30 GB: alignment, max length, split into chunks, GPU reads it +// Build: clang++ -std=c++20 -O2 -I metal-cpp mtl_probe.cpp -framework Metal -framework Foundation -framework QuartzCore +#define NS_PRIVATE_IMPLEMENTATION +#define MTL_PRIVATE_IMPLEMENTATION +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +static double now_ms() { + return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); +} + +static const char* kSrc = R"MSL( +#include +using namespace metal; +struct AxpyArgs { device const float* x; device float* y; float a; uint n; }; +kernel void axpy(constant AxpyArgs& p [[buffer(0)]], uint i [[thread_position_in_grid]]) { + if (i < p.n) p.y[i] = p.a * p.x[i] + p.y[i]; +} +// reads one uint32 at each probe offset of a (possibly huge) buffer given by raw GPU address +struct ProbeArgs { device const uint* base; device const ulong* offs; device uint* out; uint n; }; +kernel void probe(constant ProbeArgs& p [[buffer(0)]], uint i [[thread_position_in_grid]]) { + if (i < p.n) p.out[i] = p.base[p.offs[i] / 4]; +} +// streaming read of a buffer range: sum of uint32 (bandwidth through a NoCopy file buffer) +struct SumArgs { device const uint4* base; device atomic_uint* out; ulong n4; }; +kernel void sum(constant SumArgs& p [[buffer(0)]], uint i [[thread_position_in_grid]], uint g [[threads_per_grid]]) { + uint s = 0; + for (ulong k = i; k < p.n4; k += g) { uint4 v = p.base[k]; s += v.x ^ v.y ^ v.z ^ v.w; } + atomic_fetch_add_explicit(p.out, s, memory_order_relaxed); +} +)MSL"; + +struct AxpyArgs { uint64_t x, y; float a; uint32_t n; }; +struct ProbeArgs { uint64_t base, offs, out; uint32_t n; }; +struct SumArgs { uint64_t base, out; uint64_t n4; }; + +int main(int argc, char** argv) { + NS::AutoreleasePool* pool = NS::AutoreleasePool::alloc()->init(); + MTL::Device* dev = MTL::CreateSystemDefaultDevice(); + if (!dev) { std::printf("no Metal device\n"); return 1; } + std::printf("device: %s\n", dev->name()->utf8String()); + std::printf("unified memory: %d\n", (int) dev->hasUnifiedMemory()); + std::printf("maxBufferLength: %llu (%.2f GiB)\n", (unsigned long long) dev->maxBufferLength(), dev->maxBufferLength() / 1073741824.0); + std::printf("recommendedMaxWorkingSetSize: %llu (%.2f GiB)\n", (unsigned long long) dev->recommendedMaxWorkingSetSize(), + dev->recommendedMaxWorkingSetSize() / 1073741824.0); + std::printf("maxThreadgroupMemoryLength: %llu\n", (unsigned long long) dev->maxThreadgroupMemoryLength()); + std::printf("families: apple7 %d apple8 %d apple9 %d apple10 %d metal3 %d metal4 %d\n", (int) dev->supportsFamily(MTL::GPUFamilyApple7), + (int) dev->supportsFamily(MTL::GPUFamilyApple8), (int) dev->supportsFamily(MTL::GPUFamilyApple9), + (int) dev->supportsFamily(MTL::GPUFamilyApple10), (int) dev->supportsFamily(MTL::GPUFamilyMetal3), + (int) dev->supportsFamily(MTL::GPUFamilyMetal4)); + std::printf("page size: %ld\n", sysconf(_SC_PAGESIZE)); + + // ---- 2. run-time MSL compile + NS::Error* e = nullptr; + double t0 = now_ms(); + MTL::CompileOptions* co = MTL::CompileOptions::alloc()->init(); + MTL::Library* lib = dev->newLibrary(NS::String::string(kSrc, NS::UTF8StringEncoding), co, &e); + if (!lib) { std::printf("MSL compile failed: %s\n", e ? e->localizedDescription()->utf8String() : "?"); return 1; } + std::printf("MSL run-time compile: %.1f ms\n", now_ms() - t0); + auto pipe = [&](const char* n) { + MTL::Function* f = lib->newFunction(NS::String::string(n, NS::UTF8StringEncoding)); + MTL::ComputePipelineState* p = dev->newComputePipelineState(f, &e); + if (!p) { std::printf("pipeline %s failed\n", n); std::exit(1); } + return p; + }; + MTL::ComputePipelineState* p_axpy = pipe("axpy"); + MTL::ComputePipelineState* p_probe = pipe("probe"); + MTL::ComputePipelineState* p_sum = pipe("sum"); + MTL::CommandQueue* q = dev->newCommandQueue(); + + // ---- 3/4. hello kernel through raw GPU addresses; residency through a residency set + const uint32_t N = 1 << 20; + MTL::Buffer* bx = dev->newBuffer(N * 4, MTL::ResourceStorageModeShared); + MTL::Buffer* by = dev->newBuffer(N * 4, MTL::ResourceStorageModeShared); + std::printf("buffer x: contents %p gpuAddress 0x%llx (%s)\n", bx->contents(), (unsigned long long) bx->gpuAddress(), + (uint64_t) bx->contents() == bx->gpuAddress() ? "EQUAL" : "different"); + float* hx = (float*) bx->contents(); + float* hy = (float*) by->contents(); + for (uint32_t i = 0; i < N; ++i) { hx[i] = (float) i; hy[i] = 1.0f; } + MTL::ResidencySetDescriptor* rd = MTL::ResidencySetDescriptor::alloc()->init(); + MTL::ResidencySet* rs = dev->newResidencySet(rd, &e); + if (!rs) { std::printf("residency set failed\n"); return 1; } + rs->addAllocation(bx); rs->addAllocation(by); rs->commit(); + q->addResidencySet(rs); + { + AxpyArgs a{bx->gpuAddress(), by->gpuAddress(), 2.0f, N}; + MTL::CommandBuffer* cb = q->commandBuffer(); + MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder(); + enc->setComputePipelineState(p_axpy); + enc->setBytes(&a, sizeof a, 0); + enc->dispatchThreads(MTL::Size(N, 1, 1), MTL::Size(256, 1, 1)); + enc->endEncoding(); + cb->commit(); + cb->waitUntilCompleted(); + int bad = 0; + for (uint32_t i = 0; i < N; ++i) if (hy[i] != 2.0f * i + 1.0f) ++bad; + std::printf("hello axpy via raw GPU addresses + residency set: %s (%d bad)\n", bad ? "FAIL" : "OK", bad); + } + // MTLSharedEvent as the CUDA event: signal from the GPU, poll from the host + { + MTL::SharedEvent* ev = dev->newSharedEvent(); + MTL::CommandBuffer* cb = q->commandBuffer(); + MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder(); + AxpyArgs a{bx->gpuAddress(), by->gpuAddress(), 1.0f, N}; + enc->setComputePipelineState(p_axpy); + enc->setBytes(&a, sizeof a, 0); + enc->dispatchThreads(MTL::Size(N, 1, 1), MTL::Size(256, 1, 1)); + enc->endEncoding(); + cb->encodeSignalEvent(ev, 1); + double ts = now_ms(); + cb->commit(); + long spins = 0; + while (ev->signaledValue() < 1) ++spins; + std::printf("shared event: signalled after %.3f ms, %ld host polls\n", now_ms() - ts, spins); + ev->release(); + } + // dispatch cost: 1,000 tiny dispatches in one command buffer (the window-replay cost model) + { + AxpyArgs a{bx->gpuAddress(), by->gpuAddress(), 0.0f, 256}; + for (int rep = 0; rep < 3; ++rep) { + double ts = now_ms(); + MTL::CommandBuffer* cb = q->commandBufferWithUnretainedReferences(); + MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder(); + for (int k = 0; k < 1000; ++k) { + enc->setComputePipelineState(p_axpy); + enc->setBytes(&a, sizeof a, 0); + enc->dispatchThreads(MTL::Size(256, 1, 1), MTL::Size(256, 1, 1)); + } + enc->endEncoding(); + const double te = now_ms(); + cb->commit(); + cb->waitUntilCompleted(); + std::printf("1000 dependent tiny dispatches: encode %.3f ms, encode+run %.3f ms\n", te - ts, now_ms() - ts); + } + } + + // ---- 5. a > 30 GB mmapped file wrapped with newBufferWithBytesNoCopy + if (argc < 2) { pool->release(); return 0; } + const char* path = argv[1]; + const int fd = open(path, O_RDONLY); + if (fd < 0) { std::printf("open %s failed\n", path); return 1; } + struct stat sb; fstat(fd, &sb); + const uint64_t fsize = (uint64_t) sb.st_size; + const uint64_t pg = (uint64_t) sysconf(_SC_PAGESIZE); + const uint64_t mlen = (fsize + pg - 1) / pg * pg; // NoCopy wants a page-multiple length + std::printf("file %s: %.2f GiB\n", path, fsize / 1073741824.0); + for (int mode = 0; mode < 2; ++mode) { + // mode 0: PROT_READ MAP_SHARED (read-only, what the engine wants); mode 1: PROT_READ|PROT_WRITE MAP_PRIVATE + const int prot = mode == 0 ? PROT_READ : (PROT_READ | PROT_WRITE); + const int flags = mode == 0 ? MAP_SHARED : MAP_PRIVATE; + void* m = mmap(nullptr, mlen, prot, flags, fd, 0); + if (m == MAP_FAILED) { std::printf("mmap mode %d failed\n", mode); continue; } + std::printf("-- mode %d (%s): mmap at %p (page aligned %d)\n", mode, mode == 0 ? "PROT_READ MAP_SHARED" : "RW MAP_PRIVATE", m, + (int) (((uintptr_t) m % pg) == 0)); + double ts = now_ms(); + MTL::Buffer* whole = dev->newBuffer(m, mlen, MTL::ResourceStorageModeShared, nullptr); + std::printf(" one NoCopy buffer of %.2f GiB: %s (%.1f ms)\n", mlen / 1073741824.0, whole ? "OK" : "nil", now_ms() - ts); + // chunks of at most maxBufferLength / 2 (and a 4 GiB variant: one chunk per few layers) + std::vector chunks; + const uint64_t chunk = argc > 2 ? (std::strtoull(argv[2], nullptr, 10) << 20) : (4ull << 30); + ts = now_ms(); + bool all = true; + for (uint64_t off = 0; off < mlen; off += chunk) { + const uint64_t len = std::min(chunk, mlen - off); + MTL::Buffer* b = dev->newBuffer((char*) m + off, len, MTL::ResourceStorageModeShared, nullptr); + if (!b) { all = false; break; } + chunks.push_back(b); + } + std::printf(" %zu NoCopy chunks of %.2f GiB: %s (%.1f ms)\n", chunks.size(), chunk / 1073741824.0, all ? "OK" : "FAILED", now_ms() - ts); + // GPU probe reads at 64 offsets spread over the file (the file's pattern: uint32 at offset o equals (o>>12) ^ 0x5a5a5a5a + // where written; holes read 0) + const uint32_t NP = 64; + MTL::Buffer* boffs = dev->newBuffer(NP * 8, MTL::ResourceStorageModeShared); + MTL::Buffer* bout = dev->newBuffer(NP * 4, MTL::ResourceStorageModeShared); + uint64_t* offs = (uint64_t*) boffs->contents(); + for (uint32_t i = 0; i < NP; ++i) offs[i] = ((fsize / NP) * i) & ~(uint64_t) 4095; + auto run_probe = [&](MTL::Buffer* b, uint64_t base_off, const char* what) { + // offsets relative to this buffer's base + std::vector keep(offs, offs + NP); + uint32_t n = 0; + std::vector idx; + for (uint32_t i = 0; i < NP; ++i) + if (keep[i] >= base_off && keep[i] < base_off + b->length()) { offs[n++] = keep[i] - base_off; idx.push_back(i); } + MTL::ResidencySet* r2 = dev->newResidencySet(rd, &e); + r2->addAllocation(b); r2->addAllocation(boffs); r2->addAllocation(bout); r2->commit(); + double tr = now_ms(); + r2->requestResidency(); + const double treq = now_ms() - tr; + ProbeArgs a{b->gpuAddress(), boffs->gpuAddress(), bout->gpuAddress(), n}; + MTL::CommandBuffer* cb = q->commandBuffer(); + cb->useResidencySet(r2); + MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder(); + enc->setComputePipelineState(p_probe); + enc->setBytes(&a, sizeof a, 0); + enc->dispatchThreads(MTL::Size(n ? n : 1, 1, 1), MTL::Size(64, 1, 1)); + enc->endEncoding(); + tr = now_ms(); + cb->commit(); + cb->waitUntilCompleted(); + const double trun = now_ms() - tr; + int okc = 0, bad = 0; + const uint32_t* out = (const uint32_t*) bout->contents(); + for (uint32_t k = 0; k < n; ++k) { + const uint64_t fo = keep[idx[k]]; + uint32_t want = 0; + pread(fd, &want, 4, (off_t) fo); + (out[k] == want ? okc : bad)++; + } + std::printf(" GPU probe %s: %u reads, %d match pread, %d differ (requestResidency %.1f ms, run %.1f ms, status %d)\n", what, n, + okc, bad, treq, trun, (int) cb->status()); + for (uint32_t i = 0; i < NP; ++i) offs[i] = keep[i]; + r2->release(); + }; + if (whole) run_probe(whole, 0, "whole buffer"); + if (all && !chunks.empty()) run_probe(chunks.back(), (chunks.size() - 1) * chunk, "last chunk"); + // a streaming GPU read over one chunk, cold then warm (page cache) + if (all && !chunks.empty()) { + MTL::Buffer* b = chunks[chunks.size() / 2]; + MTL::Buffer* bs = dev->newBuffer(4, MTL::ResourceStorageModeShared); + for (int rep = 0; rep < 2; ++rep) { + *(uint32_t*) bs->contents() = 0; + MTL::ResidencySet* r2 = dev->newResidencySet(rd, &e); + r2->addAllocation(b); r2->addAllocation(bs); r2->commit(); + SumArgs a{b->gpuAddress(), bs->gpuAddress(), b->length() / 16}; + double tr = now_ms(); + MTL::CommandBuffer* cb = q->commandBuffer(); + cb->useResidencySet(r2); + MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder(); + enc->setComputePipelineState(p_sum); + enc->setBytes(&a, sizeof a, 0); + enc->dispatchThreads(MTL::Size(40 * 1024, 1, 1), MTL::Size(256, 1, 1)); + enc->endEncoding(); + cb->commit(); + cb->waitUntilCompleted(); + const double dt = now_ms() - tr; + std::printf(" GPU streaming read of a %.2f GiB chunk (%s): %.1f ms = %.1f GB/s\n", b->length() / 1073741824.0, + rep == 0 ? "first touch" : "again", dt, b->length() / dt / 1e6); + r2->release(); + } + bs->release(); + } + for (auto* b : chunks) b->release(); + if (whole) whole->release(); + boffs->release(); bout->release(); + munmap(m, mlen); + } + close(fd); + pool->release(); + return 0; +} diff --git a/metal/setup_mac.py b/metal/setup_mac.py new file mode 100644 index 00000000..d75d47d5 --- /dev/null +++ b/metal/setup_mac.py @@ -0,0 +1,625 @@ +"""setup.py on a Mac: Apple Silicon, the Metal engine (metal/), built from source on the Mac. + + ./setup.sh [options] (setup.py hands a macOS run to this file; the PC paths are not used) + +What it does, each step skipped when it is already done: + + 1. checks the Mac: Apple Silicon, the chip, unified memory, macOS version, the Command Line Tools, free disk + 2. recommends a model by memory (recommend, never force: an explicit --model is kept, with what it risks) + 3. installs the Python packages into .venv (cmake and ninja come from pip: no Homebrew, no sudo) + 4. builds the Metal engine from source: metal-cpp (Apple's headers) and llama.cpp's ggml at the pinned commit + 5. downloads the model (setup.py's downloader: resumable, the pinned revision) + 6. prepares the model: the native pack (tools/iq_pack.py) and the MTP draft layer (tools/mtp_fetch.py, mtp_pack.py) + 7. writes strata-.json and run-.sh with the Metal defaults (--spec 2, the Q8_0 hyper-connection + read) and starts the server (serve/server.py), the same as on a PC + +Everything shared - the model table, the downloader, the config and run-script writers, the server - is setup.py's. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import platform +import shutil +import subprocess +import sys +import zipfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT)) +import setup as S # noqa: E402 + +# Apple's metal-cpp headers for the macOS 26 SDK (https://developer.apple.com/metal/cpp/), pinned by SHA-256 +METAL_CPP_URL = "https://developer.apple.com/metal/cpp/files/metal-cpp_26.zip" +METAL_CPP_SHA256 = "4df3c078b9aadcb516212e9cb03004cbc5ce9a3e9c068fa3144d021db585a3a4" +BUILD_DIR = ROOT / "build-metal" +EXE = BUILD_DIR / "strata" +MIN_MACOS = (15, 0) # MTLResidencySet (the engine keeps every buffer resident through one) + +# The Mac's packs. shard1_gb: the file the GPU maps (resident in unified memory while the model runs); the n-gram +# table (shard 2, 28.8 GB) is read from the SSD a few rows at a time. tested: measured on the M5 Max (docs/MAC.md). +MAC_MODELS = { + "Q2_0": {"shard1_gb": 37.6, "tested": True}, + "IQ3_XXS": {"shard1_gb": 47.0, "tested": True}, + "IQ3_S": {"shard1_gb": 54.8, "tested": True}, + # Unsloth's ~4-6-bit files (family "unsloth", 4-6 shards cutting through layers): setup repacks the experts and + # dense tensors into one GGUF for the GPU (metal/tools/metal_repack.py); shard1_gb is that file, the n-gram + # table stays in its shard on the SSD + "UD-Q4_K_XL": {"shard1_gb": 82.6, "tested": True, "family": "unsloth", "shards": 4}, + "UD-Q5_K_XL": {"shard1_gb": 103.9, "tested": True, "family": "unsloth", "shards": 6}, + "UD-Q6_K_XL": {"shard1_gb": 114.8, "tested": True, "family": "unsloth", "shards": 6}, +} +# the Unsloth files at setup.py's pinned revision: name -> (bytes, SHA-256), the Hub's LFS pointers (UD-Q4_K_XL's +# are setup.py's UNSLOTH_SHARDS) +UD_SHARDS = { + "Qwen3.8-Flash-Next-UD-Q5_K_XL-00001-of-00006.gguf": (10946618, "610922cdb1afe1094e95d7a3e86b12ee33317ebbf7320ac9344e21b6ae4bb69f"), + "Qwen3.8-Flash-Next-UD-Q5_K_XL-00002-of-00006.gguf": (682434912, "494ca4ed3dbf97bc28da88af3890b8877b9032f909812d00c0526a9ca5e91d2e"), + "Qwen3.8-Flash-Next-UD-Q5_K_XL-00003-of-00006.gguf": (54400261312, "34efd79a80a1ce540a517a5d56171924b66ce1c38b04c904f17ad6d8ef17cf20"), + "Qwen3.8-Flash-Next-UD-Q5_K_XL-00004-of-00006.gguf": (49990245824, "9ee6bbe462e6830864382d629101490625b1c95afa15492b7ad550c7bed2dd13"), + "Qwen3.8-Flash-Next-UD-Q5_K_XL-00005-of-00006.gguf": (49882416192, "0b2437f661f584030cb5aeb8fb1bb70f6422518a6746bfcc0304167c7b6b8beb"), + "Qwen3.8-Flash-Next-UD-Q5_K_XL-00006-of-00006.gguf": (3320101792, "55dd96c5ad0863b06b6393151b9ad0ac727b8d58a62e02a296ca5d5ddbfee4a3"), + "Qwen3.8-Flash-Next-UD-Q6_K_XL-00001-of-00006.gguf": (10946624, "8bdc6bad55b6699f46f60708829932ff4018d7ac9bd309c388534fa31753bdb7"), + "Qwen3.8-Flash-Next-UD-Q6_K_XL-00002-of-00006.gguf": (682434912, "494ca4ed3dbf97bc28da88af3890b8877b9032f909812d00c0526a9ca5e91d2e"), + "Qwen3.8-Flash-Next-UD-Q6_K_XL-00003-of-00006.gguf": (54400261312, "34efd79a80a1ce540a517a5d56171924b66ce1c38b04c904f17ad6d8ef17cf20"), + "Qwen3.8-Flash-Next-UD-Q6_K_XL-00004-of-00006.gguf": (49814108512, "0ea4b599880a5a52fcd9c188ba1443f646c69c96571904ddbd6a79246a01a997"), + "Qwen3.8-Flash-Next-UD-Q6_K_XL-00005-of-00006.gguf": (49419317344, "9948e81ae8368144b135a7403d8c0f2cf9a6c2f9f692313865855b2832e696c9"), + "Qwen3.8-Flash-Next-UD-Q6_K_XL-00006-of-00006.gguf": (14838313984, "e4ae255234f42b18012f6d6eec5bf615b57479b7e0a0233c47436a321ffeec3f"), +} + + +def model_shard_names(model: str) -> list[str]: + """The model's files in order (shard 1 first).""" + n = MAC_MODELS[model].get("shards", 2) + if MAC_MODELS[model].get("family") == "unsloth": + return [f"Qwen3.8-Flash-Next-{model}-{i:05d}-of-{n:05d}.gguf" for i in range(1, n + 1)] + return [S.model_file(S.FAMILIES["qwen"], model, i) for i in range(1, n + 1)] + + +def shard_sha(name: str): + return UD_SHARDS.get(name) or getattr(S, "UNSLOTH_SHARDS", {}).get(name) +# The recommended sizes (owner's decision): IQ3_S is the default where it stays resident, UD-Q4_K_XL the higher-quality one +RECOMMENDED = ("IQ3_S", "UD-Q4_K_XL") # the owner's recommended sizes (UD-IQ4_XS is not offered on Mac yet) +# a pack that does not fit Metal's share streams its experts from the SSD (the engine decides by itself, f-mac-ssd): +# measured on a 32 GB M4 Mac mini, one token per step (MTP is slower there: its layer's memory is worth more as cache) +STREAM_MEASURED = {"Q2_0": "~14 tok/s", "IQ3_XXS": "~10 tok/s"} +STREAM_COPY_GAIN = "decoding about 15%, prompts about 25%" # without the experts' copy, on the 32 GB M4 (IQ3_XXS) +# A streaming Mac with this much memory keeps most of the experts in its arena (the 128 GB M5 Max: 80% of UD-Q5_K_XL's): +# there the draft layer pays, and a longer window pays more because every window costs a fixed hand-shake per layer +# (UD-Q5_K_XL, story: 28 tok/s without MTP, 41.8 at --spec 2, 50.6 at --spec 3). Smaller Macs stream without it. +STREAM_MTP_FROM_GB = 96 +STREAM_SPEC = 3 +# beside the mapped file: the prompt kernels' buffers (chunks of 2,048 rows), the KV cache, the draft layer, the +# Q8_0 copies of the hyper-connection matrices and the macOS desktop +OVERHEAD_GB = 8.0 +# the share of the unified memory Metal lets one process keep resident (recommendedMaxWorkingSetSize): 107.5 of 128 GB +# measured on the M5 Max; 3/4 is the conservative rule for the other sizes +GPU_SHARE = 0.75 +CONTEXTS = [8192, 32768, 65536, 131072] +MAC_ABOUT = {"Q2_0": "2-bit, the fastest", "IQ3_XXS": "3-bit i-quant, better quality", + "IQ3_S": "3.5-bit i-quant, the best quality (matches the full model), the slowest", + "UD-Q4_K_XL": "Unsloth ~4.5-bit (111 GB download)", "UD-Q5_K_XL": "Unsloth ~5.5-bit (158 GB download)", + "UD-Q6_K_XL": "Unsloth ~6.5-bit (169 GB download)"} +TESTED_CONTEXT = 32768 # needles and the KL harness ran to 32K on the Mac + + +# ------------------------------------------------------------------------------------------------ the Mac +def _sysctl(name: str, run=subprocess.run) -> str: + try: + return run(["sysctl", "-n", name], capture_output=True, text=True, timeout=10).stdout.strip() + except (OSError, subprocess.SubprocessError): + return "" + + +def mac_info(run=subprocess.run) -> dict: + """The chip, its unified memory, macOS, the architecture and the Command Line Tools.""" + chip = _sysctl("machdep.cpu.brand_string", run) or "unknown chip" + try: + ram = int(_sysctl("hw.memsize", run) or 0) / 2 ** 30 # GB as Apple sells them (128 GB = 2^37 bytes) + except ValueError: + ram = 0.0 + try: + ver = run(["sw_vers", "-productVersion"], capture_output=True, text=True, timeout=10).stdout.strip() + except (OSError, subprocess.SubprocessError): + ver = "" + try: + clt = run(["xcode-select", "-p"], capture_output=True, text=True, timeout=10) + clt_path = clt.stdout.strip() if clt.returncode == 0 else "" + except (OSError, subprocess.SubprocessError): + clt_path = "" + return {"chip": chip, "ram_gb": ram, "macos": ver, "arm64": platform.machine() == "arm64", + "clt": clt_path, "perf_cores": int(_sysctl("hw.perflevel0.physicalcpu", run) or 0)} + + +def macos_tuple(ver: str) -> tuple: + try: + return tuple(int(x) for x in ver.split(".")[:2]) + except ValueError: + return (0, 0) + + +def mac_problems(info: dict) -> list[str]: + """What stops the setup on this Mac (each with what to do).""" + p = [] + if not info["arm64"]: + p.append(f"this Mac has an Intel CPU ({info['chip']}): the Metal engine needs Apple Silicon (M1 or newer)") + if macos_tuple(info["macos"]) < MIN_MACOS: + p.append(f"macOS {info['macos'] or '?'}: the Metal engine needs macOS {MIN_MACOS[0]} or newer (System Settings " + "> General > Software Update)") + if not info["clt"]: + p.append("the Command Line Tools are missing (the compiler the engine is built with): run " + "`xcode-select --install`, then this setup again") + return p + + +def gpu_budget_gb(ram_gb: float) -> float: + return ram_gb * GPU_SHARE + + +def model_need_gb(model: str) -> float: + return MAC_MODELS[model]["shard1_gb"] + OVERHEAD_GB + + +def streams(model: str, ram_gb: float) -> bool: + """The pack does not fit Metal's share of the memory: the engine streams its experts from the SSD.""" + return model_need_gb(model) > gpu_budget_gb(ram_gb) + + +def recommend_model(ram_gb: float) -> tuple[str, list[str]]: + """The default pack and the notes that go with it. IQ3_S and UD-Q4_K_XL are the recommended sizes (RECOMMENDED): + the default is IQ3_S when it stays resident, with UD-Q4_K_XL named as the higher-quality choice where it fits too; + below that the largest pack that stays resident (IQ3_XXS, Q2_0); nothing fits: Q2_0 streamed from the SSD.""" + if not streams("IQ3_S", ram_gb): + notes = [] + if not streams("UD-Q4_K_XL", ram_gb): + notes.append("UD-Q4_K_XL (recommended too) also fits this Mac: higher quality than IQ3_S (92.8% top-1 against " + "Q8_0 where IQ3_S has 87.9%), about 20% slower on a story; choose it with --model UD-Q4_K_XL") + return "IQ3_S", notes + for m in ("IQ3_XXS", "Q2_0"): + if not streams(m, ram_gb): + return m, [] + return "Q2_0", [f"{ram_gb:.0f} GB of memory: no pack fits whole, so the engine streams the experts from the SSD " + f"(automatic; measured on a 32 GB M4: Q2_0 {STREAM_MEASURED['Q2_0']}, IQ3_XXS " + f"{STREAM_MEASURED['IQ3_XXS']}; smaller Macs are untested). Recommended: Q2_0, without the MTP " + "draft layer (slower when streaming)"] + + +def model_note(model: str, ram_gb: float) -> list[str]: + """What a chosen pack risks on this Mac (said, never refused).""" + notes = [] + if streams(model, ram_gb): + notes.append(f"{model} needs ~{model_need_gb(model):.0f} GB of the {gpu_budget_gb(ram_gb):.0f} GB Metal keeps " + "resident on this Mac: its experts stream from the SSD (automatic)" + + (f"; measured on a 32 GB M4: {STREAM_MEASURED[model]}" if model in STREAM_MEASURED else + "; not measured streaming")) + if MAC_MODELS[model].get("missing"): + notes.append(f"{model} does not run on this Metal engine yet ({MAC_MODELS[model]['missing']} are missing): the " + "engine will stop when it loads; kept as you chose (for testing a newer engine)") + elif not MAC_MODELS[model]["tested"]: + notes.append(f"{model} has not been measured on a Mac yet") + return notes + + +def recommend_context(ram_gb: float) -> int: + return 32768 if ram_gb < 96 else 65536 + + +# ------------------------------------------------------------------------------------------------ the engine +def metal_cpp() -> Path: + """Apple's metal-cpp headers in third_party/metal-cpp (one zip, pinned).""" + dst = ROOT / "third_party" / "metal-cpp" + if (dst / "Metal" / "Metal.hpp").exists(): + return dst + z = ROOT / "third_party" / "metal-cpp_26.zip" + S.download(METAL_CPP_URL, z, "metal-cpp (Apple's Metal headers)") + S.verify_sha256(z, z.stat().st_size, METAL_CPP_SHA256) + tmp = ROOT / "third_party" / "_metal_cpp" + shutil.rmtree(tmp, ignore_errors=True) + with zipfile.ZipFile(z) as f: + f.extractall(tmp) + shutil.rmtree(dst, ignore_errors=True) + shutil.move(str(tmp / "metal-cpp"), str(dst)) + shutil.rmtree(tmp, ignore_errors=True) + return dst + + +def tool(name: str) -> str: + """cmake / ninja from the venv's pip packages (no Homebrew).""" + p = Path(sys.executable).parent / name + return str(p) if p.exists() else (shutil.which(name) or name) + + +def engine_current() -> bool: + try: + meta = json.loads((BUILD_DIR / "BUILD.json").read_text(encoding="utf-8")) + except (OSError, ValueError): + return False + return EXE.exists() and meta.get("version") == S.source_version() and meta.get("source") == source_digest() + + +def source_digest() -> str: + """What the engine is built from: every source file's path, size and modification time (src/, include/, metal/, + third_party/ggml). A git pull, an unzipped update or a local edit changes it; nothing else does.""" + h = hashlib.sha256() + for d in ("src", "include", "metal", "third_party/ggml"): + for f in sorted((ROOT / d).rglob("*")): + if f.is_file() and f.suffix in (".cpp", ".cu", ".h", ".hpp", ".mm", ".metal", ".inc", ".txt", ".cuh"): + st = f.stat() + h.update(f"{f.relative_to(ROOT).as_posix()}|{st.st_size}|{int(st.st_mtime)}\n".encode()) + return h.hexdigest() + + +def build_engine(llama: Path, jobs: int | None = None) -> Path: + """The Metal engine from source: cmake + ninja (pip's), Apple's clang from the Command Line Tools.""" + if engine_current(): + S.ok(f"Metal engine: {EXE} (built for this source)") + return EXE + mcpp = metal_cpp() + S.say(" Building the Metal engine from source (5-15 minutes the first time) ...") + BUILD_DIR.mkdir(exist_ok=True) + log = BUILD_DIR / "build.log" + env = dict(os.environ, PATH=str(Path(sys.executable).parent) + os.pathsep + os.environ.get("PATH", "")) + cfg = [tool("cmake"), "-S", str(ROOT / "metal"), "-B", str(BUILD_DIR), "-G", "Ninja", "-DCMAKE_BUILD_TYPE=Release", + f"-DCMAKE_MAKE_PROGRAM={tool('ninja')}", f"-DMETAL_CPP_DIR={mcpp}", f"-DSTRATA_GGML_DIR={llama}"] + build = [tool("ninja"), "-C", str(BUILD_DIR), "strata"] + (["-j", str(jobs)] if jobs else []) + with open(log, "w", encoding="utf-8") as f: + for cmd in (cfg, build): + rc = subprocess.call(cmd, stdout=f, stderr=subprocess.STDOUT, env=env) + if rc != 0: + S.fail(f"the Metal engine did not build (see {log})", + "the last lines of the log name the problem; the Command Line Tools must be up to date " + "(softwareupdate --list)") + (BUILD_DIR / "BUILD.json").write_text(json.dumps({"version": S.source_version(), "source": source_digest(), + "backend": "metal"}, indent=1), encoding="utf-8") + S.ok(f"Metal engine built: {EXE}") + return EXE + + +# ------------------------------------------------------------------------------------------------ the config +def stream_mtp(stream: bool, ram_gb: float) -> bool: + """Whether the config carries the MTP draft layer: always when the model is resident; when it streams, only on a + Mac with STREAM_MTP_FROM_GB or more (a 32 GB M4 is faster without it).""" + return (not stream) or ram_gb >= STREAM_MTP_FROM_GB + + +def engine_args(pack: Path, shards: list, rt: Path, ctx: int, stream: bool = False, ram_gb: float = 0.0) -> list[str]: + """The Metal defaults: --spec 2 with the MTP draft layer (measured best on the M5 Max, docs/MAC.md) and the Q8_0 + hyper-connection read (the engine's default on Metal; STRATA_HC_Q8=0 in the config's env gives the exact BF16 + read). Streaming from the SSD: one token per step, no draft layer (measured faster on the 32 GB M4); a streaming + Mac with STREAM_MTP_FROM_GB or more keeps the draft layer and uses --spec STREAM_SPEC.""" + mtp = stream_mtp(stream, ram_gb) + args = ["--pack", str(pack), "--native", str(shards[0]), "--ple-gguf", str(shards[1])] + if shards[0].name.endswith("-metal.gguf"): # the repacked file: it is its own dense GGUF + args += ["--native-dense-gguf", str(shards[0])] + args += [ + "--expert-profile", str(ROOT / "data" / "expert-profile.bin"), "--expert-cache", "64", + "--prefill", "auto", "--spec", str(STREAM_SPEC if stream and mtp else 2)] + args += ["--suffix-draft", "0"] if stream else [] + args += ["--mtp", str(rt)] if mtp else [] + return args + ["--max-context", str(ctx), + "--mmap-experts"] # what the Metal engine does anyway (the GGUF mapped in place); the server says so + + +# the image encoder's projector (setup.py's pinned revision): name -> (bytes, SHA-256) +VISION_SHA256 = {"mmproj-Qwen3.8-Flash-Next-BF16.gguf": + (907543008, "b1a82259702816a5330d7bd7607cd9676b11780e79ff7348c21103ff3ce49bd0")} +VISION_EXE = ROOT / "build-vision" / "bin" / "strata-vision" + + +def build_vision(llama: Path) -> Path: + """strata-vision (tools/vision: llama.cpp's mtmd at the pinned commit), with ggml's Metal backend: the encoder + runs on the GPU.""" + stamp = ROOT / "build-vision" / "BUILD.json" + src = source_digest() + try: + if VISION_EXE.exists() and json.loads(stamp.read_text(encoding="utf-8")).get("source") == src: + S.ok(f"image encoder: {VISION_EXE}") + return VISION_EXE + except (OSError, ValueError): + pass + S.say(" Building the image encoder (1-3 minutes) ...") + env = dict(os.environ, PATH=str(Path(sys.executable).parent) + os.pathsep + os.environ.get("PATH", "")) + log = ROOT / "build-vision.log" + with open(log, "w", encoding="utf-8") as f: + for cmd in ([tool("cmake"), "-S", str(ROOT / "tools" / "vision"), "-B", str(ROOT / "build-vision"), "-G", "Ninja", + "-DCMAKE_BUILD_TYPE=Release", f"-DCMAKE_MAKE_PROGRAM={tool('ninja')}", f"-DLLAMA_DIR={llama}", + "-DSTRATA_VISION_CUDA=OFF", "-DSTRATA_PORTABLE=OFF"], + [tool("ninja"), "-C", str(ROOT / "build-vision"), "strata-vision"]): + if subprocess.call(cmd, stdout=f, stderr=subprocess.STDOUT, env=env) != 0: + S.fail(f"the image encoder did not build (see {log})") + stamp.write_text(json.dumps({"source": src}), encoding="utf-8") + S.ok(f"image encoder built: {VISION_EXE}") + return VISION_EXE + + +def ple_shard(files: list) -> Path: + """The shard that holds the n-gram table (per_layer_token_embd).""" + sys.path.insert(0, str(ROOT / "metal" / "tools")) + import metal_repack as R + for f in files: + rd = R.Reader(f) + rd.f.close() + if any(t["name"] == R.PLE for t in rd.tensors): + return f + S.fail(f"no shard of {files[0].name} holds the n-gram table (per_layer_token_embd)") + + +# the experts' streaming copy (metal/tools/stream_experts.py): what stays free on the disk after it is written +EXPERTS_MARGIN_GB = 10.0 + + +def experts_file_fits(need_gb: float, free_gb: float) -> bool: + return free_gb >= need_gb + EXPERTS_MARGIN_GB + + +def experts_file(native: Path) -> None: + """A streaming Mac: .experts beside the GPU's GGUF - every expert's rows in one piece, read with one SSD + request per expert instead of three (the engine uses it when it is there and matches; else the GGUF). Written + only when the disk has room for it and EXPERTS_MARGIN_GB more; otherwise setup says so and goes on.""" + out = native.with_name(native.name + ".experts") + if out.exists() and S.done(out): + S.ok(f"the experts' streaming copy: {out.name}") + return + sys.path.insert(0, str(ROOT / "metal" / "tools")) + import stream_experts as X + need = X.size_bytes(native) / 1e9 + free = S.free_gb(native.parent) + if not os.access(native.parent, os.W_OK): + S.warn(f"{native.parent} cannot be written: the experts' streaming copy ({need:.0f} GB) is not written; the " + f"engine streams from the model file ({STREAM_COPY_GAIN} slower)") + return + if not experts_file_fits(need, free): + S.warn(f"the experts' streaming copy needs {need:.0f} GB and {EXPERTS_MARGIN_GB:.0f} GB to spare on the disk " + f"({free:.0f} GB free): not written; the engine streams from the model file ({STREAM_COPY_GAIN} " + f"slower). Free some space and run ./setup.sh --setup again to add it") + return + S.say(f" Writing the experts in SSD-read order (one time, {need:.0f} GB; each expert is read with one request) ...") + S.run([sys.executable, str(ROOT / "metal" / "tools" / "stream_experts.py"), "--gguf", str(native), "--verify"]) + S.mark(out) + S.ok(f"the experts' streaming copy: {out.name}") + + +def mac_config(exe: Path, args: list, pack: Path, model_name: str, tag: str, port: int) -> dict: + return {"exe": str(exe), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"), + "model_name": model_name, "log": str(ROOT / f"strata-{tag.lower()}.log"), "lib_dirs": [], "port": port, + "backend": "metal"} + + +def mac_configs() -> list[Path]: + out = [] + for p in S.installed_configs(): + try: + if json.loads(p.read_text(encoding="utf-8-sig")).get("backend") == "metal": + out.append(p) + except (OSError, ValueError): + pass + return out + + +def start(cfg_path: Path, port: int | None, open_browser: bool = True) -> int: + """serve/server.py with this config (setup.py's start without the NVIDIA / AMD card checks).""" + cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig")) + missing = [p for p in [cfg["exe"], *[a for a in cfg["args"] if a.endswith(".gguf")]] if not Path(p).exists()] + if missing: + S.fail(f"{cfg_path.name} refers to missing files: {missing[0]}", "run ./setup.sh --setup to repair it") + cfg_path.touch() + if "--mtp" in cfg["args"][:-1]: + S.refresh_draft_vocab(Path(cfg["args"][cfg["args"].index("--mtp") + 1]), cfg.get("draft_vocab", "cjk")) + cmd = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), + "--port", str(port or cfg.get("port", 8080))] + if open_browser and cfg.get("open_browser") is not False: + cmd.append("--open") + S.say() + S.say(f" Starting {cfg.get('model_name', 'the model')} on Metal: the engine maps the model file and is ready in about " + "half a minute (longer the first time after a restart, while macOS reads the file).") + S.say(" Closing this window stops the model.") + return subprocess.call(cmd) + + +# ------------------------------------------------------------------------------------------------ main +def main(argv=None) -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--family", choices=["qwen", "unsloth"], default=None, + help="qwen = Qwen3.8-Flash-Next (GSQ-RCO), unsloth = Unsloth's UD-*_K_XL (follows --model)") + ap.add_argument("--model", choices=list(MAC_MODELS)) + ap.add_argument("--context", type=int) + ap.add_argument("--port", type=int) + ap.add_argument("--host") + ap.add_argument("--api-key") + ap.add_argument("--draft-vocab", choices=list(S.DRAFT_VOCABS)) + ap.add_argument("--no-browser", dest="browser", action="store_false", default=None) + ap.add_argument("--data-dir") + ap.add_argument("--models-dir") + ap.add_argument("--gguf-dir") + ap.add_argument("--yes", action="store_true") + ap.add_argument("--setup", action="store_true") + ap.add_argument("--no-start", action="store_true") + ap.add_argument("--check", action="store_true") + ap.add_argument("--update", action="store_true") + ap.add_argument("--build", action="store_true", help="build the engine again even when it is current") + ap.add_argument("--vision", choices=["yes", "no"], + help="let the model read images (the image encoder on the GPU, built here; default: asked, no)") + a, rest = ap.parse_known_args(argv) + if rest: + S.warn("not used on a Mac: " + " ".join(rest)) + S.say("Strata on a Mac (Apple Silicon, Metal)") + data, elsewhere = S.data_folder(a.data_dir) + roots = [data, *elsewhere] + models_root = Path(a.models_dir) if a.models_dir else data / "models" + + have = mac_configs() + if have and not (a.setup or a.model or a.check or a.no_start or a.update or a.build): + return start(have[0], a.port, a.browser is not False) + + # ---- 1. the Mac + S.step(1, "checking your Mac") + info = mac_info() + S.ok(f"{info['chip']}, {info['ram_gb']:.0f} GB unified memory, macOS {info['macos'] or '?'}") + problems = mac_problems(info) + for p in problems: + S.warn(p) + free = S.free_gb(data if data.exists() else ROOT) + S.ok(f"free disk: {free:.0f} GB at {data}") + if a.check: + return 1 if problems else 0 + if problems: + S.fail(problems[0]) + + # ---- 2. the choices + S.step(2, "your choices") + rec, notes = recommend_model(info["ram_gb"]) + for n in notes: + S.warn(n) + if a.model: + model = a.model + else: + names = [m for m in MAC_MODELS if not MAC_MODELS[m].get("missing")] # --model offers the others + for i, m in enumerate(names, 1): + S.say(f" {i}) {m:8} {MAC_ABOUT[m]} (maps {MAC_MODELS[m]['shard1_gb']:.0f} GB" + + ("" if MAC_MODELS[m]["tested"] else ", not measured on a Mac") + ")" + + (" (recommended)" if m in RECOMMENDED else "") + (" <- default" if m == rec else "")) + model = names[int(S.ask("Which size?", [str(i) for i in range(1, len(names) + 1)], + str(names.index(rec) + 1), a.yes)) - 1] + for n in model_note(model, info["ram_gb"]): + S.warn(n) + vision = a.vision or ("yes" if S.ask("Should the model also read images? (the image encoder, ~1 GB more)", + ["y", "n"], "n", a.yes) == "y" else "no") + ctx = a.context or recommend_context(info["ram_gb"]) + if ctx > TESTED_CONTEXT: + S.say(f" context {ctx}: measured on the Mac up to {TESTED_CONTEXT} (needles found at 8K-32K); longer is kept") + S.ok(f"{model}, context {ctx}") + family = MAC_MODELS[model].get("family", "qwen") + if a.family and a.family != family: + S.warn(f"--family {a.family}: {model} is a {family} file; using {family}") + fam = S.FAMILIES[family] + tag = fam["tag"] + model + need = (0 if a.gguf_dir else S.MODELS[model]["download_gb"]) + 6 # --gguf-dir: the files are there already + if free < need: + S.warn(f"about {need:.0f} GB are needed on the disk ({free:.0f} GB free): kept as you chose; it may run out") + + # ---- 3. Python packages (cmake and ninja among them: the engine build's tools) + S.step(3, "Python packages") + S.pip_install(S.requirement_lines() if S.REQUIREMENTS.exists() else S.PY_PACKAGES, "numpy, jinja2, ..., cmake, ninja") + + # ---- 4. the engine + S.step(4, "the Strata engine (Metal)") + llama = S.get_llama_cpp() + S.ok(f"llama.cpp {S.LLAMA_CPP_COMMIT[:7]} (ggml, gguf-py)") + if a.build: + (BUILD_DIR / "BUILD.json").unlink(missing_ok=True) + exe = build_engine(llama) + if a.update: + return 0 + + # ---- 5. the model + S.step(5, f"downloading {fam['title']} {model}") + models_dir = Path(a.gguf_dir) if a.gguf_dir else models_root / tag + models_dir.mkdir(parents=True, exist_ok=True) + files = [models_dir / n for n in model_shard_names(model)] + for s in files: + if s.exists() and S.done(s): + S.ok(f"{s.name} already downloaded") + continue + S.download(fam["hf"].format(q=model) + s.name, s) + S.check_shards(files) + for s in files: # the Unsloth files: pinned sizes and SHA-256 + if shard_sha(s.name): + S.verify_sha256(s, *shard_sha(s.name)) + S.ok("model files present") + + mmproj = vexe = None + if vision == "yes": + mmproj = models_root / fam["mmproj"] + if not (mmproj.exists() and S.done(mmproj)): + S.download(fam["mmproj_hf"] + fam["mmproj"], mmproj, "vision encoder") + sha = VISION_SHA256.get(fam["mmproj"]) + if sha: + S.verify_sha256(mmproj, *sha) + vexe = build_vision(llama) + + # ---- 6. the pack and the MTP draft layer + S.step(6, "preparing the model for Strata") + pack = S.find_in(roots, f"packs/{tag.lower()}") or data / "packs" / tag.lower() + env = dict(os.environ, STRATA_GGUF_PY=str(llama / "gguf-py")) + if len(files) > 2: + # many shards: the experts and dense tensors into one GGUF the GPU maps (or streams), the n-gram table read + # from its own shard (every tensor checked byte for byte: --verify) + native = data / "metal" / f"{tag.lower()}-metal.gguf" + native.parent.mkdir(parents=True, exist_ok=True) + if not (native.exists() and S.done(native)): + S.say(f" Writing the model's experts and weights into one file for the GPU (one time, " + f"{MAC_MODELS[model]['shard1_gb']:.0f} GB) ...") + S.run([sys.executable, str(ROOT / "metal" / "tools" / "metal_repack.py"), "--shard1", str(files[0]), + "--out", str(native), "--verify"]) + S.mark(native) + ple = ple_shard(files) + shards = [native, ple] + else: + shards = files + if not (pack / "native_experts.txt").exists() or not (pack / "tokenizer" / "vocab.json").exists(): + S.run([sys.executable, str(ROOT / "tools" / "iq_pack.py"), "--gguf", str(shards[0]), "--out", str(pack), + *fam.get("pack_args", [])], env=env) # Unsloth: --compat-bf16 (the host's copies; the GPU reads the file) + S.ok(f"model prepared: {pack}") + mtp = (S.find_in(roots, "mtp/mtp-q2_0.gguf") or data / "mtp" / "mtp-q2_0.gguf").parent + rt = mtp / "rt" + stream = streams(model, info["ram_gb"]) + use_mtp = stream_mtp(stream, info["ram_gb"]) + if stream and not use_mtp: + S.ok("the experts will stream from the SSD: no MTP draft layer (one token per step is faster there); " + "./setup.sh --setup on a Mac with more memory adds it") + elif stream: + S.ok(f"the experts will stream from the SSD; the MTP draft layer stays on, with --spec {STREAM_SPEC} " + "(a longer window pays when every window has a fixed cost per layer)") + if stream and info["ram_gb"] < STREAM_MTP_FROM_GB: + experts_file(shards[0]) # a small Mac: its misses are many; a big Mac's arena holds most experts + if use_mtp and not (mtp / "mtp-q2_0.gguf").exists(): + S.say(" The MTP draft layer (speculative decoding) comes from the original Qwen checkpoint: only its ~5 GB of") + S.say(" MTP tensors are downloaded.") + S.run([sys.executable, str(ROOT / "tools" / "mtp_fetch.py"), "fetch", "--out", str(mtp)], + env={**env, "STRATA_SOURCE": S.model_source()}) + S.run([sys.executable, str(ROOT / "tools" / "mtp_pack.py"), "--src", str(mtp), "--experts", "q2_0", + "--out", str(mtp / "mtp-q2_0.gguf")], env=env) + if use_mtp: + rt.mkdir(parents=True, exist_ok=True) # the Metal engine reads mtp-q2_0.gguf beside it (no rt pack) + S.refresh_draft_vocab(rt, a.draft_vocab or "cjk") + S.ok(f"MTP draft layer: {mtp / 'mtp-q2_0.gguf'}") + + # ---- 7. the config, the start script + S.step(7, "writing the start script") + port = a.port or 8080 + cfg = mac_config(exe, engine_args(pack, shards, rt, ctx, stream, info["ram_gb"]), pack, f"{fam['name']}-{model.lower()}", tag, port) + cfg["env"] = {"STRATA_METAL_STREAM": "1" if stream else "0"} # the engine follows setup's measured choice + if vision == "yes": + cfg["args"] += ["--vision"] + cfg["vision"] = {"exe": str(vexe), "mmproj": str(mmproj), "model": str(files[0]), "gpu": True, + "max_tokens": 1024} + if a.host: + cfg["host"] = a.host + if a.api_key: + cfg["api_key"] = a.api_key + if a.draft_vocab: + cfg["draft_vocab"] = a.draft_vocab + if a.browser is not None: + cfg["open_browser"] = a.browser + cfg_path = ROOT / f"strata-{tag.lower()}.json" + S.write_config(cfg_path, cfg) + script = S.write_run_script(tag, cfg_path, port, cfg.get("open_browser") is not False) + S.ok(f"start script: {script.name}") + S.say() + S.say("All set.") + S.say(f" API (OpenAI): http://127.0.0.1:{port}/v1") + S.say(f" API (Anthropic): http://127.0.0.1:{port}/v1/messages") + S.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, a.browser is not False) + + +if __name__ == "__main__": + try: + sys.exit(main()) + except KeyboardInterrupt: + S.say("\nstopped.") + sys.exit(1) diff --git a/metal/src/engine/arena_budget.h b/metal/src/engine/arena_budget.h new file mode 100644 index 00000000..fbb1c221 --- /dev/null +++ b/metal/src/engine/arena_budget.h @@ -0,0 +1,102 @@ +// metal/src/engine/arena_budget.h - how big the SSD-streaming expert arena may be (stream.h), as plain arithmetic so it +// can be tested without a Mac (metal/tests/arena_budget_test.cpp). +// +// The arena is anonymous memory the GPU keeps resident: macOS cannot page it out or drop it like file cache. It must +// leave room for macOS and the desktop, and for the other big memory the engine itself uses while it runs: +// keep macOS and the desktop: max(7 GB, 15% of the RAM) - STRATA_METAL_KEEP_FREE_GB sets it. The M5 Max +// (128 GB) froze with an 89 GB arena and 7 GB kept beside a 50 GB n-gram table; with 15% it keeps 20.6 GB. +// The 32 GB M4 (IQ3_XXS after a 6K prompt, 5 interleaved runs, memory_pressure every 3 s, vm_stat +// swapouts): 7 GB kept + 2 GB reserve 5.93 tok/s (arena ~8.5 GB, least free 50%), 7 + 0.5 6.59 (~10 GB, +// 49%), 5 + 0.5 7.47 (~12 GB, 43%); no swap-out in any run. But a 34-minute server soak with 5 GB kept +// swapped out 93 MB while its 11.7 GB arena filled (none after): 7 GB again. +// ple the n-gram table: mapped whole in RAM (--ple-io ram) it is all of it; read row by row (the default, +// F_NOCACHE: no file cache) only its bounded row cache, 1M rows of at most 192 bytes: 0.5 GB reserved. +// GPU the Metal working set less what is already allocated, less 1 GB. +// STRATA_METAL_ARENA_GB sets the arena outright. The arena is placed just before it is filled, and the memory macOS +// can give is asked again then: when it has dropped (another program), the arena shrinks (arena_shrink). +// "Available" (arena_avail) counts free and purgeable pages and the file cache macOS drops without writing anything: +// inactive pages, but no more of them than there are file-backed pages. Inactive anonymous memory (other programs') +// is left out: macOS frees it only by compressing or swapping it (the soak's 93 MB swapped out while an arena planned +// with every inactive page filled). Free + purgeable alone is too little: at the engine's start the model file's own +// pages fill the cache (6.4 GB free + purgeable on the 32 GB M4 against 15 GB a minute later). The arena is filled in steps (STRATA_METAL_ARENA_STEP_GB, default 1.5): before each step the free +// memory is asked again, and the fill stops - the rest of the arena's slots unused - when a step would take macOS +// below what it keeps (arena_grow). +#pragma once + +#include + +namespace strata::metal_engine { + +struct ArenaMem { + double phys = 0; // bytes of RAM + double working_set = 0; // the Metal device's recommended working set + double allocated = 0; // already allocated by the engine (Metal buffers) + double available = 0; // what macOS can give now without paging anything out (arena_avail) + double ple_mapped = 0; // the n-gram table's bytes when it is mapped whole in RAM, else 0 + double keep_gb = -1; // STRATA_METAL_KEEP_FREE_GB (< 0: unset) + double arena_gb = -1; // STRATA_METAL_ARENA_GB (< 0: unset) +}; + +constexpr double kGB = 1e9; + +// The GPU keeps the whole arena (and the engine's other buffers) resident through a residency set, i.e. wired. Measured on the +// M5 Max (137.4 GB), UD-Q6_K_XL: 84 GB of arena + 7.5 GB allocated (91.5 GB, 67%) ran with no swap-out; 90 GB + 7.5 GB (97.5 GB) +// made macOS swap 29,000 pages in 8 s with a "warn" pressure level and the Mac went on to freeze; UD-Q5 with 90 GB + 5.7 GB ran, +// near the edge. So arena + allocated stay under this share of the RAM, whatever the free-memory count says. +constexpr double kWiredShare = 0.67; + +/// Bytes macOS can give without compressing or swapping: free + purgeable + the clean file cache (inactive and +/// speculative pages, at most the file-backed ones). +inline double arena_avail(double free_b, double purgeable_b, double inactive_b, double speculative_b, double file_b) { + return free_b + purgeable_b + std::min(inactive_b + speculative_b, file_b); +} + +inline double arena_keep(const ArenaMem& m) { + return m.keep_gb >= 0 ? m.keep_gb * kGB : std::max(7.0 * kGB, 0.15 * m.phys); +} + +inline double arena_ple_reserve(const ArenaMem& m) { return m.ple_mapped > 0 ? m.ple_mapped : 0.5 * kGB; } + +/// The arena's bytes (at least 1 GB: a smaller arena still runs, at a low hit rate). +inline double arena_budget(const ArenaMem& m) { + if (m.arena_gb >= 0) return m.arena_gb * kGB; + const double gpu = m.working_set - m.allocated - 1.0 * kGB; + const double ram = m.available - arena_keep(m) - arena_ple_reserve(m); + const double wired = kWiredShare * m.phys - m.allocated; + return std::max(1.0 * kGB, std::min(std::min(gpu, ram), wired)); +} + +/// Just before the arena is filled: the bytes it may still have when macOS can now give `available_now` (it shrinks, +/// never grows; the explicit STRATA_METAL_ARENA_GB is kept as it is). +inline double arena_shrink(const ArenaMem& m, double planned, double available_now) { + if (m.arena_gb >= 0) return planned; + ArenaMem now = m; + now.available = available_now; + return std::min(planned, arena_budget(now)); +} + +/// The stepped fill: may the next `step` bytes of the arena be filled while macOS has `available_now` free + purgeable? +/// (the explicit STRATA_METAL_ARENA_GB always fills) +inline bool arena_grow(const ArenaMem& m, double available_now, double step) { + if (m.arena_gb >= 0) return true; + return available_now - step >= arena_keep(m) + arena_ple_reserve(m); +} + +/// The fill as a plan, for the test: the pairs' bytes in rank order, steps of `step` bytes, `avail(filled)` the free +/// memory once `filled` bytes are in. Returns how many pairs are filled. +template +inline size_t arena_fill_plan(const ArenaMem& m, const double* cost, size_t n, double step, Avail avail) { + size_t i = 0; + double filled = 0; + while (i < n) { + double s = 0; + size_t j = i; + while (j < n && (s < step || j == i)) s += cost[j++]; + if (!arena_grow(m, avail(filled), s)) break; + filled += s; + i = j; + } + return i; +} + +} // namespace strata::metal_engine diff --git a/metal/src/engine/iq_host.cpp b/metal/src/engine/iq_host.cpp new file mode 100644 index 00000000..7c893382 --- /dev/null +++ b/metal/src/engine/iq_host.cpp @@ -0,0 +1,90 @@ +// metal/src/engine/iq_host.cpp - the host-side helpers of src/kernels/cuda/iq_kernels.cu the shared host code reads +// (format tables, row sizes, the native expert blob layout). The kernels themselves are not ported: on Metal the +// decode window runs mac-kern's chain (metal/src/engine/window.cpp). Copied from iq_kernels.cu; keep in step. +#include "strata/kernels/iq_kernels.hpp" + +#define GGML_COMMON_DECL_CPP +#include "ggml-common.h" + +#include +#include + +namespace strata::kernels { +namespace { +bool is_iq(int t) { + return t == 16 || t == 17 || t == 18 || t == 20 || t == 21 || t == 22 || t == 23 || t == 29 || t == 42 || t == 11 || + t == 12 || t == 13 || t == 14 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8; // 14: Q6_K (Unsloth's Q5/Q6 gate/up) +} +// values per block of the types the grouped expert kernels take (0 = none): STRATA_GU_FMTS / STRATA_D_FMTS +int gu_qk(int t) { + switch (t) { + case 16: case 17: case 18: case 21: case 22: case 23: case 29: case 12: case 13: case 14: return 256; + case 42: return 64; + case 6: case 2: case 3: case 8: return 32; + default: return 0; + } +} +int d_qk(int t) { + switch (t) { + case 23: return 256; + case 42: return 64; + case 20: case 7: case 6: case 2: case 3: case 8: return 32; + default: return 0; + } +} +} // namespace + +bool iq_supported(int t) noexcept { return is_iq(t); } +bool embed_type_supported(int t) noexcept { return is_iq(t) || t == 30; } + +size_t iq_row_bytes(int t, int64_t n) noexcept { + switch (t) { + case 16: return (size_t) (n / 256) * sizeof(block_iq2_xxs); + case 17: return (size_t) (n / 256) * sizeof(block_iq2_xs); + case 18: return (size_t) (n / 256) * sizeof(block_iq3_xxs); + case 20: return (size_t) (n / 32) * sizeof(block_iq4_nl); + case 21: return (size_t) (n / 256) * sizeof(block_iq3_s); + case 22: return (size_t) (n / 256) * sizeof(block_iq2_s); + case 29: return (size_t) (n / 256) * sizeof(block_iq1_m); + case 23: return (size_t) (n / 256) * sizeof(block_iq4_xs); + case 11: return (size_t) (n / 256) * sizeof(block_q3_K); + case 42: return (size_t) (n / 64) * sizeof(block_q2_0); + case 12: return (size_t) (n / 256) * sizeof(block_q4_K); + case 13: return (size_t) (n / 256) * sizeof(block_q5_K); + case 14: return (size_t) (n / 256) * sizeof(block_q6_K); + case 7: return (size_t) (n / 32) * sizeof(block_q5_1); + case 6: return (size_t) (n / 32) * sizeof(block_q5_0); + case 2: return (size_t) (n / 32) * sizeof(block_q4_0); + case 3: return (size_t) (n / 32) * sizeof(block_q4_1); + case 8: return (size_t) (n / 32) * sizeof(block_q8_0); + case 30: return (size_t) n * 2; + default: return 0; + } +} + +bool native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept { + const int qg = gu_qk(gu_type), qd = d_qk(d_type); + return qg > 0 && qd > 0 && is_iq(gu_type) && is_iq(d_type) && n_embd % qg == 0 && n_ff % qd == 0 && + n_embd % 256 == 0 && (n_ff * n_embd) % 256 == 0; +} + +NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) { + NativeExpertLayout L; + L.gu_type = gu_type; + L.d_type = d_type; + L.n_embd = n_embd; + L.n_ff = n_ff; + L.gu_row = iq_row_bytes(gu_type, n_embd); + L.d_row = iq_row_bytes(d_type, n_ff); + L.up_off = (size_t) n_ff * L.gu_row; + L.down_off = 2 * L.up_off; + L.bytes = L.down_off + (size_t) n_embd * L.d_row; + return L; +} + +size_t native_expert_scratch_bytes(int64_t cap, int64_t n_ff) { + const size_t f = (size_t) cap * (size_t) n_ff * sizeof(float); + return 3 * ((f + 255) & ~(size_t) 255) + (((size_t) cap * (size_t) (n_ff / 32) * sizeof(block_q8_1) + 255) & ~(size_t) 255); +} + +} // namespace strata::kernels diff --git a/metal/src/engine/missing.cpp b/metal/src/engine/missing.cpp new file mode 100644 index 00000000..27ecec2d --- /dev/null +++ b/metal/src/engine/missing.cpp @@ -0,0 +1,80 @@ +// metal/src/engine/missing.cpp - what a kernel entry point that has no Metal implementation yet does when called. +// +// Default: say which one and stop (exit code 86), so a run never continues on outputs nobody wrote. +// STRATA_METAL_STUBS=log: say it once per entry point and return (outputs untouched) - for listing which entry points a +// code path reaches, never for answers. +#include +#include +#include +#include +#include + +namespace strata::metal_engine { + +void missing(const char* name) { + static const bool log_only = [] { + const char* v = std::getenv("STRATA_METAL_STUBS"); + return v != nullptr && std::string(v) == "log"; + }(); + if (!log_only) { + std::fprintf(stderr, "strata metal: %s has no Metal implementation yet\n", name); + std::fflush(stderr); + std::_Exit(86); + } + static std::mutex mu; + static std::set seen; + std::lock_guard lk(mu); + if (seen.insert(name).second) std::fprintf(stderr, "strata metal: STUB %s\n", name); +} + +} // namespace strata::metal_engine + +// ---- entry points the shared host loop asks every request, with nothing to do on Metal yet +#include "strata/kernels/cvec.hpp" +namespace strata::kernels { +// no control vector on Metal (--control-vector-scaled is not ported): the empty one, `loaded()` false +const Cvec& cvec() { + static const Cvec none{}; + return none; +} +} // namespace strata::kernels + +// an uncaught exception or abort on the Metal build prints where it came from (macOS gives no core dump by default and +// lldb needs a debugging permission a user's session may not have) +#include +#include +#include +#include +#include +namespace { +[[noreturn]] void metal_terminate() { + void* fr[64]; + const int n = backtrace(fr, 64); + const char msg[] = "strata metal: terminate - the call stack:\n"; + (void) !write(2, msg, sizeof msg - 1); + backtrace_symbols_fd(fr, n, 2); + std::abort(); +} +const bool g_terminate_set = (std::set_terminate(metal_terminate), true); +// a crash (SIGSEGV / SIGBUS) prints its call stack too: macOS keeps no report for a command-line process by default +void metal_crash(int sig, siginfo_t* si, void*) { + void* fr[64]; + const int n = backtrace(fr, 64); + char msg[160]; + const int m = std::snprintf(msg, sizeof msg, "strata metal: crashed (signal %d at address %p) - the call stack:\n", sig, + si ? si->si_addr : nullptr); + (void) !write(2, msg, (size_t) m); + backtrace_symbols_fd(fr, n, 2); + signal(sig, SIG_DFL); + raise(sig); +} +bool set_crash() { + struct sigaction sa {}; + sa.sa_sigaction = metal_crash; + sa.sa_flags = SA_SIGINFO; + sigaction(SIGSEGV, &sa, nullptr); + sigaction(SIGBUS, &sa, nullptr); + return true; +} +const bool g_crash_set = set_crash(); +} // namespace diff --git a/metal/src/engine/mmvq_host.cpp b/metal/src/engine/mmvq_host.cpp new file mode 100644 index 00000000..af39859b --- /dev/null +++ b/metal/src/engine/mmvq_host.cpp @@ -0,0 +1,66 @@ +// metal/src/engine/mmvq_host.cpp - the host-side helpers of src/kernels/cuda/native_mmvq.cu the shared host code reads +// (which GGUF types the dense projections take, their byte sizes). Copied from native_mmvq.cu; keep in step. The +// kernels are not ported: on Metal the decode window runs mac-kern's GEMVs (metal/src/engine/window.cpp). +#include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/native_mmvq.hpp" + +#include +#include +#include +#include + +namespace strata::kernels { +namespace { +constexpr int Q8K = 32; +constexpr std::size_t kQ81Block = 4 + 32; // half2 ds + int8 qs[32] +void validate_shape(int n_in, int ncols, int block_elems = Q8K) { + if (n_in <= 0 || n_in % block_elems != 0) + throw std::invalid_argument("native MMVQ requires n_in > 0 and divisible by its block element count"); + if (ncols < 1 || ncols > 8) throw std::invalid_argument("native MMVQ requires 1 <= ncols <= 8"); +} +} // namespace + +bool native_mmvq_supported(int ggml_type) noexcept { + return ggml_type == 2 || ggml_type == 6 || ggml_type == 7 || ggml_type == 8 || ggml_type == 11 || + ggml_type == 12 || ggml_type == 13 || ggml_type == 14 || ggml_type == 20 || + ggml_type == 23 || ggml_type == 42 || ggml_type == 16 || ggml_type == 17 || ggml_type == 18 || + ggml_type == 21 || ggml_type == 22 || ggml_type == 29; +} + +std::size_t native_mmvq_weight_bytes(int ggml_type, int n_in, int n_out) { + int block_elems, block_bytes; + switch (ggml_type) { + case 2: block_elems = 32; block_bytes = 18; break; + case 6: block_elems = 32; block_bytes = 22; break; + case 7: block_elems = 32; block_bytes = 24; break; + case 8: block_elems = 32; block_bytes = 34; break; + case 20: block_elems = 32; block_bytes = 18; break; + case 11: block_elems = 256; block_bytes = 110; break; + case 12: block_elems = 256; block_bytes = 144; break; + case 13: block_elems = 256; block_bytes = 176; break; + case 14: block_elems = 256; block_bytes = 210; break; + case 23: block_elems = 256; block_bytes = 136; break; + case 42: block_elems = 64; block_bytes = 18; break; + case 16: case 17: case 18: case 21: case 22: case 29: + block_elems = 256; block_bytes = (int) iq_row_bytes(ggml_type, 256); break; + default: throw std::invalid_argument("unsupported native MMVQ GGML type"); + } + validate_shape(n_in, 1, block_elems); + if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0"); + const std::size_t row_bytes = std::size_t(n_in / block_elems) * block_bytes; + if (row_bytes > std::numeric_limits::max() / std::size_t(n_out)) + throw std::length_error("native MMVQ weight byte count overflows size_t"); + return row_bytes * std::size_t(n_out); +} + +std::size_t native_q8_1_bytes(int n_in, int ncols) { + validate_shape(n_in, ncols); + return std::size_t(ncols) * std::size_t(n_in / Q8K) * kQ81Block; +} +std::size_t native_q8_1_il_bytes(int n_in, int ncols) { return native_q8_1_bytes(n_in, ncols) * 2; } +bool native_mmvq_il_supported(int, int, int) { return false; } +bool native_q8_0_packed_eligible(int, int) { return false; } +bool native_q8_0_packed_enabled() { return false; } +bool native_q6_k_packed_enabled() { return false; } + +} // namespace strata::kernels diff --git a/metal/src/engine/msl/mtp.metal b/metal/src/engine/msl/mtp.metal new file mode 100644 index 00000000..7159330f --- /dev/null +++ b/metal/src/engine/msl/mtp.metal @@ -0,0 +1,68 @@ +// metal/src/engine/msl/mtp.metal - the small steps of the MTP draft layer's input branches (include/strata/core/mtp.hpp) +// around mac-kern's kernels (GEMVs, the hyper-connection read, QSA, MoE, the head): +// +// mtp_rms y[r] = x[r] * rsqrt(mean(x[r]^2) + eps) * w rows of width n (w: (1 + w) folded by the host) +// mtp_xprep xprep (units.metal) of rows read with a stride: the prepared activation of one stream of rows +// mtp_combine R[t][c][d] = h[c][t][d] + e[t][d] the streams of fc_hidden plus fc_embedding +// +// Prepared activations: [4 kinds][n_tok][n] then S16 [n_tok][n / 16] (units.metal's xprep layout). + +#include +using namespace metal; + +struct RmsArgs { uint n; float eps; }; + +// grid (rows), 256 threads +kernel void mtp_rms(device const float* x [[buffer(0)]], device const float* w [[buffer(1)]], device float* y [[buffer(2)]], + constant RmsArgs& a [[buffer(3)]], uint3 tg [[threadgroup_position_in_grid]], + ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]]) { + threadgroup float part[8]; + device const float* xr = x + tg.x * a.n; + float ss = 0.0f; + for (uint d = tid; d < a.n; d += 256) ss = fma(xr[d], xr[d], ss); + ss = simd_sum(ss); + if (lane == 0) part[sg] = ss; + threadgroup_barrier(mem_flags::mem_threadgroup); + float tot = 0.0f; + for (int i = 0; i < 8; ++i) tot += part[i]; + const float rs = rsqrt(tot / float(a.n) + a.eps); + device float* yr = y + tg.x * a.n; + for (uint d = tid; d < a.n; d += 256) yr[d] = xr[d] * rs * w[d]; +} + +struct XpArgs { uint n; uint n_tok; uint plane_tok; uint stride; }; + +// one thread per 16 values of one row: row t at x + t * stride; out planes of plane_tok rows +kernel void mtp_xprep(device const float* x [[buffer(0)]], device float* xp [[buffer(1)]], constant XpArgs& a [[buffer(2)]], + uint gid [[thread_position_in_grid]]) { + const uint per = a.n / 16; + if (gid >= per * a.n_tok) return; + const uint t = gid / per, i = gid % per; + device const float* src = x + t * a.stride + 16 * i; + const uint plane = a.plane_tok * a.n; + device float* raw = xp + t * a.n + 16 * i; + float v[16]; + for (int j = 0; j < 16; ++j) v[j] = src[j]; + float s0 = 0, s1 = 0; + for (int j = 0; j < 16; j += 2) { s0 += v[j]; s1 += v[j + 1]; } + const float q2s[8] = {1.0f, 0.25f, 0.0625f, 0.015625f, 0.00390625f, 0.0009765625f, 0.000244140625f, 0.00006103515625f}; + const float p4s[4] = {1.0f, 0.00390625f, 1.52587890625e-05f, 5.9604644775390625e-08f}; + for (int j = 0; j < 16; ++j) { + raw[j] = v[j]; + raw[plane + j] = v[j] * q2s[j & 7]; + raw[2 * plane + j] = v[j] * p4s[j & 3]; + raw[3 * plane + j] = (j & 1) ? v[j] * 0.00390625f : v[j]; + } + xp[4 * plane + t * per + i] = s0 + s1; +} + +struct CombArgs { uint n; uint hc; uint n_tok; uint h_stride; }; // h: stream c's rows at h + c * h_stride + +kernel void mtp_combine(device const float* h [[buffer(0)]], device const float* e [[buffer(1)]], device float* R [[buffer(2)]], + constant CombArgs& a [[buffer(3)]], uint gid [[thread_position_in_grid]]) { + const uint per = a.hc * a.n; + if (gid >= a.n_tok * per) return; + const uint t = gid / per, c = (gid % per) / a.n, d = gid % a.n; + R[gid] = h[c * a.h_stride + t * a.n + d] + e[t * a.n + d]; +} diff --git a/metal/src/engine/msl/mtp_chain.metal b/metal/src/engine/msl/mtp_chain.metal new file mode 100644 index 00000000..62500df2 --- /dev/null +++ b/metal/src/engine/msl/mtp_chain.metal @@ -0,0 +1,92 @@ +// metal/src/engine/msl/mtp_chain.metal - the two steps that keep a whole MTP draft round on the GPU (one command +// buffer for every draft step; compiled after mac-kern's quant.metal and units.metal): +// +// mtp_pick draft j: the pick's token id (through the draft vocabulary) and its probability, the softmax of +// the draft head's logits at the pick (the host computed it after every step before) +// mtp_embed_F the next step's input: the picked token's embedding row dequantized from the model's token_embd +// (format F) - the host dequantized it before +// +// mtp_embed reads a row with mac-kern's unit decoders (units.metal Dec): a unit's dot with x is +// d1 * sum_{j < UNIT/2} q[j] xs[j] + d2 * sum_{j >= UNIT/2} q[j] xs[j] - (m1 xsum0 + m2 xsum1) +// with xs the prepared x (raw x times the kind's 2^-k) and xsum the raw sums of 16, so weight j of the unit is +// w = d * (q[j] * 2^-k) - m (d = d1 or d2 by half, m = m1 for the first 16 x values, m2 for the rest; +// a 16-wide unit has one sum: m1) +// and its position in the row is what X::load reads when x holds the positions 0 .. n-1. + +struct PickArgs { + uint nv; // the draft head's rows (the draft vocabulary, or the whole vocabulary) + uint j; // the draft step + uint use_map; // 1: map the head's row through the draft vocabulary +}; + +// one threadgroup of 1024 +kernel void mtp_pick(device const float* lg [[buffer(0)]], device const int* pick [[buffer(1)]], + device const int* vmap [[buffer(2)]], device int* dout [[buffer(3)]], device float* dprob [[buffer(4)]], + constant PickArgs& a [[buffer(5)]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + threadgroup float part[32]; + const int di = pick[0]; + const float mx = lg[di]; + float s = 0.0f; + for (uint i = tid; i < a.nv; i += 1024) s += exp(lg[i] - mx); + s = simd_sum(s); + if (lane == 0) part[sg] = s; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid == 0) { + float t = 0.0f; + for (int k = 0; k < 32; ++k) t += part[k]; + dout[a.j] = a.use_map ? vmap[di] : di; + dprob[a.j] = 1.0f / t; + } +} + +struct EmbArgs { + uint n; // the row's width + uint row_bytes; + uint j; // dout[j] is the token +}; + +template static inline float kind_scale(int pos) { + const int k = XKind::K; + if (k == XK_Q2) { + const float q2s[8] = {1.0f, 0.25f, 0.0625f, 0.015625f, 0.00390625f, 0.0009765625f, 0.000244140625f, 0.00006103515625f}; + return q2s[pos & 7]; + } + if (k == XK_P4) { + const float p4s[4] = {1.0f, 0.00390625f, 1.52587890625e-05f, 5.9604644775390625e-08f}; + return p4s[pos & 3]; + } + if (k == XK_P2) return (pos & 1) ? 0.00390625f : 1.0f; + return 1.0f; +} + +// one threadgroup of 256; posv = the floats 0 .. n-1 +template +kernel void mtp_embed(device const uchar* W [[buffer(0)]], device const int* dout [[buffer(1)]], + device const float* posv [[buffer(2)]], device float* y [[buffer(3)]], constant EmbArgs& a [[buffer(4)]], + ushort tid [[thread_index_in_threadgroup]]) { + constexpr int UNIT = fmt::UNIT, H = UNIT / 2; + threadgroup uint tab[fmt::TAB]; + load_tab(tab, tid, 256); + threadgroup_barrier(mem_flags::mem_threadgroup); + device const uchar* row = W + (ulong) dout[a.j] * a.row_bytes; + const int U = int(a.n) / UNIT; + for (int u = tid; u < U; u += 256) { + float q[UNIT], ps[UNIT], xsum[2]; + float4 sc; + Dec::run(row, u, q, sc, tab); + X::load(posv, posv, u, ps, xsum); + for (int j = 0; j < UNIT; ++j) { + const int pos = int(ps[j]); + const float d = j < H ? sc.x : sc.y; + const float m = (UNIT == 16 || j < 16) ? sc.z : sc.w; + y[pos] = d * (q[j] * kind_scale(pos)) - m; + } + } +} + +// host names by the format's GGUF type number (mtp_embed_11 = Q3_K): EMB expands F before EMB_ stringifies it +#define EMB_(F) template [[host_name("mtp_embed_" #F)]] kernel decltype(mtp_embed) mtp_embed; +#define EMB(F) EMB_(F) +EMB(T_BF16) EMB(T_Q8_0) EMB(T_Q4_0) EMB(T_Q5_0) EMB(T_IQ4_NL) EMB(T_IQ4_XS) EMB(T_Q2_0) EMB(T_IQ3_S) EMB(T_Q3_K) +EMB(T_Q4_K) EMB(T_Q5_K) EMB(T_Q6_K) EMB(T_IQ3_XXS) diff --git a/metal/src/engine/msl/ple.metal b/metal/src/engine/msl/ple.metal new file mode 100644 index 00000000..7036eaeb --- /dev/null +++ b/metal/src/engine/msl/ple.metal @@ -0,0 +1,91 @@ +// metal/src/engine/msl/ple.metal - the PLE block (include/strata/kernels/ple.hpp) after its two projections, for a +// window of T rows, on the GPU (the CUDA engine's ple.cu math; its block sums are double there, float here): +// +// key = grouped_norm(pkey, norm_key) per stream c of 4: x * rsqrt(mean(x^2) + eps) * w +// query = grouped_norm(R, norm_query) +// gate[c] = sigmoid(sign(s) sqrt(max(|s|, 1e-6))), s = key[c] . query[c] / sqrt(n_embd) +// gated = value[d] * gate[c]; normalized = grouped_norm(gated, norm_conv) +// conv[c] = silu(sum_k kW[k + 4c] * row(t - (3 - k) * 3)[c]) rows: the history, then the window's own +// R += gated + conv +// +// History: hist[row + 9 * channel] (row-fastest, oldest first, the committed rows); the window's normalized rows +// are written to norm_w[t][channel] (the host appends the kept ones at commit). + +#include +using namespace metal; + +struct PleArgs { + uint n_embd; // 2560 + uint hc; // 4 + float eps; +}; + +static inline float tg_sum(float v, threadgroup float* part, ushort sg, ushort lane) { + v = simd_sum(v); + if (lane == 0) part[sg] = v; + threadgroup_barrier(mem_flags::mem_threadgroup); + float t = 0.0f; + for (int i = 0; i < 8; ++i) t += part[i]; + threadgroup_barrier(mem_flags::mem_threadgroup); + return t; +} + +// grid (hc, T), 256 threads: y[t][c] = grouped_norm(x[t][c]) with w[c] +kernel void ple_gnorm(device const float* x [[buffer(0)]], device const float* w [[buffer(1)]], device float* y [[buffer(2)]], + constant PleArgs& a [[buffer(3)]], uint3 tg [[threadgroup_position_in_grid]], + ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]]) { + threadgroup float part[8]; + const uint c = tg.x, t = tg.y, n = a.n_embd; + device const float* xc = x + (t * a.hc + c) * n; + float ss = 0.0f; + for (uint d = tid; d < n; d += 256) ss += xc[d] * xc[d]; + const float mean = tg_sum(ss, part, sg, lane) / float(n); + const float scale = 1.0f / sqrt(mean + a.eps); + device float* yc = y + (t * a.hc + c) * n; + for (uint d = tid; d < n; d += 256) yc[d] = xc[d] * scale * w[c * n + d]; +} + +// grid (hc, T), 256 threads: the gate, then gated = value * gate and normalized = grouped_norm(gated, norm_conv) +kernel void ple_gate_norm(device const float* key [[buffer(0)]], device const float* query [[buffer(1)]], + device const float* value [[buffer(2)]], device const float* w_conv [[buffer(3)]], + device float* gated [[buffer(4)]], device float* norm_w [[buffer(5)]], + constant PleArgs& a [[buffer(6)]], uint3 tg [[threadgroup_position_in_grid]], + ushort tid [[thread_index_in_threadgroup]], ushort sg [[simdgroup_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]]) { + threadgroup float part[8]; + const uint c = tg.x, t = tg.y, n = a.n_embd, row = (t * a.hc + c) * n; + float acc = 0.0f; + for (uint d = tid; d < n; d += 256) acc += key[row + d] * query[row + d]; + const float s = tg_sum(acc, part, sg, lane) * (1.0f / sqrt(float(n))); + const float mag = sqrt(max(fabs(s), 1e-6f)); + const float sgn = s > 0.0f ? 1.0f : (s < 0.0f ? -1.0f : 0.0f); + const float gate = 1.0f / (1.0f + exp(-(sgn * mag))); + float ss = 0.0f; + for (uint d = tid; d < n; d += 256) { + const float g = value[t * n + d] * gate; + gated[row + d] = g; + ss += g * g; + } + const float mean = tg_sum(ss, part, sg, lane) / float(n); + const float scale = 1.0f / sqrt(mean + a.eps); + for (uint d = tid; d < n; d += 256) norm_w[row + d] = gated[row + d] * scale * w_conv[c * n + d]; +} + +// grid (hc * n_embd / 256, T), 256 threads: the conv over [history | the window's rows], SiLU, and the residual +kernel void ple_conv_add(device const float* hist [[buffer(0)]], device const float* norm_w [[buffer(1)]], + device const half* kw [[buffer(2)]], device const float* gated [[buffer(3)]], + device float* R [[buffer(4)]], constant PleArgs& a [[buffer(5)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + const uint ch = tg.x * 256 + tid, t = tg.y, hcd = a.hc * a.n_embd; + if (ch >= hcd) return; + float acc = 0.0f; + for (int k = 0; k < 4; ++k) { + const int p = int(t) - (3 - k) * 3; // the row this tap reads: < 0 = the committed history + const float v = p >= 0 ? norm_w[uint(p) * hcd + ch] : hist[uint(9 + p) + 9 * ch]; + acc += float(kw[k + 4 * ch]) * v; + } + const float conv = acc / (1.0f + exp(-acc)); + device float* r = R + t * hcd; + r[ch] = r[ch] + gated[t * hcd + ch] + conv; +} diff --git a/metal/src/engine/prompt_chain.inc b/metal/src/engine/prompt_chain.inc new file mode 100644 index 00000000..97648094 --- /dev/null +++ b/metal/src/engine/prompt_chain.inc @@ -0,0 +1,420 @@ +// metal/src/engine/prompt_chain.inc (included by window.cpp) - the prompt through mac-kern's prompt kernels +// (metal/tests/prompt_chain.cpp's chain, 6f6c555b), into the decode window's own state: chunks of C rows, every +// dense matrix dequantized to fp16 and multiplied on the matrix units, the routed experts as grouped GEMMs, the GDN +// state by the parallel prompt scan, QSA K/V and indexer keys into the window's caches. Added for the engine: +// the PLE block after layer 0 (GEMMs + msl/ple.metal), every row's final residual (the drafter's prompt rows), the +// window's history parity, RoPE table and pending fold. No head: the last prompt token runs as a decode window. +// +// The 8-row-window prompt path stays as the fallback: STRATA_METAL_PROMPT=window, and prompts shorter than +// STRATA_METAL_PROMPT_MIN rows (default 32). STRATA_METAL_PROMPT_CHUNK = C (default 2048). The kernel variants +// follow prompt_chain's defaults: matrix-unit register operands where the GPU has the M5's right-input layout +// (COOP_K4, function constant 7), else the older expert and attention kernels (the M4). + +namespace { +constexpr int PC_QB = 2051, PC_QCHUNKS = 33, PC_TM = 16; +struct PcDqArgs { uint32_t n_in, n_out, row_bytes, perm; }; +struct PcGemmArgs { int M, N, K, pad; }; +struct PcEpiArgs { uint32_t n_tok, n_embd, hc, hc_lr; }; +struct PcGdnPArgs { uint32_t n_tok, h_k, h_v, channels; float eps; uint32_t f32; }; +struct PcMmPlanArgs { uint32_t n_ent, topk, n_expert, tm, n_blocks; }; +struct PcMmArgs { uint64_t gate_off, up_off, down_off, gu_stride, d_stride; uint32_t gu_row, d_row, n_embd, n_ff; }; +int pc_unit_of(int t) { + return t == ref::Q2_0 || t == ref::IQ3_S || t == ref::BF16 || t == ref::F32 || t == 18 || t == 16 || t == 17 || t == 22 ? 16 : 32; +} +} // namespace + +bool Window::coop_k4() { + if (const char* e = std::getenv("COOP_K4")) return std::atoi(e) != 0; + const int lib = cx_->compile({"mm_bench.metal"}, "#define NO_GGML_COMMON 1\n"); + mtl::Pipeline p = cx_->pipeline(lib, "coop_layout_16_64_32"); + mtl::Buffer out = cx_->alloc(4 * 3 * 32 * 128 * 4); + mtl::Dispatch d; + d.p = &p; + d.args = {mtl::Arg::B(out)}; + d.tg[0] = 32; + cx_->run({d}); + const int* o = out.as(); + bool k4 = true; + for (int l = 0; l < 32 && k4; ++l) { + const int* q = o + l * 128 * 4; + const int cap = q[2]; + for (int i = 0; i + 3 < cap && k4; i += 4) + for (int j = 1; j < 4; ++j) + if (q[(i + j) * 4] != q[i * 4] + j || q[(i + j) * 4 + 1] != q[i * 4 + 1]) { k4 = false; break; } + } + cx_->free(out); + return k4; +} + +bool Window::pc_setup(int C) { + PromptBufs& b = pb_; + if (b.C >= C) return true; + const double t0 = now_ms(); + if (b.C == 0) { + b.lib = cx_->compile({"quant.metal", "units.metal", "mma.metal", "dense_mm.metal", "moe_mm.metal", "gr.metal", + "gemv.metal", "prompt.metal"}); + b.lgdn = cx_->compile({"gdn.metal", "gdn_prompt.metal"}, "#define NO_GGML_COMMON 1\n"); + b.lqsa = cx_->compile({"qsa.metal", "qsa_prompt.metal"}, "#define NO_GGML_COMMON 1\n"); + b.k4 = coop_k4(); + } + b = PromptBufs{b.lib, b.lgdn, b.lqsa, b.k4}; // (re)allocated below for the larger chunk + b.C = C; + const size_t MT = (size_t) C; + const int MB = (int) max_cells_ / 4 + 2; + b.maxrows = (int) MT * TOPK + NEXP * PC_TM; + const int nblk_max = ((int) MT * TOPK + 1023) / 1024; + auto F32 = [&](size_t n) { return cx_->alloc(4 * n); }; + auto F16 = [&](size_t n) { return cx_->alloc(2 * n); }; + b.R = F32(MT * HC * N); b.bo = F32(MT * N); b.inj[0] = F32(MT * HC); b.inj[1] = F32(MT * HC); b.xn = F32(MT * HC * N); + b.xnh = F16(MT * HC * N); b.V = F32(MT * (LR + HC)); b.loh = F16(MT * LR); b.mixed = F32(MT * N); b.mixh = F16(MT * N); + b.qkv = F32(MT * 10240); b.z = F32(MT * 6144); b.al = F32(MT * 48); b.be = F32(MT * 48); b.yg = F32(MT * 6144); + b.ygh = F16(MT * 6144); b.gqn = F32(MT * 16 * 128); b.gkn = F32(MT * 16 * 128); b.gvc = F32(MT * 6144); + b.ggb = F32(MT * 48 * 2); b.gkq = F32(MT * 16); b.go = F32(MT * 6144); + b.qfull = F32(MT * 12288); b.kcur = F32(MT * 512); b.vcur = F32(MT * 512); b.iqr = F32(MT * 512); b.ikr = F32(MT * 128); + b.qcur = F32(MT * 24 * 256); b.qcurh = F16(MT * 24 * 256); b.qidx = F32(MT * 4 * 128); b.scores = F32(MT * MB); + b.qids = cx_->alloc(4 * MT * PC_QB); b.part = F32(MT * PC_QCHUNKS * 24 * 258); b.XQ = F32(4 * MT * 6144 + MT * 384); + b.xqh = F16(MT * 6144); + b.logits = F32(MT * NEXP); b.ids = cx_->alloc(4 * MT * TOPK); b.wts = F32(MT * TOPK); + b.bcnt = cx_->alloc(4 * (size_t) nblk_max * NEXP); b.boff = cx_->alloc(4 * (size_t) nblk_max * NEXP); + b.eoff = cx_->alloc(4 * NEXP); b.tiles = cx_->alloc(8 * (size_t) (b.maxrows / PC_TM + 1)); b.meta = cx_->alloc(64); + b.stok = cx_->alloc(4 * (size_t) b.maxrows); b.sw = F32(b.maxrows); b.pos = cx_->alloc(4 * MT * TOPK); + b.XS = F16((size_t) b.maxrows * N); b.HS = F16((size_t) b.maxrows * NFF); b.YE = F32((size_t) b.maxrows * N); + b.yr = F32(MT * N); b.gsh = F32(MT * NFF); b.ush = F32(MT * NFF); b.hh = F16(MT * NFF); b.ys = F32(MT * N); b.sgv = F32(MT); + b.WD = F16((size_t) (LR + HC) * HC * N); b.WU = F16((size_t) HC * N * LR); b.Wqkv = F16((size_t) 10240 * N); + b.Wz = F16((size_t) 6144 * N); b.Wal = F16((size_t) 48 * N); b.Wbe = F16((size_t) 48 * N); b.Wout = F16((size_t) N * 6144); + b.Wq = F16((size_t) 12288 * N); b.Wk = F16((size_t) 512 * N); b.Wv = F16((size_t) 512 * N); b.Wiq = F16((size_t) 512 * N); + b.Wik = F16((size_t) 128 * N); b.Wr = F16((size_t) NEXP * N); b.Wsg = F16((size_t) N); b.Wshg = F16((size_t) NFF * N); + b.Wshu = F16((size_t) NFF * N); b.Wshd = F16((size_t) N * NFF); + // the PLE block's rows and projections + b.pemb = F32(MT * N); b.pembh = F16(MT * N); b.pkey = F32(MT * 10240); b.pval = F32(MT * N); b.keyn = F32(MT * 10240); + b.qn = F32(MT * 10240); b.gated = F32(MT * 10240); b.normW = F32(MT * 10240); + b.Wpk = F16((size_t) 10240 * N); b.Wpv = F16((size_t) N * N); + // the expert GEMM tiles (prompt_chain's defaults): v3 gate/up 16,32,32,4 and down 16,64,32,2 with the M5 layout, + // else v2 + b.gu3[0] = 16; b.gu3[1] = 32; b.gu3[2] = 32; b.gu3[3] = 4; + b.dn3[0] = 16; b.dn3[1] = 64; b.dn3[2] = 32; b.dn3[3] = 2; + b.meta.as()[2] = b.k4 ? NFF / (b.gu3[1] * b.gu3[3]) : NFF / 64; + b.meta.as()[5] = b.k4 ? N / (b.dn3[1] * b.dn3[3]) : N / 64; + std::fprintf(stderr, "strata metal: prompt kernels (mac-kern's prompt chain) for chunks of %d rows, %s, ready in %.0f ms\n", + C, b.k4 ? "matrix-unit register operands (COOP_K4)" : "the older expert / attention kernels (no M5 layout)", + now_ms() - t0); + return true; +} + +// one chunk of nT rows at cells pos0.. (the window state is exactly at pos0 before, at pos0 + nT after) +bool Window::pc_chunk(const int64_t* tokens, int nT, int64_t pos0, std::string& err) { + PromptBufs& b = pb_; + strata::core::SessionState& ss = *ss_; + const double th0 = now_ms(); + // ---- the rows: the embedding into every stream; the PLE table rows + const gguf::Tensor& te = T("token_embd.weight"); + const size_t rb = ref::row_bytes(te.type, N); + mrope_sync(pos0, nT); + for (int t = 0; t < nT; ++t) { + float* r = b.R.as() + (size_t) t * HC * N; + if (const float* img = img_row(pos0 + t)) std::memcpy(r, img, (size_t) N * 4); + else ref::dequant(te.type, (const uint8_t*) W_.ptr + te.offset + (size_t) tokens[t] * rb, r, N); + for (int c = 1; c < HC; ++c) std::memcpy(r + (size_t) c * N, r, (size_t) N * 4); + } + if (ple_on_) { + std::vector rows((size_t) nT * strata::kernels::PLE_N_HEADS); + int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]}; + for (int t = 0; t < nT; ++t) { + const int32_t tk = (int32_t) tokens[t]; + strata::kernels::ngram_rows(&tk, prev, 1, ss.ple.consts, rows.data() + (size_t) t * strata::kernels::PLE_N_HEADS); + prev[0] = prev[1]; + prev[1] = tk; + } + if (!ss.ple.table->gather_batch(rows.data(), (size_t) nT, b.pemb.as(), err)) return false; + } + b.host_ms += now_ms() - th0; + std::vector ds; + ds.reserve(2400); + nb_ = false; + if (pend_fold_ > 0) { // the last window's commit, first + fold(ds, pend_fold_, 1 - hp_); + pend_fold_ = 0; + } + auto P_ = [&](int l, const std::string& fn, const mtl::Constants& c = {}, const std::string& key = "") { + return P(l, fn, c, "pc:" + (key.empty() ? fn : key)); + }; + auto D = [&](const mtl::Pipeline* p, std::vector a, uint32_t gx, uint32_t gy, uint32_t tg, uint32_t gz = 1) { + mtl::Dispatch d; + d.p = p; + d.args = std::move(a); + d.grid[0] = gx; d.grid[1] = gy; d.grid[2] = gz; + d.tg[0] = tg; + ds.push_back(std::move(d)); + }; + auto gemm = [&](const mtl::Buffer& A, const mtl::Buffer& B, const mtl::Buffer& Y, int M, int Nn, int K) { + const int tm = 64, tn = Nn <= 64 ? 32 : 64; + const std::string fn = "gemm_f16_" + std::to_string(tm) + "_" + std::to_string(tn) + "_4"; + PcGemmArgs g{M, Nn, K, 0}; + D(P_(b.lib, fn), {mtl::Arg::B(A), mtl::Arg::B(B), mtl::Arg::B(Y), mtl::Arg::V(g)}, (Nn + tn - 1) / tn, (M + tm - 1) / tm, 128); + }; + auto dq = [&](const gguf::Tensor& t, const mtl::Buffer& out, size_t out_off = 0, uint32_t perm = 0) { + const int n_in = (int) t.shape[0], n_out = t.shape.size() > 1 ? (int) t.shape[1] : 1; + PcDqArgs a{(uint32_t) n_in, (uint32_t) n_out, (uint32_t) ref::row_bytes(t.type, n_in), perm}; + D(P_(b.lib, "dq_f16_" + std::to_string(t.type)), {mtl::Arg::B(W_, t.offset), mtl::Arg::B(out, out_off), mtl::Arg::V(a)}, + (n_in / pc_unit_of(t.type) + 63) / 64, n_out, 64); + }; + auto act16 = [&](const mtl::Buffer& x, const mtl::Buffer& xh, size_t n) { + const uint32_t nn = (uint32_t) n; + D(P_(b.lib, "act_f16"), {mtl::Arg::B(x), mtl::Arg::B(xh), mtl::Arg::V(nn)}, (nn + 255) / 256, 1, 256); + }; + int cur_inj = 0; + auto hc_read = [&](const std::string& pre, bool apply) { + const gguf::Tensor &tn = T(pre + "_norm.weight"), &tdn = T(pre + "_down.weight"), &tin = T(pre + "_inject.weight"), + &tup = T(pre + "_up.weight"); + dq(tdn, b.WD); + dq(tin, b.WD, (size_t) 2 * LR * HC * N); + GrArgs a{N, HC, LR, (uint32_t) nT, apply ? 1u : 0u, eps_}; + PcEpiArgs ea{(uint32_t) nT, N, HC, LR}; + dq(tup, b.WU, 0, HC); + D(P_(b.lib, "gr_norm_h"), {mtl::Arg::B(b.R), mtl::Arg::B(b.bo), mtl::Arg::B(b.inj[cur_inj]), mtl::Arg::B(W_, tn.offset), + mtl::Arg::B(b.xnh), mtl::Arg::V(a)}, HC, nT, 256); + gemm(b.xnh, b.WD, b.V, nT, LR + HC, HC * N); + D(P_(b.lib, "gr_epi_down"), {mtl::Arg::B(b.V), mtl::Arg::B(b.loh), mtl::Arg::B(b.inj[1 - cur_inj]), mtl::Arg::V(ea)}, + (nT * (LR + HC) + 255) / 256, 1, 256); + PcGemmArgs g{nT, HC * N, LR, 0}; + D(P_(b.lib, "gemm_hc_up_64_64_4"), {mtl::Arg::B(b.loh), mtl::Arg::B(b.WU), mtl::Arg::B(b.xnh), mtl::Arg::B(b.mixed), + mtl::Arg::B(b.mixh), mtl::Arg::V(g), mtl::Arg::V(ea)}, + HC * N / 64, (nT + 63) / 64, 128); + cur_inj = 1 - cur_inj; + }; + const int hp = hp_; + int gi = 0, qi = 0; + for (int l = 0; l < 48; ++l) { + const std::string bl = "blk." + std::to_string(l) + "."; + hc_read(bl + "hc_attn", l > 0 && !(l == 1 && ple_on_)); + if (l % 4 != 3) { + dq(T(bl + "attn_qkv.weight"), b.Wqkv); + dq(T(bl + "attn_gate.weight"), b.Wz); + dq(T(bl + "ssm_alpha.weight"), b.Wal); + dq(T(bl + "ssm_beta.weight"), b.Wbe); + dq(T(bl + "ssm_out.weight"), b.Wout); + gemm(b.mixh, b.Wqkv, b.qkv, nT, 10240, N); + gemm(b.mixh, b.Wz, b.z, nT, 6144, N); + gemm(b.mixh, b.Wal, b.al, nT, 48, N); + gemm(b.mixh, b.Wbe, b.be, nT, 48, N); + PcGdnPArgs ga{(uint32_t) nT, 16, 48, 10240, eps_, 0}; + D(P_(b.lgdn, "gdn_pre"), + {mtl::Arg::B(b.qkv), mtl::Arg::B(ghist_[hp][(size_t) gi]), mtl::Arg::B(W_, T(bl + "ssm_conv1d.weight").offset), + mtl::Arg::B(b.al), mtl::Arg::B(b.be), mtl::Arg::B(W_, T(bl + "ssm_dt.bias").offset), + mtl::Arg::B(W_, T(bl + "ssm_a").offset), mtl::Arg::B(b.gqn), mtl::Arg::B(b.gkn), mtl::Arg::B(b.gvc), + mtl::Arg::B(b.ggb), mtl::Arg::B(b.gkq), mtl::Arg::B(ghist_[1 - hp][(size_t) gi]), mtl::Arg::V(ga)}, + 16 + 24, nT, 256); + D(P_(b.lgdn, "gdn_scanr_4", mtl::Constants().i(6, 0)), + {mtl::Arg::B(gst_[(size_t) gi]), mtl::Arg::B(b.gqn), mtl::Arg::B(b.gkn), mtl::Arg::B(b.gvc), mtl::Arg::B(b.ggb), + mtl::Arg::B(b.gkq), mtl::Arg::B(b.go), mtl::Arg::V(ga)}, + 48 * 4, 1, 32 * 4); + D(P_(b.lgdn, "gdn_post"), {mtl::Arg::B(b.go), mtl::Arg::B(b.z), mtl::Arg::B(W_, T(bl + "ssm_norm.weight").offset), + mtl::Arg::B(b.ygh), mtl::Arg::B(b.yg), mtl::Arg::V(ga)}, + 48, nT, 128); + gemm(b.ygh, b.Wout, b.bo, nT, N, 6144); + ++gi; + } else { + dq(T(bl + "attn_q.weight"), b.Wq); + dq(T(bl + "attn_k.weight"), b.Wk); + dq(T(bl + "attn_v.weight"), b.Wv); + dq(T(bl + "indexer.q_proj.weight"), b.Wiq); + dq(T(bl + "indexer.k_proj.weight"), b.Wik); + dq(T(bl + "attn_output.weight"), b.Wout); + gemm(b.mixh, b.Wq, b.qfull, nT, 12288, N); + gemm(b.mixh, b.Wk, b.kcur, nT, 512, N); + gemm(b.mixh, b.Wv, b.vcur, nT, 512, N); + gemm(b.mixh, b.Wiq, b.iqr, nT, 512, N); + gemm(b.mixh, b.Wik, b.ikr, nT, 128, N); + QsaArgs a{(uint32_t) pos0, 0, (uint32_t) max_cells_, (uint32_t) nT, eps_}; + D(P_(b.lqsa, "qsa_prep", qsa_c(), qsa_k()), + {mtl::Arg::B(b.qfull), mtl::Arg::B(b.kcur), mtl::Arg::B(b.vcur), mtl::Arg::B(b.iqr), mtl::Arg::B(b.ikr), + mtl::Arg::B(W_, T(bl + "attn_q_norm.weight").offset), mtl::Arg::B(W_, T(bl + "attn_k_norm.weight").offset), + mtl::Arg::B(W_, T(bl + "indexer.q_norm.weight").offset), mtl::Arg::B(W_, T(bl + "indexer.k_norm.weight").offset), + mtl::Arg::B(cs_), mtl::Arg::B(b.qcur), mtl::Arg::B(b.qidx), mtl::Arg::B(kq_[(size_t) qi]), mtl::Arg::B(vq_[(size_t) qi]), + mtl::Arg::B(ksc_[(size_t) qi]), mtl::Arg::B(vsc_[(size_t) qi]), mtl::Arg::B(tail_[(size_t) qi]), + mtl::Arg::B(dead_[(size_t) qi]), mtl::Arg::B(pooled_[(size_t) qi]), mtl::Arg::V(a), mtl::Arg::B(mrope_)}, + 33, nT, 256); + if (pos0 + nT > PC_QB) { // some row's context is past the budget: the indexer selects + if (b.k4) + D(P_(b.lqsa, "qsa_score_mm"), {mtl::Arg::B(b.qidx), mtl::Arg::B(pooled_[(size_t) qi]), mtl::Arg::B(dead_[(size_t) qi]), + mtl::Arg::B(b.scores), mtl::Arg::V(a)}, + (uint32_t) (((pos0 + nT) / 4 + 1 + 63) / 64), (nT + 15) / 16, 128); + else + D(P_(b.lqsa, "qsa_score"), {mtl::Arg::B(b.qidx), mtl::Arg::B(pooled_[(size_t) qi]), mtl::Arg::B(dead_[(size_t) qi]), + mtl::Arg::B(b.scores), mtl::Arg::V(a)}, + (uint32_t) (((pos0 + nT) / 4 + 1 + 7) / 8), nT, 256); + } + D(P_(b.lqsa, "qsa_topk"), {mtl::Arg::B(b.scores), mtl::Arg::B(b.qids), mtl::Arg::V(a)}, nT, 1, 1024); + if (b.k4) { + const uint32_t nq = (uint32_t) nT * 24 * 256; + D(P_(b.lqsa, "qsa_q_f16"), {mtl::Arg::B(b.qcur), mtl::Arg::B(b.qcurh), mtl::Arg::V(nq)}, (nq + 255) / 256, 1, 256); + D(P_(b.lqsa, "qsa_attn_mm", mtl::Constants().b(7, true), "qsa_attn_mm#k4"), + {mtl::Arg::B(b.qcurh), mtl::Arg::B(kq_[(size_t) qi]), mtl::Arg::B(vq_[(size_t) qi]), mtl::Arg::B(ksc_[(size_t) qi]), + mtl::Arg::B(vsc_[(size_t) qi]), mtl::Arg::B(b.qids), mtl::Arg::B(b.part), mtl::Arg::V(a)}, + PC_QCHUNKS, 2, 32, nT); + } else { + D(P_(b.lqsa, "qsa_attn"), {mtl::Arg::B(b.qcur), mtl::Arg::B(kq_[(size_t) qi]), mtl::Arg::B(vq_[(size_t) qi]), + mtl::Arg::B(ksc_[(size_t) qi]), mtl::Arg::B(vsc_[(size_t) qi]), mtl::Arg::B(b.qids), + mtl::Arg::B(b.part), mtl::Arg::V(a)}, + PC_QCHUNKS, 2, 256, nT); + } + D(P_(b.lqsa, "qsa_merge"), {mtl::Arg::B(b.part), mtl::Arg::B(b.qfull), mtl::Arg::B(b.XQ), mtl::Arg::V(a)}, 24, nT, 256); + act16(b.XQ, b.xqh, (size_t) nT * 6144); + gemm(b.xqh, b.Wout, b.bo, nT, N, 6144); + ++qi; + } + // ---- MoE + hc_read(bl + "hc_ffn", true); + const gguf::Tensor &eg = T(bl + "ffn_gate_exps.weight"), &eu = T(bl + "ffn_up_exps.weight"), &ed = T(bl + "ffn_down_exps.weight"); + dq(T(bl + "ffn_gate_inp.weight"), b.Wr); + dq(T(bl + "ffn_gate_inp_shexp.weight"), b.Wsg); + dq(T(bl + "ffn_gate_shexp.weight"), b.Wshg); + dq(T(bl + "ffn_up_shexp.weight"), b.Wshu); + dq(T(bl + "ffn_down_shexp.weight"), b.Wshd); + gemm(b.mixh, b.Wr, b.logits, nT, NEXP, N); + const uint32_t nt = (uint32_t) nT; + D(P_(b.lib, "route_topk"), {mtl::Arg::B(b.logits), mtl::Arg::B(b.ids), mtl::Arg::B(b.wts), mtl::Arg::V(nt)}, (nT + 7) / 8, 1, 256); + const int nent = nT * TOPK, nblk = (nent + 1023) / 1024; + PcMmPlanArgs pa{(uint32_t) nent, TOPK, NEXP, (uint32_t) PC_TM, (uint32_t) nblk}; + const uint32_t nclr = (uint32_t) b.maxrows; + D(P_(b.lib, "mm_clear"), {mtl::Arg::B(b.stok), mtl::Arg::V(nclr)}, (b.maxrows + 255) / 256, 1, 256); + D(P_(b.lib, "mm_hist"), {mtl::Arg::B(b.ids), mtl::Arg::B(b.bcnt), mtl::Arg::V(pa)}, nblk, 1, 1024); + D(P_(b.lib, "mm_scan"), {mtl::Arg::B(b.bcnt), mtl::Arg::B(b.boff), mtl::Arg::B(b.eoff), mtl::Arg::B(b.tiles), mtl::Arg::B(b.meta), + mtl::Arg::V(pa)}, 1, 1, NEXP); + D(P_(b.lib, "mm_place"), {mtl::Arg::B(b.ids), mtl::Arg::B(b.wts), mtl::Arg::B(b.boff), mtl::Arg::B(b.eoff), mtl::Arg::B(b.stok), + mtl::Arg::B(b.sw), mtl::Arg::B(b.pos), mtl::Arg::V(pa)}, nblk, 1, 1024); + PcMmArgs ma{eg.offset, eu.offset, ed.offset, 0, 0, (uint32_t) ref::row_bytes(eg.type, N), (uint32_t) ref::row_bytes(ed.type, NFF), + N, NFF}; + ma.gu_stride = (uint64_t) ma.gu_row * NFF; + ma.d_stride = (uint64_t) ma.d_row * N; + const uint32_t ne = N; + mtl::Dispatch g; + g.p = P_(b.lib, "mm_gather"); + g.args = {mtl::Arg::B(b.mixed), mtl::Arg::B(b.stok), mtl::Arg::B(b.XS), mtl::Arg::V(ne)}; + g.tg[0] = 256; + g.indirect = &b.meta; + g.ind_off = 8 * 4; + ds.push_back(g); + auto tl3 = [](const int* t) { return std::to_string(t[0]) + "_" + std::to_string(t[1]) + "_" + std::to_string(t[2]) + "_" + std::to_string(t[3]); }; + mtl::Dispatch gu; + if (b.k4) { + const std::string fn = "mm_gu3_" + std::to_string(eg.type) + "_" + tl3(b.gu3); + gu.p = P_(b.lib, fn, mtl::Constants().b(7, true), fn + "#k4"); + } else { + const std::string fn = "mm_gu2_" + std::to_string(eg.type) + gu2_tile(eg.type); + gu.p = P_(b.lib, fn, mtl::Constants().i(5, 0), fn + "#p0"); + } + gu.args = {mtl::Arg::B(W_), mtl::Arg::B(b.XS), mtl::Arg::B(b.HS), mtl::Arg::B(b.tiles), mtl::Arg::V(ma)}; + gu.tg[0] = b.k4 ? 32 * b.gu3[3] : 64; + gu.indirect = &b.meta; + gu.ind_off = 2 * 4; + ds.push_back(gu); + mtl::Dispatch dn; + if (b.k4) { + const std::string fn = "mm_down3_" + std::to_string(ed.type) + "_" + tl3(b.dn3); + dn.p = P_(b.lib, fn, mtl::Constants().b(7, true), fn + "#k4"); + } else { + dn.p = P_(b.lib, "mm_down2_" + std::to_string(ed.type) + dn2_tile(ed.type)); + } + dn.args = {mtl::Arg::B(W_), mtl::Arg::B(b.HS), mtl::Arg::B(b.YE), mtl::Arg::B(b.tiles), mtl::Arg::V(ma)}; + dn.tg[0] = b.k4 ? 32 * b.dn3[3] : 64; + dn.indirect = &b.meta; + dn.ind_off = 5 * 4; + ds.push_back(dn); + const uint32_t ca[4] = {(uint32_t) nT, N, TOPK, 0}; + D(P_(b.lib, "mm_combine"), {mtl::Arg::B(b.YE), mtl::Arg::B(b.pos), mtl::Arg::B(b.sw), mtl::Arg::B(b.yr), mtl::Arg::V(ca)}, + (nT * N + 255) / 256, 1, 256); + gemm(b.mixh, b.Wshg, b.gsh, nT, NFF, N); + gemm(b.mixh, b.Wshu, b.ush, nT, NFF, N); + const uint32_t nh = (uint32_t) nT * NFF; + D(P_(b.lib, "swiglu_h"), {mtl::Arg::B(b.gsh), mtl::Arg::B(b.ush), mtl::Arg::B(b.hh), mtl::Arg::V(nh)}, (nh + 255) / 256, 1, 256); + gemm(b.hh, b.Wshd, b.ys, nT, N, NFF); + gemm(b.mixh, b.Wsg, b.sgv, nT, 1, N); + const uint32_t oa[2] = {(uint32_t) nT, N}; + D(P_(b.lib, "moe_out"), {mtl::Arg::B(b.yr), mtl::Arg::B(b.ys), mtl::Arg::B(b.sgv), mtl::Arg::B(b.bo), mtl::Arg::V(oa)}, + (nT * N + 255) / 256, 1, 256); + if (l == 0 && ple_on_) { + // layer 0's FFN write applied to R, then the PLE block (as the window: msl/ple.metal over nT rows) + GrArgs a{N, HC, LR, (uint32_t) nT, 1u, eps_}; + D(P_(b.lib, "gr_norm"), {mtl::Arg::B(b.R), mtl::Arg::B(b.bo), mtl::Arg::B(b.inj[cur_inj]), + mtl::Arg::B(W_, T("blk.1.hc_attn_norm.weight").offset), mtl::Arg::B(b.xn), mtl::Arg::V(a)}, + HC, nT, 256); + act16(b.pemb, b.pembh, (size_t) nT * N); + dq(T("blk.1.ple_key.weight"), b.Wpk); + dq(T("blk.1.ple_value.weight"), b.Wpv); + gemm(b.pembh, b.Wpk, b.pkey, nT, 10240, N); + gemm(b.pembh, b.Wpv, b.pval, nT, N, N); + struct PleArgs { uint32_t n_embd, hc; float eps; } pa2{N, HC, strata::kernels::NG_RMS_EPS}; + auto off = [&](const char* n) { return T(n).offset; }; + D(P(lple_, "ple_gnorm", {}, "ple_gnorm"), {mtl::Arg::B(b.pkey), mtl::Arg::B(W_, off("blk.1.ple_norm_key.weight")), + mtl::Arg::B(b.keyn), mtl::Arg::V(pa2)}, HC, nT, 256); + D(P(lple_, "ple_gnorm", {}, "ple_gnorm"), {mtl::Arg::B(b.R), mtl::Arg::B(W_, off("blk.1.ple_norm_query.weight")), + mtl::Arg::B(b.qn), mtl::Arg::V(pa2)}, HC, nT, 256); + D(P(lple_, "ple_gate_norm", {}, "ple_gate_norm"), + {mtl::Arg::B(b.keyn), mtl::Arg::B(b.qn), mtl::Arg::B(b.pval), mtl::Arg::B(W_, off("blk.1.ple_norm_conv.weight")), + mtl::Arg::B(b.gated), mtl::Arg::B(b.normW), mtl::Arg::V(pa2)}, HC, nT, 256); + D(P(lple_, "ple_conv_add", {}, "ple_conv_add"), + {mtl::Arg::B(pleHist_), mtl::Arg::B(b.normW), kw_arg(), mtl::Arg::B(b.gated), + mtl::Arg::B(b.R), mtl::Arg::V(pa2)}, HC * N / 256, nT, 256); + } + } + // every row's final residual (the last write applied): the drafter's prompt rows + { + GrArgs a{N, HC, LR, (uint32_t) nT, 1u, eps_}; + D(P_(b.lib, "gr_norm"), {mtl::Arg::B(b.R), mtl::Arg::B(b.bo), mtl::Arg::B(b.inj[cur_inj]), + mtl::Arg::B(W_, T("output_hc_norm.weight").offset), mtl::Arg::B(b.xn), mtl::Arg::V(a)}, HC, nT, 256); + } + const double g = cx_->run(ds); + b.gpu_ms += 1000.0 * g; + hp_ = 1 - hp_; + // the host side of the commit: the PLE history (the last 9 normalized rows) and the n-gram context + if (ple_on_) { + using namespace strata::kernels; + const float* nw = b.normW.as(); + float* hist = pleHist_.as(); + for (int c = 0; c < NG_HC_DIM; ++c) { + float* col = hist + (size_t) c * NG_HIST; + float tmp[NG_HIST * 2]; + int k = 0; + const int keep_old = std::max(0, NG_HIST - nT); + for (int r = NG_HIST - keep_old; r < NG_HIST; ++r) tmp[k++] = col[r]; + for (int t = std::max(0, nT - NG_HIST); t < nT; ++t) tmp[k++] = nw[(size_t) t * NG_HC_DIM + c]; + for (int r = 0; r < NG_HIST; ++r) col[r] = tmp[r]; + } + } + for (int t = 0; t < nT; ++t) { + ss.ple_prev[0] = ss.ple_prev[1]; + ss.ple_prev[1] = (int32_t) tokens[t]; + } + last_T_ = 0; // nothing to commit + return true; +} + +bool Window::prompt(const int64_t* tokens, int64_t n, int64_t pos0, + const std::function& on_chunk, std::string& err) { + static const int C = [] { + const char* e = std::getenv("STRATA_METAL_PROMPT_CHUNK"); + return std::max(64, std::min(8192, e ? std::atoi(e) : 2048)); + }(); + if (!pc_setup((int) std::min(C, std::max(n, 64)))) { err = "metal prompt: setup failed"; return false; } + const double t0 = now_ms(); + pb_.gpu_ms = pb_.host_ms = pb_.mtp_ms = 0; + for (int64_t c = 0; c < n; c += C) { + const int nT = (int) std::min(C, n - c); + if (pos0 + c + nT + 1 >= max_cells_) { err = "metal prompt: the prompt runs past the context"; return false; } + if (!pc_chunk(tokens + c, nT, pos0 + c, err)) return false; + if (on_chunk) { + const double tm0 = now_ms(); + mpsrc_ = &pb_.R; // the drafter's prompt rows are this chunk's final residuals + const bool ok = on_chunk(nullptr, nT, pos0 + c, err); + mpsrc_ = nullptr; + pb_.mtp_ms += now_ms() - tm0; + if (!ok) return false; + } + } + if (std::getenv("STRATA_METAL_TRACE") || std::getenv("STRATA_METAL_PROFILE")) + std::fprintf(stderr, "strata metal: prompt %lld tokens in %.1f ms (GPU %.1f ms, host rows %.1f ms, drafter rows %.1f ms) " + "-> %.1f tok/s\n", (long long) n, now_ms() - t0, pb_.gpu_ms, pb_.host_ms, pb_.mtp_ms, + 1000.0 * (double) n / (now_ms() - t0)); + return true; +} diff --git a/metal/src/engine/setup_host.cpp b/metal/src/engine/setup_host.cpp new file mode 100644 index 00000000..e4599092 --- /dev/null +++ b/metal/src/engine/setup_host.cpp @@ -0,0 +1,160 @@ +// metal/src/engine/setup_host.cpp - the host-side state and sizes of the CUDA kernel files that the shared host code +// sets and reads while it starts the engine (path switches, scratch sizes, the RoPE table and its config). Copied +// from gr.cu, shared_expert.cu, native_*.cu, ple.cu, qsa_decode_attn.cu, rope.cu, native_rope.cu, +// s2_expert_grouped.cu; keep in step. On Metal none of these steers a kernel: the decode window runs mac-kern's +// chain (metal/src/engine/window.cpp); they keep the host side's allocations and checks as on the PC. +#include "strata/kernels/gr.hpp" +#include "strata/kernels/native_gdn.hpp" +#include "strata/kernels/native_moe.hpp" +#include "strata/kernels/native_qsa.hpp" +#include "strata/kernels/native_qsa_indexer.hpp" +#include "strata/kernels/native_rope.hpp" +#include "strata/kernels/native_router.hpp" +#include "strata/kernels/ngram.hpp" +#include "strata/kernels/ple.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/rope.hpp" +#include "strata/kernels/rope_scaling.hpp" +#include "strata/kernels/s2_expert_grouped.hpp" +#include "strata/kernels/shared_expert.hpp" +#include "strata/kernels/fused_gr.hpp" +#include "strata/prefill/gemm.hpp" + +#include +#include +#include +#include + +namespace strata::kernels { + +namespace { +bool g_fp32_activations = false, g_native_mmvf = false, g_sh_native_bf16 = false, g_ple_native_bf16 = false, + g_ple_native_postops = false; +std::atomic g_moe_combine{false}, g_gdn{false}, g_router{false}, g_qsa{false}, g_qsa_indexer{false}, g_rope{false}; +RopeScaling g_rope_scaling; +} // namespace + +// ---- path switches (each .cu file's own flag) +void gr_set_fp32_activations(bool enabled) { g_fp32_activations = enabled; } +void gr_set_native_mmvf(bool enabled) { g_native_mmvf = enabled; } +bool gr_native_mmvf_enabled() { return g_native_mmvf; } +void shared_expert_set_native_bf16(bool enabled) { g_sh_native_bf16 = enabled; } +bool shared_expert_native_bf16_enabled() { return g_sh_native_bf16; } +void ple_set_native_bf16(bool enabled) { g_ple_native_bf16 = enabled; } +bool ple_native_bf16_enabled() { return g_ple_native_bf16; } +void ple_set_native_postops(bool enabled) { g_ple_native_postops = enabled; } +bool ple_native_postops_enabled() { return g_ple_native_postops; } +void native_moe_combine_set_enabled(bool v) { g_moe_combine.store(v, std::memory_order_relaxed); } +bool native_moe_combine_enabled() { return g_moe_combine.load(std::memory_order_relaxed); } +void native_gdn_set_enabled(bool v) { g_gdn.store(v, std::memory_order_relaxed); } +bool native_gdn_enabled() { return g_gdn.load(std::memory_order_relaxed); } +void native_router_set_enabled(bool v) { g_router.store(v, std::memory_order_relaxed); } +bool native_router_enabled() { return g_router.load(std::memory_order_relaxed); } +void native_qsa_set_enabled(bool v) { g_qsa.store(v, std::memory_order_relaxed); } +bool native_qsa_enabled() { return g_qsa.load(std::memory_order_relaxed); } +void native_qsa_indexer_set_enabled(bool v) { g_qsa_indexer.store(v, std::memory_order_relaxed); } +bool native_qsa_indexer_enabled() { return g_qsa_indexer.load(std::memory_order_relaxed); } +void native_rope_set_enabled(bool v) { g_rope.store(v, std::memory_order_relaxed); } +bool native_rope_enabled() { return g_rope.load(std::memory_order_relaxed); } +void fused_gr_check() {} // the CUDA read variants' self-test: no variants on Metal + +// ---- scratch sizes +uint64_t ple_block_scratch_bytes() { + const size_t f = (size_t) (5 * NG_HC_DIM + NG_N_EMBD + NG_HC) * sizeof(float); + const size_t q = (size_t) (NG_N_EMBD / 32) * 34; + const size_t e = (size_t) NG_N_EMBD * sizeof(uint16_t); + return ((f + 15) & ~(size_t) 15) + ((q + 15) & ~(size_t) 15) + e + 256; +} +uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s) { + constexpr int HD = 256, CHUNK = 64; + const int64_t chunks = (cap + CHUNK - 1) / CHUNK; + return (uint64_t) chunks * (uint64_t) s.n_head * (HD + 2) + 64; +} +uint64_t shared_expert_scratch_bytes(int64_t n_ff) { + const uint64_t a = ((uint64_t) n_ff * 4 + 15) & ~15ull; + const uint64_t q0 = ((uint64_t) (n_ff / 32) * 34 + 15) & ~15ull; + const uint64_t qk = ((uint64_t) (n_ff / 256) * 292 + 15) & ~15ull; + return a * 2 + q0 + qk + 32; +} +uint64_t moe_hit_grouped_scratch_bytes(int64_t n_hits, int64_t n_embd, int64_t n_ff) { + if (n_hits <= 0) return 0; + const uint64_t gu = (uint64_t) n_hits * (uint64_t) (2 * n_ff) * 4; + const uint64_t q8 = (uint64_t) n_hits * (uint64_t) (n_ff / 32) * 34; + const uint64_t hs = (uint64_t) n_hits * (uint64_t) (n_ff / 32) * 4; + const uint64_t xh = (uint64_t) (n_embd / 32) * 4; + return ((gu + 15) & ~15ull) + ((q8 + 15) & ~15ull) + 2 * ((hs + 15) & ~15ull) + ((xh + 15) & ~15ull); +} +size_t gr_workspace_init(const GrShapes& s, void* base, GrWorkspace& out) { + const size_t hc_dim = (size_t) s.hc * (size_t) s.n_embd; + const size_t sz[5] = {hc_dim * sizeof(float), hc_dim * sizeof(uint16_t), (size_t) s.hc_lr * sizeof(uint16_t), + hc_dim * sizeof(float), (size_t) s.hc_lr * sizeof(float)}; + size_t al[5], bytes = 0; + for (int k = 0; k < 5; ++k) { + al[k] = (sz[k] + 15) & ~(size_t) 15; + bytes += al[k]; + } + out.bytes = bytes; + if (base != nullptr) { + unsigned char* p = (unsigned char*) base; + void* ptr[5]; + for (int k = 0; k < 5; ++k) { + ptr[k] = p; + p += al[k]; + } + out.xn = (float*) ptr[0]; + out.xq = (uint16_t*) ptr[1]; + out.lq = (uint16_t*) ptr[2]; + out.gated = (float*) ptr[3]; + out.lo = (float*) ptr[4]; + } + return bytes; +} + +// ---- RoPE (rope.cu, native_rope.cu): the config and the host-built angle table +void rope_scaling_set(const RopeScaling& scaling) { g_rope_scaling = scaling; } +const RopeScaling& rope_scaling() { return g_rope_scaling; } +void build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, float* sin_tab) { + const int half = n_rot / 2; + for (int p = 0; p < max_pos; ++p) + for (int i = 0; i < half; ++i) { + const double inv = std::pow(theta, -2.0 * (double) i / (double) n_rot); + const double ang = (double) p * inv; + cos_tab[(size_t) p * half + i] = (float) std::cos(ang); + sin_tab[(size_t) p * half + i] = (float) std::sin(ang); + } +} +void build_rope_table(int n_rot, const RopeScaling& sc, int max_pos, float* cos_tab, float* sin_tab) { + if (sc.type == RopeScalingType::None) { + build_rope_table(n_rot, sc.freq_base, max_pos, cos_tab, sin_tab); + return; + } + const int half = n_rot / 2; + const double fs = sc.freq_scale(); + const double ms = sc.mscale(); + double cd[2]; + sc.corr_dims(n_rot, cd); + const bool correct = sc.ext_factor != 0; + for (int p = 0; p < max_pos; ++p) + for (int i = 0; i < half; ++i) { + const double inv = std::pow(sc.freq_base, -2.0 * (double) i / (double) n_rot); + const double extrap = (double) p * inv; + const double interp = fs * extrap; + double ang = interp; + if (correct) { + const double ramp = (double) rope_yarn_ramp((float) cd[0], (float) cd[1], i) * sc.ext_factor; + ang = interp * (1.0 - ramp) + extrap * ramp; + } + cos_tab[(size_t) p * half + i] = (float) (std::cos(ang) * ms); + sin_tab[(size_t) p * half + i] = (float) (std::sin(ang) * ms); + } +} +void rope_table_set(const float*, const float*, int, const RopeScaling&) {} // the window keeps its own table +void rope_table_release(const float*) {} +void native_q6_k_unpack(const void*) {} // nothing packed on Metal + +} // namespace strata::kernels + +namespace strata::prefill { +Gemm::~Gemm() {} // nothing created on Metal (no prompt GEMMs yet) +bool prompt_f16() { return false; } // the CUDA/HIP prompt path's FP16 image mode: not used on Metal +} // namespace strata::prefill diff --git a/metal/src/engine/stream.cpp b/metal/src/engine/stream.cpp new file mode 100644 index 00000000..d5fa2003 --- /dev/null +++ b/metal/src/engine/stream.cpp @@ -0,0 +1,782 @@ +// metal/src/engine/stream.cpp - see stream.h. +#include "stream.h" + +#include "ref_quant.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace strata::metal_engine { + +namespace { +constexpr int NL = 48, NE = 512; +constexpr uint64_t PAGE = 16384; +double now_ms() { return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); } +int env_int(const char* n, int d) { + const char* e = std::getenv(n); + return e && *e ? std::atoi(e) : d; +} +} // namespace + +bool ExpertStream::wanted(const gguf::File& f, const mtl::Context& cx) { + const char* e = std::getenv("STRATA_METAL_STREAM"); + if (e && std::string(e) == "1") return true; + if (e && std::string(e) == "0") return false; + // auto: stream when the mapped weights (experts and dense) and ~12 GiB beside them (the prompt buffers, KV, the + // draft layer, macOS) do not fit the GPU working set. M5 Max (115.4 GB): GSQ packs, IQ3_S and UD-Q4_K_XL stay + // resident, UD-Q5/Q6_K_XL stream; M4 32 GB (26.8 GB): every pack streams. + uint64_t all = 0; + for (const auto& kv : f.tensors) + if (kv.first != "per_layer_token_embd.weight") all += kv.second.bytes; + return (double) all + 12.0 * (1ull << 30) > (double) cx.recommended_working_set(); +} + +ExpertStream::~ExpertStream() { + { + std::lock_guard g(mu_); + stop_ = true; + } + cv_.notify_all(); + for (auto& t : io_) t.join(); + if (fd_ >= 0) ::close(fd_); +} + +bool ExpertStream::open(const gguf::File& f, std::string& err) { + fd_ = ::open(f.path.c_str(), O_RDONLY); + if (fd_ < 0) { err = "metal stream: cannot open " + f.path; return false; } + fcntl(fd_, F_NOCACHE, 1); + fcntl(fd_, F_RDAHEAD, 0); + lay_.resize(NL); + for (int l = 0; l < NL; ++l) { + const std::string b = "blk." + std::to_string(l) + "."; + const gguf::Tensor* g = f.find(b + "ffn_gate_exps.weight"); + const gguf::Tensor* u = f.find(b + "ffn_up_exps.weight"); + const gguf::Tensor* d = f.find(b + "ffn_down_exps.weight"); + if (!g || !u || !d) { err = "metal stream: layer " + std::to_string(l) + " has no routed experts"; return false; } + lay_[(size_t) l] = {g->offset, g->bytes / NE, u->offset, u->bytes / NE, d->offset, d->bytes / NE, -1}; + } + // the expert-contiguous copy beside the GGUF, when it is this GGUF's (sizes in its header) and its first and + // last experts match the GGUF's bytes + if (env_int("STRATA_METAL_CONTIG", 1) != 0) { + const std::string cp = f.path + ".experts"; + const int cfd = ::open(cp.c_str(), O_RDONLY); + bool ok = cfd >= 0; + std::vector off(NL); + if (ok) { + uint8_t h[64]; + std::vector t((size_t) NL * 4); + struct stat st {}; + ::fstat(fd_, &st); + ok = ::pread(cfd, h, 64, 0) == 64 && std::memcmp(h, "STRX", 4) == 0 && + ::pread(cfd, t.data(), t.size() * 8, 64) == (ssize_t) (t.size() * 8); + uint32_t ver = 0, nl = 0, ne = 0; + uint64_t src = 0; + std::memcpy(&ver, h + 4, 4); std::memcpy(&nl, h + 8, 4); std::memcpy(&ne, h + 12, 4); std::memcpy(&src, h + 16, 8); + ok = ok && ver == 1 && nl == (uint32_t) NL && ne == (uint32_t) NE && src == (uint64_t) st.st_size; + for (int l = 0; ok && l < NL; ++l) { + const Lay& x = lay_[(size_t) l]; + ok = t[(size_t) l * 4 + 1] == x.gs && t[(size_t) l * 4 + 2] == x.us && t[(size_t) l * 4 + 3] == x.ds; + off[(size_t) l] = t[(size_t) l * 4]; + } + if (ok) { // spot check: layer 0's first and layer 47's last expert, every slice + for (const int l : {0, NL - 1}) { + const Lay& x = lay_[(size_t) l]; + const int e = l == 0 ? 0 : NE - 1; + std::vector a(x.gs + x.us + x.ds), b(a.size()); + ok = ok && ::pread(cfd, a.data(), a.size(), (off_t) (off[(size_t) l] + (uint64_t) e * a.size())) == (ssize_t) a.size() && + ::pread(fd_, b.data(), x.gs, (off_t) (x.g + (uint64_t) e * x.gs)) == (ssize_t) x.gs && + ::pread(fd_, b.data() + x.gs, x.us, (off_t) (x.u + (uint64_t) e * x.us)) == (ssize_t) x.us && + ::pread(fd_, b.data() + x.gs + x.us, x.ds, (off_t) (x.d + (uint64_t) e * x.ds)) == (ssize_t) x.ds && + a == b; + } + } + } + if (ok) { + fcntl(cfd, F_NOCACHE, 1); + fcntl(cfd, F_RDAHEAD, 0); + cfd_ = cfd; + coff_ = off; + std::fprintf(stderr, "strata metal stream: experts read from %s (one request per expert)\n", cp.c_str()); + } else if (cfd >= 0) { + ::close(cfd); + std::fprintf(stderr, "strata metal stream: %s is not this GGUF's (sizes or bytes differ): the GGUF is read\n", + cp.c_str()); + } + } + // size classes: one LRU pool per class. The layers' slot sizes (9 in the IQ3_XXS mix) are merged into a few + // classes, each as big as its largest member, so that no member wastes more than STRATA_METAL_CLASS_WASTE (default + // 0.15) of its slot: every class must hold a whole layer's experts for a prompt chunk, so fewer classes = less + // memory tied up in those minimums. + { + const char* ew = std::getenv("STRATA_METAL_CLASS_WASTE"); + const double waste = ew ? std::atof(ew) : 0.15; + std::vector pages_of(NL); + std::vector sizes; + for (int l = 0; l < NL; ++l) { + const Lay& x = lay_[(size_t) l]; + pages_of[(size_t) l] = (x.gs + x.us + x.ds + PAGE - 1) / PAGE; + sizes.push_back(pages_of[(size_t) l]); + } + std::sort(sizes.begin(), sizes.end()); + sizes.erase(std::unique(sizes.begin(), sizes.end()), sizes.end()); + std::vector tops; // each class's slot pages, largest first + for (auto it = sizes.rbegin(); it != sizes.rend(); ++it) + if (tops.empty() || (double) *it < (1.0 - waste) * (double) tops.back()) tops.push_back(*it); + for (uint64_t t : tops) { Cls c; c.pages = t; cls_.push_back(c); } + for (int l = 0; l < NL; ++l) { + int best = 0; // the smallest class that holds the layer's slot + for (int c = 0; c < (int) cls_.size(); ++c) + if (cls_[(size_t) c].pages >= pages_of[(size_t) l]) best = c; + lay_[(size_t) l].cls = best; + } + } + nio_ = std::max(1, env_int("STRATA_METAL_IO_THREADS", 6)); + split_ = std::max(1, std::min(8, env_int("STRATA_METAL_READ_SPLIT", 1))); + // The read-ahead's depth and where its experts wait in the LRU, measured on the M4 (notes-mac-ssd.md, 3 interleaved + // pairs each): Q2_0 (1.38 MB experts) top 10 at the LRU front 12.2 tok/s vs top 6 at the tail 11.3; the IQ3_XXS + // mix (1.75 MB, the SSD is the limit) top 6 at the tail 8.06 vs top 10 at the front 7.43. + uint64_t eb = 0; + for (const auto& x : lay_) eb += x.gs + x.us + x.ds; + const bool big = (double) eb / NL > 1.5e6; + pre_k_ = env_int("STRATA_METAL_PREFETCH", big ? 6 : 10); + pre_k2_ = env_int("STRATA_METAL_PREFETCH2", 0); + prefetch_ = pre_k_ > 0; + pre_mru_ = env_int("STRATA_METAL_PREFETCH_MRU", big ? 0 : 1) != 0; + // timing only (WRONG answers): every missing expert is pointed at slot 0, nothing is read + fake_ = env_int("STRATA_METAL_STREAM_FAKE", 0) != 0; + return true; +} + +bool ExpertStream::read(void* dst, uint64_t len, uint64_t off) const { + uint8_t* p = (uint8_t*) dst; + while (len > 0) { + const ssize_t r = ::pread(fd_, p, (size_t) std::min(len, 64ull << 20), (off_t) off); + if (r <= 0) return false; + p += r; + off += (uint64_t) r; + len -= (uint64_t) r; + } + return true; +} + +bool ExpertStream::load_dense(gguf::File& f, mtl::Context& cx, const std::vector& skip, mtl::Buffer& out, + std::string& err) { + const double t0 = now_ms(); + std::vector ts; + uint64_t tot = 0; + for (auto& kv : f.tensors) { + gguf::Tensor& t = kv.second; + if (t.name.find("_exps") != std::string::npos) continue; + if (std::find(skip.begin(), skip.end(), t.name) != skip.end()) { t.offset = 0; continue; } + ts.push_back(&t); + tot += (t.bytes + 255) / 256 * 256; + } + out = cx.alloc((tot + PAGE - 1) / PAGE * PAGE); + std::vector src(ts.size()), dst(ts.size()); + uint64_t o = 0; + for (size_t i = 0; i < ts.size(); ++i) { + src[i] = ts[i]->offset; + dst[i] = o; + o += (ts[i]->bytes + 255) / 256 * 256; + } + std::atomic next{0}; + std::atomic ok{true}; + std::vector th; + for (int k = 0; k < 4; ++k) + th.emplace_back([&] { + for (;;) { + const size_t i = next++; + if (i >= ts.size()) break; + if (!read(out.as() + dst[i], ts[i]->bytes, src[i])) ok = false; + } + }); + for (auto& x : th) x.join(); + if (!ok) { err = "metal stream: reading the dense tensors failed"; return false; } + for (size_t i = 0; i < ts.size(); ++i) ts[i]->offset = dst[i]; + std::fprintf(stderr, "strata metal stream: %zu dense tensors read into memory (%.2f GB, %.1f s; %zu left out)\n", ts.size(), + tot / 1e9, (now_ms() - t0) / 1e3, skip.size()); + return true; +} + +int ExpertStream::cls_of(int s) const { // the class ranges are contiguous + int ci = 0; + while (!(s >= cls_[(size_t) ci].base && s < cls_[(size_t) ci].base + cls_[(size_t) ci].n)) ++ci; + return ci; +} + +void ExpertStream::lru_unlink(int s) { + Slot& x = slots_[(size_t) s]; + Cls& k = cls_[(size_t) cls_of(s)]; + if (x.prev >= 0) slots_[(size_t) x.prev].next = x.next; else k.head = x.next; + if (x.next >= 0) slots_[(size_t) x.next].prev = x.prev; else k.tail = x.prev; + x.prev = x.next = -1; +} + +void ExpertStream::lru_back(int s) { + lru_unlink(s); + Cls& k = cls_[(size_t) cls_of(s)]; + Slot& x = slots_[(size_t) s]; + x.prev = k.tail; + x.next = -1; + if (k.tail >= 0) slots_[(size_t) k.tail].next = s; + k.tail = s; + if (k.head < 0) k.head = s; +} + +void ExpertStream::lru_front(int s) { + lru_unlink(s); + Cls& k = cls_[(size_t) cls_of(s)]; + Slot& x = slots_[(size_t) s]; + x.next = k.head; + x.prev = -1; + if (k.head >= 0) slots_[(size_t) k.head].prev = s; + k.head = s; + if (k.tail < 0) k.tail = s; +} + +int ExpertStream::victim(int ci) { + Cls& k = cls_[(size_t) ci]; + for (int s = k.tail; s >= 0; s = slots_[(size_t) s].prev) + if (slots_[(size_t) s].state.load() == 0 && slots_[(size_t) s].pin != stamp_) { + Slot& x = slots_[(size_t) s]; + if (x.layer >= 0) { + const int key = x.layer * NE + x.e; + where_[(size_t) key] = -1; + smap_.as()[key] = 0xFFFFFFFFu; + } + x.layer = x.e = -1; + return s; + } + return -1; +} + +// One piece of an expert: slice part / split_ (gate, up, down), piece part % split_ of it. The pieces of one expert +// go to several I/O threads, so a single miss is read with several requests in flight (its latency, not only the +// SSD's throughput, is what a layer waits for). +void ExpertStream::read_part(int s, int l, int e, int part) { + const Lay& x = lay_[(size_t) l]; + if (cfd_ >= 0) { // the contiguous copy: the whole expert, piece part of split_ (the slot keeps gate | up | down) + const uint64_t len = x.gs + x.us + x.ds, src = coff_[(size_t) l] + (uint64_t) e * len; + const uint64_t a = len * (uint64_t) part / (uint64_t) split_ / 4096 * 4096; + const uint64_t b = part + 1 == split_ ? len : len * (uint64_t) (part + 1) / (uint64_t) split_ / 4096 * 4096; + uint8_t* p = host_[(size_t) s] + a; + uint64_t n = b - a, o = src + a; + while (n > 0) { + const ssize_t r = ::pread(cfd_, p, (size_t) n, (off_t) o); + if (r <= 0) { + std::fprintf(stderr, "strata metal stream: reading expert %d of layer %d failed\n", e, l); + std::exit(6); + } + p += r; o += (uint64_t) r; n -= (uint64_t) r; + } + bytes_read_ += b - a; + return; + } + const int k = part / split_, p = part % split_; + const uint64_t len = k == 0 ? x.gs : (k == 1 ? x.us : x.ds); + const uint64_t src = (k == 0 ? x.g : (k == 1 ? x.u : x.d)) + (uint64_t) e * len; + const uint64_t dst = k == 0 ? 0 : (k == 1 ? x.gs : x.gs + x.us); + const uint64_t a = len * (uint64_t) p / (uint64_t) split_ / 4096 * 4096; + const uint64_t b = p + 1 == split_ ? len : len * (uint64_t) (p + 1) / (uint64_t) split_ / 4096 * 4096; + if (b > a && !read(host_[(size_t) s] + dst + a, b - a, src + a)) { + std::fprintf(stderr, "strata metal stream: reading expert %d of layer %d failed\n", e, l); + std::exit(6); + } + bytes_read_ += b - a; +} + +void ExpertStream::io_main() { + for (;;) { + Job j; + { + std::unique_lock g(mu_); + cv_.wait(g, [&] { return stop_ || !urgent_q_.empty() || !pre_q_.empty(); }); + if (stop_) return; + if (!urgent_q_.empty()) { j = urgent_q_.front(); urgent_q_.pop_front(); } + else { j = pre_q_.front(); pre_q_.pop_front(); } + slots_[(size_t) j.slot].state = 2; + } + read_part(j.slot, j.layer, j.e, j.part); + bool done = false; + { + std::lock_guard g(mu_); + Slot& x = slots_[(size_t) j.slot]; + if (--x.left == 0) { + smap_.as()[j.layer * NE + j.e] = code_[(size_t) j.slot]; + x.state = 0; + --outstanding_; + ++reads_; + done = true; + } + } + if (done) done_cv_.notify_all(); + } +} + +void ExpertStream::submit(int s, int l, int e, bool urgent) { + Slot& x = slots_[(size_t) s]; + x.layer = (int16_t) l; + x.e = (int16_t) e; + x.state = 1; + x.pre = !urgent; + const int parts = cfd_ >= 0 ? split_ : 3 * split_; + x.left = parts; + ++outstanding_; + where_[(size_t) (l * NE + e)] = s; + for (int p = 0; p < parts; ++p) (urgent ? urgent_q_ : pre_q_).push_back({s, l, e, p}); +} + +// a queued read-ahead nobody wants: its pieces dropped, the slot freed (only before any piece has started) +void ExpertStream::cancel_slot(int s) { + Slot& x = slots_[(size_t) s]; + for (auto it = pre_q_.begin(); it != pre_q_.end();) it = it->slot == s ? pre_q_.erase(it) : it + 1; + where_[(size_t) (x.layer * NE + x.e)] = -1; + x.layer = x.e = -1; + x.state = 0; + x.pre = false; + x.left = 0; + --outstanding_; + ++pre_cancel_; + lru_back(s); +} + +// a read-ahead that is wanted now: its queued pieces go first +void ExpertStream::promote_slot(int s) { + std::vector mine; + for (auto it = pre_q_.begin(); it != pre_q_.end();) + if (it->slot == s) { mine.push_back(*it); it = pre_q_.erase(it); } + else ++it; + for (auto it = mine.rbegin(); it != mine.rend(); ++it) urgent_q_.push_front(*it); +} + +bool ExpertStream::make_arena(mtl::Context& cx, uint64_t budget, const std::string& profile, int min_slots, std::string& err, + const std::function& recheck, const std::function& grow) { + const double t0 = now_ms(); + shrink_to_ = 0; + for (auto& k : cls_) k.n = 0; // a second try (after a shrink) lays the arena out again + // the ranking: the profile's pairs, then every pair it misses, layer-interleaved + std::vector> rank; + std::vector seen((size_t) NL * NE, 0); + if (FILE* f = std::fopen(profile.c_str(), "rb")) { + char magic[4]; + uint32_t h[5]; + if (std::fread(magic, 1, 4, f) == 4 && std::memcmp(magic, "STRP", 4) == 0 && std::fread(h, 4, 5, f) == 5 && + h[1] == (uint32_t) NL && h[2] == (uint32_t) NE) { + for (uint32_t i = 0; i < h[4]; ++i) { + uint16_t p[2]; + if (std::fread(p, 2, 2, f) != 2) break; + if (p[0] < NL && p[1] < NE && !seen[(size_t) p[0] * NE + p[1]]) { + seen[(size_t) p[0] * NE + p[1]] = 1; + rank.push_back({p[0], p[1]}); + } + } + } + std::fclose(f); + } else { + std::fprintf(stderr, "strata metal stream: no expert profile at %s: the arena starts layer-interleaved\n", profile.c_str()); + } + const size_t from_profile = rank.size(); + for (int e = 0; e < NE; ++e) + for (int l = 0; l < NL; ++l) + if (!seen[(size_t) l * NE + e]) rank.push_back({l, e}); + // the pool of each size class: at least min_slots (a prompt chunk's layer needs up to 512 at once), then the + // top-ranked pairs that fit in the budget + uint64_t used = 0; + for (const auto& k : cls_) used += (uint64_t) min_slots * k.pages * PAGE; + std::vector> fill; + for (const auto& p : rank) { + Cls& k = cls_[(size_t) lay_[(size_t) p.first].cls]; + const uint64_t cost = k.n < min_slots ? 0 : k.pages * PAGE; + if (used + cost > budget) break; + used += cost; + ++k.n; + fill.push_back(p); + } + int base = 0; + for (auto& k : cls_) { + k.n = std::max(k.n, min_slots); + k.base = base; + base += k.n; + } + // the slots placed in chunks of at most maxBufferLength (and 8 GB), up to 4 (the kernels' buffers 0, 7, 8, 9) + // (8 GB each unless the arena needs bigger ones to fit 4: the M4 refused one 20.6 GB buffer, the M5 Max takes an + // 89 GB arena for UD-Q5_K_XL in 4 of ~23 GB; STRATA_METAL_ARENA_CHUNK_GB sets it) + uint64_t total = 0, biggest = 0; + for (const auto& k : cls_) { + total += (uint64_t) k.n * k.pages * PAGE; + biggest = std::max(biggest, k.pages * PAGE); + } + uint64_t want = std::max(8ull << 30, total / 4 + 4 * biggest); + if (const char* e = std::getenv("STRATA_METAL_ARENA_CHUNK_GB")) want = (uint64_t) (std::atof(e) * (1ull << 30)); + const uint64_t cmax = std::min(cx.max_buffer_length(), want) / PAGE * PAGE; + code_.assign((size_t) base, 0); + host_.assign((size_t) base, nullptr); + std::vector csize; + std::vector> at((size_t) base); + uint64_t cur = 0; + for (const auto& k : cls_) + for (int s = k.base; s < k.base + k.n; ++s) { + if (csize.empty() || cur + k.pages * PAGE > cmax) { + if (!csize.empty()) csize.back() = cur; + csize.push_back(0); + cur = 0; + } + at[(size_t) s] = {(int) csize.size() - 1, cur / PAGE}; + cur += k.pages * PAGE; + } + if (!csize.empty()) csize.back() = cur; + if (csize.size() > 4) { err = "metal stream: the arena needs more than 4 buffers (lower STRATA_METAL_ARENA_GB)"; return false; } + if (recheck) { // the memory macOS can give, asked again just before the arena is committed + uint64_t total = 0; + for (uint64_t b : csize) total += b; + const uint64_t allowed = recheck(); + if (allowed + (64ull << 20) < total) { + shrink_to_ = allowed; + err = "metal stream: less memory than planned is free now: the arena shrinks"; + return false; + } + } + for (uint64_t b : csize) { // anonymous memory wrapped no-copy: a prompt's buffers can alias a region of it + void* m = mmap(nullptr, (size_t) b, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); + if (m == MAP_FAILED) { err = "metal stream: cannot map the arena"; return false; } + chunks_.push_back(cx.wrap(m, (size_t) b)); + arena_bytes_ += b; + } + for (int s = 0; s < base; ++s) { + code_[(size_t) s] = ((uint32_t) at[(size_t) s].first << 28) | (uint32_t) at[(size_t) s].second; + host_[(size_t) s] = chunks_[(size_t) at[(size_t) s].first].as() + at[(size_t) s].second * PAGE; + } + smap_ = cx.alloc((size_t) NL * NE * 4); + std::memset(smap_.ptr, 0xFF, (size_t) NL * NE * 4); + slots_ = std::vector((size_t) base); + retired_.assign((size_t) base, 0); + where_.assign((size_t) NL * NE, -1); + for (auto& k : cls_) { + for (int s = k.base; s < k.base + k.n; ++s) { + slots_[(size_t) s].prev = s == k.base ? -1 : s - 1; + slots_[(size_t) s].next = s + 1 == k.base + k.n ? -1 : s + 1; + } + k.head = k.n ? k.base : -1; + k.tail = k.n ? k.base + k.n - 1 : -1; + } + for (int i = 0; i < nio_; ++i) io_.emplace_back([this] { io_main(); }); + // the fill: the ranked pairs in steps (best first; each step in file order) on the I/O threads; before each step + // grow() asks whether macOS still has the memory for it (arena_grow); the best-ranked ends at the LRU front + uint64_t step = 1536ull << 20; + if (const char* e = std::getenv("STRATA_METAL_ARENA_STEP_GB")) step = std::max(64ull << 20, (uint64_t) (std::atof(e) * 1e9)); + std::vector next_free(cls_.size()); + for (size_t c = 0; c < cls_.size(); ++c) next_free[c] = cls_[c].base; + size_t done = 0; + bool stopped = false; + uint64_t filled = 0; + while (done < fill.size()) { + size_t j = done; + uint64_t sb = 0; + while (j < fill.size() && (sb < step || j == done)) sb += cls_[(size_t) lay_[(size_t) fill[j++].first].cls].pages * PAGE; + if (grow && !grow(sb)) { stopped = true; break; } + std::vector> order(fill.begin() + (long) done, fill.begin() + (long) j); + std::sort(order.begin(), order.end(), [&](const auto& a, const auto& b) { + return lay_[(size_t) a.first].g + (uint64_t) a.second * lay_[(size_t) a.first].gs < + lay_[(size_t) b.first].g + (uint64_t) b.second * lay_[(size_t) b.first].gs; + }); + { + std::lock_guard g(mu_); + for (const auto& p : order) { + const int c = lay_[(size_t) p.first].cls; + submit(next_free[(size_t) c]++, p.first, p.second, true); + } + } + cv_.notify_all(); + { + std::unique_lock g(mu_); + done_cv_.wait(g, [&] { return outstanding_ == 0; }); + } + filled += sb; + done = j; + } + uint64_t retired_bytes = 0; + size_t nretired = 0; + { + std::unique_lock g(mu_); + if (stopped) // the slots not filled stay unused (their pages never touched), all but min_slots of each class + for (size_t c = 0; c < cls_.size(); ++c) { + const Cls& k = cls_[c]; + for (int s = std::max(next_free[c], k.base + std::min(min_slots, k.n)); s < k.base + k.n; ++s) { + lru_unlink(s); + retired_[(size_t) s] = 1; + retired_bytes += k.pages * PAGE; + ++nretired; + } + } + // the LRU order = the rank order (best at the front) + for (size_t i = done; i-- > 0;) lru_front(where_[(size_t) (fill[i].first * NE + fill[i].second)]); + } + if (stopped) + std::fprintf(stderr, "strata metal stream: the arena's fill stopped after %.2f GB: macOS's free memory reached what it " + "keeps; %.2f GB of the arena (%zu slots) stay unused\n", filled / 1e9, retired_bytes / 1e9, nretired); + fill_s_ = (now_ms() - t0) / 1e3; + fill_bytes_ = bytes_read_.load(); + uint64_t pairs = 0; + for (const auto& k : cls_) pairs += (uint64_t) k.n; + std::fprintf(stderr, "strata metal stream: expert arena %.2f GB, %llu slots in %zu size classes, %zu experts read from the " + "profile's top (%zu ranked) in %.1f s (%.2f GB/s); %d I/O threads, read-ahead top %d; %zu buffers\n", + (arena_bytes_ - retired_bytes) / 1e9, (unsigned long long) (pairs - nretired), cls_.size(), done, from_profile, fill_s_, + fill_bytes_ / 1e9 / std::max(1e-9, fill_s_), nio_, prefetch_ ? pre_k_ : 0, chunks_.size()); + (void) err; + return true; +} + +// the experts a predicted routing names, most likely first (by the best logit over the window's tokens) +void ExpertStream::ahead(int ln, int T, const float* pred, int K) { + K = std::min(K, 32); + std::pair pw[8 * 32]; + int np = 0; + for (int t = 0; t < T; ++t) { + const float* lg = pred + (size_t) t * NE; + int top[32]; + int nt = 0; + for (int e = 0; e < NE; ++e) { + if (nt < K) { top[nt++] = e; continue; } + int m = 0; + for (int j = 1; j < K; ++j) if (lg[top[j]] < lg[top[m]]) m = j; + if (lg[e] > lg[top[m]]) top[m] = e; + } + for (int j = 0; j < nt; ++j) { + int q = 0; + while (q < np && pw[q].second != top[j]) ++q; + if (q == np) pw[np++] = {lg[top[j]], top[j]}; + else pw[q].first = std::max(pw[q].first, lg[top[j]]); + } + } + std::sort(pw, pw + np, [](const auto& a, const auto& b) { return a.first > b.first; }); + bool any = false; + { + std::lock_guard g(mu_); + for (int j = 0; j < np; ++j) { + const int key = ln * NE + pw[j].second; + const int s0 = where_[(size_t) key]; + if (s0 >= 0) { lru_front(s0); continue; } + const int s = victim(lay_[(size_t) ln].cls); + if (s < 0) break; + submit(s, ln, pw[j].second, false); + slots_[(size_t) s].pin = stamp_; + if (pre_mru_) lru_front(s); + else lru_back(s); + ++pre_issued_; + any = true; + } + } + if (any) cv_.notify_all(); +} + +void ExpertStream::at_layer(int l, int T, int topk, const int32_t* ids, const float* pred, const float* pred2) { + const double t0 = now_ms(); + const bool prompt = T > 8; // a prompt chunk (the GEMM path): nearly every expert of the layer is used + if (l == 0) { if (prompt) ++p_chunks_; else ++windows_; } + ++stamp_; // the slots this layer uses are pinned until the next handshake + bool used[NE] = {}; + int want[NE]; + int nw = 0; + for (int i = 0; i < T * topk; ++i) { + const int e = ids[i]; + if (e < 0 || e >= NE || used[e]) continue; + used[e] = true; + want[nw++] = e; + } + if (fake_) { + for (int j = 0; j < nw; ++j) + if (where_[(size_t) (l * NE + want[j])] < 0) smap_.as()[l * NE + want[j]] = code_[0]; + host_ms_ += now_ms() - t0; + return; + } + std::vector wait; + { + std::lock_guard g(mu_); + // read-aheads of this layer (or older) that were not started and are not wanted: dropped (the slot goes free) + { + std::vector drop; + for (const Job& j : pre_q_) { + if (j.layer > l || slots_[(size_t) j.slot].state.load() != 1) continue; + if (!(j.layer == l && used[j.e]) && std::find(drop.begin(), drop.end(), j.slot) == drop.end()) drop.push_back(j.slot); + } + for (int s : drop) cancel_slot(s); + } + for (int j = 0; j < nw; ++j) // pass 1: pin what is resident (or on its way), so no miss below evicts it + if (where_[(size_t) (l * NE + want[j])] >= 0) slots_[(size_t) where_[(size_t) (l * NE + want[j])]].pin = stamp_; + for (int j = 0; j < nw; ++j) { + const int e = want[j], key = l * NE + e; + uint64_t& lk = prompt ? p_lookups_ : lookups_; + ++lk; + int s = where_[(size_t) key]; + if (s >= 0) { + Slot& x = slots_[(size_t) s]; + x.pin = stamp_; + const int st = x.state.load(); + if (st == 0) { if (x.pre) ++(prompt ? p_pre_ : pre_hits_); else ++(prompt ? p_hits_ : hits_); } + else { + ++(prompt ? p_pre_ : pre_hits_); + if (!prompt) ++late_; + promote_slot(s); // a queued read-ahead becomes urgent + wait.push_back(s); + } + if (!(prompt && x.pre)) lru_front(s); // a prompt's streamed experts stay at the LRU tail + x.pre = false; + continue; + } + ++(prompt ? p_misses_ : misses_); + s = victim(lay_[(size_t) l].cls); + if (s < 0) { std::fprintf(stderr, "strata metal stream: no free slot (layer %d)\n", l); std::exit(6); } + submit(s, l, e, true); + slots_[(size_t) s].pin = stamp_; + if (!prompt) lru_front(s); + wait.push_back(s); + } + } + if (!wait.empty()) { + cv_.notify_all(); + const double tw = now_ms(); + std::unique_lock g(mu_); + done_cv_.wait(g, [&] { + for (int s : wait) if (slots_[(size_t) s].state.load() != 0) return false; + return true; + }); + (prompt ? p_wait_ms_ : wait_ms_) += now_ms() - tw; + } + if (prompt) { + // a chunk uses nearly all of the next layer's experts: every one not in the arena is streamed in behind this + // layer's compute, into the LRU tail (the decode-hot experts stay) + if (l + 1 < NL) { + bool any = false; + std::lock_guard g(mu_); + const int ln = l + 1; + for (int e = 0; e < NE; ++e) { + if (where_[(size_t) (ln * NE + e)] >= 0) continue; + const int s = victim(lay_[(size_t) ln].cls); + if (s < 0) break; + submit(s, ln, e, false); + slots_[(size_t) s].pin = stamp_; + ++p_streamed_; + any = true; + } + if (any) cv_.notify_all(); + } + (prompt ? p_host_ms_ : host_ms_) += now_ms() - t0; + return; + } + // read-ahead: layer l + 1 (each token's top pre_k_ of the predicted router logits), then layer l + 2 (top pre_k2_) + if (prefetch_ && pred && l + 1 < NL) ahead(l + 1, T, pred, pre_k_); + if (pre_k2_ > 0 && pred2 && l + 2 < NL) ahead(l + 2, T, pred2, pre_k2_); + host_ms_ += now_ms() - t0; +} + +// A region of `bytes` at the end of one arena buffer, for a prompt's scratch buffers: its slots are emptied and held +// (state 3) while a prompt runs (hold_region), and are ordinary slots again for decoding. +uint8_t* ExpertStream::region(uint64_t bytes) { + for (int c = (int) chunks_.size() - 1; c >= 0; --c) { + if (chunks_[(size_t) c].bytes < bytes + (64ull << 20)) continue; + uint8_t* end = chunks_[(size_t) c].as() + chunks_[(size_t) c].bytes; + uint8_t* lo = end - (bytes + PAGE - 1) / PAGE * PAGE; + region_slots_.clear(); + uint8_t* first = end; + for (int s = 0; s < (int) slots_.size(); ++s) { + const uint8_t* h = host_[(size_t) s]; + const uint64_t sz = cls_[(size_t) cls_of(s)].pages * PAGE; + if (h + sz > lo && h < end) { region_slots_.push_back(s); first = std::min(first, (uint8_t*) h); } + } + { // a class left with fewer slots than a prompt chunk's layer can use (NE) would stop with "no free slot": a small + // arena (a Mac with little free memory at start) gets the prompt's buffers as their own allocation instead + std::vector stolen(cls_.size(), 0); + for (int s : region_slots_) ++stolen[(size_t) cls_of(s)]; + bool tight = false; + for (size_t i = 0; i < cls_.size(); ++i) tight = tight || (cls_[i].n > 0 && cls_[i].n - stolen[i] < NE); + if (tight) { + const uint64_t sz = (bytes + PAGE - 1) / PAGE * PAGE; + void* m = mmap(nullptr, (size_t) sz, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); + if (m == MAP_FAILED) return nullptr; + region_slots_.clear(); + region_ = (uint8_t*) m; + region_bytes_ = 0; // fresh zero pages; nothing in the arena to empty + std::fprintf(stderr, "strata metal stream: the arena is small: the prompt's %.2f GB of buffers are their own " + "allocation, not a region of its slots\n", bytes / 1e9); + return region_; + } + } + region_ = lo; + region_bytes_ = (uint64_t) (end - lo); + std::fprintf(stderr, "strata metal stream: %.2f GB of the arena (%zu slots) hold a prompt's buffers while it runs\n", + bytes / 1e9, region_slots_.size()); + return lo; + } + return nullptr; +} + +void ExpertStream::hold_region(bool hold) { + std::unique_lock g(mu_); + if (hold) { + // nothing may be reading into those slots: the queued read-aheads are dropped, the running ones waited for + std::vector drop; + for (const Job& j : pre_q_) + if (slots_[(size_t) j.slot].state.load() == 1 && std::find(drop.begin(), drop.end(), j.slot) == drop.end()) + drop.push_back(j.slot); + for (int s : drop) cancel_slot(s); + done_cv_.wait(g, [&] { return outstanding_ == 0; }); + for (int s : region_slots_) { + Slot& x = slots_[(size_t) s]; + if (x.layer >= 0) { + const int key = x.layer * NE + x.e; + where_[(size_t) key] = -1; + smap_.as()[key] = 0xFFFFFFFFu; + } + x.layer = x.e = -1; + x.pre = false; + x.state = 3; + } + if (region_) std::memset(region_, 0, (size_t) region_bytes_); + } else { + for (int s : region_slots_) { + slots_[(size_t) s].state = 0; + if (!retired_[(size_t) s]) lru_back(s); // a retired slot's memory serves the prompt only + } + } +} + +void ExpertStream::reset_stats() { + lookups_ = hits_ = pre_hits_ = late_ = misses_ = pre_issued_ = pre_cancel_ = windows_ = 0; + p_lookups_ = p_hits_ = p_pre_ = p_misses_ = p_streamed_ = p_chunks_ = 0; + p_wait_ms_ = p_host_ms_ = 0; + bytes_read_ = 0; + reads_ = 0; + wait_ms_ = host_ms_ = 0; +} + +void ExpertStream::report(FILE* f) const { + if (!ready()) return; + if (p_chunks_) + std::fprintf(f, "expert stream prompts %llu chunks: %llu distinct lookups (%.1f per layer), in the arena %.4f, streamed " + "ahead %.4f, missed %.4f; %llu streamed in; host %.1f ms per chunk, of it waiting %.1f ms\n", + (unsigned long long) p_chunks_, (unsigned long long) p_lookups_, p_lookups_ / 48.0 / p_chunks_, + p_hits_ / std::max(1.0, (double) p_lookups_), p_pre_ / std::max(1.0, (double) p_lookups_), + p_misses_ / std::max(1.0, (double) p_lookups_), (unsigned long long) p_streamed_, p_host_ms_ / p_chunks_, + p_wait_ms_ / p_chunks_); + const double w = std::max(1, windows_); + std::fprintf(f, + "expert stream %llu windows: %llu distinct lookups (%.1f per window), hits %.4f, read-ahead hits " + "%.4f (%llu of them late), misses %.4f (%.1f per window); read-aheads %llu (%.1f per window, %llu dropped); %.1f MB " + "read per window (%llu reads); host %.2f ms per window, of it waiting %.2f ms\n", + (unsigned long long) windows_, (unsigned long long) lookups_, lookups_ / w, + hits_ / std::max(1.0, (double) lookups_), pre_hits_ / std::max(1.0, (double) lookups_), + (unsigned long long) late_, misses_ / std::max(1.0, (double) lookups_), misses_ / w, + (unsigned long long) pre_issued_, pre_issued_ / w, (unsigned long long) pre_cancel_, + (bytes_read_.load() - 0) / 1e6 / w, (unsigned long long) reads_.load(), host_ms_ / w, wait_ms_ / w); +} + +} // namespace strata::metal_engine diff --git a/metal/src/engine/stream.h b/metal/src/engine/stream.h new file mode 100644 index 00000000..46317d3a --- /dev/null +++ b/metal/src/engine/stream.h @@ -0,0 +1,129 @@ +// metal/src/engine/stream.h - the SSD-streaming expert arena for Macs whose memory cannot hold the model (MAC-PLAN +// Phase 3, the small-Mac path; measured on the M4 Mac mini 32 GB, phaseA-tests/notes-mac-ssd.md). +// +// * The dense weights (everything but the routed experts) are read once into one resident shared buffer; the +// GGUF is never wrapped as a whole (a 37.6 GB NoCopy buffer cannot be made resident in 32 GB). +// * The routed experts live in a resident arena of slots (one shared MTLBuffer), filled straight from the GGUF +// with F_NOCACHE preads: one SSD read per expert slice, no staging copy, no page cache. smap (48 x 512 uint32: +// the slot's 16 KiB page in the arena, or ~0) is what the expert kernels read (moe.metal, function constant 20). +// * The decode window is one command buffer in 48 segments; after each layer's router the GPU signals a shared +// event and waits for the host (mtl_rt run_graph_seg). The host's turn (at_layer): the window's routed experts +// of that layer are looked up, the missing ones read into LRU victims (several reads in flight), smap updated; +// then the experts the NEXT layer's router predicts from this layer's FFN input are read ahead on the I/O +// threads while the GPU computes. +// * The arena starts with the expert profile's top-ranked pairs (data/expert-profile.bin). +// The numbers are exact: a slot holds the expert's GGUF bytes unchanged, so the answers are those of the resident +// engine (the kernels read the same bytes at another address). +#pragma once + +#include "gguf_lite.h" +#include "mtl_rt.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::metal_engine { + +class ExpertStream { +public: + ~ExpertStream(); + // On when STRATA_METAL_STREAM=1, or (unset / auto) when the GGUF's experts do not fit in the GPU working set + // with room to spare. =0: never (the whole GGUF wrapped, as on the M5 Max). + static bool wanted(const gguf::File& f, const mtl::Context& cx); + bool open(const gguf::File& f, std::string& err); + // pread `len` bytes at file offset `off` (F_NOCACHE) + bool read(void* dst, uint64_t len, uint64_t off) const; + // The dense tensors into one buffer; every tensor's offset in `f` is rewritten to its offset in `out`. + // Tensors named in `skip` are left out (their offset is set to 0: they must not be read any more). + bool load_dense(gguf::File& f, mtl::Context& cx, const std::vector& skip, mtl::Buffer& out, + std::string& err); + // The arena: `budget` bytes of slots, filled from the profile's ranking (or layer-interleaved if none). + // min_slots: each size class at least this many slots (576 with prompt chunks, else 64) + // recheck (optional): just before the arena is committed, the bytes it may have now (arena_shrink); when that is + // less than the arena laid out, nothing is allocated, shrink_to() says how much, and the caller tries again + bool make_arena(mtl::Context& cx, uint64_t budget, const std::string& profile, int min_slots, std::string& err, + const std::function& recheck = {}, + const std::function& grow = {}); + uint64_t shrink_to() const { return shrink_to_; } + bool ready() const { return !chunks_.empty(); } + // the arena's buffers (at most 4, each within the device's maxBufferLength): chunk(i) for i >= count is chunk 0 + const mtl::Buffer& chunk(int i) const { return chunks_[(size_t) i < chunks_.size() ? (size_t) i : 0]; } + const mtl::Buffer& smap() const { return smap_; } + uint64_t up_in_slot(int l) const { return lay_[(size_t) l].gs; } + uint64_t down_in_slot(int l) const { return lay_[(size_t) l].gs + lay_[(size_t) l].us; } + // The host's turn at layer l: ids = the window's T x topk routed ids; pred = T x 512 router logits of layer l + 1 + // computed from this layer's FFN input (nullptr: no read-ahead). + // pred2: layer l + 2's, from the same input (STRATA_METAL_PREFETCH2 = its top-k, 0 = off) + void at_layer(int l, int T, int topk, const int32_t* ids, const float* pred, const float* pred2 = nullptr); + int ahead2() const { return pre_k2_; } + // a prompt's scratch buffers inside the arena: region() places them (once), hold_region() empties and holds its + // slots while a prompt runs and gives them back after + uint8_t* region(uint64_t bytes); + void hold_region(bool hold); + void report(FILE* f) const; + void reset_stats(); + +private: + uint64_t shrink_to_ = 0; + struct Lay { uint64_t g, gs, u, us, d, ds; int cls; }; + struct Slot { int16_t layer = -1; int16_t e = -1; int prev = -1, next = -1; bool pre = false; int left = 0; uint64_t pin = 0; std::atomic state{0}; }; // 0 idle, 1 queued, 2 reading + struct Cls { uint64_t pages = 0; int n = 0; int base = 0; int head = -1, tail = -1; }; // slot range [base, base+n) + struct Job { int slot; int layer, e, part; }; // part: slice * split_ + piece + void lru_unlink(int s); + void lru_front(int s); + void lru_back(int s); + int cls_of(int s) const; + int victim(int cls); + void read_part(int slot, int l, int e, int part); + void cancel_slot(int s); + void promote_slot(int s); + void io_main(); + void ahead(int ln, int T, const float* pred, int K); + void submit(int slot, int l, int e, bool urgent); + void wait_slot(int s); + + int fd_ = -1; + // .experts (metal/tools/stream_experts.py): each expert's gate, up and down rows together, read with one + // request (cfd_ >= 0); else the GGUF's three slices. STRATA_METAL_CONTIG=0: the GGUF always. + int cfd_ = -1; + std::vector coff_; + std::vector lay_; + std::vector cls_; + std::vector slots_; + std::vector retired_; // slots left unused when the stepped fill stopped at macOS's floor (never in an LRU) + std::vector where_; // (l * 512 + e) -> slot, -1 + std::vector chunks_; + std::vector region_slots_; + uint8_t* region_ = nullptr; + uint64_t region_bytes_ = 0; + std::vector code_; // slot -> its smap value (chunk << 28 | page) + std::vector host_; // slot -> its CPU address + mtl::Buffer smap_; + uint64_t arena_bytes_ = 0; + // the I/O threads + std::vector io_; + std::mutex mu_; + std::condition_variable cv_, done_cv_; + std::deque urgent_q_, pre_q_; + bool stop_ = false; + int outstanding_ = 0; + int nio_ = 6, pre_k_ = 10, pre_k2_ = 0, split_ = 2; + bool prefetch_ = true, fake_ = false, pre_mru_ = false; + // stats + uint64_t stamp_ = 1; // the handshake count: slots pinned with the current one are in use on the GPU + uint64_t p_lookups_ = 0, p_hits_ = 0, p_pre_ = 0, p_misses_ = 0, p_streamed_ = 0, p_chunks_ = 0; + double p_wait_ms_ = 0, p_host_ms_ = 0; + uint64_t lookups_ = 0, hits_ = 0, pre_hits_ = 0, late_ = 0, misses_ = 0, pre_issued_ = 0, pre_cancel_ = 0, windows_ = 0; + std::atomic bytes_read_{0}, reads_{0}; + double wait_ms_ = 0, host_ms_ = 0, fill_s_ = 0; + uint64_t fill_bytes_ = 0; +}; + +} // namespace strata::metal_engine diff --git a/metal/src/engine/stubs.cpp b/metal/src/engine/stubs.cpp new file mode 100644 index 00000000..2b651e54 --- /dev/null +++ b/metal/src/engine/stubs.cpp @@ -0,0 +1,367 @@ +// metal/src/engine/stubs.cpp - GENERATED by metal/tools/gen_stubs.py: do not edit. +// The kernel-library entry points with no Metal implementation yet: each stops the engine with its name +// (metal/src/engine/missing.cpp). Regenerate after porting one. + +#include "strata/kernels/bf16_bits.hpp" +#include "strata/kernels/bf16_gemv.hpp" +#include "strata/kernels/cvec.hpp" +#include "strata/kernels/dequant_bf16.hpp" +#include "strata/kernels/dequant_s2.hpp" +#include "strata/kernels/elementwise.hpp" +#include "strata/kernels/f16_bits.hpp" +#include "strata/kernels/fused_gdn.hpp" +#include "strata/kernels/fused_gr.hpp" +#include "strata/kernels/gdn.hpp" +#include "strata/kernels/gfx_arch.hpp" +#include "strata/kernels/gr.hpp" +#include "strata/kernels/iq_kernels.hpp" +#include "strata/kernels/kv_q4.hpp" +#include "strata/kernels/kv_q8.hpp" +#include "strata/kernels/kv_stream.hpp" +#include "strata/kernels/mrope.hpp" +#include "strata/kernels/native_flash_attn.hpp" +#include "strata/kernels/native_gdn.hpp" +#include "strata/kernels/native_gdn_preprocess.hpp" +#include "strata/kernels/native_gr_norm.hpp" +#include "strata/kernels/native_gr_postops.hpp" +#include "strata/kernels/native_mmvq.hpp" +#include "strata/kernels/native_moe.hpp" +#include "strata/kernels/native_ple_postops.hpp" +#include "strata/kernels/native_qsa.hpp" +#include "strata/kernels/native_qsa_indexer.hpp" +#include "strata/kernels/native_qsa_score.hpp" +#include "strata/kernels/native_rope.hpp" +#include "strata/kernels/native_router.hpp" +#include "strata/kernels/ngram.hpp" +#include "strata/kernels/pdl.hpp" +#include "strata/kernels/ple.hpp" +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" +#include "strata/kernels/qsa_prompt_attn.hpp" +#include "strata/kernels/qsa_select.hpp" +#include "strata/kernels/quantize_act.hpp" +#include "strata/kernels/rope.hpp" +#include "strata/kernels/rope_scaling.hpp" +#include "strata/kernels/route_prior.hpp" +#include "strata/kernels/router_top10.hpp" +#include "strata/kernels/s2_expert_grouped.hpp" +#include "strata/kernels/s2_gemv.hpp" +#include "strata/kernels/s2_gemv_q8.hpp" +#include "strata/kernels/s_gemv.hpp" +#include "strata/kernels/sampler.hpp" +#include "strata/kernels/shared_expert.hpp" +#include "strata/kernels/verify_kernels.hpp" +#include "strata/kernels/cpu/expert.hpp" +#include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/kernels/cpu/iq_avx1.hpp" +#include "strata/kernels/cpu/iq_avx2.hpp" +#include "strata/kernels/cpu/iq_avx512.hpp" +#include "strata/kernels/cpu/kq_avx1.hpp" +#include "strata/kernels/cpu/kq_avx2.hpp" +#include "strata/kernels/cpu/native_expert.hpp" +#include "strata/kernels/cpu/pool.hpp" +#include "strata/prefill/gemm.hpp" +#include "strata/prefill/kernels.hpp" +#include "strata/prefill/moe_fused.hpp" +#include "strata/prefill/moe_fused_iq.hpp" +#include "strata/prefill/moe_mmq.hpp" +#include "strata/prefill/prefill.hpp" +#include "strata/prefill/share_rules.hpp" +#include "strata/prefill/xmx_moe.hpp" +#include "strata/core/arch_defaults.hpp" +#include "strata/core/batch_rows.hpp" +#include "strata/core/conversation_buffer.hpp" +#include "strata/core/conversation_cache.hpp" +#include "strata/core/conversation_file.hpp" +#include "strata/core/conversation_memory.hpp" +#include "strata/core/conversation_snapshot.hpp" +#include "strata/core/coupled_draft.hpp" +#include "strata/core/device.hpp" +#include "strata/core/dma_batch.hpp" +#include "strata/core/emulate.hpp" +#include "strata/core/exchange_storage.hpp" +#include "strata/core/expert_cache.hpp" +#include "strata/core/expert_source.hpp" +#include "strata/core/foresight_swap.hpp" +#include "strata/core/graph.hpp" +#include "strata/core/hit_hook.hpp" +#include "strata/core/layer.hpp" +#include "strata/core/layout.hpp" +#include "strata/core/logit_bias.hpp" +#include "strata/core/mtp.hpp" +#include "strata/core/native_dense.hpp" +#include "strata/core/native_head.hpp" +#include "strata/core/on_device.hpp" +#include "strata/core/peer_experts.hpp" +#include "strata/core/pinned.hpp" +#include "strata/core/pinned_ring.hpp" +#include "strata/core/progress.hpp" +#include "strata/core/remote_expert_opt.hpp" +#include "strata/core/remote_experts.hpp" +#include "strata/core/session.hpp" +#include "strata/core/session_save_reclaim.hpp" +#include "strata/core/spec_prob.hpp" +#include "strata/core/verify.hpp" +#include "strata/core/vmm.hpp" +#include "strata/core/weights.hpp" +#include "strata/platform/aux_cpus.hpp" +#include "strata/platform/direct_file.hpp" +#include "strata/platform/host_limits.hpp" +#include "strata/platform/memory.hpp" +#include "strata/ngram/ple_reader.hpp" +#include "strata/spec/controller.hpp" +#include "strata/spec/draft_policy.hpp" +#include "strata/spec/draft_source.hpp" +#include "strata/spec/suffix_drafter.hpp" +#include + +namespace strata::metal_engine { void missing(const char* name); } + +auto strata::core::RemoteExpertOpt::accumulate(const RemoteExperts & p0) -> void { strata::metal_engine::missing("strata::core::RemoteExpertOpt::accumulate"); } +auto strata::core::RemoteExpertOpt::adapt(const std::vector & p0, const std::vector & p1, const std::vector> & p2, int p3, ExpertSource & p4) -> bool { strata::metal_engine::missing("strata::core::RemoteExpertOpt::adapt"); return {}; } +auto strata::core::RemoteExpertOpt::attach(RemoteExperts & p0) -> void { strata::metal_engine::missing("strata::core::RemoteExpertOpt::attach"); } +auto strata::core::RemoteExpertOpt::begin(const float * p0, int p1, int p2) -> void { strata::metal_engine::missing("strata::core::RemoteExpertOpt::begin"); } +auto strata::core::RemoteExpertOpt::combine(float * p0, float * p1, int p2, int p3, const uint32_t * p4, uint32_t p5, void * p6) const -> void { strata::metal_engine::missing("strata::core::RemoteExpertOpt::combine"); } +auto strata::core::RemoteExpertOpt::copy_rows(float * p0, const float * p1, int p2, int p3, const int32_t * p4, const int32_t * p5, void * p6) const -> void { strata::metal_engine::missing("strata::core::RemoteExpertOpt::copy_rows"); } +auto strata::core::RemoteExpertOpt::init(std::string & p0) -> bool { strata::metal_engine::missing("strata::core::RemoteExpertOpt::init"); return {}; } +auto strata::core::RemoteExpertOpt::metadata_bytes() -> size_t { strata::metal_engine::missing("strata::core::RemoteExpertOpt::metadata_bytes"); return {}; } +auto strata::core::RemoteExpertOpt::owns(int64_t p0, int32_t p1) const -> bool { strata::metal_engine::missing("strata::core::RemoteExpertOpt::owns"); return {}; } +auto strata::core::RemoteExpertOpt::prepare(const RemoteExperts & p0, void * p1) const -> void { strata::metal_engine::missing("strata::core::RemoteExpertOpt::prepare"); } +auto strata::core::RemoteExpertOpt::reduce(RemoteExperts & p0, const void * p1, std::string & p2) -> bool { strata::metal_engine::missing("strata::core::RemoteExpertOpt::reduce"); return {}; } +strata::core::RemoteExpertOpt::~RemoteExpertOpt() { strata::metal_engine::missing("strata::core::RemoteExpertOpt::~RemoteExpertOpt"); } +namespace strata::kernels { void add_inplace(float * p0, const float * p1, int64_t p2, void * p3) { strata::metal_engine::missing("strata::kernels::add_inplace"); } } +namespace strata::kernels { void add_streams_broadcast(const float * p0, const float * p1, float * p2, int64_t p3, int p4, int p5, void * p6) { strata::metal_engine::missing("strata::kernels::add_streams_broadcast"); } } +namespace strata::kernels { void argmax_rows(const float * p0, int p1, int p2, void * p3, int32_t * p4, void * p5) { strata::metal_engine::missing("strata::kernels::argmax_rows"); } } +namespace strata::kernels { bool argmax_rows_wanted() { strata::metal_engine::missing("strata::kernels::argmax_rows_wanted"); return {}; } } +namespace strata::kernels { void bf16_gemv(const uint16_t * p0, const uint16_t * p1, float * p2, int64_t p3, int64_t p4, void * p5) { strata::metal_engine::missing("strata::kernels::bf16_gemv"); } } +namespace strata::kernels { void bf16_gemv_fp32_mmvf(const float * p0, const uint16_t * p1, float * p2, int64_t p3, int64_t p4, void * p5) { strata::metal_engine::missing("strata::kernels::bf16_gemv_fp32_mmvf"); } } +namespace strata::kernels { void bf16_gemv_fp32_mmvf_cols(const float * p0, const uint16_t * p1, float * p2, int64_t p3, int64_t p4, int p5, void * p6) { strata::metal_engine::missing("strata::kernels::bf16_gemv_fp32_mmvf_cols"); } } +namespace strata::kernels { void bf16_gemv_fp32_mmvf_multi(const float * p0, int64_t p1, const uint16_t * p2, float * p3, int64_t p4, int64_t p5, int64_t p6, int p7, void * p8) { strata::metal_engine::missing("strata::kernels::bf16_gemv_fp32_mmvf_multi"); } } +namespace strata::kernels { bool bf16_gemv_fp32_mmvf_multi_aux(const float * p0, int64_t p1, const uint16_t * p2, float * p3, int64_t p4, int64_t p5, int64_t p6, int p7, const uint16_t * p8, float * p9, int64_t p10, void * p11) { strata::metal_engine::missing("strata::kernels::bf16_gemv_fp32_mmvf_multi_aux"); return {}; } } +namespace strata::kernels { void bf16_gemv_split(const uint16_t * p0, const uint16_t * p1, float * p2, int64_t p3, int64_t p4, int p5, void * p6) { strata::metal_engine::missing("strata::kernels::bf16_gemv_split"); } } +namespace strata::kernels { void broadcast_streams(const float * p0, float * p1, int64_t p2, int p3, int p4, void * p5) { strata::metal_engine::missing("strata::kernels::broadcast_streams"); } } +namespace strata::kernels { void copy_from_mapped(float * p0, const float * p1, int64_t p2, void * p3) { strata::metal_engine::missing("strata::kernels::copy_from_mapped"); } } +namespace strata::kernels { void copy_from_mapped_multi(const MappedCopy * p0, int p1, void * p2) { strata::metal_engine::missing("strata::kernels::copy_from_mapped_multi"); } } +namespace strata::kernels { void copy_i32_from_mapped(int32_t * p0, const int32_t * p1, int64_t p2, void * p3) { strata::metal_engine::missing("strata::kernels::copy_i32_from_mapped"); } } +namespace strata::kernels { void copy_i32_from_mapped_unless(int32_t * p0, const int32_t * p1, long long p2, const uint32_t * p3, uint32_t p4, void * p5) { strata::metal_engine::missing("strata::kernels::copy_i32_from_mapped_unless"); } } +namespace strata::kernels { void copy_indexed(float * p0, const float * p1, int64_t p2, const int32_t * p3, int64_t p4, void * p5) { strata::metal_engine::missing("strata::kernels::copy_indexed"); } } +namespace strata::kernels { void copy_or_zero_from_mapped(float * p0, const float * p1, long long p2, const uint32_t * p3, uint32_t p4, void * p5) { strata::metal_engine::missing("strata::kernels::copy_or_zero_from_mapped"); } } +namespace strata::kernels { void copy_row_to_first(const int32_t * p0, float * p1, int64_t p2, float * p3, int64_t p4, float * p5, int64_t p6, void * p7) { strata::metal_engine::missing("strata::kernels::copy_row_to_first"); } } +namespace strata::kernels { void copy_rows_from_mapped(float * p0, const float * p1, int64_t p2, int64_t p3, const int32_t * p4, const int32_t * p5, void * p6) { strata::metal_engine::missing("strata::kernels::copy_rows_from_mapped"); } } +namespace strata::kernels { void copy_rows_strided(float * p0, const float * p1, int64_t p2, int64_t p3, int64_t p4, void * p5) { strata::metal_engine::missing("strata::kernels::copy_rows_strided"); } } +namespace strata::kernels { void coupled_draft_sample(float * p0, int p1, const int32_t * p2, const int32_t * p3, int p4, const SamplerParams * p5, int32_t * p6, int p7, int p8, const int32_t * p9, void * p10, int32_t * p11, float * p12, void * p13) { strata::metal_engine::missing("strata::kernels::coupled_draft_sample"); } } +namespace strata::kernels { size_t coupled_draft_scratch_bytes(int p0) { strata::metal_engine::missing("strata::kernels::coupled_draft_scratch_bytes"); return {}; } } +namespace strata::kernels { void coupled_draft_stage(const SamplerParams * p0, const int32_t * p1, SamplerParams * p2, int32_t * p3, int p4, void * p5) { strata::metal_engine::missing("strata::kernels::coupled_draft_stage"); } } +namespace strata::kernels::cpu { void act_quant_q8_1(const float * p0, int p1, ActQ & p2) { strata::metal_engine::missing("strata::kernels::cpu::act_quant_q8_1"); } } +namespace strata::kernels::cpu { void act_quant_q8_1_avx1(const float * p0, int p1, ActQ & p2) { strata::metal_engine::missing("strata::kernels::cpu::act_quant_q8_1_avx1"); } } +namespace strata::kernels::cpu { void act_quant_q8_1_avx2(const float * p0, int p1, ActQ & p2) { strata::metal_engine::missing("strata::kernels::cpu::act_quant_q8_1_avx2"); } } +namespace strata::kernels::cpu { void bf16_rows_dot_multi(const uint16_t * p0, int p1, int p2, const float * p3, int p4, float * p5) { strata::metal_engine::missing("strata::kernels::cpu::bf16_rows_dot_multi"); } } +namespace strata::kernels::cpu { void bf16_rows_dot_multi_avx1(const uint16_t * p0, int p1, int p2, const float * p3, int p4, float * p5) { strata::metal_engine::missing("strata::kernels::cpu::bf16_rows_dot_multi_avx1"); } } +namespace strata::kernels::cpu { void iq128_down_rows(int p0, const uint8_t * p1, size_t p2, int p3, const void *const * p4, int p5, float *const * p6, int p7, int p8) { strata::metal_engine::missing("strata::kernels::cpu::iq128_down_rows"); } } +namespace strata::kernels::cpu { bool iq128_down_supported(int p0) noexcept { strata::metal_engine::missing("strata::kernels::cpu::iq128_down_supported"); return {}; } } +namespace strata::kernels::cpu { void iq128_gu_rows(int p0, const uint8_t * p1, size_t p2, size_t p3, int p4, const void *const * p5, int p6, float *const * p7, int p8, int p9) { strata::metal_engine::missing("strata::kernels::cpu::iq128_gu_rows"); } } +namespace strata::kernels::cpu { bool iq128_supported(int p0) noexcept { strata::metal_engine::missing("strata::kernels::cpu::iq128_supported"); return {}; } } +namespace strata::kernels::cpu { void iq256_gu_rows(int p0, const uint8_t * p1, size_t p2, size_t p3, int p4, const void *const * p5, int p6, float *const * p7, int p8, int p9) { strata::metal_engine::missing("strata::kernels::cpu::iq256_gu_rows"); } } +namespace strata::kernels::cpu { void iq4nl256_down_rows(const uint8_t * p0, size_t p1, int p2, const void *const * p3, int p4, float *const * p5, int p6, int p7) { strata::metal_engine::missing("strata::kernels::cpu::iq4nl256_down_rows"); } } +namespace strata::kernels::cpu { void iq512_gu_rows(int p0, const uint8_t * p1, size_t p2, size_t p3, int p4, const void *const * p5, int p6, float *const * p7, int p8, int p9) { strata::metal_engine::missing("strata::kernels::cpu::iq512_gu_rows"); } } +namespace strata::kernels::cpu { void kq256_gu_rows(int p0, const uint8_t * p1, size_t p2, size_t p3, int p4, const void *const * p5, int p6, float *const * p7, int p8, int p9) { strata::metal_engine::missing("strata::kernels::cpu::kq256_gu_rows"); } } +namespace strata::kernels::cpu { void kq256_rows(int p0, const uint8_t * p1, size_t p2, int p3, const void *const * p4, int p5, float *const * p6, int p7, int p8) { strata::metal_engine::missing("strata::kernels::cpu::kq256_rows"); } } +namespace strata::kernels::cpu { void q2_0_gguf_rows_multi(const uint8_t * p0, size_t p1, int p2, const ActQ *const * p3, int p4, float *const * p5, int p6, int p7) { strata::metal_engine::missing("strata::kernels::cpu::q2_0_gguf_rows_multi"); } } +namespace strata::kernels::cpu { void q2_0_gguf_rows_multi_avx1(const uint8_t * p0, size_t p1, int p2, const ActQ *const * p3, int p4, float *const * p5, int p6, int p7) { strata::metal_engine::missing("strata::kernels::cpu::q2_0_gguf_rows_multi_avx1"); } } +namespace strata::kernels::cpu { void q2_0_gguf_rows_multi_avx1_legacy(const uint8_t * p0, size_t p1, int p2, const ActQ *const * p3, int p4, float *const * p5, int p6, int p7) { strata::metal_engine::missing("strata::kernels::cpu::q2_0_gguf_rows_multi_avx1_legacy"); } } +namespace strata::kernels::cpu { void q2_0_gguf_rows_multi_avx2(const uint8_t * p0, size_t p1, int p2, const ActQ *const * p3, int p4, float *const * p5, int p6, int p7) { strata::metal_engine::missing("strata::kernels::cpu::q2_0_gguf_rows_multi_avx2"); } } +namespace strata::kernels::cpu { void q2_0_gguf_rows_multi_avx2_legacy(const uint8_t * p0, size_t p1, int p2, const ActQ *const * p3, int p4, float *const * p5, int p6, int p7) { strata::metal_engine::missing("strata::kernels::cpu::q2_0_gguf_rows_multi_avx2_legacy"); } } +namespace strata::kernels::cpu { void q8k_quant_avx1(const float * p0, void * p1, int64_t p2) { strata::metal_engine::missing("strata::kernels::cpu::q8k_quant_avx1"); } } +namespace strata::kernels::cpu { void q8k_quant_avx2(const float * p0, void * p1, int64_t p2) { strata::metal_engine::missing("strata::kernels::cpu::q8k_quant_avx2"); } } +namespace strata::kernels::cpu { void s2_expert_down_rows(const uint8_t * p0, const ActQ & p1, float * p2, int p3, int p4) { strata::metal_engine::missing("strata::kernels::cpu::s2_expert_down_rows"); } } +namespace strata::kernels::cpu { void s2_expert_down_rows_multi(const uint8_t * p0, const ActQ *const * p1, int p2, float *const * p3, int p4, int p5) { strata::metal_engine::missing("strata::kernels::cpu::s2_expert_down_rows_multi"); } } +namespace strata::kernels::cpu { void s2_expert_gu_rows(const uint8_t * p0, const ActQ & p1, float * p2, int p3, int p4) { strata::metal_engine::missing("strata::kernels::cpu::s2_expert_gu_rows"); } } +namespace strata::kernels::cpu { void s2_expert_gu_rows_multi(const uint8_t * p0, const ActQ *const * p1, int p2, float *const * p3, int p4, int p5) { strata::metal_engine::missing("strata::kernels::cpu::s2_expert_gu_rows_multi"); } } +namespace strata::kernels::cpu { void s2_expert_vnni_q(const uint8_t * p0, const ActQ & p1, float * p2, ExpertScratch & p3) { strata::metal_engine::missing("strata::kernels::cpu::s2_expert_vnni_q"); } } +namespace strata::kernels { void cvec_apply(float * p0, int64_t p1, int64_t p2, int64_t p3, const float * p4, int64_t p5, const float * p6, int64_t p7, bool p8, void * p9) { strata::metal_engine::missing("strata::kernels::cvec_apply"); } } +namespace strata::kernels { bool cvec_replicate(std::string & p0) { strata::metal_engine::missing("strata::kernels::cvec_replicate"); return {}; } } +namespace strata::kernels { void cvec_set_enabled(bool p0) { strata::metal_engine::missing("strata::kernels::cvec_set_enabled"); } } +namespace strata::kernels { bool cvec_tables(const float ** p0, const float ** p1, const int ** p2) { strata::metal_engine::missing("strata::kernels::cvec_tables"); return {}; } } +namespace strata::kernels { bool cvec_upload(const std::vector & p0, const std::vector & p1, int p2, int p3, int p4, int64_t p5, int64_t p6, std::string & p7) { strata::metal_engine::missing("strata::kernels::cvec_upload"); return {}; } } +namespace strata::kernels { void doorbell_publish(const float * p0, const int32_t * p1, const float * p2, int64_t p3, int64_t p4, float * p5, int32_t * p6, float * p7, uint32_t * p8, void * p9) { strata::metal_engine::missing("strata::kernels::doorbell_publish"); } } +namespace strata::kernels { void doorbell_publish_res(const float * p0, const int32_t * p1, const int32_t * p2, int p3, int64_t p4, int64_t p5, float * p6, int32_t * p7, uint32_t * p8, void * p9) { strata::metal_engine::missing("strata::kernels::doorbell_publish_res"); } } +namespace strata::kernels { void doorbell_ring(uint32_t * p0, void * p1) { strata::metal_engine::missing("strata::kernels::doorbell_ring"); } } +namespace strata::kernels { void doorbell_wait(const uint32_t * p0, const uint32_t * p1, void * p2) { strata::metal_engine::missing("strata::kernels::doorbell_wait"); } } +namespace strata::kernels { void embedding_gather(const uint8_t * p0, const float * p1, const float * p2, int64_t p3, int p4, int p5, int p6, float * p7, void * p8) { strata::metal_engine::missing("strata::kernels::embedding_gather"); } } +namespace strata::kernels { void embedding_gather_dev(const uint8_t * p0, const float * p1, const float * p2, const int32_t * p3, int p4, int64_t p5, int p6, int p7, int p8, uint64_t p9, uint64_t p10, float * p11, void * p12) { strata::metal_engine::missing("strata::kernels::embedding_gather_dev"); } } +namespace strata::kernels { void f32_to_bf16_bulk(const float * p0, uint16_t * p1, int64_t p2, void * p3) { strata::metal_engine::missing("strata::kernels::f32_to_bf16_bulk"); } } +namespace strata::kernels { void fetch_blobs(const unsigned long long * p0, const int32_t * p1, uint8_t * p2, int64_t p3, int p4, void * p5) { strata::metal_engine::missing("strata::kernels::fetch_blobs"); } } +namespace strata::kernels { void force_token(int32_t * p0, const int32_t * p1, int p2, void * p3) { strata::metal_engine::missing("strata::kernels::force_token"); } } +namespace strata::kernels { void fused_gdn_ab(const float * p0, const uint16_t * p1, const uint16_t * p2, const float * p3, const float * p4, float * p5, float * p6, int p7, int p8, void * p9) { strata::metal_engine::missing("strata::kernels::fused_gdn_ab"); } } +namespace strata::kernels { void fused_gdn_conv_l2(float * p0, const float * p1, const float * p2, float * p3, int p4, int p5, float p6, void * p7) { strata::metal_engine::missing("strata::kernels::fused_gdn_conv_l2"); } } +namespace strata::kernels { void fused_gdn_step_norm(float * p0, const float * p1, const float * p2, const float * p3, const float * p4, const float * p5, const float * p6, const float * p7, float p8, float * p9, int p10, int p11, void * p12) { strata::metal_engine::missing("strata::kernels::fused_gdn_step_norm"); } } +namespace strata::kernels { void fused_gr_dequant_q8_0(const uint8_t * p0, uint16_t * p1, int64_t p2, void * p3) { strata::metal_engine::missing("strata::kernels::fused_gr_dequant_q8_0"); } } +namespace strata::kernels { void fused_gr_quantize_q8_0(const uint16_t * p0, uint8_t * p1, int64_t p2, void * p3) { strata::metal_engine::missing("strata::kernels::fused_gr_quantize_q8_0"); } } +namespace strata::kernels { void fused_gr_read(const FusedGrArgs & p0, void * p1) { strata::metal_engine::missing("strata::kernels::fused_gr_read"); } } +namespace strata::kernels { bool fused_gr_read_multi(const FusedGrArgs * p0, int p1, float * p2, void * p3, unsigned long long * p4, int p5) { strata::metal_engine::missing("strata::kernels::fused_gr_read_multi"); return {}; } } +namespace strata::kernels { bool fused_gr_supported(int64_t p0, int64_t p1, int64_t p2) { strata::metal_engine::missing("strata::kernels::fused_gr_supported"); return {}; } } +namespace strata::kernels { void fwht256_cuda(const float * p0, float * p1, int64_t p2, void * p3) { strata::metal_engine::missing("strata::kernels::fwht256_cuda"); } } +namespace strata::kernels { void gdn_ab_multi(const float * p0, const uint16_t * p1, const uint16_t * p2, const float * p3, const float * p4, float * p5, float * p6, int p7, int p8, int p9, void * p10) { strata::metal_engine::missing("strata::kernels::gdn_ab_multi"); } } +namespace strata::kernels { void gdn_beta_gate(float * p0, int64_t p1, void * p2) { strata::metal_engine::missing("strata::kernels::gdn_beta_gate"); } } +namespace strata::kernels { void gdn_conv_commit(float * p0, const float * p1, int p2, const int32_t * p3, void * p4) { strata::metal_engine::missing("strata::kernels::gdn_conv_commit"); } } +namespace strata::kernels { void gdn_conv_l2_multi(const float * p0, const float * p1, const float * p2, float * p3, int p4, int p5, float p6, int p7, void * p8, int p9, bool p10) { strata::metal_engine::missing("strata::kernels::gdn_conv_l2_multi"); } } +namespace strata::kernels { void gdn_conv_step(float * p0, const float * p1, const float * p2, float * p3, int64_t p4, int64_t p5, void * p6) { strata::metal_engine::missing("strata::kernels::gdn_conv_step"); } } +namespace strata::kernels { void gdn_gate(const float * p0, const float * p1, const float * p2, float * p3, int64_t p4, int64_t p5, void * p6) { strata::metal_engine::missing("strata::kernels::gdn_gate"); } } +namespace strata::kernels { void gdn_l2_norm(float * p0, int64_t p1, int64_t p2, float p3, void * p4) { strata::metal_engine::missing("strata::kernels::gdn_l2_norm"); } } +namespace strata::kernels { void gdn_out_norm(const float * p0, const float * p1, const float * p2, float * p3, int64_t p4, int64_t p5, float p6, void * p7) { strata::metal_engine::missing("strata::kernels::gdn_out_norm"); } } +namespace strata::kernels { void gdn_step(float * p0, const float * p1, const float * p2, const float * p3, const float * p4, const float * p5, float * p6, const GdnShapes & p7, void * p8) { strata::metal_engine::missing("strata::kernels::gdn_step"); } } +namespace strata::kernels { void gdn_step_norm_multi(float * p0, const float * p1, int p2, const float * p3, const float * p4, const float * p5, const float * p6, float p7, float * p8, int p9, int p10, int p11, const int32_t * p12, void * p13, int p14, void * p15) { strata::metal_engine::missing("strata::kernels::gdn_step_norm_multi"); } } +namespace strata::kernels { void gpu_noop(void * p0) { strata::metal_engine::missing("strata::kernels::gpu_noop"); } } +namespace strata::kernels { void gpu_stamp(unsigned long long * p0, int p1, void * p2) { strata::metal_engine::missing("strata::kernels::gpu_stamp"); } } +namespace strata::kernels { void gr_read(const float * p0, const float * p1, const uint16_t * p2, const uint16_t * p3, const uint16_t * p4, float p5, const GrShapes & p6, const GrWorkspace & p7, float * p8, float * p9, void * p10) { strata::metal_engine::missing("strata::kernels::gr_read"); } } +namespace strata::kernels { void gr_write(const float * p0, const float * p1, const float * p2, const GrShapes & p3, float * p4, void * p5) { strata::metal_engine::missing("strata::kernels::gr_write"); } } +namespace strata::kernels { void gr_write_multi(const float * p0, const float * p1, const float * p2, const GrShapes & p3, float * p4, int p5, void * p6) { strata::metal_engine::missing("strata::kernels::gr_write_multi"); } } +namespace strata::kernels { void indexer_key_append(const float * p0, const int32_t * p1, int32_t p2, const float * p3, float p4, const QsaIndexerBuffers & p5, const QsaShapes & p6, const float * p7, const float * p8, void * p9) { strata::metal_engine::missing("strata::kernels::indexer_key_append"); } } +namespace strata::kernels { void iq_dequant_f16(int p0, const void * p1, int64_t p2, uint16_t * p3, void * p4) { strata::metal_engine::missing("strata::kernels::iq_dequant_f16"); } } +namespace strata::kernels { void iq_dequant_f32(int p0, const void * p1, int64_t p2, float * p3, void * p4) { strata::metal_engine::missing("strata::kernels::iq_dequant_f32"); } } +namespace strata::kernels { void iq_dequant_gu_f16(int p0, const void * p1, const void * p2, int64_t p3, int64_t p4, uint16_t * p5, void * p6) { strata::metal_engine::missing("strata::kernels::iq_dequant_gu_f16"); } } +namespace strata::kernels { void iq_embed_rows(int p0, const void * p1, size_t p2, const int32_t * p3, int64_t p4, int64_t p5, float * p6, void * p7) { strata::metal_engine::missing("strata::kernels::iq_embed_rows"); } } +namespace strata::kernels { void kv_append_q4(uint8_t * p0, uint8_t * p1, const int32_t * p2, int64_t p3, int64_t p4, const float * p5, const float * p6, const QsaShapes & p7, void * p8, const KvHostPools * p9, const KvHostPools * p10) { strata::metal_engine::missing("strata::kernels::kv_append_q4"); } } +namespace strata::kernels { void kv_append_q4_step(uint8_t * p0, uint8_t * p1, const int32_t * p2, const int32_t * p3, const float * p4, const float * p5, const QsaShapes & p6, void * p7, const KvHostPools * p8) { strata::metal_engine::missing("strata::kernels::kv_append_q4_step"); } } +namespace strata::kernels { void kv_append_q4_steps(uint8_t * p0, uint8_t * p1, const int32_t * p2, const int32_t * p3, int p4, int p5, const float * p6, const float * p7, const QsaShapes & p8, void * p9, const KvHostPools * p10) { strata::metal_engine::missing("strata::kernels::kv_append_q4_steps"); } } +namespace strata::kernels { void kv_append_q8_step(int8_t * p0, int8_t * p1, uint16_t * p2, uint16_t * p3, const int32_t * p4, const int32_t * p5, const float * p6, const float * p7, const QsaShapes & p8, void * p9, const KvHostPools * p10) { strata::metal_engine::missing("strata::kernels::kv_append_q8_step"); } } +namespace strata::kernels { void kv_append_q8_steps(int8_t * p0, int8_t * p1, uint16_t * p2, uint16_t * p3, const int32_t * p4, const int32_t * p5, int p6, const float * p7, const float * p8, int p9, int p10, const QsaShapes & p11, void * p12, const KvHostPools * p13) { strata::metal_engine::missing("strata::kernels::kv_append_q8_steps"); } } +namespace strata::kernels { void kv_append_step(uint16_t * p0, uint16_t * p1, const int32_t * p2, const int32_t * p3, const float * p4, const float * p5, const QsaShapes & p6, void * p7, const KvHostPools * p8) { strata::metal_engine::missing("strata::kernels::kv_append_step"); } } +namespace strata::kernels { uint64_t kv_block_bytes(const QsaShapes & p0, int p1) { strata::metal_engine::missing("strata::kernels::kv_block_bytes"); return {}; } } +namespace strata::kernels { void kv_gather_q4_step(const uint8_t * p0, const uint8_t * p1, const int32_t * p2, const int32_t * p3, const int32_t * p4, int64_t p5, const QsaShapes & p6, uint16_t * p7, uint16_t * p8, void * p9) { strata::metal_engine::missing("strata::kernels::kv_gather_q4_step"); } } +namespace strata::kernels { void kv_gather_q8_step(const int8_t * p0, const int8_t * p1, const uint16_t * p2, const uint16_t * p3, const int32_t * p4, const int32_t * p5, const int32_t * p6, int64_t p7, const QsaShapes & p8, uint16_t * p9, uint16_t * p10, void * p11) { strata::metal_engine::missing("strata::kernels::kv_gather_q8_step"); } } +namespace strata::kernels { void kv_gather_step(const uint16_t * p0, const uint16_t * p1, const int32_t * p2, const int32_t * p3, const int32_t * p4, int64_t p5, const QsaShapes & p6, uint16_t * p7, uint16_t * p8, void * p9) { strata::metal_engine::missing("strata::kernels::kv_gather_step"); } } +namespace strata::kernels { void kv_ring_restore(const QsaAttnPools & p0, const KvHostPools & p1, int p2, int64_t p3, int64_t p4, int64_t p5, const QsaShapes & p6, void * p7) { strata::metal_engine::missing("strata::kernels::kv_ring_restore"); } } +namespace strata::kernels { void kv_ring_table(int32_t * p0, int64_t p1, int64_t p2, void * p3) { strata::metal_engine::missing("strata::kernels::kv_ring_table"); } } +namespace strata::kernels { void kv_stage_from_host(const QsaAttnPools & p0, const KvHostPools & p1, int p2, int64_t p3, const QsaShapes & p4, void * p5) { strata::metal_engine::missing("strata::kernels::kv_stage_from_host"); } } +namespace strata::kernels { KvStreamCounters kv_stream_counters(const KvStreamMap & p0) { strata::metal_engine::missing("strata::kernels::kv_stream_counters"); return {}; } } +namespace strata::kernels { void kv_stream_reset(const KvStreamMap & p0, void * p1) { strata::metal_engine::missing("strata::kernels::kv_stream_reset"); } } +namespace strata::kernels { void kv_stream_resolve(const KvStreamMap & p0, const QsaAttnPools & p1, const KvHostPools & p2, int p3, const int32_t * p4, const int32_t * p5, int64_t p6, int64_t p7, const QsaShapes & p8, void * p9) { strata::metal_engine::missing("strata::kernels::kv_stream_resolve"); } } +namespace strata::kernels { void logits_nonfinite_rows(const float * p0, int p1, int p2, uint32_t * p3, void * p4) { strata::metal_engine::missing("strata::kernels::logits_nonfinite_rows"); } } +namespace strata::kernels { void map_ids(int32_t * p0, const int32_t * p1, int p2, void * p3) { strata::metal_engine::missing("strata::kernels::map_ids"); } } +namespace strata::kernels { void moe_combine(const float * p0, const float * p1, const float * p2, float * p3, int64_t p4, int64_t p5, void * p6) { strata::metal_engine::missing("strata::kernels::moe_combine"); } } +namespace strata::kernels { void moe_group_resident(const int32_t * p0, int p1, int p2, const uint8_t * p3, int64_t p4, unsigned long long * p5, int32_t * p6, int32_t * p7, int32_t * p8, int32_t * p9, void * p10) { strata::metal_engine::missing("strata::kernels::moe_group_resident"); } } +namespace strata::kernels { void moe_grouped_s2(const unsigned long long * p0, const int32_t * p1, const int32_t * p2, const int32_t * p3, const int32_t * p4, int64_t p5, int64_t p6, const uint8_t * p7, const float * p8, void * p9, float * p10, void * p11) { strata::metal_engine::missing("strata::kernels::moe_grouped_s2"); } } +namespace strata::kernels { void moe_hit_add(float * p0, const float * p1, const int32_t * p2, const int32_t * p3, int64_t p4, int64_t p5, void * p6) { strata::metal_engine::missing("strata::kernels::moe_hit_add"); } } +namespace strata::kernels { void moe_hit_grouped_s2(const uint8_t * p0, const int32_t * p1, const int32_t * p2, int64_t p3, int64_t p4, const uint8_t * p5, void * p6, float * p7, void * p8, const float * p9) { strata::metal_engine::missing("strata::kernels::moe_hit_grouped_s2"); } } +namespace strata::kernels { void moe_hit_grouped_s2_cpu_order(const uint8_t * p0, const int32_t * p1, const int32_t * p2, int64_t p3, int64_t p4, const uint8_t * p5, void * p6, float * p7, void * p8, const float * p9, float * p10) { strata::metal_engine::missing("strata::kernels::moe_hit_grouped_s2_cpu_order"); } } +namespace strata::kernels { void moe_hit_grouped_s2_dev(const uint8_t * p0, const int32_t * p1, const int32_t * p2, const int32_t * p3, int64_t p4, int64_t p5, const uint8_t * p6, void * p7, float * p8, void * p9, const float * p10) { strata::metal_engine::missing("strata::kernels::moe_hit_grouped_s2_dev"); } } +namespace strata::kernels { void moe_hit_select(const int32_t * p0, const int32_t * p1, int p2, int p3, int32_t * p4, int32_t * p5, int32_t * p6, void * p7) { strata::metal_engine::missing("strata::kernels::moe_hit_select"); } } +namespace strata::kernels { void mtp_select(const float * p0, int64_t p1, const int32_t * p2, const int32_t * p3, float * p4, int32_t * p5, int32_t * p6, int p7, void * p8, const float * p9, float * p10) { strata::metal_engine::missing("strata::kernels::mtp_select"); } } +namespace strata::kernels { bool multi_block_head_ops() { strata::metal_engine::missing("strata::kernels::multi_block_head_ops"); return {}; } } +namespace strata::kernels { void native_expert_grouped(const NativeExpertLayout & p0, const unsigned long long * p1, const int32_t * p2, const int32_t * p3, const int32_t * p4, const int32_t * p5, int64_t p6, int64_t p7, const void * p8, void * p9, float * p10, void * p11, int64_t p12) { strata::metal_engine::missing("strata::kernels::native_expert_grouped"); } } +namespace strata::kernels { void native_flash_attn_short_step(const float * p0, const uint16_t * p1, const uint16_t * p2, const int32_t * p3, int64_t p4, int p5, const QsaShapes & p6, float * p7, int32_t * p8, const uint16_t * p9, void * p10) { strata::metal_engine::missing("strata::kernels::native_flash_attn_short_step"); } } +namespace strata::kernels { void native_gdn_beta_gate(float * p0, int64_t p1, void * p2) { strata::metal_engine::missing("strata::kernels::native_gdn_beta_gate"); } } +namespace strata::kernels { void native_gdn_conv_silu(float * p0, const float * p1, const float * p2, float * p3, float * p4, int64_t p5, int64_t p6, void * p7) { strata::metal_engine::missing("strata::kernels::native_gdn_conv_silu"); } } +namespace strata::kernels { void native_gdn_gate(const float * p0, const float * p1, const float * p2, float * p3, int64_t p4, void * p5) { strata::metal_engine::missing("strata::kernels::native_gdn_gate"); } } +namespace strata::kernels { void native_gdn_l2_norm(float * p0, int64_t p1, int64_t p2, float p3, void * p4) { strata::metal_engine::missing("strata::kernels::native_gdn_l2_norm"); } } +namespace strata::kernels { void native_gdn_out_norm(const float * p0, const float * p1, const float * p2, float * p3, int64_t p4, int64_t p5, float p6, void * p7) { strata::metal_engine::missing("strata::kernels::native_gdn_out_norm"); } } +namespace strata::kernels { void native_gdn_step(float * p0, const float * p1, const float * p2, const float * p3, const float * p4, const float * p5, float * p6, const GdnShapes & p7, void * p8) { strata::metal_engine::missing("strata::kernels::native_gdn_step"); } } +namespace strata::kernels { void native_gr_post_multi(const float * p0, const float * p1, const float * p2, float * p3, int p4, int p5, int p6, long long p7, long long p8, long long p9, void * p10) { strata::metal_engine::missing("strata::kernels::native_gr_post_multi"); } } +namespace strata::kernels { void native_mmvq(int p0, const void * p1, const void * p2, float * p3, int p4, int p5, int p6, void * p7) { strata::metal_engine::missing("strata::kernels::native_mmvq"); } } +namespace strata::kernels { void native_mmvq_il(int p0, const void * p1, const void * p2, const void * p3, float * p4, int p5, int p6, int p7, void * p8) { strata::metal_engine::missing("strata::kernels::native_mmvq_il"); } } +namespace strata::kernels { void native_moe_combine(const float * p0, const float * p1, const float * p2, float * p3, int64_t p4, int64_t p5, void * p6) { strata::metal_engine::missing("strata::kernels::native_moe_combine"); } } +namespace strata::kernels { void native_moe_combine_multi(const float * p0, const float * p1, const float * p2, float * p3, int64_t p4, int64_t p5, int p6, void * p7) { strata::metal_engine::missing("strata::kernels::native_moe_combine_multi"); } } +namespace strata::kernels { void native_moe_combine_multi_hits_gated(const float * p0, const float * p1, const float * p2, const float * p3, float * p4, int64_t p5, int64_t p6, int p7, void * p8) { strata::metal_engine::missing("strata::kernels::native_moe_combine_multi_hits_gated"); } } +namespace strata::kernels { bool native_norm_rope_usable(int p0, int p1) { strata::metal_engine::missing("strata::kernels::native_norm_rope_usable"); return {}; } } +namespace strata::kernels { void native_ple_postops_batch(float * p0, float * p1, const float * p2, float * p3, const PleWeights & p4, float * p5, float * p6, float * p7, int p8, void * p9) { strata::metal_engine::missing("strata::kernels::native_ple_postops_batch"); } } +namespace strata::kernels { void native_ple_postops_batch_snap(float * p0, float * p1, const float * p2, float * p3, const PleWeights & p4, float * p5, float * p6, float * p7, int p8, float * p9, void * p10) { strata::metal_engine::missing("strata::kernels::native_ple_postops_batch_snap"); } } +namespace strata::kernels { void native_q5_k_f32(const void * p0, const float * p1, void * p2, float * p3, int p4, int p5, int p6, void * p7) { strata::metal_engine::missing("strata::kernels::native_q5_k_f32"); } } +namespace strata::kernels { bool native_q6_k_pack(const void * p0, int p1, int p2, const char * p3) { strata::metal_engine::missing("strata::kernels::native_q6_k_pack"); return {}; } } +namespace strata::kernels { void native_q8_0_pack_host(const void * p0, void * p1, int p2, int p3) { strata::metal_engine::missing("strata::kernels::native_q8_0_pack_host"); } } +namespace strata::kernels { void native_q8_0_packed_register(const void * p0, const void * p1, int p2, int p3) { strata::metal_engine::missing("strata::kernels::native_q8_0_packed_register"); } } +namespace strata::kernels { void native_q8_0_packed_unregister(const void * p0) { strata::metal_engine::missing("strata::kernels::native_q8_0_packed_unregister"); } } +namespace strata::kernels { void native_q8_1_interleave(const void * p0, void * p1, int p2, int p3, void * p4) { strata::metal_engine::missing("strata::kernels::native_q8_1_interleave"); } } +namespace strata::kernels { void native_qsa_gate_apply(const float * p0, const float * p1, float * p2, int p3, int p4, void * p5) { strata::metal_engine::missing("strata::kernels::native_qsa_gate_apply"); } } +namespace strata::kernels { void native_qsa_indexer_append(const float * p0, const int32_t * p1, int32_t p2, const float * p3, float p4, const QsaIndexerBuffers & p5, const QsaShapes & p6, int64_t p7, const RopeScaling & p8, void * p9) { strata::metal_engine::missing("strata::kernels::native_qsa_indexer_append"); } } +namespace strata::kernels { void native_qsa_indexer_append_batch(const float * p0, int64_t p1, int64_t p2, int32_t p3, const float * p4, float p5, const QsaIndexerBuffers & p6, const QsaShapes & p7, int64_t p8, const RopeScaling & p9, void * p10) { strata::metal_engine::missing("strata::kernels::native_qsa_indexer_append_batch"); } } +namespace strata::kernels { void native_qsa_indexer_append_steps(const float * p0, const int32_t * p1, int p2, int p3, int32_t p4, const float * p5, float p6, const QsaIndexerBuffers & p7, const QsaShapes & p8, int64_t p9, const RopeScaling & p10, void * p11) { strata::metal_engine::missing("strata::kernels::native_qsa_indexer_append_steps"); } } +namespace strata::kernels { void native_qsa_rms_norm_grouped(const float * p0, const float * p1, float * p2, int p3, int p4, int p5, float p6, void * p7) { strata::metal_engine::missing("strata::kernels::native_qsa_rms_norm_grouped"); } } +namespace strata::kernels { void native_qsa_rms_norm_rope(const float * p0, int p1, const float * p2, float * p3, int p4, int p5, int p6, float p7, const RopeScaling & p8, const int * p9, void * p10) { strata::metal_engine::missing("strata::kernels::native_qsa_rms_norm_rope"); } } +namespace strata::kernels { void native_qsa_rms_norm_weighted(const float * p0, const float * p1, float * p2, int p3, int p4, float p5, void * p6) { strata::metal_engine::missing("strata::kernels::native_qsa_rms_norm_weighted"); } } +namespace strata::kernels { void native_quantize_q8_1(const float * p0, void * p1, int p2, int p3, void * p4) { strata::metal_engine::missing("strata::kernels::native_quantize_q8_1"); } } +namespace strata::kernels { void native_rope_apply(const float * p0, float * p1, int p2, int p3, int p4, const RopeScaling & p5, const int * p6, void * p7) { strata::metal_engine::missing("strata::kernels::native_rope_apply"); } } +namespace strata::kernels { void native_route_resident(const float * p0, int32_t * p1, float * p2, const int32_t * p3, int p4, float p5, int p6, int p7, unsigned long long * p8, void * p9) { strata::metal_engine::missing("strata::kernels::native_route_resident"); } } +namespace strata::kernels { void native_router_top10(const float * p0, int32_t * p1, float * p2, void * p3) { strata::metal_engine::missing("strata::kernels::native_router_top10"); } } +namespace strata::kernels { void native_router_top10_multi(const float * p0, int32_t * p1, float * p2, int p3, void * p4) { strata::metal_engine::missing("strata::kernels::native_router_top10_multi"); } } +namespace strata::kernels { bool & pdl_scope() { strata::metal_engine::missing("strata::kernels::pdl_scope"); static std::remove_cv_t> s{}; return s; } } +namespace strata::kernels { bool pdl_supported() { strata::metal_engine::missing("strata::kernels::pdl_supported"); return {}; } } +namespace strata::kernels { void ple_block(const float * p0, const float * p1, const float * p2, const PleWeights & p3, PleOut & p4, void * p5, void * p6) { strata::metal_engine::missing("strata::kernels::ple_block"); } } +namespace strata::kernels { void ple_block_projected(const float * p0, const float * p1, const float * p2, const float * p3, const PleWeights & p4, PleOut & p5, void * p6, void * p7) { strata::metal_engine::missing("strata::kernels::ple_block_projected"); } } +namespace strata::kernels { void ple_history_advance(float * p0, const float * p1, void * p2) { strata::metal_engine::missing("strata::kernels::ple_history_advance"); } } +namespace strata::kernels { void qsa_attend_step(const float * p0, const uint16_t * p1, const uint16_t * p2, const int32_t * p3, int64_t p4, const QsaShapes & p5, float * p6, float * p7, void * p8) { strata::metal_engine::missing("strata::kernels::qsa_attend_step"); } } +namespace strata::kernels { void qsa_block_scores(const float * p0, const float * p1, const float * p2, const int32_t * p3, int64_t p4, int64_t p5, const QsaShapes & p6, float * p7, void * p8, int64_t p9) { strata::metal_engine::missing("strata::kernels::qsa_block_scores"); } } +namespace strata::kernels { bool qsa_block_scores_tc(const float * p0, const float * p1, const float * p2, const int32_t * p3, int64_t p4, int64_t p5, const QsaShapes & p6, float * p7, void * p8, int64_t p9) { strata::metal_engine::missing("strata::kernels::qsa_block_scores_tc"); return {}; } } +namespace strata::kernels { void qsa_block_topk(const float * p0, const int32_t * p1, int64_t p2, int64_t p3, int64_t p4, const QsaShapes & p5, int32_t * p6, void * p7, int64_t p8) { strata::metal_engine::missing("strata::kernels::qsa_block_topk"); } } +namespace strata::kernels { void qsa_decode_attn_batch(const float * p0, const QsaAttnPools & p1, const int32_t * p2, const int32_t * p3, int64_t p4, const QsaShapes & p5, float * p6, float * p7, int64_t p8, void * p9) { strata::metal_engine::missing("strata::kernels::qsa_decode_attn_batch"); } } +namespace strata::kernels { void qsa_decode_attn_step(const float * p0, const QsaAttnPools & p1, const int32_t * p2, const int32_t * p3, int64_t p4, const QsaShapes & p5, float * p6, float * p7, void * p8) { strata::metal_engine::missing("strata::kernels::qsa_decode_attn_step"); } } +namespace strata::kernels { void qsa_gate_apply_f32(const float * p0, const float * p1, const QsaShapes & p2, float * p3, void * p4) { strata::metal_engine::missing("strata::kernels::qsa_gate_apply_f32"); } } +namespace strata::kernels { void qsa_index_step(const float * p0, const float * p1, const float * p2, const QsaShapes & p3, const int32_t * p4, int64_t p5, float * p6, void * p7) { strata::metal_engine::missing("strata::kernels::qsa_index_step"); } } +namespace strata::kernels { bool qsa_prompt_attn_batch(const float * p0, const QsaAttnPools & p1, const int32_t * p2, const int32_t * p3, int64_t p4, const QsaShapes & p5, float * p6, int64_t p7, void * p8) { strata::metal_engine::missing("strata::kernels::qsa_prompt_attn_batch"); return {}; } } +namespace strata::kernels { void qsa_step_fill(int32_t * p0, int64_t p1, const QsaShapes & p2) { strata::metal_engine::missing("strata::kernels::qsa_step_fill"); } } +namespace strata::kernels { void quantize_q8_0(const float * p0, uint8_t * p1, int64_t p2, void * p3) { strata::metal_engine::missing("strata::kernels::quantize_q8_0"); } } +namespace strata::kernels { void quantize_q8_0_scaled(const float * p0, uint8_t * p1, float * p2, int64_t p3, void * p4) { strata::metal_engine::missing("strata::kernels::quantize_q8_0_scaled"); } } +namespace strata::kernels { void quantize_q8_1_rows(const float * p0, int64_t p1, int64_t p2, void * p3, void * p4) { strata::metal_engine::missing("strata::kernels::quantize_q8_1_rows"); } } +namespace strata::kernels { void quantize_q8_K(const float * p0, uint8_t * p1, int64_t p2, void * p3) { strata::metal_engine::missing("strata::kernels::quantize_q8_K"); } } +namespace strata::kernels { void rebase_ptrs(unsigned long long * p0, const int32_t * p1, uint8_t * p2, int64_t p3, void * p4) { strata::metal_engine::missing("strata::kernels::rebase_ptrs"); } } +namespace strata::kernels { void resident_plan(const int32_t * p0, int p1, int p2, const int32_t * p3, int p4, const uint8_t * p5, const unsigned long long * p6, long long p7, int32_t * p8, long long p9, uint32_t * p10, uint32_t p11, void * p12, uint32_t * p13) { strata::metal_engine::missing("strata::kernels::resident_plan"); } } +namespace strata::kernels { void rms_norm_weighted(float * p0, const float * p1, int64_t p2, int64_t p3, float p4, void * p5) { strata::metal_engine::missing("strata::kernels::rms_norm_weighted"); } } +namespace strata::kernels { void rope_neox_apply(const float * p0, float * p1, int64_t p2, int p3, int p4, const float * p5, const float * p6, const int * p7, void * p8) { strata::metal_engine::missing("strata::kernels::rope_neox_apply"); } } +namespace strata::kernels { void route_prior_top10(const float * p0, const int32_t * p1, float p2, int32_t * p3, float * p4, int p5, void * p6) { strata::metal_engine::missing("strata::kernels::route_prior_top10"); } } +namespace strata::kernels { void router_top10(const float * p0, int p1, int p2, int p3, int * p4, float * p5, void * p6) { strata::metal_engine::missing("strata::kernels::router_top10"); } } +namespace strata::kernels { void row_top_prob(const float * p0, int p1, int p2, const int32_t * p3, float * p4, void * p5) { strata::metal_engine::missing("strata::kernels::row_top_prob"); } } +namespace strata::kernels { void row_top_prob_split(const float * p0, int p1, int p2, const int32_t * p3, float * p4, void * p5, void * p6) { strata::metal_engine::missing("strata::kernels::row_top_prob_split"); } } +namespace strata::kernels { void s2_gemv_q8(const uint8_t * p0, const uint8_t * p1, const float * p2, float * p3, int64_t p4, int64_t p5, int p6, void * p7) { strata::metal_engine::missing("strata::kernels::s2_gemv_q8"); } } +namespace strata::kernels { void s_gemv_q8_0_split(const uint8_t * p0, const uint8_t * p1, const float * p2, const float * p3, float * p4, int64_t p5, int64_t p6, const SForm & p7, void * p8) { strata::metal_engine::missing("strata::kernels::s_gemv_q8_0_split"); } } +namespace strata::kernels { void s_gemv_q8k_split(const uint8_t * p0, const uint8_t * p1, const float * p2, const float * p3, float * p4, int64_t p5, int64_t p6, const SForm & p7, void * p8) { strata::metal_engine::missing("strata::kernels::s_gemv_q8k_split"); } } +namespace strata::kernels { void sample_tokens(const float * p0, int p1, int p2, const int * p3, int p4, const SamplerParams & p5, int * p6, void * p7) { strata::metal_engine::missing("strata::kernels::sample_tokens"); } } +namespace strata::kernels { void scale_inplace(float * p0, int64_t p1, float p2, void * p3) { strata::metal_engine::missing("strata::kernels::scale_inplace"); } } +namespace strata::kernels { void scatter_rows_f32(const float * p0, float * p1, const int32_t * p2, int64_t p3, int64_t p4, void * p5) { strata::metal_engine::missing("strata::kernels::scatter_rows_f32"); } } +namespace strata::kernels { void shared_expert(const uint8_t * p0, const uint8_t * p1, const uint16_t * p2, const SForm & p3, const uint8_t * p4, const float * p5, const float * p6, const SForm & p7, const uint8_t * p8, const float * p9, const float * p10, const SForm & p11, const uint8_t * p12, const float * p13, const float * p14, const uint16_t * p15, float * p16, float * p17, int64_t p18, int64_t p19, int p20, void * p21, const float * p22, const NativeSharedWeights * p23) { strata::metal_engine::missing("strata::kernels::shared_expert"); } } +namespace strata::kernels { void shared_expert_multi(int p0, const float * p1, const uint16_t * p2, const NativeSharedWeights & p3, const uint16_t * p4, float * p5, float * p6, float * p7, float * p8, int64_t p9, int64_t p10, void * p11, const void * p12, int p13) { strata::metal_engine::missing("strata::kernels::shared_expert_multi"); } } +namespace strata::kernels { void silu_inplace(float * p0, int64_t p1, void * p2) { strata::metal_engine::missing("strata::kernels::silu_inplace"); } } +namespace strata::kernels { void spec_draft_sample(float * p0, int p1, const int32_t * p2, const int32_t * p3, int p4, const SamplerParams * p5, int32_t * p6, int p7, int p8, const int32_t * p9, void * p10, int32_t * p11, float * p12, int32_t * p13, int p14, float p15, void * p16) { strata::metal_engine::missing("strata::kernels::spec_draft_sample"); } } +namespace strata::kernels { void topk_512_step(const float * p0, const QsaShapes & p1, int64_t p2, const int32_t * p3, int32_t * p4, void * p5) { strata::metal_engine::missing("strata::kernels::topk_512_step"); } } +namespace strata::kernels { void wait_flag_ge(const uint32_t * p0, uint32_t p1, void * p2) { strata::metal_engine::missing("strata::kernels::wait_flag_ge"); } } +namespace strata::kernels { void wait_flag_ge_or(const uint32_t * p0, uint32_t p1, const uint32_t * p2, void * p3) { strata::metal_engine::missing("strata::kernels::wait_flag_ge_or"); } } +namespace strata::kernels { void window_ids(int32_t * p0, int p1, int p2, int32_t * p3, int64_t p4, void * p5) { strata::metal_engine::missing("strata::kernels::window_ids"); } } +auto strata::prefill::Gemm::bf16(const uint16_t * p0, const uint16_t * p1, float * p2, int64_t p3, int64_t p4, int64_t p5, int64_t p6, float p7, int64_t p8) -> void { strata::metal_engine::missing("strata::prefill::Gemm::bf16"); } +auto strata::prefill::Gemm::bf16_hcd_exact(const uint16_t * p0, int64_t p1, const uint16_t * p2, float * p3, int64_t p4, int64_t p5, int64_t p6) -> bool { strata::metal_engine::missing("strata::prefill::Gemm::bf16_hcd_exact"); return {}; } +auto strata::prefill::Gemm::f16(const uint16_t * p0, const uint16_t * p1, float * p2, int64_t p3, int64_t p4, int64_t p5, int64_t p6, float p7) -> void { strata::metal_engine::missing("strata::prefill::Gemm::f16"); } +auto strata::prefill::Gemm::native(const uint16_t * p0, int p1, const void * p2, float * p3, int64_t p4, int64_t p5, int64_t p6, int64_t p7, float p8, int64_t p9) -> void { strata::metal_engine::missing("strata::prefill::Gemm::native"); } +auto strata::prefill::Gemm::rebind(uint16_t * p0, int64_t p1, void * p2, size_t p3) -> void { strata::metal_engine::missing("strata::prefill::Gemm::rebind"); } +namespace strata::prefill { void blob_dequant_f16(const uint8_t * p0, uint16_t * p1, uint16_t * p2, void * p3) { strata::metal_engine::missing("strata::prefill::blob_dequant_f16"); } } +namespace strata::prefill { void copy_f32_wide(float * p0, const float * p1, int64_t p2, void * p3) { strata::metal_engine::missing("strata::prefill::copy_f32_wide"); } } +namespace strata::prefill { void copy_i32(int32_t * p0, const int32_t * p1, int64_t p2, void * p3) { strata::metal_engine::missing("strata::prefill::copy_i32"); } } +namespace strata::prefill { void f16_to_f32_wide(float * p0, const uint16_t * p1, int64_t p2, void * p3) { strata::metal_engine::missing("strata::prefill::f16_to_f32_wide"); } } +namespace strata::prefill { void gate_attn(const float * p0, const float * p1, uint16_t * p2, int64_t p3, void * p4, int64_t p5) { strata::metal_engine::missing("strata::prefill::gate_attn"); } } +namespace strata::prefill { void gather_rows16(const uint16_t * p0, const int32_t * p1, uint16_t * p2, int64_t p3, int64_t p4, void * p5) { strata::metal_engine::missing("strata::prefill::gather_rows16"); } } +namespace strata::prefill { void gdn_conv(float * p0, const float * p1, const float * p2, float * p3, int64_t p4, float p5, void * p6) { strata::metal_engine::missing("strata::prefill::gdn_conv"); } } +namespace strata::prefill { void gdn_gates(const float * p0, const float * p1, const float * p2, float * p3, float * p4, int64_t p5, void * p6) { strata::metal_engine::missing("strata::prefill::gdn_gates"); } } +namespace strata::prefill { void gdn_recurrence(float * p0, const float * p1, const float * p2, const float * p3, const float * p4, const float * p5, float p6, float * p7, uint16_t * p8, int64_t p9, void * p10, int64_t p11) { strata::metal_engine::missing("strata::prefill::gdn_recurrence"); } } +namespace strata::prefill { void gr_broadcast(const float * p0, float * p1, int64_t p2, void * p3) { strata::metal_engine::missing("strata::prefill::gr_broadcast"); } } +namespace strata::prefill { void gr_mix(const float * p0, const float * p1, float * p2, uint16_t * p3, int64_t p4, void * p5, uint16_t * p6, uint16_t * p7) { strata::metal_engine::missing("strata::prefill::gr_mix"); } } +namespace strata::prefill { void gr_mix_r(const float * p0, const float * p1, const float * p2, const float * p3, float * p4, uint16_t * p5, int64_t p6, void * p7, uint16_t * p8, uint16_t * p9) { strata::metal_engine::missing("strata::prefill::gr_mix_r"); } } +namespace strata::prefill { void gr_norm(const float * p0, const float * p1, float p2, float * p3, uint16_t * p4, int64_t p5, void * p6, uint16_t * p7) { strata::metal_engine::missing("strata::prefill::gr_norm"); } } +namespace strata::prefill { void gr_norm_rs(const float * p0, const float * p1, float p2, float * p3, uint16_t * p4, int64_t p5, void * p6, uint16_t * p7, int64_t p8) { strata::metal_engine::missing("strata::prefill::gr_norm_rs"); } } +namespace strata::prefill { void gr_silu(const float * p0, uint16_t * p1, int64_t p2, void * p3, uint16_t * p4) { strata::metal_engine::missing("strata::prefill::gr_silu"); } } +namespace strata::prefill { bool gr_upmix(const uint16_t * p0, const uint16_t * p1, const float * p2, const float * p3, const float * p4, float * p5, uint16_t * p6, uint16_t * p7, int64_t p8, void * p9) { strata::metal_engine::missing("strata::prefill::gr_upmix"); return {}; } } +namespace strata::prefill { void gr_write(float * p0, const float * p1, const float * p2, int64_t p3, int64_t p4, void * p5) { strata::metal_engine::missing("strata::prefill::gr_write"); } } +namespace strata::prefill { void gr_write_cvec_norm_rs(float * p0, const float * p1, const float * p2, int64_t p3, const float * p4, const float * p5, const int * p6, int p7, const float * p8, float p9, float * p10, uint16_t * p11, int64_t p12, void * p13, uint16_t * p14, int64_t p15) { strata::metal_engine::missing("strata::prefill::gr_write_cvec_norm_rs"); } } +namespace strata::prefill { void gr_write_norm_rs(float * p0, const float * p1, const float * p2, int64_t p3, const float * p4, float p5, float * p6, uint16_t * p7, int64_t p8, void * p9, uint16_t * p10, int64_t p11) { strata::metal_engine::missing("strata::prefill::gr_write_norm_rs"); } } +namespace strata::prefill { void kv_append(const float * p0, const float * p1, int64_t p2, int64_t p3, const int32_t * p4, int64_t p5, uint16_t * p6, uint16_t * p7, int8_t * p8, int8_t * p9, uint16_t * p10, uint16_t * p11, void * p12, const strata::kernels::KvHostPools * p13, const strata::kernels::KvHostPools * p14) { strata::metal_engine::missing("strata::prefill::kv_append"); } } +namespace strata::prefill { void moe_combine(const float * p0, const int32_t * p1, const float * p2, const float * p3, const float * p4, float * p5, int64_t p6, void * p7) { strata::metal_engine::missing("strata::prefill::moe_combine"); } } +namespace strata::prefill { void moe_combine_peer(const float * p0, const int32_t * p1, const float * p2, const float * p3, const float * p4, const float * p5, int64_t p6, float * p7, int64_t p8, void * p9) { strata::metal_engine::missing("strata::prefill::moe_combine_peer"); } } +namespace strata::prefill { void moe_combine_peer16(const float * p0, const int32_t * p1, const float * p2, const float * p3, const float * p4, const uint16_t * p5, int64_t p6, float * p7, int64_t p8, void * p9) { strata::metal_engine::missing("strata::prefill::moe_combine_peer16"); } } +namespace strata::prefill { void peer_gather_add(float * p0, const float * p1, int64_t p2, const float * p3, const int32_t * p4, const int32_t * p5, const int32_t * p6, const int32_t * p7, int64_t p8, void * p9) { strata::metal_engine::missing("strata::prefill::peer_gather_add"); } } +namespace strata::prefill { void peer_scatter_add(float * p0, const float * p1, const float * p2, const int32_t * p3, int64_t p4, void * p5) { strata::metal_engine::missing("strata::prefill::peer_scatter_add"); } } +namespace strata::prefill { void rms_rows(float * p0, const float * p1, int64_t p2, int64_t p3, int64_t p4, float p5, void * p6) { strata::metal_engine::missing("strata::prefill::rms_rows"); } } +namespace strata::prefill { void rope(float * p0, int64_t p1, int64_t p2, int64_t p3, int64_t p4, int64_t p5, const strata::kernels::RopeScaling & p6, void * p7) { strata::metal_engine::missing("strata::prefill::rope"); } } +namespace strata::prefill { void round_f16(const float * p0, float * p1, int64_t p2, void * p3) { strata::metal_engine::missing("strata::prefill::round_f16"); } } +namespace strata::prefill { void route(const float * p0, int32_t * p1, float * p2, int64_t p3, int64_t p4, void * p5) { strata::metal_engine::missing("strata::prefill::route"); } } +namespace strata::prefill { void split_q(const float * p0, float * p1, int64_t p2, void * p3) { strata::metal_engine::missing("strata::prefill::split_q"); } } +namespace strata::prefill { void sums_to_f16(const float * p0, uint16_t * p1, int64_t p2, void * p3) { strata::metal_engine::missing("strata::prefill::sums_to_f16"); } } +namespace strata::prefill { void swiglu_interleaved(const float * p0, uint16_t * p1, int64_t p2, void * p3) { strata::metal_engine::missing("strata::prefill::swiglu_interleaved"); } } +namespace strata::prefill { void swiglu_pair(const float * p0, const float * p1, uint16_t * p2, int64_t p3, void * p4) { strata::metal_engine::missing("strata::prefill::swiglu_pair"); } } +namespace strata::prefill { void to_bf16(const float * p0, uint16_t * p1, int64_t p2, void * p3, uint16_t * p4) { strata::metal_engine::missing("strata::prefill::to_bf16"); } } +namespace strata::prefill { void to_f16(const float * p0, uint16_t * p1, int64_t p2, void * p3) { strata::metal_engine::missing("strata::prefill::to_f16"); } } diff --git a/metal/src/engine/window.cpp b/metal/src/engine/window.cpp new file mode 100644 index 00000000..c9654b9c --- /dev/null +++ b/metal/src/engine/window.cpp @@ -0,0 +1,2541 @@ +// metal/src/engine/window.cpp - the decode window on Metal: Verifier::init/run/commit's Metal side (the one backend +// hook, src/core/verify.cpp under STRATA_GPU_METAL). Everything above it - the decode loop, MTP control, the serve +// protocol, the PLE table reads, the file tier - is the shared host code. +// +// The window is mac-kern's chain (metal/kernels, tests/token_chain.cpp) on the model GGUF itself: shard 1 is mmapped +// and wrapped no-copy as one MTLBuffer, every weight is read where it lies (unified memory: no upload, no expert +// cache), and one window is encoded as a dependency graph in one command buffer. Its own state lives here (the GDN +// recurrence and conv history, the int8 K/V and the indexer per QSA layer, the PLE history): the engine's +// SessionState buffers are not used by it, except the PLE token window (ss.ple_prev) and table. +// +// First version (MAC-PLAN Phase 3 start): windows of one token (no MTP drafts yet: --mtp-max-t 1), greedy. The PLE +// block's projections run on the GPU; its norms, gate and conv (10240 values) on the CPU between two command buffers +// (layer 0 | layers 1..47 + head). +#include "gguf_lite.h" +#include "mtl_rt.h" +#include "ref_quant.h" +#include "arena_budget.h" +#include "stream.h" +#include "../../tests/coop_probe.h" + +#include "strata/core/layer.hpp" +#include "strata/core/conversation_cache.hpp" +#include "strata/core/session.hpp" +#include "strata/kernels/ngram.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::gpu { uint64_t purge_device_allocations(size_t min_bytes); } // metal/src/gpu/runtime.cpp + +namespace strata::metal_engine { + +namespace { + +constexpr int N = 2560, HC = 4, LR = 320, NFF = 640, TOPK = 10, NEXP = 512, MAXT = 8, NVOCAB_MAX = 248320; +constexpr int P_MAXE = 128, P_GEXP = 16, P_GSTART = P_GEXP + P_MAXE, P_ETOK = P_GSTART + P_MAXE + 4, + P_EW = P_ETOK + P_MAXE, P_TOKENT = P_EW + P_MAXE, P_INTS = P_TOKENT + P_MAXE, P_IGU = 4, P_IDN = 8; +struct GemvArgs { uint32_t n_in, n_out, n_tok, row_bytes, x_stride, y_stride; }; +struct GrArgs { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; }; +struct MoeArgs { + uint64_t gate_off, up_off, down_off, gu_stride, d_stride; + uint32_t gu_row, d_row, n_embd, n_ff, n_tok, topk, n_expert, gx_gu, gx_dn, pad; +}; +struct GdnArgs { uint32_t h_k, h_v, channels, commit; float eps; uint32_t plane; }; +struct QsaArgs { uint32_t pos0, pos_base, max_cells, n_tok; float eps; }; +struct GlueArgs { uint32_t n, n_tok, n_embd, topk; }; +struct ArgArgs { uint32_t n_vocab, parts; }; +// the routed gate/up's i-quant grids from constant memory (QUANT_CTAB, function constant 23 of quant.metal): bitwise +// the threadgroup copy's values, 3-7% faster on the M5 Max; STRATA_METAL_CTAB=0 turns it off +bool metal_ctab() { + static const bool on = [] { + const char* e = std::getenv("STRATA_METAL_CTAB"); + return !(e && std::string(e) == "0"); + }(); + return on; +} + +int xkind(int t) { + switch (t) { + case ref::Q2_0: return 1; + case ref::Q4_K: case ref::Q5_K: return 2; + case ref::Q6_K: case ref::Q3_K: return 3; + default: return 0; + } +} + +// a prepared activation: 4 planes of MAXT rows of n, then the per-16 sums +struct Act { + mtl::Buffer b; + int n = 0; + size_t plane_bytes() const { return (size_t) 4 * MAXT * n; } +}; + +double now_ms() { return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); } + +} // namespace + +// the prompt chain's state (prompt_chain.inc): kernel libraries, the variant, buffers for chunks of C rows +struct PromptBufs { + int lib = -1, lgdn = -1, lqsa = -1; + bool k4 = false; + int C = 0, maxrows = 0; + double gpu_ms = 0, host_ms = 0, mtp_ms = 0; + int gu3[4] = {}, dn3[4] = {}; + mtl::Buffer R, bo, inj[2], xn, xnh, V, loh, mixed, mixh, qkv, z, al, be, yg, ygh, gqn, gkn, gvc, ggb, gkq, go, qfull, + kcur, vcur, iqr, ikr, qcur, qcurh, qidx, scores, qids, part, XQ, xqh, logits, ids, wts, bcnt, boff, eoff, tiles, meta, + stok, sw, pos, XS, HS, YE, yr, gsh, ush, hh, ys, sgv, WD, WU, Wqkv, Wz, Wal, Wbe, Wout, Wq, Wk, Wv, Wiq, Wik, Wr, + Wsg, Wshg, Wshu, Wshd, pemb, pembh, pkey, pval, keyn, qn, gated, normW, Wpk, Wpv; +}; + +// The vision path (--vision, GENI requests), from the shared host code: the image rows of the prompt being read +// (host rows by absolute position, null = embed the token; set by prompt_run for its duration) and the M-RoPE table +// (int32 [cells][3] (t, h, w); mrope_table_set: the host view of the device table the server fills per request). +const float* const* g_embd_rows = nullptr; +const int32_t* g_mrope_host = nullptr; +const int32_t* g_mrope_dev = nullptr; + +class Window { +public: + bool init(const strata::core::ModelGeometry& g, strata::core::SessionState& ss, const std::string& shard1, int max_t, + int64_t max_cells, std::string& err); + bool run(int T, const int32_t* tokens, int64_t pos0, bool head, int32_t* out, std::string& err); + bool commit(int n_keep, std::string& err); + bool finish(int Tn, const int32_t* tokens, int64_t pos0, bool head, int32_t* out, double t0); + bool copy_logits(int t, float* host) const; + int64_t vocab() const { return n_vocab_; } + bool ready() const { return cx_ != nullptr; } + bool streaming() const { return stream_; } + // --serve's conversation checkpoints: the window's running state (the GDN recurrences and conv histories, the + // PLE history, each QSA layer's indexer tail and tail-block key); the KV and pooled keys are positional + bool checkpoint_save(strata::core::ConversationCheckpoint& c, std::string& err); + bool checkpoint_restore(const strata::core::ConversationCheckpoint& c, std::string& err); + void reset(); // a new sequence (session_zero): the running state zeroed + void set_max_t(int t) { max_t_ = std::min(t, MAXT); } + // ---- the MTP draft layer (mtp.hpp's math on mac-kern's kernels; the MTP GGUF from tools/mtp_pack.py) + bool mtp_load(const std::string& gguf, int max_t, std::string& err); + bool mtp_prefill(const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err); + bool mtp_draft(int T, const int32_t* tokens, int64_t p, int a, int max_steps, int32_t* drafts, float* probs, + float min_p, int* n_drafts, std::string& err); + bool mtp_loaded() const { return mtp_on_; } + // the prompt through mac-kern's prompt kernels (prompt_chain.inc) + bool prompt(const int64_t* tokens, int64_t n, int64_t pos0, + const std::function& on_chunk, std::string& err); + +private: + const gguf::Tensor& T(const std::string& name) const { + const gguf::Tensor* t = f_.find(name); + if (!t) { std::fprintf(stderr, "strata metal: the model has no tensor %s\n", name.c_str()); std::exit(2); } + return *t; + } + const mtl::Pipeline* P(int lib, const std::string& fn, const mtl::Constants& c, const std::string& key) { + auto it = pcache_.find(key); + if (it == pcache_.end()) { + it = pcache_.emplace(key, cx_->pipeline(lib, fn, c)).first; + pkey_of_[&it->second] = key; + } + return &it->second; + } + void push(std::vector& ds, mtl::Dispatch d) { + d.barrier = !nb_; + nb_ = false; + // timing only (WRONG answers): STRATA_METAL_SKIP=a,b,... runs the dispatches whose pipeline name contains one + // of the words as empty grids (the marginal cost of a kernel class by leaving it out) + static const std::vector skip = [] { + std::vector v; + if (const char* e = std::getenv("STRATA_METAL_SKIP")) { + std::string s = e, w; + for (char c : s + ",") { if (c == ',') { if (!w.empty()) v.push_back(w); w.clear(); } else w += c; } + } + return v; + }(); + if (!skip.empty()) { + const std::string& k = pkey_of_[d.p]; + for (const auto& w : skip) + if (k.find(w) != std::string::npos) { d.indirect = nullptr; d.grid[0] = 0; break; } + } + ds.push_back(std::move(d)); + } + std::map pkey_of_; + void gemv(std::vector& ds, const gguf::Tensor& t, const Act& x, const mtl::Buffer& y, size_t y_stride, + int ntok, size_t y_off = 0, const mtl::Buffer* wb = nullptr); + void xprep(std::vector& ds, const mtl::Buffer& x, const Act& out, int n); + void gr_read(std::vector& ds, const std::string& pre, bool apply, const Act& out, bool final_, int ntok); + void layer(std::vector& ds, int l, int ntok, int64_t pos0); + void ple_cpu(int T); + // the MTP layer: the input branches + attention HC read + K/V append for `n` rows (srcR rows, host tokens) at + // cells cell0..; with `full` (n == 1) the rest of the layer too and the draft head into mlm_/tokout_. The + // embedding rows go to memb_ rows erow..; tokens == nullptr: memb_ row erow already holds the embedding (put + // there by mtp_embed on the GPU). `slot`: the dense attention's cell list (one per draft step of a round). + void mtp_encode(std::vector& ds, const mtl::Buffer& srcR, size_t src_off, int n, const int32_t* tokens, + int64_t cell0, bool full, int erow = 0, int slot = 0); + // a draft round's step j on the GPU: the pick and its probability (dout_/dprob_ [j]), and with `embed` the picked + // token's embedding into memb_ row 0 (the next step's input) + void mtp_pick(std::vector& ds, int j, bool embed); + void gr_read_m(std::vector& ds, const std::string& pre, mtl::Buffer& Rb, const mtl::Buffer& bo, + const mtl::Buffer& inj_in, const mtl::Buffer& inj_out, bool apply, const Act& out, bool final_, int ntok); + const gguf::Tensor& TM(const std::string& name) const { + const gguf::Tensor* x = fm_.find(name); + if (!x) { std::fprintf(stderr, "strata metal: the MTP model has no tensor %s\n", name.c_str()); std::exit(2); } + return *x; + } + size_t NM(const std::string& name) const { // the folded (1 + w) copy of an F32 norm of the MTP model + auto it = mnorm_off_.find(name); + if (it == mnorm_off_.end()) { std::fprintf(stderr, "strata metal: no MTP norm %s\n", name.c_str()); std::exit(2); } + return it->second; + } + + strata::core::SessionState* ss_ = nullptr; + gguf::File f_; + std::unique_ptr cx_; + mtl::Buffer W_; + int lib_ = -1, lgdn_ = -1, lqsa_ = -1, lsmp_ = -1, lple_ = -1; + std::map pcache_; + bool nb_ = false; + int max_t_ = 1; + int64_t max_cells_ = 0; + int64_t n_vocab_ = 0; + float eps_ = 1e-6f; + // buffers + mtl::Buffer R_, bo_, inj_[2], xn_, lo_, qkv_, z_, al_, be_, yg_, logits_, ids_, wts_, plan_, h_, ye_, gsh_, ush_, + ysh_, sg_, qfull_, kcur_, vcur_, iqr_, ikr_, qcur_, qidx_, scores_, qids_, part_, cs_, lm_, apv_, api_, tokout_, + emb_, pkey_, pval_, qkvL_, alL_, beL_, zL_, ydump_, keyn_, qn_, gated_, normW_, pleHist_; + Act XA_, XF_, XY_, XQ_, XH_, XE_; + int cur_inj_ = 0; + // state + std::vector gst_, ghist_[2], kq_, vq_, ksc_, vsc_, tail_, dead_, pooled_; + int hp_ = 0; // which of the two history buffers holds the committed conv history (all layers) + // commit(n) of a window of several tokens: the GDN fold of the kept prefix waits for the next window and runs at + // the start of its command buffer (one submit and wait less a round). Nothing else reads the GDN state between + // the two (the drafter reads the window's rows and its own caches). STRATA_METAL_LAZY_FOLD=0: at commit. + int pend_fold_ = 0; + // gdn_step's partial commit (mac-kern 56526aed, commit = 0x100 | k): a verify window of T > 1 commits its first + // row in place (it is always kept), so commit(1) needs no fold and commit(n) folds rows 1..n-1 only; a window + // without the head (the prompt) commits all its rows in the step. Opt-in (STRATA_METAL_PARTIAL=1): at --spec 2 + // it measured 0.3-0.8% slower on the M5 Max (the in-place state write costs every window, the fold it saves + // only the rounds with no accepted draft). Off: the window commits nothing and commit(n) folds n rows. + bool partial_ = std::getenv("STRATA_METAL_PARTIAL") && std::string(std::getenv("STRATA_METAL_PARTIAL")) == "1"; + bool win_head_ = true; // the window being encoded has the head + bool last_head_ = true; // the last window had it + // token_chain's --fuse (mac-kern): the GDN step writes the prepared y planes itself (no xprep), and a window whose + // context is within the selection budget skips the QSA score and top-k (the cell list is the identity: qids_ + // holds it from init, restored after a window that selected). STRATA_METAL_FUSE=0: off. + bool fuse_ = !(std::getenv("STRATA_METAL_FUSE") && std::string(std::getenv("STRATA_METAL_FUSE")) == "0"); + bool qdirty_ = false; + // mac-kern's router_route (3f9ca996): the BF16 router GEMV and moe_route in one dispatch, beside the shared + // expert's GEMVs (bitwise). Opt-in (STRATA_METAL_ROUTE=1): in this window, where the router GEMV already runs + // beside the shared GEMVs, it measured no faster (T2 GPU 13.035 vs 13.027 ms; the fused kernel alone 0.615 ms vs + // 0.566 for the two) and 0.3-0.5% slower end to end on the M5 Max. + bool routef_ = std::getenv("STRATA_METAL_ROUTE") && std::string(std::getenv("STRATA_METAL_ROUTE")) == "1"; + mtl::Buffer rcounter_; + // STRATA_METAL_KPROF=T (test tooling): once, after the 20th cached window of T tokens with the head, the GPU time + // of each kernel class alone (the window's own dispatches of that pipeline + weight role, run by themselves) + void kprof(const std::vector& ds, int Tn); + void fold(std::vector& ds, int n_keep, int hp); + // the encoded window per (T, head, hp_): built once, then only the positions are patched (the host's encode cost) + struct Cached { + std::vector ds; + std::vector cuts; // SSD streaming: the segment ends (one per layer, before its experts) + std::vector> qsa; // (dispatch, kind): 0 QsaArgs n_tok = T, 1 the merge (MAXT), 2 the scores + }; + std::map wcache_; + std::vector>* rec_ = nullptr; + // ---- SSD streaming (stream.h): the dense weights in W_, the routed experts in the arena + std::unique_ptr st_; + bool stream_ = false, st_pred_ = false; + std::vector* cuts_ = nullptr; + mtl::Buffer predL_, predL2_; // 48 x MAXT x 512: layer l + 1's (l + 2's) router logits from layer l's FFN input + int seg_T_ = 0; + bool stream_arena(std::string& err); + double run_ds(Cached& c); + // prompts on the matrix units (prompt_chunk below) + struct PromptGemm; + PromptGemm* pg_ = nullptr; + const int32_t* cut_ids_ = nullptr; // the routed ids the handshake reads (a prompt chunk's; else ids_) + const mtl::Buffer* mtp_src_ = nullptr; // the rows the draft layer's prompt K/V read (a prompt chunk's; else R_) + double pg_ms_ = 0; + int64_t pg_tok_ = 0; +public: + bool prompt_gemm_on(int64_t n) const; + bool prompt_gemm_init(std::string& err); + bool prompt_chunk(const int32_t* tokens, int Tn, int64_t pos0, std::string& err); + int prompt_chunk_rows() const; + void prompt_region(bool hold) { if (stream_ && st_ && st_->ready()) st_->hold_region(hold); } + void stream_report(FILE* f) const { + if (!st_) return; + st_->report(f); + for (int t = 1; t <= MAXT; ++t) + if (win_n_[t]) + std::fprintf(f, "stream windows T=%d %d (%s): %.2f ms each (GPU incl. the host's turns %.2f ms)\n", t, win_n_[t], + t == 8 ? "prompt rows" : "decode", win_ms_[t] / win_n_[t], win_gpu_[t] / win_n_[t]); + } + int win_n_[MAXT + 1] = {}; + double win_ms_[MAXT + 1] = {}, win_gpu_[MAXT + 1] = {}; + void at_cut(int s) { + st_->at_layer(s, seg_T_, TOPK, cut_ids_ ? cut_ids_ : ids_.as(), st_pred_ && !cut_ids_ ? predL_.as() + (size_t) s * MAXT * 512 : nullptr, + predL2_.ptr && !cut_ids_ ? predL2_.as() + (size_t) s * MAXT * 512 : nullptr); + } +private: + std::vector ple_hist_; // NG_HIST x hc_dim normalized rows, row-fastest + bool ple_on_ = false; + int last_T_ = 0; + double last_gpu_ms_ = 0; + int last_n_disp_ = 0; + int32_t last_tokens_[MAXT] = {}; + std::vector last_norm_; // the window's normalized PLE rows (T x hc_dim), for commit + // STRATA_METAL_LOGPOS= (test tooling, one-token windows): per decode position the log-probability of the + // token that came next (the next window's input: with --spec-follow, the forced text) and the top 64, in the + // KL harness's row format (phaseA-tests cuda_p0/cuda_kl.py load_lp): pos, target, lp, argmax, 4 x 0, id:lp ... + std::FILE* logpos_ = nullptr; + bool lp_pend_ = false; + int64_t lp_pos_ = 0, lp_first_ = -1; + int32_t lp_arg_ = 0; + double lp_lse_ = 0.0; + std::vector lp_row_; + std::vector> lp_top_; + void logpos(int Tn, const int32_t* tokens, int64_t pos0, bool head); + // STRATA_METAL_PROFILE=1: where a window's time goes, per window size (printed when the window goes away) + struct Prof { int64_t n = 0; double pre = 0, rg = 0, gpu = 0, fin = 0, all = 0; }; + std::map prof_; + Prof cprof_, dprof_; // commit (folds), the draft rounds + double tp_pre_ = 0, tp_rg_ = 0; +public: + ~Window(); + void prof_add(bool draft, double ms) { Prof& x = draft ? dprof_ : cprof_; ++x.n; x.all += ms; } +private: + // the Q8_0 copies of the hyper-connection matrices (the default; STRATA_HC_Q8=0: the BF16 originals) + bool hc_q8_ = false; + mtl::Buffer Q8_; + std::map q8off_; + // MTP + bool mtp_on_ = false; + int lmtp_ = -1; + gguf::File fm_; + mtl::Buffer Wm_, mnorm_, mR_, memb_, men_, me2_, mhn_, mh2_, midx_, mbo_, minj_[2], mqids_, mlm_; + std::map mnorm_off_; + std::vector mkq_, mvq_, mksc_, mvsc_, mtail_, mdead_, mpooled_; + // the draft head over a token subset (data/draft_vocab.bin, as the CUDA drafter): its rows gathered from the head + mtl::Buffer mhead_; + gguf::Tensor mhead_t_; + std::vector dvocab_; + // the draft layer's BF16 matrices in Q8_0 (half the bytes a draft step reads; drafts only: the verify window + // decides every token). STRATA_METAL_MTP_Q8=0 keeps BF16. + mtl::Buffer mq8_; + std::map mq8t_; + const mtl::Buffer& MB(const std::string& name) const { return mq8t_.count(name) ? mq8_ : Wm_; } + const gguf::Tensor& TQ(const std::string& name) const { + auto it = mq8t_.find(name); + return it != mq8t_.end() ? it->second : TM(name); + } + Act XEn_, XHn_; + PromptBufs pb_; + mtl::Buffer mpemb_; // the drafter's prompt embedding rows (mtp_prefill, one command buffer) + size_t mpemb_rows_ = 0; + const mtl::Buffer* membp_ = nullptr; // mtp_encode's embedding rows (nullptr: memb_) + const mtl::Buffer* mpsrc_ = nullptr; // the drafter's prompt rows (nullptr: R_) + bool coop_k4(); + // the vision path: the embedding row of an absolute position (an image row, or null), the M-RoPE table rows a + // window reads copied into mrope_ (qsa_prep's buffer 20, function constant 24) + const float* img_row(int64_t pos) const { return g_embd_rows ? g_embd_rows[pos] : nullptr; } + mtl::Buffer mrope_; + // the PLE conv kernel as F16 (ple_conv_add reads half): the file's own F16 tensor, or an F32 one (Unsloth's) + // narrowed with round-to-nearest-even as the host loader does + mtl::Buffer plekw_; + bool plekw_own_ = false; + mtl::Arg kw_arg() { return plekw_own_ ? mtl::Arg::B(plekw_) : mtl::Arg::B(W_, T("blk.1.ple_conv1d.weight").offset); } + const uint16_t* kw_host() { + return plekw_own_ ? plekw_.as() + : (const uint16_t*) ((const uint8_t*) W_.ptr + T("blk.1.ple_conv1d.weight").offset); + } + bool mrope_on() const { return g_mrope_host != nullptr; } + void mrope_sync(int64_t c0, int64_t n) { + if (!mrope_on()) return; + const int64_t a = std::max(0, c0 & ~(int64_t) 3), b = std::min(max_cells_, c0 + n); + if (b > a) std::memcpy(mrope_.as() + a * 3, g_mrope_host + a * 3, (size_t) (b - a) * 12); + } + mtl::Constants qsa_c() const { return mrope_on() ? mtl::Constants().b(24, true) : mtl::Constants(); } + std::string qsa_k() const { return mrope_on() ? "qsa_prep#mrope" : "qsa_prep"; } + int m5_layout_ = -1; // the M5's matmul2d layout (coop_k4), asked once: the M4's tiles differ + bool m5_layout() { if (m5_layout_ < 0) m5_layout_ = coop_k4() ? 1 : 0; return m5_layout_ == 1; } + bool pc_setup(int C); + bool pc_chunk(const int64_t* tokens, int nT, int64_t pos0, std::string& err); + // the draft round in one command buffer (msl/mtp_chain.metal): STRATA_METAL_MTP_CHAIN=0 runs a command buffer + // per step with the host's pick and embedding (as before) + int lchain_ = -1; + bool chain_ = false; + mtl::Buffer dout_, dprob_, posv_, dmap_; +}; + +bool Window::init(const strata::core::ModelGeometry& g, strata::core::SessionState& ss, const std::string& shard1, + int max_t, int64_t max_cells, std::string& err) { + ss_ = &ss; + max_t_ = std::min(max_t, MAXT); + max_cells_ = max_cells; + if (g.n_embd != N || g.hc != HC || g.hc_lr != LR || g.n_ff != NFF || g.n_expert != NEXP || g.n_layers != 48) { + err = "metal window: the geometry differs from Qwen3.8-Flash-Next's"; + return false; + } + eps_ = 1e-6f; + const double t0 = now_ms(); + if (!f_.open(shard1, err)) return false; + cx_ = std::make_unique(); + stream_ = ExpertStream::wanted(f_, *cx_); + if (stream_) { + // the model does not fit: the dense weights are read into memory below, the experts stream from the SSD + st_ = std::make_unique(); + if (!st_->open(f_, err)) return false; + } else { + madvise(f_.map, f_.map_bytes, MADV_WILLNEED); + W_ = cx_->wrap(f_.map, f_.map_bytes); + if (W_.handle == nullptr) { err = "metal window: cannot wrap " + shard1 + " as a Metal buffer"; return false; } + } + n_vocab_ = (int64_t) T("output.weight").shape[1]; + lib_ = cx_->compile({"quant.metal", "units.metal", "moe.metal", "gemv.metal", "router.metal", "gr.metal", "gr2.metal", + "glue.metal"}); + rcounter_ = cx_->alloc(16); + lgdn_ = cx_->compile({"gdn.metal"}, "#define NO_GGML_COMMON 1\n"); + lqsa_ = cx_->compile({"qsa.metal", "qsa2.metal"}, "#define NO_GGML_COMMON 1\n"); + lsmp_ = cx_->compile({"sample.metal"}, "#define NO_GGML_COMMON 1\n"); + lple_ = cx_->compile({std::string(STRATA_METAL_ENGINE_KERNELS_DEFAULT) + "/ple.metal"}, "#define NO_GGML_COMMON 1\n"); + + const int MAXC = (int) std::max(4096, (max_cells + 64) / 4 * 4 + 64), MB = MAXC / 4 + 2; + max_cells_ = MAXC; + auto A = [&](size_t bytes) { return cx_->alloc(bytes); }; + R_ = A(4 * MAXT * HC * N); bo_ = A(4 * MAXT * N); inj_[0] = A(4 * MAXT * HC); inj_[1] = A(4 * MAXT * HC); + xn_ = A(4 * MAXT * HC * N); lo_ = A(4 * MAXT * LR); qkv_ = A(4 * MAXT * 10240); z_ = A(4 * MAXT * 6144); + al_ = A(4 * MAXT * 48); be_ = A(4 * MAXT * 48); yg_ = A(4 * MAXT * 6144); logits_ = A(4 * MAXT * 512); + ids_ = A(4 * MAXT * TOPK); wts_ = A(4 * MAXT * TOPK); plan_ = A(4 * P_INTS); h_ = A(4 * MAXT * TOPK * NFF); + ye_ = A(4 * MAXT * TOPK * N); gsh_ = A(4 * MAXT * NFF); ush_ = A(4 * MAXT * NFF); ysh_ = A(4 * MAXT * N); + sg_ = A(4 * MAXT * 4); qfull_ = A(4 * MAXT * 12288); kcur_ = A(4 * MAXT * 512); vcur_ = A(4 * MAXT * 512); + iqr_ = A(4 * MAXT * 512); ikr_ = A(4 * MAXT * 128); qcur_ = A(4 * MAXT * 24 * 256); qidx_ = A(4 * MAXT * 4 * 128); + scores_ = A(4 * (size_t) MAXT * MB); qids_ = A(4 * MAXT * 2051); part_ = A(4 * (size_t) MAXT * 65 * 24 * 258); + cs_ = A(8 * (size_t) (MAXC + 16) * 32); lm_ = A(4 * (size_t) MAXT * n_vocab_); apv_ = A(4 * MAXT * 120); + api_ = A(4 * MAXT * 120); tokout_ = A(4 * MAXT); emb_ = A(4 * MAXT * N); pkey_ = A(4 * MAXT * 10240); + pval_ = A(4 * MAXT * N); + // the GDN layers' window inputs, kept per layer so commit() can fold the accepted prefix into the state + qkvL_ = A(4 * (size_t) 36 * MAXT * 10240); alL_ = A(4 * (size_t) 36 * MAXT * 48); beL_ = A(4 * (size_t) 36 * MAXT * 48); + zL_ = A(4 * (size_t) 36 * MAXT * 6144); ydump_ = A(4 * MAXT * 6144); + keyn_ = A(4 * MAXT * 10240); qn_ = A(4 * MAXT * 10240); gated_ = A(4 * MAXT * 10240); normW_ = A(4 * MAXT * 10240); + mrope_ = A(12 * (size_t) (MAXC + 16)); + pleHist_ = A(4 * 9 * 10240); + auto act = [&](int n) { Act a; a.n = n; a.b = A(4 * ((size_t) 4 * MAXT * n + (size_t) MAXT * n / 16)); return a; }; + XA_ = act(N); XF_ = act(N); XY_ = act(6144); XQ_ = act(6144); XH_ = act(NFF); XE_ = act(N); + // RoPE: cos/sin [pos][32] for the first 64 dims, NEOX pairs (i, i + 32), in double as build_rope_table + const double base = f_.meta_num.count("qwen4exp.rope.freq_base") ? f_.meta_num["qwen4exp.rope.freq_base"] : 1e7; + for (int p = 0; p < MAXC + 16; ++p) + for (int i = 0; i < 32; ++i) { + const double th = (double) p * std::pow(base, -2.0 * i / 64.0); + cs_.as()[(p * 32 + i) * 2] = (float) std::cos(th); + cs_.as()[(p * 32 + i) * 2 + 1] = (float) std::sin(th); + } + for (int t = 0; t < MAXT; ++t) + for (int c = 0; c < 2051; ++c) qids_.as()[t * 2051 + c] = c; + for (int l = 0; l < 48; ++l) { + if (l % 4 != 3) { + gst_.push_back(A(4 * 128 * 48 * 128)); + ghist_[0].push_back(A(4 * 10240 * 3)); + ghist_[1].push_back(A(4 * 10240 * 3)); + } else { + kq_.push_back(A((size_t) MAXC * 2 * 256)); + vq_.push_back(A((size_t) MAXC * 2 * 256)); + ksc_.push_back(A(2 * (size_t) MAXC * 2 * 4)); + vsc_.push_back(A(2 * (size_t) MAXC * 2 * 4)); + tail_.push_back(A(4 * 4 * 128)); + dead_.push_back(A(4 * 128)); + pooled_.push_back(A(4 * (size_t) MB * 128)); + } + } + // ---- the HC read in Q8_0 (the owner's default on Metal, as STRATA_HC_Q8 on gfx12): the BF16 down / up / inject + // matrices quantized once at load (ggml's q8_0 rule, ref_quant), read by gr_down_q8 / gr_up_q8 + { + const char* e = std::getenv("STRATA_HC_Q8"); + hc_q8_ = !(e && std::string(e) == "0"); + } + if (hc_q8_) { + const double tq = now_ms(); + size_t tot = 0; + std::vector names; + for (const auto& kv : f_.tensors) { + const gguf::Tensor& x = kv.second; + if (x.type != ref::BF16 || x.name.find("hc_") == std::string::npos || x.name.find("_norm") != std::string::npos) continue; + uint64_t ne = 1; + for (uint64_t d : x.shape) ne *= d; + q8off_[x.name] = tot; + names.push_back(x.name); + tot += ne / 32 * 34; + } + Q8_ = cx_->alloc((tot + 4095) / 4096 * 4096 + 4096); // + a page: a file with Q8_0 HC already has no copies + std::vector th; + const unsigned nth = std::max(1u, std::min(16u, std::thread::hardware_concurrency())); + for (unsigned k = 0; k < nth; ++k) + th.emplace_back([&, k] { + std::vector tmp; + std::vector raw; + for (size_t i = k; i < names.size(); i += nth) { + const gguf::Tensor& x = *f_.find(names[i]); + uint64_t ne = 1; + for (uint64_t d : x.shape) ne *= d; + tmp.resize(ne); + const uint8_t* src = (const uint8_t*) f_.map + x.offset; + if (stream_) { // F_NOCACHE reads: the page cache is kept for the arena + raw.resize(x.bytes); + if (!st_->read(raw.data(), x.bytes, x.offset)) { std::fprintf(stderr, "strata metal: read failed\n"); std::exit(6); } + src = raw.data(); + } + ref::dequant(ref::BF16, src, tmp.data(), ne); + ref::quantize_q8_0(tmp.data(), ne, Q8_.as() + q8off_[names[i]]); + } + }); + for (auto& x : th) x.join(); + std::fprintf(stderr, "strata metal: HC read in Q8_0 (STRATA_HC_Q8=0: BF16): %zu matrices, %.0f MB, made in %.0f ms\n", + names.size(), tot / 1e6, now_ms() - tq); + } + if (stream_) { + std::vector skip; // the BF16 originals of the Q8_0 HC copies are not read again + if (hc_q8_) + for (const auto& kv : q8off_) skip.push_back(kv.first); + if (!st_->load_dense(f_, *cx_, skip, W_, err)) return false; + const char* e = std::getenv("STRATA_METAL_PREFETCH"); + st_pred_ = !(e && std::atoi(e) <= 0); + if (st_pred_) predL_ = A(4 * (size_t) 48 * MAXT * 512); + if (st_pred_ && st_->ahead2() > 0) predL2_ = A(4 * (size_t) 48 * MAXT * 512); + } + ple_on_ = ss.ple.ready() && f_.find("blk.1.ple_key.weight") != nullptr; + if (ple_on_ && T("blk.1.ple_conv1d.weight").type == ref::F32) { + const gguf::Tensor& k = T("blk.1.ple_conv1d.weight"); + const size_t ne = k.bytes / 4; + plekw_ = cx_->alloc((ne * 2 + 4095) / 4096 * 4096); + const float* src = (const float*) ((const uint8_t*) W_.ptr + k.offset); + uint16_t* dst = plekw_.as(); + for (size_t i = 0; i < ne; ++i) dst[i] = ref::f32_to_f16(src[i]); + plekw_own_ = true; + } + ple_hist_.assign((size_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM, 0.0f); + last_norm_.assign((size_t) MAXT * strata::kernels::NG_HC_DIM, 0.0f); + std::fprintf(stderr, "strata metal: decode window on %s: %s %s (%.1f GB), %d cells, PLE %s, ready in %.0f ms\n", + cx_->device_name().c_str(), shard1.c_str(), stream_ ? "streamed from the SSD (experts)" : "wrapped", + f_.file_bytes / 1e9, MAXC, ple_on_ ? "on" : "OFF", now_ms() - t0); + return true; +} + +void Window::gemv(std::vector& ds, const gguf::Tensor& t, const Act& x, const mtl::Buffer& y, + size_t y_stride, int ntok, size_t y_off, const mtl::Buffer* wb) { + const int n_in = (int) t.shape[0], n_out = t.shape.size() > 1 ? (int) t.shape[1] : 1; + const int ty = t.type; + int L = 16, Rr = 1, S = 4, K = 1; + if (n_in >= 6144) { L = 32; Rr = 1; S = 8; K = 2; } + else if (n_in == 640) { L = 8; Rr = 1; S = 4; K = 1; } + else if (n_out <= 640 || ty == ref::Q2_0 || ty == ref::BF16) { L = 32; Rr = 1; S = 4; K = 1; } + { + // windows of several tokens: NR rows a lane share each x load (the window's cost is its x traffic). The sums + // run in the same order for any NR, so the answers do not change. STRATA_METAL_GEMV_NR (1, 2): the tile. + static const int nr_env = [] { const char* e = std::getenv("STRATA_METAL_GEMV_NR"); return e ? std::atoi(e) : 1; }(); + if (ntok > 1 && nr_env == 2 && n_out >= 2048) { + if (S == 8 && K == 2) { S = 4; K = 2; } + if (S == 8 && K == 1) S = 4; + if (K == 1 || (L == 32 && K == 2)) Rr = 2; + } + } + const std::string fn = "gemv_" + std::to_string(ty) + "_" + std::to_string(L) + "_" + std::to_string(Rr) + "_" + + std::to_string(S) + "_" + std::to_string(K); + const mtl::Pipeline* p = P(lib_, fn, mtl::Constants().i(0, ntok), fn + "#" + std::to_string(ntok)); + GemvArgs a{(uint32_t) n_in, (uint32_t) n_out, (uint32_t) ntok, (uint32_t) ref::row_bytes(t.type, n_in), (uint32_t) n_in, + (uint32_t) y_stride}; + mtl::Dispatch d; + d.p = p; + d.args = {mtl::Arg::B(wb ? *wb : W_, t.offset), mtl::Arg::B(x.b, x.plane_bytes() * xkind(ty)), + mtl::Arg::B(x.b, x.plane_bytes() * 4), mtl::Arg::B(y, y_off), mtl::Arg::V(a)}; + const int rpt = (S / K) * (32 / L) * Rr; + d.grid[0] = (n_out + rpt - 1) / rpt; + d.tg[0] = S * 32; + push(ds, d); +} + +void Window::xprep(std::vector& ds, const mtl::Buffer& x, const Act& out, int n) { + mtl::Dispatch d; + d.p = P(lib_, "xprep", {}, "xprep"); + const uint32_t nn = n, nt = MAXT; + d.args = {mtl::Arg::B(x), mtl::Arg::B(out.b), mtl::Arg::V(nn), mtl::Arg::V(nt)}; + d.tg[0] = 256; + d.grid[0] = (n / 16 * MAXT + 255) / 256; + push(ds, d); +} + +// the hyper-connection read (gr.metal, 3 dispatches): the previous sublayer's write folded in when `apply` +void Window::gr_read(std::vector& ds, const std::string& pre, bool apply, const Act& out, bool final_, + int ntok) { + const gguf::Tensor& tn = T(pre + "_norm.weight"); + const gguf::Tensor& tdn = T(pre + "_down.weight"); + const gguf::Tensor& tup = T(pre + "_up.weight"); + const gguf::Tensor& tin = final_ ? tdn : T(pre + "_inject.weight"); + GrArgs a{N, HC, LR, (uint32_t) ntok, apply ? 1u : 0u, eps_}; + mtl::Dispatch d1; + d1.p = P(lib_, "gr_norm", {}, "gr_norm"); + d1.args = {mtl::Arg::B(R_), mtl::Arg::B(bo_), mtl::Arg::B(inj_[cur_inj_]), mtl::Arg::B(W_, tn.offset), mtl::Arg::B(xn_), + mtl::Arg::V(a)}; + d1.grid[0] = HC; + d1.grid[1] = ntok; + d1.tg[0] = 256; + push(ds, d1); + // each matrix: its load-time Q8_0 copy (q8off_), else the file's own tensor (Unsloth's are Q8_0 already, their + // inject rows F32) + auto src = [&](const gguf::Tensor& t) -> std::pair { + auto it = q8off_.find(t.name); + return it != q8off_.end() ? std::make_pair(&Q8_, it->second) : std::make_pair(&W_, (size_t) t.offset); + }; + auto is_q8 = [&](const gguf::Tensor& t) { return q8off_.count(t.name) || t.type == ref::Q8_0; }; + const auto [bd, od] = src(tdn); + const auto [bi, oi] = src(tin); + const auto [bu, ou] = src(tup); + const bool q8 = is_q8(tdn) && is_q8(tup); + const bool injf = q8 && !final_ && !q8off_.count(tin.name) && tin.type == ref::F32; + mtl::Dispatch d2; + const char* dn = injf ? "gr_down_q8f_8_8" : q8 ? "gr_down_q8_8_8" : "gr_down_8_8"; + d2.p = P(lib_, dn, mtl::Constants().i(1, ntok), std::string(dn) + "#" + std::to_string(ntok)); + d2.args = {mtl::Arg::B(*bd, od), mtl::Arg::B(*bi, oi), mtl::Arg::B(xn_), mtl::Arg::B(lo_), + mtl::Arg::B(inj_[1 - cur_inj_]), mtl::Arg::V(a)}; + d2.grid[0] = LR + HC; + d2.tg[0] = 256; + push(ds, d2); + mtl::Dispatch d3; + const char* up = q8 ? "gr_up_q8" : "gr_up"; + d3.p = P(lib_, up, mtl::Constants().i(1, ntok), std::string(up) + "#" + std::to_string(ntok)); + GrArgs au = a; + au.n_tok = MAXT; // the plane stride of the prepared activation + d3.args = {mtl::Arg::B(*bu, ou), mtl::Arg::B(lo_), mtl::Arg::B(xn_), mtl::Arg::B(out.b), mtl::Arg::V(au)}; + d3.grid[0] = N / 16; + d3.tg[0] = 256; + push(ds, d3); + cur_inj_ = 1 - cur_inj_; +} + +void Window::layer(std::vector& ds, int l, int ntok, int64_t pos0) { + const std::string b = "blk." + std::to_string(l) + "."; + // ---- the mixer: layer 1's read after the PLE is not applied again (its pending write was applied before it) + gr_read(ds, b + "hc_attn", l > 0 && !(l == 1 && ple_on_), XA_, false, ntok); + if (l % 4 != 3) { + const int gi = l - l / 4; + // a one-token window commits in the step; a longer one leaves the state and commit() folds the kept prefix + // from the inputs kept per layer (qkvL_ ...) + const bool self_commit = ntok == 1; + const uint32_t cm = self_commit ? 1u : !partial_ ? 0u : win_head_ ? (0x100u | 1u) : 1u; + const size_t o_qkv = (size_t) gi * MAXT * 10240 * 4, o_ab = (size_t) gi * MAXT * 48 * 4, o_z = (size_t) gi * MAXT * 6144 * 4; + gemv(ds, T(b + "attn_qkv.weight"), XA_, qkvL_, 10240, ntok, o_qkv); + nb_ = true; + gemv(ds, T(b + "attn_gate.weight"), XA_, zL_, 6144, ntok, o_z); + nb_ = true; + gemv(ds, T(b + "ssm_alpha.weight"), XA_, alL_, 48, ntok, o_ab); + nb_ = true; + gemv(ds, T(b + "ssm_beta.weight"), XA_, beL_, 48, ntok, o_ab); + GdnArgs a{16, 48, 10240, cm, eps_, fuse_ ? (uint32_t) (MAXT * 6144) : 0u}; + mtl::Dispatch d; + d.p = P(lgdn_, "gdn_step", mtl::Constants().i(2, ntok), "gdn_step#" + std::to_string(ntok)); + const int hp = hp_; + d.args = {mtl::Arg::B(gst_[(size_t) gi]), mtl::Arg::B(ghist_[hp][(size_t) gi]), mtl::Arg::B(qkvL_, o_qkv), + mtl::Arg::B(alL_, o_ab), mtl::Arg::B(beL_, o_ab), mtl::Arg::B(zL_, o_z), + mtl::Arg::B(W_, T(b + "ssm_conv1d.weight").offset), + mtl::Arg::B(W_, T(b + "ssm_dt.bias").offset), mtl::Arg::B(W_, T(b + "ssm_a").offset), + mtl::Arg::B(W_, T(b + "ssm_norm.weight").offset), mtl::Arg::B(fuse_ ? XY_.b : yg_), mtl::Arg::V(a), + mtl::Arg::B(ghist_[1 - hp][(size_t) gi])}; + d.grid[0] = 48; + d.tg[0] = 512; + push(ds, d); + (void) self_commit; // the history ping-pong turns after the window (run) or at commit + if (!fuse_) xprep(ds, yg_, XY_, 6144); + gemv(ds, T(b + "ssm_out.weight"), XY_, bo_, N, ntok); + } else { + const int qi = l / 4; + gemv(ds, T(b + "attn_q.weight"), XA_, qfull_, 12288, ntok); + nb_ = true; + gemv(ds, T(b + "attn_k.weight"), XA_, kcur_, 512, ntok); + nb_ = true; + gemv(ds, T(b + "attn_v.weight"), XA_, vcur_, 512, ntok); + nb_ = true; + gemv(ds, T(b + "indexer.q_proj.weight"), XA_, iqr_, 512, ntok); + nb_ = true; + gemv(ds, T(b + "indexer.k_proj.weight"), XA_, ikr_, 128, ntok); + QsaArgs a{(uint32_t) pos0, 0, (uint32_t) max_cells_, (uint32_t) ntok, eps_}; + mtl::Dispatch d; + d.p = P(lqsa_, "qsa_prep", qsa_c(), qsa_k()); + d.args = {mtl::Arg::B(qfull_), mtl::Arg::B(kcur_), mtl::Arg::B(vcur_), mtl::Arg::B(iqr_), mtl::Arg::B(ikr_), + mtl::Arg::B(W_, T(b + "attn_q_norm.weight").offset), mtl::Arg::B(W_, T(b + "attn_k_norm.weight").offset), + mtl::Arg::B(W_, T(b + "indexer.q_norm.weight").offset), mtl::Arg::B(W_, T(b + "indexer.k_norm.weight").offset), + mtl::Arg::B(cs_), mtl::Arg::B(qcur_), mtl::Arg::B(qidx_), mtl::Arg::B(kq_[(size_t) qi]), + mtl::Arg::B(vq_[(size_t) qi]), mtl::Arg::B(ksc_[(size_t) qi]), mtl::Arg::B(vsc_[(size_t) qi]), + mtl::Arg::B(tail_[(size_t) qi]), mtl::Arg::B(dead_[(size_t) qi]), mtl::Arg::B(pooled_[(size_t) qi]), + mtl::Arg::V(a), mtl::Arg::B(mrope_)}; + d.grid[0] = 33; + d.grid[1] = ntok; + d.tg[0] = 256; + push(ds, d); + if (rec_) rec_->push_back({(int) ds.size() - 1, 0}); + mtl::Dispatch s; + s.p = P(lqsa_, "qsa_score", {}, "qsa_score"); + s.args = {mtl::Arg::B(qidx_), mtl::Arg::B(pooled_[(size_t) qi]), mtl::Arg::B(dead_[(size_t) qi]), mtl::Arg::B(scores_), + mtl::Arg::V(a)}; + s.grid[0] = (uint32_t) (((pos0 + ntok) / 4 + 1 + 7) / 8); + s.grid[1] = ntok; + s.tg[0] = 256; + const bool sel = !(fuse_ && pos0 + ntok <= 2051); + if (sel) { + push(ds, s); + if (rec_) rec_->push_back({(int) ds.size() - 1, 2}); + } + mtl::Dispatch k; + k.p = P(lqsa_, "qsa_topk2", {}, "qsa_topk"); + k.args = {mtl::Arg::B(scores_), mtl::Arg::B(qids_), mtl::Arg::V(a)}; + k.grid[0] = ntok; + k.tg[0] = 1024; + if (sel) { + push(ds, k); + if (rec_) rec_->push_back({(int) ds.size() - 1, 0}); + } + mtl::Dispatch at; + at.p = P(lqsa_, "qsa_attn", {}, "qsa_attn"); + at.args = {mtl::Arg::B(qcur_), mtl::Arg::B(kq_[(size_t) qi]), mtl::Arg::B(vq_[(size_t) qi]), mtl::Arg::B(ksc_[(size_t) qi]), + mtl::Arg::B(vsc_[(size_t) qi]), mtl::Arg::B(qids_), mtl::Arg::B(part_), mtl::Arg::V(a)}; + at.grid[0] = 33; + at.grid[1] = 2; + at.grid[2] = ntok; + at.tg[0] = 256; + push(ds, at); + if (rec_) rec_->push_back({(int) ds.size() - 1, 0}); + mtl::Dispatch m; + m.p = P(lqsa_, "qsa_merge", {}, "qsa_merge"); + QsaArgs am = a; + am.n_tok = MAXT; // the plane stride + m.args = {mtl::Arg::B(part_), mtl::Arg::B(qfull_), mtl::Arg::B(XQ_.b), mtl::Arg::V(am)}; + m.grid[0] = 24; + m.grid[1] = ntok; + m.tg[0] = 256; + push(ds, m); + if (rec_) rec_->push_back({(int) ds.size() - 1, 1}); + gemv(ds, T(b + "attn_output.weight"), XQ_, bo_, N, ntok); + } + // ---- the MoE + gr_read(ds, b + "hc_ffn", true, XF_, false, ntok); + const gguf::Tensor& trt = T(b + "ffn_gate_inp.weight"); + const bool rf = routef_ && (trt.type == ref::BF16 || trt.type == ref::F32); + if (!rf) { + gemv(ds, trt, XF_, logits_, 512, ntok); + nb_ = true; + } + if (stream_ && st_pred_ && l + 1 < 48) { // the next layer's routing guessed from this layer's FFN input + nb_ = !rf; // beside the router GEMV; with router_route it is the first reader of XF_ here: a barrier + gemv(ds, T("blk." + std::to_string(l + 1) + ".ffn_gate_inp.weight"), XF_, predL_, 512, ntok, + (size_t) l * MAXT * 512 * 4); + if (predL2_.ptr && l + 2 < 48) { + nb_ = true; + gemv(ds, T("blk." + std::to_string(l + 2) + ".ffn_gate_inp.weight"), XF_, predL2_, 512, ntok, + (size_t) l * MAXT * 512 * 4); + } + nb_ = true; + } + gemv(ds, T(b + "ffn_gate_shexp.weight"), XF_, gsh_, NFF, ntok); + nb_ = true; + gemv(ds, T(b + "ffn_up_shexp.weight"), XF_, ush_, NFF, ntok); + nb_ = true; + gemv(ds, T(b + "ffn_gate_inp_shexp.weight"), XF_, sg_, 1, ntok); + { + MoeArgs a{}; + const gguf::Tensor &tg_ = T(b + "ffn_gate_exps.weight"), &tu = T(b + "ffn_up_exps.weight"), + &td = T(b + "ffn_down_exps.weight"); + a.gate_off = tg_.offset; + a.up_off = tu.offset; + a.down_off = td.offset; + if (stream_) { // offsets inside the expert's arena slot + a.gate_off = 0; + a.up_off = st_->up_in_slot(l); + a.down_off = st_->down_in_slot(l); + } + a.gu_row = (uint32_t) ref::row_bytes(tg_.type, N); + a.d_row = (uint32_t) ref::row_bytes(td.type, NFF); + a.gu_stride = (uint64_t) a.gu_row * NFF; + a.d_stride = (uint64_t) a.d_row * N; + a.n_embd = N; + a.n_ff = NFF; + a.n_tok = ntok; + a.topk = TOPK; + a.n_expert = NEXP; + const bool dq2 = td.type == ref::Q2_0; + const int gl = 32, gr = 1, gs = 4, ds_ = 4; + // the down tile: Q2_0 8,1; else 4,2 - but on the M4 (no M5 layout) Q5_1 4,1 and Q8_0 8,1 (4,2 spills there: + // 24-36 GB/s, mac-kern 513fc615) + const bool m4 = !m5_layout(); + const int dl = dq2 || (m4 && td.type == ref::Q8_0) ? 8 : 4, + dr = dq2 || (m4 && (td.type == ref::Q8_0 || td.type == ref::Q5_1)) ? 1 : 2; + a.gx_gu = NFF / (gs * (32 / gl) * gr); + a.gx_dn = N / (ds_ * (32 / dl) * dr); + mtl::Dispatch r; + if (rf) { + // the router GEMV + moe_route (bitwise both), beside the shared expert's GEMVs + r.p = P(lib_, "router_route_" + std::to_string(trt.type), mtl::Constants().i(0, ntok), "router_route_" + std::to_string(trt.type) + "#" + std::to_string(ntok)); + GemvArgs ga{(uint32_t) N, 512, (uint32_t) ntok, (uint32_t) ref::row_bytes(trt.type, N), (uint32_t) N, 512}; + r.args = {mtl::Arg::B(W_, trt.offset), mtl::Arg::B(XF_.b, 0), mtl::Arg::B(XF_.b, XF_.plane_bytes() * 4), + mtl::Arg::B(logits_), mtl::Arg::V(ga), mtl::Arg::B(ids_), mtl::Arg::B(wts_), mtl::Arg::B(plan_), + mtl::Arg::V(a), mtl::Arg::B(rcounter_)}; + r.grid[0] = 512 / 16; + r.tg[0] = 512; + nb_ = true; + } else { + r.p = P(lib_, "moe_route", {}, "moe_route"); + r.args = {mtl::Arg::B(logits_), mtl::Arg::B(ids_), mtl::Arg::B(wts_), mtl::Arg::B(plan_), mtl::Arg::V(a)}; + r.tg[0] = 512; + } + push(ds, r); + { + GlueArgs ga{NFF, MAXT, N, TOPK}; + mtl::Dispatch d; + d.p = P(lib_, "swiglu_prep", {}, "swiglu_prep"); + d.args = {mtl::Arg::B(gsh_), mtl::Arg::B(ush_), mtl::Arg::B(XH_.b), mtl::Arg::V(ga)}; + d.grid[0] = NFF / 16; + d.grid[1] = ntok; + d.tg[0] = 16; + nb_ = !rf; // with router_route the shared GEMVs are not behind a barrier yet: this one waits for them + push(ds, d); + } + const std::string gun = "moe_gu_" + std::to_string(tg_.type) + "_" + std::to_string(gl) + "_" + std::to_string(gr) + + "_" + std::to_string(gs); + const std::string dnn = "moe_down_" + std::to_string(dq2 ? 142 : td.type) + "_" + std::to_string(dl) + "_" + + std::to_string(dr) + "_" + std::to_string(ds_); + mtl::Dispatch g; + const mtl::Buffer& EW = stream_ ? st_->chunk(0) : W_; + // function constant 23 (QUANT_CTAB): the i-quant grids from constant memory, no threadgroup copy (same values) + const bool ct = metal_ctab(); + mtl::Constants ac = stream_ ? mtl::Constants().b(20, true) : mtl::Constants(); + ac.b(23, ct); + const std::string ak = std::string(stream_ ? "#arena" : "") + (ct ? "#ct" : ""); + g.p = P(lib_, gun, ac, gun + ak); + g.args = {mtl::Arg::B(EW), mtl::Arg::B(XF_.b, XF_.plane_bytes() * xkind(tg_.type)), mtl::Arg::B(h_), mtl::Arg::B(plan_), + mtl::Arg::V(a), mtl::Arg::B(XF_.b, XF_.plane_bytes() * 4)}; + if (stream_) + for (int c = -1; c < 3; ++c) + g.args.push_back(c < 0 ? mtl::Arg::B(st_->smap(), (size_t) l * 512 * 4) : mtl::Arg::B(st_->chunk(c + 1))); + g.tg[0] = 32 * gs; + g.indirect = &plan_; + g.ind_off = P_IGU * 4; + if (cuts_) cuts_->push_back((int) ds.size()); // the host's turn: this layer's experts put in place + push(ds, g); + nb_ = true; + gemv(ds, T(b + "ffn_down_shexp.weight"), XH_, ysh_, N, ntok); + mtl::Dispatch dd; + dd.p = P(lib_, dnn, ac, dnn + ak); + dd.args = {mtl::Arg::B(EW), mtl::Arg::B(h_), mtl::Arg::B(ye_), mtl::Arg::B(plan_), mtl::Arg::V(a), mtl::Arg::B(h_)}; + if (stream_) + for (int c = -1; c < 3; ++c) + dd.args.push_back(c < 0 ? mtl::Arg::B(st_->smap(), (size_t) l * 512 * 4) : mtl::Arg::B(st_->chunk(c + 1))); + dd.tg[0] = 32 * ds_; + dd.indirect = &plan_; + dd.ind_off = P_IDN * 4; + push(ds, dd); + } + { + GlueArgs a{N, (uint32_t) ntok, N, TOPK}; + mtl::Dispatch d; + d.p = P(lib_, "moe_combine_sh", {}, "moe_combine_sh"); + d.args = {mtl::Arg::B(ye_), mtl::Arg::B(plan_), mtl::Arg::B(ysh_), mtl::Arg::B(sg_), mtl::Arg::B(bo_), mtl::Arg::V(a)}; + d.grid[0] = (ntok * N + 255) / 256; + d.tg[0] = 256; + push(ds, d); + } +} + +namespace { +float bf16f(uint16_t h) { uint32_t i = (uint32_t) h << 16; float f; std::memcpy(&f, &i, 4); return f; } +// ple.cu's gnorm_kernel: per stream, the squares rounded in f32, summed in double +void gnorm(const float* x, const float* w, float* y, int n_embd, int hc, float eps) { + for (int c = 0; c < hc; ++c) { + const float* xc = x + (size_t) c * n_embd; + double acc = 0.0; + for (int d = 0; d < n_embd; ++d) { const float sq = xc[d] * xc[d]; acc += (double) sq; } + const float mean = (float) (acc / (double) n_embd); + const float scale = 1.0f / std::sqrt(mean + eps); + for (int d = 0; d < n_embd; ++d) y[(size_t) c * n_embd + d] = xc[d] * scale * w[(size_t) c * n_embd + d]; + } +} +} // namespace + +// The PLE block (ple.hpp) for the window's T rows on the CPU, after layer 0 (its pending write applied to R): R += +// gated + silu(conv); the normalized rows go to last_norm_ (the history advances at commit). +void Window::ple_cpu(int Tn) { + using namespace strata::kernels; + const int hc_dim = NG_HC_DIM; + const float* nkey = (const float*) ((const uint8_t*) W_.ptr + T("blk.1.ple_norm_key.weight").offset); + const float* nqry = (const float*) ((const uint8_t*) W_.ptr + T("blk.1.ple_norm_query.weight").offset); + const float* nconv = (const float*) ((const uint8_t*) W_.ptr + T("blk.1.ple_norm_conv.weight").offset); + const uint16_t* kw = kw_host(); + std::vector key(hc_dim), query(hc_dim), gated(hc_dim), norm(hc_dim), hist = ple_hist_; + for (int t = 0; t < Tn; ++t) { + float* hidden = R_.as() + (size_t) t * HC * N; + gnorm(pkey_.as() + (size_t) t * hc_dim, nkey, key.data(), N, HC, NG_RMS_EPS); + gnorm(hidden, nqry, query.data(), N, HC, NG_RMS_EPS); + const float* value = pval_.as() + (size_t) t * N; + float gate[HC]; + const float inv_sqrt_n = 1.0f / std::sqrt((float) N); + for (int c = 0; c < HC; ++c) { + double acc = 0.0; + for (int d = 0; d < N; ++d) acc += (double) (key[(size_t) c * N + d] * query[(size_t) c * N + d]); + const float s = (float) acc * inv_sqrt_n; + const float mag = std::sqrt(std::max(std::fabs(s), 1e-6f)); + const float sgn = s > 0.0f ? 1.0f : (s < 0.0f ? -1.0f : 0.0f); + gate[c] = 1.0f / (1.0f + std::exp(-(sgn * mag))); + } + for (int i = 0; i < hc_dim; ++i) gated[(size_t) i] = value[i % N] * gate[i / N]; + gnorm(gated.data(), nconv, norm.data(), N, HC, NG_RMS_EPS); + for (int c = 0; c < hc_dim; ++c) { + float acc = 0.0f; + for (int k = 0; k < PLE_CONV_KERNEL; ++k) { + const int row = NG_HIST - (PLE_CONV_KERNEL - 1 - k) * NGRAM_SIZE; + const float v = row == NG_HIST ? norm[(size_t) c] : hist[(size_t) row + (size_t) NG_HIST * c]; + acc += ref::f16_to_f32(kw[k + PLE_CONV_KERNEL * c]) * v; + } + const float conv = acc / (1.0f + std::exp(-acc)); + hidden[c] = hidden[c] + gated[(size_t) c] + conv; + } + std::memcpy(last_norm_.data() + (size_t) t * hc_dim, norm.data(), (size_t) hc_dim * 4); + // the next row of this window sees this one in its history + for (int c = 0; c < hc_dim; ++c) { + float* col = hist.data() + (size_t) c * NG_HIST; + for (int r = 0; r + 1 < NG_HIST; ++r) col[r] = col[r + 1]; + col[NG_HIST - 1] = norm[(size_t) c]; + } + } +} + +bool Window::run(int Tn, const int32_t* tokens, int64_t pos0, bool head, int32_t* out, std::string& err) { + mtp_src_ = nullptr; + if (Tn < 1 || Tn > MAXT || (head && Tn > max_t_)) { err = "metal window: window size out of range"; return false; } + if (pos0 + Tn + 1 >= max_cells_) { err = "metal window: the window runs past the context"; return false; } + const double t0 = now_ms(); + // ---- the embeddings (CPU dequant of the token rows straight into the shared buffer), broadcast to the streams + const gguf::Tensor& te = T("token_embd.weight"); + const size_t rb = ref::row_bytes(te.type, N); + for (int t = 0; t < Tn; ++t) { + float* r = R_.as() + (size_t) t * HC * N; + if (const float* img = img_row(pos0 + t)) std::memcpy(r, img, (size_t) N * 4); + else ref::dequant(te.type, (const uint8_t*) W_.ptr + te.offset + (size_t) tokens[t] * rb, r, N); + for (int c = 1; c < HC; ++c) std::memcpy(r + (size_t) c * N, r, (size_t) N * 4); + } + // ---- the PLE rows (the table read is the shared host code's), projected on the GPU + if (ple_on_) { + strata::core::SessionState& ss = *ss_; + uint32_t rows[MAXT * strata::kernels::PLE_N_HEADS]; + int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]}; + for (int t = 0; t < Tn; ++t) { + strata::kernels::ngram_rows(&tokens[t], prev, 1, ss.ple.consts, rows + t * strata::kernels::PLE_N_HEADS); + prev[0] = prev[1]; + prev[1] = tokens[t]; + } + if (!ss.ple.table->gather_batch(rows, (size_t) Tn, emb_.as(), err)) return false; + } + tp_pre_ = now_ms(); + const bool sel = !(fuse_ && pos0 + Tn <= 2051); + if (sel) qdirty_ = true; + else if (qdirty_) { + for (int t = 0; t < MAXT; ++t) + for (int c = 0; c < 2051; ++c) qids_.as()[t * 2051 + c] = c; + qdirty_ = false; + } + const int key = (((((Tn * 2 + (head ? 1 : 0)) * 2 + hp_) * (MAXT + 1)) + pend_fold_) * 2 + (sel ? 1 : 0)) * 2 + + (mrope_on() ? 1 : 0); + mrope_sync(pos0, Tn); + const int fold_n = pend_fold_; + pend_fold_ = 0; + win_head_ = head; + auto hit = wcache_.find(key); + if (hit != wcache_.end()) { + // the same window shape: only the positions change (QSA's cells, the score grid) + Cached& c = hit->second; + for (const auto& [i, kind] : c.qsa) { + mtl::Dispatch& d = c.ds[(size_t) i]; + QsaArgs a{(uint32_t) pos0, 0, (uint32_t) max_cells_, (uint32_t) (kind == 1 ? MAXT : Tn), eps_}; + // the QsaArgs: the dispatch's last inline argument (qsa_prep has the M-RoPE table bound after it) + mtl::Arg* qa = nullptr; + for (auto& g : d.args) + if (!g.bytes.empty()) qa = &g; + std::memcpy(qa->bytes.data(), &a, sizeof a); + if (kind == 2) d.grid[0] = (uint32_t) (((pos0 + Tn) / 4 + 1 + 7) / 8); + } + seg_T_ = Tn; + const double r0 = now_ms(); + last_gpu_ms_ = 1000.0 * run_ds(c); + { + static const int kt = std::getenv("STRATA_METAL_KPROF") ? std::atoi(std::getenv("STRATA_METAL_KPROF")) : 0; + static int seen = 0; + if (kt == Tn && head && ++seen == 20 && !stream_) kprof(c.ds, Tn); + } + tp_rg_ = now_ms() - r0; + last_n_disp_ = (int) c.ds.size(); + return finish(Tn, tokens, pos0, head, out, t0); + } + if (stream_ && !st_->ready() && !stream_arena(err)) return false; + Cached& cw = wcache_[key]; + rec_ = &cw.qsa; + cuts_ = stream_ ? &cw.cuts : nullptr; + std::vector& ds = cw.ds; + nb_ = false; + if (fold_n > 0) fold(ds, fold_n, 1 - hp_); // the last window's commit (hp_ already turned) + if (ple_on_) { + xprep(ds, emb_, XE_, N); + gemv(ds, T("blk.1.ple_key.weight"), XE_, pkey_, 10240, Tn); + nb_ = true; + gemv(ds, T("blk.1.ple_value.weight"), XE_, pval_, N, Tn); + } + cur_inj_ = 0; + layer(ds, 0, Tn, pos0); + if (ple_on_) { + // layer 0's FFN write applied to R (gr_norm with apply writes R back; its xn is not used) + const gguf::Tensor& tn = T("blk.1.hc_attn_norm.weight"); + GrArgs a{N, HC, LR, (uint32_t) Tn, 1u, eps_}; + mtl::Dispatch d1; + d1.p = P(lib_, "gr_norm", {}, "gr_norm"); + d1.args = {mtl::Arg::B(R_), mtl::Arg::B(bo_), mtl::Arg::B(inj_[cur_inj_]), mtl::Arg::B(W_, tn.offset), mtl::Arg::B(xn_), + mtl::Arg::V(a)}; + d1.grid[0] = HC; + d1.grid[1] = Tn; + d1.tg[0] = 256; + push(ds, d1); + // the PLE block on the GPU (msl/ple.metal): norms, gate, conv, the residual update + struct PleArgs { uint32_t n_embd, hc; float eps; } pa{N, HC, strata::kernels::NG_RMS_EPS}; + auto off = [&](const char* n) { return T(n).offset; }; + mtl::Dispatch g1, g2, g3, g4; + g1.p = P(lple_, "ple_gnorm", {}, "ple_gnorm"); + g1.args = {mtl::Arg::B(pkey_), mtl::Arg::B(W_, off("blk.1.ple_norm_key.weight")), mtl::Arg::B(keyn_), mtl::Arg::V(pa)}; + g1.grid[0] = HC; g1.grid[1] = Tn; g1.tg[0] = 256; + push(ds, g1); + g2.p = g1.p; + g2.args = {mtl::Arg::B(R_), mtl::Arg::B(W_, off("blk.1.ple_norm_query.weight")), mtl::Arg::B(qn_), mtl::Arg::V(pa)}; + g2.grid[0] = HC; g2.grid[1] = Tn; g2.tg[0] = 256; + nb_ = true; // beside the key norm + push(ds, g2); + g3.p = P(lple_, "ple_gate_norm", {}, "ple_gate_norm"); + g3.args = {mtl::Arg::B(keyn_), mtl::Arg::B(qn_), mtl::Arg::B(pval_), mtl::Arg::B(W_, off("blk.1.ple_norm_conv.weight")), + mtl::Arg::B(gated_), mtl::Arg::B(normW_), mtl::Arg::V(pa)}; + g3.grid[0] = HC; g3.grid[1] = Tn; g3.tg[0] = 256; + push(ds, g3); + g4.p = P(lple_, "ple_conv_add", {}, "ple_conv_add"); + g4.args = {mtl::Arg::B(pleHist_), mtl::Arg::B(normW_), kw_arg(), + mtl::Arg::B(gated_), mtl::Arg::B(R_), mtl::Arg::V(pa)}; + g4.grid[0] = HC * N / 256; g4.grid[1] = Tn; g4.tg[0] = 256; + push(ds, g4); + } + for (int l = 1; l < 48; ++l) layer(ds, l, Tn, pos0); + // ---- the final mixer and the head + gr_read(ds, "output_hc", true, XA_, true, Tn); + if (head) gemv(ds, T("output.weight"), XA_, lm_, (size_t) n_vocab_, Tn); + if (head) { + ArgArgs a{(uint32_t) n_vocab_, 120}; + mtl::Dispatch d1, d2; + d1.p = P(lsmp_, "argmax_part", {}, "argmax_part"); + d1.args = {mtl::Arg::B(lm_), mtl::Arg::B(apv_), mtl::Arg::B(api_), mtl::Arg::V(a)}; + d1.grid[0] = 120; + d1.grid[1] = Tn; + d1.tg[0] = 256; + push(ds, d1); + d2.p = P(lsmp_, "argmax_final", {}, "argmax_final"); + d2.args = {mtl::Arg::B(apv_), mtl::Arg::B(api_), mtl::Arg::B(tokout_), mtl::Arg::V(a)}; + d2.grid[0] = Tn; + d2.tg[0] = 256; + push(ds, d2); + } + rec_ = nullptr; + cuts_ = nullptr; + seg_T_ = Tn; + const double r0 = now_ms(); + last_gpu_ms_ = 1000.0 * run_ds(cw); + tp_rg_ = now_ms() - r0; + last_n_disp_ = (int) ds.size(); + return finish(Tn, tokens, pos0, head, out, t0); +} + +double Window::run_ds(Cached& c) { + if (!stream_) return cx_->run_graph(c.ds); + return cx_->run_graph_seg(c.ds, c.cuts, [](void* u, int s) { ((Window*) u)->at_cut(s); }, this); +} + +namespace { +Window* g_stream_window = nullptr; +void stream_atexit() { + if (g_stream_window) g_stream_window->stream_report(stderr); +} +} // namespace + +// The arena, once the rest is allocated (the MTP layer loads after init): what the GPU working set and the RAM leave +// with STRATA_METAL_KEEP_FREE_GB kept for macOS (default: 7 GB, or 15% of the RAM when that is more - the M5 Max +// froze with an 89 GB arena and 7 GB left beside a 50 GB n-gram table read through the file cache; arena_budget.h); +// STRATA_METAL_ARENA_GB sets it. +bool Window::stream_arena(std::string& err) { + uint64_t phys = 0; + size_t len = sizeof phys; + sysctlbyname("hw.memsize", &phys, &len, nullptr, 0); + const double gb = 1e9; + if (!(std::getenv("STRATA_METAL_KEEP_HOST_WEIGHTS") && std::string(std::getenv("STRATA_METAL_KEEP_HOST_WEIGHTS")) == "1")) { + const uint64_t g = strata::gpu::purge_device_allocations(32u << 20); + std::fprintf(stderr, "strata metal stream: %.2f GB of the host code's device weight copies given back (unused by the " + "Metal window)\n", g / 1e9); + } + const double used = (double) cx_->allocated(); + // what macOS gives now without paging anything out (arena_avail: free, purgeable, the clean file cache; not other + // programs' inactive memory, freed only by compressing or swapping it) + auto avail_now = [&]() -> double { + vm_statistics64_data_t vs; + mach_msg_type_number_t cnt = HOST_VM_INFO64_COUNT; + if (host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t) &vs, &cnt) == KERN_SUCCESS) { + const double pg = (double) vm_page_size; + return arena_avail(vs.free_count * pg, vs.purgeable_count * pg, vs.inactive_count * pg, vs.speculative_count * pg, + vs.external_page_count * pg); + } + return (double) phys - (double) cx_->allocated(); + }; + ArenaMem am; // arena_budget.h: the rule, testable + am.phys = (double) phys; + am.working_set = (double) cx_->recommended_working_set(); + am.allocated = used; + am.available = avail_now(); + if (ss_ && ss_->ple.table && ss_->ple.table->mode() == strata::kernels::PleIo::Mmap) + am.ple_mapped = (double) ss_->ple.table->rows() * 192.0; // a row is at most 192 bytes (Q8_0 + its scale) + if (const char* e = std::getenv("STRATA_METAL_KEEP_FREE_GB")) am.keep_gb = std::atof(e); + if (const char* e = std::getenv("STRATA_METAL_ARENA_GB")) am.arena_gb = std::atof(e); + const double keep = arena_keep(am); + const double avail = am.available; + double budget = arena_budget(am); + if (budget < 2 * gb) { + std::fprintf(stderr, "strata metal stream: only %.1f GB left for the expert arena (the GPU working set %.1f GB, RAM %.1f GB, " + "%.1f GB allocated): expect a low hit rate\n", budget / gb, cx_->recommended_working_set() / gb, + phys / gb, used / gb); + budget = std::max(budget, 1.0 * gb); + } + std::string prof; + if (const char* e = std::getenv("STRATA_METAL_EXPERT_PROFILE")) prof = e; + else prof = std::string(STRATA_METAL_DATA_DEFAULT) + "/expert-profile.bin"; + std::fprintf(stderr, "strata metal stream: %.2f GB allocated before the arena; RAM %.1f GB (%.1f GB available, %.1f GB kept " + "for macOS), GPU working set %.1f GB\n", used / gb, phys / gb, avail / gb, keep / gb, + cx_->recommended_working_set() / gb); + const char* epg = std::getenv("STRATA_METAL_PROMPT_GEMM"); + const bool pg_on = !(epg && std::string(epg) == "0"); + bool minimal = false; // the arena's least layout (the min slots) is not shrunk further: it goes ahead, filled in steps + for (int tries = 0;; ++tries) { + const double planned = budget; + std::function recheck = [&]() -> uint64_t { return (uint64_t) arena_shrink(am, planned, avail_now()); }; + if (st_->make_arena(*cx_, (uint64_t) budget, prof, pg_on ? 576 : 64, err, minimal ? std::function() : recheck, + [&](uint64_t step) { return arena_grow(am, avail_now(), (double) step); })) + break; + if (st_->shrink_to() == 0 || tries == 4) return false; + if ((double) st_->shrink_to() + 64.0 * (1 << 20) >= budget) minimal = true; // no smaller layout than this one + std::fprintf(stderr, "strata metal stream: less memory is free than when the arena was planned: %.1f -> %.1f GB\n", + budget / gb, st_->shrink_to() / gb); + budget = (double) st_->shrink_to(); + } + if (pg_on && !prompt_gemm_init(err)) return false; + g_stream_window = this; + std::atexit(stream_atexit); + return true; +} + +void Window::logpos(int Tn, const int32_t* tokens, int64_t pos0, bool head) { + static const char* path = std::getenv("STRATA_METAL_LOGPOS"); + if (path == nullptr || !head) return; + if (logpos_ == nullptr) logpos_ = std::fopen(path, "ab"); + if (logpos_ == nullptr) return; + if (lp_pend_ && Tn >= 1 && pos0 == lp_pos_ + 1) { + const int32_t tgt = tokens[0]; + std::fprintf(logpos_, "%lld\t%d\t%.6f\t%d\t0\t0\t0\t0", (long long) (lp_pos_ - lp_first_), tgt, + (double) lp_row_[(size_t) tgt] - lp_lse_, lp_arg_); + for (const auto& [v, id] : lp_top_) std::fprintf(logpos_, "\t%d:%.6f", id, (double) v - lp_lse_); + std::fputc('\n', logpos_); + std::fflush(logpos_); + } + lp_pend_ = false; + if (Tn != 1) return; + if (lp_first_ < 0) lp_first_ = pos0; + const float* lg = lm_.as(); + lp_row_.assign(lg, lg + n_vocab_); + float mx = lg[0]; + int32_t am = 0; + for (int64_t i = 1; i < n_vocab_; ++i) if (lg[i] > mx) { mx = lg[i]; am = (int32_t) i; } + double s = 0.0; + for (int64_t i = 0; i < n_vocab_; ++i) s += std::exp((double) (lg[i] - mx)); + lp_lse_ = (double) mx + std::log(s); + lp_arg_ = am; + lp_top_.clear(); + for (int64_t i = 0; i < n_vocab_; ++i) lp_top_.push_back({lg[i], (int32_t) i}); + std::partial_sort(lp_top_.begin(), lp_top_.begin() + 64, lp_top_.end(), + [](const auto& a, const auto& b) { return a.first > b.first || (a.first == b.first && a.second < b.second); }); + lp_top_.resize(64); + lp_pos_ = pos0; + lp_pend_ = true; +} + +void Window::kprof(const std::vector& ds, int Tn) { + std::map pname; + for (const auto& [k, v] : pcache_) pname[&v] = k.substr(0, k.find('#')); + std::map tname; + for (const auto& [k, v] : f_.tensors) { + std::string n = k; + if (n.rfind("blk.", 0) == 0) n = n.substr(n.find('.', 4) + 1); + tname[v.offset] = n; + } + std::map q8name; + for (const auto& [k, v] : q8off_) { + std::string n = k; + if (n.rfind("blk.", 0) == 0) n = n.substr(n.find('.', 4) + 1); + q8name[v] = n; + } + std::map> by; + for (const auto& d : ds) { + std::string c = pname.count(d.p) ? pname[d.p] : "?"; + if (!d.args.empty() && d.args[0].buf == &W_ && tname.count(d.args[0].off) && c.rfind("moe_", 0) != 0) + c += " " + tname[d.args[0].off]; + else if (!d.args.empty() && d.args[0].buf == &Q8_) c += " " + (q8name.count(d.args[0].off) ? q8name[d.args[0].off] : std::string("Q8")); + mtl::Dispatch x = d; + x.barrier = true; + by[c].push_back(x); + } + auto med = [&](const std::vector& v) { + std::vector t; + for (int i = 0; i < 7; ++i) t.push_back(1000.0 * cx_->run_graph(v)); + std::sort(t.begin(), t.end()); + return t[3]; + }; + const double all = med(ds); + std::vector> rows; + double sum = 0; + for (const auto& [c, v] : by) { + const double m = med(v); + sum += m; + rows.push_back({m, c + " x" + std::to_string(v.size())}); + } + std::sort(rows.rbegin(), rows.rend()); + std::fprintf(stderr, "strata metal kprof: window T%d, %zu dispatches, GPU %.3f ms; classes alone (serialized) sum %.3f ms:\n", + Tn, ds.size(), all, sum); + for (const auto& [m, c] : rows) std::fprintf(stderr, "strata metal kprof: %8.3f ms %5.1f%% %s\n", m, 100.0 * m / sum, c.c_str()); +} + +Window::~Window() { + if (logpos_) std::fclose(logpos_); + if (std::getenv("STRATA_METAL_PROFILE") == nullptr) return; + auto line = [](const char* what, const Prof& x) { + if (x.n == 0) return; + std::fprintf(stderr, "strata metal profile: %-10s %6lld x %.3f ms: host before %.3f, run_graph %.3f (GPU %.3f, so " + "encode/submit/wait %.3f), patch+finish %.3f\n", what, (long long) x.n, x.all / x.n, x.pre / x.n, + x.rg / x.n, x.gpu / x.n, (x.rg - x.gpu) / x.n, x.fin / x.n); + }; + for (const auto& [k, x] : prof_) { + const std::string w = "window T" + std::to_string(k / 2) + (k % 2 ? "" : " nohead"); + line(w.c_str(), x); + } + line("commit", cprof_); + line("draft", dprof_); +} + +bool Window::finish(int Tn, const int32_t* tokens, int64_t pos0, bool head, int32_t* out, double t0) { + ++win_n_[Tn]; + win_ms_[Tn] += now_ms() - t0; + win_gpu_[Tn] += last_gpu_ms_; + static const bool prof = std::getenv("STRATA_METAL_PROFILE") != nullptr; + if (prof) { + Prof& x = prof_[Tn * 2 + (head ? 1 : 0)]; + const double t1 = now_ms(); + ++x.n; x.pre += tp_pre_ - t0; x.rg += tp_rg_; x.gpu += last_gpu_ms_; x.fin += t1 - tp_pre_ - tp_rg_; + x.all += t1 - t0; + } + logpos(Tn, tokens, pos0, head); + if (Tn == 1 || partial_) hp_ = 1 - hp_; // the window committed its first row (or all of them) in the step + last_head_ = head; + for (int t = 0; t < Tn; ++t) out[t] = head ? tokout_.as()[t] : -1; + last_T_ = Tn; + for (int t = 0; t < Tn; ++t) last_tokens_[t] = tokens[t]; + static const bool trace = std::getenv("STRATA_METAL_TRACE") != nullptr; + if (trace && head) { + // the pick and its margin over the runner-up (a near tie says a backend difference may flip it) + const float* lg = lm_.as(); + int i1 = -1, i2 = -1; + for (int i = 0; i < n_vocab_; ++i) { + if (i1 < 0 || lg[i] > lg[i1]) { i2 = i1; i1 = i; } + else if (i2 < 0 || lg[i] > lg[i2]) i2 = i; + } + std::fprintf(stderr, "strata metal: window pos %lld token %d -> %d (top %d %.4f, 2nd %d %.4f, margin %.4f) %.2f ms (GPU %.2f ms, %d dispatches)\n", + (long long) pos0, tokens[0], out[0], i1, lg[i1], i2, lg[i2], lg[i1] - lg[i2], now_ms() - t0, last_gpu_ms_, last_n_disp_); + } + return true; +} + +void Window::fold(std::vector& ds, int n_keep, int hp) { + const size_t off = partial_ ? 1 : 0; // rows 1.. (row 0 was committed in the window's step) + for (int l = 0; l < 48; ++l) { + if (l % 4 == 3) continue; + const int gi = l - l / 4; + const std::string b = "blk." + std::to_string(l) + "."; + const size_t o_qkv = ((size_t) gi * MAXT + off) * 10240 * 4, o_ab = ((size_t) gi * MAXT + off) * 48 * 4, + o_z = ((size_t) gi * MAXT + off) * 6144 * 4; + GdnArgs a{16, 48, 10240, 1u, eps_, 0}; + mtl::Dispatch d; + d.p = P(lgdn_, "gdn_step", mtl::Constants().i(2, n_keep), "gdn_step#" + std::to_string(n_keep)); + d.args = {mtl::Arg::B(gst_[(size_t) gi]), mtl::Arg::B(ghist_[hp][(size_t) gi]), mtl::Arg::B(qkvL_, o_qkv), + mtl::Arg::B(alL_, o_ab), mtl::Arg::B(beL_, o_ab), mtl::Arg::B(zL_, o_z), + mtl::Arg::B(W_, T(b + "ssm_conv1d.weight").offset), mtl::Arg::B(W_, T(b + "ssm_dt.bias").offset), + mtl::Arg::B(W_, T(b + "ssm_a").offset), mtl::Arg::B(W_, T(b + "ssm_norm.weight").offset), + mtl::Arg::B(ydump_), mtl::Arg::V(a), mtl::Arg::B(ghist_[1 - hp][(size_t) gi])}; + d.grid[0] = 48; + d.tg[0] = 512; + nb_ = true; // the layers' folds are independent of each other + push(ds, d); + } + nb_ = false; // what follows reads the folded state: a barrier +} + +bool Window::checkpoint_save(strata::core::ConversationCheckpoint& c, std::string& err) { + (void) err; + if (pend_fold_ > 0) { // the last commit's fold first: the checkpoint is the state after it + std::vector ds; + nb_ = false; + fold(ds, pend_fold_, 1 - hp_); + cx_->run_graph(ds); + pend_fold_ = 0; + } + const size_t gs = 4 * 128 * 48 * 128, hs = 4 * 10240 * 3, ts = 4 * 4 * 128, dsz = 4 * 128; + c.gdn.resize(gst_.size() * (gs + hs)); + for (size_t i = 0; i < gst_.size(); ++i) { + std::memcpy(c.gdn.data() + i * (gs + hs), gst_[i].ptr, gs); + std::memcpy(c.gdn.data() + i * (gs + hs) + gs, ghist_[hp_][i].ptr, hs); + } + c.ple.assign((const uint8_t*) pleHist_.ptr, (const uint8_t*) pleHist_.ptr + 4 * 9 * 10240); + c.tails.resize(tail_.size() * ts); + c.dead.resize(dead_.size() * dsz); + for (size_t j = 0; j < tail_.size(); ++j) { + std::memcpy(c.tails.data() + j * ts, tail_[j].ptr, ts); + std::memcpy(c.dead.data() + j * dsz, dead_[j].ptr, dsz); + } + c.block_pos.clear(); + return true; +} + +void Window::reset() { + pend_fold_ = 0; + last_T_ = 0; + auto zero = [](const mtl::Buffer& b, size_t n) { std::memset(b.ptr, 0, n); }; + for (size_t i = 0; i < gst_.size(); ++i) { + zero(gst_[i], 4 * 128 * 48 * 128); + zero(ghist_[0][i], 4 * 10240 * 3); + zero(ghist_[1][i], 4 * 10240 * 3); + } + zero(pleHist_, 4 * 9 * 10240); + for (size_t j = 0; j < tail_.size(); ++j) { + zero(tail_[j], 4 * 4 * 128); + zero(dead_[j], 4 * 128); + } + for (size_t j = 0; j < mtail_.size(); ++j) { + zero(mtail_[j], 4 * 4 * 128); + zero(mdead_[j], 4 * 128); + } +} + +bool Window::checkpoint_restore(const strata::core::ConversationCheckpoint& c, std::string& err) { + const size_t gs = 4 * 128 * 48 * 128, hs = 4 * 10240 * 3, ts = 4 * 4 * 128, dsz = 4 * 128; + if (c.gdn.size() != gst_.size() * (gs + hs) || c.ple.size() != (size_t) 4 * 9 * 10240 || + c.tails.size() != tail_.size() * ts || c.dead.size() != dead_.size() * dsz) { + err = "metal window: the checkpoint is not this engine's (sizes differ)"; + return false; + } + pend_fold_ = 0; // the restored state replaces whatever was pending + last_T_ = 0; + for (size_t i = 0; i < gst_.size(); ++i) { + std::memcpy(gst_[i].ptr, c.gdn.data() + i * (gs + hs), gs); + std::memcpy(ghist_[hp_][i].ptr, c.gdn.data() + i * (gs + hs) + gs, hs); + } + std::memcpy(pleHist_.ptr, c.ple.data(), c.ple.size()); + for (size_t j = 0; j < tail_.size(); ++j) { + std::memcpy(tail_[j].ptr, c.tails.data() + j * ts, ts); + std::memcpy(dead_[j].ptr, c.dead.data() + j * dsz, dsz); + } + return true; +} + +bool Window::commit(int n_keep, std::string& err) { + if (n_keep < 1 || n_keep > last_T_) { err = "metal window: commit count out of range"; return false; } + using namespace strata::kernels; + if (last_T_ > 1) { + // the GDN layers: the kept prefix folded into the state (gdn_step over n_keep tokens from the window's own + // inputs, with commit; bitwise the window's trajectory). K/V and indexer cells past the prefix are rewritten + // when those positions run again, before anything reads them. + static const bool lazy = !(std::getenv("STRATA_METAL_LAZY_FOLD") && std::string(std::getenv("STRATA_METAL_LAZY_FOLD")) == "0"); + int nf = n_keep; + if (partial_) { + if (!last_head_) { // the prompt's window committed every row in its step + if (n_keep != last_T_) { err = "metal window: a prompt window commits all its rows"; return false; } + nf = 0; + } else { + nf = n_keep - 1; // row 0 is in + } + } + if (nf > 0) { + if (lazy) { + pend_fold_ = nf; // folded at the start of the next window (from the history parity before the turn) + } else { + std::vector ds; + nb_ = false; + fold(ds, nf, hp_); + cx_->run_graph(ds); + } + hp_ = 1 - hp_; + } + } + strata::core::SessionState& ss = *ss_; + for (int t = 0; t < n_keep; ++t) { + if (ple_on_) { + const float* norm = normW_.as() + (size_t) t * NG_HC_DIM; + for (int c = 0; c < NG_HC_DIM; ++c) { + float* col = pleHist_.as() + (size_t) c * NG_HIST; + for (int r = 0; r + 1 < NG_HIST; ++r) col[r] = col[r + 1]; + col[NG_HIST - 1] = norm[c]; + } + } + ss.ple_prev[0] = ss.ple_prev[1]; + ss.ple_prev[1] = last_tokens_[t]; + } + return true; +} + + +// ================================================================================================ the MTP draft layer +bool Window::mtp_load(const std::string& gguf_path, int max_t, std::string& err) { + (void) max_t; + if (!fm_.open(gguf_path, err)) return false; + madvise(fm_.map, fm_.map_bytes, MADV_WILLNEED); + Wm_ = cx_->wrap(fm_.map, fm_.map_bytes); + if (Wm_.handle == nullptr) { err = "metal mtp: cannot wrap " + gguf_path; return false; } + // vLLM's GemmaRMSNorm scales by (1 + w): the F32 norms folded once (tools/mtp_rt.py does the same for CUDA) + size_t tot = 0; + for (const auto& kv : fm_.tensors) + if (kv.second.type == 0) { mnorm_off_[kv.first] = tot; tot += (kv.second.bytes + 255) / 256 * 256; } + mnorm_ = cx_->alloc(tot + 256); + for (const auto& kv : mnorm_off_) { + const gguf::Tensor& x = fm_.tensors.at(kv.first); + const float* src = (const float*) ((const uint8_t*) fm_.map + x.offset); + float* dst = (float*) (mnorm_.as() + kv.second); + for (uint64_t i = 0; i < x.bytes / 4; ++i) dst[i] = src[i] + 1.0f; + } + lmtp_ = cx_->compile({std::string(STRATA_METAL_ENGINE_KERNELS_DEFAULT) + "/mtp.metal"}, "#define NO_GGML_COMMON 1\n"); + { + const char* e = std::getenv("STRATA_METAL_MTP_Q8"); + if (!(e && std::string(e) == "0")) { + size_t tot = 0; + std::vector names; + for (const auto& kv : fm_.tensors) { + const gguf::Tensor& x = kv.second; + uint64_t ne = 1; + for (uint64_t d : x.shape) ne *= d; + if (x.type != ref::BF16 || x.shape.size() < 2 || x.shape[0] % 32 != 0) continue; + gguf::Tensor q = x; + q.type = ref::Q8_0; + q.offset = tot; + q.bytes = ne / 32 * 34; + mq8t_[x.name] = q; + names.push_back(x.name); + tot += (q.bytes + 255) / 256 * 256; + } + mq8_ = cx_->alloc(tot + 4096); + std::vector th; + const unsigned nth = std::max(1u, std::min(16u, std::thread::hardware_concurrency())); + for (unsigned k = 0; k < nth; ++k) + th.emplace_back([&, k] { + std::vector tmp; + for (size_t i = k; i < names.size(); i += nth) { + const gguf::Tensor& x = fm_.tensors.at(names[i]); + const uint64_t ne = x.bytes / 2; + tmp.resize(ne); + ref::dequant(ref::BF16, (const uint8_t*) fm_.map + x.offset, tmp.data(), ne); + ref::quantize_q8_0(tmp.data(), ne, mq8_.as() + mq8t_[names[i]].offset); + } + }); + for (auto& x : th) x.join(); + } + } + auto A = [&](size_t bytes) { return cx_->alloc(bytes); }; + const int MAXC = (int) max_cells_, MB = MAXC / 4 + 2; + mR_ = A(4 * MAXT * HC * N); memb_ = A(4 * MAXT * N); men_ = A(4 * MAXT * N); me2_ = A(4 * MAXT * N); + mhn_ = A(4 * MAXT * HC * N); mh2_ = A(4 * HC * MAXT * N); midx_ = A(4 * MAXT * 640); mbo_ = A(4 * MAXT * N); + minj_[0] = A(4 * MAXT * HC); minj_[1] = A(4 * MAXT * HC); mqids_ = A(4 * MAXT * 2051); mlm_ = A(4 * (size_t) n_vocab_); + auto act = [&](int n) { Act x; x.n = n; x.b = A(4 * ((size_t) 4 * MAXT * n + (size_t) MAXT * n / 16)); return x; }; + XEn_ = act(N); XHn_ = act(N); + mkq_.push_back(A((size_t) MAXC * 2 * 256)); mvq_.push_back(A((size_t) MAXC * 2 * 256)); + mksc_.push_back(A(2 * (size_t) MAXC * 2 * 4)); mvsc_.push_back(A(2 * (size_t) MAXC * 2 * 4)); + mtail_.push_back(A(4 * 4 * 128)); mdead_.push_back(A(4 * 128)); mpooled_.push_back(A(4 * (size_t) MB * 128)); + { + std::string vp; + // the subset setup put beside the draft layer (--draft-vocab: /rt/draft_vocab.bin, as CUDA reads it), + // else the repository's default + const std::string beside = gguf_path.substr(0, gguf_path.find_last_of('/') + 1) + "rt/draft_vocab.bin"; + if (const char* e = std::getenv("STRATA_METAL_DRAFT_VOCAB")) vp = e; + else if (FILE* t = std::fopen(beside.c_str(), "rb")) { std::fclose(t); vp = beside; } + else vp = std::string(STRATA_METAL_DATA_DEFAULT) + "/draft_vocab.bin"; + FILE* f = vp == "full" ? nullptr : std::fopen(vp.c_str(), "rb"); + if (f) { + int32_t id; + while (std::fread(&id, 4, 1, f) == 1) if (id >= 0 && id < n_vocab_) dvocab_.push_back(id); + std::fclose(f); + } + if (!dvocab_.empty()) { + const gguf::Tensor& h = T("output.weight"); + const size_t rb = ref::row_bytes(h.type, N); + mhead_ = A(dvocab_.size() * rb + 4096); + for (size_t i = 0; i < dvocab_.size(); ++i) + std::memcpy(mhead_.as() + i * rb, (const uint8_t*) W_.ptr + h.offset + (size_t) dvocab_[i] * rb, rb); + mhead_t_ = h; + mhead_t_.offset = 0; + mhead_t_.shape = {(uint64_t) N, (uint64_t) dvocab_.size()}; + mhead_t_.bytes = dvocab_.size() * rb; + } + } + mtp_on_ = true; + { + const int ty = T("token_embd.weight").type; + const int ok_types[] = {30, 8, 2, 6, 20, 23, 42, 21, 11, 12, 13, 14, 18}; + const char* e = std::getenv("STRATA_METAL_MTP_CHAIN"); + chain_ = !(e && std::string(e) == "0") && std::find(std::begin(ok_types), std::end(ok_types), ty) != std::end(ok_types); + if (chain_) { + lchain_ = cx_->compile({"quant.metal", "units.metal", std::string(STRATA_METAL_ENGINE_KERNELS_DEFAULT) + "/mtp_chain.metal"}); + dout_ = A(4 * MAXT); dprob_ = A(4 * MAXT); posv_ = A(4 * N); + for (int i = 0; i < N; ++i) posv_.as()[i] = (float) i; + dmap_ = A(4 * std::max(1, dvocab_.size())); + if (!dvocab_.empty()) std::memcpy(dmap_.as(), dvocab_.data(), 4 * dvocab_.size()); + // parity: a few tokens' embeddings, GPU vs the host's dequant (the per-step path's) + const gguf::Tensor& te = T("token_embd.weight"); + const size_t rb = ref::row_bytes(te.type, N); + const int32_t probe[MAXT] = {0, 1, 271, 760, 6511, 11751, 100000, (int32_t) n_vocab_ - 1}; + double worst = 0.0; + std::vector ref_row(N); + for (int k = 0; k < MAXT; ++k) { + dout_.as()[0] = probe[k]; + std::vector ds; + nb_ = false; + mtl::Dispatch d; + d.p = P(lchain_, "mtp_embed_" + std::to_string(ty), {}, "mtp_embed_" + std::to_string(ty)); + struct EmbArgs { uint32_t n, row_bytes, j; } ea{(uint32_t) N, (uint32_t) rb, 0}; + d.args = {mtl::Arg::B(W_, te.offset), mtl::Arg::B(dout_), mtl::Arg::B(posv_), mtl::Arg::B(memb_), mtl::Arg::V(ea)}; + d.tg[0] = 256; + push(ds, d); + cx_->run_graph(ds); + ref::dequant(te.type, (const uint8_t*) W_.ptr + te.offset + (size_t) probe[k] * rb, ref_row.data(), N); + for (int i = 0; i < N; ++i) worst = std::max(worst, (double) std::fabs(ref_row[i] - memb_.as()[i])); + } + std::fprintf(stderr, "strata metal: MTP draft round in one command buffer (embedding type %d on the GPU: max " + "|GPU - host| %.3g over %d rows)\n", ty, worst, MAXT); + if (worst > 1e-6) { + std::fprintf(stderr, "strata metal: the GPU embedding differs from the host's: a command buffer per step\n"); + chain_ = false; + } + } + } + std::fprintf(stderr, "strata metal: MTP draft layer from %s (%.2f GB, %zu norms folded), draft head over %s tokens\n", + gguf_path.c_str(), fm_.file_bytes / 1e9, mnorm_off_.size(), + dvocab_.empty() ? "all" : std::to_string(dvocab_.size()).c_str()); + return true; +} + +void Window::gr_read_m(std::vector& ds, const std::string& pre, mtl::Buffer& Rb, const mtl::Buffer& bo, + const mtl::Buffer& inj_in, const mtl::Buffer& inj_out, bool apply, const Act& out, bool final_, + int ntok) { + const gguf::Tensor& tdn = TQ(pre + ".input_mix_weight_down.weight"); + const gguf::Tensor& tup = TQ(pre + ".input_mix_weight_up.weight"); + const gguf::Tensor& tin = final_ ? tdn : TQ(pre + ".block_inject_weight.weight"); + const bool q8 = tdn.type == ref::Q8_0 && tup.type == ref::Q8_0 && tin.type == ref::Q8_0; + const mtl::Buffer& WB = q8 ? mq8_ : Wm_; + GrArgs a{N, HC, LR, (uint32_t) ntok, apply ? 1u : 0u, eps_}; + mtl::Dispatch d1; + d1.p = P(lib_, "gr_norm", {}, "gr_norm"); + d1.args = {mtl::Arg::B(Rb), mtl::Arg::B(bo), mtl::Arg::B(inj_in), mtl::Arg::B(mnorm_, NM(pre + ".hc_norm.weight")), + mtl::Arg::B(xn_), mtl::Arg::V(a)}; + d1.grid[0] = HC; d1.grid[1] = ntok; d1.tg[0] = 256; + push(ds, d1); + mtl::Dispatch d2; + const char* dn = q8 ? "gr_down_q8_8_8" : "gr_down_8_8"; + d2.p = P(lib_, dn, mtl::Constants().i(1, ntok), std::string(dn) + "#" + std::to_string(ntok)); + d2.args = {mtl::Arg::B(WB, tdn.offset), mtl::Arg::B(WB, tin.offset), mtl::Arg::B(xn_), mtl::Arg::B(lo_), + mtl::Arg::B(inj_out), mtl::Arg::V(a)}; + d2.grid[0] = LR + HC; d2.tg[0] = 256; + push(ds, d2); + mtl::Dispatch d3; + const char* up = q8 ? "gr_up_q8" : "gr_up"; + d3.p = P(lib_, up, mtl::Constants().i(1, ntok), std::string(up) + "#" + std::to_string(ntok)); + GrArgs au = a; + au.n_tok = MAXT; + d3.args = {mtl::Arg::B(WB, tup.offset), mtl::Arg::B(lo_), mtl::Arg::B(xn_), mtl::Arg::B(out.b), mtl::Arg::V(au)}; + d3.grid[0] = N / 16; d3.tg[0] = 256; + push(ds, d3); +} + +void Window::mtp_encode(std::vector& ds, const mtl::Buffer& srcR, size_t src_off, int n, const int32_t* tokens, + int64_t cell0, bool full, int erow, int slot) { + struct RmsArgs { uint32_t n; float eps; }; + struct XpArgs { uint32_t n, n_tok, plane_tok, stride; }; + struct CombArgs { uint32_t n, hc, n_tok, h_stride; }; + // ---- the embedding rows (host tokens: dequantized on the CPU into the shared buffer) + const gguf::Tensor& te = T("token_embd.weight"); + const size_t rb = ref::row_bytes(te.type, N); + if (tokens) + for (int i = 0; i < n; ++i) + ref::dequant(te.type, (const uint8_t*) W_.ptr + te.offset + (size_t) tokens[i] * rb, + (membp_ ? *membp_ : memb_).as() + (size_t) (erow + i) * N, N); + const std::string L = "mtp.layers.0."; + auto rms = [&](const mtl::Buffer& x, size_t xo, const std::string& w, mtl::Buffer& y, int width, int rows) { + mtl::Dispatch d; + d.p = P(lmtp_, "mtp_rms", {}, "mtp_rms"); + RmsArgs a{(uint32_t) width, eps_}; + d.args = {mtl::Arg::B(x, xo), mtl::Arg::B(mnorm_, NM(w)), mtl::Arg::B(y), mtl::Arg::V(a)}; + d.grid[0] = rows; d.tg[0] = 256; + push(ds, d); + }; + auto xp = [&](const mtl::Buffer& x, size_t xo, const Act& out, int width, int rows, int stride) { + mtl::Dispatch d; + d.p = P(lmtp_, "mtp_xprep", {}, "mtp_xprep"); + XpArgs a{(uint32_t) width, (uint32_t) rows, MAXT, (uint32_t) stride}; + d.args = {mtl::Arg::B(x, xo), mtl::Arg::B(out.b), mtl::Arg::V(a)}; + d.grid[0] = (width / 16 * rows + 255) / 256; d.tg[0] = 256; + push(ds, d); + }; + auto gm = [&](const std::string& name, const Act& x, const mtl::Buffer& y, size_t y_stride, int rows, size_t y_off = 0) { + // a GEMV on the MTP model's tensor (the window's gemv() reads the main model's buffer) + const gguf::Tensor& tt = TQ(name); + const int n_in = (int) tt.shape[0], n_out = tt.shape.size() > 1 ? (int) tt.shape[1] : 1, ty = tt.type; + int Lq = 16, Rr = 1, S = 4, K = 1; + if (n_in >= 6144) { Lq = 32; Rr = 1; S = 8; K = 2; } + else if (n_in == 640) { Lq = 8; Rr = 1; S = 4; K = 1; } + else if (n_out <= 640 || ty == ref::Q2_0 || ty == ref::BF16) { Lq = 32; Rr = 1; S = 4; K = 1; } + const std::string fn = "gemv_" + std::to_string(ty) + "_" + std::to_string(Lq) + "_" + std::to_string(Rr) + "_" + + std::to_string(S) + "_" + std::to_string(K); + GemvArgs a{(uint32_t) n_in, (uint32_t) n_out, (uint32_t) rows, (uint32_t) ref::row_bytes(ty, n_in), (uint32_t) n_in, + (uint32_t) y_stride}; + mtl::Dispatch d; + d.p = P(lib_, fn, mtl::Constants().i(0, rows), fn + "#" + std::to_string(rows)); + d.args = {mtl::Arg::B(MB(name), tt.offset), mtl::Arg::B(x.b, x.plane_bytes() * xkind(ty)), + mtl::Arg::B(x.b, x.plane_bytes() * 4), mtl::Arg::B(y, y_off), mtl::Arg::V(a)}; + const int rpt = (S / K) * (32 / Lq) * Rr; + d.grid[0] = (n_out + rpt - 1) / rpt; d.tg[0] = S * 32; + push(ds, d); + }; + // ---- e = fc_embedding(rms(embed(tok)) * (1 + w)), h = fc_hidden per stream (rms_10240(R) * (1 + w)), R = h + e + rms(membp_ ? *membp_ : memb_, (size_t) erow * N * 4, "mtp.pre_fc_norm_embedding.weight", men_, N, n); + xp(men_, 0, XEn_, N, n, N); + gm("mtp.fc_embedding.weight", XEn_, me2_, N, n); + rms(srcR, src_off, "mtp.pre_fc_norm_hidden.weight", mhn_, HC * N, n); + for (int c = 0; c < HC; ++c) { + xp(mhn_, (size_t) c * N * 4, XHn_, N, n, HC * N); + gm("mtp.fc_hidden.weight", XHn_, mh2_, N, n, (size_t) c * MAXT * N * 4); + } + { + mtl::Dispatch d; + d.p = P(lmtp_, "mtp_combine", {}, "mtp_combine"); + CombArgs a{N, HC, (uint32_t) n, (uint32_t) (MAXT * N)}; + d.args = {mtl::Arg::B(mh2_), mtl::Arg::B(me2_), mtl::Arg::B(mR_), mtl::Arg::V(a)}; + d.grid[0] = (n * HC * N + 255) / 256; d.tg[0] = 256; + push(ds, d); + } + // ---- the attention hyper-connection, K/V (and the indexer keys) into the layer's own cache + gr_read_m(ds, L + "attn_hyper_connection", mR_, mbo_, minj_[1], minj_[0], false, XA_, false, n); + gm(L + "self_attn.k_proj.weight", XA_, kcur_, 512, n); + nb_ = true; + gm(L + "self_attn.v_proj.weight", XA_, vcur_, 512, n); + nb_ = true; + gm(L + "self_attn.indexer.index_qk_proj.weight", XA_, midx_, 640, n); + if (full) { + nb_ = true; + gm(L + "self_attn.q_proj.weight", XA_, qfull_, 12288, n); + } + QsaArgs qa{(uint32_t) cell0, 0, (uint32_t) max_cells_, (uint32_t) n, eps_}; + { + mtl::Dispatch d; + d.p = P(lqsa_, "qsa_prep", qsa_c(), qsa_k()); + d.args = {mtl::Arg::B(qfull_), mtl::Arg::B(kcur_), mtl::Arg::B(vcur_), mtl::Arg::B(midx_), mtl::Arg::B(midx_, 512 * 4), + mtl::Arg::B(mnorm_, NM(L + "self_attn.q_norm.weight")), mtl::Arg::B(mnorm_, NM(L + "self_attn.k_norm.weight")), + mtl::Arg::B(mnorm_, NM(L + "self_attn.indexer.q_layernorm.weight")), + mtl::Arg::B(mnorm_, NM(L + "self_attn.indexer.k_layernorm.weight")), + mtl::Arg::B(cs_), mtl::Arg::B(qcur_), mtl::Arg::B(qidx_), mtl::Arg::B(mkq_[0]), mtl::Arg::B(mvq_[0]), + mtl::Arg::B(mksc_[0]), mtl::Arg::B(mvsc_[0]), mtl::Arg::B(mtail_[0]), mtl::Arg::B(mdead_[0]), + mtl::Arg::B(mpooled_[0]), mtl::Arg::V(qa), mtl::Arg::B(mrope_)}; + d.grid[0] = 33; d.grid[1] = n; d.tg[0] = 256; + push(ds, d); + } + if (!full) return; + // ---- dense attention over the window of cells up to this one (the draft layer's rule), the output gate, o_proj + { + int* ids = mqids_.as() + (size_t) slot * 2051; + const int64_t first = std::max(0, cell0 - 2050); + for (int64_t c = first; c <= cell0; ++c) ids[c - first] = (int) c; + mtl::Dispatch at; + at.p = P(lqsa_, "qsa_attn", {}, "qsa_attn"); + at.args = {mtl::Arg::B(qcur_), mtl::Arg::B(mkq_[0]), mtl::Arg::B(mvq_[0]), mtl::Arg::B(mksc_[0]), mtl::Arg::B(mvsc_[0]), + mtl::Arg::B(mqids_, (size_t) slot * 2051 * 4), mtl::Arg::B(part_), mtl::Arg::V(qa)}; + at.grid[0] = 33; at.grid[1] = 2; at.grid[2] = 1; at.tg[0] = 256; + push(ds, at); + mtl::Dispatch m; + m.p = P(lqsa_, "qsa_merge", {}, "qsa_merge"); + QsaArgs am = qa; + am.n_tok = MAXT; + m.args = {mtl::Arg::B(part_), mtl::Arg::B(qfull_), mtl::Arg::B(XQ_.b), mtl::Arg::V(am)}; + m.grid[0] = 24; m.grid[1] = 1; m.tg[0] = 256; + push(ds, m); + gm(L + "self_attn.o_proj.weight", XQ_, mbo_, N, 1); + } + // ---- the MLP hyper-connection (the attention write folded in), the MoE, the write + final mixer, the head + gr_read_m(ds, L + "mlp_hyper_connection", mR_, mbo_, minj_[0], minj_[1], true, XF_, false, 1); + gm(L + "mlp.gate.weight", XF_, logits_, 512, 1); + nb_ = true; + gm(L + "mlp.shared_expert.gate_proj.weight", XF_, gsh_, NFF, 1); + nb_ = true; + gm(L + "mlp.shared_expert.up_proj.weight", XF_, ush_, NFF, 1); + nb_ = true; + gm(L + "mlp.shared_expert_gate.weight", XF_, sg_, 1, 1); + { + MoeArgs a{}; + const gguf::Tensor &tgu = TM(L + "mlp.experts.gate_up_proj"), &td = TM(L + "mlp.experts.down_proj"); + a.gu_row = (uint32_t) ref::row_bytes(tgu.type, N); + a.d_row = (uint32_t) ref::row_bytes(td.type, NFF); + a.gate_off = tgu.offset; + a.up_off = tgu.offset + (uint64_t) NFF * a.gu_row; // [gate rows | up rows] per expert + a.down_off = td.offset; + a.gu_stride = (uint64_t) a.gu_row * 2 * NFF; + a.d_stride = (uint64_t) a.d_row * N; + a.n_embd = N; a.n_ff = NFF; a.n_tok = 1; a.topk = TOPK; a.n_expert = NEXP; + const bool dq2 = td.type == ref::Q2_0; + const int gl = 32, gr = 1, gs = 4, ds_ = 4; + // the down tile: Q2_0 8,1; else 4,2 - but on the M4 (no M5 layout) Q5_1 4,1 and Q8_0 8,1 (4,2 spills there: + // 24-36 GB/s, mac-kern 513fc615) + const bool m4 = !m5_layout(); + const int dl = dq2 || (m4 && td.type == ref::Q8_0) ? 8 : 4, + dr = dq2 || (m4 && (td.type == ref::Q8_0 || td.type == ref::Q5_1)) ? 1 : 2; + a.gx_gu = NFF / (gs * (32 / gl) * gr); + a.gx_dn = N / (ds_ * (32 / dl) * dr); + mtl::Dispatch r; + r.p = P(lib_, "moe_route", {}, "moe_route"); + r.args = {mtl::Arg::B(logits_), mtl::Arg::B(ids_), mtl::Arg::B(wts_), mtl::Arg::B(plan_), mtl::Arg::V(a)}; + r.tg[0] = 512; + push(ds, r); + { + GlueArgs ga{NFF, MAXT, N, TOPK}; + mtl::Dispatch d; + d.p = P(lib_, "swiglu_prep", {}, "swiglu_prep"); + d.args = {mtl::Arg::B(gsh_), mtl::Arg::B(ush_), mtl::Arg::B(XH_.b), mtl::Arg::V(ga)}; + d.grid[0] = NFF / 16; d.grid[1] = 1; d.tg[0] = 16; + nb_ = true; + push(ds, d); + } + const std::string gun = "moe_gu_" + std::to_string(tgu.type) + "_" + std::to_string(gl) + "_" + std::to_string(gr) + + "_" + std::to_string(gs); + const std::string dnn = "moe_down_" + std::to_string(dq2 ? 142 : td.type) + "_" + std::to_string(dl) + "_" + + std::to_string(dr) + "_" + std::to_string(ds_); + mtl::Dispatch g; + g.p = P(lib_, gun, mtl::Constants().b(23, metal_ctab()), gun + (metal_ctab() ? "#ct" : "")); + g.args = {mtl::Arg::B(Wm_), mtl::Arg::B(XF_.b, XF_.plane_bytes() * xkind(tgu.type)), mtl::Arg::B(h_), mtl::Arg::B(plan_), + mtl::Arg::V(a), mtl::Arg::B(XF_.b, XF_.plane_bytes() * 4)}; + g.tg[0] = 32 * gs; + g.indirect = &plan_; + g.ind_off = P_IGU * 4; + push(ds, g); + nb_ = true; + gm(L + "mlp.shared_expert.down_proj.weight", XH_, ysh_, N, 1); + mtl::Dispatch dd; + dd.p = P(lib_, dnn, {}, dnn); + dd.args = {mtl::Arg::B(Wm_), mtl::Arg::B(h_), mtl::Arg::B(ye_), mtl::Arg::B(plan_), mtl::Arg::V(a), mtl::Arg::B(h_)}; + dd.tg[0] = 32 * ds_; + dd.indirect = &plan_; + dd.ind_off = P_IDN * 4; + push(ds, dd); + GlueArgs ca{N, 1, N, TOPK}; + mtl::Dispatch cb; + cb.p = P(lib_, "moe_combine_sh", {}, "moe_combine_sh"); + cb.args = {mtl::Arg::B(ye_), mtl::Arg::B(plan_), mtl::Arg::B(ysh_), mtl::Arg::B(sg_), mtl::Arg::B(mbo_), mtl::Arg::V(ca)}; + cb.grid[0] = (N + 255) / 256; cb.tg[0] = 256; + push(ds, cb); + } + // the layer's write (R updated in place: the next draft step's input residual) and the final mixer + gr_read_m(ds, "mtp.hyper_connection_mixer", mR_, mbo_, minj_[1], minj_[0], true, XA_, true, 1); + const int64_t nv = dvocab_.empty() ? n_vocab_ : (int64_t) dvocab_.size(); + if (dvocab_.empty()) gemv(ds, T("output.weight"), XA_, mlm_, (size_t) n_vocab_, 1); + else gemv(ds, mhead_t_, XA_, mlm_, (size_t) nv, 1, 0, &mhead_); + { + ArgArgs a{(uint32_t) nv, 120}; + mtl::Dispatch d1, d2; + d1.p = P(lsmp_, "argmax_part", {}, "argmax_part"); + d1.args = {mtl::Arg::B(mlm_), mtl::Arg::B(apv_), mtl::Arg::B(api_), mtl::Arg::V(a)}; + d1.grid[0] = 120; d1.grid[1] = 1; d1.tg[0] = 256; + push(ds, d1); + d2.p = P(lsmp_, "argmax_final", {}, "argmax_final"); + d2.args = {mtl::Arg::B(apv_), mtl::Arg::B(api_), mtl::Arg::B(tokout_), mtl::Arg::V(a)}; + d2.grid[0] = 1; d2.tg[0] = 256; + push(ds, d2); + } +} + +// the prompt's K/V: cell cell0 + i pairs the main window's final residual row i with the token at cell0 + i + 1 +bool Window::mtp_prefill(const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err) { + if (!mtp_on_) { err = "metal mtp: not loaded"; return false; } + mrope_sync(cell0, n); + // every group of MAXT rows in one command buffer: the embedding rows of all of them in mpemb_ (row c + i) + if ((int64_t) mpemb_rows_ < n) { + if (mpemb_rows_ > 0) cx_->free(mpemb_); + mpemb_rows_ = (size_t) std::max(n, 64); + mpemb_ = cx_->alloc(4 * mpemb_rows_ * N); + } + membp_ = &mpemb_; + std::vector ds; + nb_ = false; + for (int64_t c = 0; c < n; c += MAXT) { + const int k = (int) std::min(MAXT, n - c); + mtp_encode(ds, mpsrc_ ? *mpsrc_ : mtp_src_ ? *mtp_src_ : R_, (size_t) c * HC * N * 4, k, next_tokens + c, + cell0 + c, false, (int) c, 0); + } + membp_ = nullptr; + cx_->run_graph(ds); + return true; +} + +void Window::mtp_pick(std::vector& ds, int j, bool embed) { + struct PickArgs { uint32_t nv, j, use_map; }; + const int64_t nv = dvocab_.empty() ? n_vocab_ : (int64_t) dvocab_.size(); + mtl::Dispatch d; + d.p = P(lchain_, "mtp_pick", {}, "mtp_pick"); + PickArgs pa{(uint32_t) nv, (uint32_t) j, dvocab_.empty() ? 0u : 1u}; + d.args = {mtl::Arg::B(mlm_), mtl::Arg::B(tokout_), mtl::Arg::B(dmap_), mtl::Arg::B(dout_), mtl::Arg::B(dprob_), + mtl::Arg::V(pa)}; + d.tg[0] = 1024; + push(ds, d); + if (!embed) return; + const gguf::Tensor& te = T("token_embd.weight"); + struct EmbArgs { uint32_t n, row_bytes, j; } ea{(uint32_t) N, (uint32_t) ref::row_bytes(te.type, N), (uint32_t) j}; + mtl::Dispatch e; + const std::string fn = "mtp_embed_" + std::to_string(te.type); + e.p = P(lchain_, fn, {}, fn); + e.args = {mtl::Arg::B(W_, te.offset), mtl::Arg::B(dout_), mtl::Arg::B(posv_), mtl::Arg::B(memb_), mtl::Arg::V(ea)}; + e.tg[0] = 256; + push(ds, e); +} + +// One round (mtp.hpp's draft()): the window's rows 0..a-1 caught up (K/V), then the full layer on row a (draft 0) and +// on its own output for the next drafts. By default the whole round is one command buffer (the pick, its +// probability and the next step's embedding on the GPU); STRATA_METAL_MTP_CHAIN=0: a command buffer per step, the +// host picking and dequantizing. The embedding rows: the catch-up's at memb_ rows 0..a-1, draft 0's at row a. +bool Window::mtp_draft(int Tn, const int32_t* tokens, int64_t p, int a, int max_steps, int32_t* drafts, float* probs, + float min_p, int* n_drafts, std::string& err) { + if (!mtp_on_) { err = "metal mtp: not loaded"; return false; } + (void) Tn; + mrope_sync(p, a + max_steps + 1); + int n = 0; + int32_t tok = tokens[a]; + if (chain_ && max_steps > 0) { + std::vector ds; + nb_ = false; + if (a > 0) mtp_encode(ds, R_, 0, a, tokens, p, false); + mtp_encode(ds, R_, (size_t) a * HC * N * 4, 1, &tok, p + a, true, a, 0); + mtp_pick(ds, 0, max_steps > 1); + for (int j = 1; j < max_steps; ++j) { + mtp_encode(ds, mR_, 0, 1, nullptr, p + a + j, true, 0, j); + mtp_pick(ds, j, j + 1 < max_steps); + } + cx_->run_graph(ds); + for (int j = 0; j < max_steps; ++j) { + const float pj = dprob_.as()[j]; + drafts[j] = dout_.as()[j]; + if (probs) probs[j] = pj; + ++n; + if (min_p > 0.0f && pj < min_p) break; + } + if (n_drafts) *n_drafts = n; + return true; + } + for (int j = 0; j < max_steps; ++j) { + std::vector ds; + nb_ = false; + if (j == 0) { + if (a > 0) mtp_encode(ds, R_, 0, a, tokens, p, false); + mtp_encode(ds, R_, (size_t) a * HC * N * 4, 1, &tok, p + a, true, a, 0); + } else { + mtp_encode(ds, mR_, 0, 1, &tok, p + a + j, true); + } + cx_->run_graph(ds); + const int32_t di = tokout_.as()[0]; + const int32_t d = dvocab_.empty() ? di : dvocab_[(size_t) di]; + // the draft's probability: softmax of the draft head's logits at the pick + const float* lg = mlm_.as(); + const float mx = lg[di]; + const int64_t nv = dvocab_.empty() ? n_vocab_ : (int64_t) dvocab_.size(); + double s = 0.0; + for (int64_t i = 0; i < nv; ++i) s += std::exp((double) (lg[i] - mx)); + const float pj = (float) (1.0 / s); + drafts[j] = d; + if (probs) probs[j] = pj; + tok = d; + ++n; + if (min_p > 0.0f && pj < min_p) break; + } + if (n_drafts) *n_drafts = n; + return true; +} + +bool Window::copy_logits(int t, float* host) const { + if (t < 0 || t >= last_T_) return false; + std::memcpy(host, lm_.as() + (size_t) t * n_vocab_, (size_t) n_vocab_ * 4); + return true; +} + + +// ================================================================================== prompts through the matrix units +// A prompt chunk of T rows (mac-kern's tests/prompt_chain.cpp, on the engine's state): every dense matrix dequantized +// to fp16 once a chunk and multiplied on the matrix units (MPP), the GDN scan, QSA over the chunk, the routed experts +// as grouped GEMMs (v2 on the M4, v3 on the M5). The GDN state, the conv history, the K/V and indexer cells and the +// PLE history are the decode window's own, so decoding goes on from them. With SSD streaming the experts of a layer +// are put in place at the layer's handshake (the arena's misses) and the next layer's are streamed in behind it. +// STRATA_METAL_PROMPT_GEMM=0: prompts through the decode window (8 rows at a time). Its numerics differ from the +// window's (fp16 operands): STRATA_METAL_PROMPT_GEMM_MIN (default 64) keeps shorter prompts on the window path. +namespace { +struct PgDq { uint32_t n_in, n_out, row_bytes, perm; }; +struct PgGemm { int M, N, K, pad; }; +struct PgEpi { uint32_t n_tok, n_embd, hc, hc_lr; }; +struct PgGdnP { uint32_t n_tok, h_k, h_v, channels; float eps; uint32_t f32; }; +struct PgPlan { uint32_t n_ent, topk, n_expert, tm, n_blocks; }; +struct PgMm { uint64_t gate_off, up_off, down_off, gu_stride, d_stride; uint32_t gu_row, d_row, n_embd, n_ff; }; +int pg_unit(int t) { return t == ref::Q2_0 || t == ref::IQ3_S || t == ref::BF16 || t == ref::F32 ? 16 : 32; } +// the v2 (M4) expert tiles: the K-quants need TK 128, Q8_0 / IQ4_XS TK 32 (their 32-value units), the rest TK 16 +std::string gu2_tile(int t) { + if (t == ref::Q4_K || t == ref::Q5_K || t == ref::Q6_K) return "_16_16_128_2"; // the M4's best (513fc615) + if (t == ref::Q8_0 || t == ref::IQ4_XS) return "_16_64_32_2"; + return "_16_64_16_2"; +} +std::string dn2_tile(int t) { return t == ref::IQ4_NL || t == ref::Q5_1 || t == ref::Q8_0 ? "_16_64_32_2" : "_16_64_16_2"; } +} // namespace + +struct Window::PromptGemm { + int MT = 0, QS = 256, TM = 16, maxrows = 0, nblk_max = 0; + int lib = -1, lgdn = -1, lqsa = -1; + bool k4 = false, gu_v3 = false, dn_v3 = false, flash = false; + mtl::Buffer R, bo, inj[2], xnh, V, loh, mixed, mixh, qkv, z, al, be, ygh, gqn, gkn, gvc, ggb, gkq, go, yg, qfull, kcur, vcur, + iqr, ikr, qcur, qcurh, qidx, scores, qids, part, XQ, xqh, logits, ids, wts, bcnt, boff, eoff, tiles, meta, stok, sw, pos, + XS, HS, YE, yr, gsh, ush, hh, ys, sgv, emb, embh, pkey, pval, keyn, qn, gated, normW; + mtl::Buffer WD, WU, Wqkv, Wz, Wal, Wbe, Wout, Wq, Wk, Wv, Wiq, Wik, Wr, Wsg, Wshg, Wshu, Wshd, Wpk, Wpv; +}; + +int Window::prompt_chunk_rows() const { return pg_ ? pg_->MT : 0; } + +bool Window::prompt_gemm_on(int64_t n) const { + static const bool on = [] { + const char* e = std::getenv("STRATA_METAL_PROMPT_GEMM"); + return e ? std::string(e) != "0" : true; + }(); + static const int64_t mn = [] { + const char* e = std::getenv("STRATA_METAL_PROMPT_GEMM_MIN"); + return e ? (int64_t) std::atoll(e) : (int64_t) 64; + }(); + return on && n >= mn && pg_ != nullptr; +} + +bool Window::prompt_gemm_init(std::string& err) { + if (pg_) return true; + if (stream_ && !st_->ready()) return stream_arena(err); // it makes the prompt buffers after the arena + const char* ec = std::getenv("STRATA_METAL_PROMPT_CHUNK"); + // Streaming: every chunk makes one pass over the layer's experts that are not in the arena, so a longer chunk + // streams each expert fewer times. M5 Max, UD-Q5, warm: 1024 -> 700 tok/s at 4K, 2048 -> 920, 4096 -> 1,100 (32K the + // same). The longer chunk's buffers (4.3 GB) come out of the arena only while a prompt runs, so it is the default on a + // big Mac; a small one keeps 1024 (the buffers would cost it cache). + uint64_t phys = 0; + size_t plen = sizeof phys; + sysctlbyname("hw.memsize", &phys, &plen, nullptr, 0); + const int stream_chunk = phys >= (96ull << 30) ? 4096 : 1024; + const int C = std::max(64, ec ? std::atoi(ec) : (stream_ ? stream_chunk : 2048)) / 64 * 64; + auto pg = std::make_unique(); + PromptGemm& p = *pg; + p.MT = C; + p.QS = std::min(C, 256); + p.lib = cx_->compile({"quant.metal", "units.metal", "mma.metal", "dense_mm.metal", "moe_mm.metal", "gr.metal", "gemv.metal", + "prompt.metal"}); + p.lgdn = cx_->compile({"gdn.metal", "gdn_prompt.metal"}, "#define NO_GGML_COMMON 1\n"); + p.lqsa = cx_->compile({"qsa.metal", "qsa_prompt.metal"}, "#define NO_GGML_COMMON 1\n"); + p.k4 = ::coop_k4(*cx_); + const char* eg = std::getenv("STRATA_METAL_PROMPT_EXPERTS"); // v2 | v3 (default: v3 with the M5's layout) + p.gu_v3 = p.dn_v3 = eg ? std::string(eg) == "v3" : p.k4; + const char* eq = std::getenv("STRATA_METAL_PROMPT_QSA"); // v1 | flash (default: flash with the M5's layout) + p.flash = eq ? std::string(eq) == "flash" : p.k4; + const size_t MT = (size_t) C; + p.maxrows = C * TOPK + NEXP * p.TM; + p.nblk_max = (C * TOPK + 1023) / 1024; + const int MB = (int) max_cells_ / 4 + 2; + // the buffers: measured first, then placed - on a streaming Mac inside the expert arena (a region of its slots + // reserved only while a prompt runs: the prompt's scratch costs no decode memory), else allocated + uint64_t need = 0; + uint8_t* region = nullptr; + bool measure = true; + auto AB = [&](size_t bytes) -> mtl::Buffer { + const size_t b = (bytes + 16383) / 16384 * 16384; + if (measure) { need += b; return mtl::Buffer{}; } + if (region == nullptr) return cx_->alloc(bytes); + mtl::Buffer r = cx_->wrap(region, b); + region += b; + return r; + }; + auto F32 = [&](size_t n) { return AB(4 * n); }; + auto F16 = [&](size_t n) { return AB(2 * n); }; + auto make = [&] { + const size_t mr = (size_t) p.maxrows; + p.R = F32(MT * HC * N); p.bo = F32(MT * N); p.inj[0] = F32(MT * HC); p.inj[1] = F32(MT * HC); p.xnh = F16(MT * HC * N); + p.V = F32(MT * (LR + HC)); p.loh = F16(MT * LR); p.mixed = F32(MT * N); p.mixh = F16(MT * N); + p.qkv = F32(MT * 10240); p.z = F32(MT * 6144); p.al = F32(MT * 48); p.be = F32(MT * 48); p.yg = F32(MT * 6144); + p.ygh = F16(MT * 6144); p.gqn = F32(MT * 16 * 128); p.gkn = F32(MT * 16 * 128); p.gvc = F32(MT * 6144); + p.ggb = F32(MT * 96); p.gkq = F32(MT * 16); p.go = F32(MT * 6144); + p.qfull = F32(MT * 12288); p.kcur = F32(MT * 512); p.vcur = F32(MT * 512); p.iqr = F32(MT * 512); p.ikr = F32(MT * 128); + p.qcur = F32(MT * 24 * 256); p.qcurh = F16(MT * 24 * 256); p.qidx = F32(MT * 4 * 128); p.scores = F32(MT * (size_t) MB); + p.qids = AB(4 * MT * 2051); + p.part = p.flash ? F32(16) : F32((size_t) p.QS * 33 * 24 * 258); + p.XQ = F32(4 * MT * 6144 + 3 * (size_t) p.QS * 6144 + MT * 384); p.xqh = F16(MT * 6144); + p.logits = F32(MT * NEXP); p.ids = AB(4 * MT * TOPK); p.wts = F32(MT * TOPK); + p.bcnt = AB(4 * (size_t) p.nblk_max * NEXP); p.boff = AB(4 * (size_t) p.nblk_max * NEXP); + p.eoff = AB(4 * NEXP); p.tiles = AB(8 * (mr / p.TM + 1)); p.meta = AB(64); + p.stok = AB(4 * mr); p.sw = F32(mr); p.pos = AB(4 * MT * TOPK); p.XS = F16(mr * N); p.HS = F16(mr * NFF); + p.YE = F32(mr * N); p.yr = F32(MT * N); p.gsh = F32(MT * NFF); p.ush = F32(MT * NFF); p.hh = F16(MT * NFF); + p.ys = F32(MT * N); p.sgv = F32(MT); + p.WD = F16((size_t) (LR + HC) * HC * N); p.WU = F16((size_t) HC * N * LR); p.Wqkv = F16((size_t) 10240 * N); + p.Wz = F16((size_t) 6144 * N); p.Wal = F16((size_t) 48 * N); p.Wbe = F16((size_t) 48 * N); p.Wout = F16((size_t) N * 6144); + p.Wq = F16((size_t) 12288 * N); p.Wk = F16((size_t) 512 * N); p.Wv = F16((size_t) 512 * N); p.Wiq = F16((size_t) 512 * N); + p.Wik = F16((size_t) 128 * N); p.Wr = F16((size_t) NEXP * N); p.Wsg = F16((size_t) N); p.Wshg = F16((size_t) NFF * N); + p.Wshu = F16((size_t) NFF * N); p.Wshd = F16((size_t) N * NFF); + if (ple_on_) { + p.emb = F32(MT * N); p.embh = F16(MT * N); p.pkey = F32(MT * 10240); p.pval = F32(MT * N); p.keyn = F32(MT * 10240); + p.qn = F32(MT * 10240); p.gated = F32(MT * 10240); p.normW = F32(MT * 10240); + p.Wpk = F16((size_t) 10240 * N); p.Wpv = F16((size_t) N * N); + } + }; + make(); + measure = false; + if (stream_) { + region = st_->region(need); + if (region == nullptr) { err = "metal prompt: no arena region for the prompt buffers"; return false; } + } + make(); + pg_ = pg.release(); + std::fprintf(stderr, "strata metal: prompts on the matrix units in chunks of %d (experts %s, QSA %s, matmul2d layout %s; " + "%.2f GB of buffers%s)\n", C, p.gu_v3 ? "v3" : "v2", p.flash ? "flash" : "v1", p.k4 ? "K4" : "other", + need / 1e9, stream_ ? ", in the expert arena while a prompt runs" : ""); + (void) err; + return true; +} + +bool Window::prompt_chunk(const int32_t* tokens, int Tn, int64_t pos0, std::string& err) { + PromptGemm& p = *pg_; + p.meta.as()[2] = p.gu_v3 ? NFF / (32 * 4) : NFF / 64; + p.meta.as()[5] = p.dn_v3 ? N / (64 * 2) : N / 64; + auto TN = [this](const std::string& n) -> const gguf::Tensor& { return this->T(n); }; + if (Tn < 1 || Tn > p.MT) { err = "metal prompt: chunk size out of range"; return false; } + if (pos0 + Tn + 1 >= max_cells_) { err = "metal prompt: the chunk runs past the context"; return false; } + if (stream_ && !st_->ready() && !stream_arena(err)) return false; + if (pend_fold_ > 0) { // the last decode window's commit, still pending + std::vector fd; + nb_ = false; + fold(fd, pend_fold_, 1 - hp_); + cx_->run_graph(fd); + pend_fold_ = 0; + } + const int T = Tn; + // ---- the embeddings into every stream, the PLE rows + { + const gguf::Tensor& te = TN("token_embd.weight"); + const size_t rb = ref::row_bytes(te.type, N); + mrope_sync(pos0, T); + for (int t = 0; t < T; ++t) { + float* r = p.R.as() + (size_t) t * HC * N; + if (const float* img = img_row(pos0 + t)) std::memcpy(r, img, (size_t) N * 4); + else ref::dequant(te.type, (const uint8_t*) W_.ptr + te.offset + (size_t) tokens[t] * rb, r, N); + for (int c = 1; c < HC; ++c) std::memcpy(r + (size_t) c * N, r, (size_t) N * 4); + } + } + strata::core::SessionState& ss = *ss_; + if (ple_on_) { + std::vector rows((size_t) T * strata::kernels::PLE_N_HEADS); + int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]}; + for (int t = 0; t < T; ++t) { + strata::kernels::ngram_rows(&tokens[t], prev, 1, ss.ple.consts, rows.data() + (size_t) t * strata::kernels::PLE_N_HEADS); + prev[0] = prev[1]; + prev[1] = tokens[t]; + } + if (!ss.ple.table->gather_batch(rows.data(), (size_t) T, p.emb.as(), err)) return false; + } + std::vector ds; + std::vector cuts; + nb_ = false; + auto D = [&](const mtl::Pipeline* pp, std::vector a, uint32_t gx, uint32_t gy, uint32_t tg, uint32_t gz = 1) { + mtl::Dispatch d; + d.p = pp; + d.args = std::move(a); + d.grid[0] = gx; d.grid[1] = gy; d.grid[2] = gz; + d.tg[0] = tg; + push(ds, d); + }; + auto PP = [&](int lib, const std::string& fn, const mtl::Constants& c = {}, const std::string& key = "") { + return P(lib, fn, c, "pg:" + (key.empty() ? fn : key)); + }; + auto gemm = [&](const mtl::Buffer& A, const mtl::Buffer& B, const mtl::Buffer& Y, int M, int Nn, int K) { + const int tm = 64, tn = Nn <= 64 ? 32 : 64; + const std::string fn = "gemm_f16_" + std::to_string(tm) + "_" + std::to_string(tn) + "_4"; + PgGemm g{M, Nn, K, 0}; + D(PP(p.lib, fn), {mtl::Arg::B(A), mtl::Arg::B(B), mtl::Arg::B(Y), mtl::Arg::V(g)}, (Nn + tn - 1) / tn, (M + tm - 1) / tm, 128); + }; + auto dqb = [&](const mtl::Buffer& src, size_t off, int type, int n_in, int n_out, const mtl::Buffer& out, size_t out_off = 0, + uint32_t perm = 0) { + PgDq a{(uint32_t) n_in, (uint32_t) n_out, (uint32_t) ref::row_bytes(type, n_in), perm}; + D(PP(p.lib, "dq_f16_" + std::to_string(type)), {mtl::Arg::B(src, off), mtl::Arg::B(out, out_off), mtl::Arg::V(a)}, + (n_in / pg_unit(type) + 63) / 64, n_out, 64); + }; + auto dq = [&](const gguf::Tensor& t, const mtl::Buffer& out, size_t out_off = 0, uint32_t perm = 0) { + const int n_in = (int) t.shape[0], n_out = t.shape.size() > 1 ? (int) t.shape[1] : 1; + if (hc_q8_ && q8off_.count(t.name)) dqb(Q8_, q8off_.at(t.name), ref::Q8_0, n_in, n_out, out, out_off, perm); + else dqb(W_, t.offset, t.type, n_in, n_out, out, out_off, perm); + }; + auto act16 = [&](const mtl::Buffer& x, const mtl::Buffer& xh, size_t n) { + const uint32_t nn = (uint32_t) n; + D(PP(p.lib, "act_f16"), {mtl::Arg::B(x), mtl::Arg::B(xh), mtl::Arg::V(nn)}, (nn + 255) / 256, 1, 256); + }; + int ci = 0; + auto hc_read = [&](const std::string& pre, bool apply) { + const gguf::Tensor &tn = TN(pre + "_norm.weight"), &tdn = TN(pre + "_down.weight"), &tin = TN(pre + "_inject.weight"), + &tup = TN(pre + "_up.weight"); + dq(tdn, p.WD); + dq(tin, p.WD, (size_t) 2 * LR * HC * N); + dq(tup, p.WU, 0, HC); + GrArgs a{N, HC, LR, (uint32_t) T, apply ? 1u : 0u, eps_}; + PgEpi ea{(uint32_t) T, N, HC, LR}; + D(PP(p.lib, "gr_norm_h"), {mtl::Arg::B(p.R), mtl::Arg::B(p.bo), mtl::Arg::B(p.inj[ci]), mtl::Arg::B(W_, tn.offset), + mtl::Arg::B(p.xnh), mtl::Arg::V(a)}, HC, T, 256); + gemm(p.xnh, p.WD, p.V, T, LR + HC, HC * N); + D(PP(p.lib, "gr_epi_down"), {mtl::Arg::B(p.V), mtl::Arg::B(p.loh), mtl::Arg::B(p.inj[1 - ci]), mtl::Arg::V(ea)}, + (T * (LR + HC) + 255) / 256, 1, 256); + PgGemm g{T, HC * N, LR, 0}; + D(PP(p.lib, "gemm_hc_up_64_64_4"), {mtl::Arg::B(p.loh), mtl::Arg::B(p.WU), mtl::Arg::B(p.xnh), mtl::Arg::B(p.mixed), + mtl::Arg::B(p.mixh), mtl::Arg::V(g), mtl::Arg::V(ea)}, HC * N / 64, (T + 63) / 64, 128); + ci = 1 - ci; + }; + // the PLE projections (the window's gemv pair as GEMMs) + if (ple_on_) { + act16(p.emb, p.embh, (size_t) T * N); + dq(TN("blk.1.ple_key.weight"), p.Wpk); + dq(TN("blk.1.ple_value.weight"), p.Wpv); + gemm(p.embh, p.Wpk, p.pkey, T, 10240, N); + gemm(p.embh, p.Wpv, p.pval, T, N, N); + } + const int MB = (int) max_cells_ / 4 + 2; + (void) MB; + for (int l = 0; l < 48; ++l) { + const std::string b = "blk." + std::to_string(l) + "."; + hc_read(b + "hc_attn", l > 0 && !(l == 1 && ple_on_)); + if (l % 4 != 3) { + const int gi = l - l / 4; + dq(TN(b + "attn_qkv.weight"), p.Wqkv); + dq(TN(b + "attn_gate.weight"), p.Wz); + dq(TN(b + "ssm_alpha.weight"), p.Wal); + dq(TN(b + "ssm_beta.weight"), p.Wbe); + dq(TN(b + "ssm_out.weight"), p.Wout); + gemm(p.mixh, p.Wqkv, p.qkv, T, 10240, N); + gemm(p.mixh, p.Wz, p.z, T, 6144, N); + gemm(p.mixh, p.Wal, p.al, T, 48, N); + gemm(p.mixh, p.Wbe, p.be, T, 48, N); + PgGdnP ga{(uint32_t) T, 16, 48, 10240, eps_, 0}; + D(PP(p.lgdn, "gdn_pre"), + {mtl::Arg::B(p.qkv), mtl::Arg::B(ghist_[hp_][(size_t) gi]), mtl::Arg::B(W_, TN(b + "ssm_conv1d.weight").offset), + mtl::Arg::B(p.al), mtl::Arg::B(p.be), mtl::Arg::B(W_, TN(b + "ssm_dt.bias").offset), mtl::Arg::B(W_, TN(b + "ssm_a").offset), + mtl::Arg::B(p.gqn), mtl::Arg::B(p.gkn), mtl::Arg::B(p.gvc), mtl::Arg::B(p.ggb), mtl::Arg::B(p.gkq), + mtl::Arg::B(ghist_[1 - hp_][(size_t) gi]), mtl::Arg::V(ga)}, 16 + 24, T, 256); + D(PP(p.lgdn, "gdn_scanr_4", mtl::Constants().i(6, 0), "gdn_scanr_4"), + {mtl::Arg::B(gst_[(size_t) gi]), mtl::Arg::B(p.gqn), mtl::Arg::B(p.gkn), mtl::Arg::B(p.gvc), mtl::Arg::B(p.ggb), + mtl::Arg::B(p.gkq), mtl::Arg::B(p.go), mtl::Arg::V(ga)}, 48 * 4, 1, 32 * 4); + D(PP(p.lgdn, "gdn_post"), {mtl::Arg::B(p.go), mtl::Arg::B(p.z), mtl::Arg::B(W_, TN(b + "ssm_norm.weight").offset), + mtl::Arg::B(p.ygh), mtl::Arg::B(p.yg), mtl::Arg::V(ga)}, 48, T, 128); + gemm(p.ygh, p.Wout, p.bo, T, N, 6144); + } else { + const int qi = l / 4; + dq(TN(b + "attn_q.weight"), p.Wq); + dq(TN(b + "attn_k.weight"), p.Wk); + dq(TN(b + "attn_v.weight"), p.Wv); + dq(TN(b + "indexer.q_proj.weight"), p.Wiq); + dq(TN(b + "indexer.k_proj.weight"), p.Wik); + dq(TN(b + "attn_output.weight"), p.Wout); + gemm(p.mixh, p.Wq, p.qfull, T, 12288, N); + gemm(p.mixh, p.Wk, p.kcur, T, 512, N); + gemm(p.mixh, p.Wv, p.vcur, T, 512, N); + gemm(p.mixh, p.Wiq, p.iqr, T, 512, N); + gemm(p.mixh, p.Wik, p.ikr, T, 128, N); + QsaArgs a{(uint32_t) pos0, 0, (uint32_t) max_cells_, (uint32_t) T, eps_}; + D(PP(p.lqsa, "qsa_prep", qsa_c(), qsa_k()), + {mtl::Arg::B(p.qfull), mtl::Arg::B(p.kcur), mtl::Arg::B(p.vcur), mtl::Arg::B(p.iqr), mtl::Arg::B(p.ikr), + mtl::Arg::B(W_, TN(b + "attn_q_norm.weight").offset), mtl::Arg::B(W_, TN(b + "attn_k_norm.weight").offset), + mtl::Arg::B(W_, TN(b + "indexer.q_norm.weight").offset), mtl::Arg::B(W_, TN(b + "indexer.k_norm.weight").offset), + mtl::Arg::B(cs_), mtl::Arg::B(p.qcur), mtl::Arg::B(p.qidx), mtl::Arg::B(kq_[(size_t) qi]), mtl::Arg::B(vq_[(size_t) qi]), + mtl::Arg::B(ksc_[(size_t) qi]), mtl::Arg::B(vsc_[(size_t) qi]), mtl::Arg::B(tail_[(size_t) qi]), + mtl::Arg::B(dead_[(size_t) qi]), mtl::Arg::B(pooled_[(size_t) qi]), mtl::Arg::V(a), mtl::Arg::B(mrope_)}, 33, T, 256); + if (pos0 + T > 2051) + D(PP(p.lqsa, "qsa_score_mm"), {mtl::Arg::B(p.qidx), mtl::Arg::B(pooled_[(size_t) qi]), mtl::Arg::B(dead_[(size_t) qi]), + mtl::Arg::B(p.scores), mtl::Arg::V(a)}, + (uint32_t) (((pos0 + T) / 4 + 1 + 63) / 64), (T + 15) / 16, 128); + D(PP(p.lqsa, "qsa_topk"), {mtl::Arg::B(p.scores), mtl::Arg::B(p.qids), mtl::Arg::V(a)}, T, 1, 1024); + if (p.flash) { + const uint32_t nq = (uint32_t) T * 24 * 256; + D(PP(p.lqsa, "qsa_q_f16"), {mtl::Arg::B(p.qcur), mtl::Arg::B(p.qcurh), mtl::Arg::V(nq)}, (nq + 255) / 256, 1, 256); + D(PP(p.lqsa, "qsa_flash", mtl::Constants().b(7, p.k4), "qsa_flash"), + {mtl::Arg::B(p.qcurh), mtl::Arg::B(kq_[(size_t) qi]), mtl::Arg::B(vq_[(size_t) qi]), mtl::Arg::B(ksc_[(size_t) qi]), + mtl::Arg::B(vsc_[(size_t) qi]), mtl::Arg::B(p.qids), mtl::Arg::B(p.qfull), mtl::Arg::B(p.xqh), mtl::Arg::V(a)}, + 2, T, 128); + } else { + // v1 attention + merge in slices of QS rows (the partials of a slice only) + for (int t0 = 0; t0 < T; t0 += p.QS) { + const int ns = std::min(p.QS, T - t0); + QsaArgs as{(uint32_t) (pos0 + t0), 0, (uint32_t) max_cells_, (uint32_t) ns, eps_}; + D(PP(p.lqsa, "qsa_attn"), {mtl::Arg::B(p.qcur, (size_t) t0 * 24 * 256 * 4), mtl::Arg::B(kq_[(size_t) qi]), + mtl::Arg::B(vq_[(size_t) qi]), mtl::Arg::B(ksc_[(size_t) qi]), mtl::Arg::B(vsc_[(size_t) qi]), + mtl::Arg::B(p.qids, (size_t) t0 * 2051 * 4), mtl::Arg::B(p.part), mtl::Arg::V(as)}, + 33, 2, 256, (uint32_t) ns); + D(PP(p.lqsa, "qsa_merge"), {mtl::Arg::B(p.part), mtl::Arg::B(p.qfull, (size_t) t0 * 12288 * 4), + mtl::Arg::B(p.XQ, (size_t) t0 * 6144 * 4), mtl::Arg::V(as)}, 24, ns, 256); + } + act16(p.XQ, p.xqh, (size_t) T * 6144); + } + gemm(p.xqh, p.Wout, p.bo, T, N, 6144); + } + if (l == 0 && ple_on_) { + // layer 0's attention write applied to R happens in the FFN read below; the PLE block comes after the FFN + } + // ---- the MoE + hc_read(b + "hc_ffn", true); + const gguf::Tensor &tr = TN(b + "ffn_gate_inp.weight"), &tsg = TN(b + "ffn_gate_inp_shexp.weight"), + &tg_ = TN(b + "ffn_gate_shexp.weight"), &tu_ = TN(b + "ffn_up_shexp.weight"), + &td_ = TN(b + "ffn_down_shexp.weight"), &eg = TN(b + "ffn_gate_exps.weight"), + &ed = TN(b + "ffn_down_exps.weight"); + dq(tr, p.Wr); + dq(tsg, p.Wsg); + dq(tg_, p.Wshg); + dq(tu_, p.Wshu); + dq(td_, p.Wshd); + gemm(p.mixh, p.Wr, p.logits, T, NEXP, N); + const uint32_t nt = (uint32_t) T; + D(PP(p.lib, "route_topk"), {mtl::Arg::B(p.logits), mtl::Arg::B(p.ids), mtl::Arg::B(p.wts), mtl::Arg::V(nt)}, (T + 7) / 8, 1, 256); + const int nent = T * TOPK, nblk = (nent + 1023) / 1024; + PgPlan pa{(uint32_t) nent, TOPK, NEXP, (uint32_t) p.TM, (uint32_t) nblk}; + const uint32_t nclr = (uint32_t) p.maxrows; + D(PP(p.lib, "mm_clear"), {mtl::Arg::B(p.stok), mtl::Arg::V(nclr)}, (p.maxrows + 255) / 256, 1, 256); + D(PP(p.lib, "mm_hist"), {mtl::Arg::B(p.ids), mtl::Arg::B(p.bcnt), mtl::Arg::V(pa)}, nblk, 1, 1024); + D(PP(p.lib, "mm_scan"), {mtl::Arg::B(p.bcnt), mtl::Arg::B(p.boff), mtl::Arg::B(p.eoff), mtl::Arg::B(p.tiles), + mtl::Arg::B(p.meta), mtl::Arg::V(pa)}, 1, 1, NEXP); + D(PP(p.lib, "mm_place"), {mtl::Arg::B(p.ids), mtl::Arg::B(p.wts), mtl::Arg::B(p.boff), mtl::Arg::B(p.eoff), + mtl::Arg::B(p.stok), mtl::Arg::B(p.sw), mtl::Arg::B(p.pos), mtl::Arg::V(pa)}, nblk, 1, 1024); + PgMm ma{eg.offset, TN(b + "ffn_up_exps.weight").offset, ed.offset, 0, 0, (uint32_t) ref::row_bytes(eg.type, N), + (uint32_t) ref::row_bytes(ed.type, NFF), N, NFF}; + ma.gu_stride = (uint64_t) ma.gu_row * NFF; + ma.d_stride = (uint64_t) ma.d_row * N; + if (stream_) { ma.gate_off = 0; ma.up_off = st_->up_in_slot(l); ma.down_off = st_->down_in_slot(l); } + const uint32_t ne_ = N; + { + mtl::Dispatch g; + g.p = PP(p.lib, "mm_gather"); + g.args = {mtl::Arg::B(p.mixed), mtl::Arg::B(p.stok), mtl::Arg::B(p.XS), mtl::Arg::V(ne_)}; + g.tg[0] = 256; + g.indirect = &p.meta; + g.ind_off = 8 * 4; + push(ds, g); + } + const mtl::Buffer& EW = stream_ ? st_->chunk(0) : W_; + auto arena_args = [&](mtl::Dispatch& d) { + if (!stream_) return; + d.args.push_back(mtl::Arg::B(st_->smap(), (size_t) l * 512 * 4)); + for (int c = 1; c < 4; ++c) d.args.push_back(mtl::Arg::B(st_->chunk(c))); + }; + const std::string ak = stream_ ? "#arena" : ""; + mtl::Dispatch gu; + if (p.gu_v3) { + const std::string fn = "mm_gu3_" + std::to_string(eg.type) + "_16_32_32_4"; + mtl::Constants c = mtl::Constants().b(7, p.k4); + if (stream_) c.b(20, true); + gu.p = PP(p.lib, fn, c, fn + ak); + gu.tg[0] = 32 * 4; + } else { + const std::string fn = "mm_gu2_" + std::to_string(eg.type) + gu2_tile(eg.type); + mtl::Constants c = mtl::Constants().i(5, 0); + if (stream_) c.b(20, true); + gu.p = PP(p.lib, fn, c, fn + ak); + gu.tg[0] = 64; + } + gu.args = {mtl::Arg::B(EW), mtl::Arg::B(p.XS), mtl::Arg::B(p.HS), mtl::Arg::B(p.tiles), mtl::Arg::V(ma)}; + arena_args(gu); + gu.indirect = &p.meta; + gu.ind_off = 2 * 4; + if (stream_) cuts.push_back((int) ds.size()); // the host's turn: this layer's experts put in place + push(ds, gu); + mtl::Dispatch dn; + if (p.dn_v3) { + const std::string fn = "mm_down3_" + std::to_string(ed.type) + "_16_64_32_2"; + mtl::Constants c = mtl::Constants().b(7, p.k4); + if (stream_) c.b(20, true); + dn.p = PP(p.lib, fn, c, fn + ak); + dn.tg[0] = 32 * 2; + } else { + const std::string fn = "mm_down2_" + std::to_string(ed.type) + dn2_tile(ed.type); + mtl::Constants c; + if (stream_) c.b(20, true); + dn.p = PP(p.lib, fn, c, fn + ak); + dn.tg[0] = 64; + } + dn.args = {mtl::Arg::B(EW), mtl::Arg::B(p.HS), mtl::Arg::B(p.YE), mtl::Arg::B(p.tiles), mtl::Arg::V(ma)}; + arena_args(dn); + dn.indirect = &p.meta; + dn.ind_off = 5 * 4; + push(ds, dn); + const uint32_t ca[4] = {(uint32_t) T, N, TOPK, 0}; + D(PP(p.lib, "mm_combine"), {mtl::Arg::B(p.YE), mtl::Arg::B(p.pos), mtl::Arg::B(p.sw), mtl::Arg::B(p.yr), mtl::Arg::V(ca)}, + (T * N + 255) / 256, 1, 256); + gemm(p.mixh, p.Wshg, p.gsh, T, NFF, N); + gemm(p.mixh, p.Wshu, p.ush, T, NFF, N); + const uint32_t nh = (uint32_t) T * NFF; + D(PP(p.lib, "swiglu_h"), {mtl::Arg::B(p.gsh), mtl::Arg::B(p.ush), mtl::Arg::B(p.hh), mtl::Arg::V(nh)}, (nh + 255) / 256, 1, 256); + gemm(p.hh, p.Wshd, p.ys, T, N, NFF); + gemm(p.mixh, p.Wsg, p.sgv, T, 1, N); + const uint32_t oa[2] = {(uint32_t) T, N}; + D(PP(p.lib, "moe_out"), {mtl::Arg::B(p.yr), mtl::Arg::B(p.ys), mtl::Arg::B(p.sgv), mtl::Arg::B(p.bo), mtl::Arg::V(oa)}, + (T * N + 255) / 256, 1, 256); + if (l == 0 && ple_on_) { + // layer 0's FFN write applied to R, then the PLE block (as the window, for T rows) + const gguf::Tensor& tn = TN("blk.1.hc_attn_norm.weight"); + GrArgs a{N, HC, LR, (uint32_t) T, 1u, eps_}; + D(P(lib_, "gr_norm", {}, "gr_norm"), {mtl::Arg::B(p.R), mtl::Arg::B(p.bo), mtl::Arg::B(p.inj[ci]), mtl::Arg::B(W_, tn.offset), + mtl::Arg::B(p.YE), mtl::Arg::V(a)}, HC, T, 256); + struct PleArgs { uint32_t n_embd, hc; float eps; } pl{N, HC, strata::kernels::NG_RMS_EPS}; + auto off = [&](const char* n) { return TN(n).offset; }; + D(P(lple_, "ple_gnorm", {}, "ple_gnorm"), {mtl::Arg::B(p.pkey), mtl::Arg::B(W_, off("blk.1.ple_norm_key.weight")), + mtl::Arg::B(p.keyn), mtl::Arg::V(pl)}, HC, T, 256); + nb_ = true; + D(P(lple_, "ple_gnorm", {}, "ple_gnorm"), {mtl::Arg::B(p.R), mtl::Arg::B(W_, off("blk.1.ple_norm_query.weight")), + mtl::Arg::B(p.qn), mtl::Arg::V(pl)}, HC, T, 256); + D(P(lple_, "ple_gate_norm", {}, "ple_gate_norm"), + {mtl::Arg::B(p.keyn), mtl::Arg::B(p.qn), mtl::Arg::B(p.pval), mtl::Arg::B(W_, off("blk.1.ple_norm_conv.weight")), + mtl::Arg::B(p.gated), mtl::Arg::B(p.normW), mtl::Arg::V(pl)}, HC, T, 256); + D(P(lple_, "ple_conv_add", {}, "ple_conv_add"), + {mtl::Arg::B(pleHist_), mtl::Arg::B(p.normW), kw_arg(), mtl::Arg::B(p.gated), + mtl::Arg::B(p.R), mtl::Arg::V(pl)}, HC * N / 256, T, 256); + } + } + // the last layer's write applied to R (the draft layer's K/V read the final residual rows) + { + const gguf::Tensor& tn = TN("output_hc_norm.weight"); + GrArgs a{N, HC, LR, (uint32_t) T, 1u, eps_}; + D(P(lib_, "gr_norm", {}, "gr_norm"), {mtl::Arg::B(p.R), mtl::Arg::B(p.bo), mtl::Arg::B(p.inj[ci]), mtl::Arg::B(W_, tn.offset), + mtl::Arg::B(p.YE), mtl::Arg::V(a)}, HC, T, 256); + } + const double t0 = now_ms(); + if (stream_) { + seg_T_ = T; + cut_ids_ = p.ids.as(); + cx_->run_graph_seg(ds, cuts, [](void* u, int s) { ((Window*) u)->at_cut(s); }, this); + cut_ids_ = nullptr; + } else { + cx_->run_graph(ds); + } + pg_ms_ += now_ms() - t0; + pg_tok_ += T; + static const bool trace = std::getenv("STRATA_METAL_TRACE") != nullptr; + if (trace) std::fprintf(stderr, "strata metal: prompt chunk pos %lld, %d rows: %.0f ms\n", (long long) pos0, T, now_ms() - t0); + // the window's state after the chunk: the conv history turned, the PLE history and token window advanced + hp_ = 1 - hp_; + if (ple_on_) { + using namespace strata::kernels; + float* hist = pleHist_.as(); + const float* nw = p.normW.as(); + for (int c = 0; c < NG_HC_DIM; ++c) { + float col[NG_HIST]; + for (int r = 0; r < NG_HIST; ++r) { + const int src = T - NG_HIST + r; // row r of the new history: chunk row src, or the old history + col[r] = src >= 0 ? nw[(size_t) src * NG_HC_DIM + c] : hist[(size_t) c * NG_HIST + (size_t) (r + T)]; + } + std::memcpy(hist + (size_t) c * NG_HIST, col, sizeof col); + } + } + if (T >= 2) { ss.ple_prev[0] = tokens[T - 2]; ss.ple_prev[1] = tokens[T - 1]; } + else { ss.ple_prev[0] = ss.ple_prev[1]; ss.ple_prev[1] = tokens[0]; } + mtp_src_ = &p.R; // the draft layer's prompt K/V read this chunk's final rows + return true; +} + +// ---------------------------------------------------------------------------------------------- the hook's entry points +namespace { +std::string g_shard1; +} +void window_register(void* w); +bool mtp_load_pending(Window* w, std::string& err); +void set_model_shard(const char* shard1) { g_shard1 = shard1 ? shard1 : ""; } + +// One decode window per process: the prompt path (Prefill::init) may bring it up before the Verifier does. +namespace { +Window* g_the_window = nullptr; +} +void* window_create() { + if (g_the_window == nullptr) g_the_window = new Window(); + return g_the_window; +} +void window_destroy(void* w) { + if (w != nullptr && w == g_the_window) { + if (g_stream_window == g_the_window) { + g_the_window->stream_report(stderr); + g_stream_window = nullptr; + } + delete g_the_window; + g_the_window = nullptr; + window_register(nullptr); + } +} +bool window_init(void* w, const strata::core::ModelGeometry& g, strata::core::SessionState& ss, int max_t, int64_t max_cells, + int64_t* n_vocab, std::string& err) { + Window* x = (Window*) w; + if (!x->ready()) { + if (g_shard1.empty()) { err = "metal window: the model shard is not set (--native SHARD1)"; return false; } + if (!x->init(g, ss, g_shard1, MAXT, max_cells, err)) return false; + window_register(w); + if (!mtp_load_pending(x, err)) return false; + } + x->set_max_t(max_t); + *n_vocab = x->vocab(); + return true; +} +bool window_ensure(const strata::core::ModelGeometry& g, strata::core::SessionState& ss, int64_t max_cells, std::string& err) { + int64_t nv = 0; + return window_init(window_create(), g, ss, MAXT, max_cells, &nv, err); +} +bool window_run(void* w, int T, const int32_t* tokens, int64_t pos0, bool head, int32_t* out, std::string& err) { + // STRATA_LOGPOS (the quant yardstick, the KL harness): every window's head logits are read, also the prompt's + // windows that sample nothing (head_sampling off) + static const bool logpos = std::getenv("STRATA_LOGPOS") != nullptr; + return ((Window*) w)->run(T, tokens, pos0, head || logpos, out, err); +} +void window_reset() { + if (g_the_window != nullptr && g_the_window->ready()) g_the_window->reset(); +} +bool window_checkpoint_save(strata::core::ConversationCheckpoint& c, std::string& err) { + if (g_the_window == nullptr || !g_the_window->ready()) { err = "metal window: not up"; return false; } + return g_the_window->checkpoint_save(c, err); +} +bool window_checkpoint_restore(const strata::core::ConversationCheckpoint& c, std::string& err) { + if (g_the_window == nullptr || !g_the_window->ready()) { err = "metal window: not up"; return false; } + return g_the_window->checkpoint_restore(c, err); +} +bool window_commit(void* w, int n_keep, std::string& err) { + const double t0 = now_ms(); + const bool ok = ((Window*) w)->commit(n_keep, err); + ((Window*) w)->prof_add(false, now_ms() - t0); + return ok; +} +bool window_copy_logits(void* w, int t, float* host) { return ((Window*) w)->copy_logits(t, host); } + +// the MTP hook (src/core/mtp.cpp under STRATA_GPU_METAL): the drafter lives beside the decode window it reads +namespace { +Window* g_window = nullptr; +} +void window_register(void* w) { g_window = (Window*) w; } +// the engine loads the drafter before the decode window exists: the path is kept and the window loads it at its init +std::string g_mtp_path; +int g_mtp_max_t = 0; +bool mtp_load(const std::string& rt_dir, int max_t, std::string& err) { + (void) err; + // the MTP model in GGUF form (tools/mtp_pack.py) beside the rt directory: STRATA_METAL_MTP_GGUF, else + // /../mtp-q2_0.gguf + std::string path; + if (const char* e = std::getenv("STRATA_METAL_MTP_GGUF")) path = e; + else { + std::string d = rt_dir; + while (!d.empty() && d.back() == '/') d.pop_back(); + const size_t s = d.rfind('/'); + path = (s == std::string::npos ? std::string(".") : d.substr(0, s)) + "/mtp-q2_0.gguf"; + } + g_mtp_path = path; + g_mtp_max_t = max_t; + return true; +} +bool mtp_load_pending(Window* w, std::string& err) { + return g_mtp_path.empty() || w->mtp_load(g_mtp_path, g_mtp_max_t, err); +} +// Prefill::run's Metal side: the prompt read through the window, MAXT rows at a time (no head), each window +// committed; on_chunk (the MTP's K/V) after each, with the window's final residual rows in place. +bool prompt_run_rows(const int64_t* tokens, int64_t n, int64_t pos0, + const std::function& on_chunk, std::string& err); +bool prompt_run(const int64_t* tokens, int64_t n, int64_t pos0, const float* const* embd_rows, + const std::function& on_chunk, std::string& err) { + struct Rows { + explicit Rows(const float* const* r) { g_embd_rows = r; } + ~Rows() { g_embd_rows = nullptr; } + } rows(embd_rows); + return prompt_run_rows(tokens, n, pos0, on_chunk, err); +} +bool prompt_run_rows(const int64_t* tokens, int64_t n, int64_t pos0, + const std::function& on_chunk, std::string& err) { + if (g_window == nullptr) { err = "metal prompt: the decode window is not up yet"; return false; } + static const bool windows = std::getenv("STRATA_METAL_PROMPT") && std::string(std::getenv("STRATA_METAL_PROMPT")) == "window"; + static const int64_t min_rows = std::getenv("STRATA_METAL_PROMPT_MIN") ? std::atoll(std::getenv("STRATA_METAL_PROMPT_MIN")) : 32; + if (!windows && !g_window->streaming() && n >= min_rows) return g_window->prompt(tokens, n, pos0, on_chunk, err); + if (!windows && g_window->streaming()) { + const char* e = std::getenv("STRATA_METAL_PROMPT_GEMM"); + const char* em = std::getenv("STRATA_METAL_PROMPT_GEMM_MIN"); + const int64_t mn = em ? std::atoll(em) : 64; + if (!(e && std::string(e) == "0") && n >= mn) { + if (!g_window->prompt_gemm_init(err)) return false; + const int C = g_window->prompt_chunk_rows(); + std::vector tk32((size_t) C); + g_window->prompt_region(true); + bool ok = true; + for (int64_t c = 0; c < n && ok; c += C) { + const int k = (int) std::min(C, n - c); + for (int i = 0; i < k; ++i) tk32[(size_t) i] = (int32_t) tokens[c + i]; + ok = g_window->prompt_chunk(tk32.data(), k, pos0 + c, err) && (!on_chunk || on_chunk(nullptr, k, pos0 + c, err)); + } + g_window->prompt_region(false); + return ok; + } + } + int32_t tk[MAXT], out[MAXT]; + for (int64_t c = 0; c < n; c += MAXT) { + const int k = (int) std::min(MAXT, n - c); + for (int i = 0; i < k; ++i) tk[i] = (int32_t) tokens[c + i]; + if (!g_window->run(k, tk, pos0 + c, false, out, err) || !g_window->commit(k, err)) return false; + if (on_chunk && !on_chunk(nullptr, k, pos0 + c, err)) return false; + } + return true; +} +bool mtp_prefill(const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err) { + if (g_window == nullptr) { err = "metal mtp: no decode window"; return false; } + return g_window->mtp_prefill(next_tokens, n, cell0, err); +} +bool mtp_draft(int T, const int32_t* tokens, int64_t p, int a, int max_steps, int32_t* drafts, float* probs, float min_p, + int* n_drafts, std::string& err) { + if (g_window == nullptr) { err = "metal mtp: no decode window"; return false; } + const double t0 = now_ms(); + const bool ok = g_window->mtp_draft(T, tokens, p, a, max_steps, drafts, probs, min_p, n_drafts, err); + g_window->prof_add(true, now_ms() - t0); + return ok; +} + +#include "prompt_chain.inc" + +} // namespace strata::metal_engine +namespace strata::gpu { void* host_view(const void* device_pointer); } +namespace strata::kernels { +void mrope_table_set(const int32_t* device_table) { + strata::metal_engine::g_mrope_dev = device_table; + strata::metal_engine::g_mrope_host = + device_table ? (const int32_t*) strata::gpu::host_view(device_table) : nullptr; +} +const int32_t* mrope_table() { return strata::metal_engine::g_mrope_dev; } +} // namespace strata::kernels +namespace strata::metal_engine { + +} // namespace strata::metal_engine diff --git a/metal/src/gguf_lite.cpp b/metal/src/gguf_lite.cpp new file mode 100644 index 00000000..44937fba --- /dev/null +++ b/metal/src/gguf_lite.cpp @@ -0,0 +1,117 @@ +// metal/src/gguf_lite.cpp - see gguf_lite.h. +#include "gguf_lite.h" + +#include "ref_quant.h" + +#include +#include +#include +#include + +#include +#include + +namespace gguf { + +namespace { +struct Reader { + const uint8_t* p; + const uint8_t* end; + bool ok = true; + template T get() { + T v{}; + if (p + sizeof(T) > end) { ok = false; return v; } + std::memcpy(&v, p, sizeof(T)); + p += sizeof(T); + return v; + } + std::string str() { + const uint64_t n = get(); + if (!ok || p + n > end) { ok = false; return {}; } + std::string s((const char*)p, n); + p += n; + return s; + } +}; +// value types: 0 u8 1 i8 2 u16 3 i16 4 u32 5 i32 6 f32 7 bool 8 string 9 array 10 u64 11 i64 12 f64 +size_t scalar_size(uint32_t t) { + switch (t) { + case 0: case 1: case 7: return 1; + case 2: case 3: return 2; + case 4: case 5: case 6: return 4; + case 10: case 11: case 12: return 8; + } + return 0; +} +double scalar_num(Reader& r, uint32_t t) { + switch (t) { + case 0: return r.get(); case 1: return r.get(); case 2: return r.get(); + case 3: return r.get(); case 4: return r.get(); case 5: return r.get(); + case 6: return r.get(); case 7: return r.get(); case 10: return (double)r.get(); + case 11: return (double)r.get(); case 12: return r.get(); + } + r.ok = false; + return 0; +} +} // namespace + +bool File::open(const std::string& p, std::string& err) { + path = p; + const int fd = ::open(p.c_str(), O_RDONLY); + if (fd < 0) { err = "cannot open " + p; return false; } + struct stat st; + fstat(fd, &st); + file_bytes = (size_t)st.st_size; + const size_t page = (size_t)getpagesize(); + map_bytes = (file_bytes + page - 1) / page * page; + map = mmap(nullptr, map_bytes, PROT_READ, MAP_SHARED, fd, 0); + ::close(fd); + if (map == MAP_FAILED) { map = nullptr; err = "mmap failed: " + p; return false; } + Reader r{(const uint8_t*)map, (const uint8_t*)map + file_bytes}; + if (r.get() != 0x46554747u) { err = "not a GGUF file"; return false; } + if (r.get() != 3) { err = "GGUF version is not 3"; return false; } + const uint64_t n_t = r.get(), n_kv = r.get(); + uint64_t align = 32; + for (uint64_t i = 0; i < n_kv && r.ok; ++i) { + const std::string key = r.str(); + const uint32_t t = r.get(); + if (t == 8) meta_str[key] = r.str(); + else if (t == 9) { + const uint32_t et = r.get(); + const uint64_t n = r.get(); + if (et == 8) for (uint64_t k = 0; k < n && r.ok; ++k) r.str(); + else r.p += n * scalar_size(et); + } else { + const double v = scalar_num(r, t); + meta_num[key] = v; + if (key == "general.alignment") align = (uint64_t)v; + } + } + std::vector ts; + for (uint64_t i = 0; i < n_t && r.ok; ++i) { + Tensor t; + t.name = r.str(); + const uint32_t nd = r.get(); + for (uint32_t k = 0; k < nd; ++k) t.shape.push_back(r.get()); + t.type = (int)r.get(); + t.offset = r.get(); + ts.push_back(t); + } + if (!r.ok) { err = "truncated GGUF header"; return false; } + const uint64_t pos = (uint64_t)(r.p - (const uint8_t*)map); + const uint64_t data = (pos + align - 1) / align * align; + for (Tensor& t : ts) { + t.offset += data; + uint64_t n = 1; + for (uint64_t d : t.shape) n *= d; + t.bytes = n / ref::block_elems(t.type) * ref::block_bytes(t.type); + tensors[t.name] = t; + } + return true; +} + +File::~File() { + if (map) munmap(map, map_bytes); +} + +} // namespace gguf diff --git a/metal/src/gguf_lite.h b/metal/src/gguf_lite.h new file mode 100644 index 00000000..0a2b5fbb --- /dev/null +++ b/metal/src/gguf_lite.h @@ -0,0 +1,37 @@ +// metal/src/gguf_lite.h - a minimal GGUF v3 reader for the Metal test programs: tensor names, shapes, types and +// file offsets, the file mmapped read-only (no copy; wrapped as one MTLBuffer by the caller). +#pragma once + +#include +#include +#include +#include +#include + +namespace gguf { + +struct Tensor { + std::string name; + std::vector shape; // ggml order: shape[0] is the contiguous (row) dimension + int type = -1; + uint64_t offset = 0; // from the start of the FILE (data start + tensor offset) + uint64_t bytes = 0; +}; + +struct File { + std::string path; + void* map = nullptr; // page-aligned mapping of the whole file + size_t map_bytes = 0; // rounded up to the page size + size_t file_bytes = 0; + std::map tensors; + std::map meta_str; + std::map meta_num; + bool open(const std::string& path, std::string& err); + const Tensor* find(const std::string& name) const { + auto it = tensors.find(name); + return it == tensors.end() ? nullptr : &it->second; + } + ~File(); +}; + +} // namespace gguf diff --git a/metal/src/gpu/runtime.cpp b/metal/src/gpu/runtime.cpp new file mode 100644 index 00000000..3da2aed9 --- /dev/null +++ b/metal/src/gpu/runtime.cpp @@ -0,0 +1,619 @@ +// metal/src/gpu/runtime.cpp - include/strata/gpu/runtime.hpp on Metal (metal-cpp). Skeleton of MAC-PLAN Phase 1. +// +// Memory model (measured on the M5 Max, phaseA-tests/mac-design.md): +// - every allocation is one MTLBuffer, storageModeShared, hazard tracking untracked (the engine orders its own work +// on streams, as on CUDA); the "device pointer" handed to the host code is the buffer's gpuAddress, which differs +// from contents() on Apple GPUs, so host code that wrongly dereferences a device pointer faults instead of +// silently working. host_view() is the sanctioned CPU view. +// - all buffers sit in one MTLResidencySet attached to every queue, so kernels may take raw gpuAddress pointers. +// Streams: a command queue + the open command buffer + the open compute encoder + a shared-event timeline. Work is +// committed at event records, synchronizations, host functions and every kFlushEvery dispatches. +// Graphs: begin_capture switches the stream to recording; dispatch/copy/memset/event ops are kept as data and +// re-encoded by graph_launch (encoding measured at ~0.17 us per dispatch on the M5 Max). +#define NS_PRIVATE_IMPLEMENTATION +#define MTL_PRIVATE_IMPLEMENTATION +#include +#include +#include + +#include "strata/gpu/metal.hpp" +#include "strata/gpu/runtime.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::gpu { + +namespace { + +constexpr int kFlushEvery = 4096; // dispatches per command buffer before an automatic commit + +struct Alloc { + MTL::Buffer* buf = nullptr; + uint64_t gpu = 0; + uint8_t* cpu = nullptr; + size_t bytes = 0; + bool host = false; // from host_alloc (the host code holds the CPU address) + bool purged = false; // purge_device_allocations: its memory given back (any later copy is an error) +}; + +struct Op { + enum Kind { Dispatch, Copy, Fill, Record, Wait } kind = Dispatch; + MTL::ComputePipelineState* pipe = nullptr; + uint8_t args[256]; + size_t arg_bytes = 0; + std::vector big_args; + metal::Grid groups, threads; + size_t tg_bytes = 0; + void* dst = nullptr; + const void* src = nullptr; + size_t bytes = 0; + int value = 0; + Event ev = nullptr; +}; + +} // namespace + +struct EventImpl { + MTL::SharedEvent* ev = nullptr; // the recording stream's timeline + uint64_t value = 0; // 0: never recorded (complete, as a fresh CUDA event) +}; + +struct GraphImpl { + std::vector ops; +}; +struct GraphExecImpl { + std::vector ops; +}; + +struct StreamImpl { + MTL::CommandQueue* q = nullptr; + MTL::CommandBuffer* cb = nullptr; + MTL::ComputeCommandEncoder* enc = nullptr; + MTL::SharedEvent* tl = nullptr; + uint64_t submitted = 0; // the timeline value the last committed command buffer signals + int pending = 0; // dispatches in the open command buffer + GraphImpl* rec = nullptr; +}; + +namespace { + +struct Runtime { + MTL::Device* dev = nullptr; + MTL::ResidencySet* rs = nullptr; + std::mutex mu; + std::map by_gpu; // gpuAddress -> allocation + std::map by_cpu; // contents() -> gpuAddress + StreamImpl* legacy = nullptr; + std::map pipes; + std::map libs; + metal::Stats stats; +}; + +Runtime& rt() { + static Runtime* r = [] { + auto* x = new Runtime; + x->dev = MTL::CreateSystemDefaultDevice(); + NS::Error* e = nullptr; + MTL::ResidencySetDescriptor* d = MTL::ResidencySetDescriptor::alloc()->init(); + x->rs = x->dev->newResidencySet(d, &e); + d->release(); + return x; + }(); + return *r; +} + +thread_local Error t_last = kSuccess; +Error fail(Error e) { + if (e != kSuccess && e != kNotReady) t_last = e; + return e; +} + +StreamImpl* make_stream() { + auto* s = new StreamImpl; + s->q = rt().dev->newCommandQueue(); + s->q->addResidencySet(rt().rs); + s->tl = rt().dev->newSharedEvent(); + s->tl->setSignaledValue(0); + return s; +} + +StreamImpl* S(Stream s) { + if (s) return s; + Runtime& r = rt(); + std::lock_guard lk(r.mu); + if (!r.legacy) r.legacy = make_stream(); + return r.legacy; +} + +/// The allocation that holds GPU address `p` (or CPU address `p` of a host allocation), with the offset into it. +const Alloc* find(const void* p, size_t* off) { + Runtime& r = rt(); + std::lock_guard lk(r.mu); + const uint64_t a = (uint64_t) (uintptr_t) p; + auto it = r.by_gpu.upper_bound(a); + if (it != r.by_gpu.begin()) { + --it; + if (a < it->first + it->second.bytes) { *off = a - it->first; return &it->second; } + } + auto ic = r.by_cpu.upper_bound((uintptr_t) p); + if (ic != r.by_cpu.begin()) { + --ic; + const Alloc& al = r.by_gpu[ic->second]; + if ((uintptr_t) p < ic->first + al.bytes) { *off = (uintptr_t) p - ic->first; return &al; } + } + return nullptr; +} + +MTL::CommandBuffer* open_cb(StreamImpl* s) { + if (!s->cb) { + s->cb = s->q->commandBufferWithUnretainedReferences(); + s->cb->retain(); + ++rt().stats.command_buffers; + } + return s->cb; +} +void end_encoder(StreamImpl* s) { + if (s->enc) { s->enc->endEncoding(); s->enc = nullptr; } +} +MTL::ComputeCommandEncoder* encoder(StreamImpl* s) { + if (!s->enc) s->enc = open_cb(s)->computeCommandEncoder(); // serial dispatch: each dispatch sees the last + return s->enc; +} +void flush(StreamImpl* s) { + if (!s->cb) return; + end_encoder(s); + s->cb->encodeSignalEvent(s->tl, ++s->submitted); + s->cb->commit(); + s->cb->release(); + s->cb = nullptr; + s->pending = 0; +} +Error wait_value(MTL::SharedEvent* ev, uint64_t v) { + while (ev->signaledValue() < v) std::this_thread::yield(); + ++rt().stats.host_syncs; + return kSuccess; +} + +void check_purged(const Alloc* a, const char* what) { + if (a && a->purged) { + std::fprintf(stderr, "strata metal runtime: a %s touches a device allocation of %.1f MB that was given back " + "(STRATA_METAL_KEEP_HOST_WEIGHTS=1 keeps it)\n", what, a->bytes / 1e6); + void* fr[48]; + backtrace_symbols_fd(fr, backtrace(fr, 48), 2); // which host code still reads it + std::abort(); + } +} + +Error encode_copy(StreamImpl* s, void* dst, const void* src, size_t n) { + size_t od = 0, os = 0; + const Alloc* ad = find(dst, &od); + const Alloc* as = find(src, &os); + check_purged(ad, "copy"); + check_purged(as, "copy"); + if (ad && as) { // buffer to buffer: a blit, in stream order + end_encoder(s); + MTL::BlitCommandEncoder* b = open_cb(s)->blitCommandEncoder(); + b->copyFromBuffer(as->buf, os, ad->buf, od, n); + b->endEncoding(); + ++rt().stats.blits; + return kSuccess; + } + // ordinary host memory on one side: the stream's earlier work must be complete first (the conservative CUDA + // pageable-memory semantics: the call returns when the copy is done) + flush(s); + wait_value(s->tl, s->submitted); + uint8_t* d = ad ? ad->cpu + od : (uint8_t*) dst; + const uint8_t* sp = as ? as->cpu + os : (const uint8_t*) src; + std::memcpy(d, sp, n); + return kSuccess; +} + +Error encode_fill(StreamImpl* s, void* p, int value, size_t n) { + size_t off = 0; + const Alloc* a = find(p, &off); + if (!a) return fail(kErrorInvalidValue); + check_purged(a, "fill"); + end_encoder(s); + MTL::BlitCommandEncoder* b = open_cb(s)->blitCommandEncoder(); + b->fillBuffer(a->buf, NS::Range::Make(off, n), (uint8_t) value); + b->endEncoding(); + ++rt().stats.blits; + return kSuccess; +} + +Error encode_dispatch(StreamImpl* s, const Op& o) { + MTL::ComputeCommandEncoder* e = encoder(s); + e->setComputePipelineState(o.pipe); + if (o.big_args.empty()) e->setBytes(o.args, o.arg_bytes, 0); + else e->setBytes(o.big_args.data(), o.big_args.size(), 0); + if (o.tg_bytes) e->setThreadgroupMemoryLength(o.tg_bytes, 0); + e->dispatchThreadgroups(MTL::Size(o.groups.x, o.groups.y, o.groups.z), MTL::Size(o.threads.x, o.threads.y, o.threads.z)); + ++rt().stats.dispatches; + if (++s->pending >= kFlushEvery) flush(s); + return kSuccess; +} + +Error record_event(EventImpl* e, StreamImpl* s) { + flush(s); // CUDA submits on launch: a recorded event must become complete without a further call + e->ev = s->tl; + e->value = s->submitted; + return kSuccess; +} +Error wait_event(StreamImpl* s, EventImpl* e) { + if (!e || e->value == 0) return kSuccess; + end_encoder(s); + open_cb(s)->encodeWait(e->ev, e->value); + return kSuccess; +} + +Error run_op(StreamImpl* s, const Op& o) { + switch (o.kind) { + case Op::Dispatch: return encode_dispatch(s, o); + case Op::Copy: return encode_copy(s, o.dst, o.src, o.bytes); + case Op::Fill: return encode_fill(s, o.dst, o.value, o.bytes); + case Op::Record: return record_event(o.ev, s); + case Op::Wait: return wait_event(s, o.ev); + } + return kSuccess; +} + +// STRATA_METAL_ALLOC_LOG=1: every allocation of 16 MB or more, with the running total (memory budgets on small Macs) +void alloc_log(const char* what, size_t n) { + static const bool on = std::getenv("STRATA_METAL_ALLOC_LOG") != nullptr; + static std::atomic tot{0}; + const uint64_t t = tot += n; + if (on && n >= (16u << 20)) std::fprintf(stderr, "strata metal runtime: %s %.1f MB (total %.2f GB)\n", what, n / 1e6, t / 1e9); +} + +Error new_alloc(void** p, size_t bytes, bool host) { + Runtime& r = rt(); + const size_t n = bytes ? bytes : 1; + MTL::Buffer* b = r.dev->newBuffer(n, MTL::ResourceStorageModeShared | MTL::ResourceHazardTrackingModeUntracked); + if (!b) return fail(kErrorMemoryAllocation); + Alloc a{b, b->gpuAddress(), (uint8_t*) b->contents(), n, host}; + alloc_log(host ? "host alloc" : "device alloc", n); + { + std::lock_guard lk(r.mu); + r.by_gpu[a.gpu] = a; + r.by_cpu[(uintptr_t) a.cpu] = a.gpu; + r.rs->addAllocation(b); + r.rs->commit(); + } + *p = host ? (void*) a.cpu : (void*) (uintptr_t) a.gpu; + return kSuccess; +} + +Error free_alloc(void* p) { + if (!p) return kSuccess; + Runtime& r = rt(); + size_t off = 0; + const Alloc* a = find(p, &off); + if (!a || off != 0) return fail(kErrorInvalidValue); + device_synchronize(); // as cudaFree: the GPU is done with it + std::lock_guard lk(r.mu); + MTL::Buffer* b = a->buf; + const uint64_t g = a->gpu; + r.by_cpu.erase((uintptr_t) a->cpu); + r.by_gpu.erase(g); + r.rs->removeAllocation(b); + r.rs->commit(); + b->release(); + return kSuccess; +} + +} // namespace + +// ---------------------------------------------------------------------------------------------------- runtime.hpp +void* host_view(const void* p) { + size_t off = 0; + const Alloc* a = find(p, &off); + return a ? a->cpu + off : nullptr; +} + +// The Metal decode window reads the model itself; the device copies of the weights the shared host code uploads for +// the CUDA-shaped kernels (the pack's dense pool, the native head, ...) are never read on Metal. On a small Mac their +// memory is worth more as expert arena: every device (not host) allocation of min_bytes or more is made purgeable-empty +// and dropped from the residency set. Returns the bytes given back. +uint64_t purge_device_allocations(size_t min_bytes) { + Runtime& r = rt(); + device_synchronize(); + std::lock_guard lk(r.mu); + uint64_t n = 0; + for (auto& [gpu, a] : r.by_gpu) { + if (a.host || a.purged || a.bytes < min_bytes) continue; + r.rs->removeAllocation(a.buf); + a.buf->setPurgeableState(MTL::PurgeableStateEmpty); + a.purged = true; + n += a.bytes; + } + r.rs->commit(); + return n; +} + +Error get_last_error() { const Error e = t_last; t_last = kSuccess; return e; } +Error peek_last_error() { return t_last; } +const char* error_string(Error e) { + switch (e) { + case kSuccess: return "no error"; + case kNotReady: return "device not ready"; + case kErrorInvalidValue: return "invalid argument"; + case kErrorMemoryAllocation: return "out of memory"; + case kErrorUnsupported: return "operation not supported on Metal"; + case kErrorLaunchFailure: return "command buffer failed"; + } + return "unknown Metal runtime error"; +} + +Error get_device(int* dev) { *dev = 0; return kSuccess; } +Error set_device(int dev) { return dev == 0 ? kSuccess : fail(kErrorInvalidValue); } +Error device_count(int* n) { *n = rt().dev ? 1 : 0; return kSuccess; } +Error device_synchronize() { + Runtime& r = rt(); + StreamImpl* s = S(nullptr); + flush(s); + return wait_value(s->tl, s->submitted); + (void) r; +} +Error mem_get_info(size_t* free_b, size_t* total_b) { + // the GPU's budget is the working set the OS grants this process; what is free is that minus what is allocated + MTL::Device* d = rt().dev; + const uint64_t budget = d->recommendedMaxWorkingSetSize(); + const uint64_t used = d->currentAllocatedSize(); + *total_b = (size_t) budget; + *free_b = (size_t) (used < budget ? budget - used : 0); + return kSuccess; +} +Error device_integrated(int* v, int) { *v = 1; return kSuccess; } +Error device_sm_count(int* v, int) { *v = 0; return fail(kErrorUnsupported); } // Apple reports no core count +Error device_clock_khz(int* v, int) { *v = 0; return fail(kErrorUnsupported); } +Error runtime_version(int* v) { *v = 0; return kSuccess; } +Error device_can_access_peer(int* v, int, int) { *v = 0; return kSuccess; } +Error device_enable_peer_access(int, unsigned) { return fail(kErrorUnsupported); } +Error get_device_properties(DeviceProp* p, int dev) { + if (dev != 0) return fail(kErrorInvalidValue); + *p = DeviceProp{}; + MTL::Device* d = rt().dev; + std::snprintf(p->name, sizeof p->name, "%s", d->name()->utf8String()); + std::snprintf(p->gcnArchName, sizeof p->gcnArchName, "%s", d->supportsFamily(MTL::GPUFamilyApple10) ? "apple10" : "apple9-or-older"); + p->warpSize = 32; // the SIMD-group width of every Apple GPU + p->totalGlobalMem = (size_t) d->recommendedMaxWorkingSetSize(); + return kSuccess; +} + +Error malloc_device_raw(void** p, size_t bytes) { return new_alloc(p, bytes, false); } +Error free_device(void* p) { return free_alloc(p); } +Error host_alloc_raw(void** p, size_t bytes, unsigned) { return new_alloc(p, bytes, true); } +Error free_host(void* p) { + { + Runtime& r = rt(); + std::lock_guard lk(r.mu); + auto it = r.by_cpu.find((uintptr_t) p); + if (it == r.by_cpu.end()) return fail(kErrorInvalidValue); + } + return free_alloc(p); +} +Error host_register(void* p, size_t bytes, unsigned) { + // existing host memory (an mmapped file, an arena) as a NoCopy buffer: page-aligned start and length required + const uintptr_t pg = 16384; + if (((uintptr_t) p % pg) != 0) return fail(kErrorInvalidValue); + Runtime& r = rt(); + const size_t n = (bytes + pg - 1) / pg * pg; + MTL::Buffer* b = r.dev->newBuffer(p, n, MTL::ResourceStorageModeShared | MTL::ResourceHazardTrackingModeUntracked, nullptr); + if (!b) return fail(kErrorMemoryAllocation); + Alloc a{b, b->gpuAddress(), (uint8_t*) b->contents(), n, true}; + alloc_log("host register", n); + std::lock_guard lk(r.mu); + r.by_gpu[a.gpu] = a; + r.by_cpu[(uintptr_t) a.cpu] = a.gpu; + r.rs->addAllocation(b); + r.rs->commit(); + return kSuccess; +} +Error host_unregister(void* p) { return free_alloc(p); } +Error host_device_pointer_raw(void** dev, void* host) { + size_t off = 0; + const Alloc* a = find(host, &off); + if (!a) return fail(kErrorInvalidValue); + *dev = (void*) (uintptr_t) (a->gpu + off); + return kSuccess; +} +Error memset_device(void* p, int value, size_t bytes) { + StreamImpl* s = S(nullptr); + const Error e = encode_fill(s, p, value, bytes); + flush(s); + wait_value(s->tl, s->submitted); + return e; +} +Error memset_async(void* p, int value, size_t bytes, Stream st) { + StreamImpl* s = S(st); + if (s->rec) { + Op o; + o.kind = Op::Fill; o.dst = p; o.value = value; o.bytes = bytes; + s->rec->ops.push_back(std::move(o)); + return kSuccess; + } + return encode_fill(s, p, value, bytes); +} + +Error memcpy_sync(void* dst, const void* src, size_t bytes, CopyKind) { + StreamImpl* s = S(nullptr); + const Error e = encode_copy(s, dst, src, bytes); + flush(s); + wait_value(s->tl, s->submitted); + return e; +} +Error memcpy_2d_async(void* dst, size_t dpitch, const void* src, size_t spitch, size_t width, size_t height, CopyKind k, Stream st) { + for (size_t r = 0; r < height; ++r) { // skeleton: one copy per row (rare in the engine) + const Error e = memcpy_async((uint8_t*) dst + r * dpitch, (const uint8_t*) src + r * spitch, width, k, st); + if (e != kSuccess) return e; + } + return kSuccess; +} +Error memcpy_peer_async(void* dst, int dst_dev, const void* src, int src_dev, size_t bytes, Stream st) { + if (dst_dev != 0 || src_dev != 0) return fail(kErrorInvalidValue); // one GPU + return memcpy_async(dst, src, bytes, kDeviceToDevice, st); +} +Error memcpy_async(void* dst, const void* src, size_t bytes, CopyKind, Stream st) { + StreamImpl* s = S(st); + if (s->rec) { + Op o; + o.kind = Op::Copy; o.dst = dst; o.src = src; o.bytes = bytes; + s->rec->ops.push_back(std::move(o)); + return kSuccess; + } + return encode_copy(s, dst, src, bytes); +} + +Error stream_create(Stream* s, unsigned) { *s = make_stream(); return kSuccess; } +Error stream_destroy(Stream s) { + if (!s) return kSuccess; + flush(s); + wait_value(s->tl, s->submitted); + s->tl->release(); + s->q->release(); + delete s; + return kSuccess; +} +Error stream_synchronize(Stream st) { + StreamImpl* s = S(st); + flush(s); + return wait_value(s->tl, s->submitted); +} +Error stream_query(Stream st) { + StreamImpl* s = S(st); + flush(s); + return s->tl->signaledValue() >= s->submitted ? kSuccess : kNotReady; +} +Error stream_wait_event(Stream st, Event e, unsigned) { + StreamImpl* s = S(st); + if (s->rec) { + Op o; + o.kind = Op::Wait; o.ev = e; + s->rec->ops.push_back(std::move(o)); + return kSuccess; + } + return wait_event(s, e); +} +Error launch_host_func(Stream st, HostFn fn, void* arg) { + // skeleton: in stream order by completing the stream first (the engine's uses are rare; Phase 2 replaces this by a + // completion handler + a shared-event wait so the host thread does not block) + StreamImpl* s = S(st); + if (s->rec) return fail(kErrorUnsupported); + flush(s); + wait_value(s->tl, s->submitted); + fn(arg); + return kSuccess; +} + +Error event_create(Event* e, unsigned) { *e = new EventImpl; return kSuccess; } +Error event_destroy(Event e) { delete e; return kSuccess; } +Error event_record(Event e, Stream st) { + StreamImpl* s = S(st); + if (s->rec) { + Op o; + o.kind = Op::Record; o.ev = e; + s->rec->ops.push_back(std::move(o)); + return kSuccess; + } + return record_event(e, s); +} +Error event_query(Event e) { return !e->ev || e->ev->signaledValue() >= e->value ? kSuccess : kNotReady; } +Error event_synchronize(Event e) { return e->ev ? wait_value(e->ev, e->value) : kSuccess; } +Error event_elapsed_ms(float* ms, Event, Event) { *ms = 0.0f; return fail(kErrorUnsupported); } + +Error begin_capture(Stream st) { + StreamImpl* s = S(st); + if (s->rec) return fail(kErrorInvalidValue); + flush(s); + s->rec = new GraphImpl; + return kSuccess; +} +Error end_capture(Stream st, Graph* g) { + StreamImpl* s = S(st); + if (!s->rec) { *g = nullptr; return fail(kErrorInvalidValue); } + *g = s->rec; + s->rec = nullptr; + return kSuccess; +} +Error graph_node_count(Graph g, size_t* n) { *n = g ? g->ops.size() : 0; return kSuccess; } +Error graph_instantiate(GraphExec* x, Graph g) { + *x = new GraphExecImpl{g->ops}; + return kSuccess; +} +Error graph_launch(GraphExec x, Stream st) { + StreamImpl* s = S(st); + if (s->rec) { // a graph launched into a capture becomes part of it (CUDA: a child graph) + s->rec->ops.insert(s->rec->ops.end(), x->ops.begin(), x->ops.end()); + return kSuccess; + } + for (const Op& o : x->ops) { + const Error e = run_op(s, o); + if (e != kSuccess) return e; + } + return kSuccess; +} +Error graph_upload(GraphExec, Stream) { return kSuccess; } +Error graph_destroy(Graph g) { delete g; return kSuccess; } +Error graph_exec_destroy(GraphExec x) { delete x; return kSuccess; } + +// ---------------------------------------------------------------------------------------------------- metal.hpp +namespace metal { + +MTL::Device* device() { return rt().dev; } + +MTL::ComputePipelineState* pipeline(const char* source_name, const char* source, const char* function, std::string& err) { + Runtime& r = rt(); + const std::string key = std::string(source_name) + "::" + function; + std::lock_guard lk(r.mu); + if (auto it = r.pipes.find(key); it != r.pipes.end()) return it->second; + MTL::Library*& lib = r.libs[source_name]; + NS::Error* e = nullptr; + if (!lib) { + MTL::CompileOptions* co = MTL::CompileOptions::alloc()->init(); + co->setMathMode(MTL::MathModeSafe); // no fast-math reassociation: parity with the CUDA reference first + lib = r.dev->newLibrary(NS::String::string(source, NS::UTF8StringEncoding), co, &e); + co->release(); + if (!lib) { + err = std::string("MSL compile of ") + source_name + ": " + (e ? e->localizedDescription()->utf8String() : "?"); + return nullptr; + } + } + MTL::Function* f = lib->newFunction(NS::String::string(function, NS::UTF8StringEncoding)); + if (!f) { err = std::string("no MSL function ") + function; return nullptr; } + MTL::ComputePipelineState* p = r.dev->newComputePipelineState(f, &e); + f->release(); + if (!p) { err = std::string("pipeline ") + function + ": " + (e ? e->localizedDescription()->utf8String() : "?"); return nullptr; } + r.pipes[key] = p; + return p; +} + +Error dispatch(Stream st, MTL::ComputePipelineState* p, const void* args, size_t arg_bytes, Grid groups, Grid threads, + size_t tg_bytes) { + if (arg_bytes > 4096) return fail(kErrorInvalidValue); // setBytes limit + StreamImpl* s = S(st); + Op o; + o.kind = Op::Dispatch; + o.pipe = p; + if (arg_bytes <= sizeof o.args) { std::memcpy(o.args, args, arg_bytes); o.arg_bytes = arg_bytes; } + else o.big_args.assign((const uint8_t*) args, (const uint8_t*) args + arg_bytes); + o.groups = groups; + o.threads = threads; + o.tg_bytes = tg_bytes; + if (s->rec) { s->rec->ops.push_back(std::move(o)); return kSuccess; } + return encode_dispatch(s, o); +} + +Stats stats() { return rt().stats; } + +} // namespace metal +} // namespace strata::gpu diff --git a/metal/src/mtl_rt.h b/metal/src/mtl_rt.h new file mode 100644 index 00000000..60a493f8 --- /dev/null +++ b/metal/src/mtl_rt.h @@ -0,0 +1,116 @@ +// metal/src/mtl_rt.h - a thin C++ face over Metal for the standalone kernel programs (parity, benches). +// +// The implementation (mtl_rt.mm) is the only Objective-C++ file; every program and test is plain C++ against this +// header. Kernels are MSL source files compiled at run time (newLibraryWithSource): the Command Line Tools have no +// offline `metal` compiler, and the runtime compiler is part of the OS. ggml-common.h (MIT, third_party/ggml) is +// prepended for the i-quant grids and block structs. +#pragma once + +#include +#include +#include +#include +#include + +namespace mtl { + +struct Buffer { + void* handle = nullptr; // id (retained) + void* ptr = nullptr; // CPU address (shared storage) + size_t bytes = 0; + template T* as() const { return static_cast(ptr); } +}; + +struct Pipeline { + void* handle = nullptr; // id + int max_threads = 0; // maxTotalThreadsPerThreadgroup + int simd_width = 0; // threadExecutionWidth + int static_tg_mem = 0; // staticThreadgroupMemoryLength +}; + +// A function-constant value set (index -> int / bool / uint). +struct Constants { + struct V { int index; int type; uint32_t v; }; // type 0 int, 1 bool, 2 uint, 3 short, 4 ushort + std::vector vals; + Constants& i(int idx, int v) { vals.push_back({idx, 0, (uint32_t)v}); return *this; } + Constants& b(int idx, bool v) { vals.push_back({idx, 1, (uint32_t)v}); return *this; } + Constants& u(int idx, uint32_t v) { vals.push_back({idx, 2, v}); return *this; } +}; + +struct Arg { // one argument of a dispatch: a buffer (+ offset) or inline bytes + const Buffer* buf = nullptr; + size_t off = 0; + std::vector bytes; + static Arg B(const Buffer& b, size_t off = 0) { Arg a; a.buf = &b; a.off = off; return a; } + template static Arg V(const T& v) { + Arg a; a.bytes.resize(sizeof(T)); std::memcpy(a.bytes.data(), &v, sizeof(T)); return a; + } +}; + +struct Dispatch { + const Pipeline* p = nullptr; + std::vector args; + uint32_t grid[3] = {1, 1, 1}; // threadgroups + uint32_t tg[3] = {32, 1, 1}; // threads per threadgroup + uint32_t tg_mem = 0; // dynamic threadgroup memory at index 0 (bytes) + const Buffer* indirect = nullptr; // grid from a GPU buffer (3 x uint32 threadgroup counts) at ind_off + size_t ind_off = 0; + bool barrier = true; // run_graph: a buffer memory barrier before this dispatch +}; + +class Context { +public: + Context(); + ~Context(); + std::string device_name() const; + bool has_family_apple(int n) const; // MTLGPUFamilyApple + bool supports_metal4() const; + uint64_t recommended_working_set() const; + uint64_t max_buffer_length() const; + uint64_t allocated() const { return allocated_; } // bytes of alloc() + wrap() buffers so far + + // Compiles a library from MSL source files (paths), prepended by `prelude` (defines) and, if include_ggml, + // ggml-common.h with GGML_COMMON_DECL_METAL/IMPL_METAL. Returns a library id (index); aborts with the + // compiler log on error. + // Safe math unless STRATA_METAL_MATH=fast (the argument is ignored; kept for callers). + int compile(const std::vector& files, const std::string& prelude = "", bool fast_math = false); + Pipeline pipeline(int lib, const std::string& fn, const Constants& c = {}); + + Buffer alloc(size_t bytes); // shared storage, zeroed + Buffer wrap(void* page_aligned, size_t bytes); // no-copy wrap (page-aligned, size multiple of page) + void free(Buffer& b); + + // Encodes `ds` into ONE compute encoder (serial or concurrent dispatch type) and ONE command buffer, `reps` + // times over; commits and waits. Returns the GPU time (GPUEndTime - GPUStartTime) in seconds. + double run(const std::vector& ds, int reps = 1, bool concurrent = false, bool barrier_between = false); + // A dependency graph in ONE concurrent encoder: a memory barrier only before dispatches with `barrier` set, so + // the dispatches between two barriers may overlap. Returns the GPU time in seconds. + double run_graph(const std::vector& ds); + // run_graph in segments: the dispatches [cuts[s-1], cuts[s]) are one concurrent encoder; after segment s (for + // s < cuts.size()) the GPU signals a shared event and waits until the host has run at_cut(s) - the host's turn + // between two parts of one committed command buffer (the SSD-streaming handshake: the routing is read, the + // missing experts are put in place). Returns the GPU time in seconds. + double run_graph_seg(const std::vector& ds, const std::vector& cuts, void (*at_cut)(void*, int), + void* user); + // One command buffer per `run_cb` call, empty or not: measures commit+wait round trips. + double run_wall(const std::vector& ds, int reps, double* gpu_seconds = nullptr); + + // Indirect command buffer: the dispatches recorded once, executed `reps` times in one command buffer. + // Buffers are bound per command (setKernelBuffer); inline bytes are not allowed (use buffers). + double run_icb(const std::vector& ds, int reps, bool barrier_between); + // Runs `ds` repeatedly for about `seconds` of wall time: lifts the GPU out of its idle clocks before a timing. + void warm(const std::vector& ds, double seconds = 0.3); + + std::string ggml_common_path; // where ggml-common.h is read from + std::string kernel_dir; // where relative kernel paths resolve + +private: + struct Impl; + Impl* impl_; + uint64_t allocated_ = 0; +}; + +double now_s(); // monotonic wall clock (seconds) +std::string read_file(const std::string& path); + +} // namespace mtl diff --git a/metal/src/mtl_rt.mm b/metal/src/mtl_rt.mm new file mode 100644 index 00000000..b8540892 --- /dev/null +++ b/metal/src/mtl_rt.mm @@ -0,0 +1,352 @@ +// metal/src/mtl_rt.mm - see mtl_rt.h. Built with ARC (-fobjc-arc). +#import +#import + +#include "mtl_rt.h" + +#include +#include +#include +#include +#include + +namespace mtl { + +double now_s() { + return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); +} + +std::string read_file(const std::string& path) { + std::ifstream f(path, std::ios::binary); + if (!f) { + std::fprintf(stderr, "mtl: cannot read %s\n", path.c_str()); + std::exit(2); + } + std::stringstream ss; + ss << f.rdbuf(); + return ss.str(); +} + +struct Context::Impl { + id dev; + id q; + std::vector> libs; + id ev = nil; // run_graph_seg's handshake timeline + uint64_t ev_v = 0; +}; + +static inline id B(const Buffer& b) { return (__bridge id)b.handle; } +static inline id P(const Pipeline* p) { return (__bridge id)p->handle; } + +Context::Context() : impl_(new Impl) { + impl_->dev = MTLCreateSystemDefaultDevice(); + if (!impl_->dev) { + std::fprintf(stderr, "mtl: no Metal device\n"); + std::exit(2); + } + impl_->q = [impl_->dev newCommandQueue]; + const char* g = std::getenv("STRATA_GGML_COMMON"); + ggml_common_path = g ? g : STRATA_GGML_COMMON_DEFAULT; + const char* k = std::getenv("STRATA_METAL_KERNELS"); + kernel_dir = k ? k : STRATA_METAL_KERNELS_DEFAULT; +} + +Context::~Context() { delete impl_; } + +std::string Context::device_name() const { return [[impl_->dev name] UTF8String]; } +bool Context::has_family_apple(int n) const { + return [impl_->dev supportsFamily:(MTLGPUFamily)(MTLGPUFamilyApple1 + (n - 1))]; +} +bool Context::supports_metal4() const { + if (@available(macOS 26.0, *)) return [impl_->dev supportsFamily:MTLGPUFamilyMetal4]; + return false; +} +uint64_t Context::recommended_working_set() const { return [impl_->dev recommendedMaxWorkingSetSize]; } +uint64_t Context::max_buffer_length() const { return [impl_->dev maxBufferLength]; } + +int Context::compile(const std::vector& files, const std::string& prelude, bool fast_math) { + std::string src = prelude + "\n#include \nusing namespace metal;\n"; + if (!ggml_common_path.empty() && prelude.find("NO_GGML_COMMON") == std::string::npos) { + src += "#define GGML_COMMON_DECL_METAL\n#define GGML_COMMON_IMPL_METAL\n"; + src += read_file(ggml_common_path); + src += "\n"; + } + for (const auto& f : files) { + std::string p = (f.size() && f[0] == '/') ? f : kernel_dir + "/" + f; + src += "#line 1 \"" + f + "\"\n" + read_file(p) + "\n"; + } + MTLCompileOptions* o = [MTLCompileOptions new]; + // Safe math by default: no reassociation, so every token of a window is bitwise what a one-token call gives + // (the kernels write their contractions as explicit fma). Measured free on the M5 Max. + fast_math = false; + if (const char* m = std::getenv("STRATA_METAL_MATH")) fast_math = std::string(m) == "fast"; + if (@available(macOS 15.0, *)) { + o.mathMode = fast_math ? MTLMathModeFast : MTLMathModeSafe; + } else { + o.fastMathEnabled = fast_math; + } + NSError* err = nil; + id lib = [impl_->dev newLibraryWithSource:[NSString stringWithUTF8String:src.c_str()] options:o error:&err]; + if (!lib) { + std::fprintf(stderr, "mtl: compile failed:\n%s\n", [[err localizedDescription] UTF8String]); + std::exit(3); + } + impl_->libs.push_back(lib); + return (int)impl_->libs.size() - 1; +} + +Pipeline Context::pipeline(int lib, const std::string& fn, const Constants& c) { + NSError* err = nil; + id f; + NSString* name = [NSString stringWithUTF8String:fn.c_str()]; + if (c.vals.empty()) { + f = [impl_->libs[lib] newFunctionWithName:name]; + // a function with (optional) function constants needs a specialization even when none is set + if (f && f.functionConstantsDictionary.count > 0) + f = [impl_->libs[lib] newFunctionWithName:name constantValues:[MTLFunctionConstantValues new] error:&err]; + } else { + MTLFunctionConstantValues* cv = [MTLFunctionConstantValues new]; + for (const auto& v : c.vals) { + int32_t iv = (int32_t)v.v; + bool bv = v.v != 0; + uint32_t uv = v.v; + switch (v.type) { + case 0: [cv setConstantValue:&iv type:MTLDataTypeInt atIndex:v.index]; break; + case 1: [cv setConstantValue:&bv type:MTLDataTypeBool atIndex:v.index]; break; + default: [cv setConstantValue:&uv type:MTLDataTypeUInt atIndex:v.index]; break; + } + } + f = [impl_->libs[lib] newFunctionWithName:name constantValues:cv error:&err]; + } + if (!f) { + std::fprintf(stderr, "mtl: no function %s %s\n", fn.c_str(), err ? [[err localizedDescription] UTF8String] : ""); + std::exit(3); + } + MTLComputePipelineDescriptor* d = [MTLComputePipelineDescriptor new]; + d.computeFunction = f; + d.supportIndirectCommandBuffers = YES; + id ps = [impl_->dev newComputePipelineStateWithDescriptor:d + options:MTLPipelineOptionNone + reflection:nil + error:&err]; + if (!ps) { + std::fprintf(stderr, "mtl: pipeline %s: %s\n", fn.c_str(), [[err localizedDescription] UTF8String]); + std::exit(3); + } + Pipeline p; + p.handle = (__bridge_retained void*)ps; + p.max_threads = (int)ps.maxTotalThreadsPerThreadgroup; + p.simd_width = (int)ps.threadExecutionWidth; + p.static_tg_mem = (int)ps.staticThreadgroupMemoryLength; + return p; +} + +Buffer Context::alloc(size_t bytes) { + id b = [impl_->dev newBufferWithLength:bytes options:MTLResourceStorageModeShared]; + if (!b) { + std::fprintf(stderr, "mtl: alloc %zu failed\n", bytes); + std::exit(4); + } + std::memset([b contents], 0, bytes); + allocated_ += bytes; + Buffer r; + r.handle = (__bridge_retained void*)b; + r.ptr = [b contents]; + r.bytes = bytes; + return r; +} + +Buffer Context::wrap(void* p, size_t bytes) { + id b = [impl_->dev newBufferWithBytesNoCopy:p length:bytes options:MTLResourceStorageModeShared deallocator:nil]; + if (!b) { + std::fprintf(stderr, "mtl: wrap %zu failed\n", bytes); + std::exit(4); + } + allocated_ += bytes; + Buffer r; + r.handle = (__bridge_retained void*)b; + r.ptr = p; + r.bytes = bytes; + return r; +} + +void Context::free(Buffer& b) { + if (b.handle) { + id x = (__bridge_transfer id)b.handle; + x = nil; + } + b = Buffer{}; +} + +static void encode(id enc, const Dispatch& d) { + [enc setComputePipelineState:P(d.p)]; + for (size_t i = 0; i < d.args.size(); ++i) { + const Arg& a = d.args[i]; + if (a.buf) + [enc setBuffer:B(*a.buf) offset:a.off atIndex:i]; + else + [enc setBytes:a.bytes.data() length:a.bytes.size() atIndex:i]; + } + if (d.tg_mem) [enc setThreadgroupMemoryLength:(d.tg_mem + 15) / 16 * 16 atIndex:0]; + if (d.indirect) + [enc dispatchThreadgroupsWithIndirectBuffer:B(*d.indirect) + indirectBufferOffset:d.ind_off + threadsPerThreadgroup:MTLSizeMake(d.tg[0], d.tg[1], d.tg[2])]; + else + [enc dispatchThreadgroups:MTLSizeMake(d.grid[0], d.grid[1], d.grid[2]) + threadsPerThreadgroup:MTLSizeMake(d.tg[0], d.tg[1], d.tg[2])]; +} + +double Context::run(const std::vector& ds, int reps, bool concurrent, bool barrier_between) { + @autoreleasepool { + id cb = [impl_->q commandBufferWithUnretainedReferences]; + id enc = + [cb computeCommandEncoderWithDispatchType:concurrent ? MTLDispatchTypeConcurrent : MTLDispatchTypeSerial]; + for (int r = 0; r < reps; ++r) + for (const auto& d : ds) { + encode(enc, d); + if (barrier_between) [enc memoryBarrierWithScope:MTLBarrierScopeBuffers]; + } + [enc endEncoding]; + [cb commit]; + [cb waitUntilCompleted]; + if (cb.status != MTLCommandBufferStatusCompleted) { + std::fprintf(stderr, "mtl: command buffer failed: %s\n", [[cb.error localizedDescription] UTF8String]); + std::exit(5); + } + return cb.GPUEndTime - cb.GPUStartTime; + } +} + +double Context::run_graph(const std::vector& ds) { + @autoreleasepool { + id cb = [impl_->q commandBufferWithUnretainedReferences]; + id enc = [cb computeCommandEncoderWithDispatchType:MTLDispatchTypeConcurrent]; + for (size_t i = 0; i < ds.size(); ++i) { + if (i > 0 && ds[i].barrier) [enc memoryBarrierWithScope:MTLBarrierScopeBuffers]; + encode(enc, ds[i]); + } + [enc endEncoding]; + [cb commit]; + [cb waitUntilCompleted]; + if (cb.status != MTLCommandBufferStatusCompleted) { + std::fprintf(stderr, "mtl: command buffer failed: %s\n", [[cb.error localizedDescription] UTF8String]); + std::exit(5); + } + return cb.GPUEndTime - cb.GPUStartTime; + } +} + +double Context::run_graph_seg(const std::vector& ds, const std::vector& cuts, void (*at_cut)(void*, int), + void* user) { + @autoreleasepool { + if (impl_->ev == nil) impl_->ev = [impl_->dev newSharedEvent]; + id ev = impl_->ev; + const uint64_t base = impl_->ev_v; + id cb = [impl_->q commandBufferWithUnretainedReferences]; + size_t i = 0; + for (size_t s = 0; s <= cuts.size(); ++s) { + const size_t end = s < cuts.size() ? (size_t) cuts[s] : ds.size(); + id enc = [cb computeCommandEncoderWithDispatchType:MTLDispatchTypeConcurrent]; + const size_t first = i; + for (; i < end; ++i) { + if (i > first && ds[i].barrier) [enc memoryBarrierWithScope:MTLBarrierScopeBuffers]; + encode(enc, ds[i]); + } + [enc endEncoding]; + if (s < cuts.size()) { + [cb encodeSignalEvent:ev value:base + 2 * s + 1]; + [cb encodeWaitForEvent:ev value:base + 2 * s + 2]; + } + } + [cb commit]; + for (size_t s = 0; s < cuts.size(); ++s) { + const uint64_t want = base + 2 * s + 1; + while (ev.signaledValue < want) { + if (cb.status >= MTLCommandBufferStatusCompleted) break; // an error: the wait below reports it + } + at_cut(user, (int) s); + ev.signaledValue = base + 2 * s + 2; + } + impl_->ev_v = base + 2 * cuts.size() + 2; + [cb waitUntilCompleted]; + if (cb.status != MTLCommandBufferStatusCompleted) { + std::fprintf(stderr, "mtl: command buffer failed: %s\n", [[cb.error localizedDescription] UTF8String]); + std::exit(5); + } + return cb.GPUEndTime - cb.GPUStartTime; + } +} + +double Context::run_wall(const std::vector& ds, int reps, double* gpu_seconds) { + double gpu = 0; + const double t0 = now_s(); + for (int r = 0; r < reps; ++r) { + @autoreleasepool { + id cb = [impl_->q commandBufferWithUnretainedReferences]; + id enc = [cb computeCommandEncoder]; + for (const auto& d : ds) encode(enc, d); + [enc endEncoding]; + [cb commit]; + [cb waitUntilCompleted]; + gpu += cb.GPUEndTime - cb.GPUStartTime; + } + } + if (gpu_seconds) *gpu_seconds = gpu; + return now_s() - t0; +} + +void Context::warm(const std::vector& ds, double seconds) { + const double t0 = now_s(); + while (now_s() - t0 < seconds) run(ds); +} + +double Context::run_icb(const std::vector& ds, int reps, bool barrier_between) { + @autoreleasepool { + size_t maxb = 1; + for (const auto& d : ds) maxb = std::max(maxb, d.args.size()); + MTLIndirectCommandBufferDescriptor* desc = [MTLIndirectCommandBufferDescriptor new]; + desc.commandTypes = MTLIndirectCommandTypeConcurrentDispatch; + desc.inheritBuffers = NO; + desc.inheritPipelineState = NO; + desc.maxKernelBufferBindCount = maxb; + id icb = [impl_->dev newIndirectCommandBufferWithDescriptor:desc + maxCommandCount:ds.size() + options:0]; + NSMutableSet* used = [NSMutableSet new]; + for (size_t i = 0; i < ds.size(); ++i) { + const Dispatch& d = ds[i]; + id c = [icb indirectComputeCommandAtIndex:i]; + [c setComputePipelineState:P(d.p)]; + for (size_t a = 0; a < d.args.size(); ++a) { + if (!d.args[a].buf) { + std::fprintf(stderr, "mtl: run_icb needs buffer arguments only\n"); + std::exit(5); + } + [c setKernelBuffer:B(*d.args[a].buf) offset:d.args[a].off atIndex:a]; + [used addObject:B(*d.args[a].buf)]; + } + if (d.tg_mem) [c setThreadgroupMemoryLength:(d.tg_mem + 15) / 16 * 16 atIndex:0]; + [c concurrentDispatchThreadgroups:MTLSizeMake(d.grid[0], d.grid[1], d.grid[2]) + threadsPerThreadgroup:MTLSizeMake(d.tg[0], d.tg[1], d.tg[2])]; + if (barrier_between) [c setBarrier]; + } + id cb = [impl_->q commandBufferWithUnretainedReferences]; + id enc = [cb computeCommandEncoderWithDispatchType:MTLDispatchTypeConcurrent]; + for (id b in used) [enc useResource:b usage:MTLResourceUsageRead | MTLResourceUsageWrite]; + for (int r = 0; r < reps; ++r) { + [enc executeCommandsInBuffer:icb withRange:NSMakeRange(0, ds.size())]; + if (barrier_between) [enc memoryBarrierWithScope:MTLBarrierScopeBuffers]; + } + [enc endEncoding]; + [cb commit]; + [cb waitUntilCompleted]; + if (cb.status != MTLCommandBufferStatusCompleted) { + std::fprintf(stderr, "mtl: icb command buffer failed: %s\n", [[cb.error localizedDescription] UTF8String]); + std::exit(5); + } + return cb.GPUEndTime - cb.GPUStartTime; + } +} + +} // namespace mtl diff --git a/metal/src/ref_quant.cpp b/metal/src/ref_quant.cpp new file mode 100644 index 00000000..ede5e5b3 --- /dev/null +++ b/metal/src/ref_quant.cpp @@ -0,0 +1,445 @@ +// metal/src/ref_quant.cpp - see ref_quant.h. The i-quant loops are transcribed from ggml-quants.c +// (dequantize_row_iq2_xxs / iq2_xs / iq2_s / iq3_xxs / iq3_s / iq4_nl / iq4_xs) at 3cf03257; the K-quants and the +// 32-blocks from Strata's include/strata/artifact/dequant.hpp (themselves transcribed from the same commit). +#include "ref_quant.h" + +#include +#include +#include +#include +#include + +#define GGML_COMMON_DECL_CPP +#define GGML_COMMON_IMPL_CPP +#include "ggml-common.h" + +namespace ref { + +const char* type_name(int t) { + switch (t) { + case F32: return "F32"; case F16: return "F16"; case BF16: return "BF16"; + case Q4_0: return "Q4_0"; case Q5_0: return "Q5_0"; case Q5_1: return "Q5_1"; case Q8_0: return "Q8_0"; + case Q3_K: return "Q3_K"; case Q4_K: return "Q4_K"; case Q5_K: return "Q5_K"; case Q6_K: return "Q6_K"; + case IQ2_XXS: return "IQ2_XXS"; case IQ2_XS: return "IQ2_XS"; case IQ2_S: return "IQ2_S"; + case IQ3_XXS: return "IQ3_XXS"; case IQ3_S: return "IQ3_S"; case IQ4_NL: return "IQ4_NL"; + case IQ4_XS: return "IQ4_XS"; case Q2_0: return "Q2_0"; + } + return "?"; +} + +int block_elems(int t) { + switch (t) { + case F32: case F16: case BF16: return 1; + case Q4_0: case Q5_0: case Q5_1: case Q8_0: case IQ4_NL: return 32; + case Q2_0: return 64; + default: return 256; + } +} + +int block_bytes(int t) { + switch (t) { + case F32: return 4; case F16: case BF16: return 2; + case Q4_0: return 18; case Q5_0: return 22; case Q5_1: return 24; case Q8_0: return 34; case IQ4_NL: return 18; case Q2_0: return 18; + case Q3_K: return 110; case Q4_K: return 144; case Q5_K: return 176; case Q6_K: return 210; + case IQ2_XXS: return 66; case IQ2_XS: return 74; case IQ2_S: return 82; case IQ3_XXS: return 98; + case IQ3_S: return 110; case IQ4_XS: return 136; + } + std::fprintf(stderr, "ref: unknown type %d\n", t); + std::exit(2); +} + +float f16_to_f32(uint16_t h) { + const uint32_t sign = (uint32_t)(h >> 15) & 1u; + uint32_t exp = (h >> 10) & 0x1Fu, man = h & 0x3FFu, f; + if (exp == 0) { + if (man == 0) + f = sign << 31; + else { + exp = 127 - 15 + 1; + while (!(man & 0x400u)) { man <<= 1; --exp; } + man &= 0x3FFu; + f = (sign << 31) | (exp << 23) | (man << 13); + } + } else if (exp == 31) + f = (sign << 31) | 0x7F800000u | (man << 13); + else + f = (sign << 31) | ((exp - 15 + 127) << 23) | (man << 13); + float out; + std::memcpy(&out, &f, 4); + return out; +} + +uint16_t f32_to_f16(float f) { + _Float16 h = (_Float16)f; + uint16_t r; + std::memcpy(&r, &h, 2); + return r; +} + +float bf16_to_f32(uint16_t h) { + const uint32_t f = (uint32_t)h << 16; + float out; + std::memcpy(&out, &f, 4); + return out; +} + +uint16_t f32_to_bf16(float f) { + uint32_t u; + std::memcpy(&u, &f, 4); + u += 0x7FFFu + ((u >> 16) & 1u); + return (uint16_t)(u >> 16); +} + +static inline uint16_t rd16(const uint8_t* p) { return (uint16_t)(p[0] | (p[1] << 8)); } + +static void get_scale_min_k4(int j, const uint8_t* q, uint8_t& d, uint8_t& m) { + if (j < 4) { + d = q[j] & 63; + m = q[j + 4] & 63; + } else { + d = (q[j + 4] & 0x0F) | ((q[j - 4] >> 6) << 4); + m = (q[j + 4] >> 4) | ((q[j - 0] >> 6) << 4); + } +} + +static void deq_block(int t, const uint8_t* b, float* y) { + switch (t) { + case Q2_0: { + const float d = f16_to_f32(rd16(b)); + for (int j = 0; j < 64; ++j) y[j] = (float)(((b[2 + j / 4] >> ((j % 4) * 2)) & 3) - 1) * d; + return; + } + case Q8_0: { + const float d = f16_to_f32(rd16(b)); + for (int j = 0; j < 32; ++j) y[j] = (float)(int8_t)b[2 + j] * d; + return; + } + case Q4_0: { + const float d = f16_to_f32(rd16(b)); + for (int j = 0; j < 16; ++j) { + y[j] = (float)((b[2 + j] & 15) - 8) * d; + y[j + 16] = (float)((b[2 + j] >> 4) - 8) * d; + } + return; + } + case Q5_0: { + const float d = f16_to_f32(rd16(b)); + uint32_t h; + std::memcpy(&h, b + 2, 4); + const uint8_t* qs = b + 6; + for (int j = 0; j < 16; ++j) { + const int x0 = (qs[j] & 15) | (((h >> j) & 1) << 4), x1 = (qs[j] >> 4) | (((h >> (j + 16)) & 1) << 4); + y[j] = (float)(x0 - 16) * d; + y[j + 16] = (float)(x1 - 16) * d; + } + return; + } + case Q5_1: { // ggml dequantize_row_q5_1: y = x * d + m + const float d = f16_to_f32(rd16(b)), m = f16_to_f32(rd16(b + 2)); + uint32_t h; + std::memcpy(&h, b + 4, 4); + const uint8_t* qs = b + 8; + for (int j = 0; j < 16; ++j) { + const int x0 = (qs[j] & 15) | (((h >> j) & 1) << 4), x1 = (qs[j] >> 4) | (((h >> (j + 16)) & 1) << 4); + y[j] = (float)x0 * d + m; + y[j + 16] = (float)x1 * d + m; + } + return; + } + case IQ4_NL: { + const float d = f16_to_f32(rd16(b)); + for (int j = 0; j < 16; ++j) { + y[j] = d * kvalues_iq4nl[b[2 + j] & 15]; + y[j + 16] = d * kvalues_iq4nl[b[2 + j] >> 4]; + } + return; + } + case IQ4_XS: { + const float d = f16_to_f32(rd16(b)); + const uint16_t sh = rd16(b + 2); + const uint8_t* sl = b + 4; + const uint8_t* qs = b + 8; + for (int ib = 0; ib < 8; ++ib) { + const int ls = ((sl[ib / 2] >> (4 * (ib % 2))) & 15) | (((sh >> (2 * ib)) & 3) << 4); + const float dl = d * (ls - 32); + for (int j = 0; j < 16; ++j) { + y[j] = dl * kvalues_iq4nl[qs[j] & 15]; + y[j + 16] = dl * kvalues_iq4nl[qs[j] >> 4]; + } + y += 32; + qs += 16; + } + return; + } + case Q6_K: { + const uint8_t* ql = b; + const uint8_t* qh = b + 128; + const int8_t* sc = (const int8_t*)(b + 192); + const float d = f16_to_f32(rd16(b + 208)); + for (int n = 0; n < 256; n += 128) { + for (int l = 0; l < 32; ++l) { + const int is = l / 16; + const int q1 = (int)((ql[l] & 15) | (((qh[l] >> 0) & 3) << 4)) - 32; + const int q2 = (int)((ql[l + 32] & 15) | (((qh[l] >> 2) & 3) << 4)) - 32; + const int q3 = (int)((ql[l] >> 4) | (((qh[l] >> 4) & 3) << 4)) - 32; + const int q4 = (int)((ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4)) - 32; + y[l] = d * sc[is] * q1; + y[l + 32] = d * sc[is + 2] * q2; + y[l + 64] = d * sc[is + 4] * q3; + y[l + 96] = d * sc[is + 6] * q4; + } + y += 128; + ql += 64; + qh += 32; + sc += 8; + } + return; + } + case Q4_K: { + const float d = f16_to_f32(rd16(b)), mn = f16_to_f32(rd16(b + 2)); + const uint8_t* sc = b + 4; + const uint8_t* q = b + 16; + int is = 0; + for (int j = 0; j < 256; j += 64) { + uint8_t s, m; + get_scale_min_k4(is, sc, s, m); + const float d1 = d * s, m1 = mn * m; + get_scale_min_k4(is + 1, sc, s, m); + const float d2 = d * s, m2 = mn * m; + for (int l = 0; l < 32; ++l) *y++ = d1 * (q[l] & 15) - m1; + for (int l = 0; l < 32; ++l) *y++ = d2 * (q[l] >> 4) - m2; + q += 32; + is += 2; + } + return; + } + case Q5_K: { + const float d = f16_to_f32(rd16(b)), mn = f16_to_f32(rd16(b + 2)); + const uint8_t* sc = b + 4; + const uint8_t* qh = b + 16; + const uint8_t* ql = b + 48; + int is = 0; + uint8_t u1 = 1, u2 = 2; + for (int j = 0; j < 256; j += 64) { + uint8_t s, m; + get_scale_min_k4(is, sc, s, m); + const float d1 = d * s, m1 = mn * m; + get_scale_min_k4(is + 1, sc, s, m); + const float d2 = d * s, m2 = mn * m; + for (int l = 0; l < 32; ++l) *y++ = d1 * ((ql[l] & 15) + ((qh[l] & u1) ? 16 : 0)) - m1; + for (int l = 0; l < 32; ++l) *y++ = d2 * ((ql[l] >> 4) + ((qh[l] & u2) ? 16 : 0)) - m2; + ql += 32; + is += 2; + u1 <<= 2; + u2 <<= 2; + } + return; + } + case Q3_K: { + const uint8_t* hm = b; + const uint8_t* q = b + 32; + const float d_all = f16_to_f32(rd16(b + 108)); + const uint32_t kmask1 = 0x03030303u, kmask2 = 0x0f0f0f0fu; + uint32_t aux[4] = {0, 0, 0, 0}; + std::memcpy(aux, b + 96, 12); + const uint32_t tmp = aux[2]; + aux[2] = ((aux[0] >> 4) & kmask2) | (((tmp >> 4) & kmask1) << 4); + aux[3] = ((aux[1] >> 4) & kmask2) | (((tmp >> 6) & kmask1) << 4); + aux[0] = (aux[0] & kmask2) | (((tmp >> 0) & kmask1) << 4); + aux[1] = (aux[1] & kmask2) | (((tmp >> 2) & kmask1) << 4); + const int8_t* scales = (const int8_t*)aux; + int is = 0; + uint8_t m = 1; + for (int n = 0; n < 256; n += 128) { + int shift = 0; + for (int j = 0; j < 4; ++j) { + float dl = d_all * (scales[is++] - 32); + for (int l = 0; l < 16; ++l) *y++ = dl * ((int8_t)((q[l] >> shift) & 3) - ((hm[l] & m) ? 0 : 4)); + dl = d_all * (scales[is++] - 32); + for (int l = 0; l < 16; ++l) + *y++ = dl * ((int8_t)((q[l + 16] >> shift) & 3) - ((hm[l + 16] & m) ? 0 : 4)); + shift += 2; + m <<= 1; + } + q += 32; + } + return; + } + case IQ2_XXS: { + const float d = f16_to_f32(rd16(b)); + const uint8_t* qs = b + 2; + for (int ib32 = 0; ib32 < 8; ++ib32) { + uint32_t aux32[2]; + std::memcpy(aux32, qs + 8 * ib32, 8); + const uint8_t* aux8 = (const uint8_t*)aux32; + const float db = d * (0.5f + (aux32[1] >> 28)) * 0.25f; + for (int l = 0; l < 4; ++l) { + const uint8_t* grid = (const uint8_t*)(iq2xxs_grid + aux8[l]); + const uint8_t signs = ksigns_iq2xs[(aux32[1] >> 7 * l) & 127]; + for (int j = 0; j < 8; ++j) y[j] = db * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f); + y += 8; + } + } + return; + } + case IQ2_XS: { + const float d = f16_to_f32(rd16(b)); + const uint8_t* q8 = b + 2; + const uint8_t* scales = b + 66; + for (int ib32 = 0; ib32 < 8; ++ib32) { + const float db0 = d * (0.5f + (scales[ib32] & 15)) * 0.25f; + const float db1 = d * (0.5f + (scales[ib32] >> 4)) * 0.25f; + for (int l = 0; l < 4; ++l) { + const uint16_t q = rd16(q8 + 2 * (4 * ib32 + l)); + const uint8_t* grid = (const uint8_t*)(iq2xs_grid + (q & 511)); + const uint8_t signs = ksigns_iq2xs[q >> 9]; + const float db = l < 2 ? db0 : db1; + for (int j = 0; j < 8; ++j) y[j] = db * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f); + y += 8; + } + } + return; + } + case IQ2_S: { + const float d = f16_to_f32(rd16(b)); + const uint8_t* qs = b + 2; + const uint8_t* qh = b + 66; + const uint8_t* scales = b + 74; + const uint8_t* signs = qs + 32; + for (int ib32 = 0; ib32 < 8; ++ib32) { + const float db0 = d * (0.5f + (scales[ib32] & 15)) * 0.25f; + const float db1 = d * (0.5f + (scales[ib32] >> 4)) * 0.25f; + for (int l = 0; l < 4; ++l) { + const float dl = l < 2 ? db0 : db1; + const uint8_t* grid = (const uint8_t*)(iq2s_grid + (qs[l] | ((qh[ib32] << (8 - 2 * l)) & 0x300))); + for (int j = 0; j < 8; ++j) y[j] = dl * grid[j] * (signs[l] & kmask_iq2xs[j] ? -1.f : 1.f); + y += 8; + } + qs += 4; + signs += 4; + } + return; + } + case IQ3_XXS: { + const float d = f16_to_f32(rd16(b)); + const uint8_t* qs = b + 2; + const uint8_t* sas = b + 2 + 64; + for (int ib32 = 0; ib32 < 8; ++ib32) { + uint32_t aux32; + std::memcpy(&aux32, sas + 4 * ib32, 4); + const float db = d * (0.5f + (aux32 >> 28)) * 0.5f; + for (int l = 0; l < 4; ++l) { + const uint8_t signs = ksigns_iq2xs[(aux32 >> 7 * l) & 127]; + const uint8_t* g1 = (const uint8_t*)(iq3xxs_grid + qs[2 * l + 0]); + const uint8_t* g2 = (const uint8_t*)(iq3xxs_grid + qs[2 * l + 1]); + for (int j = 0; j < 4; ++j) { + y[j + 0] = db * g1[j] * (signs & kmask_iq2xs[j + 0] ? -1.f : 1.f); + y[j + 4] = db * g2[j] * (signs & kmask_iq2xs[j + 4] ? -1.f : 1.f); + } + y += 8; + } + qs += 8; + } + return; + } + case IQ3_S: { + const float d = f16_to_f32(rd16(b)); + const uint8_t* qs = b + 2; + const uint8_t* qh = b + 66; + const uint8_t* signs = b + 74; + const uint8_t* scales = b + 106; + for (int ib32 = 0; ib32 < 8; ib32 += 2) { + const float db1 = d * (1 + 2 * (scales[ib32 / 2] & 15)); + const float db2 = d * (1 + 2 * (scales[ib32 / 2] >> 4)); + for (int l = 0; l < 4; ++l) { + const uint8_t* g1 = (const uint8_t*)(iq3s_grid + (qs[2 * l + 0] | ((qh[0] << (8 - 2 * l)) & 256))); + const uint8_t* g2 = (const uint8_t*)(iq3s_grid + (qs[2 * l + 1] | ((qh[0] << (7 - 2 * l)) & 256))); + for (int j = 0; j < 4; ++j) { + y[j + 0] = db1 * g1[j] * (signs[l] & kmask_iq2xs[j + 0] ? -1.f : 1.f); + y[j + 4] = db1 * g2[j] * (signs[l] & kmask_iq2xs[j + 4] ? -1.f : 1.f); + } + y += 8; + } + qs += 8; + signs += 4; + for (int l = 0; l < 4; ++l) { + const uint8_t* g1 = (const uint8_t*)(iq3s_grid + (qs[2 * l + 0] | ((qh[1] << (8 - 2 * l)) & 256))); + const uint8_t* g2 = (const uint8_t*)(iq3s_grid + (qs[2 * l + 1] | ((qh[1] << (7 - 2 * l)) & 256))); + for (int j = 0; j < 4; ++j) { + y[j + 0] = db2 * g1[j] * (signs[l] & kmask_iq2xs[j + 0] ? -1.f : 1.f); + y[j + 4] = db2 * g2[j] * (signs[l] & kmask_iq2xs[j + 4] ? -1.f : 1.f); + } + y += 8; + } + qh += 2; + qs += 8; + signs += 4; + } + return; + } + } + std::fprintf(stderr, "ref: dequant of %s not implemented\n", type_name(t)); + std::exit(2); +} + +void dequant(int t, const void* src, float* dst, size_t n) { + const uint8_t* s = (const uint8_t*)src; + if (t == F32) { std::memcpy(dst, s, n * 4); return; } + if (t == F16) { for (size_t i = 0; i < n; ++i) dst[i] = f16_to_f32(rd16(s + 2 * i)); return; } + if (t == BF16) { for (size_t i = 0; i < n; ++i) dst[i] = bf16_to_f32(rd16(s + 2 * i)); return; } + const int be = block_elems(t), bb = block_bytes(t); + for (size_t i = 0; i < n / be; ++i) deq_block(t, s + i * bb, dst + i * be); +} + +void quantize_q8_0(const float* x, size_t n, uint8_t* out) { + for (size_t b = 0; b < n / 32; ++b) { + float amax = 0.0f; + for (int j = 0; j < 32; ++j) amax = std::max(amax, std::fabs(x[b * 32 + j])); + const float d = amax / 127.0f, id = d != 0.0f ? 1.0f / d : 0.0f; + const uint16_t h = f32_to_f16(d); + uint8_t* o = out + b * 34; + o[0] = (uint8_t)h; + o[1] = (uint8_t)(h >> 8); + for (int j = 0; j < 32; ++j) o[2 + j] = (uint8_t)(int8_t)std::roundf(x[b * 32 + j] * id); + } +} + +static void put16(uint8_t* p, uint16_t v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); } + +void random_blocks(int t, uint8_t* dst, int rows, int cols, uint64_t seed, float scale) { + Rng r(seed); + const size_t n = (size_t)rows * cols; + if (t == F32 || t == F16 || t == BF16) { + for (size_t i = 0; i < n; ++i) { + const float v = r.sym() * scale * 2.0f; + if (t == F32) std::memcpy(dst + 4 * i, &v, 4); + else put16(dst + 2 * i, t == F16 ? f32_to_f16(v) : f32_to_bf16(v)); + } + return; + } + const int be = block_elems(t), bb = block_bytes(t); + const size_t nb = n / be; + for (size_t i = 0; i < nb; ++i) { + uint8_t* b = dst + i * bb; + for (int k = 0; k < bb; ++k) b[k] = (uint8_t)r.next(); + // the scale fields: magnitude so that |w| ~ scale. Typical code magnitudes differ per type. + const float u = 0.5f + r.uni(); + switch (t) { + case Q2_0: put16(b, f32_to_f16(scale * u)); break; + case Q8_0: put16(b, f32_to_f16(scale * u / 64)); break; + case Q4_0: case IQ4_NL: put16(b, f32_to_f16(scale * u / (t == Q4_0 ? 4 : 64))); break; + case Q5_0: put16(b, f32_to_f16(scale * u / 8)); break; + case Q5_1: put16(b, f32_to_f16(scale * u / 16)); put16(b + 2, f32_to_f16(-scale * u)); break; + case IQ4_XS: put16(b, f32_to_f16(scale * u / 64 / 16)); break; + case Q4_K: case Q5_K: put16(b, f32_to_f16(scale * u / 32 / 8)); put16(b + 2, f32_to_f16(scale * u / 32 / 2)); break; + case Q6_K: put16(b + 208, f32_to_f16(scale * u / 32 / 64)); break; + case Q3_K: put16(b + 108, f32_to_f16(scale * u / 32 / 2)); break; + case IQ2_XXS: case IQ2_XS: case IQ2_S: put16(b, f32_to_f16(scale * u / 4)); break; + case IQ3_XXS: put16(b, f32_to_f16(scale * u / 8)); break; + case IQ3_S: put16(b, f32_to_f16(scale * u / 64)); break; + default: break; + } + } +} + +} // namespace ref diff --git a/metal/src/ref_quant.h b/metal/src/ref_quant.h new file mode 100644 index 00000000..f20aeee9 --- /dev/null +++ b/metal/src/ref_quant.h @@ -0,0 +1,46 @@ +// metal/src/ref_quant.h - CPU reference dequantizers for the parity programs, transcribed from ggml's +// dequantize_row_* (ggml-quants.c at the pinned 3cf03257) and Strata's src/artifact/dequant.hpp (Q2_0), plus a +// deterministic generator of random-but-valid blocks for synthetic weights. +#pragma once + +#include +#include +#include + +namespace ref { + +// GGML type ids (stable, as in native_mmvq.hpp) +enum : int { + F32 = 0, F16 = 1, Q4_0 = 2, Q5_0 = 6, Q5_1 = 7, Q8_0 = 8, Q3_K = 11, Q4_K = 12, Q5_K = 13, Q6_K = 14, + IQ2_XXS = 16, IQ2_XS = 17, IQ3_XXS = 18, IQ3_S = 21, IQ2_S = 22, IQ4_NL = 20, IQ4_XS = 23, BF16 = 30, Q2_0 = 42, +}; + +const char* type_name(int t); +int block_elems(int t); +int block_bytes(int t); +inline size_t row_bytes(int t, int n) { return (size_t)n / block_elems(t) * block_bytes(t); } + +float f16_to_f32(uint16_t h); +uint16_t f32_to_f16(float f); +float bf16_to_f32(uint16_t h); +uint16_t f32_to_bf16(float f); // round to nearest even + +// Dequantizes `n` elements (a whole number of blocks) of type t. +void dequant(int t, const void* src, float* dst, size_t n); + +// ggml's quantize_row_q8_0_ref: per 32 values d = max|x| / 127 (stored fp16), q = roundf(x * (1 / d)). +void quantize_q8_0(const float* x, size_t n, uint8_t* out); + +// Fills `bytes` with random valid blocks of type t for a matrix of rows x cols: random codes, block scales drawn so +// that the weights have roughly unit-free magnitude `scale` (the d fields are finite FP16). +void random_blocks(int t, uint8_t* dst, int rows, int cols, uint64_t seed, float scale = 0.02f); + +struct Rng { + uint64_t s; + explicit Rng(uint64_t seed) : s(seed * 0x9E3779B97F4A7C15ull + 1) {} + uint64_t next() { s ^= s << 13; s ^= s >> 7; s ^= s << 17; return s; } + float uni() { return (next() >> 40) * (1.0f / 16777216.0f); } // [0,1) + float sym() { return uni() * 2.0f - 1.0f; } // [-1,1) +}; + +} // namespace ref diff --git a/metal/tests/alu_bench.cpp b/metal/tests/alu_bench.cpp new file mode 100644 index 00000000..23576071 --- /dev/null +++ b/metal/tests/alu_bench.cpp @@ -0,0 +1,39 @@ +// metal/tests/alu_bench.cpp - per-operation instruction rates of the GPU (Gops/s, one op = one lane-operation). +#include "mtl_rt.h" + +#include +#include +#include + +int main() { + mtl::Context cx; + const int lib = cx.compile({"alu_bench.metal"}, "#define NO_GGML_COMMON 1\n"); + const uint32_t groups = 2560, tg = 256, n = groups * tg; + mtl::Buffer out = cx.alloc(4 * n), tab = cx.alloc(4096); + for (int i = 0; i < 1024; ++i) tab.as()[i] = i * 7; + struct K { const char* name; double ops_per_iter; } ks[] = { + {"a_fma32", 8}, {"a_fma16", 8}, {"a_fmamix", 8}, {"a_iand", 16}, {"a_shift", 16}, {"a_cvt", 16}, + {"a_tgload", 4}, {"a_sel", 8}, {"a_dot32", 8}, {"a_dot16", 8}, {"a_dotmix", 8}, {"a_fma32x16", 8}, {"a_devload", 4}, {"a_cstload", 4}, {"a_tgload4", 4}, {"a_popc", 4}}; + std::printf("device %s\n", cx.device_name().c_str()); + for (const K& k : ks) { + mtl::Pipeline p = cx.pipeline(lib, k.name); + mtl::Dispatch d; + d.p = &p; + const float kf = 0.999f; + const uint32_t ku = 3; + d.args = {mtl::Arg::B(out), std::string(k.name) == "a_fma32" || std::string(k.name) == "a_fma16" || + std::string(k.name) == "a_fmamix" || std::string(k.name).rfind("a_dot", 0) == 0 || std::string(k.name) == "a_fma32x16" + ? mtl::Arg::V(kf) + : mtl::Arg::V(ku)}; + if (std::string(k.name) == "a_devload" || std::string(k.name) == "a_cstload") d.args.push_back(mtl::Arg::B(tab)); + d.grid[0] = groups; + d.tg[0] = tg; + cx.run({d}); + std::vector t; + for (int i = 0; i < 7; ++i) t.push_back(cx.run({d})); + std::sort(t.begin(), t.end()); + const double ops = (double)n * 1024 * k.ops_per_iter; + std::printf("%-10s %8.1f Gops/s (%.3f ms)\n", k.name, ops / t[3] / 1e9, t[3] * 1e3); + } + return 0; +} diff --git a/metal/tests/arena_budget_test.cpp b/metal/tests/arena_budget_test.cpp new file mode 100644 index 00000000..6a91a16b --- /dev/null +++ b/metal/tests/arena_budget_test.cpp @@ -0,0 +1,85 @@ +// metal/tests/arena_budget_test.cpp - the SSD-streaming arena's size rule (src/engine/arena_budget.h), on the sizes of +// the Macs it was measured on. No GPU: plain arithmetic. Exit 0 = every check passed. +#include "../src/engine/arena_budget.h" + +#include +#include +#include + +using namespace strata::metal_engine; + +static int failures = 0; +static void check(bool ok, const char* what, double got) { + std::printf("%s %-70s %.2f GB\n", ok ? "ok " : "FAIL", what, got / kGB); + failures += !ok; +} + +int main() { + // the M5 Max as it froze: 137.4 GB RAM, 115.4 GB working set, 7.0 GB allocated, 97.7 GB available + ArenaMem m5{137.4 * kGB, 115.4 * kGB, 7.0 * kGB, 97.7 * kGB}; + check(std::fabs(arena_keep(m5) - 0.15 * 137.4 * kGB) < 1e6, "M5 Max: macOS keeps 15% of the RAM (20.6 GB)", arena_keep(m5)); + const double b5 = arena_budget(m5); + check(b5 <= 97.7 * kGB - 20.6 * kGB - 0.5 * kGB + 1e6, "M5 Max: the arena leaves >= 20 GB + the n-gram reserve", b5); + check(b5 > 70 * kGB, "M5 Max: still a large arena (UD-Q5's 98 GB of experts mostly cached)", b5); + // the n-gram table mapped whole (--ple-io ram, 50.7 GB): it comes out of the arena + ArenaMem m5r = m5; + m5r.ple_mapped = 50.7 * kGB; + check(arena_budget(m5r) <= b5 - 48.0 * kGB, "M5 Max, table in RAM: the arena gives up the table's 50.7 GB", arena_budget(m5r)); + // the M4 Mac mini, 32 GB: the 7 GB floor (15% would be 5.16 GB) + ArenaMem m4{34.4 * kGB, 26.8 * kGB, 3.3 * kGB, 17.8 * kGB}; + check(std::fabs(arena_keep(m4) - 7.0 * kGB) < 1e6, "M4 32 GB: macOS keeps the 7 GB floor", arena_keep(m4)); + check(std::fabs(arena_budget(m4) - (17.8 - 7.0 - 0.5) * kGB) < 1e6, "M4 32 GB: available - 7 - 0.5", arena_budget(m4)); + ArenaMem m16{17.2 * kGB, 11 * kGB, 3 * kGB, 9 * kGB}; + check(std::fabs(arena_keep(m16) - 7.0 * kGB) < 1e6, "a 16 GB Mac: the 7 GB floor", arena_keep(m16)); + // the overrides + ArenaMem o = m4; + o.keep_gb = 12.0; + check(std::fabs(arena_budget(o) - (17.8 - 12.0 - 0.5) * kGB) < 1e6, "STRATA_METAL_KEEP_FREE_GB=12", arena_budget(o)); + o.arena_gb = 10.0; + check(std::fabs(arena_budget(o) - 10.0 * kGB) < 1e6, "STRATA_METAL_ARENA_GB=10 wins", arena_budget(o)); + check(std::fabs(arena_shrink(o, 10.0 * kGB, 1.0 * kGB) - 10.0 * kGB) < 1e6, "an explicit arena is not shrunk", 10.0 * kGB); + // never below 1 GB; the GPU working set bounds it too + ArenaMem tiny{16 * kGB, 10 * kGB, 9.5 * kGB, 8 * kGB}; + check(std::fabs(arena_budget(tiny) - 1.0 * kGB) < 1e6, "a 16 GB Mac with nothing left: 1 GB (low hit rate)", arena_budget(tiny)); + ArenaMem gpu = m5; + gpu.available = 200 * kGB; + check(std::fabs(arena_budget(gpu) - (0.67 * 137.4 - 7.0) * kGB) < 1e6, "plenty free: the wired share (67% of the RAM) bounds it", arena_budget(gpu)); + ArenaMem q6 = m5; // UD-Q6_K_XL after a reboot: 7.5 GB allocated, 125 GB "available" (cache): 84 GB ran, 90 GB swapped + q6.allocated = 7.5 * kGB; + q6.available = 125 * kGB; + check(arena_budget(q6) <= 84.7 * kGB && arena_budget(q6) > 84.0 * kGB, "M5 Max, UD-Q6 with 125 GB available: 84.6 GB, not 104", arena_budget(q6)); + // memory taken between planning and committing: it shrinks, never grows + const double s1 = arena_shrink(m5, b5, 60.0 * kGB); + check(s1 < b5 && std::fabs(s1 - (60.0 - 20.61 - 0.5) * kGB) < 0.1 * kGB, "less free when committing: it shrinks", s1); + check(std::fabs(arena_shrink(m5, b5, 130.0 * kGB) - b5) < 1e6, "more free when committing: it stays as planned", b5); + // the stepped fill (arena_grow / arena_fill_plan): 1.5 GB steps of 1.75 MB experts on the M4 (7 GB kept + 0.5) + ArenaMem s4 = m4; + s4.available = 17.8 * kGB; + check(arena_grow(s4, 17.8 * kGB, 1.5 * kGB), "a step with room: it fills", 17.8 * kGB); + check(!arena_grow(s4, 8.9 * kGB, 1.5 * kGB), "a step that would leave < 7.5 GB: it stops", 8.9 * kGB); + check(arena_grow(s4, 9.0 * kGB, 1.5 * kGB), "a step that leaves exactly 7.5 GB: it fills", 9.0 * kGB); + ArenaMem pin = s4; + pin.arena_gb = 12.0; + check(arena_grow(pin, 1.0 * kGB, 1.5 * kGB), "STRATA_METAL_ARENA_GB: always fills", 1.0 * kGB); + std::vector cost(6000, 1.75e6); // 10.5 GB of experts planned + // macOS gives exactly what is filled: the plan fills all of it while free stays >= 7.5 GB + const size_t all = arena_fill_plan(s4, cost.data(), cost.size(), 1.5 * kGB, [](double f) { return 18.5 * kGB - f; }); + check(all == cost.size(), "free memory follows the fill: every planned expert is filled", all * 1.75e6); + // another program takes 4 GB while the arena fills (after 3 GB): the fill stops at the floor, a step short + const size_t part = arena_fill_plan(s4, cost.data(), cost.size(), 1.5 * kGB, + [](double f) { return 18.5 * kGB - f - (f >= 3 * kGB ? 4 * kGB : 0); }); + const double left = 18.5 * kGB - part * 1.75e6 - 4 * kGB; + check(part < cost.size() && left >= 7.5 * kGB && left - 1.5 * kGB < 7.5 * kGB + 1.75e6, + "4 GB taken meanwhile: it stops with >= 7.5 GB free, less than a step above", part * 1.75e6); + // no room even for the first step: nothing is filled (the min slots still exist, unfilled) + check(arena_fill_plan(s4, cost.data(), cost.size(), 1.5 * kGB, [](double) { return 8.0 * kGB; }) == 0, + "no room for one step: nothing filled", 0); + // what counts as available: the M4 at the engine's start (16 KiB pages: 6.3 GB free + purgeable, 10.4 GB + // inactive, 14 GB file-backed) - the clean file cache counts; another program's inactive memory does not + check(std::fabs(arena_avail(6.3 * kGB, 0.07 * kGB, 10.4 * kGB, 0.1 * kGB, 14.1 * kGB) - 16.87 * kGB) < 1e6, + "inactive file cache counts", arena_avail(6.3 * kGB, 0.07 * kGB, 10.4 * kGB, 0.1 * kGB, 14.1 * kGB)); + check(std::fabs(arena_avail(6.3 * kGB, 0.07 * kGB, 10.4 * kGB, 0.1 * kGB, 2.0 * kGB) - 8.37 * kGB) < 1e6, + "inactive anonymous memory does not (only 2 GB file-backed)", arena_avail(6.3 * kGB, 0.07 * kGB, 10.4 * kGB, 0.1 * kGB, 2.0 * kGB)); + std::printf("%s\n", failures ? "FAILED" : "all passed"); + return failures ? 1 : 0; +} diff --git a/metal/tests/coop_layout.cpp b/metal/tests/coop_layout.cpp new file mode 100644 index 00000000..c296ad5f --- /dev/null +++ b/metal/tests/coop_layout.cpp @@ -0,0 +1,32 @@ +// metal/tests/coop_layout.cpp - which (index 0, index 1) elements of a single-simdgroup matmul2d's right input, left +// input and destination cooperative tensors each lane holds (mm_bench.metal coop_layout). +// coop_layout [TM_TN_TK] +#include "mtl_rt.h" + +#include +#include + +int main(int argc, char** argv) { + const std::string cfg = argc > 1 ? argv[1] : "16_32_16"; + mtl::Context cx; + const int lib = cx.compile({"mm_bench.metal"}, "#define NO_GGML_COMMON 1\n"); + mtl::Pipeline p = cx.pipeline(lib, "coop_layout_" + cfg); + mtl::Buffer out = cx.alloc(4 * 3 * 32 * 128 * 4); + mtl::Dispatch d; + d.p = &p; + d.args = {mtl::Arg::B(out)}; + d.tg[0] = 32; + cx.run({d}); + const int* o = out.as(); + const char* nm[3] = {"right", "left", "dest"}; + for (int w = 0; w < 3; ++w) { + std::printf("%s (tile %s):\n", nm[w], cfg.c_str()); + for (int l = 0; l < 32; ++l) { + const int* q = o + (w * 32 + l) * 128 * 4; + std::printf(" l%-2d cap %d:", l, q[2]); + for (int i = 0; i < q[2] && i < 128; ++i) std::printf(" (%d,%d)", q[i * 4], q[i * 4 + 1]); + std::printf("\n"); + } + } + return 0; +} diff --git a/metal/tests/coop_probe.h b/metal/tests/coop_probe.h new file mode 100644 index 00000000..dc781ff4 --- /dev/null +++ b/metal/tests/coop_probe.h @@ -0,0 +1,36 @@ +// metal/tests/coop_probe.h - which element layout this GPU gives matmul2d's single-simdgroup right-input cooperative +// tensor: true = runs of 4 consecutive k at one n per lane (the M5), false = anything else (the M4: runs of 2 n at one +// k). The kernels that fill right inputs per lane (mm_gu3, mm_down3, qsa_attn_mm, qsa_flash) take it as function +// constant 7. COOP_K4=0/1 in the environment overrides. +#pragma once +#include "mtl_rt.h" + +#include + +inline bool coop_k4(mtl::Context& cx) { + if (const char* e = std::getenv("COOP_K4")) return std::atoi(e) != 0; + const int lib = cx.compile({"mm_bench.metal"}, "#define NO_GGML_COMMON 1\n"); + for (const char* tile : {"coop_layout_16_64_32", "coop_layout_16_32_32"}) { + mtl::Pipeline p = cx.pipeline(lib, tile); + mtl::Buffer out = cx.alloc(4 * 3 * 32 * 128 * 4); + mtl::Dispatch d; + d.p = &p; + d.args = {mtl::Arg::B(out)}; + d.tg[0] = 32; + cx.run({d}); + // every lane: elements 4j .. 4j + 3 are (k, n), (k + 1, n), (k + 2, n), (k + 3, n), and element i + cap / 2 is + // (k + 16, n) with k % 32 < 16 (mm_gu3's paired-run decode relies on it) + const int* o = out.as(); + for (int l = 0; l < 32; ++l) { + const int* q = o + l * 128 * 4; + const int cap = q[2]; + for (int i = 0; i + 3 < cap; i += 4) + for (int j = 1; j < 4; ++j) + if (q[(i + j) * 4] != q[i * 4] + j || q[(i + j) * 4 + 1] != q[i * 4 + 1]) return false; + for (int i = 0; i < cap / 2; i += 4) + if (q[(i + cap / 2) * 4] != q[i * 4] + 16 || q[(i + cap / 2) * 4 + 1] != q[i * 4 + 1] || (q[i * 4] & 31) >= 16) + return false; + } + } + return true; +} diff --git a/metal/tests/dense_mm_parity.cpp b/metal/tests/dense_mm_parity.cpp new file mode 100644 index 00000000..33ce4500 --- /dev/null +++ b/metal/tests/dense_mm_parity.cpp @@ -0,0 +1,139 @@ +// metal/tests/dense_mm_parity.cpp - dense prompt projections (dense_mm.metal): dequantize to fp16 once, then the +// MPP GEMM. Parity vs a reference with the same fp16 operands (and the exact float one), every dense format and +// awkward row counts; then the speed on the packs' shapes for a 2048-token chunk. +// dense_mm_parity parity +// dense_mm_parity --bench speed +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include +#include + +namespace { +struct DqArgs { uint32_t n_in, n_out, row_bytes, perm; }; +struct GemmArgs { int M, N, K, pad; }; +double median(std::vector v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; } +float h16(float v) { return ref::f16_to_f32(ref::f32_to_f16(v)); } +int unit_of(int t) { + switch (t) { + case ref::Q2_0: case ref::IQ3_S: case ref::BF16: case ref::F32: return 16; + default: return 32; + } +} +} // namespace + +int main(int argc, char** argv) { + const bool bench = argc > 1 && std::string(argv[1]) == "--bench"; + mtl::Context cx; + const int lib = cx.compile({"quant.metal", "units.metal", "mma.metal", "dense_mm.metal"}); + std::printf("device %s\n", cx.device_name().c_str()); + mtl::Pipeline pact = cx.pipeline(lib, "act_f16"); + auto run_all = [&](int ty, const mtl::Buffer& W, size_t woff, int n_in, int n_out, int T, const mtl::Buffer& x, + const mtl::Buffer& xh, const mtl::Buffer& wh, const mtl::Buffer& y, const std::string& gk, + std::vector& ds, int which) { + static std::vector keep; + mtl::Pipeline* pdq = new mtl::Pipeline(cx.pipeline(lib, "dq_f16_" + std::to_string(ty))); + mtl::Pipeline* pg = new mtl::Pipeline(cx.pipeline(lib, gk)); + keep.push_back(pdq); + keep.push_back(pg); + int tm = 64, tn = 64; + std::sscanf(gk.c_str(), "gemm_f16_%d_%d", &tm, &tn); + if (which & 1) { + const uint32_t n = (uint32_t)T * n_in; + mtl::Dispatch d; d.p = &pact; d.args = {mtl::Arg::B(x), mtl::Arg::B(xh), mtl::Arg::V(n)}; + d.grid[0] = (n + 255) / 256; d.tg[0] = 256; ds.push_back(d); + } + if (which & 2) { + DqArgs a{(uint32_t)n_in, (uint32_t)n_out, (uint32_t)ref::row_bytes(ty, n_in)}; + mtl::Dispatch d; d.p = pdq; d.args = {mtl::Arg::B(W, woff), mtl::Arg::B(wh), mtl::Arg::V(a)}; + d.grid[0] = (n_in / unit_of(ty) + 63) / 64; d.grid[1] = n_out; d.tg[0] = 64; ds.push_back(d); + } + if (which & 4) { + GemmArgs g{T, n_out, n_in, 0}; + mtl::Dispatch d; d.p = pg; d.args = {mtl::Arg::B(xh), mtl::Arg::B(wh), mtl::Arg::B(y), mtl::Arg::V(g)}; + d.grid[0] = (n_out + tn - 1) / tn; d.grid[1] = (T + tm - 1) / tm; d.tg[0] = 128; ds.push_back(d); + } + }; + const std::vector types = {ref::F32, ref::BF16, ref::Q8_0, ref::Q4_0, ref::Q5_0, ref::IQ4_NL, ref::IQ4_XS, ref::Q2_0, + ref::IQ3_S, ref::Q3_K, ref::Q4_K, ref::Q5_K, ref::Q6_K}; + if (!bench) { + int fails = 0; + for (int ty : types) + for (int n_in : {2560, 640, 6144}) { + if (n_in % 256 && ref::block_elems(ty) == 256) continue; + for (int n_out : {100, 48}) { + const int T = 72; + const size_t rb = ref::row_bytes(ty, n_in); + mtl::Buffer W = cx.alloc(rb * n_out), x = cx.alloc(4 * (size_t)T * n_in), xh = cx.alloc(2 * (size_t)T * n_in), + wh = cx.alloc(2 * (size_t)n_out * n_in), y = cx.alloc(4 * (size_t)T * n_out); + ref::random_blocks(ty, W.as(), n_out, n_in, 5 + ty + n_in, 0.02f); + ref::Rng r(3); + for (size_t i = 0; i < (size_t)T * n_in; ++i) x.as()[i] = r.sym(); + std::vector ds; + run_all(ty, W, 0, n_in, n_out, T, x, xh, wh, y, "gemm_f16_64_64_4", ds, 7); + cx.run(ds); + std::vector wf((size_t)n_in * n_out); + ref::dequant(ty, W.ptr, wf.data(), wf.size()); + double se16 = 0, se = 0, sr = 0; + for (int t = 0; t < T; ++t) + for (int o = 0; o < n_out; ++o) { + double a16 = 0, ae = 0; + for (int k = 0; k < n_in; ++k) { + const float xv = x.as()[(size_t)t * n_in + k], wv = wf[(size_t)o * n_in + k]; + a16 += (double)h16(xv) * h16(wv); + ae += (double)xv * wv; + } + const double g = y.as()[(size_t)t * n_out + o]; + se16 += (g - a16) * (g - a16); + se += (g - ae) * (g - ae); + sr += ae * ae; + } + const double r16 = std::sqrt(se16 / sr), re = std::sqrt(se / sr); + const bool ok = r16 < 1e-5; + fails += !ok; + std::printf("dense mm %-7s %5d -> %4d, T %d: vs fp16 operands %.2e, vs exact %.2e %s\n", + ref::type_name(ty), n_in, n_out, T, r16, re, ok ? "PASS" : "FAIL"); + } + } + std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS"); + return fails ? 1 : 0; + } + struct Shape { const char* name; int type, n_in, n_out; }; + const std::vector shapes = {{"gdn qkv", ref::IQ4_XS, 2560, 10240}, {"gdn qkv", ref::Q3_K, 2560, 10240}, + {"gdn gate", ref::Q4_K, 2560, 6144}, {"gdn out", ref::Q6_K, 6144, 2560}, + {"qsa q", ref::Q2_0, 2560, 12288}, {"hc down", ref::BF16, 10240, 324}, + {"hc up", ref::BF16, 320, 10240}, {"router", ref::BF16, 2560, 512}, + {"alpha", ref::BF16, 2560, 48}}; + const int T = 2048; + for (const Shape& s : shapes) { + if (s.n_in % 128) { std::printf("%-9s %-6s: n_in %d not a multiple of 128 (needs the 32-chunk path)\n", s.name, ref::type_name(s.type), s.n_in); continue; } + const size_t rb = ref::row_bytes(s.type, s.n_in); + mtl::Buffer W = cx.alloc(rb * s.n_out), x = cx.alloc(4 * (size_t)T * s.n_in), xh = cx.alloc(2 * (size_t)T * s.n_in), + wh = cx.alloc(2 * (size_t)s.n_out * s.n_in), y = cx.alloc(4 * (size_t)T * s.n_out); + ref::random_blocks(s.type, W.as(), s.n_out, s.n_in, 3, 0.02f); + auto timeit = [&](int which, const std::string& gk) { + std::vector ds; + for (int i = 0; i < 4; ++i) run_all(s.type, W, 0, s.n_in, s.n_out, T, x, xh, wh, y, gk, ds, which); + cx.warm(ds, 0.2); + std::vector t; + for (int i = 0; i < 5; ++i) t.push_back(cx.run(ds) / 4); + return median(t); + }; + const double tdq = timeit(2, "gemm_f16_64_64_4"), tact = timeit(1, "gemm_f16_64_64_4"); + double best = 1e9; + std::string bk; + for (const char* gk : {"gemm_f16_64_64_4", "gemm_f16_128_64_4", "gemm_f16_64_128_4", "gemm_f16_64_32_4"}) { + const double tg = timeit(4, gk); + if (tg < best) { best = tg; bk = gk; } + } + const double fl = 2.0 * T * s.n_in * s.n_out; + std::printf("%-9s %-6s %5d -> %5d, T %d: dequant %7.1f us, act %6.1f us, GEMM %7.1f us (%5.1f TFLOP/s, %s) -> %.2f us a token\n", + s.name, ref::type_name(s.type), s.n_in, s.n_out, T, tdq * 1e6, tact * 1e6, best * 1e6, fl / best / 1e12, + bk.c_str(), (tdq + best) / T * 1e6); + } + return 0; +} diff --git a/metal/tests/expert_parity.cpp b/metal/tests/expert_parity.cpp new file mode 100644 index 00000000..3bd15ba3 --- /dev/null +++ b/metal/tests/expert_parity.cpp @@ -0,0 +1,445 @@ +// metal/tests/expert_parity.cpp - the grouped routed-expert kernels (moe.metal) against a double-precision CPU +// reference, and their speed. +// +// expert_parity [--gu Q2_0] [--dn Q2_0] [--ntok 1..8] [--gucfg L,R,S] [--dncfg L,R,S] parity (synthetic) +// expert_parity --bench [--gu ..] [--dn ..] [--ntok N] [--layers 8] [--reps 96] [--sweep] speed +// +// Parity: random valid blocks for 64 experts, random activations x ~ U(-1,1), random distinct top-10 per token, +// weights summing to 1. Checked: the plan (groups by expert id, entries in (token, k) order), h = silu(gate) * up +// per entry and y = sum_k w * down . h, each against double; reported as max |err| / max |ref| and relative L2. +// Bench: `layers` distinct copies of a 512-expert arena (no reuse across reps beyond chance; the SLC is ~32 MB), +// a different random routing per rep; GB/s = bytes of the distinct experts the kernel must read / GPU time. +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr int N_EMBD = 2560, N_FF = 640, TOPK = 10; +// plan layout (moe.metal) +constexpr int P_NG = 0, P_IGU = 4, P_IDN = 8, P_MAXE = 128, P_GEXP = 16, P_GSTART = P_GEXP + P_MAXE, + P_ETOK = P_GSTART + P_MAXE + 4, P_EW = P_ETOK + P_MAXE, P_TOKENT = P_EW + P_MAXE, + P_INTS = P_TOKENT + P_MAXE; + +struct MoeArgs { + uint64_t gate_off, up_off, down_off, gu_stride, d_stride; + uint32_t gu_row, d_row, n_embd, n_ff, n_tok, topk, n_expert, gx_gu, gx_dn, pad; +}; + +int type_of(const std::string& s) { + for (int t : {ref::Q2_0, ref::IQ3_XXS, ref::IQ2_XXS, ref::IQ2_XS, ref::IQ2_S, ref::IQ3_S, ref::IQ4_NL, ref::IQ4_XS, ref::Q4_K, ref::Q5_K, ref::Q6_K, ref::Q8_0, ref::Q5_1}) + if (s == ref::type_name(t)) return t; + std::fprintf(stderr, "unknown type %s\n", s.c_str()); + std::exit(2); +} + +struct Cfg { int L, R, S; }; +Cfg parse_cfg(const char* s) { + Cfg c{}; + if (std::sscanf(s, "%d,%d,%d", &c.L, &c.R, &c.S) != 3) { std::fprintf(stderr, "bad cfg %s\n", s); std::exit(2); } + return c; +} +std::string kname(const char* k, int t, Cfg c) { + return std::string(k) + "_" + std::to_string(t) + "_" + std::to_string(c.L) + "_" + std::to_string(c.R) + "_" + + std::to_string(c.S); +} +int rows_per_tg(Cfg c) { return c.S * (32 / c.L) * c.R; } + +struct Layout { + int gu, dn; + size_t gu_row, d_row, up_off, down_off, blob; +}; +Layout layout(int gu, int dn) { + Layout L{gu, dn}; + L.gu_row = ref::row_bytes(gu, N_EMBD); + L.d_row = ref::row_bytes(dn, N_FF); + L.up_off = (size_t)N_FF * L.gu_row; + L.down_off = 2 * L.up_off; + L.blob = L.down_off + (size_t)N_EMBD * L.d_row; + return L; +} + +void random_routing(ref::Rng& r, int ntok, int n_expert, std::vector& ids, std::vector& w, + double share = 0.0, const std::vector* prev = nullptr) { + ids.assign(ntok * TOPK, 0); + w.assign(ntok * TOPK, 0.0f); + for (int t = 0; t < ntok; ++t) { + std::set used; + float sum = 0; + for (int k = 0; k < TOPK; ++k) { + int e; + do { + // with probability `share`, reuse an expert of the previous token (verify windows share experts) + if (t > 0 && share > 0 && r.uni() < share) e = ids[(t - 1) * TOPK + (r.next() % TOPK)]; + else e = (int)(r.next() % n_expert); + } while (used.count(e)); + used.insert(e); + ids[t * TOPK + k] = e; + w[t * TOPK + k] = 0.2f + r.uni(); + sum += w[t * TOPK + k]; + } + for (int k = 0; k < TOPK; ++k) w[t * TOPK + k] /= sum; + } + (void)prev; +} + +struct Kernels { + mtl::Pipeline plan, gu, dn, comb, prep; + Cfg cgu, cdn; +}; +int xkind(int t) { + switch (t) { + case ref::Q2_0: return 1; + case ref::Q4_K: case ref::Q5_K: return 2; + case ref::Q6_K: case ref::Q3_K: return 3; + default: return 0; + } +} +constexpr int CAPE = 8 * TOPK; // entries capacity of h +// prepared buffers: x [8][N_EMBD] -> XPX, h [CAPE][N_FF] -> XPH (4 planes + S16) +constexpr size_t PLANE_X = 8 * N_EMBD, PLANE_H = (size_t)CAPE * N_FF; + +mtl::Dispatch prep_dispatch(const mtl::Pipeline& p, const mtl::Buffer& x, const mtl::Buffer& xp, uint32_t n, uint32_t nt) { + mtl::Dispatch d; + d.p = &p; + d.args = {mtl::Arg::B(x), mtl::Arg::B(xp), mtl::Arg::V(n), mtl::Arg::V(nt)}; + d.tg[0] = 256; + d.grid[0] = (n / 16 * nt + 255) / 256; + return d; +} + +int g_gu_type = 0, g_dn_type = 0; +bool g_dn_prep = false; // Q2_0 down: prepared h (an xprep dispatch) instead of the raw-x decoder +const mtl::Buffer* g_xpx = nullptr; +const mtl::Buffer* g_xph = nullptr; + +void encode_layer(std::vector& ds, const Kernels& K, const mtl::Buffer& W, size_t w_off, + const mtl::Buffer& x, const mtl::Buffer& h, const mtl::Buffer& ye, const mtl::Buffer& y, + const mtl::Buffer& ids, const mtl::Buffer& wts, const mtl::Buffer& plan, size_t plan_off, + const MoeArgs& a, bool with_plan, bool with_gu, bool with_dn, bool with_comb) { + const mtl::Buffer& XPX = *g_xpx; + const mtl::Buffer& XPH = *g_xph; + if (with_plan) { + mtl::Dispatch d; + d.p = &K.plan; + d.args = {mtl::Arg::B(ids), mtl::Arg::B(wts), mtl::Arg::B(plan, plan_off), mtl::Arg::V(a)}; + d.tg[0] = 512; + ds.push_back(d); + } + if (with_gu) { + mtl::Dispatch d; + d.p = &K.gu; + d.args = {mtl::Arg::B(W, w_off), mtl::Arg::B(XPX, 4 * PLANE_X * xkind(g_gu_type)), mtl::Arg::B(h), + mtl::Arg::B(plan, plan_off), mtl::Arg::V(a), mtl::Arg::B(XPX, 4 * PLANE_X * 4)}; + d.tg[0] = K.cgu.S * 32; + d.indirect = &plan; + d.ind_off = plan_off + P_IGU * 4; + ds.push_back(d); + } + if (with_dn) { + const int dk = g_dn_prep ? xkind(g_dn_type) : 0; + if (dk) ds.push_back(prep_dispatch(K.prep, h, XPH, N_FF, CAPE)); + mtl::Dispatch d; + d.p = &K.dn; + d.args = {mtl::Arg::B(W, w_off), + dk ? mtl::Arg::B(XPH, 4 * PLANE_H * dk) : mtl::Arg::B(h), mtl::Arg::B(ye), + mtl::Arg::B(plan, plan_off), mtl::Arg::V(a), mtl::Arg::B(XPH, 4 * PLANE_H * 4)}; + d.tg[0] = K.cdn.S * 32; + d.indirect = &plan; + d.ind_off = plan_off + P_IDN * 4; + ds.push_back(d); + } + if (with_comb) { + mtl::Dispatch d; + d.p = &K.comb; + d.args = {mtl::Arg::B(ye), mtl::Arg::B(y), mtl::Arg::B(plan, plan_off), mtl::Arg::V(a)}; + d.tg[0] = 256; + d.grid[0] = (a.n_tok * N_EMBD + 255) / 256; + ds.push_back(d); + } +} + +struct Err { + double max_abs = 0, max_ref = 0, se = 0, sr = 0; + void add(double got, double ref) { + max_abs = std::max(max_abs, std::fabs(got - ref)); + max_ref = std::max(max_ref, std::fabs(ref)); + se += (got - ref) * (got - ref); + sr += ref * ref; + } + double rel_max() const { return max_ref > 0 ? max_abs / max_ref : max_abs; } + double rel_l2() const { return sr > 0 ? std::sqrt(se / sr) : std::sqrt(se); } +}; + +double median(std::vector v) { + std::sort(v.begin(), v.end()); + return v[v.size() / 2]; +} + +} // namespace + +int main(int argc, char** argv) { + int gu = ref::Q2_0, dn = ref::Q2_0, ntok = 1, layers = 8, reps = 96; + Cfg cgu{32, 2, 4}, cdn{8, 2, 4}; + bool bench = false, sweep = false; + double share = 0.0; + bool cfg_gu_set = false, cfg_dn_set = false; + for (int i = 1; i < argc; ++i) { + std::string a = argv[i]; + auto nx = [&] { return i + 1 < argc ? argv[++i] : (std::fprintf(stderr, "%s needs a value\n", a.c_str()), std::exit(2), (char*)nullptr); }; + if (a == "--gu") gu = type_of(nx()); + else if (a == "--dn") dn = type_of(nx()); + else if (a == "--ntok") ntok = std::atoi(nx()); + else if (a == "--gucfg") { cgu = parse_cfg(nx()); cfg_gu_set = true; } + else if (a == "--dncfg") { cdn = parse_cfg(nx()); cfg_dn_set = true; } + else if (a == "--bench") bench = true; + else if (a == "--sweep") sweep = true; + else if (a == "--layers") layers = std::atoi(nx()); + else if (a == "--reps") reps = std::atoi(nx()); + else if (a == "--share") share = std::atof(nx()); + else if (a == "--dn-prep") g_dn_prep = true; + else { std::fprintf(stderr, "unknown argument %s\n", a.c_str()); return 2; } + } + (void)cfg_gu_set; + (void)cfg_dn_set; + if (dn == ref::IQ4_NL && cdn.L == 8 && !cfg_dn_set) cdn = {4, 2, 4}; + mtl::Context cx; + const int lib = cx.compile({"quant.metal", "units.metal", "moe.metal"}); + const Layout L = layout(gu, dn); + std::printf("device %s; gate/up %s, down %s, blob %zu bytes; %d token(s)\n", cx.device_name().c_str(), + ref::type_name(gu), ref::type_name(dn), L.blob, ntok); + + auto make = [&](Cfg a, Cfg b) { + Kernels K; + K.plan = cx.pipeline(lib, "moe_plan"); + K.prep = cx.pipeline(lib, "xprep"); + K.comb = cx.pipeline(lib, "moe_combine"); + K.gu = cx.pipeline(lib, kname("moe_gu", gu, a), mtl::Constants().i(22, std::getenv("MOE_PROBE") ? std::atoi(std::getenv("MOE_PROBE")) : 0).b(23, std::getenv("QUANT_CTAB") != nullptr)); + K.dn = cx.pipeline(lib, kname("moe_down", dn == ref::Q2_0 && !g_dn_prep ? 142 : dn, b)); + K.cgu = a; + K.cdn = b; + return K; + }; + auto args_for = [&](const Kernels& K, int nt, int n_expert) { + MoeArgs a{}; + a.gate_off = 0; + a.up_off = L.up_off; + a.down_off = L.down_off; + a.gu_stride = L.blob; + a.d_stride = L.blob; + a.gu_row = (uint32_t)L.gu_row; + a.d_row = (uint32_t)L.d_row; + a.n_embd = N_EMBD; + a.n_ff = N_FF; + a.n_tok = nt; + a.topk = TOPK; + a.n_expert = n_expert; + a.gx_gu = N_FF / rows_per_tg(K.cgu); + a.gx_dn = N_EMBD / rows_per_tg(K.cdn); + return a; + }; + + mtl::Buffer x = cx.alloc(4 * 8 * N_EMBD), h = cx.alloc(4 * 8 * TOPK * N_FF), ye = cx.alloc(4 * 8 * TOPK * N_EMBD), + y = cx.alloc(4 * 8 * N_EMBD); + mtl::Buffer XPX = cx.alloc(4 * (4 * PLANE_X + PLANE_X / 16)), XPH = cx.alloc(4 * (4 * PLANE_H + PLANE_H / 16)); + g_xpx = &XPX; + g_xph = &XPH; + g_gu_type = gu; + g_dn_type = dn; + ref::Rng rng(12345); + for (int i = 0; i < 8 * N_EMBD; ++i) x.as()[i] = rng.sym(); + { + mtl::Pipeline pp = cx.pipeline(lib, "xprep"); + cx.run({prep_dispatch(pp, x, XPX, N_EMBD, 8)}); + } + + if (!bench) { + // ---------------- parity ---------------- + const int NE = 64; + mtl::Buffer W = cx.alloc(L.blob * NE); + for (int e = 0; e < NE; ++e) { + uint8_t* b = W.as() + e * L.blob; + ref::random_blocks(gu, b, 2 * N_FF, N_EMBD, 1000 + e); + ref::random_blocks(dn, b + L.down_off, N_EMBD, N_FF, 5000 + e); + } + std::vector ids; + std::vector w; + random_routing(rng, ntok, NE, ids, w, 0.3); + mtl::Buffer bid = cx.alloc(4 * ids.size()), bw = cx.alloc(4 * w.size()), plan = cx.alloc(4 * P_INTS); + std::memcpy(bid.ptr, ids.data(), 4 * ids.size()); + std::memcpy(bw.ptr, w.data(), 4 * w.size()); + Kernels K = make(cgu, cdn); + MoeArgs a = args_for(K, ntok, 512); + std::vector ds; + encode_layer(ds, K, W, 0, x, h, ye, y, bid, bw, plan, 0, a, true, true, true, true); + cx.run(ds); + // the plan + const int* P = plan.as(); + std::set distinct(ids.begin(), ids.end()); + bool plan_ok = P[P_NG] == (int)distinct.size() && P[P_IGU + 1] == P[P_NG] && P[P_IDN + 1] == P[P_NG]; + { + int gi = 0; + for (int e : distinct) { + if (P[P_GEXP + gi] != e) plan_ok = false; + int j = P[P_GSTART + gi]; + for (int i = 0; i < ntok * TOPK; ++i) + if (ids[i] == e) { + if (P[P_ETOK + j] != i / TOPK || P[P_TOKENT + i] != j) plan_ok = false; + float fw; + std::memcpy(&fw, &P[P_EW + j], 4); + if (fw != w[i]) plan_ok = false; + ++j; + } + if (j != P[P_GSTART + gi + 1]) plan_ok = false; + ++gi; + } + } + // the reference + Err eh, ey; + std::vector wg(N_FF * N_EMBD), wu(N_FF * N_EMBD), wd(N_EMBD * N_FF); + std::vector yref(ntok * N_EMBD, 0.0); + for (int i = 0; i < ntok * TOPK; ++i) { + const int e = ids[i], t = i / TOPK; + const uint8_t* b = W.as() + e * L.blob; + ref::dequant(gu, b, wg.data(), wg.size()); + ref::dequant(gu, b + L.up_off, wu.data(), wu.size()); + ref::dequant(dn, b + L.down_off, wd.data(), wd.size()); + const float* xt = x.as() + t * N_EMBD; + std::vector hr(N_FF); + const int ent = P[P_TOKENT + i]; + for (int r = 0; r < N_FF; ++r) { + double g = 0, u = 0; + for (int k = 0; k < N_EMBD; ++k) { + g += (double)wg[r * N_EMBD + k] * xt[k]; + u += (double)wu[r * N_EMBD + k] * xt[k]; + } + hr[r] = g / (1.0 + std::exp(-g)) * u; + eh.add(h.as()[ent * N_FF + r], hr[r]); + } + for (int r = 0; r < N_EMBD; ++r) { + double s = 0; + // the reference down uses the GPU's h (float) so that the y check isolates the down kernel ... + for (int k = 0; k < N_FF; ++k) s += (double)wd[r * N_FF + k] * h.as()[ent * N_FF + k]; + yref[t * N_EMBD + r] += w[i] * s; + } + } + for (int i = 0; i < ntok * N_EMBD; ++i) ey.add(y.as()[i], yref[i]); + const bool ok = plan_ok && eh.rel_l2() < 1e-5 && ey.rel_l2() < 1e-5 && eh.rel_max() < 1e-4 && ey.rel_max() < 1e-4; + std::printf("parity %s/%s ntok %d gu %d,%d,%d dn %d,%d,%d: plan %s (%d groups), h rel L2 %.2e max %.2e, " + "y rel L2 %.2e max %.2e %s\n", + ref::type_name(gu), ref::type_name(dn), ntok, cgu.L, cgu.R, cgu.S, cdn.L, cdn.R, cdn.S, + plan_ok ? "ok" : "WRONG", P[P_NG], eh.rel_l2(), eh.rel_max(), ey.rel_l2(), ey.rel_max(), + ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; + } + + // ---------------- bench ---------------- + const int NE = 512; + const size_t layer_bytes = L.blob * NE; + std::printf("arena: %d layers x %d experts = %.2f GB (max buffer %.1f GB)\n", layers, NE, layers * layer_bytes / 1e9, + cx.max_buffer_length() / 1e9); + mtl::Buffer W = cx.alloc(layer_bytes * layers); + { + // 64 distinct random experts, copied over the arena + std::vector tmp(L.blob * 64); + for (int e = 0; e < 64; ++e) { + ref::random_blocks(gu, tmp.data() + e * L.blob, 2 * N_FF, N_EMBD, 1000 + e); + ref::random_blocks(dn, tmp.data() + e * L.blob + L.down_off, N_EMBD, N_FF, 5000 + e); + } + for (size_t e = 0; e < (size_t)NE * layers; ++e) + std::memcpy(W.as() + e * L.blob, tmp.data() + (e % 64) * L.blob, L.blob); + } + std::vector> rids(reps); + std::vector> rw(reps); + mtl::Buffer bid = cx.alloc(4 * 8 * TOPK * reps), bw = cx.alloc(4 * 8 * TOPK * reps), plan = cx.alloc(4 * P_INTS * reps); + auto set_routing = [&](int nt) { + double groups = 0; + for (int r = 0; r < reps; ++r) { + random_routing(rng, nt, NE, rids[r], rw[r], share); + std::memcpy(bid.as() + r * 8 * TOPK, rids[r].data(), 4 * rids[r].size()); + std::memcpy(bw.as() + r * 8 * TOPK, rw[r].data(), 4 * rw[r].size()); + groups += std::set(rids[r].begin(), rids[r].end()).size(); + } + return groups / reps; + }; + auto run_cfg = [&](const Kernels& K, int nt, double groups, bool print) { + const MoeArgs a = args_for(K, nt, NE); + std::vector dp, dg, dd, dall; + for (int r = 0; r < reps; ++r) { + const size_t woff = (size_t)(r % layers) * layer_bytes; + std::vector one; + encode_layer(one, K, W, woff, x, h, ye, y, bid, bw, plan, (size_t)r * P_INTS * 4, a, true, false, false, false); + one[0].args[0] = mtl::Arg::B(bid, (size_t)r * 8 * TOPK * 4); + one[0].args[1] = mtl::Arg::B(bw, (size_t)r * 8 * TOPK * 4); + dp.push_back(one[0]); + std::vector g, d; + encode_layer(g, K, W, woff, x, h, ye, y, bid, bw, plan, (size_t)r * P_INTS * 4, a, false, true, false, false); + encode_layer(d, K, W, woff, x, h, ye, y, bid, bw, plan, (size_t)r * P_INTS * 4, a, false, false, true, false); + dg.push_back(g[0]); + for (auto& z : d) dd.push_back(z); + dall.push_back(one[0]); + dall.push_back(g[0]); + for (auto& z : d) dall.push_back(z); + } + cx.run(dp); // plans in place + cx.warm(dall, 0.1); + std::vector tp, tg, td, ta; + for (int it = 0; it < 7; ++it) { + tp.push_back(cx.run(dp) / reps); + tg.push_back(cx.run(dg) / reps); + td.push_back(cx.run(dd) / reps); + ta.push_back(cx.run(dall) / reps); + } + const double mp = median(tp), mg = median(tg), md = median(td), ma = median(ta); + const double bg = groups * 2.0 * N_FF * L.gu_row, bd = groups * N_EMBD * L.d_row; + if (print) + std::printf("ntok %d groups %5.1f | gu %2d,%d,%d %7.1f us %6.1f GB/s | dn %2d,%d,%d %7.1f us %6.1f GB/s | " + "plan %5.1f us | layer %7.1f us = %6.1f GB/s (%4.1f%% of 585)\n", + nt, groups, K.cgu.L, K.cgu.R, K.cgu.S, mg * 1e6, bg / mg / 1e9, K.cdn.L, K.cdn.R, K.cdn.S, + md * 1e6, bd / md / 1e9, mp * 1e6, ma * 1e6, (bg + bd) / ma / 1e9, + (bg + bd) / ma / 1e9 / 585 * 100); + return std::make_pair(mg, md); + }; + const std::vector gus = {{32, 1, 4}, {32, 2, 4}, {32, 4, 4}, {32, 2, 2}, {32, 2, 8}, {32, 1, 8}, + {16, 1, 4}, {16, 2, 4}, {8, 1, 4}, {8, 2, 4}, {8, 1, 2}}; + const std::vector dns = {{8, 1, 4}, {8, 2, 4}, {8, 4, 4}, {8, 1, 8}, {8, 2, 8}, {4, 1, 4}, + {4, 2, 4}, {4, 4, 4}, {16, 1, 4}, {16, 2, 4}, {32, 1, 4}, {2, 2, 4}}; + std::vector ntoks = {ntok}; + if (sweep) ntoks = {1, 2, 3, 4, 8}; + for (int nt : ntoks) { + const double groups = set_routing(nt); + if (sweep) { + // gate/up sweep with the default down, then down sweep with the best gate/up + Cfg bgu = cgu, bdn = cdn; + double best = 1e9; + for (Cfg c : gus) { + if (N_FF % rows_per_tg(c)) continue; + auto t = run_cfg(make(c, cdn), nt, groups, false); + std::printf(" gu %2d,%d,%d: %7.1f us %6.1f GB/s\n", c.L, c.R, c.S, t.first * 1e6, + groups * 2.0 * N_FF * L.gu_row / t.first / 1e9); + if (t.first < best) { best = t.first; bgu = c; } + } + best = 1e9; + for (Cfg c : dns) { + if (N_EMBD % rows_per_tg(c)) continue; + auto t = run_cfg(make(bgu, c), nt, groups, false); + std::printf(" dn %2d,%d,%d: %7.1f us %6.1f GB/s\n", c.L, c.R, c.S, t.second * 1e6, + groups * N_EMBD * L.d_row / t.second / 1e9); + if (t.second < best) { best = t.second; bdn = c; } + } + run_cfg(make(bgu, bdn), nt, groups, true); + } else { + run_cfg(make(cgu, cdn), nt, groups, true); + } + } + return 0; +} diff --git a/metal/tests/fuse_parity.cpp b/metal/tests/fuse_parity.cpp new file mode 100644 index 00000000..e67d9e58 --- /dev/null +++ b/metal/tests/fuse_parity.cpp @@ -0,0 +1,160 @@ +// metal/tests/fuse_parity.cpp - the decode latency fusions against the kernels they replace, BITWISE, for 1..4 +// tokens: +// gemv_cat (gemv.metal) ssm_alpha + ssm_beta (BF16 2560 -> 48 + 48) in one dispatch == two gemv dispatches +// router_route the router GEMV + moe_route in one dispatch == gemv + moe_route (logits, ids, w, plan; +// twice in a row: the counter resets) +// gr_norm_comb (gr2.metal) the MoE combine folded into the next gr_norm == moe_combine_sh + gr_norm (R', xn) +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include + +namespace { +struct GemvArgs { uint32_t n_in, n_out, n_tok, row_bytes, x_stride, y_stride; }; +struct MoeArgs { + uint64_t gate_off, up_off, down_off, gu_stride, d_stride; + uint32_t gu_row, d_row, n_embd, n_ff, n_tok, topk, n_expert, gx_gu, gx_dn, pad; +}; +constexpr int P_INTS = 16 + 128 + 128 + 4 + 128 * 3, P_TOKENT = 16 + 128 + 128 + 4 + 128 * 2; +struct GrArgs { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; }; +struct GlueArgs { uint32_t n, n_tok, n_embd, topk; }; +} // namespace + +int main() { + mtl::Context cx; + const int lib = cx.compile({"quant.metal", "units.metal", "moe.metal", "gemv.metal", "router.metal", "gr.metal", + "gr2.metal", "glue.metal"}); + std::printf("device %s\n", cx.device_name().c_str()); + int fails = 0; + const int N = 2560, NO = 48, MAXT = 8; + const size_t rb = ref::row_bytes(ref::BF16, N); + mtl::Buffer Wa = cx.alloc(rb * NO), Wb = cx.alloc(rb * NO), xp = cx.alloc(4 * ((size_t)4 * MAXT * N + MAXT * N / 16)), + y1 = cx.alloc(4 * MAXT * NO), y2 = cx.alloc(4 * MAXT * NO), z1 = cx.alloc(4 * MAXT * NO), z2 = cx.alloc(4 * MAXT * NO); + ref::random_blocks(ref::BF16, Wa.as(), NO, N, 1, 0.05f); + ref::random_blocks(ref::BF16, Wb.as(), NO, N, 2, 0.05f); + ref::Rng r(3); + for (size_t i = 0; i < xp.bytes / 4; ++i) xp.as()[i] = r.sym(); + for (int nt = 1; nt <= 4; ++nt) { + mtl::Pipeline pg = cx.pipeline(lib, "gemv_30_32_1_4_1", mtl::Constants().i(0, nt)), + pc = cx.pipeline(lib, "gemvc_30_32_1_4", mtl::Constants().i(0, nt)); + const size_t s16 = (size_t)4 * 4 * MAXT * N; + GemvArgs a{(uint32_t)N, (uint32_t)NO, (uint32_t)nt, (uint32_t)rb, (uint32_t)N, (uint32_t)NO}; + auto g = [&](const mtl::Buffer& W, const mtl::Buffer& y) { + mtl::Dispatch d; + d.p = &pg; + d.args = {mtl::Arg::B(W), mtl::Arg::B(xp), mtl::Arg::B(xp, s16), mtl::Arg::B(y), mtl::Arg::V(a)}; + d.grid[0] = NO / 4; + d.tg[0] = 128; + return d; + }; + cx.run({g(Wa, y1), g(Wb, y2)}); + GemvArgs ac = a; + ac.n_out = 2 * NO; + const uint32_t sp = NO; + mtl::Dispatch d; + d.p = &pc; + d.args = {mtl::Arg::B(Wa), mtl::Arg::B(xp), mtl::Arg::B(xp, s16), mtl::Arg::B(z1), mtl::Arg::V(ac), mtl::Arg::B(Wb), + mtl::Arg::B(z2), mtl::Arg::V(sp)}; + d.grid[0] = 2 * NO / 4; + d.tg[0] = 128; + cx.run({d}); + const bool ok = std::memcmp(y1.ptr, z1.ptr, 4 * nt * NO) == 0 && std::memcmp(y2.ptr, z2.ptr, 4 * nt * NO) == 0; + fails += !ok; + std::printf("gemv_cat (alpha + beta) ntok %d: bitwise %s\n", nt, ok ? "PASS" : "FAIL"); + } + // ---- router_route + { + for (int rty : {ref::BF16, ref::F32}) { + const int NE = 512; + const size_t rbr = ref::row_bytes(rty, N); + mtl::Buffer Wr = cx.alloc(rbr * NE), lg1 = cx.alloc(4 * MAXT * NE), lg2 = cx.alloc(4 * MAXT * NE), + id1 = cx.alloc(4 * MAXT * 10), id2 = cx.alloc(4 * MAXT * 10), w1 = cx.alloc(4 * MAXT * 10), + w2 = cx.alloc(4 * MAXT * 10), pl1 = cx.alloc(4 * P_INTS), pl2 = cx.alloc(4 * P_INTS), cnt = cx.alloc(16); + ref::random_blocks(rty, Wr.as(), NE, N, 9, 0.05f); + mtl::Pipeline pr = cx.pipeline(lib, "moe_route"); + for (int nt = 1; nt <= 4; ++nt) { + mtl::Pipeline pg = cx.pipeline(lib, "gemv_" + std::to_string(rty) + "_32_1_4_1", mtl::Constants().i(0, nt)), + pf = cx.pipeline(lib, "router_route_" + std::to_string(rty), mtl::Constants().i(0, nt)); + const size_t s16 = (size_t)4 * 4 * MAXT * N; + GemvArgs ga{(uint32_t)N, (uint32_t)NE, (uint32_t)nt, (uint32_t)rbr, (uint32_t)N, (uint32_t)NE}; + MoeArgs ma{}; + ma.n_tok = nt; + ma.topk = 10; + ma.n_expert = NE; + ma.gx_gu = 5; + ma.gx_dn = 20; + mtl::Dispatch g; + g.p = &pg; + g.args = {mtl::Arg::B(Wr), mtl::Arg::B(xp), mtl::Arg::B(xp, s16), mtl::Arg::B(lg1), mtl::Arg::V(ga)}; + g.grid[0] = NE / 4; + g.tg[0] = 128; + mtl::Dispatch rt; + rt.p = ≺ + rt.args = {mtl::Arg::B(lg1), mtl::Arg::B(id1), mtl::Arg::B(w1), mtl::Arg::B(pl1), mtl::Arg::V(ma)}; + rt.tg[0] = 512; + std::memset(pl1.ptr, 0, pl1.bytes); + cx.run({g, rt}); + bool ok = true; + for (int rep_ = 0; rep_ < 2; ++rep_) { + std::memset(pl2.ptr, 0, pl2.bytes); + mtl::Dispatch f; + f.p = &pf; + f.args = {mtl::Arg::B(Wr), mtl::Arg::B(xp), mtl::Arg::B(xp, s16), mtl::Arg::B(lg2), mtl::Arg::V(ga), mtl::Arg::B(id2), + mtl::Arg::B(w2), mtl::Arg::B(pl2), mtl::Arg::V(ma), mtl::Arg::B(cnt)}; + f.grid[0] = NE / 16; + f.tg[0] = 512; + cx.run({f}); + ok = ok && std::memcmp(lg1.ptr, lg2.ptr, 4 * nt * NE) == 0 && std::memcmp(id1.ptr, id2.ptr, 4 * nt * 10) == 0 && + std::memcmp(w1.ptr, w2.ptr, 4 * nt * 10) == 0 && std::memcmp(pl1.ptr, pl2.ptr, 4 * P_INTS) == 0 && + cnt.as()[0] == 0; + } + fails += !ok; + std::printf("router_route %s ntok %d: logits, ids, w, plan bitwise (2 runs) %s\n", ref::type_name(rty), nt, + ok ? "PASS" : "FAIL"); + } + } + } + // ---- gr_norm_comb + { + const int HC = 4, TOPK = 10; + mtl::Buffer R0 = cx.alloc(4 * MAXT * HC * N), R1 = cx.alloc(4 * MAXT * HC * N), R2 = cx.alloc(4 * MAXT * HC * N), + ye = cx.alloc(4 * (size_t)MAXT * TOPK * N), ysh = cx.alloc(4 * MAXT * N), sgv = cx.alloc(4 * MAXT), + plan = cx.alloc(4 * P_INTS), inj = cx.alloc(4 * MAXT * HC), wn = cx.alloc(4 * HC * N), bo = cx.alloc(4 * MAXT * N), + x1 = cx.alloc(4 * MAXT * HC * N), x2 = cx.alloc(4 * MAXT * HC * N); + for (size_t i = 0; i < R0.bytes / 4; ++i) R0.as()[i] = r.sym(); + for (size_t i = 0; i < ye.bytes / 4; ++i) ye.as()[i] = r.sym(); + for (size_t i = 0; i < ysh.bytes / 4; ++i) ysh.as()[i] = r.sym(); + for (int i = 0; i < MAXT; ++i) sgv.as()[i] = r.sym() * 3; + for (int i = 0; i < MAXT * HC; ++i) inj.as()[i] = r.sym() * 3; + for (int i = 0; i < HC * N; ++i) wn.as()[i] = 0.5f + r.uni(); + for (int i = 0; i < MAXT * TOPK; ++i) plan.as()[P_TOKENT + i] = (i * 7) % (MAXT * TOPK); + mtl::Pipeline pcm = cx.pipeline(lib, "moe_combine_sh"), pn = cx.pipeline(lib, "gr_norm"), pnc = cx.pipeline(lib, "gr_norm_comb"); + for (int nt = 1; nt <= 4; ++nt) { + std::memcpy(R1.ptr, R0.ptr, R0.bytes); + std::memcpy(R2.ptr, R0.ptr, R0.bytes); + GlueArgs ga{(uint32_t)N, (uint32_t)nt, (uint32_t)N, TOPK}; + GrArgs gr{(uint32_t)N, HC, 320, (uint32_t)nt, 1, 1e-6f}; + mtl::Dispatch c; c.p = &pcm; + c.args = {mtl::Arg::B(ye), mtl::Arg::B(plan), mtl::Arg::B(ysh), mtl::Arg::B(sgv), mtl::Arg::B(bo), mtl::Arg::V(ga)}; + c.grid[0] = (nt * N + 255) / 256; c.tg[0] = 256; + mtl::Dispatch n1; n1.p = &pn; + n1.args = {mtl::Arg::B(R1), mtl::Arg::B(bo), mtl::Arg::B(inj), mtl::Arg::B(wn), mtl::Arg::B(x1), mtl::Arg::V(gr)}; + n1.grid[0] = HC; n1.grid[1] = nt; n1.tg[0] = 256; + cx.run({c, n1}); + const uint32_t tk = TOPK; + mtl::Dispatch n2; n2.p = &pnc; + n2.args = {mtl::Arg::B(R2), mtl::Arg::B(ye), mtl::Arg::B(inj), mtl::Arg::B(wn), mtl::Arg::B(x2), mtl::Arg::V(gr), + mtl::Arg::B(plan), mtl::Arg::B(ysh), mtl::Arg::B(sgv), mtl::Arg::V(tk)}; + n2.grid[0] = HC; n2.grid[1] = nt; n2.tg[0] = 256; + cx.run({n2}); + const bool ok = std::memcmp(R1.ptr, R2.ptr, 4 * (size_t)nt * HC * N) == 0 && std::memcmp(x1.ptr, x2.ptr, 4 * (size_t)nt * HC * N) == 0; + fails += !ok; + std::printf("gr_norm_comb ntok %d: R', xn bitwise %s\n", nt, ok ? "PASS" : "FAIL"); + } + } + std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS"); + return fails ? 1 : 0; +} diff --git a/metal/tests/gdn_parity.cpp b/metal/tests/gdn_parity.cpp new file mode 100644 index 00000000..0d8c1dea --- /dev/null +++ b/metal/tests/gdn_parity.cpp @@ -0,0 +1,201 @@ +// metal/tests/gdn_parity.cpp - the fused GDN layer step (gdn.metal) against a double-precision CPU reference of the +// native contract, the window properties, and its speed. +// +// gdn_parity parity for windows of 1..4 tokens: y, the committed state and conv history; a verify +// window leaves the state untouched; its first m outputs are bitwise a fold of m +// gdn_parity --bench GPU time per layer: 36 distinct layer states rotated (113 MB, beyond the SLC) +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { +constexpr int S = 128, HK = 16, HV = 48, C = (2 * HK + HV) * S, MAXT = 8; +struct GdnArgs { uint32_t h_k, h_v, channels, commit; float eps; uint32_t plane; }; +double median(std::vector v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; } +struct Err { + double se = 0, sr = 0; + void add(double g, double r) { se += (g - r) * (g - r); sr += r * r; } + double l2() const { return sr > 0 ? std::sqrt(se / sr) : std::sqrt(se); } +}; +} // namespace + +int main(int argc, char** argv) { + const bool bench = argc > 1 && std::string(argv[1]) == "--bench"; + mtl::Context cx; + const int lib = cx.compile({"gdn.metal"}, "#define NO_GGML_COMMON 1\n"); + std::printf("device %s\n", cx.device_name().c_str()); + const int LAYERS = bench ? 36 : 1; + const size_t st_elems = (size_t)S * HV * S; + mtl::Buffer state = cx.alloc(4 * st_elems * LAYERS), st0 = cx.alloc(4 * st_elems), hist = cx.alloc(4 * C * 3 * LAYERS), + h0 = cx.alloc(4 * C * 3), qkv = cx.alloc(4 * C * MAXT), al = cx.alloc(4 * HV * MAXT), + be = cx.alloc(4 * HV * MAXT), z = cx.alloc(4 * HV * S * MAXT), cw = cx.alloc(4 * C * 4), + dt = cx.alloc(4 * HV), sa = cx.alloc(4 * HV), gm = cx.alloc(4 * S), y = cx.alloc(4 * HV * S * MAXT), + y2 = cx.alloc(4 * HV * S * MAXT), hist2 = cx.alloc(4 * C * 3 * LAYERS); + ref::Rng r(17); + for (size_t i = 0; i < st_elems; ++i) st0.as()[i] = r.sym() * 0.1f; + for (int i = 0; i < C * 3; ++i) h0.as()[i] = r.sym(); + for (int i = 0; i < C * MAXT; ++i) qkv.as()[i] = r.sym() * 2.0f; + for (int i = 0; i < HV * MAXT; ++i) { al.as()[i] = r.sym() * 2.0f; be.as()[i] = r.sym() * 2.0f; } + for (int i = 0; i < HV * S * MAXT; ++i) z.as()[i] = r.sym() * 2.0f; + for (int i = 0; i < C * 4; ++i) cw.as()[i] = r.sym() * 0.5f; + for (int i = 0; i < HV; ++i) { dt.as()[i] = r.sym(); sa.as()[i] = -std::exp(r.sym()); } + for (int i = 0; i < S; ++i) gm.as()[i] = 1.0f + 0.2f * r.sym(); + for (int l = 0; l < LAYERS; ++l) { + std::memcpy(state.as() + l * st_elems, st0.ptr, 4 * st_elems); + std::memcpy(hist.as() + l * C * 3, h0.ptr, 4 * C * 3); + } + auto disp = [&](const mtl::Pipeline& p, int layer, int commit, const mtl::Buffer& out) { + GdnArgs a{HK, HV, C, (uint32_t)commit, 1e-6f, 0}; + mtl::Dispatch d; + d.p = &p; + d.args = {mtl::Arg::B(state, 4 * st_elems * layer), mtl::Arg::B(hist, 4 * (size_t)C * 3 * layer), mtl::Arg::B(qkv), + mtl::Arg::B(al), mtl::Arg::B(be), mtl::Arg::B(z), mtl::Arg::B(cw), mtl::Arg::B(dt), mtl::Arg::B(sa), + mtl::Arg::B(gm), mtl::Arg::B(out), mtl::Arg::V(a), mtl::Arg::B(hist2, 4 * (size_t)C * 3 * layer)}; + d.grid[0] = HV; + d.tg[0] = std::getenv("GDN_IB8") ? 1024 : 512; + return d; + }; + { + mtl::Pipeline p1 = cx.pipeline(lib, "gdn_step", mtl::Constants().i(2, 1)); + std::printf("gdn_step pipeline: max %d threads per threadgroup (the kernel needs 512)\n", p1.max_threads); + } + if (bench) { + for (int nt : {1, 2, 3, 4}) { + const char* kn = std::getenv("GDN_IB8") ? "gdn_step8" : "gdn_step"; + mtl::Pipeline p = cx.pipeline(lib, kn, mtl::Constants().i(2, nt)); + for (int commit : {1, 0}) { + std::vector ds; + for (int k = 0; k < 72; ++k) ds.push_back(disp(p, k % LAYERS, commit, y)); + cx.warm(ds, 0.1); + std::vector t; + for (int i = 0; i < 7; ++i) t.push_back(cx.run(ds) / 72); + const double m = median(t), bytes = 4.0 * st_elems * (commit ? 2 : 1); + std::printf("gdn_step ntok %d %-7s %7.2f us per layer state %.1f MB at %6.1f GB/s (x36 layers: %.3f ms)\n", + nt, commit ? "commit" : "verify", m * 1e6, bytes / 1e6, bytes / m / 1e9, 36 * m * 1e3); + } + } + return 0; + } + int fails = 0; + for (int nt = 1; nt <= 4; ++nt) { + mtl::Pipeline p = cx.pipeline(lib, std::getenv("GDN_IB8") ? "gdn_step8" : "gdn_step", mtl::Constants().i(2, nt)); + // determinism: the same verify call three times + { + std::memcpy(state.ptr, st0.ptr, 4 * st_elems); + std::memcpy(hist.ptr, h0.ptr, 4 * C * 3); + cx.run({disp(p, 0, 0, y2)}); + std::vector first((float*)y2.ptr, (float*)y2.ptr + HV * S * nt); + int diff = 0; + for (int k = 0; k < 2; ++k) { + cx.run({disp(p, 0, 0, y2)}); + diff += std::memcmp(first.data(), y2.ptr, 4 * HV * S * nt) != 0; + } + if (diff) std::printf(" ntok %d: NOT deterministic (%d of 2 repeats differ)\n", nt, diff); + } + // verify: state untouched + std::memcpy(state.ptr, st0.ptr, 4 * st_elems); + std::memcpy(hist.ptr, h0.ptr, 4 * C * 3); + cx.run({disp(p, 0, 0, y2)}); + const bool untouched = std::memcmp(state.ptr, st0.ptr, 4 * st_elems) == 0 && std::memcmp(hist.ptr, h0.ptr, 4 * C * 3) == 0; + cx.run({disp(p, 0, 1, y)}); + const bool same_y = std::memcmp(y.ptr, y2.ptr, 4 * HV * S * nt) == 0; + // the reference + std::vector Sd(st_elems), Hd(C * 3); + for (size_t i = 0; i < st_elems; ++i) Sd[i] = st0.as()[i]; + for (int i = 0; i < C * 3; ++i) Hd[i] = h0.as()[i]; + Err ey, es, eh; + for (int t = 0; t < nt; ++t) { + std::vector cv(C); + for (int c = 0; c < C; ++c) { + const double in = qkv.as()[t * C + c]; + double s = Hd[c * 3] * cw.as()[c * 4] + Hd[c * 3 + 1] * cw.as()[c * 4 + 1] + + Hd[c * 3 + 2] * cw.as()[c * 4 + 2] + in * cw.as()[c * 4 + 3]; + cv[c] = s / (1.0 + std::exp(-s)); + Hd[c * 3] = Hd[c * 3 + 1]; + Hd[c * 3 + 1] = Hd[c * 3 + 2]; + Hd[c * 3 + 2] = in; + } + for (int hh = 0; hh < 2 * HK; ++hh) { + double ss = 0; + for (int i = 0; i < S; ++i) ss += cv[hh * S + i] * cv[hh * S + i]; + const double rs = 1.0 / std::sqrt(ss / S + 1e-6 / S); + for (int i = 0; i < S; ++i) cv[hh * S + i] = cv[hh * S + i] * rs / std::sqrt((double)S); + } + for (int h = 0; h < HV; ++h) { + const int hk = h % HK; + const double* q = &cv[hk * S]; + const double* k = &cv[HK * S + hk * S]; + const double* v = &cv[2 * HK * S + h * S]; + const double av = (double)al.as()[t * HV + h] + dt.as()[h]; + const double sp = av > 20 ? av : std::log1p(std::exp(av)); + const double g = std::exp(sp * sa.as()[h]); + const double b = 1.0 / (1.0 + std::exp(-(double)be.as()[t * HV + h])); + std::vector o(S); + for (int jj = 0; jj < S; ++jj) { + double kv = 0; + for (int i = 0; i < S; ++i) kv += Sd[((size_t)i * HV + h) * S + jj] * k[i]; + const double delta = (v[jj] - g * kv) * b; + double acc = 0; + for (int i = 0; i < S; ++i) { + double& sv = Sd[((size_t)i * HV + h) * S + jj]; + sv = g * sv + k[i] * delta; + acc += sv * q[i]; + } + o[jj] = acc / std::sqrt((double)S); + } + double ss = 0; + for (int jj = 0; jj < S; ++jj) ss += o[jj] * o[jj]; + const double rs = 1.0 / std::sqrt(ss / S + 1e-6); + for (int jj = 0; jj < S; ++jj) { + const double zz = z.as()[t * HV * S + h * S + jj]; + ey.add(y.as()[t * HV * S + h * S + jj], o[jj] * rs * gm.as()[jj] / (1.0 + std::exp(-zz))); + } + } + } + for (size_t i = 0; i < st_elems; ++i) es.add(state.as()[i], Sd[i]); + for (int i = 0; i < C * 3; ++i) eh.add(hist2.as()[i], Hd[i]); + // fold property: a window of nt + 1 tokens (no commit) gives bitwise the same first nt outputs + bool prefix = true; + if (nt < 4) { + mtl::Pipeline p2 = cx.pipeline(lib, std::getenv("GDN_IB8") ? "gdn_step8" : "gdn_step", mtl::Constants().i(2, nt + 1)); + std::memcpy(state.ptr, st0.ptr, 4 * st_elems); + std::memcpy(hist.ptr, h0.ptr, 4 * C * 3); + cx.run({disp(p2, 0, 0, y2)}); + prefix = std::memcmp(y.ptr, y2.ptr, 4 * HV * S * nt) == 0; + } + // partial commit (commit = 0x100 | k): the state and history after the first k tokens, bitwise those of a + // k-token commit; y bitwise the verify window's + bool partial = true; + for (int k = 1; k < nt; ++k) { + mtl::Pipeline pk = cx.pipeline(lib, std::getenv("GDN_IB8") ? "gdn_step8" : "gdn_step", mtl::Constants().i(2, k)); + mtl::Pipeline pn = cx.pipeline(lib, std::getenv("GDN_IB8") ? "gdn_step8" : "gdn_step", mtl::Constants().i(2, nt)); + std::memcpy(state.ptr, st0.ptr, 4 * st_elems); + std::memcpy(hist.ptr, h0.ptr, 4 * C * 3); + cx.run({disp(pk, 0, 1, y2)}); + std::vector sk(state.as(), state.as() + st_elems), hk(hist2.as(), hist2.as() + C * 3); + std::memcpy(state.ptr, st0.ptr, 4 * st_elems); + cx.run({disp(pn, 0, 0, y)}); + std::vector yv(y.as(), y.as() + HV * S * nt); + std::memcpy(state.ptr, st0.ptr, 4 * st_elems); + std::memset(hist2.ptr, 0xFF, 4 * C * 3); + cx.run({disp(pn, 0, 0x100 | k, y2)}); + partial = partial && std::memcmp(state.ptr, sk.data(), 4 * st_elems) == 0 && + std::memcmp(hist2.ptr, hk.data(), 4 * C * 3) == 0 && std::memcmp(y2.ptr, yv.data(), 4 * HV * S * nt) == 0; + } + const bool ok = untouched && same_y && prefix && partial && ey.l2() < 1e-5 && es.l2() < 1e-5 && eh.l2() == 0; + fails += !ok; + std::printf("gdn parity ntok %d: y rel L2 %.2e, state %.2e, history %.1e; verify leaves state: %s, verify y == " + "commit y: %s, first %d of a longer window bitwise: %s, partial commits bitwise: %s %s\n", nt, ey.l2(), es.l2(), + eh.l2(), untouched ? "yes" : "NO", same_y ? "yes" : "NO", nt, prefix ? "yes" : "NO", partial ? "yes" : "NO", + ok ? "PASS" : "FAIL"); + } + std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS"); + return fails ? 1 : 0; +} diff --git a/metal/tests/gdn_prompt_parity.cpp b/metal/tests/gdn_prompt_parity.cpp new file mode 100644 index 00000000..24cb85bf --- /dev/null +++ b/metal/tests/gdn_prompt_parity.cpp @@ -0,0 +1,175 @@ +// metal/tests/gdn_prompt_parity.cpp - the prompt GDN passes (gdn_prompt.metal: gdn_pre -> gdn_scan -> gdn_post) +// against the decode step run over the same T tokens in order (gdn.metal's gdn_step, GDN_NTOK = T, itself checked +// against the CPU reference by gdn_parity): y, the final state and the conv history. The scan reassociates +// o = S_new^T q as g S^T q + delta (k . q), so the match is to rounding, not bitwise. Then the speed for T = 2048. +// gdn_prompt_parity [--bench] +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include +#include + +namespace { +constexpr int HK = 16, HV = 48, CH = 10240, S = 128; +struct GdnArgs { uint32_t h_k, h_v, channels, commit; float eps; uint32_t plane; }; +struct GdnPArgs { uint32_t n_tok, h_k, h_v, channels; float eps; uint32_t f32; }; +double median(std::vector v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; } +} // namespace + +int main(int argc, char** argv) { + const bool bench = argc > 1 && std::string(argv[1]) == "--bench"; + mtl::Context cx; + const int lib = cx.compile({"gdn.metal", "gdn_prompt.metal"}, "#define NO_GGML_COMMON 1\n"); + std::printf("device %s\n", cx.device_name().c_str()); + const int TMAX = 2048; + auto F = [&](size_t n) { return cx.alloc(4 * n); }; + mtl::Buffer qkv = F((size_t)TMAX * CH), al = F(TMAX * HV), be = F(TMAX * HV), z = F((size_t)TMAX * HV * S), cw = F(CH * 4), + dt = F(HV), sa = F(HV), gam = F(S), st0 = F(S * HV * S), stA = F(S * HV * S), stB = F(S * HV * S), + h0 = F(CH * 3), hA = F(CH * 3), hA2 = F(CH * 3), hB = F(CH * 3), yA = F((size_t)TMAX * HV * S), + yB = F((size_t)TMAX * HV * S), yh = cx.alloc(2 * (size_t)TMAX * HV * S), qn = F((size_t)TMAX * HK * S), + kn = F((size_t)TMAX * HK * S), vc = F((size_t)TMAX * HV * S), gb = F(2 * TMAX * HV), kq = F(TMAX * HK), + o = F((size_t)TMAX * HV * S); + const size_t NCM = (TMAX + 31) / 32; + mtl::Buffer cU = F((size_t)HV * NCM * 32 * S), cW = F((size_t)HV * NCM * 32 * S), clg = F((size_t)HV * NCM * 32), + cD = F((size_t)HV * NCM * 32 * S); + ref::Rng r(21); + for (size_t i = 0; i < (size_t)TMAX * CH; ++i) qkv.as()[i] = r.sym() * 2.0f; + for (int i = 0; i < TMAX * HV; ++i) { al.as()[i] = r.sym() * 3.0f; be.as()[i] = r.sym() * 2.0f; } + for (size_t i = 0; i < (size_t)TMAX * HV * S; ++i) z.as()[i] = r.sym() * 2.0f; + for (int i = 0; i < CH * 4; ++i) cw.as()[i] = r.sym() * 0.6f; + for (int i = 0; i < HV; ++i) { dt.as()[i] = r.sym(); sa.as()[i] = -0.2f - r.uni() * 2.0f; } + for (int i = 0; i < S; ++i) gam.as()[i] = 0.5f + r.uni(); + for (int i = 0; i < S * HV * S; ++i) st0.as()[i] = r.sym() * 0.1f; + for (int i = 0; i < CH * 3; ++i) h0.as()[i] = r.sym(); + auto prompt_ds = [&](int T, const mtl::Pipeline& pre, const mtl::Pipeline& scan, const mtl::Pipeline& post, int cb, + std::vector& ds) { + GdnPArgs a{(uint32_t)T, HK, HV, CH, 1e-6f, 1u}; + mtl::Dispatch d1; + d1.p = ⪯ + d1.args = {mtl::Arg::B(qkv), mtl::Arg::B(hB), mtl::Arg::B(cw), mtl::Arg::B(al), mtl::Arg::B(be), mtl::Arg::B(dt), + mtl::Arg::B(sa), mtl::Arg::B(qn), mtl::Arg::B(kn), mtl::Arg::B(vc), mtl::Arg::B(gb), mtl::Arg::B(kq), + mtl::Arg::B(hA2), mtl::Arg::V(a)}; + d1.grid[0] = HK + HV / 2; + d1.grid[1] = T; + d1.tg[0] = 256; + ds.push_back(d1); + if (cb == -100) { // the chunked form: gdn_cprep, gdn_cstate, gdn_cout + const uint32_t nc = (T + 31) / 32; + static mtl::Pipeline pcp = cx.pipeline(lib, "gdn_cprep"), pcs = cx.pipeline(lib, "gdn_cstate"), + pco = cx.pipeline(lib, "gdn_cout"); + mtl::Dispatch e1; e1.p = &pcp; + e1.args = {mtl::Arg::B(qn), mtl::Arg::B(kn), mtl::Arg::B(vc), mtl::Arg::B(gb), mtl::Arg::B(cU), mtl::Arg::B(cW), + mtl::Arg::B(clg), mtl::Arg::V(a)}; + e1.grid[0] = HV; e1.grid[1] = nc; e1.tg[0] = 256; ds.push_back(e1); + mtl::Dispatch e2; e2.p = &pcs; + e2.args = {mtl::Arg::B(stB), mtl::Arg::B(qn), mtl::Arg::B(kn), mtl::Arg::B(cU), mtl::Arg::B(cW), mtl::Arg::B(clg), + mtl::Arg::B(cD), mtl::Arg::B(o), mtl::Arg::V(a)}; + e2.grid[0] = HV * 4; e2.tg[0] = 256; ds.push_back(e2); + mtl::Dispatch e3; e3.p = &pco; + e3.args = {mtl::Arg::B(qn), mtl::Arg::B(kn), mtl::Arg::B(cD), mtl::Arg::B(clg), mtl::Arg::B(o), mtl::Arg::V(a)}; + e3.grid[0] = HV; e3.grid[1] = nc; e3.tg[0] = 128; ds.push_back(e3); + } else { + mtl::Dispatch d2; + d2.p = &scan; + d2.args = {mtl::Arg::B(stB), mtl::Arg::B(qn), mtl::Arg::B(kn), mtl::Arg::B(vc), mtl::Arg::B(gb), mtl::Arg::B(kq), + mtl::Arg::B(o), mtl::Arg::V(a)}; + // cb > 0: gdn_scan_ (cb column blocks of 32 a threadgroup); cb < 0: gdn_scanr_<-cb> (-cb row blocks) + d2.grid[0] = cb > 0 ? HV * 4 / cb : HV * 4; + d2.tg[0] = 32 * (cb > 0 ? cb : -cb); + ds.push_back(d2); + } + mtl::Dispatch d3; + d3.p = &post; + d3.args = {mtl::Arg::B(o), mtl::Arg::B(z), mtl::Arg::B(gam), mtl::Arg::B(yh), mtl::Arg::B(yB), mtl::Arg::V(a)}; + d3.grid[0] = HV; + d3.grid[1] = T; + d3.tg[0] = 128; + ds.push_back(d3); + }; + mtl::Pipeline pre = cx.pipeline(lib, "gdn_pre"), post = cx.pipeline(lib, "gdn_post"); + int fails = 0; + if (!bench) + for (int T : {1, 3, 37, 300}) + for (int cb : {1, 4, -2, -4, -8, -9, -100}) { + mtl::Constants pc; + if (cb < 0 && cb != -9) pc.i(6, 0); + mtl::Pipeline scan = cx.pipeline(lib, cb == -100 ? std::string("gdn_scanr_4") : cb == -9 ? std::string("gdn_scan_v") : cb > 0 ? "gdn_scan_" + std::to_string(cb) : "gdn_scanr_" + std::to_string(-cb), cb == -100 ? mtl::Constants().i(6, 0) : pc); + if (cb == -9) cb = -8; + mtl::Pipeline step = cx.pipeline(lib, "gdn_step", mtl::Constants().i(2, T)); + std::copy(st0.as(), st0.as() + S * HV * S, stA.as()); + std::copy(st0.as(), st0.as() + S * HV * S, stB.as()); + std::copy(h0.as(), h0.as() + CH * 3, hA.as()); + std::copy(h0.as(), h0.as() + CH * 3, hB.as()); + GdnArgs da{HK, HV, CH, 1, 1e-6f, 0}; + mtl::Dispatch d; + d.p = &step; + d.args = {mtl::Arg::B(stA), mtl::Arg::B(hA), mtl::Arg::B(qkv), mtl::Arg::B(al), mtl::Arg::B(be), mtl::Arg::B(z), + mtl::Arg::B(cw), mtl::Arg::B(dt), mtl::Arg::B(sa), mtl::Arg::B(gam), mtl::Arg::B(yA), mtl::Arg::V(da), + mtl::Arg::B(hA2)}; + d.grid[0] = HV; + d.tg[0] = 512; + cx.run({d}); + std::vector hdec(hA2.as(), hA2.as() + CH * 3); + std::vector ds; + prompt_ds(T, pre, scan, post, cb, ds); + cx.run(ds); + auto rel = [](const float* a, const float* b, size_t n) { + double se = 0, sr = 0; + for (size_t i = 0; i < n; ++i) { se += (double)(a[i] - b[i]) * (a[i] - b[i]); sr += (double)b[i] * b[i]; } + return std::sqrt(se / std::max(sr, 1e-30)); + }; + const double ry = rel(yB.as(), yA.as(), (size_t)T * HV * S), + rs = rel(stB.as(), stA.as(), S * HV * S), rh = rel(hA2.as(), hdec.data(), CH * 3); + double ryh = 0, syh = 0; + for (size_t i = 0; i < (size_t)T * HV * S; ++i) { + const double e = ref::f16_to_f32(yh.as()[i]) - yA.as()[i]; + ryh += e * e; + syh += (double)yA.as()[i] * yA.as()[i]; + } + const bool ok = ry < 1e-5 && rs < 1e-5 && rh == 0 && std::sqrt(ryh / syh) < 1e-3; + fails += !ok; + std::printf("T %3d, scan CB %d: y rel %.2e (fp16 %.2e), state rel %.2e, history %s %s\n", T, cb, ry, + std::sqrt(ryh / syh), rs, rh == 0 ? "exact" : "DIFFERS", ok ? "PASS" : "FAIL"); + } + if (fails || !bench) { + std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS"); + return fails ? 1 : 0; + } + // speed, T = 2048: the decode step over the chunk vs the three passes (each scan width) + const int T = 2048; + mtl::Pipeline step = cx.pipeline(lib, "gdn_step", mtl::Constants().i(2, T)); + GdnArgs da{HK, HV, CH, 1, 1e-6f, 0}; + mtl::Dispatch d; + d.p = &step; + d.args = {mtl::Arg::B(stA), mtl::Arg::B(hA), mtl::Arg::B(qkv), mtl::Arg::B(al), mtl::Arg::B(be), mtl::Arg::B(z), + mtl::Arg::B(cw), mtl::Arg::B(dt), mtl::Arg::B(sa), mtl::Arg::B(gam), mtl::Arg::B(yA), mtl::Arg::V(da), mtl::Arg::B(hA2)}; + d.grid[0] = HV; + d.tg[0] = 512; + auto timeit = [&](const std::vector& ds) { + cx.warm(ds, 0.3); + std::vector t; + for (int i = 0; i < 5; ++i) t.push_back(cx.run(ds)); + return median(t); + }; + std::printf("T %d: decode step over the chunk %.2f ms\n", T, timeit({d}) * 1e3); + for (const char* nm : {"gdn_scanr_4", "chunked", "gdn_scanr_4", "chunked"}) { + const bool ch = std::string(nm) == "chunked"; + const int cb = ch ? -100 : nm[9] == 'v' ? -8 : nm[8] == 'r' ? -(nm[10] - '0') : nm[9] - '0'; + mtl::Constants pc; + if (cb < 0 && nm[9] != 'v') pc.i(6, std::getenv("GDN_PROBE") ? std::atoi(std::getenv("GDN_PROBE")) : 0); + mtl::Pipeline scan = cx.pipeline(lib, ch ? "gdn_scanr_4" : nm, pc); + std::vector ds; + prompt_ds(T, pre, scan, post, cb, ds); + const double all = timeit(ds), tp = timeit({ds[0]}), + ts = timeit(std::vector(ds.begin() + 1, ds.end() - 1)), to = timeit({ds.back()}); + if (ch) std::printf(" chunked parts: cprep %.3f, cstate %.3f, cout %.3f ms\n", timeit({ds[1]}) * 1e3, timeit({ds[2]}) * 1e3, + timeit({ds[3]}) * 1e3); + std::printf("T %d, %-13s: pre %.3f + scan %.3f + post %.3f ms = %.3f ms together\n", T, nm, tp * 1e3, ts * 1e3, + to * 1e3, all * 1e3); + } + return 0; +} diff --git a/metal/tests/gemv_parity.cpp b/metal/tests/gemv_parity.cpp new file mode 100644 index 00000000..5687527f --- /dev/null +++ b/metal/tests/gemv_parity.cpp @@ -0,0 +1,333 @@ +// metal/tests/gemv_parity.cpp - the dense GEMV (gemv.metal) per format: parity against double, and speed per tile +// shape on the model's projection shapes. +// +// gemv_parity parity: every format, n_in 2560/640/10240, 1..8 tokens +// gemv_parity --bench [--pack Q2_0|IQ3_XXS] [--ntok N] [--all] speed on the pack's shapes (best tile per shape) +// gemv_parity --one TYPE NIN NOUT [--ntok N] sweep one shape +#include "gguf_lite.h" +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +struct GemvArgs { uint32_t n_in, n_out, n_tok, row_bytes, x_stride, y_stride; }; +struct Cfg { int L, R, S, K; }; +const std::vector kCfgs = {{32, 1, 4, 1}, {32, 2, 4, 1}, {16, 1, 4, 1}, {16, 2, 4, 1}, {8, 1, 4, 1}, + {8, 2, 4, 1}, {4, 2, 4, 1}, {4, 1, 4, 1}, {32, 1, 4, 4}, {32, 2, 4, 2}, + {32, 1, 8, 8}, {16, 1, 8, 4}, {32, 1, 8, 2}, {8, 1, 8, 1}, {1, 1, 4, 1}, + {1, 2, 4, 1}, {2, 1, 4, 1}, {2, 2, 4, 1}, {1, 1, 2, 1}, {4, 4, 4, 1}}; +int rows_per_tg(Cfg c) { return (c.S / c.K) * (32 / c.L) * c.R; } +int unit_of(int t) { + switch (t) { + case ref::Q2_0: case ref::IQ3_S: case ref::IQ3_XXS: case ref::IQ2_XXS: case ref::IQ2_XS: case ref::IQ2_S: + case ref::BF16: case ref::F32: return 16; + default: return 32; + } +} +bool cfg_ok(Cfg c, int type, int n_in) { + const int U = n_in / unit_of(type); + return U % c.K == 0 && U / c.K >= c.L / 2; +} +std::string kname(int t, Cfg c) { + return "gemv_" + std::to_string(t) + "_" + std::to_string(c.L) + "_" + std::to_string(c.R) + "_" + + std::to_string(c.S) + "_" + std::to_string(c.K); +} +double median(std::vector v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; } +// which prepared x a format reads (units.metal XK_*) +int xkind(int t) { + switch (t) { + case ref::Q2_0: return 1; + case ref::Q4_K: case ref::Q5_K: return 2; + case ref::Q6_K: case ref::Q3_K: return 3; + default: return 0; + } +} +// x [MAXT][n] -> XP [4][MAXT][n] + S16 [MAXT][n/16] +mtl::Dispatch xprep_dispatch(const mtl::Pipeline& p, const mtl::Buffer& x, const mtl::Buffer& xp, uint32_t n, uint32_t nt) { + mtl::Dispatch d; + d.p = &p; + d.args = {mtl::Arg::B(x), mtl::Arg::B(xp), mtl::Arg::V(n), mtl::Arg::V(nt)}; + d.tg[0] = 256; + d.grid[0] = (n / 16 * nt + 255) / 256; + return d; +} + +int type_of(const std::string& s) { + for (int t : {ref::Q2_0, ref::Q4_0, ref::Q5_0, ref::Q8_0, ref::Q3_K, ref::Q4_K, ref::Q5_K, ref::Q6_K, ref::IQ4_NL, + ref::IQ4_XS, ref::IQ3_S, ref::BF16}) + if (s == ref::type_name(t)) return t; + std::fprintf(stderr, "unknown type %s\n", s.c_str()); + std::exit(2); +} + +struct Shape { const char* name; int type, n_in, n_out, per_token; }; // per_token: calls per decoded token + +} // namespace + +int main(int argc, char** argv) { + bool bench = false, all = false; + int ntok = 1; + std::string gguf_path; + std::string pack = "Q2_0"; + std::vector one; + for (int i = 1; i < argc; ++i) { + std::string a = argv[i]; + if (a == "--bench") bench = true; + else if (a == "--all") all = true; + else if (a == "--ntok") ntok = std::atoi(argv[++i]); + else if (a == "--pack") pack = argv[++i]; + else if (a == "--gguf") gguf_path = argv[++i]; + else if (a == "--one") { + const int t = type_of(argv[i + 1]); + one.push_back({"one", t, std::atoi(argv[i + 2]), std::atoi(argv[i + 3]), 1}); + i += 3; + bench = true; + all = true; + } else { std::fprintf(stderr, "unknown argument %s\n", a.c_str()); return 2; } + } + mtl::Context cx; + const int lib = cx.compile({"quant.metal", "units.metal", "gemv.metal"}); + std::printf("device %s\n", cx.device_name().c_str()); + const int MAXT = 8; + mtl::Pipeline pprep = cx.pipeline(lib, "xprep"); + + if (!gguf_path.empty()) { + // real tensors: the first type-distinct ones of the file (experts: expert 0's matrix), 1 and 3 tokens + gguf::File f; + std::string err; + if (!f.open(gguf_path, err)) { std::fprintf(stderr, "%s\n", err.c_str()); return 2; } + mtl::Buffer Wf = cx.wrap(f.map, f.map_bytes); + std::map pick; + for (const auto& kv : f.tensors) { + const gguf::Tensor& t = kv.second; + if (t.shape.size() < 2 || t.name.find("token_embd") != std::string::npos || + t.name.find("per_layer") != std::string::npos) + continue; + const int ty = t.type; + const bool gemv_type = ty == ref::BF16 || ty == ref::Q8_0 || ty == ref::Q4_0 || ty == ref::Q5_0 || + ty == ref::IQ4_NL || ty == ref::IQ4_XS || ty == ref::Q2_0 || ty == ref::IQ3_S || + ty == ref::Q3_K || ty == ref::Q4_K || ty == ref::Q5_K || ty == ref::Q6_K; + if (gemv_type && !pick.count(ty)) pick[ty] = &t; + } + int fails = 0; + for (const auto& kv : pick) { + const gguf::Tensor& t = *kv.second; + const int ty = t.type, n_in = (int)t.shape[0], n_out = std::min((int)t.shape[1], 4096); + const size_t rb = ref::row_bytes(ty, n_in); + mtl::Buffer x = cx.alloc(4 * n_in * MAXT), y = cx.alloc(4 * (size_t)n_out * MAXT), + xp = cx.alloc(4 * (4 * n_in * MAXT + n_in / 16 * MAXT)); + ref::Rng r(3); + for (int i = 0; i < n_in * MAXT; ++i) x.as()[i] = r.sym(); + cx.run({xprep_dispatch(pprep, x, xp, n_in, MAXT)}); + const size_t plane = (size_t)4 * n_in * MAXT; + std::vector wf((size_t)n_in * n_out); + ref::dequant(ty, (const uint8_t*)f.map + t.offset, wf.data(), wf.size()); + Cfg c = n_in >= 6144 ? Cfg{32, 1, 8, 2} : n_in <= 640 ? Cfg{8, 1, 4, 1} : Cfg{16, 1, 4, 1}; + if (!cfg_ok(c, ty, n_in)) c = Cfg{32, 1, 4, 1}; + for (int nt : {1, 3}) { + mtl::Pipeline p = cx.pipeline(lib, kname(ty, c), mtl::Constants().i(0, nt)); + GemvArgs a{(uint32_t)n_in, (uint32_t)n_out, (uint32_t)nt, (uint32_t)rb, (uint32_t)n_in, (uint32_t)n_out}; + mtl::Dispatch d; + d.p = &p; + d.args = {mtl::Arg::B(Wf, t.offset), mtl::Arg::B(xp, plane * xkind(ty)), mtl::Arg::B(xp, plane * 4), + mtl::Arg::B(y), mtl::Arg::V(a)}; + d.grid[0] = (n_out + rows_per_tg(c) - 1) / rows_per_tg(c); + d.tg[0] = c.S * 32; + cx.run({d}); + double se = 0, sr = 0; + for (int tt = 0; tt < nt; ++tt) + for (int o = 0; o < n_out; ++o) { + double ref = 0; + for (int k = 0; k < n_in; ++k) ref += (double)wf[(size_t)o * n_in + k] * x.as()[tt * n_in + k]; + const double e = y.as()[tt * n_out + o] - ref; + se += e * e; + sr += ref * ref; + } + const double rel = std::sqrt(se / sr); + const bool ok = rel < 1e-5 && std::isfinite(rel); + fails += !ok; + std::printf("real %-7s %-34s %5d x %5d ntok %d: rel L2 %.2e %s\n", ref::type_name(ty), t.name.c_str(), + n_out, n_in, nt, rel, ok ? "PASS" : "FAIL"); + } + } + std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS"); + return fails ? 1 : 0; + } + if (!bench) { + int fails = 0; + for (int t : {ref::F32, ref::BF16, ref::Q8_0, ref::Q4_0, ref::Q5_0, ref::IQ4_NL, ref::IQ4_XS, ref::Q2_0, ref::IQ3_S, + ref::Q3_K, ref::Q4_K, ref::Q5_K, ref::Q6_K}) { + for (int n_in : {2560, 640, 10240}) { + if (n_in % ref::block_elems(t)) continue; + const int n_out = 100; // not a multiple of the rows per threadgroup on purpose + const size_t rb = ref::row_bytes(t, n_in); + mtl::Buffer W = cx.alloc(rb * n_out), x = cx.alloc(4 * n_in * MAXT), y = cx.alloc(4 * n_out * MAXT); + mtl::Buffer xp = cx.alloc(4 * (4 * n_in * MAXT + n_in / 16 * MAXT)); + ref::random_blocks(t, W.as(), n_out, n_in, 31 + t + n_in); + ref::Rng r(7 + n_in); + for (int i = 0; i < n_in * MAXT; ++i) x.as()[i] = r.sym(); + cx.run({xprep_dispatch(pprep, x, xp, n_in, MAXT)}); + const size_t plane = (size_t)4 * n_in * MAXT; + std::vector wf((size_t)n_in * n_out); + ref::dequant(t, W.ptr, wf.data(), wf.size()); + for (int nt : {1, 3, 8}) { + double worst = 0; + int not_exact = 0; + std::string worst_cfg; + for (Cfg c : kCfgs) { + if (!cfg_ok(c, t, n_in)) continue; + mtl::Pipeline p = cx.pipeline(lib, kname(t, c), mtl::Constants().i(0, nt)); + GemvArgs a{(uint32_t)n_in, (uint32_t)n_out, (uint32_t)nt, (uint32_t)rb, (uint32_t)n_in, + (uint32_t)n_out}; + std::memset(y.ptr, 0, y.bytes); + mtl::Dispatch d; + d.p = &p; + d.args = {mtl::Arg::B(W), mtl::Arg::B(xp, plane * xkind(t)), mtl::Arg::B(xp, plane * 4), + mtl::Arg::B(y), mtl::Arg::V(a)}; + d.grid[0] = (n_out + rows_per_tg(c) - 1) / rows_per_tg(c); + d.tg[0] = c.S * 32; + cx.run({d}); + double se = 0, sr = 0; + for (int tt = 0; tt < nt; ++tt) + for (int o = 0; o < n_out; ++o) { + double ref = 0; + for (int k = 0; k < n_in; ++k) ref += (double)wf[(size_t)o * n_in + k] * x.as()[tt * n_in + k]; + const double e = y.as()[tt * n_out + o] - ref; + se += e * e; + sr += ref * ref; + } + const double rel = std::sqrt(se / sr); + if (rel > worst) { worst = rel; worst_cfg = kname(t, c); } + if (nt > 1) { + // every token of a window must be bitwise what a one-token call gives + std::vector ywin((float*)y.ptr, (float*)y.ptr + nt * n_out); + mtl::Pipeline p1 = cx.pipeline(lib, kname(t, c), mtl::Constants().i(0, 1)); + GemvArgs a1 = a; + a1.n_tok = 1; + for (int tt = 0; tt < nt; ++tt) { + mtl::Dispatch d1 = d; + d1.p = &p1; + d1.args = {mtl::Arg::B(W), mtl::Arg::B(xp, plane * xkind(t) + 4 * (size_t)tt * n_in), + mtl::Arg::B(xp, plane * 4 + 4 * (size_t)tt * (n_in / 16)), mtl::Arg::B(y), + mtl::Arg::V(a1)}; + cx.run({d1}); + if (std::memcmp(y.ptr, ywin.data() + tt * n_out, 4 * n_out) != 0) ++not_exact; + } + } + } + const bool ok = worst < 1e-5 && not_exact == 0; + fails += !ok; + std::printf("parity %-7s n_in %5d ntok %d: worst rel L2 over %zu tiles %.2e (%s), window == one " + "token: %s %s\n", + ref::type_name(t), n_in, nt, kCfgs.size(), worst, worst_cfg.c_str(), + nt == 1 ? "-" : not_exact ? "NO" : "bitwise", ok ? "PASS" : "FAIL"); + } + cx.free(W); + cx.free(x); + cx.free(y); + cx.free(xp); + } + } + std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS"); + return fails ? 1 : 0; + } + + // ---- bench + std::vector shapes = one; + if (shapes.empty()) { + if (pack == "Q2_0") + shapes = { + {"hc down (x4/layer)", ref::BF16, 10240, 320, 4 * 48}, {"hc up (x4/layer)", ref::BF16, 320, 10240, 4 * 48}, + {"router", ref::BF16, 2560, 512, 48}, {"gdn qkv", ref::IQ4_XS, 2560, 10240, 13}, + {"gdn qkv", ref::Q3_K, 2560, 10240, 18}, {"gdn qkv", ref::Q4_K, 2560, 10240, 4}, + {"gdn gate", ref::Q3_K, 2560, 6144, 25}, {"gdn out", ref::IQ4_XS, 6144, 2560, 17}, + {"gdn out", ref::Q4_K, 6144, 2560, 11}, {"qsa q", ref::Q3_K, 2560, 12288, 6}, + {"qsa out", ref::Q5_K, 6144, 2560, 4}, {"qsa k", ref::Q3_K, 2560, 512, 3}, + {"shexp gate", ref::Q2_0, 2560, 640, 21}, {"shexp down", ref::Q4_0, 640, 2560, 16}, + {"shexp down", ref::Q2_0, 640, 2560, 16}, {"indexer q", ref::BF16, 2560, 512, 12}, + {"ssm alpha", ref::BF16, 2560, 48, 36}, {"lm head", ref::Q5_K, 2560, 248320, 1}, + {"gdn qkv", ref::Q6_K, 2560, 10240, 1}, + }; + else + shapes = { + {"hc down (x4/layer)", ref::BF16, 10240, 320, 4 * 48}, {"hc up (x4/layer)", ref::BF16, 320, 10240, 4 * 48}, + {"gdn qkv", ref::IQ4_XS, 2560, 10240, 11}, {"gdn qkv", ref::Q6_K, 2560, 10240, 14}, + {"gdn qkv", ref::Q4_K, 2560, 10240, 8}, {"gdn out", ref::Q6_K, 6144, 2560, 19}, + {"gdn gate", ref::IQ3_S, 2560, 6144, 10}, {"gdn gate", ref::IQ4_XS, 2560, 6144, 11}, + {"qsa out", ref::Q6_K, 6144, 2560, 10}, {"qsa q", ref::IQ4_XS, 2560, 12288, 4}, + {"shexp down", ref::IQ4_NL, 640, 2560, 40}, {"shexp up", ref::IQ3_S, 2560, 640, 27}, + {"lm head", ref::Q5_K, 2560, 248320, 1}, + }; + } + std::vector ntoks = {ntok}; + std::printf("%-20s %-7s %6s %7s %5s %9s %9s %8s %s\n", "shape", "type", "n_in", "n_out", "ntok", "us", "GB/s", + "MB", "best tile (L,R,S,K)"); + for (const Shape& s : shapes) { + const size_t rb = ref::row_bytes(s.type, s.n_in), mb = rb * s.n_out; + const int copies = (int)std::max(4, std::min(256, (1ull << 30) / mb)); + mtl::Buffer W = cx.alloc(mb * copies), x = cx.alloc(4 * s.n_in * MAXT), y = cx.alloc(4 * (size_t)s.n_out * MAXT); + { + std::vector tmp(mb); + ref::random_blocks(s.type, tmp.data(), s.n_out, s.n_in, 99); + for (int c = 0; c < copies; ++c) std::memcpy(W.as() + (size_t)c * mb, tmp.data(), mb); + } + ref::Rng r(5); + for (int i = 0; i < s.n_in * MAXT; ++i) x.as()[i] = r.sym(); + mtl::Buffer xp = cx.alloc(4 * (4 * s.n_in * MAXT + s.n_in / 16 * MAXT)); + cx.run({xprep_dispatch(pprep, x, xp, s.n_in, MAXT)}); + const size_t plane = (size_t)4 * s.n_in * MAXT; + for (int nt : ntoks) { + double best = 1e9; + Cfg bc{}; + const bool gx = std::getenv("GEMV_X") != nullptr; // gemvx_* (x staged in threadgroup memory) + const uint32_t tgm = (uint32_t)(4 * nt * (s.n_in + s.n_in / 16) + 15) / 16 * 16; + for (Cfg c : gx ? std::vector{{32, 1, 4, 1}, {32, 2, 4, 1}, {16, 1, 4, 1}, {16, 2, 4, 1}, {8, 1, 4, 1}, + {8, 2, 4, 1}, {4, 2, 4, 1}, {16, 2, 8, 1}, {8, 2, 8, 1}, {16, 4, 4, 1}, + {32, 2, 8, 1}, {2, 2, 4, 1}} + : kCfgs) { + if (!cfg_ok(c, s.type, s.n_in)) continue; + if (!all && !(c.K == 1 || s.n_in >= 6144)) continue; + if (gx && tgm > 32768) continue; + const std::string kn = gx ? "gemvx_" + std::to_string(s.type) + "_" + std::to_string(c.L) + "_" + std::to_string(c.R) + + "_" + std::to_string(c.S) + : kname(s.type, c); + mtl::Pipeline p = cx.pipeline(lib, kn, mtl::Constants().i(0, nt).i(9, std::getenv("GEMV_PROBE") ? std::atoi(std::getenv("GEMV_PROBE")) : 0)); + GemvArgs a{(uint32_t)s.n_in, (uint32_t)s.n_out, (uint32_t)nt, (uint32_t)rb, (uint32_t)s.n_in, + (uint32_t)s.n_out}; + std::vector ds; + const int R = std::max(copies, 16); + for (int k = 0; k < R; ++k) { + mtl::Dispatch d; + d.p = &p; + d.args = {mtl::Arg::B(W, (size_t)(k % copies) * mb), mtl::Arg::B(xp, plane * xkind(s.type)), + mtl::Arg::B(xp, plane * 4), mtl::Arg::B(y), mtl::Arg::V(a)}; + d.grid[0] = (s.n_out + rows_per_tg(c) - 1) / rows_per_tg(c); + d.tg[0] = c.S * 32; + if (gx) d.tg_mem = tgm; + ds.push_back(d); + } + cx.warm(ds, 0.05); + std::vector t; + for (int i = 0; i < 5; ++i) t.push_back(cx.run(ds) / R); + const double m = median(t); + if (one.size()) std::printf(" tile %2d,%d,%d,%d: %8.2f us %6.1f GB/s\n", c.L, c.R, c.S, c.K, m * 1e6, mb / m / 1e9); + if (m < best) { best = m; bc = c; } + } + std::printf("%-20s %-7s %6d %7d %5d %9.2f %9.1f %8.2f %d,%d,%d,%d\n", s.name, ref::type_name(s.type), s.n_in, + s.n_out, nt, best * 1e6, mb / best / 1e9, mb / 1e6, bc.L, bc.R, bc.S, bc.K); + } + cx.free(W); + cx.free(x); + cx.free(y); + cx.free(xp); + } + return 0; +} diff --git a/metal/tests/gr2_parity.cpp b/metal/tests/gr2_parity.cpp new file mode 100644 index 00000000..fdc2337b --- /dev/null +++ b/metal/tests/gr2_parity.cpp @@ -0,0 +1,246 @@ +// metal/tests/gr2_parity.cpp - the two-dispatch hyper-connection read (gr2.metal: gr_down3 + gr_up3), BF16 and Q8_0 +// weights, against a double-precision reference of fused_gr.hpp's formulas on the SAME weights (the Q8_0 copy +// dequantized for its own check), plus how far the Q8_0 read lands from the BF16 one; and the speed. +// +// gr2_parity parity: 1, 3 and 8 tokens, with and without the folded write, BF16 and Q8_0 +// gr2_parity --bench GPU time of the 2 dispatches (48 weight sets rotated) per tile, vs the 3-dispatch read +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { +constexpr int N = 2560, HC = 4, LR = 320, NIN = HC * N, NR = LR + HC, MAXT = 8; +struct GrArgs { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; }; +struct GrArgs3 { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; uint32_t rb_down, rb_up, comb, topk; }; +double median(std::vector v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; } +struct Err { + double se = 0, sr = 0; + void add(double g, double r) { se += (g - r) * (g - r); sr += r * r; } + double l2() const { return sr > 0 ? std::sqrt(se / sr) : std::sqrt(se); } +}; +} // namespace + +int main(int argc, char** argv) { + const bool bench = argc > 1 && std::string(argv[1]) == "--bench"; + mtl::Context cx; + const int lib = cx.compile({"quant.metal", "units.metal", "gr.metal", "gr2.metal"}); + std::printf("device %s\n", cx.device_name().c_str()); + const int SETS = bench ? 48 : 1; + const size_t bd = (size_t)LR * NIN * 2, bi = (size_t)HC * NIN * 2, bu = (size_t)NIN * LR * 2; + const size_t qd = (size_t)LR * NIN / 32 * 34, qi = (size_t)HC * NIN / 32 * 34, qu = (size_t)NIN * LR / 32 * 34; + const size_t set = bd + bi + bu + qd + qi + qu + NIN * 4; + mtl::Buffer W = cx.alloc(set * SETS); + ref::Rng rng(3); + { + uint8_t* b = W.as(); + ref::random_blocks(ref::BF16, b, LR, NIN, 11, 0.02f); + ref::random_blocks(ref::BF16, b + bd, HC, NIN, 22, 0.02f); + ref::random_blocks(ref::BF16, b + bd + bi, NIN, LR, 33, 0.1f); + std::vector f((size_t)LR * NIN); + ref::dequant(ref::BF16, b, f.data(), (size_t)LR * NIN); + ref::quantize_q8_0(f.data(), (size_t)LR * NIN, b + bd + bi + bu); + ref::dequant(ref::BF16, b + bd, f.data(), (size_t)HC * NIN); + ref::quantize_q8_0(f.data(), (size_t)HC * NIN, b + bd + bi + bu + qd); + ref::dequant(ref::BF16, b + bd + bi, f.data(), (size_t)NIN * LR); + ref::quantize_q8_0(f.data(), (size_t)NIN * LR, b + bd + bi + bu + qd + qi); + float* wn = (float*)(b + bd + bi + bu + qd + qi + qu); + for (int i = 0; i < NIN; ++i) wn[i] = 1.0f + 0.1f * rng.sym(); + for (int s = 1; s < SETS; ++s) std::memcpy(b + s * set, b, set); + } + mtl::Buffer R0 = cx.alloc(4 * MAXT * NIN), Rout = cx.alloc(4 * MAXT * NIN), bo = cx.alloc(4 * MAXT * N), + inj = cx.alloc(4 * MAXT * HC), Dprev = cx.alloc(4 * MAXT * NR * HC), D = cx.alloc(4 * MAXT * NR * HC), + rs = cx.alloc(4 * MAXT * HC), xp = cx.alloc(4 * (4 * MAXT * N + MAXT * N / 16)), + xr = cx.alloc(4 * (4 * MAXT * N + MAXT * N / 16)), xpb = cx.alloc(4 * 2 * MAXT * N), + R3 = cx.alloc(4 * MAXT * NIN), xn = cx.alloc(4 * MAXT * NIN), lo = cx.alloc(4 * MAXT * LR), + injo = cx.alloc(4 * MAXT * HC); + for (int i = 0; i < MAXT * NIN; ++i) R0.as()[i] = rng.sym() * 2.0f; + for (int i = 0; i < MAXT * N; ++i) bo.as()[i] = rng.sym(); + for (int i = 0; i < MAXT * HC; ++i) inj.as()[i] = rng.sym() * 3.0f; + // the previous read's inject partials: stream 0 carries the whole value + for (int t = 0; t < MAXT; ++t) + for (int c = 0; c < HC; ++c) Dprev.as()[(t * NR + LR + c) * HC] = inj.as()[t * HC + c]; + mtl::Pipeline pprep = cx.pipeline(lib, "xprep"); + int fails = 0; + for (int nt : bench ? std::vector{1, 3} : std::vector{1, 3, 8}) { + for (int qq = 0; qq < 2; ++qq) { + const int q8 = std::getenv("GR_Q8FIRST") ? 1 - qq : qq; + const int F = q8 ? 8 : 30; + for (int tt : bench ? std::vector{1, 2, 3} : std::vector{3}) { + for (int rps : bench ? std::vector{1, 2} : std::vector{1}) { + if (bench && tt > nt) continue; + const char* pre = (!q8 && std::getenv("GR_PRELOAD")) ? "gr_down3b_" : "gr_down3_"; + const std::string dn = !q8 && std::getenv("GR_PRELOAD") + ? std::string(pre) + std::to_string(tt) + "_" + std::to_string(rps) + : std::string(pre) + std::to_string(F) + "_" + std::to_string(tt) + "_" + std::to_string(rps); + mtl::Pipeline pd = cx.pipeline(lib, dn, mtl::Constants().i(1, nt)), + pu = cx.pipeline(lib, "gr_up3_" + std::to_string(F), mtl::Constants().i(1, nt)); + for (int apply = 0; apply < 2; ++apply) { + if (bench && !apply) continue; + GrArgs3 a{N, HC, LR, MAXT, (uint32_t)apply, 1e-6f, (uint32_t)(q8 ? NIN / 32 * 34 : NIN * 2), + (uint32_t)(q8 ? LR / 32 * 34 : LR * 2)}; + auto enc = [&](int s, std::vector& ds) { + const size_t o = (size_t)s * set; + const size_t od = q8 ? o + bd + bi + bu : o, oi = q8 ? o + bd + bi + bu + qd : o + bd, + ou = q8 ? o + bd + bi + bu + qd + qi : o + bd + bi, + ow = o + bd + bi + bu + qd + qi + qu; + mtl::Dispatch d; + d.p = &pd; + d.args = {mtl::Arg::B(W, od), mtl::Arg::B(W, oi), mtl::Arg::B(R0), mtl::Arg::B(Rout), mtl::Arg::B(bo), + mtl::Arg::B(Dprev), mtl::Arg::B(W, ow), mtl::Arg::B(D), mtl::Arg::B(rs), mtl::Arg::V(a)}; + d.grid[0] = (NR + 8 * rps - 1) / (8 * rps); + d.grid[1] = HC; + d.tg[0] = 256; + ds.push_back(d); + mtl::Dispatch u; + u.p = &pu; + u.args = {mtl::Arg::B(W, ou), mtl::Arg::B(D), mtl::Arg::B(Rout), mtl::Arg::B(xp), mtl::Arg::V(a), + mtl::Arg::B(W, ow), mtl::Arg::B(rs)}; + u.grid[0] = N / 16; + u.tg[0] = 256; + ds.push_back(u); + }; + if (bench) { + std::vector ds; + for (int k = 0; k < 96; ++k) enc(k % SETS, ds); + if (const char* only = std::getenv("GR_ONLY")) { + std::vector o; + for (size_t i = (std::string(only) == "up"); i < ds.size(); i += 2) o.push_back(ds[i]); + ds = o; + } + cx.warm(ds, 0.1); + std::vector t; + for (int i = 0; i < 7; ++i) t.push_back(cx.run(ds) / 96); + const double bytes = q8 ? qd + qi + qu : bd + bi + bu; + std::printf("bench ntok %d %-4s TT %d RPS %d: 2 dispatches %7.2f us %6.1f GB/s (%.2f MB)\n", nt, + q8 ? "Q8_0" : "BF16", tt, rps, median(t) * 1e6, bytes / median(t) / 1e9, bytes / 1e6); + continue; + } + std::vector ds; + enc(0, ds); + cx.run(ds); + const uint8_t* b = W.as(); + std::vector wd((size_t)LR * NIN), wi((size_t)HC * NIN), wu((size_t)NIN * LR); + const int ty = q8 ? ref::Q8_0 : ref::BF16; + ref::dequant(ty, b + (q8 ? bd + bi + bu : 0), wd.data(), wd.size()); + ref::dequant(ty, b + (q8 ? bd + bi + bu + qd : bd), wi.data(), wi.size()); + ref::dequant(ty, b + (q8 ? bd + bi + bu + qd + qi : bd + bi), wu.data(), wu.size()); + const float* wn = (const float*)(b + bd + bi + bu + qd + qi + qu); + Err eR, elo, einj, emix; + for (int t = 0; t < nt; ++t) { + std::vector r(NIN), x(NIN); + for (int c = 0; c < HC; ++c) { + const double g = apply ? 2.0 / (1.0 + std::exp(-(double)inj.as()[t * HC + c] / HC)) : 0.0; + double ss = 0; + for (int d = 0; d < N; ++d) { + double v = R0.as()[t * NIN + c * N + d]; + if (apply) v += bo.as()[t * N + d] * g; + r[c * N + d] = v; + ss += v * v; + } + const double rsv = 1.0 / std::sqrt(ss / N + 1e-6); + for (int d = 0; d < N; ++d) x[c * N + d] = r[c * N + d] * wn[c * N + d] * rsv; + } + for (int i = 0; i < NIN; ++i) eR.add(Rout.as()[t * NIN + i], r[i]); + std::vector lg(LR); + for (int k = 0; k < LR; ++k) { + double s = 0; + for (int i = 0; i < NIN; ++i) s += (double)wd[(size_t)k * NIN + i] * x[i]; + const double z = s / HC; + const float* dp = D.as() + (t * NR + k) * HC; + const float zg = (((dp[0] + dp[1]) + dp[2]) + dp[3]) / (float)HC; + lg[k] = zg / (1.0f + std::exp(-zg)); + elo.add(lg[k], z / (1.0 + std::exp(-z))); + } + for (int c = 0; c < HC; ++c) { + double s = 0; + for (int i = 0; i < NIN; ++i) s += (double)wi[(size_t)c * NIN + i] * x[i]; + const float* dp = D.as() + (t * NR + LR + c) * HC; + einj.add(((dp[0] + dp[1]) + dp[2]) + dp[3], s); + } + for (int d = 0; d < N; ++d) { + double m = 0; + for (int c = 0; c < HC; ++c) { + double s = 0; + for (int k = 0; k < LR; ++k) s += (double)wu[(size_t)(c * N + d) * LR + k] * lg[k]; + m += x[c * N + d] / (1.0 + std::exp(-s)); + } + emix.add(xp.as()[t * N + d], m / HC); + } + } + { + mtl::Dispatch d; + d.p = &pprep; + const uint32_t n = N, ntt = MAXT; + d.args = {mtl::Arg::B(xp), mtl::Arg::B(xr), mtl::Arg::V(n), mtl::Arg::V(ntt)}; + d.tg[0] = 256; + d.grid[0] = (N / 16 * MAXT + 255) / 256; + cx.run({d}); + } + bool planes = true; + for (int k = 0; k < 4; ++k) + planes = planes && std::memcmp(xp.as() + (size_t)k * MAXT * N, + xr.as() + (size_t)k * MAXT * N, 4 * (size_t)nt * N) == 0; + planes = planes && std::memcmp(xp.as() + 4 * MAXT * N, xr.as() + 4 * MAXT * N, + 4 * nt * N / 16) == 0; + double qdiff = -1; + if (q8) { + Err e; + for (int i = 0; i < nt * N; ++i) e.add(xp.as()[i], xpb.as()[apply * MAXT * N + i]); + qdiff = e.l2(); + } else { + std::memcpy(xpb.as() + apply * MAXT * N, xp.ptr, 4 * (size_t)MAXT * N); + } + const bool ok = eR.l2() < 1e-6 && elo.l2() < 1e-5 && einj.l2() < 1e-5 && emix.l2() < 1e-5 && planes; + fails += !ok; + char extra[96] = ""; + if (qdiff >= 0) std::snprintf(extra, sizeof extra, ", mixed vs the BF16 read %.2e", qdiff); + std::printf("parity ntok %d %-4s apply %d: R' %.2e, lo %.2e, inject %.2e, mixed %.2e, planes %s%s %s\n", + nt, q8 ? "Q8_0" : "BF16", apply, eR.l2(), elo.l2(), einj.l2(), emix.l2(), + planes ? "bitwise" : "NO", extra, ok ? "PASS" : "FAIL"); + } + } + } + } + } + if (bench) { + mtl::Pipeline pn = cx.pipeline(lib, "gr_norm"), pd = cx.pipeline(lib, "gr_down_8_8", mtl::Constants().i(1, 1)), + pu = cx.pipeline(lib, "gr_up", mtl::Constants().i(1, 1)); + GrArgs a{N, HC, LR, 1, 1, 1e-6f}; + std::vector ds; + for (int k = 0; k < 96; ++k) { + const size_t o = (size_t)(k % SETS) * set; + mtl::Dispatch d1, d2, d3; + d1.p = &pn; + d1.args = {mtl::Arg::B(R3), mtl::Arg::B(bo), mtl::Arg::B(inj), mtl::Arg::B(W, o + bd + bi + bu + qd + qi + qu), + mtl::Arg::B(xn), mtl::Arg::V(a)}; + d1.grid[0] = HC; + d1.tg[0] = 256; + d2.p = &pd; + d2.args = {mtl::Arg::B(W, o), mtl::Arg::B(W, o + bd), mtl::Arg::B(xn), mtl::Arg::B(lo), mtl::Arg::B(injo), + mtl::Arg::V(a)}; + d2.grid[0] = LR + HC; + d2.tg[0] = 256; + d3.p = &pu; + d3.args = {mtl::Arg::B(W, o + bd + bi), mtl::Arg::B(lo), mtl::Arg::B(xn), mtl::Arg::B(xp), mtl::Arg::V(a)}; + d3.grid[0] = N / 16; + d3.tg[0] = 256; + ds.push_back(d1); + ds.push_back(d2); + ds.push_back(d3); + } + cx.warm(ds, 0.1); + std::vector t; + for (int i = 0; i < 7; ++i) t.push_back(cx.run(ds) / 96); + std::printf("bench ntok 1 BF16 3-dispatch read (gr.metal): %.2f us\n", median(t) * 1e6); + return 0; + } + std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS"); + return fails ? 1 : 0; +} diff --git a/metal/tests/gr_parity.cpp b/metal/tests/gr_parity.cpp new file mode 100644 index 00000000..0df1c528 --- /dev/null +++ b/metal/tests/gr_parity.cpp @@ -0,0 +1,208 @@ +// metal/tests/gr_parity.cpp - the hyper-connection read (gr.metal) against a double-precision CPU reference +// (fused_gr.hpp's formulas), and its speed. +// +// gr_parity [--ntok N] parity for N = 1, 3, 8 (or N), with and without the folded write +// gr_parity --bench [--ntok N] per-kernel GPU time, 8 weight sets rotated (no cache reuse across calls) +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { +constexpr int N = 2560, HC = 4, LR = 320, NIN = HC * N; +struct GrArgs { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; }; +double median(std::vector v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; } +struct Err { + double se = 0, sr = 0, mx = 0, mr = 0; + void add(double g, double r) { se += (g - r) * (g - r); sr += r * r; mx = std::max(mx, std::fabs(g - r)); mr = std::max(mr, std::fabs(r)); } + double l2() const { return sr > 0 ? std::sqrt(se / sr) : std::sqrt(se); } +}; +} // namespace + +int main(int argc, char** argv) { + bool bench = false; + std::vector ntoks = {1, 3, 8}; + for (int i = 1; i < argc; ++i) { + std::string a = argv[i]; + if (a == "--bench") bench = true; + else if (a == "--ntok") ntoks = {std::atoi(argv[++i])}; + } + mtl::Context cx; + const int lib = cx.compile({"quant.metal", "units.metal", "gr.metal"}); + std::printf("device %s\n", cx.device_name().c_str()); + const int SETS = bench ? 48 : 1; + const bool q8 = std::getenv("GR_Q8") != nullptr; // the Q8_0 form of the HC matrices (gr_down_q8_*, gr_up_q8) + const int wty = q8 ? ref::Q8_0 : ref::BF16; + // GR_INJ_F32 (with GR_Q8): the inject rows as F32 (the Unsloth files), read by gr_down_q8f_* + const bool injf = q8 && std::getenv("GR_INJ_F32") != nullptr; + const size_t wd_bytes = (size_t)LR * NIN * 2, wi_bytes = (size_t)HC * NIN * 4, wu_bytes = (size_t)NIN * LR * 2; + const size_t set_bytes = wd_bytes + wi_bytes + wu_bytes + NIN * 4; + mtl::Buffer W = cx.alloc(set_bytes * SETS); + ref::Rng rng(3); + for (int s = 0; s < SETS; ++s) { + uint8_t* b = W.as() + s * set_bytes; + ref::random_blocks(ref::BF16, b, LR, NIN, 11 + s, 0.02f); + ref::random_blocks(ref::BF16, b + wd_bytes, HC, NIN, 22 + s, 0.02f); + ref::random_blocks(ref::BF16, b + wd_bytes + wi_bytes, NIN, LR, 33 + s, 0.1f); + float* wn = (float*)(b + wd_bytes + wi_bytes + wu_bytes); + for (int i = 0; i < NIN; ++i) wn[i] = 1.0f + 0.1f * rng.sym(); + if (q8) { + // GR_Q8: the three matrices as Q8_0 (quantized from the BF16 values), each at its BF16 offset (it fits) + const size_t offs[3] = {0, wd_bytes, wd_bytes + wi_bytes}; + const size_t ns[3] = {(size_t)LR * NIN, (size_t)HC * NIN, (size_t)NIN * LR}; + for (int m = 0; m < 3; ++m) { + std::vector f(ns[m]); + ref::dequant(ref::BF16, b + offs[m], f.data(), ns[m]); + if (m == 1 && injf) std::memcpy(b + offs[m], f.data(), 4 * ns[m]); + else ref::quantize_q8_0(f.data(), ns[m], b + offs[m]); + } + } + } + const int MAXT = 8; + // GR_DOWN=SG_KS selects gr_down's variant (default 8_8: 8 simdgroups split one row) + const std::string grd = std::getenv("GR_DOWN") ? std::getenv("GR_DOWN") : "8_8"; + int grd_sg = 8, grd_ks = 8; + std::sscanf(grd.c_str(), "%d_%d", &grd_sg, &grd_ks); + const int grd_rs = grd_sg / grd_ks; + mtl::Buffer R = cx.alloc(4 * MAXT * NIN), R0 = cx.alloc(4 * MAXT * NIN), bo = cx.alloc(4 * MAXT * N), + inj = cx.alloc(4 * MAXT * HC), xn = cx.alloc(4 * MAXT * NIN), lo = cx.alloc(4 * MAXT * LR), + injo = cx.alloc(4 * MAXT * HC), xp = cx.alloc(4 * (4 * MAXT * N + MAXT * N / 16)), + xr = cx.alloc(4 * (4 * MAXT * N + MAXT * N / 16)); + for (int i = 0; i < MAXT * NIN; ++i) R0.as()[i] = rng.sym() * 2.0f; + for (int i = 0; i < MAXT * N; ++i) bo.as()[i] = rng.sym(); + for (int i = 0; i < MAXT * HC; ++i) inj.as()[i] = rng.sym() * 3.0f; + mtl::Pipeline pprep = cx.pipeline(lib, "xprep"); + int fails = 0; + for (int nt : ntoks) { + mtl::Pipeline pn = cx.pipeline(lib, "gr_norm"), + pd = cx.pipeline(lib, std::string(injf ? "gr_down_q8f_" : q8 ? "gr_down_q8_" : "gr_down_") + grd, mtl::Constants().i(1, nt)), + pu = cx.pipeline(lib, q8 ? "gr_up_q8" : "gr_up", mtl::Constants().i(1, nt)); + for (int apply = 0; apply < 2; ++apply) { + GrArgs a{N, HC, LR, (uint32_t)nt, (uint32_t)apply, 1e-6f}; + std::memcpy(R.ptr, R0.ptr, R.bytes); + auto enc = [&](int set, std::vector& ds, int which) { + const size_t o = (size_t)set * set_bytes; + mtl::Dispatch d; + if (which & 1) { + d.p = &pn; + d.args = {mtl::Arg::B(R), mtl::Arg::B(bo), mtl::Arg::B(inj), mtl::Arg::B(W, o + wd_bytes + wi_bytes + wu_bytes), + mtl::Arg::B(xn), mtl::Arg::V(a)}; + d.grid[0] = HC; + d.grid[1] = nt; + d.tg[0] = 256; + ds.push_back(d); + } + if (which & 2) { + mtl::Dispatch e; + e.p = &pd; + e.args = {mtl::Arg::B(W, o), mtl::Arg::B(W, o + wd_bytes), mtl::Arg::B(xn), mtl::Arg::B(lo), + mtl::Arg::B(injo), mtl::Arg::V(a)}; + e.grid[0] = (LR + HC + grd_rs - 1) / grd_rs; // RS = SG / KS rows per threadgroup + e.tg[0] = 32 * grd_sg; + ds.push_back(e); + } + if (which & 4) { + mtl::Dispatch f; + f.p = &pu; + f.args = {mtl::Arg::B(W, o + wd_bytes + wi_bytes), mtl::Arg::B(lo), mtl::Arg::B(xn), mtl::Arg::B(xp), + mtl::Arg::V(a)}; + f.grid[0] = N / 16; + f.tg[0] = 256; + ds.push_back(f); + } + }; + if (!bench) { + std::vector ds; + enc(0, ds, 7); + cx.run(ds); + // reference + const uint8_t* b = W.as(); + std::vector wd((size_t)LR * NIN), wi((size_t)HC * NIN), wu((size_t)NIN * LR); + ref::dequant(wty, b, wd.data(), wd.size()); + ref::dequant(injf ? ref::F32 : wty, b + wd_bytes, wi.data(), wi.size()); + ref::dequant(wty, b + wd_bytes + wi_bytes, wu.data(), wu.size()); + const float* wn = (const float*)(b + wd_bytes + wi_bytes + wu_bytes); + Err eR, elo, einj, emix; + for (int t = 0; t < nt; ++t) { + std::vector r(NIN), x(NIN), l(LR); + for (int c = 0; c < HC; ++c) { + const double g = apply ? 2.0 / (1.0 + std::exp(-(double)inj.as()[t * HC + c] / HC)) : 0.0; + double ss = 0; + for (int d = 0; d < N; ++d) { + double v = R0.as()[t * NIN + c * N + d]; + if (apply) v += bo.as()[t * N + d] * g; + r[c * N + d] = v; + ss += v * v; + } + const double rs = 1.0 / std::sqrt(ss / N + 1e-6); + for (int d = 0; d < N; ++d) x[c * N + d] = r[c * N + d] * wn[c * N + d] * rs; + } + for (int i = 0; i < NIN; ++i) eR.add(R.as()[t * NIN + i], r[i]); + for (int k = 0; k < LR; ++k) { + double s = 0; + for (int i = 0; i < NIN; ++i) s += (double)wd[(size_t)k * NIN + i] * x[i]; + const double z = s / HC; + l[k] = z / (1.0 + std::exp(-z)); + elo.add(lo.as()[t * LR + k], l[k]); + } + for (int c = 0; c < HC; ++c) { + double s = 0; + for (int i = 0; i < NIN; ++i) s += (double)wi[(size_t)c * NIN + i] * x[i]; + einj.add(injo.as()[t * HC + c], s); + } + for (int d = 0; d < N; ++d) { + double m = 0; + for (int c = 0; c < HC; ++c) { + double s = 0; + // the up projection reads the GPU's lo, so the check isolates gr_up + for (int k = 0; k < LR; ++k) s += (double)wu[(size_t)(c * N + d) * LR + k] * lo.as()[t * LR + k]; + m += x[c * N + d] / (1.0 + std::exp(-s)); + } + emix.add(xp.as()[t * N + d], m / HC); + } + } + // the prepared planes must be bitwise xprep's of the raw plane + { + mtl::Dispatch d; + d.p = &pprep; + const uint32_t n = N, ntt = nt; + d.args = {mtl::Arg::B(xp), mtl::Arg::B(xr), mtl::Arg::V(n), mtl::Arg::V(ntt)}; + d.tg[0] = 256; + d.grid[0] = (N / 16 * nt + 255) / 256; + cx.run({d}); + } + const size_t elems = (size_t)4 * nt * N + (size_t)nt * N / 16; + const bool planes = std::memcmp(xp.ptr, xr.ptr, 4 * elems) == 0; + const bool ok = eR.l2() < 1e-6 && elo.l2() < 1e-5 && einj.l2() < 1e-5 && emix.l2() < 1e-5 && planes; + fails += !ok; + std::printf("parity ntok %d apply %d: R rel L2 %.2e, lo %.2e, inject %.2e, mixed %.2e, prepared planes " + "== xprep: %s %s\n", nt, apply, eR.l2(), elo.l2(), einj.l2(), emix.l2(), + planes ? "bitwise" : "NO", ok ? "PASS" : "FAIL"); + } else { + for (int which : {1, 2, 4, 7}) { + std::vector ds; + for (int r = 0; r < 96; ++r) enc(r % SETS, ds, which); + cx.warm(ds, 0.1); + std::vector ts; + for (int i = 0; i < 7; ++i) ts.push_back(cx.run(ds) / 96); + const double m = median(ts); + const double bytes = which == 1 ? 2.0 * nt * NIN * 4 + NIN * 4 + nt * NIN * 4 + : which == 2 ? wd_bytes + wi_bytes + : which == 4 ? wu_bytes + : wd_bytes + wi_bytes + wu_bytes; + std::printf("bench ntok %d apply %d %-8s %7.2f us %6.1f GB/s (%.2f MB)\n", nt, apply, + which == 1 ? "norm" : which == 2 ? "down" : which == 4 ? "up" : "all 3", m * 1e6, + bytes / m / 1e9, bytes / 1e6); + } + } + } + } + if (!bench) std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS"); + return fails ? 1 : 0; +} diff --git a/metal/tests/gridbar_bench.cpp b/metal/tests/gridbar_bench.cpp new file mode 100644 index 00000000..6420be4e --- /dev/null +++ b/metal/tests/gridbar_bench.cpp @@ -0,0 +1,66 @@ +// metal/tests/gridbar_bench.cpp - phases of a streaming read separated by dispatch boundaries vs by an in-kernel +// grid barrier (gridbar.metal), and whether a phase sees the previous phase's writes of the other threadgroups. +// gridbar_bench [MiB per phase] [phases] +#include "mtl_rt.h" + +#include +#include +#include +#include + +int main(int argc, char** argv) { + const double mib = argc > 1 ? std::atof(argv[1]) : 4.5; + const int phases = argc > 2 ? std::atoi(argv[2]) : 96; + mtl::Context cx; + const int lib = cx.compile({"gridbar.metal"}, std::getenv("GB_FENCE") ? "#define NO_GGML_COMMON 1\n#define GB_FENCE 1\n" + : "#define NO_GGML_COMMON 1\n"); + mtl::Pipeline pp = cx.pipeline(lib, "k_phases"), p1 = cx.pipeline(lib, "k_phase1"); + const uint32_t n = (uint32_t)(mib * 1048576 / 16); + mtl::Buffer src = cx.alloc((size_t)n * 16 * phases), out = cx.alloc(4u << 20), bar = cx.alloc(4), + flag = cx.alloc(4 * 64 * (size_t)phases), bad = cx.alloc(4); + for (size_t i = 0; i < src.bytes / 4; i += 1024) src.as()[i] = (uint32_t)i; + std::printf("device %s: %d phases of %.1f MiB\n", cx.device_name().c_str(), phases, mib); + // dispatch boundaries + for (uint32_t groups : {40u, 160u, 640u}) { + std::vector ds; + for (int p = 0; p < phases; ++p) { + mtl::Dispatch d; + d.p = &p1; + const uint32_t pu = p; + d.args = {mtl::Arg::B(src), mtl::Arg::B(out), mtl::Arg::V(n), mtl::Arg::V(pu)}; + d.grid[0] = groups; + d.tg[0] = 1024; + ds.push_back(d); + } + cx.warm(ds, 0.2); + std::vector t; + for (int i = 0; i < 5; ++i) t.push_back(cx.run(ds)); + std::sort(t.begin(), t.end()); + std::printf("dispatch per phase, %4u x 1024 threads: %7.2f us a phase %6.1f GB/s\n", groups, + t[2] / phases * 1e6, n * 16.0 * phases / t[2] / 1e9); + } + // grid barrier, at most one threadgroup a core + for (uint32_t groups : {10u, 20u, 40u}) { + mtl::Dispatch d; + d.p = &pp; + const uint32_t ph = phases; + d.args = {mtl::Arg::B(src), mtl::Arg::B(out), mtl::Arg::B(bar), mtl::Arg::B(flag), mtl::Arg::B(bad), + mtl::Arg::V(n), mtl::Arg::V(ph)}; + d.grid[0] = groups; + d.tg[0] = 1024; + std::vector t; + uint32_t badc = 0; + for (int i = 0; i < 6; ++i) { + bar.as()[0] = 0; + bad.as()[0] = 0; + for (size_t k = 0; k < flag.bytes / 4; ++k) flag.as()[k] = 0xFFFFFFFFu; + const double s = cx.run({d}); + if (i) t.push_back(s); + badc += bad.as()[0]; + } + std::sort(t.begin(), t.end()); + std::printf("grid barrier, %4u x 1024 threads: %7.2f us a phase %6.1f GB/s stale flags seen: %u\n", + groups, t[2] / phases * 1e6, n * 16.0 * phases / t[2] / 1e9, badc); + } + return 0; +} diff --git a/metal/tests/mm_bench.cpp b/metal/tests/mm_bench.cpp new file mode 100644 index 00000000..51f5e8f7 --- /dev/null +++ b/metal/tests/mm_bench.cpp @@ -0,0 +1,116 @@ +// metal/tests/mm_bench.cpp - matrix throughput (TFLOP/s) of MPP matmul2d and simdgroup_matrix, fp16/bf16/fp32 +// operands, fp32 results, on a square 4096^3 and on prompt-expert shapes; checks one product against the CPU. +// mm_bench +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { +struct MmArgs { int M, N, K; }; +double median(std::vector v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; } +} // namespace + +int main() { + mtl::Context cx; + std::printf("device %s, metal4 %d\n", cx.device_name().c_str(), cx.supports_metal4()); + const int lib = cx.compile({"mm_bench.metal"}, "#define NO_GGML_COMMON 1\n"); + const int MAX = 4096; + mtl::Buffer A = cx.alloc((size_t)MAX * MAX * 4), B = cx.alloc((size_t)MAX * MAX * 4), C = cx.alloc((size_t)MAX * MAX * 4); + ref::Rng r(1); + // fill as half and float views of the same random values (each kernel reads its own type) + auto fill = [&](int elem) { + for (size_t i = 0; i < (size_t)MAX * MAX; ++i) { + const float v = r.sym(); + if (elem == 4) { A.as()[i] = v; B.as()[i] = r.sym(); } + else if (elem == 2) { A.as()[i] = ref::f32_to_f16(v); B.as()[i] = ref::f32_to_f16(r.sym()); } + else { A.as()[i] = ref::f32_to_bf16(v); B.as()[i] = ref::f32_to_bf16(r.sym()); } + } + }; + struct K { std::string name; int elem; int tm, tn, sg; bool mpp; }; + const std::vector ks = { + {"mpp_mm_half_64_32_4", 2, 64, 32, 4, true}, {"mpp_mm_half_64_64_4", 2, 64, 64, 4, true}, + {"mpp_mm_half_128_64_4", 2, 128, 64, 4, true}, {"mpp_mm_half_32_64_4", 2, 32, 64, 4, true}, + {"mpp_mm_half_64_128_4", 2, 64, 128, 4, true}, {"mpp_mm_half_128_128_4", 2, 128, 128, 4, true}, + {"mpp_mm_half_16_64_2", 2, 16, 64, 2, true}, {"mpp_mm_bfloat_64_64_4", 3, 64, 64, 4, true}, + {"mpp_mm_bfloat_128_64_4", 3, 128, 64, 4, true}, {"mpp_mm_float_64_32_4", 4, 64, 32, 4, true}, + {"mpp_mm_float_64_64_4", 4, 64, 64, 4, true}, {"mpp_mm_float_128_64_4", 4, 128, 64, 4, true}, + {"sg_mm_half", 2, 64, 64, 4, false}, {"sg_mm_float", 4, 64, 64, 4, false}, + {"mpp_mm_half_64_16_2", 2, 64, 16, 2, true}, {"mpp_mm_half_64_16_4", 2, 64, 16, 4, true}, + {"mpp_mm_half_128_16_4", 2, 128, 16, 4, true}, {"mpp_mm_half_128_32_4", 2, 128, 32, 4, true}, + {"mpp_mm_half_64_32_2", 2, 64, 32, 2, true}, {"mpp_mm_half_32_16_2", 2, 32, 16, 2, true}, + {"mpp_mm_half_32_32_2", 2, 32, 32, 2, true}, {"mpp_mm_half_16_32_1", 2, 16, 32, 1, true}, + {"mpp_mm_half_16_16_1", 2, 16, 16, 1, true}, {"mpp_mm_half_128_48_4", 2, 128, 48, 4, true}, + {"mpp_mm_half_64_48_4", 2, 64, 48, 4, true}}; + struct Shape { const char* name; int M, N, K; }; + const std::vector shapes = {{"square 4096^3", 4096, 4096, 4096}, + {"expert gu 128 tok x 1280 x 2560", 128, 1280, 2560}, + {"expert down 128 tok x 2560 x 640", 128, 2560, 640}, + {"dense qkv 2048 tok x 10240 x 2560", 2048, 4096, 2560}, + {"expert gu 16 tok x 1280 x 2560", 16, 1280, 2560}, + {"expert gu^T 1280 x 48 tok x 2560", 1280, 48, 2560}, + {"expert gu^T 1280 x 16 tok x 2560", 1280, 16, 2560}, + {"many gu^T 12800 x 48 tok x 2560", 12800, 48, 2560}, + {"many gu 48 tok x 12800 x 2560", 48, 12800, 2560}}; + int filled = 0; + const char* only = std::getenv("MMB_ONLY"); // a substring of the kernel names to run + for (const K& k : ks) { + if (only && k.name.find(only) == std::string::npos) continue; + if (filled != k.elem) { fill(k.elem); filled = k.elem; } + mtl::Pipeline p = cx.pipeline(lib, k.name); + // correctness on a small product (M = tm*2, N = tn*2, K = 256) against the CPU + { + const int M = k.tm * 2, N = k.tn * 2, KK = 256; + MmArgs a{M, N, KK}; + mtl::Dispatch d; + d.p = &p; + d.args = {mtl::Arg::B(A), mtl::Arg::B(B), mtl::Arg::B(C), mtl::Arg::V(a)}; + d.grid[0] = N / k.tn; + d.grid[1] = M / k.tm; + d.tg[0] = 32 * k.sg; + cx.run({d}); + double se = 0, sr = 0; + for (int i = 0; i < M; ++i) + for (int j = 0; j < N; ++j) { + double ref = 0; + for (int q = 0; q < KK; ++q) { + auto val = [&](const mtl::Buffer& X, size_t idx) -> double { + if (k.elem == 4) return X.as()[idx]; + if (k.elem == 2) return ref::f16_to_f32(X.as()[idx]); + return ref::bf16_to_f32(X.as()[idx]); + }; + ref += val(A, (size_t)i * KK + q) * val(B, (size_t)j * KK + q); + } + const double e = C.as()[i * N + j] - ref; + se += e * e; + sr += ref * ref; + } + std::printf("%-26s check rel L2 %.2e\n", k.name.c_str(), std::sqrt(se / sr)); + } + for (const Shape& s : shapes) { + if (s.M % k.tm || s.N % k.tn) continue; + MmArgs a{s.M, s.N, s.K}; + mtl::Dispatch d; + d.p = &p; + d.args = {mtl::Arg::B(A), mtl::Arg::B(B), mtl::Arg::B(C), mtl::Arg::V(a)}; + d.grid[0] = s.N / k.tn; + d.grid[1] = s.M / k.tm; + d.tg[0] = 32 * k.sg; + const int reps = std::max(1, (int)(2e10 / (2.0 * s.M * s.N * s.K))); + std::vector ds(std::min(reps, 200), d); + cx.warm(ds, 0.2); + std::vector t; + for (int i = 0; i < 5; ++i) t.push_back(cx.run(ds) / ds.size()); + const double m = median(t); + std::printf("%-26s %-36s %8.1f us %6.2f TFLOP/s\n", k.name.c_str(), s.name, m * 1e6, + 2.0 * s.M * s.N * s.K / m / 1e12); + } + } + return 0; +} diff --git a/metal/tests/mma_parity.cpp b/metal/tests/mma_parity.cpp new file mode 100644 index 00000000..3181dbad --- /dev/null +++ b/metal/tests/mma_parity.cpp @@ -0,0 +1,178 @@ +// metal/tests/mma_parity.cpp - the simdgroup-matrix GEMV (mma.metal): parity vs double for every dense format, each +// token of a window bitwise a one-token call, and its speed on the packs' shapes against the per-lane GEMV. +// +// mma_parity parity +// mma_parity --bench speed, 1 / 3 / 8 tokens +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include +#include + +namespace { +struct MmaArgs { uint32_t n_in, n_out, row_bytes, x_stride, y_stride; }; +struct GemvArgs { uint32_t n_in, n_out, n_tok, row_bytes, x_stride, y_stride; }; +double median(std::vector v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; } +int xkind(int t) { + switch (t) { + case ref::Q2_0: return 1; + case ref::Q4_K: case ref::Q5_K: return 2; + case ref::Q6_K: case ref::Q3_K: return 3; + default: return 0; + } +} +} // namespace + +int main(int argc, char** argv) { + const bool bench = argc > 1 && std::string(argv[1]) == "--bench"; + mtl::Context cx; + const int lib = cx.compile({"quant.metal", "units.metal", "gemv.metal", "mma.metal"}); + std::printf("device %s\n", cx.device_name().c_str()); + const int MAXT = 8; + mtl::Pipeline pprep = cx.pipeline(lib, "xprep"); + const std::vector types = {ref::BF16, ref::Q8_0, ref::Q4_0, ref::Q5_0, ref::IQ4_NL, ref::IQ4_XS, ref::Q2_0, + ref::IQ3_S, ref::Q3_K, ref::Q4_K, ref::Q5_K, ref::Q6_K}; + if (!bench) { + int fails = 0; + for (int t : types) + for (int n_in : {2560, 640, 6144}) { + if (n_in % ref::block_elems(t) || (n_in == 640 && ref::block_elems(t) == 256)) continue; + const int n_out = 100; + const size_t rb = ref::row_bytes(t, n_in); + mtl::Buffer W = cx.alloc(rb * n_out), x = cx.alloc(4 * n_in * MAXT), y = cx.alloc(4 * n_out * MAXT), + y1 = cx.alloc(4 * n_out * MAXT); + ref::random_blocks(t, W.as(), n_out, n_in, 41 + t, 0.02f); + ref::Rng r(9); + for (int i = 0; i < n_in * MAXT; ++i) x.as()[i] = r.sym(); + std::vector wf((size_t)n_in * n_out); + ref::dequant(t, W.ptr, wf.data(), wf.size()); + for (int nt : {1, 3, 8}) { + mtl::Pipeline p = cx.pipeline(lib, "gemv_mma_" + std::to_string(t) + "_2", mtl::Constants().i(4, nt)); + MmaArgs a{(uint32_t)n_in, (uint32_t)n_out, (uint32_t)rb, (uint32_t)n_in, (uint32_t)n_out}; + mtl::Dispatch d; + d.p = &p; + d.args = {mtl::Arg::B(W), mtl::Arg::B(x), mtl::Arg::B(y), mtl::Arg::V(a)}; + d.grid[0] = (n_out + 15) / 16; + d.tg[0] = 64; + cx.run({d}); + double se = 0, sr = 0; + for (int tt = 0; tt < nt; ++tt) + for (int o = 0; o < n_out; ++o) { + double ref = 0; + for (int k = 0; k < n_in; ++k) ref += (double)wf[(size_t)o * n_in + k] * x.as()[tt * n_in + k]; + const double e = y.as()[tt * n_out + o] - ref; + se += e * e; + sr += ref * ref; + } + // the window property: token tt's column vs a one-token call on x shifted to row 0 + int notex = 0; + if (nt > 1) { + mtl::Pipeline p1 = cx.pipeline(lib, "gemv_mma_" + std::to_string(t) + "_2", mtl::Constants().i(4, 1)); + for (int tt = 0; tt < nt; ++tt) { + mtl::Dispatch d1 = d; + d1.p = &p1; + d1.args = {mtl::Arg::B(W), mtl::Arg::B(x, 4 * (size_t)tt * n_in), mtl::Arg::B(y1), mtl::Arg::V(a)}; + // rows past the window come from the following tokens' memory: padding only + cx.run({d1}); + notex += std::memcmp(y1.ptr, y.as() + tt * n_out, 4 * n_out) != 0; + } + } + const double rel = std::sqrt(se / sr); + const bool ok = rel < 1e-5 && notex == 0; + fails += !ok; + std::printf("mma parity %-7s n_in %5d ntok %d: rel L2 %.2e, window == one token: %s %s\n", + ref::type_name(t), n_in, nt, rel, nt == 1 ? "-" : notex ? "NO" : "bitwise", ok ? "PASS" : "FAIL"); + } + cx.free(W); + cx.free(x); + cx.free(y); + cx.free(y1); + } + std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS"); + return fails ? 1 : 0; + } + struct Shape { const char* name; int type, n_in, n_out; }; + const std::vector shapes = {{"gdn qkv", ref::IQ4_XS, 2560, 10240}, {"gdn qkv", ref::Q3_K, 2560, 10240}, + {"gdn qkv", ref::Q4_K, 2560, 10240}, {"gdn qkv", ref::Q6_K, 2560, 10240}, + {"gdn out", ref::Q5_K, 6144, 2560}, {"qsa q", ref::Q2_0, 2560, 12288}, + {"router", ref::BF16, 2560, 512}, {"lm head", ref::Q5_K, 2560, 248320}}; + std::printf("%-9s %-7s %5s | %9s %9s | %s\n", "shape", "type", "ntok", "lane us", "mma us", "mma GB/s (best SG)"); + for (const Shape& s : shapes) { + const size_t rb = ref::row_bytes(s.type, s.n_in), mb = rb * s.n_out; + const int copies = (int)std::max(4, std::min(64, (1ull << 30) / mb)); + mtl::Buffer W = cx.alloc(mb * copies), x = cx.alloc(4 * s.n_in * MAXT), y = cx.alloc(4 * (size_t)s.n_out * MAXT), + xp = cx.alloc(4 * (4 * s.n_in * MAXT + s.n_in / 16 * MAXT)); + { + std::vector tmp(mb); + ref::random_blocks(s.type, tmp.data(), s.n_out, s.n_in, 3, 0.02f); + for (int c = 0; c < copies; ++c) std::memcpy(W.as() + (size_t)c * mb, tmp.data(), mb); + } + ref::Rng r(5); + for (int i = 0; i < s.n_in * MAXT; ++i) x.as()[i] = r.sym(); + { + mtl::Dispatch d; + d.p = &pprep; + const uint32_t n = s.n_in, nt = MAXT; + d.args = {mtl::Arg::B(x), mtl::Arg::B(xp), mtl::Arg::V(n), mtl::Arg::V(nt)}; + d.tg[0] = 256; + d.grid[0] = (s.n_in / 16 * MAXT + 255) / 256; + cx.run({d}); + } + const size_t plane = (size_t)4 * s.n_in * MAXT; + for (int nt : {1, 3, 8}) { + auto time = [&](std::vector& ds) { + cx.warm(ds, 0.1); + std::vector t; + for (int i = 0; i < 5; ++i) t.push_back(cx.run(ds) / ds.size()); + return median(t); + }; + // the per-lane GEMV with its usual tile + const int L = s.n_in >= 6144 ? 32 : (s.n_out <= 640 || s.type == ref::Q2_0 || s.type == ref::BF16) ? 32 : 16; + const int S = s.n_in >= 6144 ? 8 : 4, K = s.n_in >= 6144 ? 2 : 1; + mtl::Pipeline pl = cx.pipeline(lib, "gemv_" + std::to_string(s.type) + "_" + std::to_string(L) + "_1_" + + std::to_string(S) + "_" + std::to_string(K), mtl::Constants().i(0, nt)); + GemvArgs ga{(uint32_t)s.n_in, (uint32_t)s.n_out, (uint32_t)nt, (uint32_t)rb, (uint32_t)s.n_in, (uint32_t)s.n_out}; + std::vector dl; + for (int k = 0; k < std::max(copies, 16); ++k) { + mtl::Dispatch d; + d.p = &pl; + d.args = {mtl::Arg::B(W, (size_t)(k % copies) * mb), mtl::Arg::B(xp, plane * xkind(s.type)), + mtl::Arg::B(xp, plane * 4), mtl::Arg::B(y), mtl::Arg::V(ga)}; + const int rpt = (S / K) * (32 / L); + d.grid[0] = (s.n_out + rpt - 1) / rpt; + d.tg[0] = S * 32; + dl.push_back(d); + } + const double tl = time(dl); + double best = 1e9; + int bsg = 0; + for (int sgn : {1, 2, 4}) { + mtl::Pipeline pm = cx.pipeline(lib, "gemv_mma_" + std::to_string(s.type) + "_" + std::to_string(sgn), + mtl::Constants().i(4, nt)); + MmaArgs ma{(uint32_t)s.n_in, (uint32_t)s.n_out, (uint32_t)rb, (uint32_t)s.n_in, (uint32_t)s.n_out}; + std::vector dm; + for (int k = 0; k < std::max(copies, 16); ++k) { + mtl::Dispatch d; + d.p = ± + d.args = {mtl::Arg::B(W, (size_t)(k % copies) * mb), mtl::Arg::B(x), mtl::Arg::B(y), mtl::Arg::V(ma)}; + d.grid[0] = (s.n_out + 8 * sgn - 1) / (8 * sgn); + d.tg[0] = 32 * sgn; + dm.push_back(d); + } + const double tm = time(dm); + if (tm < best) { best = tm; bsg = sgn; } + } + std::printf("%-9s %-7s %5d | %9.2f %9.2f | %6.1f (SG %d) lane %6.1f GB/s\n", s.name, ref::type_name(s.type), nt, + tl * 1e6, best * 1e6, mb / best / 1e9, bsg, mb / tl / 1e9); + } + cx.free(W); + cx.free(x); + cx.free(y); + cx.free(xp); + } + return 0; +} diff --git a/metal/tests/moe_mm_parity.cpp b/metal/tests/moe_mm_parity.cpp new file mode 100644 index 00000000..6f51f1e7 --- /dev/null +++ b/metal/tests/moe_mm_parity.cpp @@ -0,0 +1,241 @@ +// metal/tests/moe_mm_parity.cpp - the prompt-chunk routed experts (moe_mm.metal): plan, gate/up GEMM, down GEMM, +// combine, against a CPU reference that rounds the activations and weights to fp16 as the kernels do (the matrix +// units' operands) - and against the exact float reference for the size of that rounding; then the speed. +// +// moe_mm_parity [--gu Q2_0] [--dn Q2_0] [--T 256] [--tile 32,64,64,4] parity (64 experts) +// moe_mm_parity --bench [--gu ..] [--dn ..] [--T 2048] [--tile ..] per-layer time, 512 experts +#include "coop_probe.h" +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +constexpr int N_EMBD = 2560, N_FF = 640, TOPK = 10; +struct MmPlanArgs { uint32_t n_ent, topk, n_expert, tm, n_blocks; }; +struct MmArgs { uint64_t gate_off, up_off, down_off, gu_stride, d_stride; uint32_t gu_row, d_row, n_embd, n_ff; }; +double median(std::vector v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; } +int type_of(const std::string& s) { + for (int t : {ref::Q2_0, ref::IQ3_XXS, ref::IQ2_XXS, ref::IQ2_XS, ref::IQ2_S, ref::IQ3_S, ref::IQ4_NL, ref::IQ4_XS, ref::Q4_K, ref::Q5_K, ref::Q6_K, ref::Q8_0, ref::Q5_1}) + if (s == ref::type_name(t)) return t; + std::exit(2); +} +float h16(float v) { return ref::f16_to_f32(ref::f32_to_f16(v)); } +} // namespace + +int main(int argc, char** argv) { + int gu = ref::Q2_0, dn = ref::Q2_0, T = 256, TM = 16, TN = 64, TK = 16, SG = 2, DTN = -1, DTK = -1, DSG = -1; + bool bench = false, v2 = false, v3 = false, v4 = false, v5 = false; + int MS = 1; + for (int i = 1; i < argc; ++i) { + std::string a = argv[i]; + if (a == "--gu") gu = type_of(argv[++i]); + else if (a == "--dn") dn = type_of(argv[++i]); + else if (a == "--T") T = std::atoi(argv[++i]); + else if (a == "--tile") std::sscanf(argv[++i], "%d,%d,%d,%d", &TM, &TN, &TK, &SG); + else if (a == "--dtile") std::sscanf(argv[++i], "%d,%d,%d", &DTN, &DTK, &DSG); // the down kernel's TN,TK,SG + else if (a == "--bench") bench = true; + else if (a == "--v2") v2 = true; + else if (a == "--v3") v2 = v3 = true; // v2's gather + the register-operand GEMMs (TN per simdgroup) + else if (a == "--v4") { v2 = v3 = v4 = true; MS = std::atoi(argv[++i]); } // mm_gu4 with MS 16-row subtiles + else if (a == "--v5") { v2 = v3 = true; v5 = true; } // mm_gu5 (weight blocks staged in threadgroup memory) + } + if (bench && T == 256) T = 2048; + if (v4) TM = 16 * MS; // the plan's tile height; mm_gu4's name carries MS instead + mtl::Context cx; + const int lib = cx.compile({"quant.metal", "units.metal", "mma.metal", "moe_mm.metal"}); + const int NE = bench ? 512 : 64, LAYERS = bench ? 4 : 1; + const size_t gu_row = ref::row_bytes(gu, N_EMBD), d_row = ref::row_bytes(dn, N_FF); + const size_t up_off = (size_t)N_FF * gu_row, down_off = 2 * up_off, blob = down_off + (size_t)N_EMBD * d_row; + std::printf("device %s; %s/%s, T %d, %d experts, tile TM %d TN %d TK %d SG %d\n", cx.device_name().c_str(), + ref::type_name(gu), ref::type_name(dn), T, NE, TM, TN, TK, SG); + mtl::Buffer W = cx.alloc(blob * NE * LAYERS); + { + std::vector tmp(blob * 16); + for (int e = 0; e < 16; ++e) { + ref::random_blocks(gu, tmp.data() + e * blob, 2 * N_FF, N_EMBD, 100 + e, 0.02f); + ref::random_blocks(dn, tmp.data() + e * blob + down_off, N_EMBD, N_FF, 200 + e, 0.02f); + } + for (size_t e = 0; e < (size_t)NE * LAYERS; ++e) std::memcpy(W.as() + e * blob, tmp.data() + (e % 16) * blob, blob); + } + const int nent = T * TOPK, nblk = (nent + 1023) / 1024; + const int maxrows = nent + NE * TM; + mtl::Buffer x = cx.alloc(4 * (size_t)T * N_EMBD), ids = cx.alloc(4 * nent), w = cx.alloc(4 * nent), + bcnt = cx.alloc(4 * (size_t)nblk * NE), boff = cx.alloc(4 * (size_t)nblk * NE), eoff = cx.alloc(4 * NE), + tiles = cx.alloc(8 * (size_t)(maxrows / TM + 1)), meta = cx.alloc(64), stok = cx.alloc(4 * (size_t)maxrows), + sw = cx.alloc(4 * (size_t)maxrows), pos = cx.alloc(4 * nent), H = cx.alloc(4 * (size_t)maxrows * N_FF), + YE = cx.alloc(4 * (size_t)maxrows * N_EMBD), y = cx.alloc(4 * (size_t)T * N_EMBD), + XS = cx.alloc(2 * (size_t)maxrows * N_EMBD), HS = cx.alloc(2 * (size_t)maxrows * N_FF); + ref::Rng r(7); + for (size_t i = 0; i < (size_t)T * N_EMBD; ++i) x.as()[i] = r.sym(); + for (int t = 0; t < T; ++t) { + std::set used; + float s = 0; + for (int k = 0; k < TOPK; ++k) { + int e; + do e = (int)(r.next() % NE); while (used.count(e)); + used.insert(e); + ids.as()[t * TOPK + k] = e; + s += (w.as()[t * TOPK + k] = 0.2f + r.uni()); + } + for (int k = 0; k < TOPK; ++k) w.as()[t * TOPK + k] /= s; + } + mtl::Pipeline phist = cx.pipeline(lib, "mm_hist"), pscan = cx.pipeline(lib, "mm_scan"), pplace = cx.pipeline(lib, "mm_place"), + pclear = cx.pipeline(lib, "mm_clear"), pcomb = cx.pipeline(lib, "mm_combine"); + if (DTN < 0) { DTN = TN; DTK = TK; DSG = SG; } + if (dn == ref::IQ4_NL && DTK < 32) DTK = 32; + const std::string tl = std::to_string(TM) + "_" + std::to_string(TN) + "_" + std::to_string(TK) + "_" + std::to_string(SG); + const std::string dtl = std::to_string(TM) + "_" + std::to_string(DTN) + "_" + std::to_string(DTK) + "_" + std::to_string(DSG); + mtl::Constants probe; + probe.i(5, std::getenv("MM_PROBE") ? std::atoi(std::getenv("MM_PROBE")) : 0); + const bool k4 = coop_k4(cx); + if (v3) std::printf("right-input layout: %s\n", k4 ? "runs of 4 k" : "other (per-element decode)"); + mtl::Pipeline pgu = v5 ? cx.pipeline(lib, "mm_gu5_" + std::to_string(gu) + "_" + std::to_string(TN) + "_" + std::to_string(SG), + mtl::Constants().b(7, k4)) + : v4 ? cx.pipeline(lib, "mm_gu4_" + std::to_string(gu) + "_" + std::to_string(MS) + tl.substr(tl.find('_')), + mtl::Constants().b(7, k4).i(5, std::getenv("MM_PROBE") ? std::atoi(std::getenv("MM_PROBE")) : 0)) + : v3 ? cx.pipeline(lib, "mm_gu3_" + std::to_string(gu) + "_" + tl, mtl::Constants().b(7, k4).i(5, std::getenv("MM_PROBE") ? std::atoi(std::getenv("MM_PROBE")) : 0).b(23, std::getenv("QUANT_CTAB") != nullptr)) + : cx.pipeline(lib, (v2 ? "mm_gu2_" : "mm_gu_") + std::to_string(gu) + "_" + tl, probe), + pdn = v3 ? cx.pipeline(lib, "mm_down3_" + std::to_string(dn) + "_" + dtl, mtl::Constants().b(7, k4)) + : cx.pipeline(lib, (v2 ? "mm_down2_" : "mm_down_") + std::to_string(dn) + "_" + (v2 ? dtl : tl)), + pgat = cx.pipeline(lib, "mm_gather"); + MmPlanArgs pa{(uint32_t)nent, TOPK, (uint32_t)NE, (uint32_t)TM, (uint32_t)nblk}; + auto encode = [&](int layer, std::vector& ds, bool plan, bool gemm) { + if (plan) { + const uint32_t nclr = maxrows; + mtl::Dispatch c; c.p = &pclear; c.args = {mtl::Arg::B(stok), mtl::Arg::V(nclr)}; c.grid[0] = (maxrows + 255) / 256; c.tg[0] = 256; ds.push_back(c); + mtl::Dispatch h; h.p = &phist; h.args = {mtl::Arg::B(ids), mtl::Arg::B(bcnt), mtl::Arg::V(pa)}; h.grid[0] = nblk; h.tg[0] = 1024; ds.push_back(h); + meta.as()[2] = N_FF / TN; + mtl::Dispatch sc; sc.p = &pscan; sc.args = {mtl::Arg::B(bcnt), mtl::Arg::B(boff), mtl::Arg::B(eoff), mtl::Arg::B(tiles), mtl::Arg::B(meta), mtl::Arg::V(pa)}; sc.tg[0] = NE; ds.push_back(sc); + mtl::Dispatch pl; pl.p = &pplace; pl.args = {mtl::Arg::B(ids), mtl::Arg::B(w), mtl::Arg::B(boff), mtl::Arg::B(eoff), mtl::Arg::B(stok), mtl::Arg::B(sw), mtl::Arg::B(pos), mtl::Arg::V(pa)}; pl.grid[0] = nblk; pl.tg[0] = 1024; ds.push_back(pl); + } + if (gemm) { + MmArgs ma{(uint64_t)layer * NE * blob, (uint64_t)layer * NE * blob + up_off, (uint64_t)layer * NE * blob + down_off, + blob, blob, (uint32_t)gu_row, (uint32_t)d_row, N_EMBD, N_FF}; + if (v2) { + const uint32_t ne = N_EMBD; + mtl::Dispatch ga; ga.p = &pgat; ga.args = {mtl::Arg::B(x), mtl::Arg::B(stok), mtl::Arg::B(XS), mtl::Arg::V(ne)}; + ga.grid[0] = meta.as()[1]; ga.tg[0] = 256; ds.push_back(ga); + } + mtl::Dispatch g; g.p = &pgu; + if (v2) g.args = {mtl::Arg::B(W), mtl::Arg::B(XS), mtl::Arg::B(HS), mtl::Arg::B(tiles), mtl::Arg::V(ma)}; + else g.args = {mtl::Arg::B(W), mtl::Arg::B(x), mtl::Arg::B(H), mtl::Arg::B(stok), mtl::Arg::B(tiles), mtl::Arg::V(ma)}; + g.grid[0] = N_FF / (v3 ? TN * SG : TN); g.grid[1] = meta.as()[0]; g.tg[0] = 32 * SG; ds.push_back(g); + mtl::Dispatch d; d.p = &pdn; d.args = {mtl::Arg::B(W), mtl::Arg::B(v2 ? HS : H), mtl::Arg::B(YE), mtl::Arg::B(tiles), mtl::Arg::V(ma)}; + d.grid[0] = N_EMBD / (v3 ? DTN * DSG : v2 ? DTN : TN); d.grid[1] = meta.as()[0]; d.tg[0] = 32 * (v2 ? DSG : SG); ds.push_back(d); + const uint32_t ca[4] = {(uint32_t)T, N_EMBD, TOPK, 0}; + mtl::Dispatch cb; cb.p = &pcomb; cb.args = {mtl::Arg::B(YE), mtl::Arg::B(pos), mtl::Arg::B(sw), mtl::Arg::B(y), mtl::Arg::V(ca)}; + cb.grid[0] = (T * N_EMBD + 255) / 256; cb.tg[0] = 256; ds.push_back(cb); + } + }; + { + std::vector ds; + encode(0, ds, true, false); + cx.run(ds); // the plan first: the GEMMs' grid is the tile count + } + const uint32_t ntiles = meta.as()[0]; + std::printf("plan: %u tiles of %d, %u padded rows for %d entries\n", ntiles, TM, meta.as()[1], nent); + if (!bench) { + // the plan: every entry placed once, rows of an expert contiguous and in entry order + bool ok_plan = true; + std::vector seen(maxrows, 0); + for (int i = 0; i < nent; ++i) { + const int row = pos.as()[i]; + if (row < 0 || row >= (int)meta.as()[1] || stok.as()[row] != i / TOPK) ok_plan = false; + else seen[row]++; + } + for (int i = 0; i < maxrows; ++i) if (seen[i] > 1) ok_plan = false; + std::vector ds; + encode(0, ds, false, true); + cx.run(ds); + // reference: fp16 operands (x, weights, h), fp32+ accumulation; and the exact one + double se16 = 0, se = 0, sr = 0; + std::vector wg((size_t)N_FF * N_EMBD), wu(wg.size()), wd((size_t)N_EMBD * N_FF); + std::vector yr16((size_t)T * N_EMBD, 0.0), yr((size_t)T * N_EMBD, 0.0); + for (int e = 0; e < NE; ++e) { + const uint8_t* b = W.as() + e * blob; + bool any = false; + for (int i = 0; i < nent && !any; ++i) any = ids.as()[i] == e; + if (!any) continue; + ref::dequant(gu, b, wg.data(), wg.size()); + ref::dequant(gu, b + up_off, wu.data(), wu.size()); + ref::dequant(dn, b + down_off, wd.data(), wd.size()); + for (int i = 0; i < nent; ++i) { + if (ids.as()[i] != e) continue; + const int t = i / TOPK; + const float* xt = x.as() + (size_t)t * N_EMBD; + std::vector h16v(N_FF), hv(N_FF); + for (int f = 0; f < N_FF; ++f) { + double g = 0, u = 0, g16 = 0, u16 = 0; + for (int k = 0; k < N_EMBD; ++k) { + const float xk = xt[k], xh = h16(xk); + g += (double)wg[(size_t)f * N_EMBD + k] * xk; + u += (double)wu[(size_t)f * N_EMBD + k] * xk; + g16 += (double)h16(wg[(size_t)f * N_EMBD + k]) * xh; + u16 += (double)h16(wu[(size_t)f * N_EMBD + k]) * xh; + } + hv[f] = g / (1 + std::exp(-g)) * u; + h16v[f] = h16((float)(g16 / (1 + std::exp(-g16)) * u16)); + } + const double wt = w.as()[i]; + for (int d = 0; d < N_EMBD; ++d) { + double s = 0, s16 = 0; + for (int f = 0; f < N_FF; ++f) { + s += (double)wd[(size_t)d * N_FF + f] * hv[f]; + s16 += (double)h16(wd[(size_t)d * N_FF + f]) * h16v[f]; + } + yr[(size_t)t * N_EMBD + d] += wt * s; + yr16[(size_t)t * N_EMBD + d] += wt * s16; + } + } + } + for (size_t i = 0; i < yr.size(); ++i) { + const double g = y.as()[i]; + se16 += (g - yr16[i]) * (g - yr16[i]); + se += (g - yr[i]) * (g - yr[i]); + sr += yr[i] * yr[i]; + } + const double rel16 = std::sqrt(se16 / sr), rel = std::sqrt(se / sr); + const bool ok = ok_plan && rel16 < 2e-4; + std::printf("parity: plan %s; y vs fp16-operand reference rel L2 %.2e, vs exact float reference %.2e %s\n", + ok_plan ? "ok" : "WRONG", rel16, rel, ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; + } + // bench: the plan, the two GEMMs and the combine, LAYERS distinct weight sets rotated + double flops = 0; + { + const double rows = meta.as()[1]; + flops = 2.0 * nent * (2.0 * N_FF * N_EMBD + (double)N_EMBD * N_FF); + std::printf("useful GFLOP per layer %.1f (padded rows %.0f = %.2fx entries)\n", flops / 1e9, rows, rows / nent); + } + auto timeit = [&](bool plan, bool gemm, int part) { + std::vector ds; + for (int l = 0; l < 8; ++l) { + std::vector one; + encode(l % LAYERS, one, plan, gemm); + if (part >= 0 && gemm) { ds.push_back(one[part]); continue; } + for (auto& d : one) ds.push_back(d); + } + cx.warm(ds, 0.3); + std::vector t; + for (int i = 0; i < 5; ++i) t.push_back(cx.run(ds) / 8); + return median(t); + }; + const int o = v2 ? 1 : 0; + const double tp = timeit(true, false, -1), tg = timeit(false, true, o), td = timeit(false, true, o + 1), + tc = timeit(false, true, o + 2), ta = timeit(false, true, -1); + if (v2) std::printf("gather %.1f us\n", timeit(false, true, 0) * 1e6); + const double fgu = 2.0 * nent * 2.0 * N_FF * N_EMBD, fdn = 2.0 * nent * N_EMBD * N_FF; + std::printf("per layer: plan %.1f us, gate/up %.1f us (%.1f TFLOP/s useful), down %.1f us (%.1f TFLOP/s), combine %.1f us;" + " GEMMs + combine %.1f us = %.1f TFLOP/s; %.1f us per token per layer -> 48 layers: %.0f tok/s (experts only)\n", + tp * 1e6, tg * 1e6, fgu / tg / 1e12, td * 1e6, fdn / td / 1e12, tc * 1e6, ta * 1e6, flops / ta / 1e12, + (ta + tp) / T * 1e6, T / (48 * (ta + tp))); + return 0; +} diff --git a/metal/tests/pair_parity.cpp b/metal/tests/pair_parity.cpp new file mode 100644 index 00000000..1e40d19f --- /dev/null +++ b/metal/tests/pair_parity.cpp @@ -0,0 +1,118 @@ +// metal/tests/pair_parity.cpp - gemv_pair (the shared expert's gate + up + SwiGLU in one dispatch) vs double, for +// format pairs of the packs, 1 / 3 / 8 tokens; and the raw-activation Q2_0 GEMV (type 142) the down then uses. +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include + +namespace { +struct GemvArgs { uint32_t n_in, n_out, n_tok, row_bytes, x_stride, y_stride; }; +int xkind(int t) { + switch (t) { + case ref::Q2_0: return 1; + case ref::Q4_K: case ref::Q5_K: return 2; + case ref::Q6_K: case ref::Q3_K: return 3; + default: return 0; + } +} +} // namespace + +int main() { + mtl::Context cx; + const int lib = cx.compile({"quant.metal", "units.metal", "gemv.metal"}); + mtl::Pipeline pprep = cx.pipeline(lib, "xprep"); + const int NIN = 2560, NOUT = 640, MAXT = 8; + mtl::Buffer x = cx.alloc(4 * NIN * MAXT), xp = cx.alloc(4 * (4 * NIN * MAXT + NIN / 16 * MAXT)), h = cx.alloc(4 * NOUT * MAXT); + ref::Rng r(4); + for (int i = 0; i < NIN * MAXT; ++i) x.as()[i] = r.sym(); + { + mtl::Dispatch d; + d.p = &pprep; + const uint32_t n = NIN, nt = MAXT; + d.args = {mtl::Arg::B(x), mtl::Arg::B(xp), mtl::Arg::V(n), mtl::Arg::V(nt)}; + d.tg[0] = 256; + d.grid[0] = (NIN / 16 * MAXT + 255) / 256; + cx.run({d}); + } + const size_t plane = (size_t)4 * NIN * MAXT; + const std::vector> pairs = {{ref::Q2_0, ref::Q3_K}, {ref::Q3_K, ref::Q2_0}, {ref::IQ4_XS, ref::IQ3_S}, + {ref::Q4_K, ref::Q6_K}, {ref::Q5_K, ref::Q4_K}, {ref::Q6_K, ref::IQ3_S}, + {ref::Q2_0, ref::Q2_0}, {ref::IQ3_S, ref::Q4_K}}; + int fails = 0; + for (auto [fg, fu] : pairs) { + const size_t rg = ref::row_bytes(fg, NIN), ru = ref::row_bytes(fu, NIN); + mtl::Buffer Wg = cx.alloc(rg * NOUT), Wu = cx.alloc(ru * NOUT); + ref::random_blocks(fg, Wg.as(), NOUT, NIN, 7 + fg, 0.02f); + ref::random_blocks(fu, Wu.as(), NOUT, NIN, 9 + fu, 0.02f); + std::vector wg((size_t)NIN * NOUT), wu((size_t)NIN * NOUT); + ref::dequant(fg, Wg.ptr, wg.data(), wg.size()); + ref::dequant(fu, Wu.ptr, wu.data(), wu.size()); + for (int nt : {1, 3, 8}) { + mtl::Pipeline p = cx.pipeline(lib, "gemv_pair_" + std::to_string(fg) + "_" + std::to_string(fu), + mtl::Constants().i(0, nt)); + GemvArgs a{(uint32_t)NIN, (uint32_t)NOUT, (uint32_t)nt, (uint32_t)rg, (uint32_t)NIN, (uint32_t)NOUT}; + const uint32_t rbu = (uint32_t)ru; + mtl::Dispatch d; + d.p = &p; + d.args = {mtl::Arg::B(Wg), mtl::Arg::B(xp, plane * xkind(fg)), mtl::Arg::B(Wu), mtl::Arg::B(xp, plane * xkind(fu)), + mtl::Arg::B(xp, plane * 4), mtl::Arg::B(h), mtl::Arg::V(a), mtl::Arg::V(rbu)}; + d.grid[0] = NOUT / 4; + d.tg[0] = 128; + cx.run({d}); + double se = 0, sr = 0; + for (int t = 0; t < nt; ++t) + for (int o = 0; o < NOUT; ++o) { + double g = 0, u = 0; + for (int k = 0; k < NIN; ++k) { + g += (double)wg[(size_t)o * NIN + k] * x.as()[t * NIN + k]; + u += (double)wu[(size_t)o * NIN + k] * x.as()[t * NIN + k]; + } + const double ref = g / (1.0 + std::exp(-g)) * u; + const double e = h.as()[t * NOUT + o] - ref; + se += e * e; + sr += ref * ref; + } + const double rel = std::sqrt(se / sr); + fails += !(rel < 1e-5); + std::printf("pair %-7s + %-7s ntok %d: rel L2 %.2e %s\n", ref::type_name(fg), ref::type_name(fu), nt, rel, + rel < 1e-5 ? "PASS" : "FAIL"); + } + cx.free(Wg); + cx.free(Wu); + } + // the raw-activation Q2_0 GEMV + { + const int ni = 640, no = 2560; + const size_t rb = ref::row_bytes(ref::Q2_0, ni); + mtl::Buffer W = cx.alloc(rb * no), y = cx.alloc(4 * no * MAXT); + ref::random_blocks(ref::Q2_0, W.as(), no, ni, 3, 0.02f); + std::vector wf((size_t)ni * no); + ref::dequant(ref::Q2_0, W.ptr, wf.data(), wf.size()); + mtl::Pipeline p = cx.pipeline(lib, "gemv_142_8_1_4_1", mtl::Constants().i(0, 3)); + GemvArgs a{(uint32_t)ni, (uint32_t)no, 3, (uint32_t)rb, (uint32_t)ni, (uint32_t)no}; + mtl::Dispatch d; + d.p = &p; + d.args = {mtl::Arg::B(W), mtl::Arg::B(x), mtl::Arg::B(x), mtl::Arg::B(y), mtl::Arg::V(a)}; + d.grid[0] = no / 16; + d.tg[0] = 128; + cx.run({d}); + double se = 0, sr = 0; + for (int t = 0; t < 3; ++t) + for (int o = 0; o < no; ++o) { + double ref = 0; + for (int k = 0; k < ni; ++k) ref += (double)wf[(size_t)o * ni + k] * x.as()[t * ni + k]; + const double e = y.as()[t * no + o] - ref; + se += e * e; + sr += ref * ref; + } + const double rel = std::sqrt(se / sr); + fails += !(rel < 1e-5); + std::printf("Q2_0 raw-x GEMV 640 -> 2560, 3 tokens: rel L2 %.2e %s\n", rel, rel < 1e-5 ? "PASS" : "FAIL"); + } + std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS"); + return fails ? 1 : 0; +} diff --git a/metal/tests/prompt_chain.cpp b/metal/tests/prompt_chain.cpp new file mode 100644 index 00000000..876afeca --- /dev/null +++ b/metal/tests/prompt_chain.cpp @@ -0,0 +1,555 @@ +// metal/tests/prompt_chain.cpp - a whole PROMPT through every layer on the REAL weights of a GGUF (mmapped, wrapped +// no-copy), in chunks of C tokens (one command buffer a chunk): the GPU time of prompt processing with the prompt +// kernels of metal/. A timing of the real byte and FLOP stream, not a numerical check: the tokens are random ids +// (their real embedding rows start every hyper-connection stream), the parity programs check the kernels. +// +// prompt_chain [--prompt P,P,..] [--chunk C] [--breakdown] [--only CLASS] [--skip CLASS] +// +// Per layer and chunk (T tokens; activations fp32 rows, fp16 copies as the matrix units' operands): +// HC read gr_norm_h (fp16 xn) -> GEMM [w_down; w_inject] -> gr_epi_down -> gemm_hc_up (the GEMM with the +// mixing epilogue); PC_HC=plain: gr_norm -> act_f16 -> GEMM -> gr_epi_down -> GEMM -> gr_epi_up +// GDN GEMMs qkv / gate / alpha / beta -> gdn_pre (parallel) -> gdn_scan_r (the state scan) -> gdn_post +// (output norm and gate, fp16) -> GEMM out; PC_GDN=step: the decode step over the T tokens instead +// QSA GEMMs q / k / v / indexer q, k -> qsa_prep (T tokens) -> score + top-k (past the budget) -> attn -> +// merge -> GEMM out +// MoE GEMM router -> route_topk -> plan (hist, scan, clear, place) -> gather -> mm_gu2 -> mm_down2 -> +// combine; shared expert GEMMs gate, up -> swiglu_h -> GEMM down; GEMM shared gate; moe_out +// Every dense matrix is dequantized to fp16 (dq_f16) once a chunk, before its GEMM. After the last chunk: the final +// HC read and the LM head on the LAST row only (the decode kernels: gr_norm / gr_down / gr_up, GEMV, argmax). +// Left out: the PLE path and the MTP draft. +#include "coop_probe.h" +#include "gguf_lite.h" +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr int N = 2560, HC = 4, LR = 320, NFF = 640, TOPK = 10, NEXP = 512, NV = 248320, QB = 2051, QCHUNKS = 33; +struct GrArgs { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; }; +struct EpiArgs { uint32_t n_tok, n_embd, hc, hc_lr; }; +struct DqArgs { uint32_t n_in, n_out, row_bytes, perm; }; +struct GemmArgs { int M, N, K, pad; }; +struct GemvArgs { uint32_t n_in, n_out, n_tok, row_bytes, x_stride, y_stride; }; +struct GdnArgs { uint32_t h_k, h_v, channels, commit; float eps; uint32_t plane; }; +struct GdnPArgs { uint32_t n_tok, h_k, h_v, channels; float eps; uint32_t f32; }; +struct QsaArgs { uint32_t pos0, pos_base, max_cells, n_tok; float eps; }; +struct MmPlanArgs { uint32_t n_ent, topk, n_expert, tm, n_blocks; }; +struct MmArgs { uint64_t gate_off, up_off, down_off, gu_stride, d_stride; uint32_t gu_row, d_row, n_embd, n_ff; }; +struct ArgArgs { uint32_t n_vocab, parts; }; + +double median(std::vector v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; } +bool fmt_unit32(int t) { return t == ref::IQ4_XS || t == ref::IQ4_NL; } // mm_gu2 needs a K chunk >= 32 +int unit_of(int t) { return t == ref::Q2_0 || t == ref::IQ3_S || t == ref::BF16 ? 16 : 32; } + +} // namespace + +int main(int argc, char** argv) { + if (argc < 2) { std::fprintf(stderr, "usage: prompt_chain [--prompt P,..] [--chunk C] [--breakdown]\n"); return 2; } + std::vector prompts = {1024, 4096, 32768}; + int C = 2048, reps = 2; + bool breakdown = false; + std::string only, skip; + for (int i = 2; i < argc; ++i) { + std::string a = argv[i]; + if (a == "--prompt") { + prompts.clear(); + for (char* s = argv[++i]; *s;) { + prompts.push_back((int)std::strtol(s, &s, 10)); + if (*s == ',') ++s; + } + } else if (a == "--chunk") C = std::atoi(argv[++i]); + else if (a == "--reps") reps = std::atoi(argv[++i]); + else if (a == "--breakdown") breakdown = true; + else if (a == "--only") only = argv[++i]; + else if (a == "--skip") skip = argv[++i]; + } + const int PMAX = *std::max_element(prompts.begin(), prompts.end()); + gguf::File f; + std::string err; + if (!f.open(argv[1], err)) { std::fprintf(stderr, "%s\n", err.c_str()); return 2; } + mtl::Context cx; + std::printf("device %s; %s: %zu tensors, %.1f GB; chunk %d\n", cx.device_name().c_str(), argv[1], f.tensors.size(), + f.file_bytes / 1e9, C); + { + const double t0 = mtl::now_s(); + madvise(f.map, f.map_bytes, MADV_WILLNEED); + volatile uint64_t s = 0; + for (size_t o = 0; o < f.file_bytes; o += 16384) s += ((const uint8_t*)f.map)[o]; + std::printf("file touched in %.1f s\n", mtl::now_s() - t0); + } + mtl::Buffer W = cx.wrap(f.map, f.map_bytes); + auto T_ = [&](const std::string& name) -> const gguf::Tensor& { + const gguf::Tensor* t = f.find(name); + if (!t) { std::fprintf(stderr, "missing tensor %s\n", name.c_str()); std::exit(2); } + return *t; + }; + const double tc0 = mtl::now_s(); + const int lib = cx.compile({"quant.metal", "units.metal", "mma.metal", "dense_mm.metal", "moe_mm.metal", "gr.metal", + "gemv.metal", "prompt.metal"}); + const int lgdn = cx.compile({"gdn.metal", "gdn_prompt.metal"}, "#define NO_GGML_COMMON 1\n"); + const int lqsa = cx.compile({"qsa.metal", "qsa_prompt.metal"}, "#define NO_GGML_COMMON 1\n"); + const int lsmp = cx.compile({"sample.metal"}, "#define NO_GGML_COMMON 1\n"); + std::printf("kernels compiled in %.1f s\n", mtl::now_s() - tc0); + std::map pcache; + const bool k4 = coop_k4(cx); + std::printf("matmul2d right-input layout: %s\n", k4 ? "runs of 4 k (per-lane run decoders)" : "other (per-element decode)"); + auto P = [&](int l, const std::string& fn, const mtl::Constants& c = {}, const std::string& key = "") -> const mtl::Pipeline* { + const std::string k = key.empty() ? fn : key; + auto it = pcache.find(k); + if (it == pcache.end()) it = pcache.emplace(k, cx.pipeline(l, fn, c)).first; + return &it->second; + }; + + // ---- buffers (MT = the chunk's rows) + const size_t MT = C; + const int MAXC = (PMAX + 64 + 63) / 64 * 64, MB = MAXC / 4 + 2; + const int TM = 16; + const int maxrows = (int)MT * TOPK + NEXP * TM, nblk_max = ((int)MT * TOPK + 1023) / 1024; + auto F32 = [&](size_t n) { return cx.alloc(4 * n); }; + auto F16 = [&](size_t n) { return cx.alloc(2 * n); }; + mtl::Buffer R = F32(MT * HC * N), bo = F32(MT * N), inj[2] = {F32(MT * HC), F32(MT * HC)}, xn = F32(MT * HC * N), + xnh = F16(MT * HC * N), V = F32(MT * (LR + HC)), loh = F16(MT * LR), G = F32(MT * HC * N), mixed = F32(MT * N), + mixh = F16(MT * N); + mtl::Buffer qkv = F32(MT * 10240), z = F32(MT * 6144), al = F32(MT * 48), be = F32(MT * 48), yg = F32(MT * 6144), + ygh = F16(MT * 6144), gqn = F32(MT * 16 * 128), gkn = F32(MT * 16 * 128), gvc = F32(MT * 6144), + ggb = F32(MT * 48 * 2), gkq = F32(MT * 16), go = F32(MT * 6144); + const char* hc_env = std::getenv("PC_HC"); + const std::string hc_mode = hc_env ? hc_env : "fused"; // fused | plain + const char* qsa_env = std::getenv("PC_QSA"); + // flash (one pass on the matrix units, no partials) | mm (split-K on the matrix units + merge) | v1 (qsa_attn, + // fp32 + merge). The M5: flash (= mm + merge or better); the M4: v1 attention (faster there) with the GEMM score. + const std::string qsa_mode = qsa_env ? qsa_env : (k4 ? "flash" : "v1"); + // the expert GEMMs: "v2" (threadgroup-staged weights) or "v3:TM,TN,TK,SG" (register operands, TN rows a simdgroup) + const char* gu_env = std::getenv("PC_GU"); + const char* dn_env = std::getenv("PC_DN"); + // defaults (M5 Max, moe_mm_parity --v3 --bench): gate/up 16,32,32,4 (every format), down 16,64,32,2 + // without the M5's right-input layout (the M4) the per-element v3 decode is slower than v2: v2 there + const std::string gu_mode = gu_env ? gu_env : (k4 ? "v3:auto" : "v2"), dn_mode = dn_env ? dn_env : (k4 ? "v3:16,64,32,2" : "v2"); + auto v3_tile = [](const std::string& m, int* t) { std::sscanf(m.c_str() + 3, "%d,%d,%d,%d", &t[0], &t[1], &t[2], &t[3]); }; + int gu3[4] = {16, 64, 16, 2}, dn3[4] = {16, 64, 16, 2}; + if (gu_mode.rfind("v3:", 0) == 0 && gu_mode != "v3:auto") v3_tile(gu_mode, gu3); + else if (gu_mode == "v3:auto") { gu3[0] = 16; gu3[1] = 32; gu3[2] = 32; gu3[3] = 4; } + auto tl3 = [](const int* t) { return std::to_string(t[0]) + "_" + std::to_string(t[1]) + "_" + std::to_string(t[2]) + "_" + std::to_string(t[3]); }; + auto gu3_for = [&](int type) -> std::string { + (void)type; // one tile for every format since the paired-run decoders (W8) + return tl3(gu3); + }; + if (dn_mode.rfind("v3:", 0) == 0) v3_tile(dn_mode, dn3); + const bool gu_v3 = gu_mode.rfind("v3:", 0) == 0, dn_v3 = dn_mode.rfind("v3:", 0) == 0; + const char* gdn_env = std::getenv("PC_GDN"); + const std::string gdn_mode = gdn_env ? gdn_env : "scanr_4"; + mtl::Buffer qfull = F32(MT * 12288), kcur = F32(MT * 512), vcur = F32(MT * 512), iqr = F32(MT * 512), ikr = F32(MT * 128), + qcur = F32(MT * 24 * 256), qcurh = F16(MT * 24 * 256), qidx = F32(MT * 4 * 128), scores = F32(MT * MB), qids = cx.alloc(4 * MT * QB), + part = F32(MT * QCHUNKS * 24 * 258), XQ = F32(4 * MT * 6144 + MT * 384), xqh = F16(MT * 6144); + mtl::Buffer logits = F32(MT * NEXP), ids = cx.alloc(4 * MT * TOPK), wts = F32(MT * TOPK), + bcnt = cx.alloc(4 * (size_t)nblk_max * NEXP), boff = cx.alloc(4 * (size_t)nblk_max * NEXP), eoff = cx.alloc(4 * NEXP), + tiles = cx.alloc(8 * (size_t)(maxrows / TM + 1)), meta = cx.alloc(64), stok = cx.alloc(4 * (size_t)maxrows), + sw = F32(maxrows), pos = cx.alloc(4 * MT * TOPK), XS = F16((size_t)maxrows * N), HS = F16((size_t)maxrows * NFF), + YE = F32((size_t)maxrows * N), yr = F32(MT * N), gsh = F32(MT * NFF), ush = F32(MT * NFF), hh = F16(MT * NFF), + ys = F32(MT * N), sgv = F32(MT); + // fp16 weight scratch, one per role + mtl::Buffer WD = F16((size_t)(LR + HC) * HC * N), WU = F16((size_t)HC * N * LR), Wqkv = F16((size_t)10240 * N), + Wz = F16((size_t)6144 * N), Wal = F16((size_t)48 * N), Wbe = F16((size_t)48 * N), Wout = F16((size_t)N * 6144), + Wq = F16((size_t)12288 * N), Wk = F16((size_t)512 * N), Wv = F16((size_t)512 * N), Wiq = F16((size_t)512 * N), + Wik = F16((size_t)128 * N), Wr = F16((size_t)NEXP * N), Wsg = F16((size_t)N), Wshg = F16((size_t)NFF * N), + Wshu = F16((size_t)NFF * N), Wshd = F16((size_t)N * NFF); + // the last row's final read and head + mtl::Buffer xn1 = F32(HC * N), lo1 = F32(LR), inj1 = F32(HC), X1 = F32(4 * N + N / 16), lm = F32(NV), apv = F32(120), + api = cx.alloc(4 * 120), tokout = cx.alloc(16); + mtl::Buffer cs = cx.alloc(8 * (size_t)(MAXC + 16) * 32); + for (int p = 0; p < MAXC + 16; ++p) + for (int i = 0; i < 32; ++i) { + const double th = (double)p * std::pow(1e7, -2.0 * i / 64.0); + cs.as()[(p * 32 + i) * 2] = (float)std::cos(th); + cs.as()[(p * 32 + i) * 2 + 1] = (float)std::sin(th); + } + std::vector gst, ghist[2], kq, vq, ksc, vsc, tail, dead, pooled; + for (int l = 0; l < 48; ++l) { + if (l % 4 != 3) { + gst.push_back(F32(128 * 48 * 128)); + ghist[0].push_back(F32(10240 * 3)); + ghist[1].push_back(F32(10240 * 3)); + } else { + kq.push_back(cx.alloc((size_t)MAXC * 2 * 256)); + vq.push_back(cx.alloc((size_t)MAXC * 2 * 256)); + ksc.push_back(cx.alloc(2 * (size_t)MAXC * 2 * 4)); + vsc.push_back(cx.alloc(2 * (size_t)MAXC * 2 * 4)); + tail.push_back(F32(4 * 128)); + dead.push_back(F32(128)); + pooled.push_back(F32((size_t)MB * 128)); + } + } + std::vector gpar(36, 0); + // embeddings of random token ids (the real rows) + std::vector E(MT * N); + { + const gguf::Tensor& te = T_("token_embd.weight"); + const size_t rb = ref::row_bytes(te.type, N); + ref::Rng r(17); + for (size_t t = 0; t < MT; ++t) { + const uint64_t id = r.next() % 200000; + ref::dequant(te.type, (const uint8_t*)f.map + te.offset + id * rb, E.data() + t * N, N); + } + } + meta.as()[2] = gu_v3 ? NFF / (gu3[1] * gu3[3]) : NFF / 64; + meta.as()[5] = dn_v3 ? N / (dn3[1] * dn3[3]) : N / 64; + + // ---- the chunk's dispatches + std::vector ds; + std::vector cls; + auto push = [&](const mtl::Dispatch& d, const std::string& c) { + if (!only.empty() && c != only) return; + if (!skip.empty() && c == skip) return; + ds.push_back(d); + cls.push_back(c); + }; + auto D = [&](const mtl::Pipeline* p, std::vector a, uint32_t gx, uint32_t gy, uint32_t tg, const std::string& c, + uint32_t gz = 1) { + mtl::Dispatch d; + d.p = p; + d.args = std::move(a); + d.grid[0] = gx; + d.grid[1] = gy; + d.grid[2] = gz; + d.tg[0] = tg; + push(d, c); + }; + const char* gk_env = std::getenv("PC_GEMM"); + auto gemm = [&](const mtl::Buffer& A, const mtl::Buffer& B, const mtl::Buffer& Y, int M, int Nn, int K, const std::string& c) { + int tm = 64, tn = Nn <= 64 ? 32 : 64; + if (gk_env && Nn > 64) std::sscanf(gk_env, "%d,%d", &tm, &tn); + const std::string fn = "gemm_f16_" + std::to_string(tm) + "_" + std::to_string(tn) + "_4"; + GemmArgs g{M, Nn, K, 0}; + D(P(lib, fn), {mtl::Arg::B(A), mtl::Arg::B(B), mtl::Arg::B(Y), mtl::Arg::V(g)}, (Nn + tn - 1) / tn, (M + tm - 1) / tm, + 128, c); + }; + auto dq = [&](const gguf::Tensor& t, const mtl::Buffer& out, size_t out_off = 0, uint32_t perm = 0) { + const int n_in = (int)t.shape[0], n_out = t.shape.size() > 1 ? (int)t.shape[1] : 1; + DqArgs a{(uint32_t)n_in, (uint32_t)n_out, (uint32_t)ref::row_bytes(t.type, n_in), perm}; + D(P(lib, "dq_f16_" + std::to_string(t.type)), {mtl::Arg::B(W, t.offset), mtl::Arg::B(out, out_off), mtl::Arg::V(a)}, + (n_in / unit_of(t.type) + 63) / 64, n_out, 64, "dq"); + }; + auto act16 = [&](const mtl::Buffer& x, const mtl::Buffer& xh, size_t n, const std::string& c) { + const uint32_t nn = (uint32_t)n; + D(P(lib, "act_f16"), {mtl::Arg::B(x), mtl::Arg::B(xh), mtl::Arg::V(nn)}, (nn + 255) / 256, 1, 256, c); + }; + int cur_inj = 0; + // the HC read of T rows: mixed (fp32) and mixh (fp16) + auto hc_read = [&](const std::string& pre, bool apply, int T) { + const gguf::Tensor &tn = T_(pre + "_norm.weight"), &tdn = T_(pre + "_down.weight"), &tin = T_(pre + "_inject.weight"), + &tup = T_(pre + "_up.weight"); + dq(tdn, WD); + dq(tin, WD, (size_t)2 * LR * HC * N); + GrArgs a{N, HC, LR, (uint32_t)T, apply ? 1u : 0u, 1e-6f}; + EpiArgs ea{(uint32_t)T, N, HC, LR}; + if (hc_mode == "fused") { + // fp16 xn only; the up GEMM's epilogue mixes (w_up rows interleaved by the dequantization) + dq(tup, WU, 0, HC); + D(P(lib, "gr_norm_h"), {mtl::Arg::B(R), mtl::Arg::B(bo), mtl::Arg::B(inj[cur_inj]), mtl::Arg::B(W, tn.offset), + mtl::Arg::B(xnh), mtl::Arg::V(a)}, HC, T, 256, "hc"); + gemm(xnh, WD, V, T, LR + HC, HC * N, "hc gemm"); + D(P(lib, "gr_epi_down"), {mtl::Arg::B(V), mtl::Arg::B(loh), mtl::Arg::B(inj[1 - cur_inj]), mtl::Arg::V(ea)}, + (T * (LR + HC) + 255) / 256, 1, 256, "hc"); + GemmArgs g{T, HC * N, LR, 0}; + D(P(lib, "gemm_hc_up_64_64_4"), {mtl::Arg::B(loh), mtl::Arg::B(WU), mtl::Arg::B(xnh), mtl::Arg::B(mixed), + mtl::Arg::B(mixh), mtl::Arg::V(g), mtl::Arg::V(ea)}, + HC * N / 64, (T + 63) / 64, 128, "hc gemm"); + cur_inj = 1 - cur_inj; + return; + } + dq(tup, WU); + D(P(lib, "gr_norm"), {mtl::Arg::B(R), mtl::Arg::B(bo), mtl::Arg::B(inj[cur_inj]), mtl::Arg::B(W, tn.offset), + mtl::Arg::B(xn), mtl::Arg::V(a)}, HC, T, 256, "hc"); + act16(xn, xnh, (size_t)T * HC * N, "hc"); + gemm(xnh, WD, V, T, LR + HC, HC * N, "hc gemm"); + D(P(lib, "gr_epi_down"), {mtl::Arg::B(V), mtl::Arg::B(loh), mtl::Arg::B(inj[1 - cur_inj]), mtl::Arg::V(ea)}, + (T * (LR + HC) + 255) / 256, 1, 256, "hc"); + gemm(loh, WU, G, T, HC * N, LR, "hc gemm"); + D(P(lib, "gr_epi_up"), {mtl::Arg::B(G), mtl::Arg::B(xn), mtl::Arg::B(mixed), mtl::Arg::B(mixh), mtl::Arg::V(ea)}, + (T * N + 255) / 256, 1, 256, "hc"); + cur_inj = 1 - cur_inj; + }; + auto build = [&](int pos0, int T, bool head) { + ds.clear(); + cls.clear(); + int gi = 0, qi = 0; + for (int l = 0; l < 48; ++l) { + const std::string b = "blk." + std::to_string(l) + "."; + hc_read(b + "hc_attn", l > 0, T); + if (l % 4 != 3) { + const gguf::Tensor &tq = T_(b + "attn_qkv.weight"), &tz = T_(b + "attn_gate.weight"), + &ta = T_(b + "ssm_alpha.weight"), &tb = T_(b + "ssm_beta.weight"), &to = T_(b + "ssm_out.weight"); + dq(tq, Wqkv); + dq(tz, Wz); + dq(ta, Wal); + dq(tb, Wbe); + dq(to, Wout); + gemm(mixh, Wqkv, qkv, T, 10240, N, "gdn proj"); + gemm(mixh, Wz, z, T, 6144, N, "gdn proj"); + gemm(mixh, Wal, al, T, 48, N, "gdn proj"); + gemm(mixh, Wbe, be, T, 48, N, "gdn proj"); + GdnArgs a{16, 48, 10240, 1, 1e-6f, 0}; + const int par = gpar[gi]; + if (gdn_mode != "step") { + GdnPArgs ga{(uint32_t)T, 16, 48, 10240, 1e-6f, 0}; + D(P(lgdn, "gdn_pre"), + {mtl::Arg::B(qkv), mtl::Arg::B(ghist[par][gi]), mtl::Arg::B(W, T_(b + "ssm_conv1d.weight").offset), + mtl::Arg::B(al), mtl::Arg::B(be), mtl::Arg::B(W, T_(b + "ssm_dt.bias").offset), + mtl::Arg::B(W, T_(b + "ssm_a").offset), mtl::Arg::B(gqn), mtl::Arg::B(gkn), mtl::Arg::B(gvc), mtl::Arg::B(ggb), + mtl::Arg::B(gkq), mtl::Arg::B(ghist[1 - par][gi]), mtl::Arg::V(ga)}, + 16 + 24, T, 256, "gdn scan"); + const int ib = gdn_mode == "scan_v" ? 8 : std::atoi(gdn_mode.c_str() + 6); + D(P(lgdn, "gdn_" + gdn_mode, gdn_mode == "scan_v" ? mtl::Constants() : mtl::Constants().i(6, 0)), + {mtl::Arg::B(gst[gi]), mtl::Arg::B(gqn), mtl::Arg::B(gkn), mtl::Arg::B(gvc), mtl::Arg::B(ggb), mtl::Arg::B(gkq), + mtl::Arg::B(go), mtl::Arg::V(ga)}, + 48 * 4, 1, 32 * ib, "gdn scan"); + D(P(lgdn, "gdn_post"), {mtl::Arg::B(go), mtl::Arg::B(z), mtl::Arg::B(W, T_(b + "ssm_norm.weight").offset), + mtl::Arg::B(ygh), mtl::Arg::B(yg), mtl::Arg::V(ga)}, + 48, T, 128, "gdn scan"); + gemm(ygh, Wout, bo, T, N, 6144, "gdn proj"); + ++gi; + goto moe; + } + D(P(lgdn, "gdn_step", mtl::Constants().i(2, T), "gdn_step#" + std::to_string(T)), + {mtl::Arg::B(gst[gi]), mtl::Arg::B(ghist[par][gi]), mtl::Arg::B(qkv), mtl::Arg::B(al), mtl::Arg::B(be), + mtl::Arg::B(z), mtl::Arg::B(W, T_(b + "ssm_conv1d.weight").offset), mtl::Arg::B(W, T_(b + "ssm_dt.bias").offset), + mtl::Arg::B(W, T_(b + "ssm_a").offset), mtl::Arg::B(W, T_(b + "ssm_norm.weight").offset), mtl::Arg::B(yg), + mtl::Arg::V(a), mtl::Arg::B(ghist[1 - par][gi])}, + 48, 1, 512, "gdn scan"); + act16(yg, ygh, (size_t)T * 6144, "gdn proj"); + gemm(ygh, Wout, bo, T, N, 6144, "gdn proj"); + ++gi; + } else { + const gguf::Tensor &tq = T_(b + "attn_q.weight"), &tk = T_(b + "attn_k.weight"), &tv = T_(b + "attn_v.weight"), + &tiq = T_(b + "indexer.q_proj.weight"), &tik = T_(b + "indexer.k_proj.weight"), + &to = T_(b + "attn_output.weight"); + dq(tq, Wq); + dq(tk, Wk); + dq(tv, Wv); + dq(tiq, Wiq); + dq(tik, Wik); + dq(to, Wout); + gemm(mixh, Wq, qfull, T, 12288, N, "qsa proj"); + gemm(mixh, Wk, kcur, T, 512, N, "qsa proj"); + gemm(mixh, Wv, vcur, T, 512, N, "qsa proj"); + gemm(mixh, Wiq, iqr, T, 512, N, "qsa proj"); + gemm(mixh, Wik, ikr, T, 128, N, "qsa proj"); + QsaArgs a{(uint32_t)pos0, 0, (uint32_t)MAXC, (uint32_t)T, 1e-6f}; + D(P(lqsa, "qsa_prep"), + {mtl::Arg::B(qfull), mtl::Arg::B(kcur), mtl::Arg::B(vcur), mtl::Arg::B(iqr), mtl::Arg::B(ikr), + mtl::Arg::B(W, T_(b + "attn_q_norm.weight").offset), mtl::Arg::B(W, T_(b + "attn_k_norm.weight").offset), + mtl::Arg::B(W, T_(b + "indexer.q_norm.weight").offset), mtl::Arg::B(W, T_(b + "indexer.k_norm.weight").offset), + mtl::Arg::B(cs), mtl::Arg::B(qcur), mtl::Arg::B(qidx), mtl::Arg::B(kq[qi]), mtl::Arg::B(vq[qi]), + mtl::Arg::B(ksc[qi]), mtl::Arg::B(vsc[qi]), mtl::Arg::B(tail[qi]), mtl::Arg::B(dead[qi]), + mtl::Arg::B(pooled[qi]), mtl::Arg::V(a)}, + 33, T, 256, "qsa prep"); + if (pos0 + T > QB) { // some token's context is past the budget: select + if (!std::getenv("PC_QSA_SCORE")) // the GEMM score unless PC_QSA_SCORE (= the scalar qsa_score) + D(P(lqsa, "qsa_score_mm"), {mtl::Arg::B(qidx), mtl::Arg::B(pooled[qi]), mtl::Arg::B(dead[qi]), + mtl::Arg::B(scores), mtl::Arg::V(a)}, + ((pos0 + T) / 4 + 1 + 63) / 64, (T + 15) / 16, 128, "qsa score"); + else + D(P(lqsa, "qsa_score"), {mtl::Arg::B(qidx), mtl::Arg::B(pooled[qi]), mtl::Arg::B(dead[qi]), mtl::Arg::B(scores), + mtl::Arg::V(a)}, + ((pos0 + T) / 4 + 1 + 7) / 8, T, 256, "qsa score"); + D(P(lqsa, "qsa_topk"), {mtl::Arg::B(scores), mtl::Arg::B(qids), mtl::Arg::V(a)}, T, 1, 1024, "qsa sel"); + } else { + // within the budget the selection is the identity: qsa_topk only writes 0..n_kv-1 + D(P(lqsa, "qsa_topk"), {mtl::Arg::B(scores), mtl::Arg::B(qids), mtl::Arg::V(a)}, T, 1, 1024, "qsa sel"); + } + if (qsa_mode == "flash") { + const uint32_t nq = (uint32_t)T * 24 * 256; + D(P(lqsa, "qsa_q_f16"), {mtl::Arg::B(qcur), mtl::Arg::B(qcurh), mtl::Arg::V(nq)}, (nq + 255) / 256, 1, 256, "qsa attn"); + D(P(lqsa, "qsa_flash", mtl::Constants().b(7, k4)), + {mtl::Arg::B(qcurh), mtl::Arg::B(kq[qi]), mtl::Arg::B(vq[qi]), mtl::Arg::B(ksc[qi]), mtl::Arg::B(vsc[qi]), + mtl::Arg::B(qids), mtl::Arg::B(qfull), mtl::Arg::B(xqh), mtl::Arg::V(a)}, + 2, T, 128, "qsa attn"); + gemm(xqh, Wout, bo, T, N, 6144, "qsa proj"); + ++qi; + goto moe; + } + if (qsa_mode == "mm") { + const uint32_t nq = (uint32_t)T * 24 * 256; + D(P(lqsa, "qsa_q_f16"), {mtl::Arg::B(qcur), mtl::Arg::B(qcurh), mtl::Arg::V(nq)}, (nq + 255) / 256, 1, 256, "qsa attn"); + D(P(lqsa, "qsa_attn_mm", mtl::Constants().b(7, k4)), {mtl::Arg::B(qcurh), mtl::Arg::B(kq[qi]), mtl::Arg::B(vq[qi]), mtl::Arg::B(ksc[qi]), + mtl::Arg::B(vsc[qi]), mtl::Arg::B(qids), mtl::Arg::B(part), mtl::Arg::V(a)}, + QCHUNKS, 2, 32, "qsa attn", T); + } else + D(P(lqsa, "qsa_attn"), {mtl::Arg::B(qcur), mtl::Arg::B(kq[qi]), mtl::Arg::B(vq[qi]), mtl::Arg::B(ksc[qi]), + mtl::Arg::B(vsc[qi]), mtl::Arg::B(qids), mtl::Arg::B(part), mtl::Arg::V(a)}, + QCHUNKS, 2, 256, "qsa attn", T); + D(P(lqsa, "qsa_merge"), {mtl::Arg::B(part), mtl::Arg::B(qfull), mtl::Arg::B(XQ), mtl::Arg::V(a)}, 24, T, 256, + "qsa merge"); + act16(XQ, xqh, (size_t)T * 6144, "qsa proj"); + gemm(xqh, Wout, bo, T, N, 6144, "qsa proj"); + ++qi; + } + moe: + // ---- MoE + hc_read(b + "hc_ffn", true, T); + const gguf::Tensor &tr = T_(b + "ffn_gate_inp.weight"), &tsg = T_(b + "ffn_gate_inp_shexp.weight"), + &tg_ = T_(b + "ffn_gate_shexp.weight"), &tu_ = T_(b + "ffn_up_shexp.weight"), + &td_ = T_(b + "ffn_down_shexp.weight"), &eg = T_(b + "ffn_gate_exps.weight"), + &eu = T_(b + "ffn_up_exps.weight"), &ed = T_(b + "ffn_down_exps.weight"); + dq(tr, Wr); + dq(tsg, Wsg); + dq(tg_, Wshg); + dq(tu_, Wshu); + dq(td_, Wshd); + gemm(mixh, Wr, logits, T, NEXP, N, "router"); + const uint32_t nt = T; + D(P(lib, "route_topk"), {mtl::Arg::B(logits), mtl::Arg::B(ids), mtl::Arg::B(wts), mtl::Arg::V(nt)}, (T + 7) / 8, 1, + 256, "router"); + const int nent = T * TOPK, nblk = (nent + 1023) / 1024; + MmPlanArgs pa{(uint32_t)nent, TOPK, NEXP, (uint32_t)TM, (uint32_t)nblk}; + const uint32_t nclr = maxrows; + D(P(lib, "mm_clear"), {mtl::Arg::B(stok), mtl::Arg::V(nclr)}, (maxrows + 255) / 256, 1, 256, "experts"); + D(P(lib, "mm_hist"), {mtl::Arg::B(ids), mtl::Arg::B(bcnt), mtl::Arg::V(pa)}, nblk, 1, 1024, "experts"); + D(P(lib, "mm_scan"), {mtl::Arg::B(bcnt), mtl::Arg::B(boff), mtl::Arg::B(eoff), mtl::Arg::B(tiles), mtl::Arg::B(meta), + mtl::Arg::V(pa)}, 1, 1, NEXP, "experts"); + D(P(lib, "mm_place"), {mtl::Arg::B(ids), mtl::Arg::B(wts), mtl::Arg::B(boff), mtl::Arg::B(eoff), mtl::Arg::B(stok), + mtl::Arg::B(sw), mtl::Arg::B(pos), mtl::Arg::V(pa)}, nblk, 1, 1024, "experts"); + MmArgs ma{eg.offset, eu.offset, ed.offset, 0, 0, (uint32_t)ref::row_bytes(eg.type, N), + (uint32_t)ref::row_bytes(ed.type, NFF), N, NFF}; + ma.gu_stride = (uint64_t)ma.gu_row * NFF; + ma.d_stride = (uint64_t)ma.d_row * N; + const uint32_t ne = N; + mtl::Dispatch g; + g.p = P(lib, "mm_gather"); + g.args = {mtl::Arg::B(mixed), mtl::Arg::B(stok), mtl::Arg::B(XS), mtl::Arg::V(ne)}; + g.tg[0] = 256; + g.indirect = &meta; + g.ind_off = 8 * 4; + push(g, "experts"); + mtl::Dispatch gu; + gu.p = gu_v3 ? P(lib, "mm_gu3_" + std::to_string(eg.type) + "_" + gu3_for(eg.type), mtl::Constants().b(7, k4)) + : P(lib, "mm_gu2_" + std::to_string(eg.type) + (fmt_unit32(eg.type) ? "_16_64_32_2" : "_16_64_16_2"), + mtl::Constants().i(5, 0)); + gu.args = {mtl::Arg::B(W), mtl::Arg::B(XS), mtl::Arg::B(HS), mtl::Arg::B(tiles), mtl::Arg::V(ma)}; + gu.tg[0] = gu_v3 ? 32 * gu3[3] : 64; + gu.indirect = &meta; + gu.ind_off = 2 * 4; + push(gu, "experts gu"); + mtl::Dispatch dn; + dn.p = dn_v3 ? P(lib, "mm_down3_" + std::to_string(ed.type) + "_" + tl3(dn3), mtl::Constants().b(7, k4)) + : P(lib, "mm_down2_" + std::to_string(ed.type) + (ed.type == ref::IQ4_NL ? "_16_64_32_2" : "_16_64_16_2")); + dn.args = {mtl::Arg::B(W), mtl::Arg::B(HS), mtl::Arg::B(YE), mtl::Arg::B(tiles), mtl::Arg::V(ma)}; + dn.tg[0] = dn_v3 ? 32 * dn3[3] : 64; + dn.indirect = &meta; + dn.ind_off = 5 * 4; + push(dn, "experts dn"); + const uint32_t ca[4] = {(uint32_t)T, N, TOPK, 0}; + D(P(lib, "mm_combine"), {mtl::Arg::B(YE), mtl::Arg::B(pos), mtl::Arg::B(sw), mtl::Arg::B(yr), mtl::Arg::V(ca)}, + (T * N + 255) / 256, 1, 256, "experts"); + gemm(mixh, Wshg, gsh, T, NFF, N, "shared"); + gemm(mixh, Wshu, ush, T, NFF, N, "shared"); + const uint32_t nh = T * NFF; + D(P(lib, "swiglu_h"), {mtl::Arg::B(gsh), mtl::Arg::B(ush), mtl::Arg::B(hh), mtl::Arg::V(nh)}, (nh + 255) / 256, 1, 256, + "shared"); + gemm(hh, Wshd, ys, T, N, NFF, "shared"); + gemm(mixh, Wsg, sgv, T, 1, N, "shared"); + const uint32_t oa[2] = {(uint32_t)T, N}; + D(P(lib, "moe_out"), {mtl::Arg::B(yr), mtl::Arg::B(ys), mtl::Arg::B(sgv), mtl::Arg::B(bo), mtl::Arg::V(oa)}, + (T * N + 255) / 256, 1, 256, "shared"); + } + if (head) { + // the final read of the last row (decode kernels, 1 token) and the LM head + const size_t lr = (size_t)T - 1; + const gguf::Tensor &tn = T_("output_hc_norm.weight"), &tdn = T_("output_hc_down.weight"), &tup = T_("output_hc_up.weight"); + GrArgs a{N, HC, LR, 1, 1, 1e-6f}; + D(P(lib, "gr_norm"), {mtl::Arg::B(R, lr * HC * N * 4), mtl::Arg::B(bo, lr * N * 4), mtl::Arg::B(inj[cur_inj], lr * HC * 4), + mtl::Arg::B(W, tn.offset), mtl::Arg::B(xn1), mtl::Arg::V(a)}, HC, 1, 256, "head"); + D(P(lib, "gr_down_8_8", mtl::Constants().i(1, 1), "gr_down_8_8#1"), + {mtl::Arg::B(W, tdn.offset), mtl::Arg::B(W, tdn.offset), mtl::Arg::B(xn1), mtl::Arg::B(lo1), mtl::Arg::B(inj1), + mtl::Arg::V(a)}, LR + HC, 1, 256, "head"); + D(P(lib, "gr_up", mtl::Constants().i(1, 1), "gr_up#1"), + {mtl::Arg::B(W, tup.offset), mtl::Arg::B(lo1), mtl::Arg::B(xn1), mtl::Arg::B(X1), mtl::Arg::V(a)}, N / 16, 1, 256, "head"); + const gguf::Tensor& to = T_("output.weight"); + GemvArgs ga{N, NV, 1, (uint32_t)ref::row_bytes(to.type, N), N, NV}; + const std::string fn = "gemv_" + std::to_string(to.type) + "_16_1_4_1"; + const int xk = to.type == ref::Q4_K || to.type == ref::Q5_K ? 2 : (to.type == ref::Q6_K || to.type == ref::Q3_K) ? 3 : 0; + D(P(lib, fn, mtl::Constants().i(0, 1), fn + "#1"), + {mtl::Arg::B(W, to.offset), mtl::Arg::B(X1, (size_t)4 * N * xk), mtl::Arg::B(X1, (size_t)4 * N * 4), mtl::Arg::B(lm), + mtl::Arg::V(ga)}, (NV + 7) / 8, 1, 128, "head"); + ArgArgs aa{NV, 120}; + D(P(lsmp, "argmax_part"), {mtl::Arg::B(lm), mtl::Arg::B(apv), mtl::Arg::B(api), mtl::Arg::V(aa)}, 120, 1, 256, "head"); + D(P(lsmp, "argmax_final"), {mtl::Arg::B(apv), mtl::Arg::B(api), mtl::Arg::B(tokout), mtl::Arg::V(aa)}, 1, 1, 256, "head"); + } + }; + // a chunk: the embedding rows into every stream, then the chunk's command buffer; GDN history ping-pong flipped + auto run_chunk = [&](int pos0, int T, bool head) { + for (int t = 0; t < T; ++t) + for (int c = 0; c < HC; ++c) std::memcpy(R.as() + ((size_t)t * HC + c) * N, E.data() + (size_t)t * N, 4 * N); + cur_inj = 0; + build(pos0, T, head); + const double g = cx.run(ds); + for (auto& p : gpar) p ^= 1; + return g; + }; + auto prompt = [&](int Pn, double* first_chunk) { + double tot = 0; + for (int p0 = 0; p0 < Pn; p0 += C) { + const int T = std::min(C, Pn - p0); + const double g = run_chunk(p0, T, p0 + T >= Pn); + if (p0 == 0 && first_chunk) *first_chunk = g; + tot += g; + } + return tot; + }; + std::set all_cls; + // warm: the first chunk until the clocks are up + { + const double t0 = mtl::now_s(); + int n = 0; + while (mtl::now_s() - t0 < 1.5) { run_chunk(0, std::min(C, prompts[0]), false); ++n; } + std::printf("warm-up: %d chunks; %zu dispatches a chunk\n", n, ds.size()); + all_cls.insert(cls.begin(), cls.end()); + } + if (breakdown) { + // each class alone on the first chunk (pos0 0) and on a chunk at pos0 = PMAX - C (QSA past the budget) + if (PMAX > C) { // the classes of a chunk past the budget (score) too + run_chunk(std::max(0, PMAX - C), C, false); + all_cls.insert(cls.begin(), cls.end()); + } + for (int p0 : {0, std::max(0, PMAX - C)}) { + const std::string keep_only = only; + std::map by; + double all = 0; + std::vector names = {""}; + for (const auto& c : all_cls) names.push_back(c); + for (const std::string& c : names) { + only = c; + std::vector t; + for (int i = 0; i < 3; ++i) t.push_back(run_chunk(p0, C, false)); + if (c.empty()) all = median(t); + else by[c] = median(t); + } + only = keep_only; + double sum = 0; + for (auto& kv : by) sum += kv.second; + std::printf("chunk of %d at pos %d: all %.2f ms (%.0f tok/s); classes alone (sum %.2f ms):\n", C, p0, all * 1e3, C / all, + sum * 1e3); + for (auto& kv : by) std::printf(" %-10s %8.2f ms %6.2f us a token\n", kv.first.c_str(), kv.second * 1e3, kv.second / C * 1e6); + } + } + for (int Pn : prompts) { + std::vector t; + double fc = 0; + for (int r = 0; r < reps; ++r) t.push_back(prompt(Pn, &fc)); + const double m = median(t); + std::printf("prompt %6d tokens (chunks of %d): GPU %8.1f ms -> %7.1f tok/s (first chunk %.1f ms)\n", Pn, C, m * 1e3, + Pn / m, fc * 1e3); + } + return 0; +} diff --git a/metal/tests/prompt_parity.cpp b/metal/tests/prompt_parity.cpp new file mode 100644 index 00000000..2cb48351 --- /dev/null +++ b/metal/tests/prompt_parity.cpp @@ -0,0 +1,222 @@ +// metal/tests/prompt_parity.cpp - the prompt-chunk glue (prompt.metal) against CPU references: +// route_topk softmax + top 10 + renormalised weights (moe_route's rule) for 300 tokens, a third of them +// with exact ties +// the HC read as GEMMs gr_norm -> act_f16 -> [w_down; w_inject] GEMM -> gr_epi_down -> w_up GEMM -> gr_epi_up, on +// random BF16 weights, vs the exact formula (fp64) - the fp16 operands set the tolerance +// swiglu_h, moe_out elementwise +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include + +namespace { +constexpr int N = 2560, HC = 4, LR = 320; +struct GrArgs { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; }; +struct EpiArgs { uint32_t n_tok, n_embd, hc, hc_lr; }; +struct DqArgs { uint32_t n_in, n_out, row_bytes, perm; }; +struct GemmArgs { int M, N, K, pad; }; +double sig(double v) { return 1.0 / (1.0 + std::exp(-v)); } +} // namespace + +int main() { + mtl::Context cx; + const int lib = cx.compile({"quant.metal", "units.metal", "mma.metal", "dense_mm.metal", "gr.metal", "prompt.metal"}); + std::printf("device %s\n", cx.device_name().c_str()); + int fails = 0; + // ---- route_topk + { + const int T = 300; + mtl::Pipeline p = cx.pipeline(lib, "route_topk"); + mtl::Buffer lg = cx.alloc(4 * T * 512), ids = cx.alloc(4 * T * 10), w = cx.alloc(4 * T * 10); + ref::Rng r(9); + for (int t = 0; t < T; ++t) + for (int e = 0; e < 512; ++e) { + float v = r.sym() * 4.0f; + if (t % 3 == 0) v = std::round(v * 4.0f) / 4.0f; + lg.as()[t * 512 + e] = v; + } + const uint32_t nt = T; + mtl::Dispatch d; + d.p = &p; + d.args = {mtl::Arg::B(lg), mtl::Arg::B(ids), mtl::Arg::B(w), mtl::Arg::V(nt)}; + d.grid[0] = (T + 7) / 8; + d.tg[0] = 256; + cx.run({d}); + int bad = 0; + double worst = 0; + for (int t = 0; t < T; ++t) { + const float* l = lg.as() + t * 512; + float mx = -INFINITY; + for (int e = 0; e < 512; ++e) mx = std::max(mx, l[e]); + std::vector pr(512); + double s = 0; + for (int e = 0; e < 512; ++e) s += (pr[e] = std::exp((double)l[e] - mx)); + std::vector order(512); + for (int e = 0; e < 512; ++e) order[e] = e; + std::stable_sort(order.begin(), order.end(), [&](int x, int y) { return l[x] > l[y]; }); + double ss = 0; + for (int k = 0; k < 10; ++k) ss += pr[order[k]] / s; + for (int k = 0; k < 10; ++k) { + if (ids.as()[t * 10 + k] != order[k]) { ++bad; break; } + const double ref = pr[order[k]] / s / std::max(ss, 6.103515625e-5); + worst = std::max(worst, std::fabs(w.as()[t * 10 + k] - ref) / ref); + } + } + const bool ok = bad == 0 && worst < 2e-6; + fails += !ok; + std::printf("route_topk, %d tokens: id mismatches %d, worst weight rel err %.2e %s\n", T, bad, worst, ok ? "PASS" : "FAIL"); + } + // ---- the HC read as GEMMs + for (int apply = 0; apply < 2; ++apply) { + const int T = 70, NIN = HC * N, NR = LR + HC; + mtl::Buffer R = cx.alloc(4 * (size_t)T * NIN), bo = cx.alloc(4 * (size_t)T * N), inj = cx.alloc(4 * T * HC), + wn = cx.alloc(4 * NIN), wdn = cx.alloc(2 * (size_t)LR * NIN), win = cx.alloc(2 * (size_t)HC * NIN), + wup = cx.alloc(2 * (size_t)NIN * LR), xn = cx.alloc(4 * (size_t)T * NIN), xnh = cx.alloc(2 * (size_t)T * NIN), + WD = cx.alloc(2 * (size_t)NR * NIN), WU = cx.alloc(2 * (size_t)NIN * LR), V = cx.alloc(4 * (size_t)T * NR), + loh = cx.alloc(2 * (size_t)T * LR), injo = cx.alloc(4 * T * HC), G = cx.alloc(4 * (size_t)T * NIN), + mixed = cx.alloc(4 * (size_t)T * N), mixh = cx.alloc(2 * (size_t)T * N); + ref::Rng r(11 + apply); + std::vector R0((size_t)T * NIN); + for (auto& v : R0) v = r.sym(); + std::copy(R0.begin(), R0.end(), R.as()); + for (size_t i = 0; i < (size_t)T * N; ++i) bo.as()[i] = r.sym(); + for (int i = 0; i < T * HC; ++i) inj.as()[i] = r.sym() * 3.0f; + for (int i = 0; i < NIN; ++i) wn.as()[i] = 0.5f + r.uni(); + for (size_t i = 0; i < (size_t)LR * NIN; ++i) wdn.as()[i] = ref::f32_to_bf16(r.sym() * 0.05f); + for (size_t i = 0; i < (size_t)HC * NIN; ++i) win.as()[i] = ref::f32_to_bf16(r.sym() * 0.05f); + for (size_t i = 0; i < (size_t)NIN * LR; ++i) wup.as()[i] = ref::f32_to_bf16(r.sym() * 0.2f); + mtl::Pipeline pn = cx.pipeline(lib, "gr_norm"), pa = cx.pipeline(lib, "act_f16"), pdq = cx.pipeline(lib, "dq_f16_30"), + pg = cx.pipeline(lib, "gemm_f16_64_64_4"), ped = cx.pipeline(lib, "gr_epi_down"), peu = cx.pipeline(lib, "gr_epi_up"); + std::vector ds; + GrArgs ga{N, HC, LR, (uint32_t)T, (uint32_t)apply, 1e-6f}; + EpiArgs ea{(uint32_t)T, N, HC, LR}; + auto D = [&](const mtl::Pipeline& p, std::vector a, uint32_t gx, uint32_t gy, uint32_t tg) { + mtl::Dispatch d; d.p = &p; d.args = std::move(a); d.grid[0] = gx; d.grid[1] = gy; d.tg[0] = tg; ds.push_back(d); + }; + auto dq = [&](const mtl::Buffer& w, const mtl::Buffer& out, size_t ooff, int n_in, int n_out) { + DqArgs a{(uint32_t)n_in, (uint32_t)n_out, (uint32_t)(2 * n_in)}; + D(pdq, {mtl::Arg::B(w), mtl::Arg::B(out, ooff), mtl::Arg::V(a)}, (n_in / 16 + 63) / 64, n_out, 64); + }; + auto gemm = [&](const mtl::Buffer& A, const mtl::Buffer& B, const mtl::Buffer& Y, int M, int Nn, int K) { + GemmArgs g{M, Nn, K, 0}; + D(pg, {mtl::Arg::B(A), mtl::Arg::B(B), mtl::Arg::B(Y), mtl::Arg::V(g)}, (Nn + 63) / 64, (M + 63) / 64, 128); + }; + const uint32_t nx = T * NIN; + dq(wdn, WD, 0, NIN, LR); + dq(win, WD, (size_t)2 * LR * NIN, NIN, HC); + dq(wup, WU, 0, LR, NIN); + D(pn, {mtl::Arg::B(R), mtl::Arg::B(bo), mtl::Arg::B(inj), mtl::Arg::B(wn), mtl::Arg::B(xn), mtl::Arg::V(ga)}, HC, T, 256); + D(pa, {mtl::Arg::B(xn), mtl::Arg::B(xnh), mtl::Arg::V(nx)}, (nx + 255) / 256, 1, 256); + gemm(xnh, WD, V, T, NR, NIN); + D(ped, {mtl::Arg::B(V), mtl::Arg::B(loh), mtl::Arg::B(injo), mtl::Arg::V(ea)}, (T * NR + 255) / 256, 1, 256); + gemm(loh, WU, G, T, NIN, LR); + D(peu, {mtl::Arg::B(G), mtl::Arg::B(xn), mtl::Arg::B(mixed), mtl::Arg::B(mixh), mtl::Arg::V(ea)}, (T * N + 255) / 256, 1, 256); + cx.run(ds); + // the fused read: gr_norm_h (fp16 xn), the down GEMM, gr_epi_down, the up GEMM with the epilogue (w_up rows + // interleaved by dq_f16's perm) + mtl::Buffer mixed2 = cx.alloc(4 * (size_t)T * N), mixh2 = cx.alloc(2 * (size_t)T * N), WU2 = cx.alloc(2 * (size_t)NIN * LR), + xnh2 = cx.alloc(2 * (size_t)T * NIN), V2 = cx.alloc(4 * (size_t)T * NR), loh2 = cx.alloc(2 * (size_t)T * LR), + injo2 = cx.alloc(4 * T * HC); + std::copy(R0.begin(), R0.end(), R.as()); + { + mtl::Pipeline pnh = cx.pipeline(lib, "gr_norm_h"), pup = cx.pipeline(lib, "gemm_hc_up_64_64_4"); + ds.clear(); + DqArgs da{(uint32_t)LR, (uint32_t)NIN, (uint32_t)(2 * LR), (uint32_t)HC}; + D(pdq, {mtl::Arg::B(wup), mtl::Arg::B(WU2), mtl::Arg::V(da)}, (LR / 16 + 63) / 64, NIN, 64); + D(pnh, {mtl::Arg::B(R), mtl::Arg::B(bo), mtl::Arg::B(inj), mtl::Arg::B(wn), mtl::Arg::B(xnh2), mtl::Arg::V(ga)}, HC, T, 256); + gemm(xnh2, WD, V2, T, NR, NIN); + D(ped, {mtl::Arg::B(V2), mtl::Arg::B(loh2), mtl::Arg::B(injo2), mtl::Arg::V(ea)}, (T * NR + 255) / 256, 1, 256); + GemmArgs g{T, NIN, LR, 0}; + D(pup, {mtl::Arg::B(loh2), mtl::Arg::B(WU2), mtl::Arg::B(xnh2), mtl::Arg::B(mixed2), mtl::Arg::B(mixh2), mtl::Arg::V(g), + mtl::Arg::V(ea)}, NIN / 64, (T + 63) / 64, 128); + cx.run(ds); + } + // reference + double se = 0, sr = 0, sei = 0, sri = 0, ser = 0, srr = 0, se2 = 0, sh2 = 0; + std::vector x(NIN), lo(LR); + for (int t = 0; t < T; ++t) { + for (int c = 0; c < HC; ++c) { + const double g = apply ? 2.0 * sig(inj.as()[t * HC + c] / (double)HC) : 0.0; + double ss = 0; + for (int d = 0; d < N; ++d) { + const size_t i = (size_t)t * NIN + c * N + d; + const double v = R0[i] + (apply ? bo.as()[(size_t)t * N + d] * g : 0.0); + x[c * N + d] = v; + ss += v * v; + ser += (R.as()[i] - v) * (R.as()[i] - v); + srr += v * v; + } + const double rs = 1.0 / std::sqrt(ss / N + 1e-6); + for (int d = 0; d < N; ++d) x[c * N + d] *= wn.as()[c * N + d] * rs; + } + for (int k = 0; k < NR; ++k) { + const uint16_t* w = k < LR ? wdn.as() + (size_t)k * NIN : win.as() + (size_t)(k - LR) * NIN; + double s = 0; + for (int i = 0; i < NIN; ++i) s += ref::bf16_to_f32(w[i]) * x[i]; + if (k < LR) lo[k] = s / HC * sig(s / HC); + else { + const double gv = injo.as()[t * HC + k - LR]; + sei += (gv - s) * (gv - s); + sri += s * s; + } + } + for (int d = 0; d < N; ++d) { + double m = 0; + for (int c = 0; c < HC; ++c) { + const uint16_t* w = wup.as() + (size_t)(c * N + d) * LR; + double s = 0; + for (int k = 0; k < LR; ++k) s += ref::bf16_to_f32(w[k]) * lo[k]; + m += x[c * N + d] * sig(s); + } + m /= HC; + const double gv = mixed.as()[(size_t)t * N + d], g2 = mixed2.as()[(size_t)t * N + d], + h2 = ref::f16_to_f32(mixh2.as()[(size_t)t * N + d]); + se += (gv - m) * (gv - m); + se2 += (g2 - m) * (g2 - m); + sh2 += (h2 - m) * (h2 - m); + sr += m * m; + } + } + const double rm = std::sqrt(se / sr), ri = std::sqrt(sei / sri), rr = std::sqrt(ser / srr); + const double r2 = std::sqrt(se2 / sr), rh2 = std::sqrt(sh2 / sr); + const bool ok = rm < 2e-3 && ri < 2e-3 && rr < 1e-6 && r2 < 2e-3 && rh2 < 2e-3; + fails += !ok; + std::printf("HC read as GEMMs, %d tokens, apply %d: mixed rel err %.2e, inject %.2e, residual %.2e; fused read " + "(fp16 xn, up GEMM epilogue): mixed %.2e, fp16 %.2e %s\n", T, apply, rm, ri, rr, r2, rh2, ok ? "PASS" : "FAIL"); + } + // ---- swiglu_h, moe_out + { + const int n = 5000, T = 7, NE = 640; + mtl::Pipeline ps = cx.pipeline(lib, "swiglu_h"), pm = cx.pipeline(lib, "moe_out"); + mtl::Buffer g = cx.alloc(4 * n), u = cx.alloc(4 * n), h = cx.alloc(2 * n), yr = cx.alloc(4 * T * NE), + ys = cx.alloc(4 * T * NE), sg = cx.alloc(4 * T), bo = cx.alloc(4 * T * NE); + ref::Rng r(5); + for (int i = 0; i < n; ++i) { g.as()[i] = r.sym() * 6; u.as()[i] = r.sym(); } + for (int i = 0; i < T * NE; ++i) { yr.as()[i] = r.sym(); ys.as()[i] = r.sym(); } + for (int i = 0; i < T; ++i) sg.as()[i] = r.sym() * 4; + const uint32_t nn = n; + const uint32_t a2[2] = {(uint32_t)T, (uint32_t)NE}; + mtl::Dispatch d1; d1.p = &ps; d1.args = {mtl::Arg::B(g), mtl::Arg::B(u), mtl::Arg::B(h), mtl::Arg::V(nn)}; + d1.grid[0] = (n + 255) / 256; d1.tg[0] = 256; + mtl::Dispatch d2; d2.p = ± d2.args = {mtl::Arg::B(yr), mtl::Arg::B(ys), mtl::Arg::B(sg), mtl::Arg::B(bo), mtl::Arg::V(a2)}; + d2.grid[0] = (T * NE + 255) / 256; d2.tg[0] = 256; + cx.run({d1, d2}); + double w1 = 0, w2 = 0; + for (int i = 0; i < n; ++i) { + const double gv = g.as()[i], ref = gv * sig(gv) * u.as()[i]; + w1 = std::max(w1, std::fabs(ref::f16_to_f32(h.as()[i]) - ref) / (std::fabs(ref) + 1e-3)); + } + for (int i = 0; i < T * NE; ++i) { + const double ref = yr.as()[i] + sig(sg.as()[i / NE]) * ys.as()[i]; + w2 = std::max(w2, std::fabs(bo.as()[i] - ref)); + } + const bool ok = w1 < 1e-3 && w2 < 1e-5; + fails += !ok; + std::printf("swiglu_h worst rel err %.2e, moe_out worst abs err %.2e %s\n", w1, w2, ok ? "PASS" : "FAIL"); + } + std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS"); + return fails ? 1 : 0; +} diff --git a/metal/tests/qsa_parity.cpp b/metal/tests/qsa_parity.cpp new file mode 100644 index 00000000..8162ec2e --- /dev/null +++ b/metal/tests/qsa_parity.cpp @@ -0,0 +1,308 @@ +// metal/tests/qsa_parity.cpp - QSA decode (qsa.metal) stage by stage against a CPU reference, and its speed. +// +// qsa_parity [P] a context of P cells built by qsa_prep (default 3000: the selection is active above +// 2051), then a window of 3 tokens: prep, score, top-k, attention, merge. Each stage is +// checked against the CPU fed with the GPU's inputs to that stage; the ids exactly. +// qsa_parity --bench [P] GPU time of the window's kernels at context P, 1 and 3 tokens +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { +constexpr int QH = 24, QKV = 2, QD = 256, IH = 4, ID = 128, BUDGET = 2051, CH = 64, NCH = (BUDGET + CH - 1) / CH; +struct QsaArgs { uint32_t pos0, pos_base, max_cells, n_tok; float eps; }; +double median(std::vector v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; } +struct Err { + double se = 0, sr = 0; + void add(double g, double r) { se += (g - r) * (g - r); sr += r * r; } + double l2() const { return sr > 0 ? std::sqrt(se / sr) : std::sqrt(se); } +}; +float h2f(uint16_t h) { return ref::f16_to_f32(h); } +} // namespace + +int main(int argc, char** argv) { + bool bench = false; + int P = 3000; + for (int i = 1; i < argc; ++i) { + std::string a = argv[i]; + if (a == "--bench") bench = true; + else P = std::atoi(argv[i]); + } + const int MAXT = 8, MAXC = std::max(4096, (P + 64) / 4 * 4 + 64); + mtl::Context cx; + const int lib = cx.compile({"qsa.metal", "qsa2.metal"}, "#define NO_GGML_COMMON 1\n"); + // QSA_TOPK=1: the v1 top-k; QSA_ATTN=1|2|3 (default 3): which attention (2 has its own chunking and merge) + const int av = std::getenv("QSA_ATTN") ? std::atoi(std::getenv("QSA_ATTN")) : 1; + const bool v2 = av == 2; + mtl::Pipeline pprep = cx.pipeline(lib, "qsa_prep", mtl::Constants().b(24, std::getenv("QSA_MROPE") != nullptr)), pscore = cx.pipeline(lib, "qsa_score"), + ptopk = cx.pipeline(lib, std::getenv("QSA_TOPK") ? "qsa_topk" : "qsa_topk2"), + pattn = cx.pipeline(lib, av == 1 ? "qsa_attn" : av == 2 ? "qsa_attn2" : "qsa_attn3"), + pmerge = cx.pipeline(lib, v2 ? "qsa_merge2" : "qsa_merge"); + const int MB = MAXC / 4 + 2; + // per-cell inputs for every cell (context + window) + const int NC = P + MAXT; + mtl::Buffer qfull = cx.alloc(4 * (size_t)NC * QH * 2 * QD), kc = cx.alloc(4 * (size_t)NC * QKV * QD), + vc = cx.alloc(4 * (size_t)NC * QKV * QD), iq = cx.alloc(4 * (size_t)NC * IH * ID), + ik = cx.alloc(4 * (size_t)NC * ID), qn = cx.alloc(4 * QD), kn = cx.alloc(4 * QD), iqn = cx.alloc(4 * ID), + ikn = cx.alloc(4 * ID), cs = cx.alloc(8 * (size_t)(MAXC + 16) * 32), qcur = cx.alloc(4 * MAXT * QH * QD), + qidx = cx.alloc(4 * MAXT * IH * ID), kq = cx.alloc((size_t)MAXC * QKV * QD), vq = cx.alloc((size_t)MAXC * QKV * QD), + ksc = cx.alloc(2 * (size_t)MAXC * QKV * 4), vsc = cx.alloc(2 * (size_t)MAXC * QKV * 4), tail = cx.alloc(4 * 4 * ID), + dead = cx.alloc(4 * ID), pooled = cx.alloc(4 * (size_t)MB * ID), scores = cx.alloc(4 * (size_t)MAXT * MB), + ids = cx.alloc(4 * MAXT * BUDGET), part = cx.alloc(4 * (size_t)MAXT * 2 * NCH * QH * (QD + 2)), + xp = cx.alloc(4 * (4 * MAXT * QH * QD + MAXT * QH * QD / 16)); + ref::Rng r(23); + for (size_t i = 0; i < qfull.bytes / 4; ++i) qfull.as()[i] = r.sym() * 2.0f; + for (size_t i = 0; i < kc.bytes / 4; ++i) kc.as()[i] = r.sym() * 2.0f; + for (size_t i = 0; i < vc.bytes / 4; ++i) vc.as()[i] = r.sym(); + for (size_t i = 0; i < iq.bytes / 4; ++i) iq.as()[i] = r.sym(); + for (size_t i = 0; i < ik.bytes / 4; ++i) ik.as()[i] = r.sym(); + for (int i = 0; i < QD; ++i) { qn.as()[i] = 1.0f + 0.2f * r.sym(); kn.as()[i] = 1.0f + 0.2f * r.sym(); } + for (int i = 0; i < ID; ++i) { iqn.as()[i] = 1.0f + 0.2f * r.sym(); ikn.as()[i] = 1.0f + 0.2f * r.sym(); } + const uint32_t pos_base = 0; + // QSA_MROPE=1: qsa_prep with the M-RoPE table (function constant 24): random (t, h, w) positions per cell, the CPU + // reference rotating pair i by row tab[cell * 3 + i % 3]; QSA_MROPE=id: the identity table, checked bitwise + // against the plain kernel + const char* mre = std::getenv("QSA_MROPE"); + const bool mrope = mre != nullptr, mid = mrope && std::string(mre) == "id"; + mtl::Buffer mtab = cx.alloc(4 * 3 * (size_t)(MAXC + 16)); + { + ref::Rng rm(77); + for (int c = 0; c < MAXC + 16; ++c) + for (int k = 0; k < 3; ++k) mtab.as()[c * 3 + k] = mid ? c : (int)(rm.next() % (uint64_t)(MAXC + 16)); + } + for (int p = 0; p < MAXC + 16; ++p) + for (int i = 0; i < 32; ++i) { + const double inv = std::pow(1e7, -2.0 * i / 64.0), th = (double)p * inv; + cs.as()[(p * 32 + i) * 2] = (float)std::cos(th); + cs.as()[(p * 32 + i) * 2 + 1] = (float)std::sin(th); + } + auto prep = [&](uint32_t pos0, int nt) { + QsaArgs a{pos0, pos_base, (uint32_t)MAXC, (uint32_t)nt, 1e-6f}; + mtl::Dispatch d; + d.p = &pprep; + d.args = {mtl::Arg::B(qfull, 4 * (size_t)pos0 * QH * 2 * QD), mtl::Arg::B(kc, 4 * (size_t)pos0 * QKV * QD), + mtl::Arg::B(vc, 4 * (size_t)pos0 * QKV * QD), mtl::Arg::B(iq, 4 * (size_t)pos0 * IH * ID), + mtl::Arg::B(ik, 4 * (size_t)pos0 * ID), mtl::Arg::B(qn), mtl::Arg::B(kn), mtl::Arg::B(iqn), + mtl::Arg::B(ikn), mtl::Arg::B(cs), mtl::Arg::B(qcur), mtl::Arg::B(qidx), mtl::Arg::B(kq), + mtl::Arg::B(vq), mtl::Arg::B(ksc), mtl::Arg::B(vsc), mtl::Arg::B(tail), mtl::Arg::B(dead), + mtl::Arg::B(pooled), mtl::Arg::V(a), mtl::Arg::B(mtab)}; + d.grid[0] = 33; + d.grid[1] = nt; + d.tg[0] = 256; + return d; + }; + auto window = [&](uint32_t pos0, int nt, std::vector& ds) { + QsaArgs a{pos0, pos_base, (uint32_t)MAXC, (uint32_t)nt, 1e-6f}; + ds.push_back(prep(pos0, nt)); + mtl::Dispatch s; + s.p = &pscore; + s.args = {mtl::Arg::B(qidx), mtl::Arg::B(pooled), mtl::Arg::B(dead), mtl::Arg::B(scores), mtl::Arg::V(a)}; + s.grid[0] = ((pos0 + nt) / 4 + 1 + 7) / 8; + s.grid[1] = nt; + s.tg[0] = 256; + ds.push_back(s); + mtl::Dispatch k; + k.p = &ptopk; + k.args = {mtl::Arg::B(scores), mtl::Arg::B(ids), mtl::Arg::V(a)}; + k.grid[0] = nt; + k.tg[0] = 1024; + ds.push_back(k); + mtl::Dispatch at; + at.p = &pattn; + at.args = {mtl::Arg::B(qcur), mtl::Arg::B(kq), mtl::Arg::B(vq), mtl::Arg::B(ksc), mtl::Arg::B(vsc), + mtl::Arg::B(ids), mtl::Arg::B(part), mtl::Arg::V(a)}; + at.grid[0] = v2 ? (BUDGET + 31) / 32 : NCH; + at.grid[1] = v2 ? QKV * 2 : QKV; + at.grid[2] = nt; + at.tg[0] = 256; + ds.push_back(at); + mtl::Dispatch m; + m.p = &pmerge; + m.args = {mtl::Arg::B(part), mtl::Arg::B(qfull, 4 * (size_t)pos0 * QH * 2 * QD), mtl::Arg::B(xp), mtl::Arg::V(a)}; + m.grid[0] = QH; + m.grid[1] = nt; + m.tg[0] = 256; + ds.push_back(m); + }; + // the context, one cell at a time + { + std::vector ds; + for (int p = 0; p < P; ++p) ds.push_back(prep(p, 1)); + cx.run(ds); + } + if (bench) { + std::printf("device %s, context %d cells\n", cx.device_name().c_str(), P); + for (int nt : {1, 3}) { + std::vector ds; + window(P, nt, ds); + const char* names[] = {"prep", "score", "topk", "attn", "merge"}; + double total = 0; + for (int i = 0; i < 5; ++i) { + std::vector one(32, ds[i]); + cx.warm(one, 0.05); + std::vector t; + for (int k = 0; k < 7; ++k) t.push_back(cx.run(one) / 32); + std::printf(" ntok %d %-6s %7.2f us\n", nt, names[i], median(t) * 1e6); + total += median(t); + } + std::vector t; + for (int k = 0; k < 7; ++k) t.push_back(cx.run(ds)); + std::printf(" ntok %d window (5 dependent dispatches): %.2f us (sum of parts %.2f)\n", nt, median(t) * 1e6, + total * 1e6); + } + return 0; + } + const int NT = 3; + std::vector ds; + window(P, NT, ds); + // stage by stage, re-reading GPU state in between + cx.run({ds[0]}); + int fails = 0; + // ---- prep: qcur, qidx, the window cells' KV codes and the pooled keys vs CPU + { + Err eq, ei, ekv, ep; + auto normrope = [&](const float* x, const float* g, int w, int absp, bool rope, std::vector& out) { + double ss = 0; + for (int i = 0; i < w; ++i) ss += (double)x[i] * x[i]; + const double rs = 1.0 / std::sqrt(ss / w + 1e-6); + out.assign(w, 0.0); + for (int i = 0; i < w; ++i) out[i] = rs * x[i] * g[i]; + if (rope) + for (int i = 0; i < 32; ++i) { + const int pp = mrope ? mtab.as()[absp * 3 + i % 3] : absp; + const double c = cs.as()[(pp * 32 + i) * 2], s = cs.as()[(pp * 32 + i) * 2 + 1]; + const double a = out[i], b = out[i + 32]; + out[i] = a * c - b * s; + out[i + 32] = a * s + b * c; + } + }; + std::vector o; + for (int t = 0; t < NT; ++t) { + const int cell = P + t; + for (int h = 0; h < QH; ++h) { + normrope(qfull.as() + ((size_t)cell * QH + h) * 2 * QD, qn.as(), QD, cell, true, o); + for (int i = 0; i < QD; ++i) eq.add(qcur.as()[(t * QH + h) * QD + i], o[i]); + } + for (int h = 0; h < IH; ++h) { + normrope(iq.as() + ((size_t)cell * IH + h) * ID, iqn.as(), ID, cell, true, o); + for (int i = 0; i < ID; ++i) ei.add(qidx.as()[(t * IH + h) * ID + i], o[i]); + } + for (int h = 0; h < QKV; ++h) { + normrope(kc.as() + ((size_t)cell * QKV + h) * QD, kn.as(), QD, cell, true, o); + for (int i = 0; i < QD; ++i) { + const size_t row = (size_t)cell * QKV + h; + const double deq = (double)(int8_t)kq.as()[row * QD + i] * h2f(ksc.as()[row * 4 + i / 64]); + ekv.add(deq, o[i]); + } + } + } + // pooled keys of the last few completed blocks + const int nb = (P + NT) / 4; + for (int b = std::max(0, nb - 8); b < nb; ++b) { + std::vector m(ID); + for (int i = 0; i < ID; ++i) + m[i] = (((ik.as()[(4 * b) * ID + i] + ik.as()[(4 * b + 1) * ID + i]) + + ik.as()[(4 * b + 2) * ID + i]) + ik.as()[(4 * b + 3) * ID + i]) * 0.25f; + normrope(m.data(), ikn.as(), ID, 4 * b, true, o); + for (int i = 0; i < ID; ++i) ep.add(pooled.as()[b * ID + i], o[i]); + } + // int8 quantization error is ~1/254 of max|x| per group: the KV check is a quantization tolerance + const bool ok = eq.l2() < 1e-5 && ei.l2() < 1e-5 && ep.l2() < 1e-5 && ekv.l2() < 6e-3; + fails += !ok; + std::printf("prep: q rel L2 %.2e, indexer q %.2e, pooled keys %.2e, K int8 (vs float) %.2e %s\n", eq.l2(), + ei.l2(), ep.l2(), ekv.l2(), ok ? "PASS" : "FAIL"); + } + // ---- score + cx.run({ds[1]}); + { + Err es; + for (int t = 0; t < NT; ++t) { + const int n_kv = P + t + 1, n_bid = n_kv / 4; + for (int b = 0; b <= n_bid; ++b) { + const float* key = b == n_bid ? dead.as() : pooled.as() + b * ID; + double s = 0; + for (int h = 0; h < IH; ++h) { + double d = 0; + for (int i = 0; i < ID; ++i) d += (double)qidx.as()[(t * IH + h) * ID + i] * key[i]; + s += std::max(d, 0.0); + } + if (b == n_bid && (n_kv & 3)) { + // float(s + 1e9) keeps no bits of s: only check that the bias is there + if (!(scores.as()[t * MB + b] >= 1e9f)) es.add(1.0, 0.0); + } else { + es.add(scores.as()[t * MB + b], s); + } + } + } + const bool ok = es.l2() < 1e-5; + fails += !ok; + std::printf("score: rel L2 %.2e (tail +1e9 checked separately) %s\n", es.l2(), ok ? "PASS" : "FAIL"); + } + // ---- top-k (exact, from the GPU's scores) + cx.run({ds[2]}); + { + int bad = 0; + for (int t = 0; t < NT; ++t) { + const int n_kv = P + t + 1, n_bid = n_kv / 4, width = std::min(n_kv, BUDGET); + std::vector cells(n_kv); + for (int c = 0; c < n_kv; ++c) cells[c] = c; + if (n_kv > BUDGET) { + const float* sc = scores.as() + t * MB; + std::stable_sort(cells.begin(), cells.end(), [&](int x, int y) { return sc[x / 4] > sc[y / 4]; }); + cells.resize(width); + std::sort(cells.begin(), cells.end()); + } + (void)n_bid; + for (int i = 0; i < width; ++i) bad += ids.as()[t * BUDGET + i] != cells[i]; + } + fails += bad != 0; + std::printf("top-k: %d of %d ids differ (context %d: selection %s) %s\n", bad, NT * std::min(P + 1, BUDGET), P, + P + 1 > BUDGET ? "active" : "identity", bad ? "FAIL" : "PASS"); + } + // ---- attention + merge (from the GPU's qcur, ids and KV codes) + cx.run({ds[3], ds[4]}); + { + Err eo; + for (int t = 0; t < NT; ++t) { + const int n_kv = P + t + 1, width = std::min(n_kv, BUDGET); + for (int h = 0; h < QH; ++h) { + const int g = h / (QH / QKV); + std::vector s(width); + double mx = -1e300; + for (int c = 0; c < width; ++c) { + const size_t row = (size_t)ids.as()[t * BUDGET + c] * QKV + g; + double d = 0; + for (int i = 0; i < QD; ++i) + d += (double)qcur.as()[(t * QH + h) * QD + i] * (int8_t)kq.as()[row * QD + i] * + h2f(ksc.as()[row * 4 + i / 64]); + s[c] = d / 16.0; + mx = std::max(mx, s[c]); + } + double l = 0; + for (int c = 0; c < width; ++c) l += (s[c] = std::exp(s[c] - mx)); + for (int i = 0; i < QD; ++i) { + double o = 0; + for (int c = 0; c < width; ++c) { + const size_t row = (size_t)ids.as()[t * BUDGET + c] * QKV + g; + o += s[c] * (int8_t)vq.as()[row * QD + i] * h2f(vsc.as()[row * 4 + i / 64]); + } + o /= l; + const double gate = qfull.as()[((size_t)(P + t) * QH + h) * 2 * QD + QD + i]; + eo.add(xp.as()[t * QH * QD + h * QD + i], o / (1.0 + std::exp(-gate))); + } + } + } + const bool ok = eo.l2() < 1e-5; + fails += !ok; + std::printf("attention + gate: rel L2 %.2e %s\n", eo.l2(), ok ? "PASS" : "FAIL"); + } + std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS"); + return fails ? 1 : 0; +} diff --git a/metal/tests/qsa_prompt_parity.cpp b/metal/tests/qsa_prompt_parity.cpp new file mode 100644 index 00000000..18e1b3af --- /dev/null +++ b/metal/tests/qsa_prompt_parity.cpp @@ -0,0 +1,160 @@ +// metal/tests/qsa_prompt_parity.cpp - qsa_attn_mm (qsa_prompt.metal, the matrix units, fp16 operands) against qsa_attn +// (fp32, itself checked by qsa_parity), both followed by qsa_merge: the attention output of T query tokens on random +// int8 caches, within the budget (all cells, causal) and past it (2051 selected cells per token); then the speed. +// qsa_prompt_parity [--bench] +#include "coop_probe.h" +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { +constexpr int QH = 24, QKV = 2, QD = 256, QB = 2051, NCH = 33; +struct QsaArgs { uint32_t pos0, pos_base, max_cells, n_tok; float eps; }; +double median(std::vector v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; } +} // namespace + +int main(int argc, char** argv) { + const bool bench = argc > 1 && std::string(argv[1]) == "--bench"; + std::setvbuf(stdout, nullptr, _IOLBF, 0); + const bool noflash = std::getenv("QSA_NOFLASH") != nullptr; + mtl::Context cx; + const int lib = cx.compile({"qsa.metal", "qsa_prompt.metal"}, "#define NO_GGML_COMMON 1\n"); + std::printf("device %s\n", cx.device_name().c_str()); + const int T = bench ? 2048 : 96, MAXC = 40000; + mtl::Buffer kq = cx.alloc((size_t)MAXC * QKV * QD), vq = cx.alloc((size_t)MAXC * QKV * QD), ksc = cx.alloc(2 * (size_t)MAXC * QKV * 4), + vsc = cx.alloc(2 * (size_t)MAXC * QKV * 4), qcur = cx.alloc(4 * (size_t)T * QH * QD), qh = cx.alloc(2 * (size_t)T * QH * QD), + qfull = cx.alloc(4 * (size_t)T * QH * 2 * QD), ids = cx.alloc(4 * (size_t)T * QB), + part = cx.alloc(4 * (size_t)T * NCH * QH * (QD + 2)), xa = cx.alloc(4 * ((size_t)4 * T * QH * QD + (size_t)T * QH * QD / 16)), + xb = cx.alloc(4 * ((size_t)4 * T * QH * QD + (size_t)T * QH * QD / 16)); + ref::Rng r(5); + for (size_t i = 0; i < kq.bytes; ++i) { kq.as()[i] = (int8_t)((int)(r.next() % 255) - 127); vq.as()[i] = (int8_t)((int)(r.next() % 255) - 127); } + for (size_t i = 0; i < ksc.bytes / 2; ++i) { ksc.as()[i] = ref::f32_to_f16(0.004f + 0.004f * r.uni()); vsc.as()[i] = ref::f32_to_f16(0.004f + 0.004f * r.uni()); } + for (size_t i = 0; i < (size_t)T * QH * QD; ++i) qcur.as()[i] = r.sym() * 3.0f; + for (size_t i = 0; i < (size_t)T * QH * 2 * QD; ++i) qfull.as()[i] = r.sym(); + mtl::Pipeline pa = cx.pipeline(lib, "qsa_attn"), pm = cx.pipeline(lib, "qsa_merge"), pmm = cx.pipeline(lib, "qsa_attn_mm", mtl::Constants().b(7, coop_k4(cx)).i(8, std::getenv("QSA_STOP") ? std::atoi(std::getenv("QSA_STOP")) : 0)), + pq = cx.pipeline(lib, "qsa_q_f16"), pf = cx.pipeline(lib, "qsa_flash", mtl::Constants().b(7, coop_k4(cx))); + mtl::Buffer xf = cx.alloc(2 * (size_t)T * QH * QD); + std::printf("pipelines: qsa_attn_mm max threads %d, tg mem %d; qsa_flash max threads %d, tg mem %d\n", pmm.max_threads, + pmm.static_tg_mem, pf.max_threads, pf.static_tg_mem); + int fails = 0; + for (uint32_t pos0 : {0u, 30000u}) { + // ids: within the budget the identity; past it 2051 distinct ascending cells < n_kv + for (int t = 0; t < T; ++t) { + const uint32_t n_kv = pos0 + t + 1; + int* o = ids.as() + (size_t)t * QB; + if (n_kv <= (uint32_t)QB) { for (uint32_t c = 0; c < n_kv; ++c) o[c] = (int)c; continue; } + std::set s; + while ((int)s.size() < QB) s.insert((int)(r.next() % n_kv)); + int j = 0; + for (int c : s) o[j++] = c; + } + QsaArgs a{pos0, 0, (uint32_t)MAXC, (uint32_t)T, 1e-6f}; + auto D = [&](const mtl::Pipeline& p, std::vector args, uint32_t gx, uint32_t gy, uint32_t gz, uint32_t tg) { + mtl::Dispatch d; d.p = &p; d.args = std::move(args); d.grid[0] = gx; d.grid[1] = gy; d.grid[2] = gz; d.tg[0] = tg; return d; + }; + const uint32_t nq = T * QH * QD; + std::vector ref_ds = { + D(pa, {mtl::Arg::B(qcur), mtl::Arg::B(kq), mtl::Arg::B(vq), mtl::Arg::B(ksc), mtl::Arg::B(vsc), mtl::Arg::B(ids), mtl::Arg::B(part), mtl::Arg::V(a)}, NCH, QKV, T, 256), + D(pm, {mtl::Arg::B(part), mtl::Arg::B(qfull), mtl::Arg::B(xa), mtl::Arg::V(a)}, QH, T, 1, 256)}; + std::vector mm_ds = { + D(pq, {mtl::Arg::B(qcur), mtl::Arg::B(qh), mtl::Arg::V(nq)}, (nq + 255) / 256, 1, 1, 256), + D(pmm, {mtl::Arg::B(qh), mtl::Arg::B(kq), mtl::Arg::B(vq), mtl::Arg::B(ksc), mtl::Arg::B(vsc), mtl::Arg::B(ids), mtl::Arg::B(part), mtl::Arg::V(a)}, NCH, QKV, T, 32), + D(pm, {mtl::Arg::B(part), mtl::Arg::B(qfull), mtl::Arg::B(xb), mtl::Arg::V(a)}, QH, T, 1, 256)}; + const mtl::Dispatch fl = D(pf, {mtl::Arg::B(qh), mtl::Arg::B(kq), mtl::Arg::B(vq), mtl::Arg::B(ksc), mtl::Arg::B(vsc), + mtl::Arg::B(ids), mtl::Arg::B(qfull), mtl::Arg::B(xf), mtl::Arg::V(a)}, QKV, T, 1, 128); + if (bench) { + auto timeit = [&](const std::vector& ds) { + cx.warm(ds, 0.3); + std::vector t; + for (int i = 0; i < 5; ++i) t.push_back(cx.run(ds)); + return median(t); + }; + std::printf("pos0 %5u, T %d: qsa_attn %.2f ms, qsa_attn_mm %.2f ms, merge %.2f ms; qsa_flash (no merge) %.2f ms\n", pos0, + T, timeit({ref_ds[0]}) * 1e3, timeit({mm_ds[1]}) * 1e3, timeit({ref_ds[1]}) * 1e3, timeit({fl}) * 1e3); + continue; + } + cx.run(ref_ds); + std::fill(part.as(), part.as() + part.bytes / 4, std::nanf("")); // a kernel that writes nothing shows + cx.run(mm_ds); + if (std::getenv("QSA_DEBUG")) { + // how much of the partials the matrix-unit kernel wrote, and token 5's first chunk (m, l, acc[0..3]) + size_t written = 0, nonfinite = 0; + const float* pp = part.as(); + for (size_t i = 0; i < (size_t)T * NCH * QH * (QD + 2); ++i) { + if (!std::isnan(pp[i])) ++written; + if (!std::isfinite(pp[i]) && !std::isnan(pp[i])) ++nonfinite; + } + const float* q = pp + ((size_t)5 * NCH * QH) * (QD + 2); + std::printf("debug pos0 %u: %zu of %zu partial floats written (%zu inf); t5 h0: m %g l %g acc %g %g %g %g\n", pos0, + written, (size_t)T * NCH * QH * (QD + 2), nonfinite, q[QD], q[QD + 1], q[0], q[1], q[2], q[3]); + } + double se = 0, sr = 0; + for (size_t i = 0; i < (size_t)T * QH * QD; ++i) { + const double e = xb.as()[i] - xa.as()[i]; + se += e * e; + sr += (double)xa.as()[i] * xa.as()[i]; + } + const double rel = std::sqrt(se / sr); + const bool ok = rel < 3e-3; + fails += !ok; + std::printf("pos0 %5u, T %d: qsa_attn_mm vs qsa_attn (after merge) rel L2 %.2e %s\n", pos0, T, rel, ok ? "PASS" : "FAIL"); + if (noflash) continue; + cx.run({fl}); + double sf = 0; + for (size_t i = 0; i < (size_t)T * QH * QD; ++i) { + const double e = ref::f16_to_f32(xf.as()[i]) - xa.as()[i]; + sf += e * e; + } + const double relf = std::sqrt(sf / sr); + const bool okf = relf < 3e-3; + fails += !okf; + std::printf("pos0 %5u, T %d: qsa_flash (fp16 out) vs qsa_attn + merge rel L2 %.2e %s\n", pos0, T, relf, okf ? "PASS" : "FAIL"); + } + // qsa_score_mm vs qsa_score at pos0 30000: the scores of every block <= n_bid + { + const uint32_t pos0 = 30000, MB = MAXC / 4 + 2, nb = (pos0 + T) / 4 + 1; + mtl::Buffer qidx = cx.alloc(4 * (size_t)T * 4 * 128), pooled = cx.alloc(4 * (size_t)MB * 128), dead = cx.alloc(4 * 128), + sa = cx.alloc(4 * (size_t)T * MB), sb = cx.alloc(4 * (size_t)T * MB); + for (size_t i = 0; i < (size_t)T * 4 * 128; ++i) qidx.as()[i] = r.sym(); + for (size_t i = 0; i < (size_t)MB * 128; ++i) pooled.as()[i] = r.sym(); + for (int i = 0; i < 128; ++i) dead.as()[i] = r.sym(); + QsaArgs a{pos0, 0, (uint32_t)MAXC, (uint32_t)T, 1e-6f}; + mtl::Pipeline ps = cx.pipeline(lib, "qsa_score"), psm = cx.pipeline(lib, "qsa_score_mm"); + mtl::Dispatch d1; d1.p = &ps; d1.args = {mtl::Arg::B(qidx), mtl::Arg::B(pooled), mtl::Arg::B(dead), mtl::Arg::B(sa), mtl::Arg::V(a)}; + d1.grid[0] = (nb + 7) / 8; d1.grid[1] = T; d1.tg[0] = 256; + mtl::Dispatch d2; d2.p = &psm; d2.args = {mtl::Arg::B(qidx), mtl::Arg::B(pooled), mtl::Arg::B(dead), mtl::Arg::B(sb), mtl::Arg::V(a)}; + d2.grid[0] = (nb + 63) / 64; d2.grid[1] = (T + 15) / 16; d2.tg[0] = 128; + if (bench) { + auto timeit = [&](const mtl::Dispatch& d) { + cx.warm({d}, 0.3); + std::vector t; + for (int i = 0; i < 5; ++i) t.push_back(cx.run({d})); + return median(t); + }; + std::printf("score pos0 %u, T %d: qsa_score %.2f ms, qsa_score_mm %.2f ms\n", pos0, T, timeit(d1) * 1e3, timeit(d2) * 1e3); + } else { + cx.run({d1}); + cx.run({d2}); + double worst = 0; + for (int t = 0; t < T; ++t) { + const uint32_t nbid = (pos0 + t + 1) / 4; + for (uint32_t b = 0; b <= nbid; ++b) { + const double x = sa.as()[(size_t)t * MB + b], y = sb.as()[(size_t)t * MB + b]; + worst = std::max(worst, std::fabs(x - y) / (std::fabs(x) + 1.0)); // scores are O(10) + } + } + const bool ok = worst < 1e-5; + fails += !ok; + std::printf("score pos0 %u, T %d: qsa_score_mm vs qsa_score worst rel %.2e %s\n", pos0, T, worst, ok ? "PASS" : "FAIL"); + } + } + if (!bench) std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS"); + return fails ? 1 : 0; +} diff --git a/metal/tests/ref_dump.cpp b/metal/tests/ref_dump.cpp new file mode 100644 index 00000000..3cce42e6 --- /dev/null +++ b/metal/tests/ref_dump.cpp @@ -0,0 +1,30 @@ +// metal/tests/ref_dump.cpp - writes random blocks of every type ref_quant knows and their CPU-reference dequant, so +// that the reference itself can be checked against gguf-py (metal/tools/check_ref.py): +// ref_dump -> /.bin (raw blocks, 16 rows x 2560) and /.f32 +#include "ref_quant.h" + +#include +#include +#include + +int main(int argc, char** argv) { + const std::string dir = argc > 1 ? argv[1] : "."; + const int rows = 16, cols = 2560; + for (int t : {ref::Q2_0, ref::Q4_0, ref::Q5_0, ref::Q8_0, ref::Q3_K, ref::Q4_K, ref::Q5_K, ref::Q6_K, ref::IQ2_XXS, + ref::IQ2_XS, ref::IQ2_S, ref::IQ3_XXS, ref::IQ3_S, ref::IQ4_NL, ref::IQ4_XS, ref::BF16, ref::F16}) { + const size_t rb = ref::row_bytes(t, cols); + std::vector raw(rb * rows); + ref::random_blocks(t, raw.data(), rows, cols, 77 + t); + std::vector f((size_t)rows * cols); + ref::dequant(t, raw.data(), f.data(), f.size()); + const std::string n = dir + "/" + ref::type_name(t); + FILE* a = std::fopen((n + ".bin").c_str(), "wb"); + FILE* b = std::fopen((n + ".f32").c_str(), "wb"); + std::fwrite(raw.data(), 1, raw.size(), a); + std::fwrite(f.data(), 4, f.size(), b); + std::fclose(a); + std::fclose(b); + } + std::printf("wrote %s\n", dir.c_str()); + return 0; +} diff --git a/metal/tests/route_parity.cpp b/metal/tests/route_parity.cpp new file mode 100644 index 00000000..2f72329a --- /dev/null +++ b/metal/tests/route_parity.cpp @@ -0,0 +1,90 @@ +// metal/tests/route_parity.cpp - moe_route (softmax + top-10 + the expert plan) against a CPU replica of +// native_router.cu's rule, for 1..8 tokens; logits with deliberate ties. +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { +constexpr int P_NG = 0, P_MAXE = 128, P_GEXP = 16, P_GSTART = P_GEXP + P_MAXE, P_ETOK = P_GSTART + P_MAXE + 4, + P_EW = P_ETOK + P_MAXE, P_TOKENT = P_EW + P_MAXE, P_INTS = P_TOKENT + P_MAXE; +struct MoeArgs { + uint64_t gate_off, up_off, down_off, gu_stride, d_stride; + uint32_t gu_row, d_row, n_embd, n_ff, n_tok, topk, n_expert, gx_gu, gx_dn, pad; +}; +} // namespace + +int main() { + mtl::Context cx; + const int lib = cx.compile({"quant.metal", "units.metal", "moe.metal"}); + mtl::Pipeline p = cx.pipeline(lib, "moe_route"); + mtl::Buffer lg = cx.alloc(4 * 8 * 512), ids = cx.alloc(4 * 80), w = cx.alloc(4 * 80), plan = cx.alloc(4 * P_INTS); + ref::Rng r(9); + int fails = 0; + double worst_w = 0; + for (int trial = 0; trial < 200; ++trial) { + const int nt = 1 + trial % 8; + for (int i = 0; i < nt * 512; ++i) { + float v = r.sym() * 4.0f; + if (trial % 3 == 0) v = std::round(v * 4.0f) / 4.0f; // many exact ties + lg.as()[i] = v; + } + MoeArgs a{}; + a.n_tok = nt; + a.topk = 10; + a.n_expert = 512; + a.gx_gu = 1; + a.gx_dn = 1; + mtl::Dispatch d; + d.p = &p; + d.args = {mtl::Arg::B(lg), mtl::Arg::B(ids), mtl::Arg::B(w), mtl::Arg::B(plan), mtl::Arg::V(a)}; + d.tg[0] = 512; + cx.run({d}); + for (int t = 0; t < nt; ++t) { + const float* l = lg.as() + t * 512; + float mx = -INFINITY; + for (int e = 0; e < 512; ++e) mx = std::max(mx, l[e]); + std::vector pr(512); + double s = 0; + for (int e = 0; e < 512; ++e) s += (pr[e] = std::exp((double)l[e] - mx)); + for (int e = 0; e < 512; ++e) pr[e] /= s; + // top 10: largest probability, ties -> lower index (probabilities of equal logits are equal) + std::vector order(512); + for (int e = 0; e < 512; ++e) order[e] = e; + std::stable_sort(order.begin(), order.end(), [&](int x, int y) { return l[x] > l[y]; }); + double ssum = 0; + for (int k = 0; k < 10; ++k) ssum += pr[order[k]]; + for (int k = 0; k < 10; ++k) { + if (ids.as()[t * 10 + k] != order[k]) { ++fails; break; } + const double ref = pr[order[k]] / std::max(ssum, 6.103515625e-5); + worst_w = std::max(worst_w, std::fabs(w.as()[t * 10 + k] - ref) / ref); + } + } + // the plan + const int* P = plan.as(); + std::set distinct(ids.as(), ids.as() + nt * 10); + bool ok = P[P_NG] == (int)distinct.size(); + int gi = 0; + for (int e : distinct) { + if (P[P_GEXP + gi] != e) ok = false; + int j = P[P_GSTART + gi]; + for (int i = 0; i < nt * 10; ++i) + if (ids.as()[i] == e) { + if (P[P_ETOK + j] != i / 10 || P[P_TOKENT + i] != j) ok = false; + ++j; + } + if (j != P[P_GSTART + gi + 1]) ok = false; + ++gi; + } + fails += !ok; + } + std::printf("route parity, 200 windows of 1..8 tokens (a third with exact ties): ids/plan mismatches %d, worst weight " + "rel err %.2e %s\n", fails, worst_w, fails == 0 && worst_w < 2e-6 ? "PASS" : "FAIL"); + return fails ? 1 : 0; +} diff --git a/metal/tests/rt_bench.cpp b/metal/tests/rt_bench.cpp new file mode 100644 index 00000000..9fc49ff7 --- /dev/null +++ b/metal/tests/rt_bench.cpp @@ -0,0 +1,238 @@ +// metal/tests/rt_bench.cpp - the M-series GPU's achievable read bandwidth and the cost of a dispatch. +// +// rt_bench bw [MiB] streaming read kernels over a buffer (default 2048 MiB, far beyond the SLC), per +// threadgroup size and grid size; read+write (copy); small sizes (cache-resident) +// rt_bench dispatch empty / dependent / small kernels: N dispatches in one serial or concurrent encoder, +// with or without barriers, through an indirect command buffer, and one command buffer +// per dispatch (commit + wait round trip) +#include "mtl_rt.h" + +#include +#include +#include +#include +#include +#include + +static double median(std::vector v) { + std::sort(v.begin(), v.end()); + return v[v.size() / 2]; +} + +template static void timed(int warm, int reps, F f, double& med, double& best) { + for (int i = 0; i < warm; ++i) f(); + std::vector t; + for (int i = 0; i < reps; ++i) t.push_back(f()); + med = median(t); + best = *std::min_element(t.begin(), t.end()); +} + +static void bw(mtl::Context& cx, int lib, size_t mib) { + const size_t bytes = mib << 20; + mtl::Buffer src = cx.alloc(bytes); + for (size_t i = 0; i < bytes / 4; ++i) src.as()[i] = (uint32_t)(i * 2654435761u); + mtl::Buffer out = cx.alloc(64u << 20); + const uint32_t n = (uint32_t)(bytes / 16); + mtl::Pipeline pr = cx.pipeline(lib, "k_read"), pu = cx.pipeline(lib, "k_read_u4"), + pc = cx.pipeline(lib, "k_read_chunk"); + std::printf("buffer %zu MiB; k_read max threads %d, simd width %d\n", mib, pr.max_threads, pr.simd_width); + std::printf("%-12s %6s %8s %10s %10s\n", "kernel", "tg", "groups", "GB/s med", "GB/s best"); + double best_all = 0; + std::string best_cfg; + for (const mtl::Pipeline* p : {&pr, &pu}) { + for (uint32_t tg : {64u, 128u, 256u, 512u, 1024u}) { + if ((int)tg > p->max_threads) continue; + for (uint32_t groups : {80u, 160u, 320u, 640u, 1280u, 2560u, 5120u}) { + if ((size_t)groups * tg * 4 > out.bytes) continue; + mtl::Dispatch d; + d.p = p; + d.args = {mtl::Arg::B(src), mtl::Arg::B(out), mtl::Arg::V(n)}; + d.grid[0] = groups; + d.tg[0] = tg; + double med, best; + timed(2, 7, [&] { return cx.run({d}); }, med, best); + const double gm = bytes / med / 1e9, gb = bytes / best / 1e9; + std::printf("%-12s %6u %8u %10.1f %10.1f\n", p == &pr ? "read" : "read_u4", tg, groups, gm, gb); + if (gm > best_all) { + best_all = gm; + best_cfg = std::string(p == &pr ? "read" : "read_u4") + " tg " + std::to_string(tg) + " groups " + + std::to_string(groups); + } + } + } + } + // contiguous chunk per threadgroup + for (uint32_t tg : {256u, 512u, 1024u}) { + for (uint32_t chunk_kib : {16u, 64u, 256u, 1024u}) { + const uint32_t chunk = chunk_kib * 1024 / 16; + const uint32_t groups = (n + chunk - 1) / chunk; + if ((size_t)groups * tg * 4 > out.bytes) continue; + mtl::Dispatch d; + d.p = &pc; + d.args = {mtl::Arg::B(src), mtl::Arg::B(out), mtl::Arg::V(n), mtl::Arg::V(chunk)}; + d.grid[0] = groups; + d.tg[0] = tg; + double med, best; + timed(2, 7, [&] { return cx.run({d}); }, med, best); + const double gm = bytes / med / 1e9; + std::printf("chunk %4uK %6u %8u %10.1f %10.1f\n", chunk_kib, tg, groups, gm, bytes / best / 1e9); + if (gm > best_all) { + best_all = gm; + best_cfg = "chunk " + std::to_string(chunk_kib) + "K tg " + std::to_string(tg); + } + } + } + std::printf("BEST read: %.1f GB/s (%s)\n", best_all, best_cfg.c_str()); + + // read + write + { + mtl::Buffer dst = cx.alloc(bytes / 2); + mtl::Pipeline pk = cx.pipeline(lib, "k_copy"); + const uint32_t nn = (uint32_t)(bytes / 2 / 16); + double bestc = 0; + for (uint32_t tg : {256u, 1024u}) + for (uint32_t groups : {640u, 2560u}) { + mtl::Dispatch d; + d.p = &pk; + d.args = {mtl::Arg::B(src), mtl::Arg::B(dst), mtl::Arg::V(nn)}; + d.grid[0] = groups; + d.tg[0] = tg; + double med, best; + timed(2, 7, [&] { return cx.run({d}); }, med, best); + bestc = std::max(bestc, (double)bytes / med / 1e9); + } + std::printf("BEST copy (read+write, both counted): %.1f GB/s\n", bestc); + cx.free(dst); + } + // cache-resident sizes: the same kernel on a small prefix + for (size_t kib : {1024ul, 4096ul, 16384ul, 32768ul, 65536ul, 131072ul, 262144ul}) { + if (kib * 1024 > bytes) break; + const uint32_t nn = (uint32_t)(kib * 1024 / 16); + double bestg = 0; + for (uint32_t groups : {160u, 640u, 2560u}) { + mtl::Dispatch d; + d.p = &pu; + d.args = {mtl::Arg::B(src), mtl::Arg::B(out), mtl::Arg::V(nn)}; + d.grid[0] = groups; + d.tg[0] = 256; + // many repetitions in one command buffer, so the launch is amortised + const int reps = (int)std::max(1, (256ul << 10) / kib * 4); + double med, best; + timed(1, 5, [&] { return cx.run({d}, reps) / reps; }, med, best); + bestg = std::max(bestg, kib * 1024.0 / med / 1e9); + } + std::printf("resident %7zu KiB: %.1f GB/s\n", kib, bestg); + } + cx.free(src); + cx.free(out); +} + +// A read of `kib` from DRAM per dispatch (each dispatch a different, uncached chunk of a 4 GiB buffer), dependent +// dispatches in one serial encoder: the bound for a kernel that streams that much once. +static void bwsize(mtl::Context& cx, int lib) { + const size_t big = 4ull << 30; + mtl::Buffer src = cx.alloc(big), out = cx.alloc(64u << 20); + mtl::Pipeline pr = cx.pipeline(lib, "k_read"); + std::printf("%10s %8s %10s %10s\n", "chunk KiB", "tg x grp", "us/disp", "GB/s"); + for (size_t kib : {1152ul, 2304ul, 4500ul, 9000ul, 13500ul, 18000ul, 36000ul, 72000ul}) { + const size_t bytes = kib * 1024; + const int R = (int)std::min(400, big / bytes); + double bestt = 1e9; + uint32_t bg = 0, btg = 0; + for (uint32_t tg : {256u, 1024u}) + for (uint32_t groups : {80u, 160u, 320u, 640u, 1280u}) { + std::vector ds; + const uint32_t n = (uint32_t)(bytes / 16); + for (int r = 0; r < R; ++r) { + mtl::Dispatch d; + d.p = ≺ + d.args = {mtl::Arg::B(src, (size_t)r * ((big / R) & ~4095ull)), mtl::Arg::B(out), mtl::Arg::V(n)}; + d.grid[0] = groups; + d.tg[0] = tg; + ds.push_back(d); + } + double med, best; + timed(1, 5, [&] { return cx.run(ds) / R; }, med, best); + if (med < bestt) { bestt = med; bg = groups; btg = tg; } + } + std::printf("%10zu %4ux%-4u %10.2f %10.1f\n", kib, btg, bg, bestt * 1e6, bytes / bestt / 1e9); + } + cx.free(src); + cx.free(out); +} + +static void dispatch(mtl::Context& cx, int lib) { + mtl::Buffer buf = cx.alloc(1 << 20), x = cx.alloc(4 * 2560), y = cx.alloc(4 * 2560); + mtl::Pipeline pe = cx.pipeline(lib, "k_empty"), pch = cx.pipeline(lib, "k_chain"), ps = cx.pipeline(lib, "k_small"); + auto mk = [&](const mtl::Pipeline& p, int kind) { + mtl::Dispatch d; + d.p = &p; + if (kind == 2) { + d.args = {mtl::Arg::B(x), mtl::Arg::B(y)}; + d.grid[0] = 10; + d.tg[0] = 256; + } else { + d.args = {mtl::Arg::B(buf)}; + d.grid[0] = 1; + d.tg[0] = 32; + } + return d; + }; + const int N = 2000; + struct K { const char* name; const mtl::Pipeline* p; int kind; } ks[] = { + {"empty", &pe, 0}, {"chain", &pch, 1}, {"small", &ps, 2}}; + std::printf("%-8s %-36s %10s\n", "kernel", "mode", "us/dispatch"); + for (const K& k : ks) { + std::vector ds(N, mk(*k.p, k.kind)); + double med, best; + timed(2, 7, [&] { return cx.run(ds, 1, false, false); }, med, best); + std::printf("%-8s %-36s %10.2f\n", k.name, "serial encoder", med / N * 1e6); + timed(2, 7, [&] { return cx.run(ds, 1, true, false); }, med, best); + std::printf("%-8s %-36s %10.2f\n", k.name, "concurrent encoder, no barrier", med / N * 1e6); + timed(2, 7, [&] { return cx.run(ds, 1, true, true); }, med, best); + std::printf("%-8s %-36s %10.2f\n", k.name, "concurrent encoder + barrier each", med / N * 1e6); + timed(2, 7, [&] { return cx.run(ds, 1, false, true); }, med, best); + std::printf("%-8s %-36s %10.2f\n", k.name, "serial encoder + barrier each", med / N * 1e6); + timed(2, 7, [&] { return cx.run_icb(ds, 1, false); }, med, best); + std::printf("%-8s %-36s %10.2f\n", k.name, "ICB, no barrier", med / N * 1e6); + timed(2, 7, [&] { return cx.run_icb(ds, 1, true); }, med, best); + std::printf("%-8s %-36s %10.2f\n", k.name, "ICB + barrier each", med / N * 1e6); + } + // command buffer round trips + { + std::vector one(1, mk(pe, 0)); + double gpu = 0; + const int R = 300; + cx.run_wall(one, 20); + const double wall = cx.run_wall(one, R, &gpu); + std::printf("%-8s %-36s %10.2f (GPU %.2f us)\n", "empty", "1 cmdbuf/dispatch, commit+wait wall", wall / R * 1e6, + gpu / R * 1e6); + std::vector d100(100, mk(pe, 0)); + const double wall2 = cx.run_wall(d100, 100, &gpu); + std::printf("%-8s %-36s %10.2f (GPU %.2f us)\n", "empty", "100 dispatches/cmdbuf, wall per cb", wall2 / 100 * 1e6, + gpu / 100 * 1e6); + } + // the fixed cost of one command buffer as seen by the GPU timer (1 dispatch) + { + std::vector one(1, mk(pe, 0)); + double med, best; + timed(5, 21, [&] { return cx.run(one); }, med, best); + std::printf("%-8s %-36s %10.2f\n", "empty", "single dispatch cmdbuf GPU time", med * 1e6); + } + cx.free(buf); + cx.free(x); + cx.free(y); +} + +int main(int argc, char** argv) { + mtl::Context cx; + std::printf("device: %s apple9 %d apple10 %d metal4 %d working set %.1f GiB\n", cx.device_name().c_str(), + cx.has_family_apple(9), cx.has_family_apple(10), cx.supports_metal4(), + cx.recommended_working_set() / 1073741824.0); + const int lib = cx.compile({"rt_bench.metal"}, "#define NO_GGML_COMMON 1\n"); + const std::string mode = argc > 1 ? argv[1] : "all"; + if (mode == "bw" || mode == "all") bw(cx, lib, argc > 2 ? std::strtoul(argv[2], nullptr, 10) : 2048); + if (mode == "dispatch" || mode == "all") dispatch(cx, lib); + if (mode == "bwsize" || mode == "all") bwsize(cx, lib); + return 0; +} diff --git a/metal/tests/runtime_hello.cpp b/metal/tests/runtime_hello.cpp new file mode 100644 index 00000000..eee9e5f1 --- /dev/null +++ b/metal/tests/runtime_hello.cpp @@ -0,0 +1,162 @@ +// metal/tests/runtime_hello.cpp - the Metal runtime end to end, with the shared src/core/graph.cpp built unchanged: +// 1. gpu::malloc_device / host_alloc (mapped) / memcpy_async / a kernel through metal::dispatch / events / D2H +// 2. the SHARED host file src/core/graph.cpp (CapturedGraph / GraphRegistry), compiled unchanged for Metal: +// capture a 3-kernel "window", replay it 5 times, wait with wait_ms (event query polling), check the data path +// is live (each replay reads the buffers' current contents, as a CUDA graph does) +// 3. host_device_pointer: a kernel writes a mapped host buffer that the host reads without a copy +// 4. the cost of replaying a 1,000-dispatch window +#include "strata/core/graph.hpp" +#include "strata/gpu/metal.hpp" +#include "strata/gpu/runtime.hpp" + +#include +#include +#include +#include +#include + +namespace gpu = strata::gpu; + +static const char* kSrc = R"MSL( +#include +using namespace metal; +struct Axpy { device const float* x; device float* y; float a; uint n; }; +kernel void axpy(constant Axpy& p [[buffer(0)]], uint i [[thread_position_in_grid]]) { + if (i < p.n) p.y[i] = p.a * p.x[i] + p.y[i]; +} +struct Scale { device float* y; device const float* s; uint n; }; // the factor is DATA (a device buffer), not an argument +kernel void scale(constant Scale& p [[buffer(0)]], uint i [[thread_position_in_grid]]) { + if (i < p.n) p.y[i] *= p.s[0]; +} +)MSL"; +struct Axpy { uint64_t x, y; float a; uint32_t n; }; +struct Scale { uint64_t y, s; uint32_t n; }; + +static int g_fail = 0; +#define CHECK(c, ...) do { if (!(c)) { std::printf("FAIL %s:%d: ", __FILE__, __LINE__); std::printf(__VA_ARGS__); std::printf("\n"); ++g_fail; } } while (0) + +static double now_ms() { + return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); +} + +int main() { + std::string err; + MTL::ComputePipelineState* p_axpy = gpu::metal::pipeline("hello", kSrc, "axpy", err); + MTL::ComputePipelineState* p_scale = gpu::metal::pipeline("hello", kSrc, "scale", err); + CHECK(p_axpy && p_scale, "pipelines: %s", err.c_str()); + if (!p_axpy || !p_scale) return 1; + const uint32_t N = 1 << 16; + const gpu::metal::Grid groups{(N + 255) / 256, 1, 1}, threads{256, 1, 1}; + + gpu::Stream s = nullptr, s2 = nullptr; + CHECK(gpu::stream_create(&s, gpu::kStreamNonBlocking) == gpu::kSuccess, "stream"); + CHECK(gpu::stream_create(&s2, gpu::kStreamNonBlocking) == gpu::kSuccess, "stream 2"); + float *dx = nullptr, *dy = nullptr, *ds = nullptr, *hx = nullptr; + CHECK(gpu::malloc_device((void**) &dx, N * 4) == gpu::kSuccess, "malloc x"); + CHECK(gpu::malloc_device((void**) &dy, N * 4) == gpu::kSuccess, "malloc y"); + CHECK(gpu::malloc_device((void**) &ds, 4) == gpu::kSuccess, "malloc s"); + CHECK(gpu::host_alloc((void**) &hx, N * 4, gpu::kHostAllocMapped) == gpu::kSuccess, "host_alloc"); + CHECK(gpu::host_view(dx) != nullptr && gpu::host_view(dx) != (void*) dx, "a device pointer is a GPU address, not the CPU view"); + + // ---- 1. copies, a kernel, an event across two streams, D2H + std::vector x(N), y(N, 1.0f), got(N); + for (uint32_t i = 0; i < N; ++i) x[i] = (float) (i % 1000); + std::memcpy(hx, x.data(), N * 4); + gpu::memcpy_async(dx, hx, N * 4, gpu::kHostToDevice, s); // mapped host buffer -> device: a blit + gpu::memcpy_async(dy, y.data(), N * 4, gpu::kHostToDevice, s); // pageable -> device + Axpy a{(uint64_t) dx, (uint64_t) dy, 2.0f, N}; + gpu::metal::dispatch(s, p_axpy, &a, sizeof a, groups, threads); + gpu::Event ev = nullptr; + gpu::event_create(&ev, gpu::kEventDisableTiming); + gpu::event_record(ev, s); + gpu::stream_wait_event(s2, ev); // s2's kernel runs after s's + Axpy a2{(uint64_t) dx, (uint64_t) dy, 1.0f, N}; + gpu::metal::dispatch(s2, p_axpy, &a2, sizeof a2, groups, threads); + gpu::memcpy_async(got.data(), dy, N * 4, gpu::kDeviceToHost, s2); + gpu::stream_synchronize(s2); + int bad = 0; + for (uint32_t i = 0; i < N; ++i) bad += got[i] != 3.0f * x[i] + 1.0f; + CHECK(bad == 0, "step 1: %d wrong values", bad); + std::printf("1. copies + kernel + cross-stream event + D2H: %s\n", bad ? "FAIL" : "OK"); + + // ---- 2. the shared CapturedGraph from src/core/graph.cpp + { + float one = 1.0f; + gpu::memcpy_sync(ds, &one, 4, gpu::kHostToDevice); + strata::core::CapturedGraph g; + CHECK(g.begin(s, err), "begin: %s", err.c_str()); + Axpy w{(uint64_t) dx, (uint64_t) dy, 1.0f, N}; + Scale sc{(uint64_t) dy, (uint64_t) ds, N}; + gpu::metal::dispatch(s, p_axpy, &w, sizeof w, groups, threads); + gpu::metal::dispatch(s, p_scale, &sc, sizeof sc, groups, threads); + gpu::metal::dispatch(s, p_axpy, &w, sizeof w, groups, threads); + CHECK(g.end(s, err), "end: %s", err.c_str()); + CHECK(g.nodes() == 3, "nodes %zu", g.nodes()); + // host model of y + std::vector m(N); + for (uint32_t i = 0; i < N; ++i) m[i] = got[i]; + bool all = true; + for (int rep = 0; rep < 5; ++rep) { + const float f = rep % 2 ? 0.5f : 2.0f; // the per-step value changes as DATA between replays + float* sv = (float*) gpu::host_view(ds); + gpu::stream_synchronize(s); + *sv = f; + CHECK(g.launch(s, err), "launch: %s", err.c_str()); + CHECK(g.wait_ms(2000), "wait_ms timed out"); + for (uint32_t i = 0; i < N; ++i) m[i] = ((m[i] + x[i]) * f) + x[i]; + } + gpu::memcpy_sync(got.data(), dy, N * 4, gpu::kDeviceToHost); + int wrong = 0; + for (uint32_t i = 0; i < N; ++i) wrong += got[i] != m[i]; + all = wrong == 0; + CHECK(all, "graph replays: %d wrong values", wrong); + std::printf("2. shared CapturedGraph (src/core/graph.cpp): 3-kernel window, 5 replays with live data: %s\n", all ? "OK" : "FAIL"); + + strata::core::GraphRegistry reg(s); + int bodies = 0; + for (int k = 0; k < 4; ++k) + CHECK(reg.record(strata::core::LayerType::GDN, 1, [&] { ++bodies; gpu::metal::dispatch(s, p_axpy, &w, sizeof w, groups, threads); }, err), + "record: %s", err.c_str()); + CHECK(bodies == 1 && reg.size() == 1, "registry captured %d bodies", bodies); + CHECK(reg.launch(strata::core::LayerType::GDN, 1, 2000, err), "registry launch: %s", err.c_str()); + std::printf(" GraphRegistry: body captured once over 4 records, launch+wait: %s\n", bodies == 1 ? "OK" : "FAIL"); + } + + // ---- 3. a mapped host buffer written by a kernel, read by the host with no copy + { + float* dview = nullptr; + CHECK(gpu::host_device_pointer((void**) &dview, hx) == gpu::kSuccess, "host_device_pointer"); + std::memset(hx, 0, N * 4); + Axpy w{(uint64_t) dx, (uint64_t) dview, 1.0f, N}; + gpu::metal::dispatch(s, p_axpy, &w, sizeof w, groups, threads); + gpu::stream_synchronize(s); + int wrong = 0; + for (uint32_t i = 0; i < N; ++i) wrong += hx[i] != x[i]; + CHECK(wrong == 0, "mapped: %d wrong", wrong); + std::printf("3. kernel -> mapped host buffer, host reads it in place: %s\n", wrong ? "FAIL" : "OK"); + } + + // ---- 4. replay cost of a 1,000-dispatch window + { + strata::core::CapturedGraph g; + Axpy w{(uint64_t) dx, (uint64_t) dy, 0.0f, 256}; + g.begin(s, err); + for (int k = 0; k < 1000; ++k) gpu::metal::dispatch(s, p_axpy, &w, sizeof w, gpu::metal::Grid{1, 1, 1}, threads); + g.end(s, err); + for (int rep = 0; rep < 5; ++rep) { + const double t0 = now_ms(); + g.launch(s, err); + const double t1 = now_ms(); + g.wait_ms(5000); + std::printf("4. 1000-dispatch window: replay (encode+commit) %.3f ms, until complete %.3f ms\n", t1 - t0, now_ms() - t0); + } + } + const auto st = gpu::metal::stats(); + std::printf("stats: %llu dispatches, %llu command buffers, %llu blits, %llu host syncs\n", (unsigned long long) st.dispatches, + (unsigned long long) st.command_buffers, (unsigned long long) st.blits, (unsigned long long) st.host_syncs); + gpu::free_device(dx); gpu::free_device(dy); gpu::free_device(ds); gpu::free_host(hx); + gpu::event_destroy(ev); + gpu::stream_destroy(s); gpu::stream_destroy(s2); + std::printf(g_fail ? "RESULT: %d FAILED\n" : "RESULT: all passed\n", g_fail); + return g_fail ? 1 : 0; +} diff --git a/metal/tests/sample_parity.cpp b/metal/tests/sample_parity.cpp new file mode 100644 index 00000000..049439af --- /dev/null +++ b/metal/tests/sample_parity.cpp @@ -0,0 +1,61 @@ +// metal/tests/sample_parity.cpp - greedy argmax (sample.metal) vs the CPU over 248,320 logits with planted ties, +// and its time. +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include + +int main() { + constexpr uint32_t V = 248320, PARTS = 120; + mtl::Context cx; + const int lib = cx.compile({"sample.metal"}, "#define NO_GGML_COMMON 1\n"); + mtl::Pipeline pp = cx.pipeline(lib, "argmax_part"), pf = cx.pipeline(lib, "argmax_final"); + const int MAXT = 8; + mtl::Buffer lg = cx.alloc(4 * (size_t)V * MAXT), pv = cx.alloc(4 * PARTS * MAXT), pi = cx.alloc(4 * PARTS * MAXT), + out = cx.alloc(4 * MAXT); + ref::Rng r(5); + int fails = 0; + struct A { uint32_t n_vocab, parts; } a{V, PARTS}; + for (int trial = 0; trial < 20; ++trial) { + const int nt = 1 + trial % MAXT; + for (size_t i = 0; i < (size_t)V * nt; ++i) lg.as()[i] = std::round(r.sym() * 1000.0f) / 100.0f; + for (int t = 0; t < nt; ++t) { + // plant a tie at the maximum + const size_t i1 = r.next() % V, i2 = r.next() % V; + lg.as()[t * V + i1] = 20.0f; + lg.as()[t * V + i2] = 20.0f; + } + mtl::Dispatch d1, d2; + d1.p = &pp; + d1.args = {mtl::Arg::B(lg), mtl::Arg::B(pv), mtl::Arg::B(pi), mtl::Arg::V(a)}; + d1.grid[0] = PARTS; + d1.grid[1] = nt; + d1.tg[0] = 256; + d2.p = &pf; + d2.args = {mtl::Arg::B(pv), mtl::Arg::B(pi), mtl::Arg::B(out), mtl::Arg::V(a)}; + d2.grid[0] = nt; + d2.tg[0] = 256; + cx.run({d1, d2}); + for (int t = 0; t < nt; ++t) { + const float* l = lg.as() + (size_t)t * V; + int best = 0; + for (uint32_t i = 1; i < V; ++i) + if (l[i] > l[best]) best = (int)i; + fails += out.as()[t] != best; + } + if (trial == 19) { + std::vector ds; + for (int k = 0; k < 64; ++k) { ds.push_back(d1); ds.push_back(d2); } + cx.warm(ds, 0.05); + std::vector ts; + for (int k = 0; k < 7; ++k) ts.push_back(cx.run(ds) / 64); + std::sort(ts.begin(), ts.end()); + std::printf("argmax %d token(s) over %u logits: %.2f us (2 dispatches)\n", nt, V, ts[3] * 1e6); + } + } + std::printf("argmax parity, 20 windows with planted ties: %d wrong %s\n", fails, fails ? "FAIL" : "PASS"); + return fails ? 1 : 0; +} diff --git a/metal/tests/token_chain.cpp b/metal/tests/token_chain.cpp new file mode 100644 index 00000000..a47c7630 --- /dev/null +++ b/metal/tests/token_chain.cpp @@ -0,0 +1,661 @@ +// metal/tests/token_chain.cpp - one decode step of the whole model, every kernel of metal/ on the REAL weights of a +// GGUF (mmapped, wrapped no-copy as one MTLBuffer), each layer with its own tensor formats, all dispatches in one +// command buffer: the GPU time of a decode token (or a verify window) with these kernels, dispatch boundaries +// included. Not a numerical check (the activations are synthetic): a timing of the real byte stream. +// +// token_chain [--ntok N] [--ctx P] [--reps R] [--skip-qsa] [--only CLASS] +// +// Left out: the PLE path (one table row and two small projections at one layer) and the MTP draft. +#include "gguf_lite.h" +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr int N = 2560, HC = 4, LR = 320, NFF = 640, TOPK = 10, NEXP = 512, MAXT = 8; +constexpr int P_MAXE = 128, P_GEXP = 16, P_GSTART = P_GEXP + P_MAXE, P_ETOK = P_GSTART + P_MAXE + 4, + P_EW = P_ETOK + P_MAXE, P_TOKENT = P_EW + P_MAXE, P_INTS = P_TOKENT + P_MAXE, P_IGU = 4, P_IDN = 8; +struct GemvArgs { uint32_t n_in, n_out, n_tok, row_bytes, x_stride, y_stride; }; +struct GrArgs { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; }; +struct GrArgs3 { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; uint32_t rb_down, rb_up, comb, topk; }; +struct MoeArgs { + uint64_t gate_off, up_off, down_off, gu_stride, d_stride; + uint32_t gu_row, d_row, n_embd, n_ff, n_tok, topk, n_expert, gx_gu, gx_dn, pad; +}; +struct GdnArgs { uint32_t h_k, h_v, channels, commit; float eps; uint32_t plane; }; +struct QsaArgs { uint32_t pos0, pos_base, max_cells, n_tok; float eps; }; +struct GlueArgs { uint32_t n, n_tok, n_embd, topk; }; +struct ArgArgs { uint32_t n_vocab, parts; }; + +int xkind(int t) { + switch (t) { + case ref::Q2_0: return 1; + case ref::Q4_K: case ref::Q5_K: return 2; + case ref::Q6_K: case ref::Q3_K: return 3; + default: return 0; + } +} +double median(std::vector v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; } + +// a prepared activation: 4 planes of n_tok rows of n, then the per-16 sums +struct Act { + mtl::Buffer b; + int n = 0; + size_t plane_bytes() const { return (size_t)4 * MAXT * n; } +}; + +} // namespace + +int main(int argc, char** argv) { + if (argc < 2) { std::fprintf(stderr, "usage: token_chain [--ntok N] [--ctx P] [--reps R]\n"); return 2; } + int ntok = 1, ctx = 1000, reps = 10; + bool skip_qsa = false, graph = false; + // the HC read: Q8_0 copies through the 3-dispatch read by default (the owner's decision, as STRATA_HC_Q8 on gfx12); + // STRATA_HC_Q8=0 selects the exact BF16 path. --hc 3: BF16, 3 dispatches; 2: BF16, 2 dispatches; q8: Q8_0 copies, + // 2 dispatches; q8_3: Q8_0 copies, 3 dispatches + const char* hcq8 = std::getenv("STRATA_HC_Q8"); + std::string hc_mode = hcq8 && std::string(hcq8) == "0" ? "3" : "q8_3"; + bool fuse = false; // the GDN y prep in the step; no QSA score/top-k within the selection budget + bool fold_comb = false; // the MoE combine folded into the next 2-dispatch HC read (measured slower) + std::string only, skip; + for (int i = 2; i < argc; ++i) { + std::string a = argv[i]; + if (a == "--ntok") ntok = std::atoi(argv[++i]); + else if (a == "--ctx") ctx = std::atoi(argv[++i]); + else if (a == "--reps") reps = std::atoi(argv[++i]); + else if (a == "--skip-qsa") skip_qsa = true; + else if (a == "--graph") graph = true; + else if (a == "--hc") hc_mode = argv[++i]; + else if (a == "--fuse") fuse = true; + else if (a == "--fold-comb") fold_comb = true; + else if (a == "--only") only = argv[++i]; + else if (a == "--skip") skip = argv[++i]; + } + gguf::File f; + std::string err; + if (!f.open(argv[1], err)) { std::fprintf(stderr, "%s\n", err.c_str()); return 2; } + mtl::Context cx; + std::printf("device %s; %s: %zu tensors, %.1f GB; %d token(s), context %d\n", cx.device_name().c_str(), + argv[1], f.tensors.size(), f.file_bytes / 1e9, ntok, ctx); + // fault the file in (page cache), then wrap it + { + const double t0 = mtl::now_s(); + madvise(f.map, f.map_bytes, MADV_WILLNEED); + volatile uint64_t s = 0; + for (size_t o = 0; o < f.file_bytes; o += 16384) s += ((const uint8_t*)f.map)[o]; + std::printf("file touched in %.1f s\n", mtl::now_s() - t0); + } + mtl::Buffer W = cx.wrap(f.map, f.map_bytes); + auto T = [&](const std::string& name) -> const gguf::Tensor& { + const gguf::Tensor* t = f.find(name); + if (!t) { std::fprintf(stderr, "missing tensor %s\n", name.c_str()); std::exit(2); } + return *t; + }; + + const int lib = cx.compile({"quant.metal", "units.metal", "moe.metal", "gemv.metal", "gr.metal", "gr2.metal", "glue.metal", + "router.metal"}); + const int lgdn = cx.compile({"gdn.metal"}, "#define NO_GGML_COMMON 1\n"); + const int lqsa = cx.compile({"qsa.metal", "qsa2.metal"}, "#define NO_GGML_COMMON 1\n"); + const int lsmp = cx.compile({"sample.metal"}, "#define NO_GGML_COMMON 1\n"); + std::map pcache; + + // ---- buffers + const int MAXC = std::max(4096, (ctx + 64) / 4 * 4 + 64), MB = MAXC / 4 + 2; + mtl::Buffer R = cx.alloc(4 * MAXT * HC * N), bo = cx.alloc(4 * MAXT * N), inj[2] = {cx.alloc(4 * MAXT * HC), cx.alloc(4 * MAXT * HC)}, + xn = cx.alloc(4 * MAXT * HC * N), lo = cx.alloc(4 * MAXT * LR), qkv = cx.alloc(4 * MAXT * 10240), + z = cx.alloc(4 * MAXT * 6144), al = cx.alloc(4 * MAXT * 48), be = cx.alloc(4 * MAXT * 48), + yg = cx.alloc(4 * MAXT * 6144), logits = cx.alloc(4 * MAXT * 512), ids = cx.alloc(4 * MAXT * TOPK), + wts = cx.alloc(4 * MAXT * TOPK), plan = cx.alloc(4 * P_INTS), h = cx.alloc(4 * MAXT * TOPK * NFF), + ye = cx.alloc(4 * MAXT * TOPK * N), gsh = cx.alloc(4 * MAXT * NFF), ush = cx.alloc(4 * MAXT * NFF), + ysh = cx.alloc(4 * MAXT * N), sg = cx.alloc(4 * MAXT * 4), qfull = cx.alloc(4 * MAXT * 12288), + kcur = cx.alloc(4 * MAXT * 512), vcur = cx.alloc(4 * MAXT * 512), iqr = cx.alloc(4 * MAXT * 512), + ikr = cx.alloc(4 * MAXT * 128), qcur = cx.alloc(4 * MAXT * 24 * 256), qidx = cx.alloc(4 * MAXT * 4 * 128), + scores = cx.alloc(4 * (size_t)MAXT * MB), qids = cx.alloc(4 * MAXT * 2051), + part = cx.alloc(4 * (size_t)MAXT * 65 * 24 * 258), cs = cx.alloc(8 * (size_t)(MAXC + 16) * 32), + lm = cx.alloc(4 * (size_t)MAXT * 248320), apv = cx.alloc(4 * MAXT * 120), api = cx.alloc(4 * MAXT * 120), + tokout = cx.alloc(4 * MAXT); + auto act = [&](int n) { Act a; a.n = n; a.b = cx.alloc(4 * ((size_t)4 * MAXT * n + (size_t)MAXT * n / 16)); return a; }; + Act XA = act(N), XF = act(N), XY = act(6144), XQ = act(6144), XH = act(NFF); + for (size_t i = 0; i < R.bytes / 4; ++i) R.as()[i] = 0.01f * (float)((i * 2654435761u) % 200) - 1.0f; + for (int p = 0; p < MAXC + 16; ++p) + for (int i = 0; i < 32; ++i) { + const double th = (double)p * std::pow(1e7, -2.0 * i / 64.0); + cs.as()[(p * 32 + i) * 2] = (float)std::cos(th); + cs.as()[(p * 32 + i) * 2 + 1] = (float)std::sin(th); + } + // per-layer recurrent state and QSA caches + std::vector gst, ghist, ghist2, kq, vq, ksc, vsc, tail, dead, pooled; + for (int l = 0; l < 48; ++l) { + if (l % 4 != 3) { + gst.push_back(cx.alloc(4 * 128 * 48 * 128)); + ghist.push_back(cx.alloc(4 * 10240 * 3)); + ghist2.push_back(cx.alloc(4 * 10240 * 3)); + } else { + kq.push_back(cx.alloc((size_t)MAXC * 2 * 256)); + vq.push_back(cx.alloc((size_t)MAXC * 2 * 256)); + ksc.push_back(cx.alloc(2 * (size_t)MAXC * 2 * 4)); + vsc.push_back(cx.alloc(2 * (size_t)MAXC * 2 * 4)); + tail.push_back(cx.alloc(4 * 4 * 128)); + dead.push_back(cx.alloc(4 * 128)); + pooled.push_back(cx.alloc(4 * (size_t)MB * 128)); + } + } + for (int t = 0; t < MAXT; ++t) + for (int c = 0; c < 2051; ++c) qids.as()[t * 2051 + c] = c; + for (auto& b : vsc) for (size_t i = 0; i < b.bytes / 2; ++i) b.as()[i] = 0x2000; // small fp16 scales + for (auto& b : ksc) for (size_t i = 0; i < b.bytes / 2; ++i) b.as()[i] = 0x2000; + + std::vector ds; + std::vector cls; // class of each dispatch (for --only) + std::map bytes_by; + bool nb = false; // the next push is independent of the previous dispatch (no barrier before it) + auto push = [&](const mtl::Dispatch& d0, const std::string& c, double bytes = 0) { + mtl::Dispatch d = d0; + d.barrier = !nb; + nb = false; + if (!only.empty() && c != only) return; + if (!skip.empty() && c == skip) return; + ds.push_back(d); + cls.push_back(c); + bytes_by[c] += bytes; + }; + // pipelines whose names do not match the function (cached by key): create by function name first + auto Pn = [&](int l, const std::string& fn, const std::string& key, const mtl::Constants& c) -> const mtl::Pipeline* { + auto it = pcache.find(key); + if (it == pcache.end()) it = pcache.emplace(key, cx.pipeline(l, fn, c)).first; + return &it->second; + }; + // ---- SLC prefetch (--prefetch): the next HC read's weights touched concurrently with the first projection GEMV + // after the current read, so the latency-bound read finds them in the SLC + const bool prefetch = std::getenv("CHAIN_PREFETCH") != nullptr; + const bool albe = std::getenv("CHAIN_ALBE") != nullptr; // ssm_alpha + ssm_beta as one gemv_cat + // the router GEMV + moe_route as one router_route (default; CHAIN_ROUTE=0: separate) + const bool routef = !(std::getenv("CHAIN_ROUTE") && std::string(std::getenv("CHAIN_ROUTE")) == "0"); + const bool combf = std::getenv("CHAIN_COMB") != nullptr; // the MoE combine folded into the next gr_norm + bool comb_pending = false; + // routed gate/up: the i-quant grids from constant memory (QUANT_CTAB, function constant 23; bitwise; default, + // CHAIN_CTAB=0: the threadgroup copy) + const bool ctabf = !(std::getenv("CHAIN_CTAB") && std::string(std::getenv("CHAIN_CTAB")) == "0"); + mtl::Buffer rcounter = cx.alloc(16); + struct Range { const mtl::Buffer* b; size_t off, bytes; }; + std::vector pending; + mtl::Buffer sink = cx.alloc(16); + const mtl::Pipeline* ptouch = nullptr; + auto push_prefetch = [&]() { + for (const Range& r : pending) { + const uint32_t n16 = (uint32_t)(r.bytes / 16); + mtl::Dispatch d; + d.p = ptouch; + d.args = {mtl::Arg::B(*r.b, r.off), mtl::Arg::B(sink), mtl::Arg::V(n16)}; + d.grid[0] = (n16 + 1023) / 1024; + d.tg[0] = 256; + nb = true; + push(d, "prefetch", (double)r.bytes); + } + pending.clear(); + }; + // ---- GEMV by tensor, with a tile from the measured table + auto gemv2 = [&](const gguf::Tensor& t, const Act& x, const mtl::Buffer& y, size_t y_stride, const std::string& c, + int ty_override = -1) { + const int n_in = (int)t.shape[0], n_out = t.shape.size() > 1 ? (int)t.shape[1] : 1; + const int ty = ty_override >= 0 ? ty_override : t.type; + int L = 16, Rr = 1, S = 4, K = 1; + if (n_in >= 6144) { L = 32; Rr = 1; S = 8; K = 2; } + else if (n_in == 640) { L = 8; Rr = 1; S = 4; K = 1; } + else if (n_out <= 640 || ty == ref::Q2_0 || ty == ref::BF16) { L = 32; Rr = 1; S = 4; K = 1; } + const std::string fn = "gemv_" + std::to_string(ty) + "_" + std::to_string(L) + "_" + std::to_string(Rr) + "_" + + std::to_string(S) + "_" + std::to_string(K); + const mtl::Pipeline* p = Pn(lib, fn, fn + "#" + std::to_string(ntok), mtl::Constants().i(0, ntok)); + GemvArgs a{(uint32_t)n_in, (uint32_t)n_out, (uint32_t)ntok, (uint32_t)ref::row_bytes(t.type, n_in), (uint32_t)n_in, + (uint32_t)y_stride}; + mtl::Dispatch d; + d.p = p; + d.args = {mtl::Arg::B(W, t.offset), mtl::Arg::B(x.b, x.plane_bytes() * xkind(ty)), mtl::Arg::B(x.b, x.plane_bytes() * 4), + mtl::Arg::B(y), mtl::Arg::V(a)}; + const int rpt = (S / K) * (32 / L) * Rr; + d.grid[0] = (n_out + rpt - 1) / rpt; + d.tg[0] = S * 32; + push(d, c, (double)t.bytes); + if (!pending.empty()) push_prefetch(); + }; + const mtl::Pipeline* pnorm = Pn(lib, "gr_norm", "gr_norm", {}); + const mtl::Pipeline* pnormc = Pn(lib, "gr_norm_comb", "gr_norm_comb", {}); + ptouch = Pn(lib, "slc_touch", "slc_touch", {}); + const mtl::Pipeline* pdown = Pn(lib, "gr_down_8_8", "gr_down_8_8", mtl::Constants().i(1, ntok)); + const mtl::Pipeline* pup = Pn(lib, "gr_up", "gr_up", mtl::Constants().i(1, ntok)); + const mtl::Pipeline* pdownq = Pn(lib, "gr_down_q8_8_8", "gr_down_q8_8_8", mtl::Constants().i(1, ntok)); + const mtl::Pipeline* pupq = Pn(lib, "gr_up_q8", "gr_up_q8", mtl::Constants().i(1, ntok)); + const mtl::Pipeline* pprep = Pn(lib, "xprep", "xprep", {}); + const mtl::Pipeline* proute = Pn(lib, "moe_route", "moe_route", {}); + const mtl::Pipeline* pswi = Pn(lib, "swiglu_prep", "swiglu_prep", {}); + const mtl::Pipeline* pcomb = Pn(lib, "moe_combine_sh", "moe_combine_sh", {}); + const mtl::Pipeline* pgdn = Pn(lgdn, "gdn_step", "gdn_step", mtl::Constants().i(2, ntok)); + const mtl::Pipeline* qprep = Pn(lqsa, "qsa_prep", "qsa_prep", {}); + const mtl::Pipeline* qscore = Pn(lqsa, "qsa_score", "qsa_score", {}); + const int qav = std::getenv("QSA_ATTN") ? std::atoi(std::getenv("QSA_ATTN")) : 1; + const bool qv2 = qav == 2; + const mtl::Pipeline* qtopk = Pn(lqsa, std::getenv("QSA_TOPK") ? "qsa_topk" : "qsa_topk2", "qsa_topk", {}); + const mtl::Pipeline* qattn = Pn(lqsa, qav == 1 ? "qsa_attn" : qv2 ? "qsa_attn2" : "qsa_attn3", "qsa_attn", {}); + const mtl::Pipeline* qmerge = Pn(lqsa, qv2 ? "qsa_merge2" : "qsa_merge", "qsa_merge", {}); + const mtl::Pipeline* pam1 = Pn(lsmp, "argmax_part", "argmax_part", {}); + const mtl::Pipeline* pam2 = Pn(lsmp, "argmax_final", "argmax_final", {}); + + // the 2-dispatch read: residual and partial-dot ping-pong buffers, rs; the Q8_0 copies of the HC matrices + mtl::Buffer Rb[2] = {R, cx.alloc(4 * MAXT * HC * N)}, Db[2] = {cx.alloc(4 * MAXT * (LR + HC) * HC), cx.alloc(4 * MAXT * (LR + HC) * HC)}, + rsb = cx.alloc(4 * MAXT * HC); + int cur_r = 0, cur_d = 0; + std::map q8off; + mtl::Buffer Q8; + if (hc_mode == "q8" || hc_mode == "q8_3") { + size_t tot = 0; + for (const auto& kv : f.tensors) { + const gguf::Tensor& t = kv.second; + if (t.type != ref::BF16 || t.name.find("hc_") == std::string::npos || t.name.find("_norm") != std::string::npos) continue; + uint64_t ne = 1; + for (uint64_t d : t.shape) ne *= d; + q8off[t.name] = tot; + tot += ne / 32 * 34; + } + Q8 = cx.alloc((tot + 4095) / 4096 * 4096); + const double t0 = mtl::now_s(); + std::vector tmp; + for (const auto& kv : q8off) { + const gguf::Tensor& t = *f.find(kv.first); + uint64_t ne = 1; + for (uint64_t d : t.shape) ne *= d; + tmp.resize(ne); + ref::dequant(ref::BF16, (const uint8_t*)f.map + t.offset, tmp.data(), ne); + ref::quantize_q8_0(tmp.data(), ne, Q8.as() + kv.second); + } + std::printf("HC Q8_0 copies: %zu tensors, %.1f MB, quantized in %.1f s\n", q8off.size(), tot / 1e6, mtl::now_s() - t0); + } + int cur_inj = 0; + auto gr_read = [&](const std::string& pre, bool apply, const Act& out, bool final_) { + if (hc_mode != "3" && hc_mode != "q8_3") { + const bool q8 = hc_mode == "q8"; + const gguf::Tensor& tn = T(pre + "_norm.weight"); + const gguf::Tensor& tdn = T(pre + "_down.weight"); + const gguf::Tensor& tup = T(pre + "_up.weight"); + const gguf::Tensor& tin = final_ ? tdn : T(pre + "_inject.weight"); + const int tt = std::min(ntok, 3); + const std::string dn = std::string("gr_down3_") + (q8 ? "8_" : "30_") + std::to_string(tt) + "_2"; + const std::string up = std::string("gr_up3_") + (q8 ? "8" : "30"); + // after an MoE (the next layer's mixer read, the final read) the combine is folded in here + const bool comb = fold_comb && apply && pre.find("hc_ffn") == std::string::npos; + GrArgs3 a{N, HC, LR, MAXT, apply ? 1u : 0u, 1e-6f, (uint32_t)(q8 ? HC * N / 32 * 34 : HC * N * 2), + (uint32_t)(q8 ? LR / 32 * 34 : LR * 2), comb ? 1u : 0u, (uint32_t)TOPK}; + const mtl::Buffer& WB = q8 ? Q8 : W; + const size_t od = q8 ? q8off.at(tdn.name) : tdn.offset, oi = q8 ? q8off.at(tin.name) : tin.offset, + ou = q8 ? q8off.at(tup.name) : tup.offset; + mtl::Dispatch d; + d.p = Pn(lib, dn, dn + "#" + std::to_string(ntok), mtl::Constants().i(1, ntok)); + d.args = {mtl::Arg::B(WB, od), mtl::Arg::B(WB, oi), mtl::Arg::B(Rb[cur_r]), mtl::Arg::B(Rb[1 - cur_r]), + mtl::Arg::B(bo), mtl::Arg::B(Db[cur_d]), mtl::Arg::B(W, tn.offset), mtl::Arg::B(Db[1 - cur_d]), + mtl::Arg::B(rsb), mtl::Arg::V(a), mtl::Arg::B(plan), mtl::Arg::B(ye), mtl::Arg::B(ysh), mtl::Arg::B(sg)}; + d.grid[0] = (LR + HC + 15) / 16; + d.grid[1] = HC; + d.tg[0] = 256; + const double wb = q8 ? (tdn.bytes + (final_ ? 0 : tin.bytes)) * 34.0 / 64.0 : (double)tdn.bytes + (final_ ? 0 : tin.bytes); + push(d, "hc", wb); + cur_r = 1 - cur_r; + cur_d = 1 - cur_d; + mtl::Dispatch u; + u.p = Pn(lib, up, up + "#" + std::to_string(ntok), mtl::Constants().i(1, ntok)); + u.args = {mtl::Arg::B(WB, ou), mtl::Arg::B(Db[cur_d]), mtl::Arg::B(Rb[cur_r]), mtl::Arg::B(out.b), mtl::Arg::V(a), + mtl::Arg::B(W, tn.offset), mtl::Arg::B(rsb)}; + u.grid[0] = N / 16; + u.tg[0] = 256; + push(u, "hc", q8 ? tup.bytes * 34.0 / 64.0 : (double)tup.bytes); + return; + } + const gguf::Tensor& tn = T(pre + "_norm.weight"); + const gguf::Tensor& tdn = T(pre + "_down.weight"); + const gguf::Tensor& tup = T(pre + "_up.weight"); + const gguf::Tensor& tin = final_ ? tdn : T(pre + "_inject.weight"); + GrArgs a{N, HC, LR, (uint32_t)ntok, apply ? 1u : 0u, 1e-6f}; + const bool q83 = hc_mode == "q8_3"; + const mtl::Buffer& WB = q83 ? Q8 : W; + const size_t od = q83 ? q8off.at(tdn.name) : tdn.offset, oi = q83 ? q8off.at(tin.name) : tin.offset, + ou = q83 ? q8off.at(tup.name) : tup.offset; + mtl::Dispatch d1; + d1.p = pnorm; + d1.args = {mtl::Arg::B(R), mtl::Arg::B(bo), mtl::Arg::B(inj[cur_inj]), mtl::Arg::B(W, tn.offset), mtl::Arg::B(xn), + mtl::Arg::V(a)}; + if (comb_pending) { + // the MoE combine folded into this norm (gr_norm_comb; bitwise moe_combine_sh + gr_norm) + const uint32_t tk = TOPK; + d1.p = pnormc; + d1.args = {mtl::Arg::B(R), mtl::Arg::B(ye), mtl::Arg::B(inj[cur_inj]), mtl::Arg::B(W, tn.offset), mtl::Arg::B(xn), + mtl::Arg::V(a), mtl::Arg::B(plan), mtl::Arg::B(ysh), mtl::Arg::B(sg), mtl::Arg::V(tk)}; + comb_pending = false; + } + d1.grid[0] = HC; + d1.grid[1] = ntok; + d1.tg[0] = 256; + push(d1, "hc", 0); + mtl::Dispatch d2; + d2.p = q83 ? pdownq : pdown; + d2.args = {mtl::Arg::B(WB, od), mtl::Arg::B(WB, oi), mtl::Arg::B(xn), mtl::Arg::B(lo), + mtl::Arg::B(inj[1 - cur_inj]), mtl::Arg::V(a)}; + d2.grid[0] = LR + HC; + d2.tg[0] = 256; + push(d2, "hc", (double)tdn.bytes + (final_ ? 0 : tin.bytes)); + mtl::Dispatch d3; + d3.p = q83 ? pupq : pup; + d3.args = {mtl::Arg::B(WB, ou), mtl::Arg::B(lo), mtl::Arg::B(xn), mtl::Arg::B(out.b), mtl::Arg::V(a)}; + d3.grid[0] = N / 16; + d3.tg[0] = 256; + push(d3, "hc", (double)tup.bytes); + cur_inj = 1 - cur_inj; + if (prefetch && !final_) { + // the next read: blk.l.hc_attn -> blk.l.hc_ffn -> blk.(l+1).hc_attn ... -> output_hc + std::string nx; + const size_t at = pre.find(".hc_attn"); + if (at != std::string::npos) nx = pre.substr(0, at) + ".hc_ffn"; + else { + const int l = std::atoi(pre.c_str() + 4); + nx = l == 47 ? std::string("output_hc") : "blk." + std::to_string(l + 1) + ".hc_attn"; + } + const bool fin = nx == "output_hc"; + for (const std::string& part : fin ? std::vector{"_down", "_up"} + : std::vector{"_down", "_inject", "_up"}) { + const gguf::Tensor& tt = T(nx + part + ".weight"); + if (q83) { + uint64_t ne = 1; + for (uint64_t dd : tt.shape) ne *= dd; + pending.push_back({&Q8, q8off.at(tt.name), (size_t)(ne / 32 * 34) / 16 * 16}); + } else { + pending.push_back({&W, tt.offset, (size_t)tt.bytes / 16 * 16}); + } + } + } + }; + auto xprep = [&](const mtl::Buffer& x, const Act& out, int n, const std::string& c) { + mtl::Dispatch d; + d.p = pprep; + const uint32_t nn = n, nt = MAXT; + d.args = {mtl::Arg::B(x), mtl::Arg::B(out.b), mtl::Arg::V(nn), mtl::Arg::V(nt)}; + d.tg[0] = 256; + d.grid[0] = (n / 16 * MAXT + 255) / 256; + push(d, c, 0); + }; + // Every prepared activation has planes of MAXT rows (Act::plane_bytes); the producers that take a token count + // for the plane stride (gr_up, qsa_merge, swiglu_prep, xprep) are given MAXT there. + + int gi = 0, qi = 0; + for (int l = 0; l < 48; ++l) { + const std::string b = "blk." + std::to_string(l) + "."; + // ---- mixer + gr_read(b + "hc_attn", l > 0, XA, false); + if (l % 4 != 3) { + gemv2(T(b + "attn_qkv.weight"), XA, qkv, 10240, "gdn proj"); + nb = true; + gemv2(T(b + "attn_gate.weight"), XA, z, 6144, "gdn proj"); + nb = true; + if (albe) { + // ssm_alpha + ssm_beta in one dispatch (gemv_cat; bitwise the two GEMVs) + const gguf::Tensor &ta = T(b + "ssm_alpha.weight"), &tb = T(b + "ssm_beta.weight"); + const std::string fn = "gemvc_" + std::to_string(ta.type) + "_32_1_4"; + mtl::Dispatch d; + d.p = Pn(lib, fn, fn + "#" + std::to_string(ntok), mtl::Constants().i(0, ntok)); + GemvArgs ga{(uint32_t)N, 96, (uint32_t)ntok, (uint32_t)ref::row_bytes(ta.type, N), (uint32_t)N, 48}; + const uint32_t sp = 48; + d.args = {mtl::Arg::B(W, ta.offset), mtl::Arg::B(XA.b, XA.plane_bytes() * xkind(ta.type)), + mtl::Arg::B(XA.b, XA.plane_bytes() * 4), mtl::Arg::B(al), mtl::Arg::V(ga), mtl::Arg::B(W, tb.offset), + mtl::Arg::B(be), mtl::Arg::V(sp)}; + d.grid[0] = 96 / 4; + d.tg[0] = 128; + push(d, "gdn proj", (double)ta.bytes + tb.bytes); + } else { + gemv2(T(b + "ssm_alpha.weight"), XA, al, 48, "gdn proj"); + nb = true; + gemv2(T(b + "ssm_beta.weight"), XA, be, 48, "gdn proj"); + } + GdnArgs a{16, 48, 10240, 1, 1e-6f, fuse ? (uint32_t)(MAXT * 6144) : 0u}; + mtl::Dispatch d; + d.p = pgdn; + d.args = {mtl::Arg::B(gst[gi]), mtl::Arg::B(ghist[gi]), mtl::Arg::B(qkv), mtl::Arg::B(al), mtl::Arg::B(be), + mtl::Arg::B(z), mtl::Arg::B(W, T(b + "ssm_conv1d.weight").offset), mtl::Arg::B(W, T(b + "ssm_dt.bias").offset), + mtl::Arg::B(W, T(b + "ssm_a").offset), mtl::Arg::B(W, T(b + "ssm_norm.weight").offset), mtl::Arg::B(fuse ? XY.b : yg), + mtl::Arg::V(a), mtl::Arg::B(ghist2[gi])}; + d.grid[0] = 48; + d.tg[0] = 512; + push(d, "gdn step", 2.0 * 4 * 128 * 48 * 128); + if (!fuse) xprep(yg, XY, 6144, "gdn proj"); + gemv2(T(b + "ssm_out.weight"), XY, bo, N, "gdn proj"); + ++gi; + } else if (!skip_qsa) { + gemv2(T(b + "attn_q.weight"), XA, qfull, 12288, "qsa proj"); + nb = true; + gemv2(T(b + "attn_k.weight"), XA, kcur, 512, "qsa proj"); + nb = true; + gemv2(T(b + "attn_v.weight"), XA, vcur, 512, "qsa proj"); + nb = true; + gemv2(T(b + "indexer.q_proj.weight"), XA, iqr, 512, "qsa proj"); + nb = true; + gemv2(T(b + "indexer.k_proj.weight"), XA, ikr, 128, "qsa proj"); + QsaArgs a{(uint32_t)ctx, 0, (uint32_t)MAXC, (uint32_t)ntok, 1e-6f}; + mtl::Dispatch d; + d.p = qprep; + d.args = {mtl::Arg::B(qfull), mtl::Arg::B(kcur), mtl::Arg::B(vcur), mtl::Arg::B(iqr), mtl::Arg::B(ikr), + mtl::Arg::B(W, T(b + "attn_q_norm.weight").offset), mtl::Arg::B(W, T(b + "attn_k_norm.weight").offset), + mtl::Arg::B(W, T(b + "indexer.q_norm.weight").offset), mtl::Arg::B(W, T(b + "indexer.k_norm.weight").offset), + mtl::Arg::B(cs), mtl::Arg::B(qcur), mtl::Arg::B(qidx), mtl::Arg::B(kq[qi]), mtl::Arg::B(vq[qi]), + mtl::Arg::B(ksc[qi]), mtl::Arg::B(vsc[qi]), mtl::Arg::B(tail[qi]), mtl::Arg::B(dead[qi]), + mtl::Arg::B(pooled[qi]), mtl::Arg::V(a)}; + d.grid[0] = 33; + d.grid[1] = ntok; + d.tg[0] = 256; + push(d, "qsa attn", 0); + const bool sel = !(fuse && ctx + ntok <= 2051); // within the budget the selection is the identity + mtl::Dispatch s; + s.p = qscore; + s.args = {mtl::Arg::B(qidx), mtl::Arg::B(pooled[qi]), mtl::Arg::B(dead[qi]), mtl::Arg::B(scores), mtl::Arg::V(a)}; + s.grid[0] = ((ctx + ntok) / 4 + 1 + 7) / 8; + s.grid[1] = ntok; + s.tg[0] = 256; + if (sel) push(s, "qsa attn", 0); + mtl::Dispatch k; + k.p = qtopk; + k.args = {mtl::Arg::B(scores), mtl::Arg::B(qids), mtl::Arg::V(a)}; + k.grid[0] = ntok; + k.tg[0] = 1024; + if (sel) push(k, "qsa attn", 0); + mtl::Dispatch at; + at.p = qattn; + at.args = {mtl::Arg::B(qcur), mtl::Arg::B(kq[qi]), mtl::Arg::B(vq[qi]), mtl::Arg::B(ksc[qi]), mtl::Arg::B(vsc[qi]), + mtl::Arg::B(qids), mtl::Arg::B(part), mtl::Arg::V(a)}; + at.grid[0] = qv2 ? 65 : 33; + at.grid[1] = qv2 ? 4 : 2; + at.grid[2] = ntok; + at.tg[0] = 256; + push(at, "qsa attn", 2.0 * 2 * 512 * std::min(ctx, 2051)); + mtl::Dispatch m; + m.p = qmerge; + QsaArgs am = a; + am.n_tok = MAXT; // the plane stride (see above) + m.args = {mtl::Arg::B(part), mtl::Arg::B(qfull), mtl::Arg::B(XQ.b), mtl::Arg::V(am)}; + m.grid[0] = 24; + m.grid[1] = ntok; + m.tg[0] = 256; + push(m, "qsa attn", 0); + gemv2(T(b + "attn_output.weight"), XQ, bo, N, "qsa proj"); + ++qi; + } + // ---- MoE + gr_read(b + "hc_ffn", true, XF, false); + if (!routef) { + gemv2(T(b + "ffn_gate_inp.weight"), XF, logits, 512, "router"); + nb = true; + } + const bool pair = fuse && std::getenv("CHAIN_PAIR"); // measured slower (+0.11 ms): opt-in + if (pair) { + // the shared expert's gate + up + SwiGLU in one dispatch, h raw into XH's raw plane + const gguf::Tensor &tgs = T(b + "ffn_gate_shexp.weight"), &tus = T(b + "ffn_up_shexp.weight"); + const std::string fn = "gemv_pair_" + std::to_string(tgs.type) + "_" + std::to_string(tus.type); + mtl::Dispatch d; + d.p = Pn(lib, fn, fn + "#" + std::to_string(ntok), mtl::Constants().i(0, ntok)); + GemvArgs ga{(uint32_t)N, (uint32_t)NFF, (uint32_t)ntok, (uint32_t)ref::row_bytes(tgs.type, N), (uint32_t)N, + (uint32_t)NFF}; + const uint32_t rbu = (uint32_t)ref::row_bytes(tus.type, N); + d.args = {mtl::Arg::B(W, tgs.offset), mtl::Arg::B(XF.b, XF.plane_bytes() * xkind(tgs.type)), + mtl::Arg::B(W, tus.offset), mtl::Arg::B(XF.b, XF.plane_bytes() * xkind(tus.type)), + mtl::Arg::B(XF.b, XF.plane_bytes() * 4), mtl::Arg::B(XH.b), mtl::Arg::V(ga), mtl::Arg::V(rbu)}; + d.grid[0] = NFF / 4; + d.tg[0] = 128; + push(d, "shared", (double)tgs.bytes + tus.bytes); + } else { + gemv2(T(b + "ffn_gate_shexp.weight"), XF, gsh, NFF, "shared"); + nb = true; + gemv2(T(b + "ffn_up_shexp.weight"), XF, ush, NFF, "shared"); + } + nb = true; + gemv2(T(b + "ffn_gate_inp_shexp.weight"), XF, sg, 1, "shared"); + { + MoeArgs a{}; + const gguf::Tensor &tg_ = T(b + "ffn_gate_exps.weight"), &tu = T(b + "ffn_up_exps.weight"), + &td = T(b + "ffn_down_exps.weight"); + a.gate_off = tg_.offset; + a.up_off = tu.offset; + a.down_off = td.offset; + a.gu_row = (uint32_t)ref::row_bytes(tg_.type, N); + a.d_row = (uint32_t)ref::row_bytes(td.type, NFF); + a.gu_stride = (uint64_t)a.gu_row * NFF; + a.d_stride = (uint64_t)a.d_row * N; + a.n_embd = N; + a.n_ff = NFF; + a.n_tok = ntok; + a.topk = TOPK; + a.n_expert = NEXP; + // tiles (lanes per row, rows per lane, simdgroups): CHAIN_GU / CHAIN_DN / CHAIN_DN4 override + const bool dq2 = td.type == ref::Q2_0; + int gl = 32, gr = 1, gs = 4, dl = dq2 ? 8 : 4, dr = dq2 ? 1 : 2, ds_ = 4; + if (const char* e = std::getenv("CHAIN_GU")) std::sscanf(e, "%d,%d,%d", &gl, &gr, &gs); + if (const char* e = std::getenv(dq2 ? "CHAIN_DN" : "CHAIN_DN4")) std::sscanf(e, "%d,%d,%d", &dl, &dr, &ds_); + a.gx_gu = NFF / (gs * (32 / gl) * gr); + a.gx_dn = N / (ds_ * (32 / dl) * dr); + if (routef) { + // the router GEMV + moe_route in one dispatch (router_route; bitwise), concurrent with the shared GEMVs + const gguf::Tensor& tr = T(b + "ffn_gate_inp.weight"); + mtl::Dispatch r; + r.p = Pn(lib, "router_route_30", "router_route#" + std::to_string(ntok), mtl::Constants().i(0, ntok)); + GemvArgs ga{(uint32_t)N, 512, (uint32_t)ntok, (uint32_t)ref::row_bytes(tr.type, N), (uint32_t)N, 512}; + r.args = {mtl::Arg::B(W, tr.offset), mtl::Arg::B(XF.b, 0), mtl::Arg::B(XF.b, XF.plane_bytes() * 4), + mtl::Arg::B(logits), mtl::Arg::V(ga), mtl::Arg::B(ids), mtl::Arg::B(wts), mtl::Arg::B(plan), + mtl::Arg::V(a), mtl::Arg::B(rcounter)}; + r.grid[0] = 512 / 16; + r.tg[0] = 512; + nb = true; + push(r, "router", (double)tr.bytes); + } else { + mtl::Dispatch r; + r.p = proute; + r.args = {mtl::Arg::B(logits), mtl::Arg::B(ids), mtl::Arg::B(wts), mtl::Arg::B(plan), mtl::Arg::V(a)}; + r.tg[0] = 512; + push(r, "router", 0); + } + { + GlueArgs ga{NFF, MAXT, N, TOPK}; + mtl::Dispatch d; + d.p = pswi; + d.args = {mtl::Arg::B(gsh), mtl::Arg::B(ush), mtl::Arg::B(XH.b), mtl::Arg::V(ga)}; + d.grid[0] = NFF / 16; + d.grid[1] = ntok; + d.tg[0] = 16; + nb = true; + if (!pair) push(d, "shared", 0); + nb = false; + } + const std::string gun = "moe_gu_" + std::to_string(tg_.type) + "_" + std::to_string(gl) + "_" + + std::to_string(gr) + "_" + std::to_string(gs); + const std::string dnn = "moe_down_" + std::to_string(dq2 ? 142 : td.type) + "_" + std::to_string(dl) + "_" + + std::to_string(dr) + "_" + std::to_string(ds_); + mtl::Dispatch g; + g.p = Pn(lib, gun, gun + (ctabf ? "#ct" : ""), mtl::Constants().b(23, ctabf)); + g.args = {mtl::Arg::B(W), mtl::Arg::B(XF.b, XF.plane_bytes() * xkind(tg_.type)), mtl::Arg::B(h), mtl::Arg::B(plan), + mtl::Arg::V(a), mtl::Arg::B(XF.b, XF.plane_bytes() * 4)}; + g.tg[0] = 32 * gs; + g.indirect = &plan; + g.ind_off = P_IGU * 4; + push(g, "experts", 10.0 * ntok * 2 * a.gu_stride); + nb = true; + { + const gguf::Tensor& tds = T(b + "ffn_down_shexp.weight"); + // with --fuse h is raw: a Q2_0 down reads it through the raw-activation decoder (type 142) + gemv2(tds, XH, ysh, N, "shared", pair && tds.type == ref::Q2_0 ? 142 : -1); + } + mtl::Dispatch dd; + dd.p = Pn(lib, dnn, dnn, {}); + dd.args = {mtl::Arg::B(W), mtl::Arg::B(h), mtl::Arg::B(ye), mtl::Arg::B(plan), mtl::Arg::V(a), mtl::Arg::B(h)}; + dd.tg[0] = 32 * ds_; + dd.indirect = &plan; + dd.ind_off = P_IDN * 4; + push(dd, "experts", 10.0 * ntok * a.d_stride); + } + { + GlueArgs a{N, (uint32_t)ntok, N, TOPK}; + mtl::Dispatch d; + d.p = pcomb; + d.args = {mtl::Arg::B(ye), mtl::Arg::B(plan), mtl::Arg::B(ysh), mtl::Arg::B(sg), mtl::Arg::B(bo), mtl::Arg::V(a)}; + d.grid[0] = (ntok * N + 255) / 256; + d.tg[0] = 256; + if (combf && (hc_mode == "3" || hc_mode == "q8_3")) comb_pending = true; // folded into the next gr_norm + else if (!(fold_comb && hc_mode != "3")) push(d, "shared", 0); // else folded into the next HC read + } + } + // ---- the final mixer and the head + gr_read("output_hc", true, XA, true); + gemv2(T("output.weight"), XA, lm, 248320, "lm head"); + { + ArgArgs a{248320, 120}; + mtl::Dispatch d1, d2; + d1.p = pam1; + d1.args = {mtl::Arg::B(lm), mtl::Arg::B(apv), mtl::Arg::B(api), mtl::Arg::V(a)}; + d1.grid[0] = 120; + d1.grid[1] = ntok; + d1.tg[0] = 256; + push(d1, "lm head", 0); + d2.p = pam2; + d2.args = {mtl::Arg::B(apv), mtl::Arg::B(api), mtl::Arg::B(tokout), mtl::Arg::V(a)}; + d2.grid[0] = ntok; + d2.tg[0] = 256; + push(d2, "lm head", 0); + } + // the producers' plane stride must be MAXT rows: gr_up's and swiglu's args carry n_tok for the stride, so the + // gr_up launches above use a.n_tok = ntok - patch them to MAXT (the kernels loop over GR_NTOK tokens anyway) + for (auto& d : ds) + if (d.p == pup || d.p == pupq || d.p == pnorm || d.p == pdown || d.p == pdownq) { + GrArgs a; + std::memcpy(&a, d.args.back().bytes.data(), sizeof a); + if (d.p == pup || d.p == pupq) a.n_tok = MAXT; + std::memcpy(d.args.back().bytes.data(), &a, sizeof a); + } + + double total_bytes = 0; + for (auto& kv : bytes_by) total_bytes += kv.second; + std::printf("%zu dispatches; weight + state bytes %.1f MB\n", ds.size(), total_bytes / 1e6); + auto run = [&] { return graph ? cx.run_graph(ds) : cx.run(ds); }; + run(); + const double tw = mtl::now_s(); + while (mtl::now_s() - tw < 1.0) run(); + std::vector t; + for (int i = 0; i < reps; ++i) t.push_back(run()); + std::printf("HC read: %s\n", hc_mode == "3" ? "BF16, 3 dispatches" : hc_mode == "2" ? "BF16, 2 dispatches" : hc_mode == "q8_3" ? "Q8_0, 3 dispatches" : "Q8_0, 2 dispatches"); + std::printf("encoding: %s\n", graph ? "concurrent encoder, barriers at dependencies" : "serial encoder"); + const double m = median(t); + std::printf("decode step (%d token(s)): GPU %.3f ms (min %.3f, max %.3f) -> %.1f GB/s effective; %.1f tok/s if " + "every token were a window of %d\n", ntok, m * 1e3, *std::min_element(t.begin(), t.end()) * 1e3, + *std::max_element(t.begin(), t.end()) * 1e3, total_bytes / m / 1e9, ntok / m, ntok); + for (auto& kv : bytes_by) std::printf(" %-10s %8.1f MB\n", kv.first.c_str(), kv.second / 1e6); + return 0; +} diff --git a/metal/tools/chat_tokens.py b/metal/tools/chat_tokens.py new file mode 100644 index 00000000..8bbf2c11 --- /dev/null +++ b/metal/tools/chat_tokens.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +"""chat_tokens.py REPO TOKENIZER_DIR "question" : the token ids of a one-turn chat prompt (thinking off), comma +separated, for `strata generate --tokens` (the same template as the gates' rbench.py). +With --decode IDS instead of the question: the text of comma-separated ids.""" +import json, sys +from pathlib import Path + +repo, tdir = Path(sys.argv[1]), Path(sys.argv[2]) +sys.path.insert(0, str(repo / "tools")) +import strata_tokenizer as ST + +vocab = json.loads((tdir / "vocab.json").read_text(encoding="utf-8")) +toks = [None] * len(vocab) +for t, i in vocab.items(): + toks[i] = t +tok = ST.Tokenizer(toks, (tdir / "merges.txt").read_text(encoding="utf-8").split("\n"), + json.loads((tdir / "token_type.json").read_text())) +if sys.argv[3] == "--decode": + print(tok.decode([int(x) for x in sys.argv[4].replace(" ", "").split(",") if x])) +else: + ids = tok.encode("<|im_start|>user\n%s<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" % sys.argv[3], + parse_special=True) + print(",".join(str(i) for i in ids)) diff --git a/metal/tools/check_ref.py b/metal/tools/check_ref.py new file mode 100644 index 00000000..71da9290 --- /dev/null +++ b/metal/tools/check_ref.py @@ -0,0 +1,34 @@ +"""metal/tools/check_ref.py - checks metal/src/ref_quant.cpp's dequantizers against gguf-py's (and Q2_0 against +tools/gguf_writer.py's codec) on the files tests/ref_dump wrote: + + python metal/tools/check_ref.py + +Prints the max |difference| per type; the reference passes when every one is 0 (bitwise: both decode to float32). +""" +import pathlib +import sys + +import numpy as np + +ROOT = pathlib.Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "tools")) +from gguf.quants import dequantize # noqa: E402 +from gguf.constants import GGMLQuantizationType as Q # noqa: E402 + +ROWS, COLS = 16, 2560 +d = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else ".") +bad = 0 +for name in ("Q2_0", "Q4_0", "Q5_0", "Q8_0", "Q3_K", "Q4_K", "Q5_K", "Q6_K", "IQ2_XXS", "IQ2_XS", "IQ2_S", "IQ3_XXS", + "IQ3_S", "IQ4_NL", "IQ4_XS", "BF16", "F16"): + raw = np.fromfile(d / f"{name}.bin", dtype=np.uint8) + ref = np.fromfile(d / f"{name}.f32", dtype=np.float32).reshape(ROWS, COLS) + if name == "Q2_0": + from gguf_writer import dequantize_q2_0 # noqa: E402 + got = np.asarray(dequantize_q2_0(raw.tobytes()), dtype=np.float32).reshape(ROWS, COLS) + else: + got = dequantize(raw.reshape(ROWS, -1), Q[name]).astype(np.float32).reshape(ROWS, COLS) + diff = float(np.max(np.abs(got - ref))) + scale = float(np.max(np.abs(got))) + print(f"{name:8s} max |ref_quant - gguf-py| = {diff:.3e} (max |w| {scale:.3e}) {'ok' if diff == 0 else 'DIFF'}") + bad += diff != 0 +sys.exit(1 if bad else 0) diff --git a/metal/tools/gen_stubs.py b/metal/tools/gen_stubs.py new file mode 100644 index 00000000..f70ea34d --- /dev/null +++ b/metal/tools/gen_stubs.py @@ -0,0 +1,184 @@ +#!/usr/bin/env python3 +"""gen_stubs.py LINK_LOG OUT.cpp CLANG_ARGS... : stubs for the kernel-library entry points the Metal engine leaves undefined. + +LINK_LOG is the output of a failed link of `strata` (ld64 prints each undefined symbol demangled). The declarations +come from the engine's own headers through clang's AST dump (-ast-dump-filter), so every stub has the header's exact +types; it is defined in the declaring namespace (free functions) or out of line (members, trailing return type), and +calls strata::metal_engine::missing("name") (metal/src/engine/missing.cpp). Entry points that have a Metal +implementation are defined in metal/src/engine/*.cpp and are therefore not undefined: they never get a stub. +""" +import os, re, subprocess, sys, tempfile + +log, out = sys.argv[1], sys.argv[2] +clang_args = sys.argv[3:] +root = None +for a in clang_args: + if a.startswith("-I") and a.endswith("/include") and os.path.isdir(os.path.join(a[2:], "strata")): + root = a[2:] +assert root, "need -I/include among the clang args" + +# ---- the undefined symbols (demangled), from ld64's report +undef = [] +for m in re.finditer(r'^\s+"(.+)", referenced from:', open(log, errors="replace").read(), re.M): + undef.append(m.group(1)) +undef = sorted(set(undef)) + +def split_top(s): + out, d, cur = [], 0, "" + for ch in s: + if ch in "(<[": d += 1 + if ch in ")>]": d -= 1 + if ch == "," and d == 0: + out.append(cur.strip()); cur = "" + else: + cur += ch + if cur.strip(): out.append(cur.strip()) + return out + +def parse_demangled(s): + """'ns::f(int, float*) const' -> ('ns::f', nparams)""" + s = re.sub(r"\s+const$", "", s) + d, i = 0, len(s) - 1 + while i >= 0: + if s[i] == ")": d += 1 + elif s[i] == "(": + d -= 1 + if d == 0: break + i -= 1 + name, params = s[:i], s[i + 1:-1] + p = split_top(params) + if p == ["void"]: p = [] + return name, len(p) + +wanted = {} +skipped = [] +for u in undef: + if "(" not in u or u.startswith("_") or "::" not in u: + skipped.append(u); continue + n, k = parse_demangled(u) + wanted.setdefault(n, set()).add(k) + +# ---- declarations from the headers +hdrs = [] +for d in ["kernels", "kernels/cpu", "prefill", "core", "platform", "ngram", "spec"]: + p = os.path.join(root, "strata", d) + if os.path.isdir(p): + hdrs += sorted("strata/%s/%s" % (d, f) for f in os.listdir(p) if f.endswith(".hpp")) +def compiles(h): + f = tempfile.NamedTemporaryFile("w", suffix=".cpp", delete=False) + f.write('#include "%s"\n' % h); f.close() + r = subprocess.run(["clang++", "-fsyntax-only"] + clang_args + [f.name], capture_output=True, text=True) + os.unlink(f.name) + return r.returncode == 0 +bad = [h for h in hdrs if not compiles(h)] +hdrs = [h for h in hdrs if h not in bad] +for h in bad: print("HEADER-SKIPPED", h) +tu = tempfile.NamedTemporaryFile("w", suffix=".cpp", delete=False) +for h in hdrs: tu.write('#include "%s"\n' % h) +tu.close() +decls = {} # qualname -> list of (kind, type_str, params[(name,type)], is_const, is_static, file) +cmd = ["clang++", "-fsyntax-only", "-Xclang", "-ast-dump", "-Xclang", "-ast-dump-filter=strata", "-fno-color-diagnostics"] + clang_args + [tu.name] +r = subprocess.run(cmd, capture_output=True, text=True) +if r.returncode != 0: sys.stderr.write(r.stderr[-4000:]) +# the AST dump is a tree ("|-", "`-", "| " prefixes, two characters per level): walk it, keeping the enclosing +# namespaces and records, and collect every function declaration that has no body +FN = ("FunctionDecl", "CXXMethodDecl", "CXXConstructorDecl", "CXXDestructorDecl") +stack = [] # (depth, kind, name) +cur = None # the function being read: [qual, kind, type, params, depth, has_body, rest] +def flush(): + global cur + if cur and not cur[5] and cur[0] in wanted: + q, kind, ty, params, d, hb, rest = cur + decls.setdefault(q, []).append((kind, ty, params, bool(re.search(r"\)\s*const\s*(noexcept)?\s*$", ty)), " static" in rest, "")) + cur = None +for line in r.stdout.splitlines(): + if line.startswith("Dumping "): flush(); stack = []; continue + m = re.match(r"^([| `-]*)(\w+) ", line) + if not m: continue + depth = len(m.group(1)) // 2 + kind = m.group(2) + if cur and depth <= cur[4]: flush() + while stack and stack[-1][0] >= depth: stack.pop() + if cur: + if kind == "CompoundStmt" and depth == cur[4] + 1: cur[5] = True + if kind == "ParmVarDecl" and depth == cur[4] + 1: + pm = re.search(r"(?:col|line):[\d:]+(?: used| referenced)?(?: (\w+))? '([^']*)'(?::'[^']*')?", line) + if pm: cur[3].append((pm.group(1) or "", pm.group(2))) + continue + if kind == "NamespaceDecl": + nm = re.search(r"> (?:prev 0x\w+ )?(?:line|col):[\d:]+ (\w+)", line) + stack.append((depth, kind, nm.group(1) if nm else "(anonymous)")) + elif kind in ("CXXRecordDecl", "ClassTemplateDecl"): + nm = re.search(r"(?:class|struct|union) (\w+)", line) + if " implicit " in line or not nm: stack.append((depth, kind, "(implicit)")) + else: stack.append((depth, kind, nm.group(1))) + elif kind in FN and " implicit " not in line: + fm = re.findall(r"(~?\w+) '([^']*)'(?::'[^']*')?", line) + if not fm: continue + name, ty = fm[-1] + rest = line[line.rfind("'") + 1:] + names = [s[2] for s in stack] + if any(n.startswith("(") for n in names) or any(s[1] == "ClassTemplateDecl" for s in stack): continue + cur = [("::".join(names + [name])), kind, ty, [], depth, False, rest] + elif kind in ("FunctionTemplateDecl",): + stack.append((depth, kind, "(template)")) +flush() + +def nx(ty): + return " noexcept" if re.search(r"\)\s*(const\s*)?noexcept\s*$", ty) else "" + +def ret_stmt(r): + if r == "void": return "" + if r.endswith("&"): # a reference: to a zero-initialised object of its own + return " static std::remove_cv_t> s{}; return s;" % r + return " return {};" + +def ret_of(ty): + d, i = 0, len(ty) - 1 + # the function type is "R (P...)" [ const]; find the '(' that opens the parameter list + s = re.sub(r"\)\s*(const)?\s*(noexcept)?\s*$", ")", ty) + i = len(s) - 1; d = 0 + while i >= 0: + if s[i] == ")": d += 1 + elif s[i] == "(": + d -= 1 + if d == 0: break + i -= 1 + return s[:i].strip() + +lines = ['// metal/src/engine/stubs.cpp - GENERATED by metal/tools/gen_stubs.py: do not edit.', + '// The kernel-library entry points with no Metal implementation yet: each stops the engine with its name', + '// (metal/src/engine/missing.cpp). Regenerate after porting one.', ''] +lines += ['#include "%s"' % h for h in hdrs] +lines += ['#include ', '', 'namespace strata::metal_engine { void missing(const char* name); }', ''] +done, unmatched = 0, [] +for qn in sorted(wanted): + ds = decls.get(qn, []) + ds = [d for d in ds if len(d[2]) in wanted[qn]] + if not ds: + unmatched.append(qn); continue + seen = set() + for kind, ty, params, is_const, is_static, loc in ds: + key = (ty, kind) + if key in seen: continue + seen.add(key) + ps = ", ".join("%s p%d" % (t, k) if "(*)" not in t else t.replace("(*)", "(*p%d)" % k) for k, (n, t) in enumerate(params)) + if kind == "FunctionDecl": + ns, fn = qn.rsplit("::", 1) + r = ret_of(ty) + body = 'strata::metal_engine::missing("%s");' % qn + body += ret_stmt(r) + lines.append("namespace %s { %s %s(%s)%s { %s } }" % (ns, r, fn, ps, nx(ty), body)) + elif kind == "CXXMethodDecl": + r = ret_of(ty) + body = 'strata::metal_engine::missing("%s");' % qn + body += ret_stmt(r) + lines.append("auto %s(%s)%s%s -> %s { %s }" % (qn, ps, " const" if is_const else "", nx(ty), r, body)) + elif kind in ("CXXConstructorDecl", "CXXDestructorDecl"): + lines.append('%s(%s) { strata::metal_engine::missing("%s"); }' % (qn, ps, qn)) + done += 1 +open(out, "w").write("\n".join(lines) + "\n") +print("undefined %d, stubs %d, unmatched %d, skipped %d" % (len(undef), done, len(unmatched), len(skipped))) +for u in unmatched: print("UNMATCHED", u) +for u in skipped: print("SKIPPED", u) +os.unlink(tu.name) diff --git a/metal/tools/gguf_list.cpp b/metal/tools/gguf_list.cpp new file mode 100644 index 00000000..1376170e --- /dev/null +++ b/metal/tools/gguf_list.cpp @@ -0,0 +1,25 @@ +// metal/tools/gguf_list.cpp - tensor directory and scalar metadata of a GGUF (name type shape offset), for the +// Metal window's wiring. clang++ -std=c++20 -I include metal/tools/gguf_list.cpp -o gguf_list +#include "strata/artifact/gguf_reader.hpp" + +#include +#include + +int main(int argc, char** argv) { + if (argc < 2) { std::printf("usage: gguf_list [substring]\n"); return 2; } + strata::GgufFile g(argv[1]); + const std::string f = argc > 2 ? argv[2] : ""; + for (const auto& [k, v] : g.metadata()) { + if (!f.empty() && k.find(f) == std::string::npos) continue; + if (v.is_num()) std::printf("META %s = %g\n", k.c_str(), v.num()); + else if (v.type == strata::MetaType::STRING) std::printf("META %s = %s\n", k.c_str(), v.s.substr(0, 80).c_str()); + else std::printf("META %s = [%llu items]\n", k.c_str(), (unsigned long long) v.count); + } + for (const auto& t : g.tensors()) { + if (!f.empty() && t.name.find(f) == std::string::npos) continue; + std::printf("%s %s [", t.name.c_str(), t.type_name()); + for (size_t i = 0; i < t.shape.size(); ++i) std::printf(i ? ",%llu" : "%llu", (unsigned long long) t.shape[i]); + std::printf("] off %llu\n", (unsigned long long) t.offset); + } + return 0; +} diff --git a/metal/tools/metal_repack.py b/metal/tools/metal_repack.py new file mode 100644 index 00000000..b6064077 --- /dev/null +++ b/metal/tools/metal_repack.py @@ -0,0 +1,195 @@ +#!/usr/bin/env python3 +"""metal_repack.py: a multi-shard GGUF (Unsloth's UD-*_K_XL: 4-6 shards, shards cutting through layers) as ONE GGUF +for the Metal engine, which maps a single file into one GPU buffer (or streams its experts from it). + + python3 metal/tools/metal_repack.py --shard1 <...-00001-of-0000N.gguf> --out -metal.gguf [--verify] + +--verify: after writing, every tensor of the output is hashed (SHA-256) against its bytes in the source shard; any +difference stops with an error and removes the output. + +The output holds shard 1's metadata (without the split.* keys) and every tensor of every shard except the n-gram +table (per_layer_token_embd: it stays in its shard, read from the SSD by the host through --ple-gguf), byte for +byte. The dense tensors come first; then each layer's routed experts (gate, up, down) together. Every tensor starts +on a 16 KiB boundary (general.alignment = 16384: Apple Silicon's page). Prints the shard holding the n-gram table. +""" +from __future__ import annotations + +import argparse +import hashlib +import os +import re +import struct +import sys +from pathlib import Path + +ALIGN = 16384 +# GGML type -> (bytes per block, values per block) +TYPE_SIZE = {0: (4, 1), 1: (2, 1), 30: (2, 1), 2: (18, 32), 3: (20, 32), 6: (22, 32), 7: (24, 32), 8: (34, 32), + 10: (84, 256), 11: (110, 256), 12: (144, 256), 13: (176, 256), 14: (210, 256), 16: (66, 256), + 17: (74, 256), 18: (98, 256), 19: (50, 256), 20: (18, 32), 21: (110, 256), 22: (82, 256), 23: (136, 256), + 42: (18, 64)} +PLE = "per_layer_token_embd.weight" + + +class Reader: + def __init__(self, path: Path): + self.path = path + self.f = open(path, "rb") + magic, self.version, nt, nkv = struct.unpack("<4sIQQ", self.f.read(24)) + if magic != b"GGUF": + sys.exit(f"{path}: not a GGUF file") + self.kv = [] # (key, raw bytes of the whole entry) + self.align = 32 + for _ in range(nkv): + start = self.f.tell() + key = self._str() + t = struct.unpack(" str: + n = struct.unpack(" list[Path]: + m = re.match(r"(.*)-00001-of-(\d{5})\.gguf$", shard1.name) + if not m: + return [shard1] + n = int(m.group(2)) + return [shard1.with_name(f"{m.group(1)}-{i:05d}-of-{n:05d}.gguf") for i in range(1, n + 1)] + + +def tensor_hash(f, pos: int, n: int) -> str: + h = hashlib.sha256() + f.seek(pos) + while n: + buf = f.read(min(n, 64 << 20)) + if not buf: + break + h.update(buf) + n -= len(buf) + return h.hexdigest() + + +def verify(out: Path, data0: int, order: list) -> list[str]: + """The names of the tensors whose bytes in `out` differ from their source shard's (SHA-256 each).""" + bad = [] + with open(out, "rb") as o: + r = Reader(out) # the output's own table, as a reader sees it + table = {t["name"]: t for t in r.tensors} + for i, t in enumerate(order): + mine = table.get(t["name"]) + if mine is None or mine["abs"] != data0 + t["new"] or mine["bytes"] != t["bytes"] or \ + tensor_hash(o, mine["abs"], t["bytes"]) != tensor_hash(t["src"].f, t["abs"], t["bytes"]): + bad.append(t["name"]) + if i % 50 == 0: + print(f"\r verify {i + 1} / {len(order)}", end="", flush=True) + r.f.close() + print() + return bad + + +def gguf_str(s: str) -> bytes: + b = s.encode("utf-8") + return struct.pack(" int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--shard1", required=True, type=Path) + ap.add_argument("--out", required=True, type=Path) + ap.add_argument("--verify", action="store_true", help="hash every tensor of the output against the source") + a = ap.parse_args() + shards = [Reader(p) for p in shard_paths(a.shard1)] + every = [t for s in shards for t in s.tensors] + ple = [t for t in every if t["name"] == PLE] + keep = [t for t in every if t["name"] != PLE] + + def layer_of(t): + m = re.match(r"blk\.(\d+)\.", t["name"]) + return int(m.group(1)) if m else -1 + dense = [t for t in keep if "_exps." not in t["name"]] + role = {"ffn_gate_exps": 0, "ffn_up_exps": 1, "ffn_down_exps": 2} + exps = sorted((t for t in keep if "_exps." in t["name"]), + key=lambda t: (layer_of(t), role.get(t["name"].split(".")[2], 9))) + order = dense + exps + kv = [raw for key, raw in shards[0].kv if not key.startswith("split.") and key != "general.alignment"] + kv.append(gguf_str("general.alignment") + struct.pack(" [--out .experts] [--verify] + +The file: a 64-byte header ("STRX", version 1, 48 layers, 512 experts, the source GGUF's size), then per layer its +offset in this file and the three slice sizes (4 x u64 each), then the experts, layer by layer, expert by expert: +gate slice, up slice, down slice - each byte for byte the GGUF's. --verify compares every expert with the GGUF. +The engine (metal/src/engine/stream.cpp) uses it when it sits beside the GGUF as .experts and its header +matches; otherwise it reads the GGUF as before. +""" +from __future__ import annotations + +import argparse +import hashlib +import os +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import metal_repack as R # noqa: E402 + +NL, NE = 48, 512 +ALIGN = 16384 + + +def plan(gguf: Path): + """The reader, each layer's (gate, up, down, slice sizes), each layer's offset in the file, the file's size, the + first data offset.""" + rd = R.Reader(gguf) + tab = {t["name"]: t for t in rd.tensors} + lay = [] + for l in range(NL): + g, u, d = (tab[f"blk.{l}.ffn_{k}_exps.weight"] for k in ("gate", "up", "down")) + lay.append((g, u, d, g["bytes"] // NE, u["bytes"] // NE, d["bytes"] // NE)) + head_len = 64 + NL * 32 + data0 = (head_len + ALIGN - 1) // ALIGN * ALIGN + offs, at = [], data0 + for g, u, d, gs, us, ds in lay: + offs.append(at) + at += NE * (gs + us + ds) + at = (at + ALIGN - 1) // ALIGN * ALIGN + return rd, lay, offs, at, data0 + + +def size_bytes(gguf: Path) -> int: + """The size the file for this GGUF will have (setup checks the free disk with it).""" + rd, _, _, at, _ = plan(gguf) + rd.f.close() + return at + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--gguf", required=True, type=Path) + ap.add_argument("--out", type=Path) + ap.add_argument("--verify", action="store_true") + a = ap.parse_args() + out = a.out or a.gguf.with_name(a.gguf.name + ".experts") + rd, lay, offs, at, data0 = plan(a.gguf) + head = struct.pack("<4sIIIQ", b"STRX", 1, NL, NE, os.path.getsize(a.gguf)).ljust(64, b"\0") + for (g, u, d, gs, us, ds), o in zip(lay, offs): + head += struct.pack(" int: + """A Mac (Apple Silicon): the Metal engine, built from source on the Mac by metal/setup_mac.py (its own steps: + the Mac check, the pack by unified memory, the engine build, the Metal defaults). Nothing of the CUDA / HIP paths + is used or changed.""" + return subprocess.call([sys.executable, str(ROOT / "metal" / "setup_mac.py"), *argv]) + + def sycl_setup(argv) -> int: """--backend sycl: the Intel Arc engine (the SYCL port in sycl/, PR #423), experimental. There is no ready-made Intel engine: it is compiled from source on the PC (docs/INTEL_ARC.md), then sycl/setup_intel.py runs this setup @@ -5620,6 +5627,8 @@ def preview_family(a) -> int: def main() -> int: + if sys.platform == "darwin": # a Mac: metal/setup_mac.py (the Metal engine) + return mac_setup(sys.argv[1:]) ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--family", choices=list(FAMILIES) + list(PREVIEW_FAMILIES), help="qwen = Qwen3.8-Flash-Next, swift = Swift 1.5 (qwen36 = Qwen3.6-35B-A3B: download only, the " diff --git a/setup.sh b/setup.sh index 019348f1..2d1ec360 100755 --- a/setup.sh +++ b/setup.sh @@ -29,6 +29,19 @@ if [ ! -x .venv/bin/python ]; then fi done fi + # macOS: the system Python is 3.9; a standalone Python 3.12 goes into .python (no sudo, no Homebrew; pinned) + if [ -z "$PY" ] && [ "$(uname -s)" = Darwin ]; then + if [ ! -x .python/python/bin/python3 ]; then + PBS="https://github.com/astral-sh/python-build-standalone/releases/download/20261009/cpython-3.12.15%2B20261009-aarch64-apple-darwin-install_only.tar.gz" + echo "Python 3.10+ is needed; downloading a standalone Python 3.12 into .python (25 MB) ..." + mkdir -p .python && curl -fL --retry 3 -o .python/python.tar.gz "$PBS" || { echo "could not download Python"; exit 1; } + if [ "$(shasum -a 256 .python/python.tar.gz | cut -d" " -f1)" != "83dcb04777c798bd95f3687acf9ae84b09860272ee6bdfb05be8bcf9447f75b8" ]; then + rm -f .python/python.tar.gz; echo "the Python download does not match its pinned SHA-256"; exit 1 + fi + tar xzf .python/python.tar.gz -C .python && rm -f .python/python.tar.gz + fi + PY=.python/python/bin/python3 + fi if [ -z "$PY" ]; then echo "Python 3.10+ with venv is needed; installing it (sudo will ask for your password) ..." if command -v apt-get >/dev/null 2>&1; then diff --git a/src/core/conversation_state.cpp b/src/core/conversation_state.cpp index 4fbcf88b..a93715dd 100644 --- a/src/core/conversation_state.cpp +++ b/src/core/conversation_state.cpp @@ -152,8 +152,22 @@ bool conversation_checkpoint_validate(const ConversationCheckpoint& c, const Ses return true; } +#if defined(STRATA_GPU_METAL) +} // namespace strata::core +namespace strata::metal_engine { +// the running state lives in the Metal decode window (metal/src/engine/window.cpp), not in the session's buffers +bool window_checkpoint_save(strata::core::ConversationCheckpoint& c, std::string& error); +bool window_checkpoint_restore(const strata::core::ConversationCheckpoint& c, std::string& error); +} // namespace strata::metal_engine +namespace strata::core { +#endif + bool conversation_checkpoint_save(ConversationCheckpoint& c, const SessionState& ss, const ModelGeometry& g, std::string& error) { +#if defined(STRATA_GPU_METAL) + (void) ss; (void) g; + return strata::metal_engine::window_checkpoint_save(c, error); +#endif ConversationStateSizes z; if (!checkpoint_targets(ss, g, c.ids.size(), z, error)) return false; const size_t layers = owned_qsa(ss); @@ -172,6 +186,13 @@ bool conversation_checkpoint_save(ConversationCheckpoint& c, const SessionState& bool conversation_checkpoint_restore(const ConversationCheckpoint& c, SessionState& ss, const ModelGeometry& g, std::string& error) { +#if defined(STRATA_GPU_METAL) + (void) g; + if (!strata::metal_engine::window_checkpoint_restore(c, error)) return false; + ss.ple_prev[0] = c.ids.size() >= 2 ? c.ids[c.ids.size() - 2] : -1; + ss.ple_prev[1] = c.ids.size() >= 1 ? c.ids[c.ids.size() - 1] : -1; + return true; +#endif if (!conversation_checkpoint_validate(c, ss, g, error)) return false; ConversationStateSizes z; if (!conversation_session_sizes(g, ss, z, error)) return false; diff --git a/src/core/device.cu b/src/core/device.cu index a614f248..34bc679d 100644 --- a/src/core/device.cu +++ b/src/core/device.cu @@ -19,10 +19,12 @@ void check(cudaError_t e, const char* what) { // A NaN pattern, not zero. Zeros read from uninitialised memory are indistinguishable from real zeros in a // dequantized weight or a masked attention score, which is exactly the kind of wrong-but-plausible value the // Phase 1 harnesses kept catching. +#if !defined(STRATA_GPU_METAL) __global__ void poison_kernel(float* p, uint64_t n_floats) { const uint64_t i = (uint64_t) blockIdx.x * blockDim.x + threadIdx.x; if (i < n_floats) p[i] = __int_as_float(0x7fc00000); } +#endif #if defined(STRATA_USE_HIP) #if !defined(STRATA_HIP_ARCHS) @@ -232,7 +234,7 @@ std::string gpu_arch_problem(int ordinal) { } std::string device_code_error() { -#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) +#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) || defined(STRATA_GPU_METAL) return ""; // gpu_arch_problem() checks the HIP architectures against STRATA_HIP_ARCHS, before this point #else // every .cu of the engine is compiled for the same CMAKE_CUDA_ARCHITECTURES, so this kernel stands for all @@ -322,6 +324,12 @@ DeviceArena::DeviceArena(uint64_t bytes, int ordinal, bool poison) // One allocation for the whole region. cudaMalloc of a large block is the thing that can fail late, so it // happens once, here, before anything depends on it. check(cudaMalloc(&base_, (size_t) bytes), "cudaMalloc"); +#if defined(STRATA_GPU_METAL) // unified memory: the CPU writes the pattern through the allocation's CPU view + if (poison_) { + uint32_t* h = (uint32_t*) strata::gpu::host_view(base_); + for (uint64_t i = 0; i < bytes / sizeof(float); ++i) h[i] = 0x7fc00000u; + } +#else if (poison_) { const int threads = 256; const uint64_t n = bytes / sizeof(float); @@ -336,6 +344,7 @@ DeviceArena::DeviceArena(uint64_t bytes, int ordinal, bool poison) } check(cudaDeviceSynchronize(), "poison sync"); } +#endif } DeviceArena::~DeviceArena() { diff --git a/src/core/expert_cache.cpp b/src/core/expert_cache.cpp index 9fe45205..1920fdb7 100644 --- a/src/core/expert_cache.cpp +++ b/src/core/expert_cache.cpp @@ -3,7 +3,7 @@ // #533's segmented cache uses CUDA's virtual memory management (cuMem*): not on HIP, neither the RDNA backend nor // the gfx906 compat build (PR #638), which compiles this file as HIP without STRATA_USE_HIP -#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) +#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) || defined(STRATA_GPU_METAL) #define STRATA_EC_NO_VMM 1 #endif diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index f8d9212b..c0a7ec7c 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -45,6 +45,9 @@ #include #else #include +#if defined(__APPLE__) +#include // host_statistics64: the available memory +#endif #include #include #include @@ -411,6 +414,16 @@ bool host_available_memory(HostMemory& m, const std::string& meminfo, const std: } m.available = bytes; return true; +#elif defined(__APPLE__) + // macOS: free + inactive + purgeable pages (what the OS can hand out without swapping), as vm_stat reports them + (void) meminfo; (void) self_cgroup; (void) cgroup_root; + vm_statistics64_data_t vs{}; + mach_msg_type_number_t count = HOST_VM_INFO64_COUNT; + vm_size_t page_bytes = 0; + if (host_page_size(mach_host_self(), &page_bytes) != KERN_SUCCESS || + host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t) &vs, &count) != KERN_SUCCESS) return false; + m.available = ((uint64_t) vs.free_count + vs.inactive_count + vs.purgeable_count) * (uint64_t) page_bytes; + return m.available > 0; #else (void) meminfo; (void) self_cgroup; (void) cgroup_root; const long pages = sysconf(_SC_AVPHYS_PAGES); @@ -3131,10 +3144,12 @@ bool FileExpertSource::pin_cache_complement( fail("FileExpertSource: madvise could not release mapped expert layer " + std::to_string(layer)); return; } +#if !defined(__APPLE__) // macOS has no posix_fadvise; the madvise above already released the mapping if (posix_fadvise(fd_, (off_t) layer_offset, (off_t) layer_bytes, POSIX_FADV_DONTNEED) != 0) { fail("FileExpertSource: posix_fadvise could not release expert layer " + std::to_string(layer)); return; } +#endif } #endif const int64_t done = layers_done.fetch_add(1) + 1; diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index 9fbaef08..c550c732 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -52,6 +52,17 @@ #include "ggml.h" // --mtp-q4: the head rows' and projections' formats, dequantized and requantized at load #endif +#if defined(STRATA_GPU_METAL) +// The Metal backend's MTP drafter (metal/src/engine/window.cpp, beside the decode window it reads): load, prefill and +// draft hand over to it; bind has nothing to bind there. +namespace strata::metal_engine { +bool mtp_load(const std::string& rt_dir, int max_t, std::string& err); +bool mtp_prefill(const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err); +bool mtp_draft(int T, const int32_t* tokens, int64_t p, int a, int max_steps, int32_t* drafts, float* probs, float min_p, + int* n_drafts, std::string& err); +} // namespace strata::metal_engine +#endif + namespace strata::core { namespace { @@ -237,6 +248,13 @@ bool MtpDrafter::make_q4_head(std::string& err) { bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, SessionState& ss, int max_t, std::string& err, int64_t window, const MtpDrafter* shared) { +#if defined(STRATA_GPU_METAL) + (void) window; (void) shared; + g_ = &g; + ss_ = &ss; + max_t_ = max_t; + return strata::metal_engine::mtp_load(rt_dir, max_t, err); +#endif cudaGetDevice(&device_); // a layer split's last stage on another GPU: the drafter lives there g_ = &g; ss_ = &ss; @@ -416,7 +434,7 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session // --pipeline-windows 2 (the forcing graphs): the chain shares its card with stage 1's windows and the next launch // on stage 0 waits for it, so its stream gets the highest priority there (STRATA_MTP_PRIORITY=0: the default) bool prio = false; -#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) // (HIP: the default priority) +#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL) // (HIP, Metal: the default priority) static const bool hi_prio = [] { const char* v = std::getenv("STRATA_MTP_PRIORITY"); return v == nullptr || std::atoi(v) != 0; }(); int prio_lo = 0, prio_hi = 0; if (force_on_ && hi_prio && cudaDeviceGetStreamPriorityRange(&prio_lo, &prio_hi) == cudaSuccess) @@ -640,6 +658,10 @@ void draft_head_hint(int64_t n_tokens, int64_t row_bytes) { bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err, const MtpDrafter* shared) { +#if defined(STRATA_GPU_METAL) + (void) wt; (void) head; (void) window_R; (void) err; (void) shared; + return true; +#endif const OnDevice on_device(device_); wt_ = &wt; head_ = head; @@ -1344,6 +1366,10 @@ bool MtpDrafter::prepare_prefill(std::string& err) { bool MtpDrafter::prefill(const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err, bool sync) { +#if defined(STRATA_GPU_METAL) + (void) R_rows; (void) sync; // the rows are the decode window's own (the Metal drafter reads them in place) + return strata::metal_engine::mtp_prefill(next_tokens, n, cell0, err); +#endif const OnDevice on_device(device_); const Clock::time_point t0 = Clock::now(); const int64_t HCN = g_->hc * g_->n_embd; @@ -1485,6 +1511,20 @@ DraftTiming g_dt; bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* drafts, std::string& err, float* probs, float min_p, int* n_drafts) { +#if defined(STRATA_GPU_METAL) + { + if (T < 1 || T > max_t_ || a < 0 || a >= T) { err = "mtp: draft arguments out of range"; return false; } + const int max_steps = (int) std::min(std::min(max_t_ - 1, max_drafts_), (int64_t) 1 << 30); + const Clock::time_point t0 = Clock::now(); + int n = 0; + if (!strata::metal_engine::mtp_draft(T, tokens, p, a, max_steps, drafts, probs, min_p, &n, err)) return false; + for (int j = n; j < max_t_ - 1; ++j) { drafts[j] = 0; if (probs) probs[j] = 0.0f; } + if (n_drafts) *n_drafts = n; + ms_draft += ms_since(t0); + ++rounds; + return true; + } +#endif const OnDevice on_device(device_); if (T < 1 || T > max_t_ || a < 0 || a >= T) { err = "mtp: draft arguments out of range"; return false; } if (chain_live_) { err = "mtp: a pipelined chain is still in flight"; return false; } @@ -1770,6 +1810,13 @@ int MtpDrafter::chain_poll(std::string& err) { bool MtpDrafter::draft_first(int T, const float* R_row, int32_t token, int64_t cell, int32_t* drafts, std::string& err, float* probs, float min_p, int* n_drafts) { +#if defined(STRATA_GPU_METAL) + { // the decode window's row 0 is the residual (the window that just ran) + (void) R_row; + std::vector toks((size_t) T, token); + return draft(1, toks.data(), cell, 0, drafts, err, probs, min_p, n_drafts); + } +#endif const OnDevice on_device(device_); // row 0 is the real pair; rows 1.. repeat it and only write cells the next round overwrites const int64_t HCN = g_->hc * g_->n_embd; diff --git a/src/core/remote_experts.cpp b/src/core/remote_experts.cpp index 9af13abf..f01bf6fe 100644 --- a/src/core/remote_experts.cpp +++ b/src/core/remote_experts.cpp @@ -75,7 +75,7 @@ bool RemoteExperts::preflight(int device, double& free_gib, std::string& err) { // The layer waits for this GPU on the CPU pool's critical path: spin instead of sleeping, whose wake-up // costs more than a small expert batch takes (measured: ~0.3 ms per round trip on Windows). Only possible // before the device's context exists, so first thing; STRATA_REMOTE_SPIN=0 keeps the driver's default. -#if !defined(STRATA_USE_HIP) +#if !defined(STRATA_USE_HIP) && !defined(STRATA_GPU_METAL) const char* spin = std::getenv("STRATA_REMOTE_SPIN"); if (!(spin && spin[0] == '0')) cudaInitDevice(device, cudaDeviceScheduleSpin | cudaDeviceMapHost, 0); cudaGetLastError(); diff --git a/src/core/session.cpp b/src/core/session.cpp index 55317c78..157c4cc4 100644 --- a/src/core/session.cpp +++ b/src/core/session.cpp @@ -137,7 +137,24 @@ void session_release(SessionState& s) { } } +#if defined(STRATA_GPU_METAL) +} // namespace strata::core +namespace strata::metal_engine { +void window_reset(); // metal/src/engine/window.cpp: the decode window's running state back to a new sequence's +} // namespace strata::metal_engine +namespace strata::core { +#endif + void session_zero(SessionState& s, const ModelGeometry& g, const float* R_init, void* stream) { +#if defined(STRATA_GPU_METAL) + // the running state lives in the Metal decode window; the session's own device buffers are not read there + (void) g; (void) R_init; (void) stream; + strata::metal_engine::window_reset(); + s.ple_prev[0] = -1; + s.ple_prev[1] = -1; + s.ple_token = -1; + return; +#endif cudaStream_t cs = (cudaStream_t) stream; // the residual: `hc` copies of the one vector a caller hands in. A real sequence's first token is the // embedding broadcast to every stream, which is the reference's own initial condition. diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 02134b32..751fa376 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -67,6 +67,19 @@ #include #include +#if defined(STRATA_GPU_METAL) +// The Metal backend's decode window (metal/src/engine/window.cpp): this file's init/run/commit hand over to it. +namespace strata::metal_engine { +void window_destroy(void* w); +void* window_create(); +bool window_init(void* w, const strata::core::ModelGeometry& g, strata::core::SessionState& ss, int max_t, int64_t max_cells, + int64_t* n_vocab, std::string& err); +bool window_run(void* w, int T, const int32_t* tokens, int64_t pos0, bool head, int32_t* out, std::string& err); +bool window_commit(void* w, int n_keep, std::string& err); +bool window_copy_logits(void* w, int t, float* host); +} // namespace strata::metal_engine +#endif + namespace strata::core { namespace { @@ -473,7 +486,12 @@ void Verifier::diag(std::FILE* f) const { trace_dump(f); // #649: STRATA_VERIFY_TRACE=1 only } + Verifier::~Verifier() { +#if defined(STRATA_GPU_METAL) + strata::metal_engine::window_destroy(metal_); + metal_ = nullptr; +#endif const Verifier* self = this; g_diag_verifier.compare_exchange_strong(self, nullptr); for (auto& slot : g_live) { @@ -556,6 +574,11 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& max_t_ = max_t; sampling_.greedy = true; // a fresh verifier samples greedily until set_sampling says otherwise sampling_.temperature = 0.0f; +#if defined(STRATA_GPU_METAL) + if (metal_ == nullptr) metal_ = strata::metal_engine::window_create(); + return strata::metal_engine::window_init(metal_, g, ss, max_t, ss.qsa_states[ss.qsa_primary()].max_cells, &n_vocab_, + err); +#endif if (max_t < 2 || max_t > strata::kernels::kVerifyMaxT || max_t > strata::kernels::cpu::MAXT) { err = "verify: the window must hold 2.." + std::to_string(strata::kernels::kVerifyMaxT) + " tokens"; return false; @@ -1921,7 +1944,7 @@ bool Verifier::capture(int T, std::string& err) { std::fprintf(stderr, "\n%s\n", seq.c_str()); } #endif -#if !defined(STRATA_USE_HIP) // a CUDA debug listing (node types, kernel names) +#if !defined(STRATA_USE_HIP) && !defined(STRATA_GPU_METAL) // a CUDA debug listing (node types, kernel names) if (std::getenv("STRATA_VERIFY_NODES") != nullptr) { // what the window graph holds size_t nn = 0; cudaGraphGetNodes(graph, nullptr, &nn); @@ -2207,6 +2230,11 @@ bool Verifier::adapt_gate_wait(int32_t layer, std::string& err) { bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, void* user, int32_t* out, std::string& err) { +#if defined(STRATA_GPU_METAL) + (void) pool; + (void) user; + return strata::metal_engine::window_run(metal_, T, tokens, pos0, head_sampling_, out, err); +#endif using namespace strata::kernels; const OnDevice on_device(device_); last_batch_ = false; @@ -2541,6 +2569,19 @@ bool Verifier::window_logprobs(const int32_t* targets, int T, int64_t pos0, int3 std::string& err) { if (next_ != nullptr) return next_->window_logprobs(targets, T, pos0, extra_id, out, err); const OnDevice on_device(device_); +#if defined(STRATA_GPU_METAL) + // the head logits are the Metal window's (window_copy_logits, row by row) + if (n_vocab_ <= 0 || T <= 0 || targets == nullptr || out == nullptr) { + err = "window_logprobs: no head logits for this window"; + return false; + } + std::vector h((size_t) T * (size_t) n_vocab_); + for (int t = 0; t < T; ++t) + if (!strata::metal_engine::window_copy_logits(metal_, t, h.data() + (size_t) t * (size_t) n_vocab_)) { + err = "window_logprobs: the head logits copy failed"; + return false; + } +#else if (head_logits_ == nullptr || n_vocab_ <= 0 || T <= 0 || targets == nullptr || out == nullptr) { err = "window_logprobs: no head logits for this window"; return false; @@ -2551,6 +2592,7 @@ bool Verifier::window_logprobs(const int32_t* targets, int T, int64_t pos0, int3 err = "window_logprobs: the head logits copy failed"; return false; } +#endif for (int t = 0; t < T; ++t) { const float* row = h.data() + (size_t) t * (size_t) n_vocab_; const int32_t tgt = targets[t]; @@ -2597,6 +2639,9 @@ namespace { bool g_commit_async = false; } void Verifier::set_commit_async(bool on) { g_commit_async = on && std::getenv("STRATA_COMMIT_SYNC") == nullptr; } bool Verifier::commit(int n_keep, std::string& err) { +#if defined(STRATA_GPU_METAL) + return strata::metal_engine::window_commit(metal_, n_keep, err); +#endif const OnDevice on_device(device_); if (n_keep < 1 || n_keep > last_t_) { err = "verify: commit count out of range"; return false; } const Clock::time_point t0 = Clock::now(); @@ -2653,6 +2698,10 @@ bool Verifier::commit(int n_keep, std::string& err) { } bool Verifier::wait_commit(std::string& err) { +#if defined(STRATA_GPU_METAL) + (void) err; + return true; +#endif if (commit_pending_) { const OnDevice on_device(device_); commit_pending_ = false; @@ -3278,6 +3327,9 @@ void Verifier::note_nonfinite(int T, const int64_t* pos_b) { } bool Verifier::copy_logits(int t, float* host) const { +#if defined(STRATA_GPU_METAL) + return strata::metal_engine::window_copy_logits(metal_, t, host); +#endif if (next_ != nullptr) return next_->copy_logits(t, host); // a layer split: the head is on the last stage if (head_logits_ == nullptr || host == nullptr || t < 0 || n_vocab_ <= 0) return false; return cudaMemcpy(host, head_logits_ + (size_t) t * (size_t) n_vocab_, (size_t) n_vocab_ * sizeof(float), diff --git a/src/core/vmm.cpp b/src/core/vmm.cpp index e69d2b88..2ae5af6a 100644 --- a/src/core/vmm.cpp +++ b/src/core/vmm.cpp @@ -1,6 +1,6 @@ #include "strata/core/vmm.hpp" -#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) +#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL) #include #include diff --git a/src/kernels/cpu/expert_layout.cpp b/src/kernels/cpu/expert_layout.cpp index d8adb260..001fa5d4 100644 --- a/src/kernels/cpu/expert_layout.cpp +++ b/src/kernels/cpu/expert_layout.cpp @@ -60,7 +60,9 @@ bool cpu_avx512_ok() { const unsigned long long xcr0 = _xgetbv(0); #else unsigned lo = 0, hi = 0; +#if !defined(__aarch64__) // arm64 (the Metal build): no XCR0; cpuid reads zero there, so this is never reached __asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0)); +#endif const unsigned long long xcr0 = ((unsigned long long) hi << 32) | lo; #endif if ((xcr0 & 0xE6) != 0xE6) return false; // the OS saves the AVX-512 state @@ -92,7 +94,9 @@ bool cpu_avx512bw_ok() { const unsigned long long xcr0 = _xgetbv(0); #else unsigned lo = 0, hi = 0; +#if !defined(__aarch64__) // arm64 (the Metal build): no XCR0; cpuid reads zero there, so this is never reached __asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0)); +#endif const unsigned long long xcr0 = ((unsigned long long) hi << 32) | lo; #endif if ((xcr0 & 0xE6) != 0xE6) return false; // the OS saves the AVX-512 state @@ -126,7 +130,9 @@ bool cpu_avx2_ok() { const unsigned long long xcr0 = _xgetbv(0); #else unsigned lo = 0, hi = 0; +#if !defined(__aarch64__) // arm64 (the Metal build): no XCR0; cpuid reads zero there, so this is never reached __asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0)); +#endif const unsigned long long xcr0 = ((unsigned long long) hi << 32) | lo; #endif if ((xcr0 & 0x6) != 0x6) return false; // the OS saves the SSE and AVX state @@ -154,7 +160,9 @@ bool cpu_avx1_ok() { const unsigned long long xcr0 = _xgetbv(0); #else unsigned lo = 0, hi = 0; +#if !defined(__aarch64__) // arm64 (the Metal build): no XCR0; cpuid reads zero there, so this is never reached __asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0)); +#endif const unsigned long long xcr0 = ((unsigned long long) hi << 32) | lo; #endif return (xcr0 & 0x6) == 0x6; diff --git a/src/kernels/cpu/pool_affinity_linux.hpp b/src/kernels/cpu/pool_affinity_linux.hpp index 0791ac5c..bb84420c 100644 --- a/src/kernels/cpu/pool_affinity_linux.hpp +++ b/src/kernels/cpu/pool_affinity_linux.hpp @@ -65,5 +65,23 @@ inline int pin_thread_to_cpu(int core) { return pthread_setaffinity_np(pthread_self(), target.bytes, target.set); } +} // namespace strata::kernels::cpu::detail +#elif defined(__APPLE__) +#include +#include + +// macOS has no thread-to-core pinning (the scheduler places threads; affinity tags are hints at most): every CPU is +// allowed and a pin is a no-op, so the pool keeps its threads where the OS puts them. +namespace strata::kernels::cpu::detail { +inline int get_thread_affinity(std::vector& mask, std::vector* cpus = nullptr) { + mask.assign(1, ~0ul); + if (cpus) { + cpus->clear(); + for (unsigned i = 0; i < std::thread::hardware_concurrency(); ++i) cpus->push_back((int) i); + } + return 0; +} +inline int set_thread_affinity(const std::vector&) { return 0; } +inline int pin_thread_to_cpu(int) { return 0; } // nothing to do: the OS places the thread } // namespace strata::kernels::cpu::detail #endif diff --git a/src/platform/direct_file.cpp b/src/platform/direct_file.cpp index 5f8d9962..b09536c2 100644 --- a/src/platform/direct_file.cpp +++ b/src/platform/direct_file.cpp @@ -306,7 +306,12 @@ DirectFile::~DirectFile() { close(); delete impl_; } bool DirectFile::open(const std::string& path, std::string& err) { close(); +#if defined(__APPLE__) // macOS has no O_DIRECT: F_NOCACHE keeps the reads out of the unified buffer cache + impl_->fd = ::open(path.c_str(), O_RDONLY); + if (impl_->fd >= 0 && fcntl(impl_->fd, F_NOCACHE, 1) != 0) { ::close(impl_->fd); impl_->fd = -1; } +#else impl_->fd = ::open(path.c_str(), O_RDONLY | O_DIRECT); +#endif if (impl_->fd < 0) { err = "DirectFile: cannot open " + path; return false; } struct stat st; if (fstat(impl_->fd, &st) != 0) { err = "DirectFile: cannot size " + path; close(); return false; } diff --git a/src/platform/memory.cpp b/src/platform/memory.cpp index c9f2a512..4180bdf0 100644 --- a/src/platform/memory.cpp +++ b/src/platform/memory.cpp @@ -166,7 +166,14 @@ void advise_willneed(const void* p, uint64_t bytes) { void advise_willneed(int fd, uint64_t offset, uint64_t bytes) { if (fd < 0 || !read_ahead_enabled()) return; for (uint64_t at = 0; at < bytes; at += kAdviseStep) +#if defined(__APPLE__) // macOS: F_RDADVISE is the read-ahead hint + { + radvisory ra{(off_t) (offset + at), (int) std::min(kAdviseStep, bytes - at)}; + (void) fcntl(fd, F_RDADVISE, &ra); + } +#else (void) posix_fadvise(fd, (off_t) (offset + at), (off_t) std::min(kAdviseStep, bytes - at), POSIX_FADV_WILLNEED); +#endif } #endif diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 9a7dc8b5..2fa71c7c 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -100,6 +100,16 @@ void experts_native(const Batch&, const NativeGeom&, int, int64_t, const void*, } // namespace strata::prefill::fused #endif +#if defined(STRATA_GPU_METAL) +// The Metal backend reads a prompt through its decode window (metal/src/engine/window.cpp): init keeps the chunk, run +// hands over, draft_kv declines (the MTP hook reads the window's rows itself). +namespace strata::metal_engine { +bool window_ensure(const strata::core::ModelGeometry& g, strata::core::SessionState& ss, int64_t max_cells, std::string& err); +bool prompt_run(const int64_t* tokens, int64_t n, int64_t pos0, const float* const* embd_rows, + const std::function& on_chunk, std::string& err); +} // namespace strata::metal_engine +#endif + namespace strata::prefill { namespace { @@ -1042,8 +1052,8 @@ struct MoeBufs { size_t gu, h, xq, hq; }; MoeBufs moe_bufs(size_t T, int64_t n_expert, bool fused) { if (!fused) return {T * K * 1280, T * K * 640, mmq::q8_bytes((int64_t) (T * K), N), mmq::q8_bytes((int64_t) (T * K), 640)}; const size_t ts = (size_t) std::min((int64_t) T, stream_all_min() - 1); // MMQ's last small chunk - return {std::max(ts * K * 1280, (fused::group_bytes((int64_t) (T * K), (int) n_expert) + 3) / 4), - std::max(ts * K * 640, (fused::act_bytes((int64_t) (T * K), 640) + 3) / 4), + return {std::max(ts * K * 1280, (fused::group_bytes((int64_t) (T * K), (int) n_expert) + 3) / 4), + std::max(ts * K * 640, (fused::act_bytes((int64_t) (T * K), 640) + 3) / 4), std::max(mmq::q8_bytes((int64_t) (ts * K), N), fused::act_bytes((int64_t) T, N)), mmq::q8_bytes((int64_t) (ts * K), 640)}; } @@ -1073,6 +1083,12 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co core::ExpertSource* src, const core::ExpertCache* cache, const int32_t* host_res, int64_t chunk, void* stream, std::string& err, void* borrow, uint64_t borrow_bytes, bool borrow_spill) { Impl& m = *impl_; +#if defined(STRATA_GPU_METAL) + (void) wt; (void) src; (void) cache; (void) host_res; (void) stream; (void) borrow; + (void) borrow_bytes; + m.T = chunk > 0 ? chunk : 1; + return strata::metal_engine::window_ensure(g, ss, ss.qsa_states[ss.qsa_primary()].max_cells, err); +#endif m.wt = &wt; m.g = &g; m.ss = &ss; m.src = src; m.cache = cache; m.host_res = host_res; m.T = chunk; m.cs = (cudaStream_t) stream; m.stats = &stats_; if (g.n_embd != N || g.hc != HC || g.hc_lr != LR || g.n_expert < 1 || ss.k != K) { @@ -1365,6 +1381,11 @@ int64_t Prefill::chunk() const { return impl_->T; } bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err, const char** why) { Impl& m = *impl_; +#if defined(STRATA_GPU_METAL) + (void) m; (void) mtp; (void) R_rows; (void) next_tokens; (void) n; (void) cell0; (void) err; + if (why) *why = "the Metal window feeds the draft layer itself"; + return false; +#endif const core::OnDevice on_device(m.device); // the stage's own GPU current (a layer split's drafter: the last stage) auto decline = [&](const char* reason) { if (why != nullptr) *why = reason; return false; }; static const bool off = [] { const char* v = std::getenv("STRATA_MTP_BATCH"); return v != nullptr && v[0] == '0'; }(); @@ -4315,6 +4336,16 @@ bool Prefill::drain_pipeline(std::string& err) { } bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err) { +#if defined(STRATA_GPU_METAL) + { + const auto t0 = std::chrono::steady_clock::now(); + const bool ok = strata::metal_engine::prompt_run(tokens, n, pos0, embd_rows, on_chunk, err); + stats_.tokens += n; + stats_.chunks += 1; + stats_.ms_total += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + return ok; + } +#endif const bool body_ok = run_impl(tokens, n, pos0, err); std::string drain_err; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 9cd64fc0..f2ca6029 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -99,10 +99,15 @@ #include #include #include +#if !defined(__APPLE__) // major() / minor(): on macOS #include #endif +#endif #include +#if defined(STRATA_GPU_METAL) +namespace strata::metal_engine { void set_model_shard(const char* shard1); } // metal/src/engine/window.cpp +#endif #include #include @@ -553,7 +558,11 @@ struct Options { /// Plan v0.3 P6: speculative decoding with a verify window of this many tokens (the last accepted token and /// spec-1 drafts); 0 = plain decode. `spec_oracle` drafts from a token file (the expected continuation, for /// the exactness test); `spec_corrupt` N > 0 replaces every Nth draft with a wrong token. +#if defined(STRATA_GPU_METAL) + int spec = 2; // Metal: a window of 2 by default (measured best on the M5 Max; an explicit --spec wins) +#else int spec = 0; +#endif /// --serve runs up to this many sequences at once, one token each per batch window (0 = off). A request /// sent as `BGEN ...` reads its prompt and its first token through the usual path, then /// continues in slot of the batch windows (`BT ` lines, then `BDONE ...`). @@ -2754,7 +2763,13 @@ int main(int argc, char** argv) { // The experimental older-CPU build (STRATA_ISA_FLOOR=avx|none, compiled on that PC; #394 #595 #623) has ggml-cpu // for that floor, so a native pack's experts run there on ggml-cpu (every AVX2 kernel is behind cpu_avx2_ok). const char* isa_floor = strata::kernels::cpu::isa_floor_build(); +#if defined(STRATA_GPU_METAL) // Apple Silicon: every expert is on the GPU; ggml-cpu (NEON) is the only CPU expert code + strata::metal_engine::set_model_shard(o.native_preset.c_str()); // the decode window reads the model GGUF itself + o.mmap_experts = true; // ... experts included: no resident copy of them (the GGUF shards in place) + if (false) { +#else if (!strata::kernels::cpu::cpu_avx2_ok() && isa_floor[0] == '\0') { +#endif std::fprintf(stderr, "strata generate: this CPU (%s) does not support AVX2 with FMA and F16C, which this engine's " "CPU expert kernels need; Strata runs on Intel Haswell (2013), AMD Zen (2017) or newer. " "Older CPUs are EXPERIMENTAL and slow: setup compiles an engine for them on this PC " @@ -4782,7 +4797,7 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: GPU %d: %s, compute capability %d.%d%s\n", dev, name, strata::cc_major_of(p.major), strata::cc_minor_of(p.minor), strata::emulated_cc() ? " (STRATA_EMULATE_CC: a test mode, the card is emulated)" : ""); -#if !defined(STRATA_HIP_GFX906) // a CUDA toolkit mismatch; the gfx906 HIP build has no CUDART_VERSION +#if !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL) // a CUDA toolkit mismatch; the gfx906 HIP build has no CUDART_VERSION { // #542: a build whose libcudart is older than its headers (a CUDA 13 kit with a dangling libcudart.so that // CMake resolved to the system's CUDA 12 one) reads cudaDeviceProp shifted - silently, and slowly int rt = 0; @@ -12931,6 +12946,13 @@ int main(int argc, char** argv) { } } save_profile("exit"); // #477: QUIT, or the server closed stdin +#if defined(STRATA_GPU_METAL) + // the stdin reader (detached above) may still take in_mu when the server closes the pipe after QUIT; on macOS + // locking that mutex once this scope has destroyed it throws (the engine ended with an abort): end here + std::fflush(stdout); + std::fflush(stderr); + std::_Exit(0); +#endif return 0; } diff --git a/tools/test_setup_mac.py b/tools/test_setup_mac.py new file mode 100644 index 00000000..ce63dc08 --- /dev/null +++ b/tools/test_setup_mac.py @@ -0,0 +1,197 @@ +"""Tests for setup on a Mac (metal/setup_mac.py and setup.py's hand-over): the Mac check, the pack recommended by +unified memory, what a bigger choice risks, the engine arguments with the Metal defaults and the config. Runs on any +PC: sysctl / sw_vers / xcode-select are mocked. No GPU, no network. + + python -m unittest tools.test_setup_mac +""" +from __future__ import annotations + +import subprocess +import sys +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "metal")) +import setup # noqa: E402 +import setup_mac as M # noqa: E402 + + +def fake_run(values: dict, clt_rc=0): + def run(cmd, **kw): + if cmd[0] == "sysctl": + return subprocess.CompletedProcess(cmd, 0, values.get(cmd[2], ""), "") + if cmd[0] == "sw_vers": + return subprocess.CompletedProcess(cmd, 0, values.get("macos", ""), "") + if cmd[0] == "xcode-select": + return subprocess.CompletedProcess(cmd, clt_rc, "/Library/Developer/CommandLineTools" if clt_rc == 0 else "", + "") + raise AssertionError(cmd) + return run + + +M5 = {"machdep.cpu.brand_string": "Apple M5 Max", "hw.memsize": str(128 * 2 ** 30), "macos": "27.2", + "hw.perflevel0.physicalcpu": "12"} + + +class MacCheck(unittest.TestCase): + def test_reads_chip_memory_macos_and_tools(self): + with mock.patch.object(M.platform, "machine", return_value="arm64"): + info = M.mac_info(fake_run(M5)) + self.assertEqual(info["chip"], "Apple M5 Max") + self.assertAlmostEqual(info["ram_gb"], 128.0) + self.assertEqual(info["macos"], "27.2") + self.assertTrue(info["arm64"]) + self.assertTrue(info["clt"]) + self.assertEqual(M.mac_problems(info), []) + + def test_intel_old_macos_and_missing_tools_are_named(self): + with mock.patch.object(M.platform, "machine", return_value="x86_64"): + info = M.mac_info(fake_run({**M5, "macos": "14.6", "machdep.cpu.brand_string": "Intel Core i9"}, clt_rc=2)) + p = " | ".join(M.mac_problems(info)) + self.assertIn("Apple Silicon", p) + self.assertIn("macOS 15", p) + self.assertIn("xcode-select --install", p) + + +class Recommendation(unittest.TestCase): + def test_by_memory(self): + # IQ3_S and UD-Q4_K_XL are the recommended sizes; IQ3_S is the default wherever it stays resident + self.assertEqual(M.RECOMMENDED, ("IQ3_S", "UD-Q4_K_XL")) + rec, notes = M.recommend_model(128) + self.assertEqual(rec, "IQ3_S") + self.assertTrue(any("UD-Q4_K_XL" in n and "higher quality" in n for n in notes)) # named next to it + rec96, notes96 = M.recommend_model(96) + self.assertEqual(rec96, "IQ3_S") + self.assertFalse(notes96) # UD-Q4_K_XL does not fit 96 GB resident: no note + self.assertEqual(M.recommend_model(64)[0], "Q2_0") # no recommended size fits: the largest that does + self.assertEqual(M.recommend_model(80)[0], "IQ3_XXS") + rec, notes = M.recommend_model(32) + self.assertEqual(rec, "Q2_0") + self.assertTrue(notes and "stream" in notes[0] and "~14 tok/s" in notes[0]) + self.assertTrue(M.streams("Q2_0", 32) and M.streams("Q2_0", 48) and not M.streams("Q2_0", 64)) + + def test_a_bigger_choice_is_kept_with_a_note(self): + notes = M.model_note("IQ3_XXS", 64) + self.assertTrue(any("stream from the SSD" in n for n in notes)) + self.assertEqual(M.model_note("Q2_0", 128), []) + self.assertEqual(M.model_note("IQ3_S", 128), []) + + def test_context(self): + self.assertEqual(M.recommend_context(64), 32768) + self.assertEqual(M.recommend_context(128), 65536) + + +class Config(unittest.TestCase): + def test_engine_args_carry_the_metal_defaults(self): + args = M.engine_args(Path("/p/packs/q2_0"), [Path("/m/a-00001.gguf"), Path("/m/a-00002.gguf")], + Path("/d/mtp/rt"), 32768) + self.assertEqual(args[args.index("--spec") + 1], "2") + self.assertEqual(args[args.index("--native") + 1], str(Path("/m/a-00001.gguf"))) + self.assertEqual(args[args.index("--ple-gguf") + 1], str(Path("/m/a-00002.gguf"))) + self.assertEqual(args[args.index("--mtp") + 1], str(Path("/d/mtp/rt"))) + self.assertIn("--expert-profile", args) + self.assertNotIn("--hc-q8", args) # Q8_0 HC is the engine's own default on Metal + st = M.engine_args(Path("/p"), [Path("/a1.gguf"), Path("/a2.gguf")], Path("/d/mtp/rt"), 32768, stream=True) + self.assertNotIn("--mtp", st) # streaming: one token per step, no draft layer + self.assertEqual(st[st.index("--suffix-draft") + 1], "0") + self.assertEqual(st[st.index("--spec") + 1], "2") + # a big Mac that streams (UD-Q5/Q6 on 128 GB) keeps the draft layer, with a longer window + big = M.engine_args(Path("/p"), [Path("/a1.gguf"), Path("/a2.gguf")], Path("/d/mtp/rt"), 65536, stream=True, + ram_gb=128) + self.assertEqual(big[big.index("--mtp") + 1], str(Path("/d/mtp/rt"))) + self.assertEqual(big[big.index("--spec") + 1], "3") + self.assertEqual(big[big.index("--suffix-draft") + 1], "0") + small = M.engine_args(Path("/p"), [Path("/a1.gguf"), Path("/a2.gguf")], Path("/d/mtp/rt"), 32768, stream=True, + ram_gb=32) + self.assertNotIn("--mtp", small) + self.assertTrue(M.stream_mtp(False, 16) and M.stream_mtp(True, 128) and not M.stream_mtp(True, 64)) + + def test_config_is_a_model_config_with_the_metal_backend(self): + cfg = M.mac_config(Path("/r/build-metal/strata"), ["--pack", "x"], Path("/p"), "qwen3.8-flash-next-q2_0", + "Q2_0", 8080) + self.assertEqual(cfg["backend"], "metal") + self.assertEqual(cfg["tokenizer"], str(Path("/p") / "tokenizer")) + self.assertTrue(cfg["exe"] and isinstance(cfg["args"], list)) + + +class Vision(unittest.TestCase): + def test_the_projector_is_pinned_and_the_encoder_builds_with_metal(self): + self.assertIn("mmproj-Qwen3.8-Flash-Next-BF16.gguf", M.VISION_SHA256) + src = (ROOT / "metal" / "setup_mac.py").read_text(encoding="utf-8") + self.assertIn('"-DSTRATA_VISION_CUDA=OFF"', src) + self.assertIn('cfg["args"] += ["--vision"]', src) + + +class ExpertsFile(unittest.TestCase): + """The streaming Mac's .experts: written only with room on the disk, else a warning and the GGUF.""" + + def run_it(self, free_gb, done=False): + import tempfile + sys.path.insert(0, str(ROOT / "metal" / "tools")) + import stream_experts + d = Path(tempfile.mkdtemp()) + native = d / "m.gguf" + native.write_bytes(b"") + if done: + (d / "m.gguf.experts").write_bytes(b"") + (d / "m.gguf.experts.done").write_text("x") + with mock.patch.object(stream_experts, "size_bytes", return_value=40e9), \ + mock.patch.object(M.S, "free_gb", return_value=free_gb), \ + mock.patch.object(M.S, "run") as run, mock.patch.object(M.S, "warn") as warn, \ + mock.patch.object(M.S, "mark") as mark, mock.patch.object(M.S, "say"), mock.patch.object(M.S, "ok"): + M.experts_file(native) + return run, warn, mark + + def test_fits_needs_the_margin(self): + self.assertFalse(M.experts_file_fits(40, 40 + M.EXPERTS_MARGIN_GB - 0.1)) + self.assertTrue(M.experts_file_fits(40, 40 + M.EXPERTS_MARGIN_GB)) + + def test_written_and_verified_with_room(self): + run, warn, mark = self.run_it(100) + self.assertIn("--verify", run.call_args[0][0]) + self.assertTrue(str(run.call_args[0][0][1]).endswith("stream_experts.py")) + mark.assert_called_once() + warn.assert_not_called() + + def test_too_little_disk_warns_and_goes_on(self): + run, warn, mark = self.run_it(45) + run.assert_not_called() + mark.assert_not_called() + self.assertIn("not written", warn.call_args[0][0]) + + def test_done_is_not_written_again(self): + run, warn, mark = self.run_it(100, done=True) + run.assert_not_called() + + +class HandOver(unittest.TestCase): + def test_darwin_hands_the_run_to_setup_mac(self): + with mock.patch.object(setup.sys, "platform", "darwin"), \ + mock.patch.object(setup.subprocess, "call", return_value=0) as call, \ + mock.patch.object(setup.sys, "argv", ["setup.py", "--model", "Q2_0", "--yes"]): + self.assertEqual(setup.main(), 0) + cmd = call.call_args[0][0] + self.assertTrue(cmd[1].endswith(str(Path("metal") / "setup_mac.py"))) + self.assertEqual(cmd[2:], ["--model", "Q2_0", "--yes"]) + + def test_other_platforms_never_reach_it(self): + src = (ROOT / "setup.py").read_text(encoding="utf-8") + self.assertIn('if sys.platform == "darwin":', src) + with mock.patch.object(setup, "mac_setup", side_effect=AssertionError("called")), \ + mock.patch.object(setup.sys, "platform", "linux"), \ + mock.patch.object(setup.sys, "argv", ["setup.py", "--inspect", "x"]), \ + mock.patch.object(setup.subprocess, "run", return_value=subprocess.CompletedProcess([], 0)): + with self.assertRaises(SystemExit): + setup.main() + + def test_setup_sh_fetches_a_pinned_python_on_macos_only(self): + sh = (ROOT / "setup.sh").read_text(encoding="utf-8") + self.assertIn('[ "$(uname -s)" = Darwin ]', sh) + self.assertIn("83dcb04777c798bd95f3687acf9ae84b09860272ee6bdfb05be8bcf9447f75b8", sh) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/vision/strata_vision.cpp b/tools/vision/strata_vision.cpp index d8ef58fe..9a06ce1f 100644 --- a/tools/vision/strata_vision.cpp +++ b/tools/vision/strata_vision.cpp @@ -99,7 +99,7 @@ int main(int argc, char** argv) { llama_backend_init(); const auto load_t0 = std::chrono::steady_clock::now(); -#if !defined(_WIN32) +#if !defined(_WIN32) && !defined(__APPLE__) // macOS has no posix_fadvise // ask the OS for the projector file up front (128 KiB steps) so the loader's sequential reads find it cached; // STRATA_READ_AHEAD=0 turns it off, as in the engine if (const char* ra = std::getenv("STRATA_READ_AHEAD"); ra == nullptr || std::atoi(ra) != 0) {