Merge origin/main into the Monitor per-card PCIe/power branch (each card's own ceiling and limit stay; main adds the #4677 stop bound, the picture-reader changes and the MMQ row-id margin)

This commit is contained in:
Jie Ren committed 2026-11-12 00:49:11 -08:00
commit 6c1c9d0027
11 files changed
+412 -25

No files matched your search

+3 -3
View File
@@ -35303,13 +35303,13 @@
{
"name": "STRATA_SERVE_STOP_BOUND",
"backends": [
"hip"
"cuda-hip"
],
"reads": [
{
"file": "src/program/generate.cpp",
"line": 18141,
"backend": "hip",
"line": 18199,
"backend": "cuda-hip",
"fn": "getenv"
}
],
+8
View File
@@ -1,6 +1,7 @@
#pragma once
#include <algorithm>
#include <cstdint>
#include <cstring>
namespace strata::core {
// A committed input row must correspond to an output the caller can expose.
@@ -12,4 +13,11 @@ int serve_stop_bound(int accepted, int64_t remaining, const Token* outputs, IsEo
if (is_eos(outputs[i])) return i + 1;
return count;
}
// #4677: the bound is on by default on every backend; STRATA_SERVE_STOP_BOUND=0 (the variable's value, passed in)
// turns it off. It only limits which accepted rows enter the cached conversation: the tokens a request emits are the
// same either way.
inline bool serve_stop_bound_on(const char* env_value) {
return env_value == nullptr || std::strcmp(env_value, "0") != 0;
}
}
+31 -1
View File
@@ -36,6 +36,7 @@ import codecs
import json
import math
import os
import platform
import queue
import re
import select
@@ -3353,7 +3354,7 @@ class Vision:
load, the card is not in its build, the card is busy), the CPU reader is started instead, for good, with one log line
and no question."""
try:
self._start_reader()
self._start_gpu_reader()
except (RuntimeError, OSError) as e:
fallback = getattr(self, "fallback", None)
if fallback is None:
@@ -3365,6 +3366,33 @@ class Vision:
self.spawn, self.fallback, self.on_cpu = fallback, None, True
self._start_reader()
def _start_gpu_reader(self):
"""`_start_reader`, tried again when the start failed in the GPU context itself on a Linux Arm machine with shared memory (DGX Spark; see
vision_reader.retry_gpu_start): a new spawn may start while less than CONTEXT_RETRY_BUDGET_S have passed since the first one started, at most CONTEXT_RETRIES
times, CONTEXT_RETRY_WAIT_S apart. Every other start, and the last failure, are `_start_reader`'s as before (the CPU reader follows in `_start`).
STRATA_VIT_PROF=1 (the reader's diagnostic switch) prints the retry count and the time of a start that needed one."""
args, log, _env = self.spawn
retries = 0
first = time.monotonic() # the first spawn's start: a new spawn may start only within vision_reader.CONTEXT_RETRY_BUDGET_S of it
prof = bool(os.environ.get("STRATA_VIT_PROF"))
while True:
since = vision_log_size(log)
try:
res = self._start_reader()
if prof and retries:
print(f"vit-prof: GPU reader started after {retries} retries, {time.monotonic() - first:.2f} s", flush=True)
return res
except (RuntimeError, OSError) as e:
text = str(e) + chr(10) + vision_log_tail(log, since=since)
if not vision_reader.retry_gpu_start(linux=sys.platform.startswith("linux"), arm=platform.machine().lower() in ("aarch64", "arm64"),
hip="hip" in Path(str(args[0])).name.lower(), text=text, retries_done=retries,
next_start_s=time.monotonic() - first + vision_reader.CONTEXT_RETRY_WAIT_S):
if prof and retries:
print(f"vit-prof: GPU reader did not start after {retries} retries, {time.monotonic() - first:.2f} s", flush=True)
raise
retries += 1
time.sleep(vision_reader.CONTEXT_RETRY_WAIT_S)
def no_room_note(self, room) -> str:
"""The sentence for the person when the card had no room for the reader and the processor reads instead: which card (as nvidia-smi numbers it), what
the reader needed, what is free now that it is gone."""
@@ -9865,6 +9893,8 @@ def vision_on_demand_by_default(cfg: dict) -> bool:
name = re.split(r"[\\/:]", str(vis.get("exe") or ""))[-1].lower() # a path or a "component:..." reference
if backend == "hip": # AMD: the HIP reader, with the CPU reader setup wrote beside it to read when the card has no room
return VISION_ON_DEMAND_AMD_BY_DEFAULT and name in (vision_reader.GPU_READER, vision_reader.GPU_READER + ".exe") and bool(vis.get("cpu_exe"))
if vision_reader.shared_memory_nvidia_host(): # a DGX Spark: the reader stays loaded (owner 2026-11-11; vision_reader.shared_memory_nvidia_host)
return False
return name in (vision_reader.CPU_READER, vision_reader.CPU_READER + ".exe")
+255
View File
@@ -0,0 +1,255 @@
"""A GPU picture reader whose start failed in its CUDA context ("CUDA error: out of memory ... in function ggml_cuda_init") on a Linux Arm machine with shared
CPU / GPU memory (DGX Spark) is started again before the CPU reader takes over: a new spawn may start only while less than 18 s have passed since the first one
started, and at most 12 times. Every other failure goes the way it went.
python -m serve.test_vision_ctx_retry
"""
import tempfile
import threading
import time
import unittest
from pathlib import Path
from unittest import mock
import serve.server as server
from strata_control import vision_reader as VR
CTX = ("CUDA error: out of memory\n current device: 0, in function ggml_cuda_init at ggml/src/ggml-cuda/ggml-cuda.cu:367\n"
"ggml/src/ggml-cuda/ggml-cuda.cu:108: CUDA error\n")
ALLOC = "ggml_backend_cuda_buffer_type_alloc_buffer: allocating 865.48 MiB on device 0: cudaMalloc failed: out of memory\n"
DIED = "the vision encoder did not start (killed by signal 6)"
def rule(text=CTX, retries_done=0, next_start_s=0.0, **kw):
args = dict(linux=True, arm=True, hip=False)
args.update(kw)
return VR.retry_gpu_start(text=text, retries_done=retries_done, next_start_s=next_start_s, **args)
class Rule(unittest.TestCase):
def test_the_constants(self):
self.assertEqual((VR.CONTEXT_RETRIES, VR.CONTEXT_RETRY_WAIT_S, VR.CONTEXT_RETRY_BUDGET_S), (12, 1.0, 18.0))
def test_the_count_cap_ends_it(self):
for done in range(12):
self.assertTrue(rule(retries_done=done))
self.assertFalse(rule(retries_done=12))
self.assertFalse(rule(retries_done=20))
def test_the_time_bound_is_the_start_of_the_next_spawn(self):
self.assertTrue(rule(next_start_s=0.0))
self.assertTrue(rule(next_start_s=17.9))
self.assertFalse(rule(next_start_s=18.0))
self.assertFalse(rule(next_start_s=40.0))
def test_the_own_tower_wording_counts_too(self):
self.assertTrue(rule("strata-vision: Strata's picture reader did not start (cannot use GPU 0: out of memory)"))
def test_other_platforms_never_retry(self):
self.assertFalse(rule(linux=False)) # Windows, Mac
self.assertFalse(rule(arm=False)) # a PC with a card of its own
self.assertFalse(rule(hip=True)) # the AMD reader
def test_other_errors_never_retry(self):
for text in (ALLOC, # a card another program filled: no retry helps (reader_room reports it)
CTX + ALLOC,
"failed to allocate CUDA0 buffer of size 1048576 out of memory",
"CUDA error: device kernel image is invalid\n in function ggml_cuda_init",
"CUDA error: CUDA-capable device(s) is/are busy or unavailable\n in function ggml_cuda_init",
"ggml_cuda_init: failed to initialize CUDA: no CUDA-capable device is detected",
"the vision encoder did not start: it said nothing for 300 s",
"out of memory"): # no sign of the context
with self.subTest(text=text[:50]):
self.assertFalse(rule(text))
def make_vision(args=("/engine/strata-vision", "--gpu"), log_text=""):
f = tempfile.NamedTemporaryFile("w+", suffix=".log", delete=False)
f.write(log_text)
f.flush()
v = server.Vision.__new__(server.Vision)
v.spawn = (list(args), f, None)
return v, f
class Clock:
"""A fake monotonic clock: `sleep` and every spawn (`attempt_s` long) move it. It belongs to the thread that made it (the test's): `server.time` is the
process-wide `time` module, so while it is patched any other thread of the pytest process that sleeps or reads the clock (on Windows a watcher or job thread
that an earlier test left running) would call these. Those threads get the real `time.sleep` / `time.monotonic` and are neither counted nor allowed to move the clock.
Make it before patching, so the real functions it keeps are the unpatched ones."""
def __init__(self):
self.now = 0.0
self.sleeps = []
self.owner = threading.get_ident()
self._real_sleep, self._real_monotonic = time.sleep, time.monotonic
def monotonic(self):
return self.now if threading.get_ident() == self.owner else self._real_monotonic()
def sleep(self, s):
if threading.get_ident() != self.owner:
return self._real_sleep(s)
self.sleeps.append(s)
self.now += s
class Spawn(unittest.TestCase):
def run_start(self, outcomes, args=("/engine/strata-vision", "--gpu"), system="linux", machine="aarch64", logged=CTX, attempt_s=1.4, hook=None):
"""_start_gpu_reader with `_start_reader` giving `outcomes` in turn (the last one repeats; an exception is raised, anything else returned) and taking `attempt_s`
on a fake clock; returns (clock, calls, result or error)."""
v, f = make_vision(args)
self.addCleanup(lambda: (f.close(), Path(f.name).unlink()))
clock, calls = Clock(), []
def start_reader():
calls.append(clock.now) # when this spawn started
if hook is not None:
hook()
clock.now += attempt_s
o = outcomes[min(len(calls) - 1, len(outcomes) - 1)]
if isinstance(o, Exception):
f.write(logged)
f.flush()
raise o
return o
v._start_reader = start_reader
with mock.patch.object(server.sys, "platform", system), mock.patch.object(server.platform, "machine", return_value=machine), \
mock.patch.object(server.time, "sleep", clock.sleep), mock.patch.object(server.time, "monotonic", clock.monotonic):
try:
res = v._start_gpu_reader()
except RuntimeError as e:
res = e
return clock, calls, res
def test_a_start_that_works_the_first_time_is_not_delayed(self):
clock, calls, res = self.run_start([None])
self.assertEqual((len(calls), clock.sleeps), (1, []))
def test_a_success_ends_it_at_once(self):
clock, calls, res = self.run_start([RuntimeError(DIED)] * 3 + [None]) # the measured case: 3 failures, the 4th spawn works
self.assertEqual((len(calls), clock.sleeps, res), (4, [1.0, 1.0, 1.0], None))
for got, want in zip(calls, [0.0, 2.4, 4.8, 7.2]):
self.assertAlmostEqual(got, want)
def test_the_five_measured_failures_are_covered(self):
clock, calls, res = self.run_start([RuntimeError(DIED)] * 5 + [None])
self.assertEqual((len(calls), res), (6, None))
self.assertLess(calls[-1], 18.0)
def test_a_context_that_never_works_ends_by_the_time_bound_and_raises_as_before(self):
err = RuntimeError(DIED)
clock, calls, res = self.run_start([err])
self.assertIs(res, err)
self.assertEqual(len(calls), 8) # spawns start at 0, 2.4, ... 16.8 s; the next would start at 19.2 s
self.assertLess(calls[-1], 18.0)
self.assertLess(clock.now, 20.0) # the worst wait before the CPU reader takes over
def test_fast_attempts_end_by_the_count_cap(self):
err = RuntimeError(DIED)
clock, calls, res = self.run_start([err], attempt_s=0.1)
self.assertIs(res, err)
self.assertEqual((len(calls), len(clock.sleeps)), (13, 12)) # 1 spawn + 12 retries, 13.3 s: the cap, not the clock
self.assertLess(clock.now, 18.0)
def test_another_thread_that_sleeps_meanwhile_is_not_counted_and_does_not_move_the_clock(self):
"""`server.time` is the process-wide module: a thread of another part of the process that sleeps while the test has it patched (a winjob / watcher thread left
by an earlier test on Windows counted 232,838 sleeps) must get the real sleep. Here a thread sleeps in a loop and every spawn waits until it has slept once more."""
stop, slept = threading.Event(), threading.Event()
def other():
while not stop.is_set():
time.sleep(0.0002) # the fake one when it is patched, and it must not count
slept.set()
def hook():
slept.clear()
slept.wait(2)
t = threading.Thread(target=other, daemon=True)
t.start()
try:
clock, calls, res = self.run_start([RuntimeError(DIED)], attempt_s=0.1, hook=hook)
finally:
stop.set()
t.join(2)
self.assertEqual((len(calls), len(clock.sleeps)), (13, 12))
self.assertAlmostEqual(clock.now, 13 * 0.1 + 12 * 1.0) # only this thread's pauses and spawns moved it
def test_a_spawn_that_would_start_at_17_9_s_is_allowed_and_one_at_18_0_s_is_not(self):
clock, calls, res = self.run_start([RuntimeError(DIED), None], attempt_s=16.9) # fails at 16.9, next starts at 17.9
self.assertEqual((len(calls), res), (2, None))
self.assertAlmostEqual(calls[1], 17.9)
clock, calls, res = self.run_start([RuntimeError(DIED), None], attempt_s=17.0) # fails at 17.0, next would start at 18.0
self.assertEqual(len(calls), 1)
self.assertIsInstance(res, RuntimeError)
def test_the_diagnostic_line_only_with_STRATA_VIT_PROF_and_only_after_a_retry(self):
for env, outcomes, expect in (({"STRATA_VIT_PROF": "1"}, [RuntimeError(DIED)] * 3 + [None], ["vit-prof: GPU reader started after 3 retries, 8.60 s"]),
({"STRATA_VIT_PROF": "1"}, [None], []),
({}, [RuntimeError(DIED)] * 3 + [None], []),
({"STRATA_VIT_PROF": "1"}, [RuntimeError(DIED)], ["vit-prof: GPU reader did not start after 7 retries, 18.20 s"])):
with self.subTest(env=env, n=len(outcomes)), mock.patch.dict(server.os.environ, env), mock.patch("builtins.print") as pr:
server.os.environ.pop("STRATA_VIT_PROF", None) if not env else None
self.run_start(outcomes)
# (print is patched for the whole process: only this module's diagnostic lines count, whatever another thread prints meanwhile)
self.assertEqual([c.args[0] for c in pr.call_args_list if c.args and str(c.args[0]).startswith("vit-prof")], expect)
def test_no_room_is_not_retried(self):
err = server.VisionNoRoom("the vision encoder did not start: the graphics card has no room for it", None)
clock, calls, res = self.run_start([err], logged=ALLOC)
self.assertEqual((len(calls), clock.sleeps), (1, []))
self.assertIs(res, err)
def test_a_failure_that_is_not_the_context_is_not_retried(self):
err = RuntimeError("the vision encoder did not start: ERR cannot open the model")
clock, calls, res = self.run_start([err], logged="ERR cannot open the model\n")
self.assertEqual((len(calls), clock.sleeps), (1, []))
def test_other_systems_are_not_retried(self):
err = RuntimeError("the vision encoder did not start")
for kw in ({"system": "win32"}, {"system": "darwin"}, {"machine": "x86_64"}, {"machine": "AMD64"},
{"args": ("/engine/strata-vision-hip", "--gpu")}):
with self.subTest(kw=kw):
clock, calls, res = self.run_start([err], **kw)
self.assertEqual((len(calls), clock.sleeps), (1, []))
def test_an_old_failure_in_a_shared_log_does_not_count(self):
v, f = make_vision(log_text=CTX) # an earlier start's lines are in the file already
self.addCleanup(lambda: (f.close(), Path(f.name).unlink()))
v._start_reader = mock.Mock(side_effect=RuntimeError("the vision encoder did not start: ERR cannot open the model"))
clock = Clock()
with mock.patch.object(server.sys, "platform", "linux"), mock.patch.object(server.platform, "machine", return_value="aarch64"), \
mock.patch.object(server.time, "sleep", clock.sleep), mock.patch.object(server.time, "monotonic", clock.monotonic):
with self.assertRaises(RuntimeError):
v._start_gpu_reader()
self.assertEqual(v._start_reader.call_count, 1)
self.assertEqual(clock.sleeps, []) # no retry: this thread never slept
def test_start_falls_back_to_the_cpu_reader_after_the_last_retry(self):
v, f = make_vision()
self.addCleanup(lambda: (f.close(), Path(f.name).unlink()))
v.fallback = (["/engine/strata-vision"], f, None)
v.on_cpu, v.elastic = False, False
starts = []
clock = Clock()
def start_reader():
starts.append(v.on_cpu)
if not v.on_cpu:
f.write(CTX)
f.flush()
raise RuntimeError(DIED)
v._start_reader = start_reader
v.not_started_note = lambda: "note"
with mock.patch.object(server.sys, "platform", "linux"), mock.patch.object(server.platform, "machine", return_value="aarch64"), \
mock.patch.object(server.time, "sleep", clock.sleep), mock.patch.object(server.time, "monotonic", clock.monotonic), mock.patch("builtins.print"):
v._start()
self.assertEqual(starts, [False] * 13 + [True]) # fast attempts (the clock moves only by the pauses): the count cap
self.assertTrue(v.on_cpu)
if __name__ == "__main__":
unittest.main()
+45
View File
@@ -245,6 +245,12 @@ class OnDemandByDefault(unittest.TestCase):
BASE = {"args": ["--max-context", "8192", "--vision"], "gpu": 0,
"vision": {"exe": "/e/strata-vision", "mmproj": "m", "model": "t", "gpu": True, "max_tokens": 1024}}
def setUp(self):
# these tests describe a PC (x86); the Spark class (Linux on Arm) has its own tests below, so a test run on a Spark does not change them
p = mock.patch("platform.machine", return_value="x86_64")
p.start()
self.addCleanup(p.stop)
def cfg(self, **over):
import copy
c = copy.deepcopy(self.BASE)
@@ -255,6 +261,45 @@ class OnDemandByDefault(unittest.TestCase):
c[k] = v
return c
def test_the_spark_class_keeps_the_reader_loaded_by_default(self):
"""Linux on Arm with an NVIDIA GPU reader on one GPU (a DGX Spark): resident, as the AMD reader and the Mac's are (owner 2026-11-11)."""
import sys
from serve.server import apply_vision_defaults, vision_on_demand_by_default as f
for machine in ("aarch64", "arm64", "AARCH64"):
with self.subTest(machine=machine), mock.patch("platform.machine", return_value=machine), mock.patch.object(sys, "platform", "linux"):
self.assertFalse(f(self.cfg()))
c = apply_vision_defaults(self.cfg(args=["--vision", "--vram-reserve-mib", "700"]))
self.assertNotIn("elastic", c["vision"]) # no key written: the reader starts with the server
self.assertEqual(c["args"][c["args"].index("--vram-reserve-mib") + 1], "700") # the resident path's reserve, not 2,048
self.assertFalse(f(self.cfg(vision={"exe": "component:engine/strata-vision"})))
self.assertFalse(f(self.cfg(backend="cuda")))
def test_the_spark_class_still_takes_an_explicit_elastic_key_either_way(self):
import sys
from serve.server import apply_vision_defaults
with mock.patch("platform.machine", return_value="aarch64"), mock.patch.object(sys, "platform", "linux"):
c = apply_vision_defaults(self.cfg(vision={"elastic": True}))
self.assertIs(c["vision"]["elastic"], True) # the old behaviour is still reachable
self.assertEqual(c["args"], self.BASE["args"])
c = apply_vision_defaults(self.cfg(vision={"elastic": False}))
self.assertIs(c["vision"]["elastic"], False)
def test_other_hosts_keep_the_on_demand_default(self):
import sys
from serve.server import vision_on_demand_by_default as f
for system, machine in (("linux", "x86_64"), ("linux", "AMD64"), ("win32", "AMD64"), ("win32", "ARM64")): # a PC, and Windows on Arm (not this rule)
with self.subTest(system=system, machine=machine), mock.patch("platform.machine", return_value=machine), mock.patch.object(sys, "platform", system):
self.assertTrue(f(self.cfg()))
with mock.patch("platform.machine", return_value="arm64"), mock.patch.object(sys, "platform", "darwin"):
self.assertFalse(f(self.cfg())) # a Mac was never on demand
def test_the_spark_class_does_not_change_the_amd_rule(self):
import sys
import serve.server as S
with mock.patch("platform.machine", return_value="aarch64"), mock.patch.object(sys, "platform", "linux"), \
mock.patch.object(S, "VISION_ON_DEMAND_AMD_BY_DEFAULT", True):
self.assertTrue(S.vision_on_demand_by_default(self.cfg(vision={"exe": "/e/strata-vision-hip", "cpu_exe": "/e/strata-vision"}, backend="hip")))
def test_the_plain_nvidia_config_is_on_demand(self):
from serve.server import apply_vision_defaults, vision_on_demand_by_default
c = apply_vision_defaults(self.cfg())
+7 -2
View File
@@ -2,6 +2,7 @@
#include "strata/prefill/gemm.hpp"
#include "strata/kernels/dequant_bf16.hpp"
#if defined(STRATA_PREFILL_MMQ) && defined(__HIPCC__)
#include "strata/prefill/mmq_ids_margin.hpp"
#include "strata/prefill/moe_mmq.hpp"
#endif
@@ -1294,8 +1295,12 @@ bool Gemm::native_mmq(const uint16_t* X, int type, const void* W, float* Y, int6
if (ldy <= 0) ldy = N;
const auto up = [](size_t v) { return (v + 255) & ~(size_t) 255; };
// The row table is read past its end by llama.cpp's MMQ (mul_mat_q: a whole J-column tile from the start of each tile, J up to 128; the stream-k fixup:
// up to roundup(max_rows, J) from the expert's first row): kRows + the margin of mmq_ids_margin.hpp (max_rows <= kRows), the identity written over all of it.
// Exact, with only the 256 bytes of the bounds after it, a tile of 112 columns on a full chunk read 384 bytes past the table, 128 past the allocation.
const size_t ids_rows = (size_t) mmq::mmq_ids_table_rows((uint64_t) kRows, (uint64_t) kRows);
const size_t ident_off = up(mmq::q8_bytes(kRows, kMaxK));
const size_t bounds_off = ident_off + up((size_t) kRows * 4);
const size_t bounds_off = ident_off + up(ids_rows * 4);
if (!mmq_buf_) {
if (cudaMalloc(&mmq_buf_, bounds_off + 256) != cudaSuccess) {
cudaGetLastError();
@@ -1303,7 +1308,7 @@ bool Gemm::native_mmq(const uint16_t* X, int type, const void* W, float* Y, int6
return false;
}
mmq_ctx_ = new mmq::Context();
mmq::iota((int32_t*) ((uint8_t*) mmq_buf_ + ident_off), kRows, stream_);
mmq::iota((int32_t*) ((uint8_t*) mmq_buf_ + ident_off), (int64_t) ids_rows, stream_);
std::fprintf(stderr, "prefill gemm: dense MMQ on (STRATA_DENSE_MMQ=1)\n");
}
void* xq = mmq_buf_;
+6 -3
View File
@@ -2314,7 +2314,7 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t
static const bool f16_only = [] { const char* v = std::getenv("STRATA_MTP_BATCH_F16"); return v && v[0] == '1'; }();
const bool q8 = !f16_only && mmq::built() && mmq::fits(kQ8_0, Nn) && mmq::fits(kQ8_0, KV); // #420
const uint64_t per_row = 4 * (2 * Nn + 4 * HCN + LR + HC + Nn + 2 * KV + 1) + 2 * (Nn + 2 * HCN + LR + Nn) + 64 +
(q8 ? (uint64_t) mmq::q8_bytes(g.hc, Nn) + 4 * g.hc : 0);
(q8 ? (uint64_t) mmq::q8_bytes(g.hc, Nn) + 8 * g.hc : 0); // (8 * hc: the row table twice, see its margin below)
int64_t B = std::min<int64_t>(n - r0, (int64_t) (m.region_bytes / per_row) & ~(int64_t) 63);
if (st.kv_mode == 2) // a ring: one batch's cells must not share a slot (a batch can straddle one page more)
B = std::min<int64_t>(B, ((st.n_slots - 1) * strata::kernels::qsa_real_shapes().page_size) & ~(int64_t) 63);
@@ -2339,7 +2339,10 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t
float* Vc = (float*) carve((size_t) B * KV * 4);
int32_t* tok = (int32_t*) carve((size_t) B * 4);
void* xq = q8 ? carve(mmq::q8_bytes(B * g.hc, Nn)) : nullptr;
int32_t* ident = q8 ? (int32_t*) carve((size_t) B * g.hc * 4) : nullptr;
// The row table is read past its end by llama.cpp's MMQ (a whole J-column tile from the start of each tile; the stream-k fixup up to roundup(max_rows, J)
// from the expert's first row; J up to 128): rows + the margin of mmq_ids_margin.hpp, max_rows <= B * hc (one expert, p.n = 1), the identity over all of it.
const uint64_t ids_rows = q8 ? mmq::mmq_ids_table_rows((uint64_t) (B * g.hc), (uint64_t) (B * g.hc)) : 0;
int32_t* ident = q8 ? (int32_t*) carve((size_t) ids_rows * 4) : nullptr;
int32_t* bnd = q8 ? (int32_t*) carve(16) : nullptr;
if ((uint64_t) (q - m.region) > m.region_bytes) return decline("the batch buffers do not fit the scratch region");
static const bool timing = std::getenv("STRATA_DRAFT_TIMING") != nullptr; // debug: where this pass's time goes
@@ -2352,7 +2355,7 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t
std::vector<int32_t> tk((size_t) B);
if (q8) {
if (!m.mmq_ctx) m.mmq_ctx = std::make_unique<mmq::Context>();
mmq::iota(ident, B * g.hc, m.cs);
mmq::iota(ident, (int64_t) ids_rows, m.cs);
}
// y[rows, n_out] = x[rows, k] . w^T for a Q8_0 matrix: MMQ from the FP32 rows (bounds slot 0: rows, 1: rows*hc)
auto proj = [&](const float* x, const uint16_t* x16, const void* w, float* y, int64_t rows, int64_t n_out,
+4 -14
View File
@@ -33,9 +33,7 @@
#include "strata/core/expert_nibble.hpp"
#include "strata/core/conversation_snapshot.hpp"
#include "strata/core/lookup_default.hpp"
#if defined(STRATA_USE_HIP)
#include "strata/core/serve_stop_bound.hpp"
#endif
#include "strata/core/conversation_file.hpp"
#include "strata/core/session_save_reclaim.hpp"
#include "strata/core/conversation_memory.hpp"
@@ -18211,14 +18209,10 @@ int main(int argc, char** argv) {
if (fol_next < fol_sets.size() && !fol_sets[fol_next].empty()) fol = &fol_sets[fol_next];
++fol_next;
}
#if defined(STRATA_USE_HIP)
// on by default (HIP, where it was measured: 4 x R9700, Qwen3.8-Flash-Next IQ3_S, 0 of 16 continuations fell back to the older
// checkpoint against 4 of 16 without it, #4677); STRATA_SERVE_STOP_BOUND=0 turns it off
static const bool stop_bound = [] {
const char* v = std::getenv("STRATA_SERVE_STOP_BOUND");
return v == nullptr || std::strcmp(v, "0") != 0;
}();
#endif
// on by default on every backend (measured on HIP: 4 x R9700, Qwen3.8-Flash-Next IQ3_S, 0 of 16 continuations fell back to
// the older checkpoint against 4 of 16 without it, #4677; it changes no emitted token, only which accepted rows the
// session keeps); STRATA_SERVE_STOP_BOUND=0 turns it off
static const bool stop_bound = strata::core::serve_stop_bound_on(std::getenv("STRATA_SERVE_STOP_BOUND"));
int64_t chain_windows = 0, chain_drafts = 0, chain_ok = 0; // --lookup-chain's own counts
int64_t t2_rej[8] = {}, t2_hit[8] = {}; // STRATA_MTP_TOP2: rejections inside the MTP drafts by depth, runner-up hits
int64_t dp_tested[8] = {}, dp_ok[8] = {}; // STRATA_SPEC_DEPTH=1: MTP drafts tested / accepted by depth
@@ -18774,12 +18768,10 @@ int main(int argc, char** argv) {
chain_kind = 0;
int a = 0;
while (a < A.T - 1 && A.tok[a + 1] == outp[(size_t) a]) ++a;
#if defined(STRATA_USE_HIP)
if (stop_bound)
a = strata::core::serve_stop_bound(a + 1, max_new - produced_n, outp.data(), [&](int32_t y) {
return std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end();
}) - 1;
#endif
if (!V1(A).pl_commit_async(a + 1, err)) return die(err);
for (int i = 0; i <= a; ++i) consumed.push_back(A.tok[i]);
draft_offered += A.T - 1;
@@ -19316,14 +19308,12 @@ int main(int argc, char** argv) {
if (!ver.window_logprobs(fol_tg.data(), a + 1, p, 248046, fol_lp, fe))
std::fprintf(stderr, "strata serve: STRATA_FOLLOW_LOGPOS: %s\n", fe.c_str());
}
#if defined(STRATA_USE_HIP)
// A merged window contains prompt rows: every one must still be committed.
// Otherwise do not cache accepted rows whose outputs this request cannot emit.
if (stop_bound && !merged)
a = strata::core::serve_stop_bound(a + 1, max_new - produced_n, outv.data(), [&](int32_t y) {
return std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end();
}) - 1;
#endif
if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; }
if (chain_n > 0) { ++chain_windows; chain_drafts += chain_n; chain_ok += std::max(0, a - (T_mtp - 1)); }
if (!from_sfx && !first_window)
+11 -2
View File
@@ -24,6 +24,7 @@
#include "strata/kernels/native_moe.hpp"
#include "strata/kernels/native_router.hpp"
#include "strata/prefill/gemm.hpp"
#include "strata/prefill/mmq_ids_margin.hpp"
#include "strata/prefill/moe_mmq.hpp"
#include "strata/qwen35/context_fit.hpp"
#include "strata/qwen35/engine.hpp"
@@ -1386,10 +1387,18 @@ struct Engine {
rcur = dalloc_t<int32_t>((size_t) g.n_expert);
rbounds = dalloc_t<int32_t>((size_t) g.n_expert + 1);
rmax = dalloc_t<int32_t>(1);
ident = dalloc_t<int32_t>((size_t) ne);
// The row table (ids) is read past its end by llama.cpp's MMQ: mul_mat_q copies ids_dst[col_low + jt*J + j] for a whole J-column tile before it
// compares the tile with the expert's rows, and its stream-k fixup does the same for every tile up to roundup(max_rows, J) from an expert's first row,
// which can be the table's last (mmq.cuh; J goes to 128). mmq_ids_table_rows adds roundup(max_rows, 128) + 128 entries, max_rows <= T (an expert takes at
// most one row per token): the margin the Flash-Next prompt path already uses (prefill.cpp mmq_ids_rows, PR #5108). An exact table of ne ints (64 KB at the
// default chunk) was read past its end: compute-sanitizer on the same size in the Qwen3.6 one-layer test (z440-20261111-2224-d478), 311 invalid reads of size 4
// in mul_mat_q<Q8_0, 96>, 29 to 57+ bytes after a 65,536-byte allocation. The identity is written over the whole table, as there.
const int64_t ids_rows = (int64_t) MMQ::mmq_ids_table_rows((uint64_t) ne, (uint64_t) T);
if (ids_rows <= 0) { std::fprintf(stderr, "strata-q36: the MMQ row table does not fit\n"); std::exit(1); }
ident = dalloc_t<int32_t>((size_t) ids_rows);
rinv = dalloc_t<int32_t>((size_t) ne);
CK(cudaDeviceSynchronize()); // ident's cudaMemset (legacy stream) before the iota on the non-blocking stream
MMQ::iota(ident, ne, st);
MMQ::iota(ident, ids_rows, st);
CK(cudaMalloc(&mq_x, MMQ::q8_bytes(ne, g.n_embd)));
CK(cudaMalloc(&mq_hq, MMQ::q8_bytes(ne, g.n_ff)));
mq_gu = dalloc((size_t) ne * 2 * FF);
+37
View File
@@ -153,6 +153,43 @@ def vision_section(reader: Reader, base: dict) -> dict:
return out
def shared_memory_nvidia_host() -> bool:
"""Linux on Arm: the DGX Spark class (GB10: the GPU shares the system RAM, 121 GB), where the NVIDIA picture reader stays loaded instead of starting with the first
picture (owner 2026-11-11). Measured on a Spark (IQ3_S, two starts per arm): the first picture after a start takes 0.84-0.89 s resident against 3.0-7.1 s on demand
(the reader's start, and its context retry when the kernel has no free 2 MiB blocks), and again 2.2 s after every idle stop; the resident reader costs about 5 s of start
time and about 1 GiB of the shared RAM, and no expert slot (every expert is resident there). The same switch as the AMD reader and the Mac's: the reader starts with the
server, before the engine; an explicit "elastic" key in the vision section wins either way."""
import platform
import sys
return sys.platform.startswith("linux") and platform.machine().lower() in ("aarch64", "arm64")
#: A GPU reader's start that failed while it made its CUDA context on a Linux Arm machine with shared CPU / GPU memory (DGX Spark, GB10) is tried again. Such a context needs
#: physically contiguous memory (2 MiB blocks); when the kernel has almost none free, ggml's cudaSetDevice answers "CUDA error: out of memory ... in function
#: ggml_cuda_init" and the reader aborts, although 20+ GiB are free. The same start 1 to 5 s later works (the kernel compacts memory after the failed try; measured
#: on a Spark: three to five failed spawns in a row, then success: first failure to first success 9.6 to 14.6 s; one failed spawn takes 1.4 s, the pause is 1 s). Without the
#: retry the picture reader falls back to the CPU for good (90 s for a large picture, 9.7 s against 2.0 s at 1,024 tokens on the card).
#: Bounded by time and by count: a new spawn may start only while less than CONTEXT_RETRY_BUDGET_S seconds have passed since the first spawn started (about 8 spawns at
#: 2.4 s a cycle; the five measured failures end at 12 s), and at most CONTEXT_RETRIES retries (fast attempts). The worst wait before the CPU reader takes over is the
#: budget plus the last failed spawn, about 19.5 to 20 s.
CONTEXT_RETRIES = 12
CONTEXT_RETRY_WAIT_S = 1.0
CONTEXT_RETRY_BUDGET_S = 18.0
def retry_gpu_start(*, linux: bool, arm: bool, hip: bool, text: str, retries_done: int, next_start_s: float = 0.0) -> bool:
"""Should a failed GPU reader start be tried again? Only for the context failure ("out of memory" in ggml_cuda_init / cudaSetDevice), only for the NVIDIA reader on
Linux on Arm, at most CONTEXT_RETRIES times, and only if the next spawn would start less than CONTEXT_RETRY_BUDGET_S seconds after the first one (`next_start_s`: that
time, the pause included). A card another program filled says "cudaMalloc failed: out of memory" (a retry cannot help: reader_room reports it), every
other error (no device, no kernel image, busy) is not this case. `text`: what the failed start said (its message and the tail of the reader's log)."""
if not linux or not arm or hip or retries_done >= CONTEXT_RETRIES or next_start_s >= CONTEXT_RETRY_BUDGET_S:
return False
t = text.lower()
if "out of memory" not in t or "cudamalloc failed" in t or "failed to allocate" in t:
return False
return "ggml_cuda_init" in t or "cudasetdevice" in t or "cannot use gpu" in t
def cpu_fallback(vision_cfg: dict, same_program: bool = False) -> dict | None:
"""The same section for the CPU reader, when the GPU reader has one to fall back on; None otherwise. AMD and Intel name it (`cpu_exe`);
the NVIDIA reader (`strata-vision`) is the CPU reader too, without --gpu - `same_program` takes that one (the on-demand reader's
+5
View File
@@ -27,5 +27,10 @@ int main() {
++cases;
}
assert(strata::core::serve_stop_bound(4, 0, static_cast<const int*>(nullptr), [](int) { return false; }) == 0);
// on unless the variable is exactly "0" (every backend, since the bound left HIP-only)
assert(strata::core::serve_stop_bound_on(nullptr));
assert(strata::core::serve_stop_bound_on("1"));
assert(strata::core::serve_stop_bound_on(""));
assert(!strata::core::serve_stop_bound_on("0"));
std::cout << "SUMMARY stop_bound cases=" << cases << " passed\n";
}