Merge branch 'f-1402-s' into f-1402

# Conflicts:
#	serve/server.py
This commit is contained in:
Niko1221 committed 2026-10-07 11:27:21 +02:00
commit 57747c1aa9
10 files changed
+426 -24

No files matched your search

+45 -3
View File
@@ -269,7 +269,8 @@ an RX 9070 XT 16 GB and a Radeon AI PRO R9700 32 GB (both gfx1201), a Ryzen 9 39
tok/s on a 4K prompt, 52.0 -> 60.5 warm) and +5-7% on the 9070 XT, prompts unchanged, the same tokens.
- **hipBLASLt:** the validation above used hipBLASLt 1.4.1. A table calibrated on the R9700 at the engine's shapes
with that version (0.98-1.76x per GEMM over hipBLAS) changed the end-to-end prompt speed by 0-3%, within noise,
so none was shipped for it: there the plain hipBLAS path is already close. For hipBLASLt 1.5.0 (ROCm
so none was shipped for it: there the plain hipBLAS path is already close (a table I calibrated on my own R9700
with 1.4.1 measured the same: 1.15x per GEMM, +1% prompt - see "Tuning table" below). For hipBLASLt 1.5.0 (ROCm
10.2.0a nightly) `tools/hip/gfx1201-hipblaslt-100500.txt` is shipped (see "Tuning table" below); on one R9700 it
measured +3.9% prompt speed on 4,210-token prompts (1,590 vs 1,531 tok/s), a modest gain.
With the hipBLASLt 1.2.2 of a system ROCm 7.2.4 the plain path is far off, and `tools/hip/gfx1201-hipblaslt-100202.txt`
@@ -302,14 +303,21 @@ an RX 9070 XT 16 GB and a Radeon AI PRO R9700 32 GB (both gfx1201), a Ryzen 9 39
nightly); a user's repeated A/B/A/B with setup's TheRock 7.10 wheels and an i5-12600K measured +1-4%, inside a
12-20% run-to-run spread (#432) - how much it gains depends on how much of decode the router is on that setup.
`STRATA_HIP_ROUTER_OLD=1` runs the portable kernel.
- `STRATA_HIP_WMMA=1` (opt-in, gfx12 only, int8 KV): the prompt path's QSA attention on RDNA4 matrix cores
- `STRATA_HIP_WMMA=1` (opt-in, gfx12 only, int8 KV): the prompt path's QSA attention on RDNA4 matrix cores (the engine prints a one-line hint about it at start on gfx12 with `--kv int8`; it never enables it, because the output bits change; setting the variable to anything, 0 included, silences the hint)
(`v_wmma_f32_16x16x16_f16`, FP16 hi + lo halves like the CUDA tensor-core kernel; `hip_prompt_attn_wmma` bounds it
against the FP32 kernel and FP64). 7.2-7.5x the portable kernel; R9700 prompts 4K 1,784 -> 2,427 tok/s, 16K
1,797 -> 2,700 (a user with TheRock 7.10: +29-34%, #432). Not bitwise: greedy text differs from token ~50 on, as with the CUDA tensor-core attention. With it
the prompt path's expert ring is 96 slots (as STRATA_PREFILL_RING=96): with the default 384 the 9070 XT's 4K
prompts fell to 718 tok/s; with 96 they gain (1,017 -> 1,211; 16K 1,518 -> 2,032). PR #329
(bsorensen110) contributed an equivalent gfx12 WMMA kernel of the same speed (within 1%); this one also masks KV
pages that KV streaming has not made resident, as the decode kernel does.
pages that KV streaming has not made resident, as the decode kernel does. On my R9700 (engine 0.1.40,
IQ3_S at 431072 ctx, `--kv int8`, the gfx1201 hipBLASLt 1.4.1 table below, which names the machine, GPU idle):
fresh prompts of 4,210 and 8,830 tokens - the longest prompt I measured there is 8,830 tokens, the 431072 ctx is
what the model runs at, not what these prompts reach - three matched trials each, the first fresh prompt after
each start left out: 1,571 -> 2,064 and 1,568 -> 2,065 tok/s at 8,830 tokens (+31.4 and +31.7%) and 1,699 ->
1,990 at 4,210 (+17.1%), medians 1,571 -> 2,064 and a 1.27x geometric mean over those three. decode
89.8 -> 86.9 tok/s, unchanged. `STRATA_SELECT_WMMA=1` on top changed nothing at those lengths (2,026 tok/s);
its +1.5% is a 16K/262K-ctx number. `hip_prompt_attn_wmma` passes on that card.
- The prompt path's QSA top-k picks its kernel by the blocks a query actually has, not the cache's capacity (#337,
bsorensen110): the same ids, on by default with AMD (NVIDIA keeps its capacity rule: there the 64K prompts read
1-3% slower with it). `STRATA_SELECT_WMMA=1` (opt-in, gfx12) adds #337's
@@ -495,6 +503,15 @@ Shipped tables:
Swift 1.5 IQ3_XXS at 262144 ctx, fresh-prompt prefill measured 682 -> 1,038 tok/s at 1.7K tokens and
857 -> 1,524 tok/s at 6.5K (medians of 3, decode unchanged), with `hip_prefill_hipblaslt_gemm` reporting
`fallbacks=0`. setup uses it only when the installed hipBLASLt reports 1.4.1.
The 43-row revision adds the two geometries the 26 dense ones do not reach, calibrated with
`tune_hipblaslt` from the same tree and the engine's 32 MiB workspace: `f16 1280 2560 1280` (the
small-T expert GEMM, T=8..999) and `bf16 10240 2560 10240`. A prompt on Qwen3.8-Flash-Next GSQ-RCO
IQ2_XS at 192000 ctx otherwise falls back on the expert GEMM for nearly every launch:
`STRATA_HIPBLASLT_VERBOSE=1` reported 642 fallbacks over 642 distinct T values (1..1873) with the
26-row table. Adding the rows measured 711 -> 938 tok/s (+31.9 %, mean of 3 interleaved pairs:
+36.0 / +32.4 / +27.6 %) at a 3151-token prompt, decode unchanged (58.6 -> 60.6 tok/s, inside this
box's 2.3 % run drift), and `fallbacks=0`. The lookup takes the nearest T bucket for a matching
geometry, so the buckets cover the whole small-T range rather than one row per T.
- `gfx1100-hipblaslt-100500.txt`: RX 7900 XTX (gfx1100, 24 GB), calibrated with a ROCm 10.2.0a20261003 nightly
SDK (`libamdhip64.so.7.17.26392`, hipBLASLt 1.5.0, version number 100500). Same 16 dense GEMM geometries at
T=4096 and T=8192 as the other gfx1100 tables (32 rows), calibrated with `tune_hipblaslt` run against that
@@ -513,6 +530,31 @@ Shipped tables:
`STRATA_HIPBLASLT_VERBOSE=1` and look for `fallbacks=0` in its summary line, and recalibrate with
`tune_hipblaslt` before using this table with a different 1.5.0 build.
Calibrated on my PC and kept in this checkout, not shipped: `gfx1201-hipblaslt-100401.txt`, a Radeon AI PRO
R9700 (gfx1201, 32 GB, 1002:7551) on a Ryzen 9 9950X3D with 62 GiB RAM, CachyOS (kernel 7.3.0-rc6-1-cachyos-rc,
`linux-firmware-amdgpu 20260916`, the kernel's amdgpu driver), system ROCm `rocm-gfx120x-bin 10.1.0` (hipBLASLt
1.4.1, HIP 7.16.26385, clang 24.0.0), Python 3.14.7 in setup's own venv, engine 0.1.40 compiled there for gfx1201,
the model files on a 4 TB NVMe (btrfs), IQ3_S at 131072 ctx with `--kv int8`, the GPU idle. `tune_hipblaslt` over
the 32 geometries of `gfx1201-hipblaslt-100500.txt`: 1.15x geometric mean per GEMM over hipBLAS - 1.55-1.68x at
N=512/640 K=2560, 0.99-1.13x at N=10240/12288 K=2560. End to end with `tools/hip/bench_prefill.py` over two
server starts, fresh prompts of 4,210 and 8,830 tokens, three matched trials each - the first fresh prompt after
each start is left out, it is cold (949 and 1,423 tok/s there): 1,606 -> 1,613, 1,701 -> 1,726 and 1,605 -> 1,610
tok/s (+0.5, +1.5, +0.4%), medians 1,606 -> 1,613 and a 1.008x geometric mean over those three, decode
87.1 -> 85.1 tok/s - within noise, as the R9700 paragraph above found. `hip_prefill_hipblaslt_gemm` passes with it: `tuning enabled (30 rows, gfx1201,
version 100401)`, `launches=4 fallbacks=0`.
Two rows were dropped from that table: bf16 N=10240 K=320 ldy=10240 at T=4096 and at T=8192. At T=8192 hipBLAS was
faster in five separate `tune_hipblaslt` runs - 0.609-0.619 ms against 0.648-0.677 ms for the best of the 16
hipBLASLt candidates (0.90-0.95x), with four different winning solution ids, all slower than hipBLAS. Dropping only
the T=8192 row does not send that call back to hipBLAS: `closest()` matches dtype/N/K/ldy and takes the nearest T
bucket, so T=8192 would run the T=4096 row; both rows go or neither.
Two calibration notes from my machine. The first case of a fresh `tune_hipblaslt` process times its hipBLAS
baseline while the clocks are still ramping: that T=4096 shape read 0.31-0.63 ms across five runs while the case
timed right after it held 0.606-0.619 ms every time, so time a heavy case first and read the later ones. And the
first fresh prompt after the model loads is not a measurement: it gave 949 and 1,423 tok/s in the two arms of that
A/B, while the three trials after it differed by 0.4-1.5%.
## Original backend validation (PR #94)
The following is historical validation of the original backend, not a fresh
+14
View File
@@ -110,6 +110,20 @@ answer after a start differ from the next ones. Measured here (IQ3_XXS, a 3.6K-t
three switches 1 answer of 4, without `--pcie-frac 0` 2 of 4 (the first one differs), with the defaults 2 of 4.
`--pcie-frac 0` costs decode speed (the missed experts all run on the CPU), so keep it for A/B runs.
**Coupled drafts with Gumbel-max picks (opt-in, `STRATA_SPEC_COUPLED=1` and `STRATA_SPEC_GUMBEL=1`):** for a request
that samples (temperature above 0), `STRATA_SPEC_COUPLED=1` lets the draft layer sample its guesses with the target's own
chain and random draw instead of taking its most likely token. `STRATA_SPEC_GUMBEL=1` changes how both of them pick from
that chain: the token with the largest p / E, where E is exponential noise keyed by the seed, the position and the token
id (the Gumbel-max trick; it is still an exact sample of the same distribution). With the default pick, one random number
walked over the candidates sorted by probability, a draft and a target whose candidate lists differ in one token tend to
land on different tokens; with noise keyed by the token, a token gets the same noise on both sides, so they agree on the
tokens they share. Greedy requests are unchanged, and without the variables nothing changes. Measured on a Ryzen AI
Max+ 395 (Radeon 8060S, Linux, ROCm 7.14.1, the iGPU alone), UD-Q4_K_XL, `--spec 4 --mtp` (the base model's draft
layer), temperature 1.0 / top_p 0.95 / top_k 20, a 1.3K-token prompt and 512 output tokens, 12-13 requests per arm:
drafts accepted 52.8% -> 59.9%, tokens per verify window 2.65 -> 2.88, output 41.1 -> 44.9 tokens/s (+9%); a window
costs the same (draft 8.8 -> 9.1 ms of 64). `sampler_parity` checks the pick against a host reference on every sampled
path, and that its frequencies match the softmax. On an RTX 3060 (IQ3_XXS, `--spec 4 --mtp`, temperature 1.0 / top_p 0.95 / top_k 20, 12 interleaved pairs of 200-token story and code requests) `STRATA_SPEC_COUPLED=1` raised the accepted drafts from 62.1% to 66.9% and adding `STRATA_SPEC_GUMBEL=1` to 68.0%, but decode speed did not move beyond the run-to-run spread (median 43.3 tok/s with coupled alone, 42.8 with Gumbel as well): try it on your own card before relying on it.
**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
+5
View File
@@ -11,6 +11,11 @@
// the two inverse-CDF picks from one uniform agree far more often than an argmax agrees with a sample; the target's
// pick - and so the text - does not change, because verification is still exact-match against the target's sample.
//
// STRATA_SPEC_GUMBEL=1 (opt-in) replaces the inverse-CDF pick on BOTH sides with a Gumbel-max pick: argmax p_i / E_i,
// E_i ~ Exp(1) keyed by (seed, counter, token id) (sampler.cu `gumbel_exp`). A token then gets the same noise in the
// draft's and the target's draw whichever other tokens survived either cut, so they agree on the tokens they share;
// with one uniform over two probability-sorted lists, a one-token difference in the lists shifts every later pick.
//
// THE COUNTER ARITHMETIC (all positions are sequence indices; a window's row t holds the token at pos0 + t and its
// pick is the token at pos0 + t + 1, drawn with counter pos0 + t):
// * MTP cell c pairs the main model's residual at position c with the token at c + 1 and predicts the token at
+1
View File
@@ -25,6 +25,7 @@ struct SamplerParams {
uint64_t seed = 0; // drives Philox, which is counter-based on (seed, token index)
uint64_t counter = 0; // absolute draw index of row 0; advance across decode calls
bool greedy = false;
bool gumbel = false; // STRATA_SPEC_GUMBEL=1: Gumbel-max pick keyed by (seed, counter, token id) - see sampler.cu
};
// logits (n_tokens, n_vocab) -> one sampled token id per row in `out`.
+92 -4
View File
@@ -214,6 +214,25 @@ SESSION_WAIT_MAX_S = 3600
PP_CHUNK_MAX = 32768
PP_FLOOR_TOK_S = 50.0
PP_SLACK = 3.0
# Reads that had no timeout (#1317). A blocking read of the image encoder's pipe or of the engine's READY line that
# never returned held the request turn for good: the engine then sat idle in its command loop, so no watchdog could
# fire and every later request queued behind it (the "lost step" class of #481). Generous on purpose: a cold model
# load, a slow disk or a slow CPU encode is not a hang. Only a process that says nothing at all for this long is
# ended; the next request starts it again.
# STRATA_ENGINE_READY_S / STRATA_VISION_READY_S / STRATA_VISION_ENCODE_S override them (0 = wait for ever, as before).
def _timeout_env(name: str, default: float) -> float | None:
try:
v = float(os.environ.get(name, default))
except ValueError:
v = default
return None if v <= 0 else v
VISION_READY_S = _timeout_env("STRATA_VISION_READY_S", 300.0)
VISION_ENCODE_S = _timeout_env("STRATA_VISION_ENCODE_S", 300.0)
ENGINE_READY_S = _timeout_env("STRATA_ENGINE_READY_S", 900.0)
# ------------------------------------------------------------------------------------------------ engines
@@ -611,7 +630,23 @@ class StrataEngine:
self.proc = popen("the Strata engine", [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)
for line in self.proc.stdout:
# the READY read has a timeout (#1317): the lines come from a thread, up to READY, so the rest of the stream
# stays for _pump (one reader at a time)
ready_q: queue.Queue = queue.Queue()
threading.Thread(target=self._ready_pump, args=(self.proc, ready_q), daemon=True).start()
ready_deadline = None if ENGINE_READY_S is None else time.monotonic() + ENGINE_READY_S
timed_out = False
while True:
left = None if ready_deadline is None else ready_deadline - time.monotonic()
if left is not None and left <= 0:
timed_out = True
break
try:
line = ready_q.get(timeout=left)
except queue.Empty:
continue
if line is None:
break
if line.startswith("INFO "):
for kv in line.split()[1:]:
k, _, v = kv.partition("=")
@@ -623,6 +658,11 @@ class StrataEngine:
break
loading.set()
if self.max_context <= 0:
if timed_out: # still loading, or hung: end it, so the turn is not held for good
try:
self.proc.kill()
except OSError:
pass
try: # its pipes and our handle on its log (the log stays)
self.proc.wait(timeout=5)
self.proc.stdin.close()
@@ -631,7 +671,9 @@ class StrataEngine:
self.log.close()
except (OSError, subprocess.TimeoutExpired):
pass
raise RuntimeError("the engine exited before it was ready" + (f" (see {log})" if log else "") +
why = (f"the engine did not report READY within {ENGINE_READY_S:.0f} s" if timed_out else
"the engine exited before it was ready")
raise RuntimeError(why + (f" (see {log})" if log else "") +
start_failure_hint(log, log_start) + start_log_tail(log, log_start))
self.known_ctx = self.max_context # survives a failed restart: requests keep their limit and restart it
# (from PR #41, midhatn) a locally built engine can sit next to another release's BUILD.json: engines that
@@ -759,6 +801,22 @@ class StrataEngine:
RESTART_RETRY_S = 15.0 # between the tries of restart(): a dying engine's VRAM may take a while to come back
@staticmethod
def _ready_pump(proc, out: queue.Queue) -> None:
"""The engine's first lines up to READY, for a read that can time out; None when its output closed first."""
done = False
try:
for line in proc.stdout:
out.put(line)
if line.startswith("READY"):
done = True
return
except (OSError, ValueError): # the pipe closed under us (the engine was killed)
pass
finally:
if not done:
out.put(None)
def restart(self, tries: int = 3):
"""Start the engine again (the same command) after it died; the new process has its own line queue.
close() ends and waits for the old process first (EngineStuck when it cannot be ended). A start that still
@@ -1689,7 +1747,11 @@ class Vision:
stderr=log or subprocess.DEVNULL, text=True, encoding="utf-8", bufsize=1, env=env,
cwd=self.dir)
contain(self.proc)
line = self.proc.stdout.readline()
try:
line = self._readline(VISION_READY_S, "the vision encoder did not start")
except RuntimeError as e: # silent for VISION_READY_S: it was ended, and it is not left half-started
self.proc, self.stopped = None, True
raise RuntimeError(str(e)) from None
if not line.startswith("READY"):
proc, self.proc = self.proc, None
self.stopped = True
@@ -1701,6 +1763,28 @@ class Vision:
raise RuntimeError("the vision encoder did not start: " + line.strip())
self.stopped = False
def _readline(self, timeout: float, what: str) -> str:
"""One line from the encoder, waiting at most `timeout` s (#1317). On a timeout the encoder is killed, so the
next request starts a fresh one, and the read raises RuntimeError instead of holding the request turn."""
proc = self.proc
got: queue.Queue = queue.Queue()
def read():
try:
got.put(proc.stdout.readline())
except (OSError, ValueError): # killed under the read
got.put("")
threading.Thread(target=read, daemon=True).start()
try:
return got.get(timeout=timeout)
except queue.Empty:
try:
proc.kill()
except OSError:
pass
raise RuntimeError(f"{what}: it said nothing for {timeout:.0f} s") from None
def alive(self) -> bool:
return self.proc is not None and not self.stopped and self.proc.poll() is None
@@ -1827,7 +1911,11 @@ class Vision:
try:
self.proc.stdin.write(f"ENC {img.name} {out.name}\n") # relative to the encoder's cwd (#480)
self.proc.stdin.flush()
line = self.proc.stdout.readline().strip()
try:
line = self._readline(VISION_ENCODE_S, "the image could not be read").strip()
except RuntimeError as e: # silent for VISION_ENCODE_S: the encoder was ended (#1317)
self.stopped = True # alive() is False, so the next request starts it again
raise ValueError(str(e)) from None
finally: # #352: also when the encoder's pipe is gone
img.unlink(missing_ok=True)
if not line.startswith("OK"):
+84
View File
@@ -4709,5 +4709,89 @@ class ClaudeCodeBillingStamp(unittest.TestCase):
self.assertEqual(ids[1][:len(first) - 8], first[:len(first) - 8]) # all but the generation header
class UntimedReads(unittest.TestCase):
"""#1317: a read of the engine's READY line or of the image encoder's pipe that never returns held the request
turn for good. Each now has a timeout; a process that stays silent is ended and the read raises."""
def test_engine_that_never_says_ready_is_ended(self):
import serve.server as server
fake = "import time\nprint('INFO engine=0.0.0', flush=True)\ntime.sleep(600)\n"
with tempfile.TemporaryDirectory() as d:
script = Path(d) / "fake_strata.py"
script.write_text(fake, encoding="utf-8")
real = server.subprocess.Popen
procs = []
def popen(cmd, **kw):
procs.append(real([sys.executable, str(script), *cmd[1:]], **kw))
return procs[-1]
with mock.patch.object(server.subprocess, "Popen", popen), \
mock.patch.object(server, "ENGINE_READY_S", 1.0), \
mock.patch.object(server, "narrate_start", lambda *a, **k: None):
t0 = time.monotonic()
with self.assertRaises(RuntimeError) as cm:
StrataEngine("strata", [])
self.assertLess(time.monotonic() - t0, 30)
self.assertIn("did not report READY within 1 s", str(cm.exception))
procs[0].wait(10) # killed, not left running
self.assertIsNotNone(procs[0].poll())
class Silent:
"""A pipe whose readline blocks until the test lets go (or the encoder is killed)."""
def __init__(self):
self.release = threading.Event()
self.killed = False
def readline(self):
self.release.wait(30)
return ""
def kill(self):
self.killed = True
self.release.set()
def test_vision_encode_read_times_out(self):
import serve.server as server
silent = self.Silent()
v = server.Vision.__new__(server.Vision)
v.dir, v.lock, v.cache = Path(tempfile.mkdtemp(prefix="strata-vision-test-")), threading.Lock(), {}
v.stopped = False
v.proc = SimpleNamespace(stdin=io.StringIO(), stdout=silent, kill=silent.kill, poll=lambda: 1 if silent.killed else None)
try:
with mock.patch.object(server, "VISION_ENCODE_S", 0.3), \
mock.patch.object(server.Vision, "load", return_value=b""), mock.patch.object(server.Vision, "normalize", return_value=b"png"):
with self.assertRaises(ValueError) as cm:
v.encode("x")
self.assertIn("said nothing for", str(cm.exception))
self.assertTrue(silent.killed) # ended: the next request starts a fresh one
self.assertFalse(v.alive())
self.assertEqual(list(v.dir.glob("*.img")), []) # the temporary image is removed
finally:
shutil_rmtree(v.dir)
def test_vision_ready_read_times_out(self):
import serve.server as server
silent = self.Silent()
proc = SimpleNamespace(stdin=io.StringIO(), stdout=silent, kill=silent.kill, poll=lambda: None)
v = server.Vision.__new__(server.Vision)
v.spawn = (["strata-vision"], None, None)
v.dir = Path(tempfile.mkdtemp(prefix="strata-vision-test-"))
try:
with mock.patch.object(server, "popen", lambda *a, **k: proc), mock.patch.object(server, "contain"), mock.patch.object(server, "VISION_READY_S", 0.3):
with self.assertRaises(RuntimeError) as cm:
v._start()
self.assertIn("did not start", str(cm.exception))
self.assertTrue(silent.killed)
self.assertFalse(v.alive())
finally:
shutil_rmtree(v.dir)
def test_a_vision_answer_in_time_is_unchanged(self):
import serve.server as server
v = server.Vision.__new__(server.Vision)
v.proc = SimpleNamespace(stdout=SimpleNamespace(readline=lambda: "OK 7 1 1 1\n"))
self.assertEqual(v._readline(5.0, "x"), "OK 7 1 1 1\n")
if __name__ == "__main__":
unittest.main()
+60 -15
View File
@@ -63,6 +63,22 @@ __device__ __forceinline__ float philox_uniform(uint64_t seed, uint64_t counter)
return (float) (c0 >> 8) * (1.0f / 16777216.0f);
}
// GUMBEL-MAX COUPLING (STRATA_SPEC_GUMBEL=1, ported from llama.cpp-lab's --spec-coupled, lab PRs #26/#30). The pick
// is argmax_i p_i / E_i with E_i = -log(u_i) ~ Exp(1) and u_i a hash of (seed, counter, TOKEN ID) - exactly
// equivalent to argmax(log p_i + Gumbel_i), so it is an exact sample of p. Unlike the inverse-CDF pick over a
// probability-sorted list, the noise a token gets does not depend on which other tokens survived the cut, so a
// drafter whose candidate set differs from the target's still agrees with it on the tokens they share ("support
// invariant"). The MTP drafter keys on the draft's token id (via sub_to_id), the target on its row's token id.
__device__ __forceinline__ double gumbel_exp(uint64_t seed, uint64_t counter, uint32_t token) {
uint64_t z = seed ^ (counter * 0x9E3779B97F4A7C15ull) ^ ((uint64_t) token * 0xD1B54A32D192ED03ull);
z += 0x9E3779B97F4A7C15ull;
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
z ^= z >> 31;
const double u = ((double) (z >> 11) + 0.5) * (1.0 / 9007199254740992.0); // (0, 1), never 0 or 1
return -log(u);
}
// `count_in_history` and the penalty application, transcribed from `llama_sampler_penalties_apply`.
// The repeat penalty MULTIPLIES for non-positive logits and DIVIDES for positive ones - dividing
// unconditionally is the natural reading of the source paper and it INVERTS the penalty on half the
@@ -399,12 +415,21 @@ __global__ void sampler_kernel(const float* __restrict__ logits, int n_vocab, in
for (int i = 1; i < n_keep; ++i) smx = fmaxf(smx, scaled(i));
double sum = 0.0;
for (int i = 0; i < n_keep; ++i) sum += exp((double) scaled(i) - (double) smx);
const float u = philox_uniform(p.seed, p.counter + (uint64_t) t);
double cum = 0.0;
int pick = sel_ids[n_keep - 1];
for (int i = 0; i < n_keep; ++i) {
cum += exp((double) scaled(i) - (double) smx) / sum;
if ((double) u < cum) { pick = sel_ids[i]; break; }
if (p.gumbel) {
double best = -1.0;
for (int i = 0; i < n_keep; ++i) {
const double r = exp((double) scaled(i) - (double) smx) / sum /
gumbel_exp(p.seed, p.counter + (uint64_t) t, (uint32_t) sel_ids[i]);
if (r > best) { best = r; pick = sel_ids[i]; }
}
} else {
const float u = philox_uniform(p.seed, p.counter + (uint64_t) t);
double cum = 0.0;
for (int i = 0; i < n_keep; ++i) {
cum += exp((double) scaled(i) - (double) smx) / sum;
if ((double) u < cum) { pick = sel_ids[i]; break; }
}
}
if (threadIdx.x == 0) out[t] = pick;
}
@@ -455,7 +480,8 @@ __device__ __forceinline__ void warp_first(float& bv, int& bi) {
/// `*prob_out`. The sampler's own calls take kProb = false, whose code is the tail above, unchanged.
template <bool kProb = false>
__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, float* prob_out = nullptr) {
int* __restrict__ out, double* ex, float* prob_out = nullptr,
const int32_t* __restrict__ sub_to_id = nullptr) {
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;
@@ -503,13 +529,22 @@ __device__ void sampled_tail_warp(const int* sel_ids, const float* sel_logit, in
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 pi = n_keep > 0 ? n_keep - 1 : 0;
int pick = sel_ids[pi];
for (int i = 0; i < n_keep; ++i) {
cum += ex[i];
if ((double) u < cum) { pick = sel_ids[i]; pi = i; break; }
if (p.gumbel) {
double best = -1.0;
for (int i = 0; i < n_keep; ++i) {
const int id = sub_to_id != nullptr ? sub_to_id[sel_ids[i]] : sel_ids[i];
const double r = ex[i] / gumbel_exp(p.seed, p.counter + (uint64_t) t, (uint32_t) id);
if (r > best) { best = r; pick = sel_ids[i]; pi = i; }
}
} else {
const float u = philox_uniform(p.seed, p.counter + (uint64_t) t);
double cum = 0.0;
for (int i = 0; i < n_keep; ++i) {
cum += ex[i];
if ((double) u < cum) { pick = sel_ids[i]; pi = i; break; }
}
}
out[t] = pick;
if constexpr (kProb) *prob_out = n_keep > 0 ? (float) ex[pi] : 1.0f;
@@ -769,10 +804,12 @@ sampler_split_merge_kernel(const int2* __restrict__ cand, int n_blocks, int n_vo
/// The round's inputs: the request's SamplerParams and the history base (the last h slots before `cap`), from
/// mapped host memory into the device copies the chain's kernels read.
__global__ void coupled_stage_kernel(const SamplerParams* __restrict__ mp, const int* __restrict__ mh,
SamplerParams* __restrict__ dp, int* __restrict__ ring, int cap) {
SamplerParams* __restrict__ dp, int* __restrict__ ring, int cap, int gumbel) {
const volatile int* s = (const volatile int*) mp;
int* d = (int*) dp;
for (int i = threadIdx.x; i < (int) (sizeof(SamplerParams) / sizeof(int)); i += blockDim.x) d[i] = s[i];
__syncthreads(); // the word holding `gumbel` was just copied
if (threadIdx.x == 0) dp->gumbel = gumbel != 0;
const int h = strata::core::coupled_hist_len(((const volatile SamplerParams*) mp)->penalty_last_n, cap);
const volatile int* vh = (const volatile int*) mh;
for (int i = cap - h + (int) threadIdx.x; i < cap; i += blockDim.x) ring[i] = vh[i];
@@ -831,7 +868,7 @@ coupled_merge_kernel(const int2* __restrict__ cand, int n_blocks, int nv, int kp
if (p.greedy || p.temperature <= 0.0f) { // never launched for greedy requests; the argmax, defensively
if (lane == 0) { pick[0] = sel_ids[0]; prob[0] = 1.0f; }
} else {
sampled_tail_warp<true>(sel_ids, sel_logit, k, p, 0, pick, ex, prob);
sampled_tail_warp<true>(sel_ids, sel_logit, k, p, 0, pick, ex, prob, sub_to_id);
}
__syncwarp();
if (lane == 0) {
@@ -1071,6 +1108,11 @@ bool env_flag(const char* name) {
return e != nullptr && *e != '\0' && std::strcmp(e, "0") != 0;
}
bool gumbel_env() {
static const bool on = env_flag("STRATA_SPEC_GUMBEL");
return on;
}
SampledPath sampled_path() {
static const SampledPath path = env_flag("STRATA_OLD_SAMPLER") ? SampledPath::Old
: env_flag("STRATA_SAMPLER_ONE_BLOCK") ? SampledPath::OneBlock
@@ -1195,7 +1237,9 @@ bool sample_greedy_cluster(const float* logits, int n_tokens, int n_vocab, int*
}
void sample_tokens(const float* logits, int n_tokens, int n_vocab, const int* history, int history_len,
const SamplerParams& p, int* out, void* stream) {
const SamplerParams& p_in, int* out, void* stream) {
SamplerParams p = p_in;
p.gumbel = p_in.gumbel || gumbel_env(); // the target's pick; greedy rows never read it
if (n_tokens <= 0 || n_vocab <= 0) return;
if (p.penalty_last_n > 0 && (history == nullptr || history_len <= 0)) {
std::fprintf(stderr, "sample_tokens: penalty_last_n %d needs a history (got %p, len %d)\n",
@@ -1272,7 +1316,8 @@ size_t coupled_draft_scratch_bytes(int nv) {
void coupled_draft_stage(const SamplerParams* mapped_params, const int32_t* mapped_hist, SamplerParams* params,
int32_t* ring, int cap, void* stream) {
coupled_stage_kernel<<<1, 256, 0, (cudaStream_t) stream>>>(mapped_params, mapped_hist, params, ring, cap);
coupled_stage_kernel<<<1, 256, 0, (cudaStream_t) stream>>>(mapped_params, mapped_hist, params, ring, cap,
gumbel_env() ? 1 : 0);
coupled_check("coupled_draft_stage");
}
+101 -2
View File
@@ -157,6 +157,18 @@ float host_philox_uniform(uint64_t seed, uint64_t counter) {
return (float) (c0 >> 8) * (1.0f / 16777216.0f);
}
// The Gumbel-max noise, host side - a transcription of the kernel's `gumbel_exp` (STRATA_SPEC_GUMBEL): Exp(1) from
// a splitmix64 hash of (seed, counter, token id). The pick is argmax_i p_i / E_i, an exact sample of p.
double host_gumbel_exp(uint64_t seed, uint64_t counter, uint32_t token) {
uint64_t z = seed ^ (counter * 0x9E3779B97F4A7C15ull) ^ ((uint64_t) token * 0xD1B54A32D192ED03ull);
z += 0x9E3779B97F4A7C15ull;
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
z ^= z >> 31;
const double u = ((double) (z >> 11) + 0.5) * (1.0 / 9007199254740992.0);
return -std::log(u);
}
// The full SAMPLED chain, host side - the kernel's `sampler_kernel` in serial form, in llama.cpp's order:
// penalties on the raw logits during the top_k selection (ties to the lowest index), top_p's cut in double over
// the top_k list, the min_p prefix cut on its survivors, the temperature, and one Philox draw at
@@ -212,9 +224,18 @@ int sampled_reference(const std::vector<float>& l, const std::vector<int>& hist,
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);
int pick = sel_ids[(size_t) (n_keep - 1)];
if (p.gumbel) {
double best = -1.0;
for (int i = 0; i < n_keep; ++i) {
const double r = std::exp((double) scaled(i) - (double) smx) / sum /
host_gumbel_exp(p.seed, p.counter + (uint64_t) row, (uint32_t) sel_ids[(size_t) i]);
if (r > best) { best = r; pick = sel_ids[(size_t) i]; }
}
return pick;
}
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 - 1)];
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; }
@@ -333,9 +354,18 @@ int mirror_pick(const SelList& sel, int k, const strata::kernels::SamplerParams&
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);
int pick = sel.ids[(size_t) (n_keep > 0 ? n_keep - 1 : 0)];
if (p.gumbel) {
double best = -1.0;
for (int i = 0; i < n_keep; ++i) {
const double r = std::exp((double) scaled(i) - (double) smx) / sum /
host_gumbel_exp(p.seed, p.counter + (uint64_t) row, (uint32_t) sel.ids[(size_t) i]);
if (r > best) { best = r; pick = sel.ids[(size_t) i]; }
}
return pick;
}
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; }
@@ -1277,6 +1307,75 @@ int main(int argc, char** argv) {
bad += wrong;
}
// ---- GUMBEL-MAX (STRATA_SPEC_GUMBEL, p.gumbel). (a) The kernel's pick equals the host reference's, draw for draw,
// under the chains the server uses (top_k / top_p / min_p / temperature). (b) It is an exact sample: over many
// counters the picks' frequencies match the softmax of the surviving logits. (c) It is a different stream from
// the inverse-CDF draw (the flag is really read), and greedy rows ignore it.
{
int wrong = 0, draws = 0;
const int nv = 512, T = 16;
std::vector<float> l((size_t) nv * T);
std::vector<int> hist;
{
std::mt19937 rng(4242u);
std::normal_distribution<float> gd(0.0f, 2.0f);
for (auto& v : l) v = gd(rng);
}
struct Chain { int top_k; float top_p, min_p, temp; };
for (const Chain c : {Chain{20, 0.95f, 0.0f, 1.0f}, Chain{0, 1.0f, 0.0f, 0.7f}, Chain{40, 0.9f, 0.05f, 1.3f}}) {
strata::kernels::SamplerParams p;
p.top_k = c.top_k; p.top_p = c.top_p; p.min_p = c.min_p; p.temperature = c.temp;
p.seed = 77; p.counter = 1000; p.gumbel = true;
std::vector<int> want((size_t) T);
for (int t = 0; t < T; ++t)
want[(size_t) t] = sampled_reference({l.begin() + (size_t) t * nv, l.begin() + (size_t) (t + 1) * nv}, {}, p, t);
DeviceRows rows(l, T, hist, 0);
const std::vector<int> got = rows.sample(p, nullptr);
for (int t = 0; t < T; ++t) wrong += got[(size_t) t] != want[(size_t) t];
draws += T;
}
std::printf(" %-34s %s (%d of %d draws differ)\n", "gumbel: kernel vs reference", wrong ? "*** WRONG ***" : "matches",
wrong, draws);
bad += wrong;
// (b) frequencies: one 12-logit row, every row of a launch the same logits at its own counter
const int nv2 = 12, R = 64, launches = 160; // 10,240 draws
std::vector<float> row = {2.0f, 1.5f, 1.2f, 1.0f, 0.5f, 0.3f, 0.0f, -0.5f, -1.0f, -1.5f, -2.0f, -3.0f};
std::vector<float> lr;
for (int r = 0; r < R; ++r) lr.insert(lr.end(), row.begin(), row.end());
strata::kernels::SamplerParams g;
g.top_k = 0; g.top_p = 1.0f; g.temperature = 1.0f; g.seed = 5; g.gumbel = true;
std::vector<double> freq((size_t) nv2, 0.0);
DeviceRows rr(lr, R, {}, 0);
for (int k2 = 0; k2 < launches; ++k2) {
g.counter = (uint64_t) k2 * R;
for (int id : rr.sample(g, nullptr)) freq[(size_t) id] += 1.0;
}
double z = 0.0, tv = 0.0;
for (float v : row) z += std::exp((double) v);
for (int i = 0; i < nv2; ++i) tv += std::fabs(freq[(size_t) i] / (R * launches) - std::exp((double) row[(size_t) i]) / z);
tv *= 0.5;
const bool freq_bad = tv > 0.02; // 10,240 draws: total variation ~0.01 by chance
std::printf(" %-34s %s (total variation %.4f over %d draws)\n", "gumbel: frequencies = softmax",
freq_bad ? "*** WRONG ***" : "matches", tv, R * launches);
bad += freq_bad;
// (c) the flag is read (a different stream than the inverse-CDF draw), and greedy ignores it
strata::kernels::SamplerParams a; a.top_k = 20; a.top_p = 0.95f; a.temperature = 1.0f; a.seed = 9; a.counter = 3;
strata::kernels::SamplerParams b = a; b.gumbel = true;
DeviceRows rows(l, T, hist, 0);
const std::vector<int> ga = rows.sample(a, nullptr), gb = rows.sample(b, nullptr);
int same = 0;
for (int t = 0; t < T; ++t) same += ga[(size_t) t] == gb[(size_t) t];
strata::kernels::SamplerParams ga2; ga2.greedy = true; ga2.temperature = 0.0f;
strata::kernels::SamplerParams gb2 = ga2; gb2.gumbel = true;
const bool greedy_same = rows.sample(ga2, nullptr) == rows.sample(gb2, nullptr);
const bool flag_bad = same == T || !greedy_same;
std::printf(" %-34s %s (%d of %d sampled picks equal the inverse-CDF ones; greedy %s)\n", "gumbel: flag read, greedy unchanged",
flag_bad ? "*** WRONG ***" : "matches", same, T, greedy_same ? "unchanged" : "CHANGED");
bad += flag_bad;
}
std::printf("\nsampler: %d failures\n", bad);
if (bad) return 1;
if (selftest) std::printf("sampler_parity OK\n");
+7
View File
@@ -3950,6 +3950,13 @@ int main(int argc, char** argv) {
const char* name = named && p.name[0] ? p.name : "(an unnamed GPU)";
#if defined(STRATA_USE_HIP)
std::fprintf(stderr, "strata generate: GPU %d: %s (%s)\n", dev, name, named ? p.gcnArchName : "?");
// A hint only, never an action: on RDNA4 with an int8 KV the opt-in matrix-core prompt attention reads prompts
// about 30% faster (R9700, PR #1318), but its output differs from the default kernel's in the last bits, so it
// stays the user's choice. Silent when the variable is set to anything (STRATA_HIP_WMMA=0 included).
if (named && o.kv == "int8" && std::strncmp(p.gcnArchName, "gfx12", 5) == 0 && std::getenv("STRATA_HIP_WMMA") == nullptr)
std::fprintf(stderr, "strata generate: hint: STRATA_HIP_WMMA=1 reads prompts about 30%% faster on this card with "
"--kv int8 (prompt attention on the matrix cores); it is off by default because the output "
"bits change (last-place rounding). Nothing was enabled.\n");
#if defined(_WIN32)
// #468 #461: which HIP runtime was loaded - the bundled one beside the exe, or an AMD driver's System32 copy
if (HMODULE h = GetModuleHandleA("amdhip64_7.dll")) {
+17
View File
@@ -12,10 +12,27 @@ bf16 512 2560 512 8192 1036
bf16 2560 2560 2560 8192 1036
bf16 10240 320 10240 4096 1036
bf16 10240 320 10240 8192 1036
bf16 10240 2560 10240 128 1034
bf16 10240 2560 10240 256 1036
bf16 10240 2560 10240 512 1036
bf16 10240 2560 10240 1024 1036
bf16 10240 2560 10240 2048 1036
bf16 10240 2560 10240 4096 1036
bf16 10240 2560 10240 6144 1036
bf16 10240 2560 10240 8192 1036
f16 512 2560 512 4096 2106
f16 512 2560 512 8192 2106
f16 640 2560 640 4096 2106
f16 640 2560 640 8192 2106
f16 1280 2560 1280 8 2104
f16 1280 2560 1280 16 2104
f16 1280 2560 1280 32 2104
f16 1280 2560 1280 42 2104
f16 1280 2560 1280 64 2104
f16 1280 2560 1280 128 2105
f16 1280 2560 1280 256 2106
f16 1280 2560 1280 512 2106
f16 1280 2560 1280 999 2106
f16 2560 640 2560 4096 2106
f16 2560 640 2560 8192 2106
f16 2560 6144 2560 4096 2106