Merge remote-tracking branch 'origin/main' into b70

# Conflicts:
#	setup.py
This commit is contained in:
maxfridbe committed 2026-09-30 11:35:14 -05:00
commit d62ccc75ff
41 files changed
+2237 -93

No files matched your search

+2
View File
@@ -18,6 +18,8 @@ __pycache__/
# plan v0.3 P1 (repository hygiene, review E1): profiler captures and large diagnostic dumps stay out of git.
*.nsys-rep
# Pi harness metadata (local session state, not project source)
*.sqlite
*.npz
*.occ1
+30 -7
View File
@@ -8,7 +8,7 @@
# below refuses anything older: silently building for a pre-Ampere arch would produce a binary that runs
# and is wrong about its own performance, which is the worst of both outcomes.
cmake_minimum_required(VERSION 3.24)
project(strata VERSION 0.1.27 LANGUAGES CXX)
project(strata VERSION 0.1.29 LANGUAGES CXX)
add_compile_definitions(STRATA_VERSION="${PROJECT_VERSION}")
# issue #31: release builds keep a PDB beside the exe (not shipped in it), so a minidump from a stalled engine can
# be read back to the exact source line
@@ -73,6 +73,11 @@ if(STRATA_ENABLE_CUDA)
"Strata needs an NVIDIA GPU of compute capability 7.5 or newer (RTX 20 / 30 / 40 / 50 series), but "
"CMAKE_CUDA_ARCHITECTURES is '${CMAKE_CUDA_ARCHITECTURES}'.")
endif()
# #220 / #224: RTX 50 engines built with CUDA 12.8 crashed in the prompt path on Linux (13.0 and newer did not)
if(_base GREATER_EQUAL 120 AND CMAKE_CUDA_COMPILER_VERSION VERSION_LESS 13.0)
message(WARNING "Building for sm_${_base} (RTX 50) with CUDA ${CMAKE_CUDA_COMPILER_VERSION}: engines built with "
"CUDA 12.8 crashed on long prompts on these cards (issues #220, #224). Use CUDA 13.0 or newer.")
endif()
endforeach()
message(STATUS "Strata: CUDA enabled, arch ${CMAKE_CUDA_ARCHITECTURES}")
set(_strata_gpu_runtime_target CUDA::cudart)
@@ -385,6 +390,14 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
add_executable(iq_parity src/kernels/iq_parity.cpp)
target_include_directories(iq_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(iq_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
if(STRATA_ENABLE_CUDA)
# native_mmvq's multi_exact contract, bitwise: a T-column call against T single-column calls on the same Q8_1
# bytes, with the flag off as the negative control (synthetic, GPU, no model; the control assumes 32-lane warps)
add_executable(mmvq_multi_parity src/kernels/mmvq_multi_parity.cpp)
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)
endif()
add_executable(shared_expert_parity src/kernels/shared_expert_parity.cpp)
target_include_directories(shared_expert_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(shared_expert_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
@@ -409,6 +422,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
target_include_directories(sampler_parity PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(sampler_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_test(NAME sampler_parity COMMAND sampler_parity --selftest)
set_tests_properties(sampler_parity PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=0;STRATA_SAMPLER_ONE_BLOCK=0")
# the same fixtures on the other two sampled paths: the one-block kernel and the 0.1.20 kernel
add_test(NAME sampler_parity_one_block COMMAND sampler_parity --selftest)
set_tests_properties(sampler_parity_one_block PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=0;STRATA_SAMPLER_ONE_BLOCK=1")
add_test(NAME sampler_parity_old COMMAND sampler_parity --selftest)
set_tests_properties(sampler_parity_old PROPERTIES ENVIRONMENT "STRATA_OLD_SAMPLER=1;STRATA_SAMPLER_ONE_BLOCK=0")
add_executable(rope_parity src/kernels/rope_parity.cpp)
target_include_directories(rope_parity PRIVATE ${_strata_gpu_include_directories})
@@ -495,11 +514,11 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
add_test(NAME cvec_parity COMMAND cvec_parity)
# Plan v0.3 P3: native MMVQ for 1..8 tokens (bitwise selftest + --bench timing); synthetic data, no model.
if(STRATA_BUILD_TESTS)
add_executable(native_mmvq_multi bench/micro/native_mmvq_multi.cpp)
target_include_directories(native_mmvq_multi PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(native_mmvq_multi PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_test(NAME native_mmvq_multi COMMAND native_mmvq_multi --selftest)
if(STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/bench/micro/native_mmvq_multi.cpp")
add_executable(native_mmvq_multi bench/micro/native_mmvq_multi.cpp)
target_include_directories(native_mmvq_multi PRIVATE ${_strata_gpu_include_directories})
target_link_libraries(native_mmvq_multi PRIVATE strata_kernels ${_strata_gpu_runtime_target})
add_test(NAME native_mmvq_multi COMMAND native_mmvq_multi --selftest)
endif()
# Plan v0.3 P0.1: working-set lock of a host region (CPU only).
@@ -579,6 +598,10 @@ if(STRATA_BUILD_TESTS)
add_executable(conv_cache_test src/program/conv_cache_test.cpp)
target_include_directories(conv_cache_test PRIVATE include)
add_test(NAME conv_cache_test COMMAND conv_cache_test)
# the f32 -> bf16 rounding against ggml's, NaN included, over every f32 bit pattern (header-only, CPU)
add_executable(bf16_bits_test src/kernels/bf16_bits_test.cpp)
target_include_directories(bf16_bits_test PRIVATE include)
add_test(NAME bf16_bits_test COMMAND bf16_bits_test)
endif()
add_library(strata_kernels_cpu STATIC src/kernels/cpu/expert.cpp src/kernels/cpu/pool.cpp
@@ -726,7 +749,7 @@ if(STRATA_NATIVE_EXPERTS)
endif()
endif()
if(STRATA_ENABLE_CUDA AND STRATA_BUILD_TESTS)
if(STRATA_ENABLE_CUDA AND STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/bench/micro/hit_cpu_order_parity.cu")
add_executable(hit_cpu_order_parity bench/micro/hit_cpu_order_parity.cu)
target_link_libraries(hit_cpu_order_parity PRIVATE strata_kernels strata_kernels_cpu ${_strata_gpu_runtime_target})
endif()
Binary file not shown.
+7
View File
@@ -70,6 +70,13 @@ VRAM. RTX 3090, the Coder at 198K context: 99 instead of 85 tokens/s output, the
slower. It does not stream its KV cache (KV streaming is on by default from 64K), so it pays off mostly on large
cards at long contexts.
**The draft layer's tokens (0.1.27, `--draft-vocab`):** the MTP draft layer can only propose tokens from a subset
of the vocabulary (`mtp/rt/draft_vocab.bin`). Since 0.1.27 the subset includes every Chinese, Japanese and Korean
token (106,299 ids), so answers in those languages are 15-38% faster (Q2_0, RTX 5070). Its head takes ~180 MiB of
VRAM, which the expert cache leaves free for it (0.1.28). `START-HERE.bat --setup --draft-vocab en` keeps the
English/code subset from before (40,525 ids, ~110 MiB less VRAM, English answers 1-2% faster; CJK answers get
almost no drafts). `tools/draft_vocab.py` builds and inspects subsets.
**Low-RAM mode (engine 0.1.26, chosen by setup):** normally all of a model's experts are copied into RAM (23-50 GB,
pinned) and the GPU holds a copy of the most-used ones. On a PC whose RAM cannot hold them beside the system (the
experts plus ~10 GB), setup instead maps them from one file in the model's folder (`--mmap-experts`, the pack's
+3
View File
@@ -32,6 +32,9 @@
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#ifndef NOMINMAX
#define NOMINMAX // windows.h's min/max macros would break std::min/std::max in every file that includes this one
#endif
#include <windows.h>
#else
#include <fcntl.h>
+3
View File
@@ -53,6 +53,9 @@ public:
/// KV streaming: refill the ring of the drafter's window from its host copy for a sequence that continues at
/// `upto` (a conversation-cache resume). No-op unless the drafter's K/V is a ring.
void kv_restore(int64_t upto);
/// The VRAM bind() will allocate for a native head of `head_row_bytes` per vocabulary row: the draft logits and
/// the draft head over rt/draft_vocab.bin's subset. The expert cache is sized before bind(), so it reserves this.
uint64_t bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const;
/// The main model's embedding and head, and the verify window's final residuals (T rows, hc*n_embd each).
bool bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err);
+3
View File
@@ -67,10 +67,13 @@
#define cudaSetDevice hipSetDevice
#define cudaStreamBeginCapture hipStreamBeginCapture
#define cudaStreamCaptureModeThreadLocal hipStreamCaptureModeThreadLocal
#define cudaStreamCaptureStatus hipStreamCaptureStatus
#define cudaStreamCaptureStatusNone hipStreamCaptureStatusNone
#define cudaStreamCreate hipStreamCreate
#define cudaStreamCreateWithFlags hipStreamCreateWithFlags
#define cudaStreamDestroy hipStreamDestroy
#define cudaStreamEndCapture hipStreamEndCapture
#define cudaStreamIsCapturing hipStreamIsCapturing
#define cudaStreamNonBlocking hipStreamNonBlocking
#define cudaStreamQuery hipStreamQuery
#define cudaStreamSynchronize hipStreamSynchronize
+7
View File
@@ -28,6 +28,12 @@
namespace strata::kernels {
/// Round-to-nearest-even f32 -> bf16, returned as raw bits in the LOW half of the uint16.
///
/// **A NaN IS PASSED THROUGH, QUIETED, AS `ggml_compute_fp32_to_bf16` DOES.** The rounding add alone
/// carries out of the mantissa for a NaN: 0x7FFFFFFF became 0x8000 (-0) and 0x7F800001 became 0x7F80 (+inf), so
/// a NaN upstream was masked instead of propagated. The test is on the magnitude bits, the result keeps the
/// sign and the top mantissa bits and sets the quiet bit (64 = bit 6 of the bf16). Every non-NaN input,
/// infinities included, rounds exactly as before.
STRATA_BF16_HD inline uint16_t bf16_from_f32(float f) {
uint32_t i;
#if defined(__HIP_DEVICE_COMPILE__)
@@ -35,6 +41,7 @@ STRATA_BF16_HD inline uint16_t bf16_from_f32(float f) {
#else
std::memcpy(&i, &f, 4);
#endif
if ((i & 0x7FFFFFFFu) > 0x7F800000u) return (uint16_t) ((i >> 16) | 64u);
i = (i + ((i >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u;
return (uint16_t) (i >> 16);
}
+5
View File
@@ -110,6 +110,9 @@ struct PleIoOptions {
uint32_t max_inflight = 64; ///< outstanding SSD reads (decode needs 16; prefill chunks use more)
uint64_t cache_rows = 1u << 20; ///< bounded row cache: 1,048,576 rows x 90 B ~ 95 MB; 0 disables
bool io_thread = true; ///< reads submitted by a worker thread, not the caller
/// Mmap mode only (`--ple-io ram`): lock the whole mapped table in RAM at open, so no SSD read ever sits on
/// the prompt or token path. Needs RAM for the full table. POSIX only (mlock); `locked()` reports the outcome.
bool lock = false;
};
/// The PLE table. Held by pointer-to-impl so this header does not drag `<windows.h>` into every
@@ -144,6 +147,8 @@ public:
bool open(const std::string& gguf_path, std::string& err);
void close();
bool is_open() const;
/// True when `PleIoOptions::lock` was asked for and mlock succeeded (false: pages only pre-touched).
bool locked() const;
uint64_t rows() const;
/// 16 row indices -> 2560 floats. The gathered rows are flattened HEAD-SLOWEST: row h's 160 values
+64 -8
View File
@@ -242,6 +242,61 @@ CALL_START = "<tool_call>"
CALL_END = "</tool_call>"
PARAM_END = "</parameter>"
FUNC_END = "</function>"
def param_end(text: str, final: bool = False) -> int:
"""Where a parameter value in `text` ends: the first `</parameter>` followed (after whitespace) by the next
`<parameter=` or `</function>` - the same text inside a value (a file that documents the call format, #210) is
part of the value. -1: none yet; -2: a candidate whose follower has not arrived (streaming; `final` accepts it)."""
at = text.find(PARAM_END)
while at >= 0:
after = text[at + len(PARAM_END):].lstrip()
if after.startswith(("<parameter=", FUNC_END)):
return at
if not after or "<parameter=".startswith(after) or FUNC_END.startswith(after):
return at if final else -2
at = text.find(PARAM_END, at + 1)
return -1
def call_end(text: str) -> int:
"""Where a tool call's body ends (#210): the `</tool_call>` after the call's own `</function>`, found by walking
its parameters with param_end, so a value may contain either tag. -1: not complete yet. A body that is not in
the call format ends at the first `</tool_call>`, as before."""
s = text.lstrip()
pos = len(text) - len(s)
if not s.startswith("<function="):
return text.find(CALL_END) if not "<function=".startswith(s) else -1
gt = text.find(">", pos)
if gt < 0:
return -1
pos = gt + 1
while True:
rest = text[pos:]
s = rest.lstrip()
pos += len(rest) - len(s)
if s.startswith("<parameter="):
gt = text.find(">", pos)
if gt < 0:
return -1
end = param_end(text[gt + 1:])
if end < 0:
return -1
pos = gt + 1 + end + len(PARAM_END)
elif s.startswith(FUNC_END):
rest = text[pos + len(FUNC_END):]
s = rest.lstrip()
if s.startswith(CALL_END):
return pos + len(FUNC_END) + len(rest) - len(s)
return -1 if CALL_END.startswith(s) else text.find(CALL_END, pos)
elif not s or "<parameter=".startswith(s) or FUNC_END.startswith(s):
return -1
else:
return text.find(CALL_END, pos)
def parse_tool_call(body: str, schema: dict | None = None) -> ToolCall:
"""`<function=NAME>\\n<parameter=P>\\nVALUE\\n</parameter>...</function>` -> ToolCall. Values are JSON-decoded
when the tool's schema says the parameter is not a string (or, without a schema, when they parse as JSON
@@ -257,9 +312,9 @@ def parse_tool_call(body: str, schema: dict | None = None) -> ToolCall:
rest = rest[rest.index("<parameter=") + len("<parameter="):]
pname = rest[:rest.index(">")]
rest = rest[rest.index(">") + 1:]
end = rest.find("</parameter>")
end = param_end(rest, final=True)
value = rest[:end] if end >= 0 else rest
rest = rest[end + len("</parameter>"):] if end >= 0 else ""
rest = rest[end + len(PARAM_END):] if end >= 0 else ""
if value.startswith("\n"):
value = value[1:]
if value.endswith("\n"):
@@ -351,16 +406,17 @@ class OutputParser:
self.sp += 1
rest = rest[1:]
self.sval_started = True
end = rest.find("</parameter>")
end = param_end(rest)
if end >= 0:
value = rest[:end]
if value.endswith("\n"):
value = value[:-1]
args(json.dumps(value)[1:-1] + '"')
self.sp += end + len("</parameter>")
self.sp += end + len(PARAM_END)
self.ss = "between"
continue
safe = len(rest) - self._hold(rest, ("</parameter>",))
# an undecided </parameter> (-2) is held from its start, like a tag still arriving
safe = rest.find(PARAM_END) if end == -2 else len(rest) - self._hold(rest, (PARAM_END,))
if safe > 0 and rest[safe - 1] == "\n": # may be the trailing newline before </parameter>
safe -= 1
if safe > 0:
@@ -368,7 +424,7 @@ class OutputParser:
self.sp += safe
return out
elif self.ss == "raw":
end = rest.find("</parameter>")
end = param_end(rest)
if end < 0:
return out
value = rest[:end]
@@ -381,7 +437,7 @@ class OutputParser:
except ValueError:
v = value
args(json.dumps(v, ensure_ascii=False))
self.sp += end + len("</parameter>")
self.sp += end + len(PARAM_END)
self.ss = "between"
else:
return out
@@ -449,7 +505,7 @@ class OutputParser:
self.buf = self.buf[i + len(CALL_START):]
self.state = "call"
else:
i = self.buf.find(CALL_END)
i = call_end(self.buf)
if self.stream_tools:
if i >= 0:
whole, self.buf = self.buf, self.buf[:i] # scan only the body
+3
View File
@@ -31,6 +31,8 @@ import time
import urllib.error
import urllib.request
from serve.winjob import contain
PROTOCOL = "2025-06-18" # the MCP revision Strata asks for; the server's answer is used as given
DEFAULTS = {"timeout_s": 60.0, "max_result_chars": 20000, "max_rounds": 8, "start_timeout_s": 120.0}
@@ -105,6 +107,7 @@ class StdioTransport:
env=env, **extra)
except OSError as e:
raise McpError(f"could not start {command!r}: {e}") from None
contain(self.proc) # ends with the server, however it ends (Windows)
threading.Thread(target=self._read, daemon=True).start()
threading.Thread(target=self._read_stderr, daemon=True).start()
+48 -10
View File
@@ -24,6 +24,7 @@ import argparse
import collections
import base64
import hashlib
import hmac
import codecs
import json
import os
@@ -46,6 +47,7 @@ sys.path.insert(0, str(ROOT)) # run as a script (run-<model>.bat) as well as a
from serve.frontend import (ChatTemplate, Event, OutputParser, anthropic_to_messages, # noqa: E402
images_of, openai_to_messages)
from serve.mcp import McpCancelled, hub_from_config # noqa: E402
from serve.winjob import contain # noqa: E402
IM_END = "<|im_end|>"
IMAGE_PAD = "<|image_pad|>"
@@ -166,10 +168,12 @@ class StrataEngine:
daemon=True).start()
self.proc = subprocess.Popen([exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env)
contain(self.proc) # ends with the server, however it ends (Windows)
self.max_context = 0
self.can_stop = False # the engine honours a STOP line mid-request (READY <ctx> stop)
self.last = {}
self.info = {} # INFO key=value facts (engine 0.1.8+): kv, expert slots, ... (Monitor tab)
self.prefill_tok_s_mean = None
self.progress = None # (read, total) prompt tokens while a prompt is read, from PP lines
try: # a ready-made engine's BUILD.json says its version
self.info["version"] = json.loads((Path(exe).parent / "BUILD.json").read_text()).get("version")
@@ -216,6 +220,11 @@ class StrataEngine:
if "issue #29" in line:
return ("The engine stopped itself because it had stopped making progress - a hang it caught. Its log "
"line: " + line.strip() + " - please report it at github.com/Niko1221/Strata/issues.")
rc = self.proc.poll()
last = next((x.strip() for x in reversed(tail.splitlines()) if x.strip().startswith(("strata", "ERR"))), "")
if rc is not None and rc >= 0 and last: # it ended by itself: its own last words say why (#215)
return (f"The engine exited (code {rc}). Its last log line: {last} - if that does not explain it, please "
"report it at github.com/Niko1221/Strata/issues with the log.")
return ("The usual cause is running out of RAM: Linux then ends the biggest program (check: sudo dmesg | "
"grep -i -E 'killed process|out of memory'); Windows slows down instead. Close other programs or use a "
"smaller model (Q2_0 / IQ2_XS).")
@@ -308,6 +317,7 @@ class StrataEngine:
the HTTP layer turns it into an SSE comment, which keeps clients' watchdogs calm and notices a client that
has gone. A consumer that stops early (or `cancel`) makes the engine STOP, so it does not run to max_new."""
self.progress = None
self.prefill_tok_s_mean = None
# an image request takes the same sampling keys as text (#75: it used to decode greedily whatever was asked)
head = f"GENI {int(max_new)}{self.sampling_keys(sampling or {})} {embeddings}" if embeddings else \
f"GEN {int(max_new)}{self.sampling_keys(sampling or {})}"
@@ -337,6 +347,7 @@ class StrataEngine:
f = line.split()
if len(f) >= 3 and f[1].isdigit() and f[2].isdigit():
self.progress = (int(f[1]), int(f[2])) # prompt progress, one per chunk: also a heartbeat (the
self.prefill_tok_s_mean = float(f[4]) if len(f) >= 5 else None
if cancel.is_set(): # lines reset the 10 s wait, so without this a long prompt
return # would send no keep-alives at all)
yield None
@@ -388,6 +399,7 @@ class Vision:
self.dir = Path(tempfile.mkdtemp(prefix="strata-vision-"))
self.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log or subprocess.DEVNULL,
text=True, encoding="utf-8", bufsize=1, env=env)
contain(self.proc)
line = self.proc.stdout.readline()
if not line.startswith("READY"):
raise RuntimeError("the vision encoder did not start: " + line.strip())
@@ -615,7 +627,8 @@ class Service:
"""The hardware sampler behind GET /metrics (serve/telemetry.py), recording this server's tok/s too."""
if getattr(self, "telemetry", None) is None:
from serve.telemetry import Telemetry
self.telemetry = Telemetry(extra=lambda: {"tok_s": self._tok_s(), "tok_s_mean": self._tok_s_mean()},
self.telemetry = Telemetry(extra=lambda: {"tok_s": self._tok_s(), "tok_s_mean": self._tok_s_mean(),
"prefill_tok_s_mean": self._prefill_tok_s_mean()},
gpu_index=int(getattr(self, "gpu_index", 0) or 0),
gpu_indices=getattr(self, "gpu_indices", None))
@@ -641,6 +654,12 @@ class Service:
return 0.0
return s["generated"] / max(1e-6, time.time() - s["first_token"])
def _prefill_tok_s_mean(self):
"""Engine-reported mean over newly read tokens, excluding the cached prefix."""
with self.status_lock:
reading = self.status.get("busy") and self.status.get("first_token") is None
return getattr(self.engine, "prefill_tok_s_mean", None) if reading else 0.0
def metrics(self, all_requests=False) -> dict:
"""GET /metrics: what the Monitor tab shows - the engine's facts, what it is doing, the last requests, and
the hardware (with a minute of history per series)."""
@@ -663,6 +682,7 @@ class Service:
"elapsed_s": round(now - s["started"], 1) if s.get("busy") and s.get("started") else None,
"tok_s": round(self._tok_s(), 1) if state == "generating" else None,
"tok_s_mean": round(self._tok_s_mean(), 1) if state == "generating" else None,
"prefill_tok_s_mean": getattr(self.engine, "prefill_tok_s_mean", None) if s.get("busy") else None,
"tok_s_window_s": RATE_WINDOW_S if state == "generating" else None}
if state == "reading" and progress:
live["prompt_read"], live["prompt_total"] = progress
@@ -914,6 +934,8 @@ class Service:
if os.environ.get("STRATA_DEBUG") and raw_ids:
print(f"[strata] raw: {self.tok.decode(raw_ids)!r}", flush=True)
self.status["busy"] = False
self.status.pop("tail", None) # #212: the answer's end is not kept once it is done
self.status.pop("tool", None)
for ev in parser.finish():
yield "event", ev
yield "done", {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0),
@@ -1245,7 +1267,7 @@ def make_handler(svc: Service):
return True
auth = self.headers.get("Authorization", "")
given = auth[7:].strip() if auth.lower().startswith("bearer ") else self.headers.get("x-api-key", "")
if given == svc.api_key:
if hmac.compare_digest(given.encode(), svc.api_key.encode()): # #213: constant-time
return True
self._json(401, {"error": {"type": "authentication_error", "message": "missing or wrong API key"}})
return False
@@ -1310,6 +1332,8 @@ def make_handler(svc: Service):
self._json(200, {"status": "ok", "max_context": svc.engine.max_context, "model": svc.model,
"images": svc.vision is not None, "api_key": bool(svc.api_key)})
elif path == "/status":
if not self._authorized(): # #212: it shows the end of the last answer
return
with svc.status_lock:
s = dict(svc.status)
now = time.time()
@@ -1501,6 +1525,10 @@ class Server(ThreadingHTTPServer):
# either one (a forgotten second start of run-<model>.bat). Without it the second start fails loudly instead.
allow_reuse_address = os.name != "nt"
def handle_error(self, request, client_address):
if not isinstance(sys.exc_info()[1], ConnectionError): # a client that hangs up needs no stack trace
super().handle_error(request, client_address)
def warn_tight_ram(arena_mib) -> None:
"""The model's experts live in RAM (INFO arena_mib, engine 0.1.10+). With less than ~6 GB left beside them for the
@@ -1741,6 +1769,12 @@ def main() -> int:
model_name=cfg.get("model_name", "qwen3.8-flash-next"), vision=vision,
sampling_defaults=sampling_defaults,
fit_max_tokens=a.fit_max_tokens or cfg.get("fit_max_tokens") is True)
if ("STRATA_API_KEY" in os.environ and not os.environ["STRATA_API_KEY"].strip()) or any(x == "--api-key" and i + 1 < len(sys.argv) and not sys.argv[i + 1].strip() or x.strip() == "--api-key="
for i, x in enumerate(sys.argv)):
# #213: an empty key would switch authentication off without a word
print("[strata] an API key was given but it is empty: set a key, or leave --api-key / STRATA_API_KEY out",
file=sys.stderr)
return 2
svc.api_key = a.api_key or cfg.get("api_key", "")
svc.gpu_index = (gpu_list(cfg) or [0])[0] # the Monitor reads the card the engine runs on (issue #51)
svc.gpu_indices = gpu_list(cfg) # ... or every card of a layer split (issue #112)
@@ -1785,15 +1819,19 @@ def main() -> int:
import webbrowser
webbrowser.open(f"http://{'127.0.0.1' if a.host in ('0.0.0.0', '') else a.host}:{a.port}/")
try:
threading.Event().wait()
while True:
time.sleep(1) # Windows never delivers Ctrl+C to an untimed Event.wait()
except KeyboardInterrupt:
httpd.shutdown()
if hasattr(engine, "close"):
engine.close()
if vision:
vision.close()
if hub is not None:
hub.close()
print("\n[strata] stopping (Ctrl+C again to end the engine at once) ...", flush=True)
closers = [httpd.shutdown, getattr(engine, "close", None), vision.close if vision else None,
hub.close if hub is not None else None]
for close in filter(None, closers):
try:
close()
except KeyboardInterrupt: # a second Ctrl+C: don't wait for the engine to free its memory
if getattr(engine, "proc", None):
engine.proc.kill()
print("[strata] stopped", flush=True)
return 0
+1 -1
View File
@@ -256,7 +256,7 @@ class Telemetry:
with self.lock:
self.now = s
for k in ("gpu_util", "gpu_mem_used", "gpu_temp", "gpu_power", "gpu_pcie_rx_mb", "cpu", "ram_used",
"disk_read_mb", "tok_s"):
"disk_read_mb", "tok_s", "prefill_tok_s_mean"):
v = s.get(k)
self.hist[k].append(round(v, 2) if isinstance(v, float) else v)
time.sleep(1.0)
+90
View File
@@ -196,6 +196,61 @@ class ImageMarkers(unittest.TestCase):
svc.embeddings.path.unlink(missing_ok=True)
class StatusNeedsTheKey(unittest.TestCase):
"""#212: /status shows the end of the answer being written, so it needs the key like /v1/*."""
def test_status(self):
tok = ByteTokenizer()
svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
svc.api_key = "k3y"
httpd = serve(svc, port=0)
base = f"http://127.0.0.1:{httpd.server_address[1]}/status"
try:
with self.assertRaises(urllib.error.HTTPError) as e:
urllib.request.urlopen(base, timeout=10)
self.assertEqual(e.exception.code, 401)
e.exception.close()
req = urllib.request.Request(base, headers={"Authorization": "Bearer k3y"})
with urllib.request.urlopen(req, timeout=10) as r:
self.assertEqual(r.status, 200)
self.assertNotIn("tail", json.loads(r.read()))
finally:
httpd.shutdown()
httpd.server_close()
class ToolCallTerminators(unittest.TestCase):
"""#210: a value that contains </parameter> or </tool_call> (a file documenting the call format) is kept whole."""
CONTENT = ("Close each value with </parameter> and the call with </function></tool_call>.\n"
"<parameter=x>\nnot a parameter\n</parameter>\nend")
SCHEMA = [{"name": "write", "parameters": {"properties": {"path": {"type": "string"},
"content": {"type": "string"}}}}]
def run_parser(self, stream_tools, step):
from serve.frontend import OutputParser
text = ("</think>\n\n<tool_call>\n<function=write>\n<parameter=path>\ndoc.md\n</parameter>\n"
f"<parameter=content>\n{self.CONTENT}\n</parameter>\n</function>\n</tool_call>")
p = OutputParser(thinking=True, tools=self.SCHEMA, stream_tools=stream_tools)
evs = []
for i in range(0, len(text), step):
evs += p.feed(text[i:i + step])
evs += p.finish()
return evs
def test_values_keep_the_terminators(self):
for stream_tools in (False, True):
for step in (1, 7, 10_000):
with self.subTest(stream_tools=stream_tools, step=step):
evs = self.run_parser(stream_tools, step)
calls = [e.call for e in evs if e.kind == "tool_call"]
self.assertEqual(len(calls), 1)
self.assertEqual(calls[0].arguments, {"path": "doc.md", "content": self.CONTENT})
self.assertFalse([e for e in evs if e.kind == "content" and e.text.strip()])
if stream_tools:
streamed = "".join(e.text for e in evs if e.kind == "tool_args")
self.assertEqual(json.loads(streamed), {"path": "doc.md", "content": self.CONTENT})
class ClientShapes(unittest.TestCase):
"""What real clients send: Claude Code posts /v1/messages?beta=true (issue #55) and puts hook context into the
conversation as a mid-conversation system message (issue #56); some OpenAI clients send a late developer message."""
@@ -425,6 +480,41 @@ class LiveRate(unittest.TestCase):
with urllib.request.urlopen(self.base + "/metrics", timeout=10) as r:
return json.loads(r.read())
def test_prefill_rate_excludes_cached_tokens(self):
import io
import queue
from types import SimpleNamespace
engine = StrataEngine.__new__(StrataEngine)
engine.proc = SimpleNamespace(stdin=io.StringIO())
engine.lines = queue.Queue()
engine.can_stop = False
engine.max_context = 262144
engine.prefill_tok_s_mean = 9999.0
engine.lines.put("PP 10000 12000 2000 1000.0") # 8000 cached, 2000 newly read in two seconds
engine.lines.put("DONE 1 12000 4000 10 stop 0 0 8000")
gen = engine.generate([1], 1, {}, threading.Event())
self.assertIsNone(next(gen))
self.assertEqual(engine.progress, (10000, 12000))
self.assertEqual(engine.prefill_tok_s_mean, 1000.0)
self.svc.engine = engine
self.svc.status.update(busy=True, first_token=None)
self.assertEqual(self.metrics()["live"]["prefill_tok_s_mean"], 1000.0)
self.assertNotIn("prefill_tok_s", self.metrics()["live"])
self.assertEqual(self.svc._prefill_tok_s_mean(), 1000.0)
self.svc.status.update(first_token=time.time(), generated=1)
self.assertEqual(self.svc._prefill_tok_s_mean(), 0.0)
self.assertEqual(list(gen), [])
timings = request_timings(12000, 1, engine.last)
self.assertEqual(timings["prompt_per_second"], 1000.0)
engine.lines.put("PP 8000 12000")
engine.lines.put("DONE 0 12000 0 0 stop 0 0 12000")
gen = engine.generate([1], 1, {}, threading.Event())
next(gen)
self.assertIsNone(engine.prefill_tok_s_mean)
list(gen)
self.svc.status["busy"] = False
self.assertIsNone(self.metrics()["live"]["prefill_tok_s_mean"])
def test_the_live_number_is_a_rate(self):
live_samples, stop = [], threading.Event()
+67
View File
@@ -0,0 +1,67 @@
"""serve/winjob.py: a contained child - and whatever it starts - ends when the process that contained it ends, even
when that process is killed outright (the console window closed, Task Manager), with no cleanup of its own.
python -m unittest serve.test_winjob (Windows only; skipped elsewhere)
"""
import os
import subprocess
import sys
import time
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
# stands in for the server: contains a child that starts a grandchild, prints both pids, then waits to be killed
PARENT = f"""
import subprocess, sys, time
sys.path.insert(0, {str(ROOT)!r})
from serve.winjob import contain
code = ("import subprocess, sys, time; g = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(120)']); "
"print(g.pid, flush=True); time.sleep(120)")
child = subprocess.Popen([sys.executable, "-c", code], stdout=subprocess.PIPE, text=True)
ok = contain(child)
print(ok, child.pid, child.stdout.readline().strip(), flush=True)
time.sleep(120)
"""
def running(pid: int) -> bool:
out = subprocess.run(["tasklist", "/FI", f"PID eq {pid}", "/NH"], capture_output=True, text=True).stdout
return str(pid) in out
@unittest.skipUnless(os.name == "nt", "job objects are Windows-only")
class TestWinJob(unittest.TestCase):
def test_children_end_with_a_killed_server(self):
# a venv's python.exe is a launcher that runs the real interpreter as its child: kill() must reach the latter
python = getattr(sys, "_base_executable", None) or sys.executable
parent = subprocess.Popen([python, "-c", PARENT], stdout=subprocess.PIPE, text=True)
child = grandchild = None
try:
ok, child, grandchild = parent.stdout.readline().split()
child, grandchild = int(child), int(grandchild)
self.assertEqual(ok, "True")
self.assertTrue(running(child) and running(grandchild))
parent.kill() # TerminateProcess: no atexit, no finally - like closing the window
parent.wait(10)
deadline = time.monotonic() + 10
while (running(child) or running(grandchild)) and time.monotonic() < deadline:
time.sleep(0.2)
self.assertFalse(running(child), "the child outlived the server")
self.assertFalse(running(grandchild), "the grandchild outlived the server")
finally:
if parent.poll() is None:
parent.kill()
for pid in (child, grandchild): # on a failure, don't leave them sleeping
if pid and running(pid):
subprocess.run(["taskkill", "/PID", str(pid), "/F"], capture_output=True)
def test_elsewhere_or_without_a_process_it_is_a_no_op(self):
from serve.winjob import contain
self.assertFalse(contain(None))
if __name__ == "__main__":
unittest.main()
+5
View File
@@ -92,6 +92,11 @@ main { flex: 1; min-height: 0; display: flex; }
.st-metric__value small { font-size: var(--st-fs-md); font-weight: var(--st-fw-medium); color: var(--st-ink-muted); margin-left: 4px; }
.st-metric__sub { font-size: var(--st-fs-xs); color: var(--st-ink-muted); font-variant-numeric: tabular-nums; min-height: 1em; }
.st-metric__spark { display: block; overflow: visible; }
.speed-values { display: flex; justify-content: space-between; gap: var(--st-s-3); }
.speed-values > div { display: flex; flex-direction: column; gap: 10px; min-width: 0; }
.speed-values > div:last-child { text-align: right; }
.speed-values .st-metric__value { font-size: clamp(20px, 2.2vw, var(--st-fs-stat)); }
.st-metric__spark .speed-prefill { color: color-mix(in srgb, var(--st-accent) 65%, black); }
.st-metric__spark[data-tone="warn"] { color: var(--st-warn); }
.st-metric__spark[data-tone="info"] { color: var(--st-info); }
.monitor-row { display: grid; grid-template-columns: minmax(260px, 1fr) minmax(0, 2.4fr); gap: var(--st-s-4); }
+17 -5
View File
@@ -109,7 +109,7 @@ async function loadHealth() {
// ------------------------------------------------------------------ Monitor
const METRICS = [
{key: "speed", label: "Speed", icon: "gauge", unit: "tok/s", series: "tok_s"},
{key: "speed", label: "Speed", icon: "gauge", unit: "t/s", series: "tok_s"},
{key: "gpu", label: "GPU load", icon: "gpu", unit: "%", series: "gpu_util", max: 100},
{key: "vram", label: "VRAM", icon: "layers", unit: "GB", series: "gpu_mem_used"},
{key: "temp", label: "GPU temp", icon: "thermometer", unit: "°C", series: "gpu_temp", tone: "warn"},
@@ -121,11 +121,17 @@ const METRICS = [
$("metrics").innerHTML = METRICS.map((m) => `
<div class="st-card metric-card"><div class="st-metric">
<span class="st-metric__label">${icon(m.icon, "st-icon st-icon--sm")}${esc(m.label)}</span>
<span class="st-metric__value" id="mv-${m.key}">–</span>
<span class="st-metric__sub" id="ms-${m.key}"></span>
${m.key === "speed" ? `<div class="speed-values">
<div><span class="st-metric__value" id="mv-speed">-</span><span class="st-metric__sub" id="ms-speed">Decode</span></div>
<div class="speed-prefill"><span class="st-metric__value" id="mv-prefill">-</span><span class="st-metric__sub" id="ms-prefill">Prefill</span></div>
</div>` : `<span class="st-metric__value" id="mv-${m.key}">–</span>
<span class="st-metric__sub" id="ms-${m.key}"></span>`}
<svg class="st-metric__spark" id="sp-${m.key}" viewBox="0 0 100 32" preserveAspectRatio="none"${m.tone ? ` data-tone="${m.tone}"` : ""}>
<path class="area" fill="currentColor" opacity=".12"/><path class="line" fill="none" stroke="currentColor"
stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round" vector-effect="non-scaling-stroke"/></svg>
stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round" vector-effect="non-scaling-stroke"/>
${m.key === "speed" ? `<g id="sp-prefill" class="speed-prefill"><path class="area" fill="currentColor" opacity=".12"/>
<path class="line" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"
stroke-linecap="round" vector-effect="non-scaling-stroke"/></g>` : ""}</svg>
</div></div>`).join("");
function spark(id, values, max) {
@@ -226,8 +232,14 @@ function renderMonitor(live, hw, st, eng, h, last, requests, totals, kept) {
// the eight cards
const speed = live.state === "generating" ? live.tok_s : last ? last.decode_tok_s : null;
setMetric("speed", speed == null ? null : fmt(speed, 1), "tok/s", live.state === "generating" ? "now" : last ? "last request" : "");
setMetric("speed", speed == null ? null : fmt(speed, 1), "t/s",
live.state === "generating" ? "Decode now" : last ? "Decode last request" : "Decode");
const prefill = live.state !== "idle" ? live.prefill_tok_s_mean
: last && last.prompt_ms > 0 ? Math.max(0, last.prompt_tokens - (last.reused || 0)) / (last.prompt_ms / 1000) : null;
setMetric("prefill", prefill == null ? null : fmt(prefill), "t/s",
live.state === "reading" ? "Prefill now" : live.state === "generating" ? "Prefill this request" : last ? "Prefill last request" : "Prefill");
spark("sp-speed", h.tok_s);
spark("sp-prefill", h.prefill_tok_s_mean);
// a model split across several cards (issue #112): the cards show their total / mean / hottest, and each card's own
const per = (f) => (hw.gpus || []).map((g) => `GPU ${g.index} ${f(g)}`).join(" · ");
const multi = (hw.gpus || []).length > 1;
+74
View File
@@ -0,0 +1,74 @@
"""serve/winjob.py - on Windows, tie the processes Strata starts to the server's own lifetime.
Closing the console window, Task Manager or a crash end the server without running its cleanup, and the engine,
the vision encoder and the MCP servers kept running on their own. `contain(proc)` puts a child in a job object that
is set to kill everything in it when its last handle closes - and the only handle is this process's, which the OS
closes however the server ends. Processes the child starts later join the same job. The server itself stays out of
the job, so a browser that `--open` starts is not tied to it. Elsewhere, and if the job cannot be made, a no-op.
"""
from __future__ import annotations
import os
import threading
_job = None
_lock = threading.Lock()
if os.name == "nt":
import ctypes
from ctypes import wintypes
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
class _IoCounters(ctypes.Structure):
_fields_ = [(n, ctypes.c_ulonglong) for n in ("ReadOperationCount", "WriteOperationCount",
"OtherOperationCount", "ReadTransferCount",
"WriteTransferCount", "OtherTransferCount")]
class _BasicLimits(ctypes.Structure):
_fields_ = [("PerProcessUserTimeLimit", ctypes.c_longlong), ("PerJobUserTimeLimit", ctypes.c_longlong),
("LimitFlags", wintypes.DWORD), ("MinimumWorkingSetSize", ctypes.c_size_t),
("MaximumWorkingSetSize", ctypes.c_size_t), ("ActiveProcessLimit", wintypes.DWORD),
("Affinity", ctypes.c_size_t), ("PriorityClass", wintypes.DWORD),
("SchedulingClass", wintypes.DWORD)]
class _ExtendedLimits(ctypes.Structure):
_fields_ = [("BasicLimitInformation", _BasicLimits), ("IoInfo", _IoCounters),
("ProcessMemoryLimit", ctypes.c_size_t), ("JobMemoryLimit", ctypes.c_size_t),
("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", ctypes.c_size_t)]
_JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000
_JobObjectExtendedLimitInformation = 9
_k32.CreateJobObjectW.restype = wintypes.HANDLE
_k32.CreateJobObjectW.argtypes = (wintypes.LPVOID, wintypes.LPCWSTR)
_k32.SetInformationJobObject.argtypes = (wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD)
_k32.AssignProcessToJobObject.argtypes = (wintypes.HANDLE, wintypes.HANDLE)
def _make_job():
job = _k32.CreateJobObjectW(None, None) # no security attributes: the handle is not inherited
if not job:
return None
info = _ExtendedLimits()
info.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
if not _k32.SetInformationJobObject(job, _JobObjectExtendedLimitInformation, ctypes.byref(info),
ctypes.sizeof(info)):
_k32.CloseHandle(job)
return None
return job
def contain(proc) -> bool:
"""Put a started subprocess.Popen in the kill-on-close job. True if it is in; False (harmlessly) otherwise."""
global _job
if os.name != "nt" or proc is None:
return False
with _lock:
if _job is None:
_job = _make_job() or 0
if not _job:
return False
try:
return bool(_k32.AssignProcessToJobObject(_job, int(proc._handle)))
except (AttributeError, OSError, ValueError):
return False
+79 -21
View File
@@ -58,11 +58,13 @@ 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
MIN_ENGINE = (0, 1, 27) # 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
MIN_ENGINE = (0, 1, 29) # 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"]
MODELS = {
"Q2_0": {"about": "2-bit, the fastest", "download_gb": 66.4, "ram_gb": 48, "arena_gb": 34.0},
# the original model only for now: Swift 1.5's Q2_0 files split one layer's experts across the two shards, which
# the pack tool (tools/iq_pack.py) cannot prepare yet (#171)
"Q2_0": {"about": "2-bit, the fastest", "download_gb": 66.4, "ram_gb": 48, "arena_gb": 34.0, "families": ("qwen",)},
"IQ2_XS": {"about": "2-bit i-quant, a little better quality, close in speed", "download_gb": 68.0, "ram_gb": 48,
"arena_gb": 35.5},
"IQ3_XXS": {"about": "3-bit i-quant, better quality, slower (more CPU work per token)", "download_gb": 75.8,
@@ -694,6 +696,18 @@ def download(url, dst: Path, what=None):
ok(f"{what or dst.name} downloaded")
def whole_shard(s: Path) -> bool:
"""A shard as long as its own tensor directory says (check_shards' test, without stopping setup)."""
sys.path.insert(0, str(ROOT / "tools"))
from gguf_reader import GGUFFile
try:
g = GGUFFile(s)
return s.stat().st_size >= g.data_start + max((t.offset + (t.expected_bytes() or 0) for t in g.tensors),
default=0)
except (OSError, ValueError, struct.error):
return False
def check_shards(shards):
"""Every shard present and whole, or setup stops naming the file and the numbers. Whole means as long as
its own tensor directory says (the header is read, the data is not): a truncated copy (--gguf-dir, a .part
@@ -725,7 +739,9 @@ def get_llama_cpp():
tmp = ROOT / "third_party" / "_unpack"
shutil.rmtree(tmp, ignore_errors=True)
with zipfile.ZipFile(z) as f:
f.extractall(tmp)
# llama.cpp's own web UI (tools/ui) is not used, and its deep paths passed Windows' 260-character limit in a
# folder like Downloads\Strata-main\Strata-main (#206)
f.extractall(tmp, [m for m in f.namelist() if "/tools/ui/" not in m])
top = next(tmp.iterdir())
shutil.rmtree(llama, ignore_errors=True)
# PR #63: on Windows a rename can fail with PermissionError while an antivirus scanner still holds a file of the
@@ -1035,7 +1051,8 @@ def update_installed_engine(url_base) -> None:
def install_build_tools(gpu, yes):
"""The compiler and the CUDA toolkit, installed for the user (asks once). Returns (nvcc, vcvars)."""
nvcc, cuda_v = find_nvcc()
need_cuda = (12, 8) if max(int(x) for x in gpu.get("archs", [gpu["arch"]])) >= 120 else (12, 0)
# 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(int(x) for x in gpu.get("archs", [gpu["arch"]])) >= 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 = []
@@ -1330,7 +1347,18 @@ def data_folder(requested: str | None) -> tuple:
warn(f"cannot use {dest} for the model files ({e}): keeping them in {ROOT}")
dest = ROOT
elsewhere = []
for folder in [ROOT, *other_installs(settings)]:
# #198: the data folder remembered before (a --data-dir to a new place) is a source too, and so is a Strata-data
# folder nested in any of them (an install that kept its models one level down)
sources = [ROOT, *other_installs(settings)]
if settings.get("data_dir") and Path(settings["data_dir"]) != dest:
sources.append(Path(settings["data_dir"]))
sources += [f / "Strata-data" for f in list(sources) if (f / "Strata-data") != dest]
seen = set()
for folder in sources:
key = os.path.normcase(str(folder))
if key in seen:
continue
seen.add(key)
if folder == dest or not has_data(folder):
continue
if not same_drive(folder, dest):
@@ -1503,14 +1531,21 @@ def upgrade_config(cfg_path: Path, cfg: dict) -> dict:
def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_browser=True, yes=False,
layer_split=None) -> int:
layer_split=None, keep=None) -> int:
"""keep: settings given on this start that the model keeps from now on (--host, --api-key, --draft-vocab)."""
cfg = upgrade_config(cfg_path, json.loads(cfg_path.read_text(encoding="utf-8-sig")))
missing = [p for p in [cfg["exe"], *[a for a in cfg["args"] if a.endswith(".gguf")]] if not Path(p).exists()]
if missing:
fail(f"{cfg_path.name} refers to missing files: {missing[0]}", "run it again with --setup to repair")
keep = {k: v for k, v in (keep or {}).items() if v is not None}
if keep and any(cfg.get(k) != v for k, v in keep.items()): # #179: a --host/--api-key on a start was ignored
cfg.update(keep)
cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8")
ok("saved for this model: " + ", ".join("api key" if k == "api_key" else f"{k.replace('_', ' ')} {v}"
for k, v in keep.items()))
cfg_path.touch() # the most recently used model
if "--mtp" in cfg["args"][:-1]:
refresh_draft_vocab(Path(cfg["args"][cfg["args"].index("--mtp") + 1]))
refresh_draft_vocab(Path(cfg["args"][cfg["args"].index("--mtp") + 1]), cfg.get("draft_vocab", "cjk"))
cmd = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path),
"--port", str(port or cfg.get("port", 8080))]
if cfg.get("backend") == "hip": # AMD: one card, numbered as HIP numbers them
@@ -1576,17 +1611,24 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_
OLD_DRAFT_VOCABS = {"369151522226a5edaa5f12cfd1e2ae7db8f4fbdbd222f3dcf327dced9597fb25"} # to 0.1.26: 27 Han tokens
def refresh_draft_vocab(rt: Path) -> None:
"""The draft layer's token subset (data/draft_vocab.bin) in the MTP folder: copied when missing, and an older
shipped one is replaced, so an update reaches existing installs (0.1.27 added the CJK scripts, #137)."""
new, dst = ROOT / "data" / "draft_vocab.bin", rt / "draft_vocab.bin"
DRAFT_VOCABS = {"cjk": "draft_vocab.bin", "en": "draft_vocab_en.bin"}
def refresh_draft_vocab(rt: Path, choice: str = "cjk") -> None:
"""The draft layer's token subset in the MTP folder: `cjk` (data/draft_vocab.bin, since 0.1.27, #137) or `en`
(data/draft_vocab_en.bin, the English/code subset before it: ~110 MiB less VRAM, English answers 1-2% faster).
Copied when missing or when a shipped subset other than the chosen one is there; a subset made by hand is kept."""
new, dst = ROOT / "data" / DRAFT_VOCABS.get(choice, "draft_vocab.bin"), rt / "draft_vocab.bin"
if not new.exists() or not rt.is_dir():
return
if dst.exists():
old = hashlib.sha256(dst.read_bytes()).hexdigest()
if old not in OLD_DRAFT_VOCABS or old == hashlib.sha256(new.read_bytes()).hexdigest():
shipped = OLD_DRAFT_VOCABS | {hashlib.sha256((ROOT / "data" / f).read_bytes()).hexdigest()
for f in DRAFT_VOCABS.values() if (ROOT / "data" / f).exists()}
if old not in shipped or old == hashlib.sha256(new.read_bytes()).hexdigest():
return
ok("draft layer: the token subset now includes Chinese, Japanese and Korean")
ok("draft layer: the token subset " + ("with Chinese, Japanese and Korean" if choice == "cjk" else
"for English and code (less VRAM)"))
shutil.copyfile(new, dst)
@@ -1618,7 +1660,7 @@ def write_run_script(model, cfg_path, port, engine="strata"):
if WIN:
script = ROOT / f"run-{model.lower()}.bat"
script.write_text("@echo off\r\ntitle Strata " + model + "\r\ncd /d \"" + str(ROOT) + "\"\r\n" +
" ".join(f'"{x}"' for x in serve) + "\r\npause\r\n", encoding="utf-8")
" ".join(f'"{x}"' for x in serve) + "\r\nif errorlevel 1 pause\r\n", encoding="utf-8")
else:
script = ROOT / f"run-{model.lower()}.sh"
script.write_text("#!/bin/sh\ncd \"" + str(ROOT) + "\"\nexec " + " ".join(f'"{x}"' for x in serve) + "\n",
@@ -1668,6 +1710,9 @@ def main() -> int:
ap.add_argument("--check", action="store_true", help="only check this PC and exit")
ap.add_argument("--calibrate", action="store_true",
help="tune the engine's settings for this PC (about 5-10 minutes), then start the model")
ap.add_argument("--draft-vocab", choices=list(DRAFT_VOCABS),
help="the draft layer's tokens: cjk = with Chinese, Japanese and Korean (default), en = English "
"and code only (~110 MiB less VRAM, English answers 1-2%% faster)")
ap.add_argument("--low-ram", choices=["auto", "on", "off"], default="auto",
help="map the model's experts from its folder instead of copying them into RAM (for a PC with a big "
"GPU and little RAM); auto: when the experts would not fit the RAM")
@@ -1727,19 +1772,22 @@ def main() -> int:
say(f" {i}) {json.loads(c.read_text(encoding='utf-8-sig')).get('model_name', c.stem)}")
pick_cfg = have[int(ask("Tune which one?", [str(i) for i in range(1, len(have) + 1)], "1", a.yes)) - 1]
calibrate_config(pick_cfg)
return 0 if a.no_start else start(pick_cfg, a.port, run_gpu, yes=a.yes, layer_split=a.layer_split)
return 0 if a.no_start else start(pick_cfg, a.port, run_gpu, yes=a.yes, layer_split=a.layer_split,
keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab})
if have and not (a.setup or a.model or a.family or a.check or a.no_start):
if not a.build:
update_installed_engine(a.prebuilt)
if len(have) == 1:
return start(have[0], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split)
return start(have[0], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split,
keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab})
say()
for i, c in enumerate(have, 1):
say(f" {i}) {json.loads(c.read_text(encoding='utf-8-sig')).get('model_name', c.stem)}")
say(f" {len(have) + 1}) install another model / change settings")
pick = int(ask("Which one?", [str(i) for i in range(1, len(have) + 2)], "1", a.yes))
if pick <= len(have):
return start(have[pick - 1], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split)
return start(have[pick - 1], a.port, run_gpu, yes=a.yes, layer_split=a.layer_split,
keep={"host": a.host, "api_key": a.api_key, "draft_vocab": a.draft_vocab})
# ---- 1. the PC
step(1, "checking your PC")
@@ -1927,9 +1975,14 @@ def main() -> int:
for i, c in enumerate(CONTEXTS, 1):
say(f" {i}) {c // 1024}K tokens" + (" (recommended for your GPU)" if c == rec_ctx else ""))
ctx = CONTEXTS[int(ask("Context?", [str(i) for i in range(1, 6)], str(CONTEXTS.index(rec_ctx) + 1), a.yes)) - 1]
if model in ("IQ3_XXS", "IQ3_S") and ram < 90 and ctx > 131072:
warn(f"{model} with a 262K context needs more than 64 GB of RAM ({MODELS[model]['arena_gb']:.0f} GB of experts "
"+ the context): using 128K")
# The experts' arena plus the context's KV (in RAM from 64K up: ~13.7 KB/token at 8 bits) must fit, with room
# for everything else. Counted, not a fixed 90 GB: 24 GB of room keeps the rule for 64 GB PCs as it was (128K
# for both 3-bit models), while a box with ~84 GB keeps the 262K it asked for (measured: a Colab A100-40G runs
# IQ3_S at 262K with images in 56 of its 83.5 GiB).
need_gb = MODELS[model].get("arena_gb", 0) + ctx * 13 * 1056 / 1e9 + 24
if model in ("IQ3_XXS", "IQ3_S") and ram < need_gb and ctx > 131072:
warn(f"{model} with a {ctx // 1024}K context needs about {need_gb:.0f} GB of RAM "
f"({MODELS[model]['arena_gb']:.0f} GB of experts + the context + room for the rest): using 128K")
ctx = 131072
ok(f"context: {ctx} tokens")
# the KV cache (the model's memory of the conversation): 8-bit, or 4-bit after a Hadamard rotation (PR #21)
@@ -1983,6 +2036,9 @@ def main() -> int:
models_dir, shards = cand[0].parent, cand
ok(f"model files found in {models_dir}")
break
for s in shards: # #173: a whole file copied in by hand has no finish mark
if s.exists() and not done(s) and whole_shard(s):
mark(s, "whole (checked against its own tensor directory)")
have_model = all(s.exists() and (done(s) or a.gguf_dir) for s in shards)
need = (0 if a.gguf_dir or have_model else MODELS[model]["download_gb"]) + 8 + \
(40 if model == "Q2_0" and avx512 and family == "qwen" else 0) + (1 if vision != "none" else 0) + \
@@ -2097,7 +2153,7 @@ def main() -> int:
"--out", str(mtp / "mtp-q2_0.gguf")], env=env)
run([sys.executable, str(ROOT / "tools" / "mtp_rt.py"), "--gguf", str(mtp / "mtp-q2_0.gguf"), "--out", str(rt)],
env=env)
refresh_draft_vocab(rt)
refresh_draft_vocab(rt, a.draft_vocab or "cjk")
ok(f"MTP draft layer: {rt}")
# ---- 7. the start script
step(7, "writing the start script")
@@ -2163,6 +2219,8 @@ def main() -> int:
cfg["host"] = a.host
if a.api_key:
cfg["api_key"] = a.api_key
if a.draft_vocab:
cfg["draft_vocab"] = a.draft_vocab
if vision != "none" and backend != "llama":
cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), "model": str(shards[0]),
"gpu": vision == "gpu", "max_tokens": VISION[vision]["max_tokens"]}
+17 -3
View File
@@ -772,6 +772,14 @@ void expert_pool_dispatch(void* user, const float* x_f, const int32_t* ids, cons
d.experts += k;
}
namespace {
// the verify window's per-entry tables in `expert_pool_dispatch_multi` (`kind`, `distinct`, `first_of`)
// are fixed arrays of this many entries: MAXT tokens of the model's 10 routed experts must fit, and a larger k is
// refused at run time rather than written past them.
constexpr int64_t kMaxWindowEntries = 128;
static_assert(strata::kernels::cpu::MAXT * 10 <= kMaxWindowEntries, "a verify window's entries overflow the tables");
} // namespace
void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k,
float* out) {
using namespace strata::kernels::cpu;
@@ -782,6 +790,12 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
d.fail_layer = d.layers;
return;
}
if (k < 1 || n_tok * k > kMaxWindowEntries) {
d.failed = true;
d.fail = "a verify window routes more entries than the expert pool's window tables hold";
d.fail_layer = d.layers;
return;
}
if ((int64_t) d.act_multi.size() < n_tok) d.act_multi.resize((size_t) MAXT);
const ExpertLayout& lay = expert_layout();
const bool native = lay.native;
@@ -802,9 +816,9 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32
// ---- plan v0.3 P6: the GPU's share, decided and published FIRST so the GPU starts while the CPU works.
// Distinct experts in routing order; resident ones and the last pcie_num/256 of the missed ones go to the GPU.
const int64_t n = n_tok * k;
int32_t kind[128]; // per entry: -1 CPU, 0 VRAM, 1 PCIe
if (d.plan != nullptr && n <= 128 && n <= d.plan->cap) {
int64_t distinct[128], first_of[128];
int32_t kind[kMaxWindowEntries]; // per entry: -1 CPU, 0 VRAM, 1 PCIe
if (d.plan != nullptr && n <= kMaxWindowEntries && n <= d.plan->cap) {
int64_t distinct[kMaxWindowEntries], first_of[kMaxWindowEntries];
int nd = 0, nmiss = 0;
for (int64_t i = 0; i < n; ++i) {
first_of[i] = i;
+13
View File
@@ -292,6 +292,19 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
return true;
}
uint64_t MtpDrafter::bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const {
uint64_t bytes = head_logits_ ? 0 : (uint64_t) max_t_ * (uint64_t) n_vocab * sizeof(float);
if (dhead_ == nullptr) {
if (FILE* f = std::fopen((rt_dir_ + "/draft_vocab.bin").c_str(), "rb")) {
std::fseek(f, 0, SEEK_END);
const long size = std::ftell(f);
std::fclose(f);
if (size >= 4 && size % 4 == 0) bytes += (uint64_t) (size / 4) * head_row_bytes + (uint64_t) size;
}
}
return bytes;
}
bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err) {
const OnDevice on_device(device_);
wt_ = &wt;
+25 -9
View File
@@ -5,6 +5,7 @@
#include <cuda_runtime.h>
#include <climits>
#include <cstdio>
#include <cstring>
#include <exception>
@@ -102,6 +103,7 @@ const NativeEmbed* native_embed() { return g_embed; }
NativeEmbed::~NativeEmbed() {
if (host_) cudaFreeHost(host_);
else if (dev_) cudaFree(const_cast<void*>(dev_)); // the VRAM fallback below
}
bool NativeEmbed::load(const std::string& path, int64_t n_embd, int64_t n_vocab, std::string& err) {
@@ -119,17 +121,31 @@ bool NativeEmbed::load(const std::string& path, int64_t n_embd, int64_t n_vocab,
row_ = strata::kernels::iq_row_bytes((int) t->type, n_embd);
bytes_ = (uint64_t) row_ * (uint64_t) n_vocab;
if (cudaHostAlloc(&host_, bytes_, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess) {
// Under WSL2 the driver's pinned/mapped host budget (~1 GiB) can be spent by the GPU contexts
// themselves (three cards). The table is only gathered from, so keep it in the current device's VRAM
// instead: it costs its size there and reads faster than over PCIe.
cudaGetLastError();
host_ = nullptr;
err = "native embedding: cannot pin " + std::to_string(bytes_ >> 20) + " MiB";
return false;
void* d = nullptr;
if (cudaMalloc(&d, bytes_) != cudaSuccess ||
cudaMemcpy(d, gguf.tensor_data(*t), bytes_, cudaMemcpyHostToDevice) != cudaSuccess) {
if (d) cudaFree(d);
cudaGetLastError();
err = "native embedding: cannot pin " + std::to_string(bytes_ >> 20) + " MiB, nor place it in VRAM";
return false;
}
std::fprintf(stderr, "strata: native embedding: cannot pin %llu MiB, kept in VRAM instead\n",
(unsigned long long) (bytes_ >> 20));
dev_ = d;
} else {
std::memcpy(host_, gguf.tensor_data(*t), bytes_);
void* d = nullptr;
if (cudaHostGetDevicePointer(&d, host_, 0) != cudaSuccess) {
err = "native embedding: no device alias for the mapped table";
return false;
}
dev_ = d;
}
std::memcpy(host_, gguf.tensor_data(*t), bytes_);
void* d = nullptr;
if (cudaHostGetDevicePointer(&d, host_, 0) != cudaSuccess) {
err = "native embedding: no device alias for the mapped table";
return false;
}
dev_ = d;
type_ = (int) t->type;
n_embd_ = n_embd;
n_vocab_ = n_vocab;
+4 -1
View File
@@ -148,7 +148,8 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
return false;
}
if (hits.d_res == nullptr || hits.cache_base == nullptr || hits.blob <= 0) {
err = "verify: needs the profile-filled VRAM expert tier (--expert-profile and --expert-cache)";
err = "verify: needs the profile-filled VRAM expert tier (--expert-profile and --expert-cache); with "
"--expert-cache auto, no VRAM was left for it: lower --max-context, use --kv k8v4 or images on the CPU";
return false;
}
std::string why;
@@ -850,8 +851,10 @@ bool Verifier::capture(int T, std::string& err) {
if (ty == cudaGraphNodeTypeKernel) {
cudaKernelNodeParams kp{};
if (cudaGraphKernelNodeGetParams(nd, &kp) == cudaSuccess) {
#if CUDART_VERSION >= 12030 // cudaFuncGetName arrived in CUDA 12.3
const char* fn = nullptr;
if (cudaFuncGetName(&fn, kp.func) == cudaSuccess && fn) name = fn;
#endif
}
} else if (ty == cudaGraphNodeTypeMemcpy) name = "memcpy";
else if (ty == cudaGraphNodeTypeMemset) name = "memset";
+80
View File
@@ -0,0 +1,80 @@
// src/kernels/bf16_bits_test.cpp - `bf16_bits.hpp` against ggml's rule, over EVERY f32 bit pattern (CPU only).
//
// the rounding add `i + 0x7FFF + bit16` carries out of the mantissa for a NaN, so 0x7FFFFFFF came back as
// -0 and 0x7F800001 as +inf - an upstream NaN was masked instead of propagated. `ggml_compute_fp32_to_bf16`
// (ggml-impl.h at the pinned llama.cpp) tests the NaN first and returns `(i >> 16) | 64`. Three checks, all
// exhaustive (2^32 inputs, a few seconds):
//
// 1. the header equals ggml's function, transcribed below, on every input;
// 2. on every NON-NaN input it equals the previous rounding, so the change cannot move a finite value or an
// infinity by a single bit;
// 3. every NaN input gives a quiet NaN of the same sign.
//
// And the round trip over all 65,536 bf16 patterns: a non-NaN bf16 survives f32 and back unchanged.
#include "strata/kernels/bf16_bits.hpp"
#include <cstdint>
#include <cstdio>
#include <cstring>
namespace {
/// ggml_compute_fp32_to_bf16, ggml/src/ggml-impl.h (MIT, the ggml authors), on raw bits.
uint16_t ggml_bf16(uint32_t u) {
if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 64);
return (uint16_t) ((u + (0x7fffu + ((u >> 16) & 1u))) >> 16);
}
/// The rule before this fix, kept only to prove the change is confined to NaN inputs.
uint16_t previous_bf16(uint32_t u) {
u = (u + ((u >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u;
return (uint16_t) (u >> 16);
}
bool is_nan_bits(uint32_t u) { return (u & 0x7fffffffu) > 0x7f800000u; }
} // namespace
int main() {
unsigned long long vs_ggml = 0, vs_previous = 0, nan_lost = 0, nan_inputs = 0, previous_masked = 0;
uint32_t first_bad = 0;
bool have_bad = false;
for (uint64_t k = 0; k <= 0xFFFFFFFFull; ++k) {
const uint32_t u = (uint32_t) k;
float f;
std::memcpy(&f, &u, 4);
const uint16_t got = strata::kernels::bf16_from_f32(f);
if (got != ggml_bf16(u)) {
++vs_ggml;
if (!have_bad) { first_bad = u; have_bad = true; }
}
if (is_nan_bits(u)) {
++nan_inputs;
const uint32_t back = (uint32_t) got << 16;
// a quiet NaN (bit 22 of the f32) with the input's sign
if (!is_nan_bits(back) || (back & 0x00400000u) == 0 || (back >> 31) != (u >> 31)) ++nan_lost;
if (!is_nan_bits((uint32_t) previous_bf16(u) << 16)) ++previous_masked;
} else if (got != previous_bf16(u)) {
++vs_previous;
if (!have_bad) { first_bad = u; have_bad = true; }
}
}
std::printf(" f32 -> bf16 over 2^32 inputs: %llu differ from ggml, %llu non-NaN differ from the previous rule\n",
vs_ggml, vs_previous);
std::printf(" NaN inputs: %llu, not a quiet same-sign NaN now: %llu (the previous rule masked %llu of them)\n",
nan_inputs, nan_lost, previous_masked);
if (have_bad) std::printf(" first mismatch at input 0x%08x\n", first_bad);
unsigned long long trip_bad = 0;
for (uint32_t h = 0; h <= 0xFFFFu; ++h) {
const float f = strata::kernels::f32_from_bf16((uint16_t) h);
const uint16_t back = strata::kernels::bf16_from_f32(f);
const bool nan = is_nan_bits(h << 16);
if (back != (nan ? (uint16_t) (h | 64u) : (uint16_t) h)) ++trip_bad;
}
std::printf(" bf16 -> f32 -> bf16 over 65536 patterns: %llu wrong\n", trip_bad);
const bool ok = vs_ggml == 0 && vs_previous == 0 && nan_lost == 0 && trip_bad == 0 && previous_masked > 0;
std::printf("\nbf16_bits_test %s\n", ok ? "OK" : "FAILED");
return ok ? 0 : 1;
}
+21
View File
@@ -19,6 +19,7 @@
#include <immintrin.h>
#include <cmath>
#include <cstdlib>
#include <cstring>
namespace strata::kernels::cpu {
@@ -77,6 +78,23 @@ inline float hsum8(__m256 v) {
return _mm_cvtss_f32(s);
}
// E-2 (iq_avx512.cpp) on the AVX-2 path: the pool streams the expert rows from DRAM at ~25 GB/s (4 KB pages
// when large pages are refused), so ask for the bytes a few blocks before the decode needs them - 2048 B is
// two gate/up rows ahead, a row is ~1 KB. Same switch as the AVX-512 kernels: STRATA_IQ_PREFETCH is the
// distance in bytes, 0 = off, default 2048. Measured on a Zen 3 5700X3D (no AVX-512) on IQ3_S decode: -4% on
// the gate/up phase, +1.0 GB/s over the rows, -1.3% ms/round end to end. The non-temporal hint measured
// worse than T0 at the same distance, so this keeps T0.
const int prefetch_ahead = [] {
const char* v = std::getenv("STRATA_IQ_PREFETCH");
return v ? std::atoi(v) : 2048;
}();
inline void rows_ahead(const uint8_t* p) {
if (prefetch_ahead <= 0) return;
_mm_prefetch((const char*) p, _MM_HINT_T0);
_mm_prefetch((const char*) p + 64, _MM_HINT_T0);
}
// ---- per format: one 32-value half (values 64*j + 32*half .. +31) -> grid magnitudes, sign vector, scales
template <int TY> struct Fmt32;
@@ -165,6 +183,7 @@ inline void row_dot(const uint8_t* row, int nblocks, const block_q8_K* const* y,
for (int t = 0; t < NT; ++t) accf[t] = _mm256_setzero_ps();
for (int i = 0; i < nblocks; ++i) {
const uint8_t* blk = row + (size_t) i * Fmt32<TY>::bytes;
rows_ahead(blk + prefetch_ahead);
__m256i acci[NT];
for (int t = 0; t < NT; ++t) acci[t] = _mm256_setzero_si256();
for (int j = 0; j < 4; ++j) {
@@ -229,6 +248,7 @@ inline void row_dot_iq2xs(const uint8_t* row, int nblocks, const block_q8_K* con
for (int t = 0; t < NT; ++t) accf[t] = _mm256_setzero_ps();
for (int i = 0; i < nblocks; ++i) {
const uint8_t* blk = row + (size_t) i * 74;
rows_ahead(blk + prefetch_ahead);
// the 8 scale bytes -> 16 half-scales of 2*s+1, interleaved [a0, b0, a1, b1, ...] (ggml's unpack)
__m128i st = _mm_set1_epi64x((long long) u64(blk + 66));
st = _mm_unpacklo_epi8(_mm_and_si128(st, m4), _mm_and_si128(_mm_srli_epi16(st, 4), m4));
@@ -382,6 +402,7 @@ void iq4nl_rows(const uint8_t* w, size_t row_bytes, int n, const block_q8_0* con
for (int t = 0; t < NT; ++t) accf[t] = _mm256_setzero_ps();
for (int ib = 0; ib < nb; ++ib) {
const uint8_t* blk = row + (size_t) ib * sizeof(block_iq4_nl);
rows_ahead(blk + prefetch_ahead);
const __m128i bits = _mm_loadu_si128((const __m128i*) (blk + 2));
const __m128i lo = _mm_and_si128(bits, m4b); // values 0..15
const __m128i hi = _mm_and_si128(_mm_srli_epi16(bits, 4), m4b); // values 16..31
+3
View File
@@ -19,6 +19,9 @@ __device__ __forceinline__ float h2f(const uint8_t* p) {
}
__device__ __forceinline__ uint16_t f2bf(float f) {
uint32_t u = __float_as_uint(f);
// a NaN (a NaN scale in the block) stays a quiet NaN, as in ggml_compute_fp32_to_bf16 and `bf16_from_f32`:
// the rounding add below would carry it into -0 or inf
if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 64u);
u += 0x7fffu + ((u >> 16) & 1u); // round to nearest even
return (uint16_t) (u >> 16);
}
+8
View File
@@ -209,6 +209,14 @@ void kv_stream_resolve(const KvStreamMap& m, const QsaAttnPools& slots, const Kv
std::fprintf(stderr, "kv_stream: a block's scale run must be a multiple of 16 bytes\n");
std::exit(1);
}
// one sweep step looks at RT consecutive slots `(hand + thread) % n_slots`; with fewer slots than RT two
// threads see the same slot and may both take it for two different misses. The engine never streams with fewer
// than qsa_kv_resident_min() / page_size = 5,120 slots, so this is a guard, not a limit.
if (m.n_slots < RT) {
std::fprintf(stderr, "kv_stream: %lld slots is fewer than the resolve block (%d): the clock sweep would take a "
"slot twice\n", (long long) m.n_slots, RT);
std::exit(1);
}
resolve_kernel<<<1, RT, 0, (cudaStream_t) stream>>>(m, ids, steps, (int) n_q, (int) cap, (int) s.page_size);
check("resolve");
copy_kernel<<<96, 128, 0, (cudaStream_t) stream>>>(m, runs_of(slots, host, fmt, s));
+7 -4
View File
@@ -113,14 +113,16 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest
if (t < n_here) {
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);
// 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.
for (int c = warp; c < CHUNK; c += WARPS) {
if (c >= n_here) {
if (c >= n_here || srow[c] < 0) {
if (lane < G) sp[lane][c] = -FLT_MAX;
continue;
}
@@ -141,8 +143,8 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest
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) ? __expf(a - m) : 0.0f;
const float eb = (lane + 32 < n_here) ? __expf(b - m) : 0.0f;
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;
sp[h][lane] = ea;
sp[h][lane + 32] = eb;
const float l = warp_sum(ea + eb);
@@ -154,6 +156,7 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest
#pragma unroll
for (int h = 0; h < G; ++h) acc[h] = 0.0f;
for (int c = 0; c < n_here; ++c) {
if (srow[c] < 0) continue; // masked above, weight 0
float v;
if constexpr (KV_MODE == 0) {
v = __half2float(__ushort_as_half(p.v_pool[srow[c] * HD + t]));
+56
View File
@@ -429,6 +429,54 @@ __global__ void __launch_bounds__(TK_T) block_topk_reg_kernel(const float* __res
}
}
// Block scores with every key block read ONCE for all of a call's queries (block_scores_kernel's grid is
// (max_blocks / 8) x nq: ~24,600 mostly-idle blocks per layer at a decode window, each key re-read per query). A fixed
// grid strides over the blocks; per (block, query) the same arithmetic in the same order as block_scores_kernel.
// qsa_block_scores takes it for every call without an active-block count and at most MQ queries: the captured decode
// window, the uncaptured decode, and prefill's pooled16 call.
constexpr int MQ = 8;
__global__ void __launch_bounds__(SCORE_WARPS * 32) block_scores_multi_kernel(const float* __restrict__ pooled,
const float* __restrict__ dead,
const float* __restrict__ q_idx,
const int32_t* __restrict__ steps, int nq,
int64_t max_blocks, float* __restrict__ out) {
__shared__ __align__(16) float qs[MQ * IDX_HEADS * IDX_DIM];
__shared__ int64_t s_nkv[MQ], s_nbid[MQ];
for (int i = threadIdx.x; i < nq * IDX_HEADS * IDX_DIM; i += blockDim.x) qs[i] = q_idx[i];
if (threadIdx.x < nq) {
s_nkv[threadIdx.x] = steps[threadIdx.x * kStepCount + kStepNKv];
s_nbid[threadIdx.x] = steps[threadIdx.x * kStepCount + kStepNBid];
}
__syncthreads();
int64_t top = 0;
for (int q = 0; q < nq; ++q) top = s_nbid[q] > top ? s_nbid[q] : top;
const int lane = threadIdx.x & 31;
const int64_t wstride = (int64_t) gridDim.x * SCORE_WARPS;
for (int64_t b = (int64_t) blockIdx.x * SCORE_WARPS + (threadIdx.x >> 5); b <= top && b < max_blocks; b += wstride) {
const float4 kp = *reinterpret_cast<const float4*>(pooled + b * IDX_DIM + lane * 4);
const float4 kd = *reinterpret_cast<const float4*>(dead + lane * 4);
for (int qi = 0; qi < nq; ++qi) {
const int64_t n_bid = s_nbid[qi];
if (b > n_bid) continue;
const float4 k4 = (b == n_bid) ? kd : kp;
const float* q = qs + qi * IDX_HEADS * IDX_DIM + lane * 4;
float score = 0.0f;
#pragma unroll
for (int h = 0; h < IDX_HEADS; ++h) {
const float4 q4 = *reinterpret_cast<const float4*>(q + h * IDX_DIM);
float d = k4.x * q4.x + k4.y * q4.y + k4.z * q4.z + k4.w * q4.w;
#pragma unroll
for (int o = 16; o > 0; o >>= 1) d += __shfl_xor_sync(0xffffffffu, d, o);
score += d > 0.0f ? d : 0.0f;
}
if (lane == 0) {
if (b == n_bid && s_nkv[qi] % R != 0) score += 1e9f;
out[qi * max_blocks + b] = score;
}
}
}
}
} // namespace
void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq,
@@ -439,6 +487,14 @@ void qsa_block_scores(const float* pooled, const float* dead, const float* q_idx
std::exit(1);
}
// a block past a query's n_bid returns at once: the grid need only reach the batch's largest n_bid (C-1)
static const bool multi = [] { const char* v = std::getenv("STRATA_SCORES_MULTI"); return v == nullptr || std::atoi(v) != 0; }();
if (multi && nq <= MQ && active_blocks <= 0) { // no active count: decode (captured or not) and prefill's pooled16
block_scores_multi_kernel<<<256, SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(pooled, dead, q_idx, steps, (int) nq,
max_blocks, scores);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) { std::fprintf(stderr, "qsa_block_scores multi: %s\n", cudaGetErrorString(e)); std::exit(1); }
return;
}
const int64_t reach = active_blocks > 0 && active_blocks < max_blocks ? active_blocks : max_blocks;
const dim3 grid((unsigned) ((reach + SCORE_WARPS - 1) / SCORE_WARPS), (unsigned) nq);
block_scores_kernel<<<grid, SCORE_WARPS * 32, 0, (cudaStream_t) stream>>>(pooled, dead, q_idx, steps, max_blocks,
+4
View File
@@ -16,6 +16,7 @@
#include "strata/kernels/s2_expert_grouped.hpp"
#include "strata/kernels/quantize_act.hpp"
#include "strata/kernels/verify_kernels.hpp"
#include <cuda_fp16.h>
#include <cuda_runtime.h>
@@ -512,6 +513,9 @@ namespace {
// hit kernel's.
constexpr int GU_CHUNKS = (H / 32 + 31) / 32; // 3: chunks of a gate/up row per lane (80 chunks / 32 lanes)
constexpr int GMAX = 8; // entries per group (tokens routed to one expert in a window)
// a group holds one entry per token of the window routed to its expert, and the kernels below keep at
// most GMAX of them (`min(..., GMAX)`): a longer window would drop entries without a word.
static_assert(GMAX >= kVerifyMaxT, "a verify window's group can exceed GMAX entries");
constexpr int GU_ROWS = 32; // gate/up rows per block: 4 per warp
constexpr int D_ROWS = 64; // down rows per block: 8 per warp
+11 -3
View File
@@ -147,14 +147,20 @@ __global__ void s_gemv_q8_split_kernel(const uint8_t* __restrict__ x, const uint
constexpr int PER_BYTE = 8 / CODE_BITS;
const int warps_per_block = (int) (blockDim.x >> 5);
const long long o = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5);
if (o >= n_out) return;
const int lane = threadIdx.x & 31;
// THE CODEBOOK, IN SHARED MEMORY. 16 bytes, loaded once per block by the first 16 threads, instead of a
// divergent constant read per element - measured at 2.12x of this whole kernel (see the note on `kIq4Nl`).
//
// THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN, as in `s_gemv_q8k_kernel`. The return used to
// sit above them, so whenever `n_out % 8 != 0` the last block's surplus warps left before a barrier the
// others still waited at - undefined behaviour that every shape in the pack (a multiple of 8) happened to
// avoid. `o` is per-WARP, so the return below keeps whole warps together and the shuffle reduction's
// full mask stays valid.
__shared__ signed char s_iq4nl[16];
if (threadIdx.x < 16) s_iq4nl[threadIdx.x] = kIq4Nl[threadIdx.x];
__syncthreads();
if (o >= n_out) return;
const long long n_groups = n_in >> group_shift;
const long long codes_per_row = n_in / PER_BYTE;
@@ -655,8 +661,10 @@ void s_gemv_q8_0_split(const uint8_t* x_q8_0, const uint8_t* codes, const float*
form.group_elems);
std::exit(1);
}
if (form.group_elems % 4 != 0) {
std::fprintf(stderr, "s_gemv_q8_0_split: group_elems %d is not a multiple of 4\n", form.group_elems);
// SIXTEEN, NOT FOUR: a lane-iteration takes QE = 16 consecutive elements under ONE scale (see the kernel),
// so a group of 4 or 8 would read the wrong scale for most of them. The Q8_K launcher already said 16.
if (form.group_elems % 16 != 0) {
std::fprintf(stderr, "s_gemv_q8_0_split: group_elems %d is not a multiple of 16\n", form.group_elems);
std::exit(1);
}
int group_shift = 0;
+466 -4
View File
@@ -10,9 +10,14 @@
// produces a valid token, so only a comparison at the distribution level can tell them apart; the parity test
// does that against an independently computed distribution.
//
// Both kernels put ONE BLOCK per token over the vocabulary: `sampler_greedy_kernel` is the plain argmax,
// `sampler_kernel` runs the sampled chain as `top_k` block-argmax rounds followed by the top_p / temperature /
// draw chain (its header says why the selection must be parallel and why the tie rule keeps the semantics).
// `sampler_greedy_kernel` is the plain argmax, one block per token over the vocabulary. The sampled chain has
// three implementations that pick the same token, bit for bit:
// - the SPLIT top_k (default): `sampler_split_part_kernel` cuts each row into 4,096-logit blocks over the whole
// GPU, each keeps its own top_k, and `sampler_split_merge_kernel` merges those lists and runs the tail;
// - `sampler_one_block_kernel` (`STRATA_SAMPLER_ONE_BLOCK=1`, and the fallback when the split cannot run): one
// block per token, `top_k` block-argmax rounds, each over the logits after the previous pick;
// - `sampler_kernel` (`STRATA_OLD_SAMPLER=1`), the kernel of engine 0.1.20, kept as the reference.
// The two new ones share `sampled_tail_warp` (top_p / min_p / temperature / draw on one warp).
#include "strata/kernels/sampler.hpp"
#include <cuda_runtime.h>
@@ -20,6 +25,9 @@
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <vector>
namespace strata::kernels {
namespace {
@@ -170,6 +178,11 @@ __global__ void sampler_greedy_kernel(const float* __restrict__ logits, int n_vo
/// serial scan's strict `>` keeps the first maximum it meets), so the kept sequence - both its set and its
/// order - is unchanged; `top_p`'s cut reads that order in double arithmetic as before; temperature and the
/// Philox draw apply after the cut. `sampler_parity` pins all of it against the host reference.
///
/// **KEPT AS THE REFERENCE, BEHIND `STRATA_OLD_SAMPLER=1`.** Two costs remain in it: the `taken`
/// sweep is O(k) per logit per round, O(k^2 x n_vocab) per row (47 M shared-memory compares at k = 20, 500 M at
/// 64), and the double-precision tail runs on all 1,024 threads where one warp suffices - GeForce issues FP64 at
/// 1/64 of FP32. The kernels after this one remove both and select the same list in the same order.
__global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, int n_tokens,
const int* __restrict__ history, int history_len, const SamplerParams p,
int* __restrict__ out) {
@@ -302,6 +315,433 @@ __global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, in
if (threadIdx.x == 0) out[t] = pick;
}
// ---- the same list, in the same order, without the `taken` sweep ----
//
// THE SELECTION ORDER. `sampler_kernel`'s rounds rank a candidate (value, id) before (value', id') when value >
// value', or value == value' and id < id' - each thread's ascending scan keeps the first maximum it meets (strict
// `>`), and the reductions resolve a tie to the lower id. That is a strict total order (-0 and +0 compare equal and
// fall to the id, as there), so round i picks the i-th logit of the order. NaN and -inf are never picked (`s > bv`
// from -inf fails); a round that finds nothing yields the SENTINEL (-inf, n_vocab), stored as id 0.
constexpr int kSelMax = 64; // the widest top_k list, `sampler_kernel`'s KMAX
constexpr unsigned kFullMask = 0xFFFFFFFFu;
// top_k 1..64 as given; 0 ("off") and anything wider keep 64; never more than the vocabulary
__host__ __device__ __forceinline__ int sampled_k(int top_k, int n_vocab) {
int k = (top_k > 0 && top_k < kSelMax) ? top_k : kSelMax;
return k > n_vocab ? n_vocab : k;
}
// (bv, bi) <- the first of (bv, bi) and (ov, oi) in the selection order
__device__ __forceinline__ void take_first(float& bv, int& bi, float ov, int oi) {
if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; }
}
// The first of the warp's 32 candidates, left in EVERY lane. An XOR butterfly is exact here: "the first of two" is
// associative and commutative in a strict total order (two lanes never hold different candidates that compare
// equal - an id is in one lane at most, and two sentinels are the same pair), so every lane ends with the same pair.
__device__ __forceinline__ void warp_first(float& bv, int& bi) {
#pragma unroll
for (int off = 16; off > 0; off >>= 1) {
const float ov = __shfl_xor_sync(kFullMask, bv, off);
const int oi = __shfl_xor_sync(kFullMask, bi, off);
take_first(bv, bi, ov, oi);
}
}
/// **THE TAIL ON ONE WARP, WITH `sampler_kernel`'S ARITHMETIC.** `sel_ids` / `sel_logit` (shared, `k` entries) are
/// the top_k list in selection order; the 32 lanes of one warp call this and lane 0 writes `out[t]`. The old tail
/// ran on all 1,024 threads, each computing the same ~4k double `exp`s - FP64 issues at 1/64 of FP32 on GeForce.
/// Here the lanes share the `exp`s (one per entry, into `ex`) and then the quotients, and lane 0 alone runs the two
/// ORDERED sums and the two cumulative scans. Every double is the one the old chain computed: the same `exp` of
/// the same argument, the sums in the same order, `cum += e / sum` with the same correctly rounded quotient - so
/// the cut, the survivors and the pick are the same. (`n_keep == 0`, reachable only with min_p > 1, which the
/// callers clamp, read `sel_ids[-1]` in the old tail; it reads `sel_ids[0]` here.)
__device__ void sampled_tail_warp(const int* sel_ids, const float* sel_logit, int k, const SamplerParams& p, int t,
int* __restrict__ out, double* ex) {
const int lane = (int) (threadIdx.x & 31);
const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f;
int n_keep = k;
float mx = sel_logit[0];
for (int i = 1; i < k; ++i) mx = fmaxf(mx, sel_logit[i]);
if (p.top_p < 1.0f) {
for (int i = lane; i < k; i += 32) ex[i] = exp((double) sel_logit[i] - (double) mx);
__syncwarp();
double sum = 0.0;
if (lane == 0)
for (int i = 0; i < k; ++i) sum += ex[i];
sum = __shfl_sync(kFullMask, sum, 0);
__syncwarp(); // lane 0 has read every `ex` before it is overwritten
for (int i = lane; i < k; i += 32) ex[i] = ex[i] / sum;
__syncwarp();
int cut = k;
if (lane == 0) {
double cum = 0.0;
for (int i = 0; i < k; ++i) {
cum += ex[i];
if (cum >= (double) p.top_p) { cut = i + 1; break; }
}
}
cut = __shfl_sync(kFullMask, cut, 0);
if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k;
n_keep = cut;
__syncwarp(); // `ex` is written again below
}
// min_p on top_p's survivors, as in `sampler_kernel` (every lane, the same float arithmetic)
if (p.min_p > 0.0f) {
const float thresh = sel_logit[0] + logf(p.min_p);
for (int i = 0; i < n_keep; ++i)
if (sel_logit[i] < thresh) { n_keep = i; break; }
}
// temperature, then one Philox draw
float smx = sel_logit[0] * inv_t;
for (int i = 1; i < n_keep; ++i) smx = fmaxf(smx, sel_logit[i] * inv_t);
for (int i = lane; i < n_keep; i += 32) ex[i] = exp((double) (sel_logit[i] * inv_t) - (double) smx);
__syncwarp();
double sum = 0.0;
if (lane == 0)
for (int i = 0; i < n_keep; ++i) sum += ex[i];
sum = __shfl_sync(kFullMask, sum, 0);
__syncwarp();
for (int i = lane; i < n_keep; i += 32) ex[i] = ex[i] / sum;
__syncwarp();
if (lane == 0) {
const float u = philox_uniform(p.seed, p.counter + (uint64_t) t);
double cum = 0.0;
int pick = sel_ids[n_keep > 0 ? n_keep - 1 : 0];
for (int i = 0; i < n_keep; ++i) {
cum += ex[i];
if ((double) u < cum) { pick = sel_ids[i]; break; }
}
out[t] = pick;
}
}
/// **THE ONE-BLOCK SAMPLED PATH: `sampler_kernel` WITHOUT THE `taken` SWEEP.** Round i's candidates are the logits
/// strictly AFTER round i-1's pick in the selection order, `s < prev_v || (s == prev_v && v > prev_i)`, which is
/// exactly the set `taken` left: the picks so far are the first i of the order, so what comes after the last one is
/// what has not been picked. The round is then the same block argmax with the same tie rule, so the list is the
/// same list in the same order. An empty round leaves (-inf, id 0) as before, and every round after it is empty
/// in both versions (nothing after -inf beats -inf). O(k x n_vocab) per row instead of O(k^2 x n_vocab), then warp
/// 0 runs the tail. `STRATA_SAMPLER_ONE_BLOCK=1`, and the fallback when the split path cannot run.
__global__ void __launch_bounds__(1024)
sampler_one_block_kernel(const float* __restrict__ logits, int n_vocab, const int* __restrict__ history,
int history_len, const SamplerParams p, int* __restrict__ out) {
const int t = blockIdx.x;
const float* l = logits + (size_t) t * n_vocab;
// the penalty window and its membership bitmap, exactly as in `sampler_kernel`
const int* hrow = history ? history + (size_t) t * history_len : nullptr;
int hlen = 0;
if (hrow) {
hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len;
if (hlen < 0) hlen = 0;
hrow += history_len - hlen; // the window is the TAIL
}
extern __shared__ unsigned int penal_bits[];
const int bits_words = (int) ((n_vocab + 31) / 32);
const bool use_bits = hrow != nullptr && hlen > 0 && bits_words > 0;
if (use_bits) {
for (int w = threadIdx.x; w < bits_words; w += blockDim.x) penal_bits[w] = 0u;
__syncthreads();
for (int i = threadIdx.x; i < hlen; i += blockDim.x)
if (hrow[i] >= 0 && hrow[i] < n_vocab) // an id outside the vocabulary is never a candidate
atomicOr(&penal_bits[hrow[i] >> 5], 1u << (hrow[i] & 31));
__syncthreads();
}
auto hit_count = [&](int v) -> int {
if (!use_bits || !(penal_bits[v >> 5] & (1u << (v & 31)))) return 0;
return history_count(hrow, hlen, v);
};
const int k = sampled_k(p.top_k, n_vocab);
__shared__ int sel_ids[kSelMax];
__shared__ float sel_logit[kSelMax];
__shared__ double ex[kSelMax];
__shared__ float sv[32];
__shared__ int si[32];
const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31);
float prev_v = __int_as_float(0x7f800000); // +inf and id -1: round 0 takes every logit
int prev_i = -1;
for (int i = 0; i < k; ++i) {
float bv = __int_as_float(0xff800000); // -inf
int best = n_vocab;
for (int v = threadIdx.x; v < n_vocab; v += blockDim.x) {
const float s = apply_penalties(l[v], hit_count(v), p);
if ((s < prev_v || (s == prev_v && v > prev_i)) && s > bv) { bv = s; best = v; }
}
for (int off = 16; off > 0; off >>= 1) {
const float ov = __shfl_down_sync(0xFFFFFFFFu, bv, off);
const int oi = __shfl_down_sync(0xFFFFFFFFu, best, off);
if (ov > bv || (ov == bv && oi < best)) { bv = ov; best = oi; }
}
if (lane == 0) { sv[warp] = bv; si[warp] = best; }
__syncthreads();
if (warp == 0) {
const int nw = (int) ((blockDim.x + 31) >> 5);
float wv = lane < nw ? sv[lane] : __int_as_float(0xff800000);
int wi = lane < nw ? si[lane] : n_vocab;
for (int off = 16; off > 0; off >>= 1) {
const float ov = __shfl_down_sync(0xFFFFFFFFu, wv, off);
const int oi = __shfl_down_sync(0xFFFFFFFFu, wi, off);
if (ov > wv || (ov == wv && oi < wi)) { wv = ov; wi = oi; }
}
if (lane == 0) { sel_ids[i] = (wi < n_vocab) ? wi : 0; sel_logit[i] = wv; }
}
__syncthreads();
// An empty round leaves (-inf, 0): nothing comes after it, as nothing was left untaken.
prev_v = sel_logit[i];
prev_i = sel_ids[i];
}
if (warp != 0) return;
sampled_tail_warp(sel_ids, sel_logit, k, p, t, out, ex);
}
// ---- THE SPLIT top_k. `sampler_kernel` and the one-block kernel keep a row on ONE SM of 170 (5090) and walk its
// 248,320 logits k times. Here a warp keeps the top_k of 1,024 logits held in registers, four warps make a block of
// 4,096 logits that merges their lists, and a row is 61 such blocks over the whole GPU; one warp per row then
// merges the 61 lists and runs the tail. Exact, because the first k of a union are within the first k of each part
// and a merge of ordered lists is ordered - the selection order being a strict total order (above).
constexpr int kSplitPerLane = 32; // logits per lane, in registers
constexpr int kSplitWarpSpan = 32 * kSplitPerLane; // 1,024 logits per warp
constexpr int kSplitWarps = 4;
constexpr int kSplitBlockSpan = kSplitWarps * kSplitWarpSpan; // 4,096 logits per block
constexpr int kSplitMaxBlocks = 64; // lists the merge holds: n_vocab <= 262,144
constexpr int kSplitMaxRows = 64; // rows per split launch (the scratch's bound)
/// Merge `nl` (<= 64) lists of `k` candidates - list L at `lists[L * stride]`, each in the selection order and
/// padded with sentinels - into their first `k`: `sink(i, value, id)` runs in every lane for i = 0..k-1 with the
/// same pair. Lane owns lists `lane` and `lane + 32`; a round takes the first of all heads and advances the list
/// it came from. An id is in one list at most (the lists cover disjoint logits), so exactly one head matches.
template <typename Sink>
__device__ __forceinline__ void warp_merge_lists(const int2* lists, int nl, int stride, int k, int n_vocab,
Sink&& sink) {
const int lane = (int) (threadIdx.x & 31);
float hv[2];
int hi[2], pos[2];
#pragma unroll
for (int m = 0; m < 2; ++m) {
const int L = lane + 32 * m;
pos[m] = 0;
hv[m] = __int_as_float(0xff800000);
hi[m] = n_vocab;
if (L < nl) {
const int2 c = lists[(size_t) L * stride];
hi[m] = c.x;
hv[m] = __int_as_float(c.y);
}
}
for (int i = 0; i < k; ++i) {
float bv = hv[0];
int bi = hi[0];
take_first(bv, bi, hv[1], hi[1]);
warp_first(bv, bi);
sink(i, bv, bi);
if (bi < n_vocab) {
#pragma unroll
for (int m = 0; m < 2; ++m) {
if (hi[m] != bi) continue;
if (++pos[m] < k) {
const int2 c = lists[(size_t) (lane + 32 * m) * stride + pos[m]];
hi[m] = c.x;
hv[m] = __int_as_float(c.y);
} else {
hi[m] = n_vocab;
hv[m] = __int_as_float(0xff800000);
}
}
}
}
}
/// **SPLIT STAGE 1: THE top_k OF EACH 4,096-LOGIT BLOCK.** Grid (blocks per row, rows), 128 threads. Each warp
/// loads its 1,024 penalised logits once into registers (lane + 32 j: every load is one coalesced 128-byte line)
/// and runs `k` warp-argmax rounds over them with the threshold of `sampler_one_block_kernel` - no shared memory
/// and no block barrier per round. Warp 0 then merges the four warp lists into the block's list in `cand`
/// (row-major: row t, block b, entry i at `(t * n_blocks + b) * k + i`, as (id, value bits)).
__global__ void __launch_bounds__(kSplitWarps * 32)
sampler_split_part_kernel(const float* __restrict__ logits, int n_vocab, const int* __restrict__ history,
int history_len, const SamplerParams p, int k, int n_blocks, int2* __restrict__ cand) {
const int t = blockIdx.y;
const float* l = logits + (size_t) t * n_vocab;
const int warp = (int) (threadIdx.x >> 5), lane = (int) (threadIdx.x & 31);
const int blo = (int) blockIdx.x * kSplitBlockSpan;
const int* hrow = history ? history + (size_t) t * history_len : nullptr;
int hlen = 0;
if (hrow) {
hlen = p.penalty_last_n < history_len ? p.penalty_last_n : history_len;
if (hlen < 0) hlen = 0;
hrow += history_len - hlen; // the window is the TAIL
}
// The membership bitmap of THIS BLOCK'S 4,096 logits (512 bytes, not the vocabulary's 31 KB): the same test,
// and a hit pays the same exact count over the whole window.
__shared__ unsigned int bits[kSplitBlockSpan / 32];
const bool use_bits = hrow != nullptr && hlen > 0;
if (use_bits) {
for (int w = threadIdx.x; w < kSplitBlockSpan / 32; w += blockDim.x) bits[w] = 0u;
__syncthreads();
for (int i = threadIdx.x; i < hlen; i += blockDim.x) {
const int h = hrow[i];
if (h >= 0 && h < n_vocab && h >= blo && h - blo < kSplitBlockSpan)
atomicOr(&bits[(h - blo) >> 5], 1u << ((h - blo) & 31));
}
__syncthreads();
}
// This warp's logits, penalised: `apply_penalties` with a zero count returns the logit unchanged, so only the
// bitmap's hits go through it. Past the vocabulary: -inf, which no round picks.
const int lo = blo + warp * kSplitWarpSpan;
float s[kSplitPerLane];
#pragma unroll
for (int j = 0; j < kSplitPerLane; ++j) {
const int v = lo + 32 * j + lane;
s[j] = v < n_vocab ? l[v] : __int_as_float(0xff800000);
}
if (use_bits) {
#pragma unroll
for (int j = 0; j < kSplitPerLane; ++j) {
const int v = lo + 32 * j + lane, b = v - blo;
if (v < n_vocab && (bits[b >> 5] & (1u << (b & 31))))
s[j] = apply_penalties(s[j], history_count(hrow, hlen, v), p);
}
}
__shared__ int2 wl[kSplitWarps][kSelMax];
float prev_v = __int_as_float(0x7f800000); // +inf and id -1: round 0 takes every logit
int prev_i = -1;
int i = 0;
for (; i < k; ++i) {
// two chains (even and odd j), each walked in ascending id with a strict `>`, so each keeps its first in
// the order; `take_first` then orders the two
float b0 = __int_as_float(0xff800000), b1 = __int_as_float(0xff800000);
int i0 = n_vocab, i1 = n_vocab;
#pragma unroll
for (int j = 0; j < kSplitPerLane; j += 2) {
const int v0 = lo + 32 * j + lane, v1 = v0 + 32;
const float x0 = s[j], x1 = s[j + 1];
if ((x0 < prev_v || (x0 == prev_v && v0 > prev_i)) && x0 > b0) { b0 = x0; i0 = v0; }
if ((x1 < prev_v || (x1 == prev_v && v1 > prev_i)) && x1 > b1) { b1 = x1; i1 = v1; }
}
take_first(b0, i0, b1, i1);
warp_first(b0, i0);
if (i0 >= n_vocab) break; // the same in every lane: nothing left in these 1,024 logits
if (lane == 0) wl[warp][i] = make_int2(i0, __float_as_int(b0));
prev_v = b0;
prev_i = i0;
}
for (int r = i + lane; r < k; r += 32) wl[warp][r] = make_int2(n_vocab, (int) 0xff800000u); // sentinels
__syncthreads();
if (warp == 0) {
int2* dst = cand + ((size_t) t * n_blocks + blockIdx.x) * k;
warp_merge_lists(&wl[0][0], kSplitWarps, kSelMax, k, n_vocab, [&](int r, float v, int id) {
if (lane == 0) dst[r] = make_int2(id, __float_as_int(v));
});
}
}
/// **SPLIT STAGE 2: ONE WARP PER ROW MERGES THE BLOCK LISTS, THEN RUNS THE TAIL.** The row's lists (at most 64 x
/// 64 entries, 32 KB) are copied to shared memory, merged into the row's top_k list, and `sampled_tail_warp` picks.
__global__ void __launch_bounds__(32)
sampler_split_merge_kernel(const int2* __restrict__ cand, int n_blocks, int n_vocab, const SamplerParams p, int k,
int* __restrict__ out) {
const int t = blockIdx.x;
const int lane = (int) threadIdx.x;
__shared__ int2 lists[kSplitMaxBlocks * kSelMax];
__shared__ int sel_ids[kSelMax];
__shared__ float sel_logit[kSelMax];
__shared__ double ex[kSelMax];
const int2* src = cand + (size_t) t * n_blocks * k;
for (int e = lane; e < n_blocks * k; e += 32) lists[e] = src[e];
__syncwarp();
warp_merge_lists(lists, n_blocks, k, k, n_vocab, [&](int i, float v, int id) {
if (lane == 0) { sel_ids[i] = id < n_vocab ? id : 0; sel_logit[i] = v; }
});
__syncwarp();
sampled_tail_warp(sel_ids, sel_logit, k, p, t, out, ex);
}
// Which sampled path runs, read once: `STRATA_OLD_SAMPLER=1` is `sampler_kernel` (engine 0.1.20),
// `STRATA_SAMPLER_ONE_BLOCK=1` the one-block kernel; by default the split top_k wherever it applies.
enum class SampledPath { Split, OneBlock, Old };
bool env_flag(const char* name) {
const char* e = std::getenv(name);
return e != nullptr && *e != '\0' && std::strcmp(e, "0") != 0;
}
SampledPath sampled_path() {
static const SampledPath path = env_flag("STRATA_OLD_SAMPLER") ? SampledPath::Old
: env_flag("STRATA_SAMPLER_ONE_BLOCK") ? SampledPath::OneBlock
: SampledPath::Split;
return path;
}
// A stream being captured into a graph must not reach `split_scratch` (cudaMalloc): it
// gets the one-block kernel, which needs no memory of its own. The legacy stream cannot be captured.
bool stream_capturing(void* stream) {
if (stream == nullptr) return false;
cudaStreamCaptureStatus st = cudaStreamCaptureStatusNone;
if (cudaStreamIsCapturing((cudaStream_t) stream, &st) != cudaSuccess) {
(void) cudaGetLastError();
return true;
}
return st != cudaStreamCaptureStatusNone;
}
// The split's block lists, one buffer per (device, stream): launches on one stream run in order, so a stream reuses
// its buffer with no sync, and two streams never share one. Grown on demand (at least doubling, up to the size of
// `kSplitMaxRows` rows at the widest vocabulary: 2 MB), never shrunk. A grown-out buffer is retired, not freed: a
// pointer handed out earlier (to another host thread on the same stream, say) may still be waiting for its launch,
// and freeing it would need a sync that proves nothing about that thread. Doubling keeps a slot's retired buffers
// smaller than its live one, so a slot holds about 4 MB at most (0.5 MB for the engine's <= 16 rows). nullptr
// when the memory cannot be had, and the caller falls back to the one-block kernel; a failed grow is remembered, so
// later calls of that size do not retry cudaMalloc each time.
int2* split_scratch(void* stream, size_t entries) {
struct Slot {
int device;
void* stream;
int2* ptr;
size_t entries;
size_t failed; // the smallest size cudaMalloc refused (0: none)
};
static std::mutex mu;
static std::vector<Slot> slots;
static std::vector<int2*> retired;
int device = 0;
if (cudaGetDevice(&device) != cudaSuccess) {
(void) cudaGetLastError();
return nullptr;
}
std::lock_guard<std::mutex> lock(mu);
Slot* slot = nullptr;
for (Slot& s : slots)
if (s.device == device && s.stream == stream) slot = &s;
if (slot == nullptr) {
slots.push_back({device, stream, nullptr, 0, 0});
slot = &slots.back();
}
if (slot->entries >= entries) return slot->ptr;
if (slot->failed != 0 && entries >= slot->failed) return nullptr;
constexpr size_t kCap = (size_t) kSplitMaxRows * kSplitMaxBlocks * kSelMax;
size_t want = 2 * slot->entries < kCap ? 2 * slot->entries : kCap;
if (want < entries) want = entries;
int2* ptr = nullptr;
if (cudaMalloc(&ptr, want * sizeof(int2)) != cudaSuccess) {
(void) cudaGetLastError();
want = entries;
if (cudaMalloc(&ptr, want * sizeof(int2)) != cudaSuccess) {
(void) cudaGetLastError();
slot->failed = entries;
return nullptr;
}
}
if (slot->ptr != nullptr) retired.push_back(slot->ptr);
slot->ptr = ptr;
slot->entries = want;
return ptr;
}
} // namespace
void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,
@@ -320,11 +760,33 @@ void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* hi
const int gthreads = 1024;
sampler_greedy_kernel<<<(unsigned) n_tokens, gthreads, shmem, (cudaStream_t) stream>>>(
logits, n_vocab, history, history_len, p, p.penalty_last_n, p.penalty_last_n, out);
} else {
} else if (sampled_path() == SampledPath::Old) {
// The same block-per-token shape: the selection's k argmax rounds reduce inside the block. See
// `sampler_kernel`'s header for what the old one-thread-per-token launch cost.
sampler_kernel<<<(unsigned) n_tokens, 1024, shmem, (cudaStream_t) stream>>>(
logits, n_vocab, n_tokens, history, history_len, p, out);
} else {
// The split top_k by default: stage 1 over (61 blocks x rows) for 248,320 logits, stage 2 one warp per
// row. The one-block kernel when asked for, or when the split cannot run: a wider vocabulary than the merge
// holds, more than `kSplitMaxRows` rows (the engine samples at most a verify window), a stream under capture,
// no scratch.
const int k = sampled_k(p.top_k, n_vocab);
const int n_blocks = (n_vocab + kSplitBlockSpan - 1) / kSplitBlockSpan;
int2* scratch = nullptr;
if (sampled_path() == SampledPath::Split && n_blocks <= kSplitMaxBlocks && n_tokens <= kSplitMaxRows &&
!stream_capturing(stream))
// sized for 16 rows and 64 entries at least, so a verify window or a wider top_k does not regrow it
scratch = split_scratch(stream, (size_t) (n_tokens > 16 ? n_tokens : 16) * n_blocks * kSelMax);
if (scratch != nullptr) {
sampler_split_part_kernel<<<dim3((unsigned) n_blocks, (unsigned) n_tokens), kSplitWarps * 32, 0,
(cudaStream_t) stream>>>(logits, n_vocab, history, history_len, p, k,
n_blocks, scratch);
sampler_split_merge_kernel<<<(unsigned) n_tokens, 32, 0, (cudaStream_t) stream>>>(
scratch, n_blocks, n_vocab, p, k, out);
} else {
sampler_one_block_kernel<<<(unsigned) n_tokens, 1024, shmem, (cudaStream_t) stream>>>(
logits, n_vocab, history, history_len, p, out);
}
}
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
+59
View File
@@ -12,6 +12,7 @@
// instead of decaying, so the sign is checked as a property and not assumed.
// 3. `silu` IS COMPUTED IN DOUBLE then cast, because `ref/gdn.py`'s numpy does. f32 `expf` differs in the
// last bits, and the test measures that rather than asserting it away.
#include "strata/kernels/dequant_bf16.hpp"
#include "strata/kernels/elementwise.hpp"
#include "strata/kernels/f16_bits.hpp"
@@ -409,6 +410,64 @@ int main(int argc, char** argv) {
if (mismatches || guards || fma_diff == 0) ++bad;
}
// ---- THE f32 -> bf16 CONVERSIONS KEEP A NaN A NaN. `f32_to_bf16_bulk` (the header's `bf16_from_f32`
// on the device) and the prompt path's dequantizer (its own `f2bf`) against ggml_compute_fp32_to_bf16's rule;
// before the fix 0x7FFFFFFF came back as -0 and 0x7F800001 as +inf. `bf16_bits_test` covers every f32 on
// the host; this is the same header compiled by nvcc, plus the second copy in dequant_bf16.cu.
{
auto ggml_bf16 = [](uint32_t u) -> uint16_t {
if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 64);
return (uint16_t) ((u + (0x7fffu + ((u >> 16) & 1u))) >> 16);
};
std::vector<uint32_t> bits = {0x7FFFFFFFu, 0xFFFFFFFFu, 0x7F800001u, 0xFF800001u, 0x7FC00000u, 0x7FBFFFFFu,
0x7F800000u, 0xFF800000u, 0x7F7FFFFFu, 0x00000000u, 0x80000000u, 0x3F808000u,
0x3F818000u, 0x00008000u, 0x7F7F8000u};
std::mt19937 rng(13);
while (bits.size() < 4096) bits.push_back((uint32_t) rng());
const size_t n = bits.size();
float* dx = nullptr;
uint16_t* dy = nullptr;
check(cudaMalloc(&dx, n * 4), "bf16 x");
check(cudaMalloc(&dy, n * 2), "bf16 y");
check(cudaMemcpy(dx, bits.data(), n * 4, cudaMemcpyHostToDevice), "bf16 cx");
strata::kernels::f32_to_bf16_bulk(dx, dy, (int64_t) n, nullptr);
std::vector<uint16_t> got(n);
check(cudaMemcpy(got.data(), dy, n * 2, cudaMemcpyDeviceToHost), "bf16 cy");
int wrong = 0;
for (size_t i = 0; i < n; ++i) wrong += got[i] != ggml_bf16(bits[i]);
// A Q8_0 block (type 8) whose fp16 scale is a NaN: every dequantized value is NaN * q, a NaN, and it must
// still be one in BF16. A second block with an ordinary scale checks the finite path did not move.
std::vector<uint8_t> blk(2 * 34, 0);
blk[0] = 0x00; blk[1] = 0x7E; // fp16 quiet NaN
blk[34] = 0x00; blk[35] = 0x3C; // fp16 1.0
for (int j = 0; j < 32; ++j) {
blk[(size_t) (2 + j)] = (uint8_t) (int8_t) (j - 16);
blk[(size_t) (36 + j)] = (uint8_t) (int8_t) (3 * j - 50);
}
uint8_t* db = nullptr;
uint16_t* dq = nullptr;
check(cudaMalloc(&db, blk.size()), "q8 blk");
check(cudaMalloc(&dq, 64 * 2), "q8 out");
check(cudaMemcpy(db, blk.data(), blk.size(), cudaMemcpyHostToDevice), "q8 cblk");
strata::kernels::dequant_bf16(8, db, 0, 2, 32, dq, nullptr);
check(cudaDeviceSynchronize(), "dequant_bf16");
std::vector<uint16_t> q(64);
check(cudaMemcpy(q.data(), dq, 64 * 2, cudaMemcpyDeviceToHost), "q8 cout");
int dq_wrong = 0;
for (int j = 0; j < 32; ++j) {
if (!((q[(size_t) j] & 0x7FFFu) > 0x7F80u)) ++dq_wrong; // row 0: NaN scale -> NaN
const float v = (float) (3 * j - 50); // row 1: d = 1.0 -> the integer
uint32_t vb;
std::memcpy(&vb, &v, 4);
if (q[(size_t) (32 + j)] != ggml_bf16(vb)) ++dq_wrong;
}
std::printf(" f32 -> bf16 (NaN kept): bulk %d of %zu differ from ggml, dequant_bf16 %d of 64 wrong\n",
wrong, n, dq_wrong);
if (wrong || dq_wrong) ++bad;
cudaFree(dx); cudaFree(dy); cudaFree(db); cudaFree(dq);
}
std::printf("\nelementwise: %d failures\n", bad);
if (bad) return 1;
if (selftest) std::printf("elementwise_parity OK\n");
+251
View File
@@ -0,0 +1,251 @@
// src/kernels/mmvq_multi_parity.cpp - the multi_exact contract of native_mmvq, tested bitwise.
//
// build/mmvq_multi_parity
//
// WHY IT EXISTS. `include/strata/kernels/native_mmvq.hpp` says of `native_mmvq_set_multi_exact`:
//
// "true (default): the ncols == 1 layout, every column bitwise equal to a single-column call"
//
// and `include/strata/core/verify.hpp` counts "multi-column MMVQ in exact mode" among the reasons the verify window
// produces what greedy decode would, bit for bit. Nothing tested that sentence: `iq_parity` calls `native_mmvq`
// with two columns and compares against a float64 reference at 2e-2, which cannot see a difference between one
// column and T columns.
//
// WHAT IT COMPARES. The SAME Q8_1 bytes: one T-column call against T single-column calls, each reading column j
// from the same buffer (the header: "its Q8_1 blocks at j * n_in / 32"). The quantization is shared, so the only
// thing under test is how the columns are laid out.
//
// THE DATA. The weights are random bytes, except each block's fp16 scales (`d`, and `dmin` where the format has
// one), which are rewritten as normal fp16 values in +-[2^-10, 2^-5): random bytes there would put inf and NaN in
// the outputs, and on the GPU every NaN comes out as the same canonical bit pattern, so a NaN output compares equal
// whatever operations produced it and proves nothing. With finite scales and finite normal activations (the
// precondition the header puts on the input) every output is finite, and a non-finite one fails the test.
//
// THE NEGATIVE CONTROL. The same comparison with `multi_exact` off must find differences, or the test has no power
// and its pass means nothing. Where it has power depends on T: in `native_mmvq.cu` the generic layout uses
// `NW = NCOLS <= 4 ? 4 : 2` warps, and with `WARPS = 4` and `BPI = F::BPI * NW / WARPS` it coincides with the
// exact layout at T <= 4. So the control is ASSERTED on T > 4 for every case, and at T <= 4 its silence is
// reported as that coincidence rather than skipped. The control needs a row long enough for the two layouts to
// group blocks differently: IQ4_XS takes 16 blocks per iteration with 4 warps and 8 with 2, so at n_in = 2048 (8
// blocks of 256) each thread holds at most one block in both layouts and they coincide; its case uses n_in = 4096.
#include "strata/kernels/iq_kernels.hpp"
#include "strata/kernels/native_mmvq.hpp"
#include <cuda_runtime.h>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <random>
#include <vector>
namespace {
struct Case {
const char* name;
int type; // stable GGML type id, from the list in native_mmvq.hpp
int n_in;
int n_out;
int block_elems; // elements per weight block
int block_bytes;
int scale_at[2]; // byte offsets of the block's fp16 scales in native_mmvq.cu's block structs; -1 = none
};
// the types a head or a projection can have in this model
const Case CASES[] = {
{"Q4_0", 2, 2048, 512, 32, 18, {0, -1}}, // Q40Block: half d
{"Q8_0", 8, 2048, 512, 32, 34, {0, -1}}, // Q80Block: half d
{"Q4_K", 12, 2048, 512, 256, 144, {0, 2}}, // Q4KBlock: half2 dm
{"Q5_K", 13, 2048, 512, 256, 176, {0, 2}}, // Q5KBlock: half2 dm
{"Q6_K", 14, 2048, 512, 256, 210, {208, -1}}, // Q6KBlock: half d after ql, qh, scales
{"IQ4_XS", 23, 4096, 512, 256, 136, {0, -1}}, // IQ4XSBlock: half d; n_in 4096, see THE NEGATIVE CONTROL
{"Q5_K wide", 13, 4096, 2048, 256, 176, {0, 2}},
};
// a normal fp16 in +-[2^-10, 2^-5): exponent field 5..9 (bias 15), any mantissa, either sign
uint16_t sane_half(std::mt19937& rng) {
const uint32_t r = rng();
return (uint16_t) (((r >> 31) << 15) | ((5u + (r >> 10) % 5u) << 10) | (r & 0x3ffu));
}
// T = 4 is the last width where the two layouts coincide, T = 5 the first where they differ
const int WIDTHS[] = {1, 2, 3, 4, 5, 6, 8};
constexpr int COINCIDE_MAX_T = 4;
bool ck(cudaError_t e, const char* what) {
if (e == cudaSuccess) return true;
std::printf("CUDA: %s: %s\n", what, cudaGetErrorString(e));
return false;
}
// Returns the number of outputs that differ bit for bit; counts the non-finite outputs and the differences on
// outputs that are finite in both paths.
long long compare(const Case& c, int T, cudaStream_t s, long long& nonfinite, long long& diff_finite, bool& ran) {
ran = false;
if (!strata::kernels::native_mmvq_supported(c.type)) return -1;
const std::size_t wbytes = strata::kernels::native_mmvq_weight_bytes(c.type, c.n_in, c.n_out);
const std::size_t qcol = strata::kernels::native_q8_1_bytes(c.n_in, 1); // Q8_1 bytes of ONE column
const std::size_t qall = strata::kernels::native_q8_1_bytes(c.n_in, T);
if (qall != qcol * (std::size_t) T) {
std::printf("%-12s T=%d: the Q8_1 bytes of T columns (%zu) are not T times those of one (%zu): the test "
"assumes contiguous columns and they are not\n", c.name, T, qall, qcol);
return -1;
}
std::mt19937 rng(1234u + (unsigned) c.type * 97u + (unsigned) T);
std::vector<uint8_t> w(wbytes);
for (auto& b : w) b = (uint8_t) (rng() & 0xff);
const std::size_t n_blocks = (std::size_t) c.n_out * (std::size_t) (c.n_in / c.block_elems);
if (n_blocks * (std::size_t) c.block_bytes != wbytes) {
std::printf("%-12s T=%d: %zu blocks of %d bytes are not the %zu weight bytes native_mmvq expects\n", c.name,
T, n_blocks, c.block_bytes, wbytes);
return -1;
}
for (std::size_t k = 0; k < n_blocks; ++k)
for (int at : c.scale_at)
if (at >= 0) {
const uint16_t h = sane_half(rng);
std::memcpy(&w[k * (std::size_t) c.block_bytes + (std::size_t) at], &h, 2);
}
std::vector<float> x((std::size_t) T * c.n_in);
std::normal_distribution<float> nd(0.f, 1.f);
for (auto& v : x) v = nd(rng);
void* dw = nullptr;
void* xq = nullptr;
float* dx = nullptr;
float* dmulti = nullptr;
float* dsingle = nullptr;
const std::size_t ybytes = (std::size_t) T * c.n_out * 4;
if (!ck(cudaMalloc(&dw, wbytes), "malloc w") || !ck(cudaMalloc(&xq, qall), "malloc xq") ||
!ck(cudaMalloc(&dx, x.size() * 4), "malloc x") || !ck(cudaMalloc(&dmulti, ybytes), "malloc multi") ||
!ck(cudaMalloc(&dsingle, ybytes), "malloc single"))
return -1;
if (!ck(cudaMemcpy(dw, w.data(), wbytes, cudaMemcpyHostToDevice), "copy w") ||
!ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "copy x"))
return -1;
// ONE quantization, shared by both paths: the quantization is not under test
strata::kernels::quantize_q8_1_rows(dx, T, c.n_in, xq, s);
if (!ck(cudaStreamSynchronize(s), "quantize")) return -1;
try {
strata::kernels::native_mmvq(c.type, dw, xq, dmulti, c.n_in, c.n_out, T, s);
for (int j = 0; j < T; ++j)
strata::kernels::native_mmvq(c.type, dw, (const uint8_t*) xq + (std::size_t) j * qcol,
dsingle + (std::size_t) j * c.n_out, c.n_in, c.n_out, 1, s);
} catch (const std::exception& e) {
std::printf("%-12s T=%d: %s\n", c.name, T, e.what());
return -1;
}
if (!ck(cudaStreamSynchronize(s), "mmvq")) return -1;
std::vector<uint32_t> a((std::size_t) T * c.n_out), b(a.size());
if (!ck(cudaMemcpy(a.data(), dmulti, ybytes, cudaMemcpyDeviceToHost), "read multi") ||
!ck(cudaMemcpy(b.data(), dsingle, ybytes, cudaMemcpyDeviceToHost), "read single"))
return -1;
long long diff = 0;
nonfinite = 0;
diff_finite = 0;
for (std::size_t i = 0; i < a.size(); ++i) {
float fa, fb;
std::memcpy(&fa, &a[i], 4);
std::memcpy(&fb, &b[i], 4);
const bool both_finite = std::isfinite(fa) && std::isfinite(fb);
if (!both_finite) ++nonfinite;
if (a[i] != b[i]) {
++diff;
if (both_finite) ++diff_finite;
}
}
cudaFree(dw); cudaFree(xq); cudaFree(dx); cudaFree(dmulti); cudaFree(dsingle);
ran = true;
return diff;
}
struct Totals {
long long checked = 0, diff = 0, diff_finite = 0, nonfinite = 0; // all widths
long long diff_finite_wide = 0; // T > COINCIDE_MAX_T only
int powerless_cases = 0; // cases where the control found no difference at any T > COINCIDE_MAX_T
};
int sweep(bool exact, cudaStream_t s, Totals& t) {
strata::kernels::native_mmvq_set_multi_exact(exact);
if (strata::kernels::native_mmvq_multi_exact() != exact) {
std::printf("native_mmvq_multi_exact() does not reflect what was set\n");
return 1;
}
std::printf("\n=== multi_exact %s ===\n", exact ? "ON (the default)" : "off (negative control)");
std::printf("%-12s %3s %10s %10s %14s %10s\n", "type", "T", "outputs", "bits diff", "finite diff", "nonfinite");
int bad = 0;
for (const Case& c : CASES) {
long long case_wide = 0;
for (int T : WIDTHS) {
long long nf = 0, dfin = 0;
bool ran = false;
const long long diff = compare(c, T, s, nf, dfin, ran);
if (!ran) { ++bad; continue; }
const long long n = (long long) T * c.n_out;
t.checked += n;
t.diff += diff;
t.diff_finite += dfin;
t.nonfinite += nf;
if (T > COINCIDE_MAX_T) { t.diff_finite_wide += dfin; case_wide += dfin; }
const char* verdict;
if (exact) verdict = diff == 0 ? "ok" : "FAIL";
else if (dfin > 0) verdict = "control sees it";
else verdict = T <= COINCIDE_MAX_T ? "layouts coincide here (NW = 4)" : "no power at this T";
std::printf("%-12s %3d %10lld %10lld %14lld %10lld %s\n", c.name, T, n, diff, dfin, nf, verdict);
if (exact && diff != 0) ++bad;
}
if (!exact && case_wide == 0) ++t.powerless_cases;
}
return bad;
}
} // namespace
int main() {
cudaStream_t s;
if (!ck(cudaStreamCreate(&s), "stream create")) return 1;
Totals on, off;
const int bad = sweep(true, s, on);
const int bad_off = sweep(false, s, off);
strata::kernels::native_mmvq_set_multi_exact(true); // back to the default
std::printf("\nmulti_exact on: %lld outputs compared, %lld differ bitwise, %lld non-finite\n",
on.checked, on.diff, on.nonfinite);
std::printf("multi_exact off: %lld outputs compared, %lld differ bitwise (%lld on finite outputs, %lld at T > %d)\n",
off.checked, off.diff, off.diff_finite, off.diff_finite_wide, COINCIDE_MAX_T);
if (on.nonfinite != 0 || off.nonfinite != 0) {
std::printf("\nmmvq_multi_parity: FAILED. %lld non-finite outputs from finite scales and activations: the "
"bit comparison is only meaningful on finite outputs.\n", on.nonfinite + off.nonfinite);
return 1;
}
if (bad != 0 || bad_off != 0) {
std::printf("\nmmvq_multi_parity: FAILED. %d case(s) with multi_exact on differ from single-column calls "
"or did not run, %d case(s) did not run with it off. If they differ, the sentence in "
"native_mmvq.hpp does not hold, and neither does the bit-exactness verify.hpp claims.\n",
bad, bad_off);
return 1;
}
// 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 (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 "
"cannot tell the two layouts apart, so their pass above proves nothing.\n", off.powerless_cases,
COINCIDE_MAX_T);
return 1;
}
std::printf("\nmmvq_multi_parity: ok. With multi_exact on every column is bitwise equal to a single-column "
"call; with it off the control finds differences at T > %d in every case, so the comparison has "
"power.\n",
COINCIDE_MAX_T);
return 0;
}
+24
View File
@@ -6,8 +6,12 @@
#include "strata/kernels/f16_bits.hpp"
#include "strata/ngram/ple_reader.hpp"
#include <cerrno>
#include <cstdio>
#include <cstring>
#if !defined(_WIN32)
#include <sys/mman.h>
#endif
#include <vector>
#include <stdexcept>
@@ -119,6 +123,7 @@ struct PleTable::Impl {
strata::ngram::PleReader reader;
strata::ngram::PleReader::Ticket ticket;
bool pending = false;
bool locked = false;
uint32_t rows[PLE_N_HEADS] = {};
uint8_t raw[PLE_N_HEADS * PLE_ROW_BYTES] = {};
};
@@ -195,6 +200,23 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO
}
impl_->n_rows = n_rows;
}
if (io.mode == PleIo::Mmap && io.lock && impl_->data != nullptr) {
#if !defined(_WIN32)
const uint64_t page = 4096;
const uintptr_t a0 = (uintptr_t) impl_->data & ~(uintptr_t) (page - 1);
const uintptr_t a1 = (uintptr_t) impl_->data + (uintptr_t) need;
madvise((void*) a0, a1 - a0, MADV_WILLNEED);
if (mlock((const void*) a0, a1 - a0) == 0) {
impl_->locked = true;
} else {
std::fprintf(stderr, "strata: PLE table mlock failed (%s; raise `ulimit -l`): touching its pages instead\n",
std::strerror(errno));
volatile uint8_t sink = 0;
for (uintptr_t p = a0; p < a1; p += page) sink = sink + *(const volatile uint8_t*) p;
(void) sink;
}
#endif
}
impl_->mode = io.mode;
return true;
}
@@ -202,6 +224,7 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO
void PleTable::close() {
impl_->reader.close();
impl_->pending = false;
impl_->locked = false; // the unmap below releases the lock
impl_->mode = PleIo::Mmap;
delete impl_->file;
impl_->file = nullptr;
@@ -210,6 +233,7 @@ void PleTable::close() {
}
bool PleTable::is_open() const { return impl_->data != nullptr || impl_->reader.is_open(); }
bool PleTable::locked() const { return impl_->locked; }
PleIo PleTable::mode() const { return impl_->mode; }
uint64_t PleTable::rows() const { return impl_->n_rows; }
uint64_t PleTable::bytes_read() const { return impl_->bytes_read; }
+107
View File
@@ -72,6 +72,108 @@ struct Case {
bool has_offset;
};
/// THE RAGGED LAST BLOCK. The split kernels give each warp one row and a block eight warps, so with
/// `n_out % 8 != 0` the last block holds warps that have no row. Those warps used to return BEFORE the
/// codebook barrier - undefined behaviour that every real shape (a multiple of 8) avoided. Here `n_out` is
/// deliberately ragged, every row is checked against the host reference over the same bytes, and a guard
/// band past `n_out` must come back untouched: a warp without a row must neither hang the block nor write.
/// (`compute-sanitizer --tool synccheck` on this binary is the direct check of the barrier itself.)
int ragged_rows(const Case& cs, long long n_out) {
const long long n_in = 512;
const long long guard = 64;
std::mt19937 rng(77 + (unsigned) n_out);
std::normal_distribution<float> g(0.0f, 1.0f);
std::vector<float> xf((size_t) n_in);
for (auto& v : xf) v = g(rng);
SForm f;
f.code_bits = cs.bits;
f.code_bias = cs.bias;
f.group_elems = cs.group;
f.codebook = cs.cb;
f.has_offset = cs.has_offset;
const int per_byte = 8 / cs.bits;
std::vector<uint8_t> codes((size_t) (n_out * n_in / per_byte));
for (auto& v : codes) v = (uint8_t) (rng() & 0xFF);
const long long n_groups = n_in / cs.group;
std::vector<float> scales((size_t) (n_out * n_groups)), offs((size_t) (n_out * n_groups));
for (auto& v : scales) v = 0.01f + 0.001f * (float) (rng() % 20);
for (auto& v : offs) v = 0.2f * g(rng);
float* d_xf = nullptr;
uint8_t *d_xk = nullptr, *d_x0 = nullptr, *d_codes = nullptr;
float *d_scales = nullptr, *d_offs = nullptr, *d_y = nullptr;
std::vector<uint8_t> xk((size_t) (n_in / 256) * 292), x0((size_t) (n_in / 32) * 34);
check(cudaMalloc(&d_xf, (size_t) n_in * 4), "rxf");
check(cudaMalloc(&d_xk, xk.size()), "rxk");
check(cudaMalloc(&d_x0, x0.size()), "rx0");
check(cudaMalloc(&d_codes, codes.size()), "rcodes");
check(cudaMalloc(&d_scales, scales.size() * 4), "rscales");
check(cudaMalloc(&d_offs, offs.size() * 4), "roffs");
check(cudaMalloc(&d_y, (size_t) (n_out + guard) * 4), "ry");
check(cudaMemcpy(d_xf, xf.data(), (size_t) n_in * 4, cudaMemcpyHostToDevice), "rcxf");
check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "rcc");
check(cudaMemcpy(d_scales, scales.data(), scales.size() * 4, cudaMemcpyHostToDevice), "rcs");
check(cudaMemcpy(d_offs, offs.data(), offs.size() * 4, cudaMemcpyHostToDevice), "rco");
strata::kernels::quantize_q8_K(d_xf, d_xk, n_in, nullptr);
strata::kernels::quantize_q8_0(d_xf, d_x0, n_in, nullptr);
check(cudaMemcpy(xk.data(), d_xk, xk.size(), cudaMemcpyDeviceToHost), "rcxk");
check(cudaMemcpy(x0.data(), d_x0, x0.size(), cudaMemcpyDeviceToHost), "rcx0");
int bad = 0;
for (int kind = 0; kind < 2; ++kind) { // 0: Q8_K activation, 1: Q8_0 activation
std::vector<float> want((size_t) n_out);
std::vector<double> mag((size_t) n_out); // sum |w_i a_i| per row: a row whose sum cancels near 0
for (long long o = 0; o < n_out; ++o) { // must not turn f32 rounding into a relative failure
double acc = 0, am = 0;
for (long long i = 0; i < n_in; ++i) {
double a;
if (kind == 0) {
a = q8k_at(xk, i);
} else {
const uint8_t* blk = x0.data() + (size_t) (i / 32) * 34;
uint16_t dbits;
std::memcpy(&dbits, blk, 2);
a = (double) strata::kernels::f32_from_f16(dbits) * (double) ((const int8_t*) (blk + 2))[i % 32];
}
const double wa = weight_at(codes, scales, offs, f, n_in, o, i) * a;
acc += wa;
am += std::fabs(wa);
}
want[(size_t) o] = (float) acc;
mag[(size_t) o] = am;
}
// the guard band holds a NaN pattern; any write there shows up as a changed bit
std::vector<uint32_t> sentinel((size_t) (n_out + guard), 0x7FC0DEADu);
check(cudaMemcpy(d_y, sentinel.data(), sentinel.size() * 4, cudaMemcpyHostToDevice), "rsent");
if (kind == 0)
strata::kernels::s_gemv_q8k_split(d_xk, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in,
n_out, f, nullptr);
else
strata::kernels::s_gemv_q8_0_split(d_x0, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in,
n_out, f, nullptr);
check(cudaDeviceSynchronize(), "ragged split");
std::vector<uint32_t> got_bits(sentinel.size());
check(cudaMemcpy(got_bits.data(), d_y, got_bits.size() * 4, cudaMemcpyDeviceToHost), "rcy");
double m = 0, d = 0;
for (long long o = 0; o < n_out; ++o) {
float v;
std::memcpy(&v, &got_bits[(size_t) o], 4);
m += mag[(size_t) o];
d += std::fabs((double) want[(size_t) o] - (double) v);
}
long long touched = 0;
for (long long o = n_out; o < n_out + guard; ++o) touched += got_bits[(size_t) o] != 0x7FC0DEADu;
const double rel = d / (m > 1e-30 ? m : 1e-30);
const bool ok = rel <= 1e-5 && touched == 0;
std::printf(" %-28s %s n_out %3lld: rel %.3e, guard words written %lld %s\n", cs.what,
kind == 0 ? "Q8_K" : "Q8_0", n_out, rel, touched, ok ? "ok" : "*** WRONG ***");
if (!ok) ++bad;
}
cudaFree(d_xf); cudaFree(d_xk); cudaFree(d_x0); cudaFree(d_codes); cudaFree(d_scales); cudaFree(d_offs);
cudaFree(d_y);
return bad;
}
} // namespace
int main(int argc, char** argv) {
@@ -229,6 +331,11 @@ int main(int argc, char** argv) {
cudaFree(d_xf); cudaFree(d_xq); cudaFree(d_codes); cudaFree(d_scales); cudaFree(d_offs); cudaFree(d_y);
}
// ---- 4. output widths that are NOT a multiple of the eight rows per block
std::printf("\n");
for (const Case& cs : cases)
for (long long n_out : {1LL, 7LL, 9LL, 61LL}) bad += ragged_rows(cs, n_out);
std::printf("\ns_gemv_q8k: %d failures\n", bad);
if (bad) return 1;
if (selftest) std::printf("s_gemv_q8k_parity OK\n");
+433 -2
View File
@@ -17,6 +17,7 @@
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <random>
#include <string>
#include <vector>
@@ -264,13 +265,191 @@ int sampled_cut(const std::vector<float>& l, const std::vector<int>& hist, const
return cut;
}
// ---- the kernel's own semantics, for the fixtures ----
//
// `sampled_reference` picks the first unpicked logit even when it is -inf or NaN; the kernels never pick either, and
// a round that finds nothing stores id 0 with a -inf logit (and later rounds treat id 0 as taken, as `sampler_kernel`
// does). The mirror below follows the kernels, so rows with -inf, NaN, +inf and more requested than finite logits
// can be pinned exactly. On rows without those it is `sampled_reference`.
struct SelList {
std::vector<int> ids;
std::vector<float> logit;
};
// The top_k list of `sampler_kernel` for one row: `window` is the counted history (the row's last penalty_last_n).
SelList mirror_select(const float* l, int nv, const std::vector<int>& window, const strata::kernels::SamplerParams& p,
int k) {
std::vector<float> s((size_t) nv);
for (int v = 0; v < nv; ++v) {
int c = 0;
for (int h : window) c += h == v;
float x = l[v];
if (c > 0) {
if (x <= 0.0f) x *= p.penalty_repeat; else x /= p.penalty_repeat;
x -= (float) c * p.penalty_freq + (c > 0 ? 1.0f : 0.0f) * p.penalty_present;
}
s[(size_t) v] = x;
}
SelList out;
std::vector<char> taken((size_t) nv, 0);
for (int i = 0; i < k; ++i) {
int best = nv;
float bv = -std::numeric_limits<float>::infinity();
for (int v = 0; v < nv; ++v)
if (!taken[(size_t) v] && s[(size_t) v] > bv) { bv = s[(size_t) v]; best = v; }
const int id = best < nv ? best : 0;
taken[(size_t) id] = 1;
out.ids.push_back(id);
out.logit.push_back(bv);
}
return out;
}
// The tail of `sampler_kernel` over a list (its first `k` entries): top_p, min_p, temperature, the Philox draw.
int mirror_pick(const SelList& sel, int k, const strata::kernels::SamplerParams& p, int row) {
int n_keep = k;
float mx = sel.logit[0];
for (int i = 1; i < k; ++i) mx = std::fmax(mx, sel.logit[(size_t) i]);
if (p.top_p < 1.0f) {
double sum = 0.0;
for (int i = 0; i < k; ++i) sum += std::exp((double) sel.logit[(size_t) i] - (double) mx);
double cum = 0.0;
int cut = k;
for (int i = 0; i < k; ++i) {
cum += std::exp((double) sel.logit[(size_t) i] - (double) mx) / sum;
if (cum >= (double) p.top_p) { cut = i + 1; break; }
}
if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k;
n_keep = cut;
}
if (p.min_p > 0.0f) {
const float thresh = sel.logit[0] + std::log(p.min_p);
for (int i = 0; i < n_keep; ++i)
if (sel.logit[(size_t) i] < thresh) { n_keep = i; break; }
}
const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f;
auto scaled = [&](int i) { return sel.logit[(size_t) i] * inv_t; };
float smx = scaled(0);
for (int i = 1; i < n_keep; ++i) smx = std::fmax(smx, scaled(i));
double sum = 0.0;
for (int i = 0; i < n_keep; ++i) sum += std::exp((double) scaled(i) - (double) smx);
const float u = host_philox_uniform(p.seed, p.counter + (uint64_t) row);
double cum = 0.0;
int pick = sel.ids[(size_t) (n_keep > 0 ? n_keep - 1 : 0)];
for (int i = 0; i < n_keep; ++i) {
cum += std::exp((double) scaled(i) - (double) smx) / sum;
if ((double) u < cum) { pick = sel.ids[(size_t) i]; break; }
}
return pick;
}
int sampled_k(int top_k, int nv) { return std::min(nv, (top_k > 0 && top_k < 64) ? top_k : 64); }
// Rows uploaded once and sampled under many parameter sets: `sample` returns the picks of one launch on `stream`
// (nullptr: the legacy stream), -1 prefilled as in `run`.
struct DeviceRows {
float* l = nullptr;
int* h = nullptr;
int* o = nullptr;
int n_tokens = 0, nv = 0, hist_len = 0;
DeviceRows(const std::vector<float>& logits, int n_tokens_, const std::vector<int>& hist, int hist_len_)
: n_tokens(n_tokens_), nv((int) (logits.size() / (size_t) n_tokens_)), hist_len(hist_len_) {
check(cudaMalloc(&l, logits.size() * sizeof(float)), "malloc logits");
check(cudaMalloc(&o, (size_t) n_tokens * sizeof(int)), "malloc out");
check(cudaMemcpy(l, logits.data(), logits.size() * sizeof(float), cudaMemcpyHostToDevice), "copy");
if (hist_len > 0) {
check(cudaMalloc(&h, hist.size() * sizeof(int)), "malloc hist");
check(cudaMemcpy(h, hist.data(), hist.size() * sizeof(int), cudaMemcpyHostToDevice), "copy hist");
}
}
DeviceRows(const DeviceRows&) = delete;
DeviceRows& operator=(const DeviceRows&) = delete;
~DeviceRows() {
cudaFree(l);
cudaFree(o);
if (h) cudaFree(h);
}
std::vector<int> sample(const strata::kernels::SamplerParams& p, cudaStream_t stream) {
check(cudaMemset(o, 0xFF, (size_t) n_tokens * sizeof(int)), "fill out");
strata::kernels::sample_tokens(l, n_tokens, nv, h, hist_len, p, o, stream);
if (stream != nullptr) check(cudaStreamSynchronize(stream), "stream sync");
std::vector<int> got((size_t) n_tokens);
check(cudaMemcpy(got.data(), o, got.size() * sizeof(int), cudaMemcpyDeviceToHost), "back");
return got;
}
};
// The counted window of row t: the last min(penalty_last_n, hist_len) entries (none without penalties).
std::vector<int> window_of(const std::vector<int>& hist, int hist_len, int t, int last_n) {
if (hist_len <= 0 || last_n <= 0) return {};
const int h = std::min(last_n, hist_len);
const int* row = hist.data() + (size_t) t * hist_len;
return std::vector<int>(row + (hist_len - h), row + hist_len);
}
// `--bench`: the sampled path alone at the engine's vocabulary, per call, on the path the environment selects.
void bench_sampled() {
const int NV = 248320;
cudaStream_t s = nullptr;
check(cudaStreamCreate(&s), "stream");
std::mt19937 rng(20);
std::normal_distribution<float> g(0.0f, 3.0f);
for (int T : {1, 4, 8}) {
std::vector<float> l((size_t) NV * T);
for (auto& v : l) v = g(rng);
float* d_l = nullptr;
int* d_o = nullptr;
check(cudaMalloc(&d_l, l.size() * sizeof(float)), "bench logits");
check(cudaMalloc(&d_o, (size_t) T * sizeof(int)), "bench out");
check(cudaMemcpy(d_l, l.data(), l.size() * sizeof(float), cudaMemcpyHostToDevice), "bench copy");
for (int k : {20, 64}) {
strata::kernels::SamplerParams p;
p.top_k = k; p.top_p = 0.95f; p.temperature = 0.7f; p.seed = 1;
for (int w = 0; w < 3; ++w) strata::kernels::sample_tokens(d_l, T, NV, nullptr, 0, p, d_o, s);
check(cudaStreamSynchronize(s), "bench warmup");
cudaEvent_t e0, e1;
check(cudaEventCreate(&e0), "event");
check(cudaEventCreate(&e1), "event");
const int iters = 50;
check(cudaEventRecord(e0, s), "record");
for (int it = 0; it < iters; ++it) {
p.counter = (uint64_t) it;
strata::kernels::sample_tokens(d_l, T, NV, nullptr, 0, p, d_o, s);
}
check(cudaEventRecord(e1, s), "record");
check(cudaEventSynchronize(e1), "bench sync");
float ms = 0.0f;
check(cudaEventElapsedTime(&ms, e0, e1), "elapsed");
std::printf(" bench: n_vocab %d, rows %d, top_k %2d, top_p 0.95: %8.1f us per call\n", NV, T, k,
1000.0 * (double) ms / iters);
cudaEventDestroy(e0);
cudaEventDestroy(e1);
}
cudaFree(d_l);
cudaFree(d_o);
}
cudaStreamDestroy(s);
}
} // namespace
int main(int argc, char** argv) {
bool selftest = false;
bool selftest = false, bench = false;
for (int i = 1; i < argc; ++i) {
if (std::string(argv[i]) == "--selftest") selftest = true;
else { std::fprintf(stderr, "usage: sampler_parity [--selftest]\n"); return 2; }
else if (std::string(argv[i]) == "--bench") bench = true;
else { std::fprintf(stderr, "usage: sampler_parity [--selftest] [--bench]\n"); return 2; }
}
{
// the sampled path under test; ctest runs this binary once per path
auto on = [](const char* n) { const char* e = std::getenv(n); return e && *e && std::strcmp(e, "0") != 0; };
std::printf(" sampled path: %s\n", on("STRATA_OLD_SAMPLER") ? "sampler_kernel (STRATA_OLD_SAMPLER)"
: on("STRATA_SAMPLER_ONE_BLOCK") ? "one block (STRATA_SAMPLER_ONE_BLOCK)"
: "split top_k (default)");
}
if (bench) {
bench_sampled();
return 0;
}
int bad = 0;
const int NV = 512, NT = 4;
@@ -846,6 +1025,258 @@ int main(int argc, char** argv) {
cudaFree(input); cudaFree(output);
}
// ---- fixture 16: THE WHOLE top_k LIST, POSITION BY POSITION, UNDER TIES. A pick shows the list
// through one draw; this reads the list itself. Every row holds a +inf logit, so the tail's arithmetic is NaN
// (inf - inf), no cut fires and no draw lands: the chain returns its LAST kept entry, sel_ids[k - 1]. Launching
// top_k = 1..64 then reads the list one position at a time - its set and its order. The rows make the order
// rest on the tie rule: hundreds of logits share the top finite values, spread over every split block, warp and
// lane; -0 and +0 tie; -inf and NaN are mixed in; a row has fewer finite logits than 64 (the sentinel id 0 must
// come out); a penalised row lands its penalised tokens exactly on other tokens' values. Vocabularies: the
// engine's 248,320 (a partial last split block), 100,003, 262,144 (the widest split), 262,145 (one more: the
// one-block fallback) and 1,000.
{
const float inf = std::numeric_limits<float>::infinity();
const float qnan = std::numeric_limits<float>::quiet_NaN();
int wrong = 0, probes = 0, sentinels = 0;
for (int nv : {248320, 100003, 262144, 262145, 1000}) {
const int T = 4, H = 64;
std::mt19937 rng((unsigned) (1600 + nv));
std::normal_distribution<float> g(0.0f, 1.0f);
std::vector<float> l((size_t) nv * T);
for (auto& v : l) v = std::floor(g(rng) * 4.0f) / 4.0f; // quarter steps: ties everywhere
auto spread = [&](int j) { return (int) (((int64_t) j * 7919 + 13) % nv); };
// row 0: 20 logits at 6.25 and 300 at 6.0 over the whole row, two +inf
float* r0 = l.data();
for (int j = 0; j < 320; ++j) r0[spread(j)] = j < 20 ? 6.25f : 6.0f;
r0[nv / 2] = inf;
r0[nv - 1] = inf;
// row 1: nothing above 0, every zero signed by its id's parity (-0 at even ids), one +inf
float* r1 = l.data() + (size_t) nv;
for (int v = 0; v < nv; ++v) {
r1[v] = -std::fabs(r1[v]);
if (r1[v] == 0.0f) r1[v] = (v & 1) ? 0.0f : -0.0f;
}
r1[3] = inf;
// row 2: -inf everywhere but ten finite logits (two values), two NaN and a +inf: 11 candidates in all
float* r2 = l.data() + (size_t) 2 * nv;
for (int v = 0; v < nv; ++v) r2[v] = -inf;
for (int j = 0; j < 10; ++j) r2[spread(j + 400)] = j < 5 ? 1.0f : 0.5f;
r2[spread(500)] = qnan;
r2[spread(501)] = qnan;
r2[spread(502)] = inf;
// row 3: penalties. Window ids on block and warp edges, repeats, and ids outside the vocabulary; the
// penalised tokens sit at 9.0, which repeat 2 / freq 0.25 / present 0.5 turns into 4.0 - 0.25 x count
// (3.75, 3.5, ...), values the quarter-step logits share.
float* r3 = l.data() + (size_t) 3 * nv;
std::vector<int> hist((size_t) T * H, -1);
int* h3 = hist.data() + (size_t) 3 * H;
const int edges[] = {0, 1023, 1024, 4095, 4096, 8191, 8192, 12345, nv / 2 + 1, nv - 2};
int hn = 0;
for (int e : edges)
if (e < nv && e != nv / 2) {
h3[hn++] = e;
if (hn % 3 == 0) h3[hn++] = e; // counted twice
r3[e] = 9.0f;
}
h3[hn++] = nv; // ignored: outside
h3[hn++] = nv + 77;
h3[hn++] = -5;
for (int j = 0; j < 30; ++j) r3[spread(j + 600)] = j < 15 ? 3.75f : 3.5f;
r3[nv / 2] = inf; // not in the window
strata::kernels::SamplerParams base;
base.top_p = 1.0f; base.min_p = 0.0f; base.temperature = 0.8f; base.seed = 16;
base.penalty_last_n = H; base.penalty_repeat = 2.0f; base.penalty_freq = 0.25f;
base.penalty_present = 0.5f;
const int kmax = sampled_k(64, nv);
std::vector<SelList> lists;
for (int t = 0; t < T; ++t)
lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, H), base, kmax));
DeviceRows rows(l, T, hist, H);
for (int top_k = 0; top_k <= 66; ++top_k) {
strata::kernels::SamplerParams p = base;
p.top_k = top_k == 65 ? 100 : top_k == 66 ? -3 : top_k; // 0, 100 and -3 mean 64
p.top_p = (top_k & 1) ? 0.5f : 1.0f; // both tail branches (NaN: no cut)
p.counter = (uint64_t) top_k;
const int k = sampled_k(p.top_k, nv);
const std::vector<int> got = rows.sample(p, nullptr);
for (int t = 0; t < T; ++t) {
const int want = lists[(size_t) t].ids[(size_t) (k - 1)];
sentinels += (t == 2 && k > 11);
++probes;
if (got[(size_t) t] != want) {
if (wrong < 8)
std::printf(" n_vocab %d row %d top_k %d: position %d want id %d got %d\n", nv, t,
p.top_k, k - 1, want, got[(size_t) t]);
++wrong;
}
}
}
}
// the fixture must reach the sentinel (row 2 has 11 candidates) or it cannot see the "nothing left" rule
std::printf(" %-34s %s (%d of %d positions differ; %d sentinel positions)\n", "top_k list under ties",
wrong || !sentinels ? "*** WRONG ***" : "matches", wrong, probes, sentinels);
bad += wrong + (sentinels == 0);
}
// ---- fixture 17: SAMPLED DRAWS UNDER TIES. The realistic chain - finite logits on half steps,
// so dozens of tokens share each value near the top - through every stage: top_k 1 / 20 / 64, top_p 0.9 / 1,
// min_p 0 / 0.05, a hot temperature that spreads the draws over the whole list, penalties off and on (half of
// each window on the row's head, so they reorder it). 17 rows (the split's scratch is first sized for 16: this
// regrows it), on the legacy stream and on a created one. Observability: some picks must be tokens that tie
// with another kept token, or the tie rule would go untested.
{
const int T = 17, H = 64;
cudaStream_t cs = nullptr;
check(cudaStreamCreate(&cs), "fixture 17 stream");
int wrong = 0, draws = 0, tied = 0;
for (int nv : {248320, 512}) {
std::mt19937 rng((unsigned) (1700 + nv));
std::normal_distribution<float> g(0.0f, 1.5f);
std::vector<float> l((size_t) nv * T);
for (auto& v : l) v = std::floor(g(rng) * 2.0f) / 2.0f;
if (nv == 512)
for (auto& v : l) v = std::floor(v / 2.0f); // whole steps: a few big tie groups
std::vector<int> hist((size_t) T * H);
for (int t = 0; t < T; ++t) {
const float* row = l.data() + (size_t) t * nv;
const float mx = *std::max_element(row, row + nv);
std::vector<int> head;
for (int v = 0; v < nv; ++v)
if (row[v] >= mx - 1.0f) head.push_back(v);
for (int j = 0; j < H; ++j)
hist[(size_t) t * H + j] = (j & 1) ? (int) (rng() % (unsigned) nv)
: head[(size_t) (rng() % (unsigned) head.size())];
}
DeviceRows rows(l, T, hist, H);
int config = 0;
for (int pen = 0; pen < 2; ++pen) {
strata::kernels::SamplerParams base;
base.temperature = 2.5f; base.seed = 17;
base.penalty_last_n = pen ? H : 0;
base.penalty_repeat = 1.25f; base.penalty_freq = 0.25f; base.penalty_present = 0.5f;
const int kmax = sampled_k(64, nv);
std::vector<SelList> lists;
for (int t = 0; t < T; ++t)
lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, base.penalty_last_n),
base, kmax));
for (int top_k : {1, 20, 64})
for (float top_p : {0.9f, 1.0f})
for (float min_p : {0.0f, 0.05f})
for (cudaStream_t st : {(cudaStream_t) nullptr, cs}) {
strata::kernels::SamplerParams p = base;
p.top_k = top_k; p.top_p = top_p; p.min_p = min_p;
p.counter = (uint64_t) (1000 * ++config);
const int k = sampled_k(top_k, nv);
const std::vector<int> got = rows.sample(p, st);
for (int t = 0; t < T; ++t) {
const SelList& sl = lists[(size_t) t];
const int want = mirror_pick(sl, k, p, t);
++draws;
int same = 0;
for (int i = 0; i < k; ++i) {
if (sl.ids[(size_t) i] != want) continue;
for (int j = 0; j < k; ++j) same += sl.logit[(size_t) j] == sl.logit[(size_t) i];
break;
}
tied += same > 1;
if (got[(size_t) t] != want) {
if (wrong < 8)
std::printf(" n_vocab %d row %d top_k %d top_p %.2f min_p %.2f pen %d: "
"want %d got %d\n", nv, t, top_k, (double) top_p,
(double) min_p, pen, want, got[(size_t) t]);
++wrong;
}
}
}
}
}
cudaStreamDestroy(cs);
std::printf(" %-34s %s (%d of %d draws differ; %d picks tie with another kept token)\n",
"sampled draws under ties", wrong || !tied ? "*** WRONG ***" : "matches", wrong, draws, tied);
bad += wrong + (tied == 0);
}
// ---- fixture 18: THE DEFAULT PATH'S AUTOMATIC FALLBACKS. (a) A stream under graph capture
// (ThreadLocal mode) gets the one-block kernel, penalty bitmap in dynamic shared memory, inside the graph: the
// capture must succeed and the replayed graph (twice) must pick the mirror's tokens; the same stream uncaptured
// then takes the split path (its scratch is first allocated after the capture) and picks the same. (b) More
// rows than a split launch takes (64) fall back to one block; exactly 64 stay split.
{
int wrong = 0, draws = 0;
const int H = 64;
auto compare = [&](const char* what, const std::vector<int>& got, const std::vector<SelList>& lists, int k,
const strata::kernels::SamplerParams& p) {
for (size_t t = 0; t < got.size(); ++t) {
const int want = mirror_pick(lists[t], k, p, (int) t);
++draws;
if (got[t] != want) {
if (wrong < 8) std::printf(" %s row %zu: want %d got %d\n", what, t, want, got[t]);
++wrong;
}
}
};
auto make = [&](int nv, int T, unsigned seed, std::vector<float>& l, std::vector<int>& hist) {
std::mt19937 rng(seed);
std::normal_distribution<float> g(0.0f, 1.5f);
l.assign((size_t) nv * T, 0.0f);
for (auto& v : l) v = std::floor(g(rng) * 2.0f) / 2.0f;
hist.assign((size_t) T * H, 0);
for (auto& h : hist) h = (int) (rng() % (unsigned) nv);
};
{
const int nv = 248320, T = 3;
std::vector<float> l;
std::vector<int> hist;
make(nv, T, 1800u, l, hist);
strata::kernels::SamplerParams p;
p.top_k = 20; p.top_p = 0.9f; p.temperature = 2.5f; p.seed = 18; p.counter = 77;
p.penalty_last_n = H; p.penalty_repeat = 1.25f; p.penalty_freq = 0.25f; p.penalty_present = 0.5f;
const int k = sampled_k(p.top_k, nv);
std::vector<SelList> lists;
for (int t = 0; t < T; ++t)
lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, window_of(hist, H, t, H), p, k));
DeviceRows rows(l, T, hist, H);
cudaStream_t cs = nullptr;
check(cudaStreamCreate(&cs), "fixture 18 stream");
check(cudaMemset(rows.o, 0xFF, (size_t) T * sizeof(int)), "fixture 18 fill");
cudaGraph_t graph = nullptr;
cudaGraphExec_t exec = nullptr;
check(cudaStreamBeginCapture(cs, cudaStreamCaptureModeThreadLocal), "begin capture");
strata::kernels::sample_tokens(rows.l, T, nv, rows.h, H, p, rows.o, cs);
check(cudaStreamEndCapture(cs, &graph), "end capture");
check(cudaGraphInstantiate(&exec, graph, 0), "instantiate");
for (int replay = 0; replay < 2; ++replay) {
check(cudaMemset(rows.o, 0xFF, (size_t) T * sizeof(int)), "fixture 18 refill");
check(cudaGraphLaunch(exec, cs), "graph launch");
check(cudaStreamSynchronize(cs), "graph sync");
std::vector<int> got((size_t) T);
check(cudaMemcpy(got.data(), rows.o, got.size() * sizeof(int), cudaMemcpyDeviceToHost), "back");
compare("captured graph", got, lists, k, p);
}
cudaGraphExecDestroy(exec);
cudaGraphDestroy(graph);
compare("same stream, uncaptured", rows.sample(p, cs), lists, k, p);
cudaStreamDestroy(cs);
}
for (int T : {64, 70}) {
const int nv = 512;
std::vector<float> l;
std::vector<int> hist;
make(nv, T, 1810u + (unsigned) T, l, hist);
strata::kernels::SamplerParams p;
p.top_k = 64; p.top_p = 1.0f; p.temperature = 2.5f; p.seed = 18; p.counter = (uint64_t) T;
const int k = sampled_k(p.top_k, nv);
std::vector<SelList> lists;
for (int t = 0; t < T; ++t) lists.push_back(mirror_select(l.data() + (size_t) t * nv, nv, {}, p, k));
DeviceRows rows(l, T, hist, 0);
compare(T > 64 ? "70 rows (one block)" : "64 rows (split)", rows.sample(p, nullptr), lists, k, p);
}
std::printf(" %-34s %s (%d of %d draws differ)\n", "fallbacks: graph capture, row cap",
wrong ? "*** WRONG ***" : "matches", wrong, draws);
bad += wrong;
}
std::printf("\nsampler: %d failures\n", bad);
if (bad) return 1;
if (selftest) std::printf("sampler_parity OK\n");
+64 -1
View File
@@ -340,6 +340,65 @@ __global__ void __launch_bounds__(CB * RG) gdn_rec_cols_kernel(float* __restrict
#pragma unroll
for (int r = 0; r < RPG; ++r) base[r * rs] = s[r];
}
// gdn_rec_cols_kernel with the next token's inputs (q/k rows, v, gate, beta) loaded into registers while this token
// computes (software pipelining). The same arithmetic in the same order: the same bits, and the same CB-column split.
// STRATA_GDN_PIPELINE=0: gdn_rec_cols_kernel.
__global__ void __launch_bounds__(CB * RG) gdn_rec_cols_pipe_kernel(float* __restrict__ state, const float* __restrict__ h,
const float* __restrict__ gate,
const float* __restrict__ beta,
float* __restrict__ oc_out, int64_t T) {
constexpr int NT = CB * RG, LPT = S / NT; // threads, q/k rows loaded per thread
__shared__ float sk[S], sq[S], red[RG][CB];
const int head = blockIdx.x / NCB, cb = blockIdx.x % NCB;
const int c = threadIdx.x, rg = threadIdx.y, tid = rg * CB + c, col = cb * CB + c;
const int qh = head % HK;
float s[RPG];
float* base = state + ((size_t) (rg * RPG) * HV + head) * S + col;
const size_t rs = (size_t) HV * S;
#pragma unroll
for (int r = 0; r < RPG; ++r) s[r] = base[r * rs];
float nq[LPT], nk[LPT], nv = 0.0f, ng = 0.0f, nb = 0.0f;
auto fetch = [&](int64_t t) {
const float* ht = h + t * C;
#pragma unroll
for (int u = 0; u < LPT; ++u) { nq[u] = ht[qh * S + tid + u * NT]; nk[u] = ht[HK * S + qh * S + tid + u * NT]; }
nv = ht[2 * HK * S + head * S + col];
ng = gate[t * HV + head];
nb = beta[t * HV + head];
};
if (T > 0) fetch(0);
for (int64_t t = 0; t < T; ++t) {
float cq[LPT], ck[LPT];
#pragma unroll
for (int u = 0; u < LPT; ++u) { cq[u] = nq[u]; ck[u] = nk[u]; }
const float cv = nv, cg = ng, cbt = nb;
__syncthreads();
#pragma unroll
for (int u = 0; u < LPT; ++u) { sq[tid + u * NT] = cq[u]; sk[tid + u * NT] = ck[u]; }
__syncthreads();
if (t + 1 < T) fetch(t + 1);
const float g = __expf(cg);
float kv = 0.0f;
#pragma unroll
for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sk[rg * RPG + r], kv);
red[rg][c] = kv;
__syncthreads();
const float kv_col = red[0][c] + red[1][c] + red[2][c] + red[3][c];
const float delta = (cv - g * kv_col) * cbt;
float o = 0.0f;
#pragma unroll
for (int r = 0; r < RPG; ++r) {
s[r] = fmaf(g, s[r], sk[rg * RPG + r] * delta);
o = fmaf(s[r], sq[rg * RPG + r], o);
}
__syncthreads();
red[rg][c] = o;
__syncthreads();
if (rg == 0) oc_out[t * HV * S + head * S + col] = (red[0][c] + red[1][c] + red[2][c] + red[3][c]) * rsqrtf((float) S);
}
#pragma unroll
for (int r = 0; r < RPG; ++r) base[r * rs] = s[r];
}
__global__ void __launch_bounds__(S) gdn_out_norm_kernel(const float* __restrict__ z, const float* __restrict__ gamma,
float eps, float* __restrict__ y, uint16_t* __restrict__ y16) {
__shared__ float wsum[4];
@@ -636,7 +695,11 @@ void gdn_recurrence(float* state, const float* h, const float* gate, const float
if (serial || T <= 0) {
gdn_rec_kernel<<<HV, dim3(S, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, z, gamma, eps, y, y16, T);
} else {
gdn_rec_cols_kernel<<<HV * NCB, dim3(CB, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
static const bool pipe = [] { const char* v = std::getenv("STRATA_GDN_PIPELINE"); return v == nullptr || std::atoi(v) != 0; }();
if (pipe) // the software-pipelined loads (same bits)
gdn_rec_cols_pipe_kernel<<<HV * NCB, dim3(CB, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
else
gdn_rec_cols_kernel<<<HV * NCB, dim3(CB, RG), 0, (cudaStream_t) stream>>>(state, h, gate, beta, y, T);
gdn_out_norm_kernel<<<dim3((unsigned) T, HV), S, 0, (cudaStream_t) stream>>>(z, gamma, eps, y, y16);
}
check("gdn_recurrence");
+2
View File
@@ -82,6 +82,7 @@ double g_pinned_share = 1.0;
inline int ring_slots(size_t T) {
const char* v = std::getenv("STRATA_PREFILL_RING");
const int r = v ? std::atoi(v) : (g_pinned_share >= 0.9 ? 384 : 96);
if (v && r == STAGE) return STAGE; // Explicit opt-in to routed-only staging, including large chunks.
const int big = r < 16 ? 16 : r > RING_MAX ? RING_MAX : r;
return (int64_t) T >= STREAM_ALL_MIN ? big : STAGE;
}
@@ -927,6 +928,7 @@ struct PfTimer {
} // namespace
bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err) {
err.clear();
Impl& m = *impl_;
const core::OnDevice on_device(m.device);
const core::ModelGeometry& g = *m.g;
+67 -13
View File
@@ -319,8 +319,9 @@ void usage() {
" --tokens-file PATH pretokenized prompt, commas or whitespace (alternative to --tokens)\n"
" --ple-gguf PATH required PLE table (original second GGUF shard)\n"
" --no-ple explicit diagnostic ablation of the PLE layer\n"
" --ple-io direct|mmap n-gram table reads (plan v0.3 P2). direct (default): unbuffered SSD\n"
" reads, the table never enters RAM or the file cache; mmap: A/B arm\n"
" --ple-io direct|mmap|ram n-gram table reads (plan v0.3 P2). direct (default): unbuffered SSD\n"
" reads, the table never enters RAM or the file cache; mmap: A/B arm;\n"
" ram: mmap with the whole table locked in RAM at start (Linux/macOS)\n"
" --ple-row-cache N bounded cache of fetched rows, 90 B each (default 1048576; 0 = off)\n"
" --ple-inflight N outstanding SSD reads (default 64)\n"
" --ple-delay-us U fault injection: each row read completes no earlier than U us\n"
@@ -1195,11 +1196,17 @@ int main(int argc, char** argv) {
return 2;
}
if ((o.ple_io != "direct" && o.ple_io != "mmap") || o.ple_row_cache < 0 || o.ple_inflight < 1 ||
if ((o.ple_io != "direct" && o.ple_io != "mmap" && o.ple_io != "ram") || o.ple_row_cache < 0 || o.ple_inflight < 1 ||
o.ple_inflight > 1024 || !(o.ple_delay_us >= 0)) {
std::fprintf(stderr, "strata generate: invalid --ple-io/--ple-row-cache/--ple-inflight/--ple-delay-us\n");
return 2;
}
#if defined(_WIN32)
if (o.ple_io == "ram") {
std::fprintf(stderr, "strata generate: --ple-io ram is not available on Windows (no mlock); use --ple-io mmap\n");
return 2;
}
#endif
if (o.kv == "q4") o.kv = "q4_0";
if (o.kv != "fp16" && o.kv != "int8" && o.kv != "q4_0" && o.kv != "k8v4") {
std::fprintf(stderr, "strata generate: --kv must be fp16, int8, q4_0 or k8v4\n");
@@ -1324,16 +1331,21 @@ int main(int argc, char** argv) {
}
}
const bool native_pack = strata::kernels::cpu::expert_layout().native;
if (o.expert_cache_remote[0] > 0) {
// STRATA_EARLY_REMOTE_CONTEXTS=1: create EVERY secondary context here, like CUDA1's. Under WSL2 the driver's
// pinned/mapped host budget (dxg gpadl, ~1 GiB) is spent by CUDA0's weights and MTP before the later loop runs,
// and a new context then fails with cudaErrorMemoryAllocation (CUDA2: "cudaSetDevice(2) failed: out of memory").
const char* early_env = std::getenv("STRATA_EARLY_REMOTE_CONTEXTS");
const bool early_remote = early_env && early_env[0] == '1';
for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0 && (r == 0 || early_remote)) {
// Keep CUDA1's proven startup order: initialise its context before
// allocating GPU0 weights or mapping the large host expert arena.
double free_gib = 0;
if (!strata::core::RemoteExperts::preflight(remote_dev[0], free_gib, err)) {
if (!strata::core::RemoteExperts::preflight(remote_dev[r], free_gib, err)) {
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
return 1;
}
std::fprintf(stderr, "strata generate: CUDA%d context ready, %.2f GiB free before expert arena registration\n",
remote_dev[0], free_gib);
remote_dev[r], free_gib);
}
// plan v0.3 P6: the PCIe share of the missed experts, measured per kind of pack (the paper, finding on PCIe).
// PR #44: a x8 link carries half of what the native default assumes - the GPU's SMs read that share over the
@@ -1516,6 +1528,21 @@ int main(int argc, char** argv) {
std::fprintf(stderr, "strata generate: session_init failed\n");
return 1;
}
// **A GENERATE RUN ON A NATIVE PACK NEVER ZEROED THE SESSION STATE.** The canonical path zeroes it from
// `put_input` at position 0 (`session_zero`, with the embedding as `R`), but a native pack breaks out of that
// loop before the first `put_input` - it runs verify windows instead - and neither the batched prompt path
// nor the verifier zeroes anything. `sbuf` is `cudaMalloc`'d, so the GDN recurrence, the QSA KV/indexer
// state, the PLE history and `R` all started from whatever the allocator last held: finite on a fresh
// allocation and overflow/NaN after reuse, which surfaced as the whole layer stack saturating and every
// prompt decoding to the same token. `--serve` zeroes exactly this state when `resume == 0`; generate mode
// always starts from an empty sequence, so it must too.
// (#167) Every pack, not only a native one: a canonical pack whose prompt goes through the batched prompt path
// (--prefill) starts at position 0 without a put_input, so it never zeroed the state either.
strata::core::session_zero(ss, g, nullptr, main_cs);
if (cudaDeviceSynchronize() != cudaSuccess) {
std::fprintf(stderr, "strata generate: zeroing the session state failed\n");
return 1;
}
if (g.n_qsa_layers() > 0 && ss.qsa_states[0].kv_mode == 1)
std::fprintf(stderr, "strata generate: KV streaming: %lld of %lld cells per QSA layer in VRAM, the K/V in "
"%.2f GiB of pinned RAM\n", (long long) (ss.qsa_states[0].n_slots * 4),
@@ -1564,7 +1591,9 @@ int main(int argc, char** argv) {
float* ple_scratch = nullptr;
if (!o.ple_gguf.empty()) {
strata::kernels::PleIoOptions pio;
pio.mode = o.ple_io == "mmap" ? strata::kernels::PleIo::Mmap : strata::kernels::PleIo::Direct;
pio.mode = o.ple_io == "mmap" || o.ple_io == "ram" ? strata::kernels::PleIo::Mmap : strata::kernels::PleIo::Direct;
pio.lock = o.ple_io == "ram";
const auto tpl = Clock::now();
pio.max_inflight = (uint32_t) o.ple_inflight;
pio.cache_rows = (uint64_t) o.ple_row_cache;
pio.io_thread = !o.ple_sync_submit;
@@ -1572,6 +1601,10 @@ int main(int argc, char** argv) {
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
return 1;
}
if (pio.lock)
std::fprintf(stderr, "strata generate: PLE table %s (--ple-io ram) in %.1f s\n",
ple_table.locked() ? "locked in RAM" : "loaded (not locked)",
std::chrono::duration<double>(Clock::now() - tpl).count());
const strata::core::WeightRef* wk = wt.find("blk.1.ple_key.weight");
const strata::core::WeightRef* wv = wt.find("blk.1.ple_value.weight");
const strata::core::WeightRef* wnk = wt.find("blk.1.ple_norm_key.weight");
@@ -1730,7 +1763,7 @@ int main(int argc, char** argv) {
}
// Create the additional contexts after MTP has secured CUDA0 memory, but
// before the host arena maps its expert pages into their address spaces.
for (int r = 1; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) {
for (int r = 1; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0 && !early_remote) {
double free_gib = 0;
if (!strata::core::RemoteExperts::preflight(remote_dev[r], free_gib, err)) {
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
@@ -1993,12 +2026,20 @@ int main(int argc, char** argv) {
// (with borrowing - the default with a profile - the prompt path lends cache slots instead)
const bool borrow = !o.no_prefill_borrow && !o.expert_profile.empty();
const int64_t prefill_mib = (o.prefill_chunk > 0 && !borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0;
const int64_t reserve = ((int64_t) o.vram_reserve_mib + prefill_mib) << 20;
// the draft layer's head and logits are allocated when it binds, after this: 0.1.27's CJK subset made them
// ~110-180 MiB larger, and out of the reserve they left 16 GB cards below the stall line (#199)
const int64_t mtp_bind = (!o.mtp.empty() && native_head.loaded())
? (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) : 0;
const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + mtp_bind;
int64_t slots = ((int64_t) free_b - reserve) / (int64_t) strata::kernels::cpu::expert_layout().max_blob;
if (!profile.empty()) slots = std::min<int64_t>(slots, (int64_t) profile.size());
o.expert_cache = (int) std::max<int64_t>(slots, 0);
std::fprintf(stderr, "strata generate: expert cache auto: %.2f GiB free, %d MiB reserved -> %d slots\n",
(double) free_b / 1073741824.0, o.vram_reserve_mib, o.expert_cache);
std::fprintf(stderr, "strata generate: expert cache auto: %.2f GiB free, %d MiB reserved (+%lld MiB for the "
"draft head) -> %d slots\n",
(double) free_b / 1073741824.0, o.vram_reserve_mib, (long long) (mtp_bind >> 20), o.expert_cache);
if (o.expert_cache == 0) // the verify window cannot start without it (#174): say what makes room
std::fprintf(stderr, "strata generate: no VRAM is left for the expert cache: lower --max-context, use "
"--kv k8v4, run images on the CPU, or close other programs that use the GPU\n");
} else if (multi_gpu && o.expert_cache > 0) {
// a layer split's prompt path has its own buffers (it borrows no slots): an explicit cache size leaves room
// for them and the reserve, or the first prompt fails with "device buffers ... do not fit"
@@ -2064,6 +2105,7 @@ int main(int argc, char** argv) {
// STRATA_TEST_CACHE_FAIL=N: the first N opens fail as an out-of-commit cudaMalloc does (tests the retry)
int fake_fails = std::getenv("STRATA_TEST_CACHE_FAIL") ? std::atoi(std::getenv("STRATA_TEST_CACHE_FAIL")) : 0;
int failed = 0;
int zero_reads = 0;
for (int attempt = 0;; ++attempt) {
bool ok = false;
if (fake_fails > 0) {
@@ -2107,9 +2149,11 @@ int main(int argc, char** argv) {
cudaMemGetInfo(&free_b, &total_b);
const int64_t want = (int64_t) o.vram_reserve_mib << 20;
if ((int64_t) free_b >= want - (64ll << 20)) break;
// short by (want - free); a figure of 0 only says "at least", so then give back a quarter as well
// short by (want - free); a figure of 0 only says "at least": the first two such reads give back 1 GiB
// each (under WDDM the free figure read before the allocation runs ~0.7 GiB high), later ones a quarter
int64_t give = want - (int64_t) free_b + (64ll << 20);
if (free_b < ((size_t) 16 << 20)) give = std::max<int64_t>(give, xcache.bytes() / 4);
if (free_b < ((size_t) 16 << 20))
give = std::max<int64_t>(give, ++zero_reads <= 2 ? 1ll << 30 : xcache.bytes() / 4);
const int64_t keep_bytes = xcache.bytes() - give;
std::fprintf(stderr, "strata generate: only %lld MiB free once the slots are written (reserve %d MiB); "
"shrinking the expert cache\n", (long long) (free_b >> 20), o.vram_reserve_mib);
@@ -3559,6 +3603,7 @@ int main(int argc, char** argv) {
~BusyScope() { strata::core::progress().busy.store(false); strata::core::progress_at("idle"); }
} busy_scope;
stop_req.store(false); // a STOP that arrived between requests is stale
err.clear();
const bool geni = line.rfind("GENI ", 0) == 0;
if (!geni && line.rfind("GEN ", 0) != 0) {
std::printf("ERR expected: GEN <max_new> <id,id,...> or GENI <max_new> <file> <id,id,...>\n");
@@ -3844,6 +3889,7 @@ int main(int argc, char** argv) {
};
// tokens [a, b) through the windows: commit all of them, then give the draft layer their residuals
auto read_windows = [&](int64_t a, int64_t b, std::string& e) -> bool {
strata::core::progress_at("reading the prompt (verify windows), from token", a); // #217: not "batched"
// every token is committed and the picks are discarded: no head sampling (see set_head_sampling)
struct NoHeadSampling {
strata::core::Verifier& v;
@@ -3976,6 +4022,7 @@ int main(int argc, char** argv) {
int64_t at = read_from;
for (const int64_t to : {reread_to, root_at, turn_at, n - 1}) {
if (to <= at) continue;
err.clear();
const bool win = windows_ok(at, to);
if (win && !refill(err)) {
std::printf("ERR refilling a lent slot failed: %s\n", err.c_str());
@@ -3997,6 +4044,13 @@ int main(int argc, char** argv) {
if (!stop_req.load()) {
std::fprintf(stderr, "strata serve: %s\n", err.c_str());
std::printf("ERR %s\n", err.c_str());
// #224: a CUDA fault (an illegal address) poisons the context for the whole process, and
// unwinding the destructors on it could hang until the 60 s watchdog: leave at once
if (cudaPeekAtLastError() != cudaSuccess) {
std::fflush(stdout);
std::fflush(stderr);
std::_Exit(1);
}
return 1;
}
cancelled = true; // stopped while reading the prompt: refill the lent slots below, then DONE cancel
+7 -1
View File
@@ -308,7 +308,10 @@ def main() -> int:
blob = per[0] + per[1] + per[2]
layout.append((l, ts[0].type_id, ts[2].type_id, offset, blob, ts))
offset += blob * n_expert
with open(out / "native_experts.txt", "w", encoding="utf-8", newline="\n") as fo:
# written to a temporary name and renamed only when every layer is in: a stop part-way (a layer split across
# shards, #171) left a partial native_experts.txt that the next setup run took as a finished pack (#172)
tmp = out / "native_experts.txt.tmp"
with open(tmp, "w", encoding="utf-8", newline="\n") as fo:
fo.write("# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] "
"(n_expert %d, total %d; absolute offsets in %s, or in the named shard beside it)\n"
% (n_expert, offset, src.name))
@@ -316,10 +319,13 @@ def main() -> int:
ws = [model.where[t.name] for t in ts]
if len({w[3] for w in ws}) != 1:
print("layer %d: its gate/up/down tensors are in different shards" % l)
fo.close()
tmp.unlink()
return 1
gg, shard = ws[0][0], ws[0][3]
line = "%d %d %d %d %d %d %d %d" % (l, gt, dt, off, blob, *[gg.data_start + t.offset for t in ts])
fo.write(line + ("" if shard == src else " " + shard.name) + "\n")
tmp.replace(out / "native_experts.txt")
if a.skip_experts or not a.experts_bin:
if (out / "experts.bin").exists() and not a.experts_bin:
print("note: %s/experts.bin exists; the engine reads it instead of the GGUF" % out)