Merge branch 'f-139b-old' into f-139-rel

# Conflicts:
#	setup.py
This commit is contained in:
Niko1221 committed 2026-10-04 10:12:13 +02:00
commit bd34d0d87e
65 files changed
+6759 -123

No files matched your search

+5
View File
@@ -37,17 +37,22 @@ td.log
/strata-*.json
/strata-*.log
/build-strata.bat
/build-strata-cuda12.bat
/build-cuda12/
/.strata-mcp/
# image encoder (setup.py --vision): build output and the generated build script
build-vision*/
build-vision.bat
build-vision-cuda12.bat
# setup.py outputs (engine, downloads) and release builds
/engine/
/engine-cuda12/
/build-release*/
/dist/
*.done
/third_party/*.zip
/.ccache/
/.rocm-win/
+91 -7
View File
@@ -45,7 +45,19 @@ if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
endif()
option(STRATA_ENABLE_CUDA "Build the CUDA targets (Phase 2+)" OFF)
option(STRATA_ENABLE_HIP "Build the HIP targets for wave32 AMD GPUs (gfx1100, gfx1201; gfx1030 unvalidated)" OFF)
# AMD gfx906 (MI50, wave64): the same .cu sources compiled as HIP through the gfx906 compat layer. The CUDA runtime and
# cuBLAS names are mapped by the headers in include/strata/platform/hip_compat/, which go first on the include path,
# and CUDA::cudart / CUDA::cublas become aliases of HIP's targets, so every CUDA target below stays as it is. This is
# separate from STRATA_ENABLE_HIP (the wave32 RDNA backend): with it on, STRATA_ENABLE_CUDA is on and
# STRATA_ENABLE_HIP stays off, so every "CUDA" branch of the tree is the one taken.
option(STRATA_HIP_GFX906 "Build the CUDA targets for AMD gfx906 through HIP (wave64 compat layer)" OFF)
if(STRATA_HIP_GFX906)
if(STRATA_ENABLE_HIP)
message(FATAL_ERROR "STRATA_HIP_GFX906 and STRATA_ENABLE_HIP are separate backends; enable only one")
endif()
set(STRATA_ENABLE_CUDA ON CACHE BOOL "" FORCE)
endif()
option(STRATA_ENABLE_HIP "Build the HIP targets for wave32 AMD GPUs (gfx1100, gfx1201; gfx1012/gfx1030 unvalidated)" OFF)
option(STRATA_PREFILL_MMQ "Build the optional GGML MMQ prefill path for HIP" OFF)
# CUDA: MMQ prompt kernels for Q4_K / Q5_K / Q5_1 (Unsloth's UD-Q4_K_XL experts). Off by default: the engine loads
# every kernel when it starts (CUDA_MODULE_LOADING=EAGER), so these took ~5 MB of VRAM - 1-3 expert slots - from every
@@ -55,7 +67,7 @@ option(STRATA_ORCA_Q4KS_MMQ "Build the GGML Q5_0 MMQ instance for OrcaRouter Q4_
if(STRATA_PREFILL_MMQ AND NOT STRATA_ENABLE_HIP)
message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_ENABLE_HIP=ON")
endif()
if(STRATA_ENABLE_CUDA AND STRATA_ENABLE_HIP)
if(STRATA_ENABLE_CUDA AND STRATA_ENABLE_HIP AND NOT STRATA_HIP_GFX906)
message(FATAL_ERROR "STRATA_ENABLE_CUDA and STRATA_ENABLE_HIP are separate backends; enable only one")
endif()
if(STRATA_ENABLE_HIP)
@@ -80,7 +92,27 @@ if(STRATA_BUILD_CONVERSATION_TESTS)
add_test(NAME conversation_memory_test COMMAND conversation_memory_test)
endif()
if(STRATA_ENABLE_CUDA)
if(STRATA_HIP_GFX906)
if(NOT DEFINED CMAKE_HIP_ARCHITECTURES)
set(CMAKE_HIP_ARCHITECTURES gfx906 CACHE STRING "HIP architectures" FORCE)
endif()
enable_language(HIP)
find_package(hip REQUIRED)
find_package(hipblas REQUIRED)
add_library(CUDA::cudart INTERFACE IMPORTED)
target_link_libraries(CUDA::cudart INTERFACE hip::host)
target_compile_definitions(CUDA::cudart INTERFACE STRATA_HIP_GFX906=1 __HIP_PLATFORM_AMD__=1)
target_include_directories(CUDA::cudart BEFORE INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/platform/hip_compat)
add_library(CUDA::cublas INTERFACE IMPORTED)
target_link_libraries(CUDA::cublas INTERFACE roc::hipblas CUDA::cudart)
set(CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/platform/hip_compat)
include_directories(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/platform/hip_compat)
add_compile_definitions(STRATA_HIP_GFX906=1)
message(STATUS "Strata: HIP (gfx906 compat) enabled, arch ${CMAKE_HIP_ARCHITECTURES}")
set(_strata_gpu_runtime_target CUDA::cudart)
set(_strata_gpu_blas_target CUDA::cublas)
set(_strata_gpu_include_directories ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES})
elseif(STRATA_ENABLE_CUDA)
# #585: CMake links CUDA code with the STATIC runtime by default, and the targets below also link CUDA::cudart (the
# DLL's import library). MSVC with a CUDA 12.x toolkit - the experimental Pascal/Volta build - then fails with
# LNK1169 (every cudart symbol defined twice); GNU ld lets it pass. That build links the shared runtime alone. The
@@ -126,13 +158,18 @@ if(STRATA_ENABLE_CUDA)
"CUDA 12.8 crashed on long prompts on these cards (issues #220, #224). Use CUDA 13.0 or newer.")
endif()
endforeach()
if(STRATA_EXPERIMENTAL_SM60)
# every target sees it: the Pascal / Volta code paths (the Volta prompt attention, PR #600) are compiled into this
# build only, so the ready-made engine (sm_75+) keeps exactly the code it had
add_compile_definitions(STRATA_EXPERIMENTAL_SM60=1)
endif()
message(STATUS "Strata: CUDA enabled, arch ${CMAKE_CUDA_ARCHITECTURES}")
set(_strata_gpu_runtime_target CUDA::cudart)
set(_strata_gpu_blas_target CUDA::cublas)
set(_strata_gpu_include_directories ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES})
elseif(STRATA_ENABLE_HIP)
set(_strata_gpu_runtime_target strata_hip_runtime)
set(_strata_gpu_blas_target roc::hipblas)
set(_strata_gpu_blas_target ${STRATA_HIP_BLAS_TARGETS})
set(_strata_gpu_include_directories ${STRATA_HIP_COMPAT_INCLUDE_DIR})
endif()
@@ -328,7 +365,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
src/kernels/cuda/native_flash_attn.cu
src/kernels/cuda/native_qsa_indexer.cu
src/kernels/cuda/native_qsa_score.cu
PROPERTIES COMPILE_OPTIONS "--use_fast_math")
PROPERTIES COMPILE_OPTIONS "$<IF:$<BOOL:${STRATA_HIP_GFX906}>,,--use_fast_math>")
elseif(STRATA_ENABLE_HIP)
# Keep Q8_K's multiply and magic-bias rounding as separate FP32 operations on HIP; contraction to an
# FMA changes tie results. The embedding gather also relies on separately rounded operations.
@@ -450,6 +487,14 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
if(STRATA_ENABLE_HIP)
enable_testing()
set(_strata_hip_tests)
add_executable(hip_prefill_gemm tests/hip/prefill_gemm.cpp)
target_link_libraries(hip_prefill_gemm PRIVATE strata_prefill strata_hip_runtime)
add_test(NAME hip_prefill_gemm COMMAND hip_prefill_gemm)
list(APPEND _strata_hip_tests hip_prefill_gemm)
add_executable(hip_q2_zero tests/hip/q2_zero.cpp)
target_link_libraries(hip_q2_zero PRIVATE strata_kernels strata_hip_runtime)
add_test(NAME hip_q2_zero COMMAND hip_q2_zero)
list(APPEND _strata_hip_tests hip_q2_zero)
add_executable(hip_expert_cache_staging tests/hip/expert_cache_staging.cpp)
target_link_libraries(hip_expert_cache_staging PRIVATE strata_engine)
add_test(NAME hip_expert_cache_staging COMMAND hip_expert_cache_staging)
@@ -583,6 +628,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
target_include_directories(mmvq_multi_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(mmvq_multi_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_test(NAME mmvq_multi_parity COMMAND mmvq_multi_parity)
if(STRATA_HIP_GFX906) # the CUDA layout, where the negative control has power (the wave64 one is exact at every T)
add_test(NAME mmvq_multi_parity_cuda_layout COMMAND mmvq_multi_parity)
set_tests_properties(mmvq_multi_parity_cuda_layout PROPERTIES ENVIRONMENT "STRATA_MMVQ_WAVE=0")
endif()
endif()
# the IQ kernels that decode a weight part once for every column/entry, bitwise vs the per-column ones
# (GPU, synthetic, no model; --bench adds old/new timings)
@@ -591,11 +640,16 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
target_link_libraries(iq_multi_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_test(NAME iq_multi_parity COMMAND iq_multi_parity)
# the prompt path's DeltaNet recurrence: gdn_rec_kh_kernel against gdn_rec_cols_pipe_kernel, bitwise (GPU,
# synthetic, no model; --bench adds timings)
if(STRATA_ENABLE_CUDA)
# synthetic, no model; --bench adds timings). NVIDIA only: cp.async and the CUDA occupancy API (not on gfx906)
if(STRATA_ENABLE_CUDA AND NOT STRATA_HIP_GFX906)
add_executable(gdn_rec_parity src/prefill/gdn_rec_parity.cu)
target_link_libraries(gdn_rec_parity PRIVATE ${_strata_gpu_runtime_target})
add_test(NAME gdn_rec_parity COMMAND gdn_rec_parity)
# the prompt path's BF16 products against cuBLAS's own BF16 GEMM, within fp32 rounding (sm_7x runs them on the
# FP16 tensor cores; GPU, synthetic, no model; --bench adds timings)
add_executable(gemm_bf16_parity src/prefill/gemm_bf16_parity.cu)
target_link_libraries(gemm_bf16_parity PRIVATE strata_prefill )
add_test(NAME gemm_bf16_parity COMMAND gemm_bf16_parity)
endif()
# native_expert_grouped's group stride and fused SwiGLU + q8_1, bitwise vs the launches before them (GPU, synthetic,
# no model; --bench adds v1/new timings of a window's 48 calls in a graph)
@@ -608,6 +662,9 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
target_link_libraries(shared_expert_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_test(NAME shared_expert_parity COMMAND shared_expert_parity --selftest)
add_executable(fused_gr_bench src/kernels/fused_gr_bench.cpp)
target_include_directories(fused_gr_bench PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(fused_gr_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_executable(gr_parity src/kernels/gr_parity.cpp)
target_include_directories(gr_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(gr_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
@@ -652,10 +709,22 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
target_link_libraries(quantize_act_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_test(NAME quantize_act_parity COMMAND quantize_act_parity --selftest)
# the verify window's routing in one multi-column BF16 projection + one top-k, bitwise the per-token calls
add_executable(route_window_parity src/kernels/route_window_parity.cpp)
target_include_directories(route_window_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(route_window_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_test(NAME route_window_parity COMMAND route_window_parity)
add_executable(router_top10_parity src/kernels/router_top10_parity.cpp)
target_include_directories(router_top10_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(router_top10_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_test(NAME router_top10_parity COMMAND router_top10_parity --selftest)
if(STRATA_HIP_GFX906)
# the S6 router (STRATA_HIP_ROUTER_FAST=1 on gfx906) against the portable kernel, bitwise, on wave64
add_executable(hip_router_fast tests/hip/router_fast.cpp)
target_include_directories(hip_router_fast PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(hip_router_fast PRIVATE strata_kernels ${_strata_gpu_runtime_target})
endif()
add_executable(s_gemv_parity src/kernels/s_gemv_parity.cpp)
target_include_directories(s_gemv_parity PRIVATE ${_strata_gpu_include_directories})
@@ -1058,6 +1127,9 @@ if(STRATA_NATIVE_EXPERTS)
add_executable(native_expert_parity src/kernels/native_expert_parity.cpp)
target_include_directories(native_expert_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(native_expert_parity PRIVATE strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target})
add_executable(native_expert_bench src/kernels/native_expert_bench.cpp)
target_include_directories(native_expert_bench PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(native_expert_bench PRIVATE strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target})
if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA)
# Unsloth UD-Q4_K_XL's three expert pairs (and Q8_0 alone, its embedding) on synthetic ggml-quantized weights
# at 2560/640: GPU and CPU experts against the float reference, GPU dequantizers against to_float.
@@ -1140,3 +1212,15 @@ if(STRATA_BUILD_TESTS)
add_subdirectory(tests)
endif()
endif()
# ---- HIP gfx906: every CUDA source of the tree (and the ggml-cuda MMQ sources) is compiled as HIP ----
if(STRATA_HIP_GFX906)
file(GLOB_RECURSE _strata_cu CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/*.cu ${CMAKE_CURRENT_SOURCE_DIR}/bench/micro/*.cu
${CMAKE_CURRENT_SOURCE_DIR}/tools/vision/*.cu)
if(_strata_mmq)
file(GLOB _strata_mmq_cu ${_strata_mmq}/*.cu ${_strata_mmq}/template-instances/*.cu)
list(APPEND _strata_cu ${_strata_mmq_cu})
target_compile_definitions(strata_mmq PRIVATE GGML_USE_HIP)
endif()
set_source_files_properties(${_strata_cu} PROPERTIES LANGUAGE HIP)
endif()
+2
View File
@@ -58,6 +58,8 @@ other cards: [speed of each model](docs/MODELS.md#how-fast-is-each-size), [commu
| **System** | Windows 10 / 11 or Linux, and a current graphics driver from NVIDIA or AMD |
Everything else is installed for you. Two or three cards can share the model ([multi-GPU](docs/MULTI_GPU.md)).
Older cards (Tesla P40 / V100, GTX 10, Radeon VII / MI50, RX 6700 XT, RX 5500 XT) run through community-written,
experimental paths: [Older GPUs](docs/OLDER_GPUS.md).
The full list: [docs/INSTALL.md](docs/INSTALL.md#what-you-need).
## Install
@@ -0,0 +1,121 @@
# Community benchmark: 2x AMD Instinct MI50 16 GB (gfx906), Xeon E5-2666 v3
Measured on 2026-10-03 by [JeanP00l](https://github.com/JeanP00l) on a Linux server. This tests the Coder
(IQ1_M) with a 131,072-token context, the layer split across two MI50 cards, and the gfx906 build of #638. That
build is an opt-in HIP build, separate from the wave32 RDNA backend.
The median decode throughput was **50.1 tok/s at 4,096 prompt tokens, 47.8 tok/s at 32,768 and 45.7 tok/s at
128,000**. Prompts were read at 321, 523 and 517 tok/s. The requests are synthetic code-explanation requests
with greedy decoding and a 256-token output cap. They do not establish general answer quality or performance on
other workloads.
## Hardware and software
- **GPUs:** 2x AMD Instinct MI50 16 GB (Vega 20, gfx906, wave64; HIP names them "AMD Radeon VII"). Power limit
85 W per card, set by the owner (the cards' own limit is higher). PCIe 3.0 x16 on both. Peer access between them
works, through the CPU's root complex (no direct bridge). Blower fans; no clock locking beyond the power limit.
The engine's PCIe probe measured 13.8 GB/s host to device.
- **CPU and RAM:** Intel Xeon E5-2666 v3 (10 cores, 20 threads, AVX2, no AVX-512); the engine used 9 expert-pool
workers plus its host thread. 32 GB DDR4 quad-channel (Linux reports 31.2 GiB). 8 GiB swap file. One SATA SSD.
- **OS and runtime:** Ubuntu 24.04.4 LTS, kernel 6.8.0-138-generic, the kernel's amdgpu driver. HIP 7.14 from the
community image `mixa3607/rocm-gfx906:7.14-complete` (AMD's current ROCm no longer ships gfx906 libraries).
- **Source:** [`mi50-bench-build`](https://github.com/JeanP00l/Strata/tree/mi50-bench-build) at `ea51fd3`, which is
`main` 99f3dbd (engine 0.1.38) with #638 (at 17beb33), #639, #640 and #637 merged. #638's later commits
(a914b13) only fix the CUDA/RDNA compile and do not change the gfx906 binary's behaviour.
- **Build:** `-DSTRATA_HIP_GFX906=ON -DCMAKE_HIP_ARCHITECTURES=gfx906 -DSTRATA_PORTABLE=ON`, ROCm clang, Ninja,
llama.cpp at the pinned 3cf0325.
- **Other services:** the machine's other GPU services were stopped, so the two cards ran only Strata. CPU services
(a database, a sync daemon) kept running. This was not a fully isolated operating system.
## Model and configuration
**Model:** [`ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF`](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF),
IQ1_M. The repository revision was not recorded; the shard SHA-256 hashes matched the `.sha256` files downloaded
with them:
- `Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00001-of-00002.gguf` `e11083ba855e7666b48ea3f2db6a9c3a20c18751a012cc24f948de91b7087fad`
- `Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00002-of-00002.gguf` `316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113`
The native pack and the MTP draft layer were prepared with the repository's tools on 2026-09-29. The expert profile is the bundled
`data/expert-profile-coder.bin`.
**Configuration** ([strata-coder.json](strata-coder.json); `/m` is the model directory, `/work` the build):
- context 131,072, `--kv int8 --kv-resident 32768` (32,768 KV cells per attention layer in VRAM, the rest streamed
from RAM);
- `layer_split 27`: layers 0-26 on GPU 0, 27-47 on GPU 1. With #639 each GPU loads only its own layers' dense
weights;
- expert cache `auto`, `--vram-reserve-mib 600`: 6,912 + 5,376 slots = **all 12,288 experts in VRAM**, prefilled
from the profile, no eviction;
- `--prefill 4096`, with the prompt path borrowing 1,193 + 1,084 cache slots;
- MTP `--spec 4 --spec-min-p 0.5`; suffix drafting on (the default);
- `--pcie-frac 0`, required with `STRATA_ARENA_MMAP=1` (#640, the expert arena as a read-only mapped file; 23.4
GiB of VRAM-held experts handed back to the OS at start);
- no vision, no calibration, no speed projection, no control vectors;
- reasoning off (`reasoning_effort: none`), temperature 0, 256 generated tokens per speed run.
## Method
[benchmark.py](benchmark.py) is the script of the
[RTX 5090 report](../2026-09-30-community-rtx-5090/README.md), unchanged. It builds deterministic synthetic Python
filler, puts a different nonce near the start of each request, and counts the rendered chat prompt with Strata's
tokenizer. Its request hashes and the output text of every run are in [results.json](results.json); the aggregates
are in [summary.json](summary.json).
The server ran in a container with both cards (the repository's `serve/` and `tools/` from the source above):
```bash
docker run --device=/dev/kfd --device=/dev/dri --group-add video --ipc=host --ulimit memlock=-1 \
-e HSA_OVERRIDE_GFX_VERSION=9.0.6 -e STRATA_ARENA_MMAP=1 ... \
python3 serve/server.py --engine strata --config strata-coder.json --port 8080
python3 benchmark.py --root /opt/strata --pack /m/pack-coder --url http://127.0.0.1:8080 --out results/
python3 tools/needle_bench.py --url http://127.0.0.1:8080 --lengths 32k,128k --depths 10,50,90 --out needles.json
```
- One short warm-up request is excluded.
- Three runs at each length ran serially, in increasing-length order, on the same loaded engine.
- All nine speed requests read their whole prompt: **zero reused tokens**.
- The expert cache was filled at start and kept between requests. Loading time is excluded.
- TTFT is streaming, from just before the HTTP request to the first nonempty text delta, over loopback.
- Prompt throughput is freshly read tokens / `prompt_ms`. Decode throughput is `engine_generated / decode_ms`.
- [engine.log](engine.log) is the engine's whole log for this session, including the start-up decisions.
## Results
Each cell is the median **[minimum-maximum]** of three runs. Every request generated 256 tokens and stopped at
the output limit. No speed request failed or was cancelled.
| Prompt tokens | Reused | Prompt tok/s | Decode tok/s | TTFT seconds | Total seconds |
| ---: | ---: | ---: | ---: | ---: | ---: |
| 4,096 | 0 | 320.9 [309.9-324.7] | 50.1 [49.3-54.0] | 12.81 [12.66-13.26] | 17.90 [17.38-18.43] |
| 32,768 | 0 | 522.8 [522.6-523.4] | 47.8 [47.6-48.5] | 62.81 [62.75-62.84] | 68.10 [68.10-68.15] |
| 128,000 | 0 | 516.8 [516.5-516.9] | 45.7 [44.8-51.5] | 248.09 [248.06-248.27] | 253.75 [253.03-253.84] |
- The decode expert-cache hit rate was 100% for every request. All experts are in VRAM; the CPU pool computes none.
- The 4K prompt reads at about 60% of the longer ones' speed, because a 4,096-token chunk pays the fixed per-chunk
cost once.
- Draft acceptance varies between runs (decode 44.8-51.5 tok/s at 128K) although the text is greedy.
**Memory**, from [telemetry.jsonl](telemetry.jsonl) (1,699 one-second samples over 1,763 s, from start through
the recall checks):
- VRAM peak: 15.42 GiB on GPU 0 and 14.70 GiB on GPU 1 (`mem_info_vram_used`, the whole card).
- RAM: `MemAvailable` never below **25.1 GiB** of 31.2.
- Swap: no growth during the run. The swap file held ~1.3 GiB from earlier use before the start.
These are sampled values; brief peaks between samples can be missed.
## Recall and limitations
The repository's unchanged `tools/needle_bench.py` found **all six needles**, at depths 10%, 50% and 90% at both
lengths ([needles.json](needles.json)):
- `32k` prompts were 25,776-25,777 tokens and `128k` prompts 103,725-103,727 tokens.
- The last 128K case reused 49,785 prompt tokens; the other five reused none.
**Limits of this report:**
- One machine, one quantization, one configuration, and a small synthetic workload.
- Long output, sampled decoding, thinking, coding-task correctness, vision, tool use, concurrency and a sustained
thermal run were not part of this report.
- For context, on the same machine and model, llama.cpp (3cf0325, ROCm) measured 26.9 tok/s `tg128` on 2026-09-29.
That is a different workload, not a controlled comparison.
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""Serial, fresh-prompt Strata benchmark. Run inside its prepared environment."""
import argparse
import hashlib
import json
import statistics
import sys
import time
import urllib.request
from pathlib import Path
def get(url):
with urllib.request.urlopen(url, timeout=30) as response:
return json.load(response)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, default=Path("/workspace/Strata"))
parser.add_argument("--pack", type=Path, default=Path("/workspace/Strata-data/packs/iq2_xs"))
parser.add_argument("--url", default="http://127.0.0.1:18080")
parser.add_argument("--out", type=Path, default=Path("/workspace/results"))
parser.add_argument("--targets", default="4096,32768,128000")
parser.add_argument("--runs", type=int, default=3)
args = parser.parse_args()
args.out.mkdir(parents=True, exist_ok=True)
sys.path[:0] = [str(args.root), str(args.root / "tools")]
from strata_tokenizer import Tokenizer
from serve.frontend import ChatTemplate, openai_to_messages
directory = args.pack / "tokenizer"
vocab = json.loads((directory / "vocab.json").read_text())
tokens = [None] * len(vocab)
for token, number in vocab.items():
tokens[number] = token
tokenizer = Tokenizer(tokens, (directory / "merges.txt").read_text().splitlines(),
json.loads((directory / "token_type.json").read_text()))
template = ChatTemplate(directory / "chat_template.jinja")
initial = get(args.url + "/v1/status")
(args.out / "initial-status.json").write_text(json.dumps(initial, indent=2) + "\n")
rows = []
def request(content, maximum=256):
return {"model": "strata", "messages": [{"role": "user", "content": content}],
"temperature": 0, "reasoning_effort": "none", "max_tokens": maximum,
"stream": True, "stream_options": {"include_usage": True}}
def count(req):
messages, tools, kwargs = openai_to_messages(req)
return len(tokenizer.encode(template.render(messages, tools, **kwargs), parse_special=True))
def perform(label, req, expected=None):
body = json.dumps(req).encode()
(args.out / (label + "-request.json")).write_bytes(body + b"\n")
print("start", label, "tokens", expected, flush=True)
chunks, texts, first, finish = [], [], None, None
started = time.perf_counter()
wire = urllib.request.Request(args.url + "/v1/chat/completions", data=body,
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(wire, timeout=1800) as response:
for line in response:
if not line.startswith(b"data: "):
continue
payload = line[6:].strip()
if payload == b"[DONE]":
break
chunk = json.loads(payload)
chunks.append(chunk)
for choice in chunk.get("choices", []):
delta = choice.get("delta", {})
text = (delta.get("content") or "") + (delta.get("reasoning_content") or "")
if text:
first = first if first is not None else time.perf_counter() - started
texts.append(text)
finish = choice.get("finish_reason") or finish
elapsed = time.perf_counter() - started
metrics = get(args.url + "/metrics")
engine = metrics["requests"][0]
usage = next((chunk["usage"] for chunk in reversed(chunks) if "usage" in chunk), {})
row = {"label": label, "expected_prompt_tokens": expected,
"request_sha256": hashlib.sha256(body).hexdigest(),
"client_ttft_s": first, "client_elapsed_s": elapsed, "finish_reason": finish,
"usage": usage, "engine": engine, "text": "".join(texts)}
if expected is not None and engine["prompt_tokens"] != expected:
raise RuntimeError(f"token count mismatch: {expected} vs {engine['prompt_tokens']}")
if not texts:
raise RuntimeError(f"no text received for {label}")
(args.out / (label + "-raw.json")).write_text(json.dumps({"chunks": chunks, "row": row}, indent=2) + "\n")
rows.append(row)
(args.out / "results.json").write_text(json.dumps(rows, indent=2) + "\n")
print("done", label, json.dumps({"ttft_s": first, "elapsed_s": elapsed, "engine": engine}), flush=True)
return row
perform("warmup", request("Reply with exactly the word READY.", 16))
# Each nonce occurs before the filler so previous long prompts cannot be reused.
filler = "\n".join(f"def task_{i:05d}(value: int) -> int: return (value * {(i % 97) + 1} + {i}) % 100003"
for i in range(12000))
ending = ("\n\nWrite a detailed explanation of the code above. Discuss deterministic integer transforms, "
"modulo arithmetic, testing, naming, complexity, and maintainability. Write at least 600 words.")
for target in map(int, args.targets.split(",")):
for run in range(1, args.runs + 1):
prefix = f"Benchmark nonce: series-{target}-trial-{run}.\nReview this synthetic Python module:\n"
lo, hi = 0, len(filler)
while lo < hi:
middle = (lo + hi + 1) // 2
if count(request(prefix + filler[:middle] + ending)) <= target:
lo = middle
else:
hi = middle - 1
req = request(prefix + filler[:lo] + ending)
actual = count(req)
if actual < target - 20 or actual > target:
raise RuntimeError(f"could not construct target {target}: {actual}")
perform(f"tokens-{target}-run-{run}", req, actual)
measured = [row for row in rows if row["label"] != "warmup"]
groups = {}
for target in map(int, args.targets.split(",")):
subset = [r for r in measured if r["label"].startswith(f"tokens-{target}-")]
values = {
"prompt_tokens": [r["engine"]["prompt_tokens"] for r in subset],
"cached_tokens": [r["engine"].get("reused", 0) for r in subset],
"output_tokens": [r["engine"]["engine_generated"] for r in subset],
"client_ttft_s": [r["client_ttft_s"] for r in subset],
"client_elapsed_s": [r["client_elapsed_s"] for r in subset],
"prefill_tok_s": [(r["engine"]["prompt_tokens"] - (r["engine"].get("reused") or 0)) / (r["engine"]["prompt_ms"] / 1000) for r in subset],
"decode_tok_s": [r["engine"]["engine_generated"] / (r["engine"]["decode_ms"] / 1000) for r in subset],
}
groups[str(target)] = {key: {"median": statistics.median(v), "min": min(v), "max": max(v)}
for key, v in values.items()}
(args.out / "summary.json").write_text(json.dumps(groups, indent=2) + "\n")
print("summary", json.dumps(groups), flush=True)
if __name__ == "__main__":
main()
@@ -0,0 +1,50 @@
{
"service": "strata",
"model": "qwen3.8-flash-next-coder",
"loaded": true,
"auto_load": true,
"structured_output": {
"formats": [
"json_object",
"json_schema"
],
"method": "prompt_and_validate",
"constrained_decoding": false,
"stream_buffered": true
},
"engine": "0.1.38",
"started": 1791055531,
"uptime_s": 2,
"cache_max_tokens": 131072,
"context": {
"native": 131072,
"max_positions": 131072
},
"concurrency": {
"serving": 1,
"requested": 1
},
"dialects": [
"/v1/chat/completions",
"/v1/messages"
],
"vision": {
"enabled": false,
"available": false,
"error": null
},
"activity": {
"requests": 0,
"in_flight": 0,
"last_request_at": null
},
"last_timings": null,
"machine": {
"at": 1791055534,
"gpu": null,
"ram": {
"used_gib": 4.9,
"total_gib": 31.2
}
}
}
@@ -0,0 +1,56 @@
[
{
"length": "32k",
"depth": 10,
"prompt_tokens": 25776,
"seconds": 52.6,
"found": true,
"word": "meadow-copper-504",
"answer": "meadow-copper-504"
},
{
"length": "32k",
"depth": 50,
"prompt_tokens": 25776,
"seconds": 50.7,
"found": true,
"word": "falcon-quartz-940",
"answer": "falcon-quartz-940"
},
{
"length": "32k",
"depth": 90,
"prompt_tokens": 25777,
"seconds": 50.8,
"found": true,
"word": "willow-cobalt-696",
"answer": "willow-cobalt-696"
},
{
"length": "128k",
"depth": 10,
"prompt_tokens": 103727,
"seconds": 206.9,
"found": true,
"word": "falcon-saffron-138",
"answer": "falcon-saffron-138"
},
{
"length": "128k",
"depth": 50,
"prompt_tokens": 103725,
"seconds": 205.9,
"found": true,
"word": "quartz-tundra-528",
"answer": "quartz-tundra-528"
},
{
"length": "128k",
"depth": 90,
"prompt_tokens": 103725,
"seconds": 112.5,
"found": true,
"word": "quartz-glacier-192",
"answer": "quartz-glacier-192"
}
]
@@ -0,0 +1,382 @@
[
{
"label": "warmup",
"expected_prompt_tokens": null,
"request_sha256": "b63e57873441a996a529b246a66cf12de70a7c671777f99329354d5c195f788f",
"client_ttft_s": 0.44287488800182473,
"client_elapsed_s": 0.5121355729934294,
"finish_reason": "stop",
"usage": {
"prompt_tokens": 19,
"completion_tokens": 2,
"total_tokens": 21,
"prompt_tokens_details": {
"cached_tokens": 0
}
},
"engine": {
"projection": null,
"time": 1791055534.084382,
"duration_s": 0.5,
"finish": "stop",
"prompt_tokens": 19,
"reused": 0,
"output_tokens": 2,
"prompt_total": 19,
"prompt_read": 19,
"engine_generated": 2,
"prompt_ms": 398.1,
"decode_ms": 108.4,
"decode_tok_s": 18.5,
"hit_rate": 1.0,
"ram_blobs": 0,
"file_blobs": 0,
"file_mb": 0.0,
"drafts_offered": 3,
"drafts_accepted": 3
},
"text": "READY"
},
{
"label": "tokens-4096-run-1",
"expected_prompt_tokens": 4096,
"request_sha256": "5d94c652067354bbe72930d2bdad3886564f08cf2546b32411af02d33ad3ce05",
"client_ttft_s": 13.26403624098748,
"client_elapsed_s": 18.427036346998648,
"finish_reason": "length",
"usage": {
"prompt_tokens": 4096,
"completion_tokens": 256,
"total_tokens": 4352,
"prompt_tokens_details": {
"cached_tokens": 0
}
},
"engine": {
"projection": null,
"time": 1791055535.8394356,
"duration_s": 18.4,
"finish": "length",
"prompt_tokens": 4096,
"reused": 0,
"output_tokens": 256,
"prompt_total": 4096,
"prompt_read": 4096,
"engine_generated": 256,
"prompt_ms": 13216.0,
"decode_ms": 5189.0,
"decode_tok_s": 49.3,
"hit_rate": 1.0,
"ram_blobs": 0,
"file_blobs": 0,
"file_mb": 0.0,
"drafts_offered": 210,
"drafts_accepted": 145
},
"text": "The provided Python module presents a series of deterministic integer transforms, each encapsulated within a uniquely named function. These functions, labeled from `task_00000` to `task_00112` (and potentially beyond), follow a consistent mathematical pattern: they take an integer input, apply a linear transformation of the form `(value * multiplier + offset) % modulus`, and return the result. This structure is a classic example of a linear congruential generator (LCG) component, often used in pseudo-random number generation, hashing, or cryptographic primitives, though here it appears to be a synthetic benchmark or test harness.\n\n### Deterministic Integer Transforms and Modulo Arithmetic\n\nEach function implements a linear congruential step: `f(x) = (a * x + c) % m`, where `a` is the multiplier, `c` is the increment, and `m` is the modulus (100003 in all cases). The modulus 100003 is a prime number, which is significant because it ensures that the multiplicative group modulo 100003 is cyclic, and for certain choices of `a` and `c`, the transformation can be a permutation of the"
},
{
"label": "tokens-4096-run-2",
"expected_prompt_tokens": 4096,
"request_sha256": "8da8a04e70e4d916f6630729082bdfb9d6ebbb47117aad60bc0541bce198a213",
"client_ttft_s": 12.663496508001117,
"client_elapsed_s": 17.377855258993804,
"finish_reason": "length",
"usage": {
"prompt_tokens": 4096,
"completion_tokens": 256,
"total_tokens": 4352,
"prompt_tokens_details": {
"cached_tokens": 0
}
},
"engine": {
"projection": null,
"time": 1791055555.3915784,
"duration_s": 17.4,
"finish": "length",
"prompt_tokens": 4096,
"reused": 0,
"output_tokens": 256,
"prompt_total": 4096,
"prompt_read": 4096,
"engine_generated": 256,
"prompt_ms": 12615.4,
"decode_ms": 4740.3,
"decode_tok_s": 54.0,
"hit_rate": 1.0,
"ram_blobs": 0,
"file_blobs": 0,
"file_mb": 0.0,
"drafts_offered": 208,
"drafts_accepted": 156
},
"text": "The provided Python module consists of a series of functions, each named with a specific pattern (`task_XXXXX`), that perform a deterministic integer transformation. Each function takes a single integer argument `value` and returns an integer result computed using a linear transformation followed by a modulo operation. The general form of each function is:\n\n```python\ndef task_XXXXX(value: int) -> int:\n return (value * A + B) % 100003\n```\n\nwhere `A` and `B` are constants specific to each function. The modulus `100003` is a prime number, which is significant in modular arithmetic because it ensures that the multiplicative group modulo 100003 is cyclic and that every non-zero element has a multiplicative inverse. This property is often exploited in cryptographic algorithms, hash functions, and pseudo-random number generators.\n\n### Deterministic Integer Transforms\n\nEach function implements a linear congruential transformation, a common technique in number theory and computer science. The transformation `value * A + B` is an affine transformation over the integers. When combined with the modulo operation, it becomes a function from the finite field (or ring) of integers modulo 10"
},
{
"label": "tokens-4096-run-3",
"expected_prompt_tokens": 4096,
"request_sha256": "946079edb58e764050805886156dc8f877cc29e1ca8d01c84e9a1e7917d49492",
"client_ttft_s": 12.811999237994314,
"client_elapsed_s": 17.900370211005793,
"finish_reason": "length",
"usage": {
"prompt_tokens": 4096,
"completion_tokens": 256,
"total_tokens": 4352,
"prompt_tokens_details": {
"cached_tokens": 0
}
},
"engine": {
"projection": null,
"time": 1791055573.9388902,
"duration_s": 17.9,
"finish": "length",
"prompt_tokens": 4096,
"reused": 0,
"output_tokens": 256,
"prompt_total": 4096,
"prompt_read": 4096,
"engine_generated": 256,
"prompt_ms": 12763.9,
"decode_ms": 5114.7,
"decode_tok_s": 50.1,
"hit_rate": 1.0,
"ram_blobs": 0,
"file_blobs": 0,
"file_mb": 0.0,
"drafts_offered": 222,
"drafts_accepted": 146
},
"text": "The provided Python module presents a series of deterministic integer transforms, each encapsulated within a uniquely named function. These functions, labeled from `task_00000` to `task_00112` (and potentially beyond), follow a consistent mathematical pattern: they take an integer input, apply a linear transformation, and return the result modulo a large prime number, specifically 100003. This structure serves as a synthetic benchmark for evaluating code generation, pattern recognition, and algorithmic consistency in automated systems.\n\n### Deterministic Integer Transforms and Modulo Arithmetic\n\nAt the core of each function is the expression `(value * multiplier + offset) % 100003`. This is a classic linear congruential generator (LCG) step, often used in pseudo-random number generation or cryptographic hashing, though here it is applied deterministically to a single input. The multiplier and offset vary per function, creating a unique mapping for each task. For instance, `task_00000` uses a multiplier of 1 and an offset of 0, effectively returning `value % 100003`. In contrast, `task_00097` uses a multiplier of 1"
},
{
"label": "tokens-32768-run-1",
"expected_prompt_tokens": 32768,
"request_sha256": "e37cfc2ab9867d91130927440df24a57255a736b8d0d829d07d828e22e3de572",
"client_ttft_s": 62.74767600699852,
"client_elapsed_s": 68.09618598900852,
"finish_reason": "length",
"usage": {
"prompt_tokens": 32768,
"completion_tokens": 256,
"total_tokens": 33024,
"prompt_tokens_details": {
"cached_tokens": 0
}
},
"engine": {
"projection": null,
"time": 1791055594.1634562,
"duration_s": 68.0,
"finish": "length",
"prompt_tokens": 32768,
"reused": 0,
"output_tokens": 256,
"prompt_total": 32768,
"prompt_read": 32768,
"engine_generated": 256,
"prompt_ms": 62608.4,
"decode_ms": 5375.3,
"decode_tok_s": 47.6,
"hit_rate": 1.0,
"ram_blobs": 0,
"file_blobs": 0,
"file_mb": 0.0,
"drafts_offered": 230,
"drafts_accepted": 152
},
"text": "This Python module presents a highly repetitive, synthetic collection of functions that serve as a benchmark for deterministic integer transforms. The code consists of a series of functions named `task_00000` through `task_00888` (and potentially beyond), each performing a specific linear transformation on an input integer `value` and returning the result modulo 100003.\n\n### Deterministic Integer Transforms and Modulo Arithmetic\n\nAt the core of each function is a linear congruential generator (LCG) style operation: `(value * multiplier + addend) % 100003`. The modulus, 100003, is a prime number. This choice of modulus is significant because it ensures that the multiplicative group of integers modulo 100003 is cyclic, which is a desirable property for cryptographic or pseudo-random number generation contexts, although here it is used for deterministic hashing or transformation.\n\nThe structure of the functions reveals a pattern in the `multiplier` and `addend` parameters. For the first 97 functions (`task_00000` to `task_00096`), the multiplier increases linearly from 1 to"
},
{
"label": "tokens-32768-run-2",
"expected_prompt_tokens": 32768,
"request_sha256": "ed2dfaa11aecad9f4563f33bb5f5d4b8704486508700b8fa572722cc1225ee26",
"client_ttft_s": 62.81415034100064,
"client_elapsed_s": 68.14694995200261,
"finish_reason": "length",
"usage": {
"prompt_tokens": 32768,
"completion_tokens": 256,
"total_tokens": 33024,
"prompt_tokens_details": {
"cached_tokens": 0
}
},
"engine": {
"projection": null,
"time": 1791055664.4150822,
"duration_s": 68.0,
"finish": "length",
"prompt_tokens": 32768,
"reused": 0,
"output_tokens": 256,
"prompt_total": 32768,
"prompt_read": 32768,
"engine_generated": 256,
"prompt_ms": 62675.9,
"decode_ms": 5359.3,
"decode_tok_s": 47.8,
"hit_rate": 1.0,
"ram_blobs": 0,
"file_blobs": 0,
"file_mb": 0.0,
"drafts_offered": 222,
"drafts_accepted": 147
},
"text": "This Python module presents a highly repetitive, synthetic collection of functions that perform deterministic integer transforms. Each function follows a strict pattern: it accepts an integer `value`, applies a linear transformation of the form `(value * multiplier + offset) % modulus`, and returns the result. The modulus is consistently set to `100003`, which is a prime number. This choice of modulus is significant because it ensures that the multiplicative group of integers modulo 100003 is cyclic, and every non-zero multiplier has a unique modular inverse. This property is often desirable in cryptographic or hashing contexts, though here it appears to be used for simple arithmetic obfuscation or benchmarking.\n\n### Deterministic Integer Transforms and Modulo Arithmetic\n\nThe core operation in each function is a linear congruential generator (LCG) step, commonly used in pseudo-random number generation. The formula $f(x) = (ax + c) \\pmod m$ defines an affine transformation over the finite field $\\mathbb{Z}_m$. In this module, $m = 100003$. The multipliers ($a$) and offsets ($c$) vary per function. For example, `task_00000`"
},
{
"label": "tokens-32768-run-3",
"expected_prompt_tokens": 32768,
"request_sha256": "2a3c7342622e80c3cd8b37e062f0a2f64640c119ece8cccbf168639041eac079",
"client_ttft_s": 62.844907227001386,
"client_elapsed_s": 68.09568050300004,
"finish_reason": "length",
"usage": {
"prompt_tokens": 32768,
"completion_tokens": 256,
"total_tokens": 33024,
"prompt_tokens_details": {
"cached_tokens": 0
}
},
"engine": {
"projection": null,
"time": 1791055734.689819,
"duration_s": 68.0,
"finish": "length",
"prompt_tokens": 32768,
"reused": 0,
"output_tokens": 256,
"prompt_total": 32768,
"prompt_read": 32768,
"engine_generated": 256,
"prompt_ms": 62706.6,
"decode_ms": 5277.5,
"decode_tok_s": 48.5,
"hit_rate": 1.0,
"ram_blobs": 0,
"file_blobs": 0,
"file_mb": 0.0,
"drafts_offered": 234,
"drafts_accepted": 153
},
"text": "This Python module presents a highly repetitive, synthetic collection of functions that perform deterministic integer transforms. Each function follows a strict pattern: it accepts an integer `value`, applies a linear transformation of the form `(value * multiplier + offset) % modulus`, and returns the result. The modulus is consistently set to `100003`, which is a prime number. This choice of modulus is significant because it ensures that the multiplicative group of integers modulo 100003 is cyclic, meaning that for any non-zero multiplier, the transformation is bijective (a permutation) over the set of integers modulo 100003. This property is often desirable in cryptographic contexts or pseudo-random number generation, although here it appears to be used for benchmarking or synthetic data generation.\n\n### Deterministic Integer Transforms and Modulo Arithmetic\n\nThe core operation in each function is a linear congruential generator (LCG) step, defined by the formula $f(x) = (ax + c) \\pmod m$. In this module, $m = 100003$. The multiplier $a$ and the increment $c$ vary per function. For example, `task_00000` uses $a"
},
{
"label": "tokens-128000-run-1",
"expected_prompt_tokens": 128000,
"request_sha256": "3235aac3f934cf1d889c25973ca172b355509dc2522fdfb463fbefe979a9075d",
"client_ttft_s": 248.26734286299325,
"client_elapsed_s": 253.83500957599608,
"finish_reason": "length",
"usage": {
"prompt_tokens": 128000,
"completion_tokens": 256,
"total_tokens": 128256,
"prompt_tokens_details": {
"cached_tokens": 0
}
},
"engine": {
"projection": null,
"time": 1791055809.118869,
"duration_s": 253.5,
"finish": "length",
"prompt_tokens": 128000,
"reused": 0,
"output_tokens": 256,
"prompt_total": 128000,
"prompt_read": 128000,
"engine_generated": 256,
"prompt_ms": 247841.6,
"decode_ms": 5596.2,
"decode_tok_s": 45.7,
"hit_rate": 1.0,
"ram_blobs": 0,
"file_blobs": 0,
"file_mb": 0.0,
"drafts_offered": 232,
"drafts_accepted": 152
},
"text": "This Python module represents a synthetic benchmark designed to test the performance and correctness of integer arithmetic operations, specifically focusing on linear transforms and modular arithmetic. The code consists of a series of functions, each named `task_XXXXX`, where `XXXXX` is a zero-padded integer index. Each function accepts a single integer argument `value` and returns an integer result.\n\n### 1. Deterministic Integer Transforms\n\nThe core logic of every function in this module is identical in structure:\n```python\nreturn (value * A + B) % M\n```\nWhere:\n- `value` is the input integer.\n- `A` is a multiplier (coefficient).\n- `B` is an additive constant.\n- `M` is the modulus, which is consistently `100003` throughout the entire module.\n\nThis represents a **linear congruential transform**. In computer science, such transforms are fundamental in pseudorandom number generation (LCG), hashing functions, and cryptographic primitives. The specific form `(value * A + B) % M` ensures that the output is always within the range `[0, M-1]`, regardless of how large the input `value` is.\n\n### 2"
},
{
"label": "tokens-128000-run-2",
"expected_prompt_tokens": 128000,
"request_sha256": "5f4b8bc9f0afc7765320abd89960c0938e0d7cf5974e962fdbd0613fef31c8d4",
"client_ttft_s": 248.0881588330085,
"client_elapsed_s": 253.0268927290017,
"finish_reason": "length",
"usage": {
"prompt_tokens": 128000,
"completion_tokens": 256,
"total_tokens": 128256,
"prompt_tokens_details": {
"cached_tokens": 0
}
},
"engine": {
"projection": null,
"time": 1791056068.9450965,
"duration_s": 252.7,
"finish": "length",
"prompt_tokens": 128000,
"reused": 0,
"output_tokens": 256,
"prompt_total": 128000,
"prompt_read": 128000,
"engine_generated": 256,
"prompt_ms": 247669.4,
"decode_ms": 4967.1,
"decode_tok_s": 51.5,
"hit_rate": 1.0,
"ram_blobs": 0,
"file_blobs": 0,
"file_mb": 0.0,
"drafts_offered": 205,
"drafts_accepted": 163
},
"text": "This Python module represents a synthetic benchmark designed to test the performance and correctness of integer arithmetic operations, specifically focusing on linear transforms and modular arithmetic. The code consists of a series of functions, each named `task_XXXXX`, where `XXXXX` is a zero-padded integer index. Each function accepts a single integer argument `value` and returns an integer result.\n\n### 1. Deterministic Integer Transforms\n\nThe core logic of each function is a linear transformation of the form:\n$$ f(x) = (a \\cdot x + b) \\pmod m $$\nwhere:\n- $x$ is the input `value`.\n- $a$ is the multiplier (coefficient).\n- $b$ is the additive constant.\n- $m$ is the modulus, which is consistently set to `100003` across all functions.\n\nThe multiplier $a$ and the constant $b$ vary deterministically based on the function's index. For example:\n- `task_00000`: $a=1, b=0$\n- `task_00001`: $a=2, b=1$\n- `task_00002`:"
},
{
"label": "tokens-128000-run-3",
"expected_prompt_tokens": 128000,
"request_sha256": "5c3fb71db9f9f44765f28389d1032f2c8b6687d1bf5ca6f33aeb924072cfa6e4",
"client_ttft_s": 248.0611828550027,
"client_elapsed_s": 253.7529949669988,
"finish_reason": "length",
"usage": {
"prompt_tokens": 128000,
"completion_tokens": 256,
"total_tokens": 128256,
"prompt_tokens_details": {
"cached_tokens": 0
}
},
"engine": {
"projection": null,
"time": 1791056328.0391443,
"duration_s": 253.4,
"finish": "length",
"prompt_tokens": 128000,
"reused": 0,
"output_tokens": 256,
"prompt_total": 128000,
"prompt_read": 128000,
"engine_generated": 256,
"prompt_ms": 247650.3,
"decode_ms": 5720.0,
"decode_tok_s": 44.8,
"hit_rate": 1.0,
"ram_blobs": 0,
"file_blobs": 0,
"file_mb": 0.0,
"drafts_offered": 235,
"drafts_accepted": 149
},
"text": "This Python module represents a synthetic benchmark designed to test the performance and correctness of integer arithmetic operations, specifically focusing on linear transformations combined with modular arithmetic. The code consists of a series of functions, each named `task_XXXXX`, where `XXXXX` is a zero-padded integer index. Each function accepts a single integer argument `value` and returns a new integer calculated using the formula:\n\n$$ f(value) = (value \\times A + B) \\pmod{M} $$\n\nwhere $A$ is a multiplier, $B$ is an additive constant, and $M$ is the modulus, which is consistently set to `100003` throughout the module.\n\n### Deterministic Integer Transforms and Modulo Arithmetic\n\nThe core logic of each function is a deterministic linear congruential transformation. In computer science, such transformations are fundamental to pseudorandom number generators (PRNGs), hash functions, and cryptographic primitives. The specific form $ (value \\times A + B) \\pmod{M} $ ensures that the output is always within the range $[0, M-1]$.\n\nThe modulus $M = 100003$ is a prime number. This choice is significant because"
}
]
@@ -0,0 +1,45 @@
{
"exe": "/work/build-906/strata",
"args": [
"--pack",
"/m/pack-coder",
"--native",
"/m/coder/Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00001-of-00002.gguf",
"--ple-gguf",
"/m/coder/Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-00002-of-00002.gguf",
"--expert-profile",
"/opt/strata/data/expert-profile-coder.bin",
"--expert-cache",
"auto",
"--prefill",
"4096",
"--spec",
"4",
"--spec-min-p",
"0.5",
"--mtp",
"/m/mtp/rt",
"--max-context",
"131072",
"--kv",
"int8",
"--vram-reserve-mib",
"600",
"--kv-resident",
"32768",
"--pcie-frac",
"0"
],
"cwd": "/opt/strata",
"tokenizer": "/m/pack-coder/tokenizer",
"model_name": "qwen3.8-flash-next-coder",
"log": "/work/strata-coder.log",
"lib_dirs": [],
"port": 8080,
"host": "0.0.0.0",
"gpu": [
0,
1
],
"layer_split": "27"
}
@@ -0,0 +1,113 @@
{
"4096": {
"prompt_tokens": {
"median": 4096,
"min": 4096,
"max": 4096
},
"cached_tokens": {
"median": 0,
"min": 0,
"max": 0
},
"output_tokens": {
"median": 256,
"min": 256,
"max": 256
},
"client_ttft_s": {
"median": 12.811999237994314,
"min": 12.663496508001117,
"max": 13.26403624098748
},
"client_elapsed_s": {
"median": 17.900370211005793,
"min": 17.377855258993804,
"max": 18.427036346998648
},
"prefill_tok_s": {
"median": 320.90505253096626,
"min": 309.9273607748184,
"max": 324.68253087496237
},
"decode_tok_s": {
"median": 50.05181144544157,
"min": 49.3351320100212,
"max": 54.00502077927557
}
},
"32768": {
"prompt_tokens": {
"median": 32768,
"min": 32768,
"max": 32768
},
"cached_tokens": {
"median": 0,
"min": 0,
"max": 0
},
"output_tokens": {
"median": 256,
"min": 256,
"max": 256
},
"client_ttft_s": {
"median": 62.81415034100064,
"min": 62.74767600699852,
"max": 62.844907227001386
},
"client_elapsed_s": {
"median": 68.09618598900852,
"min": 68.09568050300004,
"max": 68.14694995200261
},
"prefill_tok_s": {
"median": 522.8165850031671,
"min": 522.5606236026192,
"max": 523.3802492956216
},
"decode_tok_s": {
"median": 47.767432313921596,
"min": 47.625248823321485,
"max": 48.50781620085268
}
},
"128000": {
"prompt_tokens": {
"median": 128000,
"min": 128000,
"max": 128000
},
"cached_tokens": {
"median": 0,
"min": 0,
"max": 0
},
"output_tokens": {
"median": 256,
"min": 256,
"max": 256
},
"client_ttft_s": {
"median": 248.0881588330085,
"min": 248.0611828550027,
"max": 248.26734286299325
},
"client_elapsed_s": {
"median": 253.7529949669988,
"min": 253.0268927290017,
"max": 253.83500957599608
},
"prefill_tok_s": {
"median": 516.8179839737974,
"min": 516.4588995551998,
"max": 516.857843499483
},
"decode_tok_s": {
"median": 45.745327186305,
"min": 44.75524475524476,
"max": 51.5391274586781
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,104 @@
# V100 (sm_70): a tensor-core QSA prompt attention (2026-10-03)
On sm_70 the prompt path ran the QSA attention on the decode kernel, one query at a time with FP32 FMAs. `prompt_attn_v70_kernel`
(`src/kernels/cuda/qsa_prompt_attn.cu`) does the two matrix products on Volta's tensor cores (`mma.sync.m8n8k4`).
`STRATA_PROMPT_ATTN_OLD=1` is the old path, so every number below is the same binary with and without that switch.
## Rig
- Tesla V100-PCIE-32GB (sm_70, PCIe gen3 x16), driver 550.120, one card used; a second V100 and a Quadro RTX 4000 (sm_75) are in the
PC and hidden with `CUDA_VISIBLE_DEVICES`. Intel Core i9-7960X (AVX-512), 125 GB RAM, Linux 6.8, CUDA 12.8, GCC 13.
- Engine: `origin/main` at `99f3dbd` (0.1.35 + 83 commits) with this change, built with
`-DCMAKE_CUDA_ARCHITECTURES=70 -DSTRATA_EXPERIMENTAL_SM60=ON`.
- Model: Unsloth `Qwen3.8-Flash-Next-UD-IQ4_XS` (3 shards), packed with `tools/iq_pack.py --compat-bf16`, MTP head from
`tools/mtp_fetch.py`. Not one of setup's models (see the limits). `--max-context 204800`, `--kv int8`, `--spec 2`.
## Prompt speed
One server start per configuration (cold), a 2K warm-up request, then three prompts of random words, each answered greedily
(temperature 0, 48 tokens). The numbers are the server's own line `strata serve: prompt N tokens = 0 reused + N read in T ms`. One run per
cell; repeated starts of the same configuration gave the same seconds.
| Prompt tokens | old path | new kernel | gain | read time, old -> new |
| ---: | ---: | ---: | ---: | ---: |
| 7,194 | 1,010 tok/s | 1,164 tok/s | +15% | 7.1 s -> 6.2 s |
| 28,650 | 1,063 tok/s | 1,251 tok/s | +18% | 26.9 s -> 22.9 s |
| 114,338 | 973 tok/s | 1,123 tok/s | +15% | 117.5 s -> 101.8 s |
Decode is unchanged within the noise (38-51 tok/s, 48 tokens per request): it does not use this kernel.
## Where the time went (nsys, one V100, 28,650-token prompt, GPU kernel time of the whole capture: prefill plus 128-193 decode tokens)
`strata-1gpu-32k-*.nsys-rep`; the "before" capture is 0.1.35 (`d9ab843`), the "after" one is the same base with this change and the BF16 change
of #540 / the closed #593 (BF16 GEMMs through FP16; that one only removes `magma_sgemmEx`, which is not in this table).
| | before | after |
| --- | ---: | ---: |
| QSA attention on the decode kernel (`attn_chunk_kernel<1>`) | 5.78 s (19.2%) | 0.18 s (decode steps only) |
| `prompt_attn_v70_kernel` | - | 2.16 s (9.0%; 12% of the prompt part) |
## Accuracy
`qsa_prompt_attn_parity` (synthetic, no model; build with `-DSTRATA_PARITY_PROMPT_ATTN=ON`), V100, 32K context, 2,048 queries per chunk, output scale 3.6:
| KV | error vs FP64, old kernel | error vs FP64, new kernel | time per chunk, old -> new |
| --- | ---: | ---: | ---: |
| int8 | 2.4e-6 | 5.1e-6 | 38.1 -> 13.4 ms (2.8x) |
| fp16 | 1.9e-6 | 5.3e-6 | 37.3 -> 28.3 ms (1.3x) |
The 1,500- and 2,100-token contexts also pass (int8: 3.2x and 2.2x). The test's Q4_0 cases are skipped below sm_80, where the dispatcher keeps the
old kernel (upstream's mode 4 is sm_80+ only).
## Output checks
- **Needle recall** (`tools/needle_bench.py --lengths 8k,32k,128k --depths 10,30,50,70,90`, greedy, thinking off, a fresh server per
configuration; prompts of 7.9K, 32.0K and 122.7K tokens): **15 of 15 found with the old path, 15 of 15 with the new kernel.** The read times of
the later depths are shorter because the server reuses the checkpoint of the text before the needle.
- **Greedy output** (48 tokens, the three prompts above): identical for the 28,650- and 114,338-token prompts. For the 7,194-token prompt the
answer starts the same and **differs later**: the kernel sums in another order and a greedy decode can follow a near tie elsewhere. A recall test
with a code word does not tell small shifts of the output distribution apart, and a teacher-forced top-1 comparison was not run.
## Distribution check (teacher-forced, against the old path and against controls)
The method of `docs/UNSLOTH_Q4.md`: `STRATA_LOGPOS=<file> STRATA_LOGPOS_TOPK=256` on a serve engine (`--short-read 640 --adapt-every 100000`, greedy,
`--max-context 204800`). Each prompt is a chat: a long first message (8,543 / 32,906 / 99,040 tokens of this repository's docs and code, read by the
batched prompt path, i.e. by the kernel under test), a short reply, and a last message of ~600 tokens of other repository text that goes through the verify
windows, where every token is scored: 617 positions per prompt. KL is old || other over the old run's top 256 plus a bucket for the rest.
| comparison | KL mean (8.5K / 33K / 99K) | argmax same | top-10 overlap |
| --- | --- | --- | --- |
| old path vs old path (a second run) | 0 / 0 / 0 | 100% | 100% |
| new kernel vs new kernel (a second run) | 0 / 0 / 0 | 100% | 100% |
| **old path vs new kernel** | 0.028 / 0.040 / 0.116 | 97.7 / 93.2 / 86.4% | 93.3 / 91.9 / 88.4% |
| control A: old path, BF16 GEMMs without the FP16 detour (`STRATA_BF16_VIA_F16=0`) | 0.026 / 0.051 / 0.090 | 97.2 / 91.4 / 91.2% | 92.9 / 91.4 / 88.5% |
| control B: old path, `--prefill 2048` instead of auto (8192) | 0.023 / 0.035 / 0.038 | 97.9 / 94.8 / 95.6% | 92.9 / 92.2 / 89.7% |
Median KL old vs new: 0.0007 / 0.0088 / 0.022; p99: 0.35 / 0.39 / 1.12 (heavy-tailed). The perplexity of the true tokens moves a lot under every
change (old 365 / 127 / 24; new 346 / 192 / 12; control A 395 / 161 / 18), so it says nothing about quality here.
Reading: the model amplifies small numeric differences, and both controls, which change nothing but the order of the rounding, move the distribution as
much as the kernel does. At 99K the kernel is somewhat above both controls; this is one document and 617 positions, so a real effect there is neither
confirmed nor excluded.
**The kernel on the model's own data.** A temporary check (not in this PR) ran the decode kernel beside the new one on the same inputs, for every 8th batch of
32 queries, in all 12 QSA layers, on the three prompts above (positions up to 98K, ~5 million (query, head) rows of 256): ||new - old|| / ||old|| per row is
4.4e-7 on average and 4.8e-6 in the worst row; the largest absolute difference is 4e-5 against values up to 31. No trend over the layers or the context
length. That is FP32 rounding level, so the differences above come from the model's sensitivity, not from the kernel's arithmetic.
## Limits
- sm_70 only (`__CUDA_ARCH__` 700-749). Q4_0 KV (`--kv q4_0`) and the QSA block scores (`block_scores_kernel`, the warp kernel below sm_80) still use their
old kernels on Volta.
- One request, one card. The Unsloth IQ4_XS pack is not a setup model; the GSQ-RCO quants were not run on this rig.
- The profile above is one capture of one prompt. The distribution check is one document per length; the 99K row is the least certain.
## Reproduce
```sh
cmake -S . -B build -DSTRATA_ENABLE_CUDA=ON -DSTRATA_BUILD_TESTS=OFF -DSTRATA_PARITY_PROMPT_ATTN=ON \
-DCMAKE_CUDA_ARCHITECTURES=70 -DSTRATA_EXPERIMENTAL_SM60=ON
cmake --build build --target strata qsa_prompt_attn_parity -j
CUDA_VISIBLE_DEVICES=0 ./build/qsa_prompt_attn_parity 32768 2048 5 # the accuracy table
STRATA_PROMPT_ATTN_OLD=1 <start script> # the old path; without the variable: the new kernel
python tools/needle_bench.py --url http://127.0.0.1:8081 --lengths 8k,32k,128k --depths 10,30,50,70,90
```
+12 -1
View File
@@ -11,7 +11,7 @@ endif()
# report ran it (#311), the maintainers have not.
set(_strata_hip_validated gfx1100 gfx1201)
set(_strata_hip_community gfx1101 gfx1200)
set(_strata_hip_unvalidated gfx1102 gfx1030)
set(_strata_hip_unvalidated gfx1012 gfx1102 gfx1030 gfx1031)
# CMake hands HIP a ';' list, but a -DCMAKE_HIP_ARCHITECTURES typed by hand (or ROCm's own Windows tooling) may use
# spaces, which foreach(IN LISTS) would otherwise treat as one element.
string(REPLACE " " ";" _strata_hip_norm "${CMAKE_HIP_ARCHITECTURES}")
@@ -44,6 +44,13 @@ string(REPLACE ";" "," STRATA_HIP_ARCHS "${STRATA_HIP_ARCH_LIST}")
enable_language(HIP)
find_package(hip CONFIG REQUIRED)
find_package(hipblas CONFIG REQUIRED)
# Older distro hipBLAS has no workspace API. The compatibility shim uses
# rocBLAS directly for that version; newer hipBLAS keeps its existing path.
set(STRATA_HIP_BLAS_TARGETS roc::hipblas)
if(hipblas_VERSION VERSION_LESS "1.0")
find_package(rocblas CONFIG REQUIRED)
list(APPEND STRATA_HIP_BLAS_TARGETS roc::rocblas)
endif()
find_package(hipblaslt CONFIG QUIET)
if(NOT TARGET hip::host)
@@ -67,6 +74,10 @@ add_library(strata_hip_runtime INTERFACE)
target_include_directories(strata_hip_runtime BEFORE INTERFACE
"${STRATA_HIP_COMPAT_INCLUDE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include")
target_compile_definitions(strata_hip_runtime INTERFACE STRATA_USE_HIP=1 "STRATA_HIP_ARCHS=\"${STRATA_HIP_ARCHS}\"")
option(STRATA_GFX1012_PORTABLE_DOT "Use the portable signed-byte dot control on gfx1012" OFF)
if(STRATA_GFX1012_PORTABLE_DOT)
target_compile_definitions(strata_hip_runtime INTERFACE STRATA_GFX1012_PORTABLE_DOT=1)
endif()
target_link_libraries(strata_hip_runtime INTERFACE hip::host)
# The shim renames the CUDA runtime to HIP, force-included into every host and device source. On Windows the host
# compiler is ROCm's clang++ too (tools/hip/build_windows.bat: CMake refuses to mix cl.exe with Clang HIP), which takes
+2 -1
View File
@@ -44,7 +44,8 @@ Requirements (details: [INSTALL.md](INSTALL.md#what-you-need)):
- **GPU:** NVIDIA RTX 20, 30, 40 or 50 series, or AMD Radeon RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT,
RX 9070 / 9070 XT, Radeon AI PRO R9700, RX 6800 / 6900 series; 12 GB of VRAM or more (an NVIDIA card with 8 GB runs,
slowly). GTX 10 series and older, and integrated GPUs, are not supported.
slowly). GTX 10 series and older, and integrated GPUs, are not supported; Pascal / Volta cards (P40, V100) and some
older AMD cards have experimental paths the user opts into ([OLDER_GPUS.md](OLDER_GPUS.md)).
- **Driver:** NVIDIA 580 or newer. AMD on Linux: the kernel's amdgpu driver; on Windows: a current AMD Adrenalin
driver. If the driver is missing or too old, tell the user to update it (NVIDIA App / nvidia.com/drivers, or AMD
Software) and restart; do not install drivers yourself unless they ask.
+67 -3
View File
@@ -5,7 +5,8 @@ covers the build on Linux (on Windows a ready-made engine, see [Windows](#window
RX 9070 / 9070 XT / Radeon AI PRO R9700 (RDNA4, gfx1201; see [RDNA4](#rdna4-gfx1201)). The RX 7800 XT / 7700 XT
(gfx1101) and the RX 9060 XT (gfx1200) were validated by their owners (see [Community-validated
cards](#community-validated-cards)); the RX 6800 / 6900 series (RDNA2, gfx1030) builds and runs too, reported by a community machine and not yet validated by the maintainers (see [RDNA2](#rdna2-gfx1030)). Setup chooses it by itself on a PC with no NVIDIA card Strata can use (`--backend hip` on a PC with both); the
install steps for users are in [INSTALL.md](INSTALL.md#amd-cards). Other AMD architectures, wave64, and mixed
install steps for users are in [INSTALL.md](INSTALL.md#amd-cards). gfx906 (Instinct MI50 / MI60, Radeon VII; wave64) has a separate
opt-in build, see [gfx906](#gfx906-instinct-mi50--mi60-radeon-vii-wave64-built-from-source). Other AMD architectures and mixed
AMD/NVIDIA execution in one run are not supported.
The backend maps the CUDA-shaped runtime and BLAS calls to HIP/hipBLAS, uses
@@ -347,8 +348,71 @@ run it; the report below is from a community machine: an RX 6900 XT 16 GB (gfx10
[AMD_HIP_PERFORMANCE.md](AMD_HIP_PERFORMANCE.md) cost 8.6 and 13.6 tok/s here (30 with the defaults): keep the
defaults on a 16 GB card.
- **hipBLASLt:** ROCm's hipBLASLt ships no gfx1030 kernels, so there is no table and the plain hipBLAS path runs.
- **Not validated:** gfx1031 / gfx1032 (the same `dp4a` path, no hardware report), setup's own build path and the
`gfx103X-all` wheels on gfx1030, images, answer-quality benchmarks.
- **gfx1031** (RX 6700 XT, #524): setup knows it (the `gfx103X-all` wheels, unvalidated); its reporter runs it daily
on one card.
- **Not validated:** gfx1032 (the same `dp4a` path, no hardware report), setup's own build path and the
`gfx103X-all` wheels on gfx1030, images, answer-quality benchmarks. RDNA1 (gfx1012, RX 5500 XT) builds by hand:
[OLDER_GPUS.md](OLDER_GPUS.md#amd-building-gfx906-and-gfx1012).
## gfx906 (Instinct MI50 / MI60, Radeon VII): wave64, built from source
gfx906 is wave64 and has no WMMA and no packed byte arithmetic, so the wave32 backend above refuses it. A separate opt-in build compiles the CUDA sources as HIP through a small compat layer
(`include/strata/platform/hip_compat/`), with a CUDA warp mapped to a logical half of the 64-lane wavefront
(32-wide shuffles, a ballot of its own half). The hot kernels have wave64 layouts of their own (below). Setup does
not build it yet: build by hand, and run `serve/server.py` with a config as on any other card.
**ROCm.** AMD's current ROCm releases no longer ship gfx906 libraries. The build and the measurements below used
HIP 7.14 from the community image [`mixa3607/rocm-gfx906:7.14-complete`](https://hub.docker.com/r/mixa3607/rocm-gfx906)
(rocBLAS/hipBLAS with gfx906 kernels), on the kernel's amdgpu driver (Ubuntu 24.04, kernel 6.8). hipBLASLt is not
used.
```sh
# inside the image, with this checkout at /src and llama.cpp at the pinned commit in third_party/llama.cpp
apt-get update && apt-get install -y cmake ninja-build git python3 build-essential
cmake -S . -B build-906 -G Ninja -DSTRATA_HIP_GFX906=ON -DCMAKE_HIP_ARCHITECTURES=gfx906 \
-DSTRATA_GGML_DIR=/src/third_party/llama.cpp \
-DCMAKE_C_COMPILER=/opt/rocm/llvm/bin/clang -DCMAKE_CXX_COMPILER=/opt/rocm/llvm/bin/clang++
ninja -C build-906 strata
```
`STRATA_HIP_GFX906` turns on the CUDA targets and refuses `STRATA_ENABLE_HIP` (one HIP build at a time). Run the
container with `--device=/dev/kfd --device=/dev/dri --group-add video --ipc=host --ulimit memlock=-1`; on some boards
`HSA_OVERRIDE_GFX_VERSION=9.0.6` is needed for the runtime to accept the card.
**What differs from the CUDA build** (all under `STRATA_HIP_GFX906`; each A/B switch restores the CUDA layout):
| | gfx906 | switch |
|---|---|---|
| grouped native experts | mode 7: signs as `dp4a(g ^ m, u) - dp4a(m, u)` (no byte SIMD), grids and activations in LDS, one weight load per group; the IQ formats only (Unsloth's K-quant / Q5_1 / Q8_0 experts take the CUDA layout) | `STRATA_EXP_MODE=2` (previous AMD layout) |
| MMVQ | one wavefront per row, 64-lane butterfly, no LDS | `STRATA_MMVQ_WAVE=0` |
| router top-10 | one wavefront, register argmax | - |
| verify-window routing (256-expert router) | the window's tokens in one multi-column BF16 projection + one top-k, ~3 ms of a ~55 ms window | `STRATA_ROUTE_PER_TOKEN=1` |
| hyper-connection read | norm loads in flight, 8 lanes per row for `up` | `STRATA_GR_FAST=0` |
| `gr_down_multi`, opt-in | split along K (8 rows x 5 slices of 2048), ~3% per window; sums in another order than the single-token read, so off by default | `STRATA_GR_SPLIT=1` |
| IQ4 table lookup | llama.cpp's `v_perm_b32` sequence (HIP's `__byte_perm` is a scratch array) | - |
| QSA prompt attention | the FP32 kernel (no tensor cores / WMMA) | - |
Every switch above was checked bitwise against the layout it replaces: the parity tests on synthetic data,
`native_expert_bench` on real GGUF rows (one mode against another), and the greedy text of a fixed request.
**Measured** on 2x Instinct MI50 16 GB (85 W power limit each, PCIe 3.0 x16 both, peer access between them),
Xeon E5-2666 v3 (10 cores, AVX2), 32 GB DDR4, SATA SSD; Coder IQ1_M (`--native` pack), 131,072-token context,
`--kv int8 --kv-resident 32768`, `--layer-split 27`, `--prefill 4096`, MTP `--spec 4 --spec-min-p 0.5`,
`--pcie-frac 0`, `STRATA_ARENA_MMAP=1`. Measured on the port this build was cut from (builds on the 0.1.30 and 0.1.33 bases, the same
kernels, plus the layer-split weight trim and the mapped arena, which are separate pull requests):
- all 12,288 experts held in VRAM across the two cards;
- a 17,043-token agent prompt (Claude Code's first request, tools included) read in 43.5 s (392 tok/s), decode
on it 57.7-59.3 tok/s;
- 25 GB of the 32 GB RAM available while serving;
- six repeats of that request with a 6,000-token output cap and a 900-second two-client load test run six times
(407 requests, 202,940 tokens): no stalls, no errors, no GPU faults.
For comparison on the same machine: llama.cpp (3cf0325, ROCm) on the same Coder IQ1_M measured 26.9 tok/s `tg128`.
**Not done:** setup.py detection and an automatic build, Windows, images (`--vision`), MI60 and Radeon VII (the
same gfx906 ISA; not run), a single-card run, the tensor-split experiment (the halves of every layer on two cards;
it works but is not part of this build).
## Tuning table
+3
View File
@@ -15,6 +15,9 @@ and their limits. Report what you actually measured and label estimates separate
- [2026-09-30: RTX 5090, Core Ultra 9 285K, 64 GB RAM](../bench/results/2026-09-30-community-rtx-5090/README.md):
Strata 0.1.29, original Flash-Next IQ2_XS, 131,072-token context; three runs
each at 4,096, 32,768, and 128,000 prompt tokens, plus six recall checks.
- [2026-10-03: 2x AMD Instinct MI50 16 GB (gfx906), Xeon E5-2666 v3, 32 GB RAM](../bench/results/2026-10-03-community-2x-mi50/README.md):
the gfx906 build (#638) with #639 and #640, Coder IQ1_M, 131,072-token context, layer split across both cards;
three runs each at 4,096, 32,768, and 128,000 prompt tokens, plus six recall checks.
## What to record
+71
View File
@@ -0,0 +1,71 @@
# NVIDIA Tesla V100 / Titan V (Volta, sm_70): the community build
Strata's ready-made engine and the support matrix start at compute capability 7.5 (RTX 20). A V100 (7.0) runs the same
engine compiled for it, through the experimental build that issue #236 added. It is **community-tested, not part of the
supported cards**: no ready-made engine is published for it and the numbers below come from one machine.
## Build
CUDA 13 dropped Volta, so the build needs a **CUDA 12.x** toolkit (12.8 was used) and a host GCC that toolkit accepts.
```sh
cmake -S . -B build -DSTRATA_ENABLE_CUDA=ON -DSTRATA_BUILD_TESTS=OFF \
-DCMAKE_CUDA_ARCHITECTURES=70 -DSTRATA_EXPERIMENTAL_SM60=ON
cmake --build build --target strata -j
```
Setup does the same by itself for a model on a V100 (the experimental CUDA 12 engine, in `engine-cuda12/`: ready-made
on Windows, compiled with a CUDA 12.x toolkit on Linux; [OLDER_GPUS.md](OLDER_GPUS.md)). For a PC with a V100 and a newer card, a build for both architectures (`-DCMAKE_CUDA_ARCHITECTURES="70;86"`) is the
natural choice (a community report in issue #509 ran an RTX 3080 beside a V100 that way; it was not repeated here). On the
measuring PC a Quadro RTX 4000 (sm_75) sits beside the V100s and was hidden with `CUDA_VISIBLE_DEVICES` because the sm_70-only
build has no code for it.
## What runs on Volta
The flag only lowers the floor (CMake and the runtime device check) and replaces two intrinsics Volta lacks. It does not
select "old" kernels everywhere: which kernel runs is decided per architecture when the engine is built.
| Part of the prompt path | On sm_70 |
| --- | --- |
| MoE experts (ggml MMQ) | `dp4a` kernels (Volta has no int8 tensor cores) |
| Dense projections (dequantized weights) | FP16 tensor-core GEMMs (cuBLAS / CUTLASS `s884`) |
| BF16 projections (hyper-connection, router, indexer, ...) | converted to FP16 and run on the FP16 tensor cores (#655, #540; `STRATA_BF16_TC=0`: cuBLAS BF16, an FP32 SIMT kernel on Volta) |
| QSA attention for decode and verify windows (and prompts with `STRATA_PROMPT_ATTN_OLD=1`) | #540's kernel (fewer shuffles, bit-exact; `STRATA_ATTN_PRE75=0`: the one other cards run) |
| QSA prompt attention, int8 / FP16 / K8V4 KV | `prompt_attn_v70_kernel` on `mma.m8n8k4` (`STRATA_PROMPT_ATTN_OLD=1`: the decode kernel, one query at a time) |
| QSA prompt attention, Q4_0 KV | the decode kernel |
| QSA block scores | the warp kernel (the tensor-core scorer needs sm_80) |
## Measured
One V100-PCIE-32GB, i9-7960X, Unsloth `UD-IQ4_XS` (not a setup model), int8 KV, MTP `--spec 2`; prompt read speed of random-word prompts, tokens/s,
with and without the Volta attention kernel (`STRATA_PROMPT_ATTN_OLD=1`):
| Prompt tokens | old attention path | `prompt_attn_v70_kernel` |
| --- | ---: | ---: |
| 7,194 | 1,010 | 1,164 |
| 28,650 | 1,063 | 1,251 |
| 114,338 | 973 | 1,123 |
Decode was 38-51 tok/s in every run and is not affected. The profile, the parity numbers, the needle test and the limits are in
[bench/results/2026-10-03-v100-prompt-attn](../bench/results/2026-10-03-v100-prompt-attn/README.md).
What the kernel does and does not guarantee: against an FP64 reference its error is about 5e-6 (output scale 3.6; the FP32 kernel it replaces: 2e-6); 15 of 15
needles were found; greedy output was identical on the 28,650- and 114,338-token prompts and differed late in the answer on the 7,194-token one (another
summation order).
## Checking and benchmarking the Volta kernels
```sh
cmake -S . -B build -DSTRATA_PARITY_PROMPT_ATTN=ON ... && cmake --build build --target qsa_prompt_attn_parity
CUDA_VISIBLE_DEVICES=0 ./build/qsa_prompt_attn_parity 32768 2048 5 # synthetic, no model; exit 0 = PASS
```
It compares the tensor-core attention with the FP32 kernel and an FP64 host reference and times both. The Q4_0 cases are skipped below
sm_80.
## Limits
- A layer split over two V100 was not measured with this kernel. The cards work in turn on a single request, so a split adds expert-cache room, not prompt speed.
- sm_60 (Pascal) is covered by the same flag but was not measured here.
- Volta's tensor cores take FP16 only: a model's BF16 weights are converted, and a weight outside FP16's range would saturate (none did in
the check above).
+111
View File
@@ -0,0 +1,111 @@
# Older GPUs (experimental)
Strata's supported cards are NVIDIA RTX 20 / 30 / 40 / 50 and the AMD cards in [AMD_HIP.md](AMD_HIP.md). The cards
below run through **opt-in, experimental** paths that community members wrote and measured on their own machines. The
maintainers have none of these cards: each path is compile-checked and unit-tested here, and the ready-made engines
and their output stay exactly as they were. Numbers are the reporters' own, on one machine each.
## Support matrix
### NVIDIA
| Cards | Compute capability | How it runs | What is different on it | Reported |
| --- | --- | --- | --- | --- |
| Tesla P100 | 6.0 | the CUDA 12 engine | `__dp4a` emulated (bit-exact); BF16 projections through fp32 | not measured |
| Tesla P40 / P4, GTX 10 series | 6.1 | the CUDA 12 engine | BF16 projections through fp32 (cuBLAS has no BF16 GEMM there, #395) | P40, IQ3_S, engine 0.1.30: prompt 217-374 tok/s, decode 30-33 tok/s (#395) |
| Tesla V100, Titan V | 7.0 | the CUDA 12 engine | BF16 projections on the FP16 tensor cores (#655, #540); the prompt attention on `mma.m8n8k4` (#600); a leaner attention kernel (#540) | V100-PCIE-32GB, UD-IQ4_XS: prompt 1,123-1,251 tok/s (#600); V100 32GB, IQ2_XS: prompt +22% from #540 |
| RTX 20 (Turing) | 7.5 | **supported**, the ready-made engine | opt-in: `STRATA_BF16_TC=1` runs the BF16 projections on the FP16 tensor cores | RTX 2080 Ti, Q2_0: prompt +15-18% (#655) |
A card needs enough VRAM to be useful: 12 GB or more is recommended, as for every card (a 2 GB GT 1030 is compute
capability 6.1 too, and cannot hold any of the model).
### AMD
| Cards | Architecture | How it runs | Reported |
| --- | --- | --- | --- |
| RX 6800 / 6900 series | gfx1030 | setup (`--backend hip`), unvalidated | [AMD_HIP.md](AMD_HIP.md#rdna2-gfx1030) |
| RX 6700 XT | gfx1031 | setup (`--backend hip`), unvalidated (#524) | used daily by its reporter, one card |
| RX 5500 XT (RDNA1) | gfx1012 | built by hand: `-DCMAKE_HIP_ARCHITECTURES=gfx1012` (HIP 5.7 or 7) | 8 GB card, IQ3_S, 8K prompt: 15.3 tok/s decode (#442) |
| Instinct MI50 / MI60, Radeon VII | gfx906 (wave64) | built by hand: `-DSTRATA_HIP_GFX906=ON` | 2x MI50, Coder IQ1_M, 128K context: decode 50.1 / 47.8 / 45.7 tok/s at 4K / 32K / 128K prompt tokens, prompt ~520 tok/s (#677) |
## NVIDIA: the CUDA 12 engine
CUDA 13 dropped Pascal and Volta: it cannot compile for them. Setup therefore keeps a **second engine**, built with
CUDA 12.9 and `-DSTRATA_EXPERIMENTAL_SM60=ON`, in its own folder (`engine-cuda12\`, beside `engine\`). One engine runs
per model, so the choice is made per model, by the oldest card that model runs on:
- **Every card the model uses is RTX 20 or newer:** the ready-made CUDA 13 engine, as always.
- **A card is Pascal or Volta:** the CUDA 12 engine. Setup says so (`CUDA 12: sm_70 is older than CUDA 13 supports
...`). On Windows it downloads `strata-windows-x64-cuda12.zip` with NVIDIA's CUDA 12 libraries (from pip, like the
CUDA 13 ones); on Linux, or with `--build`, it compiles the engine with a CUDA 12.x toolkit.
### Opting in
An older card is used only when you choose it; a PC with a newer card keeps recommending the newer one.
| You | Setup |
| --- | --- |
| have only Pascal / Volta NVIDIA cards (and no AMD card it can use) | uses them, with the CUDA 12 engine |
| name the card: `START-HERE.bat --setup --gpu 1`, or `--gpus 0,1` with a newer card | uses it; the model gets the CUDA 12 engine |
| `--cuda 12` (or `STRATA_CUDA=12`) | the CUDA 12 engine for this model, on any card |
| `--cuda 13` | the CUDA 13 engine even with an older card (a warning: it has no code for that card) |
| `STRATA_EXPERIMENTAL_SM60=1` | the older cards are listed as usable (the setting from #295 still works) |
The choice is kept in the model's config (`"cuda": 12`): its starts and `UPDATE.bat` keep it, and other models keep
their own engine. Setting the model up again chooses again (by its cards; add `--cuda 12` to keep a forced choice). A Pascal / Volta card added to a model at a start (`--gpus`) moves that model to the
CUDA 12 engine.
`--cuda 12` is also the way to run Strata with an NVIDIA driver older than 580: CUDA 12 needs 528 or newer on Windows
(527.41, NVIDIA's minor-version compatibility) and 525 on Linux; setup's "driver too old" stop says so. Such old
drivers were not tested here.
### Mixed cards
A model that shares a V100 with an RTX 30 / 40 card runs both on the CUDA 12 engine (it has code for sm_60 to sm_89,
plus PTX). An RTX 50 card (sm_120) in a CUDA 12 engine is a warning, not a stop: CUDA 12.8 and newer compile for it,
but engines built with 12.8 crashed on long prompts there (#220, #224). Keep the RTX 50 card on its own model (`--gpu
N`), where it runs the CUDA 13 engine.
### Building it yourself
```sh
# Linux (Windows: the same with the toolkit's nvcc.exe)
cmake -S . -B build-cuda12 -DSTRATA_ENABLE_CUDA=ON -DSTRATA_BUILD_TESTS=OFF -DSTRATA_EXPERIMENTAL_SM60=ON \
-DCMAKE_CUDA_ARCHITECTURES="61;70" -DCMAKE_CUDA_COMPILER=/usr/local/cuda-12.9/bin/nvcc
cmake --build build-cuda12 --target strata -j
```
Setup does the same when it compiles: it looks for the newest CUDA 12.x toolkit (`STRATA_NVCC=<path to nvcc>` picks
one, #601; on glibc 2.43 use 12.8, see [TROUBLESHOOTING.md](TROUBLESHOOTING.md)).
### What the flag changes, and what it does not
`-DSTRATA_EXPERIMENTAL_SM60=ON` lowers the runtime floor to compute capability 6.0 and compiles the older cards' code
paths into that build only: the Volta prompt attention (#600), #540's attention kernel (used below sm_75), and the
Pascal BF16 path. The ready-made CUDA 13 engine has none of them, so its kernels and its output are unchanged. The
FP16 path for BF16 projections is in every build but runs by default only below sm_75; RTX 20 owners can try it with
`STRATA_BF16_TC=1` (`=0` turns it off on a V100). It is not bitwise the same as cuBLAS's BF16 kernel (FP16 tensor-core
sums round differently): #540 measured a mean KL of 8.4e-3 on the next-token distribution of 24 code prompts on a V100
(the same top-1 in 23), the size of other summation-order changes; #655 a worst relative difference of 3.5e-5 per
product on an RTX 2080 Ti.
A/B switches: `STRATA_BF16_TC=0|1`, `STRATA_PROMPT_ATTN_OLD=1` (the decode kernel for prompts), `STRATA_ATTN_PRE75=0`
(#540's kernel off). [NVIDIA_V100.md](NVIDIA_V100.md) has the V100 build, its measurements and the parity test.
## AMD: building gfx906 and gfx1012
Setup does not build these; build by hand and run `serve/server.py` with a config, as on any other card.
- **gfx906** (MI50 / MI60 / Radeon VII, wave64): a separate opt-in build, `-DSTRATA_HIP_GFX906=ON
-DCMAKE_HIP_ARCHITECTURES=gfx906` (not `STRATA_ENABLE_HIP`). Current ROCm no longer ships gfx906 libraries; the
reporter used a community ROCm 7.14 image. Recipe, kernels and measurements: [AMD_HIP.md](AMD_HIP.md#gfx906-instinct-mi50--mi60-radeon-vii-wave64-built-from-source).
- **gfx1012** (RX 5500 XT): the wave32 backend, `-DSTRATA_ENABLE_HIP=ON -DCMAKE_HIP_ARCHITECTURES=gfx1012`. HIP 5.7
(Ubuntu's packages) works: older hipBLAS (0.x) is used through rocBLAS, the legacy HIP names and the missing
`__syncwarp` are version-gated, and RDNA1's missing signed dot4 uses llama.cpp's SDWA sequence
(`-DSTRATA_GFX1012_PORTABLE_DOT=ON`: the portable one).
## Reports welcome
These paths stay experimental until more people run them. A report with the card, the driver / ROCm version, the
model and the engine log (`strata-<model>.log`) in an issue helps; [COMMUNITY_BENCHMARKS.md](COMMUNITY_BENCHMARKS.md)
has the format for measurements.
+3
View File
@@ -168,6 +168,9 @@ bool moe_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer,
/// rung, so a host that sees it knows `h_x_f`/`h_ids`/`h_weights` are in place.
bool moe_route(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b,
const float* x, void* stream, std::string& err, const Doorbell* db = nullptr);
/// The verify window's n tokens routed at once (see layer.cpp); bitwise per token what `moe_route` gives.
bool moe_route_window(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b,
const float* x, float* logits, int32_t* ids, float* weights, int n, void* stream, std::string& err);
/// The finishing half: the shared expert and the combination.
///
+41
View File
@@ -1,5 +1,45 @@
#pragma once
#include <hipblas/hipblas.h>
#include <hipblas/hipblas-version.h>
#if hipblasVersionMajor == 0
// Ubuntu's hipBLAS 0.54 has no workspace API or compute-type enum. Use its
// underlying rocBLAS API directly, including ownership of the real handle,
// so the engine's explicit workspace contract is preserved.
#include <rocblas/rocblas.h>
#define CUBLAS_COMPUTE_32F rocblas_datatype_f32_r
#define CUBLAS_DEFAULT_MATH 0
#define CUBLAS_GEMM_DEFAULT rocblas_gemm_algo_standard
#define CUBLAS_OP_N rocblas_operation_none
#define CUBLAS_OP_T rocblas_operation_transpose
#define CUBLAS_STATUS_SUCCESS rocblas_status_success
#define CUDA_R_16BF rocblas_datatype_bf16_r
#define CUDA_R_16F rocblas_datatype_f16_r
#define CUDA_R_32F rocblas_datatype_f32_r
#define cublasCreate rocblas_create_handle
#define cublasDestroy rocblas_destroy_handle
#define cublasHandle_t rocblas_handle
#define cublasSetStream rocblas_set_stream
#define cublasSetWorkspace rocblas_set_workspace
#define cublasStatus_t rocblas_status
inline rocblas_status cublasSetMathMode(rocblas_handle h, int mode) {
// This API has only its default arithmetic; GEMM below explicitly selects
// FP32 accumulation. Reject any request for a different math mode.
if (!h) return rocblas_status_invalid_handle;
return mode == CUBLAS_DEFAULT_MATH ? rocblas_status_success : rocblas_status_invalid_value;
}
inline rocblas_status cublasGemmEx(rocblas_handle h, rocblas_operation trans_a,
rocblas_operation trans_b, int m, int n, int k, const void* alpha,
const void* a, rocblas_datatype a_type, int lda,
const void* b, rocblas_datatype b_type, int ldb, const void* beta,
void* c, rocblas_datatype c_type, int ldc,
rocblas_datatype compute_type, rocblas_gemm_algo algo) {
return rocblas_gemm_ex(h, trans_a, trans_b, m, n, k, alpha,
a, a_type, lda, b, b_type, ldb, beta, c, c_type, ldc,
c, c_type, ldc, compute_type, algo, 0, 0);
}
#else
#define CUBLAS_COMPUTE_32F HIPBLAS_COMPUTE_32F
#define CUBLAS_DEFAULT_MATH HIPBLAS_DEFAULT_MATH
#define CUBLAS_GEMM_DEFAULT HIPBLAS_GEMM_DEFAULT
@@ -17,3 +57,4 @@
#define cublasSetStream hipblasSetStream
#define cublasSetWorkspace hipblasSetWorkspace
#define cublasStatus_t hipblasStatus_t
#endif
+11
View File
@@ -10,6 +10,7 @@
#endif
#endif
#include <hip/hip_runtime.h>
#include <hip/hip_version.h>
// Do not let HIP's legacy macro corrupt libstdc++ attribute names.
#ifdef __noinline__
#undef __noinline__
@@ -39,7 +40,11 @@
#define cudaEventSynchronize hipEventSynchronize
#define cudaEvent_t hipEvent_t
#define cudaFree hipFree
#if HIP_VERSION_MAJOR < 7
#define cudaFreeHost hipHostFree
#else
#define cudaFreeHost hipFreeHost
#endif
#define cudaFuncAttributeMaxDynamicSharedMemorySize hipFuncAttributeMaxDynamicSharedMemorySize
#define cudaGetDevice hipGetDevice
#define cudaGetDeviceCount hipGetDeviceCount
@@ -54,9 +59,15 @@
#define cudaGraphUpload hipGraphUpload
#define cudaGraph_t hipGraph_t
#define cudaHostAlloc hipHostMalloc
#if HIP_VERSION_MAJOR < 7
#define cudaHostAllocDefault hipHostMallocDefault
#define cudaHostAllocMapped hipHostMallocMapped
#define cudaHostAllocPortable hipHostMallocPortable
#else
#define cudaHostAllocDefault hipHostAllocDefault
#define cudaHostAllocMapped hipHostAllocMapped
#define cudaHostAllocPortable hipHostAllocPortable
#endif
#define cudaHostGetDevicePointer hipHostGetDevicePointer
#define cudaHostRegister hipHostRegister
#define cudaHostRegisterMapped hipHostRegisterMapped
+31 -1
View File
@@ -1,8 +1,9 @@
#pragma once
// CUDA device intrinsics used by Strata kernels that HIP does not provide on RDNA2 / RDNA3 / RDNA4 (wave32).
// CUDA device intrinsics used by Strata kernels on supported wave32 HIP targets.
// This header is included only from the HIP cuda_runtime compatibility shim.
#if defined(__HIPCC__)
#include <hip/hip_version.h>
#include <cstdint>
@@ -25,6 +26,21 @@ __device__ __forceinline__ int dp4a(int a, int b, int c) {
// RDNA2 has no sudot4 (that is gfx11+), but it has the plain signed v_dot4_i32_i8 (dot1-insts): the same
// signed x signed byte products accumulated modulo 2^32, no clamp.
return __builtin_amdgcn_sdot4(a, b, c, false);
#elif defined(__gfx1012__) && !defined(STRATA_GFX1012_PORTABLE_DOT)
// RDNA1 has no native signed dot4. SDWA selects and sign-extends byte
// operands directly, avoiding separate shift/mask/sign-extension work.
// Adapted from pinned llama.cpp ggml-cuda/common.cuh (MIT; see
// third_party/ggml/LICENSE), same modulo-2^32 accumulation contract.
int lo, hi;
asm("v_mul_i32_i24 %1, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0 src1_sel:BYTE_0\n"
"v_mul_i32_i24 %2, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_1 src1_sel:BYTE_1\n"
"v_add3_u32 %0, %1, %2, %0\n"
"v_mul_i32_i24 %1, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_2 src1_sel:BYTE_2\n"
"v_mul_i32_i24 %2, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_3 src1_sel:BYTE_3\n"
"v_add3_u32 %0, %1, %2, %0\n"
// c changes before the high-byte reads; it must not alias a or b.
: "+&v"(c), "=&v"(lo), "=&v"(hi) : "v"(a), "v"(b));
return c;
#else
const uint32_t ua = static_cast<uint32_t>(a);
const uint32_t ub = static_cast<uint32_t>(b);
@@ -84,6 +100,17 @@ __device__ __forceinline__ void require_full_wave_mask(uint32_t mask) {
if (mask != 0xffffffffu) __builtin_trap();
}
// Older HIP has no __syncwarp. A wave barrier alone does not order memory.
// Release/acquire fences cover the shared-memory exchange used by attention.
#if HIP_VERSION_MAJOR < 7
__device__ __forceinline__ void syncwarp(uint32_t mask = 0xffffffffu) {
require_full_wave_mask(mask);
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup");
__builtin_amdgcn_wave_barrier();
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup");
}
#endif
template <typename T>
__device__ __forceinline__ T shfl_xor_sync(uint32_t mask, T value, int lane_mask, int width = 32) {
require_full_wave_mask(mask);
@@ -125,6 +152,9 @@ __device__ __forceinline__ unsigned ballot_sync(uint32_t mask, int predicate) {
#define __shfl_up_sync(...) (::strata::hip_compat::shfl_up_sync(__VA_ARGS__))
#define __shfl_sync(...) (::strata::hip_compat::shfl_sync(__VA_ARGS__))
#define __ballot_sync(mask, predicate) (::strata::hip_compat::ballot_sync((mask), (predicate)))
#if HIP_VERSION_MAJOR < 7
#define __syncwarp(...) (::strata::hip_compat::syncwarp(__VA_ARGS__))
#endif
// AMD's sleep instruction accepts only 0..15; the synchronization loops use it as a
// backoff hint, so use its smallest portable delay independently of CUDA cycle counts.
#define __nanosleep(cycles) __builtin_amdgcn_s_sleep(1)
@@ -0,0 +1,4 @@
#pragma once
// CUDA spelling used by the attention kernels; included only in HIP builds.
#include <hip/hip_math_constants.h>
#define CUDART_INF_F HIP_INF_F
+4
View File
@@ -44,6 +44,10 @@ void bf16_gemv_split(const uint16_t* x, const uint16_t* w, float* y, int64_t n_i
/// No allocations or synchronization, including when stream is null (the CUDA default stream).
void bf16_gemv_fp32_mmvf(const float* x, const uint16_t* w, float* y,
int64_t n_in, int64_t n_out, void* stream);
/// `ncols` columns at once: x is [ncols][n_in], y is [ncols][n_out]; each column bitwise equal to a
/// `bf16_gemv_fp32_mmvf` call on it.
void bf16_gemv_fp32_mmvf_cols(const float* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, int ncols,
void* stream);
/// bf16_gemv_fp32_mmvf for n_tok (1..8) activation rows x[t * ldx], outputs y[t * ldy + j]; one launch,
/// the weight read once, every output bit-identical to its own single-row call.
void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy,
+3
View File
@@ -19,6 +19,9 @@
#pragma once
#include <cstdint>
#if defined(STRATA_HIP_GFX906)
#include <cuda_runtime.h> // gfx906: the compat layer (__forceinline__, __nanosleep, __dp4a)
#endif
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 610
__device__ __forceinline__ int strata_dp4a(const int a, const int b, const int c) {
+2
View File
@@ -49,6 +49,8 @@ constexpr int kFusedGrMaxT = 8;
void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream,
unsigned long long* stamp_buf = nullptr, int stamp_i0 = 0);
/// The bench only: the AMD latency-hidden kernels on (1) or off (0); -1 = STRATA_GR_FAST.
void fused_gr_set_fast(int on);
/// The multi read's variants (#315; not main's opt-in STRATA_GR_V3 read, which sums in another order), all computing
/// every output with the plain read's operations in its order, so bitwise the plain read's and the single-token
/// read's: plain (0.1.31's default: the norm one block per token, the down projection on 41 blocks), split (the norm
+3
View File
@@ -68,6 +68,9 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long
/// (native_grouped_parity checks it); kept for A/B timing. Set before graph capture; captured graphs keep theirs.
void native_grouped_set_v1(bool v1);
/// The bench only: the AMD kernel layout (STRATA_EXP_MODE values; -1 = the environment's) and the phase
/// (0 all, 1 gate/up + SwiGLU + quantize, 2 down).
void native_expert_set_mode(int mode, int phase);
/// `iq_mmvq` and `native_expert_grouped` decode each weight part once and apply it to every column / entry;
/// true selects the older kernels that decode it again per column (STRATA_OLD_IQ_MMVQ=1 at startup). Both give
/// bitwise the same results. Set before graph capture; captured graphs keep the kernels they captured.
+3
View File
@@ -15,6 +15,9 @@
#pragma once
#include <cstdint>
#if defined(__HIPCC__) && defined(STRATA_HIP_GFX906) // PR #638: the gfx906 compat build only
#include <hip/hip_runtime.h>
#endif
#include "strata/kernels/rope_scaling.hpp"
@@ -0,0 +1,26 @@
// cublas_v2.h for a STRATA_ENABLE_HIP build: the cuBLAS names src/prefill/gemm.cu uses, on hipBLAS.
#pragma once
#include "strata_hip.h"
#ifndef HIPBLAS_V2
#define HIPBLAS_V2
#endif
#include <hipblas/hipblas.h>
#define cublasHandle_t hipblasHandle_t
#define cublasStatus_t hipblasStatus_t
#define CUBLAS_STATUS_SUCCESS HIPBLAS_STATUS_SUCCESS
#define cublasCreate hipblasCreate
#define cublasDestroy hipblasDestroy
#define cublasSetStream hipblasSetStream
#define cublasGemmEx hipblasGemmEx
#define CUBLAS_OP_N HIPBLAS_OP_N
#define CUBLAS_OP_T HIPBLAS_OP_T
#define CUBLAS_GEMM_DEFAULT HIPBLAS_GEMM_DEFAULT
#define CUBLAS_COMPUTE_32F HIPBLAS_COMPUTE_32F
#define CUDA_R_32F HIP_R_32F
#define CUDA_R_16F HIP_R_16F
#define CUDA_R_16BF HIP_R_16BF
// rocBLAS picks its own math and workspace; the NVIDIA-only knobs are accepted and ignored
#define CUBLAS_DEFAULT_MATH 0
#define cublasSetMathMode(handle, mode) HIPBLAS_STATUS_SUCCESS
#define cublasSetWorkspace(handle, ptr, bytes) HIPBLAS_STATUS_SUCCESS
@@ -0,0 +1,2 @@
#pragma once
#include "strata_hip.h"
@@ -0,0 +1,2 @@
#pragma once
#include "strata_hip.h"
@@ -0,0 +1,4 @@
// math_constants.h for a STRATA_ENABLE_HIP build: the CUDART_* constants the tree uses.
#pragma once
#define CUDART_INF_F __builtin_huge_valf()
#define CUDART_NAN_F __builtin_nanf("")
@@ -0,0 +1,295 @@
// strata_hip.h - the CUDA runtime/cuBLAS names Strata uses, mapped onto HIP/hipBLAS for AMD GPUs (gfx906).
//
// This directory is put FIRST on the include path of a STRATA_ENABLE_HIP build only; its `cuda_runtime.h`,
// `cuda_fp16.h` and `cublas_v2.h` include this header instead of the NVIDIA ones, so the engine's sources stay
// one tree. The mapping list follows llama.cpp's ggml-cuda/vendors/hip.h (MIT) where the two overlap.
//
// The warp contract: every Strata kernel is written for a 32-lane warp. gfx906 runs 64-lane wavefronts, so
// here a CUDA warp is a LOGICAL 32-lane half of a wavefront: every shuffle defaults to width 32 (a
// `__shfl_down_sync(m, v, 1)` at lane 31 must not read lane 32), `__ballot_sync` returns the 32-bit mask of the
// caller's own half, and `__syncwarp` is a wavefront barrier plus an LDS fence. That keeps every kernel's
// arithmetic, lane mapping and reduction order exactly as on NVIDIA; wave64-native rewrites of the hot kernels
// are separate, measured changes.
#pragma once
#ifndef HIP_DISABLE_WARP_SYNC_BUILTINS
#define HIP_DISABLE_WARP_SYNC_BUILTINS 1
#endif
#include <hip/hip_runtime.h>
#include <hip/hip_fp16.h>
#include <cstdint>
#include <cstdlib>
#define STRATA_HIP_GFX906 1
// ---- runtime: types and constants ------------------------------------------------------------------------
#define cudaError_t hipError_t
#define cudaSuccess hipSuccess
#define cudaErrorNotReady hipErrorNotReady
#define cudaErrorMemoryAllocation hipErrorOutOfMemory
#define cudaErrorStreamCaptureUnsupported hipErrorStreamCaptureUnsupported
#define cudaErrorPeerAccessAlreadyEnabled hipErrorPeerAccessAlreadyEnabled
#define cudaStream_t hipStream_t
#define cudaEvent_t hipEvent_t
#define cudaGraph_t hipGraph_t
#define cudaGraphExec_t hipGraphExec_t
#define cudaGraphNode_t hipGraphNode_t
#define cudaDeviceProp hipDeviceProp_t
#define cudaMemcpyKind hipMemcpyKind
#define cudaMemcpyHostToDevice hipMemcpyHostToDevice
#define cudaMemcpyDeviceToHost hipMemcpyDeviceToHost
#define cudaMemcpyDeviceToDevice hipMemcpyDeviceToDevice
#define cudaMemcpyDefault hipMemcpyDefault
#define cudaStreamNonBlocking hipStreamNonBlocking
#define cudaStreamCaptureModeThreadLocal hipStreamCaptureModeThreadLocal
#define cudaStreamCaptureModeRelaxed hipStreamCaptureModeRelaxed
#define cudaStreamCaptureModeGlobal hipStreamCaptureModeGlobal
#define cudaStreamCaptureStatus hipStreamCaptureStatus
#define cudaStreamCaptureStatusNone hipStreamCaptureStatusNone
#define cudaStreamCaptureStatusActive hipStreamCaptureStatusActive
#define cudaEventDisableTiming hipEventDisableTiming
#define cudaEventDefault hipEventDefault
#define cudaHostAllocDefault hipHostMallocDefault
#define cudaHostAllocPortable hipHostMallocPortable
#define cudaHostAllocMapped hipHostMallocMapped
#define cudaHostAllocWriteCombined hipHostMallocWriteCombined
#define cudaHostRegisterDefault hipHostRegisterDefault
#define cudaHostRegisterPortable hipHostRegisterPortable
#define cudaHostRegisterMapped hipHostRegisterMapped
#define cudaHostRegisterReadOnly hipHostRegisterReadOnly
#define cudaDeviceScheduleSpin hipDeviceScheduleSpin
#define cudaDeviceScheduleYield hipDeviceScheduleYield
#define cudaDeviceScheduleBlockingSync hipDeviceScheduleBlockingSync
#define cudaDeviceMapHost hipDeviceMapHost
#define cudaFuncAttributeMaxDynamicSharedMemorySize hipFuncAttributeMaxDynamicSharedMemorySize
#define cudaDevAttrMultiProcessorCount hipDeviceAttributeMultiprocessorCount
#define cudaDevAttrClockRate hipDeviceAttributeClockRate
#define cudaDevAttrComputeCapabilityMajor hipDeviceAttributeComputeCapabilityMajor
#define cudaDevAttrComputeCapabilityMinor hipDeviceAttributeComputeCapabilityMinor
#define cudaDevAttrMaxSharedMemoryPerBlockOptin hipDeviceAttributeSharedMemPerBlockOptin
#define cudaDevAttrMemoryClockRate hipDeviceAttributeMemoryClockRate
#define cudaDevAttrGlobalMemoryBusWidth hipDeviceAttributeMemoryBusWidth
// ---- runtime: functions ----------------------------------------------------------------------------------
#define cudaGetErrorString hipGetErrorString
#define cudaGetErrorName hipGetErrorName
#define cudaGetLastError hipGetLastError
#define cudaPeekAtLastError hipPeekAtLastError
#define cudaGetDevice hipGetDevice
#define cudaSetDevice hipSetDevice
#define cudaGetDeviceCount hipGetDeviceCount
#define cudaGetDeviceProperties hipGetDeviceProperties
// The shared-memory opt-in limit: some HIP versions report 0 for it on GCN cards; the real ceiling there is
// the plain per-block limit (64 KB of LDS on gfx906).
inline hipError_t strata_device_get_attribute(int* v, hipDeviceAttribute_t a, int dev) {
hipError_t e = hipDeviceGetAttribute(v, a, dev);
if (e == hipSuccess && a == hipDeviceAttributeSharedMemPerBlockOptin && *v <= 0)
e = hipDeviceGetAttribute(v, hipDeviceAttributeMaxSharedMemoryPerBlock, dev);
return e;
}
#define cudaDeviceGetAttribute strata_device_get_attribute
#define cudaDeviceSynchronize hipDeviceSynchronize
#define cudaDeviceCanAccessPeer hipDeviceCanAccessPeer
#define cudaDeviceEnablePeerAccess hipDeviceEnablePeerAccess
#define cudaDriverGetVersion hipDriverGetVersion
#define cudaRuntimeGetVersion hipRuntimeGetVersion
#define cudaSetDeviceFlags hipSetDeviceFlags
#define cudaMalloc hipMalloc
#define cudaFree hipFree
#define cudaMemGetInfo hipMemGetInfo
#define cudaMemcpy hipMemcpy
#define cudaMemcpyAsync hipMemcpyAsync
#define cudaMemcpyPeerAsync hipMemcpyPeerAsync
#define cudaMemcpy2DAsync hipMemcpy2DAsync
#define cudaMemset hipMemset
#define cudaMemsetAsync hipMemsetAsync
// Mapped host memory is how the GPU and the CPU talk inside a running graph (the doorbells, the CPU experts'
// results, the verify flags): a kernel spins on a word the CPU writes, and the CPU on a word the kernel writes.
// On AMD that needs FINE-GRAINED (coherent) memory - coarse-grained host memory may sit in the GPU's L2 for the
// whole kernel and the spin never sees the other side. So every mapped allocation is made coherent here.
inline hipError_t strata_host_alloc(void** p, size_t bytes, unsigned int flags) {
if (flags & hipHostMallocMapped) flags |= hipHostMallocCoherent;
return hipHostMalloc(p, bytes, flags);
}
template <typename T> inline hipError_t strata_host_alloc(T** p, size_t bytes, unsigned int flags) {
return strata_host_alloc(reinterpret_cast<void**>(p), bytes, flags);
}
#define cudaHostAlloc strata_host_alloc
#define cudaMallocHost(ptr, size) hipHostMalloc(ptr, size, hipHostMallocDefault)
#define cudaFreeHost hipHostFree
#define cudaHostRegister hipHostRegister
#define cudaHostUnregister hipHostUnregister
#define cudaHostGetDevicePointer hipHostGetDevicePointer
#define cudaStreamCreate hipStreamCreate
#define cudaStreamCreateWithFlags hipStreamCreateWithFlags
#define cudaStreamDestroy hipStreamDestroy
#define cudaStreamSynchronize hipStreamSynchronize
#define cudaStreamQuery hipStreamQuery
#define cudaStreamWaitEvent hipStreamWaitEvent
#define cudaStreamBeginCapture hipStreamBeginCapture
#define cudaStreamEndCapture hipStreamEndCapture
#define cudaStreamIsCapturing hipStreamIsCapturing
#define cudaLaunchHostFunc hipLaunchHostFunc
#define cudaEventCreate hipEventCreate
#define cudaEventCreateWithFlags hipEventCreateWithFlags
#define cudaEventDestroy hipEventDestroy
#define cudaEventRecord hipEventRecord
#define cudaEventQuery hipEventQuery
#define cudaEventSynchronize hipEventSynchronize
#define cudaEventElapsedTime hipEventElapsedTime
#define cudaGraphLaunch hipGraphLaunch
#define cudaGraphUpload hipGraphUpload
#define cudaGraphDestroy hipGraphDestroy
#define cudaGraphExecDestroy hipGraphExecDestroy
#define cudaGraphGetNodes hipGraphGetNodes
#define cudaGraphNodeType hipGraphNodeType
#define cudaGraphNodeGetType hipGraphNodeGetType
#define cudaGraphNodeTypeKernel hipGraphNodeTypeKernel
#define cudaGraphNodeTypeMemcpy hipGraphNodeTypeMemcpy
#define cudaGraphNodeTypeMemset hipGraphNodeTypeMemset
#define cudaKernelNodeParams hipKernelNodeParams
#define cudaGraphKernelNodeGetParams hipGraphKernelNodeGetParams
inline hipError_t cudaFuncGetName(const char** name, const void*) { *name = nullptr; return hipErrorNotSupported; }
#define cudaFuncSetAttribute(fn, attr, val) hipFuncSetAttribute(reinterpret_cast<const void*>(fn), attr, val)
#define cudaMemcpyToSymbol(sym, src, ...) hipMemcpyToSymbol(HIP_SYMBOL(sym), src, __VA_ARGS__)
// CUDA 12 has a 3-argument cudaGraphInstantiate(exec, graph, flags) and the older 5-argument one; HIP spells
// the first hipGraphInstantiateWithFlags. Both are used in the tree.
inline hipError_t cudaGraphInstantiate(hipGraphExec_t* exec, hipGraph_t graph, unsigned long long flags) {
return hipGraphInstantiateWithFlags(exec, graph, flags);
}
inline hipError_t cudaGraphInstantiate(hipGraphExec_t* exec, hipGraph_t graph, hipGraphNode_t* err_node,
char* log, size_t log_size) {
return hipGraphInstantiate(exec, graph, err_node, log, log_size);
}
// cudaInitDevice(dev, deviceFlags, flags): initialise a device and its scheduling flags WITHOUT making it the
// current device (CUDA's contract; the layer split relies on it - a changed current device put GPU 0's expert
// cache on GPU 1).
inline hipError_t cudaInitDevice(int device, unsigned int device_flags, unsigned int /*flags*/) {
int prev = 0;
hipError_t e = hipGetDevice(&prev);
if (e != hipSuccess) return e;
e = hipSetDevice(device);
if (e != hipSuccess) return e;
if (hipSetDeviceFlags(device_flags) != hipSuccess) (void) hipGetLastError(); // context already active
return hipSetDevice(prev);
}
// ---- device side -----------------------------------------------------------------------------------------
#if defined(__HIP_DEVICE_COMPILE__) || defined(__HIPCC__)
// Logical 32-lane warps (see the header comment). The width argument, when given, wins.
#define __shfl_sync(mask, var, lane, ...) __shfl(var, lane, STRATA_SHFL_W(__VA_ARGS__))
#define __shfl_up_sync(mask, var, delta, ...) __shfl_up(var, delta, STRATA_SHFL_W(__VA_ARGS__))
#define __shfl_down_sync(mask, var, delta, ...) __shfl_down(var, delta, STRATA_SHFL_W(__VA_ARGS__))
#define __shfl_xor_sync(mask, var, lanemask, ...) __shfl_xor(var, lanemask, STRATA_SHFL_W(__VA_ARGS__))
// STRATA_SHFL_W() -> 32, STRATA_SHFL_W(w) -> w
#define STRATA_SHFL_W(...) STRATA_SHFL_W_I(dummy, ##__VA_ARGS__, STRATA_SHFL_W_GIVEN, STRATA_SHFL_W_DEFAULT)(__VA_ARGS__)
#define STRATA_SHFL_W_I(d, a, b, ...) b
#define STRATA_SHFL_W_GIVEN(w) (w)
#define STRATA_SHFL_W_DEFAULT(...) 32
#define __all_sync(mask, pred) __all(pred)
#define __any_sync(mask, pred) __any(pred)
static __device__ __forceinline__ unsigned int strata_ballot32(int pred) {
const unsigned long long b = __ballot(pred);
return (unsigned int) (b >> (__lane_id() & 32u));
}
#define __ballot_sync(mask, pred) strata_ballot32(pred)
#define __activemask() ((unsigned int) (__ballot(1) >> (__lane_id() & 32u)))
static __device__ __forceinline__ void strata_syncwarp() {
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "wavefront");
__builtin_amdgcn_wave_barrier();
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "wavefront");
}
#define __syncwarp(...) strata_syncwarp()
// __nanosleep(ns): s_sleep counts 64 clocks per unit (~40 ns at the 1.7 GHz shader clock); a spin loop only
// needs "back off a little", not an exact time.
static __device__ __forceinline__ void strata_nanosleep(unsigned int ns) {
if (ns >= 400) __builtin_amdgcn_s_sleep(8);
else __builtin_amdgcn_s_sleep(1);
}
#define __nanosleep(ns) strata_nanosleep(ns)
#define __trap() __builtin_trap()
// __dp4a(a, b, c): signed 8-bit dot product plus accumulator; gfx906 has v_dot4_i32_i8.
static __device__ __forceinline__ int strata_dp4a(int a, int b, int c) {
#if defined(__gfx906__) || defined(__gfx908__) || defined(__gfx90a__) || defined(__gfx942__) || defined(__GFX11__) || defined(__GFX12__)
return __builtin_amdgcn_sdot4(a, b, c, false);
#else
const int8_t* va = reinterpret_cast<const int8_t*>(&a);
const int8_t* vb = reinterpret_cast<const int8_t*>(&b);
return c + va[0] * vb[0] + va[1] * vb[1] + va[2] * vb[2] + va[3] * vb[3];
#endif
}
static __device__ __forceinline__ unsigned int strata_dp4a(unsigned int a, unsigned int b, unsigned int c) {
const uint8_t* va = reinterpret_cast<const uint8_t*>(&a);
const uint8_t* vb = reinterpret_cast<const uint8_t*>(&b);
return c + va[0] * vb[0] + va[1] * vb[1] + va[2] * vb[2] + va[3] * vb[3];
}
#define __dp4a strata_dp4a
// SIMD-in-a-word byte ops (CUDA semantics: __vsub4 wraps per byte, __vsubss4 saturates, __vcmp*4 give 0xff)
typedef int8_t strata_i8x4 __attribute__((ext_vector_type(4)));
typedef uint8_t strata_u8x4 __attribute__((ext_vector_type(4)));
static __device__ __forceinline__ unsigned int strata_vsub4(unsigned int a, unsigned int b) {
const strata_u8x4 va = __builtin_bit_cast(strata_u8x4, a);
const strata_u8x4 vb = __builtin_bit_cast(strata_u8x4, b);
return __builtin_bit_cast(unsigned int, (strata_u8x4) (va - vb));
}
static __device__ __forceinline__ int strata_vsubss4(int a, int b) {
const strata_i8x4 va = __builtin_bit_cast(strata_i8x4, a);
const strata_i8x4 vb = __builtin_bit_cast(strata_i8x4, b);
return __builtin_bit_cast(int, (strata_i8x4) __builtin_elementwise_sub_sat(va, vb));
}
static __device__ __forceinline__ unsigned int strata_vcmpeq4(unsigned int a, unsigned int b) {
const strata_u8x4 va = __builtin_bit_cast(strata_u8x4, a);
const strata_u8x4 vb = __builtin_bit_cast(strata_u8x4, b);
strata_u8x4 c;
#pragma unroll
for (int i = 0; i < 4; ++i) c[i] = va[i] == vb[i] ? 0xff : 0x00;
return __builtin_bit_cast(unsigned int, c);
}
static __device__ __forceinline__ unsigned int strata_vcmpne4(unsigned int a, unsigned int b) {
return ~strata_vcmpeq4(a, b);
}
#define __vsub4(a, b) ((int) strata_vsub4((unsigned int) (a), (unsigned int) (b)))
#define __vsubss4(a, b) strata_vsubss4((int) (a), (int) (b))
#define __vcmpeq4(a, b) strata_vcmpeq4((unsigned int) (a), (unsigned int) (b))
#define __vcmpne4(a, b) strata_vcmpne4((unsigned int) (a), (unsigned int) (b))
// __fmul_rn / __fadd_rn / __fsub_rn: on NVIDIA these are never contracted into an FMA (that is their point - the
// engine uses them where a result must match a reference bit for bit). HIP spells them as plain operators, which
// clang's default -ffp-contract=fast-honor-pragmas may fuse. The pragma keeps each one a separate rounding.
static __device__ __forceinline__ float strata_fmul_rn(float a, float b) {
#pragma clang fp contract(off)
return a * b;
}
static __device__ __forceinline__ float strata_fadd_rn(float a, float b) {
#pragma clang fp contract(off)
return a + b;
}
static __device__ __forceinline__ float strata_fsub_rn(float a, float b) {
#pragma clang fp contract(off)
return a - b;
}
#define __fmul_rn(a, b) strata_fmul_rn((a), (b))
#define __fadd_rn(a, b) strata_fadd_rn((a), (b))
#define __fsub_rn(a, b) strata_fsub_rn((a), (b))
// __byte_perm(x, y, s): HIP's own version builds an 8-byte array and indexes it - the array lands in SCRATCH
// memory, and every IQ4 codebook lookup went through it (a 0.9 MB IQ4_NL GEMV took 290 us, ~3 GB/s). gfx906 has
// v_perm_b32, which selects bytes of {src0:src1} (src1 low) by byte selectors 0-7: the same operation, one
// instruction. CUDA reads the low 3 bits of each of the four low selector nibbles.
static __device__ __forceinline__ unsigned int strata_byte_perm(unsigned int x, unsigned int y, unsigned int s) {
const unsigned int sel = (s & 0x7u) | ((s & 0x70u) << 4) | ((s & 0x700u) << 8) | ((s & 0x7000u) << 12);
return __builtin_amdgcn_perm(y, x, sel);
}
#define __byte_perm(x, y, s) strata_byte_perm((unsigned int) (x), (unsigned int) (y), (unsigned int) (s))
#endif // device side
+7
View File
@@ -26,6 +26,8 @@ public:
std::string& err);
/// Y[T, N] (fp32, row stride ldy) = X[T, K] (bf16, row-major) . W[N, K]^T (bf16, row-major). `beta` = 1 adds.
/// Below sm_80 (no BF16 tensor cores): Volta converts both to FP16 and runs the FP16 tensor-core GEMM (Turing with
/// STRATA_BF16_TC=1), Pascal widens both to fp32 (cublasSgemm); see gemm.cu.
void bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy = 0,
float beta = 0.0f);
@@ -52,6 +54,11 @@ private:
void* workspace_ = nullptr;
bool external_ = false;
void* hipblaslt_state_ = nullptr;
// below sm_80: FP16 (Pascal: fp32) copies of a BF16 product's weight and activation slice (Gemm::bf16)
uint16_t* tc_w_ = nullptr;
int64_t tc_w_elems_ = 0;
uint16_t* tc_x_ = nullptr;
int64_t tc_x_elems_ = 0;
};
+259 -75
View File
@@ -104,6 +104,17 @@ PREBUILT_ASSET = "strata-windows-x64.zip" if WIN else "strata-linux-x64.zip"
# the CUDA libraries the ready-made engine loads (the same CUDA 13.0 it is built with), from NVIDIA's pip packages
CUDA_WHEELS = ["nvidia-cublas==13.0.2.14", "nvidia-cuda-runtime==13.0.96"]
MIN_DRIVER = 580 # CUDA 13.0
# Older NVIDIA GPUs (experimental): CUDA 13 dropped Pascal (sm_60/61) and Volta (sm_70), so a model whose GPUs include
# one runs a second engine, built with CUDA 12.9 (-DSTRATA_EXPERIMENTAL_SM60=ON) and kept in its own folder: the
# ready-made one is CUDA12_ASSET (Windows; on Linux it is compiled here with a CUDA 12.x toolkit). One engine runs per
# model, so the choice is per model config, by its oldest GPU; --cuda 12|13 overrides it (docs/OLDER_GPUS.md).
CUDA13_MIN_ARCH = 75 # the oldest compute capability CUDA 13 compiles for (sm_75, RTX 20)
CUDA12_ASSET = "strata-windows-x64-cuda12.zip" if WIN else "strata-linux-x64-cuda12.zip"
CUDA12_WHEELS = ["nvidia-cublas-cu12==12.9.1.4", "nvidia-cuda-runtime-cu12==12.9.79"]
# CUDA 12.x minor-version compatibility (NVIDIA's table: Linux 525.60.13, Windows 527.41); the wheels match the 12.9.1
# toolkit the CUDA 12 zip is built with (cuBLAS 12.9.1.4, runtime 12.9.79). Not tested on such an old driver here.
CUDA12_MIN_DRIVER = 528 if WIN else 525
ENGINE12_DIR = "engine-cuda12"
MIN_ENGINE = (0, 1, 39) # v0.1.39: the #577 file-tier regression fixed, the OpenAI Responses API (#451, Codex), a reply stuck on one token ended (#606), the head before the arena (#620), effort_position (#458), --vram-reserve hot resize opt-in (#533), PR batch; v0.1.38: prompts faster (one gather per expert group #372, the first chunk's PLE rows beside layer 0 #374, DeltaNet three heads per thread #413), --kv q4_0 prompts on tensor cores (#452), Q5_0 experts on the GPU (#473), IQ4_XS on AVX-2 (#415), unbuffered expert loading on Windows (#357 #362), --peer-device (#531), a 6 GB card starts (#496), PR batch; v0.1.37: a silent engine is restarted (#481), Windows AMD counts the desktop's VRAM (#380 #377 #497), a steadier PCIe probe (#485), fixes #496 #495 #498 #505 #493; v0.1.36: a cancelled prompt logged as read so far (#471), the draft-head hint (#474), UPDATE.bat (#475), --expert-profile-save (#477); v0.1.35: Windows AMD uses its bundled HIP runtime (#468 #461), the low-RAM resident mode on Windows 32 GB (#467), fixes #460 #459 #446 #447 #457 #448 #444; v0.1.34: AMD on Windows (a ready-made HIP engine), an MCP server for AI assistants (tools/strata_mcp.py), a shorter README; v0.1.33: a portable image encoder again (#411 #412), setup recommends instead of forcing (#406 #403 #364 #384), fixes #352 #365 #369 #371 #375 #393 #408 #414; v0.1.32: split prompts faster (#340), AMD router +12%, Unsloth Q4 in setup, faster Q4 prompts, #326/#327/#342/#344 fixes, PR batch; v0.1.31: Unsloth UD-Q4_K_XL (experimental), GGUF-in-place low-RAM mode, Windows GGUF load 2x, server race + tokenizer fixes, AMD intrinsics; v0.1.30: short prompts faster (streaming from 1024 tokens), resident low-RAM variant, multi-GPU session carve, RDNA4; v0.1.29: sampled answers faster (split top-k), #154 correctness fixes; v0.1.28: the expert cache reserves the draft head, a cancelled request no longer fails the next; v0.1.27: RTX 20 (sm_75) in the ready-made engine, the HIP build without CUDA headers; v0.1.26: the draft layer's prompt pass in batches; v0.1.25: faster prompts (grouping off the copy engine, fused hyper-connection kernels), AMD HIP backend, --kv k8v4; v0.1.24: long prompts faster (QSA select on tensor cores); v0.1.23: image requests honor sampling, 8 GB cards start, batched verify window; v0.1.22: faster prompts (tensor-core attention), multi-GPU across images/steering/KV streaming; v0.1.21: multi-GPU layer split (--gpus); v0.1.20: system-prompt checkpoint, PCIe probe, hit rate; v0.1.19: penalties
PY_PACKAGES = ["numpy", "jinja2", "regex", "pyyaml", "tqdm", "requests", "cmake", "ninja", "pillow", "psutil"]
REQUIREMENTS = ROOT / "requirements.txt" # the same packages and their dependencies, pinned (#214)
@@ -539,22 +550,84 @@ def cc(g) -> str:
return f"{g['arch'][:-1]}.{g['arch'][-1]}"
OLD_GPUS = None # why Pascal / Volta cards are admitted in this run (old_gpus_opt_in), None: they are not
def experimental_sm60() -> bool:
"""#295: STRATA_EXPERIMENTAL_SM60=1 admits Pascal (6.x) and Volta (7.0) cards: the community build
(-DSTRATA_EXPERIMENTAL_SM60=ON, compiled here with a CUDA 12.x toolkit), not the ready-made engine."""
return os.environ.get("STRATA_EXPERIMENTAL_SM60", "").strip() == "1"
"""#295: STRATA_EXPERIMENTAL_SM60=1 admits Pascal (6.x) and Volta (7.0) cards, run by the experimental CUDA 12
engine (-DSTRATA_EXPERIMENTAL_SM60=ON). So does naming such a card (--gpu N / --gpus), --cuda 12, or a PC that
has no newer card (old_gpus_opt_in)."""
return os.environ.get("STRATA_EXPERIMENTAL_SM60", "").strip() == "1" or OLD_GPUS is not None
def sm60_card(arch) -> bool:
return 60 <= int(arch) <= 70
def old_gpus_opt_in(found, named=(), cuda=None, other=False):
"""Why this run may use Pascal / Volta cards (the experimental CUDA 12 engine), or None. The cards are an opt-in:
the user named one (`named`: --gpu / --gpus), asked for --cuda 12, set STRATA_EXPERIMENTAL_SM60=1, or the PC has
no card the ready-made engine runs on and no supported AMD card (`other`; it used to stop there). A PC with a
newer card keeps recommending it."""
old = [g for g in found if sm60_card(g["arch"])]
if not old:
return None
if os.environ.get("STRATA_EXPERIMENTAL_SM60", "").strip() == "1":
return "STRATA_EXPERIMENTAL_SM60=1"
if str(cuda) == "12":
return "--cuda 12"
picked = [g for g in old if g["index"] in set(named)]
if picked:
return "you chose " + ", ".join(f"GPU {g['index']} ({g['name']})" for g in picked)
if not other and not any(int(g["arch"]) >= CUDA13_MIN_ARCH for g in found):
return "it is the only kind of NVIDIA GPU in this PC"
return None
def named_gpus(gpu, gpus) -> list:
"""The card numbers --gpu / --gpus name (an unreadable value: none; parse_gpus says what is wrong later)."""
try:
if gpus and str(gpus).strip().lower() != "all":
return [int(x) for x in str(gpus).split(",") if x.strip()]
return [int(gpu)] if gpu is not None else []
except ValueError:
return []
def cuda_choice(archs, cuda=None):
"""The CUDA toolkit of one model's engine: (12 or 13, why). 13 (the ready-made engine) unless a card is older
than CUDA 13 supports (Pascal / Volta: CUDA 13 cannot compile for them) - one engine runs per model, so its oldest
card decides. `cuda` (--cuda 12|13) overrides it; setup recommends, it does not refuse (the caller warns)."""
archs = sorted({int(x) for x in archs})
old = [a for a in archs if a < CUDA13_MIN_ARCH]
if str(cuda) == "13":
return 13, ("--cuda 13 (as you chose)" + (f"; CUDA 13 has no code for sm_{old[0]}: the engine will not run "
"on that card" if old else ""))
if str(cuda) == "12":
return 12, "--cuda 12 (as you chose" + ("; RTX 50 (sm_120) engines built with CUDA 12.8 crashed on long "
"prompts, #220" if archs and archs[-1] >= 120 else "") + ")"
if old:
return 12, (f"sm_{old[0]} is older than CUDA 13 supports (it dropped Pascal and Volta): this model runs the "
"experimental CUDA 12 engine")
return 13, None
def engine_dir(toolkit=13) -> Path:
"""The folder of the engine a model runs: engine/ (CUDA 13, or HIP), engine-cuda12/ (the experimental one)."""
return ROOT / (ENGINE12_DIR if int(toolkit) == 12 else "engine")
def config_toolkit(cfg: dict) -> int:
"""12 when a model config runs the experimental CUDA 12 engine (its exe is in engine-cuda12/), else 13."""
return 12 if cfg.get("cuda") == 12 or Path(str(cfg.get("exe", ""))).parent.name == ENGINE12_DIR else 13
def gpu_problem(g, together=False):
"""Why Strata cannot use this card, in plain words (None: it can)."""
if int(g["arch"]) < 75 and not (sm60_card(g["arch"]) and experimental_sm60()):
return (f"not supported - older than the RTX 20 series (compute capability {cc(g)}; Strata needs 7.5 or "
"newer" + ("; STRATA_EXPERIMENTAL_SM60=1 tries the community build for it" if sm60_card(g["arch"])
else "") + ")")
"newer" + ("; experimental: choose it with --gpu " + str(g["index"]) + " (the CUDA 12 engine, "
"docs/OLDER_GPUS.md)" if sm60_card(g["arch"]) else "") + ")")
if together and g["vram_gb"] < SPLIT_MIN_VRAM_GB - 0.5:
return (f"not supported together with other GPUs - {g['vram_gb']:.0f} GB of VRAM (a card sharing the model "
f"needs {SPLIT_MIN_VRAM_GB} GB or more)")
@@ -644,9 +717,9 @@ def check_gpus(sel, found, what="", yes=False, named=False) -> None:
fail(f"GPU {i}{'' if g is None else ' (' + g['name'] + ')'} {what}cannot be used: {p}", hint)
def engine_archs():
def engine_archs(toolkit=13):
"""The GPU generations the installed engine has code for: (archs, ptx), or None when there is none."""
info = ROOT / "engine" / "BUILD.json"
info = engine_dir(toolkit) / "BUILD.json"
try:
meta = json.loads(info.read_text())
except (OSError, ValueError):
@@ -663,8 +736,8 @@ def engine_archs_hip():
return [str(x) for x in meta.get("archs", [])] if meta.get("backend") == "hip" else None
def engine_runs_on(g) -> bool:
ea = engine_archs()
def engine_runs_on(g, toolkit=13) -> bool:
ea = engine_archs(toolkit)
if ea is None or not ea[0]:
return True
archs, ptx = ea
@@ -813,7 +886,8 @@ def offer_together(cfg_path: Path, cfg: dict, yes: bool) -> dict:
short = split_short(pair) # #448: one card recommended (asked "n" by default), as for --resident
for g in short:
say(f" {split_short_note(g)}.")
missing = [g for g in pair if not engine_runs_on(g)]
tk = config_toolkit(cfg)
missing = [g for g in pair if not (engine_runs_on(g) if tk == 13 else engine_runs_on(g, tk))]
if missing:
say(" The installed engine has no code for " + ", ".join(g["name"] for g in missing) + ": to use them "
"together, run START-HERE.bat --setup --gpus " + ",".join(str(g["index"]) for g in pair))
@@ -1224,38 +1298,46 @@ def pip_install(packages, what):
ok(f"{what} installed")
def cuda_lib_dirs():
"""Where pip put NVIDIA's CUDA libraries (nvidia/cu13/bin/x86_64 on Windows, nvidia/cu13/lib on Linux)."""
pattern = "cublas64_13.dll" if WIN else "libcublas.so.13*"
def cuda_lib_dirs(toolkit=13):
"""Where pip put NVIDIA's CUDA libraries (nvidia/cu13/bin/x86_64 on Windows, nvidia/cu13/lib on Linux).
toolkit 12: the CUDA 12 wheels' cuBLAS and runtime, in two folders (nvidia/cublas/bin, nvidia/cuda_runtime/bin)."""
if int(toolkit) == 12:
patterns = ("cublas64_12.dll", "cudart64_12.dll") if WIN else ("libcublas.so.12*", "libcudart.so.12*")
else:
patterns = ("cublas64_13.dll",) if WIN else ("libcublas.so.13*",)
dirs = []
for sp in {Path(p) for p in sys.path if p.endswith("site-packages")}:
for hit in (sp / "nvidia").rglob(pattern) if (sp / "nvidia").is_dir() else []:
if hit.parent not in dirs:
dirs.append(hit.parent)
for pattern in patterns:
for hit in (sp / "nvidia").rglob(pattern) if (sp / "nvidia").is_dir() else []:
if hit.parent not in dirs:
dirs.append(hit.parent)
return [str(d) for d in dirs]
# ------------------------------------------------------------------------------------------------ AMD
# The RX 7900 XT / XTX (gfx1100) and the RX 9070 series / Radeon AI PRO R9700 (gfx1201) on Linux, through the HIP
# backend (docs/AMD_HIP.md); the RX 7800 XT / 7700 XT (gfx1101, #254) and the RX 9060 XT (gfx1200, #256) were run by
# their owners; the RX 6800 / 6900 series (gfx1030, #311) runs but is unvalidated. There is no ready-made AMD engine: ROCm comes from AMD's TheRock Python wheels into .venv (no sudo;
# their owners; the RX 6800 / 6900 series (gfx1030, #311) and the RX 6700 XT (gfx1031, #524) run but are unvalidated. There is no ready-made AMD engine: ROCm comes from AMD's TheRock Python wheels into .venv (no sudo;
# a system ROCm 7 in /opt/rocm is used when it has hipcc and hipBLAS) and the engine is compiled here for the cards.
# No images yet.
ROCM_INDEXES = {"gfx1100": "https://rocm.nightlies.amd.com/v2/gfx110X-dgpu/", # TheRock's wheels per GPU family
"gfx1101": "https://rocm.nightlies.amd.com/v2/gfx110X-dgpu/",
"gfx1200": "https://rocm.nightlies.amd.com/v2/gfx120X-all/",
"gfx1201": "https://rocm.nightlies.amd.com/v2/gfx120X-all/",
"gfx1030": "https://rocm.nightlies.amd.com/v2/gfx103X-all/"}
"gfx1030": "https://rocm.nightlies.amd.com/v2/gfx103X-all/",
"gfx1031": "https://rocm.nightlies.amd.com/v2/gfx103X-all/"}
ROCM_VERSION = os.environ.get("STRATA_ROCM_VERSION", "7.10.0a20251120") # what Strata's HIP build was tested with
ROCM_SYSTEM_MIN = (7, 0) # an older system ROCm is passed over for the wheels (gfx1201 needs ROCm 6.4 or newer)
AMD_ARCHS = ("gfx1100", "gfx1101", "gfx1200", "gfx1201", "gfx1030")
AMD_ARCHS = ("gfx1100", "gfx1101", "gfx1200", "gfx1201", "gfx1030", "gfx1031")
AMD_NAMES = {"gfx1100": "AMD Radeon RX 7900 series (gfx1100)", # when sysfs has no product name
"gfx1101": "AMD Radeon RX 7800 XT / 7700 XT (gfx1101)",
"gfx1200": "AMD Radeon RX 9060 series (gfx1200)",
"gfx1201": "AMD Radeon RX 9070 series / AI PRO R9700 (gfx1201)",
"gfx1030": "AMD Radeon RX 6800 / 6900 series (gfx1030)"}
"gfx1030": "AMD Radeon RX 6800 / 6900 series (gfx1030)",
"gfx1031": "AMD Radeon RX 6700 XT series (gfx1031)"}
AMD_CARDS = ("the RX 7900 XT / XTX (gfx1100), RX 7800 XT / 7700 XT (gfx1101), RX 9060 XT (gfx1200) and "
"RX 9070 / 9070 XT / Radeon AI PRO R9700 (gfx1201), and the RX 6800 / 6900 series (gfx1030, unvalidated)")
"RX 9070 / 9070 XT / Radeon AI PRO R9700 (gfx1201), and the RX 6800 / 6900 series (gfx1030) and RX 6700 XT "
"(gfx1031, #524), both unvalidated")
def rocm_index(arch):
@@ -1833,10 +1915,12 @@ def prebuilt_bases(url_base) -> list[str]:
return [PREBUILT_TAG_URL.format(version=source_version()), base]
def get_prebuilt(url_base, gpu, vision, updating=False) -> Path | None:
def get_prebuilt(url_base, gpu, vision, updating=False, toolkit=13) -> Path | None:
"""The ready-made engine in engine/ (kept between runs), or None when there is none for this PC.
updating: called to replace an installed engine, which starts instead when this fails (no compile)."""
eng = ROOT / "engine"
updating: called to replace an installed engine, which starts instead when this fails (no compile).
toolkit 12: the experimental CUDA 12 engine (CUDA12_ASSET) in engine-cuda12/."""
eng = engine_dir(toolkit)
asset = CUDA12_ASSET if int(toolkit) == 12 else PREBUILT_ASSET
info = eng / "BUILD.json"
if info.exists() and (eng / EXE).exists() and json.loads(info.read_text()).get("backend") != "hip":
meta = json.loads(info.read_text())
@@ -1857,13 +1941,14 @@ def get_prebuilt(url_base, gpu, vision, updating=False) -> Path | None:
info.unlink()
if not url_base:
return None
z = ROOT / "engine" / PREBUILT_ASSET
eng.mkdir(exist_ok=True)
z = eng / asset
bases = prebuilt_bases(url_base)
for i, base in enumerate(bases):
if not base.startswith(("http://", "https://")):
break
try: # not published (yet), or no internet: compile instead
req = urllib.request.Request(base + PREBUILT_ASSET, method="HEAD", headers={"User-Agent": "strata-setup"})
req = urllib.request.Request(base + asset, method="HEAD", headers={"User-Agent": "strata-setup"})
urllib.request.urlopen(req, timeout=60).close()
break
except OSError as e:
@@ -1872,9 +1957,9 @@ def get_prebuilt(url_base, gpu, vision, updating=False) -> Path | None:
continue
warn(f"no ready-made engine at {base} ({e})" + ("" if updating else ": compiling instead"))
return None
say(" Downloading the ready-made Strata engine ...")
download(base + PREBUILT_ASSET, z, "Strata engine")
tmp = ROOT / "engine" / "_unpack"
say(" Downloading the ready-made Strata engine" + (" (CUDA 12, experimental)" if int(toolkit) == 12 else "") + " ...")
download(base + asset, z, "Strata engine")
tmp = eng / "_unpack"
shutil.rmtree(tmp, ignore_errors=True)
with zipfile.ZipFile(z) as f:
f.extractall(tmp)
@@ -1917,11 +2002,17 @@ def get_prebuilt(url_base, gpu, vision, updating=False) -> Path | None:
return eng
def update_installed_engine(url_base) -> None:
def update_installed_engine(url_base, toolkit=None) -> None:
"""An installed ready-made engine older than MIN_ENGINE is replaced before the model starts, so a plain
START-HERE.bat on an existing install picks up a new release. If that cannot happen (no internet, the model
still running, no ready-made engine for this GPU) the installed engine is kept and starts as before."""
eng = ROOT / "engine"
still running, no ready-made engine for this GPU) the installed engine is kept and starts as before.
toolkit None: engine/, then the experimental CUDA 12 engine in engine-cuda12/ when one is installed."""
if toolkit is None:
update_installed_engine(url_base, 13)
if (engine_dir(12) / "BUILD.json").exists():
update_installed_engine(url_base, 12)
return
eng = engine_dir(toolkit)
info = eng / "BUILD.json"
if not info.exists() or not (eng / EXE).exists():
return
@@ -1979,14 +2070,19 @@ def update_installed_engine(url_base) -> None:
if gpu is None:
raise RuntimeError("no NVIDIA GPU found")
gpu = {**gpu, "archs": sorted({int(gpu["arch"]), *(int(x) for x in meta.get("archs", []))})}
build_engine(gpu, vision, False, get_llama_cpp())
if int(toolkit) == 12: # the cards it was compiled for (the main GPU may be newer)
gpu["archs"] = sorted({int(x) for x in meta.get("archs", [])}) or gpu["archs"]
build_engine(gpu, vision, False, get_llama_cpp(), toolkit=toolkit)
except (Exception, SystemExit) as e:
warn(f"could not compile the updated engine{'' if isinstance(e, SystemExit) else f' ({e})'}: starting the installed one")
return
new = None
if gpu is not None:
try:
new = get_prebuilt(url_base, gpu, "gpu", updating=True)
if int(toolkit) == 12: # the cards the CUDA 12 engine serves, not the newest one
gpu = {**gpu, "archs": [x for x in (int(a) for a in meta.get("archs", [])) if x < CUDA13_MIN_ARCH]
or [int(gpu["arch"])]}
new = get_prebuilt(url_base, gpu, "gpu", updating=True, toolkit=toolkit)
except Exception as e: # a failed download must not stop the model from starting
warn(f"updating the engine failed ({e})")
if new is None:
@@ -1994,25 +2090,36 @@ def update_installed_engine(url_base) -> None:
info.write_text(meta_text) # get_prebuilt drops it before downloading: put it back
warn(f"could not update the engine: starting the installed {meta.get('version')}")
return
pip_install(CUDA_WHEELS, "NVIDIA CUDA libraries (cuBLAS, CUDA runtime; ~0.4 GB)")
pip_cuda_libs(toolkit)
def pip_cuda_libs(toolkit=13) -> None:
"""NVIDIA's cuBLAS and CUDA runtime for a ready-made engine, from pip: CUDA 13's, or the CUDA 12 engine's."""
if int(toolkit) == 12:
pip_install(CUDA12_WHEELS, "NVIDIA CUDA 12 libraries for the experimental engine (cuBLAS, CUDA runtime; ~0.7 GB)")
else:
pip_install(CUDA_WHEELS, "NVIDIA CUDA libraries (cuBLAS, CUDA runtime; ~0.4 GB)")
def install_build_tools(gpu, yes):
"""The compiler and the CUDA toolkit, installed for the user (asks once). Returns (nvcc, vcvars)."""
archs = [int(x) for x in gpu.get("archs", [gpu["arch"]])]
# #295: Pascal / Volta (STRATA_EXPERIMENTAL_SM60=1) need a CUDA 12.x toolkit - CUDA 13 cannot build sm_60/sm_70
old = min(archs) < 75
# #295: Pascal / Volta need a CUDA 12.x toolkit - CUDA 13 cannot build sm_60/sm_70; gpu["toolkit"] = 12: the
# experimental CUDA 12 engine for any cards (--cuda 12, docs/OLDER_GPUS.md)
old = int(gpu.get("toolkit") or (12 if min(archs) < CUDA13_MIN_ARCH else 13)) == 12
need12 = (12, 8) if max(archs) >= 120 else (12, 0) # sm_120 needs CUDA 12.8 or newer
if old and max(archs) >= 120:
fail("one engine cannot be built for both an RTX 50 card (CUDA 13) and a Pascal/Volta card (CUDA 12.x)",
"choose the cards of one kind with --gpu / --gpus")
warn("an RTX 50 card (sm_120) in a CUDA 12 engine: engines built with CUDA 12.8 crashed on long prompts there "
"(#220, #224); the RTX 50 card alone (--gpu N) runs the ready-made CUDA 13 engine")
nvcc, cuda_v = find_nvcc(below=(13, 0)) if old else find_nvcc()
if old and (nvcc is None or cuda_v < (12, 0)):
fail("the experimental Pascal/Volta build (STRATA_EXPERIMENTAL_SM60=1) needs the NVIDIA CUDA Toolkit 12.x "
"(CUDA 13 cannot compile for these cards)",
"install CUDA 12.9 (or another 12.x; it can sit next to a newer one) from "
"https://developer.nvidia.com/cuda-toolkit-archive and run it again")
if old and (nvcc is None or cuda_v < need12):
fail("the experimental CUDA 12 engine (Pascal / Volta, or --cuda 12) is compiled here with the NVIDIA CUDA "
f"Toolkit {need12[0]}.{need12[1]} or a newer 12.x (CUDA 13 cannot compile for these cards)" +
(f"; found CUDA {cuda_v[0]}.{cuda_v[1]}" if nvcc else ""),
"install CUDA 12.9 (it can sit next to a newer one) from https://developer.nvidia.com/cuda-toolkit-archive "
"and run it again (STRATA_NVCC=<its nvcc> picks one toolkit)")
# RTX 50 (sm_120): CUDA 13.0 - an engine built with 12.8 crashed in the prompt path on Linux (#220)
need_cuda = (13, 0) if max(archs) >= 120 else (12, 0)
need_cuda = need12 if old else (13, 0) if max(archs) >= 120 else (12, 0)
vcvars = find_vcvars() if WIN else None
have_cc = vcvars is not None if WIN else shutil.which("g++") is not None
missing = []
@@ -2116,9 +2223,10 @@ def isa_floor_defs(floor: str, bdir: Path, meta: dict) -> list:
return [f"-DSTRATA_ISA_FLOOR={floor}"] if floor else []
def engine_defs(archs) -> list:
"""Extra CMake definitions for the engine: the experimental Pascal/Volta build (#295) for cards below sm_75."""
return ["-DSTRATA_EXPERIMENTAL_SM60=ON"] if min(int(x) for x in archs) < 75 else []
def engine_defs(archs, toolkit=13) -> list:
"""Extra CMake definitions for the engine: the experimental Pascal/Volta build (#295) for cards below sm_75, and
for every CUDA 12 engine (the same build as the ready-made CUDA 12 one: it admits the older cards)."""
return ["-DSTRATA_EXPERIMENTAL_SM60=ON"] if min(int(x) for x in archs) < 75 or int(toolkit) == 12 else []
def prebuilt_vision(meta: dict, gpu: dict, vision: str) -> str:
@@ -2135,10 +2243,15 @@ def prebuilt_vision(meta: dict, gpu: dict, vision: str) -> str:
return vision
def build_engine(gpu, vision, yes, llama) -> Path:
def build_engine(gpu, vision, yes, llama, toolkit=None) -> Path:
"""Compile the engine (and, for images, the encoder) for this GPU; the results go to engine/. A compiled
engine whose source files changed since (a `git pull`) is compiled again: only the changed files, a few minutes."""
eng = ROOT / "engine"
engine whose source files changed since (a `git pull`) is compiled again: only the changed files, a few minutes.
toolkit 12 (default: 12 for a card older than CUDA 13 supports): the experimental CUDA 12 engine, in
engine-cuda12/ with its own build folders."""
if toolkit is None:
toolkit = 12 if min(int(x) for x in gpu.get("archs", [gpu["arch"]])) < CUDA13_MIN_ARCH else 13
t12 = int(toolkit) == 12
eng = engine_dir(toolkit)
eng.mkdir(exist_ok=True)
stamp = eng / "BUILD.json"
meta = json.loads(stamp.read_text()) if stamp.exists() else {}
@@ -2159,30 +2272,32 @@ def build_engine(gpu, vision, yes, llama) -> Path:
return eng
if local:
archs = sorted(built | set(archs))
nvcc, vcvars = install_build_tools({**gpu, "archs": archs}, yes)
nvcc, vcvars = install_build_tools({**gpu, "archs": archs, "toolkit": toolkit}, yes)
cuda_archs = ";".join(str(x) for x in archs)
bdir, vdir = (ROOT / "build-cuda12", ROOT / "build-vision-cuda12") if t12 else (ROOT / "build", ROOT / "build-vision")
if not engine_ok:
say(" Compiling the engine for " + ", ".join(f"sm_{x}" for x in archs) + " (a card it had no code for; "
"10-20 minutes, once) ..." if new_arch else
" The engine's source changed: compiling it again (only what changed, a few minutes) ..."
if local and (eng / EXE).exists() else " Compiling the Strata engine for your GPU (10-20 minutes, once) ...")
cmake_build(ROOT, ROOT / "build", "strata",
cmake_build(ROOT, bdir, "strata",
["-DSTRATA_ENABLE_CUDA=ON", "-DSTRATA_BUILD_TESTS=OFF", f"-DCMAKE_CUDA_ARCHITECTURES={cuda_archs}",
f"-DCMAKE_CUDA_COMPILER={nvcc}", f"-DSTRATA_GGML_DIR={llama}", *engine_defs(archs),
*isa_floor_defs(floor, ROOT / "build", meta)],
vcvars, "build-strata.bat")
shutil.copy2(ROOT / "build" / EXE, eng / EXE)
f"-DCMAKE_CUDA_COMPILER={nvcc}", f"-DSTRATA_GGML_DIR={llama}", *engine_defs(archs, toolkit),
*isa_floor_defs(floor, bdir, meta)],
vcvars, "build-strata-cuda12.bat" if t12 else "build-strata.bat")
shutil.copy2(bdir / EXE, eng / EXE)
if not vision_ok:
say(" Compiling the image encoder" + (" with CUDA (10-20 minutes, once) ..." if vision == "gpu" else " ..."))
defs = [f"-DLLAMA_DIR={llama}", f"-DSTRATA_VISION_CUDA={'ON' if vision == 'gpu' else 'OFF'}"]
if vision == "gpu":
defs += [f"-DCMAKE_CUDA_ARCHITECTURES={cuda_archs}", f"-DCMAKE_CUDA_COMPILER={nvcc}"]
cmake_build(ROOT / "tools" / "vision", ROOT / "build-vision", "strata-vision", defs, vcvars, "build-vision.bat")
shutil.copy2(ROOT / "build-vision" / "bin" / VEXE, eng / VEXE)
cmake_build(ROOT / "tools" / "vision", vdir, "strata-vision", defs, vcvars,
"build-vision-cuda12.bat" if t12 else "build-vision.bat")
shutil.copy2(vdir / "bin" / VEXE, eng / VEXE)
bindir = Path(nvcc).parent # the toolkit's own libraries (bin, bin/x64, lib64)
dirs = [str(d) for d in (bindir, bindir / "x64", bindir.parent / "lib64") if d.is_dir()]
stamp.write_text(json.dumps({"source": "local", "version": source_version(), "archs": archs,
"vision": vision,
"vision": vision, **({"toolkit": 12} if t12 else {}),
"cuda_dirs": dirs, "src": src, "vision_src": vsrc if want_vision else None,
**({"isa_floor": floor} if floor else {})}, indent=1))
ok(f"engine compiled: {eng / EXE}")
@@ -2672,7 +2787,7 @@ def choices_from_config(cfg_path: Path) -> dict:
"vision": ("gpu" if vis.get("gpu") else "cpu") if isinstance(vis, dict) else "none",
"esp": ("on" if Path(esp_path).name == ESP_VECTOR.name else esp_path) if esp_path else "off",
"host": cfg.get("host"), "api_key": cfg.get("api_key"), "port": cfg.get("port"), "gpu": cfg.get("gpu"),
"layer_split": cfg.get("layer_split"),
"layer_split": cfg.get("layer_split"), "cuda": 12 if config_toolkit(cfg) == 12 else None,
# #493: --vram-reserve-mib given at setup (images write the default 700 themselves)
"vram_reserve_mib": int(val("--vram-reserve-mib")) if (val("--vram-reserve-mib") or "").isdigit() and (
vis is None or int(val("--vram-reserve-mib")) != VISION["gpu"]["reserve_mib"]) else None}
@@ -2980,6 +3095,10 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_
ok(f"GPU: {g['name']} ({g['vram_gb']:.0f} GB, AMD)")
else:
found = gpus()
global OLD_GPUS # Pascal / Volta: named on this start, or this model's CUDA 12 engine
OLD_GPUS = OLD_GPUS or old_gpus_opt_in(found, gpu if isinstance(gpu, list) else [gpu] if gpu is not None else
cfg.get("gpu") if isinstance(cfg.get("gpu"), list) else [cfg.get("gpu")],
12 if config_toolkit(cfg) == 12 else None)
if cfg.get("backend") == "hip":
pass
elif isinstance(gpu, list): # --gpus: saved, this model runs on these cards from now on
@@ -3186,25 +3305,68 @@ def refresh_draft_vocab(rt: Path, choice: str = "cjk") -> None:
def ensure_engine_for(cards, cfg_path: Path, cfg: dict, yes: bool) -> dict:
"""The installed engine must have code for every card the model starts on: a card added later (--gpus with an
older or newer generation, #128) or a new GPU in the PC otherwise stops the start with 'no kernel image'. Such a
card gets the engine compiled for all of them, before the start."""
missing = [g for g in cards if not engine_runs_on(g)]
card gets the engine compiled for all of them, before the start. A Pascal / Volta card added to a model on the
CUDA 13 engine moves the model to the experimental CUDA 12 engine (CUDA 13 has no code for it)."""
tk = config_toolkit(cfg)
if tk == 13 and any(int(g["arch"]) < CUDA13_MIN_ARCH for g in cards):
return use_cuda12(cards, cfg_path, cfg, yes)
missing = [g for g in cards if not (engine_runs_on(g) if tk == 13 else engine_runs_on(g, tk))]
if not missing:
return cfg
info = ROOT / "engine" / "BUILD.json"
eng = engine_dir(tk)
info = eng / "BUILD.json"
meta = json.loads(info.read_text())
say()
say(" The installed engine has no code for " + ", ".join(f"{g['name']} (sm_{g['arch']})" for g in missing) +
": it is compiled for " + ("these cards" if len(cards) > 1 else "it") + " now.")
main = gpu_info(cards[0]["index"])
archs = sorted({int(x) for x in meta.get("archs", [])} | {int(g["arch"]) for g in cards})
vision = meta.get("vision") or ("gpu" if (ROOT / "engine" / VEXE).exists() else "none")
build_engine({**main, "archs": archs}, vision, yes, get_llama_cpp())
vision = meta.get("vision") or ("gpu" if (eng / VEXE).exists() else "none")
build_engine({**main, "archs": archs}, vision, yes, get_llama_cpp(), toolkit=tk)
dirs = json.loads(info.read_text()).get("cuda_dirs") or []
cfg["lib_dirs"] = dirs + [d for d in cfg.get("lib_dirs") or [] if d not in dirs]
write_config(cfg_path, cfg)
return cfg
def get_cuda12_engine(url_base, gpu, vision, yes, build=False) -> Path:
"""The experimental CUDA 12 engine for these cards (gpu["archs"]): the ready-made one (Windows) with NVIDIA's
CUDA 12 libraries, or compiled here with a CUDA 12.x toolkit (Linux, --build, or no ready-made one)."""
eng = None if build else get_prebuilt(url_base, gpu, vision, toolkit=12)
if eng is not None and json.loads((eng / "BUILD.json").read_text()).get("source") != "local":
pip_cuda_libs(12)
if vision != "none" and not (eng / VEXE).exists():
eng = None
return eng if eng is not None else build_engine(gpu, vision, yes, get_llama_cpp(), toolkit=12)
def engine_lib_dirs(eng: Path, toolkit=13) -> list:
"""The library folders a CUDA engine loads from: its own (a compiled one: the toolkit's), else pip's wheels."""
meta = json.loads((eng / "BUILD.json").read_text())
return meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs(toolkit)
def use_cuda12(cards, cfg_path: Path, cfg: dict, yes: bool) -> dict:
"""A model on the CUDA 13 engine now has a Pascal / Volta card (a --gpus at start): the model's config moves to
the experimental CUDA 12 engine (one engine per model; its other models keep theirs)."""
old = min(int(g["arch"]) for g in cards)
say()
warn(f"sm_{old} is older than CUDA 13 supports (it dropped Pascal and Volta): this model moves to the experimental "
"CUDA 12 engine (docs/OLDER_GPUS.md; START-HERE.bat --setup --cuda 13 and newer cards only moves it back)")
main = gpu_info(cards[0]["index"]) or cards[0]
vision = "gpu" if cfg.get("vision") else "none"
eng = get_cuda12_engine(os.environ.get("STRATA_PREBUILT_URL", PREBUILT_URL),
{**main, "archs": sorted({int(g["arch"]) for g in cards})}, vision, yes)
cfg["exe"] = str(eng / EXE)
cfg["cuda"] = 12
cfg["lib_dirs"] = engine_lib_dirs(eng, 12)
if cfg.get("vision") and (eng / VEXE).exists():
cfg["vision"]["exe"] = str(eng / VEXE)
write_config(cfg_path, cfg)
ok(f"engine: {eng / EXE} (CUDA 12, experimental)")
return cfg
def write_run_script(model, cfg_path, port, open_browser=True):
"""run-<model>.bat / .sh: the server with this config; `open_browser` False (#609: --no-browser) leaves --open out."""
serve = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path),
@@ -3312,6 +3474,10 @@ def main() -> int:
help="update the installed engine, Python packages and model settings as a start would, without "
"starting the model (UPDATE.bat / update.sh run it after a git pull)")
ap.add_argument("--build", action="store_true", help="compile the engine instead of using the ready-made one")
ap.add_argument("--cuda", choices=["12", "13", "auto"], default=os.environ.get("STRATA_CUDA") or None,
help="NVIDIA: the CUDA toolkit of this model's engine. auto (default): CUDA 13, the ready-made "
"engine; CUDA 12 (experimental) when a chosen card is older than CUDA 13 supports (Pascal, "
"Volta). 12 also runs with an older driver (Windows 528+, Linux 525+). docs/OLDER_GPUS.md")
ap.add_argument("--prebuilt", default=os.environ.get("STRATA_PREBUILT_URL", PREBUILT_URL),
help="where the ready-made engine is (a URL folder or a local folder)")
ap.add_argument("--check", action="store_true", help="only check this PC and exit")
@@ -3382,13 +3548,15 @@ def main() -> int:
a.port = a.port or ch["port"]
if a.vram_reserve_mib is None: # #493: an explicit reserve set up before
a.vram_reserve_mib = ch.get("vram_reserve_mib")
if a.cuda is None and ch.get("cuda") == 12: # the experimental CUDA 12 engine, as before
a.cuda = "12"
if isinstance(ch.get("gpu"), list): # a layer split: set up across the same cards again
a.gpus = a.gpus or ",".join(str(g) for g in ch["gpu"])
a.layer_split = a.layer_split or ch.get("layer_split")
else:
a.gpu = a.gpu if a.gpu is not None else ch.get("gpu")
a.yes = True
global GPU_PICK
global GPU_PICK, OLD_GPUS
# starting an installed model: --gpus 0,2 (or all) saves those cards for it and starts on them (it used to start
# on the first one alone unless given with --setup), --gpu N runs this start on one card; neither: the saved
# choice, and asked once when the PC has cards that could share the model
@@ -3431,8 +3599,14 @@ def main() -> int:
step(1, "checking your PC")
found = gpus()
amd = amd_gpus()
nv_ok = any(gpu_problem(g) is None for g in found)
amd_ok = [g for g in amd if amd_problem(g) is None]
# older NVIDIA GPUs (Pascal / Volta): the experimental CUDA 12 engine, when chosen (docs/OLDER_GPUS.md)
OLD_GPUS = OLD_GPUS or old_gpus_opt_in(found, named_gpus(a.gpu, a.gpus), a.cuda,
other=bool(amd_ok) or a.backend == "hip")
if OLD_GPUS and a.backend != "hip":
warn(f"older NVIDIA GPUs (Pascal / Volta) can be used ({OLD_GPUS}): experimental, through a second engine "
"built with CUDA 12 (docs/OLDER_GPUS.md)")
nv_ok = any(gpu_problem(g) is None for g in found)
hip = a.backend == "hip" or (a.backend is None and not nv_ok and bool(amd_ok))
if a.backend is None and nv_ok and amd_ok:
# both kinds of card: asked (a first run on such a PC used to take NVIDIA without mentioning the Radeon)
@@ -3446,6 +3620,7 @@ def main() -> int:
hip = ask("Which cards?", ["1", "2"], "1", a.yes or a.check) == "2"
if a.check and not hip:
say(f" (the AMD card: {'START-HERE.bat' if WIN else './setup.sh'} --backend hip)")
cuda_tk = 13 # NVIDIA: the toolkit of this model's engine (cuda_choice)
if hip: # AMD: compiled here; Windows: ready-made
if WIN and a.gpus:
fail("several AMD cards sharing one model (--gpus) is Linux-only for now", "use one card: --gpu N")
@@ -3493,9 +3668,15 @@ def main() -> int:
if multi:
ok("GPUs: " + " + ".join(gpu_name(x) for x in chosen) + " together (the model's layers are split across them)")
ok(f"GPU: {gpu['name']}, {gpu['vram_gb']:.1f} GB VRAM, compute capability {cc(gpu)}, driver {gpu['driver']}")
if driver_major(gpu) < MIN_DRIVER:
fail(f"the NVIDIA driver is too old ({gpu['driver']}; {MIN_DRIVER} or newer is needed)",
"update it with the NVIDIA App or from https://www.nvidia.com/drivers, restart, and run this again")
cuda_tk, why = cuda_choice(gpu["archs"], a.cuda) # one engine per model: its oldest card decides
if why:
(warn if cuda_tk == 13 or str(a.cuda) == "12" else ok)(f"CUDA {cuda_tk}: {why}")
min_driver = CUDA12_MIN_DRIVER if cuda_tk == 12 else MIN_DRIVER
if driver_major(gpu) < min_driver:
fail(f"the NVIDIA driver is too old ({gpu['driver']}; {min_driver} or newer is needed)",
"update it with the NVIDIA App or from https://www.nvidia.com/drivers, restart, and run this again" +
("" if cuda_tk == 12 else f" (or --cuda 12: the experimental CUDA 12 engine runs with driver "
f"{CUDA12_MIN_DRIVER} or newer, docs/OLDER_GPUS.md)"))
if gpu["vram_gb"] < 11:
warn("less than 12 GB of VRAM: Strata will run, but most experts stay on the CPU and it will be slow")
ram = ram_gb()
@@ -3804,21 +3985,22 @@ def main() -> int:
gpu = hip_card(eng, gpu, amd)
a.gpu = gpu["index"] if gpu["count"] > 1 else a.gpu
else:
eng = None if a.build or hip else get_prebuilt(a.prebuilt, gpu, vision)
eng = None if a.build or hip else get_prebuilt(a.prebuilt, gpu, vision, **({"toolkit": 12} if cuda_tk == 12
else {}))
if eng is not None and not hip and json.loads((eng / "BUILD.json").read_text()).get("source") != "local":
pip_install(CUDA_WHEELS, "NVIDIA CUDA libraries (cuBLAS, CUDA runtime; ~0.4 GB)")
pip_cuda_libs(cuda_tk)
if vision != "none" and not (eng / VEXE).exists():
warn("the ready-made engine has no image encoder: compiling it")
eng = None
else:
vision = prebuilt_vision(json.loads((eng / "BUILD.json").read_text()), gpu, vision)
if eng is None:
eng = build_engine_hip(gpu, llama, vision) if hip else build_engine(gpu, vision, a.yes, llama)
eng = build_engine_hip(gpu, llama, vision) if hip else build_engine(gpu, vision, a.yes, llama, toolkit=cuda_tk)
meta = json.loads((eng / "BUILD.json").read_text())
if hip and WIN: # the ready-made engine's rocm/bin, first on the engine's PATH
lib_dirs = [str(d) for d in hip_lib_dirs(eng)]
else:
lib_dirs = meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs()
lib_dirs = meta.get("lib_dirs") or meta.get("cuda_dirs") or cuda_lib_dirs(cuda_tk)
engine_ver = tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:3] if x.isdigit())
need_engine = MODELS[model].get("engine", UNSLOTH_ENGINE)
if budget is not None and engine_ver < need_engine: # checked before the 94-111 GB download
@@ -4018,6 +4200,8 @@ def main() -> int:
cfg = {"exe": str(eng / EXE), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"),
"model_name": f"{fam['name']}-{model.lower()}", "log": str(ROOT / f"strata-{tag.lower()}.log"),
"lib_dirs": lib_dirs, "port": port}
if cuda_tk == 12: # the experimental CUDA 12 engine (engine-cuda12/)
cfg["cuda"] = 12
if hip:
cfg["backend"] = "hip"
# the dense prompt GEMMs through hipBLASLt with kernels measured on this GPU generation (tools/hip; +40-60%
+12 -2
View File
@@ -212,7 +212,7 @@ std::string gpu_arch_problem(int ordinal) {
}
std::string device_code_error() {
#if defined(STRATA_USE_HIP)
#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)
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
@@ -263,7 +263,17 @@ DeviceInfo device_info(int ordinal) {
// supported arch is enforced by CMake; RUNNING on an older card is caught here, because a binary can be carried
// to a machine with an older card and would otherwise silently take whatever path the driver chose. The HIP
// backend checks the card against the architectures the binary was compiled for (and wave32).
#if defined(STRATA_USE_HIP)
#if defined(STRATA_HIP_GFX906)
// AMD gfx906 (the STRATA_HIP_GFX906 compat build, not STRATA_USE_HIP): the build targets one gfx arch
// (CMAKE_HIP_ARCHITECTURES, wave64); a card of another arch fails at the first kernel launch with
// hipErrorInvalidDeviceFunction. gcnArchName says which it is.
{
std::string arch(p.gcnArchName);
if (const size_t colon = arch.find(':'); colon != std::string::npos) arch.resize(colon);
d.arch = arch;
}
if (p.gcnArchName[0] != 0) d.name += std::string(" (") + p.gcnArchName + ")";
#elif defined(STRATA_USE_HIP)
d.arch = base_arch(p.gcnArchName);
if (const std::string why = arch_problem(p, ordinal); !why.empty()) throw CudaError(why, -1);
#else
+12 -6
View File
@@ -1,8 +1,14 @@
// src/core/expert_cache.cpp - R4's slot storage and residency table. Read the header first.
#include "strata/core/expert_cache.hpp"
// #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)
#define STRATA_EC_NO_VMM 1
#endif
#include <cuda_runtime.h>
#if !defined(STRATA_USE_HIP)
#if !defined(STRATA_EC_NO_VMM)
#include <cuda.h> // #533: the virtual memory management types (the functions come through the runtime's entry points)
#endif
@@ -148,7 +154,7 @@ ExpertCache::~ExpertCache() { close(); }
// ---- #533: the segmented arena (--vram-elastic). The driver API's virtual memory functions, looked up through the
// runtime (no link against the driver library): one address range for the whole arena, backed by physical segments,
// and the tail's segments unmapped / mapped again later. Nothing here runs unless a segment size was set.
#if !defined(STRATA_USE_HIP)
#if !defined(STRATA_EC_NO_VMM)
namespace {
struct Vmm {
CUresult (CUDAAPI* device_get)(CUdevice*, int) = nullptr;
@@ -227,7 +233,7 @@ bool map_segment(const Vmm& v, int dev, CUdeviceptr va, size_t bytes, unsigned l
#endif
bool ExpertCache::open_segmented(uint64_t want, std::string& err) {
#if defined(STRATA_USE_HIP)
#if defined(STRATA_EC_NO_VMM)
(void) want;
err = "ExpertCache: --vram-elastic (a segmented expert cache) is CUDA-only for now";
return false;
@@ -280,7 +286,7 @@ bool ExpertCache::open_segmented(uint64_t want, std::string& err) {
}
void ExpertCache::release_segmented() {
#if !defined(STRATA_USE_HIP)
#if !defined(STRATA_EC_NO_VMM)
const Vmm& v = vmm();
if (base_ != nullptr) cudaDeviceSynchronize();
const CUdeviceptr va = reinterpret_cast<CUdeviceptr>(base_);
@@ -318,7 +324,7 @@ bool ExpertCache::shrink(int64_t keep_bytes, std::string& err) {
err = "the expert cache is not segmented (the engine needs --vram-elastic)";
return false;
}
#if defined(STRATA_USE_HIP)
#if defined(STRATA_EC_NO_VMM)
(void) keep_bytes;
return false;
#else
@@ -352,7 +358,7 @@ bool ExpertCache::grow(int64_t want_bytes, std::string& err) {
err = "the expert cache is not segmented (the engine needs --vram-elastic)";
return false;
}
#if defined(STRATA_USE_HIP)
#if defined(STRATA_EC_NO_VMM)
(void) want_bytes;
return false;
#else
+28
View File
@@ -387,6 +387,34 @@ if (db != nullptr && g_publish_kernel) {
// write idempotent across replays of the same graph - a captured literal would ring the same number
// forever and the host would never see a change.
strata::kernels::doorbell_ring(db->d_seq, stream); } return true;}
// The verify window's routing: n tokens' logits in one BF16 projection and their top-k in one launch, each token
// bitwise what `moe_route` gives it (the projection is the same kernel per column, the top-k kernel is per token).
// Anything else (a native router, the canonical BF16 GEMVs, a doorbell) takes the per-token `moe_route`.
bool moe_route_window(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b,
const float* x, float* logits, int32_t* ids, float* weights, int n, void* stream, std::string& err) {
using namespace strata::kernels;
const bool batched = native_bf16_projections && !(native_router_enabled() && g.n_expert == 512 && k == 10) &&
!std::getenv("STRATA_ROUTE_PER_TOKEN");
if (!batched || n == 1) {
for (int t = 0; t < n; ++t) {
MoEBuffers mb = b;
mb.logits = logits + t * g.n_expert; mb.ids = ids + t * k; mb.weights = weights + t * k;
if (!moe_route(tables, g, layer, k, mb, x + t * g.n_embd, stream, err, nullptr)) return false;
}
return true;
}
const LayerView v(tables, layer);
const WeightRef* w_router = v.get("ffn_gate_inp.weight");
if (w_router == nullptr) { err = v.name("ffn_gate_inp.weight") + " is missing"; return false; }
if (std::getenv("STRATA_ROUTE_PROJ_PER_TOKEN"))
for (int t = 0; t < n; ++t)
bf16_gemv_fp32_mmvf(x + t * g.n_embd, (const uint16_t*) w_router->data, logits + t * g.n_expert, g.n_embd,
g.n_expert, stream);
else
bf16_gemv_fp32_mmvf_cols(x, (const uint16_t*) w_router->data, logits, g.n_embd, g.n_expert, n, stream);
router_top10(logits, n, (int) g.n_expert, (int) k, ids, weights, stream);
return true;
}
bool moe_shared(const WeightTable& tables, const ModelGeometry& g, int64_t layer, const MoEBuffers& b, const float* x, void* stream, std::string& err) { using namespace strata::kernels; const LayerView v(tables, layer); const WeightRef* w_ginp = v.get("ffn_gate_inp_shexp.weight"); const WeightRef* w_sgate = v.get("ffn_gate_shexp.weight"); const WeightRef* w_sup = v.get("ffn_up_shexp.weight"); const WeightRef* w_sdown = v.get("ffn_down_shexp.weight"); const char* missing = !w_ginp ? "ffn_gate_inp_shexp.weight" : !w_sgate ? "ffn_gate_shexp.weight" : !w_sup ? "ffn_up_shexp.weight" : !w_sdown ? "ffn_down_shexp.weight" : nullptr; if (missing) { err = v.name(missing) + " is missing"; return false; }
// ---- the shared expert. Its three weights are quantized, so they need their planes.
SForm f_gate, f_up, f_down; if (!sform_of(*w_sgate, f_gate, v.name("ffn_gate_shexp.weight"), err)) return false; if (!sform_of(*w_sup, f_up, v.name("ffn_up_shexp.weight"), err)) return false; if (!sform_of(*w_sdown, f_down, v.name("ffn_down_shexp.weight"), err)) return false; Planes p_gate, p_up, p_down; if (!plane_ptrs(*w_sgate, v.name("ffn_gate_shexp.weight"), p_gate, err)) return false; if (!plane_ptrs(*w_sup, v.name("ffn_up_shexp.weight"), p_up, err)) return false; if (!plane_ptrs(*w_sdown, v.name("ffn_down_shexp.weight"), p_down, err)) return false;
+2 -2
View File
@@ -452,7 +452,7 @@ LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std::
std::mutex err_mu;
std::string err;
const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
std::vector<wchar_t> wpath((size_t) std::max(wide, 1), L'\0');
std::vector<wchar_t> wpath((size_t) (std::max)(wide, 1), L'\0');
if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide);
auto worker = [&]() {
HANDLE h = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
@@ -520,7 +520,7 @@ bool experts_unbuffered(const std::vector<std::string>& files, uint64_t arena_by
uint64_t seed = (uint64_t) GetTickCount64() * 6364136223846793005ull + 1442695040888963407ull;
for (const std::string& f : files) {
const int wide = MultiByteToWideChar(CP_UTF8, 0, f.c_str(), -1, nullptr, 0);
std::vector<wchar_t> w((size_t) std::max(wide, 1), L'\0');
std::vector<wchar_t> w((size_t) (std::max)(wide, 1), L'\0');
if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, f.c_str(), -1, w.data(), wide);
HANDLE h = CreateFileW(w.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS,
nullptr);
+9
View File
@@ -801,6 +801,15 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
NE, n, cs);
native_router_top10_multi(logits_ + tb * NE, ids_ + tb * K, w_ + tb * K, n, cs);
} catch (const std::exception& e) { err = "verify router: " + std::string(e.what()); return false; }
#if defined(STRATA_HIP_GFX906)
} else if (dec_batch) {
// gfx906: the Coder's 256-expert router (the native router is 512 x 10 only) for the whole window in one
// multi-column BF16 projection and one top-k, bitwise the per-token calls (route_window_parity); ~3 ms
// of a ~55 ms verify window on 2x MI50. STRATA_ROUTE_PER_TOKEN=1: the per-token calls.
if (!moe_route_window(wt, g, l, K, ss.moe, mixed_ + tb * N, logits_ + tb * NE, ids_ + tb * K, w_ + tb * K, n,
cs, err))
return false;
#endif
} else
for (int t = tb; t < te; ++t) {
MoEBuffers mb = ss.moe;
+271
View File
@@ -712,7 +712,11 @@ int down_chunk(bool staged, int* tile_out) {
// the down kernel's outputs (lo, inject_out) are strictly per-token, so the chunk boundaries are safe, and
// the up kernel below still sees every token of the batch in one launch.
#if defined(__HIPCC__)
#if defined(STRATA_HIP_GFX906)
const bool small_tile = false; // gfx906: 64 KiB LDS, the 2560 tile as before (8 tokens slice into launches)
#else
const bool small_tile = true; // all eight tokens fit gfx1100's 64 KiB LDS at this tile
#endif
#else
int cc_maj = 0, cc_min = 0;
cudaDeviceGetAttribute(&cc_maj, cudaDevAttrComputeCapabilityMajor, dev);
@@ -759,10 +763,26 @@ int down_chunk(bool staged, int* tile_out) {
// many tokens as fit the card, the up projection; the profile's stamps after the norm and after the down projection.
// kHcPlain is the default read exactly as before (never main's opt-in STRATA_GR_V3 path, which fused_gr_read_multi
// takes first).
#if defined(STRATA_HIP_GFX906)
__global__ void __launch_bounds__(THREADS) gr_norm_fast_kernel(GrMulti m); // below, with the AMD fast path
__global__ void __launch_bounds__(THREADS) gr_up_fast_kernel(GrMulti m);
} // namespace
static bool gr_fast();
namespace {
#endif
void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long long* stamp_buf, int stamp_i0) {
const int n_tok = m.T;
#if defined(STRATA_HIP_GFX906)
// gfx906: the latency-hidden norm/up (STRATA_GR_FAST=0: off) - the same sums in the same order as the kernels
// they replace (gr_parity checks the multi-token read against single-token calls bitwise)
const bool fast = gr_fast();
if (variant >= kHcSplit) gr_norm_split_kernel<<<dim3((unsigned) n_tok, HC), THREADS, 0, st>>>(m);
else if (fast) gr_norm_fast_kernel<<<n_tok, THREADS, 0, st>>>(m);
else gr_norm_multi_kernel<<<n_tok, THREADS, 0, st>>>(m);
#else
if (variant >= kHcSplit) gr_norm_split_kernel<<<dim3((unsigned) n_tok, HC), THREADS, 0, st>>>(m);
else gr_norm_multi_kernel<<<n_tok, THREADS, 0, st>>>(m);
#endif
if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, (void*) st);
const bool staged = variant >= kHcStaged;
int tv = 2560;
@@ -796,6 +816,10 @@ void launch_multi(const GrMulti& m, int variant, cudaStream_t st, unsigned long
}
}
if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, (void*) st);
#if defined(STRATA_HIP_GFX906)
if (fast) gr_up_fast_kernel<<<UPM_BLOCKS, THREADS, 0, st>>>(m);
else
#endif
gr_up_multi_kernel<<<UPM_BLOCKS, THREADS, 0, st>>>(m);
}
@@ -811,8 +835,230 @@ int env_variant() {
// per device: the variant `fused_gr_check` chose (0 = not checked yet)
std::atomic<int> g_variant[64];
#if defined(STRATA_HIP_GFX906)
// ---- AMD fast path (STRATA_GR_FAST, default 1; 0 = the old kernels): the same arithmetic per value in the same order, latency
// hidden. gr_norm: one block per token (as before) but a thread's 10 float4 of R / bo / w_norm are loaded
// before any is used, and xn stays in registers until rs is known (was: store, then re-read the 40 KB).
// gr_up: a warp's 8 rows of w_up and their epilogue inputs are loaded before the dots (was: one row's load chain
// after another).
constexpr int NQ = D / (THREADS * 4); // 10 float4 per thread
static_assert(D % (THREADS * 4) == 0, "whole float4 per thread");
__global__ void __launch_bounds__(THREADS) gr_norm_fast_kernel(GrMulti m) {
__shared__ float part[WARPS][HC];
__shared__ float s_rs[HC];
const FusedGrArgs& a = m.a[blockIdx.x];
float* xn = m.xn + (size_t) blockIdx.x * D;
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
float gw[HC];
#pragma unroll
for (int c = 0; c < HC; ++c) gw[c] = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f;
float4 r[NQ], g[NQ];
#pragma unroll
for (int k = 0; k < NQ; ++k) {
const int i = t * 4 + k * THREADS * 4;
r[k] = *reinterpret_cast<const float4*>(a.R + i);
g[k] = *reinterpret_cast<const float4*>(a.w_norm + i);
}
if (a.apply) {
#pragma unroll
for (int k = 0; k < NQ; ++k) {
const int i = t * 4 + k * THREADS * 4, c = i / N, d = i - c * N;
const float4 b = *reinterpret_cast<const float4*>(a.bo_prev + d);
r[k].x = fmaf(b.x, gw[c], r[k].x); r[k].y = fmaf(b.y, gw[c], r[k].y);
r[k].z = fmaf(b.z, gw[c], r[k].z); r[k].w = fmaf(b.w, gw[c], r[k].w);
}
}
float ss[HC] = {0.0f, 0.0f, 0.0f, 0.0f};
#pragma unroll
for (int k = 0; k < NQ; ++k) {
const int i = t * 4 + k * THREADS * 4, c = i / N;
const float sq = r[k].x * r[k].x + r[k].y * r[k].y + r[k].z * r[k].z + r[k].w * r[k].w;
#pragma unroll
for (int cc = 0; cc < HC; ++cc) if (cc == c) ss[cc] += sq;
r[k] = make_float4(r[k].x * g[k].x, r[k].y * g[k].y, r[k].z * g[k].z, r[k].w * g[k].w);
}
#pragma unroll
for (int c = 0; c < HC; ++c) {
const float v = warp_sum(ss[c]);
if (lane == 0) part[warp][c] = v;
}
__syncthreads();
if (t < HC) {
float s = 0.0f;
for (int w = 0; w < WARPS; ++w) s += part[w][t];
s_rs[t] = rsqrtf(s / (float) N + a.eps);
a.rs[t] = s_rs[t];
}
__syncthreads();
#pragma unroll
for (int k = 0; k < NQ; ++k) {
const int i = t * 4 + k * THREADS * 4;
const float sr = s_rs[i / N];
*reinterpret_cast<float4*>(xn + i) = make_float4(r[k].x * sr, r[k].y * sr, r[k].z * sr, r[k].w * sr);
}
}
// gr_up: 8 lanes per row instead of a 32-lane warp. Lane j holds the old lanes j, j+8, j+16, j+24 (and chunk
// 32+j, the old lane j's second chunk): the xor tree's stages 16 and 8 are its own adds (a + b == b + a), stages
// 4, 2, 1 are shuffles inside the 8 - the same tree, bitwise the same sum, 3 shuffles a token instead of 5 and no
// idle lanes on the tail chunks. A block's 64 rows are 2 passes of 32 groups, their weights loaded up front.
__device__ __forceinline__ float xor8(float v) {
#pragma unroll
for (int o = 4; o > 0; o >>= 1) v += __shfl_xor(v, o, 64);
return v;
}
__global__ void __launch_bounds__(THREADS) gr_up_fast_kernel(GrMulti m) {
__shared__ __align__(16) float lo[kFusedGrMaxT][LR];
__shared__ float g[kFusedGrMaxT][HC][UPM_COLS];
const int t = threadIdx.x, j = t & 7, grp = t >> 3;
const int T = m.T;
const int d0 = blockIdx.x * UPM_COLS;
static_assert(LR == 40 * 8 && HC * UPM_COLS == 64 && THREADS == 256, "geometry");
uint4 w[2][5];
float rv[2] = {0.0f, 0.0f}, wn[2] = {0.0f, 0.0f}, rsc[2] = {0.0f, 0.0f}, bo[2] = {0.0f, 0.0f}, ip[2] = {0.0f, 0.0f};
const bool apply = j < T && m.a[j < T ? j : 0].apply;
#pragma unroll
for (int p = 0; p < 2; ++p) {
const int r = grp + 32 * p, c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd;
const uint4* w4 = reinterpret_cast<const uint4*>(m.a[0].w_up + (size_t) i * LR);
#pragma unroll
for (int q = 0; q < 4; ++q) w[p][q] = __ldg(w4 + j + 8 * q);
w[p][4] = __ldg(w4 + 32 + j);
if (j < T) {
const FusedGrArgs& a = m.a[j];
rv[p] = a.R[i];
wn[p] = a.w_norm[i];
rsc[p] = a.rs[c];
if (apply) { bo[p] = a.bo_prev[d0 + dd]; ip[p] = a.inj_prev[c]; }
}
}
for (int i = t; i < T * LR; i += THREADS) lo[i / LR][i % LR] = m.a[i / LR].lo[i % LR];
__syncthreads();
#pragma unroll
for (int p = 0; p < 2; ++p) {
const int r = grp + 32 * p, c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd;
float mine = 0.0f;
#pragma unroll
for (int k = 0; k < kFusedGrMaxT; ++k) {
if (k >= T) break;
const float* l = lo[k];
const float p0 = dot8(w[p][0], l + j * 8) + dot8(w[p][4], l + (32 + j) * 8); // old lane j
const float p1 = dot8(w[p][1], l + (j + 8) * 8); // old lane j + 8
const float p2 = dot8(w[p][2], l + (j + 16) * 8); // old lane j + 16
const float p3 = dot8(w[p][3], l + (j + 24) * 8); // old lane j + 24
const float s = xor8((p0 + p2) + (p1 + p3)); // stage 16: (j, j+16), (j+8, j+24); stage 8; then 4, 2, 1
if (j == k) mine = s;
}
if (j < T) {
float x0 = rv[p];
if (apply) {
x0 = fmaf(bo[p], 2.0f * sigmoidf_(ip[p] / (float) HC), x0);
m.a[j].R_out[i] = x0;
}
const float x = x0 * wn[p] * rsc[p];
g[j][c][dd] = x * sigmoidf_(mine);
}
}
__syncthreads();
for (int i = t; i < T * UPM_COLS; i += THREADS) {
const int k = i / UPM_COLS, col = i - k * UPM_COLS;
float s = 0.0f;
#pragma unroll
for (int c = 0; c < HC; ++c) s += g[k][c][col];
m.a[k].mixed[d0 + col] = s / (float) HC;
}
}
#endif
#if defined(STRATA_HIP_GFX906)
// ---- AMD: `gr_down_multi` split along K. The CUDA kernel is one warp per row of w_down (320 + 4 rows), 41
// blocks: on a 60-CU gfx906 that left most of the card idle and read the 6.5 MB matrix at ~100 GB/s. Here a block
// is 8 wavefronts = 8 rows of one K-slice of 2048 (the slice of every token's xn staged in LDS once), 41 x 5
// blocks, and a second kernel adds the 5 slice sums in a fixed order and runs the epilogue. A token's result does
// not depend on how many tokens share the window (each column is reduced on its own).
constexpr int GS_SL = 2048; // K per slice
constexpr int GS_S = D / GS_SL; // 5 slices
constexpr int GS_ROWS = LR + HC; // 324: the down rows, then the inject rows
constexpr int GS_WAVES = 8;
static_assert(D % GS_SL == 0 && GS_SL == 64 * 8 * 4, "a lane takes 4 chunks of 8 per slice");
// the slice sums: a module-scope device array is per device by construction, and needs no allocation during a
// graph capture
__device__ float g_gr_part[GS_S * kFusedGrMaxT * GS_ROWS];
__global__ void __launch_bounds__(GS_WAVES * 64) gr_down_split_kernel(GrMulti m) {
float* part = g_gr_part;
extern __shared__ __align__(16) float tile[]; // [T][GS_SL]
const int t = threadIdx.x, lane = t & 63, wave = t >> 6;
const int T = m.T, sl = blockIdx.y;
const bool inject_block = blockIdx.x == DOWN_BLOCKS;
const int row = inject_block ? wave : blockIdx.x * GS_WAVES + wave;
const bool active = !(inject_block && (m.a[0].w_inject == nullptr || wave >= HC));
const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? row : 0) * D;
const uint4* w4 = reinterpret_cast<const uint4*>(wrow) + sl * (GS_SL / 8);
uint4 wv[4];
if (active) {
#pragma unroll
for (int q = 0; q < 4; ++q) wv[q] = __ldg(w4 + lane + 64 * q);
}
const float4* src4 = reinterpret_cast<const float4*>(m.xn);
float4* tile4 = reinterpret_cast<float4*>(tile);
for (int i = t; i < T * (GS_SL / 4); i += GS_WAVES * 64) {
const int k = i / (GS_SL / 4), off = i - k * (GS_SL / 4);
tile4[i] = src4[((size_t) k * D + (size_t) sl * GS_SL) / 4 + off];
}
__syncthreads();
if (!active) return;
float acc[kFusedGrMaxT];
#pragma unroll
for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f;
#pragma unroll
for (int q = 0; q < 4; ++q) {
const int j = lane + 64 * q;
#pragma unroll
for (int k = 0; k < kFusedGrMaxT; ++k)
if (k < T) acc[k] += dot8(wv[q], tile + k * GS_SL + j * 8);
}
#pragma unroll
for (int k = 0; k < kFusedGrMaxT; ++k) {
if (k >= T) break;
float v = acc[k];
#pragma unroll
for (int off = 32; off > 0; off >>= 1) v += __shfl_xor(v, off, 64);
if (lane == 0) part[((size_t) sl * kFusedGrMaxT + k) * GS_ROWS + (inject_block ? LR + row : row)] = v;
}
}
__global__ void gr_down_finish_kernel(GrMulti m) {
const float* part = g_gr_part;
const int i = blockIdx.x * blockDim.x + threadIdx.x;
const int k = i / GS_ROWS, r = i - k * GS_ROWS;
if (k >= m.T) return;
const bool inject = r >= LR;
if (inject && m.a[0].w_inject == nullptr) return;
float s = 0.0f;
#pragma unroll
for (int sl = 0; sl < GS_S; ++sl) s += part[((size_t) sl * kFusedGrMaxT + k) * GS_ROWS + r];
if (inject) {
m.a[k].inject_out[r - LR] = s;
} else {
const float x = s / (float) HC;
m.a[k].lo[r] = x / (1.0f + __expf(-x));
}
}
#endif
} // namespace
#if defined(STRATA_HIP_GFX906)
int g_gr_fast = -1; // fused_gr_set_fast (the bench); -1 = STRATA_GR_FAST
static bool gr_fast() {
static const bool env = [] { const char* v = std::getenv("STRATA_GR_FAST"); return v ? std::atoi(v) != 0 : true; }();
return g_gr_fast >= 0 ? g_gr_fast != 0 : env;
}
#else
int g_gr_fast = -1;
#endif
void fused_gr_set_fast(int on) { g_gr_fast = on; }
void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf,
int stamp_i0) {
if (n_tok < 1 || n_tok > kFusedGrMaxT || xn_scratch == nullptr) {
@@ -875,6 +1121,31 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi
}
return;
}
#if defined(STRATA_HIP_GFX906)
// gfx906, opt-in STRATA_GR_SPLIT=1: the latency-hidden norm/up (STRATA_GR_FAST) with the K-split down (~3% faster
// per verify window). Its fixed-order finish sums the K slices in another order than the single-token
// fused_gr_read, so the multi-token read is then no longer bitwise equal to T single-token calls (gr_parity's
// contract); off by default for that reason.
static const bool split_on = std::getenv("STRATA_GR_SPLIT") && std::string(std::getenv("STRATA_GR_SPLIT")) == "1";
if (split_on) {
const bool fast = gr_fast();
if (fast) gr_norm_fast_kernel<<<n_tok, THREADS, 0, st>>>(m);
else gr_norm_multi_kernel<<<n_tok, THREADS, 0, st>>>(m);
if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, stream);
gr_down_split_kernel<<<dim3(DOWN_BLOCKS + 1, GS_S), GS_WAVES * 64, (size_t) n_tok * GS_SL * sizeof(float), st>>>(
m);
gr_down_finish_kernel<<<(unsigned) ((n_tok * GS_ROWS + 255) / 256), 256, 0, st>>>(m);
if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, stream);
if (fast) gr_up_fast_kernel<<<UPM_BLOCKS, THREADS, 0, st>>>(m);
else gr_up_multi_kernel<<<UPM_BLOCKS, THREADS, 0, st>>>(m);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "fused_gr_read_multi: %s\n", cudaGetErrorString(e));
std::exit(1);
}
return;
}
#endif
// the default read (STRATA_GR_V3 unset): v1, or the bitwise-equal v2 / v3 this card's check accepted
launch_multi(m, fused_gr_variant(), st, stamp_buf, stamp_i0);
const cudaError_t e = cudaGetLastError();
+666 -1
View File
@@ -17,6 +17,7 @@
#include <cstdio>
#include <cstdlib>
#include <type_traits>
namespace strata::kernels {
namespace {
@@ -40,6 +41,18 @@ __device__ __forceinline__ uint32_t unpack_ksigns(const uint8_t v) {
return s * 0x01010101;
}
__device__ __forceinline__ int2 get_int_from_table_16(const int& q4, const int8_t* table) {
#if defined(STRATA_HIP_GFX906)
// AMD: llama.cpp's HIP lookup (vecdotq.cuh) - v_perm_b32 takes 3-bit byte indices, so the low and high halves
// of the table are looked up and the index MSB picks between them: 4 perms per 8 values.
const uint32_t* v32 = reinterpret_cast<const uint32_t*>(table);
const uint32_t q_even = (uint32_t) q4, q_odd = (uint32_t) q4 >> 4;
const uint32_t el = __builtin_amdgcn_perm(v32[1], v32[0], q_even & 0x07070707u);
const uint32_t ol = __builtin_amdgcn_perm(v32[1], v32[0], q_odd & 0x07070707u);
const uint32_t eh = __builtin_amdgcn_perm(v32[3], v32[2], q_even & 0x07070707u);
const uint32_t oh = __builtin_amdgcn_perm(v32[3], v32[2], q_odd & 0x07070707u);
return make_int2((int) __builtin_amdgcn_perm(eh, el, 0x03020100u | ((q_even & 0x08080808u) >> 1)),
(int) __builtin_amdgcn_perm(oh, ol, 0x03020100u | ((q_odd & 0x08080808u) >> 1)));
#else
const uint32_t* table32 = (const uint32_t*) table;
uint32_t tmp[2];
const uint32_t low_high_selection_indices = (0x32103210 | ((q4 & 0x88888888) >> 1));
@@ -51,6 +64,7 @@ __device__ __forceinline__ int2 get_int_from_table_16(const int& q4, const int8_
tmp[i] = __byte_perm(low, high, low_high_selection_indices >> shift);
}
return make_int2(__byte_perm(tmp[0], tmp[1], 0x6420), __byte_perm(tmp[0], tmp[1], 0x7531));
#endif
}
#define ggml_cuda_dp4a(a, b, c) STRATA_DP4A((a), (b), (c))
@@ -1212,6 +1226,16 @@ __device__ void dq_q2_0(const void* vx, int64_t ibs, dst_t* yy, int tid) {
for (int j = 0; j < 8; ++j) {
const int i = part * 8 + j;
const int code = (x[b].qs[i / 4] >> ((i % 4) * 2)) & 3;
#if defined(__HIPCC__) && defined(__gfx1012__) && HIP_VERSION_MAJOR < 7
// HIP 5.7 on RDNA1 folds the half path's negative scale times +0
// to +0. Preserve the scale's sign, as the FP32/CPU paths do.
if constexpr (std::is_same_v<dst_t, __half>) {
if (code == 1) {
yy[b * 64 + i] = __ushort_as_half(__half_as_ushort(x[b].d) & 0x8000u);
continue;
}
}
#endif
yy[b * 64 + i] = cvt<dst_t>(d * (float) (code - 1));
}
}
@@ -1533,6 +1557,560 @@ size_t native_expert_scratch_bytes(int64_t cap, int64_t n_ff) {
return 3 * ((f + 255) & ~(size_t) 255) + (((size_t) cap * (size_t) (n_ff / 32) * sizeof(block_q8_1) + 255) & ~(size_t) 255);
}
#if defined(STRATA_HIP_GFX906)
// ---- AMD layouts for the grouped native experts (STRATA_EXP_MODE; 0 = the CUDA one above).
// 1 (W64): a row per 64-lane wavefront - 4x the wavefronts, ~1-2 calls per lane, a 64-lane butterfly.
// 2 (R2): a 32-lane logical warp computes TWO rows in one loop - two independent load chains in flight.
// Either way a (row, entry) sum does not depend on the window size.
template<int TY>
__device__ __forceinline__ float row_dot64(const uint8_t* row, const block_q8_1* x, int nb, int lane) {
using F = Fmt<TY>;
float s = 0.0f;
for (int k = lane; k < nb * F::ipb; k += 64) {
const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
s += F::dot(row, x + kbx * (F::qk / 32), kbx, iqs);
}
#pragma unroll
for (int o = 32; o > 0; o >>= 1) s += __shfl_xor(s, o, 64);
return s;
}
template<int TY>
__device__ __forceinline__ void row_dot2(const uint8_t* r0, const uint8_t* r1, const block_q8_1* x, int nb, int lane,
float& o0, float& o1) {
using F = Fmt<TY>;
float s0 = 0.0f, s1 = 0.0f;
for (int k = lane; k < nb * F::ipb; k += 32) {
const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
const block_q8_1* xk = x + kbx * (F::qk / 32);
const float a = F::dot(r0, xk, kbx, iqs);
const float b = F::dot(r1, xk, kbx, iqs);
s0 += a;
s1 += b;
}
o0 = warp_sum(s0);
o1 = warp_sum(s1);
}
template<int TY, int NR>
__device__ __forceinline__ void row_dotn(const uint8_t* const* r, const block_q8_1* x, int nb, int lane, float* o) {
using F = Fmt<TY>;
float acc[NR];
#pragma unroll
for (int i = 0; i < NR; ++i) acc[i] = 0.0f;
for (int k = lane; k < nb * F::ipb; k += 32) {
const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
const block_q8_1* xk = x + kbx * (F::qk / 32);
float d[NR];
#pragma unroll
for (int i = 0; i < NR; ++i) d[i] = F::dot(r[i], xk, kbx, iqs);
#pragma unroll
for (int i = 0; i < NR; ++i) acc[i] += d[i];
}
#pragma unroll
for (int i = 0; i < NR; ++i) o[i] = warp_sum(acc[i]);
}
template<int TG, int MODE>
__global__ void __launch_bounds__(256) native_gu_amd_kernel(const unsigned long long* __restrict__ grp_ptr,
const int32_t* __restrict__ grp_start,
const int32_t* __restrict__ n_groups,
const int32_t* __restrict__ ent_tok,
const block_q8_1* __restrict__ xq, NativeExpertLayout L,
float* __restrict__ gate, float* __restrict__ up) {
const int g = blockIdx.y;
if (g >= *n_groups) return;
const uint8_t* blob = (const uint8_t*) grp_ptr[g];
const int nb = (int) (L.n_embd / Fmt<TG>::qk), xb = (int) (L.n_embd / 32);
const int e0 = grp_start[g], e1 = grp_start[g + 1];
const int nrow = 2 * (int) L.n_ff;
auto wrow = [&](int row) -> const uint8_t* {
const bool is_up = row >= L.n_ff;
return blob + (is_up ? L.up_off : 0) + (size_t) (is_up ? row - (int) L.n_ff : row) * L.gu_row;
};
auto put = [&](int row, int e, float v) {
const bool is_up = row >= L.n_ff;
(is_up ? up : gate)[(size_t) e * L.n_ff + (is_up ? row - (int) L.n_ff : row)] = v;
};
if constexpr (MODE == 1) {
const int lane = threadIdx.x & 63, row = blockIdx.x * 4 + (threadIdx.x >> 6);
if (row >= nrow) return;
const uint8_t* wr = wrow(row);
for (int e = e0; e < e1; ++e) {
const float v = row_dot64<TG>(wr, xq + (size_t) ent_tok[e] * xb, nb, lane);
if (lane == 0) put(row, e, v);
}
} else if constexpr (MODE == 4) {
const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
const int row0 = blockIdx.x * 32 + warp;
if (row0 >= nrow) return;
const uint8_t* w[4];
#pragma unroll
for (int i = 0; i < 4; ++i) w[i] = wrow(row0 + 8 * i < nrow ? row0 + 8 * i : row0);
for (int e = e0; e < e1; ++e) {
float o[4];
row_dotn<TG, 4>(w, xq + (size_t) ent_tok[e] * xb, nb, lane, o);
if (lane == 0)
#pragma unroll
for (int i = 0; i < 4; ++i) if (row0 + 8 * i < nrow) put(row0 + 8 * i, e, o[i]);
}
} else {
const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
const int row0 = blockIdx.x * 16 + warp, row1 = row0 + 8;
if (row0 >= nrow) return;
const bool two = row1 < nrow;
const uint8_t* w0 = wrow(row0);
const uint8_t* w1 = wrow(two ? row1 : row0);
for (int e = e0; e < e1; ++e) {
float a, b;
row_dot2<TG>(w0, w1, xq + (size_t) ent_tok[e] * xb, nb, lane, a, b);
if (lane == 0) { put(row0, e, a); if (two) put(row1, e, b); }
}
}
}
template<int TD, int MODE>
__global__ void __launch_bounds__(256) native_down_amd_kernel(const unsigned long long* __restrict__ grp_ptr,
const int32_t* __restrict__ grp_start,
const int32_t* __restrict__ n_groups,
const int32_t* __restrict__ ent_dst,
const block_q8_1* __restrict__ hq, NativeExpertLayout L,
float* __restrict__ out) {
const int g = blockIdx.y;
if (g >= *n_groups) return;
const uint8_t* blob = (const uint8_t*) grp_ptr[g];
const int nb = (int) (L.n_ff / Fmt<TD>::qk), hb = (int) (L.n_ff / 32);
const int e0 = grp_start[g], e1 = grp_start[g + 1];
const int nrow = (int) L.n_embd;
if constexpr (MODE == 1) {
const int lane = threadIdx.x & 63, r = blockIdx.x * 4 + (threadIdx.x >> 6);
if (r >= nrow) return;
const uint8_t* wr = blob + L.down_off + (size_t) r * L.d_row;
for (int e = e0; e < e1; ++e) {
const float v = row_dot64<TD>(wr, hq + (size_t) e * hb, nb, lane);
if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = v;
}
} else if constexpr (MODE == 4) {
const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
const int r0 = blockIdx.x * 32 + warp;
if (r0 >= nrow) return;
const uint8_t* w[4];
#pragma unroll
for (int i = 0; i < 4; ++i) w[i] = blob + L.down_off + (size_t) (r0 + 8 * i < nrow ? r0 + 8 * i : r0) * L.d_row;
for (int e = e0; e < e1; ++e) {
float o[4];
row_dotn<TD, 4>(w, hq + (size_t) e * hb, nb, lane, o);
if (lane == 0)
#pragma unroll
for (int i = 0; i < 4; ++i) if (r0 + 8 * i < nrow) out[(size_t) ent_dst[e] * L.n_embd + r0 + 8 * i] = o[i];
}
} else {
const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
const int r0 = blockIdx.x * 16 + warp, r1 = r0 + 8;
if (r0 >= nrow) return;
const bool two = r1 < nrow;
const uint8_t* w0 = blob + L.down_off + (size_t) r0 * L.d_row;
const uint8_t* w1 = blob + L.down_off + (size_t) (two ? r1 : r0) * L.d_row;
for (int e = e0; e < e1; ++e) {
float a, b;
row_dot2<TD>(w0, w1, hq + (size_t) e * hb, nb, lane, a, b);
if (lane == 0) {
out[(size_t) ent_dst[e] * L.n_embd + r0] = a;
if (two) out[(size_t) ent_dst[e] * L.n_embd + r1] = b;
}
}
}
}
// ---- 5 (LDS): gate/up of the grid formats (IQ2_S, IQ3_XXS, IQ3_S) with the codebook grid and the group's q8_1
// activations in LDS. The bench showed gate/up compute-bound, not bandwidth-bound (T = 2 costs ~1.8x T = 1 on the
// same weights, 110-130 GB/s): each call issues its grid lookups and eight activation loads through the vector
// memory path after the weight load. Same calls, same lane-strided k, same R2 row pairs, same warp_sum: the
// output is bitwise the mode-2 one.
template<int TY> struct GridOf;
template<> struct GridOf<22> { using T = uint64_t; static constexpr int N = 1024; __device__ static const T* src() { return iq2s_grid; } };
template<> struct GridOf<18> { using T = uint32_t; static constexpr int N = 256; __device__ static const T* src() { return iq3xxs_grid; } };
template<> struct GridOf<21> { using T = uint32_t; static constexpr int N = 512; __device__ static const T* src() { return iq3s_grid; } };
template<> struct GridOf<23> { using T = uint32_t; static constexpr int N = 1; __device__ static const T* src() { return iq3s_grid; } }; // IQ4_XS: no grid
// SG = 1 (mode 6): the signs without byte-SIMD ops, which gfx906 lacks (strata_vcmpne4 / strata_vsub4 unpack to
// ~12 word ops each). m = the sign nibble as 0x00/0xff bytes; (g ^ m) is g or -g-1 per byte, so
// dp4a(g ^ m, u) - dp4a(m, u) = sum(s g u) exactly - the same integers, the same floats.
__device__ __forceinline__ int nib_mask(uint32_t n) {
const uint32_t b = __umul24(n & 0xFu, 0x204081u) & 0x01010101u;
return (int) ((b << 8) - b);
}
template<int TY, int SG> struct DotG;
template<int SG> struct DotG<22, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,
const uint64_t* grid) {
const block_iq2_s* bq2 = (const block_iq2_s*) vbq + kbx;
const int qs_packed = get_int_b2(bq2->qs, iqs / 2);
const uint8_t* qs = (const uint8_t*) &qs_packed;
const int qh = bq2->qh[iqs / 2];
const int signs_packed_32 = get_int_b2(bq2->qs, QK_K / 32 + iqs / 2);
const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
const int ls0 = bq2->scales[iqs / 2] & 0x0F;
const int ls1 = bq2->scales[iqs / 2] >> 4;
int sumi0 = 0, sumi1 = 0;
#pragma unroll
for (int l0 = 0; l0 < 8; l0 += 2) {
const int* grid_pos = (const int*) (grid + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300)));
const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
int& acc = l0 < 4 ? sumi0 : sumi1;
if constexpr (SG == 1) {
const int m0 = nib_mask(signs_packed_8[l0 / 2]), m1 = nib_mask(signs_packed_8[l0 / 2] >> 4);
acc = ggml_cuda_dp4a(grid_pos[0] ^ m0, u0, acc);
acc = ggml_cuda_dp4a(grid_pos[1] ^ m1, u1, acc);
acc -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0));
} else {
const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000);
const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000);
const int grid_l = __vsub4(grid_pos[0] ^ signs0, signs0);
const int grid_h = __vsub4(grid_pos[1] ^ signs1, signs1);
acc = ggml_cuda_dp4a(grid_l, u0, acc);
acc = ggml_cuda_dp4a(grid_h, u1, acc);
}
}
const int sumi = (sumi0 * ls0 + sumi1 * ls1 + (sumi0 + sumi1) / 2) / 4;
const float d = __half2float(bq2->d) * __low2float(bq8_1[iqs / 2].ds);
return d * sumi;
} };
template<int SG> struct DotG<18, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,
const uint32_t* grid) {
const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx;
const int2 q3_packed = make_int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1));
const uint8_t* q3 = (const uint8_t*) &q3_packed;
const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2);
int sumi = 0;
#pragma unroll
for (int l0 = 0; l0 < 8; l0 += 2) {
const int2 grid_pos = make_int2(grid[q3[l0 + 0]], grid[q3[l0 + 1]]);
const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2));
const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
if constexpr (SG == 1) {
const int m0 = nib_mask(signs), m1 = nib_mask(signs >> 4);
sumi = ggml_cuda_dp4a(grid_pos.x ^ m0, u0, sumi);
sumi = ggml_cuda_dp4a(grid_pos.y ^ m1, u1, sumi);
sumi -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0));
} else {
const int signs0 = __vcmpne4(signs & 0x08040201, 0);
const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0);
const int signs1 = __vcmpne4(signs & 0x80402010, 0);
const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1);
sumi = ggml_cuda_dp4a(grid_l, u0, sumi);
sumi = ggml_cuda_dp4a(grid_h, u1, sumi);
}
}
const int ls = aux32 >> 28;
sumi = (ls * sumi + sumi / 2) / 2;
const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds);
return d * sumi;
} };
template<int SG> struct DotG<21, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,
const uint32_t* grid) {
const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx;
const int2 qs_packed = make_int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1));
const uint8_t* qs = (const uint8_t*) &qs_packed;
const int qh = bq3->qh[iqs / 2];
const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2);
const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
int sumi = 0;
#pragma unroll
for (int l0 = 0; l0 < 8; l0 += 2) {
const int2 grid_pos = make_int2(grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)],
grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]);
const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
if constexpr (SG == 1) {
const int m0 = nib_mask(signs_packed_8[l0 / 2]), m1 = nib_mask(signs_packed_8[l0 / 2] >> 4);
sumi = ggml_cuda_dp4a(grid_pos.x ^ m0, u0, sumi);
sumi = ggml_cuda_dp4a(grid_pos.y ^ m1, u1, sumi);
sumi -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0));
} else {
const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000);
const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000);
const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0);
const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1);
sumi = ggml_cuda_dp4a(grid_l, u0, sumi);
sumi = ggml_cuda_dp4a(grid_h, u1, sumi);
}
}
sumi *= 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F);
const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds);
return d * sumi;
} };
template<int SG> struct DotG<23, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,
const uint32_t*) { return vec_dot_iq4_xs_q8_1(vbq, bq8_1, kbx, iqs); } };
constexpr int LDS_RB = 64; // gate/up rows per block (4 R2 passes of 16)
constexpr int LDS_NT = 4; // entries whose activations sit in LDS at once
template<int TG, int SG, bool TI = false>
__global__ void __launch_bounds__(256) native_gu_lds_kernel(const unsigned long long* __restrict__ grp_ptr,
const int32_t* __restrict__ grp_start,
const int32_t* __restrict__ n_groups,
const int32_t* __restrict__ ent_tok,
const block_q8_1* __restrict__ xq, NativeExpertLayout L,
float* __restrict__ gate, float* __restrict__ up) {
using GT = typename GridOf<TG>::T;
using F = Fmt<TG>;
__shared__ GT sgrid[GridOf<TG>::N];
extern __shared__ int sx_raw[]; // LDS_NT tokens x xb blocks of q8_1 (36 bytes = 9 ints each)
const int g = blockIdx.y;
if (g >= *n_groups) return; // uniform over the block
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
const GT* gsrc = GridOf<TG>::src();
for (int i = tid; i < GridOf<TG>::N; i += 256) sgrid[i] = gsrc[i];
const uint8_t* blob = (const uint8_t*) grp_ptr[g];
const int nb = (int) (L.n_embd / F::qk), xb = (int) (L.n_embd / 32);
const int e0 = grp_start[g], e1 = grp_start[g + 1];
const int nrow = 2 * (int) L.n_ff;
const block_q8_1* sx = (const block_q8_1*) sx_raw;
auto wrow = [&](int row) -> const uint8_t* {
const bool is_up = row >= L.n_ff;
return blob + (is_up ? L.up_off : 0) + (size_t) (is_up ? row - (int) L.n_ff : row) * L.gu_row;
};
auto put = [&](int row, int e, float v) {
const bool is_up = row >= L.n_ff;
(is_up ? up : gate)[(size_t) e * L.n_ff + (is_up ? row - (int) L.n_ff : row)] = v;
};
for (int c0 = e0; c0 < e1; c0 += LDS_NT) {
const int cn = min(LDS_NT, e1 - c0);
__syncthreads();
for (int j = 0; j < cn; ++j) {
const int* src = (const int*) (xq + (size_t) ent_tok[c0 + j] * xb);
for (int i = tid; i < xb * 9; i += 256) sx_raw[j * xb * 9 + i] = src[i];
}
__syncthreads();
for (int p = 0; p < LDS_RB / 16; ++p) {
const int row0 = blockIdx.x * LDS_RB + p * 16 + warp, row1 = row0 + 8;
if (row0 >= nrow) break;
const bool two = row1 < nrow;
const uint8_t* w0 = wrow(row0);
const uint8_t* w1 = wrow(two ? row1 : row0);
if constexpr (TI) { // mode 7: the tokens inside the k loop - one weight load per k for all of them
auto pass = [&](auto ntc) {
constexpr int NTC = decltype(ntc)::value;
float s0[NTC], s1[NTC];
#pragma unroll
for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; }
for (int k = lane; k < nb * F::ipb; k += 32) {
const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
#pragma unroll
for (int j = 0; j < NTC; ++j) {
const block_q8_1* xk = sx + (size_t) j * xb + kbx * (F::qk / 32);
const float a = DotG<TG, SG>::f(w0, xk, kbx, iqs, sgrid);
const float b = DotG<TG, SG>::f(w1, xk, kbx, iqs, sgrid);
s0[j] += a;
s1[j] += b;
}
}
#pragma unroll
for (int j = 0; j < NTC; ++j) {
const float a = warp_sum(s0[j]), b = warp_sum(s1[j]);
if (lane == 0) { put(row0, c0 + j, a); if (two) put(row1, c0 + j, b); }
}
};
switch (cn) {
case 1: pass(std::integral_constant<int, 1>{}); break;
case 2: pass(std::integral_constant<int, 2>{}); break;
case 3: pass(std::integral_constant<int, 3>{}); break;
default: pass(std::integral_constant<int, 4>{}); break;
}
continue;
}
for (int j = 0; j < cn; ++j) {
const block_q8_1* x = sx + (size_t) j * xb;
float s0 = 0.0f, s1 = 0.0f;
for (int k = lane; k < nb * F::ipb; k += 32) {
const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
const block_q8_1* xk = x + kbx * (F::qk / 32);
const float a = DotG<TG, SG>::f(w0, xk, kbx, iqs, sgrid);
const float b = DotG<TG, SG>::f(w1, xk, kbx, iqs, sgrid);
s0 += a;
s1 += b;
}
s0 = warp_sum(s0);
s1 = warp_sum(s1);
if (lane == 0) { put(row0, c0 + j, s0); if (two) put(row1, c0 + j, s1); }
}
}
}
}
// ---- 7 (down): the group's q8_1 h rows in LDS, the tokens inside the k loop, the R2 row pairs of mode 2 -
// the same per-(row, entry) sums in the same order: bitwise the mode-2 output.
template<int TD>
__global__ void __launch_bounds__(256) native_down_lds_kernel(const unsigned long long* __restrict__ grp_ptr,
const int32_t* __restrict__ grp_start,
const int32_t* __restrict__ n_groups,
const int32_t* __restrict__ ent_dst,
const block_q8_1* __restrict__ hq, NativeExpertLayout L,
float* __restrict__ out) {
using F = Fmt<TD>;
extern __shared__ int sh_raw[]; // LDS_NT entries x hb blocks of q8_1
const int g = blockIdx.y;
if (g >= *n_groups) return;
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
const uint8_t* blob = (const uint8_t*) grp_ptr[g];
const int nb = (int) (L.n_ff / F::qk), hb = (int) (L.n_ff / 32);
const int e0 = grp_start[g], e1 = grp_start[g + 1];
const int nrow = (int) L.n_embd;
const block_q8_1* sh = (const block_q8_1*) sh_raw;
for (int c0 = e0; c0 < e1; c0 += LDS_NT) {
const int cn = min(LDS_NT, e1 - c0);
__syncthreads();
{
const int* src = (const int*) (hq + (size_t) c0 * hb); // the chunk's entries are contiguous
for (int i = tid; i < cn * hb * 9; i += 256) sh_raw[i] = src[i];
}
__syncthreads();
for (int p = 0; p < LDS_RB / 16; ++p) {
const int r0 = blockIdx.x * LDS_RB + p * 16 + warp, r1 = r0 + 8;
if (r0 >= nrow) break;
const bool two = r1 < nrow;
const uint8_t* w0 = blob + L.down_off + (size_t) r0 * L.d_row;
const uint8_t* w1 = blob + L.down_off + (size_t) (two ? r1 : r0) * L.d_row;
auto pass = [&](auto ntc) {
constexpr int NTC = decltype(ntc)::value;
float s0[NTC], s1[NTC];
#pragma unroll
for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; }
for (int k = lane; k < nb * F::ipb; k += 32) {
const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
#pragma unroll
for (int j = 0; j < NTC; ++j) {
const block_q8_1* xk = sh + (size_t) j * hb + kbx * (F::qk / 32);
const float a = F::dot(w0, xk, kbx, iqs);
const float b = F::dot(w1, xk, kbx, iqs);
s0[j] += a;
s1[j] += b;
}
}
#pragma unroll
for (int j = 0; j < NTC; ++j) {
const float a = warp_sum(s0[j]), b = warp_sum(s1[j]);
if (lane == 0) {
out[(size_t) ent_dst[c0 + j] * L.n_embd + r0] = a;
if (two) out[(size_t) ent_dst[c0 + j] * L.n_embd + r1] = b;
}
}
};
switch (cn) {
case 1: pass(std::integral_constant<int, 1>{}); break;
case 2: pass(std::integral_constant<int, 2>{}); break;
case 3: pass(std::integral_constant<int, 3>{}); break;
default: pass(std::integral_constant<int, 4>{}); break;
}
}
}
}
// ---- 8: mode 7's gate/up with SwiGLU and the q8_1 quantization in the epilogue. A block takes h rows
// [r0, r0 + 32): gate rows r0.. and up rows r0.. (64 weight rows, the same per-(row, entry) sums as mode 7), so
// one 32-lane warp per entry holds exactly one q8_1 block of h and runs quantize_q8_1_kernel's own code on it -
// bitwise the separate kernels' hq, two launches fewer per call.
template<int TG>
__global__ void __launch_bounds__(256) native_gu_fused_kernel(const unsigned long long* __restrict__ grp_ptr,
const int32_t* __restrict__ grp_start,
const int32_t* __restrict__ n_groups,
const int32_t* __restrict__ ent_tok,
const block_q8_1* __restrict__ xq, NativeExpertLayout L,
block_q8_1* __restrict__ hq) {
using GT = typename GridOf<TG>::T;
using F = Fmt<TG>;
__shared__ GT sgrid[GridOf<TG>::N];
__shared__ float res[LDS_NT][64];
extern __shared__ int sx_raw[];
const int g = blockIdx.y;
if (g >= *n_groups) return;
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
const GT* gsrc = GridOf<TG>::src();
for (int i = tid; i < GridOf<TG>::N; i += 256) sgrid[i] = gsrc[i];
const uint8_t* blob = (const uint8_t*) grp_ptr[g];
const int nb = (int) (L.n_embd / F::qk), xb = (int) (L.n_embd / 32), hb = (int) (L.n_ff / 32);
const int e0 = grp_start[g], e1 = grp_start[g + 1];
const int r0 = blockIdx.x * 32;
const block_q8_1* sx = (const block_q8_1*) sx_raw;
auto wrow = [&](int i) -> const uint8_t* { // i < 32: gate row r0 + i, else up row r0 + i - 32
return blob + (i < 32 ? (size_t) 0 : L.up_off) + (size_t) (r0 + (i & 31)) * L.gu_row;
};
for (int c0 = e0; c0 < e1; c0 += LDS_NT) {
const int cn = min(LDS_NT, e1 - c0);
__syncthreads();
for (int j = 0; j < cn; ++j) {
const int* src = (const int*) (xq + (size_t) ent_tok[c0 + j] * xb);
for (int i = tid; i < xb * 9; i += 256) sx_raw[j * xb * 9 + i] = src[i];
}
__syncthreads();
for (int p = 0; p < 4; ++p) {
const int i0 = p * 16 + warp, i1 = i0 + 8;
const uint8_t* w0 = wrow(i0);
const uint8_t* w1 = wrow(i1);
auto pass = [&](auto ntc) {
constexpr int NTC = decltype(ntc)::value;
float s0[NTC], s1[NTC];
#pragma unroll
for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; }
for (int k = lane; k < nb * F::ipb; k += 32) {
const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
#pragma unroll
for (int j = 0; j < NTC; ++j) {
const block_q8_1* xk = sx + (size_t) j * xb + kbx * (F::qk / 32);
const float a = DotG<TG, 1>::f(w0, xk, kbx, iqs, sgrid);
const float b = DotG<TG, 1>::f(w1, xk, kbx, iqs, sgrid);
s0[j] += a;
s1[j] += b;
}
}
#pragma unroll
for (int j = 0; j < NTC; ++j) {
const float a = warp_sum(s0[j]), b = warp_sum(s1[j]);
if (lane == 0) { res[j][i0] = a; res[j][i1] = b; }
}
};
switch (cn) {
case 1: pass(std::integral_constant<int, 1>{}); break;
case 2: pass(std::integral_constant<int, 2>{}); break;
case 3: pass(std::integral_constant<int, 3>{}); break;
default: pass(std::integral_constant<int, 4>{}); break;
}
}
__syncthreads();
if (warp < cn) { // swiglu_entries_kernel + quantize_q8_1_kernel, one block of 32 h values per entry
const float gg = res[warp][lane], uu = res[warp][32 + lane];
const float xi = (gg / (1.0f + __expf(-gg))) * uu;
float amax = fabsf(xi), sum = xi;
#pragma unroll
for (int o = 16; o > 0; o >>= 1) {
amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));
sum += __shfl_xor_sync(0xffffffffu, sum, o);
}
const float d = amax / 127.0f;
const int8_t q = amax == 0.0f ? 0 : roundf(xi / d);
block_q8_1* y = hq + (size_t) (c0 + warp) * hb + blockIdx.x;
y->qs[lane] = q;
if (lane == 0) y->ds = make_half2(d, sum);
}
}
}
int g_exp_mode = -1; // native_expert_set_mode (the bench); -1 = STRATA_EXP_MODE, default 7
int exp_mode() {
static const int m = [] { const char* v = std::getenv("STRATA_EXP_MODE"); return v ? std::atoi(v) : 7; }();
return g_exp_mode >= 0 ? g_exp_mode : m;
}
#endif
int g_exp_phase = 0; // the bench: 0 all, 1 gate/up + swiglu + quantize only, 2 down only
void native_expert_set_mode(int mode, int phase) {
#if defined(STRATA_HIP_GFX906)
g_exp_mode = mode;
#else
(void) mode;
#endif
g_exp_phase = phase;
}
namespace {
bool g_grouped_v1 = env_on("STRATA_GROUPED_V1");
} // namespace
@@ -1555,15 +2133,76 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long
const bool v1 = g_grouped_v1;
const int64_t gy = (v1 || grid_groups <= 0 || grid_groups > cap_groups) ? cap_groups : grid_groups;
const dim3 ggu((unsigned) ((2 * L.n_ff + GU_ROWS - 1) / GU_ROWS), (unsigned) gy);
#if defined(STRATA_HIP_GFX906)
const int em0 = exp_mode();
#endif
#if defined(STRATA_HIP_GFX906)
const bool fused_gu = em0 == 8 && (L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23) &&
L.n_ff % 32 == 0;
if (fused_gu && g_exp_phase != 2) {
const dim3 gl((unsigned) (L.n_ff / 32), (unsigned) cap_groups);
const size_t sh = (size_t) LDS_NT * (size_t) (L.n_embd / 32) * sizeof(block_q8_1);
switch (L.gu_type) {
case 18: native_gu_fused_kernel<18><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;
case 21: native_gu_fused_kernel<21><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;
case 23: native_gu_fused_kernel<23><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;
default: native_gu_fused_kernel<22><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;
}
check("native_expert_grouped/gu fused");
}
if (g_exp_phase != 2 && !fused_gu) {
#else
if (g_exp_phase != 2) {
#endif
#if defined(STRATA_HIP_GFX906)
const bool lds_gu = (em0 == 5 || em0 == 6 || em0 == 7 || em0 == 8) && (L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23);
if (lds_gu) {
const dim3 gl((unsigned) ((2 * L.n_ff + LDS_RB - 1) / LDS_RB), (unsigned) cap_groups);
const size_t sh = (size_t) LDS_NT * (size_t) (L.n_embd / 32) * sizeof(block_q8_1);
switch (L.gu_type) {
case 18: if (em0 >= 7) native_gu_lds_kernel<18, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<18, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<18, 0><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
case 21: if (em0 >= 7) native_gu_lds_kernel<21, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<21, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<21, 0><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
case 23: if (em0 >= 7) native_gu_lds_kernel<23, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<23, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
default: if (em0 >= 7) native_gu_lds_kernel<22, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<22, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<22, 0><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
}
} else {
const int em = exp_mode() >= 5 ? 2 : exp_mode();
const dim3 ggu_amd((unsigned) ((2 * L.n_ff + (em == 1 ? 3 : em == 4 ? 31 : 15)) / (em == 1 ? 4 : em == 4 ? 32 : 16)), (unsigned) cap_groups);
#define STRATA_GU_AMD(T) \
case T: if (em == 1) native_gu_amd_kernel<T, 1><<<ggu_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); \
else if (em == 4) native_gu_amd_kernel<T, 4><<<ggu_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); \
else native_gu_amd_kernel<T, 2><<<ggu_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
// the AMD layouts cover the IQ packs' gate/up types; Unsloth's Q4_K / Q5_K take the CUDA layout below
const bool amd_gu = L.gu_type == 16 || L.gu_type == 17 || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 ||
L.gu_type == 23 || L.gu_type == 29 || L.gu_type == 42;
if ((em == 1 || em == 2 || em == 4) && amd_gu) {
switch (L.gu_type) {
STRATA_GU_AMD(16) STRATA_GU_AMD(17) STRATA_GU_AMD(18) STRATA_GU_AMD(21) STRATA_GU_AMD(22) STRATA_GU_AMD(23)
STRATA_GU_AMD(29) STRATA_GU_AMD(42)
}
} else
#undef STRATA_GU_AMD
#endif
switch (L.gu_type) {
#define STRATA_GU(T) case T: launch_gu<T>(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
STRATA_GU_FMTS(STRATA_GU)
#undef STRATA_GU
default: std::fprintf(stderr, "native_expert_grouped: gate/up type %d\n", L.gu_type); std::exit(1);
}
#if defined(STRATA_HIP_GFX906)
}
#endif
check("native_expert_grouped/gu");
const long long nh = (long long) cap_entries * L.n_ff;
if (v1) {
#if defined(STRATA_HIP_GFX906)
// gfx906: the separate SwiGLU and q8_1 passes stay the default (the A/B baseline); the RDNA one-pass
// kernel (bitwise the same) with STRATA_HIP_SWIGLU_FUSED=1
static const bool sw_fused = env_on("STRATA_HIP_SWIGLU_FUSED");
const bool sw_v1 = v1 || !sw_fused;
#else
const bool sw_v1 = v1;
#endif
if (sw_v1) {
swiglu_entries_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, nh);
quantize_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(h, hq, nh);
} else {
@@ -1571,7 +2210,33 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long
(int) L.n_ff, hq);
}
check("native_expert_grouped/swiglu");
}
if (g_exp_phase == 1) return;
const dim3 gd((unsigned) ((L.n_embd + 7) / 8), (unsigned) gy);
#if defined(STRATA_HIP_GFX906)
if ((em0 == 7 || em0 == 8) && (L.d_type == 20 || L.d_type == 42)) {
const dim3 gl((unsigned) ((L.n_embd + LDS_RB - 1) / LDS_RB), (unsigned) cap_groups);
const size_t sh = (size_t) LDS_NT * (size_t) (L.n_ff / 32) * sizeof(block_q8_1);
if (L.d_type == 20) native_down_lds_kernel<20><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
else native_down_lds_kernel<42><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
check("native_expert_grouped/down");
return;
}
const int em = exp_mode() >= 5 ? 2 : exp_mode();
const dim3 gd_amd((unsigned) ((L.n_embd + (em == 1 ? 3 : em == 4 ? 31 : 15)) / (em == 1 ? 4 : em == 4 ? 32 : 16)), (unsigned) cap_groups);
#define STRATA_D_AMD(T) \
case T: if (em == 1) native_down_amd_kernel<T, 1><<<gd_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); \
else if (em == 4) native_down_amd_kernel<T, 4><<<gd_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); \
else native_down_amd_kernel<T, 2><<<gd_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;
// the AMD layouts cover the IQ packs' down types; the others (Unsloth's Q4_K / Q5_K / Q5_1 / Q8_0) take the
// CUDA layout below
if ((em == 1 || em == 2 || em == 4) && (L.d_type == 20 || L.d_type == 23 || L.d_type == 42)) {
switch (L.d_type) {
STRATA_D_AMD(20) STRATA_D_AMD(23) STRATA_D_AMD(42)
}
} else
#undef STRATA_D_AMD
#endif
switch (L.d_type) {
#define STRATA_DOWN(T) case T: launch_down<T>(gd, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;
STRATA_D_FMTS(STRATA_DOWN)
+13
View File
@@ -183,4 +183,17 @@ void bf16_gemv_fp32_mmvf(const float* x, const uint16_t* w, float* y,
}
void bf16_gemv_fp32_mmvf_cols(const float* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, int ncols,
void* stream) {
// columns contiguous: the existing multi-row kernel (weight read once, each output bitwise its one-row call),
// up to 8 rows per launch
for (int c0 = 0; c0 < ncols; c0 += 8) {
const int nc = ncols - c0 < 8 ? ncols - c0 : 8;
if (nc == 1) bf16_gemv_fp32_mmvf(x + (size_t) c0 * n_in, w, y + (size_t) c0 * n_out, n_in, n_out, stream);
else bf16_gemv_fp32_mmvf_multi(x + (size_t) c0 * n_in, n_in, w, y + (size_t) c0 * n_out, n_out, n_in, n_out, nc,
stream);
}
}
} // namespace strata::kernels
+91
View File
@@ -32,6 +32,7 @@
#include <cuda_runtime.h>
#include <cstdint>
#include <cstdlib>
#include <limits>
#include <stdexcept>
#include <string>
@@ -418,6 +419,17 @@ __device__ __align__(4) int8_t iq4nl_values[16] = {
};
__device__ __forceinline__ int2 iq4_table_lookup(int q4) {
#if defined(STRATA_HIP_GFX906)
// AMD: llama.cpp's HIP lookup (see iq_kernels.cu get_int_from_table_16): 4 v_perm_b32 per 8 values
const uint32_t* v32 = reinterpret_cast<const uint32_t*>(iq4nl_values);
const uint32_t q_even = (uint32_t) q4, q_odd = (uint32_t) q4 >> 4;
const uint32_t el = __builtin_amdgcn_perm(v32[1], v32[0], q_even & 0x07070707u);
const uint32_t ol = __builtin_amdgcn_perm(v32[1], v32[0], q_odd & 0x07070707u);
const uint32_t eh = __builtin_amdgcn_perm(v32[3], v32[2], q_even & 0x07070707u);
const uint32_t oh = __builtin_amdgcn_perm(v32[3], v32[2], q_odd & 0x07070707u);
return make_int2((int) __builtin_amdgcn_perm(eh, el, 0x03020100u | ((q_even & 0x08080808u) >> 1)),
(int) __builtin_amdgcn_perm(oh, ol, 0x03020100u | ((q_odd & 0x08080808u) >> 1)));
#else
const uint32_t* table32 = reinterpret_cast<const uint32_t*>(iq4nl_values);
uint32_t tmp[2];
const uint32_t low_high_selection_indices = 0x32103210 | ((q4 & 0x88888888) >> 1);
@@ -429,6 +441,7 @@ __device__ __forceinline__ int2 iq4_table_lookup(int q4) {
tmp[i] = __byte_perm(low, high, low_high_selection_indices >> shift);
}
return make_int2(__byte_perm(tmp[0], tmp[1], 0x6420), __byte_perm(tmp[0], tmp[1], 0x7531));
#endif
}
// Exact pinned vec_dot_iq4_xs_q8_1: a lane consumes one 32-element subblock,
@@ -1099,6 +1112,77 @@ void launch_check() {
}
}
#if defined(STRATA_HIP_GFX906)
// ---- AMD (wave64) layout: one wavefront per R rows, four wavefronts per block, the row's blocks strided over the
// 64 lanes exactly as the CUDA kernels stride them over a block (kbx = lane / T, stride 64 / T), and a 64-lane
// butterfly instead of the LDS partials and __syncthreads of the one-block-per-row layout: on gfx906 a block per
// 2 KB row spent most of its time being launched and joined. The SAME kernel serves every column count 1..8, so a
// column's sums do not depend on how many columns (verify tokens) ride along. STRATA_MMVQ_WAVE=0: the CUDA layout.
bool g_wave_off = std::getenv("STRATA_MMVQ_WAVE") && std::string(std::getenv("STRATA_MMVQ_WAVE")) == "0";
template<typename F, int NCOLS, int R>
__launch_bounds__(256)
__global__ void native_mmvq_wave_kernel(const typename F::Block* __restrict__ w, const Q81Block* __restrict__ x,
float* __restrict__ y, int n_in, int n_out) {
constexpr int BPIW = 64 / F::T;
static_assert(64 % F::T == 0, "a block's threads must tile the wavefront");
const int lane = int(threadIdx.x) & 63;
const int row0 = (int(blockIdx.x) * 4 + (int(threadIdx.x) >> 6)) * R;
if (row0 >= n_out) return;
const int blocks_per_row = n_in / F::DIV;
const int x_stride = n_in / Q8K;
const int kqs = F::kqs(lane);
float tmp[NCOLS][R] = {};
for (int kbx = lane / F::T; kbx < blocks_per_row; kbx += BPIW) {
const int kby = kbx * F::KBY;
#pragma unroll
for (int i = 0; i < R; ++i) {
if (row0 + i < n_out) {
const typename F::W wv = F::load(w + std::size_t(row0 + i) * blocks_per_row + kbx, kqs);
#pragma unroll
for (int j = 0; j < NCOLS; ++j) tmp[j][i] += F::apply(wv, x + std::size_t(j) * x_stride + kby, kqs);
}
}
}
#pragma unroll
for (int j = 0; j < NCOLS; ++j)
#pragma unroll
for (int i = 0; i < R; ++i) {
float v = tmp[j][i];
#pragma unroll
for (int off = 32; off > 0; off >>= 1) v += __shfl_xor(v, off, 64);
if (lane == 0 && row0 + i < n_out) y[std::size_t(j) * n_out + row0 + i] = v;
}
}
template<typename F, int NCOLS>
void wave_launch_n(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, cudaStream_t s) {
const auto* w = static_cast<const typename F::Block*>(weights);
const auto* x = static_cast<const Q81Block*>(x_q8_1);
constexpr int R = 1;
const unsigned blocks = unsigned((std::size_t(n_out) + 4 * R - 1) / (4 * R));
native_mmvq_wave_kernel<F, NCOLS, R><<<blocks, 256, 0, s>>>(w, x, y, n_in, n_out);
}
template<typename F>
void wave_launch(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) {
const auto s = static_cast<cudaStream_t>(stream);
switch (ncols) {
case 1: wave_launch_n<F, 1>(weights, x_q8_1, y, n_in, n_out, s); break;
case 2: wave_launch_n<F, 2>(weights, x_q8_1, y, n_in, n_out, s); break;
case 3: wave_launch_n<F, 3>(weights, x_q8_1, y, n_in, n_out, s); break;
case 4: wave_launch_n<F, 4>(weights, x_q8_1, y, n_in, n_out, s); break;
case 5: wave_launch_n<F, 5>(weights, x_q8_1, y, n_in, n_out, s); break;
case 6: wave_launch_n<F, 6>(weights, x_q8_1, y, n_in, n_out, s); break;
case 7: wave_launch_n<F, 7>(weights, x_q8_1, y, n_in, n_out, s); break;
case 8: wave_launch_n<F, 8>(weights, x_q8_1, y, n_in, n_out, s); break;
default: throw std::invalid_argument("native MMVQ (wave) requires 1 <= ncols <= 8");
}
}
#define STRATA_WAVE_MMVQ(...) \
if (!g_wave_off) { wave_launch<__VA_ARGS__>(weights, x_q8_1, y, n_in, n_out, ncols, stream); launch_check(); return; }
#else
#define STRATA_WAVE_MMVQ(...)
#endif
template<typename Weight, int Qi>
void small_mmvq(const void* weights, const void* x_q8_1, float* y,
int n_in, int n_out, int ncols, void* stream) {
@@ -1108,6 +1192,7 @@ void small_mmvq(const void* weights, const void* x_q8_1, float* y,
validate_pointer(x_q8_1);
validate_pointer(y);
validate_stream(stream);
STRATA_WAVE_MMVQ(SmallTraits<Weight, Qi>)
if (ncols > 1) {
launch_multi<SmallTraits<Weight, Qi>>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
launch_check();
@@ -1172,6 +1257,7 @@ void native_q5_k_mmvq(const void* weights, const void* x_q8_1, float* y,
validate_pointer(x_q8_1);
validate_pointer(y);
validate_stream(stream);
STRATA_WAVE_MMVQ(Q5KTraits)
if (ncols > 1) {
launch_multi<Q5KTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
launch_check();
@@ -1212,6 +1298,7 @@ void native_q2_0_mmvq(const void* weights, const void* x_q8_1, float* y,
validate_pointer(x_q8_1);
validate_pointer(y);
validate_stream(stream);
STRATA_WAVE_MMVQ(Q20Traits)
if (ncols > 1) {
launch_multi<Q20Traits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
launch_check();
@@ -1251,6 +1338,7 @@ void native_q3_k_mmvq(const void* weights, const void* x_q8_1, float* y,
validate_pointer(x_q8_1);
validate_pointer(y);
validate_stream(stream);
STRATA_WAVE_MMVQ(Q3KTraits)
if (ncols > 1) {
launch_multi<Q3KTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
launch_check();
@@ -1290,6 +1378,7 @@ void native_iq4_xs_mmvq(const void* weights, const void* x_q8_1, float* y,
validate_pointer(x_q8_1);
validate_pointer(y);
validate_stream(stream);
STRATA_WAVE_MMVQ(IQ4XSTraits)
if (ncols > 1) {
launch_multi<IQ4XSTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
launch_check();
@@ -1329,6 +1418,7 @@ void native_q4_k_mmvq(const void* weights, const void* x_q8_1, float* y,
validate_pointer(x_q8_1);
validate_pointer(y);
validate_stream(stream);
STRATA_WAVE_MMVQ(Q4KTraits)
if (ncols > 1) {
launch_multi<Q4KTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
launch_check();
@@ -1368,6 +1458,7 @@ void native_q6_k_mmvq(const void* weights, const void* x_q8_1, float* y,
validate_pointer(x_q8_1);
validate_pointer(y);
validate_stream(stream);
STRATA_WAVE_MMVQ(Q6KTraits)
if (ncols > 1) {
launch_multi<Q6KTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
launch_check();
+251 -12
View File
@@ -181,6 +181,217 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest
for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
}
// PR #540 (sskver): the same attention with fewer shuffles and less shared-memory traffic, bit for bit the kernel
// above (same operands, same order); +7% prompt speed on a V100, where this kernel reads every prompt chunk. It
// uses more registers (80 vs 38 on sm_70), so it runs on cards below sm_75 only, and exists only in the experimental
// build (-DSTRATA_EXPERIMENTAL_SM60=ON): the ready-made engine keeps exactly the kernel above.
#if defined(STRATA_EXPERIMENTAL_SM60)
// The 12 heads' lane sums (`part[12..15]` zero), reduce-scattered with warp_sum's pairing order (xor 16, 8, 4, 2, 1):
// every output adds the same two operands at every level, so each sum is bit for bit warp_sum's (float add commutes),
// for 16 shuffles instead of 12 x 5. Lane l ends holding head head_of_lane(l); lanes l and l^1 agree.
__device__ __forceinline__ float reduce12(const float (&part)[16], int lane) {
float r8[8];
#pragma unroll
for (int i = 0; i < 8; ++i) {
const bool hi = (lane & 16) != 0;
r8[i] = (hi ? part[i + 8] : part[i]) + __shfl_xor_sync(0xffffffffu, hi ? part[i] : part[i + 8], 16);
}
float r4[4];
#pragma unroll
for (int i = 0; i < 4; ++i) {
const bool hi = (lane & 8) != 0;
r4[i] = (hi ? r8[i + 4] : r8[i]) + __shfl_xor_sync(0xffffffffu, hi ? r8[i] : r8[i + 4], 8);
}
float r2[2];
#pragma unroll
for (int i = 0; i < 2; ++i) {
const bool hi = (lane & 4) != 0;
r2[i] = (hi ? r4[i + 2] : r4[i]) + __shfl_xor_sync(0xffffffffu, hi ? r4[i] : r4[i + 2], 4);
}
const bool hi2 = (lane & 2) != 0;
const float r1 = (hi2 ? r2[1] : r2[0]) + __shfl_xor_sync(0xffffffffu, hi2 ? r2[0] : r2[1], 2);
return r1 + __shfl_xor_sync(0xffffffffu, r1, 1);
}
__device__ __forceinline__ int head_of_lane(int lane) {
return ((lane >> 4) & 1) * 8 + ((lane >> 3) & 1) * 4 + ((lane >> 2) & 1) * 2 + ((lane >> 1) & 1);
}
// One V element of pool row `row`, dimension `d` (the value loop's own thread index), per KV format.
template <int KV_MODE>
__device__ __forceinline__ float load_v1(const QsaAttnPools& p, long long row, int d) {
if constexpr (KV_MODE == 0) {
return __half2float(__ushort_as_half(p.v_pool[row * HD + d]));
} else if constexpr (KV_MODE == 1) {
const float sc = __half2float(__ushort_as_half(p.v_scale[row * (HD / KV_Q8_GROUP) + d / KV_Q8_GROUP]));
return (float) p.v_q[row * HD + d] * sc;
} else { // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back
constexpr int bytes_per_head = (HD / QK4_0) * sizeof(block_q4_0);
const int b = d / QK4_0;
const int rem = d % QK4_0;
const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + row * bytes_per_head) + b;
const float dd = __half2float(__ushort_as_half(blk->d));
const int j = rem < 16 ? rem : (rem - 16);
const uint8_t byte = blk->qs[j];
const int nibble = (rem < 16) ? ((byte & 0x0F) - 8) : ((byte >> 4) - 8);
return (float) nibble * dd;
}
}
template <int KV_MODE>
__global__ void __launch_bounds__(THREADS) attn_chunk_kernel_pre75(const float* __restrict__ q, QsaAttnPools p,
const int32_t* __restrict__ ids,
const int32_t* __restrict__ step, int n_kv_heads,
int page_size, float scale, float* __restrict__ part_acc,
float* __restrict__ part_m, float* __restrict__ part_l,
int n_chunks, int cap = 0, long long scratch_stride = 0) {
// batched form: query blockIdx.z, with its own q row, selection, step and scratch
q += (size_t) blockIdx.z * (size_t) (n_kv_heads * G) * HD;
ids += (size_t) blockIdx.z * (size_t) cap;
step += (size_t) blockIdx.z * kStepCount;
part_acc += (size_t) blockIdx.z * (size_t) scratch_stride;
part_m += (size_t) blockIdx.z * (size_t) scratch_stride;
part_l += (size_t) blockIdx.z * (size_t) scratch_stride;
__shared__ __align__(16) float sq[G][HD]; // 12 KB: this KV head's query heads (dead once the scores are done)
__shared__ float sp[G][CHUNK]; // scores
__shared__ long long srow[CHUNK]; // pool row of each cell (page, kv head, slot)
// probabilities, cell-major: the value loop reads one cell's 12 as three float4. They are first written after the
// __syncthreads that ends the score phase, the last reader of sq, so they share its storage (64 x 12 of its 256 x 12
// floats) and the block's shared memory stays what it was before the cell-major layout.
float (*const spt)[G] = reinterpret_cast<float (*)[G]>(&sq[0][0]);
static_assert(CHUNK * G <= G * HD, "spt must fit in sq");
const int n_ids = __ldg(step + kStepWidth);
const int chunk = blockIdx.x, kvh = blockIdx.y;
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const int c0 = chunk * CHUNK;
const int n_here = min(CHUNK, n_ids - c0);
const int slot = kvh * n_chunks + chunk;
if (n_here <= 0) {
if (t < G) { part_m[slot * G + t] = -FLT_MAX; part_l[slot * G + t] = 0.0f; }
return;
}
for (int i = t; i < G * HD; i += THREADS) sq[i / HD][i % HD] = q[(size_t) (kvh * G) * HD + i];
if (t < CHUNK) {
long long r = -1;
if (t < n_here) {
const int cell = ids[c0 + t];
const long long page = (long long) p.page_table[cell / page_size];
// a block the KV streaming could not make resident keeps page -1 (ctl[3]); its cells are masked
// (score -FLT_MAX, weight 0) instead of being read from before the pool.
if (page >= 0) r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
}
srow[t] = r;
}
__syncthreads();
// scores: each warp takes cells warp, warp+8, ...; each lane holds 8 of the 256 dimensions. NC cells per step
// (warp + 8 * (i + j)): a lane's q slice comes out of shared memory once for all of them, which cuts the traffic
// that bounds this phase (24 x 16 B per lane per cell, against the FMAs) by NC; every dot product is the same
// expression as for a single cell, so the scores are unchanged.
constexpr int NC = 2; // 4 measured slower on a V100 (the registers cost occupancy)
const int hd = head_of_lane(lane);
for (int i = 0; i < CHUNK / WARPS; i += NC) {
int cc[NC];
bool all_ok = true;
#pragma unroll
for (int j = 0; j < NC; ++j) {
cc[j] = warp + WARPS * (i + j);
all_ok = all_ok && cc[j] < n_here && srow[cc[j]] >= 0;
}
if (all_ok) {
float kk[NC][8];
#pragma unroll
for (int j = 0; j < NC; ++j) load8<KV_MODE>(p, false, srow[cc[j]], lane * 8, kk[j]);
float pp[NC][16];
#pragma unroll
for (int h = 0; h < G; ++h) {
const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8]);
const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + 4]);
#pragma unroll
for (int j = 0; j < NC; ++j)
pp[j][h] = kk[j][0] * qa.x + kk[j][1] * qa.y + kk[j][2] * qa.z + kk[j][3] * qa.w +
kk[j][4] * qb.x + kk[j][5] * qb.y + kk[j][6] * qb.z + kk[j][7] * qb.w;
}
#pragma unroll
for (int j = 0; j < NC; ++j) {
#pragma unroll
for (int h = G; h < 16; ++h) pp[j][h] = 0.0f;
const float sj = reduce12(pp[j], lane);
if ((lane & 1) == 0 && hd < G) sp[hd][cc[j]] = sj * scale;
}
} else {
for (int k = 0; k < NC; ++k) { // a masked or out-of-range cell in the group: one cell at a time
const int c = cc[k];
if (c >= n_here || srow[c] < 0) {
if (lane < G) sp[lane][c] = -FLT_MAX;
continue;
}
float k8[8];
load8<KV_MODE>(p, false, srow[c], lane * 8, k8);
float part[16];
#pragma unroll
for (int h = 0; h < G; ++h) {
const float4 qa = *reinterpret_cast<const float4*>(&sq[h][lane * 8]);
const float4 qb = *reinterpret_cast<const float4*>(&sq[h][lane * 8 + 4]);
part[h] = k8[0] * qa.x + k8[1] * qa.y + k8[2] * qa.z + k8[3] * qa.w +
k8[4] * qb.x + k8[5] * qb.y + k8[6] * qb.z + k8[7] * qb.w;
}
#pragma unroll
for (int h = G; h < 16; ++h) part[h] = 0.0f;
const float s = reduce12(part, lane);
if ((lane & 1) == 0 && hd < G) sp[hd][c] = s * scale;
}
}
}
__syncthreads();
// per-head chunk max and exp-sum: warp w handles heads w and w+8.
for (int h = warp; h < G; h += WARPS) {
const float a = sp[h][lane], b = sp[h][lane + 32];
const float m = warp_max(fmaxf(a, b));
const float ea = (lane < n_here && srow[lane] >= 0) ? __expf(a - m) : 0.0f;
const float eb = (lane + 32 < n_here && srow[lane + 32] >= 0) ? __expf(b - m) : 0.0f;
spt[lane][h] = ea;
spt[lane + 32][h] = eb;
const float l = warp_sum(ea + eb);
if (lane == 0) { part_m[slot * G + h] = m; part_l[slot * G + h] = l; }
}
__syncthreads();
// values: thread t owns dimension t for all 12 heads.
float acc[G];
#pragma unroll
for (int h = 0; h < G; ++h) acc[h] = 0.0f;
// One cell's 12 weights (three broadcast float4 loads) into the 12 accumulators; the cells are folded in
// ascending order, so the sums are the plain loop's, bit for bit.
const auto fold = [&](int c, float v) {
const float4* w4 = reinterpret_cast<const float4*>(spt[c]);
const float4 w0 = w4[0], w1 = w4[1], w2 = w4[2];
acc[0] = fmaf(w0.x, v, acc[0]); acc[1] = fmaf(w0.y, v, acc[1]);
acc[2] = fmaf(w0.z, v, acc[2]); acc[3] = fmaf(w0.w, v, acc[3]);
acc[4] = fmaf(w1.x, v, acc[4]); acc[5] = fmaf(w1.y, v, acc[5]);
acc[6] = fmaf(w1.z, v, acc[6]); acc[7] = fmaf(w1.w, v, acc[7]);
acc[8] = fmaf(w2.x, v, acc[8]); acc[9] = fmaf(w2.y, v, acc[9]);
acc[10] = fmaf(w2.z, v, acc[10]); acc[11] = fmaf(w2.w, v, acc[11]);
};
int c = 0;
// four cells at a time with their V loads issued together (the loop was one dependent load chain per cell);
// a group holding a masked cell (page -1, rare) leaves this loop and the scalar one below finishes the chunk.
for (; c + 4 <= n_here; c += 4) {
const long long r0 = srow[c], r1 = srow[c + 1], r2 = srow[c + 2], r3 = srow[c + 3];
if ((r0 | r1 | r2 | r3) < 0) break;
const float v0 = load_v1<KV_MODE>(p, r0, t), v1 = load_v1<KV_MODE>(p, r1, t);
const float v2 = load_v1<KV_MODE>(p, r2, t), v3 = load_v1<KV_MODE>(p, r3, t);
fold(c, v0);
fold(c + 1, v1);
fold(c + 2, v2);
fold(c + 3, v3);
}
for (; c < n_here; ++c) {
if (srow[c] < 0) continue; // masked above, weight 0
fold(c, load_v1<KV_MODE>(p, srow[c], t));
}
#pragma unroll
for (int h = 0; h < G; ++h) part_acc[((size_t) slot * G + h) * HD + t] = acc[h];
}
#endif // STRATA_EXPERIMENTAL_SM60
__global__ void __launch_bounds__(HD) attn_merge_kernel(const float* __restrict__ part_acc,
const float* __restrict__ part_m,
const float* __restrict__ part_l, int n_chunks,
@@ -206,6 +417,34 @@ __global__ void __launch_bounds__(HD) attn_merge_kernel(const float* __restrict_
attn[(size_t) h * HD + d] = L > 0.0f ? acc / L : 0.0f;
}
#if defined(STRATA_EXPERIMENTAL_SM60)
// the current device is below sm_75 (per device: a layer split can mix cards); STRATA_ATTN_PRE75=0 turns PR #540's
// kernel off (A/B)
bool pre75_attn() {
static const bool off = [] {
const char* e = std::getenv("STRATA_ATTN_PRE75");
return e != nullptr && e[0] == '0';
}();
static int cc[64] = {};
int dev = 0;
if (off) return false;
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
if (cc[dev] == 0) {
int major = 0, minor = 0;
if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess ||
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) {
cudaGetLastError();
return false;
}
cc[dev] = 10 * major + minor;
}
return cc[dev] < 75;
}
#define STRATA_ATTN_CHUNK(M) (pre75_attn() ? attn_chunk_kernel_pre75<M> : attn_chunk_kernel<M>)
#else
#define STRATA_ATTN_CHUNK(M) attn_chunk_kernel<M>
#endif
} // namespace
void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
@@ -228,16 +467,16 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3
const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q);
cudaStream_t st = (cudaStream_t) stream;
if (kv_mode == 3)
attn_chunk_kernel<3><<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,
STRATA_ATTN_CHUNK(3)<<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,
scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride);
else if (kv_mode == 2)
attn_chunk_kernel<2><<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,
STRATA_ATTN_CHUNK(2)<<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,
scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride);
else if (kv_mode == 1)
attn_chunk_kernel<1><<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,
STRATA_ATTN_CHUNK(1)<<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,
scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride);
else
attn_chunk_kernel<0><<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,
STRATA_ATTN_CHUNK(0)<<<grid, THREADS, 0, st>>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size,
scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride);
attn_merge_kernel<<<dim3((unsigned) s.n_head, (unsigned) n_q), HD, 0, st>>>(part_acc, part_m, part_l, n_chunks,
attn, stride);
@@ -276,17 +515,17 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32
const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv);
cudaStream_t st = (cudaStream_t) stream;
if (kv_mode == 3)
attn_chunk_kernel<3><<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size,
scale, part_acc, part_m, part_l, n_chunks);
STRATA_ATTN_CHUNK(3)<<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size,
scale, part_acc, part_m, part_l, n_chunks, 0, 0);
else if (kv_mode == 2)
attn_chunk_kernel<2><<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size,
scale, part_acc, part_m, part_l, n_chunks);
STRATA_ATTN_CHUNK(2)<<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size,
scale, part_acc, part_m, part_l, n_chunks, 0, 0);
else if (kv_mode == 1)
attn_chunk_kernel<1><<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size,
scale, part_acc, part_m, part_l, n_chunks);
STRATA_ATTN_CHUNK(1)<<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size,
scale, part_acc, part_m, part_l, n_chunks, 0, 0);
else
attn_chunk_kernel<0><<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size,
scale, part_acc, part_m, part_l, n_chunks);
STRATA_ATTN_CHUNK(0)<<<grid, THREADS, 0, st>>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size,
scale, part_acc, part_m, part_l, n_chunks, 0, 0);
attn_merge_kernel<<<(unsigned) s.n_head, HD, 0, st>>>(part_acc, part_m, part_l, n_chunks, attn);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
+395 -3
View File
@@ -736,6 +736,391 @@ bool launch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const
return true;
}
// PR #600: compiled only into the experimental build (-DSTRATA_EXPERIMENTAL_SM60=ON), the one build that runs on a
// Volta card; the ready-made engine has none of it (no extra kernels to load, the same code as before).
#if !defined(__HIPCC__) && defined(STRATA_EXPERIMENTAL_SM60)
// ---- sm_70 (Volta): v1's structure on mma.m8n8k4 ------------------------------------------------------------------
// Volta's tensor cores only have m8n8k4 (FP16 in, FP32 accumulate): per warp FOUR independent 8x8x4 products, one per
// quad-pair (QP q = lanes 4q..4q+3 and 4q+16..4q+19; thread j = (lane & 3) + 4 * (lane >> 4) within it). Layout, measured on
// a V100 (tools-free microtest, and equal to turbomind's SM70_MMA_884): the thread holds row j of A (k 0..3 as two
// registers) and column j of B (k 0..3); C register i is row (lane & 1) + 4 * (lane >> 4) + 2 * ((i >> 1) & 1),
// column (lane & 2) + 4 * (i >> 2) + (i & 1) of its QP's 8x8 tile.
// q.k: warp w owns dims [64w, 64w+64) = int8 scale group w; QP q takes cells 8q..8q+7 of the 32-cell chunk; 16 k-steps
// of 4 dims, two 8-row blocks (12 heads + 4 zero rows), q as hi + lo halves. The warp's partial (times the
// cells' K scale) goes to S.part[w]; the softmax adds the four groups in a fixed order (deterministic).
// p.v: warp w owns dims [64w, 64w+64) again; QP q takes the 16 dims 64w+16q.. (two n-tiles of 8); k = the 32 cells in
// steps of 4; p carries the V scale (as v1) and is split into hi + lo halves.
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700 && __CUDA_ARCH__ < 750
#define STRATA_PA_VOLTA 1
#else
#define STRATA_PA_VOLTA 0
#endif
__device__ __forceinline__ void mma884(float* c, uint32_t a0, uint32_t a1, uint32_t b0, uint32_t b1) {
#if STRATA_PA_VOLTA
asm volatile("mma.sync.aligned.m8n8k4.row.col.f32.f16.f16.f32 {%0,%1,%2,%3,%4,%5,%6,%7}, {%8,%9}, {%10,%11}, "
"{%0,%1,%2,%3,%4,%5,%6,%7};\n"
: "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]), "+f"(c[4]), "+f"(c[5]), "+f"(c[6]), "+f"(c[7])
: "r"(a0), "r"(a1), "r"(b0), "r"(b1));
#else
__trap(); // m8n8k4 is a Volta instruction; the host only launches this kernel on sm_70
#endif
}
template <int KV_MODE>
struct Smem70 {
using KElem = typename std::conditional<KV_MODE == 0, __half, int8_t>::type;
using VElem = typename std::conditional<KV_MODE == 1, int8_t, __half>::type;
static constexpr int KROW = KV_MODE == 0 ? HD + 8 : HD + 16;
static constexpr int VROW = KV_MODE == 1 ? HD + 16 : HD + 8;
__half qh[16][QS];
__half ql[16][QS];
KElem k[CH][KROW];
VElem v[CH][VROW];
float ks[CH][4];
float vs[CH][4];
float part[4][16][CH + 4]; // q.k per dim group (scaled by the cell's K scale)
float s[16][CH + 4]; // the chunk's probabilities
float qmax[THREADS / 32];
float alpha[16];
float lsum[16];
float mrow[16];
long long row[CH];
};
template <int KV_MODE>
__global__ void __launch_bounds__(THREADS) prompt_attn_v70_kernel(const float* __restrict__ q, QsaAttnPools p,
const int32_t* __restrict__ ids,
const int32_t* __restrict__ steps, int n_kv_heads,
int page_size, float scale_log2,
float* __restrict__ attn, int cap) {
extern __shared__ __align__(16) unsigned char smem_raw[];
Smem70<KV_MODE>& S = *reinterpret_cast<Smem70<KV_MODE>*>(smem_raw);
const int qi = blockIdx.x, kvh = blockIdx.y;
const int n_head = n_kv_heads * G;
q += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
attn += (size_t) qi * n_head * HD + (size_t) kvh * G * HD;
ids += (size_t) qi * cap;
const int n = __ldg(steps + (size_t) qi * kStepCount + kStepWidth);
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const int qp = (lane >> 2) & 3, jj = (lane & 3) + 4 * (lane >> 4); // quad-pair, thread within it
const int crow = (lane & 1) + 4 * (lane >> 4); // C row of register 0 (+2 per register pair)
const int ccol = lane & 2; // C column of register 0 (+4 per half, +1 per reg)
// q: 12 heads + 4 zero rows, scaled by a power of two that puts its largest value near 2^14 (exact, and the
// lo halves stay out of FP16's subnormal range), then split into hi + lo halves
float qm = 0.0f;
for (int i = t; i < G * HD; i += THREADS) qm = fmaxf(qm, fabsf(q[i]));
#pragma unroll
for (int o = 16; o > 0; o >>= 1) qm = fmaxf(qm, __shfl_xor_sync(0xffffffffu, qm, o));
if (lane == 0) S.qmax[warp] = qm;
__syncthreads();
qm = fmaxf(fmaxf(S.qmax[0], S.qmax[1]), fmaxf(S.qmax[2], S.qmax[3]));
int qe = 0;
if (qm > 0.0f) frexpf(qm, &qe); // qm < 2^qe
const float qup = ldexpf(1.0f, 14 - qe), qdown = ldexpf(scale_log2, qe - 14);
for (int i = t; i < 16 * HD; i += THREADS) {
const int h = i / HD, d = i % HD;
const float x = h < G ? q[(size_t) h * HD + d] * qup : 0.0f;
const __half hi = __float2half_rn(x);
S.qh[h][d] = hi;
S.ql[h][d] = __float2half_rn(x - __half2float(hi));
}
if (t < 16) { S.mrow[t] = -INFINITY; S.lsum[t] = 0.0f; }
float acc[2][2][8];
#pragma unroll
for (int rb = 0; rb < 2; ++rb)
#pragma unroll
for (int nt = 0; nt < 2; ++nt)
#pragma unroll
for (int i = 0; i < 8; ++i) acc[rb][nt][i] = 0.0f;
for (int c0 = 0; c0 < n; c0 += CH) {
const int nh = min(CH, n - c0);
if (t < CH) {
long long r = -1;
if (t < nh) {
const int cell = ids[c0 + t];
const long long page = (long long) p.page_table[cell / page_size];
r = (page * n_kv_heads + kvh) * page_size + (cell % page_size);
}
S.row[t] = r;
}
__syncthreads(); // rows ready; the previous chunk's p.v is done with k, v, s
// gather the chunk's K and V rows (16-byte pieces; K8V4's V as q4_0 blocks dequantized to fp16)
// and their scales
{
constexpr int KPIECES = HD * (int) sizeof(typename Smem<KV_MODE>::KElem) / 16; // per K row
for (int i = t; i < CH * KPIECES; i += THREADS) {
const int c = i / KPIECES, pc = i % KPIECES;
const long long r = S.row[c];
uint4 kx = make_uint4(0, 0, 0, 0);
if (r >= 0) {
if constexpr (KV_MODE == 0)
kx = __ldg(reinterpret_cast<const uint4*>(p.k_pool + r * HD) + pc);
else // modes 1 and 3: the K side is INT8
kx = __ldg(reinterpret_cast<const uint4*>(p.k_q + r * HD) + pc);
}
*reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.k[c][0]) + pc * 16) = kx;
}
if constexpr (KV_MODE == 3) { // V: dequantize the row's q4_0 blocks straight into the fp16 V row
constexpr int BLKS = HD / QK4_0;
constexpr int BYTES = BLKS * (int) sizeof(block_q4_0);
for (int i = t; i < CH * BLKS; i += THREADS) {
const int c = i / BLKS, b = i % BLKS;
const long long r = S.row[c];
#pragma unroll
for (int j = 0; j < QK4_0; ++j) S.v[c][b * QK4_0 + j] = __half(0);
if (r >= 0) {
const block_q4_0* blk = reinterpret_cast<const block_q4_0*>(p.v_q4 + r * BYTES) + b;
const float d = __half2float(__ushort_as_half(blk->d));
#pragma unroll
for (int j = 0; j < QK4_0 / 2; ++j) {
S.v[c][b * QK4_0 + j] = __float2half_rn((float) ((int)(blk->qs[j] & 0x0F) - 8) * d);
S.v[c][b * QK4_0 + j + QK4_0 / 2] =
__float2half_rn((float) ((int)(blk->qs[j] >> 4) - 8) * d);
}
}
}
} else {
constexpr int VPIECES = HD * (int) sizeof(typename Smem<KV_MODE>::VElem) / 16; // per V row
for (int i = t; i < CH * VPIECES; i += THREADS) {
const int c = i / VPIECES, pc = i % VPIECES;
const long long r = S.row[c];
uint4 vx = make_uint4(0, 0, 0, 0);
if (r >= 0) {
if constexpr (KV_MODE == 1)
vx = __ldg(reinterpret_cast<const uint4*>(p.v_q + r * HD) + pc);
else
vx = __ldg(reinterpret_cast<const uint4*>(p.v_pool + r * HD) + pc);
}
*reinterpret_cast<uint4*>(reinterpret_cast<unsigned char*>(&S.v[c][0]) + pc * 16) = vx;
}
}
for (int i = t; i < CH * 4; i += THREADS) {
const int c = i / 4, g = i % 4;
const long long r = S.row[c];
float a = 0.0f, b = 0.0f;
if (r >= 0) {
if constexpr (KV_MODE == 1) {
a = __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g]));
b = __half2float(__ushort_as_half(p.v_scale[r * (HD / KV_Q8_GROUP) + g]));
} else if constexpr (KV_MODE == 3) { // K as int8, V dequantized to fp16 (scale 1)
a = __half2float(__ushort_as_half(p.k_scale[r * (HD / KV_Q8_GROUP) + g]));
b = 1.0f;
} else {
a = b = 1.0f;
}
}
S.ks[c][g] = a;
S.vs[c][g] = b;
}
}
__syncthreads();
// scores: warp w = dim group w (64 dims), QP q = cells 8q..8q+7
{
float tg[2][8];
#pragma unroll
for (int rb = 0; rb < 2; ++rb)
#pragma unroll
for (int i = 0; i < 8; ++i) tg[rb][i] = 0.0f;
const int cell_b = qp * 8 + jj;
#pragma unroll
for (int ks = 0; ks < 16; ++ks) {
const int d0 = warp * 64 + ks * 4;
uint32_t b0, b1;
if constexpr (KV_MODE != 0) { // modes 1 and 3: the K side is INT8 codes, exact in FP16
const uint32_t raw = *reinterpret_cast<const uint32_t*>(&S.k[cell_b][d0]);
b0 = i8x2_to_h2(raw & 0xffffu);
b1 = i8x2_to_h2(raw >> 16);
} else {
const uint2 raw = *reinterpret_cast<const uint2*>(&S.k[cell_b][d0]);
b0 = raw.x;
b1 = raw.y;
}
#pragma unroll
for (int rb = 0; rb < 2; ++rb) {
const uint2 ah = *reinterpret_cast<const uint2*>(&S.qh[rb * 8 + jj][d0]);
const uint2 al = *reinterpret_cast<const uint2*>(&S.ql[rb * 8 + jj][d0]);
mma884(tg[rb], ah.x, ah.y, b0, b1);
mma884(tg[rb], al.x, al.y, b0, b1);
}
}
#pragma unroll
for (int rb = 0; rb < 2; ++rb)
#pragma unroll
for (int i = 0; i < 8; ++i) {
const int row = rb * 8 + crow + 2 * ((i >> 1) & 1);
const int cell = qp * 8 + ccol + 4 * (i >> 2) + (i & 1);
S.part[warp][row][cell] = tg[rb][i] * S.ks[cell][warp];
}
}
__syncthreads();
// online softmax: row t/8, 4 cells per thread, 8 threads per row (lanes 8r..8r+7 of a warp)
{
constexpr int PER = CH / 8;
const int r = t >> 3, sub = t & 7;
float x[PER], mx = -INFINITY;
#pragma unroll
for (int j = 0; j < PER; ++j) {
const int c = sub * PER + j;
const float sum4 = ((S.part[0][r][c] + S.part[1][r][c]) + S.part[2][r][c]) + S.part[3][r][c];
x[j] = c < nh ? sum4 * qdown : -INFINITY;
mx = fmaxf(mx, x[j]);
}
#pragma unroll
for (int o = 1; o < 8; o <<= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffffu, mx, o));
const float m_old = S.mrow[r];
const float m_new = fmaxf(m_old, mx);
float sum = 0.0f;
#pragma unroll
for (int j = 0; j < PER; ++j) {
const float e = x[j] == -INFINITY ? 0.0f : exp2f(x[j] - m_new);
S.s[r][sub * PER + j] = e;
sum += e;
}
#pragma unroll
for (int o = 1; o < 8; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
__syncwarp();
if (sub == 0) {
const float a = m_old == -INFINITY ? 0.0f : exp2f(m_old - m_new);
S.alpha[r] = a;
S.lsum[r] = fmaf(S.lsum[r], a, sum);
S.mrow[r] = m_new;
}
}
__syncthreads();
__syncthreads();
// p.v: warp w owns dims [64w, 64w+64) (int8 scale group w), QP q its 16 dims 64w+16q..; the V scale is folded
// into p relative to the chunk's largest, times 2^14 (as v1)
{
float vmax = 0.0f;
#pragma unroll
for (int c = lane; c < CH; c += 32) vmax = fmaxf(vmax, S.vs[c][warp]);
#pragma unroll
for (int o = 16; o > 0; o >>= 1) vmax = fmaxf(vmax, __shfl_xor_sync(0xffffffffu, vmax, o));
const float vup = vmax > 0.0f ? 16384.0f / vmax : 0.0f, vdown = vmax * (1.0f / 16384.0f);
float tmp[2][2][8];
#pragma unroll
for (int rb = 0; rb < 2; ++rb)
#pragma unroll
for (int nt = 0; nt < 2; ++nt)
#pragma unroll
for (int i = 0; i < 8; ++i) tmp[rb][nt][i] = 0.0f;
#pragma unroll
for (int ks = 0; ks < CH / 4; ++ks) {
const int c0 = ks * 4;
float w[4];
#pragma unroll
for (int e = 0; e < 4; ++e) w[e] = S.vs[c0 + e][warp] * vup;
uint2 ah[2], al[2];
#pragma unroll
for (int rb = 0; rb < 2; ++rb) {
const float4 pv = *reinterpret_cast<const float4*>(&S.s[rb * 8 + jj][c0]);
const float p0 = pv.x * w[0], p1 = pv.y * w[1], p2 = pv.z * w[2], p3 = pv.w * w[3];
ah[rb].x = pack_h2(p0, p1);
ah[rb].y = pack_h2(p2, p3);
const float2 f01 = __half22float2(*reinterpret_cast<const __half2*>(&ah[rb].x));
const float2 f23 = __half22float2(*reinterpret_cast<const __half2*>(&ah[rb].y));
al[rb].x = pack_h2(p0 - f01.x, p1 - f01.y);
al[rb].y = pack_h2(p2 - f23.x, p3 - f23.y);
}
#pragma unroll
for (int nt = 0; nt < 2; ++nt) {
const int d = warp * 64 + qp * 16 + nt * 8 + jj;
uint32_t b0, b1;
if constexpr (KV_MODE == 1) {
const uint32_t x0 = (uint8_t) S.v[c0][d] | ((uint32_t) (uint8_t) S.v[c0 + 1][d] << 8);
const uint32_t x1 = (uint8_t) S.v[c0 + 2][d] | ((uint32_t) (uint8_t) S.v[c0 + 3][d] << 8);
b0 = i8x2_to_h2(x0);
b1 = i8x2_to_h2(x1);
} else {
const __half2 h0 = __halves2half2(S.v[c0][d], S.v[c0 + 1][d]);
const __half2 h1 = __halves2half2(S.v[c0 + 2][d], S.v[c0 + 3][d]);
b0 = *reinterpret_cast<const uint32_t*>(&h0);
b1 = *reinterpret_cast<const uint32_t*>(&h1);
}
#pragma unroll
for (int rb = 0; rb < 2; ++rb) {
mma884(tmp[rb][nt], ah[rb].x, ah[rb].y, b0, b1);
mma884(tmp[rb][nt], al[rb].x, al[rb].y, b0, b1);
}
}
}
#pragma unroll
for (int rb = 0; rb < 2; ++rb) {
float a_[2];
a_[0] = S.alpha[rb * 8 + crow];
a_[1] = S.alpha[rb * 8 + crow + 2];
#pragma unroll
for (int nt = 0; nt < 2; ++nt)
#pragma unroll
for (int i = 0; i < 8; ++i)
acc[rb][nt][i] = fmaf(acc[rb][nt][i], a_[(i >> 1) & 1], tmp[rb][nt][i] * vdown);
}
}
}
__syncthreads();
#pragma unroll
for (int rb = 0; rb < 2; ++rb)
#pragma unroll
for (int h = 0; h < 2; ++h) {
const int row = rb * 8 + crow + 2 * h;
if (row >= G) continue;
const float l = S.lsum[row];
const float inv = l > 0.0f ? 1.0f / l : 0.0f;
#pragma unroll
for (int nt = 0; nt < 2; ++nt)
#pragma unroll
for (int hh = 0; hh < 2; ++hh) {
const int i = hh * 4 + h * 2; // registers i, i+1: row h, columns ccol + 4 * hh + {0, 1}
const int d = warp * 64 + qp * 16 + nt * 8 + ccol + 4 * hh;
*reinterpret_cast<float2*>(attn + (size_t) row * HD + d) =
make_float2(acc[rb][nt][i] * inv, acc[rb][nt][i + 1] * inv);
}
}
}
template <int KV_MODE>
bool launch70(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap,
const QsaShapes& s, float* attn, int64_t n_q, cudaStream_t st) {
static bool attr[64] = {};
int dev = 0;
cudaGetDevice(&dev);
const int bytes = (int) sizeof(Smem70<KV_MODE>);
if (dev < 0 || dev >= 64) return false;
if (!attr[dev]) {
if (cudaFuncSetAttribute(prompt_attn_v70_kernel<KV_MODE>, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes) !=
cudaSuccess) {
cudaGetLastError();
return false;
}
attr[dev] = true;
}
const float scale_log2 = 1.4426950408889634f / sqrtf((float) HD);
for (int64_t q0 = 0; q0 < n_q; q0 += 65535) {
const int64_t nb = n_q - q0 < 65535 ? n_q - q0 : 65535;
prompt_attn_v70_kernel<KV_MODE><<<dim3((unsigned) nb, (unsigned) s.n_head_kv), THREADS, bytes, st>>>(
q + q0 * s.n_head * HD, pools, ids + q0 * cap, steps + q0 * kStepCount, (int) s.n_head_kv,
(int) s.page_size, scale_log2, attn + q0 * s.n_head * HD, (int) cap);
}
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "qsa_prompt_attn_batch (sm_70): %s\n", cudaGetErrorString(e));
std::exit(1);
}
return true;
}
#else // AMD, or a build without STRATA_EXPERIMENTAL_SM60: no m8n8k4 kernel (the caller keeps the old one)
template <int KV_MODE>
bool launch70(const float*, const QsaAttnPools&, const int32_t*, const int32_t*, int64_t, const QsaShapes&, float*,
int64_t, cudaStream_t) {
return false;
}
#endif // !__HIPCC__ && STRATA_EXPERIMENTAL_SM60
#if defined(__HIPCC__)
// ---- S6: the int8-KV prompt attention on RDNA4 matrix cores (opt-in: STRATA_HIP_WMMA=1, gfx12 only). The design of
// the v2 kernel above with gfx12's v_wmma_f32_16x16x16_f16 (wave32) in place of m16n8k16: wave w owns dims
@@ -1022,11 +1407,14 @@ bool launch_wmma(const float* q, const QsaAttnPools& pools, const int32_t* ids,
bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps,
int64_t cap, const QsaShapes& s, float* attn, int64_t n_q, void* stream) {
if (n_q <= 0) return true;
bool turing = false; // per call, from the CURRENT device (a layer split can mix Turing with newer cards)
bool volta = false, turing = false; // per call, from the CURRENT device (a layer split can mix Turing with newer cards)
{ // sm_75 or newer: the MMA above compiles for both. sm_80+ runs the cp.async kernel (launch_i8); Turing has
// no cp.async, so it runs the v1 kernel (launch<1>, same accuracy, another summation order). An older card
// keeps the old kernel.
// #371: the compute capability with its minor - sm_70 (V100) has no m16n8k8 (the kernels trap below sm_75)
#if defined(STRATA_HIP_GFX906)
return false; // gfx906: the tensor-core and WMMA kernels are not for it; the FP32 kernel runs
#endif
static int cc[64] = {};
int dev = 0;
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
@@ -1042,13 +1430,14 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3
cc[dev] = w && (!std::strcmp(w, "1") || !std::strcmp(w, "attn")) ? 75
: 10 * strata::cc_major_of(major) + strata::cc_minor_of(minor);
}
if (cc[dev] < 75) return false;
if (cc[dev] < 70) return false;
volta = cc[dev] < 75; // sm_70: the m8n8k4 kernel (STRATA_PA_VOLTA); STRATA_QSA_WARP=1 still forces the old one
turing = cc[dev] < 80;
}
#if defined(__HIPCC__)
// the tensor-core kernels are compiled out on AMD (its major version is not a CUDA sm); RDNA4 has its own int8-KV
// matrix-core kernel, opt-in (STRATA_HIP_WMMA=1); everything else keeps the old kernel
(void) turing;
(void) turing; (void) volta;
if (pools.k_q != nullptr && pools.v_q != nullptr && pools.k_scale != nullptr && pools.v_scale != nullptr &&
pools.k_q4 == nullptr && pools.v_q4 == nullptr && s.head_dim == HD && s.n_head == (int64_t) G * s.n_head_kv &&
cap > 0 && ids && steps && pools.page_table && hip_wmma_usable())
@@ -1069,6 +1458,7 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3
}
if (pools.k_q != nullptr && pools.v_q4 != nullptr) { // hybrid K8V4: int8 K + dequantized-q4 V
if (!pools.k_scale) return false;
if (volta) return launch70<3>(q, pools, ids, steps, cap, s, attn, n_q, st);
return launch<3>(q, pools, ids, steps, cap, s, attn, n_q, st);
}
if (pools.k_q != nullptr) {
@@ -1077,10 +1467,12 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3
// for how far the model amplifies an FP32-level change. Turing always takes it: v2's cp.async does not
// exist before sm_80.
static const bool v1 = std::getenv("STRATA_PROMPT_ATTN_V1") != nullptr;
if (volta) return launch70<1>(q, pools, ids, steps, cap, s, attn, n_q, st);
if (v1 || turing) return launch<1>(q, pools, ids, steps, cap, s, attn, n_q, st);
return launch_i8(q, pools, ids, steps, cap, s, attn, n_q, st);
}
if (!pools.k_pool || !pools.v_pool) return false;
if (volta) return launch70<0>(q, pools, ids, steps, cap, s, attn, n_q, st);
return launch<0>(q, pools, ids, steps, cap, s, attn, n_q, st);
}
+96
View File
@@ -186,6 +186,83 @@ __global__ void router_top10_kernel(const float* __restrict__ logits, int n_toke
}
}
#if defined(STRATA_HIP_GFX906)
// AMD (wave64): the same routing in ONE wavefront per token. The block-wide kernel above spends its time in
// barriers - 10 selection passes with two __syncthreads each over 8 logical warps - not in arithmetic (43 us per
// token on gfx906). Here every lane holds up to RW_PER probabilities in registers and each pass is a 64-lane
// butterfly argmax: no LDS round trip, no block barrier. Bit-identical to the kernel above: fmaxf trees are
// exact, the exponentials and the (float) products are the same expressions, the sum stays one serial ascending
// scan, and the argmax keeps the lowest index on a tie (a total order, so the butterfly's association is free).
constexpr int RW_PER = 8; // n_expert <= 64 * 8
__global__ void __launch_bounds__(64) router_top10_wave_kernel(const float* __restrict__ logits, int n_tokens,
int n_expert, int k, int* __restrict__ ids,
float* __restrict__ weights) {
__shared__ double s_ex[64 * RW_PER];
__shared__ double s_sum;
const int t = blockIdx.x;
if (t >= n_tokens) return;
const int lane = threadIdx.x;
const float* l = logits + (size_t) t * n_expert;
float lv[RW_PER];
float mx = -INFINITY;
#pragma unroll
for (int j = 0; j < RW_PER; ++j) {
const int e = lane + 64 * j;
lv[j] = e < n_expert ? l[e] : -INFINITY;
mx = fmaxf(mx, lv[j]);
}
#pragma unroll
for (int off = 32; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_xor(mx, off, 64));
#pragma unroll
for (int j = 0; j < RW_PER; ++j) {
const int e = lane + 64 * j;
if (e < n_expert) s_ex[e] = exp((double) lv[j] - (double) mx);
}
__syncthreads();
if (lane == 0) {
double sum = 0.0;
for (int e = 0; e < n_expert; ++e) sum += s_ex[e];
s_sum = sum;
}
__syncthreads();
const float inv = (float) (1.0 / s_sum);
float p[RW_PER];
#pragma unroll
for (int j = 0; j < RW_PER; ++j) {
const int e = lane + 64 * j;
p[j] = e < n_expert ? (float) (s_ex[e] * inv) : -INFINITY;
}
unsigned taken = 0;
for (int i = 0; i < k; ++i) {
float bv = -INFINITY;
int bi = n_expert;
#pragma unroll
for (int j = 0; j < RW_PER; ++j) {
const int e = lane + 64 * j;
if (e >= n_expert || (taken >> j & 1u)) continue;
if (p[j] > bv || (p[j] == bv && e < bi)) { bv = p[j]; bi = e; }
}
#pragma unroll
for (int off = 32; off > 0; off >>= 1) {
const float ov = __shfl_xor(bv, off, 64);
const int oi = __shfl_xor(bi, off, 64);
if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }
}
if (bi >= n_expert) break;
if ((bi & 63) == lane) taken |= 1u << (bi >> 6);
if (lane == 0) { ids[(size_t) t * k + i] = bi; weights[(size_t) t * k + i] = bv; }
}
if (lane == 0) {
double s = 0.0;
for (int i = 0; i < k; ++i) s += (double) weights[(size_t) t * k + i];
const double sc = fmax(s, 6.103515625e-05); // 2**-14
for (int i = 0; i < k; ++i)
weights[(size_t) t * k + i] = (float) ((double) weights[(size_t) t * k + i] / sc);
}
}
#endif // STRATA_HIP_GFX906
#if defined(__HIPCC__)
// ---- S6, AMD: the same router, BIT-IDENTICAL, without its serial parts. Measured on RDNA4 (gfx1201) the kernel
// above took 39 us per call in decode (16% of the GPU's decode time): the ascending double sum is 512 dependent FP64
@@ -346,7 +423,13 @@ void router_top10(const float* logits, int n_tokens, int n_expert, int k, int* i
void* stream) {
#if defined(__HIPCC__)
{
#if defined(STRATA_HIP_GFX906)
// gfx906 (wave64): the one-wavefront kernel below stays the default; the S6 kernel is wave32-shaped and only
// runs here on request (STRATA_HIP_ROUTER_FAST=1) until it is measured on this card
static const bool old = std::getenv("STRATA_HIP_ROUTER_FAST") == nullptr;
#else
static const bool old = std::getenv("STRATA_HIP_ROUTER_OLD") != nullptr;
#endif
if (!old && n_tokens > 0 && n_expert > 64 && n_expert <= 512 && k > 0 && k <= 32) {
launch_generic(logits, n_tokens, n_expert, k, ids, weights, stream, 1);
const cudaError_t e = cudaGetLastError();
@@ -375,6 +458,19 @@ void router_top10(const float* logits, int n_tokens, int n_expert, int k, int* i
RT_MAX_THREADS * 64);
std::exit(1);
}
#if defined(STRATA_HIP_GFX906)
if (n_expert <= 64 * RW_PER && !std::getenv("STRATA_ROUTER_BLOCK")) {
router_top10_wave_kernel<<<(unsigned) n_tokens, 64, 0, (cudaStream_t) stream>>>(logits, n_tokens, n_expert, k,
ids, weights);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
std::fprintf(stderr, "router_top10 launch: %s\n", cudaGetErrorString(e));
std::exit(1);
}
if (stream == nullptr && cudaDeviceSynchronize() != cudaSuccess) std::exit(1);
return;
}
#endif
int threads = n_expert < RT_MAX_THREADS ? n_expert : RT_MAX_THREADS;
threads = (threads + 31) & ~31; // at least one full warp, for the reductions
// the selection's taken-mask, then n_expert doubles for the exponentials, then n_expert floats for the
+3 -1
View File
@@ -545,7 +545,9 @@ void copy_indexed(float* dst, const float* src, int64_t stride, const int32_t* i
// a GPU timestamp (ns, %globaltimer) into buf[i] - the verify window's stage profiler
namespace { __global__ void gpu_stamp_kernel(unsigned long long* buf, int i) {
unsigned long long t;
#if defined(__HIPCC__)
#if defined(STRATA_HIP_GFX906)
t = wall_clock64() * 40ull; // gfx906: the wall clock runs at 25 MHz (hipDeviceAttributeWallClockRate) -> ns
#elif defined(__HIPCC__)
t = wall_clock64() * 10ull; // gfx10.3 / gfx11 / gfx12: a constant 100 MHz counter, in ns
#else
asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t));
+116
View File
@@ -0,0 +1,116 @@
// src/kernels/fused_gr_bench.cpp - fused_gr_read_multi: the AMD fast kernels (STRATA_GR_FAST) against the old
// ones, bit for bit on every output (lo, rs, inject, mixed, the in-place R), and each one's time.
//
// build/fused_gr_bench [iters] [T min] [T max]
#include "strata/kernels/fused_gr.hpp"
#include <cuda_runtime.h>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <vector>
namespace K = strata::kernels;
static uint16_t bf16(float x) {
uint32_t u;
std::memcpy(&u, &x, 4);
return (uint16_t) ((u + 0x7fff + ((u >> 16) & 1)) >> 16);
}
int main(int argc, char** argv) {
setvbuf(stdout, nullptr, _IONBF, 0);
const int iters = argc > 1 ? std::atoi(argv[1]) : 500;
const int t_lo = argc > 2 ? std::atoi(argv[2]) : 1, t_hi = argc > 3 ? std::atoi(argv[3]) : 6;
const int N = 2560, HC = 4, D = N * HC, LR = 320, TM = K::kFusedGrMaxT;
std::mt19937 rng(7);
std::normal_distribution<float> nd(0.f, 1.f);
auto fill = [&](std::vector<float>& v, float sc) { for (auto& x : v) x = sc * nd(rng); };
std::vector<float> R((size_t) TM * D), bo((size_t) TM * N), inj((size_t) TM * HC), wn(D);
fill(R, 1.0f); fill(bo, 0.5f); fill(inj, 1.0f); fill(wn, 0.3f);
for (auto& x : wn) x += 1.0f;
std::vector<uint16_t> wd((size_t) LR * D), wu((size_t) D * LR), wi((size_t) HC * D);
for (auto& x : wd) x = bf16(0.02f * nd(rng));
for (auto& x : wu) x = bf16(0.05f * nd(rng));
for (auto& x : wi) x = bf16(0.02f * nd(rng));
float *dR, *dbo, *dinj, *dwn, *dxn, *dlo, *drs, *dio, *dmix;
uint16_t *dwd, *dwu, *dwi;
cudaMalloc((void**) &dR, R.size() * 4);
cudaMalloc((void**) &dbo, bo.size() * 4);
cudaMalloc((void**) &dinj, inj.size() * 4);
cudaMalloc((void**) &dwn, wn.size() * 4);
cudaMalloc((void**) &dxn, (size_t) TM * D * 4);
cudaMalloc((void**) &dlo, (size_t) TM * LR * 4);
cudaMalloc((void**) &drs, (size_t) TM * HC * 4);
cudaMalloc((void**) &dio, (size_t) TM * HC * 4);
cudaMalloc((void**) &dmix, (size_t) TM * N * 4);
cudaMalloc((void**) &dwd, wd.size() * 2);
cudaMalloc((void**) &dwu, wu.size() * 2);
cudaMalloc((void**) &dwi, wi.size() * 2);
cudaMemcpy(dbo, bo.data(), bo.size() * 4, cudaMemcpyHostToDevice);
cudaMemcpy(dinj, inj.data(), inj.size() * 4, cudaMemcpyHostToDevice);
cudaMemcpy(dwn, wn.data(), wn.size() * 4, cudaMemcpyHostToDevice);
cudaMemcpy(dwd, wd.data(), wd.size() * 2, cudaMemcpyHostToDevice);
cudaMemcpy(dwu, wu.data(), wu.size() * 2, cudaMemcpyHostToDevice);
cudaMemcpy(dwi, wi.data(), wi.size() * 2, cudaMemcpyHostToDevice);
cudaStream_t s;
cudaStreamCreate(&s);
cudaEvent_t e0, e1;
cudaEventCreate(&e0);
cudaEventCreate(&e1);
int failures = 0;
for (int T = t_lo; T <= t_hi; ++T)
for (int apply = 0; apply < 2; ++apply)
for (int inject = 0; inject < 2; ++inject) {
K::FusedGrArgs a[TM];
for (int t = 0; t < T; ++t) {
a[t].R = dR + (size_t) t * D; a[t].R_out = dR + (size_t) t * D; a[t].apply = apply;
a[t].bo_prev = dbo + (size_t) t * N; a[t].inj_prev = dinj + (size_t) t * HC;
a[t].w_norm = dwn; a[t].w_down = dwd; a[t].w_up = dwu; a[t].w_inject = inject ? dwi : nullptr;
a[t].lo = dlo + (size_t) t * LR; a[t].rs = drs + (size_t) t * HC;
a[t].inject_out = dio + (size_t) t * HC; a[t].mixed = dmix + (size_t) t * N;
}
std::vector<float> out[2];
for (int f = 0; f < 2; ++f) {
cudaMemcpy(dR, R.data(), R.size() * 4, cudaMemcpyHostToDevice);
cudaMemset(dlo, 0xff, (size_t) TM * LR * 4);
cudaMemset(drs, 0xff, (size_t) TM * HC * 4);
cudaMemset(dio, 0xff, (size_t) TM * HC * 4);
cudaMemset(dmix, 0xff, (size_t) TM * N * 4);
K::fused_gr_set_fast(f);
K::fused_gr_read_multi(a, T, dxn, s);
cudaStreamSynchronize(s);
auto& o = out[f];
o.resize((size_t) TM * (D + LR + HC + HC + N));
float* p = o.data();
cudaMemcpy(p, dR, (size_t) TM * D * 4, cudaMemcpyDeviceToHost); p += (size_t) TM * D;
cudaMemcpy(p, dlo, (size_t) TM * LR * 4, cudaMemcpyDeviceToHost); p += (size_t) TM * LR;
cudaMemcpy(p, drs, (size_t) TM * HC * 4, cudaMemcpyDeviceToHost); p += (size_t) TM * HC;
cudaMemcpy(p, dio, (size_t) TM * HC * 4, cudaMemcpyDeviceToHost); p += (size_t) TM * HC;
cudaMemcpy(p, dmix, (size_t) TM * N * 4, cudaMemcpyDeviceToHost);
}
const bool same = std::memcmp(out[0].data(), out[1].data(), out[0].size() * 4) == 0;
double us[2] = {1e30, 1e30};
for (int round = 0; round < 3; ++round)
for (int f = 0; f < 2; ++f) {
K::fused_gr_set_fast(f);
for (int i = 0; i < 20; ++i) K::fused_gr_read_multi(a, T, dxn, s);
cudaEventRecord(e0, s);
for (int i = 0; i < iters; ++i) K::fused_gr_read_multi(a, T, dxn, s);
cudaEventRecord(e1, s);
cudaEventSynchronize(e1);
float ms = 0;
cudaEventElapsedTime(&ms, e0, e1);
us[f] = std::fmin(us[f], 1e3 * ms / iters);
}
std::printf("T %d apply %d inject %d | old %6.1f us fast %6.1f us | %s\n", T, apply, inject, us[0], us[1],
same ? "bitwise equal" : "DIFFERS");
if (!same) ++failures;
}
std::printf("fused_gr_bench: %d differing\n", failures);
return failures ? 1 : 0;
}
+1 -1
View File
@@ -329,7 +329,7 @@ int main() {
float* d_at4 = dalloc<float>((size_t) QH * D);
const bool took = k::qsa_prompt_attn_batch(d_q, pools, d_ids, d_step, cells, s, d_at4, 1, nullptr);
if (!took) {
#if defined(STRATA_USE_HIP)
#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)
// AMD: the tensor-core prompt path is CUDA-only, so it refuses every pool and the old kernel runs
std::printf("[5/5] qsa_prompt_attn mode 3: PASS (refused on HIP - the old kernel runs)\n");
#else
+12
View File
@@ -36,6 +36,8 @@
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#include <random>
#include <vector>
@@ -236,6 +238,16 @@ int main() {
}
// THE NEGATIVE CONTROL, asserted where it can see something: past T = 4 the generic layout is a different one,
// so if it still finds no difference the comparison cannot tell the layouts apart and the pass proves nothing.
#if defined(STRATA_HIP_GFX906)
// gfx906: the wave64 layout (one wavefront per row) is the same kernel for every column count, so multi_exact
// has nothing to switch and the control cannot see a difference. The control with power is the CUDA layout:
// ctest's mmvq_multi_parity_cuda_layout runs this with STRATA_MMVQ_WAVE=0.
if (off.powerless_cases != 0 && !(std::getenv("STRATA_MMVQ_WAVE") && std::string(std::getenv("STRATA_MMVQ_WAVE")) == "0")) {
std::printf("\nmmvq_multi_parity: ok (gfx906 wave64 layout: every column count runs the same exact kernel, "
"so the negative control has no other layout to find; mmvq_multi_parity_cuda_layout checks it).\n");
return 0;
}
#endif
if (off.powerless_cases != 0) {
std::printf("\nmmvq_multi_parity: FAILED (no power). In %d case(s) no output differs with multi_exact off at "
"any T > %d, where the generic layout is not the exact one: for those cases this comparison "
+170
View File
@@ -0,0 +1,170 @@
// src/kernels/native_expert_bench.cpp - the grouped native experts on real GGUF rows: one AMD layout against
// another, bit for bit, and each one's time.
//
// build/native_expert_bench <shard1.gguf> <layer[,layer...]> <groups> <tokens per group> <ref mode> <mode> [iters]
//
// Modes are STRATA_EXP_MODE values. A group is one expert (distinct blobs, ~2 MB each, so G >= 8 does not fit
// in L2); its entries read distinct tokens of an 8-token window. The output must be bitwise equal to the
// reference mode's: the verify window's text depends on it.
#include "strata/artifact/gguf_reader.hpp"
#include "strata/kernels/cpu/native_expert.hpp"
#include "strata/kernels/iq_kernels.hpp"
#include "ggml.h"
#include <cuda_runtime.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <sstream>
#include <string>
#include <vector>
namespace cpu = strata::kernels::cpu;
namespace K = strata::kernels;
int main(int argc, char** argv) {
setvbuf(stdout, nullptr, _IONBF, 0);
if (argc < 7) {
std::fprintf(stderr, "usage: native_expert_bench <shard1.gguf> <layer[,layer]> <groups> <tokens> <ref mode> <mode> [iters]\n");
return 2;
}
strata::GgufFile gguf(argv[1]);
std::vector<int> layers;
{
std::stringstream ss(argv[2]);
std::string t;
while (std::getline(ss, t, ',')) layers.push_back(std::atoi(t.c_str()));
}
const int G = std::atoi(argv[3]), T = std::atoi(argv[4]), mref = std::atoi(argv[5]), mode = std::atoi(argv[6]);
const int iters = argc > 7 ? std::atoi(argv[7]) : 200;
const int NTOK = 8;
if (T < 1 || T > NTOK || G < 1) { std::fprintf(stderr, "tokens 1..8, groups >= 1\n"); return 2; }
const int64_t H = 2560, FF_FULL = 640, FF = FF_FULL; // Flash-Next's expert geometry
int failures = 0;
cudaStream_t s;
cudaStreamCreate(&s);
cudaEvent_t e0, e1;
cudaEventCreate(&e0);
cudaEventCreate(&e1);
for (int l : layers) {
const strata::TensorInfo* t[3] = {};
const char* roles[3] = {"gate", "up", "down"};
for (const auto& ti : gguf.tensors())
for (int r = 0; r < 3; ++r)
if (ti.name == "blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight") t[r] = &ti;
if (!t[0] || !t[1] || !t[2]) { std::printf("layer %d: no expert tensors\n", l); ++failures; continue; }
cpu::NativeFmt f;
std::string err;
if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, H, FF, f, err)) {
std::printf("layer %d: %s\n", l, err.c_str()); ++failures; continue;
}
cpu::NativeFmt ff; // the full expert's geometry, for strides into the GGUF
if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, H, FF_FULL, ff, err)) {
std::printf("layer %d: %s\n", l, err.c_str()); ++failures; continue;
}
const size_t dsz = f.bytes - f.down_off, dsz_full = ff.bytes - ff.down_off;
const size_t drow = dsz / H, drow_full = dsz_full / H;
std::vector<uint8_t> blobs((size_t) G * f.bytes);
for (int g = 0; g < G; ++g) {
const size_t E = (size_t) ((g * 37 + 5) % 256);
uint8_t* b = blobs.data() + (size_t) g * f.bytes;
std::memcpy(b, gguf.tensor_data(*t[0]) + E * ff.up_off, f.up_off);
std::memcpy(b + f.up_off, gguf.tensor_data(*t[1]) + E * ff.up_off, f.up_off);
for (int64_t r = 0; r < H; ++r)
std::memcpy(b + f.down_off + r * drow, gguf.tensor_data(*t[2]) + E * dsz_full + r * drow_full, drow);
}
std::mt19937 rng(17 + l);
std::normal_distribution<float> nd(0.f, 1.f);
std::vector<float> x((size_t) NTOK * H);
for (auto& v : x) v = nd(rng);
const int NE = G * T;
std::vector<unsigned long long> ptr(G);
std::vector<int32_t> start(G + 1), dst(NE), tok(NE);
const auto L = K::native_expert_layout(f.gu_type, f.d_type, H, FF);
uint8_t* dblob;
void *dx, *dxq, *dscr;
float* dout;
unsigned long long* dptr;
int32_t *dstart, *dn, *ddst, *dtok;
cudaMalloc((void**) &dblob, blobs.size());
cudaMalloc(&dx, x.size() * 4);
cudaMalloc(&dxq, (size_t) NTOK * H / 32 * 36);
cudaMalloc(&dscr, K::native_expert_scratch_bytes(NE, FF));
cudaMalloc((void**) &dout, (size_t) NE * H * 4);
cudaMalloc((void**) &dptr, (size_t) G * 8);
cudaMalloc((void**) &dstart, (size_t) (G + 1) * 4);
cudaMalloc((void**) &dn, 4);
cudaMalloc((void**) &ddst, (size_t) NE * 4);
cudaMalloc((void**) &dtok, (size_t) NE * 4);
for (int g = 0; g < G; ++g) {
ptr[g] = (unsigned long long) (dblob + (size_t) g * f.bytes);
start[g] = g * T;
for (int j = 0; j < T; ++j) {
dst[g * T + j] = g * T + j;
tok[g * T + j] = (g * 3 + j) % NTOK;
}
}
start[G] = NE;
cudaMemcpy(dblob, blobs.data(), blobs.size(), cudaMemcpyHostToDevice);
cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice);
cudaMemcpy(dptr, ptr.data(), (size_t) G * 8, cudaMemcpyHostToDevice);
cudaMemcpy(dstart, start.data(), (size_t) (G + 1) * 4, cudaMemcpyHostToDevice);
cudaMemcpy(dn, &G, 4, cudaMemcpyHostToDevice);
cudaMemcpy(ddst, dst.data(), (size_t) NE * 4, cudaMemcpyHostToDevice);
cudaMemcpy(dtok, tok.data(), (size_t) NE * 4, cudaMemcpyHostToDevice);
K::quantize_q8_1_rows((const float*) dx, NTOK, H, dxq, s);
auto run = [&](int m, int phase) {
K::native_expert_set_mode(m, phase);
K::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, G, NE, dxq, dscr, dout, s);
};
std::vector<float> ref((size_t) NE * H), got((size_t) NE * H);
cudaMemsetAsync(dout, 0xff, got.size() * 4, s);
run(mref, 0);
cudaMemcpyAsync(ref.data(), dout, ref.size() * 4, cudaMemcpyDeviceToHost, s);
cudaMemsetAsync(dout, 0xff, got.size() * 4, s);
run(mode, 0);
cudaMemcpyAsync(got.data(), dout, got.size() * 4, cudaMemcpyDeviceToHost, s);
if (cudaStreamSynchronize(s) != cudaSuccess) { std::printf("layer %d: CUDA error\n", l); return 1; }
size_t ndiff = 0;
double worst = 0;
for (size_t i = 0; i < ref.size(); ++i)
if (std::memcmp(&ref[i], &got[i], 4) != 0) {
++ndiff;
worst = std::fmax(worst, std::fabs((double) ref[i] - got[i]) / (std::fabs((double) ref[i]) + 1e-6));
}
auto time = [&](int m, int phase) {
for (int i = 0; i < 10; ++i) run(m, phase);
cudaEventRecord(e0, s);
for (int i = 0; i < iters; ++i) run(m, phase);
cudaEventRecord(e1, s);
cudaEventSynchronize(e1);
float ms = 0;
cudaEventElapsedTime(&ms, e0, e1);
return 1e3 * ms / iters;
};
const double gu_b = (double) G * 2 * f.up_off, d_b = (double) G * dsz;
double us[2][3] = {{1e30, 1e30, 1e30}, {1e30, 1e30, 1e30}};
for (int round = 0; round < 3; ++round) // interleaved, the minimum: the clocks wander between runs
for (int k = 0; k < 2; ++k)
for (int p = 0; p < 3; ++p) us[k][p] = std::fmin(us[k][p], time(k ? mode : mref, p));
std::printf("layer %2d %-7s/%-6s G %d T %d | mode %d: all %7.1f us gu %7.1f us (%3.0f GB/s) down %6.1f us (%3.0f GB/s)"
" | mode %d: all %7.1f us gu %7.1f us (%3.0f GB/s) down %6.1f us (%3.0f GB/s) | %s\n",
l, ggml_type_name((ggml_type) f.gu_type), ggml_type_name((ggml_type) f.d_type), G, T,
mref, us[0][0], us[0][1], gu_b / us[0][1] / 1e3, us[0][2], d_b / us[0][2] / 1e3,
mode, us[1][0], us[1][1], gu_b / us[1][1] / 1e3, us[1][2], d_b / us[1][2] / 1e3,
ndiff ? "DIFFERS" : "bitwise equal");
if (ndiff) {
std::printf(" %zu of %zu outputs differ, worst rel %.2e\n", ndiff, ref.size(), worst);
++failures;
}
K::native_expert_set_mode(-1, 0);
cudaFree(dblob); cudaFree(dx); cudaFree(dxq); cudaFree(dscr); cudaFree(dout); cudaFree(dptr);
cudaFree(dstart); cudaFree(dn); cudaFree(ddst); cudaFree(dtok);
}
std::printf("native_expert_bench: %d differing\n", failures);
return failures ? 1 : 0;
}
+12
View File
@@ -41,6 +41,18 @@ float h2f(uint16_t b) { __half h; *reinterpret_cast<uint16_t*>(&h) = b; return _
uint16_t f2h(float f) { __half h = __float2half(f); return *reinterpret_cast<uint16_t*>(&h); }
int run(int fmt, int64_t ctx, int64_t nq, int reps) { // fmt 1 int8, 0 fp16, 2 q4_0
#if !defined(__HIPCC__) && !defined(STRATA_USE_HIP)
if (fmt == 2) { // mode 4 (Q4_0 KV) runs on sm_80 and newer only: below that the dispatcher keeps the old kernel
int dev = 0, major = 0;
ck(cudaGetDevice(&dev), "device");
ck(cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev), "cc");
if (major < 8) {
std::printf("SKIP q4_0 ctx %lld: the tensor-core kernel takes Q4_0 KV on sm_80+ only (this device: sm_%d)\n",
(long long) ctx, major);
return 0;
}
}
#endif
const k::QsaShapes s = k::qsa_real_shapes();
const int64_t HD = s.head_dim, NKV = s.n_head_kv, NH = s.n_head, PS = s.page_size;
const int64_t pages = (ctx + PS - 1) / PS, rows = pages * NKV * PS;
+75
View File
@@ -0,0 +1,75 @@
// route_window_parity - the verify window's batched routing against the per-token calls, bit for bit.
//
// `moe_route_window` replaces n per-token (projection + top-k) pairs by one multi-column BF16 projection and one
// n-token top-k. Speculative decoding is exact only if a token's route does not depend on how many tokens share
// its window, so both batched kernels must equal their one-token forms exactly - this checks that on random data
// shaped like the router (2560 -> 256, top-10) and like the shared-expert gate (2560 -> 1).
#include "strata/kernels/bf16_gemv.hpp"
#include "strata/kernels/router_top10.hpp"
#include <cuda_runtime.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <random>
#include <vector>
namespace {
void ck(cudaError_t e, const char* what) {
if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); std::exit(2); }
}
uint16_t bf16(float f) { uint32_t i; std::memcpy(&i, &f, 4); return (uint16_t) ((i + ((i >> 16) & 1u) + 0x7FFFu) >> 16); }
} // namespace
int main() {
const int N = 2560, E = 256, K = 10;
int bad = 0;
std::mt19937 rng(7);
std::normal_distribution<float> nd(0.0f, 1.0f);
for (int n_out : {E, 1}) {
for (int T : {2, 3, 4, 6}) {
std::vector<uint16_t> w((size_t) n_out * N);
std::vector<float> x((size_t) T * N);
for (auto& v : w) v = bf16(nd(rng) * 0.05f);
for (auto& v : x) v = nd(rng);
uint16_t* dw; float *dx, *dy1, *dyn;
ck(cudaMalloc(&dw, w.size() * 2), "w"); ck(cudaMalloc(&dx, x.size() * 4), "x");
ck(cudaMalloc(&dy1, (size_t) T * n_out * 4), "y1"); ck(cudaMalloc(&dyn, (size_t) T * n_out * 4), "yn");
ck(cudaMemcpy(dw, w.data(), w.size() * 2, cudaMemcpyHostToDevice), "up w");
ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "up x");
for (int t = 0; t < T; ++t)
strata::kernels::bf16_gemv_fp32_mmvf(dx + (size_t) t * N, dw, dy1 + (size_t) t * n_out, N, n_out, nullptr);
strata::kernels::bf16_gemv_fp32_mmvf_cols(dx, dw, dyn, N, n_out, T, nullptr);
ck(cudaDeviceSynchronize(), "sync");
std::vector<float> y1((size_t) T * n_out), yn((size_t) T * n_out);
ck(cudaMemcpy(y1.data(), dy1, y1.size() * 4, cudaMemcpyDeviceToHost), "down 1");
ck(cudaMemcpy(yn.data(), dyn, yn.size() * 4, cudaMemcpyDeviceToHost), "down n");
const bool same = std::memcmp(y1.data(), yn.data(), y1.size() * 4) == 0;
std::printf(" mmvf cols n_out %3d T %d %s\n", n_out, T, same ? "bit-identical" : "*** DIFFERS ***");
if (!same) ++bad;
if (n_out == E) {
int *i1, *in_; float *w1, *wn;
ck(cudaMalloc(&i1, (size_t) T * K * 4), "i1"); ck(cudaMalloc(&in_, (size_t) T * K * 4), "in");
ck(cudaMalloc(&w1, (size_t) T * K * 4), "w1"); ck(cudaMalloc(&wn, (size_t) T * K * 4), "wn");
for (int t = 0; t < T; ++t)
strata::kernels::router_top10(dy1 + (size_t) t * E, 1, E, K, i1 + t * K, w1 + t * K, nullptr);
strata::kernels::router_top10(dy1, T, E, K, in_, wn, nullptr);
ck(cudaDeviceSynchronize(), "sync top");
std::vector<int> a((size_t) T * K), b((size_t) T * K);
std::vector<float> fa((size_t) T * K), fb((size_t) T * K);
ck(cudaMemcpy(a.data(), i1, a.size() * 4, cudaMemcpyDeviceToHost), "ids1");
ck(cudaMemcpy(b.data(), in_, b.size() * 4, cudaMemcpyDeviceToHost), "idsn");
ck(cudaMemcpy(fa.data(), w1, fa.size() * 4, cudaMemcpyDeviceToHost), "w1");
ck(cudaMemcpy(fb.data(), wn, fb.size() * 4, cudaMemcpyDeviceToHost), "wn");
const bool s2 = a == b && std::memcmp(fa.data(), fb.data(), fa.size() * 4) == 0;
std::printf(" top10 n T %d %s\n", T, s2 ? "bit-identical" : "*** DIFFERS ***");
if (!s2) ++bad;
cudaFree(i1); cudaFree(in_); cudaFree(w1); cudaFree(wn);
}
cudaFree(dw); cudaFree(dx); cudaFree(dy1); cudaFree(dyn);
}
}
std::printf(bad ? "route_window_parity: %d FAILURES\n" : "route_window_parity OK\n", bad);
return bad ? 1 : 0;
}
+124
View File
@@ -3,8 +3,12 @@
#include "strata/kernels/dequant_bf16.hpp"
#include <cublas_v2.h>
#include <cuda_fp16.h>
#include <cuda_runtime.h>
#include <algorithm>
#include <atomic>
#if defined(__HIPCC__) && defined(STRATA_HIPBLASLT_AVAILABLE)
// The HIP compatibility shim maps CUDA shuffle spellings to Strata helpers.
// hipBLASLt's public headers declare native HIP shuffle functions, so keep
@@ -298,6 +302,8 @@ Gemm::~Gemm() {
delete static_cast<HipLtState*>(hipblaslt_state_);
#endif
if (handle_) cublasDestroy((cublasHandle_t) handle_);
if (tc_w_) cudaFree(tc_w_);
if (tc_x_) cudaFree(tc_x_);
if (!external_) {
if (scratch_) cudaFree(scratch_);
if (workspace_) cudaFree(workspace_);
@@ -372,6 +378,89 @@ bool Gemm::init(void* stream, int64_t scratch_elems, std::string& err) {
return true;
}
#if !defined(__HIPCC__)
// ---- below sm_80: BF16 GEMMs without BF16 tensor cores (PR #655, #540, #395) ----------------------------------------
// Turing and Volta have no BF16 tensor cores: cublasGemmEx on CUDA_R_16BF inputs falls back to a SIMT fp32 kernel
// (magma_sgemmEx), a fifth of a 4K prompt on an RTX 2080 Ti (#655) and ~10% of a V100's prompt (#540). BF16 -> FP16
// is exact for every value inside FP16's normal range (the 7-bit mantissa fits in 10 bits); weights and normalized
// activations sit there. With the FP16 path, the weight is converted once per call and the activations in row
// slices, into the instance's own buffers, and the product runs as the FP16 GEMM (fp32 accumulate) on the tensor
// cores. Finite values beyond FP16's range are clamped to +-65504 (#540) instead of becoming Inf. A beta = 1
// product (STRATA_PREFILL_BF16X2's remainder, ~2^-9 of the original, deep in FP16's subnormal band) keeps cuBLAS.
// Default: on for compute capability 7.0 - 7.4 (Volta: only the experimental STRATA_EXPERIMENTAL_SM60 build runs
// there), OFF for 7.5 (RTX 20 in the ready-made engine: the sums round differently, so it is opt-in until it has
// been gated). STRATA_BF16_TC=1 / =0 turns it on / off on any 7.x card (=2, a test mode: on any card).
// Pascal (6.x) has no tensor cores and cuBLAS has no BF16 GEMM for it (#395, measured NOT_SUPPORTED on a P40): both
// operands are widened to fp32 by an exact shift and the product is cublasSgemm with the same fp32 accumulator.
namespace {
__global__ void bf16_to_f16_kernel(const uint16_t* __restrict__ in, __half* __restrict__ out, int64_t n) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
float f = __uint_as_float((uint32_t) in[i] << 16);
if (f > 65504.0f && !isinf(f)) f = 65504.0f;
else if (f < -65504.0f && !isinf(f)) f = -65504.0f;
out[i] = __float2half_rn(f);
}
}
void bf16_to_f16(const uint16_t* in, uint16_t* out, int64_t n, cudaStream_t st) {
if (n <= 0) return;
bf16_to_f16_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, st>>>(in, reinterpret_cast<__half*>(out), n);
}
#if defined(STRATA_EXPERIMENTAL_SM60) // Pascal runs only the experimental build
__global__ void bf16_to_f32_kernel(const uint16_t* __restrict__ in, float* __restrict__ out, int64_t n) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) out[i] = __uint_as_float((uint32_t) in[i] << 16);
}
void bf16_to_f32(const uint16_t* in, float* out, int64_t n, cudaStream_t st) {
if (n <= 0) return;
bf16_to_f32_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, st>>>(in, out, n);
}
#endif
// The current device's compute capability as 10 * major + minor, per device (a layer split can mix cards); 0: not
// known, read as "not an old card" so a failed query keeps the cuBLAS BF16 call.
int current_cc() {
static std::atomic<int> cc[64] = {};
int dev = 0;
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return 0; }
int v = cc[dev].load(std::memory_order_relaxed);
if (v == 0) {
int major = 0, minor = 0;
if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess ||
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) {
cudaGetLastError();
return 0;
}
v = 10 * major + minor;
cc[dev].store(v, std::memory_order_relaxed);
}
return v;
}
// 0: cuBLAS's BF16 GEMM, 1: through FP16 (tensor cores), 2: through FP32 (Pascal)
int bf16_path() {
static const int forced = [] {
const char* v = std::getenv("STRATA_BF16_TC");
return v != nullptr && v[0] != '\0' ? std::atoi(v) : -1;
}();
const int cc = current_cc();
if (forced == 2 && cc > 0) return 1; // a test mode: the FP16 path on any card (gemm_bf16_parity on sm_80+)
if (cc <= 0 || cc >= 80) return 0;
if (cc < 70) return 2;
if (forced >= 0) return forced != 0 ? 1 : 0;
return cc < 75 ? 1 : 0;
}
bool grow(uint16_t*& p, int64_t& have, int64_t want) { // `have`, `want`: 2-byte elements
if (have >= want) return true;
if (p) cudaFree(p);
p = nullptr;
have = 0;
if (cudaMalloc((void**) &p, (size_t) want * 2) != cudaSuccess) { cudaGetLastError(); p = nullptr; return false; }
have = want;
return true;
}
constexpr int64_t kXSliceElems = 16ll << 20; // 32 MiB of FP16 activations per slice (64 MiB as fp32)
} // namespace
#endif
void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy,
float beta) {
if (T <= 0 || N <= 0) return;
@@ -383,6 +472,41 @@ void Gemm::bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64
STRATA_ABSORB_HIPBLAS_STICKY("hipBLASLt bf16");
return;
}
#endif
#if !defined(__HIPCC__)
if (const int path = K > 0 ? bf16_path() : 0; path == 1 && N > 1 && beta == 0.0f) {
// a single output row stays cuBLAS's GEMV, faster than the conversions; beta = 1: see above
const int64_t x_rows = std::max<int64_t>(1, std::min<int64_t>(T, kXSliceElems / K));
if (grow(tc_w_, tc_w_elems_, N * K) && grow(tc_x_, tc_x_elems_, x_rows * K)) {
bf16_to_f16(W, tc_w_, N * K, (cudaStream_t) stream_);
for (int64_t t0 = 0; t0 < T; t0 += x_rows) {
const int64_t n = std::min<int64_t>(x_rows, T - t0);
bf16_to_f16(X + t0 * K, tc_x_, n * K, (cudaStream_t) stream_);
f16(tc_x_, tc_w_, Y + t0 * ldy, n, N, K, ldy, beta);
}
return;
}
}
#if defined(STRATA_EXPERIMENTAL_SM60)
else if (path == 2) {
// Pascal: fp32 copies (2 elements of the 2-byte buffers each). Every tile is a disjoint block of Y, so each
// gets the caller's beta.
const int64_t x_rows = std::max<int64_t>(1, std::min<int64_t>(T, kXSliceElems / K));
if (grow(tc_w_, tc_w_elems_, 2 * N * K) && grow(tc_x_, tc_x_elems_, 2 * x_rows * K)) {
float* const wf = reinterpret_cast<float*>(tc_w_);
float* const xf = reinterpret_cast<float*>(tc_x_);
bf16_to_f32(W, wf, N * K, (cudaStream_t) stream_);
for (int64_t t0 = 0; t0 < T; t0 += x_rows) {
const int64_t n = std::min<int64_t>(x_rows, T - t0);
bf16_to_f32(X + t0 * K, xf, n * K, (cudaStream_t) stream_);
ck(cublasSgemm((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) n, (int) K, &alpha,
wf, (int) K, xf, (int) K, &beta, Y + t0 * ldy, (int) ldy),
"cublasSgemm (bf16 on Pascal)");
}
return;
}
}
#endif
#endif
// Column-major view: Y^T[N, T] = W[N, K] (stored K x N col-major, transposed) . X^T[K, T].
ck(cublasGemmEx((cublasHandle_t) handle_, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) T, (int) K, &alpha, W,
+155
View File
@@ -0,0 +1,155 @@
// src/prefill/gemm_bf16_parity.cu - Gemm::bf16 against cuBLAS's own BF16 product (GPU, synthetic, no model).
//
// Below sm_80 (no BF16 tensor cores) Gemm::bf16 converts the weight and the activations to FP16 and runs the FP16
// tensor-core GEMM (Volta by default, Turing with STRATA_BF16_TC=1) or widens them to fp32 (Pascal); everywhere else
// it is the cuBLAS BF16 call itself. (On Pascal the cuBLAS BF16 reference itself may be refused: the test then fails
// at the reference, which says so.) This
// checks the result against cublasGemmEx on the same BF16 inputs, within fp32-accumulation rounding, over the prompt
// path's shapes: the hyper-connection down / up projections, the router and indexer rows, the PLE value matrix, a T
// large enough to slice the activations, beta = 1 accumulation (the bf16x2 low parts) and an output row stride wider
// than N. --bench adds the time of each against the cuBLAS BF16 product.
#include "strata/prefill/gemm.hpp"
#include <cublas_v2.h>
#include <cuda_runtime.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <random>
#include <string>
#include <vector>
namespace {
uint16_t to_bf16(float f) { // round to nearest even
uint32_t u;
std::memcpy(&u, &f, 4);
u += 0x7fffu + ((u >> 16) & 1u);
return (uint16_t) (u >> 16);
}
bool ok_or(cudaError_t e, const char* what) {
if (e != cudaSuccess) std::printf("FAIL: %s: %s\n", what, cudaGetErrorString(e));
return e == cudaSuccess;
}
struct Shape {
int64_t T, N, K, ldy;
const char* what;
};
} // namespace
int main(int argc, char** argv) {
const bool bench = argc > 1 && std::string(argv[1]) == "--bench";
int dev = 0, maj = 0, min = 0;
cudaGetDevice(&dev);
cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev);
cudaDeviceGetAttribute(&min, cudaDevAttrComputeCapabilityMinor, dev);
std::printf("gemm_bf16_parity: compute capability %d.%d\n", maj, min);
cudaStream_t st = nullptr;
if (!ok_or(cudaStreamCreate(&st), "stream")) return 1;
strata::prefill::Gemm gemm;
std::string err;
if (!gemm.init(st, 0, err)) { std::printf("FAIL: %s\n", err.c_str()); return 1; }
cublasHandle_t h = nullptr;
if (cublasCreate(&h) != CUBLAS_STATUS_SUCCESS) { std::printf("FAIL: cublasCreate\n"); return 1; }
cublasSetStream(h, st);
const Shape shapes[] = {
{4096, 320, 10240, 0, "hc down (activations sliced)"},
{4096, 10240, 320, 0, "hc up"},
{777, 2560, 2560, 0, "PLE value"},
{512, 512, 2560, 0, "router / indexer q"},
{300, 4, 10240, 0, "hc inject"},
{2048, 1, 2560, 0, "single row"},
{333, 128, 2560, 136, "row stride wider than N"},
};
std::mt19937 rng(1234);
std::normal_distribution<float> nd(0.0f, 1.0f);
int failures = 0;
for (const Shape& s : shapes) {
const int64_t ldy = s.ldy > 0 ? s.ldy : s.N;
std::vector<uint16_t> x((size_t) (s.T * s.K)), xlo(x.size()), w((size_t) (s.N * s.K));
for (size_t i = 0; i < x.size(); ++i) {
const float v = 3.0f * nd(rng); // activations: normalized, a few units
x[i] = to_bf16(v);
xlo[i] = to_bf16(1e-3f * nd(rng)); // a bf16x2 low part
}
for (auto& v : w) v = to_bf16(0.02f * nd(rng));
uint16_t *dx = nullptr, *dxlo = nullptr, *dw = nullptr;
float *dy = nullptr, *dr = nullptr;
const size_t ybytes = (size_t) (s.T * ldy) * 4;
bool ok = ok_or(cudaMalloc((void**) &dx, x.size() * 2), "x") && ok_or(cudaMalloc((void**) &dxlo, x.size() * 2), "xlo") &&
ok_or(cudaMalloc((void**) &dw, w.size() * 2), "w") && ok_or(cudaMalloc((void**) &dy, ybytes), "y") &&
ok_or(cudaMalloc((void**) &dr, ybytes), "ref");
if (!ok) return 1;
cudaMemcpy(dx, x.data(), x.size() * 2, cudaMemcpyHostToDevice);
cudaMemcpy(dxlo, xlo.data(), xlo.size() * 2, cudaMemcpyHostToDevice);
cudaMemcpy(dw, w.data(), w.size() * 2, cudaMemcpyHostToDevice);
cudaMemset(dy, 0, ybytes);
cudaMemset(dr, 0, ybytes);
// the product under test: X . W^T, then the low part added with beta = 1
gemm.bf16(dx, dw, dy, s.T, s.N, s.K, ldy);
gemm.bf16(dxlo, dw, dy, s.T, s.N, s.K, ldy, 1.0f);
// the reference: cuBLAS on the BF16 inputs, the same two calls
const float one = 1.0f, zero = 0.0f;
auto ref = [&](const uint16_t* X, float beta) {
return cublasGemmEx(h, CUBLAS_OP_T, CUBLAS_OP_N, (int) s.N, (int) s.T, (int) s.K, &one, dw, CUDA_R_16BF,
(int) s.K, X, CUDA_R_16BF, (int) s.K, &beta, dr, CUDA_R_32F, (int) ldy,
CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT);
};
if (ref(dx, zero) != CUBLAS_STATUS_SUCCESS || ref(dxlo, one) != CUBLAS_STATUS_SUCCESS) {
std::printf("FAIL: reference cublasGemmEx\n");
return 1;
}
if (!ok_or(cudaStreamSynchronize(st), "sync")) return 1;
std::vector<float> y((size_t) (s.T * ldy)), r(y.size());
cudaMemcpy(y.data(), dy, ybytes, cudaMemcpyDeviceToHost);
cudaMemcpy(r.data(), dr, ybytes, cudaMemcpyDeviceToHost);
double worst = 0.0, mag = 1e-30;
int bad = 0;
for (int64_t t = 0; t < s.T; ++t)
for (int64_t c = 0; c < s.N; ++c) {
const float a = y[(size_t) (t * ldy + c)], b = r[(size_t) (t * ldy + c)];
if (!std::isfinite(a)) ++bad;
worst = std::max(worst, (double) std::fabs(a - b));
mag = std::max(mag, (double) std::fabs(b));
}
// the untouched columns of a wider row stride stay as they were
for (int64_t t = 0; t < s.T && ldy > s.N; ++t)
for (int64_t c = s.N; c < ldy; ++c)
if (y[(size_t) (t * ldy + c)] != 0.0f) ++bad;
const bool pass = bad == 0 && worst <= 1e-4 * mag;
if (!pass) ++failures;
std::printf(" %-32s T %5lld N %5lld K %5lld ldy %5lld: worst |diff| %.3e of max |ref| %.3e (rel %.2e) %s\n",
s.what, (long long) s.T, (long long) s.N, (long long) s.K, (long long) ldy, worst, mag, worst / mag,
pass ? "pass" : "FAIL");
if (bench) {
auto time = [&](auto&& f) {
for (int i = 0; i < 3; ++i) f();
cudaStreamSynchronize(st);
const auto t0 = std::chrono::steady_clock::now();
for (int i = 0; i < 20; ++i) f();
cudaStreamSynchronize(st);
return std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count() / 20;
};
const double us_gemm = time([&] { gemm.bf16(dx, dw, dy, s.T, s.N, s.K, ldy); });
const double us_ref = time([&] { ref(dx, zero); });
std::printf(" bench: Gemm::bf16 %9.1f us cuBLAS BF16 %9.1f us (%.2fx)\n", us_gemm, us_ref,
us_ref / us_gemm);
}
cudaFree(dx); cudaFree(dxlo); cudaFree(dw); cudaFree(dy); cudaFree(dr);
}
cublasDestroy(h);
cudaStreamDestroy(st);
std::printf("gemm_bf16_parity: %d failures\n", failures);
return failures == 0 ? 0 : 1;
}
+6
View File
@@ -364,6 +364,11 @@ const DevInfo& dev_info() {
DevInfo& d = g_dev[dev & 31];
if (d.done) return d;
d.done = true;
#if defined(STRATA_HIP_GFX906)
// gfx906 reports compute capability 9.0 through HIP, but the mma.sync bodies above are CUDA sm_80+ only and
// empty in a hipcc build: never available here (the prompt path keeps its own expert GEMMs)
return d;
#else
int major = 0, minor = 0;
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
@@ -385,6 +390,7 @@ const DevInfo& dev_info() {
cudaOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_d, expert_kernel<false>, THREADS, smem_bytes(false));
if (d.occ_gu < 1 || d.occ_d < 1) d.cc = 0; // does not fit this card: the MMQ path
cudaGetLastError();
#endif
return d;
}
+8
View File
@@ -516,6 +516,7 @@ struct DevInfo {
std::mutex g_mu;
DevInfo g_dev[32];
#if !defined(STRATA_HIP_GFX906)
template <int T, bool GU, int WW> bool setup_ww(int& occ) {
cudaFuncAttributes fa{};
if (cudaFuncGetAttributes(&fa, native_kernel<T, GU, WW>) != cudaSuccess || fa.ptxVersion < 80) return false;
@@ -530,6 +531,7 @@ template <int T, bool GU, int WW> bool setup_ww(int& occ) {
return true;
}
template <int T, bool GU> bool setup_one(int& occ) { return setup_ww<T, GU, 4>(occ) && setup_ww<T, GU, 2>(occ); }
#endif
const DevInfo& dev_info() {
int dev = 0;
@@ -538,6 +540,11 @@ const DevInfo& dev_info() {
DevInfo& d = g_dev[dev & 31];
if (d.done) return d;
d.done = true;
#if defined(STRATA_HIP_GFX906)
// gfx906 reports compute capability 9.0 through HIP, but the mma.sync bodies above are CUDA sm_80+ only and
// empty in a hipcc build: never available here (the prompt path keeps its own expert GEMMs)
return d;
#else
int major = 0;
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev);
@@ -548,6 +555,7 @@ const DevInfo& dev_info() {
setup_one<T_Q2_0, false>(occ) && setup_one<T_IQ4_NL, false>(occ);
d.occ = d.ok ? occ : 1;
cudaGetLastError();
#endif
return d;
}
+2
View File
@@ -2985,6 +2985,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
{ // #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;
@@ -2995,6 +2996,7 @@ int main(int argc, char** argv) {
"toolkit>, with its libcudart.so present) (#542)\n",
CUDART_VERSION / 1000, CUDART_VERSION % 1000 / 10, rt / 1000, rt % 1000 / 10);
}
#endif
#endif
const std::string e = strata::core::device_code_error();
if (!e.empty()) {
+25 -5
View File
@@ -18,7 +18,7 @@
namespace {
constexpr int kLanes = 32;
constexpr int kIntegerResults = 7;
constexpr int kIntegerResults = 10;
__global__ void intrinsic_probe(int* integer_results, float* float_shuffle, double* double_shuffle,
unsigned* ballot, const uint32_t* dot_inputs) {
@@ -37,6 +37,20 @@ __global__ void intrinsic_probe(int* integer_results, float* float_shuffle, doub
__dp4a(static_cast<int>(dot_inputs[lane * 2]), static_cast<int>(dot_inputs[lane * 2 + 1]),
0x7fffffff - lane);
__shared__ int exchanged[kLanes];
int sum = 0;
for (int iteration = 0; iteration < 64; ++iteration) {
exchanged[lane] = static_cast<int>(dot_inputs[lane * 2] & 255u) + iteration;
__syncwarp();
sum += exchanged[lane ^ 1];
__syncwarp();
}
integer_results[lane * kIntegerResults + 7] = sum;
const int input_a = static_cast<int>(dot_inputs[lane * 2]);
const int input_b = static_cast<int>(dot_inputs[lane * 2 + 1]);
integer_results[lane * kIntegerResults + 8] = __dp4a(input_a, input_b, input_a);
integer_results[lane * kIntegerResults + 9] = __dp4a(input_a, input_b, input_b);
float_shuffle[lane * 4 + 0] = __shfl_xor_sync(mask, static_cast<float>(lane), 1);
float_shuffle[lane * 4 + 1] = static_cast<float>(__shfl_down_sync(mask, lane, 4, 8));
float_shuffle[lane * 4 + 2] = static_cast<float>(__shfl_up_sync(mask, lane, 1));
@@ -153,7 +167,7 @@ int main() {
CHECK(hipMemcpy(&ballot, device_ballot, sizeof(ballot), hipMemcpyDeviceToHost));
constexpr uint32_t a = 0x80ff017fu, b = 0x0203fe81u;
const uint32_t expected_integer[kIntegerResults - 1] = {
const uint32_t expected_integer[6] = {
static_cast<uint32_t>(dp4a_reference(a, b, 7)),
static_cast<uint32_t>(dp4a_reference(0x7f7f7f7fu, 0x7f7f7f7fu, std::numeric_limits<int>::max())),
byte_sub_reference(0x00ff0102u, 0x01010103u),
@@ -163,11 +177,17 @@ int main() {
};
bool ok = ballot == 0x55555555u;
for (int lane = 0; lane < kLanes; ++lane) {
for (int i = 0; i < kIntegerResults - 1; ++i)
for (int i = 0; i < 6; ++i)
ok = ok && static_cast<uint32_t>(integers[lane * kIntegerResults + i]) == expected_integer[i];
ok = ok && static_cast<uint32_t>(integers[lane * kIntegerResults + kIntegerResults - 1]) ==
ok = ok && static_cast<uint32_t>(integers[lane * kIntegerResults + 6]) ==
static_cast<uint32_t>(dp4a_reference(dot_inputs[lane * 2], dot_inputs[lane * 2 + 1],
0x7fffffff - lane));
ok = ok && integers[lane * kIntegerResults + 7] ==
64 * static_cast<int>(dot_inputs[(lane ^ 1) * 2] & 255u) + 2016;
for (int alias = 0; alias < 2; ++alias)
ok = ok && static_cast<uint32_t>(integers[lane * kIntegerResults + 8 + alias]) ==
static_cast<uint32_t>(dp4a_reference(dot_inputs[lane * 2], dot_inputs[lane * 2 + 1],
static_cast<int>(dot_inputs[lane * 2 + alias])));
ok = ok && float_shuffle[lane * 4 + 0] == static_cast<float>(lane ^ 1);
const int down = lane % 8 < 4 ? lane + 4 : lane;
ok = ok && float_shuffle[lane * 4 + 1] == static_cast<float>(down);
@@ -211,6 +231,6 @@ int main() {
std::fprintf(stderr, "HIP intrinsic parity failed (ballot 0x%08x)\n", ballot);
return 1;
}
std::puts("HIP intrinsics parity OK: dynamic signed dot4/overflow, byte permute, packed integer boundaries, wave32 shuffles, ballot and sleep");
std::puts("HIP intrinsics parity OK: dynamic signed dot4/overflow, byte permute, packed integer boundaries, wave32 shuffles, shared-memory exchange, ballot and sleep");
return 0;
}
+93
View File
@@ -0,0 +1,93 @@
// BF16/F16 prefill through the actual engine GEMM path against a CPU reference.
#include <hip/hip_runtime.h>
#include <hip/hip_bfloat16.h>
#include <hip/hip_fp16.h>
#include "strata/prefill/gemm.hpp"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <vector>
#define CHECK(call) do { const auto e = (call); if (e != hipSuccess) { \
std::fprintf(stderr, "%s: %s\n", #call, hipGetErrorString(e)); std::exit(2); } } while (0)
struct Buffer {
void* p = nullptr;
explicit Buffer(size_t bytes) { CHECK(hipMalloc(&p, bytes)); }
~Buffer() { if (p) (void) hipFree(p); }
};
bool run(strata::prefill::Gemm& gemm, hipStream_t stream, bool bf16,
int t, int n, int k, int ldy, float beta) {
std::mt19937 rng(51012 + t + n);
std::uniform_real_distribution<float> dist(-0.25f, 0.25f);
std::vector<uint16_t> x((size_t)t*k), w((size_t)n*k);
std::vector<float> xf(x.size()), wf(w.size());
auto fill = [&](auto& bits, auto& values) {
for (size_t i = 0; i < bits.size(); ++i) {
if (bf16) {
const hip_bfloat16 v(dist(rng));
bits[i] = v.data;
const uint32_t wide = static_cast<uint32_t>(v.data) << 16;
std::memcpy(&values[i], &wide, 4);
} else {
const __half v = __float2half_rn(dist(rng));
std::memcpy(&bits[i], &v, 2);
values[i] = __half2float(v);
}
}
};
fill(x, xf); fill(w, wf);
constexpr int offset = 5;
std::vector<float> initial(offset + (size_t)t*ldy + 8, -777.25f);
for (int r = 0; r < t; ++r) for (int c = 0; c < n; ++c)
initial[offset + (size_t)r*ldy + c] = (r+c)%17 * 0.03125f;
Buffer dx(x.size()*2), dw(w.size()*2), dy(initial.size()*4);
CHECK(hipMemcpyAsync(dx.p,x.data(),x.size()*2,hipMemcpyHostToDevice,stream));
CHECK(hipMemcpyAsync(dw.p,w.data(),w.size()*2,hipMemcpyHostToDevice,stream));
CHECK(hipMemcpyAsync(dy.p,initial.data(),initial.size()*4,hipMemcpyHostToDevice,stream));
if (bf16) gemm.bf16((const uint16_t*)dx.p,(const uint16_t*)dw.p,(float*)dy.p+offset,t,n,k,ldy,beta);
else gemm.f16((const uint16_t*)dx.p,(const uint16_t*)dw.p,(float*)dy.p+offset,t,n,k,ldy,beta);
CHECK(hipStreamSynchronize(stream));
std::vector<float> got(initial.size());
CHECK(hipMemcpy(got.data(),dy.p,got.size()*4,hipMemcpyDeviceToHost));
std::vector<bool> active(got.size());
double diff2=0, ref2=0, maximum=0;
bool ok=true;
for (int r=0;r<t;++r) for (int c=0;c<n;++c) {
const size_t j=offset+(size_t)r*ldy+c;
active[j]=true;
double ref=beta*initial[j];
for (int i=0;i<k;++i) ref+=(double)xf[(size_t)r*k+i]*wf[(size_t)c*k+i];
const double d=(double)got[j]-ref;
ok=ok && std::isfinite(got[j]);
diff2+=d*d; ref2+=ref*ref; maximum=std::max(maximum,std::abs(d));
}
for (size_t j=0;j<got.size();++j) if (!active[j]) ok=ok && got[j]==initial[j];
const double rel=std::sqrt(diff2/std::max(ref2,1e-300));
ok=ok && rel<1e-4 && maximum<5e-3;
std::printf("%s %s T=%d N=%d K=%d ldy=%d beta=%.1f rel_l2=%.3g max_abs=%.3g\n",
ok?"PASS":"FAIL",bf16?"BF16":"F16",t,n,k,ldy,beta,rel,maximum);
return ok;
}
int main() {
setvbuf(stdout,nullptr,_IONBF,0);
hipStream_t stream;
CHECK(hipStreamCreateWithFlags(&stream,hipStreamNonBlocking));
bool ok=true;
{
strata::prefill::Gemm gemm;
std::string error;
if (!gemm.init(stream,0,error)) { std::fprintf(stderr,"%s\n",error.c_str()); return 2; }
ok=run(gemm,stream,true,16,96,2560,96,0) && ok;
ok=run(gemm,stream,true,17,48,2560,64,1) && ok;
ok=run(gemm,stream,false,32,640,2560,648,0) && ok;
ok=run(gemm,stream,false,64,2560,640,2560,1) && ok;
}
CHECK(hipStreamDestroy(stream));
return ok?0:1;
}
+50
View File
@@ -0,0 +1,50 @@
// Q2_0 dequant must preserve signed zero when a negative scale meets code 1.
// This caught HIP 5.7/gfx1012 folding the half product to positive zero.
#include "strata/kernels/iq_kernels.hpp"
#include <hip/hip_runtime.h>
#include <hip/hip_fp16.h>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#define CHECK(call) do { const auto e = (call); if (e != hipSuccess) { \
std::fprintf(stderr, "%s: %s\n", #call, hipGetErrorString(e)); std::exit(2); } } while (0)
int main() {
// GGUF Q2_0: one half scale followed by sixteen packed 2-bit bytes.
struct Block { uint16_t d; uint8_t qs[16]; };
static_assert(sizeof(Block) == 18);
constexpr int blocks = 16, values = blocks * 64;
std::vector<Block> input(blocks);
std::vector<uint16_t> expected(values), got(values);
for (int b = 0; b < blocks; ++b) {
const float scale = (b & 1) ? -0.5f : 0.5f;
const __half half_scale = __float2half(scale);
std::memcpy(&input[b].d, &half_scale, 2);
for (int i = 0; i < 16; ++i) input[b].qs[i] = 0xe4; // codes 0,1,2,3
for (int i = 0; i < 64; ++i) {
const __half value = __float2half(scale * float((i % 4) - 1));
std::memcpy(&expected[b * 64 + i], &value, 2);
}
}
void* weights = nullptr;
uint16_t* output = nullptr;
CHECK(hipMalloc(&weights, input.size() * sizeof(Block)));
CHECK(hipMalloc(reinterpret_cast<void**>(&output), values * sizeof(uint16_t)));
CHECK(hipMemcpy(weights, input.data(), input.size() * sizeof(Block), hipMemcpyHostToDevice));
strata::kernels::iq_dequant_f16(42, weights, values, output, nullptr);
CHECK(hipDeviceSynchronize());
CHECK(hipMemcpy(got.data(), output, values * sizeof(uint16_t), hipMemcpyDeviceToHost));
int failures = 0;
for (int i = 0; i < values; ++i) {
if (got[i] == expected[i]) continue;
if (failures++ < 4)
std::printf("index=%d got=0x%04x expected=0x%04x\n", i, unsigned(got[i]), unsigned(expected[i]));
}
CHECK(hipFree(weights));
CHECK(hipFree(output));
std::printf("hip_q2_zero: %d values, %d failures\n", values, failures);
return failures ? 1 : 0;
}
+3
View File
@@ -76,6 +76,9 @@ class KfdDetection(unittest.TestCase):
self.assertTrue(setup.ROCM_INDEXES["gfx1200"].endswith("/gfx120X-all/"))
self.assertEqual(setup.ROCM_INDEXES["gfx1101"], setup.ROCM_INDEXES["gfx1100"])
self.assertEqual(setup.ROCM_INDEXES["gfx1200"], setup.ROCM_INDEXES["gfx1201"])
# #524: the RX 6700 XT (gfx1031) takes the RDNA2 wheels, as the RX 6800 / 6900 (gfx1030)
self.assertEqual(setup.ROCM_INDEXES["gfx1031"], setup.ROCM_INDEXES["gfx1030"])
self.assertIsNone(setup.amd_problem({"arch": "gfx1031"}))
class GpuLists(unittest.TestCase):
+2 -2
View File
@@ -162,8 +162,8 @@ class ExperimentalSm60(unittest.TestCase):
for arch in ("60", "61", "70"):
p = setup.gpu_problem(self.card(arch))
self.assertIn("not supported", p)
self.assertIn("STRATA_EXPERIMENTAL_SM60=1", p)
self.assertNotIn("STRATA_EXPERIMENTAL_SM60", setup.gpu_problem(self.card("52")))
self.assertIn("choose it with --gpu 0", p) # the CUDA 12 engine (docs/OLDER_GPUS.md)
self.assertNotIn("--gpu", setup.gpu_problem(self.card("52")))
self.assertIsNone(setup.gpu_problem(self.card("75")))
with mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": "1"}):
for arch in ("60", "61", "70", "75", "120"):
+287
View File
@@ -0,0 +1,287 @@
"""Older NVIDIA GPUs (experimental): Pascal / Volta run a second engine built with CUDA 12 (engine-cuda12/), chosen per
model config by its oldest card; --cuda 12|13 overrides it. A PC whose cards the ready-made CUDA 13 engine runs on
gets exactly what it got before. No GPU, no downloads.
python -m unittest tools.test_setup_older_gpus
"""
from __future__ import annotations
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(Path(__file__).resolve().parent))
import setup # noqa: E402
from test_setup_choices import quiet # noqa: E402
from test_setup_golden import PROFILES, install, argv_for # noqa: E402
def card(i, name, vram, arch, driver="580.97"):
return {"index": i, "name": name, "vram_gb": vram, "arch": arch, "driver": driver}
V100 = card(0, "Tesla V100-PCIE-32GB", 32.0, "70", "575.57")
P40 = card(0, "Tesla P40", 24.0, "61", "535.104")
class Choice(unittest.TestCase):
def test_by_the_oldest_card(self):
self.assertEqual(setup.cuda_choice(["120"]), (13, None))
self.assertEqual(setup.cuda_choice([75, 86, 89]), (13, None))
for archs in ([70], [61], [60], [70, 86]):
tk, why = setup.cuda_choice(archs)
self.assertEqual(tk, 12, archs)
self.assertIn(f"sm_{min(archs)} is older than CUDA 13 supports", why)
def test_the_override_is_honored_with_a_warning(self):
tk, why = setup.cuda_choice([70], "13")
self.assertEqual(tk, 13) # recommend, never force: kept, and said
self.assertIn("will not run on that card", why)
self.assertEqual(setup.cuda_choice([86], "12")[0], 12)
self.assertIn("#220", setup.cuda_choice([86, 120], "12")[1])
self.assertEqual(setup.cuda_choice([70], "auto")[0], 12)
self.assertEqual(setup.cuda_choice([86], "auto"), (13, None))
def test_engine_folders_and_configs(self):
with mock.patch.object(setup, "ROOT", Path("/s")):
self.assertEqual(setup.engine_dir(), Path("/s/engine"))
self.assertEqual(setup.engine_dir(12), Path("/s/engine-cuda12"))
self.assertEqual(setup.config_toolkit({"exe": "/s/engine/strata.exe"}), 13)
self.assertEqual(setup.config_toolkit({"exe": "/s/engine-cuda12/strata.exe"}), 12)
self.assertEqual(setup.config_toolkit({"exe": "x", "cuda": 12}), 12)
self.assertEqual(setup.engine_defs([86], 12), ["-DSTRATA_EXPERIMENTAL_SM60=ON"])
self.assertEqual(setup.engine_defs([86]), [])
class OptIn(unittest.TestCase):
"""Pascal / Volta cards are used only when chosen; a PC with a newer card keeps recommending the newer one."""
def setUp(self):
self.env = mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": ""})
self.env.start()
def tearDown(self):
self.env.stop()
def test_reasons(self):
rtx = card(0, "RTX 3090", 24.0, "86")
v100 = {**V100, "index": 1}
self.assertIsNone(setup.old_gpus_opt_in([rtx]))
self.assertIsNone(setup.old_gpus_opt_in([rtx, v100])) # the default: unchanged
self.assertIn("you chose GPU 1", setup.old_gpus_opt_in([rtx, v100], [1]))
self.assertIsNone(setup.old_gpus_opt_in([rtx, v100], [0]))
self.assertEqual(setup.old_gpus_opt_in([rtx, v100], cuda="12"), "--cuda 12")
self.assertIn("only kind", setup.old_gpus_opt_in([V100]))
self.assertIsNone(setup.old_gpus_opt_in([V100], other=True)) # an AMD card it can use instead
self.assertIsNone(setup.old_gpus_opt_in([card(0, "GTX 980", 4.0, "52")]))
with mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": "1"}):
self.assertEqual(setup.old_gpus_opt_in([rtx, v100]), "STRATA_EXPERIMENTAL_SM60=1")
def test_named(self):
self.assertEqual(setup.named_gpus(None, "0,2"), [0, 2])
self.assertEqual(setup.named_gpus(1, None), [1])
self.assertEqual(setup.named_gpus(None, "all"), [])
self.assertEqual(setup.named_gpus(None, "x"), [])
def test_the_gate_follows_the_opt_in(self):
with mock.patch.object(setup, "OLD_GPUS", None):
self.assertIsNotNone(setup.gpu_problem(V100))
with mock.patch.object(setup, "OLD_GPUS", "you chose GPU 0"):
self.assertIsNone(setup.gpu_problem(V100))
self.assertIsNotNone(setup.gpu_problem(card(0, "GTX 980", 4.0, "52")))
class Libraries(unittest.TestCase):
def test_cuda12_wheels_two_folders(self):
with tempfile.TemporaryDirectory() as d:
sp = Path(d) / "site-packages"
names = {"cublas/bin/cublas64_12.dll", "cuda_runtime/bin/cudart64_12.dll", "cu13/bin/x86_64/cublas64_13.dll",
"cublas/lib/libcublas.so.12", "cuda_runtime/lib/libcudart.so.12", "cu13/lib/libcublas.so.13"}
for n in names:
f = sp / "nvidia" / n
f.parent.mkdir(parents=True, exist_ok=True)
f.write_bytes(b"")
with mock.patch.object(sys, "path", [str(sp)]):
for win in (True, False):
with mock.patch.object(setup, "WIN", win):
got12 = sorted(Path(x).relative_to(sp / "nvidia").as_posix() for x in setup.cuda_lib_dirs(12))
got13 = [Path(x).relative_to(sp / "nvidia").as_posix() for x in setup.cuda_lib_dirs()]
if win:
self.assertEqual(got12, ["cublas/bin", "cuda_runtime/bin"])
self.assertEqual(got13, ["cu13/bin/x86_64"])
else:
self.assertEqual(got12, ["cublas/lib", "cuda_runtime/lib"])
self.assertEqual(got13, ["cu13/lib"])
def test_wheels_pinned_to_12(self):
self.assertTrue(all("-cu12==12." in w for w in setup.CUDA12_WHEELS))
self.assertEqual(setup.CUDA12_ASSET, "strata-windows-x64-cuda12.zip" if setup.WIN else
"strata-linux-x64-cuda12.zip")
class BuildTools(unittest.TestCase):
"""The compile path: a CUDA 12 engine looks for a 12.x toolkit (STRATA_NVCC picks one), sm_120 needs 12.8+."""
def tools(self, gpu, nvcc):
seen = []
def find(below=None):
seen.append(below)
return nvcc(below)
with mock.patch.object(setup, "find_nvcc", find), mock.patch.object(setup, "find_vcvars", lambda: "vcvars"), \
mock.patch.object(setup.shutil, "which", lambda n: "/usr/bin/" + n):
got, text = quiet(setup.install_build_tools, gpu, True)
return got, seen, text
def test_cuda12_on_a_newer_card(self):
got, seen, _ = self.tools({"arch": "86", "archs": [86], "toolkit": 12},
lambda below: ("nvcc12", (12, 9)) if below else ("nvcc13", (13, 0)))
self.assertEqual((got[0], seen), ("nvcc12", [(13, 0)]))
def test_sm120_in_a_cuda12_engine_warns_and_needs_12_8(self):
got, _, text = self.tools({"arch": "70", "archs": [70, 120]},
lambda below: ("nvcc12", (12, 9)) if below else ("nvcc13", (13, 0)))
self.assertEqual(got[0], "nvcc12")
self.assertIn("#220", text)
with self.assertRaises(SystemExit):
self.tools({"arch": "70", "archs": [70, 120]}, lambda below: ("nvcc12", (12, 6)) if below else (None, None))
def fake_prebuilt(calls):
"""get_prebuilt that installs an engine in the folder of the toolkit it is asked for (and says which)."""
def get(url_base, gpu, vision, updating=False, toolkit=13):
calls.append(toolkit)
eng = setup.engine_dir(toolkit)
eng.mkdir(exist_ok=True)
(eng / "BUILD.json").write_text(json.dumps({"version": "0.1.39", "source": "release", "archs": [86], "ptx": True,
"cuda": "12.9" if toolkit == 12 else "13.0", "vision": "gpu"}))
(eng / setup.EXE).write_bytes(b"")
return eng
return get
class Install(unittest.TestCase):
"""setup.main() on mocked PCs (tools/test_setup_golden.py's harness)."""
def run_setup(self, ram, found, argv, env=None):
calls, libs = [], []
extra = [mock.patch.object(setup, "get_prebuilt", fake_prebuilt(calls)),
mock.patch.object(setup, "pip_cuda_libs", lambda tk=13: libs.append(tk)),
mock.patch.object(setup, "OLD_GPUS", None),
mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": "", "STRATA_CUDA": "", **(env or {})})]
code, out, cfg, asked = install(ram, found, argv, extra=extra)
return code, out, cfg, calls, libs
def test_a_v100_alone_gets_the_cuda12_engine(self):
code, out, cfg, calls, libs = self.run_setup(95.0, [V100], argv_for("qwen", "IQ3_XXS"))
self.assertEqual(code, 0, out[-3000:])
self.assertEqual((calls, libs), ([12], [12]))
self.assertEqual(cfg["cuda"], 12)
self.assertEqual(cfg["exe"], "<T>/engine-cuda12/<EXE>")
self.assertIn("sm_70 is older than CUDA 13 supports", out)
self.assertIn("experimental", out)
def test_a_p40_with_an_older_driver(self):
code, out, cfg, calls, _ = self.run_setup(95.0, [P40], argv_for("qwen", "IQ3_XXS"))
self.assertEqual(code, 0, out[-3000:]) # driver 535: enough for CUDA 12
self.assertEqual(calls, [12])
def test_a_newer_card_beside_a_v100_is_unchanged(self):
"""The RTX 3090 is recommended as before; the V100 is listed with how to choose it."""
rtx = card(0, "NVIDIA GeForce RTX 3090", 24.0, "86")
found = [rtx, {**V100, "index": 1}]
code, out, cfg, calls, libs = self.run_setup(95.0, found, argv_for("qwen", "IQ3_XXS"))
code0, _, cfg0, _ = install(95.0, [rtx], argv_for("qwen", "IQ3_XXS"))
self.assertEqual(code, 0, out[-3000:])
self.assertEqual((calls, libs), ([13], [13]))
self.assertNotIn("cuda", cfg)
self.assertEqual(cfg["exe"], "<T>/engine/<EXE>")
self.assertIn("choose it with --gpu 1", out)
skip = ("gpu", "gpus_asked", "lib_dirs") # one card vs two; the fake engine's library folders
self.assertEqual({k: v for k, v in cfg.items() if k not in skip}, {k: v for k, v in cfg0.items() if k not in skip})
def test_naming_the_v100_beside_a_newer_card(self):
found = [card(0, "NVIDIA GeForce RTX 3090", 24.0, "86"), {**V100, "index": 1}]
code, out, cfg, calls, _ = self.run_setup(95.0, found, argv_for("qwen", "IQ3_XXS") + ["--gpu", "1"])
self.assertEqual(code, 0, out[-3000:])
self.assertEqual(calls, [12])
self.assertEqual((cfg["cuda"], cfg["gpu"]), (12, 1))
self.assertIn("you chose GPU 1", out)
def test_cuda12_asked_for_on_a_newer_card(self):
ram, found = PROFILES["128GB-1x24GB"]
for argv, env in ((["--cuda", "12"], None), ([], {"STRATA_CUDA": "12"})):
with self.subTest(argv=argv, env=env):
code, out, cfg, calls, _ = self.run_setup(ram, found, argv_for("qwen", "IQ3_XXS") + argv, env)
self.assertEqual(code, 0, out[-3000:])
self.assertEqual((calls, cfg["cuda"]), ([12], 12))
self.assertIn("--cuda 12 (as you chose", out)
def test_an_old_driver_is_told_about_cuda12(self):
code, out, _, _, _ = self.run_setup(127.8, [card(0, "NVIDIA GeForce RTX 4090", 24.0, "89", "550.54")],
argv_for("qwen", "IQ3_XXS"))
self.assertEqual(code, 1)
self.assertIn("580 or newer is needed", out)
self.assertIn("--cuda 12", out)
code, out, cfg, calls, _ = self.run_setup(127.8, [card(0, "NVIDIA GeForce RTX 4090", 24.0, "89", "550.54")],
argv_for("qwen", "IQ3_XXS") + ["--cuda", "12"])
self.assertEqual(code, 0, out[-3000:])
self.assertEqual(calls, [12])
def test_cuda13_forced_on_a_v100_is_said(self):
code, out, cfg, calls, _ = self.run_setup(95.0, [V100], argv_for("qwen", "IQ3_XXS") + ["--cuda", "13"])
self.assertIn("will not run on that card", out)
class Start(unittest.TestCase):
"""At a start: a Pascal / Volta card added to a CUDA 13 model moves that model to the CUDA 12 engine; updates
look at both engine folders."""
def test_an_old_card_added_moves_the_model(self):
with tempfile.TemporaryDirectory() as d:
root = Path(d)
cfg_path = root / "strata-iq3_xxs.json"
cfg = {"exe": str(root / "engine" / setup.EXE), "args": [], "lib_dirs": ["<cu13>"]}
calls = []
with mock.patch.object(setup, "ROOT", root), \
mock.patch.object(setup, "get_prebuilt", fake_prebuilt(calls)), \
mock.patch.object(setup, "pip_cuda_libs", lambda tk=13: None), \
mock.patch.object(setup, "cuda_lib_dirs", lambda tk=13: [f"<cu{tk}>"]), \
mock.patch.object(setup, "gpu_info", lambda i=None: None):
got, text = quiet(setup.ensure_engine_for, [card(0, "RTX 3090", 24.0, "86"), {**V100, "index": 1}],
cfg_path, dict(cfg), True)
self.assertEqual(calls, [12])
self.assertEqual(Path(got["exe"]).parent.name, "engine-cuda12")
self.assertEqual((got["cuda"], got["lib_dirs"]), (12, ["<cu12>"]))
self.assertIn("moves to the experimental CUDA 12 engine", text)
self.assertEqual(json.loads(cfg_path.read_text())["cuda"], 12)
def test_update_looks_at_both_engines(self):
with tempfile.TemporaryDirectory() as d:
root = Path(d)
seen = []
real = setup.update_installed_engine
def spy(url_base, toolkit=None):
if toolkit is None:
return real(url_base, toolkit)
seen.append(toolkit)
with mock.patch.object(setup, "ROOT", root), mock.patch.object(setup, "update_installed_engine", spy):
spy("u")
self.assertEqual(seen, [13])
(root / "engine-cuda12").mkdir()
(root / "engine-cuda12" / "BUILD.json").write_text("{}")
seen.clear()
spy("u")
self.assertEqual(seen, [13, 12])
if __name__ == "__main__":
unittest.main()